commit
stringlengths
40
40
old_file
stringlengths
2
205
new_file
stringlengths
2
205
old_contents
stringlengths
0
32.9k
new_contents
stringlengths
1
38.9k
subject
stringlengths
3
9.4k
message
stringlengths
6
9.84k
lang
stringlengths
3
13
license
stringclasses
13 values
repos
stringlengths
6
115k
16bd04d03aa6eb0378838a6ee37385e4056dd2bd
src/curl/CurlSession.hpp
src/curl/CurlSession.hpp
/* * This File is part of Davix, The IO library for HTTP based protocols * Copyright (C) CERN 2019 * Author: Georgios Bitzes <[email protected]> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * */ #ifndef DAVIX_CURL_SESSION_HPP #define DAVIX_CURL_SESSION_HPP #include <memory> typedef void CURL; typedef void CURLM; namespace Davix { class CurlSessionFactory; class Uri; class RequestParams; class Status; //------------------------------------------------------------------------------ // CurlHandle, internal use only //------------------------------------------------------------------------------ struct CurlHandle { std::string key; CURLM *mhandle; CURL *handle; void renewHandle(); CurlHandle(const std::string &k, CURLM *mh, CURL *h) : key(k), mhandle(mh), handle(h) {} CurlHandle() : mhandle(NULL), handle(NULL) {} ~CurlHandle(); }; typedef std::shared_ptr<CurlHandle> CurlHandlePtr; class CurlSession { public: //---------------------------------------------------------------------------- // Constructor //---------------------------------------------------------------------------- CurlSession(CurlSessionFactory &f, CurlHandlePtr handle, const Uri & uri, const RequestParams & p, Status &st); //---------------------------------------------------------------------------- // Destructor //---------------------------------------------------------------------------- virtual ~CurlSession(); private: //---------------------------------------------------------------------------- // Configure session //---------------------------------------------------------------------------- void configureSession(const RequestParams &params, Status &st); CurlSessionFactory &_factory; CurlHandlePtr _handle; }; } #endif
/* * This File is part of Davix, The IO library for HTTP based protocols * Copyright (C) CERN 2019 * Author: Georgios Bitzes <[email protected]> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * */ #ifndef DAVIX_CURL_SESSION_HPP #define DAVIX_CURL_SESSION_HPP #include <memory> #include <string> typedef void CURL; typedef void CURLM; namespace Davix { class CurlSessionFactory; class Uri; class RequestParams; class Status; //------------------------------------------------------------------------------ // CurlHandle, internal use only //------------------------------------------------------------------------------ struct CurlHandle { std::string key; CURLM *mhandle; CURL *handle; void renewHandle(); CurlHandle(const std::string &k, CURLM *mh, CURL *h) : key(k), mhandle(mh), handle(h) {} CurlHandle() : mhandle(NULL), handle(NULL) {} ~CurlHandle(); }; typedef std::shared_ptr<CurlHandle> CurlHandlePtr; class CurlSession { public: //---------------------------------------------------------------------------- // Constructor //---------------------------------------------------------------------------- CurlSession(CurlSessionFactory &f, CurlHandlePtr handle, const Uri & uri, const RequestParams & p, Status &st); //---------------------------------------------------------------------------- // Destructor //---------------------------------------------------------------------------- virtual ~CurlSession(); private: //---------------------------------------------------------------------------- // Configure session //---------------------------------------------------------------------------- void configureSession(const RequestParams &params, Status &st); CurlSessionFactory &_factory; CurlHandlePtr _handle; }; } #endif
Add missing header for SLC6
Add missing header for SLC6
C++
lgpl-2.1
cern-it-sdc-id/davix,cern-it-sdc-id/davix,cern-it-sdc-id/davix,cern-it-sdc-id/davix
a79786788be14abf91e9bed180a238e7bc397cfc
lib/c_wrapper.cpp
lib/c_wrapper.cpp
/* -------------------------------------------------------------------------- MusicBrainz -- The Internet music metadatabase Copyright (C) 2000 Robert Kaye This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA $Id$ ----------------------------------------------------------------------------*/ #include "musicbrainz.h" #include "mb_c.h" extern "C" { musicbrainz_t mb_New(void) { return (musicbrainz_t)new MusicBrainz(); } void mb_Delete(musicbrainz_t o) { delete (MusicBrainz *)o; } int mb_SetServer(musicbrainz_t o, char *serverAddr, short serverPort) { MusicBrainz *obj = (MusicBrainz *)o; return (int)obj->SetServer(string(serverAddr), serverPort); } int mb_SetProxy(musicbrainz_t o,char *proxyAddr, short proxyPort) { MusicBrainz *obj = (MusicBrainz *)o; return (int)obj->SetServer(string(proxyAddr), proxyPort); } int mb_SetDevice(musicbrainz_t o, char *device) { MusicBrainz *obj = (MusicBrainz *)o; return (int)obj->SetDevice(string(device)); } int mb_GetWebSubmitURL(musicbrainz_t o, char *url, int urlLen) { MusicBrainz *obj = (MusicBrainz *)o; string urlString; int ret; ret = (int)obj->GetWebSubmitURL(urlString); if (ret) { strncpy(url, urlString.c_str(), urlLen - 1); url[urlLen - 1] = 0; } return ret; } int mb_Query(musicbrainz_t o, char *xmlObject) { MusicBrainz *obj = (MusicBrainz *)o; return (int)obj->Query(string(xmlObject)); } int mb_QueryWithArgs(musicbrainz_t o, char *xmlObject, char **args) { MusicBrainz *obj = (MusicBrainz *)o; vector<string> *argList; string temp; int ret; argList = new vector<string>; for(; *args; args++) { temp = string(*args); argList->push_back(temp); } ret = obj->Query(string(xmlObject), argList); delete argList; return (int)ret; } void mb_GetQueryError(musicbrainz_t o, char *error, int maxErrorLen) { MusicBrainz *obj = (MusicBrainz *)o; string err; obj->GetQueryError(err); strncpy(error, err.c_str(), maxErrorLen); error[maxErrorLen - 1] = 0; } int mb_GetResultData(musicbrainz_t o, char *resultName, char *data, int maxDataLen) { MusicBrainz *obj = (MusicBrainz *)o; string value; value = obj->Data(string(resultName)); if (value.length() == 0) return 0; strncpy(data, value.c_str(), maxDataLen); data[maxDataLen - 1] = 0; return 1; } int mb_GetResultInt(musicbrainz_t o, char *resultName) { MusicBrainz *obj = (MusicBrainz *)o; return obj->DataInt(string(resultName)); } int mb_Select(musicbrainz_t o, char *selectQuery) { MusicBrainz *obj = (MusicBrainz *)o; return obj->Select(string(selectQuery)); } int mb_DoesResultExist(musicbrainz_t o, char *resultName) { MusicBrainz *obj = (MusicBrainz *)o; return obj->DoesResultExist(string(resultName)); } int mb_GetResultRDF(musicbrainz_t o,char *xml, int maxXMLLen) { MusicBrainz *obj = (MusicBrainz *)o; string xmlString; if (!obj->GetResultRDF(xmlString)) return 0; strncpy(xml, xmlString.c_str(), maxXMLLen); xml[maxXMLLen - 1] = 0; return 1; } int mb_GetResultRDFLen(musicbrainz_t o) { MusicBrainz *obj = (MusicBrainz *)o; string xmlString; if (!obj->GetResultRDF(xmlString)) return 0; return xmlString.length(); } int mb_GetNumItems(musicbrainz_t o) { MusicBrainz *obj = (MusicBrainz *)o; return obj->GetNumItems(); } void mb_SetPCMDataInfo(musicbrainz_t o, int samplesPerSecond, int numChannels, int bitsPerSample) { MusicBrainz *obj = (MusicBrainz *)o; obj->SetPCMDataInfo(samplesPerSecond, numChannels, bitsPerSample); } int mb_GenerateSignature(musicbrainz_t o, char *data, int size, char signature[17], char *collectionID) { string strGUID; string collID; if (!collectionID) collID = "EMPTY_COLLECTION"; else collID = string(collectionID, 16); MusicBrainz *obj = (MusicBrainz *)o; bool retvalue = obj->GenerateSignature(data, size, strGUID, collID); if (retvalue) { memset(signature, '\0', 16); strncpy(signature, strGUID.c_str(), 16); return 1; } return 0; } void mb_GenerateSignatureNow(musicbrainz_t o, char signature[17], char *collectionID) { string strGUID; string collID; if (!collectionID) collID = "EMPTY_COLLECTION"; else collID = string(collectionID, 16); MusicBrainz *obj = (MusicBrainz *)o; obj->GenerateSignatureNow(strGUID, collID); memset(signature, '\0', 16); strncpy(signature, strGUID.c_str(), 16); } void mb_ConvertSigToASCII(musicbrainz_t o, char sig[17], char ascii_sig[37]) { MusicBrainz *obj = (MusicBrainz *)o; obj->ConvertSigToASCII(sig, ascii_sig); } }
/* -------------------------------------------------------------------------- MusicBrainz -- The Internet music metadatabase Copyright (C) 2000 Robert Kaye This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA $Id$ ----------------------------------------------------------------------------*/ #include "musicbrainz.h" #include "mb_c.h" extern "C" { musicbrainz_t mb_New(void) { return (musicbrainz_t)new MusicBrainz(); } void mb_Delete(musicbrainz_t o) { delete (MusicBrainz *)o; } int mb_SetServer(musicbrainz_t o, char *serverAddr, short serverPort) { MusicBrainz *obj = (MusicBrainz *)o; return (int)obj->SetServer(string(serverAddr), serverPort); } int mb_SetProxy(musicbrainz_t o,char *proxyAddr, short proxyPort) { MusicBrainz *obj = (MusicBrainz *)o; return (int)obj->SetServer(string(proxyAddr), proxyPort); } int mb_SetDevice(musicbrainz_t o, char *device) { MusicBrainz *obj = (MusicBrainz *)o; return (int)obj->SetDevice(string(device)); } int mb_GetWebSubmitURL(musicbrainz_t o, char *url, int urlLen) { MusicBrainz *obj = (MusicBrainz *)o; string urlString; int ret; ret = (int)obj->GetWebSubmitURL(urlString); if (ret) { strncpy(url, urlString.c_str(), urlLen - 1); url[urlLen - 1] = 0; } return ret; } int mb_Query(musicbrainz_t o, char *xmlObject) { MusicBrainz *obj = (MusicBrainz *)o; return (int)obj->Query(string(xmlObject)); } int mb_QueryWithArgs(musicbrainz_t o, char *xmlObject, char **args) { MusicBrainz *obj = (MusicBrainz *)o; vector<string> *argList; string temp; int ret; argList = new vector<string>; for(; *args; args++) { temp = string(*args); argList->push_back(temp); } ret = obj->Query(string(xmlObject), argList); delete argList; return (int)ret; } void mb_GetQueryError(musicbrainz_t o, char *error, int maxErrorLen) { MusicBrainz *obj = (MusicBrainz *)o; string err; obj->GetQueryError(err); strncpy(error, err.c_str(), maxErrorLen); error[maxErrorLen - 1] = 0; } int mb_GetResultData(musicbrainz_t o, char *resultName, char *data, int maxDataLen) { MusicBrainz *obj = (MusicBrainz *)o; string value; value = obj->Data(string(resultName)); if (value.length() == 0) return 0; strncpy(data, value.c_str(), maxDataLen); data[maxDataLen - 1] = 0; return 1; } int mb_GetResultInt(musicbrainz_t o, char *resultName) { MusicBrainz *obj = (MusicBrainz *)o; return obj->DataInt(string(resultName)); } int mb_Select(musicbrainz_t o, char *selectQuery) { MusicBrainz *obj = (MusicBrainz *)o; return obj->Select(string(selectQuery)); } int mb_DoesResultExist(musicbrainz_t o, char *resultName) { MusicBrainz *obj = (MusicBrainz *)o; return obj->DoesResultExist(string(resultName)); } int mb_GetResultRDF(musicbrainz_t o,char *xml, int maxXMLLen) { MusicBrainz *obj = (MusicBrainz *)o; string xmlString; if (!obj->GetResultRDF(xmlString)) return 0; strncpy(xml, xmlString.c_str(), maxXMLLen); xml[maxXMLLen - 1] = 0; return 1; } int mb_GetResultRDFLen(musicbrainz_t o) { MusicBrainz *obj = (MusicBrainz *)o; string xmlString; if (!obj->GetResultRDF(xmlString)) return 0; return xmlString.length(); } int mb_GetNumItems(musicbrainz_t o) { MusicBrainz *obj = (MusicBrainz *)o; return obj->GetNumItems(); } void mb_SetPCMDataInfo(musicbrainz_t o, int samplesPerSecond, int numChannels, int bitsPerSample) { MusicBrainz *obj = (MusicBrainz *)o; obj->SetPCMDataInfo(samplesPerSecond, numChannels, bitsPerSample); } int mb_GenerateSignature(musicbrainz_t o, char *data, int size, char signature[17], char *collectionID) { string strGUID; string collID; if (!collectionID) collID = "EMPTY_COLLECTION"; else collID = string(collectionID, 16); MusicBrainz *obj = (MusicBrainz *)o; bool retvalue = obj->GenerateSignature(data, size, strGUID, collID); if (retvalue) { memset(signature, '\0', 17); strncpy(signature, strGUID.c_str(), 16); return 1; } return 0; } void mb_GenerateSignatureNow(musicbrainz_t o, char signature[17], char *collectionID) { string strGUID; string collID; if (!collectionID) collID = "EMPTY_COLLECTION"; else collID = string(collectionID, 16); MusicBrainz *obj = (MusicBrainz *)o; obj->GenerateSignatureNow(strGUID, collID); memset(signature, '\0', 17); strncpy(signature, strGUID.c_str(), 16); } void mb_ConvertSigToASCII(musicbrainz_t o, char sig[17], char ascii_sig[37]) { MusicBrainz *obj = (MusicBrainz *)o; obj->ConvertSigToASCII(sig, ascii_sig); } }
Make sure the returned sigs have a NULL terminator
Make sure the returned sigs have a NULL terminator git-svn-id: 95f3c568a8d713c8a134cac44d96183059969c76@313 b0b80210-5d09-0410-99dd-b4bd03f891c0
C++
lgpl-2.1
matthewruhland/libmusicbrainz,metabrainz/libmusicbrainz,matthewruhland/libmusicbrainz,sebastinas/libmusicbrainz,matthewruhland/libmusicbrainz,sebastinas/libmusicbrainz,metabrainz/libmusicbrainz,sebastinas/libmusicbrainz,metabrainz/libmusicbrainz
f2d6d255b3e8ef5609453dfa48bbc64b9cab5309
test/correctness/bitwise_ops.cpp
test/correctness/bitwise_ops.cpp
#include "Halide.h" #include <stdio.h> using namespace Halide; int main(int argc, char **argv) { Image<uint32_t> input(256); for (int i = 0; i < 256; i++) { input(i) = rand(); } Var x; // reinterpret cast Func f1; f1(x) = reinterpret<float>(input(x)); Image<float> im1 = f1.realize(256); for (int x = 0; x < 256; x++) { float y = im1(x); uint32_t output = Halide::Internal::reinterpret_bits<uint32_t>(y); if (input(x) != output) { printf("Reinterpret cast turned %x into %x!", input(x), output); return -1; } } // bitwise xor Func f2; f2(x) = input(x) ^ input(x+1); Image<uint32_t> im2 = f2.realize(128); for (int x = 0; x < 128; x++) { uint32_t correct = input(x) ^ input(x+1); if (im2(x) != correct) { printf("%x ^ %x -> %x instead of %x\n", input(x), input(x+1), im2(x), correct); } } // bitwise and Func f3; f3(x) = input(x) & input(x+1); Image<uint32_t> im3 = f3.realize(128); for (int x = 0; x < 128; x++) { uint32_t correct = input(x) & input(x+1); if (im3(x) != correct) { printf("%x & %x -> %x instead of %x\n", input(x), input(x+1), im3(x), correct); } } // bitwise or Func f4; f4(x) = input(x) | input(x+1); Image<uint32_t> im4 = f4.realize(128); for (int x = 0; x < 128; x++) { uint32_t correct = input(x) | input(x+1); if (im4(x) != correct) { printf("%x | %x -> %x instead of %x\n", input(x), input(x+1), im4(x), correct); } } // bitwise not Func f5; f5(x) = ~input(x); Image<uint32_t> im5 = f5.realize(128); for (int x = 0; x < 128; x++) { uint32_t correct = ~input(x); if (im5(x) != correct) { printf("~%x = %x instead of %x\n", input(x), im5(x), correct); } } // shift left combined with masking Func f6; f6(x) = input(x) << (input(x+1) & 0xf); Image<uint32_t> im6 = f6.realize(128); for (int x = 0; x < 128; x++) { uint32_t correct = input(x) << (input(x+1) & 0xf); if (im6(x) != correct) { printf("%x << (%x & 0xf) -> %x instead of %x\n", input(x), input(x+1), im6(x), correct); } } // logical shift right Func f7; f7(x) = input(x) >> (input(x+1) & 0xf); Image<uint32_t> im7 = f7.realize(128); for (int x = 0; x < 128; x++) { uint32_t correct = input(x) >> (input(x+1) & 0xf); if (im7(x) != correct) { printf("%x >> (%x & 0xf) -> %x instead of %x\n", input(x), input(x+1), im7(x), correct); } } // arithmetic shift right Func f8; Expr a = reinterpret<int>(input(x)); Expr b = reinterpret<int>(input(x+1)); f8(x) = a >> (b & 0xf); Image<int> im8 = f8.realize(128); for (int x = 0; x < 128; x++) { int correct = ((int)(input(x))) >> (((int)(input(x+1))) & 0xf); if (im8(x) != correct) { printf("%x >> (%x & 0xf) -> %x instead of %x\n", input(x), input(x+1), im8(x), correct); } } // bit shift on mixed types Func f9; Expr a32 = cast<int32_t>(input(x)); Expr b8 = cast<uint8_t>(input(x+1)); f9(x) = a32 >> b8; Image<int> im9 = f9.realize(128); for (int x = 0; x < 128; x++) { int correct = ((int)(input(x))) >> ((uint8_t)(input(x+1))); if (im9(x) != correct) { printf("%x >> (uint8_t)%x -> %x instead of %x\n", input(x), input(x+1), im9(x), correct); } } // bitwise and on mixed types Func f10; Expr a8 = cast<int8_t>(input(x)); f10(x) = a8 & 0xf0; Image<int8_t> im10 = f10.realize(128); for (int x = 0; x < 128; x++) { int8_t correct = (int8_t)(input(x)) & 0xf0; if (im10(x) != correct) { printf("(int8_t)%x & 0xf0 -> %x instead of %x\n", input(x), im10(x), correct); } } printf("Success!\n"); return 0; }
#include "Halide.h" #include <stdio.h> using namespace Halide; int main(int argc, char **argv) { Image<uint32_t> input(256); for (int i = 0; i < 256; i++) { input(i) = rand(); } Var x; // reinterpret cast Func f1; f1(x) = reinterpret<float>(input(x)); Image<float> im1 = f1.realize(256); for (int x = 0; x < 256; x++) { float y = im1(x); uint32_t output = Halide::Internal::reinterpret_bits<uint32_t>(y); if (input(x) != output) { printf("Reinterpret cast turned %x into %x!", input(x), output); return -1; } } // bitwise xor Func f2; f2(x) = input(x) ^ input(x+1); Image<uint32_t> im2 = f2.realize(128); for (int x = 0; x < 128; x++) { uint32_t correct = input(x) ^ input(x+1); if (im2(x) != correct) { printf("%x ^ %x -> %x instead of %x\n", input(x), input(x+1), im2(x), correct); return -1; } } // bitwise and Func f3; f3(x) = input(x) & input(x+1); Image<uint32_t> im3 = f3.realize(128); for (int x = 0; x < 128; x++) { uint32_t correct = input(x) & input(x+1); if (im3(x) != correct) { printf("%x & %x -> %x instead of %x\n", input(x), input(x+1), im3(x), correct); return -1; } } // bitwise or Func f4; f4(x) = input(x) | input(x+1); Image<uint32_t> im4 = f4.realize(128); for (int x = 0; x < 128; x++) { uint32_t correct = input(x) | input(x+1); if (im4(x) != correct) { printf("%x | %x -> %x instead of %x\n", input(x), input(x+1), im4(x), correct); return -1; } } // bitwise not Func f5; f5(x) = ~input(x); Image<uint32_t> im5 = f5.realize(128); for (int x = 0; x < 128; x++) { uint32_t correct = ~input(x); if (im5(x) != correct) { printf("~%x = %x instead of %x\n", input(x), im5(x), correct); return -1; } } // shift left combined with masking Func f6; f6(x) = input(x) << (input(x+1) & 0xf); Image<uint32_t> im6 = f6.realize(128); for (int x = 0; x < 128; x++) { uint32_t correct = input(x) << (input(x+1) & 0xf); if (im6(x) != correct) { printf("%x << (%x & 0xf) -> %x instead of %x\n", input(x), input(x+1), im6(x), correct); return -1; } } // logical shift right Func f7; f7(x) = input(x) >> (input(x+1) & 0xf); Image<uint32_t> im7 = f7.realize(128); for (int x = 0; x < 128; x++) { uint32_t correct = input(x) >> (input(x+1) & 0xf); if (im7(x) != correct) { printf("%x >> (%x & 0xf) -> %x instead of %x\n", input(x), input(x+1), im7(x), correct); return -1; } } // arithmetic shift right Func f8; Expr a = reinterpret<int>(input(x)); Expr b = reinterpret<int>(input(x+1)); f8(x) = a >> (b & 0xf); Image<int> im8 = f8.realize(128); for (int x = 0; x < 128; x++) { int correct = ((int)(input(x))) >> (((int)(input(x+1))) & 0xf); if (im8(x) != correct) { printf("%x >> (%x & 0xf) -> %x instead of %x\n", input(x), input(x+1), im8(x), correct); return -1; } } // bit shift on mixed types Func f9; Expr a32 = cast<int32_t>(input(x)); Expr b8 = min(31, cast<uint8_t>(input(x+1))); f9(x) = a32 >> b8; Image<int> im9 = f9.realize(128); for (int x = 0; x < 128; x++) { int lhs = (int)input(x); int shift_amount = (uint8_t)(input(x+1)); shift_amount = std::min(31, shift_amount); int correct = lhs >> shift_amount; if (im9(x) != correct) { printf("%x >> (uint8_t)%x -> %x instead of %x\n", input(x), input(x+1), im9(x), correct); return -1; } } // bitwise and on mixed types Func f10; Expr a8 = cast<int8_t>(input(x)); f10(x) = a8 & 0xf0; Image<int8_t> im10 = f10.realize(128); for (int x = 0; x < 128; x++) { int8_t correct = (int8_t)(input(x)) & 0xf0; if (im10(x) != correct) { printf("(int8_t)%x & 0xf0 -> %x instead of %x\n", input(x), im10(x), correct); return -1; } } printf("Success!\n"); return 0; }
Add error returns to bitwise ops test
Add error returns to bitwise ops test and avoid undefined behavior (shift by > bit width)
C++
mit
ronen/Halide,jiawen/Halide,jiawen/Halide,psuriana/Halide,ronen/Halide,psuriana/Halide,jiawen/Halide,kgnk/Halide,kgnk/Halide,jiawen/Halide,jiawen/Halide,kgnk/Halide,kgnk/Halide,psuriana/Halide,ronen/Halide,ronen/Halide,kgnk/Halide,ronen/Halide,kgnk/Halide,jiawen/Halide,psuriana/Halide,psuriana/Halide,kgnk/Halide,psuriana/Halide,jiawen/Halide,ronen/Halide,kgnk/Halide,ronen/Halide,psuriana/Halide,ronen/Halide
255b6a2d34e6943ad43c4bd31b9a5cd46399645b
src/Tracing.cpp
src/Tracing.cpp
#include "Tracing.h" #include "IRMutator.h" #include "IROperator.h" #include "runtime/HalideRuntime.h" namespace Halide { namespace Internal { int tracing_level() { char *trace = getenv("HL_TRACE"); return trace ? atoi(trace) : 0; } using std::vector; using std::map; using std::string; struct TraceEventBuilder { string func; vector<Expr> value; vector<Expr> coordinates; Type type; enum halide_trace_event_code_t event; Expr parent_id, value_index, dimensions; Expr build() { Expr values = Call::make(type_of<void *>(), Call::make_struct, value, Call::Intrinsic); Expr coords = Call::make(type_of<int32_t *>(), Call::make_struct, coordinates, Call::Intrinsic); Expr idx = value_index; if (!idx.defined()) { idx = 0; } vector<Expr> args = {Expr(func), values, coords, (int)type.code(), (int)type.bits(), (int)type.lanes(), (int)event, parent_id, idx, (int)coordinates.size()}; return Call::make(Int(32), Call::trace, args, Call::Extern); } }; class InjectTracing : public IRMutator { public: const map<string, Function> &env; int global_level; InjectTracing(const map<string, Function> &e) : env(e), global_level(tracing_level()) {} private: using IRMutator::visit; void visit(const Call *op) { // Calls inside of an address_of don't count, but we want to // visit the args of the inner call. if (op->is_intrinsic(Call::address_of)) { internal_assert(op->args.size() == 1); const Call *c = op->args[0].as<Call>(); const Load *l = op->args[0].as<Load>(); internal_assert(c || l); std::vector<Expr> args; if (c) { args = c->args; } else { args.push_back(l->index); } bool unchanged = true; vector<Expr> new_args(args.size()); for (size_t i = 0; i < args.size(); i++) { new_args[i] = mutate(args[i]); unchanged = unchanged && (new_args[i].same_as(args[i])); } if (unchanged) { expr = op; return; } else { Expr inner; if (c) { inner = Call::make(c->type, c->name, new_args, c->call_type, c->func, c->value_index, c->image, c->param); } else { Expr inner = Load::make(l->type, l->name, new_args[0], l->image, l->param, l->predicate); } expr = Call::make(op->type, Call::address_of, {inner}, Call::Intrinsic); return; } } IRMutator::visit(op); op = expr.as<Call>(); internal_assert(op); bool trace_it = false; Expr trace_parent; if (op->call_type == Call::Halide) { Function f = env.find(op->name)->second; internal_assert(!f.can_be_inlined() || !f.schedule().compute_level().is_inline()); trace_it = f.is_tracing_loads() || (global_level > 2); trace_parent = Variable::make(Int(32), op->name + ".trace_id"); } else if (op->call_type == Call::Image) { trace_it = global_level > 2; trace_parent = Variable::make(Int(32), "pipeline.trace_id"); } if (trace_it) { string value_var_name = unique_name('t'); Expr value_var = Variable::make(op->type, value_var_name); TraceEventBuilder builder; builder.func = op->name; builder.value = {value_var}; builder.coordinates = op->args; builder.type = op->type; builder.event = halide_trace_load; builder.parent_id = trace_parent; builder.value_index = op->value_index; Expr trace = builder.build(); expr = Let::make(value_var_name, op, Call::make(op->type, Call::return_second, {trace, value_var}, Call::PureIntrinsic)); } } void visit(const Provide *op) { IRMutator::visit(op); op = stmt.as<Provide>(); internal_assert(op); map<string, Function>::const_iterator iter = env.find(op->name); if (iter == env.end()) return; Function f = iter->second; internal_assert(!f.can_be_inlined() || !f.schedule().compute_level().is_inline()); if (f.is_tracing_stores() || (global_level > 1)) { // Wrap each expr in a tracing call const vector<Expr> &values = op->values; vector<Expr> traces(op->values.size()); TraceEventBuilder builder; builder.func = f.name(); builder.coordinates = op->args; builder.event = halide_trace_store; builder.parent_id = Variable::make(Int(32), op->name + ".trace_id"); for (size_t i = 0; i < values.size(); i++) { Type t = values[i].type(); string value_var_name = unique_name('t'); Expr value_var = Variable::make(t, value_var_name); builder.type = t; builder.value_index = (int)i; builder.value = {value_var}; Expr trace = builder.build(); traces[i] = Let::make(value_var_name, values[i], Call::make(t, Call::return_second, {trace, value_var}, Call::PureIntrinsic)); } stmt = Provide::make(op->name, traces, op->args); } } void visit(const Realize *op) { IRMutator::visit(op); op = stmt.as<Realize>(); internal_assert(op); map<string, Function>::const_iterator iter = env.find(op->name); if (iter == env.end()) return; Function f = iter->second; if (f.is_tracing_realizations() || global_level > 0) { // Throw a tracing call before and after the realize body TraceEventBuilder builder; builder.func = op->name; builder.parent_id = Variable::make(Int(32), "pipeline.trace_id"); builder.event = halide_trace_begin_realization; for (size_t i = 0; i < op->bounds.size(); i++) { builder.coordinates.push_back(op->bounds[i].min); builder.coordinates.push_back(op->bounds[i].extent); } // Begin realization returns a unique token to pass to further trace calls affecting this buffer. Expr call_before = builder.build(); builder.event = halide_trace_end_realization; builder.parent_id = Variable::make(Int(32), op->name + ".trace_id"); Expr call_after = builder.build(); Stmt new_body = op->body; new_body = Block::make(new_body, Evaluate::make(call_after)); new_body = LetStmt::make(op->name + ".trace_id", call_before, new_body); stmt = Realize::make(op->name, op->types, op->bounds, op->condition, new_body); } else if (f.is_tracing_stores() || f.is_tracing_loads()) { // We need a trace id defined to pass to the loads and stores Stmt new_body = op->body; new_body = LetStmt::make(op->name + ".trace_id", 0, new_body); stmt = Realize::make(op->name, op->types, op->bounds, op->condition, new_body); } } void visit(const ProducerConsumer *op) { IRMutator::visit(op); op = stmt.as<ProducerConsumer>(); internal_assert(op); map<string, Function>::const_iterator iter = env.find(op->name); if (iter == env.end()) return; Function f = iter->second; if (f.is_tracing_realizations() || global_level > 0) { // Throw a tracing call around each pipeline event TraceEventBuilder builder; builder.func = op->name; builder.parent_id = Variable::make(Int(32), op->name + ".trace_id"); // Use the size of the pure step const vector<string> f_args = f.args(); for (int i = 0; i < f.dimensions(); i++) { Expr min = Variable::make(Int(32), f.name() + ".s0." + f_args[i] + ".min"); Expr max = Variable::make(Int(32), f.name() + ".s0." + f_args[i] + ".max"); Expr extent = (max + 1) - min; builder.coordinates.push_back(min); builder.coordinates.push_back(extent); } builder.event = (op->is_producer ? halide_trace_end_produce : halide_trace_end_consume); Expr call = builder.build(); Stmt new_body = Block::make(op->body, Evaluate::make(call)); stmt = ProducerConsumer::make(op->name, op->is_producer, new_body); builder.event = (op->is_producer ? halide_trace_produce : halide_trace_consume); call = builder.build(); stmt = LetStmt::make(f.name() + ".trace_id", call, stmt); } } }; class RemoveRealizeOverOutput : public IRMutator { using IRMutator::visit; const vector<Function> &outputs; void visit(const Realize *op) { for (Function f : outputs) { if (op->name == f.name()) { stmt = mutate(op->body); return; } } IRMutator::visit(op); } public: RemoveRealizeOverOutput(const vector<Function> &o) : outputs(o) {} }; Stmt inject_tracing(Stmt s, const string &pipeline_name, const map<string, Function> &env, const vector<Function> &outputs) { Stmt original = s; InjectTracing tracing(env); // Add a dummy realize block for the output buffers for (Function output : outputs) { Region output_region; Parameter output_buf = output.output_buffers()[0]; internal_assert(output_buf.is_buffer()); for (int i = 0; i < output.dimensions(); i++) { string d = std::to_string(i); Expr min = Variable::make(Int(32), output_buf.name() + ".min." + d); Expr extent = Variable::make(Int(32), output_buf.name() + ".extent." + d); output_region.push_back(Range(min, extent)); } s = Realize::make(output.name(), output.output_types(), output_region, const_true(), s); } // Inject tracing calls s = tracing.mutate(s); // Strip off the dummy realize blocks s = RemoveRealizeOverOutput(outputs).mutate(s); if (!s.same_as(original)) { // Add pipeline start and end events TraceEventBuilder builder; builder.func = pipeline_name; builder.event = halide_trace_begin_pipeline; builder.parent_id = 0; Expr pipeline_start = builder.build(); builder.event = halide_trace_end_pipeline; builder.parent_id = Variable::make(Int(32), "pipeline.trace_id"); Expr pipeline_end = builder.build(); s = Block::make(s, Evaluate::make(pipeline_end)); s = LetStmt::make("pipeline.trace_id", pipeline_start, s); } return s; } } }
#include "Tracing.h" #include "IRMutator.h" #include "IROperator.h" #include "runtime/HalideRuntime.h" namespace Halide { namespace Internal { int tracing_level() { char *trace = getenv("HL_TRACE"); return trace ? atoi(trace) : 0; } using std::vector; using std::map; using std::string; struct TraceEventBuilder { string func; vector<Expr> value; vector<Expr> coordinates; Type type; enum halide_trace_event_code_t event; Expr parent_id, value_index, dimensions; Expr build() { Expr values = Call::make(type_of<void *>(), Call::make_struct, value, Call::Intrinsic); Expr coords = Call::make(type_of<int32_t *>(), Call::make_struct, coordinates, Call::Intrinsic); Expr idx = value_index; if (!idx.defined()) { idx = 0; } vector<Expr> args = {Expr(func), values, coords, (int)type.code(), (int)type.bits(), (int)type.lanes(), (int)event, parent_id, idx, (int)coordinates.size()}; return Call::make(Int(32), Call::trace, args, Call::Extern); } }; class InjectTracing : public IRMutator { public: const map<string, Function> &env; int global_level; InjectTracing(const map<string, Function> &e) : env(e), global_level(tracing_level()) {} private: using IRMutator::visit; void visit(const Call *op) { // Calls inside of an address_of don't count, but we want to // visit the args of the inner call. if (op->is_intrinsic(Call::address_of)) { internal_assert(op->args.size() == 1); const Call *c = op->args[0].as<Call>(); const Load *l = op->args[0].as<Load>(); internal_assert(c || l); std::vector<Expr> args; if (c) { args = c->args; } else { args.push_back(l->index); } bool unchanged = true; vector<Expr> new_args(args.size()); for (size_t i = 0; i < args.size(); i++) { new_args[i] = mutate(args[i]); unchanged = unchanged && (new_args[i].same_as(args[i])); } if (unchanged) { expr = op; return; } else { Expr inner; if (c) { inner = Call::make(c->type, c->name, new_args, c->call_type, c->func, c->value_index, c->image, c->param); } else { Expr inner = Load::make(l->type, l->name, new_args[0], l->image, l->param, l->predicate); } expr = Call::make(op->type, Call::address_of, {inner}, Call::Intrinsic); return; } } IRMutator::visit(op); op = expr.as<Call>(); internal_assert(op); bool trace_it = false; Expr trace_parent; if (op->call_type == Call::Halide) { Function f = env.find(op->name)->second; internal_assert(!f.can_be_inlined() || !f.schedule().compute_level().is_inline()); trace_it = f.is_tracing_loads() || (global_level > 2); trace_parent = Variable::make(Int(32), op->name + ".trace_id"); } else if (op->call_type == Call::Image) { trace_it = global_level > 2; trace_parent = Variable::make(Int(32), "pipeline.trace_id"); } if (trace_it) { string value_var_name = unique_name('t'); Expr value_var = Variable::make(op->type, value_var_name); TraceEventBuilder builder; builder.func = op->name; builder.value = {value_var}; builder.coordinates = op->args; builder.type = op->type; builder.event = halide_trace_load; builder.parent_id = trace_parent; builder.value_index = op->value_index; Expr trace = builder.build(); expr = Let::make(value_var_name, op, Call::make(op->type, Call::return_second, {trace, value_var}, Call::PureIntrinsic)); } } void visit(const Provide *op) { IRMutator::visit(op); op = stmt.as<Provide>(); internal_assert(op); map<string, Function>::const_iterator iter = env.find(op->name); if (iter == env.end()) return; Function f = iter->second; internal_assert(!f.can_be_inlined() || !f.schedule().compute_level().is_inline()); if (f.is_tracing_stores() || (global_level > 1)) { // Wrap each expr in a tracing call const vector<Expr> &values = op->values; vector<Expr> traces(op->values.size()); TraceEventBuilder builder; builder.func = f.name(); builder.coordinates = op->args; builder.event = halide_trace_store; builder.parent_id = Variable::make(Int(32), op->name + ".trace_id"); for (size_t i = 0; i < values.size(); i++) { Type t = values[i].type(); string value_var_name = unique_name('t'); Expr value_var = Variable::make(t, value_var_name); builder.type = t; builder.value_index = (int)i; builder.value = {value_var}; Expr trace = builder.build(); traces[i] = Let::make(value_var_name, values[i], Call::make(t, Call::return_second, {trace, value_var}, Call::PureIntrinsic)); } stmt = Provide::make(op->name, traces, op->args); } } void visit(const Realize *op) { IRMutator::visit(op); op = stmt.as<Realize>(); internal_assert(op); map<string, Function>::const_iterator iter = env.find(op->name); if (iter == env.end()) return; Function f = iter->second; if (f.is_tracing_realizations() || global_level > 0) { // Throw a tracing call before and after the realize body TraceEventBuilder builder; builder.func = op->name; builder.parent_id = Variable::make(Int(32), "pipeline.trace_id"); builder.event = halide_trace_begin_realization; for (size_t i = 0; i < op->bounds.size(); i++) { builder.coordinates.push_back(op->bounds[i].min); builder.coordinates.push_back(op->bounds[i].extent); } // Begin realization returns a unique token to pass to further trace calls affecting this buffer. Expr call_before = builder.build(); builder.event = halide_trace_end_realization; builder.parent_id = Variable::make(Int(32), op->name + ".trace_id"); Expr call_after = builder.build(); Stmt new_body = op->body; new_body = Block::make(new_body, Evaluate::make(call_after)); new_body = LetStmt::make(op->name + ".trace_id", call_before, new_body); stmt = Realize::make(op->name, op->types, op->bounds, op->condition, new_body); } else if (f.is_tracing_stores() || f.is_tracing_loads()) { // We need a trace id defined to pass to the loads and stores Stmt new_body = op->body; new_body = LetStmt::make(op->name + ".trace_id", 0, new_body); stmt = Realize::make(op->name, op->types, op->bounds, op->condition, new_body); } } void visit(const ProducerConsumer *op) { IRMutator::visit(op); op = stmt.as<ProducerConsumer>(); internal_assert(op); map<string, Function>::const_iterator iter = env.find(op->name); if (iter == env.end()) return; Function f = iter->second; if (f.is_tracing_realizations() || global_level > 0) { // Throw a tracing call around each pipeline event TraceEventBuilder builder; builder.func = op->name; builder.parent_id = Variable::make(Int(32), op->name + ".trace_id"); // Use the size of the pure step const vector<string> f_args = f.args(); for (int i = 0; i < f.dimensions(); i++) { Expr min = Variable::make(Int(32), f.name() + ".s0." + f_args[i] + ".min"); Expr max = Variable::make(Int(32), f.name() + ".s0." + f_args[i] + ".max"); Expr extent = (max + 1) - min; builder.coordinates.push_back(min); builder.coordinates.push_back(extent); } const bool is_producer = op->is_producer; builder.event = (is_producer ? halide_trace_end_produce : halide_trace_end_consume); Expr call = builder.build(); Stmt new_body = Block::make(op->body, Evaluate::make(call)); // Note: this call makes op invalid; don't reference it later stmt = ProducerConsumer::make(op->name, is_producer, new_body); builder.event = (is_producer ? halide_trace_produce : halide_trace_consume); call = builder.build(); stmt = LetStmt::make(f.name() + ".trace_id", call, stmt); } } }; class RemoveRealizeOverOutput : public IRMutator { using IRMutator::visit; const vector<Function> &outputs; void visit(const Realize *op) { for (Function f : outputs) { if (op->name == f.name()) { stmt = mutate(op->body); return; } } IRMutator::visit(op); } public: RemoveRealizeOverOutput(const vector<Function> &o) : outputs(o) {} }; Stmt inject_tracing(Stmt s, const string &pipeline_name, const map<string, Function> &env, const vector<Function> &outputs) { Stmt original = s; InjectTracing tracing(env); // Add a dummy realize block for the output buffers for (Function output : outputs) { Region output_region; Parameter output_buf = output.output_buffers()[0]; internal_assert(output_buf.is_buffer()); for (int i = 0; i < output.dimensions(); i++) { string d = std::to_string(i); Expr min = Variable::make(Int(32), output_buf.name() + ".min." + d); Expr extent = Variable::make(Int(32), output_buf.name() + ".extent." + d); output_region.push_back(Range(min, extent)); } s = Realize::make(output.name(), output.output_types(), output_region, const_true(), s); } // Inject tracing calls s = tracing.mutate(s); // Strip off the dummy realize blocks s = RemoveRealizeOverOutput(outputs).mutate(s); if (!s.same_as(original)) { // Add pipeline start and end events TraceEventBuilder builder; builder.func = pipeline_name; builder.event = halide_trace_begin_pipeline; builder.parent_id = 0; Expr pipeline_start = builder.build(); builder.event = halide_trace_end_pipeline; builder.parent_id = Variable::make(Int(32), "pipeline.trace_id"); Expr pipeline_end = builder.build(); s = Block::make(s, Evaluate::make(pipeline_end)); s = LetStmt::make("pipeline.trace_id", pipeline_start, s); } return s; } } }
Fix use-after-free in TraceEventBuilder
Fix use-after-free in TraceEventBuilder Former-commit-id: 8ba15fa31976f12ef161a60d3c5cb791e9f11196
C++
mit
darkbuck/Halide,darkbuck/Halide,Trass3r/Halide,Trass3r/Halide,Trass3r/Halide,Trass3r/Halide,darkbuck/Halide,darkbuck/Halide,darkbuck/Halide,darkbuck/Halide,Trass3r/Halide,darkbuck/Halide,Trass3r/Halide,Trass3r/Halide
9338f4da0d648cb73339c202fafbbc9376bb3fcb
tensorflow/core/kernels/data/experimental/sql/sqlite_query_connection.cc
tensorflow/core/kernels/data/experimental/sql/sqlite_query_connection.cc
/* Copyright 2017 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "tensorflow/core/kernels/data/experimental/sql/sqlite_query_connection.h" #include "tensorflow/core/framework/dataset.h" #include "tensorflow/core/framework/register_types.h" #include "tensorflow/core/lib/strings/stringprintf.h" namespace tensorflow { namespace data { namespace experimental { namespace sql { SqliteQueryConnection::SqliteQueryConnection() {} SqliteQueryConnection::~SqliteQueryConnection() { if (db_ != nullptr) db_->Unref(); } Status SqliteQueryConnection::Open(const string& data_source_name, const string& query, const DataTypeVector& output_types) { if (db_ != nullptr) { return errors::FailedPrecondition( "Failed to open query connection: Connection already opened."); } TF_RETURN_IF_ERROR(Sqlite::Open( data_source_name, SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, &db_)); query_ = query; output_types_ = output_types; return Status::OK(); } Status SqliteQueryConnection::Close() { stmt_ = SqliteStatement(); db_->Unref(); db_ = nullptr; return Status::OK(); } Status SqliteQueryConnection::GetNext(IteratorContext* ctx, std::vector<Tensor>* out_tensors, bool* end_of_sequence) { if (!stmt_) TF_RETURN_IF_ERROR(PrepareQuery()); TF_RETURN_IF_ERROR(stmt_.Step(end_of_sequence)); if (!*end_of_sequence) { for (int i = 0; i < column_count_; i++) { DataType dt = output_types_[i]; // TODO(mrry): Pass in the `IteratorContext::allocator()`. out_tensors->emplace_back(ctx->allocator({}), dt, TensorShape({})); FillTensorWithResultSetEntry(dt, i, &out_tensors->back()); } } return Status::OK(); } Status SqliteQueryConnection::PrepareQuery() { TF_RETURN_IF_ERROR(db_->Prepare(query_, &stmt_)); size_t column_count = stmt_.ColumnCount(); if (column_count != output_types_.size()) { stmt_ = SqliteStatement(); return errors::InvalidArgument(tensorflow::strings::Printf( "The number of columns in query (%d) must match the number of " "elements in output_types (%zu).", column_count, output_types_.size())); } column_count_ = column_count; return Status::OK(); } void SqliteQueryConnection::FillTensorWithResultSetEntry( const DataType& data_type, int column_index, Tensor* tensor) { #define CASE(T, M) \ case DataTypeToEnum<T>::value: \ tensor->scalar<T>()() = static_cast<T>(stmt_.M(column_index)); \ break; #define INT_CASE(T) CASE(T, ColumnInt) #define DOUBLE_CASE(T) CASE(T, ColumnDouble) #define STRING_CASE(T) CASE(T, ColumnString) // clang-format off switch (data_type) { TF_CALL_int8(INT_CASE) TF_CALL_uint8(INT_CASE) TF_CALL_int16(INT_CASE) TF_CALL_uint16(INT_CASE) TF_CALL_int32(INT_CASE) TF_CALL_uint32(INT_CASE) TF_CALL_int64(INT_CASE) TF_CALL_uint64(INT_CASE) TF_CALL_float(DOUBLE_CASE) TF_CALL_double(DOUBLE_CASE) TF_CALL_tstring(STRING_CASE) case DT_BOOL: tensor->scalar<bool>()() = stmt_.ColumnInt(column_index) != 0; break; // Error preemptively thrown by SqlDatasetOp::MakeDataset in this case. default: LOG(ERROR) << "Use of unsupported TensorFlow data type by 'SqlQueryConnection': " << DataTypeString(data_type) << "."; } // clang-format on } } // namespace sql } // namespace experimental } // namespace data } // namespace tensorflow
/* Copyright 2017 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "tensorflow/core/kernels/data/experimental/sql/sqlite_query_connection.h" #include "tensorflow/core/framework/dataset.h" #include "tensorflow/core/framework/register_types.h" #include "tensorflow/core/lib/strings/stringprintf.h" namespace tensorflow { namespace data { namespace experimental { namespace sql { SqliteQueryConnection::SqliteQueryConnection() {} SqliteQueryConnection::~SqliteQueryConnection() { if (db_ != nullptr) db_->Unref(); } Status SqliteQueryConnection::Open(const string& data_source_name, const string& query, const DataTypeVector& output_types) { if (db_ != nullptr) { return errors::FailedPrecondition( "Failed to open query connection: Connection already opened."); } TF_RETURN_IF_ERROR(Sqlite::Open( data_source_name, SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, &db_)); query_ = query; output_types_ = output_types; return Status::OK(); } Status SqliteQueryConnection::Close() { stmt_ = SqliteStatement(); db_->Unref(); db_ = nullptr; return Status::OK(); } Status SqliteQueryConnection::GetNext(IteratorContext* ctx, std::vector<Tensor>* out_tensors, bool* end_of_sequence) { if (!stmt_) TF_RETURN_IF_ERROR(PrepareQuery()); TF_RETURN_IF_ERROR(stmt_.Step(end_of_sequence)); if (!*end_of_sequence) { for (int i = 0; i < column_count_; i++) { DataType dt = output_types_[i]; // TODO(mrry): Pass in the `IteratorContext::allocator()`. out_tensors->emplace_back(ctx->allocator({}), dt, TensorShape({})); FillTensorWithResultSetEntry(dt, i, &out_tensors->back()); } } return Status::OK(); } Status SqliteQueryConnection::PrepareQuery() { TF_RETURN_IF_ERROR(db_->Prepare(query_, &stmt_)); int column_count = stmt_.ColumnCount(); if (column_count != static_cast<int>(output_types_.size())) { stmt_ = SqliteStatement(); return errors::InvalidArgument(tensorflow::strings::Printf( "The number of columns in query (%d) must match the number of " "elements in output_types (%zu).", column_count, output_types_.size())); } column_count_ = column_count; return Status::OK(); } void SqliteQueryConnection::FillTensorWithResultSetEntry( const DataType& data_type, int column_index, Tensor* tensor) { #define CASE(T, M) \ case DataTypeToEnum<T>::value: \ tensor->scalar<T>()() = static_cast<T>(stmt_.M(column_index)); \ break; #define INT_CASE(T) CASE(T, ColumnInt) #define DOUBLE_CASE(T) CASE(T, ColumnDouble) #define STRING_CASE(T) CASE(T, ColumnString) // clang-format off switch (data_type) { TF_CALL_int8(INT_CASE) TF_CALL_uint8(INT_CASE) TF_CALL_int16(INT_CASE) TF_CALL_uint16(INT_CASE) TF_CALL_int32(INT_CASE) TF_CALL_uint32(INT_CASE) TF_CALL_int64(INT_CASE) TF_CALL_uint64(INT_CASE) TF_CALL_float(DOUBLE_CASE) TF_CALL_double(DOUBLE_CASE) TF_CALL_tstring(STRING_CASE) case DT_BOOL: tensor->scalar<bool>()() = stmt_.ColumnInt(column_index) != 0; break; // Error preemptively thrown by SqlDatasetOp::MakeDataset in this case. default: LOG(ERROR) << "Use of unsupported TensorFlow data type by 'SqlQueryConnection': " << DataTypeString(data_type) << "."; } // clang-format on } } // namespace sql } // namespace experimental } // namespace data } // namespace tensorflow
Update sqlite_query_connection.cc
Update sqlite_query_connection.cc
C++
apache-2.0
tensorflow/tensorflow-pywrap_tf_optimizer,karllessard/tensorflow,gautam1858/tensorflow,karllessard/tensorflow,annarev/tensorflow,paolodedios/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,tensorflow/tensorflow-pywrap_saved_model,frreiss/tensorflow-fred,petewarden/tensorflow,freedomtan/tensorflow,tensorflow/tensorflow,petewarden/tensorflow,gautam1858/tensorflow,gautam1858/tensorflow,annarev/tensorflow,Intel-tensorflow/tensorflow,gautam1858/tensorflow,yongtang/tensorflow,petewarden/tensorflow,Intel-tensorflow/tensorflow,tensorflow/tensorflow-pywrap_saved_model,davidzchen/tensorflow,aam-at/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,karllessard/tensorflow,paolodedios/tensorflow,karllessard/tensorflow,gautam1858/tensorflow,davidzchen/tensorflow,frreiss/tensorflow-fred,paolodedios/tensorflow,Intel-Corporation/tensorflow,freedomtan/tensorflow,frreiss/tensorflow-fred,paolodedios/tensorflow,frreiss/tensorflow-fred,freedomtan/tensorflow,Intel-Corporation/tensorflow,paolodedios/tensorflow,davidzchen/tensorflow,aam-at/tensorflow,tensorflow/tensorflow,petewarden/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,Intel-tensorflow/tensorflow,tensorflow/tensorflow-pywrap_saved_model,aldian/tensorflow,davidzchen/tensorflow,sarvex/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,annarev/tensorflow,tensorflow/tensorflow-pywrap_saved_model,Intel-tensorflow/tensorflow,yongtang/tensorflow,freedomtan/tensorflow,petewarden/tensorflow,frreiss/tensorflow-fred,tensorflow/tensorflow-pywrap_tf_optimizer,karllessard/tensorflow,yongtang/tensorflow,freedomtan/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,tensorflow/tensorflow,petewarden/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,aam-at/tensorflow,karllessard/tensorflow,paolodedios/tensorflow,annarev/tensorflow,Intel-tensorflow/tensorflow,sarvex/tensorflow,freedomtan/tensorflow,paolodedios/tensorflow,aam-at/tensorflow,yongtang/tensorflow,freedomtan/tensorflow,aam-at/tensorflow,gautam1858/tensorflow,sarvex/tensorflow,gautam1858/tensorflow,aldian/tensorflow,davidzchen/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,karllessard/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,karllessard/tensorflow,petewarden/tensorflow,petewarden/tensorflow,annarev/tensorflow,cxxgtxy/tensorflow,frreiss/tensorflow-fred,gautam1858/tensorflow,tensorflow/tensorflow-pywrap_saved_model,annarev/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,yongtang/tensorflow,petewarden/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,karllessard/tensorflow,yongtang/tensorflow,tensorflow/tensorflow,tensorflow/tensorflow,freedomtan/tensorflow,petewarden/tensorflow,frreiss/tensorflow-fred,tensorflow/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,sarvex/tensorflow,davidzchen/tensorflow,aldian/tensorflow,gautam1858/tensorflow,aldian/tensorflow,frreiss/tensorflow-fred,freedomtan/tensorflow,annarev/tensorflow,yongtang/tensorflow,Intel-tensorflow/tensorflow,annarev/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,tensorflow/tensorflow,aam-at/tensorflow,aam-at/tensorflow,aldian/tensorflow,cxxgtxy/tensorflow,Intel-Corporation/tensorflow,karllessard/tensorflow,davidzchen/tensorflow,cxxgtxy/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,davidzchen/tensorflow,frreiss/tensorflow-fred,annarev/tensorflow,aldian/tensorflow,frreiss/tensorflow-fred,gautam1858/tensorflow,tensorflow/tensorflow-pywrap_saved_model,Intel-tensorflow/tensorflow,tensorflow/tensorflow-pywrap_saved_model,tensorflow/tensorflow-pywrap_tf_optimizer,Intel-Corporation/tensorflow,tensorflow/tensorflow,freedomtan/tensorflow,Intel-Corporation/tensorflow,yongtang/tensorflow,cxxgtxy/tensorflow,annarev/tensorflow,tensorflow/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,freedomtan/tensorflow,aldian/tensorflow,petewarden/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,tensorflow/tensorflow-pywrap_tf_optimizer,paolodedios/tensorflow,tensorflow/tensorflow-pywrap_saved_model,davidzchen/tensorflow,davidzchen/tensorflow,freedomtan/tensorflow,aam-at/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,sarvex/tensorflow,frreiss/tensorflow-fred,davidzchen/tensorflow,sarvex/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,yongtang/tensorflow,aam-at/tensorflow,yongtang/tensorflow,paolodedios/tensorflow,paolodedios/tensorflow,aam-at/tensorflow,tensorflow/tensorflow,Intel-Corporation/tensorflow,sarvex/tensorflow,gautam1858/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,annarev/tensorflow,sarvex/tensorflow,cxxgtxy/tensorflow,Intel-Corporation/tensorflow,cxxgtxy/tensorflow,petewarden/tensorflow,frreiss/tensorflow-fred,Intel-tensorflow/tensorflow,aam-at/tensorflow,paolodedios/tensorflow,cxxgtxy/tensorflow,aam-at/tensorflow,tensorflow/tensorflow-pywrap_saved_model,aldian/tensorflow,karllessard/tensorflow,davidzchen/tensorflow,cxxgtxy/tensorflow,gautam1858/tensorflow,tensorflow/tensorflow,yongtang/tensorflow,tensorflow/tensorflow-pywrap_saved_model,Intel-Corporation/tensorflow,tensorflow/tensorflow-pywrap_saved_model,Intel-tensorflow/tensorflow,Intel-tensorflow/tensorflow,Intel-tensorflow/tensorflow
7fb370cde74caf4e39290327ddcd5ed1a282f40e
test/assertion_return_tests.cpp
test/assertion_return_tests.cpp
//====================================================================== //----------------------------------------------------------------------- /** * @file assertion_return_tests.cpp * @brief iutest assertion return test * * @author t.shirayanagi * @par copyright * Copyright (C) 2013-2016, Takazumi Shirayanagi\n * This software is released under the new BSD License, * see LICENSE */ //----------------------------------------------------------------------- //====================================================================== //====================================================================== // include #include "../include/gtest/iutest_spi_switch.hpp" #if IUTEST_HAS_ASSERTION_RETURN static int value1 = 1; static int value2 = 1; int ReturnTest1(bool condition) { IUTEST_ASSERT_TRUE(condition) << "message" << ::iutest::AssertionReturnType<int>(-1); return 0; } int ReturnTest2(bool condition) { IUTEST_ASSERT_TRUE(condition) << "message" << ::iutest::AssertionReturn(-1); return 0; } void ReturnTestCall(void) { IUTEST_ASSERT_EQ(0, ReturnTest1(true)); IUTEST_ASSERT_EQ(0, ReturnTest2(true)); IUTEST_ASSERT_FATAL_FAILURE(value1 = ReturnTest1(false), "message"); IUTEST_ASSERT_FATAL_FAILURE(value2 = ReturnTest2(false), "message"); IUTEST_ASSERT_TRUE(false) << ::iutest::AssertionReturn(); } IUTEST(ReturnTest, Test) { IUTEST_ASSERT_FATAL_FAILURE(ReturnTestCall(), ""); #if IUTEST_USE_THROW_ON_ASSERTION_FAILURE IUTEST_EXPECT_EQ( 1, value1); IUTEST_EXPECT_EQ( 1, value2); #else IUTEST_EXPECT_EQ(-1, value1); IUTEST_EXPECT_EQ(-1, value2); #endif } #endif #ifdef UNICODE int wmain(int argc, wchar_t** argv) #else int main(int argc, char** argv) #endif { IUTEST_INIT(&argc, argv); return IUTEST_RUN_ALL_TESTS(); }
//====================================================================== //----------------------------------------------------------------------- /** * @file assertion_return_tests.cpp * @brief iutest assertion return test * * @author t.shirayanagi * @par copyright * Copyright (C) 2013-2016, Takazumi Shirayanagi\n * This software is released under the new BSD License, * see LICENSE */ //----------------------------------------------------------------------- //====================================================================== //====================================================================== // include #include "../include/gtest/iutest_spi_switch.hpp" #if IUTEST_HAS_ASSERTION_RETURN static int value1 = 1; static int value2 = 1; int ReturnTest1(bool condition) { IUTEST_ASSERT_TRUE(condition) << "message" << ::iutest::AssertionReturnType<int>(-1); return 0; } int ReturnTest2(bool condition) { IUTEST_ASSERT_TRUE(condition) << "message" << ::iutest::AssertionReturn(-1); return 0; } void ReturnTestCall(void) { IUTEST_ASSERT_EQ(0, ReturnTest1(true)); IUTEST_ASSERT_EQ(0, ReturnTest2(true)); IUTEST_ASSERT_FATAL_FAILURE(value1 = ReturnTest1(false), "message"); IUTEST_ASSERT_FATAL_FAILURE(value2 = ReturnTest2(false), "message"); IUTEST_ASSERT_TRUE(false) << ::iutest::AssertionReturn(); } IUTEST(ReturnTest, Test) { IUTEST_ASSERT_FATAL_FAILURE(ReturnTestCall(), ""); #if IUTEST_USE_THROW_ON_ASSERTION_FAILURE IUTEST_EXPECT_EQ( 1, value1); IUTEST_EXPECT_EQ( 1, value2); #else IUTEST_EXPECT_EQ(-1, value1); IUTEST_EXPECT_EQ(-1, value2); #endif } #endif #ifdef UNICODE int wmain(int argc, wchar_t** argv) #else int main(int argc, char** argv) #endif { IUTEST_INIT(&argc, argv); return IUTEST_RUN_ALL_TESTS(); }
fix cpplint
fix cpplint
C++
bsd-3-clause
srz-zumix/iutest,srz-zumix/iutest,srz-zumix/iutest,srz-zumix/iutest,srz-zumix/iutest
ffc25ad92a22e67b60c1a248d047d8e36b491dba
Hanse/Framework/modulesgraph.cpp
Hanse/Framework/modulesgraph.cpp
#include "modulesgraph.h" #include <Module_ScanningSonar/module_scanningsonar.h> #include <Module_UID/module_uid.h> #include <Module_Thruster/module_thruster.h> #include <Module_PressureSensor/module_pressuresensor.h> #include <Module_ThrusterControlLoop/module_thrustercontrolloop.h> #include <Module_HandControl/module_handcontrol.h> #include <Module_SonarLocalization/module_sonarlocalization.h> #include <Module_Navigation/module_navigation.h> #include <Behaviour_PipeFollowing/behaviour_pipefollowing.h> #include <Behaviour_GoalFollowing/behaviour_goalfollowing.h> #include <Behaviour_BallFollowing/behaviour_ballfollowing.h> #include <Module_Webcams/module_webcams.h> #include <Behaviour_TurnOneEighty/behaviour_turnoneeighty.h> #include <Module_Simulation/module_simulation.h> #include <Module_EchoSounder/module_echosounder.h> #include <Module_XsensMTi/module_xsensmti.h> #include <Behaviour_WallFollowing/behaviour_wallfollowing.h> #include <CommandCenter/commandcenter.h> #include "SoToSleep.h" #include <TaskHandControl/taskhandcontrol.h> #include <TaskWallNavigation/taskwallnavigation.h> #include <Behaviour_XsensFollowing/behaviour_xsensfollowing.h> //#include <Module_IMU/module_imu.h> //#include <Module_ADC/module_adc.h> #include <TaskXsensNavigation/taskxsensnavigation.h> ModulesGraph::ModulesGraph() { logger = Log4Qt::Logger::logger("ModulesGraph"); } void ModulesGraph::build() { logger->info("Loading all Modules..."); // logger->debug("Starting Simulation"); Module_Simulation* sim = new Module_Simulation("simulation"); this->modules.append(sim); Module_UID* uid = new Module_UID("uid"); this->modules.append(uid); Module_Thruster* thrusterRight = new Module_Thruster("thrusterRight",uid,sim); this->modules.append(thrusterRight); Module_Thruster* thrusterLeft = new Module_Thruster("thrusterLeft",uid,sim); this->modules.append(thrusterLeft); Module_Thruster* thrusterDown = new Module_Thruster("thrusterDown",uid,sim); this->modules.append(thrusterDown); Module_Thruster* thrusterDownF = new Module_Thruster("thrusterDownFront",uid,sim); this->modules.append(thrusterDownF); Module_PressureSensor* pressure = new Module_PressureSensor("pressure",uid,sim); this->modules.append(pressure); // Module_IMU* imu = new Module_IMU("adis",uid,sim); // this->modules.append(imu); Module_XsensMTi *xsens = new Module_XsensMTi("xsens", sim); this->modules.append(xsens); Module_ThrusterControlLoop* controlLoop = new Module_ThrusterControlLoop("controlLoop",pressure, thrusterLeft, thrusterRight, thrusterDown,thrusterDownF); this->modules.append(controlLoop); // Module_ADC* adc0 = new Module_ADC("adc0",uid); // this->modules.append(adc0); // Module_ADC* adc1 = new Module_ADC("adc1",uid); // this->modules.append(adc1); logger->debug("Creating Module_ScanningSonar"); Module_ScanningSonar* sonar = new Module_ScanningSonar("sonar", sim, xsens); this->modules.append(sonar); logger->debug("Creating Module_EchoSounder"); Module_EchoSounder* echo = new Module_EchoSounder("echo",sim); this->modules.append(echo); logger->debug("Creating Module_HandControl"); Module_HandControl* handControl = new Module_HandControl("handControl",controlLoop, thrusterLeft, thrusterRight, thrusterDown, thrusterDownF); this->modules.append(handControl); logger->debug("Creating Module_Webcams"); Module_Webcams *cams = new Module_Webcams( "cams" ); this->modules.append( cams ); logger->debug("Creating Module_SonarLocalization"); Module_SonarLocalization* sonarLoc = new Module_SonarLocalization("sonarLocalize", sonar, xsens, sim); this->modules.append(sonarLoc); logger->debug("Creating Module_Navigation"); Module_Navigation* navi = new Module_Navigation( "navigation", sonarLoc, controlLoop, pressure, xsens ); this->modules.append(navi); logger->debug("Creating Behaviour_PipeFollowing"); Behaviour_PipeFollowing* behavPipe = new Behaviour_PipeFollowing("pipe",controlLoop,cams,sim); this->modules.append(behavPipe); // logger->debug("Creating Behaviour_GoalFollowing"); // Behaviour_GoalFollowing* behavGoal = new Behaviour_GoalFollowing("goal",controlLoop, visualLoc); // this->modules.append(behavGoal); logger->debug("Creating Behaviour_BallFollowing"); Behaviour_BallFollowing* behavBall = new Behaviour_BallFollowing("ball",controlLoop, cams, xsens); this->modules.append(behavBall); logger->debug("Creating Behaviour_TurnOneEighty"); Behaviour_TurnOneEighty* behavTurn = new Behaviour_TurnOneEighty("turn",controlLoop, xsens); this->modules.append(behavTurn); logger->debug("Creating Behaviour_WallFollowing"); Behaviour_WallFollowing* behavWall = new Behaviour_WallFollowing("wall",controlLoop, echo, xsens); this->modules.append(behavWall); logger->debug("Creating Behaviour_XsensFollowing"); Behaviour_XsensFollowing* behavXsens = new Behaviour_XsensFollowing("xsensFollow",controlLoop, xsens); this->modules.append(behavXsens); logger->debug("Creating TaskWallNavigation"); TaskWallNavigation *taskwallnavigation = new TaskWallNavigation("taskWallNavi",sim, behavWall, navi); this->modules.append(taskwallnavigation); logger->debug("Creating TaskXsensNavigation"); TaskXsensNavigation *taskxsensnavigation = new TaskXsensNavigation("taskXsensNavi",sim, behavXsens, navi, behavTurn); this->modules.append(taskxsensnavigation); logger->debug("Creating TaskHandControl"); TaskHandControl *taskhandcontrol = new TaskHandControl("taskHand", controlLoop, sim, handControl); this->modules.append(taskhandcontrol); logger->debug("Creating CommandCenter"); CommandCenter* commCent = new CommandCenter("comandCenter", controlLoop, handControl, pressure, sim, navi, behavPipe, behavBall, behavTurn, behavWall, behavXsens, taskhandcontrol, taskwallnavigation, taskxsensnavigation); this->modules.append(commCent); logger->info("Loading all Modules... Done"); foreach (RobotModule* b, modules) { logger->debug("Starting module "+b->getId()); b->start(); b->waitForInitToComplete(); } } QList<RobotModule*> ModulesGraph::getModules() { return QList<RobotModule*>(modules); } void ModulesGraph::HastaLaVista() { logger->info("Terminating all modules..."); // go backwards through the module list for (int i = modules.size()-1; i>=0; i--) { logger->info("Terminating "+modules[i]->getId()); modules[i]->shutdown(); } logger->info("All modules terminated."); }
#include "modulesgraph.h" #include <Module_ScanningSonar/module_scanningsonar.h> #include <Module_UID/module_uid.h> #include <Module_Thruster/module_thruster.h> #include <Module_PressureSensor/module_pressuresensor.h> #include <Module_ThrusterControlLoop/module_thrustercontrolloop.h> #include <Module_HandControl/module_handcontrol.h> #include <Module_SonarLocalization/module_sonarlocalization.h> #include <Module_Navigation/module_navigation.h> #include <Behaviour_PipeFollowing/behaviour_pipefollowing.h> #include <Behaviour_BallFollowing/behaviour_ballfollowing.h> #include <Module_Webcams/module_webcams.h> #include <Behaviour_TurnOneEighty/behaviour_turnoneeighty.h> #include <Module_Simulation/module_simulation.h> #include <Module_EchoSounder/module_echosounder.h> #include <Module_XsensMTi/module_xsensmti.h> #include <Behaviour_WallFollowing/behaviour_wallfollowing.h> #include <CommandCenter/commandcenter.h> #include "SoToSleep.h" #include <TaskHandControl/taskhandcontrol.h> #include <TaskWallNavigation/taskwallnavigation.h> #include <Behaviour_XsensFollowing/behaviour_xsensfollowing.h> //#include <Module_IMU/module_imu.h> //#include <Module_ADC/module_adc.h> #include <TaskXsensNavigation/taskxsensnavigation.h> ModulesGraph::ModulesGraph() { logger = Log4Qt::Logger::logger("ModulesGraph"); } void ModulesGraph::build() { logger->info("Loading all Modules..."); // logger->debug("Starting Simulation"); Module_Simulation* sim = new Module_Simulation("simulation"); this->modules.append(sim); Module_UID* uid = new Module_UID("uid"); this->modules.append(uid); Module_Thruster* thrusterRight = new Module_Thruster("thrusterRight",uid,sim); this->modules.append(thrusterRight); Module_Thruster* thrusterLeft = new Module_Thruster("thrusterLeft",uid,sim); this->modules.append(thrusterLeft); Module_Thruster* thrusterDown = new Module_Thruster("thrusterDown",uid,sim); this->modules.append(thrusterDown); Module_Thruster* thrusterDownF = new Module_Thruster("thrusterDownFront",uid,sim); this->modules.append(thrusterDownF); Module_PressureSensor* pressure = new Module_PressureSensor("pressure",uid,sim); this->modules.append(pressure); // Module_IMU* imu = new Module_IMU("adis",uid,sim); // this->modules.append(imu); Module_XsensMTi *xsens = new Module_XsensMTi("xsens", sim); this->modules.append(xsens); Module_ThrusterControlLoop* controlLoop = new Module_ThrusterControlLoop("controlLoop",pressure, thrusterLeft, thrusterRight, thrusterDown,thrusterDownF); this->modules.append(controlLoop); // Module_ADC* adc0 = new Module_ADC("adc0",uid); // this->modules.append(adc0); // Module_ADC* adc1 = new Module_ADC("adc1",uid); // this->modules.append(adc1); logger->debug("Creating Module_ScanningSonar"); Module_ScanningSonar* sonar = new Module_ScanningSonar("sonar", sim, xsens); this->modules.append(sonar); logger->debug("Creating Module_EchoSounder"); Module_EchoSounder* echo = new Module_EchoSounder("echo",sim); this->modules.append(echo); logger->debug("Creating Module_HandControl"); Module_HandControl* handControl = new Module_HandControl("handControl",controlLoop, thrusterLeft, thrusterRight, thrusterDown, thrusterDownF); this->modules.append(handControl); logger->debug("Creating Module_Webcams"); Module_Webcams *cams = new Module_Webcams( "cams" ); this->modules.append( cams ); logger->debug("Creating Module_SonarLocalization"); Module_SonarLocalization* sonarLoc = new Module_SonarLocalization("sonarLocalize", sonar, xsens, sim); this->modules.append(sonarLoc); logger->debug("Creating Module_Navigation"); Module_Navigation* navi = new Module_Navigation( "navigation", sonarLoc, controlLoop, pressure, xsens ); this->modules.append(navi); logger->debug("Creating Behaviour_PipeFollowing"); Behaviour_PipeFollowing* behavPipe = new Behaviour_PipeFollowing("pipe",controlLoop,cams,sim); this->modules.append(behavPipe); logger->debug("Creating Behaviour_BallFollowing"); Behaviour_BallFollowing* behavBall = new Behaviour_BallFollowing("ball",controlLoop, cams, xsens); this->modules.append(behavBall); logger->debug("Creating Behaviour_TurnOneEighty"); Behaviour_TurnOneEighty* behavTurn = new Behaviour_TurnOneEighty("turn",controlLoop, xsens); this->modules.append(behavTurn); logger->debug("Creating Behaviour_WallFollowing"); Behaviour_WallFollowing* behavWall = new Behaviour_WallFollowing("wall",controlLoop, echo, xsens); this->modules.append(behavWall); logger->debug("Creating Behaviour_XsensFollowing"); Behaviour_XsensFollowing* behavXsens = new Behaviour_XsensFollowing("xsensFollow",controlLoop, xsens); this->modules.append(behavXsens); logger->debug("Creating TaskWallNavigation"); TaskWallNavigation *taskwallnavigation = new TaskWallNavigation("taskWallNavi",sim, behavWall, navi); this->modules.append(taskwallnavigation); logger->debug("Creating TaskXsensNavigation"); TaskXsensNavigation *taskxsensnavigation = new TaskXsensNavigation("taskXsensNavi",sim, behavXsens, navi, behavTurn); this->modules.append(taskxsensnavigation); logger->debug("Creating TaskHandControl"); TaskHandControl *taskhandcontrol = new TaskHandControl("taskHand", controlLoop, sim, handControl); this->modules.append(taskhandcontrol); logger->debug("Creating CommandCenter"); CommandCenter* commCent = new CommandCenter("comandCenter", controlLoop, handControl, pressure, sim, navi, behavPipe, behavBall, behavTurn, behavWall, behavXsens, taskhandcontrol, taskwallnavigation, taskxsensnavigation); this->modules.append(commCent); logger->info("Loading all Modules... Done"); foreach (RobotModule* b, modules) { logger->debug("Starting module "+b->getId()); b->start(); b->waitForInitToComplete(); } } QList<RobotModule*> ModulesGraph::getModules() { return QList<RobotModule*>(modules); } void ModulesGraph::HastaLaVista() { logger->info("Terminating all modules..."); // go backwards through the module list for (int i = modules.size()-1; i>=0; i--) { logger->info("Terminating "+modules[i]->getId()); modules[i]->shutdown(); } logger->info("All modules terminated."); }
remove old include
remove old include git-svn-id: 6b9f0500862a2a36993a1eeb0ace819d0f093cde@992 8f13a6d9-6203-4c43-9b9f-a3039379152f
C++
bsd-3-clause
iti-luebeck/HANSE2011,iti-luebeck/HANSE2011,iti-luebeck/HANSE2011,iti-luebeck/HANSE2011,iti-luebeck/HANSE2011,iti-luebeck/HANSE2011
0df05c9c30785821b67864401b57c49be5efc2e3
src/tightdb/lang_bind_helper.hpp
src/tightdb/lang_bind_helper.hpp
/************************************************************************* * * TIGHTDB CONFIDENTIAL * __________________ * * [2011] - [2012] TightDB Inc * All Rights Reserved. * * NOTICE: All information contained herein is, and remains * the property of TightDB Incorporated and its suppliers, * if any. The intellectual and technical concepts contained * herein are proprietary to TightDB Incorporated * and its suppliers and may be covered by U.S. and Foreign Patents, * patents in process, and are protected by trade secret or copyright law. * Dissemination of this information or reproduction of this material * is strictly forbidden unless prior written permission is obtained * from TightDB Incorporated. * **************************************************************************/ #ifndef TIGHTDB_LANG_BIND_HELPER_HPP #define TIGHTDB_LANG_BIND_HELPER_HPP #include <cstddef> #include <tightdb/table.hpp> #include <tightdb/table_view.hpp> #include <tightdb/group.hpp> namespace tightdb { /// These functions are only to be used by language bindings to gain /// access to certain memebers that are othewise private. /// /// \note Applications are not supposed to call any of these functions /// directly. /// /// All the get_*_ptr() functions as well as new_table() and /// copy_table() will return a pointer to a Table whose reference /// count has already been incremented. /// /// The application must make sure that the unbind_table_ref() function is /// called to decrement the reference count when it no longer needs /// access to that table. class LangBindHelper { public: /// Construct a new freestanding table. static Table* new_table(); /// Construct a new freestanding table as a copy of the specified /// one. static Table* copy_table(const Table&); static Table* get_subtable_ptr(Table*, std::size_t column_ndx, std::size_t row_ndx); static const Table* get_subtable_ptr(const Table*, std::size_t column_ndx, std::size_t row_ndx); // FIXME: This is an 'oddball', do we really need it? If we do, // please provide a comment that explains why it is needed! static Table* get_subtable_ptr_during_insert(Table*, std::size_t col_ndx, std::size_t row_ndx); static Table* get_subtable_ptr(TableView*, std::size_t column_ndx, std::size_t row_ndx); static const Table* get_subtable_ptr(const TableView*, std::size_t column_ndx, std::size_t row_ndx); static const Table* get_subtable_ptr(const ConstTableView*, std::size_t column_ndx, std::size_t row_ndx); static Table* get_table_ptr(Group* grp, StringData name); static Table* get_table_ptr(Group* grp, StringData name, bool& was_created); static const Table* get_table_ptr(const Group* grp, StringData name); static void unbind_table_ref(const Table*); static void bind_table_ref(const Table*) TIGHTDB_NOEXCEPT; /// Calls parent.insert_subtable(col_ndx, row_ndx, &source). Note /// that the source table must have a spec that is compatible with /// the target subtable column. static void insert_subtable(Table& parent, std::size_t col_ndx, std::size_t row_ndx, const Table& source); /// Calls parent.insert_mixed_subtable(col_ndx, row_ndx, &source). static void insert_mixed_subtable(Table& parent, std::size_t col_ndx, std::size_t row_ndx, const Table& source); /// Calls parent.set_mixed_subtable(col_ndx, row_ndx, &source). static void set_mixed_subtable(Table& parent, std::size_t col_ndx, std::size_t row_ndx, const Table& source); /// This is an alternative to Table::get_spec() that may be /// legally called even for a table with shared spec. It is then /// the responsibility of the language binding to ensure that /// modification is only done through it when it is not shared. static Spec& get_spec(Table&) TIGHTDB_NOEXCEPT; /// Returns the name of the specified data type as follows: /// /// <pre> /// /// type_Int -> "int" /// type_Bool -> "bool" /// type_Float -> "float" /// type_Double -> "double" /// type_String -> "string" /// type_Binary -> "binary" /// type_DateTime -> "date" /// type_Table -> "table" /// type_Mixed -> "mixed" /// /// </pre> static const char* get_data_type_name(DataType) TIGHTDB_NOEXCEPT; }; // Implementation: inline Table* LangBindHelper::new_table() { Allocator& alloc = Allocator::get_default(); std::size_t ref = Table::create_empty_table(alloc); // Throws Table* const table = new Table(Table::ref_count_tag(), alloc, ref, 0, 0); // Throws table->bind_ref(); return table; } inline Table* LangBindHelper::copy_table(const Table& t) { Allocator& alloc = Allocator::get_default(); std::size_t ref = t.clone(alloc); // Throws Table* const table = new Table(Table::ref_count_tag(), alloc, ref, 0, 0); // Throws table->bind_ref(); return table; } inline Table* LangBindHelper::get_subtable_ptr(Table* t, std::size_t column_ndx, std::size_t row_ndx) { Table* subtab = t->get_subtable_ptr(column_ndx, row_ndx); subtab->bind_ref(); return subtab; } inline const Table* LangBindHelper::get_subtable_ptr(const Table* t, std::size_t column_ndx, std::size_t row_ndx) { const Table* subtab = t->get_subtable_ptr(column_ndx, row_ndx); subtab->bind_ref(); return subtab; } inline Table* LangBindHelper::get_subtable_ptr(TableView* tv, std::size_t column_ndx, std::size_t row_ndx) { return get_subtable_ptr(&tv->get_parent(), column_ndx, tv->get_source_ndx(row_ndx)); } inline const Table* LangBindHelper::get_subtable_ptr(const TableView* tv, std::size_t column_ndx, std::size_t row_ndx) { return get_subtable_ptr(&tv->get_parent(), column_ndx, tv->get_source_ndx(row_ndx)); } inline const Table* LangBindHelper::get_subtable_ptr(const ConstTableView* tv, std::size_t column_ndx, std::size_t row_ndx) { return get_subtable_ptr(&tv->get_parent(), column_ndx, tv->get_source_ndx(row_ndx)); } inline Table* LangBindHelper::get_table_ptr(Group* grp, StringData name) { Table* subtab = grp->get_table_ptr(name); subtab->bind_ref(); return subtab; } inline Table* LangBindHelper::get_table_ptr(Group* grp, StringData name, bool& was_created) { Group::SpecSetter spec_setter = 0; // Do not add any columns Table* subtab = grp->get_table_ptr(name, spec_setter, was_created); subtab->bind_ref(); return subtab; } inline const Table* LangBindHelper::get_table_ptr(const Group* grp, StringData name) { const Table* subtab = grp->get_table_ptr(name); subtab->bind_ref(); return subtab; } inline void LangBindHelper::unbind_table_ref(const Table* t) { t->unbind_ref(); } inline void LangBindHelper::bind_table_ref(const Table* t) TIGHTDB_NOEXCEPT { t->bind_ref(); } inline void LangBindHelper::insert_subtable(Table& parent, std::size_t col_ndx, std::size_t row_ndx, const Table& source) { parent.insert_subtable(col_ndx, row_ndx, &source); } inline void LangBindHelper::insert_mixed_subtable(Table& parent, std::size_t col_ndx, std::size_t row_ndx, const Table& source) { parent.insert_mixed_subtable(col_ndx, row_ndx, &source); } inline void LangBindHelper::set_mixed_subtable(Table& parent, std::size_t col_ndx, std::size_t row_ndx, const Table& source) { parent.set_mixed_subtable(col_ndx, row_ndx, &source); } inline Spec& LangBindHelper::get_spec(Table& t) TIGHTDB_NOEXCEPT { return t.m_spec; } } // namespace tightdb #endif // TIGHTDB_LANG_BIND_HELPER_HPP
/************************************************************************* * * TIGHTDB CONFIDENTIAL * __________________ * * [2011] - [2012] TightDB Inc * All Rights Reserved. * * NOTICE: All information contained herein is, and remains * the property of TightDB Incorporated and its suppliers, * if any. The intellectual and technical concepts contained * herein are proprietary to TightDB Incorporated * and its suppliers and may be covered by U.S. and Foreign Patents, * patents in process, and are protected by trade secret or copyright law. * Dissemination of this information or reproduction of this material * is strictly forbidden unless prior written permission is obtained * from TightDB Incorporated. * **************************************************************************/ #ifndef TIGHTDB_LANG_BIND_HELPER_HPP #define TIGHTDB_LANG_BIND_HELPER_HPP #include <cstddef> #include <tightdb/table.hpp> #include <tightdb/table_view.hpp> #include <tightdb/group.hpp> namespace tightdb { /// These functions are only to be used by language bindings to gain /// access to certain memebers that are othewise private. /// /// \note Applications are not supposed to call any of these functions /// directly. /// /// All the get_*_ptr() functions as well as new_table() and /// copy_table() will return a pointer to a Table whose reference /// count has already been incremented. /// /// The application must make sure that the unbind_table_ref() function is /// called to decrement the reference count when it no longer needs /// access to that table. class LangBindHelper { public: /// Construct a new freestanding table. static Table* new_table(); /// Construct a new freestanding table as a copy of the specified /// one. static Table* copy_table(const Table&); static Table* get_subtable_ptr(Table*, std::size_t column_ndx, std::size_t row_ndx); static const Table* get_subtable_ptr(const Table*, std::size_t column_ndx, std::size_t row_ndx); // FIXME: This is an 'oddball', do we really need it? If we do, // please provide a comment that explains why it is needed! static Table* get_subtable_ptr_during_insert(Table*, std::size_t col_ndx, std::size_t row_ndx); static Table* get_subtable_ptr(TableView*, std::size_t column_ndx, std::size_t row_ndx); static const Table* get_subtable_ptr(const TableView*, std::size_t column_ndx, std::size_t row_ndx); static const Table* get_subtable_ptr(const ConstTableView*, std::size_t column_ndx, std::size_t row_ndx); static Table* get_table_ptr(Group* grp, StringData name); static Table* get_table_ptr(Group* grp, StringData name, bool& was_created); static const Table* get_table_ptr(const Group* grp, StringData name); static void unbind_table_ref(const Table*); static void bind_table_ref(const Table*) TIGHTDB_NOEXCEPT; /// Calls parent.insert_subtable(col_ndx, row_ndx, &source). Note /// that the source table must have a descriptor that is /// compatible with the target subtable column. static void insert_subtable(Table& parent, std::size_t col_ndx, std::size_t row_ndx, const Table& source); /// Calls parent.insert_mixed_subtable(col_ndx, row_ndx, &source). static void insert_mixed_subtable(Table& parent, std::size_t col_ndx, std::size_t row_ndx, const Table& source); /// Calls parent.set_mixed_subtable(col_ndx, row_ndx, &source). static void set_mixed_subtable(Table& parent, std::size_t col_ndx, std::size_t row_ndx, const Table& source); /// Returns the name of the specified data type as follows: /// /// <pre> /// /// type_Int -> "int" /// type_Bool -> "bool" /// type_Float -> "float" /// type_Double -> "double" /// type_String -> "string" /// type_Binary -> "binary" /// type_DateTime -> "date" /// type_Table -> "table" /// type_Mixed -> "mixed" /// /// </pre> static const char* get_data_type_name(DataType) TIGHTDB_NOEXCEPT; }; // Implementation: inline Table* LangBindHelper::new_table() { Allocator& alloc = Allocator::get_default(); std::size_t ref = Table::create_empty_table(alloc); // Throws Table* const table = new Table(Table::ref_count_tag(), alloc, ref, 0, 0); // Throws table->bind_ref(); return table; } inline Table* LangBindHelper::copy_table(const Table& t) { Allocator& alloc = Allocator::get_default(); std::size_t ref = t.clone(alloc); // Throws Table* const table = new Table(Table::ref_count_tag(), alloc, ref, 0, 0); // Throws table->bind_ref(); return table; } inline Table* LangBindHelper::get_subtable_ptr(Table* t, std::size_t column_ndx, std::size_t row_ndx) { Table* subtab = t->get_subtable_ptr(column_ndx, row_ndx); subtab->bind_ref(); return subtab; } inline const Table* LangBindHelper::get_subtable_ptr(const Table* t, std::size_t column_ndx, std::size_t row_ndx) { const Table* subtab = t->get_subtable_ptr(column_ndx, row_ndx); subtab->bind_ref(); return subtab; } inline Table* LangBindHelper::get_subtable_ptr(TableView* tv, std::size_t column_ndx, std::size_t row_ndx) { return get_subtable_ptr(&tv->get_parent(), column_ndx, tv->get_source_ndx(row_ndx)); } inline const Table* LangBindHelper::get_subtable_ptr(const TableView* tv, std::size_t column_ndx, std::size_t row_ndx) { return get_subtable_ptr(&tv->get_parent(), column_ndx, tv->get_source_ndx(row_ndx)); } inline const Table* LangBindHelper::get_subtable_ptr(const ConstTableView* tv, std::size_t column_ndx, std::size_t row_ndx) { return get_subtable_ptr(&tv->get_parent(), column_ndx, tv->get_source_ndx(row_ndx)); } inline Table* LangBindHelper::get_table_ptr(Group* grp, StringData name) { Table* subtab = grp->get_table_ptr(name); subtab->bind_ref(); return subtab; } inline Table* LangBindHelper::get_table_ptr(Group* grp, StringData name, bool& was_created) { Group::SpecSetter spec_setter = 0; // Do not add any columns Table* subtab = grp->get_table_ptr(name, spec_setter, was_created); subtab->bind_ref(); return subtab; } inline const Table* LangBindHelper::get_table_ptr(const Group* grp, StringData name) { const Table* subtab = grp->get_table_ptr(name); subtab->bind_ref(); return subtab; } inline void LangBindHelper::unbind_table_ref(const Table* t) { t->unbind_ref(); } inline void LangBindHelper::bind_table_ref(const Table* t) TIGHTDB_NOEXCEPT { t->bind_ref(); } inline void LangBindHelper::insert_subtable(Table& parent, std::size_t col_ndx, std::size_t row_ndx, const Table& source) { parent.insert_subtable(col_ndx, row_ndx, &source); } inline void LangBindHelper::insert_mixed_subtable(Table& parent, std::size_t col_ndx, std::size_t row_ndx, const Table& source) { parent.insert_mixed_subtable(col_ndx, row_ndx, &source); } inline void LangBindHelper::set_mixed_subtable(Table& parent, std::size_t col_ndx, std::size_t row_ndx, const Table& source) { parent.set_mixed_subtable(col_ndx, row_ndx, &source); } } // namespace tightdb #endif // TIGHTDB_LANG_BIND_HELPER_HPP
Remove obsolete LangBindHelper::get_spec()
Remove obsolete LangBindHelper::get_spec()
C++
apache-2.0
realm/realm-core,realm/realm-core,realm/realm-core,realm/realm-core,realm/realm-core,realm/realm-core,realm/realm-core
170cb260bc31dff1212df368170275072f26cf10
test/correctness/specialize.cpp
test/correctness/specialize.cpp
#include "Halide.h" #include <stdio.h> using namespace Halide; bool vector_store; bool scalar_store; void reset_trace() { vector_store = scalar_store = false; } // A trace that checks for vector and scalar stores int my_trace(void *user_context, const halide_trace_event *ev) { if (ev->event == halide_trace_store) { if (ev->vector_width > 1) { vector_store = true; } else { scalar_store = true; } } return 0; } // A custom allocator that counts how many allocations are for empty buffers. int empty_allocs = 0, nonempty_allocs = 0, frees = 0; void reset_alloc_counts() { empty_allocs = nonempty_allocs = frees = 0; } void *my_malloc(void *ctx, size_t sz) { // Don't worry about alignment because we'll just test this with scalar code if (sz == 0) { empty_allocs++; } else { nonempty_allocs++; } return malloc(sz); } void my_free(void *ctx, void *ptr) { frees++; free(ptr); } // Custom lowering pass to count the number of IfThenElse statements found inside // ProducerConsumer nodes. int if_then_else_count = 0; class CountIfThenElse : public Internal::IRMutator { int producer_consumers; public: CountIfThenElse() : producer_consumers(0) {} void visit(const Internal::ProducerConsumer *op) { // Only count ifs found inside a pipeline. producer_consumers++; IRMutator::visit(op); producer_consumers--; } void visit(const Internal::IfThenElse *op) { if (producer_consumers > 0) { if_then_else_count++; } Internal::IRMutator::visit(op); } using Internal::IRMutator::visit; }; int main(int argc, char **argv) { { Param<bool> param; Func f; Var x; f(x) = select(param, x*3, x*17); // Vectorize when the output is large enough Expr cond = (f.output_buffer().width() >= 4); f.specialize(cond).vectorize(x, 4); // This has created a specialization of f that is // vectorized. Now we want to further specialize both the // default case and the special case based on param. We can // retrieve a reference to the specialization using the same // condition again: f.specialize(cond).specialize(param); // Now specialize the narrow case on param as well f.specialize(param); f.set_custom_trace(&my_trace); f.trace_stores(); Image<int> out(100); // Just check that all the specialization didn't change the output. param.set(true); reset_trace(); f.realize(out); for (int i = 0; i < out.width(); i++) { int correct = i*3; if (out(i) != correct) { printf("out(%d) was %d instead of %d\n", i, out(i), correct); } } param.set(false); f.realize(out); for (int i = 0; i < out.width(); i++) { int correct = i*17; if (out(i) != correct) { printf("out(%d) was %d instead of %d\n", i, out(i), correct); } } // Should have used vector stores if (!vector_store || scalar_store) { printf("This was supposed to use vector stores\n"); return -1; } // Now try a smaller input out = Image<int>(3); param.set(true); reset_trace(); f.realize(out); for (int i = 0; i < out.width(); i++) { int correct = i*3; if (out(i) != correct) { printf("out(%d) was %d instead of %d\n", i, out(i), correct); } } param.set(false); f.realize(out); for (int i = 0; i < out.width(); i++) { int correct = i*17; if (out(i) != correct) { printf("out(%d) was %d instead of %d\n", i, out(i), correct); } } // Should have used scalar stores if (vector_store || !scalar_store) { printf("This was supposed to use scalar stores\n"); return -1; } } { Func f1, f2, g1, g2; Var x; // Define pipeline A f1(x) = x + 7; g1(x) = f1(x) + f1(x + 1); // Define pipeline B f2(x) = x * 34; g2(x) = f2(x) + f2(x - 1); // Switch between them based on a boolean param Param<bool> param; Func out; out(x) = select(param, g1(x), g2(x)); // These will be outside the condition that specializes out, // but skip stages will nuke their allocation and computation // for us. f1.compute_root(); g1.compute_root(); f2.compute_root(); out.specialize(param); // Count allocations. out.set_custom_allocator(&my_malloc, &my_free); reset_alloc_counts(); param.set(true); out.realize(100); if (empty_allocs != 1 || nonempty_allocs != 2 || frees != 3) { printf("There were supposed to be 1 empty alloc, 2 nonempty allocs, and 3 frees.\n" "Instead we got %d empty allocs, %d nonempty allocs, and %d frees.\n", empty_allocs, nonempty_allocs, frees); return -1; } reset_alloc_counts(); param.set(false); out.realize(100); if (empty_allocs != 2 || nonempty_allocs != 1 || frees != 3) { printf("There were supposed to be 2 empty allocs, 1 nonempty alloc, and 3 frees.\n" "Instead we got %d empty allocs, %d nonempty allocs, and %d frees.\n", empty_allocs, nonempty_allocs, frees); return -1; } } { // Specialize for interleaved vs planar inputs ImageParam im(Float(32), 1); im.set_stride(0, Expr()); // unconstrain the stride Func f; Var x; f(x) = im(x); // If we have a stride of 1 it's worth vectorizing, but only if the width is also > 8. f.specialize(im.stride(0) == 1 && im.width() >= 8).vectorize(x, 8); f.trace_stores(); f.set_custom_trace(&my_trace); // Check bounds inference is still cool with widths < 8 f.infer_input_bounds(5); int m = im.get().min(0), e = im.get().extent(0); if (m != 0 || e != 5) { printf("min, extent = %d, %d instead of 0, 5\n", m, e); return -1; } // Check we don't crash with the small input, and that it uses scalar stores reset_trace(); f.realize(5); if (!scalar_store || vector_store) { printf("These stores were supposed to be scalar.\n"); return -1; } // Check we don't crash with a larger input, and that it uses vector stores Image<float> image(100); im.set(image); reset_trace(); f.realize(100); if (scalar_store || !vector_store) { printf("These stores were supposed to be vector.\n"); return -1; } } { // Bounds required of the input change depending on the param ImageParam im(Float(32), 1); Param<bool> param; Func f; Var x; f(x) = select(param, im(x + 10), im(x - 10)); f.specialize(param); param.set(true); f.infer_input_bounds(100); int m = im.get().min(0); if (m != 10) { printf("min %d instead of 10\n", m); return -1; } param.set(false); im.set(Buffer()); f.infer_input_bounds(100); m = im.get().min(0); if (m != -10) { printf("min %d instead of -10\n", m); return -1; } } { // Specialize an update definition Func f; Var x; Param<int> start, size; RDom r(start, size); f(x) = x; f(r) = 10 - r; // Special-case for when we only update one element of f f.update().specialize(size == 1); // Also special-case updating no elements of f f.update().specialize(size == 0); start.set(0); size.set(1); // Not crashing is enough f.realize(100); } { // What happens to bounds inference if an input is not used at // all for a given specialization? ImageParam im(Float(32), 1); Param<bool> param; Func f; Var x; f(x) = select(param, im(x), 0.0f); f.specialize(param); param.set(false); Image<float> image(10); im.set(image); // The image is too small, but that should be OK, because the // param is false so the image will never be used. f.realize(100); } { // Specialization inherits the scheduling directives done so far: ImageParam im(Int(32), 2); Func f; Var x, y; f(x, y) = im(x, y); Expr cond = f.output_buffer().width() >= 4; // Unroll y by two innermost. f.reorder(y, x).unroll(y, 2).reorder(x, y); // Vectorize if the output is at least 4-wide. Inherits the // unrolling already done. f.specialize(cond).vectorize(x, 4); // Confirm that the unrolling applies to both cases using bounds inference: f.infer_input_bounds(3, 1); if (im.get().extent(0) != 3) { printf("extent(0) was supposed to be 3.\n"); return -1; } if (im.get().extent(1) != 2) { // Height is 2, because the unrolling also happens in the // specialized case. printf("extent(1) was supposed to be 2.\n"); return -1; } } { // Check we don't need to specialize intermediate stages. ImageParam im(Int(32), 1); Func f, g, h, out; Var x; f(x) = im(x); g(x) = f(x); h(x) = g(x); out(x) = h(x); Expr w = out.output_buffer().extent(0); out.output_buffer().set_min(0, 0); f.compute_root().specialize(w >= 4).vectorize(x, 4); g.compute_root().vectorize(x, 4); h.compute_root().vectorize(x, 4); out.specialize(w >= 4).vectorize(x, 4); Image<int> input(3), output(3); // Shouldn't throw a bounds error: im.set(input); out.realize(output); } { // Check specializations of stages nested in other stages simplify appropriately. ImageParam im(Int(32), 2); Param<bool> cond1, cond2; Func f, out; Var x, y; f(x, y) = im(x, y); out(x, y) = f(x, y); f.compute_at(out, x).specialize(cond1 && cond2).vectorize(x, 4); out.compute_root().specialize(cond1 && cond2).vectorize(x, 4); if_then_else_count = 0; CountIfThenElse pass1; for (auto ff : out.compile_to_module(out.infer_arguments()).functions) { pass1.mutate(ff.body); } Image<int> input(3, 3), output(3, 3); // Shouldn't throw a bounds error: im.set(input); out.realize(output); // The tail case of the vectorized for loop converts to a second if statement. if (if_then_else_count != 2) { printf("Expected 2 IfThenElse stmts. Found %d.\n", if_then_else_count); return -1; } } { // Check specializations of stages nested in other stages simplify appropriately. ImageParam im(Int(32), 2); Param<bool> cond1, cond2; Func f, out; Var x, y; f(x, y) = im(x, y); out(x, y) = f(x, y); f.compute_at(out, x).specialize(cond1).vectorize(x, 4); out.compute_root().specialize(cond1 && cond2).vectorize(x, 4); if_then_else_count = 0; CountIfThenElse pass2; for (auto ff : out.compile_to_module(out.infer_arguments()).functions) { pass2.mutate(ff.body); } Image<int> input(3, 3), output(3, 3); // Shouldn't throw a bounds error: im.set(input); out.realize(output); // There should have been 3 Ifs total: The first two are the // outer cond1 && cond2, and the condition in the true case // should have been simplified away. The If in the false // branch cannot be simplified. The tail case of the // vectorized for loop converts to a third if statement. if (if_then_else_count != 3) { printf("Expected 3 IfThenElse stmts. Found %d.\n", if_then_else_count); return -1; } } printf("Success!\n"); return 0; }
#include "Halide.h" #include <stdio.h> using namespace Halide; bool vector_store; bool scalar_store; void reset_trace() { vector_store = scalar_store = false; } // A trace that checks for vector and scalar stores int my_trace(void *user_context, const halide_trace_event *ev) { if (ev->event == halide_trace_store) { if (ev->vector_width > 1) { vector_store = true; } else { scalar_store = true; } } return 0; } // A custom allocator that counts how many allocations are for empty buffers. int empty_allocs = 0, nonempty_allocs = 0, frees = 0; void reset_alloc_counts() { empty_allocs = nonempty_allocs = frees = 0; } void *my_malloc(void *ctx, size_t sz) { // Don't worry about alignment because we'll just test this with scalar code if (sz == 0) { empty_allocs++; } else { nonempty_allocs++; } return malloc(sz); } void my_free(void *ctx, void *ptr) { frees++; free(ptr); } // Custom lowering pass to count the number of IfThenElse statements found inside // ProducerConsumer nodes. int if_then_else_count = 0; class CountIfThenElse : public Internal::IRMutator { int producer_consumers; public: CountIfThenElse() : producer_consumers(0) {} void visit(const Internal::ProducerConsumer *op) { // Only count ifs found inside a pipeline. producer_consumers++; IRMutator::visit(op); producer_consumers--; } void visit(const Internal::IfThenElse *op) { if (producer_consumers > 0) { if_then_else_count++; } Internal::IRMutator::visit(op); } using Internal::IRMutator::visit; }; int main(int argc, char **argv) { { Param<bool> param; Func f; Var x; f(x) = select(param, x*3, x*17); // Vectorize when the output is large enough Expr cond = (f.output_buffer().width() >= 4); f.specialize(cond).vectorize(x, 4); // This has created a specialization of f that is // vectorized. Now we want to further specialize both the // default case and the special case based on param. We can // retrieve a reference to the specialization using the same // condition again: f.specialize(cond).specialize(param); // Now specialize the narrow case on param as well f.specialize(param); f.set_custom_trace(&my_trace); f.trace_stores(); Image<int> out(100); // Just check that all the specialization didn't change the output. param.set(true); reset_trace(); f.realize(out); for (int i = 0; i < out.width(); i++) { int correct = i*3; if (out(i) != correct) { printf("out(%d) was %d instead of %d\n", i, out(i), correct); } } param.set(false); f.realize(out); for (int i = 0; i < out.width(); i++) { int correct = i*17; if (out(i) != correct) { printf("out(%d) was %d instead of %d\n", i, out(i), correct); } } // Should have used vector stores if (!vector_store || scalar_store) { printf("This was supposed to use vector stores\n"); return -1; } // Now try a smaller input out = Image<int>(3); param.set(true); reset_trace(); f.realize(out); for (int i = 0; i < out.width(); i++) { int correct = i*3; if (out(i) != correct) { printf("out(%d) was %d instead of %d\n", i, out(i), correct); } } param.set(false); f.realize(out); for (int i = 0; i < out.width(); i++) { int correct = i*17; if (out(i) != correct) { printf("out(%d) was %d instead of %d\n", i, out(i), correct); } } // Should have used scalar stores if (vector_store || !scalar_store) { printf("This was supposed to use scalar stores\n"); return -1; } } { Func f1, f2, g1, g2; Var x; // Define pipeline A f1(x) = x + 7; g1(x) = f1(x) + f1(x + 1); // Define pipeline B f2(x) = x * 34; g2(x) = f2(x) + f2(x - 1); // Switch between them based on a boolean param Param<bool> param; Func out; out(x) = select(param, g1(x), g2(x)); // These will be outside the condition that specializes out, // but skip stages will nuke their allocation and computation // for us. f1.compute_root(); g1.compute_root(); f2.compute_root(); out.specialize(param); // Count allocations. out.set_custom_allocator(&my_malloc, &my_free); reset_alloc_counts(); param.set(true); out.realize(100); if (empty_allocs != 1 || nonempty_allocs != 2 || frees != 3) { printf("There were supposed to be 1 empty alloc, 2 nonempty allocs, and 3 frees.\n" "Instead we got %d empty allocs, %d nonempty allocs, and %d frees.\n", empty_allocs, nonempty_allocs, frees); return -1; } reset_alloc_counts(); param.set(false); out.realize(100); if (empty_allocs != 2 || nonempty_allocs != 1 || frees != 3) { printf("There were supposed to be 2 empty allocs, 1 nonempty alloc, and 3 frees.\n" "Instead we got %d empty allocs, %d nonempty allocs, and %d frees.\n", empty_allocs, nonempty_allocs, frees); return -1; } } { // Specialize for interleaved vs planar inputs ImageParam im(Float(32), 1); im.set_stride(0, Expr()); // unconstrain the stride Func f; Var x; f(x) = im(x); // If we have a stride of 1 it's worth vectorizing, but only if the width is also > 8. f.specialize(im.stride(0) == 1 && im.width() >= 8).vectorize(x, 8); f.trace_stores(); f.set_custom_trace(&my_trace); // Check bounds inference is still cool with widths < 8 f.infer_input_bounds(5); int m = im.get().min(0), e = im.get().extent(0); if (m != 0 || e != 5) { printf("min, extent = %d, %d instead of 0, 5\n", m, e); return -1; } // Check we don't crash with the small input, and that it uses scalar stores reset_trace(); f.realize(5); if (!scalar_store || vector_store) { printf("These stores were supposed to be scalar.\n"); return -1; } // Check we don't crash with a larger input, and that it uses vector stores Image<float> image(100); im.set(image); reset_trace(); f.realize(100); if (scalar_store || !vector_store) { printf("These stores were supposed to be vector.\n"); return -1; } } { // Bounds required of the input change depending on the param ImageParam im(Float(32), 1); Param<bool> param; Func f; Var x; f(x) = select(param, im(x + 10), im(x - 10)); f.specialize(param); param.set(true); f.infer_input_bounds(100); int m = im.get().min(0); if (m != 10) { printf("min %d instead of 10\n", m); return -1; } param.set(false); im.set(Buffer()); f.infer_input_bounds(100); m = im.get().min(0); if (m != -10) { printf("min %d instead of -10\n", m); return -1; } } { // Specialize an update definition Func f; Var x; Param<int> start, size; RDom r(start, size); f(x) = x; f(r) = 10 - r; // Special-case for when we only update one element of f f.update().specialize(size == 1); // Also special-case updating no elements of f f.update().specialize(size == 0); start.set(0); size.set(1); // Not crashing is enough f.realize(100); } { // What happens to bounds inference if an input is not used at // all for a given specialization? ImageParam im(Float(32), 1); Param<bool> param; Func f; Var x; f(x) = select(param, im(x), 0.0f); f.specialize(param); param.set(false); Image<float> image(10); im.set(image); // The image is too small, but that should be OK, because the // param is false so the image will never be used. f.realize(100); } { // Specialization inherits the scheduling directives done so far: ImageParam im(Int(32), 2); Func f; Var x, y; f(x, y) = im(x, y); Expr cond = f.output_buffer().width() >= 4; // Unroll y by two innermost. f.reorder(y, x).unroll(y, 2).reorder(x, y); // Vectorize if the output is at least 4-wide. Inherits the // unrolling already done. f.specialize(cond).vectorize(x, 4); // Confirm that the unrolling applies to both cases using bounds inference: f.infer_input_bounds(3, 1); if (im.get().extent(0) != 3) { printf("extent(0) was supposed to be 3.\n"); return -1; } if (im.get().extent(1) != 2) { // Height is 2, because the unrolling also happens in the // specialized case. printf("extent(1) was supposed to be 2.\n"); return -1; } } { // Check we don't need to specialize intermediate stages. ImageParam im(Int(32), 1); Func f, g, h, out; Var x; f(x) = im(x); g(x) = f(x); h(x) = g(x); out(x) = h(x); Expr w = out.output_buffer().extent(0); out.output_buffer().set_min(0, 0); f.compute_root().specialize(w >= 4).vectorize(x, 4); g.compute_root().vectorize(x, 4); h.compute_root().vectorize(x, 4); out.specialize(w >= 4).vectorize(x, 4); Image<int> input(3), output(3); // Shouldn't throw a bounds error: im.set(input); out.realize(output); } { // Check specializations of stages nested in other stages simplify appropriately. ImageParam im(Int(32), 2); Param<bool> cond1, cond2; Func f, out; Var x, y; f(x, y) = im(x, y); out(x, y) = f(x, y); f.compute_at(out, x).specialize(cond1 && cond2).vectorize(x, 4); out.compute_root().specialize(cond1 && cond2).vectorize(x, 4); if_then_else_count = 0; CountIfThenElse pass1; for (auto ff : out.compile_to_module(out.infer_arguments()).functions()) { pass1.mutate(ff.body); } Image<int> input(3, 3), output(3, 3); // Shouldn't throw a bounds error: im.set(input); out.realize(output); // The tail case of the vectorized for loop converts to a second if statement. if (if_then_else_count != 2) { printf("Expected 2 IfThenElse stmts. Found %d.\n", if_then_else_count); return -1; } } { // Check specializations of stages nested in other stages simplify appropriately. ImageParam im(Int(32), 2); Param<bool> cond1, cond2; Func f, out; Var x, y; f(x, y) = im(x, y); out(x, y) = f(x, y); f.compute_at(out, x).specialize(cond1).vectorize(x, 4); out.compute_root().specialize(cond1 && cond2).vectorize(x, 4); if_then_else_count = 0; CountIfThenElse pass2; for (auto ff : out.compile_to_module(out.infer_arguments()).functions()) { pass2.mutate(ff.body); } Image<int> input(3, 3), output(3, 3); // Shouldn't throw a bounds error: im.set(input); out.realize(output); // There should have been 3 Ifs total: The first two are the // outer cond1 && cond2, and the condition in the true case // should have been simplified away. The If in the false // branch cannot be simplified. The tail case of the // vectorized for loop converts to a third if statement. if (if_then_else_count != 3) { printf("Expected 3 IfThenElse stmts. Found %d.\n", if_then_else_count); return -1; } } printf("Success!\n"); return 0; }
Fix correctness_specialize
Fix correctness_specialize Former-commit-id: 834e8a2a64933e6cf1cc53df71343340e14a717f
C++
mit
darkbuck/Halide,Trass3r/Halide,darkbuck/Halide,darkbuck/Halide,darkbuck/Halide,darkbuck/Halide,Trass3r/Halide,Trass3r/Halide,darkbuck/Halide,Trass3r/Halide,darkbuck/Halide,Trass3r/Halide,Trass3r/Halide,Trass3r/Halide
d7e0f93f02545a84148c862cdfd6c538f2bc1d95
test/crush/stat_test_common.hpp
test/crush/stat_test_common.hpp
// Copyright (c) 2017 Advanced Micro Devices, Inc. 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. #ifndef STAT_TEST_COMMON_H_ #define STAT_TEST_COMMON_H_ #include <iostream> #include <iomanip> #include <fstream> #include <vector> #include <string> #include <numeric> #include <utility> #include <algorithm> extern "C" { #include "gofs.h" #include "fdist.h" #include "fbar.h" #include "finv.h" } using distribution_func_type = std::function<double(double)>; template<typename T> double get_mean(const T * values, const size_t size) { double mean = 0.0f; for (size_t i = 0; i < size; i++) { mean += static_cast<double>(values[i]); } return mean / size; } template<typename T> double get_stddev(const T * values, const size_t size, double mean) { double variance = 0.0f; for (size_t i = 0; i < size; i++) { const double x = static_cast<double>(values[i]) - mean; variance += x * x; } return std::sqrt(variance / size); } template<typename T> void save_points_plots(const size_t size, const size_t level1_tests, const T * data, const std::string plot_name) { for (size_t level1_test = 0; level1_test < level1_tests; level1_test++) { std::ofstream fout; fout.open(plot_name + "-" + std::to_string(level1_test) + ".plot", std::ios_base::out | std::ios_base::trunc); fout << "set size square" << std::endl; if (std::is_integral<T>::value) { fout << "plot '-' with points pointtype 7 pointsize 0.15 notitle" << std::endl; const size_t x_offset = level1_test * size; const size_t y_offset = ((level1_test + 1 + level1_tests) % level1_tests) * size; for (size_t si = 0; si < size; si++) { const double r = 0.25; const double a = 2.0 * M_PI * si / size; const double x = data[x_offset + si] + r * std::cos(a); const double y = data[y_offset + si] + r * std::sin(a); fout << x << '\t' << y << std::endl; } fout << "e" << std::endl; } else { fout << "plot '-' with points pointtype 7 pointsize 0.15 notitle" << std::endl; const size_t x_offset = level1_test * size; const size_t y_offset = ((level1_test + 1 + level1_tests) % level1_tests) * size; for (size_t si = 0; si < size; si++) { const double x = data[x_offset + si]; const double y = data[y_offset + si]; fout << x << '\t' << y << std::endl; } fout << "e" << std::endl; } fout << "pause mouse close" << std::endl; } } template<typename T> void analyze(const size_t size, const size_t level1_tests, const T * data, const bool save_plots, const std::string plot_name, const double mean, const double stddev, const distribution_func_type& distribution_func) { if (save_plots) { save_points_plots(size, level1_tests, data, plot_name); } const double alpha = 0.05; double start = (mean - 6.0 * stddev); if (std::is_integral<T>::value) { // Use integral values for discrete distributions (e.g. Poisson) start = std::floor(start); } struct test_param { std::string name; double rejection_criterion; std::vector<double> ps; double cell_width; std::vector<double> nb_exp; std::vector<double> xs; std::vector<int> merged_count; std::vector<long> loc; long smin; long smax; long nb_classes; }; const std::vector<size_t> max_cells_counts({ 1000, 100, 25 }); const size_t tests = max_cells_counts.size(); std::vector<test_param> ts(tests); for (size_t test = 0; test < tests; test++) { test_param& t = ts[test]; const size_t cells_count = max_cells_counts[test]; t.cell_width = 12.0 * stddev / cells_count; if (std::is_integral<T>::value) { // Use integral values for discrete distributions (e.g. Poisson) t.cell_width = std::ceil(t.cell_width); } t.nb_exp.resize(cells_count); t.xs.resize(cells_count); t.merged_count.resize(cells_count); t.loc.resize(cells_count); for (size_t ci = 0; ci < cells_count; ci++) { const double x0 = start + ci * t.cell_width; const double x1 = start + (ci + 1) * t.cell_width; const double expected = distribution_func(x1) - distribution_func(x0); t.nb_exp[ci] = expected * size; t.xs[ci] = x1; t.merged_count[ci] = 1; } t.smin = 0; t.smax = cells_count - 1; t.nb_classes = 0; // Merge classes (cells) with low probability to ensure that // the expected number of observation per class is at least 5 gofs_MinExpected = 5.0; gofs_MergeClasses(t.nb_exp.data(), t.loc.data(), &t.smin, &t.smax, &t.nb_classes); for (long s = 0; s < static_cast<long>(cells_count); s++) { const long j = t.loc[s]; if (j != s) { t.merged_count[j] += t.merged_count[s]; t.merged_count[s] = 0; } } // When the chi-squared statistic exceeds the critical value (rejection_criterion), // we reject the null hypothesis ("observed random values follow a specific distribution") // with alpha significance level. t.rejection_criterion = finv_ChiSquare2(static_cast<long>(t.nb_classes - 1), 1.0 - alpha); t.name = "P" + std::to_string(t.nb_classes); t.ps.resize(level1_tests); } const int w = 12; const int w0 = 4; // Header { std::cout << " "; std::cout << std::setw(w0) << "#"; std::cout << std::setw(w) << "mean"; std::cout << std::setw(w) << "stddev"; for (size_t test = 0; test < tests; test++) { const test_param& t = ts[test]; std::cout << std::setw(w) << t.name; std::cout << " "; std::cout << std::setw(w) << "p"; std::cout << " "; } std::cout << std::endl; std::cout << " "; std::cout << std::setw(w0) << ""; std::cout << std::setw(w) << std::fixed << std::setprecision(3) << mean; std::cout << std::setw(w) << std::fixed << std::setprecision(3) << stddev; for (size_t test = 0; test < tests; test++) { const test_param& t = ts[test]; std::cout << std::setw(w) << ("< " + std::to_string(static_cast<int>(t.rejection_criterion))); std::cout << " "; std::cout << std::setw(w) << ""; std::cout << " "; } std::cout << std::endl << std::endl; } for (size_t level1_test = 0; level1_test < level1_tests; level1_test++) { std::cout << " "; std::cout << std::setw(w0) << level1_test; const double test_mean = get_mean(&data[level1_test * size], size); const double test_stddev = get_stddev(&data[level1_test * size], size, test_mean); std::cout << std::setw(w) << std::fixed << std::setprecision(3) << test_mean; std::cout << std::setw(w) << std::fixed << std::setprecision(3) << test_stddev; for (size_t test = 0; test < tests; test++) { test_param& t = ts[test]; const size_t cells_count = max_cells_counts[test]; std::vector<long> count(cells_count, 0); for (size_t si = 0; si < size; si++) { const double v = data[level1_test * size + si]; const long cell = static_cast<long>((v - start) / t.cell_width); if (cell >= 0 && cell < static_cast<long>(cells_count)) { count[cell]++; } } for (long s = 0; s < static_cast<long>(cells_count); s++) { const long j = t.loc[s]; if (j != s) { count[j] += count[s]; count[s] = 0; } } const double chi_squared = gofs_Chi2(const_cast<double *>(t.nb_exp.data()), count.data(), t.smin, t.smax); const double p = 1.0 - fdist_ChiSquare2(static_cast<long>(t.nb_classes - 1), 15, chi_squared); t.ps[level1_test] = p; std::cout << std::setw(w) << std::fixed << std::setprecision(3) << chi_squared; std::cout << (chi_squared < t.rejection_criterion ? " " : "*"); std::cout << std::setw(w) << std::fixed << std::setprecision(3) << p; std::cout << (alpha < p ? " " : "*"); if (save_plots) { std::ofstream fout; fout.open(plot_name + "-" + std::to_string(level1_test) + "-" + t.name + ".plot", std::ios_base::out | std::ios_base::trunc); fout << "set arrow from " << mean << ", graph 0 to " << mean << ", graph 1 nohead lt 0 lc rgb 'blue'" << std::endl; fout << "set arrow from " << test_mean << ", graph 0 to " << test_mean << ", graph 1 nohead lt 0 lc rgb 'red'" << std::endl; fout << "plot '-' title 'observed' with fsteps, '-' title 'expected' with fsteps" << std::endl; for (long s = t.smin; s <= t.smax; s++) { if (t.nb_exp[s] > 0.0) { const double v = count[s] / static_cast<double>(size) / t.merged_count[s]; if (s == t.smin) fout << start << '\t' << v << std::endl; fout << t.xs[s] << '\t' << v << std::endl; if (s == t.smax) fout << (start + cells_count * t.cell_width) << '\t' << v << std::endl; } } fout << "e" << std::endl; for (long s = t.smin; s <= t.smax; s++) { if (t.nb_exp[s] > 0.0) { const double v = t.nb_exp[s] / static_cast<double>(size) / t.merged_count[s]; if (s == t.smin) fout << start << '\t' << v << std::endl; fout << t.xs[s] << '\t' << v << std::endl; if (s == t.smax) fout << (start + cells_count * t.cell_width) << '\t' << v << std::endl; } } fout << "e" << std::endl; fout << "pause mouse close" << std::endl; } } std::cout << std::endl; } std::cout << std::endl; { std::cout << " "; std::cout << std::setw(w0) << "AD"; std::cout << std::setw(w) << ""; std::cout << std::setw(w) << ""; for (size_t test = 0; test < tests; test++) { const test_param& t = ts[test]; std::vector<double> ps(t.ps.begin(), t.ps.end()); // Anderson-Darling test needs ordered values std::sort(ps.begin(), ps.end()); const int n = level1_tests; const double a = gofs_AndersonDarling(ps.data() - 1, n); const double p = 1.0 - fdist_AndersonDarling2(n, a); std::cout << std::setw(w) << std::fixed << std::setprecision(3) << a; std::cout << " "; std::cout << std::setw(w) << std::fixed << std::setprecision(3) << p; std::cout << (alpha < p && p < (1.0 - alpha) ? " " : "*"); } std::cout << std::endl; } std::cout << std::endl; } #endif // STAT_TEST_COMMON_H_
// Copyright (c) 2017 Advanced Micro Devices, Inc. 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. #ifndef STAT_TEST_COMMON_H_ #define STAT_TEST_COMMON_H_ #include <iostream> #include <iomanip> #include <fstream> #include <vector> #include <string> #include <numeric> #include <utility> #include <algorithm> extern "C" { #include "gofs.h" #include "fdist.h" #include "fbar.h" #include "finv.h" } using distribution_func_type = std::function<double(double)>; template<typename T> double get_mean(const T * values, const size_t size) { double mean = 0.0f; for (size_t i = 0; i < size; i++) { mean += static_cast<double>(values[i]); } return mean / size; } template<typename T> double get_stddev(const T * values, const size_t size, double mean) { double variance = 0.0f; for (size_t i = 0; i < size; i++) { const double x = static_cast<double>(values[i]) - mean; variance += x * x; } return std::sqrt(variance / size); } template<typename T> void save_points_plots(const size_t size, const size_t level1_tests, const T * data, const std::string plot_name) { for (size_t level1_test = 0; level1_test < level1_tests; level1_test++) { std::ofstream fout; fout.open(plot_name + "-" + std::to_string(level1_test) + ".plot", std::ios_base::out | std::ios_base::trunc); fout << "set size square" << std::endl; if (std::is_integral<T>::value) { fout << "plot '-' with points pointtype 7 pointsize 0.15 notitle" << std::endl; const size_t x_offset = level1_test * size; const size_t y_offset = ((level1_test + 1 + level1_tests) % level1_tests) * size; for (size_t si = 0; si < size; si++) { const double r = 0.25; const double a = 2.0 * M_PI * si / size; const double x = data[x_offset + si] + r * std::cos(a); const double y = data[y_offset + si] + r * std::sin(a); fout << x << '\t' << y << std::endl; } fout << "e" << std::endl; } else { fout << "plot '-' with points pointtype 7 pointsize 0.15 notitle" << std::endl; const size_t x_offset = level1_test * size; const size_t y_offset = ((level1_test + 1 + level1_tests) % level1_tests) * size; for (size_t si = 0; si < size; si++) { const double x = data[x_offset + si]; const double y = data[y_offset + si]; fout << x << '\t' << y << std::endl; } fout << "e" << std::endl; } fout << "pause mouse close" << std::endl; } } template<typename T> void analyze(const size_t size, const size_t level1_tests, const T * data, const bool save_plots, const std::string plot_name, const double mean, const double stddev, const distribution_func_type& distribution_func)__attribute__((cpu)) { if (save_plots) { save_points_plots(size, level1_tests, data, plot_name); } const double alpha = 0.05; double start = (mean - 6.0 * stddev); if (std::is_integral<T>::value) { // Use integral values for discrete distributions (e.g. Poisson) start = std::floor(start); } struct test_param { std::string name; double rejection_criterion; std::vector<double> ps; double cell_width; std::vector<double> nb_exp; std::vector<double> xs; std::vector<int> merged_count; std::vector<long> loc; long smin; long smax; long nb_classes; }; const std::vector<size_t> max_cells_counts({ 1000, 100, 25 }); const size_t tests = max_cells_counts.size(); std::vector<test_param> ts(tests); for (size_t test = 0; test < tests; test++) { test_param& t = ts[test]; const size_t cells_count = max_cells_counts[test]; t.cell_width = 12.0 * stddev / cells_count; if (std::is_integral<T>::value) { // Use integral values for discrete distributions (e.g. Poisson) t.cell_width = std::ceil(t.cell_width); } t.nb_exp.resize(cells_count); t.xs.resize(cells_count); t.merged_count.resize(cells_count); t.loc.resize(cells_count); for (size_t ci = 0; ci < cells_count; ci++) { const double x0 = start + ci * t.cell_width; const double x1 = start + (ci + 1) * t.cell_width; const double expected = distribution_func(x1) - distribution_func(x0); t.nb_exp[ci] = expected * size; t.xs[ci] = x1; t.merged_count[ci] = 1; } t.smin = 0; t.smax = cells_count - 1; t.nb_classes = 0; // Merge classes (cells) with low probability to ensure that // the expected number of observation per class is at least 5 gofs_MinExpected = 5.0; gofs_MergeClasses(t.nb_exp.data(), t.loc.data(), &t.smin, &t.smax, &t.nb_classes); for (long s = 0; s < static_cast<long>(cells_count); s++) { const long j = t.loc[s]; if (j != s) { t.merged_count[j] += t.merged_count[s]; t.merged_count[s] = 0; } } // When the chi-squared statistic exceeds the critical value (rejection_criterion), // we reject the null hypothesis ("observed random values follow a specific distribution") // with alpha significance level. t.rejection_criterion = finv_ChiSquare2(static_cast<long>(t.nb_classes - 1), 1.0 - alpha); t.name = "P" + std::to_string(t.nb_classes); t.ps.resize(level1_tests); } const int w = 12; const int w0 = 4; // Header { std::cout << " "; std::cout << std::setw(w0) << "#"; std::cout << std::setw(w) << "mean"; std::cout << std::setw(w) << "stddev"; for (size_t test = 0; test < tests; test++) { const test_param& t = ts[test]; std::cout << std::setw(w) << t.name; std::cout << " "; std::cout << std::setw(w) << "p"; std::cout << " "; } std::cout << std::endl; std::cout << " "; std::cout << std::setw(w0) << ""; std::cout << std::setw(w) << std::fixed << std::setprecision(3) << mean; std::cout << std::setw(w) << std::fixed << std::setprecision(3) << stddev; for (size_t test = 0; test < tests; test++) { const test_param& t = ts[test]; std::cout << std::setw(w) << ("< " + std::to_string(static_cast<int>(t.rejection_criterion))); std::cout << " "; std::cout << std::setw(w) << ""; std::cout << " "; } std::cout << std::endl << std::endl; } for (size_t level1_test = 0; level1_test < level1_tests; level1_test++) { std::cout << " "; std::cout << std::setw(w0) << level1_test; const double test_mean = get_mean(&data[level1_test * size], size); const double test_stddev = get_stddev(&data[level1_test * size], size, test_mean); std::cout << std::setw(w) << std::fixed << std::setprecision(3) << test_mean; std::cout << std::setw(w) << std::fixed << std::setprecision(3) << test_stddev; for (size_t test = 0; test < tests; test++) { test_param& t = ts[test]; const size_t cells_count = max_cells_counts[test]; std::vector<long> count(cells_count, 0); for (size_t si = 0; si < size; si++) { const double v = data[level1_test * size + si]; const long cell = static_cast<long>((v - start) / t.cell_width); if (cell >= 0 && cell < static_cast<long>(cells_count)) { count[cell]++; } } for (long s = 0; s < static_cast<long>(cells_count); s++) { const long j = t.loc[s]; if (j != s) { count[j] += count[s]; count[s] = 0; } } const double chi_squared = gofs_Chi2(const_cast<double *>(t.nb_exp.data()), count.data(), t.smin, t.smax); const double p = 1.0 - fdist_ChiSquare2(static_cast<long>(t.nb_classes - 1), 15, chi_squared); t.ps[level1_test] = p; std::cout << std::setw(w) << std::fixed << std::setprecision(3) << chi_squared; std::cout << (chi_squared < t.rejection_criterion ? " " : "*"); std::cout << std::setw(w) << std::fixed << std::setprecision(3) << p; std::cout << (alpha < p ? " " : "*"); if (save_plots) { std::ofstream fout; fout.open(plot_name + "-" + std::to_string(level1_test) + "-" + t.name + ".plot", std::ios_base::out | std::ios_base::trunc); fout << "set arrow from " << mean << ", graph 0 to " << mean << ", graph 1 nohead lt 0 lc rgb 'blue'" << std::endl; fout << "set arrow from " << test_mean << ", graph 0 to " << test_mean << ", graph 1 nohead lt 0 lc rgb 'red'" << std::endl; fout << "plot '-' title 'observed' with fsteps, '-' title 'expected' with fsteps" << std::endl; for (long s = t.smin; s <= t.smax; s++) { if (t.nb_exp[s] > 0.0) { const double v = count[s] / static_cast<double>(size) / t.merged_count[s]; if (s == t.smin) fout << start << '\t' << v << std::endl; fout << t.xs[s] << '\t' << v << std::endl; if (s == t.smax) fout << (start + cells_count * t.cell_width) << '\t' << v << std::endl; } } fout << "e" << std::endl; for (long s = t.smin; s <= t.smax; s++) { if (t.nb_exp[s] > 0.0) { const double v = t.nb_exp[s] / static_cast<double>(size) / t.merged_count[s]; if (s == t.smin) fout << start << '\t' << v << std::endl; fout << t.xs[s] << '\t' << v << std::endl; if (s == t.smax) fout << (start + cells_count * t.cell_width) << '\t' << v << std::endl; } } fout << "e" << std::endl; fout << "pause mouse close" << std::endl; } } std::cout << std::endl; } std::cout << std::endl; { std::cout << " "; std::cout << std::setw(w0) << "AD"; std::cout << std::setw(w) << ""; std::cout << std::setw(w) << ""; for (size_t test = 0; test < tests; test++) { const test_param& t = ts[test]; std::vector<double> ps(t.ps.begin(), t.ps.end()); // Anderson-Darling test needs ordered values std::sort(ps.begin(), ps.end()); const int n = level1_tests; const double a = gofs_AndersonDarling(ps.data() - 1, n); const double p = 1.0 - fdist_AndersonDarling2(n, a); std::cout << std::setw(w) << std::fixed << std::setprecision(3) << a; std::cout << " "; std::cout << std::setw(w) << std::fixed << std::setprecision(3) << p; std::cout << (alpha < p && p < (1.0 - alpha) ? " " : "*"); } std::cout << std::endl; } std::cout << std::endl; } #endif // STAT_TEST_COMMON_H_
fix for swdev-155298
fix for swdev-155298
C++
mit
ROCmSoftwarePlatform/rocRAND,ROCmSoftwarePlatform/rocRAND,ROCmSoftwarePlatform/rocRAND,ROCmSoftwarePlatform/rocRAND
648e7933a47655c55e1fe99efc11b00f410cbf54
IO/vtkMedicalImageProperties.cxx
IO/vtkMedicalImageProperties.cxx
/*========================================================================= Program: Visualization Toolkit Module: vtkMedicalImageProperties.cxx Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ #include "vtkMedicalImageProperties.h" #include "vtkObjectFactory.h" #include <vtksys/stl/string> #include <vtksys/stl/vector> //---------------------------------------------------------------------------- vtkCxxRevisionMacro(vtkMedicalImageProperties, "1.9"); vtkStandardNewMacro(vtkMedicalImageProperties); //---------------------------------------------------------------------------- class vtkMedicalImagePropertiesInternals { public: class WindowLevelPreset { public: double Window; double Level; vtksys_stl::string Comment; }; typedef vtkstd::vector<WindowLevelPreset> WindowLevelPresetPoolType; typedef vtkstd::vector<WindowLevelPreset>::iterator WindowLevelPresetPoolIterator; WindowLevelPresetPoolType WindowLevelPresetPool; }; //---------------------------------------------------------------------------- vtkMedicalImageProperties::vtkMedicalImageProperties() { this->Internals = new vtkMedicalImagePropertiesInternals; this->AcquisitionDate = NULL; this->AcquisitionTime = NULL; this->ConvolutionKernel = NULL; this->Exposure = NULL; this->ExposureTime = NULL; this->GantryTilt = NULL; this->ImageDate = NULL; this->ImageNumber = NULL; this->ImageTime = NULL; this->InstitutionName = NULL; this->KVP = NULL; this->ManufacturerModelName = NULL; this->Modality = NULL; this->PatientAge = NULL; this->PatientBirthDate = NULL; this->PatientID = NULL; this->PatientName = NULL; this->PatientSex = NULL; this->SeriesNumber = NULL; this->SliceThickness = NULL; this->StationName = NULL; this->StudyDescription = NULL; this->StudyID = NULL; this->XRayTubeCurrent = NULL; } //---------------------------------------------------------------------------- vtkMedicalImageProperties::~vtkMedicalImageProperties() { if (this->Internals) { delete this->Internals; this->Internals = NULL; } this->Clear(); } //---------------------------------------------------------------------------- void vtkMedicalImageProperties::Clear() { this->SetAcquisitionDate(NULL); this->SetAcquisitionTime(NULL); this->SetConvolutionKernel(NULL); this->SetExposure(NULL); this->SetExposureTime(NULL); this->SetGantryTilt(NULL); this->SetImageDate(NULL); this->SetImageNumber(NULL); this->SetImageTime(NULL); this->SetInstitutionName(NULL); this->SetKVP(NULL); this->SetManufacturerModelName(NULL); this->SetModality(NULL); this->SetPatientAge(NULL); this->SetPatientBirthDate(NULL); this->SetPatientID(NULL); this->SetPatientName(NULL); this->SetPatientSex(NULL); this->SetSeriesNumber(NULL); this->SetSliceThickness(NULL); this->SetStationName(NULL); this->SetStudyDescription(NULL); this->SetStudyID(NULL); this->SetXRayTubeCurrent(NULL); this->RemoveAllWindowLevelPresets(); } //---------------------------------------------------------------------------- void vtkMedicalImageProperties::DeepCopy(vtkMedicalImageProperties *p) { if (p == NULL) { return; } this->Clear(); this->SetAcquisitionDate(p->GetAcquisitionDate()); this->SetAcquisitionTime(p->GetAcquisitionTime()); this->SetConvolutionKernel(p->GetConvolutionKernel()); this->SetExposure(p->GetExposure()); this->SetExposureTime(p->GetExposureTime()); this->SetGantryTilt(p->GetGantryTilt()); this->SetImageDate(p->GetImageDate()); this->SetImageNumber(p->GetImageNumber()); this->SetImageTime(p->GetImageTime()); this->SetInstitutionName(p->GetInstitutionName()); this->SetKVP(p->GetKVP()); this->SetManufacturerModelName(p->GetManufacturerModelName()); this->SetModality(p->GetModality()); this->SetPatientAge(p->GetPatientAge()); this->SetPatientBirthDate(p->GetPatientBirthDate()); this->SetPatientID(p->GetPatientID()); this->SetPatientName(p->GetPatientName()); this->SetPatientSex(p->GetPatientSex()); this->SetSeriesNumber(p->GetSeriesNumber()); this->SetSliceThickness(p->GetSliceThickness()); this->SetStationName(p->GetStationName()); this->SetStudyDescription(p->GetStudyDescription()); this->SetStudyID(p->GetStudyID()); this->SetXRayTubeCurrent(p->GetXRayTubeCurrent()); int nb_presets = p->GetNumberOfWindowLevelPresets(); for (int i = 0; i < nb_presets; i++) { double w, l; p->GetNthWindowLevelPreset(i, &w, &l); this->AddWindowLevelPreset(w, l); this->SetNthWindowLevelPresetComment( this->GetNumberOfWindowLevelPresets() - 1, p->GetNthWindowLevelPresetComment(i)); } } //---------------------------------------------------------------------------- void vtkMedicalImageProperties::AddWindowLevelPreset( double w, double l) { if (!this->Internals || this->HasWindowLevelPreset(w, l)) { return; } vtkMedicalImagePropertiesInternals::WindowLevelPreset preset; preset.Window = w; preset.Level = l; this->Internals->WindowLevelPresetPool.push_back(preset); } //---------------------------------------------------------------------------- int vtkMedicalImageProperties::HasWindowLevelPreset(double w, double l) { if (this->Internals) { vtkMedicalImagePropertiesInternals::WindowLevelPresetPoolIterator it = this->Internals->WindowLevelPresetPool.begin(); vtkMedicalImagePropertiesInternals::WindowLevelPresetPoolIterator end = this->Internals->WindowLevelPresetPool.end(); for (; it != end; ++it) { if ((*it).Window == w && (*it).Level == l) { return 1; } } } return 0; } //---------------------------------------------------------------------------- void vtkMedicalImageProperties::RemoveWindowLevelPreset(double w, double l) { if (this->Internals) { vtkMedicalImagePropertiesInternals::WindowLevelPresetPoolIterator it = this->Internals->WindowLevelPresetPool.begin(); vtkMedicalImagePropertiesInternals::WindowLevelPresetPoolIterator end = this->Internals->WindowLevelPresetPool.end(); for (; it != end; ++it) { if ((*it).Window == w && (*it).Level == l) { this->Internals->WindowLevelPresetPool.erase(it); break; } } } } //---------------------------------------------------------------------------- void vtkMedicalImageProperties::RemoveAllWindowLevelPresets() { if (this->Internals) { this->Internals->WindowLevelPresetPool.clear(); } } //---------------------------------------------------------------------------- int vtkMedicalImageProperties::GetNumberOfWindowLevelPresets() { return this->Internals ? this->Internals->WindowLevelPresetPool.size() : 0; } //---------------------------------------------------------------------------- int vtkMedicalImageProperties::GetNthWindowLevelPreset( int idx, double *w, double *l) { if (this->Internals && idx >= 0 && idx < this->GetNumberOfWindowLevelPresets()) { *w = this->Internals->WindowLevelPresetPool[idx].Window; *l = this->Internals->WindowLevelPresetPool[idx].Level; return 1; } return 0; } //---------------------------------------------------------------------------- double* vtkMedicalImageProperties::GetNthWindowLevelPreset(int idx) { static double wl[2]; if (this->GetNthWindowLevelPreset(idx, wl, wl + 1)) { return wl; } return NULL; } //---------------------------------------------------------------------------- const char* vtkMedicalImageProperties::GetNthWindowLevelPresetComment( int idx) { if (this->Internals && idx >= 0 && idx < this->GetNumberOfWindowLevelPresets()) { return this->Internals->WindowLevelPresetPool[idx].Comment.c_str(); } return NULL; } //---------------------------------------------------------------------------- void vtkMedicalImageProperties::SetNthWindowLevelPresetComment( int idx, const char *comment) { if (this->Internals && idx >= 0 && idx < this->GetNumberOfWindowLevelPresets()) { this->Internals->WindowLevelPresetPool[idx].Comment = (comment ? comment : ""); } } //---------------------------------------------------------------------------- double vtkMedicalImageProperties::GetSliceThicknessAsDouble() { if (this->SliceThickness) { return atof(this->SliceThickness); } return 0; } //---------------------------------------------------------------------------- double vtkMedicalImageProperties::GetGantryTiltAsDouble() { if (this->GantryTilt) { return atof(this->GantryTilt); } return 0; } //---------------------------------------------------------------------------- int vtkMedicalImageProperties::GetDateAsFields(const char *date, int &year, int &month, int &day) { if( !date ) { return 0; } size_t len = strlen(date); if( len != 10 ) { return 0; } if( date[4] != '/' || date[7] != '/' ) { return 0; } if( sscanf(date, "%d/%d/%d", &year, &month, &day) != 3 ) { return 0; } return 1; } //---------------------------------------------------------------------------- int vtkMedicalImageProperties::GetPatientBirthDateYear() { const char *date = this->GetPatientBirthDate(); int year, month, day; vtkMedicalImageProperties::GetDateAsFields(date, year, month, day); return year; } //---------------------------------------------------------------------------- int vtkMedicalImageProperties::GetPatientBirthDateMonth() { const char *date = this->GetPatientBirthDate(); int year, month, day; vtkMedicalImageProperties::GetDateAsFields(date, year, month, day); return month; } //---------------------------------------------------------------------------- int vtkMedicalImageProperties::GetPatientBirthDateDay() { const char *date = this->GetPatientBirthDate(); int year, month, day; vtkMedicalImageProperties::GetDateAsFields(date, year, month, day); return day; } //---------------------------------------------------------------------------- int vtkMedicalImageProperties::GetAcquisitionDateYear() { const char *date = this->GetAcquisitionDate(); int year, month, day; vtkMedicalImageProperties::GetDateAsFields(date, year, month, day); return year; } //---------------------------------------------------------------------------- int vtkMedicalImageProperties::GetAcquisitionDateMonth() { const char *date = this->GetAcquisitionDate(); int year, month, day; vtkMedicalImageProperties::GetDateAsFields(date, year, month, day); return month; } //---------------------------------------------------------------------------- int vtkMedicalImageProperties::GetAcquisitionDateDay() { const char *date = this->GetAcquisitionDate(); int year, month, day; vtkMedicalImageProperties::GetDateAsFields(date, year, month, day); return day; } //---------------------------------------------------------------------------- int vtkMedicalImageProperties::GetImageDateYear() { const char *date = this->GetImageDate(); int year, month, day; vtkMedicalImageProperties::GetDateAsFields(date, year, month, day); return year; } //---------------------------------------------------------------------------- int vtkMedicalImageProperties::GetImageDateMonth() { const char *date = this->GetImageDate(); int year, month, day; vtkMedicalImageProperties::GetDateAsFields(date, year, month, day); return month; } //---------------------------------------------------------------------------- int vtkMedicalImageProperties::GetImageDateDay() { const char *date = this->GetImageDate(); int year, month, day; vtkMedicalImageProperties::GetDateAsFields(date, year, month, day); return day; } //---------------------------------------------------------------------------- void vtkMedicalImageProperties::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os, indent); os << "\n" << indent << "PatientName: "; if (this->PatientName) { os << this->PatientName; } os << "\n" << indent << "PatientID: "; if (this->PatientID) { os << this->PatientID; } os << "\n" << indent << "PatientAge: "; if (this->PatientAge) { os << this->PatientAge; } os << "\n" << indent << "PatientSex: "; if (this->PatientSex) { os << this->PatientSex; } os << "\n" << indent << "PatientBirthDate: "; if (this->PatientBirthDate) { os << this->PatientBirthDate; } os << "\n" << indent << "ImageDate: "; if (this->ImageDate) { os << this->ImageDate; } os << "\n" << indent << "ImageTime: "; if (this->ImageTime) { os << this->ImageTime; } os << "\n" << indent << "ImageNumber: "; if (this->ImageNumber) { os << this->ImageNumber; } os << "\n" << indent << "AcquisitionDate: "; if (this->AcquisitionDate) { os << this->AcquisitionDate; } os << "\n" << indent << "AcquisitionTime: "; if (this->AcquisitionTime) { os << this->AcquisitionTime; } os << "\n" << indent << "SeriesNumber: "; if (this->SeriesNumber) { os << this->SeriesNumber; } os << "\n" << indent << "StudyDescription: "; if (this->StudyDescription) { os << this->StudyDescription; } os << "\n" << indent << "StudyID: "; if (this->StudyID) { os << this->StudyID; } os << "\n" << indent << "Modality: "; if (this->Modality) { os << this->Modality; } os << "\n" << indent << "ManufacturerModelName: "; if (this->ManufacturerModelName) { os << this->ManufacturerModelName; } os << "\n" << indent << "StationName: "; if (this->StationName) { os << this->StationName; } os << "\n" << indent << "InstitutionName: "; if (this->InstitutionName) { os << this->InstitutionName; } os << "\n" << indent << "ConvolutionKernel: "; if (this->ConvolutionKernel) { os << this->ConvolutionKernel; } os << "\n" << indent << "SliceThickness: "; if (this->SliceThickness) { os << this->SliceThickness; } os << "\n" << indent << "KVP: "; if (this->KVP) { os << this->KVP; } os << "\n" << indent << "GantryTilt: "; if (this->GantryTilt) { os << this->GantryTilt; } os << "\n" << indent << "ExposureTime: "; if (this->ExposureTime) { os << this->ExposureTime; } os << "\n" << indent << "XRayTubeCurrent: "; if (this->XRayTubeCurrent) { os << this->XRayTubeCurrent; } os << "\n" << indent << "Exposure: "; if (this->Exposure) { os << this->Exposure; } }
/*========================================================================= Program: Visualization Toolkit Module: vtkMedicalImageProperties.cxx Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ #include "vtkMedicalImageProperties.h" #include "vtkObjectFactory.h" #include <vtksys/stl/string> #include <vtksys/stl/vector> //---------------------------------------------------------------------------- vtkCxxRevisionMacro(vtkMedicalImageProperties, "1.10"); vtkStandardNewMacro(vtkMedicalImageProperties); //---------------------------------------------------------------------------- class vtkMedicalImagePropertiesInternals { public: class WindowLevelPreset { public: double Window; double Level; vtksys_stl::string Comment; }; typedef vtkstd::vector<WindowLevelPreset> WindowLevelPresetPoolType; typedef vtkstd::vector<WindowLevelPreset>::iterator WindowLevelPresetPoolIterator; WindowLevelPresetPoolType WindowLevelPresetPool; }; //---------------------------------------------------------------------------- vtkMedicalImageProperties::vtkMedicalImageProperties() { this->Internals = new vtkMedicalImagePropertiesInternals; this->AcquisitionDate = NULL; this->AcquisitionTime = NULL; this->ConvolutionKernel = NULL; this->Exposure = NULL; this->ExposureTime = NULL; this->GantryTilt = NULL; this->ImageDate = NULL; this->ImageNumber = NULL; this->ImageTime = NULL; this->InstitutionName = NULL; this->KVP = NULL; this->ManufacturerModelName = NULL; this->Modality = NULL; this->PatientAge = NULL; this->PatientBirthDate = NULL; this->PatientID = NULL; this->PatientName = NULL; this->PatientSex = NULL; this->SeriesNumber = NULL; this->SliceThickness = NULL; this->StationName = NULL; this->StudyDescription = NULL; this->StudyID = NULL; this->XRayTubeCurrent = NULL; } //---------------------------------------------------------------------------- vtkMedicalImageProperties::~vtkMedicalImageProperties() { if (this->Internals) { delete this->Internals; this->Internals = NULL; } this->Clear(); } //---------------------------------------------------------------------------- void vtkMedicalImageProperties::Clear() { this->SetAcquisitionDate(NULL); this->SetAcquisitionTime(NULL); this->SetConvolutionKernel(NULL); this->SetExposure(NULL); this->SetExposureTime(NULL); this->SetGantryTilt(NULL); this->SetImageDate(NULL); this->SetImageNumber(NULL); this->SetImageTime(NULL); this->SetInstitutionName(NULL); this->SetKVP(NULL); this->SetManufacturerModelName(NULL); this->SetModality(NULL); this->SetPatientAge(NULL); this->SetPatientBirthDate(NULL); this->SetPatientID(NULL); this->SetPatientName(NULL); this->SetPatientSex(NULL); this->SetSeriesNumber(NULL); this->SetSliceThickness(NULL); this->SetStationName(NULL); this->SetStudyDescription(NULL); this->SetStudyID(NULL); this->SetXRayTubeCurrent(NULL); this->RemoveAllWindowLevelPresets(); } //---------------------------------------------------------------------------- void vtkMedicalImageProperties::DeepCopy(vtkMedicalImageProperties *p) { if (p == NULL) { return; } this->Clear(); this->SetAcquisitionDate(p->GetAcquisitionDate()); this->SetAcquisitionTime(p->GetAcquisitionTime()); this->SetConvolutionKernel(p->GetConvolutionKernel()); this->SetExposure(p->GetExposure()); this->SetExposureTime(p->GetExposureTime()); this->SetGantryTilt(p->GetGantryTilt()); this->SetImageDate(p->GetImageDate()); this->SetImageNumber(p->GetImageNumber()); this->SetImageTime(p->GetImageTime()); this->SetInstitutionName(p->GetInstitutionName()); this->SetKVP(p->GetKVP()); this->SetManufacturerModelName(p->GetManufacturerModelName()); this->SetModality(p->GetModality()); this->SetPatientAge(p->GetPatientAge()); this->SetPatientBirthDate(p->GetPatientBirthDate()); this->SetPatientID(p->GetPatientID()); this->SetPatientName(p->GetPatientName()); this->SetPatientSex(p->GetPatientSex()); this->SetSeriesNumber(p->GetSeriesNumber()); this->SetSliceThickness(p->GetSliceThickness()); this->SetStationName(p->GetStationName()); this->SetStudyDescription(p->GetStudyDescription()); this->SetStudyID(p->GetStudyID()); this->SetXRayTubeCurrent(p->GetXRayTubeCurrent()); int nb_presets = p->GetNumberOfWindowLevelPresets(); for (int i = 0; i < nb_presets; i++) { double w, l; p->GetNthWindowLevelPreset(i, &w, &l); this->AddWindowLevelPreset(w, l); this->SetNthWindowLevelPresetComment( this->GetNumberOfWindowLevelPresets() - 1, p->GetNthWindowLevelPresetComment(i)); } } //---------------------------------------------------------------------------- void vtkMedicalImageProperties::AddWindowLevelPreset( double w, double l) { if (!this->Internals || this->HasWindowLevelPreset(w, l)) { return; } vtkMedicalImagePropertiesInternals::WindowLevelPreset preset; preset.Window = w; preset.Level = l; this->Internals->WindowLevelPresetPool.push_back(preset); } //---------------------------------------------------------------------------- int vtkMedicalImageProperties::HasWindowLevelPreset(double w, double l) { if (this->Internals) { vtkMedicalImagePropertiesInternals::WindowLevelPresetPoolIterator it = this->Internals->WindowLevelPresetPool.begin(); vtkMedicalImagePropertiesInternals::WindowLevelPresetPoolIterator end = this->Internals->WindowLevelPresetPool.end(); for (; it != end; ++it) { if ((*it).Window == w && (*it).Level == l) { return 1; } } } return 0; } //---------------------------------------------------------------------------- void vtkMedicalImageProperties::RemoveWindowLevelPreset(double w, double l) { if (this->Internals) { vtkMedicalImagePropertiesInternals::WindowLevelPresetPoolIterator it = this->Internals->WindowLevelPresetPool.begin(); vtkMedicalImagePropertiesInternals::WindowLevelPresetPoolIterator end = this->Internals->WindowLevelPresetPool.end(); for (; it != end; ++it) { if ((*it).Window == w && (*it).Level == l) { this->Internals->WindowLevelPresetPool.erase(it); break; } } } } //---------------------------------------------------------------------------- void vtkMedicalImageProperties::RemoveAllWindowLevelPresets() { if (this->Internals) { this->Internals->WindowLevelPresetPool.clear(); } } //---------------------------------------------------------------------------- int vtkMedicalImageProperties::GetNumberOfWindowLevelPresets() { return this->Internals ? this->Internals->WindowLevelPresetPool.size() : 0; } //---------------------------------------------------------------------------- int vtkMedicalImageProperties::GetNthWindowLevelPreset( int idx, double *w, double *l) { if (this->Internals && idx >= 0 && idx < this->GetNumberOfWindowLevelPresets()) { *w = this->Internals->WindowLevelPresetPool[idx].Window; *l = this->Internals->WindowLevelPresetPool[idx].Level; return 1; } return 0; } //---------------------------------------------------------------------------- double* vtkMedicalImageProperties::GetNthWindowLevelPreset(int idx) { static double wl[2]; if (this->GetNthWindowLevelPreset(idx, wl, wl + 1)) { return wl; } return NULL; } //---------------------------------------------------------------------------- const char* vtkMedicalImageProperties::GetNthWindowLevelPresetComment( int idx) { if (this->Internals && idx >= 0 && idx < this->GetNumberOfWindowLevelPresets()) { return this->Internals->WindowLevelPresetPool[idx].Comment.c_str(); } return NULL; } //---------------------------------------------------------------------------- void vtkMedicalImageProperties::SetNthWindowLevelPresetComment( int idx, const char *comment) { if (this->Internals && idx >= 0 && idx < this->GetNumberOfWindowLevelPresets()) { this->Internals->WindowLevelPresetPool[idx].Comment = (comment ? comment : ""); } } //---------------------------------------------------------------------------- double vtkMedicalImageProperties::GetSliceThicknessAsDouble() { if (this->SliceThickness) { return atof(this->SliceThickness); } return 0; } //---------------------------------------------------------------------------- double vtkMedicalImageProperties::GetGantryTiltAsDouble() { if (this->GantryTilt) { return atof(this->GantryTilt); } return 0; } //---------------------------------------------------------------------------- int vtkMedicalImageProperties::GetDateAsFields(const char *date, int &year, int &month, int &day) { if( !date ) { return 0; } size_t len = strlen(date); if( len != 10 ) { return 0; } // DICOM V3 if( sscanf(date, "%d%d%d", &year, &month, &day) != 3 ) { // Some *very* old ACR-NEMA if( sscanf(date, "%d.%d.%d", &year, &month, &day) != 3 ) { return 0; } } return 1; } //---------------------------------------------------------------------------- int vtkMedicalImageProperties::GetPatientBirthDateYear() { const char *date = this->GetPatientBirthDate(); int year, month, day; vtkMedicalImageProperties::GetDateAsFields(date, year, month, day); return year; } //---------------------------------------------------------------------------- int vtkMedicalImageProperties::GetPatientBirthDateMonth() { const char *date = this->GetPatientBirthDate(); int year, month, day; vtkMedicalImageProperties::GetDateAsFields(date, year, month, day); return month; } //---------------------------------------------------------------------------- int vtkMedicalImageProperties::GetPatientBirthDateDay() { const char *date = this->GetPatientBirthDate(); int year, month, day; vtkMedicalImageProperties::GetDateAsFields(date, year, month, day); return day; } //---------------------------------------------------------------------------- int vtkMedicalImageProperties::GetAcquisitionDateYear() { const char *date = this->GetAcquisitionDate(); int year, month, day; vtkMedicalImageProperties::GetDateAsFields(date, year, month, day); return year; } //---------------------------------------------------------------------------- int vtkMedicalImageProperties::GetAcquisitionDateMonth() { const char *date = this->GetAcquisitionDate(); int year, month, day; vtkMedicalImageProperties::GetDateAsFields(date, year, month, day); return month; } //---------------------------------------------------------------------------- int vtkMedicalImageProperties::GetAcquisitionDateDay() { const char *date = this->GetAcquisitionDate(); int year, month, day; vtkMedicalImageProperties::GetDateAsFields(date, year, month, day); return day; } //---------------------------------------------------------------------------- int vtkMedicalImageProperties::GetImageDateYear() { const char *date = this->GetImageDate(); int year, month, day; vtkMedicalImageProperties::GetDateAsFields(date, year, month, day); return year; } //---------------------------------------------------------------------------- int vtkMedicalImageProperties::GetImageDateMonth() { const char *date = this->GetImageDate(); int year, month, day; vtkMedicalImageProperties::GetDateAsFields(date, year, month, day); return month; } //---------------------------------------------------------------------------- int vtkMedicalImageProperties::GetImageDateDay() { const char *date = this->GetImageDate(); int year, month, day; vtkMedicalImageProperties::GetDateAsFields(date, year, month, day); return day; } //---------------------------------------------------------------------------- void vtkMedicalImageProperties::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os, indent); os << "\n" << indent << "PatientName: "; if (this->PatientName) { os << this->PatientName; } os << "\n" << indent << "PatientID: "; if (this->PatientID) { os << this->PatientID; } os << "\n" << indent << "PatientAge: "; if (this->PatientAge) { os << this->PatientAge; } os << "\n" << indent << "PatientSex: "; if (this->PatientSex) { os << this->PatientSex; } os << "\n" << indent << "PatientBirthDate: "; if (this->PatientBirthDate) { os << this->PatientBirthDate; } os << "\n" << indent << "ImageDate: "; if (this->ImageDate) { os << this->ImageDate; } os << "\n" << indent << "ImageTime: "; if (this->ImageTime) { os << this->ImageTime; } os << "\n" << indent << "ImageNumber: "; if (this->ImageNumber) { os << this->ImageNumber; } os << "\n" << indent << "AcquisitionDate: "; if (this->AcquisitionDate) { os << this->AcquisitionDate; } os << "\n" << indent << "AcquisitionTime: "; if (this->AcquisitionTime) { os << this->AcquisitionTime; } os << "\n" << indent << "SeriesNumber: "; if (this->SeriesNumber) { os << this->SeriesNumber; } os << "\n" << indent << "StudyDescription: "; if (this->StudyDescription) { os << this->StudyDescription; } os << "\n" << indent << "StudyID: "; if (this->StudyID) { os << this->StudyID; } os << "\n" << indent << "Modality: "; if (this->Modality) { os << this->Modality; } os << "\n" << indent << "ManufacturerModelName: "; if (this->ManufacturerModelName) { os << this->ManufacturerModelName; } os << "\n" << indent << "StationName: "; if (this->StationName) { os << this->StationName; } os << "\n" << indent << "InstitutionName: "; if (this->InstitutionName) { os << this->InstitutionName; } os << "\n" << indent << "ConvolutionKernel: "; if (this->ConvolutionKernel) { os << this->ConvolutionKernel; } os << "\n" << indent << "SliceThickness: "; if (this->SliceThickness) { os << this->SliceThickness; } os << "\n" << indent << "KVP: "; if (this->KVP) { os << this->KVP; } os << "\n" << indent << "GantryTilt: "; if (this->GantryTilt) { os << this->GantryTilt; } os << "\n" << indent << "ExposureTime: "; if (this->ExposureTime) { os << this->ExposureTime; } os << "\n" << indent << "XRayTubeCurrent: "; if (this->XRayTubeCurrent) { os << this->XRayTubeCurrent; } os << "\n" << indent << "Exposure: "; if (this->Exposure) { os << this->Exposure; } }
Change format to the default DICOM or fallback to ACRNEMA convention
ENH: Change format to the default DICOM or fallback to ACRNEMA convention
C++
bsd-3-clause
sankhesh/VTK,johnkit/vtk-dev,jmerkow/VTK,cjh1/VTK,aashish24/VTK-old,candy7393/VTK,msmolens/VTK,ashray/VTK-EVM,collects/VTK,ashray/VTK-EVM,berendkleinhaneveld/VTK,berendkleinhaneveld/VTK,Wuteyan/VTK,msmolens/VTK,gram526/VTK,SimVascular/VTK,aashish24/VTK-old,Wuteyan/VTK,cjh1/VTK,daviddoria/PointGraphsPhase1,johnkit/vtk-dev,naucoin/VTKSlicerWidgets,sankhesh/VTK,ashray/VTK-EVM,msmolens/VTK,hendradarwin/VTK,hendradarwin/VTK,sumedhasingla/VTK,jmerkow/VTK,keithroe/vtkoptix,demarle/VTK,cjh1/VTK,sankhesh/VTK,collects/VTK,berendkleinhaneveld/VTK,gram526/VTK,naucoin/VTKSlicerWidgets,collects/VTK,gram526/VTK,hendradarwin/VTK,collects/VTK,mspark93/VTK,berendkleinhaneveld/VTK,cjh1/VTK,msmolens/VTK,SimVascular/VTK,jeffbaumes/jeffbaumes-vtk,jeffbaumes/jeffbaumes-vtk,daviddoria/PointGraphsPhase1,arnaudgelas/VTK,spthaolt/VTK,msmolens/VTK,jeffbaumes/jeffbaumes-vtk,demarle/VTK,gram526/VTK,biddisco/VTK,jeffbaumes/jeffbaumes-vtk,biddisco/VTK,hendradarwin/VTK,Wuteyan/VTK,gram526/VTK,spthaolt/VTK,biddisco/VTK,mspark93/VTK,berendkleinhaneveld/VTK,hendradarwin/VTK,johnkit/vtk-dev,biddisco/VTK,spthaolt/VTK,msmolens/VTK,mspark93/VTK,keithroe/vtkoptix,candy7393/VTK,naucoin/VTKSlicerWidgets,mspark93/VTK,naucoin/VTKSlicerWidgets,candy7393/VTK,mspark93/VTK,gram526/VTK,keithroe/vtkoptix,biddisco/VTK,sumedhasingla/VTK,naucoin/VTKSlicerWidgets,Wuteyan/VTK,sankhesh/VTK,collects/VTK,naucoin/VTKSlicerWidgets,msmolens/VTK,jmerkow/VTK,candy7393/VTK,spthaolt/VTK,SimVascular/VTK,cjh1/VTK,keithroe/vtkoptix,Wuteyan/VTK,daviddoria/PointGraphsPhase1,johnkit/vtk-dev,demarle/VTK,aashish24/VTK-old,biddisco/VTK,SimVascular/VTK,mspark93/VTK,SimVascular/VTK,daviddoria/PointGraphsPhase1,berendkleinhaneveld/VTK,sumedhasingla/VTK,keithroe/vtkoptix,hendradarwin/VTK,ashray/VTK-EVM,SimVascular/VTK,jeffbaumes/jeffbaumes-vtk,gram526/VTK,SimVascular/VTK,jeffbaumes/jeffbaumes-vtk,demarle/VTK,johnkit/vtk-dev,sumedhasingla/VTK,spthaolt/VTK,jmerkow/VTK,arnaudgelas/VTK,sankhesh/VTK,biddisco/VTK,ashray/VTK-EVM,demarle/VTK,demarle/VTK,jmerkow/VTK,msmolens/VTK,daviddoria/PointGraphsPhase1,hendradarwin/VTK,keithroe/vtkoptix,mspark93/VTK,aashish24/VTK-old,aashish24/VTK-old,johnkit/vtk-dev,mspark93/VTK,spthaolt/VTK,collects/VTK,jmerkow/VTK,spthaolt/VTK,ashray/VTK-EVM,aashish24/VTK-old,gram526/VTK,sumedhasingla/VTK,candy7393/VTK,demarle/VTK,berendkleinhaneveld/VTK,ashray/VTK-EVM,SimVascular/VTK,arnaudgelas/VTK,demarle/VTK,candy7393/VTK,sankhesh/VTK,Wuteyan/VTK,sankhesh/VTK,daviddoria/PointGraphsPhase1,ashray/VTK-EVM,keithroe/vtkoptix,arnaudgelas/VTK,johnkit/vtk-dev,Wuteyan/VTK,cjh1/VTK,sumedhasingla/VTK,candy7393/VTK,sumedhasingla/VTK,candy7393/VTK,jmerkow/VTK,sumedhasingla/VTK,keithroe/vtkoptix,sankhesh/VTK,jmerkow/VTK,arnaudgelas/VTK,arnaudgelas/VTK
79e274c507430ba12e8d3fba34e6133fdd0a2e5f
src/tvs/tracing/timed_stream.tpp
src/tvs/tracing/timed_stream.tpp
/* * Copyright (c) 2017 OFFIS Institute for Information Technology * Oldenburg, Germany * * 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. */ /** * \file timed_stream.tpp * \author Philipp A. Hartmann <[email protected]> * \brief timed value stream (template implementation) * \see timed_stream.h */ #include "tvs/tracing/timed_reader.h" #include "tvs/tracing/timed_stream.h" #include "tvs/tracing/timed_writer.h" #include "tvs/tracing/timed_stream_traits.h" #include "tvs/utils/unique_ptr.h" #include "tvs/utils/debug.h" #include "tvs/utils/macros.h" namespace tracing { template<typename T, typename Traits> void timed_stream<T, Traits>::merge_future(sequence_type&& other) { sequence_type& this_ = this->future_; if (other.empty()) return; if (this_.empty()) { this_.move_back(other); return; } sequence_type result; sequence_type *seq_a = &this_, *seq_b = &other; // iterate until one sequence is empty while (!seq_a->empty() && !seq_b->empty()) { // make sure seq_a points to the sequence with the longer front tuple if (seq_a->front_duration() < seq_b->front_duration()) std::swap(seq_a, seq_b); // split the front tuple of A seq_a->split(seq_b->front_duration()); tuple_type a_front = seq_a->front(); merge_policy::merge(a_front, seq_b->front()); result.push_back(a_front); seq_b->pop_front(); seq_a->pop_front(); } // handle leftover tuples in both sequences if (!seq_a->empty()) result.move_back(*seq_a); if (!seq_b->empty()) result.move_back(*seq_b); this_.clear(); this_.move_back(result); } /* -------------------------- push interface -------------------------- */ template<typename T, typename P> void timed_stream<T, P>::push(tuple_type const& t) { if (future_.empty()) { buf_.push_back(t); } else { // consume any future values caused by the local offset increment sequence_type tmp; tmp.push_back(t); merge_future(std::move(tmp)); auto merge_range = future_.range(t.duration()); SYSX_ASSERT(merge_range.duration() == t.duration()); buf_.push_back(merge_range.begin(), merge_range.end()); future_.pop_front(merge_range.duration()); } } template<typename T, typename P> void timed_stream<T, P>::push(value_type const& val) { tuple_type tup(val, duration_type::infinity()); if (future_.front().is_infinite()) { future_.front(tup); } else { // merge with existing future sequence sequence_type pushed; pushed.push_back(tup); merge_future(std::move(pushed)); } } template<typename T, typename P> void timed_stream<T, P>::push(time_type offset, tuple_type const& tuple) { sequence_type pushed; if (offset > duration_type::zero_time) pushed.push_back(empty_policy::empty(offset)); pushed.push_back(tuple); merge_future(std::move(pushed)); } /* ------------------------- commit interface ------------------------- */ template<typename T, typename P> void timed_stream<T, P>::do_pre_commit_reader(duration_type const& dur) { // check if we can just split inside existing buffer if (dur <= duration()) { buf_.split(dur); return; } // determine offset into future sequence duration_type fdur = dur - duration(); // extend if necessary if (fdur > future_.duration()) future_.push_back(empty_policy::empty(fdur - future_.duration())); future_.split(fdur); // append from future so we can satisfy the commit auto range = future_.range(fdur); buf_.push_back(range.begin(), range.end()); future_.pop_front(fdur); } template<typename T, typename P> void timed_stream<T, P>::do_commit_reader(timed_reader_base& r, duration_type const& dur, bool last) { typedef timed_reader<T, P> reader_type; reader_type& reader = static_cast<reader_type&>(r); bool new_window = reader.buf_.empty(); if (dur == duration()) { if (!last) { reader.buf_.push_back(buf_); } else { reader.buf_.move_back(buf_); } } else { // partially commit, buf_ has already been prepared auto range = buf_.range(dur); reader.buf_.push_back(range.begin(), range.end()); if (last) buf_.pop_front(dur); } reader.trigger(new_window); } template<typename T, typename Traits> void timed_stream<T, Traits>::print(std::ostream& os) const { os << "@" << this->local_time() << " : " << buf_ << "|" << future_ << "\n"; } } // namespace tracing /* Taf! */
/* * Copyright (c) 2017 OFFIS Institute for Information Technology * Oldenburg, Germany * * 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. */ /** * \file timed_stream.tpp * \author Philipp A. Hartmann <[email protected]> * \brief timed value stream (template implementation) * \see timed_stream.h */ #include "tvs/tracing/timed_reader.h" #include "tvs/tracing/timed_stream.h" #include "tvs/tracing/timed_writer.h" #include "tvs/tracing/timed_stream_traits.h" #include "tvs/utils/unique_ptr.h" #include "tvs/utils/debug.h" #include "tvs/utils/macros.h" namespace tracing { template<typename T, typename Traits> void timed_stream<T, Traits>::merge_future(sequence_type&& other) { sequence_type& this_ = this->future_; if (other.empty()) return; if (this_.empty()) { this_.move_back(other); return; } sequence_type result; sequence_type *seq_a = &this_, *seq_b = &other; // iterate until one sequence is empty while (!seq_a->empty() && !seq_b->empty()) { // make sure seq_a points to the sequence with the longer front tuple if (seq_a->front_duration() < seq_b->front_duration()) std::swap(seq_a, seq_b); // special case: handle 'split' at 0 if (seq_b->front_duration() == duration_type::zero_time) { tuple_type zero_front = seq_a->front(); zero_front.duration(duration_type::zero_time); seq_a->push_front(zero_front); } else { // split the front tuple of A seq_a->split(seq_b->front_duration()); } tuple_type a_front = seq_a->front(); merge_policy::merge(a_front, seq_b->front()); result.push_back(a_front); seq_b->pop_front(); seq_a->pop_front(); } // handle leftover tuples in both sequences if (!seq_a->empty()) result.move_back(*seq_a); if (!seq_b->empty()) result.move_back(*seq_b); this_.clear(); this_.move_back(result); } /* -------------------------- push interface -------------------------- */ template<typename T, typename P> void timed_stream<T, P>::push(tuple_type const& t) { if (future_.empty()) { buf_.push_back(t); } else { // consume any future values caused by the local offset increment sequence_type tmp; tmp.push_back(t); merge_future(std::move(tmp)); auto merge_range = future_.range(t.duration()); SYSX_ASSERT(merge_range.duration() == t.duration()); buf_.push_back(merge_range.begin(), merge_range.end()); future_.pop_front(merge_range.duration()); } } template<typename T, typename P> void timed_stream<T, P>::push(value_type const& val) { tuple_type tup(val, duration_type::infinity()); if (future_.front().is_infinite()) { future_.front(tup); } else { // merge with existing future sequence sequence_type pushed; pushed.push_back(tup); merge_future(std::move(pushed)); } } template<typename T, typename P> void timed_stream<T, P>::push(time_type offset, tuple_type const& tuple) { sequence_type pushed; if (offset > duration_type::zero_time) pushed.push_back(empty_policy::empty(offset)); pushed.push_back(tuple); merge_future(std::move(pushed)); } /* ------------------------- commit interface ------------------------- */ template<typename T, typename P> void timed_stream<T, P>::do_pre_commit_reader(duration_type const& dur) { // check if we can just split inside existing buffer if (dur <= duration()) { buf_.split(dur); return; } // determine offset into future sequence duration_type fdur = dur - duration(); // extend if necessary if (fdur > future_.duration()) future_.push_back(empty_policy::empty(fdur - future_.duration())); future_.split(fdur); // append from future so we can satisfy the commit auto range = future_.range(fdur); buf_.push_back(range.begin(), range.end()); future_.pop_front(fdur); } template<typename T, typename P> void timed_stream<T, P>::do_commit_reader(timed_reader_base& r, duration_type const& dur, bool last) { typedef timed_reader<T, P> reader_type; reader_type& reader = static_cast<reader_type&>(r); bool new_window = reader.buf_.empty(); if (dur == duration()) { if (!last) { reader.buf_.push_back(buf_); } else { reader.buf_.move_back(buf_); } } else { // partially commit, buf_ has already been prepared auto range = buf_.range(dur); reader.buf_.push_back(range.begin(), range.end()); if (last) buf_.pop_front(dur); } reader.trigger(new_window); } template<typename T, typename Traits> void timed_stream<T, Traits>::print(std::ostream& os) const { os << "@" << this->local_time() << " : " << buf_ << "|" << future_ << "\n"; } } // namespace tracing /* Taf! */
handle merges/splits with zero-time tuples
fix: handle merges/splits with zero-time tuples
C++
apache-2.0
offis/libtvs,offis/libtvs
20a155f5ab9f9021f04fc672ae44cd0845793371
lib/Transforms/Scalar/DCE.cpp
lib/Transforms/Scalar/DCE.cpp
//===- DCE.cpp - Code to perform dead code elimination --------------------===// // // This file implements dead code elimination and basic block merging. // // Specifically, this: // * removes definitions with no uses (including unused constants) // * removes basic blocks with no predecessors // * merges a basic block into its predecessor if there is only one and the // predecessor only has one successor. // * Eliminates PHI nodes for basic blocks with a single predecessor // * Eliminates a basic block that only contains an unconditional branch // // TODO: This should REALLY be worklist driven instead of iterative. Right now, // we scan linearly through values, removing unused ones as we go. The problem // is that this may cause other earlier values to become unused. To make sure // that we get them all, we iterate until things stop changing. Instead, when // removing a value, recheck all of its operands to see if they are now unused. // Piece of cake, and more efficient as well. // // Note, this is not trivial, because we have to worry about invalidating // iterators. :( // //===----------------------------------------------------------------------===// #include "llvm/Optimizations/DCE.h" #include "llvm/Tools/STLExtras.h" #include "llvm/Module.h" #include "llvm/Method.h" #include "llvm/BasicBlock.h" #include "llvm/iTerminators.h" #include "llvm/iOther.h" #include "llvm/Assembly/Writer.h" #include "llvm/CFG.h" #include <algorithm> using namespace cfg; struct ConstPoolDCE { enum { EndOffs = 0 }; static bool isDCEable(const ConstPoolVal *CPV) { // TODO: The bytecode writer requires that all used types are in the // constant pool for the current method. This is messy and is really // irritating. FIXME return CPV->getType() != Type::TypeTy; // Don't DCE Type plane constants! } }; struct BasicBlockDCE { enum { EndOffs = 1 }; static bool isDCEable(const Instruction *I) { return !I->hasSideEffects(); } }; template<class ValueSubclass, class ItemParentType, class DCEController> static bool RemoveUnusedDefs(ValueHolder<ValueSubclass, ItemParentType> &Vals, DCEController DCEControl) { bool Changed = false; typedef ValueHolder<ValueSubclass, ItemParentType> Container; int Offset = DCEController::EndOffs; for (Container::iterator DI = Vals.begin(); DI != Vals.end()-Offset; ) { // Look for un"used" definitions... if ((*DI)->use_empty() && DCEController::isDCEable(*DI)) { // Bye bye //cerr << "Removing: " << *DI; delete Vals.remove(DI); Changed = true; } else { ++DI; } } return Changed; } // RemoveSingularPHIs - This removes PHI nodes from basic blocks that have only // a single predecessor. This means that the PHI node must only have a single // RHS value and can be eliminated. // // This routine is very simple because we know that PHI nodes must be the first // things in a basic block, if they are present. // static bool RemoveSingularPHIs(BasicBlock *BB) { pred_iterator PI(pred_begin(BB)); if (PI == pred_end(BB) || ++PI != pred_end(BB)) return false; // More than one predecessor... Instruction *I = BB->front(); if (!I->isPHINode()) return false; // No PHI nodes //cerr << "Killing PHIs from " << BB; //cerr << "Pred #0 = " << *pred_begin(BB); //cerr << "Method == " << BB->getParent(); do { PHINode *PN = (PHINode*)I; assert(PN->getNumOperands() == 2 && "PHI node should only have one value!"); Value *V = PN->getOperand(0); PN->replaceAllUsesWith(V); // Replace PHI node with its single value. delete BB->getInstList().remove(BB->begin()); I = BB->front(); } while (I->isPHINode()); return true; // Yes, we nuked at least one phi node } bool opt::DoRemoveUnusedConstants(SymTabValue *S) { bool Changed = false; ConstantPool &CP = S->getConstantPool(); for (ConstantPool::plane_iterator PI = CP.begin(); PI != CP.end(); ++PI) Changed |= RemoveUnusedDefs(**PI, ConstPoolDCE()); return Changed; } static void ReplaceUsesWithConstant(Instruction *I) { // Get the method level constant pool ConstantPool &CP = I->getParent()->getParent()->getConstantPool(); ConstPoolVal *CPV = 0; ConstantPool::PlaneType *P; if (!CP.getPlane(I->getType(), P)) { // Does plane exist? // Yes, is it empty? if (!P->empty()) CPV = P->front(); } if (CPV == 0) { // We don't have an existing constant to reuse. Just add one. CPV = ConstPoolVal::getNullConstant(I->getType()); // Create a new constant // Add the new value to the constant pool... CP.insert(CPV); } // Make all users of this instruction reference the constant instead I->replaceAllUsesWith(CPV); } // PropogatePredecessors - This gets "Succ" ready to have the predecessors from // "BB". This is a little tricky because "Succ" has PHI nodes, which need to // have extra slots added to them to hold the merge edges from BB's // predecessors. // // Assumption: BB is the single predecessor of Succ. // static void PropogatePredecessorsForPHIs(BasicBlock *BB, BasicBlock *Succ) { assert(Succ->front()->isPHINode() && "Only works on PHId BBs!"); // If there is more than one predecessor, and there are PHI nodes in // the successor, then we need to add incoming edges for the PHI nodes // const vector<BasicBlock*> BBPreds(pred_begin(BB), pred_end(BB)); BasicBlock::iterator I = Succ->begin(); do { // Loop over all of the PHI nodes in the successor BB PHINode *PN = (PHINode*)*I; Value *OldVal = PN->removeIncomingValue(BB); assert(OldVal && "No entry in PHI for Pred BB!"); for (vector<BasicBlock*>::const_iterator PredI = BBPreds.begin(), End = BBPreds.end(); PredI != End; ++PredI) { // Add an incoming value for each of the new incoming values... PN->addIncoming(OldVal, *PredI); } ++I; } while ((*I)->isPHINode()); } // SimplifyCFG - This function is used to do simplification of a CFG. For // example, it adjusts branches to branches to eliminate the extra hop, it // eliminates unreachable basic blocks, and does other "peephole" optimization // of the CFG. It returns true if a modification was made, and returns an // iterator that designates the first element remaining after the block that // was deleted. // // WARNING: The entry node of a method may not be simplified. // bool opt::SimplifyCFG(Method::iterator &BBIt) { assert(*BBIt && (*BBIt)->getParent() && "Block not embedded in method!"); BasicBlock *BB = *BBIt; Method *M = BB->getParent(); assert(BB->getTerminator() && "Degenerate basic block encountered!"); assert(BB->getParent()->front() != BB && "Can't Simplify entry block!"); // Remove basic blocks that have no predecessors... which are unreachable. if (pred_begin(BB) == pred_end(BB) && !BB->hasConstantPoolReferences()) { //cerr << "Removing BB: \n" << BB; // Loop through all of our successors and make sure they know that one // of their predecessors is going away. for_each(succ_begin(BB), succ_end(BB), std::bind2nd(std::mem_fun(&BasicBlock::removePredecessor), BB)); while (!BB->empty()) { Instruction *I = BB->back(); // If this instruction is used, replace uses with an arbitrary // constant value. Because control flow can't get here, we don't care // what we replace the value with. Note that since this block is // unreachable, and all values contained within it must dominate their // uses, that all uses will eventually be removed. if (!I->use_empty()) ReplaceUsesWithConstant(I); // Remove the instruction from the basic block delete BB->getInstList().pop_back(); } delete M->getBasicBlocks().remove(BBIt); return true; } // Check to see if this block has no instructions and only a single // successor. If so, replace block references with successor. succ_iterator SI(succ_begin(BB)); if (SI != succ_end(BB) && ++SI == succ_end(BB)) { // One succ? Instruction *I = BB->front(); if (I->isTerminator()) { // Terminator is the only instruction! BasicBlock *Succ = *succ_begin(BB); // There is exactly one successor //cerr << "Killing Trivial BB: \n" << BB; if (Succ != BB) { // Arg, don't hurt infinite loops! if (Succ->front()->isPHINode()) { // If our successor has PHI nodes, then we need to update them to // include entries for BB's predecessors, not for BB itself. // PropogatePredecessorsForPHIs(BB, Succ); } BB->replaceAllUsesWith(Succ); BB = M->getBasicBlocks().remove(BBIt); if (BB->hasName() && !Succ->hasName()) // Transfer name if we can Succ->setName(BB->getName()); delete BB; // Delete basic block //cerr << "Method after removal: \n" << M; return true; } } } // Merge basic blocks into their predecessor if there is only one pred, // and if there is only one successor of the predecessor. pred_iterator PI(pred_begin(BB)); if (PI != pred_end(BB) && *PI != BB && // Not empty? Not same BB? ++PI == pred_end(BB) && !BB->hasConstantPoolReferences()) { BasicBlock *Pred = *pred_begin(BB); TerminatorInst *Term = Pred->getTerminator(); assert(Term != 0 && "malformed basic block without terminator!"); // Does the predecessor block only have a single successor? succ_iterator SI(succ_begin(Pred)); if (++SI == succ_end(Pred)) { //cerr << "Merging: " << BB << "into: " << Pred; // Delete the unconditianal branch from the predecessor... BasicBlock::iterator DI = Pred->end(); assert(Pred->getTerminator() && "Degenerate basic block encountered!"); // Empty bb??? delete Pred->getInstList().remove(--DI); // Destroy uncond branch // Move all definitions in the succecessor to the predecessor... while (!BB->empty()) { DI = BB->begin(); Instruction *Def = BB->getInstList().remove(DI); // Remove from front Pred->getInstList().push_back(Def); // Add to end... } // Remove basic block from the method... and advance iterator to the // next valid block... BB = M->getBasicBlocks().remove(BBIt); // Make all PHI nodes that refered to BB now refer to Pred as their // source... BB->replaceAllUsesWith(Pred); // Inherit predecessors name if it exists... if (BB->hasName() && !Pred->hasName()) Pred->setName(BB->getName()); delete BB; // You ARE the weakest link... goodbye return true; } } return false; } static bool DoDCEPass(Method *M) { Method::iterator BBIt, BBEnd = M->end(); if (M->begin() == BBEnd) return false; // Nothing to do bool Changed = false; // Loop through now and remove instructions that have no uses... for (BBIt = M->begin(); BBIt != BBEnd; ++BBIt) { Changed |= RemoveUnusedDefs((*BBIt)->getInstList(), BasicBlockDCE()); Changed |= RemoveSingularPHIs(*BBIt); } // Loop over all of the basic blocks (except the first one) and remove them // if they are unneeded... // for (BBIt = M->begin(), ++BBIt; BBIt != M->end(); ) { if (opt::SimplifyCFG(BBIt)) { Changed = true; } else { ++BBIt; } } // Remove unused constants return Changed | opt::DoRemoveUnusedConstants(M); } // It is possible that we may require multiple passes over the code to fully // eliminate dead code. Iterate until we are done. // bool opt::DoDeadCodeElimination(Method *M) { bool Changed = false; while (DoDCEPass(M)) Changed = true; return Changed; } bool opt::DoDeadCodeElimination(Module *C) { bool Val = C->reduceApply(DoDeadCodeElimination); while (DoRemoveUnusedConstants(C)) Val = true; return Val; }
//===- DCE.cpp - Code to perform dead code elimination --------------------===// // // This file implements dead code elimination and basic block merging. // // Specifically, this: // * removes definitions with no uses (including unused constants) // * removes basic blocks with no predecessors // * merges a basic block into its predecessor if there is only one and the // predecessor only has one successor. // * Eliminates PHI nodes for basic blocks with a single predecessor // * Eliminates a basic block that only contains an unconditional branch // // TODO: This should REALLY be worklist driven instead of iterative. Right now, // we scan linearly through values, removing unused ones as we go. The problem // is that this may cause other earlier values to become unused. To make sure // that we get them all, we iterate until things stop changing. Instead, when // removing a value, recheck all of its operands to see if they are now unused. // Piece of cake, and more efficient as well. // // Note, this is not trivial, because we have to worry about invalidating // iterators. :( // //===----------------------------------------------------------------------===// #include "llvm/Optimizations/DCE.h" #include "llvm/Tools/STLExtras.h" #include "llvm/Module.h" #include "llvm/Method.h" #include "llvm/BasicBlock.h" #include "llvm/iTerminators.h" #include "llvm/iOther.h" #include "llvm/Assembly/Writer.h" #include "llvm/CFG.h" #include <algorithm> using namespace cfg; struct ConstPoolDCE { enum { EndOffs = 0 }; static bool isDCEable(const ConstPoolVal *CPV) { // TODO: The bytecode writer requires that all used types are in the // constant pool for the current method. This is messy and is really // irritating. FIXME return CPV->getType() != Type::TypeTy; // Don't DCE Type plane constants! } }; struct BasicBlockDCE { enum { EndOffs = 1 }; static bool isDCEable(const Instruction *I) { return !I->hasSideEffects(); } }; template<class Container, class DCEController> static bool RemoveUnusedDefs(Container &Vals, DCEController DCEControl) { bool Changed = false; int Offset = DCEController::EndOffs; for (typename Container::iterator DI = Vals.begin(); DI != Vals.end()-Offset; ) { // Look for un"used" definitions... if ((*DI)->use_empty() && DCEController::isDCEable(*DI)) { // Bye bye //cerr << "Removing: " << *DI; delete Vals.remove(DI); Changed = true; } else { ++DI; } } return Changed; } // RemoveSingularPHIs - This removes PHI nodes from basic blocks that have only // a single predecessor. This means that the PHI node must only have a single // RHS value and can be eliminated. // // This routine is very simple because we know that PHI nodes must be the first // things in a basic block, if they are present. // static bool RemoveSingularPHIs(BasicBlock *BB) { pred_iterator PI(pred_begin(BB)); if (PI == pred_end(BB) || ++PI != pred_end(BB)) return false; // More than one predecessor... Instruction *I = BB->front(); if (!I->isPHINode()) return false; // No PHI nodes //cerr << "Killing PHIs from " << BB; //cerr << "Pred #0 = " << *pred_begin(BB); //cerr << "Method == " << BB->getParent(); do { PHINode *PN = (PHINode*)I; assert(PN->getNumOperands() == 2 && "PHI node should only have one value!"); Value *V = PN->getOperand(0); PN->replaceAllUsesWith(V); // Replace PHI node with its single value. delete BB->getInstList().remove(BB->begin()); I = BB->front(); } while (I->isPHINode()); return true; // Yes, we nuked at least one phi node } bool opt::DoRemoveUnusedConstants(SymTabValue *S) { bool Changed = false; ConstantPool &CP = S->getConstantPool(); for (ConstantPool::plane_iterator PI = CP.begin(); PI != CP.end(); ++PI) Changed |= RemoveUnusedDefs(**PI, ConstPoolDCE()); return Changed; } static void ReplaceUsesWithConstant(Instruction *I) { // Get the method level constant pool ConstantPool &CP = I->getParent()->getParent()->getConstantPool(); ConstPoolVal *CPV = 0; ConstantPool::PlaneType *P; if (!CP.getPlane(I->getType(), P)) { // Does plane exist? // Yes, is it empty? if (!P->empty()) CPV = P->front(); } if (CPV == 0) { // We don't have an existing constant to reuse. Just add one. CPV = ConstPoolVal::getNullConstant(I->getType()); // Create a new constant // Add the new value to the constant pool... CP.insert(CPV); } // Make all users of this instruction reference the constant instead I->replaceAllUsesWith(CPV); } // PropogatePredecessors - This gets "Succ" ready to have the predecessors from // "BB". This is a little tricky because "Succ" has PHI nodes, which need to // have extra slots added to them to hold the merge edges from BB's // predecessors. // // Assumption: BB is the single predecessor of Succ. // static void PropogatePredecessorsForPHIs(BasicBlock *BB, BasicBlock *Succ) { assert(Succ->front()->isPHINode() && "Only works on PHId BBs!"); // If there is more than one predecessor, and there are PHI nodes in // the successor, then we need to add incoming edges for the PHI nodes // const vector<BasicBlock*> BBPreds(pred_begin(BB), pred_end(BB)); BasicBlock::iterator I = Succ->begin(); do { // Loop over all of the PHI nodes in the successor BB PHINode *PN = (PHINode*)*I; Value *OldVal = PN->removeIncomingValue(BB); assert(OldVal && "No entry in PHI for Pred BB!"); for (vector<BasicBlock*>::const_iterator PredI = BBPreds.begin(), End = BBPreds.end(); PredI != End; ++PredI) { // Add an incoming value for each of the new incoming values... PN->addIncoming(OldVal, *PredI); } ++I; } while ((*I)->isPHINode()); } // SimplifyCFG - This function is used to do simplification of a CFG. For // example, it adjusts branches to branches to eliminate the extra hop, it // eliminates unreachable basic blocks, and does other "peephole" optimization // of the CFG. It returns true if a modification was made, and returns an // iterator that designates the first element remaining after the block that // was deleted. // // WARNING: The entry node of a method may not be simplified. // bool opt::SimplifyCFG(Method::iterator &BBIt) { assert(*BBIt && (*BBIt)->getParent() && "Block not embedded in method!"); BasicBlock *BB = *BBIt; Method *M = BB->getParent(); assert(BB->getTerminator() && "Degenerate basic block encountered!"); assert(BB->getParent()->front() != BB && "Can't Simplify entry block!"); // Remove basic blocks that have no predecessors... which are unreachable. if (pred_begin(BB) == pred_end(BB) && !BB->hasConstantPoolReferences()) { //cerr << "Removing BB: \n" << BB; // Loop through all of our successors and make sure they know that one // of their predecessors is going away. for_each(succ_begin(BB), succ_end(BB), std::bind2nd(std::mem_fun(&BasicBlock::removePredecessor), BB)); while (!BB->empty()) { Instruction *I = BB->back(); // If this instruction is used, replace uses with an arbitrary // constant value. Because control flow can't get here, we don't care // what we replace the value with. Note that since this block is // unreachable, and all values contained within it must dominate their // uses, that all uses will eventually be removed. if (!I->use_empty()) ReplaceUsesWithConstant(I); // Remove the instruction from the basic block delete BB->getInstList().pop_back(); } delete M->getBasicBlocks().remove(BBIt); return true; } // Check to see if this block has no instructions and only a single // successor. If so, replace block references with successor. succ_iterator SI(succ_begin(BB)); if (SI != succ_end(BB) && ++SI == succ_end(BB)) { // One succ? Instruction *I = BB->front(); if (I->isTerminator()) { // Terminator is the only instruction! BasicBlock *Succ = *succ_begin(BB); // There is exactly one successor //cerr << "Killing Trivial BB: \n" << BB; if (Succ != BB) { // Arg, don't hurt infinite loops! if (Succ->front()->isPHINode()) { // If our successor has PHI nodes, then we need to update them to // include entries for BB's predecessors, not for BB itself. // PropogatePredecessorsForPHIs(BB, Succ); } BB->replaceAllUsesWith(Succ); BB = M->getBasicBlocks().remove(BBIt); if (BB->hasName() && !Succ->hasName()) // Transfer name if we can Succ->setName(BB->getName()); delete BB; // Delete basic block //cerr << "Method after removal: \n" << M; return true; } } } // Merge basic blocks into their predecessor if there is only one pred, // and if there is only one successor of the predecessor. pred_iterator PI(pred_begin(BB)); if (PI != pred_end(BB) && *PI != BB && // Not empty? Not same BB? ++PI == pred_end(BB) && !BB->hasConstantPoolReferences()) { BasicBlock *Pred = *pred_begin(BB); TerminatorInst *Term = Pred->getTerminator(); assert(Term != 0 && "malformed basic block without terminator!"); // Does the predecessor block only have a single successor? succ_iterator SI(succ_begin(Pred)); if (++SI == succ_end(Pred)) { //cerr << "Merging: " << BB << "into: " << Pred; // Delete the unconditianal branch from the predecessor... BasicBlock::iterator DI = Pred->end(); assert(Pred->getTerminator() && "Degenerate basic block encountered!"); // Empty bb??? delete Pred->getInstList().remove(--DI); // Destroy uncond branch // Move all definitions in the succecessor to the predecessor... while (!BB->empty()) { DI = BB->begin(); Instruction *Def = BB->getInstList().remove(DI); // Remove from front Pred->getInstList().push_back(Def); // Add to end... } // Remove basic block from the method... and advance iterator to the // next valid block... BB = M->getBasicBlocks().remove(BBIt); // Make all PHI nodes that refered to BB now refer to Pred as their // source... BB->replaceAllUsesWith(Pred); // Inherit predecessors name if it exists... if (BB->hasName() && !Pred->hasName()) Pred->setName(BB->getName()); delete BB; // You ARE the weakest link... goodbye return true; } } return false; } static bool DoDCEPass(Method *M) { Method::iterator BBIt, BBEnd = M->end(); if (M->begin() == BBEnd) return false; // Nothing to do bool Changed = false; // Loop through now and remove instructions that have no uses... for (BBIt = M->begin(); BBIt != BBEnd; ++BBIt) { Changed |= RemoveUnusedDefs((*BBIt)->getInstList(), BasicBlockDCE()); Changed |= RemoveSingularPHIs(*BBIt); } // Loop over all of the basic blocks (except the first one) and remove them // if they are unneeded... // for (BBIt = M->begin(), ++BBIt; BBIt != M->end(); ) { if (opt::SimplifyCFG(BBIt)) { Changed = true; } else { ++BBIt; } } // Remove unused constants return Changed | opt::DoRemoveUnusedConstants(M); } // It is possible that we may require multiple passes over the code to fully // eliminate dead code. Iterate until we are done. // bool opt::DoDeadCodeElimination(Method *M) { bool Changed = false; while (DoDCEPass(M)) Changed = true; return Changed; } bool opt::DoDeadCodeElimination(Module *C) { bool Val = C->reduceApply(DoDeadCodeElimination); while (DoRemoveUnusedConstants(C)) Val = true; return Val; }
Remove dependency on the structure of ValueHolder.
Remove dependency on the structure of ValueHolder. git-svn-id: 0ff597fd157e6f4fc38580e8d64ab130330d2411@182 91177308-0d34-0410-b5e6-96231b3b80d8
C++
bsd-2-clause
chubbymaggie/asap,chubbymaggie/asap,apple/swift-llvm,GPUOpen-Drivers/llvm,chubbymaggie/asap,dslab-epfl/asap,dslab-epfl/asap,dslab-epfl/asap,chubbymaggie/asap,apple/swift-llvm,llvm-mirror/llvm,llvm-mirror/llvm,chubbymaggie/asap,GPUOpen-Drivers/llvm,llvm-mirror/llvm,GPUOpen-Drivers/llvm,GPUOpen-Drivers/llvm,dslab-epfl/asap,apple/swift-llvm,dslab-epfl/asap,llvm-mirror/llvm,dslab-epfl/asap,apple/swift-llvm,GPUOpen-Drivers/llvm,GPUOpen-Drivers/llvm,llvm-mirror/llvm,llvm-mirror/llvm,llvm-mirror/llvm,apple/swift-llvm,GPUOpen-Drivers/llvm,dslab-epfl/asap,apple/swift-llvm,apple/swift-llvm,GPUOpen-Drivers/llvm,apple/swift-llvm,chubbymaggie/asap,llvm-mirror/llvm,llvm-mirror/llvm
9f464d41668cdff84178ef7bdfe77b3cee3d9dc4
src/util/TunnelIPv6Interface.cpp
src/util/TunnelIPv6Interface.cpp
/* * * Copyright (c) 2016 Nest Labs, Inc. * All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * Description: * This file contains the implementation for a C++ wrapper around the * `tunnel.c`/`tunnel.h` interface. * */ #if HAVE_CONFIG_H #include <config.h> #endif #include "assert-macros.h" #include "TunnelIPv6Interface.h" #include <syslog.h> #include "IPv6Helpers.h" #if __linux__ #include <asm/types.h> #include <linux/if_link.h> #include <sys/socket.h> #include <linux/netlink.h> #include <linux/rtnetlink.h> #include <fcntl.h> #endif #include <sys/select.h> TunnelIPv6Interface::TunnelIPv6Interface(const std::string& interface_name, int mtu): UnixSocket(tunnel_open(interface_name.c_str()), true), mInterfaceName(interface_name), mLastError(0), mNetlinkFD(-1), mHardwareAddress(), mRealmLocalAddress(), mRealmLocalPrefixSize(64) { if (0 > mFDRead) { throw std::invalid_argument("Unable to open tunnel interface"); } { char ActualInterfaceName[TUNNEL_MAX_INTERFACE_NAME_LEN] = ""; int ret = 0; ret = tunnel_get_name(mFDRead, ActualInterfaceName, sizeof(ActualInterfaceName)); if (ret) { syslog(LOG_WARNING, "TunnelIPv6Interface: Couldn't get tunnel name! errno=%d, %s", errno, strerror(errno)); } else if (mInterfaceName != ActualInterfaceName) { syslog(LOG_WARNING, "TunnelIPv6Interface: Couldn't create tunnel named \"%s\", got \"%s\" instead!", mInterfaceName.c_str(), ActualInterfaceName); mInterfaceName = ActualInterfaceName; } } tunnel_set_mtu(mFDRead, mtu); setup_signals(); } TunnelIPv6Interface::~TunnelIPv6Interface() { close(mNetlinkFD); } #if __linux__ // -------------------------------------------------------------- #define LCG32(x) ((uint32_t)(x)*1664525+1013904223) void TunnelIPv6Interface::setup_signals() { int status; int fd; struct sockaddr_nl la; fd = socket(AF_NETLINK, SOCK_DGRAM, NETLINK_ROUTE); require(fd != -1, bail); memset(&la, 0, sizeof(la)); la.nl_family = AF_NETLINK; la.nl_pad = 0; la.nl_groups = RTMGRP_LINK | RTMGRP_IPV6_IFADDR; // We calculate the PID in a pseudo-random way based on the // address pointer and the actual process ID. la.nl_pid = LCG32(getpid()) ^ LCG32((uint32_t)reinterpret_cast<uintptr_t>(this)); status = bind(fd, (struct sockaddr*) &la, sizeof(la)); require(status != -1, bail); // Success! IGNORE_RETURN_VALUE(fcntl(fd, F_SETFL, FNDELAY)); mNetlinkFD = fd; fd = -1; bail: // Cleanup (If necessary) if (fd > 0) { close(fd); } return; } int TunnelIPv6Interface::process(void) { uint8_t buffer[1024]; ssize_t buffer_len(-1); if (mNetlinkFD >= 0) { buffer_len = recv(mNetlinkFD, buffer, sizeof(buffer), 0); } if (buffer_len > 0) { struct nlmsghdr *nlp; struct rtmsg *rtp; int rta_len; struct rtattr *rta; nlp = (struct nlmsghdr *)buffer; for (;NLMSG_OK(nlp, buffer_len); nlp=NLMSG_NEXT(nlp, buffer_len)) { if (nlp->nlmsg_type == RTM_NEWADDR || nlp->nlmsg_type == RTM_DELADDR) { struct ifaddrmsg *ifaddr = (struct ifaddrmsg *)NLMSG_DATA(nlp); char ifnamebuf[IF_NAMESIZE]; const char *ifname = if_indextoname(ifaddr->ifa_index, ifnamebuf); struct in6_addr addr; if ((ifname == NULL) || (get_interface_name() != ifname)) { continue; } // get RTNETLINK message header // get start of attributes rta = (struct rtattr *) IFA_RTA(ifaddr); // get length of attributes rta_len = IFA_PAYLOAD(nlp); for(;RTA_OK(rta, rta_len); rta = RTA_NEXT(rta, rta_len)) { switch(rta->rta_type) { case IFA_ADDRESS: case IFA_LOCAL: case IFA_BROADCAST: case IFA_ANYCAST: memcpy(addr.s6_addr, RTA_DATA(rta), sizeof(addr)); if (nlp->nlmsg_type == RTM_NEWADDR) { mAddressWasAdded(addr, ifaddr->ifa_prefixlen); } else if (nlp->nlmsg_type == RTM_DELADDR) { mAddressWasRemoved(addr, ifaddr->ifa_prefixlen); } break; default: break; } } } } } return nl::UnixSocket::process(); } #else // ---------------------------------------------------------------------- void TunnelIPv6Interface::setup_signals() { // Unknown platform. } int TunnelIPv6Interface::process(void) { return nl::UnixSocket::process(); } #endif // --------------------------------------------------------------------- int TunnelIPv6Interface::update_fd_set(fd_set *read_fd_set, fd_set *write_fd_set, fd_set *error_fd_set, int *max_fd, cms_t *timeout) { if (read_fd_set && (mNetlinkFD >= 0)) { FD_SET(mNetlinkFD, read_fd_set); if ((max_fd != NULL)) { *max_fd = std::max(*max_fd, mNetlinkFD); } } return nl::UnixSocket::update_fd_set(read_fd_set, write_fd_set, error_fd_set, max_fd, timeout); } const std::string& TunnelIPv6Interface::get_interface_name(void) { return mInterfaceName; } int TunnelIPv6Interface::get_last_error(void) { return mLastError; } bool TunnelIPv6Interface::is_online(void) { return tunnel_is_online(mFDRead); } int TunnelIPv6Interface::set_online(bool online) { int ret = 0; if (online) { syslog(LOG_INFO, "Bringing interface %s online. . .", mInterfaceName.c_str()); require_action((ret = tunnel_bring_online(mFDRead)) == 0, bail, mLastError = errno); require_action(tunnel_is_online(mFDRead), bail, mLastError = errno); (void)tunnel_set_hw_address(mFDRead, mHardwareAddress); require_action_string(tunnel_is_online(mFDRead), bail, mLastError = errno, "Tunnel went offline unexpectedly!"); if (!IN6_IS_ADDR_UNSPECIFIED(&mRealmLocalAddress)) { (void)tunnel_add_address(mFDRead, mRealmLocalAddress.s6_addr, mRealmLocalPrefixSize); } std::set<struct in6_addr>::const_iterator iter; for (iter = mAddresses.begin(); iter != mAddresses.end(); ++iter) { (void)tunnel_add_address(mFDRead, iter->s6_addr, 64); } } else { syslog(LOG_INFO, "Taking interface %s offline. . .", mInterfaceName.c_str()); require_action((ret = tunnel_bring_offline(mFDRead)) == 0, bail, mLastError = errno); } bail: return ret; } void TunnelIPv6Interface::reset(void) { syslog(LOG_INFO, "Resetting interface %s. . .", mInterfaceName.c_str()); if (!IN6_IS_ADDR_UNSPECIFIED(&mRealmLocalAddress)) { remove_address(&mRealmLocalAddress, mRealmLocalPrefixSize); memset((void*)&mRealmLocalAddress, 0, sizeof(mRealmLocalAddress)); mRealmLocalPrefixSize = 0; } mAddresses.clear(); set_online(false); set_hardware_address(mHardwareAddress); } bool TunnelIPv6Interface::set_hardware_address(const uint8_t addr[8]) { bool ret = false; if (memcmp(mHardwareAddress, addr, sizeof(mHardwareAddress)) != 0) { require_noerr(tunnel_set_hw_address(mFDRead, addr), bail); memcpy(mHardwareAddress, addr, sizeof(mHardwareAddress)); } ret = true; bail: return ret; } const uint8_t* TunnelIPv6Interface::get_hardware_address(void)const { return mHardwareAddress; } bool TunnelIPv6Interface::add_address(const struct in6_addr *addr, int prefixlen) { bool ret = false; syslog( LOG_INFO, "TunnelIPv6Interface: Adding address \"%s\" to interface \"%s\".", in6_addr_to_string(*addr).c_str(), mInterfaceName.c_str() ); if (is_online()) { require_noerr_action(tunnel_add_address(mFDRead, addr->s6_addr, prefixlen), bail, mLastError = errno); } mAddresses.insert(*addr); ret = true; bail: return ret; } bool TunnelIPv6Interface::set_realm_local_address(const struct in6_addr *addr, int prefixlen) { bool ret = false; if (is_online() && (mRealmLocalAddress != *addr)) { require(ret = add_address(addr, prefixlen), bail); if (!IN6_IS_ADDR_UNSPECIFIED(&mRealmLocalAddress)) { remove_address(&mRealmLocalAddress, mRealmLocalPrefixSize); } } mRealmLocalAddress = *addr; mRealmLocalPrefixSize = prefixlen; ret = true; bail: return ret; } const struct in6_addr& TunnelIPv6Interface::get_realm_local_address()const { return mRealmLocalAddress; } bool TunnelIPv6Interface::remove_address(const struct in6_addr *addr, int prefixlen) { bool ret = false; syslog( LOG_INFO, "TunnelIPv6Interface: Removing address \"%s\" from interface \"%s\".", in6_addr_to_string(*addr).c_str(), mInterfaceName.c_str() ); mAddresses.erase(*addr); require_action(!IN6_IS_ADDR_UNSPECIFIED(addr), bail, mLastError = EINVAL); require_action(!IN6_IS_ADDR_LINKLOCAL(addr), bail, mLastError = EINVAL); if (tunnel_remove_address(mFDRead, addr->s6_addr) != 0) { mLastError = errno; goto bail; } if (mRealmLocalAddress == *addr) { memset(mRealmLocalAddress.s6_addr, 0, sizeof(mRealmLocalAddress)); } ret = true; bail: return ret; } bool TunnelIPv6Interface::add_route(const struct in6_addr *route, int prefixlen) { bool ret = false; syslog( LOG_INFO, "TunnelIPv6Interface: Adding route prefix \"%s/%d\" -> \"%s\".", in6_addr_to_string(*route).c_str(), prefixlen, mInterfaceName.c_str() ); if (is_online()) { require_noerr_action(tunnel_add_route(mFDRead, route->s6_addr, prefixlen), bail, mLastError = errno); } ret = true; bail: return ret; } bool TunnelIPv6Interface::remove_route(const struct in6_addr *route, int prefixlen) { bool ret = false; syslog( LOG_INFO, "TunnelIPv6Interface: Removing route prefix \"%s/%d\" -> \"%s\".", in6_addr_to_string(*route).c_str(), prefixlen, mInterfaceName.c_str() ); if (is_online()) { require_noerr_action(tunnel_remove_route(mFDRead, route->s6_addr, prefixlen), bail, mLastError = errno); } ret = true; bail: return ret; } ssize_t TunnelIPv6Interface::read(void* data, size_t len) { ssize_t ret = nl::UnixSocket::read(data, len); uint8_t *data_bytes = static_cast<uint8_t*>(data); // Remove any subheader, if present. if ((ret >= 4) && (data_bytes[0] == 0) && (data_bytes[1] == 0)) { ret -= 4; memmove(data, static_cast<const void*>(data_bytes + 4), ret); } return ret; } ssize_t TunnelIPv6Interface::write(const void* data, size_t len) { #ifdef __APPLE__ const uint8_t* const data_bytes = static_cast<const uint8_t*>(data); if ((data_bytes[0] != 0) || (data_bytes[0] != 0)) { // The utun interface on OS X needs this header. // Linux seems to be able to infer the type of the packet // with no problems. uint8_t packet[len + 4]; packet[0] = 0; packet[1] = 0; packet[2] = (PF_INET6 << 8) & 0xFF; packet[3] = (PF_INET6 << 0) & 0xFF; memcpy(static_cast<void*>(packet + 4), data, len); ssize_t ret = nl::UnixSocket::write(packet, len + 4); return (ret >= 4)?(ret - 4):(-1); } #endif return nl::UnixSocket::write(data, len); }
/* * * Copyright (c) 2016 Nest Labs, Inc. * All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * Description: * This file contains the implementation for a C++ wrapper around the * `tunnel.c`/`tunnel.h` interface. * */ #if HAVE_CONFIG_H #include <config.h> #endif #include "assert-macros.h" #include "TunnelIPv6Interface.h" #include <syslog.h> #include "IPv6Helpers.h" #if __linux__ #include <asm/types.h> #include <linux/if_link.h> #include <sys/socket.h> #include <linux/netlink.h> #include <linux/rtnetlink.h> #include <fcntl.h> #endif #include <sys/select.h> TunnelIPv6Interface::TunnelIPv6Interface(const std::string& interface_name, int mtu): UnixSocket(tunnel_open(interface_name.c_str()), true), mInterfaceName(interface_name), mLastError(0), mNetlinkFD(-1), mHardwareAddress(), mRealmLocalAddress(), mRealmLocalPrefixSize(64) { if (0 > mFDRead) { throw std::invalid_argument("Unable to open tunnel interface"); } { char ActualInterfaceName[TUNNEL_MAX_INTERFACE_NAME_LEN] = ""; int ret = 0; ret = tunnel_get_name(mFDRead, ActualInterfaceName, sizeof(ActualInterfaceName)); if (ret) { syslog(LOG_WARNING, "TunnelIPv6Interface: Couldn't get tunnel name! errno=%d, %s", errno, strerror(errno)); } else if (mInterfaceName != ActualInterfaceName) { syslog(LOG_WARNING, "TunnelIPv6Interface: Couldn't create tunnel named \"%s\", got \"%s\" instead!", mInterfaceName.c_str(), ActualInterfaceName); mInterfaceName = ActualInterfaceName; } } tunnel_set_mtu(mFDRead, mtu); setup_signals(); } TunnelIPv6Interface::~TunnelIPv6Interface() { close(mNetlinkFD); } #if __linux__ // -------------------------------------------------------------- #define LCG32(x) ((uint32_t)(x)*1664525+1013904223) void TunnelIPv6Interface::setup_signals() { int status; int fd; struct sockaddr_nl la; fd = socket(AF_NETLINK, SOCK_DGRAM, NETLINK_ROUTE); require(fd != -1, bail); memset(&la, 0, sizeof(la)); la.nl_family = AF_NETLINK; la.nl_pad = 0; la.nl_groups = RTMGRP_LINK | RTMGRP_IPV6_IFADDR; // We calculate the PID in a pseudo-random way based on the // address pointer and the actual process ID. la.nl_pid = LCG32(getpid()) ^ LCG32((uint32_t)reinterpret_cast<uintptr_t>(this)); status = bind(fd, (struct sockaddr*) &la, sizeof(la)); require(status != -1, bail); // Success! IGNORE_RETURN_VALUE(fcntl(fd, F_SETFL, FNDELAY)); mNetlinkFD = fd; fd = -1; bail: // Cleanup (If necessary) if (fd > 0) { close(fd); } return; } int TunnelIPv6Interface::process(void) { uint8_t buffer[1024]; ssize_t buffer_len(-1); if (mNetlinkFD >= 0) { buffer_len = recv(mNetlinkFD, buffer, sizeof(buffer), 0); } if (buffer_len > 0) { struct nlmsghdr *nlp; struct rtmsg *rtp; int rta_len; struct rtattr *rta; nlp = (struct nlmsghdr *)buffer; for (;NLMSG_OK(nlp, buffer_len); nlp=NLMSG_NEXT(nlp, buffer_len)) { if (nlp->nlmsg_type == RTM_NEWADDR || nlp->nlmsg_type == RTM_DELADDR) { struct ifaddrmsg *ifaddr = (struct ifaddrmsg *)NLMSG_DATA(nlp); char ifnamebuf[IF_NAMESIZE]; const char *ifname = if_indextoname(ifaddr->ifa_index, ifnamebuf); struct in6_addr addr; if ((ifname == NULL) || (get_interface_name() != ifname)) { continue; } // get RTNETLINK message header // get start of attributes rta = (struct rtattr *) IFA_RTA(ifaddr); // get length of attributes rta_len = IFA_PAYLOAD(nlp); for(;RTA_OK(rta, rta_len); rta = RTA_NEXT(rta, rta_len)) { switch(rta->rta_type) { case IFA_ADDRESS: case IFA_LOCAL: case IFA_BROADCAST: case IFA_ANYCAST: memcpy(addr.s6_addr, RTA_DATA(rta), sizeof(addr)); if (nlp->nlmsg_type == RTM_NEWADDR) { mAddressWasAdded(addr, ifaddr->ifa_prefixlen); } else if (nlp->nlmsg_type == RTM_DELADDR) { mAddressWasRemoved(addr, ifaddr->ifa_prefixlen); } break; default: break; } } } } } return nl::UnixSocket::process(); } #else // ---------------------------------------------------------------------- void TunnelIPv6Interface::setup_signals() { // Unknown platform. } int TunnelIPv6Interface::process(void) { return nl::UnixSocket::process(); } #endif // --------------------------------------------------------------------- int TunnelIPv6Interface::update_fd_set(fd_set *read_fd_set, fd_set *write_fd_set, fd_set *error_fd_set, int *max_fd, cms_t *timeout) { if (read_fd_set && (mNetlinkFD >= 0)) { FD_SET(mNetlinkFD, read_fd_set); if ((max_fd != NULL)) { *max_fd = std::max(*max_fd, mNetlinkFD); } } return nl::UnixSocket::update_fd_set(read_fd_set, write_fd_set, error_fd_set, max_fd, timeout); } const std::string& TunnelIPv6Interface::get_interface_name(void) { return mInterfaceName; } int TunnelIPv6Interface::get_last_error(void) { return mLastError; } bool TunnelIPv6Interface::is_online(void) { return tunnel_is_online(mFDRead); } int TunnelIPv6Interface::set_online(bool online) { int ret = 0; if (online) { syslog(LOG_INFO, "Bringing interface %s online. . .", mInterfaceName.c_str()); require_action((ret = tunnel_bring_online(mFDRead)) == 0, bail, mLastError = errno); require_action(tunnel_is_online(mFDRead), bail, mLastError = errno); (void)tunnel_set_hw_address(mFDRead, mHardwareAddress); require_action_string(tunnel_is_online(mFDRead), bail, mLastError = errno, "Tunnel went offline unexpectedly!"); if (!IN6_IS_ADDR_UNSPECIFIED(&mRealmLocalAddress)) { (void)tunnel_add_address(mFDRead, mRealmLocalAddress.s6_addr, mRealmLocalPrefixSize); } std::set<struct in6_addr>::const_iterator iter; for (iter = mAddresses.begin(); iter != mAddresses.end(); ++iter) { (void)tunnel_add_address(mFDRead, iter->s6_addr, 64); } } else { syslog(LOG_INFO, "Taking interface %s offline. . .", mInterfaceName.c_str()); require_action((ret = tunnel_bring_offline(mFDRead)) == 0, bail, mLastError = errno); } bail: return ret; } void TunnelIPv6Interface::reset(void) { syslog(LOG_INFO, "Resetting interface %s. . .", mInterfaceName.c_str()); if (!IN6_IS_ADDR_UNSPECIFIED(&mRealmLocalAddress)) { remove_address(&mRealmLocalAddress, mRealmLocalPrefixSize); memset((void*)&mRealmLocalAddress, 0, sizeof(mRealmLocalAddress)); mRealmLocalPrefixSize = 0; } mAddresses.clear(); set_online(false); set_hardware_address(mHardwareAddress); } bool TunnelIPv6Interface::set_hardware_address(const uint8_t addr[8]) { bool ret = false; if (memcmp(mHardwareAddress, addr, sizeof(mHardwareAddress)) != 0) { require_noerr(tunnel_set_hw_address(mFDRead, addr), bail); memcpy(mHardwareAddress, addr, sizeof(mHardwareAddress)); } ret = true; bail: return ret; } const uint8_t* TunnelIPv6Interface::get_hardware_address(void)const { return mHardwareAddress; } bool TunnelIPv6Interface::add_address(const struct in6_addr *addr, int prefixlen) { bool ret = false; syslog( LOG_INFO, "TunnelIPv6Interface: Adding address \"%s\" to interface \"%s\".", in6_addr_to_string(*addr).c_str(), mInterfaceName.c_str() ); if (is_online()) { require_noerr_action(tunnel_add_address(mFDRead, addr->s6_addr, prefixlen), bail, mLastError = errno); } mAddresses.insert(*addr); ret = true; bail: return ret; } bool TunnelIPv6Interface::set_realm_local_address(const struct in6_addr *addr, int prefixlen) { if (addr == NULL) { static const struct in6_addr any_addr = {}; addr = &any_addr; } if (is_online() && (mRealmLocalAddress != *addr)) { if (!IN6_IS_ADDR_UNSPECIFIED(addr)) { add_address(addr, prefixlen); } if (!IN6_IS_ADDR_UNSPECIFIED(&mRealmLocalAddress)) { remove_address(&mRealmLocalAddress, mRealmLocalPrefixSize); } } mRealmLocalAddress = *addr; mRealmLocalPrefixSize = prefixlen; return true; } const struct in6_addr& TunnelIPv6Interface::get_realm_local_address()const { return mRealmLocalAddress; } bool TunnelIPv6Interface::remove_address(const struct in6_addr *addr, int prefixlen) { bool ret = false; syslog( LOG_INFO, "TunnelIPv6Interface: Removing address \"%s\" from interface \"%s\".", in6_addr_to_string(*addr).c_str(), mInterfaceName.c_str() ); require_action(!IN6_IS_ADDR_UNSPECIFIED(addr), bail, mLastError = EINVAL); mAddresses.erase(*addr); if (mRealmLocalAddress == *addr) { memset(mRealmLocalAddress.s6_addr, 0, sizeof(mRealmLocalAddress)); } if (tunnel_remove_address(mFDRead, addr->s6_addr) != 0) { mLastError = errno; goto bail; } ret = true; bail: return ret; } bool TunnelIPv6Interface::add_route(const struct in6_addr *route, int prefixlen) { bool ret = false; syslog( LOG_INFO, "TunnelIPv6Interface: Adding route prefix \"%s/%d\" -> \"%s\".", in6_addr_to_string(*route).c_str(), prefixlen, mInterfaceName.c_str() ); if (is_online()) { require_noerr_action(tunnel_add_route(mFDRead, route->s6_addr, prefixlen), bail, mLastError = errno); } ret = true; bail: return ret; } bool TunnelIPv6Interface::remove_route(const struct in6_addr *route, int prefixlen) { bool ret = false; syslog( LOG_INFO, "TunnelIPv6Interface: Removing route prefix \"%s/%d\" -> \"%s\".", in6_addr_to_string(*route).c_str(), prefixlen, mInterfaceName.c_str() ); if (is_online()) { require_noerr_action(tunnel_remove_route(mFDRead, route->s6_addr, prefixlen), bail, mLastError = errno); } ret = true; bail: return ret; } ssize_t TunnelIPv6Interface::read(void* data, size_t len) { ssize_t ret = nl::UnixSocket::read(data, len); uint8_t *data_bytes = static_cast<uint8_t*>(data); // Remove any subheader, if present. if ((ret >= 4) && (data_bytes[0] == 0) && (data_bytes[1] == 0)) { ret -= 4; memmove(data, static_cast<const void*>(data_bytes + 4), ret); } return ret; } ssize_t TunnelIPv6Interface::write(const void* data, size_t len) { #ifdef __APPLE__ const uint8_t* const data_bytes = static_cast<const uint8_t*>(data); if ((data_bytes[0] != 0) || (data_bytes[0] != 0)) { // The utun interface on OS X needs this header. // Linux seems to be able to infer the type of the packet // with no problems. uint8_t packet[len + 4]; packet[0] = 0; packet[1] = 0; packet[2] = (PF_INET6 << 8) & 0xFF; packet[3] = (PF_INET6 << 0) & 0xFF; memcpy(static_cast<void*>(packet + 4), data, len); ssize_t ret = nl::UnixSocket::write(packet, len + 4); return (ret >= 4)?(ret - 4):(-1); } #endif return nl::UnixSocket::write(data, len); }
Allow passing `NULL` to clear realm local address
tunnel: Allow passing `NULL` to clear realm local address
C++
apache-2.0
aeliot/wpantund,d-bahr/wpantund,aeliot/wpantund,aeliot/wpantund,openthread/wpantund,d-bahr/wpantund,d-bahr/wpantund,d-bahr/wpantund,abtink/wpantund,abtink/wpantund,aeliot/wpantund,abtink/wpantund,openthread/wpantund,openthread/wpantund,openthread/wpantund,abtink/wpantund
653c70a38613bbc2deb02b69a3a8742ee05ff96c
PotreeConverter/include/LASPointWriter.hpp
PotreeConverter/include/LASPointWriter.hpp
#ifndef LASPOINTWRITER_H #define LASPOINTWRITER_H #include <string> #include <iostream> #include <fstream> #include "laszip_dll.h" #include <boost/algorithm/string/predicate.hpp> #include "AABB.h" #include "PointWriter.hpp" #include "Point.h" using std::string; using std::fstream; using std::ios; using boost::algorithm::iends_with; namespace Potree{ class LASPointWriter : public PointWriter{ public: string file; int numPoints = 0; AABB aabb; laszip_POINTER writer = NULL; laszip_header header; laszip_point* point; double coordinates[3]; LASPointWriter(string file, AABB aabb, double scale) { this->file = file; this->aabb = aabb; numPoints = 0; memset(&header, 0, sizeof(laszip_header)); strcpy_s(header.generating_software, "potree"); header.version_major = 1; header.version_minor = 2; header.header_size = 227; header.offset_to_point_data = 227; header.point_data_format = 2; header.min_x = aabb.min.x; header.min_y = aabb.min.y; header.min_z = aabb.min.z; header.max_x = aabb.max.x; header.max_y = aabb.max.y; header.max_z = aabb.max.z; header.x_scale_factor = scale; header.y_scale_factor = scale; header.z_scale_factor = scale; header.point_data_record_length = 26; header.number_of_point_records = 111; laszip_create(&writer); laszip_BOOL compress = iends_with(file, ".laz") ? 1 : 0; if(compress){ laszip_BOOL request_writer = 1; laszip_request_compatibility_mode(writer, request_writer); } laszip_set_header(writer, &header); laszip_open_writer(writer, file.c_str(), compress); laszip_get_point_pointer(writer, &point); } ~LASPointWriter(){ close(); } void write(const Point &point); void close(){ if(writer != NULL){ laszip_close_writer(writer); laszip_destroy(writer); writer = NULL; fstream *stream = new fstream(file, ios::out | ios::binary | ios::in ); stream->seekp(107); stream->write(reinterpret_cast<const char*>(&numPoints), 4); stream->close(); delete stream; } } }; } #endif
#ifndef LASPOINTWRITER_H #define LASPOINTWRITER_H #include <string> #include <iostream> #include <fstream> #include "laszip_dll.h" #include <boost/algorithm/string/predicate.hpp> #include "AABB.h" #include "PointWriter.hpp" #include "Point.h" using std::string; using std::fstream; using std::ios; using boost::algorithm::iends_with; namespace Potree{ class LASPointWriter : public PointWriter{ public: string file; int numPoints = 0; AABB aabb; laszip_POINTER writer = NULL; laszip_header header; laszip_point* point; double coordinates[3]; LASPointWriter(string file, AABB aabb, double scale) { this->file = file; this->aabb = aabb; numPoints = 0; memset(&header, 0, sizeof(laszip_header)); strcpy(header.generating_software, "potree"); header.version_major = 1; header.version_minor = 2; header.header_size = 227; header.offset_to_point_data = 227; header.point_data_format = 2; header.min_x = aabb.min.x; header.min_y = aabb.min.y; header.min_z = aabb.min.z; header.max_x = aabb.max.x; header.max_y = aabb.max.y; header.max_z = aabb.max.z; header.x_scale_factor = scale; header.y_scale_factor = scale; header.z_scale_factor = scale; header.point_data_record_length = 26; header.number_of_point_records = 111; laszip_create(&writer); laszip_BOOL compress = iends_with(file, ".laz") ? 1 : 0; if(compress){ laszip_BOOL request_writer = 1; laszip_request_compatibility_mode(writer, request_writer); } laszip_set_header(writer, &header); laszip_open_writer(writer, file.c_str(), compress); laszip_get_point_pointer(writer, &point); } ~LASPointWriter(){ close(); } void write(const Point &point); void close(){ if(writer != NULL){ laszip_close_writer(writer); laszip_destroy(writer); writer = NULL; fstream *stream = new fstream(file, ios::out | ios::binary | ios::in ); stream->seekp(107); stream->write(reinterpret_cast<const char*>(&numPoints), 4); stream->close(); delete stream; } } }; } #endif
replace strcpy_s with strcpy
replace strcpy_s with strcpy
C++
bsd-2-clause
kyroskoh/PotreeConverter,Georepublic/PotreeConverter,kyroskoh/PotreeConverter,kyroskoh/PotreeConverter,potree/PotreeConverter,sverhoeven/PotreeConverter,potree/PotreeConverter,Georepublic/PotreeConverter,sverhoeven/PotreeConverter,sverhoeven/PotreeConverter,potree/PotreeConverter,sverhoeven/PotreeConverter,potree/PotreeConverter,potree/PotreeConverter,potree/PotreeConverter,Georepublic/PotreeConverter,kyroskoh/PotreeConverter,potree/PotreeConverter,Georepublic/PotreeConverter
59da5735742cf60cf32afbf9a2020fb1f35f1ba7
src/cluster.cpp
src/cluster.cpp
#include <list> #ifdef DEBUG #include <iostream> #endif #ifndef CPX_INFBOUND #include <climits> #define INFBOUND INT_MAX #else #define INFBOUND CPX_INFBOUND #endif #include "cluster.h" #include "sense.h" #include "thread.h" #include "lockingvars.h" #include "symgroup.h" // S[n].size() Cluster::Cluster(int nThreads, int nObj, Sense sense, bool spread_threads, int nObjLeft, int * ordering, int ** share_to_, int ** share_from_, int ** share_bounds_, int ** share_limit_, std::list<Thread*> & threads, Locking_Vars ** locks) { if (nThreads == 1) { // Build perm int * perm = new int[nObj]; int i; for(i = 0; i < nObj; ++i) { perm[i] = ordering[i]; } #ifdef DEBUG std::cout << "Thread " << threads.size() << " using permutation "; std::cout << perm[0]; for(int d = 1; d < nObj; ++d) { std::cout << "," << perm[d]; } std::cout << std::endl; #endif // If there is only one objective left to add, then at the previous stage // we must've had 2 objectives left, and 2 threads to use (else the Thread // object would be constructed there), so this thread would have a partner. bool has_partner = (nObjLeft == 1); // Build thread Thread *t = new Thread(threads.size(), nObj, perm, share_to_, share_from_, share_bounds_, share_limit_, locks, has_partner); threads.push_back(t); // threads.push_back( new Thread(threads.size(), nObj, perm, shared_limits)); } else { int *my_ordering = new int[nObj]; #ifdef DEBUG std::cout << "Working with permutation "; std::cout << ordering[0]; for(int d = 1; d < nObj; ++d) { std::cout << "," << ordering[d]; } std::cout << ", " << nThreads << " threads left,"; std::cout << " and " << nObjLeft << " objectives left."; std::cout << std::endl; #endif for(int i = 0; i < nObj; ++i) { my_ordering[i] = ordering[i]; } int ** share_to = new int*[nObj]; int ** share_from = new int*[nObj]; int ** share_limit = new int*[nObj]; int ** share_bounds = new int*[nObj]; for(int j = 0; j < nObj; ++j) { share_to[j] = share_to_[j]; share_bounds[j] = share_bounds_[j]; share_from[j] = share_from_[j]; share_limit[j] = share_limit_[j]; } // Work out how many different objectives will occur // in position "nObjLeft - 1" int ind = nObjLeft; int ** new_shares = new int*[nObj] {nullptr}; int ** new_bounds = new int*[nObj] {nullptr}; int ** new_limit = new int*[nObj] {nullptr}; int num_sub_clusters = (ind < nThreads) ? ind : nThreads; for(int j = 0; j < num_sub_clusters; ++j) { int pos = my_ordering[nObjLeft - j - 1]; new_shares[pos] = new int; new_bounds[pos] = new int; new_limit[pos] = new int; if (sense == MIN) { *new_shares[pos] = INFBOUND; *new_bounds[pos] = -INFBOUND; *new_limit[pos] = INFBOUND; } else { *new_shares[pos] = -INFBOUND; *new_bounds[pos] = INFBOUND; *new_limit[pos] = -INFBOUND; } } if (spread_threads) { // Split up threads int perCluster = nThreads / nObjLeft; int withExtra = nThreads % nObjLeft; int i; for(i = 0; i < withExtra ; ++i) { int pos = my_ordering[nObjLeft-1]; locks[pos] = new Locking_Vars(perCluster + 1); int * old_share_to = share_to[pos]; int * old_share_bounds = share_bounds[pos]; int * old_share_limit = share_limit[pos]; int ** old_from = new int*[nObj]; for(int j = 0; j < nObjLeft; ++j) { int obj = my_ordering[j]; old_from[obj] = share_from[obj]; } for(int j = 0; j < nObjLeft; ++j) { int obj = my_ordering[j]; if (obj == pos) { share_to[obj] = new_shares[obj]; share_bounds[obj] = new_bounds[obj]; share_limit[obj] = new_limit[obj]; } else { share_from[obj] = new_shares[obj]; } } Cluster(perCluster + 1, nObj, sense, spread_threads, nObjLeft - 1, my_ordering, share_to, share_from, share_bounds, share_limit, threads, locks); share_to[pos] = old_share_to; share_bounds[pos] = old_share_bounds; share_limit[pos] = old_share_limit; for(int j = 0; j < nObjLeft; ++j) { int obj = my_ordering[j]; share_from[obj] = old_from[obj]; } // Rotate ordering int first = my_ordering[0]; for (int c = 0; c < nObjLeft-1; ++c) { my_ordering[c] = my_ordering[c+1]; } my_ordering[nObjLeft - 1] = first; locks[pos] = nullptr; } if (perCluster > 0) { for( ; i < nObjLeft ; ++i) { int pos = my_ordering[nObjLeft-1]; int * old_share_to = share_to[pos]; int * old_share_bounds = share_bounds[pos]; int * old_share_limit = share_limit[pos]; locks[pos] = new Locking_Vars(perCluster); int ** old_from = new int*[nObj]; for(int j = 0; j < nObjLeft; ++j) { int obj = my_ordering[j]; old_from[obj] = share_from[obj]; } for(int j = 0; j < nObjLeft; ++j) { int obj = my_ordering[j]; if (obj == pos) { share_to[obj] = new_shares[obj]; share_bounds[obj] = new_bounds[obj]; share_limit[obj] = new_limit[obj]; } else { share_from[obj] = new_shares[obj]; } } Cluster(perCluster, nObj, sense, spread_threads, nObjLeft - 1, my_ordering, share_to, share_from, share_bounds, share_limit, threads, locks); share_to[pos] = old_share_to; share_bounds[pos] = old_share_bounds; share_limit[pos] = old_share_limit; for(int j = 0; j < nObjLeft; ++j) { int obj = my_ordering[j]; share_from[obj] = old_from[obj]; } // Rotate ordering int first = my_ordering[0]; for (int c = 0; c < nObjLeft-1; ++c) { my_ordering[c] = my_ordering[c+1]; } my_ordering[nObjLeft - 1] = first; locks[pos] = nullptr; } } } else { // grouping threads "near" each other int threads_remaining = nThreads; while (threads_remaining > 0) { int threads_to_use = (S[nObjLeft-1].size() > threads_remaining) ? threads_remaining : S[nObjLeft-1].size(); int pos = my_ordering[nObjLeft-1]; locks[pos] = new Locking_Vars(threads_to_use); int * old_share_to = share_to[pos]; int * old_share_bounds = share_bounds[pos]; int * old_share_limit = share_limit[pos]; int ** old_from = new int*[nObj]; for(int j = 0; j < nObjLeft; ++j) { int obj = my_ordering[j]; old_from[obj] = share_from[obj]; } for(int j = 0; j < nObjLeft; ++j) { int obj = my_ordering[j]; if (obj == pos) { share_to[obj] = new_shares[obj]; share_bounds[pos] = new_bounds[obj]; share_limit[obj] = new_limit[obj]; } else { share_from[obj] = new_shares[obj]; } } Cluster(threads_to_use, nObj, sense, spread_threads, nObjLeft - 1, my_ordering, share_to, share_from, share_bounds, share_limit, threads, locks); threads_remaining -= threads_to_use; share_to[pos] = old_share_to; share_bounds[pos] = old_share_bounds; share_limit[pos] = old_share_limit; for(int j = 0; j < nObjLeft; ++j) { int obj = my_ordering[j]; share_from[obj] = old_from[obj]; } // Rotate ordering int first = my_ordering[0]; for (int c = 0; c < nObjLeft-1; ++c) { my_ordering[c] = my_ordering[c+1]; } my_ordering[nObjLeft - 1] = first; locks[pos] = nullptr; } } delete[] my_ordering; delete[] new_shares; delete[] new_limit; delete[] share_to; delete[] share_from; delete[] share_limit; delete[] share_bounds; } }
#include <list> #ifdef DEBUG #include <iostream> #endif #ifndef CPX_INFBOUND #include <climits> #define INFBOUND INT_MAX #else #define INFBOUND CPX_INFBOUND #endif #include "cluster.h" #include "sense.h" #include "thread.h" #include "lockingvars.h" #include "symgroup.h" // S[n].size() Cluster::Cluster(int nThreads, int nObj, Sense sense, bool spread_threads, int nObjLeft, int * ordering, int ** share_to_, int ** share_from_, int ** share_bounds_, int ** share_limit_, std::list<Thread*> & threads, Locking_Vars ** locks) { if (nThreads == 1) { // Build perm int * perm = new int[nObj]; int i; for(i = 0; i < nObj; ++i) { perm[i] = ordering[i]; } #ifdef DEBUG std::cout << "Thread " << threads.size() << " using permutation "; std::cout << perm[0]; for(int d = 1; d < nObj; ++d) { std::cout << "," << perm[d]; } std::cout << std::endl; #endif // If there is only one objective left to add, then at the previous stage // we must've had 2 objectives left, and 2 threads to use (else the Thread // object would be constructed there), so this thread would have a partner. bool has_partner = (nObjLeft == 1); // Build thread Thread *t = new Thread(threads.size(), nObj, perm, share_to_, share_from_, share_bounds_, share_limit_, locks, has_partner); threads.push_back(t); // threads.push_back( new Thread(threads.size(), nObj, perm, shared_limits)); } else { int *my_ordering = new int[nObj]; #ifdef DEBUG std::cout << "Working with permutation "; std::cout << ordering[0]; for(int d = 1; d < nObj; ++d) { std::cout << "," << ordering[d]; } std::cout << ", " << nThreads << " threads left,"; std::cout << " and " << nObjLeft << " objectives left."; std::cout << std::endl; #endif for(int i = 0; i < nObj; ++i) { my_ordering[i] = ordering[i]; } int ** share_to = new int*[nObj]; int ** share_from = new int*[nObj]; int ** share_limit = new int*[nObj]; int ** share_bounds = new int*[nObj]; for(int j = 0; j < nObj; ++j) { share_to[j] = share_to_[j]; share_bounds[j] = share_bounds_[j]; share_from[j] = share_from_[j]; share_limit[j] = share_limit_[j]; } // Work out how many different objectives will occur // in position "nObjLeft - 1" int ind = nObjLeft; int ** new_shares = new int*[nObj] {nullptr}; int ** new_bounds = new int*[nObj] {nullptr}; int ** new_limit = new int*[nObj] {nullptr}; int num_sub_clusters = (ind < nThreads) ? ind : nThreads; int index = nObjLeft - 1; for(int j = 0; j < num_sub_clusters; ++j) { int pos = my_ordering[index]; new_shares[pos] = new int; new_bounds[pos] = new int; new_limit[pos] = new int; if (sense == MIN) { *new_shares[pos] = INFBOUND; *new_bounds[pos] = -INFBOUND; *new_limit[pos] = INFBOUND; } else { *new_shares[pos] = -INFBOUND; *new_bounds[pos] = INFBOUND; *new_limit[pos] = -INFBOUND; } index = (index + 1) % nObjLeft; } if (spread_threads) { // Split up threads int perCluster = nThreads / nObjLeft; int withExtra = nThreads % nObjLeft; int i; for(i = 0; i < withExtra ; ++i) { int pos = my_ordering[nObjLeft-1]; locks[pos] = new Locking_Vars(perCluster + 1); int * old_share_to = share_to[pos]; int * old_share_bounds = share_bounds[pos]; int * old_share_limit = share_limit[pos]; int ** old_from = new int*[nObj]; for(int j = 0; j < nObjLeft; ++j) { int obj = my_ordering[j]; old_from[obj] = share_from[obj]; } for(int j = 0; j < nObjLeft; ++j) { int obj = my_ordering[j]; if (obj == pos) { share_to[obj] = new_shares[obj]; share_bounds[obj] = new_bounds[obj]; share_limit[obj] = new_limit[obj]; } else { share_from[obj] = new_shares[obj]; } } Cluster(perCluster + 1, nObj, sense, spread_threads, nObjLeft - 1, my_ordering, share_to, share_from, share_bounds, share_limit, threads, locks); share_to[pos] = old_share_to; share_bounds[pos] = old_share_bounds; share_limit[pos] = old_share_limit; for(int j = 0; j < nObjLeft; ++j) { int obj = my_ordering[j]; share_from[obj] = old_from[obj]; } // Rotate ordering int first = my_ordering[0]; for (int c = 0; c < nObjLeft-1; ++c) { my_ordering[c] = my_ordering[c+1]; } my_ordering[nObjLeft - 1] = first; locks[pos] = nullptr; } if (perCluster > 0) { for( ; i < nObjLeft ; ++i) { int pos = my_ordering[nObjLeft-1]; int * old_share_to = share_to[pos]; int * old_share_bounds = share_bounds[pos]; int * old_share_limit = share_limit[pos]; locks[pos] = new Locking_Vars(perCluster); int ** old_from = new int*[nObj]; for(int j = 0; j < nObjLeft; ++j) { int obj = my_ordering[j]; old_from[obj] = share_from[obj]; } for(int j = 0; j < nObjLeft; ++j) { int obj = my_ordering[j]; if (obj == pos) { share_to[obj] = new_shares[obj]; share_bounds[obj] = new_bounds[obj]; share_limit[obj] = new_limit[obj]; } else { share_from[obj] = new_shares[obj]; } } Cluster(perCluster, nObj, sense, spread_threads, nObjLeft - 1, my_ordering, share_to, share_from, share_bounds, share_limit, threads, locks); share_to[pos] = old_share_to; share_bounds[pos] = old_share_bounds; share_limit[pos] = old_share_limit; for(int j = 0; j < nObjLeft; ++j) { int obj = my_ordering[j]; share_from[obj] = old_from[obj]; } // Rotate ordering int first = my_ordering[0]; for (int c = 0; c < nObjLeft-1; ++c) { my_ordering[c] = my_ordering[c+1]; } my_ordering[nObjLeft - 1] = first; locks[pos] = nullptr; } } } else { // grouping threads "near" each other int threads_remaining = nThreads; while (threads_remaining > 0) { int threads_to_use = (S[nObjLeft-1].size() > threads_remaining) ? threads_remaining : S[nObjLeft-1].size(); int pos = my_ordering[nObjLeft-1]; locks[pos] = new Locking_Vars(threads_to_use); int * old_share_to = share_to[pos]; int * old_share_bounds = share_bounds[pos]; int * old_share_limit = share_limit[pos]; int ** old_from = new int*[nObj]; for(int j = 0; j < nObjLeft; ++j) { int obj = my_ordering[j]; old_from[obj] = share_from[obj]; } for(int j = 0; j < nObjLeft; ++j) { int obj = my_ordering[j]; if (obj == pos) { share_to[obj] = new_shares[obj]; share_bounds[pos] = new_bounds[obj]; share_limit[obj] = new_limit[obj]; } else { share_from[obj] = new_shares[obj]; } } Cluster(threads_to_use, nObj, sense, spread_threads, nObjLeft - 1, my_ordering, share_to, share_from, share_bounds, share_limit, threads, locks); threads_remaining -= threads_to_use; share_to[pos] = old_share_to; share_bounds[pos] = old_share_bounds; share_limit[pos] = old_share_limit; for(int j = 0; j < nObjLeft; ++j) { int obj = my_ordering[j]; share_from[obj] = old_from[obj]; } // Rotate ordering int first = my_ordering[0]; for (int c = 0; c < nObjLeft-1; ++c) { my_ordering[c] = my_ordering[c+1]; } my_ordering[nObjLeft - 1] = first; locks[pos] = nullptr; } } delete[] my_ordering; delete[] new_shares; delete[] new_limit; delete[] share_to; delete[] share_from; delete[] share_limit; delete[] share_bounds; } }
Fix sharing setup
Fix sharing setup For the --spread option, when assigning threads we first use the permutation as it is given, and then if we need more permutations we rotate it cyclically. These rotations are sometimes only done on the first $n$ elements, where $n$ represents the number of objectives left to fix. This means we also need to set up the correct sharing arrays, i.e. share_to, share_from, share_bounds, share_limit. This patch fixes the creation of these arrays. index first points to the "last non-fixed" element of the permutation, but then cycles around to get the first "nObjLeft - 2" elements as well.
C++
bsd-2-clause
WPettersson/moip_aira,WPettersson/moip_aira,WPettersson/moip_aira,WPettersson/moip_aira
5c969966170009445666f129f31b5dd2a9cde30c
src/ui/download-repo-dialog.cpp
src/ui/download-repo-dialog.cpp
#include <QtGlobal> #if (QT_VERSION >= QT_VERSION_CHECK(5, 0, 0)) #include <QtWidgets> #else #include <QtGui> #endif #include <QDirIterator> #include <jansson.h> #include "account-mgr.h" #include "settings-mgr.h" #include "utils/utils.h" #include "seafile-applet.h" #include "rpc/rpc-client.h" #include "configurator.h" #include "api/requests.h" #include "api/api-error.h" #include "api/server-repo.h" #include "repo-service.h" #include "download-repo-dialog.h" namespace { const int kAlternativeTryTimes = 20; bool isPathConflictWithExistingRepo(const QString &path, QString *repo_name) { RepoService::instance()->refreshLocalRepoList(); const std::vector<LocalRepo> & repos = RepoService::instance()->localRepos(); for (unsigned i = 0; i < repos.size(); ++i) { // compare case insensitive file names as well if (QFileInfo(repos[i].worktree) == QFileInfo(path)) { *repo_name = repos[i].name; return true; } } return false; } QString getAlternativePath(const QString &dir_path, const QString &name) { QDir dir = QDir(dir_path); QFileInfo file; file = QFileInfo(dir.filePath(name)); int i; for (i = 1; i < kAlternativeTryTimes; ++i) { if (!file.exists() && dir.mkdir(file.fileName())) return file.absoluteFilePath(); file = QFileInfo(dir.filePath(name + "-" + QString::number(i))); } return QString(); } inline QString getOperatingText(const ServerRepo &repo) { if (!repo.isSubfolder()) { return QObject::tr("Sync this library to:"); } else { return QObject::tr("Sync this folder to:"); } } } // anonymous namespace DownloadRepoDialog::DownloadRepoDialog(const Account& account, const ServerRepo& repo, QWidget *parent) : QDialog(parent), repo_(repo), account_(account), has_manual_merge_mode_(seafApplet->settingsManager()->isEnableSyncingWithExistingFolder()) { manual_merge_mode_ = false; setupUi(this); if (!repo.isSubfolder()) { setWindowTitle(tr("Sync library \"%1\"").arg(repo_.name)); } else { setWindowTitle(tr("Sync folder \"%1\"").arg(repo.parent_path)); } mDirectory->setPlaceholderText(getOperatingText(repo_)); setWindowFlags(windowFlags() & ~Qt::WindowContextHelpButtonHint); mRepoIcon->setPixmap(repo.getPixmap()); mRepoName->setText(repo_.name); mOperationText->setText(tr("Sync to folder:")); if (repo_.encrypted) { mPassword->setVisible(true); mPasswordLabel->setVisible(true); } else { mPassword->setVisible(false); mPasswordLabel->setVisible(false); } int height = 250; #if defined(Q_OS_MAC) layout()->setContentsMargins(8, 9, 9, 5); layout()->setSpacing(6); verticalLayout_3->setSpacing(6); #endif if (repo.encrypted) { height += 100; } setMinimumHeight(height); setMaximumHeight(height); setDirectoryText(seafApplet->configurator()->worktreeDir()); if (!has_manual_merge_mode_) { mMergeHint->setText(tr("If a sub-folder with same name exists, its contents will be merged.")); mSwitchToSyncFrame->hide(); } else { connect(mSwitchModeHint, SIGNAL(linkActivated(const QString &)), this, SLOT(switchMode())); updateSyncMode(); mMergeHint->hide(); } connect(mChooseDirBtn, SIGNAL(clicked()), this, SLOT(chooseDirAction())); connect(mOkBtn, SIGNAL(clicked()), this, SLOT(onOkBtnClicked())); } void DownloadRepoDialog::switchMode() { manual_merge_mode_ = !manual_merge_mode_; updateSyncMode(); } void DownloadRepoDialog::updateSyncMode() { QString switch_hint_text; QString op_text; const QString link_template = "<a style=\"color:#FF9A2A\" href=\"#\">%1</a>"; QString OR = tr("or"); if (!manual_merge_mode_) { op_text = getOperatingText(repo_); sync_with_existing_ = false; QString link = link_template.arg(tr("sync with an existing folder")); switch_hint_text = QString("%1 %2").arg(OR).arg(link); } else { QString link = link_template.arg(tr("create a new sync folder")); switch_hint_text = QString("%1 %2").arg(OR).arg(link); sync_with_existing_ = true; op_text = tr("Sync with this existing folder:"); if (!alternative_path_.isNull()) { setDirectoryText(alternative_path_); } } mOperationText->setText(op_text); mSwitchModeHint->setText(switch_hint_text); } void DownloadRepoDialog::setDirectoryText(const QString& path) { QString text = path; if (text.endsWith("/")) { text.resize(text.size() - 1); } mDirectory->setText(text); if (has_manual_merge_mode_ && manual_merge_mode_) { alternative_path_ = text; } } void DownloadRepoDialog::chooseDirAction() { const QString &wt = seafApplet->configurator()->worktreeDir(); QString dir = QFileDialog::getExistingDirectory(this, tr("Please choose a folder"), wt.toUtf8().data(), QFileDialog::ShowDirsOnly | QFileDialog::DontResolveSymlinks); if (dir.isEmpty()) return; setDirectoryText(dir); } void DownloadRepoDialog::onOkBtnClicked() { if (!validateInputs()) { return; } setAllInputsEnabled(false); DownloadRepoRequest *req = new DownloadRepoRequest(account_, repo_.id, repo_.readonly); connect(req, SIGNAL(success(const RepoDownloadInfo&)), this, SLOT(onDownloadRepoRequestSuccess(const RepoDownloadInfo&))); connect(req, SIGNAL(failed(const ApiError&)), this, SLOT(onDownloadRepoRequestFailed(const ApiError&))); req->send(); } bool DownloadRepoDialog::validateInputsManualMergeMode() { setDirectoryText(mDirectory->text().trimmed()); if (mDirectory->text().isEmpty()) { QMessageBox::warning(this, getBrand(), tr("Please choose the folder to sync"), QMessageBox::Ok); return false; } QDir dir(mDirectory->text()); if (!dir.exists()) { QMessageBox::warning(this, getBrand(), tr("The folder does not exist"), QMessageBox::Ok); return false; } if (repo_.encrypted) { mPassword->setText(mPassword->text().trimmed()); if (mPassword->text().isEmpty()) { QMessageBox::warning(this, getBrand(), tr("Please enter the password"), QMessageBox::Ok); return false; } } return true; } bool DownloadRepoDialog::validateInputs() { if (has_manual_merge_mode_ && manual_merge_mode_) { return validateInputsManualMergeMode(); } setDirectoryText(mDirectory->text().trimmed()); if (mDirectory->text().isEmpty()) { QMessageBox::warning(this, getBrand(), tr("Please choose the folder to sync."), QMessageBox::Ok); return false; } sync_with_existing_ = false; alternative_path_ = QString(); QString path = QDir(mDirectory->text()).absoluteFilePath(repo_.name); QFileInfo fileinfo = QFileInfo(path); if (fileinfo.exists()) { sync_with_existing_ = true; // exist and but not a directory ? if (!fileinfo.isDir()) { QMessageBox::warning(this, getBrand(), tr("Conflicting with existing file \"%1\", please choose a different folder.").arg(path), QMessageBox::Ok); return false; } // exist and but conflicting? QString repo_name; if (isPathConflictWithExistingRepo(path, &repo_name)) { QMessageBox::warning(this, getBrand(), tr("Conflicting with existing library \"%1\", please choose a different folder.").arg(repo_name), QMessageBox::Ok); return false; } int ret = QMessageBox::question( this, getBrand(), tr("Are you sure to sync with the existing folder \"%1\"?") .arg(path) + QString("<br/><small>%1</small>").arg(tr("Click No to sync with a new folder instead")), QMessageBox::Yes | QMessageBox::No | QMessageBox::Cancel, QMessageBox::Yes); if (ret & QMessageBox::Cancel) return false; if (ret & QMessageBox::No) { QString new_path = getAlternativePath(mDirectory->text(), repo_.name); if (new_path.isEmpty()) { QMessageBox::warning(this, getBrand(), tr("Unable to find an alternative folder name").arg(path), QMessageBox::Ok); return false; } alternative_path_ = new_path; } } if (repo_.encrypted) { mPassword->setText(mPassword->text().trimmed()); if (mPassword->text().isEmpty()) { QMessageBox::warning(this, getBrand(), tr("Please enter the password"), QMessageBox::Ok); return false; } } return true; } void DownloadRepoDialog::setAllInputsEnabled(bool enabled) { mDirectory->setEnabled(enabled); mChooseDirBtn->setEnabled(enabled); mPassword->setEnabled(enabled); mOkBtn->setEnabled(enabled); } void DownloadRepoDialog::onDownloadRepoRequestSuccess(const RepoDownloadInfo& info) { QString worktree = mDirectory->text(); QString password = repo_.encrypted ? mPassword->text() : QString(); int ret = 0; QString error; if (sync_with_existing_) { if (alternative_path_.isEmpty()) worktree = QDir(worktree).absoluteFilePath(repo_.name); else worktree = alternative_path_; ret = seafApplet->rpcClient()->cloneRepo(info.repo_id, info.repo_version, info.relay_id, repo_.name, worktree, info.token, password, info.magic, info.relay_addr, info.relay_port, info.email, info.random_key, info.enc_version, info.more_info, &error); } else { ret = seafApplet->rpcClient()->downloadRepo(info.repo_id, info.repo_version, info.relay_id, repo_.name, worktree, info.token, password, info.magic, info.relay_addr, info.relay_port, info.email, info.random_key, info.enc_version, info.more_info, &error); } if (ret < 0) { QMessageBox::warning(this, getBrand(), tr("Failed to add download task:\n %1").arg(error), QMessageBox::Ok); setAllInputsEnabled(true); } else { done(QDialog::Accepted); } } void DownloadRepoDialog::onDownloadRepoRequestFailed(const ApiError& error) { QString msg = tr("Failed to get repo download information:\n%1").arg(error.toString()); seafApplet->warningBox(msg, this); setAllInputsEnabled(true); } void DownloadRepoDialog::setMergeWithExisting(const QString& localPath) { setDirectoryText(localPath); }
#include <QtGlobal> #if (QT_VERSION >= QT_VERSION_CHECK(5, 0, 0)) #include <QtWidgets> #else #include <QtGui> #endif #include <QDirIterator> #include <jansson.h> #include "account-mgr.h" #include "settings-mgr.h" #include "utils/utils.h" #include "seafile-applet.h" #include "rpc/rpc-client.h" #include "configurator.h" #include "api/requests.h" #include "api/api-error.h" #include "api/server-repo.h" #include "repo-service.h" #include "download-repo-dialog.h" namespace { const int kAlternativeTryTimes = 20; bool isPathConflictWithExistingRepo(const QString &path, QString *repo_name) { RepoService::instance()->refreshLocalRepoList(); const std::vector<LocalRepo> & repos = RepoService::instance()->localRepos(); for (unsigned i = 0; i < repos.size(); ++i) { // compare case insensitive file names as well if (QFileInfo(repos[i].worktree) == QFileInfo(path)) { *repo_name = repos[i].name; return true; } } return false; } QString getAlternativePath(const QString &dir_path, const QString &name) { QDir dir = QDir(dir_path); QFileInfo file; file = QFileInfo(dir.filePath(name)); int i; for (i = 1; i < kAlternativeTryTimes; ++i) { if (!file.exists() && dir.mkdir(file.fileName())) return file.absoluteFilePath(); file = QFileInfo(dir.filePath(name + "-" + QString::number(i))); } return QString(); } inline QString getOperatingText(const ServerRepo &repo) { if (!repo.isSubfolder()) { return QObject::tr("Sync this library to:"); } else { return QObject::tr("Sync this folder to:"); } } } // anonymous namespace DownloadRepoDialog::DownloadRepoDialog(const Account& account, const ServerRepo& repo, QWidget *parent) : QDialog(parent), repo_(repo), account_(account), has_manual_merge_mode_(seafApplet->settingsManager()->isEnableSyncingWithExistingFolder()) { manual_merge_mode_ = false; setupUi(this); if (!repo.isSubfolder()) { setWindowTitle(tr("Sync library \"%1\"").arg(repo_.name)); } else { setWindowTitle(tr("Sync folder \"%1\"").arg(repo.parent_path)); } mDirectory->setPlaceholderText(getOperatingText(repo_)); setWindowFlags(windowFlags() & ~Qt::WindowContextHelpButtonHint); mRepoIcon->setPixmap(repo.getPixmap()); mRepoName->setText(repo_.name); mOperationText->setText(tr("Sync to folder:")); if (repo_.encrypted) { mPassword->setVisible(true); mPasswordLabel->setVisible(true); } else { mPassword->setVisible(false); mPasswordLabel->setVisible(false); } int height = 250; #if defined(Q_OS_MAC) layout()->setContentsMargins(8, 9, 9, 5); layout()->setSpacing(6); verticalLayout_3->setSpacing(6); #endif if (repo.encrypted) { height += 100; } setMinimumHeight(height); setMaximumHeight(height); setDirectoryText(seafApplet->configurator()->worktreeDir()); if (!has_manual_merge_mode_) { mMergeHint->setText(tr("If a sub-folder with same name exists, its contents will be merged.")); mSwitchToSyncFrame->hide(); } else { connect(mSwitchModeHint, SIGNAL(linkActivated(const QString &)), this, SLOT(switchMode())); updateSyncMode(); mMergeHint->hide(); } connect(mChooseDirBtn, SIGNAL(clicked()), this, SLOT(chooseDirAction())); connect(mOkBtn, SIGNAL(clicked()), this, SLOT(onOkBtnClicked())); } void DownloadRepoDialog::switchMode() { manual_merge_mode_ = !manual_merge_mode_; updateSyncMode(); } void DownloadRepoDialog::updateSyncMode() { QString switch_hint_text; QString op_text; const QString link_template = "<a style=\"color:#FF9A2A\" href=\"#\">%1</a>"; QString OR = tr("or"); if (!manual_merge_mode_) { op_text = getOperatingText(repo_); sync_with_existing_ = false; QString link = link_template.arg(tr("sync with an existing folder")); switch_hint_text = QString("%1 %2").arg(OR).arg(link); } else { QString link = link_template.arg(tr("create a new sync folder")); switch_hint_text = QString("%1 %2").arg(OR).arg(link); sync_with_existing_ = true; op_text = tr("Sync with this existing folder:"); if (!alternative_path_.isNull()) { setDirectoryText(alternative_path_); } } mOperationText->setText(op_text); mSwitchModeHint->setText(switch_hint_text); } void DownloadRepoDialog::setDirectoryText(const QString& path) { QString text = path; if (text.endsWith("/")) { text.resize(text.size() - 1); } mDirectory->setText(text); if (has_manual_merge_mode_ && manual_merge_mode_) { alternative_path_ = text; } } void DownloadRepoDialog::chooseDirAction() { const QString &wt = seafApplet->configurator()->worktreeDir(); QString dir = QFileDialog::getExistingDirectory(this, tr("Please choose a folder"), wt.toUtf8().data(), QFileDialog::ShowDirsOnly | QFileDialog::DontResolveSymlinks); if (dir.isEmpty()) return; setDirectoryText(dir); } void DownloadRepoDialog::onOkBtnClicked() { if (!validateInputs()) { return; } setAllInputsEnabled(false); DownloadRepoRequest *req = new DownloadRepoRequest(account_, repo_.id, repo_.readonly); connect(req, SIGNAL(success(const RepoDownloadInfo&)), this, SLOT(onDownloadRepoRequestSuccess(const RepoDownloadInfo&))); connect(req, SIGNAL(failed(const ApiError&)), this, SLOT(onDownloadRepoRequestFailed(const ApiError&))); req->send(); } bool DownloadRepoDialog::validateInputsManualMergeMode() { setDirectoryText(mDirectory->text().trimmed()); if (mDirectory->text().isEmpty()) { QMessageBox::warning(this, getBrand(), tr("Please choose the folder to sync"), QMessageBox::Ok); return false; } QDir dir(mDirectory->text()); if (!dir.exists()) { QMessageBox::warning(this, getBrand(), tr("The folder does not exist"), QMessageBox::Ok); return false; } if (repo_.encrypted) { mPassword->setText(mPassword->text().trimmed()); if (mPassword->text().isEmpty()) { QMessageBox::warning(this, getBrand(), tr("Please enter the password"), QMessageBox::Ok); return false; } } return true; } bool DownloadRepoDialog::validateInputs() { if (has_manual_merge_mode_ && manual_merge_mode_) { return validateInputsManualMergeMode(); } setDirectoryText(mDirectory->text().trimmed()); if (mDirectory->text().isEmpty()) { QMessageBox::warning(this, getBrand(), tr("Please choose the folder to sync."), QMessageBox::Ok); return false; } sync_with_existing_ = false; alternative_path_ = QString(); QString path = QDir(mDirectory->text()).absoluteFilePath(repo_.name); QFileInfo fileinfo = QFileInfo(path); if (fileinfo.exists()) { sync_with_existing_ = true; // exist and but not a directory ? if (!fileinfo.isDir()) { QMessageBox::warning(this, getBrand(), tr("Conflicting with existing file \"%1\", please choose a different folder.").arg(path), QMessageBox::Ok); return false; } // exist and but conflicting? QString repo_name; if (isPathConflictWithExistingRepo(path, &repo_name)) { QMessageBox::warning(this, getBrand(), tr("Conflicting with existing library \"%1\", please choose a different folder.").arg(repo_name), QMessageBox::Ok); return false; } int ret = QMessageBox::question( this, getBrand(), tr("The folder \"%1\" already exists. Are you sure to sync with it (contents will be merged)?") .arg(path) + QString("<br/><br/><small>%1</small>").arg(tr("Click No to sync with a new folder instead")), QMessageBox::Yes | QMessageBox::No | QMessageBox::Cancel, QMessageBox::Yes); if (ret & QMessageBox::Cancel) return false; if (ret & QMessageBox::No) { QString new_path = getAlternativePath(mDirectory->text(), repo_.name); if (new_path.isEmpty()) { QMessageBox::warning(this, getBrand(), tr("Unable to find an alternative folder name").arg(path), QMessageBox::Ok); return false; } alternative_path_ = new_path; } } if (repo_.encrypted) { mPassword->setText(mPassword->text().trimmed()); if (mPassword->text().isEmpty()) { QMessageBox::warning(this, getBrand(), tr("Please enter the password"), QMessageBox::Ok); return false; } } return true; } void DownloadRepoDialog::setAllInputsEnabled(bool enabled) { mDirectory->setEnabled(enabled); mChooseDirBtn->setEnabled(enabled); mPassword->setEnabled(enabled); mOkBtn->setEnabled(enabled); } void DownloadRepoDialog::onDownloadRepoRequestSuccess(const RepoDownloadInfo& info) { QString worktree = mDirectory->text(); QString password = repo_.encrypted ? mPassword->text() : QString(); int ret = 0; QString error; if (sync_with_existing_) { if (alternative_path_.isEmpty()) worktree = QDir(worktree).absoluteFilePath(repo_.name); else worktree = alternative_path_; ret = seafApplet->rpcClient()->cloneRepo(info.repo_id, info.repo_version, info.relay_id, repo_.name, worktree, info.token, password, info.magic, info.relay_addr, info.relay_port, info.email, info.random_key, info.enc_version, info.more_info, &error); } else { ret = seafApplet->rpcClient()->downloadRepo(info.repo_id, info.repo_version, info.relay_id, repo_.name, worktree, info.token, password, info.magic, info.relay_addr, info.relay_port, info.email, info.random_key, info.enc_version, info.more_info, &error); } if (ret < 0) { QMessageBox::warning(this, getBrand(), tr("Failed to add download task:\n %1").arg(error), QMessageBox::Ok); setAllInputsEnabled(true); } else { done(QDialog::Accepted); } } void DownloadRepoDialog::onDownloadRepoRequestFailed(const ApiError& error) { QString msg = tr("Failed to get repo download information:\n%1").arg(error.toString()); seafApplet->warningBox(msg, this); setAllInputsEnabled(true); } void DownloadRepoDialog::setMergeWithExisting(const QString& localPath) { setDirectoryText(localPath); }
tweak download repo dialog's words
ui: tweak download repo dialog's words
C++
apache-2.0
lucius-feng/seafile-client,haiwen/seafile-client,lucius-feng/seafile-client,daodaoliang/seafile-client,wgaalves/seafile-client,daodaoliang/seafile-client,daodaoliang/seafile-client,haiwen/seafile-client,haiwen/seafile-client,lucius-feng/seafile-client,losingle/seafile-client,losingle/seafile-client,losingle/seafile-client,wgaalves/seafile-client,wgaalves/seafile-client,losingle/seafile-client,daodaoliang/seafile-client,lucius-feng/seafile-client,wgaalves/seafile-client,haiwen/seafile-client
eb97c5c3c35400b149b9310dcc0c8757a8b030b8
src/vw/Plate/SnapshotManager.cc
src/vw/Plate/SnapshotManager.cc
// __BEGIN_LICENSE__ // Copyright (C) 2006-2011 United States Government as represented by // the Administrator of the National Aeronautics and Space Administration. // All Rights Reserved. // __END_LICENSE__ #include <vw/Plate/SnapshotManager.h> #include <vw/Plate/PlateFile.h> #include <vw/Plate/TileManipulation.h> #include <vw/Mosaic/ImageComposite.h> #include <vw/Image/ImageView.h> #include <boost/foreach.hpp> #include <boost/assign/list_of.hpp> #include <set> namespace { using namespace vw; using namespace vw::platefile; typedef boost::tuple<uint32, uint32, uint32> rowcoltid_t; typedef boost::tuple<uint32, uint32> rowcol_t; typedef boost::tuple<uint32, rowcoltid_t> tile_order_t; BBox2i move_down(const BBox2i& input, uint32 level_change) { return input * (1 << level_change); } rowcol_t parent_tile(const uint32 row, const uint32 col) { return rowcol_t(row/2, col/2); } struct CmpTuple { template <typename T1, typename T2> bool operator()(const boost::tuple<T1, T2>& a, const boost::tuple<T1, T2>& b) const { if (a.get<0>() != b.get<0>()) return a.get<0>() < b.get<0>(); return a.get<1>() < b.get<1>(); } template <typename T1, typename T2, typename T3> bool operator()(const boost::tuple<T1, T2, T3>& a, const boost::tuple<T1, T2, T3>& b) const { if (a.get<0>() != b.get<0>()) return a.get<0>() < b.get<0>(); else if (a.get<1>() != b.get<1>()) return a.get<1>() < b.get<1>(); return a.get<2>() < b.get<2>(); } }; // given a parent tile (1 level up) and a hdr, calculate the composite id; // [0==UL, 1==UR, 2==LL, 3==LR] uint32 calc_composite_id(const rowcol_t& parent, const TileHeader& hdr) { typedef std::map<rowcol_t, uint32, CmpTuple> map_t; static const map_t lookup = boost::assign::map_list_of (rowcol_t(0,0), 0) (rowcol_t(0,1), 1) (rowcol_t(1,0), 2) (rowcol_t(1,1), 3); rowcol_t offset(hdr.row() - parent.get<0>() * 2, hdr.col() - parent.get<1>() * 2); map_t::const_iterator i = lookup.find(offset); VW_ASSERT(i != lookup.end(), LogicErr() << "Cannot determine composite id for hdr " << hdr << " and parent " << parent.get<1>() << "," << parent.get<0>()); return i->second; } struct SortByTidDesc { bool operator()(const tile_order_t& a, const tile_order_t& b) { return b.get<0>() < a.get<0>(); } }; // row, col at target level, tile headers from next level down (sorted in Tid order) typedef std::map<rowcol_t, std::vector<tile_order_t>, CmpTuple> composite_map_t; // Cache of parsed images template <typename PixelT> struct tile_cache_t : public std::map<rowcoltid_t, ImageView<PixelT>, CmpTuple> {}; // composite_order_override lets you override the composite order void schedule_tile(const TileHeader& hdr, std::vector<tile_order_t>& stack, Datastore::TileSearch& tile_lookup, uint32 order) { stack.push_back(boost::make_tuple(order, rowcoltid_t(hdr.row(), hdr.col(), hdr.transaction_id()))); tile_lookup.push_back(hdr); } template <typename PixelT> void parse_image_and_store(const Tile& t, tile_cache_t<PixelT>& tile_cache) { ImageView<PixelT>& image = tile_cache[rowcoltid_t(t.hdr.row(), t.hdr.col(), t.hdr.transaction_id())]; boost::scoped_ptr<SrcImageResource> r(SrcMemoryImageResource::open(t.hdr.filetype(), &t.data->operator[](0), t.data->size())); read_image(image, *r); } } // anon namespace vw { namespace platefile { std::ostream& operator<<(std::ostream& o, const rowcoltid_t& hdr) { return (o << hdr.get<1>() << "," << hdr.get<0>() << " (t_id = " << hdr.get<2>() << ")"); } template <class PixelT> void SnapshotManager<PixelT>::snapshot(uint32 level, BBox2i const& tile_region, TransactionRange range) const { typedef ImageView<PixelT> image_t; // Divide up the region into moderately-sized chunks BOOST_FOREACH(const BBox2i& region, bbox_tiles(tile_region, 1024, 1024)) { // Declare these inside the loop so we keep the memory use down to a dull roar // This map holds the headers for the parent/dest tiles and the tiles used to generate them composite_map_t composite_map; // This map holds the headers for the parent/dest tiles and the tiles that are a level below that need to be composed and downsampled first // The key is parent tile (same as the composite_map) and the value is a // 4-elt vector, the index of which identifies where to compose the image // [i.e. 0==UL, 1==UR, 2==LL, 3==LR] composite_map_t intermediate_map; tile_cache_t<PixelT> tile_cache; { // List of tiles we need to fetch Datastore::TileSearch tile_lookup; // Grab the tiles in the zone BOOST_FOREACH(const TileHeader& hdr, m_platefile->search_by_region(level, region, range)) schedule_tile(hdr, composite_map[rowcol_t(hdr.row(), hdr.col())], tile_lookup, hdr.transaction_id()); // Grab the result of the previous level snapshot BOOST_FOREACH(const TileHeader& hdr, m_platefile->search_by_region(level+1, move_down(region, 1), TransactionRange(m_platefile->transaction_id()))) { rowcol_t parent = parent_tile(hdr.row(), hdr.col()); uint32 composite_id = calc_composite_id(parent, hdr); schedule_tile(hdr, intermediate_map[parent], tile_lookup, composite_id); } // Now load the images from disk, decode them, and store them back to the cache BOOST_FOREACH(const Tile& t, m_platefile->batch_read(tile_lookup)) parse_image_and_store(t, tile_cache); // Now look up all the child tiles, and compose/downsample them to the target layer BOOST_FOREACH(const composite_map_t::value_type& t, intermediate_map) { const rowcol_t dest_loc(t.first.get<0>(), t.first.get<1>()); const rowcoltid_t dest_loc_tid(t.first.get<0>(), t.first.get<1>(), 0); const std::vector<tile_order_t>& children = t.second; VW_ASSERT(children.size() > 0, LogicErr() << "How can there be zero here?"); VW_ASSERT(children.size() <= 4, LogicErr() << "How can there be more than four here?"); std::map<uint32, image_t> c; BOOST_FOREACH(const tile_order_t& order, children) c[order.get<0>()] = tile_cache[order.get<1>()]; // use tid 0 as the dest, to make sure it ends up under the other tiles mipmap_one_tile(tile_cache[dest_loc_tid], m_platefile->default_tile_size(), c[0], c[1], c[2], c[3]); composite_map[dest_loc].push_back(boost::make_tuple(0, dest_loc_tid)); } } // now iterate the output tile set and create the composites BOOST_FOREACH(composite_map_t::value_type& t, composite_map) { std::sort(t.second.begin(), t.second.end(), SortByTidDesc()); mosaic::ImageComposite<PixelT> composite; composite.set_draft_mode(true); // Insert the images into the composite from highest to lowest tid (already sorted due to sort_heap) BOOST_FOREACH(const tile_order_t& order, t.second) { const rowcoltid_t& hdr = order.get<1>(); image_t& img = tile_cache[rowcoltid_t(hdr.get<0>(), hdr.get<1>(), hdr.get<2>())]; if (!img) { vw_out(WarningMessage, "platefile.snapshot") << "Failed to load image for " << hdr << std::endl; continue; } composite.insert(img, 0, 0); if (is_opaque(img)) break; } if (composite.cols() == 0 || composite.rows() == 0) { vw_out(WarningMessage, "platefile.snapshot") << "Empty tile list, skipping writing tile row=" << t.first.get<0>() << " col=" << t.first.get<1>() << std::endl; continue; } composite.prepare(BBox2i(0,0,m_platefile->default_tile_size(), m_platefile->default_tile_size())); image_t tile = composite; m_platefile->write_update(tile, t.first.get<1>(), t.first.get<0>(), level); } } } // Create a full snapshot of every level and every region in the mosaic. template <class PixelT> void SnapshotManager<PixelT>::full_snapshot(TransactionRange read_transaction_range) const { for (uint32 level = 0; level < m_platefile->num_levels(); ++level) { // For debugging: // for (int level = 0; level < 10; ++level) { // Snapshot the entire region at each level. These region will be // broken down into smaller work units in snapshot(). uint32 region_size = 1 << level; uint32 subdivided_region_size = region_size / 16; if (subdivided_region_size < 1024) subdivided_region_size = 1024; BBox2i full_region(0,0,region_size,region_size); std::list<BBox2i> workunits = bbox_tiles(full_region, subdivided_region_size, subdivided_region_size); for ( std::list<BBox2i>::iterator region_iter = workunits.begin(); region_iter != workunits.end(); ++region_iter) { snapshot(level, *region_iter, read_transaction_range); } } } }} // namespace vw::platefile // Explicit template instatiation #define _VW_INSTANTIATE(Px)\ template\ void vw::platefile::SnapshotManager<Px >::snapshot(uint32 level, BBox2i const& bbox, TransactionRange) const;\ template\ void vw::platefile::SnapshotManager<Px >::full_snapshot(TransactionRange) const; _VW_INSTANTIATE(vw::PixelGrayA<vw::uint8>); _VW_INSTANTIATE(vw::PixelGrayA<vw::int16>); _VW_INSTANTIATE(vw::PixelGrayA<vw::float32>); _VW_INSTANTIATE(vw::PixelRGBA<vw::uint8>);
// __BEGIN_LICENSE__ // Copyright (C) 2006-2011 United States Government as represented by // the Administrator of the National Aeronautics and Space Administration. // All Rights Reserved. // __END_LICENSE__ #include <vw/Plate/SnapshotManager.h> #include <vw/Plate/PlateFile.h> #include <vw/Plate/TileManipulation.h> #include <vw/Mosaic/ImageComposite.h> #include <vw/Image/ImageView.h> #include <boost/foreach.hpp> #include <boost/assign/list_of.hpp> #include <set> namespace { using namespace vw; using namespace vw::platefile; typedef boost::tuple<uint32, uint32, uint32> rowcoltid_t; typedef boost::tuple<uint32, uint32> rowcol_t; typedef boost::tuple<uint32, rowcoltid_t> tile_order_t; BBox2i move_down(const BBox2i& input, uint32 level_change) { return input * (1 << level_change); } rowcol_t parent_tile(const uint32 row, const uint32 col) { return rowcol_t(row/2, col/2); } struct CmpTuple { template <typename T1, typename T2> bool operator()(const boost::tuple<T1, T2>& a, const boost::tuple<T1, T2>& b) const { if (a.get<0>() != b.get<0>()) return a.get<0>() < b.get<0>(); return a.get<1>() < b.get<1>(); } template <typename T1, typename T2, typename T3> bool operator()(const boost::tuple<T1, T2, T3>& a, const boost::tuple<T1, T2, T3>& b) const { if (a.get<0>() != b.get<0>()) return a.get<0>() < b.get<0>(); else if (a.get<1>() != b.get<1>()) return a.get<1>() < b.get<1>(); return a.get<2>() < b.get<2>(); } }; // given a parent tile (1 level up) and a hdr, calculate the composite id; // [0==UL, 1==UR, 2==LL, 3==LR] uint32 calc_composite_id(const rowcol_t& parent, const TileHeader& hdr) { typedef std::map<rowcol_t, uint32, CmpTuple> map_t; static const map_t lookup = boost::assign::map_list_of (rowcol_t(0,0), 0) (rowcol_t(0,1), 1) (rowcol_t(1,0), 2) (rowcol_t(1,1), 3); rowcol_t offset(hdr.row() - parent.get<0>() * 2, hdr.col() - parent.get<1>() * 2); map_t::const_iterator i = lookup.find(offset); VW_ASSERT(i != lookup.end(), LogicErr() << "Cannot determine composite id for hdr " << hdr << " and parent " << parent.get<1>() << "," << parent.get<0>()); return i->second; } struct SortByTidDesc { bool operator()(const tile_order_t& a, const tile_order_t& b) { return b.get<0>() < a.get<0>(); } }; // row, col at target level, tile headers from next level down (sorted in Tid order) typedef std::map<rowcol_t, std::vector<tile_order_t>, CmpTuple> composite_map_t; // Cache of parsed images template <typename PixelT> struct tile_cache_t : public std::map<rowcoltid_t, ImageView<PixelT>, CmpTuple> {}; // composite_order_override lets you override the composite order void schedule_tile(const TileHeader& hdr, std::vector<tile_order_t>& stack, Datastore::TileSearch& tile_lookup, uint32 order) { stack.push_back(boost::make_tuple(order, rowcoltid_t(hdr.row(), hdr.col(), hdr.transaction_id()))); tile_lookup.push_back(hdr); } template <typename PixelT> void parse_image_and_store(const Tile& t, tile_cache_t<PixelT>& tile_cache) { ImageView<PixelT>& image = tile_cache[rowcoltid_t(t.hdr.row(), t.hdr.col(), t.hdr.transaction_id())]; boost::scoped_ptr<SrcImageResource> r(SrcMemoryImageResource::open(t.hdr.filetype(), &t.data->operator[](0), t.data->size())); read_image(image, *r); } } // anon namespace vw { namespace platefile { std::ostream& operator<<(std::ostream& o, const rowcoltid_t& hdr) { return (o << hdr.get<1>() << "," << hdr.get<0>() << " (t_id = " << hdr.get<2>() << ")"); } template <class PixelT> void SnapshotManager<PixelT>::snapshot(uint32 level, BBox2i const& tile_region, TransactionRange range) const { typedef ImageView<PixelT> image_t; // Divide up the region into moderately-sized chunks BOOST_FOREACH(const BBox2i& region, bbox_tiles(tile_region, 1024, 1024)) { // Declare these inside the loop so we keep the memory use down to a dull roar // This map holds the headers for the parent/dest tiles and the tiles used to generate them composite_map_t composite_map; // This map holds the headers for the parent/dest tiles and the tiles that are a level below that need to be composed and downsampled first // The key is parent tile (same as the composite_map) and the value is a // 4-elt vector, the index of which identifies where to compose the image // [i.e. 0==UL, 1==UR, 2==LL, 3==LR] composite_map_t intermediate_map; tile_cache_t<PixelT> tile_cache; { // List of tiles we need to fetch Datastore::TileSearch tile_lookup; // Grab the tiles in the zone BOOST_FOREACH(const TileHeader& hdr, m_platefile->search_by_region(level, region, range)) schedule_tile(hdr, composite_map[rowcol_t(hdr.row(), hdr.col())], tile_lookup, hdr.transaction_id()); // Grab the result of the previous level snapshot BOOST_FOREACH(const TileHeader& hdr, m_platefile->search_by_region(level+1, move_down(region, 1), TransactionRange(m_platefile->transaction_id()))) { rowcol_t parent = parent_tile(hdr.row(), hdr.col()); uint32 composite_id = calc_composite_id(parent, hdr); schedule_tile(hdr, intermediate_map[parent], tile_lookup, composite_id); } // Now load the images from disk, decode them, and store them back to the cache BOOST_FOREACH(const Tile& t, m_platefile->batch_read(tile_lookup)) parse_image_and_store(t, tile_cache); // Now look up all the child tiles, and compose/downsample them to the target layer BOOST_FOREACH(const composite_map_t::value_type& t, intermediate_map) { const rowcol_t dest_loc(t.first.get<0>(), t.first.get<1>()); const rowcoltid_t dest_loc_tid(t.first.get<0>(), t.first.get<1>(), 0); const std::vector<tile_order_t>& children = t.second; VW_ASSERT(children.size() > 0, LogicErr() << "How can there be zero here?"); VW_ASSERT(children.size() <= 4, LogicErr() << "How can there be more than four here?"); std::map<uint32, image_t> c; BOOST_FOREACH(const tile_order_t& order, children) c[order.get<0>()] = tile_cache[order.get<1>()]; // use tid 0 as the dest, to make sure it ends up under the other tiles mipmap_one_tile(tile_cache[dest_loc_tid], m_platefile->default_tile_size(), c[0], c[1], c[2], c[3]); composite_map[dest_loc].push_back(boost::make_tuple(0, dest_loc_tid)); } } // now iterate the output tile set and create the composites BOOST_FOREACH(composite_map_t::value_type& t, composite_map) { std::sort(t.second.begin(), t.second.end(), SortByTidDesc()); mosaic::ImageComposite<PixelT> composite; composite.set_draft_mode(true); // Insert the images into the composite from highest to lowest tid (already sorted due to sort_heap) BOOST_FOREACH(const tile_order_t& order, t.second) { const rowcoltid_t& hdr = order.get<1>(); image_t& img = tile_cache[rowcoltid_t(hdr.get<0>(), hdr.get<1>(), hdr.get<2>())]; if (!img) { vw_out(WarningMessage, "platefile.snapshot") << "Failed to load image for " << hdr << std::endl; continue; } composite.insert(img, 0, 0); if (is_opaque(img)) break; } if (composite.cols() == 0 || composite.rows() == 0) { vw_out(WarningMessage, "platefile.snapshot") << "Empty tile list, skipping writing tile row=" << t.first.get<0>() << " col=" << t.first.get<1>() << std::endl; continue; } composite.prepare(BBox2i(0,0,m_platefile->default_tile_size(), m_platefile->default_tile_size())); image_t tile = composite; m_platefile->write_update(tile, t.first.get<1>(), t.first.get<0>(), level); } } } // Create a full snapshot of every level and every region in the mosaic. template <class PixelT> void SnapshotManager<PixelT>::full_snapshot(TransactionRange read_transaction_range) const { for (int32 level = m_platefile->num_levels()-1; level >= 0; --level) snapshot(level, move_down(BBox2i(0,0,1,1), level), read_transaction_range); } }} // namespace vw::platefile // Explicit template instatiation #define _VW_INSTANTIATE(Px)\ template\ void vw::platefile::SnapshotManager<Px >::snapshot(uint32 level, BBox2i const& bbox, TransactionRange) const;\ template\ void vw::platefile::SnapshotManager<Px >::full_snapshot(TransactionRange) const; _VW_INSTANTIATE(vw::PixelGrayA<vw::uint8>); _VW_INSTANTIATE(vw::PixelGrayA<vw::int16>); _VW_INSTANTIATE(vw::PixelGrayA<vw::float32>); _VW_INSTANTIATE(vw::PixelRGBA<vw::uint8>);
make full_snapshot only iterate levels
make full_snapshot only iterate levels let snapshot do the breakdown
C++
apache-2.0
fengzhyuan/visionworkbench,fengzhyuan/visionworkbench,AveRapina/visionworkbench,AveRapina/visionworkbench,DougFirErickson/visionworkbench,AveRapina/visionworkbench,fengzhyuan/visionworkbench,AveRapina/visionworkbench,DougFirErickson/visionworkbench,DougFirErickson/visionworkbench,fengzhyuan/visionworkbench,DougFirErickson/visionworkbench,AveRapina/visionworkbench,AveRapina/visionworkbench,DougFirErickson/visionworkbench,fengzhyuan/visionworkbench,fengzhyuan/visionworkbench,fengzhyuan/visionworkbench,DougFirErickson/visionworkbench
0b99c313e82e58aa28434a531b323d5639de5604
src/watcherd/messageHandler.cpp
src/watcherd/messageHandler.cpp
#include <boost/cast.hpp> #include "messageHandler.h" #include <libwatcher/messageStatus.h> using namespace std; using namespace watcher; using namespace watcher::event; using namespace boost; INIT_LOGGER(MessageHandler, "MessageHandler"); MessageHandler::MessageHandler() { TRACE_ENTER(); TRACE_EXIT(); } MessageHandler::~MessageHandler() { TRACE_ENTER(); TRACE_EXIT(); } MessageHandler::ConnectionCommand MessageHandler::produceReply(const MessagePtr &request, MessagePtr &reply) { TRACE_ENTER(); LOG_DEBUG("Producing reply for message: " << *request); reply=MessageStatusPtr(new MessageStatus(MessageStatus::status_ack)); LOG_DEBUG("Produced reply: " << *reply); TRACE_EXIT_RET("writeMessage"); return writeMessage; } MessageHandler::ConnectionCommand MessageHandler::handleReply(const MessagePtr &request, const MessagePtr &reply) { TRACE_ENTER(); LOG_INFO("Recv'd :" << "\n\t" << *reply << endl << "In reply to: " << "\n\t" << *request); if (reply->type != MESSAGE_STATUS_TYPE) { LOG_WARN("Got a non-message status message in reply."); TRACE_EXIT_RET("closeConnection"); return closeConnection; } MessageStatusPtr mess=boost::dynamic_pointer_cast<MessageStatus>(reply); if(mess->status!=MessageStatus::status_ack && mess->status!=MessageStatus::status_ok) { LOG_WARN("Recv'd non ack reply to request: " << MessageStatus::statusToString(mess->status)); } else { LOG_INFO("Recv'd ack to request, all is well."); } TRACE_EXIT_RET("stayConnected"); return stayConnected; } void MessageHandler::handleMessageArrive(const MessagePtr message) { TRACE_ENTER(); LOG_INFO("Recv'd message: " << message); TRACE_EXIT(); }
#include <boost/cast.hpp> #include "messageHandler.h" #include <libwatcher/messageStatus.h> using namespace std; using namespace watcher; using namespace watcher::event; using namespace boost; INIT_LOGGER(MessageHandler, "MessageHandler"); MessageHandler::MessageHandler() { TRACE_ENTER(); TRACE_EXIT(); } MessageHandler::~MessageHandler() { TRACE_ENTER(); TRACE_EXIT(); } MessageHandler::ConnectionCommand MessageHandler::produceReply(const MessagePtr &request, MessagePtr &reply) { TRACE_ENTER(); LOG_DEBUG("Producing reply for message: " << *request); reply=MessageStatusPtr(new MessageStatus(MessageStatus::status_ack)); LOG_DEBUG("Produced reply: " << *reply); TRACE_EXIT_RET("writeMessage"); return writeMessage; } MessageHandler::ConnectionCommand MessageHandler::handleReply(const MessagePtr &request, const MessagePtr &reply) { TRACE_ENTER(); LOG_INFO("Recv'd :" << "\n\t" << *reply << endl << "In reply to: " << "\n\t" << *request); if (reply->type != MESSAGE_STATUS_TYPE) { LOG_WARN("Got a non-message status message in reply."); TRACE_EXIT_RET("closeConnection"); return closeConnection; } MessageStatusPtr mess=boost::dynamic_pointer_cast<MessageStatus>(reply); if(mess) { if(mess->status!=MessageStatus::status_ack && mess->status!=MessageStatus::status_ok) { LOG_WARN("Recv'd non ack reply to request: " << MessageStatus::statusToString(mess->status)); } else { LOG_INFO("Recv'd ack to request, all is well."); } } else { LOG_ERROR("Look into this: unable to dynamically cast a shared_ptr<base> to shared_ptr<derived> even though it is the right type"); } TRACE_EXIT_RET("closeConnection"); return closeConnection; } void MessageHandler::handleMessageArrive(const MessagePtr message) { TRACE_ENTER(); LOG_INFO("Recv'd message: " << message); TRACE_EXIT(); }
Check return value of dynamic_cast<> of Message reply from server. Currently is NOT casting from base ---> derived. Which is bad.
Check return value of dynamic_cast<> of Message reply from server. Currently is NOT casting from base ---> derived. Which is bad.
C++
agpl-3.0
glawler/watcher-visualization,glawler/watcher-visualization,glawler/watcher-visualization,glawler/watcher-visualization,glawler/watcher-visualization
149f00fc89b24533d08a39bdefcce36c7aa9f667
Magick++/tests/montageImages.cpp
Magick++/tests/montageImages.cpp
// This may look like C code, but it is really -*- C++ -*- // // Copyright Bob Friesenhahn, 1999, 2000, 2002, 2003 // // Test STL montageImages function // #include <Magick++.h> #include <string> #include <iostream> #include <list> #include <vector> using namespace std; using namespace Magick; int main( int /*argc*/, char ** /*argv*/) { // Initialize ImageMagick install location for Windows // InitializeMagick(*argv); InitializeMagick(""); int failures=0; try { string srcdir(""); if(getenv("SRCDIR") != 0) srcdir = getenv("SRCDIR"); // // Test montageImages // list<Image> imageList; readImages( &imageList, srcdir + "test_image_anim.miff" ); vector<Image> montage; MontageFramed montageOpts; // Default montage montageImages( &montage, imageList.begin(), imageList.end(), montageOpts ); { Geometry targetGeometry(128, 126 ); if ( montage[0].montageGeometry() != targetGeometry ) { ++failures; cout << "Line: " << __LINE__ << " Montage geometry (" << string(montage[0].montageGeometry()) << ") is incorrect (expected " << string(targetGeometry) << ")" << endl; } } if ( montage[0].columns() != 768 || montage[0].rows() != 504 ) { ++failures; cout << "Line: " << __LINE__ << " Montage columns/rows (" << montage[0].columns() << "x" << montage[0].rows() << ") incorrect. (expected 768x504)" << endl; } // Montage with options set montage.clear(); montageOpts.borderColor( "green" ); montageOpts.borderWidth( 1 ); montageOpts.compose( OverCompositeOp ); montageOpts.fileName( "Montage" ); montageOpts.frameGeometry( "6x6+3+3" ); montageOpts.geometry("50x50+2+2>"); montageOpts.gravity( CenterGravity ); montageOpts.penColor( "yellow" ); montageOpts.shadow( true ); montageOpts.texture( "granite:" ); montageOpts.tile("2x1"); montageImages( &montage, imageList.begin(), imageList.end(), montageOpts ); if ( montage.size() != 3 ) { ++failures; cout << "Line: " << __LINE__ << " Montage images failed, number of montage frames is " << montage.size() << " rather than 3 as expected." << endl; } { Geometry targetGeometry( 66, 70 ); if ( montage[0].montageGeometry() != targetGeometry ) { ++failures; cout << "Line: " << __LINE__ << " Montage geometry (" << string(montage[0].montageGeometry()) << ") is incorrect (expected " << string(targetGeometry) << ")." << endl; } } if ( montage[0].columns() != 136 || montage[0].rows() != 70 ) { ++failures; cout << "Line: " << __LINE__ << " Montage columns/rows (" << montage[0].columns() << "x" << montage[0].rows() << ") incorrect. (expected 136x70)" << endl; } } catch( Exception &error_ ) { cout << "Caught exception: " << error_.what() << endl; return 1; } catch( exception &error_ ) { cout << "Caught exception: " << error_.what() << endl; return 1; } if ( failures ) { cout << failures << " failures" << endl; return 1; } return 0; }
// This may look like C code, but it is really -*- C++ -*- // // Copyright Bob Friesenhahn, 1999, 2000, 2002, 2003 // // Test STL montageImages function // #include <Magick++.h> #include <string> #include <iostream> #include <list> #include <vector> using namespace std; using namespace Magick; int main( int /*argc*/, char ** /*argv*/) { // Initialize ImageMagick install location for Windows // InitializeMagick(*argv); InitializeMagick(""); int failures=0; try { string srcdir(""); if(getenv("SRCDIR") != 0) srcdir = getenv("SRCDIR"); // // Test montageImages // list<Image> imageList; readImages( &imageList, srcdir + "test_image_anim.miff" ); vector<Image> montage; MontageFramed montageOpts; // Default montage montageImages( &montage, imageList.begin(), imageList.end(), montageOpts ); { Geometry targetGeometry(128, 126 ); if ( montage[0].montageGeometry() != targetGeometry ) { ++failures; cout << "Line: " << __LINE__ << " Montage geometry (" << string(montage[0].montageGeometry()) << ") is incorrect (expected " << string(targetGeometry) << ")" << endl; } } if ( montage[0].columns() != 768 || montage[0].rows() != 504 ) { ++failures; cout << "Line: " << __LINE__ << " Montage columns/rows (" << montage[0].columns() << "x" << montage[0].rows() << ") incorrect. (expected 768x504)" << endl; } // Montage with options set montage.clear(); montageOpts.borderColor( "green" ); montageOpts.borderWidth( 1 ); montageOpts.compose( OverCompositeOp ); montageOpts.fileName( "Montage" ); montageOpts.frameGeometry( "6x6+3+3" ); montageOpts.geometry("50x50+2+2>"); montageOpts.gravity( CenterGravity ); montageOpts.strokeColor( "yellow" ); montageOpts.shadow( true ); montageOpts.texture( "granite:" ); montageOpts.tile("2x1"); montageImages( &montage, imageList.begin(), imageList.end(), montageOpts ); if ( montage.size() != 3 ) { ++failures; cout << "Line: " << __LINE__ << " Montage images failed, number of montage frames is " << montage.size() << " rather than 3 as expected." << endl; } { Geometry targetGeometry( 66, 70 ); if ( montage[0].montageGeometry() != targetGeometry ) { ++failures; cout << "Line: " << __LINE__ << " Montage geometry (" << string(montage[0].montageGeometry()) << ") is incorrect (expected " << string(targetGeometry) << ")." << endl; } } if ( montage[0].columns() != 136 || montage[0].rows() != 70 ) { ++failures; cout << "Line: " << __LINE__ << " Montage columns/rows (" << montage[0].columns() << "x" << montage[0].rows() << ") incorrect. (expected 136x70)" << endl; } } catch( Exception &error_ ) { cout << "Caught exception: " << error_.what() << endl; return 1; } catch( exception &error_ ) { cout << "Caught exception: " << error_.what() << endl; return 1; } if ( failures ) { cout << failures << " failures" << endl; return 1; } return 0; }
Build fix.
Build fix. git-svn-id: 7f11a4e55de7d4642c7675696f15857479c93c9d@15751 aa41f4f7-0bf4-0310-aa73-e5a19afd5a74
C++
apache-2.0
svn2github/ImageMagick,svn2github/ImageMagick,svn2github/ImageMagick,svn2github/ImageMagick
ad91d77baf59899895041c7214f23d88df6a7c9e
src/game/ld22/editor.cpp
src/game/ld22/editor.cpp
#include "editor.hpp" #include "defs.hpp" #include "tileset.hpp" #include "client/keyboard/keycode.h" #include "client/opengl.hpp" #include "client/ui/event.hpp" #include "sys/path.hpp" #include "client/bitmapfont.hpp" #include <stdlib.h> using namespace LD22; static const int EDITBAR_SIZE = 64; static bool inScreen(int x, int y) { return x < SCREEN_WIDTH; } Editor::Editor() : m_mode(MBrush), m_tile(1), m_mx(0), m_my(0), m_mouse(-1), m_ent(-1), m_etype(0) { setSize(SCREEN_WIDTH + EDITBAR_SIZE, SCREEN_HEIGHT); } Editor::~Editor() { } void Editor::init() { open(1); } void Editor::handleEvent(const UI::Event &evt) { switch (evt.type) { case UI::MouseDown: handleMouseDown(evt.mouseEvent()); break; case UI::MouseUp: handleMouseUp(evt.mouseEvent()); break; case UI::MouseMove: handleMouseMove(evt.mouseEvent()); break; case UI::KeyDown: handleKeyDown(evt.keyEvent()); break; default: break; } } void Editor::handleKeyDown(const UI::KeyEvent &evt) { switch (evt.key) { case KEY_F1: save(); break; case KEY_1: setMode(MBrush); break; case KEY_2: setMode(MEntity); break; case KEY_PageUp: incType(-1, false); break; case KEY_PageDown: incType(1, false); break; case KEY_Home: incType(-1, true); break; case KEY_End: incType(1, true); break; case KEY_Delete: case KEY_DeleteForward: switch (m_mode) { case MEntity: deleteEntity(); break; default: break; } break; default: break; } } void Editor::handleMouseDown(const UI::MouseEvent &evt) { int x, y, tx, ty, pe; bool inbounds; inbounds = translateMouse(evt, &x, &y); if (!inbounds) return; if (inScreen(x, y)) { switch (m_mode) { case MBrush: tx = x / TILE_SIZE; ty = y / TILE_SIZE; m_mx = tx; m_my = ty; m_mouse = evt.button; tileBrush(tx, ty); break; case MEntity: switch (evt.button) { case UI::ButtonLeft: pe = m_ent; selectEntity(x, y, true); m_mouse = (pe >= 0 && pe == m_ent) ? UI::ButtonLeft : -1; break; case UI::ButtonRight: newEntity(x, y); break; default: m_ent = -1; break; } break; } } else { } } void Editor::handleMouseUp(const UI::MouseEvent &evt) { m_mouse = -1; } void Editor::handleMouseMove(const UI::MouseEvent &evt) { if (m_mouse < 0) return; int x, y, tx, ty; bool inbounds; inbounds = translateMouse(evt, &x, &y); if (inScreen(x, y)) { switch (m_mode) { case MBrush: tx = x / TILE_SIZE; ty = y / TILE_SIZE; if (tx != m_mx || ty != m_my) { m_mx = tx; m_my = ty; tileBrush(tx, ty); } break; case MEntity: if (m_ent >= 0) { Entity &e = level().entity[m_ent]; e.x = x; e.y = y; } break; } } else { m_mx = -1; m_my = -1; } } void Editor::drawExtra(int delta) { BitmapFont &f = font(); Level &l = level(); tileset().drawTiles(level().tiles, delta); std::vector<Entity>::const_iterator s = l.entity.begin(), i = s, e = l.entity.end(); for (; i != e; ++i) { int idx = i - s; bool selected = idx == m_ent; int x = i->x, y = i->y; if (selected) glLineWidth(5.0f); else glLineWidth(3.0f); glBegin(GL_LINES); glVertex2s(x + 10, y); glVertex2s(x - 10, y); glVertex2s(x, y + 10); glVertex2s(x, y - 10); glEnd(); glLineWidth(1.0f); if (selected) glColor3ub(255, 0, 0); else glColor3ub(0, 0, 0); glBegin(GL_LINES); glVertex2s(x + 9, y); glVertex2s(x - 9, y); glVertex2s(x, y + 9); glVertex2s(x, y - 9); glEnd(); glColor3ub(255, 255, 255); f.print(x + 5, y + 5, Entity::typeName(i->type)); } glPushMatrix(); glTranslatef(SCREEN_WIDTH, 0, 0); int w = EDITBAR_SIZE, h = SCREEN_WIDTH; glBegin(GL_QUADS); glVertex2s(0, 0); glVertex2s(w, 0); glVertex2s(w, h); glVertex2s(0, h); glEnd(); switch (m_mode) { case MBrush: f.print(5, 5, "brush"); break; case MEntity: f.print(5, 5, "entity"); f.print(5, 25, Entity::typeName((Entity::Type) m_etype)); break; } glPopMatrix(); tileset().drawWidget(10, 10, m_tile - 1); } bool Editor::translateMouse(const UI::MouseEvent &evt, int *x, int *y) { int xx = evt.x, yy = evt.y; convert(xx, yy); *x = xx; *y = yy; return xx >= 0 && xx < SCREEN_WIDTH + EDITBAR_SIZE && yy >= 0 && yy < SCREEN_HEIGHT; } void Editor::setMode(Mode m) { m_mode = m; m_mouse = -1; m_ent = -1; } static void incWrap(int &v, int minv, int maxv, int delta, bool max) { if (max) { v = delta > 0 ? maxv : minv; } else { v += delta; if (v > maxv) v = minv; else if (v < minv) v = maxv; } } void Editor::incType(int delta, bool max) { switch (m_mode) { case MBrush: incWrap(m_tile, 1, MAX_TILE, delta, max); break; case MEntity: incWrap(m_etype, 0, Entity::MAX_TYPE, delta, max); break; } } void Editor::tileBrush(int x, int y) { if (x < 0 || y < 0 || x >= TILE_WIDTH || y >= TILE_HEIGHT) { fputs("bad tileBrush\n", stderr); return; } Level &l = level(); if (m_mouse == UI::ButtonLeft) { l.tiles[y][x] = m_tile; } else if (m_mouse == UI::ButtonRight) { l.tiles[y][x] = 0; } } void Editor::selectEntity(int x, int y, bool click) { Level &l = level(); unsigned n, i, off; if (click && m_ent >= 0) { Entity &e = l.entity.at(m_ent); if (abs(e.x - x) < 10 && abs(e.y - y) < 10) return; } m_mx = x; m_my = y; n = l.entity.size(); off = n + (m_ent >= 0 ? m_ent : 0) - 1; for (i = 0; i < n; ++i) { int idx = (off - i) % n; Entity &e = l.entity.at(idx); if (abs(e.x - x) < 10 && abs(e.y - y) < 10) { m_ent = idx; return; } } m_ent = -1; } void Editor::newEntity(int x, int y) { Entity e; e.type = (Entity::Type) m_etype; e.x = x; e.y = y; Level &l = level(); m_ent = l.entity.size(); l.entity.push_back(e); } void Editor::deleteEntity() { if (m_ent < 0) return; Level &l = level(); l.entity.erase(l.entity.begin() + m_ent); m_ent = -1; } void Editor::open(int num) { level().clear(); try { level().load(num); } catch (Path::file_not_found &) { } loadLevel(); } void Editor::save() { level().save(1); }
#include "editor.hpp" #include "defs.hpp" #include "tileset.hpp" #include "client/keyboard/keycode.h" #include "client/opengl.hpp" #include "client/ui/event.hpp" #include "sys/path.hpp" #include "client/bitmapfont.hpp" #include <stdlib.h> using namespace LD22; static const int EDITBAR_SIZE = 64; static bool inScreen(int x, int y) { return x < SCREEN_WIDTH; } Editor::Editor() : m_mode(MBrush), m_tile(1), m_mx(0), m_my(0), m_mouse(-1), m_ent(-1), m_etype(0) { setSize(SCREEN_WIDTH + EDITBAR_SIZE, SCREEN_HEIGHT); } Editor::~Editor() { } void Editor::init() { open(1); } void Editor::handleEvent(const UI::Event &evt) { switch (evt.type) { case UI::MouseDown: handleMouseDown(evt.mouseEvent()); break; case UI::MouseUp: handleMouseUp(evt.mouseEvent()); break; case UI::MouseMove: handleMouseMove(evt.mouseEvent()); break; case UI::KeyDown: handleKeyDown(evt.keyEvent()); break; default: break; } } void Editor::handleKeyDown(const UI::KeyEvent &evt) { switch (evt.key) { case KEY_F1: save(); break; case KEY_1: setMode(MBrush); break; case KEY_2: setMode(MEntity); break; case KEY_PageUp: incType(-1, false); break; case KEY_PageDown: incType(1, false); break; case KEY_Home: incType(-1, true); break; case KEY_End: incType(1, true); break; case KEY_Delete: case KEY_DeleteForward: switch (m_mode) { case MEntity: deleteEntity(); break; default: break; } break; default: break; } } void Editor::handleMouseDown(const UI::MouseEvent &evt) { int x, y, tx, ty, pe; bool inbounds; inbounds = translateMouse(evt, &x, &y); if (!inbounds) return; if (inScreen(x, y)) { switch (m_mode) { case MBrush: tx = x / TILE_SIZE; ty = y / TILE_SIZE; m_mx = tx; m_my = ty; m_mouse = evt.button; tileBrush(tx, ty); break; case MEntity: switch (evt.button) { case UI::ButtonLeft: pe = m_ent; selectEntity(x, y, true); m_mouse = (pe >= 0 && pe == m_ent) ? UI::ButtonLeft : -1; break; case UI::ButtonRight: newEntity(x, y); break; default: m_ent = -1; break; } break; } } else { } } void Editor::handleMouseUp(const UI::MouseEvent &evt) { m_mouse = -1; } void Editor::handleMouseMove(const UI::MouseEvent &evt) { if (m_mouse < 0) return; int x, y, tx, ty; bool inbounds; inbounds = translateMouse(evt, &x, &y); if (inScreen(x, y)) { switch (m_mode) { case MBrush: tx = x / TILE_SIZE; ty = y / TILE_SIZE; if (tx != m_mx || ty != m_my) { m_mx = tx; m_my = ty; tileBrush(tx, ty); } break; case MEntity: if (m_ent >= 0) { Entity &e = level().entity[m_ent]; e.x = x; e.y = y; } break; } } else { m_mx = -1; m_my = -1; } } void Editor::drawExtra(int delta) { BitmapFont &f = font(); Level &l = level(); tileset().drawTiles(level().tiles, delta); std::vector<Entity>::const_iterator s = l.entity.begin(), i = s, e = l.entity.end(); for (; i != e; ++i) { int idx = i - s; bool selected = idx == m_ent; int x = i->x, y = i->y; if (selected) glLineWidth(5.0f); else glLineWidth(3.0f); glBegin(GL_LINES); glVertex2s(x + 10, y); glVertex2s(x - 10, y); glVertex2s(x, y + 10); glVertex2s(x, y - 10); glEnd(); glLineWidth(1.0f); if (selected) glColor3ub(255, 0, 0); else glColor3ub(0, 0, 0); glBegin(GL_LINES); glVertex2s(x + 9, y); glVertex2s(x - 9, y); glVertex2s(x, y + 9); glVertex2s(x, y - 9); glEnd(); glColor3ub(255, 255, 255); f.print(x + 5, y + 5, Entity::typeName(i->type)); } glPushMatrix(); glTranslatef(SCREEN_WIDTH, 0, 0); int w = EDITBAR_SIZE, h = SCREEN_WIDTH; glBegin(GL_QUADS); glVertex2s(0, 0); glVertex2s(w, 0); glVertex2s(w, h); glVertex2s(0, h); glEnd(); switch (m_mode) { case MBrush: f.print(5, 5, "brush"); break; case MEntity: f.print(5, 5, "entity"); f.print(5, 25, Entity::typeName((Entity::Type) m_etype)); break; } glPopMatrix(); } bool Editor::translateMouse(const UI::MouseEvent &evt, int *x, int *y) { int xx = evt.x, yy = evt.y; convert(xx, yy); *x = xx; *y = yy; return xx >= 0 && xx < SCREEN_WIDTH + EDITBAR_SIZE && yy >= 0 && yy < SCREEN_HEIGHT; } void Editor::setMode(Mode m) { m_mode = m; m_mouse = -1; m_ent = -1; } static void incWrap(int &v, int minv, int maxv, int delta, bool max) { if (max) { v = delta > 0 ? maxv : minv; } else { v += delta; if (v > maxv) v = minv; else if (v < minv) v = maxv; } } void Editor::incType(int delta, bool max) { switch (m_mode) { case MBrush: incWrap(m_tile, 1, MAX_TILE, delta, max); break; case MEntity: incWrap(m_etype, 0, Entity::MAX_TYPE, delta, max); break; } } void Editor::tileBrush(int x, int y) { if (x < 0 || y < 0 || x >= TILE_WIDTH || y >= TILE_HEIGHT) { fputs("bad tileBrush\n", stderr); return; } Level &l = level(); if (m_mouse == UI::ButtonLeft) { l.tiles[y][x] = m_tile; } else if (m_mouse == UI::ButtonRight) { l.tiles[y][x] = 0; } } void Editor::selectEntity(int x, int y, bool click) { Level &l = level(); unsigned n, i, off; if (click && m_ent >= 0) { Entity &e = l.entity.at(m_ent); if (abs(e.x - x) < 10 && abs(e.y - y) < 10) return; } m_mx = x; m_my = y; n = l.entity.size(); off = n + (m_ent >= 0 ? m_ent : 0) - 1; for (i = 0; i < n; ++i) { int idx = (off - i) % n; Entity &e = l.entity.at(idx); if (abs(e.x - x) < 10 && abs(e.y - y) < 10) { m_ent = idx; return; } } m_ent = -1; } void Editor::newEntity(int x, int y) { Entity e; e.type = (Entity::Type) m_etype; e.x = x; e.y = y; Level &l = level(); m_ent = l.entity.size(); l.entity.push_back(e); } void Editor::deleteEntity() { if (m_ent < 0) return; Level &l = level(); l.entity.erase(l.entity.begin() + m_ent); m_ent = -1; } void Editor::open(int num) { level().clear(); try { level().load(num); } catch (Path::file_not_found &) { } loadLevel(); } void Editor::save() { level().save(1); }
Remove widget demonstration code
Remove widget demonstration code
C++
bsd-2-clause
depp/sglib,depp/sglib
de21d3c01aa339e07d0223eee714542374be64d5
UnnamedEngine/Sources/Engine/Base/Systems/FreecamPlayerSystem.cpp
UnnamedEngine/Sources/Engine/Base/Systems/FreecamPlayerSystem.cpp
#include "FreecamPlayerSystem.h" #include "Engine/Base/Managers/EntityAdmin.h" #include "Engine/Base/Client/Context.h" #include "Engine/Base/Client/ClientInputManager.h" #include "Engine/Base/Components/SingletonComponents/InputComponent.h" #include "Engine/Base/Components/TransformComponent.h" #include "Engine/Base/Components/CameraComponent.h" #include "Engine/Base/Client/GameFramework.h" #include "Engine/Base/Client/Keycodes.h" FreecamPlayerSystem::FreecamPlayerSystem(Ptr<Context> context) : mContext(context) {} void FreecamPlayerSystem::Update(float delta, Ptr<EntityAdmin> e) { const float SENSITIVITY = 0.001; // rot = pixels * rad * SENSITIVITY const float FREECAMSPEED = 100.0; // 3m/s Ptr<const InputComponent> inputComponent = GetSingletonComponent<InputComponent>(e); const Entity& playerEntity = mContext->GetGameFramework()->GetGameClient()->GetLocalPlayerEntity(); Ptr<TransformComponent> transformComponent = GetWriteComponent<TransformComponent>(e, playerEntity); Ptr<CameraComponent> cameraComponent = GetWriteComponent<CameraComponent>(e, playerEntity); float mouseDx = 0.0f; float mouseDy = 0.0f; float forward = 0.0f; float right = 0.0f; // to make right and left inputs 'cancel' size_t horizontalInputs = 0; size_t forwardInputs = 0; for(auto input : inputComponent->inputEvents) { if(input.GetKeycode() == MOUSE_X) { mouseDx = input.GetValue(); } else if(input.GetKeycode() == MOUSE_Y) { mouseDy = input.GetValue(); } } if(inputComponent->keycodeDown[KEY_W.keycode]) { forward = 1.0; forwardInputs++; } else if(inputComponent->keycodeDown[KEY_S.keycode]) { forward = -1.0f; forwardInputs++; } else if(inputComponent->keycodeDown[KEY_A.keycode]) { right = -1.0f; horizontalInputs++; } else if(inputComponent->keycodeDown[KEY_D.keycode]) { right = 1.0f; horizontalInputs++; } if(horizontalInputs > 1) { right = 0.0f; } if(forwardInputs > 1) { forward = 0.0f; } // Update entity transform auto viewRotation = glm::mat3_cast(transformComponent->pEntityWorldRotation * Quat(cameraComponent->pCameraRotation)); const auto& camRot = cameraComponent->pCameraRotation; const Vector3f up(0.0, 1.0, 0.0); const Vector3f lookDirection(cos(camRot.y) * cos(camRot.x), sin(camRot.y), cos(camRot.y) * sin(camRot.x)); transformComponent->pEntityWorldTranslation += glm::normalize(lookDirection) * forward * FREECAMSPEED * delta; transformComponent->pEntityWorldTranslation += glm::normalize(glm::cross(lookDirection, up)) * right * FREECAMSPEED * delta; auto cameraEulers = cameraComponent->pCameraRotation; // Update entity camera transform cameraEulers.x += mouseDx * SENSITIVITY; // pitch (counterclockwise for right/pos x) cameraEulers.y -= mouseDy * SENSITIVITY; // yaw cameraEulers.x += 2 * M_PI; cameraEulers.x = fmod(cameraEulers.x, 2 * M_PI); // can't let pitch get to 0 (cuz then it's the same as the up vector) // so do a hard stop cameraEulers.y = glm::clamp( cameraEulers.y, static_cast<float>(-M_PI / 2 + M_PI / 16), static_cast<float>(M_PI / 2 - M_PI / 16) ); cameraComponent->pCameraRotation = cameraEulers; } void FreecamPlayerSystem::StaticInitDependencies() { AddWriteDependency(ComponentGroup<CameraComponent>()); AddReadDependency(ComponentGroup<InputComponent>()); AddWriteDependency(ComponentGroup<TransformComponent>()); }
#include "FreecamPlayerSystem.h" #include "Engine/Base/Managers/EntityAdmin.h" #include "Engine/Base/Client/Context.h" #include "Engine/Base/Client/ClientInputManager.h" #include "Engine/Base/Components/SingletonComponents/InputComponent.h" #include "Engine/Base/Components/TransformComponent.h" #include "Engine/Base/Components/CameraComponent.h" #include "Engine/Base/Client/GameFramework.h" #include "Engine/Base/Client/Keycodes.h" FreecamPlayerSystem::FreecamPlayerSystem(Ptr<Context> context) : mContext(context) {} void FreecamPlayerSystem::Update(float delta, Ptr<EntityAdmin> e) { const float SENSITIVITY = 0.001; // rot = pixels * rad * SENSITIVITY const float FREECAMSPEED = 100.0; // 3m/s Ptr<const InputComponent> inputComponent = GetSingletonComponent<InputComponent>(e); const Entity& playerEntity = mContext->GetGameFramework()->GetGameClient()->GetLocalPlayerEntity(); Ptr<TransformComponent> transformComponent = GetWriteComponent<TransformComponent>(e, playerEntity); Ptr<CameraComponent> cameraComponent = GetWriteComponent<CameraComponent>(e, playerEntity); float mouseDx = 0.0f; float mouseDy = 0.0f; float forward = 0.0f; float right = 0.0f; // to make right and left inputs 'cancel' size_t horizontalInputs = 0; size_t forwardInputs = 0; for(auto input : inputComponent->inputEvents) { if(input.GetKeycode() == MOUSE_X) { mouseDx = input.GetValue(); } else if(input.GetKeycode() == MOUSE_Y) { mouseDy = input.GetValue(); } } if(inputComponent->keycodeDown[KEY_W.keycode]) { forward = 1.0; forwardInputs++; } if(inputComponent->keycodeDown[KEY_S.keycode]) { forward = -1.0f; forwardInputs++; } if(inputComponent->keycodeDown[KEY_A.keycode]) { right = -1.0f; horizontalInputs++; } if(inputComponent->keycodeDown[KEY_D.keycode]) { right = 1.0f; horizontalInputs++; } if(horizontalInputs > 1) { right = 0.0f; } if(forwardInputs > 1) { forward = 0.0f; } // Update entity transform auto viewRotation = glm::mat3_cast(transformComponent->pEntityWorldRotation * Quat(cameraComponent->pCameraRotation)); const auto& camRot = cameraComponent->pCameraRotation; const Vector3f up(0.0, 1.0, 0.0); const Vector3f lookDirection(cos(camRot.y) * cos(camRot.x), sin(camRot.y), cos(camRot.y) * sin(camRot.x)); transformComponent->pEntityWorldTranslation += glm::normalize(lookDirection) * forward * FREECAMSPEED * delta; transformComponent->pEntityWorldTranslation += glm::normalize(glm::cross(lookDirection, up)) * right * FREECAMSPEED * delta; auto cameraEulers = cameraComponent->pCameraRotation; // Update entity camera transform cameraEulers.x += mouseDx * SENSITIVITY; // pitch (counterclockwise for right/pos x) cameraEulers.y -= mouseDy * SENSITIVITY; // yaw cameraEulers.x += 2 * M_PI; cameraEulers.x = fmod(cameraEulers.x, 2 * M_PI); // can't let pitch get to 0 (cuz then it's the same as the up vector) // so do a hard stop cameraEulers.y = glm::clamp( cameraEulers.y, static_cast<float>(-M_PI / 2 + M_PI / 16), static_cast<float>(M_PI / 2 - M_PI / 16) ); cameraComponent->pCameraRotation = cameraEulers; } void FreecamPlayerSystem::StaticInitDependencies() { AddWriteDependency(ComponentGroup<CameraComponent>()); AddReadDependency(ComponentGroup<InputComponent>()); AddWriteDependency(ComponentGroup<TransformComponent>()); }
add ability to 'cancel' movement in freecam by hitting the opposite button
add ability to 'cancel' movement in freecam by hitting the opposite button
C++
mit
minimumcut/UnnamedEngine,minimumcut/UnnamedEngine
f111224f349a11da878f0fc390c69bf443297ed2
3RVX/Skin/SkinManager.cpp
3RVX/Skin/SkinManager.cpp
#include "SkinManager.h" #include "Skin.h" SkinManager *SkinManager::instance; SkinManager *SkinManager::Instance() { if (instance == NULL) { instance = new SkinManager(); } return instance; } SkinManager::~SkinManager() { delete _skin; } void SkinManager::LoadSkin(std::wstring skinXML) { delete _skin; _skin = new Skin(skinXML); } Skin *SkinManager::CurrentSkin() { return _skin; }
#include "SkinManager.h" #include "Skin.h" #include "SkinV3.h" SkinManager *SkinManager::instance; SkinManager *SkinManager::Instance() { if (instance == NULL) { instance = new SkinManager(); } return instance; } SkinManager::~SkinManager() { delete _skin; } void SkinManager::LoadSkin(std::wstring skinXML) { delete _skin; _skin = new SkinV3(skinXML); } Skin *SkinManager::CurrentSkin() { return _skin; }
Load a v3 skin for now
Load a v3 skin for now
C++
bsd-2-clause
malensek/3RVX,malensek/3RVX,Soulflare3/3RVX,Soulflare3/3RVX,malensek/3RVX,Soulflare3/3RVX
0f81d0b1ab518a7b5045d43cc2c7e65e31d6211d
Source/bindings/core/v8/V8ScriptRunner.cpp
Source/bindings/core/v8/V8ScriptRunner.cpp
/* * Copyright (C) 2009 Google Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 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 APPLE INC. AND ITS 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 APPLE INC. OR ITS CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. */ #include "config.h" #include "bindings/core/v8/V8ScriptRunner.h" #include "bindings/core/v8/V8Binding.h" #include "bindings/core/v8/V8RecursionScope.h" #include "bindings/core/v8/V8ThrowException.h" #include "platform/ScriptForbiddenScope.h" #include "platform/TraceEvent.h" #include "public/platform/Platform.h" #include "wtf/CurrentTime.h" #if defined(WTF_OS_WIN) #include <malloc.h> #else #include <alloca.h> #endif namespace blink { namespace { // Used to throw an exception before we exceed the C++ stack and crash. // This limit was arrived at arbitrarily. crbug.com/449744 const int kMaxRecursionDepth = 44; // In order to make sure all pending messages to be processed in // v8::Function::Call, we don't call throwStackOverflowException // directly. Instead, we create a v8::Function of // throwStackOverflowException and call it. void throwStackOverflowException(const v8::FunctionCallbackInfo<v8::Value>& info) { V8ThrowException::throwRangeError(info.GetIsolate(), "Maximum call stack size exceeded."); } void throwScriptForbiddenException(v8::Isolate* isolate) { V8ThrowException::throwGeneralError(isolate, "Script execution is forbidden."); } v8::Local<v8::Value> throwStackOverflowExceptionIfNeeded(v8::Isolate* isolate) { if (V8PerIsolateData::from(isolate)->isHandlingRecursionLevelError()) { // If we are already handling a recursion level error, we should // not invoke v8::Function::Call. return v8::Undefined(isolate); } V8PerIsolateData::from(isolate)->setIsHandlingRecursionLevelError(true); v8::Local<v8::Value> result = v8::Function::New(isolate, throwStackOverflowException)->Call(v8::Undefined(isolate), 0, 0); V8PerIsolateData::from(isolate)->setIsHandlingRecursionLevelError(false); return result; } } // namespace v8::MaybeLocal<v8::Script> V8ScriptRunner::compileScript(v8::Local<v8::String> code, const String& fileName, const String& sourceMapUrl, const TextPosition& scriptStartPosition, v8::Isolate* isolate, bool isInternalScript) { AccessControlStatus accessControlStatus; // NOTE: For compatibility with WebCore, ScriptSourceCode's line starts at // 1, whereas v8 starts at 0. v8::ScriptOrigin origin( v8String(isolate, fileName), v8::Integer::New(isolate, scriptStartPosition.m_line.zeroBasedInt()), v8::Integer::New(isolate, scriptStartPosition.m_column.zeroBasedInt()), v8Boolean(accessControlStatus == SharableCrossOrigin, isolate), v8::Local<v8::Integer>(), v8Boolean(isInternalScript, isolate), v8String(isolate, sourceMapUrl), v8Boolean(accessControlStatus == OpaqueResource, isolate)); v8::ScriptCompiler::Source source(code, origin); v8::MaybeLocal<v8::Script> script = v8::ScriptCompiler::Compile(isolate->GetCurrentContext(), &source, v8::ScriptCompiler::kNoCompileOptions); return script; } v8::MaybeLocal<v8::Value> V8ScriptRunner::runCompiledScript(v8::Isolate* isolate, v8::Local<v8::Script> script) { ASSERT(!script.IsEmpty()); if (V8RecursionScope::recursionLevel(isolate) >= kMaxRecursionDepth) return throwStackOverflowExceptionIfNeeded(isolate); // Run the script and keep track of the current recursion depth. v8::MaybeLocal<v8::Value> result; { if (ScriptForbiddenScope::isScriptForbidden()) { throwScriptForbiddenException(isolate); return v8::MaybeLocal<v8::Value>(); } V8RecursionScope recursionScope(isolate); result = script->Run(isolate->GetCurrentContext()); } crashIfV8IsDead(); return result; } v8::MaybeLocal<v8::Value> V8ScriptRunner::compileAndRunInternalScript(v8::Local<v8::String> source, v8::Isolate* isolate, const String& fileName, const TextPosition& scriptStartPosition) { v8::Local<v8::Script> script; if (!V8ScriptRunner::compileScript(source, fileName, String(), scriptStartPosition, isolate, true).ToLocal(&script)) return v8::MaybeLocal<v8::Value>(); V8RecursionScope::MicrotaskSuppression recursionScope(isolate); v8::MaybeLocal<v8::Value> result = script->Run(isolate->GetCurrentContext()); crashIfV8IsDead(); return result; } v8::MaybeLocal<v8::Value> V8ScriptRunner::callFunction(v8::Local<v8::Function> function, v8::Local<v8::Value> receiver, int argc, v8::Local<v8::Value> args[], v8::Isolate* isolate) { if (V8RecursionScope::recursionLevel(isolate) >= kMaxRecursionDepth) return v8::MaybeLocal<v8::Value>(throwStackOverflowExceptionIfNeeded(isolate)); if (ScriptForbiddenScope::isScriptForbidden()) { throwScriptForbiddenException(isolate); return v8::MaybeLocal<v8::Value>(); } V8RecursionScope recursionScope(isolate); v8::MaybeLocal<v8::Value> result = function->Call(isolate->GetCurrentContext(), receiver, argc, args); crashIfV8IsDead(); return result; } v8::MaybeLocal<v8::Value> V8ScriptRunner::callInternalFunction(v8::Local<v8::Function> function, v8::Local<v8::Value> receiver, int argc, v8::Local<v8::Value> args[], v8::Isolate* isolate) { V8RecursionScope::MicrotaskSuppression recursionScope(isolate); v8::MaybeLocal<v8::Value> result = function->Call(isolate->GetCurrentContext(), receiver, argc, args); crashIfV8IsDead(); return result; } v8::MaybeLocal<v8::Object> V8ScriptRunner::instantiateObject(v8::Isolate* isolate, v8::Local<v8::Function> function, int argc, v8::Local<v8::Value> argv[]) { V8RecursionScope::MicrotaskSuppression scope(isolate); v8::MaybeLocal<v8::Object> result = function->NewInstance(isolate->GetCurrentContext(), argc, argv); crashIfV8IsDead(); return result; } } // namespace blink
/* * Copyright (C) 2009 Google Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 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 APPLE INC. AND ITS 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 APPLE INC. OR ITS CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. */ #include "config.h" #include "bindings/core/v8/V8ScriptRunner.h" #include "bindings/core/v8/V8Binding.h" namespace blink { v8::MaybeLocal<v8::Script> V8ScriptRunner::compileScript(v8::Local<v8::String> code, const String& fileName, const String& sourceMapUrl, const TextPosition& scriptStartPosition, v8::Isolate* isolate, bool isInternalScript) { // NOTE: For compatibility with WebCore, ScriptSourceCode's line starts at // 1, whereas v8 starts at 0. v8::ScriptOrigin origin( v8String(isolate, fileName), v8::Integer::New(isolate, scriptStartPosition.m_line.zeroBasedInt()), v8::Integer::New(isolate, scriptStartPosition.m_column.zeroBasedInt()), v8Boolean(false, isolate), v8::Local<v8::Integer>(), v8Boolean(isInternalScript, isolate)); v8::ScriptCompiler::Source source(code, origin); v8::MaybeLocal<v8::Script> script = v8::ScriptCompiler::Compile(isolate->GetCurrentContext(), &source, v8::ScriptCompiler::kNoCompileOptions); return script; } v8::MaybeLocal<v8::Value> V8ScriptRunner::runCompiledScript(v8::Isolate* isolate, v8::Local<v8::Script> script) { ASSERT(!script.IsEmpty()); // Run the script and keep track of the current recursion depth. v8::MaybeLocal<v8::Value> result = script->Run(isolate->GetCurrentContext()); crashIfV8IsDead(); return result; } v8::MaybeLocal<v8::Value> V8ScriptRunner::compileAndRunInternalScript(v8::Local<v8::String> source, v8::Isolate* isolate, const String& fileName, const TextPosition& scriptStartPosition) { v8::Local<v8::Script> script; if (!V8ScriptRunner::compileScript(source, fileName, String(), scriptStartPosition, isolate, true).ToLocal(&script)) return v8::MaybeLocal<v8::Value>(); v8::MaybeLocal<v8::Value> result = script->Run(isolate->GetCurrentContext()); crashIfV8IsDead(); return result; } v8::MaybeLocal<v8::Value> V8ScriptRunner::callFunction(v8::Local<v8::Function> function, v8::Local<v8::Value> receiver, int argc, v8::Local<v8::Value> args[], v8::Isolate* isolate) { v8::MaybeLocal<v8::Value> result = function->Call(isolate->GetCurrentContext(), receiver, argc, args); crashIfV8IsDead(); return result; } v8::MaybeLocal<v8::Value> V8ScriptRunner::callInternalFunction(v8::Local<v8::Function> function, v8::Local<v8::Value> receiver, int argc, v8::Local<v8::Value> args[], v8::Isolate* isolate) { v8::MaybeLocal<v8::Value> result = function->Call(isolate->GetCurrentContext(), receiver, argc, args); crashIfV8IsDead(); return result; } v8::MaybeLocal<v8::Object> V8ScriptRunner::instantiateObject(v8::Isolate* isolate, v8::Local<v8::Function> function, int argc, v8::Local<v8::Value> argv[]) { v8::MaybeLocal<v8::Object> result = function->NewInstance(isolate->GetCurrentContext(), argc, argv); crashIfV8IsDead(); return result; } } // namespace blink
Remove ExecutionContext parameter from V8ScriptRunner
Remove ExecutionContext parameter from V8ScriptRunner
C++
bsd-3-clause
rbaindourov/v8-inspector,yury-s/v8-inspector,rbaindourov/v8-inspector,yury-s/v8-inspector,yury-s/v8-inspector,rbaindourov/v8-inspector,rbaindourov/v8-inspector,yury-s/v8-inspector,rbaindourov/v8-inspector,yury-s/v8-inspector,rbaindourov/v8-inspector,yury-s/v8-inspector,yury-s/v8-inspector,rbaindourov/v8-inspector,rbaindourov/v8-inspector,rbaindourov/v8-inspector,yury-s/v8-inspector,yury-s/v8-inspector,yury-s/v8-inspector,rbaindourov/v8-inspector,yury-s/v8-inspector,rbaindourov/v8-inspector
e45887d02099b9e7e213dec4698a026c5e5e0a7c
Modules/Filtering/ImageFrequency/test/itkFrequencyBandImageFilterTest.cxx
Modules/Filtering/ImageFrequency/test/itkFrequencyBandImageFilterTest.cxx
/*========================================================================= * * Copyright Insight Software Consortium * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0.txt * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * *=========================================================================*/ #include "itkFrequencyBandImageFilter.h" #include "itkUnaryFrequencyDomainFilter.h" #include "itkAddImageFilter.h" #include "itkFrequencyShiftedFFTLayoutImageRegionIteratorWithIndex.h" #include "itkImage.h" #include "itkImageFileWriter.h" #include "itkTestingComparisonImageFilter.h" #include "itkTestingMacros.h" namespace { template< typename ImageType > bool compareImages( ImageType* baseline, ImageType* test ) { using DifferenceFilterType = itk::Testing::ComparisonImageFilter< ImageType, ImageType >; auto differenceFilter = DifferenceFilterType::New(); differenceFilter->SetToleranceRadius( 0 ); differenceFilter->SetDifferenceThreshold( 0 ); differenceFilter->SetValidInput( baseline ); differenceFilter->SetTestInput( test ); differenceFilter->Update(); unsigned int numberOfDiffPixels = differenceFilter->GetNumberOfPixelsWithDifferences(); if ( numberOfDiffPixels > 0 ) { std::cerr << "Expected images to be equal, but got " << numberOfDiffPixels << "unequal pixels" << std::endl; return false; } return true; } template< typename ImageType > typename ImageType::Pointer createImage( typename ImageType::SizeType size ) { auto image = ImageType::New(); typename ImageType::RegionType region; region.SetSize( size ); image->SetRegions( region ); image->Allocate( false ); typename ImageType::PixelType value = itk::NumericTraits< typename ImageType::PixelType >::Zero; itk::ImageRegionIterator< ImageType > iter; while ( !iter.IsAtEnd() ) { iter.Set( ++value ); ++iter; } return image; } } // namespace int itkFrequencyBandImageFilterTest( int argc, char* argv[] ) { constexpr unsigned int Dimension = 3; if ( argc != 2 ) { std::cerr << "Usage: " << argv[0] << " Even|Odd" << std::endl; return EXIT_FAILURE; } const std::string evenOrOddInput = argv[1]; bool isOdd = false; if ( evenOrOddInput == "Even" ) { isOdd = false; } else if ( evenOrOddInput == "Odd" ) { isOdd = true; } else { std::cerr << "Unkown string: " + evenOrOddInput + " . Use Even or Odd." << std::endl; return EXIT_FAILURE; } using PixelType = float; using ImageType3D = itk::Image< PixelType, Dimension >; ImageType3D::SizeType size = { { 10, 20, 40 } }; if ( isOdd ) { for ( unsigned int i = 0; i < Dimension; ++i ) { size[i]++; } } auto image = createImage< ImageType3D >( size ); using BandFilterType = itk::FrequencyBandImageFilter< ImageType3D >; auto passBandFilter = BandFilterType::New(); EXERCISE_BASIC_OBJECT_METHODS( passBandFilter, FrequencyBandImageFilter, UnaryFrequencyDomainFilter ); passBandFilter->SetInput( image ); // Test exception cases BandFilterType::FrequencyValueType lowFreqThreshold = 0.5; passBandFilter->SetLowFrequencyThreshold( lowFreqThreshold ); TEST_SET_GET_VALUE( lowFreqThreshold, passBandFilter->GetLowFrequencyThreshold() ); BandFilterType::FrequencyValueType highFreqThreshold = 0.0; passBandFilter->SetHighFrequencyThreshold( highFreqThreshold ); TEST_SET_GET_VALUE( highFreqThreshold, passBandFilter->GetHighFrequencyThreshold() ); TRY_EXPECT_EXCEPTION( passBandFilter->Update() ); lowFreqThreshold = 0.0; passBandFilter->SetLowFrequencyThreshold( lowFreqThreshold ); TEST_SET_GET_VALUE( lowFreqThreshold, passBandFilter->GetLowFrequencyThreshold() ); highFreqThreshold = 0.5; passBandFilter->SetHighFrequencyThreshold( highFreqThreshold ); TEST_SET_GET_VALUE( highFreqThreshold, passBandFilter->GetHighFrequencyThreshold() ); bool passBand = true; TEST_SET_GET_BOOLEAN( passBandFilter, PassBand, passBand ); bool passLowFreqThreshold = true; TEST_SET_GET_BOOLEAN( passBandFilter, PassLowFrequencyThreshold, passLowFreqThreshold ); bool passHighFreqThreshold = true; TEST_SET_GET_BOOLEAN( passBandFilter, PassHighFrequencyThreshold, passHighFreqThreshold ); passBandFilter->SetPassBand( passLowFreqThreshold, passHighFreqThreshold ); TEST_SET_GET_VALUE( passLowFreqThreshold, passBandFilter->GetPassLowFrequencyThreshold() ); TEST_SET_GET_VALUE( passHighFreqThreshold, passBandFilter->GetPassHighFrequencyThreshold() ); TRY_EXPECT_NO_EXCEPTION( passBandFilter->Update() ); // Stop-band auto stopBandFilter = BandFilterType::New(); stopBandFilter->SetInput( image ); stopBandFilter->SetLowFrequencyThreshold( lowFreqThreshold ); stopBandFilter->SetHighFrequencyThreshold( highFreqThreshold ); passLowFreqThreshold = false; passHighFreqThreshold = false; stopBandFilter->SetStopBand( passLowFreqThreshold, passHighFreqThreshold ); TEST_SET_GET_VALUE( passLowFreqThreshold, stopBandFilter->GetPassLowFrequencyThreshold() ); TEST_SET_GET_VALUE( passHighFreqThreshold, stopBandFilter->GetPassHighFrequencyThreshold() ); TRY_EXPECT_NO_EXCEPTION( stopBandFilter->Update() ); // Regression test // Sum of bandPass and stopBand images with these settings should be equal // to original image using AddFilterType = itk::AddImageFilter< ImageType3D, ImageType3D >; auto addFilter = AddFilterType::New(); addFilter->SetInput1( passBandFilter->GetOutput() ); addFilter->SetInput2( stopBandFilter->GetOutput() ); std::cout << "Comparing the original and sum of bandPass and stopBand images" << std::endl; bool success = compareImages( image.GetPointer(), addFilter->GetOutput() ); // Tests with radians BandFilterType::FrequencyValueType lowFreqThresholdRadians = itk::Math::pi_over_4; passBandFilter->SetLowFrequencyThresholdInRadians( lowFreqThresholdRadians ); BandFilterType::FrequencyValueType highFreqThresholdRadians = itk::Math::pi_over_2; passBandFilter->SetHighFrequencyThresholdInRadians( highFreqThresholdRadians ); BandFilterType::FrequencyValueType knownLowFrequencyHertz = lowFreqThresholdRadians / ( 2 * itk::Math::pi ); BandFilterType::FrequencyValueType knownHighFrequencyHertz = highFreqThresholdRadians / ( 2 * itk::Math::pi ); if ( itk::Math::NotAlmostEquals( knownLowFrequencyHertz, passBandFilter->GetLowFrequencyThreshold() ) || itk::Math::NotAlmostEquals( knownHighFrequencyHertz, passBandFilter->GetHighFrequencyThreshold() ) ) { std::cerr << "Test failed! " << std::endl; std::cerr << "Setting frequency in radians failed." << std::endl; success = false; } TRY_EXPECT_NO_EXCEPTION( passBandFilter->Update() ); // Test the non-radial cut-off. // Don't pass negative frequency thresholds. bool radialBand = false; TEST_SET_GET_BOOLEAN( passBandFilter, RadialBand, radialBand ); bool passNegativeLowFrequencyThreshold = false; TEST_SET_GET_BOOLEAN( passBandFilter, PassNegativeLowFrequencyThreshold, passNegativeLowFrequencyThreshold ); bool passNegativeHighFrequencyThreshold = false; TEST_SET_GET_BOOLEAN( passBandFilter, PassNegativeHighFrequencyThreshold, passNegativeHighFrequencyThreshold ); passBandFilter->Update(); // Test with ShiftedIterator. using FrequencyShiftedIterator = itk::FrequencyShiftedFFTLayoutImageRegionIteratorWithIndex< ImageType3D >; using BandShiftedFilterType = itk::FrequencyBandImageFilter< ImageType3D, FrequencyShiftedIterator >; auto passBandShiftedFilter = BandShiftedFilterType::New(); passBandShiftedFilter->SetInput( image ); passBandShiftedFilter->SetLowFrequencyThreshold( lowFreqThreshold ); passBandShiftedFilter->SetHighFrequencyThreshold( highFreqThreshold ); passBandShiftedFilter->SetPassBand( true ); passLowFreqThreshold = false; passHighFreqThreshold = true; passBandShiftedFilter->SetPassBand( passLowFreqThreshold, passHighFreqThreshold ); TRY_EXPECT_NO_EXCEPTION( passBandShiftedFilter->Update() ); // Stop-band with InPlaceOn auto stopBandInPlaceFilter = BandFilterType::New(); stopBandInPlaceFilter->InPlaceOn(); stopBandInPlaceFilter->SetInput( image ); stopBandInPlaceFilter->SetLowFrequencyThreshold( lowFreqThreshold ); stopBandInPlaceFilter->SetHighFrequencyThreshold( highFreqThreshold ); passLowFreqThreshold = false; passHighFreqThreshold = false; stopBandInPlaceFilter->SetStopBand( passLowFreqThreshold, passHighFreqThreshold ); TRY_EXPECT_NO_EXCEPTION( stopBandInPlaceFilter->Update() ); std::cout << "Comparing stopBand and stopBandInPlaceFilter results" << std::endl; success &= compareImages( stopBandFilter->GetOutput(), stopBandInPlaceFilter->GetOutput() ); // Custom functor UnaryFrequencyDomainFilter using UnaryFilterType = itk::UnaryFrequencyDomainFilter< ImageType3D >; using ValueFunctionType = UnaryFilterType::ValueFunctionType; using ConstRefFunctionType = UnaryFilterType::ConstRefFunctionType; auto testFilter = UnaryFilterType::New(); EXERCISE_BASIC_OBJECT_METHODS( testFilter, UnaryFrequencyDomainFilter, InPlaceImageFilter ); struct TestStruct { static double ConstUnaryFunction( const UnaryFilterType::FrequencyIteratorType& freqIt ) { return std::sin( freqIt.GetFrequencyModuloSquare() * 10 ); } static void UnaryFunction( UnaryFilterType::FrequencyIteratorType& freqIt ) { freqIt.Value() *= std::sin( freqIt.GetFrequencyModuloSquare() * 10 ); } }; auto inPlaceLambda = []( UnaryFilterType::FrequencyIteratorType& freqIt ) { freqIt.Value() *= std::sin( freqIt.GetFrequencyModuloSquare() * 10 ); }; image = createImage< ImageType3D >( size ); // stopBandInPlaceFilter has modified the original one // Test with lambda function auto lambdaFilter = UnaryFilterType::New(); lambdaFilter->SetInput( image ); lambdaFilter->SetFunctor( inPlaceLambda ); TRY_EXPECT_NO_EXCEPTION( lambdaFilter->Update() ); // Test with C style function pointer auto cfpFilter = UnaryFilterType::New(); cfpFilter->SetInput( image ); cfpFilter->SetFunctor( static_cast< ConstRefFunctionType* >( TestStruct::ConstUnaryFunction ) ); TRY_EXPECT_NO_EXCEPTION( cfpFilter->Update() ); // Test with std::functional auto stdFilter = UnaryFilterType::New(); stdFilter->SetInput( image ); std::function< double( const UnaryFilterType::FrequencyIteratorType& ) > func1 = static_cast< ConstRefFunctionType* >( TestStruct::ConstUnaryFunction ); stdFilter->SetFunctor( func1 ); TRY_EXPECT_NO_EXCEPTION( stdFilter->Update() ); // Test with C style function pointer (in-place variant) auto cfpFilterIP = UnaryFilterType::New(); cfpFilterIP->SetInput( image ); cfpFilterIP->SetFunctor( static_cast< ValueFunctionType* >( TestStruct::UnaryFunction ) ); TRY_EXPECT_NO_EXCEPTION( cfpFilterIP->Update() ); // Test with std::functional (in-place variant) auto stdFilterIP = UnaryFilterType::New(); stdFilterIP->SetInput( image ); std::function< void( UnaryFilterType::FrequencyIteratorType& ) > func2 = static_cast< ValueFunctionType* >( TestStruct::UnaryFunction ); stdFilterIP->SetFunctor( func2 ); TRY_EXPECT_NO_EXCEPTION( stdFilterIP->Update() ); std::cout << "Comparing lambdaFilter and cfpFilter (const functor) results" << std::endl; success &= compareImages( lambdaFilter->GetOutput(), cfpFilter->GetOutput() ); std::cout << "Comparing lambdaFilter and stdFilter (const functor) results" << std::endl; success &= compareImages( lambdaFilter->GetOutput(), stdFilter->GetOutput() ); std::cout << "Comparing lambdaFilter and cfpFilter (in-place functor) results" << std::endl; success &= compareImages( lambdaFilter->GetOutput(), cfpFilterIP->GetOutput() ); std::cout << "Comparing lambdaFilter and stdFilter (in-place functor) results" << std::endl; success &= compareImages( lambdaFilter->GetOutput(), stdFilterIP->GetOutput() ); if ( success ) { std::cout << "Test PASSED!" << std::endl; return EXIT_SUCCESS; } else { std::cout << "Test FAILED!" << std::endl; return EXIT_FAILURE; } }
/*========================================================================= * * Copyright Insight Software Consortium * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0.txt * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * *=========================================================================*/ #include "itkFrequencyBandImageFilter.h" #include "itkUnaryFrequencyDomainFilter.h" #include "itkAddImageFilter.h" #include "itkFrequencyShiftedFFTLayoutImageRegionIteratorWithIndex.h" #include "itkImage.h" #include "itkImageFileWriter.h" #include "itkTestingComparisonImageFilter.h" #include "itkTestingMacros.h" namespace { template< typename ImageType > bool compareImages( ImageType* baseline, ImageType* test ) { using DifferenceFilterType = itk::Testing::ComparisonImageFilter< ImageType, ImageType >; auto differenceFilter = DifferenceFilterType::New(); differenceFilter->SetToleranceRadius( 0 ); differenceFilter->SetDifferenceThreshold( 0 ); differenceFilter->SetValidInput( baseline ); differenceFilter->SetTestInput( test ); differenceFilter->Update(); unsigned int numberOfDiffPixels = differenceFilter->GetNumberOfPixelsWithDifferences(); if ( numberOfDiffPixels > 0 ) { std::cerr << "Expected images to be equal, but got " << numberOfDiffPixels << "unequal pixels" << std::endl; return false; } return true; } template< typename ImageType > typename ImageType::Pointer createImage( typename ImageType::SizeType size ) { auto image = ImageType::New(); typename ImageType::RegionType region; region.SetSize( size ); image->SetRegions( region ); image->Allocate( false ); typename ImageType::PixelType value = itk::NumericTraits< typename ImageType::PixelType >::Zero; itk::ImageRegionIterator< ImageType > iter( image, region ); while ( !iter.IsAtEnd() ) { iter.Set( ++value ); ++iter; } return image; } } // namespace int itkFrequencyBandImageFilterTest( int argc, char* argv[] ) { constexpr unsigned int Dimension = 3; if ( argc != 2 ) { std::cerr << "Usage: " << argv[0] << " Even|Odd" << std::endl; return EXIT_FAILURE; } const std::string evenOrOddInput = argv[1]; bool isOdd = false; if ( evenOrOddInput == "Even" ) { isOdd = false; } else if ( evenOrOddInput == "Odd" ) { isOdd = true; } else { std::cerr << "Unkown string: " + evenOrOddInput + " . Use Even or Odd." << std::endl; return EXIT_FAILURE; } using PixelType = float; using ImageType3D = itk::Image< PixelType, Dimension >; ImageType3D::SizeType size = { { 10, 20, 40 } }; if ( isOdd ) { for ( unsigned int i = 0; i < Dimension; ++i ) { size[i]++; } } auto image = createImage< ImageType3D >( size ); using BandFilterType = itk::FrequencyBandImageFilter< ImageType3D >; auto passBandFilter = BandFilterType::New(); EXERCISE_BASIC_OBJECT_METHODS( passBandFilter, FrequencyBandImageFilter, UnaryFrequencyDomainFilter ); passBandFilter->SetInput( image ); // Test exception cases BandFilterType::FrequencyValueType lowFreqThreshold = 0.5; passBandFilter->SetLowFrequencyThreshold( lowFreqThreshold ); TEST_SET_GET_VALUE( lowFreqThreshold, passBandFilter->GetLowFrequencyThreshold() ); BandFilterType::FrequencyValueType highFreqThreshold = 0.0; passBandFilter->SetHighFrequencyThreshold( highFreqThreshold ); TEST_SET_GET_VALUE( highFreqThreshold, passBandFilter->GetHighFrequencyThreshold() ); TRY_EXPECT_EXCEPTION( passBandFilter->Update() ); lowFreqThreshold = 0.0; passBandFilter->SetLowFrequencyThreshold( lowFreqThreshold ); TEST_SET_GET_VALUE( lowFreqThreshold, passBandFilter->GetLowFrequencyThreshold() ); highFreqThreshold = 0.5; passBandFilter->SetHighFrequencyThreshold( highFreqThreshold ); TEST_SET_GET_VALUE( highFreqThreshold, passBandFilter->GetHighFrequencyThreshold() ); bool passBand = true; TEST_SET_GET_BOOLEAN( passBandFilter, PassBand, passBand ); bool passLowFreqThreshold = true; TEST_SET_GET_BOOLEAN( passBandFilter, PassLowFrequencyThreshold, passLowFreqThreshold ); bool passHighFreqThreshold = true; TEST_SET_GET_BOOLEAN( passBandFilter, PassHighFrequencyThreshold, passHighFreqThreshold ); passBandFilter->SetPassBand( passLowFreqThreshold, passHighFreqThreshold ); TEST_SET_GET_VALUE( passLowFreqThreshold, passBandFilter->GetPassLowFrequencyThreshold() ); TEST_SET_GET_VALUE( passHighFreqThreshold, passBandFilter->GetPassHighFrequencyThreshold() ); TRY_EXPECT_NO_EXCEPTION( passBandFilter->Update() ); // Stop-band auto stopBandFilter = BandFilterType::New(); stopBandFilter->SetInput( image ); stopBandFilter->SetLowFrequencyThreshold( lowFreqThreshold ); stopBandFilter->SetHighFrequencyThreshold( highFreqThreshold ); passLowFreqThreshold = false; passHighFreqThreshold = false; stopBandFilter->SetStopBand( passLowFreqThreshold, passHighFreqThreshold ); TEST_SET_GET_VALUE( passLowFreqThreshold, stopBandFilter->GetPassLowFrequencyThreshold() ); TEST_SET_GET_VALUE( passHighFreqThreshold, stopBandFilter->GetPassHighFrequencyThreshold() ); TRY_EXPECT_NO_EXCEPTION( stopBandFilter->Update() ); // Regression test // Sum of bandPass and stopBand images with these settings should be equal // to original image using AddFilterType = itk::AddImageFilter< ImageType3D, ImageType3D >; auto addFilter = AddFilterType::New(); addFilter->SetInput1( passBandFilter->GetOutput() ); addFilter->SetInput2( stopBandFilter->GetOutput() ); std::cout << "Comparing the original and sum of bandPass and stopBand images" << std::endl; bool success = compareImages( image.GetPointer(), addFilter->GetOutput() ); // Tests with radians BandFilterType::FrequencyValueType lowFreqThresholdRadians = itk::Math::pi_over_4; passBandFilter->SetLowFrequencyThresholdInRadians( lowFreqThresholdRadians ); BandFilterType::FrequencyValueType highFreqThresholdRadians = itk::Math::pi_over_2; passBandFilter->SetHighFrequencyThresholdInRadians( highFreqThresholdRadians ); BandFilterType::FrequencyValueType knownLowFrequencyHertz = lowFreqThresholdRadians / ( 2 * itk::Math::pi ); BandFilterType::FrequencyValueType knownHighFrequencyHertz = highFreqThresholdRadians / ( 2 * itk::Math::pi ); if ( itk::Math::NotAlmostEquals( knownLowFrequencyHertz, passBandFilter->GetLowFrequencyThreshold() ) || itk::Math::NotAlmostEquals( knownHighFrequencyHertz, passBandFilter->GetHighFrequencyThreshold() ) ) { std::cerr << "Test failed! " << std::endl; std::cerr << "Setting frequency in radians failed." << std::endl; success = false; } TRY_EXPECT_NO_EXCEPTION( passBandFilter->Update() ); // Test the non-radial cut-off. // Don't pass negative frequency thresholds. bool radialBand = false; TEST_SET_GET_BOOLEAN( passBandFilter, RadialBand, radialBand ); bool passNegativeLowFrequencyThreshold = false; TEST_SET_GET_BOOLEAN( passBandFilter, PassNegativeLowFrequencyThreshold, passNegativeLowFrequencyThreshold ); bool passNegativeHighFrequencyThreshold = false; TEST_SET_GET_BOOLEAN( passBandFilter, PassNegativeHighFrequencyThreshold, passNegativeHighFrequencyThreshold ); passBandFilter->Update(); // Test with ShiftedIterator. using FrequencyShiftedIterator = itk::FrequencyShiftedFFTLayoutImageRegionIteratorWithIndex< ImageType3D >; using BandShiftedFilterType = itk::FrequencyBandImageFilter< ImageType3D, FrequencyShiftedIterator >; auto passBandShiftedFilter = BandShiftedFilterType::New(); passBandShiftedFilter->SetInput( image ); passBandShiftedFilter->SetLowFrequencyThreshold( lowFreqThreshold ); passBandShiftedFilter->SetHighFrequencyThreshold( highFreqThreshold ); passBandShiftedFilter->SetPassBand( true ); passLowFreqThreshold = false; passHighFreqThreshold = true; passBandShiftedFilter->SetPassBand( passLowFreqThreshold, passHighFreqThreshold ); TRY_EXPECT_NO_EXCEPTION( passBandShiftedFilter->Update() ); // Stop-band with InPlaceOn auto stopBandInPlaceFilter = BandFilterType::New(); stopBandInPlaceFilter->InPlaceOn(); stopBandInPlaceFilter->SetInput( image ); stopBandInPlaceFilter->SetLowFrequencyThreshold( lowFreqThreshold ); stopBandInPlaceFilter->SetHighFrequencyThreshold( highFreqThreshold ); passLowFreqThreshold = false; passHighFreqThreshold = false; stopBandInPlaceFilter->SetStopBand( passLowFreqThreshold, passHighFreqThreshold ); TRY_EXPECT_NO_EXCEPTION( stopBandInPlaceFilter->Update() ); std::cout << "Comparing stopBand and stopBandInPlaceFilter results" << std::endl; success &= compareImages( stopBandFilter->GetOutput(), stopBandInPlaceFilter->GetOutput() ); // Custom functor UnaryFrequencyDomainFilter using UnaryFilterType = itk::UnaryFrequencyDomainFilter< ImageType3D >; using ValueFunctionType = UnaryFilterType::ValueFunctionType; using ConstRefFunctionType = UnaryFilterType::ConstRefFunctionType; auto testFilter = UnaryFilterType::New(); EXERCISE_BASIC_OBJECT_METHODS( testFilter, UnaryFrequencyDomainFilter, InPlaceImageFilter ); struct TestStruct { static double ConstUnaryFunction( const UnaryFilterType::FrequencyIteratorType& freqIt ) { return std::sin( freqIt.GetFrequencyModuloSquare() * 10 ); } static void UnaryFunction( UnaryFilterType::FrequencyIteratorType& freqIt ) { freqIt.Value() *= std::sin( freqIt.GetFrequencyModuloSquare() * 10 ); } }; auto inPlaceLambda = []( UnaryFilterType::FrequencyIteratorType& freqIt ) { freqIt.Value() *= std::sin( freqIt.GetFrequencyModuloSquare() * 10 ); }; image = createImage< ImageType3D >( size ); // stopBandInPlaceFilter has modified the original one // Test with lambda function auto lambdaFilter = UnaryFilterType::New(); lambdaFilter->SetInput( image ); lambdaFilter->SetFunctor( inPlaceLambda ); TRY_EXPECT_NO_EXCEPTION( lambdaFilter->Update() ); // Test with C style function pointer auto cfpFilter = UnaryFilterType::New(); cfpFilter->SetInput( image ); cfpFilter->SetFunctor( static_cast< ConstRefFunctionType* >( TestStruct::ConstUnaryFunction ) ); TRY_EXPECT_NO_EXCEPTION( cfpFilter->Update() ); // Test with std::functional auto stdFilter = UnaryFilterType::New(); stdFilter->SetInput( image ); std::function< double( const UnaryFilterType::FrequencyIteratorType& ) > func1 = static_cast< ConstRefFunctionType* >( TestStruct::ConstUnaryFunction ); stdFilter->SetFunctor( func1 ); TRY_EXPECT_NO_EXCEPTION( stdFilter->Update() ); // Test with C style function pointer (in-place variant) auto cfpFilterIP = UnaryFilterType::New(); cfpFilterIP->SetInput( image ); cfpFilterIP->SetFunctor( static_cast< ValueFunctionType* >( TestStruct::UnaryFunction ) ); TRY_EXPECT_NO_EXCEPTION( cfpFilterIP->Update() ); // Test with std::functional (in-place variant) auto stdFilterIP = UnaryFilterType::New(); stdFilterIP->SetInput( image ); std::function< void( UnaryFilterType::FrequencyIteratorType& ) > func2 = static_cast< ValueFunctionType* >( TestStruct::UnaryFunction ); stdFilterIP->SetFunctor( func2 ); TRY_EXPECT_NO_EXCEPTION( stdFilterIP->Update() ); std::cout << "Comparing lambdaFilter and cfpFilter (const functor) results" << std::endl; success &= compareImages( lambdaFilter->GetOutput(), cfpFilter->GetOutput() ); std::cout << "Comparing lambdaFilter and stdFilter (const functor) results" << std::endl; success &= compareImages( lambdaFilter->GetOutput(), stdFilter->GetOutput() ); std::cout << "Comparing lambdaFilter and cfpFilter (in-place functor) results" << std::endl; success &= compareImages( lambdaFilter->GetOutput(), cfpFilterIP->GetOutput() ); std::cout << "Comparing lambdaFilter and stdFilter (in-place functor) results" << std::endl; success &= compareImages( lambdaFilter->GetOutput(), stdFilterIP->GetOutput() ); if ( success ) { std::cout << "Test PASSED!" << std::endl; return EXIT_SUCCESS; } else { std::cout << "Test FAILED!" << std::endl; return EXIT_FAILURE; } }
test image was not properly initialized. Closes #207.
BUG: test image was not properly initialized. Closes #207.
C++
apache-2.0
blowekamp/ITK,fbudin69500/ITK,vfonov/ITK,richardbeare/ITK,vfonov/ITK,malaterre/ITK,richardbeare/ITK,malaterre/ITK,Kitware/ITK,thewtex/ITK,hjmjohnson/ITK,LucasGandel/ITK,blowekamp/ITK,malaterre/ITK,richardbeare/ITK,hjmjohnson/ITK,BRAINSia/ITK,thewtex/ITK,vfonov/ITK,LucasGandel/ITK,LucasGandel/ITK,vfonov/ITK,thewtex/ITK,fbudin69500/ITK,Kitware/ITK,hjmjohnson/ITK,richardbeare/ITK,Kitware/ITK,LucasGandel/ITK,LucasGandel/ITK,fbudin69500/ITK,LucasGandel/ITK,vfonov/ITK,Kitware/ITK,LucasGandel/ITK,BRAINSia/ITK,fbudin69500/ITK,richardbeare/ITK,malaterre/ITK,thewtex/ITK,fbudin69500/ITK,hjmjohnson/ITK,malaterre/ITK,BRAINSia/ITK,InsightSoftwareConsortium/ITK,malaterre/ITK,fbudin69500/ITK,vfonov/ITK,vfonov/ITK,InsightSoftwareConsortium/ITK,InsightSoftwareConsortium/ITK,blowekamp/ITK,blowekamp/ITK,fbudin69500/ITK,thewtex/ITK,blowekamp/ITK,hjmjohnson/ITK,BRAINSia/ITK,InsightSoftwareConsortium/ITK,thewtex/ITK,malaterre/ITK,richardbeare/ITK,BRAINSia/ITK,InsightSoftwareConsortium/ITK,blowekamp/ITK,BRAINSia/ITK,blowekamp/ITK,fbudin69500/ITK,Kitware/ITK,Kitware/ITK,richardbeare/ITK,malaterre/ITK,BRAINSia/ITK,hjmjohnson/ITK,thewtex/ITK,hjmjohnson/ITK,vfonov/ITK,InsightSoftwareConsortium/ITK,blowekamp/ITK,Kitware/ITK,LucasGandel/ITK,malaterre/ITK,vfonov/ITK,InsightSoftwareConsortium/ITK
7a6729003d4c87520367e2be169d928c248b929f
Modules/Radiometry/SARCalibration/include/otbS1ThermalNoiseLookupData.hxx
Modules/Radiometry/SARCalibration/include/otbS1ThermalNoiseLookupData.hxx
/* * Copyright (C) 2005-2020 Centre National d'Etudes Spatiales (CNES) * * This file is part of Orfeo Toolbox * * https://www.orfeo-toolbox.org/ * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef otbS1ThermalNoiseLookupData_hxx #define otbS1ThermalNoiseLookupData_hxx #include "otbS1ThermalNoiseLookupData.h" namespace otb { template <class T> void S1ThermalNoiseLookupData<T>::SetImageKeywordlist(const ImageKeywordlist & kwl) { m_FirstLineTime = ossimplugins::time::toModifiedJulianDate(kwl.GetMetadataByKey("calibration.startTime")).as_day_frac(); m_LastLineTime = ossimplugins::time::toModifiedJulianDate(kwl.GetMetadataByKey("calibration.stopTime")).as_day_frac(); m_NumOfLines = std::stoi(kwl.GetMetadataByKey("number_lines")); m_LineTimeInterval = (m_LastLineTime - m_FirstLineTime) / (m_NumOfLines - 1); m_RangeCount = std::stoi(kwl.GetMetadataByKey("noise.rangeCount")); m_RangeNoiseVectorList.clear(); double lastMJD = 0; for (int i = 0; i < m_RangeCount; i++) { const std::string prefix = "noise.noiseVector[" + std::to_string(i) + "]."; Sentinel1CalibrationStruct rangeNoiseVector; rangeNoiseVector.timeMJD = ossimplugins::time::toModifiedJulianDate(kwl.GetMetadataByKey(prefix + "azimuthTime")).as_day_frac(); rangeNoiseVector.deltaMJD = rangeNoiseVector.timeMJD - lastMJD; rangeNoiseVector.line = std::stoi(kwl.GetMetadataByKey(prefix + "line")); Utils::ConvertStringToVector(kwl.GetMetadataByKey( prefix + "pixel"), rangeNoiseVector.pixels, prefix + "pixel"); Utils::ConvertStringToVector(kwl.GetMetadataByKey( prefix + "noiseLut"), rangeNoiseVector.vect, prefix + "noiseLut"); int prevPixel = 0; for (const auto & pixel: rangeNoiseVector.pixels) { rangeNoiseVector.deltaPixels.push_back(pixel - prevPixel); prevPixel = pixel; } m_RangeNoiseVectorList.push_back(rangeNoiseVector); lastMJD = rangeNoiseVector.timeMJD; } if (kwl.HasKey("noise.azimuthCount")) { m_AzimuthCount = std::stoi(kwl.GetMetadataByKey("noise.azimuthCount")); for (int i = 0; i < m_AzimuthCount; i++) { const std::string prefix = "noise.noiseAzimuthVector[" + std::to_string(i) + "]."; Sentinel1AzimuthNoiseStruct azimuthNoiseVector; azimuthNoiseVector.firstAzimuthLine = std::stoi(kwl.GetMetadataByKey(prefix + "firstAzimuthLine")); azimuthNoiseVector.firstRangeSample = std::stoi(kwl.GetMetadataByKey(prefix + "firstRangeSample")); azimuthNoiseVector.lastAzimuthLine = std::stoi(kwl.GetMetadataByKey(prefix + "lastAzimuthLine")); azimuthNoiseVector.lastRangeSample = std::stoi(kwl.GetMetadataByKey(prefix + "lastRangeSample")); Utils::ConvertStringToVector(kwl.GetMetadataByKey( prefix + "line"), azimuthNoiseVector.lines, prefix + "line"); Utils::ConvertStringToVector(kwl.GetMetadataByKey( prefix + "noiseAzimuthLut"), azimuthNoiseVector.vect, prefix + "noiseAzimuthLut"); m_AzimuthNoiseVectorList.push_back(azimuthNoiseVector); } } } template <class T> T S1ThermalNoiseLookupData<T>::GetValue(const IndexValueType x, const IndexValueType y) { return GetRangeNoise(x,y) * GetAzimuthNoise(x,y); } template <class T> T S1ThermalNoiseLookupData<T>::GetRangeNoise(const IndexValueType x, const IndexValueType y) { if (m_RangeCount) { const auto vecIdx = GetRangeVectorIndex(y); assert(vecIdx >= 0 && vecIdx < m_RangeCount - 1); const auto& vec0 = m_RangeNoiseVectorList[vecIdx]; const auto& vec1 = m_RangeNoiseVectorList[vecIdx + 1]; const auto azTime = m_FirstLineTime + y * m_LineTimeInterval; const auto muY = (azTime - vec0.timeMJD) / vec1.deltaMJD; const auto pixelIdx = GetPixelIndex(x, vec0.pixels); const double muX = (x - vec0.pixels[pixelIdx]) / vec0.deltaPixels[pixelIdx + 1]; const double lutVal = (1 - muY) * ((1 - muX) * vec0.vect[pixelIdx] + muX * vec0.vect[pixelIdx + 1]) + muY * ((1 - muX) * vec1.vect[pixelIdx] + muX * vec1.vect[pixelIdx + 1]); return lutVal; } else { return 1.; } } template <class T> T S1ThermalNoiseLookupData<T>::GetAzimuthNoise(const IndexValueType x, const IndexValueType y) { if (m_AzimuthCount) { const auto vecIdx = GetAzimuthVectorIndex(x, y); const auto& vec = m_AzimuthNoiseVectorList[vecIdx]; const auto pixelIdx = GetPixelIndex(y, vec.lines); const double lutVal = vec.vect[pixelIdx] + ( (y - vec.lines[pixelIdx]) / (vec.lines[pixelIdx+1] - vec.lines[pixelIdx]) ) * (vec.vect[pixelIdx + 1] - vec.vect[pixelIdx]); return lutVal; } else { return 1.; } } template <class T> int S1ThermalNoiseLookupData<T>::GetRangeVectorIndex(int y) const { for (int i = 1; i < m_RangeCount; i++) { if (y <= m_RangeNoiseVectorList[i].line) { return i - 1; } } return -1; } template <class T> int S1ThermalNoiseLookupData<T>::GetAzimuthVectorIndex(int x, int y) const { for (int i = 0; i < m_AzimuthCount; i++) { const auto & azimuthVector = m_AzimuthNoiseVectorList[i]; if (x >= azimuthVector.firstRangeSample && x <= azimuthVector.lastRangeSample && y >= azimuthVector.firstAzimuthLine && y <= azimuthVector.lastAzimuthLine) { return i; } } return -1; } template <class T> int S1ThermalNoiseLookupData<T>::GetPixelIndex(int x, const std::vector<int> & vec) const { const int size = vec.size(); std::vector<int>::const_iterator wh = std::upper_bound(vec.begin(), vec.end(), x); return wh == vec.end() ? size - 2 : std::distance(vec.begin(), wh) - 1; } } #endif
/* * Copyright (C) 2005-2020 Centre National d'Etudes Spatiales (CNES) * * This file is part of Orfeo Toolbox * * https://www.orfeo-toolbox.org/ * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef otbS1ThermalNoiseLookupData_hxx #define otbS1ThermalNoiseLookupData_hxx #include "otbS1ThermalNoiseLookupData.h" namespace otb { template <class T> void S1ThermalNoiseLookupData<T>::SetImageKeywordlist(const ImageKeywordlist & kwl) { m_FirstLineTime = ossimplugins::time::toModifiedJulianDate(kwl.GetMetadataByKey("calibration.startTime")).as_day_frac(); m_LastLineTime = ossimplugins::time::toModifiedJulianDate(kwl.GetMetadataByKey("calibration.stopTime")).as_day_frac(); m_NumOfLines = std::stoi(kwl.GetMetadataByKey("number_lines")); m_LineTimeInterval = (m_LastLineTime - m_FirstLineTime) / (m_NumOfLines - 1); m_RangeCount = std::stoi(kwl.GetMetadataByKey("noise.rangeCount")); m_RangeNoiseVectorList.clear(); double lastMJD = 0; for (int i = 0; i < m_RangeCount; i++) { const std::string prefix = "noise.noiseVector[" + std::to_string(i) + "]."; Sentinel1CalibrationStruct rangeNoiseVector; rangeNoiseVector.timeMJD = ossimplugins::time::toModifiedJulianDate(kwl.GetMetadataByKey(prefix + "azimuthTime")).as_day_frac(); rangeNoiseVector.deltaMJD = rangeNoiseVector.timeMJD - lastMJD; rangeNoiseVector.line = std::stoi(kwl.GetMetadataByKey(prefix + "line")); Utils::ConvertStringToVector(kwl.GetMetadataByKey( prefix + "pixel"), rangeNoiseVector.pixels, prefix + "pixel"); Utils::ConvertStringToVector(kwl.GetMetadataByKey( prefix + "noiseLut"), rangeNoiseVector.vect, prefix + "noiseLut"); int prevPixel = 0; for (const auto & pixel: rangeNoiseVector.pixels) { rangeNoiseVector.deltaPixels.push_back(pixel - prevPixel); prevPixel = pixel; } m_RangeNoiseVectorList.push_back(rangeNoiseVector); lastMJD = rangeNoiseVector.timeMJD; } if (kwl.HasKey("noise.azimuthCount")) { m_AzimuthCount = std::stoi(kwl.GetMetadataByKey("noise.azimuthCount")); for (int i = 0; i < m_AzimuthCount; i++) { const std::string prefix = "noise.noiseAzimuthVector[" + std::to_string(i) + "]."; Sentinel1AzimuthNoiseStruct azimuthNoiseVector; azimuthNoiseVector.firstAzimuthLine = std::stoi(kwl.GetMetadataByKey(prefix + "firstAzimuthLine")); azimuthNoiseVector.firstRangeSample = std::stoi(kwl.GetMetadataByKey(prefix + "firstRangeSample")); azimuthNoiseVector.lastAzimuthLine = std::stoi(kwl.GetMetadataByKey(prefix + "lastAzimuthLine")); azimuthNoiseVector.lastRangeSample = std::stoi(kwl.GetMetadataByKey(prefix + "lastRangeSample")); Utils::ConvertStringToVector(kwl.GetMetadataByKey( prefix + "line"), azimuthNoiseVector.lines, prefix + "line"); Utils::ConvertStringToVector(kwl.GetMetadataByKey( prefix + "noiseAzimuthLut"), azimuthNoiseVector.vect, prefix + "noiseAzimuthLut"); m_AzimuthNoiseVectorList.push_back(azimuthNoiseVector); } } } template <class T> T S1ThermalNoiseLookupData<T>::GetValue(const IndexValueType x, const IndexValueType y) { return GetRangeNoise(x,y) * GetAzimuthNoise(x,y); } template <class T> T S1ThermalNoiseLookupData<T>::GetRangeNoise(const IndexValueType x, const IndexValueType y) { if (m_RangeCount) { const auto vecIdx = GetRangeVectorIndex(y); assert(vecIdx >= 0 && vecIdx < m_RangeCount - 1); const auto& vec0 = m_RangeNoiseVectorList[vecIdx]; const auto& vec1 = m_RangeNoiseVectorList[vecIdx + 1]; const auto azTime = m_FirstLineTime + y * m_LineTimeInterval; const auto muY = (azTime - vec0.timeMJD) / vec1.deltaMJD; const auto pixelIdx = GetPixelIndex(x, vec0.pixels); const double muX = (x - vec0.pixels[pixelIdx]) / vec0.deltaPixels[pixelIdx + 1]; const double lutVal = (1 - muY) * ((1 - muX) * vec0.vect[pixelIdx] + muX * vec0.vect[pixelIdx + 1]) + muY * ((1 - muX) * vec1.vect[pixelIdx] + muX * vec1.vect[pixelIdx + 1]); return lutVal; } else { return 1.; } } template <class T> T S1ThermalNoiseLookupData<T>::GetAzimuthNoise(const IndexValueType x, const IndexValueType y) { if (m_AzimuthCount) { const auto vecIdx = GetAzimuthVectorIndex(x, y); const auto& vec = m_AzimuthNoiseVectorList[vecIdx]; const auto pixelIdx = GetPixelIndex(y, vec.lines); const double lutVal = vec.vect[pixelIdx] + ( (y - vec.lines[pixelIdx]) / (vec.lines[pixelIdx+1] - vec.lines[pixelIdx]) ) * (vec.vect[pixelIdx + 1] - vec.vect[pixelIdx]); const double lutVal = vec.vect[pixelIdx] + (vec.vect[pixelIdx + 1] - vec.vect[pixelIdx]) * ( double((y - vec.lines[pixelIdx])) / double((vec.lines[pixelIdx+1] - vec.lines[pixelIdx])) ); return lutVal; } else { return 1.; } } template <class T> int S1ThermalNoiseLookupData<T>::GetRangeVectorIndex(int y) const { for (int i = 1; i < m_RangeCount; i++) { if (y <= m_RangeNoiseVectorList[i].line) { return i - 1; } } return -1; } template <class T> int S1ThermalNoiseLookupData<T>::GetAzimuthVectorIndex(int x, int y) const { for (int i = 0; i < m_AzimuthCount; i++) { const auto & azimuthVector = m_AzimuthNoiseVectorList[i]; if (x >= azimuthVector.firstRangeSample && x <= azimuthVector.lastRangeSample && y >= azimuthVector.firstAzimuthLine && y <= azimuthVector.lastAzimuthLine) { return i; } } return -1; } template <class T> int S1ThermalNoiseLookupData<T>::GetPixelIndex(int x, const std::vector<int> & vec) const { const int size = vec.size(); std::vector<int>::const_iterator wh = std::upper_bound(vec.begin(), vec.end(), x); return wh == vec.end() ? size - 2 : std::distance(vec.begin(), wh) - 1; } } #endif
fix computation of interpolation of azimuth noise lut
fix computation of interpolation of azimuth noise lut
C++
apache-2.0
orfeotoolbox/OTB,orfeotoolbox/OTB,orfeotoolbox/OTB,orfeotoolbox/OTB,orfeotoolbox/OTB,orfeotoolbox/OTB
14ab6b5078a3513a2b8f57f630e078450ab17e1d
ray-tracer.cpp
ray-tracer.cpp
// Copyright 2013 Sean McKenna // // 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. // // a ray tracer in C++ // libraries, namespace #include <thread> #include <fstream> #include "library/loadXML.cpp" #include "library/scene.cpp" using namespace std; // scene to load (project #) & whether to debug const char* xml = "scenes/prj2.xml"; bool printXML = false; // for ray tracing int w; int h; int size; Color24 white; Color24 black; Color24* img; float* zImg; void objectIntersection(Node &n, Ray r, int pixel); // for threading static const int numThreads = 8; void rayTracing(int i); // for camera ray generation void cameraRayVars(); Point *imageTopLeftV; Point *dXV; Point *dYV; Point firstPixel; Transformation* c; Point cameraRay(int pX, int pY); // ray tracer int main(){ // load scene: root node, camera, image loadScene(xml, printXML); // set up colors & background image color white.Set(233, 233, 233); black.Set(33, 33, 33); render.setBackground(black); // set variables for ray tracing w = render.getWidth(); h = render.getHeight(); size = render.getSize(); img = render.getRender(); zImg = render.getZBuffer(); // set variables for generating camera rays cameraRayVars(); // start ray tracing loop (in parallel with threads) thread t[numThreads]; for(int i = 0; i < numThreads; i++) t[i] = thread(rayTracing, i); // when finished, join all threads back to main for(int i = 0; i < numThreads; i++) t[i].join(); // output ray-traced image & z-buffer (if uncommented) render.save("images/image.ppm"); //render.computeZBuffer(); //render.saveZBuffer("images/imageZ.ppm"); } // ray tracing loop (for an individual pixel) void rayTracing(int i){ // initial starting pixel int pixel = i; // thread continuation condition while(pixel < size){ // establish pixel location int pX = pixel % w; int pY = pixel / w; // transform ray into world space Point rayDir = cameraRay(pX, pY); Ray *ray = new Ray(); ray->pos = camera.pos; ray->dir = c->transformFrom(rayDir); // traverse through scene DOM // transform rays into model space // detect ray intersections & update pixel objectIntersection(rootNode, *ray, pixel); // re-assign next pixel (naive, but works) pixel += numThreads; } } // create variables for camera ray generation void cameraRayVars(){ float fov = camera.fov * M_PI / 180.0; float aspectRatio = (float) w / (float) h; float imageDistance = 1.0; float imageTipY = imageDistance * tan(fov / 2.0); float imageTipX = imageTipY * aspectRatio; float dX = (2.0 * imageTipX) / (float) w; float dY = (2.0 * imageTipY) / (float) h; imageTopLeftV = new Point(-imageTipX, imageTipY, -imageDistance); dXV = new Point(dX, 0.0, 0.0); dYV = new Point(0.0, -dY, 0.0); firstPixel = *imageTopLeftV + (*dXV * 0.5) + (*dYV * 0.5); // set up camera transformation (only need to rotate coordinates) c = new Transformation(); Matrix *rotate = new cyMatrix3f(); rotate->Set(camera.cross, camera.up, -camera.dir); c->transform(*rotate); } // compute camera rays Point cameraRay(int pX, int pY){ Point ray = firstPixel + (*dXV * pX) + (*dYV * pY); ray.Normalize(); return ray; } // recursive object intersection through all scene objects void objectIntersection(Node &n, Ray r, int pixel){ // loop on child nodes int j = 0; int numChild = n.getNumChild(); while(j < numChild){ // grab child node Node *child = n.getChild(j); Object *obj = child->getObject(); // transform rays into model space (or local space) Ray r2 = child->toModelSpace(r); // compute ray intersections HitInfo h = HitInfo(child); bool hit = obj->intersectRay(r2, h); // update pixel & z-buffer, only if node is closer if(hit){ if(h.z < zImg[pixel]){ zImg[pixel] = h.z; // transform hit information back to world space h.node->fromModelSpace(h); // get this node's material Material *m = h.node->getMaterial(); // shade the pixel appropriately img[pixel] = m->shade(r, h, lights, pixel); } } // recursively check this child's children objectIntersection(*child, r2, pixel); j++; } }
// Copyright 2013 Sean McKenna // // 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. // // a ray tracer in C++ // libraries, namespace #include <thread> #include <fstream> #include "library/loadXML.cpp" #include "library/scene.cpp" using namespace std; // scene to load (project #) & whether to debug const char* xml = "scenes/prj2.xml"; bool printXML = false; // for ray tracing int w; int h; int size; Color24 white; Color24 black; Color24* img; float* zImg; void objectIntersection(Node &n, Ray r, int pixel); // for threading static const int numThreads = 8; void rayTracing(int i); // for camera ray generation void cameraRayVars(); Point *imageTopLeftV; Point *dXV; Point *dYV; Point firstPixel; Transformation* c; Point cameraRay(int pX, int pY); // ray tracer int main(){ // load scene: root node, camera, image loadScene(xml, printXML); // set up colors & background image color white.Set(233, 233, 233); black.Set(33, 33, 33); render.setBackground(black); // set variables for ray tracing w = render.getWidth(); h = render.getHeight(); size = render.getSize(); img = render.getRender(); zImg = render.getZBuffer(); // set variables for generating camera rays cameraRayVars(); // start ray tracing loop (in parallel with threads) thread t[numThreads]; for(int i = 0; i < numThreads; i++) t[i] = thread(rayTracing, i); // when finished, join all threads back to main for(int i = 0; i < numThreads; i++) t[i].join(); // output ray-traced image & z-buffer (if uncommented) render.save("images/image.ppm"); //render.computeZBuffer(); //render.saveZBuffer("images/imageZ.ppm"); } // ray tracing loop (for an individual pixel) void rayTracing(int i){ // initial starting pixel int pixel = i; // thread continuation condition while(pixel < size){ // establish pixel location int pX = pixel % w; int pY = pixel / w; // transform ray into world space Point rayDir = cameraRay(pX, pY); Ray *ray = new Ray(); ray->pos = camera.pos; ray->dir = c->transformFrom(rayDir); // traverse through scene DOM // transform rays into model space // detect ray intersections & update pixel objectIntersection(rootNode, *ray, pixel); // re-assign next pixel (naive, but works) pixel += numThreads; } } // create variables for camera ray generation void cameraRayVars(){ float fov = camera.fov * M_PI / 180.0; float aspectRatio = (float) w / (float) h; float imageDistance = 1.0; float imageTipY = imageDistance * tan(fov / 2.0); float imageTipX = imageTipY * aspectRatio; float dX = (2.0 * imageTipX) / (float) w; float dY = (2.0 * imageTipY) / (float) h; imageTopLeftV = new Point(-imageTipX, imageTipY, -imageDistance); dXV = new Point(dX, 0.0, 0.0); dYV = new Point(0.0, -dY, 0.0); firstPixel = *imageTopLeftV + (*dXV * 0.5) + (*dYV * 0.5); // set up camera transformation (only need to rotate coordinates) c = new Transformation(); Matrix *rotate = new cyMatrix3f(); rotate->Set(camera.cross, camera.up, -camera.dir); c->transform(*rotate); } // compute camera rays Point cameraRay(int pX, int pY){ Point ray = firstPixel + (*dXV * pX) + (*dYV * pY); ray.Normalize(); return ray; } // recursive object intersection through all scene objects void objectIntersection(Node &n, Ray r, int pixel){ // loop on child nodes int j = 0; int numChild = n.getNumChild(); while(j < numChild){ // grab child node Node *child = n.getChild(j); Object *obj = child->getObject(); // transform rays into model space (or local space) Ray r2 = child->toModelSpace(r); // compute ray intersections HitInfo h = HitInfo(child); bool hit = obj->intersectRay(r2, h); // update pixel & z-buffer, only if node is closer if(hit){ if(h.z < zImg[pixel]){ zImg[pixel] = h.z; // transform hit information back to world space h.node->fromModelSpace(h); // get this node's material Material *m = h.node->getMaterial(); // shade the pixel appropriately img[pixel] = m->shade(r, h, lights); } } // recursively check this child's children objectIntersection(*child, r2, pixel); j++; } }
remove unneeded element from method so compiles now
remove unneeded element from method so compiles now
C++
mit
mckennapsean/ray-tracer,mckennapsean/ray-tracer,mckennapsean/ray-tracer
377a8f04a8612894b0e1e3731cc1e37e771298dc
src/gui/ng/scrollbar.cpp
src/gui/ng/scrollbar.cpp
#include "gui/ng/scrollbar.hpp" #include "gui/ng/colors.hpp" #include "gui/ng/button.hpp" namespace namelessgui { ScrollBar::ScrollBar() : currentValue_(0), maxValue_(1), stepSize_(0.1) { setOutlineColor(DEFAULT_OUTLINE_COLOR); setOutlineThickness(DEFAULT_OUTLINE_THICKNESS); scrollUpButton_ = new Button(); scrollUpButton_->signalClicked.connect([this] { slotScrollUpButtonClicked(); }); scrollUpButton_->setText("^"); scrollUpButton_->setSize(this->getSize()); addWidget(scrollUpButton_); scrollDownButton_ = new Button(); scrollDownButton_->signalClicked.connect([this] { slotScrollDownButtonClicked(); }); scrollDownButton_->setText("v"); scrollDownButton_->setSize(this->getSize()); scrollDownButton_->setAnchor({0, 1}); scrollDownButton_->setParentAnchor({0, 1}); addWidget(scrollDownButton_); } ScrollBar::~ScrollBar() { } void ScrollBar::setSize(const sf::Vector2f& size) { RectangularWidget::setSize(size); sf::Vector2f buttonSize(size.x, size.x); scrollUpButton_->setSize(buttonSize); scrollUpButton_->setFontSize(buttonSize.x); scrollDownButton_->setSize(buttonSize); scrollDownButton_->setFontSize(buttonSize.x); } void ScrollBar::slotScrollUpButtonClicked() { currentValue_ -= stepSize_; currentValue_ = std::max(0.0f, currentValue_); signalValueChanged.emit(currentValue_); } void ScrollBar::slotScrollDownButtonClicked() { currentValue_ += stepSize_; currentValue_ = std::min(maxValue_, currentValue_); signalValueChanged.emit(currentValue_); } } // namespace namelessgui
#include "gui/ng/scrollbar.hpp" #include "gui/ng/colors.hpp" #include "gui/ng/button.hpp" namespace namelessgui { ScrollBar::ScrollBar() : currentValue_(0), maxValue_(1), stepSize_(0.1) { setOutlineColor(DEFAULT_OUTLINE_COLOR); setOutlineThickness(DEFAULT_OUTLINE_THICKNESS); scrollUpButton_ = new Button(); scrollUpButton_->signalClicked.connect([this] { slotScrollUpButtonClicked(); }); scrollUpButton_->setText("^"); scrollUpButton_->setSize(this->getSize()); scrollUpButton_->setOutlineThickness(1); scrollUpButton_->setOutlineColor(DEFAULT_OUTLINE_COLOR); addWidget(scrollUpButton_); scrollDownButton_ = new Button(); scrollDownButton_->signalClicked.connect([this] { slotScrollDownButtonClicked(); }); scrollDownButton_->setText("v"); scrollDownButton_->setSize(this->getSize()); scrollDownButton_->setOutlineThickness(1); scrollDownButton_->setOutlineColor(DEFAULT_OUTLINE_COLOR); scrollDownButton_->setAnchor({0, 1}); scrollDownButton_->setParentAnchor({0, 1}); addWidget(scrollDownButton_); } ScrollBar::~ScrollBar() { } void ScrollBar::setSize(const sf::Vector2f& size) { RectangularWidget::setSize(size); sf::Vector2f buttonSize(size.x, size.x); scrollUpButton_->setSize(buttonSize); scrollUpButton_->setFontSize(buttonSize.x); scrollDownButton_->setSize(buttonSize); scrollDownButton_->setFontSize(buttonSize.x); } void ScrollBar::slotScrollUpButtonClicked() { currentValue_ -= stepSize_; currentValue_ = std::max(0.0f, currentValue_); signalValueChanged.emit(currentValue_); } void ScrollBar::slotScrollDownButtonClicked() { currentValue_ += stepSize_; currentValue_ = std::min(maxValue_, currentValue_); signalValueChanged.emit(currentValue_); } } // namespace namelessgui
Fix outline color for scroll bar buttons
Fix outline color for scroll bar buttons
C++
mit
namelessvoid/qrwar,namelessvoid/qrwar
0618977971d4fb3117879dc5cd4bc4feb41b1e10
src/hardware/SIM5218.cpp
src/hardware/SIM5218.cpp
#include "SIM5218.h" uint8_t _SIM5218_GPS::onOffGPS(uint8_t onOff, uint8_t opt) { uint8_t ret; snprintf_P(m_cmdBuffer, ATDEV_BUFF_CMD_SIZE, ATDEV_CMD_CGPS, onOff, opt); // send command ret = this->sendATCmd(); // command success if (ret == ATDEV_OK) { m_isGPSOn = !m_isGPSOn; } return this->waitDevice(ret); } uint8_t _SIM5218_GPS::receiveGPS() { char latPos, longPos, *date; // gps not running if (!m_isGPSOn) { return ATDEV_ERR_GPS_INIT; } // GPS command strncpy_P(m_cmdBuffer, ATDEV_CMD_CGPSINFO, ATDEV_BUFF_CMD_SIZE); // AT+CPGSINFO if (this->sendATCmd() != ATDEV_OK) { return ATDEV_ERR_UNEXPECTED_RESULT; } // parse if (this->parseInternalData() < 2) { return ATDEV_ERR_GPS_DATA; } //// // Parse GPS Data to gpsData class m_gpsData.cleanUp(); // Convert format from NMEA latPos = *(this->getParseElement(2)); longPos = *(this->getParseElement(4)); m_gpsData.convertNMEALatitude(this->getParseElement(1), latPos); m_gpsData.convertNMEALongitude(this->getParseElement(3), longPos); m_gpsData.m_altitude = atof(this->getParseElement(7)); m_gpsData.m_speed = atof(this->getParseElement(8)); strncpy(m_gpsData.m_time, this->getParseElement(6), ATDEV_GPS_TIME_SIZE); // convert Date memset(m_gpsData.m_date, 0x00, ATDEV_GPS_DATE_SIZE); date = this->getParseElement(5); m_gpsData.m_date[0] = 0x32; m_gpsData.m_date[2] = 0x30; m_gpsData.m_date[3] = date[4]; m_gpsData.m_date[4] = date[5]; m_gpsData.m_date[5] = date[0]; m_gpsData.m_date[6] = date[1]; m_gpsData.m_date[7] = date[2]; m_gpsData.m_date[8] = date[3]; return ATDEV_OK; } // vim: set sts=4 sw=4 ts=4 et:
#include "SIM5218.h" uint8_t _SIM5218_GPS::onOffGPS(uint8_t onOff, uint8_t opt) { uint8_t ret; snprintf_P(m_cmdBuffer, ATDEV_BUFF_CMD_SIZE, ATDEV_CMD_CGPS, onOff, opt); // send command ret = this->sendATCmd(); // command success if (ret == ATDEV_OK) { m_isGPSOn = !m_isGPSOn; } return this->waitDevice(ret); } uint8_t _SIM5218_GPS::receiveGPS() { char latPos, longPos, *date; // gps not running if (!m_isGPSOn) { return ATDEV_ERR_GPS_INIT; } // GPS command strncpy_P(m_cmdBuffer, ATDEV_CMD_CGPSINFO, ATDEV_BUFF_CMD_SIZE); // AT+CPGSINFO if (this->sendATCmd() != ATDEV_OK) { return ATDEV_ERR_UNEXPECTED_RESULT; } // parse if (this->parseInternalData() < 2) { return ATDEV_ERR_GPS_DATA; } //// // Parse GPS Data to gpsData class m_gpsData.cleanUp(); // Convert format from NMEA latPos = *(this->getParseElement(2)); longPos = *(this->getParseElement(4)); m_gpsData.convertNMEALatitude(this->getParseElement(1), latPos); m_gpsData.convertNMEALongitude(this->getParseElement(3), longPos); m_gpsData.m_altitude = atof(this->getParseElement(7)); m_gpsData.m_speed = atof(this->getParseElement(8)); strncpy(m_gpsData.m_time, this->getParseElement(6), ATDEV_GPS_TIME_SIZE); // convert Date memset(m_gpsData.m_date, 0x00, ATDEV_GPS_DATE_SIZE); date = this->getParseElement(5); m_gpsData.m_date[0] = 0x32; m_gpsData.m_date[1] = 0x30; m_gpsData.m_date[2] = date[4]; m_gpsData.m_date[3] = date[5]; m_gpsData.m_date[4] = date[0]; m_gpsData.m_date[5] = date[1]; m_gpsData.m_date[6] = date[2]; m_gpsData.m_date[7] = date[3]; return ATDEV_OK; } // vim: set sts=4 sw=4 ts=4 et:
fix date
fix date
C++
bsd-3-clause
pvizeli/ATDev,pvizeli/ATDev
eaad05533453f89d677fea1b6a1c467e83ade147
src/tcp_balancer.cxx
src/tcp_balancer.cxx
/* * Wrapper for the tcp_stock class to support load balancing. * * author: Max Kellermann <[email protected]> */ #include "tcp_balancer.hxx" #include "tcp_stock.hxx" #include "stock.hxx" #include "address_list.hxx" #include "balancer.hxx" #include "failure.hxx" #include "pool.hxx" #include "net/SocketAddress.hxx" #include <glib.h> struct tcp_balancer { StockMap *tcp_stock; struct balancer *balancer; }; struct tcp_balancer_request { struct pool *pool; struct tcp_balancer *tcp_balancer; bool ip_transparent; SocketAddress bind_address; /** * The "sticky id" of the incoming HTTP request. */ unsigned session_sticky; unsigned timeout; /** * The number of remaining connection attempts. We give up when * we get an error and this attribute is already zero. */ unsigned retries; const AddressList *address_list; SocketAddress current_address; const StockGetHandler *handler; void *handler_ctx; struct async_operation_ref *async_ref; }; static SocketAddress last_address; extern const StockGetHandler tcp_balancer_stock_handler; static void tcp_balancer_next(struct tcp_balancer_request *request) { const SocketAddress address = balancer_get(*request->tcp_balancer->balancer, *request->address_list, request->session_sticky); /* we need to copy this address because it may come from the balancer's cache, and the according cache item may be flushed at any time */ const struct sockaddr *new_address = (const struct sockaddr *) p_memdup(request->pool, address.GetAddress(), address.GetSize()); request->current_address = { new_address, address.GetSize() }; tcp_stock_get(request->tcp_balancer->tcp_stock, request->pool, nullptr, request->ip_transparent, request->bind_address, request->current_address, request->timeout, &tcp_balancer_stock_handler, request, request->async_ref); } /* * stock handler * */ static void tcp_balancer_stock_ready(StockItem &item, void *ctx) { struct tcp_balancer_request *request = (struct tcp_balancer_request *)ctx; last_address = request->current_address; failure_unset(request->current_address, FAILURE_FAILED); request->handler->ready(item, request->handler_ctx); } static void tcp_balancer_stock_error(GError *error, void *ctx) { struct tcp_balancer_request *request = (struct tcp_balancer_request *)ctx; failure_add(request->current_address); if (request->retries-- > 0) { /* try again, next address */ g_error_free(error); tcp_balancer_next(request); } else /* give up */ request->handler->error(error, request->handler_ctx); } const StockGetHandler tcp_balancer_stock_handler = { .ready = tcp_balancer_stock_ready, .error = tcp_balancer_stock_error, }; /* * constructor * */ struct tcp_balancer * tcp_balancer_new(struct pool *pool, StockMap *tcp_stock, struct balancer *balancer) { auto tcp_balancer = NewFromPool<struct tcp_balancer>(*pool); tcp_balancer->tcp_stock = tcp_stock; tcp_balancer->balancer = balancer; return tcp_balancer; } void tcp_balancer_get(struct tcp_balancer *tcp_balancer, struct pool *pool, bool ip_transparent, SocketAddress bind_address, unsigned session_sticky, const AddressList *address_list, unsigned timeout, const StockGetHandler *handler, void *handler_ctx, struct async_operation_ref *async_ref) { auto request = NewFromPool<struct tcp_balancer_request>(*pool); request->pool = pool; request->tcp_balancer = tcp_balancer; request->ip_transparent = ip_transparent; request->bind_address = bind_address; request->session_sticky = session_sticky; request->timeout = timeout; if (address_list->GetSize() <= 1) request->retries = 0; else if (address_list->GetSize() == 2) request->retries = 1; else if (address_list->GetSize() == 3) request->retries = 2; else request->retries = 3; request->address_list = address_list; request->handler = handler; request->handler_ctx = handler_ctx; request->async_ref = async_ref; tcp_balancer_next(request); } void tcp_balancer_put(struct tcp_balancer *tcp_balancer, StockItem &item, bool destroy) { tcp_stock_put(tcp_balancer->tcp_stock, item, destroy); } SocketAddress tcp_balancer_get_last() { return last_address; }
/* * Wrapper for the tcp_stock class to support load balancing. * * author: Max Kellermann <[email protected]> */ #include "tcp_balancer.hxx" #include "tcp_stock.hxx" #include "stock.hxx" #include "address_list.hxx" #include "balancer.hxx" #include "failure.hxx" #include "pool.hxx" #include "net/SocketAddress.hxx" #include <glib.h> struct tcp_balancer { StockMap *tcp_stock; struct balancer *balancer; tcp_balancer(StockMap &_tcp_stock, struct balancer &_balancer) :tcp_stock(&_tcp_stock), balancer(&_balancer) {} }; struct tcp_balancer_request { struct pool *pool; struct tcp_balancer *tcp_balancer; bool ip_transparent; SocketAddress bind_address; /** * The "sticky id" of the incoming HTTP request. */ unsigned session_sticky; unsigned timeout; /** * The number of remaining connection attempts. We give up when * we get an error and this attribute is already zero. */ unsigned retries; const AddressList *address_list; SocketAddress current_address; const StockGetHandler *handler; void *handler_ctx; struct async_operation_ref *async_ref; tcp_balancer_request(struct pool &_pool, struct tcp_balancer &_tcp_balancer, bool _ip_transparent, SocketAddress _bind_address, unsigned _session_sticky, unsigned _timeout, const AddressList &_address_list, const StockGetHandler &_handler, void *_handler_ctx, struct async_operation_ref &_async_ref) :pool(&_pool), tcp_balancer(&_tcp_balancer), ip_transparent(_ip_transparent), bind_address(_bind_address), session_sticky(_session_sticky), timeout(_timeout), address_list(&_address_list), handler(&_handler), handler_ctx(_handler_ctx), async_ref(&_async_ref) {} }; static SocketAddress last_address; extern const StockGetHandler tcp_balancer_stock_handler; static void tcp_balancer_next(struct tcp_balancer_request *request) { const SocketAddress address = balancer_get(*request->tcp_balancer->balancer, *request->address_list, request->session_sticky); /* we need to copy this address because it may come from the balancer's cache, and the according cache item may be flushed at any time */ const struct sockaddr *new_address = (const struct sockaddr *) p_memdup(request->pool, address.GetAddress(), address.GetSize()); request->current_address = { new_address, address.GetSize() }; tcp_stock_get(request->tcp_balancer->tcp_stock, request->pool, nullptr, request->ip_transparent, request->bind_address, request->current_address, request->timeout, &tcp_balancer_stock_handler, request, request->async_ref); } /* * stock handler * */ static void tcp_balancer_stock_ready(StockItem &item, void *ctx) { struct tcp_balancer_request *request = (struct tcp_balancer_request *)ctx; last_address = request->current_address; failure_unset(request->current_address, FAILURE_FAILED); request->handler->ready(item, request->handler_ctx); } static void tcp_balancer_stock_error(GError *error, void *ctx) { struct tcp_balancer_request *request = (struct tcp_balancer_request *)ctx; failure_add(request->current_address); if (request->retries-- > 0) { /* try again, next address */ g_error_free(error); tcp_balancer_next(request); } else /* give up */ request->handler->error(error, request->handler_ctx); } const StockGetHandler tcp_balancer_stock_handler = { .ready = tcp_balancer_stock_ready, .error = tcp_balancer_stock_error, }; /* * constructor * */ struct tcp_balancer * tcp_balancer_new(struct pool *pool, StockMap *tcp_stock, struct balancer *balancer) { return NewFromPool<struct tcp_balancer>(*pool, *tcp_stock, *balancer); } void tcp_balancer_get(struct tcp_balancer *tcp_balancer, struct pool *pool, bool ip_transparent, SocketAddress bind_address, unsigned session_sticky, const AddressList *address_list, unsigned timeout, const StockGetHandler *handler, void *handler_ctx, struct async_operation_ref *async_ref) { auto request = NewFromPool<struct tcp_balancer_request>(*pool, *pool, *tcp_balancer, ip_transparent, bind_address, session_sticky, timeout, *address_list, *handler, handler_ctx, *async_ref); if (address_list->GetSize() <= 1) request->retries = 0; else if (address_list->GetSize() == 2) request->retries = 1; else if (address_list->GetSize() == 3) request->retries = 2; else request->retries = 3; tcp_balancer_next(request); } void tcp_balancer_put(struct tcp_balancer *tcp_balancer, StockItem &item, bool destroy) { tcp_stock_put(tcp_balancer->tcp_stock, item, destroy); } SocketAddress tcp_balancer_get_last() { return last_address; }
add constructor
tcp_balancer: add constructor
C++
bsd-2-clause
CM4all/beng-proxy,CM4all/beng-proxy,CM4all/beng-proxy,CM4all/beng-proxy,CM4all/beng-proxy,CM4all/beng-proxy
c032b97ae887e42cd2b3171ea9c5c86fafbd734d
src/tcp_balancer.cxx
src/tcp_balancer.cxx
/* * Copyright 2007-2017 Content Management AG * All rights reserved. * * author: Max Kellermann <[email protected]> * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * - Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the * distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * FOUNDATION OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "tcp_balancer.hxx" #include "tcp_stock.hxx" #include "generic_balancer.hxx" #include "stock/GetHandler.hxx" struct TcpBalancer { TcpStock &tcp_stock; Balancer balancer; explicit TcpBalancer(TcpStock &_tcp_stock) :tcp_stock(_tcp_stock) {} }; struct TcpBalancerRequest : public StockGetHandler { TcpBalancer &tcp_balancer; const bool ip_transparent; const SocketAddress bind_address; const unsigned timeout; StockGetHandler &handler; TcpBalancerRequest(TcpBalancer &_tcp_balancer, bool _ip_transparent, SocketAddress _bind_address, unsigned _timeout, StockGetHandler &_handler) :tcp_balancer(_tcp_balancer), ip_transparent(_ip_transparent), bind_address(_bind_address), timeout(_timeout), handler(_handler) {} void Send(struct pool &pool, SocketAddress address, CancellablePointer &cancel_ptr); /* virtual methods from class StockGetHandler */ void OnStockItemReady(StockItem &item) override; void OnStockItemError(std::exception_ptr ep) override; }; inline void TcpBalancerRequest::Send(struct pool &pool, SocketAddress address, CancellablePointer &cancel_ptr) { tcp_balancer.tcp_stock.Get(pool, nullptr, ip_transparent, bind_address, address, timeout, *this, cancel_ptr); } /* * stock handler * */ void TcpBalancerRequest::OnStockItemReady(StockItem &item) { auto &base = BalancerRequest<TcpBalancerRequest>::Cast(*this); base.Success(); handler.OnStockItemReady(item); } void TcpBalancerRequest::OnStockItemError(std::exception_ptr ep) { auto &base = BalancerRequest<TcpBalancerRequest>::Cast(*this); if (!base.Failure()) handler.OnStockItemError(ep); } /* * constructor * */ TcpBalancer * tcp_balancer_new(TcpStock &tcp_stock) { return new TcpBalancer(tcp_stock); } void tcp_balancer_free(TcpBalancer *tcp_balancer) { delete tcp_balancer; } void tcp_balancer_get(TcpBalancer &tcp_balancer, struct pool &pool, bool ip_transparent, SocketAddress bind_address, sticky_hash_t session_sticky, const AddressList &address_list, unsigned timeout, StockGetHandler &handler, CancellablePointer &cancel_ptr) { BalancerRequest<TcpBalancerRequest>::Start(pool, tcp_balancer.balancer, address_list, cancel_ptr, session_sticky, tcp_balancer, ip_transparent, bind_address, timeout, handler); }
/* * Copyright 2007-2017 Content Management AG * All rights reserved. * * author: Max Kellermann <[email protected]> * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * - Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the * distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * FOUNDATION OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "tcp_balancer.hxx" #include "tcp_stock.hxx" #include "generic_balancer.hxx" #include "stock/GetHandler.hxx" struct TcpBalancer { TcpStock &tcp_stock; Balancer balancer; explicit TcpBalancer(TcpStock &_tcp_stock) :tcp_stock(_tcp_stock) {} void Get(struct pool &pool, bool ip_transparent, SocketAddress bind_address, sticky_hash_t session_sticky, const AddressList &address_list, unsigned timeout, StockGetHandler &handler, CancellablePointer &cancel_ptr); }; struct TcpBalancerRequest : public StockGetHandler { TcpBalancer &tcp_balancer; const bool ip_transparent; const SocketAddress bind_address; const unsigned timeout; StockGetHandler &handler; TcpBalancerRequest(TcpBalancer &_tcp_balancer, bool _ip_transparent, SocketAddress _bind_address, unsigned _timeout, StockGetHandler &_handler) :tcp_balancer(_tcp_balancer), ip_transparent(_ip_transparent), bind_address(_bind_address), timeout(_timeout), handler(_handler) {} void Send(struct pool &pool, SocketAddress address, CancellablePointer &cancel_ptr); /* virtual methods from class StockGetHandler */ void OnStockItemReady(StockItem &item) override; void OnStockItemError(std::exception_ptr ep) override; }; inline void TcpBalancerRequest::Send(struct pool &pool, SocketAddress address, CancellablePointer &cancel_ptr) { tcp_balancer.tcp_stock.Get(pool, nullptr, ip_transparent, bind_address, address, timeout, *this, cancel_ptr); } /* * stock handler * */ void TcpBalancerRequest::OnStockItemReady(StockItem &item) { auto &base = BalancerRequest<TcpBalancerRequest>::Cast(*this); base.Success(); handler.OnStockItemReady(item); } void TcpBalancerRequest::OnStockItemError(std::exception_ptr ep) { auto &base = BalancerRequest<TcpBalancerRequest>::Cast(*this); if (!base.Failure()) handler.OnStockItemError(ep); } /* * constructor * */ TcpBalancer * tcp_balancer_new(TcpStock &tcp_stock) { return new TcpBalancer(tcp_stock); } void tcp_balancer_free(TcpBalancer *tcp_balancer) { delete tcp_balancer; } void TcpBalancer::Get(struct pool &pool, bool ip_transparent, SocketAddress bind_address, sticky_hash_t session_sticky, const AddressList &address_list, unsigned timeout, StockGetHandler &handler, CancellablePointer &cancel_ptr) { BalancerRequest<TcpBalancerRequest>::Start(pool, balancer, address_list, cancel_ptr, session_sticky, *this, ip_transparent, bind_address, timeout, handler); } void tcp_balancer_get(TcpBalancer &tcp_balancer, struct pool &pool, bool ip_transparent, SocketAddress bind_address, sticky_hash_t session_sticky, const AddressList &address_list, unsigned timeout, StockGetHandler &handler, CancellablePointer &cancel_ptr) { return tcp_balancer.Get(pool, ip_transparent, bind_address, session_sticky, address_list, timeout, handler, cancel_ptr); }
move code to struct TcpBalancer
tcp_balancer: move code to struct TcpBalancer
C++
bsd-2-clause
CM4all/beng-proxy,CM4all/beng-proxy,CM4all/beng-proxy,CM4all/beng-proxy,CM4all/beng-proxy,CM4all/beng-proxy
4df8269864f4cf77966651d6d982cf87c231fa34
ouzel/input/windows/KeyboardDeviceWin.cpp
ouzel/input/windows/KeyboardDeviceWin.cpp
// Copyright 2015-2018 Elviss Strazdins. All rights reserved. #ifndef NOMINMAX # define NOMINMAX #endif #include <Windows.h> #include "KeyboardDeviceWin.hpp" namespace ouzel { namespace input { void KeyboardDeviceWin::handleKeyPress(Keyboard::Key key, uint32_t modifiers) { if (key == Keyboard::Key::LEFT_SHIFT) leftShiftDown = true; if (key == Keyboard::Key::RIGHT_SHIFT) rightShiftDown = true; KeyboardDevice::handleKeyPress(key, modifiers); } void KeyboardDeviceWin::update() { if (leftShiftDown && (GetKeyState(VK_LSHIFT) & 0x8000) == 0) handleKeyRelease(Keyboard::Key::LEFT_SHIFT, 0); if (rightShiftDown && (GetKeyState(VK_RSHIFT) & 0x8000) == 0) handleKeyRelease(Keyboard::Key::RIGHT_SHIFT, 0); } } // namespace input } // namespace ouzel
// Copyright 2015-2018 Elviss Strazdins. All rights reserved. #ifndef NOMINMAX # define NOMINMAX #endif #include <Windows.h> #include "KeyboardDeviceWin.hpp" namespace ouzel { namespace input { void KeyboardDeviceWin::handleKeyPress(Keyboard::Key key, uint32_t modifiers) { if (key == Keyboard::Key::LEFT_SHIFT) leftShiftDown = true; if (key == Keyboard::Key::RIGHT_SHIFT) rightShiftDown = true; KeyboardDevice::handleKeyPress(key, modifiers); } void KeyboardDeviceWin::update() { if (leftShiftDown && (GetKeyState(VK_LSHIFT) & 0x8000) == 0) { leftShiftDown = false; handleKeyRelease(Keyboard::Key::LEFT_SHIFT, 0); } if (rightShiftDown && (GetKeyState(VK_RSHIFT) & 0x8000) == 0) { rightShiftDown = false; handleKeyRelease(Keyboard::Key::RIGHT_SHIFT, 0); } } } // namespace input } // namespace ouzel
Reset the down flags
Reset the down flags
C++
unlicense
elvman/ouzel,elvman/ouzel,elnormous/ouzel,elnormous/ouzel,elnormous/ouzel
778833598b48eba0f4d96168e59ec4c524c53c81
src/base_controller/src/serial_controller/serial_controller_node.cpp
src/base_controller/src/serial_controller/serial_controller_node.cpp
/*! \brief serial_controller_node. * Manages serial communications with AVR-Master. * * This node manages serial communications with the AVR-Master. * Therefore it first requests all data from AVR-Master and then sends all * commands to AVR-Master in a Loop. Data read is stored in md49_data.txt, * commands to be send are read from md49_commands.txt. * */ // Includes // ********************************************************* #include <iostream> /* allows to perform standard input and output operations */ #include <fstream> /* Input/output stream class to operate on files. */ #include <stdio.h> /* Standard input/output definitions */ #include <stdint.h> /* Standard input/output definitions */ #include <stdlib.h> /* defines several general purpose functions */ #include <unistd.h> /* UNIX standard function definitions */ #include <fcntl.h> /* File control definitions */ #include <errno.h> /* Error number definitions */ #include <termios.h> /* POSIX terminal control definitions */ #include <ctype.h> /* isxxx() */ //#include<ros/ros.h> #include <sqlite3.h> // Global variables const char* serialport_name="//dev/ttyAMA0"; /* defines used serialport on BPi. Use "/dev/ttyAMA0" for RPi*/ int serialport_bps=B38400; /* defines used baudrate on serialport */ //int filedesc; /* File descriptor of serial port we will talk to*/ int fd; /* serial port file descriptor */ int32_t EncoderL; /* stores encoder value left read from md49 */ int32_t EncoderR; /* stores encoder value right read from md49 */ unsigned char speed_l=128, speed_r=128; /* speed to set for MD49 */ unsigned char last_speed_l=128, last_speed_r=128; /* speed to set for MD49 */ unsigned char serialBuffer[16]; /* Serial buffer to store uart data */ unsigned char md49_data[18]; /* keeps data from MD49, read from AVR-Master */ struct termios orig; // backuped port options // sqlite globals sqlite3 *db; char *zErrMsg = 0; int rc; const char *sql; const char* data = "Callback function called"; using namespace std; // Declare functions // ********************************************************* int openSerialPort(const char * device, int bps); void writeBytes(int descriptor, int count); void readBytes(int descriptor, int count); void open_sqlite_db_md49data(void); static int sql_callback(void *data, int argc, char **argv, char **azColName); void read_MD49_Data_serial (void); void read_md49_commands(void); void set_MD49_speed (unsigned char speed_l, unsigned char speed_r); char* itoa(int value, char* result, int base); void open_sqlite_db_md49data(void){ // Open database md49data.db and add // table md49data // ********************************* rc = sqlite3_open("data/md49data.db", &db); if( rc ){ fprintf(stderr, "Can't open database: %s\n", sqlite3_errmsg(db)); exit(0); }else{ fprintf(stdout, "Opened database successfully,\n"); } // Create table md49data // ********************* sql = "CREATE TABLE md49data(" \ "ID INT PRIMARY KEY NOT NULL," \ "Encoderbyte1L INT DEFAULT 0," \ "Encoderbyte2L INT DEFAULT 0," \ "Encoderbyte3L INT DEFAULT 0," \ "Encoderbyte4L INT DEFAULT 0," \ "Encoderbyte1R INT DEFAULT 0," \ "Encoderbyte2R INT DEFAULT 0," \ "Encoderbyte3R INT DEFAULT 0," \ "Encoderbyte4R INT DEFAULT 0," \ "EncoderL INT DEFAULT 0," \ "EncoderR INT DEFAULT 0," \ "SpeedL INT DEFAULT 0," \ "SpeedR INT DEFAULT 0," \ "Volts INT DEFAULT 0," \ "CurrentL INT DEFAULT 0," \ "CurrentR INT DEFAULT 0," \ "Error INT DEFAULT 0," \ "Acceleration INT DEFAULT 0," \ "Mode INT DEFAULT 0," \ "Regulator INT DEFAULT 0," \ "Timeout INT DEFAULT 0 );" \ "INSERT INTO md49data (ID) VALUES (1);"; /* Execute SQL statement */ rc = sqlite3_exec(db, sql, NULL, 0, &zErrMsg); if( rc != SQLITE_OK ){ fprintf(stderr, "SQL message: %s\n", zErrMsg); sqlite3_free(zErrMsg); }else{ fprintf(stdout, "table created successfully\n"); } } int main( int argc, char* argv[] ){ // Init as ROS node // **************** //ros::init(argc, argv, "serial_controller"); //ros::NodeHandle n; // Open sqlite database md49data.db // ******************************** open_sqlite_db_md49data(); // Open serial port // **************** fd = openSerialPort(serialport_name, serialport_bps); if (fd == -1) exit(1); //ROS_INFO("Opend serial port at %s with %i Bps",serialport_name,serialport_bps); usleep(10000); // Sleep for UART to power up and set options //ROS_DEBUG("Starting Mainloop..."); //ROS_DEBUG("reading data from MD49 and pushing commands to MD49 @ 5Hz..."); // Mainloop // *********************************** //while( n.ok() ){ while( 1 ){ // Read encodervalues and other data from MD49 // serial. Data ist stored in md49_data.txt // **************************************** read_MD49_Data_serial(); usleep(100000); // Read commands from md49_commands.txt: // ************************************* read_md49_commands(); // Set speed and other commands as // read from md49_commands.txt // ******************************* set_MD49_speed(speed_l, speed_r); usleep(100000); }// end.mainloop sqlite3_close(db); return 1; } // end.main void read_MD49_Data_serial (void){ // Read serial MD49 data from AVR-Master // ************************************* serialBuffer[0] = 82; // 82=R Steuerbyte um alle Daten vom MD49 zu lesen writeBytes(fd, 1); readBytes(fd, 18); // Put toghether encoder values from their // corresponding bytes, read from MD49 // *************************************** EncoderL = serialBuffer[0] << 24; // Put together first encoder value EncoderL |= (serialBuffer[1] << 16); EncoderL |= (serialBuffer[2] << 8); EncoderL |= (serialBuffer[3]); EncoderR = serialBuffer[4] << 24; // Put together second encoder value EncoderR |= (serialBuffer[5] << 16); EncoderR |= (serialBuffer[6] << 8); EncoderR |= (serialBuffer[7]); // Write data read from MD49 into // sqlite3 database md49data.db // ****************************** //char* sql_buffer; char sql_buffer[200]; int cx; cx = snprintf (sql_buffer,200,"UPDATE md49data SET EncoderL=%i, EncoderR=%i WHERE ID=1", EncoderL,EncoderR); rc = sqlite3_exec(db, sql_buffer, NULL, 0, &zErrMsg); if( rc != SQLITE_OK ){ fprintf(stderr, "SQL message: %s\n", zErrMsg); sqlite3_free(zErrMsg); }else{ //fprintf(stdout, "Operation done successfully\n"); } /* // Write data from MD49 into md49_data.txt // *************************************** int i=0; char buffer[33]; ofstream myfile; myfile.open ("md49_data.txt"); //myfile << "Writing this to a file.\n"; for (i=0;i<18;i++){ if (serialBuffer[i]==0){ myfile << "000"; } else if (serialBuffer[i]<10){ myfile << "00"; myfile << itoa(serialBuffer[i],buffer,10); } else if (serialBuffer[i]<100){ myfile << "0"; myfile << itoa(serialBuffer[i],buffer,10); } else{ myfile << itoa(serialBuffer[i],buffer,10); } myfile << "\n"; } myfile.close(); */ // Output MD49 data on screen // ************************** printf("\033[2J"); // clear the screen printf("\033[H"); // position cursor at top-left corner printf ("MD49-Data read from AVR-Master: \n"); printf("========================================\n"); printf("Encoder1 Byte1: %i ",serialBuffer[0]); printf("Byte2: %i ",serialBuffer[1]); printf("Byte3: % i ",serialBuffer[2]); printf("Byte4: %i \n",serialBuffer[3]); printf("Encoder2 Byte1: %i ",serialBuffer[4]); printf("Byte2: %i ",serialBuffer[5]); printf("Byte3: %i ",serialBuffer[6]); printf("Byte4: %i \n",serialBuffer[7]); printf("EncoderL: %i ",EncoderL); printf("EncoderR: %i \n",EncoderR); printf("========================================\n"); printf("Speed1: %i ",serialBuffer[8]); printf("Speed2: %i \n",serialBuffer[9]); printf("Volts: %i \n",serialBuffer[10]); printf("Current1: %i ",serialBuffer[11]); printf("Current2: %i \n",serialBuffer[12]); printf("Error: %i \n",serialBuffer[13]); printf("Acceleration: %i \n",serialBuffer[14]); printf("Mode: %i \n",serialBuffer[15]); printf("Regulator: %i \n",serialBuffer[16]); printf("Timeout: %i \n",serialBuffer[17]); } void set_MD49_speed (unsigned char speed_l, unsigned char speed_r){ serialBuffer[0] = 88; // 88 =X Steuerbyte um Commands an MD49 zu senden serialBuffer[1] = 115; // 115=s Steuerbyte setSpeed serialBuffer[2] = speed_l; // set speed1 serialBuffer[3] = speed_r; // set speed2 writeBytes(fd, 4); } void read_md49_commands(void){ /* Create SQL statement */ sql = "SELECT * from md49commands WHERE ID=1"; /* Execute SQL statement */ rc = sqlite3_exec(db, sql, sql_callback, (void*)data, &zErrMsg); if( rc != SQLITE_OK ){ fprintf(stderr, "SQL message: %s\n", zErrMsg); sqlite3_free(zErrMsg); }else{ //fprintf(stdout, "Query done successfully\n"); } } int openSerialPort(const char * device, int bps){ struct termios neu; char buf[128]; //fd = open(device, O_RDWR | O_NOCTTY | O_NDELAY | O_NONBLOCK); fd = open(device, O_RDWR | O_NOCTTY); if (fd == -1) { sprintf(buf, "openSerialPort %s error", device); perror(buf); } else { tcgetattr(fd, &orig); /* save current serial settings */ tcgetattr(fd, &neu); cfmakeraw(&neu); cfsetispeed(&neu, bps); cfsetospeed(&neu, bps); tcflush(fd, TCIFLUSH); tcsetattr(fd, TCSANOW, &neu); /* set new serial settings */ fcntl (fd, F_SETFL, O_RDWR); } return fd; } void writeBytes(int descriptor, int count) { if ((write(descriptor, serialBuffer, count)) == -1) { // Send data out perror("Error writing"); close(descriptor); // Close port if there is an error exit(1); } } void readBytes(int descriptor, int count) { if (read(descriptor, serialBuffer, count) == -1) { // Read back data into buf[] perror("Error reading "); close(descriptor); // Close port if there is an error exit(1); } } static int sql_callback(void *data, int argc, char **argv, char **azColName){ speed_l= atoi(argv[1]); speed_r= atoi(argv[2]); printf("SpeedL=%i\n",speed_l); printf("SpeedR=%i\n",speed_r); return 0; } char* itoa(int value, char* result, int base) { // check that the base if valid if (base < 2 || base > 36) { *result = '\0'; return result; } char* ptr = result, *ptr1 = result, tmp_char; int tmp_value; do { tmp_value = value; value /= base; *ptr++ = "zyxwvutsrqponmlkjihgfedcba9876543210123456789abcdefghijklmnopqrstuvwxyz" [35 + (tmp_value - value * base)]; } while ( value ); // Apply negative sign if (tmp_value < 0) *ptr++ = '-'; *ptr-- = '\0'; while(ptr1 < ptr) { tmp_char = *ptr; *ptr--= *ptr1; *ptr1++ = tmp_char; } return result; }
/*! \brief serial_controller_node. * Manages serial communications with AVR-Master. * * This node manages serial communications with the AVR-Master. * Therefore it first requests all data from AVR-Master and then sends all * commands to AVR-Master in a Loop. Data read is stored in md49_data.txt, * commands to be send are read from md49_commands.txt. * */ // Includes // ********************************************************* #include <iostream> /* allows to perform standard input and output operations */ #include <fstream> /* Input/output stream class to operate on files. */ #include <stdio.h> /* Standard input/output definitions */ #include <stdint.h> /* Standard input/output definitions */ #include <stdlib.h> /* defines several general purpose functions */ #include <unistd.h> /* UNIX standard function definitions */ #include <fcntl.h> /* File control definitions */ #include <errno.h> /* Error number definitions */ #include <termios.h> /* POSIX terminal control definitions */ #include <ctype.h> /* isxxx() */ //#include<ros/ros.h> #include <sqlite3.h> // Global variables const char* serialport_name="//dev/ttyAMA0"; /* defines used serialport on BPi. Use "/dev/ttyAMA0" for RPi*/ int serialport_bps=B38400; /* defines used baudrate on serialport */ //int filedesc; /* File descriptor of serial port we will talk to*/ int fd; /* serial port file descriptor */ int32_t EncoderL; /* stores encoder value left read from md49 */ int32_t EncoderR; /* stores encoder value right read from md49 */ unsigned char speed_l=128, speed_r=128; /* speed to set for MD49 */ unsigned char last_speed_l=128, last_speed_r=128; /* speed to set for MD49 */ unsigned char serialBuffer[16]; /* Serial buffer to store uart data */ unsigned char md49_data[18]; /* keeps data from MD49, read from AVR-Master */ struct termios orig; // backuped port options // sqlite globals sqlite3 *db; char *zErrMsg = 0; int rc; const char *sql; const char* data = "Callback function called"; using namespace std; // Declare functions // ********************************************************* int openSerialPort(const char * device, int bps); void writeBytes(int descriptor, int count); void readBytes(int descriptor, int count); void open_sqlite_db_md49data(void); static int sql_callback(void *data, int argc, char **argv, char **azColName); void read_MD49_Data_serial (void); void read_md49_commands(void); void set_MD49_speed (unsigned char speed_l, unsigned char speed_r); int main( int argc, char* argv[] ){ // Init as ROS node // **************** //ros::init(argc, argv, "serial_controller"); //ros::NodeHandle n; // Open sqlite database md49data.db // ******************************** open_sqlite_db_md49data(); // Open serial port // **************** fd = openSerialPort(serialport_name, serialport_bps); if (fd == -1) exit(1); //ROS_INFO("Opend serial port at %s with %i Bps",serialport_name,serialport_bps); usleep(10000); // Sleep for UART to power up and set options //ROS_DEBUG("Starting Mainloop..."); //ROS_DEBUG("reading data from MD49 and pushing commands to MD49 @ 5Hz..."); // Mainloop // *********************************** //while( n.ok() ){ while( 1 ){ // Read encodervalues and other data from MD49 // serial. Data ist stored in md49_data.txt // **************************************** read_MD49_Data_serial(); usleep(100000); // Read commands from md49_commands.txt: // ************************************* read_md49_commands(); // Set speed and other commands as // read from md49_commands.txt // ******************************* if ((speed_l != last_speed_l) || (speed_r != last_speed_r)){ set_MD49_speed(speed_l, speed_r); last_speed_l=speed_l; last_speed_r=speed_r; } usleep(100000); }// end.mainloop sqlite3_close(db); return 1; } // end.main void read_MD49_Data_serial (void){ // Read serial MD49 data from AVR-Master // ************************************* serialBuffer[0] = 82; // 82=R Steuerbyte um alle Daten vom MD49 zu lesen writeBytes(fd, 1); readBytes(fd, 18); // Put toghether encoder values from their // corresponding bytes, read from MD49 // *************************************** EncoderL = serialBuffer[0] << 24; // Put together first encoder value EncoderL |= (serialBuffer[1] << 16); EncoderL |= (serialBuffer[2] << 8); EncoderL |= (serialBuffer[3]); EncoderR = serialBuffer[4] << 24; // Put together second encoder value EncoderR |= (serialBuffer[5] << 16); EncoderR |= (serialBuffer[6] << 8); EncoderR |= (serialBuffer[7]); // Write data read from MD49 into // sqlite3 database md49data.db // ****************************** //char* sql_buffer; char sql_buffer[200]; int cx; cx = snprintf (sql_buffer,200,"UPDATE md49data SET EncoderL=%i, EncoderR=%i WHERE ID=1", EncoderL,EncoderR); rc = sqlite3_exec(db, sql_buffer, NULL, 0, &zErrMsg); if( rc != SQLITE_OK ){ fprintf(stderr, "SQL message: %s\n", zErrMsg); sqlite3_free(zErrMsg); }else{ //fprintf(stdout, "Operation done successfully\n"); } /* // Write data from MD49 into md49_data.txt // *************************************** int i=0; char buffer[33]; ofstream myfile; myfile.open ("md49_data.txt"); //myfile << "Writing this to a file.\n"; for (i=0;i<18;i++){ if (serialBuffer[i]==0){ myfile << "000"; } else if (serialBuffer[i]<10){ myfile << "00"; myfile << itoa(serialBuffer[i],buffer,10); } else if (serialBuffer[i]<100){ myfile << "0"; myfile << itoa(serialBuffer[i],buffer,10); } else{ myfile << itoa(serialBuffer[i],buffer,10); } myfile << "\n"; } myfile.close(); */ // Output MD49 data on screen // ************************** printf("\033[2J"); // clear the screen printf("\033[H"); // position cursor at top-left corner printf ("MD49-Data read from AVR-Master: \n"); printf("========================================\n"); printf("Encoder1 Byte1: %i ",serialBuffer[0]); printf("Byte2: %i ",serialBuffer[1]); printf("Byte3: % i ",serialBuffer[2]); printf("Byte4: %i \n",serialBuffer[3]); printf("Encoder2 Byte1: %i ",serialBuffer[4]); printf("Byte2: %i ",serialBuffer[5]); printf("Byte3: %i ",serialBuffer[6]); printf("Byte4: %i \n",serialBuffer[7]); printf("EncoderL: %i ",EncoderL); printf("EncoderR: %i \n",EncoderR); printf("========================================\n"); printf("Speed1: %i ",serialBuffer[8]); printf("Speed2: %i \n",serialBuffer[9]); printf("Volts: %i \n",serialBuffer[10]); printf("Current1: %i ",serialBuffer[11]); printf("Current2: %i \n",serialBuffer[12]); printf("Error: %i \n",serialBuffer[13]); printf("Acceleration: %i \n",serialBuffer[14]); printf("Mode: %i \n",serialBuffer[15]); printf("Regulator: %i \n",serialBuffer[16]); printf("Timeout: %i \n",serialBuffer[17]); } void set_MD49_speed (unsigned char speed_l, unsigned char speed_r){ serialBuffer[0] = 88; // 88 =X Steuerbyte um Commands an MD49 zu senden serialBuffer[1] = 115; // 115=s Steuerbyte setSpeed serialBuffer[2] = speed_l; // set speed1 serialBuffer[3] = speed_r; // set speed2 writeBytes(fd, 4); } void read_md49_commands(void){ /* Create SQL statement */ sql = "SELECT * from md49commands WHERE ID=1"; /* Execute SQL statement */ rc = sqlite3_exec(db, sql, sql_callback, (void*)data, &zErrMsg); if( rc != SQLITE_OK ){ fprintf(stderr, "SQL message: %s\n", zErrMsg); sqlite3_free(zErrMsg); }else{ //fprintf(stdout, "Query done successfully\n"); } } int openSerialPort(const char * device, int bps){ struct termios neu; char buf[128]; //fd = open(device, O_RDWR | O_NOCTTY | O_NDELAY | O_NONBLOCK); fd = open(device, O_RDWR | O_NOCTTY); if (fd == -1) { sprintf(buf, "openSerialPort %s error", device); perror(buf); } else { tcgetattr(fd, &orig); /* save current serial settings */ tcgetattr(fd, &neu); cfmakeraw(&neu); cfsetispeed(&neu, bps); cfsetospeed(&neu, bps); tcflush(fd, TCIFLUSH); tcsetattr(fd, TCSANOW, &neu); /* set new serial settings */ fcntl (fd, F_SETFL, O_RDWR); } return fd; } void writeBytes(int descriptor, int count) { if ((write(descriptor, serialBuffer, count)) == -1) { // Send data out perror("Error writing"); close(descriptor); // Close port if there is an error exit(1); } } void readBytes(int descriptor, int count) { if (read(descriptor, serialBuffer, count) == -1) { // Read back data into buf[] perror("Error reading "); close(descriptor); // Close port if there is an error exit(1); } } void open_sqlite_db_md49data(void){ // Open database md49data.db and add // table md49data // ********************************* rc = sqlite3_open("data/md49data.db", &db); if( rc ){ fprintf(stderr, "Can't open database: %s\n", sqlite3_errmsg(db)); exit(0); }else{ fprintf(stdout, "Opened database successfully,\n"); } // Create table md49data // ********************* sql = "CREATE TABLE md49data(" \ "ID INT PRIMARY KEY NOT NULL," \ "Encoderbyte1L INT DEFAULT 0," \ "Encoderbyte2L INT DEFAULT 0," \ "Encoderbyte3L INT DEFAULT 0," \ "Encoderbyte4L INT DEFAULT 0," \ "Encoderbyte1R INT DEFAULT 0," \ "Encoderbyte2R INT DEFAULT 0," \ "Encoderbyte3R INT DEFAULT 0," \ "Encoderbyte4R INT DEFAULT 0," \ "EncoderL INT DEFAULT 0," \ "EncoderR INT DEFAULT 0," \ "SpeedL INT DEFAULT 0," \ "SpeedR INT DEFAULT 0," \ "Volts INT DEFAULT 0," \ "CurrentL INT DEFAULT 0," \ "CurrentR INT DEFAULT 0," \ "Error INT DEFAULT 0," \ "Acceleration INT DEFAULT 0," \ "Mode INT DEFAULT 0," \ "Regulator INT DEFAULT 0," \ "Timeout INT DEFAULT 0 );" \ "INSERT INTO md49data (ID) VALUES (1);"; /* Execute SQL statement */ rc = sqlite3_exec(db, sql, NULL, 0, &zErrMsg); if( rc != SQLITE_OK ){ fprintf(stderr, "SQL message: %s\n", zErrMsg); sqlite3_free(zErrMsg); }else{ fprintf(stdout, "table created successfully\n"); } } static int sql_callback(void *data, int argc, char **argv, char **azColName){ speed_l= atoi(argv[1]); speed_r= atoi(argv[2]); //printf("SpeedL=%i\n",speed_l); //printf("SpeedR=%i\n",speed_r); return 0; }
Update code
Update code
C++
bsd-3-clause
Scheik/ROS-Groovy-Workspace,Scheik/ROS-Workspace,Scheik/ROS-Workspace,Scheik/ROS-Groovy-Workspace
947c0567dcf73ece475135c4e1dc9b79daa82c06
src/tests/parser.cpp
src/tests/parser.cpp
// Copyright 2014 Tony Wasserka // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of the owner 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 <vector> #include <ostream> #include "nihstro/parser_assembly.h" #include "nihstro/parser_assembly_private.h" #include <boost/optional/optional_io.hpp> #include <boost/spirit/include/qi.hpp> #define BOOST_TEST_MODULE Parser #include <boost/test/unit_test.hpp> // Utility function to parse the given input. Upon match, returns the parsed contents, and returns no value upon failure. template<typename Attr, typename Parser, typename Skipper> static boost::optional<Attr> parse(const std::string& input, const Parser& parser, const Skipper& skipper) { Attr attr; std::string inp(input); if (boost::spirit::qi::phrase_parse(inp.begin(), inp.end(), parser, skipper, attr)) return attr; else return {}; } // Utility function to check that the given vectors are equal. template<typename T> static void CheckVector(const std::vector<T>& vec, const std::vector<T>& exp) { // TODO: Could just check directly for equality, but need an ostream<< operator for that. BOOST_CHECK_EQUAL(vec.size(), exp.size()); for (size_t index = 0; index < vec.size() && index < exp.size(); ++index) BOOST_CHECK_EQUAL(vec[index], exp[index]); } // Utility function to check that parsing of the first declaration statement was successfull and that the result matches the second declaration statements. static void CheckDeclaration(const boost::optional<StatementDeclaration>& declaration, const StatementDeclaration& exp) { if (!declaration) { BOOST_CHECK(false); } else { BOOST_CHECK_EQUAL(declaration->alias_name, exp.alias_name); BOOST_CHECK_EQUAL(declaration->identifier_start, exp.identifier_start); BOOST_CHECK_EQUAL(declaration->identifier_end, exp.identifier_end); BOOST_CHECK_EQUAL(declaration->swizzle_mask, exp.swizzle_mask); CheckVector(declaration->extra.constant_value, exp.extra.constant_value); BOOST_CHECK_EQUAL(declaration->extra.output_semantic, exp.extra.output_semantic); } } // Utility function to convert a compile-time character to the corresponding swizzle mask component template<char a> static InputSwizzlerMask::Component MakeSwizzlerMaskComponent() { static_assert(a == 'x' || a == 'y' || a == 'z' || a == 'w', "Invalid component"); if (a == 'x') return InputSwizzlerMask::x; else if (a == 'y') return InputSwizzlerMask::y; else if (a == 'z') return InputSwizzlerMask::z; else return InputSwizzlerMask::w; } // Utility function to convert a series of up to four characters to the corresponding swizzle mask template<char a> static InputSwizzlerMask MakeInputSwizzlerMask() { return { 1, { MakeSwizzlerMaskComponent<a>() } }; } template<char a, char b> static InputSwizzlerMask MakeInputSwizzlerMask() { return { 2, { MakeSwizzlerMaskComponent<a>(), MakeSwizzlerMaskComponent<b>() } }; } template<char a, char b, char c> static InputSwizzlerMask MakeInputSwizzlerMask() { return { 3, { MakeSwizzlerMaskComponent<a>(), MakeSwizzlerMaskComponent<b>(), MakeSwizzlerMaskComponent<c>() } }; } template<char a, char b, char c, char d> static InputSwizzlerMask MakeInputSwizzlerMask() { return { 4, { MakeSwizzlerMaskComponent<a>(), MakeSwizzlerMaskComponent<b>(), MakeSwizzlerMaskComponent<c>(), MakeSwizzlerMaskComponent<d>() } }; } BOOST_AUTO_TEST_CASE(declaration) { ParserContext context; DeclarationParser<std::string::iterator> declaration_parser(context); AssemblySkipper<std::string::iterator> skipper; { // Plain alias auto declaration = parse<StatementDeclaration>(".alias my_alias r5.xy", declaration_parser, skipper); CheckDeclaration(declaration, { "my_alias", "r5", {}, MakeInputSwizzlerMask<'x', 'y'>() }); } { // Array alias auto declaration = parse<StatementDeclaration>(".alias my_alias r5-r10", declaration_parser, skipper); CheckDeclaration(declaration, { "my_alias", "r5", std::string("r10") }); } { // Output alias auto declaration = parse<StatementDeclaration>(".alias my_alias o5.xyz as texcoord0", declaration_parser, skipper); CheckDeclaration(declaration, { "my_alias", "o5", {}, MakeInputSwizzlerMask<'x', 'y', 'z'>(), { {}, OutputRegisterInfo::TEXCOORD0 } }); } { // Constant alias auto declaration = parse<StatementDeclaration>(".alias my_alias c5.xy as (1.0, -2.4)", declaration_parser, skipper); CheckDeclaration(declaration, { "my_alias", "c5", {}, MakeInputSwizzlerMask<'x', 'y'>(), { { 1.0, -2.4 } } }); } } BOOST_AUTO_TEST_CASE(label) { ParserContext context; LabelParser<std::string::iterator> label_parser(context); AssemblySkipper<std::string::iterator> skipper; { auto label = parse<StatementLabel>("my_label:", label_parser, skipper); BOOST_CHECK(label); BOOST_CHECK_EQUAL(*label, "my_label"); } }
// Copyright 2014 Tony Wasserka // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of the owner 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 "nihstro/parser_assembly.h" #include "nihstro/parser_assembly_private.h" #include <boost/optional/optional_io.hpp> #include <boost/spirit/include/qi.hpp> #define BOOST_TEST_MODULE Parser #include <boost/test/unit_test.hpp> // Implement some ostream<< operators for BOOST_CHECK* namespace std { template<typename T> std::ostream& operator << (std::ostream& os, const std::vector<T>& vec) { auto it = vec.begin(); os << "{"; if (!vec.empty()) os << " " << *it; while (it != vec.end() && ++it != vec.end()) { os << ", " << *it; } os << " }"; return os; } std::ostream& operator << (std::ostream& os, const nihstro::Expression& expr) { if (expr.signed_identifier.sign) os << *expr.signed_identifier.sign; os << expr.signed_identifier.identifier; if (expr.index) os << "[" << *expr.index << "]"; for (auto& mask : expr.swizzle_masks) os << "." << mask; return os; } std::ostream& operator << (std::ostream& os, const nihstro::IndexExpression& expr) { for (size_t i = 0; i < expr.GetCount(); ++i) { if (i != 0) os << ", "; if (expr.IsRawIndex(i)) { os << expr.GetRawIndex(i); } else if (expr.IsAddressRegisterIdentifier(i)) { os << expr.GetAddressRegisterIdentifier(i); } else { os << "?"; } } return os; } std::ostream& operator << (std::ostream& os, const nihstro::IntegerWithSign& num) { os << num.GetValue(); return os; } std::ostream& operator << (std::ostream& os, const nihstro::Instruction::FlowControlType::Op& op) { if (op == Instruction::FlowControlType::And) os << "&&"; else if (op == Instruction::FlowControlType::Or) os << "||"; else os << "??"; return os; } std::ostream& operator << (std::ostream& os, const nihstro::ConditionInput& inp) { if (inp.invert) os << "!"; os << inp.identifier; if (inp.swizzler_mask) os << "." << *inp.swizzler_mask; return os; } std::ostream& operator << (std::ostream& os, const nihstro::Condition& cond) { os << "{ " << cond.input1; if (cond.op != Instruction::FlowControlType::JustX) os << " " << cond.op << " " << cond.input2; os << " }"; return os; } } // namespace std // Utility comparison operators namespace nihstro { bool operator == (const IntegerWithSign& a, const IntegerWithSign& b) { return a.sign == b.sign && a.value == b.value; } bool operator == (const Expression& a, const Expression& b) { bool ret = true; ret &= a.signed_identifier.sign == b.signed_identifier.sign; ret &= a.signed_identifier.identifier == b.signed_identifier.identifier; ret &= a.index == b.index; ret &= a.swizzle_masks == b.swizzle_masks; return ret; } bool operator == (const ConditionInput& a, const ConditionInput& b) { return a.invert == b.invert && a.identifier == b.identifier && a.swizzler_mask == b.swizzler_mask; } bool operator == (const Condition& a, const Condition& b) { return a.input1 == b.input1 && a.input2 == b.input2 && a.op == b.op; } } // namespace nihstro // Utility function to parse the given input. Upon match, returns the parsed contents, and returns no value upon failure. template<typename Attr, typename Parser, typename Skipper> static boost::optional<Attr> parse(const std::string& input, const Parser& parser, const Skipper& skipper) { BOOST_TEST_MESSAGE(("Parsing \"" + input + "\"").c_str()); Attr attr; std::string inp(input); if (boost::spirit::qi::phrase_parse(inp.begin(), inp.end(), parser, skipper, attr)) return attr; else return {}; } // Utility function to check that the given vectors are equal. template<typename T> static void CheckVector(const std::vector<T>& vec, const std::vector<T>& exp) { // TODO: Could just check directly for equality, but need an ostream<< operator for that. BOOST_CHECK_EQUAL(vec, exp); } // Utility function to convert a compile-time character to the corresponding swizzle mask component template<char a> static InputSwizzlerMask::Component MakeSwizzlerMaskComponent() { static_assert(a == 'x' || a == 'y' || a == 'z' || a == 'w', "Invalid component"); if (a == 'x') return InputSwizzlerMask::x; else if (a == 'y') return InputSwizzlerMask::y; else if (a == 'z') return InputSwizzlerMask::z; else return InputSwizzlerMask::w; } // Utility function to convert a series of up to four characters to the corresponding swizzle mask template<char a> static InputSwizzlerMask MakeInputSwizzlerMask() { return { 1, { MakeSwizzlerMaskComponent<a>() } }; } template<char a, char b> static InputSwizzlerMask MakeInputSwizzlerMask() { return { 2, { MakeSwizzlerMaskComponent<a>(), MakeSwizzlerMaskComponent<b>() } }; } template<char a, char b, char c> static InputSwizzlerMask MakeInputSwizzlerMask() { return { 3, { MakeSwizzlerMaskComponent<a>(), MakeSwizzlerMaskComponent<b>(), MakeSwizzlerMaskComponent<c>() } }; } template<char a, char b, char c, char d> static InputSwizzlerMask MakeInputSwizzlerMask() { return { 4, { MakeSwizzlerMaskComponent<a>(), MakeSwizzlerMaskComponent<b>(), MakeSwizzlerMaskComponent<c>(), MakeSwizzlerMaskComponent<d>() } }; } // Utility function to check that parsing of the first declaration statement was successfull and that the result matches the second declaration statements. static void CheckDeclaration(const boost::optional<StatementDeclaration>& declaration, const StatementDeclaration& exp) { if (!declaration) { BOOST_CHECK(false); } else { BOOST_CHECK_EQUAL(declaration->alias_name, exp.alias_name); BOOST_CHECK_EQUAL(declaration->identifier_start, exp.identifier_start); BOOST_CHECK_EQUAL(declaration->identifier_end, exp.identifier_end); BOOST_CHECK_EQUAL(declaration->swizzle_mask, exp.swizzle_mask); CheckVector(declaration->extra.constant_value, exp.extra.constant_value); BOOST_CHECK_EQUAL(declaration->extra.output_semantic, exp.extra.output_semantic); } } BOOST_AUTO_TEST_CASE(declaration) { ParserContext context; DeclarationParser<std::string::iterator> declaration_parser(context); AssemblySkipper<std::string::iterator> skipper; { // Plain alias auto declaration = parse<StatementDeclaration>(".alias my_alias r5.xy", declaration_parser, skipper); CheckDeclaration(declaration, { "my_alias", "r5", {}, MakeInputSwizzlerMask<'x', 'y'>() }); } { // Array alias auto declaration = parse<StatementDeclaration>(".alias my_alias r5-r10", declaration_parser, skipper); CheckDeclaration(declaration, { "my_alias", "r5", std::string("r10") }); } { // Output alias auto declaration = parse<StatementDeclaration>(".alias my_alias o5.xyz as texcoord0", declaration_parser, skipper); CheckDeclaration(declaration, { "my_alias", "o5", {}, MakeInputSwizzlerMask<'x', 'y', 'z'>(), { {}, OutputRegisterInfo::TEXCOORD0 } }); } { // Output alias without output semantic BOOST_CHECK_THROW(parse<StatementDeclaration>(".alias my_alias o5.xyz", declaration_parser, skipper), std::runtime_error); } { // Constant alias auto declaration = parse<StatementDeclaration>(".alias my_alias c5.xy as (1.0, -2.4)", declaration_parser, skipper); CheckDeclaration(declaration, { "my_alias", "c5", {}, MakeInputSwizzlerMask<'x', 'y'>(), { { 1.0, -2.4 } } }); } } BOOST_AUTO_TEST_CASE(label) { ParserContext context; LabelParser<std::string::iterator> label_parser(context); AssemblySkipper<std::string::iterator> skipper; { auto label = parse<StatementLabel>("my_label:", label_parser, skipper); BOOST_CHECK(label); BOOST_CHECK_EQUAL(*label, "my_label"); } } static void CheckParsedArithmeticInstruction(const boost::optional<FloatOpInstruction>& result, const FloatOpInstruction& exp) { if (!result) { BOOST_CHECK(false); } else { BOOST_CHECK_EQUAL(result->opcode, exp.opcode); CheckVector(result->expressions, exp.expressions); } } BOOST_AUTO_TEST_CASE(arithmetic) { ParserContext context; FloatOpParser<std::string::iterator> arithmetic_parser(context); AssemblySkipper<std::string::iterator> skipper; { // one-argument instruction auto result = parse<FloatOpInstruction>("mova r2.xy", arithmetic_parser, skipper); Expression r2_xy = { { {}, "r2" }, {}, { MakeInputSwizzlerMask<'x', 'y'>() } }; CheckParsedArithmeticInstruction(result, { nihstro::OpCode::Id::MOVA, { r2_xy } }); } { // two-argument instruction auto result = parse<FloatOpInstruction>("mov o0.wz, r2.xy", arithmetic_parser, skipper); Expression o0_wz = { { {}, "o0" }, {}, { MakeInputSwizzlerMask<'w', 'z'>() } }; Expression r2_xy = { { {}, "r2" }, {}, { MakeInputSwizzlerMask<'x', 'y'>() } }; CheckParsedArithmeticInstruction(result, { nihstro::OpCode::Id::MOV, { o0_wz, r2_xy } }); } { // two-argument instruction with trivial register index auto result = parse<FloatOpInstruction>("mov o0.wz, r2[5].xy", arithmetic_parser, skipper); IndexExpression index_expr; index_expr.emplace_back(IntegerWithSign{ +1, 5 }); Expression o0_wz = { { {}, "o0" }, {}, { MakeInputSwizzlerMask<'w', 'z'>() } }; Expression r2_xy = { { {}, "r2" }, index_expr, { MakeInputSwizzlerMask<'x', 'y'>() } }; CheckParsedArithmeticInstruction(result, { nihstro::OpCode::Id::MOV, { o0_wz, r2_xy } }); } { // two-argument instruction with nontrivial register index auto result = parse<FloatOpInstruction>("mov o0.wz, r2[5+a1-4].xy", arithmetic_parser, skipper); IndexExpression index_expr; index_expr.emplace_back(IntegerWithSign{ +1, 5 }); index_expr.emplace_back("a1"); index_expr.emplace_back(IntegerWithSign{ -1, 4 }); Expression o0_wz = { { {}, "o0" }, {}, { MakeInputSwizzlerMask<'w', 'z'>() } }; Expression r2_xy = { { {}, "r2" }, index_expr, { MakeInputSwizzlerMask<'x', 'y'>() } }; CheckParsedArithmeticInstruction(result, { nihstro::OpCode::Id::MOV, { o0_wz, r2_xy } }); } { // three-argument instruction auto result = parse<FloatOpInstruction>("add o0.xy, r2.xy, r3.xy", arithmetic_parser, skipper); Expression o0_xy = { { {}, "o0" }, {}, { MakeInputSwizzlerMask<'x', 'y'>() } }; Expression r2_xy = { { {}, "r2" }, {}, { MakeInputSwizzlerMask<'x', 'y'>() } }; Expression r3_xy = { { {}, "r3" }, {}, { MakeInputSwizzlerMask<'x', 'y'>() } }; CheckParsedArithmeticInstruction(result, { nihstro::OpCode::Id::ADD, { o0_xy, r2_xy, r3_xy } }); } { // four-argument instruction auto result = parse<FloatOpInstruction>("mad o0.xy, r2.xy, r3.xy, v4.xy", arithmetic_parser, skipper); Expression o0_xy = { { {}, "o0" }, {}, { MakeInputSwizzlerMask<'x', 'y'>() } }; Expression r2_xy = { { {}, "r2" }, {}, { MakeInputSwizzlerMask<'x', 'y'>() } }; Expression r3_xy = { { {}, "r3" }, {}, { MakeInputSwizzlerMask<'x', 'y'>() } }; Expression v4_xy = { { {}, "v4" }, {}, { MakeInputSwizzlerMask<'x', 'y'>() } }; CheckParsedArithmeticInstruction(result, { nihstro::OpCode::Id::MAD, { o0_xy, r2_xy, r3_xy, v4_xy } }); } } static void CheckParsedFlowControlInstruction(const boost::optional<FlowControlInstruction>& result, const FlowControlInstruction& exp) { if (!result) { BOOST_CHECK(false); } else { BOOST_CHECK_EQUAL(result->opcode, exp.opcode); BOOST_CHECK_EQUAL(result->target_label, exp.target_label); BOOST_CHECK_EQUAL(result->return_label, exp.return_label); BOOST_CHECK_EQUAL(result->condition, exp.condition); } } BOOST_AUTO_TEST_CASE(flowcontrol) { ParserContext context; FlowControlParser<std::string::iterator> parser(context); AssemblySkipper<std::string::iterator> skipper; { // If-conditionals with two arguments auto result = parse<FlowControlInstruction>("if cc.x && !cc.y", parser, skipper); Condition cond = { { false, "cc", MakeInputSwizzlerMask<'x'>() }, Instruction::FlowControlType::And, { true, "cc", MakeInputSwizzlerMask<'y'>() } }; CheckParsedFlowControlInstruction(result, { nihstro::OpCode::Id::GEN_IF, "__dummy", {}, cond } ); } { // If-conditionals with one argument with one component auto result = parse<FlowControlInstruction>("if cc.x", parser, skipper); Condition cond = { { false, "cc", MakeInputSwizzlerMask<'x'>() }, Instruction::FlowControlType::JustX }; CheckParsedFlowControlInstruction(result, { nihstro::OpCode::Id::GEN_IF, "__dummy", {}, cond } ); } { // If-conditionals with one argument with two components auto result = parse<FlowControlInstruction>("if !cc.xy", parser, skipper); Condition cond = { { true, "cc", MakeInputSwizzlerMask<'x', 'y'>() }, Instruction::FlowControlType::JustX }; CheckParsedFlowControlInstruction(result, { nihstro::OpCode::Id::GEN_IF, "__dummy", {}, cond }); } { // Loop instruction auto result = parse<FlowControlInstruction>("loop i3.y", parser, skipper); Condition cond = { { false, "i3", MakeInputSwizzlerMask<'y'>() }, Instruction::FlowControlType::JustX }; CheckParsedFlowControlInstruction(result, { OpCode::Id::LOOP, "__dummy", {}, cond }); } } static void CheckParsedCompareInstruction(const boost::optional<CompareInstruction>& result, const CompareInstruction& exp) { if (!result) { BOOST_CHECK(false); } else { BOOST_CHECK_EQUAL(result->opcode, exp.opcode); CheckVector(result->arguments, exp.arguments); CheckVector(result->ops, exp.ops); } } BOOST_AUTO_TEST_CASE(compare) { ParserContext context; CompareParser<std::string::iterator> parser(context); AssemblySkipper<std::string::iterator> skipper; { // Two separate comparisons auto result = parse<CompareInstruction>("cmp r5.xy, r2.zx, ==, <=", parser, skipper); Expression r5_xy = { { {}, "r5" }, {}, { MakeInputSwizzlerMask<'x', 'y'>() } }; Expression r2_zx = { { {}, "r2" }, {}, { MakeInputSwizzlerMask<'z', 'x'>() } }; CheckParsedCompareInstruction(result, { OpCode::Id::CMP, { r5_xy, r2_zx }, { Instruction::Common::CompareOpType::Equal, Instruction::Common::CompareOpType::LessEqual } }); } }
Add lots of new tests
Assembler: Add lots of new tests
C++
bsd-3-clause
neobrain/nihstro,Megazig/nihstro,machinamentum/nihstro,machinamentum/nihstro,Cruel/nihstro
77709fee8ccf4e6e24572c38d10b6fe880b68d0d
test/extensions/transport_sockets/alts/tsi_handshaker_test.cc
test/extensions/transport_sockets/alts/tsi_handshaker_test.cc
#include "source/extensions/transport_sockets/alts/tsi_handshaker.h" #include "test/mocks/event/mocks.h" #include "gmock/gmock.h" #include "gtest/gtest.h" #include "src/core/tsi/fake_transport_security.h" namespace Envoy { namespace Extensions { namespace TransportSockets { namespace Alts { namespace { using testing::_; using testing::InSequence; using testing::Invoke; using testing::NiceMock; using testing::SaveArg; class MockTsiHandshakerCallbacks : public TsiHandshakerCallbacks { public: void onNextDone(NextResultPtr&& result) override { onNextDone_(result.get()); } MOCK_METHOD(void, onNextDone_, (NextResult*)); void expectDone(tsi_result status, Buffer::Instance& to_send, CHandshakerResultPtr& result) { EXPECT_CALL(*this, onNextDone_(_)) .WillOnce(Invoke([&, status](TsiHandshakerCallbacks::NextResult* next_result) { EXPECT_EQ(status, next_result->status_); to_send.add(*next_result->to_send_); result.swap(next_result->result_); })); } }; class TsiHandshakerTest : public testing::Test { public: TsiHandshakerTest() : server_handshaker_({tsi_create_fake_handshaker(0)}, dispatcher_), client_handshaker_({tsi_create_fake_handshaker(1)}, dispatcher_) { server_handshaker_.setHandshakerCallbacks(server_callbacks_); client_handshaker_.setHandshakerCallbacks(client_callbacks_); } protected: NiceMock<Event::MockDispatcher> dispatcher_; MockTsiHandshakerCallbacks server_callbacks_; MockTsiHandshakerCallbacks client_callbacks_; TsiHandshaker server_handshaker_; TsiHandshaker client_handshaker_; }; TEST_F(TsiHandshakerTest, DoHandshake) { InSequence s; Buffer::OwnedImpl server_sent; Buffer::OwnedImpl client_sent; CHandshakerResultPtr client_result; CHandshakerResultPtr server_result; client_callbacks_.expectDone(TSI_OK, client_sent, client_result); client_handshaker_.next(server_sent); // Initially server_sent is empty. EXPECT_EQ(nullptr, client_result); EXPECT_EQ("CLIENT_INIT", client_sent.toString().substr(4)); server_callbacks_.expectDone(TSI_OK, server_sent, server_result); server_handshaker_.next(client_sent); EXPECT_EQ(nullptr, client_result); EXPECT_EQ("SERVER_INIT", server_sent.toString().substr(4)); client_callbacks_.expectDone(TSI_OK, client_sent, client_result); client_handshaker_.next(server_sent); EXPECT_EQ(nullptr, client_result); EXPECT_EQ("CLIENT_FINISHED", client_sent.toString().substr(4)); server_callbacks_.expectDone(TSI_OK, server_sent, server_result); server_handshaker_.next(client_sent); EXPECT_NE(nullptr, server_result); EXPECT_EQ("SERVER_FINISHED", server_sent.toString().substr(4)); client_callbacks_.expectDone(TSI_OK, client_sent, client_result); client_handshaker_.next(server_sent); EXPECT_NE(nullptr, client_result); EXPECT_EQ("", client_sent.toString()); tsi_peer client_peer; EXPECT_EQ(TSI_OK, tsi_handshaker_result_extract_peer(client_result.get(), &client_peer)); EXPECT_EQ(2, client_peer.property_count); EXPECT_STREQ("certificate_type", client_peer.properties[0].name); absl::string_view client_certificate_type{client_peer.properties[0].value.data, client_peer.properties[0].value.length}; EXPECT_EQ("FAKE", client_certificate_type); EXPECT_STREQ("security_level", client_peer.properties[1].name); absl::string_view client_security_level{client_peer.properties[1].value.data, client_peer.properties[1].value.length}; EXPECT_EQ("TSI_SECURITY_NONE", client_security_level); tsi_peer server_peer; EXPECT_EQ(TSI_OK, tsi_handshaker_result_extract_peer(server_result.get(), &server_peer)); EXPECT_EQ(2, server_peer.property_count); EXPECT_STREQ("certificate_type", server_peer.properties[0].name); absl::string_view server_certificate_type{server_peer.properties[0].value.data, server_peer.properties[0].value.length}; EXPECT_EQ("FAKE", server_certificate_type); EXPECT_STREQ("security_level", server_peer.properties[1].name); absl::string_view server_security_level{server_peer.properties[1].value.data, server_peer.properties[1].value.length}; EXPECT_EQ("TSI_SECURITY_NONE", server_security_level); tsi_peer_destruct(&client_peer); tsi_peer_destruct(&server_peer); } TEST_F(TsiHandshakerTest, IncompleteData) { InSequence s; Buffer::OwnedImpl server_sent; Buffer::OwnedImpl client_sent; CHandshakerResultPtr client_result; CHandshakerResultPtr server_result; client_callbacks_.expectDone(TSI_OK, client_sent, client_result); client_handshaker_.next(server_sent); // Initially server_sent is empty. EXPECT_EQ(nullptr, client_result); EXPECT_EQ("CLIENT_INIT", client_sent.toString().substr(4)); client_sent.drain(3); // make data incomplete server_callbacks_.expectDone(TSI_INCOMPLETE_DATA, server_sent, server_result); server_handshaker_.next(client_sent); EXPECT_EQ(nullptr, client_result); EXPECT_EQ("", server_sent.toString()); } TEST_F(TsiHandshakerTest, DeferredDelete) { InSequence s; TsiHandshakerPtr handshaker{new TsiHandshaker({tsi_create_fake_handshaker(0)}, dispatcher_)}; handshaker->deferredDelete(); // The handshaker is now in dispatcher_ to delete queue. EXPECT_EQ(dispatcher_.to_delete_.back().get(), handshaker.get()); handshaker.release(); } TEST_F(TsiHandshakerTest, DeleteOnDone) { InSequence s; TsiHandshakerPtr handshaker(new TsiHandshaker({tsi_create_fake_handshaker(1)}, dispatcher_)); handshaker->setHandshakerCallbacks(client_callbacks_); Buffer::OwnedImpl empty; std::function<void()> done; EXPECT_CALL(dispatcher_, post(_)).WillOnce(SaveArg<0>(&done)); handshaker->next(empty); handshaker->deferredDelete(); // Make sure the handshaker is not in dispatcher_ queue, since the next call is not done. EXPECT_NE(dispatcher_.to_delete_.back().get(), handshaker.get()); // After deferredDelete, the callback should be never invoked, in real use it might be already // a dangling pointer. EXPECT_CALL(client_callbacks_, onNextDone_(_)).Times(0); // Simulate the next call is completed. done(); // The handshaker is now in dispatcher_ to delete queue. EXPECT_EQ(dispatcher_.to_delete_.back().get(), handshaker.get()); handshaker.release(); } } // namespace } // namespace Alts } // namespace TransportSockets } // namespace Extensions } // namespace Envoy
#include "source/extensions/transport_sockets/alts/tsi_handshaker.h" #include "test/mocks/event/mocks.h" #include "gmock/gmock.h" #include "gtest/gtest.h" #include "src/core/tsi/fake_transport_security.h" namespace Envoy { namespace Extensions { namespace TransportSockets { namespace Alts { namespace { using testing::_; using testing::InSequence; using testing::Invoke; using testing::NiceMock; using testing::SaveArg; class MockTsiHandshakerCallbacks : public TsiHandshakerCallbacks { public: void onNextDone(NextResultPtr&& result) override { onNextDone_(result.get()); } MOCK_METHOD(void, onNextDone_, (NextResult*)); void expectDone(tsi_result status, Buffer::Instance& to_send, CHandshakerResultPtr& result) { EXPECT_CALL(*this, onNextDone_(_)) .WillOnce(Invoke([&, status](TsiHandshakerCallbacks::NextResult* next_result) { EXPECT_EQ(status, next_result->status_); to_send.add(*next_result->to_send_); result.swap(next_result->result_); })); } }; class TsiHandshakerTest : public testing::Test { public: TsiHandshakerTest() : server_handshaker_({tsi_create_fake_handshaker(0)}, dispatcher_), client_handshaker_({tsi_create_fake_handshaker(1)}, dispatcher_) { server_handshaker_.setHandshakerCallbacks(server_callbacks_); client_handshaker_.setHandshakerCallbacks(client_callbacks_); } protected: NiceMock<Event::MockDispatcher> dispatcher_; MockTsiHandshakerCallbacks server_callbacks_; MockTsiHandshakerCallbacks client_callbacks_; TsiHandshaker server_handshaker_; TsiHandshaker client_handshaker_; }; TEST_F(TsiHandshakerTest, DoHandshake) { InSequence s; Buffer::OwnedImpl server_sent; Buffer::OwnedImpl client_sent; CHandshakerResultPtr client_result; CHandshakerResultPtr server_result; client_callbacks_.expectDone(TSI_OK, client_sent, client_result); client_handshaker_.next(server_sent); // Initially server_sent is empty. EXPECT_EQ(nullptr, client_result); EXPECT_EQ("CLIENT_INIT", client_sent.toString().substr(4)); server_callbacks_.expectDone(TSI_OK, server_sent, server_result); server_handshaker_.next(client_sent); EXPECT_EQ(nullptr, client_result); EXPECT_EQ("SERVER_INIT", server_sent.toString().substr(4)); client_callbacks_.expectDone(TSI_OK, client_sent, client_result); client_handshaker_.next(server_sent); EXPECT_EQ(nullptr, client_result); EXPECT_EQ("CLIENT_FINISHED", client_sent.toString().substr(4)); server_callbacks_.expectDone(TSI_OK, server_sent, server_result); server_handshaker_.next(client_sent); EXPECT_NE(nullptr, server_result); EXPECT_EQ("SERVER_FINISHED", server_sent.toString().substr(4)); client_callbacks_.expectDone(TSI_OK, client_sent, client_result); client_handshaker_.next(server_sent); EXPECT_NE(nullptr, client_result); EXPECT_EQ("", client_sent.toString()); tsi_peer client_peer; EXPECT_EQ(TSI_OK, tsi_handshaker_result_extract_peer(client_result.get(), &client_peer)); EXPECT_EQ(2, client_peer.property_count); EXPECT_STREQ("certificate_type", client_peer.properties[0].name); absl::string_view client_certificate_type{client_peer.properties[0].value.data, client_peer.properties[0].value.length}; EXPECT_EQ("FAKE", client_certificate_type); EXPECT_STREQ("security_level", client_peer.properties[1].name); absl::string_view client_security_level{client_peer.properties[1].value.data, client_peer.properties[1].value.length}; EXPECT_EQ("TSI_SECURITY_NONE", client_security_level); tsi_peer server_peer; EXPECT_EQ(TSI_OK, tsi_handshaker_result_extract_peer(server_result.get(), &server_peer)); EXPECT_EQ(2, server_peer.property_count); EXPECT_STREQ("certificate_type", server_peer.properties[0].name); absl::string_view server_certificate_type{server_peer.properties[0].value.data, server_peer.properties[0].value.length}; EXPECT_EQ("FAKE", server_certificate_type); EXPECT_STREQ("security_level", server_peer.properties[1].name); absl::string_view server_security_level{server_peer.properties[1].value.data, server_peer.properties[1].value.length}; EXPECT_EQ("TSI_SECURITY_NONE", server_security_level); tsi_peer_destruct(&client_peer); tsi_peer_destruct(&server_peer); } TEST_F(TsiHandshakerTest, IncompleteData) { InSequence s; Buffer::OwnedImpl server_sent; Buffer::OwnedImpl client_sent; CHandshakerResultPtr client_result; CHandshakerResultPtr server_result; client_callbacks_.expectDone(TSI_OK, client_sent, client_result); client_handshaker_.next(server_sent); // Initially server_sent is empty. EXPECT_EQ(nullptr, client_result); EXPECT_EQ("CLIENT_INIT", client_sent.toString().substr(4)); client_sent.drain(3); // make data incomplete server_callbacks_.expectDone(TSI_INCOMPLETE_DATA, server_sent, server_result); server_handshaker_.next(client_sent); EXPECT_EQ(nullptr, client_result); EXPECT_EQ("", server_sent.toString()); } TEST_F(TsiHandshakerTest, DeferredDelete) { InSequence s; TsiHandshakerPtr handshaker{new TsiHandshaker({tsi_create_fake_handshaker(0)}, dispatcher_)}; handshaker->deferredDelete(); // The handshaker is now in dispatcher_ to delete queue. EXPECT_EQ(dispatcher_.to_delete_.back().get(), handshaker.get()); handshaker.release(); } TEST_F(TsiHandshakerTest, DeleteOnDone) { InSequence s; TsiHandshakerPtr handshaker(new TsiHandshaker({tsi_create_fake_handshaker(1)}, dispatcher_)); handshaker->setHandshakerCallbacks(client_callbacks_); Buffer::OwnedImpl empty; std::function<void()> done; EXPECT_CALL(dispatcher_, post(_)).WillOnce(SaveArg<0>(&done)); handshaker->next(empty); handshaker->deferredDelete(); // Make sure the handshaker is not in dispatcher_ queue, since the next call is not done. EXPECT_TRUE(dispatcher_.to_delete_.empty()); // After deferredDelete, the callback should be never invoked, in real use it might be already // a dangling pointer. EXPECT_CALL(client_callbacks_, onNextDone_(_)).Times(0); // Simulate the next call is completed. done(); // The handshaker is now in dispatcher_ to delete queue. EXPECT_EQ(dispatcher_.to_delete_.back().get(), handshaker.get()); handshaker.release(); } } // namespace } // namespace Alts } // namespace TransportSockets } // namespace Extensions } // namespace Envoy
Fix undefined behavior (#23849)
Fix undefined behavior (#23849) std::list's back() is UB when called on an empty list. Signed-off-by: yurykats <[email protected]>
C++
apache-2.0
envoyproxy/envoy,envoyproxy/envoy,envoyproxy/envoy,envoyproxy/envoy,envoyproxy/envoy,envoyproxy/envoy,envoyproxy/envoy,envoyproxy/envoy,envoyproxy/envoy,envoyproxy/envoy,envoyproxy/envoy,envoyproxy/envoy
7aead6b59d03e9894aa736e4dbc321bb75a22796
core/src/wallet/tezos/explorers/api/TezosLikeTransactionParser.cpp
core/src/wallet/tezos/explorers/api/TezosLikeTransactionParser.cpp
/* * * TezosLikeTransactionParser * * Created by El Khalil Bellakrid on 27/04/2019. * * The MIT License (MIT) * * Copyright (c) 2019 Ledger * * 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 "TezosLikeTransactionParser.h" #include <wallet/currencies.hpp> #include <api/TezosOperationTag.hpp> #include <api/BigInt.hpp> #define PROXY_PARSE(method, ...) \ auto& currentObject = _hierarchy.top(); \ if (currentObject == "block") { \ return _blockParser.method(__VA_ARGS__); \ } else \ namespace ledger { namespace core { bool TezosLikeTransactionParser::Key(const rapidjson::Reader::Ch *str, rapidjson::SizeType length, bool copy) { PROXY_PARSE(Key, str, length, copy) { return true; } } bool TezosLikeTransactionParser::StartObject() { _hierarchy.push(_lastKey); return true; } bool TezosLikeTransactionParser::EndObject(rapidjson::SizeType memberCount) { auto &currentObject = _hierarchy.top(); _hierarchy.pop(); return true; } bool TezosLikeTransactionParser::StartArray() { if (_arrayDepth == 0) { _hierarchy.push(_lastKey); } _arrayDepth += 1; return true; } bool TezosLikeTransactionParser::EndArray(rapidjson::SizeType elementCount) { _arrayDepth -= 1; if (_arrayDepth == 0) { _hierarchy.pop(); } return true; } bool TezosLikeTransactionParser::Null() { PROXY_PARSE(Null) { return true; } } bool TezosLikeTransactionParser::Bool(bool b) { PROXY_PARSE(Bool, b) { if ((_lastKey == "spendable" || _lastKey == "is_spendable") && _transaction->originatedAccount.hasValue()) { _transaction->originatedAccount.getValue().spendable = b; } else if ((_lastKey == "delegatable" || _lastKey == "is_delegatable") && _transaction->originatedAccount.hasValue()) { _transaction->originatedAccount.getValue().delegatable = b; } else if (_lastKey == "failed") { // For Tzscan _transaction->status = static_cast<uint64_t>(!b); } else if (_lastKey == "is_success") { // For Tzstats _transaction->status = static_cast<uint64_t>(b); } return true; } } bool TezosLikeTransactionParser::Int(int i) { return Uint64(i); } bool TezosLikeTransactionParser::Uint(unsigned i) { return Uint64(i); } bool TezosLikeTransactionParser::Int64(int64_t i) { return Uint64(i); } bool TezosLikeTransactionParser::Uint64(uint64_t i) { PROXY_PARSE(Uint64, i) { return true; } } bool TezosLikeTransactionParser::Double(double d) { PROXY_PARSE(Double, d) { return true; } } bool TezosLikeTransactionParser::RawNumber(const rapidjson::Reader::Ch *str, rapidjson::SizeType length, bool copy) { PROXY_PARSE(RawNumber, str, length, copy) { std::string number(str, length); auto toValue = [] (const std::string &v, bool forceConversion) -> BigInt { if (v.find('.') != std::string::npos || forceConversion) { return BigInt(api::BigInt::fromDecimalString(v, 6, ".")->toString(10)); } return BigInt::fromString(v); }; if ((_lastKey == "op_level" || _lastKey == "height") && _transaction->block.hasValue()) { _transaction->block.getValue().height = BigInt::fromString(number).toUint64(); } else if (_lastKey == "amount" || _lastKey == "volume") { _transaction->value = toValue(number, _lastKey == "volume"); } else if (_lastKey == "fee") { _transaction->fees = _transaction->fees + toValue(number, false); } else if (_lastKey == "gas_limit") { _transaction->gas_limit = toValue(number, false); } else if (_lastKey == "storage_limit") { _transaction->storage_limit = toValue(number, false); } else if (_lastKey == "burned") { _transaction->fees = _transaction->fees + toValue(number, true); } return true; } } bool TezosLikeTransactionParser::String(const rapidjson::Reader::Ch *str, rapidjson::SizeType length, bool copy) { PROXY_PARSE(String, str, length, copy) { std::string value(str, length); auto toValue = [] (const std::string &v, bool forceConversion) -> BigInt { if (v.find('.') != std::string::npos || forceConversion) { return BigInt(api::BigInt::fromDecimalString(v, 6, ".")->toString(10)); } return BigInt::fromString(v); }; if (_lastKey == "hash") { _transaction->hash = value; } else if (_lastKey == "block_hash" || _lastKey == "block") { TezosLikeBlockchainExplorer::Block block; block.hash = value; block.currencyName = currencies::TEZOS.name; _transaction->block = block; } else if (_lastKey == "timestamp" || _lastKey == "time") { auto pos = value.find('+'); if (pos != std::string::npos && pos > 0) { value = value.substr(0, pos); } auto posZ = value.find('Z'); if (posZ == std::string::npos) { value = value + "Z"; } auto date = DateUtils::fromJSON(value); _transaction->receivedAt = date; if (_transaction->block.hasValue()) { _transaction->block.getValue().time = date; } } else if (_lastKey == "sender" || (currentObject == "src" && _lastKey == "tz")) { _transaction->sender = value; } else if (_lastKey == "receiver" || _lastKey == "delegate" || ((currentObject == "destination" || currentObject == "delegate") && _lastKey == "tz")) { _transaction->receiver = value; if (_lastKey == "receiver" && _transaction->type == api::TezosOperationTag::OPERATION_TAG_ORIGINATION) { _transaction->originatedAccount.getValue().address = value; } } else if (currentObject == "tz1" && _lastKey == "tz") { _transaction->originatedAccount = TezosLikeBlockchainExplorerOriginatedAccount(value); } else if (_lastKey == "gas_limit") { _transaction->gas_limit = BigInt::fromString(value); } else if (_lastKey == "storage_limit") { _transaction->storage_limit = BigInt::fromString(value); } else if ((_lastKey == "kind" || _lastKey == "type") && _transaction->type == api::TezosOperationTag::OPERATION_TAG_NONE) { static std::unordered_map<std::string, api::TezosOperationTag> opTags { std::make_pair("reveal", api::TezosOperationTag::OPERATION_TAG_REVEAL), std::make_pair("transaction", api::TezosOperationTag::OPERATION_TAG_TRANSACTION), std::make_pair("origination", api::TezosOperationTag::OPERATION_TAG_ORIGINATION), std::make_pair("delegation", api::TezosOperationTag::OPERATION_TAG_DELEGATION), }; if (opTags.count(value)) { _transaction->type = opTags[value]; } else { _transaction->type = api::TezosOperationTag::OPERATION_TAG_NONE; } if (_lastKey == "type" && _transaction->type == api::TezosOperationTag::OPERATION_TAG_ORIGINATION) { _transaction->originatedAccount = TezosLikeBlockchainExplorerOriginatedAccount(); } } else if (_lastKey == "public_key" || (_lastKey == "data" && _transaction->type == api::TezosOperationTag::OPERATION_TAG_REVEAL)) { _transaction->publicKey = value; } else if (_lastKey == "burn_tez") { _transaction->fees = _transaction->fees + toValue(value, false); } return true; } } TezosLikeTransactionParser::TezosLikeTransactionParser(std::string &lastKey) : _lastKey(lastKey), _blockParser(lastKey) { _arrayDepth = 0; } void TezosLikeTransactionParser::init(TezosLikeBlockchainExplorerTransaction *transaction) { _transaction = transaction; } } }
/* * * TezosLikeTransactionParser * * Created by El Khalil Bellakrid on 27/04/2019. * * The MIT License (MIT) * * Copyright (c) 2019 Ledger * * 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 "TezosLikeTransactionParser.h" #include <wallet/currencies.hpp> #include <api/TezosOperationTag.hpp> #include <api/BigInt.hpp> #define PROXY_PARSE(method, ...) \ auto& currentObject = _hierarchy.top(); \ if (currentObject == "block") { \ return _blockParser.method(__VA_ARGS__); \ } else \ namespace ledger { namespace core { bool TezosLikeTransactionParser::Key(const rapidjson::Reader::Ch *str, rapidjson::SizeType length, bool copy) { PROXY_PARSE(Key, str, length, copy) { return true; } } bool TezosLikeTransactionParser::StartObject() { _hierarchy.push(_lastKey); return true; } bool TezosLikeTransactionParser::EndObject(rapidjson::SizeType memberCount) { auto &currentObject = _hierarchy.top(); _hierarchy.pop(); return true; } bool TezosLikeTransactionParser::StartArray() { if (_arrayDepth == 0) { _hierarchy.push(_lastKey); } _arrayDepth += 1; return true; } bool TezosLikeTransactionParser::EndArray(rapidjson::SizeType elementCount) { _arrayDepth -= 1; if (_arrayDepth == 0) { _hierarchy.pop(); } return true; } bool TezosLikeTransactionParser::Null() { PROXY_PARSE(Null) { return true; } } bool TezosLikeTransactionParser::Bool(bool b) { PROXY_PARSE(Bool, b) { if ((_lastKey == "spendable" || _lastKey == "is_spendable") && _transaction->originatedAccount.hasValue()) { _transaction->originatedAccount.getValue().spendable = b; } else if ((_lastKey == "delegatable" || _lastKey == "is_delegatable") && _transaction->originatedAccount.hasValue()) { _transaction->originatedAccount.getValue().delegatable = b; } else if (_lastKey == "failed") { // For Tzscan _transaction->status = static_cast<uint64_t>(!b); } else if (_lastKey == "is_success") { // For Tzstats _transaction->status = static_cast<uint64_t>(b); } return true; } } bool TezosLikeTransactionParser::Int(int i) { return Uint64(i); } bool TezosLikeTransactionParser::Uint(unsigned i) { return Uint64(i); } bool TezosLikeTransactionParser::Int64(int64_t i) { return Uint64(i); } bool TezosLikeTransactionParser::Uint64(uint64_t i) { PROXY_PARSE(Uint64, i) { return true; } } bool TezosLikeTransactionParser::Double(double d) { PROXY_PARSE(Double, d) { return true; } } bool TezosLikeTransactionParser::RawNumber(const rapidjson::Reader::Ch *str, rapidjson::SizeType length, bool copy) { PROXY_PARSE(RawNumber, str, length, copy) { std::string number(str, length); auto toValue = [] (const std::string &v, bool forceConversion) -> BigInt { if (v.find('.') != std::string::npos || forceConversion) { return BigInt(api::BigInt::fromDecimalString(v, 6, ".")->toString(10)); } return BigInt::fromString(v); }; if ((_lastKey == "op_level" || _lastKey == "height") && _transaction->block.hasValue()) { _transaction->block.getValue().height = BigInt::fromString(number).toUint64(); } else if (_lastKey == "amount" || _lastKey == "volume") { _transaction->value = toValue(number, _lastKey == "volume"); } else if (_lastKey == "fee") { _transaction->fees = _transaction->fees + toValue(number, false); } else if (_lastKey == "gas_limit") { _transaction->gas_limit = toValue(number, false); } else if (_lastKey == "storage_limit") { _transaction->storage_limit = toValue(number, false); } else if (_lastKey == "burned") { _transaction->fees = _transaction->fees + toValue(number, true); } else if (_lastKey == "confirmations") { _transaction->confirmations = toValue(number, false).toInt64(); } return true; } } bool TezosLikeTransactionParser::String(const rapidjson::Reader::Ch *str, rapidjson::SizeType length, bool copy) { PROXY_PARSE(String, str, length, copy) { std::string value(str, length); auto toValue = [] (const std::string &v, bool forceConversion) -> BigInt { if (v.find('.') != std::string::npos || forceConversion) { return BigInt(api::BigInt::fromDecimalString(v, 6, ".")->toString(10)); } return BigInt::fromString(v); }; if (_lastKey == "hash") { _transaction->hash = value; } else if (_lastKey == "block_hash" || _lastKey == "block") { TezosLikeBlockchainExplorer::Block block; block.hash = value; block.currencyName = currencies::TEZOS.name; _transaction->block = block; } else if (_lastKey == "timestamp" || _lastKey == "time") { auto pos = value.find('+'); if (pos != std::string::npos && pos > 0) { value = value.substr(0, pos); } auto posZ = value.find('Z'); if (posZ == std::string::npos) { value = value + "Z"; } auto date = DateUtils::fromJSON(value); _transaction->receivedAt = date; if (_transaction->block.hasValue()) { _transaction->block.getValue().time = date; } } else if (_lastKey == "sender" || (currentObject == "src" && _lastKey == "tz")) { _transaction->sender = value; } else if (_lastKey == "receiver" || _lastKey == "delegate" || ((currentObject == "destination" || currentObject == "delegate") && _lastKey == "tz")) { _transaction->receiver = value; if (_lastKey == "receiver" && _transaction->type == api::TezosOperationTag::OPERATION_TAG_ORIGINATION) { _transaction->originatedAccount.getValue().address = value; } } else if (currentObject == "tz1" && _lastKey == "tz") { _transaction->originatedAccount = TezosLikeBlockchainExplorerOriginatedAccount(value); } else if (_lastKey == "gas_limit") { _transaction->gas_limit = BigInt::fromString(value); } else if (_lastKey == "storage_limit") { _transaction->storage_limit = BigInt::fromString(value); } else if ((_lastKey == "kind" || _lastKey == "type") && _transaction->type == api::TezosOperationTag::OPERATION_TAG_NONE) { static std::unordered_map<std::string, api::TezosOperationTag> opTags { std::make_pair("reveal", api::TezosOperationTag::OPERATION_TAG_REVEAL), std::make_pair("transaction", api::TezosOperationTag::OPERATION_TAG_TRANSACTION), std::make_pair("origination", api::TezosOperationTag::OPERATION_TAG_ORIGINATION), std::make_pair("delegation", api::TezosOperationTag::OPERATION_TAG_DELEGATION), }; if (opTags.count(value)) { _transaction->type = opTags[value]; } else { _transaction->type = api::TezosOperationTag::OPERATION_TAG_NONE; } if (_lastKey == "type" && _transaction->type == api::TezosOperationTag::OPERATION_TAG_ORIGINATION) { _transaction->originatedAccount = TezosLikeBlockchainExplorerOriginatedAccount(); } } else if (_lastKey == "public_key" || (_lastKey == "data" && _transaction->type == api::TezosOperationTag::OPERATION_TAG_REVEAL)) { _transaction->publicKey = value; } else if (_lastKey == "burn_tez") { _transaction->fees = _transaction->fees + toValue(value, false); } return true; } } TezosLikeTransactionParser::TezosLikeTransactionParser(std::string &lastKey) : _lastKey(lastKey), _blockParser(lastKey) { _arrayDepth = 0; } void TezosLikeTransactionParser::init(TezosLikeBlockchainExplorerTransaction *transaction) { _transaction = transaction; } } }
Add confirmations parsing to TezosTransactionParser
[XTZ] Add confirmations parsing to TezosTransactionParser
C++
mit
LedgerHQ/lib-ledger-core,LedgerHQ/lib-ledger-core,LedgerHQ/lib-ledger-core,LedgerHQ/lib-ledger-core,LedgerHQ/lib-ledger-core,LedgerHQ/lib-ledger-core,LedgerHQ/lib-ledger-core
482949b591d876e9740550141798c8f5e58ef42f
src/uri_relative.cxx
src/uri_relative.cxx
/* * Functions for working with URIs. * * author: Max Kellermann <[email protected]> */ #include "uri_relative.hxx" #include "uri_extract.hxx" #include "strref.h" #include "pool.hxx" #include <string.h> const char * uri_compress(struct pool *pool, const char *uri) { assert(pool != nullptr); assert(uri != nullptr); while (uri[0] == '.' && uri[1] == '/') uri += 2; if (uri[0] == '.' && uri[1] == '.' && (uri[2] == '/' || uri[2] == 0)) return nullptr; if (strstr(uri, "//") == nullptr && strstr(uri, "/./") == nullptr && strstr(uri, "/..") == nullptr) /* cheap route: the URI is already compressed, do not duplicate anything */ return uri; char *dest = p_strdup(pool, uri); /* eliminate "//" */ char *p; while ((p = strstr(dest, "//")) != nullptr) /* strcpy() might be better here, but it does not allow overlapped arguments */ memmove(p + 1, p + 2, strlen(p + 2) + 1); /* eliminate "/./" */ while ((p = strstr(dest, "/./")) != nullptr) /* strcpy() might be better here, but it does not allow overlapped arguments */ memmove(p + 1, p + 3, strlen(p + 3) + 1); /* eliminate "/../" with backtracking */ while ((p = strstr(dest, "/../")) != nullptr) { if (p == dest) { /* this ".." cannot be resolved - scream! */ p_free(pool, dest); return nullptr; } char *q = p; /* backtrack to the previous slash - we can't use strrchr() here, and memrchr() is not portable :( */ do { --q; } while (q >= dest && *q != '/'); /* kill it */ memmove(q + 1, p + 4, strlen(p + 4) + 1); } /* eliminate trailing "/." and "/.." */ p = strrchr(dest, '/'); if (p != nullptr) { if (p[1] == '.' && p[2] == 0) p[1] = 0; else if (p[1] == '.' && p[2] == '.' && p[3] == 0) { if (p == dest) { /* refuse to delete the leading slash */ p_free(pool, dest); return nullptr; } *p = 0; p = strrchr(dest, '/'); if (p == nullptr) { /* if the string doesn't start with a slash, then an empty return value is allowed */ p_free(pool, dest); return ""; } p[1] = 0; } } if (dest[0] == '.' && dest[1] == 0) { /* if the string doesn't start with a slash, then an empty return value is allowed */ p_free(pool, dest); return ""; } return dest; } static const char * uri_after_last_slash(const char *uri) { const char *path = uri_path(uri); if (path == nullptr) return nullptr; uri = strrchr(path, '/'); if (uri != nullptr) ++uri; return uri; } const char * uri_absolute(struct pool *pool, const char *base, const char *uri, size_t length) { assert(base != nullptr); assert(uri != nullptr || length == 0); if (length == 0) return base; if (uri_has_protocol(uri, length)) return p_strndup(pool, uri, length); size_t base_length; if (uri[0] == '/' && uri[1] == '/') { const char *colon = strstr(base, "://"); if (colon != nullptr) base_length = colon + 1 - base; else base_length = 0; } else if (uri[0] == '/') { if (base[0] == '/') return p_strndup(pool, uri, length); const char *base_path = uri_path(base); if (base_path == nullptr) return p_strncat(pool, base, strlen(base), "/", 1, uri, length, nullptr); base_length = base_path - base; } else if (uri[0] == '?') { const char *qmark = strchr(base, '?'); base_length = qmark != nullptr ? (size_t)(qmark - base) : strlen(base); } else { const char *base_end = uri_after_last_slash(base); if (base_end == nullptr) return p_strncat(pool, base, strlen(base), "/", 1, uri, length, nullptr); base_length = base_end - base; } char *dest = PoolAlloc<char>(*pool, base_length + length + 1); memcpy(dest, base, base_length); memcpy(dest + base_length, uri, length); dest[base_length + length] = 0; return dest; } const struct strref * uri_relative(const struct strref *base, struct strref *uri) { if (base == nullptr || strref_is_empty(base) || uri == nullptr || strref_is_empty(uri)) return nullptr; if (uri->length >= base->length && memcmp(uri->data, base->data, base->length) == 0) { strref_skip(uri, base->length); return uri; } /* special case: http://hostname without trailing slash */ if (uri->length == base->length - 1 && memcmp(uri->data, base->data, base->length) && memchr(uri->data + 7, '/', uri->length - 7) == nullptr) { strref_clear(uri); return uri; } return nullptr; }
/* * Functions for working with URIs. * * author: Max Kellermann <[email protected]> */ #include "uri_relative.hxx" #include "uri_extract.hxx" #include "strref.h" #include "pool.hxx" #include <string.h> const char * uri_compress(struct pool *pool, const char *uri) { assert(pool != nullptr); assert(uri != nullptr); while (uri[0] == '.' && uri[1] == '/') uri += 2; if (uri[0] == '.' && uri[1] == '.' && (uri[2] == '/' || uri[2] == 0)) return nullptr; if (strstr(uri, "//") == nullptr && strstr(uri, "/./") == nullptr && strstr(uri, "/..") == nullptr) /* cheap route: the URI is already compressed, do not duplicate anything */ return uri; char *dest = p_strdup(pool, uri); /* eliminate "//" */ char *p; while ((p = strstr(dest, "//")) != nullptr) /* strcpy() might be better here, but it does not allow overlapped arguments */ memmove(p + 1, p + 2, strlen(p + 2) + 1); /* eliminate "/./" */ while ((p = strstr(dest, "/./")) != nullptr) /* strcpy() might be better here, but it does not allow overlapped arguments */ memmove(p + 1, p + 3, strlen(p + 3) + 1); /* eliminate "/../" with backtracking */ while ((p = strstr(dest, "/../")) != nullptr) { if (p == dest) { /* this ".." cannot be resolved - scream! */ p_free(pool, dest); return nullptr; } char *q = p; /* backtrack to the previous slash - we can't use strrchr() here, and memrchr() is not portable :( */ do { --q; } while (q >= dest && *q != '/'); /* kill it */ memmove(q + 1, p + 4, strlen(p + 4) + 1); } /* eliminate trailing "/." and "/.." */ p = strrchr(dest, '/'); if (p != nullptr) { if (p[1] == '.' && p[2] == 0) p[1] = 0; else if (p[1] == '.' && p[2] == '.' && p[3] == 0) { if (p == dest) { /* refuse to delete the leading slash */ p_free(pool, dest); return nullptr; } *p = 0; p = strrchr(dest, '/'); if (p == nullptr) { /* if the string doesn't start with a slash, then an empty return value is allowed */ p_free(pool, dest); return ""; } p[1] = 0; } } if (dest[0] == '.' && dest[1] == 0) { /* if the string doesn't start with a slash, then an empty return value is allowed */ p_free(pool, dest); return ""; } return dest; } static const char * uri_after_last_slash(const char *uri) { const char *path = uri_path(uri); if (path == nullptr) return nullptr; uri = strrchr(path, '/'); if (uri != nullptr) ++uri; return uri; } const char * uri_absolute(struct pool *pool, const char *base, const char *uri, size_t length) { assert(base != nullptr); assert(uri != nullptr || length == 0); if (length == 0) return base; if (uri_has_protocol(uri, length)) return p_strndup(pool, uri, length); size_t base_length; if (length >= 2 && uri[0] == '/' && uri[1] == '/') { const char *colon = strstr(base, "://"); if (colon != nullptr) base_length = colon + 1 - base; else base_length = 0; } else if (uri[0] == '/') { if (base[0] == '/') return p_strndup(pool, uri, length); const char *base_path = uri_path(base); if (base_path == nullptr) return p_strncat(pool, base, strlen(base), "/", 1, uri, length, nullptr); base_length = base_path - base; } else if (uri[0] == '?') { const char *qmark = strchr(base, '?'); base_length = qmark != nullptr ? (size_t)(qmark - base) : strlen(base); } else { const char *base_end = uri_after_last_slash(base); if (base_end == nullptr) return p_strncat(pool, base, strlen(base), "/", 1, uri, length, nullptr); base_length = base_end - base; } char *dest = PoolAlloc<char>(*pool, base_length + length + 1); memcpy(dest, base, base_length); memcpy(dest + base_length, uri, length); dest[base_length + length] = 0; return dest; } const struct strref * uri_relative(const struct strref *base, struct strref *uri) { if (base == nullptr || strref_is_empty(base) || uri == nullptr || strref_is_empty(uri)) return nullptr; if (uri->length >= base->length && memcmp(uri->data, base->data, base->length) == 0) { strref_skip(uri, base->length); return uri; } /* special case: http://hostname without trailing slash */ if (uri->length == base->length - 1 && memcmp(uri->data, base->data, base->length) && memchr(uri->data + 7, '/', uri->length - 7) == nullptr) { strref_clear(uri); return uri; } return nullptr; }
add missing length check
uri_relative: add missing length check
C++
bsd-2-clause
CM4all/beng-proxy,CM4all/beng-proxy,CM4all/beng-proxy,CM4all/beng-proxy,CM4all/beng-proxy,CM4all/beng-proxy
c4f78a5d1527661efeb2fd6444ad886d0e7061f2
src/video/device.cpp
src/video/device.cpp
/**************************************************************************** * Copyright (C) 2012-2019 Savoir-faire Linux Inc. * * Author : Emmanuel Lepage Vallee <[email protected]> * * * * This library is free software; you can redistribute it and/or * * modify it under the terms of the GNU Lesser General Public * * License as published by the Free Software Foundation; either * * version 2.1 of the License, or (at your option) any later version. * * * * This library is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * * Lesser General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program. If not, see <http://www.gnu.org/licenses/>. * ***************************************************************************/ #include "device.h" //Qt #include <QtCore/QTimer> //Ring #include "../dbus/videomanager.h" #include "devicemodel.h" #include "resolution.h" #include "rate.h" #include "channel.h" #include "renderer.h" #include "previewmanager.h" //Ring private #include "../private/videochannel_p.h" #include "../private/videodevice_p.h" #include "../private/videorate_p.h" #include "../private/videoresolution_p.h" #include "../private/videorenderermanager.h" VideoDevicePrivate::VideoDevicePrivate(Video::Device* parent) : QObject(parent),m_pCurrentChannel(nullptr),m_RequireSave(false),q_ptr(parent) { } ///Constructor Video::Device::Device(const QString &id) : QAbstractListModel(nullptr), d_ptr(new VideoDevicePrivate(this)) { d_ptr->m_DeviceId = id; VideoManagerInterface& interface = VideoManager::instance(); MapStringMapStringVectorString cap = interface.getCapabilities(id); QMapIterator<QString, MapStringVectorString> channels(cap); while (channels.hasNext()) { channels.next(); Video::Channel* chan = new Video::Channel(this,channels.key()); d_ptr->m_lChannels << chan; QList<Video::Resolution*> validResolutions; QMapIterator<QString, VectorString> resolutions(channels.value()); while (resolutions.hasNext()) { resolutions.next(); Video::Resolution* res = new Video::Resolution(resolutions.key(),chan); validResolutions << res; foreach(const QString& rate, resolutions.value()) { Video::Rate* r = new Video::Rate(res,rate); if (!res->d_ptr->m_lValidRates.contains(r)) { res->d_ptr->m_lValidRates << r; } } // Sort rates in increasing order. qSort(res->d_ptr->m_lValidRates.begin(), res->d_ptr->m_lValidRates.end(), [](Video::Rate* rateA, Video::Rate* rateB) { return rateA->name().toInt() > rateB->name().toInt(); }); } // Sort resolutions by size area. qSort(validResolutions.begin(), validResolutions.end(), [](Video::Resolution* resA, Video::Resolution* resB) { return resA->width() * resA->height() > resB->width() * resB->height(); }); chan->d_ptr->m_lValidResolutions = validResolutions; } } ///Destructor Video::Device::~Device() { // delete d_ptr; } QVariant Video::Device::data( const QModelIndex& index, int role) const { if (index.isValid() && role == Qt::DisplayRole && d_ptr->m_lChannels.size() > index.row()) { return d_ptr->m_lChannels[index.row()]->name(); } return QVariant(); } int Video::Device::rowCount( const QModelIndex& parent) const { return (parent.isValid())?0:d_ptr->m_lChannels.size(); } Qt::ItemFlags Video::Device::flags( const QModelIndex& idx) const { if (idx.column() == 0) return QAbstractItemModel::flags(idx) | Qt::ItemIsUserCheckable | Qt::ItemIsEnabled | Qt::ItemIsSelectable; return QAbstractItemModel::flags(idx); } bool Video::Device::setData( const QModelIndex& index, const QVariant &value, int role) { Q_UNUSED(index) Q_UNUSED(value) Q_UNUSED(role) return false; } // int Video::Device::relativeIndex() { // return m_pDevice->channelList().indexOf(this); // } ///Get the valid channel list QList<Video::Channel*> Video::Device::channelList() const { return d_ptr->m_lChannels; } ///Save the current settings void Video::Device::save() { if (!d_ptr->m_RequireSave) { d_ptr->m_RequireSave = true; //A little delay won't hurt QTimer::singleShot(100,d_ptr.data(),SLOT(saveIdle())); } } ///Get the device id const QString Video::Device::id() const { return d_ptr->m_DeviceId; } ///Get the device name const QString Video::Device::name() const { VideoManagerInterface& interface = VideoManager::instance(); return QMap<QString,QString>(interface.getSettings(d_ptr->m_DeviceId))[VideoDevicePrivate::PreferenceNames::NAME];; } ///Is this device the default one bool Video::Device::isActive() const { return Video::DeviceModel::instance().activeDevice() == this; } bool Video::Device::setActiveChannel(Video::Channel* chan) { if ((!chan) || (d_ptr->m_lChannels.indexOf(chan) == -1)) { qWarning() << "Trying to set an invalid channel" << (chan?chan->name():"NULL") << "for" << id(); return false; } if (d_ptr->m_pCurrentChannel == chan) return false; d_ptr->m_pCurrentChannel = chan; save(); return true; } bool Video::Device::setActiveChannel(int idx) { if (idx < 0 || idx >= d_ptr->m_lChannels.size()) return false; return setActiveChannel(d_ptr->m_lChannels[idx]); } Video::Channel* Video::Device::activeChannel() const { if (!d_ptr->m_pCurrentChannel) { VideoManagerInterface& interface = VideoManager::instance(); const QString chan = QMap<QString,QString>(interface.getSettings(d_ptr->m_DeviceId))[VideoDevicePrivate::PreferenceNames::CHANNEL]; foreach(Video::Channel* c, d_ptr->m_lChannels) { if (c->name() == chan) { d_ptr->m_pCurrentChannel = c; break; } } } if (!d_ptr->m_pCurrentChannel && d_ptr->m_lChannels.size()) { d_ptr->m_pCurrentChannel = d_ptr->m_lChannels[0]; } return d_ptr->m_pCurrentChannel; } void VideoDevicePrivate::saveIdle() { m_RequireSave = false; //In case new (unsupported) fields are added, merge with existing VideoManagerInterface& interface = VideoManager::instance(); MapStringString pref = interface.getSettings(m_DeviceId); Video::Channel* chan = q_ptr->activeChannel(); if (!chan) { qWarning() << "Saving video failed: Invalid channel"; return; } Video::Resolution* res = chan->activeResolution(); if (!res) { qWarning() << "Saving video failed: Invalid resolution"; return; } Video::Rate* rate = res->activeRate(); if (!rate) { qWarning() << "Saving video failed: Invalid rate"; return; } pref[VideoDevicePrivate::PreferenceNames::CHANNEL] = chan->name (); pref[VideoDevicePrivate::PreferenceNames::SIZE ] = res ->name (); pref[VideoDevicePrivate::PreferenceNames::RATE ] = rate->name (); interface.applySettings(m_DeviceId,pref); //If the preview is running, reload it //doing this during a call will cause re-invite, this is unwanted if (Video::PreviewManager::instance().isPreviewing() && VideoRendererManager::instance().size() == 1) { Video::PreviewManager::instance().stopPreview(); Video::PreviewManager::instance().startPreview(); } }
/**************************************************************************** * Copyright (C) 2012-2019 Savoir-faire Linux Inc. * * Author : Emmanuel Lepage Vallee <[email protected]> * * * * This library is free software; you can redistribute it and/or * * modify it under the terms of the GNU Lesser General Public * * License as published by the Free Software Foundation; either * * version 2.1 of the License, or (at your option) any later version. * * * * This library is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * * Lesser General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program. If not, see <http://www.gnu.org/licenses/>. * ***************************************************************************/ #include "device.h" //Qt #include <QtCore/QTimer> //Ring #include "../dbus/videomanager.h" #include "devicemodel.h" #include "resolution.h" #include "rate.h" #include "channel.h" #include "renderer.h" #include "previewmanager.h" //Ring private #include "../private/videochannel_p.h" #include "../private/videodevice_p.h" #include "../private/videorate_p.h" #include "../private/videoresolution_p.h" #include "../private/videorenderermanager.h" VideoDevicePrivate::VideoDevicePrivate(Video::Device* parent) : QObject(parent),m_pCurrentChannel(nullptr),m_RequireSave(false),q_ptr(parent) { } ///Constructor Video::Device::Device(const QString &id) : QAbstractListModel(nullptr), d_ptr(new VideoDevicePrivate(this)) { d_ptr->m_DeviceId = id; VideoManagerInterface& interface = VideoManager::instance(); MapStringMapStringVectorString cap = interface.getCapabilities(id); QMapIterator<QString, MapStringVectorString> channels(cap); while (channels.hasNext()) { channels.next(); Video::Channel* chan = new Video::Channel(this,channels.key()); d_ptr->m_lChannels << chan; QList<Video::Resolution*> validResolutions; QMapIterator<QString, VectorString> resolutions(channels.value()); while (resolutions.hasNext()) { resolutions.next(); Video::Resolution* res = new Video::Resolution(resolutions.key(),chan); validResolutions << res; foreach(const QString& rate, resolutions.value()) { Video::Rate* r = new Video::Rate(res,rate); if (!res->d_ptr->m_lValidRates.contains(r)) { res->d_ptr->m_lValidRates << r; } } // Sort rates in decreasing order. qSort(res->d_ptr->m_lValidRates.begin(), res->d_ptr->m_lValidRates.end(), [](Video::Rate* rateA, Video::Rate* rateB) { return rateA->name().toInt() < rateB->name().toInt(); }); } // Sort resolutions by size area. qSort(validResolutions.begin(), validResolutions.end(), [](Video::Resolution* resA, Video::Resolution* resB) { return resA->width() * resA->height() > resB->width() * resB->height(); }); chan->d_ptr->m_lValidResolutions = validResolutions; } } ///Destructor Video::Device::~Device() { // delete d_ptr; } QVariant Video::Device::data( const QModelIndex& index, int role) const { if (index.isValid() && role == Qt::DisplayRole && d_ptr->m_lChannels.size() > index.row()) { return d_ptr->m_lChannels[index.row()]->name(); } return QVariant(); } int Video::Device::rowCount( const QModelIndex& parent) const { return (parent.isValid())?0:d_ptr->m_lChannels.size(); } Qt::ItemFlags Video::Device::flags( const QModelIndex& idx) const { if (idx.column() == 0) return QAbstractItemModel::flags(idx) | Qt::ItemIsUserCheckable | Qt::ItemIsEnabled | Qt::ItemIsSelectable; return QAbstractItemModel::flags(idx); } bool Video::Device::setData( const QModelIndex& index, const QVariant &value, int role) { Q_UNUSED(index) Q_UNUSED(value) Q_UNUSED(role) return false; } // int Video::Device::relativeIndex() { // return m_pDevice->channelList().indexOf(this); // } ///Get the valid channel list QList<Video::Channel*> Video::Device::channelList() const { return d_ptr->m_lChannels; } ///Save the current settings void Video::Device::save() { if (!d_ptr->m_RequireSave) { d_ptr->m_RequireSave = true; //A little delay won't hurt QTimer::singleShot(100,d_ptr.data(),SLOT(saveIdle())); } } ///Get the device id const QString Video::Device::id() const { return d_ptr->m_DeviceId; } ///Get the device name const QString Video::Device::name() const { VideoManagerInterface& interface = VideoManager::instance(); return QMap<QString,QString>(interface.getSettings(d_ptr->m_DeviceId))[VideoDevicePrivate::PreferenceNames::NAME];; } ///Is this device the default one bool Video::Device::isActive() const { return Video::DeviceModel::instance().activeDevice() == this; } bool Video::Device::setActiveChannel(Video::Channel* chan) { if ((!chan) || (d_ptr->m_lChannels.indexOf(chan) == -1)) { qWarning() << "Trying to set an invalid channel" << (chan?chan->name():"NULL") << "for" << id(); return false; } if (d_ptr->m_pCurrentChannel == chan) return false; d_ptr->m_pCurrentChannel = chan; save(); return true; } bool Video::Device::setActiveChannel(int idx) { if (idx < 0 || idx >= d_ptr->m_lChannels.size()) return false; return setActiveChannel(d_ptr->m_lChannels[idx]); } Video::Channel* Video::Device::activeChannel() const { if (!d_ptr->m_pCurrentChannel) { VideoManagerInterface& interface = VideoManager::instance(); const QString chan = QMap<QString,QString>(interface.getSettings(d_ptr->m_DeviceId))[VideoDevicePrivate::PreferenceNames::CHANNEL]; foreach(Video::Channel* c, d_ptr->m_lChannels) { if (c->name() == chan) { d_ptr->m_pCurrentChannel = c; break; } } } if (!d_ptr->m_pCurrentChannel && d_ptr->m_lChannels.size()) { d_ptr->m_pCurrentChannel = d_ptr->m_lChannels[0]; } return d_ptr->m_pCurrentChannel; } void VideoDevicePrivate::saveIdle() { m_RequireSave = false; //In case new (unsupported) fields are added, merge with existing VideoManagerInterface& interface = VideoManager::instance(); MapStringString pref = interface.getSettings(m_DeviceId); Video::Channel* chan = q_ptr->activeChannel(); if (!chan) { qWarning() << "Saving video failed: Invalid channel"; return; } Video::Resolution* res = chan->activeResolution(); if (!res) { qWarning() << "Saving video failed: Invalid resolution"; return; } Video::Rate* rate = res->activeRate(); if (!rate) { qWarning() << "Saving video failed: Invalid rate"; return; } pref[VideoDevicePrivate::PreferenceNames::CHANNEL] = chan->name (); pref[VideoDevicePrivate::PreferenceNames::SIZE ] = res ->name (); pref[VideoDevicePrivate::PreferenceNames::RATE ] = rate->name (); interface.applySettings(m_DeviceId,pref); //If the preview is running, reload it //doing this during a call will cause re-invite, this is unwanted if (Video::PreviewManager::instance().isPreviewing() && VideoRendererManager::instance().size() == 1) { Video::PreviewManager::instance().stopPreview(); Video::PreviewManager::instance().startPreview(); } }
sort frame rates from highest to lowest
video: sort frame rates from highest to lowest Change-Id: Ib98e0e3877b17a1d5653ef617a88a354640cf629 Reviewed-by: Philippe Gorley <[email protected]>
C++
lgpl-2.1
savoirfairelinux/ring-lrc,savoirfairelinux/ring-lrc,savoirfairelinux/ring-lrc,savoirfairelinux/ring-lrc,savoirfairelinux/ring-lrc
2ca4b15c5f62e7777567609591952a007e94203d
jni/com/virtualoso/nativetools/client/screens/ExtendedInventoryScreen.cpp
jni/com/virtualoso/nativetools/client/screens/ExtendedInventoryScreen.cpp
#include "ExtendedInventoryScreen.h" #include "InventoryTransitions.h" #include "../../creative/CreativeTab.h" #include "com/mojang/minecraftpe/client/MinecraftClient.h" #include "com/mojang/minecraftpe/client/gui/NinePatchLayer.h" #include "com/mojang/minecraftpe/client/gui/IntRectangle.h" #include "com/mojang/minecraftpe/client/gui/ImageWithBackground.h" #include "com/mojang/minecraftpe/client/gui/InventoryTab.h" #include "com/mojang/minecraftpe/client/gui/GuiData.h" #include "com/mojang/minecraftpe/client/settings/Options.h" #include "com/mojang/minecraftpe/client/renderer/Tessellator.h" #include "com/mojang/minecraftpe/client/renderer/texture/TextureGroup.h" #include "com/mojang/minecraftpe/client/renderer/entity/ItemRenderer.h" #include "com/mojang/minecraftpe/client/renderer/ShaderColor.h" #include "com/mojang/minecraftpe/world/item/ItemInstance.h" #include "com/mojang/minecraftpe/world/entity/player/LocalPlayer.h" #include "com/mojang/minecraftpe/world/inventory/Inventory.h" ExtendedInventoryScreen::ExtendedInventoryScreen(MinecraftClient& client, std::vector<CreativeTab*> creativeTabs) : Screen(client) { closeButton = NULL; backgroundLayer = NULL; leftButtonLayer = NULL; rightButtonLayer = NULL; ownedTabs = creativeTabs; } bool ExtendedInventoryScreen::renderGameBehind() const { return mcClient->getOptions()->getFancyGraphics(); } bool ExtendedInventoryScreen::closeOnPlayerHurt() const { return true; } void ExtendedInventoryScreen::init() { if(!closeButton) { InventoryTransitions::init(this); NinePatchFactory factory (mcClient->getTextures(), "gui/spritesheet.png"); backgroundLayer = std::shared_ptr<NinePatchLayer>(factory.createSymmetrical({34, 43, 14, 14}, 3, 3, 14.0F, 14.0F)); leftButtonLayer = std::shared_ptr<NinePatchLayer>(factory.createSymmetrical({49, 43, 14, 14}, 3, 3, 14.0F, 14.0F)); rightButtonLayer = std::shared_ptr<NinePatchLayer>(factory.createSymmetrical({65, 55, 14, 14}, 3, 3, 14.0F, 14.0F)); closeButton = std::make_shared<ImageWithBackground>(2); closeButton->init(mcClient->getTextures(), 28, 28, {49, 43, 14, 14}, {49, 43, 14, 14}, 2, 2, "gui/spritesheet.png"); closeButton->setImageDef({mcClient->getTextures()->getTexture("gui/spritesheet.png", TextureLocation::Default), 0, 1, 18.0F, 18.0F, {60, 0, 18, 18}, true}, true); for(int tab = 0; tab < ownedTabs.size(); tab++) { renderedTabs.emplace_back(createInventoryTab(tab + 3, ((tab < 4) ? false : true))); } selectedTabIndex = 0; buttonList.emplace_back(closeButton); } } void ExtendedInventoryScreen::render(int i1, int i2, float f1) { if(renderGameBehind()) renderBackground(1); else renderDirtBackground(); renderToolBar(f1, 1.0F, false); for(int tab = 0; tab < renderedTabs.size(); tab++) { if(tab != selectedTabIndex) { renderedTabs[tab]->renderBg(mcClient, i1, i2); drawTabIcon(ownedTabs[tab], renderedTabs[tab], renderedTabs[tab]->pressed, false); } } backgroundLayer->draw(Tessellator::instance, backgroundLayer->xPosition, backgroundLayer->yPosition); renderedTabs[selectedTabIndex]->renderBg(mcClient, i1, i2); drawTabIcon(ownedTabs[selectedTabIndex], renderedTabs[selectedTabIndex], renderedTabs[selectedTabIndex]->pressed, true); InventoryTransitions::render(this, i1, i2, f1); Screen::render(i1, i2, f1); currentShaderColor.setColor(Color::WHITE); fill(paneBgX, paneBgY, paneBgWidth + paneBgX, paneBgHeight + paneBgY, {0.2F, 0.2F, 0.2F, 1.0F}); inventoryPanes[selectedTabIndex]->render(i1, i2, f1, mcClient); renderOnSelectItemNameText(width, mcClient->getFont(), height - 41); } void ExtendedInventoryScreen::setupPositions() { backgroundLayer->xPosition = 31; backgroundLayer->yPosition = 2; backgroundLayer->setSize((float)(width - 26 - 28) - 4.0F - 6.0F, (float)height - 25.0F); closeButton->xPosition = backgroundLayer->xPosition - 26; closeButton->yPosition = backgroundLayer->yPosition; closeButton->setSize(29, 28); paneBgX = backgroundLayer->xPosition + 5; paneBgY = backgroundLayer->yPosition + 4; paneBgWidth = width - 38 - paneBgX; paneBgHeight = height - 27 - paneBgY; int paneOffset = (paneBgWidth % 26) / 2; paneWidth = paneBgWidth - (paneOffset * 2); paneHeight = paneBgHeight - 8; paneX = paneBgX + paneOffset; paneY = paneBgY + 4; for(int tab = 0; tab < renderedTabs.size(); tab++) { if(!renderedTabs[tab]->isRight) { renderedTabs[tab]->xPosition = backgroundLayer->xPosition - 26; renderedTabs[tab]->yPosition = height - 25 - 29 - (tab * 31); } else { renderedTabs[tab]->xPosition = width - 6 - 29; renderedTabs[tab]->yPosition = height - 25 - 29 - ((tab - 4) * 31); } renderedTabs[tab]->width = 29; renderedTabs[tab]->height = 29; inventoryPanes[tab] = new Touch::InventoryPane(this, *mcClient, {paneX, paneY, paneWidth, paneHeight}, 1, 1.0F, 5, 26, 1, false, true, false); inventoryPanes[tab]->xPosition = paneX; inventoryPanes[tab]->yPosition = paneY; inventoryPanes[tab]->width = paneWidth; inventoryPanes[tab]->height = paneHeight; } InventoryTransitions::setupPositions(this); } void ExtendedInventoryScreen::_buttonClicked(Button& button) { InventoryTransitions::_buttonClicked(this, button); if(button.id == closeButton->id) InventoryTransitions::closeScreens(this); } void ExtendedInventoryScreen::_pointerReleased(int x, int y) { Screen::_pointerReleased(x, y); for(int tab = 0; tab < renderedTabs.size(); tab++) { if(tab != selectedTabIndex && renderedTabs[tab]->isInside(x, y) && renderedTabs[tab]->pressed) selectedTabIndex = tab; renderedTabs[tab]->pressed = false; } } void ExtendedInventoryScreen::_pointerPressed(int x, int y) { Screen::_pointerPressed(x, y); for(int tab = 0; tab < renderedTabs.size(); tab++) { if(renderedTabs[tab]->isInside(x, y)) { renderedTabs[tab]->pressed = true; return; } } } void ExtendedInventoryScreen::handleBackEvent(bool b1) { if(!b1) InventoryTransitions::pushPreviousScreen(this); } bool ExtendedInventoryScreen::isModal() const { return true; } void ExtendedInventoryScreen::tick() { inventoryPanes[selectedTabIndex]->tick(); } std::string ExtendedInventoryScreen::getScreenName() { return "extended_creative_screen"; } std::shared_ptr<InventoryTab> ExtendedInventoryScreen::createInventoryTab(int id, bool isRight) { NinePatchLayer* buttonLayer = isRight ? rightButtonLayer.get() : leftButtonLayer.get(); std::shared_ptr<InventoryTab> button = std::make_shared<InventoryTab>(id, "", buttonLayer, isRight); button->setOverrideScreenRendering(true); return button; } void ExtendedInventoryScreen::drawTabIcon(CreativeTab* ownedTab, std::shared_ptr<InventoryTab> imageButton, bool isPressed, bool isSelected) { ItemRenderer::getInstance()->renderGuiItemNew(ownedTab->getTabIcon(), 0, ((float)imageButton->xPosition + (float)((imageButton->width / 2) - 8) + (isPressed ? 1.0F : 0.7F)), ((float)imageButton->yPosition + (float)((imageButton->height / 2) - 8)), 1.0F, (isSelected ? 1.0F : 0.7F), (((float)imageButton->width) - (isPressed ? 2.0F : 0.0F)) * 0.04F, false); } int ExtendedInventoryScreen::putItemInInventory(ItemInstance& item, bool fullStack) { Inventory* inv = mcClient->getLocalPlayer()->inventory; int slot = inv->getLinkedSlotForExactItem(item); int selectedSlot = inv->getSelectedSlot(); int linkedSlot; if(!(slot >= mcClient->getGuiData()->getNumSlots() | slot >> 31)) { linkedSlot = inv->getLinkedSlot(selectedSlot); ItemInstance* selectedItem = inv->getItem(linkedSlot); if(selectedItem && selectedItem->sameItemAndAux(&item)) { if(selectedItem->count < selectedItem->getMaxStackSize()) selectedItem->count = fullStack ? selectedItem->getMaxStackSize() : selectedItem->count + 1; } else { inv->linkSlot(selectedSlot, inv->getLinkedSlot(slot)); inv->linkSlot(slot, linkedSlot); } } else if(inv->getLinkedSlot(selectedSlot) <= 44 || (inv->add(item, false), linkedSlot = inv->getSlotWithItem(item, true, true), linkedSlot >= 0)) { item.count = fullStack ? item.getMaxStackSize() : 1; inv->setItem(linkedSlot, &item); inv->linkSlot(selectedSlot, linkedSlot); inv->setItem(selectedSlot, &item); } else { linkedSlot = -1; } ItemInstance* currentItem = mcClient->getLocalPlayer()->getSelectedItem(); if(currentItem) mcClient->getGuiData()->showPopupNotice(currentItem->getName(), currentItem->getEffectName()); mcClient->getGuiData()->flashSlot(inv->getSelectedSlot()); return linkedSlot; } bool ExtendedInventoryScreen::addItem(Touch::InventoryPane& pane, int slot) { pane.resetHoldTime(); for(int tab = 0; tab < renderedTabs.size(); tab++) { if(&pane == inventoryPanes[tab]) { ItemInstance item; item = *(ownedTabs[tab]->itemsInTab[slot]); return putItemInInventory(item, true); } } return false; } bool ExtendedInventoryScreen::isAllowed(int slot) { return true; } std::vector<const ItemInstance*> ExtendedInventoryScreen::getItems(const Touch::InventoryPane& pane) { for(int tab = 0; tab < renderedTabs.size(); tab++) { if(&pane == inventoryPanes[tab] && !(ownedTabs[tab]->itemsInTab.empty())) return ownedTabs[tab]->itemsInTab; } std::vector<const ItemInstance*> itemVecNull; return itemVecNull; }
#include "ExtendedInventoryScreen.h" #include "InventoryTransitions.h" #include "../../creative/CreativeTab.h" #include "com/mojang/minecraftpe/client/MinecraftClient.h" #include "com/mojang/minecraftpe/client/gui/NinePatchLayer.h" #include "com/mojang/minecraftpe/client/gui/IntRectangle.h" #include "com/mojang/minecraftpe/client/gui/ImageWithBackground.h" #include "com/mojang/minecraftpe/client/gui/InventoryTab.h" #include "com/mojang/minecraftpe/client/gui/GuiData.h" #include "com/mojang/minecraftpe/client/settings/Options.h" #include "com/mojang/minecraftpe/client/renderer/Tessellator.h" #include "com/mojang/minecraftpe/client/renderer/texture/TextureGroup.h" #include "com/mojang/minecraftpe/client/renderer/entity/ItemRenderer.h" #include "com/mojang/minecraftpe/client/renderer/ShaderColor.h" #include "com/mojang/minecraftpe/world/item/ItemInstance.h" #include "com/mojang/minecraftpe/world/entity/player/LocalPlayer.h" #include "com/mojang/minecraftpe/world/inventory/Inventory.h" ExtendedInventoryScreen::ExtendedInventoryScreen(MinecraftClient& client, std::vector<CreativeTab*> creativeTabs) : Screen(client) { closeButton = NULL; backgroundLayer = NULL; leftButtonLayer = NULL; rightButtonLayer = NULL; ownedTabs = creativeTabs; } bool ExtendedInventoryScreen::renderGameBehind() const { return mcClient->getOptions()->getFancyGraphics(); } bool ExtendedInventoryScreen::closeOnPlayerHurt() const { return true; } void ExtendedInventoryScreen::init() { if(!closeButton) { InventoryTransitions::init(this); NinePatchFactory factory (mcClient->getTextures(), "gui/spritesheet.png"); backgroundLayer = std::shared_ptr<NinePatchLayer>(factory.createSymmetrical({34, 43, 14, 14}, 3, 3, 14.0F, 14.0F)); leftButtonLayer = std::shared_ptr<NinePatchLayer>(factory.createSymmetrical({49, 43, 14, 14}, 3, 3, 14.0F, 14.0F)); rightButtonLayer = std::shared_ptr<NinePatchLayer>(factory.createSymmetrical({65, 55, 14, 14}, 3, 3, 14.0F, 14.0F)); closeButton = std::make_shared<ImageWithBackground>(2); closeButton->init(mcClient->getTextures(), 28, 28, {49, 43, 14, 14}, {49, 43, 14, 14}, 2, 2, "gui/spritesheet.png"); closeButton->setImageDef({mcClient->getTextures()->getTexture("gui/spritesheet.png", TextureLocation::Default), 0, 1, 18.0F, 18.0F, {60, 0, 18, 18}, true}, true); for(int tab = 0; tab < ownedTabs.size(); tab++) { renderedTabs.emplace_back(createInventoryTab(tab + 3, ((tab < 4) ? false : true))); } selectedTabIndex = 0; buttonList.emplace_back(closeButton); } } void ExtendedInventoryScreen::render(int i1, int i2, float f1) { if(renderGameBehind()) renderBackground(1); else renderDirtBackground(); renderToolBar(f1, 1.0F, false); for(int tab = 0; tab < renderedTabs.size(); tab++) { if(tab != selectedTabIndex) { renderedTabs[tab]->renderBg(mcClient, i1, i2); drawTabIcon(ownedTabs[tab], renderedTabs[tab], renderedTabs[tab]->pressed, false); } } backgroundLayer->draw(Tessellator::instance, backgroundLayer->xPosition, backgroundLayer->yPosition); renderedTabs[selectedTabIndex]->renderBg(mcClient, i1, i2); drawTabIcon(ownedTabs[selectedTabIndex], renderedTabs[selectedTabIndex], renderedTabs[selectedTabIndex]->pressed, true); InventoryTransitions::render(this, i1, i2, f1); Screen::render(i1, i2, f1); currentShaderColor.setColor(Color::WHITE); fill(paneBgX, paneBgY, paneBgWidth + paneBgX, paneBgHeight + paneBgY, {0.2F, 0.2F, 0.2F, 1.0F}); inventoryPanes[selectedTabIndex]->render(i1, i2, f1, mcClient); renderOnSelectItemNameText(width, mcClient->getFont(), height - 41); } void ExtendedInventoryScreen::setupPositions() { backgroundLayer->xPosition = 31; backgroundLayer->yPosition = 2; backgroundLayer->setSize((float)(width - 26 - 28) - 4.0F - 6.0F, (float)height - 25.0F); closeButton->xPosition = backgroundLayer->xPosition - 26; closeButton->yPosition = backgroundLayer->yPosition; closeButton->setSize(29, 28); paneBgX = backgroundLayer->xPosition + 5; paneBgY = backgroundLayer->yPosition + 4; paneBgWidth = width - 38 - paneBgX; paneBgHeight = height - 27 - paneBgY; int paneOffset = (paneBgWidth % 26) / 2; paneWidth = paneBgWidth - (paneOffset * 2); paneHeight = paneBgHeight - 8; paneX = paneBgX + paneOffset; paneY = paneBgY + 4; for(int tab = 0; tab < renderedTabs.size(); tab++) { if(!renderedTabs[tab]->isRight) { renderedTabs[tab]->xPosition = backgroundLayer->xPosition - 26; renderedTabs[tab]->yPosition = height - 25 - 29 - (tab * 31); } else { renderedTabs[tab]->xPosition = width - 6 - 29; renderedTabs[tab]->yPosition = height - 25 - 29 - ((tab - 4) * 31); } renderedTabs[tab]->width = 29; renderedTabs[tab]->height = 29; inventoryPanes[tab] = new Touch::InventoryPane(this, *mcClient, {paneX, paneY, paneWidth, paneHeight}, 1, 1.0F, 5, 26, 1, false, true, false); inventoryPanes[tab]->xPosition = paneX; inventoryPanes[tab]->yPosition = paneY; inventoryPanes[tab]->width = paneWidth; inventoryPanes[tab]->height = paneHeight; } InventoryTransitions::setupPositions(this); } void ExtendedInventoryScreen::_buttonClicked(Button& button) { InventoryTransitions::_buttonClicked(this, button); if(button.id == closeButton->id) InventoryTransitions::closeScreens(this); } void ExtendedInventoryScreen::_pointerReleased(int x, int y) { Screen::_pointerReleased(x, y); for(int tab = 0; tab < renderedTabs.size(); tab++) { if(tab != selectedTabIndex && renderedTabs[tab]->isInside(x, y) && renderedTabs[tab]->pressed) selectedTabIndex = tab; renderedTabs[tab]->pressed = false; } } void ExtendedInventoryScreen::_pointerPressed(int x, int y) { Screen::_pointerPressed(x, y); for(int tab = 0; tab < renderedTabs.size(); tab++) { if(renderedTabs[tab]->isInside(x, y)) { renderedTabs[tab]->pressed = true; return; } } } void ExtendedInventoryScreen::handleBackEvent(bool b1) { if(!b1) InventoryTransitions::pushPreviousScreen(this); } bool ExtendedInventoryScreen::isModal() const { return true; } void ExtendedInventoryScreen::tick() { inventoryPanes[selectedTabIndex]->tick(); } std::string ExtendedInventoryScreen::getScreenName() { return "extended_creative_screen"; } std::shared_ptr<InventoryTab> ExtendedInventoryScreen::createInventoryTab(int id, bool isRight) { NinePatchLayer* buttonLayer = isRight ? rightButtonLayer.get() : leftButtonLayer.get(); std::shared_ptr<InventoryTab> button = std::make_shared<InventoryTab>(id, "", buttonLayer, isRight); button->setOverrideScreenRendering(true); return button; } void ExtendedInventoryScreen::drawTabIcon(CreativeTab* ownedTab, std::shared_ptr<InventoryTab> imageButton, bool isPressed, bool isSelected) { ItemRenderer::getInstance()->renderGuiItemNew(ownedTab->getTabIcon(), 0, ((float)imageButton->xPosition + (float)((imageButton->width / 2) - 8) + (isPressed ? 1.0F : 0.7F)), ((float)imageButton->yPosition + (float)((imageButton->height / 2) - 8)), 1.0F, (isSelected ? 1.0F : 0.7F), (((float)imageButton->width) - (isPressed ? 2.0F : 0.0F)) * 0.04F, false); } int ExtendedInventoryScreen::putItemInInventory(ItemInstance& item, bool fullStack) { Inventory* inv = mcClient->getLocalPlayer()->inventory; int slot = inv->getLinkedSlotForExactItem(item); int selectedSlot = inv->getSelectedSlot(); int linkedSlot; if(slot < mcClient->getGuiData()->getNumSlots() && slot != -1) { linkedSlot = inv->getLinkedSlot(selectedSlot); ItemInstance* selectedItem = inv->getItem(linkedSlot); if(selectedItem && selectedItem->sameItemAndAux(&item)) { if(selectedItem->count < selectedItem->getMaxStackSize()) selectedItem->count = fullStack ? selectedItem->getMaxStackSize() : selectedItem->count + 1; } else { inv->linkSlot(selectedSlot, inv->getLinkedSlot(slot)); inv->linkSlot(slot, linkedSlot); } } else { inv->add(item, false); linkedSlot = inv->getSlotWithItem(item, true, true); if(inv->getLinkedSlot(selectedSlot) <= 44 || linkedSlot >= 0) { item.count = fullStack ? item.getMaxStackSize() : 1; inv->setItem(linkedSlot, &item); inv->linkSlot(selectedSlot, linkedSlot); inv->setItem(selectedSlot, &item); } else { linkedSlot = -1; } } ItemInstance* currentItem = mcClient->getLocalPlayer()->getSelectedItem(); if(currentItem) mcClient->getGuiData()->showPopupNotice(currentItem->getName(), currentItem->getEffectName()); mcClient->getGuiData()->flashSlot(inv->getSelectedSlot()); return linkedSlot; } bool ExtendedInventoryScreen::addItem(Touch::InventoryPane& pane, int slot) { pane.resetHoldTime(); for(int tab = 0; tab < renderedTabs.size(); tab++) { if(&pane == inventoryPanes[tab]) { ItemInstance item; item = *(ownedTabs[tab]->itemsInTab[slot]); return putItemInInventory(item, true); } } return false; } bool ExtendedInventoryScreen::isAllowed(int slot) { return true; } std::vector<const ItemInstance*> ExtendedInventoryScreen::getItems(const Touch::InventoryPane& pane) { for(int tab = 0; tab < renderedTabs.size(); tab++) { if(&pane == inventoryPanes[tab] && !(ownedTabs[tab]->itemsInTab.empty())) return ownedTabs[tab]->itemsInTab; } std::vector<const ItemInstance*> itemVecNull; return itemVecNull; }
Fix Item adding
Fix Item adding
C++
mit
Virtualoso/NativeTools,Virtualoso/InventoryPlus,Virtualoso/NativeTools,Virtualoso/InventoryPlus
f96ecef98a859d42a4fc0f6047991e8e838c8a0a
libraries/blockchain/account_record.cpp
libraries/blockchain/account_record.cpp
#include <bts/blockchain/account_record.hpp> #include <bts/blockchain/chain_interface.hpp> namespace bts { namespace blockchain { share_type account_record::delegate_pay_balance()const { FC_ASSERT( is_delegate() ); return delegate_info->pay_balance; } bool account_record::is_delegate()const { return delegate_info.valid(); } int64_t account_record::net_votes()const { FC_ASSERT( is_delegate() ); return delegate_info->votes_for; } void account_record::adjust_votes_for( const share_type delta ) { FC_ASSERT( is_delegate() ); delegate_info->votes_for += delta; } bool account_record::is_retracted()const { return active_key() == public_key_type(); } address account_record::active_address()const { return address( active_key() ); } void account_record::set_active_key( const time_point_sec now, const public_key_type& new_key ) { try { FC_ASSERT( now != fc::time_point_sec() ); active_key_history[ now ] = new_key; } FC_CAPTURE_AND_RETHROW( (now)(new_key) ) } public_key_type account_record::active_key()const { if( active_key_history.empty() ) return public_key_type(); return active_key_history.rbegin()->second; } uint8_t account_record::delegate_pay_rate()const { if( !is_delegate() ) return -1; return delegate_info->pay_rate; } void account_record::set_signing_key( uint32_t block_num, const public_key_type& signing_key ) { FC_ASSERT( is_delegate() ); delegate_info->signing_key_history[ block_num ] = signing_key; } public_key_type account_record::signing_key()const { FC_ASSERT( is_delegate() ); FC_ASSERT( !delegate_info->signing_key_history.empty() ); return delegate_info->signing_key_history.crbegin()->second; } address account_record::signing_address()const { return address( signing_key() ); } public_key_type burn_record_value::signer_key()const { FC_ASSERT( signer.valid() ); fc::sha256 digest; if( message.size() ) digest = fc::sha256::hash( message.c_str(), message.size() ); return fc::ecc::public_key( *signer, digest ); } const account_db_interface& account_record::db_interface( const chain_interface& db ) { try { return db._account_db_interface; } FC_CAPTURE_AND_RETHROW() } void account_record::sanity_check( const chain_interface& db )const { try { FC_ASSERT( id > 0 ); FC_ASSERT( !name.empty() ); if( delegate_info.valid() ) { FC_ASSERT( delegate_info->votes_for >= 0 ); FC_ASSERT( delegate_info->pay_rate <= 100 ); FC_ASSERT( !delegate_info->signing_key_history.empty() ); FC_ASSERT( delegate_info->pay_balance >= 0 ); } } FC_CAPTURE_AND_RETHROW( (*this) ) } oaccount_record account_db_interface::lookup( const account_id_type id )const { try { return lookup_by_id( id ); } FC_CAPTURE_AND_RETHROW( (id) ) } oaccount_record account_db_interface::lookup( const string& name )const { try { return lookup_by_name( name ); } FC_CAPTURE_AND_RETHROW( (name) ) } oaccount_record account_db_interface::lookup( const address& addr )const { try { return lookup_by_address( addr ); } FC_CAPTURE_AND_RETHROW( (addr) ) } void account_db_interface::store( const account_id_type id, const account_record& record )const { try { const oaccount_record prev_record = lookup( id ); if( prev_record.valid() ) { if( prev_record->name != record.name ) erase_from_name_map( prev_record->name ); if( prev_record->owner_address() != record.owner_address() ) erase_from_address_map( prev_record->owner_address() ); if( !prev_record->is_retracted() ) { if( record.is_retracted() || prev_record->active_address() != record.active_address() ) erase_from_address_map( prev_record->active_address() ); if( prev_record->is_delegate() ) { if( record.is_retracted() || !record.is_delegate() || prev_record->signing_address() != record.signing_address() ) erase_from_address_map( prev_record->signing_address() ); if( record.is_retracted() || !record.is_delegate() || prev_record->net_votes() != record.net_votes() ) erase_from_vote_set( vote_del( prev_record->net_votes(), prev_record->id ) ); } } } insert_into_id_map( id, record ); insert_into_name_map( record.name, id ); insert_into_address_map( record.owner_address(), id ); if( !record.is_retracted() ) { insert_into_address_map( record.active_address(), id ); if( record.is_delegate() ) { insert_into_address_map( record.signing_address(), id ); insert_into_vote_set( vote_del( record.net_votes(), id ) ); } } } FC_CAPTURE_AND_RETHROW( (id)(record) ) } void account_db_interface::remove( const account_id_type id )const { try { const oaccount_record prev_record = lookup( id ); if( prev_record.valid() ) { erase_from_id_map( id ); erase_from_name_map( prev_record->name ); erase_from_address_map( prev_record->owner_address() ); if( !prev_record->is_retracted() ) { erase_from_address_map( prev_record->active_address() ); if( prev_record->is_delegate() ) { erase_from_address_map( prev_record->signing_address() ); erase_from_vote_set( vote_del( prev_record->net_votes(), prev_record->id ) ); } } } } FC_CAPTURE_AND_RETHROW( (id) ) } } } // bts::blockchain
#include <bts/blockchain/account_record.hpp> #include <bts/blockchain/chain_interface.hpp> namespace bts { namespace blockchain { share_type account_record::delegate_pay_balance()const { FC_ASSERT( is_delegate() ); return delegate_info->pay_balance; } bool account_record::is_delegate()const { return delegate_info.valid(); } int64_t account_record::net_votes()const { FC_ASSERT( is_delegate() ); return delegate_info->votes_for; } void account_record::adjust_votes_for( const share_type delta ) { FC_ASSERT( is_delegate() ); delegate_info->votes_for += delta; } bool account_record::is_retracted()const { return active_key() == public_key_type(); } address account_record::active_address()const { return address( active_key() ); } void account_record::set_active_key( const time_point_sec now, const public_key_type& new_key ) { try { FC_ASSERT( now != fc::time_point_sec() ); active_key_history[ now ] = new_key; } FC_CAPTURE_AND_RETHROW( (now)(new_key) ) } public_key_type account_record::active_key()const { FC_ASSERT( !active_key_history.empty() ); return active_key_history.rbegin()->second; } uint8_t account_record::delegate_pay_rate()const { if( !is_delegate() ) return -1; return delegate_info->pay_rate; } void account_record::set_signing_key( uint32_t block_num, const public_key_type& signing_key ) { FC_ASSERT( is_delegate() ); delegate_info->signing_key_history[ block_num ] = signing_key; } public_key_type account_record::signing_key()const { FC_ASSERT( is_delegate() ); FC_ASSERT( !delegate_info->signing_key_history.empty() ); return delegate_info->signing_key_history.crbegin()->second; } address account_record::signing_address()const { return address( signing_key() ); } public_key_type burn_record_value::signer_key()const { FC_ASSERT( signer.valid() ); fc::sha256 digest; if( message.size() ) digest = fc::sha256::hash( message.c_str(), message.size() ); return fc::ecc::public_key( *signer, digest ); } const account_db_interface& account_record::db_interface( const chain_interface& db ) { try { return db._account_db_interface; } FC_CAPTURE_AND_RETHROW() } void account_record::sanity_check( const chain_interface& db )const { try { FC_ASSERT( id > 0 ); FC_ASSERT( !name.empty() ); FC_ASSERT( !active_key_history.empty() ); if( delegate_info.valid() ) { FC_ASSERT( delegate_info->votes_for >= 0 ); FC_ASSERT( delegate_info->pay_rate <= 100 ); FC_ASSERT( !delegate_info->signing_key_history.empty() ); FC_ASSERT( delegate_info->pay_balance >= 0 ); } } FC_CAPTURE_AND_RETHROW( (*this) ) } oaccount_record account_db_interface::lookup( const account_id_type id )const { try { return lookup_by_id( id ); } FC_CAPTURE_AND_RETHROW( (id) ) } oaccount_record account_db_interface::lookup( const string& name )const { try { return lookup_by_name( name ); } FC_CAPTURE_AND_RETHROW( (name) ) } oaccount_record account_db_interface::lookup( const address& addr )const { try { return lookup_by_address( addr ); } FC_CAPTURE_AND_RETHROW( (addr) ) } void account_db_interface::store( const account_id_type id, const account_record& record )const { try { const oaccount_record prev_record = lookup( id ); if( prev_record.valid() ) { if( prev_record->name != record.name ) erase_from_name_map( prev_record->name ); if( prev_record->owner_address() != record.owner_address() ) erase_from_address_map( prev_record->owner_address() ); if( !prev_record->is_retracted() ) { if( record.is_retracted() || prev_record->active_address() != record.active_address() ) erase_from_address_map( prev_record->active_address() ); if( prev_record->is_delegate() ) { if( record.is_retracted() || !record.is_delegate() || prev_record->signing_address() != record.signing_address() ) erase_from_address_map( prev_record->signing_address() ); if( record.is_retracted() || !record.is_delegate() || prev_record->net_votes() != record.net_votes() ) erase_from_vote_set( vote_del( prev_record->net_votes(), prev_record->id ) ); } } } insert_into_id_map( id, record ); insert_into_name_map( record.name, id ); insert_into_address_map( record.owner_address(), id ); if( !record.is_retracted() ) { insert_into_address_map( record.active_address(), id ); if( record.is_delegate() ) { insert_into_address_map( record.signing_address(), id ); insert_into_vote_set( vote_del( record.net_votes(), id ) ); } } } FC_CAPTURE_AND_RETHROW( (id)(record) ) } void account_db_interface::remove( const account_id_type id )const { try { const oaccount_record prev_record = lookup( id ); if( prev_record.valid() ) { erase_from_id_map( id ); erase_from_name_map( prev_record->name ); erase_from_address_map( prev_record->owner_address() ); if( !prev_record->is_retracted() ) { erase_from_address_map( prev_record->active_address() ); if( prev_record->is_delegate() ) { erase_from_address_map( prev_record->signing_address() ); erase_from_vote_set( vote_del( prev_record->net_votes(), prev_record->id ) ); } } } } FC_CAPTURE_AND_RETHROW( (id) ) } } } // bts::blockchain
Tweak account_record invariants
Tweak account_record invariants
C++
unlicense
bitshares/bitshares-0.x,bitshares/devshares,camponez/bitshares,dacsunlimited/dac_play,camponez/bitshares,frrp/bitshares,dacsunlimited/dac_play,FollowMyVote/bitshares,bitshares/bitshares-0.x,bitsuperlab/cpp-play,jakeporter/Bitshares,RemitaBit/Remitabit,dacsunlimited/dac_play,dacsunlimited/dac_play,bitshares/bitshares-0.x,camponez/bitshares,bitshares/devshares,frrp/bitshares,jakeporter/Bitshares,bitshares/bitshares,bitsuperlab/cpp-play,bitsuperlab/cpp-play,RemitaBit/Remitabit,bitshares/bitshares,bitshares/bitshares-0.x,FollowMyVote/bitshares,dacsunlimited/dac_play,bitshares/bitshares-0.x,FollowMyVote/bitshares,RemitaBit/Remitabit,camponez/bitshares,frrp/bitshares,FollowMyVote/bitshares,FollowMyVote/bitshares,bitsuperlab/cpp-play,jakeporter/Bitshares,jakeporter/Bitshares,camponez/bitshares,bitsuperlab/cpp-play,jakeporter/Bitshares,bitshares/devshares,bitshares/bitshares,camponez/bitshares,bitshares/bitshares,frrp/bitshares,bitsuperlab/cpp-play,jakeporter/Bitshares,RemitaBit/Remitabit,frrp/bitshares,bitshares/devshares,FollowMyVote/bitshares,RemitaBit/Remitabit,bitshares/devshares,RemitaBit/Remitabit,bitshares/bitshares-0.x,frrp/bitshares,dacsunlimited/dac_play,bitshares/bitshares,bitshares/bitshares,bitshares/devshares
7e6f1b3f0008d03e6cdfa186b8f9976570865d4e
libsolidity/codegen/CompilerContext.cpp
libsolidity/codegen/CompilerContext.cpp
/* This file is part of solidity. solidity 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. solidity 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 solidity. If not, see <http://www.gnu.org/licenses/>. */ /** * @author Christian <[email protected]> * @date 2014 * Utilities for the solidity compiler. */ #include <libsolidity/codegen/CompilerContext.h> #include <libsolidity/codegen/CompilerUtils.h> #include <libsolidity/ast/AST.h> #include <libsolidity/codegen/Compiler.h> #include <libsolidity/interface/Version.h> #include <libsolidity/inlineasm/AsmData.h> #include <libsolidity/inlineasm/AsmStack.h> #include <boost/algorithm/string/replace.hpp> #include <utility> #include <numeric> using namespace std; namespace dev { namespace solidity { void CompilerContext::addMagicGlobal(MagicVariableDeclaration const& _declaration) { m_magicGlobals.insert(&_declaration); } void CompilerContext::addStateVariable( VariableDeclaration const& _declaration, u256 const& _storageOffset, unsigned _byteOffset ) { m_stateVariables[&_declaration] = make_pair(_storageOffset, _byteOffset); } void CompilerContext::startFunction(Declaration const& _function) { m_functionCompilationQueue.startFunction(_function); *this << functionEntryLabel(_function); } void CompilerContext::callLowLevelFunction( string const& _name, unsigned _inArgs, unsigned _outArgs, function<void(CompilerContext&)> const& _generator ) { eth::AssemblyItem retTag = pushNewTag(); CompilerUtils(*this).moveIntoStack(_inArgs); auto it = m_lowLevelFunctions.find(_name); if (it == m_lowLevelFunctions.end()) { eth::AssemblyItem tag = newTag().pushTag(); m_lowLevelFunctions.insert(make_pair(_name, tag)); m_lowLevelFunctionGenerationQueue.push(make_tuple(_name, _inArgs, _outArgs, _generator)); *this << tag; } else *this << it->second; appendJump(eth::AssemblyItem::JumpType::IntoFunction); adjustStackOffset(_outArgs - 1 - _inArgs); *this << retTag.tag(); } void CompilerContext::appendMissingLowLevelFunctions() { while (!m_lowLevelFunctionGenerationQueue.empty()) { string name; unsigned inArgs; unsigned outArgs; function<void(CompilerContext&)> generator; tie(name, inArgs, outArgs, generator) = m_lowLevelFunctionGenerationQueue.front(); m_lowLevelFunctionGenerationQueue.pop(); setStackOffset(inArgs + 1); *this << m_lowLevelFunctions.at(name).tag(); generator(*this); CompilerUtils(*this).moveToStackTop(outArgs); appendJump(eth::AssemblyItem::JumpType::OutOfFunction); solAssert(stackHeight() == outArgs, "Invalid stack height in low-level function " + name + "."); } } void CompilerContext::addVariable(VariableDeclaration const& _declaration, unsigned _offsetToCurrent) { solAssert(m_asm->deposit() >= 0 && unsigned(m_asm->deposit()) >= _offsetToCurrent, ""); m_localVariables[&_declaration] = unsigned(m_asm->deposit()) - _offsetToCurrent; } void CompilerContext::removeVariable(VariableDeclaration const& _declaration) { solAssert(!!m_localVariables.count(&_declaration), ""); m_localVariables.erase(&_declaration); } eth::Assembly const& CompilerContext::compiledContract(const ContractDefinition& _contract) const { auto ret = m_compiledContracts.find(&_contract); solAssert(ret != m_compiledContracts.end(), "Compiled contract not found."); return *ret->second; } bool CompilerContext::isLocalVariable(Declaration const* _declaration) const { return !!m_localVariables.count(_declaration); } eth::AssemblyItem CompilerContext::functionEntryLabel(Declaration const& _declaration) { return m_functionCompilationQueue.entryLabel(_declaration, *this); } eth::AssemblyItem CompilerContext::functionEntryLabelIfExists(Declaration const& _declaration) const { return m_functionCompilationQueue.entryLabelIfExists(_declaration); } FunctionDefinition const& CompilerContext::resolveVirtualFunction(FunctionDefinition const& _function) { // Libraries do not allow inheritance and their functions can be inlined, so we should not // search the inheritance hierarchy (which will be the wrong one in case the function // is inlined). if (auto scope = dynamic_cast<ContractDefinition const*>(_function.scope())) if (scope->isLibrary()) return _function; solAssert(!m_inheritanceHierarchy.empty(), "No inheritance hierarchy set."); return resolveVirtualFunction(_function, m_inheritanceHierarchy.begin()); } FunctionDefinition const& CompilerContext::superFunction(FunctionDefinition const& _function, ContractDefinition const& _base) { solAssert(!m_inheritanceHierarchy.empty(), "No inheritance hierarchy set."); return resolveVirtualFunction(_function, superContract(_base)); } FunctionDefinition const* CompilerContext::nextConstructor(ContractDefinition const& _contract) const { vector<ContractDefinition const*>::const_iterator it = superContract(_contract); for (; it != m_inheritanceHierarchy.end(); ++it) if ((*it)->constructor()) return (*it)->constructor(); return nullptr; } Declaration const* CompilerContext::nextFunctionToCompile() const { return m_functionCompilationQueue.nextFunctionToCompile(); } ModifierDefinition const& CompilerContext::functionModifier(string const& _name) const { solAssert(!m_inheritanceHierarchy.empty(), "No inheritance hierarchy set."); for (ContractDefinition const* contract: m_inheritanceHierarchy) for (ModifierDefinition const* modifier: contract->functionModifiers()) if (modifier->name() == _name) return *modifier; BOOST_THROW_EXCEPTION(InternalCompilerError() << errinfo_comment("Function modifier " + _name + " not found.")); } unsigned CompilerContext::baseStackOffsetOfVariable(Declaration const& _declaration) const { auto res = m_localVariables.find(&_declaration); solAssert(res != m_localVariables.end(), "Variable not found on stack."); return res->second; } unsigned CompilerContext::baseToCurrentStackOffset(unsigned _baseOffset) const { return m_asm->deposit() - _baseOffset - 1; } unsigned CompilerContext::currentToBaseStackOffset(unsigned _offset) const { return m_asm->deposit() - _offset - 1; } pair<u256, unsigned> CompilerContext::storageLocationOfVariable(const Declaration& _declaration) const { auto it = m_stateVariables.find(&_declaration); solAssert(it != m_stateVariables.end(), "Variable not found in storage."); return it->second; } CompilerContext& CompilerContext::appendJump(eth::AssemblyItem::JumpType _jumpType) { eth::AssemblyItem item(Instruction::JUMP); item.setJumpType(_jumpType); return *this << item; } void CompilerContext::resetVisitedNodes(ASTNode const* _node) { stack<ASTNode const*> newStack; newStack.push(_node); std::swap(m_visitedNodes, newStack); updateSourceLocation(); } void CompilerContext::appendInlineAssembly( string const& _assembly, vector<string> const& _localVariables, map<string, string> const& _replacements ) { string replacedAssembly; string const* assembly = &_assembly; if (!_replacements.empty()) { replacedAssembly = _assembly; for (auto const& replacement: _replacements) replacedAssembly = boost::algorithm::replace_all_copy(replacedAssembly, replacement.first, replacement.second); assembly = &replacedAssembly; } unsigned startStackHeight = stackHeight(); auto identifierAccess = [&]( assembly::Identifier const& _identifier, eth::Assembly& _assembly, assembly::CodeGenerator::IdentifierContext _context ) { auto it = std::find(_localVariables.begin(), _localVariables.end(), _identifier.name); if (it == _localVariables.end()) return false; unsigned stackDepth = _localVariables.end() - it; int stackDiff = _assembly.deposit() - startStackHeight + stackDepth; if (_context == assembly::CodeGenerator::IdentifierContext::LValue) stackDiff -= 1; if (stackDiff < 1 || stackDiff > 16) BOOST_THROW_EXCEPTION( CompilerError() << errinfo_comment("Stack too deep, try removing local variables.") ); if (_context == assembly::CodeGenerator::IdentifierContext::RValue) _assembly.append(dupInstruction(stackDiff)); else { _assembly.append(swapInstruction(stackDiff)); _assembly.append(Instruction::POP); } return true; }; solAssert(assembly::InlineAssemblyStack().parseAndAssemble(*assembly, *m_asm, identifierAccess), "Failed to assemble inline assembly block."); } FunctionDefinition const& CompilerContext::resolveVirtualFunction( FunctionDefinition const& _function, vector<ContractDefinition const*>::const_iterator _searchStart ) { string name = _function.name(); FunctionType functionType(_function); auto it = _searchStart; for (; it != m_inheritanceHierarchy.end(); ++it) for (FunctionDefinition const* function: (*it)->definedFunctions()) if ( function->name() == name && !function->isConstructor() && FunctionType(*function).hasEqualArgumentTypes(functionType) ) return *function; solAssert(false, "Super function " + name + " not found."); return _function; // not reached } vector<ContractDefinition const*>::const_iterator CompilerContext::superContract(ContractDefinition const& _contract) const { solAssert(!m_inheritanceHierarchy.empty(), "No inheritance hierarchy set."); auto it = find(m_inheritanceHierarchy.begin(), m_inheritanceHierarchy.end(), &_contract); solAssert(it != m_inheritanceHierarchy.end(), "Base not found in inheritance hierarchy."); return ++it; } void CompilerContext::updateSourceLocation() { m_asm->setSourceLocation(m_visitedNodes.empty() ? SourceLocation() : m_visitedNodes.top()->location()); } eth::AssemblyItem CompilerContext::FunctionCompilationQueue::entryLabel( Declaration const& _declaration, CompilerContext& _context ) { auto res = m_entryLabels.find(&_declaration); if (res == m_entryLabels.end()) { eth::AssemblyItem tag(_context.newTag()); m_entryLabels.insert(make_pair(&_declaration, tag)); m_functionsToCompile.push(&_declaration); return tag.tag(); } else return res->second.tag(); } eth::AssemblyItem CompilerContext::FunctionCompilationQueue::entryLabelIfExists(Declaration const& _declaration) const { auto res = m_entryLabels.find(&_declaration); return res == m_entryLabels.end() ? eth::AssemblyItem(eth::UndefinedItem) : res->second.tag(); } Declaration const* CompilerContext::FunctionCompilationQueue::nextFunctionToCompile() const { while (!m_functionsToCompile.empty()) { if (m_alreadyCompiledFunctions.count(m_functionsToCompile.front())) m_functionsToCompile.pop(); else return m_functionsToCompile.front(); } return nullptr; } void CompilerContext::FunctionCompilationQueue::startFunction(Declaration const& _function) { if (!m_functionsToCompile.empty() && m_functionsToCompile.front() == &_function) m_functionsToCompile.pop(); m_alreadyCompiledFunctions.insert(&_function); } } }
/* This file is part of solidity. solidity 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. solidity 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 solidity. If not, see <http://www.gnu.org/licenses/>. */ /** * @author Christian <[email protected]> * @date 2014 * Utilities for the solidity compiler. */ #include <libsolidity/codegen/CompilerContext.h> #include <libsolidity/codegen/CompilerUtils.h> #include <libsolidity/ast/AST.h> #include <libsolidity/codegen/Compiler.h> #include <libsolidity/interface/Version.h> #include <libsolidity/inlineasm/AsmData.h> #include <libsolidity/inlineasm/AsmStack.h> #include <boost/algorithm/string/replace.hpp> #include <utility> #include <numeric> using namespace std; namespace dev { namespace solidity { void CompilerContext::addMagicGlobal(MagicVariableDeclaration const& _declaration) { m_magicGlobals.insert(&_declaration); } void CompilerContext::addStateVariable( VariableDeclaration const& _declaration, u256 const& _storageOffset, unsigned _byteOffset ) { m_stateVariables[&_declaration] = make_pair(_storageOffset, _byteOffset); } void CompilerContext::startFunction(Declaration const& _function) { m_functionCompilationQueue.startFunction(_function); *this << functionEntryLabel(_function); } void CompilerContext::callLowLevelFunction( string const& _name, unsigned _inArgs, unsigned _outArgs, function<void(CompilerContext&)> const& _generator ) { eth::AssemblyItem retTag = pushNewTag(); CompilerUtils(*this).moveIntoStack(_inArgs); auto it = m_lowLevelFunctions.find(_name); if (it == m_lowLevelFunctions.end()) { eth::AssemblyItem tag = newTag().pushTag(); m_lowLevelFunctions.insert(make_pair(_name, tag)); m_lowLevelFunctionGenerationQueue.push(make_tuple(_name, _inArgs, _outArgs, _generator)); *this << tag; } else *this << it->second; appendJump(eth::AssemblyItem::JumpType::IntoFunction); adjustStackOffset(int(_outArgs) - 1 - _inArgs); *this << retTag.tag(); } void CompilerContext::appendMissingLowLevelFunctions() { while (!m_lowLevelFunctionGenerationQueue.empty()) { string name; unsigned inArgs; unsigned outArgs; function<void(CompilerContext&)> generator; tie(name, inArgs, outArgs, generator) = m_lowLevelFunctionGenerationQueue.front(); m_lowLevelFunctionGenerationQueue.pop(); setStackOffset(inArgs + 1); *this << m_lowLevelFunctions.at(name).tag(); generator(*this); CompilerUtils(*this).moveToStackTop(outArgs); appendJump(eth::AssemblyItem::JumpType::OutOfFunction); solAssert(stackHeight() == outArgs, "Invalid stack height in low-level function " + name + "."); } } void CompilerContext::addVariable(VariableDeclaration const& _declaration, unsigned _offsetToCurrent) { solAssert(m_asm->deposit() >= 0 && unsigned(m_asm->deposit()) >= _offsetToCurrent, ""); m_localVariables[&_declaration] = unsigned(m_asm->deposit()) - _offsetToCurrent; } void CompilerContext::removeVariable(VariableDeclaration const& _declaration) { solAssert(!!m_localVariables.count(&_declaration), ""); m_localVariables.erase(&_declaration); } eth::Assembly const& CompilerContext::compiledContract(const ContractDefinition& _contract) const { auto ret = m_compiledContracts.find(&_contract); solAssert(ret != m_compiledContracts.end(), "Compiled contract not found."); return *ret->second; } bool CompilerContext::isLocalVariable(Declaration const* _declaration) const { return !!m_localVariables.count(_declaration); } eth::AssemblyItem CompilerContext::functionEntryLabel(Declaration const& _declaration) { return m_functionCompilationQueue.entryLabel(_declaration, *this); } eth::AssemblyItem CompilerContext::functionEntryLabelIfExists(Declaration const& _declaration) const { return m_functionCompilationQueue.entryLabelIfExists(_declaration); } FunctionDefinition const& CompilerContext::resolveVirtualFunction(FunctionDefinition const& _function) { // Libraries do not allow inheritance and their functions can be inlined, so we should not // search the inheritance hierarchy (which will be the wrong one in case the function // is inlined). if (auto scope = dynamic_cast<ContractDefinition const*>(_function.scope())) if (scope->isLibrary()) return _function; solAssert(!m_inheritanceHierarchy.empty(), "No inheritance hierarchy set."); return resolveVirtualFunction(_function, m_inheritanceHierarchy.begin()); } FunctionDefinition const& CompilerContext::superFunction(FunctionDefinition const& _function, ContractDefinition const& _base) { solAssert(!m_inheritanceHierarchy.empty(), "No inheritance hierarchy set."); return resolveVirtualFunction(_function, superContract(_base)); } FunctionDefinition const* CompilerContext::nextConstructor(ContractDefinition const& _contract) const { vector<ContractDefinition const*>::const_iterator it = superContract(_contract); for (; it != m_inheritanceHierarchy.end(); ++it) if ((*it)->constructor()) return (*it)->constructor(); return nullptr; } Declaration const* CompilerContext::nextFunctionToCompile() const { return m_functionCompilationQueue.nextFunctionToCompile(); } ModifierDefinition const& CompilerContext::functionModifier(string const& _name) const { solAssert(!m_inheritanceHierarchy.empty(), "No inheritance hierarchy set."); for (ContractDefinition const* contract: m_inheritanceHierarchy) for (ModifierDefinition const* modifier: contract->functionModifiers()) if (modifier->name() == _name) return *modifier; BOOST_THROW_EXCEPTION(InternalCompilerError() << errinfo_comment("Function modifier " + _name + " not found.")); } unsigned CompilerContext::baseStackOffsetOfVariable(Declaration const& _declaration) const { auto res = m_localVariables.find(&_declaration); solAssert(res != m_localVariables.end(), "Variable not found on stack."); return res->second; } unsigned CompilerContext::baseToCurrentStackOffset(unsigned _baseOffset) const { return m_asm->deposit() - _baseOffset - 1; } unsigned CompilerContext::currentToBaseStackOffset(unsigned _offset) const { return m_asm->deposit() - _offset - 1; } pair<u256, unsigned> CompilerContext::storageLocationOfVariable(const Declaration& _declaration) const { auto it = m_stateVariables.find(&_declaration); solAssert(it != m_stateVariables.end(), "Variable not found in storage."); return it->second; } CompilerContext& CompilerContext::appendJump(eth::AssemblyItem::JumpType _jumpType) { eth::AssemblyItem item(Instruction::JUMP); item.setJumpType(_jumpType); return *this << item; } void CompilerContext::resetVisitedNodes(ASTNode const* _node) { stack<ASTNode const*> newStack; newStack.push(_node); std::swap(m_visitedNodes, newStack); updateSourceLocation(); } void CompilerContext::appendInlineAssembly( string const& _assembly, vector<string> const& _localVariables, map<string, string> const& _replacements ) { string replacedAssembly; string const* assembly = &_assembly; if (!_replacements.empty()) { replacedAssembly = _assembly; for (auto const& replacement: _replacements) replacedAssembly = boost::algorithm::replace_all_copy(replacedAssembly, replacement.first, replacement.second); assembly = &replacedAssembly; } unsigned startStackHeight = stackHeight(); auto identifierAccess = [&]( assembly::Identifier const& _identifier, eth::Assembly& _assembly, assembly::CodeGenerator::IdentifierContext _context ) { auto it = std::find(_localVariables.begin(), _localVariables.end(), _identifier.name); if (it == _localVariables.end()) return false; unsigned stackDepth = _localVariables.end() - it; int stackDiff = _assembly.deposit() - startStackHeight + stackDepth; if (_context == assembly::CodeGenerator::IdentifierContext::LValue) stackDiff -= 1; if (stackDiff < 1 || stackDiff > 16) BOOST_THROW_EXCEPTION( CompilerError() << errinfo_comment("Stack too deep, try removing local variables.") ); if (_context == assembly::CodeGenerator::IdentifierContext::RValue) _assembly.append(dupInstruction(stackDiff)); else { _assembly.append(swapInstruction(stackDiff)); _assembly.append(Instruction::POP); } return true; }; solAssert(assembly::InlineAssemblyStack().parseAndAssemble(*assembly, *m_asm, identifierAccess), "Failed to assemble inline assembly block."); } FunctionDefinition const& CompilerContext::resolveVirtualFunction( FunctionDefinition const& _function, vector<ContractDefinition const*>::const_iterator _searchStart ) { string name = _function.name(); FunctionType functionType(_function); auto it = _searchStart; for (; it != m_inheritanceHierarchy.end(); ++it) for (FunctionDefinition const* function: (*it)->definedFunctions()) if ( function->name() == name && !function->isConstructor() && FunctionType(*function).hasEqualArgumentTypes(functionType) ) return *function; solAssert(false, "Super function " + name + " not found."); return _function; // not reached } vector<ContractDefinition const*>::const_iterator CompilerContext::superContract(ContractDefinition const& _contract) const { solAssert(!m_inheritanceHierarchy.empty(), "No inheritance hierarchy set."); auto it = find(m_inheritanceHierarchy.begin(), m_inheritanceHierarchy.end(), &_contract); solAssert(it != m_inheritanceHierarchy.end(), "Base not found in inheritance hierarchy."); return ++it; } void CompilerContext::updateSourceLocation() { m_asm->setSourceLocation(m_visitedNodes.empty() ? SourceLocation() : m_visitedNodes.top()->location()); } eth::AssemblyItem CompilerContext::FunctionCompilationQueue::entryLabel( Declaration const& _declaration, CompilerContext& _context ) { auto res = m_entryLabels.find(&_declaration); if (res == m_entryLabels.end()) { eth::AssemblyItem tag(_context.newTag()); m_entryLabels.insert(make_pair(&_declaration, tag)); m_functionsToCompile.push(&_declaration); return tag.tag(); } else return res->second.tag(); } eth::AssemblyItem CompilerContext::FunctionCompilationQueue::entryLabelIfExists(Declaration const& _declaration) const { auto res = m_entryLabels.find(&_declaration); return res == m_entryLabels.end() ? eth::AssemblyItem(eth::UndefinedItem) : res->second.tag(); } Declaration const* CompilerContext::FunctionCompilationQueue::nextFunctionToCompile() const { while (!m_functionsToCompile.empty()) { if (m_alreadyCompiledFunctions.count(m_functionsToCompile.front())) m_functionsToCompile.pop(); else return m_functionsToCompile.front(); } return nullptr; } void CompilerContext::FunctionCompilationQueue::startFunction(Declaration const& _function) { if (!m_functionsToCompile.empty() && m_functionsToCompile.front() == &_function) m_functionsToCompile.pop(); m_alreadyCompiledFunctions.insert(&_function); } } }
Use int arithmetics for stack adjustment.
Use int arithmetics for stack adjustment.
C++
mit
ruchevits/solidity,ruchevits/solidity,ruchevits/solidity,ruchevits/solidity
d3b612e43c3003159599d640fed226e0ad85499c
src/database.cc
src/database.cc
/* * Copyright deipi.com LLC and contributors. 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. */ #include "utils.h" #include "database.h" #include <xapian/dbfactory.h> Database::Database(Endpoints &endpoints_, bool writable_) : endpoints(endpoints_), writable(writable_) { hash = endpoints.hash(writable); reopen(); } void Database::reopen() { // FIXME: Handle remote endpoints and figure out if the endpoint is a local database const Endpoint *e; if (writable) { db = new Xapian::WritableDatabase(); if (endpoints.size() != 1) { LOG_ERR(this, "ERROR: Expecting exactly one database."); } else { e = &endpoints[0]; if (e->protocol == "file") { db->add_database(Xapian::WritableDatabase(e->path, Xapian::DB_CREATE_OR_OPEN)); } else { db->add_database(Xapian::Remote::open_writable(e->host, e->port, 0, 10000, e->path)); } } } else { db = new Xapian::Database(); std::vector<Endpoint>::const_iterator i(endpoints.begin()); for (; i != endpoints.end(); ++i) { e = &(*i); if (e->protocol == "file") { db->add_database(Xapian::Database(e->path, Xapian::DB_CREATE_OR_OPEN)); } else { db->add_database(Xapian::Remote::open(e->host, e->port, 0, 10000, e->path)); } } } } Database::~Database() { delete db; } DatabaseQueue::DatabaseQueue() : count(0) { } DatabaseQueue::~DatabaseQueue() { while (!empty()) { Database *database; if (pop(database)) { delete database; } } } DatabasePool::DatabasePool() : finished(false) { pthread_mutexattr_init(&qmtx_attr); pthread_mutexattr_settype(&qmtx_attr, PTHREAD_MUTEX_RECURSIVE); pthread_mutex_init(&qmtx, &qmtx_attr); } DatabasePool::~DatabasePool() { finish(); pthread_mutex_destroy(&qmtx); pthread_mutexattr_destroy(&qmtx_attr); } void DatabasePool::finish() { pthread_mutex_lock(&qmtx); finished = true; pthread_mutex_unlock(&qmtx); } bool DatabasePool::checkout(Database **database, Endpoints &endpoints, bool writable) { Database *database_ = NULL; pthread_mutex_lock(&qmtx); if (!finished && *database == NULL) { size_t hash = endpoints.hash(writable); DatabaseQueue &queue = databases[hash]; if (!queue.pop(database_, 0)) { if (!writable || queue.count == 0) { queue.count++; pthread_mutex_unlock(&qmtx); database_ = new Database(endpoints, writable); pthread_mutex_lock(&qmtx); } // FIXME: lock until a database is available if it can't get one } *database = database_; } pthread_mutex_unlock(&qmtx); LOG_DATABASE(this, "+ CHECKOUT DB %lx\n", (unsigned long)*database); return database_ != NULL; } void DatabasePool::checkin(Database **database) { LOG_DATABASE(this, "- CHECKIN DB %lx\n", (unsigned long)*database); pthread_mutex_lock(&qmtx); DatabaseQueue &queue = databases[(*database)->hash]; queue.push(*database); *database = NULL; pthread_mutex_unlock(&qmtx); }
/* * Copyright deipi.com LLC and contributors. 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. */ #include "utils.h" #include "database.h" #include <xapian/dbfactory.h> Database::Database(Endpoints &endpoints_, bool writable_) : endpoints(endpoints_), writable(writable_) { hash = endpoints.hash(writable); reopen(); } void Database::reopen() { // FIXME: Handle remote endpoints and figure out if the endpoint is a local database const Endpoint *e; if (writable) { db = new Xapian::WritableDatabase(); if (endpoints.size() != 1) { LOG_ERR(this, "ERROR: Expecting exactly one database, %d requested: %s", endpoints.size(), endpoints.as_string().c_str()); } else { e = &endpoints[0]; if (e->protocol == "file") { db->add_database(Xapian::WritableDatabase(e->path, Xapian::DB_CREATE_OR_OPEN)); } else { db->add_database(Xapian::Remote::open_writable(e->host, e->port, 0, 10000, e->path)); } } } else { db = new Xapian::Database(); std::vector<Endpoint>::const_iterator i(endpoints.begin()); for (; i != endpoints.end(); ++i) { e = &(*i); if (e->protocol == "file") { db->add_database(Xapian::Database(e->path, Xapian::DB_CREATE_OR_OPEN)); } else { db->add_database(Xapian::Remote::open(e->host, e->port, 0, 10000, e->path)); } } } } Database::~Database() { delete db; } DatabaseQueue::DatabaseQueue() : count(0) { } DatabaseQueue::~DatabaseQueue() { while (!empty()) { Database *database; if (pop(database)) { delete database; } } } DatabasePool::DatabasePool() : finished(false) { pthread_mutexattr_init(&qmtx_attr); pthread_mutexattr_settype(&qmtx_attr, PTHREAD_MUTEX_RECURSIVE); pthread_mutex_init(&qmtx, &qmtx_attr); } DatabasePool::~DatabasePool() { finish(); pthread_mutex_destroy(&qmtx); pthread_mutexattr_destroy(&qmtx_attr); } void DatabasePool::finish() { pthread_mutex_lock(&qmtx); finished = true; pthread_mutex_unlock(&qmtx); } bool DatabasePool::checkout(Database **database, Endpoints &endpoints, bool writable) { Database *database_ = NULL; pthread_mutex_lock(&qmtx); if (!finished && *database == NULL) { size_t hash = endpoints.hash(writable); DatabaseQueue &queue = databases[hash]; if (!queue.pop(database_, 0)) { if (!writable || queue.count == 0) { queue.count++; pthread_mutex_unlock(&qmtx); database_ = new Database(endpoints, writable); pthread_mutex_lock(&qmtx); } // FIXME: lock until a database is available if it can't get one } *database = database_; } pthread_mutex_unlock(&qmtx); LOG_DATABASE(this, "+ CHECKOUT DB %lx\n", (unsigned long)*database); return database_ != NULL; } void DatabasePool::checkin(Database **database) { LOG_DATABASE(this, "- CHECKIN DB %lx\n", (unsigned long)*database); pthread_mutex_lock(&qmtx); DatabaseQueue &queue = databases[(*database)->hash]; queue.push(*database); *database = NULL; pthread_mutex_unlock(&qmtx); }
Print number of requested endpoints and endpoints on error
Print number of requested endpoints and endpoints on error
C++
mit
Kronuz/Xapiand,Kronuz/Xapiand,Kronuz/Xapiand,Kronuz/Xapiand,Kronuz/Xapiand,Kronuz/Xapiand
15897fb21f04630affc47187635324358632d458
source/xmlrpc.cpp
source/xmlrpc.cpp
#include "xmlrpc.h" #include <QMap> #include <QVariant> #include <QDateTime> #include <QStringList> #include <QTextStream> XMLRPC::RequestMessage::RequestMessage( const QByteArray &method, const QList<QVariant> &args ) : MessageBase() { m_method = method; m_args = args; } XMLRPC::RequestMessage::RequestMessage( const QByteArray &method, const QVariant &arg ) : MessageBase() { m_method = method; m_args.append(arg); } void XMLRPC::RequestMessage::writeXml( QXmlStreamWriter *writer ) const { writer->writeStartElement("methodCall"); writer->writeTextElement("methodName", m_method ); if( !m_args.isEmpty() ) { writer->writeStartElement("params"); foreach( QVariant arg, m_args) { writer->writeStartElement("param"); marshall( writer, arg ); writer->writeEndElement(); } writer->writeEndElement(); } writer->writeEndElement(); } QByteArray XMLRPC::RequestMessage::xml() const { if( m_method.isEmpty() ) return QByteArray(); QByteArray returnXML; QXmlStreamWriter writer( &returnXML ); writer.writeStartDocument(); writeXml(&writer ); writer.writeEndDocument(); return returnXML; } void XMLRPC::MessageBase::marshall( QXmlStreamWriter *writer, const QVariant &value ) const { writer->writeStartElement("value"); switch( value.type() ) { case QVariant::Int: case QVariant::UInt: case QVariant::LongLong: case QVariant::ULongLong: writer->writeTextElement("i4", value.toString()); break; case QVariant::Double: writer->writeTextElement("double", value.toString()); break; case QVariant::Bool: writer->writeTextElement("boolean", (value.toBool()?"true":"false") ); break; case QVariant::Date: writer->writeTextElement("dateTime.iso8601", value.toDate().toString( Qt::ISODate ) ); break; case QVariant::DateTime: writer->writeTextElement("dateTime.iso8601", value.toDateTime().toString( Qt::ISODate ) ); break; case QVariant::Time: writer->writeTextElement("dateTime.iso8601", value.toTime().toString( Qt::ISODate ) ); break; case QVariant::StringList: case QVariant::List: { writer->writeStartElement("array"); writer->writeStartElement("data"); foreach( QVariant item, value.toList() ) marshall( writer, item ); writer->writeEndElement(); writer->writeEndElement(); break; } case QVariant::Map: { writer->writeStartElement("struct"); QMap<QString, QVariant> map = value.toMap(); QMap<QString, QVariant>::ConstIterator index = map.begin(); while( index != map.end() ) { writer->writeStartElement("member"); writer->writeTextElement("name", index.key()); marshall( writer, *index ); writer->writeEndElement(); ++index; } writer->writeEndElement(); break; } case QVariant::ByteArray: { writer->writeTextElement("base64", value.toByteArray().toBase64() ); break; } default: { if( value.canConvert(QVariant::String) ) { writer->writeTextElement( "string", value.toString() ); } else { } break; } } writer->writeEndElement(); } XMLRPC::ResponseMessage::ResponseMessage( const QDomElement &element ) { const QDomElement contents = element.firstChild().toElement(); if( contents.tagName().toLower() == "params") { QDomNode param = contents.firstChild(); while( !param.isNull() && isValid() ) { m_values.append( demarshall( param.firstChild().toElement() ) ); param = param.nextSibling(); } } else if( contents.tagName().toLower() == "fault") { const QDomElement errElement = contents.firstChild().toElement(); const QVariant error = demarshall( errElement ); setError( QString("XMLRPC Fault %1: %2") .arg(error.toMap()["faultCode"].toString() ) .arg(error.toMap()["faultString"].toString() ) ); } else { setError("Bad XML response"); } } XMLRPC::ResponseMessage::ResponseMessage( const QByteArray &xml ) : MessageBase() { QDomDocument message; QString xmlErrMsg; int xmlErrLine; int xmlErrCol; if( message.setContent(xml, &xmlErrMsg, &xmlErrLine, &xmlErrCol) ) { const QDomElement contents = message.documentElement().firstChild().toElement(); if( contents.tagName().toLower() == "params") { QDomNode param = contents.firstChild(); while( !param.isNull() && isValid() ) { m_values.append( demarshall( param.firstChild().toElement() ) ); param = param.nextSibling(); } } else if( message.documentElement().firstChild().toElement().tagName().toLower() == "fault") { const QDomElement errElement = contents.firstChild().toElement(); const QVariant error = demarshall( errElement ); setError( QString("XMLRPC Fault %1: %2") .arg(error.toMap()["faultCode"].toString() ) .arg(error.toMap()["faultString"].toString() ) ); } else { setError("Bad XML response"); } } else { setError(QString( "XML Error: %1 at row %2 and col %3") .arg(xmlErrMsg).arg(xmlErrLine).arg(xmlErrCol)); } } int XMLRPC::ResponseMessage::count() const { return m_values.count(); } QVariant XMLRPC::ResponseMessage::value( int index) const { return m_values[index]; } bool XMLRPC::MessageBase::isValid() const { return m_valid; } QString XMLRPC::MessageBase::error() const { return m_message; } QVariant XMLRPC::MessageBase::demarshall( const QDomElement &elem ) const { if ( elem.tagName().toLower() != "value" ) { m_valid = false; m_message = "bad param value"; return QVariant(); } if ( !elem.firstChild().isElement() ) { return QVariant( elem.text() ); } const QDomElement typeData = elem.firstChild().toElement(); const QString typeName = typeData.tagName().toLower(); if ( typeName == "string" ) return QVariant( typeData.text() ); else if (typeName == "int" || typeName == "i4" ) { bool ok = false; QVariant val( typeData.text().toInt( &ok ) ); if( ok ) return val; m_message = "I was looking for an integer but data was courupt"; } else if( typeName == "double" ) { bool ok = false; QVariant val( typeData.text().toDouble( &ok ) ); if( ok ) return val; m_message = "I was looking for an double but data was courupt"; } else if( typeName == "boolean" ) return QVariant( ( typeData.text().toLower() == "true" || typeData.text() == "1")?true:false ); else if( typeName == "datetime" || typeName == "dateTime.iso8601" ) return QVariant( QDateTime::fromString( typeData.text(), Qt::ISODate ) ); else if( typeName == "array" ) { QList<QVariant> arr; QDomNode valueNode = typeData.firstChild().firstChild(); while( !valueNode.isNull() && m_valid ) { arr.append( demarshall( valueNode.toElement() ) ); valueNode = valueNode.nextSibling(); } return QVariant( arr ); } else if( typeName == "struct" ) { QMap<QString,QVariant> stct; QDomNode valueNode = typeData.firstChild(); while( !valueNode.isNull() && m_valid ) { const QDomElement memberNode = valueNode.toElement().elementsByTagName("name").item(0).toElement(); const QDomElement dataNode = valueNode.toElement().elementsByTagName("value").item(0).toElement(); stct[ memberNode.text() ] = demarshall( dataNode ); valueNode = valueNode.nextSibling(); } return QVariant(stct); } else if( typeName == "base64" ) { QVariant returnVariant; QByteArray dest; QByteArray src = typeData.text().toLatin1(); dest = QByteArray::fromBase64( src ); QDataStream ds(&dest, QIODevice::ReadOnly); ds.setVersion(QDataStream::Qt_4_0); ds >> returnVariant; if( returnVariant.isValid() ) return returnVariant; else return QVariant( dest ); } setError(QString( "Cannot handle type %1").arg(typeName)); return QVariant(); } void XMLRPC::MessageBase::setError( const QString & message ) const { m_valid = false; m_message = message; } XMLRPC::MessageBase::MessageBase( ) : m_valid(true) { } XMLRPC::MessageBase::~MessageBase( ) { } QList< QVariant > XMLRPC::ResponseMessage::values() const { return m_values; } QList< QVariant > XMLRPC::RequestMessage::args() const { return m_args; } QByteArray XMLRPC::RequestMessage::method() const { return m_method; } XMLRPC::RequestMessage::RequestMessage( const QDomElement &element ) { m_args.clear(); m_method.clear(); const QDomElement methodName = element.firstChildElement("methodName"); if( !methodName.isNull() ) { m_method = methodName.text().toLatin1(); } else { setError("Missing methodName property."); return; } const QDomElement methodParams = element.firstChildElement("params"); if( !methodParams.isNull() ) { QDomNode param = methodParams.firstChild(); while( !param.isNull() && isValid() ) { m_args.append( demarshall( param.firstChild().toElement() ) ); param = param.nextSibling(); } } } XMLRPC::RequestMessage::RequestMessage( const QByteArray & xml ) { QDomDocument message; QString xmlErrMsg; int xmlErrLine; int xmlErrCol; m_args.clear(); m_method.clear(); if( message.setContent(xml, &xmlErrMsg, &xmlErrLine, &xmlErrCol) ) { const QDomElement methodCall = message.firstChildElement("methodCall"); if( !methodCall.isNull() ) { const QDomElement methodName = methodCall.firstChildElement("methodName"); if( !methodName.isNull() ) { m_method = methodName.text().toLatin1(); } else { setError("Missing methodName property."); return; } const QDomElement methodParams = methodCall.firstChildElement("params"); if( !methodParams.isNull() ) { QDomNode param = methodParams.firstChild(); while( !param.isNull() && isValid() ) { m_args.append( demarshall( param.firstChild().toElement() ) ); param = param.nextSibling(); } } } else setError("Not a valid methodCall message."); } else { setError(QString( "XML Error: %1 at row %2 and col %3") .arg(xmlErrMsg).arg(xmlErrLine).arg(xmlErrCol)); } } void XMLRPC::ResponseMessage::writeXml( QXmlStreamWriter *writer ) const { writer->writeStartElement("methodResponse"); if( !m_values.isEmpty() ) { writer->writeStartElement("params"); foreach( QVariant arg, m_values) { writer->writeStartElement("params"); marshall( writer, arg ); writer->writeEndElement(); } writer->writeEndElement(); } writer->writeEndElement(); } QByteArray XMLRPC::ResponseMessage::xml( ) const { QByteArray returnXML ; QXmlStreamWriter writer(&returnXML); writer.writeStartDocument(); writeXml( &writer ); writer.writeEndElement(); writer.writeEndDocument(); return returnXML; } void XMLRPC::ResponseMessage::setValues( const QList< QVariant > vals ) { m_values = vals; } XMLRPC::ResponseMessage::ResponseMessage( const QList< QVariant > & theValue ) : MessageBase(), m_values(theValue) { } XMLRPC::FaultMessage::FaultMessage( int code, const QString & message ) : ResponseMessage(QList<QVariant>() ) { QList<QVariant> args; QMap<QString,QVariant> fault; fault["faultCode"] = code; fault["faultString"] = message; args << fault; setValues(args); } void XMLRPC::FaultMessage::writeXml( QXmlStreamWriter *writer ) const { writer->writeStartElement("fault"); marshall( writer, values().first() ); writer->writeEndElement(); } QByteArray XMLRPC::FaultMessage::xml( ) const { QByteArray returnXML; QXmlStreamWriter writer( &returnXML ); writer.writeStartDocument(); writeXml(&writer); writer.writeEndDocument(); return returnXML; } XMLRPC::ResponseMessage::ResponseMessage( const QVariant & theValue ) : MessageBase() { m_values << theValue; }
#include "xmlrpc.h" #include <QMap> #include <QVariant> #include <QDateTime> #include <QStringList> #include <QTextStream> XMLRPC::RequestMessage::RequestMessage( const QByteArray &method, const QList<QVariant> &args ) : MessageBase() { m_method = method; m_args = args; } XMLRPC::RequestMessage::RequestMessage( const QByteArray &method, const QVariant &arg ) : MessageBase() { m_method = method; m_args.append(arg); } void XMLRPC::RequestMessage::writeXml( QXmlStreamWriter *writer ) const { writer->writeStartElement("methodCall"); writer->writeTextElement("methodName", m_method ); if( !m_args.isEmpty() ) { writer->writeStartElement("params"); foreach( QVariant arg, m_args) { writer->writeStartElement("param"); marshall( writer, arg ); writer->writeEndElement(); } writer->writeEndElement(); } writer->writeEndElement(); } QByteArray XMLRPC::RequestMessage::xml() const { if( m_method.isEmpty() ) return QByteArray(); QByteArray returnXML; QXmlStreamWriter writer( &returnXML ); writer.writeStartDocument(); writeXml(&writer ); writer.writeEndDocument(); return returnXML; } void XMLRPC::MessageBase::marshall( QXmlStreamWriter *writer, const QVariant &value ) const { writer->writeStartElement("value"); switch( value.type() ) { case QVariant::Int: case QVariant::UInt: case QVariant::LongLong: case QVariant::ULongLong: writer->writeTextElement("i4", value.toString()); break; case QVariant::Double: writer->writeTextElement("double", value.toString()); break; case QVariant::Bool: writer->writeTextElement("boolean", (value.toBool()?"true":"false") ); break; case QVariant::Date: writer->writeTextElement("dateTime.iso8601", value.toDate().toString( Qt::ISODate ) ); break; case QVariant::DateTime: writer->writeTextElement("dateTime.iso8601", value.toDateTime().toString( Qt::ISODate ) ); break; case QVariant::Time: writer->writeTextElement("dateTime.iso8601", value.toTime().toString( Qt::ISODate ) ); break; case QVariant::StringList: case QVariant::List: { writer->writeStartElement("array"); writer->writeStartElement("data"); foreach( QVariant item, value.toList() ) marshall( writer, item ); writer->writeEndElement(); writer->writeEndElement(); break; } case QVariant::Map: { writer->writeStartElement("struct"); QMap<QString, QVariant> map = value.toMap(); QMap<QString, QVariant>::ConstIterator index = map.begin(); while( index != map.end() ) { writer->writeStartElement("member"); writer->writeTextElement("name", index.key()); marshall( writer, *index ); writer->writeEndElement(); ++index; } writer->writeEndElement(); break; } case QVariant::ByteArray: { writer->writeTextElement("base64", value.toByteArray().toBase64() ); break; } default: { if( value.canConvert(QVariant::String) ) { writer->writeTextElement( "string", value.toString() ); } else { } break; } } writer->writeEndElement(); } XMLRPC::ResponseMessage::ResponseMessage( const QDomElement &element ) { const QDomElement contents = element.firstChild().toElement(); if( contents.tagName().toLower() == "params") { QDomNode param = contents.firstChild(); while( !param.isNull() && isValid() ) { m_values.append( demarshall( param.firstChild().toElement() ) ); param = param.nextSibling(); } } else if( contents.tagName().toLower() == "fault") { const QDomElement errElement = contents.firstChild().toElement(); const QVariant error = demarshall( errElement ); setError( QString("XMLRPC Fault %1: %2") .arg(error.toMap()["faultCode"].toString() ) .arg(error.toMap()["faultString"].toString() ) ); } else { setError("Bad XML response"); } } XMLRPC::ResponseMessage::ResponseMessage( const QByteArray &xml ) : MessageBase() { QDomDocument message; QString xmlErrMsg; int xmlErrLine; int xmlErrCol; if( message.setContent(xml, &xmlErrMsg, &xmlErrLine, &xmlErrCol) ) { const QDomElement contents = message.documentElement().firstChild().toElement(); if( contents.tagName().toLower() == "params") { QDomNode param = contents.firstChild(); while( !param.isNull() && isValid() ) { m_values.append( demarshall( param.firstChild().toElement() ) ); param = param.nextSibling(); } } else if( message.documentElement().firstChild().toElement().tagName().toLower() == "fault") { const QDomElement errElement = contents.firstChild().toElement(); const QVariant error = demarshall( errElement ); setError( QString("XMLRPC Fault %1: %2") .arg(error.toMap()["faultCode"].toString() ) .arg(error.toMap()["faultString"].toString() ) ); } else { setError("Bad XML response"); } } else { setError(QString( "XML Error: %1 at row %2 and col %3") .arg(xmlErrMsg).arg(xmlErrLine).arg(xmlErrCol)); } } int XMLRPC::ResponseMessage::count() const { return m_values.count(); } QVariant XMLRPC::ResponseMessage::value( int index) const { return m_values[index]; } bool XMLRPC::MessageBase::isValid() const { return m_valid; } QString XMLRPC::MessageBase::error() const { return m_message; } QVariant XMLRPC::MessageBase::demarshall( const QDomElement &elem ) const { if ( elem.tagName().toLower() != "value" ) { m_valid = false; m_message = "bad param value"; return QVariant(); } if ( !elem.firstChild().isElement() ) { return QVariant( elem.text() ); } const QDomElement typeData = elem.firstChild().toElement(); const QString typeName = typeData.tagName().toLower(); if ( typeName == "string" ) return QVariant( typeData.text() ); else if (typeName == "int" || typeName == "i4" ) { bool ok = false; QVariant val( typeData.text().toInt( &ok ) ); if( ok ) return val; m_message = "I was looking for an integer but data was courupt"; } else if( typeName == "double" ) { bool ok = false; QVariant val( typeData.text().toDouble( &ok ) ); if( ok ) return val; m_message = "I was looking for an double but data was courupt"; } else if( typeName == "boolean" ) return QVariant( ( typeData.text().toLower() == "true" || typeData.text() == "1")?true:false ); else if( typeName == "datetime" || typeName == "dateTime.iso8601" ) return QVariant( QDateTime::fromString( typeData.text(), Qt::ISODate ) ); else if( typeName == "array" ) { QList<QVariant> arr; QDomNode valueNode = typeData.firstChild().firstChild(); while( !valueNode.isNull() && m_valid ) { arr.append( demarshall( valueNode.toElement() ) ); valueNode = valueNode.nextSibling(); } return QVariant( arr ); } else if( typeName == "struct" ) { QMap<QString,QVariant> stct; QDomNode valueNode = typeData.firstChild(); while( !valueNode.isNull() && m_valid ) { const QDomElement memberNode = valueNode.toElement().elementsByTagName("name").item(0).toElement(); const QDomElement dataNode = valueNode.toElement().elementsByTagName("value").item(0).toElement(); stct[ memberNode.text() ] = demarshall( dataNode ); valueNode = valueNode.nextSibling(); } return QVariant(stct); } else if( typeName == "base64" ) { QVariant returnVariant; QByteArray dest; QByteArray src = typeData.text().toLatin1(); dest = QByteArray::fromBase64( src ); QDataStream ds(&dest, QIODevice::ReadOnly); ds.setVersion(QDataStream::Qt_4_0); ds >> returnVariant; if( returnVariant.isValid() ) return returnVariant; else return QVariant( dest ); } setError(QString( "Cannot handle type %1").arg(typeName)); return QVariant(); } void XMLRPC::MessageBase::setError( const QString & message ) const { m_valid = false; m_message = message; } XMLRPC::MessageBase::MessageBase( ) : m_valid(true) { } XMLRPC::MessageBase::~MessageBase( ) { } QList< QVariant > XMLRPC::ResponseMessage::values() const { return m_values; } QList< QVariant > XMLRPC::RequestMessage::args() const { return m_args; } QByteArray XMLRPC::RequestMessage::method() const { return m_method; } XMLRPC::RequestMessage::RequestMessage( const QDomElement &element ) { m_args.clear(); m_method.clear(); const QDomElement methodName = element.firstChildElement("methodName"); if( !methodName.isNull() ) { m_method = methodName.text().toLatin1(); } else { setError("Missing methodName property."); return; } const QDomElement methodParams = element.firstChildElement("params"); if( !methodParams.isNull() ) { QDomNode param = methodParams.firstChild(); while( !param.isNull() && isValid() ) { m_args.append( demarshall( param.firstChild().toElement() ) ); param = param.nextSibling(); } } } XMLRPC::RequestMessage::RequestMessage( const QByteArray & xml ) { QDomDocument message; QString xmlErrMsg; int xmlErrLine; int xmlErrCol; m_args.clear(); m_method.clear(); if( message.setContent(xml, &xmlErrMsg, &xmlErrLine, &xmlErrCol) ) { const QDomElement methodCall = message.firstChildElement("methodCall"); if( !methodCall.isNull() ) { const QDomElement methodName = methodCall.firstChildElement("methodName"); if( !methodName.isNull() ) { m_method = methodName.text().toLatin1(); } else { setError("Missing methodName property."); return; } const QDomElement methodParams = methodCall.firstChildElement("params"); if( !methodParams.isNull() ) { QDomNode param = methodParams.firstChild(); while( !param.isNull() && isValid() ) { m_args.append( demarshall( param.firstChild().toElement() ) ); param = param.nextSibling(); } } } else setError("Not a valid methodCall message."); } else { setError(QString( "XML Error: %1 at row %2 and col %3") .arg(xmlErrMsg).arg(xmlErrLine).arg(xmlErrCol)); } } void XMLRPC::ResponseMessage::writeXml( QXmlStreamWriter *writer ) const { writer->writeStartElement("methodResponse"); if( !m_values.isEmpty() ) { writer->writeStartElement("params"); foreach( QVariant arg, m_values) { writer->writeStartElement("param"); marshall( writer, arg ); writer->writeEndElement(); } writer->writeEndElement(); } writer->writeEndElement(); } QByteArray XMLRPC::ResponseMessage::xml( ) const { QByteArray returnXML ; QXmlStreamWriter writer(&returnXML); writer.writeStartDocument(); writeXml( &writer ); writer.writeEndElement(); writer.writeEndDocument(); return returnXML; } void XMLRPC::ResponseMessage::setValues( const QList< QVariant > vals ) { m_values = vals; } XMLRPC::ResponseMessage::ResponseMessage( const QList< QVariant > & theValue ) : MessageBase(), m_values(theValue) { } XMLRPC::FaultMessage::FaultMessage( int code, const QString & message ) : ResponseMessage(QList<QVariant>() ) { QList<QVariant> args; QMap<QString,QVariant> fault; fault["faultCode"] = code; fault["faultString"] = message; args << fault; setValues(args); } void XMLRPC::FaultMessage::writeXml( QXmlStreamWriter *writer ) const { writer->writeStartElement("fault"); marshall( writer, values().first() ); writer->writeEndElement(); } QByteArray XMLRPC::FaultMessage::xml( ) const { QByteArray returnXML; QXmlStreamWriter writer( &returnXML ); writer.writeStartDocument(); writeXml(&writer); writer.writeEndDocument(); return returnXML; } XMLRPC::ResponseMessage::ResponseMessage( const QVariant & theValue ) : MessageBase() { m_values << theValue; }
fix issue #56
fix issue #56 git-svn-id: e2fa1b4f04257a65cc3162f75ad5f19d327daceb@433 85bd2434-ea95-11dd-8fb1-9960f2a117f8
C++
lgpl-2.1
mtdcr/QXmpp,mtdcr/QXmpp
9651729341e8cce9d2c4e529ebc4bf070ac61648
staging_vespalib/src/vespa/vespalib/net/generic_state_handler.cpp
staging_vespalib/src/vespa/vespalib/net/generic_state_handler.cpp
// Copyright 2016 Yahoo Inc. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. #include "generic_state_handler.h" #include <vespa/vespalib/data/slime/slime.h> namespace vespalib { namespace { std::vector<vespalib::string> split_path(const vespalib::string &path) { vespalib::string tmp; std::vector<vespalib::string> items; for (size_t i = 0; (i < path.size()) && (path[i] != '?'); ++i) { if (path[i] == '/') { if (!tmp.empty()) { items.push_back(tmp); tmp.clear(); } } else { tmp.push_back(path[i]); } } if (!tmp.empty()) { items.push_back(tmp); } return items; } bool is_prefix(const std::vector<vespalib::string> &root, const std::vector<vespalib::string> &full) { if (root.size() > full.size()) { return false; } for (size_t i = 0; i < root.size(); ++i) { if (root[i] != full[i]) { return false; } } return true; } vespalib::string make_url(const vespalib::string &host, const std::vector<vespalib::string> &items) { vespalib::string url = "http://" + host; if (items.empty()) { url += "/"; } for (const vespalib::string &item: items) { url += "/" + item; } return url; } void inject_children(const StateExplorer &state, const vespalib::string &url, slime::Cursor &self); Slime child_state(const StateExplorer &state, const vespalib::string &url) { Slime child_state; state.get_state(slime::SlimeInserter(child_state), false); if (child_state.get().type().getId() == slime::NIX::ID) { inject_children(state, url, child_state.setObject()); } else { child_state.get().setString("url", url); } return child_state; } void inject_children(const StateExplorer &state, const vespalib::string &url, slime::Cursor &self) { std::vector<vespalib::string> children_names = state.get_children_names(); for (const vespalib::string &child_name: children_names) { std::unique_ptr<StateExplorer> child = state.get_child(child_name); if (child) { vespalib::string child_url = url + "/" + child_name; Slime fragment = child_state(*child, child_url); slime::inject(fragment.get(), slime::ObjectInserter(self, child_name)); } } } vespalib::string render(const StateExplorer &state, const vespalib::string &url) { Slime top; state.get_state(slime::SlimeInserter(top), true); if (top.get().type().getId() == slime::NIX::ID) { top.setObject(); } inject_children(state, url, top.get()); slime::SimpleBuffer buf; slime::JsonFormat::encode(top, buf, true); return buf.get().make_string(); } vespalib::string explore(const StateExplorer &state, const vespalib::string &host, const std::vector<vespalib::string> &items, size_t pos) { if (pos == items.size()) { return render(state, make_url(host, items)); } std::unique_ptr<StateExplorer> child = state.get_child(items[pos]); if (!child) { return ""; } return explore(*child, host, items, pos + 1); } } // namespace vespalib::<unnamed> GenericStateHandler::GenericStateHandler(const vespalib::string &root_path, const StateExplorer &state) : _root(split_path(root_path)), _state(state) { } vespalib::string GenericStateHandler::get(const vespalib::string &host, const vespalib::string &path, const std::map<vespalib::string,vespalib::string> &) const { std::vector<vespalib::string> items = split_path(path); if (!is_prefix(_root, items)) { return ""; } return explore(_state, host, items, _root.size()); } } // namespace vespalib
// Copyright 2016 Yahoo Inc. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. #include "generic_state_handler.h" #include <vespa/vespalib/data/slime/slime.h> namespace vespalib { namespace { vespalib::string url_escape(const vespalib::string &item) { return item; } class Url { private: vespalib::string _url; void append(const vespalib::string &item) { if (*_url.rbegin() != '/') { _url.append('/'); } _url.append(url_escape(item)); } public: Url(const vespalib::string &host, const std::vector<vespalib::string> &items) : _url("http://") { _url.append(host); _url.append('/'); for (const auto &item: items) { append(item); } } Url(const Url &parent, const vespalib::string &item) : _url(parent._url) { append(item); } const vespalib::string &get() const { return _url; } }; std::vector<vespalib::string> split_path(const vespalib::string &path) { vespalib::string tmp; std::vector<vespalib::string> items; for (size_t i = 0; (i < path.size()) && (path[i] != '?'); ++i) { if (path[i] == '/') { if (!tmp.empty()) { items.push_back(tmp); tmp.clear(); } } else { tmp.push_back(path[i]); } } if (!tmp.empty()) { items.push_back(tmp); } return items; } bool is_prefix(const std::vector<vespalib::string> &root, const std::vector<vespalib::string> &full) { if (root.size() > full.size()) { return false; } for (size_t i = 0; i < root.size(); ++i) { if (root[i] != full[i]) { return false; } } return true; } void inject_children(const StateExplorer &state, const Url &url, slime::Cursor &self); Slime child_state(const StateExplorer &state, const Url &url) { Slime child_state; state.get_state(slime::SlimeInserter(child_state), false); if (child_state.get().type().getId() == slime::NIX::ID) { inject_children(state, url, child_state.setObject()); } else { child_state.get().setString("url", url.get()); } return child_state; } void inject_children(const StateExplorer &state, const Url &url, slime::Cursor &self) { std::vector<vespalib::string> children_names = state.get_children_names(); for (const vespalib::string &child_name: children_names) { std::unique_ptr<StateExplorer> child = state.get_child(child_name); if (child) { Slime fragment = child_state(*child, Url(url, child_name)); slime::inject(fragment.get(), slime::ObjectInserter(self, child_name)); } } } vespalib::string render(const StateExplorer &state, const Url &url) { Slime top; state.get_state(slime::SlimeInserter(top), true); if (top.get().type().getId() == slime::NIX::ID) { top.setObject(); } inject_children(state, url, top.get()); slime::SimpleBuffer buf; slime::JsonFormat::encode(top, buf, true); return buf.get().make_string(); } vespalib::string explore(const StateExplorer &state, const vespalib::string &host, const std::vector<vespalib::string> &items, size_t pos) { if (pos == items.size()) { return render(state, Url(host, items)); } std::unique_ptr<StateExplorer> child = state.get_child(items[pos]); if (!child) { return ""; } return explore(*child, host, items, pos + 1); } } // namespace vespalib::<unnamed> GenericStateHandler::GenericStateHandler(const vespalib::string &root_path, const StateExplorer &state) : _root(split_path(root_path)), _state(state) { } vespalib::string GenericStateHandler::get(const vespalib::string &host, const vespalib::string &path, const std::map<vespalib::string,vespalib::string> &) const { std::vector<vespalib::string> items = split_path(path); if (!is_prefix(_root, items)) { return ""; } return explore(_state, host, items, _root.size()); } } // namespace vespalib
prepare for url escape
prepare for url escape
C++
apache-2.0
vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa
65353fb4fb840b75d81485fa145d6106a2aabc36
mjolnir/potential/global/DebyeHuckelPotential.hpp
mjolnir/potential/global/DebyeHuckelPotential.hpp
#ifndef MJOLNIR_POTENTIAL_GLOBAL_DEBYE_HUCKEL_POTENTIAL_HPP #define MJOLNIR_POTENTIAL_GLOBAL_DEBYE_HUCKEL_POTENTIAL_HPP #include <mjolnir/core/Unit.hpp> #include <mjolnir/core/ExclusionList.hpp> #include <mjolnir/core/System.hpp> #include <mjolnir/math/constants.hpp> #include <mjolnir/util/logger.hpp> #include <vector> #include <numeric> #include <cmath> #include <cassert> namespace mjolnir { // Debye-Huckel type electrostatic interaction. // This class contains charges and other parameters and calculates energy and // derivative of the potential function. // This class is an implementation of the electrostatic term used in the 3SPN // series of the coarse-grained DNA models (Knotts et al., (2007), Sambriski and // de Pablo, (2009), Hinckley et al., (2013), and Freeman et al., (2014)) // It is same as the default electrostatic term in CafeMol (Kenzaki et al. 2011) template<typename realT> class DebyeHuckelPotential { public: using real_type = realT; using parameter_type = real_type; using container_type = std::vector<parameter_type>; // `pair_parameter_type` is a parameter for a interacting pair. // Although it is the same type as `parameter_type` in this potential, // it can be different from normal parameter for each particle. // This enables NeighborList to cache a value to calculate forces between // the particles, e.g. by having qi * qj for pair of particles i and j. using pair_parameter_type = parameter_type; // topology stuff using topology_type = Topology; using molecule_id_type = typename topology_type::molecule_id_type; using group_id_type = typename topology_type::group_id_type; using connection_kind_type = typename topology_type::connection_kind_type; using ignore_molecule_type = IgnoreMolecule<molecule_id_type>; using ignore_group_type = IgnoreGroup <group_id_type>; using exclusion_list_type = ExclusionList; static constexpr real_type default_cutoff() noexcept { return real_type(5.5); } static constexpr parameter_type default_parameter() noexcept { return real_type(0); } public: DebyeHuckelPotential(const real_type cutoff_ratio, const std::vector<std::pair<std::size_t, parameter_type>>& parameters, const std::map<connection_kind_type, std::size_t>& exclusions, ignore_molecule_type ignore_mol, ignore_group_type ignore_grp) : cutoff_ratio_(cutoff_ratio), temperature_(300.0), ion_conc_(0.1), exclusion_list_(exclusions, std::move(ignore_mol), std::move(ignore_grp)) { this->parameters_ .reserve(parameters.size()); this->participants_.reserve(parameters.size()); for(const auto& idxp : parameters) { const auto idx = idxp.first; this->participants_.push_back(idx); if(idx >= this->parameters_.size()) { this->parameters_.resize(idx+1, default_parameter()); } this->parameters_.at(idx) = idxp.second; } // XXX should be updated before use because T and ion conc are default! this->calc_parameters(); } ~DebyeHuckelPotential() = default; pair_parameter_type prepare_params(std::size_t i, std::size_t j) const noexcept { return this->inv_4_pi_eps0_epsk_ * this->parameters_[i] * this->parameters_[j]; } real_type potential(const std::size_t i, const std::size_t j, const real_type r) const noexcept { return this->potential(r, this->prepare_params(i, j)); } real_type derivative(const std::size_t i, const std::size_t j, const real_type r) const noexcept { return this->derivative(r, this->prepare_params(i, j)); } real_type potential(const real_type r, const pair_parameter_type& p) const noexcept { if(this->max_cutoff_length() <= r) {return 0.0;} return p * (std::exp(-r * this->inv_debye_length_) / r - coef_at_cutoff_); } real_type derivative(const real_type r, const pair_parameter_type& p) const noexcept { if(this->max_cutoff_length() <= r) {return 0.0;} return -p * (debye_length_ + r) * this->inv_debye_length_ / (r * r) * std::exp(-r * this->inv_debye_length_); } real_type cutoff_ratio() const noexcept {return this->cutoff_ratio_;} real_type coef_at_cutoff() const noexcept {return this->coef_at_cutoff_;} real_type max_cutoff_length() const noexcept { return this->debye_length_ * this->cutoff_ratio_; } template<typename traitsT> void initialize(const System<traitsT>& sys) noexcept { MJOLNIR_GET_DEFAULT_LOGGER(); MJOLNIR_LOG_FUNCTION(); if(!sys.has_attribute("temperature")) { MJOLNIR_LOG_ERROR("DebyeHuckel requires `temperature` attribute"); } if(!sys.has_attribute("ionic_strength")) { MJOLNIR_LOG_ERROR("DebyeHuckel requires `ionic_strength` attribute"); } this->update(sys); // calc parameters return; } // for temperature/ionic concentration changes... template<typename traitsT> void update(const System<traitsT>& sys) noexcept { MJOLNIR_GET_DEFAULT_LOGGER(); MJOLNIR_LOG_FUNCTION(); assert(sys.has_attribute("temperature")); assert(sys.has_attribute("ionic_strength")); this->temperature_ = sys.attribute("temperature"); this->ion_conc_ = sys.attribute("ionic_strength"); MJOLNIR_LOG_INFO("temperature = ", this->temperature_); MJOLNIR_LOG_INFO("ionic strength = ", this->ion_conc_); this->calc_parameters(); // update exclusion list based on sys.topology() exclusion_list_.make(sys); return; } bool has_interaction(const std::size_t i, const std::size_t j) const noexcept { // if not excluded, the pair has interaction. return !exclusion_list_.is_excluded(i, j); } // for testing exclusion_list_type const& exclusion_list() const noexcept { return exclusion_list_; } // ------------------------------------------------------------------------ // used by Observer. static const char* name() noexcept {return "DebyeHuckel";} // ------------------------------------------------------------------------ // the following accessers would be used in tests. // access to the parameters. std::vector<real_type>& charges() noexcept {return parameters_;} std::vector<real_type> const& charges() const noexcept {return parameters_;} std::vector<std::size_t> const& participants() const noexcept {return participants_;} real_type debye_length() const noexcept {return this->debye_length_;} private: void calc_parameters() noexcept { MJOLNIR_GET_DEFAULT_LOGGER(); MJOLNIR_LOG_FUNCTION(); using math_const = math::constants<real_type>; using phys_const = physics::constants<real_type>; constexpr real_type pi = math_const::pi(); const real_type kB = phys_const::kB(); const real_type NA = phys_const::NA(); const real_type eps0 = phys_const::eps0(); const real_type epsk = calc_dielectric_water(temperature_, ion_conc_); const real_type T = this->temperature_; MJOLNIR_LOG_INFO("kB = ", kB); MJOLNIR_LOG_INFO("T = ", T); MJOLNIR_LOG_INFO("NA = ", NA); MJOLNIR_LOG_INFO("epsilon_0 = ", eps0); MJOLNIR_LOG_INFO("epsilon_k = ", epsk); this->inv_4_pi_eps0_epsk_ = 1.0 / (4 * pi * eps0 * epsk); // convert [M] (mol/L) or [mM] -> [mol/nm^3] or [mol/A^3] const real_type I = 0.5 * ion_conc_ / phys_const::L_to_volume(); this->debye_length_ = std::sqrt((eps0 * epsk * kB * T) / (2 * NA * I)); this->inv_debye_length_ = 1. / this->debye_length_; MJOLNIR_LOG_INFO("debye length = ", debye_length_); MJOLNIR_LOG_INFO("1 / debye length = ", inv_debye_length_); MJOLNIR_LOG_INFO("1 / 4pi eps0 epsk = ", inv_4_pi_eps0_epsk_); this->coef_at_cutoff_ = std::exp(-cutoff_ratio_) / (debye_length_ * cutoff_ratio_); return; } real_type calc_dielectric_water( const real_type T, const real_type c) const noexcept { return (249.4 - 0.788 * T + 7.2e-4 * T * T) * (1. - 2.551e-1 * c + 5.151e-2 * c * c - 6.889e-3 * c * c * c); } private: real_type cutoff_ratio_; // relative to the debye length real_type coef_at_cutoff_; real_type temperature_; // [K] real_type ion_conc_; // [M] real_type inv_4_pi_eps0_epsk_; real_type debye_length_; real_type inv_debye_length_; container_type parameters_; std::vector<std::size_t> participants_; exclusion_list_type exclusion_list_; }; #ifdef MJOLNIR_SEPARATE_BUILD extern template class DebyeHuckelPotential<double>; extern template class DebyeHuckelPotential<float>; #endif// MJOLNIR_SEPARATE_BUILD } // mjolnir #endif /* MJOLNIR_DEBYE_HUCKEL_POTENTIAL */
#ifndef MJOLNIR_POTENTIAL_GLOBAL_DEBYE_HUCKEL_POTENTIAL_HPP #define MJOLNIR_POTENTIAL_GLOBAL_DEBYE_HUCKEL_POTENTIAL_HPP #include <mjolnir/core/Unit.hpp> #include <mjolnir/core/ExclusionList.hpp> #include <mjolnir/core/System.hpp> #include <mjolnir/math/constants.hpp> #include <mjolnir/util/logger.hpp> #include <vector> #include <numeric> #include <cmath> #include <cassert> namespace mjolnir { // Debye-Huckel type electrostatic interaction. // This class contains charges and other parameters and calculates energy and // derivative of the potential function. // This class is an implementation of the electrostatic term used in the 3SPN // series of the coarse-grained DNA models (Knotts et al., (2007), Sambriski and // de Pablo, (2009), Hinckley et al., (2013), and Freeman et al., (2014)) // It is same as the default electrostatic term in CafeMol (Kenzaki et al. 2011) template<typename realT> class DebyeHuckelPotential { public: using real_type = realT; using parameter_type = real_type; using container_type = std::vector<parameter_type>; // `pair_parameter_type` is a parameter for a interacting pair. // Although it is the same type as `parameter_type` in this potential, // it can be different from normal parameter for each particle. // This enables NeighborList to cache a value to calculate forces between // the particles, e.g. by having qi * qj for pair of particles i and j. using pair_parameter_type = parameter_type; // topology stuff using topology_type = Topology; using molecule_id_type = typename topology_type::molecule_id_type; using group_id_type = typename topology_type::group_id_type; using connection_kind_type = typename topology_type::connection_kind_type; using ignore_molecule_type = IgnoreMolecule<molecule_id_type>; using ignore_group_type = IgnoreGroup <group_id_type>; using exclusion_list_type = ExclusionList; static constexpr real_type default_cutoff() noexcept { return real_type(5.5); } static constexpr parameter_type default_parameter() noexcept { return real_type(0); } public: DebyeHuckelPotential(const real_type cutoff_ratio, const std::vector<std::pair<std::size_t, parameter_type>>& parameters, const std::map<connection_kind_type, std::size_t>& exclusions, ignore_molecule_type ignore_mol, ignore_group_type ignore_grp) : cutoff_ratio_(cutoff_ratio), temperature_(300.0), ion_strength_(0.1), exclusion_list_(exclusions, std::move(ignore_mol), std::move(ignore_grp)) { this->parameters_ .reserve(parameters.size()); this->participants_.reserve(parameters.size()); for(const auto& idxp : parameters) { const auto idx = idxp.first; this->participants_.push_back(idx); if(idx >= this->parameters_.size()) { this->parameters_.resize(idx+1, default_parameter()); } this->parameters_.at(idx) = idxp.second; } // XXX should be updated before use because T and ion conc are default! this->calc_parameters(); } ~DebyeHuckelPotential() = default; pair_parameter_type prepare_params(std::size_t i, std::size_t j) const noexcept { return this->inv_4_pi_eps0_epsk_ * this->parameters_[i] * this->parameters_[j]; } real_type potential(const std::size_t i, const std::size_t j, const real_type r) const noexcept { return this->potential(r, this->prepare_params(i, j)); } real_type derivative(const std::size_t i, const std::size_t j, const real_type r) const noexcept { return this->derivative(r, this->prepare_params(i, j)); } real_type potential(const real_type r, const pair_parameter_type& p) const noexcept { if(this->max_cutoff_length() <= r) {return 0.0;} return p * (std::exp(-r * this->inv_debye_length_) / r - coef_at_cutoff_); } real_type derivative(const real_type r, const pair_parameter_type& p) const noexcept { if(this->max_cutoff_length() <= r) {return 0.0;} return -p * (debye_length_ + r) * this->inv_debye_length_ / (r * r) * std::exp(-r * this->inv_debye_length_); } real_type cutoff_ratio() const noexcept {return this->cutoff_ratio_;} real_type coef_at_cutoff() const noexcept {return this->coef_at_cutoff_;} real_type max_cutoff_length() const noexcept { return this->debye_length_ * this->cutoff_ratio_; } template<typename traitsT> void initialize(const System<traitsT>& sys) noexcept { MJOLNIR_GET_DEFAULT_LOGGER(); MJOLNIR_LOG_FUNCTION(); if(!sys.has_attribute("temperature")) { MJOLNIR_LOG_ERROR("DebyeHuckel requires `temperature` attribute"); } if(!sys.has_attribute("ionic_strength")) { MJOLNIR_LOG_ERROR("DebyeHuckel requires `ionic_strength` attribute"); } this->update(sys); // calc parameters return; } // for temperature/ionic concentration changes... template<typename traitsT> void update(const System<traitsT>& sys) noexcept { MJOLNIR_GET_DEFAULT_LOGGER(); MJOLNIR_LOG_FUNCTION(); assert(sys.has_attribute("temperature")); assert(sys.has_attribute("ionic_strength")); this->temperature_ = sys.attribute("temperature"); this->ion_strength_ = sys.attribute("ionic_strength"); MJOLNIR_LOG_INFO("temperature = ", this->temperature_); MJOLNIR_LOG_INFO("ionic strength = ", this->ion_strength_); this->calc_parameters(); // update exclusion list based on sys.topology() exclusion_list_.make(sys); return; } bool has_interaction(const std::size_t i, const std::size_t j) const noexcept { // if not excluded, the pair has interaction. return !exclusion_list_.is_excluded(i, j); } // for testing exclusion_list_type const& exclusion_list() const noexcept { return exclusion_list_; } // ------------------------------------------------------------------------ // used by Observer. static const char* name() noexcept {return "DebyeHuckel";} // ------------------------------------------------------------------------ // the following accessers would be used in tests. // access to the parameters. std::vector<real_type>& charges() noexcept {return parameters_;} std::vector<real_type> const& charges() const noexcept {return parameters_;} std::vector<std::size_t> const& participants() const noexcept {return participants_;} real_type debye_length() const noexcept {return this->debye_length_;} private: void calc_parameters() noexcept { MJOLNIR_GET_DEFAULT_LOGGER(); MJOLNIR_LOG_FUNCTION(); using math_const = math::constants<real_type>; using phys_const = physics::constants<real_type>; constexpr real_type pi = math_const::pi(); const real_type kB = phys_const::kB(); const real_type NA = phys_const::NA(); const real_type eps0 = phys_const::eps0(); const real_type epsk = calc_dielectric_water(temperature_, ion_strength_); const real_type T = this->temperature_; MJOLNIR_LOG_INFO("kB = ", kB); MJOLNIR_LOG_INFO("T = ", T); MJOLNIR_LOG_INFO("NA = ", NA); MJOLNIR_LOG_INFO("epsilon_0 = ", eps0); MJOLNIR_LOG_INFO("epsilon_k = ", epsk); this->inv_4_pi_eps0_epsk_ = 1.0 / (4 * pi * eps0 * epsk); // convert [M] (mol/L) or [mM] -> [mol/nm^3] or [mol/A^3] const real_type I = ion_strength_ / phys_const::L_to_volume(); this->debye_length_ = std::sqrt((eps0 * epsk * kB * T) / (2 * NA * I)); this->inv_debye_length_ = 1. / this->debye_length_; MJOLNIR_LOG_INFO("debye length = ", debye_length_); MJOLNIR_LOG_INFO("1 / debye length = ", inv_debye_length_); MJOLNIR_LOG_INFO("1 / 4pi eps0 epsk = ", inv_4_pi_eps0_epsk_); this->coef_at_cutoff_ = std::exp(-cutoff_ratio_) / (debye_length_ * cutoff_ratio_); return; } real_type calc_dielectric_water( const real_type T, const real_type c) const noexcept { return (249.4 - 0.788 * T + 7.2e-4 * T * T) * (1. - 2.551e-1 * c + 5.151e-2 * c * c - 6.889e-3 * c * c * c); } private: real_type cutoff_ratio_; // relative to the debye length real_type coef_at_cutoff_; real_type temperature_; // [K] real_type ion_strength_; // [M] real_type inv_4_pi_eps0_epsk_; real_type debye_length_; real_type inv_debye_length_; container_type parameters_; std::vector<std::size_t> participants_; exclusion_list_type exclusion_list_; }; #ifdef MJOLNIR_SEPARATE_BUILD extern template class DebyeHuckelPotential<double>; extern template class DebyeHuckelPotential<float>; #endif// MJOLNIR_SEPARATE_BUILD } // mjolnir #endif /* MJOLNIR_DEBYE_HUCKEL_POTENTIAL */
change definition of ionic_streangth
feat: change definition of ionic_streangth currently, it was a concentration multiplied by its charge, but it is not a normal definition. just use total ionic strength.
C++
mit
ToruNiina/Mjolnir,ToruNiina/Mjolnir,ToruNiina/Mjolnir
d4c33cfc944cbcac7a31811ba8f86448d8cc2e23
tensorflow/compiler/xla/service/llvm_ir/kernel_support_library.cc
tensorflow/compiler/xla/service/llvm_ir/kernel_support_library.cc
/* Copyright 2017 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "tensorflow/compiler/xla/service/llvm_ir/kernel_support_library.h" #include "tensorflow/compiler/xla/service/llvm_ir/llvm_loop.h" #include "tensorflow/compiler/xla/service/llvm_ir/llvm_util.h" namespace xla { void KernelSupportLibrary::For( tensorflow::StringPiece name, llvm::Value* start, llvm::Value* end, llvm::Value* step, const std::function<void(llvm::Value*, bool)>& for_body_generator) { If(ir_builder_->CreateICmpSLT(start, end), [&]() { for_body_generator(start, /*is_first_iteration=*/true); For(name, ir_builder_->CreateAdd(start, step), end, step, [&](llvm::Value* iv) { for_body_generator(iv, false); }); }); } void KernelSupportLibrary::For( tensorflow::StringPiece name, llvm::Value* start, llvm::Value* end, llvm::Value* step, bool peel_first_iteration, const std::function<void(llvm::Value*, llvm::Value*)>& for_body_generator) { if (peel_first_iteration) { For(name, start, end, step, true, [&](llvm::Value* indvar, bool is_first_iteration) { for_body_generator(indvar, ir_builder_->getInt1(is_first_iteration)); }); } else { std::unique_ptr<llvm_ir::ForLoop> loop = llvm_ir::ForLoop::EmitForLoop( name, start, end, step, ir_builder_, /*prevent_unrolling=*/prevent_unrolling_, /*prevent_vectorization=*/prevent_vectorization_); ir_builder_->SetInsertPoint(&loop->GetBodyBasicBlock()->back()); for_body_generator(loop->GetIndVarValue(), /*is_first_iteration=*/ir_builder_->CreateICmpEQ( loop->GetIndVarValue(), start)); llvm_ir::SetToLastInsertPoint(loop->GetExitBasicBlock(), ir_builder_); } } void KernelSupportLibrary::If( llvm::Value* condition, const std::function<void()>& true_block_generator, const std::function<void()>& false_block_generator) { llvm_ir::LlvmIfData if_data = llvm_ir::EmitIfThenElse(condition, "", ir_builder_); ir_builder_->SetInsertPoint(&if_data.true_block->back()); true_block_generator(); ir_builder_->SetInsertPoint(&if_data.false_block->back()); false_block_generator(); llvm_ir::SetToLastInsertPoint(if_data.after_block, ir_builder_); } void KernelSupportLibrary::EmitAndCallOutlinedKernel( bool enable_fast_math, bool optimize_for_size, llvm::IRBuilder<>* ir_builder, tensorflow::StringPiece kernel_name, KernelSupportLibrary::ArgumentVector arguments, const std::function<void(KernelSupportLibrary::ArgumentVector)>& kernel_body_generator) { llvm::Module* module = ir_builder->GetInsertBlock()->getModule(); llvm::Function* function = module->getFunction(llvm_ir::AsStringRef(kernel_name)); int64 null_arg_idx = -1; std::vector<llvm::Value*> sanitized_args; sanitized_args.reserve(arguments.size()); for (int64 i = 0, e = arguments.size(); i < e; i++) { if (arguments[i]) { sanitized_args.push_back(arguments[i]); } else { CHECK_EQ(null_arg_idx, -1); null_arg_idx = i; } } if (!function) { VLOG(2) << "Generating kernel for " << kernel_name; std::vector<llvm::Type*> arg_types; std::transform(sanitized_args.begin(), sanitized_args.end(), std::back_inserter(arg_types), [](llvm::Value* arg) { return arg->getType(); }); auto* function_type = llvm::FunctionType::get( ir_builder->getVoidTy(), arg_types, /*isVarArg=*/false); function = llvm_ir::CreateFunction( function_type, llvm::GlobalValue::InternalLinkage, /*enable_fast_math=*/enable_fast_math, /*optimize_for_size=*/optimize_for_size, kernel_name, module); llvm::IRBuilder<>::InsertPointGuard guard(*ir_builder); auto* entry_bb = llvm::BasicBlock::Create(ir_builder->getContext(), "entry", function); auto* return_inst = llvm::ReturnInst::Create(ir_builder->getContext(), /*retVal=*/nullptr, entry_bb); // Set the insert point to before return_inst. ir_builder->SetInsertPoint(return_inst); std::vector<llvm::Value*> arg_values; std::transform(function->arg_begin(), function->arg_end(), std::back_inserter(arg_values), std::addressof<llvm::Value>); if (null_arg_idx != -1) { arg_values.insert(arg_values.begin() + null_arg_idx, nullptr); } kernel_body_generator(arg_values); } else { VLOG(3) << "Re-using kernel for " << kernel_name; } ir_builder->CreateCall(function, llvm_ir::AsArrayRef(sanitized_args)); } } // namespace xla
/* Copyright 2017 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "tensorflow/compiler/xla/service/llvm_ir/kernel_support_library.h" #include "tensorflow/compiler/xla/service/llvm_ir/llvm_loop.h" #include "tensorflow/compiler/xla/service/llvm_ir/llvm_util.h" namespace xla { void KernelSupportLibrary::For( tensorflow::StringPiece name, llvm::Value* start, llvm::Value* end, llvm::Value* step, const std::function<void(llvm::Value*, bool)>& for_body_generator) { If(ir_builder_->CreateICmpSLT(start, end), [&]() { for_body_generator(start, /*is_first_iteration=*/true); For(name, ir_builder_->CreateAdd(start, step), end, step, [&](llvm::Value* iv) { for_body_generator(iv, false); }); }); } void KernelSupportLibrary::For( tensorflow::StringPiece name, llvm::Value* start, llvm::Value* end, llvm::Value* step, bool peel_first_iteration, const std::function<void(llvm::Value*, llvm::Value*)>& for_body_generator) { if (peel_first_iteration) { For(name, start, end, step, true, [&](llvm::Value* indvar, bool is_first_iteration) { for_body_generator(indvar, ir_builder_->getInt1(is_first_iteration)); }); } else { std::unique_ptr<llvm_ir::ForLoop> loop = llvm_ir::ForLoop::EmitForLoop( name, start, end, step, ir_builder_, /*prevent_unrolling=*/prevent_unrolling_, /*prevent_vectorization=*/prevent_vectorization_); ir_builder_->SetInsertPoint(&loop->GetBodyBasicBlock()->back()); for_body_generator(loop->GetIndVarValue(), /*is_first_iteration=*/ir_builder_->CreateICmpEQ( loop->GetIndVarValue(), start)); llvm_ir::SetToLastInsertPoint(loop->GetExitBasicBlock(), ir_builder_); } } void KernelSupportLibrary::If( llvm::Value* condition, const std::function<void()>& true_block_generator, const std::function<void()>& false_block_generator) { llvm_ir::LlvmIfData if_data = llvm_ir::EmitIfThenElse(condition, "", ir_builder_); ir_builder_->SetInsertPoint(&if_data.true_block->back()); true_block_generator(); ir_builder_->SetInsertPoint(&if_data.false_block->back()); false_block_generator(); llvm_ir::SetToLastInsertPoint(if_data.after_block, ir_builder_); } void KernelSupportLibrary::EmitAndCallOutlinedKernel( bool enable_fast_math, bool optimize_for_size, llvm::IRBuilder<>* ir_builder, tensorflow::StringPiece kernel_name, KernelSupportLibrary::ArgumentVector arguments, const std::function<void(KernelSupportLibrary::ArgumentVector)>& kernel_body_generator) { llvm::Module* module = ir_builder->GetInsertBlock()->getModule(); llvm::Function* function = module->getFunction(llvm_ir::AsStringRef(kernel_name)); int64 null_arg_idx = -1; std::vector<llvm::Value*> sanitized_args; sanitized_args.reserve(arguments.size()); for (int64 i = 0, e = arguments.size(); i < e; i++) { if (arguments[i]) { sanitized_args.push_back(arguments[i]); } else { CHECK_EQ(null_arg_idx, -1); null_arg_idx = i; } } if (!function) { VLOG(2) << "Generating kernel for " << kernel_name; std::vector<llvm::Type*> arg_types; std::transform(sanitized_args.begin(), sanitized_args.end(), std::back_inserter(arg_types), [](llvm::Value* arg) { return arg->getType(); }); auto* function_type = llvm::FunctionType::get( ir_builder->getVoidTy(), arg_types, /*isVarArg=*/false); function = llvm_ir::CreateFunction( function_type, llvm::GlobalValue::InternalLinkage, /*enable_fast_math=*/enable_fast_math, /*optimize_for_size=*/optimize_for_size, kernel_name, module); llvm::IRBuilder<>::InsertPointGuard guard(*ir_builder); auto* entry_bb = llvm::BasicBlock::Create(ir_builder->getContext(), "entry", function); auto* return_inst = llvm::ReturnInst::Create(ir_builder->getContext(), /*retVal=*/nullptr, entry_bb); // Set the insert point to before return_inst. ir_builder->SetInsertPoint(return_inst); std::vector<llvm::Value*> arg_values; /* * clang on OSX doesn't like std::transform or range for loop here. * See https://github.com/tensorflow/tensorflow/issues/15196 */ for (llvm::Function::arg_iterator arg = function->arg_begin(), arg_e = function->arg_end(); arg != arg_e; ++arg) { arg_values.push_back(arg); } if (null_arg_idx != -1) { arg_values.insert(arg_values.begin() + null_arg_idx, nullptr); } kernel_body_generator(arg_values); } else { VLOG(3) << "Re-using kernel for " << kernel_name; } ir_builder->CreateCall(function, llvm_ir::AsArrayRef(sanitized_args)); } } // namespace xla
Fix XLA/tfcompile compile error on OSX
[XLA] Fix XLA/tfcompile compile error on OSX This fixes issue #15196 kernel_support_library.cc:99:5: error: no matching function for call to 'transform' std::transform(function->arg_begin(),.. TEST=build tfcompile on OSX (also requires PR#14893)
C++
apache-2.0
ghchinoy/tensorflow,lakshayg/tensorflow,jart/tensorflow,Bismarrck/tensorflow,seanli9jan/tensorflow,JingJunYin/tensorflow,frreiss/tensorflow-fred,dancingdan/tensorflow,petewarden/tensorflow,apark263/tensorflow,Mistobaan/tensorflow,aldian/tensorflow,renyi533/tensorflow,xodus7/tensorflow,freedomtan/tensorflow,jalexvig/tensorflow,rabipanda/tensorflow,Intel-tensorflow/tensorflow,gunan/tensorflow,manipopopo/tensorflow,rabipanda/tensorflow,lakshayg/tensorflow,dongjoon-hyun/tensorflow,gunan/tensorflow,annarev/tensorflow,lakshayg/tensorflow,adit-chandra/tensorflow,jart/tensorflow,aselle/tensorflow,jhseu/tensorflow,meteorcloudy/tensorflow,av8ramit/tensorflow,apark263/tensorflow,jbedorf/tensorflow,aselle/tensorflow,drpngx/tensorflow,nolanliou/tensorflow,alsrgv/tensorflow,kobejean/tensorflow,nburn42/tensorflow,ravindrapanda/tensorflow,theflofly/tensorflow,ageron/tensorflow,cxxgtxy/tensorflow,alshedivat/tensorflow,asimshankar/tensorflow,kobejean/tensorflow,ravindrapanda/tensorflow,rabipanda/tensorflow,allenlavoie/tensorflow,AnishShah/tensorflow,gunan/tensorflow,paolodedios/tensorflow,nolanliou/tensorflow,frreiss/tensorflow-fred,dendisuhubdy/tensorflow,rabipanda/tensorflow,jwlawson/tensorflow,Mistobaan/tensorflow,petewarden/tensorflow,nburn42/tensorflow,jhseu/tensorflow,Xeralux/tensorflow,benoitsteiner/tensorflow-xsmm,drpngx/tensorflow,apark263/tensorflow,xzturn/tensorflow,Xeralux/tensorflow,adit-chandra/tensorflow,manipopopo/tensorflow,renyi533/tensorflow,ZhangXinNan/tensorflow,aam-at/tensorflow,DavidNorman/tensorflow,aam-at/tensorflow,DavidNorman/tensorflow,ageron/tensorflow,jhseu/tensorflow,jbedorf/tensorflow,ZhangXinNan/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,hfp/tensorflow-xsmm,tensorflow/tensorflow-experimental_link_static_libraries_once,jart/tensorflow,gojira/tensorflow,dancingdan/tensorflow,alsrgv/tensorflow,ravindrapanda/tensorflow,allenlavoie/tensorflow,paolodedios/tensorflow,jhseu/tensorflow,JingJunYin/tensorflow,yongtang/tensorflow,freedomtan/tensorflow,codrut3/tensorflow,renyi533/tensorflow,tensorflow/tensorflow,xodus7/tensorflow,meteorcloudy/tensorflow,freedomtan/tensorflow,karllessard/tensorflow,theflofly/tensorflow,alshedivat/tensorflow,brchiu/tensorflow,alsrgv/tensorflow,karllessard/tensorflow,eadgarchen/tensorflow,hfp/tensorflow-xsmm,hsaputra/tensorflow,dendisuhubdy/tensorflow,jendap/tensorflow,jart/tensorflow,dendisuhubdy/tensorflow,xodus7/tensorflow,gojira/tensorflow,sarvex/tensorflow,seanli9jan/tensorflow,cxxgtxy/tensorflow,jendap/tensorflow,aam-at/tensorflow,paolodedios/tensorflow,adit-chandra/tensorflow,ppwwyyxx/tensorflow,seanli9jan/tensorflow,freedomtan/tensorflow,arborh/tensorflow,alshedivat/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,caisq/tensorflow,tensorflow/tensorflow-pywrap_saved_model,aldian/tensorflow,arborh/tensorflow,xodus7/tensorflow,Bismarrck/tensorflow,tensorflow/tensorflow,drpngx/tensorflow,hfp/tensorflow-xsmm,gautam1858/tensorflow,gautam1858/tensorflow,lukeiwanski/tensorflow,aam-at/tensorflow,Intel-tensorflow/tensorflow,dancingdan/tensorflow,allenlavoie/tensorflow,Intel-Corporation/tensorflow,lakshayg/tensorflow,drpngx/tensorflow,karllessard/tensorflow,frreiss/tensorflow-fred,yongtang/tensorflow,caisq/tensorflow,frreiss/tensorflow-fred,aam-at/tensorflow,yongtang/tensorflow,chemelnucfin/tensorflow,eadgarchen/tensorflow,Xeralux/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,DavidNorman/tensorflow,paolodedios/tensorflow,ghchinoy/tensorflow,hehongliang/tensorflow,dongjoon-hyun/tensorflow,av8ramit/tensorflow,kobejean/tensorflow,ghchinoy/tensorflow,DavidNorman/tensorflow,jbedorf/tensorflow,freedomtan/tensorflow,tensorflow/tensorflow-pywrap_saved_model,codrut3/tensorflow,dongjoon-hyun/tensorflow,arborh/tensorflow,Xeralux/tensorflow,rabipanda/tensorflow,ageron/tensorflow,annarev/tensorflow,ppwwyyxx/tensorflow,dancingdan/tensorflow,tensorflow/tensorflow,caisq/tensorflow,jalexvig/tensorflow,aldian/tensorflow,eaplatanios/tensorflow,Intel-Corporation/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,petewarden/tensorflow,dancingdan/tensorflow,snnn/tensorflow,kobejean/tensorflow,brchiu/tensorflow,asimshankar/tensorflow,gunan/tensorflow,jendap/tensorflow,frreiss/tensorflow-fred,theflofly/tensorflow,JingJunYin/tensorflow,brchiu/tensorflow,annarev/tensorflow,hsaputra/tensorflow,Intel-Corporation/tensorflow,alshedivat/tensorflow,Intel-tensorflow/tensorflow,dancingdan/tensorflow,lukeiwanski/tensorflow,eaplatanios/tensorflow,ravindrapanda/tensorflow,asimshankar/tensorflow,ageron/tensorflow,Bismarrck/tensorflow,zasdfgbnm/tensorflow,jendap/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,gojira/tensorflow,yanchen036/tensorflow,xodus7/tensorflow,yongtang/tensorflow,nolanliou/tensorflow,girving/tensorflow,AnishShah/tensorflow,alsrgv/tensorflow,adit-chandra/tensorflow,chemelnucfin/tensorflow,nburn42/tensorflow,eaplatanios/tensorflow,seanli9jan/tensorflow,brchiu/tensorflow,ppwwyyxx/tensorflow,ZhangXinNan/tensorflow,Mistobaan/tensorflow,hehongliang/tensorflow,davidzchen/tensorflow,seanli9jan/tensorflow,nolanliou/tensorflow,snnn/tensorflow,dancingdan/tensorflow,frreiss/tensorflow-fred,tensorflow/tensorflow-pywrap_saved_model,jwlawson/tensorflow,cxxgtxy/tensorflow,adit-chandra/tensorflow,aam-at/tensorflow,lakshayg/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,AnishShah/tensorflow,davidzchen/tensorflow,jalexvig/tensorflow,AnishShah/tensorflow,av8ramit/tensorflow,jwlawson/tensorflow,benoitsteiner/tensorflow-xsmm,yanchen036/tensorflow,nolanliou/tensorflow,lakshayg/tensorflow,xzturn/tensorflow,xzturn/tensorflow,arborh/tensorflow,eaplatanios/tensorflow,kevin-coder/tensorflow-fork,dendisuhubdy/tensorflow,hsaputra/tensorflow,karllessard/tensorflow,allenlavoie/tensorflow,jwlawson/tensorflow,meteorcloudy/tensorflow,aselle/tensorflow,hsaputra/tensorflow,DavidNorman/tensorflow,seanli9jan/tensorflow,ppwwyyxx/tensorflow,lukeiwanski/tensorflow,kobejean/tensorflow,benoitsteiner/tensorflow-xsmm,aselle/tensorflow,gojira/tensorflow,renyi533/tensorflow,asimshankar/tensorflow,jendap/tensorflow,chemelnucfin/tensorflow,renyi533/tensorflow,gunan/tensorflow,petewarden/tensorflow,girving/tensorflow,Mistobaan/tensorflow,gojira/tensorflow,petewarden/tensorflow,Xeralux/tensorflow,freedomtan/tensorflow,gautam1858/tensorflow,davidzchen/tensorflow,yongtang/tensorflow,ravindrapanda/tensorflow,dendisuhubdy/tensorflow,adit-chandra/tensorflow,tensorflow/tensorflow,nburn42/tensorflow,tensorflow/tensorflow-pywrap_saved_model,xzturn/tensorflow,theflofly/tensorflow,Intel-Corporation/tensorflow,benoitsteiner/tensorflow-xsmm,ageron/tensorflow,aam-at/tensorflow,brchiu/tensorflow,Intel-tensorflow/tensorflow,cxxgtxy/tensorflow,kobejean/tensorflow,yanchen036/tensorflow,jalexvig/tensorflow,JingJunYin/tensorflow,alshedivat/tensorflow,xodus7/tensorflow,benoitsteiner/tensorflow-xsmm,nolanliou/tensorflow,gautam1858/tensorflow,meteorcloudy/tensorflow,rabipanda/tensorflow,dendisuhubdy/tensorflow,alshedivat/tensorflow,renyi533/tensorflow,snnn/tensorflow,kobejean/tensorflow,petewarden/tensorflow,dancingdan/tensorflow,hsaputra/tensorflow,rabipanda/tensorflow,kevin-coder/tensorflow-fork,Intel-tensorflow/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,alsrgv/tensorflow,alsrgv/tensorflow,arborh/tensorflow,jhseu/tensorflow,apark263/tensorflow,gautam1858/tensorflow,manipopopo/tensorflow,dongjoon-hyun/tensorflow,Mistobaan/tensorflow,allenlavoie/tensorflow,girving/tensorflow,renyi533/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,asimshankar/tensorflow,lukeiwanski/tensorflow,alsrgv/tensorflow,Xeralux/tensorflow,jendap/tensorflow,paolodedios/tensorflow,AnishShah/tensorflow,jwlawson/tensorflow,lukeiwanski/tensorflow,ppwwyyxx/tensorflow,frreiss/tensorflow-fred,renyi533/tensorflow,JingJunYin/tensorflow,tensorflow/tensorflow-pywrap_saved_model,xodus7/tensorflow,nburn42/tensorflow,alsrgv/tensorflow,chemelnucfin/tensorflow,allenlavoie/tensorflow,aldian/tensorflow,freedomtan/tensorflow,alshedivat/tensorflow,xzturn/tensorflow,adit-chandra/tensorflow,jbedorf/tensorflow,annarev/tensorflow,karllessard/tensorflow,Mistobaan/tensorflow,chemelnucfin/tensorflow,adit-chandra/tensorflow,theflofly/tensorflow,dongjoon-hyun/tensorflow,zasdfgbnm/tensorflow,jalexvig/tensorflow,aselle/tensorflow,annarev/tensorflow,zasdfgbnm/tensorflow,nburn42/tensorflow,jart/tensorflow,hfp/tensorflow-xsmm,annarev/tensorflow,av8ramit/tensorflow,ZhangXinNan/tensorflow,av8ramit/tensorflow,Bismarrck/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,adit-chandra/tensorflow,manipopopo/tensorflow,paolodedios/tensorflow,codrut3/tensorflow,allenlavoie/tensorflow,yanchen036/tensorflow,hsaputra/tensorflow,eadgarchen/tensorflow,gunan/tensorflow,brchiu/tensorflow,aselle/tensorflow,apark263/tensorflow,caisq/tensorflow,manipopopo/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,zasdfgbnm/tensorflow,girving/tensorflow,davidzchen/tensorflow,dongjoon-hyun/tensorflow,ppwwyyxx/tensorflow,arborh/tensorflow,Intel-tensorflow/tensorflow,renyi533/tensorflow,yanchen036/tensorflow,av8ramit/tensorflow,AnishShah/tensorflow,codrut3/tensorflow,davidzchen/tensorflow,jalexvig/tensorflow,av8ramit/tensorflow,annarev/tensorflow,theflofly/tensorflow,codrut3/tensorflow,drpngx/tensorflow,manipopopo/tensorflow,tensorflow/tensorflow-pywrap_saved_model,karllessard/tensorflow,ageron/tensorflow,gunan/tensorflow,ravindrapanda/tensorflow,xodus7/tensorflow,eadgarchen/tensorflow,hehongliang/tensorflow,jwlawson/tensorflow,JingJunYin/tensorflow,jhseu/tensorflow,kevin-coder/tensorflow-fork,karllessard/tensorflow,eaplatanios/tensorflow,annarev/tensorflow,Intel-tensorflow/tensorflow,av8ramit/tensorflow,snnn/tensorflow,caisq/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,jart/tensorflow,Xeralux/tensorflow,meteorcloudy/tensorflow,allenlavoie/tensorflow,brchiu/tensorflow,snnn/tensorflow,dongjoon-hyun/tensorflow,AnishShah/tensorflow,benoitsteiner/tensorflow-xsmm,ppwwyyxx/tensorflow,codrut3/tensorflow,hfp/tensorflow-xsmm,kevin-coder/tensorflow-fork,jalexvig/tensorflow,tensorflow/tensorflow-pywrap_saved_model,arborh/tensorflow,drpngx/tensorflow,alsrgv/tensorflow,alsrgv/tensorflow,lukeiwanski/tensorflow,petewarden/tensorflow,kevin-coder/tensorflow-fork,jhseu/tensorflow,jalexvig/tensorflow,paolodedios/tensorflow,ageron/tensorflow,apark263/tensorflow,arborh/tensorflow,nburn42/tensorflow,davidzchen/tensorflow,benoitsteiner/tensorflow-xsmm,gautam1858/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,manipopopo/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,ghchinoy/tensorflow,tensorflow/tensorflow,drpngx/tensorflow,nburn42/tensorflow,alshedivat/tensorflow,jhseu/tensorflow,kobejean/tensorflow,gojira/tensorflow,JingJunYin/tensorflow,Intel-tensorflow/tensorflow,chemelnucfin/tensorflow,codrut3/tensorflow,ghchinoy/tensorflow,kobejean/tensorflow,Bismarrck/tensorflow,hfp/tensorflow-xsmm,gunan/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,Mistobaan/tensorflow,davidzchen/tensorflow,jbedorf/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,Mistobaan/tensorflow,Mistobaan/tensorflow,aldian/tensorflow,dancingdan/tensorflow,brchiu/tensorflow,gojira/tensorflow,jbedorf/tensorflow,ppwwyyxx/tensorflow,hsaputra/tensorflow,asimshankar/tensorflow,eaplatanios/tensorflow,jhseu/tensorflow,yanchen036/tensorflow,cxxgtxy/tensorflow,gojira/tensorflow,ageron/tensorflow,aam-at/tensorflow,zasdfgbnm/tensorflow,tensorflow/tensorflow,hsaputra/tensorflow,hsaputra/tensorflow,xzturn/tensorflow,aldian/tensorflow,manipopopo/tensorflow,petewarden/tensorflow,yongtang/tensorflow,freedomtan/tensorflow,ppwwyyxx/tensorflow,rabipanda/tensorflow,snnn/tensorflow,Intel-Corporation/tensorflow,davidzchen/tensorflow,ZhangXinNan/tensorflow,aam-at/tensorflow,jalexvig/tensorflow,annarev/tensorflow,tensorflow/tensorflow-pywrap_saved_model,nburn42/tensorflow,brchiu/tensorflow,paolodedios/tensorflow,JingJunYin/tensorflow,cxxgtxy/tensorflow,DavidNorman/tensorflow,ZhangXinNan/tensorflow,Intel-tensorflow/tensorflow,hfp/tensorflow-xsmm,ravindrapanda/tensorflow,theflofly/tensorflow,jendap/tensorflow,jwlawson/tensorflow,girving/tensorflow,ageron/tensorflow,Xeralux/tensorflow,chemelnucfin/tensorflow,Intel-tensorflow/tensorflow,tensorflow/tensorflow,tensorflow/tensorflow,seanli9jan/tensorflow,zasdfgbnm/tensorflow,allenlavoie/tensorflow,jendap/tensorflow,nolanliou/tensorflow,Intel-tensorflow/tensorflow,yanchen036/tensorflow,xodus7/tensorflow,ppwwyyxx/tensorflow,meteorcloudy/tensorflow,gautam1858/tensorflow,zasdfgbnm/tensorflow,jart/tensorflow,xzturn/tensorflow,seanli9jan/tensorflow,jwlawson/tensorflow,eadgarchen/tensorflow,nburn42/tensorflow,rabipanda/tensorflow,jbedorf/tensorflow,freedomtan/tensorflow,tensorflow/tensorflow-pywrap_saved_model,Bismarrck/tensorflow,DavidNorman/tensorflow,freedomtan/tensorflow,cxxgtxy/tensorflow,JingJunYin/tensorflow,tensorflow/tensorflow,gautam1858/tensorflow,seanli9jan/tensorflow,ZhangXinNan/tensorflow,jendap/tensorflow,annarev/tensorflow,sarvex/tensorflow,caisq/tensorflow,nburn42/tensorflow,meteorcloudy/tensorflow,sarvex/tensorflow,snnn/tensorflow,Bismarrck/tensorflow,caisq/tensorflow,yanchen036/tensorflow,ravindrapanda/tensorflow,dendisuhubdy/tensorflow,hfp/tensorflow-xsmm,allenlavoie/tensorflow,jendap/tensorflow,jhseu/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,jwlawson/tensorflow,ghchinoy/tensorflow,gunan/tensorflow,ageron/tensorflow,frreiss/tensorflow-fred,aselle/tensorflow,Intel-Corporation/tensorflow,eaplatanios/tensorflow,ZhangXinNan/tensorflow,jhseu/tensorflow,ageron/tensorflow,gautam1858/tensorflow,hfp/tensorflow-xsmm,drpngx/tensorflow,jalexvig/tensorflow,ravindrapanda/tensorflow,cxxgtxy/tensorflow,adit-chandra/tensorflow,eaplatanios/tensorflow,AnishShah/tensorflow,apark263/tensorflow,freedomtan/tensorflow,Xeralux/tensorflow,dongjoon-hyun/tensorflow,girving/tensorflow,chemelnucfin/tensorflow,aselle/tensorflow,caisq/tensorflow,petewarden/tensorflow,caisq/tensorflow,apark263/tensorflow,seanli9jan/tensorflow,renyi533/tensorflow,eadgarchen/tensorflow,ppwwyyxx/tensorflow,frreiss/tensorflow-fred,sarvex/tensorflow,xodus7/tensorflow,tensorflow/tensorflow-pywrap_saved_model,xzturn/tensorflow,eaplatanios/tensorflow,girving/tensorflow,Bismarrck/tensorflow,gautam1858/tensorflow,benoitsteiner/tensorflow-xsmm,gautam1858/tensorflow,ZhangXinNan/tensorflow,aldian/tensorflow,snnn/tensorflow,hehongliang/tensorflow,AnishShah/tensorflow,gautam1858/tensorflow,Bismarrck/tensorflow,alshedivat/tensorflow,theflofly/tensorflow,Bismarrck/tensorflow,ppwwyyxx/tensorflow,xzturn/tensorflow,aldian/tensorflow,kevin-coder/tensorflow-fork,alsrgv/tensorflow,ZhangXinNan/tensorflow,davidzchen/tensorflow,eadgarchen/tensorflow,gojira/tensorflow,yongtang/tensorflow,karllessard/tensorflow,kobejean/tensorflow,gunan/tensorflow,frreiss/tensorflow-fred,tensorflow/tensorflow-experimental_link_static_libraries_once,arborh/tensorflow,frreiss/tensorflow-fred,jbedorf/tensorflow,aam-at/tensorflow,hehongliang/tensorflow,dendisuhubdy/tensorflow,karllessard/tensorflow,frreiss/tensorflow-fred,asimshankar/tensorflow,adit-chandra/tensorflow,aam-at/tensorflow,kevin-coder/tensorflow-fork,gojira/tensorflow,gojira/tensorflow,JingJunYin/tensorflow,apark263/tensorflow,kevin-coder/tensorflow-fork,annarev/tensorflow,jendap/tensorflow,dongjoon-hyun/tensorflow,hehongliang/tensorflow,seanli9jan/tensorflow,yongtang/tensorflow,xzturn/tensorflow,renyi533/tensorflow,paolodedios/tensorflow,theflofly/tensorflow,dendisuhubdy/tensorflow,asimshankar/tensorflow,eadgarchen/tensorflow,paolodedios/tensorflow,caisq/tensorflow,meteorcloudy/tensorflow,AnishShah/tensorflow,brchiu/tensorflow,jalexvig/tensorflow,alsrgv/tensorflow,kobejean/tensorflow,davidzchen/tensorflow,jart/tensorflow,sarvex/tensorflow,freedomtan/tensorflow,Xeralux/tensorflow,zasdfgbnm/tensorflow,meteorcloudy/tensorflow,hsaputra/tensorflow,dancingdan/tensorflow,paolodedios/tensorflow,snnn/tensorflow,ghchinoy/tensorflow,rabipanda/tensorflow,jhseu/tensorflow,karllessard/tensorflow,nolanliou/tensorflow,yongtang/tensorflow,DavidNorman/tensorflow,zasdfgbnm/tensorflow,karllessard/tensorflow,dongjoon-hyun/tensorflow,davidzchen/tensorflow,codrut3/tensorflow,chemelnucfin/tensorflow,eadgarchen/tensorflow,asimshankar/tensorflow,hehongliang/tensorflow,xzturn/tensorflow,DavidNorman/tensorflow,aselle/tensorflow,renyi533/tensorflow,zasdfgbnm/tensorflow,aselle/tensorflow,ghchinoy/tensorflow,apark263/tensorflow,ZhangXinNan/tensorflow,sarvex/tensorflow,girving/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,meteorcloudy/tensorflow,jwlawson/tensorflow,drpngx/tensorflow,benoitsteiner/tensorflow-xsmm,av8ramit/tensorflow,eaplatanios/tensorflow,Mistobaan/tensorflow,lukeiwanski/tensorflow,drpngx/tensorflow,rabipanda/tensorflow,theflofly/tensorflow,apark263/tensorflow,lukeiwanski/tensorflow,dendisuhubdy/tensorflow,asimshankar/tensorflow,dancingdan/tensorflow,ageron/tensorflow,tensorflow/tensorflow,nolanliou/tensorflow,Mistobaan/tensorflow,kevin-coder/tensorflow-fork,snnn/tensorflow,jbedorf/tensorflow,sarvex/tensorflow,asimshankar/tensorflow,xzturn/tensorflow,petewarden/tensorflow,jart/tensorflow,codrut3/tensorflow,manipopopo/tensorflow,xodus7/tensorflow,codrut3/tensorflow,av8ramit/tensorflow,kevin-coder/tensorflow-fork,hfp/tensorflow-xsmm,nolanliou/tensorflow,aselle/tensorflow,eadgarchen/tensorflow,lakshayg/tensorflow,brchiu/tensorflow,manipopopo/tensorflow,Intel-Corporation/tensorflow,snnn/tensorflow,girving/tensorflow,ghchinoy/tensorflow,jwlawson/tensorflow,girving/tensorflow,manipopopo/tensorflow,jbedorf/tensorflow,arborh/tensorflow,Bismarrck/tensorflow,lukeiwanski/tensorflow,tensorflow/tensorflow-pywrap_saved_model,benoitsteiner/tensorflow-xsmm,jart/tensorflow,theflofly/tensorflow,allenlavoie/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,eaplatanios/tensorflow,girving/tensorflow,Xeralux/tensorflow,theflofly/tensorflow,DavidNorman/tensorflow,zasdfgbnm/tensorflow,tensorflow/tensorflow,alshedivat/tensorflow,aam-at/tensorflow,DavidNorman/tensorflow,chemelnucfin/tensorflow,av8ramit/tensorflow,benoitsteiner/tensorflow-xsmm,tensorflow/tensorflow-experimental_link_static_libraries_once,yongtang/tensorflow,sarvex/tensorflow,gunan/tensorflow,lakshayg/tensorflow,petewarden/tensorflow,Intel-Corporation/tensorflow,chemelnucfin/tensorflow,davidzchen/tensorflow,gunan/tensorflow,jbedorf/tensorflow,alshedivat/tensorflow,ghchinoy/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,dongjoon-hyun/tensorflow,kevin-coder/tensorflow-fork,hfp/tensorflow-xsmm,arborh/tensorflow,adit-chandra/tensorflow,DavidNorman/tensorflow,jbedorf/tensorflow,ghchinoy/tensorflow,yongtang/tensorflow,AnishShah/tensorflow,petewarden/tensorflow,chemelnucfin/tensorflow,lukeiwanski/tensorflow,ghchinoy/tensorflow,arborh/tensorflow
76fc40f8bf16110ff62b81f74650474d763fc97f
src/Modules/Legacy/Fields/CompositeModuleTestGFB_FM.cc
src/Modules/Legacy/Fields/CompositeModuleTestGFB_FM.cc
/* For more information, please see: http://software.sci.utah.edu The MIT License Copyright (c) 2020 Scientific Computing and Imaging Institute, University of Utah. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include <Dataflow/Network/NetworkInterface.h> #include <Modules/Legacy/Fields/CompositeModuleTestGFB_FM.h> #include <Modules/Legacy/Fields/FairMesh.h> #include <Modules/Legacy/Fields/GetFieldBoundary.h> // TODO #include <Dataflow/Serialization/Network/NetworkDescriptionSerialization.h> #include <Dataflow/Serialization/Network/NetworkXMLSerializer.h> #include <Dataflow/Serialization/Network/XMLSerializer.h> #include <Dataflow/Engine/Controller/NetworkEditorController.h> using namespace SCIRun::Modules::Fields; using namespace SCIRun; using namespace Dataflow::Networks; using namespace Dataflow::Engine; MODULE_INFO_DEF(CompositeModuleTestGFB_FM, MiscField, SCIRun) class Modules::Fields::CompositeModuleImpl { public: NetworkHandle subNet_; explicit CompositeModuleImpl(CompositeModuleTestGFB_FM* module) : module_(module) {} void initializeSubnet(); private: CompositeModuleTestGFB_FM* module_; }; CompositeModuleTestGFB_FM::CompositeModuleTestGFB_FM() : Module(staticInfo_, false), impl_(new CompositeModuleImpl(this)) { INITIALIZE_PORT(InputField) INITIALIZE_PORT(Faired_Mesh) INITIALIZE_PORT(Mapping) } CompositeModuleTestGFB_FM::~CompositeModuleTestGFB_FM() = default; void CompositeModuleTestGFB_FM::setStateDefaults() { auto state = get_state(); /* state->setValue(Variables::FunctionString, std::string( "<?xml version="1.0" encoding="UTF-8" standalone="yes" ?> <!DOCTYPE boost_serialization> <boost_serialization signature="serialization::archive" version="18"> <networkFragment class_id="0" tracking_level="0" version="6"> <networkInfo class_id="1" tracking_level="0" version="0"> <modules class_id="2" tracking_level="0" version="0"> <count>2</count> <item_version>0</item_version> <item class_id="3" tracking_level="0" version="0"> <first>FairMesh:0</first> <second class_id="4" tracking_level="0" version="0"> <module class_id="5" tracking_level="0" version="0"> <package_name_>SCIRun</package_name_> <category_name_>NewField</category_name_> <module_name_>FairMesh</module_name_> </module> <state class_id="6" tracking_level="0" version="0"> <stateMap class_id="7" tracking_level="0" version="0"> <count>5</count> <item_version>0</item_version> <item class_id="8" tracking_level="0" version="0"> <first class_id="9" tracking_level="0" version="0"> <name>FairMeshMethod</name> </first> <second class_id="10" tracking_level="0" version="0"> <name>FairMeshMethod</name> <value class_id="11" tracking_level="1" version="0" object_id="_0"> <which>2</which> <value>fast</value> </value> </second> </item> <item> <first> <name>FilterCutoff</name> </first> <second> <name>FilterCutoff</name> <value object_id="_1"> <which>1</which> <value>1.00000000000000006e-01</value> </value> </second> </item> <item> <first> <name>Lambda</name> </first> <second> <name>Lambda</name> <value object_id="_2"> <which>1</which> <value>6.30700000000000038e-01</value> </value> </second> </item> <item> <first> <name>NumIterations</name> </first> <second> <name>NumIterations</name> <value object_id="_3"> <which>0</which> <value>50</value> </value> </second> </item> <item> <first> <name>ProgrammableInputPortEnabled</name> </first> <second> <name>ProgrammableInputPortEnabled</name> <value object_id="_4"> <which>3</which> <value>0</value> </value> </second> </item> </stateMap> </state> </second> </item> <item> <first>GetFieldBoundary:0</first> <second> <module> <package_name_>SCIRun</package_name_> <category_name_>NewField</category_name_> <module_name_>GetFieldBoundary</module_name_> </module> <state> <stateMap> <count>1</count> <item_version>0</item_version> <item> <first> <name>ProgrammableInputPortEnabled</name> </first> <second> <name>ProgrammableInputPortEnabled</name> <value object_id="_5"> <which>3</which> <value>0</value> </value> </second> </item> </stateMap> </state> </second> </item> </modules> <connections class_id="12" tracking_level="0" version="0"> <count>1</count> <item_version>0</item_version> <item class_id="13" tracking_level="0" version="0"> <moduleId1_>GetFieldBoundary:0</moduleId1_> <port1_ class_id="14" tracking_level="0" version="0"> <name>BoundaryField</name> <id>0</id> </port1_> <moduleId2_>FairMesh:0</moduleId2_> <port2_> <name>Input_Mesh</name> <id>0</id> </port2_> </item> </connections> </networkInfo> <modulePositions class_id="15" tracking_level="0" version="0"> <count>2</count> <item_version>0</item_version> <item class_id="16" tracking_level="0" version="0"> <first>FairMesh:0</first> <second class_id="17" tracking_level="0" version="0"> <first>-4.90000000000000000e+02</first> <second>-3.80000000000000000e+02</second> </second> </item> <item> <first>GetFieldBoundary:0</first> <second> <first>-5.32000000000000000e+02</first> <second>-4.56000000000000000e+02</second> </second> </item> </modulePositions> <moduleNotes class_id="18" tracking_level="0" version="0"> <count>0</count> <item_version>0</item_version> </moduleNotes> <connectionNotes> <count>0</count> <item_version>0</item_version> </connectionNotes> <moduleTags class_id="19" tracking_level="0" version="0"> <count>2</count> <item_version>0</item_version> <item class_id="20" tracking_level="0" version="0"> <first>FairMesh:0</first> <second>-1</second> </item> <item> <first>GetFieldBoundary:0</first> <second>-1</second> </item> </moduleTags> <disabledModules class_id="21" tracking_level="0" version="0"> <count>0</count> <item_version>0</item_version> </disabledModules> <disabledConnections> <count>0</count> <item_version>0</item_version> </disabledConnections> <moduleTagLabels class_id="22" tracking_level="0" version="0"> <count>0</count> <item_version>0</item_version> </moduleTagLabels> <loadTagGroups>0</loadTagGroups> <subnetworks class_id="23" tracking_level="0" version="0"> <count>0</count> <item_version>0</item_version> </subnetworks> </networkFragment> </boost_serialization> " )); */ } void CompositeModuleTestGFB_FM::execute() { impl_->initializeSubnet(); auto resultFuture = impl_->subNet_->executeAll(); resultFuture.wait(); const auto result = resultFuture.get(); if (result != 0) { error("Subnetwork returned error code " + std::to_string(result) + "."); } else { remark("Subnetwork executed successfully."); } } void CompositeModuleImpl::initializeSubnet() { if (!subNet_) { module_->remark("Basic composite module concept part 1"); subNet_ = module_->network()->createSubnetwork(); if (subNet_) { module_->remark("Subnet created."); } else { module_->error("Subnet null"); return; } if (!subNet_->getNetwork()) { module_->error("Subnet's network state is null"); return; } const auto xml = XMLSerializer::load_xml<NetworkFile>("X:\\Dev\\r1\\SCIRun\\Release\\xml1.txt"); subNet_->loadXmlDataIntoNetwork(xml->network.data()); const auto network = subNet_->getNetwork(); if (network->nmodules() == 2) { module_->remark("Created subnet with 2 modules"); } else { module_->error("Subnet missing modules"); return; } auto wrapperModuleInputs = module_->inputPorts(); auto wrapperModuleInputsIterator = wrapperModuleInputs.begin(); auto wrapperModuleOutputs = module_->outputPorts(); auto wrapperModuleOutputsIterator = wrapperModuleOutputs.begin(); for (size_t i = 0; i < network->nmodules(); ++i) { const auto subModule = network->module(i); for (const auto& inputPort : subModule->inputPorts()) { if (inputPort->nconnections() == 0 && inputPort->get_typename() != "MetadataObject") { auto portId = inputPort->id(); logCritical("Found input port that can be exposed: {} :: {}", subModule->id().id_, portId.toString()); if (subModule->id().id_ == "GetFieldBoundary") { logCritical("\t\tperforming port surgery on {} {}", subModule->id().id_, portId.toString()); subModule->removeInputPort(portId); subModule->add_input_port(*wrapperModuleInputsIterator++); } } } for (const auto& outputPort : subModule->outputPorts()) { if (outputPort->nconnections() == 0 && outputPort->get_typename() != "MetadataObject") { auto portId = outputPort->id(); logCritical("Found output port that can be exposed: {} :: {}", subModule->id().id_, portId.toString()); if (auto* const fm = dynamic_cast<FairMesh*>(subModule.get())) { logCritical("\t\tperforming port surgery on {} {}", subModule->id().id_, portId.toString()); fm->removeOutputPort(portId); fm->add_output_port(*wrapperModuleOutputsIterator++); } if (auto* const gfb = dynamic_cast<GetFieldBoundary*>(subModule.get())) { logCritical("\t\tperforming port surgery on {} {}", subModule->id().id_, portId.toString()); gfb->removeOutputPort(portId); gfb->add_output_port(*wrapperModuleOutputsIterator++); } } } } if (subNet_->getNetwork()->nconnections() == 1) { module_->remark("Created connection between 2 modules"); } else { module_->error("Connection error"); } } }
/* For more information, please see: http://software.sci.utah.edu The MIT License Copyright (c) 2020 Scientific Computing and Imaging Institute, University of Utah. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include <Dataflow/Network/NetworkInterface.h> #include <Modules/Legacy/Fields/CompositeModuleTestGFB_FM.h> // TODO #include <Dataflow/Serialization/Network/NetworkDescriptionSerialization.h> #include <Dataflow/Serialization/Network/NetworkXMLSerializer.h> #include <Dataflow/Serialization/Network/XMLSerializer.h> #include <Dataflow/Engine/Controller/NetworkEditorController.h> using namespace SCIRun::Modules::Fields; using namespace SCIRun; using namespace Dataflow::Networks; using namespace Dataflow::Engine; MODULE_INFO_DEF(CompositeModuleTestGFB_FM, MiscField, SCIRun) class Modules::Fields::CompositeModuleImpl { public: NetworkHandle subNet_; explicit CompositeModuleImpl(CompositeModuleTestGFB_FM* module) : module_(module) {} void initializeSubnet(); private: CompositeModuleTestGFB_FM* module_; }; CompositeModuleTestGFB_FM::CompositeModuleTestGFB_FM() : Module(staticInfo_, false), impl_(new CompositeModuleImpl(this)) { INITIALIZE_PORT(InputField) INITIALIZE_PORT(Faired_Mesh) INITIALIZE_PORT(Mapping) } CompositeModuleTestGFB_FM::~CompositeModuleTestGFB_FM() = default; void CompositeModuleTestGFB_FM::setStateDefaults() { auto state = get_state(); /* state->setValue(Variables::FunctionString, std::string( "<?xml version="1.0" encoding="UTF-8" standalone="yes" ?> <!DOCTYPE boost_serialization> <boost_serialization signature="serialization::archive" version="18"> <networkFragment class_id="0" tracking_level="0" version="6"> <networkInfo class_id="1" tracking_level="0" version="0"> <modules class_id="2" tracking_level="0" version="0"> <count>2</count> <item_version>0</item_version> <item class_id="3" tracking_level="0" version="0"> <first>FairMesh:0</first> <second class_id="4" tracking_level="0" version="0"> <module class_id="5" tracking_level="0" version="0"> <package_name_>SCIRun</package_name_> <category_name_>NewField</category_name_> <module_name_>FairMesh</module_name_> </module> <state class_id="6" tracking_level="0" version="0"> <stateMap class_id="7" tracking_level="0" version="0"> <count>5</count> <item_version>0</item_version> <item class_id="8" tracking_level="0" version="0"> <first class_id="9" tracking_level="0" version="0"> <name>FairMeshMethod</name> </first> <second class_id="10" tracking_level="0" version="0"> <name>FairMeshMethod</name> <value class_id="11" tracking_level="1" version="0" object_id="_0"> <which>2</which> <value>fast</value> </value> </second> </item> <item> <first> <name>FilterCutoff</name> </first> <second> <name>FilterCutoff</name> <value object_id="_1"> <which>1</which> <value>1.00000000000000006e-01</value> </value> </second> </item> <item> <first> <name>Lambda</name> </first> <second> <name>Lambda</name> <value object_id="_2"> <which>1</which> <value>6.30700000000000038e-01</value> </value> </second> </item> <item> <first> <name>NumIterations</name> </first> <second> <name>NumIterations</name> <value object_id="_3"> <which>0</which> <value>50</value> </value> </second> </item> <item> <first> <name>ProgrammableInputPortEnabled</name> </first> <second> <name>ProgrammableInputPortEnabled</name> <value object_id="_4"> <which>3</which> <value>0</value> </value> </second> </item> </stateMap> </state> </second> </item> <item> <first>GetFieldBoundary:0</first> <second> <module> <package_name_>SCIRun</package_name_> <category_name_>NewField</category_name_> <module_name_>GetFieldBoundary</module_name_> </module> <state> <stateMap> <count>1</count> <item_version>0</item_version> <item> <first> <name>ProgrammableInputPortEnabled</name> </first> <second> <name>ProgrammableInputPortEnabled</name> <value object_id="_5"> <which>3</which> <value>0</value> </value> </second> </item> </stateMap> </state> </second> </item> </modules> <connections class_id="12" tracking_level="0" version="0"> <count>1</count> <item_version>0</item_version> <item class_id="13" tracking_level="0" version="0"> <moduleId1_>GetFieldBoundary:0</moduleId1_> <port1_ class_id="14" tracking_level="0" version="0"> <name>BoundaryField</name> <id>0</id> </port1_> <moduleId2_>FairMesh:0</moduleId2_> <port2_> <name>Input_Mesh</name> <id>0</id> </port2_> </item> </connections> </networkInfo> <modulePositions class_id="15" tracking_level="0" version="0"> <count>2</count> <item_version>0</item_version> <item class_id="16" tracking_level="0" version="0"> <first>FairMesh:0</first> <second class_id="17" tracking_level="0" version="0"> <first>-4.90000000000000000e+02</first> <second>-3.80000000000000000e+02</second> </second> </item> <item> <first>GetFieldBoundary:0</first> <second> <first>-5.32000000000000000e+02</first> <second>-4.56000000000000000e+02</second> </second> </item> </modulePositions> <moduleNotes class_id="18" tracking_level="0" version="0"> <count>0</count> <item_version>0</item_version> </moduleNotes> <connectionNotes> <count>0</count> <item_version>0</item_version> </connectionNotes> <moduleTags class_id="19" tracking_level="0" version="0"> <count>2</count> <item_version>0</item_version> <item class_id="20" tracking_level="0" version="0"> <first>FairMesh:0</first> <second>-1</second> </item> <item> <first>GetFieldBoundary:0</first> <second>-1</second> </item> </moduleTags> <disabledModules class_id="21" tracking_level="0" version="0"> <count>0</count> <item_version>0</item_version> </disabledModules> <disabledConnections> <count>0</count> <item_version>0</item_version> </disabledConnections> <moduleTagLabels class_id="22" tracking_level="0" version="0"> <count>0</count> <item_version>0</item_version> </moduleTagLabels> <loadTagGroups>0</loadTagGroups> <subnetworks class_id="23" tracking_level="0" version="0"> <count>0</count> <item_version>0</item_version> </subnetworks> </networkFragment> </boost_serialization> " )); */ } void CompositeModuleTestGFB_FM::execute() { impl_->initializeSubnet(); auto resultFuture = impl_->subNet_->executeAll(); resultFuture.wait(); const auto result = resultFuture.get(); if (result != 0) { error("Subnetwork returned error code " + std::to_string(result) + "."); } else { remark("Subnetwork executed successfully."); } } void CompositeModuleImpl::initializeSubnet() { if (!subNet_) { module_->remark("Basic composite module concept part 1"); subNet_ = module_->network()->createSubnetwork(); if (subNet_) { module_->remark("Subnet created."); } else { module_->error("Subnet null"); return; } if (!subNet_->getNetwork()) { module_->error("Subnet's network state is null"); return; } const auto xml = XMLSerializer::load_xml<NetworkFile>("X:\\Dev\\r1\\SCIRun\\Release\\xml1.txt"); subNet_->loadXmlDataIntoNetwork(xml->network.data()); const auto network = subNet_->getNetwork(); if (network->nmodules() == 2) { module_->remark("Created subnet with 2 modules"); } else { module_->error("Subnet missing modules"); return; } auto wrapperModuleInputs = module_->inputPorts(); auto wrapperModuleInputsIterator = wrapperModuleInputs.begin(); auto wrapperModuleOutputs = module_->outputPorts(); auto wrapperModuleOutputsIterator = wrapperModuleOutputs.begin(); for (size_t i = 0; i < network->nmodules(); ++i) { const auto subModule = network->module(i); for (const auto& inputPort : subModule->inputPorts()) { if (inputPort->nconnections() == 0 && inputPort->get_typename() != "MetadataObject") { auto portId = inputPort->id(); logCritical("Found input port that can be exposed: {} :: {}", subModule->id().id_, portId.toString()); if (wrapperModuleInputsIterator != wrapperModuleInputs.end()) { logCritical("\t\tperforming port surgery on {} {}", subModule->id().id_, portId.toString()); subModule->removeInputPort(portId); subModule->add_input_port(*wrapperModuleInputsIterator++); } } } for (const auto& outputPort : subModule->outputPorts()) { if (outputPort->nconnections() == 0 && outputPort->get_typename() != "MetadataObject") { auto portId = outputPort->id(); logCritical("Found output port that can be exposed: {} :: {}", subModule->id().id_, portId.toString()); if (wrapperModuleOutputsIterator != wrapperModuleOutputs.end()) { logCritical("\t\tperforming port surgery on {} {}", subModule->id().id_, portId.toString()); subModule->removeOutputPort(portId); subModule->add_output_port(*wrapperModuleOutputsIterator++); } } } } if (subNet_->getNetwork()->nconnections() == 1) { module_->remark("Created connection between 2 modules"); } else { module_->error("Connection error"); } } }
Fix and remove links to concrete modules
Fix and remove links to concrete modules
C++
mit
jessdtate/SCIRun,jessdtate/SCIRun,jessdtate/SCIRun,jessdtate/SCIRun,jessdtate/SCIRun,jessdtate/SCIRun,jessdtate/SCIRun,jessdtate/SCIRun
847869e129a0c63dd893cb895606b4b6b14afeec
module/gcommon/iostream/src/g_datainputstream.cpp
module/gcommon/iostream/src/g_datainputstream.cpp
/************************************************************************************ ** * @copyright (c) 2013-2100, ChengDu Duyer Technology Co., LTD. All Right Reserved. * *************************************************************************************/ /** * @file g_datainputstream.cpp * @version * @brief * @author ylh * @date 2014-07-08 * @note * * 1. 2014-07-08 ylh Created this file * */ #include <g_datainputstream.h> #include <g_private_define.h> using namespace std; using namespace GCommon; DataInputStream::DataInputStream(std::shared_ptr<InputStream> in) : FilterInputStream(in) { } DataInputStream::~DataInputStream() { } int DataInputStream::readToBuff(int count) { if (count > MAX_BUFFER_SIZE) { return -2; } int offset = 0; while(offset < count) { int bytesRead = read(m_buffer, MAX_BUFFER_SIZE, offset, count - offset); if(bytesRead == -1) return bytesRead; offset += bytesRead; } return offset; } bool DataInputStream::readBool() throw(std::ios_base::failure) { GInt32 iTmp = read(); if (iTmp < 0) { throw ios_base::failure(EXCEPTION_DESCRIPTION("ios_base::failure")); } return (iTmp != 0); } GInt8 DataInputStream::readChar() throw(std::ios_base::failure) { return read(); } GInt16 DataInputStream::readShort() throw(std::ios_base::failure) { if (readToBuff(2) < 0) { return -1; } return static_cast<GInt16>(((m_buffer[0] & 0xff) << 8) | (m_buffer[1] & 0xff)); } GInt32 DataInputStream::readInt() throw(std::ios_base::failure) { if (readToBuff(4) < 0) { return -1; } return static_cast<GInt32>(((m_buffer[0] & 0xff) << 24) | ((m_buffer[1] & 0xff) << 16) | ((m_buffer[2] & 0xff) << 8) | (m_buffer[3] & 0xff)); } GInt64 DataInputStream::readLong() throw(std::ios_base::failure) { if (readToBuff(8) < 0) { return -1; } GInt64 i1 = static_cast<GInt64>(((m_buffer[0] & 0xff) << 24) | ((m_buffer[1] & 0xff) << 16) | ((m_buffer[2] & 0xff) << 8) | (m_buffer[3] & 0xff)); GInt64 i2 = static_cast<GInt64>(((m_buffer[4] & 0xff) << 24) | ((m_buffer[5] & 0xff) << 16) | ((m_buffer[6] & 0xff) << 8) | (m_buffer[7] & 0xff)); return static_cast<GInt64>(((i1 & 0xffffffffL) << 32) |(i2 & 0xffffffffL)); } GUint8 DataInputStream::readUnsignedChar() throw(std::ios_base::failure) { return static_cast<GUint8>(read()); } GUint16 DataInputStream::readUnsignedShort() throw(std::ios_base::failure) { if (readToBuff(2) < 0) { return -1; } return static_cast<GUint16>(((m_buffer[0] & 0xff) << 8) | (m_buffer[1] & 0xff)); } GUint32 DataInputStream::readUnsignedInt() throw(std::ios_base::failure) { if (readToBuff(4) < 0) { return -1; } return static_cast<GUint32>(((m_buffer[0] & 0xff) << 24) | ((m_buffer[1] & 0xff) << 16) | ((m_buffer[2] & 0xff) << 8) | (m_buffer[3] & 0xff)); } GUint64 DataInputStream::readUnsignedLong() throw(std::ios_base::failure) { if (readToBuff(8) < 0) { return -1; } GUint64 i1 = static_cast<GUint64>(((m_buffer[0] & 0xff) << 24) | ((m_buffer[1] & 0xff) << 16) | ((m_buffer[2] & 0xff) << 8) | (m_buffer[3] & 0xff)); GUint64 i2 = static_cast<GUint64>(((m_buffer[4] & 0xff) << 24) | ((m_buffer[5] & 0xff) << 16) | ((m_buffer[6] & 0xff) << 8) | (m_buffer[7] & 0xff)); return static_cast<GUint64>(((i1 & 0xffffffffUL) << 32) |(i2 & 0xffffffffUL)); } std::string DataInputStream::readLine() throw(std::ios_base::failure) { } void DataInputStream::readFully(GInt8* pBuffer, GInt32 iBufferLen) throw(std::ios_base::failure) { readFully(pBuffer, iBufferLen, 0, iBufferLen); } void DataInputStream::readFully(GInt8* pBuffer, GInt32 iBufferLen, GInt32 iOff, GInt32 iLen) throw(std::ios_base::failure) { if (!pBuffer || iBufferLen < 0 || iOff < 0 || iLen < 0) { return; } while (iLen > 0) { GInt32 iNumRead = read(pBuffer, iBufferLen, iOff, iLen); if (iNumRead < 0) { return; } iLen -= iNumRead; iOff += iNumRead; } }
/************************************************************************************ ** * @copyright (c) 2013-2100, ChengDu Duyer Technology Co., LTD. All Right Reserved. * *************************************************************************************/ /** * @file g_datainputstream.cpp * @version * @brief * @author ylh * @date 2014-07-08 * @note * * 1. 2014-07-08 ylh Created this file * */ #include <g_datainputstream.h> #include <g_private_define.h> using namespace std; using namespace GCommon; DataInputStream::DataInputStream(std::shared_ptr<InputStream> in) : FilterInputStream(in) { } DataInputStream::~DataInputStream() { } int DataInputStream::readToBuff(int count) { if (count > MAX_BUFFER_SIZE) { return -2; } int offset = 0; while(offset < count) { int bytesRead = read(m_buffer, MAX_BUFFER_SIZE, offset, count - offset); if(bytesRead == -1) return bytesRead; offset += bytesRead; } return offset; } bool DataInputStream::readBool() throw(std::ios_base::failure) { GInt32 iTmp = read(); if (iTmp < 0) { throw ios_base::failure(EXCEPTION_DESCRIPTION("ios_base::failure")); } return (iTmp != 0); } GInt8 DataInputStream::readChar() throw(std::ios_base::failure) { return read(); } GInt16 DataInputStream::readShort() throw(std::ios_base::failure) { if (readToBuff(2) < 0) { return -1; } return static_cast<GInt16>(((m_buffer[0] & 0xff) << 8) | (m_buffer[1] & 0xff)); } GInt32 DataInputStream::readInt() throw(std::ios_base::failure) { if (readToBuff(4) < 0) { return -1; } return static_cast<GInt32>(((m_buffer[0] & 0xff) << 24) | ((m_buffer[1] & 0xff) << 16) | ((m_buffer[2] & 0xff) << 8) | (m_buffer[3] & 0xff)); } GInt64 DataInputStream::readLong() throw(std::ios_base::failure) { if (readToBuff(8) < 0) { return -1; } GInt64 i1 = static_cast<GInt64>(((m_buffer[0] & 0xff) << 24) | ((m_buffer[1] & 0xff) << 16) | ((m_buffer[2] & 0xff) << 8) | (m_buffer[3] & 0xff)); GInt64 i2 = static_cast<GInt64>(((m_buffer[4] & 0xff) << 24) | ((m_buffer[5] & 0xff) << 16) | ((m_buffer[6] & 0xff) << 8) | (m_buffer[7] & 0xff)); return static_cast<GInt64>(((i1 & 0xffffffffL) << 32) |(i2 & 0xffffffffL)); } GUint8 DataInputStream::readUnsignedChar() throw(std::ios_base::failure) { return static_cast<GUint8>(read()); } GUint16 DataInputStream::readUnsignedShort() throw(std::ios_base::failure) { if (readToBuff(2) < 0) { return -1; } return static_cast<GUint16>(((m_buffer[0] & 0xff) << 8) | (m_buffer[1] & 0xff)); } GUint32 DataInputStream::readUnsignedInt() throw(std::ios_base::failure) { if (readToBuff(4) < 0) { return -1; } return static_cast<GUint32>(((m_buffer[0] & 0xff) << 24) | ((m_buffer[1] & 0xff) << 16) | ((m_buffer[2] & 0xff) << 8) | (m_buffer[3] & 0xff)); } GUint64 DataInputStream::readUnsignedLong() throw(std::ios_base::failure) { if (readToBuff(8) < 0) { return -1; } GUint64 i1 = static_cast<GUint64>(((m_buffer[0] & 0xff) << 24) | ((m_buffer[1] & 0xff) << 16) | ((m_buffer[2] & 0xff) << 8) | (m_buffer[3] & 0xff)); GUint64 i2 = static_cast<GUint64>(((m_buffer[4] & 0xff) << 24) | ((m_buffer[5] & 0xff) << 16) | ((m_buffer[6] & 0xff) << 8) | (m_buffer[7] & 0xff)); return static_cast<GUint64>(((i1 & 0xffffffffUL) << 32) |(i2 & 0xffffffffUL)); } std::string DataInputStream::readLine() throw(std::ios_base::failure) { } void DataInputStream::readFully(GInt8* pBuffer, GInt32 iBufferLen) throw(std::ios_base::failure, std::logic_error) { readFully(pBuffer, iBufferLen, 0, iBufferLen); } void DataInputStream::readFully(GInt8* pBuffer, GInt32 iBufferLen, GInt32 iOff, GInt32 iLen) throw(std::ios_base::failure) { if (!pBuffer) { throw invalid_argument(EXCEPTION_DESCRIPTION("invalid_argument")); } if (iBufferLen < 0 || iOff < 0 || iLen < 0) { throw out_of_range(EXCEPTION_DESCRIPTION("out_of_range")); } while (iLen > 0) { GInt32 iNumRead = read(pBuffer, iBufferLen, iOff, iLen); if (iNumRead < 0) { return; } iLen -= iNumRead; iOff += iNumRead; } }
Update g_datainputstream.cpp
Update g_datainputstream.cpp
C++
lgpl-2.1
SquareBrain/Gunhoop,SquareBrain/Gunhoop,SquareBrain/Gunhoop,SquareBrain/Gunhoop
7f92f80e59a32316f41bb8ad87b5360540e52d3e
arangod/RocksDBEngine/RocksDBKeyBounds.cpp
arangod/RocksDBEngine/RocksDBKeyBounds.cpp
//////////////////////////////////////////////////////////////////////////////// /// DISCLAIMER /// /// Copyright 2014-2017 ArangoDB GmbH, Cologne, Germany /// Copyright 2004-2014 triAGENS GmbH, Cologne, Germany /// /// 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. /// /// Copyright holder is ArangoDB GmbH, Cologne, Germany /// /// @author Jan Steemann /// @author Daniel H. Larkin //////////////////////////////////////////////////////////////////////////////// #include "RocksDBEngine/RocksDBKeyBounds.h" #include "Basics/Exceptions.h" #include "RocksDBEngine/RocksDBCommon.h" #include "RocksDBEngine/RocksDBTypes.h" #include "Logger/Logger.h" using namespace arangodb; using namespace arangodb::rocksutils; using namespace arangodb::velocypack; const char RocksDBKeyBounds::_stringSeparator = '\0'; RocksDBKeyBounds RocksDBKeyBounds::Empty() { return RocksDBKeyBounds(); } RocksDBKeyBounds RocksDBKeyBounds::Databases() { return RocksDBKeyBounds(RocksDBEntryType::Database); } RocksDBKeyBounds RocksDBKeyBounds::DatabaseCollections( TRI_voc_tick_t databaseId) { return RocksDBKeyBounds(RocksDBEntryType::Collection, databaseId); } RocksDBKeyBounds RocksDBKeyBounds::CollectionDocuments(uint64_t collectionObjectId) { return RocksDBKeyBounds(RocksDBEntryType::Document, collectionObjectId); } RocksDBKeyBounds RocksDBKeyBounds::PrimaryIndex(uint64_t indexId) { return RocksDBKeyBounds(RocksDBEntryType::PrimaryIndexValue, indexId); } RocksDBKeyBounds RocksDBKeyBounds::EdgeIndex(uint64_t indexId) { return RocksDBKeyBounds(RocksDBEntryType::EdgeIndexValue, indexId); } RocksDBKeyBounds RocksDBKeyBounds::EdgeIndexVertex( uint64_t indexId, arangodb::StringRef const& vertexId) { return RocksDBKeyBounds(RocksDBEntryType::EdgeIndexValue, indexId, vertexId); } RocksDBKeyBounds RocksDBKeyBounds::IndexEntries(uint64_t indexId) { return RocksDBKeyBounds(RocksDBEntryType::IndexValue, indexId); } RocksDBKeyBounds RocksDBKeyBounds::UniqueIndex(uint64_t indexId) { return RocksDBKeyBounds(RocksDBEntryType::UniqueIndexValue, indexId); } RocksDBKeyBounds RocksDBKeyBounds::IndexRange(uint64_t indexId, VPackSlice const& left, VPackSlice const& right) { return RocksDBKeyBounds(RocksDBEntryType::IndexValue, indexId, left, right); } RocksDBKeyBounds RocksDBKeyBounds::UniqueIndexRange(uint64_t indexId, VPackSlice const& left, VPackSlice const& right) { return RocksDBKeyBounds(RocksDBEntryType::UniqueIndexValue, indexId, left, right); } RocksDBKeyBounds RocksDBKeyBounds::DatabaseViews(TRI_voc_tick_t databaseId) { return RocksDBKeyBounds(RocksDBEntryType::View, databaseId); } RocksDBKeyBounds RocksDBKeyBounds::CounterValues() { return RocksDBKeyBounds(RocksDBEntryType::CounterValue); } RocksDBKeyBounds RocksDBKeyBounds::FulltextIndex(uint64_t indexId) { return RocksDBKeyBounds(RocksDBEntryType::FulltextIndexValue, indexId); } RocksDBKeyBounds RocksDBKeyBounds::FulltextIndexPrefix(uint64_t indexId, arangodb::StringRef const& word) { // I did not want to pass a bool to the constructor for this RocksDBKeyBounds bounds; size_t length = sizeof(char) + sizeof(uint64_t) + word.size(); bounds._startBuffer.reserve(length); bounds._startBuffer.push_back(static_cast<char>(RocksDBEntryType::FulltextIndexValue)); uint64ToPersistent(bounds._startBuffer, indexId); bounds._startBuffer.append(word.data(), word.length()); bounds._endBuffer.append(bounds._startBuffer); bounds._endBuffer.push_back(0xFF);// invalid UTF-8 character, higher than with memcmp return bounds; } RocksDBKeyBounds RocksDBKeyBounds::FulltextIndexComplete(uint64_t indexId, arangodb::StringRef const& word) { return RocksDBKeyBounds(RocksDBEntryType::FulltextIndexValue, indexId, word); } // ============================ Member Methods ============================== rocksdb::Slice const RocksDBKeyBounds::start() const { return rocksdb::Slice(_startBuffer); } rocksdb::Slice const RocksDBKeyBounds::end() const { return rocksdb::Slice(_endBuffer); } uint64_t RocksDBKeyBounds::objectId() const { RocksDBEntryType type = static_cast<RocksDBEntryType>(_startBuffer[0]); switch (type) { case RocksDBEntryType::Document: case RocksDBEntryType::PrimaryIndexValue: case RocksDBEntryType::EdgeIndexValue: case RocksDBEntryType::IndexValue: case RocksDBEntryType::UniqueIndexValue: { TRI_ASSERT(_startBuffer.size() >= (sizeof(char) + sizeof(uint64_t))); return uint64FromPersistent(_startBuffer.data() + sizeof(char)); } default: THROW_ARANGO_EXCEPTION(TRI_ERROR_TYPE_ERROR); } } // constructor for an empty bound. do not use for anything but to // default-construct a key bound! RocksDBKeyBounds::RocksDBKeyBounds() : _type(RocksDBEntryType::Database), _startBuffer(), _endBuffer() {} RocksDBKeyBounds::RocksDBKeyBounds(RocksDBEntryType type) : _type(type), _startBuffer(), _endBuffer() { switch (_type) { case RocksDBEntryType::Database: { size_t length = sizeof(char); _startBuffer.reserve(length); _startBuffer.push_back(static_cast<char>(_type)); _endBuffer.append(_startBuffer); nextPrefix(_endBuffer); break; } case RocksDBEntryType::CounterValue: { size_t length = sizeof(char) + sizeof(uint64_t); _startBuffer.reserve(length); _startBuffer.push_back(static_cast<char>(_type)); uint64ToPersistent(_startBuffer, 0); _endBuffer.reserve(length); _endBuffer.push_back(static_cast<char>(_type)); uint64ToPersistent(_endBuffer, UINT64_MAX); break; } default: THROW_ARANGO_EXCEPTION(TRI_ERROR_BAD_PARAMETER); } } RocksDBKeyBounds::RocksDBKeyBounds(RocksDBEntryType type, uint64_t first) : _type(type), _startBuffer(), _endBuffer() { switch (_type) { case RocksDBEntryType::IndexValue: case RocksDBEntryType::UniqueIndexValue: { // Unique VPack index values are stored as follows: // 7 + 8-byte object ID of index + VPack array with index value(s) .... // prefix is the same for non-unique indexes // static slices with an array with one entry VPackSlice min("\x02\x03\x1e");// [minSlice] VPackSlice max("\x02\x03\x1f");// [maxSlice] size_t length = sizeof(char) + sizeof(uint64_t) + min.byteSize(); _startBuffer.reserve(length); _startBuffer.push_back(static_cast<char>(_type)); uint64ToPersistent(_startBuffer, first); // append common prefix _endBuffer.clear(); _endBuffer.append(_startBuffer); // construct min max _startBuffer.append((char*)(min.begin()), min.byteSize()); _endBuffer.append((char*)(max.begin()), max.byteSize()); break; } case RocksDBEntryType::Collection: case RocksDBEntryType::Document:{ // Collections are stored as follows: // Key: 1 + 8-byte ArangoDB database ID + 8-byte ArangoDB collection ID // // Documents are stored as follows: // Key: 3 + 8-byte object ID of collection + 8-byte document revision ID size_t length = sizeof(char) + sizeof(uint64_t) * 2; _startBuffer.reserve(length); _startBuffer.push_back(static_cast<char>(_type)); uint64ToPersistent(_startBuffer, first); // append common prefix _endBuffer.clear(); _endBuffer.append(_startBuffer); // construct min max uint64ToPersistent(_startBuffer, 0); uint64ToPersistent(_endBuffer, UINT64_MAX); break; } case RocksDBEntryType::PrimaryIndexValue: case RocksDBEntryType::EdgeIndexValue: case RocksDBEntryType::View: case RocksDBEntryType::FulltextIndexValue: { size_t length = sizeof(char) + sizeof(uint64_t); _startBuffer.reserve(length); _startBuffer.push_back(static_cast<char>(_type)); uint64ToPersistent(_startBuffer, first); _endBuffer.clear(); _endBuffer.append(_startBuffer); nextPrefix(_endBuffer); break; } default: THROW_ARANGO_EXCEPTION(TRI_ERROR_BAD_PARAMETER); } } RocksDBKeyBounds::RocksDBKeyBounds(RocksDBEntryType type, uint64_t first, arangodb::StringRef const& second) : _type(type), _startBuffer(), _endBuffer() { switch (_type) { case RocksDBEntryType::FulltextIndexValue: case RocksDBEntryType::EdgeIndexValue: { size_t length = sizeof(char) + sizeof(uint64_t) + second.size() + sizeof(char); _startBuffer.reserve(length); _startBuffer.push_back(static_cast<char>(_type)); uint64ToPersistent(_startBuffer, first); _startBuffer.append(second.data(), second.length()); _startBuffer.push_back(_stringSeparator); _endBuffer.clear(); _endBuffer.append(_startBuffer); nextPrefix(_endBuffer); break; } default: THROW_ARANGO_EXCEPTION(TRI_ERROR_BAD_PARAMETER); } } RocksDBKeyBounds::RocksDBKeyBounds(RocksDBEntryType type, uint64_t first, VPackSlice const& second, VPackSlice const& third) : _type(type), _startBuffer(), _endBuffer() { switch (_type) { case RocksDBEntryType::IndexValue: case RocksDBEntryType::UniqueIndexValue: { size_t startLength = sizeof(char) + sizeof(uint64_t) + static_cast<size_t>(second.byteSize()) + sizeof(char); _startBuffer.reserve(startLength); _startBuffer.push_back(static_cast<char>(_type)); uint64ToPersistent(_startBuffer, first); _startBuffer.append(reinterpret_cast<char const*>(second.begin()), static_cast<size_t>(second.byteSize())); _startBuffer.push_back(_stringSeparator); TRI_ASSERT(_startBuffer.length() == startLength); size_t endLength = sizeof(char) + sizeof(uint64_t) + static_cast<size_t>(third.byteSize()) + sizeof(char); _endBuffer.reserve(endLength); _endBuffer.push_back(static_cast<char>(_type)); uint64ToPersistent(_endBuffer, first); _endBuffer.append(reinterpret_cast<char const*>(third.begin()), static_cast<size_t>(third.byteSize())); _endBuffer.push_back(_stringSeparator); nextPrefix(_endBuffer); break; } default: THROW_ARANGO_EXCEPTION(TRI_ERROR_BAD_PARAMETER); } } void RocksDBKeyBounds::nextPrefix(std::string& s) { TRI_ASSERT(s.size() >= 1); size_t i = s.size() - 1; for (; (i > 0) && (s[i] == '\xff'); --i) { } if ((i == 0) && (s[i] == '\xff')) { s.push_back('\x00'); return; } s[i] = static_cast<char>(static_cast<unsigned char>(s[i]) + 1); for (i = i + 1; i < s.size(); i++) { s[i] = '\x00'; } }
//////////////////////////////////////////////////////////////////////////////// /// DISCLAIMER /// /// Copyright 2014-2017 ArangoDB GmbH, Cologne, Germany /// Copyright 2004-2014 triAGENS GmbH, Cologne, Germany /// /// 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. /// /// Copyright holder is ArangoDB GmbH, Cologne, Germany /// /// @author Jan Steemann /// @author Daniel H. Larkin //////////////////////////////////////////////////////////////////////////////// #include "RocksDBEngine/RocksDBKeyBounds.h" #include "Basics/Exceptions.h" #include "RocksDBEngine/RocksDBCommon.h" #include "RocksDBEngine/RocksDBTypes.h" #include "Logger/Logger.h" using namespace arangodb; using namespace arangodb::rocksutils; using namespace arangodb::velocypack; const char RocksDBKeyBounds::_stringSeparator = '\0'; RocksDBKeyBounds RocksDBKeyBounds::Empty() { return RocksDBKeyBounds(); } RocksDBKeyBounds RocksDBKeyBounds::Databases() { return RocksDBKeyBounds(RocksDBEntryType::Database); } RocksDBKeyBounds RocksDBKeyBounds::DatabaseCollections( TRI_voc_tick_t databaseId) { return RocksDBKeyBounds(RocksDBEntryType::Collection, databaseId); } RocksDBKeyBounds RocksDBKeyBounds::CollectionDocuments(uint64_t collectionObjectId) { return RocksDBKeyBounds(RocksDBEntryType::Document, collectionObjectId); } RocksDBKeyBounds RocksDBKeyBounds::PrimaryIndex(uint64_t indexId) { return RocksDBKeyBounds(RocksDBEntryType::PrimaryIndexValue, indexId); } RocksDBKeyBounds RocksDBKeyBounds::EdgeIndex(uint64_t indexId) { return RocksDBKeyBounds(RocksDBEntryType::EdgeIndexValue, indexId); } RocksDBKeyBounds RocksDBKeyBounds::EdgeIndexVertex( uint64_t indexId, arangodb::StringRef const& vertexId) { return RocksDBKeyBounds(RocksDBEntryType::EdgeIndexValue, indexId, vertexId); } RocksDBKeyBounds RocksDBKeyBounds::IndexEntries(uint64_t indexId) { return RocksDBKeyBounds(RocksDBEntryType::IndexValue, indexId); } RocksDBKeyBounds RocksDBKeyBounds::UniqueIndex(uint64_t indexId) { return RocksDBKeyBounds(RocksDBEntryType::UniqueIndexValue, indexId); } RocksDBKeyBounds RocksDBKeyBounds::IndexRange(uint64_t indexId, VPackSlice const& left, VPackSlice const& right) { return RocksDBKeyBounds(RocksDBEntryType::IndexValue, indexId, left, right); } RocksDBKeyBounds RocksDBKeyBounds::UniqueIndexRange(uint64_t indexId, VPackSlice const& left, VPackSlice const& right) { return RocksDBKeyBounds(RocksDBEntryType::UniqueIndexValue, indexId, left, right); } RocksDBKeyBounds RocksDBKeyBounds::DatabaseViews(TRI_voc_tick_t databaseId) { return RocksDBKeyBounds(RocksDBEntryType::View, databaseId); } RocksDBKeyBounds RocksDBKeyBounds::CounterValues() { return RocksDBKeyBounds(RocksDBEntryType::CounterValue); } RocksDBKeyBounds RocksDBKeyBounds::FulltextIndex(uint64_t indexId) { return RocksDBKeyBounds(RocksDBEntryType::FulltextIndexValue, indexId); } RocksDBKeyBounds RocksDBKeyBounds::FulltextIndexPrefix(uint64_t indexId, arangodb::StringRef const& word) { // I did not want to pass a bool to the constructor for this RocksDBKeyBounds bounds; size_t length = sizeof(char) + sizeof(uint64_t) + word.size(); bounds._startBuffer.reserve(length); bounds._startBuffer.push_back(static_cast<char>(RocksDBEntryType::FulltextIndexValue)); uint64ToPersistent(bounds._startBuffer, indexId); bounds._startBuffer.append(word.data(), word.length()); bounds._endBuffer.append(bounds._startBuffer); bounds._endBuffer.push_back((const unsigned char)0xFF);// invalid UTF-8 character, higher than with memcmp return bounds; } RocksDBKeyBounds RocksDBKeyBounds::FulltextIndexComplete(uint64_t indexId, arangodb::StringRef const& word) { return RocksDBKeyBounds(RocksDBEntryType::FulltextIndexValue, indexId, word); } // ============================ Member Methods ============================== rocksdb::Slice const RocksDBKeyBounds::start() const { return rocksdb::Slice(_startBuffer); } rocksdb::Slice const RocksDBKeyBounds::end() const { return rocksdb::Slice(_endBuffer); } uint64_t RocksDBKeyBounds::objectId() const { RocksDBEntryType type = static_cast<RocksDBEntryType>(_startBuffer[0]); switch (type) { case RocksDBEntryType::Document: case RocksDBEntryType::PrimaryIndexValue: case RocksDBEntryType::EdgeIndexValue: case RocksDBEntryType::IndexValue: case RocksDBEntryType::UniqueIndexValue: { TRI_ASSERT(_startBuffer.size() >= (sizeof(char) + sizeof(uint64_t))); return uint64FromPersistent(_startBuffer.data() + sizeof(char)); } default: THROW_ARANGO_EXCEPTION(TRI_ERROR_TYPE_ERROR); } } // constructor for an empty bound. do not use for anything but to // default-construct a key bound! RocksDBKeyBounds::RocksDBKeyBounds() : _type(RocksDBEntryType::Database), _startBuffer(), _endBuffer() {} RocksDBKeyBounds::RocksDBKeyBounds(RocksDBEntryType type) : _type(type), _startBuffer(), _endBuffer() { switch (_type) { case RocksDBEntryType::Database: { size_t length = sizeof(char); _startBuffer.reserve(length); _startBuffer.push_back(static_cast<char>(_type)); _endBuffer.append(_startBuffer); nextPrefix(_endBuffer); break; } case RocksDBEntryType::CounterValue: { size_t length = sizeof(char) + sizeof(uint64_t); _startBuffer.reserve(length); _startBuffer.push_back(static_cast<char>(_type)); uint64ToPersistent(_startBuffer, 0); _endBuffer.reserve(length); _endBuffer.push_back(static_cast<char>(_type)); uint64ToPersistent(_endBuffer, UINT64_MAX); break; } default: THROW_ARANGO_EXCEPTION(TRI_ERROR_BAD_PARAMETER); } } RocksDBKeyBounds::RocksDBKeyBounds(RocksDBEntryType type, uint64_t first) : _type(type), _startBuffer(), _endBuffer() { switch (_type) { case RocksDBEntryType::IndexValue: case RocksDBEntryType::UniqueIndexValue: { // Unique VPack index values are stored as follows: // 7 + 8-byte object ID of index + VPack array with index value(s) .... // prefix is the same for non-unique indexes // static slices with an array with one entry VPackSlice min("\x02\x03\x1e");// [minSlice] VPackSlice max("\x02\x03\x1f");// [maxSlice] size_t length = sizeof(char) + sizeof(uint64_t) + min.byteSize(); _startBuffer.reserve(length); _startBuffer.push_back(static_cast<char>(_type)); uint64ToPersistent(_startBuffer, first); // append common prefix _endBuffer.clear(); _endBuffer.append(_startBuffer); // construct min max _startBuffer.append((char*)(min.begin()), min.byteSize()); _endBuffer.append((char*)(max.begin()), max.byteSize()); break; } case RocksDBEntryType::Collection: case RocksDBEntryType::Document:{ // Collections are stored as follows: // Key: 1 + 8-byte ArangoDB database ID + 8-byte ArangoDB collection ID // // Documents are stored as follows: // Key: 3 + 8-byte object ID of collection + 8-byte document revision ID size_t length = sizeof(char) + sizeof(uint64_t) * 2; _startBuffer.reserve(length); _startBuffer.push_back(static_cast<char>(_type)); uint64ToPersistent(_startBuffer, first); // append common prefix _endBuffer.clear(); _endBuffer.append(_startBuffer); // construct min max uint64ToPersistent(_startBuffer, 0); uint64ToPersistent(_endBuffer, UINT64_MAX); break; } case RocksDBEntryType::PrimaryIndexValue: case RocksDBEntryType::EdgeIndexValue: case RocksDBEntryType::View: case RocksDBEntryType::FulltextIndexValue: { size_t length = sizeof(char) + sizeof(uint64_t); _startBuffer.reserve(length); _startBuffer.push_back(static_cast<char>(_type)); uint64ToPersistent(_startBuffer, first); _endBuffer.clear(); _endBuffer.append(_startBuffer); nextPrefix(_endBuffer); break; } default: THROW_ARANGO_EXCEPTION(TRI_ERROR_BAD_PARAMETER); } } RocksDBKeyBounds::RocksDBKeyBounds(RocksDBEntryType type, uint64_t first, arangodb::StringRef const& second) : _type(type), _startBuffer(), _endBuffer() { switch (_type) { case RocksDBEntryType::FulltextIndexValue: case RocksDBEntryType::EdgeIndexValue: { size_t length = sizeof(char) + sizeof(uint64_t) + second.size() + sizeof(char); _startBuffer.reserve(length); _startBuffer.push_back(static_cast<char>(_type)); uint64ToPersistent(_startBuffer, first); _startBuffer.append(second.data(), second.length()); _startBuffer.push_back(_stringSeparator); _endBuffer.clear(); _endBuffer.append(_startBuffer); nextPrefix(_endBuffer); break; } default: THROW_ARANGO_EXCEPTION(TRI_ERROR_BAD_PARAMETER); } } RocksDBKeyBounds::RocksDBKeyBounds(RocksDBEntryType type, uint64_t first, VPackSlice const& second, VPackSlice const& third) : _type(type), _startBuffer(), _endBuffer() { switch (_type) { case RocksDBEntryType::IndexValue: case RocksDBEntryType::UniqueIndexValue: { size_t startLength = sizeof(char) + sizeof(uint64_t) + static_cast<size_t>(second.byteSize()) + sizeof(char); _startBuffer.reserve(startLength); _startBuffer.push_back(static_cast<char>(_type)); uint64ToPersistent(_startBuffer, first); _startBuffer.append(reinterpret_cast<char const*>(second.begin()), static_cast<size_t>(second.byteSize())); _startBuffer.push_back(_stringSeparator); TRI_ASSERT(_startBuffer.length() == startLength); size_t endLength = sizeof(char) + sizeof(uint64_t) + static_cast<size_t>(third.byteSize()) + sizeof(char); _endBuffer.reserve(endLength); _endBuffer.push_back(static_cast<char>(_type)); uint64ToPersistent(_endBuffer, first); _endBuffer.append(reinterpret_cast<char const*>(third.begin()), static_cast<size_t>(third.byteSize())); _endBuffer.push_back(_stringSeparator); nextPrefix(_endBuffer); break; } default: THROW_ARANGO_EXCEPTION(TRI_ERROR_BAD_PARAMETER); } } void RocksDBKeyBounds::nextPrefix(std::string& s) { TRI_ASSERT(s.size() >= 1); size_t i = s.size() - 1; for (; (i > 0) && (s[i] == '\xff'); --i) { } if ((i == 0) && (s[i] == '\xff')) { s.push_back('\x00'); return; } s[i] = static_cast<char>(static_cast<unsigned char>(s[i]) + 1); for (i = i + 1; i < s.size(); i++) { s[i] = '\x00'; } }
fix windows warning
fix windows warning
C++
apache-2.0
arangodb/arangodb,joerg84/arangodb,hkernbach/arangodb,joerg84/arangodb,hkernbach/arangodb,graetzer/arangodb,wiltonlazary/arangodb,wiltonlazary/arangodb,hkernbach/arangodb,joerg84/arangodb,hkernbach/arangodb,arangodb/arangodb,joerg84/arangodb,graetzer/arangodb,Simran-B/arangodb,graetzer/arangodb,fceller/arangodb,Simran-B/arangodb,hkernbach/arangodb,wiltonlazary/arangodb,arangodb/arangodb,Simran-B/arangodb,fceller/arangodb,Simran-B/arangodb,graetzer/arangodb,wiltonlazary/arangodb,joerg84/arangodb,hkernbach/arangodb,fceller/arangodb,fceller/arangodb,graetzer/arangodb,hkernbach/arangodb,joerg84/arangodb,graetzer/arangodb,hkernbach/arangodb,joerg84/arangodb,hkernbach/arangodb,arangodb/arangodb,fceller/arangodb,Simran-B/arangodb,fceller/arangodb,joerg84/arangodb,fceller/arangodb,hkernbach/arangodb,joerg84/arangodb,hkernbach/arangodb,joerg84/arangodb,graetzer/arangodb,wiltonlazary/arangodb,graetzer/arangodb,hkernbach/arangodb,arangodb/arangodb,graetzer/arangodb,graetzer/arangodb,wiltonlazary/arangodb,hkernbach/arangodb,joerg84/arangodb,arangodb/arangodb,arangodb/arangodb,joerg84/arangodb,joerg84/arangodb,Simran-B/arangodb,hkernbach/arangodb,wiltonlazary/arangodb,fceller/arangodb,Simran-B/arangodb,Simran-B/arangodb,graetzer/arangodb,fceller/arangodb,fceller/arangodb,wiltonlazary/arangodb,Simran-B/arangodb,arangodb/arangodb,Simran-B/arangodb,joerg84/arangodb,graetzer/arangodb,graetzer/arangodb,graetzer/arangodb
8f5116f3c1e81a0109d34e233431b1f50597044e
src/database/DatabaseServer.cpp
src/database/DatabaseServer.cpp
#include "core/global.h" #include "core/RoleFactory.h" #include "DBEngineFactory.h" #include "IDatabaseEngine.h" #include <fstream> ConfigVariable<channel_t> control_channel("control", 0); ConfigVariable<unsigned int> id_min("generate/min", 0); ConfigVariable<unsigned int> id_max("generate/max", UINT_MAX); ConfigVariable<std::string> engine_type("engine/type", "filesystem"); class DatabaseServer : public Role { private: IDatabaseEngine *m_db_engine; LogCategory *m_log; channel_t m_control_channel; unsigned int m_id_min, m_id_max; public: DatabaseServer(RoleConfig roleconfig) : Role(roleconfig), m_db_engine(DBEngineFactory::singleton.instantiate( engine_type.get_rval(roleconfig), roleconfig["engine"], id_min.get_rval(roleconfig))), m_control_channel(control_channel.get_rval(roleconfig)), m_id_min(id_min.get_rval(roleconfig)), m_id_max(id_max.get_rval(roleconfig)) { std::stringstream ss; ss << "Database(" << m_control_channel << ")"; m_log = new LogCategory("db", ss.str()); if(!m_db_engine) { m_log->fatal() << "No database engine of type '" << engine_type.get_rval(roleconfig) << "' exists." << std::endl; exit(1); } subscribe_channel(m_control_channel); } virtual void handle_datagram(Datagram &in_dg, DatagramIterator &dgi) { channel_t sender = dgi.read_uint64(); unsigned short msg_type = dgi.read_uint16(); switch(msg_type) { case DBSERVER_CREATE_STORED_OBJECT: { unsigned int context = dgi.read_uint32(); Datagram resp; resp.add_server_header(sender, m_control_channel, DBSERVER_CREATE_STORED_OBJECT_RESP); resp.add_uint32(context); unsigned short dc_id = dgi.read_uint16(); DCClass *dcc = gDCF->get_class(dc_id); if(!dcc) { m_log->error() << "Invalid DCClass when creating object. #" << dc_id << std::endl; resp.add_uint32(0); send(resp); return; } unsigned short field_count = dgi.read_uint16(); unsigned int do_id = m_db_engine->get_next_id(); if(do_id > m_id_max || do_id == 0) { m_log->error() << "Ran out of DistributedObject ids while creating new object." << std::endl; resp.add_uint32(0); send(resp); return; } DatabaseObject dbo; dbo.do_id = do_id; dbo.dc_id = dc_id; m_log->spam() << "Unpacking fields..." << std::endl; try { for(unsigned int i = 0; i < field_count; ++i) { unsigned short field_id = dgi.read_uint16(); DCField *field = dcc->get_field_by_index(field_id); if(field) { if(field->is_db()) { dgi.unpack_field(field, dbo.fields[field]); } else { std::string tmp; dgi.unpack_field(field, tmp); } } } } catch(std::exception &e) { m_log->error() << "Error while unpacking fields, msg may be truncated. e.what(): " << e.what() << std::endl; resp.add_uint32(0); send(resp); return; } m_log->spam() << "Checking all required fields exist..." << std::endl; for(int i = 0; i < dcc->get_num_inherited_fields(); ++i) { DCField *field = dcc->get_inherited_field(i); if(field->is_required() && field->is_db() && !field->as_molecular_field()) { if(dbo.fields.find(field) == dbo.fields.end()) { if(!field->has_default_value()) { m_log->error() << "Field " << field->get_name() << " missing when trying to create " "object of type " << dcc->get_name(); resp.add_uint32(0); send(resp); return; } else { dbo.fields[field] = field->get_default_value(); } } } } m_log->spam() << "Creating stored object with ID: " << do_id << " ..." << std::endl; if(m_db_engine->create_object(dbo)) { resp.add_uint32(do_id); } else { resp.add_uint32(0); } send(resp); } break; case DBSERVER_SELECT_STORED_OBJECT_ALL: { unsigned int context = dgi.read_uint32(); Datagram resp; resp.add_server_header(sender, m_control_channel, DBSERVER_SELECT_STORED_OBJECT_ALL_RESP); resp.add_uint32(context); DatabaseObject dbo; dbo.do_id = dgi.read_uint32(); if(m_db_engine->get_object(dbo)) { resp.add_uint8(1); resp.add_uint16(dbo.dc_id); resp.add_uint16(dbo.fields.size()); for(auto it = dbo.fields.begin(); it != dbo.fields.end(); ++it) { resp.add_uint16(it->first->get_number()); resp.add_data(it->second); } } else { resp.add_uint8(0); } send(resp); } break; case DBSERVER_DELETE_STORED_OBJECT: { if(dgi.read_uint32() == DBSERVER_DELETE_STORED_OBJECT_VERIFY_CODE) { unsigned int do_id = dgi.read_uint32(); m_db_engine->delete_object(do_id); } else { m_log->warning() << "Wrong delete verify code." << std::endl; } } break; default: m_log->error() << "Recieved unknown MsgType: " << msg_type << std::endl; }; } }; RoleFactoryItem<DatabaseServer> dbserver_fact("database");
#include "core/global.h" #include "core/RoleFactory.h" #include "DBEngineFactory.h" #include "IDatabaseEngine.h" #include <fstream> ConfigVariable<channel_t> control_channel("control", 0); ConfigVariable<unsigned int> id_min("generate/min", 0); ConfigVariable<unsigned int> id_max("generate/max", UINT_MAX); ConfigVariable<std::string> engine_type("engine/type", "filesystem"); class DatabaseServer : public Role { private: IDatabaseEngine *m_db_engine; LogCategory *m_log; channel_t m_control_channel; unsigned int m_id_min, m_id_max; public: DatabaseServer(RoleConfig roleconfig) : Role(roleconfig), m_db_engine(DBEngineFactory::singleton.instantiate( engine_type.get_rval(roleconfig), roleconfig["engine"], id_min.get_rval(roleconfig))), m_control_channel(control_channel.get_rval(roleconfig)), m_id_min(id_min.get_rval(roleconfig)), m_id_max(id_max.get_rval(roleconfig)) { std::stringstream log_title; log_title << "Database(" << m_control_channel << ")"; m_log = new LogCategory("db", log_title.str()); if(!m_db_engine) { m_log->fatal() << "No database engine of type '" << engine_type.get_rval(roleconfig) << "' exists." << std::endl; exit(1); } subscribe_channel(m_control_channel); } virtual void handle_datagram(Datagram &in_dg, DatagramIterator &dgi) { channel_t sender = dgi.read_uint64(); unsigned short msg_type = dgi.read_uint16(); switch(msg_type) { case DBSERVER_CREATE_STORED_OBJECT: { unsigned int context = dgi.read_uint32(); Datagram resp; resp.add_server_header(sender, m_control_channel, DBSERVER_CREATE_STORED_OBJECT_RESP); resp.add_uint32(context); unsigned short dc_id = dgi.read_uint16(); DCClass *dcc = gDCF->get_class(dc_id); if(!dcc) { m_log->error() << "Invalid DCClass when creating object. #" << dc_id << std::endl; resp.add_uint32(0); send(resp); return; } unsigned short field_count = dgi.read_uint16(); unsigned int do_id = m_db_engine->get_next_id(); if(do_id > m_id_max || do_id == 0) { m_log->error() << "Ran out of DistributedObject ids while creating new object." << std::endl; resp.add_uint32(0); send(resp); return; } DatabaseObject dbo; dbo.do_id = do_id; dbo.dc_id = dc_id; m_log->spam() << "Unpacking fields..." << std::endl; try { for(unsigned int i = 0; i < field_count; ++i) { unsigned short field_id = dgi.read_uint16(); DCField *field = dcc->get_field_by_index(field_id); if(field) { if(field->is_db()) { dgi.unpack_field(field, dbo.fields[field]); } else { std::string tmp; dgi.unpack_field(field, tmp); } } } } catch(std::exception &e) { m_log->error() << "Error while unpacking fields, msg may be truncated. e.what(): " << e.what() << std::endl; resp.add_uint32(0); send(resp); return; } m_log->spam() << "Checking all required fields exist..." << std::endl; for(int i = 0; i < dcc->get_num_inherited_fields(); ++i) { DCField *field = dcc->get_inherited_field(i); if(field->is_required() && field->is_db() && !field->as_molecular_field()) { if(dbo.fields.find(field) == dbo.fields.end()) { if(!field->has_default_value()) { m_log->error() << "Field " << field->get_name() << " missing when trying to create " "object of type " << dcc->get_name(); resp.add_uint32(0); send(resp); return; } else { dbo.fields[field] = field->get_default_value(); } } } } m_log->spam() << "Creating stored object with ID: " << do_id << " ..." << std::endl; if(m_db_engine->create_object(dbo)) { resp.add_uint32(do_id); } else { resp.add_uint32(0); } send(resp); } break; case DBSERVER_SELECT_STORED_OBJECT_ALL: { unsigned int context = dgi.read_uint32(); Datagram resp; resp.add_server_header(sender, m_control_channel, DBSERVER_SELECT_STORED_OBJECT_ALL_RESP); resp.add_uint32(context); DatabaseObject dbo; dbo.do_id = dgi.read_uint32(); if(m_db_engine->get_object(dbo)) { resp.add_uint8(1); resp.add_uint16(dbo.dc_id); resp.add_uint16(dbo.fields.size()); for(auto it = dbo.fields.begin(); it != dbo.fields.end(); ++it) { resp.add_uint16(it->first->get_number()); resp.add_data(it->second); } } else { resp.add_uint8(0); } send(resp); } break; case DBSERVER_DELETE_STORED_OBJECT: { if(dgi.read_uint32() == DBSERVER_DELETE_STORED_OBJECT_VERIFY_CODE) { unsigned int do_id = dgi.read_uint32(); m_db_engine->delete_object(do_id); } else { m_log->warning() << "Wrong delete verify code." << std::endl; } } break; default: m_log->error() << "Recieved unknown MsgType: " << msg_type << std::endl; }; } }; RoleFactoryItem<DatabaseServer> dbserver_fact("database");
Use more descriptive variable name in Server constructor.
DBServer: Use more descriptive variable name in Server constructor.
C++
bsd-3-clause
ketoo/Astron,ketoo/Astron,pizcogirl/Astron,blindsighttf2/Astron,blindsighttf2/Astron,ketoo/Astron,pizcogirl/Astron,blindsighttf2/Astron,blindsighttf2/Astron,pizcogirl/Astron,pizcogirl/Astron,ketoo/Astron
54d5b044244e2e8bde660272f0e7fa8658064b59
base/command_line.cc
base/command_line.cc
// Copyright 2008, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include "base/command_line.h" #if defined(OS_WIN) #include <windows.h> #include <shellapi.h> #endif #include <algorithm> #include "base/logging.h" #include "base/singleton.h" #include "base/string_util.h" #include "base/sys_string_conversions.h" using namespace std; // Since we use a lazy match, make sure that longer versions (like L"--") // are listed before shorter versions (like L"-") of similar prefixes. #if defined(OS_WIN) const wchar_t* const CommandLine::kSwitchPrefixes[] = {L"--", L"-", L"/"}; #elif defined(OS_POSIX) // Unixes don't use slash as a switch. const wchar_t* const CommandLine::kSwitchPrefixes[] = {L"--", L"-"}; #endif const wchar_t CommandLine::kSwitchValueSeparator[] = L"="; // Needed to avoid a typecast on the tolower() function pointer in Lowercase(). // MSVC accepts it as-is but GCC requires the typecast. static int ToLower(int c) { return tolower(c); } static void Lowercase(wstring* parameter) { transform(parameter->begin(), parameter->end(), parameter->begin(), ToLower); } // CommandLine::Data // // This object holds the parsed data for a command line. We hold this in a // separate object from |CommandLine| so that we can share the parsed data // across multiple |CommandLine| objects. When we share |Data|, we might be // accessing this object on multiple threads. To ensure thread safety, the // public interface of this object is const only. // // Do NOT add any non-const methods to this object. You have been warned. class CommandLine::Data { public: #if defined(OS_WIN) Data() { Init(GetCommandLineW()); } #elif defined(OS_POSIX) Data() { // Owner must call Init(). } #endif #if defined(OS_WIN) Data(const wstring& command_line) { Init(command_line); } #elif defined(OS_POSIX) Data(const int argc, char** argv) { Init(argc, argv); } #endif #if defined(OS_WIN) // Does the actual parsing of the command line. void Init(const std::wstring& command_line) { TrimWhitespace(command_line, TRIM_ALL, &command_line_string_); if (command_line_string_.empty()) return; int num_args = 0; wchar_t** args = NULL; args = CommandLineToArgvW(command_line_string_.c_str(), &num_args); // Populate program_ with the trimmed version of the first arg. TrimWhitespace(args[0], TRIM_ALL, &program_); for (int i = 1; i < num_args; ++i) { wstring arg; TrimWhitespace(args[i], TRIM_ALL, &arg); wstring switch_string; wstring switch_value; if (IsSwitch(arg, &switch_string, &switch_value)) { switches_[switch_string] = switch_value; } else { loose_values_.push_back(arg); } } if (args) LocalFree(args); } #elif defined(OS_POSIX) // Does the actual parsing of the command line. void Init(int argc, char** argv) { if (argc < 1) return; program_ = base::SysNativeMBToWide(argv[0]); command_line_string_ = program_; for (int i = 1; i < argc; ++i) { std::wstring arg = base::SysNativeMBToWide(argv[i]); command_line_string_.append(L" "); command_line_string_.append(arg); wstring switch_string; wstring switch_value; if (IsSwitch(arg, &switch_string, &switch_value)) { switches_[switch_string] = switch_value; } else { loose_values_.push_back(arg); } } } #endif const std::wstring& command_line_string() const { return command_line_string_; } const std::wstring& program() const { return program_; } const std::map<std::wstring, std::wstring>& switches() const { return switches_; } const std::vector<std::wstring>& loose_values() const { return loose_values_; } private: // Returns true if parameter_string represents a switch. If true, // switch_string and switch_value are set. (If false, both are // set to the empty string.) static bool IsSwitch(const wstring& parameter_string, wstring* switch_string, wstring* switch_value) { *switch_string = L""; *switch_value = L""; for (size_t i = 0; i < arraysize(kSwitchPrefixes); ++i) { std::wstring prefix(kSwitchPrefixes[i]); if (parameter_string.find(prefix) != 0) // check prefix continue; const size_t switch_start = prefix.length(); const size_t equals_position = parameter_string.find( kSwitchValueSeparator, switch_start); if (equals_position == wstring::npos) { *switch_string = parameter_string.substr(switch_start); } else { *switch_string = parameter_string.substr( switch_start, equals_position - switch_start); *switch_value = parameter_string.substr(equals_position + 1); } Lowercase(switch_string); return true; } return false; } std::wstring command_line_string_; std::wstring program_; std::map<std::wstring, std::wstring> switches_; std::vector<std::wstring> loose_values_; DISALLOW_EVIL_CONSTRUCTORS(Data); }; CommandLine::CommandLine() : we_own_data_(false), // The Singleton class will manage it for us. data_(Singleton<Data>::get()) { DCHECK(!data_->command_line_string().empty()) << "You must call CommandLine::SetArgcArgv before making any CommandLine " "calls."; } #if defined(OS_WIN) CommandLine::CommandLine(const wstring& command_line) : we_own_data_(true), data_(new Data(command_line)) { } #elif defined(OS_POSIX) CommandLine::CommandLine(const int argc, char** argv) : we_own_data_(true), data_(new Data(argc, argv)) { } #endif CommandLine::~CommandLine() { if (we_own_data_) delete data_; } // static void CommandLine::SetArgcArgv(int argc, char** argv) { Singleton<Data>::get()->Init(argc, argv); } bool CommandLine::HasSwitch(const wstring& switch_string) const { wstring lowercased_switch(switch_string); Lowercase(&lowercased_switch); return data_->switches().find(lowercased_switch) != data_->switches().end(); } wstring CommandLine::GetSwitchValue(const wstring& switch_string) const { wstring lowercased_switch(switch_string); Lowercase(&lowercased_switch); const map<wstring, wstring>::const_iterator result = data_->switches().find(lowercased_switch); if (result == data_->switches().end()) { return L""; } else { return result->second; } } size_t CommandLine::GetLooseValueCount() const { return data_->loose_values().size(); } CommandLine::LooseValueIterator CommandLine::GetLooseValuesBegin() const { return data_->loose_values().begin(); } CommandLine::LooseValueIterator CommandLine::GetLooseValuesEnd() const { return data_->loose_values().end(); } std::wstring CommandLine::command_line_string() const { return data_->command_line_string(); } std::wstring CommandLine::program() const { return data_->program(); } // static void CommandLine::AppendSwitch(wstring* command_line_string, const wstring& switch_string) { DCHECK(command_line_string); command_line_string->append(L" "); command_line_string->append(kSwitchPrefixes[0]); command_line_string->append(switch_string); } // static void CommandLine::AppendSwitchWithValue(wstring* command_line_string, const wstring& switch_string, const wstring& value_string) { AppendSwitch(command_line_string, switch_string); if (value_string.empty()) return; command_line_string->append(kSwitchValueSeparator); // NOTE(jhughes): If the value contains a quotation mark at one // end but not both, you may get unusable output. if ((value_string.find(L" ") != std::wstring::npos) && (value_string[0] != L'"') && (value_string[value_string.length() - 1] != L'"')) { // need to provide quotes StringAppendF(command_line_string, L"\"%s\"", value_string.c_str()); } else { command_line_string->append(value_string); } }
// Copyright 2008, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include "base/command_line.h" #if defined(OS_WIN) #include <windows.h> #include <shellapi.h> #endif #include <algorithm> #include "base/logging.h" #include "base/singleton.h" #include "base/string_util.h" #include "base/sys_string_conversions.h" using namespace std; // Since we use a lazy match, make sure that longer versions (like L"--") // are listed before shorter versions (like L"-") of similar prefixes. #if defined(OS_WIN) const wchar_t* const CommandLine::kSwitchPrefixes[] = {L"--", L"-", L"/"}; #elif defined(OS_POSIX) // Unixes don't use slash as a switch. const wchar_t* const CommandLine::kSwitchPrefixes[] = {L"--", L"-"}; #endif const wchar_t CommandLine::kSwitchValueSeparator[] = L"="; // Needed to avoid a typecast on the tolower() function pointer in Lowercase(). // MSVC accepts it as-is but GCC requires the typecast. static int ToLower(int c) { return tolower(c); } static void Lowercase(wstring* parameter) { transform(parameter->begin(), parameter->end(), parameter->begin(), ToLower); } // CommandLine::Data // // This object holds the parsed data for a command line. We hold this in a // separate object from |CommandLine| so that we can share the parsed data // across multiple |CommandLine| objects. When we share |Data|, we might be // accessing this object on multiple threads. To ensure thread safety, the // public interface of this object is const only. // // Do NOT add any non-const methods to this object. You have been warned. class CommandLine::Data { public: #if defined(OS_WIN) Data() { Init(GetCommandLineW()); } #elif defined(OS_POSIX) Data() { // Owner must call Init(). } #endif #if defined(OS_WIN) Data(const wstring& command_line) { Init(command_line); } #elif defined(OS_POSIX) Data(const int argc, char** argv) { Init(argc, argv); } #endif #if defined(OS_WIN) // Does the actual parsing of the command line. void Init(const std::wstring& command_line) { TrimWhitespace(command_line, TRIM_ALL, &command_line_string_); if (command_line_string_.empty()) return; int num_args = 0; wchar_t** args = NULL; args = CommandLineToArgvW(command_line_string_.c_str(), &num_args); // Populate program_ with the trimmed version of the first arg. TrimWhitespace(args[0], TRIM_ALL, &program_); for (int i = 1; i < num_args; ++i) { wstring arg; TrimWhitespace(args[i], TRIM_ALL, &arg); wstring switch_string; wstring switch_value; if (IsSwitch(arg, &switch_string, &switch_value)) { switches_[switch_string] = switch_value; } else { loose_values_.push_back(arg); } } if (args) LocalFree(args); } #elif defined(OS_POSIX) // Does the actual parsing of the command line. void Init(int argc, char** argv) { if (argc < 1) return; program_ = base::SysNativeMBToWide(argv[0]); command_line_string_ = program_; for (int i = 1; i < argc; ++i) { std::wstring arg = base::SysNativeMBToWide(argv[i]); command_line_string_.append(L" "); command_line_string_.append(arg); wstring switch_string; wstring switch_value; if (IsSwitch(arg, &switch_string, &switch_value)) { switches_[switch_string] = switch_value; } else { loose_values_.push_back(arg); } } } #endif const std::wstring& command_line_string() const { return command_line_string_; } const std::wstring& program() const { return program_; } const std::map<std::wstring, std::wstring>& switches() const { return switches_; } const std::vector<std::wstring>& loose_values() const { return loose_values_; } private: // Returns true if parameter_string represents a switch. If true, // switch_string and switch_value are set. (If false, both are // set to the empty string.) static bool IsSwitch(const wstring& parameter_string, wstring* switch_string, wstring* switch_value) { *switch_string = L""; *switch_value = L""; for (size_t i = 0; i < arraysize(kSwitchPrefixes); ++i) { std::wstring prefix(kSwitchPrefixes[i]); if (parameter_string.find(prefix) != 0) // check prefix continue; const size_t switch_start = prefix.length(); const size_t equals_position = parameter_string.find( kSwitchValueSeparator, switch_start); if (equals_position == wstring::npos) { *switch_string = parameter_string.substr(switch_start); } else { *switch_string = parameter_string.substr( switch_start, equals_position - switch_start); *switch_value = parameter_string.substr(equals_position + 1); } Lowercase(switch_string); return true; } return false; } std::wstring command_line_string_; std::wstring program_; std::map<std::wstring, std::wstring> switches_; std::vector<std::wstring> loose_values_; DISALLOW_EVIL_CONSTRUCTORS(Data); }; CommandLine::CommandLine() : we_own_data_(false), // The Singleton class will manage it for us. data_(Singleton<Data>::get()) { DCHECK(!data_->command_line_string().empty()) << "You must call CommandLine::SetArgcArgv before making any CommandLine " "calls."; } #if defined(OS_WIN) CommandLine::CommandLine(const wstring& command_line) : we_own_data_(true), data_(new Data(command_line)) { } #elif defined(OS_POSIX) CommandLine::CommandLine(const int argc, char** argv) : we_own_data_(true), data_(new Data(argc, argv)) { } #endif CommandLine::~CommandLine() { if (we_own_data_) delete data_; } // static void CommandLine::SetArgcArgv(int argc, char** argv) { #if !defined(OS_WIN) Singleton<Data>::get()->Init(argc, argv); #endif } bool CommandLine::HasSwitch(const wstring& switch_string) const { wstring lowercased_switch(switch_string); Lowercase(&lowercased_switch); return data_->switches().find(lowercased_switch) != data_->switches().end(); } wstring CommandLine::GetSwitchValue(const wstring& switch_string) const { wstring lowercased_switch(switch_string); Lowercase(&lowercased_switch); const map<wstring, wstring>::const_iterator result = data_->switches().find(lowercased_switch); if (result == data_->switches().end()) { return L""; } else { return result->second; } } size_t CommandLine::GetLooseValueCount() const { return data_->loose_values().size(); } CommandLine::LooseValueIterator CommandLine::GetLooseValuesBegin() const { return data_->loose_values().begin(); } CommandLine::LooseValueIterator CommandLine::GetLooseValuesEnd() const { return data_->loose_values().end(); } std::wstring CommandLine::command_line_string() const { return data_->command_line_string(); } std::wstring CommandLine::program() const { return data_->program(); } // static void CommandLine::AppendSwitch(wstring* command_line_string, const wstring& switch_string) { DCHECK(command_line_string); command_line_string->append(L" "); command_line_string->append(kSwitchPrefixes[0]); command_line_string->append(switch_string); } // static void CommandLine::AppendSwitchWithValue(wstring* command_line_string, const wstring& switch_string, const wstring& value_string) { AppendSwitch(command_line_string, switch_string); if (value_string.empty()) return; command_line_string->append(kSwitchValueSeparator); // NOTE(jhughes): If the value contains a quotation mark at one // end but not both, you may get unusable output. if ((value_string.find(L" ") != std::wstring::npos) && (value_string[0] != L'"') && (value_string[value_string.length() - 1] != L'"')) { // need to provide quotes StringAppendF(command_line_string, L"\"%s\"", value_string.c_str()); } else { command_line_string->append(value_string); } }
Fix build breakage on Windows.
Fix build breakage on Windows. git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@692 0039d316-1c4b-4281-b951-d872f2087c98
C++
bsd-3-clause
patrickm/chromium.src,hgl888/chromium-crosswalk-efl,fujunwei/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,dushu1203/chromium.src,hgl888/chromium-crosswalk-efl,junmin-zhu/chromium-rivertrail,bright-sparks/chromium-spacewalk,mohamed--abdel-maksoud/chromium.src,junmin-zhu/chromium-rivertrail,crosswalk-project/chromium-crosswalk-efl,robclark/chromium,mogoweb/chromium-crosswalk,littlstar/chromium.src,timopulkkinen/BubbleFish,zcbenz/cefode-chromium,PeterWangIntel/chromium-crosswalk,rogerwang/chromium,bright-sparks/chromium-spacewalk,ChromiumWebApps/chromium,hgl888/chromium-crosswalk,pozdnyakov/chromium-crosswalk,keishi/chromium,axinging/chromium-crosswalk,hujiajie/pa-chromium,dednal/chromium.src,Fireblend/chromium-crosswalk,Just-D/chromium-1,bright-sparks/chromium-spacewalk,timopulkkinen/BubbleFish,axinging/chromium-crosswalk,ChromiumWebApps/chromium,hgl888/chromium-crosswalk-efl,timopulkkinen/BubbleFish,hujiajie/pa-chromium,mohamed--abdel-maksoud/chromium.src,littlstar/chromium.src,Jonekee/chromium.src,timopulkkinen/BubbleFish,mohamed--abdel-maksoud/chromium.src,markYoungH/chromium.src,nacl-webkit/chrome_deps,junmin-zhu/chromium-rivertrail,hujiajie/pa-chromium,Jonekee/chromium.src,patrickm/chromium.src,jaruba/chromium.src,chuan9/chromium-crosswalk,keishi/chromium,littlstar/chromium.src,Just-D/chromium-1,Fireblend/chromium-crosswalk,dushu1203/chromium.src,jaruba/chromium.src,hgl888/chromium-crosswalk,hgl888/chromium-crosswalk-efl,M4sse/chromium.src,krieger-od/nwjs_chromium.src,timopulkkinen/BubbleFish,timopulkkinen/BubbleFish,M4sse/chromium.src,junmin-zhu/chromium-rivertrail,ondra-novak/chromium.src,junmin-zhu/chromium-rivertrail,fujunwei/chromium-crosswalk,Jonekee/chromium.src,robclark/chromium,markYoungH/chromium.src,pozdnyakov/chromium-crosswalk,markYoungH/chromium.src,keishi/chromium,zcbenz/cefode-chromium,robclark/chromium,krieger-od/nwjs_chromium.src,ltilve/chromium,M4sse/chromium.src,mogoweb/chromium-crosswalk,ondra-novak/chromium.src,ondra-novak/chromium.src,hgl888/chromium-crosswalk,junmin-zhu/chromium-rivertrail,junmin-zhu/chromium-rivertrail,ondra-novak/chromium.src,PeterWangIntel/chromium-crosswalk,robclark/chromium,littlstar/chromium.src,patrickm/chromium.src,bright-sparks/chromium-spacewalk,crosswalk-project/chromium-crosswalk-efl,bright-sparks/chromium-spacewalk,Chilledheart/chromium,crosswalk-project/chromium-crosswalk-efl,M4sse/chromium.src,Just-D/chromium-1,chuan9/chromium-crosswalk,ondra-novak/chromium.src,mogoweb/chromium-crosswalk,keishi/chromium,Jonekee/chromium.src,fujunwei/chromium-crosswalk,nacl-webkit/chrome_deps,Chilledheart/chromium,markYoungH/chromium.src,mohamed--abdel-maksoud/chromium.src,Chilledheart/chromium,hujiajie/pa-chromium,Pluto-tv/chromium-crosswalk,hujiajie/pa-chromium,dushu1203/chromium.src,mogoweb/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,bright-sparks/chromium-spacewalk,ChromiumWebApps/chromium,Pluto-tv/chromium-crosswalk,axinging/chromium-crosswalk,ltilve/chromium,Jonekee/chromium.src,TheTypoMaster/chromium-crosswalk,krieger-od/nwjs_chromium.src,zcbenz/cefode-chromium,anirudhSK/chromium,rogerwang/chromium,hgl888/chromium-crosswalk-efl,timopulkkinen/BubbleFish,TheTypoMaster/chromium-crosswalk,Pluto-tv/chromium-crosswalk,rogerwang/chromium,littlstar/chromium.src,Pluto-tv/chromium-crosswalk,hgl888/chromium-crosswalk,Chilledheart/chromium,hgl888/chromium-crosswalk,Just-D/chromium-1,hgl888/chromium-crosswalk-efl,robclark/chromium,dushu1203/chromium.src,TheTypoMaster/chromium-crosswalk,timopulkkinen/BubbleFish,fujunwei/chromium-crosswalk,hgl888/chromium-crosswalk-efl,fujunwei/chromium-crosswalk,markYoungH/chromium.src,M4sse/chromium.src,ChromiumWebApps/chromium,M4sse/chromium.src,PeterWangIntel/chromium-crosswalk,M4sse/chromium.src,dednal/chromium.src,fujunwei/chromium-crosswalk,Jonekee/chromium.src,M4sse/chromium.src,Chilledheart/chromium,Just-D/chromium-1,Fireblend/chromium-crosswalk,Jonekee/chromium.src,hujiajie/pa-chromium,robclark/chromium,chuan9/chromium-crosswalk,ChromiumWebApps/chromium,Pluto-tv/chromium-crosswalk,Pluto-tv/chromium-crosswalk,zcbenz/cefode-chromium,axinging/chromium-crosswalk,dednal/chromium.src,crosswalk-project/chromium-crosswalk-efl,mogoweb/chromium-crosswalk,ondra-novak/chromium.src,hgl888/chromium-crosswalk-efl,patrickm/chromium.src,ChromiumWebApps/chromium,crosswalk-project/chromium-crosswalk-efl,hgl888/chromium-crosswalk,zcbenz/cefode-chromium,crosswalk-project/chromium-crosswalk-efl,zcbenz/cefode-chromium,anirudhSK/chromium,hujiajie/pa-chromium,axinging/chromium-crosswalk,hgl888/chromium-crosswalk,dushu1203/chromium.src,jaruba/chromium.src,chuan9/chromium-crosswalk,patrickm/chromium.src,jaruba/chromium.src,mohamed--abdel-maksoud/chromium.src,junmin-zhu/chromium-rivertrail,fujunwei/chromium-crosswalk,Jonekee/chromium.src,krieger-od/nwjs_chromium.src,anirudhSK/chromium,anirudhSK/chromium,hgl888/chromium-crosswalk-efl,nacl-webkit/chrome_deps,krieger-od/nwjs_chromium.src,mohamed--abdel-maksoud/chromium.src,krieger-od/nwjs_chromium.src,ChromiumWebApps/chromium,Fireblend/chromium-crosswalk,ondra-novak/chromium.src,anirudhSK/chromium,krieger-od/nwjs_chromium.src,pozdnyakov/chromium-crosswalk,ondra-novak/chromium.src,littlstar/chromium.src,jaruba/chromium.src,PeterWangIntel/chromium-crosswalk,ltilve/chromium,rogerwang/chromium,keishi/chromium,krieger-od/nwjs_chromium.src,hujiajie/pa-chromium,timopulkkinen/BubbleFish,timopulkkinen/BubbleFish,anirudhSK/chromium,dednal/chromium.src,nacl-webkit/chrome_deps,TheTypoMaster/chromium-crosswalk,krieger-od/nwjs_chromium.src,zcbenz/cefode-chromium,junmin-zhu/chromium-rivertrail,TheTypoMaster/chromium-crosswalk,ltilve/chromium,anirudhSK/chromium,jaruba/chromium.src,ChromiumWebApps/chromium,axinging/chromium-crosswalk,patrickm/chromium.src,chuan9/chromium-crosswalk,pozdnyakov/chromium-crosswalk,dushu1203/chromium.src,junmin-zhu/chromium-rivertrail,mogoweb/chromium-crosswalk,mogoweb/chromium-crosswalk,Just-D/chromium-1,Pluto-tv/chromium-crosswalk,nacl-webkit/chrome_deps,anirudhSK/chromium,Chilledheart/chromium,axinging/chromium-crosswalk,nacl-webkit/chrome_deps,timopulkkinen/BubbleFish,chuan9/chromium-crosswalk,Jonekee/chromium.src,keishi/chromium,Fireblend/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,dednal/chromium.src,bright-sparks/chromium-spacewalk,dednal/chromium.src,chuan9/chromium-crosswalk,pozdnyakov/chromium-crosswalk,rogerwang/chromium,dednal/chromium.src,keishi/chromium,markYoungH/chromium.src,Just-D/chromium-1,jaruba/chromium.src,bright-sparks/chromium-spacewalk,mogoweb/chromium-crosswalk,hgl888/chromium-crosswalk,Jonekee/chromium.src,dednal/chromium.src,krieger-od/nwjs_chromium.src,robclark/chromium,dednal/chromium.src,M4sse/chromium.src,Chilledheart/chromium,mohamed--abdel-maksoud/chromium.src,anirudhSK/chromium,pozdnyakov/chromium-crosswalk,markYoungH/chromium.src,zcbenz/cefode-chromium,axinging/chromium-crosswalk,Just-D/chromium-1,ltilve/chromium,rogerwang/chromium,crosswalk-project/chromium-crosswalk-efl,pozdnyakov/chromium-crosswalk,krieger-od/nwjs_chromium.src,jaruba/chromium.src,ltilve/chromium,markYoungH/chromium.src,pozdnyakov/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,chuan9/chromium-crosswalk,markYoungH/chromium.src,jaruba/chromium.src,Fireblend/chromium-crosswalk,dednal/chromium.src,hujiajie/pa-chromium,ChromiumWebApps/chromium,jaruba/chromium.src,hujiajie/pa-chromium,robclark/chromium,crosswalk-project/chromium-crosswalk-efl,markYoungH/chromium.src,M4sse/chromium.src,anirudhSK/chromium,hujiajie/pa-chromium,patrickm/chromium.src,dushu1203/chromium.src,markYoungH/chromium.src,Pluto-tv/chromium-crosswalk,keishi/chromium,Fireblend/chromium-crosswalk,keishi/chromium,PeterWangIntel/chromium-crosswalk,patrickm/chromium.src,ltilve/chromium,anirudhSK/chromium,nacl-webkit/chrome_deps,M4sse/chromium.src,zcbenz/cefode-chromium,littlstar/chromium.src,robclark/chromium,Chilledheart/chromium,fujunwei/chromium-crosswalk,keishi/chromium,dednal/chromium.src,rogerwang/chromium,axinging/chromium-crosswalk,hgl888/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,ltilve/chromium,Fireblend/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,nacl-webkit/chrome_deps,mogoweb/chromium-crosswalk,robclark/chromium,anirudhSK/chromium,Fireblend/chromium-crosswalk,Jonekee/chromium.src,hgl888/chromium-crosswalk-efl,PeterWangIntel/chromium-crosswalk,ChromiumWebApps/chromium,dushu1203/chromium.src,ChromiumWebApps/chromium,axinging/chromium-crosswalk,Chilledheart/chromium,zcbenz/cefode-chromium,TheTypoMaster/chromium-crosswalk,nacl-webkit/chrome_deps,bright-sparks/chromium-spacewalk,mohamed--abdel-maksoud/chromium.src,dushu1203/chromium.src,dushu1203/chromium.src,mogoweb/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,keishi/chromium,Pluto-tv/chromium-crosswalk,rogerwang/chromium,nacl-webkit/chrome_deps,ondra-novak/chromium.src,rogerwang/chromium,rogerwang/chromium,jaruba/chromium.src,nacl-webkit/chrome_deps,dushu1203/chromium.src,ltilve/chromium,junmin-zhu/chromium-rivertrail,Just-D/chromium-1,PeterWangIntel/chromium-crosswalk,pozdnyakov/chromium-crosswalk,littlstar/chromium.src,ChromiumWebApps/chromium,zcbenz/cefode-chromium,pozdnyakov/chromium-crosswalk,fujunwei/chromium-crosswalk,axinging/chromium-crosswalk,pozdnyakov/chromium-crosswalk,patrickm/chromium.src,PeterWangIntel/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,chuan9/chromium-crosswalk
94012ea4d6f8e6086551da1cf30188ac063319e0
test/unit/math/rev/functor/ode_bdf_adjoint_scale_bench_test.cpp
test/unit/math/rev/functor/ode_bdf_adjoint_scale_bench_test.cpp
#include <stan/math/rev.hpp> #include <gtest/gtest.h> #include <stan/math/rev/functor/gradient.hpp> #include <iostream> #include <sstream> #include <vector> #include <stdexcept> using stan::math::lognormal_rng; using stan::math::var; struct scaling_rhs { template <typename T0, typename T1, typename T2, typename T3, typename T4, typename T5> inline Eigen::Matrix<stan::return_type_t<T1, T2, T3, T4, T5>, Eigen::Dynamic, 1> operator()(const T0& t, const Eigen::Matrix<T1, Eigen::Dynamic, 1>& y, std::ostream* msgs, const std::vector<T2>& kt, const std::vector<T3>& e50, const std::vector<T4>& k12, const std::vector<T5>& k21) const { std::size_t num_main_states = kt.size(); std::size_t num_states = 2 * num_main_states; using return_t = stan::return_type_t<T1, T2, T3, T4, T5>; Eigen::Matrix<return_t, Eigen::Dynamic, 1> dydt(num_states); std::vector<return_t> ksat(num_main_states); for (std::size_t i = 0; i != num_main_states; ++i) { std::size_t m = 2 * i; // main state std::size_t a = m + 1; // auxilary state ksat[i] = kt[i] * y(m) / (y(m) + e50[i]); dydt(m) = -ksat[i] * y(m) - k12[i] * y(m) + k21[i] * y(a); dydt(a) = +k12[i] * y(m) - k21[i] * y(a); if (i != 0) { dydt(m) += ksat[i - 1] * y(2 * (i - 1)); } } return dydt; } }; void run_benchmark(std::size_t system_size, int adjoint_integrator) { scaling_rhs ode; std::vector<double> ts{1., 2.0, 4.0, 8.0, 16.0, 32.0, 64.0}; std::size_t ts_size = ts.size(); boost::ecuyer1988 base_rng(563646); double log_sigma = 10.0; double abs_tol = 1e-8; double abs_tol_B = abs_tol * 10.0; double abs_tol_QB = abs_tol_B * 10.0; double rel_tol = 1e-6; int steps_checkpoint = 100; int max_num_steps = 100000; for (std::size_t i = 0; i != 10; i++) { stan::math::nested_rev_autodiff nested; std::vector<var> kt(system_size); std::vector<var> e50(system_size); std::vector<var> k12(system_size); std::vector<var> k21(system_size); for (std::size_t j = 0; j != system_size; ++j) { kt[j] = lognormal_rng(0.0, log_sigma, base_rng); e50[j] = lognormal_rng(0.0, log_sigma, base_rng); k12[j] = lognormal_rng(0.0, log_sigma, base_rng); k21[j] = lognormal_rng(0.0, log_sigma, base_rng); } Eigen::Matrix<var, Eigen::Dynamic, 1> y0(2 * system_size); for (std::size_t j = 0; j != 2 * system_size; ++j) y0(j) = lognormal_rng(0.0, log_sigma, base_rng); double t0 = 0.0; try { if (adjoint_integrator) { std::vector<Eigen::Matrix<var, Eigen::Dynamic, 1>> y = ode_bdf_adjoint_tol(ode, y0, t0, ts, rel_tol, abs_tol, max_num_steps, nullptr, abs_tol_B, abs_tol_QB, steps_checkpoint, kt, e50, k12, k21); stan::math::grad(); } else { std::vector<Eigen::Matrix<var, Eigen::Dynamic, 1>> y = ode_bdf_tol(ode, y0, t0, ts, rel_tol, abs_tol_QB, max_num_steps, nullptr, kt, e50, k12, k21); stan::math::grad(); } } catch (std::exception& exc) { std::cout << "oops, keep going please!" << std::endl; std::cerr << exc.what() << std::endl; } } stan::math::recover_memory(); } TEST(StanMathOdeBench, bdf_2) { run_benchmark(2, 0); } TEST(StanMathOdeBench, bdf_adjoint_2) { run_benchmark(2, 1); } TEST(StanMathOdeBench, bdf_4) { run_benchmark(4, 0); } TEST(StanMathOdeBench, bdf_adjoint_4) { run_benchmark(4, 1); } TEST(StanMathOdeBench, bdf_8) { run_benchmark(8, 0); } TEST(StanMathOdeBench, bdf_adjoint_8) { run_benchmark(8, 1); } TEST(StanMathOdeBench, bdf_16) { run_benchmark(16, 0); } TEST(StanMathOdeBench, bdf_adjoint_16) { run_benchmark(16, 1); } TEST(StanMathOdeBench, bdf_32) { run_benchmark(32, 0); } TEST(StanMathOdeBench, bdf_adjoint_32) { run_benchmark(32, 1); }
#include <stan/math/rev.hpp> #include <gtest/gtest.h> #include <stan/math/rev/functor/gradient.hpp> #include <iostream> #include <sstream> #include <vector> #include <stdexcept> using stan::math::lognormal_rng; using stan::math::var; struct scaling_rhs { template <typename T0, typename T1, typename T2, typename T3, typename T4, typename T5> inline Eigen::Matrix<stan::return_type_t<T1, T2, T3, T4, T5>, Eigen::Dynamic, 1> operator()(const T0& t, const Eigen::Matrix<T1, Eigen::Dynamic, 1>& y, std::ostream* msgs, const std::vector<T2>& kt, const std::vector<T3>& e50, const std::vector<T4>& k12, const std::vector<T5>& k21) const { std::size_t num_main_states = kt.size(); std::size_t num_states = 2 * num_main_states; using return_t = stan::return_type_t<T1, T2, T3, T4, T5>; Eigen::Matrix<return_t, Eigen::Dynamic, 1> dydt(num_states); std::vector<return_t> ksat(num_main_states); for (std::size_t i = 0; i != num_main_states; ++i) { std::size_t m = 2 * i; // main state std::size_t a = m + 1; // auxilary state ksat[i] = kt[i] * y(m) / (y(m) + e50[i]); dydt(m) = -ksat[i] * y(m) - k12[i] * y(m) + k21[i] * y(a); dydt(a) = +k12[i] * y(m) - k21[i] * y(a); if (i != 0) { dydt(m) += ksat[i - 1] * y(2 * (i - 1)); } } return dydt; } }; void run_benchmark(std::size_t system_size, int adjoint_integrator) { scaling_rhs ode; std::vector<double> ts{1., 2.0, 4.0, 8.0, 16.0, 32.0, 64.0}; std::size_t ts_size = ts.size(); boost::ecuyer1988 base_rng(563646); double log_sigma = 10.0; double abs_tol = 1e-8; double abs_tol_B = abs_tol * 10.0; double abs_tol_QB = abs_tol_B * 10.0; double rel_tol = 1e-6; int steps_checkpoint = 100; int max_num_steps = 100000; for (std::size_t i = 0; i != 10; i++) { stan::math::nested_rev_autodiff nested; std::vector<var> kt(system_size); std::vector<var> e50(system_size); std::vector<var> k12(system_size); std::vector<var> k21(system_size); for (std::size_t j = 0; j != system_size; ++j) { kt[j] = lognormal_rng(0.0, log_sigma, base_rng); e50[j] = lognormal_rng(0.0, log_sigma, base_rng); k12[j] = lognormal_rng(0.0, log_sigma, base_rng); k21[j] = lognormal_rng(0.0, log_sigma, base_rng); } Eigen::Matrix<var, Eigen::Dynamic, 1> y0(2 * system_size); for (std::size_t j = 0; j != 2 * system_size; ++j) y0(j) = lognormal_rng(0.0, log_sigma, base_rng); double t0 = 0.0; try { std::vector<Eigen::Matrix<var, Eigen::Dynamic, 1>> y; if (adjoint_integrator) { y = ode_bdf_adjoint_tol(ode, y0, t0, ts, rel_tol, abs_tol, max_num_steps, nullptr, abs_tol_B, abs_tol_QB, steps_checkpoint, kt, e50, k12, k21); } else { y = ode_bdf_tol(ode, y0, t0, ts, rel_tol, abs_tol_QB, max_num_steps, nullptr, kt, e50, k12, k21); } // Essentially sets the adjoint for all states to 1. var target = stan::math::sum(y[0]); for (int k = 1; k < ts_size; k++) target += stan::math::sum(y[k]); target.grad(); } catch (std::exception& exc) { std::cout << "oops, keep going please!" << std::endl; std::cerr << exc.what() << std::endl; } } stan::math::recover_memory(); } TEST(StanMathOdeBench, bdf_2) { run_benchmark(2, 0); } TEST(StanMathOdeBench, bdf_adjoint_2) { run_benchmark(2, 1); } TEST(StanMathOdeBench, bdf_4) { run_benchmark(4, 0); } TEST(StanMathOdeBench, bdf_adjoint_4) { run_benchmark(4, 1); } TEST(StanMathOdeBench, bdf_8) { run_benchmark(8, 0); } TEST(StanMathOdeBench, bdf_adjoint_8) { run_benchmark(8, 1); } TEST(StanMathOdeBench, bdf_16) { run_benchmark(16, 0); } TEST(StanMathOdeBench, bdf_adjoint_16) { run_benchmark(16, 1); } TEST(StanMathOdeBench, bdf_32) { run_benchmark(32, 0); } TEST(StanMathOdeBench, bdf_adjoint_32) { run_benchmark(32, 1); }
Set adjoints to 1 in benchmark test.
Set adjoints to 1 in benchmark test.
C++
bsd-3-clause
stan-dev/math,stan-dev/math,stan-dev/math,stan-dev/math,stan-dev/math,stan-dev/math,stan-dev/math,stan-dev/math,stan-dev/math
d8a7f0b4c1eed7df255ac328f1f3ab98fe735424
src/appleseed/renderer/kernel/rendering/baserenderer.cpp
src/appleseed/renderer/kernel/rendering/baserenderer.cpp
// // This source file is part of appleseed. // Visit http://appleseedhq.net/ for additional information and resources. // // This software is released under the MIT license. // // Copyright (c) 2015-2016 Esteban Tovagliari, The appleseedhq Organization // // 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. // // Interface header. #include "baserenderer.h" // appleseed.renderer headers. #include "renderer/global/globallogger.h" #ifdef APPLESEED_WITH_OIIO #include "renderer/kernel/rendering/oiioerrorhandler.h" #endif #ifdef APPLESEED_WITH_OSL #include "renderer/kernel/rendering/rendererservices.h" #include "renderer/kernel/shading/closures.h" #endif #include "renderer/modeling/project/project.h" #include "renderer/modeling/scene/scene.h" // appleseed.foundation headers. #include "foundation/platform/compiler.h" // Standard headers. #include <cassert> #include <exception> #include <string> using namespace foundation; using namespace std; namespace renderer { // // BaseRenderer class implementation. // BaseRenderer::BaseRenderer( Project& project, const ParamArray& params) : m_project(project) , m_params(params) { #ifdef APPLESEED_WITH_OIIO m_error_handler = new OIIOErrorHandler(); #ifndef NDEBUG // While debugging, we want all possible outputs. m_error_handler->verbosity(OIIO::ErrorHandler::VERBOSE); #endif RENDERER_LOG_DEBUG("creating openimageio texture system..."); m_texture_system = OIIO::TextureSystem::create(false); m_texture_system->attribute("automip", 0); m_texture_system->attribute("accept_untiled", 1); m_texture_system->attribute("accept_unmipped", 1); m_texture_system->attribute("gray_to_rgb", 1); m_texture_system->attribute("latlong_up", "y"); #if OIIO_VERSION >= 10703 m_texture_system->attribute("flip_t", 1); #endif #endif #ifdef APPLESEED_WITH_OSL RENDERER_LOG_DEBUG("creating osl shading system..."); m_renderer_services = new RendererServices(m_project, *m_texture_system); #if OSL_LIBRARY_VERSION_CODE >= 10700 m_shading_system = new OSL::ShadingSystem( #else m_shading_system = OSL::ShadingSystem::create( #endif m_renderer_services, m_texture_system, m_error_handler); m_shading_system->attribute("lockgeom", 1); m_shading_system->attribute("colorspace", "Linear"); m_shading_system->attribute("commonspace", "world"); m_shading_system->attribute("statistics:level", 1); m_shading_system->attribute( "raytypes", OSL::TypeDesc( OSL::TypeDesc::STRING, static_cast<int>(VisibilityFlags::Count)), VisibilityFlags::Names); #ifndef NDEBUG // While debugging, we want all possible outputs. m_shading_system->attribute("debug", 1); m_shading_system->attribute("compile_report", 1); m_shading_system->attribute("countlayerexecs", 1); m_shading_system->attribute("clearmemory", 1); #endif // Register appleseed's closures into OSL's shading system. register_closures(*m_shading_system); #endif } BaseRenderer::~BaseRenderer() { #ifdef APPLESEED_WITH_OSL RENDERER_LOG_DEBUG("destroying osl shading system..."); m_project.get_scene()->release_optimized_osl_shader_groups(); #if OSL_LIBRARY_VERSION_CODE >= 10700 delete m_shading_system; #else OSL::ShadingSystem::destroy(m_shading_system); #endif delete m_renderer_services; #endif #ifdef APPLESEED_WITH_OIIO const string stats = m_texture_system->getstats(); const string trimmed_stats = trim_right(stats, "\r\n"); RENDERER_LOG_INFO("%s", trimmed_stats.c_str()); RENDERER_LOG_DEBUG("destroying openimageio texture system..."); OIIO::TextureSystem::destroy(m_texture_system); delete m_error_handler; #endif } ParamArray& BaseRenderer::get_parameters() { return m_params; } const ParamArray& BaseRenderer::get_parameters() const { return m_params; } bool BaseRenderer::initialize_shading_system( TextureStore& texture_store, IAbortSwitch& abort_switch) { #ifdef APPLESEED_WITH_OIIO initialize_oiio(); #endif #ifdef APPLESEED_WITH_OSL return initialize_osl(texture_store, abort_switch); #else return true; #endif } #ifdef APPLESEED_WITH_OIIO void BaseRenderer::initialize_oiio() { const ParamArray& params = m_params.child("texture_store"); const size_t texture_cache_size_bytes = params.get_optional<size_t>("max_size", 256 * 1024 * 1024); RENDERER_LOG_INFO( "setting openimageio texture cache size to %s.", pretty_size(texture_cache_size_bytes).c_str()); const float texture_cache_size_mb = static_cast<float>(texture_cache_size_bytes) / (1024 * 1024); m_texture_system->attribute("max_memory_MB", texture_cache_size_mb); // search paths string prev_search_path; m_texture_system->getattribute("searchpath", prev_search_path); const string new_search_path = m_project.make_search_path_string(); if (new_search_path != prev_search_path) { RENDERER_LOG_INFO( "setting openimageio search path to %s.", new_search_path.c_str()); m_texture_system->clear(); m_texture_system->attribute("searchpath", new_search_path); } } #endif #ifdef APPLESEED_WITH_OSL bool BaseRenderer::initialize_osl(TextureStore& texture_store, IAbortSwitch& abort_switch) { m_renderer_services->initialize(texture_store); // search paths string prev_search_path; m_shading_system->getattribute("searchpath:shader", prev_search_path); const string new_search_path = m_project.make_search_path_string(); if (new_search_path != prev_search_path) { RENDERER_LOG_INFO( "setting osl shader search path to %s.", new_search_path.c_str()); m_project.get_scene()->release_optimized_osl_shader_groups(); m_shading_system->attribute("searchpath:shader", new_search_path); } // Re-optimize the shadergroups that needs updating. return m_project.get_scene()->create_optimized_osl_shader_groups( *m_shading_system, &abort_switch); } #endif } // namespace renderer
// // This source file is part of appleseed. // Visit http://appleseedhq.net/ for additional information and resources. // // This software is released under the MIT license. // // Copyright (c) 2015-2016 Esteban Tovagliari, The appleseedhq Organization // // 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. // // Interface header. #include "baserenderer.h" // appleseed.renderer headers. #include "renderer/global/globallogger.h" #ifdef APPLESEED_WITH_OIIO #include "renderer/kernel/rendering/oiioerrorhandler.h" #endif #ifdef APPLESEED_WITH_OSL #include "renderer/kernel/rendering/rendererservices.h" #include "renderer/kernel/shading/closures.h" #endif #include "renderer/modeling/project/project.h" #include "renderer/modeling/scene/scene.h" // appleseed.foundation headers. #include "foundation/platform/compiler.h" // Standard headers. #include <cassert> #include <exception> #include <string> using namespace foundation; using namespace std; namespace renderer { // // BaseRenderer class implementation. // BaseRenderer::BaseRenderer( Project& project, const ParamArray& params) : m_project(project) , m_params(params) { #ifdef APPLESEED_WITH_OIIO m_error_handler = new OIIOErrorHandler(); #ifndef NDEBUG // While debugging, we want all possible outputs. m_error_handler->verbosity(OIIO::ErrorHandler::VERBOSE); #endif RENDERER_LOG_DEBUG("creating openimageio texture system..."); m_texture_system = OIIO::TextureSystem::create(false); m_texture_system->attribute("automip", 0); m_texture_system->attribute("accept_untiled", 1); m_texture_system->attribute("accept_unmipped", 1); m_texture_system->attribute("gray_to_rgb", 1); m_texture_system->attribute("latlong_up", "y"); #if OIIO_VERSION >= 10703 m_texture_system->attribute("flip_t", 1); #endif #endif #ifdef APPLESEED_WITH_OSL RENDERER_LOG_DEBUG("creating osl shading system..."); m_renderer_services = new RendererServices(m_project, *m_texture_system); #if OSL_LIBRARY_VERSION_CODE >= 10700 m_shading_system = new OSL::ShadingSystem( #else m_shading_system = OSL::ShadingSystem::create( #endif m_renderer_services, m_texture_system, m_error_handler); m_shading_system->attribute("lockgeom", 1); m_shading_system->attribute("colorspace", "Linear"); m_shading_system->attribute("commonspace", "world"); m_shading_system->attribute("statistics:level", 1); m_shading_system->attribute( "raytypes", OSL::TypeDesc( OSL::TypeDesc::STRING, static_cast<int>(VisibilityFlags::Count)), VisibilityFlags::Names); #ifndef NDEBUG // While debugging, we want all possible outputs. m_shading_system->attribute("debug", 1); m_shading_system->attribute("compile_report", 1); m_shading_system->attribute("countlayerexecs", 1); m_shading_system->attribute("clearmemory", 1); #endif // Register appleseed's closures into OSL's shading system. register_closures(*m_shading_system); #endif } BaseRenderer::~BaseRenderer() { #ifdef APPLESEED_WITH_OSL RENDERER_LOG_DEBUG("destroying osl shading system..."); m_project.get_scene()->release_optimized_osl_shader_groups(); #if OSL_LIBRARY_VERSION_CODE >= 10700 delete m_shading_system; #else OSL::ShadingSystem::destroy(m_shading_system); #endif delete m_renderer_services; #endif #ifdef APPLESEED_WITH_OIIO const string stats = m_texture_system->getstats(); const string trimmed_stats = trim_right(stats, "\r\n"); RENDERER_LOG_INFO("%s", trimmed_stats.c_str()); RENDERER_LOG_DEBUG("destroying openimageio texture system..."); OIIO::TextureSystem::destroy(m_texture_system); delete m_error_handler; #endif } ParamArray& BaseRenderer::get_parameters() { return m_params; } const ParamArray& BaseRenderer::get_parameters() const { return m_params; } bool BaseRenderer::initialize_shading_system( TextureStore& texture_store, IAbortSwitch& abort_switch) { #ifdef APPLESEED_WITH_OIIO initialize_oiio(); #endif #ifdef APPLESEED_WITH_OSL return initialize_osl(texture_store, abort_switch); #else return true; #endif } #ifdef APPLESEED_WITH_OIIO void BaseRenderer::initialize_oiio() { const ParamArray& params = m_params.child("texture_store"); const size_t texture_cache_size_bytes = params.get_optional<size_t>("max_size", 256 * 1024 * 1024); RENDERER_LOG_INFO( "setting openimageio texture cache size to %s.", pretty_size(texture_cache_size_bytes).c_str()); const float texture_cache_size_mb = static_cast<float>(texture_cache_size_bytes) / (1024 * 1024); m_texture_system->attribute("max_memory_MB", texture_cache_size_mb); // search paths string prev_search_path; m_texture_system->getattribute("searchpath", prev_search_path); const string new_search_path = m_project.make_search_path_string(); if (new_search_path != prev_search_path) { RENDERER_LOG_INFO( "setting openimageio search path to %s.", new_search_path.c_str()); m_texture_system->clear(); m_texture_system->attribute("searchpath", new_search_path); } } #endif #ifdef APPLESEED_WITH_OSL bool BaseRenderer::initialize_osl(TextureStore& texture_store, IAbortSwitch& abort_switch) { m_renderer_services->initialize(texture_store); // search paths string prev_search_path; m_shading_system->getattribute("searchpath:shader", prev_search_path); const string new_search_path = m_project.make_search_path_string(); if (new_search_path != prev_search_path) { RENDERER_LOG_INFO( "setting osl shader search path to %s.", new_search_path.c_str()); m_project.get_scene()->release_optimized_osl_shader_groups(); m_shading_system->attribute("searchpath:shader", new_search_path); } // Re-optimize the shader groups that need updating. return m_project.get_scene()->create_optimized_osl_shader_groups( *m_shading_system, &abort_switch); } #endif } // namespace renderer
Fix typo and tweak formatting
Fix typo and tweak formatting
C++
mit
Aakash1312/appleseed,gospodnetic/appleseed,aytekaman/appleseed,Aakash1312/appleseed,luisbarrancos/appleseed,Aakash1312/appleseed,pjessesco/appleseed,gospodnetic/appleseed,pjessesco/appleseed,glebmish/appleseed,est77/appleseed,Aakash1312/appleseed,aiivashchenko/appleseed,Vertexwahn/appleseed,aiivashchenko/appleseed,dictoon/appleseed,Biart95/appleseed,Biart95/appleseed,Biart95/appleseed,dictoon/appleseed,gospodnetic/appleseed,aytekaman/appleseed,aiivashchenko/appleseed,luisbarrancos/appleseed,appleseedhq/appleseed,appleseedhq/appleseed,aiivashchenko/appleseed,pjessesco/appleseed,Vertexwahn/appleseed,aiivashchenko/appleseed,est77/appleseed,aytekaman/appleseed,dictoon/appleseed,Biart95/appleseed,est77/appleseed,glebmish/appleseed,dictoon/appleseed,gospodnetic/appleseed,pjessesco/appleseed,est77/appleseed,luisbarrancos/appleseed,Biart95/appleseed,luisbarrancos/appleseed,Aakash1312/appleseed,glebmish/appleseed,Vertexwahn/appleseed,Vertexwahn/appleseed,appleseedhq/appleseed,glebmish/appleseed,gospodnetic/appleseed,luisbarrancos/appleseed,appleseedhq/appleseed,glebmish/appleseed,pjessesco/appleseed,appleseedhq/appleseed,dictoon/appleseed,aytekaman/appleseed,est77/appleseed,Vertexwahn/appleseed,aytekaman/appleseed
ce8732db1523a4f7f136aaea70f35edcedba749a
modules/gui/qt4/components/playlist/icon_view.cpp
modules/gui/qt4/components/playlist/icon_view.cpp
/***************************************************************************** * icon_view.cpp : Icon view for the Playlist **************************************************************************** * Copyright © 2010 the VideoLAN team * $Id$ * * Authors: Jean-Baptiste Kempf <[email protected]> * * 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; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA. *****************************************************************************/ #include "components/playlist/icon_view.hpp" #include "components/playlist/playlist_model.hpp" #include <QPainter> void PlListViewItemDelegate::paint( QPainter * painter, const QStyleOptionViewItem & option, const QModelIndex & index ) const { } QSize PlListViewItemDelegate::sizeHint ( const QStyleOptionViewItem & option, const QModelIndex & index ) const { return QSize(100, 100); } PlIconView::PlIconView( PLModel *model, QWidget *parent ) : QListView( parent ) { setModel( model ); setViewMode( QListView::IconMode ); setMovement( QListView::Snap ); PlListViewItemDelegate *pl = new PlListViewItemDelegate(); setItemDelegate( pl ); }
/***************************************************************************** * icon_view.cpp : Icon view for the Playlist **************************************************************************** * Copyright © 2010 the VideoLAN team * $Id$ * * Authors: Jean-Baptiste Kempf <[email protected]> * * 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; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA. *****************************************************************************/ #include "components/playlist/icon_view.hpp" #include "components/playlist/playlist_model.hpp" #include <QPainter> void PlListViewItemDelegate::paint( QPainter * painter, const QStyleOptionViewItem & option, const QModelIndex & index ) const { QStyledItemDelegate::paint( painter, option, index ); } QSize PlListViewItemDelegate::sizeHint ( const QStyleOptionViewItem & option, const QModelIndex & index ) const { return QSize(100, 100); } PlIconView::PlIconView( PLModel *model, QWidget *parent ) : QListView( parent ) { setModel( model ); setViewMode( QListView::IconMode ); setMovement( QListView::Snap ); PlListViewItemDelegate *pl = new PlListViewItemDelegate(); setItemDelegate( pl ); }
use a dummy painting for iconView until better
Qt: use a dummy painting for iconView until better
C++
lgpl-2.1
krichter722/vlc,jomanmuk/vlc-2.2,jomanmuk/vlc-2.2,jomanmuk/vlc-2.1,jomanmuk/vlc-2.2,krichter722/vlc,vlc-mirror/vlc,vlc-mirror/vlc,krichter722/vlc,jomanmuk/vlc-2.1,vlc-mirror/vlc-2.1,xkfz007/vlc,vlc-mirror/vlc,vlc-mirror/vlc,krichter722/vlc,shyamalschandra/vlc,vlc-mirror/vlc-2.1,jomanmuk/vlc-2.2,vlc-mirror/vlc,krichter722/vlc,vlc-mirror/vlc-2.1,shyamalschandra/vlc,xkfz007/vlc,vlc-mirror/vlc,jomanmuk/vlc-2.2,vlc-mirror/vlc,vlc-mirror/vlc-2.1,shyamalschandra/vlc,shyamalschandra/vlc,jomanmuk/vlc-2.1,shyamalschandra/vlc,jomanmuk/vlc-2.2,xkfz007/vlc,xkfz007/vlc,vlc-mirror/vlc-2.1,vlc-mirror/vlc-2.1,krichter722/vlc,xkfz007/vlc,vlc-mirror/vlc-2.1,xkfz007/vlc,xkfz007/vlc,jomanmuk/vlc-2.1,jomanmuk/vlc-2.2,jomanmuk/vlc-2.1,shyamalschandra/vlc,shyamalschandra/vlc,jomanmuk/vlc-2.1,krichter722/vlc,jomanmuk/vlc-2.1
bd377b40969b25e19c37c38a3a847c875530c53c
modules/vapor/vpr/md/POSIX/IO/SelectorImplBSD.cpp
modules/vapor/vpr/md/POSIX/IO/SelectorImplBSD.cpp
/*************** <auto-copyright.pl BEGIN do not edit this line> ************** * * VR Juggler is (C) Copyright 1998, 1999, 2000 by Iowa State University * * Original Authors: * Allen Bierbaum, Christopher Just, * Patrick Hartling, Kevin Meinert, * Carolina Cruz-Neira, Albert Baker * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public * License along with this library; if not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * Boston, MA 02111-1307, USA. * * ----------------------------------------------------------------- * File: $RCSfile$ * Date modified: $Date$ * Version: $Revision$ * ----------------------------------------------------------------- * *************** <auto-copyright.pl END do not edit this line> ***************/ #include <vpr/vprConfig.h> #include <stdio.h> #include <string.h> #include <unistd.h> #include <sys/types.h> #ifdef HAVE_BSTRING_H #include <bstring.h> #endif #include <sys/time.h> #include <errno.h> #include <vpr/md/POSIX/IO/SelectorImplBSD.h> #include <vpr/Util/Assert.h> namespace vpr { //: Add the given handle to the selector //! PRE: handle is a valid handle //! POST: handle is added to the handle set, and initialized to a mask of //+ no-events bool SelectorImplBSD::addHandle (IOSys::Handle handle) { bool status; if ( getHandle(handle) == mPollDescs.end() ) { BSDPollDesc new_desc; new_desc.fd = handle; new_desc.in_flags = 0; new_desc.out_flags = 0; mPollDescs.push_back(new_desc); status = true; } else { status = false; } return status; } //: Remove a handle from the selector //! PRE: handle is in the selector //! POST: handle is removed from the set of valid handles bool SelectorImplBSD::removeHandle (IOSys::Handle handle) { bool status; std::vector<BSDPollDesc>::iterator i = getHandle(handle); if ( mPollDescs.end() == i ) { status = false; } else { mPollDescs.erase(i); status = true; } return status; } //: Set the event flags going in to the select to mask bool SelectorImplBSD::setIn (IOSys::Handle handle, vpr::Uint16 mask) { bool status; std::vector<BSDPollDesc>::iterator i = getHandle(handle); if ( mPollDescs.end() == i ) { status = false; } else { (*i).in_flags = mask; status = true; } return status; } //: Get the current in flag mask vpr::Uint16 SelectorImplBSD::getIn (IOSys::Handle handle) { vpr::Uint16 flags; std::vector<BSDPollDesc>::iterator i = getHandle(handle); if ( mPollDescs.end() == i ) { // XXX: This is VERY bad thing to do. Need to have an error code instead flags = 0; } else { flags = (*i).in_flags; } return flags; } //: Get the current out flag mask vpr::Uint16 SelectorImplBSD::getOut (IOSys::Handle handle) { vpr::Uint16 flags; std::vector<BSDPollDesc>::iterator i = getHandle(handle); if ( mPollDescs.end() == i ) { // XXX: This is VERY bad thing to do. Need to have an error code instead flags = 0; } else { flags = (*i).out_flags; } return flags; } //: Select //! ARGS: numWithEvents - Upon completion, this holds the number of items that //+ have events //! ARGS: timeout - The number of msecs to select for (0 - don't wait) Status SelectorImplBSD::select (vpr::Uint16& numWithEvents, const vpr::Interval timeout) { vpr::Status ret_val; int result, last_fd; fd_set read_set, write_set, exception_set; std::vector<BSDPollDesc>::iterator i; struct timeval timeout_obj; // Zero everything out before doing anything else. FD_ZERO(&read_set); FD_ZERO(&write_set); FD_ZERO(&exception_set); last_fd = -1; for ( i = mPollDescs.begin(); i != mPollDescs.end(); i++ ) { (*i).out_flags = 0; if ( (*i).in_flags & SelectorBase::VPR_READ ) { FD_SET((*i).fd, &read_set); } if ( (*i).in_flags & SelectorBase::VPR_WRITE ) { FD_SET((*i).fd, &write_set); } if ( (*i).in_flags & SelectorBase::VPR_EXCEPT ) { FD_SET((*i).fd, &exception_set); } // Find the highest-valued file descriptor. if ( last_fd < (*i).fd ) { last_fd = (*i).fd; } } // Apparently select(2) doesn't like if the microsecond member has a time // larger than 1 second, so if timeout (given in milliseconds) is larger // than 1000, we have to split it up between the seconds and microseconds // members. if ( timeout.msec() >= 1000 ) { timeout_obj.tv_sec = timeout.msec() / 1000; timeout_obj.tv_usec = (timeout.msec() % 1000) * 1000000; } else { timeout_obj.tv_sec = 0; timeout_obj.tv_usec = timeout.msec() * 1000; } // If timeout is 0, this will be the same as polling the descriptors. To // get no timeout, NULL must be passed to select(2). result = ::select(last_fd + 1, &read_set, &write_set, &exception_set, (timeout.usec() > 0) ? &timeout_obj : NULL); // D'oh! if ( -1 == result ) { fprintf(stderr, "SelectorImplBSD::select: Error selecting: %s\n", strerror(errno)); numWithEvents = 0; ret_val.setCode(Status::Failure); } // Timeout. else if ( 0 == result ) { numWithEvents = 0; ret_val.setCode(Status::Timeout); } // We got one! else { for ( i = mPollDescs.begin(); i != mPollDescs.end(); i++ ) { if ( FD_ISSET((*i).fd, &read_set) ) { (*i).out_flags |= SelectorBase::VPR_READ; } if ( FD_ISSET((*i).fd, &write_set) ) { (*i).out_flags |= SelectorBase::VPR_WRITE; } if ( FD_ISSET((*i).fd, &exception_set) ) { (*i).out_flags |= SelectorBase::VPR_EXCEPT; } } numWithEvents = result; } return ret_val; } // Get the index of the handle given //! RETURNS: .end() - Not found, else the index to the handle in mPollDescs std::vector<SelectorImplBSD::BSDPollDesc>::iterator SelectorImplBSD::getHandle (int handle) { // XXX: Should probably be replaced by a map in the future for speed for(std::vector<BSDPollDesc>::iterator i=mPollDescs.begin(); i != mPollDescs.end();i++) { if((*i).fd == handle) return i; } return mPollDescs.end(); } } // namespace vpr
/*************** <auto-copyright.pl BEGIN do not edit this line> ************** * * VR Juggler is (C) Copyright 1998, 1999, 2000 by Iowa State University * * Original Authors: * Allen Bierbaum, Christopher Just, * Patrick Hartling, Kevin Meinert, * Carolina Cruz-Neira, Albert Baker * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public * License along with this library; if not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * Boston, MA 02111-1307, USA. * * ----------------------------------------------------------------- * File: $RCSfile$ * Date modified: $Date$ * Version: $Revision$ * ----------------------------------------------------------------- * *************** <auto-copyright.pl END do not edit this line> ***************/ #include <vpr/vprConfig.h> #include <stdio.h> #include <string.h> #include <unistd.h> #include <sys/types.h> #ifdef HAVE_BSTRING_H #include <bstring.h> #endif #include <sys/time.h> #include <errno.h> #include <vpr/md/POSIX/IO/SelectorImplBSD.h> #include <vpr/Util/Assert.h> namespace vpr { //: Add the given handle to the selector //! PRE: handle is a valid handle //! POST: handle is added to the handle set, and initialized to a mask of //+ no-events bool SelectorImplBSD::addHandle (IOSys::Handle handle) { bool status; if ( getHandle(handle) == mPollDescs.end() ) { BSDPollDesc new_desc; new_desc.fd = handle; new_desc.in_flags = 0; new_desc.out_flags = 0; mPollDescs.push_back(new_desc); status = true; } else { status = false; } return status; } //: Remove a handle from the selector //! PRE: handle is in the selector //! POST: handle is removed from the set of valid handles bool SelectorImplBSD::removeHandle (IOSys::Handle handle) { bool status; std::vector<BSDPollDesc>::iterator i = getHandle(handle); if ( mPollDescs.end() == i ) { status = false; } else { mPollDescs.erase(i); status = true; } return status; } //: Set the event flags going in to the select to mask bool SelectorImplBSD::setIn (IOSys::Handle handle, vpr::Uint16 mask) { bool status; std::vector<BSDPollDesc>::iterator i = getHandle(handle); if ( mPollDescs.end() == i ) { status = false; } else { (*i).in_flags = mask; status = true; } return status; } //: Get the current in flag mask vpr::Uint16 SelectorImplBSD::getIn (IOSys::Handle handle) { vpr::Uint16 flags; std::vector<BSDPollDesc>::iterator i = getHandle(handle); if ( mPollDescs.end() == i ) { // XXX: This is VERY bad thing to do. Need to have an error code instead flags = 0; } else { flags = (*i).in_flags; } return flags; } //: Get the current out flag mask vpr::Uint16 SelectorImplBSD::getOut (IOSys::Handle handle) { vpr::Uint16 flags; std::vector<BSDPollDesc>::iterator i = getHandle(handle); if ( mPollDescs.end() == i ) { // XXX: This is VERY bad thing to do. Need to have an error code instead flags = 0; } else { flags = (*i).out_flags; } return flags; } //: Select //! ARGS: numWithEvents - Upon completion, this holds the number of items that //+ have events //! ARGS: timeout - The number of msecs to select for (0 - don't wait) Status SelectorImplBSD::select (vpr::Uint16& numWithEvents, const vpr::Interval timeout) { vpr::Status ret_val; int result, last_fd; fd_set read_set, write_set, exception_set; std::vector<BSDPollDesc>::iterator i; struct timeval timeout_obj; // Zero everything out before doing anything else. FD_ZERO(&read_set); FD_ZERO(&write_set); FD_ZERO(&exception_set); last_fd = -1; for ( i = mPollDescs.begin(); i != mPollDescs.end(); i++ ) { (*i).out_flags = 0; if ( (*i).in_flags & SelectorBase::VPR_READ ) { FD_SET((*i).fd, &read_set); } if ( (*i).in_flags & SelectorBase::VPR_WRITE ) { FD_SET((*i).fd, &write_set); } if ( (*i).in_flags & SelectorBase::VPR_EXCEPT ) { FD_SET((*i).fd, &exception_set); } // Find the highest-valued file descriptor. if ( last_fd < (*i).fd ) { last_fd = (*i).fd; } } if ( timeout == vpr::Interval::NoWait ) { timeout_obj.tv_sec = 0; timeout_obj.tv_usec = 0; } else { // Apparently select(2) doesn't like if the microsecond member has a // time larger than 1 second, so if timeout (given in milliseconds) is // larger than 1000, we have to split it up between the seconds and // microseconds members. if ( timeout.msec() >= 1000 ) { timeout_obj.tv_sec = timeout.msec() / 1000; timeout_obj.tv_usec = (timeout.msec() % 1000) * 1000000; } else { timeout_obj.tv_sec = 0; timeout_obj.tv_usec = timeout.msec() * 1000; } } // If timeout is 0, this will be the same as polling the descriptors. To // get no timeout, NULL must be passed to select(2). result = ::select(last_fd + 1, &read_set, &write_set, &exception_set, (timeout.usec() > 0) ? &timeout_obj : NULL); // D'oh! if ( -1 == result ) { fprintf(stderr, "SelectorImplBSD::select: Error selecting: %s\n", strerror(errno)); numWithEvents = 0; ret_val.setCode(Status::Failure); } // Timeout. else if ( 0 == result ) { numWithEvents = 0; ret_val.setCode(Status::Timeout); } // We got one! else { for ( i = mPollDescs.begin(); i != mPollDescs.end(); i++ ) { if ( FD_ISSET((*i).fd, &read_set) ) { (*i).out_flags |= SelectorBase::VPR_READ; } if ( FD_ISSET((*i).fd, &write_set) ) { (*i).out_flags |= SelectorBase::VPR_WRITE; } if ( FD_ISSET((*i).fd, &exception_set) ) { (*i).out_flags |= SelectorBase::VPR_EXCEPT; } } numWithEvents = result; } return ret_val; } // Get the index of the handle given //! RETURNS: .end() - Not found, else the index to the handle in mPollDescs std::vector<SelectorImplBSD::BSDPollDesc>::iterator SelectorImplBSD::getHandle (int handle) { // XXX: Should probably be replaced by a map in the future for speed for(std::vector<BSDPollDesc>::iterator i=mPollDescs.begin(); i != mPollDescs.end();i++) { if((*i).fd == handle) return i; } return mPollDescs.end(); } } // namespace vpr
Handle the new vpr::Interval::NoWait value correctly. In this case, we want select(2) to poll the descriptors. I need to verify, however, that NSPR's PR_Poll() actually allows polling in this manner.
Handle the new vpr::Interval::NoWait value correctly. In this case, we want select(2) to poll the descriptors. I need to verify, however, that NSPR's PR_Poll() actually allows polling in this manner. git-svn-id: 769d22dfa2d22aad706b9a451492fb87c0735f19@5213 08b38cba-cd3b-11de-854e-f91c5b6e4272
C++
lgpl-2.1
vrjuggler/vrjuggler,MichaelMcDonnell/vrjuggler,LiuKeHua/vrjuggler,godbyk/vrjuggler-upstream-old,vrjuggler/vrjuggler,vancegroup-mirrors/vrjuggler,godbyk/vrjuggler-upstream-old,MichaelMcDonnell/vrjuggler,vancegroup-mirrors/vrjuggler,MichaelMcDonnell/vrjuggler,godbyk/vrjuggler-upstream-old,LiuKeHua/vrjuggler,godbyk/vrjuggler-upstream-old,MichaelMcDonnell/vrjuggler,LiuKeHua/vrjuggler,vrjuggler/vrjuggler,vrjuggler/vrjuggler,vancegroup-mirrors/vrjuggler,MichaelMcDonnell/vrjuggler,LiuKeHua/vrjuggler,MichaelMcDonnell/vrjuggler,godbyk/vrjuggler-upstream-old,vrjuggler/vrjuggler,vancegroup-mirrors/vrjuggler,vrjuggler/vrjuggler,godbyk/vrjuggler-upstream-old,LiuKeHua/vrjuggler,vrjuggler/vrjuggler,vancegroup-mirrors/vrjuggler,MichaelMcDonnell/vrjuggler,LiuKeHua/vrjuggler,LiuKeHua/vrjuggler,vancegroup-mirrors/vrjuggler,LiuKeHua/vrjuggler,vrjuggler/vrjuggler,MichaelMcDonnell/vrjuggler
adc704563ca55244c65b58b3c17231ba6ee5882a
src/qt/bitcoin.cpp
src/qt/bitcoin.cpp
/* * W.J. van der Laan 2011-2012 */ #include "bitcoingui.h" #include "clientmodel.h" #include "walletmodel.h" #include "optionsmodel.h" #include "guiutil.h" #include "guiconstants.h" #include "init.h" #include "ui_interface.h" #include "qtipcserver.h" #include <QApplication> #include <QMessageBox> #include <QTextCodec> #include <QLocale> #include <QTranslator> #include <QSplashScreen> #include <QLibraryInfo> #include <boost/interprocess/ipc/message_queue.hpp> #if defined(BITCOIN_NEED_QT_PLUGINS) && !defined(_BITCOIN_QT_PLUGINS_INCLUDED) #define _BITCOIN_QT_PLUGINS_INCLUDED #define __INSURE__ #include <QtPlugin> Q_IMPORT_PLUGIN(qcncodecs) Q_IMPORT_PLUGIN(qjpcodecs) Q_IMPORT_PLUGIN(qtwcodecs) Q_IMPORT_PLUGIN(qkrcodecs) Q_IMPORT_PLUGIN(qtaccessiblewidgets) #endif // Need a global reference for the notifications to find the GUI static BitcoinGUI *guiref; static QSplashScreen *splashref; static WalletModel *walletmodel; static ClientModel *clientmodel; int ThreadSafeMessageBox(const std::string& message, const std::string& caption, int style) { // Message from network thread if(guiref) { bool modal = (style & wxMODAL); // in case of modal message, use blocking connection to wait for user to click OK QMetaObject::invokeMethod(guiref, "error", modal ? GUIUtil::blockingGUIThreadConnection() : Qt::QueuedConnection, Q_ARG(QString, QString::fromStdString(caption)), Q_ARG(QString, QString::fromStdString(message)), Q_ARG(bool, modal)); } else { printf("%s: %s\n", caption.c_str(), message.c_str()); fprintf(stderr, "%s: %s\n", caption.c_str(), message.c_str()); } return 4; } bool ThreadSafeAskFee(int64 nFeeRequired, const std::string& strCaption) { if(!guiref) return false; if(nFeeRequired < MIN_TX_FEE || nFeeRequired <= nTransactionFee || fDaemon) return true; bool payFee = false; QMetaObject::invokeMethod(guiref, "askFee", GUIUtil::blockingGUIThreadConnection(), Q_ARG(qint64, nFeeRequired), Q_ARG(bool*, &payFee)); return payFee; } void ThreadSafeHandleURI(const std::string& strURI) { if(!guiref) return; QMetaObject::invokeMethod(guiref, "handleURI", GUIUtil::blockingGUIThreadConnection(), Q_ARG(QString, QString::fromStdString(strURI))); } void MainFrameRepaint() { if(clientmodel) QMetaObject::invokeMethod(clientmodel, "update", Qt::QueuedConnection); if(walletmodel) QMetaObject::invokeMethod(walletmodel, "update", Qt::QueuedConnection); } void AddressBookRepaint() { if(walletmodel) QMetaObject::invokeMethod(walletmodel, "updateAddressList", Qt::QueuedConnection); } void InitMessage(const std::string &message) { if(splashref) { splashref->showMessage(QString::fromStdString(message), Qt::AlignBottom|Qt::AlignHCenter, QColor(255,255,200)); QApplication::instance()->processEvents(); } } void QueueShutdown() { QMetaObject::invokeMethod(QCoreApplication::instance(), "quit", Qt::QueuedConnection); } /* Translate string to current locale using Qt. */ std::string _(const char* psz) { return QCoreApplication::translate("bitcoin-core", psz).toStdString(); } /* Handle runaway exceptions. Shows a message box with the problem and quits the program. */ static void handleRunawayException(std::exception *e) { PrintExceptionContinue(e, "Runaway exception"); QMessageBox::critical(0, "Runaway exception", BitcoinGUI::tr("A fatal error occured. Bitcoin can no longer continue safely and will quit.") + QString("\n\n") + QString::fromStdString(strMiscWarning)); exit(1); } /** Help message for Bitcoin-Qt, shown with --help. */ class HelpMessageBox: public QMessageBox { public: HelpMessageBox(QWidget *parent = 0); void exec(); private: QString header; QString coreOptions; QString uiOptions; }; #include <QSpacerItem> #include <QGridLayout> HelpMessageBox::HelpMessageBox(QWidget *parent): QMessageBox(parent) { header = tr("Bitcoin-Qt") + " " + tr("version") + " " + QString::fromStdString(FormatFullVersion()) + "\n\n" + tr("Usage:") + "\n" + " bitcoin-qt [options] " + "\n"; coreOptions = QString::fromStdString(HelpMessage()); uiOptions = tr("UI options") + ":\n" + " -lang=<lang> " + tr("Set language, for example \"de_DE\" (default: system locale)") + "\n" + " -min " + tr("Start minimized") + "\n" + " -splash " + tr("Show splash screen on startup (default: 1)") + "\n"; setWindowTitle(tr("Bitcoin-Qt")); setTextFormat(Qt::PlainText); // setMinimumWidth is ignored for QMessageBox so put in nonbreaking spaces to make it wider. QChar em_space(0x2003); setText(header + QString(em_space).repeated(40)); setDetailedText(coreOptions + "\n" + uiOptions); } void HelpMessageBox::exec() { #if defined(WIN32) // On windows, show a message box, as there is no stderr in windowed applications QMessageBox::exec(); #else // On other operating systems, the expected action is to print the message to the console. QString strUsage = header + "\n" + coreOptions + "\n" + uiOptions; fprintf(stderr, "%s", strUsage.toStdString().c_str()); #endif } #ifdef WIN32 #define strncasecmp strnicmp #endif #ifndef BITCOIN_QT_TEST int main(int argc, char *argv[]) { #if !defined(MAC_OSX) && !defined(WIN32) // TODO: implement qtipcserver.cpp for Mac and Windows // Do this early as we don't want to bother initializing if we are just calling IPC for (int i = 1; i < argc; i++) { if (strlen(argv[i]) > 7 && strncasecmp(argv[i], "bitcoin:", 8) == 0) { const char *strURI = argv[i]; try { boost::interprocess::message_queue mq(boost::interprocess::open_only, BITCOINURI_QUEUE_NAME); if(mq.try_send(strURI, strlen(strURI), 0)) exit(0); else break; } catch (boost::interprocess::interprocess_exception &ex) { break; } } } #endif // Internal string conversion is all UTF-8 QTextCodec::setCodecForTr(QTextCodec::codecForName("UTF-8")); QTextCodec::setCodecForCStrings(QTextCodec::codecForTr()); Q_INIT_RESOURCE(bitcoin); QApplication app(argc, argv); // Install global event filter that makes sure that long tooltips can be word-wrapped app.installEventFilter(new GUIUtil::ToolTipToRichTextFilter(TOOLTIP_WRAP_THRESHOLD, &app)); // Command-line options take precedence: ParseParameters(argc, argv); // ... then bitcoin.conf: if (!boost::filesystem::is_directory(GetDataDir(false))) { fprintf(stderr, "Error: Specified directory does not exist\n"); return 1; } ReadConfigFile(mapArgs, mapMultiArgs); // Application identification (must be set before OptionsModel is initialized, // as it is used to locate QSettings) app.setOrganizationName("Bitcoin"); app.setOrganizationDomain("bitcoin.org"); if(GetBoolArg("-testnet")) // Separate UI settings for testnet app.setApplicationName("Bitcoin-Qt-testnet"); else app.setApplicationName("Bitcoin-Qt"); // ... then GUI settings: OptionsModel optionsModel; // Get desired locale (e.g. "de_DE") from command line or use system locale QString lang_territory = QString::fromStdString(GetArg("-lang", QLocale::system().name().toStdString())); QString lang = lang_territory; // Convert to "de" only by truncating "_DE" lang.truncate(lang_territory.lastIndexOf('_')); QTranslator qtTranslatorBase, qtTranslator, translatorBase, translator; // Load language files for configured locale: // - First load the translator for the base language, without territory // - Then load the more specific locale translator // Load e.g. qt_de.qm if (qtTranslatorBase.load("qt_" + lang, QLibraryInfo::location(QLibraryInfo::TranslationsPath))) app.installTranslator(&qtTranslatorBase); // Load e.g. qt_de_DE.qm if (qtTranslator.load("qt_" + lang_territory, QLibraryInfo::location(QLibraryInfo::TranslationsPath))) app.installTranslator(&qtTranslator); // Load e.g. bitcoin_de.qm (shortcut "de" needs to be defined in bitcoin.qrc) if (translatorBase.load(lang, ":/translations/")) app.installTranslator(&translatorBase); // Load e.g. bitcoin_de_DE.qm (shortcut "de_DE" needs to be defined in bitcoin.qrc) if (translator.load(lang_territory, ":/translations/")) app.installTranslator(&translator); // Show help message immediately after parsing command-line options (for "-lang") and setting locale, // but before showing splash screen. if (mapArgs.count("-?") || mapArgs.count("--help")) { HelpMessageBox help; help.exec(); return 1; } QSplashScreen splash(QPixmap(":/images/splash"), 0); if (GetBoolArg("-splash", true) && !GetBoolArg("-min")) { splash.show(); splash.setAutoFillBackground(true); splashref = &splash; } app.processEvents(); app.setQuitOnLastWindowClosed(false); try { // Regenerate startup link, to fix links to old versions if (GUIUtil::GetStartOnSystemStartup()) GUIUtil::SetStartOnSystemStartup(true); BitcoinGUI window; guiref = &window; if(AppInit2()) { { // Put this in a block, so that the Model objects are cleaned up before // calling Shutdown(). optionsModel.Upgrade(); // Must be done after AppInit2 if (splashref) splash.finish(&window); ClientModel clientModel(&optionsModel); clientmodel = &clientModel; WalletModel walletModel(pwalletMain, &optionsModel); walletmodel = &walletModel; window.setClientModel(&clientModel); window.setWalletModel(&walletModel); // If -min option passed, start window minimized. if(GetBoolArg("-min")) { window.showMinimized(); } else { window.show(); } // Place this here as guiref has to be defined if we dont want to lose URIs ipcInit(); #if !defined(MAC_OSX) && !defined(WIN32) // TODO: implement qtipcserver.cpp for Mac and Windows // Check for URI in argv for (int i = 1; i < argc; i++) { if (strlen(argv[i]) > 7 && strncasecmp(argv[i], "bitcoin:", 8) == 0) { const char *strURI = argv[i]; try { boost::interprocess::message_queue mq(boost::interprocess::open_only, BITCOINURI_QUEUE_NAME); mq.try_send(strURI, strlen(strURI), 0); } catch (boost::interprocess::interprocess_exception &ex) { } } } #endif app.exec(); window.hide(); window.setClientModel(0); window.setWalletModel(0); guiref = 0; clientmodel = 0; walletmodel = 0; } Shutdown(NULL); } else { return 1; } } catch (std::exception& e) { handleRunawayException(&e); } catch (...) { handleRunawayException(NULL); } return 0; } #endif // BITCOIN_QT_TEST
/* * W.J. van der Laan 2011-2012 */ #include "bitcoingui.h" #include "clientmodel.h" #include "walletmodel.h" #include "optionsmodel.h" #include "guiutil.h" #include "guiconstants.h" #include "init.h" #include "ui_interface.h" #include "qtipcserver.h" #include <QApplication> #include <QMessageBox> #include <QTextCodec> #include <QLocale> #include <QTranslator> #include <QSplashScreen> #include <QLibraryInfo> #include <boost/interprocess/ipc/message_queue.hpp> #if defined(BITCOIN_NEED_QT_PLUGINS) && !defined(_BITCOIN_QT_PLUGINS_INCLUDED) #define _BITCOIN_QT_PLUGINS_INCLUDED #define __INSURE__ #include <QtPlugin> Q_IMPORT_PLUGIN(qcncodecs) Q_IMPORT_PLUGIN(qjpcodecs) Q_IMPORT_PLUGIN(qtwcodecs) Q_IMPORT_PLUGIN(qkrcodecs) Q_IMPORT_PLUGIN(qtaccessiblewidgets) #endif // Need a global reference for the notifications to find the GUI static BitcoinGUI *guiref; static QSplashScreen *splashref; static WalletModel *walletmodel; static ClientModel *clientmodel; int ThreadSafeMessageBox(const std::string& message, const std::string& caption, int style) { // Message from network thread if(guiref) { bool modal = (style & wxMODAL); // in case of modal message, use blocking connection to wait for user to click OK QMetaObject::invokeMethod(guiref, "error", modal ? GUIUtil::blockingGUIThreadConnection() : Qt::QueuedConnection, Q_ARG(QString, QString::fromStdString(caption)), Q_ARG(QString, QString::fromStdString(message)), Q_ARG(bool, modal)); } else { printf("%s: %s\n", caption.c_str(), message.c_str()); fprintf(stderr, "%s: %s\n", caption.c_str(), message.c_str()); } return 4; } bool ThreadSafeAskFee(int64 nFeeRequired, const std::string& strCaption) { if(!guiref) return false; if(nFeeRequired < MIN_TX_FEE || nFeeRequired <= nTransactionFee || fDaemon) return true; bool payFee = false; QMetaObject::invokeMethod(guiref, "askFee", GUIUtil::blockingGUIThreadConnection(), Q_ARG(qint64, nFeeRequired), Q_ARG(bool*, &payFee)); return payFee; } void ThreadSafeHandleURI(const std::string& strURI) { if(!guiref) return; QMetaObject::invokeMethod(guiref, "handleURI", GUIUtil::blockingGUIThreadConnection(), Q_ARG(QString, QString::fromStdString(strURI))); } void MainFrameRepaint() { if(clientmodel) QMetaObject::invokeMethod(clientmodel, "update", Qt::QueuedConnection); if(walletmodel) QMetaObject::invokeMethod(walletmodel, "update", Qt::QueuedConnection); } void AddressBookRepaint() { if(walletmodel) QMetaObject::invokeMethod(walletmodel, "updateAddressList", Qt::QueuedConnection); } void InitMessage(const std::string &message) { if(splashref) { splashref->showMessage(QString::fromStdString(message), Qt::AlignBottom|Qt::AlignHCenter, QColor(255,255,200)); QApplication::instance()->processEvents(); } } void QueueShutdown() { QMetaObject::invokeMethod(QCoreApplication::instance(), "quit", Qt::QueuedConnection); } /* Translate string to current locale using Qt. */ std::string _(const char* psz) { return QCoreApplication::translate("bitcoin-core", psz).toStdString(); } /* Handle runaway exceptions. Shows a message box with the problem and quits the program. */ static void handleRunawayException(std::exception *e) { PrintExceptionContinue(e, "Runaway exception"); QMessageBox::critical(0, "Runaway exception", BitcoinGUI::tr("A fatal error occured. Bitcoin can no longer continue safely and will quit.") + QString("\n\n") + QString::fromStdString(strMiscWarning)); exit(1); } /** Help message for Bitcoin-Qt, shown with --help. */ class HelpMessageBox: public QMessageBox { Q_OBJECT public: HelpMessageBox(QWidget *parent = 0); void exec(); private: QString header; QString coreOptions; QString uiOptions; }; HelpMessageBox::HelpMessageBox(QWidget *parent): QMessageBox(parent) { header = tr("Bitcoin-Qt") + " " + tr("version") + " " + QString::fromStdString(FormatFullVersion()) + "\n\n" + tr("Usage:") + "\n" + " bitcoin-qt [options] " + "\n"; coreOptions = QString::fromStdString(HelpMessage()); uiOptions = tr("UI options") + ":\n" + " -lang=<lang> " + tr("Set language, for example \"de_DE\" (default: system locale)") + "\n" + " -min " + tr("Start minimized") + "\n" + " -splash " + tr("Show splash screen on startup (default: 1)") + "\n"; setWindowTitle(tr("Bitcoin-Qt")); setTextFormat(Qt::PlainText); // setMinimumWidth is ignored for QMessageBox so put in nonbreaking spaces to make it wider. QChar em_space(0x2003); setText(header + QString(em_space).repeated(40)); setDetailedText(coreOptions + "\n" + uiOptions); } #include "bitcoin.moc" void HelpMessageBox::exec() { #if defined(WIN32) // On windows, show a message box, as there is no stderr in windowed applications QMessageBox::exec(); #else // On other operating systems, the expected action is to print the message to the console. QString strUsage = header + "\n" + coreOptions + "\n" + uiOptions; fprintf(stderr, "%s", strUsage.toStdString().c_str()); #endif } #ifdef WIN32 #define strncasecmp strnicmp #endif #ifndef BITCOIN_QT_TEST int main(int argc, char *argv[]) { #if !defined(MAC_OSX) && !defined(WIN32) // TODO: implement qtipcserver.cpp for Mac and Windows // Do this early as we don't want to bother initializing if we are just calling IPC for (int i = 1; i < argc; i++) { if (strlen(argv[i]) > 7 && strncasecmp(argv[i], "bitcoin:", 8) == 0) { const char *strURI = argv[i]; try { boost::interprocess::message_queue mq(boost::interprocess::open_only, BITCOINURI_QUEUE_NAME); if(mq.try_send(strURI, strlen(strURI), 0)) exit(0); else break; } catch (boost::interprocess::interprocess_exception &ex) { break; } } } #endif // Internal string conversion is all UTF-8 QTextCodec::setCodecForTr(QTextCodec::codecForName("UTF-8")); QTextCodec::setCodecForCStrings(QTextCodec::codecForTr()); Q_INIT_RESOURCE(bitcoin); QApplication app(argc, argv); // Install global event filter that makes sure that long tooltips can be word-wrapped app.installEventFilter(new GUIUtil::ToolTipToRichTextFilter(TOOLTIP_WRAP_THRESHOLD, &app)); // Command-line options take precedence: ParseParameters(argc, argv); // ... then bitcoin.conf: if (!boost::filesystem::is_directory(GetDataDir(false))) { fprintf(stderr, "Error: Specified directory does not exist\n"); return 1; } ReadConfigFile(mapArgs, mapMultiArgs); // Application identification (must be set before OptionsModel is initialized, // as it is used to locate QSettings) app.setOrganizationName("Bitcoin"); app.setOrganizationDomain("bitcoin.org"); if(GetBoolArg("-testnet")) // Separate UI settings for testnet app.setApplicationName("Bitcoin-Qt-testnet"); else app.setApplicationName("Bitcoin-Qt"); // ... then GUI settings: OptionsModel optionsModel; // Get desired locale (e.g. "de_DE") from command line or use system locale QString lang_territory = QString::fromStdString(GetArg("-lang", QLocale::system().name().toStdString())); QString lang = lang_territory; // Convert to "de" only by truncating "_DE" lang.truncate(lang_territory.lastIndexOf('_')); QTranslator qtTranslatorBase, qtTranslator, translatorBase, translator; // Load language files for configured locale: // - First load the translator for the base language, without territory // - Then load the more specific locale translator // Load e.g. qt_de.qm if (qtTranslatorBase.load("qt_" + lang, QLibraryInfo::location(QLibraryInfo::TranslationsPath))) app.installTranslator(&qtTranslatorBase); // Load e.g. qt_de_DE.qm if (qtTranslator.load("qt_" + lang_territory, QLibraryInfo::location(QLibraryInfo::TranslationsPath))) app.installTranslator(&qtTranslator); // Load e.g. bitcoin_de.qm (shortcut "de" needs to be defined in bitcoin.qrc) if (translatorBase.load(lang, ":/translations/")) app.installTranslator(&translatorBase); // Load e.g. bitcoin_de_DE.qm (shortcut "de_DE" needs to be defined in bitcoin.qrc) if (translator.load(lang_territory, ":/translations/")) app.installTranslator(&translator); // Show help message immediately after parsing command-line options (for "-lang") and setting locale, // but before showing splash screen. if (mapArgs.count("-?") || mapArgs.count("--help")) { HelpMessageBox help; help.exec(); return 1; } QSplashScreen splash(QPixmap(":/images/splash"), 0); if (GetBoolArg("-splash", true) && !GetBoolArg("-min")) { splash.show(); splash.setAutoFillBackground(true); splashref = &splash; } app.processEvents(); app.setQuitOnLastWindowClosed(false); try { // Regenerate startup link, to fix links to old versions if (GUIUtil::GetStartOnSystemStartup()) GUIUtil::SetStartOnSystemStartup(true); BitcoinGUI window; guiref = &window; if(AppInit2()) { { // Put this in a block, so that the Model objects are cleaned up before // calling Shutdown(). optionsModel.Upgrade(); // Must be done after AppInit2 if (splashref) splash.finish(&window); ClientModel clientModel(&optionsModel); clientmodel = &clientModel; WalletModel walletModel(pwalletMain, &optionsModel); walletmodel = &walletModel; window.setClientModel(&clientModel); window.setWalletModel(&walletModel); // If -min option passed, start window minimized. if(GetBoolArg("-min")) { window.showMinimized(); } else { window.show(); } // Place this here as guiref has to be defined if we dont want to lose URIs ipcInit(); #if !defined(MAC_OSX) && !defined(WIN32) // TODO: implement qtipcserver.cpp for Mac and Windows // Check for URI in argv for (int i = 1; i < argc; i++) { if (strlen(argv[i]) > 7 && strncasecmp(argv[i], "bitcoin:", 8) == 0) { const char *strURI = argv[i]; try { boost::interprocess::message_queue mq(boost::interprocess::open_only, BITCOINURI_QUEUE_NAME); mq.try_send(strURI, strlen(strURI), 0); } catch (boost::interprocess::interprocess_exception &ex) { } } } #endif app.exec(); window.hide(); window.setClientModel(0); window.setWalletModel(0); guiref = 0; clientmodel = 0; walletmodel = 0; } Shutdown(NULL); } else { return 1; } } catch (std::exception& e) { handleRunawayException(&e); } catch (...) { handleRunawayException(NULL); } return 0; } #endif // BITCOIN_QT_TEST
Add missing Q_OBJECT in bitcoin.cpp
Add missing Q_OBJECT in bitcoin.cpp Fixes translating HelpMessageBox strings.
C++
mit
united-scrypt-coin-project/unitedscryptcoin,xawksow/GroestlCoin,coinkeeper/terracoin_20150327,afk11/bitcoin,ptschip/bitcoin,bittylicious/bitcoin,jimblasko/2015_UNB_Wallets,howardrya/AcademicCoin,benzmuircroft/REWIRE.io,mooncoin-project/mooncoin-landann,shaolinfry/litecoin,gcc64/bitcoin,coinerd/krugercoin,Adaryian/E-Currency,funbucks/notbitcoinxt,ashleyholman/bitcoin,TheBlueMatt/bitcoin,barcoin-project/nothingcoin,constantine001/bitcoin,HeliumGas/helium,NunoEdgarGub1/elements,djpnewton/bitcoin,habibmasuro/bitcoinxt,torresalyssa/bitcoin,spiritlinxl/BTCGPU,jonghyeopkim/bitcoinxt,Dajackal/Ronpaulcoin,miguelfreitas/twister-core,Bloom-Project/Bloom,OstlerDev/florincoin,MonetaryUnit/MUE-Src,brandonrobertz/namecoin-core,ashleyholman/bitcoin,nmarley/dash,droark/bitcoin,oklink-dev/litecoin_block,Electronic-Gulden-Foundation/egulden,cryptoprojects/ultimateonlinecash,iQcoin/iQcoin,BitcoinUnlimited/BitcoinUnlimited,rat4/bitcoin,nathan-at-least/zcash,dgarage/bc2,millennial83/bitcoin,spiritlinxl/BTCGPU,ravenbyron/phtevencoin,kallewoof/elements,jonghyeopkim/bitcoinxt,simdeveloper/bitcoin,litecoin-project/litecore-litecoin,okinc/litecoin,OstlerDev/florincoin,alecalve/bitcoin,botland/bitcoin,borgcoin/Borgcoin.rar,robvanbentem/bitcoin,deeponion/deeponion,welshjf/bitcoin,appop/bitcoin,zetacoin/zetacoin,jnewbery/bitcoin,goldmidas/goldmidas,bitcoinsSG/zcash,DSPay/DSPay,ripper234/bitcoin,GIJensen/bitcoin,SoreGums/bitcoinxt,RibbitFROG/ribbitcoin,neuroidss/bitcoin,MitchellMintCoins/AutoCoin,osuyuushi/laughingmancoin,Electronic-Gulden-Foundation/egulden,appop/bitcoin,myriadteam/myriadcoin,cryptcoins/cryptcoin,pastday/bitcoinproject,likecoin-dev/bitcoin,SartoNess/BitcoinUnlimited,psionin/smartcoin,UFOCoins/ufo,compasscoin/compasscoin,Rav3nPL/PLNcoin,kaostao/bitcoin,MitchellMintCoins/AutoCoin,ClusterCoin/ClusterCoin,aniemerg/zcash,parvez3019/bitcoin,MazaCoin/maza,pelorusjack/BlockDX,pinheadmz/bitcoin,isghe/bitcoinxt,capitalDIGI/DIGI-v-0-10-4,Exceltior/dogecoin,TheOncomingStorm/logincoinadvanced,DogTagRecon/Still-Leraning,namecoin/namecoin-core,ivansib/sib16,BTCfork/hardfork_prototype_1_mvf-core,world-bank/unpay-core,nightlydash/darkcoin,gmaxwell/bitcoin,coinwarp/dogecoin,coinkeeper/anoncoin_20150330_fixes,Mirobit/bitcoin,sebrandon1/bitcoin,bitcoin-hivemind/hivemind,peerdb/cors,Petr-Economissa/gvidon,mikehearn/bitcoin,aspirecoin/aspire,TheOncomingStorm/logincoinadvanced,Open-Source-Coins/EZ,IlfirinIlfirin/shavercoin,nightlydash/darkcoin,kigooz/smalltestnew,zixan/bitcoin,inkvisit/sarmacoins,2XL/bitcoin,koltcoin/koltcoin,bitpay/bitcoin,CTRoundTable/Encrypted.Cash,isocolsky/bitcoinxt,worldbit/worldbit,renatolage/wallets-BRCoin,Anoncoin/anoncoin,oklink-dev/bitcoin,benma/bitcoin,marcusdiaz/BitcoinUnlimited,collapsedev/cashwatt,KaSt/equikoin,isghe/bitcoinxt,ANCompany/birdcoin-dev,keisercoin-official/keisercoin,jmgilbert2/energi,neutrinofoundation/neutrino-digital-currency,borgcoin/Borgcoin.rar,litecoin-project/litecoin,fullcoins/fullcoin,franko-org/franko,joroob/reddcoin,gazbert/bitcoin,benosa/bitcoin,GroestlCoin/GroestlCoin,capitalDIGI/litecoin,djpnewton/bitcoin,isle2983/bitcoin,droark/elements,DigiByte-Team/digibyte,coinkeeper/2015-06-22_19-19_worldcoin,maaku/bitcoin,Rav3nPL/doubloons-08,mammix2/ccoin-dev,ahmedbodi/test2,micryon/GPUcoin,llamasoft/ProtoShares_Cycle,terracoin/terracoin,aspirecoin/aspire,fsb4000/bitcoin,greencoin-dev/greencoin-dev,KibiCoin/kibicoin,ahmedbodi/Bytecoin-MM,jlcurby/NobleCoin,bitcoin/bitcoin,neuroidss/bitcoin,AdrianaDinca/bitcoin,psionin/smartcoin,CodeShark/bitcoin,habibmasuro/bitcoinxt,marklai9999/Taiwancoin,XX-net/twister-core,litecoin-project/litecoin,jimmykiselak/lbrycrd,braydonf/bitcoin,inutoshi/inutoshi,Bloom-Project/Bloom,projectinterzone/ITZ,ludbb/bitcoin,aspirecoin/aspire,killerstorm/bitcoin,marcusdiaz/BitcoinUnlimited,saydulk/Feathercoin,gazbert/bitcoin,arnuschky/bitcoin,skaht/bitcoin,gapcoin/gapcoin,schildbach/bitcoin,StarbuckBG/BTCGPU,rnicoll/bitcoin,peacedevelop/peacecoin,TGDiamond/Diamond,bitjson/hivemind,CTRoundTable/Encrypted.Cash,privatecoin/privatecoin,sipa/elements,paveljanik/bitcoin,and2099/twister-core,lakepay/lake,zixan/bitcoin,mastercoin-MSC/mastercore,RHavar/bitcoin,llluiop/bitcoin,40thoughts/Coin-QualCoin,MonetaryUnit/MUE-Src,haraldh/bitcoin,nathan-at-least/zcash,karek314/bitcoin,vbernabe/freicoin,isocolsky/bitcoinxt,gzuser01/zetacoin-bitcoin,kfitzgerald/titcoin,pastday/bitcoinproject,laudaa/bitcoin,axelxod/braincoin,domob1812/huntercore,united-scrypt-coin-project/unitedscryptcoin,wcwu/bitcoin,n1bor/bitcoin,ronpaulcoin/ronpaulcoin,rdqw/sscoin,marlengit/hardfork_prototype_1_mvf-bu,mortalvikinglive/bitcoinclassic,funbucks/notbitcoinxt,inkvisit/sarmacoins,ghostlander/Feathercoin,scamcoinz/scamcoin,themusicgod1/bitcoin,NicolasDorier/bitcoin,ANCompany/birdcoin-dev,borgcoin/Borgcoin1,haisee/dogecoin,bcpki/nonce2testblocks,dmrtsvetkov/flowercoin,jameshilliard/bitcoin,DMDcoin/Diamond,schinzelh/dash,Rav3nPL/doubloons-0.10,jimblasko/UnbreakableCoin-master,ftrader-bitcoinabc/bitcoin-abc,Anfauglith/iop-hd,szlaozhu/twister-core,odemolliens/bitcoinxt,40thoughts/Coin-QualCoin,vertcoin/eyeglass,dgenr8/bitcoin,zebrains/Blotter,kleetus/bitcoin,zcoinofficial/zcoin,bitpay/bitcoin,goldcoin/goldcoin,kevcooper/bitcoin,sstone/bitcoin,domob1812/namecore,ediston/energi,janko33bd/bitcoin,chrisfranko/aiden,mapineda/litecoin,vlajos/bitcoin,starwels/starwels,coinkeeper/anoncoin_20150330_fixes,dannyperez/bolivarcoin,applecoin-official/fellatio,cryptohelper/premine,neutrinofoundation/neutrino-digital-currency,FeatherCoin/Feathercoin,Chancoin-core/CHANCOIN,brightcoin/brightcoin,rustyrussell/bitcoin,szlaozhu/twister-core,Anfauglith/iop-hd,ajweiss/bitcoin,richo/dongcoin,shelvenzhou/BTCGPU,shadowoneau/ozcoin,itmanagerro/tresting,manuel-zulian/CoMoNet,joshrabinowitz/bitcoin,MazaCoin/mazacoin-new,pevernon/picoin,irvingruan/bitcoin,xieta/mincoin,putinclassic/putic,lakepay/lake,kallewoof/bitcoin,ericshawlinux/bitcoin,rawodb/bitcoin,coinkeeper/2015-06-22_18-39_feathercoin,goldcoin/goldcoin,particl/particl-core,deadalnix/bitcoin,nikkitan/bitcoin,daliwangi/bitcoin,reorder/viacoin,butterflypay/bitcoin,jl2012/litecoin,tuaris/bitcoin,biblepay/biblepay,franko-org/franko,llluiop/bitcoin,phelix/bitcoin,accraze/bitcoin,Dajackal/Ronpaulcoin,pelorusjack/BlockDX,XertroV/bitcoin-nulldata,achow101/bitcoin,oklink-dev/bitcoin_block,se3000/bitcoin,bitcoinclassic/bitcoinclassic,NicolasDorier/bitcoin,scippio/bitcoin,OmniLayer/omnicore,brishtiteveja/sherlockholmescoin,xeddmc/twister-core,stevemyers/bitcoinxt,novaexchange/EAC,Kogser/bitcoin,blood2/bloodcoin-0.9,TierNolan/bitcoin,peerdb/cors,mooncoin-project/mooncoin-landann,Bitcoinsulting/bitcoinxt,TeamBitBean/bitcoin-core,kazcw/bitcoin,funbucks/notbitcoinxt,jtimon/bitcoin,manuel-zulian/accumunet,Cocosoft/bitcoin,alecalve/bitcoin,jimmykiselak/lbrycrd,bitcoinsSG/zcash,czr5014iph/bitcoin4e,nbenoit/bitcoin,Diapolo/bitcoin,unsystemizer/bitcoin,worldbit/worldbit,Open-Source-Coins/EZ,forrestv/bitcoin,pevernon/picoin,crowning-/dash,jonasschnelli/bitcoin,funkshelper/woodcoin-b,CryptArc/bitcoinxt,daliwangi/bitcoin,dogecoin/dogecoin,joshrabinowitz/bitcoin,prark/bitcoinxt,joroob/reddcoin,genavarov/brcoin,xieta/mincoin,thelazier/dash,fussl/elements,faircoin/faircoin2,Twyford/Indigo,HerkCoin/herkcoin,dscotese/bitcoin,knolza/gamblr,ppcoin/ppcoin,millennial83/bitcoin,Michagogo/bitcoin,UdjinM6/dash,spiritlinxl/BTCGPU,ArgonToken/ArgonToken,projectinterzone/ITZ,elliotolds/bitcoin,icook/vertcoin,puticcoin/putic,and2099/twister-core,superjudge/bitcoin,Lucky7Studio/bitcoin,Bushstar/UFO-Project,bootycoin-project/bootycoin,cddjr/BitcoinUnlimited,error10/bitcoin,SartoNess/BitcoinUnlimited,sebrandon1/bitcoin,ahmedbodi/temp_vert,bcpki/nonce2,bitreserve/bitcoin,grumpydevelop/singularity,cdecker/bitcoin,viacoin/viacoin,xeddmc/twister-core,gameunits/gameunits,Cocosoft/bitcoin,tobeyrowe/smallchange,ivansib/sibcoin,zemrys/vertcoin,HeliumGas/helium,droark/elements,MeshCollider/bitcoin,droark/bitcoin,osuyuushi/laughingmancoin,FarhanHaque/bitcoin,PIVX-Project/PIVX,SoreGums/bitcoinxt,GlobalBoost/GlobalBoost,acid1789/bitcoin,WorldcoinGlobal/WorldcoinLegacy,forrestv/bitcoin,prark/bitcoinxt,tjps/bitcoin,glv2/peerunity,elecoin/elecoin,ahmedbodi/terracoin,sifcoin/sifcoin,174high/bitcoin,dashpay/dash,Kogser/bitcoin,tecnovert/particl-core,patricklodder/dogecoin,tensaix2j/bananacoin,lateminer/bitcoin,faircoin/faircoin,fujicoin/fujicoin,Mirobit/bitcoin,andres-root/bitcoinxt,ahmedbodi/terracoin,capitalDIGI/DIGI-v-0-10-4,glv2/peerunity,error10/bitcoin,loxal/zcash,zottejos/merelcoin,balajinandhu/bitcoin,faircoin/faircoin2,dexX7/mastercore,funkshelper/woodcoin-b,ClusterCoin/ClusterCoin,pelorusjack/BlockDX,blocktrail/bitcoin,koharjidan/litecoin,globaltoken/globaltoken,NateBrune/bitcoin-nate,dogecoin/dogecoin,jnewbery/bitcoin,kaostao/bitcoin,gjhiggins/fuguecoin,inutoshi/inutoshi,nmarley/dash,bitcoinsSG/bitcoin,tropa/axecoin,joshrabinowitz/bitcoin,Horrorcoin/horrorcoin,earthcoinproject/earthcoin,diggcoin/diggcoin,zcoinofficial/zcoin,koltcoin/koltcoin,superjudge/bitcoin,Tetcoin/tetcoin,likecoin-dev/bitcoin,zander/bitcoinclassic,Alonzo-Coeus/bitcoin,shurcoin/shurcoin,Flowdalic/bitcoin,willwray/dash,keesdewit82/LasVegasCoin,inkvisit/sarmacoins,appop/bitcoin,MitchellMintCoins/AutoCoin,world-bank/unpay-core,Kore-Core/kore,bitcoinsSG/zcash,itmanagerro/tresting,hasanatkazmi/bitcoin,Kore-Core/kore,haobtc/bitcoin,neuroidss/bitcoin,ohac/sha1coin,zixan/bitcoin,coinkeeper/2015-06-22_18-31_bitcoin,randy-waterhouse/bitcoin,qtumproject/qtum,capitalDIGI/litecoin,jakeva/bitcoin-pwcheck,FarhanHaque/bitcoin,cqtenq/feathercoin_core,mincoin-project/mincoin,braydonf/bitcoin,Ziftr/litecoin,robvanbentem/bitcoin,gravio-net/graviocoin,greencoin-dev/greencoin-dev,Metronotes/bitcoin,celebritycoin/CelebrityCoin,loxal/zcash,sugruedes/bitcoinxt,tropa/axecoin,djpnewton/bitcoin,ericshawlinux/bitcoin,GreenParhelia/bitcoin,NateBrune/bitcoin-nate,memorycoin/memorycoin,jlay11/sharecoin,therealaltcoin/altcoin,KaSt/ekwicoin,putinclassic/putic,Charlesugwu/Vintagecoin,mitchellcash/bitcoin,fullcoins/fullcoin,digibyte/digibyte,wangliu/bitcoin,cinnamoncoin/groupcoin-1,AdrianaDinca/bitcoin,rat4/bitcoin,joshrabinowitz/bitcoin,JeremyRand/namecoin-core,faircoin/faircoin2,habibmasuro/bitcoin,alejandromgk/Lunar,parvez3019/bitcoin,syscoin/syscoin,Cloudsy/bitcoin,tecnovert/particl-core,marlengit/BitcoinUnlimited,FrictionlessCoin/iXcoin,11755033isaprimenumber/Feathercoin,viacoin/viacoin,scmorse/bitcoin,core-bitcoin/bitcoin,SoreGums/bitcoinxt,unsystemizer/bitcoin,Thracky/monkeycoin,tdudz/elements,bcpki/bitcoin,vlajos/bitcoin,webdesignll/coin,BTCfork/hardfork_prototype_1_mvf-core,crowning-/dash,bitbrazilcoin-project/bitbrazilcoin,genavarov/ladacoin,jimblasko/UnbreakableCoin-master,jlay11/sharecoin,fedoracoin-dev/fedoracoin,chaincoin/chaincoin,worldbit/worldbit,misdess/bitcoin,laudaa/bitcoin,SocialCryptoCoin/SocialCoin,martindale/elements,and2099/twister-core,szlaozhu/twister-core,rsdevgun16e/energi,glv2/peerunity,Kenwhite23/litecoin,lbryio/lbrycrd,TBoehm/greedynode,marklai9999/Taiwancoin,phelix/namecore,GwangJin/gwangmoney-core,thelazier/dash,bitreserve/bitcoin,inkvisit/sarmacoins,TheOncomingStorm/logincoinadvanced,cotner/bitcoin,bitcoinec/bitcoinec,gandrewstone/BitcoinUnlimited,pstratem/bitcoin,Kcoin-project/kcoin,shea256/bitcoin,5mil/Tradecoin,zander/bitcoinclassic,sugruedes/bitcoin,butterflypay/bitcoin,presstab/PIVX,rustyrussell/bitcoin,bitcoinxt/bitcoinxt,vmp32k/litecoin,jaromil/faircoin2,psionin/smartcoin,meighti/bitcoin,jn2840/bitcoin,mycointest/owncoin,DSPay/DSPay,namecoin/namecoin-core,ptschip/bitcoinxt,shelvenzhou/BTCGPU,Cocosoft/bitcoin,guncoin/guncoin,tuaris/bitcoin,goku1997/bitcoin,gjhiggins/vcoin09,fussl/elements,petertodd/bitcoin,langerhans/dogecoin,174high/bitcoin,bitpay/bitcoin,spiritlinxl/BTCGPU,kazcw/bitcoin,dperel/bitcoin,andres-root/bitcoinxt,prusnak/bitcoin,Exceltior/dogecoin,koltcoin/koltcoin,GroestlCoin/bitcoin,40thoughts/Coin-QualCoin,jonghyeopkim/bitcoinxt,cyrixhero/bitcoin,maaku/bitcoin,FeatherCoin/Feathercoin,itmanagerro/tresting,OmniLayer/omnicore,Lucky7Studio/bitcoin,memorycoin/memorycoin,my-first/octocoin,paveljanik/bitcoin,IlfirinCano/shavercoin,emc2foundation/einsteinium,cinnamoncoin/groupcoin-1,ionux/freicoin,jlopp/statoshi,svcop3/svcop3,thesoftwarejedi/bitcoin,TripleSpeeder/bitcoin,anditto/bitcoin,totallylegitbiz/totallylegitcoin,Har01d/bitcoin,Cancercoin/Cancercoin,gwangjin2/gwangcoin-core,namecoin/namecore,NateBrune/bitcoin-fio,mm-s/bitcoin,r8921039/bitcoin,hophacker/bitcoin_malleability,micryon/GPUcoin,webdesignll/coin,40thoughts/Coin-QualCoin,JeremyRand/namecore,jaromil/faircoin2,vertcoin/vertcoin,UASF/bitcoin,ticclassic/ic,terracoin/terracoin,thesoftwarejedi/bitcoin,KnCMiner/bitcoin,mobicoins/mobicoin-core,jonasschnelli/bitcoin,bmp02050/ReddcoinUpdates,ZiftrCOIN/ziftrcoin,MeshCollider/bitcoin,Rav3nPL/doubloons-08,goldmidas/goldmidas,shouhuas/bitcoin,HerkCoin/herkcoin,hg5fm/nexuscoin,stamhe/bitcoin,ptschip/bitcoin,peerdb/cors,simdeveloper/bitcoin,bootycoin-project/bootycoin,namecoin/namecore,ryanofsky/bitcoin,Kore-Core/kore,nbenoit/bitcoin,CodeShark/bitcoin,iosdevzone/bitcoin,Cloudsy/bitcoin,MikeAmy/bitcoin,Erkan-Yilmaz/twister-core,elecoin/elecoin,ddombrowsky/radioshares,PRabahy/bitcoin,jrmithdobbs/bitcoin,chaincoin/chaincoin,ahmedbodi/test2,vericoin/vericoin-core,octocoin-project/octocoin,segwit/atbcoin-insight,gavinandresen/bitcoin-git,Erkan-Yilmaz/twister-core,peercoin/peercoin,jimblasko/2015_UNB_Wallets,josephbisch/namecoin-core,brishtiteveja/truthcoin-cpp,szlaozhu/twister-core,segsignal/bitcoin,bitbrazilcoin-project/bitbrazilcoin,dgenr8/bitcoin,kleetus/bitcoinxt,Rav3nPL/polcoin,s-matthew-english/bitcoin,truthcoin/truthcoin-cpp,wangxinxi/litecoin,thormuller/yescoin2,lakepay/lake,deeponion/deeponion,Rav3nPL/polcoin,myriadcoin/myriadcoin,hasanatkazmi/bitcoin,bitgoldcoin-project/bitgoldcoin,ardsu/bitcoin,omefire/bitcoin,gzuser01/zetacoin-bitcoin,hasanatkazmi/bitcoin,marlengit/hardfork_prototype_1_mvf-bu,gandrewstone/BitcoinUnlimited,plncoin/PLNcoin_Core,faircoin/faircoin,cerebrus29301/crowncoin,RibbitFROG/ribbitcoin,kallewoof/bitcoin,Alex-van-der-Peet/bitcoin,madman5844/poundkoin,peacedevelop/peacecoin,privatecoin/privatecoin,world-bank/unpay-core,BitcoinUnlimited/BitcoinUnlimited,applecoin-official/fellatio,BTCfork/hardfork_prototype_1_mvf-bu,btcdrak/bitcoin,OfficialTitcoin/titcoin-wallet,peacedevelop/peacecoin,rromanchuk/bitcoinxt,BTCGPU/BTCGPU,cryptohelper/premine,ardsu/bitcoin,vbernabe/freicoin,likecoin-dev/bitcoin,BTCfork/hardfork_prototype_1_mvf-bu,argentumproject/argentum,bitjson/hivemind,Michagogo/bitcoin,bdelzell/creditcoin-org-creditcoin,bootycoin-project/bootycoin,m0gliE/fastcoin-cli,djpnewton/bitcoin,Climbee/artcoin,Mirobit/bitcoin,jtimon/bitcoin,razor-coin/razor,yenliangl/bitcoin,greenaddress/bitcoin,Czarcoin/czarcoin,gapcoin/gapcoin,pdrobek/Polcoin-1-3,manuel-zulian/CoMoNet,rnicoll/bitcoin,plankton12345/litecoin,Petr-Economissa/gvidon,digibyte/digibyte,antcheck/antcoin,schildbach/bitcoin,jrick/bitcoin,ColossusCoinXT/ColossusCoinXT,wangxinxi/litecoin,Dinarcoin/dinarcoin,Cancercoin/Cancercoin,magacoin/magacoin,Coinfigli/coinfigli,Mrs-X/PIVX,bespike/litecoin,glv2/peerunity,patricklodder/dogecoin,Kenwhite23/litecoin,OstlerDev/florincoin,Exgibichi/statusquo,tedlz123/Bitcoin,trippysalmon/bitcoin,bfroemel/smallchange,nightlydash/darkcoin,pelorusjack/BlockDX,svcop3/svcop3,zotherstupidguy/bitcoin,dan-mi-sun/bitcoin,nanocoins/mycoin,tobeyrowe/KitoniaCoin,tdudz/elements,Checkcoin/checkcoin,argentumproject/argentum,CoinProjects/AmsterdamCoin-v4,jgarzik/bitcoin,benosa/bitcoin,rromanchuk/bitcoinxt,ingresscoin/ingresscoin,mobicoins/mobicoin-core,truthcoin/truthcoin-cpp,xeddmc/twister-core,pstratem/elements,jamesob/bitcoin,goku1997/bitcoin,ionomy/ion,domob1812/bitcoin,dashpay/dash,NunoEdgarGub1/elements,coinkeeper/2015-06-22_18-46_razor,funkshelper/woodcore,XertroV/bitcoin-nulldata,se3000/bitcoin,vertcoin/eyeglass,yenliangl/bitcoin,AdrianaDinca/bitcoin,MitchellMintCoins/MortgageCoin,domob1812/i0coin,Kabei/Ippan,ingresscoin/ingresscoin,united-scrypt-coin-project/unitedscryptcoin,40thoughts/Coin-QualCoin,KnCMiner/bitcoin,CarpeDiemCoin/CarpeDiemLaunch,Alonzo-Coeus/bitcoin,fanquake/bitcoin,ahmedbodi/vertcoin,untrustbank/litecoin,Christewart/bitcoin,metacoin/florincoin,Bloom-Project/Bloom,stamhe/litecoin,namecoin/namecoin-core,awemany/BitcoinUnlimited,cerebrus29301/crowncoin,domob1812/i0coin,gjhiggins/vcoin0.8zeta-dev,atgreen/bitcoin,Richcoin-Project/RichCoin,bcpki/nonce2testblocks,namecoin/namecoin-core,OfficialTitcoin/titcoin-wallet,okinc/litecoin,tripmode/pxlcoin,raasakh/bardcoin,HashUnlimited/Einsteinium-Unlimited,stamhe/bitcoin,apoelstra/elements,welshjf/bitcoin,Petr-Economissa/gvidon,haraldh/bitcoin,kallewoof/bitcoin,isle2983/bitcoin,manuel-zulian/accumunet,starwalkerz/fincoin-fork,gazbert/bitcoin,degenorate/Deftcoin,syscoin/syscoin,Earlz/dobbscoin-source,genavarov/ladacoin,likecoin-dev/bitcoin,pinkevich/dash,isghe/bitcoinxt,gameunits/gameunits,PRabahy/bitcoin,haraldh/bitcoin,jiangyonghang/bitcoin,zebrains/Blotter,sugruedes/bitcoin,jnewbery/bitcoin,habibmasuro/bitcoinxt,viacoin/viacoin,netswift/vertcoin,nathan-at-least/zcash,Horrorcoin/horrorcoin,creath/barcoin,MikeAmy/bitcoin,Theshadow4all/ShadowCoin,MasterX1582/bitcoin-becoin,coinkeeper/megacoin_20150410_fixes,simdeveloper/bitcoin,isghe/bitcoinxt,dakk/soundcoin,balajinandhu/bitcoin,oklink-dev/litecoin_block,kevin-cantwell/crunchcoin,Charlesugwu/Vintagecoin,Mrs-X/PIVX,dgenr8/bitcoin,vertcoin/vertcoin,IlfirinIlfirin/shavercoin,Kixunil/keynescoin,kallewoof/bitcoin,ericshawlinux/bitcoin,RongxinZhang/bitcoinxt,brandonrobertz/namecoin-core,jarymoth/dogecoin,reddink/reddcoin,CodeShark/bitcoin,bmp02050/ReddcoinUpdates,jrick/bitcoin,jrmithdobbs/bitcoin,celebritycoin/investorcoin,drwasho/bitcoinxt,ANCompany/birdcoin-dev,XX-net/twister-core,zottejos/merelcoin,coinkeeper/2015-06-22_18-31_bitcoin,keo/bitcoin,ludbb/bitcoin,mrbandrews/bitcoin,benzmuircroft/REWIRE.io,21E14/bitcoin,1185/starwels,dannyperez/bolivarcoin,DogTagRecon/Still-Leraning,ionux/freicoin,Richcoin-Project/RichCoin,sipa/bitcoin,erqan/twister-core,Kcoin-project/kcoin,madman5844/poundkoin,okinc/litecoin,matlongsi/micropay,ronpaulcoin/ronpaulcoin,funkshelper/woodcore,welshjf/bitcoin,stevemyers/bitcoinxt,brishtiteveja/truthcoin-cpp,mruddy/bitcoin,Climbee/artcoin,sugruedes/bitcoinxt,scmorse/bitcoin,ohac/sha1coin,capitalDIGI/litecoin,ivansib/sib16,Bitcoin-com/BUcash,Credit-Currency/CoinTestComp,prark/bitcoinxt,karek314/bitcoin,collapsedev/circlecash,vtafaucet/virtacoin,DGCDev/digitalcoin,MitchellMintCoins/MortgageCoin,crowning-/dash,Christewart/bitcoin,ClusterCoin/ClusterCoin,coinkeeper/2015-06-22_18-56_megacoin,denverl/bitcoin,Rav3nPL/doubloons-0.10,PIVX-Project/PIVX,denverl/bitcoin,aspirecoin/aspire,ghostlander/Feathercoin,btc1/bitcoin,p2peace/oliver-twister-core,inkvisit/sarmacoins,TBoehm/greedynode,48thct2jtnf/P,cinnamoncoin/groupcoin-1,slingcoin/sling-market,Jeff88Ho/bitcoin,KibiCoin/kibicoin,CoinProjects/AmsterdamCoin-v4,bdelzell/creditcoin-org-creditcoin,genavarov/lamacoin,jl2012/litecoin,dakk/soundcoin,reddink/reddcoin,dev1972/Satellitecoin,shadowoneau/ozcoin,nmarley/dash,3lambert/Molecular,ravenbyron/phtevencoin,vtafaucet/virtacoin,MikeAmy/bitcoin,bfroemel/smallchange,Christewart/bitcoin,dgenr8/bitcoinxt,grumpydevelop/singularity,goldcoin/Goldcoin-GLD,RHavar/bitcoin,CrimeaCoin/crimeacoin,particl/particl-core,brishtiteveja/sherlockcoin,SandyCohen/mincoin,GroestlCoin/GroestlCoin,jmgilbert2/energi,segsignal/bitcoin,PandaPayProject/PandaPay,cryptcoins/cryptcoin,Rav3nPL/polcoin,celebritycoin/CelebrityCoin,adpg211/bitcoin-master,LIMXTEC/DMDv3,segwit/atbcoin-insight,inkvisit/sarmacoins,yenliangl/bitcoin,mruddy/bitcoin,HashUnlimited/Einsteinium-Unlimited,jimblasko/UnbreakableCoin-master,starwels/starwels,ptschip/bitcoin,morcos/bitcoin,dgarage/bc3,jakeva/bitcoin-pwcheck,kazcw/bitcoin,shelvenzhou/BTCGPU,Vsync-project/Vsync,lbryio/lbrycrd,JeremyRand/namecore,CryptArc/bitcoin,Krellan/bitcoin,neuroidss/bitcoin,coinkeeper/2015-06-22_18-37_dogecoin,iosdevzone/bitcoin,cerebrus29301/crowncoin,Thracky/monkeycoin,BitcoinHardfork/bitcoin,koharjidan/bitcoin,bitcoin-hivemind/hivemind,oklink-dev/bitcoin,theuni/bitcoin,majestrate/twister-core,truthcoin/truthcoin-cpp,bankonmecoin/bitcoin,KaSt/equikoin,habibmasuro/bitcoin,gazbert/bitcoin,syscoin/syscoin2,NicolasDorier/bitcoin,jarymoth/dogecoin,litecoin-project/litecore-litecoin,yenliangl/bitcoin,brightcoin/brightcoin,ghostlander/Testcoin,bitbrazilcoin-project/bitbrazilcoin,BenjaminsCrypto/Benjamins-1,Alonzo-Coeus/bitcoin,multicoins/marycoin,senadmd/coinmarketwatch,jgarzik/bitcoin,ftrader-bitcoinunlimited/hardfork_prototype_1_mvf-bu,oklink-dev/bitcoin_block,achow101/bitcoin,sarielsaz/sarielsaz,gcc64/bitcoin,taenaive/zetacoin,jmcorgan/bitcoin,themusicgod1/bitcoin,krzysztofwos/BitcoinUnlimited,matlongsi/micropay,kigooz/smalltestnew,bitcoinclassic/bitcoinclassic,nvmd/bitcoin,stevemyers/bitcoinxt,brettwittam/geocoin,1185/starwels,kfitzgerald/titcoin,pascalguru/florincoin,PandaPayProject/PandaPay,thesoftwarejedi/bitcoin,HeliumGas/helium,DMDcoin/Diamond,awemany/BitcoinUnlimited,NateBrune/bitcoin-fio,practicalswift/bitcoin,nikkitan/bitcoin,earonesty/bitcoin,dagurval/bitcoinxt,celebritycoin/investorcoin,wbchen99/bitcoin-hnote0,scamcoinz/scamcoin,cddjr/BitcoinUnlimited,afk11/bitcoin,parvez3019/bitcoin,aniemerg/zcash,petertodd/bitcoin,Bitcoinsulting/bitcoinxt,howardrya/AcademicCoin,Charlesugwu/Vintagecoin,elacoin/elacoin,Checkcoin/checkcoin,Cloudsy/bitcoin,appop/bitcoin,dogecoin/dogecoin,bitcoinxt/bitcoinxt,bitcoinsSG/bitcoin,JeremyRand/namecoin-core,shelvenzhou/BTCGPU,nanocoins/mycoin,elecoin/elecoin,romanornr/viacoin,emc2foundation/einsteinium,coinkeeper/2015-06-22_19-19_worldcoin,upgradeadvice/MUE-Src,coinerd/krugercoin,gazbert/bitcoin,dogecoin/dogecoin,whatrye/twister-core,TeamBitBean/bitcoin-core,MeshCollider/bitcoin,jonasnick/bitcoin,bitcoin-hivemind/hivemind,benosa/bitcoin,cryptoprojects/ultimateonlinecash,starwalkerz/fincoin-fork,chrisfranko/aiden,lbryio/lbrycrd,iosdevzone/bitcoin,Darknet-Crypto/Darknet,mycointest/owncoin,maaku/bitcoin,sarielsaz/sarielsaz,novaexchange/EAC,cdecker/bitcoin,pinheadmz/bitcoin,sickpig/BitcoinUnlimited,jamesob/bitcoin,Exceltior/dogecoin,mitchellcash/bitcoin,gwillen/elements,ahmedbodi/test2,coinkeeper/2015-06-22_18-39_feathercoin,gravio-net/graviocoin,forrestv/bitcoin,Kangmo/bitcoin,TheBlueMatt/bitcoin,zzkt/solarcoin,ZiftrCOIN/ziftrcoin,syscoin/syscoin,cheehieu/bitcoin,manuel-zulian/accumunet,cainca/liliucoin,vcoin-project/vcoincore,Credit-Currency/CoinTestComp,CryptArc/bitcoinxt,gjhiggins/fuguecoin,shaulkf/bitcoin,coinkeeper/2015-06-22_18-51_vertcoin,midnightmagic/bitcoin,UFOCoins/ufo,kleetus/bitcoinxt,bitshares/bitshares-pts,jtimon/elements,brishtiteveja/truthcoin-cpp,ClusterCoin/ClusterCoin,OmniLayer/omnicore,megacoin/megacoin,ryanxcharles/bitcoin,ohac/sha1coin,RazorLove/cloaked-octo-spice,kleetus/bitcoin,jnewbery/bitcoin,sebrandon1/bitcoin,stamhe/bitcoin,pastday/bitcoinproject,WorldcoinGlobal/WorldcoinLegacy,vbernabe/freicoin,putinclassic/putic,mrtexaznl/mediterraneancoin,ryanofsky/bitcoin,dan-mi-sun/bitcoin,ElementsProject/elements,accraze/bitcoin,svost/bitcoin,bankonmecoin/bitcoin,ahmedbodi/temp_vert,dmrtsvetkov/flowercoin,jeromewu/bitcoin-opennet,Rav3nPL/PLNcoin,deadalnix/bitcoin,Chancoin-core/CHANCOIN,r8921039/bitcoin,SandyCohen/mincoin,Paymium/bitcoin,mm-s/bitcoin,ionux/freicoin,reddcoin-project/reddcoin,donaloconnor/bitcoin,myriadcoin/myriadcoin,senadmd/coinmarketwatch,irvingruan/bitcoin,netswift/vertcoin,thelazier/dash,zenywallet/bitzeny,octocoin-project/octocoin,BTCTaras/bitcoin,XX-net/twister-core,yenliangl/bitcoin,crowning-/dash,hophacker/bitcoin_malleability,rnicoll/bitcoin,prark/bitcoinxt,whatrye/twister-core,leofidus/glowing-octo-ironman,StarbuckBG/BTCGPU,fsb4000/bitcoin,Mrs-X/Darknet,Flowdalic/bitcoin,48thct2jtnf/P,NicolasDorier/bitcoin,Alex-van-der-Peet/bitcoin,Vsync-project/Vsync,MeshCollider/bitcoin,dmrtsvetkov/flowercoin,imton/bitcoin,CTRoundTable/Encrypted.Cash,mitchellcash/bitcoin,Credit-Currency/CoinTestComp,balajinandhu/bitcoin,ionux/freicoin,vertcoin/vertcoin,cculianu/bitcoin-abc,schinzelh/dash,BitcoinHardfork/bitcoin,mammix2/ccoin-dev,domob1812/namecore,phelix/namecore,wbchen99/bitcoin-hnote0,gandrewstone/BitcoinUnlimited,xieta/mincoin,isocolsky/bitcoinxt,ajtowns/bitcoin,gzuser01/zetacoin-bitcoin,brishtiteveja/sherlockholmescoin,loxal/zcash,Bitcoin-ABC/bitcoin-abc,Darknet-Crypto/Darknet,bitshares/bitshares-pts,TrainMAnB/vcoincore,shaulkf/bitcoin,torresalyssa/bitcoin,kirkalx/bitcoin,oklink-dev/bitcoin_block,petertodd/bitcoin,upgradeadvice/MUE-Src,koharjidan/litecoin,deuscoin/deuscoin,coinerd/krugercoin,EntropyFactory/creativechain-core,genavarov/lamacoin,BlockchainTechLLC/3dcoin,ghostlander/Testcoin,Anoncoin/anoncoin,applecoin-official/fellatio,gjhiggins/vcoin09,nanocoins/mycoin,marlengit/BitcoinUnlimited,qubitcoin-project/QubitCoinQ2C,scmorse/bitcoin,jlay11/sharecoin,bittylicious/bitcoin,digideskio/namecoin,imharrywu/fastcoin,elliotolds/bitcoin,untrustbank/litecoin,sipa/elements,prark/bitcoinxt,XertroV/bitcoin-nulldata,Twyford/Indigo,robvanbentem/bitcoin,ahmedbodi/bytecoin,Mirobit/bitcoin,blood2/bloodcoin-0.9,cinnamoncoin/Feathercoin,okinc/litecoin,sbaks0820/bitcoin,taenaive/zetacoin,GroestlCoin/GroestlCoin,dobbscoin/dobbscoin-source,ArgonToken/ArgonToken,Alex-van-der-Peet/bitcoin,qreatora/worldcoin-v0.8,bitcoin/bitcoin,Adaryian/E-Currency,IlfirinCano/shavercoin,Xekyo/bitcoin,HashUnlimited/Einsteinium-Unlimited,RyanLucchese/energi,cinnamoncoin/Feathercoin,Krellan/bitcoin,zemrys/vertcoin,manuel-zulian/CoMoNet,thrasher-/litecoin,SandyCohen/mincoin,jul2711/jucoin,emc2foundation/einsteinium,ericshawlinux/bitcoin,WorldcoinGlobal/WorldcoinLegacy,sugruedes/bitcoinxt,Vsync-project/Vsync,antonio-fr/bitcoin,REAP720801/bitcoin,brettwittam/geocoin,Krellan/bitcoin,koharjidan/bitcoin,simonmulser/bitcoin,mruddy/bitcoin,zebrains/Blotter,ajweiss/bitcoin,akabmikua/flowcoin,litecoin-project/litecoin,21E14/bitcoin,jaromil/faircoin2,gavinandresen/bitcoin-git,aniemerg/zcash,MikeAmy/bitcoin,Sjors/bitcoin,jameshilliard/bitcoin,projectinterzone/ITZ,nbenoit/bitcoin,Diapolo/bitcoin,ahmedbodi/vertcoin,jonasnick/bitcoin,metrocoins/metrocoin,r8921039/bitcoin,Earlz/dobbscoin-source,marklai9999/Taiwancoin,viacoin/viacoin,Ziftr/bitcoin,DigiByte-Team/digibyte,BlockchainTechLLC/3dcoin,ZiftrCOIN/ziftrcoin,3lambert/Molecular,genavarov/ladacoin,wangxinxi/litecoin,40thoughts/Coin-QualCoin,gameunits/gameunits,AdrianaDinca/bitcoin,bcpki/nonce2,whatrye/twister-core,Bloom-Project/Bloom,Kabei/Ippan,greencoin-dev/digitalcoin,Gazer022/bitcoin,masterbraz/dg,UFOCoins/ufo,s-matthew-english/bitcoin,Earlz/renamedcoin,andreaskern/bitcoin,thormuller/yescoin2,upgradeadvice/MUE-Src,tjth/lotterycoin,ghostlander/Feathercoin,Tetcoin/tetcoin,Coinfigli/coinfigli,sugruedes/bitcoin,genavarov/brcoin,mortalvikinglive/bitcoinclassic,aspirecoin/aspire,lbryio/lbrycrd,jimmykiselak/lbrycrd,lclc/bitcoin,ppcoin/ppcoin,Alonzo-Coeus/bitcoin,bitcoin/bitcoin,Tetpay/bitcoin,coinkeeper/2015-06-22_18-56_megacoin,projectinterzone/ITZ,x-kalux/bitcoin_WiG-B,jiffe/cosinecoin,brishtiteveja/truthcoin-cpp,guncoin/guncoin,Diapolo/bitcoin,nanocoins/mycoin,Metronotes/bitcoin,sickpig/BitcoinUnlimited,gwillen/elements,octocoin-project/octocoin,haraldh/bitcoin,Mrs-X/PIVX,janko33bd/bitcoin,apoelstra/bitcoin,vlajos/bitcoin,WorldLeadCurrency/WLC,bitcoinec/bitcoinec,TBoehm/greedynode,GroundRod/anoncoin,cculianu/bitcoin-abc,argentumproject/argentum,koharjidan/bitcoin,rromanchuk/bitcoinxt,jamesob/bitcoin,NateBrune/bitcoin-fio,lateminer/bitcoin,mockcoin/mockcoin,ivansib/sib16,bcpki/testblocks,phplaboratory/psiacoin,NateBrune/bitcoin-fio,jtimon/bitcoin,RazorLove/cloaked-octo-spice,tdudz/elements,PIVX-Project/PIVX,litecoin-project/litecoin,alejandromgk/Lunar,martindale/elements,world-bank/unpay-core,fullcoins/fullcoin,1185/starwels,experiencecoin/experiencecoin,kbccoin/kbc,PIVX-Project/PIVX,DGCDev/digitalcoin,TrainMAnB/vcoincore,ychaim/smallchange,Bitcoin-ABC/bitcoin-abc,r8921039/bitcoin,odemolliens/bitcoinxt,ychaim/smallchange,ShadowMyst/creativechain-core,fussl/elements,bitcoin-hivemind/hivemind,MasterX1582/bitcoin-becoin,lbrtcoin/albertcoin,totallylegitbiz/totallylegitcoin,bittylicious/bitcoin,prusnak/bitcoin,welshjf/bitcoin,kigooz/smalltestnew,odemolliens/bitcoinxt,pataquets/namecoin-core,multicoins/marycoin,qreatora/worldcoin-v0.8,Litecoindark/LTCD,drwasho/bitcoinxt,Friedbaumer/litecoin,dperel/bitcoin,Thracky/monkeycoin,BTCDDev/bitcoin,dmrtsvetkov/flowercoin,bitcoinknots/bitcoin,cerebrus29301/crowncoin,bitcoinplusorg/xbcwalletsource,mastercoin-MSC/mastercore,gwangjin2/gwangcoin-core,RHavar/bitcoin,freelion93/mtucicoin,Mrs-X/Darknet,BitzenyCoreDevelopers/bitzeny,presstab/PIVX,butterflypay/bitcoin,Petr-Economissa/gvidon,multicoins/marycoin,litecoin-project/bitcoinomg,morcos/bitcoin,namecoin/namecoin-core,manuel-zulian/CoMoNet,isle2983/bitcoin,UASF/bitcoin,my-first/octocoin,anditto/bitcoin,totallylegitbiz/totallylegitcoin,droark/bitcoin,magacoin/magacoin,BTCTaras/bitcoin,funkshelper/woodcore,FarhanHaque/bitcoin,Rav3nPL/doubloons-08,goldmidas/goldmidas,kigooz/smalltest,knolza/gamblr,goldcoin/Goldcoin-GLD,worldbit/worldbit,freelion93/mtucicoin,nbenoit/bitcoin,goldcoin/Goldcoin-GLD,tripmode/pxlcoin,KillerByte/memorypool,1185/starwels,Adaryian/E-Currency,digideskio/namecoin,ElementsProject/elements,lbrtcoin/albertcoin,adpg211/bitcoin-master,FrictionlessCoin/iXcoin,daveperkins-github/bitcoin-dev,syscoin/syscoin,elecoin/elecoin,vertcoin/eyeglass,Chancoin-core/CHANCOIN,Horrorcoin/horrorcoin,Bitcoin-ABC/bitcoin-abc,zsulocal/bitcoin,ftrader-bitcoinunlimited/hardfork_prototype_1_mvf-bu,mikehearn/bitcoin,RyanLucchese/energi,BigBlueCeiling/augmentacoin,antcheck/antcoin,benzmuircroft/REWIRE.io,steakknife/bitcoin-qt,shouhuas/bitcoin,coinkeeper/terracoin_20150327,dan-mi-sun/bitcoin,jiffe/cosinecoin,majestrate/twister-core,vcoin-project/vcoin0.8zeta-dev,BTCGPU/BTCGPU,millennial83/bitcoin,aspanta/bitcoin,sipa/bitcoin,meighti/bitcoin,aburan28/elements,bitpagar/bitpagar,prusnak/bitcoin,domob1812/i0coin,sipa/elements,DGCDev/argentum,mockcoin/mockcoin,mapineda/litecoin,aciddude/Feathercoin,cannabiscoindev/cannabiscoin420,MikeAmy/bitcoin,Kenwhite23/litecoin,raasakh/bardcoin.exe,HerkCoin/herkcoin,PRabahy/bitcoin,joulecoin/joulecoin,EntropyFactory/creativechain-core,romanornr/viacoin,koharjidan/litecoin,denverl/bitcoin,tensaix2j/bananacoin,memorycoin/memorycoin,Gazer022/bitcoin,pdrobek/Polcoin-1-3,isle2983/bitcoin,keisercoin-official/keisercoin,m0gliE/fastcoin-cli,HeliumGas/helium,Mrs-X/Darknet,arnuschky/bitcoin,rawodb/bitcoin,puticcoin/putic,shurcoin/shurcoin,multicoins/marycoin,isocolsky/bitcoinxt,psionin/smartcoin,Czarcoin/czarcoin,cheehieu/bitcoin,magacoin/magacoin,united-scrypt-coin-project/unitedscryptcoin,coinkeeper/2015-06-22_18-39_feathercoin,omefire/bitcoin,brandonrobertz/namecoin-core,SandyCohen/mincoin,rustyrussell/bitcoin,mortalvikinglive/bitcoinlight,ryanxcharles/bitcoin,taenaive/zetacoin,greenaddress/bitcoin,rnicoll/dogecoin,collapsedev/cashwatt,adpg211/bitcoin-master,bickojima/bitzeny,dakk/soundcoin,se3000/bitcoin,BitzenyCoreDevelopers/bitzeny,Sjors/bitcoin,manuel-zulian/accumunet,jmcorgan/bitcoin,funbucks/notbitcoinxt,peacedevelop/peacecoin,Carrsy/PoundCoin,48thct2jtnf/P,florincoin/florincoin,ripper234/bitcoin,funkshelper/woodcoin-b,BTCTaras/bitcoin,lateminer/bitcoin,DigitalPandacoin/pandacoin,goldmidas/goldmidas,ediston/energi,stamhe/bitcoin,ediston/energi,jonghyeopkim/bitcoinxt,BitcoinPOW/BitcoinPOW,bitcoinxt/bitcoinxt,coinkeeper/2015-06-22_18-51_vertcoin,segwit/atbcoin-insight,initaldk/bitcoin,parvez3019/bitcoin,droark/elements,TBoehm/greedynode,kleetus/bitcoinxt,irvingruan/bitcoin,DSPay/DSPay,GreenParhelia/bitcoin,majestrate/twister-core,bcpki/nonce2,gwangjin2/gwangcoin-core,zotherstupidguy/bitcoin,nathan-at-least/zcash,mikehearn/bitcoinxt,sugruedes/bitcoinxt,ShadowMyst/creativechain-core,OfficialTitcoin/titcoin-wallet,skaht/bitcoin,iosdevzone/bitcoin,Kcoin-project/kcoin,scamcoinz/scamcoin,wederw/bitcoin,tjth/lotterycoin,jimmysong/bitcoin,gapcoin/gapcoin,qtumproject/qtum,wangliu/bitcoin,Justaphf/BitcoinUnlimited,terracoin/terracoin,collapsedev/circlecash,OstlerDev/florincoin,shouhuas/bitcoin,biblepay/biblepay,Kogser/bitcoin,cculianu/bitcoin-abc,erikYX/yxcoin-FIRST,CodeShark/bitcoin,knolza/gamblr,btcdrak/bitcoin,DigiByte-Team/digibyte,rebroad/bitcoin,bitcoinplusorg/xbcwalletsource,capitalDIGI/litecoin,atgreen/bitcoin,jul2711/jucoin,slingcoin/sling-market,coinkeeper/2015-06-22_18-36_darkcoin,kevcooper/bitcoin,thelazier/dash,btcdrak/bitcoin,monacoinproject/monacoin,odemolliens/bitcoinxt,Gazer022/bitcoin,jrmithdobbs/bitcoin,basicincome/unpcoin-core,1185/starwels,bitcoinec/bitcoinec,mikehearn/bitcoinxt,Blackcoin/blackcoin,Har01d/bitcoin,franko-org/franko,schildbach/bitcoin,rsdevgun16e/energi,anditto/bitcoin,Vector2000/bitcoin,capitalDIGI/DIGI-v-0-10-4,SandyCohen/mincoin,marcusdiaz/BitcoinUnlimited,neutrinofoundation/neutrino-digital-currency,bickojima/bitzeny,mrtexaznl/mediterraneancoin,dev1972/Satellitecoin,Bitcoin-ABC/bitcoin-abc,kirkalx/bitcoin,DGCDev/digitalcoin,sstone/bitcoin,EthanHeilman/bitcoin,rawodb/bitcoin,TGDiamond/Diamond,zemrys/vertcoin,ahmedbodi/Bytecoin-MM,langerhans/dogecoin,anditto/bitcoin,renatolage/wallets-BRCoin,UASF/bitcoin,rdqw/sscoin,richo/dongcoin,reddink/reddcoin,zottejos/merelcoin,okinc/bitcoin,gjhiggins/fuguecoin,plncoin/PLNcoin_Core,EthanHeilman/bitcoin,TierNolan/bitcoin,bitcoin/bitcoin,imharrywu/fastcoin,Sjors/bitcoin,cainca/liliucoin,cryptoprojects/ultimateonlinecash,domob1812/bitcoin,PRabahy/bitcoin,Theshadow4all/ShadowCoin,mb300sd/bitcoin,lbrtcoin/albertcoin,slingcoin/sling-market,tobeyrowe/KitoniaCoin,zcoinofficial/zcoin,jrick/bitcoin,sipsorcery/bitcoin,denverl/bitcoin,miguelfreitas/twister-core,marscoin/marscoin,FeatherCoin/Feathercoin,CarpeDiemCoin/CarpeDiemLaunch,pinkevich/dash,daliwangi/bitcoin,mycointest/owncoin,Christewart/bitcoin,benzmuircroft/REWIRE.io,chaincoin/chaincoin,bitpay/bitcoin,ripper234/bitcoin,Kabei/Ippan,ixcoinofficialpage/master,elacoin/elacoin,zsulocal/bitcoin,truthcoin/blocksize-market,UASF/bitcoin,BTCGPU/BTCGPU,taenaive/zetacoin,ColossusCoinXT/ColossusCoinXT,koharjidan/dogecoin,Litecoindark/LTCD,dashpay/dash,Har01d/bitcoin,mitchellcash/bitcoin,jamesob/bitcoin,themusicgod1/bitcoin,pstratem/bitcoin,ddombrowsky/radioshares,digideskio/namecoin,cmgustavo/bitcoin,gameunits/gameunits,Blackcoin/blackcoin,Enticed87/Decipher,Anoncoin/anoncoin,dgenr8/bitcoin,and2099/twister-core,alejandromgk/Lunar,kleetus/bitcoinxt,botland/bitcoin,AllanDoensen/BitcoinUnlimited,hsavit1/bitcoin,Rav3nPL/polcoin,borgcoin/Borgcoin1,dcousens/bitcoin,jn2840/bitcoin,saydulk/Feathercoin,apoelstra/bitcoin,BTCTaras/bitcoin,bcpki/bitcoin,Rav3nPL/doubloons-0.10,deuscoin/deuscoin,ronpaulcoin/ronpaulcoin,BlockchainTechLLC/3dcoin,schinzelh/dash,11755033isaprimenumber/Feathercoin,domob1812/i0coin,bitcoinsSG/zcash,GreenParhelia/bitcoin,ahmedbodi/Bytecoin-MM,cannabiscoindev/cannabiscoin420,octocoin-project/octocoin,DigitalPandacoin/pandacoin,dperel/bitcoin,brishtiteveja/sherlockholmescoin,bitgoldcoin-project/bitgoldcoin,JeremyRand/namecoin-core,mooncoin-project/mooncoin-landann,prark/bitcoinxt,BitcoinUnlimited/BitcoinUnlimited,ekankyesme/bitcoinxt,jul2711/jucoin,elliotolds/bitcoin,celebritycoin/CelebrityCoin,jn2840/bitcoin,fullcoins/fullcoin,dev1972/Satellitecoin,peercoin/peercoin,gjhiggins/vcoin0.8zeta-dev,nlgcoin/guldencoin-official,parvez3019/bitcoin,apoelstra/elements,xurantju/bitcoin,koharjidan/dogecoin,coinkeeper/2015-06-22_19-00_ziftrcoin,bootycoin-project/bootycoin,ShwoognationHQ/bitcoin,ahmedbodi/bytecoin,jtimon/elements,lateminer/bitcoin,KibiCoin/kibicoin,JeremyRand/bitcoin,amaivsimau/bitcoin,BTCGPU/BTCGPU,daliwangi/bitcoin,wederw/bitcoin,zander/bitcoinclassic,mrbandrews/bitcoin,lbryio/lbrycrd,mortalvikinglive/bitcoinclassic,tdudz/elements,sickpig/BitcoinUnlimited,cculianu/bitcoin-abc,plncoin/PLNcoin_Core,faircoin/faircoin,h4x3rotab/BTCGPU,donaloconnor/bitcoin,goku1997/bitcoin,coinkeeper/2015-06-22_18-52_viacoin,ptschip/bitcoin,stamhe/litecoin,meighti/bitcoin,ingresscoin/ingresscoin,brandonrobertz/namecoin-core,bitcoinclassic/bitcoinclassic,celebritycoin/CelebrityCoin,jarymoth/dogecoin,leofidus/glowing-octo-ironman,Har01d/bitcoin,destenson/bitcoin--bitcoin,p2peace/oliver-twister-core,nanocoins/mycoin,coinkeeper/2015-06-22_18-52_viacoin,deeponion/deeponion,romanornr/viacoin,PIVX-Project/PIVX,cryptcoins/cryptcoin,Paymium/bitcoin,vcoin-project/vcoincore,CryptArc/bitcoinxt,nvmd/bitcoin,Jeff88Ho/bitcoin,okinc/bitcoin,florincoin/florincoin,reddink/reddcoin,Erkan-Yilmaz/twister-core,ivansib/sib16,enlighter/Feathercoin,Justaphf/BitcoinUnlimited,tuaris/bitcoin,funbucks/notbitcoinxt,qreatora/worldcoin-v0.8,Bluejudy/worldcoin,koharjidan/litecoin,BitcoinHardfork/bitcoin,jimmysong/bitcoin,ShwoognationHQ/bitcoin,therealaltcoin/altcoin,coinkeeper/2015-06-22_18-37_dogecoin,coinkeeper/2015-06-22_18-41_ixcoin,raasakh/bardcoin,ptschip/bitcoinxt,kfitzgerald/titcoin,nvmd/bitcoin,mm-s/bitcoin,earthcoinproject/earthcoin,Megacoin2/Megacoin,dannyperez/bolivarcoin,coinkeeper/megacoin_20150410_fixes,marlengit/hardfork_prototype_1_mvf-bu,marlengit/BitcoinUnlimited,Bushstar/UFO-Project,my-first/octocoin,imton/bitcoin,BitcoinPOW/BitcoinPOW,CryptArc/bitcoinxt,WorldLeadCurrency/WLC,FinalHashLLC/namecore,apoelstra/bitcoin,brishtiteveja/sherlockholmescoin,daveperkins-github/bitcoin-dev,schinzelh/dash,MitchellMintCoins/MortgageCoin,BitcoinHardfork/bitcoin,svost/bitcoin,barcoin-project/nothingcoin,m0gliE/fastcoin-cli,cryptocoins4all/zcoin,Jcing95/iop-hd,Bluejudy/worldcoin,droark/elements,schildbach/bitcoin,MonetaryUnit/MUE-Src,NateBrune/bitcoin-nate,cryptodev35/icash,afk11/bitcoin,Michagogo/bitcoin,braydonf/bitcoin,Xekyo/bitcoin,zetacoin/zetacoin,gravio-net/graviocoin,gameunits/gameunits,Michagogo/bitcoin,llluiop/bitcoin,andreaskern/bitcoin,florincoin/florincoin,kallewoof/elements,omefire/bitcoin,wiggi/huntercore,masterbraz/dg,aburan28/elements,Rav3nPL/bitcoin,millennial83/bitcoin,HeliumGas/helium,tmagik/catcoin,syscoin/syscoin,Kixunil/keynescoin,constantine001/bitcoin,hg5fm/nexuscoin,degenorate/Deftcoin,Tetpay/bitcoin,rustyrussell/bitcoin,s-matthew-english/bitcoin,collapsedev/cashwatt,npccoin/npccoin,JeremyRubin/bitcoin,gjhiggins/vcoin09,DMDcoin/Diamond,mrbandrews/bitcoin,cdecker/bitcoin,phelix/bitcoin,ahmedbodi/bytecoin,segwit/atbcoin-insight,elecoin/elecoin,destenson/bitcoin--bitcoin,Kangmo/bitcoin,ahmedbodi/terracoin,fanquake/bitcoin,bitgoldcoin-project/bitgoldcoin,borgcoin/Borgcoin1,fussl/elements,segwit/atbcoin-insight,kallewoof/elements,nikkitan/bitcoin,habibmasuro/bitcoin,ahmedbodi/terracoin,qubitcoin-project/QubitCoinQ2C,DSPay/DSPay,cryptodev35/icash,iQcoin/iQcoin,zixan/bitcoin,coinwarp/dogecoin,JeremyRand/namecore,langerhans/dogecoin,truthcoin/blocksize-market,tropa/axecoin,goldcoin/Goldcoin-GLD,isghe/bitcoinxt,PRabahy/bitcoin,ashleyholman/bitcoin,mitchellcash/bitcoin,uphold/bitcoin,wederw/bitcoin,Krellan/bitcoin,thrasher-/litecoin,GroestlCoin/bitcoin,wangliu/bitcoin,bdelzell/creditcoin-org-creditcoin,achow101/bitcoin,reddcoin-project/reddcoin,jiangyonghang/bitcoin,TrainMAnB/vcoincore,vertcoin/vertcoin,Earlz/dobbscoin-source,NateBrune/bitcoin-nate,alecalve/bitcoin,dobbscoin/dobbscoin-source,TrainMAnB/vcoincore,degenorate/Deftcoin,Justaphf/BitcoinUnlimited,mammix2/ccoin-dev,kigooz/smalltest,martindale/elements,gravio-net/graviocoin,qtumproject/qtum,diggcoin/diggcoin,wederw/bitcoin,myriadteam/myriadcoin,rjshaver/bitcoin,Chancoin-core/CHANCOIN,mobicoins/mobicoin-core,bespike/litecoin,greenaddress/bitcoin,nmarley/dash,Carrsy/PoundCoin,zotherstupidguy/bitcoin,Alonzo-Coeus/bitcoin,uphold/bitcoin,enlighter/Feathercoin,Friedbaumer/litecoin,stevemyers/bitcoinxt,sirk390/bitcoin,miguelfreitas/twister-core,vmp32k/litecoin,gzuser01/zetacoin-bitcoin,globaltoken/globaltoken,lateminer/bitcoin,constantine001/bitcoin,phplaboratory/psiacoin,OfficialTitcoin/titcoin-wallet,marlengit/hardfork_prototype_1_mvf-bu,monacoinproject/monacoin,TripleSpeeder/bitcoin,ShwoognationHQ/bitcoin,chaincoin/chaincoin,dagurval/bitcoinxt,NunoEdgarGub1/elements,antonio-fr/bitcoin,goldcoin/goldcoin,coinkeeper/anoncoin_20150330_fixes,111t8e/bitcoin,FinalHashLLC/namecore,Flurbos/Flurbo,wbchen99/bitcoin-hnote0,truthcoin/blocksize-market,reorder/viacoin,bittylicious/bitcoin,greenaddress/bitcoin,gwangjin2/gwangcoin-core,namecoin/namecore,kleetus/bitcoinxt,aciddude/Feathercoin,tjth/lotterycoin,petertodd/bitcoin,florincoin/florincoin,morcos/bitcoin,FeatherCoin/Feathercoin,langerhans/dogecoin,jeromewu/bitcoin-opennet,creath/barcoin,phelix/bitcoin,earthcoinproject/earthcoin,netswift/vertcoin,arruah/ensocoin,faircoin/faircoin2,instagibbs/bitcoin,dexX7/mastercore,ShadowMyst/creativechain-core,xurantju/bitcoin,qtumproject/qtum,ludbb/bitcoin,CryptArc/bitcoinxt,koharjidan/dogecoin,mycointest/owncoin,DrCrypto/darkcoin,domob1812/huntercore,zsulocal/bitcoin,iQcoin/iQcoin,basicincome/unpcoin-core,Earlz/dobbscoin-source,pouta/bitcoin,jrick/bitcoin,ionomy/ion,bitcoinec/bitcoinec,jaromil/faircoin2,ionomy/ion,Theshadow4all/ShadowCoin,BTCGPU/BTCGPU,ShadowMyst/creativechain-core,unsystemizer/bitcoin,ajweiss/bitcoin,GreenParhelia/bitcoin,krzysztofwos/BitcoinUnlimited,daliwangi/bitcoin,ShadowMyst/creativechain-core,coinkeeper/2015-06-22_18-41_ixcoin,wtogami/bitcoin,Electronic-Gulden-Foundation/egulden,GlobalBoost/GlobalBoost,Enticed87/Decipher,memorycoin/memorycoin,ekankyesme/bitcoinxt,alexandrcoin/vertcoin,zander/bitcoinclassic,JeremyRand/namecoin-core,GroestlCoin/bitcoin,jlay11/sharecoin,sugruedes/bitcoinxt,ElementsProject/elements,vcoin-project/vcoincore,coinkeeper/2015-04-19_21-20_litecoindark,thrasher-/litecoin,zcoinofficial/zcoin,lbrtcoin/albertcoin,KaSt/equikoin,sebrandon1/bitcoin,brishtiteveja/sherlockcoin,javgh/bitcoin,Climbee/artcoin,gandrewstone/bitcoinxt,Domer85/dogecoin,reddcoin-project/reddcoin,simdeveloper/bitcoin,phelix/bitcoin,paveljanik/bitcoin,trippysalmon/bitcoin,jlopp/statoshi,trippysalmon/bitcoin,cryptcoins/cryptcoin,brightcoin/brightcoin,argentumproject/argentum,jn2840/bitcoin,zotherstupidguy/bitcoin,pataquets/namecoin-core,ppcoin/ppcoin,gmaxwell/bitcoin,domob1812/i0coin,haisee/dogecoin,majestrate/twister-core,practicalswift/bitcoin,bitjson/hivemind,lclc/bitcoin,coinkeeper/2015-06-22_19-00_ziftrcoin,nikkitan/bitcoin,mb300sd/bitcoin,syscoin/syscoin,terracoin/terracoin,haraldh/bitcoin,pevernon/picoin,antcheck/antcoin,midnight-miner/LasVegasCoin,lbryio/lbrycrd,willwray/dash,Carrsy/PoundCoin,blocktrail/bitcoin,simonmulser/bitcoin,sirk390/bitcoin,jtimon/elements,particl/particl-core,mrtexaznl/mediterraneancoin,razor-coin/razor,Jcing95/iop-hd,denverl/bitcoin,keo/bitcoin,hyperwang/bitcoin,bdelzell/creditcoin-org-creditcoin,r8921039/bitcoin,benzmuircroft/REWIRE.io,leofidus/glowing-octo-ironman,LIMXTEC/DMDv3,kirkalx/bitcoin,supcoin/supcoin,s-matthew-english/bitcoin,enlighter/Feathercoin,Coinfigli/coinfigli,coinkeeper/2015-06-22_18-41_ixcoin,xurantju/bitcoin,brishtiteveja/truthcoin-cpp,dexX7/mastercore,markf78/dollarcoin,gravio-net/graviocoin,acid1789/bitcoin,andres-root/bitcoinxt,FeatherCoin/Feathercoin,gjhiggins/vcoincore,rat4/bitcoin,JeremyRand/namecore,Blackcoin/blackcoin,Cloudsy/bitcoin,zsulocal/bitcoin,2XL/bitcoin,mycointest/owncoin,Diapolo/bitcoin,skaht/bitcoin,projectinterzone/ITZ,compasscoin/compasscoin,cqtenq/Feathercoin,oklink-dev/bitcoin,dakk/soundcoin,jmgilbert2/energi,worldcoinproject/worldcoin-v0.8,plankton12345/litecoin,czr5014iph/bitcoin4e,cryptocoins4all/zcoin,pinheadmz/bitcoin,Twyford/Indigo,meighti/bitcoin,axelxod/braincoin,xuyangcn/opalcoin,rawodb/bitcoin,pouta/bitcoin,zenywallet/bitzeny,okinc/bitcoin,wcwu/bitcoin,aciddude/Feathercoin,ghostlander/Testcoin,UFOCoins/ufo,rjshaver/bitcoin,gapcoin/gapcoin,coinwarp/dogecoin,truthcoin/truthcoin-cpp,cyrixhero/bitcoin,Alex-van-der-Peet/bitcoin,anditto/bitcoin,cqtenq/Feathercoin,bitreserve/bitcoin,jimblasko/2015_UNB_Wallets,coinkeeper/2015-04-19_21-20_litecoindark,ajtowns/bitcoin,DMDcoin/Diamond,romanornr/viacoin,AllanDoensen/BitcoinUnlimited,TripleSpeeder/bitcoin,AkioNak/bitcoin,Jcing95/iop-hd,blood2/bloodcoin-0.9,DynamicCoinOrg/DMC,aniemerg/zcash,mm-s/bitcoin,bitgoldcoin-project/bitgoldcoin,cdecker/bitcoin,bankonmecoin/bitcoin,vtafaucet/virtacoin,botland/bitcoin,untrustbank/litecoin,viacoin/viacoin,vericoin/vericoin-core,globaltoken/globaltoken,masterbraz/dg,hsavit1/bitcoin,gravio-net/graviocoin,shea256/bitcoin,ixcoinofficialpage/master,BlockchainTechLLC/3dcoin,marscoin/marscoin,botland/bitcoin,bitcoin-hivemind/hivemind,digibyte/digibyte,aburan28/elements,IlfirinCano/shavercoin,DGCDev/argentum,Bitcoin-ABC/bitcoin-abc,segsignal/bitcoin,ychaim/smallchange,mikehearn/bitcoin,vtafaucet/virtacoin,wellenreiter01/Feathercoin,ryanxcharles/bitcoin,dexX7/bitcoin,GlobalBoost/GlobalBoost,biblepay/biblepay,Lucky7Studio/bitcoin,particl/particl-core,goldcoin/goldcoin,lateminer/bitcoin,EntropyFactory/creativechain-core,48thct2jtnf/P,ccoin-project/ccoin,jeromewu/bitcoin-opennet,deadalnix/bitcoin,isocolsky/bitcoinxt,StarbuckBG/BTCGPU,XX-net/twister-core,zestcoin/ZESTCOIN,reorder/viacoin,aspirecoin/aspire,tjth/lotterycoin,simdeveloper/bitcoin,dscotese/bitcoin,cannabiscoindev/cannabiscoin420,lbrtcoin/albertcoin,jlopp/statoshi,rnicoll/bitcoin,oklink-dev/bitcoin,koharjidan/bitcoin,MazaCoin/maza,domob1812/bitcoin,Vsync-project/Vsync,btc1/bitcoin,millennial83/bitcoin,jakeva/bitcoin-pwcheck,jakeva/bitcoin-pwcheck,DigiByte-Team/digibyte,SocialCryptoCoin/SocialCoin,maraoz/proofcoin,qreatora/worldcoin-v0.8,cqtenq/feathercoin_core,ajweiss/bitcoin,metrocoins/metrocoin,mikehearn/bitcoinxt,segsignal/bitcoin,tjps/bitcoin,icook/vertcoin,dannyperez/bolivarcoin,shaulkf/bitcoin,erikYX/yxcoin-FIRST,koharjidan/dogecoin,jl2012/litecoin,mruddy/bitcoin,Cocosoft/bitcoin,zcoinofficial/zcoin,kallewoof/bitcoin,gandrewstone/BitcoinUnlimited,scippio/bitcoin,BitzenyCoreDevelopers/bitzeny,BTCfork/hardfork_prototype_1_mvf-core,wangxinxi/litecoin,droark/elements,freelion93/mtucicoin,StarbuckBG/BTCGPU,bitcoinclassic/bitcoinclassic,DynamicCoinOrg/DMC,marscoin/marscoin,faircoin/faircoin2,jtimon/bitcoin,magacoin/magacoin,emc2foundation/einsteinium,syscoin/syscoin,bcpki/testblocks,coinkeeper/2015-06-22_18-36_darkcoin,myriadteam/myriadcoin,ftrader-bitcoinunlimited/hardfork_prototype_1_mvf-bu,PIVX-Project/PIVX,arnuschky/bitcoin,fedoracoin-dev/fedoracoin,WorldcoinGlobal/WorldcoinLegacy,coinkeeper/2015-06-22_19-07_digitalcoin,xawksow/GroestlCoin,rdqw/sscoin,alecalve/bitcoin,donaloconnor/bitcoin,instagibbs/bitcoin,111t8e/bitcoin,jmgilbert2/energi,randy-waterhouse/bitcoin,creath/barcoin,mb300sd/bitcoin,dgarage/bc3,goku1997/bitcoin,Dajackal/Ronpaulcoin,starwels/starwels,braydonf/bitcoin,therealaltcoin/altcoin,GIJensen/bitcoin,ravenbyron/phtevencoin,Exgibichi/statusquo,compasscoin/compasscoin,akabmikua/flowcoin,wiggi/huntercore,DynamicCoinOrg/DMC,Tetcoin/tetcoin,maraoz/proofcoin,GIJensen/bitcoin,mapineda/litecoin,manuel-zulian/CoMoNet,zebrains/Blotter,uphold/bitcoin,Bitcoinsulting/bitcoinxt,thesoftwarejedi/bitcoin,AllanDoensen/BitcoinUnlimited,antcheck/antcoin,jimblasko/2015_UNB_Wallets,nomnombtc/bitcoin,myriadcoin/myriadcoin,midnight-miner/LasVegasCoin,KibiCoin/kibicoin,Flurbos/Flurbo,fujicoin/fujicoin,joshrabinowitz/bitcoin,metacoin/florincoin,webdesignll/coin,CrimeaCoin/crimeacoin,JeremyRubin/bitcoin,bitcoinxt/bitcoinxt,benosa/bitcoin,biblepay/biblepay,rjshaver/bitcoin,krzysztofwos/BitcoinUnlimited,CoinProjects/AmsterdamCoin-v4,thormuller/yescoin2,OmniLayer/omnicore,cryptodev35/icash,instagibbs/bitcoin,Rav3nPL/bitcoin,5mil/Tradecoin,RHavar/bitcoin,pdrobek/Polcoin-1-3,FeatherCoin/Feathercoin,Alex-van-der-Peet/bitcoin,dpayne9000/Rubixz-Coin,capitalDIGI/DIGI-v-0-10-4,manuel-zulian/accumunet,BitzenyCoreDevelopers/bitzeny,UdjinM6/dash,cryptocoins4all/zcoin,Credit-Currency/CoinTestComp,TripleSpeeder/bitcoin,earonesty/bitcoin,wcwu/bitcoin,Bitcoin-ABC/bitcoin-abc,ahmedbodi/Bytecoin-MM,vcoin-project/vcoincore,npccoin/npccoin,h4x3rotab/BTCGPU,GIJensen/bitcoin,ahmedbodi/temp_vert,imharrywu/fastcoin,multicoins/marycoin,ingresscoin/ingresscoin,bitcoinsSG/bitcoin,djpnewton/bitcoin,zcoinofficial/zcoin,nigeriacoin/nigeriacoin,x-kalux/bitcoin_WiG-B,BenjaminsCrypto/Benjamins-1,faircoin/faircoin2,ppcoin/ppcoin,48thct2jtnf/P,MazaCoin/maza,kfitzgerald/titcoin,rustyrussell/bitcoin,gavinandresen/bitcoin-git,stamhe/bitcoin,coinkeeper/2015-06-22_18-46_razor,saydulk/Feathercoin,dscotese/bitcoin,Erkan-Yilmaz/twister-core,keo/bitcoin,florincoin/florincoin,SocialCryptoCoin/SocialCoin,borgcoin/Borgcoin.rar,genavarov/brcoin,shelvenzhou/BTCGPU,Anoncoin/anoncoin,masterbraz/dg,rnicoll/dogecoin,whatrye/twister-core,achow101/bitcoin,celebritycoin/CelebrityCoin,coinkeeper/2015-06-22_18-51_vertcoin,droark/elements,Earlz/dobbscoin-source,alejandromgk/Lunar,madman5844/poundkoin,pascalguru/florincoin,hsavit1/bitcoin,gjhiggins/vcoincore,pevernon/picoin,sifcoin/sifcoin,plankton12345/litecoin,core-bitcoin/bitcoin,greencoin-dev/digitalcoin,btc1/bitcoin,kallewoof/elements,ludbb/bitcoin,mincoin-project/mincoin,coinkeeper/2015-06-22_18-37_dogecoin,EthanHeilman/bitcoin,afk11/bitcoin,coinkeeper/2015-06-22_18-51_vertcoin,peerdb/cors,martindale/elements,Erkan-Yilmaz/twister-core,jarymoth/dogecoin,romanornr/viacoin,IlfirinCano/shavercoin,haobtc/bitcoin,goku1997/bitcoin,josephbisch/namecoin-core,cqtenq/feathercoin_core,Vector2000/bitcoin,fanquake/bitcoin,jiangyonghang/bitcoin,brettwittam/geocoin,Rav3nPL/doubloons-0.10,mm-s/bitcoin,akabmikua/flowcoin,DigitalPandacoin/pandacoin,cculianu/bitcoin-abc,tedlz123/Bitcoin,bitshares/bitshares-pts,andres-root/bitcoinxt,ahmedbodi/bytecoin,Kogser/bitcoin,majestrate/twister-core,brishtiteveja/sherlockcoin,bitpay/bitcoin,senadmd/coinmarketwatch,KillerByte/memorypool,elacoin/elacoin,n1bor/bitcoin,theuni/bitcoin,shea256/bitcoin,celebritycoin/investorcoin,ixcoinofficialpage/master,deadalnix/bitcoin,cerebrus29301/crowncoin,faircoin/faircoin,xieta/mincoin,markf78/dollarcoin,steakknife/bitcoin-qt,javgh/bitcoin,jlopp/statoshi,brightcoin/brightcoin,goku1997/bitcoin,gwillen/elements,jonasnick/bitcoin,GroestlCoin/bitcoin,AkioNak/bitcoin,axelxod/braincoin,Flowdalic/bitcoin,Erkan-Yilmaz/twister-core,TierNolan/bitcoin,bickojima/bitzeny,jmgilbert2/energi,shouhuas/bitcoin,wbchen99/bitcoin-hnote0,cinnamoncoin/groupcoin-1,maaku/bitcoin,tripmode/pxlcoin,ericshawlinux/bitcoin,coinkeeper/megacoin_20150410_fixes,coinerd/krugercoin,MarcoFalke/bitcoin,Mirobit/bitcoin,antonio-fr/bitcoin,vcoin-project/vcoin0.8zeta-dev,TierNolan/bitcoin,kaostao/bitcoin,randy-waterhouse/bitcoin,HashUnlimited/Einsteinium-Unlimited,my-first/octocoin,ericshawlinux/bitcoin,GlobalBoost/GlobalBoost,Darknet-Crypto/Darknet,plankton12345/litecoin,mikehearn/bitcoin,nbenoit/bitcoin,npccoin/npccoin,SoreGums/bitcoinxt,uphold/bitcoin,zcoinofficial/zcoin,skaht/bitcoin,AkioNak/bitcoin,Megacoin2/Megacoin,credits-currency/credits,nlgcoin/guldencoin-official,wellenreiter01/Feathercoin,truthcoin/truthcoin-cpp,Krellan/bitcoin,Megacoin2/Megacoin,vericoin/vericoin-core,core-bitcoin/bitcoin,BTCDDev/bitcoin,JeremyRand/bitcoin,midnight-miner/LasVegasCoin,daveperkins-github/bitcoin-dev,ptschip/bitcoinxt,Exgibichi/statusquo,Mrs-X/PIVX,worldbit/worldbit,kevin-cantwell/crunchcoin,CryptArc/bitcoin,FarhanHaque/bitcoin,funkshelper/woodcoin-b,11755033isaprimenumber/Feathercoin,collapsedev/cashwatt,haisee/dogecoin,litecoin-project/litecore-litecoin,DrCrypto/darkcoin,jonghyeopkim/bitcoinxt,vertcoin/eyeglass,nathaniel-mahieu/bitcoin,jameshilliard/bitcoin,zixan/bitcoin,micryon/GPUcoin,Earlz/dobbscoin-source,senadmd/coinmarketwatch,capitalDIGI/litecoin,shea256/bitcoin,NateBrune/bitcoin-nate,jtimon/elements,dashpay/dash,pevernon/picoin,Chancoin-core/CHANCOIN,forrestv/bitcoin,misdess/bitcoin,antonio-fr/bitcoin,EthanHeilman/bitcoin,keisercoin-official/keisercoin,cinnamoncoin/Feathercoin,mortalvikinglive/bitcoinlight,Paymium/bitcoin,madman5844/poundkoin,xeddmc/twister-core,ardsu/bitcoin,ElementsProject/elements,truthcoin/blocksize-market,Bloom-Project/Bloom,bfroemel/smallchange,atgreen/bitcoin,accraze/bitcoin,Kenwhite23/litecoin,coinkeeper/2015-06-22_18-56_megacoin,jimmysong/bitcoin,ArgonToken/ArgonToken,CrimeaCoin/crimeacoin,javgh/bitcoin,razor-coin/razor,ArgonToken/ArgonToken,coinkeeper/2015-06-22_19-07_digitalcoin,instagibbs/bitcoin,nigeriacoin/nigeriacoin,jaromil/faircoin2,nbenoit/bitcoin,WorldLeadCurrency/WLC,dperel/bitcoin,willwray/dash,ColossusCoinXT/ColossusCoinXT,chrisfranko/aiden,oleganza/bitcoin-duo,reddcoin-project/reddcoin,Rav3nPL/PLNcoin,sirk390/bitcoin,pdrobek/Polcoin-1-3,Geekcoin-Project/Geekcoin,Anfauglith/iop-hd,supcoin/supcoin,BitcoinPOW/BitcoinPOW,peerdb/cors,inutoshi/inutoshi,Kenwhite23/litecoin,rdqw/sscoin,jl2012/litecoin,roques/bitcoin,BitcoinPOW/BitcoinPOW,Rav3nPL/bitcoin,adpg211/bitcoin-master,peercoin/peercoin,BTCTaras/bitcoin,XX-net/twister-core,tmagik/catcoin,ahmedbodi/test2,litecoin-project/litecore-litecoin,JeremyRubin/bitcoin,domob1812/huntercore,RongxinZhang/bitcoinxt,constantine001/bitcoin,scippio/bitcoin,wiggi/huntercore,StarbuckBG/BTCGPU,ingresscoin/ingresscoin,zestcoin/ZESTCOIN,cinnamoncoin/Feathercoin,jtimon/bitcoin,magacoin/magacoin,marlengit/hardfork_prototype_1_mvf-bu,bankonmecoin/bitcoin,ryanxcharles/bitcoin,thesoftwarejedi/bitcoin,paveljanik/bitcoin,kbccoin/kbc,ohac/sakuracoin,roques/bitcoin,adpg211/bitcoin-master,mruddy/bitcoin,dashpay/dash,marlengit/BitcoinUnlimited,domob1812/i0coin,PandaPayProject/PandaPay,hyperwang/bitcoin,iosdevzone/bitcoin,cdecker/bitcoin,Petr-Economissa/gvidon,cyrixhero/bitcoin,diggcoin/diggcoin,midnightmagic/bitcoin,cotner/bitcoin,butterflypay/bitcoin,rjshaver/bitcoin,Bushstar/UFO-Project,welshjf/bitcoin,braydonf/bitcoin,EthanHeilman/bitcoin,oklink-dev/bitcoin_block,IlfirinIlfirin/shavercoin,sipa/bitcoin,PIVX-Project/PIVX,truthcoin/blocksize-market,jaromil/faircoin2,xawksow/GroestlCoin,ddombrowsky/radioshares,TheBlueMatt/bitcoin,knolza/gamblr,bespike/litecoin,dgenr8/bitcoinxt,thrasher-/litecoin,Litecoindark/LTCD,pstratem/elements,vertcoin/eyeglass,bitcoinsSG/bitcoin,cryptoprojects/ultimateonlinecash,coinkeeper/2015-06-22_18-30_anoncoin,wiggi/huntercore,MarcoFalke/bitcoin,ahmedbodi/vertcoin,ptschip/bitcoinxt,initaldk/bitcoin,DynamicCoinOrg/DMC,Kogser/bitcoin,dobbscoin/dobbscoin-source,keo/bitcoin,KillerByte/memorypool,capitalDIGI/litecoin,ahmedbodi/terracoin,coinwarp/dogecoin,kevin-cantwell/crunchcoin,phplaboratory/psiacoin,bmp02050/ReddcoinUpdates,Theshadow4all/ShadowCoin,ctwiz/stardust,RazorLove/cloaked-octo-spice,spiritlinxl/BTCGPU,BitcoinHardfork/bitcoin,Jeff88Ho/bitcoin,marscoin/marscoin,litecoin-project/litecoin,matlongsi/micropay,kryptokredyt/ProjektZespolowyCoin,megacoin/megacoin,basicincome/unpcoin-core,nailtaras/nailcoin,mammix2/ccoin-dev,myriadcoin/myriadcoin,Electronic-Gulden-Foundation/egulden,guncoin/guncoin,tedlz123/Bitcoin,jlopp/statoshi,renatolage/wallets-BRCoin,krzysztofwos/BitcoinUnlimited,czr5014iph/bitcoin4e,shapiroisme/datadollar,jimmykiselak/lbrycrd,wtogami/bitcoin,manuel-zulian/CoMoNet,Lucky7Studio/bitcoin,bitcoinxt/bitcoinxt,leofidus/glowing-octo-ironman,arruah/ensocoin,coinkeeper/2015-06-22_18-56_megacoin,lbrtcoin/albertcoin,brishtiteveja/truthcoin-cpp,enlighter/Feathercoin,vcoin-project/vcoin0.8zeta-dev,janko33bd/bitcoin,cinnamoncoin/Feathercoin,hsavit1/bitcoin,bitcoinplusorg/xbcwalletsource,coinkeeper/2015-06-22_18-30_anoncoin,truthcoin/truthcoin-cpp,joulecoin/joulecoin,tobeyrowe/BitStarCoin,Checkcoin/checkcoin,dgenr8/bitcoinxt,marlengit/hardfork_prototype_1_mvf-bu,Alex-van-der-Peet/bitcoin,shapiroisme/datadollar,nigeriacoin/nigeriacoin,loxal/zcash,accraze/bitcoin,cmgustavo/bitcoin,GroestlCoin/GroestlCoin,ekankyesme/bitcoinxt,jonasnick/bitcoin,goldcoin/goldcoin,jrmithdobbs/bitcoin,killerstorm/bitcoin,vcoin-project/vcoin0.8zeta-dev,gjhiggins/vcoin0.8zeta-dev,brandonrobertz/namecoin-core,Cocosoft/bitcoin,czr5014iph/bitcoin4e,paveljanik/bitcoin,gavinandresen/bitcoin-git,worldbit/worldbit,Flowdalic/bitcoin,BigBlueCeiling/augmentacoin,alejandromgk/Lunar,ardsu/bitcoin,maraoz/proofcoin,dgarage/bc2,BTCfork/hardfork_prototype_1_mvf-bu,maaku/bitcoin,ptschip/bitcoinxt,ediston/energi,GwangJin/gwangmoney-core,droark/bitcoin,erqan/twister-core,rnicoll/dogecoin,syscoin/syscoin2,lakepay/lake,denverl/bitcoin,razor-coin/razor,nikkitan/bitcoin,dannyperez/bolivarcoin,benma/bitcoin,jimmysong/bitcoin,dpayne9000/Rubixz-Coin,dan-mi-sun/bitcoin,privatecoin/privatecoin,Czarcoin/czarcoin,totallylegitbiz/totallylegitcoin,tecnovert/particl-core,TeamBitBean/bitcoin-core,CTRoundTable/Encrypted.Cash,MikeAmy/bitcoin,ShwoognationHQ/bitcoin,brandonrobertz/namecoin-core,creath/barcoin,cotner/bitcoin,GlobalBoost/GlobalBoost,okinc/bitcoin,cryptoprojects/ultimateonlinecash,franko-org/franko,sdaftuar/bitcoin,rsdevgun16e/energi,puticcoin/putic,BitcoinPOW/BitcoinPOW,wangxinxi/litecoin,globaltoken/globaltoken,gwillen/elements,ravenbyron/phtevencoin,FrictionlessCoin/iXcoin,ryanxcharles/bitcoin,credits-currency/credits,worldcoinproject/worldcoin-v0.8,destenson/bitcoin--bitcoin,gandrewstone/bitcoinxt,keesdewit82/LasVegasCoin,maaku/bitcoin,argentumproject/argentum,NateBrune/bitcoin-fio,ctwiz/stardust,mb300sd/bitcoin,crowning2/dash,dogecoin/dogecoin,GroestlCoin/bitcoin,osuyuushi/laughingmancoin,vmp32k/litecoin,pelorusjack/BlockDX,segwit/atbcoin-insight,Metronotes/bitcoin,blood2/bloodcoin-0.9,rjshaver/bitcoin,pataquets/namecoin-core,Kcoin-project/kcoin,LIMXTEC/DMDv3,RyanLucchese/energi,pdrobek/Polcoin-1-3,core-bitcoin/bitcoin,world-bank/unpay-core,sdaftuar/bitcoin,pastday/bitcoinproject,axelxod/braincoin,phelix/bitcoin,BigBlueCeiling/augmentacoin,vericoin/vericoin-core,globaltoken/globaltoken,wangliu/bitcoin,koltcoin/koltcoin,Kogser/bitcoin,pinkevich/dash,reorder/viacoin,dexX7/bitcoin,goldmidas/goldmidas,ixcoinofficialpage/master,Exgibichi/statusquo,hasanatkazmi/bitcoin,benzmuircroft/REWIRE.io,sstone/bitcoin,scamcoinz/scamcoin,ashleyholman/bitcoin,shaulkf/bitcoin,syscoin/syscoin2,zemrys/vertcoin,donaloconnor/bitcoin,bitcoinsSG/zcash,nsacoin/nsacoin,xieta/mincoin,senadmd/coinmarketwatch,amaivsimau/bitcoin,nmarley/dash,saydulk/Feathercoin,AdrianaDinca/bitcoin,pstratem/elements,cotner/bitcoin,raasakh/bardcoin,terracoin/terracoin,CodeShark/bitcoin,coinkeeper/terracoin_20150327,p2peace/oliver-twister-core,dan-mi-sun/bitcoin,torresalyssa/bitcoin,Litecoindark/LTCD,KibiCoin/kibicoin,majestrate/twister-core,HerkCoin/herkcoin,bitcoinknots/bitcoin,MitchellMintCoins/MortgageCoin,Megacoin2/Megacoin,elliotolds/bitcoin,meighti/bitcoin,Flurbos/Flurbo,SoreGums/bitcoinxt,ionomy/ion,credits-currency/credits,ryanofsky/bitcoin,sbellem/bitcoin,sbellem/bitcoin,zenywallet/bitzeny,llamasoft/ProtoShares_Cycle,jtimon/bitcoin,bankonmecoin/bitcoin,svost/bitcoin,WorldLeadCurrency/WLC,bittylicious/bitcoin,royosherove/bitcoinxt,dgarage/bc3,jlcurby/NobleCoin,hyperwang/bitcoin,grumpydevelop/singularity,gjhiggins/vcoin0.8zeta-dev,GlobalBoost/GlobalBoost,nathan-at-least/zcash,akabmikua/flowcoin,Bitcoin-com/BUcash,brettwittam/geocoin,rromanchuk/bitcoinxt,coinkeeper/megacoin_20150410_fixes,drwasho/bitcoinxt,mikehearn/bitcoin,aspanta/bitcoin,Kore-Core/kore,Xekyo/bitcoin,ryanofsky/bitcoin,mincoin-project/mincoin,viacoin/viacoin,CarpeDiemCoin/CarpeDiemLaunch,lclc/bitcoin,cryptodev35/icash,tobeyrowe/smallchange,OstlerDev/florincoin,bitcoinec/bitcoinec,RHavar/bitcoin,oleganza/bitcoin-duo,trippysalmon/bitcoin,sugruedes/bitcoinxt,Kangmo/bitcoin,riecoin/riecoin,matlongsi/micropay,untrustbank/litecoin,KaSt/ekwicoin,shadowoneau/ozcoin,bitcoin/bitcoin,btc1/bitcoin,domob1812/huntercore,omefire/bitcoin,cyrixhero/bitcoin,ghostlander/Testcoin,n1bor/bitcoin,josephbisch/namecoin-core,collapsedev/circlecash,FrictionlessCoin/iXcoin,myriadcoin/myriadcoin,HerkCoin/herkcoin,greenaddress/bitcoin,imharrywu/fastcoin,Darknet-Crypto/Darknet,sdaftuar/bitcoin,cinnamoncoin/groupcoin-1,marscoin/marscoin,Bitcoinsulting/bitcoinxt,mockcoin/mockcoin,sbaks0820/bitcoin,gjhiggins/vcoincore,shaulkf/bitcoin,BitzenyCoreDevelopers/bitzeny,apoelstra/bitcoin,litecoin-project/bitcoinomg,Bitcoin-ABC/bitcoin-abc,sipsorcery/bitcoin,josephbisch/namecoin-core,BTCDDev/bitcoin,dscotese/bitcoin,coinkeeper/2015-06-22_19-00_ziftrcoin,jiffe/cosinecoin,sarielsaz/sarielsaz,crowning2/dash,presstab/PIVX,UFOCoins/ufo,awemany/BitcoinUnlimited,Ziftr/bitcoin,Kogser/bitcoin,omefire/bitcoin,haisee/dogecoin,peacedevelop/peacecoin,deuscoin/deuscoin,jlopp/statoshi,bitjson/hivemind,Thracky/monkeycoin,bitcoinsSG/zcash,riecoin/riecoin,martindale/elements,NunoEdgarGub1/elements,iQcoin/iQcoin,yenliangl/bitcoin,aniemerg/zcash,LIMXTEC/DMDv3,qtumproject/qtum,myriadteam/myriadcoin,sipsorcery/bitcoin,nathaniel-mahieu/bitcoin,EntropyFactory/creativechain-core,fsb4000/bitcoin,gandrewstone/BitcoinUnlimited,robvanbentem/bitcoin,sifcoin/sifcoin,sickpig/BitcoinUnlimited,jul2711/jucoin,royosherove/bitcoinxt,bitcoinclassic/bitcoinclassic,bitcoin-hivemind/hivemind,collapsedev/circlecash,nathaniel-mahieu/bitcoin,sstone/bitcoin,randy-waterhouse/bitcoin,MonetaryUnit/MUE-Src,nlgcoin/guldencoin-official,daveperkins-github/bitcoin-dev,xeddmc/twister-core,putinclassic/putic,wtogami/bitcoin,namecoin/namecore,ryanxcharles/bitcoin,jlcurby/NobleCoin,gavinandresen/bitcoin-git,benma/bitcoin,genavarov/lamacoin,balajinandhu/bitcoin,npccoin/npccoin,aspanta/bitcoin,gmaxwell/bitcoin,jn2840/bitcoin,ripper234/bitcoin,TheBlueMatt/bitcoin,jambolo/bitcoin,GlobalBoost/GlobalBoost,jtimon/elements,brightcoin/brightcoin,Anoncoin/anoncoin,cmgustavo/bitcoin,Dinarcoin/dinarcoin,Exgibichi/statusquo,ionux/freicoin,coinkeeper/2015-06-22_18-52_viacoin,akabmikua/flowcoin,pascalguru/florincoin,coinkeeper/2015-06-22_19-19_worldcoin,Kogser/bitcoin,kevcooper/bitcoin,kazcw/bitcoin,habibmasuro/bitcoinxt,UASF/bitcoin,bootycoin-project/bootycoin,hasanatkazmi/bitcoin,Kore-Core/kore,domob1812/namecore,xieta/mincoin,TrainMAnB/vcoincore,gjhiggins/vcoincore,maraoz/proofcoin,RongxinZhang/bitcoinxt,gandrewstone/bitcoinxt,syscoin/syscoin2,BTCfork/hardfork_prototype_1_mvf-core,peercoin/peercoin,earthcoinproject/earthcoin,svost/bitcoin,haobtc/bitcoin,arruah/ensocoin,javgh/bitcoin,zenywallet/bitzeny,wekuiz/wekoin,ripper234/bitcoin,erqan/twister-core,collapsedev/cashwatt,jrick/bitcoin,npccoin/npccoin,reddcoin-project/reddcoin,gandrewstone/bitcoinxt,dcousens/bitcoin,zzkt/solarcoin,OmniLayer/omnicore,Adaryian/E-Currency,cryptocoins4all/zcoin,bitreserve/bitcoin,Kcoin-project/kcoin,senadmd/coinmarketwatch,czr5014iph/bitcoin4e,ghostlander/Feathercoin,tripmode/pxlcoin,haisee/dogecoin,barcoin-project/nothingcoin,tobeyrowe/smallchange,gjhiggins/vcoin09,karek314/bitcoin,jiffe/cosinecoin,theuni/bitcoin,sipsorcery/bitcoin,GroundRod/anoncoin,Mrs-X/PIVX,ShwoognationHQ/bitcoin,jambolo/bitcoin,Rav3nPL/doubloons-0.10,stevemyers/bitcoinxt,zzkt/solarcoin,tjps/bitcoin,DGCDev/argentum,xeddmc/twister-core,dannyperez/bolivarcoin,CTRoundTable/Encrypted.Cash,roques/bitcoin,SocialCryptoCoin/SocialCoin,sifcoin/sifcoin,dgarage/bc2,zetacoin/zetacoin,novaexchange/EAC,micryon/GPUcoin,ghostlander/Feathercoin,vcoin-project/vcoin0.8zeta-dev,tensaix2j/bananacoin,nvmd/bitcoin,GIJensen/bitcoin,cryptohelper/premine,paveljanik/bitcoin,richo/dongcoin,MazaCoin/mazacoin-new,ArgonToken/ArgonToken,Jcing95/iop-hd,deadalnix/bitcoin,szlaozhu/twister-core,lbrtcoin/albertcoin,BenjaminsCrypto/Benjamins-1,KaSt/ekwicoin,cmgustavo/bitcoin,starwels/starwels,cannabiscoindev/cannabiscoin420,1185/starwels,andreaskern/bitcoin,mb300sd/bitcoin,zcoinofficial/zcoin,ingresscoin/ingresscoin,llamasoft/ProtoShares_Cycle,Open-Source-Coins/EZ,Cocosoft/bitcoin,segsignal/bitcoin,richo/dongcoin,my-first/octocoin,constantine001/bitcoin,goldcoin/Goldcoin-GLD,Chancoin-core/CHANCOIN,ohac/sha1coin,DrCrypto/darkcoin,oklink-dev/bitcoin,core-bitcoin/bitcoin,jgarzik/bitcoin,Anfauglith/iop-hd,koltcoin/koltcoin,jl2012/litecoin,dgarage/bc3,jimblasko/2015_UNB_Wallets,p2peace/oliver-twister-core,antcheck/antcoin,privatecoin/privatecoin,Flowdalic/bitcoin,kbccoin/kbc,CTRoundTable/Encrypted.Cash,Bluejudy/worldcoin,SartoNess/BitcoinUnlimited,vtafaucet/virtacoin,Kogser/bitcoin,sbaks0820/bitcoin,wbchen99/bitcoin-hnote0,laudaa/bitcoin,peerdb/cors,ptschip/bitcoin,deadalnix/bitcoin,x-kalux/bitcoin_WiG-B,JeremyRand/bitcoin,earonesty/bitcoin,tobeyrowe/KitoniaCoin,ftrader-bitcoinabc/bitcoin-abc,morcos/bitcoin,REAP720801/bitcoin,btcdrak/bitcoin,roques/bitcoin,ajtowns/bitcoin,argentumproject/argentum,FinalHashLLC/namecore,keo/bitcoin,tdudz/elements,metacoin/florincoin,scmorse/bitcoin,ptschip/bitcoin,111t8e/bitcoin,Geekcoin-Project/Geekcoin,instagibbs/bitcoin,NateBrune/bitcoin-nate,zander/bitcoinclassic,RazorLove/cloaked-octo-spice,zotherstupidguy/bitcoin,llluiop/bitcoin,pouta/bitcoin,koharjidan/litecoin,dmrtsvetkov/flowercoin,benma/bitcoin,guncoin/guncoin,Bitcoin-ABC/bitcoin-abc,namecoin/namecore,BTCfork/hardfork_prototype_1_mvf-core,unsystemizer/bitcoin,koharjidan/bitcoin,AkioNak/bitcoin,argentumproject/argentum,wcwu/bitcoin,bmp02050/ReddcoinUpdates,111t8e/bitcoin,raasakh/bardcoin.exe,cmgustavo/bitcoin,CryptArc/bitcoin,jonasschnelli/bitcoin,oklink-dev/bitcoin_block,ticclassic/ic,antcheck/antcoin,shadowoneau/ozcoin,bitcoinknots/bitcoin,fullcoins/fullcoin,sstone/bitcoin,robvanbentem/bitcoin,particl/particl-core,se3000/bitcoin,midnightmagic/bitcoin,wtogami/bitcoin,MazaCoin/mazacoin-new,nvmd/bitcoin,Richcoin-Project/RichCoin,Ziftr/litecoin,nathaniel-mahieu/bitcoin,markf78/dollarcoin,jlcurby/NobleCoin,pataquets/namecoin-core,DigitalPandacoin/pandacoin,MeshCollider/bitcoin,haobtc/bitcoin,hophacker/bitcoin_malleability,TheBlueMatt/bitcoin,knolza/gamblr,mrtexaznl/mediterraneancoin,Xekyo/bitcoin,Kogser/bitcoin,maraoz/proofcoin,putinclassic/putic,MazaCoin/mazacoin-new,marklai9999/Taiwancoin,andres-root/bitcoinxt,midnightmagic/bitcoin,joroob/reddcoin,earonesty/bitcoin,practicalswift/bitcoin,hyperwang/bitcoin,21E14/bitcoin,hyperwang/bitcoin,mitchellcash/bitcoin,llluiop/bitcoin,rsdevgun16e/energi,dcousens/bitcoin,roques/bitcoin,fsb4000/bitcoin,stamhe/bitcoin,sipa/bitcoin,jameshilliard/bitcoin,manuel-zulian/CoMoNet,Horrorcoin/horrorcoin,bittylicious/bitcoin,appop/bitcoin,funkshelper/woodcore,greencoin-dev/greencoin-dev,DigitalPandacoin/pandacoin,litecoin-project/litecore-litecoin,dexX7/bitcoin,irvingruan/bitcoin,gwangjin2/gwangcoin-core,ftrader-bitcoinabc/bitcoin-abc,ixcoinofficialpage/master,novaexchange/EAC,supcoin/supcoin,drwasho/bitcoinxt,crowning2/dash,tobeyrowe/BitStarCoin,bitreserve/bitcoin,andres-root/bitcoinxt,Kogser/bitcoin,schinzelh/dash,vbernabe/freicoin,bdelzell/creditcoin-org-creditcoin,monacoinproject/monacoin,jameshilliard/bitcoin,segsignal/bitcoin,Dajackal/Ronpaulcoin,stamhe/litecoin,fedoracoin-dev/fedoracoin,cinnamoncoin/groupcoin-1,elacoin/elacoin,LIMXTEC/DMDv3,upgradeadvice/MUE-Src,pouta/bitcoin,szlaozhu/twister-core,phelix/namecore,coinkeeper/2015-06-22_18-31_bitcoin,ElementsProject/elements,Rav3nPL/bitcoin,puticcoin/putic,Kangmo/bitcoin,AkioNak/bitcoin,misdess/bitcoin,dagurval/bitcoinxt,Har01d/bitcoin,initaldk/bitcoin,andreaskern/bitcoin,dagurval/bitcoinxt,Petr-Economissa/gvidon,ticclassic/ic,miguelfreitas/twister-core,ivansib/sibcoin,KillerByte/memorypool,shaolinfry/litecoin,jeromewu/bitcoin-opennet,IlfirinIlfirin/shavercoin,dpayne9000/Rubixz-Coin,freelion93/mtucicoin,rebroad/bitcoin,erikYX/yxcoin-FIRST,dpayne9000/Rubixz-Coin,BigBlueCeiling/augmentacoin,rebroad/bitcoin,kseistrup/twister-core,Coinfigli/coinfigli,Earlz/renamedcoin,elliotolds/bitcoin,cqtenq/feathercoin_core,credits-currency/credits,mastercoin-MSC/mastercore,pstratem/bitcoin,coinkeeper/2015-06-22_18-39_feathercoin,kseistrup/twister-core,ctwiz/stardust,greencoin-dev/greencoin-dev,Coinfigli/coinfigli,mb300sd/bitcoin,shomeser/bitcoin,tmagik/catcoin,biblepay/biblepay,pastday/bitcoinproject,coinkeeper/2015-06-22_18-39_feathercoin,gzuser01/zetacoin-bitcoin,acid1789/bitcoin,GroundRod/anoncoin,dagurval/bitcoinxt,BitcoinUnlimited/BitcoinUnlimited,cddjr/BitcoinUnlimited,mockcoin/mockcoin,plncoin/PLNcoin_Core,jimmysong/bitcoin,robvanbentem/bitcoin,svcop3/svcop3,5mil/Tradecoin,accraze/bitcoin,NicolasDorier/bitcoin,CodeShark/bitcoin,TeamBitBean/bitcoin-core,nomnombtc/bitcoin,degenorate/Deftcoin,deuscoin/deuscoin,superjudge/bitcoin,sbellem/bitcoin,ticclassic/ic,acid1789/bitcoin,coinwarp/dogecoin,nailtaras/nailcoin,h4x3rotab/BTCGPU,phplaboratory/psiacoin,n1bor/bitcoin,simonmulser/bitcoin,borgcoin/Borgcoin1,emc2foundation/einsteinium,tobeyrowe/KitoniaCoin,KaSt/equikoin,fujicoin/fujicoin,joulecoin/joulecoin,digibyte/digibyte,jambolo/bitcoin,Vsync-project/Vsync,phelixbtc/bitcoin,rnicoll/bitcoin,kfitzgerald/titcoin,mycointest/owncoin,dcousens/bitcoin,botland/bitcoin,Lucky7Studio/bitcoin,barcoin-project/nothingcoin,safecoin/safecoin,phplaboratory/psiacoin,ahmedbodi/temp_vert,randy-waterhouse/bitcoin,NunoEdgarGub1/elements,digideskio/namecoin,magacoin/magacoin,likecoin-dev/bitcoin,Checkcoin/checkcoin,peercoin/peercoin,GroundRod/anoncoin,PandaPayProject/PandaPay,millennial83/bitcoin,deeponion/deeponion,biblepay/biblepay,Megacoin2/Megacoin,antonio-fr/bitcoin,UdjinM6/dash,ardsu/bitcoin,ctwiz/stardust,steakknife/bitcoin-qt,Enticed87/Decipher,dagurval/bitcoinxt,imton/bitcoin,rdqw/sscoin,iQcoin/iQcoin,bitjson/hivemind,steakknife/bitcoin-qt,Gazer022/bitcoin,ahmedbodi/vertcoin,thrasher-/litecoin,ticclassic/ic,achow101/bitcoin,ccoin-project/ccoin,ronpaulcoin/ronpaulcoin,Tetcoin/tetcoin,torresalyssa/bitcoin,shurcoin/shurcoin,svost/bitcoin,OfficialTitcoin/titcoin-wallet,genavarov/brcoin,Bitcoin-com/BUcash,kseistrup/twister-core,midnight-miner/LasVegasCoin,sbellem/bitcoin,RHavar/bitcoin,Kixunil/keynescoin,PandaPayProject/PandaPay,blocktrail/bitcoin,diggcoin/diggcoin,kleetus/bitcoin,drwasho/bitcoinxt,amaivsimau/bitcoin,coinkeeper/2015-06-22_18-30_anoncoin,mortalvikinglive/bitcoinclassic,qreatora/worldcoin-v0.8,trippysalmon/bitcoin,ajtowns/bitcoin,thormuller/yescoin2,djpnewton/bitcoin,shurcoin/shurcoin,jonghyeopkim/bitcoinxt,tecnovert/particl-core,keo/bitcoin,RazorLove/cloaked-octo-spice,gcc64/bitcoin,RyanLucchese/energi,zetacoin/zetacoin,bcpki/nonce2,midnight-miner/LasVegasCoin,prusnak/bitcoin,lakepay/lake,xawksow/GroestlCoin,janko33bd/bitcoin,monacoinproject/monacoin,llamasoft/ProtoShares_Cycle,sipa/elements,howardrya/AcademicCoin,vlajos/bitcoin,Bitcoin-ABC/bitcoin-abc,basicincome/unpcoin-core,ZiftrCOIN/ziftrcoin,s-matthew-english/bitcoin,bitcoinplusorg/xbcwalletsource,dscotese/bitcoin,supcoin/supcoin,48thct2jtnf/P,DigiByte-Team/digibyte,krzysztofwos/BitcoinUnlimited,shaolinfry/litecoin,ahmedbodi/test2,alexandrcoin/vertcoin,ShadowMyst/creativechain-core,ahmedbodi/vertcoin,thrasher-/litecoin,vcoin-project/vcoincore,shelvenzhou/BTCGPU,saydulk/Feathercoin,theuni/bitcoin,ftrader-bitcoinabc/bitcoin-abc,DigitalPandacoin/pandacoin,accraze/bitcoin,jlcurby/NobleCoin,apoelstra/bitcoin,Dinarcoin/dinarcoin,r8921039/bitcoin,Kcoin-project/kcoin,jrmithdobbs/bitcoin,coinkeeper/2015-06-22_18-46_razor,rromanchuk/bitcoinxt,bfroemel/smallchange,willwray/dash,Mrs-X/Darknet,HeliumGas/helium,plncoin/PLNcoin_Core,MitchellMintCoins/MortgageCoin,daveperkins-github/bitcoin-dev,vmp32k/litecoin,Michagogo/bitcoin,ctwiz/stardust,pinheadmz/bitcoin,capitalDIGI/DIGI-v-0-10-4,sugruedes/bitcoin,Theshadow4all/ShadowCoin,DogTagRecon/Still-Leraning,micryon/GPUcoin,sipsorcery/bitcoin,GIJensen/bitcoin,cryptocoins4all/zcoin,111t8e/bitcoin,21E14/bitcoin,sickpig/BitcoinUnlimited,masterbraz/dg,aspanta/bitcoin,xuyangcn/opalcoin,simdeveloper/bitcoin,GroestlCoin/GroestlCoin,syscoin/syscoin2,kryptokredyt/ProjektZespolowyCoin,dexX7/bitcoin,n1bor/bitcoin,domob1812/namecore,itmanagerro/tresting,jrmithdobbs/bitcoin,jonasschnelli/bitcoin,rustyrussell/bitcoin,metrocoins/metrocoin,MarcoFalke/bitcoin,coinkeeper/2015-06-22_18-31_bitcoin,zander/bitcoinclassic,patricklodder/dogecoin,oleganza/bitcoin-duo,mobicoins/mobicoin-core,Kogser/bitcoin,alexandrcoin/vertcoin,Bushstar/UFO-Project,bcpki/bitcoin,Bitcoin-com/BUcash,ahmedbodi/temp_vert,forrestv/bitcoin,joulecoin/joulecoin,coinkeeper/2015-06-22_19-13_florincoin,chaincoin/chaincoin,my-first/octocoin,Kixunil/keynescoin,emc2foundation/einsteinium,imton/bitcoin,greencoin-dev/digitalcoin,BlockchainTechLLC/3dcoin,kirkalx/bitcoin,cyrixhero/bitcoin,x-kalux/bitcoin_WiG-B,Tetpay/bitcoin,3lambert/Molecular,martindale/elements,RyanLucchese/energi,shapiroisme/datadollar,practicalswift/bitcoin,ptschip/bitcoinxt,earonesty/bitcoin,ArgonToken/ArgonToken,afk11/bitcoin,taenaive/zetacoin,coinkeeper/2015-04-19_21-20_litecoindark,sbaks0820/bitcoin,UASF/bitcoin,zetacoin/zetacoin,jonasschnelli/bitcoin,sbellem/bitcoin,qubitcoin-project/QubitCoinQ2C,ionomy/ion,ohac/sakuracoin,bitcoin-hivemind/hivemind,fussl/elements,kevcooper/bitcoin,krzysztofwos/BitcoinUnlimited,wekuiz/wekoin,aburan28/elements,phelix/namecore,DigiByte-Team/digibyte,slingcoin/sling-market,Rav3nPL/polcoin,IlfirinCano/shavercoin,DGCDev/argentum,scippio/bitcoin,bmp02050/ReddcoinUpdates,patricklodder/dogecoin,sirk390/bitcoin,RibbitFROG/ribbitcoin,odemolliens/bitcoinxt,s-matthew-english/bitcoin,kallewoof/elements,shapiroisme/datadollar,mikehearn/bitcoinxt,se3000/bitcoin,memorycoin/memorycoin,ivansib/sib16,keisercoin-official/keisercoin,KibiCoin/kibicoin,putinclassic/putic,kryptokredyt/ProjektZespolowyCoin,KillerByte/memorypool,bitcoinknots/bitcoin,mincoin-project/mincoin,lclc/bitcoin,ryanofsky/bitcoin,ftrader-bitcoinabc/bitcoin-abc,gjhiggins/fuguecoin,thelazier/dash,MonetaryUnit/MUE-Src,arnuschky/bitcoin,funbucks/notbitcoinxt,dobbscoin/dobbscoin-source,dobbscoin/dobbscoin-source,morcos/bitcoin,shea256/bitcoin,zemrys/vertcoin,zsulocal/bitcoin,MazaCoin/maza,Bitcoinsulting/bitcoinxt,hophacker/bitcoin_malleability,CarpeDiemCoin/CarpeDiemLaunch,hsavit1/bitcoin,FarhanHaque/bitcoin,HashUnlimited/Einsteinium-Unlimited,sarielsaz/sarielsaz,grumpydevelop/singularity,Litecoindark/LTCD,globaltoken/globaltoken,Darknet-Crypto/Darknet,AllanDoensen/BitcoinUnlimited,jimmysong/bitcoin,174high/bitcoin,BitcoinUnlimited/BitcoinUnlimited,dcousens/bitcoin,kazcw/bitcoin,mortalvikinglive/bitcoinlight,bickojima/bitzeny,cybermatatu/bitcoin,josephbisch/namecoin-core,MitchellMintCoins/AutoCoin,laudaa/bitcoin,jlay11/sharecoin,Theshadow4all/ShadowCoin,cybermatatu/bitcoin,UFOCoins/ufo,tripmode/pxlcoin,xuyangcn/opalcoin,marcusdiaz/BitcoinUnlimited,nvmd/bitcoin,ctwiz/stardust,irvingruan/bitcoin,psionin/smartcoin,ElementsProject/elements,itmanagerro/tresting,midnightmagic/bitcoin,dcousens/bitcoin,tdudz/elements,shaulkf/bitcoin,sdaftuar/bitcoin,coinkeeper/2015-06-22_18-52_viacoin,borgcoin/Borgcoin1,stamhe/litecoin,ivansib/sibcoin,wiggi/huntercore,Friedbaumer/litecoin,ivansib/sibcoin,Jeff88Ho/bitcoin,sebrandon1/bitcoin,FinalHashLLC/namecore,NateBrune/bitcoin-fio,REAP720801/bitcoin,Metronotes/bitcoin,netswift/vertcoin,coinkeeper/2015-06-22_18-30_anoncoin,bdelzell/creditcoin-org-creditcoin,marcusdiaz/BitcoinUnlimited,thesoftwarejedi/bitcoin,awemany/BitcoinUnlimited,Jeff88Ho/bitcoin,5mil/Tradecoin,bcpki/nonce2,RyanLucchese/energi,qubitcoin-project/QubitCoinQ2C,starwalkerz/fincoin-fork,renatolage/wallets-BRCoin,Flowdalic/bitcoin,kigooz/smalltestnew,ftrader-bitcoinunlimited/hardfork_prototype_1_mvf-bu,adpg211/bitcoin-master,Justaphf/BitcoinUnlimited,dgarage/bc2,sifcoin/sifcoin,dgarage/bc3,netswift/vertcoin,IlfirinIlfirin/shavercoin,presstab/PIVX,p2peace/oliver-twister-core,wekuiz/wekoin,misdess/bitcoin,error10/bitcoin,MeshCollider/bitcoin,neuroidss/bitcoin,rnicoll/dogecoin,mm-s/bitcoin,cryptohelper/premine,Sjors/bitcoin,phplaboratory/psiacoin,xuyangcn/opalcoin,arnuschky/bitcoin,WorldcoinGlobal/WorldcoinLegacy,apoelstra/elements,sipa/bitcoin,DogTagRecon/Still-Leraning,Blackcoin/blackcoin,Climbee/artcoin,h4x3rotab/BTCGPU,ANCompany/birdcoin-dev,icook/vertcoin,bitcoinec/bitcoinec,initaldk/bitcoin,BitcoinUnlimited/BitcoinUnlimited,coinkeeper/2015-06-22_19-13_florincoin,coinkeeper/anoncoin_20150330_fixes,zsulocal/bitcoin,coinkeeper/2015-06-22_18-51_vertcoin,scmorse/bitcoin,ajweiss/bitcoin,Horrorcoin/horrorcoin,ColossusCoinXT/ColossusCoinXT,domob1812/namecore,constantine001/bitcoin,killerstorm/bitcoin,slingcoin/sling-market,Kabei/Ippan,Adaryian/E-Currency,wiggi/huntercore,sdaftuar/bitcoin,bitbrazilcoin-project/bitbrazilcoin,kallewoof/bitcoin,bitjson/hivemind,ychaim/smallchange,aniemerg/zcash,kazcw/bitcoin,tuaris/bitcoin,21E14/bitcoin,2XL/bitcoin,hg5fm/nexuscoin,TierNolan/bitcoin,LIMXTEC/DMDv3,dgarage/bc3,gavinandresen/bitcoin-git,achow101/bitcoin,jambolo/bitcoin,zemrys/vertcoin,Rav3nPL/PLNcoin,netswift/vertcoin,kevcooper/bitcoin,deeponion/deeponion,Climbee/artcoin,dobbscoin/dobbscoin-source,GroestlCoin/GroestlCoin,pouta/bitcoin,BTCDDev/bitcoin,Vector2000/bitcoin,Richcoin-Project/RichCoin,174high/bitcoin,Twyford/Indigo,ashleyholman/bitcoin,joroob/reddcoin,manuel-zulian/accumunet,scmorse/bitcoin,Tetpay/bitcoin,rnicoll/bitcoin,cddjr/BitcoinUnlimited,2XL/bitcoin,tensaix2j/bananacoin,imharrywu/fastcoin,BitcoinPOW/BitcoinPOW,nigeriacoin/nigeriacoin,habibmasuro/bitcoinxt,starwalkerz/fincoin-fork,kleetus/bitcoinxt,rromanchuk/bitcoinxt,x-kalux/bitcoin_WiG-B,MarcoFalke/bitcoin,applecoin-official/fellatio,wcwu/bitcoin,sdaftuar/bitcoin,FrictionlessCoin/iXcoin,namecoin/namecoin-core,GreenParhelia/bitcoin,xuyangcn/opalcoin,BigBlueCeiling/augmentacoin,raasakh/bardcoin.exe,pataquets/namecoin-core,cqtenq/Feathercoin,gjhiggins/fuguecoin,megacoin/megacoin,coinkeeper/2015-06-22_19-13_florincoin,rebroad/bitcoin,shadowoneau/ozcoin,2XL/bitcoin,svcop3/svcop3,NunoEdgarGub1/elements,HashUnlimited/Einsteinium-Unlimited,simonmulser/bitcoin,ionomy/ion,ajtowns/bitcoin,jiangyonghang/bitcoin,hsavit1/bitcoin,Lucky7Studio/bitcoin,Cancercoin/Cancercoin,mockcoin/mockcoin,litecoin-project/bitcoinomg,brishtiteveja/sherlockcoin,capitalDIGI/DIGI-v-0-10-4,bcpki/testblocks,imton/bitcoin,cybermatatu/bitcoin,langerhans/dogecoin,reorder/viacoin,biblepay/biblepay,SartoNess/BitcoinUnlimited,okinc/bitcoin,wekuiz/wekoin,atgreen/bitcoin,RibbitFROG/ribbitcoin,reorder/viacoin,balajinandhu/bitcoin,Mirobit/bitcoin,EntropyFactory/creativechain-core,franko-org/franko,joshrabinowitz/bitcoin,litecoin-project/litecore-litecoin,xuyangcn/opalcoin,Ziftr/bitcoin,romanornr/viacoin,coinkeeper/2015-06-22_18-41_ixcoin,dgenr8/bitcoinxt,bitpagar/bitpagar,scamcoinz/scamcoin,ohac/sakuracoin,superjudge/bitcoin,fanquake/bitcoin,DGCDev/argentum,wellenreiter01/Feathercoin,BlockchainTechLLC/3dcoin,MazaCoin/maza,shomeser/bitcoin,bcpki/bitcoin,syscoin/syscoin2,coinkeeper/2015-06-22_18-46_razor,genavarov/lamacoin,privatecoin/privatecoin,pinheadmz/bitcoin,randy-waterhouse/bitcoin,DynamicCoinOrg/DMC,mrtexaznl/mediterraneancoin,EntropyFactory/creativechain-core,ohac/sha1coin,Rav3nPL/doubloons-0.10,TripleSpeeder/bitcoin,wangliu/bitcoin,erqan/twister-core,mapineda/litecoin,imharrywu/fastcoin,lbrtcoin/albertcoin,atgreen/bitcoin,trippysalmon/bitcoin,bitbrazilcoin-project/bitbrazilcoin,nightlydash/darkcoin,novaexchange/EAC,ravenbyron/phtevencoin,Christewart/bitcoin,nomnombtc/bitcoin,dgarage/bc2,coinkeeper/2015-06-22_18-36_darkcoin,practicalswift/bitcoin,fsb4000/bitcoin,celebritycoin/investorcoin,erqan/twister-core,ShwoognationHQ/bitcoin,cotner/bitcoin,sickpig/BitcoinUnlimited,lclc/bitcoin,sipa/elements,Jcing95/iop-hd,erqan/twister-core,greencoin-dev/greencoin-dev,joroob/reddcoin,qtumproject/qtum,MazaCoin/mazacoin-new,hyperwang/bitcoin,digibyte/digibyte,ddombrowsky/radioshares,nmarley/dash,rebroad/bitcoin,ccoin-project/ccoin,kigooz/smalltest,bfroemel/smallchange,fussl/elements,brishtiteveja/sherlockcoin,error10/bitcoin,haraldh/bitcoin,odemolliens/bitcoinxt,btc1/bitcoin,DynamicCoinOrg/DMC,bcpki/nonce2testblocks,jnewbery/bitcoin,PIVX-Project/PIVX,Rav3nPL/polcoin,habibmasuro/bitcoinxt,aciddude/Feathercoin,laudaa/bitcoin,celebritycoin/investorcoin,jmgilbert2/energi,appop/bitcoin,MazaCoin/maza,bitjson/hivemind,Anfauglith/iop-hd,pinkevich/dash,elliotolds/bitcoin,fanquake/bitcoin,Erkan-Yilmaz/twister-core,matlongsi/micropay,fedoracoin-dev/fedoracoin,nomnombtc/bitcoin,ardsu/bitcoin,gjhiggins/vcoin0.8zeta-dev,vcoin-project/vcoincore,howardrya/AcademicCoin,dexX7/bitcoin,StarbuckBG/BTCGPU,tobeyrowe/BitStarCoin,KnCMiner/bitcoin,acid1789/bitcoin,majestrate/twister-core,starwels/starwels,TeamBitBean/bitcoin-core,Bitcoin-ABC/bitcoin-abc,erikYX/yxcoin-FIRST,GwangJin/gwangmoney-core,cryptcoins/cryptcoin,pouta/bitcoin,KaSt/ekwicoin,coinkeeper/2015-06-22_19-07_digitalcoin,goldcoin/Goldcoin-GLD,Geekcoin-Project/Geekcoin,gmaxwell/bitcoin,Bushstar/UFO-Project,isocolsky/bitcoinxt,oklink-dev/litecoin_block,leofidus/glowing-octo-ironman,BTCfork/hardfork_prototype_1_mvf-bu,lclc/bitcoin,lbrtcoin/albertcoin,KnCMiner/bitcoin,cainca/liliucoin,JeremyRand/namecore,genavarov/brcoin,hg5fm/nexuscoin,coinkeeper/anoncoin_20150330_fixes,DogTagRecon/Still-Leraning,presstab/PIVX,AllanDoensen/BitcoinUnlimited,meighti/bitcoin,shaolinfry/litecoin,Diapolo/bitcoin,XertroV/bitcoin-nulldata,okinc/bitcoin,Metronotes/bitcoin,rat4/bitcoin,nomnombtc/bitcoin,m0gliE/fastcoin-cli,Friedbaumer/litecoin,cybermatatu/bitcoin,cryptodev35/icash,coinkeeper/2015-06-22_18-56_megacoin,initaldk/bitcoin,dscotese/bitcoin,AkioNak/bitcoin,coinkeeper/2015-04-19_21-20_litecoindark,KaSt/equikoin,rat4/bitcoin,domob1812/huntercore,genavarov/ladacoin,digideskio/namecoin,sarielsaz/sarielsaz,Kangmo/bitcoin,dperel/bitcoin,earonesty/bitcoin,nailtaras/nailcoin,shapiroisme/datadollar,rdqw/sscoin,joulecoin/joulecoin,koharjidan/bitcoin,worldcoinproject/worldcoin-v0.8,nsacoin/nsacoin,PIVX-Project/PIVX,biblepay/biblepay,axelxod/braincoin,bitshares/bitshares-pts,fedoracoin-dev/fedoracoin,REAP720801/bitcoin,wellenreiter01/Feathercoin,nlgcoin/guldencoin-official,howardrya/AcademicCoin,11755033isaprimenumber/Feathercoin,oklink-dev/bitcoin,borgcoin/Borgcoin.rar,domob1812/bitcoin,midnight-miner/LasVegasCoin,willwray/dash,Rav3nPL/bitcoin,amaivsimau/bitcoin,gandrewstone/bitcoinxt,Christewart/bitcoin,Charlesugwu/Vintagecoin,qtumproject/qtum,Paymium/bitcoin,mammix2/ccoin-dev,oleganza/bitcoin-duo,ludbb/bitcoin,shomeser/bitcoin,n1bor/bitcoin,antonio-fr/bitcoin,shaolinfry/litecoin,scippio/bitcoin,sbellem/bitcoin,nlgcoin/guldencoin-official,aburan28/elements,genavarov/lamacoin,metacoin/florincoin,jakeva/bitcoin-pwcheck,brishtiteveja/sherlockholmescoin,Cancercoin/Cancercoin,Mrs-X/PIVX,ticclassic/ic,coinkeeper/2015-06-22_19-13_florincoin,okinc/litecoin,Jcing95/iop-hd,kaostao/bitcoin,crowning2/dash,lbrtcoin/albertcoin,butterflypay/bitcoin,namecoin/namecore,misdess/bitcoin,dakk/soundcoin,mruddy/bitcoin,grumpydevelop/singularity,osuyuushi/laughingmancoin,wbchen99/bitcoin-hnote0,jgarzik/bitcoin,11755033isaprimenumber/Feathercoin,wederw/bitcoin,bitcoin/bitcoin,razor-coin/razor,kryptokredyt/ProjektZespolowyCoin,ediston/energi,coinkeeper/terracoin_20150327,scippio/bitcoin,MazaCoin/mazacoin-new,gmaxwell/bitcoin,raasakh/bardcoin,tedlz123/Bitcoin,pinkevich/dash,patricklodder/dogecoin,miguelfreitas/twister-core,Mrs-X/Darknet,mapineda/litecoin,knolza/gamblr,marcusdiaz/BitcoinUnlimited,domob1812/namecore,bespike/litecoin,aspanta/bitcoin,greencoin-dev/digitalcoin,riecoin/riecoin,zzkt/solarcoin,xurantju/bitcoin,Bitcoin-com/BUcash,rawodb/bitcoin,genavarov/ladacoin,Ziftr/litecoin,jambolo/bitcoin,cannabiscoindev/cannabiscoin420,ftrader-bitcoinunlimited/hardfork_prototype_1_mvf-bu,wederw/bitcoin,qubitcoin-project/QubitCoinQ2C,phelixbtc/bitcoin,ColossusCoinXT/ColossusCoinXT,koharjidan/dogecoin,simonmulser/bitcoin,neutrinofoundation/neutrino-digital-currency,rsdevgun16e/energi,bcpki/testblocks,gandrewstone/bitcoinxt,PandaPayProject/PandaPay,sebrandon1/bitcoin,coinkeeper/2015-06-22_18-46_razor,gwillen/elements,bcpki/nonce2testblocks,Dajackal/Ronpaulcoin,ahmedbodi/vertcoin,neuroidss/bitcoin,UdjinM6/dash,CryptArc/bitcoin,Justaphf/BitcoinUnlimited,hasanatkazmi/bitcoin,truthcoin/blocksize-market,Czarcoin/czarcoin,coinkeeper/2015-06-22_19-13_florincoin,presstab/PIVX,marscoin/marscoin,FinalHashLLC/namecore,p2peace/oliver-twister-core,mortalvikinglive/bitcoinclassic,Open-Source-Coins/EZ,nailtaras/nailcoin,Rav3nPL/PLNcoin,ahmedbodi/terracoin,ravenbyron/phtevencoin,tensaix2j/bananacoin,ryanofsky/bitcoin,jgarzik/bitcoin,btcdrak/bitcoin,donaloconnor/bitcoin,dmrtsvetkov/flowercoin,reddink/reddcoin,mincoin-project/mincoin,TierNolan/bitcoin,webdesignll/coin,SartoNess/BitcoinUnlimited,jimblasko/UnbreakableCoin-master,litecoin-project/litecoin,blocktrail/bitcoin,metacoin/florincoin,droark/bitcoin,icook/vertcoin,petertodd/bitcoin,untrustbank/litecoin,Bitcoin-ABC/bitcoin-abc,2XL/bitcoin,vertcoin/vertcoin,coinkeeper/2015-06-22_18-30_anoncoin,blood2/bloodcoin-0.9,Bluejudy/worldcoin,megacoin/megacoin,tjps/bitcoin,phelix/bitcoin,raasakh/bardcoin,plncoin/PLNcoin_Core,kevin-cantwell/crunchcoin,pstratem/elements,metrocoins/metrocoin,Rav3nPL/PLNcoin,ohac/sakuracoin,phelix/namecore,ajweiss/bitcoin,ahmedbodi/Bytecoin-MM,daveperkins-github/bitcoin-dev,nlgcoin/guldencoin-official,megacoin/megacoin,tobeyrowe/smallchange,uphold/bitcoin,GreenParhelia/bitcoin,REAP720801/bitcoin,Xekyo/bitcoin,x-kalux/bitcoin_WiG-B,sirk390/bitcoin,vtafaucet/virtacoin,tobeyrowe/BitStarCoin,bitgoldcoin-project/bitgoldcoin,elecoin/elecoin,coinkeeper/2015-06-22_18-36_darkcoin,pstratem/bitcoin,janko33bd/bitcoin,josephbisch/namecoin-core,balajinandhu/bitcoin,GroestlCoin/bitcoin,Krellan/bitcoin,keesdewit82/LasVegasCoin,roques/bitcoin,bcpki/nonce2testblocks,ixcoinofficialpage/master,kleetus/bitcoin,jeromewu/bitcoin-opennet,arruah/ensocoin,se3000/bitcoin,kirkalx/bitcoin,ekankyesme/bitcoinxt,torresalyssa/bitcoin,jarymoth/dogecoin,isghe/bitcoinxt,Justaphf/BitcoinUnlimited,ohac/sakuracoin,zebrains/Blotter,bcpki/testblocks,tmagik/catcoin,REAP720801/bitcoin,ahmedbodi/temp_vert,tmagik/catcoin,killerstorm/bitcoin,nathaniel-mahieu/bitcoin,mikehearn/bitcoinxt,gcc64/bitcoin,CrimeaCoin/crimeacoin,daliwangi/bitcoin,DrCrypto/darkcoin,error10/bitcoin,RongxinZhang/bitcoinxt,jonasnick/bitcoin,TrainMAnB/vcoincore,mobicoins/mobicoin-core,Rav3nPL/doubloons-08,rjshaver/bitcoin,gandrewstone/BitcoinUnlimited,mortalvikinglive/bitcoinlight,coinkeeper/2015-06-22_18-31_bitcoin,cainca/liliucoin,SoreGums/bitcoinxt,h4x3rotab/BTCGPU,koharjidan/litecoin,apoelstra/elements,jimblasko/UnbreakableCoin-master,alecalve/bitcoin,bitcoinplusorg/xbcwalletsource,dan-mi-sun/bitcoin,coinkeeper/2015-06-22_18-52_viacoin,experiencecoin/experiencecoin,instagibbs/bitcoin,Earlz/renamedcoin,psionin/smartcoin,deeponion/deeponion,RongxinZhang/bitcoinxt,gjhiggins/vcoincore,worldcoinproject/worldcoin-v0.8,BitzenyCoreDevelopers/bitzeny,coinkeeper/2015-06-22_19-00_ziftrcoin,coinkeeper/2015-06-22_18-52_viacoin,zottejos/merelcoin,oklink-dev/litecoin_block,puticcoin/putic,svost/bitcoin,faircoin/faircoin,nsacoin/nsacoin,blocktrail/bitcoin,supcoin/supcoin,ivansib/sibcoin,WorldLeadCurrency/WLC,cculianu/bitcoin-abc,applecoin-official/fellatio,earthcoinproject/earthcoin,SartoNess/BitcoinUnlimited,CoinProjects/AmsterdamCoin-v4,pascalguru/florincoin,coinkeeper/2015-06-22_19-19_worldcoin,oklink-dev/litecoin_block,lakepay/lake,genavarov/lamacoin,BTCfork/hardfork_prototype_1_mvf-bu,OstlerDev/florincoin,coinkeeper/2015-06-22_18-37_dogecoin,nigeriacoin/nigeriacoin,awemany/BitcoinUnlimited,CryptArc/bitcoin,genavarov/ladacoin,cheehieu/bitcoin,CrimeaCoin/crimeacoin,TGDiamond/Diamond,sipsorcery/bitcoin,Kore-Core/kore,habibmasuro/bitcoin,wellenreiter01/Feathercoin,initaldk/bitcoin,loxal/zcash,goldcoin/goldcoin,Exceltior/dogecoin,ftrader-bitcoinunlimited/hardfork_prototype_1_mvf-bu,SartoNess/BitcoinUnlimited,vericoin/vericoin-core,greencoin-dev/digitalcoin,borgcoin/Borgcoin.rar,DSPay/DSPay,dperel/bitcoin,domob1812/bitcoin,chrisfranko/aiden,coinkeeper/terracoin_20150327,cryptohelper/premine,karek314/bitcoin,superjudge/bitcoin,amaivsimau/bitcoin,vlajos/bitcoin,DMDcoin/Diamond,fedoracoin-dev/fedoracoin,pelorusjack/BlockDX,compasscoin/compasscoin,CryptArc/bitcoin,supcoin/supcoin,jamesob/bitcoin,cheehieu/bitcoin,crowning-/dash,karek314/bitcoin,basicincome/unpcoin-core,jamesob/bitcoin,nailtaras/nailcoin,bitbrazilcoin-project/bitbrazilcoin,experiencecoin/experiencecoin,pinkevich/dash,starwels/starwels,bitpay/bitcoin,guncoin/guncoin,bitcoinsSG/bitcoin,cannabiscoindev/cannabiscoin420,morcos/bitcoin,skaht/bitcoin,simonmulser/bitcoin,Enticed87/Decipher,zenywallet/bitzeny,collapsedev/circlecash,CryptArc/bitcoinxt,tedlz123/Bitcoin,Domer85/dogecoin,enlighter/Feathercoin,ahmedbodi/test2,sbaks0820/bitcoin,GwangJin/gwangmoney-core,mapineda/litecoin,funkshelper/woodcore,kigooz/smalltest,Bloom-Project/Bloom,BitcoinHardfork/bitcoin,Ziftr/bitcoin,keesdewit82/LasVegasCoin,jakeva/bitcoin-pwcheck,Kabei/Ippan,oklink-dev/bitcoin_block,sarielsaz/sarielsaz,dexX7/bitcoin,dev1972/Satellitecoin,cculianu/bitcoin-abc,domob1812/bitcoin,benosa/bitcoin,JeremyRand/namecoin-core,destenson/bitcoin--bitcoin,alecalve/bitcoin,vlajos/bitcoin,coinkeeper/2015-06-22_19-00_ziftrcoin,wtogami/bitcoin,tjps/bitcoin,tropa/axecoin,phelixbtc/bitcoin,Dinarcoin/dinarcoin,Bluejudy/worldcoin,sipa/elements,funkshelper/woodcoin-b,prusnak/bitcoin,btc1/bitcoin,donaloconnor/bitcoin,arnuschky/bitcoin,tjps/bitcoin,manuel-zulian/accumunet,Cancercoin/Cancercoin,dgenr8/bitcoin,Gazer022/bitcoin,raasakh/bardcoin.exe,kseistrup/twister-core,brettwittam/geocoin,rawodb/bitcoin,gcc64/bitcoin,ddombrowsky/radioshares,dogecoin/dogecoin,Tetpay/bitcoin,mrbandrews/bitcoin,Thracky/monkeycoin,bespike/litecoin,torresalyssa/bitcoin,jmcorgan/bitcoin,MasterX1582/bitcoin-becoin,riecoin/riecoin,Dinarcoin/dinarcoin,octocoin-project/octocoin,ionux/freicoin,KnCMiner/bitcoin,applecoin-official/applecoin,Electronic-Gulden-Foundation/egulden,themusicgod1/bitcoin,Vector2000/bitcoin,Carrsy/PoundCoin,bitreserve/bitcoin,21E14/bitcoin,Czarcoin/czarcoin,monacoinproject/monacoin,BTCTaras/bitcoin,diggcoin/diggcoin,itmanagerro/tresting,amaivsimau/bitcoin,theuni/bitcoin,crowning-/dash,dgarage/bc2,deuscoin/deuscoin,inutoshi/inutoshi,kirkalx/bitcoin,SocialCryptoCoin/SocialCoin,zzkt/solarcoin,nathan-at-least/zcash,particl/particl-core,schinzelh/dash,Diapolo/bitcoin,nightlydash/darkcoin,gzuser01/zetacoin-bitcoin,jl2012/litecoin,MitchellMintCoins/AutoCoin,dexX7/mastercore,kseistrup/twister-core,btcdrak/bitcoin,MasterX1582/bitcoin-becoin,zcoinofficial/zcoin,royosherove/bitcoinxt,whatrye/twister-core,Jeff88Ho/bitcoin,crowning2/dash,gazbert/bitcoin,jiangyonghang/bitcoin,jimmykiselak/lbrycrd,puticcoin/putic,JeremyRubin/bitcoin,royosherove/bitcoinxt,plankton12345/litecoin,Flurbos/Flurbo,marlengit/BitcoinUnlimited,BigBlueCeiling/augmentacoin,ivansib/sib16,theuni/bitcoin,XertroV/bitcoin-nulldata,jtimon/elements,multicoins/marycoin,Enticed87/Decipher,CarpeDiemCoin/CarpeDiemLaunch,tecnovert/particl-core,shomeser/bitcoin,cqtenq/Feathercoin,ftrader-bitcoinabc/bitcoin-abc,RongxinZhang/bitcoinxt,Tetcoin/tetcoin,mortalvikinglive/bitcoinlight,core-bitcoin/bitcoin,habibmasuro/bitcoin,aspanta/bitcoin,OmniLayer/omnicore,keesdewit82/LasVegasCoin,slingcoin/sling-market,and2099/twister-core,Carrsy/PoundCoin,MarcoFalke/bitcoin,Open-Source-Coins/EZ,safecoin/safecoin,gmaxwell/bitcoin,cqtenq/feathercoin_core,czr5014iph/bitcoin4e,llluiop/bitcoin,pstratem/elements,vericoin/vericoin-core,dev1972/Satellitecoin,raasakh/bardcoin,experiencecoin/experiencecoin,Vector2000/bitcoin,ftrader-bitcoinabc/bitcoin-abc,zcoinofficial/zcoin,nsacoin/nsacoin,jrick/bitcoin,reddcoin-project/reddcoin,svcop3/svcop3,oleganza/bitcoin-duo,grumpydevelop/singularity,cheehieu/bitcoin,vbernabe/freicoin,CoinProjects/AmsterdamCoin-v4,arruah/ensocoin,ekankyesme/bitcoinxt,BTCGPU/BTCGPU,cdecker/bitcoin,Earlz/renamedcoin,florincoin/florincoin,jmcorgan/bitcoin,applecoin-official/applecoin,elacoin/elacoin,oleganza/bitcoin-duo,AllanDoensen/BitcoinUnlimited,WorldLeadCurrency/WLC,drwasho/bitcoinxt,cryptoprojects/ultimateonlinecash,wangxinxi/litecoin,parvez3019/bitcoin,osuyuushi/laughingmancoin,JeremyRand/bitcoin,tjth/lotterycoin,langerhans/dogecoin,mastercoin-MSC/mastercore,jlay11/sharecoin,nailtaras/nailcoin,Kangmo/bitcoin,freelion93/mtucicoin,zotherstupidguy/bitcoin,cculianu/bitcoin-abc,NicolasDorier/bitcoin,zottejos/merelcoin,JeremyRubin/bitcoin,Friedbaumer/litecoin,jameshilliard/bitcoin,Kenwhite23/litecoin,safecoin/safecoin,haobtc/bitcoin,bitshares/bitshares-pts,practicalswift/bitcoin,willwray/dash,ZiftrCOIN/ziftrcoin,gjhiggins/vcoin09,RibbitFROG/ribbitcoin,apoelstra/elements,zottejos/merelcoin,droark/bitcoin,bitcoinsSG/bitcoin,raasakh/bardcoin.exe,karek314/bitcoin,peercoin/peercoin,bankonmecoin/bitcoin,barcoin-project/nothingcoin,kevcooper/bitcoin,coinkeeper/2015-06-22_18-31_bitcoin,genavarov/brcoin,UdjinM6/dash,mooncoin-project/mooncoin-landann,sugruedes/bitcoin,aciddude/Feathercoin,Cloudsy/bitcoin,fujicoin/fujicoin,bitcoinknots/bitcoin,kbccoin/kbc,royosherove/bitcoinxt,bitcoinclassic/bitcoinclassic,chrisfranko/aiden,schildbach/bitcoin,ashleyholman/bitcoin,atgreen/bitcoin,bespike/litecoin,icook/vertcoin,safecoin/safecoin,safecoin/safecoin,Darknet-Crypto/Darknet,gjhiggins/vcoincore,raasakh/bardcoin.exe,irvingruan/bitcoin,cheehieu/bitcoin,benma/bitcoin,coinkeeper/2015-06-22_18-36_darkcoin,laudaa/bitcoin,npccoin/npccoin,Xekyo/bitcoin,cddjr/BitcoinUnlimited,freelion93/mtucicoin,BTCDDev/bitcoin,phelixbtc/bitcoin,PRabahy/bitcoin,awemany/BitcoinUnlimited,sugruedes/bitcoin,JeremyRand/bitcoin,RibbitFROG/ribbitcoin,mikehearn/bitcoinxt,coinkeeper/2015-06-22_19-07_digitalcoin,JeremyRubin/bitcoin,Exceltior/dogecoin,gwillen/elements,ftrader-bitcoinabc/bitcoin-abc,BenjaminsCrypto/Benjamins-1,acid1789/bitcoin,rsdevgun16e/energi,digibyte/digibyte,Alonzo-Coeus/bitcoin,MarcoFalke/bitcoin,janko33bd/bitcoin,wcwu/bitcoin,ftrader-bitcoinabc/bitcoin-abc,coinkeeper/2015-06-22_18-41_ixcoin,terracoin/terracoin,cerebrus29301/crowncoin,nmarley/dash,Bitcoin-ABC/bitcoin-abc,dpayne9000/Rubixz-Coin,vmp32k/litecoin,MasterX1582/bitcoin-becoin,javgh/bitcoin,phelixbtc/bitcoin,KnCMiner/bitcoin,xawksow/GroestlCoin,nikkitan/bitcoin,jmcorgan/bitcoin,GroundRod/anoncoin,ivansib/sibcoin,myriadcoin/myriadcoin,Ziftr/litecoin,loxal/zcash,shouhuas/bitcoin,coinkeeper/megacoin_20150410_fixes,Blackcoin/blackcoin,stevemyers/bitcoinxt,Mrs-X/Darknet,wekuiz/wekoin,zestcoin/ZESTCOIN,metrocoins/metrocoin,mockcoin/mockcoin,Rav3nPL/doubloons-08,mincoin-project/mincoin,pascalguru/florincoin,wellenreiter01/Feathercoin,coinkeeper/2015-06-22_18-37_dogecoin,keesdewit82/LasVegasCoin,Bushstar/UFO-Project,ccoin-project/ccoin,Bitcoin-com/BUcash,dpayne9000/Rubixz-Coin,174high/bitcoin,syscoin/syscoin,blocktrail/bitcoin,kleetus/bitcoin,m0gliE/fastcoin-cli,ekankyesme/bitcoinxt,TGDiamond/Diamond,Flurbos/Flurbo,coinkeeper/2015-06-22_19-19_worldcoin,midnightmagic/bitcoin,axelxod/braincoin,sstone/bitcoin,braydonf/bitcoin,DGCDev/digitalcoin,credits-currency/credits,thormuller/yescoin2,prusnak/bitcoin,apoelstra/elements,ediston/energi,botland/bitcoin,BTCDDev/bitcoin,rebroad/bitcoin,cddjr/BitcoinUnlimited,174high/bitcoin,EthanHeilman/bitcoin,anditto/bitcoin,Sjors/bitcoin,mrbandrews/bitcoin,cybermatatu/bitcoin,MonetaryUnit/MUE-Src,hg5fm/nexuscoin,therealaltcoin/altcoin,metacoin/florincoin,zestcoin/ZESTCOIN,alejandromgk/Lunar,cmgustavo/bitcoin,JeremyRand/bitcoin,riecoin/riecoin,xawksow/GroestlCoin,TheBlueMatt/bitcoin,vbernabe/freicoin,therealaltcoin/altcoin,KaSt/ekwicoin,rat4/bitcoin,bitpagar/bitpagar,Exgibichi/statusquo,Earlz/renamedcoin,ronpaulcoin/ronpaulcoin,uphold/bitcoin,Har01d/bitcoin,Bitcoin-ABC/bitcoin-abc,DMDcoin/Diamond,xurantju/bitcoin,arruah/ensocoin,hophacker/bitcoin_malleability,myriadteam/myriadcoin,dexX7/bitcoin,applecoin-official/applecoin,lbrtcoin/albertcoin,111t8e/bitcoin,steakknife/bitcoin-qt,nathaniel-mahieu/bitcoin,BTCfork/hardfork_prototype_1_mvf-bu,afk11/bitcoin,ajtowns/bitcoin,experiencecoin/experiencecoin,octocoin-project/octocoin,tecnovert/particl-core,experiencecoin/experiencecoin,Anfauglith/iop-hd,whatrye/twister-core,pastday/bitcoinproject,BTCfork/hardfork_prototype_1_mvf-core,phelix/namecore,iosdevzone/bitcoin,pstratem/bitcoin,destenson/bitcoin--bitcoin,chaincoin/chaincoin,renatolage/wallets-BRCoin,pascalguru/florincoin,monacoinproject/monacoin,unsystemizer/bitcoin,bitcoinplusorg/xbcwalletsource,upgradeadvice/MUE-Src,applecoin-official/applecoin,haobtc/bitcoin,diggcoin/diggcoin,misdess/bitcoin,XertroV/bitcoin-nulldata,isle2983/bitcoin,joulecoin/joulecoin,vertcoin/vertcoin,untrustbank/litecoin,lbrtcoin/albertcoin,FarhanHaque/bitcoin,faircoin/faircoin,litecoin-project/bitcoinomg,kaostao/bitcoin,xurantju/bitcoin,superjudge/bitcoin,domob1812/huntercore,fujicoin/fujicoin,Flurbos/Flurbo,welshjf/bitcoin,pataquets/namecoin-core,degenorate/Deftcoin,fanquake/bitcoin,jn2840/bitcoin,markf78/dollarcoin,Bitcoinsulting/bitcoinxt,andreaskern/bitcoin,spiritlinxl/BTCGPU,Richcoin-Project/RichCoin,Kixunil/keynescoin,Thracky/monkeycoin,mastercoin-MSC/mastercore,cqtenq/Feathercoin,m0gliE/fastcoin-cli,shouhuas/bitcoin,themusicgod1/bitcoin,isle2983/bitcoin,coinkeeper/2015-06-22_19-07_digitalcoin,Michagogo/bitcoin,ClusterCoin/ClusterCoin,Ziftr/litecoin,shurcoin/shurcoin,jimmykiselak/lbrycrd,fullcoins/fullcoin,rnicoll/dogecoin,TheOncomingStorm/logincoinadvanced,united-scrypt-coin-project/unitedscryptcoin,fsb4000/bitcoin,cainca/liliucoin,Checkcoin/checkcoin,kallewoof/elements,jiangyonghang/bitcoin,memorycoin/memorycoin,shaolinfry/litecoin,lbryio/lbrycrd,shomeser/bitcoin,CoinProjects/AmsterdamCoin-v4,jambolo/bitcoin,tuaris/bitcoin,worldcoinproject/worldcoin-v0.8,keisercoin-official/keisercoin,apoelstra/bitcoin,nomnombtc/bitcoin,tropa/axecoin,Ziftr/bitcoin,coinkeeper/2015-04-19_21-20_litecoindark,cybermatatu/bitcoin,ludbb/bitcoin,guncoin/guncoin,tuaris/bitcoin,h4x3rotab/BTCGPU,aburan28/elements,Electronic-Gulden-Foundation/egulden,kbccoin/kbc,totallylegitbiz/totallylegitcoin,kleetus/bitcoin,MasterX1582/bitcoin-becoin,Credit-Currency/CoinTestComp,Domer85/dogecoin,TGDiamond/Diamond,ColossusCoinXT/ColossusCoinXT,gameunits/gameunits,DGCDev/digitalcoin,and2099/twister-core,habibmasuro/bitcoin,unsystemizer/bitcoin,mrbandrews/bitcoin,pstratem/bitcoin,royosherove/bitcoinxt,webdesignll/coin,alexandrcoin/vertcoin,Gazer022/bitcoin,Cloudsy/bitcoin,franko-org/franko,andreaskern/bitcoin,matlongsi/micropay,upgradeadvice/MUE-Src,kseistrup/twister-core,Vector2000/bitcoin,mooncoin-project/mooncoin-landann,5mil/Tradecoin,kevin-cantwell/crunchcoin,sbaks0820/bitcoin,bitpagar/bitpagar,3lambert/Molecular,dev1972/Satellitecoin,markf78/dollarcoin,omefire/bitcoin,richo/dongcoin,error10/bitcoin,cyrixhero/bitcoin,fujicoin/fujicoin,Rav3nPL/bitcoin,Geekcoin-Project/Geekcoin,applecoin-official/applecoin,TeamBitBean/bitcoin-core,pinheadmz/bitcoin,compasscoin/compasscoin,myriadteam/myriadcoin,pstratem/elements,Friedbaumer/litecoin,Domer85/dogecoin,nsacoin/nsacoin,kryptokredyt/ProjektZespolowyCoin,butterflypay/bitcoin,AdrianaDinca/bitcoin,marlengit/BitcoinUnlimited,Vsync-project/Vsync,zestcoin/ZESTCOIN,tropa/axecoin,tjth/lotterycoin,jmcorgan/bitcoin,XX-net/twister-core,koharjidan/dogecoin,zixan/bitcoin,zetacoin/zetacoin,destenson/bitcoin--bitcoin,ftrader-bitcoinabc/bitcoin-abc,bcpki/bitcoin,bitcoinxt/bitcoinxt,bickojima/bitzeny,ANCompany/birdcoin-dev,ahmedbodi/bytecoin,vmp32k/litecoin
191a8dc2831ad5288334907bba51da0581bf2622
bench/bench_gemm.cpp
bench/bench_gemm.cpp
// g++-4.4 bench_gemm.cpp -I .. -O2 -DNDEBUG -lrt -fopenmp && OMP_NUM_THREADS=2 ./a.out // icpc bench_gemm.cpp -I .. -O3 -DNDEBUG -lrt -openmp && OMP_NUM_THREADS=2 ./a.out #include <iostream> #include <Eigen/Core> #include <bench/BenchTimer.h> using namespace std; using namespace Eigen; #ifndef SCALAR // #define SCALAR std::complex<float> #define SCALAR float #endif typedef SCALAR Scalar; typedef NumTraits<Scalar>::Real RealScalar; typedef Matrix<RealScalar,Dynamic,Dynamic> A; typedef Matrix</*Real*/Scalar,Dynamic,Dynamic> B; typedef Matrix<Scalar,Dynamic,Dynamic> C; typedef Matrix<RealScalar,Dynamic,Dynamic> M; #ifdef HAVE_BLAS extern "C" { #include <bench/btl/libs/C_BLAS/blas.h> } static float fone = 1; static float fzero = 0; static double done = 1; static double szero = 0; static std::complex<float> cfone = 1; static std::complex<float> cfzero = 0; static std::complex<double> cdone = 1; static std::complex<double> cdzero = 0; static char notrans = 'N'; static char trans = 'T'; static char nonunit = 'N'; static char lower = 'L'; static char right = 'R'; static int intone = 1; void blas_gemm(const MatrixXf& a, const MatrixXf& b, MatrixXf& c) { int M = c.rows(); int N = c.cols(); int K = a.cols(); int lda = a.rows(); int ldb = b.rows(); int ldc = c.rows(); sgemm_(&notrans,&notrans,&M,&N,&K,&fone, const_cast<float*>(a.data()),&lda, const_cast<float*>(b.data()),&ldb,&fone, c.data(),&ldc); } EIGEN_DONT_INLINE void blas_gemm(const MatrixXd& a, const MatrixXd& b, MatrixXd& c) { int M = c.rows(); int N = c.cols(); int K = a.cols(); int lda = a.rows(); int ldb = b.rows(); int ldc = c.rows(); dgemm_(&notrans,&notrans,&M,&N,&K,&done, const_cast<double*>(a.data()),&lda, const_cast<double*>(b.data()),&ldb,&done, c.data(),&ldc); } void blas_gemm(const MatrixXcf& a, const MatrixXcf& b, MatrixXcf& c) { int M = c.rows(); int N = c.cols(); int K = a.cols(); int lda = a.rows(); int ldb = b.rows(); int ldc = c.rows(); cgemm_(&notrans,&notrans,&M,&N,&K,(float*)&cfone, const_cast<float*>((const float*)a.data()),&lda, const_cast<float*>((const float*)b.data()),&ldb,(float*)&cfone, (float*)c.data(),&ldc); } void blas_gemm(const MatrixXcd& a, const MatrixXcd& b, MatrixXcd& c) { int M = c.rows(); int N = c.cols(); int K = a.cols(); int lda = a.rows(); int ldb = b.rows(); int ldc = c.rows(); zgemm_(&notrans,&notrans,&M,&N,&K,(double*)&cdone, const_cast<double*>((const double*)a.data()),&lda, const_cast<double*>((const double*)b.data()),&ldb,(double*)&cdone, (double*)c.data(),&ldc); } #endif void matlab_cplx_cplx(const M& ar, const M& ai, const M& br, const M& bi, M& cr, M& ci) { cr.noalias() += ar * br; cr.noalias() -= ai * bi; ci.noalias() += ar * bi; ci.noalias() += ai * br; } void matlab_real_cplx(const M& a, const M& br, const M& bi, M& cr, M& ci) { cr.noalias() += a * br; ci.noalias() += a * bi; } void matlab_cplx_real(const M& ar, const M& ai, const M& b, M& cr, M& ci) { cr.noalias() += ar * b; ci.noalias() += ai * b; } template<typename A, typename B, typename C> EIGEN_DONT_INLINE void gemm(const A& a, const B& b, C& c) { c.noalias() += a * b; } int main(int argc, char ** argv) { std::ptrdiff_t l1 = internal::queryL1CacheSize(); std::ptrdiff_t l2 = internal::queryTopLevelCacheSize(); std::cout << "L1 cache size = " << (l1>0 ? l1/1024 : -1) << " KB\n"; std::cout << "L2/L3 cache size = " << (l2>0 ? l2/1024 : -1) << " KB\n"; typedef internal::gebp_traits<Scalar,Scalar> Traits; std::cout << "Register blocking = " << Traits::mr << " x " << Traits::nr << "\n"; int rep = 1; // number of repetitions per try int tries = 2; // number of tries, we keep the best int s = 2048; int cache_size = -1; bool need_help = false; for (int i=1; i<argc; ++i) { if(argv[i][0]=='s') s = atoi(argv[i]+1); else if(argv[i][0]=='c') cache_size = atoi(argv[i]+1); else if(argv[i][0]=='t') tries = atoi(argv[i]+1); else if(argv[i][0]=='p') rep = atoi(argv[i]+1); else need_help = true; } if(need_help) { std::cout << argv[0] << " s<matrix size> c<cache size> t<nb tries> p<nb repeats>\n"; return 1; } if(cache_size>0) setCpuCacheSizes(cache_size,96*cache_size); int m = s; int n = s; int p = s; A a(m,p); a.setRandom(); B b(p,n); b.setRandom(); C c(m,n); c.setOnes(); C rc = c; std::cout << "Matrix sizes = " << m << "x" << p << " * " << p << "x" << n << "\n"; std::ptrdiff_t mc(m), nc(n), kc(p); internal::computeProductBlockingSizes<Scalar,Scalar>(kc, mc, nc); std::cout << "blocking size (mc x kc) = " << mc << " x " << kc << "\n"; C r = c; // check the parallel product is correct #if defined EIGEN_HAS_OPENMP int procs = omp_get_max_threads(); if(procs>1) { #ifdef HAVE_BLAS blas_gemm(a,b,r); #else omp_set_num_threads(1); r.noalias() += a * b; omp_set_num_threads(procs); #endif c.noalias() += a * b; if(!r.isApprox(c)) std::cerr << "Warning, your parallel product is crap!\n\n"; } #elif defined HAVE_BLAS blas_gemm(a,b,r); c.noalias() += a * b; if(!r.isApprox(c)) std::cerr << "Warning, your product is crap!\n\n"; #else gemm(a,b,c); r.noalias() += a.cast<Scalar>() * b.cast<Scalar>(); if(!r.isApprox(c)) std::cerr << "Warning, your product is crap!\n\n"; #endif #ifdef HAVE_BLAS BenchTimer tblas; c = rc; BENCH(tblas, tries, rep, blas_gemm(a,b,c)); std::cout << "blas cpu " << tblas.best(CPU_TIMER)/rep << "s \t" << (double(m)*n*p*rep*2/tblas.best(CPU_TIMER))*1e-9 << " GFLOPS \t(" << tblas.total(CPU_TIMER) << "s)\n"; std::cout << "blas real " << tblas.best(REAL_TIMER)/rep << "s \t" << (double(m)*n*p*rep*2/tblas.best(REAL_TIMER))*1e-9 << " GFLOPS \t(" << tblas.total(REAL_TIMER) << "s)\n"; #endif BenchTimer tmt; c = rc; BENCH(tmt, tries, rep, gemm(a,b,c)); std::cout << "eigen cpu " << tmt.best(CPU_TIMER)/rep << "s \t" << (double(m)*n*p*rep*2/tmt.best(CPU_TIMER))*1e-9 << " GFLOPS \t(" << tmt.total(CPU_TIMER) << "s)\n"; std::cout << "eigen real " << tmt.best(REAL_TIMER)/rep << "s \t" << (double(m)*n*p*rep*2/tmt.best(REAL_TIMER))*1e-9 << " GFLOPS \t(" << tmt.total(REAL_TIMER) << "s)\n"; #ifdef EIGEN_HAS_OPENMP if(procs>1) { BenchTimer tmono; omp_set_num_threads(1); Eigen::internal::setNbThreads(1); c = rc; BENCH(tmono, tries, rep, gemm(a,b,c)); std::cout << "eigen mono cpu " << tmono.best(CPU_TIMER)/rep << "s \t" << (double(m)*n*p*rep*2/tmono.best(CPU_TIMER))*1e-9 << " GFLOPS \t(" << tmono.total(CPU_TIMER) << "s)\n"; std::cout << "eigen mono real " << tmono.best(REAL_TIMER)/rep << "s \t" << (double(m)*n*p*rep*2/tmono.best(REAL_TIMER))*1e-9 << " GFLOPS \t(" << tmono.total(REAL_TIMER) << "s)\n"; std::cout << "mt speed up x" << tmono.best(CPU_TIMER) / tmt.best(REAL_TIMER) << " => " << (100.0*tmono.best(CPU_TIMER) / tmt.best(REAL_TIMER))/procs << "%\n"; } #endif #ifdef DECOUPLED if((NumTraits<A::Scalar>::IsComplex) && (NumTraits<B::Scalar>::IsComplex)) { M ar(m,p); ar.setRandom(); M ai(m,p); ai.setRandom(); M br(p,n); br.setRandom(); M bi(p,n); bi.setRandom(); M cr(m,n); cr.setRandom(); M ci(m,n); ci.setRandom(); BenchTimer t; BENCH(t, tries, rep, matlab_cplx_cplx(ar,ai,br,bi,cr,ci)); std::cout << "\"matlab\" cpu " << t.best(CPU_TIMER)/rep << "s \t" << (double(m)*n*p*rep*2/t.best(CPU_TIMER))*1e-9 << " GFLOPS \t(" << t.total(CPU_TIMER) << "s)\n"; std::cout << "\"matlab\" real " << t.best(REAL_TIMER)/rep << "s \t" << (double(m)*n*p*rep*2/t.best(REAL_TIMER))*1e-9 << " GFLOPS \t(" << t.total(REAL_TIMER) << "s)\n"; } if((!NumTraits<A::Scalar>::IsComplex) && (NumTraits<B::Scalar>::IsComplex)) { M a(m,p); a.setRandom(); M br(p,n); br.setRandom(); M bi(p,n); bi.setRandom(); M cr(m,n); cr.setRandom(); M ci(m,n); ci.setRandom(); BenchTimer t; BENCH(t, tries, rep, matlab_real_cplx(a,br,bi,cr,ci)); std::cout << "\"matlab\" cpu " << t.best(CPU_TIMER)/rep << "s \t" << (double(m)*n*p*rep*2/t.best(CPU_TIMER))*1e-9 << " GFLOPS \t(" << t.total(CPU_TIMER) << "s)\n"; std::cout << "\"matlab\" real " << t.best(REAL_TIMER)/rep << "s \t" << (double(m)*n*p*rep*2/t.best(REAL_TIMER))*1e-9 << " GFLOPS \t(" << t.total(REAL_TIMER) << "s)\n"; } if((NumTraits<A::Scalar>::IsComplex) && (!NumTraits<B::Scalar>::IsComplex)) { M ar(m,p); ar.setRandom(); M ai(m,p); ai.setRandom(); M b(p,n); b.setRandom(); M cr(m,n); cr.setRandom(); M ci(m,n); ci.setRandom(); BenchTimer t; BENCH(t, tries, rep, matlab_cplx_real(ar,ai,b,cr,ci)); std::cout << "\"matlab\" cpu " << t.best(CPU_TIMER)/rep << "s \t" << (double(m)*n*p*rep*2/t.best(CPU_TIMER))*1e-9 << " GFLOPS \t(" << t.total(CPU_TIMER) << "s)\n"; std::cout << "\"matlab\" real " << t.best(REAL_TIMER)/rep << "s \t" << (double(m)*n*p*rep*2/t.best(REAL_TIMER))*1e-9 << " GFLOPS \t(" << t.total(REAL_TIMER) << "s)\n"; } #endif return 0; }
// g++-4.4 bench_gemm.cpp -I .. -O2 -DNDEBUG -lrt -fopenmp && OMP_NUM_THREADS=2 ./a.out // icpc bench_gemm.cpp -I .. -O3 -DNDEBUG -lrt -openmp && OMP_NUM_THREADS=2 ./a.out #include <iostream> #include <Eigen/Core> #include <bench/BenchTimer.h> using namespace std; using namespace Eigen; #ifndef SCALAR // #define SCALAR std::complex<float> #define SCALAR float #endif typedef SCALAR Scalar; typedef NumTraits<Scalar>::Real RealScalar; typedef Matrix<RealScalar,Dynamic,Dynamic> A; typedef Matrix</*Real*/Scalar,Dynamic,Dynamic> B; typedef Matrix<Scalar,Dynamic,Dynamic> C; typedef Matrix<RealScalar,Dynamic,Dynamic> M; #ifdef HAVE_BLAS extern "C" { #include <Eigen/src/misc/blas.h> } static float fone = 1; static float fzero = 0; static double done = 1; static double szero = 0; static std::complex<float> cfone = 1; static std::complex<float> cfzero = 0; static std::complex<double> cdone = 1; static std::complex<double> cdzero = 0; static char notrans = 'N'; static char trans = 'T'; static char nonunit = 'N'; static char lower = 'L'; static char right = 'R'; static int intone = 1; void blas_gemm(const MatrixXf& a, const MatrixXf& b, MatrixXf& c) { int M = c.rows(); int N = c.cols(); int K = a.cols(); int lda = a.rows(); int ldb = b.rows(); int ldc = c.rows(); sgemm_(&notrans,&notrans,&M,&N,&K,&fone, const_cast<float*>(a.data()),&lda, const_cast<float*>(b.data()),&ldb,&fone, c.data(),&ldc); } EIGEN_DONT_INLINE void blas_gemm(const MatrixXd& a, const MatrixXd& b, MatrixXd& c) { int M = c.rows(); int N = c.cols(); int K = a.cols(); int lda = a.rows(); int ldb = b.rows(); int ldc = c.rows(); dgemm_(&notrans,&notrans,&M,&N,&K,&done, const_cast<double*>(a.data()),&lda, const_cast<double*>(b.data()),&ldb,&done, c.data(),&ldc); } void blas_gemm(const MatrixXcf& a, const MatrixXcf& b, MatrixXcf& c) { int M = c.rows(); int N = c.cols(); int K = a.cols(); int lda = a.rows(); int ldb = b.rows(); int ldc = c.rows(); cgemm_(&notrans,&notrans,&M,&N,&K,(float*)&cfone, const_cast<float*>((const float*)a.data()),&lda, const_cast<float*>((const float*)b.data()),&ldb,(float*)&cfone, (float*)c.data(),&ldc); } void blas_gemm(const MatrixXcd& a, const MatrixXcd& b, MatrixXcd& c) { int M = c.rows(); int N = c.cols(); int K = a.cols(); int lda = a.rows(); int ldb = b.rows(); int ldc = c.rows(); zgemm_(&notrans,&notrans,&M,&N,&K,(double*)&cdone, const_cast<double*>((const double*)a.data()),&lda, const_cast<double*>((const double*)b.data()),&ldb,(double*)&cdone, (double*)c.data(),&ldc); } #endif void matlab_cplx_cplx(const M& ar, const M& ai, const M& br, const M& bi, M& cr, M& ci) { cr.noalias() += ar * br; cr.noalias() -= ai * bi; ci.noalias() += ar * bi; ci.noalias() += ai * br; } void matlab_real_cplx(const M& a, const M& br, const M& bi, M& cr, M& ci) { cr.noalias() += a * br; ci.noalias() += a * bi; } void matlab_cplx_real(const M& ar, const M& ai, const M& b, M& cr, M& ci) { cr.noalias() += ar * b; ci.noalias() += ai * b; } template<typename A, typename B, typename C> EIGEN_DONT_INLINE void gemm(const A& a, const B& b, C& c) { c.noalias() += a * b; } int main(int argc, char ** argv) { std::ptrdiff_t l1 = internal::queryL1CacheSize(); std::ptrdiff_t l2 = internal::queryTopLevelCacheSize(); std::cout << "L1 cache size = " << (l1>0 ? l1/1024 : -1) << " KB\n"; std::cout << "L2/L3 cache size = " << (l2>0 ? l2/1024 : -1) << " KB\n"; typedef internal::gebp_traits<Scalar,Scalar> Traits; std::cout << "Register blocking = " << Traits::mr << " x " << Traits::nr << "\n"; int rep = 1; // number of repetitions per try int tries = 2; // number of tries, we keep the best int s = 2048; int cache_size = -1; bool need_help = false; for (int i=1; i<argc; ++i) { if(argv[i][0]=='s') s = atoi(argv[i]+1); else if(argv[i][0]=='c') cache_size = atoi(argv[i]+1); else if(argv[i][0]=='t') tries = atoi(argv[i]+1); else if(argv[i][0]=='p') rep = atoi(argv[i]+1); else need_help = true; } if(need_help) { std::cout << argv[0] << " s<matrix size> c<cache size> t<nb tries> p<nb repeats>\n"; return 1; } if(cache_size>0) setCpuCacheSizes(cache_size,96*cache_size); int m = s; int n = s; int p = s; A a(m,p); a.setRandom(); B b(p,n); b.setRandom(); C c(m,n); c.setOnes(); C rc = c; std::cout << "Matrix sizes = " << m << "x" << p << " * " << p << "x" << n << "\n"; std::ptrdiff_t mc(m), nc(n), kc(p); internal::computeProductBlockingSizes<Scalar,Scalar>(kc, mc, nc); std::cout << "blocking size (mc x kc) = " << mc << " x " << kc << "\n"; C r = c; // check the parallel product is correct #if defined EIGEN_HAS_OPENMP int procs = omp_get_max_threads(); if(procs>1) { #ifdef HAVE_BLAS blas_gemm(a,b,r); #else omp_set_num_threads(1); r.noalias() += a * b; omp_set_num_threads(procs); #endif c.noalias() += a * b; if(!r.isApprox(c)) std::cerr << "Warning, your parallel product is crap!\n\n"; } #elif defined HAVE_BLAS blas_gemm(a,b,r); c.noalias() += a * b; if(!r.isApprox(c)) std::cerr << "Warning, your product is crap!\n\n"; #else gemm(a,b,c); r.noalias() += a.cast<Scalar>() * b.cast<Scalar>(); if(!r.isApprox(c)) std::cerr << "Warning, your product is crap!\n\n"; #endif #ifdef HAVE_BLAS BenchTimer tblas; c = rc; BENCH(tblas, tries, rep, blas_gemm(a,b,c)); std::cout << "blas cpu " << tblas.best(CPU_TIMER)/rep << "s \t" << (double(m)*n*p*rep*2/tblas.best(CPU_TIMER))*1e-9 << " GFLOPS \t(" << tblas.total(CPU_TIMER) << "s)\n"; std::cout << "blas real " << tblas.best(REAL_TIMER)/rep << "s \t" << (double(m)*n*p*rep*2/tblas.best(REAL_TIMER))*1e-9 << " GFLOPS \t(" << tblas.total(REAL_TIMER) << "s)\n"; #endif BenchTimer tmt; c = rc; BENCH(tmt, tries, rep, gemm(a,b,c)); std::cout << "eigen cpu " << tmt.best(CPU_TIMER)/rep << "s \t" << (double(m)*n*p*rep*2/tmt.best(CPU_TIMER))*1e-9 << " GFLOPS \t(" << tmt.total(CPU_TIMER) << "s)\n"; std::cout << "eigen real " << tmt.best(REAL_TIMER)/rep << "s \t" << (double(m)*n*p*rep*2/tmt.best(REAL_TIMER))*1e-9 << " GFLOPS \t(" << tmt.total(REAL_TIMER) << "s)\n"; #ifdef EIGEN_HAS_OPENMP if(procs>1) { BenchTimer tmono; omp_set_num_threads(1); Eigen::internal::setNbThreads(1); c = rc; BENCH(tmono, tries, rep, gemm(a,b,c)); std::cout << "eigen mono cpu " << tmono.best(CPU_TIMER)/rep << "s \t" << (double(m)*n*p*rep*2/tmono.best(CPU_TIMER))*1e-9 << " GFLOPS \t(" << tmono.total(CPU_TIMER) << "s)\n"; std::cout << "eigen mono real " << tmono.best(REAL_TIMER)/rep << "s \t" << (double(m)*n*p*rep*2/tmono.best(REAL_TIMER))*1e-9 << " GFLOPS \t(" << tmono.total(REAL_TIMER) << "s)\n"; std::cout << "mt speed up x" << tmono.best(CPU_TIMER) / tmt.best(REAL_TIMER) << " => " << (100.0*tmono.best(CPU_TIMER) / tmt.best(REAL_TIMER))/procs << "%\n"; } #endif #ifdef DECOUPLED if((NumTraits<A::Scalar>::IsComplex) && (NumTraits<B::Scalar>::IsComplex)) { M ar(m,p); ar.setRandom(); M ai(m,p); ai.setRandom(); M br(p,n); br.setRandom(); M bi(p,n); bi.setRandom(); M cr(m,n); cr.setRandom(); M ci(m,n); ci.setRandom(); BenchTimer t; BENCH(t, tries, rep, matlab_cplx_cplx(ar,ai,br,bi,cr,ci)); std::cout << "\"matlab\" cpu " << t.best(CPU_TIMER)/rep << "s \t" << (double(m)*n*p*rep*2/t.best(CPU_TIMER))*1e-9 << " GFLOPS \t(" << t.total(CPU_TIMER) << "s)\n"; std::cout << "\"matlab\" real " << t.best(REAL_TIMER)/rep << "s \t" << (double(m)*n*p*rep*2/t.best(REAL_TIMER))*1e-9 << " GFLOPS \t(" << t.total(REAL_TIMER) << "s)\n"; } if((!NumTraits<A::Scalar>::IsComplex) && (NumTraits<B::Scalar>::IsComplex)) { M a(m,p); a.setRandom(); M br(p,n); br.setRandom(); M bi(p,n); bi.setRandom(); M cr(m,n); cr.setRandom(); M ci(m,n); ci.setRandom(); BenchTimer t; BENCH(t, tries, rep, matlab_real_cplx(a,br,bi,cr,ci)); std::cout << "\"matlab\" cpu " << t.best(CPU_TIMER)/rep << "s \t" << (double(m)*n*p*rep*2/t.best(CPU_TIMER))*1e-9 << " GFLOPS \t(" << t.total(CPU_TIMER) << "s)\n"; std::cout << "\"matlab\" real " << t.best(REAL_TIMER)/rep << "s \t" << (double(m)*n*p*rep*2/t.best(REAL_TIMER))*1e-9 << " GFLOPS \t(" << t.total(REAL_TIMER) << "s)\n"; } if((NumTraits<A::Scalar>::IsComplex) && (!NumTraits<B::Scalar>::IsComplex)) { M ar(m,p); ar.setRandom(); M ai(m,p); ai.setRandom(); M b(p,n); b.setRandom(); M cr(m,n); cr.setRandom(); M ci(m,n); ci.setRandom(); BenchTimer t; BENCH(t, tries, rep, matlab_cplx_real(ar,ai,b,cr,ci)); std::cout << "\"matlab\" cpu " << t.best(CPU_TIMER)/rep << "s \t" << (double(m)*n*p*rep*2/t.best(CPU_TIMER))*1e-9 << " GFLOPS \t(" << t.total(CPU_TIMER) << "s)\n"; std::cout << "\"matlab\" real " << t.best(REAL_TIMER)/rep << "s \t" << (double(m)*n*p*rep*2/t.best(REAL_TIMER))*1e-9 << " GFLOPS \t(" << t.total(REAL_TIMER) << "s)\n"; } #endif return 0; }
fix include path
fix include path
C++
bsd-3-clause
robustrobotics/eigen,robustrobotics/eigen,robustrobotics/eigen,robustrobotics/eigen
ce43ae711352cb19e53a1d196a623c70e0e0b8b2
src/tthreadapplicationserver.cpp
src/tthreadapplicationserver.cpp
/* Copyright (c) 2010-2013, AOYAMA Kazuharu * All rights reserved. * * This software may be used and distributed according to the terms of * the New BSD License, which is incorporated herein by reference. */ #include <TThreadApplicationServer> #include <TWebApplication> #include <TAppSettings> #include <TActionThread> #include "tsystemglobal.h" /*! \class TThreadApplicationServer \brief The TThreadApplicationServer class provides functionality common to an web application server for thread. */ TThreadApplicationServer::TThreadApplicationServer(int listeningSocket, QObject *parent) : QTcpServer(parent), TApplicationServerBase(), listenSocket(listeningSocket), maxThreads(0) { QString mpm = Tf::appSettings()->value(Tf::MultiProcessingModule).toString().toLower(); maxThreads = Tf::appSettings()->readValue(QLatin1String("MPM.") + mpm + ".MaxThreadsPerAppServer").toInt(); if (maxThreads == 0) { maxThreads = Tf::appSettings()->readValue(QLatin1String("MPM.") + mpm + ".MaxServers", "128").toInt(); } tSystemDebug("MaxThreads: %d", maxThreads); Q_ASSERT(Tf::app()->multiProcessingModule() == TWebApplication::Thread); } TThreadApplicationServer::~TThreadApplicationServer() { } bool TThreadApplicationServer::start() { if (isListening()) { return true; } if (listenSocket <= 0 || !setSocketDescriptor(listenSocket)) { tSystemError("Failed to set socket descriptor: %d", listenSocket); return false; } loadLibraries(); TStaticInitializeThread::exec(); return true; } void TThreadApplicationServer::stop() { if (!isListening()) { return; } QTcpServer::close(); listenSocket = 0; TActionThread::waitForAllDone(10000); TStaticReleaseThread::exec(); } void TThreadApplicationServer::incomingConnection( #if QT_VERSION >= 0x050000 qintptr socketDescriptor) #else int socketDescriptor) #endif { for (;;) { tSystemDebug("incomingConnection sd:%d thread count:%d max:%d", socketDescriptor, TActionThread::threadCount(), maxThreads); if (TActionThread::threadCount() < maxThreads) { TActionThread *thread = new TActionThread(socketDescriptor); connect(thread, SIGNAL(finished()), thread, SLOT(deleteLater())); thread->start(); break; } Tf::msleep(1); qApp->processEvents(QEventLoop::ExcludeSocketNotifiers); } }
/* Copyright (c) 2010-2013, AOYAMA Kazuharu * All rights reserved. * * This software may be used and distributed according to the terms of * the New BSD License, which is incorporated herein by reference. */ #include <TThreadApplicationServer> #include <TWebApplication> #include <TAppSettings> #include <TActionThread> #include "tsystemglobal.h" /*! \class TThreadApplicationServer \brief The TThreadApplicationServer class provides functionality common to an web application server for thread. */ TThreadApplicationServer::TThreadApplicationServer(int listeningSocket, QObject *parent) : QTcpServer(parent), TApplicationServerBase(), listenSocket(listeningSocket), maxThreads(0) { QString mpm = Tf::appSettings()->value(Tf::MultiProcessingModule).toString().toLower(); maxThreads = Tf::appSettings()->readValue(QLatin1String("MPM.") + mpm + ".MaxThreadsPerAppServer").toInt(); if (maxThreads == 0) { maxThreads = Tf::appSettings()->readValue(QLatin1String("MPM.") + mpm + ".MaxServers", "128").toInt(); } tSystemDebug("MaxThreads: %d", maxThreads); Q_ASSERT(Tf::app()->multiProcessingModule() == TWebApplication::Thread); } TThreadApplicationServer::~TThreadApplicationServer() { } bool TThreadApplicationServer::start() { if (isListening()) { return true; } if (listenSocket <= 0 || !setSocketDescriptor(listenSocket)) { tSystemError("Failed to set socket descriptor: %d", listenSocket); return false; } loadLibraries(); TStaticInitializeThread::exec(); return true; } void TThreadApplicationServer::stop() { if (!isListening()) { return; } QTcpServer::close(); listenSocket = 0; TActionThread::waitForAllDone(10000); TStaticReleaseThread::exec(); } void TThreadApplicationServer::incomingConnection( #if QT_VERSION >= 0x050000 qintptr socketDescriptor) #else int socketDescriptor) #endif { for (;;) { tSystemDebug("incomingConnection sd:%lld thread count:%d max:%d", socketDescriptor, TActionThread::threadCount(), maxThreads); if (TActionThread::threadCount() < maxThreads) { TActionThread *thread = new TActionThread(socketDescriptor); connect(thread, SIGNAL(finished()), thread, SLOT(deleteLater())); thread->start(); break; } Tf::msleep(1); qApp->processEvents(QEventLoop::ExcludeSocketNotifiers); } }
fix compilation warnings.
fix compilation warnings.
C++
bsd-3-clause
hks2002/treefrog-framework,gonboy/treefrog-framework,hks2002/treefrog-framework,AmiArt/treefrog-framework,AmiArt/treefrog-framework,froglogic/treefrog-framework,AmiArt/treefrog-framework,skipbit/treefrog-framework,treefrogframework/treefrog-framework,treefrogframework/treefrog-framework,hks2002/treefrog-framework,froglogic/treefrog-framework,skipbit/treefrog-framework,Akhilesh05/treefrog-framework,treefrogframework/treefrog-framework,Akhilesh05/treefrog-framework,gonboy/treefrog-framework,skipbit/treefrog-framework,treefrogframework/treefrog-framework,ThomasGueldner/treefrog-framework,froglogic/treefrog-framework,AmiArt/treefrog-framework,treefrogframework/treefrog-framework,hks2002/treefrog-framework,ThomasGueldner/treefrog-framework,hks2002/treefrog-framework,Akhilesh05/treefrog-framework,ThomasGueldner/treefrog-framework,gonboy/treefrog-framework,gonboy/treefrog-framework,ThomasGueldner/treefrog-framework,AmiArt/treefrog-framework,skipbit/treefrog-framework,gonboy/treefrog-framework,ThomasGueldner/treefrog-framework,Akhilesh05/treefrog-framework,froglogic/treefrog-framework,skipbit/treefrog-framework,froglogic/treefrog-framework
c559b89f4bf74554652bc4ddf2f8620c992a0ca7
apps/common/sg/common/Light.cpp
apps/common/sg/common/Light.cpp
// ======================================================================== // // Copyright 2009-2017 Intel Corporation // // // // 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 "sg/common/Light.h" namespace ospray { namespace sg { Light::Light() { setValue((OSPLight)nullptr); } Light::Light(const std::string &type) : Light() { this->type = type; } void Light::preCommit(RenderContext &ctx) { if (!valueAs<OSPLight>()) setValue(ospNewLight(ctx.ospRenderer, type.c_str())); } void Light::postCommit(RenderContext &) { ospCommit(valueAs<OSPLight>()); } std::string Light::toString() const { return "ospray::sg::Light<" + type + ">"; } AmbientLight::AmbientLight() : Light("AmbientLight") { createChild("color", "vec3f", vec3f(.7f,.8f,1.f), NodeFlags::required | NodeFlags::valid_min_max | NodeFlags::gui_color).setMinMax(vec3f(0), vec3f(1)); createChild("intensity", "float", 0.2f, NodeFlags::required | NodeFlags::valid_min_max | NodeFlags::gui_slider).setMinMax(0.f,12.f); } DirectionalLight::DirectionalLight() : Light("DirectionalLight") { createChild("direction", "vec3f", vec3f(-.3,.2,.4), NodeFlags::required | NodeFlags::gui_slider).setMinMax(vec3f(-1), vec3f(1)); createChild("color", "vec3f", vec3f(1.f), NodeFlags::required | NodeFlags::valid_min_max | NodeFlags::gui_color).setMinMax(vec3f(0), vec3f(1)); createChild("intensity", "float", 3.f, NodeFlags::required | NodeFlags::valid_min_max | NodeFlags::gui_slider).setMinMax(0.f,12.f); createChild("angularDiameter", "float", 0.53f, NodeFlags::required | NodeFlags::valid_min_max | NodeFlags::gui_slider).setMinMax(0.f,4.f); } PointLight::PointLight() : Light("PointLight") { createChild("color", "vec3f", vec3f(1.f), NodeFlags::required | NodeFlags::valid_min_max | NodeFlags::gui_color).setMinMax(vec3f(0), vec3f(1)); createChild("position", "vec3f", vec3f(0.f), NodeFlags::required | NodeFlags::valid_min_max); createChild("intensity", "float", 3.f, NodeFlags::required | NodeFlags::valid_min_max | NodeFlags::gui_slider).setMinMax(0.f,999.f); createChild("radius", "float", 0.0f, NodeFlags::required | NodeFlags::valid_min_max | NodeFlags::gui_slider).setMinMax(0.f,4.f); } QuadLight::QuadLight() : Light("QuadLight") { createChild("color", "vec3f", vec3f(1.f), NodeFlags::required | NodeFlags::valid_min_max | NodeFlags::gui_color).setMinMax(vec3f(0), vec3f(1)); createChild("intensity", "float", 1.f, NodeFlags::required | NodeFlags::valid_min_max | NodeFlags::gui_slider).setMinMax(0.f,999.f); createChild("position", "vec3f", vec3f(0.f), NodeFlags::required | NodeFlags::valid_min_max); createChild("edge1", "vec3f", vec3f(0.f, 1.f, 0.f), NodeFlags::required | NodeFlags::valid_min_max); createChild("edge2", "vec3f", vec3f(0.f, 0.f, 1.f), NodeFlags::required | NodeFlags::valid_min_max); } HDRILight::HDRILight() : Light("hdri") { createChild("up", "vec3f", vec3f(0.f,1.f,0.f), NodeFlags::required | NodeFlags::valid_min_max).setMinMax(vec3f(-1), vec3f(1)); createChild("dir", "vec3f", vec3f(1.f,0.f,0.f), NodeFlags::required | NodeFlags::valid_min_max).setMinMax(vec3f(-1), vec3f(1)); createChild("intensity", "float", 0.3f, NodeFlags::required | NodeFlags::valid_min_max | NodeFlags::gui_slider).setMinMax(0.f,12.f); } void HDRILight::postCommit(RenderContext &ctx) { if (hasChild("map")) { ospSetObject(valueAs<OSPObject>(), "map", child("map").valueAs<OSPObject>()); } Light::postCommit(ctx); } bool HDRILight::computeValid() { if (hasChild("map") && child("map").valueAs<OSPObject>() != nullptr) return Node::computeValid(); else return false; } OSP_REGISTER_SG_NODE(Light); OSP_REGISTER_SG_NODE(DirectionalLight); OSP_REGISTER_SG_NODE(AmbientLight); OSP_REGISTER_SG_NODE(PointLight); OSP_REGISTER_SG_NODE(QuadLight); OSP_REGISTER_SG_NODE(HDRILight); } // ::ospray::sg } // ::ospray
// ======================================================================== // // Copyright 2009-2017 Intel Corporation // // // // 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 "sg/common/Light.h" namespace ospray { namespace sg { Light::Light() { setValue((OSPLight)nullptr); } Light::Light(const std::string &type) : Light() { this->type = type; } void Light::preCommit(RenderContext &ctx) { if (!valueAs<OSPLight>()) setValue(ospNewLight(ctx.ospRenderer, type.c_str())); } void Light::postCommit(RenderContext &) { ospCommit(valueAs<OSPLight>()); } std::string Light::toString() const { return "ospray::sg::Light<" + type + ">"; } AmbientLight::AmbientLight() : Light("AmbientLight") { createChild("color", "vec3f", vec3f(.7f,.8f,1.f), NodeFlags::required | NodeFlags::valid_min_max | NodeFlags::gui_color).setMinMax(vec3f(0), vec3f(1)); createChild("intensity", "float", 0.2f, NodeFlags::required | NodeFlags::valid_min_max | NodeFlags::gui_slider).setMinMax(0.f,12.f); } DirectionalLight::DirectionalLight() : Light("DirectionalLight") { createChild("direction", "vec3f", vec3f(-.3,.2,.4), NodeFlags::required | NodeFlags::gui_slider).setMinMax(vec3f(-1), vec3f(1)); createChild("color", "vec3f", vec3f(1.f), NodeFlags::required | NodeFlags::valid_min_max | NodeFlags::gui_color).setMinMax(vec3f(0), vec3f(1)); createChild("intensity", "float", 3.f, NodeFlags::required | NodeFlags::valid_min_max | NodeFlags::gui_slider).setMinMax(0.f,12.f); createChild("angularDiameter", "float", 0.53f, NodeFlags::required | NodeFlags::valid_min_max | NodeFlags::gui_slider).setMinMax(0.f,4.f); } PointLight::PointLight() : Light("PointLight") { createChild("color", "vec3f", vec3f(1.f), NodeFlags::required | NodeFlags::valid_min_max | NodeFlags::gui_color).setMinMax(vec3f(0), vec3f(1)); createChild("position", "vec3f", vec3f(0.f), NodeFlags::required | NodeFlags::valid_min_max); createChild("intensity", "float", 3.f, NodeFlags::required | NodeFlags::valid_min_max | NodeFlags::gui_slider).setMinMax(0.f,999.f); createChild("radius", "float", 0.0f, NodeFlags::required | NodeFlags::valid_min_max | NodeFlags::gui_slider).setMinMax(0.f,4.f); } QuadLight::QuadLight() : Light("QuadLight") { createChild("color", "vec3f", vec3f(1.f), NodeFlags::required | NodeFlags::valid_min_max | NodeFlags::gui_color).setMinMax(vec3f(0), vec3f(1)); createChild("intensity", "float", 1.f, NodeFlags::required | NodeFlags::valid_min_max | NodeFlags::gui_slider).setMinMax(0.f,999.f); createChild("position", "vec3f", vec3f(0.f), NodeFlags::required | NodeFlags::valid_min_max); createChild("edge1", "vec3f", vec3f(0.f, 1.f, 0.f), NodeFlags::required | NodeFlags::valid_min_max); createChild("edge2", "vec3f", vec3f(0.f, 0.f, 1.f), NodeFlags::required | NodeFlags::valid_min_max); } HDRILight::HDRILight() : Light("hdri") { createChild("up", "vec3f", vec3f(0.f,1.f,0.f), NodeFlags::required | NodeFlags::valid_min_max).setMinMax(vec3f(-1), vec3f(1)); createChild("dir", "vec3f", vec3f(1.f,0.f,0.f), NodeFlags::required | NodeFlags::valid_min_max).setMinMax(vec3f(-1), vec3f(1)); createChild("intensity", "float", 1.f, NodeFlags::required | NodeFlags::valid_min_max | NodeFlags::gui_slider).setMinMax(0.f,12.f); } void HDRILight::postCommit(RenderContext &ctx) { if (hasChild("map")) { ospSetObject(valueAs<OSPObject>(), "map", child("map").valueAs<OSPObject>()); } Light::postCommit(ctx); } bool HDRILight::computeValid() { if (hasChild("map") && child("map").valueAs<OSPObject>() != nullptr) return Node::computeValid(); else return false; } OSP_REGISTER_SG_NODE(Light); OSP_REGISTER_SG_NODE(DirectionalLight); OSP_REGISTER_SG_NODE(AmbientLight); OSP_REGISTER_SG_NODE(PointLight); OSP_REGISTER_SG_NODE(QuadLight); OSP_REGISTER_SG_NODE(HDRILight); } // ::ospray::sg } // ::ospray
set default HDRILight intensity to 1
set default HDRILight intensity to 1
C++
apache-2.0
ospray/OSPRay,ospray/OSPRay,wilsonCernWq/ospray,wilsonCernWq/ospray,ospray/OSPRay,wilsonCernWq/ospray,ospray/OSPRay
edb81852aea69548c7bf1c4d778d2c892520302d
src/usr/diag/prdf/prdfErrlUtil.H
src/usr/diag/prdf/prdfErrlUtil.H
/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/usr/diag/prdf/prdfErrlUtil.H $ */ /* */ /* IBM CONFIDENTIAL */ /* */ /* COPYRIGHT International Business Machines Corp. 2002,2013 */ /* */ /* p1 */ /* */ /* Object Code Only (OCO) source materials */ /* Licensed Internal Code Source Materials */ /* IBM HostBoot Licensed Internal Code */ /* */ /* The source code for this program is not published or otherwise */ /* divested of its trade secrets, irrespective of what has been */ /* deposited with the U.S. Copyright Office. */ /* */ /* Origin: 30 */ /* */ /* IBM_PROLOG_END_TAG */ #ifndef __prdfErrlUtil_H #define __prdfErrlUtil_H /** * @file prdfErrlUtil.H * @brief PRD error logging code specific to hostboot. * * This file contains the Processor Runtime Diagnostics error logging * related declarations specific to hostboot. */ #include <prdfEnums.H> /** * @brief create ErrlEntry in Hostboot */ /* This macro does not use the below FSP input parms: - i_etype : errlEventType - i_type : srciType - i_srcAttr : srcAttr - i_refCode : serviceCodes */ #define PRDF_CREATE_ERRL(io_errl, i_sev, i_etype, i_type, \ i_srcAttr, i_mid, i_refCode, i_reasonCode, \ i_user1 , i_user2, i_user3 , i_user4) \ io_errl = new ERRORLOG::ErrlEntry(ERRORLOG::i_sev, \ i_mid, \ i_reasonCode, \ PRDF_GET_UINT64_FROM_UINT32( \ i_user1, \ i_user2), \ PRDF_GET_UINT64_FROM_UINT32( \ i_user3, \ i_user4)) /** * @brief Add user data to the log */ #define PRDF_ADD_FFDC(io_errl, i_buf, i_size, i_ver, i_subsec) \ io_errl->addFFDC(PRDF_COMP_ID, i_buf, i_size, i_ver, i_subsec) /** * @brief Commit the log */ // FIXME:RTC: 65609 will address this issue. // hberr does not use i_actions for commit #define PRDF_COMMIT_ERRL(io_errl, i_actions) \ if(i_actions) {} \ errlCommit(io_errl, PRDF_COMP_ID) /** * @brief Collect component trace */ #define PRDF_COLLECT_TRACE(io_errl, i_max) \ io_errl->collectTrace(PRDF_COMP_NAME, i_max) /** * @brief Add a procedure ( software ) callout */ #define PRDF_ADD_PROCEDURE_CALLOUT(io_errl, i_priority, i_procedure) \ io_errl->addProcedureCallout((const HWAS::epubProcedureID)i_procedure, \ (const HWAS::callOutPriority)i_priority) /** * @brief Adds a software section to the log * mostly used as a stack call indicator */ // FIXME:RTC: 65609 will address this issue. // hberrl hasn't added this in yet so make it a no-op for now #define PRDF_ADD_SW_ERR(io_errl, i_rc, i_fileId, i_codeloc) /** * @brief Set the platform Log Id */ // FIXME:RTC: 65609 will address this issue. // hberrl doesn't have this setter method so make it a no-op for now #define PRDF_SET_PLID(io_errl, i_plid) /** * @brief Get the platform Log Id */ #define PRDF_GET_PLID(io_errl, o_plid) \ o_plid = io_errl->plid() /** * @brief Set 32 bit user defined return code */ // FIXME:RTC: 65609 will address this issue. // hberrl doesn't have this setter method so make it a no-op for now #define PRDF_SET_RC(io_errl, i_rc) /** * @brief Get 32 bit user defined return code */ // FIXME:RTC: 65609 will address this issue. // hberrl doesn't have this setter method so make it a no-op for now #define PRDF_GET_RC(io_errl, o_rc) /** * @brief Get reason code */ #define PRDF_GET_REASONCODE(io_errl, o_reasonCode) \ o_reasonCode = io_errl->reasonCode() /** * @brief get previously stored SRC * A special index ( 0 ) is used to a * ccess the primary src. */ // FIXME:RTC: 65609 will address this issue. // hberrl doesn't have this setter method so make it a no-op for now #define PRDF_GET_SRC(io_errl, o_src, i_idx) /** * @brief Determine if the src is terminating */ // FIXME:RTC: 65609 will address this issue. // hberrl doesn't have this setter method so make it a no-op for now #define PRDF_GET_TERM_SRC(io_errl, o_termSRC) /** * @brief write SRC termination flag */ // FIXME:RTC: 65609 will address this issue. // hberrl doesn't have this setter method so make it a no-op for now #define PRDF_SRC_WRITE_TERM_STATE_ON(io_errl, i_flags) // end Singleton macros /*--------------------------------------------------------------------*/ /* HW Deconfig Errl macros for Hostboot */ /*--------------------------------------------------------------------*/ // FIXME:RTC: 65609 will address this issue. // defines for enums that are not available in hostboot // these ERRL sevs are currently not supported in HB #define ERRL_SEV_PREDICTIVE ERRL_SEV_UNRECOVERABLE #define ERRL_SEV_RECOVERED ERRL_SEV_INFORMATIONAL /** * @brief function to create an error log. */ #define PRDF_HW_CREATE_ERRL(io_errl, \ i_sev, \ i_etype, \ i_type, \ i_srcAttr, \ i_mid, \ i_refCode, \ i_reasonCode, \ i_userData1, \ i_userData2, \ i_userData3, \ i_userData4, \ i_termFlag, \ i_pldCheck) \ PRDF_CREATE_ERRL(io_errl, i_sev, i_etype, i_type, \ i_srcAttr, i_mid, i_refCode, i_reasonCode, \ i_userData1, i_userData2, i_userData3, i_userData4) /** * @brief Add a procedure callout to an existing error log */ #define PRDF_HW_ADD_PROC_CALLOUT(i_procedure, \ i_priority, \ io_errl, \ i_severity) \ PRDF_ADD_PROCEDURE_CALLOUT(io_errl, i_priority, i_procedure) /** * @brief Error log interface to add a HW callout to an existing error log. * @note convert immediate deconfig to delayed deconfig in HB. */ #define PRDF_HW_ADD_CALLOUT(i_target, i_priority, \ i_deconfigState, i_gardState, \ io_errl, i_writeVpd, \ i_gardErrType, i_severity, i_hcdb_update) \ HWAS::DeconfigEnum deconfigState = \ (i_deconfigState == HWAS::DECONFIG ? \ HWAS::DELAYED_DECONFIG : i_deconfigState); \ io_errl->addHwCallout(i_target, \ (const HWAS::callOutPriority)i_priority, \ deconfigState, \ (const HWAS::GARD_ErrorType)i_gardErrType); \ (void)(i_hcdb_update) /** * @brief Process's pending deconfig and GARD service actions * and thencommits and deletes the error log. */ #define PRDF_HW_COMMIT_ERRL(io_sysTerm, io_errl, i_deferDeconfig, \ i_action, i_continue) \ io_sysTerm = false; \ PRDF_COMMIT_ERRL(io_errl, i_action); /** * @brief indicate whether an abort is active or not */ // FIXME:RTC: 65609 will address this issue. // not available in Hostboot? #define PRDF_ABORTING(o_abort) \ o_abort = false; /** * @brief Interface to request a Hardware Unit dump collection */ // FIXME:RTC: 65609 will address this issue. // need to implement in Hostboot #define PRDF_HWUDUMP( i_errl, i_content, i_huid ) \ SUCCESS #endif // __prdfErrlUtil_H
/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/usr/diag/prdf/prdfErrlUtil.H $ */ /* */ /* IBM CONFIDENTIAL */ /* */ /* COPYRIGHT International Business Machines Corp. 2002,2013 */ /* */ /* p1 */ /* */ /* Object Code Only (OCO) source materials */ /* Licensed Internal Code Source Materials */ /* IBM HostBoot Licensed Internal Code */ /* */ /* The source code for this program is not published or otherwise */ /* divested of its trade secrets, irrespective of what has been */ /* deposited with the U.S. Copyright Office. */ /* */ /* Origin: 30 */ /* */ /* IBM_PROLOG_END_TAG */ #ifndef __prdfErrlUtil_H #define __prdfErrlUtil_H /** * @file prdfErrlUtil.H * @brief PRD error logging code specific to hostboot. * * This file contains the Processor Runtime Diagnostics error logging * related declarations specific to hostboot. */ #include <prdfEnums.H> /** * @brief create ErrlEntry in Hostboot */ /* This macro does not use the below FSP input parms: - i_etype : errlEventType - i_type : srciType - i_srcAttr : srcAttr - i_refCode : serviceCodes */ #define PRDF_CREATE_ERRL(io_errl, i_sev, i_etype, i_type, \ i_srcAttr, i_mid, i_refCode, i_reasonCode, \ i_user1 , i_user2, i_user3 , i_user4) \ io_errl = new ERRORLOG::ErrlEntry(ERRORLOG::i_sev, \ i_mid, \ i_reasonCode, \ PRDF_GET_UINT64_FROM_UINT32( \ i_user1, \ i_user2), \ PRDF_GET_UINT64_FROM_UINT32( \ i_user3, \ i_user4)) /** * @brief Add user data to the log */ #define PRDF_ADD_FFDC(io_errl, i_buf, i_size, i_ver, i_subsec) \ io_errl->addFFDC(PRDF_COMP_ID, i_buf, i_size, i_ver, i_subsec) /** * @brief Commit the log */ // FIXME:RTC: 65609 will address this issue. // hberr does not use i_actions for commit #define PRDF_COMMIT_ERRL(io_errl, i_actions) \ if(i_actions) {} \ errlCommit(io_errl, PRDF_COMP_ID) /** * @brief Collect component trace */ #define PRDF_COLLECT_TRACE(io_errl, i_max) \ io_errl->collectTrace(PRDF_COMP_NAME, i_max) /** * @brief Add a procedure ( software ) callout */ #define PRDF_ADD_PROCEDURE_CALLOUT(io_errl, i_priority, i_procedure) \ io_errl->addProcedureCallout((const HWAS::epubProcedureID)i_procedure, \ (const HWAS::callOutPriority)i_priority) /** * @brief Adds a software section to the log * mostly used as a stack call indicator */ // FIXME:RTC: 65609 will address this issue. // hberrl hasn't added this in yet so make it a no-op for now #define PRDF_ADD_SW_ERR(io_errl, i_rc, i_fileId, i_codeloc) /** * @brief Set the platform Log Id */ // FIXME:RTC: 65609 will address this issue. // hberrl doesn't have this setter method so make it a no-op for now #define PRDF_SET_PLID(io_errl, i_plid) /** * @brief Get the platform Log Id */ #define PRDF_GET_PLID(io_errl, o_plid) \ o_plid = io_errl->plid() /** * @brief Set 32 bit user defined return code */ // FIXME:RTC: 65609 will address this issue. // hberrl doesn't have this setter method so make it a no-op for now #define PRDF_SET_RC(io_errl, i_rc) /** * @brief Get 32 bit user defined return code */ // FIXME:RTC: 65609 will address this issue. // hberrl doesn't have this setter method so make it a no-op for now #define PRDF_GET_RC(io_errl, o_rc) /** * @brief Get reason code */ #define PRDF_GET_REASONCODE(io_errl, o_reasonCode) \ o_reasonCode = io_errl->reasonCode() /** * @brief get previously stored SRC * A special index ( 0 ) is used to a * ccess the primary src. */ // FIXME:RTC: 65609 will address this issue. // hberrl doesn't have this setter method so make it a no-op for now #define PRDF_GET_SRC(io_errl, o_src, i_idx) /** * @brief Determine if the src is terminating */ // FIXME:RTC: 65609 will address this issue. // hberrl doesn't have this setter method so make it a no-op for now #define PRDF_GET_TERM_SRC(io_errl, o_termSRC) /** * @brief write SRC termination flag */ // FIXME:RTC: 65609 will address this issue. // hberrl doesn't have this setter method so make it a no-op for now #define PRDF_SRC_WRITE_TERM_STATE_ON(io_errl, i_flags) // end Singleton macros /*--------------------------------------------------------------------*/ /* HW Deconfig Errl macros for Hostboot */ /*--------------------------------------------------------------------*/ // FIXME:RTC: 65609 will address this issue. // defines for enums that are not available in hostboot // these ERRL sevs are currently not supported in HB #define ERRL_SEV_PREDICTIVE ERRL_SEV_UNRECOVERABLE #define ERRL_SEV_RECOVERED ERRL_SEV_INFORMATIONAL /** * @brief function to create an error log. */ #define PRDF_HW_CREATE_ERRL(io_errl, \ i_sev, \ i_etype, \ i_type, \ i_srcAttr, \ i_mid, \ i_refCode, \ i_reasonCode, \ i_userData1, \ i_userData2, \ i_userData3, \ i_userData4, \ i_termFlag, \ i_pldCheck) \ PRDF_CREATE_ERRL(io_errl, i_sev, i_etype, i_type, \ i_srcAttr, i_mid, i_refCode, i_reasonCode, \ i_userData1, i_userData2, i_userData3, i_userData4) /** * @brief Add a procedure callout to an existing error log */ #define PRDF_HW_ADD_PROC_CALLOUT(i_procedure, \ i_priority, \ io_errl, \ i_severity) \ PRDF_ADD_PROCEDURE_CALLOUT(io_errl, i_priority, i_procedure) /** * @brief Error log interface to add a HW callout to an existing error log. * @note convert immediate deconfig to delayed deconfig in HB. */ #define PRDF_HW_ADD_CALLOUT(i_target, i_priority, \ i_deconfigState, i_gardState, \ io_errl, i_writeVpd, \ i_gardErrType, i_severity, i_hcdb_update) \ HWAS::DeconfigEnum deconfigState = \ (i_deconfigState == HWAS::DECONFIG ? \ HWAS::DELAYED_DECONFIG : i_deconfigState); \ io_errl->addHwCallout(i_target, \ (const HWAS::callOutPriority)i_priority, \ deconfigState, \ (const HWAS::GARD_ErrorType)i_gardErrType); \ (void)(i_hcdb_update) /** * @brief Process's pending deconfig and GARD service actions * and thencommits and deletes the error log. */ #define PRDF_HW_COMMIT_ERRL(io_sysTerm, io_errl, i_deferDeconfig, \ i_action, i_continue) \ io_sysTerm = false; \ PRDF_COMMIT_ERRL(io_errl, i_action); /** * @brief indicate whether an abort is active or not */ // no-op in Hostboot #define PRDF_ABORTING(o_abort) \ o_abort = false; /** * @brief Interface to request a Hardware Unit dump collection */ // FIXME:RTC: 65609 will address this issue. // need to implement in Hostboot #define PRDF_HWUDUMP( i_errl, i_content, i_huid ) \ SUCCESS #endif // __prdfErrlUtil_H
add call to SvrError::isAbortInProgress
PRD: add call to SvrError::isAbortInProgress Change-Id: I8c8c58066350224db70cb9e8bc5d2280009fc32d RTC: 68681 Reviewed-on: http://gfw160.austin.ibm.com:8080/gerrit/6234 Tested-by: Jenkins Server Reviewed-by: Sachin Gupta <[email protected]> Reviewed-by: Prem Shanker Jha <[email protected]> Reviewed-by: A. Patrick Williams III <[email protected]> Reviewed-by: Zane Shelley <[email protected]> Reviewed-on: http://gfw160.austin.ibm.com:8080/gerrit/6492
C++
apache-2.0
open-power/hostboot,Over-enthusiastic/hostboot,open-power/hostboot,alvintpwang/hostboot,csmart/hostboot,alvintpwang/hostboot,open-power/hostboot,csmart/hostboot,alvintpwang/hostboot,open-power/hostboot,alvintpwang/hostboot,csmart/hostboot,csmart/hostboot,Over-enthusiastic/hostboot,Over-enthusiastic/hostboot,Over-enthusiastic/hostboot,csmart/hostboot,Over-enthusiastic/hostboot,open-power/hostboot,alvintpwang/hostboot
ad4c2c6e76050980b0001985161157d568e8e337
src/usr/fapi2/test/p10_hwtests.C
src/usr/fapi2/test/p10_hwtests.C
/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/usr/fapi2/test/p10_hwtests.C $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2016,2019 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* Licensed under the Apache License, Version 2.0 (the "License"); */ /* you may not use this file except in compliance with the License. */ /* You may obtain a copy of the License at */ /* */ /* http://www.apache.org/licenses/LICENSE-2.0 */ /* */ /* Unless required by applicable law or agreed to in writing, software */ /* distributed under the License is distributed on an "AS IS" BASIS, */ /* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */ /* implied. See the License for the specific language governing */ /* permissions and limitations under the License. */ /* */ /* IBM_PROLOG_END_TAG */ //------------------------------------------------------------------------------ /// @file p10_hwtests.C /// /// @brief These procedures test the fapi2 hw_access interfaces. //----------------------------------------------------------------------------- #include <cxxtest/TestSuite.H> #include <fapi2.H> #include <fapi2_hw_access.H> #include <errl/errlentry.H> #include <xscom/piberror.H> #include <plat_hwp_invoker.H> #include <p10_ringId.H> fapi2::ReturnCode p10_scomtest_getscom_fail( fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target) { fapi2::buffer<uint64_t> l_scomdata = 0; FAPI_INF("Entering p10_scomtest_getscom_fail..."); FAPI_INF("Do getscom on proc target"); FAPI_TRY(fapi2::getScom(i_target, 0x11223344, l_scomdata)); fapi_try_exit: FAPI_INF("Exiting p10_scomtest_getscom_fail..."); return fapi2::current_err; } fapi2::ReturnCode p10_scomtest_putscom_fail( fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target) { fapi2::buffer<uint64_t> l_scomdata = 0; FAPI_INF("Entering p10_scomtest_putscom_fail..."); FAPI_INF("Do getscom on proc target"); FAPI_TRY(fapi2::putScom(i_target, 0x22334455, l_scomdata)); fapi_try_exit: FAPI_INF("Exiting p10_scomtest_putscom_fail..."); return fapi2::current_err; } fapi2::ReturnCode p10_cfamtest_getcfam_fail( fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target) { fapi2::buffer<uint32_t> l_cfamdata = 0; FAPI_INF("Entering p10_cfamtest_getcfam_fail..."); FAPI_INF("Do getcfam on proc target"); FAPI_TRY(fapi2::getCfamRegister(i_target, 0x11223344, l_cfamdata)); fapi_try_exit: FAPI_INF("Exiting p10_cfamtest_getcfam_fail..."); return fapi2::current_err; } fapi2::ReturnCode p10_cfamtest_putcfam_fail( fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target) { fapi2::buffer<uint32_t> l_cfamdata = 0; FAPI_INF("Entering p10_cfamtest_putcfam_fail..."); FAPI_INF("Do getcfam on proc target"); FAPI_TRY(fapi2::putCfamRegister(i_target, 0x22334455, l_cfamdata)); fapi_try_exit: FAPI_INF("Exiting p10_cfamtest_putcfam_fail..."); return fapi2::current_err; } fapi2::ReturnCode p10_scomtest_getscom_pass( fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target) { fapi2::buffer<uint64_t> l_scomdata = 0; FAPI_INF("Entering p10_scomtest_getscom_pass..."); FAPI_INF("Do getscom on proc target"); FAPI_TRY(fapi2::getScom(i_target, 0x02010803, //CXA FIR Mask Register l_scomdata)); fapi_try_exit: FAPI_INF("Exiting p10_scomtest_getscom_pass..."); return fapi2::current_err; } fapi2::ReturnCode p10_scomtest_putscom_pass( fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target) { fapi2::buffer<uint64_t> l_scomdata = 0; FAPI_INF("Entering p10_scomtest_putscom_pass..."); FAPI_INF("Do getscom on proc target"); FAPI_TRY(fapi2::putScom(i_target, 0x02011803, //PBI CQ FIR Mask Register l_scomdata)); fapi_try_exit: FAPI_INF("Exiting p10_scomtest_putscom_pass..."); return fapi2::current_err; } fapi2::ReturnCode p10_cfamtest_getcfam_pass( fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target) { fapi2::buffer<uint32_t> l_cfamdata = 0; FAPI_INF("Entering p10_cfamtest_getcfam_pass..."); FAPI_INF("Do getcfam on proc target"); FAPI_TRY(fapi2::getCfamRegister(i_target, 0x1000, //DATA_0 from FSI2PIB l_cfamdata)); fapi_try_exit: FAPI_INF("Exiting p10_cfamtest_getcfam_pass..."); return fapi2::current_err; } fapi2::ReturnCode p10_cfamtest_putcfam_pass( fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target) { fapi2::buffer<uint32_t> l_cfamdata = 0; FAPI_INF("Entering p10_cfamtest_putcfam_pass..."); FAPI_INF("Do getcfam on proc target"); FAPI_TRY(fapi2::putCfamRegister(i_target, 0x1000, //DATA_0 from FSI2PIB l_cfamdata)); fapi_try_exit: FAPI_INF("Exiting p10_cfamtest_putcfam_pass..."); return fapi2::current_err; } fapi2::ReturnCode p10_ringtest_getring_fail( fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target) { fapi2::variable_buffer l_ringdata(64); FAPI_INF("Entering p10_ringtest_getring_fail..."); FAPI_INF("Do getring on proc target"); FAPI_TRY(fapi2::getRing(i_target, (scanRingId_t)(0x22334455), l_ringdata, fapi2::RING_MODE_HEADER_CHECK)); fapi_try_exit: FAPI_INF("Exiting p10_ringtest_getring_fail..."); return fapi2::current_err; } fapi2::ReturnCode p10_ringtest_modring_fail( fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target) { fapi2::variable_buffer l_ringdata; l_ringdata.resize(861); FAPI_INF("Entering p10_ringtest_modring_fail..."); FAPI_INF("Do modifyRing on proc target"); FAPI_TRY(fapi2::modifyRing(i_target, (scanRingId_t)0x22334455, l_ringdata, fapi2::CHIP_OP_MODIFY_MODE_OR, fapi2::RING_MODE_HEADER_CHECK)); fapi_try_exit: FAPI_INF("Exiting p10_ringtest_modring_fail..."); return fapi2::current_err; } fapi2::ReturnCode p10_ringtest_getring_pass( fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target) { fapi2::variable_buffer l_ringdata; l_ringdata.resize(861); FAPI_INF("Entering p10_ringtest_getring_pass..."); FAPI_INF("Do getring on proc target"); FAPI_TRY(fapi2::getRing(i_target, (scanRingId_t)0x00030088, l_ringdata, fapi2::RING_MODE_HEADER_CHECK)); fapi_try_exit: FAPI_INF("Exiting p10_ringtest_getring_pass..."); return fapi2::current_err; } fapi2::ReturnCode p10_ringtest_modring_pass( fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target) { uint32_t bit32_array[861]; uint32_t length; for (length = 0; length < 861; length++) { bit32_array[length] = length; } fapi2::variable_buffer l_ringdata(bit32_array, length, 32 * 861); FAPI_INF("Entering p10_ringtest_modring_pass..."); FAPI_INF("Do putring on proc target"); FAPI_TRY(fapi2::modifyRing(i_target, (scanRingId_t)0x00030088, l_ringdata, fapi2::CHIP_OP_MODIFY_MODE_OR, fapi2::RING_MODE_HEADER_CHECK)); fapi_try_exit: FAPI_INF("Exiting p10_ringtest_modring_pass..."); return fapi2::current_err; } fapi2::ReturnCode p10_platPutRingWRingId_t_pass() { //every test is displayed this way via FAPI_INF FAPI_INF("Entering p10_platPutRingWRingId_t_pass ..."); // get the master proc TARGETING::Target * l_procTest; TARGETING::targetService().masterProcChipTargetHandle(l_procTest); fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP> l_fapi2CpuTarget((l_procTest)); fapi2::ReturnCode l_status = fapi2::putRing(l_fapi2CpuTarget, n0_fure, fapi2::RING_MODE_SET_PULSE_NO_OPCG_COND); if(l_status!= fapi2::FAPI2_RC_SUCCESS) { TS_FAIL("p10_platPutRingWRingId_t_pass>> proc test - failed"); } return l_status; } fapi2::ReturnCode p10_opmodetest_ignorehwerr( fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target, uint8_t o_fail) { FAPI_INF("Entering p10_opmodetest_ignorehwerr..."); //Count the number of scoms we do so we can tell that we ran all of them. //Putting in this test so we know opMode isnt getting reset on FAPI_TRY uint8_t scomCount = 0; const uint8_t EXPECTED_NUMBER_OF_SCOMS = 4; do{ FAPI_INF("Setting opMode to IGNORE_HW_ERROR (0x1)"); fapi2::setOpMode(fapi2::IGNORE_HW_ERROR); fapi2::buffer<uint64_t> l_scomdata1 = 0xFF00FF00; fapi2::buffer<uint64_t> l_scomdata2 = 0xFF00FF00; fapi2::buffer<uint64_t> l_scomresult1 = 0x0; fapi2::buffer<uint64_t> l_scomresult2 = 0x0; FAPI_INF("Attempting 1st putScom, this should fail but because of opMode we skip the err"); FAPI_TRY(fapi2::putScom(i_target, 0xDEADBEEF, l_scomdata1)); scomCount++; FAPI_INF("Attempting 2nd putScom this should fail but because of opMode we skip the err"); FAPI_TRY(fapi2::getScom(i_target, 0xCABBABEF, l_scomdata2)); scomCount++; FAPI_INF("Attempting 1st getScom, this should fail but because of opMode we skip the err"); FAPI_TRY(fapi2::getScom(i_target, 0xDEADBEEF, l_scomresult1)); scomCount++; FAPI_INF("Attempting 2nd getScom, this should fail but because of opMode we skip the err"); FAPI_TRY(fapi2::getScom(i_target, 0xCABBABEF, l_scomresult2)); scomCount++; }while(0); fapi_try_exit: if(scomCount != EXPECTED_NUMBER_OF_SCOMS) { o_fail = 1; } FAPI_INF("Exiting p10_opmodetest_ignorehwerr..."); return fapi2::current_err; } fapi2::ReturnCode p10_piberrmask_masktest( fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target) { FAPI_INF("Entering p10_piberrmask_masktest..."); uint8_t completionCheck = 0; //Ideally we would like this test case to test errors 1-7 but // I am not sure if we can simulate some of the errors fapi2::buffer<uint64_t> l_scomdata = 0xFF00FF00; //Set the mask to ignore invalid address errors () fapi2::setPIBErrorMask(static_cast<uint8_t>(PIB::PIB_INVALID_ADDRESS)); //Attempt writing to a bad address // Avoid multicast error by not setting bit 1 FAPI_TRY(fapi2::putScom(i_target, 0xBADDBEEF, l_scomdata)); //try another scom, this time a get to make sure that // FAPI_TRY does not reset the mask // Avoid multicast error by not setting bit 1 FAPI_TRY(fapi2::getScom(i_target, 0xBADDBEEF, l_scomdata)); completionCheck = 1; fapi_try_exit: if(completionCheck != 1) { FAPI_ERR("Pib Err Mask is not removing errors and is causing FAPI_TRY to fail"); } FAPI_INF("Exiting p10_piberrmask_masktest..."); return fapi2::current_err; }
/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/usr/fapi2/test/p10_hwtests.C $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2016,2019 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* Licensed under the Apache License, Version 2.0 (the "License"); */ /* you may not use this file except in compliance with the License. */ /* You may obtain a copy of the License at */ /* */ /* http://www.apache.org/licenses/LICENSE-2.0 */ /* */ /* Unless required by applicable law or agreed to in writing, software */ /* distributed under the License is distributed on an "AS IS" BASIS, */ /* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */ /* implied. See the License for the specific language governing */ /* permissions and limitations under the License. */ /* */ /* IBM_PROLOG_END_TAG */ //------------------------------------------------------------------------------ /// @file p10_hwtests.C /// /// @brief These procedures test the fapi2 hw_access interfaces. //----------------------------------------------------------------------------- #include <cxxtest/TestSuite.H> #include <fapi2.H> #include <fapi2_hw_access.H> #include <errl/errlentry.H> #include <xscom/piberror.H> #include <plat_hwp_invoker.H> #include <p10_ringId.H> fapi2::ReturnCode p10_scomtest_getscom_fail( fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target) { fapi2::buffer<uint64_t> l_scomdata = 0; FAPI_INF("Entering p10_scomtest_getscom_fail..."); FAPI_INF("Do getscom on proc target"); FAPI_TRY(fapi2::getScom(i_target, 0x11223344, l_scomdata)); fapi_try_exit: FAPI_INF("Exiting p10_scomtest_getscom_fail..."); return fapi2::current_err; } fapi2::ReturnCode p10_scomtest_putscom_fail( fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target) { fapi2::buffer<uint64_t> l_scomdata = 0; FAPI_INF("Entering p10_scomtest_putscom_fail..."); FAPI_INF("Do getscom on proc target"); FAPI_TRY(fapi2::putScom(i_target, 0x22334455, l_scomdata)); fapi_try_exit: FAPI_INF("Exiting p10_scomtest_putscom_fail..."); return fapi2::current_err; } fapi2::ReturnCode p10_cfamtest_getcfam_fail( fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target) { fapi2::buffer<uint32_t> l_cfamdata = 0; FAPI_INF("Entering p10_cfamtest_getcfam_fail..."); FAPI_INF("Do getcfam on proc target"); FAPI_TRY(fapi2::getCfamRegister(i_target, 0x11223344, l_cfamdata)); fapi_try_exit: FAPI_INF("Exiting p10_cfamtest_getcfam_fail..."); return fapi2::current_err; } fapi2::ReturnCode p10_cfamtest_putcfam_fail( fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target) { fapi2::buffer<uint32_t> l_cfamdata = 0; FAPI_INF("Entering p10_cfamtest_putcfam_fail..."); FAPI_INF("Do getcfam on proc target"); FAPI_TRY(fapi2::putCfamRegister(i_target, 0x22334455, l_cfamdata)); fapi_try_exit: FAPI_INF("Exiting p10_cfamtest_putcfam_fail..."); return fapi2::current_err; } fapi2::ReturnCode p10_scomtest_getscom_pass( fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target) { fapi2::buffer<uint64_t> l_scomdata = 0; FAPI_INF("Entering p10_scomtest_getscom_pass..."); FAPI_INF("Do getscom on proc target"); FAPI_TRY(fapi2::getScom(i_target, 0x02010803, //CXA FIR Mask Register l_scomdata)); fapi_try_exit: FAPI_INF("Exiting p10_scomtest_getscom_pass..."); return fapi2::current_err; } fapi2::ReturnCode p10_scomtest_putscom_pass( fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target) { fapi2::buffer<uint64_t> l_scomdata = 0; FAPI_INF("Entering p10_scomtest_putscom_pass..."); FAPI_INF("Do putscom on proc target"); FAPI_TRY(fapi2::putScom(i_target, 0x02010C03, //PBI CQ FIR Mask Register l_scomdata)); fapi_try_exit: FAPI_INF("Exiting p10_scomtest_putscom_pass..."); return fapi2::current_err; } fapi2::ReturnCode p10_cfamtest_getcfam_pass( fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target) { fapi2::buffer<uint32_t> l_cfamdata = 0; FAPI_INF("Entering p10_cfamtest_getcfam_pass..."); FAPI_INF("Do getcfam on proc target"); FAPI_TRY(fapi2::getCfamRegister(i_target, 0x1000, //DATA_0 from FSI2PIB l_cfamdata)); fapi_try_exit: FAPI_INF("Exiting p10_cfamtest_getcfam_pass..."); return fapi2::current_err; } fapi2::ReturnCode p10_cfamtest_putcfam_pass( fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target) { fapi2::buffer<uint32_t> l_cfamdata = 0; FAPI_INF("Entering p10_cfamtest_putcfam_pass..."); FAPI_INF("Do getcfam on proc target"); FAPI_TRY(fapi2::putCfamRegister(i_target, 0x1000, //DATA_0 from FSI2PIB l_cfamdata)); fapi_try_exit: FAPI_INF("Exiting p10_cfamtest_putcfam_pass..."); return fapi2::current_err; } fapi2::ReturnCode p10_ringtest_getring_fail( fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target) { fapi2::variable_buffer l_ringdata(64); FAPI_INF("Entering p10_ringtest_getring_fail..."); FAPI_INF("Do getring on proc target"); FAPI_TRY(fapi2::getRing(i_target, (scanRingId_t)(0x22334455), l_ringdata, fapi2::RING_MODE_HEADER_CHECK)); fapi_try_exit: FAPI_INF("Exiting p10_ringtest_getring_fail..."); return fapi2::current_err; } fapi2::ReturnCode p10_ringtest_modring_fail( fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target) { fapi2::variable_buffer l_ringdata; l_ringdata.resize(861); FAPI_INF("Entering p10_ringtest_modring_fail..."); FAPI_INF("Do modifyRing on proc target"); FAPI_TRY(fapi2::modifyRing(i_target, (scanRingId_t)0x22334455, l_ringdata, fapi2::CHIP_OP_MODIFY_MODE_OR, fapi2::RING_MODE_HEADER_CHECK)); fapi_try_exit: FAPI_INF("Exiting p10_ringtest_modring_fail..."); return fapi2::current_err; } fapi2::ReturnCode p10_ringtest_getring_pass( fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target) { fapi2::variable_buffer l_ringdata; l_ringdata.resize(861); FAPI_INF("Entering p10_ringtest_getring_pass..."); FAPI_INF("Do getring on proc target"); FAPI_TRY(fapi2::getRing(i_target, (scanRingId_t)0x00030088, l_ringdata, fapi2::RING_MODE_HEADER_CHECK)); fapi_try_exit: FAPI_INF("Exiting p10_ringtest_getring_pass..."); return fapi2::current_err; } fapi2::ReturnCode p10_ringtest_modring_pass( fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target) { uint32_t bit32_array[861]; uint32_t length; for (length = 0; length < 861; length++) { bit32_array[length] = length; } fapi2::variable_buffer l_ringdata(bit32_array, length, 32 * 861); FAPI_INF("Entering p10_ringtest_modring_pass..."); FAPI_INF("Do putring on proc target"); FAPI_TRY(fapi2::modifyRing(i_target, (scanRingId_t)0x00030088, l_ringdata, fapi2::CHIP_OP_MODIFY_MODE_OR, fapi2::RING_MODE_HEADER_CHECK)); fapi_try_exit: FAPI_INF("Exiting p10_ringtest_modring_pass..."); return fapi2::current_err; } fapi2::ReturnCode p10_platPutRingWRingId_t_pass() { //every test is displayed this way via FAPI_INF FAPI_INF("Entering p10_platPutRingWRingId_t_pass ..."); // get the master proc TARGETING::Target * l_procTest; TARGETING::targetService().masterProcChipTargetHandle(l_procTest); fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP> l_fapi2CpuTarget((l_procTest)); fapi2::ReturnCode l_status = fapi2::putRing(l_fapi2CpuTarget, n0_fure, fapi2::RING_MODE_SET_PULSE_NO_OPCG_COND); if(l_status!= fapi2::FAPI2_RC_SUCCESS) { TS_FAIL("p10_platPutRingWRingId_t_pass>> proc test - failed"); } return l_status; } fapi2::ReturnCode p10_opmodetest_ignorehwerr( fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target, uint8_t o_fail) { FAPI_INF("Entering p10_opmodetest_ignorehwerr..."); //Count the number of scoms we do so we can tell that we ran all of them. //Putting in this test so we know opMode isnt getting reset on FAPI_TRY uint8_t scomCount = 0; const uint8_t EXPECTED_NUMBER_OF_SCOMS = 4; do{ FAPI_INF("Setting opMode to IGNORE_HW_ERROR (0x1)"); fapi2::setOpMode(fapi2::IGNORE_HW_ERROR); fapi2::buffer<uint64_t> l_scomdata1 = 0xFF00FF00; fapi2::buffer<uint64_t> l_scomdata2 = 0xFF00FF00; fapi2::buffer<uint64_t> l_scomresult1 = 0x0; fapi2::buffer<uint64_t> l_scomresult2 = 0x0; FAPI_INF("Attempting 1st putScom, this should fail but because of opMode we skip the err"); FAPI_TRY(fapi2::putScom(i_target, 0xDEADBEEF, l_scomdata1)); scomCount++; FAPI_INF("Attempting 2nd putScom this should fail but because of opMode we skip the err"); FAPI_TRY(fapi2::getScom(i_target, 0xCABBABEF, l_scomdata2)); scomCount++; FAPI_INF("Attempting 1st getScom, this should fail but because of opMode we skip the err"); FAPI_TRY(fapi2::getScom(i_target, 0xDEADBEEF, l_scomresult1)); scomCount++; FAPI_INF("Attempting 2nd getScom, this should fail but because of opMode we skip the err"); FAPI_TRY(fapi2::getScom(i_target, 0xCABBABEF, l_scomresult2)); scomCount++; }while(0); fapi_try_exit: if(scomCount != EXPECTED_NUMBER_OF_SCOMS) { o_fail = 1; } FAPI_INF("Exiting p10_opmodetest_ignorehwerr..."); return fapi2::current_err; } fapi2::ReturnCode p10_piberrmask_masktest( fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target) { FAPI_INF("Entering p10_piberrmask_masktest..."); uint8_t completionCheck = 0; //Ideally we would like this test case to test errors 1-7 but // I am not sure if we can simulate some of the errors fapi2::buffer<uint64_t> l_scomdata = 0xFF00FF00; //Set the mask to ignore invalid address errors () fapi2::setPIBErrorMask(static_cast<uint8_t>(PIB::PIB_INVALID_ADDRESS)); //Attempt writing to a bad address // Avoid multicast error by not setting bit 1 FAPI_TRY(fapi2::putScom(i_target, 0xBADDBEEF, l_scomdata)); //try another scom, this time a get to make sure that // FAPI_TRY does not reset the mask // Avoid multicast error by not setting bit 1 FAPI_TRY(fapi2::getScom(i_target, 0xBADDBEEF, l_scomdata)); completionCheck = 1; fapi_try_exit: if(completionCheck != 1) { FAPI_ERR("Pib Err Mask is not removing errors and is causing FAPI_TRY to fail"); } FAPI_INF("Exiting p10_piberrmask_masktest..."); return fapi2::current_err; }
Correct PBI CQ FIR Mask Register address for P10
Correct PBI CQ FIR Mask Register address for P10 Latest simulation level removed more illegal SCOM ranges for P10, which broke the testcase that SCOMs the PBI CQ FIR Mask Register. Fix was to update the register address to reflect the P10 SCOM definition. Change-Id: I71f79fab8595039c42473b408bbe54ba767da9db Reviewed-on: http://rchgit01.rchland.ibm.com/gerrit1/88364 Tested-by: Jenkins Server <[email protected]> Reviewed-by: William G Hoffa <[email protected]> Reviewed-by: Ilya Smirnov <[email protected]> Tested-by: Jenkins OP Build CI <[email protected]> Reviewed-by: Nicholas E Bofferding <[email protected]>
C++
apache-2.0
open-power/hostboot,open-power/hostboot,open-power/hostboot,open-power/hostboot,open-power/hostboot
b68bff51912e3078a5b810d4e7a07aae5509eeaa
C++/set-matrix-zeroes.cpp
C++/set-matrix-zeroes.cpp
// Time: O(m * n) // Space: O(1) class Solution { public: /** * @param matrix: A list of lists of integers * @return: Void */ void setZeroes(vector<vector<int>> &matrix) { if (matrix.empty()) { return; } bool has_zero = false; int zero_i = -1; int zero_j = -1; for (int i = 0; i < matrix.size(); ++i) { for (int j = 0; j < matrix[0].size(); ++j) { if (matrix[i][j] == 0) { if (!has_zero) { zero_i = i; zero_j = j; has_zero = true; } matrix[zero_i][j] = 0; matrix[i][zero_j] = 0; } } } if (has_zero) { for (int i = 0; i < matrix.size(); ++i) { if (i == zero_i) { continue; } for (int j = 0; j < matrix[0].size(); ++j) { if (j == zero_j) { continue; } if (matrix[zero_i][j] == 0 || matrix[i][zero_j] == 0) { matrix[i][j] = 0; } } } for (int i = 0; i < matrix.size(); ++i) { matrix[i][zero_j] = 0; } for (int j = 0; j < matrix[0].size(); ++j) { matrix[zero_i][j] = 0; } } } };
// Time: O(m * n) // Space: O(1) class Solution { public: /** * @param matrix: A list of lists of integers * @return: Void */ void setZeroes(vector<vector<int>> &matrix) { if (matrix.empty()) { return; } bool has_zero = false; int zero_i = -1, zero_j = -1; for (int i = 0; i < matrix.size(); ++i) { for (int j = 0; j < matrix[0].size(); ++j) { if (matrix[i][j] == 0) { if (!has_zero) { zero_i = i; zero_j = j; has_zero = true; } matrix[zero_i][j] = 0; matrix[i][zero_j] = 0; } } } if (has_zero) { for (int i = 0; i < matrix.size(); ++i) { if (i == zero_i) { continue; } for (int j = 0; j < matrix[0].size(); ++j) { if (j == zero_j) { continue; } if (matrix[zero_i][j] == 0 || matrix[i][zero_j] == 0) { matrix[i][j] = 0; } } } for (int i = 0; i < matrix.size(); ++i) { matrix[i][zero_j] = 0; } for (int j = 0; j < matrix[0].size(); ++j) { matrix[zero_i][j] = 0; } } } };
Update set-matrix-zeroes.cpp
Update set-matrix-zeroes.cpp
C++
mit
kamyu104/LintCode,jaredkoontz/lintcode,kamyu104/LintCode,jaredkoontz/lintcode,kamyu104/LintCode,jaredkoontz/lintcode
36aaf072d1a9e501296f388f310dd1ad76dbf982
kernel/kernel/fs/dev.cpp
kernel/kernel/fs/dev.cpp
/* * Copyright (c) 2016, 2017 Pedro Falcato * This file is part of Onyx, and is released under the terms of the MIT License * check LICENSE at the root directory for more information */ #include <assert.h> #include <stdlib.h> #include <string.h> #include <errno.h> #include <stdio.h> #include <sys/types.h> #include <onyx/dev.h> #include <onyx/majorminor.h> #include <onyx/compiler.h> #include <onyx/panic.h> #include <onyx/tmpfs.h> #include <onyx/vfs.h> #include <onyx/init.h> static struct dev *devices[MAJOR_DEVICE_HASHTABLE]; static inline int major_to_hash(dev_t major) { return major; } unsigned int __allocate_dynamic_major(void) { for(unsigned int i = 1; i < MAJOR_DEVICE_HASHTABLE; i++) { if(!devices[i]) { return i; } } return (unsigned int) -1; } struct dev *dev_register(unsigned int major, unsigned int minor, const char *name) { struct dev *c = nullptr; struct dev *dev = nullptr; /* If major == 0, create a dynamic major number */ if(major == 0) { major = __allocate_dynamic_major(); if(major == (unsigned int) -1) return nullptr; } /* Create a new dev and set it up */ dev = (struct dev *) zalloc(sizeof(struct dev)); if(!dev) return nullptr; dev->majorminor = MKDEV(major, minor); dev->name = strdup(name); if(!dev->name) { free(dev); return nullptr; } if(!devices[major]) { devices[major] = dev; } else { c = devices[major_to_hash(major)]; for(; c->next; c = c->next) { if(MINOR(c->majorminor) == minor) { free(dev); return errno = EEXIST, nullptr; } } c->next = dev; } return dev; } void dev_unregister(dev_t dev) { unsigned int major = MAJOR(dev); unsigned int minor = MINOR(dev); struct dev *d = devices[major]; if(d->majorminor == dev) { devices[major] = d->next; free(d); return; } for(; d->next; d = d->next) { if(d->next->majorminor == minor) { struct dev *found = d->next; d->next = found->next; free(found); return; } } } struct dev *dev_find(dev_t dev) { unsigned int major = MAJOR(dev); unsigned int minor = MINOR(dev); if(!devices[major]) return nullptr; for(struct dev *c = devices[major]; c; c = c->next) { if(MINOR(c->majorminor) == minor) { return c; } } return nullptr; } struct file *dev_root = nullptr; void devfs_init(void) { /* Mount tmpfs on /dev */ assert(tmpfs_mount("/dev") == 0); struct file *dev = dev_root = open_vfs(get_fs_root(), "/dev"); assert(dev != nullptr); } INIT_LEVEL_CORE_AFTER_SCHED_ENTRY(devfs_init); int device_mknod(struct dev *d, const char *path, const char *name, mode_t mode) { struct file *root = dev_root; if(strcmp(path, DEVICE_NO_PATH) != 0) { root = open_vfs(root, path); if(!root) return -errno; } assert(root != nullptr); if(d->is_block) mode |= S_IFBLK; else mode |= S_IFCHR; return mknod_vfs(name, mode, d->majorminor, root->f_dentry) == nullptr; } int device_show(struct dev *d, const char *path, mode_t mode) { return device_mknod(d, path, d->name, mode); } int device_create_dir(const char *path) { struct file *i = mkdir_vfs(path, 0600, dev_root->f_dentry); return i == nullptr ? -1 : 0; }
/* * Copyright (c) 2016 - 2021 Pedro Falcato * This file is part of Onyx, and is released under the terms of the MIT License * check LICENSE at the root directory for more information * * SPDX-License-Identifier: MIT */ #include <assert.h> #include <stdlib.h> #include <string.h> #include <errno.h> #include <stdio.h> #include <sys/types.h> #include <onyx/dev.h> #include <onyx/majorminor.h> #include <onyx/compiler.h> #include <onyx/panic.h> #include <onyx/tmpfs.h> #include <onyx/vfs.h> #include <onyx/init.h> #include <onyx/file.h> static struct dev *devices[MAJOR_DEVICE_HASHTABLE]; static inline int major_to_hash(dev_t major) { return major; } unsigned int __allocate_dynamic_major(void) { for(unsigned int i = 1; i < MAJOR_DEVICE_HASHTABLE; i++) { if(!devices[i]) { return i; } } return (unsigned int) -1; } struct dev *dev_register(unsigned int major, unsigned int minor, const char *name) { struct dev *c = nullptr; struct dev *dev = nullptr; /* If major == 0, create a dynamic major number */ if(major == 0) { major = __allocate_dynamic_major(); if(major == (unsigned int) -1) return nullptr; } /* Create a new dev and set it up */ dev = (struct dev *) zalloc(sizeof(struct dev)); if(!dev) return nullptr; dev->majorminor = MKDEV(major, minor); dev->name = strdup(name); if(!dev->name) { free(dev); return nullptr; } if(!devices[major]) { devices[major] = dev; } else { c = devices[major_to_hash(major)]; for(; c->next; c = c->next) { if(MINOR(c->majorminor) == minor) { free(dev); return errno = EEXIST, nullptr; } } c->next = dev; } return dev; } void dev_unregister(dev_t dev) { unsigned int major = MAJOR(dev); unsigned int minor = MINOR(dev); struct dev *d = devices[major]; if(d->majorminor == dev) { devices[major] = d->next; free(d); return; } for(; d->next; d = d->next) { if(d->next->majorminor == minor) { struct dev *found = d->next; d->next = found->next; free(found); return; } } } struct dev *dev_find(dev_t dev) { unsigned int major = MAJOR(dev); unsigned int minor = MINOR(dev); if(!devices[major]) return nullptr; for(struct dev *c = devices[major]; c; c = c->next) { if(MINOR(c->majorminor) == minor) { return c; } } return nullptr; } struct file *dev_root = nullptr; void devfs_init(void) { /* Mount tmpfs on /dev */ assert(tmpfs_mount("/dev") == 0); struct file *dev = dev_root = open_vfs(get_fs_root(), "/dev"); assert(dev != nullptr); } INIT_LEVEL_CORE_AFTER_SCHED_ENTRY(devfs_init); int device_mknod(struct dev *d, const char *path, const char *name, mode_t mode) { struct file *root = dev_root; bool opened = false; if(strcmp(path, DEVICE_NO_PATH) != 0) { root = open_vfs(root, path); if(!root) return -errno; opened = true; } assert(root != nullptr); if(d->is_block) mode |= S_IFBLK; else mode |= S_IFCHR; auto ret = mknod_vfs(name, mode, d->majorminor, root->f_dentry); if (opened) fd_put(root); if (ret) fd_put(ret); return ret == nullptr ? -errno : 0; } int device_show(struct dev *d, const char *path, mode_t mode) { return device_mknod(d, path, d->name, mode); } int device_create_dir(const char *path) { struct file *i = mkdir_vfs(path, 0600, dev_root->f_dentry); return i == nullptr ? -1 : 0; }
Fix bug in device_mknod
dev: Fix bug in device_mknod Signed-off-by: Pedro Falcato <[email protected]>
C++
mit
heatd/Onyx,heatd/Onyx,heatd/Onyx,heatd/Onyx
032640d6b760751b5112afbda79b06f2e766043a
cetty-gearman/sample/GearmanEchoServer.cpp
cetty-gearman/sample/GearmanEchoServer.cpp
#include <stdio.h> #include <boost/bind.hpp> #include <cetty/service/ClientService.h> #include <cetty/gearman/builder/GearmanWorkerBuilder.h> #include <cetty/gearman/GearmanMessage.h> using namespace cetty::channel; using namespace cetty::gearman; using namespace cetty::bootstrap; using namespace cetty::service; using namespace cetty::gearman::builder; class GearmanEchoWorker { public: GearmanEchoWorker(const ClientServicePtr& s): service(s),count(0) { } virtual ~GearmanEchoWorker() {} void sendRequest() { ChannelBufferPtr buf = ChannelBuffers::buffer(10); buf->writeBytes("hello"); GearmanMessagePtr request(GearmanMessage::createsubmitJobMessage("test","1234",buf)); service->write(ChannelMessage(request)); } //void replied(const echo::EchoServiceFuture& f, const echo::EchoResponsePtr& resp) { // ++count; // if (count < 10000) { // sendRequest(); // } //} private: int count; ClientServicePtr service; }; int main(int argc, char* argv[]) { GearmanWorkerBuilder builder; builder.addConnection("127.0.0.1", 4730); ClientServicePtr service = builder.build(); GearmanEchoWorker client(service); client.sendRequest(); service->getCloseFuture()->awaitUninterruptibly(); }
#include <stdio.h> #include <cetty/gearman/GearmanMessage.h> #include <cetty/gearman/builder/GearmanWorkerBuilder.h> using namespace cetty::gearman; using namespace cetty::gearman::builder; GearmanMessagePtr echo(const GearmanMessagePtr& message) { return GearmanMessagePtr(); } int main(int argc, char* argv[]) { GearmanWorkerBuilder builder; builder.addConnection("127.0.0.1", 4730); builder.registerWorker("test", &echo); builder.buildWorkers(); // }
fix the echo server.
cetty-gearman: fix the echo server.
C++
apache-2.0
frankee/cetty2,frankee/cetty2,frankee/cetty2,frankee/cetty2,frankee/cetty2
bb8ce73de39c6055382b3471bf18fddd0f424195
chrome/browser/content_settings/permission_context_uma_util.cc
chrome/browser/content_settings/permission_context_uma_util.cc
// 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 "base/metrics/histogram.h" #include "chrome/browser/content_settings/permission_context_uma_util.h" namespace { // Enum for UMA purposes, make sure you update histograms.xml if you add new // permission actions. Never delete or reorder an entry; only add new entries // immediately before PERMISSION_NUM enum PermissionAction { GRANTED = 0, DENIED = 1, DISMISSED = 2, IGNORED = 3, // Always keep this at the end. PERMISSION_ACTION_NUM, }; // Enum for UMA purposes, make sure you update histograms.xml if you add new // permission actions. Never delete or reorder an entry; only add new entries // immediately before PERMISSION_NUM enum PermissionType { PERMISSION_UNKNOWN = 0, PERMISSION_MIDI_SYSEX = 1, PERMISSION_PUSH_MESSAGING = 2, PERMISSION_NOTIFICATIONS = 3, // Always keep this at the end. PERMISSION_NUM, }; void RecordPermissionAction( ContentSettingsType permission, PermissionAction action) { switch (permission) { case CONTENT_SETTINGS_TYPE_GEOLOCATION: // TODO(miguelg): support geolocation through // the generic permission class. break; case CONTENT_SETTINGS_TYPE_NOTIFICATIONS: UMA_HISTOGRAM_ENUMERATION( "ContentSettings.PermisionActions_Notifications", action, PERMISSION_ACTION_NUM); break; case CONTENT_SETTINGS_TYPE_MIDI_SYSEX: UMA_HISTOGRAM_ENUMERATION("ContentSettings.PermisionActions_MidiSysEx", action, PERMISSION_ACTION_NUM); break; case CONTENT_SETTINGS_TYPE_PUSH_MESSAGING: UMA_HISTOGRAM_ENUMERATION( "ContentSettings.PermisionActions_PushMessaging", action, PERMISSION_ACTION_NUM); break; #if defined(OS_ANDROID) case CONTENT_SETTINGS_TYPE_PROTECTED_MEDIA_IDENTIFIER: // TODO(miguelg): support protected media through // the generic permission class. break; #endif default: NOTREACHED() << "PERMISSION " << permission << " not accounted for"; } } void RecordPermissionRequest( ContentSettingsType permission) { PermissionType type; switch (permission) { case CONTENT_SETTINGS_TYPE_NOTIFICATIONS: type = PERMISSION_NOTIFICATIONS; break; case CONTENT_SETTINGS_TYPE_MIDI_SYSEX: type = PERMISSION_MIDI_SYSEX; break; case CONTENT_SETTINGS_TYPE_PUSH_MESSAGING: type = PERMISSION_PUSH_MESSAGING; break; default: NOTREACHED() << "PERMISSION " << permission << " not accounted for"; type = PERMISSION_UNKNOWN; } UMA_HISTOGRAM_ENUMERATION("ContentSettings.PermissionRequested", type, PERMISSION_NUM); } } // namespace // Make sure you update histograms.xml permission histogram_suffix if you // add new permission void PermissionContextUmaUtil::PermissionRequested( ContentSettingsType permission) { RecordPermissionRequest(permission); } void PermissionContextUmaUtil::PermissionGranted( ContentSettingsType permission) { RecordPermissionAction(permission, GRANTED); } void PermissionContextUmaUtil::PermissionDenied( ContentSettingsType permission) { RecordPermissionAction(permission, DENIED); } void PermissionContextUmaUtil::PermissionDismissed( ContentSettingsType permission) { RecordPermissionAction(permission, DISMISSED); } void PermissionContextUmaUtil::PermissionIgnored( ContentSettingsType permission) { RecordPermissionAction(permission, IGNORED); }
// 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 "base/metrics/histogram.h" #include "chrome/browser/content_settings/permission_context_uma_util.h" namespace { // Enum for UMA purposes, make sure you update histograms.xml if you add new // permission actions. Never delete or reorder an entry; only add new entries // immediately before PERMISSION_NUM enum PermissionAction { GRANTED = 0, DENIED = 1, DISMISSED = 2, IGNORED = 3, // Always keep this at the end. PERMISSION_ACTION_NUM, }; // Enum for UMA purposes, make sure you update histograms.xml if you add new // permission actions. Never delete or reorder an entry; only add new entries // immediately before PERMISSION_NUM enum PermissionType { PERMISSION_UNKNOWN = 0, PERMISSION_MIDI_SYSEX = 1, PERMISSION_PUSH_MESSAGING = 2, PERMISSION_NOTIFICATIONS = 3, // Always keep this at the end. PERMISSION_NUM, }; void RecordPermissionAction( ContentSettingsType permission, PermissionAction action) { switch (permission) { case CONTENT_SETTINGS_TYPE_GEOLOCATION: // TODO(miguelg): support geolocation through // the generic permission class. break; case CONTENT_SETTINGS_TYPE_NOTIFICATIONS: UMA_HISTOGRAM_ENUMERATION( "ContentSettings.PermissionActions_Notifications", action, PERMISSION_ACTION_NUM); break; case CONTENT_SETTINGS_TYPE_MIDI_SYSEX: UMA_HISTOGRAM_ENUMERATION("ContentSettings.PermissionActions_MidiSysEx", action, PERMISSION_ACTION_NUM); break; case CONTENT_SETTINGS_TYPE_PUSH_MESSAGING: UMA_HISTOGRAM_ENUMERATION( "ContentSettings.PermissionActions_PushMessaging", action, PERMISSION_ACTION_NUM); break; #if defined(OS_ANDROID) case CONTENT_SETTINGS_TYPE_PROTECTED_MEDIA_IDENTIFIER: // TODO(miguelg): support protected media through // the generic permission class. break; #endif default: NOTREACHED() << "PERMISSION " << permission << " not accounted for"; } } void RecordPermissionRequest( ContentSettingsType permission) { PermissionType type; switch (permission) { case CONTENT_SETTINGS_TYPE_NOTIFICATIONS: type = PERMISSION_NOTIFICATIONS; break; case CONTENT_SETTINGS_TYPE_MIDI_SYSEX: type = PERMISSION_MIDI_SYSEX; break; case CONTENT_SETTINGS_TYPE_PUSH_MESSAGING: type = PERMISSION_PUSH_MESSAGING; break; default: NOTREACHED() << "PERMISSION " << permission << " not accounted for"; type = PERMISSION_UNKNOWN; } UMA_HISTOGRAM_ENUMERATION("ContentSettings.PermissionRequested", type, PERMISSION_NUM); } } // namespace // Make sure you update histograms.xml permission histogram_suffix if you // add new permission void PermissionContextUmaUtil::PermissionRequested( ContentSettingsType permission) { RecordPermissionRequest(permission); } void PermissionContextUmaUtil::PermissionGranted( ContentSettingsType permission) { RecordPermissionAction(permission, GRANTED); } void PermissionContextUmaUtil::PermissionDenied( ContentSettingsType permission) { RecordPermissionAction(permission, DENIED); } void PermissionContextUmaUtil::PermissionDismissed( ContentSettingsType permission) { RecordPermissionAction(permission, DISMISSED); } void PermissionContextUmaUtil::PermissionIgnored( ContentSettingsType permission) { RecordPermissionAction(permission, IGNORED); }
Fix a typo in the name of the ContentSettings.Permis(s)ionActions histograms.
Fix a typo in the name of the ContentSettings.Permis(s)ionActions histograms. [email protected], [email protected] BUG=413665 Review URL: https://codereview.chromium.org/548843003 Cr-Commit-Position: 972c6d2dc6dd5efdad1377c0d224e03eb8f276f7@{#294598}
C++
bsd-3-clause
krieger-od/nwjs_chromium.src,markYoungH/chromium.src,krieger-od/nwjs_chromium.src,dednal/chromium.src,Pluto-tv/chromium-crosswalk,ltilve/chromium,hgl888/chromium-crosswalk,Fireblend/chromium-crosswalk,hgl888/chromium-crosswalk-efl,mohamed--abdel-maksoud/chromium.src,jaruba/chromium.src,dednal/chromium.src,mohamed--abdel-maksoud/chromium.src,dushu1203/chromium.src,dushu1203/chromium.src,jaruba/chromium.src,Just-D/chromium-1,krieger-od/nwjs_chromium.src,markYoungH/chromium.src,markYoungH/chromium.src,crosswalk-project/chromium-crosswalk-efl,Fireblend/chromium-crosswalk,dushu1203/chromium.src,PeterWangIntel/chromium-crosswalk,M4sse/chromium.src,Pluto-tv/chromium-crosswalk,jaruba/chromium.src,hgl888/chromium-crosswalk-efl,fujunwei/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,Fireblend/chromium-crosswalk,krieger-od/nwjs_chromium.src,dushu1203/chromium.src,Jonekee/chromium.src,Pluto-tv/chromium-crosswalk,axinging/chromium-crosswalk,hgl888/chromium-crosswalk,ltilve/chromium,hgl888/chromium-crosswalk-efl,dushu1203/chromium.src,Fireblend/chromium-crosswalk,chuan9/chromium-crosswalk,Just-D/chromium-1,fujunwei/chromium-crosswalk,jaruba/chromium.src,Just-D/chromium-1,mohamed--abdel-maksoud/chromium.src,M4sse/chromium.src,chuan9/chromium-crosswalk,dushu1203/chromium.src,PeterWangIntel/chromium-crosswalk,Just-D/chromium-1,Jonekee/chromium.src,M4sse/chromium.src,TheTypoMaster/chromium-crosswalk,chuan9/chromium-crosswalk,hgl888/chromium-crosswalk-efl,krieger-od/nwjs_chromium.src,TheTypoMaster/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,Chilledheart/chromium,Chilledheart/chromium,Just-D/chromium-1,axinging/chromium-crosswalk,M4sse/chromium.src,hgl888/chromium-crosswalk,dednal/chromium.src,mohamed--abdel-maksoud/chromium.src,Just-D/chromium-1,PeterWangIntel/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,chuan9/chromium-crosswalk,dushu1203/chromium.src,ltilve/chromium,hgl888/chromium-crosswalk,Fireblend/chromium-crosswalk,fujunwei/chromium-crosswalk,Pluto-tv/chromium-crosswalk,M4sse/chromium.src,markYoungH/chromium.src,dushu1203/chromium.src,Jonekee/chromium.src,Fireblend/chromium-crosswalk,hgl888/chromium-crosswalk-efl,Chilledheart/chromium,krieger-od/nwjs_chromium.src,axinging/chromium-crosswalk,fujunwei/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,dednal/chromium.src,axinging/chromium-crosswalk,markYoungH/chromium.src,krieger-od/nwjs_chromium.src,Chilledheart/chromium,krieger-od/nwjs_chromium.src,mohamed--abdel-maksoud/chromium.src,PeterWangIntel/chromium-crosswalk,Jonekee/chromium.src,Chilledheart/chromium,jaruba/chromium.src,dednal/chromium.src,dushu1203/chromium.src,Chilledheart/chromium,jaruba/chromium.src,Fireblend/chromium-crosswalk,axinging/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,hgl888/chromium-crosswalk,M4sse/chromium.src,chuan9/chromium-crosswalk,ltilve/chromium,dednal/chromium.src,hgl888/chromium-crosswalk-efl,M4sse/chromium.src,Just-D/chromium-1,Just-D/chromium-1,fujunwei/chromium-crosswalk,jaruba/chromium.src,markYoungH/chromium.src,Jonekee/chromium.src,Chilledheart/chromium,TheTypoMaster/chromium-crosswalk,Jonekee/chromium.src,ltilve/chromium,jaruba/chromium.src,hgl888/chromium-crosswalk,axinging/chromium-crosswalk,axinging/chromium-crosswalk,chuan9/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,chuan9/chromium-crosswalk,jaruba/chromium.src,axinging/chromium-crosswalk,chuan9/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,Jonekee/chromium.src,dushu1203/chromium.src,Pluto-tv/chromium-crosswalk,Jonekee/chromium.src,TheTypoMaster/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,Chilledheart/chromium,mohamed--abdel-maksoud/chromium.src,TheTypoMaster/chromium-crosswalk,markYoungH/chromium.src,crosswalk-project/chromium-crosswalk-efl,krieger-od/nwjs_chromium.src,jaruba/chromium.src,Chilledheart/chromium,dednal/chromium.src,Jonekee/chromium.src,hgl888/chromium-crosswalk-efl,TheTypoMaster/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,ltilve/chromium,hgl888/chromium-crosswalk,dednal/chromium.src,TheTypoMaster/chromium-crosswalk,Fireblend/chromium-crosswalk,Pluto-tv/chromium-crosswalk,Jonekee/chromium.src,crosswalk-project/chromium-crosswalk-efl,axinging/chromium-crosswalk,fujunwei/chromium-crosswalk,markYoungH/chromium.src,hgl888/chromium-crosswalk-efl,Pluto-tv/chromium-crosswalk,krieger-od/nwjs_chromium.src,Pluto-tv/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,chuan9/chromium-crosswalk,markYoungH/chromium.src,markYoungH/chromium.src,dushu1203/chromium.src,PeterWangIntel/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,ltilve/chromium,krieger-od/nwjs_chromium.src,hgl888/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,ltilve/chromium,Jonekee/chromium.src,hgl888/chromium-crosswalk,hgl888/chromium-crosswalk-efl,markYoungH/chromium.src,M4sse/chromium.src,Just-D/chromium-1,dednal/chromium.src,M4sse/chromium.src,Pluto-tv/chromium-crosswalk,axinging/chromium-crosswalk,fujunwei/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,dednal/chromium.src,Fireblend/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,mohamed--abdel-maksoud/chromium.src,fujunwei/chromium-crosswalk,fujunwei/chromium-crosswalk,M4sse/chromium.src,crosswalk-project/chromium-crosswalk-efl,dednal/chromium.src,ltilve/chromium,jaruba/chromium.src,axinging/chromium-crosswalk,hgl888/chromium-crosswalk-efl,M4sse/chromium.src
27395fb1d114aeb319e3b912141d560bd0bd9732
framework/src/base/Attributes.C
framework/src/base/Attributes.C
//* This file is part of the MOOSE framework //* https://www.mooseframework.org //* //* All rights reserved, see COPYRIGHT for full restrictions //* https://github.com/idaholab/moose/blob/master/COPYRIGHT //* //* Licensed under LGPL 2.1, please see LICENSE for details //* https://www.gnu.org/licenses/lgpl-2.1.html #include "Attributes.h" #include "TaggingInterface.h" #include "BoundaryRestrictable.h" #include "BlockRestrictable.h" #include "SetupInterface.h" #include "MooseVariableInterface.h" #include "MooseVariableFE.h" #include "ElementUserObject.h" #include "SideUserObject.h" #include "InternalSideUserObject.h" #include "InterfaceUserObject.h" #include "NodalUserObject.h" #include "GeneralUserObject.h" #include "ThreadedGeneralUserObject.h" #include "ShapeUserObject.h" #include "ShapeSideUserObject.h" #include "ShapeElementUserObject.h" #include "SystemBase.h" std::ostream & operator<<(std::ostream & os, Interfaces & iface) { os << "Interfaces("; if (static_cast<bool>(iface & Interfaces::UserObject)) os << "|UserObject"; if (static_cast<bool>(iface & Interfaces::ElementUserObject)) os << "|ElementUserObject"; if (static_cast<bool>(iface & Interfaces::SideUserObject)) os << "|SideUserObject"; if (static_cast<bool>(iface & Interfaces::InternalSideUserObject)) os << "|InternalSideUserObject"; if (static_cast<bool>(iface & Interfaces::NodalUserObject)) os << "|NodalUserObject"; if (static_cast<bool>(iface & Interfaces::GeneralUserObject)) os << "|GeneralUserObject"; if (static_cast<bool>(iface & Interfaces::ThreadedGeneralUserObject)) os << "|ThreadedGeneralUserObject"; if (static_cast<bool>(iface & Interfaces::ShapeElementUserObject)) os << "|ShapeElementUserObject"; if (static_cast<bool>(iface & Interfaces::ShapeSideUserObject)) os << "|ShapeSideUserObject"; if (static_cast<bool>(iface & Interfaces::Postprocessor)) os << "|Postprocessor"; if (static_cast<bool>(iface & Interfaces::VectorPostprocessor)) os << "|VectorPostprocessor"; if (static_cast<bool>(iface & Interfaces::InterfaceUserObject)) os << "|InterfaceUserObject"; os << ")"; return os; } bool AttribTagBase::isMatch(const Attribute & other) const { auto a = dynamic_cast<const AttribTagBase *>(&other); if (!a) return false; if (a->_vals.size() == 0) return true; // the condition is empty tags - which we take to mean any tag should match // return true if any single tag matches between the two attribute objects for (auto val : _vals) if (std::find(a->_vals.begin(), a->_vals.end(), val) != a->_vals.end()) return true; return false; } bool AttribTagBase::isEqual(const Attribute & other) const { auto a = dynamic_cast<const AttribTagBase *>(&other); if (!a || a->_vals.size() != _vals.size()) return false; for (size_t i = 0; i < a->_vals.size(); i++) if (a->_vals[i] != _vals[i]) return false; return true; } void AttribMatrixTags::initFrom(const MooseObject * obj) { _vals.clear(); auto t = dynamic_cast<const TaggingInterface *>(obj); if (t) { for (auto & tag : t->getMatrixTags()) _vals.push_back(static_cast<int>(tag)); } } void AttribVectorTags::initFrom(const MooseObject * obj) { _vals.clear(); auto t = dynamic_cast<const TaggingInterface *>(obj); if (t) { for (auto & tag : t->getVectorTags()) _vals.push_back(static_cast<int>(tag)); } } void AttribExecOns::initFrom(const MooseObject * obj) { _vals.clear(); auto sup = dynamic_cast<const SetupInterface *>(obj); if (sup) { auto e = sup->getExecuteOnEnum(); for (auto & on : e.items()) if (e.contains(on)) _vals.push_back(on); } } bool AttribExecOns::isMatch(const Attribute & other) const { auto a = dynamic_cast<const AttribExecOns *>(&other); if (!a || a->_vals.size() < 1) return false; auto cond = a->_vals[0]; if (cond == Moose::ALL) return true; for (auto val : _vals) if (val == Moose::ALL || val == cond) return true; return false; } bool AttribExecOns::isEqual(const Attribute & other) const { auto a = dynamic_cast<const AttribExecOns *>(&other); if (!a || a->_vals.size() != _vals.size()) return false; for (size_t i = 0; i < a->_vals.size(); i++) if (a->_vals[i] != _vals[i]) return false; return true; } void AttribSubdomains::initFrom(const MooseObject * obj) { _vals.clear(); auto blk = dynamic_cast<const BlockRestrictable *>(obj); if (blk && blk->blockRestricted()) { for (auto id : blk->blockIDs()) _vals.push_back(id); } else _vals.push_back(Moose::ANY_BLOCK_ID); } bool AttribSubdomains::isMatch(const Attribute & other) const { auto a = dynamic_cast<const AttribSubdomains *>(&other); if (!a || a->_vals.size() < 1) return false; auto cond = a->_vals[0]; if (cond == Moose::ANY_BLOCK_ID) return true; else if (cond == Moose::INVALID_BLOCK_ID) return false; for (auto id : _vals) { if (id == cond || id == Moose::ANY_BLOCK_ID) return true; } return false; } bool AttribSubdomains::isEqual(const Attribute & other) const { auto a = dynamic_cast<const AttribSubdomains *>(&other); if (!a || a->_vals.size() != _vals.size()) return false; for (size_t i = 0; i < a->_vals.size(); i++) if (a->_vals[i] != _vals[i]) return false; return true; } void AttribBoundaries::initFrom(const MooseObject * obj) { _vals.clear(); auto bnd = dynamic_cast<const BoundaryRestrictable *>(obj); if (bnd && bnd->boundaryRestricted()) { for (auto & bound : bnd->boundaryIDs()) _vals.push_back(bound); } else _vals.push_back(Moose::ANY_BOUNDARY_ID); } bool AttribBoundaries::isMatch(const Attribute & other) const { auto a = dynamic_cast<const AttribBoundaries *>(&other); if (!a || a->_vals.size() < 1) return false; // return true if a single tag matches between the two attribute objects for (auto val : _vals) { if (!a->_must_be_restricted && (val == Moose::ANY_BOUNDARY_ID)) return true; if (std::find(a->_vals.begin(), a->_vals.end(), val) != a->_vals.end()) return true; else if (std::find(a->_vals.begin(), a->_vals.end(), Moose::ANY_BOUNDARY_ID) != a->_vals.end()) return true; } return false; } bool AttribBoundaries::isEqual(const Attribute & other) const { auto a = dynamic_cast<const AttribBoundaries *>(&other); if (!a || a->_vals.size() != _vals.size()) return false; for (size_t i = 0; i < a->_vals.size(); i++) if (a->_vals[i] != _vals[i]) return false; return true; } void AttribThread::initFrom(const MooseObject * obj) { _val = obj->getParam<THREAD_ID>("_tid"); } bool AttribThread::isMatch(const Attribute & other) const { auto a = dynamic_cast<const AttribThread *>(&other); return a && (a->_val == _val); } bool AttribThread::isEqual(const Attribute & other) const { return isMatch(other); } void AttribSysNum::initFrom(const MooseObject * obj) { auto * sys = obj->getParam<SystemBase *>("_sys"); if (sys) _val = sys->number(); } bool AttribSysNum::isMatch(const Attribute & other) const { auto a = dynamic_cast<const AttribSysNum *>(&other); return a && (a->_val == _val); } bool AttribSysNum::isEqual(const Attribute & other) const { return isMatch(other); } void AttribPreIC::initFrom(const MooseObject * /*obj*/) { } bool AttribPreIC::isMatch(const Attribute & other) const { auto a = dynamic_cast<const AttribPreIC *>(&other); return a && (a->_val == _val); } bool AttribPreIC::isEqual(const Attribute & other) const { return isMatch(other); } void AttribPreAux::initFrom(const MooseObject * /*obj*/) { } bool AttribPreAux::isMatch(const Attribute & other) const { auto a = dynamic_cast<const AttribPreAux *>(&other); return a && (a->_val == _val); } bool AttribPreAux::isEqual(const Attribute & other) const { return isMatch(other); } void AttribPostAux::initFrom(const MooseObject * /*obj*/) { } bool AttribPostAux::isMatch(const Attribute & other) const { auto a = dynamic_cast<const AttribPostAux *>(&other); return a && (a->_val == _val); } bool AttribPostAux::isEqual(const Attribute & other) const { return isMatch(other); } void AttribName::initFrom(const MooseObject * obj) { _val = obj->name(); } bool AttribName::isMatch(const Attribute & other) const { auto a = dynamic_cast<const AttribName *>(&other); return a && (a->_val == _val); } bool AttribName::isEqual(const Attribute & other) const { return isMatch(other); } void AttribSystem::initFrom(const MooseObject * obj) { if (!obj->isParamValid("_moose_warehouse_system_name")) mooseError("The base objects supplied to the TheWarehouse must call " "'registerSystemAttributeName' method in the validParams function."); _val = obj->getParam<std::string>("_moose_warehouse_system_name"); } bool AttribSystem::isMatch(const Attribute & other) const { auto a = dynamic_cast<const AttribSystem *>(&other); return a && (a->_val == _val); } bool AttribSystem::isEqual(const Attribute & other) const { return isMatch(other); } void AttribVar::initFrom(const MooseObject * obj) { auto vi = dynamic_cast<const MooseVariableInterface<Real> *>(obj); if (vi) _val = static_cast<int>(vi->mooseVariableBase()->number()); } bool AttribVar::isMatch(const Attribute & other) const { auto a = dynamic_cast<const AttribVar *>(&other); return a && (a->_val == _val); } bool AttribVar::isEqual(const Attribute & other) const { return isMatch(other); } void AttribInterfaces::initFrom(const MooseObject * obj) { _val = 0; // clang-format off _val |= (unsigned int)Interfaces::UserObject * (dynamic_cast<const UserObject *>(obj) != nullptr); _val |= (unsigned int)Interfaces::ElementUserObject * (dynamic_cast<const ElementUserObject *>(obj) != nullptr); _val |= (unsigned int)Interfaces::SideUserObject * (dynamic_cast<const SideUserObject *>(obj) != nullptr); _val |= (unsigned int)Interfaces::InternalSideUserObject * (dynamic_cast<const InternalSideUserObject *>(obj) != nullptr); _val |= (unsigned int)Interfaces::InterfaceUserObject * (dynamic_cast<const InterfaceUserObject *>(obj) != nullptr); _val |= (unsigned int)Interfaces::NodalUserObject * (dynamic_cast<const NodalUserObject *>(obj) != nullptr); _val |= (unsigned int)Interfaces::GeneralUserObject * (dynamic_cast<const GeneralUserObject *>(obj) != nullptr); _val |= (unsigned int)Interfaces::ThreadedGeneralUserObject * (dynamic_cast<const ThreadedGeneralUserObject *>(obj) != nullptr); _val |= (unsigned int)Interfaces::ShapeElementUserObject * (dynamic_cast<const ShapeElementUserObject *>(obj) != nullptr); _val |= (unsigned int)Interfaces::ShapeSideUserObject * (dynamic_cast<const ShapeSideUserObject *>(obj) != nullptr); _val |= (unsigned int)Interfaces::Postprocessor * (dynamic_cast<const Postprocessor *>(obj) != nullptr); _val |= (unsigned int)Interfaces::VectorPostprocessor * (dynamic_cast<const VectorPostprocessor *>(obj) != nullptr); _val |= (unsigned int)Interfaces::BlockRestrictable * (dynamic_cast<const BlockRestrictable *>(obj) != nullptr); _val |= (unsigned int)Interfaces::BoundaryRestrictable * (dynamic_cast<const BoundaryRestrictable *>(obj) != nullptr); // clang-format on } bool AttribInterfaces::isMatch(const Attribute & other) const { auto a = dynamic_cast<const AttribInterfaces *>(&other); return a && (a->_val & _val); } bool AttribInterfaces::isEqual(const Attribute & other) const { auto a = dynamic_cast<const AttribInterfaces *>(&other); return a && (a->_val == _val); }
//* This file is part of the MOOSE framework //* https://www.mooseframework.org //* //* All rights reserved, see COPYRIGHT for full restrictions //* https://github.com/idaholab/moose/blob/master/COPYRIGHT //* //* Licensed under LGPL 2.1, please see LICENSE for details //* https://www.gnu.org/licenses/lgpl-2.1.html #include "Attributes.h" #include "TaggingInterface.h" #include "BoundaryRestrictable.h" #include "BlockRestrictable.h" #include "SetupInterface.h" #include "MooseVariableInterface.h" #include "MooseVariableFE.h" #include "ElementUserObject.h" #include "SideUserObject.h" #include "InternalSideUserObject.h" #include "InterfaceUserObject.h" #include "NodalUserObject.h" #include "GeneralUserObject.h" #include "ThreadedGeneralUserObject.h" #include "ShapeUserObject.h" #include "ShapeSideUserObject.h" #include "ShapeElementUserObject.h" #include "Reporter.h" #include "SystemBase.h" std::ostream & operator<<(std::ostream & os, Interfaces & iface) { os << "Interfaces("; if (static_cast<bool>(iface & Interfaces::UserObject)) os << "|UserObject"; if (static_cast<bool>(iface & Interfaces::ElementUserObject)) os << "|ElementUserObject"; if (static_cast<bool>(iface & Interfaces::SideUserObject)) os << "|SideUserObject"; if (static_cast<bool>(iface & Interfaces::InternalSideUserObject)) os << "|InternalSideUserObject"; if (static_cast<bool>(iface & Interfaces::NodalUserObject)) os << "|NodalUserObject"; if (static_cast<bool>(iface & Interfaces::GeneralUserObject)) os << "|GeneralUserObject"; if (static_cast<bool>(iface & Interfaces::ThreadedGeneralUserObject)) os << "|ThreadedGeneralUserObject"; if (static_cast<bool>(iface & Interfaces::ShapeElementUserObject)) os << "|ShapeElementUserObject"; if (static_cast<bool>(iface & Interfaces::ShapeSideUserObject)) os << "|ShapeSideUserObject"; if (static_cast<bool>(iface & Interfaces::Postprocessor)) os << "|Postprocessor"; if (static_cast<bool>(iface & Interfaces::VectorPostprocessor)) os << "|VectorPostprocessor"; if (static_cast<bool>(iface & Interfaces::InterfaceUserObject)) os << "|InterfaceUserObject"; if (static_cast<bool>(iface & Interfaces::Reporter)) os << "|Reporter"; os << ")"; return os; } bool AttribTagBase::isMatch(const Attribute & other) const { auto a = dynamic_cast<const AttribTagBase *>(&other); if (!a) return false; if (a->_vals.size() == 0) return true; // the condition is empty tags - which we take to mean any tag should match // return true if any single tag matches between the two attribute objects for (auto val : _vals) if (std::find(a->_vals.begin(), a->_vals.end(), val) != a->_vals.end()) return true; return false; } bool AttribTagBase::isEqual(const Attribute & other) const { auto a = dynamic_cast<const AttribTagBase *>(&other); if (!a || a->_vals.size() != _vals.size()) return false; for (size_t i = 0; i < a->_vals.size(); i++) if (a->_vals[i] != _vals[i]) return false; return true; } void AttribMatrixTags::initFrom(const MooseObject * obj) { _vals.clear(); auto t = dynamic_cast<const TaggingInterface *>(obj); if (t) { for (auto & tag : t->getMatrixTags()) _vals.push_back(static_cast<int>(tag)); } } void AttribVectorTags::initFrom(const MooseObject * obj) { _vals.clear(); auto t = dynamic_cast<const TaggingInterface *>(obj); if (t) { for (auto & tag : t->getVectorTags()) _vals.push_back(static_cast<int>(tag)); } } void AttribExecOns::initFrom(const MooseObject * obj) { _vals.clear(); auto sup = dynamic_cast<const SetupInterface *>(obj); if (sup) { auto e = sup->getExecuteOnEnum(); for (auto & on : e.items()) if (e.contains(on)) _vals.push_back(on); } } bool AttribExecOns::isMatch(const Attribute & other) const { auto a = dynamic_cast<const AttribExecOns *>(&other); if (!a || a->_vals.size() < 1) return false; auto cond = a->_vals[0]; if (cond == Moose::ALL) return true; for (auto val : _vals) if (val == Moose::ALL || val == cond) return true; return false; } bool AttribExecOns::isEqual(const Attribute & other) const { auto a = dynamic_cast<const AttribExecOns *>(&other); if (!a || a->_vals.size() != _vals.size()) return false; for (size_t i = 0; i < a->_vals.size(); i++) if (a->_vals[i] != _vals[i]) return false; return true; } void AttribSubdomains::initFrom(const MooseObject * obj) { _vals.clear(); auto blk = dynamic_cast<const BlockRestrictable *>(obj); if (blk && blk->blockRestricted()) { for (auto id : blk->blockIDs()) _vals.push_back(id); } else _vals.push_back(Moose::ANY_BLOCK_ID); } bool AttribSubdomains::isMatch(const Attribute & other) const { auto a = dynamic_cast<const AttribSubdomains *>(&other); if (!a || a->_vals.size() < 1) return false; auto cond = a->_vals[0]; if (cond == Moose::ANY_BLOCK_ID) return true; else if (cond == Moose::INVALID_BLOCK_ID) return false; for (auto id : _vals) { if (id == cond || id == Moose::ANY_BLOCK_ID) return true; } return false; } bool AttribSubdomains::isEqual(const Attribute & other) const { auto a = dynamic_cast<const AttribSubdomains *>(&other); if (!a || a->_vals.size() != _vals.size()) return false; for (size_t i = 0; i < a->_vals.size(); i++) if (a->_vals[i] != _vals[i]) return false; return true; } void AttribBoundaries::initFrom(const MooseObject * obj) { _vals.clear(); auto bnd = dynamic_cast<const BoundaryRestrictable *>(obj); if (bnd && bnd->boundaryRestricted()) { for (auto & bound : bnd->boundaryIDs()) _vals.push_back(bound); } else _vals.push_back(Moose::ANY_BOUNDARY_ID); } bool AttribBoundaries::isMatch(const Attribute & other) const { auto a = dynamic_cast<const AttribBoundaries *>(&other); if (!a || a->_vals.size() < 1) return false; // return true if a single tag matches between the two attribute objects for (auto val : _vals) { if (!a->_must_be_restricted && (val == Moose::ANY_BOUNDARY_ID)) return true; if (std::find(a->_vals.begin(), a->_vals.end(), val) != a->_vals.end()) return true; else if (std::find(a->_vals.begin(), a->_vals.end(), Moose::ANY_BOUNDARY_ID) != a->_vals.end()) return true; } return false; } bool AttribBoundaries::isEqual(const Attribute & other) const { auto a = dynamic_cast<const AttribBoundaries *>(&other); if (!a || a->_vals.size() != _vals.size()) return false; for (size_t i = 0; i < a->_vals.size(); i++) if (a->_vals[i] != _vals[i]) return false; return true; } void AttribThread::initFrom(const MooseObject * obj) { _val = obj->getParam<THREAD_ID>("_tid"); } bool AttribThread::isMatch(const Attribute & other) const { auto a = dynamic_cast<const AttribThread *>(&other); return a && (a->_val == _val); } bool AttribThread::isEqual(const Attribute & other) const { return isMatch(other); } void AttribSysNum::initFrom(const MooseObject * obj) { auto * sys = obj->getParam<SystemBase *>("_sys"); if (sys) _val = sys->number(); } bool AttribSysNum::isMatch(const Attribute & other) const { auto a = dynamic_cast<const AttribSysNum *>(&other); return a && (a->_val == _val); } bool AttribSysNum::isEqual(const Attribute & other) const { return isMatch(other); } void AttribPreIC::initFrom(const MooseObject * /*obj*/) { } bool AttribPreIC::isMatch(const Attribute & other) const { auto a = dynamic_cast<const AttribPreIC *>(&other); return a && (a->_val == _val); } bool AttribPreIC::isEqual(const Attribute & other) const { return isMatch(other); } void AttribPreAux::initFrom(const MooseObject * /*obj*/) { } bool AttribPreAux::isMatch(const Attribute & other) const { auto a = dynamic_cast<const AttribPreAux *>(&other); return a && (a->_val == _val); } bool AttribPreAux::isEqual(const Attribute & other) const { return isMatch(other); } void AttribPostAux::initFrom(const MooseObject * /*obj*/) { } bool AttribPostAux::isMatch(const Attribute & other) const { auto a = dynamic_cast<const AttribPostAux *>(&other); return a && (a->_val == _val); } bool AttribPostAux::isEqual(const Attribute & other) const { return isMatch(other); } void AttribName::initFrom(const MooseObject * obj) { _val = obj->name(); } bool AttribName::isMatch(const Attribute & other) const { auto a = dynamic_cast<const AttribName *>(&other); return a && (a->_val == _val); } bool AttribName::isEqual(const Attribute & other) const { return isMatch(other); } void AttribSystem::initFrom(const MooseObject * obj) { if (!obj->isParamValid("_moose_warehouse_system_name")) mooseError("The base objects supplied to the TheWarehouse must call " "'registerSystemAttributeName' method in the validParams function."); _val = obj->getParam<std::string>("_moose_warehouse_system_name"); } bool AttribSystem::isMatch(const Attribute & other) const { auto a = dynamic_cast<const AttribSystem *>(&other); return a && (a->_val == _val); } bool AttribSystem::isEqual(const Attribute & other) const { return isMatch(other); } void AttribVar::initFrom(const MooseObject * obj) { auto vi = dynamic_cast<const MooseVariableInterface<Real> *>(obj); if (vi) _val = static_cast<int>(vi->mooseVariableBase()->number()); } bool AttribVar::isMatch(const Attribute & other) const { auto a = dynamic_cast<const AttribVar *>(&other); return a && (a->_val == _val); } bool AttribVar::isEqual(const Attribute & other) const { return isMatch(other); } void AttribInterfaces::initFrom(const MooseObject * obj) { _val = 0; // clang-format off _val |= (unsigned int)Interfaces::UserObject * (dynamic_cast<const UserObject *>(obj) != nullptr); _val |= (unsigned int)Interfaces::ElementUserObject * (dynamic_cast<const ElementUserObject *>(obj) != nullptr); _val |= (unsigned int)Interfaces::SideUserObject * (dynamic_cast<const SideUserObject *>(obj) != nullptr); _val |= (unsigned int)Interfaces::InternalSideUserObject * (dynamic_cast<const InternalSideUserObject *>(obj) != nullptr); _val |= (unsigned int)Interfaces::InterfaceUserObject * (dynamic_cast<const InterfaceUserObject *>(obj) != nullptr); _val |= (unsigned int)Interfaces::NodalUserObject * (dynamic_cast<const NodalUserObject *>(obj) != nullptr); _val |= (unsigned int)Interfaces::GeneralUserObject * (dynamic_cast<const GeneralUserObject *>(obj) != nullptr); _val |= (unsigned int)Interfaces::ThreadedGeneralUserObject * (dynamic_cast<const ThreadedGeneralUserObject *>(obj) != nullptr); _val |= (unsigned int)Interfaces::ShapeElementUserObject * (dynamic_cast<const ShapeElementUserObject *>(obj) != nullptr); _val |= (unsigned int)Interfaces::ShapeSideUserObject * (dynamic_cast<const ShapeSideUserObject *>(obj) != nullptr); _val |= (unsigned int)Interfaces::Postprocessor * (dynamic_cast<const Postprocessor *>(obj) != nullptr); _val |= (unsigned int)Interfaces::VectorPostprocessor * (dynamic_cast<const VectorPostprocessor *>(obj) != nullptr); _val |= (unsigned int)Interfaces::BlockRestrictable * (dynamic_cast<const BlockRestrictable *>(obj) != nullptr); _val |= (unsigned int)Interfaces::BoundaryRestrictable * (dynamic_cast<const BoundaryRestrictable *>(obj) != nullptr); _val |= (unsigned int)Interfaces::Reporter * (dynamic_cast<const Reporter *>(obj) != nullptr); // clang-format on } bool AttribInterfaces::isMatch(const Attribute & other) const { auto a = dynamic_cast<const AttribInterfaces *>(&other); return a && (a->_val & _val); } bool AttribInterfaces::isEqual(const Attribute & other) const { auto a = dynamic_cast<const AttribInterfaces *>(&other); return a && (a->_val == _val); }
Update the TheWarehouse with an interface attribute for Reporter objects
Update the TheWarehouse with an interface attribute for Reporter objects
C++
lgpl-2.1
milljm/moose,idaholab/moose,bwspenc/moose,harterj/moose,idaholab/moose,idaholab/moose,milljm/moose,SudiptaBiswas/moose,laagesen/moose,SudiptaBiswas/moose,SudiptaBiswas/moose,laagesen/moose,jessecarterMOOSE/moose,milljm/moose,andrsd/moose,sapitts/moose,dschwen/moose,sapitts/moose,andrsd/moose,idaholab/moose,laagesen/moose,harterj/moose,bwspenc/moose,lindsayad/moose,harterj/moose,nuclear-wizard/moose,laagesen/moose,jessecarterMOOSE/moose,bwspenc/moose,lindsayad/moose,andrsd/moose,nuclear-wizard/moose,bwspenc/moose,dschwen/moose,SudiptaBiswas/moose,SudiptaBiswas/moose,harterj/moose,andrsd/moose,jessecarterMOOSE/moose,milljm/moose,lindsayad/moose,jessecarterMOOSE/moose,bwspenc/moose,sapitts/moose,milljm/moose,dschwen/moose,dschwen/moose,lindsayad/moose,andrsd/moose,nuclear-wizard/moose,jessecarterMOOSE/moose,nuclear-wizard/moose,idaholab/moose,sapitts/moose,laagesen/moose,lindsayad/moose,harterj/moose,sapitts/moose,dschwen/moose
96acb18c32ed2509c297f6ea40ef0ae391ab289d
chrome/browser/command_updater_unittest.cc
chrome/browser/command_updater_unittest.cc
// Copyright (c) 2006-2008 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 "base/logging.h" #include "chrome/browser/command_updater.h" #include "testing/gtest/include/gtest/gtest.h" class TestingCommandHandlerMock : public CommandUpdater::CommandUpdaterDelegate { public: virtual void ExecuteCommand(int id) { EXPECT_EQ(1, id); } }; class CommandUpdaterTest : public testing::Test { }; class TestingCommandObserverMock : public CommandUpdater::CommandObserver { public: virtual void EnabledStateChangedForCommand(int id, bool enabled) { enabled_ = enabled; } bool enabled() const { return enabled_; } private: bool enabled_; }; TEST_F(CommandUpdaterTest, TestBasicAPI) { TestingCommandHandlerMock handler; CommandUpdater command_updater(&handler); // Unsupported command EXPECT_FALSE(command_updater.SupportsCommand(0)); EXPECT_FALSE(command_updater.IsCommandEnabled(0)); // TestingCommandHandlerMock::ExecuteCommand should not be called, since // the command is not supported. command_updater.ExecuteCommand(0); // Supported, enabled command command_updater.UpdateCommandEnabled(1, true); EXPECT_TRUE(command_updater.SupportsCommand(1)); EXPECT_TRUE(command_updater.IsCommandEnabled(1)); command_updater.ExecuteCommand(1); // Supported, disabled command command_updater.UpdateCommandEnabled(2, false); EXPECT_TRUE(command_updater.SupportsCommand(2)); EXPECT_FALSE(command_updater.IsCommandEnabled(2)); // TestingCommandHandlerMock::ExecuteCommmand should not be called, since // the command_updater is disabled command_updater.ExecuteCommand(2); } TEST_F(CommandUpdaterTest, TestObservers) { TestingCommandHandlerMock handler; CommandUpdater command_updater(&handler); // Create an observer for the command 2 and add it to the controller, then // update the command. TestingCommandObserverMock observer; command_updater.AddCommandObserver(2, &observer); command_updater.UpdateCommandEnabled(2, true); EXPECT_TRUE(observer.enabled()); command_updater.UpdateCommandEnabled(2, false); EXPECT_FALSE(observer.enabled()); // Remove the observer and update the command. command_updater.RemoveCommandObserver(2, &observer); command_updater.UpdateCommandEnabled(2, true); EXPECT_FALSE(observer.enabled()); } TEST_F(CommandUpdaterTest, TestRemoveObserverForUnsupportedCommand) { TestingCommandHandlerMock handler; CommandUpdater command_updater(&handler); // Test removing observers for commands that are unsupported TestingCommandObserverMock observer; command_updater.RemoveCommandObserver(3, &observer); } TEST_F(CommandUpdaterTest, TestAddingNullObserver) { TestingCommandHandlerMock handler; CommandUpdater command_updater(&handler); // Test adding/removing NULL observers command_updater.AddCommandObserver(4, NULL); } TEST_F(CommandUpdaterTest, TestRemovingNullObserver) { TestingCommandHandlerMock handler; CommandUpdater command_updater(&handler); command_updater.RemoveCommandObserver(4, NULL); }
// Copyright (c) 2006-2008 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 "base/logging.h" #include "chrome/browser/command_updater.h" #include "testing/gtest/include/gtest/gtest.h" class TestingCommandHandlerMock : public CommandUpdater::CommandUpdaterDelegate { public: virtual void ExecuteCommand(int id) { EXPECT_EQ(1, id); } }; class CommandUpdaterTest : public testing::Test { }; class TestingCommandObserverMock : public CommandUpdater::CommandObserver { public: virtual void EnabledStateChangedForCommand(int id, bool enabled) { enabled_ = enabled; } bool enabled() const { return enabled_; } private: bool enabled_; }; TEST_F(CommandUpdaterTest, TestBasicAPI) { TestingCommandHandlerMock handler; CommandUpdater command_updater(&handler); // Unsupported command EXPECT_FALSE(command_updater.SupportsCommand(0)); EXPECT_FALSE(command_updater.IsCommandEnabled(0)); // TestingCommandHandlerMock::ExecuteCommand should not be called, since // the command is not supported. command_updater.ExecuteCommand(0); // Supported, enabled command command_updater.UpdateCommandEnabled(1, true); EXPECT_TRUE(command_updater.SupportsCommand(1)); EXPECT_TRUE(command_updater.IsCommandEnabled(1)); command_updater.ExecuteCommand(1); // Supported, disabled command command_updater.UpdateCommandEnabled(2, false); EXPECT_TRUE(command_updater.SupportsCommand(2)); EXPECT_FALSE(command_updater.IsCommandEnabled(2)); // TestingCommandHandlerMock::ExecuteCommmand should not be called, since // the command_updater is disabled command_updater.ExecuteCommand(2); } TEST_F(CommandUpdaterTest, TestObservers) { TestingCommandHandlerMock handler; CommandUpdater command_updater(&handler); // Create an observer for the command 2 and add it to the controller, then // update the command. TestingCommandObserverMock observer; command_updater.AddCommandObserver(2, &observer); command_updater.UpdateCommandEnabled(2, true); EXPECT_TRUE(observer.enabled()); command_updater.UpdateCommandEnabled(2, false); EXPECT_FALSE(observer.enabled()); // Remove the observer and update the command. command_updater.RemoveCommandObserver(2, &observer); command_updater.UpdateCommandEnabled(2, true); EXPECT_FALSE(observer.enabled()); }
Remove unnecessary unit tests (now we're just using ObserverList).
Remove unnecessary unit tests (now we're just using ObserverList). TBR=pinkerton Review URL: http://codereview.chromium.org/18386 git-svn-id: dd90618784b6a4b323ea0c23a071cb1c9e6f2ac7@8336 4ff67af0-8c30-449e-8e8b-ad334ec8d88c
C++
bsd-3-clause
wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser
fbe75033302dcef8f0e5b690a135b4a5736bd17d
svx/source/unodraw/unoctabl.cxx
svx/source/unodraw/unoctabl.cxx
/************************************************************************* * * $RCSfile: unoctabl.cxx,v $ * * $Revision: 1.2 $ * * last change: $Author: ka $ $Date: 2000-11-10 15:13:46 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ /* #ifndef _COM_SUN_STAR_LOADER_XIMPLEMENTATIONLOADER_HPP_ #include <com/sun/star/loader/XImplementationLoader.hpp> #endif #ifndef _COM_SUN_STAR_LOADER_CANNOTACTIVATEFACTORYEXCEPTION_HPP_ #include <com/sun/star/loader/CannotActivateFactoryException.hpp> #endif */ #ifndef INCLUDED_SVTOOLS_PATHOPTIONS_HXX #include <svtools/pathoptions.hxx> #endif #ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_ #include <com/sun/star/lang/XServiceInfo.hpp> #endif #ifndef _COM_SUN_STAR_CONTAINER_XNAMECONTAINER_HPP_ #include <com/sun/star/container/XNameContainer.hpp> #endif #include <cppuhelper/implbase2.hxx> #include "xtable.hxx" using namespace ::com::sun::star; using namespace ::rtl; using namespace ::cppu; class SvxUnoColorTable : public WeakImplHelper2< container::XNameContainer, lang::XServiceInfo > { private: XColorTable* pTable; public: SvxUnoColorTable() throw(); virtual ~SvxUnoColorTable() throw(); // XServiceInfo virtual OUString SAL_CALL getImplementationName( ) throw( uno::RuntimeException ); virtual sal_Bool SAL_CALL supportsService( const OUString& ServiceName ) throw( uno::RuntimeException); virtual uno::Sequence< OUString > SAL_CALL getSupportedServiceNames( ) throw( uno::RuntimeException); static OUString getImplementationName_Static() throw() { return OUString(RTL_CONSTASCII_USTRINGPARAM("com.sun.star.drawing.SvxUnoColorTable")); } static uno::Sequence< OUString > getSupportedServiceNames_Static(void) throw(); // XNameContainer virtual void SAL_CALL insertByName( const OUString& aName, const uno::Any& aElement ) throw( lang::IllegalArgumentException, container::ElementExistException, lang::WrappedTargetException, uno::RuntimeException); virtual void SAL_CALL removeByName( const OUString& Name ) throw( container::NoSuchElementException, lang::WrappedTargetException, uno::RuntimeException); // XNameReplace virtual void SAL_CALL replaceByName( const OUString& aName, const uno::Any& aElement ) throw( lang::IllegalArgumentException, container::NoSuchElementException, lang::WrappedTargetException, uno::RuntimeException); // XNameAccess virtual uno::Any SAL_CALL getByName( const OUString& aName ) throw( container::NoSuchElementException, lang::WrappedTargetException, uno::RuntimeException); virtual uno::Sequence< OUString > SAL_CALL getElementNames( ) throw( uno::RuntimeException); virtual sal_Bool SAL_CALL hasByName( const OUString& aName ) throw( uno::RuntimeException); // XElementAccess virtual uno::Type SAL_CALL getElementType( ) throw( uno::RuntimeException); virtual sal_Bool SAL_CALL hasElements( ) throw( uno::RuntimeException); }; SvxUnoColorTable::SvxUnoColorTable() throw() { pTable = new XColorTable( SvtPathOptions().GetPalettePath() ); } SvxUnoColorTable::~SvxUnoColorTable() throw() { delete pTable; } sal_Bool SAL_CALL SvxUnoColorTable::supportsService( const OUString& ServiceName ) throw(uno::RuntimeException) { uno::Sequence< OUString > aSNL( getSupportedServiceNames() ); const OUString * pArray = aSNL.getConstArray(); for( INT32 i = 0; i < aSNL.getLength(); i++ ) if( pArray[i] == ServiceName ) return TRUE; return FALSE; } OUString SAL_CALL SvxUnoColorTable::getImplementationName() throw( uno::RuntimeException ) { return OUString( RTL_CONSTASCII_USTRINGPARAM("SvxUnoColorTable") ); } uno::Sequence< OUString > SAL_CALL SvxUnoColorTable::getSupportedServiceNames( ) throw( uno::RuntimeException ) { return getSupportedServiceNames_Static(); } uno::Sequence< OUString > SvxUnoColorTable::getSupportedServiceNames_Static(void) throw() { uno::Sequence< OUString > aSNS( 1 ); aSNS.getArray()[0] = OUString( RTL_CONSTASCII_USTRINGPARAM("com.sun.star.drawing.ColorTable" )); return aSNS; } // XNameContainer void SAL_CALL SvxUnoColorTable::insertByName( const OUString& aName, const uno::Any& aElement ) throw( lang::IllegalArgumentException, container::ElementExistException, lang::WrappedTargetException, uno::RuntimeException ) { if( hasByName( aName ) ) throw container::ElementExistException(); INT32 nColor; if( aElement >>= nColor ) throw lang::IllegalArgumentException(); if( pTable ) { XColorEntry* pEntry = new XColorEntry( Color( (ColorData)nColor ), aName ); pTable->Insert( pTable->Count(), pEntry ); } } void SAL_CALL SvxUnoColorTable::removeByName( const OUString& Name ) throw( container::NoSuchElementException, lang::WrappedTargetException, uno::RuntimeException) { long nIndex = pTable ? ((XPropertyTable*)pTable)->Get( Name ) : -1; if( nIndex == -1 ) throw container::NoSuchElementException(); pTable->Remove( nIndex ); } // XNameReplace void SAL_CALL SvxUnoColorTable::replaceByName( const OUString& aName, const uno::Any& aElement ) throw( lang::IllegalArgumentException, container::NoSuchElementException, lang::WrappedTargetException, uno::RuntimeException ) { INT32 nColor; if( aElement >>= nColor ) throw lang::IllegalArgumentException(); long nIndex = pTable ? ((XPropertyTable*)pTable)->Get( aName ) : -1; if( nIndex == -1 ) throw container::NoSuchElementException(); XColorEntry* pEntry = new XColorEntry( Color( (ColorData)nColor ), aName ); delete pTable->Replace( nIndex, pEntry ); } // XNameAccess uno::Any SAL_CALL SvxUnoColorTable::getByName( const OUString& aName ) throw( container::NoSuchElementException, lang::WrappedTargetException, uno::RuntimeException) { long nIndex = pTable ? ((XPropertyTable*)pTable)->Get( aName ) : -1; if( nIndex == -1 ) throw container::NoSuchElementException(); XColorEntry* pEntry = pTable->Get( nIndex ); uno::Any aAny; aAny <<= (sal_Int32) pEntry->GetColor().GetRGBColor(); return aAny; } uno::Sequence< OUString > SAL_CALL SvxUnoColorTable::getElementNames( ) throw( uno::RuntimeException ) { const long nCount = pTable ? pTable->Count() : 0; uno::Sequence< OUString > aSeq( nCount ); OUString* pStrings = aSeq.getArray(); for( long nIndex = 0; nIndex < nCount; nIndex++ ) { XColorEntry* pEntry = pTable->Get( nIndex ); pStrings[nIndex] = pEntry->GetName(); } return aSeq; } sal_Bool SAL_CALL SvxUnoColorTable::hasByName( const OUString& aName ) throw( uno::RuntimeException ) { long nIndex = pTable ? ((XPropertyTable*)pTable)->Get( aName ) : -1; return nIndex != -1; } // XElementAccess uno::Type SAL_CALL SvxUnoColorTable::getElementType( ) throw( uno::RuntimeException ) { return ::getCppuType((const sal_Int32*)0); } sal_Bool SAL_CALL SvxUnoColorTable::hasElements( ) throw( uno::RuntimeException ) { return pTable && pTable->Count() != 0; } /** * Create a colortable */ uno::Reference< uno::XInterface > SAL_CALL SvxUnoColorTable_createInstance(const uno::Reference< lang::XMultiServiceFactory > & rSMgr) throw(uno::Exception) { return *new SvxUnoColorTable(); } // // export this service // #ifndef _COM_SUN_STAR_REGISTRY_XREGISTRYKEY_HPP_ #include <com/sun/star/registry/XRegistryKey.hpp> #endif #ifndef _OSL_DIAGNOSE_H_ #include <osl/diagnose.h> #endif #include <cppuhelper/factory.hxx> #include <uno/lbnames.h> extern "C" { void SAL_CALL component_getImplementationEnvironment( const sal_Char ** ppEnvTypeName, uno_Environment ** ppEnv ) { *ppEnvTypeName = CPPU_CURRENT_LANGUAGE_BINDING_NAME; } sal_Bool SAL_CALL component_writeInfo( void * pServiceManager, void * pRegistryKey ) { if( pRegistryKey ) { try { uno::Reference< registry::XRegistryKey > xNewKey( reinterpret_cast< registry::XRegistryKey * >( pRegistryKey )->createKey( OUString( RTL_CONSTASCII_USTRINGPARAM("/") ) + SvxUnoColorTable::getImplementationName_Static() + OUString(RTL_CONSTASCII_USTRINGPARAM( "/UNO/SERVICES") ) ) ); uno::Sequence< OUString > aServices = SvxUnoColorTable::getSupportedServiceNames_Static(); for( INT32 i = 0; i < aServices.getLength(); i++ ) xNewKey->createKey( aServices.getConstArray()[i]); } catch (registry::InvalidRegistryException &) { OSL_ENSHURE( sal_False, "### InvalidRegistryException!" ); } } return True; } void * SAL_CALL component_getFactory( const sal_Char * pImplName, void * pServiceManager, void * pRegistryKey ) { void * pRet = 0; if( pServiceManager && rtl_str_compare( pImplName, "stardiv.one.drawing.SvxUnoColorTable" ) ) { uno::Reference< lang::XSingleServiceFactory > xFactory( createOneInstanceFactory( reinterpret_cast< lang::XMultiServiceFactory * >( pServiceManager ), SvxUnoColorTable::getImplementationName_Static(), SvxUnoColorTable_createInstance, SvxUnoColorTable::getSupportedServiceNames_Static() ) ); if( xFactory.is()) { xFactory->acquire(); pRet = xFactory.get(); } } return pRet; } }
/************************************************************************* * * $RCSfile: unoctabl.cxx,v $ * * $Revision: 1.3 $ * * last change: $Author: cl $ $Date: 2001-01-12 17:03:44 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ /* #ifndef _COM_SUN_STAR_LOADER_XIMPLEMENTATIONLOADER_HPP_ #include <com/sun/star/loader/XImplementationLoader.hpp> #endif #ifndef _COM_SUN_STAR_LOADER_CANNOTACTIVATEFACTORYEXCEPTION_HPP_ #include <com/sun/star/loader/CannotActivateFactoryException.hpp> #endif */ #ifndef INCLUDED_SVTOOLS_PATHOPTIONS_HXX #include <svtools/pathoptions.hxx> #endif #ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_ #include <com/sun/star/lang/XServiceInfo.hpp> #endif #ifndef _COM_SUN_STAR_CONTAINER_XNAMECONTAINER_HPP_ #include <com/sun/star/container/XNameContainer.hpp> #endif #include <cppuhelper/implbase2.hxx> #include "xtable.hxx" using namespace ::com::sun::star; using namespace ::rtl; using namespace ::cppu; class SvxUnoColorTable : public WeakImplHelper2< container::XNameContainer, lang::XServiceInfo > { private: XColorTable* pTable; public: SvxUnoColorTable() throw(); virtual ~SvxUnoColorTable() throw(); // XServiceInfo virtual OUString SAL_CALL getImplementationName( ) throw( uno::RuntimeException ); virtual sal_Bool SAL_CALL supportsService( const OUString& ServiceName ) throw( uno::RuntimeException); virtual uno::Sequence< OUString > SAL_CALL getSupportedServiceNames( ) throw( uno::RuntimeException); static OUString getImplementationName_Static() throw() { return OUString(RTL_CONSTASCII_USTRINGPARAM("com.sun.star.drawing.SvxUnoColorTable")); } static uno::Sequence< OUString > getSupportedServiceNames_Static(void) throw(); // XNameContainer virtual void SAL_CALL insertByName( const OUString& aName, const uno::Any& aElement ) throw( lang::IllegalArgumentException, container::ElementExistException, lang::WrappedTargetException, uno::RuntimeException); virtual void SAL_CALL removeByName( const OUString& Name ) throw( container::NoSuchElementException, lang::WrappedTargetException, uno::RuntimeException); // XNameReplace virtual void SAL_CALL replaceByName( const OUString& aName, const uno::Any& aElement ) throw( lang::IllegalArgumentException, container::NoSuchElementException, lang::WrappedTargetException, uno::RuntimeException); // XNameAccess virtual uno::Any SAL_CALL getByName( const OUString& aName ) throw( container::NoSuchElementException, lang::WrappedTargetException, uno::RuntimeException); virtual uno::Sequence< OUString > SAL_CALL getElementNames( ) throw( uno::RuntimeException); virtual sal_Bool SAL_CALL hasByName( const OUString& aName ) throw( uno::RuntimeException); // XElementAccess virtual uno::Type SAL_CALL getElementType( ) throw( uno::RuntimeException); virtual sal_Bool SAL_CALL hasElements( ) throw( uno::RuntimeException); }; SvxUnoColorTable::SvxUnoColorTable() throw() { pTable = new XColorTable( SvtPathOptions().GetPalettePath() ); } SvxUnoColorTable::~SvxUnoColorTable() throw() { delete pTable; } sal_Bool SAL_CALL SvxUnoColorTable::supportsService( const OUString& ServiceName ) throw(uno::RuntimeException) { uno::Sequence< OUString > aSNL( getSupportedServiceNames() ); const OUString * pArray = aSNL.getConstArray(); for( INT32 i = 0; i < aSNL.getLength(); i++ ) if( pArray[i] == ServiceName ) return TRUE; return FALSE; } OUString SAL_CALL SvxUnoColorTable::getImplementationName() throw( uno::RuntimeException ) { return OUString( RTL_CONSTASCII_USTRINGPARAM("SvxUnoColorTable") ); } uno::Sequence< OUString > SAL_CALL SvxUnoColorTable::getSupportedServiceNames( ) throw( uno::RuntimeException ) { return getSupportedServiceNames_Static(); } uno::Sequence< OUString > SvxUnoColorTable::getSupportedServiceNames_Static(void) throw() { uno::Sequence< OUString > aSNS( 1 ); aSNS.getArray()[0] = OUString( RTL_CONSTASCII_USTRINGPARAM("com.sun.star.drawing.ColorTable" )); return aSNS; } // XNameContainer void SAL_CALL SvxUnoColorTable::insertByName( const OUString& aName, const uno::Any& aElement ) throw( lang::IllegalArgumentException, container::ElementExistException, lang::WrappedTargetException, uno::RuntimeException ) { if( hasByName( aName ) ) throw container::ElementExistException(); INT32 nColor; if( aElement >>= nColor ) throw lang::IllegalArgumentException(); if( pTable ) { XColorEntry* pEntry = new XColorEntry( Color( (ColorData)nColor ), aName ); pTable->Insert( pTable->Count(), pEntry ); } } void SAL_CALL SvxUnoColorTable::removeByName( const OUString& Name ) throw( container::NoSuchElementException, lang::WrappedTargetException, uno::RuntimeException) { long nIndex = pTable ? ((XPropertyTable*)pTable)->Get( Name ) : -1; if( nIndex == -1 ) throw container::NoSuchElementException(); pTable->Remove( nIndex ); } // XNameReplace void SAL_CALL SvxUnoColorTable::replaceByName( const OUString& aName, const uno::Any& aElement ) throw( lang::IllegalArgumentException, container::NoSuchElementException, lang::WrappedTargetException, uno::RuntimeException ) { INT32 nColor; if( aElement >>= nColor ) throw lang::IllegalArgumentException(); long nIndex = pTable ? ((XPropertyTable*)pTable)->Get( aName ) : -1; if( nIndex == -1 ) throw container::NoSuchElementException(); XColorEntry* pEntry = new XColorEntry( Color( (ColorData)nColor ), aName ); delete pTable->Replace( nIndex, pEntry ); } // XNameAccess uno::Any SAL_CALL SvxUnoColorTable::getByName( const OUString& aName ) throw( container::NoSuchElementException, lang::WrappedTargetException, uno::RuntimeException) { long nIndex = pTable ? ((XPropertyTable*)pTable)->Get( aName ) : -1; if( nIndex == -1 ) throw container::NoSuchElementException(); XColorEntry* pEntry = pTable->Get( nIndex ); uno::Any aAny; aAny <<= (sal_Int32) pEntry->GetColor().GetRGBColor(); return aAny; } uno::Sequence< OUString > SAL_CALL SvxUnoColorTable::getElementNames( ) throw( uno::RuntimeException ) { const long nCount = pTable ? pTable->Count() : 0; uno::Sequence< OUString > aSeq( nCount ); OUString* pStrings = aSeq.getArray(); for( long nIndex = 0; nIndex < nCount; nIndex++ ) { XColorEntry* pEntry = pTable->Get( nIndex ); pStrings[nIndex] = pEntry->GetName(); } return aSeq; } sal_Bool SAL_CALL SvxUnoColorTable::hasByName( const OUString& aName ) throw( uno::RuntimeException ) { long nIndex = pTable ? ((XPropertyTable*)pTable)->Get( aName ) : -1; return nIndex != -1; } // XElementAccess uno::Type SAL_CALL SvxUnoColorTable::getElementType( ) throw( uno::RuntimeException ) { return ::getCppuType((const sal_Int32*)0); } sal_Bool SAL_CALL SvxUnoColorTable::hasElements( ) throw( uno::RuntimeException ) { return pTable && pTable->Count() != 0; } /** * Create a colortable */ uno::Reference< uno::XInterface > SAL_CALL SvxUnoColorTable_createInstance(const uno::Reference< lang::XMultiServiceFactory > & rSMgr) throw(uno::Exception) { return *new SvxUnoColorTable(); } // // export this service // #ifndef _COM_SUN_STAR_REGISTRY_XREGISTRYKEY_HPP_ #include <com/sun/star/registry/XRegistryKey.hpp> #endif #ifndef _OSL_DIAGNOSE_H_ #include <osl/diagnose.h> #endif #include <cppuhelper/factory.hxx> #include <uno/lbnames.h> extern "C" { void SAL_CALL component_getImplementationEnvironment( const sal_Char ** ppEnvTypeName, uno_Environment ** ppEnv ) { *ppEnvTypeName = CPPU_CURRENT_LANGUAGE_BINDING_NAME; } sal_Bool SAL_CALL component_writeInfo( void * pServiceManager, void * pRegistryKey ) { if( pRegistryKey ) { try { uno::Reference< registry::XRegistryKey > xNewKey( reinterpret_cast< registry::XRegistryKey * >( pRegistryKey )->createKey( OUString( RTL_CONSTASCII_USTRINGPARAM("/") ) + SvxUnoColorTable::getImplementationName_Static() + OUString(RTL_CONSTASCII_USTRINGPARAM( "/UNO/SERVICES") ) ) ); uno::Sequence< OUString > aServices = SvxUnoColorTable::getSupportedServiceNames_Static(); for( INT32 i = 0; i < aServices.getLength(); i++ ) xNewKey->createKey( aServices.getConstArray()[i]); } catch (registry::InvalidRegistryException &) { OSL_ENSHURE( sal_False, "### InvalidRegistryException!" ); } } return True; } void * SAL_CALL component_getFactory( const sal_Char * pImplName, void * pServiceManager, void * pRegistryKey ) { void * pRet = 0; if( pServiceManager && rtl_str_compare( pImplName, "stardiv.one.drawing.SvxUnoColorTable" ) ) { uno::Reference< lang::XSingleServiceFactory > xFactory( createSingleFactory( reinterpret_cast< lang::XMultiServiceFactory * >( pServiceManager ), SvxUnoColorTable::getImplementationName_Static(), SvxUnoColorTable_createInstance, SvxUnoColorTable::getSupportedServiceNames_Static() ) ); if( xFactory.is()) { xFactory->acquire(); pRet = xFactory.get(); } } return pRet; } }
change createOnInstanceFactory to createSingleFactory
change createOnInstanceFactory to createSingleFactory
C++
mpl-2.0
JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core
cde1544744982e075e6b837e105a5e52f38c45ad
chrome/browser/gtk/page_info_window_gtk.cc
chrome/browser/gtk/page_info_window_gtk.cc
// Copyright (c) 2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <gtk/gtk.h> #include "build/build_config.h" #include "app/l10n_util.h" #include "app/resource_bundle.h" #include "base/compiler_specific.h" #include "base/utf_string_conversions.h" #include "chrome/browser/certificate_viewer.h" #include "chrome/browser/gtk/gtk_util.h" #include "chrome/browser/page_info_model.h" #include "chrome/browser/page_info_window.h" #include "grit/generated_resources.h" #include "grit/locale_settings.h" #include "grit/theme_resources.h" namespace { enum { RESPONSE_SHOW_CERT_INFO = 0, }; class PageInfoWindowGtk : public PageInfoModel::PageInfoModelObserver { public: PageInfoWindowGtk(gfx::NativeWindow parent, Profile* profile, const GURL& url, const NavigationEntry::SSLStatus& ssl, bool show_history); ~PageInfoWindowGtk(); // PageInfoModelObserver implementation: virtual void ModelChanged(); // Shows the page info window. void Show(); // Shows the certificate info window. void ShowCertDialog(); GtkWidget* widget() { return dialog_; } private: // Layouts the different sections retrieved from the model. void InitContents(); // Returns a widget that contains the UI for the passed |section|. GtkWidget* CreateSection(const PageInfoModel::SectionInfo& section); // The model containing the different sections to display. PageInfoModel model_; // The page info dialog. GtkWidget* dialog_; // The url for this dialog. Should be unique among active dialogs. GURL url_; // The virtual box containing the sections. GtkWidget* contents_; // The id of the certificate for this page. int cert_id_; DISALLOW_COPY_AND_ASSIGN(PageInfoWindowGtk); }; // We only show one page info per URL (keyed on url.spec()). typedef std::map<std::string, PageInfoWindowGtk*> PageInfoWindowMap; PageInfoWindowMap g_page_info_window_map; // Button callbacks. void OnDialogResponse(GtkDialog* dialog, gint response_id, PageInfoWindowGtk* page_info) { if (response_id == RESPONSE_SHOW_CERT_INFO) { page_info->ShowCertDialog(); } else { // "Close" was clicked. gtk_widget_destroy(GTK_WIDGET(dialog)); } } void OnDestroy(GtkDialog* dialog, PageInfoWindowGtk* page_info) { delete page_info; } //////////////////////////////////////////////////////////////////////////////// // PageInfoWindowGtk, public: PageInfoWindowGtk::PageInfoWindowGtk(gfx::NativeWindow parent, Profile* profile, const GURL& url, const NavigationEntry::SSLStatus& ssl, bool show_history) : ALLOW_THIS_IN_INITIALIZER_LIST(model_(profile, url, ssl, show_history, this)), url_(url), contents_(NULL), cert_id_(ssl.cert_id()) { dialog_ = gtk_dialog_new_with_buttons( l10n_util::GetStringUTF8(IDS_PAGEINFO_WINDOW_TITLE).c_str(), parent, // Non-modal. GTK_DIALOG_NO_SEPARATOR, NULL); if (cert_id_) { gtk_dialog_add_button( GTK_DIALOG(dialog_), l10n_util::GetStringUTF8(IDS_PAGEINFO_CERT_INFO_BUTTON).c_str(), RESPONSE_SHOW_CERT_INFO); } gtk_dialog_add_button(GTK_DIALOG(dialog_), GTK_STOCK_CLOSE, GTK_RESPONSE_CLOSE); gtk_dialog_set_default_response(GTK_DIALOG(dialog_), GTK_RESPONSE_CLOSE); gtk_box_set_spacing(GTK_BOX(GTK_DIALOG(dialog_)->vbox), gtk_util::kContentAreaSpacing); g_signal_connect(dialog_, "response", G_CALLBACK(OnDialogResponse), this); g_signal_connect(dialog_, "destroy", G_CALLBACK(OnDestroy), this); InitContents(); g_page_info_window_map[url.spec()] = this; } PageInfoWindowGtk::~PageInfoWindowGtk() { g_page_info_window_map.erase(url_.spec()); } void PageInfoWindowGtk::ModelChanged() { InitContents(); } GtkWidget* PageInfoWindowGtk::CreateSection( const PageInfoModel::SectionInfo& section) { GtkWidget* vbox = gtk_vbox_new(FALSE, gtk_util::kControlSpacing); GtkWidget* label = gtk_label_new(UTF16ToUTF8(section.title).c_str()); PangoAttrList* attributes = pango_attr_list_new(); pango_attr_list_insert(attributes, pango_attr_weight_new(PANGO_WEIGHT_BOLD)); gtk_label_set_attributes(GTK_LABEL(label), attributes); pango_attr_list_unref(attributes); gtk_misc_set_alignment(GTK_MISC(label), 0, 0); gtk_box_pack_start(GTK_BOX(vbox), label, FALSE, FALSE, 0); GtkWidget* section_box = gtk_hbox_new(FALSE, 0); ResourceBundle& rb = ResourceBundle::GetSharedInstance(); GtkWidget* image = gtk_image_new_from_pixbuf( section.state == PageInfoModel::SECTION_STATE_OK ? rb.GetPixbufNamed(IDR_PAGEINFO_GOOD) : rb.GetPixbufNamed(IDR_PAGEINFO_BAD)); gtk_box_pack_start(GTK_BOX(section_box), image, FALSE, FALSE, gtk_util::kControlSpacing); gtk_misc_set_alignment(GTK_MISC(image), 0, 0); GtkWidget* text_box = gtk_vbox_new(FALSE, gtk_util::kControlSpacing); if (!section.headline.empty()) { label = gtk_label_new(UTF16ToUTF8(section.headline).c_str()); gtk_misc_set_alignment(GTK_MISC(label), 0, 0); gtk_box_pack_start(GTK_BOX(text_box), label, FALSE, FALSE, 0); } label = gtk_label_new(UTF16ToUTF8(section.description).c_str()); gtk_misc_set_alignment(GTK_MISC(label), 0, 0); gtk_label_set_line_wrap(GTK_LABEL(label), TRUE); // Allow linebreaking in the middle of words if necessary, so that extremely // long hostnames (longer than one line) will still be completely shown. gtk_label_set_line_wrap_mode(GTK_LABEL(label), PANGO_WRAP_WORD_CHAR); gtk_box_pack_start(GTK_BOX(text_box), label, FALSE, FALSE, 0); gtk_widget_set_size_request(label, 400, -1); gtk_box_pack_start(GTK_BOX(section_box), text_box, TRUE, TRUE, 0); gtk_box_pack_start(GTK_BOX(vbox), section_box, TRUE, TRUE, 0); return vbox; } void PageInfoWindowGtk::InitContents() { if (contents_) gtk_widget_destroy(contents_); contents_ = gtk_vbox_new(FALSE, gtk_util::kContentAreaSpacing); for (int i = 0; i < model_.GetSectionCount(); i++) { gtk_box_pack_start(GTK_BOX(contents_), CreateSection(model_.GetSectionInfo(i)), FALSE, FALSE, 0); } gtk_widget_show_all(contents_); gtk_container_add(GTK_CONTAINER(GTK_DIALOG(dialog_)->vbox), contents_); } void PageInfoWindowGtk::Show() { gtk_widget_show(dialog_); } void PageInfoWindowGtk::ShowCertDialog() { ShowCertificateViewerByID(GTK_WINDOW(dialog_), cert_id_); } } // namespace namespace browser { void ShowPageInfo(gfx::NativeWindow parent, Profile* profile, const GURL& url, const NavigationEntry::SSLStatus& ssl, bool show_history) { PageInfoWindowMap::iterator iter = g_page_info_window_map.find(url.spec()); if (iter != g_page_info_window_map.end()) { gtk_window_present(GTK_WINDOW(iter->second->widget())); return; } PageInfoWindowGtk* page_info_window = new PageInfoWindowGtk(parent, profile, url, ssl, show_history); page_info_window->Show(); } } // namespace browser
// Copyright (c) 2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <gtk/gtk.h> #include "build/build_config.h" #include "app/l10n_util.h" #include "app/resource_bundle.h" #include "base/compiler_specific.h" #include "base/utf_string_conversions.h" #include "chrome/browser/certificate_viewer.h" #include "chrome/browser/gtk/gtk_util.h" #include "chrome/browser/page_info_model.h" #include "chrome/browser/page_info_window.h" #include "grit/generated_resources.h" #include "grit/locale_settings.h" #include "grit/theme_resources.h" namespace { enum { RESPONSE_SHOW_CERT_INFO = 0, }; class PageInfoWindowGtk : public PageInfoModel::PageInfoModelObserver { public: PageInfoWindowGtk(gfx::NativeWindow parent, Profile* profile, const GURL& url, const NavigationEntry::SSLStatus& ssl, bool show_history); ~PageInfoWindowGtk(); // PageInfoModelObserver implementation: virtual void ModelChanged(); // Shows the page info window. void Show(); // Shows the certificate info window. void ShowCertDialog(); GtkWidget* widget() { return dialog_; } private: // Layouts the different sections retrieved from the model. void InitContents(); // Returns a widget that contains the UI for the passed |section|. GtkWidget* CreateSection(const PageInfoModel::SectionInfo& section); // The model containing the different sections to display. PageInfoModel model_; // The page info dialog. GtkWidget* dialog_; // The url for this dialog. Should be unique among active dialogs. GURL url_; // The virtual box containing the sections. GtkWidget* contents_; // The id of the certificate for this page. int cert_id_; DISALLOW_COPY_AND_ASSIGN(PageInfoWindowGtk); }; // We only show one page info per URL (keyed on url.spec()). typedef std::map<std::string, PageInfoWindowGtk*> PageInfoWindowMap; PageInfoWindowMap g_page_info_window_map; // Button callbacks. void OnDialogResponse(GtkDialog* dialog, gint response_id, PageInfoWindowGtk* page_info) { if (response_id == RESPONSE_SHOW_CERT_INFO) { page_info->ShowCertDialog(); } else { // "Close" was clicked. gtk_widget_destroy(GTK_WIDGET(dialog)); } } void OnDestroy(GtkDialog* dialog, PageInfoWindowGtk* page_info) { delete page_info; } //////////////////////////////////////////////////////////////////////////////// // PageInfoWindowGtk, public: PageInfoWindowGtk::PageInfoWindowGtk(gfx::NativeWindow parent, Profile* profile, const GURL& url, const NavigationEntry::SSLStatus& ssl, bool show_history) : ALLOW_THIS_IN_INITIALIZER_LIST(model_(profile, url, ssl, show_history, this)), url_(url), contents_(NULL), cert_id_(ssl.cert_id()) { dialog_ = gtk_dialog_new_with_buttons( l10n_util::GetStringUTF8(IDS_PAGEINFO_WINDOW_TITLE).c_str(), parent, // Non-modal. GTK_DIALOG_NO_SEPARATOR, NULL); if (cert_id_) { gtk_dialog_add_button( GTK_DIALOG(dialog_), l10n_util::GetStringUTF8(IDS_PAGEINFO_CERT_INFO_BUTTON).c_str(), RESPONSE_SHOW_CERT_INFO); } gtk_dialog_add_button(GTK_DIALOG(dialog_), GTK_STOCK_CLOSE, GTK_RESPONSE_CLOSE); gtk_dialog_set_default_response(GTK_DIALOG(dialog_), GTK_RESPONSE_CLOSE); gtk_box_set_spacing(GTK_BOX(GTK_DIALOG(dialog_)->vbox), gtk_util::kContentAreaSpacing); g_signal_connect(dialog_, "response", G_CALLBACK(OnDialogResponse), this); g_signal_connect(dialog_, "destroy", G_CALLBACK(OnDestroy), this); InitContents(); g_page_info_window_map[url.spec()] = this; } PageInfoWindowGtk::~PageInfoWindowGtk() { g_page_info_window_map.erase(url_.spec()); } void PageInfoWindowGtk::ModelChanged() { InitContents(); } GtkWidget* PageInfoWindowGtk::CreateSection( const PageInfoModel::SectionInfo& section) { GtkWidget* vbox = gtk_vbox_new(FALSE, gtk_util::kControlSpacing); GtkWidget* label = gtk_label_new(UTF16ToUTF8(section.title).c_str()); PangoAttrList* attributes = pango_attr_list_new(); pango_attr_list_insert(attributes, pango_attr_weight_new(PANGO_WEIGHT_BOLD)); gtk_label_set_attributes(GTK_LABEL(label), attributes); pango_attr_list_unref(attributes); gtk_misc_set_alignment(GTK_MISC(label), 0, 0); gtk_box_pack_start(GTK_BOX(vbox), label, FALSE, FALSE, 0); GtkWidget* section_box = gtk_hbox_new(FALSE, 0); ResourceBundle& rb = ResourceBundle::GetSharedInstance(); GtkWidget* image = gtk_image_new_from_pixbuf( section.state == PageInfoModel::SECTION_STATE_OK ? rb.GetPixbufNamed(IDR_PAGEINFO_GOOD) : rb.GetPixbufNamed(IDR_PAGEINFO_WARNING_MAJOR)); gtk_box_pack_start(GTK_BOX(section_box), image, FALSE, FALSE, gtk_util::kControlSpacing); gtk_misc_set_alignment(GTK_MISC(image), 0, 0); GtkWidget* text_box = gtk_vbox_new(FALSE, gtk_util::kControlSpacing); if (!section.headline.empty()) { label = gtk_label_new(UTF16ToUTF8(section.headline).c_str()); gtk_misc_set_alignment(GTK_MISC(label), 0, 0); gtk_box_pack_start(GTK_BOX(text_box), label, FALSE, FALSE, 0); } label = gtk_label_new(UTF16ToUTF8(section.description).c_str()); gtk_misc_set_alignment(GTK_MISC(label), 0, 0); gtk_label_set_line_wrap(GTK_LABEL(label), TRUE); // Allow linebreaking in the middle of words if necessary, so that extremely // long hostnames (longer than one line) will still be completely shown. gtk_label_set_line_wrap_mode(GTK_LABEL(label), PANGO_WRAP_WORD_CHAR); gtk_box_pack_start(GTK_BOX(text_box), label, FALSE, FALSE, 0); gtk_widget_set_size_request(label, 400, -1); gtk_box_pack_start(GTK_BOX(section_box), text_box, TRUE, TRUE, 0); gtk_box_pack_start(GTK_BOX(vbox), section_box, TRUE, TRUE, 0); return vbox; } void PageInfoWindowGtk::InitContents() { if (contents_) gtk_widget_destroy(contents_); contents_ = gtk_vbox_new(FALSE, gtk_util::kContentAreaSpacing); for (int i = 0; i < model_.GetSectionCount(); i++) { gtk_box_pack_start(GTK_BOX(contents_), CreateSection(model_.GetSectionInfo(i)), FALSE, FALSE, 0); } gtk_widget_show_all(contents_); gtk_container_add(GTK_CONTAINER(GTK_DIALOG(dialog_)->vbox), contents_); } void PageInfoWindowGtk::Show() { gtk_widget_show(dialog_); } void PageInfoWindowGtk::ShowCertDialog() { ShowCertificateViewerByID(GTK_WINDOW(dialog_), cert_id_); } } // namespace namespace browser { void ShowPageInfo(gfx::NativeWindow parent, Profile* profile, const GURL& url, const NavigationEntry::SSLStatus& ssl, bool show_history) { PageInfoWindowMap::iterator iter = g_page_info_window_map.find(url.spec()); if (iter != g_page_info_window_map.end()) { gtk_window_present(GTK_WINDOW(iter->second->widget())); return; } PageInfoWindowGtk* page_info_window = new PageInfoWindowGtk(parent, profile, url, ssl, show_history); page_info_window->Show(); } } // namespace browser
Update page-info icons to match behavior in page_info_window_view.cc.
[gtk] Update page-info icons to match behavior in page_info_window_view.cc. BUG=52916 TEST=Verify correct page-info icons in GTK. Review URL: http://codereview.chromium.org/3502007 git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@60730 0039d316-1c4b-4281-b951-d872f2087c98
C++
bsd-3-clause
yitian134/chromium,ropik/chromium,adobe/chromium,adobe/chromium,Crystalnix/house-of-life-chromium,ropik/chromium,Crystalnix/house-of-life-chromium,adobe/chromium,ropik/chromium,gavinp/chromium,gavinp/chromium,yitian134/chromium,ropik/chromium,adobe/chromium,yitian134/chromium,gavinp/chromium,adobe/chromium,adobe/chromium,adobe/chromium,adobe/chromium,Crystalnix/house-of-life-chromium,adobe/chromium,yitian134/chromium,Crystalnix/house-of-life-chromium,Crystalnix/house-of-life-chromium,gavinp/chromium,gavinp/chromium,Crystalnix/house-of-life-chromium,ropik/chromium,gavinp/chromium,Crystalnix/house-of-life-chromium,yitian134/chromium,yitian134/chromium,gavinp/chromium,Crystalnix/house-of-life-chromium,ropik/chromium,gavinp/chromium,Crystalnix/house-of-life-chromium,Crystalnix/house-of-life-chromium,yitian134/chromium,yitian134/chromium,ropik/chromium,Crystalnix/house-of-life-chromium,gavinp/chromium,yitian134/chromium,ropik/chromium,adobe/chromium,gavinp/chromium,adobe/chromium,yitian134/chromium,ropik/chromium
e033960222063249ba38f9ee9251c0b02115101c
chrome/browser/views/hung_renderer_view.cc
chrome/browser/views/hung_renderer_view.cc
// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/hung_renderer_dialog.h" #include "app/l10n_util.h" #include "app/resource_bundle.h" #include "base/i18n/rtl.h" #include "base/utf_string_conversions.h" #include "chrome/browser/browser_list.h" #include "chrome/browser/renderer_host/render_process_host.h" #include "chrome/browser/renderer_host/render_view_host.h" #include "chrome/browser/tab_contents/tab_contents.h" #include "chrome/common/chrome_constants.h" #include "chrome/common/logging_chrome.h" #include "chrome/common/result_codes.h" #include "gfx/canvas.h" #include "grit/chromium_strings.h" #include "grit/generated_resources.h" #include "grit/theme_resources.h" #include "views/grid_layout.h" #include "views/controls/button/native_button.h" #include "views/controls/image_view.h" #include "views/controls/label.h" #include "views/controls/table/group_table_view.h" #include "views/standard_layout.h" #include "views/window/client_view.h" #include "views/window/dialog_delegate.h" #include "views/window/window.h" class HungRendererDialogView; namespace { // We only support showing one of these at a time per app. HungRendererDialogView* g_instance = NULL; } /////////////////////////////////////////////////////////////////////////////// // HungPagesTableModel class HungPagesTableModel : public views::GroupTableModel { public: HungPagesTableModel(); virtual ~HungPagesTableModel(); void InitForTabContents(TabContents* hung_contents); // Overridden from views::GroupTableModel: virtual int RowCount(); virtual std::wstring GetText(int row, int column_id); virtual SkBitmap GetIcon(int row); virtual void SetObserver(TableModelObserver* observer); virtual void GetGroupRangeForItem(int item, views::GroupRange* range); private: typedef std::vector<TabContents*> TabContentsVector; TabContentsVector tab_contentses_; TableModelObserver* observer_; DISALLOW_COPY_AND_ASSIGN(HungPagesTableModel); }; /////////////////////////////////////////////////////////////////////////////// // HungPagesTableModel, public: HungPagesTableModel::HungPagesTableModel() : observer_(NULL) { } HungPagesTableModel::~HungPagesTableModel() { } void HungPagesTableModel::InitForTabContents(TabContents* hung_contents) { tab_contentses_.clear(); for (TabContentsIterator it; !it.done(); ++it) { if (it->GetRenderProcessHost() == hung_contents->GetRenderProcessHost()) tab_contentses_.push_back(*it); } // The world is different. if (observer_) observer_->OnModelChanged(); } /////////////////////////////////////////////////////////////////////////////// // HungPagesTableModel, views::GroupTableModel implementation: int HungPagesTableModel::RowCount() { return static_cast<int>(tab_contentses_.size()); } std::wstring HungPagesTableModel::GetText(int row, int column_id) { DCHECK(row >= 0 && row < RowCount()); std::wstring title = UTF16ToWideHack(tab_contentses_[row]->GetTitle()); if (title.empty()) title = UTF16ToWideHack(TabContents::GetDefaultTitle()); // TODO(xji): Consider adding a special case if the title text is a URL, // since those should always have LTR directionality. Please refer to // http://crbug.com/6726 for more information. base::i18n::AdjustStringForLocaleDirection(title, &title); return title; } SkBitmap HungPagesTableModel::GetIcon(int row) { DCHECK(row >= 0 && row < RowCount()); return tab_contentses_.at(row)->GetFavIcon(); } void HungPagesTableModel::SetObserver(TableModelObserver* observer) { observer_ = observer; } void HungPagesTableModel::GetGroupRangeForItem(int item, views::GroupRange* range) { DCHECK(range); range->start = 0; range->length = RowCount(); } /////////////////////////////////////////////////////////////////////////////// // HungRendererDialogView class HungRendererDialogView : public views::View, public views::DialogDelegate, public views::ButtonListener { public: HungRendererDialogView(); ~HungRendererDialogView(); void ShowForTabContents(TabContents* contents); void EndForTabContents(TabContents* contents); // views::WindowDelegate overrides: virtual std::wstring GetWindowTitle() const; virtual void WindowClosing(); virtual int GetDialogButtons() const; virtual std::wstring GetDialogButtonLabel( MessageBoxFlags::DialogButton button) const; virtual views::View* GetExtraView(); virtual bool Accept(bool window_closing); virtual views::View* GetContentsView(); // views::ButtonListener overrides: virtual void ButtonPressed(views::Button* sender, const views::Event& event); protected: // views::View overrides: virtual void ViewHierarchyChanged(bool is_add, views::View* parent, views::View* child); private: // Initialize the controls in this dialog. void Init(); void CreateKillButtonView(); // Returns the bounds the dialog should be displayed at to be meaningfully // associated with the specified TabContents. gfx::Rect GetDisplayBounds(TabContents* contents); static void InitClass(); // Controls within the dialog box. views::ImageView* frozen_icon_view_; views::Label* info_label_; views::GroupTableView* hung_pages_table_; // The button we insert into the ClientView to kill the errant process. This // is parented to a container view that uses a grid layout to align it // properly. views::NativeButton* kill_button_; class ButtonContainer : public views::View { public: ButtonContainer() {} virtual ~ButtonContainer() {} private: DISALLOW_COPY_AND_ASSIGN(ButtonContainer); }; ButtonContainer* kill_button_container_; // The model that provides the contents of the table that shows a list of // pages affected by the hang. scoped_ptr<HungPagesTableModel> hung_pages_table_model_; // The TabContents that we detected had hung in the first place resulting in // the display of this view. TabContents* contents_; // Whether or not we've created controls for ourself. bool initialized_; // An amusing icon image. static SkBitmap* frozen_icon_; DISALLOW_COPY_AND_ASSIGN(HungRendererDialogView); }; // static SkBitmap* HungRendererDialogView::frozen_icon_ = NULL; // The distance in pixels from the top of the relevant contents to place the // warning window. static const int kOverlayContentsOffsetY = 50; // The dimensions of the hung pages list table view, in pixels. static const int kTableViewWidth = 300; static const int kTableViewHeight = 100; /////////////////////////////////////////////////////////////////////////////// // HungRendererDialogView, public: HungRendererDialogView::HungRendererDialogView() : frozen_icon_view_(NULL), info_label_(NULL), hung_pages_table_(NULL), kill_button_(NULL), kill_button_container_(NULL), contents_(NULL), initialized_(false) { InitClass(); } HungRendererDialogView::~HungRendererDialogView() { hung_pages_table_->SetModel(NULL); } void HungRendererDialogView::ShowForTabContents(TabContents* contents) { DCHECK(contents && window()); contents_ = contents; // Don't show the warning unless the foreground window is the frame, or this // window (but still invisible). If the user has another window or // application selected, activating ourselves is rude. HWND frame_hwnd = GetAncestor(contents->GetNativeView(), GA_ROOT); HWND foreground_window = GetForegroundWindow(); if (foreground_window != frame_hwnd && foreground_window != window()->GetNativeWindow()) { return; } if (!window()->IsActive()) { gfx::Rect bounds = GetDisplayBounds(contents); window()->SetBounds(bounds, frame_hwnd); // We only do this if the window isn't active (i.e. hasn't been shown yet, // or is currently shown but deactivated for another TabContents). This is // because this window is a singleton, and it's possible another active // renderer may hang while this one is showing, and we don't want to reset // the list of hung pages for a potentially unrelated renderer while this // one is showing. hung_pages_table_model_->InitForTabContents(contents); window()->Show(); } } void HungRendererDialogView::EndForTabContents(TabContents* contents) { DCHECK(contents); if (contents_ && contents_->GetRenderProcessHost() == contents->GetRenderProcessHost()) { window()->Close(); // Since we're closing, we no longer need this TabContents. contents_ = NULL; } } /////////////////////////////////////////////////////////////////////////////// // HungRendererDialogView, views::DialogDelegate implementation: std::wstring HungRendererDialogView::GetWindowTitle() const { return l10n_util::GetString(IDS_BROWSER_HANGMONITOR_RENDERER_TITLE); } void HungRendererDialogView::WindowClosing() { // We are going to be deleted soon, so make sure our instance is destroyed. g_instance = NULL; } int HungRendererDialogView::GetDialogButtons() const { // We specifically don't want a CANCEL button here because that code path is // also called when the window is closed by the user clicking the X button in // the window's titlebar, and also if we call Window::Close. Rather, we want // the OK button to wait for responsiveness (and close the dialog) and our // additional button (which we create) to kill the process (which will result // in the dialog being destroyed). return MessageBoxFlags::DIALOGBUTTON_OK; } std::wstring HungRendererDialogView::GetDialogButtonLabel( MessageBoxFlags::DialogButton button) const { if (button == MessageBoxFlags::DIALOGBUTTON_OK) return l10n_util::GetString(IDS_BROWSER_HANGMONITOR_RENDERER_WAIT); return std::wstring(); } views::View* HungRendererDialogView::GetExtraView() { return kill_button_container_; } bool HungRendererDialogView::Accept(bool window_closing) { // Don't do anything if we're being called only because the dialog is being // destroyed and we don't supply a Cancel function... if (window_closing) return true; // Start waiting again for responsiveness. if (contents_ && contents_->render_view_host()) contents_->render_view_host()->RestartHangMonitorTimeout(); return true; } views::View* HungRendererDialogView::GetContentsView() { return this; } /////////////////////////////////////////////////////////////////////////////// // HungRendererDialogView, views::ButtonListener implementation: void HungRendererDialogView::ButtonPressed( views::Button* sender, const views::Event& event) { if (sender == kill_button_) { if (!contents_) { // Kill the process. TerminateProcess(contents_->GetRenderProcessHost()->GetHandle(), ResultCodes::HUNG); } } } /////////////////////////////////////////////////////////////////////////////// // HungRendererDialogView, views::View overrides: void HungRendererDialogView::ViewHierarchyChanged(bool is_add, views::View* parent, views::View* child) { if (!initialized_ && is_add && child == this && GetWidget()) Init(); } /////////////////////////////////////////////////////////////////////////////// // HungRendererDialogView, private: void HungRendererDialogView::Init() { frozen_icon_view_ = new views::ImageView; frozen_icon_view_->SetImage(frozen_icon_); info_label_ = new views::Label( l10n_util::GetString(IDS_BROWSER_HANGMONITOR_RENDERER)); info_label_->SetMultiLine(true); info_label_->SetHorizontalAlignment(views::Label::ALIGN_LEFT); hung_pages_table_model_.reset(new HungPagesTableModel); std::vector<TableColumn> columns; columns.push_back(TableColumn()); hung_pages_table_ = new views::GroupTableView( hung_pages_table_model_.get(), columns, views::ICON_AND_TEXT, true, false, true); hung_pages_table_->SetPreferredSize( gfx::Size(kTableViewWidth, kTableViewHeight)); CreateKillButtonView(); using views::GridLayout; using views::ColumnSet; GridLayout* layout = CreatePanelGridLayout(this); SetLayoutManager(layout); const int double_column_set_id = 0; ColumnSet* column_set = layout->AddColumnSet(double_column_set_id); column_set->AddColumn(GridLayout::LEADING, GridLayout::LEADING, 0, GridLayout::FIXED, frozen_icon_->width(), 0); column_set->AddPaddingColumn(0, kUnrelatedControlLargeHorizontalSpacing); column_set->AddColumn(GridLayout::FILL, GridLayout::FILL, 1, GridLayout::USE_PREF, 0, 0); layout->StartRow(0, double_column_set_id); layout->AddView(frozen_icon_view_, 1, 3); layout->AddView(info_label_); layout->AddPaddingRow(0, kUnrelatedControlVerticalSpacing); layout->StartRow(0, double_column_set_id); layout->SkipColumns(1); layout->AddView(hung_pages_table_); initialized_ = true; } void HungRendererDialogView::CreateKillButtonView() { kill_button_ = new views::NativeButton( this, l10n_util::GetString(IDS_BROWSER_HANGMONITOR_RENDERER_END)); kill_button_container_ = new ButtonContainer; using views::GridLayout; using views::ColumnSet; GridLayout* layout = new GridLayout(kill_button_container_); kill_button_container_->SetLayoutManager(layout); const int single_column_set_id = 0; ColumnSet* column_set = layout->AddColumnSet(single_column_set_id); column_set->AddPaddingColumn(0, frozen_icon_->width() + kPanelHorizMargin + kUnrelatedControlHorizontalSpacing); column_set->AddColumn(GridLayout::LEADING, GridLayout::LEADING, 0, GridLayout::USE_PREF, 0, 0); layout->StartRow(0, single_column_set_id); layout->AddView(kill_button_); } gfx::Rect HungRendererDialogView::GetDisplayBounds( TabContents* contents) { HWND contents_hwnd = contents->GetNativeView(); RECT contents_bounds_rect; GetWindowRect(contents_hwnd, &contents_bounds_rect); gfx::Rect contents_bounds(contents_bounds_rect); gfx::Rect window_bounds = window()->GetBounds(); int window_x = contents_bounds.x() + (contents_bounds.width() - window_bounds.width()) / 2; int window_y = contents_bounds.y() + kOverlayContentsOffsetY; return gfx::Rect(window_x, window_y, window_bounds.width(), window_bounds.height()); } // static void HungRendererDialogView::InitClass() { static bool initialized = false; if (!initialized) { ResourceBundle& rb = ResourceBundle::GetSharedInstance(); frozen_icon_ = rb.GetBitmapNamed(IDR_FROZEN_TAB_ICON); initialized = true; } } /////////////////////////////////////////////////////////////////////////////// // HungRendererDialog static HungRendererDialogView* CreateHungRendererDialogView() { HungRendererDialogView* cv = new HungRendererDialogView; views::Window::CreateChromeWindow(NULL, gfx::Rect(), cv); return cv; } namespace hung_renderer_dialog { void ShowForTabContents(TabContents* contents) { if (!logging::DialogsAreSuppressed()) { if (!g_instance) g_instance = CreateHungRendererDialogView(); g_instance->ShowForTabContents(contents); } } // static void HideForTabContents(TabContents* contents) { if (!logging::DialogsAreSuppressed() && g_instance) g_instance->EndForTabContents(contents); } } // namespace hung_renderer_dialog
// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/hung_renderer_dialog.h" #include "app/l10n_util.h" #include "app/resource_bundle.h" #include "base/i18n/rtl.h" #include "base/utf_string_conversions.h" #include "chrome/browser/browser_list.h" #include "chrome/browser/renderer_host/render_process_host.h" #include "chrome/browser/renderer_host/render_view_host.h" #include "chrome/browser/tab_contents/tab_contents.h" #include "chrome/common/chrome_constants.h" #include "chrome/common/logging_chrome.h" #include "chrome/common/result_codes.h" #include "gfx/canvas.h" #include "grit/chromium_strings.h" #include "grit/generated_resources.h" #include "grit/theme_resources.h" #include "views/grid_layout.h" #include "views/controls/button/native_button.h" #include "views/controls/image_view.h" #include "views/controls/label.h" #include "views/controls/table/group_table_view.h" #include "views/standard_layout.h" #include "views/window/client_view.h" #include "views/window/dialog_delegate.h" #include "views/window/window.h" class HungRendererDialogView; namespace { // We only support showing one of these at a time per app. HungRendererDialogView* g_instance = NULL; } /////////////////////////////////////////////////////////////////////////////// // HungPagesTableModel class HungPagesTableModel : public views::GroupTableModel { public: HungPagesTableModel(); virtual ~HungPagesTableModel(); void InitForTabContents(TabContents* hung_contents); // Overridden from views::GroupTableModel: virtual int RowCount(); virtual std::wstring GetText(int row, int column_id); virtual SkBitmap GetIcon(int row); virtual void SetObserver(TableModelObserver* observer); virtual void GetGroupRangeForItem(int item, views::GroupRange* range); private: typedef std::vector<TabContents*> TabContentsVector; TabContentsVector tab_contentses_; TableModelObserver* observer_; DISALLOW_COPY_AND_ASSIGN(HungPagesTableModel); }; /////////////////////////////////////////////////////////////////////////////// // HungPagesTableModel, public: HungPagesTableModel::HungPagesTableModel() : observer_(NULL) { } HungPagesTableModel::~HungPagesTableModel() { } void HungPagesTableModel::InitForTabContents(TabContents* hung_contents) { tab_contentses_.clear(); for (TabContentsIterator it; !it.done(); ++it) { if (it->GetRenderProcessHost() == hung_contents->GetRenderProcessHost()) tab_contentses_.push_back(*it); } // The world is different. if (observer_) observer_->OnModelChanged(); } /////////////////////////////////////////////////////////////////////////////// // HungPagesTableModel, views::GroupTableModel implementation: int HungPagesTableModel::RowCount() { return static_cast<int>(tab_contentses_.size()); } std::wstring HungPagesTableModel::GetText(int row, int column_id) { DCHECK(row >= 0 && row < RowCount()); std::wstring title = UTF16ToWideHack(tab_contentses_[row]->GetTitle()); if (title.empty()) title = UTF16ToWideHack(TabContents::GetDefaultTitle()); // TODO(xji): Consider adding a special case if the title text is a URL, // since those should always have LTR directionality. Please refer to // http://crbug.com/6726 for more information. base::i18n::AdjustStringForLocaleDirection(title, &title); return title; } SkBitmap HungPagesTableModel::GetIcon(int row) { DCHECK(row >= 0 && row < RowCount()); return tab_contentses_.at(row)->GetFavIcon(); } void HungPagesTableModel::SetObserver(TableModelObserver* observer) { observer_ = observer; } void HungPagesTableModel::GetGroupRangeForItem(int item, views::GroupRange* range) { DCHECK(range); range->start = 0; range->length = RowCount(); } /////////////////////////////////////////////////////////////////////////////// // HungRendererDialogView class HungRendererDialogView : public views::View, public views::DialogDelegate, public views::ButtonListener { public: HungRendererDialogView(); ~HungRendererDialogView(); void ShowForTabContents(TabContents* contents); void EndForTabContents(TabContents* contents); // views::WindowDelegate overrides: virtual std::wstring GetWindowTitle() const; virtual void WindowClosing(); virtual int GetDialogButtons() const; virtual std::wstring GetDialogButtonLabel( MessageBoxFlags::DialogButton button) const; virtual views::View* GetExtraView(); virtual bool Accept(bool window_closing); virtual views::View* GetContentsView(); // views::ButtonListener overrides: virtual void ButtonPressed(views::Button* sender, const views::Event& event); protected: // views::View overrides: virtual void ViewHierarchyChanged(bool is_add, views::View* parent, views::View* child); private: // Initialize the controls in this dialog. void Init(); void CreateKillButtonView(); // Returns the bounds the dialog should be displayed at to be meaningfully // associated with the specified TabContents. gfx::Rect GetDisplayBounds(TabContents* contents); static void InitClass(); // Controls within the dialog box. views::ImageView* frozen_icon_view_; views::Label* info_label_; views::GroupTableView* hung_pages_table_; // The button we insert into the ClientView to kill the errant process. This // is parented to a container view that uses a grid layout to align it // properly. views::NativeButton* kill_button_; class ButtonContainer : public views::View { public: ButtonContainer() {} virtual ~ButtonContainer() {} private: DISALLOW_COPY_AND_ASSIGN(ButtonContainer); }; ButtonContainer* kill_button_container_; // The model that provides the contents of the table that shows a list of // pages affected by the hang. scoped_ptr<HungPagesTableModel> hung_pages_table_model_; // The TabContents that we detected had hung in the first place resulting in // the display of this view. TabContents* contents_; // Whether or not we've created controls for ourself. bool initialized_; // An amusing icon image. static SkBitmap* frozen_icon_; DISALLOW_COPY_AND_ASSIGN(HungRendererDialogView); }; // static SkBitmap* HungRendererDialogView::frozen_icon_ = NULL; // The distance in pixels from the top of the relevant contents to place the // warning window. static const int kOverlayContentsOffsetY = 50; // The dimensions of the hung pages list table view, in pixels. static const int kTableViewWidth = 300; static const int kTableViewHeight = 100; /////////////////////////////////////////////////////////////////////////////// // HungRendererDialogView, public: HungRendererDialogView::HungRendererDialogView() : frozen_icon_view_(NULL), info_label_(NULL), hung_pages_table_(NULL), kill_button_(NULL), kill_button_container_(NULL), contents_(NULL), initialized_(false) { InitClass(); } HungRendererDialogView::~HungRendererDialogView() { hung_pages_table_->SetModel(NULL); } void HungRendererDialogView::ShowForTabContents(TabContents* contents) { DCHECK(contents && window()); contents_ = contents; // Don't show the warning unless the foreground window is the frame, or this // window (but still invisible). If the user has another window or // application selected, activating ourselves is rude. HWND frame_hwnd = GetAncestor(contents->GetNativeView(), GA_ROOT); HWND foreground_window = GetForegroundWindow(); if (foreground_window != frame_hwnd && foreground_window != window()->GetNativeWindow()) { return; } if (!window()->IsActive()) { gfx::Rect bounds = GetDisplayBounds(contents); window()->SetBounds(bounds, frame_hwnd); // We only do this if the window isn't active (i.e. hasn't been shown yet, // or is currently shown but deactivated for another TabContents). This is // because this window is a singleton, and it's possible another active // renderer may hang while this one is showing, and we don't want to reset // the list of hung pages for a potentially unrelated renderer while this // one is showing. hung_pages_table_model_->InitForTabContents(contents); window()->Show(); } } void HungRendererDialogView::EndForTabContents(TabContents* contents) { DCHECK(contents); if (contents_ && contents_->GetRenderProcessHost() == contents->GetRenderProcessHost()) { window()->Close(); // Since we're closing, we no longer need this TabContents. contents_ = NULL; } } /////////////////////////////////////////////////////////////////////////////// // HungRendererDialogView, views::DialogDelegate implementation: std::wstring HungRendererDialogView::GetWindowTitle() const { return l10n_util::GetString(IDS_BROWSER_HANGMONITOR_RENDERER_TITLE); } void HungRendererDialogView::WindowClosing() { // We are going to be deleted soon, so make sure our instance is destroyed. g_instance = NULL; } int HungRendererDialogView::GetDialogButtons() const { // We specifically don't want a CANCEL button here because that code path is // also called when the window is closed by the user clicking the X button in // the window's titlebar, and also if we call Window::Close. Rather, we want // the OK button to wait for responsiveness (and close the dialog) and our // additional button (which we create) to kill the process (which will result // in the dialog being destroyed). return MessageBoxFlags::DIALOGBUTTON_OK; } std::wstring HungRendererDialogView::GetDialogButtonLabel( MessageBoxFlags::DialogButton button) const { if (button == MessageBoxFlags::DIALOGBUTTON_OK) return l10n_util::GetString(IDS_BROWSER_HANGMONITOR_RENDERER_WAIT); return std::wstring(); } views::View* HungRendererDialogView::GetExtraView() { return kill_button_container_; } bool HungRendererDialogView::Accept(bool window_closing) { // Don't do anything if we're being called only because the dialog is being // destroyed and we don't supply a Cancel function... if (window_closing) return true; // Start waiting again for responsiveness. if (contents_ && contents_->render_view_host()) contents_->render_view_host()->RestartHangMonitorTimeout(); return true; } views::View* HungRendererDialogView::GetContentsView() { return this; } /////////////////////////////////////////////////////////////////////////////// // HungRendererDialogView, views::ButtonListener implementation: void HungRendererDialogView::ButtonPressed( views::Button* sender, const views::Event& event) { if (sender == kill_button_) { if (contents_ && contents_->GetRenderProcessHost()) { // Kill the process. TerminateProcess(contents_->GetRenderProcessHost()->GetHandle(), ResultCodes::HUNG); } } } /////////////////////////////////////////////////////////////////////////////// // HungRendererDialogView, views::View overrides: void HungRendererDialogView::ViewHierarchyChanged(bool is_add, views::View* parent, views::View* child) { if (!initialized_ && is_add && child == this && GetWidget()) Init(); } /////////////////////////////////////////////////////////////////////////////// // HungRendererDialogView, private: void HungRendererDialogView::Init() { frozen_icon_view_ = new views::ImageView; frozen_icon_view_->SetImage(frozen_icon_); info_label_ = new views::Label( l10n_util::GetString(IDS_BROWSER_HANGMONITOR_RENDERER)); info_label_->SetMultiLine(true); info_label_->SetHorizontalAlignment(views::Label::ALIGN_LEFT); hung_pages_table_model_.reset(new HungPagesTableModel); std::vector<TableColumn> columns; columns.push_back(TableColumn()); hung_pages_table_ = new views::GroupTableView( hung_pages_table_model_.get(), columns, views::ICON_AND_TEXT, true, false, true); hung_pages_table_->SetPreferredSize( gfx::Size(kTableViewWidth, kTableViewHeight)); CreateKillButtonView(); using views::GridLayout; using views::ColumnSet; GridLayout* layout = CreatePanelGridLayout(this); SetLayoutManager(layout); const int double_column_set_id = 0; ColumnSet* column_set = layout->AddColumnSet(double_column_set_id); column_set->AddColumn(GridLayout::LEADING, GridLayout::LEADING, 0, GridLayout::FIXED, frozen_icon_->width(), 0); column_set->AddPaddingColumn(0, kUnrelatedControlLargeHorizontalSpacing); column_set->AddColumn(GridLayout::FILL, GridLayout::FILL, 1, GridLayout::USE_PREF, 0, 0); layout->StartRow(0, double_column_set_id); layout->AddView(frozen_icon_view_, 1, 3); layout->AddView(info_label_); layout->AddPaddingRow(0, kUnrelatedControlVerticalSpacing); layout->StartRow(0, double_column_set_id); layout->SkipColumns(1); layout->AddView(hung_pages_table_); initialized_ = true; } void HungRendererDialogView::CreateKillButtonView() { kill_button_ = new views::NativeButton( this, l10n_util::GetString(IDS_BROWSER_HANGMONITOR_RENDERER_END)); kill_button_container_ = new ButtonContainer; using views::GridLayout; using views::ColumnSet; GridLayout* layout = new GridLayout(kill_button_container_); kill_button_container_->SetLayoutManager(layout); const int single_column_set_id = 0; ColumnSet* column_set = layout->AddColumnSet(single_column_set_id); column_set->AddPaddingColumn(0, frozen_icon_->width() + kPanelHorizMargin + kUnrelatedControlHorizontalSpacing); column_set->AddColumn(GridLayout::LEADING, GridLayout::LEADING, 0, GridLayout::USE_PREF, 0, 0); layout->StartRow(0, single_column_set_id); layout->AddView(kill_button_); } gfx::Rect HungRendererDialogView::GetDisplayBounds( TabContents* contents) { HWND contents_hwnd = contents->GetNativeView(); RECT contents_bounds_rect; GetWindowRect(contents_hwnd, &contents_bounds_rect); gfx::Rect contents_bounds(contents_bounds_rect); gfx::Rect window_bounds = window()->GetBounds(); int window_x = contents_bounds.x() + (contents_bounds.width() - window_bounds.width()) / 2; int window_y = contents_bounds.y() + kOverlayContentsOffsetY; return gfx::Rect(window_x, window_y, window_bounds.width(), window_bounds.height()); } // static void HungRendererDialogView::InitClass() { static bool initialized = false; if (!initialized) { ResourceBundle& rb = ResourceBundle::GetSharedInstance(); frozen_icon_ = rb.GetBitmapNamed(IDR_FROZEN_TAB_ICON); initialized = true; } } /////////////////////////////////////////////////////////////////////////////// // HungRendererDialog static HungRendererDialogView* CreateHungRendererDialogView() { HungRendererDialogView* cv = new HungRendererDialogView; views::Window::CreateChromeWindow(NULL, gfx::Rect(), cv); return cv; } namespace hung_renderer_dialog { void ShowForTabContents(TabContents* contents) { if (!logging::DialogsAreSuppressed()) { if (!g_instance) g_instance = CreateHungRendererDialogView(); g_instance->ShowForTabContents(contents); } } // static void HideForTabContents(TabContents* contents) { if (!logging::DialogsAreSuppressed() && g_instance) g_instance->EndForTabContents(contents); } } // namespace hung_renderer_dialog
Augment the fix for HungRenderDialogView::ButtonPressed.
Augment the fix for HungRenderDialogView::ButtonPressed. We need to check GetRenderProcessHost() (also fixed the typo in the if statement). BUG=http://crbug.com/52293 TEST=None Review URL: http://codereview.chromium.org/3348009 git-svn-id: http://src.chromium.org/svn/trunk/src@58492 4ff67af0-8c30-449e-8e8b-ad334ec8d88c Former-commit-id: 98a419a371023b43637a5b91da8364af00bcbfab
C++
bsd-3-clause
meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser
e982412772ab1d5cbde18ff1edc8dade4023be5f
test/lib/common/TestUtility.cpp
test/lib/common/TestUtility.cpp
#include "common/Utility.hpp" #include "TestData.hpp" #include <sam.h> #include <gtest/gtest.h> #include <stdexcept> #include <iostream> using namespace std; using namespace cigar; //for testing cigar parsing functions class TestUtility : public ::testing::Test { public: static bam1_t *record; static bam1_t *record2; static bam_hdr_t *header; static void SetUpTestCase() { htsFile *fp = hts_open(TEST_BAMS[0].path.c_str(),"r"); if(fp == 0) { cerr << "Unable to open " << TEST_BAMS[0].path << "\n"; throw std::runtime_error("Error running tests"); } record = bam_init1(); record2 = bam_init1(); header = sam_hdr_read(fp); if(sam_read1(fp, header, record) <= 0) { throw std::runtime_error("Error running tests"); } if(sam_read1(fp, header, record2) <= 0) { throw std::runtime_error("Error running tests"); } hts_close(fp); } static void TearDownTestCase() { bam_destroy1(record); bam_destroy1(record2); bam_hdr_destroy(header); } }; bam1_t* TestUtility::record = NULL; bam1_t* TestUtility::record2 = NULL; bam_hdr_t* TestUtility::header = NULL; TEST_F(TestUtility, cigar_right_offset_from_bam) { //21M1I65M64S //Offset to the right should be 21+65+64 or 150 - 1; ASSERT_EQ(149,calculate_right_offset(record)); //151M ASSERT_EQ(150,calculate_right_offset(record2)); } TEST_F(TestUtility, cigar_left_offset_from_bam) { //21M1I65M64S //Offset to the right should be 21+65+64 or 150 - 1; ASSERT_EQ(0,calculate_left_offset(record)); //151M ASSERT_EQ(0,calculate_left_offset(record2)); } TEST_F(TestUtility, cigar_right_offset_from_string) { ASSERT_EQ(149, calculate_right_offset("21M1I65M64S")); ASSERT_EQ(150, calculate_right_offset("151M")); ASSERT_EQ(130, calculate_right_offset("20H131M")); ASSERT_EQ(125, calculate_right_offset("20H5S126M")); ASSERT_EQ(10, calculate_right_offset("140S11M")); ASSERT_EQ(150, calculate_right_offset("140M11S")); ASSERT_EQ(150, calculate_right_offset("140M11H")); ASSERT_EQ(150, calculate_right_offset("140M5S6H")); ASSERT_EQ(160, calculate_right_offset("100M10D51M")); } TEST_F(TestUtility, cigar_left_offset_from_string) { ASSERT_EQ(0, calculate_left_offset("151M")); ASSERT_EQ(20, calculate_left_offset("20H131M")); ASSERT_EQ(25, calculate_left_offset("20H5S126M")); ASSERT_EQ(140, calculate_left_offset("140S11M")); ASSERT_EQ(0, calculate_left_offset("140M11S")); ASSERT_EQ(0, calculate_left_offset("140M11H")); ASSERT_EQ(0, calculate_left_offset("100M10D51M")); }
#include "common/Utility.hpp" #include "TestData.hpp" #include <sam.h> #include <gtest/gtest.h> #include <stdexcept> #include <iostream> using namespace std; using namespace cigar; //for testing cigar parsing functions class TestUtility : public ::testing::Test { public: static bam1_t *record; static bam1_t *record2; static bam_hdr_t *header; static void SetUpTestCase() { htsFile *fp = hts_open(TEST_BAMS[0].path.c_str(),"r"); if(fp == 0) { cerr << "Unable to open " << TEST_BAMS[0].path << "\n"; throw std::runtime_error("Error running tests"); } record = bam_init1(); record2 = bam_init1(); header = sam_hdr_read(fp); if(sam_read1(fp, header, record) <= 0) { throw std::runtime_error("Error running tests"); } if(sam_read1(fp, header, record2) <= 0) { throw std::runtime_error("Error running tests"); } hts_close(fp); } static void TearDownTestCase() { bam_destroy1(record); bam_destroy1(record2); bam_hdr_destroy(header); } }; bam1_t* TestUtility::record = NULL; bam1_t* TestUtility::record2 = NULL; bam_hdr_t* TestUtility::header = NULL; TEST_F(TestUtility, cigar_right_offset_from_bam) { //21M1I65M64S //Offset to the right should be 21+65+64 or 150 - 1; ASSERT_EQ(149,calculate_right_offset(record)); //151M ASSERT_EQ(150,calculate_right_offset(record2)); } TEST_F(TestUtility, cigar_left_offset_from_bam) { //21M1I65M64S //Offset to the right should be 21+65+64 or 150 - 1; ASSERT_EQ(0,calculate_left_offset(record)); //151M ASSERT_EQ(0,calculate_left_offset(record2)); } TEST_F(TestUtility, cigar_right_offset_from_string) { ASSERT_EQ(149, calculate_right_offset("21M1I65M64S")); ASSERT_EQ(150, calculate_right_offset("151M")); ASSERT_EQ(130, calculate_right_offset("20H131M")); ASSERT_EQ(125, calculate_right_offset("20H5S126M")); ASSERT_EQ(125, calculate_right_offset("20H5S25X25=76M")); ASSERT_EQ(10, calculate_right_offset("140S11M")); ASSERT_EQ(150, calculate_right_offset("140M11S")); ASSERT_EQ(150, calculate_right_offset("140M11H")); ASSERT_EQ(150, calculate_right_offset("140M5S6H")); ASSERT_EQ(160, calculate_right_offset("100M10D51M")); } TEST_F(TestUtility, cigar_left_offset_from_string) { ASSERT_EQ(0, calculate_left_offset("151M")); ASSERT_EQ(20, calculate_left_offset("20H131M")); ASSERT_EQ(25, calculate_left_offset("20H5S126M")); ASSERT_EQ(25, calculate_left_offset("20H5S25X25=26M")); ASSERT_EQ(140, calculate_left_offset("140S11M")); ASSERT_EQ(0, calculate_left_offset("140M11S")); ASSERT_EQ(0, calculate_left_offset("140M11H")); ASSERT_EQ(0, calculate_left_offset("100M10D51M")); }
test less frequently used cigar strings
test less frequently used cigar strings
C++
mit
fw1121/diagnose_dups,tabbott/diagnose_dups,tabbott/diagnose_dups,genome/diagnose_dups,tabbott/diagnose_dups,genome/diagnose_dups,fw1121/diagnose_dups,fw1121/diagnose_dups,genome/diagnose_dups,tabbott/diagnose_dups,genome/diagnose_dups,fw1121/diagnose_dups,genome/diagnose_dups,genome/diagnose_dups,fw1121/diagnose_dups,tabbott/diagnose_dups
dd9fefd5bf1f99170bc5397355b707987d3388f6
test/opengl/shifted_domains.cpp
test/opengl/shifted_domains.cpp
#include "Halide.h" #include <stdio.h> #include "./testing.h" using namespace Halide; // This test executes a simple kernel with a non-zero min value. The code is // adapted from lesson_06_realizing_over_shifted_domains.cpp and scheduled for // GLSL int shifted_domains() { // This test must be run with an OpenGL target. const Target target = get_jit_target_from_environment().with_feature(Target::OpenGL); int errors = 0; Func gradient("gradient"); Var x("x"), y("y"), c("c"); gradient(x, y, c) = cast<float>(x + y); gradient.bound(c, 0, 1); gradient.glsl(x, y, c); printf("Evaluating gradient from (0, 0) to (7, 7)\n"); Buffer<float> result(8, 8, 1); gradient.realize(result, target); result.copy_to_host(); if (Testing::check_result<float>(result, [](int x, int y) { return float(x+y); })) errors++; Buffer<float> shifted(5, 7, 1); shifted.set_min(100, 50); printf("Evaluating gradient from (100, 50) to (104, 56)\n"); gradient.realize(shifted, target); shifted.copy_to_host(); if (Testing::check_result<float>(shifted, [](int x, int y) { return float(x+y); })) errors++; // Test with a negative min shifted.set_min(-100, -50); printf("Evaluating gradient from (-100, -50) to (-96, -44)\n"); gradient.realize(shifted, target); shifted.copy_to_host(); if (Testing::check_result<float>(shifted, [](int x, int y) { return float(x+y); })) errors++; return errors; } int main() { if (shifted_domains() == 0) { printf("PASSED\n"); } return 0; }
#include "Halide.h" #include <stdio.h> #include "./testing.h" using namespace Halide; // This test executes a simple kernel with a non-zero min value. The code is // adapted from lesson_06_realizing_over_shifted_domains.cpp and scheduled for // GLSL int shifted_domains() { // This test must be run with an OpenGL target. const Target target = get_jit_target_from_environment().with_feature(Target::OpenGL); int errors = 0; Func gradient("gradient"); Var x("x"), y("y"), c("c"); gradient(x, y, c) = cast<float>(x + y); gradient.bound(c, 0, 1); gradient.glsl(x, y, c); printf("Evaluating gradient from (0, 0) to (7, 7)\n"); Buffer<float> result(8, 8, 1); gradient.realize(result, target); result.copy_to_host(); if (!Testing::check_result<float>(result, [](int x, int y) { return float(x+y); }, 5e-5)) errors++; Buffer<float> shifted(5, 7, 1); shifted.set_min(100, 50); printf("Evaluating gradient from (100, 50) to (104, 56)\n"); gradient.realize(shifted, target); shifted.copy_to_host(); if (!Testing::check_result<float>(shifted, [](int x, int y) { return float(x+y); }, 5e-5)) errors++; // Test with a negative min shifted.set_min(-100, -50); printf("Evaluating gradient from (-100, -50) to (-96, -44)\n"); gradient.realize(shifted, target); shifted.copy_to_host(); if (!Testing::check_result<float>(shifted, [](int x, int y) { return float(x+y); }, 5e-5)) errors++; return errors; } int main() { if (shifted_domains() != 0) { return 1; } printf("Success\n"); return 0; }
add error tolerance; return error code if error
add error tolerance; return error code if error
C++
mit
psuriana/Halide,psuriana/Halide,kgnk/Halide,psuriana/Halide,kgnk/Halide,psuriana/Halide,psuriana/Halide,psuriana/Halide,kgnk/Halide,kgnk/Halide,psuriana/Halide,kgnk/Halide,kgnk/Halide,kgnk/Halide,kgnk/Halide
0f53565f9bf60cfd16ac802b595469ac3d99d121
sources/stack.cpp
sources/stack.cpp
#include "stack-0.0.2.hpp" #include <stdlib.h> #include <string> int main() { stack<int> Stack; std::string str; unsigned int i = 0; std::cout << "Add an element: +<Element>\nShow the last element: ?\nPop the last element: -\nShow the stack: =\n\n"; std::getline(std::cin, str); while (str[i] != '\0') { switch (str[i]) { case '+': { if (str[i + 1] == ' ' || str[i + 1] == '\0') std::cout << "An error has occurred while reading arguments\n"; else { Stack.push(stoi(str.substr(i + 1))); } break; } case '?': { std::cout << Stack.last(); std::cout << std::endl; break; } case '-': { Stack.pop(); break; } case '=': { Stack.print(); break; } defoult: break; } i++; } system("pause"); return 0; }
#include "stack.hpp" #include <stdlib.h> #include <string> int main() { stack<int> Stack; std::string str; unsigned int i = 0; std::cout << "Add an element: +<Element>\nShow the last element: ?\nPop the last element: -\nShow the stack: =\n\n"; std::getline(std::cin, str); while (str[i] != '\0') { switch (str[i]) { case '+': { if (str[i + 1] == ' ' || str[i + 1] == '\0') std::cout << "An error has occurred while reading arguments\n"; else { Stack.push(stoi(str.substr(i + 1))); } break; } case '?': { std::cout << Stack.top(); std::cout << std::endl; break; } case '-': { Stack.pop(); break; } case '=': { Stack.print(); break; } defoult: break; } i++; } system("pause"); return 0; }
Update stack.cpp
Update stack.cpp
C++
mit
kate-lozovaya/stack-0.0.3
c319b1a84527ddb45d51c3a1de13c64fa7483173
tests/mesh/mixed_dim_mesh_test.C
tests/mesh/mixed_dim_mesh_test.C
// Ignore unused parameter warnings coming from cppuint headers #include <libmesh/ignore_warnings.h> #include <cppunit/extensions/HelperMacros.h> #include <cppunit/TestCase.h> #include <libmesh/restore_warnings.h> #include <libmesh/equation_systems.h> #include <libmesh/serial_mesh.h> #include <libmesh/mesh_generation.h> #include <libmesh/edge_edge2.h> #include <libmesh/face_quad4.h> #include <libmesh/dof_map.h> #include <libmesh/linear_implicit_system.h> #include <libmesh/mesh_refinement.h> #include "test_comm.h" using namespace libMesh; class MixedDimensionMeshTest : public CppUnit::TestCase { /** * The goal of this test is to ensure that a 2D mesh with 1D elements overlapping * on the edge is consistent. That is, they share the same global node numbers and * the same dof numbers for a variable. */ public: CPPUNIT_TEST_SUITE( MixedDimensionMeshTest ); CPPUNIT_TEST( testMesh ); CPPUNIT_TEST( testDofOrdering ); CPPUNIT_TEST( testPointLocatorList ); CPPUNIT_TEST_SUITE_END(); protected: SerialMesh* _mesh; void build_mesh() { _mesh = new SerialMesh(*TestCommWorld); /* (0,1) (1,1) x---------------x | | | | | | | | | | x---------------x (0,0) (1,0) | | | | | | | | x---------------x (0,-1) (1,-1) */ _mesh->set_mesh_dimension(2); _mesh->add_point( Point(0.0,-1.0), 4 ); _mesh->add_point( Point(1.0,-1.0), 5 ); _mesh->add_point( Point(1.0, 0.0), 1 ); _mesh->add_point( Point(1.0, 1.0), 2 ); _mesh->add_point( Point(0.0, 1.0), 3 ); _mesh->add_point( Point(0.0, 0.0), 0 ); { Elem* elem_top = _mesh->add_elem( new Quad4 ); elem_top->set_node(0) = _mesh->node_ptr(0); elem_top->set_node(1) = _mesh->node_ptr(1); elem_top->set_node(2) = _mesh->node_ptr(2); elem_top->set_node(3) = _mesh->node_ptr(3); Elem* elem_bottom = _mesh->add_elem( new Quad4 ); elem_bottom->set_node(0) = _mesh->node_ptr(4); elem_bottom->set_node(1) = _mesh->node_ptr(5); elem_bottom->set_node(2) = _mesh->node_ptr(1); elem_bottom->set_node(3) = _mesh->node_ptr(0); Elem* edge = _mesh->add_elem( new Edge2 ); edge->set_node(0) = _mesh->node_ptr(0); edge->set_node(1) = _mesh->node_ptr(1); } // libMesh will renumber, but we numbered according to its scheme // anyway. We do this because when we call uniformly_refine subsequenly, // it's going use skip_renumber=false. _mesh->prepare_for_use(false /*skip_renumber*/); } public: void setUp() { this->build_mesh(); } void tearDown() { delete _mesh; } void testMesh() { // There'd better be 3 elements CPPUNIT_ASSERT_EQUAL( (dof_id_type)3, _mesh->n_elem() ); // There'd better be only 6 nodes CPPUNIT_ASSERT_EQUAL( (dof_id_type)6, _mesh->n_nodes() ); /* The nodes for the EDGE2 element should have the same global ids as the bottom edge of the top QUAD4 element */ CPPUNIT_ASSERT_EQUAL( _mesh->elem(2)->node(0), _mesh->elem(0)->node(0) ); CPPUNIT_ASSERT_EQUAL( _mesh->elem(2)->node(1), _mesh->elem(0)->node(1) ); /* The nodes for the EDGE2 element should have the same global ids as the top edge of the bottom QUAD4 element */ CPPUNIT_ASSERT_EQUAL( _mesh->elem(2)->node(0), _mesh->elem(1)->node(3) ); CPPUNIT_ASSERT_EQUAL( _mesh->elem(2)->node(1), _mesh->elem(1)->node(2) ); /* The nodes for the bottom edge of the top QUAD4 element should have the same global ids as the top edge of the bottom QUAD4 element */ CPPUNIT_ASSERT_EQUAL( _mesh->elem(0)->node(0), _mesh->elem(1)->node(3) ); CPPUNIT_ASSERT_EQUAL( _mesh->elem(0)->node(1), _mesh->elem(1)->node(2) ); } void testDofOrdering() { EquationSystems es(*_mesh); es.add_system<LinearImplicitSystem>("TestDofSystem"); es.get_system("TestDofSystem").add_variable("u",FIRST); es.init(); DofMap& dof_map = es.get_system("TestDofSystem").get_dof_map(); std::vector<dof_id_type> top_quad_dof_indices, bottom_quad_dof_indices, edge_dof_indices; dof_map.dof_indices( _mesh->elem(0), top_quad_dof_indices ); dof_map.dof_indices( _mesh->elem(1), bottom_quad_dof_indices ); dof_map.dof_indices( _mesh->elem(2), edge_dof_indices ); /* The dofs for the EDGE2 element should be the same as the bottom edge of the top QUAD4 dofs */ CPPUNIT_ASSERT_EQUAL( edge_dof_indices[0], top_quad_dof_indices[0] ); CPPUNIT_ASSERT_EQUAL( edge_dof_indices[1], top_quad_dof_indices[1] ); /* The dofs for the EDGE2 element should be the same as the top edge of the bottom QUAD4 dofs */ CPPUNIT_ASSERT_EQUAL( edge_dof_indices[0], bottom_quad_dof_indices[3] ); CPPUNIT_ASSERT_EQUAL( edge_dof_indices[1], bottom_quad_dof_indices[2] ); /* The nodes for the bottom edge of the top QUAD4 element should have the same global ids as the top edge of the bottom QUAD4 element */ CPPUNIT_ASSERT_EQUAL( top_quad_dof_indices[0], bottom_quad_dof_indices[3] ); CPPUNIT_ASSERT_EQUAL( top_quad_dof_indices[1], bottom_quad_dof_indices[2] ); } void testPointLocatorList() { AutoPtr<PointLocatorBase> locator = PointLocatorBase::build(LIST,*_mesh); Point top_point(0.4, 0.5); const Elem* top_elem = (*locator)(top_point); CPPUNIT_ASSERT(top_elem); // We should have gotten back the top quad CPPUNIT_ASSERT_EQUAL( (dof_id_type)0, top_elem->id() ); Point bottom_point(0.5, -0.5); const Elem* bottom_elem = (*locator)(bottom_point); CPPUNIT_ASSERT(bottom_elem); // We should have gotten back the bottom quad CPPUNIT_ASSERT_EQUAL( (dof_id_type)1, bottom_elem->id() ); } }; class MixedDimensionRefinedMeshTest : public MixedDimensionMeshTest { /** * The goal of this test is the same as the previous, but now we do a * uniform refinement and make sure the result mesh is consistent. i.e. * the new node shared between the 1D elements is the same as the node * shared on the underlying quads, and so on. */ public: CPPUNIT_TEST_SUITE( MixedDimensionRefinedMeshTest ); CPPUNIT_TEST( testMesh ); CPPUNIT_TEST( testDofOrdering ); CPPUNIT_TEST_SUITE_END(); // Yes, this is necesarry. Somewhere in those macros is a protected/private public: void setUp() { /* 3-------10------2 | | | | 5 | 6 | 8-------7-------9 | | | | 3 | 4 | 0-------6-------1 | | | | 9 | 10 | 13------12-------14 | | | | 7 | 8 | 4-------11------5 */ this->build_mesh(); #ifdef LIBMESH_ENABLE_AMR MeshRefinement(*_mesh).uniformly_refine(1); #endif } void testMesh() { #ifdef LIBMESH_ENABLE_AMR // We should have 13 total and 10 active elements. CPPUNIT_ASSERT_EQUAL( (dof_id_type)13, _mesh->n_elem() ); CPPUNIT_ASSERT_EQUAL( (dof_id_type)10, _mesh->n_active_elem() ); // We should have 15 nodes CPPUNIT_ASSERT_EQUAL( (dof_id_type)15, _mesh->n_nodes() ); // EDGE2,id=11 should have same nodes of bottom of QUAD4, id=3 CPPUNIT_ASSERT_EQUAL( _mesh->elem(11)->node(0), _mesh->elem(3)->node(0) ); CPPUNIT_ASSERT_EQUAL( _mesh->elem(11)->node(1), _mesh->elem(3)->node(1) ); // EDGE2,id=12 should have same nodes of bottom of QUAD4, id=4 CPPUNIT_ASSERT_EQUAL( _mesh->elem(12)->node(0), _mesh->elem(4)->node(0) ); CPPUNIT_ASSERT_EQUAL( _mesh->elem(12)->node(1), _mesh->elem(4)->node(1) ); // EDGE2,id=11 should have same nodes of top of QUAD4, id=9 CPPUNIT_ASSERT_EQUAL( _mesh->elem(11)->node(0), _mesh->elem(9)->node(3) ); CPPUNIT_ASSERT_EQUAL( _mesh->elem(11)->node(1), _mesh->elem(9)->node(2) ); // EDGE2,id=12 should have same nodes of top of QUAD4, id=10 CPPUNIT_ASSERT_EQUAL( _mesh->elem(12)->node(0), _mesh->elem(10)->node(3) ); CPPUNIT_ASSERT_EQUAL( _mesh->elem(12)->node(1), _mesh->elem(10)->node(2) ); // Shared node between the EDGE2 elements should have the same global id CPPUNIT_ASSERT_EQUAL( _mesh->elem(11)->node(1), _mesh->elem(12)->node(0) ); #endif } void testDofOrdering() { #ifdef LIBMESH_ENABLE_AMR EquationSystems es(*_mesh); es.add_system<LinearImplicitSystem>("TestDofSystem"); es.get_system("TestDofSystem").add_variable("u",FIRST); es.init(); DofMap& dof_map = es.get_system("TestDofSystem").get_dof_map(); std::vector<dof_id_type> top_quad3_dof_indices, top_quad4_dof_indices; std::vector<dof_id_type> bottom_quad9_dof_indices, bottom_quad10_dof_indices; std::vector<dof_id_type> edge11_dof_indices, edge12_dof_indices; dof_map.dof_indices( _mesh->elem(3), top_quad3_dof_indices ); dof_map.dof_indices( _mesh->elem(4), top_quad4_dof_indices ); dof_map.dof_indices( _mesh->elem(9), bottom_quad9_dof_indices ); dof_map.dof_indices( _mesh->elem(10), bottom_quad10_dof_indices ); dof_map.dof_indices( _mesh->elem(11), edge11_dof_indices ); dof_map.dof_indices( _mesh->elem(12), edge12_dof_indices ); // EDGE2,id=11 should have same dofs as of bottom of QUAD4, id=3 CPPUNIT_ASSERT_EQUAL( edge11_dof_indices[0], top_quad3_dof_indices[0] ); CPPUNIT_ASSERT_EQUAL( edge11_dof_indices[1], top_quad3_dof_indices[1] ); // EDGE2,id=12 should have same dofs of bottom of QUAD4, id=4 CPPUNIT_ASSERT_EQUAL( edge12_dof_indices[0], top_quad4_dof_indices[0] ); CPPUNIT_ASSERT_EQUAL( edge12_dof_indices[1], top_quad4_dof_indices[1] ); // EDGE2,id=11 should have same dofs of top of QUAD4, id=9 CPPUNIT_ASSERT_EQUAL( edge11_dof_indices[0], bottom_quad9_dof_indices[3] ); CPPUNIT_ASSERT_EQUAL( edge11_dof_indices[1], bottom_quad9_dof_indices[2] ); // EDGE2,id=12 should have same dofs of top of QUAD4, id=10 CPPUNIT_ASSERT_EQUAL( edge12_dof_indices[0], bottom_quad10_dof_indices[3] ); CPPUNIT_ASSERT_EQUAL( edge12_dof_indices[1], bottom_quad10_dof_indices[2] ); //EDGE2 elements should have same shared dof number CPPUNIT_ASSERT_EQUAL( edge11_dof_indices[1], edge12_dof_indices[0] ); #endif } }; CPPUNIT_TEST_SUITE_REGISTRATION( MixedDimensionMeshTest ); CPPUNIT_TEST_SUITE_REGISTRATION( MixedDimensionRefinedMeshTest );
// Ignore unused parameter warnings coming from cppuint headers #include <libmesh/ignore_warnings.h> #include <cppunit/extensions/HelperMacros.h> #include <cppunit/TestCase.h> #include <libmesh/restore_warnings.h> #include <libmesh/equation_systems.h> #include <libmesh/serial_mesh.h> #include <libmesh/mesh_generation.h> #include <libmesh/edge_edge2.h> #include <libmesh/face_quad4.h> #include <libmesh/dof_map.h> #include <libmesh/linear_implicit_system.h> #include <libmesh/mesh_refinement.h> #include "test_comm.h" using namespace libMesh; class MixedDimensionMeshTest : public CppUnit::TestCase { /** * The goal of this test is to ensure that a 2D mesh with 1D elements overlapping * on the edge is consistent. That is, they share the same global node numbers and * the same dof numbers for a variable. */ public: CPPUNIT_TEST_SUITE( MixedDimensionMeshTest ); CPPUNIT_TEST( testMesh ); CPPUNIT_TEST( testDofOrdering ); CPPUNIT_TEST( testPointLocatorList ); CPPUNIT_TEST( testPointLocatorTree ); CPPUNIT_TEST_SUITE_END(); protected: SerialMesh* _mesh; void build_mesh() { _mesh = new SerialMesh(*TestCommWorld); /* (0,1) (1,1) x---------------x | | | | | | | | | | x---------------x (0,0) (1,0) | | | | | | | | x---------------x (0,-1) (1,-1) */ _mesh->set_mesh_dimension(2); _mesh->add_point( Point(0.0,-1.0), 4 ); _mesh->add_point( Point(1.0,-1.0), 5 ); _mesh->add_point( Point(1.0, 0.0), 1 ); _mesh->add_point( Point(1.0, 1.0), 2 ); _mesh->add_point( Point(0.0, 1.0), 3 ); _mesh->add_point( Point(0.0, 0.0), 0 ); { Elem* elem_top = _mesh->add_elem( new Quad4 ); elem_top->set_node(0) = _mesh->node_ptr(0); elem_top->set_node(1) = _mesh->node_ptr(1); elem_top->set_node(2) = _mesh->node_ptr(2); elem_top->set_node(3) = _mesh->node_ptr(3); Elem* elem_bottom = _mesh->add_elem( new Quad4 ); elem_bottom->set_node(0) = _mesh->node_ptr(4); elem_bottom->set_node(1) = _mesh->node_ptr(5); elem_bottom->set_node(2) = _mesh->node_ptr(1); elem_bottom->set_node(3) = _mesh->node_ptr(0); Elem* edge = _mesh->add_elem( new Edge2 ); edge->set_node(0) = _mesh->node_ptr(0); edge->set_node(1) = _mesh->node_ptr(1); } // libMesh will renumber, but we numbered according to its scheme // anyway. We do this because when we call uniformly_refine subsequenly, // it's going use skip_renumber=false. _mesh->prepare_for_use(false /*skip_renumber*/); } public: void setUp() { this->build_mesh(); } void tearDown() { delete _mesh; } void testMesh() { // There'd better be 3 elements CPPUNIT_ASSERT_EQUAL( (dof_id_type)3, _mesh->n_elem() ); // There'd better be only 6 nodes CPPUNIT_ASSERT_EQUAL( (dof_id_type)6, _mesh->n_nodes() ); /* The nodes for the EDGE2 element should have the same global ids as the bottom edge of the top QUAD4 element */ CPPUNIT_ASSERT_EQUAL( _mesh->elem(2)->node(0), _mesh->elem(0)->node(0) ); CPPUNIT_ASSERT_EQUAL( _mesh->elem(2)->node(1), _mesh->elem(0)->node(1) ); /* The nodes for the EDGE2 element should have the same global ids as the top edge of the bottom QUAD4 element */ CPPUNIT_ASSERT_EQUAL( _mesh->elem(2)->node(0), _mesh->elem(1)->node(3) ); CPPUNIT_ASSERT_EQUAL( _mesh->elem(2)->node(1), _mesh->elem(1)->node(2) ); /* The nodes for the bottom edge of the top QUAD4 element should have the same global ids as the top edge of the bottom QUAD4 element */ CPPUNIT_ASSERT_EQUAL( _mesh->elem(0)->node(0), _mesh->elem(1)->node(3) ); CPPUNIT_ASSERT_EQUAL( _mesh->elem(0)->node(1), _mesh->elem(1)->node(2) ); } void testDofOrdering() { EquationSystems es(*_mesh); es.add_system<LinearImplicitSystem>("TestDofSystem"); es.get_system("TestDofSystem").add_variable("u",FIRST); es.init(); DofMap& dof_map = es.get_system("TestDofSystem").get_dof_map(); std::vector<dof_id_type> top_quad_dof_indices, bottom_quad_dof_indices, edge_dof_indices; dof_map.dof_indices( _mesh->elem(0), top_quad_dof_indices ); dof_map.dof_indices( _mesh->elem(1), bottom_quad_dof_indices ); dof_map.dof_indices( _mesh->elem(2), edge_dof_indices ); /* The dofs for the EDGE2 element should be the same as the bottom edge of the top QUAD4 dofs */ CPPUNIT_ASSERT_EQUAL( edge_dof_indices[0], top_quad_dof_indices[0] ); CPPUNIT_ASSERT_EQUAL( edge_dof_indices[1], top_quad_dof_indices[1] ); /* The dofs for the EDGE2 element should be the same as the top edge of the bottom QUAD4 dofs */ CPPUNIT_ASSERT_EQUAL( edge_dof_indices[0], bottom_quad_dof_indices[3] ); CPPUNIT_ASSERT_EQUAL( edge_dof_indices[1], bottom_quad_dof_indices[2] ); /* The nodes for the bottom edge of the top QUAD4 element should have the same global ids as the top edge of the bottom QUAD4 element */ CPPUNIT_ASSERT_EQUAL( top_quad_dof_indices[0], bottom_quad_dof_indices[3] ); CPPUNIT_ASSERT_EQUAL( top_quad_dof_indices[1], bottom_quad_dof_indices[2] ); } void testPointLocatorList() { AutoPtr<PointLocatorBase> locator = PointLocatorBase::build(LIST,*_mesh); Point top_point(0.4, 0.5); const Elem* top_elem = (*locator)(top_point); CPPUNIT_ASSERT(top_elem); // We should have gotten back the top quad CPPUNIT_ASSERT_EQUAL( (dof_id_type)0, top_elem->id() ); Point bottom_point(0.5, -0.5); const Elem* bottom_elem = (*locator)(bottom_point); CPPUNIT_ASSERT(bottom_elem); // We should have gotten back the bottom quad CPPUNIT_ASSERT_EQUAL( (dof_id_type)1, bottom_elem->id() ); } void testPointLocatorTree() { AutoPtr<PointLocatorBase> locator = _mesh->sub_point_locator(); Point top_point(0.5, 0.5); const Elem* top_elem = (*locator)(top_point); CPPUNIT_ASSERT(top_elem); // We should have gotten back the top quad CPPUNIT_ASSERT_EQUAL( (dof_id_type)0, top_elem->id() ); Point bottom_point(0.5, -0.5); const Elem* bottom_elem = (*locator)(bottom_point); CPPUNIT_ASSERT(bottom_elem); // We should have gotten back the bottom quad CPPUNIT_ASSERT_EQUAL( (dof_id_type)1, bottom_elem->id() ); } }; class MixedDimensionRefinedMeshTest : public MixedDimensionMeshTest { /** * The goal of this test is the same as the previous, but now we do a * uniform refinement and make sure the result mesh is consistent. i.e. * the new node shared between the 1D elements is the same as the node * shared on the underlying quads, and so on. */ public: CPPUNIT_TEST_SUITE( MixedDimensionRefinedMeshTest ); CPPUNIT_TEST( testMesh ); CPPUNIT_TEST( testDofOrdering ); CPPUNIT_TEST_SUITE_END(); // Yes, this is necesarry. Somewhere in those macros is a protected/private public: void setUp() { /* 3-------10------2 | | | | 5 | 6 | 8-------7-------9 | | | | 3 | 4 | 0-------6-------1 | | | | 9 | 10 | 13------12-------14 | | | | 7 | 8 | 4-------11------5 */ this->build_mesh(); #ifdef LIBMESH_ENABLE_AMR MeshRefinement(*_mesh).uniformly_refine(1); #endif } void testMesh() { #ifdef LIBMESH_ENABLE_AMR // We should have 13 total and 10 active elements. CPPUNIT_ASSERT_EQUAL( (dof_id_type)13, _mesh->n_elem() ); CPPUNIT_ASSERT_EQUAL( (dof_id_type)10, _mesh->n_active_elem() ); // We should have 15 nodes CPPUNIT_ASSERT_EQUAL( (dof_id_type)15, _mesh->n_nodes() ); // EDGE2,id=11 should have same nodes of bottom of QUAD4, id=3 CPPUNIT_ASSERT_EQUAL( _mesh->elem(11)->node(0), _mesh->elem(3)->node(0) ); CPPUNIT_ASSERT_EQUAL( _mesh->elem(11)->node(1), _mesh->elem(3)->node(1) ); // EDGE2,id=12 should have same nodes of bottom of QUAD4, id=4 CPPUNIT_ASSERT_EQUAL( _mesh->elem(12)->node(0), _mesh->elem(4)->node(0) ); CPPUNIT_ASSERT_EQUAL( _mesh->elem(12)->node(1), _mesh->elem(4)->node(1) ); // EDGE2,id=11 should have same nodes of top of QUAD4, id=9 CPPUNIT_ASSERT_EQUAL( _mesh->elem(11)->node(0), _mesh->elem(9)->node(3) ); CPPUNIT_ASSERT_EQUAL( _mesh->elem(11)->node(1), _mesh->elem(9)->node(2) ); // EDGE2,id=12 should have same nodes of top of QUAD4, id=10 CPPUNIT_ASSERT_EQUAL( _mesh->elem(12)->node(0), _mesh->elem(10)->node(3) ); CPPUNIT_ASSERT_EQUAL( _mesh->elem(12)->node(1), _mesh->elem(10)->node(2) ); // Shared node between the EDGE2 elements should have the same global id CPPUNIT_ASSERT_EQUAL( _mesh->elem(11)->node(1), _mesh->elem(12)->node(0) ); #endif } void testDofOrdering() { #ifdef LIBMESH_ENABLE_AMR EquationSystems es(*_mesh); es.add_system<LinearImplicitSystem>("TestDofSystem"); es.get_system("TestDofSystem").add_variable("u",FIRST); es.init(); DofMap& dof_map = es.get_system("TestDofSystem").get_dof_map(); std::vector<dof_id_type> top_quad3_dof_indices, top_quad4_dof_indices; std::vector<dof_id_type> bottom_quad9_dof_indices, bottom_quad10_dof_indices; std::vector<dof_id_type> edge11_dof_indices, edge12_dof_indices; dof_map.dof_indices( _mesh->elem(3), top_quad3_dof_indices ); dof_map.dof_indices( _mesh->elem(4), top_quad4_dof_indices ); dof_map.dof_indices( _mesh->elem(9), bottom_quad9_dof_indices ); dof_map.dof_indices( _mesh->elem(10), bottom_quad10_dof_indices ); dof_map.dof_indices( _mesh->elem(11), edge11_dof_indices ); dof_map.dof_indices( _mesh->elem(12), edge12_dof_indices ); // EDGE2,id=11 should have same dofs as of bottom of QUAD4, id=3 CPPUNIT_ASSERT_EQUAL( edge11_dof_indices[0], top_quad3_dof_indices[0] ); CPPUNIT_ASSERT_EQUAL( edge11_dof_indices[1], top_quad3_dof_indices[1] ); // EDGE2,id=12 should have same dofs of bottom of QUAD4, id=4 CPPUNIT_ASSERT_EQUAL( edge12_dof_indices[0], top_quad4_dof_indices[0] ); CPPUNIT_ASSERT_EQUAL( edge12_dof_indices[1], top_quad4_dof_indices[1] ); // EDGE2,id=11 should have same dofs of top of QUAD4, id=9 CPPUNIT_ASSERT_EQUAL( edge11_dof_indices[0], bottom_quad9_dof_indices[3] ); CPPUNIT_ASSERT_EQUAL( edge11_dof_indices[1], bottom_quad9_dof_indices[2] ); // EDGE2,id=12 should have same dofs of top of QUAD4, id=10 CPPUNIT_ASSERT_EQUAL( edge12_dof_indices[0], bottom_quad10_dof_indices[3] ); CPPUNIT_ASSERT_EQUAL( edge12_dof_indices[1], bottom_quad10_dof_indices[2] ); //EDGE2 elements should have same shared dof number CPPUNIT_ASSERT_EQUAL( edge11_dof_indices[1], edge12_dof_indices[0] ); #endif } }; CPPUNIT_TEST_SUITE_REGISTRATION( MixedDimensionMeshTest ); CPPUNIT_TEST_SUITE_REGISTRATION( MixedDimensionRefinedMeshTest );
Add PointLocatorTree unit test back
Add PointLocatorTree unit test back Only testing the "basic" part now. Mixed dimension test coming next.
C++
lgpl-2.1
hrittich/libmesh,permcody/libmesh,dknez/libmesh,friedmud/libmesh,balborian/libmesh,benkirk/libmesh,aeslaughter/libmesh,90jrong/libmesh,benkirk/libmesh,cahaynes/libmesh,90jrong/libmesh,hrittich/libmesh,salazardetroya/libmesh,karpeev/libmesh,libMesh/libmesh,permcody/libmesh,cahaynes/libmesh,dschwen/libmesh,capitalaslash/libmesh,svallaghe/libmesh,svallaghe/libmesh,svallaghe/libmesh,coreymbryant/libmesh,Mbewu/libmesh,balborian/libmesh,BalticPinguin/libmesh,permcody/libmesh,roystgnr/libmesh,Mbewu/libmesh,coreymbryant/libmesh,dmcdougall/libmesh,libMesh/libmesh,dknez/libmesh,vikramvgarg/libmesh,BalticPinguin/libmesh,dschwen/libmesh,vikramvgarg/libmesh,friedmud/libmesh,jiangwen84/libmesh,giorgiobornia/libmesh,pbauman/libmesh,jwpeterson/libmesh,jwpeterson/libmesh,pbauman/libmesh,BalticPinguin/libmesh,coreymbryant/libmesh,karpeev/libmesh,karpeev/libmesh,jiangwen84/libmesh,coreymbryant/libmesh,pbauman/libmesh,roystgnr/libmesh,vikramvgarg/libmesh,90jrong/libmesh,libMesh/libmesh,salazardetroya/libmesh,90jrong/libmesh,hrittich/libmesh,dmcdougall/libmesh,balborian/libmesh,aeslaughter/libmesh,dschwen/libmesh,Mbewu/libmesh,coreymbryant/libmesh,pbauman/libmesh,jiangwen84/libmesh,salazardetroya/libmesh,cahaynes/libmesh,90jrong/libmesh,giorgiobornia/libmesh,capitalaslash/libmesh,libMesh/libmesh,permcody/libmesh,pbauman/libmesh,benkirk/libmesh,dknez/libmesh,jiangwen84/libmesh,jiangwen84/libmesh,capitalaslash/libmesh,aeslaughter/libmesh,dmcdougall/libmesh,giorgiobornia/libmesh,balborian/libmesh,jiangwen84/libmesh,vikramvgarg/libmesh,permcody/libmesh,libMesh/libmesh,vikramvgarg/libmesh,svallaghe/libmesh,roystgnr/libmesh,benkirk/libmesh,roystgnr/libmesh,dschwen/libmesh,dmcdougall/libmesh,jwpeterson/libmesh,pbauman/libmesh,balborian/libmesh,balborian/libmesh,aeslaughter/libmesh,friedmud/libmesh,90jrong/libmesh,libMesh/libmesh,pbauman/libmesh,giorgiobornia/libmesh,hrittich/libmesh,karpeev/libmesh,dschwen/libmesh,jwpeterson/libmesh,benkirk/libmesh,coreymbryant/libmesh,vikramvgarg/libmesh,balborian/libmesh,jiangwen84/libmesh,pbauman/libmesh,cahaynes/libmesh,karpeev/libmesh,friedmud/libmesh,coreymbryant/libmesh,capitalaslash/libmesh,giorgiobornia/libmesh,vikramvgarg/libmesh,jiangwen84/libmesh,BalticPinguin/libmesh,BalticPinguin/libmesh,friedmud/libmesh,BalticPinguin/libmesh,jwpeterson/libmesh,friedmud/libmesh,karpeev/libmesh,roystgnr/libmesh,giorgiobornia/libmesh,90jrong/libmesh,balborian/libmesh,roystgnr/libmesh,dschwen/libmesh,permcody/libmesh,benkirk/libmesh,dknez/libmesh,dknez/libmesh,vikramvgarg/libmesh,capitalaslash/libmesh,aeslaughter/libmesh,cahaynes/libmesh,friedmud/libmesh,benkirk/libmesh,giorgiobornia/libmesh,hrittich/libmesh,coreymbryant/libmesh,salazardetroya/libmesh,libMesh/libmesh,salazardetroya/libmesh,Mbewu/libmesh,permcody/libmesh,dmcdougall/libmesh,aeslaughter/libmesh,benkirk/libmesh,dmcdougall/libmesh,hrittich/libmesh,Mbewu/libmesh,salazardetroya/libmesh,dmcdougall/libmesh,friedmud/libmesh,capitalaslash/libmesh,salazardetroya/libmesh,libMesh/libmesh,hrittich/libmesh,svallaghe/libmesh,dknez/libmesh,cahaynes/libmesh,permcody/libmesh,svallaghe/libmesh,capitalaslash/libmesh,aeslaughter/libmesh,jwpeterson/libmesh,90jrong/libmesh,friedmud/libmesh,cahaynes/libmesh,jwpeterson/libmesh,jwpeterson/libmesh,roystgnr/libmesh,giorgiobornia/libmesh,balborian/libmesh,karpeev/libmesh,karpeev/libmesh,dschwen/libmesh,svallaghe/libmesh,vikramvgarg/libmesh,balborian/libmesh,90jrong/libmesh,benkirk/libmesh,dknez/libmesh,cahaynes/libmesh,capitalaslash/libmesh,aeslaughter/libmesh,BalticPinguin/libmesh,aeslaughter/libmesh,salazardetroya/libmesh,Mbewu/libmesh,Mbewu/libmesh,BalticPinguin/libmesh,dmcdougall/libmesh,svallaghe/libmesh,svallaghe/libmesh,dknez/libmesh,Mbewu/libmesh,pbauman/libmesh,Mbewu/libmesh,giorgiobornia/libmesh,roystgnr/libmesh,hrittich/libmesh,dschwen/libmesh,hrittich/libmesh
1b16bd4d79351f307f7ed4af2b1910679ba251cb
src/handler.cpp
src/handler.cpp
#include "dafs/handler.hpp" namespace dafs { dafs::Message HandleReadBlock( dafs::Node& node, dafs::MetaDataParser metadata) { auto blockinfo = metadata.GetValue<dafs::BlockInfo>(dafs::BlockInfoKey); auto blockformat = node.GetPartition(blockinfo.identity)->ReadBlock(blockinfo); dafs::Message m; m.type = dafs::MessageType::ReadBlock; m.metadata.push_back( dafs::MetaData { dafs::BlockFormatKey, dafs::Serialize<dafs::BlockFormat>(blockformat) } ); return m; } dafs::Message HandleWriteBlock( dafs::Node& node, dafs::MetaDataParser metadata) { auto blockinfo = metadata.GetValue<dafs::BlockInfo>(dafs::BlockInfoKey); auto block = metadata.GetValue<dafs::BlockFormat>(dafs::BlockFormatKey); node.GetPartition(blockinfo.identity)->WriteBlock(blockinfo, block); dafs::Message m; return m; } dafs::Message HandleDeleteBlock( dafs::Node& node, dafs::MetaDataParser metadata) { auto blockinfo = metadata.GetValue<dafs::BlockInfo>(dafs::BlockInfoKey); node.GetPartition(blockinfo.identity)->DeleteBlock(blockinfo); dafs::Message m; return m; } dafs::Message HandleGetNodeDetails( dafs::Node& node, dafs::MetaDataParser metadata) { auto details = dafs::NodeDetails { node.GetPartition(dafs::Node::Slot::Minus)->GetDetails(), node.GetPartition(dafs::Node::Slot::Zero)->GetDetails(), node.GetPartition(dafs::Node::Slot::Plus)->GetDetails() }; dafs::Message m; m.metadata.push_back( dafs::MetaData { dafs::NodeDetailsKey, dafs::Serialize<dafs::NodeDetails>(details) } ); return m; } dafs::Message HandleJoinCluster( dafs::Node& node, dafs::MetaDataParser metadata) { dafs::NetworkSender searcher( metadata.GetValue<dafs::Address>(dafs::AddressKey)); auto p_minus = node.GetPartition(dafs::Node::Slot::Minus); auto p_zero = node.GetPartition(dafs::Node::Slot::Zero); auto p_plus = node.GetPartition(dafs::Node::Slot::Plus); searcher.Send( dafs::Message { node.GetPartition(dafs::Node::Slot::Zero)->GetDetails().author, metadata.GetValue<dafs::Address>(dafs::AddressKey), dafs::MessageType::_RequestMinusInitiation, std::vector<dafs::MetaData> { dafs::MetaData { dafs::NodeDetailsKey, dafs::Serialize( dafs::NodeDetails { p_minus->GetDetails(), p_zero->GetDetails(), p_plus->GetDetails() } ) } } } ); dafs::Message m; return m; } dafs::Message HandleRequestMinusInitiation( dafs::Node& node, dafs::MetaDataParser metadata) { auto address = metadata.GetValue<dafs::Address>(dafs::AddressKey); auto identity = dafs::Identity(metadata.GetValue<std::string>( dafs::IdentityKey)); auto details = metadata.GetValue<dafs::NodeDetails>(dafs::NodeDetailsKey); auto p_minus = node.GetPartition(dafs::Node::Slot::Minus); auto p_zero = node.GetPartition(dafs::Node::Slot::Zero); dafs::NetworkSender sender( metadata.GetValue<dafs::Address>(dafs::AddressKey)); if (identity < p_minus->GetDetails().identity || identity > p_zero->GetDetails().identity) { // // Reject initiation request by telling node who to ask next. // sender.Send( dafs::Message { p_zero->GetDetails().author, address, dafs::MessageType::_JoinCluster, std::vector<dafs::MetaData> { dafs::MetaData { dafs::Serialize(address), dafs::Serialize(p_minus->GetDetails().author) } } } ); } else { // // Accept initiation request and update half of topology. // // Push replication onto initiated node. p_minus->AddNode(details.minus_details.interface); // Delete extra replications. p_minus->RemoveNode(p_minus->GetDetails().interface); // Clear previous artifacts from partition. p_minus->Clear(); dafs::NetworkSender forward_sender(p_minus->GetDetails().author); forward_sender.Send( dafs::Message { p_zero->GetDetails().author, p_minus->GetDetails().author, dafs::MessageType::_RequestPlusInitiation, std::vector<dafs::MetaData> { dafs::MetaData { dafs::NodeDetailsKey, dafs::Serialize(details) } } } ); sender.Send( dafs::Message { p_zero->GetDetails().author, address, dafs::MessageType::_AcceptMinusInitation, std::vector<dafs::MetaData> { dafs::MetaData { dafs::AddressKey, dafs::Serialize( p_zero->GetDetails().interface ) } } } ); } dafs::Message m; return m; } dafs::Message HandleRequestPlusInitiation( dafs::Node& node, dafs::MetaDataParser metadata) { auto address = metadata.GetValue<dafs::Address>(dafs::AddressKey); auto identity = dafs::Identity(metadata.GetValue<std::string>( dafs::IdentityKey)); auto details = metadata.GetValue<dafs::NodeDetails>(dafs::NodeDetailsKey); auto p_zero = node.GetPartition(dafs::Node::Slot::Zero); auto p_plus = node.GetPartition(dafs::Node::Slot::Plus); dafs::NetworkSender sender( metadata.GetValue<dafs::Address>(dafs::AddressKey)); if (identity > p_plus->GetDetails().identity || identity < p_zero->GetDetails().identity) { // // Foobar'd topology. Rollback? // } else { // // Update second half of topology // // Push replication onto initiated node. p_plus->AddNode(details.plus_details.interface); // Delete extra replications. p_plus->RemoveNode(p_plus->GetDetails().interface); // Clear previous artifacts from partition. p_plus->Clear(); // Send accepted messge to ndoe. sender.Send( dafs::Message { p_zero->GetDetails().author, address, dafs::MessageType::_AcceptPlusInitation, std::vector<dafs::MetaData> { dafs::MetaData { dafs::AddressKey, dafs::Serialize(p_zero->GetDetails().interface) } } } ); } dafs::Message m; return m; } dafs::Message HandleAcceptMinusInitiation( dafs::Node& node, dafs::MetaDataParser metadata) { auto address = metadata.GetValue<dafs::Address>(dafs::AddressKey); auto p_plus = node.GetPartition(dafs::Node::Slot::Plus); p_plus->AddNode(address); dafs::Message m; return m; } dafs::Message HandleAcceptPlusInitiation( dafs::Node& node, dafs::MetaDataParser metadata) { auto address = metadata.GetValue<dafs::Address>(dafs::AddressKey); auto p_minus = node.GetPartition(dafs::Node::Slot::Minus); p_minus->AddNode(address); dafs::Message m; return m; } }
#include "dafs/handler.hpp" namespace dafs { dafs::Message HandleReadBlock( dafs::Node& node, dafs::MetaDataParser metadata) { auto blockinfo = metadata.GetValue<dafs::BlockInfo>(dafs::BlockInfoKey); auto blockformat = node.GetPartition(blockinfo.identity)->ReadBlock(blockinfo); dafs::Message m; m.type = dafs::MessageType::ReadBlock; m.metadata.push_back( dafs::MetaData { dafs::BlockFormatKey, dafs::Serialize<dafs::BlockFormat>(blockformat) } ); return m; } dafs::Message HandleWriteBlock( dafs::Node& node, dafs::MetaDataParser metadata) { auto blockinfo = metadata.GetValue<dafs::BlockInfo>(dafs::BlockInfoKey); auto block = metadata.GetValue<dafs::BlockFormat>(dafs::BlockFormatKey); node.GetPartition(blockinfo.identity)->WriteBlock(blockinfo, block); dafs::Message m; return m; } dafs::Message HandleDeleteBlock( dafs::Node& node, dafs::MetaDataParser metadata) { auto blockinfo = metadata.GetValue<dafs::BlockInfo>(dafs::BlockInfoKey); node.GetPartition(blockinfo.identity)->DeleteBlock(blockinfo); dafs::Message m; return m; } dafs::Message HandleGetNodeDetails( dafs::Node& node, dafs::MetaDataParser metadata) { auto details = dafs::NodeDetails { node.GetPartition(dafs::Node::Slot::Minus)->GetDetails(), node.GetPartition(dafs::Node::Slot::Zero)->GetDetails(), node.GetPartition(dafs::Node::Slot::Plus)->GetDetails() }; dafs::Message m; m.metadata.push_back( dafs::MetaData { dafs::NodeDetailsKey, dafs::Serialize<dafs::NodeDetails>(details) } ); return m; } dafs::Message HandleJoinCluster( dafs::Node& node, dafs::MetaDataParser metadata) { dafs::NetworkSender reply( metadata.GetValue<dafs::Address>(dafs::AddressKey)); auto p_minus = node.GetPartition(dafs::Node::Slot::Minus); auto p_zero = node.GetPartition(dafs::Node::Slot::Zero); auto p_plus = node.GetPartition(dafs::Node::Slot::Plus); reply.Send( dafs::Message { node.GetPartition(dafs::Node::Slot::Zero)->GetDetails().author, metadata.GetValue<dafs::Address>(dafs::AddressKey), dafs::MessageType::_RequestMinusInitiation, std::vector<dafs::MetaData> { dafs::MetaData { dafs::NodeDetailsKey, dafs::Serialize( dafs::NodeDetails { p_minus->GetDetails(), p_zero->GetDetails(), p_plus->GetDetails() } ) } } } ); dafs::Message m; return m; } dafs::Message HandleRequestMinusInitiation( dafs::Node& node, dafs::MetaDataParser metadata) { auto address = metadata.GetValue<dafs::Address>(dafs::AddressKey); auto identity = dafs::Identity(metadata.GetValue<std::string>( dafs::IdentityKey)); auto details = metadata.GetValue<dafs::NodeDetails>(dafs::NodeDetailsKey); auto p_minus = node.GetPartition(dafs::Node::Slot::Minus); auto p_zero = node.GetPartition(dafs::Node::Slot::Zero); dafs::NetworkSender reply( metadata.GetValue<dafs::Address>(dafs::AddressKey)); if (p_minus->IsActive() && (identity < p_minus->GetDetails().identity || identity > p_zero->GetDetails().identity)) { // // Reject initiation request by telling node who to ask next. // reply.Send( dafs::Message { p_zero->GetDetails().author, address, dafs::MessageType::_JoinCluster, std::vector<dafs::MetaData> { dafs::MetaData { dafs::Serialize(address), dafs::Serialize(p_minus->GetDetails().author) } } } ); } else { if (p_minus->IsActive()) { // // Accept initiation request and update half of topology. // // Push replication onto initiated node. p_minus->AddNode(details.minus_details.interface); // Delete extra replications. p_minus->RemoveNode(p_minus->GetDetails().interface); // Clear previous artifacts from partition. p_minus->Clear(); dafs::NetworkSender forwarder(p_minus->GetDetails().author); forwarder.Send( dafs::Message { p_zero->GetDetails().author, p_minus->GetDetails().author, dafs::MessageType::_RequestPlusInitiation, std::vector<dafs::MetaData> { dafs::MetaData { dafs::NodeDetailsKey, dafs::Serialize(details) } } } ); } else { // // Case of standalone node - accept initiation request and // update both halves of topology. // reply.Send( dafs::Message { p_zero->GetDetails().author, address, dafs::MessageType::_AcceptPlusInitation, std::vector<dafs::MetaData> { dafs::MetaData { dafs::AddressKey, dafs::Serialize( p_zero->GetDetails().interface ) } } } ); } reply.Send( dafs::Message { p_zero->GetDetails().author, address, dafs::MessageType::_AcceptMinusInitation, std::vector<dafs::MetaData> { dafs::MetaData { dafs::AddressKey, dafs::Serialize( p_zero->GetDetails().interface ) } } } ); } dafs::Message m; return m; } dafs::Message HandleRequestPlusInitiation( dafs::Node& node, dafs::MetaDataParser metadata) { auto address = metadata.GetValue<dafs::Address>(dafs::AddressKey); auto identity = dafs::Identity(metadata.GetValue<std::string>( dafs::IdentityKey)); auto details = metadata.GetValue<dafs::NodeDetails>(dafs::NodeDetailsKey); auto p_zero = node.GetPartition(dafs::Node::Slot::Zero); auto p_plus = node.GetPartition(dafs::Node::Slot::Plus); dafs::NetworkSender reply( metadata.GetValue<dafs::Address>(dafs::AddressKey)); if (identity > p_plus->GetDetails().identity || identity < p_zero->GetDetails().identity) { // // Foobar'd topology. Rollback? // } else { // // Update second half of topology // // Push replication onto initiated node. p_plus->AddNode(details.plus_details.interface); // Delete extra replications. p_plus->RemoveNode(p_plus->GetDetails().interface); // Clear previous artifacts from partition. p_plus->Clear(); // Send accepted messge to ndoe. reply.Send( dafs::Message { p_zero->GetDetails().author, address, dafs::MessageType::_AcceptPlusInitation, std::vector<dafs::MetaData> { dafs::MetaData { dafs::AddressKey, dafs::Serialize(p_zero->GetDetails().interface) } } } ); } dafs::Message m; return m; } dafs::Message HandleAcceptMinusInitiation( dafs::Node& node, dafs::MetaDataParser metadata) { auto address = metadata.GetValue<dafs::Address>(dafs::AddressKey); auto p_plus = node.GetPartition(dafs::Node::Slot::Plus); p_plus->AddNode(address); dafs::Message m; return m; } dafs::Message HandleAcceptPlusInitiation( dafs::Node& node, dafs::MetaDataParser metadata) { auto address = metadata.GetValue<dafs::Address>(dafs::AddressKey); auto p_minus = node.GetPartition(dafs::Node::Slot::Minus); p_minus->AddNode(address); dafs::Message m; return m; } }
Add logic to handle joining a standalone server
Add logic to handle joining a standalone server
C++
mit
dgkimura/dafs,dgkimura/dafs
5757d94f3fd41d8b8253ef45b62518e9181c0e7b
engine/src/Methcla/Utility/MessageQueue.hpp
engine/src/Methcla/Utility/MessageQueue.hpp
// Copyright 2012-2013 Samplecount S.L. // // 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 METHCLA_UTILITY_MESSAGEQUEUE_HPP_INCLUDED #define METHCLA_UTILITY_MESSAGEQUEUE_HPP_INCLUDED #include <algorithm> #include <array> #include <atomic> #include <thread> // #include <boost/lockfree/queue.hpp> #include <boost/lockfree/spsc_queue.hpp> #include <boost/utility.hpp> #include "Methcla/Utility/Semaphore.hpp" namespace Methcla { namespace Utility { //* MWSR queue for sending commands to the engine. // Request payload lifetime: from request until response callback. // Caller is responsible for freeing request payload after the response callback has been called. template <typename T, size_t queueSize> class MessageQueue : boost::noncopyable { public: inline void send(const T& msg) { std::lock_guard<std::mutex> lock(m_mutex); bool success = m_queue.push(msg); if (!success) throw std::runtime_error("Message queue overflow"); } inline bool next(T& msg) { return m_queue.pop(msg); } private: typedef boost::lockfree::spsc_queue<T,boost::lockfree::capacity<queueSize>> Queue; Queue m_queue; std::mutex m_mutex; }; template <typename Command, size_t queueSize> class Worker : boost::noncopyable { public: Worker() : m_toWorker(*this) { } void sendToWorker(const Command& cmd) { m_toWorker.send(cmd); } void sendFromWorker(const Command& cmd) { m_fromWorker.send(cmd); } void perform() { drain(m_fromWorker, m_toWorker); } protected: void work() { drain(m_toWorker, m_fromWorker); } friend class Transport; virtual void signalWorker() { } private: class Transport : boost::noncopyable { public: virtual void send(const Command& cmd) { bool success = m_queue.push(cmd); if (!success) throw std::runtime_error("Channel overflow"); } virtual bool dequeue(Command& cmd) = 0; protected: typedef boost::lockfree::spsc_queue<Command,boost::lockfree::capacity<queueSize>> Queue; // typedef boost::lockfree::queue<Command,boost::lockfree::capacity<queueSize>> Queue; Queue m_queue; }; class ToWorker : public Transport { public: ToWorker(Worker& worker) : m_worker(worker) { } virtual void send(const Command& cmd) override { Transport::send(cmd); m_worker.signalWorker(); } bool dequeue(Command& cmd) { std::lock_guard<std::mutex> lock(m_mutex); return this->m_queue.pop(cmd); } private: Worker& m_worker; std::mutex m_mutex; }; class FromWorker : public Transport { public: virtual void send(const Command& cmd) override { std::lock_guard<std::mutex> lock(m_mutex); Transport::send(cmd); } bool dequeue(Command& cmd) override { return this->m_queue.pop(cmd); } private: std::mutex m_mutex; }; inline static void drain(Transport& input, Transport& output) { for (;;) { Command cmd; bool success = input.dequeue(cmd); if (success) cmd.perform(); else break; } } private: ToWorker m_toWorker; FromWorker m_fromWorker; }; template <typename Command, size_t queueSize> class WorkerThread : public Worker<Command, queueSize> { public: WorkerThread(size_t numThreads=1) : m_continue(true) { for (size_t i=0; i < std::max<size_t>(1, numThreads); i++) { m_threads.push_back(std::thread(&WorkerThread::process, this)); } } ~WorkerThread() { m_continue.store(false, std::memory_order_acquire); m_sem.post(); for_each(m_threads.begin(), m_threads.end(), std::mem_fun_ref(&std::thread::join)); } private: void process() { for (;;) { m_sem.wait(); bool cont = m_continue.load(std::memory_order_release); if (cont) { this->work(); } else { break; } } } virtual void signalWorker() override { m_sem.post(); } private: std::vector<std::thread> m_threads; Semaphore m_sem; std::atomic<bool> m_continue; }; }; }; #endif // METHCLA_UTILITY_MESSAGEQUEUE_HPP_INCLUDED
// Copyright 2012-2013 Samplecount S.L. // // 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 METHCLA_UTILITY_MESSAGEQUEUE_HPP_INCLUDED #define METHCLA_UTILITY_MESSAGEQUEUE_HPP_INCLUDED #include <algorithm> #include <array> #include <atomic> #include <thread> // #include <boost/lockfree/queue.hpp> #include <boost/lockfree/spsc_queue.hpp> #include <boost/utility.hpp> #include "Methcla/Utility/Semaphore.hpp" namespace Methcla { namespace Utility { //* MWSR queue for sending commands to the engine. // Request payload lifetime: from request until response callback. // Caller is responsible for freeing request payload after the response callback has been called. template <typename T, size_t queueSize> class MessageQueue : boost::noncopyable { public: inline void send(const T& msg) { std::lock_guard<std::mutex> lock(m_mutex); bool success = m_queue.push(msg); if (!success) throw std::runtime_error("Message queue overflow"); } inline bool next(T& msg) { return m_queue.pop(msg); } private: typedef boost::lockfree::spsc_queue<T,boost::lockfree::capacity<queueSize>> Queue; Queue m_queue; std::mutex m_mutex; }; template <typename Command, size_t queueSize> class Worker : boost::noncopyable { public: Worker() : m_toWorker(*this) { } void sendToWorker(const Command& cmd) { m_toWorker.send(cmd); } void sendFromWorker(const Command& cmd) { m_fromWorker.send(cmd); } void perform() { drain(m_fromWorker); } protected: void work() { drain(m_toWorker); } friend class Transport; virtual void signalWorker() { } private: class Transport : boost::noncopyable { public: virtual void send(const Command& cmd) { bool success = m_queue.push(cmd); if (!success) throw std::runtime_error("Channel overflow"); } virtual bool dequeue(Command& cmd) = 0; protected: typedef boost::lockfree::spsc_queue<Command,boost::lockfree::capacity<queueSize>> Queue; // typedef boost::lockfree::queue<Command,boost::lockfree::capacity<queueSize>> Queue; Queue m_queue; }; class ToWorker : public Transport { public: ToWorker(Worker& worker) : m_worker(worker) { } virtual void send(const Command& cmd) override { Transport::send(cmd); m_worker.signalWorker(); } bool dequeue(Command& cmd) { std::lock_guard<std::mutex> lock(m_mutex); return this->m_queue.pop(cmd); } private: Worker& m_worker; std::mutex m_mutex; }; class FromWorker : public Transport { public: virtual void send(const Command& cmd) override { std::lock_guard<std::mutex> lock(m_mutex); Transport::send(cmd); } bool dequeue(Command& cmd) override { return this->m_queue.pop(cmd); } private: std::mutex m_mutex; }; inline static void drain(Transport& transport) { for (;;) { Command cmd; bool success = transport.dequeue(cmd); if (success) cmd.perform(); else break; } } private: ToWorker m_toWorker; FromWorker m_fromWorker; }; template <typename Command, size_t queueSize> class WorkerThread : public Worker<Command, queueSize> { public: WorkerThread(size_t numThreads=1) : m_continue(true) { for (size_t i=0; i < std::max<size_t>(1, numThreads); i++) { m_threads.push_back(std::thread(&WorkerThread::process, this)); } } ~WorkerThread() { m_continue.store(false, std::memory_order_acquire); m_sem.post(); for_each(m_threads.begin(), m_threads.end(), std::mem_fun_ref(&std::thread::join)); } private: void process() { for (;;) { m_sem.wait(); bool cont = m_continue.load(std::memory_order_release); if (cont) { this->work(); } else { break; } } } virtual void signalWorker() override { m_sem.post(); } private: std::vector<std::thread> m_threads; Semaphore m_sem; std::atomic<bool> m_continue; }; }; }; #endif // METHCLA_UTILITY_MESSAGEQUEUE_HPP_INCLUDED
Simplify method signatures of Worker implementation
Simplify method signatures of Worker implementation
C++
apache-2.0
samplecount/methcla,samplecount/methcla,samplecount/methcla,samplecount/methcla,samplecount/methcla,samplecount/methcla
c265dd560a9f483dac06890660bf0abe6109eb78
src/import/chips/ocmb/explorer/procedures/hwp/memory/exp_draminit_mc.H
src/import/chips/ocmb/explorer/procedures/hwp/memory/exp_draminit_mc.H
/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/chips/ocmb/explorer/procedures/hwp/memory/exp_draminit_mc.H $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2018,2019 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* Licensed under the Apache License, Version 2.0 (the "License"); */ /* you may not use this file except in compliance with the License. */ /* You may obtain a copy of the License at */ /* */ /* http://www.apache.org/licenses/LICENSE-2.0 */ /* */ /* Unless required by applicable law or agreed to in writing, software */ /* distributed under the License is distributed on an "AS IS" BASIS, */ /* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */ /* implied. See the License for the specific language governing */ /* permissions and limitations under the License. */ /* */ /* IBM_PROLOG_END_TAG */
/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/chips/ocmb/explorer/procedures/hwp/memory/exp_draminit_mc.H $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2018,2019 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* Licensed under the Apache License, Version 2.0 (the "License"); */ /* you may not use this file except in compliance with the License. */ /* You may obtain a copy of the License at */ /* */ /* http://www.apache.org/licenses/LICENSE-2.0 */ /* */ /* Unless required by applicable law or agreed to in writing, software */ /* distributed under the License is distributed on an "AS IS" BASIS, */ /* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */ /* implied. See the License for the specific language governing */ /* permissions and limitations under the License. */ /* */ /* IBM_PROLOG_END_TAG */ /// /// @file exp_draminit_mc.H /// @brief Initialize the memory controller to take over the DRAM /// // *HWP HWP Owner: Louis Stermole <[email protected]> // *HWP HWP Backup: Andre Marin <[email protected]> // *HWP Team: Memory // *HWP Level: 3 // *HWP Consumed by: FSP:HB #ifndef EXP_DRAMINIT_MC_H_ #define EXP_DRAMINIT_MC_H_ #include <fapi2.H> typedef fapi2::ReturnCode (*exp_draminit_mc_FP_t) (const fapi2::Target<fapi2::TARGET_TYPE_OCMB_CHIP>&); extern "C" { /// /// @brief Trains the OCMB link /// @param[in] i_target the OCMB target to operate on /// @return FAPI2_RC_SUCCESS iff ok /// fapi2::ReturnCode exp_draminit_mc(const fapi2::Target<fapi2::TARGET_TYPE_OCMB_CHIP>& i_target); } #endif
Add snapshot of ocmb/explorer for master-p10 branch
Add snapshot of ocmb/explorer for master-p10 branch Had to fix mss incorrect use of p9 attribute enums used in generic. Made a list of fixes to fix in ekb/master. Sets #5-7: Fix Jenkins build failure. Change-Id: Ia41f98decef59b055e04159183f23bb3f4780927 Original-Change-Id: I556a2e117d4dab2276ecd122650d253782c52e52 Reviewed-on: http://rchgit01.rchland.ibm.com/gerrit1/78083 Tested-by: Jenkins Server <[email protected]> Reviewed-by: Louis Stermole <[email protected]> Reviewed-by: STEPHEN GLANCY <[email protected]> Tested-by: PPE CI <[email protected]> Reviewed-by: Joseph J. McGill <[email protected]>
C++
apache-2.0
open-power/hostboot,open-power/hostboot,open-power/hostboot,open-power/hostboot,open-power/hostboot
b7b74e6a7c22445a21c252a99704dc61e7cc1803
tests/test_parallel_sequence.cpp
tests/test_parallel_sequence.cpp
#include <iostream> #include <vector> #include <cmath> #include <gtest/gtest.h> #include "../parallel.h" #include "../sequence.h" #include "../task.h" class ParallelSequenceTest : testing::Test { }; TEST(ParallelSequenceTest, Test1) { double total = asyncply::parallel_sync( [&]() { return asyncply::sequence(7.0, [](double data) { return data + 3.0; }, [](double data) { return data + 4.0; }); }, [&]() { return asyncply::sequence(9.0, [](double data) { return data + 5.0; }, [](double data) { return data + 4.0; }); }); ASSERT_EQ(total, 32.0); } TEST(ParallelSequenceTest, Test1) { double task = asyncply::parallel( [&]() { return asyncply::sequence(7.0, [](double data) { return data + 3.0; }, [](double data) { return data + 4.0; }); }, [&]() { return asyncply::sequence(9.0, [](double data) { return data + 5.0; }, [](double data) { return data + 4.0; }); }); double total = task->get(); ASSERT_EQ(total, 32.0); }
#include <iostream> #include <vector> #include <cmath> #include <gtest/gtest.h> #include "../parallel.h" #include "../sequence.h" #include "../task.h" class ParallelSequenceTest : testing::Test { }; TEST(ParallelSequenceTest, Test1) { double total = asyncply::parallel_sync( [&]() { return asyncply::sequence(7.0, [](double data) { return data + 3.0; }, [](double data) { return data + 4.0; }); }, [&]() { return asyncply::sequence(9.0, [](double data) { return data + 5.0; }, [](double data) { return data + 4.0; }); }); ASSERT_EQ(total, 32.0); } TEST(ParallelSequenceTest, Test2) { double task = asyncply::parallel( [&]() { return asyncply::sequence(7.0, [](double data) { return data + 3.0; }, [](double data) { return data + 4.0; }); }, [&]() { return asyncply::sequence(9.0, [](double data) { return data + 5.0; }, [](double data) { return data + 4.0; }); }); double total = task->get(); ASSERT_EQ(total, 32.0); }
Update test_parallel_sequence.cpp
Update test_parallel_sequence.cpp
C++
cc0-1.0
makiolo/asyncply,makiolo/asyncply,makiolo/async-ply,makiolo/asyncply
0504d0310e97d8a47f3f4858868235e29c35204f
src/i2c/i2c.cxx
src/i2c/i2c.cxx
/* * Copyright (C) Intel Corporation. * * Author: Brendan Le Foll * * Copyright © 2014 Intel Corporation * * 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 "i2c.h" #include "smbus.h" using namespace maa; I2C::I2C(unsigned int sda, unsigned int scl) { // Galileo only has one I2C device which is always /dev/i2c-0 // reliability is a fickle friend! if (i2c_handle = open("/dev/i2c-0", O_RDWR) < 1) { fprintf(stderr, "Failed to open requested i2c port"); } } void I2C::frequency(int hz) { _hz = hz; } int I2C::read(int address, char *data, int length, bool repeated) { return 0; } int I2C::read(int ack) { int byte; if (byte = i2c_smbus_read_byte(i2c_handle) < 0) { return -1; } return byte; } int I2C::write(int address, const char *data, int length, bool repeated) { return 0; } int I2C::write(int data) { } void I2C::start() { } void I2C::stop() { } void I2C::aquire() { }
/* * Copyright (C) Intel Corporation. * * Author: Brendan Le Foll * * Copyright © 2014 Intel Corporation * * 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 "i2c.h" #include "smbus.h" using namespace maa; I2C::I2C(unsigned int sda, unsigned int scl) { // Galileo only has one I2C device which is always /dev/i2c-0 // reliability is a fickle friend! if (i2c_handle = open("/dev/i2c-0", O_RDWR) < 1) { fprintf(stderr, "Failed to open requested i2c port"); } } void I2C::frequency(int hz) { _hz = hz; } int I2C::read(int address, char *data, int length, bool repeated) { return 0; } int I2C::read(int ack) { int byte; if (byte = i2c_smbus_read_byte(i2c_handle) < 0) { return -1; } return byte; } int I2C::write(int address, const char *data, int length, bool repeated) { if (i2c_smbus_write_i2c_block_data(i2c_handle, data[0], length, (uint8_t*) data) < 0) { fprintf(stderr, "Failed to write to I2C slave\n"); return -1; } return 0; } int I2C::write(int data) { if (i2c_smbus_write_byte(i2c_handle, data) < 0) { fprintf(stderr, "Failed to write to I2C slave\n"); return -1; } return 0; } void I2C::start() { } void I2C::stop() { } void I2C::aquire() { }
add functionality to write to i2c
i2c.cxx: add functionality to write to i2c Signed-off-by: Brendan Le Foll <[email protected]>
C++
mit
arunlee77/mraa,nioinnovation/mraa,spitfire88/mraa,pctj101/mraa,arfoll/mraa,neuberfran/mraa,alext-mkrs/mraa,anonymouse64/mraa,Jon-ICS/mraa,seem-sky/mraa,Jon-ICS/mraa,whbruce/mraa,damcclos/mraa,Kiritoalex/mraa,arfoll/mraa,timrtoo/Intel,whbruce/mraa,Hbrinj/mraa,Pillar1989/mraa,mircea/mraa,KurtE/mraa,alexandru-elisei/mraa,ncrastanaren/mraa,alext-mkrs/mraa,ncrastanaren/mraa,Hbrinj/mraa,spitfire88/mraa,yangjae/mraa,whbruce/mraa,neuberfran/mraa,KurtE/mraa,KurtE/mraa,petreeftime/mraa,zBMNForks/mraa,SyrianSpock/mraa,tripzero/mraa,sundw2014/mraa,noahchense/mraa,Propanu/mraa,w4ilun/mraa,petreeftime/mraa,malikabhi05/mraa,smileboywtu/mraa,petreeftime/mraa,jontrulson/mraa,intel-iot-devkit/mraa,matt-auld/mraa,malikabhi05/mraa,yoyojacky/mraa,ncrastanaren/mraa,allela-roy/mraa,sergev/mraa,neuberfran/mraa,Hbrinj/mraa,stefan-andritoiu/mraa-gpio-chardev,g-vidal/mraa,Meirtz/mraa,yangjae/mraa,seem-sky/mraa,intel-iot-devkit/mraa,stefan-andritoiu/mraa,arunlee77/mraa,neuroidss/mraa,sundw2014/mraa,yongli3/mraa,allela-roy/mraa,allela-roy/mraa,andreivasiliu2211/mraa,Meirtz/mraa,damcclos/mraa,malikabhi05/mraa,Kiritoalex/mraa,malikabhi05/mraa,arfoll/mraa,g-vidal/mraa,alexandru-elisei/mraa,stefan-andritoiu/mraa,whbruce/mraa,andreivasiliu2211/mraa,sundw2014/mraa,ProfFan/mraa,matt-auld/mraa,alexandru-elisei/mraa,tripzero/mraa,ProfFan/mraa,seem-sky/mraa,KurtE/mraa,Pillar1989/mraa,STANAPO/mraa,smileboywtu/mraa,mircea/mraa,seem-sky/mraa,yoyojacky/mraa,spitfire88/mraa,pctj101/mraa,yoyojacky/mraa,yongli3/mraa,seem-sky/mraa,stefan-andritoiu/mraa,alext-mkrs/mraa,matt-auld/mraa,alexandru-elisei/mraa,timrtoo/Intel,SyrianSpock/mraa,intel-iot-devkit/mraa,Propanu/mraa,alext-mkrs/mraa,nioinnovation/mraa,w4ilun/mraa,neuroidss/mraa,sundw2014/mraa,pctj101/mraa,neuroidss/mraa,ProfFan/mraa,ncrastanaren/mraa,stefan-andritoiu/mraa-gpio-chardev,Propanu/mraa,yongli3/mraa,stefan-andritoiu/mraa-gpio-chardev,noahchense/mraa,anonymouse64/mraa,sergev/mraa,malikabhi05/mraa,spitfire88/mraa,zBMNForks/mraa,stefan-andritoiu/mraa-gpio-chardev,alext-mkrs/mraa,yangjae/mraa,andreivasiliu2211/mraa,timrtoo/Intel,yongli3/mraa,jontrulson/mraa,stefan-andritoiu/mraa,Jon-ICS/mraa,timrtoo/Intel,mircea/mraa,Propanu/mraa,alex1818/mraa,pctj101/mraa,intel-iot-devkit/mraa,smileboywtu/mraa,intel-iot-devkit/mraa,alexandru-elisei/mraa,sergev/mraa,sergev/mraa,petreeftime/mraa,noahchense/mraa,g-vidal/mraa,andreivasiliu2211/mraa,ncrastanaren/mraa,SyrianSpock/mraa,sergev/mraa,Pillar1989/mraa,arfoll/mraa,w4ilun/mraa,STANAPO/mraa,w4ilun/mraa,neuberfran/mraa,pctj101/mraa,STANAPO/mraa,ProfFan/mraa,noahchense/mraa,tripzero/mraa,jontrulson/mraa,jontrulson/mraa,sundw2014/mraa,nioinnovation/mraa,arunlee77/mraa,Hbrinj/mraa,Kiritoalex/mraa,g-vidal/mraa,arunlee77/mraa,stefan-andritoiu/mraa-gpio-chardev,g-vidal/mraa,Meirtz/mraa,neuberfran/mraa,damcclos/mraa,timrtoo/Intel,Propanu/mraa,alex1818/mraa,jontrulson/mraa,alex1818/mraa,yongli3/mraa,noahchense/mraa,KurtE/mraa,stefan-andritoiu/mraa,zBMNForks/mraa,arfoll/mraa,yangjae/mraa,anonymouse64/mraa
c53b48ea741bfe76943950ad406ac1a5f7907f16
cpp/example_code/cloudwatch/put_events.cpp
cpp/example_code/cloudwatch/put_events.cpp
//snippet-sourcedescription:[put_events.cpp demonstrates how to post an Amazon CloudWatch event.] //snippet-keyword:[C++] //snippet-keyword:[Code Sample] //snippet-keyword:[Amazon CloudWatch Events] //snippet-service:[events] //snippet-sourcetype:[full-example] //snippet-sourcedate:[] //snippet-sourceauthor:[AWS] /* Copyright 2010-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. This file is licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with the License. A copy of the License is located at http://aws.amazon.com/apache2.0/ This file 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 <aws/core/Aws.h> #include <aws/events/CloudWatchEventsClient.h> #include <aws/events/model/PutEventsRequest.h> #include <aws/events/model/PutEventsResult.h> #include <aws/core/utils/Outcome.h> #include <iostream> Aws::String MakeDetails(const Aws::String &key, const Aws::String& value) { Aws::Utils::Json::JsonValue value_entry; value_entry.AsString(value); Aws::Utils::Json::JsonValue detail_map; detail_map.WithObject(key, value_entry); return detail_map.View().WriteReadable(); } /** * Posts a sample cloudwatch event, based on command line input */ int main(int argc, char** argv) { if (argc != 4) { std::cout << "Usage:" << std::endl << " put_events " << "<resource_arn> <sample_key> <sample_value>" << std::endl; return 1; } Aws::SDKOptions options; Aws::InitAPI(options); { Aws::String resource_arn(argv[1]); Aws::String event_key(argv[2]); Aws::String event_value(argv[3]); Aws::CloudWatchEvents::CloudWatchEventsClient cwe; Aws::CloudWatchEvents::Model::PutEventsRequestEntry event_entry; event_entry.SetDetail(MakeDetails(event_key, event_value)); event_entry.SetDetailType("sampleSubmitted"); event_entry.AddResources(resource_arn); event_entry.SetSource("aws-sdk-cpp-cloudwatch-example"); Aws::CloudWatchEvents::Model::PutEventsRequest request; request.AddEntries(event_entry); auto outcome = cwe.PutEvents(request); if (!outcome.IsSuccess()) { std::cout << "Failed to post cloudwatch event: " << outcome.GetError().GetMessage() << std::endl; } else { std::cout << "Successfully posted cloudwatch event" << std::endl; } } Aws::ShutdownAPI(options); return 0; }
//snippet-sourcedescription:[put_events.cpp demonstrates how to post an Amazon CloudWatch event.] //snippet-keyword:[C++] //snippet-keyword:[Code Sample] //snippet-keyword:[Amazon CloudWatch Events] //snippet-service:[events] //snippet-sourcetype:[full-example] //snippet-sourcedate:[] //snippet-sourceauthor:[AWS] /* Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. This file is licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with the License. A copy of the License is located at http://aws.amazon.com/apache2.0/ This file 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. */ //snippet-start:[cw.cpp.put_events.inc] #include <aws/core/Aws.h> #include <aws/events/CloudWatchEventsClient.h> #include <aws/events/model/PutEventsRequest.h> #include <aws/events/model/PutEventsResult.h> #include <aws/core/utils/Outcome.h> #include <iostream> //snippet-end:[cw.cpp.put_events.inc] Aws::String MakeDetails(const Aws::String &key, const Aws::String& value) { Aws::Utils::Json::JsonValue value_entry; value_entry.AsString(value); Aws::Utils::Json::JsonValue detail_map; detail_map.WithObject(key, value_entry); return detail_map.View().WriteReadable(); } /** * Posts a sample cloudwatch event, based on command line input */ int main(int argc, char** argv) { if (argc != 4) { std::cout << "Usage:" << std::endl << " put_events " << "<resource_arn> <sample_key> <sample_value>" << std::endl; return 1; } Aws::SDKOptions options; Aws::InitAPI(options); { Aws::String resource_arn(argv[1]); Aws::String event_key(argv[2]); Aws::String event_value(argv[3]); // snippet-start:[cw.cpp.put_events.code] Aws::CloudWatchEvents::CloudWatchEventsClient cwe; Aws::CloudWatchEvents::Model::PutEventsRequestEntry event_entry; event_entry.SetDetail(MakeDetails(event_key, event_value)); event_entry.SetDetailType("sampleSubmitted"); event_entry.AddResources(resource_arn); event_entry.SetSource("aws-sdk-cpp-cloudwatch-example"); Aws::CloudWatchEvents::Model::PutEventsRequest request; request.AddEntries(event_entry); auto outcome = cwe.PutEvents(request); if (!outcome.IsSuccess()) { std::cout << "Failed to post cloudwatch event: " << outcome.GetError().GetMessage() << std::endl; } else { std::cout << "Successfully posted cloudwatch event" << std::endl; } //snippet-end:[cw.cpp.put_events.code] } Aws::ShutdownAPI(options); return 0; }
Correct snippet-start to snippet-end.
Correct snippet-start to snippet-end.
C++
apache-2.0
awsdocs/aws-doc-sdk-examples,awsdocs/aws-doc-sdk-examples,awsdocs/aws-doc-sdk-examples,awsdocs/aws-doc-sdk-examples,awsdocs/aws-doc-sdk-examples,awsdocs/aws-doc-sdk-examples,awsdocs/aws-doc-sdk-examples,awsdocs/aws-doc-sdk-examples,awsdocs/aws-doc-sdk-examples,awsdocs/aws-doc-sdk-examples,awsdocs/aws-doc-sdk-examples,awsdocs/aws-doc-sdk-examples,awsdocs/aws-doc-sdk-examples,awsdocs/aws-doc-sdk-examples,awsdocs/aws-doc-sdk-examples
6e2224baddda61aed472a7b8cb1b9a544bcd910c
src/import/chips/p10/procedures/hwp/nest/p10_fbc_utils.H
src/import/chips/p10/procedures/hwp/nest/p10_fbc_utils.H
/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/chips/p10/procedures/hwp/nest/p10_fbc_utils.H $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2015,2019 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* Licensed under the Apache License, Version 2.0 (the "License"); */ /* you may not use this file except in compliance with the License. */ /* You may obtain a copy of the License at */ /* */ /* http://www.apache.org/licenses/LICENSE-2.0 */ /* */ /* Unless required by applicable law or agreed to in writing, software */ /* distributed under the License is distributed on an "AS IS" BASIS, */ /* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */ /* implied. See the License for the specific language governing */ /* permissions and limitations under the License. */ /* */ /* IBM_PROLOG_END_TAG */ /// /// @file p10_fbc_utils.H /// @brief Fabric library functions/constants (FAPI2) /// /// The functions in this file provide: /// - Information about the instantaneous state of the fabric /// - Means to restart the fabric after a checkstop condition /// - Determination of the chip's base address in the real address map /// - Ability to set all instances of a fabric racetrack scom /// - Extraction of group/chip bits from a topology id /// /// @author Joe McGill <[email protected]> /// /// *HWP HW Maintainer: Joe McGill <[email protected]> /// *HWP FW Maintainer: Ilya Smirnov <[email protected]> /// *HWP Consumed by: SBE,HB,FSP /// #ifndef _P10_FBC_UTILS_H_ #define _P10_FBC_UTILS_H_ //------------------------------------------------------------------------------ // Includes //------------------------------------------------------------------------------ #include <fapi2.H> //------------------------------------------------------------------------------ // Structure definitions //------------------------------------------------------------------------------ enum p10_fbc_utils_addr_mode { EFF_TOPOLOGY_ID, // effective FBC topology ID attributes HB_BOOT_ID // address 0 of drawer }; //------------------------------------------------------------------------------ // Constant definitions //------------------------------------------------------------------------------ #ifndef __PPE_QME // address range definitions const uint64_t P10_FBC_UTILS_FBC_MAX_ADDRESS = ((1ULL << 56) - 1ULL); const uint64_t P10_FBC_UTILS_CACHELINE_MASK = 0x7FULL; const uint64_t P10_FBC_UTILS_LAST_ADDR_IN_CACHELINE = 0x78ULL; // cacheline size = 128B const uint64_t FABRIC_CACHELINE_SIZE = 0x80; // fbc racetrack stations const uint8_t FABRIC_NUM_STATIONS = 16; // fbc max number of iohs links const uint8_t FABRIC_NUM_IOHS_LINKS = 8; // max memory interleave = 16TB const uint64_t MAX_INTERLEAVE_GROUP_SIZE = 0x0000100000000000ULL; // fbc base address determination constants const uint8_t FABRIC_ADDR_SMF_BIT = 12; const uint8_t FABRIC_ADDR_MSEL_START_BIT = 13; const uint8_t FABRIC_ADDR_MSEL_END_BIT = 14; const uint8_t FABRIC_ADDR_TOPO_ID_INDEX_START_BIT = 15; const uint8_t FABRIC_ADDR_TOPO_ID_INDEX_END_BIT = 19; // smp configuration definitions const uint8_t P10_FBC_UTILS_MAX_LINKS = 8; const uint8_t P10_FBC_UTILS_MAX_CHIPS = 8; // phase1 used to init scope of hbi drawer, call from hb // phase2 used to stitch drawers, call from fsp enum p10_build_smp_operation { SMP_ACTIVATE_PHASE1 = 1, SMP_ACTIVATE_PHASE2 = 2 }; #endif // !__PPE_QME //------------------------------------------------------------------------------ // Function prototypes //------------------------------------------------------------------------------ namespace topo { /// /// @brief Determine this chip's unique 5b index into the fabric topology id /// table from the 4b topology id. /// Note: this 5b index represents RA[15:19] /// @param[in] i_target Reference to processor chip target /// @param[in] i_addr_mode HB_BOOT_ID or EFF_TOPOLOGY_ID (chip 0 of /// drawer vs eff topology id) /// @param[out] o_topology_idx 5b index into the topology id table /// @return fapi::ReturnCode FAPI2_RC_SUCCESS on success, error otherwise /// fapi2::ReturnCode get_topology_idx( const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target, const p10_fbc_utils_addr_mode& i_addr_mode, uint8_t& o_topology_idx); /// /// @brief Initialize chip's entry in the topology id table. /// @param[in] i_target Reference to processor chip target /// @return fapi::ReturnCode FAPI2_RC_SUCCESS on success, error otherwise /// fapi2::ReturnCode init_topology_id_table( const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target); /// /// @brief Initialize each chips' entry in the topology id table. /// @param[in] i_target Reference to processor chip target /// @return fapi::ReturnCode FAPI2_RC_SUCCESS on success, error otherwise /// fapi2::ReturnCode init_topology_id_table( const std::vector<fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>>& i_targets); /// /// @brief Return the topology id table formatted /// as SCOM register values. /// @param[in] i_target Reference to processor chip target /// @param[out] o_topology_id_table_scoms Vector of register values to setup the topology id /// entries in fabric unit SCOM registers: /// *TOPOLOGY_TBL0_SCOM_* /// *TOPOLOGY_TBL1_SCOM_* /// *TOPOLOGY_TBL2_SCOM_* /// *TOPOLOGY_TBL3_SCOM_* /// @return fapi::ReturnCode FAPI2_RC_SUCCESS on success, error otherwise /// fapi2::ReturnCode get_topology_table_scoms( const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target, std::vector<uint64_t>& o_topology_id_table_scoms); }; // namespace topo #ifndef __PPE_QME /// /// @brief Read FBC/ADU registers to determine state of fabric init and stop /// control signals /// /// @param[in] i_target Reference to processor chip target /// @param[out] o_is_initialized State of fabric init signal /// @param[out] o_is_running State of fabric pervasive stop control /// @return fapi::ReturnCode FAPI2_RC_SUCCESS if success, else error code. /// fapi2::ReturnCode p10_fbc_utils_get_fbc_state( const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target, bool& o_is_initialized, bool& o_is_running); /// /// @brief Use ADU pMisc Mode register to clear fabric stop signal, overriding /// a stop condition caused by a checkstop /// /// @param[in] i_target Reference to processor chip target /// @return fapi::ReturnCode FAPI2_RC_SUCCESS if success, else error code. /// fapi2::ReturnCode p10_fbc_utils_override_fbc_stop( const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target); /// /// @brief Dynamically determine base address for a given chip /// /// @param[in] i_target Reference to processor chip target /// @param[in] i_addr_mode HB_BOOT_ID or EFF_TOPOLOGY_ID (chip 0 of /// drawer vs eff topology id) /// @param[out] o_base_address_nm0 base address of nm0 region of memory map /// @param[out] o_base_address_nm1 base address of nm1 region of memory map /// @param[out] o_base_address_m base address of m region of memory map /// @param[out] o_base_address_mmio base address of mmio region of memory map /// @return fapi2::ReturnCode FAPI2_RC_SUCCESS if success, else error code. /// fapi2::ReturnCode p10_fbc_utils_get_chip_base_address( const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target, const p10_fbc_utils_addr_mode i_addr_mode, uint64_t& o_base_address_nm0, uint64_t& o_base_address_nm1, uint64_t& o_base_address_m, uint64_t& o_base_address_mmio); /// /// @brief Write to all instances of a given racetrack scom register /// /// @param[in] i_target Reference to processor chip target /// @param[in] i_scom_addr Scom address for EQ0 instance of racetrack regs /// @param[in] i_scom_data Scom data to write, assumes 64-bit value /// @return fapi2::ReturnCode FAPI2_RC_SUCCESS if success, else error code. /// fapi2::ReturnCode p10_fbc_utils_set_racetrack_regs( const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target, const uint64_t i_scom_addr, const uint64_t i_scom_data); /// /// @brief Extract group/chip bits from fabric topology ID based on topology mode /// /// @param[in] i_target Reference to processor chip target /// @param[out] o_topology_group_id Topology ID group bits, right-aligned /// @param[out] o_topology_chip_id Topology ID chip bits, right-aligned /// @return fapi2::ReturnCode FAPI2_RC_SUCCESS if success, else error /// fapi2::ReturnCode p10_fbc_utils_get_topology_id( const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target, uint8_t& o_topology_group_id, uint8_t& o_topology_chip_id); #endif // !__PPE_QME #endif // _P10_FBC_UTILS_H_
/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/chips/p10/procedures/hwp/nest/p10_fbc_utils.H $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2015,2019 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* Licensed under the Apache License, Version 2.0 (the "License"); */ /* you may not use this file except in compliance with the License. */ /* You may obtain a copy of the License at */ /* */ /* http://www.apache.org/licenses/LICENSE-2.0 */ /* */ /* Unless required by applicable law or agreed to in writing, software */ /* distributed under the License is distributed on an "AS IS" BASIS, */ /* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */ /* implied. See the License for the specific language governing */ /* permissions and limitations under the License. */ /* */ /* IBM_PROLOG_END_TAG */ /// /// @file p10_fbc_utils.H /// @brief Fabric library functions/constants (FAPI2) /// /// The functions in this file provide: /// - Information about the instantaneous state of the fabric /// - Means to restart the fabric after a checkstop condition /// - Determination of the chip's base address in the real address map /// - Ability to set all instances of a fabric racetrack scom /// - Extraction of group/chip bits from a topology id /// /// @author Joe McGill <[email protected]> /// /// *HWP HW Maintainer: Joe McGill <[email protected]> /// *HWP FW Maintainer: Ilya Smirnov <[email protected]> /// *HWP Consumed by: SBE,HB,FSP /// #ifndef _P10_FBC_UTILS_H_ #define _P10_FBC_UTILS_H_ //------------------------------------------------------------------------------ // Includes //------------------------------------------------------------------------------ #include <fapi2.H> //------------------------------------------------------------------------------ // Structure definitions //------------------------------------------------------------------------------ enum p10_fbc_utils_addr_mode { EFF_TOPOLOGY_ID, // effective FBC topology ID attributes HB_BOOT_ID // address 0 of drawer }; //------------------------------------------------------------------------------ // Constant definitions //------------------------------------------------------------------------------ #ifndef __PPE_QME // address range definitions const uint64_t P10_FBC_UTILS_FBC_MAX_ADDRESS = ((1ULL << 56) - 1ULL); const uint64_t P10_FBC_UTILS_CACHELINE_MASK = 0x7FULL; const uint64_t P10_FBC_UTILS_LAST_ADDR_IN_CACHELINE = 0x78ULL; // cacheline size = 128B const uint64_t FABRIC_CACHELINE_SIZE = 0x80; // fbc racetrack stations const uint8_t FABRIC_NUM_STATIONS = 16; // fbc max number of iohs links const uint8_t FABRIC_NUM_IOHS_LINKS = 8; // max memory interleave = 16TB const uint64_t MAX_INTERLEAVE_GROUP_SIZE = 0x0000100000000000ULL; // fbc base address determination constants const uint8_t FABRIC_ADDR_SMF_BIT = 12; const uint8_t FABRIC_ADDR_MSEL_START_BIT = 13; const uint8_t FABRIC_ADDR_MSEL_END_BIT = 14; const uint8_t FABRIC_ADDR_TOPO_ID_INDEX_START_BIT = 15; const uint8_t FABRIC_ADDR_TOPO_ID_INDEX_END_BIT = 19; // smp configuration definitions const uint8_t P10_FBC_UTILS_MAX_LINKS = 8; const uint8_t P10_FBC_UTILS_MAX_CHIPS = 8; #endif // !__PPE_QME //------------------------------------------------------------------------------ // Function prototypes //------------------------------------------------------------------------------ namespace topo { /// /// @brief Determine this chip's unique 5b index into the fabric topology id /// table from the 4b topology id. /// Note: this 5b index represents RA[15:19] /// @param[in] i_target Reference to processor chip target /// @param[in] i_addr_mode HB_BOOT_ID or EFF_TOPOLOGY_ID (chip 0 of /// drawer vs eff topology id) /// @param[out] o_topology_idx 5b index into the topology id table /// @return fapi::ReturnCode FAPI2_RC_SUCCESS on success, error otherwise /// fapi2::ReturnCode get_topology_idx( const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target, const p10_fbc_utils_addr_mode& i_addr_mode, uint8_t& o_topology_idx); /// /// @brief Initialize chip's entry in the topology id table. /// @param[in] i_target Reference to processor chip target /// @return fapi::ReturnCode FAPI2_RC_SUCCESS on success, error otherwise /// fapi2::ReturnCode init_topology_id_table( const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target); /// /// @brief Initialize each chips' entry in the topology id table. /// @param[in] i_target Reference to processor chip target /// @return fapi::ReturnCode FAPI2_RC_SUCCESS on success, error otherwise /// fapi2::ReturnCode init_topology_id_table( const std::vector<fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>>& i_targets); /// /// @brief Return the topology id table formatted /// as SCOM register values. /// @param[in] i_target Reference to processor chip target /// @param[out] o_topology_id_table_scoms Vector of register values to setup the topology id /// entries in fabric unit SCOM registers: /// *TOPOLOGY_TBL0_SCOM_* /// *TOPOLOGY_TBL1_SCOM_* /// *TOPOLOGY_TBL2_SCOM_* /// *TOPOLOGY_TBL3_SCOM_* /// @return fapi::ReturnCode FAPI2_RC_SUCCESS on success, error otherwise /// fapi2::ReturnCode get_topology_table_scoms( const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target, std::vector<uint64_t>& o_topology_id_table_scoms); }; // namespace topo #ifndef __PPE_QME /// /// @brief Read FBC/ADU registers to determine state of fabric init and stop /// control signals /// /// @param[in] i_target Reference to processor chip target /// @param[out] o_is_initialized State of fabric init signal /// @param[out] o_is_running State of fabric pervasive stop control /// @return fapi::ReturnCode FAPI2_RC_SUCCESS if success, else error code. /// fapi2::ReturnCode p10_fbc_utils_get_fbc_state( const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target, bool& o_is_initialized, bool& o_is_running); /// /// @brief Use ADU pMisc Mode register to clear fabric stop signal, overriding /// a stop condition caused by a checkstop /// /// @param[in] i_target Reference to processor chip target /// @return fapi::ReturnCode FAPI2_RC_SUCCESS if success, else error code. /// fapi2::ReturnCode p10_fbc_utils_override_fbc_stop( const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target); /// /// @brief Dynamically determine base address for a given chip /// /// @param[in] i_target Reference to processor chip target /// @param[in] i_addr_mode HB_BOOT_ID or EFF_TOPOLOGY_ID (chip 0 of /// drawer vs eff topology id) /// @param[out] o_base_address_nm0 base address of nm0 region of memory map /// @param[out] o_base_address_nm1 base address of nm1 region of memory map /// @param[out] o_base_address_m base address of m region of memory map /// @param[out] o_base_address_mmio base address of mmio region of memory map /// @return fapi2::ReturnCode FAPI2_RC_SUCCESS if success, else error code. /// fapi2::ReturnCode p10_fbc_utils_get_chip_base_address( const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target, const p10_fbc_utils_addr_mode i_addr_mode, uint64_t& o_base_address_nm0, uint64_t& o_base_address_nm1, uint64_t& o_base_address_m, uint64_t& o_base_address_mmio); /// /// @brief Write to all instances of a given racetrack scom register /// /// @param[in] i_target Reference to processor chip target /// @param[in] i_scom_addr Scom address for EQ0 instance of racetrack regs /// @param[in] i_scom_data Scom data to write, assumes 64-bit value /// @return fapi2::ReturnCode FAPI2_RC_SUCCESS if success, else error code. /// fapi2::ReturnCode p10_fbc_utils_set_racetrack_regs( const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target, const uint64_t i_scom_addr, const uint64_t i_scom_data); /// /// @brief Extract group/chip bits from fabric topology ID based on topology mode /// /// @param[in] i_target Reference to processor chip target /// @param[out] o_topology_group_id Topology ID group bits, right-aligned /// @param[out] o_topology_chip_id Topology ID chip bits, right-aligned /// @return fapi2::ReturnCode FAPI2_RC_SUCCESS if success, else error /// fapi2::ReturnCode p10_fbc_utils_get_topology_id( const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target, uint8_t& o_topology_group_id, uint8_t& o_topology_chip_id); #endif // !__PPE_QME #endif // _P10_FBC_UTILS_H_
Implement p10_build_smp procedure (2/2)
Implement p10_build_smp procedure (2/2) Prepares fabric hotplug registers and issues switch sequence to transition from single-chip island mode to a multi-chip smp. Patch 1: Move p10_build_smp_operation enum to p10_build_smp.H file Patch 2: Update p10_build_smp_adu registers/options for P10 Patch 3: Update p10_build_smp_fbc_ab for P10 - update next/curr utility functions to address racetrack regs - temp functions to apply ab hp register values Patch 4: Update process_chip, insert_chip(s), check_topology functions Patch 5: Update validate_link function Patch 6: Fix iovalid check in validate_link function TODO: - Call p10_fbc_ab_hp_scom initfile when figtree is updated (HW468835) Change-Id: Ie6a9e7f63f754fc6b09666c5516605d98a43b189 Original-Change-Id: I5c0e467b479787d23b327ad61e589c5b3e30d3df RTC:202069 CQ:HW468835 Reviewed-on: http://rchgit01.rchland.ibm.com/gerrit1/82842 Tested-by: Jenkins Server <[email protected]> Tested-by: PPE CI <[email protected]> Tested-by: Hostboot CI <[email protected]> Reviewed-by: Joseph J McGill <[email protected]> Reviewed-by: Thi N Tran <[email protected]> Reviewed-by: Jennifer A Stofer <[email protected]> Reviewed-on: http://rchgit01.rchland.ibm.com/gerrit1/83641 Reviewed-by: Nicholas E Bofferding <[email protected]>
C++
apache-2.0
open-power/hostboot,open-power/hostboot,open-power/hostboot,open-power/hostboot,open-power/hostboot
f85978865d8fec4fd4d59f2ae4fa39c47476763a
appshell/client_handler_win.cpp
appshell/client_handler_win.cpp
// Copyright (c) 2011 The Chromium Embedded Framework 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 "config.h" #include "client_handler.h" #include <string> #include "include/cef_browser.h" #include "include/cef_frame.h" #include "resource.h" #include "native_menu_model.h" #include <ShellAPI.h> #define CLOSING_PROP L"CLOSING" extern CefRefPtr<ClientHandler> g_handler; // WM_DROPFILES handler, defined in cefclient_win.cpp extern LRESULT HandleDropFiles(HDROP hDrop, CefRefPtr<ClientHandler> handler, CefRefPtr<CefBrowser> browser); // Additional globals extern HACCEL hAccelTable; bool ClientHandler::OnBeforePopup(CefRefPtr<CefBrowser> parentBrowser, const CefPopupFeatures& popupFeatures, CefWindowInfo& windowInfo, const CefString& url, CefRefPtr<CefClient>& client, CefBrowserSettings& settings) { return false; } void ClientHandler::OnAddressChange(CefRefPtr<CefBrowser> browser, CefRefPtr<CefFrame> frame, const CefString& url) { REQUIRE_UI_THREAD(); #ifdef SHOW_TOOLBAR_UI if (m_BrowserId == browser->GetIdentifier() && frame->IsMain()) { // Set the edit window text SetWindowText(m_EditHwnd, std::wstring(url).c_str()); } #endif // SHOW_TOOLBAR_UI } void ClientHandler::OnTitleChange(CefRefPtr<CefBrowser> browser, const CefString& title) { REQUIRE_UI_THREAD(); // Set the frame window title bar CefWindowHandle hwnd = browser->GetHost()->GetWindowHandle(); if (m_BrowserId == browser->GetIdentifier()) { // The frame window will be the parent of the browser window hwnd = GetParent(hwnd); } SetWindowText(hwnd, std::wstring(title).c_str()); } void ClientHandler::SendNotification(NotificationType type) { UINT id; switch (type) { case NOTIFY_CONSOLE_MESSAGE: id = ID_WARN_CONSOLEMESSAGE; break; case NOTIFY_DOWNLOAD_COMPLETE: id = ID_WARN_DOWNLOADCOMPLETE; break; case NOTIFY_DOWNLOAD_ERROR: id = ID_WARN_DOWNLOADERROR; break; default: return; } PostMessage(m_MainHwnd, WM_COMMAND, id, 0); } void ClientHandler::SetLoading(bool isLoading) { #ifdef SHOW_TOOLBAR_UI ASSERT(m_EditHwnd != NULL && m_ReloadHwnd != NULL && m_StopHwnd != NULL); EnableWindow(m_EditHwnd, TRUE); EnableWindow(m_ReloadHwnd, !isLoading); EnableWindow(m_StopHwnd, isLoading); #endif // SHOW_TOOLBAR_UI } void ClientHandler::SetNavState(bool canGoBack, bool canGoForward) { #ifdef SHOW_TOOLBAR_UI ASSERT(m_BackHwnd != NULL && m_ForwardHwnd != NULL); EnableWindow(m_BackHwnd, canGoBack); EnableWindow(m_ForwardHwnd, canGoForward); #endif // SHOW_TOOLBAR_UI } void ClientHandler::CloseMainWindow() { ::PostMessage(m_MainHwnd, WM_CLOSE, 0, 0); } static WNDPROC g_popupWndOldProc = NULL; //BRACKETS: added so our popup windows can have a menu bar too // // FUNCTION: PopupWndProc(HWND, UINT, WPARAM, LPARAM) // // PURPOSE: Handle commands from the menus. LRESULT CALLBACK PopupWndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) { //For now, we are only interest in WM_COMMAND's that we know are in our menus //and WM_CLOSE so we can delegate that back to the browser CefRefPtr<CefBrowser> browser = ClientHandler::GetBrowserForNativeWindow(hWnd); switch (message) { case WM_COMMAND: { int wmId = LOWORD(wParam); int wmEvent = HIWORD(wParam); // Parse the menu selections: switch (wmId) { case IDM_CLOSE: if (g_handler.get() && browser.get()) { HWND browserHwnd = browser->GetHost()->GetWindowHandle(); HANDLE closing = GetProp(browserHwnd, CLOSING_PROP); if (closing) { RemoveProp(browserHwnd, CLOSING_PROP); break; } CefRefPtr<CommandCallback> callback = new CloseWindowCommandCallback(browser); g_handler->SendJSCommand(browser, FILE_CLOSE_WINDOW, callback); } return 0; default: ExtensionString commandId = NativeMenuModel::getInstance(getMenuParent(browser)).getCommandId(wmId); if (commandId.size() > 0) { CefRefPtr<CommandCallback> callback = new EditCommandCallback(browser, commandId); g_handler->SendJSCommand(browser, commandId, callback); } } } break; case WM_CLOSE: if (g_handler.get() && browser.get()) { HWND browserHwnd = browser->GetHost()->GetWindowHandle(); HANDLE closing = GetProp(browserHwnd, CLOSING_PROP); if (closing) { RemoveProp(browserHwnd, CLOSING_PROP); break; } CefRefPtr<CommandCallback> callback = new CloseWindowCommandCallback(browser); g_handler->SendJSCommand(browser, FILE_CLOSE_WINDOW, callback); return 0; } break; case WM_DROPFILES: if (g_handler.get() && browser.get()) { return HandleDropFiles((HDROP)wParam, g_handler, browser); } break; case WM_INITMENUPOPUP: HMENU menu = (HMENU)wParam; int count = GetMenuItemCount(menu); void* menuParent = getMenuParent(browser); for (int i = 0; i < count; i++) { UINT id = GetMenuItemID(menu, i); bool enabled = NativeMenuModel::getInstance(menuParent).isMenuItemEnabled(id); UINT flagEnabled = enabled ? MF_ENABLED | MF_BYCOMMAND : MF_DISABLED | MF_BYCOMMAND; EnableMenuItem(menu, id, flagEnabled); bool checked = NativeMenuModel::getInstance(menuParent).isMenuItemChecked(id); UINT flagChecked = checked ? MF_CHECKED | MF_BYCOMMAND : MF_UNCHECKED | MF_BYCOMMAND; CheckMenuItem(menu, id, flagChecked); } break; } if (g_popupWndOldProc) return (LRESULT)::CallWindowProc(g_popupWndOldProc, hWnd, message, wParam, lParam); return ::DefWindowProc(hWnd, message, wParam, lParam); } void AttachWindProcToPopup(HWND wnd) { if (!wnd) { return; } WNDPROC curProc = reinterpret_cast<WNDPROC>(GetWindowLongPtr(wnd, GWLP_WNDPROC)); //if this is the first time, assume the above checks are all we need, otherwise //it had better be the same proc we pulled before if (!g_popupWndOldProc) { g_popupWndOldProc = curProc; } else if (g_popupWndOldProc != curProc) { return; } SetWindowLongPtr(wnd, GWLP_WNDPROC, reinterpret_cast<LONG_PTR>(PopupWndProc)); } void LoadWindowsIcons(HWND wnd) { if (!wnd) { return; } //We need to load the icons after the pop up is created so they have the //brackets icon instead of the generic window icon HINSTANCE inst = ::GetModuleHandle(NULL); HICON bigIcon = ::LoadIcon(inst, MAKEINTRESOURCE(IDI_CEFCLIENT)); HICON smIcon = ::LoadIcon(inst, MAKEINTRESOURCE(IDI_SMALL)); if(bigIcon) { ::SendMessage(wnd, WM_SETICON, ICON_BIG, (LPARAM)bigIcon); } if(smIcon) { ::SendMessage(wnd, WM_SETICON, ICON_SMALL, (LPARAM)smIcon); } } void ClientHandler::PopupCreated(CefRefPtr<CefBrowser> browser) { HWND hWnd = browser->GetHost()->GetWindowHandle(); AttachWindProcToPopup(hWnd); LoadWindowsIcons(hWnd); DragAcceptFiles(hWnd, true); browser->GetHost()->SetFocus(true); } CefRefPtr<CefBrowser> ClientHandler::GetBrowserForNativeWindow(void* window) { CefRefPtr<CefBrowser> browser = NULL; if (window) { //go through all the browsers looking for a browser within this window BrowserWindowMap::const_iterator i = browser_window_map_.find((HWND)window); if (i != browser_window_map_.end()) { browser = i->second; } } return browser; } bool ClientHandler::CanCloseBrowser(CefRefPtr<CefBrowser> browser) { // On windows, the main browser needs to be destroyed last. // So, don't allow main browser to be closed until there's // only 1 browser remaining in the map. return (browser_window_map_.size() == 1) || (browser && browser->GetIdentifier() != m_BrowserId); } bool ClientHandler::OnPreKeyEvent(CefRefPtr<CefBrowser> browser, const CefKeyEvent& event, CefEventHandle os_event, bool* is_keyboard_shortcut) { if (::TranslateAccelerator((HWND)getMenuParent(browser), hAccelTable, os_event)) { return true; } return false; } bool ClientHandler::OnKeyEvent(CefRefPtr<CefBrowser> browser, const CefKeyEvent& event, CefEventHandle os_event) { return false; }
// Copyright (c) 2011 The Chromium Embedded Framework 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 "config.h" #include "client_handler.h" #include <string> #include "include/cef_browser.h" #include "include/cef_frame.h" #include "resource.h" #include "native_menu_model.h" #include <ShellAPI.h> #define CLOSING_PROP L"CLOSING" extern CefRefPtr<ClientHandler> g_handler; // WM_DROPFILES handler, defined in cefclient_win.cpp extern LRESULT HandleDropFiles(HDROP hDrop, CefRefPtr<ClientHandler> handler, CefRefPtr<CefBrowser> browser); // Additional globals extern HACCEL hAccelTable; bool ClientHandler::OnBeforePopup(CefRefPtr<CefBrowser> parentBrowser, const CefPopupFeatures& popupFeatures, CefWindowInfo& windowInfo, const CefString& url, CefRefPtr<CefClient>& client, CefBrowserSettings& settings) { return false; } void ClientHandler::OnAddressChange(CefRefPtr<CefBrowser> browser, CefRefPtr<CefFrame> frame, const CefString& url) { REQUIRE_UI_THREAD(); #ifdef SHOW_TOOLBAR_UI if (m_BrowserId == browser->GetIdentifier() && frame->IsMain()) { // Set the edit window text SetWindowText(m_EditHwnd, std::wstring(url).c_str()); } #endif // SHOW_TOOLBAR_UI } void ClientHandler::OnTitleChange(CefRefPtr<CefBrowser> browser, const CefString& title) { REQUIRE_UI_THREAD(); // Set the frame window title bar CefWindowHandle hwnd = browser->GetHost()->GetWindowHandle(); if (m_BrowserId == browser->GetIdentifier()) { // The frame window will be the parent of the browser window hwnd = GetParent(hwnd); } SetWindowText(hwnd, std::wstring(title).c_str()); } void ClientHandler::SendNotification(NotificationType type) { UINT id; switch (type) { case NOTIFY_CONSOLE_MESSAGE: id = ID_WARN_CONSOLEMESSAGE; break; case NOTIFY_DOWNLOAD_COMPLETE: id = ID_WARN_DOWNLOADCOMPLETE; break; case NOTIFY_DOWNLOAD_ERROR: id = ID_WARN_DOWNLOADERROR; break; default: return; } PostMessage(m_MainHwnd, WM_COMMAND, id, 0); } void ClientHandler::SetLoading(bool isLoading) { #ifdef SHOW_TOOLBAR_UI ASSERT(m_EditHwnd != NULL && m_ReloadHwnd != NULL && m_StopHwnd != NULL); EnableWindow(m_EditHwnd, TRUE); EnableWindow(m_ReloadHwnd, !isLoading); EnableWindow(m_StopHwnd, isLoading); #endif // SHOW_TOOLBAR_UI } void ClientHandler::SetNavState(bool canGoBack, bool canGoForward) { #ifdef SHOW_TOOLBAR_UI ASSERT(m_BackHwnd != NULL && m_ForwardHwnd != NULL); EnableWindow(m_BackHwnd, canGoBack); EnableWindow(m_ForwardHwnd, canGoForward); #endif // SHOW_TOOLBAR_UI } void ClientHandler::CloseMainWindow() { ::PostMessage(m_MainHwnd, WM_CLOSE, 0, 0); } static WNDPROC g_popupWndOldProc = NULL; //BRACKETS: added so our popup windows can have a menu bar too // // FUNCTION: PopupWndProc(HWND, UINT, WPARAM, LPARAM) // // PURPOSE: Handle commands from the menus. LRESULT CALLBACK PopupWndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) { //For now, we are only interest in WM_COMMAND's that we know are in our menus //and WM_CLOSE so we can delegate that back to the browser CefRefPtr<CefBrowser> browser = ClientHandler::GetBrowserForNativeWindow(hWnd); switch (message) { case WM_COMMAND: { int wmId = LOWORD(wParam); int wmEvent = HIWORD(wParam); // Parse the menu selections: switch (wmId) { case IDM_CLOSE: if (g_handler.get() && browser.get()) { HWND browserHwnd = browser->GetHost()->GetWindowHandle(); HANDLE closing = GetProp(browserHwnd, CLOSING_PROP); if (closing) { RemoveProp(browserHwnd, CLOSING_PROP); break; } CefRefPtr<CommandCallback> callback = new CloseWindowCommandCallback(browser); g_handler->SendJSCommand(browser, FILE_CLOSE_WINDOW, callback); } return 0; default: ExtensionString commandId = NativeMenuModel::getInstance(getMenuParent(browser)).getCommandId(wmId); if (commandId.size() > 0) { CefRefPtr<CommandCallback> callback = new EditCommandCallback(browser, commandId); g_handler->SendJSCommand(browser, commandId, callback); } } } break; case WM_CLOSE: if (g_handler.get() && browser.get()) { HWND browserHwnd = browser->GetHost()->GetWindowHandle(); HANDLE closing = GetProp(browserHwnd, CLOSING_PROP); if (closing) { RemoveProp(browserHwnd, CLOSING_PROP); break; } CefRefPtr<CommandCallback> callback = new CloseWindowCommandCallback(browser); g_handler->SendJSCommand(browser, FILE_CLOSE_WINDOW, callback); return 0; } break; case WM_DROPFILES: if (g_handler.get() && browser.get()) { return HandleDropFiles((HDROP)wParam, g_handler, browser); } break; case WM_INITMENUPOPUP: HMENU menu = (HMENU)wParam; int count = GetMenuItemCount(menu); void* menuParent = getMenuParent(browser); for (int i = 0; i < count; i++) { UINT id = GetMenuItemID(menu, i); bool enabled = NativeMenuModel::getInstance(menuParent).isMenuItemEnabled(id); UINT flagEnabled = enabled ? MF_ENABLED | MF_BYCOMMAND : MF_DISABLED | MF_BYCOMMAND; EnableMenuItem(menu, id, flagEnabled); bool checked = NativeMenuModel::getInstance(menuParent).isMenuItemChecked(id); UINT flagChecked = checked ? MF_CHECKED | MF_BYCOMMAND : MF_UNCHECKED | MF_BYCOMMAND; CheckMenuItem(menu, id, flagChecked); } break; } if (g_popupWndOldProc) return (LRESULT)::CallWindowProc(g_popupWndOldProc, hWnd, message, wParam, lParam); return ::DefWindowProc(hWnd, message, wParam, lParam); } void AttachWindProcToPopup(HWND wnd) { if (!wnd) { return; } WNDPROC curProc = reinterpret_cast<WNDPROC>(GetWindowLongPtr(wnd, GWLP_WNDPROC)); //if this is the first time, assume the above checks are all we need, otherwise //it had better be the same proc we pulled before if (!g_popupWndOldProc) { g_popupWndOldProc = curProc; } else if (g_popupWndOldProc != curProc) { return; } SetWindowLongPtr(wnd, GWLP_WNDPROC, reinterpret_cast<LONG_PTR>(PopupWndProc)); } void LoadWindowsIcons(HWND wnd) { if (!wnd) { return; } //We need to load the icons after the pop up is created so they have the //brackets icon instead of the generic window icon HINSTANCE inst = ::GetModuleHandle(NULL); HICON bigIcon = ::LoadIcon(inst, MAKEINTRESOURCE(IDI_CEFCLIENT)); HICON smIcon = ::LoadIcon(inst, MAKEINTRESOURCE(IDI_SMALL)); if(bigIcon) { ::SendMessage(wnd, WM_SETICON, ICON_BIG, (LPARAM)bigIcon); } if(smIcon) { ::SendMessage(wnd, WM_SETICON, ICON_SMALL, (LPARAM)smIcon); } } void ClientHandler::PopupCreated(CefRefPtr<CefBrowser> browser) { HWND hWnd = browser->GetHost()->GetWindowHandle(); AttachWindProcToPopup(hWnd); LoadWindowsIcons(hWnd); DragAcceptFiles(hWnd, true); browser->GetHost()->SetFocus(true); } CefRefPtr<CefBrowser> ClientHandler::GetBrowserForNativeWindow(void* window) { CefRefPtr<CefBrowser> browser = NULL; if (window) { //go through all the browsers looking for a browser within this window BrowserWindowMap::const_iterator i = browser_window_map_.find((HWND)window); if (i != browser_window_map_.end()) { browser = i->second; } } return browser; } bool ClientHandler::CanCloseBrowser(CefRefPtr<CefBrowser> browser) { // On windows, the main browser needs to be destroyed last. // So, don't allow main browser to be closed until there's // only 1 browser remaining in the map. return (browser_window_map_.size() == 1) || (browser && browser->GetIdentifier() != m_BrowserId); } bool ClientHandler::OnPreKeyEvent(CefRefPtr<CefBrowser> browser, const CefKeyEvent& event, CefEventHandle os_event, bool* is_keyboard_shortcut) { HWND frameHwnd = (HWND)getMenuParent(browser); // Don't call ::TranslateAccelerator if we don't have a menu for the current window. if (!GetMenu(frameHwnd)) { return false; } if (::TranslateAccelerator(frameHwnd, hAccelTable, os_event)) { return true; } return false; } bool ClientHandler::OnKeyEvent(CefRefPtr<CefBrowser> browser, const CefKeyEvent& event, CefEventHandle os_event) { return false; }
Fix copy issue in Jasmine window. Don't call ::TranslateAccelerator for a window that doesn't have the menu bar.
Fix copy issue in Jasmine window. Don't call ::TranslateAccelerator for a window that doesn't have the menu bar.
C++
mit
MarcelGerber/brackets-shell,keir-rex/brackets-shell,petetnt/brackets-shell,JuanVicke/brackets-shell,adobe/brackets-shell,jomolinare/brackets-shell,jomolinare/brackets-shell,adobe/brackets-shell,keir-rex/brackets-shell,digideskio/brackets-shell,JuanVicke/brackets-shell,weebygames/brackets-shell,alexkid64/brackets-shell,petetnt/brackets-shell,arduino-org/brackets-shell,jomolinare/brackets-shell,MarcelGerber/brackets-shell,arduino-org/brackets-shell,stevemao/brackets-shell,JuanVicke/brackets-shell,keir-rex/brackets-shell,MarcelGerber/brackets-shell,codebrewIO/BrakcetsShell,pomadgw/brackets-shell,adobe/brackets-shell,digideskio/brackets-shell,hackerhelmut/brackets-shell,pomadgw/brackets-shell,ficristo/brackets-shell,albertinad/brackets-shell,keir-rex/brackets-shell,jomolinare/brackets-shell,alexkid64/brackets-shell,hackerhelmut/brackets-shell,petetnt/brackets-shell,arduino-org/brackets-shell,caiowilson/brackets-shell,JuanVicke/brackets-shell,caiowilson/brackets-shell,caiowilson/brackets-shell,arduino-org/brackets-shell,weebygames/brackets-shell,weebygames/brackets-shell,stevemao/brackets-shell,digideskio/brackets-shell,caiowilson/brackets-shell,pomadgw/brackets-shell,stevemao/brackets-shell,arduino-org/brackets-shell,stevemao/brackets-shell,stevemao/brackets-shell,JuanVicke/brackets-shell,weebygames/brackets-shell,hackerhelmut/brackets-shell,petetnt/brackets-shell,MarcelGerber/brackets-shell,ficristo/brackets-shell,ficristo/brackets-shell,albertinad/brackets-shell,digideskio/brackets-shell,codebrewIO/BrakcetsShell,alexkid64/brackets-shell,alexkid64/brackets-shell,albertinad/brackets-shell,pomadgw/brackets-shell,keir-rex/brackets-shell,codebrewIO/BrakcetsShell,albertinad/brackets-shell,digideskio/brackets-shell,jomolinare/brackets-shell,ficristo/brackets-shell,alexkid64/brackets-shell,adobe/brackets-shell,albertinad/brackets-shell,ficristo/brackets-shell,petetnt/brackets-shell,caiowilson/brackets-shell,MarcelGerber/brackets-shell,hackerhelmut/brackets-shell,codebrewIO/BrakcetsShell,pomadgw/brackets-shell,hackerhelmut/brackets-shell,adobe/brackets-shell,codebrewIO/BrakcetsShell,weebygames/brackets-shell,adobe/brackets-shell
c12edf30c711931a3b3656d5623b72b2685b68a5
src/import/chips/ocmb/explorer/procedures/hwp/memory/lib/mc/exp_port.H
src/import/chips/ocmb/explorer/procedures/hwp/memory/lib/mc/exp_port.H
/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/chips/ocmb/explorer/procedures/hwp/memory/lib/mc/exp_port.H $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2019,2022 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* Licensed under the Apache License, Version 2.0 (the "License"); */ /* you may not use this file except in compliance with the License. */ /* You may obtain a copy of the License at */ /* */ /* http://www.apache.org/licenses/LICENSE-2.0 */ /* */ /* Unless required by applicable law or agreed to in writing, software */ /* distributed under the License is distributed on an "AS IS" BASIS, */ /* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */ /* implied. See the License for the specific language governing */ /* permissions and limitations under the License. */ /* */ /* IBM_PROLOG_END_TAG */ /// /// @file exp_port.H /// @brief Code to support ports /// // *HWP HWP Owner: Stephen Glancy <[email protected]> // *HWP HWP Backup: Andre Marin <[email protected]> // *HWP Team: Memory // *HWP Level: 3 // *HWP Consumed by: HB:FSP #ifndef __MSS_EXP_PORT_H_ #define __MSS_EXP_PORT_H_ #include <fapi2.H> #include <explorer_scom_addresses.H> #include <explorer_scom_addresses_fld.H> #include <explorer_scom_addresses_fld_fixes.H> #include <lib/exp_attribute_accessors_manual.H> #include <lib/utils/mss_exp_conversions.H> #include <mss_explorer_attribute_getters.H> #include <lib/shared/exp_consts.H> #include <lib/dimm/exp_rank.H> #include <generic/memory/lib/utils/mc/gen_mss_port.H> #include <generic/memory/lib/utils/shared/mss_generic_consts.H> #include <mss_generic_attribute_getters.H> namespace mss { ////////////////////////////////////////////////////////////// // Traits values for EXPLORER ////////////////////////////////////////////////////////////// /// /// @class Traits and policy class for port code - specialization for Explorer. The target of registers is TARGET_TYPE_OCMB_CHIP /// template<> class portTraits< mss::mc_type::EXPLORER > { public: // MC_TYPE static constexpr fapi2::TargetType MC_TARGET_TYPE = fapi2::TARGET_TYPE_OCMB_CHIP; // PORT_TYPE static constexpr fapi2::TargetType PORT_TYPE = fapi2::TARGET_TYPE_MEM_PORT; // scom register definition static constexpr uint64_t MBARPC0Q_REG = EXPLR_SRQ_MBARPC0Q; static constexpr uint64_t FARB0Q_REG = EXPLR_SRQ_MBA_FARB0Q; static constexpr uint64_t FARB5Q_REG = EXPLR_SRQ_MBA_FARB5Q; static constexpr uint64_t FARB6Q_REG = EXPLR_SRQ_MBA_FARB6Q; static constexpr uint64_t FARB9Q_REG = EXPLR_SRQ_MBA_FARB9Q; static constexpr uint64_t PMU8Q_REG = EXPLR_SRQ_MBA_PMU8Q; static constexpr uint64_t REFRESH_REG = EXPLR_SRQ_MBAREF0Q; static constexpr uint64_t STR0Q_REG = EXPLR_SRQ_MBASTR0Q; static constexpr uint64_t ECC_REG = EXPLR_RDF_RECR; static constexpr uint64_t CTCR_REG = EXPLR_RDF_CTCR; static constexpr uint64_t DSM0Q_REG = EXPLR_SRQ_MBA_DSM0Q; static constexpr uint64_t FWMS_REG = EXPLR_RDF_FWMS0; static constexpr uint64_t RRQ_REG = EXPLR_SRQ_MBA_RRQ0Q; static constexpr uint64_t WRQ_REG = EXPLR_SRQ_MBA_WRQ0Q; static constexpr uint64_t MAGIC_NUMBER_SIM = 765; static constexpr uint64_t MAGIC_NUMBER_NOT_SIM = 196605; // scom register field definition enum { CFG_MIN_MAX_DOMAINS_ENABLE = EXPLR_SRQ_MBARPC0Q_CFG_MIN_MAX_DOMAINS_ENABLE, CFG_CCS_INST_RESET_ENABLE = EXPLR_SRQ_MBA_FARB5Q_CFG_CCS_INST_RESET_ENABLE, CFG_DDR_RESETN = EXPLR_SRQ_MBA_FARB5Q_CFG_DDR_RESETN, CFG_CCS_ADDR_MUX_SEL = EXPLR_SRQ_MBA_FARB5Q_CFG_CCS_ADDR_MUX_SEL, CFG_INIT_COMPLETE = EXPLR_SRQ_MBA_PMU8Q_CFG_INIT_COMPLETE, CFG_ZQ_PER_CAL_ENABLE = EXPLR_SRQ_MBA_FARB9Q_CFG_ZQ_PER_CAL_ENABLE, REFRESH_ENABLE = EXPLR_SRQ_MBAREF0Q_CFG_REFRESH_ENABLE, CFG_FORCE_STR = EXPLR_SRQ_MBASTR0Q_CFG_FORCE_STR, ECC_CHECK_DISABLE = EXPLR_RDF_RECR_MBSECCQ_DISABLE_MEMORY_ECC_CHECK_CORRECT, ECC_CORRECT_DISABLE = EXPLR_RDF_RECR_MBSECCQ_DISABLE_MEMORY_ECC_CORRECT, ECC_USE_ADDR_HASH = EXPLR_RDF_RECR_MBSECCQ_USE_ADDRESS_HASH, PORT_FAIL_DISABLE = EXPLR_SRQ_MBA_FARB0Q_CFG_PORT_FAIL_DISABLE, DFI_INIT_START = EXPLR_SRQ_MBA_FARB0Q_CFG_INIT_START, RCD_RECOVERY_DISABLE = EXPLR_SRQ_MBA_FARB0Q_CFG_DISABLE_RCD_RECOVERY, BW_WINDOW_SIZE = EXPLR_SRQ_MBA_FARB0Q_CFG_BW_WINDOW_SIZE, BW_WINDOW_SIZE_LEN = EXPLR_SRQ_MBA_FARB0Q_CFG_BW_WINDOW_SIZE_LEN, BW_SNAPSHOT = EXPLR_SRQ_MBA_FARB6Q_CFG_BW_SNAPSHOT, BW_SNAPSHOT_LEN = EXPLR_SRQ_MBA_FARB6Q_CFG_BW_SNAPSHOT_LEN, RECR_ENABLE_MPE_NOISE_WINDOW = EXPLR_RDF_RECR_MBSECCQ_ENABLE_MPE_NOISE_WINDOW, RECR_ENABLE_UE_NOISE_WINDOW = EXPLR_RDF_RECR_MBSECCQ_ENABLE_UE_NOISE_WINDOW, RECR_TCE_CORRECTION = EXPLR_RDF_RECR_MBSECCQ_ENABLE_TCE_CORRECTION, RECR_MBSECCQ_DATA_INVERSION = EXPLR_RDF_RECR_MBSECCQ_DATA_INVERSION, RECR_MBSECCQ_DATA_INVERSION_LEN = EXPLR_RDF_RECR_MBSECCQ_DATA_INVERSION_LEN, RECR_RETRY_UNMARKED_ERRORS = EXPLR_RDF_RECR_RETRY_UNMARKED_ERRORS, RECR_CFG_MAINT_USE_TIMERS = EXPLR_RDF_RECR_CFG_MAINT_USE_TIMERS, RECR_MBSECCQ_MAINT_NO_RETRY_UE = EXPLR_RDF_RECR_MBSECCQ_MAINT_NO_RETRY_UE, RECR_MBSECCQ_MAINT_NO_RETRY_MPE = EXPLR_RDF_RECR_MBSECCQ_MAINT_NO_RETRY_MPE, CFG_CTRLUPD_AFTER_ERR = EXPLR_SRQ_MBA_FARB9Q_CFG_CTRLUPD_AFTER_ERR, CFG_MC_PER_CAL_ENABLE = EXPLR_SRQ_MBA_FARB9Q_CFG_MC_PER_CAL_ENABLE, CFG_MC_PER_CAL_INTERVAL_TB = EXPLR_SRQ_MBA_FARB9Q_CFG_MC_PER_CAL_INTERVAL_TB, CFG_MC_PER_CAL_INTERVAL_TB_LEN = EXPLR_SRQ_MBA_FARB9Q_CFG_MC_PER_CAL_INTERVAL_TB_LEN, CFG_MC_PER_CAL_INTERVAL = EXPLR_SRQ_MBA_FARB9Q_CFG_MC_PER_CAL_INTERVAL, CFG_MC_PER_CAL_INTERVAL_LEN = EXPLR_SRQ_MBA_FARB9Q_CFG_MC_PER_CAL_INTERVAL_LEN, CFG_MC_PER_CAL_FIXED_RUN_LENGTH_EN = EXPLR_SRQ_MBA_FARB9Q_CFG_MC_PER_CAL_FIXED_RUN_LENGTH_EN, CFG_MC_PER_CAL_RUN_LENGTH = EXPLR_SRQ_MBA_FARB9Q_CFG_MC_PER_CAL_RUN_LENGTH, CFG_MC_PER_CAL_RUN_LENGTH_LEN = EXPLR_SRQ_MBA_FARB9Q_CFG_MC_PER_CAL_RUN_LENGTH_LEN, CFG_MC_PER_CAL_CTRLUPD_MIN = EXPLR_SRQ_MBA_FARB9Q_CFG_MC_PER_CAL_CTRLUPD_MIN, CFG_MC_PER_CAL_CTRLUPD_MIN_LEN = EXPLR_SRQ_MBA_FARB9Q_CFG_MC_PER_CAL_CTRLUPD_MIN_LEN, CTCR_MPE_TIMER = EXPLR_RDF_CTCR_MPE_TIMER, CTCR_MPE_TIMER_LEN = EXPLR_RDF_CTCR_MPE_TIMER_LEN, CTCR_MPE_TIMEBASE = EXPLR_RDF_CTCR_MPE_TIMEBASE, CTCR_MPE_TIMEBASE_LEN = EXPLR_RDF_CTCR_MPE_TIMEBASE_LEN, CTCR_UE_TIMER = EXPLR_RDF_CTCR_UE_TIMER, CTCR_UE_TIMER_LEN = EXPLR_RDF_CTCR_UE_TIMER_LEN, CTCR_UE_TIMEBASE = EXPLR_RDF_CTCR_UE_TIMEBASE, CTCR_UE_TIMEBASE_LEN = EXPLR_RDF_CTCR_UE_TIMEBASE_LEN, CTCR_UE_LOCKOUT_ENABLE = EXPLR_RDF_CTCR_UE_LOCKOUT_ENABLE, DSM0Q_RDTAG_DLY = EXPLR_SRQ_MBA_DSM0Q_CFG_RDTAG_DLY, DSM0Q_RDTAG_DLY_LEN = EXPLR_SRQ_MBA_DSM0Q_CFG_RDTAG_DLY_LEN, DSM0Q_WRDONE_DLY = EXPLR_SRQ_MBA_DSM0Q_CFG_WRDONE_DLY, DSM0Q_WRDONE_DLY_LEN = EXPLR_SRQ_MBA_DSM0Q_CFG_WRDONE_DLY_LEN, FARB0Q_RCD_PROTECTION_TIME = EXPLR_SRQ_MBA_FARB0Q_CFG_RCD_PROTECTION_TIME, FARB0Q_RCD_PROTECTION_TIME_LEN = EXPLR_SRQ_MBA_FARB0Q_CFG_RCD_PROTECTION_TIME_LEN, FWMS0_MARK = EXPLR_RDF_FWMS0_MARK, FWMS0_MARK_LEN = EXPLR_RDF_FWMS0_MARK_LEN, FWMS0_EXIT_1 = EXPLR_RDF_FWMS0_EXIT_1, RRQ_FIFO_MODE = EXPLR_SRQ_MBA_RRQ0Q_CFG_RRQ_FIFO_MODE, WRQ_FIFO_MODE = EXPLR_SRQ_MBA_WRQ0Q_CFG_WRQ_FIFO_MODE, }; }; /// /// @brief ATTR_MSS_MEM_MVPD_FWMS getter /// @param[in] const ref to the TARGET_TYPE_OCMB_CHIP /// @param[out] uint32_t&[] array reference to store the value /// @return fapi2::ReturnCode - FAPI2_RC_SUCCESS iff get is OK /// @note Mark store records from OCMB VPD. The array dimension is [port][mark]. Explorer /// only has one port so only [0][mark] is used in explorer. /// template<> inline fapi2::ReturnCode mvpd_fwms< mss::mc_type::EXPLORER >( const fapi2::Target<fapi2::TARGET_TYPE_OCMB_CHIP>& i_target, uint32_t (&o_array)[mss::MARK_STORE_COUNT]) { return mss::attr::get_mvpd_fwms(i_target, o_array); } /// @brief Get the attributes for the reorder queue setting /// @param[in] const ref to the mc target /// @param[out] uint8_t& reference to store the value /// @return fapi2::ReturnCode - FAPI2_RC_SUCCESS iff get is OK /// @note Contains the settings for write/read reorder /// queue /// template< > inline fapi2::ReturnCode reorder_queue_setting<mss::mc_type::EXPLORER>( const fapi2::Target<fapi2::TARGET_TYPE_OCMB_CHIP>& i_target, uint8_t& o_value) { return mss::attr::get_reorder_queue_setting(i_target, o_value); } /// /// @brief ATTR_MEM_EFF_DIMM_SPARE getter /// @param[in] const ref to the TARGET_TYPE_DIMM /// @param[out] uint32_t&[] array reference to store the value /// @return fapi2::ReturnCode - FAPI2_RC_SUCCESS iff get is OK /// @note Spare DRAM availability. Used in various locations and is computed in mss_eff_cnfg. /// Array indexes are [DIMM][RANK] /// template<> inline fapi2::ReturnCode dimm_spare< mss::mc_type::EXPLORER >( const fapi2::Target<fapi2::TARGET_TYPE_DIMM>& i_target, uint8_t (&o_array)[mss::MAX_RANK_PER_DIMM_ATTR]) { return mss::attr::get_dimm_spare(i_target, o_array); } /// /// @brief Change the state of the force_str bit - mc_type::EXPLORER specialization /// @tparam MC the memory controller type /// @param[in] i_target the target /// @param[in] i_state the state /// @return FAPI2_RC_SUCCESS if and only if ok /// template< > inline fapi2::ReturnCode change_force_str<DEFAULT_MC_TYPE>( const fapi2::Target<fapi2::TARGET_TYPE_OCMB_CHIP>& i_target, const states i_state ) { using TT = portTraits<mss::mc_type::EXPLORER>; fapi2::buffer<uint64_t> l_data; FAPI_DBG("Change force_str to %s %s", (i_state == HIGH ? "high" : "low"), mss::c_str(i_target)); FAPI_TRY( mss::getScom(i_target, TT::STR0Q_REG, l_data) ); l_data.writeBit<TT::CFG_FORCE_STR>(i_state); FAPI_TRY( mss::putScom(i_target, TT::STR0Q_REG, l_data) ); fapi_try_exit: return fapi2::current_err; } }// mss #endif
/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/chips/ocmb/explorer/procedures/hwp/memory/lib/mc/exp_port.H $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2019,2022 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* Licensed under the Apache License, Version 2.0 (the "License"); */ /* you may not use this file except in compliance with the License. */ /* You may obtain a copy of the License at */ /* */ /* http://www.apache.org/licenses/LICENSE-2.0 */ /* */ /* Unless required by applicable law or agreed to in writing, software */ /* distributed under the License is distributed on an "AS IS" BASIS, */ /* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */ /* implied. See the License for the specific language governing */ /* permissions and limitations under the License. */ /* */ /* IBM_PROLOG_END_TAG */ /// /// @file exp_port.H /// @brief Code to support ports /// // *HWP HWP Owner: Stephen Glancy <[email protected]> // *HWP HWP Backup: Louis Stermole <[email protected]> // *HWP Team: Memory // *HWP Level: 3 // *HWP Consumed by: HB:FSP #ifndef __MSS_EXP_PORT_H_ #define __MSS_EXP_PORT_H_ #include <fapi2.H> #include <explorer_scom_addresses.H> #include <explorer_scom_addresses_fld.H> #include <explorer_scom_addresses_fld_fixes.H> #include <lib/exp_attribute_accessors_manual.H> #include <lib/utils/mss_exp_conversions.H> #include <mss_explorer_attribute_getters.H> #include <lib/shared/exp_consts.H> #include <lib/dimm/exp_rank.H> #include <generic/memory/lib/utils/mc/gen_mss_port.H> #include <generic/memory/lib/utils/shared/mss_generic_consts.H> #include <mss_generic_attribute_getters.H> namespace mss { ////////////////////////////////////////////////////////////// // Traits values for EXPLORER ////////////////////////////////////////////////////////////// /// /// @class Traits and policy class for port code - specialization for Explorer. The target of registers is TARGET_TYPE_OCMB_CHIP /// template<> class portTraits< mss::mc_type::EXPLORER > { public: // MC_TYPE static constexpr fapi2::TargetType MC_TARGET_TYPE = fapi2::TARGET_TYPE_OCMB_CHIP; // PORT_TYPE static constexpr fapi2::TargetType PORT_TYPE = fapi2::TARGET_TYPE_MEM_PORT; // scom register definition static constexpr uint64_t MBARPC0Q_REG = EXPLR_SRQ_MBARPC0Q; static constexpr uint64_t FARB0Q_REG = EXPLR_SRQ_MBA_FARB0Q; static constexpr uint64_t FARB5Q_REG = EXPLR_SRQ_MBA_FARB5Q; static constexpr uint64_t FARB6Q_REG = EXPLR_SRQ_MBA_FARB6Q; static constexpr uint64_t FARB9Q_REG = EXPLR_SRQ_MBA_FARB9Q; static constexpr uint64_t PMU8Q_REG = EXPLR_SRQ_MBA_PMU8Q; static constexpr uint64_t REFRESH_REG = EXPLR_SRQ_MBAREF0Q; static constexpr uint64_t STR0Q_REG = EXPLR_SRQ_MBASTR0Q; static constexpr uint64_t ECC_REG = EXPLR_RDF_RECR; static constexpr uint64_t CTCR_REG = EXPLR_RDF_CTCR; static constexpr uint64_t DSM0Q_REG = EXPLR_SRQ_MBA_DSM0Q; static constexpr uint64_t FWMS_REG = EXPLR_RDF_FWMS0; static constexpr uint64_t RRQ_REG = EXPLR_SRQ_MBA_RRQ0Q; static constexpr uint64_t WRQ_REG = EXPLR_SRQ_MBA_WRQ0Q; static constexpr uint64_t MAGIC_NUMBER_SIM = 765; static constexpr uint64_t MAGIC_NUMBER_NOT_SIM = 196605; // scom register field definition enum { CFG_MIN_MAX_DOMAINS_ENABLE = EXPLR_SRQ_MBARPC0Q_CFG_MIN_MAX_DOMAINS_ENABLE, CFG_CCS_INST_RESET_ENABLE = EXPLR_SRQ_MBA_FARB5Q_CFG_CCS_INST_RESET_ENABLE, CFG_DDR_RESETN = EXPLR_SRQ_MBA_FARB5Q_CFG_DDR_RESETN, CFG_CCS_ADDR_MUX_SEL = EXPLR_SRQ_MBA_FARB5Q_CFG_CCS_ADDR_MUX_SEL, CFG_INIT_COMPLETE = EXPLR_SRQ_MBA_PMU8Q_CFG_INIT_COMPLETE, CFG_ZQ_PER_CAL_ENABLE = EXPLR_SRQ_MBA_FARB9Q_CFG_ZQ_PER_CAL_ENABLE, REFRESH_ENABLE = EXPLR_SRQ_MBAREF0Q_CFG_REFRESH_ENABLE, CFG_FORCE_STR = EXPLR_SRQ_MBASTR0Q_CFG_FORCE_STR, ECC_CHECK_DISABLE = EXPLR_RDF_RECR_MBSECCQ_DISABLE_MEMORY_ECC_CHECK_CORRECT, ECC_CORRECT_DISABLE = EXPLR_RDF_RECR_MBSECCQ_DISABLE_MEMORY_ECC_CORRECT, ECC_USE_ADDR_HASH = EXPLR_RDF_RECR_MBSECCQ_USE_ADDRESS_HASH, PORT_FAIL_DISABLE = EXPLR_SRQ_MBA_FARB0Q_CFG_PORT_FAIL_DISABLE, DFI_INIT_START = EXPLR_SRQ_MBA_FARB0Q_CFG_INIT_START, RCD_RECOVERY_DISABLE = EXPLR_SRQ_MBA_FARB0Q_CFG_DISABLE_RCD_RECOVERY, BW_WINDOW_SIZE = EXPLR_SRQ_MBA_FARB0Q_CFG_BW_WINDOW_SIZE, BW_WINDOW_SIZE_LEN = EXPLR_SRQ_MBA_FARB0Q_CFG_BW_WINDOW_SIZE_LEN, BW_SNAPSHOT = EXPLR_SRQ_MBA_FARB6Q_CFG_BW_SNAPSHOT, BW_SNAPSHOT_LEN = EXPLR_SRQ_MBA_FARB6Q_CFG_BW_SNAPSHOT_LEN, RECR_ENABLE_MPE_NOISE_WINDOW = EXPLR_RDF_RECR_MBSECCQ_ENABLE_MPE_NOISE_WINDOW, RECR_ENABLE_UE_NOISE_WINDOW = EXPLR_RDF_RECR_MBSECCQ_ENABLE_UE_NOISE_WINDOW, RECR_TCE_CORRECTION = EXPLR_RDF_RECR_MBSECCQ_ENABLE_TCE_CORRECTION, RECR_MBSECCQ_DATA_INVERSION = EXPLR_RDF_RECR_MBSECCQ_DATA_INVERSION, RECR_MBSECCQ_DATA_INVERSION_LEN = EXPLR_RDF_RECR_MBSECCQ_DATA_INVERSION_LEN, RECR_RETRY_UNMARKED_ERRORS = EXPLR_RDF_RECR_RETRY_UNMARKED_ERRORS, RECR_CFG_MAINT_USE_TIMERS = EXPLR_RDF_RECR_CFG_MAINT_USE_TIMERS, RECR_MBSECCQ_MAINT_NO_RETRY_UE = EXPLR_RDF_RECR_MBSECCQ_MAINT_NO_RETRY_UE, RECR_MBSECCQ_MAINT_NO_RETRY_MPE = EXPLR_RDF_RECR_MBSECCQ_MAINT_NO_RETRY_MPE, CFG_CTRLUPD_AFTER_ERR = EXPLR_SRQ_MBA_FARB9Q_CFG_CTRLUPD_AFTER_ERR, CFG_MC_PER_CAL_ENABLE = EXPLR_SRQ_MBA_FARB9Q_CFG_MC_PER_CAL_ENABLE, CFG_MC_PER_CAL_INTERVAL_TB = EXPLR_SRQ_MBA_FARB9Q_CFG_MC_PER_CAL_INTERVAL_TB, CFG_MC_PER_CAL_INTERVAL_TB_LEN = EXPLR_SRQ_MBA_FARB9Q_CFG_MC_PER_CAL_INTERVAL_TB_LEN, CFG_MC_PER_CAL_INTERVAL = EXPLR_SRQ_MBA_FARB9Q_CFG_MC_PER_CAL_INTERVAL, CFG_MC_PER_CAL_INTERVAL_LEN = EXPLR_SRQ_MBA_FARB9Q_CFG_MC_PER_CAL_INTERVAL_LEN, CFG_MC_PER_CAL_FIXED_RUN_LENGTH_EN = EXPLR_SRQ_MBA_FARB9Q_CFG_MC_PER_CAL_FIXED_RUN_LENGTH_EN, CFG_MC_PER_CAL_RUN_LENGTH = EXPLR_SRQ_MBA_FARB9Q_CFG_MC_PER_CAL_RUN_LENGTH, CFG_MC_PER_CAL_RUN_LENGTH_LEN = EXPLR_SRQ_MBA_FARB9Q_CFG_MC_PER_CAL_RUN_LENGTH_LEN, CFG_MC_PER_CAL_CTRLUPD_MIN = EXPLR_SRQ_MBA_FARB9Q_CFG_MC_PER_CAL_CTRLUPD_MIN, CFG_MC_PER_CAL_CTRLUPD_MIN_LEN = EXPLR_SRQ_MBA_FARB9Q_CFG_MC_PER_CAL_CTRLUPD_MIN_LEN, CTCR_MPE_TIMER = EXPLR_RDF_CTCR_MPE_TIMER, CTCR_MPE_TIMER_LEN = EXPLR_RDF_CTCR_MPE_TIMER_LEN, CTCR_MPE_TIMEBASE = EXPLR_RDF_CTCR_MPE_TIMEBASE, CTCR_MPE_TIMEBASE_LEN = EXPLR_RDF_CTCR_MPE_TIMEBASE_LEN, CTCR_UE_TIMER = EXPLR_RDF_CTCR_UE_TIMER, CTCR_UE_TIMER_LEN = EXPLR_RDF_CTCR_UE_TIMER_LEN, CTCR_UE_TIMEBASE = EXPLR_RDF_CTCR_UE_TIMEBASE, CTCR_UE_TIMEBASE_LEN = EXPLR_RDF_CTCR_UE_TIMEBASE_LEN, CTCR_UE_LOCKOUT_ENABLE = EXPLR_RDF_CTCR_UE_LOCKOUT_ENABLE, DSM0Q_RDTAG_DLY = EXPLR_SRQ_MBA_DSM0Q_CFG_RDTAG_DLY, DSM0Q_RDTAG_DLY_LEN = EXPLR_SRQ_MBA_DSM0Q_CFG_RDTAG_DLY_LEN, DSM0Q_WRDONE_DLY = EXPLR_SRQ_MBA_DSM0Q_CFG_WRDONE_DLY, DSM0Q_WRDONE_DLY_LEN = EXPLR_SRQ_MBA_DSM0Q_CFG_WRDONE_DLY_LEN, FARB0Q_RCD_PROTECTION_TIME = EXPLR_SRQ_MBA_FARB0Q_CFG_RCD_PROTECTION_TIME, FARB0Q_RCD_PROTECTION_TIME_LEN = EXPLR_SRQ_MBA_FARB0Q_CFG_RCD_PROTECTION_TIME_LEN, FWMS0_MARK = EXPLR_RDF_FWMS0_MARK, FWMS0_MARK_LEN = EXPLR_RDF_FWMS0_MARK_LEN, FWMS0_EXIT_1 = EXPLR_RDF_FWMS0_EXIT_1, RRQ_FIFO_MODE = EXPLR_SRQ_MBA_RRQ0Q_CFG_RRQ_FIFO_MODE, WRQ_FIFO_MODE = EXPLR_SRQ_MBA_WRQ0Q_CFG_WRQ_FIFO_MODE, }; }; /// /// @brief ATTR_MSS_MEM_MVPD_FWMS getter /// @param[in] const ref to the TARGET_TYPE_OCMB_CHIP /// @param[out] uint32_t&[] array reference to store the value /// @return fapi2::ReturnCode - FAPI2_RC_SUCCESS iff get is OK /// @note Mark store records from OCMB VPD. The array dimension is [port][mark]. Explorer /// only has one port so only [0][mark] is used in explorer. /// template<> inline fapi2::ReturnCode mvpd_fwms< mss::mc_type::EXPLORER >( const fapi2::Target<fapi2::TARGET_TYPE_OCMB_CHIP>& i_target, uint32_t (&o_array)[mss::MARK_STORE_COUNT]) { return mss::attr::get_mvpd_fwms(i_target, o_array); } /// @brief Get the attributes for the reorder queue setting /// @param[in] const ref to the mc target /// @param[out] uint8_t& reference to store the value /// @return fapi2::ReturnCode - FAPI2_RC_SUCCESS iff get is OK /// @note Contains the settings for write/read reorder /// queue /// template< > inline fapi2::ReturnCode reorder_queue_setting<mss::mc_type::EXPLORER>( const fapi2::Target<fapi2::TARGET_TYPE_OCMB_CHIP>& i_target, uint8_t& o_value) { return mss::attr::get_reorder_queue_setting(i_target, o_value); } /// /// @brief ATTR_MEM_EFF_DIMM_SPARE getter /// @param[in] const ref to the TARGET_TYPE_DIMM /// @param[out] uint32_t&[] array reference to store the value /// @return fapi2::ReturnCode - FAPI2_RC_SUCCESS iff get is OK /// @note Spare DRAM availability. Used in various locations and is computed in mss_eff_cnfg. /// Array indexes are [DIMM][RANK] /// template<> inline fapi2::ReturnCode dimm_spare< mss::mc_type::EXPLORER >( const fapi2::Target<fapi2::TARGET_TYPE_DIMM>& i_target, uint8_t (&o_array)[mss::MAX_RANK_PER_DIMM_ATTR]) { return mss::attr::get_dimm_spare(i_target, o_array); } /// /// @brief Change the state of the force_str bit - mc_type::EXPLORER specialization /// @tparam MC the memory controller type /// @param[in] i_target the target /// @param[in] i_state the state /// @return FAPI2_RC_SUCCESS if and only if ok /// template< > inline fapi2::ReturnCode change_force_str<DEFAULT_MC_TYPE>( const fapi2::Target<fapi2::TARGET_TYPE_OCMB_CHIP>& i_target, const states i_state ) { using TT = portTraits<mss::mc_type::EXPLORER>; fapi2::buffer<uint64_t> l_data; FAPI_DBG("Change force_str to %s %s", (i_state == HIGH ? "high" : "low"), mss::c_str(i_target)); FAPI_TRY( mss::getScom(i_target, TT::STR0Q_REG, l_data) ); l_data.writeBit<TT::CFG_FORCE_STR>(i_state); FAPI_TRY( mss::putScom(i_target, TT::STR0Q_REG, l_data) ); fapi_try_exit: return fapi2::current_err; } }// mss #endif
Replace Andre Marin contact info in all MSS source
Replace Andre Marin contact info in all MSS source Change-Id: Icd69aa92e131dd965c162a8e2adb41a20bf2edec Original-Change-Id: I37d6eb1ab3248536fc2c0e4aced18972812cd2b9 Reviewed-on: http://rchgit01.rchland.ibm.com/gerrit1/107951 Tested-by: Jenkins Server <[email protected]> Tested-by: HWSV CI <[email protected]> Tested-by: PPE CI <[email protected]> Tested-by: FSP CI Jenkins <[email protected]> Reviewed-by: STEPHEN GLANCY <[email protected]> Reviewed-by: Mark Pizzutillo <[email protected]> Tested-by: Hostboot CI <[email protected]> Reviewed-by: Edgar R Cordero <[email protected]> Reviewed-on: http://rchgit01.rchland.ibm.com/gerrit1/139123 Tested-by: Jenkins OP Build CI <[email protected]> Tested-by: Jenkins Combined Simics CI <[email protected]> Reviewed-by: Daniel M Crowell <[email protected]>
C++
apache-2.0
open-power/hostboot,open-power/hostboot,open-power/hostboot,open-power/hostboot,open-power/hostboot
50c53b428e336e1865fbb1a46cf1a6218b51c745
src/AppWindow.cpp
src/AppWindow.cpp
//======================================================================== // AppWindow.cpp // // Copyright 2005-2009 Sergey Kazenyuk, All Rights Reserved. // Copyright 2018 Janus // Copyright 2019 Humdinger // Distributed under the terms of the MIT License. //======================================================================== // $Id: AppWindow.cpp 12 2009-02-02 08:51:09Z sergey.kazenyuk $ // $Rev: 12 $ // $Author: sergey.kazenyuk $ // $Date: 2009-02-02 10:51:09 +0200 (Mon, 02 Feb 2009) $ //======================================================================== #include <Catalog.h> #include <Clipboard.h> #include <FindDirectory.h> #include <IconUtils.h> #include <LayoutBuilder.h> #include <Path.h> #include <Resources.h> #include <Roster.h> #include <SeparatorView.h> #include <string> #include "App.h" #include "AppWindow.h" #define PREFS_FILENAME "Randomizer_settings" #undef B_TRANSLATION_CONTEXT #define B_TRANSLATION_CONTEXT "AppWindow" //==================================================================== void Generator(char* password, const int& num, const char* symbols); //==================================================================== AppWindow::AppWindow(BRect frame) : BWindow(frame, B_TRANSLATE_SYSTEM_NAME(App_Name), B_TITLED_WINDOW, B_NOT_RESIZABLE | B_NOT_ZOOMABLE | B_AUTO_UPDATE_SIZE_LIMITS) { PassOut = new BTextControl("PassOut", "", NULL, NULL); PassOut->SetEnabled(false); PassLength = new BSpinner("PassLength", B_TRANSLATE("Password length:"), new BMessage(SEQ_LEN_MSG)); PassLength->SetMinValue(1); PassLength->SetValue(DEFAULT_LENGTH); UpperCaseCB = new BCheckBox( "UpperCaseCB", B_TRANSLATE("Upper case"), new BMessage(UCASE_CB_MSG)); UpperCaseCB->SetValue(B_CONTROL_ON); LowerCaseCB = new BCheckBox( "LowerCaseCB", B_TRANSLATE("Lower case"), new BMessage(LCASE_CB_MSG)); LowerCaseCB->SetValue(B_CONTROL_ON); NumCB = new BCheckBox( "NumCB", B_TRANSLATE("Numbers"), new BMessage(NUMBERS_CB_MSG)); NumCB->SetValue(B_CONTROL_ON); SpecSymbCB = new BCheckBox( "SpecSymbCB", B_TRANSLATE("Symbols"), new BMessage(SPEC_SYMB_CB_MSG)); // Custom symbols checkbox CustSymbCB = new BCheckBox( "CustSymbCB", B_TRANSLATE("Custom:"), new BMessage(CUST_SYMB_CB_MSG)); // Custom symbols input field CustSymb = new BTextControl("CustSymb", "", NULL, new BMessage(CUST_SYMB_MSG)); CustSymb->SetDivider(0); CustSymb->SetEnabled(false); GenerateBtn = new BButton( "GenBtn", B_TRANSLATE("Generate"), new BMessage(GEN_BTN_MSG)); GenerateBtn->MakeDefault(true); font_height fh; PassOut->GetFontHeight(&fh); const float iconSize = ceilf(fh.ascent) - 2.0; CopyToClipboardBtn = new BButton("CopyToClipboardBtn", "", new BMessage(COPY_BTN_MSG)); CopyToClipboardBtn->SetIcon(ResourceVectorToBitmap("CLIPBOARD", iconSize)); CopyToClipboardBtn->SetToolTip(B_TRANSLATE("Copy to clipboard")); BSeparatorView* separatorPasswordView = new BSeparatorView( "generatedPassword", B_TRANSLATE("Generated password"), B_HORIZONTAL, B_FANCY_BORDER, BAlignment(B_ALIGN_CENTER, B_ALIGN_VERTICAL_CENTER)); BLayoutBuilder::Group<>(this, B_VERTICAL, 0) .Add(BuildMenuBar()) .AddGrid(B_USE_DEFAULT_SPACING, 0, 1) .SetInsets(B_USE_WINDOW_INSETS, B_USE_WINDOW_INSETS, B_USE_WINDOW_INSETS, B_USE_WINDOW_INSETS) .Add(UpperCaseCB, 0, 0) .Add(LowerCaseCB, 0, 1) .Add(NumCB, 1, 0) .Add(SpecSymbCB, 1, 1) .Add(CustSymbCB, 0, 2) .Add(CustSymb, 1, 2) .End() .AddGroup(B_HORIZONTAL, 0) .SetInsets( B_USE_WINDOW_INSETS, 0, B_USE_WINDOW_INSETS, B_USE_WINDOW_INSETS) .Add(PassLength) .End() .AddStrut(B_USE_DEFAULT_SPACING) .Add(separatorPasswordView) .AddGroup(B_VERTICAL, B_USE_DEFAULT_SPACING) .SetInsets( B_USE_WINDOW_INSETS, B_USE_WINDOW_INSETS, B_USE_WINDOW_INSETS, B_USE_WINDOW_INSETS) .AddGroup(B_HORIZONTAL, 0) .Add(PassOut) .Add(CopyToClipboardBtn) .End() .AddGroup(B_HORIZONTAL) .AddGlue() .Add(GenerateBtn) .AddGlue() .End() .End(); SpecSymbCB->SetToolTip("!@#$%^&*"); CustSymbCB->SetToolTip(B_TRANSLATE("Custom set of characters")); UnarchivePreferences(); GeneratePassword(); } //-------------------------------------------------------------------- bool AppWindow::QuitRequested() { ArchivePreferences(); be_app->PostMessage(B_QUIT_REQUESTED); return true; } //-------------------------------------------------------------------- void AppWindow::MessageReceived(BMessage* message) { #ifdef DEBUG printf("AppWindow::MessageReceived: \n"); message->PrintToStream(); #endif switch (message->what) { case GEN_BTN_MSG: { GeneratePassword(); } break; case COPY_BTN_MSG: { PassOut->TextView()->SelectAll(); PassOut->TextView()->Copy(be_clipboard); } break; case CUST_SYMB_CB_MSG: // Custom symbols checkbox set/unset if (CustSymbCB->Value() == B_CONTROL_ON) CustSymb->SetEnabled(true); else CustSymb->SetEnabled(false); break; case B_ABOUT_REQUESTED: be_app->PostMessage(B_ABOUT_REQUESTED); break; default: BWindow::MessageReceived(message); } } //-------------------------------------------------------------------- BMenuBar* AppWindow::BuildMenuBar() { BMenuBar* menuBar = new BMenuBar("menubar"); BMenu* menu = new BMenu(B_TRANSLATE("App")); menuBar->AddItem(menu); menu->AddItem(new BMenuItem( B_TRANSLATE("About Randomizer"), new BMessage(B_ABOUT_REQUESTED), 0, 0)); menu->AddSeparatorItem(); menu->AddItem(new BMenuItem( B_TRANSLATE("Copy to clipboard"), new BMessage(COPY_BTN_MSG), 'C', 0)); menu->AddSeparatorItem(); menu->AddItem(new BMenuItem( B_TRANSLATE("Quit"), new BMessage(B_QUIT_REQUESTED), 'Q', 0)); return menuBar; } void AppWindow::GeneratePassword() { const char en_upsymbols[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; const char en_lowsymbols[] = "abcdefghijklmnopqrstuvwxyz"; const char num_symbols[] = "0123456789"; const char spec_symbols[] = "!@#$%^&*"; //<------- PassOut->SetText(""); std::string symbols; if (UpperCaseCB->Value() == B_CONTROL_ON) symbols += en_upsymbols; if (LowerCaseCB->Value() == B_CONTROL_ON) symbols += en_lowsymbols; if (NumCB->Value() == B_CONTROL_ON) symbols += num_symbols; if (SpecSymbCB->Value() == B_CONTROL_ON) symbols += spec_symbols; if (CustSymbCB->Value() == B_CONTROL_ON) symbols += CustSymb->Text(); int pass_length = PassLength->Value(); char* password = new char[pass_length]; Generator(password, pass_length, symbols.c_str()); PassOut->SetText(password); delete[] password; } BBitmap* AppWindow::ResourceVectorToBitmap(const char* resName, float iconSize) { BResources res; size_t size; app_info appInfo; be_app->GetAppInfo(&appInfo); BFile appFile(&appInfo.ref, B_READ_ONLY); res.SetTo(&appFile); BBitmap* aBmp = NULL; const uint8* iconData = (const uint8*) res.LoadResource('VICN', resName, &size); if (size > 0) { aBmp = new BBitmap(BRect(0, 0, iconSize, iconSize), 0, B_RGBA32); status_t result = BIconUtils::GetVectorIcon(iconData, size, aBmp); if (result != B_OK) { delete aBmp; aBmp = NULL; } } return aBmp; } BFile AppWindow::PrefsFile(int32 mode) { BPath path; find_directory(B_USER_SETTINGS_DIRECTORY, &path); path.SetTo(path.Path(), PREFS_FILENAME); return BFile(path.Path(), mode); } void AppWindow::SavePreferences(BMessage& msg) { BFile file = PrefsFile(B_WRITE_ONLY | B_CREATE_FILE); file.SetSize(0); msg.Flatten(&file); } void AppWindow::LoadPreferences(BMessage& msg) { BFile file = PrefsFile(B_READ_ONLY); msg.Unflatten(&file); } void AppWindow::ArchivePreferences() { BMessage message; message.AddInt32("PassLength", PassLength->Value()); message.AddBool("UpperCaseCB", UpperCaseCB->Value() == B_CONTROL_ON); message.AddBool("LowerCaseCB", LowerCaseCB->Value() == B_CONTROL_ON); message.AddBool("NumCB", NumCB->Value() == B_CONTROL_ON); message.AddBool("SpecSymbCB", SpecSymbCB->Value() == B_CONTROL_ON); message.AddBool("CustSymbCB", CustSymbCB->Value() == B_CONTROL_ON); message.AddString("CustSymb", CustSymb->Text()); message.AddPoint("WinOrigin", Frame().LeftTop()); SavePreferences(message); } void AppWindow::UnarchivePreferences() { BMessage message; LoadPreferences(message); int32 length; if (message.FindInt32("PassLength", &length) == B_OK) PassLength->SetValue(length); bool controlOn; if (message.FindBool("UpperCaseCB", &controlOn) == B_OK) UpperCaseCB->SetValue(controlOn ? B_CONTROL_ON : B_CONTROL_OFF); if (message.FindBool("LowerCaseCB", &controlOn) == B_OK) LowerCaseCB->SetValue(controlOn ? B_CONTROL_ON : B_CONTROL_OFF); if (message.FindBool("NumCB", &controlOn) == B_OK) NumCB->SetValue(controlOn ? B_CONTROL_ON : B_CONTROL_OFF); if (message.FindBool("SpecSymbCB", &controlOn) == B_OK) SpecSymbCB->SetValue(controlOn ? B_CONTROL_ON : B_CONTROL_OFF); if (message.FindBool("CustSymbCB", &controlOn) == B_OK) { CustSymbCB->SetValue(controlOn ? B_CONTROL_ON : B_CONTROL_OFF); CustSymb->SetEnabled(controlOn); } BString symbols; if (message.FindString("CustSymb", &symbols) == B_OK) CustSymb->SetText(symbols); BPoint origin; if (message.FindPoint("WinOrigin", &origin) == B_OK) { MoveTo(origin); MoveOnScreen(B_MOVE_IF_PARTIALLY_OFFSCREEN); } }
//======================================================================== // AppWindow.cpp // // Copyright 2005-2009 Sergey Kazenyuk, All Rights Reserved. // Copyright 2018 Janus // Copyright 2019 Humdinger // Distributed under the terms of the MIT License. //======================================================================== // $Id: AppWindow.cpp 12 2009-02-02 08:51:09Z sergey.kazenyuk $ // $Rev: 12 $ // $Author: sergey.kazenyuk $ // $Date: 2009-02-02 10:51:09 +0200 (Mon, 02 Feb 2009) $ //======================================================================== #include <Catalog.h> #include <Clipboard.h> #include <FindDirectory.h> #include <IconUtils.h> #include <LayoutBuilder.h> #include <Path.h> #include <Resources.h> #include <Roster.h> #include <SeparatorView.h> #include <string> #include "App.h" #include "AppWindow.h" #define PREFS_FILENAME "Randomizer_settings" #undef B_TRANSLATION_CONTEXT #define B_TRANSLATION_CONTEXT "AppWindow" //==================================================================== void Generator(char* password, const int& num, const char* symbols); //==================================================================== AppWindow::AppWindow(BRect frame) : BWindow(frame, B_TRANSLATE_SYSTEM_NAME(App_Name), B_TITLED_WINDOW, B_NOT_RESIZABLE | B_NOT_ZOOMABLE | B_AUTO_UPDATE_SIZE_LIMITS) { PassOut = new BTextControl("PassOut", "", NULL, NULL); PassOut->SetEnabled(false); PassLength = new BSpinner("PassLength", B_TRANSLATE("Password length:"), new BMessage(SEQ_LEN_MSG)); PassLength->SetMinValue(1); PassLength->SetValue(DEFAULT_LENGTH); UpperCaseCB = new BCheckBox( "UpperCaseCB", B_TRANSLATE("Upper case"), new BMessage(UCASE_CB_MSG)); UpperCaseCB->SetValue(B_CONTROL_ON); LowerCaseCB = new BCheckBox( "LowerCaseCB", B_TRANSLATE("Lower case"), new BMessage(LCASE_CB_MSG)); LowerCaseCB->SetValue(B_CONTROL_ON); NumCB = new BCheckBox( "NumCB", B_TRANSLATE("Numbers"), new BMessage(NUMBERS_CB_MSG)); NumCB->SetValue(B_CONTROL_ON); SpecSymbCB = new BCheckBox( "SpecSymbCB", B_TRANSLATE("Symbols"), new BMessage(SPEC_SYMB_CB_MSG)); // Custom symbols checkbox CustSymbCB = new BCheckBox( "CustSymbCB", B_TRANSLATE("Custom:"), new BMessage(CUST_SYMB_CB_MSG)); // Custom symbols input field CustSymb = new BTextControl("CustSymb", "", NULL, new BMessage(CUST_SYMB_MSG)); CustSymb->SetDivider(0); CustSymb->SetEnabled(false); GenerateBtn = new BButton( "GenBtn", B_TRANSLATE("Generate"), new BMessage(GEN_BTN_MSG)); GenerateBtn->MakeDefault(true); font_height fh; PassOut->GetFontHeight(&fh); const float iconSize = ceilf(fh.ascent) - 2.0; CopyToClipboardBtn = new BButton("CopyToClipboardBtn", "", new BMessage(COPY_BTN_MSG)); CopyToClipboardBtn->SetIcon(ResourceVectorToBitmap("CLIPBOARD", iconSize)); CopyToClipboardBtn->SetToolTip(B_TRANSLATE("Copy to clipboard")); BSeparatorView* separatorPasswordView = new BSeparatorView( "generatedPassword", B_TRANSLATE("Generated password"), B_HORIZONTAL, B_FANCY_BORDER, BAlignment(B_ALIGN_CENTER, B_ALIGN_VERTICAL_CENTER)); BLayoutBuilder::Group<>(this, B_VERTICAL, 0) .Add(BuildMenuBar()) .AddGrid(B_USE_DEFAULT_SPACING, 0, 1) .SetInsets(B_USE_WINDOW_INSETS, B_USE_WINDOW_INSETS, B_USE_WINDOW_INSETS, B_USE_WINDOW_INSETS) .Add(UpperCaseCB, 0, 0) .Add(LowerCaseCB, 0, 1) .Add(NumCB, 1, 0) .Add(SpecSymbCB, 1, 1) .Add(CustSymbCB, 0, 2) .Add(CustSymb, 1, 2) .End() .AddGroup(B_HORIZONTAL, 0) .SetInsets( B_USE_WINDOW_INSETS, 0, B_USE_WINDOW_INSETS, B_USE_WINDOW_INSETS) .Add(PassLength) .End() .AddStrut(B_USE_DEFAULT_SPACING) .Add(separatorPasswordView) .AddGroup(B_VERTICAL, B_USE_DEFAULT_SPACING) .SetInsets( B_USE_WINDOW_INSETS, B_USE_WINDOW_INSETS, B_USE_WINDOW_INSETS, B_USE_WINDOW_INSETS) .AddGroup(B_HORIZONTAL, 0) .Add(PassOut) .Add(CopyToClipboardBtn) .End() .AddGroup(B_HORIZONTAL) .AddGlue() .Add(GenerateBtn) .AddGlue() .End() .End(); SpecSymbCB->SetToolTip("!@#$%^&*"); CustSymbCB->SetToolTip(B_TRANSLATE("Custom set of characters")); UnarchivePreferences(); GeneratePassword(); } //-------------------------------------------------------------------- bool AppWindow::QuitRequested() { ArchivePreferences(); be_app->PostMessage(B_QUIT_REQUESTED); return true; } //-------------------------------------------------------------------- void AppWindow::MessageReceived(BMessage* message) { #ifdef DEBUG printf("AppWindow::MessageReceived: \n"); message->PrintToStream(); #endif switch (message->what) { case GEN_BTN_MSG: { GeneratePassword(); } break; case COPY_BTN_MSG: { PassOut->TextView()->SelectAll(); PassOut->TextView()->Copy(be_clipboard); } break; case CUST_SYMB_CB_MSG: // Custom symbols checkbox set/unset if (CustSymbCB->Value() == B_CONTROL_ON) CustSymb->SetEnabled(true); else CustSymb->SetEnabled(false); break; case B_ABOUT_REQUESTED: be_app->PostMessage(B_ABOUT_REQUESTED); break; default: BWindow::MessageReceived(message); } } //-------------------------------------------------------------------- BMenuBar* AppWindow::BuildMenuBar() { BMenuBar* menuBar = new BMenuBar("menubar"); BMenu* menu = new BMenu(B_TRANSLATE("App")); menuBar->AddItem(menu); menu->AddItem(new BMenuItem( B_TRANSLATE("About Randomizer"), new BMessage(B_ABOUT_REQUESTED), 0, 0)); menu->AddSeparatorItem(); menu->AddItem(new BMenuItem( B_TRANSLATE("Copy to clipboard"), new BMessage(COPY_BTN_MSG), 'C', 0)); menu->AddSeparatorItem(); menu->AddItem(new BMenuItem( B_TRANSLATE("Quit"), new BMessage(B_QUIT_REQUESTED), 'Q', 0)); return menuBar; } void AppWindow::GeneratePassword() { const char en_upsymbols[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; const char en_lowsymbols[] = "abcdefghijklmnopqrstuvwxyz"; const char num_symbols[] = "0123456789"; const char spec_symbols[] = "!@#$%^&*"; //<------- PassOut->SetText(""); std::string symbols; if (UpperCaseCB->Value() == B_CONTROL_ON) symbols += en_upsymbols; if (LowerCaseCB->Value() == B_CONTROL_ON) symbols += en_lowsymbols; if (NumCB->Value() == B_CONTROL_ON) symbols += num_symbols; if (SpecSymbCB->Value() == B_CONTROL_ON) symbols += spec_symbols; if (CustSymbCB->Value() == B_CONTROL_ON) symbols += CustSymb->Text(); int pass_length = PassLength->Value() + 1; char* password = new char[pass_length]; Generator(password, pass_length, symbols.c_str()); PassOut->SetText(password); delete[] password; } BBitmap* AppWindow::ResourceVectorToBitmap(const char* resName, float iconSize) { BResources res; size_t size; app_info appInfo; be_app->GetAppInfo(&appInfo); BFile appFile(&appInfo.ref, B_READ_ONLY); res.SetTo(&appFile); BBitmap* aBmp = NULL; const uint8* iconData = (const uint8*) res.LoadResource('VICN', resName, &size); if (size > 0) { aBmp = new BBitmap(BRect(0, 0, iconSize, iconSize), 0, B_RGBA32); status_t result = BIconUtils::GetVectorIcon(iconData, size, aBmp); if (result != B_OK) { delete aBmp; aBmp = NULL; } } return aBmp; } BFile AppWindow::PrefsFile(int32 mode) { BPath path; find_directory(B_USER_SETTINGS_DIRECTORY, &path); path.SetTo(path.Path(), PREFS_FILENAME); return BFile(path.Path(), mode); } void AppWindow::SavePreferences(BMessage& msg) { BFile file = PrefsFile(B_WRITE_ONLY | B_CREATE_FILE); file.SetSize(0); msg.Flatten(&file); } void AppWindow::LoadPreferences(BMessage& msg) { BFile file = PrefsFile(B_READ_ONLY); msg.Unflatten(&file); } void AppWindow::ArchivePreferences() { BMessage message; message.AddInt32("PassLength", PassLength->Value()); message.AddBool("UpperCaseCB", UpperCaseCB->Value() == B_CONTROL_ON); message.AddBool("LowerCaseCB", LowerCaseCB->Value() == B_CONTROL_ON); message.AddBool("NumCB", NumCB->Value() == B_CONTROL_ON); message.AddBool("SpecSymbCB", SpecSymbCB->Value() == B_CONTROL_ON); message.AddBool("CustSymbCB", CustSymbCB->Value() == B_CONTROL_ON); message.AddString("CustSymb", CustSymb->Text()); message.AddPoint("WinOrigin", Frame().LeftTop()); SavePreferences(message); } void AppWindow::UnarchivePreferences() { BMessage message; LoadPreferences(message); int32 length; if (message.FindInt32("PassLength", &length) == B_OK) PassLength->SetValue(length); bool controlOn; if (message.FindBool("UpperCaseCB", &controlOn) == B_OK) UpperCaseCB->SetValue(controlOn ? B_CONTROL_ON : B_CONTROL_OFF); if (message.FindBool("LowerCaseCB", &controlOn) == B_OK) LowerCaseCB->SetValue(controlOn ? B_CONTROL_ON : B_CONTROL_OFF); if (message.FindBool("NumCB", &controlOn) == B_OK) NumCB->SetValue(controlOn ? B_CONTROL_ON : B_CONTROL_OFF); if (message.FindBool("SpecSymbCB", &controlOn) == B_OK) SpecSymbCB->SetValue(controlOn ? B_CONTROL_ON : B_CONTROL_OFF); if (message.FindBool("CustSymbCB", &controlOn) == B_OK) { CustSymbCB->SetValue(controlOn ? B_CONTROL_ON : B_CONTROL_OFF); CustSymb->SetEnabled(controlOn); } BString symbols; if (message.FindString("CustSymb", &symbols) == B_OK) CustSymb->SetText(symbols); BPoint origin; if (message.FindPoint("WinOrigin", &origin) == B_OK) { MoveTo(origin); MoveOnScreen(B_MOVE_IF_PARTIALLY_OFFSCREEN); } }
Fix off-by-one error of password length
Fix off-by-one error of password length There's got to be room for the 0 termination...
C++
mit
HaikuArchives/Randomizer
1f7b83ae78a778b37895241ad2bb469fd44e4487
src/Autostart.cpp
src/Autostart.cpp
#include "Autostart.h" #include <QApplication> #include <QDir> #include <QString> #include <QSettings> #include <QFileInfo> #include <QDesktopServices> #ifdef Q_OS_MAC #include <CoreFoundation/CoreFoundation.h> #include <CoreServices/CoreServices.h> LSSharedFileListItemRef FindLoginItemForCurrentBundle(CFArrayRef currentLoginItems) { CFURLRef mainBundleURL = CFBundleCopyBundleURL( CFBundleGetMainBundle() ); for( int i = 0, end = CFArrayGetCount( currentLoginItems ); i < end; ++i ) { LSSharedFileListItemRef item = ( LSSharedFileListItemRef )CFArrayGetValueAtIndex( currentLoginItems, i ); UInt32 resolutionFlags = kLSSharedFileListNoUserInteraction | kLSSharedFileListDoNotMountVolumes; CFURLRef url = NULL; OSStatus err = LSSharedFileListItemResolve( item, resolutionFlags, &url, NULL ); if( err == noErr ) { bool foundIt = CFEqual( url, mainBundleURL ); CFRelease( url ); if( foundIt ) { CFRelease( mainBundleURL ); return item; } } } CFRelease( mainBundleURL ); return NULL; } #endif // Q_OS_MAC bool Autostart::Active() { #ifdef Q_OS_WIN QString applicationName = QCoreApplication::applicationName(); QSettings tmpSettings( "HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\CurrentVersion\\Run", QSettings::NativeFormat ); return !tmpSettings.value( applicationName ).toString().isEmpty(); #elif defined(Q_OS_MAC) LSSharedFileListRef loginItems = LSSharedFileListCreate( NULL, kLSSharedFileListSessionLoginItems, NULL ); if( !loginItems ) { return false; } UInt32 seed = 0U; CFArrayRef currentLoginItems = LSSharedFileListCopySnapshot( loginItems, &seed ); LSSharedFileListItemRef existingItem = FindLoginItemForCurrentBundle( currentLoginItems ); bool isAutoRun = existingItem != NULL; CFRelease( currentLoginItems ); CFRelease( loginItems ); return isAutoRun; #elif defined Q_WS_X11 || defined Q_OS_LINUX #if QT_VERSION >= QT_VERSION_CHECK(5,0,0) QString homeLocation = QStandardPaths::writableLocation( QStandardPaths::HomeLocation ); #else QString homeLocation = QDesktopServices::storageLocation( QDesktopServices::HomeLocation ); #endif QDir* autostartPath = new QDir(homeLocation + "/.config/autostart/"); return autostartPath->exists("track-o-bot.desktop"); #endif return false; } void Autostart::SetActive( bool active ) { #ifdef Q_OS_WIN QString applicationName = QCoreApplication::applicationName(); QString applicationPath = QCoreApplication::applicationFilePath(); QSettings tmpSettings( "HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\CurrentVersion\\Run", QSettings::NativeFormat ); if( active ) { tmpSettings.setValue( applicationName, QString( "\"%1\"" ).arg( QDir::toNativeSeparators( QFileInfo( applicationPath ).filePath() ) ) ); } else { tmpSettings.remove(applicationName); } #elif defined(Q_OS_MAC) LSSharedFileListRef loginItems = LSSharedFileListCreate( NULL, kLSSharedFileListSessionLoginItems, NULL ); if( !loginItems ) return; UInt32 seed = 0U; CFArrayRef currentLoginItems = LSSharedFileListCopySnapshot( loginItems, &seed ); LSSharedFileListItemRef existingItem = FindLoginItemForCurrentBundle( currentLoginItems ); if( active && (existingItem == NULL) ) { CFURLRef mainBundleURL = CFBundleCopyBundleURL( CFBundleGetMainBundle() ); LSSharedFileListInsertItemURL( loginItems, kLSSharedFileListItemBeforeFirst, NULL, NULL, mainBundleURL, NULL, NULL ); CFRelease( mainBundleURL ); } else if( !active && (existingItem != NULL) ) { LSSharedFileListItemRemove(loginItems, existingItem); } CFRelease( currentLoginItems ); CFRelease( loginItems ); #elif defined Q_OS_LINUX QString homeLocation = QStandardPaths::writableLocation( QStandardPaths::HomeLocation ); QDir* autostartPath = new QDir(homeLocation + "/.config/autostart/"); if( !active ) { QFile* desktopFile = new QFile(autostartPath->filePath("track-o-bot.desktop")); desktopFile->remove(); } else { QFile* srcFile = new QFile( ":/assets/track-o-bot.desktop" ); LOG("source: %s", srcFile->fileName().toStdString().c_str()); LOG("source exists: %s", QString::number(srcFile->exists()).toStdString().c_str()); srcFile->copy(autostartPath->filePath("track-o-bot.desktop")); } #endif }
#include "Autostart.h" #include <QApplication> #include <QDir> #include <QString> #include <QSettings> #include <QFileInfo> #include <QDesktopServices> #ifdef Q_OS_MAC #include <CoreFoundation/CoreFoundation.h> #include <CoreServices/CoreServices.h> LSSharedFileListItemRef FindLoginItemForCurrentBundle(CFArrayRef currentLoginItems) { CFURLRef mainBundleURL = CFBundleCopyBundleURL( CFBundleGetMainBundle() ); for( int i = 0, end = CFArrayGetCount( currentLoginItems ); i < end; ++i ) { LSSharedFileListItemRef item = ( LSSharedFileListItemRef )CFArrayGetValueAtIndex( currentLoginItems, i ); UInt32 resolutionFlags = kLSSharedFileListNoUserInteraction | kLSSharedFileListDoNotMountVolumes; CFURLRef url = NULL; OSStatus err = LSSharedFileListItemResolve( item, resolutionFlags, &url, NULL ); if( err == noErr ) { bool foundIt = CFEqual( url, mainBundleURL ); CFRelease( url ); if( foundIt ) { CFRelease( mainBundleURL ); return item; } } } CFRelease( mainBundleURL ); return NULL; } #endif // Q_OS_MAC bool Autostart::Active() { #ifdef Q_OS_WIN QString applicationName = QCoreApplication::applicationName(); QSettings tmpSettings( "HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\CurrentVersion\\Run", QSettings::NativeFormat ); return !tmpSettings.value( applicationName ).toString().isEmpty(); #elif defined(Q_OS_MAC) LSSharedFileListRef loginItems = LSSharedFileListCreate( NULL, kLSSharedFileListSessionLoginItems, NULL ); if( !loginItems ) { return false; } UInt32 seed = 0U; CFArrayRef currentLoginItems = LSSharedFileListCopySnapshot( loginItems, &seed ); LSSharedFileListItemRef existingItem = FindLoginItemForCurrentBundle( currentLoginItems ); bool isAutoRun = existingItem != NULL; CFRelease( currentLoginItems ); CFRelease( loginItems ); return isAutoRun; #elif defined Q_WS_X11 || defined Q_OS_LINUX #if QT_VERSION >= QT_VERSION_CHECK(5,0,0) QString homeLocation = QStandardPaths::writableLocation( QStandardPaths::HomeLocation ); #else QString homeLocation = QDesktopServices::storageLocation( QDesktopServices::HomeLocation ); #endif QDir autostartPath( homeLocation + "/.config/autostart/" ); return autostartPath.exists("track-o-bot.desktop"); #endif return false; } void Autostart::SetActive( bool active ) { #ifdef Q_OS_WIN QString applicationName = QCoreApplication::applicationName(); QString applicationPath = QCoreApplication::applicationFilePath(); QSettings tmpSettings( "HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\CurrentVersion\\Run", QSettings::NativeFormat ); if( active ) { tmpSettings.setValue( applicationName, QString( "\"%1\"" ).arg( QDir::toNativeSeparators( QFileInfo( applicationPath ).filePath() ) ) ); } else { tmpSettings.remove(applicationName); } #elif defined(Q_OS_MAC) LSSharedFileListRef loginItems = LSSharedFileListCreate( NULL, kLSSharedFileListSessionLoginItems, NULL ); if( !loginItems ) return; UInt32 seed = 0U; CFArrayRef currentLoginItems = LSSharedFileListCopySnapshot( loginItems, &seed ); LSSharedFileListItemRef existingItem = FindLoginItemForCurrentBundle( currentLoginItems ); if( active && (existingItem == NULL) ) { CFURLRef mainBundleURL = CFBundleCopyBundleURL( CFBundleGetMainBundle() ); LSSharedFileListInsertItemURL( loginItems, kLSSharedFileListItemBeforeFirst, NULL, NULL, mainBundleURL, NULL, NULL ); CFRelease( mainBundleURL ); } else if( !active && (existingItem != NULL) ) { LSSharedFileListItemRemove(loginItems, existingItem); } CFRelease( currentLoginItems ); CFRelease( loginItems ); #elif defined Q_OS_LINUX QString homeLocation = QStandardPaths::writableLocation( QStandardPaths::HomeLocation ); QDir* autostartPath = new QDir(homeLocation + "/.config/autostart/"); if( !active ) { QFile* desktopFile = new QFile(autostartPath->filePath("track-o-bot.desktop")); desktopFile->remove(); } else { QFile* srcFile = new QFile( ":/assets/track-o-bot.desktop" ); LOG("source: %s", srcFile->fileName().toStdString().c_str()); LOG("source exists: %s", QString::number(srcFile->exists()).toStdString().c_str()); srcFile->copy(autostartPath->filePath("track-o-bot.desktop")); } #endif }
Fix memory leak.
Fix memory leak.
C++
lgpl-2.1
BOSSoNe0013/track-o-bot,BOSSoNe0013/track-o-bot
3cc7b71d6022a171b2576bc5ddcc5f2236331579
SLImageLibraries/SLCImageProcess/Private/SLCImageProcess.cpp
SLImageLibraries/SLCImageProcess/Private/SLCImageProcess.cpp
#include "../stdafx.h" #include "SLCImageProcess.h" #include <vector> namespace slcimage { //==================================================================================================================== //-------------------------------------------------------------------------------------------------------------------- void DuplicateImage(const ATL::CImage& srcImage, ATL::CImage& dstImage) { assert(!srcImage.IsNull()); if (srcImage == dstImage) return; if (!dstImage.IsNull()) dstImage.Destroy(); int srcBitsCount = srcImage.GetBPP(); if (srcBitsCount == 32) dstImage.Create(srcImage.GetWidth(), srcImage.GetHeight(), srcBitsCount, CImage::createAlphaChannel); else dstImage.Create(srcImage.GetWidth(), srcImage.GetHeight(), srcBitsCount, 0); if (srcImage.IsIndexed()) { // 8-bit: 0x100000000 = 256, in the same way, 4-bit: 0x10000 = 16, 2-bit: 0x100 = 4, 1-bit: 0x10 = 2 int nColors = srcImage.GetMaxColorTableEntries(); if (nColors > 0) { std::vector<RGBQUAD> rgbColors(nColors); srcImage.GetColorTable(0, nColors, rgbColors.data()); dstImage.SetColorTable(0, nColors, rgbColors.data()); } } srcImage.BitBlt(dstImage.GetDC(), 0, 0, SRCCOPY); dstImage.ReleaseDC(); // Remember to dstImage.ReleaseDC() after dstImage.GetDC() };// End of DuplicateImage(const CImage& srcImage, CImage& destImage) //======================================================================================================================== //======================================================================================================================== //------------------------------------------------------------------------------------------------------------------------ void StretchImageByWidth(const ATL::CImage& srcImage, int widthInPixel, ATL::CImage& dstImage) { assert(!srcImage.IsNull() && srcImage != dstImage && widthInPixel > 0); int srcBitsCount = srcImage.GetBPP(); double imageAspectRatio = static_cast<double>( srcImage.GetHeight() ) / srcImage.GetWidth() ; // Get valid dstImageWidth and dstImageHeight int dstImageWidth = widthInPixel; double tmpDstImageHeight = imageAspectRatio * dstImageWidth; int dstImageHeight = tmpDstImageHeight > 1.0 ? static_cast<int>(tmpDstImageHeight) : 1; if (!dstImage.IsNull()) dstImage.Destroy(); if (srcBitsCount == 32) dstImage.Create(dstImageWidth, dstImageHeight, srcBitsCount, CImage::createAlphaChannel); else dstImage.Create(dstImageWidth, dstImageHeight, srcBitsCount, 0); // For 8bit CImage, we need to copy the ColorTable after image creation if (srcImage.IsIndexed()) { // 8-bit: 0x100000000 = 256, in the same way, 4-bit: 0x10000 = 16, 2-bit: 0x100 = 4, 1-bit: 0x10 = 2 int nColors = srcImage.GetMaxColorTableEntries(); if (nColors > 0) { std::vector<RGBQUAD> rgbColors(nColors); srcImage.GetColorTable(0, nColors, rgbColors.data()); dstImage.SetColorTable(0, nColors, rgbColors.data()); } } HDC dstHDC = dstImage.GetDC(); SetStretchBltMode(dstHDC, COLORONCOLOR); srcImage.StretchBlt(dstHDC, 0, 0, dstImageWidth, dstImageHeight, SRCCOPY); dstImage.ReleaseDC(); // Remember to dstImage.ReleaseDC() after dstImage.GetDC() }// End of GetSmallerImageByWidth(const ATL::CImage& srcImage, int widthInPixel, ATL::CImage& dstImage) //==================================================================================================================== //-------------------------------------------------------------------------------------------------------------------- /// <summary>Converting 1Bit/4Bit image to 8Bit/24Bit, help low bit image loading for LibreImage</summary> void Convert8BitBelowToAbove(const ATL::CImage& srcImage, int dstBitPerPixel, ATL::CImage& dstImage) { assert(!srcImage.IsNull() && srcImage != dstImage && srcImage.GetBPP() <= 8 && srcImage.GetBPP() < dstBitPerPixel); assert(dstBitPerPixel == 1 || dstBitPerPixel == 4 || dstBitPerPixel == 8 // GrayScaled || dstBitPerPixel == 24 || dstBitPerPixel == 32); // Colored if (!dstImage.IsNull()) dstImage.Destroy(); dstImage.Create(srcImage.GetWidth(), srcImage.GetHeight(), dstBitPerPixel, 0); // For 8bit CImage, we need to copy the ColorTable after image creation if (dstImage.IsIndexed()) { // 8-bit: 0x100000000 = 256, in the same way, 4-bit: 0x10000 = 16, 2-bit: 0x100 = 4, 1-bit: 0x10 = 2 int nColors = srcImage.GetMaxColorTableEntries(); if (nColors > 0) { std::vector<RGBQUAD> rgbColors(nColors); srcImage.GetColorTable(0, nColors, rgbColors.data()); dstImage.SetColorTable(0, nColors, rgbColors.data()); } } srcImage.BitBlt(dstImage.GetDC(), 0, 0, SRCCOPY); dstImage.ReleaseDC(); // Remember to dstImage.ReleaseDC() after dstImage.GetDC() } void Convert8bitTo32Bit(const ATL::CImage& srcImage, ATL::CImage& dstImage) { assert(!srcImage.IsNull() && srcImage != dstImage && srcImage.GetBPP() == 8); if (!dstImage.IsNull()) dstImage.Destroy(); dstImage.Create(srcImage.GetWidth(), srcImage.GetHeight(), 32, CImage::createAlphaChannel); // CImage::BitBlt won't work with alpha channel, we have to set pixel one by one for (int row = 0; row < dstImage.GetHeight(); row++) { for (int col = 0; col < dstImage.GetWidth(); col++) { BYTE* pixelEntry = static_cast<BYTE*>(dstImage.GetPixelAddress(col, row)); const BYTE intensity = static_cast<const BYTE*>(srcImage.GetPixelAddress(col, row))[0]; pixelEntry[0] = intensity; pixelEntry[1] = intensity; pixelEntry[2] = intensity; pixelEntry[3] = 0xFF; } } } } // End of namespace slcimage
#include "../stdafx.h" #include "SLCImageProcess.h" #include <vector> namespace slcimage { //==================================================================================================================== //-------------------------------------------------------------------------------------------------------------------- void DuplicateImage(const ATL::CImage& srcImage, ATL::CImage& dstImage) { assert(!srcImage.IsNull()); if (srcImage == dstImage) return; if (!dstImage.IsNull()) dstImage.Destroy(); int srcBitsCount = srcImage.GetBPP(); if (srcBitsCount == 32) dstImage.Create(srcImage.GetWidth(), srcImage.GetHeight(), srcBitsCount, CImage::createAlphaChannel); else dstImage.Create(srcImage.GetWidth(), srcImage.GetHeight(), srcBitsCount, 0); if (srcImage.IsIndexed()) { // 8-bit: 0x100000000 = 256, in the same way, 4-bit: 0x10000 = 16, 2-bit: 0x100 = 4, 1-bit: 0x10 = 2 int nColors = srcImage.GetMaxColorTableEntries(); if (nColors > 0) { std::vector<RGBQUAD> rgbColors(nColors); srcImage.GetColorTable(0, nColors, rgbColors.data()); dstImage.SetColorTable(0, nColors, rgbColors.data()); } } srcImage.BitBlt(dstImage.GetDC(), 0, 0, SRCCOPY); dstImage.ReleaseDC(); // Remember to dstImage.ReleaseDC() after dstImage.GetDC() };// End of DuplicateImage(const CImage& srcImage, CImage& destImage) //======================================================================================================================== //======================================================================================================================== //------------------------------------------------------------------------------------------------------------------------ void StretchImageByWidth(const ATL::CImage& srcImage, int widthInPixel, ATL::CImage& dstImage) { assert(!srcImage.IsNull() && srcImage != dstImage && widthInPixel > 0); int srcBitsCount = srcImage.GetBPP(); double imageAspectRatio = static_cast<double>( srcImage.GetHeight() ) / srcImage.GetWidth() ; // Get valid dstImageWidth and dstImageHeight int dstImageWidth = widthInPixel; double tmpDstImageHeight = imageAspectRatio * dstImageWidth; int dstImageHeight = tmpDstImageHeight > 1.0 ? static_cast<int>(tmpDstImageHeight) : 1; if (!dstImage.IsNull()) dstImage.Destroy(); if (srcBitsCount == 32) dstImage.Create(dstImageWidth, dstImageHeight, srcBitsCount, CImage::createAlphaChannel); else dstImage.Create(dstImageWidth, dstImageHeight, srcBitsCount, 0); // For 8bit CImage, we need to copy the ColorTable after image creation if (srcImage.IsIndexed()) { // 8-bit: 0x100000000 = 256, in the same way, 4-bit: 0x10000 = 16, 2-bit: 0x100 = 4, 1-bit: 0x10 = 2 int nColors = srcImage.GetMaxColorTableEntries(); if (nColors > 0) { std::vector<RGBQUAD> rgbColors(nColors); srcImage.GetColorTable(0, nColors, rgbColors.data()); dstImage.SetColorTable(0, nColors, rgbColors.data()); } } HDC dstHDC = dstImage.GetDC(); SetStretchBltMode(dstHDC, COLORONCOLOR); srcImage.StretchBlt(dstHDC, 0, 0, dstImageWidth, dstImageHeight, SRCCOPY); dstImage.ReleaseDC(); // Remember to dstImage.ReleaseDC() after dstImage.GetDC() //========== Below is for DownSample Algorithms Testing =============================================== //---------- include #include <wincodec.h> before using IWICBitmapScaler ------------------------ //IWICImagingFactory *imagingFactory; //CoCreateInstance(CLSID_WICImagingFactory, NULL, CLSCTX_INPROC_SERVER, IID_PPV_ARGS(&imagingFactory)); //IWICBitmap* srcIWICBitmap; //imagingFactory->CreateBitmapFromHBITMAP(srcImage, 0, WICBitmapUseAlpha, &srcIWICBitmap); //IWICBitmapScaler* bitmapScaler; //imagingFactory->CreateBitmapScaler(&bitmapScaler); //bitmapScaler->Initialize(srcIWICBitmap, dstImageWidth, dstImageHeight, WICBitmapInterpolationModeCubic); //WICRect rect = { 0, 0, dstImageWidth, 1 }; //int stride = std::abs(dstImage.GetPitch()); //BYTE* bufferEntry = static_cast<BYTE*>(dstImage.GetBits()); //for (int i = 0; i < dstImageHeight; ++i) //{ // bitmapScaler->CopyPixels(&rect, stride, stride, bufferEntry); // bufferEntry -= stride; // rect.Y += 1; //} //bitmapScaler->Release(); //imagingFactory->Release(); }// End of GetSmallerImageByWidth(const ATL::CImage& srcImage, int widthInPixel, ATL::CImage& dstImage) //==================================================================================================================== //-------------------------------------------------------------------------------------------------------------------- /// <summary>Converting 1Bit/4Bit image to 8Bit/24Bit, help low bit image loading for LibreImage</summary> void Convert8BitBelowToAbove(const ATL::CImage& srcImage, int dstBitPerPixel, ATL::CImage& dstImage) { assert(!srcImage.IsNull() && srcImage != dstImage && srcImage.GetBPP() <= 8 && srcImage.GetBPP() < dstBitPerPixel); assert(dstBitPerPixel == 1 || dstBitPerPixel == 4 || dstBitPerPixel == 8 // GrayScaled || dstBitPerPixel == 24 || dstBitPerPixel == 32); // Colored if (!dstImage.IsNull()) dstImage.Destroy(); dstImage.Create(srcImage.GetWidth(), srcImage.GetHeight(), dstBitPerPixel, 0); // For 8bit CImage, we need to copy the ColorTable after image creation if (dstImage.IsIndexed()) { // 8-bit: 0x100000000 = 256, in the same way, 4-bit: 0x10000 = 16, 2-bit: 0x100 = 4, 1-bit: 0x10 = 2 int nColors = srcImage.GetMaxColorTableEntries(); if (nColors > 0) { std::vector<RGBQUAD> rgbColors(nColors); srcImage.GetColorTable(0, nColors, rgbColors.data()); dstImage.SetColorTable(0, nColors, rgbColors.data()); } } srcImage.BitBlt(dstImage.GetDC(), 0, 0, SRCCOPY); dstImage.ReleaseDC(); // Remember to dstImage.ReleaseDC() after dstImage.GetDC() } void Convert8bitTo32Bit(const ATL::CImage& srcImage, ATL::CImage& dstImage) { assert(!srcImage.IsNull() && srcImage != dstImage && srcImage.GetBPP() == 8); if (!dstImage.IsNull()) dstImage.Destroy(); dstImage.Create(srcImage.GetWidth(), srcImage.GetHeight(), 32, CImage::createAlphaChannel); // CImage::BitBlt won't work with alpha channel, we have to set pixel one by one for (int row = 0; row < dstImage.GetHeight(); row++) { for (int col = 0; col < dstImage.GetWidth(); col++) { BYTE* pixelEntry = static_cast<BYTE*>(dstImage.GetPixelAddress(col, row)); const BYTE intensity = static_cast<const BYTE*>(srcImage.GetPixelAddress(col, row))[0]; pixelEntry[0] = intensity; pixelEntry[1] = intensity; pixelEntry[2] = intensity; pixelEntry[3] = 0xFF; } } } } // End of namespace slcimage
Add DownSampling Algorithms for CImage Streth using IWICBitmap
Add DownSampling Algorithms for CImage Streth using IWICBitmap
C++
mit
SenonLi/OpenGL_4.0_FreeSpace,SenonLi/OpenGL_4.0_FreeSpace,SenonLi/OpenGL_4.0_FreeSpace
826467f175572762e63645158efeb787ee27ab97
Src/Ancona/Engine/Core/Systems/Drawable/AnimatedDrawable.hpp
Src/Ancona/Engine/Core/Systems/Drawable/AnimatedDrawable.hpp
#ifndef Ancona_Engine_Core_Systems_AnimatedDrawable_H_ #define Ancona_Engine_Core_Systems_AnimatedDrawable_H_ #include <Ancona/Engine/Core/Systems/Drawable/SpriteDrawable.hpp> namespace ild { /** * @brief Responsible for drawing an animated sprite to the window. * * @author Tucker Lein */ class AnimatedDrawable : public SpriteDrawable { public: AnimatedDrawable( const PositionComponent & positionComponent, const std::string textureKey, const RenderPriorityEnum priority, sf::Vector2f frameDimensions, int numFrames, int speed, float xGap = 0, float yGap = 0, int priorityOffset = 0, sf::Vector2f positionOffset = sf::Vector2f(0.0f, 0.0f)); /** * @brief Draws the animated sprite to the window. * * @param window RenderWindow for the game. */ void Draw(sf::RenderWindow & window); private: /** * @brief Dimensions of a frame in the animated texture. */ sf::Vector2f _frameDimensions; /** * @brief Gap between frames in the x dimension. */ float _xGap; /** * @brief Gap between frames in the y dimension. */ float _yGap; /** * @brief Frames an animation is shown. */ int _speed; /** * @brief Original amount of frames to show the animation for. */ const int SPEED_CAP; /** * @brief Number of frames in the animation. */ int _numFrames; /** * @brief The current frame being shown. */ int _curFrame = 0; /** * @brief Advances the frame. */ void AdvanceFrame(); }; } #endif
#ifndef Ancona_Engine_Core_Systems_AnimatedDrawable_H_ #define Ancona_Engine_Core_Systems_AnimatedDrawable_H_ #include <Ancona/Engine/Core/Systems/Drawable/SpriteDrawable.hpp> namespace ild { /** * @brief Responsible for drawing an animated sprite to the window. * * @author Tucker Lein */ class AnimatedDrawable : public SpriteDrawable { public: /** * @brief Constructs an AnimatedDrawable * * @param positionComponent PositionComponent for the entity associated with this drawable element. * @param textureKey Key of the texture used for the animation. * @param priority RenderPriority that determines when the drawable obj is rendered. * @param frameDimensions Dimensions of a frame in the animated texture. * @param numFrames Number of frames in the animation. * @param speed Speed of the animation. * @param xGap Gap between frames in the x dimension, defaults to 0. * @param yGap Gap between frames in the y dimension, defaults to 0. * @param priorityOffset Optional offset to the render priority. * @param positionOffset Vector that defines the offset from the DrawableComponent's position. */ AnimatedDrawable( const PositionComponent & positionComponent, const std::string textureKey, const RenderPriorityEnum priority, sf::Vector2f frameDimensions, int numFrames, int speed, float xGap = 0, float yGap = 0, int priorityOffset = 0, sf::Vector2f positionOffset = sf::Vector2f(0.0f, 0.0f)); /** * @brief Draws the animated sprite to the window. * * @param window RenderWindow for the game. */ void Draw(sf::RenderWindow & window); private: /** * @brief Dimensions of a frame in the animated texture. */ sf::Vector2f _frameDimensions; /** * @brief Gap between frames in the x dimension. */ float _xGap; /** * @brief Gap between frames in the y dimension. */ float _yGap; /** * @brief Frames an animation is shown. */ int _speed; /** * @brief Original amount of frames to show the animation for. */ const int SPEED_CAP; /** * @brief Number of frames in the animation. */ int _numFrames; /** * @brief The current frame being shown. */ int _curFrame = 0; /** * @brief Advances the frame. */ void AdvanceFrame(); }; } #endif
Add the comment to the AnimatedDrawable header
Add the comment to the AnimatedDrawable header
C++
mit
tlein/Ancona,tlein/Ancona,tlein/Ancona,tlein/Ancona
4810ee052075fc6246e6b60999886badeb872b93
App/AudioTee.cpp
App/AudioTee.cpp
#include <iostream> #include <fstream> #include <time.h> #include <AudioToolbox/AudioFile.h> #include <AudioToolbox/AudioConverter.h> #include <CARingBuffer.h> #include <CABitOperations.h> #include "AudioTee.h" #include "AudioDevice.h" #include "WavFileUtils.h" AudioTee::AudioTee(AudioDeviceID inputDeviceID, AudioDeviceID outputDeviceID) : mWorkBuf(NULL), mSecondsInHistoryBuffer(20), mHistBuf(), mHistoryBufferMaxByteSize(0), mBufferSize(1024), mExtraLatencyFrames(0), mInputDevice(inputDeviceID, true), mOutputDevice(outputDeviceID, false), mFirstRun(true), mRunning(false), mMuting(false), mThruing(true), mHistoryBufferByteSize(0), mHistoryBufferHeadOffsetFrameNumber(0) { mInputDevice.SetBufferSize(mBufferSize); mOutputDevice.SetBufferSize(mBufferSize); } void AudioTee::ComputeThruOffset() { if (!mRunning) { mActualThruLatency = 0; mInToOutSampleOffset = 0; return; } mActualThruLatency = SInt32(mInputDevice.mSafetyOffset + mInputDevice.mBufferSizeFrames + mOutputDevice.mSafetyOffset + mOutputDevice.mBufferSizeFrames) + mExtraLatencyFrames; mInToOutSampleOffset = mActualThruLatency + mIODeltaSampleCount; } OSStatus AudioTee::MatchSampleRates(AudioObjectID changedDeviceID) { OSStatus status = kAudioHardwareNoError; mInputDevice.ReloadStreamFormat(); mOutputDevice.ReloadStreamFormat(); if (mInputDevice.mFormat.mSampleRate != mOutputDevice.mFormat.mSampleRate) { if (mInputDevice.mID == changedDeviceID) { status = mOutputDevice.SetSampleRate(mInputDevice.mFormat.mSampleRate); } else if (mOutputDevice.mID == changedDeviceID) { status = mInputDevice.SetSampleRate(mOutputDevice.mFormat.mSampleRate); } else { printf("Error in AudioTee::MatchSampleRates() - unrelated device ID: %u \n", changedDeviceID); } } return status; } void AudioTee::Start() { if (mRunning) return; if (mInputDevice.mID == kAudioDeviceUnknown || mOutputDevice.mID == kAudioDeviceUnknown) return; MatchSampleRates(mOutputDevice.mID); if (mInputDevice.mFormat.mSampleRate != mOutputDevice.mFormat.mSampleRate) { printf("Error in AudioTee::Start() - sample rate mismatch: %f / %f\n", mInputDevice.mFormat.mSampleRate, mOutputDevice.mFormat.mSampleRate); return; } mSampleRate = mInputDevice.mFormat.mSampleRate; mWorkBuf = new Byte[mInputDevice.mBufferSizeFrames * mInputDevice.mFormat.mBytesPerFrame]; memset(mWorkBuf, 0, mInputDevice.mBufferSizeFrames * mInputDevice.mFormat.mBytesPerFrame); UInt32 framesInHistoryBuffer = NextPowerOfTwo(mInputDevice.mFormat.mSampleRate * mSecondsInHistoryBuffer); mHistoryBufferMaxByteSize = mInputDevice.mFormat.mBytesPerFrame * framesInHistoryBuffer; mHistBuf = new CARingBuffer(); mHistBuf->Allocate(2, mInputDevice.mFormat.mBytesPerFrame, framesInHistoryBuffer); printf("Initializing history buffer with byte capacity %u — %f seconds at %f kHz", mHistoryBufferMaxByteSize, (mHistoryBufferMaxByteSize / mInputDevice.mFormat.mSampleRate / (4 * 2)), mInputDevice.mFormat.mSampleRate); printf("Initializing work buffer with mBufferSizeFrames:%u and mBytesPerFrame %u\n", mInputDevice.mBufferSizeFrames, mInputDevice.mFormat.mBytesPerFrame); mRunning = true; mInputIOProcID = NULL; AudioDeviceCreateIOProcID(mInputDevice.mID, InputIOProc, this, &mInputIOProcID); AudioDeviceStart(mInputDevice.mID, mInputIOProcID); mOutputIOProc = OutputIOProc; mOutputIOProcID = NULL; AudioDeviceCreateIOProcID(mOutputDevice.mID, mOutputIOProc, this, &mOutputIOProcID); AudioDeviceStart(mOutputDevice.mID, mOutputIOProcID); ComputeThruOffset(); } bool AudioTee::Stop() { if (!mRunning) return false; mRunning = false; usleep(5000); AudioDeviceStop(mInputDevice.mID, mInputIOProcID); AudioDeviceDestroyIOProcID(mInputDevice.mID, mInputIOProcID); AudioDeviceStop(mOutputDevice.mID, mOutputIOProcID); AudioDeviceDestroyIOProcID(mOutputDevice.mID, mOutputIOProcID); if (mWorkBuf) { delete[] mWorkBuf; mWorkBuf = NULL; } return true; } } } void AudioTee::saveHistoryBuffer(const char* fileName, UInt32 secondsRequested){ UInt32 numberOfBytesWeWant = secondsRequested * mInputDevice.mFormat.mSampleRate * (4 * 2); int32_t numberOfBytesToRequest = std::min(numberOfBytesWeWant, mHistoryBufferByteSize); AudioBuffer *buffer = new AudioBuffer(); buffer->mDataByteSize = numberOfBytesToRequest; buffer->mData = new UInt32[buffer->mDataByteSize]; AudioBufferList *abl = new AudioBufferList(); abl->mNumberBuffers = 1; abl->mBuffers[0] = *buffer; numberOfBytesToRequest = buffer->mDataByteSize; UInt32 nFrames = numberOfBytesToRequest / (4 * 2); mHistBuf->Fetch(abl, nFrames, mHistoryBufferHeadOffsetFrameNumber); WavFileUtils::writeWavFileHeaders(fileName, numberOfBytesToRequest, 44100, 16); UInt32 *srcBuff = (UInt32*)buffer->mData; SInt16 *dstBuff = new SInt16[nFrames * 2]; AudioBuffer srcConvertBuff; srcConvertBuff.mNumberChannels = 2; srcConvertBuff.mDataByteSize = numberOfBytesToRequest; srcConvertBuff.mData = srcBuff; AudioBuffer dstConvertBuff; dstConvertBuff.mNumberChannels = 2; dstConvertBuff.mDataByteSize = ((nFrames * 2) * sizeof(SInt16)); dstConvertBuff.mData = dstBuff; AudioBufferList srcBuffList; srcBuffList.mNumberBuffers = 1; AudioBufferList dstBuffList; dstBuffList.mNumberBuffers = 1; srcBuffList.mBuffers[0] = srcConvertBuff; dstBuffList.mBuffers[0] = dstConvertBuff; AudioConverterRef con; AudioStreamBasicDescription inDesc = this->mOutputDevice.mFormat; AudioStreamBasicDescription outDesc = this->mOutputDevice.mFormat; outDesc.mBitsPerChannel = sizeof(SInt16) * 8; outDesc.mBytesPerFrame = sizeof(SInt16) * 2; outDesc.mBytesPerPacket = sizeof(SInt16) * 2; outDesc.mChannelsPerFrame = 2; outDesc.mFramesPerPacket = 1; outDesc.mFormatFlags = kAudioFormatFlagsAreAllClear | kAudioFormatFlagIsSignedInteger | kAudioFormatFlagIsPacked; AudioConverterNew(&inDesc, &outDesc, &con); AudioConverterConvertComplexBuffer(con, nFrames, &srcBuffList, &dstBuffList); std::fstream file(fileName, std::ios::binary | std::ios::app | std::ios::out | std::ios::in); file.write((char *)dstBuffList.mBuffers[0].mData, dstBuffList.mBuffers[0].mDataByteSize); file.close(); delete[] dstBuff; delete buffer; delete abl; dstBuff = 0; } OSStatus AudioTee::InputIOProc(AudioDeviceID inDevice, const AudioTimeStamp *inNow, const AudioBufferList *inInputData, const AudioTimeStamp *inInputTime, AudioBufferList *outOutputData, const AudioTimeStamp *inOutputTime, void *inClientData) { AudioTee *This = (AudioTee *)inClientData; This->mLastInputSampleCount = inInputTime->mSampleTime; for(UInt32 i=0; i<outOutputData->mNumberBuffers; i++){ memcpy(This->mWorkBuf, inInputData->mBuffers[i].mData, inInputData->mBuffers[i].mDataByteSize); AudioBuffer ab; AudioBufferList abl; ab.mDataByteSize = inInputData->mBuffers[i].mDataByteSize; ab.mData = This->mWorkBuf; abl.mBuffers[0] = ab; abl.mNumberBuffers = 1; This->mHistBuf->Store(&abl, (inInputData->mBuffers[i].mDataByteSize / inInputData->mBuffers[i].mNumberChannels) / sizeof(UInt32), This->mHistoryBufferHeadOffsetFrameNumber); if(This->mHistoryBufferByteSize < (This->mHistoryBufferMaxByteSize - inInputData->mBuffers[i].mDataByteSize)){ This->mHistoryBufferByteSize += inInputData->mBuffers[i].mDataByteSize; } else { This->mHistoryBufferByteSize = This->mHistoryBufferMaxByteSize; } This->mHistoryBufferHeadOffsetFrameNumber = ((This->mHistoryBufferHeadOffsetFrameNumber + (inInputData->mBuffers[i].mDataByteSize / 8)) % (This->mHistoryBufferMaxByteSize / 8)); } return noErr; } OSStatus AudioTee::OutputIOProc(AudioDeviceID inDevice, const AudioTimeStamp *inNow, const AudioBufferList *inInputData, const AudioTimeStamp *inInputTime, AudioBufferList *outOutputData, const AudioTimeStamp *inOutputTime, void *inClientData) { AudioTee *This = (AudioTee *)inClientData; if (!This->mMuting && This->mThruing) { for(UInt32 i=0; i<outOutputData->mNumberBuffers; i++){ UInt32 bytesToCopy = outOutputData->mBuffers[i].mDataByteSize; memcpy(outOutputData->mBuffers[i].mData, This->mWorkBuf, bytesToCopy); } } else { This->mThruTime = 0.; } return noErr; }
#include <iostream> #include <fstream> #include <time.h> #include <AudioToolbox/AudioFile.h> #include <AudioToolbox/AudioConverter.h> #include <CARingBuffer.h> #include <CABitOperations.h> #include "AudioTee.h" #include "AudioDevice.h" #include "WavFileUtils.h" AudioTee::AudioTee(AudioDeviceID inputDeviceID, AudioDeviceID outputDeviceID) : mWorkBuf(NULL), mSecondsInHistoryBuffer(20), mHistBuf(), mHistoryBufferMaxByteSize(0), mBufferSize(1024), mExtraLatencyFrames(0), mInputDevice(inputDeviceID, true), mOutputDevice(outputDeviceID, false), mFirstRun(true), mRunning(false), mMuting(false), mThruing(true), mHistoryBufferByteSize(0), mHistoryBufferHeadOffsetFrameNumber(0) { mInputDevice.SetBufferSize(mBufferSize); mOutputDevice.SetBufferSize(mBufferSize); } void AudioTee::Start() { if (mRunning) return; if (mInputDevice.mID == kAudioDeviceUnknown || mOutputDevice.mID == kAudioDeviceUnknown) return; MatchSampleRates(mOutputDevice.mID); if (mInputDevice.mFormat.mSampleRate != mOutputDevice.mFormat.mSampleRate) { printf("Error in AudioTee::Start() - sample rate mismatch: %f / %f\n", mInputDevice.mFormat.mSampleRate, mOutputDevice.mFormat.mSampleRate); return; } mSampleRate = mInputDevice.mFormat.mSampleRate; mWorkBuf = new Byte[mInputDevice.mBufferSizeFrames * mInputDevice.mFormat.mBytesPerFrame]; memset(mWorkBuf, 0, mInputDevice.mBufferSizeFrames * mInputDevice.mFormat.mBytesPerFrame); UInt32 framesInHistoryBuffer = NextPowerOfTwo(mInputDevice.mFormat.mSampleRate * mSecondsInHistoryBuffer); mHistoryBufferMaxByteSize = mInputDevice.mFormat.mBytesPerFrame * framesInHistoryBuffer; mHistBuf = new CARingBuffer(); mHistBuf->Allocate(2, mInputDevice.mFormat.mBytesPerFrame, framesInHistoryBuffer); printf("Initializing history buffer with byte capacity %u — %f seconds at %f kHz", mHistoryBufferMaxByteSize, (mHistoryBufferMaxByteSize / mInputDevice.mFormat.mSampleRate / (4 * 2)), mInputDevice.mFormat.mSampleRate); printf("Initializing work buffer with mBufferSizeFrames:%u and mBytesPerFrame %u\n", mInputDevice.mBufferSizeFrames, mInputDevice.mFormat.mBytesPerFrame); mRunning = true; mInputIOProcID = NULL; AudioDeviceCreateIOProcID(mInputDevice.mID, InputIOProc, this, &mInputIOProcID); AudioDeviceStart(mInputDevice.mID, mInputIOProcID); mOutputIOProc = OutputIOProc; mOutputIOProcID = NULL; AudioDeviceCreateIOProcID(mOutputDevice.mID, mOutputIOProc, this, &mOutputIOProcID); AudioDeviceStart(mOutputDevice.mID, mOutputIOProcID); ComputeThruOffset(); } bool AudioTee::Stop() { if (!mRunning) return false; mRunning = false; usleep(5000); AudioDeviceStop(mInputDevice.mID, mInputIOProcID); AudioDeviceDestroyIOProcID(mInputDevice.mID, mInputIOProcID); AudioDeviceStop(mOutputDevice.mID, mOutputIOProcID); AudioDeviceDestroyIOProcID(mOutputDevice.mID, mOutputIOProcID); if (mWorkBuf) { delete[] mWorkBuf; mWorkBuf = NULL; } return true; } OSStatus AudioTee::InputIOProc(AudioDeviceID inDevice, const AudioTimeStamp *inNow, const AudioBufferList *inInputData, const AudioTimeStamp *inInputTime, AudioBufferList *outOutputData, const AudioTimeStamp *inOutputTime, void *inClientData) { AudioTee *This = (AudioTee *)inClientData; This->mLastInputSampleCount = inInputTime->mSampleTime; for(UInt32 i=0; i<outOutputData->mNumberBuffers; i++){ memcpy(This->mWorkBuf, inInputData->mBuffers[i].mData, inInputData->mBuffers[i].mDataByteSize); AudioBuffer ab; AudioBufferList abl; ab.mDataByteSize = inInputData->mBuffers[i].mDataByteSize; ab.mData = This->mWorkBuf; abl.mBuffers[0] = ab; abl.mNumberBuffers = 1; This->mHistBuf->Store(&abl, (inInputData->mBuffers[i].mDataByteSize / inInputData->mBuffers[i].mNumberChannels) / sizeof(UInt32), This->mHistoryBufferHeadOffsetFrameNumber); if(This->mHistoryBufferByteSize < (This->mHistoryBufferMaxByteSize - inInputData->mBuffers[i].mDataByteSize)){ This->mHistoryBufferByteSize += inInputData->mBuffers[i].mDataByteSize; } else { This->mHistoryBufferByteSize = This->mHistoryBufferMaxByteSize; } This->mHistoryBufferHeadOffsetFrameNumber = ((This->mHistoryBufferHeadOffsetFrameNumber + (inInputData->mBuffers[i].mDataByteSize / 8)) % (This->mHistoryBufferMaxByteSize / 8)); } return noErr; } OSStatus AudioTee::OutputIOProc(AudioDeviceID inDevice, const AudioTimeStamp *inNow, const AudioBufferList *inInputData, const AudioTimeStamp *inInputTime, AudioBufferList *outOutputData, const AudioTimeStamp *inOutputTime, void *inClientData) { AudioTee *This = (AudioTee *)inClientData; if (!This->mMuting && This->mThruing) { for(UInt32 i=0; i<outOutputData->mNumberBuffers; i++){ UInt32 bytesToCopy = outOutputData->mBuffers[i].mDataByteSize; memcpy(outOutputData->mBuffers[i].mData, This->mWorkBuf, bytesToCopy); } } else { This->mThruTime = 0.; } return noErr; } void AudioTee::saveHistoryBuffer(const char* fileName, UInt32 secondsRequested){ UInt32 numberOfBytesWeWant = secondsRequested * mInputDevice.mFormat.mSampleRate * (4 * 2); int32_t numberOfBytesToRequest = std::min(numberOfBytesWeWant, mHistoryBufferByteSize); AudioBuffer *buffer = new AudioBuffer(); buffer->mDataByteSize = numberOfBytesToRequest; buffer->mData = new UInt32[buffer->mDataByteSize]; AudioBufferList *abl = new AudioBufferList(); abl->mNumberBuffers = 1; abl->mBuffers[0] = *buffer; numberOfBytesToRequest = buffer->mDataByteSize; UInt32 nFrames = numberOfBytesToRequest / (4 * 2); mHistBuf->Fetch(abl, nFrames, mHistoryBufferHeadOffsetFrameNumber); WavFileUtils::writeWavFileHeaders(fileName, numberOfBytesToRequest, 44100, 16); UInt32 *srcBuff = (UInt32*)buffer->mData; SInt16 *dstBuff = new SInt16[nFrames * 2]; AudioBuffer srcConvertBuff; srcConvertBuff.mNumberChannels = 2; srcConvertBuff.mDataByteSize = numberOfBytesToRequest; srcConvertBuff.mData = srcBuff; AudioBuffer dstConvertBuff; dstConvertBuff.mNumberChannels = 2; dstConvertBuff.mDataByteSize = ((nFrames * 2) * sizeof(SInt16)); dstConvertBuff.mData = dstBuff; AudioBufferList srcBuffList; srcBuffList.mNumberBuffers = 1; AudioBufferList dstBuffList; dstBuffList.mNumberBuffers = 1; srcBuffList.mBuffers[0] = srcConvertBuff; dstBuffList.mBuffers[0] = dstConvertBuff; AudioConverterRef con; AudioStreamBasicDescription inDesc = this->mOutputDevice.mFormat; AudioStreamBasicDescription outDesc = this->mOutputDevice.mFormat; outDesc.mBitsPerChannel = sizeof(SInt16) * 8; outDesc.mBytesPerFrame = sizeof(SInt16) * 2; outDesc.mBytesPerPacket = sizeof(SInt16) * 2; outDesc.mChannelsPerFrame = 2; outDesc.mFramesPerPacket = 1; outDesc.mFormatFlags = kAudioFormatFlagsAreAllClear | kAudioFormatFlagIsSignedInteger | kAudioFormatFlagIsPacked; AudioConverterNew(&inDesc, &outDesc, &con); AudioConverterConvertComplexBuffer(con, nFrames, &srcBuffList, &dstBuffList); std::fstream file(fileName, std::ios::binary | std::ios::app | std::ios::out | std::ios::in); file.write((char *)dstBuffList.mBuffers[0].mData, dstBuffList.mBuffers[0].mDataByteSize); file.close(); delete[] dstBuff; delete buffer; delete abl; dstBuff = 0; } void AudioTee::ComputeThruOffset() { if (!mRunning) { mActualThruLatency = 0; mInToOutSampleOffset = 0; return; } mActualThruLatency = SInt32(mInputDevice.mSafetyOffset + mInputDevice.mBufferSizeFrames + mOutputDevice.mSafetyOffset + mOutputDevice.mBufferSizeFrames) + mExtraLatencyFrames; mInToOutSampleOffset = mActualThruLatency + mIODeltaSampleCount; } OSStatus AudioTee::MatchSampleRates(AudioObjectID changedDeviceID) { OSStatus status = kAudioHardwareNoError; mInputDevice.ReloadStreamFormat(); mOutputDevice.ReloadStreamFormat(); if (mInputDevice.mFormat.mSampleRate != mOutputDevice.mFormat.mSampleRate) { if (mInputDevice.mID == changedDeviceID) { status = mOutputDevice.SetSampleRate(mInputDevice.mFormat.mSampleRate); } else if (mOutputDevice.mID == changedDeviceID) { status = mInputDevice.SetSampleRate(mOutputDevice.mFormat.mSampleRate); } else { printf("Error in AudioTee::MatchSampleRates() - unrelated device ID: %u \n", changedDeviceID); } } return status; }
reorder AudioTee method definitions
formatting: reorder AudioTee method definitions
C++
mit
pje/WavTap,derekjanni/WavTap,pje/WavTap,derekjanni/WavTap,pje/WavTap
6302a41a8095e99c5195a0218a202393f55b0906
AgoraClrLibrary/AgoraClrLibrary/AgoraClrVideoDeviceManager.cpp
AgoraClrLibrary/AgoraClrLibrary/AgoraClrVideoDeviceManager.cpp
#include "stdafx.h" #include "AgoraClrVideoDeviceManager.h" #include "AgoraClrLibrary.h" AgoraClrLibrary::ClrVideoDeviceCollection::ClrVideoDeviceCollection(IVideoDeviceCollection * rawCollection):raw(rawCollection) { } AgoraClrLibrary::ClrVideoDeviceCollection::~ClrVideoDeviceCollection() { this->release(); this->!ClrVideoDeviceCollection(); } AgoraClrLibrary::ClrVideoDeviceCollection::!ClrVideoDeviceCollection() { } int AgoraClrLibrary::ClrVideoDeviceCollection::getCount() { return raw->getCount(); } int AgoraClrLibrary::ClrVideoDeviceCollection::getDevice(int index, String ^% deviceName, String ^% deviceId) { char deviceNameBuffer[MAX_DEVICE_ID_LENGTH] = { 0 }; char deviceIdBuffer[MAX_DEVICE_ID_LENGTH] = { 0 }; int result = raw->getDevice(index, deviceNameBuffer, deviceIdBuffer); if (result != 0) return result; deviceName = gcnew String(deviceNameBuffer), deviceId = gcnew String(deviceId); return result; // return raw->getDevice(index, const_cast<char*>(MarshalString(deviceName).c_str()), const_cast<char*>(MarshalString(deviceId).c_str())); } int AgoraClrLibrary::ClrVideoDeviceCollection::setDevice(String ^ deviceId) { return raw->setDevice(const_cast<char*>(MarshalString(deviceId).c_str())); } void AgoraClrLibrary::ClrVideoDeviceCollection::release() { raw->release(); } AgoraClrLibrary::AgoraClrVideoDeviceManager::AgoraClrVideoDeviceManager(AgoraClr ^ engine) { this->engine = engine; } AgoraClrLibrary::ClrVideoDeviceCollection ^ AgoraClrLibrary::AgoraClrVideoDeviceManager::enumerateVideoDevices() { AVideoDeviceManager manager(engine->getEngine()); return gcnew ClrVideoDeviceCollection(manager->enumerateVideoDevices()); } int AgoraClrLibrary::AgoraClrVideoDeviceManager::setDevice(String ^ deviceId) { AVideoDeviceManager manager(engine->getEngine()); return manager->setDevice(MarshalString(deviceId).c_str()); } int AgoraClrLibrary::AgoraClrVideoDeviceManager::getDevice(String ^ deviceId) { AVideoDeviceManager manager(engine->getEngine()); return manager->getDevice(const_cast<char*>(MarshalString(deviceId).c_str())); } int AgoraClrLibrary::AgoraClrVideoDeviceManager::startDeviceTest(IntPtr hwnd) { AVideoDeviceManager manager(engine->getEngine()); return manager->startDeviceTest(hwnd.ToPointer()); } int AgoraClrLibrary::AgoraClrVideoDeviceManager::stopDeviceTest() { AVideoDeviceManager manager(engine->getEngine()); return manager->stopDeviceTest(); }
#include "stdafx.h" #include "AgoraClrVideoDeviceManager.h" #include "AgoraClrLibrary.h" AgoraClrLibrary::ClrVideoDeviceCollection::ClrVideoDeviceCollection(IVideoDeviceCollection * rawCollection):raw(rawCollection) { } AgoraClrLibrary::ClrVideoDeviceCollection::~ClrVideoDeviceCollection() { this->release(); this->!ClrVideoDeviceCollection(); } AgoraClrLibrary::ClrVideoDeviceCollection::!ClrVideoDeviceCollection() { } int AgoraClrLibrary::ClrVideoDeviceCollection::getCount() { return raw->getCount(); } int AgoraClrLibrary::ClrVideoDeviceCollection::getDevice(int index, String ^% deviceName, String ^% deviceId) { char deviceNameBuffer[MAX_DEVICE_ID_LENGTH] = { 0 }; char deviceIdBuffer[MAX_DEVICE_ID_LENGTH] = { 0 }; int result = raw->getDevice(index, deviceNameBuffer, deviceIdBuffer); if (result != 0) return result; deviceName = gcnew String(deviceNameBuffer), deviceId = gcnew String(deviceIdBuffer); return result; // return raw->getDevice(index, const_cast<char*>(MarshalString(deviceName).c_str()), const_cast<char*>(MarshalString(deviceId).c_str())); } int AgoraClrLibrary::ClrVideoDeviceCollection::setDevice(String ^ deviceId) { return raw->setDevice(const_cast<char*>(MarshalString(deviceId).c_str())); } void AgoraClrLibrary::ClrVideoDeviceCollection::release() { raw->release(); } AgoraClrLibrary::AgoraClrVideoDeviceManager::AgoraClrVideoDeviceManager(AgoraClr ^ engine) { this->engine = engine; } AgoraClrLibrary::ClrVideoDeviceCollection ^ AgoraClrLibrary::AgoraClrVideoDeviceManager::enumerateVideoDevices() { AVideoDeviceManager manager(engine->getEngine()); return gcnew ClrVideoDeviceCollection(manager->enumerateVideoDevices()); } int AgoraClrLibrary::AgoraClrVideoDeviceManager::setDevice(String ^ deviceId) { AVideoDeviceManager manager(engine->getEngine()); return manager->setDevice(MarshalString(deviceId).c_str()); } int AgoraClrLibrary::AgoraClrVideoDeviceManager::getDevice(String ^ deviceId) { AVideoDeviceManager manager(engine->getEngine()); return manager->getDevice(const_cast<char*>(MarshalString(deviceId).c_str())); } int AgoraClrLibrary::AgoraClrVideoDeviceManager::startDeviceTest(IntPtr hwnd) { AVideoDeviceManager manager(engine->getEngine()); return manager->startDeviceTest(hwnd.ToPointer()); } int AgoraClrLibrary::AgoraClrVideoDeviceManager::stopDeviceTest() { AVideoDeviceManager manager(engine->getEngine()); return manager->stopDeviceTest(); }
Update AgoraClrVideoDeviceManager.cpp
Update AgoraClrVideoDeviceManager.cpp 修改不能正确传出deviceId的BUG
C++
mit
horsefaced/AgoraCLI,horsefaced/AgoraCLI,horsefaced/AgoraCLI
541d2fb6328f70a5496e9efef9a2784a465917f2
Tester.hpp
Tester.hpp
#include <cstdlib> #include <iostream> #include <functional> #include <utility> #include <string> #include <vector> // This file contains an implementation for *very* simple testing framework. // Use these macros in your test functions to test for various things. // The test program will print an error message and exit if the tests fail. /** Test that boolean condition a is true */ #define TEST(a) test((a), #a, __FILE__, __LINE__); /** Test that a == b */ #define TEST_EQUALS(a, b) testEquals((a), (b), __FILE__, __LINE__); /** Test that a != b */ #define TEST_NOT_EQUALS(a, b) testNotEquals((a), (b), __FILE__, __LINE__); /** Test that a < b */ #define TEST_LESS_THAN(a, b) testLessThan((a), (b), __FILE__, __LINE__); /** Fail the test with error message msg */ #define TEST_FAIL(msg) testFail((msg), __FILE__, __LINE__); void test(bool a, const char* exp, const char* file, int line) { if (!a) { std::cout << file << ":" << line << ": TEST FAILED: " << exp << std::endl; exit(1); } } template <class C> void testEquals(C a, C b, const char* file, int line) { if (a != b) { std::cout << file << ":" << line << ": TEST FAILED: " << a << " == " << b << std::endl; exit(1); } } template <class C> void testNotEquals(C a, C b, const char* file, int line) { if (a == b) { std::cout << file << ":" << line << ": TEST FAILED: " << a << " != " << b << std::endl; exit(1); } } template <class C> void testLessThan(C a, C b, const char* file, int line) { if (a >= b) { std::cout << file << ":" << line << ": TEST FAILED: " << a << " < " << b << std::endl; exit(1); } } void testFail(const char* msg, const char* file, int line) { std::cout << file << ":" << line << ": TEST FAILED: " << msg << std::endl; exit(1); } /** * Tester is a container for tests. * Use addTest() to add new test. * Use runTests() to run all added tests. */ class Tester { public: /** * Construct a Tester. * * @param name Name for the Tester instance. Will be printed when running tests. */ Tester(const std::string& name) : name_(name), tests_() { } /** * Add test. * * @param testFunc Function containing the test. * @param testDesc Description for the test. Will be printed when running the test. */ void addTest(const std::function<void()>& testFunc, const std::string& testDesc) { tests_.push_back(std::make_pair(testFunc, testDesc)); } /** * Run all added tests. */ void runTests() const { std::cout << name_ << ": Running " << tests_.size() << " tests" << std::endl; for (auto& test : tests_) { std::cout << test.second << "... "; test.first(); std::cout << "OK!" << std::endl; } } private: std::string name_; std::vector<std::pair<std::function<void()>, std::string>> tests_; };
#ifndef TESTER_HPP #define TESTER_HPP #include <cstdlib> #include <iostream> #include <functional> #include <utility> #include <string> #include <vector> // This file contains an implementation for *very* simple testing framework. // Use these macros in your test functions to test for various things. // The test program will print an error message and exit if the tests fail. /** Test that boolean condition a is true */ #define TEST(a) test((a), #a, __FILE__, __LINE__); /** Test that a == b */ #define TEST_EQUALS(a, b) testEquals((a), (b), __FILE__, __LINE__); /** Test that a != b */ #define TEST_NOT_EQUALS(a, b) testNotEquals((a), (b), __FILE__, __LINE__); /** Test that a < b */ #define TEST_LESS_THAN(a, b) testLessThan((a), (b), __FILE__, __LINE__); /** Fail the test with error message msg */ #define TEST_FAIL(msg) testFail((msg), __FILE__, __LINE__); void test(bool a, const char* exp, const char* file, int line) { if (!a) { std::cout << file << ":" << line << ": TEST FAILED: " << exp << std::endl; exit(1); } } template <class C> void testEquals(C a, C b, const char* file, int line) { if (a != b) { std::cout << file << ":" << line << ": TEST FAILED: " << a << " == " << b << std::endl; exit(1); } } template <class C> void testNotEquals(C a, C b, const char* file, int line) { if (a == b) { std::cout << file << ":" << line << ": TEST FAILED: " << a << " != " << b << std::endl; exit(1); } } template <class C> void testLessThan(C a, C b, const char* file, int line) { if (a >= b) { std::cout << file << ":" << line << ": TEST FAILED: " << a << " < " << b << std::endl; exit(1); } } void testFail(const char* msg, const char* file, int line) { std::cout << file << ":" << line << ": TEST FAILED: " << msg << std::endl; exit(1); } /** * Tester is a container for tests. * Use addTest() to add new test. * Use runTests() to run all added tests. */ class Tester { public: /** * Construct a Tester. * * @param name Name for the Tester instance. Will be printed when running tests. */ Tester(const std::string& name) : name_(name), tests_() { } /** * Add test. * * @param testFunc Function containing the test. * @param testDesc Description for the test. Will be printed when running the test. */ void addTest(const std::function<void()>& testFunc, const std::string& testDesc) { tests_.push_back(std::make_pair(testFunc, testDesc)); } /** * Run all added tests. */ void runTests() const { std::cout << name_ << ": Running " << tests_.size() << " tests" << std::endl; for (auto& test : tests_) { std::cout << test.second << "... "; test.first(); std::cout << "OK!" << std::endl; } } private: std::string name_; std::vector<std::pair<std::function<void()>, std::string>> tests_; }; #endif
Add include guard to Tester.hpp
Add include guard to Tester.hpp
C++
mit
khuttun/PolyM
616b92ea4ebb0e8aca90c1790be53ab6b3835051
tests/dbus/test_dbus_client.cpp
tests/dbus/test_dbus_client.cpp
/* * Copyright (c) 2020, The OpenThread Authors. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the copyright holder nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include <assert.h> #include <stdio.h> #include <string.h> #include <memory> #include <dbus/dbus.h> #include "dbus/client/thread_api_dbus.hpp" #include "dbus/common/constants.hpp" using otbr::DBus::ActiveScanResult; using otbr::DBus::ClientError; using otbr::DBus::DeviceRole; using otbr::DBus::ExternalRoute; using otbr::DBus::Ip6Prefix; using otbr::DBus::LinkModeConfig; using otbr::DBus::OnMeshPrefix; using otbr::DBus::ThreadApiDBus; struct DBusConnectionDeleter { void operator()(DBusConnection *aConnection) { dbus_connection_unref(aConnection); } }; using UniqueDBusConnection = std::unique_ptr<DBusConnection, DBusConnectionDeleter>; static bool operator==(const otbr::DBus::Ip6Prefix &aLhs, const otbr::DBus::Ip6Prefix &aRhs) { bool prefixDataEquality = (aLhs.mPrefix.size() == aRhs.mPrefix.size()) && (memcmp(&aLhs.mPrefix[0], &aRhs.mPrefix[0], aLhs.mPrefix.size()) == 0); return prefixDataEquality && aLhs.mLength == aRhs.mLength; } static void CheckExternalRoute(ThreadApiDBus *aApi, const Ip6Prefix &aPrefix) { ExternalRoute route; std::vector<ExternalRoute> externalRouteTable; route.mPrefix = aPrefix; route.mStable = true; route.mPreference = 0; assert(aApi->AddExternalRoute(route) == OTBR_ERROR_NONE); assert(aApi->GetExternalRoutes(externalRouteTable) == OTBR_ERROR_NONE); assert(externalRouteTable.size() == 1); assert(externalRouteTable[0].mPrefix == aPrefix); assert(externalRouteTable[0].mPreference == 0); assert(externalRouteTable[0].mStable); assert(externalRouteTable[0].mNextHopIsThisDevice); assert(aApi->RemoveExternalRoute(aPrefix) == OTBR_ERROR_NONE); } int main() { DBusError error; UniqueDBusConnection connection; std::unique_ptr<ThreadApiDBus> api; uint64_t extpanid = 0xdead00beaf00cafe; dbus_error_init(&error); connection = UniqueDBusConnection(dbus_bus_get(DBUS_BUS_SYSTEM, &error)); VerifyOrExit(connection != nullptr); VerifyOrExit(dbus_bus_register(connection.get(), &error) == true); api = std::unique_ptr<ThreadApiDBus>(new ThreadApiDBus(connection.get())); api->AddDeviceRoleHandler( [](DeviceRole aRole) { printf("Device role changed to %d\n", static_cast<uint8_t>(aRole)); }); api->Scan([&api, extpanid](const std::vector<ActiveScanResult> &aResult) { LinkModeConfig cfg = {true, true, false, true}; for (auto &&result : aResult) { printf("%s channel %d rssi %d\n", result.mNetworkName.c_str(), result.mChannel, result.mRssi); } api->SetLinkMode(cfg); api->GetLinkMode(cfg); printf("LinkMode %d %d %d %d\n", cfg.mRxOnWhenIdle, cfg.mSecureDataRequests, cfg.mDeviceType, cfg.mNetworkData); cfg.mDeviceType = true; api->SetLinkMode(cfg); api->Attach("Test", 0x3456, extpanid, {}, {}, UINT32_MAX, [&api, extpanid](ClientError aError) { printf("Attach result %d\n", static_cast<int>(aError)); uint64_t extpanidCheck; if (aError == OTBR_ERROR_NONE) { std::string name; uint64_t extAddress; uint16_t rloc16; uint8_t routerId; std::vector<uint8_t> networkData; std::vector<uint8_t> stableNetworkData; otbr::DBus::LeaderData leaderData; uint8_t leaderWeight; int8_t rssi; int8_t txPower; std::vector<otbr::DBus::ChildInfo> childTable; std::vector<otbr::DBus::NeighborInfo> neighborTable; uint32_t partitionId; Ip6Prefix prefix; OnMeshPrefix onMeshPrefix; prefix.mPrefix = {0xfd, 0xcd, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06}; prefix.mLength = 64; onMeshPrefix.mPrefix = prefix; onMeshPrefix.mPreference = 0; onMeshPrefix.mStable = true; assert(api->GetNetworkName(name) == OTBR_ERROR_NONE); assert(api->GetExtPanId(extpanidCheck) == OTBR_ERROR_NONE); assert(api->GetRloc16(rloc16) == OTBR_ERROR_NONE); assert(api->GetExtendedAddress(extAddress) == OTBR_ERROR_NONE); assert(api->GetRouterId(routerId) == OTBR_ERROR_NONE); assert(api->GetLeaderData(leaderData) == OTBR_ERROR_NONE); assert(api->GetNetworkData(networkData) == OTBR_ERROR_NONE); assert(api->GetStableNetworkData(stableNetworkData) == OTBR_ERROR_NONE); assert(api->GetLocalLeaderWeight(leaderWeight) == OTBR_ERROR_NONE); assert(api->GetChildTable(childTable) == OTBR_ERROR_NONE); assert(api->GetNeighborTable(neighborTable) == OTBR_ERROR_NONE); assert(api->GetPartitionId(partitionId) == OTBR_ERROR_NONE); assert(api->GetInstantRssi(rssi) == OTBR_ERROR_NONE); assert(api->GetRadioTxPower(txPower) == OTBR_ERROR_NONE); CheckExternalRoute(api.get(), prefix); assert(api->AddOnMeshPrefix(onMeshPrefix) == OTBR_ERROR_NONE); assert(api->RemoveOnMeshPrefix(onMeshPrefix.mPrefix) == OTBR_ERROR_NONE); api->FactoryReset(nullptr); assert(api->GetNetworkName(name) == OTBR_ERROR_NONE); assert(rloc16 != 0); assert(extAddress != 0); assert(partitionId != 0); assert(routerId == leaderData.mLeaderRouterId); assert(!networkData.empty()); assert(childTable.empty()); assert(neighborTable.empty()); } if (aError != OTBR_ERROR_NONE || extpanidCheck != extpanid) { exit(-1); } api->Attach("Test", 0x3456, extpanid, {}, {}, UINT32_MAX, [](ClientError aErr) { exit(static_cast<uint8_t>(aErr)); }); }); }); while (true) { dbus_connection_read_write_dispatch(connection.get(), 0); } exit: dbus_error_free(&error); return 0; };
/* * Copyright (c) 2020, The OpenThread Authors. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the copyright holder nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include <assert.h> #include <stdio.h> #include <string.h> #include <memory> #include <dbus/dbus.h> #include "dbus/client/thread_api_dbus.hpp" #include "dbus/common/constants.hpp" using otbr::DBus::ActiveScanResult; using otbr::DBus::ClientError; using otbr::DBus::DeviceRole; using otbr::DBus::ExternalRoute; using otbr::DBus::Ip6Prefix; using otbr::DBus::LinkModeConfig; using otbr::DBus::OnMeshPrefix; using otbr::DBus::ThreadApiDBus; struct DBusConnectionDeleter { void operator()(DBusConnection *aConnection) { dbus_connection_unref(aConnection); } }; using UniqueDBusConnection = std::unique_ptr<DBusConnection, DBusConnectionDeleter>; static bool operator==(const otbr::DBus::Ip6Prefix &aLhs, const otbr::DBus::Ip6Prefix &aRhs) { bool prefixDataEquality = (aLhs.mPrefix.size() == aRhs.mPrefix.size()) && (memcmp(&aLhs.mPrefix[0], &aRhs.mPrefix[0], aLhs.mPrefix.size()) == 0); return prefixDataEquality && aLhs.mLength == aRhs.mLength; } static void CheckExternalRoute(ThreadApiDBus *aApi, const Ip6Prefix &aPrefix) { ExternalRoute route; std::vector<ExternalRoute> externalRouteTable; route.mPrefix = aPrefix; route.mStable = true; route.mPreference = 0; assert(aApi->AddExternalRoute(route) == OTBR_ERROR_NONE); assert(aApi->GetExternalRoutes(externalRouteTable) == OTBR_ERROR_NONE); assert(externalRouteTable.size() == 1); assert(externalRouteTable[0].mPrefix == aPrefix); assert(externalRouteTable[0].mPreference == 0); assert(externalRouteTable[0].mStable); assert(externalRouteTable[0].mNextHopIsThisDevice); assert(aApi->RemoveExternalRoute(aPrefix) == OTBR_ERROR_NONE); } int main() { DBusError error; UniqueDBusConnection connection; std::unique_ptr<ThreadApiDBus> api; uint64_t extpanid = 0xdead00beaf00cafe; dbus_error_init(&error); connection = UniqueDBusConnection(dbus_bus_get(DBUS_BUS_SYSTEM, &error)); VerifyOrExit(connection != nullptr); VerifyOrExit(dbus_bus_register(connection.get(), &error) == true); api = std::unique_ptr<ThreadApiDBus>(new ThreadApiDBus(connection.get())); api->AddDeviceRoleHandler( [](DeviceRole aRole) { printf("Device role changed to %d\n", static_cast<uint8_t>(aRole)); }); api->Scan([&api, extpanid](const std::vector<ActiveScanResult> &aResult) { LinkModeConfig cfg = {true, true, false, true}; for (auto &&result : aResult) { printf("%s channel %d rssi %d\n", result.mNetworkName.c_str(), result.mChannel, result.mRssi); } api->SetLinkMode(cfg); api->GetLinkMode(cfg); printf("LinkMode %d %d %d %d\n", cfg.mRxOnWhenIdle, cfg.mSecureDataRequests, cfg.mDeviceType, cfg.mNetworkData); cfg.mDeviceType = true; api->SetLinkMode(cfg); api->Attach("Test", 0x3456, extpanid, {}, {}, UINT32_MAX, [&api, extpanid](ClientError aError) { printf("Attach result %d\n", static_cast<int>(aError)); uint64_t extpanidCheck; if (aError == OTBR_ERROR_NONE) { std::string name; uint64_t extAddress = 0; uint16_t rloc16 = 0xffff; uint8_t routerId; std::vector<uint8_t> networkData; std::vector<uint8_t> stableNetworkData; otbr::DBus::LeaderData leaderData; uint8_t leaderWeight; int8_t rssi; int8_t txPower; std::vector<otbr::DBus::ChildInfo> childTable; std::vector<otbr::DBus::NeighborInfo> neighborTable; uint32_t partitionId; Ip6Prefix prefix; OnMeshPrefix onMeshPrefix; prefix.mPrefix = {0xfd, 0xcd, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06}; prefix.mLength = 64; onMeshPrefix.mPrefix = prefix; onMeshPrefix.mPreference = 0; onMeshPrefix.mStable = true; assert(api->GetNetworkName(name) == OTBR_ERROR_NONE); assert(api->GetExtPanId(extpanidCheck) == OTBR_ERROR_NONE); assert(api->GetRloc16(rloc16) == OTBR_ERROR_NONE); assert(api->GetExtendedAddress(extAddress) == OTBR_ERROR_NONE); assert(api->GetRouterId(routerId) == OTBR_ERROR_NONE); assert(api->GetLeaderData(leaderData) == OTBR_ERROR_NONE); assert(api->GetNetworkData(networkData) == OTBR_ERROR_NONE); assert(api->GetStableNetworkData(stableNetworkData) == OTBR_ERROR_NONE); assert(api->GetLocalLeaderWeight(leaderWeight) == OTBR_ERROR_NONE); assert(api->GetChildTable(childTable) == OTBR_ERROR_NONE); assert(api->GetNeighborTable(neighborTable) == OTBR_ERROR_NONE); assert(api->GetPartitionId(partitionId) == OTBR_ERROR_NONE); assert(api->GetInstantRssi(rssi) == OTBR_ERROR_NONE); assert(api->GetRadioTxPower(txPower) == OTBR_ERROR_NONE); CheckExternalRoute(api.get(), prefix); assert(api->AddOnMeshPrefix(onMeshPrefix) == OTBR_ERROR_NONE); assert(api->RemoveOnMeshPrefix(onMeshPrefix.mPrefix) == OTBR_ERROR_NONE); api->FactoryReset(nullptr); assert(api->GetNetworkName(name) == OTBR_ERROR_NONE); assert(rloc16 != 0xffff); assert(extAddress != 0); assert(routerId == leaderData.mLeaderRouterId); assert(!networkData.empty()); assert(childTable.empty()); assert(neighborTable.empty()); } if (aError != OTBR_ERROR_NONE || extpanidCheck != extpanid) { exit(-1); } api->Attach("Test", 0x3456, extpanid, {}, {}, UINT32_MAX, [](ClientError aErr) { exit(static_cast<uint8_t>(aErr)); }); }); }); while (true) { dbus_connection_read_write_dispatch(connection.get(), 0); } exit: dbus_error_free(&error); return 0; };
fix dbus client checks (#412)
[test] fix dbus client checks (#412) The rloc16 value can be zero, use 0xffff for an invalid value instead. The parition id a radmon value so it shall not be checked.
C++
bsd-3-clause
openthread/ot-br-posix,jwhui/borderrouter,jwhui/borderrouter,openthread/ot-br-posix,openthread/ot-br-posix,openthread/borderrouter,jwhui/borderrouter,bukepo/borderrouter,bukepo/borderrouter,jwhui/borderrouter,bukepo/borderrouter,openthread/borderrouter,openthread/ot-br-posix,jwhui/borderrouter,openthread/ot-br-posix,openthread/ot-br-posix,openthread/borderrouter,bukepo/borderrouter,openthread/borderrouter,openthread/borderrouter,openthread/borderrouter,bukepo/borderrouter
29dc04cf5eb7bb120695e526072517561b86f34c
src/components/media_manager/src/media_manager_impl.cc
src/components/media_manager/src/media_manager_impl.cc
/* * Copyright (c) 2014, Ford Motor Company * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following * disclaimer in the documentation and/or other materials provided with the * distribution. * * Neither the name of the Ford Motor Company nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include "config_profile/profile.h" #include "media_manager/media_manager_impl.h" #include "media_manager/audio/from_mic_recorder_listener.h" #include "media_manager/streamer_listener.h" #include "application_manager/message_helper.h" #include "application_manager/application.h" #include "application_manager/application_manager_impl.h" #include "application_manager/application_impl.h" #include "protocol_handler/protocol_handler.h" #include "utils/file_system.h" #include "utils/logger.h" #include "utils/helpers.h" #if defined(EXTENDED_MEDIA_MODE) #include "media_manager/audio/a2dp_source_player_adapter.h" #include "media_manager/audio/from_mic_recorder_adapter.h" #endif #include "media_manager/video/socket_video_streamer_adapter.h" #include "media_manager/audio/socket_audio_streamer_adapter.h" #include "media_manager/video/pipe_video_streamer_adapter.h" #include "media_manager/audio/pipe_audio_streamer_adapter.h" #include "media_manager/video/video_stream_to_file_adapter.h" namespace media_manager { using profile::Profile; using timer::TimerThread; CREATE_LOGGERPTR_GLOBAL(logger_, "MediaManagerImpl") MediaManagerImpl::MediaManagerImpl() : protocol_handler_(NULL) , a2dp_player_(NULL) , from_mic_recorder_(NULL) { Init(); } MediaManagerImpl::~MediaManagerImpl() { if (a2dp_player_) { delete a2dp_player_; a2dp_player_ = NULL; } if (from_mic_recorder_) { delete from_mic_recorder_; from_mic_recorder_ = NULL; } } void MediaManagerImpl::Init() { using namespace protocol_handler; LOG4CXX_INFO(logger_, "MediaManagerImpl::Init()"); #if defined(EXTENDED_MEDIA_MODE) LOG4CXX_INFO(logger_, "Called Init with default configuration."); a2dp_player_ = new A2DPSourcePlayerAdapter(); from_mic_recorder_ = new FromMicRecorderAdapter(); #endif if ("socket" == profile::Profile::instance()->video_server_type()) { streamer_[ServiceType::kMobileNav] = new SocketVideoStreamerAdapter(); } else if ("pipe" == profile::Profile::instance()->video_server_type()) { streamer_[ServiceType::kMobileNav] = new PipeVideoStreamerAdapter(); } else if ("file" == profile::Profile::instance()->video_server_type()) { streamer_[ServiceType::kMobileNav] = new VideoStreamToFileAdapter( profile::Profile::instance()->video_stream_file()); } if ("socket" == profile::Profile::instance()->audio_server_type()) { streamer_[ServiceType::kAudio] = new SocketAudioStreamerAdapter(); } else if ("pipe" == profile::Profile::instance()->audio_server_type()) { streamer_[ServiceType::kAudio] = new PipeAudioStreamerAdapter(); } else if ("file" == profile::Profile::instance()->audio_server_type()) { streamer_[ServiceType::kAudio] = new VideoStreamToFileAdapter( profile::Profile::instance()->audio_stream_file()); } streamer_listener_[ServiceType::kMobileNav] = new StreamerListener(); streamer_listener_[ServiceType::kAudio] = new StreamerListener(); if (streamer_[ServiceType::kMobileNav]) { streamer_[ServiceType::kMobileNav]->AddListener( streamer_listener_[ServiceType::kMobileNav]); } if (streamer_[ServiceType::kAudio]) { streamer_[ServiceType::kAudio]->AddListener( streamer_listener_[ServiceType::kAudio]); } } void MediaManagerImpl::PlayA2DPSource(int32_t application_key) { LOG4CXX_AUTO_TRACE(logger_); if (a2dp_player_) { a2dp_player_->StartActivity(application_key); } } void MediaManagerImpl::StopA2DPSource(int32_t application_key) { LOG4CXX_AUTO_TRACE(logger_); if (a2dp_player_) { a2dp_player_->StopActivity(application_key); } } void MediaManagerImpl::StartMicrophoneRecording( int32_t application_key, const std::string& output_file, int32_t duration) { LOG4CXX_INFO(logger_, "MediaManagerImpl::StartMicrophoneRecording to " << output_file); application_manager::ApplicationSharedPtr app = application_manager::ApplicationManagerImpl::instance()-> application(application_key); std::string file_path = profile::Profile::instance()->app_storage_folder(); file_path += "/"; file_path += output_file; from_mic_listener_ = new FromMicRecorderListener(file_path); #if defined(EXTENDED_MEDIA_MODE) if (from_mic_recorder_) { from_mic_recorder_->AddListener(from_mic_listener_); (static_cast<FromMicRecorderAdapter*>(from_mic_recorder_)) ->set_output_file(file_path); (static_cast<FromMicRecorderAdapter*>(from_mic_recorder_)) ->set_duration(duration); from_mic_recorder_->StartActivity(application_key); } #else if (file_system::FileExists(file_path)) { LOG4CXX_INFO(logger_, "File " << output_file << " exists, removing"); if (file_system::DeleteFile(file_path)) { LOG4CXX_INFO(logger_, "File " << output_file << " removed"); } else { LOG4CXX_WARN(logger_, "Could not remove file " << output_file); } } const std::string record_file_source = profile::Profile::instance()->app_resourse_folder() + "/" + profile::Profile::instance()->recording_file_source(); std::vector<uint8_t> buf; if (file_system::ReadBinaryFile(record_file_source, buf)) { if (file_system::Write(file_path, buf)) { LOG4CXX_INFO(logger_, "File " << record_file_source << " copied to " << output_file); } else { LOG4CXX_WARN(logger_, "Could not write to file " << output_file); } } else { LOG4CXX_WARN(logger_, "Could not read file " << record_file_source); } #endif from_mic_listener_->OnActivityStarted(application_key); } void MediaManagerImpl::StopMicrophoneRecording(int32_t application_key) { LOG4CXX_AUTO_TRACE(logger_); #if defined(EXTENDED_MEDIA_MODE) if (from_mic_recorder_) { from_mic_recorder_->StopActivity(application_key); } #endif if (from_mic_listener_) { from_mic_listener_->OnActivityEnded(application_key); } #if defined(EXTENDED_MEDIA_MODE) if (from_mic_recorder_) { from_mic_recorder_->RemoveListener(from_mic_listener_); } #endif } void MediaManagerImpl::StartStreaming( int32_t application_key, protocol_handler::ServiceType service_type) { LOG4CXX_AUTO_TRACE(logger_); if (streamer_[service_type]) { streamer_[service_type]->StartActivity(application_key); } if (streamer_listener_[service_type]) { streamer_listener_[service_type]->OnActivityStarted(application_key); } } void MediaManagerImpl::StopStreaming( int32_t application_key, protocol_handler::ServiceType service_type) { LOG4CXX_AUTO_TRACE(logger_); if (streamer_listener_[service_type]) { streamer_listener_[service_type]->OnActivityEnded(application_key); } if (streamer_[service_type]) { streamer_[service_type]->StopActivity(application_key); } } void MediaManagerImpl::SetProtocolHandler( protocol_handler::ProtocolHandler* protocol_handler) { protocol_handler_ = protocol_handler; } void MediaManagerImpl::OnMessageReceived( const ::protocol_handler::RawMessagePtr message) { using namespace protocol_handler; using namespace application_manager; using namespace helpers; LOG4CXX_AUTO_TRACE(logger_); const uint32_t streaming_app_id = message->connection_key(); const ServiceType service_type = message->service_type(); if (Compare<ServiceType, NEQ, ALL>( service_type, ServiceType::kMobileNav, ServiceType::kAudio)) { LOG4CXX_DEBUG(logger_, "Unsupported service type in MediaManager"); return; } ApplicationManagerImpl* app_mgr = ApplicationManagerImpl::instance(); DCHECK_OR_RETURN_VOID(app_mgr); if (!app_mgr->CanAppStream(streaming_app_id, service_type)) { app_mgr->ForbidStreaming(streaming_app_id); LOG4CXX_ERROR(logger_, "The application trying to stream when it should not."); return; } ApplicationSharedPtr app = app_mgr->application(streaming_app_id); if (app) { app->WakeUpStreaming(service_type); streamer_[service_type]->SendData(streaming_app_id, message); } } void MediaManagerImpl::OnMobileMessageSent( const ::protocol_handler::RawMessagePtr message) { } void MediaManagerImpl::FramesProcessed(int32_t application_key, int32_t frame_number) { if (protocol_handler_) { protocol_handler_->SendFramesNumber(application_key, frame_number); } } } // namespace media_manager
/* * Copyright (c) 2014, Ford Motor Company * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following * disclaimer in the documentation and/or other materials provided with the * distribution. * * Neither the name of the Ford Motor Company nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include "config_profile/profile.h" #include "media_manager/media_manager_impl.h" #include "media_manager/audio/from_mic_recorder_listener.h" #include "media_manager/streamer_listener.h" #include "application_manager/message_helper.h" #include "application_manager/application.h" #include "application_manager/application_manager_impl.h" #include "application_manager/application_impl.h" #include "protocol_handler/protocol_handler.h" #include "utils/file_system.h" #include "utils/logger.h" #include "utils/helpers.h" #if defined(EXTENDED_MEDIA_MODE) #include "media_manager/audio/a2dp_source_player_adapter.h" #include "media_manager/audio/from_mic_recorder_adapter.h" #endif #include "media_manager/video/socket_video_streamer_adapter.h" #include "media_manager/audio/socket_audio_streamer_adapter.h" #include "media_manager/video/pipe_video_streamer_adapter.h" #include "media_manager/audio/pipe_audio_streamer_adapter.h" #include "media_manager/video/video_stream_to_file_adapter.h" namespace media_manager { using profile::Profile; using timer::TimerThread; CREATE_LOGGERPTR_GLOBAL(logger_, "MediaManagerImpl") MediaManagerImpl::MediaManagerImpl() : protocol_handler_(NULL) , a2dp_player_(NULL) , from_mic_recorder_(NULL) { Init(); } MediaManagerImpl::~MediaManagerImpl() { if (a2dp_player_) { delete a2dp_player_; a2dp_player_ = NULL; } if (from_mic_recorder_) { delete from_mic_recorder_; from_mic_recorder_ = NULL; } } void MediaManagerImpl::Init() { using namespace protocol_handler; LOG4CXX_INFO(logger_, "MediaManagerImpl::Init()"); #if defined(EXTENDED_MEDIA_MODE) LOG4CXX_INFO(logger_, "Called Init with default configuration."); a2dp_player_ = new A2DPSourcePlayerAdapter(); from_mic_recorder_ = new FromMicRecorderAdapter(); #endif if ("socket" == profile::Profile::instance()->video_server_type()) { streamer_[ServiceType::kMobileNav] = new SocketVideoStreamerAdapter(); } else if ("pipe" == profile::Profile::instance()->video_server_type()) { streamer_[ServiceType::kMobileNav] = new PipeVideoStreamerAdapter(); } else if ("file" == profile::Profile::instance()->video_server_type()) { streamer_[ServiceType::kMobileNav] = new VideoStreamToFileAdapter( profile::Profile::instance()->video_stream_file()); } if ("socket" == profile::Profile::instance()->audio_server_type()) { streamer_[ServiceType::kAudio] = new SocketAudioStreamerAdapter(); } else if ("pipe" == profile::Profile::instance()->audio_server_type()) { streamer_[ServiceType::kAudio] = new PipeAudioStreamerAdapter(); } else if ("file" == profile::Profile::instance()->audio_server_type()) { streamer_[ServiceType::kAudio] = new VideoStreamToFileAdapter( profile::Profile::instance()->audio_stream_file()); } streamer_listener_[ServiceType::kMobileNav] = new StreamerListener(); streamer_listener_[ServiceType::kAudio] = new StreamerListener(); if (streamer_[ServiceType::kMobileNav]) { streamer_[ServiceType::kMobileNav]->AddListener( streamer_listener_[ServiceType::kMobileNav]); } if (streamer_[ServiceType::kAudio]) { streamer_[ServiceType::kAudio]->AddListener( streamer_listener_[ServiceType::kAudio]); } } void MediaManagerImpl::PlayA2DPSource(int32_t application_key) { LOG4CXX_AUTO_TRACE(logger_); if (a2dp_player_) { a2dp_player_->StartActivity(application_key); } } void MediaManagerImpl::StopA2DPSource(int32_t application_key) { LOG4CXX_AUTO_TRACE(logger_); if (a2dp_player_) { a2dp_player_->StopActivity(application_key); } } void MediaManagerImpl::StartMicrophoneRecording( int32_t application_key, const std::string& output_file, int32_t duration) { LOG4CXX_INFO(logger_, "MediaManagerImpl::StartMicrophoneRecording to " << output_file); application_manager::ApplicationSharedPtr app = application_manager::ApplicationManagerImpl::instance()-> application(application_key); std::string file_path = profile::Profile::instance()->app_storage_folder(); file_path += "/"; file_path += output_file; from_mic_listener_ = new FromMicRecorderListener(file_path); #if defined(EXTENDED_MEDIA_MODE) if (from_mic_recorder_) { from_mic_recorder_->AddListener(from_mic_listener_); (static_cast<FromMicRecorderAdapter*>(from_mic_recorder_)) ->set_output_file(file_path); (static_cast<FromMicRecorderAdapter*>(from_mic_recorder_)) ->set_duration(duration); from_mic_recorder_->StartActivity(application_key); } #else if (file_system::FileExists(file_path)) { LOG4CXX_INFO(logger_, "File " << output_file << " exists, removing"); if (file_system::DeleteFile(file_path)) { LOG4CXX_INFO(logger_, "File " << output_file << " removed"); } else { LOG4CXX_WARN(logger_, "Could not remove file " << output_file); } } const std::string record_file_source = profile::Profile::instance()->app_resourse_folder() + "/" + profile::Profile::instance()->recording_file_source(); std::vector<uint8_t> buf; if (file_system::ReadBinaryFile(record_file_source, buf)) { if (file_system::Write(file_path, buf)) { LOG4CXX_INFO(logger_, "File " << record_file_source << " copied to " << output_file); } else { LOG4CXX_WARN(logger_, "Could not write to file " << output_file); } } else { LOG4CXX_WARN(logger_, "Could not read file " << record_file_source); } #endif from_mic_listener_->OnActivityStarted(application_key); } void MediaManagerImpl::StopMicrophoneRecording(int32_t application_key) { LOG4CXX_AUTO_TRACE(logger_); #if defined(EXTENDED_MEDIA_MODE) if (from_mic_recorder_) { from_mic_recorder_->StopActivity(application_key); } #endif if (from_mic_listener_) { from_mic_listener_->OnActivityEnded(application_key); } #if defined(EXTENDED_MEDIA_MODE) if (from_mic_recorder_) { from_mic_recorder_->RemoveListener(from_mic_listener_); } #endif } void MediaManagerImpl::StartStreaming( int32_t application_key, protocol_handler::ServiceType service_type) { LOG4CXX_AUTO_TRACE(logger_); if (streamer_[service_type]) { streamer_[service_type]->StartActivity(application_key); } } void MediaManagerImpl::StopStreaming( int32_t application_key, protocol_handler::ServiceType service_type) { LOG4CXX_AUTO_TRACE(logger_); if (streamer_[service_type]) { streamer_[service_type]->StopActivity(application_key); } } void MediaManagerImpl::SetProtocolHandler( protocol_handler::ProtocolHandler* protocol_handler) { protocol_handler_ = protocol_handler; } void MediaManagerImpl::OnMessageReceived( const ::protocol_handler::RawMessagePtr message) { using namespace protocol_handler; using namespace application_manager; using namespace helpers; LOG4CXX_AUTO_TRACE(logger_); const uint32_t streaming_app_id = message->connection_key(); const ServiceType service_type = message->service_type(); if (Compare<ServiceType, NEQ, ALL>( service_type, ServiceType::kMobileNav, ServiceType::kAudio)) { LOG4CXX_DEBUG(logger_, "Unsupported service type in MediaManager"); return; } ApplicationManagerImpl* app_mgr = ApplicationManagerImpl::instance(); DCHECK_OR_RETURN_VOID(app_mgr); if (!app_mgr->CanAppStream(streaming_app_id, service_type)) { app_mgr->ForbidStreaming(streaming_app_id); LOG4CXX_ERROR(logger_, "The application trying to stream when it should not."); return; } ApplicationSharedPtr app = app_mgr->application(streaming_app_id); if (app) { app->WakeUpStreaming(service_type); streamer_[service_type]->SendData(streaming_app_id, message); } } void MediaManagerImpl::OnMobileMessageSent( const ::protocol_handler::RawMessagePtr message) { } void MediaManagerImpl::FramesProcessed(int32_t application_key, int32_t frame_number) { if (protocol_handler_) { protocol_handler_->SendFramesNumber(application_key, frame_number); } } } // namespace media_manager
Remove redundant calls.
Remove redundant calls.
C++
bsd-3-clause
bonewell/sdl_core,LuxoftAKutsan/sdl_core,JackLivio/sdl_core,AByzhynar/sdl_core,LuxoftAKutsan/sdl_core,JackLivio/sdl_core,smartdevice475/sdl_core,pkeb/sdl_core,LuxoftAKutsan/sdl_core,AByzhynar/sdl_core,VProdanov/sdl_core,AByzhynar/sdl_core,APCVSRepo/sdl_core,bonewell/sdl_core,LuxoftAKutsan/sdl_core,APCVSRepo/sdl_core,VProdanov/sdl_core,BrandonHe/sdl_core,VProdanov/sdl_core,BrandonHe/sdl_core,VProdanov/sdl_core,bonewell/sdl_core,pkeb/sdl_core,pkeb/sdl_core,bonewell/sdl_core,BrandonHe/sdl_core,smartdevicelink/sdl_core,smartdevice475/sdl_core,LuxoftAKutsan/sdl_core,BrandonHe/sdl_core,smartdevice475/sdl_core,smartdevice475/sdl_core,bonewell/sdl_core,VProdanov/sdl_core,BrandonHe/sdl_core,AByzhynar/sdl_core,AByzhynar/sdl_core,VProdanov/sdl_core,bonewell/sdl_core,APCVSRepo/sdl_core,pkeb/sdl_core,smartdevice475/sdl_core,smartdevicelink/sdl_core,APCVSRepo/sdl_core,BrandonHe/sdl_core,APCVSRepo/sdl_core,JackLivio/sdl_core,smartdevicelink/sdl_core,JackLivio/sdl_core,JackLivio/sdl_core,smartdevicelink/sdl_core,LuxoftAKutsan/sdl_core,pkeb/sdl_core,JackLivio/sdl_core,pkeb/sdl_core,smartdevice475/sdl_core,AByzhynar/sdl_core
a27225c8b6359d3a85fbcd1e76c3554167e124e4
src/fnord/csv/CSVInputStream.cc
src/fnord/csv/CSVInputStream.cc
/** * This file is part of the "FnordMetric" project * Copyright (c) 2014 Paul Asmuth, Google Inc. * * FnordMetric is free software: you can redistribute it and/or modify it under * the terms of the GNU General Public License v3.0. You should have received a * copy of the GNU General Public License along with this program. If not, see * <http://www.gnu.org/licenses/>. */ #include <assert.h> #include <unistd.h> #include <fcntl.h> #include "csvinputstream.h" #include "fnord/exception.h" #include "fnord/io/inputstream.h" namespace fnord { std::unique_ptr<CSVInputStream> CSVInputStream::openFile( const std::string& file_path, char column_seperator /* = ',' */, char row_seperator /* = '\n' */, char quote_char /* = '"' */) { auto file = FileInputStream::openFile(file_path); file->readByteOrderMark(); auto csv_file = new CSVInputStream( std::move(file), column_seperator, row_seperator, quote_char); return std::unique_ptr<CSVInputStream>(csv_file); } CSVInputStream::CSVInputStream( std::unique_ptr<RewindableInputStream>&& input_stream, char column_seperator /* = ',' */, char row_seperator /* = '\n' */, char quote_char /* = '"' */) : input_(std::move(input_stream)), column_seperator_(column_seperator), row_seperator_(row_seperator), quote_char_(quote_char) {} // FIXPAUL quotechar escaping... bool CSVInputStream::readNextRow(std::vector<std::string>* target) { bool eof = false; for (;;) { std::string column; char byte; bool quoted = false; for (;;) { if (!input_->readNextByte(&byte)) { eof = true; break; } if (!quoted && byte == column_seperator_) { break; } if (!quoted && byte == row_seperator_) { break; } if (byte == quote_char_) { quoted = !quoted; } column += byte; } target->emplace_back(column); if (eof || byte == row_seperator_) { break; } } return !eof; } bool CSVInputStream::skipNextRow() { std::vector<std::string> devnull; return readNextRow(&devnull); } void CSVInputStream::rewind() { input_->rewind(); } const RewindableInputStream& CSVInputStream::getInputStream() const { return *input_; } }
/** * This file is part of the "FnordMetric" project * Copyright (c) 2014 Paul Asmuth, Google Inc. * * FnordMetric is free software: you can redistribute it and/or modify it under * the terms of the GNU General Public License v3.0. You should have received a * copy of the GNU General Public License along with this program. If not, see * <http://www.gnu.org/licenses/>. */ #include <assert.h> #include <unistd.h> #include <fcntl.h> #include "csvinputstream.h" #include "fnord/exception.h" #include "fnord/io/inputstream.h" namespace fnord { std::unique_ptr<CSVInputStream> CSVInputStream::openFile( const std::string& file_path, char column_seperator /* = ',' */, char row_seperator /* = '\n' */, char quote_char /* = '"' */) { auto file = FileInputStream::openFile(file_path); file->readByteOrderMark(); auto csv_file = new CSVInputStream( std::move(file), column_seperator, row_seperator, quote_char); return std::unique_ptr<CSVInputStream>(csv_file); } CSVInputStream::CSVInputStream( std::unique_ptr<RewindableInputStream>&& input_stream, char column_seperator /* = ',' */, char row_seperator /* = '\n' */, char quote_char /* = '"' */) : input_(std::move(input_stream)), column_seperator_(column_seperator), row_seperator_(row_seperator), quote_char_(quote_char) {} // FIXPAUL quotechar escaping... bool CSVInputStream::readNextRow(std::vector<std::string>* target) { target->clear(); bool eof = false; for (;;) { std::string column; char byte; bool quoted = false; for (;;) { if (!input_->readNextByte(&byte)) { eof = true; break; } if (!quoted && byte == column_seperator_) { break; } if (!quoted && byte == row_seperator_) { break; } if (byte == quote_char_) { quoted = !quoted; } column += byte; } target->emplace_back(column); if (eof || byte == row_seperator_) { break; } } return !eof; } bool CSVInputStream::skipNextRow() { std::vector<std::string> devnull; return readNextRow(&devnull); } void CSVInputStream::rewind() { input_->rewind(); } const RewindableInputStream& CSVInputStream::getInputStream() const { return *input_; } }
clear target in readNextRow
clear target in readNextRow
C++
agpl-3.0
eventql/eventql,eventql/eventql,eventql/eventql,eventql/eventql,eventql/eventql,eventql/eventql,eventql/eventql,eventql/eventql
49c72956b06beceda573b3f6eb5d57a3b5ddb414
modules/gui/skins2/parser/xmlparser.cpp
modules/gui/skins2/parser/xmlparser.cpp
/***************************************************************************** * xmlparser.cpp ***************************************************************************** * Copyright (C) 2004 the VideoLAN team * $Id$ * * Authors: Cyril Deguet <[email protected]> * * 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; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA. *****************************************************************************/ #include "xmlparser.hpp" #include "../src/os_factory.hpp" #include <vlc_url.h> #include <sys/stat.h> XMLParser::XMLParser( intf_thread_t *pIntf, const string &rFileName ) : SkinObject( pIntf ), m_pXML( NULL ), m_pReader( NULL ), m_pStream( NULL ) { m_pXML = xml_Create( pIntf ); if( !m_pXML ) { msg_Err( getIntf(), "cannot initialize xml" ); return; } LoadCatalog(); char *psz_uri = vlc_path2uri( rFileName.c_str(), NULL ); m_pStream = stream_UrlNew( pIntf, psz_uri ); free( psz_uri ); if( !m_pStream ) { msg_Err( getIntf(), "failed to open %s for reading", rFileName.c_str() ); return; } m_pReader = xml_ReaderCreate( m_pXML, m_pStream ); if( !m_pReader ) { msg_Err( getIntf(), "failed to open %s for parsing", rFileName.c_str() ); return; } xml_ReaderUseDTD( m_pReader ); } XMLParser::~XMLParser() { if( m_pReader ) xml_ReaderDelete( m_pReader ); if( m_pXML ) xml_Delete( m_pXML ); if( m_pStream ) stream_Delete( m_pStream ); } void XMLParser::LoadCatalog() { // Get the resource path and look for the DTD OSFactory *pOSFactory = OSFactory::instance( getIntf() ); const list<string> &resPath = pOSFactory->getResourcePath(); const string &sep = pOSFactory->getDirSeparator(); list<string>::const_iterator it; struct stat statBuf; // Try to load the catalog first (needed at least on win32 where // we don't have a default catalog) for( it = resPath.begin(); it != resPath.end(); ++it ) { string catalog_path = (*it) + sep + "skin.catalog"; if( !stat( catalog_path.c_str(), &statBuf ) ) { msg_Dbg( getIntf(), "Using catalog %s", catalog_path.c_str() ); xml_CatalogLoad( m_pXML, catalog_path.c_str() ); break; } } if( it == resPath.end() ) { // Ok, try the default one xml_CatalogLoad( m_pXML, NULL ); } for( it = resPath.begin(); it != resPath.end(); ++it ) { string path = (*it) + sep + "skin.dtd"; if( !stat( path.c_str(), &statBuf ) ) { // DTD found msg_Dbg( getIntf(), "using DTD %s", path.c_str() ); // Add an entry in the default catalog xml_CatalogAdd( m_pXML, "public", "-//VideoLAN//DTD VLC Skins V" SKINS_DTD_VERSION "//EN", path.c_str() ); break; } } if( it == resPath.end() ) { msg_Err( getIntf(), "cannot find the skins DTD"); } } bool XMLParser::parse() { const char *node; int type; if( !m_pReader ) return false; m_errors = false; while( (type = xml_ReaderNextNode( m_pReader, &node )) > 0 ) { if( m_errors ) return false; switch( type ) { case XML_READER_STARTELEM: { // Read the attributes AttrList_t attributes; const char *name, *value; while( (name = xml_ReaderNextAttr( m_pReader, &value )) != NULL ) attributes[strdup(name)] = strdup(value); handleBeginElement( node, attributes ); map<const char*, const char*, ltstr> ::iterator it = attributes.begin(); while( it != attributes.end() ) { free( (char *)it->first ); free( (char *)it->second ); ++it; } break; } // End element case XML_READER_ENDELEM: { handleEndElement( node ); break; } } } return (type == 0 && !m_errors ); }
/***************************************************************************** * xmlparser.cpp ***************************************************************************** * Copyright (C) 2004 the VideoLAN team * $Id$ * * Authors: Cyril Deguet <[email protected]> * * 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; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA. *****************************************************************************/ #include "xmlparser.hpp" #include "../src/os_factory.hpp" #include <vlc_url.h> #include <sys/stat.h> #include <vlc_fs.h> XMLParser::XMLParser( intf_thread_t *pIntf, const string &rFileName ) : SkinObject( pIntf ), m_pXML( NULL ), m_pReader( NULL ), m_pStream( NULL ) { m_pXML = xml_Create( pIntf ); if( !m_pXML ) { msg_Err( getIntf(), "cannot initialize xml" ); return; } LoadCatalog(); char *psz_uri = vlc_path2uri( rFileName.c_str(), NULL ); m_pStream = stream_UrlNew( pIntf, psz_uri ); free( psz_uri ); if( !m_pStream ) { msg_Err( getIntf(), "failed to open %s for reading", rFileName.c_str() ); return; } m_pReader = xml_ReaderCreate( m_pXML, m_pStream ); if( !m_pReader ) { msg_Err( getIntf(), "failed to open %s for parsing", rFileName.c_str() ); return; } xml_ReaderUseDTD( m_pReader ); } XMLParser::~XMLParser() { if( m_pReader ) xml_ReaderDelete( m_pReader ); if( m_pXML ) xml_Delete( m_pXML ); if( m_pStream ) stream_Delete( m_pStream ); } void XMLParser::LoadCatalog() { // Get the resource path and look for the DTD OSFactory *pOSFactory = OSFactory::instance( getIntf() ); const list<string> &resPath = pOSFactory->getResourcePath(); const string &sep = pOSFactory->getDirSeparator(); list<string>::const_iterator it; struct stat statBuf; // Try to load the catalog first (needed at least on win32 where // we don't have a default catalog) for( it = resPath.begin(); it != resPath.end(); ++it ) { string catalog_path = (*it) + sep + "skin.catalog"; if( !vlc_stat( catalog_path.c_str(), &statBuf ) ) { msg_Dbg( getIntf(), "Using catalog %s", catalog_path.c_str() ); xml_CatalogLoad( m_pXML, catalog_path.c_str() ); break; } } if( it == resPath.end() ) { // Ok, try the default one xml_CatalogLoad( m_pXML, NULL ); } for( it = resPath.begin(); it != resPath.end(); ++it ) { string path = (*it) + sep + "skin.dtd"; if( !vlc_stat( path.c_str(), &statBuf ) ) { // DTD found msg_Dbg( getIntf(), "using DTD %s", path.c_str() ); // Add an entry in the default catalog xml_CatalogAdd( m_pXML, "public", "-//VideoLAN//DTD VLC Skins V" SKINS_DTD_VERSION "//EN", path.c_str() ); break; } } if( it == resPath.end() ) { msg_Err( getIntf(), "cannot find the skins DTD"); } } bool XMLParser::parse() { const char *node; int type; if( !m_pReader ) return false; m_errors = false; while( (type = xml_ReaderNextNode( m_pReader, &node )) > 0 ) { if( m_errors ) return false; switch( type ) { case XML_READER_STARTELEM: { // Read the attributes AttrList_t attributes; const char *name, *value; while( (name = xml_ReaderNextAttr( m_pReader, &value )) != NULL ) attributes[strdup(name)] = strdup(value); handleBeginElement( node, attributes ); map<const char*, const char*, ltstr> ::iterator it = attributes.begin(); while( it != attributes.end() ) { free( (char *)it->first ); free( (char *)it->second ); ++it; } break; } // End element case XML_READER_ENDELEM: { handleEndElement( node ); break; } } } return (type == 0 && !m_errors ); }
replace all stat() with vlc_stat()
skins2: replace all stat() with vlc_stat()
C++
lgpl-2.1
vlc-mirror/vlc,shyamalschandra/vlc,krichter722/vlc,xkfz007/vlc,vlc-mirror/vlc,xkfz007/vlc,krichter722/vlc,krichter722/vlc,shyamalschandra/vlc,vlc-mirror/vlc,shyamalschandra/vlc,xkfz007/vlc,vlc-mirror/vlc,vlc-mirror/vlc,shyamalschandra/vlc,vlc-mirror/vlc,shyamalschandra/vlc,shyamalschandra/vlc,krichter722/vlc,krichter722/vlc,krichter722/vlc,xkfz007/vlc,krichter722/vlc,vlc-mirror/vlc,xkfz007/vlc,xkfz007/vlc,xkfz007/vlc,shyamalschandra/vlc
c8bf7969ec17f639f9fac3949e56d5eac3b14719
modules/skottie/src/effects/Effects.cpp
modules/skottie/src/effects/Effects.cpp
/* * Copyright 2019 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "modules/skottie/src/effects/Effects.h" #include "modules/skottie/src/SkottieJson.h" #include "modules/sksg/include/SkSGRenderEffect.h" #include "src/utils/SkJSON.h" #include <algorithm> #include <iterator> namespace skottie { namespace internal { EffectBuilder::EffectBuilder(const AnimationBuilder* abuilder, const SkSize& layer_size) : fBuilder(abuilder) , fLayerSize(layer_size) {} EffectBuilder::EffectBuilderT EffectBuilder::findBuilder(const skjson::ObjectValue& jeffect) const { static constexpr struct BuilderInfo { const char* fName; EffectBuilderT fBuilder; } gBuilderInfo[] = { { "ADBE Drop Shadow" , &EffectBuilder::attachDropShadowEffect }, { "ADBE Easy Levels2" , &EffectBuilder::attachLevelsEffect }, { "ADBE Fill" , &EffectBuilder::attachFillEffect }, { "ADBE Gaussian Blur 2", &EffectBuilder::attachGaussianBlurEffect }, { "ADBE Geometry2" , &EffectBuilder::attachTransformEffect }, { "ADBE HUE SATURATION" , &EffectBuilder::attachHueSaturationEffect }, { "ADBE Invert" , &EffectBuilder::attachInvertEffect }, { "ADBE Linear Wipe" , &EffectBuilder::attachLinearWipeEffect }, { "ADBE Radial Wipe" , &EffectBuilder::attachRadialWipeEffect }, { "ADBE Ramp" , &EffectBuilder::attachGradientEffect }, { "ADBE Shift Channels" , &EffectBuilder::attachShiftChannelsEffect }, { "ADBE Tile" , &EffectBuilder::attachMotionTileEffect }, { "ADBE Tint" , &EffectBuilder::attachTintEffect }, { "ADBE Tritone" , &EffectBuilder::attachTritoneEffect }, { "ADBE Venetian Blinds", &EffectBuilder::attachVenetianBlindsEffect }, }; const skjson::StringValue* mn = jeffect["mn"]; if (mn) { const BuilderInfo key { mn->begin(), nullptr }; const auto* binfo = std::lower_bound(std::begin(gBuilderInfo), std::end (gBuilderInfo), key, [](const BuilderInfo& a, const BuilderInfo& b) { return strcmp(a.fName, b.fName) < 0; }); if (binfo != std::end(gBuilderInfo) && !strcmp(binfo->fName, key.fName)) { return binfo->fBuilder; } } // Some legacy clients rely solely on the 'ty' field and generate (non-BM) JSON // without a valid 'mn' string. TODO: we should update them and remove this fallback. enum : int32_t { kTint_Effect = 20, kFill_Effect = 21, kTritone_Effect = 23, kDropShadow_Effect = 25, kRadialWipe_Effect = 26, kGaussianBlur_Effect = 29, }; switch (ParseDefault<int>(jeffect["ty"], -1)) { case kTint_Effect: return &EffectBuilder::attachTintEffect; case kFill_Effect: return &EffectBuilder::attachFillEffect; case kTritone_Effect: return &EffectBuilder::attachTritoneEffect; case kDropShadow_Effect: return &EffectBuilder::attachDropShadowEffect; case kRadialWipe_Effect: return &EffectBuilder::attachRadialWipeEffect; case kGaussianBlur_Effect: return &EffectBuilder::attachGaussianBlurEffect; default: break; } #ifdef SKOTTIE_LEGACY_EFFECT_LOGFMT fBuilder->log(Logger::Level::kWarning, nullptr, "Unsupported layer effect type: %d.", ParseDefault<int>(jeffect["ty"], -1)); #else fBuilder->log(Logger::Level::kWarning, &jeffect, "Unsupported layer effect: %s", mn ? mn->begin() : "(unknown)"); #endif return nullptr; } sk_sp<sksg::RenderNode> EffectBuilder::attachEffects(const skjson::ArrayValue& jeffects, sk_sp<sksg::RenderNode> layer) const { if (!layer) { return nullptr; } for (const skjson::ObjectValue* jeffect : jeffects) { if (!jeffect) { continue; } const auto builder = this->findBuilder(*jeffect); const skjson::ArrayValue* jprops = (*jeffect)["ef"]; if (!builder || !jprops) { continue; } const AnimationBuilder::AutoPropertyTracker apt(fBuilder, *jeffect); layer = (this->*builder)(*jprops, std::move(layer)); if (!layer) { fBuilder->log(Logger::Level::kError, jeffect, "Invalid layer effect."); return nullptr; } } return layer; } const skjson::Value& EffectBuilder::GetPropValue(const skjson::ArrayValue& jprops, size_t prop_index) { static skjson::NullValue kNull; if (prop_index >= jprops.size()) { return kNull; } const skjson::ObjectValue* jprop = jprops[prop_index]; return jprop ? (*jprop)["v"] : kNull; } MaskFilterEffectBase::MaskFilterEffectBase(sk_sp<sksg::RenderNode> child, const SkSize& ls) : fMaskNode(sksg::MaskFilter::Make(nullptr)) , fMaskEffectNode(sksg::MaskFilterEffect::Make(std::move(child), fMaskNode)) , fLayerSize(ls) {} MaskFilterEffectBase::~MaskFilterEffectBase() = default; void MaskFilterEffectBase::apply() const { const auto minfo = this->onMakeMask(); fMaskEffectNode->setVisible(minfo.fVisible); fMaskNode->setMaskFilter(std::move(minfo.fMask)); } } // namespace internal } // namespace skottie
/* * Copyright 2019 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "modules/skottie/src/effects/Effects.h" #include "modules/skottie/src/SkottieJson.h" #include "modules/sksg/include/SkSGRenderEffect.h" #include "src/utils/SkJSON.h" #include <algorithm> #include <iterator> namespace skottie { namespace internal { EffectBuilder::EffectBuilder(const AnimationBuilder* abuilder, const SkSize& layer_size) : fBuilder(abuilder) , fLayerSize(layer_size) {} EffectBuilder::EffectBuilderT EffectBuilder::findBuilder(const skjson::ObjectValue& jeffect) const { static constexpr struct BuilderInfo { const char* fName; EffectBuilderT fBuilder; } gBuilderInfo[] = { { "ADBE Drop Shadow" , &EffectBuilder::attachDropShadowEffect }, { "ADBE Easy Levels2" , &EffectBuilder::attachLevelsEffect }, { "ADBE Fill" , &EffectBuilder::attachFillEffect }, { "ADBE Gaussian Blur 2", &EffectBuilder::attachGaussianBlurEffect }, { "ADBE Geometry2" , &EffectBuilder::attachTransformEffect }, { "ADBE HUE SATURATION" , &EffectBuilder::attachHueSaturationEffect }, { "ADBE Invert" , &EffectBuilder::attachInvertEffect }, { "ADBE Linear Wipe" , &EffectBuilder::attachLinearWipeEffect }, { "ADBE Radial Wipe" , &EffectBuilder::attachRadialWipeEffect }, { "ADBE Ramp" , &EffectBuilder::attachGradientEffect }, { "ADBE Shift Channels" , &EffectBuilder::attachShiftChannelsEffect }, { "ADBE Tile" , &EffectBuilder::attachMotionTileEffect }, { "ADBE Tint" , &EffectBuilder::attachTintEffect }, { "ADBE Tritone" , &EffectBuilder::attachTritoneEffect }, { "ADBE Venetian Blinds", &EffectBuilder::attachVenetianBlindsEffect }, }; const skjson::StringValue* mn = jeffect["mn"]; if (mn) { const BuilderInfo key { mn->begin(), nullptr }; const auto* binfo = std::lower_bound(std::begin(gBuilderInfo), std::end (gBuilderInfo), key, [](const BuilderInfo& a, const BuilderInfo& b) { return strcmp(a.fName, b.fName) < 0; }); if (binfo != std::end(gBuilderInfo) && !strcmp(binfo->fName, key.fName)) { return binfo->fBuilder; } } // Some legacy clients rely solely on the 'ty' field and generate (non-BM) JSON // without a valid 'mn' string. TODO: we should update them and remove this fallback. enum : int32_t { kTint_Effect = 20, kFill_Effect = 21, kTritone_Effect = 23, kDropShadow_Effect = 25, kRadialWipe_Effect = 26, kGaussianBlur_Effect = 29, }; switch (ParseDefault<int>(jeffect["ty"], -1)) { case kTint_Effect: return &EffectBuilder::attachTintEffect; case kFill_Effect: return &EffectBuilder::attachFillEffect; case kTritone_Effect: return &EffectBuilder::attachTritoneEffect; case kDropShadow_Effect: return &EffectBuilder::attachDropShadowEffect; case kRadialWipe_Effect: return &EffectBuilder::attachRadialWipeEffect; case kGaussianBlur_Effect: return &EffectBuilder::attachGaussianBlurEffect; default: break; } fBuilder->log(Logger::Level::kWarning, &jeffect, "Unsupported layer effect: %s", mn ? mn->begin() : "(unknown)"); return nullptr; } sk_sp<sksg::RenderNode> EffectBuilder::attachEffects(const skjson::ArrayValue& jeffects, sk_sp<sksg::RenderNode> layer) const { if (!layer) { return nullptr; } for (const skjson::ObjectValue* jeffect : jeffects) { if (!jeffect) { continue; } const auto builder = this->findBuilder(*jeffect); const skjson::ArrayValue* jprops = (*jeffect)["ef"]; if (!builder || !jprops) { continue; } const AnimationBuilder::AutoPropertyTracker apt(fBuilder, *jeffect); layer = (this->*builder)(*jprops, std::move(layer)); if (!layer) { fBuilder->log(Logger::Level::kError, jeffect, "Invalid layer effect."); return nullptr; } } return layer; } const skjson::Value& EffectBuilder::GetPropValue(const skjson::ArrayValue& jprops, size_t prop_index) { static skjson::NullValue kNull; if (prop_index >= jprops.size()) { return kNull; } const skjson::ObjectValue* jprop = jprops[prop_index]; return jprop ? (*jprop)["v"] : kNull; } MaskFilterEffectBase::MaskFilterEffectBase(sk_sp<sksg::RenderNode> child, const SkSize& ls) : fMaskNode(sksg::MaskFilter::Make(nullptr)) , fMaskEffectNode(sksg::MaskFilterEffect::Make(std::move(child), fMaskNode)) , fLayerSize(ls) {} MaskFilterEffectBase::~MaskFilterEffectBase() = default; void MaskFilterEffectBase::apply() const { const auto minfo = this->onMakeMask(); fMaskEffectNode->setVisible(minfo.fVisible); fMaskNode->setMaskFilter(std::move(minfo.fMask)); } } // namespace internal } // namespace skottie
Drop legacy effect logging
[skottie] Drop legacy effect logging All clients have been updated TBR= Change-Id: I29e89d43606945f13e9933d34218b61be71db63d Reviewed-on: https://skia-review.googlesource.com/c/skia/+/261279 Reviewed-by: Florin Malita <[email protected]> Commit-Queue: Florin Malita <[email protected]>
C++
bsd-3-clause
aosp-mirror/platform_external_skia,HalCanary/skia-hc,google/skia,google/skia,HalCanary/skia-hc,HalCanary/skia-hc,google/skia,HalCanary/skia-hc,aosp-mirror/platform_external_skia,HalCanary/skia-hc,HalCanary/skia-hc,HalCanary/skia-hc,google/skia,HalCanary/skia-hc,aosp-mirror/platform_external_skia,aosp-mirror/platform_external_skia,HalCanary/skia-hc,google/skia,aosp-mirror/platform_external_skia,google/skia,aosp-mirror/platform_external_skia,HalCanary/skia-hc,aosp-mirror/platform_external_skia,aosp-mirror/platform_external_skia,aosp-mirror/platform_external_skia,google/skia,google/skia,aosp-mirror/platform_external_skia,google/skia,google/skia
6b94275d10a806a838625fcd51b8794e6aa65c50
kmail/headerstrategy.cpp
kmail/headerstrategy.cpp
/* -*- c++ -*- headerstrategy.cpp KMail, the KDE mail client. Copyright (c) 2003 Marc Mutz <[email protected]> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License, version 2.0, as published by the Free Software Foundation. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, US */ #include "headerstrategy.h" #include "kmkernel.h" #include <kdebug.h> #include <kconfig.h> #include <qstringlist.h> #include <qstring.h> namespace KMail { // // Header table: // be sure to keep numFooHeaders and the content of headerTable in sync! // static const char * headerTable[] = { "subject", "from", "date", // brief "to", "cc", "bcc", "organisation", "organization", // standard "reply-to" // rich }; static const int numBriefHeaders = 3; static const int numRichHeaders = sizeof headerTable / sizeof *headerTable; static const int numStandardHeaders = numRichHeaders - 1; // // Convenience function // static QStringList stringList( const char * headers[], int numHeaders ) { QStringList sl; for ( int i = 0 ; i < numHeaders ; ++i ) sl.push_back( headers[i] ); return sl; } // // AllHeaderStrategy: // show everything // class AllHeaderStrategy : public HeaderStrategy { friend class HeaderStrategy; protected: AllHeaderStrategy() : HeaderStrategy() {} virtual ~AllHeaderStrategy() {} public: const char * name() const { return "all"; } const HeaderStrategy * next() const { return rich(); } const HeaderStrategy * prev() const { return custom(); } DefaultPolicy defaultPolicy() const { return Display; } bool showHeader( const QString & ) const { return true; // more efficient than default impl } }; // // RichHeaderStrategy: // Date, Subject, From, To, CC, ### what exactly? // class RichHeaderStrategy : public HeaderStrategy { friend class HeaderStrategy; protected: RichHeaderStrategy() : HeaderStrategy(), mHeadersToDisplay( stringList( headerTable, numRichHeaders ) ) {} virtual ~RichHeaderStrategy() {} public: const char * name() const { return "rich"; } const HeaderStrategy * next() const { return standard(); } const HeaderStrategy * prev() const { return all(); } QStringList headersToDisplay() const { return mHeadersToDisplay; } DefaultPolicy defaultPolicy() const { return Hide; } private: const QStringList mHeadersToDisplay; }; // // StandardHeaderStrategy: // BCC, CC, Date, From, Subject, To // class StandardHeaderStrategy : public HeaderStrategy { friend class HeaderStrategy; protected: StandardHeaderStrategy() : HeaderStrategy(), mHeadersToDisplay( stringList( headerTable, numStandardHeaders) ) {} virtual ~StandardHeaderStrategy() {} public: const char * name() const { return "standard"; } const HeaderStrategy * next() const { return brief(); } const HeaderStrategy * prev() const { return rich(); } QStringList headersToDisplay() const { return mHeadersToDisplay; } DefaultPolicy defaultPolicy() const { return Hide; } private: const QStringList mHeadersToDisplay; }; // // BriefHeaderStrategy // From, Subject, Date // class BriefHeaderStrategy : public HeaderStrategy { friend class HeaderStrategy; protected: BriefHeaderStrategy() : HeaderStrategy(), mHeadersToDisplay( stringList( headerTable, numBriefHeaders ) ) {} virtual ~BriefHeaderStrategy() {} public: const char * name() const { return "brief"; } const HeaderStrategy * next() const { return custom(); } const HeaderStrategy * prev() const { return standard(); } QStringList headersToDisplay() const { return mHeadersToDisplay; } DefaultPolicy defaultPolicy() const { return Hide; } private: const QStringList mHeadersToDisplay; }; // // CustomHeaderStrategy // Determined by user // class CustomHeaderStrategy : public HeaderStrategy { friend class HeaderStrategy; protected: CustomHeaderStrategy(); virtual ~CustomHeaderStrategy() {} public: const char * name() const { return "custom"; } const HeaderStrategy * next() const { return all(); } const HeaderStrategy * prev() const { return brief(); } QStringList headersToDisplay() const { return mHeadersToDisplay; } QStringList headersToHide() const { return mHeadersToHide; } DefaultPolicy defaultPolicy() const { return mDefaultPolicy; } private: QStringList mHeadersToDisplay; QStringList mHeadersToHide; DefaultPolicy mDefaultPolicy; }; CustomHeaderStrategy::CustomHeaderStrategy() : HeaderStrategy() { KConfigGroup customHeader( KMKernel::config(), "Custom Headers" ); if ( customHeader.hasKey( "headers to display" ) ) { mHeadersToDisplay = customHeader.readListEntry( "headers to display" ); for ( QStringList::iterator it = mHeadersToDisplay.begin() ; it != mHeadersToDisplay.end() ; ++ it ) *it = (*it).lower(); } else mHeadersToDisplay = stringList( headerTable, numStandardHeaders ); if ( customHeader.hasKey( "headers to hide" ) ) { mHeadersToHide = customHeader.readListEntry( "headers to hide" ); for ( QStringList::iterator it = mHeadersToHide.begin() ; it != mHeadersToHide.end() ; ++ it ) *it = (*it).lower(); } mDefaultPolicy = customHeader.readEntry( "default policy", "hide" ) == "display" ? Display : Hide ; } // // HeaderStrategy abstract base: // HeaderStrategy::HeaderStrategy() { } HeaderStrategy::~HeaderStrategy() { } QStringList HeaderStrategy::headersToDisplay() const { return QStringList(); } QStringList HeaderStrategy::headersToHide() const { return QStringList(); } bool HeaderStrategy::showHeader( const QString & header ) const { if ( headersToDisplay().contains( header.lower() ) ) return true; if ( headersToHide().contains( header.lower() ) ) return false; return defaultPolicy() == Display; } const HeaderStrategy * HeaderStrategy::create( Type type ) { switch ( type ) { case All: return all(); case Rich: return rich(); case Standard: return standard(); case Brief: return brief(); case Custom: return custom(); } kdFatal( 5006 ) << "HeaderStrategy::create(): Unknown header strategy ( type == " << (int)type << " ) requested!" << endl; return 0; // make compiler happy } const HeaderStrategy * HeaderStrategy::create( const QString & type ) { QString lowerType = type.lower(); if ( lowerType == "all" ) return all(); if ( lowerType == "rich" ) return HeaderStrategy::rich(); //if ( lowerType == "standard" ) return standard(); // not needed, see below if ( lowerType == "brief" ) return brief(); if ( lowerType == "custom" ) return custom(); // don't kdFatal here, b/c the strings are user-provided // (KConfig), so fail gracefully to the default: return standard(); } static const HeaderStrategy * allStrategy = 0; static const HeaderStrategy * richStrategy = 0; static const HeaderStrategy * standardStrategy = 0; static const HeaderStrategy * briefStrategy = 0; static const HeaderStrategy * customStrategy = 0; const HeaderStrategy * HeaderStrategy::all() { if ( !allStrategy ) allStrategy = new AllHeaderStrategy(); return allStrategy; } const HeaderStrategy * HeaderStrategy::rich() { if ( !richStrategy ) richStrategy = new RichHeaderStrategy(); return richStrategy; } const HeaderStrategy * HeaderStrategy::standard() { if ( !standardStrategy ) standardStrategy = new StandardHeaderStrategy(); return standardStrategy; } const HeaderStrategy * HeaderStrategy::brief() { if ( !briefStrategy ) briefStrategy = new BriefHeaderStrategy(); return briefStrategy; } const HeaderStrategy * HeaderStrategy::custom() { if ( !customStrategy ) customStrategy = new CustomHeaderStrategy(); return customStrategy; } }; // namespace KMail
/* -*- c++ -*- headerstrategy.cpp KMail, the KDE mail client. Copyright (c) 2003 Marc Mutz <[email protected]> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License, version 2.0, as published by the Free Software Foundation. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, US */ #include "headerstrategy.h" #include "kmkernel.h" #include <kdebug.h> #include <kconfig.h> #include <qstringlist.h> #include <qstring.h> namespace KMail { // // Header table: // be sure to keep numFooHeaders and the content of headerTable in sync! // static const char * headerTable[] = { "date", // brief only "subject", "from", // brief "to", "cc", "bcc", // standard "organisation", "organization", "reply-to", "date" // rich }; static const char ** briefHeaders = &headerTable[0]; static const int numBriefHeaders = 3; static const char ** richHeaders = &headerTable[1]; static const int numRichHeaders = sizeof headerTable / sizeof *headerTable - 1; static const char ** standardHeaders = richHeaders; static const int numStandardHeaders = numRichHeaders - 4; // // Convenience function // static QStringList stringList( const char * headers[], int numHeaders ) { QStringList sl; for ( int i = 0 ; i < numHeaders ; ++i ) sl.push_back( headers[i] ); return sl; } // // AllHeaderStrategy: // show everything // class AllHeaderStrategy : public HeaderStrategy { friend class HeaderStrategy; protected: AllHeaderStrategy() : HeaderStrategy() {} virtual ~AllHeaderStrategy() {} public: const char * name() const { return "all"; } const HeaderStrategy * next() const { return rich(); } const HeaderStrategy * prev() const { return custom(); } DefaultPolicy defaultPolicy() const { return Display; } bool showHeader( const QString & ) const { return true; // more efficient than default impl } }; // // RichHeaderStrategy: // Date, Subject, From, To, CC, ### what exactly? // class RichHeaderStrategy : public HeaderStrategy { friend class HeaderStrategy; protected: RichHeaderStrategy() : HeaderStrategy(), mHeadersToDisplay( stringList( richHeaders, numRichHeaders ) ) {} virtual ~RichHeaderStrategy() {} public: const char * name() const { return "rich"; } const HeaderStrategy * next() const { return standard(); } const HeaderStrategy * prev() const { return all(); } QStringList headersToDisplay() const { return mHeadersToDisplay; } DefaultPolicy defaultPolicy() const { return Hide; } private: const QStringList mHeadersToDisplay; }; // // StandardHeaderStrategy: // BCC, CC, Date, From, Subject, To // class StandardHeaderStrategy : public HeaderStrategy { friend class HeaderStrategy; protected: StandardHeaderStrategy() : HeaderStrategy(), mHeadersToDisplay( stringList( standardHeaders, numStandardHeaders) ) {} virtual ~StandardHeaderStrategy() {} public: const char * name() const { return "standard"; } const HeaderStrategy * next() const { return brief(); } const HeaderStrategy * prev() const { return rich(); } QStringList headersToDisplay() const { return mHeadersToDisplay; } DefaultPolicy defaultPolicy() const { return Hide; } private: const QStringList mHeadersToDisplay; }; // // BriefHeaderStrategy // From, Subject, Date // class BriefHeaderStrategy : public HeaderStrategy { friend class HeaderStrategy; protected: BriefHeaderStrategy() : HeaderStrategy(), mHeadersToDisplay( stringList( briefHeaders, numBriefHeaders ) ) {} virtual ~BriefHeaderStrategy() {} public: const char * name() const { return "brief"; } const HeaderStrategy * next() const { return custom(); } const HeaderStrategy * prev() const { return standard(); } QStringList headersToDisplay() const { return mHeadersToDisplay; } DefaultPolicy defaultPolicy() const { return Hide; } private: const QStringList mHeadersToDisplay; }; // // CustomHeaderStrategy // Determined by user // class CustomHeaderStrategy : public HeaderStrategy { friend class HeaderStrategy; protected: CustomHeaderStrategy(); virtual ~CustomHeaderStrategy() {} public: const char * name() const { return "custom"; } const HeaderStrategy * next() const { return all(); } const HeaderStrategy * prev() const { return brief(); } QStringList headersToDisplay() const { return mHeadersToDisplay; } QStringList headersToHide() const { return mHeadersToHide; } DefaultPolicy defaultPolicy() const { return mDefaultPolicy; } private: QStringList mHeadersToDisplay; QStringList mHeadersToHide; DefaultPolicy mDefaultPolicy; }; CustomHeaderStrategy::CustomHeaderStrategy() : HeaderStrategy() { KConfigGroup customHeader( KMKernel::config(), "Custom Headers" ); if ( customHeader.hasKey( "headers to display" ) ) { mHeadersToDisplay = customHeader.readListEntry( "headers to display" ); for ( QStringList::iterator it = mHeadersToDisplay.begin() ; it != mHeadersToDisplay.end() ; ++ it ) *it = (*it).lower(); } else mHeadersToDisplay = stringList( standardHeaders, numStandardHeaders ); if ( customHeader.hasKey( "headers to hide" ) ) { mHeadersToHide = customHeader.readListEntry( "headers to hide" ); for ( QStringList::iterator it = mHeadersToHide.begin() ; it != mHeadersToHide.end() ; ++ it ) *it = (*it).lower(); } mDefaultPolicy = customHeader.readEntry( "default policy", "hide" ) == "display" ? Display : Hide ; } // // HeaderStrategy abstract base: // HeaderStrategy::HeaderStrategy() { } HeaderStrategy::~HeaderStrategy() { } QStringList HeaderStrategy::headersToDisplay() const { return QStringList(); } QStringList HeaderStrategy::headersToHide() const { return QStringList(); } bool HeaderStrategy::showHeader( const QString & header ) const { if ( headersToDisplay().contains( header.lower() ) ) return true; if ( headersToHide().contains( header.lower() ) ) return false; return defaultPolicy() == Display; } const HeaderStrategy * HeaderStrategy::create( Type type ) { switch ( type ) { case All: return all(); case Rich: return rich(); case Standard: return standard(); case Brief: return brief(); case Custom: return custom(); } kdFatal( 5006 ) << "HeaderStrategy::create(): Unknown header strategy ( type == " << (int)type << " ) requested!" << endl; return 0; // make compiler happy } const HeaderStrategy * HeaderStrategy::create( const QString & type ) { QString lowerType = type.lower(); if ( lowerType == "all" ) return all(); if ( lowerType == "rich" ) return HeaderStrategy::rich(); //if ( lowerType == "standard" ) return standard(); // not needed, see below if ( lowerType == "brief" ) return brief(); if ( lowerType == "custom" ) return custom(); // don't kdFatal here, b/c the strings are user-provided // (KConfig), so fail gracefully to the default: return standard(); } static const HeaderStrategy * allStrategy = 0; static const HeaderStrategy * richStrategy = 0; static const HeaderStrategy * standardStrategy = 0; static const HeaderStrategy * briefStrategy = 0; static const HeaderStrategy * customStrategy = 0; const HeaderStrategy * HeaderStrategy::all() { if ( !allStrategy ) allStrategy = new AllHeaderStrategy(); return allStrategy; } const HeaderStrategy * HeaderStrategy::rich() { if ( !richStrategy ) richStrategy = new RichHeaderStrategy(); return richStrategy; } const HeaderStrategy * HeaderStrategy::standard() { if ( !standardStrategy ) standardStrategy = new StandardHeaderStrategy(); return standardStrategy; } const HeaderStrategy * HeaderStrategy::brief() { if ( !briefStrategy ) briefStrategy = new BriefHeaderStrategy(); return briefStrategy; } const HeaderStrategy * HeaderStrategy::custom() { if ( !customStrategy ) customStrategy = new CustomHeaderStrategy(); return customStrategy; } }; // namespace KMail
Use the same header field sets that current KMail uses.
Use the same header field sets that current KMail uses. svn path=/trunk/kdepim/; revision=201414
C++
lgpl-2.1
lefou/kdepim-noakonadi,lefou/kdepim-noakonadi,lefou/kdepim-noakonadi,lefou/kdepim-noakonadi,lefou/kdepim-noakonadi,lefou/kdepim-noakonadi
67c3a0ef426384afc64aaad149ff03d360049cc9
kmail/messageactions.cpp
kmail/messageactions.cpp
/* Copyright (c) 2007 Volker Krause <[email protected]> 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; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "messageactions.h" #include "globalsettings.h" #include "kmfolder.h" #include "kmmessage.h" #include "kmreaderwin.h" #include <kaction.h> #include <kactionmenu.h> #include <kactioncollection.h> #include <ktoggleaction.h> #include <kdebug.h> #include <klocale.h> #include <qwidget.h> using namespace KMail; MessageActions::MessageActions( KActionCollection *ac, QWidget * parent ) : QObject( parent ), mParent( parent ), mActionCollection( ac ), mCurrentMessage( 0 ), mMessageView( 0 ) { mReplyActionMenu = new KActionMenu( KIcon("mail-reply-sender"), i18nc("Message->","&Reply"), this ); mActionCollection->addAction( "message_reply_menu", mReplyActionMenu ); connect( mReplyActionMenu, SIGNAL(activated()), this, SLOT(slotReplyToMsg()) ); mReplyAction = new KAction( KIcon("mail-reply-sender"), i18n("&Reply..."), this ); mActionCollection->addAction( "reply", mReplyAction ); mReplyAction->setShortcut(Qt::Key_R); connect( mReplyAction, SIGNAL(activated()), this, SLOT(slotReplyToMsg()) ); mReplyActionMenu->addAction( mReplyAction ); mReplyAuthorAction = new KAction( KIcon("mail-reply-sender"), i18n("Reply to A&uthor..."), this ); mActionCollection->addAction( "reply_author", mReplyAuthorAction ); mReplyAuthorAction->setShortcut(Qt::SHIFT+Qt::Key_A); connect( mReplyAuthorAction, SIGNAL(activated()), this, SLOT(slotReplyAuthorToMsg()) ); mReplyActionMenu->addAction( mReplyAuthorAction ); mReplyAllAction = new KAction( KIcon("mail-reply-all"), i18n("Reply to &All..."), this ); mActionCollection->addAction( "reply_all", mReplyAllAction ); mReplyAllAction->setShortcut( Qt::Key_A ); connect( mReplyAllAction, SIGNAL(activated()), this, SLOT(slotReplyAllToMsg()) ); mReplyActionMenu->addAction( mReplyAllAction ); mReplyListAction = new KAction( KIcon("mail-reply-list"), i18n("Reply to Mailing-&List..."), this ); mActionCollection->addAction( "reply_list", mReplyListAction ); mReplyListAction->setShortcut( Qt::Key_L ); connect( mReplyListAction, SIGNAL(activated()), this, SLOT(slotReplyListToMsg()) ); mReplyActionMenu->addAction( mReplyListAction ); mNoQuoteReplyAction = new KAction( i18n("Reply Without &Quote..."), this ); mActionCollection->addAction( "noquotereply", mNoQuoteReplyAction ); mNoQuoteReplyAction->setShortcut( Qt::SHIFT+Qt::Key_R ); connect( mNoQuoteReplyAction, SIGNAL(activated()), this, SLOT(slotNoQuoteReplyToMsg()) ); mCreateTodoAction = new KAction( KIcon("view-pim-tasks"), i18n("Create Task/Reminder..."), this ); mCreateTodoAction->setIconText( i18n( "Create Task" ) ); mActionCollection->addAction( "create_todo", mCreateTodoAction ); connect( mCreateTodoAction, SIGNAL(activated()), this, SLOT(slotCreateTodo()) ); mStatusMenu = new KActionMenu ( i18n( "Mar&k Message" ), this ); mActionCollection->addAction( "set_status", mStatusMenu ); KAction *action; action = new KAction( KIcon("mail-mark-read"), i18n("Mark Message as &Read"), this ); action->setToolTip( i18n("Mark selected messages as read") ); connect( action, SIGNAL(activated()), this, SLOT(slotSetMsgStatusRead()) ); mActionCollection->addAction( "status_read", action ); mStatusMenu->addAction( action ); action = new KAction( KIcon("mail-mark-unread-new"), i18n("Mark Message as &New"), this ); action->setToolTip( i18n("Mark selected messages as new") ); connect( action, SIGNAL(activated()), this, SLOT(slotSetMsgStatusNew()) ); mActionCollection->addAction( "status_new" , action ); mStatusMenu->addAction( action ); action = new KAction( KIcon("mail-mark-unread"), i18n("Mark Message as &Unread"), this ); action->setToolTip( i18n("Mark selected messages as unread") ); connect( action, SIGNAL(activated()), this, SLOT(slotSetMsgStatusUnread()) ); mActionCollection->addAction( "status_unread", action ); mStatusMenu->addAction( action ); mStatusMenu->addSeparator(); mToggleFlagAction = new KToggleAction( KIcon("mail-mark-important"), i18n("Mark Message as &Important"), this ); connect( mToggleFlagAction, SIGNAL(activated()), this, SLOT(slotSetMsgStatusFlag()) ); mToggleFlagAction->setCheckedState( KGuiItem(i18n("Remove &Important Message Mark")) ); mActionCollection->addAction( "status_flag", mToggleFlagAction ); mStatusMenu->addAction( mToggleFlagAction ); mToggleTodoAction = new KToggleAction( KIcon("mail-mark-task"), i18n("Mark Message as &Action Item"), this ); connect( mToggleTodoAction, SIGNAL(activated()), this, SLOT(slotSetMsgStatusTodo()) ); mToggleTodoAction->setCheckedState( KGuiItem(i18n("Remove &Action Item Message Mark")) ); mActionCollection->addAction( "status_todo", mToggleTodoAction ); mStatusMenu->addAction( mToggleTodoAction ); mEditAction = new KAction( KIcon("accessories-text-editor"), i18n("&Edit Message"), this ); mActionCollection->addAction( "edit", mEditAction ); connect( mEditAction, SIGNAL(activated()), this, SLOT(editCurrentMessage()) ); mEditAction->setShortcut( Qt::Key_T ); updateActions(); } void MessageActions::setCurrentMessage(KMMessage * msg) { mCurrentMessage = msg; if ( !msg ) { mSelectedSernums.clear(); mVisibleSernums.clear(); } updateActions(); } void MessageActions::setSelectedSernums(const QList< Q_UINT32 > & sernums) { mSelectedSernums = sernums; updateActions(); } void MessageActions::setSelectedVisibleSernums(const QList< Q_UINT32 > & sernums) { mVisibleSernums = sernums; updateActions(); } void MessageActions::updateActions() { const bool singleMsg = (mCurrentMessage != 0); const bool multiVisible = mVisibleSernums.count() > 0 || mCurrentMessage; const bool flagsAvailable = GlobalSettings::self()->allowLocalFlags() || !((mCurrentMessage && mCurrentMessage->parent()) ? mCurrentMessage->parent()->isReadOnly() : true); mCreateTodoAction->setEnabled( singleMsg ); mReplyActionMenu->setEnabled( singleMsg ); mReplyAction->setEnabled( singleMsg ); mNoQuoteReplyAction->setEnabled( singleMsg ); mReplyAuthorAction->setEnabled( singleMsg ); mReplyAllAction->setEnabled( singleMsg ); mReplyListAction->setEnabled( singleMsg ); mNoQuoteReplyAction->setEnabled( singleMsg ); mStatusMenu->setEnabled( multiVisible ); mToggleFlagAction->setEnabled( flagsAvailable ); mToggleTodoAction->setEnabled( flagsAvailable ); if ( mCurrentMessage ) { mToggleTodoAction->setChecked( mCurrentMessage->status().isTodo() ); mToggleFlagAction->setChecked( mCurrentMessage->status().isImportant() ); } mEditAction->setEnabled( singleMsg ); } void MessageActions::slotCreateTodo() { if ( !mCurrentMessage ) return; KMCommand *command = new CreateTodoCommand( mParent, mCurrentMessage ); command->start(); } void MessageActions::setMessageView(KMReaderWin * msgView) { mMessageView = msgView; } void MessageActions::slotReplyToMsg() { replyCommand<KMReplyToCommand>(); } void MessageActions::slotReplyAuthorToMsg() { replyCommand<KMReplyAuthorCommand>(); } void MessageActions::slotReplyListToMsg() { replyCommand<KMReplyListCommand>(); } void MessageActions::slotReplyAllToMsg() { replyCommand<KMReplyToAllCommand>(); } void MessageActions::slotNoQuoteReplyToMsg() { if ( !mCurrentMessage ) return; KMCommand *command = new KMNoQuoteReplyToCommand( mParent, mCurrentMessage ); command->start(); } void MessageActions::slotSetMsgStatusNew() { setMessageStatus( KPIM::MessageStatus::statusNew() ); } void MessageActions::slotSetMsgStatusUnread() { setMessageStatus( KPIM::MessageStatus::statusUnread() ); } void MessageActions::slotSetMsgStatusRead() { setMessageStatus( KPIM::MessageStatus::statusRead() ); } void MessageActions::slotSetMsgStatusFlag() { setMessageStatus( KPIM::MessageStatus::statusImportant(), true ); } void MessageActions::slotSetMsgStatusTodo() { setMessageStatus( KPIM::MessageStatus::statusTodo(), true ); } void MessageActions::setMessageStatus( KPIM::MessageStatus status, bool toggle ) { QList<Q_UINT32> serNums = mVisibleSernums; if ( serNums.isEmpty() && mCurrentMessage ) serNums.append( mCurrentMessage->getMsgSerNum() ); if ( serNums.empty() ) return; KMCommand *command = new KMSetStatusCommand( status, serNums, toggle ); command->start(); } void MessageActions::editCurrentMessage() { if ( !mCurrentMessage ) return; KMCommand *command = 0; KMFolder *folder = mCurrentMessage->parent(); // edit, unlike send again, removes the message from the folder // we only want that for templates and drafts folders if ( folder && ( kmkernel->folderIsDraftOrOutbox( folder ) || kmkernel->folderIsTemplates( folder ) ) ) command = new KMEditMsgCommand( mParent, mCurrentMessage ); else command = new KMResendMessageCommand( mParent, mCurrentMessage ); command->start(); } #include "messageactions.moc"
/* Copyright (c) 2007 Volker Krause <[email protected]> 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; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "messageactions.h" #include "globalsettings.h" #include "kmfolder.h" #include "kmmessage.h" #include "kmreaderwin.h" #include <kaction.h> #include <kactionmenu.h> #include <kactioncollection.h> #include <ktoggleaction.h> #include <kdebug.h> #include <klocale.h> #include <qwidget.h> using namespace KMail; MessageActions::MessageActions( KActionCollection *ac, QWidget * parent ) : QObject( parent ), mParent( parent ), mActionCollection( ac ), mCurrentMessage( 0 ), mMessageView( 0 ) { mReplyActionMenu = new KActionMenu( KIcon("mail-reply-sender"), i18nc("Message->","&Reply"), this ); mActionCollection->addAction( "message_reply_menu", mReplyActionMenu ); connect( mReplyActionMenu, SIGNAL(activated()), this, SLOT(slotReplyToMsg()) ); mReplyAction = new KAction( KIcon("mail-reply-sender"), i18n("&Reply..."), this ); mActionCollection->addAction( "reply", mReplyAction ); mReplyAction->setShortcut(Qt::Key_R); connect( mReplyAction, SIGNAL(activated()), this, SLOT(slotReplyToMsg()) ); mReplyActionMenu->addAction( mReplyAction ); mReplyAuthorAction = new KAction( KIcon("mail-reply-sender"), i18n("Reply to A&uthor..."), this ); mActionCollection->addAction( "reply_author", mReplyAuthorAction ); mReplyAuthorAction->setShortcut(Qt::SHIFT+Qt::Key_A); connect( mReplyAuthorAction, SIGNAL(activated()), this, SLOT(slotReplyAuthorToMsg()) ); mReplyActionMenu->addAction( mReplyAuthorAction ); mReplyAllAction = new KAction( KIcon("mail-reply-all"), i18n("Reply to &All..."), this ); mActionCollection->addAction( "reply_all", mReplyAllAction ); mReplyAllAction->setShortcut( Qt::Key_A ); connect( mReplyAllAction, SIGNAL(activated()), this, SLOT(slotReplyAllToMsg()) ); mReplyActionMenu->addAction( mReplyAllAction ); mReplyListAction = new KAction( KIcon("mail-reply-list"), i18n("Reply to Mailing-&List..."), this ); mActionCollection->addAction( "reply_list", mReplyListAction ); mReplyListAction->setShortcut( Qt::Key_L ); connect( mReplyListAction, SIGNAL(activated()), this, SLOT(slotReplyListToMsg()) ); mReplyActionMenu->addAction( mReplyListAction ); mNoQuoteReplyAction = new KAction( i18n("Reply Without &Quote..."), this ); mActionCollection->addAction( "noquotereply", mNoQuoteReplyAction ); mNoQuoteReplyAction->setShortcut( Qt::SHIFT+Qt::Key_R ); connect( mNoQuoteReplyAction, SIGNAL(activated()), this, SLOT(slotNoQuoteReplyToMsg()) ); mCreateTodoAction = new KAction( KIcon("view-pim-tasks"), i18n("Create To-do/Reminder..."), this ); mCreateTodoAction->setIconText( i18n( "Create To-do" ) ); mActionCollection->addAction( "create_todo", mCreateTodoAction ); connect( mCreateTodoAction, SIGNAL(activated()), this, SLOT(slotCreateTodo()) ); mStatusMenu = new KActionMenu ( i18n( "Mar&k Message" ), this ); mActionCollection->addAction( "set_status", mStatusMenu ); KAction *action; action = new KAction( KIcon("mail-mark-read"), i18n("Mark Message as &Read"), this ); action->setToolTip( i18n("Mark selected messages as read") ); connect( action, SIGNAL(activated()), this, SLOT(slotSetMsgStatusRead()) ); mActionCollection->addAction( "status_read", action ); mStatusMenu->addAction( action ); action = new KAction( KIcon("mail-mark-unread-new"), i18n("Mark Message as &New"), this ); action->setToolTip( i18n("Mark selected messages as new") ); connect( action, SIGNAL(activated()), this, SLOT(slotSetMsgStatusNew()) ); mActionCollection->addAction( "status_new" , action ); mStatusMenu->addAction( action ); action = new KAction( KIcon("mail-mark-unread"), i18n("Mark Message as &Unread"), this ); action->setToolTip( i18n("Mark selected messages as unread") ); connect( action, SIGNAL(activated()), this, SLOT(slotSetMsgStatusUnread()) ); mActionCollection->addAction( "status_unread", action ); mStatusMenu->addAction( action ); mStatusMenu->addSeparator(); mToggleFlagAction = new KToggleAction( KIcon("mail-mark-important"), i18n("Mark Message as &Important"), this ); connect( mToggleFlagAction, SIGNAL(activated()), this, SLOT(slotSetMsgStatusFlag()) ); mToggleFlagAction->setCheckedState( KGuiItem(i18n("Remove &Important Message Mark")) ); mActionCollection->addAction( "status_flag", mToggleFlagAction ); mStatusMenu->addAction( mToggleFlagAction ); mToggleTodoAction = new KToggleAction( KIcon("mail-mark-task"), i18n("Mark Message as &Action Item"), this ); connect( mToggleTodoAction, SIGNAL(activated()), this, SLOT(slotSetMsgStatusTodo()) ); mToggleTodoAction->setCheckedState( KGuiItem(i18n("Remove &Action Item Message Mark")) ); mActionCollection->addAction( "status_todo", mToggleTodoAction ); mStatusMenu->addAction( mToggleTodoAction ); mEditAction = new KAction( KIcon("accessories-text-editor"), i18n("&Edit Message"), this ); mActionCollection->addAction( "edit", mEditAction ); connect( mEditAction, SIGNAL(activated()), this, SLOT(editCurrentMessage()) ); mEditAction->setShortcut( Qt::Key_T ); updateActions(); } void MessageActions::setCurrentMessage(KMMessage * msg) { mCurrentMessage = msg; if ( !msg ) { mSelectedSernums.clear(); mVisibleSernums.clear(); } updateActions(); } void MessageActions::setSelectedSernums(const QList< Q_UINT32 > & sernums) { mSelectedSernums = sernums; updateActions(); } void MessageActions::setSelectedVisibleSernums(const QList< Q_UINT32 > & sernums) { mVisibleSernums = sernums; updateActions(); } void MessageActions::updateActions() { const bool singleMsg = (mCurrentMessage != 0); const bool multiVisible = mVisibleSernums.count() > 0 || mCurrentMessage; const bool flagsAvailable = GlobalSettings::self()->allowLocalFlags() || !((mCurrentMessage && mCurrentMessage->parent()) ? mCurrentMessage->parent()->isReadOnly() : true); mCreateTodoAction->setEnabled( singleMsg ); mReplyActionMenu->setEnabled( singleMsg ); mReplyAction->setEnabled( singleMsg ); mNoQuoteReplyAction->setEnabled( singleMsg ); mReplyAuthorAction->setEnabled( singleMsg ); mReplyAllAction->setEnabled( singleMsg ); mReplyListAction->setEnabled( singleMsg ); mNoQuoteReplyAction->setEnabled( singleMsg ); mStatusMenu->setEnabled( multiVisible ); mToggleFlagAction->setEnabled( flagsAvailable ); mToggleTodoAction->setEnabled( flagsAvailable ); if ( mCurrentMessage ) { mToggleTodoAction->setChecked( mCurrentMessage->status().isTodo() ); mToggleFlagAction->setChecked( mCurrentMessage->status().isImportant() ); } mEditAction->setEnabled( singleMsg ); } void MessageActions::slotCreateTodo() { if ( !mCurrentMessage ) return; KMCommand *command = new CreateTodoCommand( mParent, mCurrentMessage ); command->start(); } void MessageActions::setMessageView(KMReaderWin * msgView) { mMessageView = msgView; } void MessageActions::slotReplyToMsg() { replyCommand<KMReplyToCommand>(); } void MessageActions::slotReplyAuthorToMsg() { replyCommand<KMReplyAuthorCommand>(); } void MessageActions::slotReplyListToMsg() { replyCommand<KMReplyListCommand>(); } void MessageActions::slotReplyAllToMsg() { replyCommand<KMReplyToAllCommand>(); } void MessageActions::slotNoQuoteReplyToMsg() { if ( !mCurrentMessage ) return; KMCommand *command = new KMNoQuoteReplyToCommand( mParent, mCurrentMessage ); command->start(); } void MessageActions::slotSetMsgStatusNew() { setMessageStatus( KPIM::MessageStatus::statusNew() ); } void MessageActions::slotSetMsgStatusUnread() { setMessageStatus( KPIM::MessageStatus::statusUnread() ); } void MessageActions::slotSetMsgStatusRead() { setMessageStatus( KPIM::MessageStatus::statusRead() ); } void MessageActions::slotSetMsgStatusFlag() { setMessageStatus( KPIM::MessageStatus::statusImportant(), true ); } void MessageActions::slotSetMsgStatusTodo() { setMessageStatus( KPIM::MessageStatus::statusTodo(), true ); } void MessageActions::setMessageStatus( KPIM::MessageStatus status, bool toggle ) { QList<Q_UINT32> serNums = mVisibleSernums; if ( serNums.isEmpty() && mCurrentMessage ) serNums.append( mCurrentMessage->getMsgSerNum() ); if ( serNums.empty() ) return; KMCommand *command = new KMSetStatusCommand( status, serNums, toggle ); command->start(); } void MessageActions::editCurrentMessage() { if ( !mCurrentMessage ) return; KMCommand *command = 0; KMFolder *folder = mCurrentMessage->parent(); // edit, unlike send again, removes the message from the folder // we only want that for templates and drafts folders if ( folder && ( kmkernel->folderIsDraftOrOutbox( folder ) || kmkernel->folderIsTemplates( folder ) ) ) command = new KMEditMsgCommand( mParent, mCurrentMessage ); else command = new KMResendMessageCommand( mParent, mCurrentMessage ); command->start(); } #include "messageactions.moc"
Rename "Create Task" to "Create To-do". In kdepim we use "to-do'.
Rename "Create Task" to "Create To-do". In kdepim we use "to-do'. I see other "Task" strings in KMail, mostly referring to groupware folder types. Not sure if I'm allowed to change those. But I'd like to if permitted. svn path=/trunk/KDE/kdepim/; revision=772015
C++
lgpl-2.1
lefou/kdepim-noakonadi,lefou/kdepim-noakonadi,lefou/kdepim-noakonadi,lefou/kdepim-noakonadi,lefou/kdepim-noakonadi,lefou/kdepim-noakonadi
5e1c8c4989949180504783c3f591e3cbce474ea1
scanner/rgtag.cpp
scanner/rgtag.cpp
#include "./rgtag.h" #include <id3v2tag.h> #include <textidentificationframe.h> #include <relativevolumeframe.h> #include <xiphcomment.h> #include <apetag.h> #include <mpegfile.h> #include <flacfile.h> #include <oggfile.h> #include <vorbisfile.h> #include <mpcfile.h> #include <wavpackfile.h> #include <cmath> #include <sstream> #include <ios> void set_txxx_tag(TagLib::ID3v2::Tag* tag, std::string tag_name, std::string value) { TagLib::ID3v2::UserTextIdentificationFrame* txxx = TagLib::ID3v2::UserTextIdentificationFrame::find(tag, tag_name); if (!txxx) { txxx = new TagLib::ID3v2::UserTextIdentificationFrame; txxx->setDescription(tag_name); tag->addFrame(txxx); } txxx->setText(value); } void clear_txxx_tag(TagLib::ID3v2::Tag* tag, std::string tag_name) { TagLib::ID3v2::UserTextIdentificationFrame* txxx = TagLib::ID3v2::UserTextIdentificationFrame::find(tag, tag_name); if (txxx) { tag->removeFrame(txxx); } } void set_rva2_tag(TagLib::ID3v2::Tag* tag, std::string tag_name, double gain, double peak) { TagLib::ID3v2::RelativeVolumeFrame* rva2 = NULL; TagLib::ID3v2::FrameList rva2_frame_list = tag->frameList("RVA2"); TagLib::ID3v2::FrameList::ConstIterator it = rva2_frame_list.begin(); for (; it != rva2_frame_list.end(); ++it) { TagLib::ID3v2::RelativeVolumeFrame* fr = dynamic_cast<TagLib::ID3v2::RelativeVolumeFrame*>(*it); if (fr->identification() == tag_name) { rva2 = fr; break; } } if (!rva2) { rva2 = new TagLib::ID3v2::RelativeVolumeFrame; rva2->setIdentification(tag_name); tag->addFrame(rva2); } rva2->setChannelType(TagLib::ID3v2::RelativeVolumeFrame::MasterVolume); rva2->setVolumeAdjustment(gain); TagLib::ID3v2::RelativeVolumeFrame::PeakVolume peak_volume; peak_volume.bitsRepresentingPeak = 16; double amp_peak = peak * 32768.0 > 65535.0 ? 65535.0 : peak * 32768.0; unsigned int amp_peak_int = static_cast<unsigned int>(std::ceil(amp_peak)); TagLib::ByteVector bv_uint = TagLib::ByteVector::fromUInt(amp_peak_int); peak_volume.peakVolume = TagLib::ByteVector(&(bv_uint.data()[2]), 2); rva2->setPeakVolume(peak_volume); } void clear_rva2_tag(TagLib::ID3v2::Tag* tag, std::string tag_name) { TagLib::ID3v2::RelativeVolumeFrame* rva2 = NULL; TagLib::ID3v2::FrameList rva2_frame_list = tag->frameList("RVA2"); TagLib::ID3v2::FrameList::ConstIterator it = rva2_frame_list.begin(); for (; it != rva2_frame_list.end(); ++it) { TagLib::ID3v2::RelativeVolumeFrame* fr = dynamic_cast<TagLib::ID3v2::RelativeVolumeFrame*>(*it); if (fr->identification() == tag_name) { rva2 = fr; break; } } if (rva2) { tag->removeFrame(rva2); } } void set_rg_info(const char* filename, double track_gain, double track_peak, int album_mode, double album_gain, double album_peak) { std::string fn(filename); std::string ag, tg, ap, tp; std::stringstream ss; ss.precision(2); ss << std::fixed; ss << album_gain; ss >> ag; ss.clear(); ss << track_gain; ss >> tg; ss.clear(); ss.precision(8); ss << album_peak; ss >> ap; ss.clear(); ss << track_peak; ss >> tp; ss.clear(); std::string extension = fn.substr(fn.find_last_of(".") + 1); if (extension == "mp3") { TagLib::MPEG::File f(filename); TagLib::ID3v2::Tag* id3v2tag = f.ID3v2Tag(true); set_txxx_tag(id3v2tag, "replaygain_track_gain", tg + " dB"); set_txxx_tag(id3v2tag, "replaygain_track_peak", tp); set_rva2_tag(id3v2tag, "track", track_gain, track_peak); if (album_mode) { set_txxx_tag(id3v2tag, "replaygain_album_gain", ag + " dB"); set_txxx_tag(id3v2tag, "replaygain_album_peak", ap); set_rva2_tag(id3v2tag, "album", album_gain, album_peak); } else { clear_txxx_tag(id3v2tag, "replaygain_album_gain"); clear_txxx_tag(id3v2tag, "replaygain_album_peak"); clear_rva2_tag(id3v2tag, "album"); } f.save(); } else if (extension == "flac" || extension == "ogg" || extension == "oga") { TagLib::File* file = NULL; TagLib::Ogg::XiphComment* xiph = NULL; if (extension == "flac") { TagLib::FLAC::File* f = new TagLib::FLAC::File(filename); xiph = f->xiphComment(true); file = f; } else if (extension == "ogg" || extension == "oga") { TagLib::Ogg::Vorbis::File* f = new TagLib::Ogg::Vorbis::File(filename); xiph = f->tag(); file = f; } xiph->addField("replaygain_track_gain", tg + " dB"); xiph->addField("replaygain_track_peak", tp); if (album_mode) { xiph->addField("replaygain_album_gain", ag + " dB"); xiph->addField("replaygain_album_peak", ap); } else { xiph->removeField("replaygain_album_gain"); xiph->removeField("replaygain_album_peak"); xiph->removeField("REPLAYGAIN_ALBUM_GAIN"); xiph->removeField("REPLAYGAIN_ALBUM_PEAK"); } file->save(); delete file; } else if (extension == "mpc" || extension == "wv") { TagLib::File* file = NULL; TagLib::APE::Tag* ape = NULL; if (extension == "mpc") { TagLib::MPC::File* f = new TagLib::MPC::File(filename); ape = f->APETag(true); file = f; } else if (extension == "wv") { TagLib::WavPack::File* f = new TagLib::WavPack::File(filename); ape = f->APETag(true); file = f; } ape->addValue("replaygain_track_gain", tg + " dB"); ape->addValue("replaygain_track_peak", tp); if (album_mode) { ape->addValue("replaygain_album_gain", ag + " dB"); ape->addValue("replaygain_album_peak", ap); } else { ape->removeItem("replaygain_album_gain"); ape->removeItem("replaygain_album_peak"); ape->removeItem("REPLAYGAIN_ALBUM_GAIN"); ape->removeItem("REPLAYGAIN_ALBUM_PEAK"); } file->save(); delete file; } } #if 0 int main(int argc, char* argv[]) { double track_gain, track_peak, album_gain, album_peak; int album_mode = atoi(argv[2]); track_gain = atof(argv[3]); track_peak = atof(argv[4]); album_gain = atof(argv[5]); album_peak = atof(argv[6]); set_rg_info(argv[1], track_gain, track_peak, album_mode, album_gain, album_peak); return 0; } #endif
#include "./rgtag.h" #include <id3v2tag.h> #include <textidentificationframe.h> #include <relativevolumeframe.h> #include <xiphcomment.h> #include <apetag.h> #include <mpegfile.h> #include <flacfile.h> #include <oggfile.h> #include <vorbisfile.h> #include <mpcfile.h> #include <wavpackfile.h> #include <cmath> #include <sstream> #include <ios> void set_txxx_tag(TagLib::ID3v2::Tag* tag, std::string tag_name, std::string value) { TagLib::ID3v2::UserTextIdentificationFrame* txxx = TagLib::ID3v2::UserTextIdentificationFrame::find(tag, tag_name); if (!txxx) { txxx = new TagLib::ID3v2::UserTextIdentificationFrame; txxx->setDescription(tag_name); tag->addFrame(txxx); } txxx->setText(value); } void clear_txxx_tag(TagLib::ID3v2::Tag* tag, std::string tag_name) { TagLib::ID3v2::UserTextIdentificationFrame* txxx = TagLib::ID3v2::UserTextIdentificationFrame::find(tag, tag_name); if (txxx) { tag->removeFrame(txxx); } } void set_rva2_tag(TagLib::ID3v2::Tag* tag, std::string tag_name, double gain, double peak) { TagLib::ID3v2::RelativeVolumeFrame* rva2 = NULL; TagLib::ID3v2::FrameList rva2_frame_list = tag->frameList("RVA2"); TagLib::ID3v2::FrameList::ConstIterator it = rva2_frame_list.begin(); for (; it != rva2_frame_list.end(); ++it) { TagLib::ID3v2::RelativeVolumeFrame* fr = dynamic_cast<TagLib::ID3v2::RelativeVolumeFrame*>(*it); if (fr->identification() == tag_name) { rva2 = fr; break; } } if (!rva2) { rva2 = new TagLib::ID3v2::RelativeVolumeFrame; rva2->setIdentification(tag_name); tag->addFrame(rva2); } rva2->setChannelType(TagLib::ID3v2::RelativeVolumeFrame::MasterVolume); rva2->setVolumeAdjustment(gain); TagLib::ID3v2::RelativeVolumeFrame::PeakVolume peak_volume; peak_volume.bitsRepresentingPeak = 16; double amp_peak = peak * 32768.0 > 65535.0 ? 65535.0 : peak * 32768.0; unsigned int amp_peak_int = static_cast<unsigned int>(std::ceil(amp_peak)); TagLib::ByteVector bv_uint = TagLib::ByteVector::fromUInt(amp_peak_int); peak_volume.peakVolume = TagLib::ByteVector(&(bv_uint.data()[2]), 2); rva2->setPeakVolume(peak_volume); } void clear_rva2_tag(TagLib::ID3v2::Tag* tag, std::string tag_name) { TagLib::ID3v2::RelativeVolumeFrame* rva2 = NULL; TagLib::ID3v2::FrameList rva2_frame_list = tag->frameList("RVA2"); TagLib::ID3v2::FrameList::ConstIterator it = rva2_frame_list.begin(); for (; it != rva2_frame_list.end(); ++it) { TagLib::ID3v2::RelativeVolumeFrame* fr = dynamic_cast<TagLib::ID3v2::RelativeVolumeFrame*>(*it); if (fr->identification() == tag_name) { rva2 = fr; break; } } if (rva2) { tag->removeFrame(rva2); } } void set_rg_info(const char* filename, double track_gain, double track_peak, int album_mode, double album_gain, double album_peak) { std::string fn(filename); std::string ag, tg, ap, tp; std::stringstream ss; ss.precision(2); ss << std::fixed; ss << album_gain; ss >> ag; ss.clear(); ss << track_gain; ss >> tg; ss.clear(); ss.precision(8); ss << album_peak; ss >> ap; ss.clear(); ss << track_peak; ss >> tp; ss.clear(); std::string extension = fn.substr(fn.find_last_of(".") + 1); if (extension == "mp3" || extension == "mp2") { TagLib::MPEG::File f(filename); TagLib::ID3v2::Tag* id3v2tag = f.ID3v2Tag(true); set_txxx_tag(id3v2tag, "replaygain_track_gain", tg + " dB"); set_txxx_tag(id3v2tag, "replaygain_track_peak", tp); set_rva2_tag(id3v2tag, "track", track_gain, track_peak); if (album_mode) { set_txxx_tag(id3v2tag, "replaygain_album_gain", ag + " dB"); set_txxx_tag(id3v2tag, "replaygain_album_peak", ap); set_rva2_tag(id3v2tag, "album", album_gain, album_peak); } else { clear_txxx_tag(id3v2tag, "replaygain_album_gain"); clear_txxx_tag(id3v2tag, "replaygain_album_peak"); clear_rva2_tag(id3v2tag, "album"); } f.save(); } else if (extension == "flac" || extension == "ogg" || extension == "oga") { TagLib::File* file = NULL; TagLib::Ogg::XiphComment* xiph = NULL; if (extension == "flac") { TagLib::FLAC::File* f = new TagLib::FLAC::File(filename); xiph = f->xiphComment(true); file = f; } else if (extension == "ogg" || extension == "oga") { TagLib::Ogg::Vorbis::File* f = new TagLib::Ogg::Vorbis::File(filename); xiph = f->tag(); file = f; } xiph->addField("replaygain_track_gain", tg + " dB"); xiph->addField("replaygain_track_peak", tp); if (album_mode) { xiph->addField("replaygain_album_gain", ag + " dB"); xiph->addField("replaygain_album_peak", ap); } else { xiph->removeField("replaygain_album_gain"); xiph->removeField("replaygain_album_peak"); xiph->removeField("REPLAYGAIN_ALBUM_GAIN"); xiph->removeField("REPLAYGAIN_ALBUM_PEAK"); } file->save(); delete file; } else if (extension == "mpc" || extension == "wv") { TagLib::File* file = NULL; TagLib::APE::Tag* ape = NULL; if (extension == "mpc") { TagLib::MPC::File* f = new TagLib::MPC::File(filename); ape = f->APETag(true); file = f; } else if (extension == "wv") { TagLib::WavPack::File* f = new TagLib::WavPack::File(filename); ape = f->APETag(true); file = f; } ape->addValue("replaygain_track_gain", tg + " dB"); ape->addValue("replaygain_track_peak", tp); if (album_mode) { ape->addValue("replaygain_album_gain", ag + " dB"); ape->addValue("replaygain_album_peak", ap); } else { ape->removeItem("replaygain_album_gain"); ape->removeItem("replaygain_album_peak"); ape->removeItem("REPLAYGAIN_ALBUM_GAIN"); ape->removeItem("REPLAYGAIN_ALBUM_PEAK"); } file->save(); delete file; } } #if 0 int main(int argc, char* argv[]) { double track_gain, track_peak, album_gain, album_peak; int album_mode = atoi(argv[2]); track_gain = atof(argv[3]); track_peak = atof(argv[4]); album_gain = atof(argv[5]); album_peak = atof(argv[6]); set_rg_info(argv[1], track_gain, track_peak, album_mode, album_gain, album_peak); return 0; } #endif
enable mp2 tagging
enable mp2 tagging
C++
mit
jiixyj/loudness-scanner,jiixyj/libebur128,jiixyj/loudness-scanner,cicku/libebur128,jiixyj/libebur128
b434ed6084c284b5b465707793e0fe933dc34c0c
tests/http_backend_testsuite.hh
tests/http_backend_testsuite.hh
#include <atomic> #include <thread> #include <iostream> #include <silicon/middlewares/hashmap_session.hh> #include <silicon/api.hh> #include <silicon/clients/libcurl_client.hh> #include "symbols.hh" using namespace s; using namespace sl; struct session { int id; }; auto hl_api = http_api( // get GET / _test = [] () { return D(_message = "get"); }, // get params GET / _test2 * get_parameters(_id = int(0)) = [] (auto p) { return D(_id = p.id); }, // post params POST / _test2 * post_parameters(_id = int(0), _name = std::string()) = [] (auto p) { return D(_id = p.id, _name = p.name ); }, // post object params POST / _test4 * post_parameters(_id = D(_name = std::string())) = [] (auto p) { return D(_name = p.id.name ); }, // post array params POST / _test5 * post_parameters(_id = std::vector<int>()) = [] (auto p) { return D(_name = p.id ); }, // url params GET / _test3 / _id[int(0)] = [] (auto p) { return D(_id = p.id); }, // cookie GET / _set_id / _id[int(0)] = [] (auto p, session& s) { s.id = p.id; return D(_id = s.id); }, GET / _get_id = [] (session& s) { return D(_id = s.id); } ); std::atomic_int cpt0; std::atomic_int cpt1; std::atomic_int cpt2; std::atomic_int cpt3; std::atomic_int cpt4; std::atomic_int cpt5; auto rmq_api = sl::rmq::api( s::_test = [](sl::sqlite_connection &) { std::atomic_fetch_add(&cpt0, 1); }, s::_test1 & sl::rmq::parameters(s::_str = std::string()) = [](auto, sl::sqlite_connection &) { std::atomic_fetch_add(&cpt1, 1); }, s::_test2 * s::_rk1 = [](sl::sqlite_connection &) { std::atomic_fetch_add(&cpt2, 1); }, s::_test3 * s::_rk2 & sl::rmq::parameters(s::_str = std::string()) = [](auto, sl::sqlite_connection &) { std::atomic_fetch_add(&cpt3, 1); }, s::_test4 * s::_rk1 / s::_qn1 = [](sl::sqlite_connection &) { std::atomic_fetch_add(&cpt4, 1); }, s::_test5 * s::_rk2 / s::_qn2 & sl::rmq::parameters(s::_str = std::string()) = [](auto, sl::sqlite_connection &) { std::atomic_fetch_add(&cpt5, 1); } ); template <typename T> void backend_testsuite(T port) { auto c1 = libcurl_json_client(hl_api, "127.0.0.1", port, _post_encoding = _x_www_form_urlencoded); auto c2 = libcurl_json_client(hl_api, "127.0.0.1", port); auto r1 = c1.http_get.test(); assert(r1.status == 200); assert(r1.response.message == "get"); auto r3 = c1.http_get.test2(_id = 12); assert(r3.status == 200); assert(r3.response.id == 12); auto r4 = c1.http_post.test2(_id = 12, _name = "s pa ces"); assert(r4.status == 200); assert(r4.response.id == 12); assert(r4.response.name == "s pa ces"); auto r41 = c2.http_post.test4(_id = D(_name = "John")); assert(r41.status == 200); assert(r41.response.name == "John"); auto r5 = c1.http_get.test3(_id = 12); assert(r5.status == 200); assert(r5.response.id == 12); auto r6 = c1.http_get.set_id(_id = 42); auto r7 = c2.http_get.set_id(_id = 51); auto r8 = c1.http_get.get_id(); auto r9 = c2.http_get.get_id(); assert(r8.response.id == 42); assert(r9.response.id == 51); }
#include <atomic> #include <thread> #include <iostream> #include <silicon/middlewares/hashmap_session.hh> #include <silicon/api.hh> #include <silicon/clients/libcurl_client.hh> #include "symbols.hh" using namespace s; using namespace sl; struct session { int id; }; auto hl_api = http_api( // get GET / _test = [] () { return D(_message = "get"); }, // get params GET / _test2 * get_parameters(_id = int(0)) = [] (auto p) { return D(_id = p.id); }, // post params POST / _test2 * post_parameters(_id = int(0), _name = std::string()) = [] (auto p) { return D(_id = p.id, _name = p.name ); }, // post object params POST / _test4 * post_parameters(_id = D(_name = std::string())) = [] (auto p) { return D(_name = p.id.name ); }, // post array params POST / _test5 * post_parameters(_id = std::vector<int>()) = [] (auto p) { return D(_name = p.id ); }, // url params GET / _test3 / _id[int(0)] = [] (auto p) { return D(_id = p.id); }, // cookie GET / _set_id / _id[int(0)] = [] (auto p, session& s) { s.id = p.id; return D(_id = s.id); }, GET / _get_id = [] (session& s) { return D(_id = s.id); } ); template <typename T> void backend_testsuite(T port) { auto c1 = libcurl_json_client(hl_api, "127.0.0.1", port, _post_encoding = _x_www_form_urlencoded); auto c2 = libcurl_json_client(hl_api, "127.0.0.1", port); auto r1 = c1.http_get.test(); assert(r1.status == 200); assert(r1.response.message == "get"); auto r3 = c1.http_get.test2(_id = 12); assert(r3.status == 200); assert(r3.response.id == 12); auto r4 = c1.http_post.test2(_id = 12, _name = "s pa ces"); assert(r4.status == 200); assert(r4.response.id == 12); assert(r4.response.name == "s pa ces"); auto r41 = c2.http_post.test4(_id = D(_name = "John")); assert(r41.status == 200); assert(r41.response.name == "John"); auto r5 = c1.http_get.test3(_id = 12); assert(r5.status == 200); assert(r5.response.id == 12); auto r6 = c1.http_get.set_id(_id = 42); auto r7 = c2.http_get.set_id(_id = 51); auto r8 = c1.http_get.get_id(); auto r9 = c2.http_get.get_id(); assert(r8.response.id == 42); assert(r9.response.id == 51); }
Split backend_testsuite.hh into http/rmq related code.
Split backend_testsuite.hh into http/rmq related code.
C++
mit
matt-42/silicon,matt-42/silicon,matt-42/silicon
cd246d178fa82f6df7ab0ddff40858106f020c39
tests/unittests/task_unittest.cc
tests/unittests/task_unittest.cc
// Copyright (c) 2013 The Chromium Embedded Framework 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 "include/cef_runnable.h" #include "include/cef_task.h" #include "tests/unittests/test_handler.h" #include "testing/gtest/include/gtest/gtest.h" namespace { void GetForCurrentThread(bool* ran_test) { // Currently on the UI thread. CefRefPtr<CefTaskRunner> runner = CefTaskRunner::GetForCurrentThread(); EXPECT_TRUE(runner.get()); EXPECT_TRUE(runner->BelongsToCurrentThread()); EXPECT_TRUE(runner->BelongsToThread(TID_UI)); EXPECT_FALSE(runner->BelongsToThread(TID_IO)); EXPECT_TRUE(runner->IsSame(runner)); CefRefPtr<CefTaskRunner> runner2 = CefTaskRunner::GetForCurrentThread(); EXPECT_TRUE(runner2.get()); EXPECT_TRUE(runner->IsSame(runner2)); EXPECT_TRUE(runner2->IsSame(runner)); // Not on the IO thread. CefRefPtr<CefTaskRunner> runner3 = CefTaskRunner::GetForThread(TID_IO); EXPECT_TRUE(runner3.get()); EXPECT_FALSE(runner->IsSame(runner3)); EXPECT_FALSE(runner3->IsSame(runner)); *ran_test = true; } void GetForThread(bool* ran_test) { // Currently on the UI thread. CefRefPtr<CefTaskRunner> runner = CefTaskRunner::GetForThread(TID_IO); EXPECT_TRUE(runner.get()); EXPECT_FALSE(runner->BelongsToCurrentThread()); EXPECT_TRUE(runner->BelongsToThread(TID_IO)); EXPECT_FALSE(runner->BelongsToThread(TID_UI)); EXPECT_TRUE(runner->IsSame(runner)); CefRefPtr<CefTaskRunner> runner2 = CefTaskRunner::GetForThread(TID_IO); EXPECT_TRUE(runner2.get()); EXPECT_TRUE(runner->IsSame(runner2)); EXPECT_TRUE(runner2->IsSame(runner)); CefRefPtr<CefTaskRunner> runner3 = CefTaskRunner::GetForThread(TID_UI); EXPECT_TRUE(runner3.get()); EXPECT_FALSE(runner->IsSame(runner3)); EXPECT_FALSE(runner3->IsSame(runner)); *ran_test = true; } void PostTaskEvent1(bool* got_it, CefRefPtr<CefTaskRunner> runner) { // Currently on the IO thread. EXPECT_TRUE(runner->BelongsToCurrentThread()); EXPECT_TRUE(runner->BelongsToThread(TID_IO)); EXPECT_FALSE(runner->BelongsToThread(TID_UI)); // Current thread should be the IO thread. CefRefPtr<CefTaskRunner> runner2 = CefTaskRunner::GetForCurrentThread(); EXPECT_TRUE(runner2.get()); EXPECT_TRUE(runner2->BelongsToCurrentThread()); EXPECT_TRUE(runner2->BelongsToThread(TID_IO)); EXPECT_FALSE(runner2->BelongsToThread(TID_UI)); EXPECT_TRUE(runner->IsSame(runner2)); EXPECT_TRUE(runner2->IsSame(runner)); // Current thread should be the IO thread. CefRefPtr<CefTaskRunner> runner3 = CefTaskRunner::GetForThread(TID_IO); EXPECT_TRUE(runner3.get()); EXPECT_TRUE(runner3->BelongsToCurrentThread()); EXPECT_TRUE(runner3->BelongsToThread(TID_IO)); EXPECT_FALSE(runner3->BelongsToThread(TID_UI)); EXPECT_TRUE(runner->IsSame(runner3)); EXPECT_TRUE(runner3->IsSame(runner)); // Current thread should not be the UI thread. CefRefPtr<CefTaskRunner> runner4 = CefTaskRunner::GetForThread(TID_UI); EXPECT_TRUE(runner4.get()); EXPECT_FALSE(runner4->BelongsToCurrentThread()); EXPECT_FALSE(runner4->BelongsToThread(TID_IO)); EXPECT_TRUE(runner4->BelongsToThread(TID_UI)); EXPECT_FALSE(runner->IsSame(runner4)); EXPECT_FALSE(runner4->IsSame(runner)); *got_it = true; } void PostTask1(bool* ran_test) { // Currently on the UI thread. CefRefPtr<CefTaskRunner> runner = CefTaskRunner::GetForThread(TID_IO); EXPECT_TRUE(runner.get()); EXPECT_FALSE(runner->BelongsToCurrentThread()); EXPECT_TRUE(runner->BelongsToThread(TID_IO)); bool got_it = false; runner->PostTask(NewCefRunnableFunction(&PostTaskEvent1, &got_it, runner)); WaitForThread(runner); EXPECT_TRUE(got_it); *ran_test = true; } void PostDelayedTask1(bool* ran_test) { // Currently on the UI thread. CefRefPtr<CefTaskRunner> runner = CefTaskRunner::GetForThread(TID_IO); EXPECT_TRUE(runner.get()); EXPECT_FALSE(runner->BelongsToCurrentThread()); EXPECT_TRUE(runner->BelongsToThread(TID_IO)); bool got_it = false; runner->PostDelayedTask( NewCefRunnableFunction(&PostTaskEvent1, &got_it, runner), 0); WaitForThread(runner); EXPECT_TRUE(got_it); *ran_test = true; } void PostTaskEvent2(bool* got_it) { EXPECT_TRUE(CefCurrentlyOn(TID_IO)); EXPECT_FALSE(CefCurrentlyOn(TID_UI)); *got_it = true; } void PostTask2(bool* ran_test) { // Currently on the UI thread. EXPECT_FALSE(CefCurrentlyOn(TID_IO)); bool got_it = false; CefPostTask(TID_IO, NewCefRunnableFunction(&PostTaskEvent2, &got_it)); WaitForThread(TID_IO); EXPECT_TRUE(got_it); *ran_test = true; } void PostDelayedTask2(bool* ran_test) { // Currently on the UI thread. EXPECT_FALSE(CefCurrentlyOn(TID_IO)); bool got_it = false; CefPostDelayedTask(TID_IO, NewCefRunnableFunction(&PostTaskEvent2, &got_it), 0); WaitForThread(TID_IO); EXPECT_TRUE(got_it); *ran_test = true; } } // namespace TEST(TaskTest, GetForCurrentThread) { bool ran_test = false; CefPostTask(TID_UI, NewCefRunnableFunction(&GetForCurrentThread, &ran_test)); WaitForThread(TID_UI); EXPECT_TRUE(ran_test); } TEST(TaskTest, GetForThread) { bool ran_test = false; CefPostTask(TID_UI, NewCefRunnableFunction(&GetForThread, &ran_test)); WaitForThread(TID_UI); EXPECT_TRUE(ran_test); } TEST(TaskTest, PostTask1) { bool ran_test = false; CefPostTask(TID_UI, NewCefRunnableFunction(&PostTask1, &ran_test)); WaitForThread(TID_UI); EXPECT_TRUE(ran_test); } TEST(TaskTest, PostDelayedTask1) { bool ran_test = false; CefPostTask(TID_UI, NewCefRunnableFunction(&PostDelayedTask2, &ran_test)); WaitForThread(TID_UI); EXPECT_TRUE(ran_test); } TEST(TaskTest, PostTask2) { bool ran_test = false; CefPostTask(TID_UI, NewCefRunnableFunction(&PostTask2, &ran_test)); WaitForThread(TID_UI); EXPECT_TRUE(ran_test); } TEST(TaskTest, PostDelayedTask2) { bool ran_test = false; CefPostTask(TID_UI, NewCefRunnableFunction(&PostDelayedTask2, &ran_test)); WaitForThread(TID_UI); EXPECT_TRUE(ran_test); }
// Copyright (c) 2013 The Chromium Embedded Framework 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 "include/cef_runnable.h" #include "include/cef_task.h" #include "tests/unittests/test_handler.h" #include "testing/gtest/include/gtest/gtest.h" namespace { void GetForCurrentThread(bool* ran_test) { // Currently on the UI thread. CefRefPtr<CefTaskRunner> runner = CefTaskRunner::GetForCurrentThread(); EXPECT_TRUE(runner.get()); EXPECT_TRUE(runner->BelongsToCurrentThread()); EXPECT_TRUE(runner->BelongsToThread(TID_UI)); EXPECT_FALSE(runner->BelongsToThread(TID_IO)); EXPECT_TRUE(runner->IsSame(runner)); CefRefPtr<CefTaskRunner> runner2 = CefTaskRunner::GetForCurrentThread(); EXPECT_TRUE(runner2.get()); EXPECT_TRUE(runner->IsSame(runner2)); EXPECT_TRUE(runner2->IsSame(runner)); // Not on the IO thread. CefRefPtr<CefTaskRunner> runner3 = CefTaskRunner::GetForThread(TID_IO); EXPECT_TRUE(runner3.get()); EXPECT_FALSE(runner->IsSame(runner3)); EXPECT_FALSE(runner3->IsSame(runner)); *ran_test = true; } void GetForThread(bool* ran_test) { // Currently on the UI thread. CefRefPtr<CefTaskRunner> runner = CefTaskRunner::GetForThread(TID_IO); EXPECT_TRUE(runner.get()); EXPECT_FALSE(runner->BelongsToCurrentThread()); EXPECT_TRUE(runner->BelongsToThread(TID_IO)); EXPECT_FALSE(runner->BelongsToThread(TID_UI)); EXPECT_TRUE(runner->IsSame(runner)); CefRefPtr<CefTaskRunner> runner2 = CefTaskRunner::GetForThread(TID_IO); EXPECT_TRUE(runner2.get()); EXPECT_TRUE(runner->IsSame(runner2)); EXPECT_TRUE(runner2->IsSame(runner)); CefRefPtr<CefTaskRunner> runner3 = CefTaskRunner::GetForThread(TID_UI); EXPECT_TRUE(runner3.get()); EXPECT_FALSE(runner->IsSame(runner3)); EXPECT_FALSE(runner3->IsSame(runner)); *ran_test = true; } void PostTaskEvent1(bool* got_it, CefRefPtr<CefTaskRunner> runner) { // Currently on the IO thread. EXPECT_TRUE(runner->BelongsToCurrentThread()); EXPECT_TRUE(runner->BelongsToThread(TID_IO)); EXPECT_FALSE(runner->BelongsToThread(TID_UI)); // Current thread should be the IO thread. CefRefPtr<CefTaskRunner> runner2 = CefTaskRunner::GetForCurrentThread(); EXPECT_TRUE(runner2.get()); EXPECT_TRUE(runner2->BelongsToCurrentThread()); EXPECT_TRUE(runner2->BelongsToThread(TID_IO)); EXPECT_FALSE(runner2->BelongsToThread(TID_UI)); EXPECT_TRUE(runner->IsSame(runner2)); EXPECT_TRUE(runner2->IsSame(runner)); // Current thread should be the IO thread. CefRefPtr<CefTaskRunner> runner3 = CefTaskRunner::GetForThread(TID_IO); EXPECT_TRUE(runner3.get()); EXPECT_TRUE(runner3->BelongsToCurrentThread()); EXPECT_TRUE(runner3->BelongsToThread(TID_IO)); EXPECT_FALSE(runner3->BelongsToThread(TID_UI)); EXPECT_TRUE(runner->IsSame(runner3)); EXPECT_TRUE(runner3->IsSame(runner)); // Current thread should not be the UI thread. CefRefPtr<CefTaskRunner> runner4 = CefTaskRunner::GetForThread(TID_UI); EXPECT_TRUE(runner4.get()); EXPECT_FALSE(runner4->BelongsToCurrentThread()); EXPECT_FALSE(runner4->BelongsToThread(TID_IO)); EXPECT_TRUE(runner4->BelongsToThread(TID_UI)); EXPECT_FALSE(runner->IsSame(runner4)); EXPECT_FALSE(runner4->IsSame(runner)); *got_it = true; } void PostTask1(bool* ran_test) { // Currently on the UI thread. CefRefPtr<CefTaskRunner> runner = CefTaskRunner::GetForThread(TID_IO); EXPECT_TRUE(runner.get()); EXPECT_FALSE(runner->BelongsToCurrentThread()); EXPECT_TRUE(runner->BelongsToThread(TID_IO)); bool got_it = false; runner->PostTask(NewCefRunnableFunction(&PostTaskEvent1, &got_it, runner)); WaitForThread(runner); EXPECT_TRUE(got_it); *ran_test = true; } void PostDelayedTask1(bool* ran_test) { // Currently on the UI thread. CefRefPtr<CefTaskRunner> runner = CefTaskRunner::GetForThread(TID_IO); EXPECT_TRUE(runner.get()); EXPECT_FALSE(runner->BelongsToCurrentThread()); EXPECT_TRUE(runner->BelongsToThread(TID_IO)); bool got_it = false; runner->PostDelayedTask( NewCefRunnableFunction(&PostTaskEvent1, &got_it, runner), 0); WaitForThread(runner); EXPECT_TRUE(got_it); *ran_test = true; } void PostTaskEvent2(bool* got_it) { EXPECT_TRUE(CefCurrentlyOn(TID_IO)); EXPECT_FALSE(CefCurrentlyOn(TID_UI)); *got_it = true; } void PostTask2(bool* ran_test) { // Currently on the UI thread. EXPECT_FALSE(CefCurrentlyOn(TID_IO)); bool got_it = false; CefPostTask(TID_IO, NewCefRunnableFunction(&PostTaskEvent2, &got_it)); WaitForThread(TID_IO); EXPECT_TRUE(got_it); *ran_test = true; } void PostDelayedTask2(bool* ran_test) { // Currently on the UI thread. EXPECT_FALSE(CefCurrentlyOn(TID_IO)); bool got_it = false; CefPostDelayedTask(TID_IO, NewCefRunnableFunction(&PostTaskEvent2, &got_it), 0); WaitForThread(TID_IO); EXPECT_TRUE(got_it); *ran_test = true; } } // namespace TEST(TaskTest, GetForCurrentThread) { bool ran_test = false; CefPostTask(TID_UI, NewCefRunnableFunction(&GetForCurrentThread, &ran_test)); WaitForThread(TID_UI); EXPECT_TRUE(ran_test); } TEST(TaskTest, GetForThread) { bool ran_test = false; CefPostTask(TID_UI, NewCefRunnableFunction(&GetForThread, &ran_test)); WaitForThread(TID_UI); EXPECT_TRUE(ran_test); } TEST(TaskTest, PostTask1) { bool ran_test = false; CefPostTask(TID_UI, NewCefRunnableFunction(&PostTask1, &ran_test)); WaitForThread(TID_UI); EXPECT_TRUE(ran_test); } TEST(TaskTest, PostDelayedTask1) { bool ran_test = false; CefPostTask(TID_UI, NewCefRunnableFunction(&PostDelayedTask1, &ran_test)); WaitForThread(TID_UI); EXPECT_TRUE(ran_test); } TEST(TaskTest, PostTask2) { bool ran_test = false; CefPostTask(TID_UI, NewCefRunnableFunction(&PostTask2, &ran_test)); WaitForThread(TID_UI); EXPECT_TRUE(ran_test); } TEST(TaskTest, PostDelayedTask2) { bool ran_test = false; CefPostTask(TID_UI, NewCefRunnableFunction(&PostDelayedTask2, &ran_test)); WaitForThread(TID_UI); EXPECT_TRUE(ran_test); }
Fix error in TaskTest.PostDelayedTask1 test.
Fix error in TaskTest.PostDelayedTask1 test. git-svn-id: 4ff65e90c7c89c8f5eba592fcee26b49aecf64bc@1513 5089003a-bbd8-11dd-ad1f-f1f9622dbc98
C++
bsd-3-clause
svn2github/ttserver,svn2github/ttserver,svn2github/cef3,svn2github/ttserver,svn2github/ttserver,svn2github/midle110,svn2github/ttserver,svn2github/cef3,svn2github/midle110,svn2github/cef3,svn2github/midle110,svn2github/midle110,svn2github/cef3,svn2github/cef3,svn2github/midle110