text
stringlengths
54
60.6k
<commit_before>1c749fca-2f67-11e5-bb1e-6c40088e03e4<commit_msg>1c7b6788-2f67-11e5-a29a-6c40088e03e4<commit_after>1c7b6788-2f67-11e5-a29a-6c40088e03e4<|endoftext|>
<commit_before>a46ef391-327f-11e5-b9af-9cf387a8033e<commit_msg>a476c4a8-327f-11e5-b604-9cf387a8033e<commit_after>a476c4a8-327f-11e5-b604-9cf387a8033e<|endoftext|>
<commit_before>a562f840-35ca-11e5-8a18-6c40088e03e4<commit_msg>a56927c6-35ca-11e5-a089-6c40088e03e4<commit_after>a56927c6-35ca-11e5-a089-6c40088e03e4<|endoftext|>
<commit_before>92323b28-2d14-11e5-af21-0401358ea401<commit_msg>92323b29-2d14-11e5-af21-0401358ea401<commit_after>92323b29-2d14-11e5-af21-0401358ea401<|endoftext|>
<commit_before>8fd0498f-2d14-11e5-af21-0401358ea401<commit_msg>8fd04990-2d14-11e5-af21-0401358ea401<commit_after>8fd04990-2d14-11e5-af21-0401358ea401<|endoftext|>
<commit_before>#include <cuda_runtime.h> #include <cublas_v2.h> #include <cassert> #include <cstdlib> #include <ctime> #include <cstdio> #include <iostream> using namespace std; #define M_MAX 256 #define K_MAX 32768 #define N_MAX 16344 /* * K N * ____________ ____________ * | | | | * | | | | * | M_{1} | | M_{2} | * M | | * K | | * | | | | * |____________| |____________| * */ int main() { cublasHandle_t cublasHandle; void* devPtr[3], * hostPtr[3]; float alpha, beta; clock_t startTime; alpha = beta = 1.0; assert(cublasCreate(&cublasHandle) == CUBLAS_STATUS_SUCCESS); assert(cudaMalloc(&devPtr[0], M_MAX * K_MAX * sizeof(float)) == cudaSuccess); assert(cudaMalloc(&devPtr[1], K_MAX * N_MAX * sizeof(float)) == cudaSuccess); assert(cudaMalloc(&devPtr[2], M_MAX * N_MAX * sizeof(float)) == cudaSuccess); assert(hostPtr[0] = malloc(M_MAX * K_MAX * sizeof(float))); assert(hostPtr[1] = malloc(K_MAX * N_MAX * sizeof(float))); assert(hostPtr[2] = malloc(M_MAX * N_MAX * sizeof(float))); for (int m = 64; m <= M_MAX; m <<= 1) { for (int k = 64; k <= K_MAX; k <<= 1) { printf("M: %d, K: %d\n", m, k); for (int n = 128; n <= N_MAX; n <<= 1) { int repeat = (M_MAX / m) * (N_MAX / n) * (K_MAX / k); startTime = clock(); while (repeat--) { assert(cublasSetMatrix(k, m, sizeof(float), hostPtr[0], k, devPtr[0], k) == CUBLAS_STATUS_SUCCESS); assert(cublasSetMatrix(n, k, sizeof(float), hostPtr[1], n, devPtr[1], n) == CUBLAS_STATUS_SUCCESS); assert(cublasSetMatrix(n, m, sizeof(float), hostPtr[2], n, devPtr[2], n) == CUBLAS_STATUS_SUCCESS); assert(cublasSgemm(cublasHandle, CUBLAS_OP_N, CUBLAS_OP_N, n, m, k, &alpha, (const float*) devPtr[1], n, (const float*) devPtr[0], k, &beta, (float*) devPtr[2], n) == CUBLAS_STATUS_SUCCESS); assert(cublasGetMatrix(k, m, sizeof(float), devPtr[0], k, hostPtr[0], k) == CUBLAS_STATUS_SUCCESS); assert(cublasGetMatrix(n, k, sizeof(float), devPtr[1], n, hostPtr[1], n) == CUBLAS_STATUS_SUCCESS); assert(cublasGetMatrix(n, m, sizeof(float), devPtr[2], n, hostPtr[2], n) == CUBLAS_STATUS_SUCCESS); } printf("N: %d, time: %lf\n", n, (double) (clock() - startTime) / CLOCKS_PER_SEC); } } } free(hostPtr[2]); free(hostPtr[1]); free(hostPtr[0]); assert(cudaFree(devPtr[2]) == cudaSuccess); assert(cudaFree(devPtr[1]) == cudaSuccess); assert(cudaFree(devPtr[0]) == cudaSuccess); cublasDestroy(cublasHandle); return 0; } <commit_msg>[master] Second running version. Of constant output size<commit_after>#include <cuda_runtime.h> #include <cublas_v2.h> #include <cassert> #include <cstdlib> #include <ctime> #include <cstdio> #include <iostream> using namespace std; #define M_MAX 256 #define K_MAX 32768 #define MAT_MAX (1 << 21) /* * K N * ____________ ____________ * | | | | * | | | | * | M_{1} | | M_{2} | * M | | * K | | * | | | | * |____________| |____________| * */ int main() { cublasHandle_t cublasHandle; void* devPtr[3], * hostPtr[3]; float alpha, beta; clock_t startTime; alpha = beta = 1.0; assert(cublasCreate(&cublasHandle) == CUBLAS_STATUS_SUCCESS); assert(cudaMalloc(&devPtr[0], M_MAX * K_MAX * sizeof(float)) == cudaSuccess); assert(hostPtr[0] = malloc(M_MAX * K_MAX * sizeof(float))); for (int m = 64; m <= M_MAX; m <<= 1) { for (int k = 64; k <= K_MAX; k <<= 1) { printf("M: %d, K: %d\n", m, k); int nMax; if (m < k) { nMax = MAT_MAX / k; } else { nMax = MAT_MAX / m; } assert(cudaMalloc(&devPtr[1], K_MAX * nMax * sizeof(float)) == cudaSuccess); assert(cudaMalloc(&devPtr[2], M_MAX * nMax * sizeof(float)) == cudaSuccess); assert(hostPtr[1] = malloc(K_MAX * nMax * sizeof(float))); assert(hostPtr[2] = malloc(M_MAX * nMax * sizeof(float))); for (int n = 128; n <= nMax; n <<= 1) { int repeat = (M_MAX / m) * (MAT_MAX / 64 / n) * (K_MAX / k); startTime = clock(); while (repeat--) { assert(cublasSetMatrix(k, m, sizeof(float), hostPtr[0], k, devPtr[0], k) == CUBLAS_STATUS_SUCCESS); assert(cublasSetMatrix(n, k, sizeof(float), hostPtr[1], n, devPtr[1], n) == CUBLAS_STATUS_SUCCESS); assert(cublasSetMatrix(n, m, sizeof(float), hostPtr[2], n, devPtr[2], n) == CUBLAS_STATUS_SUCCESS); assert(cublasSgemm(cublasHandle, CUBLAS_OP_N, CUBLAS_OP_N, n, m, k, &alpha, (const float*) devPtr[1], n, (const float*) devPtr[0], k, &beta, (float*) devPtr[2], n) == CUBLAS_STATUS_SUCCESS); assert(cublasGetMatrix(k, m, sizeof(float), devPtr[0], k, hostPtr[0], k) == CUBLAS_STATUS_SUCCESS); assert(cublasGetMatrix(n, k, sizeof(float), devPtr[1], n, hostPtr[1], n) == CUBLAS_STATUS_SUCCESS); assert(cublasGetMatrix(n, m, sizeof(float), devPtr[2], n, hostPtr[2], n) == CUBLAS_STATUS_SUCCESS); } printf("N: %d, time: %lf\n", n, (double) (clock() - startTime) / CLOCKS_PER_SEC); } free(hostPtr[2]); free(hostPtr[1]); assert(cudaFree(devPtr[2]) == cudaSuccess); assert(cudaFree(devPtr[1]) == cudaSuccess); } } free(hostPtr[0]); assert(cudaFree(devPtr[0]) == cudaSuccess); cublasDestroy(cublasHandle); return 0; } <|endoftext|>
<commit_before>3bd94abd-2e4f-11e5-a83c-28cfe91dbc4b<commit_msg>3be0484f-2e4f-11e5-9b3c-28cfe91dbc4b<commit_after>3be0484f-2e4f-11e5-9b3c-28cfe91dbc4b<|endoftext|>
<commit_before>2e2ab1fa-2e4f-11e5-9257-28cfe91dbc4b<commit_msg>2e3143c5-2e4f-11e5-89d0-28cfe91dbc4b<commit_after>2e3143c5-2e4f-11e5-89d0-28cfe91dbc4b<|endoftext|>
<commit_before>99118b21-327f-11e5-9797-9cf387a8033e<commit_msg>9918a330-327f-11e5-8207-9cf387a8033e<commit_after>9918a330-327f-11e5-8207-9cf387a8033e<|endoftext|>
<commit_before>7916ff86-2d53-11e5-baeb-247703a38240<commit_msg>79178050-2d53-11e5-baeb-247703a38240<commit_after>79178050-2d53-11e5-baeb-247703a38240<|endoftext|>
<commit_before>c262d6cf-2747-11e6-9a2b-e0f84713e7b8<commit_msg>Added that feature we discussed on... Was it monday?<commit_after>c26dec00-2747-11e6-85d3-e0f84713e7b8<|endoftext|>
<commit_before>8c3d204e-2d14-11e5-af21-0401358ea401<commit_msg>8c3d204f-2d14-11e5-af21-0401358ea401<commit_after>8c3d204f-2d14-11e5-af21-0401358ea401<|endoftext|>
<commit_before>66e10346-2fa5-11e5-9173-00012e3d3f12<commit_msg>66e37442-2fa5-11e5-a6ad-00012e3d3f12<commit_after>66e37442-2fa5-11e5-a6ad-00012e3d3f12<|endoftext|>
<commit_before>/* main.cpp * */ #include "main.h" //constructor - initialize drive robot_class::robot_class() : drive ( left_front_motor.jag, left_rear_motor.jag, right_front_motor.jag, right_rear_motor.jag ) { GetWatchdog().SetEnabled(false); //we don't want Watchdog //now set the necessary inversions drive.SetInvertedMotor(left_front_motor.type, left_front_motor.reverse); drive.SetInvertedMotor(left_rear_motor.type, left_rear_motor.reverse); drive.SetInvertedMotor(right_front_motor.type, right_front_motor.reverse); drive.SetInvertedMotor(right_rear_motor.type, right_rear_motor.reverse); } void robot_class::RobotInit() { //do nothing } void robot_class::DisabledInit() { //do nothing } void robot_class::AutonomousInit() { //do nothing } void robot_class::TeleopInit() { //do nothing } void robot_class::DisabledPeriodic() { //do nothing } void robot_class::AutonomousPeriodic() { //do nothing } void robot_class::TeleopPeriodic() { //do nothing } void robot_class::DisabledContinuous() { //do nothing } void robot_class::AutonomousContinuous() { //do nothing } void robot_class::TeleopContinuous() { //actually do something!! :D drive.TankDrive(left_joystick, right_joystick); Wait(0.005); } //the following macro tells the library that we want to generate code //for our class robot_class START_ROBOT_CLASS(robot_class); <commit_msg>explicitly includes ports.h<commit_after>/* main.cpp * */ #include "main.h" #include "ports.h" //constructor - initialize drive robot_class::robot_class() : drive ( left_front_motor.jag, left_rear_motor.jag, right_front_motor.jag, right_rear_motor.jag ) { GetWatchdog().SetEnabled(false); //we don't want Watchdog //now set the necessary inversions drive.SetInvertedMotor(left_front_motor.type, left_front_motor.reverse); drive.SetInvertedMotor(left_rear_motor.type, left_rear_motor.reverse); drive.SetInvertedMotor(right_front_motor.type, right_front_motor.reverse); drive.SetInvertedMotor(right_rear_motor.type, right_rear_motor.reverse); } void robot_class::RobotInit() { //do nothing } void robot_class::DisabledInit() { //do nothing } void robot_class::AutonomousInit() { //do nothing } void robot_class::TeleopInit() { //do nothing } void robot_class::DisabledPeriodic() { //do nothing } void robot_class::AutonomousPeriodic() { //do nothing } void robot_class::TeleopPeriodic() { //do nothing } void robot_class::DisabledContinuous() { //do nothing } void robot_class::AutonomousContinuous() { //do nothing } void robot_class::TeleopContinuous() { //actually do something!! :D drive.TankDrive(left_joystick, right_joystick); Wait(0.005); } //the following macro tells the library that we want to generate code //for our class robot_class START_ROBOT_CLASS(robot_class); <|endoftext|>
<commit_before>dea911e1-2747-11e6-a278-e0f84713e7b8<commit_msg>lets try again<commit_after>deb7c55c-2747-11e6-a98e-e0f84713e7b8<|endoftext|>
<commit_before>#include <stdio.h> // Standard Input/Output Header #include <stdlib.h> // C Standard General Utilities Library #include <omp.h> // Open Multi-Processing Library #include "testio.h" // Test Input/Output Header int main (int argc, char const *argv[]){ Testio myTestio; printf("Nombre de processeurs : %d \n",omp_get_num_procs()); printf("Nombre de thread actifs : %d \n",omp_get_num_threads()); int n; #pragma omp parallel for schedule(dynamic,2) for(n=0;n<18;n++){ printf("Element %d traité par le thread %d \n",n,omp_get_thread_num()); } return EXIT_SUCCESS; } <commit_msg>Changes to be committed: modified: main.cpp<commit_after>#include <stdio.h> // Standard Input/Output Header #include <stdlib.h> // C Standard General Utilities Library #include <omp.h> // Open Multi-Processing Library #include "testio.h" // Test Input/Output Header /** Mets tes tests dedans Tristan :) */ int Test_Tristan() { } /** Mets tes tests dedans Etienne :) */ int Test_Etienne() { Testio myTestio; printf("Nombre de processeurs : %d \n",omp_get_num_procs()); printf("Nombre de thread actifs : %d \n",omp_get_num_threads()); int n; #pragma omp parallel for schedule(dynamic,2) for(n=0;n<18;n++){ printf("Element %d traité par le thread %d \n",n,omp_get_thread_num()); } } int main (int argc, char const *argv[]){ Test_Tristan(); Test_Etienne(); return EXIT_SUCCESS; } <|endoftext|>
<commit_before>b0eae25c-35ca-11e5-9168-6c40088e03e4<commit_msg>b0f1b65e-35ca-11e5-9b97-6c40088e03e4<commit_after>b0f1b65e-35ca-11e5-9b97-6c40088e03e4<|endoftext|>
<commit_before>#include "ray.hpp" Ray transformRay(glm::mat4 const& mat, Ray const& ray) { glm::vec4 a{ray.m_origin,1.0f}; glm::vec4 b{ray.m_direction,0.0f}; return {mat*a,mat*b}; }<commit_msg>Camera updated with matrix<commit_after>#include "ray.hpp" Ray transformRay(glm::mat4 const& mat, Ray const& ray) { glm::vec4 a{ray.m_origin,1.0f}; glm::vec4 b{ray.m_direction,0.0f}; return {glm::vec3(mat*a),glm::vec3(mat*b)}; }<|endoftext|>
<commit_before>6793d886-2fa5-11e5-83ed-00012e3d3f12<commit_msg>6795d454-2fa5-11e5-8282-00012e3d3f12<commit_after>6795d454-2fa5-11e5-8282-00012e3d3f12<|endoftext|>
<commit_before>dbad7638-313a-11e5-a3ed-3c15c2e10482<commit_msg>dbb500ee-313a-11e5-a5a6-3c15c2e10482<commit_after>dbb500ee-313a-11e5-a5a6-3c15c2e10482<|endoftext|>
<commit_before>8e9fabe8-2d14-11e5-af21-0401358ea401<commit_msg>8e9fabe9-2d14-11e5-af21-0401358ea401<commit_after>8e9fabe9-2d14-11e5-af21-0401358ea401<|endoftext|>
<commit_before>a22bbeb5-2747-11e6-87de-e0f84713e7b8<commit_msg>Gapjgjchguagdmg<commit_after>a2376568-2747-11e6-8657-e0f84713e7b8<|endoftext|>
<commit_before>/* MIT License Copyright (c) 2017 CPirc 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 <cstdio> #include <cstring> #include <cctype> #include <cassert> #include "bitboard.h" #include "uci.h" /* reads from the file descriptor fd into the pre-allocated buffer pointed to by buff, * until either it hits EOF, '\n', or it reads buff_len - 1 characters. * Returns true if it read less than buff_len characters (or if the EOF character was read) * false otherwise. */ bool getline_auto(FILE *fd, char *buff, std::size_t buff_len) { assert(buff && fd && buff_len); std::size_t idx = 0, idx_len = buff_len - 1; int curr; bool ret = true; while ( ((curr = std::fgetc(fd)) != EOF) && curr != '\n') { if (idx == idx_len) { break; } if (!std::isblank(curr)) { buff[idx++] = (char)curr; } } //flush stdin if (curr != EOF && curr != '\n') { ret = false; while ( ((curr = std::fgetc(fd)) != EOF) && curr != '\n'); } buff[idx] = '\0'; return ret; } /* The start of all things (after _start) */ int main(int argc, char *argv[]) { init_bitboards(); char protocol[12]; assert(!std::setvbuf(stdout, NULL, _IONBF, 0)); assert(!std::setvbuf(stdin, NULL, _IONBF, 0)); if (getline_auto(stdin, protocol, 12)) { if (!std::strncmp(protocol, "uci", 3)) { return uci_main(argc, argv); } std::puts("Unsupported protocol!"); } else std::puts("Stack overflow!"); /*Position pos; parse_fen_to_position("3q3k/1Q4R1/2pNB2p/2Pp3n/8/6P1/3r2r1/7K b - - 3 38", pos); parse_fen_to_position("rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1", pos); start_search(pos);*/ return 1; } <commit_msg>Remove assert() for setvbuf.<commit_after>/* MIT License Copyright (c) 2017 CPirc 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 <cstdio> #include <cstring> #include <cctype> #include <cassert> #include "bitboard.h" #include "uci.h" /* reads from the file descriptor fd into the pre-allocated buffer pointed to by buff, * until either it hits EOF, '\n', or it reads buff_len - 1 characters. * Returns true if it read less than buff_len characters (or if the EOF character was read) * false otherwise. */ bool getline_auto(FILE *fd, char *buff, std::size_t buff_len) { assert(buff && fd && buff_len); std::size_t idx = 0, idx_len = buff_len - 1; int curr; bool ret = true; while ( ((curr = std::fgetc(fd)) != EOF) && curr != '\n') { if (idx == idx_len) { break; } if (!std::isblank(curr)) { buff[idx++] = (char)curr; } } //flush stdin if (curr != EOF && curr != '\n') { ret = false; while ( ((curr = std::fgetc(fd)) != EOF) && curr != '\n'); } buff[idx] = '\0'; return ret; } /* The start of all things (after _start) */ int main(int argc, char *argv[]) { init_bitboards(); char protocol[12]; std::setvbuf(stdout, NULL, _IONBF, 0); std::setvbuf(stdin, NULL, _IONBF, 0); if (getline_auto(stdin, protocol, 12)) { if (!std::strncmp(protocol, "uci", 3)) { return uci_main(argc, argv); } std::puts("Unsupported protocol!"); } else std::puts("Stack overflow!"); /*Position pos; parse_fen_to_position("3q3k/1Q4R1/2pNB2p/2Pp3n/8/6P1/3r2r1/7K b - - 3 38", pos); parse_fen_to_position("rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1", pos); start_search(pos);*/ return 1; } <|endoftext|>
<commit_before>809e91ad-2d15-11e5-af21-0401358ea401<commit_msg>809e91ae-2d15-11e5-af21-0401358ea401<commit_after>809e91ae-2d15-11e5-af21-0401358ea401<|endoftext|>
<commit_before>3366951c-2f67-11e5-8d9f-6c40088e03e4<commit_msg>336e79d0-2f67-11e5-8d2a-6c40088e03e4<commit_after>336e79d0-2f67-11e5-8d2a-6c40088e03e4<|endoftext|>
<commit_before>92323aba-2d14-11e5-af21-0401358ea401<commit_msg>92323abb-2d14-11e5-af21-0401358ea401<commit_after>92323abb-2d14-11e5-af21-0401358ea401<|endoftext|>
<commit_before>6ff15294-2749-11e6-871c-e0f84713e7b8<commit_msg>I finished programming, there is nothing left to program<commit_after>70017957-2749-11e6-9cc4-e0f84713e7b8<|endoftext|>
<commit_before>ee253a06-585a-11e5-b175-6c40088e03e4<commit_msg>ee2e09f4-585a-11e5-a8f0-6c40088e03e4<commit_after>ee2e09f4-585a-11e5-a8f0-6c40088e03e4<|endoftext|>
<commit_before>c9b3202e-327f-11e5-9465-9cf387a8033e<commit_msg>c9be5b73-327f-11e5-ae67-9cf387a8033e<commit_after>c9be5b73-327f-11e5-ae67-9cf387a8033e<|endoftext|>
<commit_before>0deb287a-2f67-11e5-8fb3-6c40088e03e4<commit_msg>0df24f5e-2f67-11e5-8fe3-6c40088e03e4<commit_after>0df24f5e-2f67-11e5-8fe3-6c40088e03e4<|endoftext|>
<commit_before>610138f8-2d3d-11e5-9950-c82a142b6f9b<commit_msg>61a9f42b-2d3d-11e5-bb93-c82a142b6f9b<commit_after>61a9f42b-2d3d-11e5-bb93-c82a142b6f9b<|endoftext|>
<commit_before>#include <cstdlib> #include <ctime> #include <iostream> #include <iterator> #include <string> #include <vector> #include <dastring/dastring.h> #include "optparse.h" typedef std::string string_type; typedef std::vector<string_type> strings_type; typedef dastring::ngram_generator ngram_generator_type; typedef dastring::writer_base<string_type, ngram_generator_type> writer_type; typedef dastring::reader_base<string_type> reader_type; typedef dastring::query::exact<string_type, ngram_generator_type> query_exact_type; typedef dastring::query::cosine<string_type, ngram_generator_type> query_cosine_type; typedef dastring::query::dice<string_type, ngram_generator_type> query_dice_type; typedef dastring::query::jaccard<string_type, ngram_generator_type> query_jaccard_type; typedef dastring::query::overlap<string_type, ngram_generator_type> query_overlap_type; class option : public optparse { public: enum { MODE_INTERACTIVE, MODE_BUILD, MODE_HELP, }; enum { QT_EXACT, QT_DICE, QT_COSINE, QT_JACCARD, QT_OVERLAP, }; int mode; std::string name; int ngram_size; int query_type; double threshold; public: option() : mode(MODE_INTERACTIVE), name(""), ngram_size(3), query_type(QT_EXACT), threshold(1.) { } BEGIN_OPTION_MAP_INLINE() ON_OPTION(SHORTOPT('b') || LONGOPT("build")) mode = MODE_BUILD; ON_OPTION_WITH_ARG(SHORTOPT('d') || LONGOPT("database")) name = arg; ON_OPTION_WITH_ARG(SHORTOPT('n') || LONGOPT("ngram")) ngram_size = std::atoi(arg); ON_OPTION(SHORTOPT('h') || LONGOPT("help")) mode = MODE_HELP; END_OPTION_MAP() }; int usage(std::ostream& os, const char *argv0) { os << "USAGE: " << argv0 << " [OPTIONS]" << std::endl; os << std::endl; return 0; } int build(option& opt) { int n = 0; clock_t clk; std::istream& is = std::cin; std::ostream& os = std::cout; std::ostream& es = std::cerr; // Show parameters for database construction. os << "Constructing the database" << std::endl; os << "Database name: " << opt.name << std::endl; os << "N-gram length: " << opt.ngram_size << std::endl; os.flush(); // Open the database for construction. clk = std::clock(); ngram_generator_type gen(opt.ngram_size); writer_type db(gen, opt.name); if (db.fail()) { es << "ERROR: " << db.error() << std::endl; return 1; } // Insert every string from STDIN into the database. for (;;) { std::string line; std::getline(is, line); if (is.eof()) { break; } if (!db.insert(line)) { es << "ERROR: " << db.error() << std::endl; return 1; } // Progress report. if (++n % 10000 == 0) { os << "Number of strings: " << n << std::endl; os.flush(); } } os << "Number of strings: " << n << std::endl; os << std::endl; os.flush(); // Finalize the database. os << "Flushing the database" << std::endl; if (!db.close()) { es << "ERROR: " << db.error() << std::endl; return 1; } os << std::endl; // Report the elaped time for construction. os << "Seconds required: " << (std::clock() - clk) / (double)CLOCKS_PER_SEC << std::endl; os << std::endl; os.flush(); return 0; } int interactive(option& opt) { reader_type db; std::istream& is = std::cin; std::ostream& os = std::cout; std::ostream& es = std::cerr; db.open(opt.name); ngram_generator_type gen(opt.ngram_size); for (;;) { // Show a prompt. switch (opt.query_type) { case option::QT_EXACT: os << "[exact]$ "; break; case option::QT_DICE: os << "[dice>=" << opt.threshold << "]$ "; break; case option::QT_COSINE: os << "[cosine>=" << opt.threshold << "]$ "; break; case option::QT_JACCARD: os << "[jaccard>=" << opt.threshold << "]$ "; break; case option::QT_OVERLAP: os << "[overlap>=" << opt.threshold << "]$ "; break; } // Read a line. std::string line; std::getline(is, line); if (is.eof()) { break; } // Check if the line indicates a command. if (line.compare(0, 16, ":set query exact") == 0) { opt.query_type = option::QT_EXACT; } else if (line.compare(0, 16, ":set query dice ") == 0) { opt.query_type = option::QT_DICE; opt.threshold = std::atof(line.c_str() + 16); } else if (line.compare(0, 18, ":set query cosine ") == 0) { opt.query_type = option::QT_COSINE; opt.threshold = std::atof(line.c_str() + 18); } else if (line.compare(0, 19, ":set query jaccard ") == 0) { opt.query_type = option::QT_JACCARD; opt.threshold = std::atof(line.c_str() + 19); } else if (line.compare(0, 19, ":set query overlap ") == 0) { opt.query_type = option::QT_OVERLAP; opt.threshold = std::atof(line.c_str() + 19); } else if (line == ":help") { //usage_interactive(os); } else if (line == ":quit") { break; } else { // The line is a query. strings_type xstrs; clock_t clk = std::clock(); // Issue a query. switch (opt.query_type) { case option::QT_EXACT: db.retrieve( query_exact_type(gen, line), std::back_inserter(xstrs) ); break; case option::QT_DICE: db.retrieve( query_dice_type(gen, line, opt.threshold), std::back_inserter(xstrs) ); break; case option::QT_COSINE: db.retrieve( query_cosine_type(gen, line, opt.threshold), std::back_inserter(xstrs) ); break; case option::QT_JACCARD: db.retrieve( query_jaccard_type(gen, line, opt.threshold), std::back_inserter(xstrs) ); break; case option::QT_OVERLAP: db.retrieve( query_overlap_type(gen, line, opt.threshold), std::back_inserter(xstrs) ); break; } // Output the retrieved strings. strings_type::const_iterator it; for (it = xstrs.begin();it != xstrs.end();++it) { os << '\t' << *it << std::endl; } os << xstrs.size() << " strings retrieved (" << (std::clock() - clk) / (double)CLOCKS_PER_SEC << " sec)" << std::endl; } } return 0; } int main(int argc, char *argv[]) { option opt; std::istream& is = std::cin; std::ostream& os = std::cout; std::ostream& es = std::cerr; // Show the copyright information. os << DASTRING_NAME " "; os << DASTRING_MAJOR_VERSION << "." << DASTRING_MINOR_VERSION << " "; os << DASTRING_COPYRIGHT << std::endl; os << std::endl; // Parse the command-line options. try { int arg_used = opt.parse(argv, argc); } catch (const optparse::unrecognized_option& e) { es << "ERROR: unrecognized option: " << e.what() << std::endl; return 1; } catch (const optparse::invalid_value& e) { es << "ERROR: " << e.what() << std::endl; return 1; } // Branches for the processing mode. switch (opt.mode) { case option::MODE_HELP: return usage(os, argv[0]); case option::MODE_BUILD: return build(opt); case option::MODE_INTERACTIVE: return interactive(opt); default: return 1; } } <commit_msg>Revised the prompt symbol a bit.<commit_after>#include <cstdlib> #include <ctime> #include <iostream> #include <iterator> #include <string> #include <vector> #include <dastring/dastring.h> #include "optparse.h" typedef std::string string_type; typedef std::vector<string_type> strings_type; typedef dastring::ngram_generator ngram_generator_type; typedef dastring::writer_base<string_type, ngram_generator_type> writer_type; typedef dastring::reader_base<string_type> reader_type; typedef dastring::query::exact<string_type, ngram_generator_type> query_exact_type; typedef dastring::query::cosine<string_type, ngram_generator_type> query_cosine_type; typedef dastring::query::dice<string_type, ngram_generator_type> query_dice_type; typedef dastring::query::jaccard<string_type, ngram_generator_type> query_jaccard_type; typedef dastring::query::overlap<string_type, ngram_generator_type> query_overlap_type; class option : public optparse { public: enum { MODE_INTERACTIVE, MODE_BUILD, MODE_HELP, }; enum { QT_EXACT, QT_DICE, QT_COSINE, QT_JACCARD, QT_OVERLAP, }; int mode; std::string name; int ngram_size; int query_type; double threshold; public: option() : mode(MODE_INTERACTIVE), name(""), ngram_size(3), query_type(QT_EXACT), threshold(1.) { } BEGIN_OPTION_MAP_INLINE() ON_OPTION(SHORTOPT('b') || LONGOPT("build")) mode = MODE_BUILD; ON_OPTION_WITH_ARG(SHORTOPT('d') || LONGOPT("database")) name = arg; ON_OPTION_WITH_ARG(SHORTOPT('n') || LONGOPT("ngram")) ngram_size = std::atoi(arg); ON_OPTION(SHORTOPT('h') || LONGOPT("help")) mode = MODE_HELP; END_OPTION_MAP() }; int usage(std::ostream& os, const char *argv0) { os << "USAGE: " << argv0 << " [OPTIONS]" << std::endl; os << std::endl; return 0; } int build(option& opt) { int n = 0; clock_t clk; std::istream& is = std::cin; std::ostream& os = std::cout; std::ostream& es = std::cerr; // Show parameters for database construction. os << "Constructing the database" << std::endl; os << "Database name: " << opt.name << std::endl; os << "N-gram length: " << opt.ngram_size << std::endl; os.flush(); // Open the database for construction. clk = std::clock(); ngram_generator_type gen(opt.ngram_size); writer_type db(gen, opt.name); if (db.fail()) { es << "ERROR: " << db.error() << std::endl; return 1; } // Insert every string from STDIN into the database. for (;;) { std::string line; std::getline(is, line); if (is.eof()) { break; } if (!db.insert(line)) { es << "ERROR: " << db.error() << std::endl; return 1; } // Progress report. if (++n % 10000 == 0) { os << "Number of strings: " << n << std::endl; os.flush(); } } os << "Number of strings: " << n << std::endl; os << std::endl; os.flush(); // Finalize the database. os << "Flushing the database" << std::endl; if (!db.close()) { es << "ERROR: " << db.error() << std::endl; return 1; } os << std::endl; // Report the elaped time for construction. os << "Seconds required: " << (std::clock() - clk) / (double)CLOCKS_PER_SEC << std::endl; os << std::endl; os.flush(); return 0; } int interactive(option& opt) { reader_type db; std::istream& is = std::cin; std::ostream& os = std::cout; std::ostream& es = std::cerr; db.open(opt.name); ngram_generator_type gen(opt.ngram_size); for (;;) { // Show a prompt. switch (opt.query_type) { case option::QT_EXACT: os << "[exact]> "; break; case option::QT_DICE: os << "[dice>=" << opt.threshold << "]> "; break; case option::QT_COSINE: os << "[cosine>=" << opt.threshold << "]> "; break; case option::QT_JACCARD: os << "[jaccard>=" << opt.threshold << "]> "; break; case option::QT_OVERLAP: os << "[overlap>=" << opt.threshold << "]> "; break; } // Read a line. std::string line; std::getline(is, line); if (is.eof()) { break; } // Check if the line indicates a command. if (line.compare(0, 16, ":set query exact") == 0) { opt.query_type = option::QT_EXACT; } else if (line.compare(0, 16, ":set query dice ") == 0) { opt.query_type = option::QT_DICE; opt.threshold = std::atof(line.c_str() + 16); } else if (line.compare(0, 18, ":set query cosine ") == 0) { opt.query_type = option::QT_COSINE; opt.threshold = std::atof(line.c_str() + 18); } else if (line.compare(0, 19, ":set query jaccard ") == 0) { opt.query_type = option::QT_JACCARD; opt.threshold = std::atof(line.c_str() + 19); } else if (line.compare(0, 19, ":set query overlap ") == 0) { opt.query_type = option::QT_OVERLAP; opt.threshold = std::atof(line.c_str() + 19); } else if (line == ":help") { //usage_interactive(os); } else if (line == ":quit") { break; } else { // The line is a query. strings_type xstrs; clock_t clk = std::clock(); // Issue a query. switch (opt.query_type) { case option::QT_EXACT: db.retrieve( query_exact_type(gen, line), std::back_inserter(xstrs) ); break; case option::QT_DICE: db.retrieve( query_dice_type(gen, line, opt.threshold), std::back_inserter(xstrs) ); break; case option::QT_COSINE: db.retrieve( query_cosine_type(gen, line, opt.threshold), std::back_inserter(xstrs) ); break; case option::QT_JACCARD: db.retrieve( query_jaccard_type(gen, line, opt.threshold), std::back_inserter(xstrs) ); break; case option::QT_OVERLAP: db.retrieve( query_overlap_type(gen, line, opt.threshold), std::back_inserter(xstrs) ); break; } // Output the retrieved strings. strings_type::const_iterator it; for (it = xstrs.begin();it != xstrs.end();++it) { os << '\t' << *it << std::endl; } os << xstrs.size() << " strings retrieved (" << (std::clock() - clk) / (double)CLOCKS_PER_SEC << " sec)" << std::endl; } } return 0; } int main(int argc, char *argv[]) { option opt; std::istream& is = std::cin; std::ostream& os = std::cout; std::ostream& es = std::cerr; // Show the copyright information. os << DASTRING_NAME " "; os << DASTRING_MAJOR_VERSION << "." << DASTRING_MINOR_VERSION << " "; os << DASTRING_COPYRIGHT << std::endl; os << std::endl; // Parse the command-line options. try { int arg_used = opt.parse(argv, argc); } catch (const optparse::unrecognized_option& e) { es << "ERROR: unrecognized option: " << e.what() << std::endl; return 1; } catch (const optparse::invalid_value& e) { es << "ERROR: " << e.what() << std::endl; return 1; } // Branches for the processing mode. switch (opt.mode) { case option::MODE_HELP: return usage(os, argv[0]); case option::MODE_BUILD: return build(opt); case option::MODE_INTERACTIVE: return interactive(opt); default: return 1; } } <|endoftext|>
<commit_before>85627921-2d15-11e5-af21-0401358ea401<commit_msg>85627922-2d15-11e5-af21-0401358ea401<commit_after>85627922-2d15-11e5-af21-0401358ea401<|endoftext|>
<commit_before>/* Request handlers for WSGI apps and static files Copyright (c) 2016 Roman Miroshnychenko <romanvm@yandex.ua> License: MIT, see License.txt */ #include "request_handlers.h" #include <boost/iostreams/filtering_stream.hpp> #include <boost/iostreams/filter/gzip.hpp> #include <boost/iostreams/copy.hpp> #include <fstream> #include <iostream> #include <sstream> using namespace std; namespace py = boost::python; namespace fs = boost::filesystem; namespace sys = boost::system; namespace alg = boost::algorithm; namespace wsgi_boost { #pragma region StaticRequestHandler void StaticRequestHandler::handle() { const auto content_dir_path = fs::path{ m_request.content_dir }; if (!fs::exists(content_dir_path)) { m_response.send_mesage("500 Internal Server Error", "Error 500: Internal server error! Invalid content directory."); return; } if (m_request.method != "GET" && m_request.method != "HEAD") { m_response.send_mesage("405 Method Not Allowed"); return; } open_file(content_dir_path); } void StaticRequestHandler::open_file(const fs::path& content_dir_path) { fs::path path = content_dir_path; path /= boost::regex_replace(m_request.path, m_request.path_regex, ""); if (fs::exists(path)) { path = fs::canonical(path); // Checking if path is inside content_dir if (distance(content_dir_path.begin(), content_dir_path.end()) <= distance(path.begin(), path.end()) && equal(content_dir_path.begin(), content_dir_path.end(), path.begin())) { if (fs::is_directory(path)) { path /= "index.html"; } if (fs::exists(path) && fs::is_regular_file(path)) { ifstream ifs; ifs.open(path.string(), ifstream::in | ios::binary); if (ifs) { headers_type out_headers; out_headers.emplace_back("Cache-Control", m_cache_control); time_t last_modified = fs::last_write_time(path); out_headers.emplace_back("Last-Modified", time_to_header(last_modified)); string ims = m_request.get_header("If-Modified-Since"); if (ims != "" && header_to_time(ims) >= last_modified) { out_headers.emplace_back("Content-Length", "0"); m_response.send_header("304 Not Modified", out_headers, true); return; } string ext = path.extension().string(); string mime = get_mime(ext); out_headers.emplace_back("Content-Type", mime); if (m_request.use_gzip && is_compressable(ext) && m_request.check_header("Accept-Encoding", "gzip")) { boost::iostreams::filtering_istream gzstream; gzstream.push(boost::iostreams::gzip_compressor()); gzstream.push(ifs); stringstream compressed; boost::iostreams::copy(gzstream, compressed); out_headers.emplace_back("Content-Encoding", "gzip"); send_file(compressed, out_headers); } else { out_headers.emplace_back("Accept-Ranges", "bytes"); send_file(ifs, out_headers); } ifs.close(); return; } } } } m_response.send_mesage("404 Not Found", "Error 404: Requested content not found!"); } void StaticRequestHandler::send_file(istream& content_stream, headers_type& headers) { content_stream.seekg(0, ios::end); size_t length = content_stream.tellg(); headers.emplace_back("Content-Length", to_string(length)); size_t start_pos = 0; size_t end_pos = length - 1; string requested_range = m_request.get_header("Range"); pair<string, string> range; if (requested_range != "" && ((range = parse_range(requested_range)) != pair<string, string>())) { if (range.first != string()) { start_pos = stoull(range.first); } else { range.first = to_string(start_pos); } if (range.second != string()) { end_pos = stoull(range.second); } else { range.second = to_string(end_pos); } if (start_pos > end_pos || start_pos >= length || end_pos >= length) { m_response.send_mesage("416 Range Not Satisfiable"); return; } else { headers.emplace_back("Content-Range", "bytes " + range.first + "-" + range.second + "/" + to_string(length)); m_response.send_header("206 Partial Content", headers, true); } } else { m_response.send_header("200 OK", headers, true); } if (start_pos > 0) { content_stream.seekg(start_pos); } else { content_stream.seekg(0, ios::beg); } if (m_request.method == "GET") { const size_t buffer_size = 131072; vector<char> buffer(buffer_size); size_t read_length; size_t bytes_left = end_pos - start_pos + 1; while (bytes_left > 0 && ((read_length = content_stream.read(&buffer[0], min(bytes_left, buffer_size)).gcount()) > 0)) { sys::error_code ec = m_response.send_data(string(&buffer[0], read_length), true); if (ec) return; bytes_left -= read_length; } } } #pragma endregion #pragma region WsgiRequestHandler WsgiRequestHandler::WsgiRequestHandler(Request& request, Response& response, py::object& app, bool async) : BaseRequestHandler(request, response), m_app{ app }, m_async{ async } { function<void(py::object)> wr{ [this](py::object data) { sys::error_code ec = m_response.send_header(m_status, m_out_headers); if (ec) return; m_headers_sent = true; string cpp_data = py::extract<string>(data); GilRelease release_gil; m_response.send_data(cpp_data); } }; m_write = py::make_function(wr, py::default_call_policies(), py::args("data"), boost::mpl::vector<void, py::object>()); function<py::object(py::str, py::list, py::object)> sr{ [this](py::str status, py::list headers, py::object exc_info = py::object()) { if (!exc_info.is_none()) { py::object format_exc = py::import("traceback").attr("format_exc")(); string exc_msg = py::extract<string>(format_exc); cerr << exc_msg << '\n'; exc_info = py::object(); } this->m_status = py::extract<string>(status); m_out_headers.clear(); bool has_cont_len = false; bool has_chunked = false; for (size_t i = 0; i < py::len(headers); ++i) { py::object header = headers[i]; string header_name = py::extract<string>(header[0]); string header_value = py::extract<string>(header[1]); // If a WSGI app does not provide Content-Length header (e.g. Django) // we use Transfer-Encoding: chunked if (alg::iequals(header_name, "Content-Length")) has_cont_len = true; if (alg::iequals(header_name, "Transfer-Encoding") && header_value.find("chunked") == string::npos) has_chunked = true; m_out_headers.emplace_back(header_name, header_value); } if (!(has_cont_len || has_chunked)) { this->m_send_chunked = true; m_out_headers.emplace_back("Transfer-Encoding", "chunked"); } return m_write; } }; m_start_response = py::make_function(sr, py::default_call_policies(), (py::arg("status"), "headers", py::arg("exc_info") = py::object()), boost::mpl::vector<py::object, py::str, py::list, py::object>()); } void WsgiRequestHandler::handle() { if (m_app.is_none()) { m_response.send_mesage("500 Internal Server Error", "Error 500: Internal server error! WSGI application is not set."); return; } prepare_environ(); if (m_request.check_header("Expect", "100-continue")) { m_response.send_mesage("100 Continue"); } py::object args = get_python_object(Py_BuildValue("(O,O)", m_environ.ptr(), m_start_response.ptr())); Iterator iterable{ get_python_object(PyEval_CallObject(m_app.ptr(), args.ptr())) }; send_iterable(iterable); } void WsgiRequestHandler::prepare_environ() { m_environ["REQUEST_METHOD"] = m_request.method; m_environ["SCRIPT_NAME"] = ""; pair<string, string> path_and_query = split_path(m_request.path); m_environ["PATH_INFO"] = path_and_query.first; m_environ["QUERY_STRING"] = path_and_query.second; string ct = m_request.get_header("Content-Type"); if (ct != "") { m_environ["CONTENT_TYPE"] = ct; } string cl = m_request.get_header("Content-Length"); if (cl != "") { m_environ["CONTENT_LENGTH"] = cl; } m_environ["SERVER_NAME"] = m_request.host_name; m_environ["SERVER_PORT"] = to_string(m_request.local_endpoint_port); m_environ["SERVER_PROTOCOL"] = m_request.http_version; for (const auto& header : m_request.headers) { std::string env_header = transform_header(header.first); if (env_header == "HTTP_CONTENT_TYPE" || env_header == "HTTP_CONTENT_LENGTH") { continue; } if (!py::extract<bool>(m_environ.attr("__contains__")(env_header))) { m_environ[env_header] = header.second; } else { m_environ[env_header] = m_environ[env_header] + "," + header.second; } } m_environ["REMOTE_ADDR"] = m_environ["REMOTE_HOST"] = m_request.remote_address(); m_environ["REMOTE_PORT"] = to_string(m_request.remote_port()); m_environ["wsgi.version"] = py::make_tuple<int, int>(1, 0); m_environ["wsgi.url_scheme"] = m_request.url_scheme; InputWrapper input{ m_request.connection(), m_async }; m_environ["wsgi.input"] = input; m_environ["wsgi.errors"] = py::import("sys").attr("stderr"); m_environ["wsgi.multithread"] = true; m_environ["wsgi.multiprocess"] = false; m_environ["wsgi.run_once"] = false; m_environ["wsgi.file_wrapper"] = py::import("wsgiref.util").attr("FileWrapper"); } void WsgiRequestHandler::send_iterable(Iterator& iterable) { py::object iterator = iterable.attr("__iter__")(); while (true) { try { #if PY_MAJOR_VERSION < 3 std::string chunk = py::extract<string>(iterator.attr("next")()); #else std::string chunk = py::extract<string>(iterator.attr("__next__")()); #endif GilRelease release_gil; sys::error_code ec; if (!m_headers_sent) { ec = m_response.send_header(m_status, m_out_headers); if (ec) break; m_headers_sent = true; } if (m_send_chunked) chunk = hex(chunk.length()) + "\r\n" + chunk + "\r\n"; ec = m_response.send_data(chunk, m_async); if (ec) break; } catch (const py::error_already_set&) { if (PyErr_ExceptionMatches(PyExc_StopIteration)) { PyErr_Clear(); if (m_send_chunked) m_response.send_data("0\r\n\r\n"); break; } throw; } } } #pragma endregion } <commit_msg>Fix bug with incorrect determiming chunked transfer encoding from a WSGI app<commit_after>/* Request handlers for WSGI apps and static files Copyright (c) 2016 Roman Miroshnychenko <romanvm@yandex.ua> License: MIT, see License.txt */ #include "request_handlers.h" #include <boost/iostreams/filtering_stream.hpp> #include <boost/iostreams/filter/gzip.hpp> #include <boost/iostreams/copy.hpp> #include <fstream> #include <iostream> #include <sstream> using namespace std; namespace py = boost::python; namespace fs = boost::filesystem; namespace sys = boost::system; namespace alg = boost::algorithm; namespace wsgi_boost { #pragma region StaticRequestHandler void StaticRequestHandler::handle() { const auto content_dir_path = fs::path{ m_request.content_dir }; if (!fs::exists(content_dir_path)) { m_response.send_mesage("500 Internal Server Error", "Error 500: Internal server error! Invalid content directory."); return; } if (m_request.method != "GET" && m_request.method != "HEAD") { m_response.send_mesage("405 Method Not Allowed"); return; } open_file(content_dir_path); } void StaticRequestHandler::open_file(const fs::path& content_dir_path) { fs::path path = content_dir_path; path /= boost::regex_replace(m_request.path, m_request.path_regex, ""); if (fs::exists(path)) { path = fs::canonical(path); // Checking if path is inside content_dir if (distance(content_dir_path.begin(), content_dir_path.end()) <= distance(path.begin(), path.end()) && equal(content_dir_path.begin(), content_dir_path.end(), path.begin())) { if (fs::is_directory(path)) { path /= "index.html"; } if (fs::exists(path) && fs::is_regular_file(path)) { ifstream ifs; ifs.open(path.string(), ifstream::in | ios::binary); if (ifs) { headers_type out_headers; out_headers.emplace_back("Cache-Control", m_cache_control); time_t last_modified = fs::last_write_time(path); out_headers.emplace_back("Last-Modified", time_to_header(last_modified)); string ims = m_request.get_header("If-Modified-Since"); if (ims != "" && header_to_time(ims) >= last_modified) { out_headers.emplace_back("Content-Length", "0"); m_response.send_header("304 Not Modified", out_headers, true); return; } string ext = path.extension().string(); string mime = get_mime(ext); out_headers.emplace_back("Content-Type", mime); if (m_request.use_gzip && is_compressable(ext) && m_request.check_header("Accept-Encoding", "gzip")) { boost::iostreams::filtering_istream gzstream; gzstream.push(boost::iostreams::gzip_compressor()); gzstream.push(ifs); stringstream compressed; boost::iostreams::copy(gzstream, compressed); out_headers.emplace_back("Content-Encoding", "gzip"); send_file(compressed, out_headers); } else { out_headers.emplace_back("Accept-Ranges", "bytes"); send_file(ifs, out_headers); } ifs.close(); return; } } } } m_response.send_mesage("404 Not Found", "Error 404: Requested content not found!"); } void StaticRequestHandler::send_file(istream& content_stream, headers_type& headers) { content_stream.seekg(0, ios::end); size_t length = content_stream.tellg(); headers.emplace_back("Content-Length", to_string(length)); size_t start_pos = 0; size_t end_pos = length - 1; string requested_range = m_request.get_header("Range"); pair<string, string> range; if (requested_range != "" && ((range = parse_range(requested_range)) != pair<string, string>())) { if (range.first != string()) { start_pos = stoull(range.first); } else { range.first = to_string(start_pos); } if (range.second != string()) { end_pos = stoull(range.second); } else { range.second = to_string(end_pos); } if (start_pos > end_pos || start_pos >= length || end_pos >= length) { m_response.send_mesage("416 Range Not Satisfiable"); return; } else { headers.emplace_back("Content-Range", "bytes " + range.first + "-" + range.second + "/" + to_string(length)); m_response.send_header("206 Partial Content", headers, true); } } else { m_response.send_header("200 OK", headers, true); } if (start_pos > 0) { content_stream.seekg(start_pos); } else { content_stream.seekg(0, ios::beg); } if (m_request.method == "GET") { const size_t buffer_size = 131072; vector<char> buffer(buffer_size); size_t read_length; size_t bytes_left = end_pos - start_pos + 1; while (bytes_left > 0 && ((read_length = content_stream.read(&buffer[0], min(bytes_left, buffer_size)).gcount()) > 0)) { sys::error_code ec = m_response.send_data(string(&buffer[0], read_length), true); if (ec) return; bytes_left -= read_length; } } } #pragma endregion #pragma region WsgiRequestHandler WsgiRequestHandler::WsgiRequestHandler(Request& request, Response& response, py::object& app, bool async) : BaseRequestHandler(request, response), m_app{ app }, m_async{ async } { function<void(py::object)> wr{ [this](py::object data) { sys::error_code ec = m_response.send_header(m_status, m_out_headers); if (ec) return; m_headers_sent = true; string cpp_data = py::extract<string>(data); GilRelease release_gil; m_response.send_data(cpp_data); } }; m_write = py::make_function(wr, py::default_call_policies(), py::args("data"), boost::mpl::vector<void, py::object>()); function<py::object(py::str, py::list, py::object)> sr{ [this](py::str status, py::list headers, py::object exc_info = py::object()) { if (!exc_info.is_none()) { py::object format_exc = py::import("traceback").attr("format_exc")(); string exc_msg = py::extract<string>(format_exc); cerr << exc_msg << '\n'; exc_info = py::object(); } this->m_status = py::extract<string>(status); m_out_headers.clear(); bool has_cont_len = false; bool has_chunked = false; for (size_t i = 0; i < py::len(headers); ++i) { py::object header = headers[i]; string header_name = py::extract<string>(header[0]); string header_value = py::extract<string>(header[1]); // If a WSGI app does not provide Content-Length header (e.g. Django) // we use Transfer-Encoding: chunked if (alg::iequals(header_name, "Content-Length")) has_cont_len = true; if (alg::iequals(header_name, "Transfer-Encoding") && header_value.find("chunked") != string::npos) has_chunked = true; m_out_headers.emplace_back(header_name, header_value); } if (!(has_cont_len || has_chunked)) { this->m_send_chunked = true; m_out_headers.emplace_back("Transfer-Encoding", "chunked"); } return m_write; } }; m_start_response = py::make_function(sr, py::default_call_policies(), (py::arg("status"), "headers", py::arg("exc_info") = py::object()), boost::mpl::vector<py::object, py::str, py::list, py::object>()); } void WsgiRequestHandler::handle() { if (m_app.is_none()) { m_response.send_mesage("500 Internal Server Error", "Error 500: Internal server error! WSGI application is not set."); return; } prepare_environ(); if (m_request.check_header("Expect", "100-continue")) { m_response.send_mesage("100 Continue"); } py::object args = get_python_object(Py_BuildValue("(O,O)", m_environ.ptr(), m_start_response.ptr())); Iterator iterable{ get_python_object(PyEval_CallObject(m_app.ptr(), args.ptr())) }; send_iterable(iterable); } void WsgiRequestHandler::prepare_environ() { m_environ["REQUEST_METHOD"] = m_request.method; m_environ["SCRIPT_NAME"] = ""; pair<string, string> path_and_query = split_path(m_request.path); m_environ["PATH_INFO"] = path_and_query.first; m_environ["QUERY_STRING"] = path_and_query.second; string ct = m_request.get_header("Content-Type"); if (ct != "") { m_environ["CONTENT_TYPE"] = ct; } string cl = m_request.get_header("Content-Length"); if (cl != "") { m_environ["CONTENT_LENGTH"] = cl; } m_environ["SERVER_NAME"] = m_request.host_name; m_environ["SERVER_PORT"] = to_string(m_request.local_endpoint_port); m_environ["SERVER_PROTOCOL"] = m_request.http_version; for (const auto& header : m_request.headers) { std::string env_header = transform_header(header.first); if (env_header == "HTTP_CONTENT_TYPE" || env_header == "HTTP_CONTENT_LENGTH") { continue; } if (!py::extract<bool>(m_environ.attr("__contains__")(env_header))) { m_environ[env_header] = header.second; } else { m_environ[env_header] = m_environ[env_header] + "," + header.second; } } m_environ["REMOTE_ADDR"] = m_environ["REMOTE_HOST"] = m_request.remote_address(); m_environ["REMOTE_PORT"] = to_string(m_request.remote_port()); m_environ["wsgi.version"] = py::make_tuple<int, int>(1, 0); m_environ["wsgi.url_scheme"] = m_request.url_scheme; InputWrapper input{ m_request.connection(), m_async }; m_environ["wsgi.input"] = input; m_environ["wsgi.errors"] = py::import("sys").attr("stderr"); m_environ["wsgi.multithread"] = true; m_environ["wsgi.multiprocess"] = false; m_environ["wsgi.run_once"] = false; m_environ["wsgi.file_wrapper"] = py::import("wsgiref.util").attr("FileWrapper"); } void WsgiRequestHandler::send_iterable(Iterator& iterable) { py::object iterator = iterable.attr("__iter__")(); while (true) { try { #if PY_MAJOR_VERSION < 3 std::string chunk = py::extract<string>(iterator.attr("next")()); #else std::string chunk = py::extract<string>(iterator.attr("__next__")()); #endif GilRelease release_gil; sys::error_code ec; if (!m_headers_sent) { ec = m_response.send_header(m_status, m_out_headers); if (ec) break; m_headers_sent = true; } if (m_send_chunked) chunk = hex(chunk.length()) + "\r\n" + chunk + "\r\n"; ec = m_response.send_data(chunk, m_async); if (ec) break; } catch (const py::error_already_set&) { if (PyErr_ExceptionMatches(PyExc_StopIteration)) { PyErr_Clear(); if (m_send_chunked) m_response.send_data("0\r\n\r\n"); break; } throw; } } } #pragma endregion } <|endoftext|>
<commit_before>#include <QtGui/QGuiApplication> #include <QtWidgets/QApplication> #include <QQuickItem> #include <QDebug> #include <QSettings> #include <QQmlContext> #include <QSortFilterProxyModel> #include <QtWidgets/QFileDialog> #include <QTime> #include "qtquick2applicationviewer.h" #include "resourcelistmodel.h" #include "humanlistmodel.h" #include "savedgamelistmodel.h" #include "settings.h" #include "savesaccess.h" #define TESTING 0 QString appVersion() { // Version History // --------------------- // 0.4 - first release, only resource editing // 0.5 - second release, only tweaked resource list // 1.0 - units: add and remove // return "1.0 beta 2"; } int main(int argc, char *argv[]) { // Seed the random number generator QTime time = QTime::currentTime(); qsrand((uint)time.msec()); QApplication app(argc, argv); QtQuick2ApplicationViewer viewer; viewer.setMinimumWidth(400); viewer.setMinimumHeight(350); QStringList libPaths = QCoreApplication::libraryPaths(); libPaths.append(QCoreApplication::applicationDirPath() + "/plugins"); app.setLibraryPaths(libPaths); #if TESTING QByteArray binary; unsigned int result; bool failed(false); for( unsigned int value=0; value<65000; value++ ) { binary = SavesAccess::toBinary(value); result = SavesAccess::toInt(binary); if( result != value) { qDebug() << "Value" << value << "returned" << result; failed = true; break; } } if( failed ) { qDebug() << "[FAILURE] The tests did NOT succeed!"; } else { qDebug() << "[PASSED] All tests passed."; } #endif QCoreApplication::setApplicationName("Axe and Pick"); QCoreApplication::setOrganizationDomain("potatominingcorp.com"); QCoreApplication::setOrganizationName("Potato Mining Corporation"); app.setWindowIcon(QIcon()); viewer.setTitle(QCoreApplication::applicationName() + " v" + appVersion()); // Register the list item types for the enumerations in QML qmlRegisterType<Resource>("Resource", 1,0, "Resource"); // Load and create the settings. Give QML access. Settings settings; viewer.rootContext()->setContextProperty("settings", &settings); // // SAVED GAMES // // This holds the info for all the saved games. SavesAccess savesAccess; savesAccess.setFilePath(settings.value("TimberAndStone/GameInstallationDirectory").toString()); SavedGameListModel * savedGameModel = new SavedGameListModel(new SavedGame, qApp); savesAccess.setSavedGameListModel(savedGameModel); savesAccess.loadGamesList(); viewer.rootContext()->setContextProperty("savesAccess", &savesAccess); viewer.rootContext()->setContextProperty("savedGameModel", savedGameModel); // // RESOURCES // // Create a model that holds our resource data, and // add the data to it. Then make it available to QML. ResourceListModel * resourceModel = new ResourceListModel(new Resource, qApp); savesAccess.setResourceListModel(resourceModel); viewer.rootContext()->setContextProperty("resourceModel", resourceModel); // Create the proxy model that contains the results of the filter. QSortFilterProxyModel * proxyResourceModel = new QSortFilterProxyModel(); proxyResourceModel->setSourceModel(resourceModel); proxyResourceModel->setFilterRole(Resource::FilterStringRole); // This prevents unknown items from showing up in the list. proxyResourceModel->setFilterRegExp("^(?!unknown).*"); viewer.rootContext()->setContextProperty("resourceModelProxy", proxyResourceModel); // Enable the case insensitivity proxyResourceModel->setFilterCaseSensitivity(Qt::CaseInsensitive); // Setup sorting the resources //proxyResourceModel->setSortRole(Resource::TypeRole); //proxyResourceModel->sort(0); // // UNITS // // Humans HumanListModel * humanModel = new HumanListModel(new Human, qApp); savesAccess.setHumanModel(humanModel); viewer.rootContext()->setContextProperty("humanModel", humanModel); QSortFilterProxyModel * proxyHumanModel = new QSortFilterProxyModel(); proxyHumanModel->setSourceModel(humanModel); proxyHumanModel->setFilterRole(Human::FilterStringRole); proxyHumanModel->setFilterCaseSensitivity(Qt::CaseInsensitive); viewer.rootContext()->setContextProperty("humanModelProxy", proxyHumanModel); proxyHumanModel->setFilterRegExp("^(?!unknown).*"); // Neutral Mobs NeutralMobListModel * neutralMobModel = new NeutralMobListModel(new NeutralMob, qApp); savesAccess.setNeutralMobModel(neutralMobModel); viewer.rootContext()->setContextProperty("neutralMobModel", neutralMobModel); QSortFilterProxyModel * proxyNeutralMobModel = new QSortFilterProxyModel(); proxyNeutralMobModel->setSourceModel(neutralMobModel); proxyNeutralMobModel->setFilterRole(NeutralMob::FilterStringRole); proxyNeutralMobModel->setFilterCaseSensitivity(Qt::CaseInsensitive); viewer.rootContext()->setContextProperty("neutralMobModelProxy", proxyNeutralMobModel); // Violent Mobs ViolentMobListModel * violentMobModel = new ViolentMobListModel(new ViolentMob, qApp); savesAccess.setViolentMobModel(violentMobModel); viewer.rootContext()->setContextProperty("violentMobModel", violentMobModel); QSortFilterProxyModel * proxyViolentMobModel = new QSortFilterProxyModel(); proxyViolentMobModel->setSourceModel(violentMobModel); proxyViolentMobModel->setFilterRole(ViolentMob::FilterStringRole); proxyViolentMobModel->setFilterCaseSensitivity(Qt::CaseInsensitive); viewer.rootContext()->setContextProperty("violentMobModelProxy", proxyViolentMobModel); // Load the QML viewer.setMainQmlFile(QStringLiteral("qml/AxeAndPick/main.qml")); // Show the GUI viewer.showExpanded(); return app.exec(); } <commit_msg>Updated version information to version 1.0, beta 3<commit_after>#include <QtGui/QGuiApplication> #include <QtWidgets/QApplication> #include <QQuickItem> #include <QDebug> #include <QSettings> #include <QQmlContext> #include <QSortFilterProxyModel> #include <QtWidgets/QFileDialog> #include <QTime> #include "qtquick2applicationviewer.h" #include "resourcelistmodel.h" #include "humanlistmodel.h" #include "savedgamelistmodel.h" #include "settings.h" #include "savesaccess.h" #define TESTING 0 QString appVersion() { // Version History // --------------------- // 0.4 - first release, only resource editing // 0.5 - second release, only tweaked resource list // 1.0 - units: add and remove, added error display // return "1.0 beta 3"; } int main(int argc, char *argv[]) { // Seed the random number generator QTime time = QTime::currentTime(); qsrand((uint)time.msec()); QApplication app(argc, argv); QtQuick2ApplicationViewer viewer; viewer.setMinimumWidth(400); viewer.setMinimumHeight(350); QStringList libPaths = QCoreApplication::libraryPaths(); libPaths.append(QCoreApplication::applicationDirPath() + "/plugins"); app.setLibraryPaths(libPaths); #if TESTING QByteArray binary; unsigned int result; bool failed(false); for( unsigned int value=0; value<65000; value++ ) { binary = SavesAccess::toBinary(value); result = SavesAccess::toInt(binary); if( result != value) { qDebug() << "Value" << value << "returned" << result; failed = true; break; } } if( failed ) { qDebug() << "[FAILURE] The tests did NOT succeed!"; } else { qDebug() << "[PASSED] All tests passed."; } #endif QCoreApplication::setApplicationName("Axe and Pick"); QCoreApplication::setOrganizationDomain("potatominingcorp.com"); QCoreApplication::setOrganizationName("Potato Mining Corporation"); app.setWindowIcon(QIcon()); viewer.setTitle(QCoreApplication::applicationName() + " v" + appVersion()); // Register the list item types for the enumerations in QML qmlRegisterType<Resource>("Resource", 1,0, "Resource"); // Load and create the settings. Give QML access. Settings settings; viewer.rootContext()->setContextProperty("settings", &settings); // // SAVED GAMES // // This holds the info for all the saved games. SavesAccess savesAccess; savesAccess.setFilePath(settings.value("TimberAndStone/GameInstallationDirectory").toString()); SavedGameListModel * savedGameModel = new SavedGameListModel(new SavedGame, qApp); savesAccess.setSavedGameListModel(savedGameModel); savesAccess.loadGamesList(); viewer.rootContext()->setContextProperty("savesAccess", &savesAccess); viewer.rootContext()->setContextProperty("savedGameModel", savedGameModel); // // RESOURCES // // Create a model that holds our resource data, and // add the data to it. Then make it available to QML. ResourceListModel * resourceModel = new ResourceListModel(new Resource, qApp); savesAccess.setResourceListModel(resourceModel); viewer.rootContext()->setContextProperty("resourceModel", resourceModel); // Create the proxy model that contains the results of the filter. QSortFilterProxyModel * proxyResourceModel = new QSortFilterProxyModel(); proxyResourceModel->setSourceModel(resourceModel); proxyResourceModel->setFilterRole(Resource::FilterStringRole); // This prevents unknown items from showing up in the list. proxyResourceModel->setFilterRegExp("^(?!unknown).*"); viewer.rootContext()->setContextProperty("resourceModelProxy", proxyResourceModel); // Enable the case insensitivity proxyResourceModel->setFilterCaseSensitivity(Qt::CaseInsensitive); // Setup sorting the resources //proxyResourceModel->setSortRole(Resource::TypeRole); //proxyResourceModel->sort(0); // // UNITS // // Humans HumanListModel * humanModel = new HumanListModel(new Human, qApp); savesAccess.setHumanModel(humanModel); viewer.rootContext()->setContextProperty("humanModel", humanModel); QSortFilterProxyModel * proxyHumanModel = new QSortFilterProxyModel(); proxyHumanModel->setSourceModel(humanModel); proxyHumanModel->setFilterRole(Human::FilterStringRole); proxyHumanModel->setFilterCaseSensitivity(Qt::CaseInsensitive); viewer.rootContext()->setContextProperty("humanModelProxy", proxyHumanModel); proxyHumanModel->setFilterRegExp("^(?!unknown).*"); // Neutral Mobs NeutralMobListModel * neutralMobModel = new NeutralMobListModel(new NeutralMob, qApp); savesAccess.setNeutralMobModel(neutralMobModel); viewer.rootContext()->setContextProperty("neutralMobModel", neutralMobModel); QSortFilterProxyModel * proxyNeutralMobModel = new QSortFilterProxyModel(); proxyNeutralMobModel->setSourceModel(neutralMobModel); proxyNeutralMobModel->setFilterRole(NeutralMob::FilterStringRole); proxyNeutralMobModel->setFilterCaseSensitivity(Qt::CaseInsensitive); viewer.rootContext()->setContextProperty("neutralMobModelProxy", proxyNeutralMobModel); // Violent Mobs ViolentMobListModel * violentMobModel = new ViolentMobListModel(new ViolentMob, qApp); savesAccess.setViolentMobModel(violentMobModel); viewer.rootContext()->setContextProperty("violentMobModel", violentMobModel); QSortFilterProxyModel * proxyViolentMobModel = new QSortFilterProxyModel(); proxyViolentMobModel->setSourceModel(violentMobModel); proxyViolentMobModel->setFilterRole(ViolentMob::FilterStringRole); proxyViolentMobModel->setFilterCaseSensitivity(Qt::CaseInsensitive); viewer.rootContext()->setContextProperty("violentMobModelProxy", proxyViolentMobModel); // Load the QML viewer.setMainQmlFile(QStringLiteral("qml/AxeAndPick/main.qml")); // Show the GUI viewer.showExpanded(); return app.exec(); } <|endoftext|>
<commit_before>#include "neural_network.h" #include <cmath> #include <algorithm> #include <map> NeuralNetwork::NeuralNetwork(const TrainingParameters & parameters): parameters(parameters), genome(parameters), inputNeurons(parameters.numberOfInputs), outputNeurons(parameters.numberOfOutputs) { MutateGenesAndBuildNetwork(); } NeuralNetwork::NeuralNetwork(const Genome& genome): parameters(genome.GetTrainingParameters()), genome(genome), inputNeurons(genome.GetTrainingParameters().numberOfInputs), outputNeurons(genome.GetTrainingParameters().numberOfOutputs) { MutateGenesAndBuildNetwork(); } NeuralNetwork::NeuralNetwork(Genome&& genome): parameters(genome.GetTrainingParameters()), genome(std::move(genome)), inputNeurons(genome.GetTrainingParameters().numberOfInputs), outputNeurons(genome.GetTrainingParameters().numberOfOutputs) { MutateGenesAndBuildNetwork(); } NeuralNetwork::NeuralNetwork(const NeuralNetwork& other) : parameters(other.parameters), genome(other.genome), neurons(other.neurons.size()), inputNeurons(other.inputNeurons.size()), outputNeurons(other.outputNeurons.size()) { BuildNetworkFromGenes(); } NeuralNetwork::NeuralNetwork(NeuralNetwork&& other) : parameters(std::move(other.parameters)), genome(std::move(other.genome)), neurons(other.neurons.size()), inputNeurons(std::move(other.inputNeurons.size())), outputNeurons(std::move(other.outputNeurons.size())) { BuildNetworkFromGenes(); } NeuralNetwork& NeuralNetwork::operator=(const NeuralNetwork& other) { layerMap = other.layerMap; genome = other.genome; neurons = other.neurons; inputNeurons.resize(other.inputNeurons.size()); outputNeurons.resize(other.outputNeurons.size()); const_cast<TrainingParameters&>(this->parameters) = other.parameters; InterpretInputsAndOutputs(); return *this; } void NeuralNetwork::BuildNetworkFromGenes() { neurons.resize(genome.GetNeuronCount()); for (const auto& gene : genome) { if (gene.isEnabled) { Neuron::IncomingConnection connection; connection.neuron = &neurons[gene.from]; connection.weight = gene.weight; connection.isRecursive = gene.isRecursive; neurons[gene.to].AddConnection(std::move(connection)); } } InterpretInputsAndOutputs(); CategorizeNeuronsIntoLayers(); } void NeuralNetwork::SetInputs(const std::vector<float>& inputs) { if (inputNeurons.size() != inputs.size()) { throw std::out_of_range("Number of inputs provided doesn't match genetic information"); } for(size_t i = 0U; i < inputNeurons.size(); ++i) { inputNeurons[i]->SetInput(inputs[i]); }; } std::vector<float> NeuralNetwork::GetOutputs() { for (size_t i = 1; i < layerMap.size() - 1; ++i) { for (auto& neuron : layerMap[i]){ neuron->RequestDataAndGetActionPotential(); } } std::vector<float> outputs; outputs.reserve(outputNeurons.size()); for(auto& outputNeuron : outputNeurons) { outputs.push_back(outputNeuron->RequestDataAndGetActionPotential()); } return outputs; } std::vector<float> NeuralNetwork::GetOutputs(const std::vector<float>& inputs) { SetInputs(inputs); return GetOutputs(); } void NeuralNetwork::InterpretInputsAndOutputs() { // Bias for (auto i = 0U; i < parameters.advanced.structure.numberOfBiasNeurons; i++) { neurons[i].SetInput(1.0f); } // Inputs for (auto i = 0U; i < parameters.numberOfInputs; i++) { inputNeurons[i] = &neurons[i + parameters.advanced.structure.numberOfBiasNeurons]; } // Outputs for (auto i = 0U; i < parameters.numberOfOutputs; i++) { outputNeurons[i] = &neurons[genome[i * parameters.numberOfOutputs].to]; } } bool NeuralNetwork::ShouldAddConnection() const { const bool hasChanceOccured = DidChanceOccure(parameters.advanced.mutation.chanceForConnectionalMutation); const bool hasSpaceForNewConnections = GetGenome().GetNeuronCount() > (parameters.numberOfInputs + parameters.numberOfOutputs + parameters.advanced.structure.numberOfBiasNeurons); return hasChanceOccured && hasSpaceForNewConnections; } bool NeuralNetwork::DidChanceOccure(float chance) { auto num = rand() % 100; return num < int(100.0f * chance); } size_t NeuralNetwork::GetRandomNumberBetween(size_t min, size_t max) { if (min == max) { return min; } return rand() % (max - min) + min; } void NeuralNetwork::AddRandomNeuron() { auto& randGene = GetRandomEnabledGene(); auto indexOfNewNeuron = genome.GetNeuronCount(); Gene g1; g1.from = randGene.from; g1.to = indexOfNewNeuron; g1.weight = randGene.weight; Gene g2; g2.from = indexOfNewNeuron; g2.to = randGene.to; g2.weight = randGene.weight; randGene.isEnabled = false; genome.AppendGene(std::move(g1)); genome.AppendGene(std::move(g2)); } void NeuralNetwork::AddRandomConnection() { size_t fromNeuronIndex = rand() % neurons.size(); size_t toNeuronIndex = (rand() % (neurons.size() -1)) + 1; if (fromNeuronIndex == toNeuronIndex) { if (fromNeuronIndex < (neurons.size() - 1)) { fromNeuronIndex++; } else { fromNeuronIndex--; } } Gene newConnectionGene; newConnectionGene.from = fromNeuronIndex; newConnectionGene.to = toNeuronIndex; auto& fromNeuron = neurons[fromNeuronIndex]; auto& toNeuron = neurons[toNeuronIndex]; auto& lowerNeuron = fromNeuron.GetLayer() <= toNeuron.GetLayer() ? fromNeuron : toNeuron; auto& higherNeuron = fromNeuron.GetLayer() <= toNeuron.GetLayer() ? toNeuron : fromNeuron; newConnectionGene.isRecursive = &lowerNeuron == &toNeuron; if (!genome.DoesContainGene(newConnectionGene)) { Neuron::IncomingConnection newConnection; newConnection.isRecursive = newConnectionGene.isRecursive; newConnection.neuron = &lowerNeuron; newConnection.weight = newConnectionGene.weight; genome.AppendGene(std::move(newConnectionGene)); higherNeuron.AddConnection(std::move(newConnection)); } } void NeuralNetwork::ShuffleWeights() { for (size_t i = 0; i < genome.GetGeneCount(); i++) { if (ShouldMutateWeight()) { MutateWeightOfGeneAt(i); } } } void NeuralNetwork::MutateWeightOfGeneAt(size_t index) { if (DidChanceOccure(parameters.advanced.mutation.chanceOfTotalWeightReset)) { genome[index].SetRandomWeight(); } else { PerturbWeightAt(index); } } void NeuralNetwork::PerturbWeightAt(size_t index) { constexpr float perturbanceBoundaries = 0.5f; auto perturbance = (float)(rand() % 10'000) / 9'999.0f * perturbanceBoundaries; if (rand() % 2) { perturbance = -perturbance; } genome[index].weight += perturbance; if (genome[index].weight < -1.0f) { genome[index].weight = -1.0f; } else if (genome[index].weight > 1.0f) { genome[index].weight = 1.0f; } } void NeuralNetwork::MutateGenesAndBuildNetwork() { if (ShouldAddConnection()) { BuildNetworkFromGenes(); AddRandomConnection(); } else if (ShouldAddNeuron()) { AddRandomNeuron(); BuildNetworkFromGenes(); } else { ShuffleWeights(); BuildNetworkFromGenes(); } } void NeuralNetwork::CategorizeNeuronsIntoLayers() { for (auto* out : outputNeurons) { CategorizeNeuronBranchIntoLayers(*out); } size_t highestLayer = 0U; for (auto* out : outputNeurons) { if (out->GetLayer() > highestLayer) { highestLayer = out->GetLayer(); }; } for (auto* out : outputNeurons) { out->SetLayer(highestLayer); } for (auto& neuron : neurons) { layerMap[neuron.GetLayer()].push_back(&neuron); } } void NeuralNetwork::CategorizeNeuronBranchIntoLayers(Neuron& currNode) { for (auto &in : currNode.GetConnections()) { if (!in.isRecursive) { CategorizeNeuronBranchIntoLayers(*in.neuron); currNode.SetLayer(in.neuron->GetLayer() + 1); } } } Gene& NeuralNetwork::GetRandomEnabledGene() { size_t num = rand() % genome.GetGeneCount(); auto& randGene = genome.begin() + num; while (randGene != genome.end() && !randGene->isEnabled) { ++randGene; } if (randGene == genome.end()) { randGene = genome.begin() + num; while (randGene != genome.begin() && !randGene->isEnabled) { --randGene; } } if (!randGene->isEnabled) { throw std::exception("Could not insert neuron because every gene is disabled"); } return *randGene; }<commit_msg>Same as last<commit_after>#include "neural_network.h" #include <cmath> #include <algorithm> #include <map> NeuralNetwork::NeuralNetwork(const TrainingParameters & parameters): parameters(parameters), genome(parameters), inputNeurons(parameters.numberOfInputs), outputNeurons(parameters.numberOfOutputs) { MutateGenesAndBuildNetwork(); } NeuralNetwork::NeuralNetwork(const Genome& genome): parameters(genome.GetTrainingParameters()), genome(genome), inputNeurons(genome.GetTrainingParameters().numberOfInputs), outputNeurons(genome.GetTrainingParameters().numberOfOutputs) { MutateGenesAndBuildNetwork(); } NeuralNetwork::NeuralNetwork(Genome&& genome): parameters(genome.GetTrainingParameters()), genome(std::move(genome)), inputNeurons(genome.GetTrainingParameters().numberOfInputs), outputNeurons(genome.GetTrainingParameters().numberOfOutputs) { MutateGenesAndBuildNetwork(); } NeuralNetwork::NeuralNetwork(const NeuralNetwork& other) : parameters(other.parameters), genome(other.genome), neurons(other.neurons.size()), inputNeurons(other.inputNeurons.size()), outputNeurons(other.outputNeurons.size()) { BuildNetworkFromGenes(); } NeuralNetwork::NeuralNetwork(NeuralNetwork&& other) : parameters(std::move(other.parameters)), genome(std::move(other.genome)), neurons(other.neurons.size()), inputNeurons(std::move(other.inputNeurons.size())), outputNeurons(std::move(other.outputNeurons.size())) { BuildNetworkFromGenes(); } NeuralNetwork& NeuralNetwork::operator=(const NeuralNetwork& other) { layerMap = other.layerMap; genome = other.genome; neurons = other.neurons; inputNeurons.resize(other.inputNeurons.size()); outputNeurons.resize(other.outputNeurons.size()); const_cast<TrainingParameters&>(this->parameters) = other.parameters; InterpretInputsAndOutputs(); return *this; } void NeuralNetwork::BuildNetworkFromGenes() { neurons.resize(genome.GetNeuronCount()); for (const auto& gene : genome) { if (gene.isEnabled) { Neuron::IncomingConnection connection; connection.neuron = &neurons[gene.from]; connection.weight = gene.weight; connection.isRecursive = gene.isRecursive; neurons[gene.to].AddConnection(std::move(connection)); } } InterpretInputsAndOutputs(); CategorizeNeuronsIntoLayers(); } void NeuralNetwork::SetInputs(const std::vector<float>& inputs) { if (inputNeurons.size() != inputs.size()) { throw std::out_of_range("Number of inputs provided doesn't match genetic information"); } for(size_t i = 0U; i < inputNeurons.size(); ++i) { inputNeurons[i]->SetInput(inputs[i]); }; } std::vector<float> NeuralNetwork::GetOutputs() { for (size_t i = 1; i < layerMap.size() - 1; ++i) { for (auto& neuron : layerMap[i]){ neuron->RequestDataAndGetActionPotential(); } } std::vector<float> outputs; outputs.reserve(outputNeurons.size()); for(auto& outputNeuron : outputNeurons) { outputs.push_back(outputNeuron->RequestDataAndGetActionPotential()); } return outputs; } std::vector<float> NeuralNetwork::GetOutputs(const std::vector<float>& inputs) { SetInputs(inputs); return GetOutputs(); } void NeuralNetwork::InterpretInputsAndOutputs() { // Bias for (auto i = 0U; i < parameters.advanced.structure.numberOfBiasNeurons; i++) { neurons[i].SetInput(1.0f); } // Inputs for (auto i = 0U; i < parameters.numberOfInputs; i++) { inputNeurons[i] = &neurons[i + parameters.advanced.structure.numberOfBiasNeurons]; } // Outputs for (auto i = 0U; i < parameters.numberOfOutputs; i++) { outputNeurons[i] = &neurons[genome[i * parameters.numberOfOutputs].to]; } } bool NeuralNetwork::ShouldAddConnection() const { const bool hasChanceOccured = DidChanceOccure(parameters.advanced.mutation.chanceForConnectionalMutation); const bool hasSpaceForNewConnections = GetGenome().GetNeuronCount() > (parameters.numberOfInputs + parameters.numberOfOutputs + parameters.advanced.structure.numberOfBiasNeurons); return hasChanceOccured && hasSpaceForNewConnections; } bool NeuralNetwork::DidChanceOccure(float chance) { auto num = rand() % 100; return num < int(100.0f * chance); } size_t NeuralNetwork::GetRandomNumberBetween(size_t min, size_t max) { if (min == max) { return min; } return rand() % (max - min) + min; } void NeuralNetwork::AddRandomNeuron() { auto& randGene = GetRandomEnabledGene(); auto indexOfNewNeuron = genome.GetNeuronCount(); Gene g1; g1.from = randGene.from; g1.to = indexOfNewNeuron; g1.weight = randGene.weight; Gene g2; g2.from = indexOfNewNeuron; g2.to = randGene.to; g2.weight = randGene.weight; randGene.isEnabled = false; genome.AppendGene(std::move(g1)); genome.AppendGene(std::move(g2)); } void NeuralNetwork::AddRandomConnection() { size_t fromNeuronIndex = rand() % neurons.size(); auto inputRange = parameters.advanced.structure.numberOfBiasNeurons + parameters.numberOfInputs; size_t toNeuronIndex = (rand() % (neurons.size() - inputRange)) + inputRange; if (fromNeuronIndex == toNeuronIndex) { if (fromNeuronIndex < (neurons.size() - 1)) { fromNeuronIndex++; } else { fromNeuronIndex--; } } Gene newConnectionGene; newConnectionGene.from = fromNeuronIndex; newConnectionGene.to = toNeuronIndex; auto& fromNeuron = neurons[fromNeuronIndex]; auto& toNeuron = neurons[toNeuronIndex]; auto& lowerNeuron = fromNeuron.GetLayer() <= toNeuron.GetLayer() ? fromNeuron : toNeuron; auto& higherNeuron = fromNeuron.GetLayer() <= toNeuron.GetLayer() ? toNeuron : fromNeuron; newConnectionGene.isRecursive = &lowerNeuron == &toNeuron; if (!genome.DoesContainGene(newConnectionGene)) { Neuron::IncomingConnection newConnection; newConnection.isRecursive = newConnectionGene.isRecursive; newConnection.neuron = &lowerNeuron; newConnection.weight = newConnectionGene.weight; genome.AppendGene(std::move(newConnectionGene)); higherNeuron.AddConnection(std::move(newConnection)); } } void NeuralNetwork::ShuffleWeights() { for (size_t i = 0; i < genome.GetGeneCount(); i++) { if (ShouldMutateWeight()) { MutateWeightOfGeneAt(i); } } } void NeuralNetwork::MutateWeightOfGeneAt(size_t index) { if (DidChanceOccure(parameters.advanced.mutation.chanceOfTotalWeightReset)) { genome[index].SetRandomWeight(); } else { PerturbWeightAt(index); } } void NeuralNetwork::PerturbWeightAt(size_t index) { constexpr float perturbanceBoundaries = 0.5f; auto perturbance = (float)(rand() % 10'000) / 9'999.0f * perturbanceBoundaries; if (rand() % 2) { perturbance = -perturbance; } genome[index].weight += perturbance; if (genome[index].weight < -1.0f) { genome[index].weight = -1.0f; } else if (genome[index].weight > 1.0f) { genome[index].weight = 1.0f; } } void NeuralNetwork::MutateGenesAndBuildNetwork() { if (ShouldAddConnection()) { BuildNetworkFromGenes(); AddRandomConnection(); } else if (ShouldAddNeuron()) { AddRandomNeuron(); BuildNetworkFromGenes(); } else { ShuffleWeights(); BuildNetworkFromGenes(); } } void NeuralNetwork::CategorizeNeuronsIntoLayers() { for (auto* out : outputNeurons) { CategorizeNeuronBranchIntoLayers(*out); } size_t highestLayer = 0U; for (auto* out : outputNeurons) { if (out->GetLayer() > highestLayer) { highestLayer = out->GetLayer(); }; } for (auto* out : outputNeurons) { out->SetLayer(highestLayer); } for (auto& neuron : neurons) { layerMap[neuron.GetLayer()].push_back(&neuron); } } void NeuralNetwork::CategorizeNeuronBranchIntoLayers(Neuron& currNode) { for (auto &in : currNode.GetConnections()) { if (!in.isRecursive) { CategorizeNeuronBranchIntoLayers(*in.neuron); currNode.SetLayer(in.neuron->GetLayer() + 1); } } } Gene& NeuralNetwork::GetRandomEnabledGene() { size_t num = rand() % genome.GetGeneCount(); auto& randGene = genome.begin() + num; while (randGene != genome.end() && !randGene->isEnabled) { ++randGene; } if (randGene == genome.end()) { randGene = genome.begin() + num; while (randGene != genome.begin() && !randGene->isEnabled) { --randGene; } } if (!randGene->isEnabled) { throw std::exception("Could not insert neuron because every gene is disabled"); } return *randGene; }<|endoftext|>
<commit_before>void CreateOnlineCalibPars(){ // Create TOF Online Calibration Object for reconstruction // and write it on CDB AliTOFcalib *tofcalib = new AliTOFcalib(); tofcalib->CreateCalArrays(); TObjArray *tofCalOnline = (TObjArray*) tofcalib->GetTOFCalArrayOnline(); // Write the offline calibration object on CDB AliCDBManager *man = AliCDBManager::Instance(); man->SetDefaultStorage("local://$ALICE"); Int_t nChannels = AliTOFGeometry::NSectors()*(2*(AliTOFGeometry::NStripC()+AliTOFGeometry::NStripB())+AliTOFGeometry::NStripA())*AliTOFGeometry::NpadZ()*AliTOFGeometry::NpadX(); Float_t delay=0.; Float_t meanDelay=0.3; Float_t sigmaDelay=0.08; TRandom *rnd = new TRandom(4357); for (Int_t ipad = 0 ; ipad<nChannels; ipad++){ AliTOFChannelOnline *calChannelOnline = (AliTOFChannelOnline*)tofCalOnline->At(ipad); delay = rnd->Gaus(meanDelay,sigmaDelay); calChannelOnline->SetDelay(delay); calChannelOnline->SetStatus(AliTOFChannelOnline::kTOFOnlineOk); } tofcalib->WriteParOnlineOnCDB("TOF/Calib"); return; } <commit_msg>Replacing obsolete file & Updating macro to create online delays in CDB to new calibration objects<commit_after>void CreateOnlineCalibPars(){ // Create TOF Online Calibration Object for reconstruction // and write it on CDB; // NB: only delay set, status still ok AliTOFcalib *tofcalib = new AliTOFcalib(); tofcalib->CreateCalArrays(); TObjArray *tofCalOnline = (TObjArray*) tofcalib->GetTOFCalArrayOnline(); TObjArray *tofCalOnlinePulser = (TObjArray*) tofcalib->GetTOFCalArrayOnlinePulser(); TObjArray *tofCalOnlineNoise = (TObjArray*) tofcalib->GetTOFCalArrayOnlineNoise(); TObjArray *tofCalOnlineHW = (TObjArray*) tofcalib->GetTOFCalArrayOnlineHW(); // Write the offline calibration object on CDB AliCDBManager *man = AliCDBManager::Instance(); man->SetDefaultStorage("local://$ALICE"); Int_t nChannels = AliTOFGeometry::NSectors()*(2*(AliTOFGeometry::NStripC()+AliTOFGeometry::NStripB())+AliTOFGeometry::NStripA())*AliTOFGeometry::NpadZ()*AliTOFGeometry::NpadX(); Float_t delay=0.; Float_t meanDelay=0.3; Float_t sigmaDelay=0.08; TRandom *rnd = new TRandom(4357); for (Int_t ipad = 0 ; ipad<nChannels; ipad++){ AliTOFChannelOnline *calChannelOnline = (AliTOFChannelOnline*)tofCalOnline->At(ipad); AliTOFChannelOnlineStatus *calChannelOnlinePulser = (AliTOFChannelOnlineStatus*)tofCalOnlinePulser->At(ipad); AliTOFChannelOnlineStatus *calChannelOnlineNoise = (AliTOFChannelOnlineStatus*)tofCalOnlineNoise->At(ipad); AliTOFChannelOnlineStatus *calChannelOnlineHW = (AliTOFChannelOnlineStatus*)tofCalOnlineHW->At(ipad); delay = rnd->Gaus(meanDelay,sigmaDelay); calChannelOnline->SetDelay(delay); calChannelOnlinePulser->SetStatus(AliTOFChannelOnlineStatus::kTOFPulserOk); calChannelOnlineNoise->SetStatus(AliTOFChannelOnlineStatus::kTOFNoiseOk); calChannelOnlineHW->SetStatus(AliTOFChannelOnlineStatus::kTOFHWOk); } tofcalib->WriteParOnlineOnCDB("TOF/Calib"); tofcalib->WriteParOnlinePulserOnCDB("TOF/Calib"); tofcalib->WriteParOnlineNoiseOnCDB("TOF/Calib"); tofcalib->WriteParOnlineHWOnCDB("TOF/Calib"); return; } <|endoftext|>
<commit_before>af438c5e-4b02-11e5-92ad-28cfe9171a43<commit_msg>fixed bug<commit_after>af508b0f-4b02-11e5-9ac4-28cfe9171a43<|endoftext|>
<commit_before>/* opendatacon * * Copyright (c) 2014: * * DCrip3fJguWgVCLrZFfA7sIGgvx1Ou3fHfCxnrz4svAi * yxeOtDhDCXf1Z4ApgXvX5ahqQmzRfJ2DoX8S05SqHA== * * 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. */ /* * JSONClientDataPort.cpp * * Created on: 22/07/2014 * Author: Neil Stephens <dearknarl@gmail.com> */ #include <thread> #include <chrono> #include <opendnp3/LogLevels.h> #include "JSONClientPort.h" JSONClientPort::JSONClientPort(std::string aName, std::string aConfFilename, const Json::Value aConfOverrides): JSONPort(aName, aConfFilename, aConfOverrides) {}; void JSONClientPort::BuildOrRebuild(asiodnp3::DNP3Manager& DNP3Mgr, openpal::LogFilters& LOG_LEVEL) {} void JSONClientPort::Enable() { if(enabled) return; JSONPortConf* pConf = static_cast<JSONPortConf*>(this->pConf.get()); try { asio::ip::tcp::resolver resolver(*pIOS); asio::ip::tcp::resolver::query query(pConf->mAddrConf.IP, std::to_string(pConf->mAddrConf.Port)); auto endpoint_iterator = resolver.resolve(query); pSock.reset(new asio::ip::tcp::socket(*pIOS)); asio::async_connect(*pSock.get(), endpoint_iterator,std::bind(&JSONClientPort::ConnectCompletionHandler,this,std::placeholders::_1)); } catch(std::exception& e) { std::string msg = "Problem opening connection: "+Name+": "+e.what(); auto log_entry = openpal::LogEntry("JSONClientPort", openpal::logflags::ERR,"", msg.c_str(), -1); pLoggers->Log(log_entry); return; } }; void JSONClientPort::ConnectCompletionHandler(asio::error_code err_code) { if(err_code) { std::string msg = Name+": Connect error: '"+err_code.message()+"'"; auto log_entry = openpal::LogEntry("JSONClientPort", openpal::logflags::INFO,"", msg.c_str(), -1); pLoggers->Log(log_entry); //try again later JSONPortConf* pConf = static_cast<JSONPortConf*>(this->pConf.get()); pTCPRetryTimer.reset(new Timer_t(*pIOS, std::chrono::milliseconds(pConf->retry_time_ms))); pTCPRetryTimer->async_wait( [this](asio::error_code err_code) { if(err_code != asio::error::operation_aborted) Enable(); }); return; } std::string msg = Name+": Connect success!"; auto log_entry = openpal::LogEntry("JSONClientPort", openpal::logflags::INFO,"", msg.c_str(), -1); pLoggers->Log(log_entry); enabled = true; Read(); } void JSONClientPort::Read() { asio::async_read(*pSock.get(), buf,asio::transfer_at_least(1), std::bind(&JSONClientPort::ReadCompletionHandler,this,std::placeholders::_1)); } void JSONClientPort::ReadCompletionHandler(asio::error_code err_code) { if(err_code) { if(err_code != asio::error::eof) { std::string msg = Name+": Read error: '"+err_code.message()+"'"; auto log_entry = openpal::LogEntry("JSONClientPort", openpal::logflags::ERR,"", msg.c_str(), -1); pLoggers->Log(log_entry); return; } else { std::string msg = Name+": '"+err_code.message()+"' : Retrying..."; auto log_entry = openpal::LogEntry("JSONClientPort", openpal::logflags::WARN,"", msg.c_str(), -1); pLoggers->Log(log_entry); } } //transfer content between matched braces to get processed as json char ch; std::string braced; size_t count_open_braces = 0, count_close_braces = 0; while(buf.size() > 0) { ch = buf.sgetc(); buf.consume(1); if(ch=='{') { count_open_braces++; if(count_open_braces == 1) braced.clear(); //discard anything before the first brace } if(ch=='}') { count_close_braces++; if(count_close_braces > count_open_braces) { braced.clear(); //discard because it must be outside matched braces count_close_braces = count_open_braces = 0; } } braced.push_back(ch); //check if we've found a match to the first brace if(count_open_braces > 0 && count_close_braces == count_open_braces) { ProcessBraced(braced); braced.clear(); count_close_braces = count_open_braces = 0; } } //put back the leftovers for(auto ch : braced) buf.sputc(ch); if(!err_code) //not eof - read more Read(); else { //remote end closed the connection - reset and try reconnecting Disable(); Enable(); } } //At this point we have a whole (hopefully JSON) object - ie. {.*} //Here we parse it and extract any paths that match our point config void JSONClientPort::ProcessBraced(std::string braced) { Json::Value JSONRoot; // will contain the root value after parsing. Json::Reader JSONReader; bool parsing_success = JSONReader.parse(braced, JSONRoot); if (parsing_success) { JSONPortConf* pConf = static_cast<JSONPortConf*>(this->pConf.get()); //little functor to traverse any paths, starting at the root //pass a JSON array of nodes representing the path (that's how we store our point config after all) auto TraversePath = [&JSONRoot](const Json::Value nodes) { //val will traverse any paths, starting at the root auto val = JSONRoot; //traverse for(unsigned int n = 0; n < nodes.size(); ++n) if((val = val[nodes[n].asCString()]).isNull()) break; return val; }; Json::Value timestamp_val = TraversePath(pConf->pPointConf->TimestampPath); for(auto& point_pair : pConf->pPointConf->Analogs) { Json::Value val = TraversePath(point_pair.second["JSONPath"]); //if the path existed, load up the point if(!val.isNull()) { if(val.isNumeric()) LoadT(opendnp3::Analog(val.asDouble(),static_cast<uint8_t>(opendnp3::AnalogQuality::ONLINE)),point_pair.first, timestamp_val); else if(val.isString()) { double value; try { value = std::stod(val.asString()); } catch(std::exception&) { LoadT(opendnp3::Analog(0,static_cast<uint8_t>(opendnp3::AnalogQuality::COMM_LOST)),point_pair.first, timestamp_val); continue; } LoadT(opendnp3::Analog(value,static_cast<uint8_t>(opendnp3::AnalogQuality::ONLINE)),point_pair.first, timestamp_val); } } } for(auto& point_pair : pConf->pPointConf->Binaries) { Json::Value val = TraversePath(point_pair.second["JSONPath"]); //if the path existed, load up the point if(!val.isNull()) { bool true_val = false; opendnp3::BinaryQuality qual = opendnp3::BinaryQuality::ONLINE; if(!point_pair.second["TrueVal"].isNull()) { true_val = (val == point_pair.second["TrueVal"]); if(!point_pair.second["FalseVal"].isNull()) if (!true_val && (val != point_pair.second["FalseVal"])) qual = opendnp3::BinaryQuality::COMM_LOST; } else if(!point_pair.second["FlaseVal"].isNull()) true_val = !(val == point_pair.second["FalseVal"]); else if(val.isNumeric() || val.isBool()) true_val = val.asBool(); else if(val.isString()) { true_val = (val.asString() == "true"); if(!true_val && (val.asString() != "false")) qual = opendnp3::BinaryQuality::COMM_LOST; } else qual = opendnp3::BinaryQuality::COMM_LOST; LoadT(opendnp3::Binary(true_val,static_cast<uint8_t>(qual)),point_pair.first,timestamp_val); } } //TODO: implement controls } else { std::string msg = "Error parsing JSON string: '"+braced+"'"; auto log_entry = openpal::LogEntry("JSONClientPort", openpal::logflags::WARN,"", msg.c_str(), -1); pLoggers->Log(log_entry); } } template<typename T> inline void JSONClientPort::LoadT(T meas, uint16_t index, Json::Value timestamp_val) { std::string msg = "Measurement Event '"+std::string(typeid(meas).name())+"'"; auto log_entry = openpal::LogEntry("JSONClientPort", openpal::logflags::DBG,"", msg.c_str(), -1); pLoggers->Log(log_entry); if(!timestamp_val.isNull() && timestamp_val.isUInt64()) { meas = T(meas.value, meas.quality, timestamp_val.asUInt64()); } for(auto IOHandler_pair : Subscribers) IOHandler_pair.second->Event(meas, index, this->Name); } void JSONClientPort::Disable() { //cancel the retry timer (otherwise it would tie up the io_service on shutdown) if(pTCPRetryTimer.get() != nullptr) pTCPRetryTimer->cancel(); //shutdown and close socket by using destructor pSock.reset(nullptr); enabled = false; }; <commit_msg>JSONClientPort: Fix incorrect check of JSON point FalseVal<commit_after>/* opendatacon * * Copyright (c) 2014: * * DCrip3fJguWgVCLrZFfA7sIGgvx1Ou3fHfCxnrz4svAi * yxeOtDhDCXf1Z4ApgXvX5ahqQmzRfJ2DoX8S05SqHA== * * 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. */ /* * JSONClientDataPort.cpp * * Created on: 22/07/2014 * Author: Neil Stephens <dearknarl@gmail.com> */ #include <thread> #include <chrono> #include <opendnp3/LogLevels.h> #include "JSONClientPort.h" JSONClientPort::JSONClientPort(std::string aName, std::string aConfFilename, const Json::Value aConfOverrides): JSONPort(aName, aConfFilename, aConfOverrides) {}; void JSONClientPort::BuildOrRebuild(asiodnp3::DNP3Manager& DNP3Mgr, openpal::LogFilters& LOG_LEVEL) {} void JSONClientPort::Enable() { if(enabled) return; JSONPortConf* pConf = static_cast<JSONPortConf*>(this->pConf.get()); try { asio::ip::tcp::resolver resolver(*pIOS); asio::ip::tcp::resolver::query query(pConf->mAddrConf.IP, std::to_string(pConf->mAddrConf.Port)); auto endpoint_iterator = resolver.resolve(query); pSock.reset(new asio::ip::tcp::socket(*pIOS)); asio::async_connect(*pSock.get(), endpoint_iterator,std::bind(&JSONClientPort::ConnectCompletionHandler,this,std::placeholders::_1)); } catch(std::exception& e) { std::string msg = "Problem opening connection: "+Name+": "+e.what(); auto log_entry = openpal::LogEntry("JSONClientPort", openpal::logflags::ERR,"", msg.c_str(), -1); pLoggers->Log(log_entry); return; } }; void JSONClientPort::ConnectCompletionHandler(asio::error_code err_code) { if(err_code) { std::string msg = Name+": Connect error: '"+err_code.message()+"'"; auto log_entry = openpal::LogEntry("JSONClientPort", openpal::logflags::INFO,"", msg.c_str(), -1); pLoggers->Log(log_entry); //try again later JSONPortConf* pConf = static_cast<JSONPortConf*>(this->pConf.get()); pTCPRetryTimer.reset(new Timer_t(*pIOS, std::chrono::milliseconds(pConf->retry_time_ms))); pTCPRetryTimer->async_wait( [this](asio::error_code err_code) { if(err_code != asio::error::operation_aborted) Enable(); }); return; } std::string msg = Name+": Connect success!"; auto log_entry = openpal::LogEntry("JSONClientPort", openpal::logflags::INFO,"", msg.c_str(), -1); pLoggers->Log(log_entry); enabled = true; Read(); } void JSONClientPort::Read() { asio::async_read(*pSock.get(), buf,asio::transfer_at_least(1), std::bind(&JSONClientPort::ReadCompletionHandler,this,std::placeholders::_1)); } void JSONClientPort::ReadCompletionHandler(asio::error_code err_code) { if(err_code) { if(err_code != asio::error::eof) { std::string msg = Name+": Read error: '"+err_code.message()+"'"; auto log_entry = openpal::LogEntry("JSONClientPort", openpal::logflags::ERR,"", msg.c_str(), -1); pLoggers->Log(log_entry); return; } else { std::string msg = Name+": '"+err_code.message()+"' : Retrying..."; auto log_entry = openpal::LogEntry("JSONClientPort", openpal::logflags::WARN,"", msg.c_str(), -1); pLoggers->Log(log_entry); } } //transfer content between matched braces to get processed as json char ch; std::string braced; size_t count_open_braces = 0, count_close_braces = 0; while(buf.size() > 0) { ch = buf.sgetc(); buf.consume(1); if(ch=='{') { count_open_braces++; if(count_open_braces == 1) braced.clear(); //discard anything before the first brace } if(ch=='}') { count_close_braces++; if(count_close_braces > count_open_braces) { braced.clear(); //discard because it must be outside matched braces count_close_braces = count_open_braces = 0; } } braced.push_back(ch); //check if we've found a match to the first brace if(count_open_braces > 0 && count_close_braces == count_open_braces) { ProcessBraced(braced); braced.clear(); count_close_braces = count_open_braces = 0; } } //put back the leftovers for(auto ch : braced) buf.sputc(ch); if(!err_code) //not eof - read more Read(); else { //remote end closed the connection - reset and try reconnecting Disable(); Enable(); } } //At this point we have a whole (hopefully JSON) object - ie. {.*} //Here we parse it and extract any paths that match our point config void JSONClientPort::ProcessBraced(std::string braced) { Json::Value JSONRoot; // will contain the root value after parsing. Json::Reader JSONReader; bool parsing_success = JSONReader.parse(braced, JSONRoot); if (parsing_success) { JSONPortConf* pConf = static_cast<JSONPortConf*>(this->pConf.get()); //little functor to traverse any paths, starting at the root //pass a JSON array of nodes representing the path (that's how we store our point config after all) auto TraversePath = [&JSONRoot](const Json::Value nodes) { //val will traverse any paths, starting at the root auto val = JSONRoot; //traverse for(unsigned int n = 0; n < nodes.size(); ++n) if((val = val[nodes[n].asCString()]).isNull()) break; return val; }; Json::Value timestamp_val = TraversePath(pConf->pPointConf->TimestampPath); for(auto& point_pair : pConf->pPointConf->Analogs) { Json::Value val = TraversePath(point_pair.second["JSONPath"]); //if the path existed, load up the point if(!val.isNull()) { if(val.isNumeric()) LoadT(opendnp3::Analog(val.asDouble(),static_cast<uint8_t>(opendnp3::AnalogQuality::ONLINE)),point_pair.first, timestamp_val); else if(val.isString()) { double value; try { value = std::stod(val.asString()); } catch(std::exception&) { LoadT(opendnp3::Analog(0,static_cast<uint8_t>(opendnp3::AnalogQuality::COMM_LOST)),point_pair.first, timestamp_val); continue; } LoadT(opendnp3::Analog(value,static_cast<uint8_t>(opendnp3::AnalogQuality::ONLINE)),point_pair.first, timestamp_val); } } } for(auto& point_pair : pConf->pPointConf->Binaries) { Json::Value val = TraversePath(point_pair.second["JSONPath"]); //if the path existed, load up the point if(!val.isNull()) { bool true_val = false; opendnp3::BinaryQuality qual = opendnp3::BinaryQuality::ONLINE; if(!point_pair.second["TrueVal"].isNull()) { true_val = (val == point_pair.second["TrueVal"]); if(!point_pair.second["FalseVal"].isNull()) if (!true_val && (val != point_pair.second["FalseVal"])) qual = opendnp3::BinaryQuality::COMM_LOST; } else if(!point_pair.second["FalseVal"].isNull()) true_val = !(val == point_pair.second["FalseVal"]); else if(val.isNumeric() || val.isBool()) true_val = val.asBool(); else if(val.isString()) { true_val = (val.asString() == "true"); if(!true_val && (val.asString() != "false")) qual = opendnp3::BinaryQuality::COMM_LOST; } else qual = opendnp3::BinaryQuality::COMM_LOST; LoadT(opendnp3::Binary(true_val,static_cast<uint8_t>(qual)),point_pair.first,timestamp_val); } } //TODO: implement controls } else { std::string msg = "Error parsing JSON string: '"+braced+"'"; auto log_entry = openpal::LogEntry("JSONClientPort", openpal::logflags::WARN,"", msg.c_str(), -1); pLoggers->Log(log_entry); } } template<typename T> inline void JSONClientPort::LoadT(T meas, uint16_t index, Json::Value timestamp_val) { std::string msg = "Measurement Event '"+std::string(typeid(meas).name())+"'"; auto log_entry = openpal::LogEntry("JSONClientPort", openpal::logflags::DBG,"", msg.c_str(), -1); pLoggers->Log(log_entry); if(!timestamp_val.isNull() && timestamp_val.isUInt64()) { meas = T(meas.value, meas.quality, timestamp_val.asUInt64()); } for(auto IOHandler_pair : Subscribers) IOHandler_pair.second->Event(meas, index, this->Name); } void JSONClientPort::Disable() { //cancel the retry timer (otherwise it would tie up the io_service on shutdown) if(pTCPRetryTimer.get() != nullptr) pTCPRetryTimer->cancel(); //shutdown and close socket by using destructor pSock.reset(nullptr); enabled = false; }; <|endoftext|>
<commit_before>616d1ee1-2e4f-11e5-95b7-28cfe91dbc4b<commit_msg>617448e6-2e4f-11e5-a347-28cfe91dbc4b<commit_after>617448e6-2e4f-11e5-a347-28cfe91dbc4b<|endoftext|>
<commit_before>/********************************* ********************************** ** ** ** Wababa: Simple Question Game ** ** ** ********************************** *********************************/ // Preprocessor Commands #include <iostream> #include <string> //Global Scope Namespace using namespace std; // Wababa Answer Variables int a = 5; int apples; string b = "woof"; string c = "sally"; string bark; string dollname; void answerA (int answer, int thevar) { if ( answer == thevar ) cout << "Yes!\n"; else cout << "Wrong!\n"; } void answerQ (string answer, string thevar) { if ( answer == thevar ) cout << "Yes!\n"; else cout << "Wrong!\n"; } int main () { // Wababa Welcome. string wababa; wababa = "Wababa!\n\n"; cout << wababa; // Question #1 cout << "How many red items are there: "; cin >> apples; answerA(apples, a); // Question #2 cout << "What did the pet say: "; cin >> bark; answerQ(bark,b); // Question #3 cout << "What's her name: "; cin >> dollname; answerQ(dollname,c); // Returns 0 return 0; } <commit_msg>Made the third answer more cryptic.<commit_after>/********************************* ********************************** ** ** ** Wababa: Simple Question Game ** ** ** ********************************** *********************************/ // Preprocessor Commands #include <iostream> #include <string> //Global Scope Namespace using namespace std; // Wababa Answer Variables int a = 5; int apples; string b = "woof"; string c = "sally"; string bark; string dollname; void answerA (int answer, int thevar) { if ( answer == thevar ) cout << "Yes!\n"; else cout << "Wrong!\n"; } void answerQ (string answer, string thevar) { if ( answer == thevar ) cout << "Yes!\n"; else cout << "Wrong!\n"; } int main () { // Wababa Welcome. string wababa; wababa = "Wababa!\n\n"; cout << wababa; // Question #1 cout << "How many red items are there: "; cin >> apples; answerA(apples, a); // Question #2 cout << "What did the pet say: "; cin >> bark; answerQ(bark,b); // Question #3 cout << "What's the pretty thing's name: "; cin >> dollname; answerQ(dollname,c); // Returns 0 return 0; } <|endoftext|>
<commit_before>b21b275c-327f-11e5-b559-9cf387a8033e<commit_msg>b2214dc7-327f-11e5-80b0-9cf387a8033e<commit_after>b2214dc7-327f-11e5-80b0-9cf387a8033e<|endoftext|>
<commit_before>7fd69545-2e4f-11e5-abbf-28cfe91dbc4b<commit_msg>7fdd95ee-2e4f-11e5-afaa-28cfe91dbc4b<commit_after>7fdd95ee-2e4f-11e5-afaa-28cfe91dbc4b<|endoftext|>
<commit_before>60bb47a2-2d16-11e5-af21-0401358ea401<commit_msg>60bb47a3-2d16-11e5-af21-0401358ea401<commit_after>60bb47a3-2d16-11e5-af21-0401358ea401<|endoftext|>
<commit_before>8562791c-2d15-11e5-af21-0401358ea401<commit_msg>8562791d-2d15-11e5-af21-0401358ea401<commit_after>8562791d-2d15-11e5-af21-0401358ea401<|endoftext|>
<commit_before>#define PARSE_TABLE_ROWS 18 #define PARSE_TABLE_COLS 7 #include "parse.h" #include <iostream> #include <string> #include <vector> #include <utility> using namespace parse; struct S; struct V; struct E; struct S : public Nonterminal<S> { private: std::string s; public: S(E e); S(V v, std::string s, E e); std::string to_string() { return s; } }; struct V : public Nonterminal<V> { private: std::string s; public: V(std::string s); V(std::string s, E e); std::string to_string() { return s; } }; struct E : public Nonterminal<E> { private: std::string s; public: E(V v); std::string to_string() { return s; } }; S::S(E e) : s("E[" + e.to_string() + "]") {} S::S(V v, std::string s, E e) : s("V[" + v.to_string() + "], " + s + ", E[" + e.to_string() + "]") {} V::V(std::string s) : s(s) {} V::V(std::string s, E e) : s(s + ", E[" + e.to_string() + "]") {} E::E(V v) : s("V[" + v.to_string() + "]") {} struct Rule1 { S operator()(V v, std::string s, E e) { return S(v, s, e); } }; struct Rule2 { S operator()(E e) { return S(e); } }; struct Rule3 { E operator()(V v) { return E(v); } }; struct Rule4 { V operator()(std::string s) { return V(s); } }; struct Rule5 { V operator()(std::string s, E e) { return V(s, e); } }; int main(int argc, char* argv []) { using x = Terminal<0>; using deref = Terminal<1>; using assign = Terminal<2>; using Parser = LrParser< Production< S, Right<V, assign, E>, Rule1 >, Production< S, Right<E>, Rule2 >, Production< E, Right<V>, Rule3 >, Production< V, Right<x>, Rule4 >, Production< V, Right<deref, E>, Rule5 > >; std::vector<std::pair<std::string, int>> tokens = { {"x", 0}, {"=", 2}, {"*", 1}, {"*", 1}, {"*", 1}, {"x", 0}, {"", -1}}; auto res = Parser::parse(tokens.begin(), tokens.end()); if(res) { std::cout << res.get().to_string() << std::endl; } else { std::cout << "Input is malformed" << std::endl; } return 0; } <commit_msg>Delete main.cpp<commit_after><|endoftext|>
<commit_before>db8a68ab-327f-11e5-8267-9cf387a8033e<commit_msg>db91ffb8-327f-11e5-b97f-9cf387a8033e<commit_after>db91ffb8-327f-11e5-b97f-9cf387a8033e<|endoftext|>
<commit_before>d4f662c2-35ca-11e5-9100-6c40088e03e4<commit_msg>d4fd1298-35ca-11e5-93c7-6c40088e03e4<commit_after>d4fd1298-35ca-11e5-93c7-6c40088e03e4<|endoftext|>
<commit_before>1c9c69ba-2f67-11e5-8551-6c40088e03e4<commit_msg>1ca636c0-2f67-11e5-bdfe-6c40088e03e4<commit_after>1ca636c0-2f67-11e5-bdfe-6c40088e03e4<|endoftext|>
<commit_before>788ff194-2d53-11e5-baeb-247703a38240<commit_msg>78907498-2d53-11e5-baeb-247703a38240<commit_after>78907498-2d53-11e5-baeb-247703a38240<|endoftext|>
<commit_before>778d6fce-2d53-11e5-baeb-247703a38240<commit_msg>778def58-2d53-11e5-baeb-247703a38240<commit_after>778def58-2d53-11e5-baeb-247703a38240<|endoftext|>
<commit_before>439d10d8-2e3a-11e5-a2c5-c03896053bdd<commit_msg>43ab443a-2e3a-11e5-9b5d-c03896053bdd<commit_after>43ab443a-2e3a-11e5-9b5d-c03896053bdd<|endoftext|>
<commit_before>d2bda963-327f-11e5-8a93-9cf387a8033e<commit_msg>d2c3d42e-327f-11e5-bcb1-9cf387a8033e<commit_after>d2c3d42e-327f-11e5-bcb1-9cf387a8033e<|endoftext|>
<commit_before>// Rectangles #include <cassert> #include <fstream> #include <iostream> #include <unordered_map> #include <vector> #include "named_rect.h" struct Results { std::vector<char> overlaps; std::vector<char> contains; std::vector<char> containedBy; std::vector<char> touches; }; using ResultsType = std::unordered_map<char, Results>; // Get the corresponding Result object for the given rectangle name. Results* getResults(ResultsType* results, char name) { bool inserted = false; auto it = results->find(name); if (it == std::end(*results)) std::tie(it, inserted) = results->insert(std::make_pair(name, Results())); return &it->second; } // Given a list of rectangle names, print them out in a comma separated line. void printNames(std::ostream& os, const std::vector<char>& names) { if (names.empty()) { os << '0'; } else { const size_t size = names.size(); for (size_t i = 0; i < size; ++i) { os << names[i]; if (i < size - 1) os << ','; } } os << std::endl; } void printResults(std::ostream& os, const ResultsType& results) { for (const auto& it : results) { os << it.first << std::endl; printNames(os, it.second.overlaps); printNames(os, it.second.contains); printNames(os, it.second.containedBy); printNames(os, it.second.touches); os << std::endl; } } int main() { std::vector<NamedRect> rectangles; // Read the rectangles in the file into our list of rectangles. readRectanglesFromFile("rectangles.txt", &rectangles); for (const auto& rect : rectangles) std::cout << "Rect: " << rect << std::endl; ResultsType results; for (const auto& first : rectangles) { Results* r = getResults(&results, first.name); for (const auto& second : rectangles) { if (first.rect.overlaps(second.rect)) r->overlaps.push_back(second.name); if (first.rect.contains(second.rect)) r->contains.push_back(second.name); if (second.rect.contains(first.rect)) r->containedBy.push_back(first.name); if (first.rect.touches(second.rect)) r->touches.push_back(second.name); } } #if 0 printResults(std::cout, results); #else std::ofstream outFile("results.txt", std::ios::out); printResults(outFile, results); #endif return 0; } <commit_msg>Added some logging.<commit_after>// Rectangles #include <cassert> #include <fstream> #include <iostream> #include <unordered_map> #include <vector> #include "named_rect.h" struct Results { std::vector<char> overlaps; std::vector<char> contains; std::vector<char> containedBy; std::vector<char> touches; }; using ResultsType = std::unordered_map<char, Results>; // Get the corresponding Result object for the given rectangle name. Results* getResults(ResultsType* results, char name) { bool inserted = false; auto it = results->find(name); if (it == std::end(*results)) std::tie(it, inserted) = results->insert(std::make_pair(name, Results())); return &it->second; } // Given a list of rectangle names, print them out in a comma separated line. void printNames(std::ostream& os, const std::vector<char>& names) { if (names.empty()) { os << '0'; } else { const size_t size = names.size(); for (size_t i = 0; i < size; ++i) { os << names[i]; if (i < size - 1) os << ','; } } os << std::endl; } void printResults(std::ostream& os, const ResultsType& results) { for (const auto& it : results) { os << it.first << std::endl; printNames(os, it.second.overlaps); printNames(os, it.second.contains); printNames(os, it.second.containedBy); printNames(os, it.second.touches); os << std::endl; } } int main() { std::vector<NamedRect> rectangles; // Read the rectangles in the file into our list of rectangles. std::cout << "Loading rectangles from file: rectangles.txt" << std::endl; readRectanglesFromFile("rectangles.txt", &rectangles); #if 0 for (const auto& rect : rectangles) std::cout << "Rect: " << rect << std::endl; #endif // 0 std::cout << "Calculating results..." << std::endl; ResultsType results; for (const auto& first : rectangles) { Results* r = getResults(&results, first.name); for (const auto& second : rectangles) { if (first.rect.overlaps(second.rect)) r->overlaps.push_back(second.name); if (first.rect.contains(second.rect)) r->contains.push_back(second.name); if (second.rect.contains(first.rect)) r->containedBy.push_back(first.name); if (first.rect.touches(second.rect)) r->touches.push_back(second.name); } } std::cout << "Writing output to file: results.txt" << std::endl; #if 0 printResults(std::cout, results); #else std::ofstream outFile("results.txt", std::ios::out); printResults(outFile, results); #endif return 0; } <|endoftext|>
<commit_before>25183ab0-2e4f-11e5-8fb0-28cfe91dbc4b<commit_msg>251efe70-2e4f-11e5-9004-28cfe91dbc4b<commit_after>251efe70-2e4f-11e5-9004-28cfe91dbc4b<|endoftext|>
<commit_before>8597401e-4b02-11e5-9ec6-28cfe9171a43<commit_msg>more fixes<commit_after>85a2c1d1-4b02-11e5-bd19-28cfe9171a43<|endoftext|>
<commit_before>#include "mitkContour.h" #include "mitkCommon.h" #include <fstream> int mitkContourTest(int argc, char* argv[]) { mitk::Contour::Pointer contour; std::cout << "Testing mitk::Contour::New(): "; contour = mitk::Contour::New(); if (contour.IsNull()) { std::cout<<"[FAILED]"<<std::endl; return EXIT_FAILURE; } else { std::cout<<"[PASSED]"<<std::endl; } std::cout << "Testing mitk::Contour::AddVertex(): "; mitk::ITKPoint3D p; p.Fill(0); contour->AddVertex(p); p.Fill(1); contour->AddVertex(p); p.Fill(2); contour->AddVertex(p); if (contour->GetNumberOfPoints() != 3) { std::cout<<"[FAILED]"<<std::endl; return EXIT_FAILURE; } else { std::cout<<"[PASSED]"<<std::endl; } std::cout << "Testing mitk::Contour::GetPoints()"; mitk::Contour::PointsContainerPointer points = contour->GetPoints(); if ( points.IsNull() ) { std::cout<<"[FAILED]"<<std::endl; return EXIT_FAILURE; } else { std::cout<<"[PASSED]"<<std::endl; } std::cout << "Testing mitk::Contour::Initialize()"; contour->Initialize(); if (contour->GetNumberOfPoints() != 0) { std::cout<<"[FAILED]"<<std::endl; return EXIT_FAILURE; } else { std::cout<<"[PASSED]"<<std::endl; } contour->SetPoints(points); if ( contour->GetNumberOfPoints() != 3) { std::cout<<"[FAILED]"<<std::endl; return EXIT_FAILURE; }; mitk::Contour::PathPointer path = contour->GetContourPath(); if ( path.IsNull() ) { return EXIT_FAILURE; } std::cout<<"[TEST DONE]"<<std::endl; return EXIT_SUCCESS; } <commit_msg>extended<commit_after>#include "mitkContour.h" #include "mitkCommon.h" #include <fstream> int mitkContourTest(int argc, char* argv[]) { mitk::Contour::Pointer contour; std::cout << "Testing mitk::Contour::New(): "; contour = mitk::Contour::New(); if (contour.IsNull()) { std::cout<<"[FAILED]"<<std::endl; return EXIT_FAILURE; } else { std::cout<<"[PASSED]"<<std::endl; } std::cout << "Testing mitk::Contour::AddVertex(): "; mitk::ITKPoint3D p; p.Fill(0); contour->AddVertex(p); p.Fill(1); contour->AddVertex(p); p.Fill(2); contour->AddVertex(p); if (contour->GetNumberOfPoints() != 3) { std::cout<<"[FAILED]"<<std::endl; return EXIT_FAILURE; } else { std::cout<<"[PASSED]"<<std::endl; } std::cout << "Testing mitk::Contour::GetPoints()"; mitk::Contour::PointsContainerPointer points = contour->GetPoints(); if ( points.IsNull() ) { std::cout<<"[FAILED]"<<std::endl; return EXIT_FAILURE; } else { std::cout<<"[PASSED]"<<std::endl; } std::cout << "Testing mitk::Contour::Initialize()"; contour->Initialize(); if (contour->GetNumberOfPoints() != 0) { std::cout<<"[FAILED]"<<std::endl; return EXIT_FAILURE; } else { std::cout<<"[PASSED]"<<std::endl; } contour->SetPoints(points); if ( contour->GetNumberOfPoints() != 3) { std::cout<<"[FAILED]"<<std::endl; return EXIT_FAILURE; }; mitk::Contour::PathPointer path = contour->GetContourPath(); if ( path.IsNull() ) { return EXIT_FAILURE; } contour->UpdateOutputInformation(); contour->SetClosed(false); if (contour->GetClosed()) { std::cout<<"[FAILED] "<<std::endl; return EXIT_FAILURE; } std::cout<<"[TEST DONE]"<<std::endl; return EXIT_SUCCESS; } <|endoftext|>
<commit_before>21e3e705-2d3f-11e5-91df-c82a142b6f9b<commit_msg>2257694a-2d3f-11e5-80ba-c82a142b6f9b<commit_after>2257694a-2d3f-11e5-80ba-c82a142b6f9b<|endoftext|>
<commit_before>85627909-2d15-11e5-af21-0401358ea401<commit_msg>8562790a-2d15-11e5-af21-0401358ea401<commit_after>8562790a-2d15-11e5-af21-0401358ea401<|endoftext|>
<commit_before>61d52870-2749-11e6-8201-e0f84713e7b8<commit_msg>lets try again<commit_after>61e17863-2749-11e6-810c-e0f84713e7b8<|endoftext|>
<commit_before>#include <cstdio> #include <iostream> #include <vector> #include <opencv2/highgui.hpp> #include <opencv2/imgproc.hpp> #include <opencv2/objdetect.hpp> #include <opencv2/opencv.hpp> #include "linefinder.h" #define PI 3.1415926 using namespace cv; using namespace std; int main() { int houghVote=200; string arg=argv[1]; bool showSteps=argv[2]; string window_name="Processed Video"; namedWindow(window_name,CV_WINDOW_KEEPRATIO); //resizable window; VideoCapture capture(arg); if (!capture.isOpened()) //if this fails, try to open as a video camera, through the use of an integer param { capture.open(atoi(arg.c_str())); } double dWidth=capture.get(CV_CAP_PROP_FRAME_WIDTH); //get the width of frames of the video double dHeight=capture.get(CV_CAP_PROP_FRAME_HEIGHT); //get the height of frames of the video cout<<"Frame Size = "<<dWidth<<"x"<<dHeight<<endl; Size frameSize(static_cast<int>(dWidth),static_cast<int>(dHeight)); //VideoWriter oVideoWriter("LaneDetection.avi",CV_FOURCC('P','I','M','1'),20,frameSize,true); //initialize the VideoWriter object Mat image; image=imread(argv[1]); while(1) { capture>>image; if(image.empty()) break; Mat gray; cvtColor(image,gray,CV_RGB2GRAY); //vector<string> codes; //Mat corners; //findDataMatrix(gray, codes, corners); //drawDataMatrixCodes(image, codes, corners); Rect roi(0,image.cols/3,image.cols-1,image.rows-image.cols/3);// set the ROI for the image Mat imgROI=image(roi); //Display the image if(showSteps) { namedWindow("Original Image"); imshow("Original Image",imgROI); } //Canny algorithm Mat contours; Canny(imgROI,contours,50,250); Mat contoursInv; threshold(contours,contoursInv,128,255,THRESH_BINARY_INV); //Display Canny image if(showSteps) { namedWindow("Contours"); imshow("Contours1",contoursInv); } /* *Hough tranform for line detection with feedback *Increase by 25 for the next frame if we found some lines. *This is so we don't miss other lines that may crop up in the next frame *but at the same time we don't want to start the feed back loop from scratch. */ vector<Vec2f> lines; if(houghVote<1 or lines.size() > 2) { //lost all lines. reset houghVote=200; } else { houghVote+=25; } while(lines.size()<5&&houghVote>0) { HoughLines(contours,lines,1,PI/180,houghVote); houghVote-=5; } cout<<houghVote<<"\n"; Mat result(imgROI.size(),CV_8U,Scalar(255)); imgROI.copyTo(result); //Draw the limes vector<Vec2f>::const_iterator it=lines.begin(); Mat hough(imgROI.size(),CV_8U,Scalar(0)); while(it!=lines.end()) { float rho=(*it)[0]; //first element is distance rho float theta=(*it)[1]; //second element is angle theta if(theta>0.09 && theta<1.48||theta < 3.14 && theta > 1.66) // filter to remove vertical and horizontal lines { // point of intersection of the line with first row Point pt1(rho/cos(theta),0); // point of intersection of the line with last row Point pt2((rho-result.rows*sin(theta))/cos(theta),result.rows); // draw a white line line(result,pt1,pt2,Scalar(255),8); line(hough,pt1,pt2,Scalar(255),8); } //cout << "line: (" << rho << "," << theta << ")\n"; ++it; } //Display the detected line image if(showSteps) { namedWindow("Detected Lines with Hough"); imshow("Detected Lines with Hough",result); } //Create LineFinder instance LineFinder ld; //Set probabilistic Hough parameters ld.setLineLengthAndGap(60,10); ld.setMinVote(4); //Detect lines vector<Vec4i> li=ld.findLines(contours); Mat houghP(imgROI.size(),CV_8U,Scalar(0)); ld.setShift(0); ld.drawDetectedLines(houghP); cout<<"First Hough"<<"\n"; if(showSteps) { namedWindow("Detected Lines with HoughP"); imshow("Detected Lines with HoughP",houghP); } //bitwise AND of the two hough images bitwise_and(houghP,hough,houghP); Mat houghPinv(imgROI.size(),CV_8U,Scalar(0)); Mat dst(imgROI.size(),CV_8U,Scalar(0)); threshold(houghP,houghPinv,150,255,THRESH_BINARY_INV); // threshold and invert to black lines if(showSteps) { namedWindow("Detected Lines with Bitwise"); imshow("Detected Lines with Bitwise",houghPinv); } Canny(houghPinv,contours,100,350); li=ld.findLines(contours); //Display Canny image if(showSteps) { namedWindow("Contours"); imshow("Contours2",contours); } //Set probabilistic Hough parameters ld.setLineLengthAndGap(5,2); ld.setMinVote(1); ld.setShift(image.cols/3); ld.drawDetectedLines(image); stringstream stream; stream<<"Lines Segments: "<<lines.size(); putText(image,stream.str(),Point(10,image.rows-10),2,0.8,Scalar(0,0,255),0); imshow(window_name,image); //oVideoWriter.write(image); //writer the frame into the file char key=(char)waitKey(10); lines.clear(); } } <commit_msg>Optimization of codes<commit_after>#include <cstdio> #include <iostream> #include <vector> #include <opencv2/highgui.hpp> #include <opencv2/imgproc.hpp> #include <opencv2/opencv.hpp> #include "linefinder.h" #define PI 3.1415926 using namespace cv; using namespace std; int main() { int houghVote=200; string arg="/dev/video0"; bool showSteps=true; string window_name="Processed Image"; namedWindow(window_name); VideoCapture capture(arg); if (!capture.isOpened()) //If this fails, try to open as a video camera, through the use of an integer param { capture.open(atoi(arg.c_str())); } double dWidth=capture.get(CV_CAP_PROP_FRAME_WIDTH); //get the width of frames of the video double dHeight=capture.get(CV_CAP_PROP_FRAME_HEIGHT); //get the height of frames of the video cout<<"Frame Size: "<<dWidth<<"x"<<dHeight<<endl; Mat image; image=imread(arg); while(true) { capture>>image; if(image.empty()) break; //Set the ROI for the image Rect roi((image.cols-image.rows)/2,0,image.rows,image.rows); Mat imgROI=image(roi); //Canny algorithm Mat contours; Canny(imgROI,contours,50,250); /* *Hough tranform for line detection with feedback *Increase by 25 for the next frame if we found some lines. *This is so we don't miss other lines that may crop up in the next frame *but at the same time we don't want to start the feed back loop from scratch. */ vector<Vec2f> lines; if(houghVote<1||lines.size()>10) //All lines lost. Reset houghVote=200; else houghVote+=25; while(lines.size()<2&&houghVote>0) { HoughLines(contours,lines,1,PI/180,houghVote); houghVote-=5; } clog<<"houghVote="<<houghVote<<endl; Mat result(imgROI.size(),CV_8U,Scalar(255)); imgROI.copyTo(result); //Draw the lines for(vector<Vec2f>::const_iterator it=lines.begin();it!=lines.end();++it) { float rho=(*it)[0]; //first element is distance rho float theta=(*it)[1]; //second element is angle theta //if((theta>0.09&&theta<1.48)||(theta<3.14&&theta>1.66)) //filter to remove vertical and horizontal lines { //point of intersection of the line with first row Point pt1(rho/cos(theta),0); //point of intersection of the line with last row Point pt2((rho-result.rows*sin(theta))/cos(theta),result.rows); //Draw a line line(result,pt1,pt2,Scalar(0,255,255),3,CV_AA); } clog<<"Line: ("<<rho<<","<<theta<<")\n"; } stringstream overlayedText; overlayedText<<"Lines Segments: "<<lines.size(); putText(result,overlayedText.str(),Point(10,image.rows-10),2,0.8,Scalar(0,0,255),0); imshow(window_name,result); lines.clear(); char key=(char)waitKey(1); } } <|endoftext|>
<commit_before>ff0dd858-585a-11e5-8aa5-6c40088e03e4<commit_msg>ff199b8c-585a-11e5-9f4e-6c40088e03e4<commit_after>ff199b8c-585a-11e5-9f4e-6c40088e03e4<|endoftext|>
<commit_before>#include "xchainer/gradient_check.h" #include <algorithm> #include <memory> #include <tuple> #include <vector> #include <gtest/gtest-spi.h> #include <gtest/gtest.h> #include <gsl/gsl> #include "xchainer/array.h" #include "xchainer/check_backward.h" #include "xchainer/op_node.h" #include "xchainer/shape.h" namespace xchainer { namespace { using Arrays = std::vector<Array>; using Fprop = std::function<std::vector<Array>(const std::vector<Array>&)>; /* Arrays IncorrectBackwardUnaryFunc(const Arrays& inputs) { const Array& lhs = inputs[0]; Array out = Array::EmptyLike(lhs); out.set_requires_grad(lhs.requires_grad()); if (out.requires_grad()) { std::shared_ptr<ArrayNode> lhs_node = lhs.mutable_node(); std::shared_ptr<ArrayNode> out_node = out.RenewNode(); int64_t out_rank = lhs_node->rank(); auto next_nodes = std::vector<std::shared_ptr<ArrayNode>>{lhs_node}; std::function<Array(const Array&)> empty_func; auto lhs_func = lhs.requires_grad() ? [](const Array& gout) { return gout * gout; } : empty_func; auto backward_functions = std::vector<std::function<Array(const Array&)>>{lhs_func}; std::shared_ptr<OpNode> op_node = std::make_shared<OpNode>("incorrect_unary", out_rank, next_nodes, backward_functions); out_node->set_next_node(op_node); out_node->set_rank(out_rank + 1); } VisitDtype(lhs.dtype(), [&](auto pt) { using T = typename decltype(pt)::type; int64_t total_size = lhs.total_size(); auto* ldata = static_cast<const T*>(lhs.data().get()); auto* odata = static_cast<T*>(out.data().get()); for (int64_t i = 0; i < total_size; i++) { odata[i] = ldata[i]; } }); return {out}; } Arrays IncorrectBackwardBinaryFunc(const Arrays& inputs) { const Array& lhs = inputs[0]; const Array& rhs = inputs[1]; CheckEqual(lhs.dtype(), rhs.dtype()); CheckEqual(lhs.shape(), rhs.shape()); Array out = Array::EmptyLike(lhs); out.set_requires_grad(lhs.requires_grad() || rhs.requires_grad()); if (out.requires_grad()) { std::shared_ptr<ArrayNode> lhs_node = lhs.mutable_node(); std::shared_ptr<ArrayNode> rhs_node = rhs.mutable_node(); std::shared_ptr<ArrayNode> out_node = out.RenewNode(); int64_t out_rank = std::max(lhs_node->rank(), rhs_node->rank()); auto next_nodes = std::vector<std::shared_ptr<ArrayNode>>{lhs_node, rhs_node}; std::function<Array(const Array&)> empty_func; auto lhs_func = lhs.requires_grad() ? [rhs](const Array& gout) { return gout + rhs; } : empty_func; auto rhs_func = rhs.requires_grad() ? [lhs](const Array& gout) { return gout + lhs; } : empty_func; auto backward_functions = std::vector<std::function<Array(const Array&)>>{lhs_func, rhs_func}; std::shared_ptr<OpNode> op_node = std::make_shared<OpNode>("incorrect_binary", out_rank, next_nodes, backward_functions); out_node->set_next_node(op_node); out_node->set_rank(out_rank + 1); } VisitDtype(lhs.dtype(), [&](auto pt) { using T = typename decltype(pt)::type; int64_t total_size = lhs.total_size(); auto* ldata = static_cast<const T*>(lhs.data().get()); auto* rdata = static_cast<const T*>(rhs.data().get()); auto* odata = static_cast<T*>(out.data().get()); for (int64_t i = 0; i < total_size; i++) { odata[i] = ldata[i] * rdata[i]; } }); return {out}; } class CheckBackwardBaseTest : public ::testing::Test { protected: template <typename T> Array MakeArray(const Shape& shape, const T* data) const { int64_t size = shape.total_size(); auto a = std::make_unique<T[]>(size); std::copy(data, data + size, a.get()); return Array::FromBuffer(shape, TypeToDtype<T>, std::move(a)); } void CheckBaseBackwardComputation(bool expect_correct, Fprop fprop, const Arrays& inputs, const Arrays& grad_outputs, const Arrays& eps, double atol, double rtol) { if (!expect_correct && std::any_of(inputs.begin(), inputs.end(), [](const Array& input) { return input.requires_grad(); })) { // Catch the gtest failure expected to be generated by CheckBackwardComputation but without failing this test EXPECT_NONFATAL_FAILURE(CheckBackwardComputation(fprop, inputs, grad_outputs, eps, atol, rtol), "Backward check failure"); } else { // We cannot expect any failures in case none of the input std::vector<Array> require gradients CheckBackwardComputation(fprop, inputs, grad_outputs, eps, atol, rtol); } } }; class CheckBackwardUnaryTest : public CheckBackwardBaseTest, public ::testing::WithParamInterface<bool> { protected: void SetUp() override { requires_grad = GetParam(); } template <typename T> void CheckBackwardComputation(bool expect_correct, Fprop fprop, const Shape& shape, const T* input_data, const T* grad_output_data, const T* eps_data, double atol, double rtol) { Arrays inputs{MakeArray(shape, input_data)}; Arrays grad_outputs{MakeArray(shape, grad_output_data)}; Arrays eps{MakeArray(shape, eps_data)}; inputs[0].set_requires_grad(requires_grad); // parameterized by test CheckBaseBackwardComputation(expect_correct, fprop, inputs, grad_outputs, eps, atol, rtol); } private: bool requires_grad; }; class CheckBackwardBinaryTest : public CheckBackwardBaseTest, public ::testing::WithParamInterface<std::tuple<bool, bool>> { protected: void SetUp() override { requires_grads = {std::get<0>(GetParam()), std::get<1>(GetParam())}; } template <typename T> void CheckBackwardComputation(bool expect_correct, Fprop fprop, const Shape& shape, const T* input_data1, const T* input_data2, const T* grad_output_data, const T* eps_data1, const T* eps_data2, double atol, double rtol) { Arrays inputs{MakeArray(shape, input_data1), MakeArray(shape, input_data2)}; Arrays grad_outputs{MakeArray(shape, grad_output_data)}; Arrays eps{MakeArray(shape, eps_data1), MakeArray(shape, eps_data2)}; inputs[0].set_requires_grad(requires_grads[0]); // parameterized by test inputs[1].set_requires_grad(requires_grads[1]); CheckBaseBackwardComputation(expect_correct, fprop, inputs, grad_outputs, eps, atol, rtol); } private: std::vector<bool> requires_grads; }; TEST_P(CheckBackwardUnaryTest, CorrectBackward) { float input_data[]{1.f, 2.f, 3.f}; float grad_output_data[]{0.f, -2.f, 3.f}; float eps_data[]{1.f, 2.f, 3.f}; Fprop fprop = [](const Arrays& inputs) -> Arrays { return {inputs[0]}; }; CheckBackwardComputation(true, fprop, {1, 3}, input_data, grad_output_data, eps_data, 1e-5, 1e-4); } TEST_P(CheckBackwardUnaryTest, IncorrectBackward) { float input_data[]{-2.f, 3.f, 1.f}; float grad_output_data[]{0.f, -2.f, 1.f}; float eps_data[]{1.f, 2.f, 3.f}; CheckBackwardComputation(false, &IncorrectBackwardUnaryFunc, {1, 3}, input_data, grad_output_data, eps_data, 1e-5, 1e-4); } TEST_P(CheckBackwardBinaryTest, CorrectBackward) { float input_data1[]{1.f, 2.f, 3.f}; float input_data2[]{0.f, 1.f, 2.f}; float eps_data1[]{1.f, 2.f, 3.f}; float eps_data2[]{3.f, -2.f, 3.f}; float grad_output_data[]{1.f, -2.f, 3.f}; Fprop fprop = [](const Arrays& inputs) -> Arrays { return {inputs[0] * inputs[1]}; }; CheckBackwardComputation(true, fprop, {1, 3}, input_data1, input_data2, grad_output_data, eps_data1, eps_data2, 1e-5, 1e-4); } TEST_P(CheckBackwardBinaryTest, IncorrectBackward) { float input_data1[]{3.f, -2.f, 1.f}; float input_data2[]{0.f, 1.4f, 2.f}; float eps_data1[]{1.f, 2.f, 3.8f}; float eps_data2[]{3.f, -2.f, -3.f}; float grad_output_data[]{4.f, -2.f, 3.f}; CheckBackwardComputation(false, &IncorrectBackwardBinaryFunc, {1, 3}, input_data1, input_data2, grad_output_data, eps_data1, eps_data2, 1e-5, 1e-4); } INSTANTIATE_TEST_CASE_P(ForEachSingleSetRequiresGrad, CheckBackwardUnaryTest, ::testing::Bool()); INSTANTIATE_TEST_CASE_P(ForEachCombinedSetRequiresGrad, CheckBackwardBinaryTest, ::testing::Combine(::testing::Bool(), ::testing::Bool())); */ } // namespace } // namespace xchainer <commit_msg>Pass all CheckBackward with correct backward functions<commit_after>#include "xchainer/gradient_check.h" #include <algorithm> #include <memory> #include <tuple> #include <vector> #include <gtest/gtest-spi.h> #include <gtest/gtest.h> #include <gsl/gsl> #include "xchainer/array.h" #include "xchainer/check_backward.h" #include "xchainer/op_node.h" #include "xchainer/shape.h" namespace xchainer { namespace { using Arrays = std::vector<Array>; using Fprop = std::function<std::vector<Array>(const std::vector<Array>&)>; /* Arrays IncorrectBackwardUnaryFunc(const Arrays& inputs) { const Array& lhs = inputs[0]; Array out = Array::EmptyLike(lhs); out.set_requires_grad(lhs.requires_grad()); if (out.requires_grad()) { std::shared_ptr<ArrayNode> lhs_node = lhs.mutable_node(); std::shared_ptr<ArrayNode> out_node = out.RenewNode(); int64_t out_rank = lhs_node->rank(); auto next_nodes = std::vector<std::shared_ptr<ArrayNode>>{lhs_node}; std::function<Array(const Array&)> empty_func; auto lhs_func = lhs.requires_grad() ? [](const Array& gout) { return gout * gout; } : empty_func; auto backward_functions = std::vector<std::function<Array(const Array&)>>{lhs_func}; std::shared_ptr<OpNode> op_node = std::make_shared<OpNode>("incorrect_unary", out_rank, next_nodes, backward_functions); out_node->set_next_node(op_node); out_node->set_rank(out_rank + 1); } VisitDtype(lhs.dtype(), [&](auto pt) { using T = typename decltype(pt)::type; int64_t total_size = lhs.total_size(); auto* ldata = static_cast<const T*>(lhs.data().get()); auto* odata = static_cast<T*>(out.data().get()); for (int64_t i = 0; i < total_size; i++) { odata[i] = ldata[i]; } }); return {out}; } Arrays IncorrectBackwardBinaryFunc(const Arrays& inputs) { const Array& lhs = inputs[0]; const Array& rhs = inputs[1]; CheckEqual(lhs.dtype(), rhs.dtype()); CheckEqual(lhs.shape(), rhs.shape()); Array out = Array::EmptyLike(lhs); out.set_requires_grad(lhs.requires_grad() || rhs.requires_grad()); if (out.requires_grad()) { std::shared_ptr<ArrayNode> lhs_node = lhs.mutable_node(); std::shared_ptr<ArrayNode> rhs_node = rhs.mutable_node(); std::shared_ptr<ArrayNode> out_node = out.RenewNode(); int64_t out_rank = std::max(lhs_node->rank(), rhs_node->rank()); auto next_nodes = std::vector<std::shared_ptr<ArrayNode>>{lhs_node, rhs_node}; std::function<Array(const Array&)> empty_func; auto lhs_func = lhs.requires_grad() ? [rhs](const Array& gout) { return gout + rhs; } : empty_func; auto rhs_func = rhs.requires_grad() ? [lhs](const Array& gout) { return gout + lhs; } : empty_func; auto backward_functions = std::vector<std::function<Array(const Array&)>>{lhs_func, rhs_func}; std::shared_ptr<OpNode> op_node = std::make_shared<OpNode>("incorrect_binary", out_rank, next_nodes, backward_functions); out_node->set_next_node(op_node); out_node->set_rank(out_rank + 1); } VisitDtype(lhs.dtype(), [&](auto pt) { using T = typename decltype(pt)::type; int64_t total_size = lhs.total_size(); auto* ldata = static_cast<const T*>(lhs.data().get()); auto* rdata = static_cast<const T*>(rhs.data().get()); auto* odata = static_cast<T*>(out.data().get()); for (int64_t i = 0; i < total_size; i++) { odata[i] = ldata[i] * rdata[i]; } }); return {out}; } */ class CheckBackwardBaseTest : public ::testing::Test { protected: template <typename T> Array MakeArray(const Shape& shape, const T* data) const { int64_t size = shape.total_size(); auto a = std::make_unique<T[]>(size); std::copy(data, data + size, a.get()); return Array::FromBuffer(shape, TypeToDtype<T>, std::move(a)); } void CheckBaseBackwardComputation(bool expect_correct, Fprop fprop, const Arrays& inputs, const Arrays& grad_outputs, const Arrays& eps, double atol, double rtol) { if (!expect_correct && std::any_of(inputs.begin(), inputs.end(), [](const Array& input) { return input.requires_grad(); })) { // Catch the gtest failure expected to be generated by CheckBackwardComputation but without failing this test EXPECT_NONFATAL_FAILURE(CheckBackwardComputation(fprop, inputs, grad_outputs, eps, atol, rtol), "Backward check failure"); } else { // We cannot expect any failures in case none of the input std::vector<Array> require gradients CheckBackwardComputation(fprop, inputs, grad_outputs, eps, atol, rtol); } } }; class CheckBackwardUnaryTest : public CheckBackwardBaseTest, public ::testing::WithParamInterface<bool> { protected: void SetUp() override { requires_grad = GetParam(); } template <typename T> void CheckBackwardComputation(bool expect_correct, Fprop fprop, const Shape& shape, const T* input_data, const T* grad_output_data, const T* eps_data, double atol, double rtol) { Arrays inputs{MakeArray(shape, input_data)}; Arrays grad_outputs{MakeArray(shape, grad_output_data)}; Arrays eps{MakeArray(shape, eps_data)}; inputs[0].set_requires_grad(requires_grad); // parameterized by test CheckBaseBackwardComputation(expect_correct, fprop, inputs, grad_outputs, eps, atol, rtol); } private: bool requires_grad; }; class CheckBackwardBinaryTest : public CheckBackwardBaseTest, public ::testing::WithParamInterface<std::tuple<bool, bool>> { protected: void SetUp() override { requires_grads = {std::get<0>(GetParam()), std::get<1>(GetParam())}; } template <typename T> void CheckBackwardComputation(bool expect_correct, Fprop fprop, const Shape& shape, const T* input_data1, const T* input_data2, const T* grad_output_data, const T* eps_data1, const T* eps_data2, double atol, double rtol) { Arrays inputs{MakeArray(shape, input_data1), MakeArray(shape, input_data2)}; Arrays grad_outputs{MakeArray(shape, grad_output_data)}; Arrays eps{MakeArray(shape, eps_data1), MakeArray(shape, eps_data2)}; inputs[0].set_requires_grad(requires_grads[0]); // parameterized by test inputs[1].set_requires_grad(requires_grads[1]); CheckBaseBackwardComputation(expect_correct, fprop, inputs, grad_outputs, eps, atol, rtol); } private: std::vector<bool> requires_grads; }; TEST_P(CheckBackwardUnaryTest, CorrectBackward) { float input_data[]{1.f, 2.f, 3.f}; float grad_output_data[]{0.f, -2.f, 3.f}; float eps_data[]{1.f, 2.f, 3.f}; Fprop fprop = [](const Arrays& inputs) -> Arrays { return {inputs[0]}; }; CheckBackwardComputation(true, fprop, {1, 3}, input_data, grad_output_data, eps_data, 1e-5, 1e-4); } /* TEST_P(CheckBackwardUnaryTest, IncorrectBackward) { float input_data[]{-2.f, 3.f, 1.f}; float grad_output_data[]{0.f, -2.f, 1.f}; float eps_data[]{1.f, 2.f, 3.f}; CheckBackwardComputation(false, &IncorrectBackwardUnaryFunc, {1, 3}, input_data, grad_output_data, eps_data, 1e-5, 1e-4); } */ TEST_P(CheckBackwardBinaryTest, CorrectBackward) { float input_data1[]{1.f, 2.f, 3.f}; float input_data2[]{0.f, 1.f, 2.f}; float eps_data1[]{1.f, 2.f, 3.f}; float eps_data2[]{3.f, -2.f, 3.f}; float grad_output_data[]{1.f, -2.f, 3.f}; Fprop fprop = [](const Arrays& inputs) -> Arrays { return {inputs[0] * inputs[1]}; }; CheckBackwardComputation(true, fprop, {1, 3}, input_data1, input_data2, grad_output_data, eps_data1, eps_data2, 1e-5, 1e-4); } /* TEST_P(CheckBackwardBinaryTest, IncorrectBackward) { float input_data1[]{3.f, -2.f, 1.f}; float input_data2[]{0.f, 1.4f, 2.f}; float eps_data1[]{1.f, 2.f, 3.8f}; float eps_data2[]{3.f, -2.f, -3.f}; float grad_output_data[]{4.f, -2.f, 3.f}; CheckBackwardComputation(false, &IncorrectBackwardBinaryFunc, {1, 3}, input_data1, input_data2, grad_output_data, eps_data1, eps_data2, 1e-5, 1e-4); } */ INSTANTIATE_TEST_CASE_P(ForEachSingleSetRequiresGrad, CheckBackwardUnaryTest, ::testing::Bool()); INSTANTIATE_TEST_CASE_P(ForEachCombinedSetRequiresGrad, CheckBackwardBinaryTest, ::testing::Combine(::testing::Bool(), ::testing::Bool())); } // namespace } // namespace xchainer <|endoftext|>
<commit_before>#include "xchainer/routines/logic.h" #include <algorithm> #include <cmath> #include <cstdint> #include <limits> #include <string> #include <vector> #include <gtest/gtest.h> #include <nonstd/optional.hpp> #include "xchainer/array.h" #include "xchainer/device_id.h" #include "xchainer/dtype.h" #include "xchainer/testing/array.h" #include "xchainer/testing/array_check.h" #include "xchainer/testing/device_session.h" namespace xchainer { namespace { class LogicTest : public ::testing::TestWithParam<std::string> { protected: void SetUp() override { const std::string& backend_name = GetParam(); device_session_.emplace(DeviceId{backend_name, 0}); } void TearDown() override { device_session_.reset(); } private: nonstd::optional<testing::DeviceSession> device_session_; }; TEST_P(LogicTest, Equal) { using T = float; struct Param { T a; T b; bool e; }; std::vector<Param> data = {{1.0f, 1.0f, true}, {1.0f, -1.0f, false}, {2.0f, 3.0f, false}, {1.0f, std::nanf(""), false}, {std::nanf(""), std::nanf(""), false}, {std::numeric_limits<T>::infinity(), std::numeric_limits<T>::infinity(), true}, {0.0f, -0.0f, true}}; std::vector<T> a_data; std::vector<T> b_data; std::vector<bool> e_data; std::transform(data.begin(), data.end(), std::back_inserter(a_data), [](const auto& param) { return param.a; }); std::transform(data.begin(), data.end(), std::back_inserter(b_data), [](const auto& param) { return param.b; }); std::transform(data.begin(), data.end(), std::back_inserter(e_data), [](const auto& param) { return param.e; }); Shape shape{static_cast<int64_t>(data.size())}; Array a = testing::BuildArray(shape).WithData<T>(a_data.begin(), a_data.end()); Array b = testing::BuildArray(shape).WithData<T>(b_data.begin(), b_data.end()); Array e = testing::BuildArray(shape).WithData<bool>(e_data.begin(), e_data.end()); Array c = Equal(a, b); ASSERT_EQ(c.dtype(), Dtype::kBool); EXPECT_TRUE(c.IsContiguous()); testing::ExpectEqual<bool>(e, c); } INSTANTIATE_TEST_CASE_P( ForEachBackend, LogicTest, ::testing::Values( #ifdef XCHAINER_ENABLE_CUDA std::string{"cuda"}, #endif // XCHAINER_ENABLE_CUDA std::string{"native"})); } // namespace } // namespace xchainer <commit_msg>Add Equal routine test with broadcasting<commit_after>#include "xchainer/routines/logic.h" #include <algorithm> #include <cmath> #include <cstdint> #include <limits> #include <string> #include <vector> #include <gtest/gtest.h> #include <nonstd/optional.hpp> #include "xchainer/array.h" #include "xchainer/device_id.h" #include "xchainer/dtype.h" #include "xchainer/testing/array.h" #include "xchainer/testing/array_check.h" #include "xchainer/testing/device_session.h" namespace xchainer { namespace { class LogicTest : public ::testing::TestWithParam<std::string> { protected: void SetUp() override { const std::string& backend_name = GetParam(); device_session_.emplace(DeviceId{backend_name, 0}); } void TearDown() override { device_session_.reset(); } private: nonstd::optional<testing::DeviceSession> device_session_; }; TEST_P(LogicTest, Equal) { using T = float; struct Param { T a; T b; bool e; }; std::vector<Param> data = {{1.0f, 1.0f, true}, {1.0f, -1.0f, false}, {2.0f, 3.0f, false}, {1.0f, std::nanf(""), false}, {std::nanf(""), std::nanf(""), false}, {std::numeric_limits<T>::infinity(), std::numeric_limits<T>::infinity(), true}, {0.0f, -0.0f, true}}; std::vector<T> a_data; std::vector<T> b_data; std::vector<bool> e_data; std::transform(data.begin(), data.end(), std::back_inserter(a_data), [](const auto& param) { return param.a; }); std::transform(data.begin(), data.end(), std::back_inserter(b_data), [](const auto& param) { return param.b; }); std::transform(data.begin(), data.end(), std::back_inserter(e_data), [](const auto& param) { return param.e; }); Shape shape{static_cast<int64_t>(data.size())}; Array a = testing::BuildArray(shape).WithData<T>(a_data.begin(), a_data.end()); Array b = testing::BuildArray(shape).WithData<T>(b_data.begin(), b_data.end()); Array e = testing::BuildArray(shape).WithData<bool>(e_data.begin(), e_data.end()); Array c = Equal(a, b); ASSERT_EQ(c.dtype(), Dtype::kBool); EXPECT_TRUE(c.IsContiguous()); testing::ExpectEqual<bool>(e, c); } TEST_P(LogicTest, EqualBroadcast) { using T = int32_t; Array a = testing::BuildArray({2, 3}).WithLinearData<T>(); Array b = testing::BuildArray({2, 1}).WithLinearData<T>(); Array e = testing::BuildArray({2, 3}).WithData<bool>({true, false, false, false, false, false}); Array o = Equal(a, b); testing::ExpectEqual<bool>(e, o); } INSTANTIATE_TEST_CASE_P( ForEachBackend, LogicTest, ::testing::Values( #ifdef XCHAINER_ENABLE_CUDA std::string{"cuda"}, #endif // XCHAINER_ENABLE_CUDA std::string{"native"})); } // namespace } // namespace xchainer <|endoftext|>
<commit_before>#include "ofApp.h" //-------------------------------------------------------------- // setupSender // - クライアントとの通信系を構築します。 // - Note: 宛先は固定です。 void ofApp::setupSender(bool flag){ // フラグの初期化 bSendMode = flag; _prevSendTime = ofGetElapsedTimeMillis(); if (!bSendMode) { // 送信オフ cout << "setupSender....NO --- No use clients." << endl; return; } else { // 送信オン cout << "setupSender...YES" << endl; // ofxOSCの初期化 // 宛先は3つ。 senders[0].setup("127.0.0.1", 3001); // Tested with Max // senders[0].setup("127.0.0.1", 12011); senders[1].setup("127.0.0.1", 12022); senders[2].setup("127.0.0.1", 12033); } } //-------------------------------------------------------------- // updateSender // - クライアントとの通信を更新します。 // - Note: 宛先は固定です。 void ofApp::updateSender(){ // 送信モードかつ、送信対象メッセージありの時のみ送信 if (bSendMode && bNeedSending) { // 送信タイミングの調整。 // 所定インターバルを経過していれば送信する。 if (ofGetElapsedTimeMillis() > _prevSendTime + sendInterval ){ _prevSendTime = ofGetElapsedTimeMillis(); cout << "send!" << endl; send(); // 後始末 - 1回ぽっきりで送信を抑止する場合はコメントアウトする。 // bNeedSending = false; } } } //-------------------------------------------------------------- // send // - クライアントとの通信をおこないます。 // - Note: 宛先は固定です。 // - TODO: OSCバンドルするべき? void ofApp::send(){ // メッセージ送信 ofxOscMessage m0, m1, m2, m3, m4, m5; m0.setAddress("/dsng2/ctl/FRAMEINFO"); // 送信回次 int, 時刻 float m1.setAddress("/dsng2/ctl/sp"); // 速さ(スカラー量), float m2.setAddress("/dsng2/ctl/st"); // ハンドル角 (-1.0 〜 1.0), float m3.setAddress("/dsng2/ctl/dir"); // 方角 0-360, float m4.setAddress("/dsng2/ctl/px"); // 位置.x座標 , float m5.setAddress("/dsng2/ctl/py"); // 位置.y座標, float m0.addIntArg(_sendCount++); m0.addFloatArg(ofGetElapsedTimeMillis()); m1.addFloatArg(bike._speed); m2.addFloatArg(bike._steer); m3.addFloatArg(bike._direction); m4.addFloatArg(bike._location.x); m5.addFloatArg(bike._location.y); // 各宛先に送信 for (int i =0; i<3; i++) { senders[i].sendMessage(m0); senders[i].sendMessage(m1); senders[i].sendMessage(m2); senders[i].sendMessage(m3); senders[i].sendMessage(m4); senders[i].sendMessage(m5); } } <commit_msg>cleaning<commit_after>#include "ofApp.h" //-------------------------------------------------------------- // setupSender // - クライアントとの通信系を構築します。 // - Note: 宛先は固定です。 void ofApp::setupSender(bool flag){ // フラグの初期化 bSendMode = flag; _prevSendTime = ofGetElapsedTimeMillis(); if (!bSendMode) { // 送信オフ cout << "setupSender....NO --- No use clients." << endl; return; } else { // 送信オン cout << "setupSender...YES" << endl; // ofxOSCの初期化 // 宛先は3つ。 // senders[0].setup("127.0.0.1", 3001); // Tested with Max senders[0].setup("127.0.0.1", 12011); senders[1].setup("127.0.0.1", 12022); senders[2].setup("127.0.0.1", 12033); } } //-------------------------------------------------------------- // updateSender // - クライアントとの通信を更新します。 // - Note: 宛先は固定です。 void ofApp::updateSender(){ // 送信モードかつ、送信対象メッセージありの時のみ送信 if (bSendMode && bNeedSending) { // 送信タイミングの調整。 // 所定インターバルを経過していれば送信する。 if (ofGetElapsedTimeMillis() > _prevSendTime + sendInterval ){ _prevSendTime = ofGetElapsedTimeMillis(); cout << "send!" << endl; send(); // 後始末 - 1回ぽっきりで送信を抑止する場合はコメントアウトする。 // bNeedSending = false; } } } //-------------------------------------------------------------- // send // - クライアントとの通信をおこないます。 // - Note: 宛先は固定です。 // - TODO: OSCバンドルするべき? void ofApp::send(){ // メッセージ作成 ofxOscMessage m0, m1, m2, m3, m4, m5; m0.setAddress("/dsng2/ctl/FRAMEINFO"); // 送信回次 int, 時刻 float m1.setAddress("/dsng2/ctl/sp"); // 速さ(スカラー量), float m2.setAddress("/dsng2/ctl/st"); // ハンドル角 (-1.0 〜 1.0), float m3.setAddress("/dsng2/ctl/dir"); // 方角 0-360, float m4.setAddress("/dsng2/ctl/px"); // 位置.x座標 , float m5.setAddress("/dsng2/ctl/py"); // 位置.y座標, float m0.addIntArg(_sendCount++); m0.addFloatArg(ofGetElapsedTimeMillis()); m1.addFloatArg(bike._speed); m2.addFloatArg(bike._steer); m3.addFloatArg(bike._direction); m4.addFloatArg(bike._location.x); m5.addFloatArg(bike._location.y); // 各宛先に送信 for (int i =0; i<3; i++) { senders[i].sendMessage(m0); senders[i].sendMessage(m1); senders[i].sendMessage(m2); senders[i].sendMessage(m3); senders[i].sendMessage(m4); senders[i].sendMessage(m5); } } <|endoftext|>
<commit_before>/* MIKOEDGEN * * Mikola Samardak's Edit Script Generator, implemented as a dare, * using Myers's algorithm from * „An O(ND) Difference Algorithm and Its Variations“. * * Currently suits better for binary, mostly because output can * hardly be considered human-readable. * Output script consists of sequence of instructions and raw data * to be inserted or deleted. * Format: * @a,b: - jump to offsets a, b for first and second string respectively. * +c:A - insert array A of length c. * -c:A - delete array A of length c. * * TODO: compact together sequences of hunks with the same operation. * * TODO: it would be cool and more convenient to represent a and b positions * as a 2-dimensional points instead of separate values. * * TODO: incorporate optimizations described in part 4 of the paper. */ #include <algorithm> #include <cassert> #include <iostream> #include <unordered_map> #include <vector> enum DiffOp { DIFF_INSERT, DIFF_DELETE, DIFF_NOP, }; struct Hunk { int apos; int bpos; DiffOp op; int length; }; struct Snake { int astart, bstart; int amid, bmid; int aend, bend; bool is_valid() const { return (astart <= amid && bstart <= bmid) && ((aend - amid) == (bend - bmid)); } bool has_diagonal() const { return (amid == aend) && (bend == bmid); } DiffOp diff_op() const { if (astart < amid) { return DIFF_DELETE; } else if (bstart < bmid) { return DIFF_INSERT; } else { return DIFF_NOP; } } }; static std::ostream& operator << (std::ostream& s, const Snake& snake) { s << "Snake{"; s << std::to_string(snake.astart) + ","; s << std::to_string(snake.bstart) + ","; s << std::to_string(snake.amid) + ","; s << std::to_string(snake.bmid) + ","; s << std::to_string(snake.aend) + ","; s << std::to_string(snake.bend); s << "}"; return s; } static std::vector<Hunk> process_snakes(std::vector<Snake> snakes) { std::vector<Hunk> hunks; Hunk hunk; for (auto snake = snakes.cbegin(); snake != snakes.cend(); snake--) { if (snake->bstart == -1) { continue; } DiffOp op = snake->diff_op(); if (op == DIFF_NOP) { continue; } if (op == hunk.op && !snake->has_diagonal()) { hunk.apos = snake->astart; hunk.bpos = snake->bstart; hunk.length++; } else { hunks.push_back(hunk); hunk = Hunk{ snake->astart, snake->bstart, op, 1, }; } } std::reverse(hunks.begin(), hunks.end()); return std::move(hunks); } static std::vector<std::unordered_map<int,int>> compute_trace(std::string a, std::string b) { const int alen = a.size(); const int blen = b.size(); std::vector<std::unordered_map<int,int>> vs; std::unordered_map<int,int> v; v[1] = 0; for (int d = 0; d <= alen + blen; d++) { bool solved = false; for (int k = -d; k <= d; k += 2) { int apos; if (k == -d || (k != d && v[k-1] < v[k+1])) { apos = v[k+1]; } else { apos = v[k-1]+1; } int bpos = apos - k; while (apos < alen && bpos < blen && a[apos] == b[bpos]) { apos++; bpos++; } v[k] = apos; if (apos >= alen && bpos >= blen) { solved = true; break; } } vs.push_back(std::unordered_map<int,int>(v)); if (solved) { return std::move(vs); } } throw std::logic_error("Unable to solve trace. Should actually never happen >vv<"); } static std::vector<Hunk> compute_hunks(std::string a, std::string b) { const int alen = a.size(); const int blen = b.size(); std::vector<std::unordered_map<int,int>> vs; // find shortest D-path std::unordered_map<int,int> v; v[1] = 0; for (int d = 0; d <= alen + blen; d++) { bool solved = false; std::cout << "d: " << d << "\n"; for (int k = -d; k <= d; k += 2) { int apos; int bpos; if (k == -d || (k != d && v[k-1] < v[k+1])) { apos = v[k+1]; } else { apos = v[k-1]+1; } bpos = apos - k; while (apos < alen && bpos < blen && a[apos] == b[bpos]) { apos++; bpos++; } v[k] = apos; std::cout << "v[" << k << "] = (" << apos << "," << bpos << ")\n"; if (apos >= alen && bpos >= blen) { std::cout << "found solution of length " << d << "\n"; solved = true; break; } } vs.push_back(std::unordered_map<int,int>(v)); if (solved) { break; } } // calculate snakes starting at the last endpoint std::vector<Snake> snakes; int apos = alen; int bpos = blen; for (int d = vs.size() - 1; apos > 0 || bpos > 0; d--) { auto v = vs[d]; std::cout << "d: " << d << "\n"; std::cout << "pos: (" << apos << "," << bpos << ")\n"; int k = apos - bpos; // end int aend = v[k]; int bend = apos - k; bool down = (k == -d || (k != d && v[k-1] < v[k+1])); int kprev = (down) ? k+1 : k-1; // start int astart = v[kprev]; int bstart = astart - kprev; // middle int amid = (down) ? astart : astart + 1; int bmid = amid - k; Snake snake{astart, bstart, amid, bmid, aend, bend}; snakes.push_back(snake); apos = astart; bpos = bstart; } return process_snakes(snakes); } int main(void) { std::string a = "CABCABBA"; std::string b = "CBABACA"; auto snakes = compute_snakes(a, b); std::cout << "\nSnakes:\n"; for (auto snake = snakes.begin(); snake != snakes.end(); ++snake) { std::cout << *snake << "\n"; } } // vim: tabstop=8 softtabstop=8 shiftwidth=8 noexpandtab <commit_msg>main: implement generating diff output.<commit_after>/* MIKOEDGEN * * Mikola Samardak's Edit Script Generator, implemented as a dare, * using Myers's algorithm from * „An O(ND) Difference Algorithm and Its Variations“. * * Currently suits better for binary, mostly because output can * hardly be considered human-readable. * Output script consists of sequence of instructions and raw data * to be inserted or deleted. * Format: * @a,b: - jump to offsets a, b for first and second string respectively. * +c:A - insert array A of length c. * -c:A - delete array A of length c. * * TODO: compact together sequences of hunks with the same operation. * * TODO: it would be cool and more convenient to represent a and b positions * as a 2-dimensional points instead of separate values. * * TODO: incorporate optimizations described in part 4 of the paper. */ #include <algorithm> #include <cassert> #include <fstream> #include <iostream> #include <unordered_map> #include <vector> enum DiffOp { DIFF_INSERT, DIFF_DELETE, DIFF_NOP, }; struct Snake { int astart, bstart; int amid, bmid; int aend, bend; bool is_valid() const { return (astart <= amid && bstart <= bmid) && ((aend - amid) == (bend - bmid)); } bool has_diagonal() const { return (amid == aend) && (bend == bmid); } DiffOp diff_op() const { if (astart < amid) { return DIFF_DELETE; } else if (bstart < bmid) { return DIFF_INSERT; } else { return DIFF_NOP; } } }; struct Hunk { int apos; int bpos; DiffOp op; int length; std::string data; std::string marshall() const { std::string s; s += "@" + std::to_string(apos) + "," + std::to_string(bpos) + ":"; if (op == DIFF_INSERT) { s += "+"; } else if (op == DIFF_DELETE) { s += "-"; } else { throw std::logic_error("Bad DiffOp"); } s += std::to_string(length); s += ":"; s += data; return std::move(s); } }; static std::vector<std::unordered_map<int,int>> compute_trace(std::string a, std::string b) { const int alen = a.size(); const int blen = b.size(); std::vector<std::unordered_map<int,int>> vs; std::unordered_map<int,int> v; v[1] = 0; for (int d = 0; d <= alen + blen; d++) { bool solved = false; for (int k = -d; k <= d; k += 2) { int apos; if (k == -d || (k != d && v[k-1] < v[k+1])) { apos = v[k+1]; } else { apos = v[k-1]+1; } int bpos = apos - k; while (apos < alen && bpos < blen && a[apos] == b[bpos]) { apos++; bpos++; } v[k] = apos; if (apos >= alen && bpos >= blen) { solved = true; break; } } vs.push_back(std::unordered_map<int,int>(v)); if (solved) { return std::move(vs); } } throw std::logic_error("Unable to solve trace. Should actually never happen >vv<"); } static std::vector<Snake> compute_snakes( const std::vector<std::unordered_map<int,int>> vs, const int alen, const int blen ) { std::vector<Snake> snakes; int apos = alen; int bpos = blen; for (int d = vs.size() - 1; apos > 0 || bpos > 0; d--) { auto v = vs[d]; int k = apos - bpos; // end int aend = v[k]; int bend = apos - k; bool down = (k == -d || (k != d && v[k-1] < v[k+1])); int kprev = (down) ? k+1 : k-1; // start int astart = v[kprev]; int bstart = astart - kprev; // middle int amid = (down) ? astart : astart + 1; int bmid = amid - k; Snake snake{astart, bstart, amid, bmid, aend, bend}; snakes.push_back(snake); apos = astart; bpos = bstart; } return std::move(snakes); } static std::vector<Hunk> process_snakes(std::vector<Snake> snakes) { std::vector<Hunk> hunks; Hunk hunk = {}; for (auto snake = snakes.cbegin(); snake != snakes.cend(); snake++) { if (snake->bstart == -1) { continue; } DiffOp op = snake->diff_op(); if (op == DIFF_NOP) { continue; } // TODO: merge sequences of hunks with the same op. hunk = Hunk { snake->astart, snake->bstart, op, 1, }; hunks.push_back(hunk); } std::reverse(hunks.begin(), hunks.end()); return std::move(hunks); } static std::vector<Hunk> compute_hunks(std::string a, std::string b) { const int alen = a.size(); const int blen = b.size(); std::vector<std::unordered_map<int,int>> vs = compute_trace(a, b); std::vector<Snake> snakes = compute_snakes(vs, alen, blen); std::vector<Hunk> hunks = process_snakes(snakes); // а потім маленьке звірятко загортає все це у фольгу for (auto hunk = hunks.begin(); hunk != hunks.end(); hunk++) { if (hunk->op == DIFF_INSERT) { hunk->data = b.substr(hunk->bpos, hunk->length); } else { hunk->data = a.substr(hunk->apos, hunk->length); } } return std::move(hunks); } int main(int argc, char* argv[]) { if (argc != 3) { std::cout << "Usage:\n"; std::cout << " " << argv[0] << " <file1> <file2>"; return -1; } std::ifstream file1; file1.exceptions(std::ifstream::failbit); file1.open(argv[1], std::ifstream::in | std::ifstream::binary); std::ifstream file2; file2.exceptions(std::ifstream::failbit); file2.open(argv[2], std::ifstream::in | std::ifstream::binary); std::string a( (std::istreambuf_iterator<char>(file1)), (std::istreambuf_iterator<char>()) ); std::string b( (std::istreambuf_iterator<char>(file2)), (std::istreambuf_iterator<char>()) ); std::cout << "-" << a; std::cout << "+" << b; auto hunks = compute_hunks(a, b); std::cout << "\nHunks:\n"; for (auto hunk = hunks.cbegin(); hunk != hunks.cend(); ++hunk) { std::cout << hunk->marshall() << "\n"; } } // vim: tabstop=8 softtabstop=8 shiftwidth=8 noexpandtab <|endoftext|>
<commit_before>#include "command_file.hpp" #include "list.hpp" #include "object_schema.hpp" #include "property.hpp" #include "results.hpp" #include "schema.hpp" #include "impl/realm_coordinator.hpp" #include <realm/commit_log.hpp> #include <realm/disable_sync_to_disk.hpp> #include <realm/group_shared.hpp> #include <realm/link_view.hpp> #include <iostream> #include <sstream> #include <sys/types.h> #include <sys/uio.h> #include <unistd.h> using namespace realm; #define FUZZ_SORTED 0 #define FUZZ_LINKVIEW 1 #define FUZZ_LOG 0 // Read from a fd until eof into a string // Needs to use unbuffered i/o to work properly with afl static void read_all(std::string& buffer, int fd) { buffer.clear(); size_t offset = 0; while (true) { buffer.resize(offset + 4096); ssize_t bytes_read = read(fd, &buffer[offset], 4096); if (bytes_read < 4096) { buffer.resize(offset + bytes_read); break; } offset += 4096; } } static Query query(fuzzer::RealmState& state) { #if FUZZ_LINKVIEW return state.table.where(state.lv); #else return state.table.where().greater(1, 100).less(1, 50000); #endif } static TableView tableview(fuzzer::RealmState& state) { auto tv = query(state).find_all(); #if FUZZ_SORTED tv.sort({1, 0}, {true, true}); #endif return tv; } // Apply the changes from the command file and then return whether a change // notification should occur static bool apply_changes(fuzzer::CommandFile& commands, fuzzer::RealmState& state) { auto tv = tableview(state); #if FUZZ_LOG for (size_t i = 0; i < tv.size(); ++i) fprintf(stderr, "pre: %lld\n", tv.get_int(0, i)); #endif commands.run(state); auto tv2 = tableview(state); if (tv.size() != tv2.size()) return true; for (size_t i = 0; i < tv.size(); ++i) { #if FUZZ_LOG fprintf(stderr, "%lld %lld\n", tv.get_int(0, i), tv2.get_int(0, i)); #endif if (!tv.is_row_attached(i)) return true; if (tv.get_int(0, i) != tv2.get_int(0, i)) return true; if (find(begin(state.modified), end(state.modified), tv.get_int(0, i)) != end(state.modified)) return true; } return false; } static void verify(CollectionChangeIndices const& changes, std::vector<int64_t> values, fuzzer::RealmState& state) { auto tv = tableview(state); // Apply the changes from the transaction log to our copy of the // initial, using UITableView's batching rules (i.e. delete, then // insert, then update) auto it = util::make_reverse_iterator(changes.deletions.end()); auto end = util::make_reverse_iterator(changes.deletions.begin()); for (; it != end; ++it) { values.erase(values.begin() + it->first, values.begin() + it->second); } for (auto i : changes.insertions.as_indexes()) { values.insert(values.begin() + i, tv.get_int(1, i)); } if (values.size() != tv.size()) { abort(); } for (auto i : changes.modifications.as_indexes()) { if (changes.insertions.contains(i)) abort(); values[i] = tv.get_int(1, i); } #if FUZZ_SORTED if (!std::is_sorted(values.begin(), values.end())) abort(); #endif for (size_t i = 0; i < values.size(); ++i) { if (values[i] != tv.get_int(1, i)) { #if FUZZ_LOG fprintf(stderr, "%lld %lld\n", values[i], tv.get_int(1, i)); #endif abort(); } } } static void test(Realm::Config const& config, SharedRealm& r, SharedRealm& r2, std::istream& input_stream) { fuzzer::RealmState state = { *r, *_impl::RealmCoordinator::get_existing_coordinator(r->config().path), *r->read_group()->get_table("class_object"), r->read_group()->get_table("class_linklist")->get_linklist(0, 0), 0, {} }; fuzzer::CommandFile command(input_stream); if (command.initial_values.empty()) { return; } command.import(state); fuzzer::RealmState state2 = { *r2, state.coordinator, *r2->read_group()->get_table("class_object"), r2->read_group()->get_table("class_linklist")->get_linklist(0, 0), state.uid, {} }; #if FUZZ_LINKVIEW && !FUZZ_SORTED auto results = List(r, ObjectSchema(), state.lv); #else auto results = Results(r, ObjectSchema(), query(state)) #if FUZZ_SORTED .sort({{1, 0}, {true, true}}) #endif ; #endif // FUZZ_LINKVIEW std::vector<int64_t> initial_values; for (size_t i = 0; i < results.size(); ++i) initial_values.push_back(results.get(i).get_int(1)); CollectionChangeIndices changes; int notification_calls = 0; auto token = results.add_notification_callback([&](CollectionChangeIndices c, std::exception_ptr err) { if (notification_calls > 0 && c.empty()) abort(); changes = c; ++notification_calls; }); state.coordinator.on_change(); r->notify(); if (notification_calls != 1) { abort(); } bool expect_notification = apply_changes(command, state2); state.coordinator.on_change(); r->notify(); if (notification_calls != 1 + expect_notification) { abort(); } verify(changes, initial_values, state); } int main(int argc, char** argv) { std::ios_base::sync_with_stdio(false); realm::disable_sync_to_disk(); Realm::Config config; config.path = "fuzzer.realm"; config.cache = false; config.in_memory = true; config.automatic_change_notifications = false; Schema schema{ {"object", "", { {"id", PropertyTypeInt}, {"value", PropertyTypeInt} }}, {"linklist", "", { {"list", PropertyTypeArray, "object"} }} }; config.schema = std::make_unique<Schema>(schema); unlink(config.path.c_str()); auto r = Realm::get_shared_realm(config); auto r2 = Realm::get_shared_realm(config); auto& coordinator = *_impl::RealmCoordinator::get_existing_coordinator(config.path); r->begin_transaction(); r->read_group()->get_table("class_linklist")->add_empty_row(); r->commit_transaction(); auto test_on = [&](auto& buffer) { std::istringstream ss(buffer); test(config, r, r2, ss); if (r->is_in_transaction()) r->cancel_transaction(); r2->invalidate(); coordinator.on_change(); }; if (argc > 1) { std::string buffer; for (int i = 1; i < argc; ++i) { int fd = open(argv[i], O_RDONLY); if (fd < 0) abort(); read_all(buffer, fd); close(fd); test_on(buffer); } unlink(config.path.c_str()); return 0; } #ifdef __AFL_HAVE_MANUAL_CONTROL std::string buffer; while (__AFL_LOOP(1000)) { read_all(buffer, 0); test_on(buffer); } #else std::string buffer; read_all(buffer, 0); test_on(buffer); #endif unlink(config.path.c_str()); return 0; } <commit_msg>Allow non-empty no-op changesets when there should be no notification in the fuzzer<commit_after>#include "command_file.hpp" #include "list.hpp" #include "object_schema.hpp" #include "property.hpp" #include "results.hpp" #include "schema.hpp" #include "impl/realm_coordinator.hpp" #include <realm/commit_log.hpp> #include <realm/disable_sync_to_disk.hpp> #include <realm/group_shared.hpp> #include <realm/link_view.hpp> #include <iostream> #include <sstream> #include <sys/types.h> #include <sys/uio.h> #include <unistd.h> using namespace realm; #define FUZZ_SORTED 0 #define FUZZ_LINKVIEW 1 #define FUZZ_LOG 0 // Read from a fd until eof into a string // Needs to use unbuffered i/o to work properly with afl static void read_all(std::string& buffer, int fd) { buffer.clear(); size_t offset = 0; while (true) { buffer.resize(offset + 4096); ssize_t bytes_read = read(fd, &buffer[offset], 4096); if (bytes_read < 4096) { buffer.resize(offset + bytes_read); break; } offset += 4096; } } static Query query(fuzzer::RealmState& state) { #if FUZZ_LINKVIEW return state.table.where(state.lv); #else return state.table.where().greater(1, 100).less(1, 50000); #endif } static TableView tableview(fuzzer::RealmState& state) { auto tv = query(state).find_all(); #if FUZZ_SORTED tv.sort({1, 0}, {true, true}); #endif return tv; } // Apply the changes from the command file and then return whether a change // notification should occur static bool apply_changes(fuzzer::CommandFile& commands, fuzzer::RealmState& state) { auto tv = tableview(state); #if FUZZ_LOG for (size_t i = 0; i < tv.size(); ++i) fprintf(stderr, "pre: %lld\n", tv.get_int(0, i)); #endif commands.run(state); auto tv2 = tableview(state); if (tv.size() != tv2.size()) return true; for (size_t i = 0; i < tv.size(); ++i) { #if FUZZ_LOG fprintf(stderr, "%lld %lld\n", tv.get_int(0, i), tv2.get_int(0, i)); #endif if (!tv.is_row_attached(i)) return true; if (tv.get_int(0, i) != tv2.get_int(0, i)) return true; if (find(begin(state.modified), end(state.modified), tv.get_int(0, i)) != end(state.modified)) return true; } return false; } static auto verify(CollectionChangeIndices const& changes, std::vector<int64_t> values, fuzzer::RealmState& state) { auto tv = tableview(state); // Apply the changes from the transaction log to our copy of the // initial, using UITableView's batching rules (i.e. delete, then // insert, then update) auto it = util::make_reverse_iterator(changes.deletions.end()); auto end = util::make_reverse_iterator(changes.deletions.begin()); for (; it != end; ++it) { values.erase(values.begin() + it->first, values.begin() + it->second); } for (auto i : changes.insertions.as_indexes()) { values.insert(values.begin() + i, tv.get_int(1, i)); } if (values.size() != tv.size()) { abort(); } for (auto i : changes.modifications.as_indexes()) { if (changes.insertions.contains(i)) abort(); values[i] = tv.get_int(1, i); } #if FUZZ_SORTED if (!std::is_sorted(values.begin(), values.end())) abort(); #endif for (size_t i = 0; i < values.size(); ++i) { if (values[i] != tv.get_int(1, i)) { #if FUZZ_LOG fprintf(stderr, "%lld %lld\n", values[i], tv.get_int(1, i)); #endif abort(); } } return values; } static void verify_no_op(CollectionChangeIndices const& changes, std::vector<int64_t> values, fuzzer::RealmState& state) { auto new_values = verify(changes, values, state); if (!std::equal(begin(values), end(values), begin(new_values), end(new_values))) abort(); } static void test(Realm::Config const& config, SharedRealm& r, SharedRealm& r2, std::istream& input_stream) { fuzzer::RealmState state = { *r, *_impl::RealmCoordinator::get_existing_coordinator(r->config().path), *r->read_group()->get_table("class_object"), r->read_group()->get_table("class_linklist")->get_linklist(0, 0), 0, {} }; fuzzer::CommandFile command(input_stream); if (command.initial_values.empty()) { return; } command.import(state); fuzzer::RealmState state2 = { *r2, state.coordinator, *r2->read_group()->get_table("class_object"), r2->read_group()->get_table("class_linklist")->get_linklist(0, 0), state.uid, {} }; #if FUZZ_LINKVIEW && !FUZZ_SORTED auto results = List(r, ObjectSchema(), state.lv); #else auto results = Results(r, ObjectSchema(), query(state)) #if FUZZ_SORTED .sort({{1, 0}, {true, true}}) #endif ; #endif // FUZZ_LINKVIEW std::vector<int64_t> initial_values; for (size_t i = 0; i < results.size(); ++i) initial_values.push_back(results.get(i).get_int(1)); CollectionChangeIndices changes; int notification_calls = 0; auto token = results.add_notification_callback([&](CollectionChangeIndices c, std::exception_ptr err) { if (notification_calls > 0 && c.empty()) abort(); changes = c; ++notification_calls; }); state.coordinator.on_change(); r->notify(); if (notification_calls != 1) { abort(); } bool expect_notification = apply_changes(command, state2); state.coordinator.on_change(); r->notify(); if (expect_notification) { if (notification_calls != 2) abort(); verify(changes, initial_values, state); } else { if (notification_calls == 2) verify_no_op(changes, initial_values, state); } } int main(int argc, char** argv) { std::ios_base::sync_with_stdio(false); realm::disable_sync_to_disk(); Realm::Config config; config.path = "fuzzer.realm"; config.cache = false; config.in_memory = true; config.automatic_change_notifications = false; Schema schema{ {"object", "", { {"id", PropertyTypeInt}, {"value", PropertyTypeInt} }}, {"linklist", "", { {"list", PropertyTypeArray, "object"} }} }; config.schema = std::make_unique<Schema>(schema); unlink(config.path.c_str()); auto r = Realm::get_shared_realm(config); auto r2 = Realm::get_shared_realm(config); auto& coordinator = *_impl::RealmCoordinator::get_existing_coordinator(config.path); r->begin_transaction(); r->read_group()->get_table("class_linklist")->add_empty_row(); r->commit_transaction(); auto test_on = [&](auto& buffer) { std::istringstream ss(buffer); test(config, r, r2, ss); if (r->is_in_transaction()) r->cancel_transaction(); r2->invalidate(); coordinator.on_change(); }; if (argc > 1) { std::string buffer; for (int i = 1; i < argc; ++i) { int fd = open(argv[i], O_RDONLY); if (fd < 0) abort(); read_all(buffer, fd); close(fd); test_on(buffer); } unlink(config.path.c_str()); return 0; } #ifdef __AFL_HAVE_MANUAL_CONTROL std::string buffer; while (__AFL_LOOP(1000)) { read_all(buffer, 0); test_on(buffer); } #else std::string buffer; read_all(buffer, 0); test_on(buffer); #endif unlink(config.path.c_str()); return 0; } <|endoftext|>
<commit_before>#include "gamemechanics.h" #include <QPainter> #include <QtCore/qmath.h> #include <QLabel> #include <QMouseEvent> GameMechanics::GameMechanics(QWidget *parent) : QWidget(parent) { imageName = new QString(); pieceCount = 3; array = new Piece*[pieceCount]; for (int i = 0; i < pieceCount; i++) array[i] = new Piece[pieceCount]; for (int x = 0; x < pieceCount; x++) for(int y = 0; y < pieceCount; y++) { array[x][y].x = x; array[x][y].y = y; } typeOfPainting = empty; winflag = false; } //----------------------------------------- void GameMechanics::mixArray() //Начинаем перемешивать части картинок по алгоритму { int mas[2] = {-1,1}; int x, y; for(int i = 0; i<23 * pieceCount; i++) { x = abs((mas[rand() % 2] + emptyImagePos.x()) % pieceCount); y = abs((mas[rand() % 2] + emptyImagePos.x()) % pieceCount); if (!swapEmpty(x, emptyImagePos.y())) i--; if (!swapEmpty(emptyImagePos.x(), y)) i--; } } //----------------------------------------- void GameMechanics::newGame() { pieceWidth = this->width() / pieceCount; pieceHeight = this->height() / pieceCount; typeOfPainting = fullImage; QImage temp(*imageName); temp = temp.scaled(QSize(this->width() + pieceCount, this->height())); image = &temp; for (int x = 0; x < pieceCount; x++) for(int y = 0; y < pieceCount; y++) { array[x][y].x = x; array[x][y].y = y; } for(int x = 0; x < pieceCount; x++) for(int y = 0; y < pieceCount; y++) array[x][y].img = image->copy(pieceWidth * x, pieceHeight * y, pieceWidth, pieceHeight); emptyImagePos.setX(pieceCount - 1); emptyImagePos.setY(pieceCount - 1); winflag = false; repaint(); mixArray(); typeOfPainting = fullImage; } //---------------------------------------- void GameMechanics::hint() { typeOfPainting = fullImage; repaint(); } //---------------------------------------- GameMechanics::~GameMechanics() { for (int i = 0; i < pieceCount; i++) delete[] array[i]; delete[] array; } //---------------------------------------- void GameMechanics::paintEvent(QPaintEvent *paintEvent) { QPainter painter(this); painter.begin(this); int n = 0; switch(typeOfPainting) { case pieces: pieceWidth = this->width() / pieceCount; pieceHeight = this->height() / pieceCount; //рисуем картинки for(int x = 0; x < pieceCount; x++) for(int y = 0; y < pieceCount; y++) painter.drawImage(pieceWidth * x,pieceHeight * y + y, array[x][y].img); painter.setPen(QColor(0, 0, 0)); painter.setBrush(QColor(255, 255, 255)); painter.drawRect(pieceWidth * emptyImagePos.x(), pieceHeight * emptyImagePos.y() + emptyImagePos.y(), pieceWidth, pieceHeight); //рисуем линии между картинками for(int x = pieceWidth; x < this->width(); x += pieceWidth) painter.drawLine(x, 0, x, this->height()); for(int y = pieceHeight; y < this->height(); y += pieceHeight, n++) painter.drawLine(0, y + n, this->width(), y+n); break; case fullImage: for(int x = 0; x < pieceCount; x++) for(int y = 0; y < pieceCount; y++) painter.drawImage(pieceWidth * array[x][y].x, pieceHeight * array[x][y].y, array[x][y].img); break; default: painter.drawText(this->width() / 2 - 70, this->height() / 2 - 15, tr("Begin the game, please!")); break; }; painter.end(); } //---------------------------------------- void GameMechanics::mousePressEvent(QMouseEvent *event) { imagePressed(event->localPos()); } //---------------------------------------- void GameMechanics::imagePressed(QPointF pos) { if(typeOfPainting == pieces) { int x = (int)pos.x(); int y = (int)pos.y(); x /= pieceWidth; y /= pieceHeight; if ( x == emptyImagePos.x() && y == emptyImagePos.y()) return; swapEmpty(x,y); repaint(); if(!winflag && checkArray()) { win(); typeOfPainting = fullImage; } } if(typeOfPainting == fullImage && !winflag) { typeOfPainting = pieces; repaint(); } if(typeOfPainting == fullImage && winflag) { repaint(); } } //---------------------------------------- int GameMechanics::swapEmpty(int x, int y) { if( (abs(x - emptyImagePos.x()) == 1 && y == emptyImagePos.y()) || (abs(y - emptyImagePos.y()) == 1 && x == emptyImagePos.x()) ) { Piece tempPiece = array[x][y]; array[x][y] = array[emptyImagePos.x()][emptyImagePos.y()]; array[emptyImagePos.x()][emptyImagePos.y()] = tempPiece; emptyImagePos.setX(x); emptyImagePos.setY(y); return 1; } else return 0; } //---------------------------------------- bool GameMechanics::checkArray() { for(int x = 0; x < pieceCount; x++) for(int y = 0; y < pieceCount; y++) if(array[x][y].x != x || array[x][y].y != y) return 0; winflag = true; return 1; } //---------------------------------------- void GameMechanics::changeLevel(int level) { if (level > 1 && level <6) { for (int i = 0; i < pieceCount; i++) delete[] array[i]; delete[] array; pieceCount = level; array = new Piece*[pieceCount]; for (int i = 0; i < pieceCount; i++) array[i] = new Piece[pieceCount]; for (int x = 0; x < pieceCount; x++) for(int y = 0; y < pieceCount; y++) { array[x][y].x = x; array[x][y].y = y; } } } //---------------------------------------- <commit_msg>The last commit!!!<commit_after>#include "gamemechanics.h" #include <QPainter> #include <QtCore/qmath.h> #include <QLabel> #include <QMouseEvent> GameMechanics::GameMechanics(QWidget *parent) : QWidget(parent) { imageName = new QString(); pieceCount = 2; array = new Piece*[pieceCount]; for (int i = 0; i < pieceCount; i++) array[i] = new Piece[pieceCount]; for (int x = 0; x < pieceCount; x++) for(int y = 0; y < pieceCount; y++) { array[x][y].x = x; array[x][y].y = y; } typeOfPainting = empty; winflag = false; } //----------------------------------------- void GameMechanics::mixArray() //Начинаем перемешивать части картинок по алгоритму { int mas[2] = {-1,1}; int x, y; for(int i = 0; i<23 * pieceCount; i++) { x = abs((mas[rand() % 2] + emptyImagePos.x()) % pieceCount); y = abs((mas[rand() % 2] + emptyImagePos.x()) % pieceCount); if (!swapEmpty(x, emptyImagePos.y())) i--; if (!swapEmpty(emptyImagePos.x(), y)) i--; } } //----------------------------------------- void GameMechanics::newGame() { pieceWidth = this->width() / pieceCount; pieceHeight = this->height() / pieceCount; typeOfPainting = fullImage; QImage temp(*imageName); temp = temp.scaled(QSize(this->width() + pieceCount, this->height())); image = &temp; for (int x = 0; x < pieceCount; x++) for(int y = 0; y < pieceCount; y++) { array[x][y].x = x; array[x][y].y = y; } for(int x = 0; x < pieceCount; x++) for(int y = 0; y < pieceCount; y++) array[x][y].img = image->copy(pieceWidth * x, pieceHeight * y, pieceWidth, pieceHeight); emptyImagePos.setX(pieceCount - 1); emptyImagePos.setY(pieceCount - 1); winflag = false; repaint(); mixArray(); typeOfPainting = fullImage; } //---------------------------------------- void GameMechanics::hint() { typeOfPainting = fullImage; repaint(); } //---------------------------------------- GameMechanics::~GameMechanics() { for (int i = 0; i < pieceCount; i++) delete[] array[i]; delete[] array; } //---------------------------------------- void GameMechanics::paintEvent(QPaintEvent *paintEvent) { QPainter painter(this); painter.begin(this); int n = 0; switch(typeOfPainting) { case pieces: pieceWidth = this->width() / pieceCount; pieceHeight = this->height() / pieceCount; //рисуем картинки for(int x = 0; x < pieceCount; x++) for(int y = 0; y < pieceCount; y++) painter.drawImage(pieceWidth * x,pieceHeight * y + y, array[x][y].img); painter.setPen(QColor(0, 0, 0)); painter.setBrush(QColor(255, 255, 255)); painter.drawRect(pieceWidth * emptyImagePos.x(), pieceHeight * emptyImagePos.y() + emptyImagePos.y(), pieceWidth, pieceHeight); //рисуем линии между картинками for(int x = pieceWidth; x < this->width(); x += pieceWidth) painter.drawLine(x, 0, x, this->height()); for(int y = pieceHeight; y < this->height(); y += pieceHeight, n++) painter.drawLine(0, y + n, this->width(), y+n); break; case fullImage: for(int x = 0; x < pieceCount; x++) for(int y = 0; y < pieceCount; y++) painter.drawImage(pieceWidth * array[x][y].x, pieceHeight * array[x][y].y, array[x][y].img); break; default: painter.drawText(this->width() / 2 - 70, this->height() / 2 - 15, tr("Begin the game, please!")); break; }; painter.end(); } //---------------------------------------- void GameMechanics::mousePressEvent(QMouseEvent *event) { imagePressed(event->posF()); } //---------------------------------------- void GameMechanics::imagePressed(QPointF pos) { if(typeOfPainting == pieces) { int x = (int)pos.x(); int y = (int)pos.y(); x /= pieceWidth; y /= pieceHeight; if ( x == emptyImagePos.x() && y == emptyImagePos.y()) return; swapEmpty(x,y); repaint(); if(!winflag && checkArray()) { win(); typeOfPainting = fullImage; } } if(typeOfPainting == fullImage && !winflag) { typeOfPainting = pieces; repaint(); } if(typeOfPainting == fullImage && winflag) { repaint(); } } //---------------------------------------- int GameMechanics::swapEmpty(int x, int y) { if( (abs(x - emptyImagePos.x()) == 1 && y == emptyImagePos.y()) || (abs(y - emptyImagePos.y()) == 1 && x == emptyImagePos.x()) ) { Piece tempPiece = array[x][y]; array[x][y] = array[emptyImagePos.x()][emptyImagePos.y()]; array[emptyImagePos.x()][emptyImagePos.y()] = tempPiece; emptyImagePos.setX(x); emptyImagePos.setY(y); return 1; } else return 0; } //---------------------------------------- bool GameMechanics::checkArray() { for(int x = 0; x < pieceCount; x++) for(int y = 0; y < pieceCount; y++) if(array[x][y].x != x || array[x][y].y != y) return 0; winflag = true; return 1; } //---------------------------------------- void GameMechanics::changeLevel(int level) { if (level > 1 && level <6) { for (int i = 0; i < pieceCount; i++) delete[] array[i]; delete[] array; pieceCount = level; array = new Piece*[pieceCount]; for (int i = 0; i < pieceCount; i++) array[i] = new Piece[pieceCount]; for (int x = 0; x < pieceCount; x++) for(int y = 0; y < pieceCount; y++) { array[x][y].x = x; array[x][y].y = y; } } } //---------------------------------------- <|endoftext|>
<commit_before>//g++ genmasterpair.cpp -lcrypto++ -o genmasterpair #include <string> using namespace std; #include <crypto++/rsa.h> #include <crypto++/osrng.h> #include <crypto++/base64.h> #include <crypto++/files.h> #include <crypto++/aes.h> #include <crypto++/modes.h> #include <crypto++/ripemd.h> using namespace CryptoPP; void GenKeyPair() { cout << "Enter master key password" << endl; string pass; cin >> pass; // InvertibleRSAFunction is used directly only because the private key // won't actually be used to perform any cryptographic operation; // otherwise, an appropriate typedef'ed type from rsa.h would have been used. AutoSeededRandomPool rng; InvertibleRSAFunction privkey; privkey.Initialize(rng, 1024*8); // With the current version of Crypto++, MessageEnd() needs to be called // explicitly because Base64Encoder doesn't flush its buffer on destruction. string privKeyDer; StringSink privKeyDerSink(privKeyDer); privkey.DEREncode(privKeyDerSink); //Hash the pass phrase to create 128 bit key string hashedPass; RIPEMD128 hash; StringSource(pass, true, new HashFilter(hash, new StringSink(hashedPass))); // Generate a random IV byte iv[AES::BLOCKSIZE]; rng.GenerateBlock(iv, AES::BLOCKSIZE); //Encrypt private key CFB_Mode<AES>::Encryption cfbEncryption((const unsigned char*)hashedPass.c_str(), hashedPass.length(), iv); byte encPrivKey[privKeyDer.length()+1]; cfbEncryption.ProcessData(encPrivKey, (const byte*)privKeyDer.c_str(), privKeyDer.length()); string encPrivKeyStr((char *)encPrivKey, privKeyDer.length()); //Save private key to file StringSource encPrivKeySrc(encPrivKeyStr, true); Base64Encoder sink(new FileSink("master-privkey-enc.txt")); encPrivKeySrc.CopyTo(sink); sink.MessageEnd(); //Save initialization vector key to file StringSource ivStr(iv, AES::BLOCKSIZE, true); Base64Encoder sink2(new FileSink("master-privkey-iv.txt")); ivStr.CopyTo(sink2); sink2.MessageEnd(); // Suppose we want to store the public key separately, // possibly because we will be sending the public key to a third party. RSAFunction pubkey(privkey); Base64Encoder pubkeysink(new FileSink("master-pubkey.txt")); pubkey.DEREncode(pubkeysink); pubkeysink.MessageEnd(); } int main() { GenKeyPair(); } <commit_msg>Clarify question prompts<commit_after>//g++ genmasterpair.cpp -lcrypto++ -o genmasterpair #include <string> using namespace std; #include <crypto++/rsa.h> #include <crypto++/osrng.h> #include <crypto++/base64.h> #include <crypto++/files.h> #include <crypto++/aes.h> #include <crypto++/modes.h> #include <crypto++/ripemd.h> using namespace CryptoPP; void GenKeyPair() { cout << "Enter new master key password" << endl; string pass; cin >> pass; // InvertibleRSAFunction is used directly only because the private key // won't actually be used to perform any cryptographic operation; // otherwise, an appropriate typedef'ed type from rsa.h would have been used. AutoSeededRandomPool rng; InvertibleRSAFunction privkey; privkey.Initialize(rng, 1024*8); // With the current version of Crypto++, MessageEnd() needs to be called // explicitly because Base64Encoder doesn't flush its buffer on destruction. string privKeyDer; StringSink privKeyDerSink(privKeyDer); privkey.DEREncode(privKeyDerSink); //Hash the pass phrase to create 128 bit key string hashedPass; RIPEMD128 hash; StringSource(pass, true, new HashFilter(hash, new StringSink(hashedPass))); // Generate a random IV byte iv[AES::BLOCKSIZE]; rng.GenerateBlock(iv, AES::BLOCKSIZE); //Encrypt private key CFB_Mode<AES>::Encryption cfbEncryption((const unsigned char*)hashedPass.c_str(), hashedPass.length(), iv); byte encPrivKey[privKeyDer.length()+1]; cfbEncryption.ProcessData(encPrivKey, (const byte*)privKeyDer.c_str(), privKeyDer.length()); string encPrivKeyStr((char *)encPrivKey, privKeyDer.length()); //Save private key to file StringSource encPrivKeySrc(encPrivKeyStr, true); Base64Encoder sink(new FileSink("master-privkey-enc.txt")); encPrivKeySrc.CopyTo(sink); sink.MessageEnd(); //Save initialization vector key to file StringSource ivStr(iv, AES::BLOCKSIZE, true); Base64Encoder sink2(new FileSink("master-privkey-iv.txt")); ivStr.CopyTo(sink2); sink2.MessageEnd(); // Suppose we want to store the public key separately, // possibly because we will be sending the public key to a third party. RSAFunction pubkey(privkey); Base64Encoder pubkeysink(new FileSink("master-pubkey.txt")); pubkey.DEREncode(pubkeysink); pubkeysink.MessageEnd(); } int main() { GenKeyPair(); } <|endoftext|>
<commit_before>#ifndef ITERTOOLS_HPP #define ITERTOOLS_HPP #include <chain.hpp> #include <combinations.hpp> #include <combinations_with_replacement.hpp> #include <compress.hpp> #include <count.hpp> #include <cycle.hpp> #include <dropwhile.hpp> #include <enumerate.hpp> #include <filter.hpp> #include <filterfalse.hpp> #include <groupby.hpp> #include <grouper.hpp> #include <imap.hpp> #include <iterator_range.hpp> #include <iterbase.hpp> #include <moving_section.hpp> #include <permutations.hpp> #include <powerset.hpp> #include <product.hpp> #include <range.hpp> #include <repeat.hpp> #include <reverse.hpp> #include <slice.hpp> #include <sorted.hpp> #include <takewhile.hpp> #include <unique_everseen.hpp> #include <unique_justseen.hpp> #include <wrap_iter.hpp> #include <zip.hpp> #include <zip_longest.hpp> //not sure if should include "iterator_range.hpp" //since it's already in everything #endif <commit_msg>Removes include of iterbase from itertools.hpp<commit_after>#ifndef ITERTOOLS_HPP #define ITERTOOLS_HPP #include <chain.hpp> #include <combinations.hpp> #include <combinations_with_replacement.hpp> #include <compress.hpp> #include <count.hpp> #include <cycle.hpp> #include <dropwhile.hpp> #include <enumerate.hpp> #include <filter.hpp> #include <filterfalse.hpp> #include <groupby.hpp> #include <grouper.hpp> #include <imap.hpp> #include <iterator_range.hpp> #include <moving_section.hpp> #include <permutations.hpp> #include <powerset.hpp> #include <product.hpp> #include <range.hpp> #include <repeat.hpp> #include <reverse.hpp> #include <slice.hpp> #include <sorted.hpp> #include <takewhile.hpp> #include <unique_everseen.hpp> #include <unique_justseen.hpp> #include <wrap_iter.hpp> #include <zip.hpp> #include <zip_longest.hpp> //not sure if should include "iterator_range.hpp" //since it's already in everything #endif <|endoftext|>
<commit_before>// Copyright 2020 Open Source Robotics Foundation, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <benchmark/benchmark.h> #include <memory> #include <string> #include <vector> #include "lifecycle_msgs/msg/state.hpp" #include "lifecycle_msgs/srv/change_state.hpp" #include "lifecycle_msgs/srv/get_available_states.hpp" #include "lifecycle_msgs/srv/get_available_transitions.hpp" #include "lifecycle_msgs/srv/get_state.hpp" #include "performance_test_fixture/performance_test_fixture.hpp" #include "rclcpp/rclcpp.hpp" #include "rclcpp_lifecycle/lifecycle_node.hpp" /** * Benchmarks for measuring performance of a lifecycle_node client. * * A service client of a lifecycle node is not a class that's explicitly part of ros2 core, * but it is the expected interface for interacting with a lifecycle node, so for that reason * this benchmark exists. */ using namespace std::chrono_literals; constexpr char const * lifecycle_node_name = "lc_talker"; constexpr char const * node_get_state_topic = "/lc_talker/get_state"; constexpr char const * node_change_state_topic = "/lc_talker/change_state"; constexpr char const * node_get_available_states_topic = "/lc_talker/get_available_states"; constexpr char const * node_get_available_transitions_topic = "/lc_talker/get_available_transitions"; constexpr char const * node_get_transition_graph_topic = "/lc_talker/get_transition_graph"; const lifecycle_msgs::msg::State unknown_state = lifecycle_msgs::msg::State(); class LifecycleServiceClient : public rclcpp::Node { public: explicit LifecycleServiceClient(std::string node_name) : Node(node_name) { client_get_available_states_ = this->create_client<lifecycle_msgs::srv::GetAvailableStates>( node_get_available_states_topic); client_get_available_transitions_ = this->create_client<lifecycle_msgs::srv::GetAvailableTransitions>( node_get_available_transitions_topic); client_get_transition_graph_ = this->create_client<lifecycle_msgs::srv::GetAvailableTransitions>( node_get_transition_graph_topic); client_get_state_ = this->create_client<lifecycle_msgs::srv::GetState>( node_get_state_topic); client_change_state_ = this->create_client<lifecycle_msgs::srv::ChangeState>( node_change_state_topic); } lifecycle_msgs::msg::State get_state(std::chrono::seconds time_out = 1s) { auto request = std::make_shared<lifecycle_msgs::srv::GetState::Request>(); if (!client_get_state_->wait_for_service(time_out)) { throw std::runtime_error("Wait for service timed out"); } auto future_result = client_get_state_->async_send_request(request); auto future_status = future_result.wait_for(time_out); if (future_status != std::future_status::ready) { throw std::runtime_error("Get state request failed"); } if (!future_result.valid()) { throw std::runtime_error("Future result was not valid"); } return future_result.get()->current_state; } bool change_state(std::uint8_t transition, std::chrono::seconds time_out = 1s) { auto request = std::make_shared<lifecycle_msgs::srv::ChangeState::Request>(); request->transition.id = transition; if (!client_change_state_->wait_for_service(time_out)) { throw std::runtime_error("Wait for service timed out"); } auto future_result = client_change_state_->async_send_request(request); auto future_status = future_result.wait_for(time_out); if (future_status != std::future_status::ready) { throw std::runtime_error("Change state request failed"); } if (!future_result.valid()) { throw std::runtime_error("Future result was not valid"); } return future_result.get()->success; } std::vector<lifecycle_msgs::msg::State> get_available_states(std::chrono::seconds time_out = 1s) { auto request = std::make_shared<lifecycle_msgs::srv::GetAvailableStates::Request>(); if (!client_get_available_states_->wait_for_service(time_out)) { throw std::runtime_error("Wait for service timed out"); } auto future_result = client_get_available_states_->async_send_request(request); auto future_status = future_result.wait_for(time_out); if (future_status != std::future_status::ready) { throw std::runtime_error("Get available states request failed"); } if (!future_result.valid()) { throw std::runtime_error("Future result was not valid"); } return future_result.get()->available_states; } std::vector<lifecycle_msgs::msg::TransitionDescription> get_available_transitions(std::chrono::seconds time_out = 1s) { auto request = std::make_shared<lifecycle_msgs::srv::GetAvailableTransitions::Request>(); if (!client_get_available_transitions_->wait_for_service(time_out)) { throw std::runtime_error("Wait for service timed out"); } auto future_result = client_get_available_transitions_->async_send_request(request); auto future_status = future_result.wait_for(time_out); if (future_status != std::future_status::ready) { throw std::runtime_error("Get available transitions request failed"); } if (!future_result.valid()) { throw std::runtime_error("Future result was not valid"); } return future_result.get()->available_transitions; } std::vector<lifecycle_msgs::msg::TransitionDescription> get_transition_graph(std::chrono::seconds time_out = 1s) { auto request = std::make_shared<lifecycle_msgs::srv::GetAvailableTransitions::Request>(); if (!client_get_transition_graph_->wait_for_service(time_out)) { throw std::runtime_error("Wait for service timed out"); } auto future_result = client_get_transition_graph_->async_send_request(request); auto future_status = future_result.wait_for(time_out); if (future_status != std::future_status::ready) { throw std::runtime_error("Get transition graph request failed"); } if (!future_result.valid()) { throw std::runtime_error("Future result was not valid"); } return future_result.get()->available_transitions; } private: std::shared_ptr<rclcpp::Client<lifecycle_msgs::srv::GetAvailableStates>> client_get_available_states_; std::shared_ptr<rclcpp::Client<lifecycle_msgs::srv::GetAvailableTransitions>> client_get_available_transitions_; std::shared_ptr<rclcpp::Client<lifecycle_msgs::srv::GetAvailableTransitions>> client_get_transition_graph_; std::shared_ptr<rclcpp::Client<lifecycle_msgs::srv::GetState>> client_get_state_; std::shared_ptr<rclcpp::Client<lifecycle_msgs::srv::ChangeState>> client_change_state_; }; class BenchmarkLifecycleClient : public performance_test_fixture::PerformanceTest { public: void SetUp(benchmark::State & state) { rclcpp::init(0, nullptr); lifecycle_node = std::make_shared<rclcpp_lifecycle::LifecycleNode>(lifecycle_node_name); lifecycle_client = std::make_shared<LifecycleServiceClient>("lifecycle_client"); executor = std::make_shared<rclcpp::executors::SingleThreadedExecutor>(); executor->add_node(lifecycle_node->get_node_base_interface()); executor->add_node(lifecycle_client->get_node_base_interface()); spinner_ = std::thread(&rclcpp::executors::SingleThreadedExecutor::spin, executor); performance_test_fixture::PerformanceTest::SetUp(state); } void TearDown(benchmark::State & state) { performance_test_fixture::PerformanceTest::TearDown(state); executor->cancel(); spinner_.join(); lifecycle_node.reset(); lifecycle_client.reset(); rclcpp::shutdown(); } protected: std::shared_ptr<rclcpp_lifecycle::LifecycleNode> lifecycle_node; std::shared_ptr<LifecycleServiceClient> lifecycle_client; std::shared_ptr<rclcpp::executors::SingleThreadedExecutor> executor; std::thread spinner_; }; BENCHMARK_F(BenchmarkLifecycleClient, get_state)(benchmark::State & state) { for (auto _ : state) { const auto lifecycle_state = lifecycle_client->get_state(); if (lifecycle_state.id != lifecycle_msgs::msg::State::PRIMARY_STATE_UNCONFIGURED) { const std::string msg = std::string("Expected state did not match actual: ") + std::to_string(lifecycle_state.id); state.SkipWithError(msg.c_str()); } benchmark::DoNotOptimize(lifecycle_state); benchmark::ClobberMemory(); } } BENCHMARK_F(BenchmarkLifecycleClient, change_state)(benchmark::State & state) { bool success = lifecycle_client->change_state(lifecycle_msgs::msg::Transition::TRANSITION_CONFIGURE); if (!success) { state.SkipWithError("Transition to configured state failed"); } reset_heap_counters(); for (auto _ : state) { success = lifecycle_client->change_state(lifecycle_msgs::msg::Transition::TRANSITION_ACTIVATE); if (!success) { state.SkipWithError("Transition to active state failed"); } success = lifecycle_client->change_state(lifecycle_msgs::msg::Transition::TRANSITION_DEACTIVATE); if (!success) { state.SkipWithError("Transition to inactive state failed"); } } } BENCHMARK_F(BenchmarkLifecycleClient, get_available_states)(benchmark::State & state) { for (auto _ : state) { constexpr size_t expected_states = 11u; const auto states = lifecycle_client->get_available_states(); if (states.size() != expected_states) { const std::string msg = std::string("Expected number of states did not match actual: ") + std::to_string(states.size()); state.SkipWithError(msg.c_str()); } benchmark::DoNotOptimize(states); benchmark::ClobberMemory(); } } BENCHMARK_F(BenchmarkLifecycleClient, get_available_transitions)(benchmark::State & state) { for (auto _ : state) { constexpr size_t expected_transitions = 2u; const auto transitions = lifecycle_client->get_available_transitions(); if (transitions.size() != expected_transitions) { const std::string msg = std::string("Expected number of transitions did not match actual: ") + std::to_string(transitions.size()); state.SkipWithError(msg.c_str()); } benchmark::DoNotOptimize(transitions); benchmark::ClobberMemory(); } } BENCHMARK_F(BenchmarkLifecycleClient, get_transition_graph)(benchmark::State & state) { for (auto _ : state) { constexpr size_t expected_transitions = 25u; const auto transitions = lifecycle_client->get_transition_graph(); if (transitions.size() != expected_transitions) { const std::string msg = std::string("Expected number of transitions did not match actual: ") + std::to_string(transitions.size()); state.SkipWithError(msg.c_str()); } benchmark::DoNotOptimize(transitions); benchmark::ClobberMemory(); } } <commit_msg>Fix destruction order in lifecycle benchmark (#1675)<commit_after>// Copyright 2020 Open Source Robotics Foundation, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <benchmark/benchmark.h> #include <memory> #include <string> #include <vector> #include "lifecycle_msgs/msg/state.hpp" #include "lifecycle_msgs/srv/change_state.hpp" #include "lifecycle_msgs/srv/get_available_states.hpp" #include "lifecycle_msgs/srv/get_available_transitions.hpp" #include "lifecycle_msgs/srv/get_state.hpp" #include "performance_test_fixture/performance_test_fixture.hpp" #include "rclcpp/rclcpp.hpp" #include "rclcpp_lifecycle/lifecycle_node.hpp" /** * Benchmarks for measuring performance of a lifecycle_node client. * * A service client of a lifecycle node is not a class that's explicitly part of ros2 core, * but it is the expected interface for interacting with a lifecycle node, so for that reason * this benchmark exists. */ using namespace std::chrono_literals; constexpr char const * lifecycle_node_name = "lc_talker"; constexpr char const * node_get_state_topic = "/lc_talker/get_state"; constexpr char const * node_change_state_topic = "/lc_talker/change_state"; constexpr char const * node_get_available_states_topic = "/lc_talker/get_available_states"; constexpr char const * node_get_available_transitions_topic = "/lc_talker/get_available_transitions"; constexpr char const * node_get_transition_graph_topic = "/lc_talker/get_transition_graph"; const lifecycle_msgs::msg::State unknown_state = lifecycle_msgs::msg::State(); class LifecycleServiceClient : public rclcpp::Node { public: explicit LifecycleServiceClient(std::string node_name) : Node(node_name) { client_get_available_states_ = this->create_client<lifecycle_msgs::srv::GetAvailableStates>( node_get_available_states_topic); client_get_available_transitions_ = this->create_client<lifecycle_msgs::srv::GetAvailableTransitions>( node_get_available_transitions_topic); client_get_transition_graph_ = this->create_client<lifecycle_msgs::srv::GetAvailableTransitions>( node_get_transition_graph_topic); client_get_state_ = this->create_client<lifecycle_msgs::srv::GetState>( node_get_state_topic); client_change_state_ = this->create_client<lifecycle_msgs::srv::ChangeState>( node_change_state_topic); } lifecycle_msgs::msg::State get_state(std::chrono::seconds time_out = 1s) { auto request = std::make_shared<lifecycle_msgs::srv::GetState::Request>(); if (!client_get_state_->wait_for_service(time_out)) { throw std::runtime_error("Wait for service timed out"); } auto future_result = client_get_state_->async_send_request(request); auto future_status = future_result.wait_for(time_out); if (future_status != std::future_status::ready) { throw std::runtime_error("Get state request failed"); } if (!future_result.valid()) { throw std::runtime_error("Future result was not valid"); } return future_result.get()->current_state; } bool change_state(std::uint8_t transition, std::chrono::seconds time_out = 1s) { auto request = std::make_shared<lifecycle_msgs::srv::ChangeState::Request>(); request->transition.id = transition; if (!client_change_state_->wait_for_service(time_out)) { throw std::runtime_error("Wait for service timed out"); } auto future_result = client_change_state_->async_send_request(request); auto future_status = future_result.wait_for(time_out); if (future_status != std::future_status::ready) { throw std::runtime_error("Change state request failed"); } if (!future_result.valid()) { throw std::runtime_error("Future result was not valid"); } return future_result.get()->success; } std::vector<lifecycle_msgs::msg::State> get_available_states(std::chrono::seconds time_out = 1s) { auto request = std::make_shared<lifecycle_msgs::srv::GetAvailableStates::Request>(); if (!client_get_available_states_->wait_for_service(time_out)) { throw std::runtime_error("Wait for service timed out"); } auto future_result = client_get_available_states_->async_send_request(request); auto future_status = future_result.wait_for(time_out); if (future_status != std::future_status::ready) { throw std::runtime_error("Get available states request failed"); } if (!future_result.valid()) { throw std::runtime_error("Future result was not valid"); } return future_result.get()->available_states; } std::vector<lifecycle_msgs::msg::TransitionDescription> get_available_transitions(std::chrono::seconds time_out = 1s) { auto request = std::make_shared<lifecycle_msgs::srv::GetAvailableTransitions::Request>(); if (!client_get_available_transitions_->wait_for_service(time_out)) { throw std::runtime_error("Wait for service timed out"); } auto future_result = client_get_available_transitions_->async_send_request(request); auto future_status = future_result.wait_for(time_out); if (future_status != std::future_status::ready) { throw std::runtime_error("Get available transitions request failed"); } if (!future_result.valid()) { throw std::runtime_error("Future result was not valid"); } return future_result.get()->available_transitions; } std::vector<lifecycle_msgs::msg::TransitionDescription> get_transition_graph(std::chrono::seconds time_out = 1s) { auto request = std::make_shared<lifecycle_msgs::srv::GetAvailableTransitions::Request>(); if (!client_get_transition_graph_->wait_for_service(time_out)) { throw std::runtime_error("Wait for service timed out"); } auto future_result = client_get_transition_graph_->async_send_request(request); auto future_status = future_result.wait_for(time_out); if (future_status != std::future_status::ready) { throw std::runtime_error("Get transition graph request failed"); } if (!future_result.valid()) { throw std::runtime_error("Future result was not valid"); } return future_result.get()->available_transitions; } private: std::shared_ptr<rclcpp::Client<lifecycle_msgs::srv::GetAvailableStates>> client_get_available_states_; std::shared_ptr<rclcpp::Client<lifecycle_msgs::srv::GetAvailableTransitions>> client_get_available_transitions_; std::shared_ptr<rclcpp::Client<lifecycle_msgs::srv::GetAvailableTransitions>> client_get_transition_graph_; std::shared_ptr<rclcpp::Client<lifecycle_msgs::srv::GetState>> client_get_state_; std::shared_ptr<rclcpp::Client<lifecycle_msgs::srv::ChangeState>> client_change_state_; }; class BenchmarkLifecycleClient : public performance_test_fixture::PerformanceTest { public: void SetUp(benchmark::State & state) { rclcpp::init(0, nullptr); lifecycle_node = std::make_shared<rclcpp_lifecycle::LifecycleNode>(lifecycle_node_name); lifecycle_client = std::make_shared<LifecycleServiceClient>("lifecycle_client"); executor = std::make_shared<rclcpp::executors::SingleThreadedExecutor>(); executor->add_node(lifecycle_node->get_node_base_interface()); executor->add_node(lifecycle_client->get_node_base_interface()); spinner_ = std::thread(&rclcpp::executors::SingleThreadedExecutor::spin, executor); performance_test_fixture::PerformanceTest::SetUp(state); } void TearDown(benchmark::State & state) { performance_test_fixture::PerformanceTest::TearDown(state); executor->cancel(); spinner_.join(); executor.reset(); lifecycle_client.reset(); lifecycle_node.reset(); rclcpp::shutdown(); } protected: std::shared_ptr<rclcpp_lifecycle::LifecycleNode> lifecycle_node; std::shared_ptr<LifecycleServiceClient> lifecycle_client; std::shared_ptr<rclcpp::executors::SingleThreadedExecutor> executor; std::thread spinner_; }; BENCHMARK_F(BenchmarkLifecycleClient, get_state)(benchmark::State & state) { for (auto _ : state) { const auto lifecycle_state = lifecycle_client->get_state(); if (lifecycle_state.id != lifecycle_msgs::msg::State::PRIMARY_STATE_UNCONFIGURED) { const std::string msg = std::string("Expected state did not match actual: ") + std::to_string(lifecycle_state.id); state.SkipWithError(msg.c_str()); } benchmark::DoNotOptimize(lifecycle_state); benchmark::ClobberMemory(); } } BENCHMARK_F(BenchmarkLifecycleClient, change_state)(benchmark::State & state) { bool success = lifecycle_client->change_state(lifecycle_msgs::msg::Transition::TRANSITION_CONFIGURE); if (!success) { state.SkipWithError("Transition to configured state failed"); } reset_heap_counters(); for (auto _ : state) { success = lifecycle_client->change_state(lifecycle_msgs::msg::Transition::TRANSITION_ACTIVATE); if (!success) { state.SkipWithError("Transition to active state failed"); } success = lifecycle_client->change_state(lifecycle_msgs::msg::Transition::TRANSITION_DEACTIVATE); if (!success) { state.SkipWithError("Transition to inactive state failed"); } } } BENCHMARK_F(BenchmarkLifecycleClient, get_available_states)(benchmark::State & state) { for (auto _ : state) { constexpr size_t expected_states = 11u; const auto states = lifecycle_client->get_available_states(); if (states.size() != expected_states) { const std::string msg = std::string("Expected number of states did not match actual: ") + std::to_string(states.size()); state.SkipWithError(msg.c_str()); } benchmark::DoNotOptimize(states); benchmark::ClobberMemory(); } } BENCHMARK_F(BenchmarkLifecycleClient, get_available_transitions)(benchmark::State & state) { for (auto _ : state) { constexpr size_t expected_transitions = 2u; const auto transitions = lifecycle_client->get_available_transitions(); if (transitions.size() != expected_transitions) { const std::string msg = std::string("Expected number of transitions did not match actual: ") + std::to_string(transitions.size()); state.SkipWithError(msg.c_str()); } benchmark::DoNotOptimize(transitions); benchmark::ClobberMemory(); } } BENCHMARK_F(BenchmarkLifecycleClient, get_transition_graph)(benchmark::State & state) { for (auto _ : state) { constexpr size_t expected_transitions = 25u; const auto transitions = lifecycle_client->get_transition_graph(); if (transitions.size() != expected_transitions) { const std::string msg = std::string("Expected number of transitions did not match actual: ") + std::to_string(transitions.size()); state.SkipWithError(msg.c_str()); } benchmark::DoNotOptimize(transitions); benchmark::ClobberMemory(); } } <|endoftext|>
<commit_before>#include "Simulator.h" #include "DistanceCalculator.h" #include <chrono> #include <thread> extern DistanceCalculator gDistanceCalculator; Simulator::Simulator() :ThreadedClass("Simulator") { self.fieldCoords = cv::Point(-100, 100); self.polarMetricCoords = cv::Point(0,0); // distribute balls uniformly for (int i = 0; i < NUMBER_OF_BALLS; i++) { balls[i].fieldCoords.x = ((i % 3) - 1) * 100; balls[i].fieldCoords.y = (i / 3 - 1.5) * 110; balls[i].id = i; } Start(); } void Simulator::UpdateGatePos(){ // angles are wrong double a1 = gDistanceCalculator.angleBetween(self.fieldCoords, blueGate.fieldCoords) + self.getAngle(); double a2 = gDistanceCalculator.angleBetween(self.fieldCoords, yellowGate.fieldCoords) + self.getAngle(); double d1 = gDistanceCalculator.getDistanceInverted(self.fieldCoords, blueGate.fieldCoords); double d2 = gDistanceCalculator.getDistanceInverted(self.fieldCoords, yellowGate.fieldCoords); // draw gates frame_blank.copyTo(frame); double x1 = d1*sin(a1 / 180 * CV_PI); double y1 = d1*cos(a1 / 180 * CV_PI); double x2 = d2*sin(a2 / 180 * CV_PI); double y2 = d2*cos(a2 / 180 * CV_PI); cv::Scalar color(236, 137, 48); cv::Scalar color2(61, 255, 244); cv::circle(frame, cv::Point(x1, y1) + cv::Point(frame.size() / 2), 38, color, -1); cv::circle(frame, cv::Point(x2, y2) + cv::Point(frame.size() / 2), 38, color2, -1); // balls for (int i = 0; i < NUMBER_OF_BALLS; i++){ double a = gDistanceCalculator.angleBetween(self.fieldCoords, balls[i].fieldCoords) + self.getAngle(); double d = gDistanceCalculator.getDistanceInverted(self.fieldCoords, balls[i].fieldCoords); double x = d*sin(a / 180 * CV_PI); double y = d*cos(a / 180 * CV_PI); cv::Scalar color(48, 154, 236); cv::circle(frame, cv::Point(x, y) + cv::Point(frame.size() / 2), 12, color, -1); } { std::lock_guard<std::mutex> lock(mutex); frame.copyTo(frame_copy); } } void Simulator::UpdateRobotPos(){ UpdateGatePos(); } Simulator::~Simulator() { WaitForStop(); } cv::Mat & Simulator::Capture(bool bFullFrame){ return frame_copy; } cv::Size Simulator::GetFrameSize(bool bFullFrame){ return frame.size(); } double Simulator::GetFPS(){ return 0; } cv::Mat & Simulator::GetLastFrame(bool bFullFrame){ return frame; } void Simulator::TogglePlay(){ } void Simulator::Drive(double fowardSpeed, double direction, double angularSpeed){ self.polarMetricCoords.y += angularSpeed; self.fieldCoords.x += fowardSpeed * sin((direction - self.getAngle()) / 180 * CV_PI); self.fieldCoords.y += fowardSpeed * cos((direction - self.getAngle()) / 180 * CV_PI); } const Speed & Simulator::GetActualSpeed(){ return actualSpeed; } const Speed & Simulator::GetTargetSpeed(){ return targetSpeed; } void Simulator::Init(){ } std::string Simulator::GetDebugInfo() { return "simulating wheels"; } void Simulator::Run(){ while (!stop_thread){ UpdateRobotPos(); std::this_thread::sleep_for(std::chrono::milliseconds(50)); } }<commit_msg>angles fixed<commit_after>#include "Simulator.h" #include "DistanceCalculator.h" #include <chrono> #include <thread> extern DistanceCalculator gDistanceCalculator; Simulator::Simulator() :ThreadedClass("Simulator") { self.fieldCoords = cv::Point(-100, 100); self.polarMetricCoords = cv::Point(0,0); // distribute balls uniformly for (int i = 0; i < NUMBER_OF_BALLS; i++) { balls[i].fieldCoords.x = ((i % 3) - 1) * 100; balls[i].fieldCoords.y = (i / 3 - 1.5) * 110; balls[i].id = i; } Start(); } void Simulator::UpdateGatePos(){ double a1 = gDistanceCalculator.angleBetween(cv::Point(0, 1), self.fieldCoords- blueGate.fieldCoords) + self.getAngle(); double a2 = gDistanceCalculator.angleBetween(cv::Point(0, 1), self.fieldCoords - yellowGate.fieldCoords) + self.getAngle(); double d1 = gDistanceCalculator.getDistanceInverted(self.fieldCoords, blueGate.fieldCoords); double d2 = gDistanceCalculator.getDistanceInverted(self.fieldCoords, yellowGate.fieldCoords); // draw gates frame_blank.copyTo(frame); double x1 = d1*sin(a1 / 180 * CV_PI); double y1 = d1*cos(a1 / 180 * CV_PI); double x2 = d2*sin(a2 / 180 * CV_PI); double y2 = d2*cos(a2 / 180 * CV_PI); cv::Scalar color(236, 137, 48); cv::Scalar color2(61, 255, 244); cv::circle(frame, cv::Point(x1, y1) + cv::Point(frame.size() / 2), 38, color, -1); cv::circle(frame, cv::Point(x2, y2) + cv::Point(frame.size() / 2), 38, color2, -1); // balls for (int i = 0; i < NUMBER_OF_BALLS; i++){ double a = gDistanceCalculator.angleBetween(cv::Point(0, 1), self.fieldCoords - balls[i].fieldCoords) + self.getAngle(); double d = gDistanceCalculator.getDistanceInverted(self.fieldCoords, balls[i].fieldCoords); double x = d*sin(a / 180 * CV_PI); double y = d*cos(a / 180 * CV_PI); cv::Scalar color(48, 154, 236); cv::circle(frame, cv::Point(x, y) + cv::Point(frame.size() / 2), 12, color, -1); } { std::lock_guard<std::mutex> lock(mutex); frame.copyTo(frame_copy); } } void Simulator::UpdateRobotPos(){ UpdateGatePos(); } Simulator::~Simulator() { WaitForStop(); } cv::Mat & Simulator::Capture(bool bFullFrame){ return frame_copy; } cv::Size Simulator::GetFrameSize(bool bFullFrame){ return frame.size(); } double Simulator::GetFPS(){ return 0; } cv::Mat & Simulator::GetLastFrame(bool bFullFrame){ return frame; } void Simulator::TogglePlay(){ } void Simulator::Drive(double fowardSpeed, double direction, double angularSpeed){ self.polarMetricCoords.y += angularSpeed; self.fieldCoords.x += fowardSpeed * sin((direction - self.getAngle()) / 180 * CV_PI); self.fieldCoords.y += fowardSpeed * cos((direction - self.getAngle()) / 180 * CV_PI); } const Speed & Simulator::GetActualSpeed(){ return actualSpeed; } const Speed & Simulator::GetTargetSpeed(){ return targetSpeed; } void Simulator::Init(){ } std::string Simulator::GetDebugInfo() { return "simulating wheels"; } void Simulator::Run(){ while (!stop_thread){ UpdateRobotPos(); std::this_thread::sleep_for(std::chrono::milliseconds(50)); } }<|endoftext|>
<commit_before>#include <stdafx.h> #include <playfab/PlayFabCurlHttpPlugin.h> #include <playfab/PlayFabSettings.h> #include <curl/curl.h> #include <stdexcept> namespace PlayFab { PlayFabCurlHttpPlugin::PlayFabCurlHttpPlugin() { activeRequestCount = 0; threadRunning = true; workerThread = std::thread(&PlayFabCurlHttpPlugin::WorkerThread, this); }; PlayFabCurlHttpPlugin::~PlayFabCurlHttpPlugin() { threadRunning = false; try { workerThread.join(); } catch (...) { } } void PlayFabCurlHttpPlugin::WorkerThread() { size_t queueSize; while (this->threadRunning) { try { std::unique_ptr<CallRequestContainerBase> requestContainer = nullptr; { // LOCK httpRequestMutex std::unique_lock<std::mutex> lock(this->httpRequestMutex); queueSize = this->pendingRequests.size(); if (queueSize != 0) { requestContainer = std::move(this->pendingRequests[0]); this->pendingRequests.pop_front(); } } // UNLOCK httpRequestMutex if (queueSize == 0) { std::this_thread::sleep_for(std::chrono::milliseconds(10)); continue; } if (requestContainer != nullptr) { CallRequestContainer* requestContainerPtr = dynamic_cast<CallRequestContainer*>(requestContainer.get()); if (requestContainerPtr != nullptr) { requestContainer.release(); ExecuteRequest(std::unique_ptr<CallRequestContainer>(requestContainerPtr)); } } } catch (const std::exception& ex) { PlayFabPluginManager::GetInstance().HandleException(ex); } catch (...) { } } } void PlayFabCurlHttpPlugin::HandleCallback(std::unique_ptr<CallRequestContainer> requestContainer) { CallRequestContainer& reqContainer = *requestContainer; reqContainer.finished = true; if (PlayFabSettings::threadedCallbacks) { HandleResults(std::move(requestContainer)); } if (!PlayFabSettings::threadedCallbacks) { { // LOCK httpRequestMutex std::unique_lock<std::mutex> lock(httpRequestMutex); pendingResults.push_back(std::unique_ptr<CallRequestContainerBase>(static_cast<CallRequestContainerBase*>(requestContainer.release()))); } // UNLOCK httpRequestMutex } } size_t PlayFabCurlHttpPlugin::CurlReceiveData(char* buffer, size_t blockSize, size_t blockCount, void* userData) { CallRequestContainer* reqContainer = reinterpret_cast<CallRequestContainer*>(userData); reqContainer->responseString.append(buffer, blockSize * blockCount); return (blockSize * blockCount); } void PlayFabCurlHttpPlugin::MakePostRequest(std::unique_ptr<CallRequestContainerBase> requestContainer) { { // LOCK httpRequestMutex std::unique_lock<std::mutex> lock(httpRequestMutex); pendingRequests.push_back(std::move(requestContainer)); activeRequestCount++; } // UNLOCK httpRequestMutex } void PlayFabCurlHttpPlugin::ExecuteRequest(std::unique_ptr<CallRequestContainer> requestContainer) { CallRequestContainer& reqContainer = *requestContainer; // Set up curl handle CURL* curlHandle = curl_easy_init(); curl_easy_reset(curlHandle); curl_easy_setopt(curlHandle, CURLOPT_NOSIGNAL, true); std::string urlString = reqContainer.GetFullUrl(); curl_easy_setopt(curlHandle, CURLOPT_URL, urlString.c_str()); // Set up headers curl_slist* curlHttpHeaders = nullptr; curlHttpHeaders = curl_slist_append(curlHttpHeaders, "Accept: application/json"); curlHttpHeaders = curl_slist_append(curlHttpHeaders, "Content-Type: application/json; charset=utf-8"); curlHttpHeaders = curl_slist_append(curlHttpHeaders, ("X-PlayFabSDK: " + PlayFabSettings::versionString).c_str()); curlHttpHeaders = curl_slist_append(curlHttpHeaders, "X-ReportErrorAsSuccess: true"); auto headers = reqContainer.GetHeaders(); if (headers.size() > 0) { for (auto const &obj : headers) { if (obj.first.length() != 0 && obj.second.length() != 0) // no empty keys or values in headers { std::string header = obj.first + ": " + obj.second; curlHttpHeaders = curl_slist_append(curlHttpHeaders, header.c_str()); } } } curl_easy_setopt(curlHandle, CURLOPT_HTTPHEADER, curlHttpHeaders); // Set up post & payload std::string payload = reqContainer.GetRequestBody(); curl_easy_setopt(curlHandle, CURLOPT_POST, nullptr); curl_easy_setopt(curlHandle, CURLOPT_POSTFIELDS, payload.c_str()); // Process result // TODO: CURLOPT_ERRORBUFFER ? curl_easy_setopt(curlHandle, CURLOPT_TIMEOUT_MS, 10000L); curl_easy_setopt(curlHandle, CURLOPT_WRITEDATA, &reqContainer); curl_easy_setopt(curlHandle, CURLOPT_WRITEFUNCTION, CurlReceiveData); // Send curl_easy_setopt(curlHandle, CURLOPT_SSL_VERIFYPEER, false); // TODO: Replace this with a ca-bundle ref??? const auto res = curl_easy_perform(curlHandle); long curlHttpResponseCode = 0; curl_easy_getinfo(curlHandle, CURLINFO_RESPONSE_CODE, &curlHttpResponseCode); if (res != CURLE_OK) { reqContainer.errorWrapper.HttpCode = curlHttpResponseCode != 0 ? curlHttpResponseCode : 408; reqContainer.errorWrapper.HttpStatus = "Failed to contact server"; reqContainer.errorWrapper.ErrorCode = PlayFabErrorConnectionTimeout; reqContainer.errorWrapper.ErrorName = "Failed to contact server"; reqContainer.errorWrapper.ErrorMessage = "Failed to contact server, curl error: " + std::to_string(res); HandleCallback(std::move(requestContainer)); } else { Json::CharReaderBuilder jsonReaderFactory; std::unique_ptr<Json::CharReader> jsonReader(jsonReaderFactory.newCharReader()); JSONCPP_STRING jsonParseErrors; const bool parsedSuccessfully = jsonReader->parse(reqContainer.responseString.c_str(), reqContainer.responseString.c_str() + reqContainer.responseString.length(), &reqContainer.responseJson, &jsonParseErrors); if (parsedSuccessfully) { reqContainer.errorWrapper.HttpCode = reqContainer.responseJson.get("code", Json::Value::null).asInt(); reqContainer.errorWrapper.HttpStatus = reqContainer.responseJson.get("status", Json::Value::null).asString(); reqContainer.errorWrapper.Data = reqContainer.responseJson.get("data", Json::Value::null); reqContainer.errorWrapper.ErrorName = reqContainer.responseJson.get("error", Json::Value::null).asString(); reqContainer.errorWrapper.ErrorCode = static_cast<PlayFabErrorCode>(reqContainer.responseJson.get("errorCode", Json::Value::null).asInt()); reqContainer.errorWrapper.ErrorMessage = reqContainer.responseJson.get("errorMessage", Json::Value::null).asString(); reqContainer.errorWrapper.ErrorDetails = reqContainer.responseJson.get("errorDetails", Json::Value::null); } else { reqContainer.errorWrapper.HttpCode = curlHttpResponseCode != 0 ? curlHttpResponseCode : 408; reqContainer.errorWrapper.HttpStatus = reqContainer.responseString; reqContainer.errorWrapper.ErrorCode = PlayFabErrorConnectionTimeout; reqContainer.errorWrapper.ErrorName = "Failed to parse PlayFab response"; reqContainer.errorWrapper.ErrorMessage = jsonParseErrors; } HandleCallback(std::move(requestContainer)); } curl_slist_free_all(curlHttpHeaders); curlHttpHeaders = nullptr; curl_easy_cleanup(curlHandle); } void PlayFabCurlHttpPlugin::HandleResults(std::unique_ptr<CallRequestContainer> requestContainer) { CallRequestContainer& reqContainer = *requestContainer; auto callback = reqContainer.GetCallback(); if (callback != nullptr) { callback( reqContainer.responseJson.get("code", Json::Value::null).asInt(), reqContainer.responseString, std::unique_ptr<CallRequestContainerBase>(static_cast<CallRequestContainerBase*>(requestContainer.release()))); } } size_t PlayFabCurlHttpPlugin::Update() { if (PlayFabSettings::threadedCallbacks) { throw std::runtime_error("You should not call Update() when PlayFabSettings::threadedCallbacks == true"); } std::unique_ptr<CallRequestContainerBase> requestContainer = nullptr; { // LOCK httpRequestMutex std::unique_lock<std::mutex> lock(httpRequestMutex); if (pendingResults.empty()) { return activeRequestCount; } requestContainer = std::move(this->pendingResults[0]); this->pendingResults.pop_front(); activeRequestCount--; } // UNLOCK httpRequestMutex HandleResults(std::unique_ptr<CallRequestContainer>(static_cast<CallRequestContainer*>(requestContainer.release()))); // activeRequestCount can be altered by HandleResults, so we have to re-lock and return an updated value { // LOCK httpRequestMutex std::unique_lock<std::mutex> lock(httpRequestMutex); return activeRequestCount; } } } <commit_msg>Bug fix: Curl Http plugin is disabling CURLOPT_SSL_VERIFYPEER (#553)<commit_after>#include <stdafx.h> #include <playfab/PlayFabCurlHttpPlugin.h> #include <playfab/PlayFabSettings.h> #include <curl/curl.h> #include <stdexcept> namespace PlayFab { PlayFabCurlHttpPlugin::PlayFabCurlHttpPlugin() { activeRequestCount = 0; threadRunning = true; workerThread = std::thread(&PlayFabCurlHttpPlugin::WorkerThread, this); }; PlayFabCurlHttpPlugin::~PlayFabCurlHttpPlugin() { threadRunning = false; try { workerThread.join(); } catch (...) { } } void PlayFabCurlHttpPlugin::WorkerThread() { size_t queueSize; while (this->threadRunning) { try { std::unique_ptr<CallRequestContainerBase> requestContainer = nullptr; { // LOCK httpRequestMutex std::unique_lock<std::mutex> lock(this->httpRequestMutex); queueSize = this->pendingRequests.size(); if (queueSize != 0) { requestContainer = std::move(this->pendingRequests[0]); this->pendingRequests.pop_front(); } } // UNLOCK httpRequestMutex if (queueSize == 0) { std::this_thread::sleep_for(std::chrono::milliseconds(10)); continue; } if (requestContainer != nullptr) { CallRequestContainer* requestContainerPtr = dynamic_cast<CallRequestContainer*>(requestContainer.get()); if (requestContainerPtr != nullptr) { requestContainer.release(); ExecuteRequest(std::unique_ptr<CallRequestContainer>(requestContainerPtr)); } } } catch (const std::exception& ex) { PlayFabPluginManager::GetInstance().HandleException(ex); } catch (...) { } } } void PlayFabCurlHttpPlugin::HandleCallback(std::unique_ptr<CallRequestContainer> requestContainer) { CallRequestContainer& reqContainer = *requestContainer; reqContainer.finished = true; if (PlayFabSettings::threadedCallbacks) { HandleResults(std::move(requestContainer)); } if (!PlayFabSettings::threadedCallbacks) { { // LOCK httpRequestMutex std::unique_lock<std::mutex> lock(httpRequestMutex); pendingResults.push_back(std::unique_ptr<CallRequestContainerBase>(static_cast<CallRequestContainerBase*>(requestContainer.release()))); } // UNLOCK httpRequestMutex } } size_t PlayFabCurlHttpPlugin::CurlReceiveData(char* buffer, size_t blockSize, size_t blockCount, void* userData) { CallRequestContainer* reqContainer = reinterpret_cast<CallRequestContainer*>(userData); reqContainer->responseString.append(buffer, blockSize * blockCount); return (blockSize * blockCount); } void PlayFabCurlHttpPlugin::MakePostRequest(std::unique_ptr<CallRequestContainerBase> requestContainer) { { // LOCK httpRequestMutex std::unique_lock<std::mutex> lock(httpRequestMutex); pendingRequests.push_back(std::move(requestContainer)); activeRequestCount++; } // UNLOCK httpRequestMutex } void PlayFabCurlHttpPlugin::ExecuteRequest(std::unique_ptr<CallRequestContainer> requestContainer) { CallRequestContainer& reqContainer = *requestContainer; // Set up curl handle CURL* curlHandle = curl_easy_init(); curl_easy_reset(curlHandle); curl_easy_setopt(curlHandle, CURLOPT_NOSIGNAL, true); std::string urlString = reqContainer.GetFullUrl(); curl_easy_setopt(curlHandle, CURLOPT_URL, urlString.c_str()); // Set up headers curl_slist* curlHttpHeaders = nullptr; curlHttpHeaders = curl_slist_append(curlHttpHeaders, "Accept: application/json"); curlHttpHeaders = curl_slist_append(curlHttpHeaders, "Content-Type: application/json; charset=utf-8"); curlHttpHeaders = curl_slist_append(curlHttpHeaders, ("X-PlayFabSDK: " + PlayFabSettings::versionString).c_str()); curlHttpHeaders = curl_slist_append(curlHttpHeaders, "X-ReportErrorAsSuccess: true"); auto headers = reqContainer.GetHeaders(); if (headers.size() > 0) { for (auto const &obj : headers) { if (obj.first.length() != 0 && obj.second.length() != 0) // no empty keys or values in headers { std::string header = obj.first + ": " + obj.second; curlHttpHeaders = curl_slist_append(curlHttpHeaders, header.c_str()); } } } curl_easy_setopt(curlHandle, CURLOPT_HTTPHEADER, curlHttpHeaders); // Set up post & payload std::string payload = reqContainer.GetRequestBody(); curl_easy_setopt(curlHandle, CURLOPT_POST, nullptr); curl_easy_setopt(curlHandle, CURLOPT_POSTFIELDS, payload.c_str()); // Process result // TODO: CURLOPT_ERRORBUFFER ? curl_easy_setopt(curlHandle, CURLOPT_TIMEOUT_MS, 10000L); curl_easy_setopt(curlHandle, CURLOPT_WRITEDATA, &reqContainer); curl_easy_setopt(curlHandle, CURLOPT_WRITEFUNCTION, CurlReceiveData); // Send curl_easy_setopt(curlHandle, CURLOPT_SSL_VERIFYPEER, true); const auto res = curl_easy_perform(curlHandle); long curlHttpResponseCode = 0; curl_easy_getinfo(curlHandle, CURLINFO_RESPONSE_CODE, &curlHttpResponseCode); if (res != CURLE_OK) { reqContainer.errorWrapper.HttpCode = curlHttpResponseCode != 0 ? curlHttpResponseCode : 408; reqContainer.errorWrapper.HttpStatus = "Failed to contact server"; reqContainer.errorWrapper.ErrorCode = PlayFabErrorConnectionTimeout; reqContainer.errorWrapper.ErrorName = "Failed to contact server"; reqContainer.errorWrapper.ErrorMessage = "Failed to contact server, curl error: " + std::to_string(res); HandleCallback(std::move(requestContainer)); } else { Json::CharReaderBuilder jsonReaderFactory; std::unique_ptr<Json::CharReader> jsonReader(jsonReaderFactory.newCharReader()); JSONCPP_STRING jsonParseErrors; const bool parsedSuccessfully = jsonReader->parse(reqContainer.responseString.c_str(), reqContainer.responseString.c_str() + reqContainer.responseString.length(), &reqContainer.responseJson, &jsonParseErrors); if (parsedSuccessfully) { reqContainer.errorWrapper.HttpCode = reqContainer.responseJson.get("code", Json::Value::null).asInt(); reqContainer.errorWrapper.HttpStatus = reqContainer.responseJson.get("status", Json::Value::null).asString(); reqContainer.errorWrapper.Data = reqContainer.responseJson.get("data", Json::Value::null); reqContainer.errorWrapper.ErrorName = reqContainer.responseJson.get("error", Json::Value::null).asString(); reqContainer.errorWrapper.ErrorCode = static_cast<PlayFabErrorCode>(reqContainer.responseJson.get("errorCode", Json::Value::null).asInt()); reqContainer.errorWrapper.ErrorMessage = reqContainer.responseJson.get("errorMessage", Json::Value::null).asString(); reqContainer.errorWrapper.ErrorDetails = reqContainer.responseJson.get("errorDetails", Json::Value::null); } else { reqContainer.errorWrapper.HttpCode = curlHttpResponseCode != 0 ? curlHttpResponseCode : 408; reqContainer.errorWrapper.HttpStatus = reqContainer.responseString; reqContainer.errorWrapper.ErrorCode = PlayFabErrorConnectionTimeout; reqContainer.errorWrapper.ErrorName = "Failed to parse PlayFab response"; reqContainer.errorWrapper.ErrorMessage = jsonParseErrors; } HandleCallback(std::move(requestContainer)); } curl_slist_free_all(curlHttpHeaders); curlHttpHeaders = nullptr; curl_easy_cleanup(curlHandle); } void PlayFabCurlHttpPlugin::HandleResults(std::unique_ptr<CallRequestContainer> requestContainer) { CallRequestContainer& reqContainer = *requestContainer; auto callback = reqContainer.GetCallback(); if (callback != nullptr) { callback( reqContainer.responseJson.get("code", Json::Value::null).asInt(), reqContainer.responseString, std::unique_ptr<CallRequestContainerBase>(static_cast<CallRequestContainerBase*>(requestContainer.release()))); } } size_t PlayFabCurlHttpPlugin::Update() { if (PlayFabSettings::threadedCallbacks) { throw std::runtime_error("You should not call Update() when PlayFabSettings::threadedCallbacks == true"); } std::unique_ptr<CallRequestContainerBase> requestContainer = nullptr; { // LOCK httpRequestMutex std::unique_lock<std::mutex> lock(httpRequestMutex); if (pendingResults.empty()) { return activeRequestCount; } requestContainer = std::move(this->pendingResults[0]); this->pendingResults.pop_front(); activeRequestCount--; } // UNLOCK httpRequestMutex HandleResults(std::unique_ptr<CallRequestContainer>(static_cast<CallRequestContainer*>(requestContainer.release()))); // activeRequestCount can be altered by HandleResults, so we have to re-lock and return an updated value { // LOCK httpRequestMutex std::unique_lock<std::mutex> lock(httpRequestMutex); return activeRequestCount; } } } <|endoftext|>
<commit_before>// Copyright 2015 Open Source Robotics Foundation, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef TEST_ARRAY_GENERATOR_HPP_ #define TEST_ARRAY_GENERATOR_HPP_ #include <climits> #include <random> #include <string> #include <type_traits> /** * Helper function to generate a test pattern for boolean type. * Alternating true (even index) and false (odd index) pattern. * @param C Container (vector, array, etc) to be filled * @param size How many elements to fill in. Must size<=container_size */ template< typename C, typename std::enable_if< std::is_same<typename C::value_type, bool>::value >::type * = nullptr > void test_vector_fill(C * container, size_t size, bool val1 = true, bool val2 = false) { for (size_t i = 0; i < size; i++) { if ((i % 2) == 0) { (*container)[i] = val2; } else { (*container)[i] = val1; } } } /** * Helper function to generate a test pattern for integer number types. * The template type parameter must be an integer number type. * Mininum and maximum values for the type and random values in the middle. * @param C Container (vector, array, etc) to be filled * @param size How many elements to fill in. Must size<=container_size * @param min Minimum value in the range to fill. * @param max Maximum value in the range to fill. */ template< typename C, typename std::enable_if< std::is_integral<typename C::value_type>::value && !std::is_same<typename C::value_type, bool>::value && !std::is_same<typename C::value_type, char>::value && !std::is_same<typename C::value_type, int8_t>::value && !std::is_same<typename C::value_type, uint8_t>::value >::type * = nullptr > void test_vector_fill(C * container, size_t size, typename C::value_type min, typename C::value_type max) { std::default_random_engine rand_generator; std::uniform_int_distribution<typename C::value_type> randnum(min, max); if (size > 0) { (*container)[0] = min; for (size_t i = 1; i < size - 1; i++) { (*container)[i] = randnum(rand_generator); } (*container)[size - 1] = max; } } /** * Helper function to generate a test pattern for char type and derivatives. * Note: this is necessary because uniform_int_distribution is not defined for * char type. * Mininum and maximum values for the type and random values in the middle. * @param C Container (vector, array, etc) to be filled * @param size How many elements to fill in. Must size<=container_size * @param min Minimum value in the range to fill. * @param max Maximum value in the range to fill. */ template< typename C, typename std::enable_if< std::is_same<typename C::value_type, char>::value || std::is_same<typename C::value_type, int8_t>::value || std::is_same<typename C::value_type, uint8_t>::value >::type * = nullptr > void test_vector_fill(C * container, size_t size, typename C::value_type min, typename C::value_type max) { std::default_random_engine rand_generator; std::uniform_int_distribution<int> randnum(static_cast<int>(min), static_cast<int>(max)); if (size > 0) { (*container)[0] = min; for (size_t i = 1; i < size - 1; i++) { (*container)[i] = static_cast<typename C::value_type>(randnum(rand_generator)); } (*container)[size - 1] = max; } } /** * Helper function to generate a test pattern for float number types. * Mininum and maximum values for the type and random numbers in the middle. * @param C Container (vector, array, etc) to be filled * @param size How many elements to fill in. Must size<=container_size * @param min Minimum value in the range to fill. * @param max Maximum value in the range to fill. */ template< typename C, typename std::enable_if< std::is_floating_point<typename C::value_type>::value >::type * = nullptr > void test_vector_fill(C * container, size_t size, typename C::value_type min, typename C::value_type max) { std::default_random_engine rand_generator; std::uniform_real_distribution<typename C::value_type> randnum(min, max); if (size > 0) { (*container)[0] = min; for (size_t i = 1; i < size - 1; i++) { (*container)[i] = randnum(rand_generator); } (*container)[size - 1] = max; } } /** * Helper function to generate a test pattern for string types. * Mininum and maximum values for the type and random numbers in the middle. * @param C Container (vector, array, etc) to be filled * @param size How many elements to fill in. Must size<=container_size * @param min Minimum value in the range to fill. * @param max Maximum value in the range to fill. * @param minlength Minimum length of the generated strings. * @param maxlength Maximum length of the generated strings. */ template< typename C, typename std::enable_if< std::is_same<typename C::value_type, typename std::string>::value >::type * = nullptr > void test_vector_fill(C * container, size_t size, int min, int max, int minlength, const int maxlength) { std::default_random_engine rand_generator; std::uniform_int_distribution<int> randnum(min, max); std::uniform_int_distribution<int> randlen(minlength, maxlength); if (size > 0) { char * tmpstr = reinterpret_cast<char *>(malloc(maxlength)); std::snprintf(tmpstr, minlength, "%*d", minlength, min); (*container)[0] = std::string(tmpstr); for (size_t i = 1; i < size - 1; i++) { int length = randlen(rand_generator); std::snprintf(tmpstr, length, "%*d", length, randnum(rand_generator)); (*container)[i] = std::string(tmpstr); } std::snprintf(tmpstr, maxlength, "%*d", maxlength, max); (*container)[size - 1] = std::string(tmpstr); } } #endif // TEST_ARRAY_GENERATOR_HPP_ <commit_msg>[rosidl_generator_cpp] Deterministic testing (#184)<commit_after>// Copyright 2015 Open Source Robotics Foundation, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef TEST_ARRAY_GENERATOR_HPP_ #define TEST_ARRAY_GENERATOR_HPP_ #include <climits> #include <random> #include <string> #include <type_traits> /** * Helper function to generate a test pattern for boolean type. * Alternating true (even index) and false (odd index) pattern. * @param C Container (vector, array, etc) to be filled * @param size How many elements to fill in. Must size<=container_size */ template< typename C, typename std::enable_if< std::is_same<typename C::value_type, bool>::value >::type * = nullptr > void test_vector_fill(C * container, size_t size, bool val1 = true, bool val2 = false) { for (size_t i = 0; i < size; i++) { if ((i % 2) == 0) { (*container)[i] = val2; } else { (*container)[i] = val1; } } } /** * Helper function to generate a test pattern for integer number types. * The template type parameter must be an integer number type. * Mininum and maximum values for the type and distributed values in the middle. * @param C Container (vector, array, etc) to be filled * @param size How many elements to fill in. Must size<=container_size * @param min Minimum value in the range to fill. * @param max Maximum value in the range to fill. */ template< typename C, typename std::enable_if< std::is_integral<typename C::value_type>::value && !std::is_same<typename C::value_type, bool>::value >::type * = nullptr > void test_vector_fill(C * container, size_t size, typename C::value_type min, typename C::value_type max) { if (size > 0 && min != max) { typename C::value_type step = (max - min) / size; (*container)[0] = min; for (size_t i = 1; i < size - 1; i++) { (*container)[i] = min + i * step; } (*container)[size - 1] = max; } } /** * Helper function to generate a test pattern for float number types. * Mininum and maximum values for the type and distributed values in the middle. * @param C Container (vector, array, etc) to be filled * @param size How many elements to fill in. Must size<=container_size * @param min Minimum value in the range to fill. * @param max Maximum value in the range to fill. */ template< typename C, typename std::enable_if< std::is_floating_point<typename C::value_type>::value >::type * = nullptr > void test_vector_fill(C * container, size_t size, typename C::value_type min, typename C::value_type max) { if (size > 0 && min != max) { typename C::value_type step = (max - min) / size; (*container)[0] = min; for (size_t i = 1; i < size - 1; i++) { (*container)[i] = min + i * step; } (*container)[size - 1] = max; } } /** * Helper function to generate a test pattern for string types. * Mininum and maximum values for the type and distributed values in the middle. * @param C Container (vector, array, etc) to be filled * @param size How many elements to fill in. Must size<=container_size * @param min Minimum value in the range to fill. * @param max Maximum value in the range to fill. * @param minlength Minimum length of the generated strings. * @param maxlength Maximum length of the generated strings. */ template< typename C, typename std::enable_if< std::is_same<typename C::value_type, typename std::string>::value >::type * = nullptr > void test_vector_fill(C * container, size_t size, int min, int max, int minlength, const int maxlength) { if (size > 0 && min != max && minlength != maxlength) { int step = (max - min) / size; int step_length = (maxlength - minlength) / size; char * tmpstr = reinterpret_cast<char *>(malloc(maxlength)); std::snprintf(tmpstr, minlength, "%*d", minlength, min); (*container)[0] = std::string(tmpstr); for (size_t i = 1; i < size - 1; i++) { int value = min + i * step; int length = minlength + i * step_length; std::snprintf(tmpstr, length, "%*d", length, value); (*container)[i] = std::string(tmpstr); } std::snprintf(tmpstr, maxlength, "%*d", maxlength, max); (*container)[size - 1] = std::string(tmpstr); } } #endif // TEST_ARRAY_GENERATOR_HPP_ <|endoftext|>
<commit_before>#ifdef WITH_BASISU #define BASISU_NO_ITERATOR_DEBUG_LEVEL #ifdef __clang__ #pragma GCC diagnostic ignored "-Wunknown-warning-option" #endif #ifdef __GNUC__ #pragma GCC diagnostic ignored "-Wclass-memaccess" #pragma GCC diagnostic ignored "-Wunused-value" #endif #include "encoder/basisu_comp.h" #include "gltfpack.h" struct BasisSettings { int etc1s_l; int etc1s_q; int uastc_l; float uastc_q; }; static const BasisSettings kBasisSettings[10] = { {1, 1, 0, 1.5f}, {1, 6, 0, 1.f}, {1, 20, 1, 1.0f}, {1, 50, 1, 0.75f}, {1, 90, 1, 0.5f}, {1, 128, 1, 0.4f}, {1, 160, 1, 0.34f}, {1, 192, 1, 0.29f}, // default {1, 224, 2, 0.26f}, {1, 255, 2, 0.f}, }; static std::unique_ptr<basisu::job_pool> gJobPool; void encodeInit(int jobs) { using namespace basisu; basisu_encoder_init(); uint32_t num_threads = jobs == 0 ? std::thread::hardware_concurrency() : jobs; gJobPool.reset(new job_pool(num_threads)); } static bool encodeInternal(const char* input, const char* output, bool yflip, bool normal_map, bool linear, bool uastc, int uastc_l, float uastc_q, int etc1s_l, int etc1s_q, int zstd_l, int width, int height) { using namespace basisu; basis_compressor_params params; params.m_multithreading = gJobPool->get_total_threads() > 1; params.m_pJob_pool = gJobPool.get(); if (uastc) { static const uint32_t s_level_flags[TOTAL_PACK_UASTC_LEVELS] = {cPackUASTCLevelFastest, cPackUASTCLevelFaster, cPackUASTCLevelDefault, cPackUASTCLevelSlower, cPackUASTCLevelVerySlow}; params.m_uastc = true; params.m_pack_uastc_flags &= ~cPackUASTCLevelMask; params.m_pack_uastc_flags |= s_level_flags[uastc_l]; params.m_rdo_uastc = uastc_q > 0; params.m_rdo_uastc_quality_scalar = uastc_q; params.m_rdo_uastc_dict_size = 1024; } else { params.m_compression_level = etc1s_l; params.m_quality_level = etc1s_q; params.m_max_endpoint_clusters = 0; params.m_max_selector_clusters = 0; params.m_no_selector_rdo = normal_map; params.m_no_endpoint_rdo = normal_map; } params.m_perceptual = !linear; params.m_mip_gen = true; params.m_mip_srgb = !linear; params.m_resample_width = width; params.m_resample_height = height; params.m_y_flip = yflip; params.m_create_ktx2_file = true; params.m_ktx2_srgb_transfer_func = !linear; if (zstd_l) { params.m_ktx2_uastc_supercompression = basist::KTX2_SS_ZSTANDARD; params.m_ktx2_zstd_supercompression_level = zstd_l; } params.m_read_source_images = true; params.m_write_output_basis_files = true; params.m_source_filenames.resize(1); params.m_source_filenames[0] = input; params.m_out_filename = output; params.m_status_output = false; basis_compressor c; if (!c.init(params)) return false; return c.process() == basis_compressor::cECSuccess; } static const char* encodeImage(const std::string& data, const char* mime_type, std::string& result, const ImageInfo& info, const Settings& settings) { TempFile temp_input(mimeExtension(mime_type)); TempFile temp_output(".ktx2"); if (!writeFile(temp_input.path.c_str(), data)) return "error writing temporary file"; int quality = settings.texture_quality[info.kind]; bool uastc = settings.texture_mode[info.kind] == TextureMode_UASTC; const BasisSettings& bs = kBasisSettings[quality - 1]; int width = 0, height = 0; if (!getDimensions(data, mime_type, width, height)) return "error parsing image header"; adjustDimensions(width, height, settings); int zstd = uastc ? 9 : 0; if (!encodeInternal(temp_input.path.c_str(), temp_output.path.c_str(), settings.texture_flipy, info.normal_map, !info.srgb, uastc, bs.uastc_l, bs.uastc_q, bs.etc1s_l, bs.etc1s_q, zstd, width, height)) return "error encoding image"; if (!readFile(temp_output.path.c_str(), result)) return "error reading temporary file"; return nullptr; } void encodeImages(std::string* encoded, const cgltf_data* data, const std::vector<ImageInfo>& images, const char* input_path, const Settings& settings) { assert(gJobPool); for (size_t i = 0; i < data->images_count; ++i) { const cgltf_image& image = data->images[i]; ImageInfo info = images[i]; if (settings.texture_mode[info.kind] == TextureMode_Raw) continue; gJobPool->add_job([=]() { std::string img_data; std::string mime_type; std::string result; if (!readImage(image, input_path, img_data, mime_type)) encoded[i] = "error reading source file"; else if (const char* error = encodeImage(img_data, mime_type.c_str(), result, info, settings)) encoded[i] = error; else encoded[i].swap(result); }, nullptr); // explicitly pass token to make sure we're using thread-safe job_pool implementation } gJobPool->wait_for_all(); } #endif <commit_msg>gltfpack: Initialize interval_timer globals early<commit_after>#ifdef WITH_BASISU #define BASISU_NO_ITERATOR_DEBUG_LEVEL #ifdef __clang__ #pragma GCC diagnostic ignored "-Wunknown-warning-option" #endif #ifdef __GNUC__ #pragma GCC diagnostic ignored "-Wclass-memaccess" #pragma GCC diagnostic ignored "-Wunused-value" #endif #include "encoder/basisu_comp.h" #include "gltfpack.h" struct BasisSettings { int etc1s_l; int etc1s_q; int uastc_l; float uastc_q; }; static const BasisSettings kBasisSettings[10] = { {1, 1, 0, 1.5f}, {1, 6, 0, 1.f}, {1, 20, 1, 1.0f}, {1, 50, 1, 0.75f}, {1, 90, 1, 0.5f}, {1, 128, 1, 0.4f}, {1, 160, 1, 0.34f}, {1, 192, 1, 0.29f}, // default {1, 224, 2, 0.26f}, {1, 255, 2, 0.f}, }; static std::unique_ptr<basisu::job_pool> gJobPool; void encodeInit(int jobs) { using namespace basisu; basisu_encoder_init(); uint32_t num_threads = jobs == 0 ? std::thread::hardware_concurrency() : jobs; gJobPool.reset(new job_pool(num_threads)); interval_timer::init(); // make sure interval_timer globals are initialized from main thread } static bool encodeInternal(const char* input, const char* output, bool yflip, bool normal_map, bool linear, bool uastc, int uastc_l, float uastc_q, int etc1s_l, int etc1s_q, int zstd_l, int width, int height) { using namespace basisu; basis_compressor_params params; params.m_multithreading = gJobPool->get_total_threads() > 1; params.m_pJob_pool = gJobPool.get(); if (uastc) { static const uint32_t s_level_flags[TOTAL_PACK_UASTC_LEVELS] = {cPackUASTCLevelFastest, cPackUASTCLevelFaster, cPackUASTCLevelDefault, cPackUASTCLevelSlower, cPackUASTCLevelVerySlow}; params.m_uastc = true; params.m_pack_uastc_flags &= ~cPackUASTCLevelMask; params.m_pack_uastc_flags |= s_level_flags[uastc_l]; params.m_rdo_uastc = uastc_q > 0; params.m_rdo_uastc_quality_scalar = uastc_q; params.m_rdo_uastc_dict_size = 1024; } else { params.m_compression_level = etc1s_l; params.m_quality_level = etc1s_q; params.m_max_endpoint_clusters = 0; params.m_max_selector_clusters = 0; params.m_no_selector_rdo = normal_map; params.m_no_endpoint_rdo = normal_map; } params.m_perceptual = !linear; params.m_mip_gen = true; params.m_mip_srgb = !linear; params.m_resample_width = width; params.m_resample_height = height; params.m_y_flip = yflip; params.m_create_ktx2_file = true; params.m_ktx2_srgb_transfer_func = !linear; if (zstd_l) { params.m_ktx2_uastc_supercompression = basist::KTX2_SS_ZSTANDARD; params.m_ktx2_zstd_supercompression_level = zstd_l; } params.m_read_source_images = true; params.m_write_output_basis_files = true; params.m_source_filenames.resize(1); params.m_source_filenames[0] = input; params.m_out_filename = output; params.m_status_output = false; basis_compressor c; if (!c.init(params)) return false; return c.process() == basis_compressor::cECSuccess; } static const char* encodeImage(const std::string& data, const char* mime_type, std::string& result, const ImageInfo& info, const Settings& settings) { TempFile temp_input(mimeExtension(mime_type)); TempFile temp_output(".ktx2"); if (!writeFile(temp_input.path.c_str(), data)) return "error writing temporary file"; int quality = settings.texture_quality[info.kind]; bool uastc = settings.texture_mode[info.kind] == TextureMode_UASTC; const BasisSettings& bs = kBasisSettings[quality - 1]; int width = 0, height = 0; if (!getDimensions(data, mime_type, width, height)) return "error parsing image header"; adjustDimensions(width, height, settings); int zstd = uastc ? 9 : 0; if (!encodeInternal(temp_input.path.c_str(), temp_output.path.c_str(), settings.texture_flipy, info.normal_map, !info.srgb, uastc, bs.uastc_l, bs.uastc_q, bs.etc1s_l, bs.etc1s_q, zstd, width, height)) return "error encoding image"; if (!readFile(temp_output.path.c_str(), result)) return "error reading temporary file"; return nullptr; } void encodeImages(std::string* encoded, const cgltf_data* data, const std::vector<ImageInfo>& images, const char* input_path, const Settings& settings) { assert(gJobPool); for (size_t i = 0; i < data->images_count; ++i) { const cgltf_image& image = data->images[i]; ImageInfo info = images[i]; if (settings.texture_mode[info.kind] == TextureMode_Raw) continue; gJobPool->add_job([=]() { std::string img_data; std::string mime_type; std::string result; if (!readImage(image, input_path, img_data, mime_type)) encoded[i] = "error reading source file"; else if (const char* error = encodeImage(img_data, mime_type.c_str(), result, info, settings)) encoded[i] = error; else encoded[i].swap(result); }, nullptr); // explicitly pass token to make sure we're using thread-safe job_pool implementation } gJobPool->wait_for_all(); } #endif <|endoftext|>
<commit_before>#include <ros/ros.h> #include <image_transport/image_transport.h> #include <cv_bridge/cv_bridge.h> #include <sensor_msgs/image_encodings.h> #include <opencv2/imgproc.hpp> #include <opencv2/highgui.hpp> class ImageBlurer { public: ImageBlurer(); void blur_image(const sensor_msgs::ImageConstPtr& msg); private: ros::NodeHandle nh_; ros::NodeHandle pnh_; image_transport::ImageTransport it_; image_transport::ImageTransport pit_; image_transport::Subscriber image_sub_; image_transport::Publisher image_pub_; }; ImageBlurer::ImageBlurer() : nh_{}, pnh_{"~"}, it_{nh_}, pit_{pnh_}, image_sub_{it_.subscribe("src_image", 1, &ImageBlurer::blur_image, this)}, image_pub_{pit_.advertise("dest_image", 1)} { } void ImageBlurer::blur_image(const sensor_msgs::ImageConstPtr& msg) { try { cv::Mat dest_image; cv::blur(cv_bridge::CvImagePtr{cv_bridge::toCvShare(msg, sensor_msgs::image_encodings::BGR8)}->image, dest_image, cv::Size(2, 100)); image_pub_.publish(cv_bridge::CvImage{std_msgs::Header{}, "bgr8", dest_image}.toImageMsg()); } catch (cv_bridge::Exception& e) { ROS_ERROR_STREAM("cv_bridge exception: " << e.what()); } } int main(int argc, char** argv) { ros::init(argc, argv, "image_blurer"); ImageBlurer ib{}; ros::spin(); return 0; } <commit_msg>Avoid to make extra rvalue<commit_after>#include <ros/ros.h> #include <image_transport/image_transport.h> #include <cv_bridge/cv_bridge.h> #include <sensor_msgs/image_encodings.h> #include <opencv2/imgproc.hpp> #include <opencv2/highgui.hpp> class ImageBlurer { public: ImageBlurer(); void blur_image(const sensor_msgs::ImageConstPtr& msg); private: ros::NodeHandle nh_; ros::NodeHandle pnh_; image_transport::ImageTransport it_; image_transport::ImageTransport pit_; image_transport::Subscriber image_sub_; image_transport::Publisher image_pub_; }; ImageBlurer::ImageBlurer() : nh_{}, pnh_{"~"}, it_{nh_}, pit_{pnh_}, image_sub_{it_.subscribe("src_image", 1, &ImageBlurer::blur_image, this)}, image_pub_{pit_.advertise("dest_image", 1)} { } void ImageBlurer::blur_image(const sensor_msgs::ImageConstPtr& msg) { try { cv::Mat dest_image; cv::blur(cv_bridge::toCvShare(msg, sensor_msgs::image_encodings::BGR8)->image, dest_image, cv::Size(2, 100)); image_pub_.publish(cv_bridge::CvImage{std_msgs::Header{}, "bgr8", dest_image}.toImageMsg()); } catch (cv_bridge::Exception& e) { ROS_ERROR_STREAM("cv_bridge exception: " << e.what()); } } int main(int argc, char** argv) { ros::init(argc, argv, "image_blurer"); ImageBlurer ib{}; ros::spin(); return 0; } <|endoftext|>
<commit_before>#include <ros/ros.h> #include <image_transport/image_transport.h> #include <cv_bridge/cv_bridge.h> #include <sensor_msgs/image_encodings.h> #include <opencv2/imgproc.hpp> #include <opencv2/highgui.hpp> class ImageBlurer { public: ImageBlurer(); void blur_image(const sensor_msgs::ImageConstPtr& msg); private: ros::NodeHandle nh_; ros::NodeHandle pnh_; image_transport::ImageTransport it_; image_transport::ImageTransport pit_; image_transport::Subscriber image_sub_; image_transport::Publisher image_pub_; }; ImageBlurer::ImageBlurer() : nh_{}, pnh_{"~"}, it_{nh_}, pit_{pnh_}, image_sub_{it_.subscribe("src_image", 1, &ImageBlurer::blur_image, this)}, image_pub_{pit_.advertise("dest_image", 1)} { } void ImageBlurer::blur_image(const sensor_msgs::ImageConstPtr& msg) { try { cv_bridge::CvImagePtr dest_ptr{cv_bridge::toCvCopy(msg, sensor_msgs::image_encodings::BGR8)}; cv::blur(cv_bridge::CvImagePtr{cv_bridge::toCvCopy(msg, sensor_msgs::image_encodings::BGR8)}->image, dest_ptr->image, cv::Size(2, 100)); image_pub_.publish(dest_ptr->toImageMsg()); } catch (cv_bridge::Exception& e) { ROS_ERROR_STREAM("cv_bridge exception: " << e.what()); } } int main(int argc, char** argv) { ros::init(argc, argv, "image_blurer"); ImageBlurer ib{}; ros::spin(); return 0; } <commit_msg>Refactor image preparing & handling<commit_after>#include <ros/ros.h> #include <image_transport/image_transport.h> #include <cv_bridge/cv_bridge.h> #include <sensor_msgs/image_encodings.h> #include <opencv2/imgproc.hpp> #include <opencv2/highgui.hpp> class ImageBlurer { public: ImageBlurer(); void blur_image(const sensor_msgs::ImageConstPtr& msg); private: ros::NodeHandle nh_; ros::NodeHandle pnh_; image_transport::ImageTransport it_; image_transport::ImageTransport pit_; image_transport::Subscriber image_sub_; image_transport::Publisher image_pub_; }; ImageBlurer::ImageBlurer() : nh_{}, pnh_{"~"}, it_{nh_}, pit_{pnh_}, image_sub_{it_.subscribe("src_image", 1, &ImageBlurer::blur_image, this)}, image_pub_{pit_.advertise("dest_image", 1)} { } void ImageBlurer::blur_image(const sensor_msgs::ImageConstPtr& msg) { try { cv::Mat dest_image; cv::blur(cv_bridge::CvImagePtr{cv_bridge::toCvCopy(msg, sensor_msgs::image_encodings::RGB8)}->image, dest_image, cv::Size(2, 100)); image_pub_.publish(cv_bridge::CvImage{std_msgs::Header{}, "rgb8", dest_image}.toImageMsg()); } catch (cv_bridge::Exception& e) { ROS_ERROR_STREAM("cv_bridge exception: " << e.what()); } } int main(int argc, char** argv) { ros::init(argc, argv, "image_blurer"); ImageBlurer ib{}; ros::spin(); return 0; } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: animationcommandnode.cxx,v $ * * $Revision: 1.6 $ * * last change: $Author: obo $ $Date: 2006-09-17 08:33:51 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_slideshow.hxx" // must be first #include "canvas/debug.hxx" #include "canvas/verbosetrace.hxx" #include "com/sun/star/presentation/EffectCommands.hpp" #include "animationcommandnode.hxx" #include "delayevent.hxx" #include "tools.hxx" #include "nodetools.hxx" namespace presentation { namespace internal { void AnimationCommandNode::dispose() { mxCommandNode.clear(); BaseNode::dispose(); } void AnimationCommandNode::activate_() { namespace EffectCommands = com::sun::star::presentation::EffectCommands; switch( mxCommandNode->getCommand() ) { // the command is user defined case EffectCommands::CUSTOM: break; // the command is an ole verb. case EffectCommands::VERB: break; // the command starts playing on a media object case EffectCommands::PLAY: break; // the command toggles the pause status on a media object case EffectCommands::TOGGLEPAUSE: break; // the command stops the animation on a media object case EffectCommands::STOP: break; // the command stops all currently running sound effects case EffectCommands::STOPAUDIO: getContext().mrEventMultiplexer.notifyCommandStopAudio( getSelf() ); break; } // deactivate ASAP: scheduleDeactivationEvent( makeEvent( boost::bind( &AnimationNode::deactivate, getSelf() ) ) ); } bool AnimationCommandNode::hasPendingAnimation() const { return false; } } // namespace internal } // namespace presentation <commit_msg>INTEGRATION: CWS presfixes09 (1.4.18); FILE MERGED 2006/10/18 19:54:29 thb 1.4.18.5: RESYNC: (1.5-1.6); FILE MERGED 2006/09/15 22:13:51 thb 1.4.18.4: RESYNC: (1.4-1.5); FILE MERGED 2006/04/03 16:19:00 thb 1.4.18.3: #i37778# Now passing down ComponentContext to all interested parties; building a second, all-exports version of the slideshow component (to facilitate unit testing also for internal classes) - this made necessary renaming ImportFailedException to ShapeLoadFailedException (because of silly i63703); applied relevant parts of #i63770# (const-correctness); reworked view handling in such a way that views are now kept in one central repository (and are not duplicated across all interested objects); moved code from namespace presentation to namespace slideshow 2006/03/24 18:23:16 thb 1.4.18.2: #i37778# Moved whole slideshow engine from namespace presentation (which conflicts with one of the UNO subnamespaces) to slideshow 2006/03/15 15:22:19 thb 1.4.18.1: #i49357# Removed external include guards from all non-export headers (and from the cxx files, anyway)<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: animationcommandnode.cxx,v $ * * $Revision: 1.7 $ * * last change: $Author: kz $ $Date: 2006-12-13 15:29:27 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_slideshow.hxx" // must be first #include "canvas/debug.hxx" #include "canvas/verbosetrace.hxx" #include "com/sun/star/presentation/EffectCommands.hpp" #include "animationcommandnode.hxx" #include "delayevent.hxx" #include "tools.hxx" #include "nodetools.hxx" namespace slideshow { namespace internal { void AnimationCommandNode::dispose() { mxCommandNode.clear(); BaseNode::dispose(); } void AnimationCommandNode::activate_() { namespace EffectCommands = com::sun::star::presentation::EffectCommands; switch( mxCommandNode->getCommand() ) { // the command is user defined case EffectCommands::CUSTOM: break; // the command is an ole verb. case EffectCommands::VERB: break; // the command starts playing on a media object case EffectCommands::PLAY: break; // the command toggles the pause status on a media object case EffectCommands::TOGGLEPAUSE: break; // the command stops the animation on a media object case EffectCommands::STOP: break; // the command stops all currently running sound effects case EffectCommands::STOPAUDIO: getContext().mrEventMultiplexer.notifyCommandStopAudio( getSelf() ); break; } // deactivate ASAP: scheduleDeactivationEvent( makeEvent( boost::bind( &AnimationNode::deactivate, getSelf() ) ) ); } bool AnimationCommandNode::hasPendingAnimation() const { return false; } } // namespace internal } // namespace slideshow <|endoftext|>
<commit_before>/** @file * * The implementation of the MultiplyElement class. * * @author Nicolas Bock <nicolas.bock@freeon.org> * @author Matt Challacombe <matt.challacombe@freeon.org> */ #include "multiplyelement.h" #include "messages.h" #include "logger.h" #include "index.h" #include <string.h> /** The constructor. * * @param ANode The node of matrix A. * @param BNode The node of matrix B. * @param CNode The node of matrix C. */ MultiplyElement::MultiplyElement (int blocksize, int tier, int depth, CProxy_Node A, CProxy_Node B, CProxy_Node C) { DEBUG("tier %d ME(%d,%d,%d) constructor\n", tier, thisIndex.x, thisIndex.y, thisIndex.z); this->blocksize = blocksize; this->tier = tier; this->depth = depth; this->A = A; this->B = B; this->C = C; if(tier < depth) { for(int i = 0; i < 2; i++) { for(int j = 0; j < 2; j++) { for(int k = 0; k < 2; k++) { nextConvolutionExists[i][j][k] = true; } } } } CResult = NULL; numberCalls = 0; wasMigrated = false; } /** The migration constructor. * * @param msg The migration message. */ MultiplyElement::MultiplyElement (CkMigrateMessage *msg) { INFO("ME(%d,%d,%d) migration constructor\n", thisIndex.x, thisIndex.y, thisIndex.z); /* Reset the migration flag on the new PE. */ wasMigrated = false; } /** The destructor. */ MultiplyElement::~MultiplyElement () { DEBUG("tier %d ME(%d,%d,%d) destructor\n", tier, thisIndex.x, thisIndex.y, thisIndex.z); delete[] CResult; if(!wasMigrated && (tier < depth)) { DEBUG("tier %d ME(%d,%d,%d) destructor, pruning lower tier elements\n", tier, thisIndex.x, thisIndex.y, thisIndex.z); /* Recursively prune convolution elements. */ for(int i = 0; i < 2; i++) { for(int j = 0; j < 2; j++) { for(int k = 0; k < 2; k++) { if(nextConvolutionExists[i][j][k]) { DEBUG("tier %d ME(%d,%d,%d) destructor, pruning tier %d ME(%d,%d,%d)\n", tier, thisIndex.x, thisIndex.y, thisIndex.z, tier+1, (thisIndex.x << 1)+i, (thisIndex.y << 1)+j, (thisIndex.z << 1)+k); nextConvolution((thisIndex.x << 1)+i, (thisIndex.y << 1)+j, (thisIndex.z << 1)+k).ckDestroy(); DEBUG("tier %d ME(%d,%d,%d) destructor, pruning tier %d ME(%d,%d,%d), here 2\n", tier, thisIndex.x, thisIndex.y, thisIndex.z, tier+1, (thisIndex.x << 1)+i, (thisIndex.y << 1)+j, (thisIndex.z << 1)+k); nextConvolutionExists[i][j][k] = false; DEBUG("tier %d ME(%d,%d,%d) destructor, pruning tier %d ME(%d,%d,%d), here 3\n", tier, thisIndex.x, thisIndex.y, thisIndex.z, tier+1, (thisIndex.x << 1)+i, (thisIndex.y << 1)+j, (thisIndex.z << 1)+k); } } } } } DEBUG("tier %d ME(%d,%d,%d) destructor done\n", tier, thisIndex.x, thisIndex.y, thisIndex.z); } /** The the next convolution array. * * @param nextConvolution The next convolution array. */ void MultiplyElement::setNextTier (CProxy_MultiplyElement nextConvolution, CProxy_Node nextA, CProxy_Node nextB, CkCallback &cb) { DEBUG("tier %d ME(%d,%d,%d) setting nextTier\n", tier, thisIndex.x, thisIndex.y, thisIndex.z); this->nextConvolution = nextConvolution; this->nextA = nextA; this->nextB = nextB; contribute(cb); } /** The PUP method. * * @param p The object. */ void MultiplyElement::pup (PUP::er &p) { CBase_MultiplyElement::pup(p); p|index; p|blocksize; p|numberCalls; p|depth; p|tier; p|A; p|B; p|C; for(int i = 0; i < 2; i++) { for(int j = 0; j < 2; j++) { for(int k = 0; k < 2; k++) { p|nextConvolutionExists[i][j][k]; } } } if(tier < depth) { p|nextConvolution; p|nextA; p|nextB; } int numberElements = (CResult == NULL ? 0 : blocksize*blocksize); p|numberElements; if(p.isUnpacking()) { INFO("tier %d ME(%d,%d,%d) pup: unpacking %d elements\n", tier, thisIndex.x, thisIndex.y, thisIndex.z, numberElements); } else { if(p.isSizing()) { DEBUG("tier %d ME(%d,%d,%d) pup: sizing %d elements\n", tier, thisIndex.x, thisIndex.y, thisIndex.z, numberElements); } else { INFO("tier %d ME(%d,%d,%d) pup: packing %d elements\n", tier, thisIndex.x, thisIndex.y, thisIndex.z, numberElements); /* Set the wasMigrated flag to indicate that this instance is going to * get destroyed because of a migration, and not because of pruning. */ wasMigrated = true; //print("packing"); } } if(numberElements > 0) { if(p.isUnpacking()) { CResult = new double[numberElements]; } PUParray(p, CResult, numberElements); //print("unpacking"); } else { if(p.isUnpacking()) { CResult = NULL; } } } /** Multiply nodes. * * @param cb The callback. */ void MultiplyElement::multiply (double tolerance, CkCallback &cb) { DEBUG("tier %d ME(%d,%d,%d) multiply\n", tier, thisIndex.x, thisIndex.y, thisIndex.z); if(numberCalls > 0) { ABORT("tier %d ME(%d,%d,%d) this MultiplyElement has been called before\n", tier, thisIndex.x, thisIndex.y, thisIndex.z); } numberCalls++; if(tier == depth) { NodeInfoMsg *AInfo = A(thisIndex.x, thisIndex.z).info(); NodeInfoMsg *BInfo = B(thisIndex.z, thisIndex.y).info(); if(AInfo->norm*BInfo->norm > tolerance) { if(CResult != NULL) { ABORT("tier %d ME(%d,%d,%d) CResult is not NULL\n", tier, thisIndex.x, thisIndex.y, thisIndex.z); } DEBUG("tier %d ME(%d,%d,%d) multiplying blocks\n", tier, thisIndex.x, thisIndex.y, thisIndex.z); CResult = new double[blocksize*blocksize]; memset(CResult, 0, sizeof(double)*blocksize*blocksize); NodeBlockMsg *ABlock = A(thisIndex.x, thisIndex.z).getBlock(); NodeBlockMsg *BBlock = B(thisIndex.z, thisIndex.y).getBlock(); for(int i = 0; i < blocksize; i++) { for(int j = 0; j < blocksize; j++) { for(int k = 0; k < blocksize; k++) { CResult[BLOCK_INDEX(i, j, 0, 0, blocksize)] += ABlock->block[BLOCK_INDEX(i, k, 0, 0, blocksize)] *BBlock->block[BLOCK_INDEX(k, j, 0, 0, blocksize)]; } } } INFO("tier %d ME(%d,%d,%d) sleeping\n", tier, thisIndex.x, thisIndex.y, thisIndex.z); sleep(30); } else { ABORT("tier %d ME(%d,%d,%d) skipping block product\n", tier, thisIndex.x, thisIndex.y, thisIndex.z); } delete AInfo; delete BInfo; } else { /* Get information on A and B matrices. */ NodeInfoMsg *AInfo[2][2]; NodeInfoMsg *BInfo[2][2]; for(int i = 0; i < 2; i++) { for(int j = 0; j < 2; j++) { AInfo[i][j] = A((thisIndex.x << 1)+i, (thisIndex.z << 1)+j).info(); BInfo[i][j] = B((thisIndex.z << 1)+i, (thisIndex.y << 1)+j).info(); } } /* Check what products are necessary one tier down. */ for(int i = 0; i < 2; i++) { for(int j = 0; j < 2; j++) { for(int k = 0; k < 2; k++) { if(AInfo[i][k]->norm*BInfo[k][j]->norm > tolerance) { if(!nextConvolutionExists[i][j][k]) { DEBUG("tier %d ME(%d,%d,%d) adding product ME(%d,%d,%d): C(%d,%d) <- A(%d,%d)*B(%d,%d)\n", tier, thisIndex.x, thisIndex.y, thisIndex.z, (thisIndex.x << 1)+i, (thisIndex.y << 1)+j, (thisIndex.z << 1)+k, (thisIndex.x << 1)+i, (thisIndex.y << 1)+j, (thisIndex.x << 1)+i, (thisIndex.z << 1)+k, (thisIndex.z << 1)+k, (thisIndex.y << 1)+j); nextConvolution((thisIndex.x << 1)+i, (thisIndex.y << 1)+j, (thisIndex.z << 1)+k).insert(blocksize, tier+1, depth, A, B, C); nextConvolutionExists[i][j][k] = true; } else { DEBUG("tier %d ME(%d,%d,%d) keeping product ME(%d,%d,%d): C(%d,%d) <- A(%d,%d)*B(%d,%d)\n", tier, thisIndex.x, thisIndex.y, thisIndex.z, (thisIndex.x << 1)+i, (thisIndex.y << 1)+j, (thisIndex.z << 1)+k, (thisIndex.x << 1)+i, (thisIndex.y << 1)+j, (thisIndex.x << 1)+i, (thisIndex.z << 1)+k, (thisIndex.z << 1)+k, (thisIndex.y << 1)+j); } } else { if(nextConvolutionExists[i][j][k]) { DEBUG("tier %d ME(%d,%d,%d) dropping product ME(%d,%d,%d): C(%d,%d) <- A(%d,%d)*B(%d,%d)\n", tier, thisIndex.x, thisIndex.y, thisIndex.z, (thisIndex.x << 1)+i, (thisIndex.y << 1)+j, (thisIndex.z << 1)+k, (thisIndex.x << 1)+i, (thisIndex.y << 1)+j, (thisIndex.x << 1)+i, (thisIndex.z << 1)+k, (thisIndex.z << 1)+k, (thisIndex.y << 1)+j); nextConvolutionExists[i][j][k] = false; nextConvolution((thisIndex.x << 1)+i, (thisIndex.y << 1)+j, (thisIndex.z << 1)+k).ckDestroy(); } else { DEBUG("tier %d ME(%d,%d,%d) product already does not exist ME(%d,%d,%d): C(%d,%d) <- A(%d,%d)*B(%d,%d)\n", tier, thisIndex.x, thisIndex.y, thisIndex.z, (thisIndex.x << 1)+i, (thisIndex.y << 1)+j, (thisIndex.z << 1)+k, (thisIndex.x << 1)+i, (thisIndex.y << 1)+j, (thisIndex.x << 1)+i, (thisIndex.z << 1)+k, (thisIndex.z << 1)+k, (thisIndex.y << 1)+j); } } } } } for(int i = 0; i < 2; i++) { for(int j = 0; j < 2; j++) { delete AInfo[i][j]; delete BInfo[i][j]; } } } DEBUG("tier %d ME(%d,%d,%d) contribute\n", tier, thisIndex.x, thisIndex.y, thisIndex.z); contribute(cb); #ifdef FORCED_MIGRATION if(CkNumPes() > 1) { INFO("tier %d ME(%d,%d,%d) requesting migration to PE %d\n", tier, thisIndex.x, thisIndex.y, thisIndex.z, (CkMyPe()+1)%CkNumPes()); migrateMe((CkMyPe()+1)%CkNumPes()); } #endif } /** Push the C submatrices back into the C Matrix. * * @param cb The callback. */ void MultiplyElement::storeBack (CkCallback &cb) { #ifdef DEBUG_OUTPUT DEBUG("tier %d ME(%d,%d,%d) storing back\n", tier, thisIndex.x, thisIndex.y, thisIndex.z); printDense(blocksize, CResult); #endif C(thisIndex.x, thisIndex.y).add(blocksize, CResult); contribute(cb); } /** Print a MultiplyElement. */ void MultiplyElement::print (std::string tag) { INFO("tier %d ME(%d,%d,%d) [%s] CResult = %p\n", tier, thisIndex.x, thisIndex.y, thisIndex.z, tag.c_str(), CResult); } #include "multiplyelement.def.h" <commit_msg>Another debug print statement.<commit_after>/** @file * * The implementation of the MultiplyElement class. * * @author Nicolas Bock <nicolas.bock@freeon.org> * @author Matt Challacombe <matt.challacombe@freeon.org> */ #include "multiplyelement.h" #include "messages.h" #include "logger.h" #include "index.h" #include <string.h> /** The constructor. * * @param ANode The node of matrix A. * @param BNode The node of matrix B. * @param CNode The node of matrix C. */ MultiplyElement::MultiplyElement (int blocksize, int tier, int depth, CProxy_Node A, CProxy_Node B, CProxy_Node C) { DEBUG("tier %d ME(%d,%d,%d) constructor\n", tier, thisIndex.x, thisIndex.y, thisIndex.z); this->blocksize = blocksize; this->tier = tier; this->depth = depth; this->A = A; this->B = B; this->C = C; if(tier < depth) { for(int i = 0; i < 2; i++) { for(int j = 0; j < 2; j++) { for(int k = 0; k < 2; k++) { nextConvolutionExists[i][j][k] = true; } } } } CResult = NULL; numberCalls = 0; wasMigrated = false; } /** The migration constructor. * * @param msg The migration message. */ MultiplyElement::MultiplyElement (CkMigrateMessage *msg) { INFO("ME(%d,%d,%d) migration constructor\n", thisIndex.x, thisIndex.y, thisIndex.z); /* Reset the migration flag on the new PE. */ wasMigrated = false; } /** The destructor. */ MultiplyElement::~MultiplyElement () { DEBUG("tier %d ME(%d,%d,%d) destructor\n", tier, thisIndex.x, thisIndex.y, thisIndex.z); delete[] CResult; if(!wasMigrated && (tier < depth)) { DEBUG("tier %d ME(%d,%d,%d) destructor, pruning lower tier elements\n", tier, thisIndex.x, thisIndex.y, thisIndex.z); /* Recursively prune convolution elements. */ for(int i = 0; i < 2; i++) { for(int j = 0; j < 2; j++) { for(int k = 0; k < 2; k++) { if(nextConvolutionExists[i][j][k]) { DEBUG("tier %d ME(%d,%d,%d) destructor, pruning tier %d ME(%d,%d,%d)\n", tier, thisIndex.x, thisIndex.y, thisIndex.z, tier+1, (thisIndex.x << 1)+i, (thisIndex.y << 1)+j, (thisIndex.z << 1)+k); nextConvolution((thisIndex.x << 1)+i, (thisIndex.y << 1)+j, (thisIndex.z << 1)+k).ckDestroy(); DEBUG("tier %d ME(%d,%d,%d) destructor, pruning tier %d ME(%d,%d,%d), here 2\n", tier, thisIndex.x, thisIndex.y, thisIndex.z, tier+1, (thisIndex.x << 1)+i, (thisIndex.y << 1)+j, (thisIndex.z << 1)+k); nextConvolutionExists[i][j][k] = false; DEBUG("tier %d ME(%d,%d,%d) destructor, pruning tier %d ME(%d,%d,%d), here 3\n", tier, thisIndex.x, thisIndex.y, thisIndex.z, tier+1, (thisIndex.x << 1)+i, (thisIndex.y << 1)+j, (thisIndex.z << 1)+k); } } } } } DEBUG("tier %d ME(%d,%d,%d) destructor done\n", tier, thisIndex.x, thisIndex.y, thisIndex.z); } /** The the next convolution array. * * @param nextConvolution The next convolution array. */ void MultiplyElement::setNextTier (CProxy_MultiplyElement nextConvolution, CProxy_Node nextA, CProxy_Node nextB, CkCallback &cb) { DEBUG("tier %d ME(%d,%d,%d) setting nextTier\n", tier, thisIndex.x, thisIndex.y, thisIndex.z); this->nextConvolution = nextConvolution; this->nextA = nextA; this->nextB = nextB; contribute(cb); } /** The PUP method. * * @param p The object. */ void MultiplyElement::pup (PUP::er &p) { CBase_MultiplyElement::pup(p); p|index; p|blocksize; p|numberCalls; p|depth; p|tier; p|A; p|B; p|C; for(int i = 0; i < 2; i++) { for(int j = 0; j < 2; j++) { for(int k = 0; k < 2; k++) { p|nextConvolutionExists[i][j][k]; } } } if(tier < depth) { p|nextConvolution; p|nextA; p|nextB; } int numberElements = (CResult == NULL ? 0 : blocksize*blocksize); p|numberElements; if(p.isUnpacking()) { INFO("tier %d ME(%d,%d,%d) pup: unpacking %d elements\n", tier, thisIndex.x, thisIndex.y, thisIndex.z, numberElements); } else { if(p.isSizing()) { DEBUG("tier %d ME(%d,%d,%d) pup: sizing %d elements\n", tier, thisIndex.x, thisIndex.y, thisIndex.z, numberElements); } else { INFO("tier %d ME(%d,%d,%d) pup: packing %d elements\n", tier, thisIndex.x, thisIndex.y, thisIndex.z, numberElements); /* Set the wasMigrated flag to indicate that this instance is going to * get destroyed because of a migration, and not because of pruning. */ wasMigrated = true; //print("packing"); } } if(numberElements > 0) { if(p.isUnpacking()) { CResult = new double[numberElements]; } PUParray(p, CResult, numberElements); //print("unpacking"); } else { if(p.isUnpacking()) { CResult = NULL; } } INFO("tier %d ME(%d,%d,%d) pup: done\n", tier, thisIndex.x, thisIndex.y, thisIndex.z); } /** Multiply nodes. * * @param cb The callback. */ void MultiplyElement::multiply (double tolerance, CkCallback &cb) { DEBUG("tier %d ME(%d,%d,%d) multiply\n", tier, thisIndex.x, thisIndex.y, thisIndex.z); if(numberCalls > 0) { ABORT("tier %d ME(%d,%d,%d) this MultiplyElement has been called before\n", tier, thisIndex.x, thisIndex.y, thisIndex.z); } numberCalls++; if(tier == depth) { NodeInfoMsg *AInfo = A(thisIndex.x, thisIndex.z).info(); NodeInfoMsg *BInfo = B(thisIndex.z, thisIndex.y).info(); if(AInfo->norm*BInfo->norm > tolerance) { if(CResult != NULL) { ABORT("tier %d ME(%d,%d,%d) CResult is not NULL\n", tier, thisIndex.x, thisIndex.y, thisIndex.z); } DEBUG("tier %d ME(%d,%d,%d) multiplying blocks\n", tier, thisIndex.x, thisIndex.y, thisIndex.z); CResult = new double[blocksize*blocksize]; memset(CResult, 0, sizeof(double)*blocksize*blocksize); NodeBlockMsg *ABlock = A(thisIndex.x, thisIndex.z).getBlock(); NodeBlockMsg *BBlock = B(thisIndex.z, thisIndex.y).getBlock(); for(int i = 0; i < blocksize; i++) { for(int j = 0; j < blocksize; j++) { for(int k = 0; k < blocksize; k++) { CResult[BLOCK_INDEX(i, j, 0, 0, blocksize)] += ABlock->block[BLOCK_INDEX(i, k, 0, 0, blocksize)] *BBlock->block[BLOCK_INDEX(k, j, 0, 0, blocksize)]; } } } INFO("tier %d ME(%d,%d,%d) sleeping\n", tier, thisIndex.x, thisIndex.y, thisIndex.z); sleep(30); } else { ABORT("tier %d ME(%d,%d,%d) skipping block product\n", tier, thisIndex.x, thisIndex.y, thisIndex.z); } delete AInfo; delete BInfo; } else { /* Get information on A and B matrices. */ NodeInfoMsg *AInfo[2][2]; NodeInfoMsg *BInfo[2][2]; for(int i = 0; i < 2; i++) { for(int j = 0; j < 2; j++) { AInfo[i][j] = A((thisIndex.x << 1)+i, (thisIndex.z << 1)+j).info(); BInfo[i][j] = B((thisIndex.z << 1)+i, (thisIndex.y << 1)+j).info(); } } /* Check what products are necessary one tier down. */ for(int i = 0; i < 2; i++) { for(int j = 0; j < 2; j++) { for(int k = 0; k < 2; k++) { if(AInfo[i][k]->norm*BInfo[k][j]->norm > tolerance) { if(!nextConvolutionExists[i][j][k]) { DEBUG("tier %d ME(%d,%d,%d) adding product ME(%d,%d,%d): C(%d,%d) <- A(%d,%d)*B(%d,%d)\n", tier, thisIndex.x, thisIndex.y, thisIndex.z, (thisIndex.x << 1)+i, (thisIndex.y << 1)+j, (thisIndex.z << 1)+k, (thisIndex.x << 1)+i, (thisIndex.y << 1)+j, (thisIndex.x << 1)+i, (thisIndex.z << 1)+k, (thisIndex.z << 1)+k, (thisIndex.y << 1)+j); nextConvolution((thisIndex.x << 1)+i, (thisIndex.y << 1)+j, (thisIndex.z << 1)+k).insert(blocksize, tier+1, depth, A, B, C); nextConvolutionExists[i][j][k] = true; } else { DEBUG("tier %d ME(%d,%d,%d) keeping product ME(%d,%d,%d): C(%d,%d) <- A(%d,%d)*B(%d,%d)\n", tier, thisIndex.x, thisIndex.y, thisIndex.z, (thisIndex.x << 1)+i, (thisIndex.y << 1)+j, (thisIndex.z << 1)+k, (thisIndex.x << 1)+i, (thisIndex.y << 1)+j, (thisIndex.x << 1)+i, (thisIndex.z << 1)+k, (thisIndex.z << 1)+k, (thisIndex.y << 1)+j); } } else { if(nextConvolutionExists[i][j][k]) { DEBUG("tier %d ME(%d,%d,%d) dropping product ME(%d,%d,%d): C(%d,%d) <- A(%d,%d)*B(%d,%d)\n", tier, thisIndex.x, thisIndex.y, thisIndex.z, (thisIndex.x << 1)+i, (thisIndex.y << 1)+j, (thisIndex.z << 1)+k, (thisIndex.x << 1)+i, (thisIndex.y << 1)+j, (thisIndex.x << 1)+i, (thisIndex.z << 1)+k, (thisIndex.z << 1)+k, (thisIndex.y << 1)+j); nextConvolutionExists[i][j][k] = false; nextConvolution((thisIndex.x << 1)+i, (thisIndex.y << 1)+j, (thisIndex.z << 1)+k).ckDestroy(); } else { DEBUG("tier %d ME(%d,%d,%d) product already does not exist ME(%d,%d,%d): C(%d,%d) <- A(%d,%d)*B(%d,%d)\n", tier, thisIndex.x, thisIndex.y, thisIndex.z, (thisIndex.x << 1)+i, (thisIndex.y << 1)+j, (thisIndex.z << 1)+k, (thisIndex.x << 1)+i, (thisIndex.y << 1)+j, (thisIndex.x << 1)+i, (thisIndex.z << 1)+k, (thisIndex.z << 1)+k, (thisIndex.y << 1)+j); } } } } } for(int i = 0; i < 2; i++) { for(int j = 0; j < 2; j++) { delete AInfo[i][j]; delete BInfo[i][j]; } } } DEBUG("tier %d ME(%d,%d,%d) contribute\n", tier, thisIndex.x, thisIndex.y, thisIndex.z); contribute(cb); #ifdef FORCED_MIGRATION if(CkNumPes() > 1) { INFO("tier %d ME(%d,%d,%d) requesting migration to PE %d\n", tier, thisIndex.x, thisIndex.y, thisIndex.z, (CkMyPe()+1)%CkNumPes()); migrateMe((CkMyPe()+1)%CkNumPes()); } #endif } /** Push the C submatrices back into the C Matrix. * * @param cb The callback. */ void MultiplyElement::storeBack (CkCallback &cb) { #ifdef DEBUG_OUTPUT DEBUG("tier %d ME(%d,%d,%d) storing back\n", tier, thisIndex.x, thisIndex.y, thisIndex.z); printDense(blocksize, CResult); #endif C(thisIndex.x, thisIndex.y).add(blocksize, CResult); contribute(cb); } /** Print a MultiplyElement. */ void MultiplyElement::print (std::string tag) { INFO("tier %d ME(%d,%d,%d) [%s] CResult = %p\n", tier, thisIndex.x, thisIndex.y, thisIndex.z, tag.c_str(), CResult); } #include "multiplyelement.def.h" <|endoftext|>
<commit_before>#include "testApp.h" #include "ofxSimpleGuiToo.h" bool recording = false; //-------------------------------------------------------------- void testApp::setup(){ kinect.setup(); kinect.setupGui(); gui.loadFromXML(); gui.setAutoSave(true); gui.setAlignRight(true); ofSetFrameRate(30); ofSetVerticalSync(true); ofEnableAlphaBlending(); blobTracker.addListener(&blobEvents); } //-------------------------------------------------------------- void testApp::update(){ bool newFrame = kinect.update(); if(newFrame) { int minBlobSize = 40; int maxBlobSize = kinect.getHeight(); contours.findContours(kinect.getOutline(), minBlobSize*minBlobSize, maxBlobSize*maxBlobSize, 20, false, true); doPersonTracking(); } ofSetWindowTitle(ofToString(ofGetFrameRate(), 1)); } void testApp::doPersonTracking() { // people.clear(); // run the blob tracker vector<ofVec3f> blobs; ofVec2f dims(kinect.getWidth(), kinect.getHeight()); // use the z coordinate. for(int i = 0; i < contours.blobs.size(); i++) { ofVec3f b = ofVec3f(contours.blobs[i].centroid.x/(float)kinect.getWidth(), contours.blobs[i].centroid.y/(float)kinect.getHeight(), i); blobs.push_back(b); } blobTracker.track(blobs); ofxBlobEvent e; while(blobEvents.getNextEvent(e)) { if(e.eventType==ofxBlobTracker_entered) { people[e.blobId] = BoundBlob(); people[e.blobId].init(contours.blobs[(int)e.pos.z]); people[e.blobId].setDepth(kinect.getDepth(contours.blobs[(int)e.pos.z])); if(recording) { ofVec3f bounds(640,480, 255); ofVec3f f = people[e.blobId].left/bounds; anim.addFrame("hand_left", (const float*)&f.x); f = people[e.blobId].right/bounds; anim.addFrame("hand_right", (const float*)&f.x); f = people[e.blobId].top/bounds; anim.addFrame("top", (const float*)&f.x); f = people[e.blobId].bottom/bounds; anim.addFrame("bottom", (const float*)&f.x); } } else if(e.eventType==ofxBlobTracker_moved) { people[e.blobId].update(contours.blobs[(int)e.pos.z]); if(recording) { ofVec3f bounds(640,480, 255); ofVec3f f = people[e.blobId].left/bounds; anim.addFrame("hand_left", (const float*)&f.x); f = people[e.blobId].right/bounds; anim.addFrame("hand_right", (const float*)&f.x); f = people[e.blobId].top/bounds; anim.addFrame("top", (const float*)&f.x); f = people[e.blobId].bottom/bounds; anim.addFrame("bottom", (const float*)&f.x); } } else if(e.eventType==ofxBlobTracker_exited) { people.erase(e.blobId); } } /*if(contours.blobs.size()==people.size()) { // match the nearest for(int i = 0; i < contours.blobs.size(); i++) { people.push_back(BoundBlob()); people.back().init(contours.blobs[i]); } } else if() { }*/ } //-------------------------------------------------------------- void testApp::draw(){ kinect.drawDebug(); contours.draw(); map<int,BoundBlob>::iterator it; for(it = people.begin(); it != people.end(); it++) { (*it).second.draw(); ofDrawBitmapString(ofToString((*it).first), (*it).second.centroid); } gui.draw(); } //-------------------------------------------------------------- void testApp::keyPressed(int key){ switch(key) { case ' ': gui.toggleDraw(); break; case 'f': ofToggleFullscreen(); break; case 'b': kinect.learnBackground = true; break; case 'r': recording ^= true; if(!recording) { // just finished recording anim.save(ofToDataPath(ofGetTimestampString()+".txt")); anim.animations.clear(); } break; } } //-------------------------------------------------------------- void testApp::keyReleased(int key){ } //-------------------------------------------------------------- void testApp::mouseMoved(int x, int y ){ } //-------------------------------------------------------------- void testApp::mouseDragged(int x, int y, int button){ } //-------------------------------------------------------------- void testApp::mousePressed(int x, int y, int button){ } //-------------------------------------------------------------- void testApp::mouseReleased(int x, int y, int button){ } //-------------------------------------------------------------- void testApp::windowResized(int w, int h){ } //-------------------------------------------------------------- void testApp::gotMessage(ofMessage msg){ } //-------------------------------------------------------------- void testApp::dragEvent(ofDragInfo dragInfo){ }<commit_msg>Made kinect recorder output centroid<commit_after>#include "testApp.h" #include "ofxSimpleGuiToo.h" bool recording = false; //-------------------------------------------------------------- void testApp::setup(){ kinect.setup(); kinect.setupGui(); gui.loadFromXML(); gui.setAutoSave(true); gui.setAlignRight(true); ofSetFrameRate(30); ofSetVerticalSync(true); ofEnableAlphaBlending(); blobTracker.addListener(&blobEvents); } //-------------------------------------------------------------- void testApp::update(){ bool newFrame = kinect.update(); if(newFrame) { int minBlobSize = 40; int maxBlobSize = kinect.getHeight(); contours.findContours(kinect.getOutline(), minBlobSize*minBlobSize, maxBlobSize*maxBlobSize, 20, false, true); doPersonTracking(); } ofSetWindowTitle(ofToString(ofGetFrameRate(), 1)); } void testApp::doPersonTracking() { // people.clear(); // run the blob tracker vector<ofVec3f> blobs; ofVec2f dims(kinect.getWidth(), kinect.getHeight()); // use the z coordinate. for(int i = 0; i < contours.blobs.size(); i++) { ofVec3f b = ofVec3f(contours.blobs[i].centroid.x/(float)kinect.getWidth(), contours.blobs[i].centroid.y/(float)kinect.getHeight(), i); blobs.push_back(b); } blobTracker.track(blobs); ofxBlobEvent e; while(blobEvents.getNextEvent(e)) { if(e.eventType==ofxBlobTracker_entered) { people[e.blobId] = BoundBlob(); people[e.blobId].init(contours.blobs[(int)e.pos.z]); people[e.blobId].setDepth(kinect.getDepth(contours.blobs[(int)e.pos.z])); if(recording) { ofVec3f bounds(640,480, 255); ofVec3f f = people[e.blobId].left/bounds; anim.addFrame("hand_left", (const float*)&f.x); f = people[e.blobId].right/bounds; anim.addFrame("hand_right", (const float*)&f.x); f = people[e.blobId].top/bounds; anim.addFrame("top", (const float*)&f.x); f = people[e.blobId].bottom/bounds; anim.addFrame("bottom", (const float*)&f.x); f = people[e.blobId].centroid/bounds; anim.addFrame("centroid", (const float*)&f.x); } } else if(e.eventType==ofxBlobTracker_moved) { people[e.blobId].update(contours.blobs[(int)e.pos.z]); if(recording) { ofVec3f bounds(640,480, 255); ofVec3f f = people[e.blobId].left/bounds; anim.addFrame("hand_left", (const float*)&f.x); f = people[e.blobId].right/bounds; anim.addFrame("hand_right", (const float*)&f.x); f = people[e.blobId].top/bounds; anim.addFrame("top", (const float*)&f.x); f = people[e.blobId].bottom/bounds; anim.addFrame("bottom", (const float*)&f.x); f = people[e.blobId].centroid/bounds; anim.addFrame("centroid", (const float*)&f.x); } } else if(e.eventType==ofxBlobTracker_exited) { people.erase(e.blobId); } } /*if(contours.blobs.size()==people.size()) { // match the nearest for(int i = 0; i < contours.blobs.size(); i++) { people.push_back(BoundBlob()); people.back().init(contours.blobs[i]); } } else if() { }*/ } //-------------------------------------------------------------- void testApp::draw(){ kinect.drawDebug(); contours.draw(); map<int,BoundBlob>::iterator it; for(it = people.begin(); it != people.end(); it++) { (*it).second.draw(); ofDrawBitmapString(ofToString((*it).first), (*it).second.centroid); } gui.draw(); } //-------------------------------------------------------------- void testApp::keyPressed(int key){ switch(key) { case ' ': gui.toggleDraw(); break; case 'f': ofToggleFullscreen(); break; case 'b': kinect.learnBackground = true; break; case 'r': recording ^= true; if(!recording) { // just finished recording anim.save(ofToDataPath(ofGetTimestampString()+".txt")); anim.animations.clear(); } break; } } //-------------------------------------------------------------- void testApp::keyReleased(int key){ } //-------------------------------------------------------------- void testApp::mouseMoved(int x, int y ){ } //-------------------------------------------------------------- void testApp::mouseDragged(int x, int y, int button){ } //-------------------------------------------------------------- void testApp::mousePressed(int x, int y, int button){ } //-------------------------------------------------------------- void testApp::mouseReleased(int x, int y, int button){ } //-------------------------------------------------------------- void testApp::windowResized(int w, int h){ } //-------------------------------------------------------------- void testApp::gotMessage(ofMessage msg){ } //-------------------------------------------------------------- void testApp::dragEvent(ofDragInfo dragInfo){ }<|endoftext|>
<commit_before>#include <VMDE/VMDE.hpp> namespace VM76 { GDrawable::GDrawable* test_obj; void loop() { for (;;) { ::main_draw_start(); glClearColor(0.0f, 0.0f, 0.0f, 0.0f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glEnable(GL_BLEND); glEnable(GL_DEPTH_TEST); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); // Activate Shader glUseProgram(main_shader->shaderProgram); // Setup uniforms GLuint model_location = glGetUniformLocation(main_shader->shaderProgram, "brightness"); glUniform1f(model_location, VMDE->state.brightness); // Setup textures char uniform_name[16]; for (int index = 0; index < 16; index++) if (Res::tex_unit[index]) { sprintf(uniform_name, "colortex%d", index); glActiveTexture(GL_TEXTURE0 + index); glBindTexture(GL_TEXTURE_2D, Res::tex_unit[index]->texture); glUniform1i(glGetUniformLocation(main_shader->shaderProgram, (GLchar*) uniform_name), index); } //matrix2D(); test_obj->model = glm::translate(test_obj->model, glm::vec3(0.0001f, 0.0001f, 0.0001f)); GDrawable::draw(test_obj, projection, view); ::main_draw_end(); } } static GLfloat vtx[] = { 0.0, 0.0, 0.0, 1.0, 1.0, 1.0, 1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 1.0, 1.0, 1.0, 1.0, 0.0, 1.0, 1.0, 1.0, 0.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 0.0, 0.0, 1.0, 1.0, 1.0, 1.0, 1.0, 0.0 }; static GLuint itx[] = {0, 1, 3, 1, 2, 3}; void start_game() { ::init_engine(800, 600); new Res::Texture((char*)"../Media/terrain.png", 0); test_obj = GDrawable::create(); test_obj->vtx_c = sizeof(vtx) / sizeof(GLfloat); test_obj->ind_c = sizeof(itx) / sizeof(GLuint); test_obj->vertices = vtx; test_obj->indices = itx; test_obj->tri_mesh_count = sizeof(itx) / sizeof(GLuint) / 3; GDrawable::fbind(test_obj); projection = glm::perspective(1.0f, float(VMDE->width) / float(VMDE->height), -1.0f, 1.0f); view = glm::lookAt(glm::vec3(2.0, 0.0, 2.0), glm::vec3(0.0, 0.0, 0.0), glm::vec3(0.0, 1.0, 0.0)); loop(); } } int main() { log("Starting game"); VM76::start_game(); } <commit_msg>正确地关闭程序<commit_after>#include <VMDE/VMDE.hpp> namespace VM76 { GDrawable::GDrawable* test_obj = NULL; void loop() { for (;;) { glfwPollEvents(); ::main_draw_start(); glClearColor(0.2f, 0.3f, 0.3f, 1.0f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); // Activate Shader glUseProgram(main_shader->shaderProgram); // Setup uniforms GLuint model_location = glGetUniformLocation(main_shader->shaderProgram, "brightness"); glUniform1f(model_location, VMDE->state.brightness); // Setup textures char uniform_name[16]; for (int index = 0; index < 16; index++) if (Res::tex_unit[index]) { sprintf(uniform_name, "colortex%d", index); glActiveTexture(GL_TEXTURE0 + index); glBindTexture(GL_TEXTURE_2D, Res::tex_unit[index]->texture); glUniform1i(glGetUniformLocation(main_shader->shaderProgram, (GLchar*) uniform_name), index); } test_obj->model = glm::translate(test_obj->model, glm::vec3(0.0001f, 0.0001f, 0.0001f)); test_obj->model = glm::rotate(test_obj->model, 0.01f, glm::vec3(1.0f, 1.0f, 1.0f)); GDrawable::draw(test_obj, projection, view); ::main_draw_end(); } } static GLfloat vtx[] = { 0.0, 0.0, 0.0, 1.0, 1.0, 1.0, 1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 1.0, 1.0, 1.0, 1.0, 0.0, 1.0, 1.0, 1.0, 0.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 0.0, 0.0, 1.0, 1.0, 1.0, 1.0, 1.0, 0.0, 0.0, 0.0, 1.0, 1.0, 1.0, 1.0, 1.0, 0.0, 0.0, 0.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 0.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 0.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 0.0, }; static GLuint itx[] = {0,1,3, 1,2,3, 4,5,7, 5,6,7}; void start_game() { ::init_engine(800, 600); new Res::Texture((char*)"../Media/terrain.png", 0); test_obj = GDrawable::create(); test_obj->vtx_c = sizeof(vtx) / sizeof(GLfloat); test_obj->ind_c = sizeof(itx) / sizeof(GLuint); test_obj->vertices = vtx; test_obj->indices = itx; test_obj->tri_mesh_count = sizeof(itx) / sizeof(GLuint) / 3; GDrawable::fbind(test_obj); projection = glm::perspective(1.0f, float(VMDE->width) / float(VMDE->height), -1.0f, 1.0f); view = glm::lookAt(glm::vec3(2.0, 3.0, 2.0), glm::vec3(0.0, 0.0, 0.0), glm::vec3(0.0, 1.0, 0.0)); loop(); } void terminate() { GDrawable::dispose(test_obj); } } extern "C" { void client_terminate() { VM76::terminate(); } } int main() { log("Starting game"); VM76::start_game(); } <|endoftext|>
<commit_before>/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #if !defined(MEMORYMANAGERIMPL_HEADER_GUARD_1357924680) #define MEMORYMANAGERIMPL_HEADER_GUARD_1357924680 // Base include file. Must be first. #include <new> #include <xalanc/Include/PlatformDefinitions.hpp> #include <xercesc/framework/MemoryManager.hpp> #if defined(XALAN_WINDOWS) #include <windows.h> #include <stdexcept> #include <stdlib.h> class XalanMemoryManagerImpl : public XALAN_CPP_NAMESPACE_QUALIFIER MemoryManagerType { public: XalanMemoryManagerImpl( DWORD defSize = 0 ) : m_heapHandle(NULL) { m_heapHandle = HeapCreate( HEAP_NO_SERIALIZE, 0, // dwInitialSize defSize); if( m_heapHandle == NULL ) { XALAN_USING_STD(runtime_error) char buffer[20]; buffer[0] = 0; _ultoa( GetLastError(), buffer, 10); throw runtime_error(buffer); } } virtual void* allocate( size_t size ) { LPVOID ptr = HeapAlloc( m_heapHandle, //HANDLE hHeap 0, //DWORD dwFlags size //SIZE_T dwBytes ); if( ptr == 0) { XALAN_USING_STD(bad_alloc) throw bad_alloc(); } return ptr; } virtual void deallocate( void* pDataPointer ) { if ( 0 == HeapFree( m_heapHandle, //HANDLE hHeap, 0, //DWORD dwFlags, pDataPointer ) )//*LPVOID lpMem { XALAN_USING_STD(bad_alloc) throw bad_alloc(); } } MemoryManager* getExceptionMemoryManager() { return this; } virtual ~XalanMemoryManagerImpl() { if( 0 == HeapDestroy(m_heapHandle) ) { XALAN_USING_STD(runtime_error) char buffer[20]; buffer[0] = 0; _ultoa( GetLastError(), buffer, 10); throw runtime_error(buffer); } } private: // Not implemented XalanMemoryManagerImpl& operator=(const XalanMemoryManagerImpl&); XalanMemoryManagerImpl(const XalanMemoryManagerImpl&); //Data HANDLE m_heapHandle; }; #else class XalanMemoryManagerImpl : public XALAN_CPP_NAMESPACE_QUALIFIER MemoryManagerType { public: virtual ~XalanMemoryManagerImpl() { } virtual void* allocate( size_t size ) { void* memptr = ::operator new(size); if (memptr != NULL) { return memptr; } XALAN_USING_STD(bad_alloc) throw bad_alloc(); } virtual void deallocate( void* pDataPointer ) { operator delete(pDataPointer); } }; #endif #endif // MEMORYMANAGERIMPL_HEADER_GUARD_1357924680 <commit_msg>Changes for compatibility with the updated Xerces-C MemoryManager class.<commit_after>/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #if !defined(MEMORYMANAGERIMPL_HEADER_GUARD_1357924680) #define MEMORYMANAGERIMPL_HEADER_GUARD_1357924680 // Base include file. Must be first. #include <new> #include <xalanc/Include/PlatformDefinitions.hpp> #include <xercesc/framework/MemoryManager.hpp> #if defined(XALAN_WINDOWS) #include <windows.h> #include <stdexcept> #include <stdlib.h> class XalanMemoryManagerImpl : public XALAN_CPP_NAMESPACE_QUALIFIER MemoryManagerType { public: XalanMemoryManagerImpl( DWORD defSize = 0 ) : m_heapHandle(NULL) { m_heapHandle = HeapCreate( HEAP_NO_SERIALIZE, 0, // dwInitialSize defSize); if( m_heapHandle == NULL ) { XALAN_USING_STD(runtime_error) char buffer[20]; buffer[0] = 0; _ultoa( GetLastError(), buffer, 10); throw runtime_error(buffer); } } virtual void* allocate( size_t size ) { LPVOID ptr = HeapAlloc( m_heapHandle, //HANDLE hHeap 0, //DWORD dwFlags size //SIZE_T dwBytes ); if( ptr == 0) { XALAN_USING_STD(bad_alloc) throw bad_alloc(); } return ptr; } virtual void deallocate( void* pDataPointer ) { if ( 0 == HeapFree( m_heapHandle, //HANDLE hHeap, 0, //DWORD dwFlags, pDataPointer ) )//*LPVOID lpMem { XALAN_USING_STD(bad_alloc) throw bad_alloc(); } } MemoryManager* getExceptionMemoryManager() { return this; } virtual ~XalanMemoryManagerImpl() { if( 0 == HeapDestroy(m_heapHandle) ) { XALAN_USING_STD(runtime_error) char buffer[20]; buffer[0] = 0; _ultoa( GetLastError(), buffer, 10); throw runtime_error(buffer); } } private: // Not implemented XalanMemoryManagerImpl& operator=(const XalanMemoryManagerImpl&); XalanMemoryManagerImpl(const XalanMemoryManagerImpl&); //Data HANDLE m_heapHandle; }; #else class XalanMemoryManagerImpl : public XALAN_CPP_NAMESPACE_QUALIFIER MemoryManagerType { public: virtual ~XalanMemoryManagerImpl() { } virtual void* allocate( size_t size ) { void* memptr = ::operator new(size); if (memptr != NULL) { return memptr; } XALAN_USING_STD(bad_alloc) throw bad_alloc(); } virtual void deallocate( void* pDataPointer ) { operator delete(pDataPointer); } MemoryManager* getExceptionMemoryManager() { return this; } }; #endif #endif // MEMORYMANAGERIMPL_HEADER_GUARD_1357924680 <|endoftext|>
<commit_before>/** This software was developed by the University of Tennessee as part of the Distributed Data Analysis of Neutron Scattering Experiments (DANSE) project funded by the US National Science Foundation. If you use DANSE applications to do scientific research that leads to publication, we ask that you acknowledge the use of the software with the following sentence: "This work benefited from DANSE software developed under NSF award DMR-0520547." copyright 2008, University of Tennessee */ #include "parameters.hh" #include <stdio.h> #include <math.h> using namespace std; /** * TODO: normalize all dispersion weight lists */ /** * Weight points */ WeightPoint :: WeightPoint() { value = 0.0; weight = 0.0; } WeightPoint :: WeightPoint(double v, double w) { value = v; weight = w; } /** * Dispersion models */ DispersionModel :: DispersionModel() { npts = 1; width = 0.0; }; void DispersionModel :: accept_as_source(DispersionVisitor* visitor, void* from, void* to) { visitor->dispersion_to_dict(from, to); } void DispersionModel :: accept_as_destination(DispersionVisitor* visitor, void* from, void* to) { visitor->dispersion_from_dict(from, to); } void DispersionModel :: operator() (void *param, vector<WeightPoint> &weights){ // Check against zero width if (width<=0) { width = 0.0; npts = 1; } Parameter* par = (Parameter*)param; double value = (*par)(); if (npts<2) { weights.insert(weights.end(), WeightPoint(value, 1.0)); } else { for(int i=0; i<npts; i++) { double val = value + width * (1.0*i/float(npts-1) - 0.5); if ( ((*par).has_min==false || val>(*par).min) && ((*par).has_max==false || val<(*par).max) ) weights.insert(weights.end(), WeightPoint(val, 1.0)); } } } /** * Method to set the weights * Not implemented for this class */ void DispersionModel :: set_weights(int npoints, double* values, double* weights){} /** * Gaussian dispersion */ GaussianDispersion :: GaussianDispersion() { npts = 1; width = 0.0; nsigmas = 2; }; void GaussianDispersion :: accept_as_source(DispersionVisitor* visitor, void* from, void* to) { visitor->gaussian_to_dict(from, to); } void GaussianDispersion :: accept_as_destination(DispersionVisitor* visitor, void* from, void* to) { visitor->gaussian_from_dict(from, to); } double gaussian_weight(double mean, double sigma, double x) { double vary, expo_value; vary = x-mean; expo_value = -vary*vary/(2*sigma*sigma); //return 1.0; return exp(expo_value); } /** * Gaussian dispersion * @param mean: mean value of the Gaussian * @param sigma: standard deviation of the Gaussian * @param x: value at which the Gaussian is evaluated * @return: value of the Gaussian */ void GaussianDispersion :: operator() (void *param, vector<WeightPoint> &weights){ // Check against zero width if (width<=0) { width = 0.0; npts = 1; nsigmas = 3; } Parameter* par = (Parameter*)param; double value = (*par)(); if (npts<2) { weights.insert(weights.end(), WeightPoint(value, 1.0)); } else { for(int i=0; i<npts; i++) { // We cover n(nsigmas) times sigmas on each side of the mean double val = value + width * (2.0*nsigmas*i/float(npts-1) - nsigmas); if ( ((*par).has_min==false || val>(*par).min) && ((*par).has_max==false || val<(*par).max) ) { double _w = gaussian_weight(value, width, val); weights.insert(weights.end(), WeightPoint(val, _w)); } } } } /** * Array dispersion based on input arrays */ void ArrayDispersion :: accept_as_source(DispersionVisitor* visitor, void* from, void* to) { visitor->array_to_dict(from, to); } void ArrayDispersion :: accept_as_destination(DispersionVisitor* visitor, void* from, void* to) { visitor->array_from_dict(from, to); } /** * Method to get the weights */ void ArrayDispersion :: operator() (void *param, vector<WeightPoint> &weights) { Parameter* par = (Parameter*)param; double value = (*par)(); for(int i=0; i<npts; i++) { double val = value + _values[i]; if ( ((*par).has_min==false || val>(*par).min) && ((*par).has_max==false || val<(*par).max) ) weights.insert(weights.end(), WeightPoint(val, _weights[i])); } } /** * Method to set the weights */ void ArrayDispersion :: set_weights(int npoints, double* values, double* weights){ npts = npoints; _values = values; _weights = weights; } /** * Parameters */ Parameter :: Parameter() { value = 0; min = 0.0; max = 0.0; has_min = false; has_max = false; has_dispersion = false; dispersion = new GaussianDispersion(); } Parameter :: Parameter(double _value) { value = _value; min = 0.0; max = 0.0; has_min = false; has_max = false; has_dispersion = false; dispersion = new GaussianDispersion(); } Parameter :: Parameter(double _value, bool disp) { value = _value; min = 0.0; max = 0.0; has_min = false; has_max = false; has_dispersion = disp; dispersion = new GaussianDispersion(); } void Parameter :: get_weights(vector<WeightPoint> &weights) { (*dispersion)((void*)this, weights); } void Parameter :: set_min(double value) { has_min = true; min = value; } void Parameter :: set_max(double value) { has_max = true; max = value; } double Parameter :: operator()() { return value; } double Parameter :: operator=(double _value){ value = _value; } <commit_msg>revert code<commit_after>/** This software was developed by the University of Tennessee as part of the Distributed Data Analysis of Neutron Scattering Experiments (DANSE) project funded by the US National Science Foundation. If you use DANSE applications to do scientific research that leads to publication, we ask that you acknowledge the use of the software with the following sentence: "This work benefited from DANSE software developed under NSF award DMR-0520547." copyright 2008, University of Tennessee */ #include "parameters.hh" #include <stdio.h> #include <math.h> using namespace std; /** * TODO: normalize all dispersion weight lists */ /** * Weight points */ WeightPoint :: WeightPoint() { value = 0.0; weight = 0.0; } WeightPoint :: WeightPoint(double v, double w) { value = v; weight = w; } /** * Dispersion models */ DispersionModel :: DispersionModel() { npts = 1; width = 0.0; }; void DispersionModel :: accept_as_source(DispersionVisitor* visitor, void* from, void* to) { visitor->dispersion_to_dict(from, to); } void DispersionModel :: accept_as_destination(DispersionVisitor* visitor, void* from, void* to) { visitor->dispersion_from_dict(from, to); } void DispersionModel :: operator() (void *param, vector<WeightPoint> &weights){ // Check against zero width if (width<=0) { width = 0.0; npts = 1; } Parameter* par = (Parameter*)param; double value = (*par)(); if (npts<2) { weights.insert(weights.end(), WeightPoint(value, 1.0)); } else { for(int i=0; i<npts; i++) { double val = value + width * (1.0*i/float(npts-1) - 0.5); if ( ((*par).has_min==false || val>(*par).min) && ((*par).has_max==false || val<(*par).max) ) weights.insert(weights.end(), WeightPoint(val, 1.0)); } } } /** * Method to set the weights * Not implemented for this class */ void DispersionModel :: set_weights(int npoints, double* values, double* weights){} /** * Gaussian dispersion */ GaussianDispersion :: GaussianDispersion() { npts = 1; width = 0.0; nsigmas = 2; }; void GaussianDispersion :: accept_as_source(DispersionVisitor* visitor, void* from, void* to) { visitor->gaussian_to_dict(from, to); } void GaussianDispersion :: accept_as_destination(DispersionVisitor* visitor, void* from, void* to) { visitor->gaussian_from_dict(from, to); } double gaussian_weight(double mean, double sigma, double x) { double vary, expo_value; vary = x-mean; expo_value = -vary*vary/(2*sigma*sigma); //return 1.0; return exp(expo_value); } /** * Gaussian dispersion * @param mean: mean value of the Gaussian * @param sigma: standard deviation of the Gaussian * @param x: value at which the Gaussian is evaluated * @return: value of the Gaussian */ void GaussianDispersion :: operator() (void *param, vector<WeightPoint> &weights){ // Check against zero width if (width<=0) { width = 0.0; npts = 1; nsigmas = 3; } Parameter* par = (Parameter*)param; double value = (*par)(); if (npts<2) { weights.insert(weights.end(), WeightPoint(value, 1.0)); } else { for(int i=0; i<npts; i++) { // We cover n(nsigmas) times sigmas on each side of the mean double val = value + width * (2.0*nsigmas*i/float(npts-1) - nsigmas); if ( ((*par).has_min==false || val>(*par).min) && ((*par).has_max==false || val<(*par).max) ) { double _w = gaussian_weight(value, width, val); weights.insert(weights.end(), WeightPoint(val, _w)); } } } } /** * Array dispersion based on input arrays */ void ArrayDispersion :: accept_as_source(DispersionVisitor* visitor, void* from, void* to) { visitor->array_to_dict(from, to); } void ArrayDispersion :: accept_as_destination(DispersionVisitor* visitor, void* from, void* to) { visitor->array_from_dict(from, to); } /** * Method to get the weights */ void ArrayDispersion :: operator() (void *param, vector<WeightPoint> &weights) { Parameter* par = (Parameter*)param; double value = (*par)(); if (npts<2) { weights.insert(weights.end(), WeightPoint(value, 1.0)); } else { for(int i=0; i<npts; i++) { if ( ((*par).has_min==false || _values[i]>(*par).min) && ((*par).has_max==false || _values[i]<(*par).max) ) weights.insert(weights.end(), WeightPoint(_values[i], _weights[i])); } } } /** * Method to set the weights */ void ArrayDispersion :: set_weights(int npoints, double* values, double* weights){ npts = npoints; _values = values; _weights = weights; } /** * Parameters */ Parameter :: Parameter() { value = 0; min = 0.0; max = 0.0; has_min = false; has_max = false; has_dispersion = false; dispersion = new GaussianDispersion(); } Parameter :: Parameter(double _value) { value = _value; min = 0.0; max = 0.0; has_min = false; has_max = false; has_dispersion = false; dispersion = new GaussianDispersion(); } Parameter :: Parameter(double _value, bool disp) { value = _value; min = 0.0; max = 0.0; has_min = false; has_max = false; has_dispersion = disp; dispersion = new GaussianDispersion(); } void Parameter :: get_weights(vector<WeightPoint> &weights) { (*dispersion)((void*)this, weights); } void Parameter :: set_min(double value) { has_min = true; min = value; } void Parameter :: set_max(double value) { has_max = true; max = value; } double Parameter :: operator()() { return value; } double Parameter :: operator=(double _value){ value = _value; } <|endoftext|>
<commit_before>/* * Copyright (c) 2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ #include <IOKit/IOKitLib.h> #include <IOKit/usb/IOUSBLib.h> #include <osquery/core.h> #include <osquery/tables.h> #include <osquery/filesystem.h> #include "osquery/core/conversions.h" namespace osquery { namespace tables { std::string getUSBProperty(const CFMutableDictionaryRef& details, const std::string& key) { // Get a property from the device. auto cfkey = CFStringCreateWithCString(kCFAllocatorDefault, key.c_str(), kCFStringEncodingUTF8); auto property = CFDictionaryGetValue(details, cfkey); CFRelease(cfkey); if (property) { if (CFGetTypeID(property) == CFNumberGetTypeID()) { return stringFromCFNumber((CFDataRef)property); } else if (CFGetTypeID(property) == CFStringGetTypeID()) { return stringFromCFString((CFStringRef)property); } } return ""; } void genUSBDevice(const io_service_t& device, QueryData& results) { Row r; // Get the device details CFMutableDictionaryRef details; IORegistryEntryCreateCFProperties( device, &details, kCFAllocatorDefault, kNilOptions); r["usb_address"] = getUSBProperty(details, "USB Address"); r["usb_port"] = getUSBProperty(details, "PortNum"); r["model"] = getUSBProperty(details, "USB Product Name"); r["model_id"] = getUSBProperty(details, "idProduct"); r["vendor"] = getUSBProperty(details, "USB Vendor Name"); r["vendor_id"] = getUSBProperty(details, "idVendor"); r["serial"] = getUSBProperty(details, "iSerialNumber"); auto non_removable = getUSBProperty(details, "non-removable"); r["removable"] = (non_removable == "yes") ? "0" : "1"; results.push_back(r); CFRelease(details); } QueryData genUSBDevices(QueryContext& context) { QueryData results; auto matching = IOServiceMatching(kIOUSBDeviceClassName); if (matching == nullptr) { // No devices matched USB, very odd. return results; } io_iterator_t it; auto kr = IOServiceGetMatchingServices(kIOMasterPortDefault, matching, &it); if (kr != KERN_SUCCESS) { return results; } io_service_t device; while ((device = IOIteratorNext(it))) { genUSBDevice(device, results); IOObjectRelease(device); } IOObjectRelease(it); return results; } } } <commit_msg>[Fix #1432] Improve OS X USB device reporting<commit_after>/* * Copyright (c) 2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ #include <iomanip> #include <sstream> #include <IOKit/IOKitLib.h> #include <IOKit/usb/IOUSBLib.h> #include <osquery/core.h> #include <osquery/tables.h> #include <osquery/filesystem.h> #include "osquery/core/conversions.h" namespace osquery { namespace tables { std::string getUSBProperty(const CFMutableDictionaryRef& details, const std::string& key) { // Get a property from the device. auto cfkey = CFStringCreateWithCString(kCFAllocatorDefault, key.c_str(), kCFStringEncodingUTF8); auto property = CFDictionaryGetValue(details, cfkey); CFRelease(cfkey); if (property) { if (CFGetTypeID(property) == CFNumberGetTypeID()) { return stringFromCFNumber((CFDataRef)property); } else if (CFGetTypeID(property) == CFStringGetTypeID()) { return stringFromCFString((CFStringRef)property); } } return ""; } inline void idToHex(std::string& id) { int base = AS_LITERAL(int, id); std::stringstream hex_id; hex_id << std::hex << std::setw(4) << std::setfill('0') << (base & 0xFFFF); id = hex_id.str(); } void genUSBDevice(const io_service_t& device, QueryData& results) { Row r; // Get the device details CFMutableDictionaryRef details; IORegistryEntryCreateCFProperties( device, &details, kCFAllocatorDefault, kNilOptions); r["usb_address"] = getUSBProperty(details, "USB Address"); r["usb_port"] = getUSBProperty(details, "PortNum"); r["model"] = getUSBProperty(details, "USB Product Name"); if (r.at("model").size() == 0) { // Could not find the model name from IOKit, use the label. io_name_t name; if (IORegistryEntryGetName(device, name) == KERN_SUCCESS) { r["model"] = std::string(name); } } r["model_id"] = getUSBProperty(details, "idProduct"); r["vendor"] = getUSBProperty(details, "USB Vendor Name"); r["vendor_id"] = getUSBProperty(details, "idVendor"); r["serial"] = getUSBProperty(details, "USB Serial Number"); if (r.at("serial").size() == 0) { r["serial"] = getUSBProperty(details, "iSerialNumber"); } auto non_removable = getUSBProperty(details, "non-removable"); r["removable"] = (non_removable == "yes") ? "0" : "1"; if (r.at("vendor_id").size() > 0 && r.at("model_id").size() > 0) { // Only add the USB device on OS X if it contains a Vendor and Model ID. // On OS X 10.11 the simulation hubs are PCI devices within IOKit and // lack the useful USB metadata. idToHex(r["vendor_id"]); idToHex(r["model_id"]); results.push_back(r); } CFRelease(details); } QueryData genUSBDevices(QueryContext& context) { QueryData results; auto matching = IOServiceMatching(kIOUSBDeviceClassName); if (matching == nullptr) { // No devices matched USB, very odd. return results; } io_iterator_t it; auto kr = IOServiceGetMatchingServices(kIOMasterPortDefault, matching, &it); if (kr != KERN_SUCCESS) { return results; } io_service_t device; while ((device = IOIteratorNext(it))) { genUSBDevice(device, results); IOObjectRelease(device); } IOObjectRelease(it); return results; } } } <|endoftext|>
<commit_before>#ifndef _SNARKFRONT_AES_INV_CIPHER_HPP_ #define _SNARKFRONT_AES_INV_CIPHER_HPP_ #include <array> #include <cstdint> #include "AES_InvSBox.hpp" #include "AES_KeyExpansion.hpp" namespace snarkfront { //////////////////////////////////////////////////////////////////////////////// // FIPS PUB 197, NIST November 2001 // // Algorithm Key Length Block Size Number of Rounds // (Nk words) (Nb words) (Nr) // // AES-128 4 4 10 // AES-192 6 4 12 // AES-256 8 4 14 // //////////////////////////////////////////////////////////////////////////////// // 5.3 Inverse Cipher // template <typename VAR, typename T, typename U, typename BITWISE> class AES_InvCipher { public: typedef VAR VarType; typedef std::array<VAR, 16> BlockType; typedef AES_KeyExpansion<VAR, T, U, BITWISE> KeyExpansion; AES_InvCipher() = default; // AES-128 void operator() (const std::array<VAR, 16>& in, std::array<VAR, 16>& out, const std::array<VAR, 176>& w) const { decrypt(in, out, w); } // AES-192 void operator() (const std::array<VAR, 16>& in, std::array<VAR, 16>& out, const std::array<VAR, 208>& w) const { decrypt(in, out, w); } // AES-256 void operator() (const std::array<VAR, 16>& in, std::array<VAR, 16>& out, const std::array<VAR, 240>& w) const { decrypt(in, out, w); } private: // AES-128 key schedule size 176 (Nr = 10) // AES-192 key schedule size 208 (Nr = 12) // AES-256 key schedule size 240 (Nr = 14) template <std::size_t WSZ> void decrypt(const std::array<VAR, 16>& in, std::array<VAR, 16>& out, const std::array<VAR, WSZ>& w) const // 16 * (Nr + 1) octets { const auto Nr = w.size() / 16 - 1; auto state = in; AddRoundKey(state, w, 16*Nr); for (std::size_t round = Nr - 1; round > 0; --round) { InvShiftRows(state); InvSubBytes(state); AddRoundKey(state, w, 16*round); InvMixColumns(state); } InvShiftRows(state); InvSubBytes(state); AddRoundKey(state, w, 0); out = state; } // 5.3.1 InvShiftRows() Transformation void InvShiftRows(std::array<VAR, 16>& state) const { VAR tmp; // second row rotate right by one element tmp = state[13]; state[13] = state[9]; state[9] = state[5]; state[5] = state[1]; state[1] = tmp; // third row rotate right by two elements tmp = state[14]; state[14] = state[6]; state[6] = tmp; tmp = state[10]; state[10] = state[2]; state[2] = tmp; // fourth row rotate right by three elements tmp = state[15]; state[15] = state[3]; state[3] = state[7]; state[7] = state[11]; state[11] = tmp; } // 5.3.2 InvSubBytes() Transformation void InvSubBytes(std::array<VAR, 16>& state) const { for (auto& a : state) a = m_inv_sbox(a); } // 5.3.3 InvMixColumns() Transformation void InvMixColumns(std::array<VAR, 16>& state) const { // irreducible polynomial for AES const auto modpoly = BITWISE::constant(0x1b); for (std::size_t i = 0; i < 16; i += 4) { const VAR xs0 = BITWISE::xtime(state[i], modpoly), // {02} * s0 xxs0 = BITWISE::xtime(xs0, modpoly), // {04} * s0 xxxs0 = BITWISE::xtime(xxs0, modpoly); // {08} * s0 const VAR xs1 = BITWISE::xtime(state[i + 1], modpoly), // {02} * s1 xxs1 = BITWISE::xtime(xs1, modpoly), // {04} * s1 xxxs1 = BITWISE::xtime(xxs1, modpoly); // {08} * s1 const VAR xs2 = BITWISE::xtime(state[i + 2], modpoly), // {02} * s2 xxs2 = BITWISE::xtime(xs2, modpoly), // {04} * s2 xxxs2 = BITWISE::xtime(xxs2, modpoly); // {08} * s2 const VAR xs3 = BITWISE::xtime(state[i + 3], modpoly), // {02} * s3 xxs3 = BITWISE::xtime(xs3, modpoly), // {04} * s3 xxxs3 = BITWISE::xtime(xxs3, modpoly); // {08} * s3 // sp0 = ({0e} * s0) XOR ({0b} * s1) XOR ({0d} * s2) XOR ({09} * s3) const VAR sp0 = BITWISE::XOR( BITWISE::XOR(xs0, BITWISE::XOR(xxs0, xxxs0)), BITWISE::XOR( BITWISE::XOR(state[i + 1], BITWISE::XOR(xs1, xxxs1)), BITWISE::XOR( BITWISE::XOR(state[i + 2], BITWISE::XOR(xxs2, xxxs2)), BITWISE::XOR(state[i + 3], xxxs3)))); // sp1 = ({09} * s0) XOR ({0e} * s1) XOR ({0b} * s2) XOR ({0d} * s3) const VAR sp1 = BITWISE::XOR( BITWISE::XOR(state[i], xxxs0), BITWISE::XOR( BITWISE::XOR(xs1, BITWISE::XOR(xxs1, xxxs1)), BITWISE::XOR( BITWISE::XOR(state[i + 2], BITWISE::XOR(xs2, xxxs2)), BITWISE::XOR(state[i + 3], BITWISE::XOR(xxs3, xxxs3))))); // sp2 = ({0d} * s0) XOR ({09} * s1) XOR ({0e} * s2) XOR ({0b} * s3) const VAR sp2 = BITWISE::XOR( BITWISE::XOR(state[i], BITWISE::XOR(xxs0, xxxs0)), BITWISE::XOR( BITWISE::XOR(state[i + 1], xxxs1), BITWISE::XOR( BITWISE::XOR(xs2, BITWISE::XOR(xxs2, xxxs2)), BITWISE::XOR(state[i + 3], BITWISE::XOR(xs3, xxxs3))))); // sp3 = ({0b} * s0) XOR ({0d} * s1) XOR ({09} * s2) XOR ({0e} * s3) const VAR sp3 = BITWISE::XOR( BITWISE::XOR(state[i], BITWISE::XOR(xs0, xxxs0)), BITWISE::XOR( BITWISE::XOR(state[i + 1], BITWISE::XOR(xxs1, xxxs1)), BITWISE::XOR( BITWISE::XOR(state[i + 2], xxxs2), BITWISE::XOR(xs3, BITWISE::XOR(xxs3, xxxs3))))); state[i] = sp0; state[i + 1] = sp1; state[i + 2] = sp2; state[i + 3] = sp3; } } // 5.3.4 AddRoundKey() Transformation template <std::size_t N> void AddRoundKey(std::array<VAR, 16>& state, const std::array<VAR, N>& w, const std::size_t offset) const { for (std::size_t i = 0; i < 16; ++i) state[i] = BITWISE::XOR(state[i], w[i + offset]); } const AES_InvSBox<T, U, BITWISE> m_inv_sbox; }; //////////////////////////////////////////////////////////////////////////////// // typedefs // namespace zk { template <typename FR> using AES_Decrypt = AES_InvCipher<AST_Var<Alg_uint8<FR>>, AST_Node<Alg_uint8<FR>>, AST_Op<Alg_uint8<FR>>, BitwiseAST<Alg_uint8<FR>>>; } // namespace zk namespace eval { typedef AES_InvCipher<std::uint8_t, std::uint8_t, std::uint8_t, BitwiseINT<std::uint8_t>> AES_Decrypt; } // namespace eval } // namespace snarkfront #endif <commit_msg>scope header file paths<commit_after>#ifndef _SNARKFRONT_AES_INV_CIPHER_HPP_ #define _SNARKFRONT_AES_INV_CIPHER_HPP_ #include <array> #include <cstdint> #include <snarkfront/AES_InvSBox.hpp> #include <snarkfront/AES_KeyExpansion.hpp> namespace snarkfront { //////////////////////////////////////////////////////////////////////////////// // FIPS PUB 197, NIST November 2001 // // Algorithm Key Length Block Size Number of Rounds // (Nk words) (Nb words) (Nr) // // AES-128 4 4 10 // AES-192 6 4 12 // AES-256 8 4 14 // //////////////////////////////////////////////////////////////////////////////// // 5.3 Inverse Cipher // template <typename VAR, typename T, typename U, typename BITWISE> class AES_InvCipher { public: typedef VAR VarType; typedef std::array<VAR, 16> BlockType; typedef AES_KeyExpansion<VAR, T, U, BITWISE> KeyExpansion; AES_InvCipher() = default; // AES-128 void operator() (const std::array<VAR, 16>& in, std::array<VAR, 16>& out, const std::array<VAR, 176>& w) const { decrypt(in, out, w); } // AES-192 void operator() (const std::array<VAR, 16>& in, std::array<VAR, 16>& out, const std::array<VAR, 208>& w) const { decrypt(in, out, w); } // AES-256 void operator() (const std::array<VAR, 16>& in, std::array<VAR, 16>& out, const std::array<VAR, 240>& w) const { decrypt(in, out, w); } private: // AES-128 key schedule size 176 (Nr = 10) // AES-192 key schedule size 208 (Nr = 12) // AES-256 key schedule size 240 (Nr = 14) template <std::size_t WSZ> void decrypt(const std::array<VAR, 16>& in, std::array<VAR, 16>& out, const std::array<VAR, WSZ>& w) const // 16 * (Nr + 1) octets { const auto Nr = w.size() / 16 - 1; auto state = in; AddRoundKey(state, w, 16*Nr); for (std::size_t round = Nr - 1; round > 0; --round) { InvShiftRows(state); InvSubBytes(state); AddRoundKey(state, w, 16*round); InvMixColumns(state); } InvShiftRows(state); InvSubBytes(state); AddRoundKey(state, w, 0); out = state; } // 5.3.1 InvShiftRows() Transformation void InvShiftRows(std::array<VAR, 16>& state) const { VAR tmp; // second row rotate right by one element tmp = state[13]; state[13] = state[9]; state[9] = state[5]; state[5] = state[1]; state[1] = tmp; // third row rotate right by two elements tmp = state[14]; state[14] = state[6]; state[6] = tmp; tmp = state[10]; state[10] = state[2]; state[2] = tmp; // fourth row rotate right by three elements tmp = state[15]; state[15] = state[3]; state[3] = state[7]; state[7] = state[11]; state[11] = tmp; } // 5.3.2 InvSubBytes() Transformation void InvSubBytes(std::array<VAR, 16>& state) const { for (auto& a : state) a = m_inv_sbox(a); } // 5.3.3 InvMixColumns() Transformation void InvMixColumns(std::array<VAR, 16>& state) const { // irreducible polynomial for AES const auto modpoly = BITWISE::constant(0x1b); for (std::size_t i = 0; i < 16; i += 4) { const VAR xs0 = BITWISE::xtime(state[i], modpoly), // {02} * s0 xxs0 = BITWISE::xtime(xs0, modpoly), // {04} * s0 xxxs0 = BITWISE::xtime(xxs0, modpoly); // {08} * s0 const VAR xs1 = BITWISE::xtime(state[i + 1], modpoly), // {02} * s1 xxs1 = BITWISE::xtime(xs1, modpoly), // {04} * s1 xxxs1 = BITWISE::xtime(xxs1, modpoly); // {08} * s1 const VAR xs2 = BITWISE::xtime(state[i + 2], modpoly), // {02} * s2 xxs2 = BITWISE::xtime(xs2, modpoly), // {04} * s2 xxxs2 = BITWISE::xtime(xxs2, modpoly); // {08} * s2 const VAR xs3 = BITWISE::xtime(state[i + 3], modpoly), // {02} * s3 xxs3 = BITWISE::xtime(xs3, modpoly), // {04} * s3 xxxs3 = BITWISE::xtime(xxs3, modpoly); // {08} * s3 // sp0 = ({0e} * s0) XOR ({0b} * s1) XOR ({0d} * s2) XOR ({09} * s3) const VAR sp0 = BITWISE::XOR( BITWISE::XOR(xs0, BITWISE::XOR(xxs0, xxxs0)), BITWISE::XOR( BITWISE::XOR(state[i + 1], BITWISE::XOR(xs1, xxxs1)), BITWISE::XOR( BITWISE::XOR(state[i + 2], BITWISE::XOR(xxs2, xxxs2)), BITWISE::XOR(state[i + 3], xxxs3)))); // sp1 = ({09} * s0) XOR ({0e} * s1) XOR ({0b} * s2) XOR ({0d} * s3) const VAR sp1 = BITWISE::XOR( BITWISE::XOR(state[i], xxxs0), BITWISE::XOR( BITWISE::XOR(xs1, BITWISE::XOR(xxs1, xxxs1)), BITWISE::XOR( BITWISE::XOR(state[i + 2], BITWISE::XOR(xs2, xxxs2)), BITWISE::XOR(state[i + 3], BITWISE::XOR(xxs3, xxxs3))))); // sp2 = ({0d} * s0) XOR ({09} * s1) XOR ({0e} * s2) XOR ({0b} * s3) const VAR sp2 = BITWISE::XOR( BITWISE::XOR(state[i], BITWISE::XOR(xxs0, xxxs0)), BITWISE::XOR( BITWISE::XOR(state[i + 1], xxxs1), BITWISE::XOR( BITWISE::XOR(xs2, BITWISE::XOR(xxs2, xxxs2)), BITWISE::XOR(state[i + 3], BITWISE::XOR(xs3, xxxs3))))); // sp3 = ({0b} * s0) XOR ({0d} * s1) XOR ({09} * s2) XOR ({0e} * s3) const VAR sp3 = BITWISE::XOR( BITWISE::XOR(state[i], BITWISE::XOR(xs0, xxxs0)), BITWISE::XOR( BITWISE::XOR(state[i + 1], BITWISE::XOR(xxs1, xxxs1)), BITWISE::XOR( BITWISE::XOR(state[i + 2], xxxs2), BITWISE::XOR(xs3, BITWISE::XOR(xxs3, xxxs3))))); state[i] = sp0; state[i + 1] = sp1; state[i + 2] = sp2; state[i + 3] = sp3; } } // 5.3.4 AddRoundKey() Transformation template <std::size_t N> void AddRoundKey(std::array<VAR, 16>& state, const std::array<VAR, N>& w, const std::size_t offset) const { for (std::size_t i = 0; i < 16; ++i) state[i] = BITWISE::XOR(state[i], w[i + offset]); } const AES_InvSBox<T, U, BITWISE> m_inv_sbox; }; //////////////////////////////////////////////////////////////////////////////// // typedefs // namespace zk { template <typename FR> using AES_Decrypt = AES_InvCipher<AST_Var<Alg_uint8<FR>>, AST_Node<Alg_uint8<FR>>, AST_Op<Alg_uint8<FR>>, BitwiseAST<Alg_uint8<FR>>>; } // namespace zk namespace eval { typedef AES_InvCipher<std::uint8_t, std::uint8_t, std::uint8_t, BitwiseINT<std::uint8_t>> AES_Decrypt; } // namespace eval } // namespace snarkfront #endif <|endoftext|>
<commit_before>// The MIT License (MIT) // // Copyright (c) 2015 Sergey Makeev, Vadim Slyusarev // // 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 "Tests.h" #include <UnitTest++.h> #include <MTScheduler.h> SUITE(StackSizeTests) { //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// struct StandartStackSizeTask { MT_DECLARE_TASK(StandartStackSizeTask, MT::StackRequirements::STANDARD, MT::Color::Blue); void Do(MT::FiberContext&) { byte stackData[28000]; memset(stackData, 0x0D, MT_ARRAY_SIZE(stackData)); } }; //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// struct ExtendedStackSizeTask { MT_DECLARE_TASK(ExtendedStackSizeTask, MT::StackRequirements::EXTENDED, MT::Color::Red); void Do(MT::FiberContext&) { byte stackData[262144]; memset(stackData, 0x0D, MT_ARRAY_SIZE(stackData)); } }; //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// TEST(RunStandartTasks) { MT::TaskScheduler scheduler; StandartStackSizeTask tasks[100]; scheduler.RunAsync(MT::TaskGroup::Default(), &tasks[0], MT_ARRAY_SIZE(tasks)); CHECK(scheduler.WaitAll(1000)); } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// TEST(RunExtendedTasks) { MT::TaskScheduler scheduler; ExtendedStackSizeTask tasks[100]; scheduler.RunAsync(MT::TaskGroup::Default(), &tasks[0], MT_ARRAY_SIZE(tasks)); CHECK(scheduler.WaitAll(1000)); } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// TEST(RunMixedTasks) { MT::TaskScheduler scheduler; MT::TaskPool<ExtendedStackSizeTask, 64> extendedTaskPool; MT::TaskPool<StandartStackSizeTask, 64> standardTaskPool; MT::TaskHandle taskHandles[100]; for (size_t i = 0; i < MT_ARRAY_SIZE(taskHandles); ++i) { MT::TaskHandle handle; if (i & 1) { handle = extendedTaskPool.Alloc(ExtendedStackSizeTask()); } else { handle = standardTaskPool.Alloc(StandartStackSizeTask()); } taskHandles[i] = handle; } scheduler.RunAsync(MT::TaskGroup::Default(), &taskHandles[0], MT_ARRAY_SIZE(taskHandles)); CHECK(scheduler.WaitAll(1000)); } } <commit_msg>Fix OSX test<commit_after>// The MIT License (MIT) // // Copyright (c) 2015 Sergey Makeev, Vadim Slyusarev // // 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 "Tests.h" #include <UnitTest++.h> #include <MTScheduler.h> SUITE(StackSizeTests) { //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// struct StandartStackSizeTask { MT_DECLARE_TASK(StandartStackSizeTask, MT::StackRequirements::STANDARD, MT::Color::Blue); void Do(MT::FiberContext&) { byte stackData[26000]; memset(stackData, 0x0D, MT_ARRAY_SIZE(stackData)); } }; //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// struct ExtendedStackSizeTask { MT_DECLARE_TASK(ExtendedStackSizeTask, MT::StackRequirements::EXTENDED, MT::Color::Red); void Do(MT::FiberContext&) { byte stackData[262144]; memset(stackData, 0x0D, MT_ARRAY_SIZE(stackData)); } }; //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// TEST(RunStandartTasks) { MT::TaskScheduler scheduler; StandartStackSizeTask tasks[100]; scheduler.RunAsync(MT::TaskGroup::Default(), &tasks[0], MT_ARRAY_SIZE(tasks)); CHECK(scheduler.WaitAll(1000)); } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// TEST(RunExtendedTasks) { MT::TaskScheduler scheduler; ExtendedStackSizeTask tasks[100]; scheduler.RunAsync(MT::TaskGroup::Default(), &tasks[0], MT_ARRAY_SIZE(tasks)); CHECK(scheduler.WaitAll(1000)); } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// TEST(RunMixedTasks) { MT::TaskScheduler scheduler; MT::TaskPool<ExtendedStackSizeTask, 64> extendedTaskPool; MT::TaskPool<StandartStackSizeTask, 64> standardTaskPool; MT::TaskHandle taskHandles[100]; for (size_t i = 0; i < MT_ARRAY_SIZE(taskHandles); ++i) { MT::TaskHandle handle; if (i & 1) { handle = extendedTaskPool.Alloc(ExtendedStackSizeTask()); } else { handle = standardTaskPool.Alloc(StandartStackSizeTask()); } taskHandles[i] = handle; } scheduler.RunAsync(MT::TaskGroup::Default(), &taskHandles[0], MT_ARRAY_SIZE(taskHandles)); CHECK(scheduler.WaitAll(1000)); } } <|endoftext|>
<commit_before>/*************************************************************************** * Copyright (C) 2014 by Marcin Ziemiński <zieminn@gmail.com> * * * * 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.1 of the License, or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU 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 "proxy-service-adaptee.h" #include "proxy-service.h" #include "otr-constants.h" #include <TelepathyQt/DBusObject> ProxyServiceAdaptee::ProxyServiceAdaptee(ProxyService *ps, const QDBusConnection &dbusConnection) : adaptor(new Tp::Service::ProxyServiceAdaptor(dbusConnection, this, ps->dbusObject())), ps(ps) { connect(ps, SIGNAL(keyGenerationStarted(const QString&)), SLOT(onKeyGenerationStarted(const QString&))); connect(ps, SIGNAL(keyGenerationFinished(const QString&, bool)), SLOT(onKeyGenerationFinished(const QString&, bool))); } ProxyServiceAdaptee::~ProxyServiceAdaptee() { } uint ProxyServiceAdaptee::policy() const { switch(ps->getPolicy()) { case OTRL_POLICY_ALWAYS: return 0; case OTRL_POLICY_OPPORTUNISTIC: return 1; case OTRL_POLICY_MANUAL: return 2; case OTRL_POLICY_NEVER: default: return 3; } } void ProxyServiceAdaptee::setPolicy(uint otrPolicy) { switch(otrPolicy) { case 0: ps->setPolicy(OTRL_POLICY_ALWAYS); case 1: ps->setPolicy(OTRL_POLICY_OPPORTUNISTIC); case 2: ps->setPolicy(OTRL_POLICY_MANUAL); case 3: ps->setPolicy(OTRL_POLICY_NEVER); default: // nos uch policy return; } } void ProxyServiceAdaptee::onProxyConnected(const QDBusObjectPath &proxyPath) { Q_EMIT proxyConnected(proxyPath); } void ProxyServiceAdaptee::onProxyDisconnected(const QDBusObjectPath &proxyPath) { Q_EMIT proxyDisconnected(proxyPath); } void ProxyServiceAdaptee::onKeyGenerationStarted(const QString &accountId) { Q_EMIT(keyGenerationStarted(OTR::utils::objectPathFor(accountId))); } void ProxyServiceAdaptee::onKeyGenerationFinished(const QString &accountId, bool error) { Q_EMIT(keyGenerationFinished(OTR::utils::objectPathFor(accountId), error)); } void ProxyServiceAdaptee::generatePrivateKey(const QDBusObjectPath &accountPath, const Tp::Service::ProxyServiceAdaptor::GeneratePrivateKeyContextPtr &context) { Tp::AccountPtr ac = ps->accountManager()->accountForObjectPath(accountPath.path()); if(ac && ac->isValidAccount() && ps->createNewPrivateKey(OTR::utils::accountIdFor(accountPath), ac->normalizedName())) { context->setFinished(); } else { // TODO better errors context->setFinishedWithError(TP_QT_ERROR_INVALID_ARGUMENT, QLatin1String("Could not generate private key for given account")); } } void ProxyServiceAdaptee::getFingerprintForAccount(QDBusObjectPath accountPath, const Tp::Service::ProxyServiceAdaptor::GetFingerprintForAccountContextPtr &context) { Tp::AccountPtr ac = ps->accountManager()->accountForObjectPath(accountPath.path()); if(ac && ac->isValidAccount()) { context->setFinished(ps->getFingerprintFor(OTR::utils::accountIdFor(accountPath), ac->normalizedName())); } else { context->setFinishedWithError(TP_QT_ERROR_INVALID_ARGUMENT, QLatin1String("No such valid account")); } } <commit_msg>Fixed policy settings bug.<commit_after>/*************************************************************************** * Copyright (C) 2014 by Marcin Ziemiński <zieminn@gmail.com> * * * * 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.1 of the License, or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU 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 "proxy-service-adaptee.h" #include "proxy-service.h" #include "otr-constants.h" #include <TelepathyQt/DBusObject> ProxyServiceAdaptee::ProxyServiceAdaptee(ProxyService *ps, const QDBusConnection &dbusConnection) : adaptor(new Tp::Service::ProxyServiceAdaptor(dbusConnection, this, ps->dbusObject())), ps(ps) { connect(ps, SIGNAL(keyGenerationStarted(const QString&)), SLOT(onKeyGenerationStarted(const QString&))); connect(ps, SIGNAL(keyGenerationFinished(const QString&, bool)), SLOT(onKeyGenerationFinished(const QString&, bool))); } ProxyServiceAdaptee::~ProxyServiceAdaptee() { } uint ProxyServiceAdaptee::policy() const { switch(ps->getPolicy()) { case OTRL_POLICY_ALWAYS: return 0; case OTRL_POLICY_OPPORTUNISTIC: return 1; case OTRL_POLICY_MANUAL: return 2; case OTRL_POLICY_NEVER: default: return 3; } } void ProxyServiceAdaptee::setPolicy(uint otrPolicy) { switch(otrPolicy) { case 0: ps->setPolicy(OTRL_POLICY_ALWAYS); return; case 1: ps->setPolicy(OTRL_POLICY_OPPORTUNISTIC); return; case 2: ps->setPolicy(OTRL_POLICY_MANUAL); return; case 3: ps->setPolicy(OTRL_POLICY_NEVER); return; default: // nos uch policy return; } } void ProxyServiceAdaptee::onProxyConnected(const QDBusObjectPath &proxyPath) { Q_EMIT proxyConnected(proxyPath); } void ProxyServiceAdaptee::onProxyDisconnected(const QDBusObjectPath &proxyPath) { Q_EMIT proxyDisconnected(proxyPath); } void ProxyServiceAdaptee::onKeyGenerationStarted(const QString &accountId) { Q_EMIT(keyGenerationStarted(OTR::utils::objectPathFor(accountId))); } void ProxyServiceAdaptee::onKeyGenerationFinished(const QString &accountId, bool error) { Q_EMIT(keyGenerationFinished(OTR::utils::objectPathFor(accountId), error)); } void ProxyServiceAdaptee::generatePrivateKey(const QDBusObjectPath &accountPath, const Tp::Service::ProxyServiceAdaptor::GeneratePrivateKeyContextPtr &context) { Tp::AccountPtr ac = ps->accountManager()->accountForObjectPath(accountPath.path()); if(ac && ac->isValidAccount() && ps->createNewPrivateKey(OTR::utils::accountIdFor(accountPath), ac->normalizedName())) { context->setFinished(); } else { // TODO better errors context->setFinishedWithError(TP_QT_ERROR_INVALID_ARGUMENT, QLatin1String("Could not generate private key for given account")); } } void ProxyServiceAdaptee::getFingerprintForAccount(QDBusObjectPath accountPath, const Tp::Service::ProxyServiceAdaptor::GetFingerprintForAccountContextPtr &context) { Tp::AccountPtr ac = ps->accountManager()->accountForObjectPath(accountPath.path()); if(ac && ac->isValidAccount()) { context->setFinished(ps->getFingerprintFor(OTR::utils::accountIdFor(accountPath), ac->normalizedName())); } else { context->setFinishedWithError(TP_QT_ERROR_INVALID_ARGUMENT, QLatin1String("No such valid account")); } } <|endoftext|>
<commit_before><commit_msg>fix of parsing<commit_after><|endoftext|>
<commit_before><commit_msg>Set VK_COMMAND_BUFFER_USAGE_RENDER_PASS_CONTINUE_BIT on secondary begin<commit_after><|endoftext|>
<commit_before> #include "../../Flare.h" #include "FlareMainMenu.h" #include "../../Game/FlareGame.h" #include "../../Game/FlareSaveGame.h" #include "../../Player/FlareMenuPawn.h" #include "../../Player/FlareMenuManager.h" #include "../../Player/FlarePlayerController.h" #define LOCTEXT_NAMESPACE "FlareMainMenu" /*---------------------------------------------------- Construct ----------------------------------------------------*/ void SFlareMainMenu::Construct(const FArguments& InArgs) { // Data MenuManager = InArgs._MenuManager; const FFlareStyleCatalog& Theme = FFlareStyleSet::GetDefaultTheme(); AFlarePlayerController* PC = MenuManager->GetPC(); SaveSlotCount = 3; Initialized = false; // Build structure ChildSlot .HAlign(HAlign_Fill) .VAlign(VAlign_Fill) [ SNew(SVerticalBox) + SVerticalBox::Slot() .AutoHeight() .HAlign(HAlign_Fill) .VAlign(VAlign_Center) .Padding(Theme.ContentPadding) [ SNew(SHorizontalBox) // Icon + SHorizontalBox::Slot() .AutoWidth() [ SNew(SImage) .Image(FFlareStyleSet::GetIcon("HeliumRain")) ] // Title + SHorizontalBox::Slot() .VAlign(VAlign_Center) .Padding(Theme.ContentPadding) [ SNew(STextBlock) .TextStyle(&Theme.TitleFont) .Text(LOCTEXT("MainMenu", "HELIUM RAIN")) ] // Settings + SHorizontalBox::Slot() .HAlign(HAlign_Right) .VAlign(VAlign_Bottom) .Padding(Theme.TitleButtonPadding) .AutoWidth() [ SNew(SFlareRoundButton) .Text(LOCTEXT("Settings", "Settings")) .Icon(AFlareMenuManager::GetMenuIcon(EFlareMenu::MENU_Settings, true)) .OnClicked(this, &SFlareMainMenu::OnOpenSettings) ] // Quit + SHorizontalBox::Slot() .HAlign(HAlign_Right) .VAlign(VAlign_Bottom) .Padding(Theme.TitleButtonPadding) .AutoWidth() [ SNew(SFlareRoundButton) .Text(LOCTEXT("Quit", "Quit game")) .Icon(AFlareMenuManager::GetMenuIcon(EFlareMenu::MENU_Quit, true)) .OnClicked(this, &SFlareMainMenu::OnQuitGame) ] ] // Separator + SVerticalBox::Slot() .AutoHeight() .Padding(FMargin(200, 40)) [ SNew(SImage).Image(&Theme.SeparatorBrush) ] // Save slots + SVerticalBox::Slot() [ SAssignNew(SaveBox, SHorizontalBox) ] ]; // Add save slots for (int32 Index = 1; Index <= SaveSlotCount; Index++) { TSharedPtr<int32> IndexPtr(new int32(Index)); SaveBox->AddSlot() .HAlign(HAlign_Center) .VAlign(VAlign_Top) [ SNew(SVerticalBox) // Slot N + SVerticalBox::Slot() .AutoHeight() .Padding(Theme.TitlePadding) [ SNew(STextBlock) .TextStyle(&Theme.TitleFont) .Text(FText::FromString(FString::FromInt(Index) + "/")) ] // Company emblem + SVerticalBox::Slot() .AutoHeight() .Padding(Theme.ContentPadding) [ SNew(SHorizontalBox) + SHorizontalBox::Slot() .HAlign(HAlign_Center) [ SNew(SImage) .Image(this, &SFlareMainMenu::GetSaveIcon, Index) ] ] // Description + SVerticalBox::Slot() .AutoHeight() [ SNew(STextBlock) .TextStyle(&Theme.TextFont) .Text(this, &SFlareMainMenu::GetText, Index) ] // Launch + SVerticalBox::Slot() .HAlign(HAlign_Left) .VAlign(VAlign_Center) .AutoHeight() .Padding(Theme.SmallContentPadding) [ SNew(SFlareButton) .Text(this, &SFlareMainMenu::GetButtonText, Index) .Icon(this, &SFlareMainMenu::GetButtonIcon, Index) .OnClicked(this, &SFlareMainMenu::OnOpenSlot, IndexPtr) .Width(5) .Height(1) ] // Delete + SVerticalBox::Slot() .HAlign(HAlign_Left) .VAlign(VAlign_Center) .AutoHeight() .Padding(Theme.SmallContentPadding) [ SNew(SFlareButton) .Text(LOCTEXT("Delete", "Delete game")) .Icon(FFlareStyleSet::GetIcon("Delete")) .OnClicked(this, &SFlareMainMenu::OnDeleteSlot, IndexPtr) .Width(5) .Height(1) .Visibility(this, &SFlareMainMenu::GetDeleteButtonVisibility, Index) ] ]; } } /*---------------------------------------------------- Interaction ----------------------------------------------------*/ void SFlareMainMenu::Setup() { SetEnabled(false); SetVisibility(EVisibility::Hidden); } void SFlareMainMenu::Enter() { FLOG("SFlareMainMenu::Enter"); UpdateSaveSlots(); SetEnabled(true); SetVisibility(EVisibility::Visible); } void SFlareMainMenu::Exit() { SetEnabled(false); Initialized = false; SaveSlots.Empty(); SetVisibility(EVisibility::Hidden); } /*---------------------------------------------------- Callbacks ----------------------------------------------------*/ FText SFlareMainMenu::GetText(int32 Index) const { if (IsExistingGame(Index - 1)) { const FFlareSaveSlotInfo& SaveSlotInfo = SaveSlots[Index - 1]; FString CompanyString = SaveSlotInfo.CompanyName.ToString(); FString ShipString = FString::FromInt(SaveSlotInfo.CompanyShipCount) + " " + LOCTEXT("Ships", "ships").ToString(); FString MoneyString = FString::FromInt(SaveSlotInfo.CompanyMoney) + " " + LOCTEXT("Credits", "credits").ToString(); return FText::FromString(CompanyString + "\n" + ShipString + "\n" + MoneyString + "\n"); } else { return FText::FromString("\n\n\n"); } } const FSlateBrush* SFlareMainMenu::GetSaveIcon(int32 Index) const { return (IsExistingGame(Index - 1) ? &SaveSlots[Index - 1].EmblemBrush : FFlareStyleSet::GetIcon("HeliumRain")); } EVisibility SFlareMainMenu::GetDeleteButtonVisibility(int32 Index) const { return (IsExistingGame(Index - 1) ? EVisibility::Visible : EVisibility::Collapsed); } FText SFlareMainMenu::GetButtonText(int32 Index) const { return (IsExistingGame(Index - 1) ? LOCTEXT("Load", "Load game") : LOCTEXT("Create", "New game")); } const FSlateBrush* SFlareMainMenu::GetButtonIcon(int32 Index) const { return (IsExistingGame(Index - 1) ? FFlareStyleSet::GetIcon("Load") : FFlareStyleSet::GetIcon("New")); } void SFlareMainMenu::OnOpenSlot(TSharedPtr<int32> Index) { AFlarePlayerController* PC = MenuManager->GetPC(); AFlareGame* Game = MenuManager->GetGame(); if (PC && Game) { // Load the world bool WorldLoaded = Game->LoadWorld(PC, *Index); if (!WorldLoaded) { Game->CreateWorld(PC); } // Go to the ship MenuManager->OpenMenu(EFlareMenu::MENU_FlyShip, PC->GetShipPawn()); } } void SFlareMainMenu::OnDeleteSlot(TSharedPtr<int32> Index) { AFlareGame::DeleteSaveFile(*Index); UpdateSaveSlots(); } void SFlareMainMenu::OnOpenSettings() { MenuManager->OpenMenu(EFlareMenu::MENU_Settings); } void SFlareMainMenu::OnQuitGame() { MenuManager->OpenMenu(EFlareMenu::MENU_Quit); } /*---------------------------------------------------- Helpers ----------------------------------------------------*/ void SFlareMainMenu::UpdateSaveSlots() { // Setup SaveSlots.Empty(); FVector2D EmblemSize = 128 * FVector2D::UnitVector; UMaterial* BaseEmblemMaterial = Cast<UMaterial>(FFlareStyleSet::GetIcon("CompanyEmblem")->GetResourceObject()); // Get all saves for (int32 Index = 1; Index <= SaveSlotCount; Index++) { FFlareSaveSlotInfo SaveSlotInfo; SaveSlotInfo.EmblemBrush.ImageSize = EmblemSize; UFlareSaveGame* Save = AFlareGame::LoadSaveFile(Index); SaveSlotInfo.Save = Save; if (Save) { // Basic setup AFlareGame* Game = MenuManager->GetPC()->GetGame(); FFlareCompanySave& Company = Save->CompanyData[0]; UFlareCustomizationCatalog* Catalog = Game->GetCustomizationCatalog(); SaveSlotInfo.CompanyName = LOCTEXT("Company", "Mining Syndicate"); FLOGV("SFlareMainMenu::UpdateSaveSlots : found valid save data in slot %d", Index); // Count player ships SaveSlotInfo.CompanyShipCount = 0; for (int32 Index = 0; Index < Save->ShipData.Num(); Index++) { const FFlareSpacecraftSave& Spacecraft = Save->ShipData[Index]; if (Spacecraft.CompanyIdentifier == Save->PlayerData.CompanyIdentifier) { SaveSlotInfo.CompanyShipCount++; } } // Money SaveSlotInfo.CompanyMoney = 50000; // Emblem material SaveSlotInfo.Emblem = UMaterialInstanceDynamic::Create(BaseEmblemMaterial, Game->GetWorld()); SaveSlotInfo.Emblem->SetVectorParameterValue("BasePaintColor", Catalog->GetColor(Company.CustomizationBasePaintColorIndex)); SaveSlotInfo.Emblem->SetVectorParameterValue("PaintColor", Catalog->GetColor(Company.CustomizationPaintColorIndex)); SaveSlotInfo.Emblem->SetVectorParameterValue("OverlayColor", Catalog->GetColor(Company.CustomizationOverlayColorIndex)); SaveSlotInfo.Emblem->SetVectorParameterValue("GlowColor", Catalog->GetColor(Company.CustomizationLightColorIndex)); // Create the brush dynamically SaveSlotInfo.EmblemBrush.SetResourceObject(SaveSlotInfo.Emblem); } else { SaveSlotInfo.Save = NULL; SaveSlotInfo.Emblem = NULL; SaveSlotInfo.EmblemBrush = FSlateNoResource(); SaveSlotInfo.CompanyShipCount = 0; SaveSlotInfo.CompanyMoney = 0; SaveSlotInfo.CompanyName = FText::FromString(""); } SaveSlots.Add(SaveSlotInfo); } FLOG("SFlareMainMenu::UpdateSaveSlots : all slots found"); Initialized = true; } bool SFlareMainMenu::IsExistingGame(int32 Index) const { return Initialized && Index < SaveSlots.Num() && SaveSlots[Index].Save; } #undef LOCTEXT_NAMESPACE <commit_msg>Fix shadow variable build error on Linux<commit_after> #include "../../Flare.h" #include "FlareMainMenu.h" #include "../../Game/FlareGame.h" #include "../../Game/FlareSaveGame.h" #include "../../Player/FlareMenuPawn.h" #include "../../Player/FlareMenuManager.h" #include "../../Player/FlarePlayerController.h" #define LOCTEXT_NAMESPACE "FlareMainMenu" /*---------------------------------------------------- Construct ----------------------------------------------------*/ void SFlareMainMenu::Construct(const FArguments& InArgs) { // Data MenuManager = InArgs._MenuManager; const FFlareStyleCatalog& Theme = FFlareStyleSet::GetDefaultTheme(); AFlarePlayerController* PC = MenuManager->GetPC(); SaveSlotCount = 3; Initialized = false; // Build structure ChildSlot .HAlign(HAlign_Fill) .VAlign(VAlign_Fill) [ SNew(SVerticalBox) + SVerticalBox::Slot() .AutoHeight() .HAlign(HAlign_Fill) .VAlign(VAlign_Center) .Padding(Theme.ContentPadding) [ SNew(SHorizontalBox) // Icon + SHorizontalBox::Slot() .AutoWidth() [ SNew(SImage) .Image(FFlareStyleSet::GetIcon("HeliumRain")) ] // Title + SHorizontalBox::Slot() .VAlign(VAlign_Center) .Padding(Theme.ContentPadding) [ SNew(STextBlock) .TextStyle(&Theme.TitleFont) .Text(LOCTEXT("MainMenu", "HELIUM RAIN")) ] // Settings + SHorizontalBox::Slot() .HAlign(HAlign_Right) .VAlign(VAlign_Bottom) .Padding(Theme.TitleButtonPadding) .AutoWidth() [ SNew(SFlareRoundButton) .Text(LOCTEXT("Settings", "Settings")) .Icon(AFlareMenuManager::GetMenuIcon(EFlareMenu::MENU_Settings, true)) .OnClicked(this, &SFlareMainMenu::OnOpenSettings) ] // Quit + SHorizontalBox::Slot() .HAlign(HAlign_Right) .VAlign(VAlign_Bottom) .Padding(Theme.TitleButtonPadding) .AutoWidth() [ SNew(SFlareRoundButton) .Text(LOCTEXT("Quit", "Quit game")) .Icon(AFlareMenuManager::GetMenuIcon(EFlareMenu::MENU_Quit, true)) .OnClicked(this, &SFlareMainMenu::OnQuitGame) ] ] // Separator + SVerticalBox::Slot() .AutoHeight() .Padding(FMargin(200, 40)) [ SNew(SImage).Image(&Theme.SeparatorBrush) ] // Save slots + SVerticalBox::Slot() [ SAssignNew(SaveBox, SHorizontalBox) ] ]; // Add save slots for (int32 Index = 1; Index <= SaveSlotCount; Index++) { TSharedPtr<int32> IndexPtr(new int32(Index)); SaveBox->AddSlot() .HAlign(HAlign_Center) .VAlign(VAlign_Top) [ SNew(SVerticalBox) // Slot N° + SVerticalBox::Slot() .AutoHeight() .Padding(Theme.TitlePadding) [ SNew(STextBlock) .TextStyle(&Theme.TitleFont) .Text(FText::FromString(FString::FromInt(Index) + "/")) ] // Company emblem + SVerticalBox::Slot() .AutoHeight() .Padding(Theme.ContentPadding) [ SNew(SHorizontalBox) + SHorizontalBox::Slot() .HAlign(HAlign_Center) [ SNew(SImage) .Image(this, &SFlareMainMenu::GetSaveIcon, Index) ] ] // Description + SVerticalBox::Slot() .AutoHeight() [ SNew(STextBlock) .TextStyle(&Theme.TextFont) .Text(this, &SFlareMainMenu::GetText, Index) ] // Launch + SVerticalBox::Slot() .HAlign(HAlign_Left) .VAlign(VAlign_Center) .AutoHeight() .Padding(Theme.SmallContentPadding) [ SNew(SFlareButton) .Text(this, &SFlareMainMenu::GetButtonText, Index) .Icon(this, &SFlareMainMenu::GetButtonIcon, Index) .OnClicked(this, &SFlareMainMenu::OnOpenSlot, IndexPtr) .Width(5) .Height(1) ] // Delete + SVerticalBox::Slot() .HAlign(HAlign_Left) .VAlign(VAlign_Center) .AutoHeight() .Padding(Theme.SmallContentPadding) [ SNew(SFlareButton) .Text(LOCTEXT("Delete", "Delete game")) .Icon(FFlareStyleSet::GetIcon("Delete")) .OnClicked(this, &SFlareMainMenu::OnDeleteSlot, IndexPtr) .Width(5) .Height(1) .Visibility(this, &SFlareMainMenu::GetDeleteButtonVisibility, Index) ] ]; } } /*---------------------------------------------------- Interaction ----------------------------------------------------*/ void SFlareMainMenu::Setup() { SetEnabled(false); SetVisibility(EVisibility::Hidden); } void SFlareMainMenu::Enter() { FLOG("SFlareMainMenu::Enter"); UpdateSaveSlots(); SetEnabled(true); SetVisibility(EVisibility::Visible); } void SFlareMainMenu::Exit() { SetEnabled(false); Initialized = false; SaveSlots.Empty(); SetVisibility(EVisibility::Hidden); } /*---------------------------------------------------- Callbacks ----------------------------------------------------*/ FText SFlareMainMenu::GetText(int32 Index) const { if (IsExistingGame(Index - 1)) { const FFlareSaveSlotInfo& SaveSlotInfo = SaveSlots[Index - 1]; FString CompanyString = SaveSlotInfo.CompanyName.ToString(); FString ShipString = FString::FromInt(SaveSlotInfo.CompanyShipCount) + " " + LOCTEXT("Ships", "ships").ToString(); FString MoneyString = FString::FromInt(SaveSlotInfo.CompanyMoney) + " " + LOCTEXT("Credits", "credits").ToString(); return FText::FromString(CompanyString + "\n" + ShipString + "\n" + MoneyString + "\n"); } else { return FText::FromString("\n\n\n"); } } const FSlateBrush* SFlareMainMenu::GetSaveIcon(int32 Index) const { return (IsExistingGame(Index - 1) ? &SaveSlots[Index - 1].EmblemBrush : FFlareStyleSet::GetIcon("HeliumRain")); } EVisibility SFlareMainMenu::GetDeleteButtonVisibility(int32 Index) const { return (IsExistingGame(Index - 1) ? EVisibility::Visible : EVisibility::Collapsed); } FText SFlareMainMenu::GetButtonText(int32 Index) const { return (IsExistingGame(Index - 1) ? LOCTEXT("Load", "Load game") : LOCTEXT("Create", "New game")); } const FSlateBrush* SFlareMainMenu::GetButtonIcon(int32 Index) const { return (IsExistingGame(Index - 1) ? FFlareStyleSet::GetIcon("Load") : FFlareStyleSet::GetIcon("New")); } void SFlareMainMenu::OnOpenSlot(TSharedPtr<int32> Index) { AFlarePlayerController* PC = MenuManager->GetPC(); AFlareGame* Game = MenuManager->GetGame(); if (PC && Game) { // Load the world bool WorldLoaded = Game->LoadWorld(PC, *Index); if (!WorldLoaded) { Game->CreateWorld(PC); } // Go to the ship MenuManager->OpenMenu(EFlareMenu::MENU_FlyShip, PC->GetShipPawn()); } } void SFlareMainMenu::OnDeleteSlot(TSharedPtr<int32> Index) { AFlareGame::DeleteSaveFile(*Index); UpdateSaveSlots(); } void SFlareMainMenu::OnOpenSettings() { MenuManager->OpenMenu(EFlareMenu::MENU_Settings); } void SFlareMainMenu::OnQuitGame() { MenuManager->OpenMenu(EFlareMenu::MENU_Quit); } /*---------------------------------------------------- Helpers ----------------------------------------------------*/ void SFlareMainMenu::UpdateSaveSlots() { // Setup SaveSlots.Empty(); FVector2D EmblemSize = 128 * FVector2D::UnitVector; UMaterial* BaseEmblemMaterial = Cast<UMaterial>(FFlareStyleSet::GetIcon("CompanyEmblem")->GetResourceObject()); // Get all saves for (int32 Index = 1; Index <= SaveSlotCount; Index++) { FFlareSaveSlotInfo SaveSlotInfo; SaveSlotInfo.EmblemBrush.ImageSize = EmblemSize; UFlareSaveGame* Save = AFlareGame::LoadSaveFile(Index); SaveSlotInfo.Save = Save; if (Save) { // Basic setup AFlareGame* Game = MenuManager->GetPC()->GetGame(); FFlareCompanySave& Company = Save->CompanyData[0]; UFlareCustomizationCatalog* Catalog = Game->GetCustomizationCatalog(); SaveSlotInfo.CompanyName = LOCTEXT("Company", "Mining Syndicate"); FLOGV("SFlareMainMenu::UpdateSaveSlots : found valid save data in slot %d", Index); // Count player ships SaveSlotInfo.CompanyShipCount = 0; for (int32 ShipIndex = 0; ShipIndex < Save->ShipData.Num(); ShipIndex++) { const FFlareSpacecraftSave& Spacecraft = Save->ShipData[ShipIndex]; if (Spacecraft.CompanyIdentifier == Save->PlayerData.CompanyIdentifier) { SaveSlotInfo.CompanyShipCount++; } } // Money SaveSlotInfo.CompanyMoney = 50000; // Emblem material SaveSlotInfo.Emblem = UMaterialInstanceDynamic::Create(BaseEmblemMaterial, Game->GetWorld()); SaveSlotInfo.Emblem->SetVectorParameterValue("BasePaintColor", Catalog->GetColor(Company.CustomizationBasePaintColorIndex)); SaveSlotInfo.Emblem->SetVectorParameterValue("PaintColor", Catalog->GetColor(Company.CustomizationPaintColorIndex)); SaveSlotInfo.Emblem->SetVectorParameterValue("OverlayColor", Catalog->GetColor(Company.CustomizationOverlayColorIndex)); SaveSlotInfo.Emblem->SetVectorParameterValue("GlowColor", Catalog->GetColor(Company.CustomizationLightColorIndex)); // Create the brush dynamically SaveSlotInfo.EmblemBrush.SetResourceObject(SaveSlotInfo.Emblem); } else { SaveSlotInfo.Save = NULL; SaveSlotInfo.Emblem = NULL; SaveSlotInfo.EmblemBrush = FSlateNoResource(); SaveSlotInfo.CompanyShipCount = 0; SaveSlotInfo.CompanyMoney = 0; SaveSlotInfo.CompanyName = FText::FromString(""); } SaveSlots.Add(SaveSlotInfo); } FLOG("SFlareMainMenu::UpdateSaveSlots : all slots found"); Initialized = true; } bool SFlareMainMenu::IsExistingGame(int32 Index) const { return Initialized && Index < SaveSlots.Num() && SaveSlots[Index].Save; } #undef LOCTEXT_NAMESPACE <|endoftext|>
<commit_before>//===- llvm/unittest/ADT/SmallVectorMap.cpp ---------------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // SmallVector unit tests. // //===----------------------------------------------------------------------===// #include "gtest/gtest.h" #include "llvm/ADT/SmallVector.h" #include <stdarg.h> using namespace llvm; namespace { /// A helper class that counts the total number of constructor and /// destructor calls. class Constructable { private: static int numConstructorCalls; static int numDestructorCalls; static int numAssignmentCalls; int value; public: Constructable() : value(0) { ++numConstructorCalls; } Constructable(int val) : value(val) { ++numConstructorCalls; } Constructable(const Constructable & src) { value = src.value; ++numConstructorCalls; } ~Constructable() { ++numDestructorCalls; } Constructable & operator=(const Constructable & src) { value = src.value; ++numAssignmentCalls; return *this; } int getValue() const { return abs(value); } static void reset() { numConstructorCalls = 0; numDestructorCalls = 0; numAssignmentCalls = 0; } static int getNumConstructorCalls() { return numConstructorCalls; } static int getNumDestructorCalls() { return numDestructorCalls; } friend bool operator==(const Constructable & c0, const Constructable & c1) { return c0.getValue() == c1.getValue(); } friend bool operator!=(const Constructable & c0, const Constructable & c1) { return c0.getValue() != c1.getValue(); } }; int Constructable::numConstructorCalls; int Constructable::numDestructorCalls; int Constructable::numAssignmentCalls; // Test fixture class class SmallVectorTest : public testing::Test { protected: typedef SmallVector<Constructable, 4> VectorType; VectorType theVector; VectorType otherVector; void SetUp() { Constructable::reset(); } void assertEmpty(VectorType & v) { // Size tests EXPECT_EQ(0u, v.size()); EXPECT_TRUE(v.empty()); // Iterator tests EXPECT_TRUE(v.begin() == v.end()); } // Assert that theVector contains the specified values, in order. void assertValuesInOrder(VectorType & v, size_t size, ...) { EXPECT_EQ(size, v.size()); va_list ap; va_start(ap, size); for (size_t i = 0; i < size; ++i) { int value = va_arg(ap, int); EXPECT_EQ(value, v[i].getValue()); } va_end(ap); } // Generate a sequence of values to initialize the vector. void makeSequence(VectorType & v, int start, int end) { for (int i = start; i <= end; ++i) { v.push_back(Constructable(i)); } } }; // New vector test. TEST_F(SmallVectorTest, EmptyVectorTest) { SCOPED_TRACE("EmptyVectorTest"); assertEmpty(theVector); EXPECT_TRUE(theVector.rbegin() == theVector.rend()); EXPECT_EQ(0, Constructable::getNumConstructorCalls()); EXPECT_EQ(0, Constructable::getNumDestructorCalls()); } // Simple insertions and deletions. TEST_F(SmallVectorTest, PushPopTest) { SCOPED_TRACE("PushPopTest"); // Push an element theVector.push_back(Constructable(1)); // Size tests assertValuesInOrder(theVector, 1u, 1); EXPECT_FALSE(theVector.begin() == theVector.end()); EXPECT_FALSE(theVector.empty()); // Push another element theVector.push_back(Constructable(2)); assertValuesInOrder(theVector, 2u, 1, 2); // Pop one element theVector.pop_back(); assertValuesInOrder(theVector, 1u, 1); // Pop another element theVector.pop_back(); assertEmpty(theVector); // Check number of constructor calls. Should be 2 for each list element, // one for the argument to push_back, and one for the list element itself. EXPECT_EQ(4, Constructable::getNumConstructorCalls()); EXPECT_EQ(4, Constructable::getNumDestructorCalls()); } // Clear test. TEST_F(SmallVectorTest, ClearTest) { SCOPED_TRACE("ClearTest"); makeSequence(theVector, 1, 2); theVector.clear(); assertEmpty(theVector); EXPECT_EQ(4, Constructable::getNumConstructorCalls()); EXPECT_EQ(4, Constructable::getNumDestructorCalls()); } // Resize smaller test. TEST_F(SmallVectorTest, ResizeShrinkTest) { SCOPED_TRACE("ResizeShrinkTest"); makeSequence(theVector, 1, 3); theVector.resize(1); assertValuesInOrder(theVector, 1u, 1); EXPECT_EQ(6, Constructable::getNumConstructorCalls()); EXPECT_EQ(5, Constructable::getNumDestructorCalls()); } // Resize bigger test. TEST_F(SmallVectorTest, ResizeGrowTest) { SCOPED_TRACE("ResizeGrowTest"); theVector.resize(2); // XXX: I don't know where the extra construct/destruct is coming from. EXPECT_EQ(3, Constructable::getNumConstructorCalls()); EXPECT_EQ(1, Constructable::getNumDestructorCalls()); EXPECT_EQ(2u, theVector.size()); } // Resize with fill value. TEST_F(SmallVectorTest, ResizeFillTest) { SCOPED_TRACE("ResizeFillTest"); theVector.resize(3, Constructable(77)); assertValuesInOrder(theVector, 3u, 77, 77, 77); } // Overflow past fixed size. TEST_F(SmallVectorTest, OverflowTest) { SCOPED_TRACE("OverflowTest"); // Push more elements than the fixed size makeSequence(theVector, 1, 10); // test size and values EXPECT_EQ(10u, theVector.size()); for (int i = 0; i < 10; ++i) { EXPECT_EQ(i+1, theVector[i].getValue()); } // Now resize back to fixed size theVector.resize(1); assertValuesInOrder(theVector, 1u, 1); } // Iteration tests. TEST_F(SmallVectorTest, IterationTest) { makeSequence(theVector, 1, 2); // Forward Iteration VectorType::iterator it = theVector.begin(); EXPECT_TRUE(*it == theVector.front()); EXPECT_TRUE(*it == theVector[0]); EXPECT_EQ(1, it->getValue()); ++it; EXPECT_TRUE(*it == theVector[1]); EXPECT_TRUE(*it == theVector.back()); EXPECT_EQ(2, it->getValue()); ++it; EXPECT_TRUE(it == theVector.end()); --it; EXPECT_TRUE(*it == theVector[1]); EXPECT_EQ(2, it->getValue()); --it; EXPECT_TRUE(*it == theVector[0]); EXPECT_EQ(1, it->getValue()); // Reverse Iteration VectorType::reverse_iterator rit = theVector.rbegin(); EXPECT_TRUE(*rit == theVector[1]); EXPECT_EQ(2, rit->getValue()); ++rit; EXPECT_TRUE(*rit == theVector[0]); EXPECT_EQ(1, rit->getValue()); ++rit; EXPECT_TRUE(rit == theVector.rend()); --rit; EXPECT_TRUE(*rit == theVector[0]); EXPECT_EQ(1, rit->getValue()); --rit; EXPECT_TRUE(*rit == theVector[1]); EXPECT_EQ(2, rit->getValue()); } // Swap test. TEST_F(SmallVectorTest, SwapTest) { SCOPED_TRACE("SwapTest"); makeSequence(theVector, 1, 2); std::swap(theVector, otherVector); assertEmpty(theVector); assertValuesInOrder(otherVector, 2u, 1, 2); } // Append test TEST_F(SmallVectorTest, AppendTest) { SCOPED_TRACE("AppendTest"); makeSequence(otherVector, 2, 3); theVector.push_back(Constructable(1)); theVector.append(otherVector.begin(), otherVector.end()); assertValuesInOrder(theVector, 3u, 1, 2, 3); } // Append repeated test TEST_F(SmallVectorTest, AppendRepeatedTest) { SCOPED_TRACE("AppendRepeatedTest"); theVector.push_back(Constructable(1)); theVector.append(2, Constructable(77)); assertValuesInOrder(theVector, 3u, 1, 77, 77); } // Assign test TEST_F(SmallVectorTest, AssignTest) { SCOPED_TRACE("AssignTest"); theVector.push_back(Constructable(1)); theVector.assign(2, Constructable(77)); assertValuesInOrder(theVector, 2u, 77, 77); } // Erase a single element TEST_F(SmallVectorTest, EraseTest) { SCOPED_TRACE("EraseTest"); makeSequence(theVector, 1, 3); theVector.erase(theVector.begin()); assertValuesInOrder(theVector, 2u, 2, 3); } // Erase a range of elements TEST_F(SmallVectorTest, EraseRangeTest) { SCOPED_TRACE("EraseRangeTest"); makeSequence(theVector, 1, 3); theVector.erase(theVector.begin(), theVector.begin() + 2); assertValuesInOrder(theVector, 1u, 3); } // Insert a single element. TEST_F(SmallVectorTest, InsertTest) { SCOPED_TRACE("InsertTest"); makeSequence(theVector, 1, 3); theVector.insert(theVector.begin() + 1, Constructable(77)); assertValuesInOrder(theVector, 4u, 1, 77, 2, 3); } // Insert repeated elements. TEST_F(SmallVectorTest, InsertRepeatedTest) { SCOPED_TRACE("InsertRepeatedTest"); makeSequence(theVector, 1, 3); theVector.insert(theVector.begin() + 1, 3, Constructable(77)); assertValuesInOrder(theVector, 6u, 1, 77, 77, 77, 2, 3); } // Insert range. TEST_F(SmallVectorTest, InsertRangeTest) { SCOPED_TRACE("InsertRepeatedTest"); makeSequence(theVector, 1, 3); theVector.insert(theVector.begin() + 1, 3, Constructable(77)); assertValuesInOrder(theVector, 6u, 1, 77, 77, 77, 2, 3); } // Comparison tests. TEST_F(SmallVectorTest, ComparisonTest) { SCOPED_TRACE("ComparisonTest"); makeSequence(theVector, 1, 3); makeSequence(otherVector, 1, 3); EXPECT_TRUE(theVector == otherVector); EXPECT_FALSE(theVector != otherVector); otherVector.clear(); makeSequence(otherVector, 2, 4); EXPECT_FALSE(theVector == otherVector); EXPECT_TRUE(theVector != otherVector); } // Constant vector tests. TEST_F(SmallVectorTest, ConstVectorTest) { const VectorType constVector; EXPECT_EQ(0u, constVector.size()); EXPECT_TRUE(constVector.empty()); EXPECT_TRUE(constVector.begin() == constVector.end()); } } <commit_msg>Fix naming of file.<commit_after>//===- llvm/unittest/ADT/SmallVectorTest.cpp ------------------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // SmallVector unit tests. // //===----------------------------------------------------------------------===// #include "gtest/gtest.h" #include "llvm/ADT/SmallVector.h" #include <stdarg.h> using namespace llvm; namespace { /// A helper class that counts the total number of constructor and /// destructor calls. class Constructable { private: static int numConstructorCalls; static int numDestructorCalls; static int numAssignmentCalls; int value; public: Constructable() : value(0) { ++numConstructorCalls; } Constructable(int val) : value(val) { ++numConstructorCalls; } Constructable(const Constructable & src) { value = src.value; ++numConstructorCalls; } ~Constructable() { ++numDestructorCalls; } Constructable & operator=(const Constructable & src) { value = src.value; ++numAssignmentCalls; return *this; } int getValue() const { return abs(value); } static void reset() { numConstructorCalls = 0; numDestructorCalls = 0; numAssignmentCalls = 0; } static int getNumConstructorCalls() { return numConstructorCalls; } static int getNumDestructorCalls() { return numDestructorCalls; } friend bool operator==(const Constructable & c0, const Constructable & c1) { return c0.getValue() == c1.getValue(); } friend bool operator!=(const Constructable & c0, const Constructable & c1) { return c0.getValue() != c1.getValue(); } }; int Constructable::numConstructorCalls; int Constructable::numDestructorCalls; int Constructable::numAssignmentCalls; // Test fixture class class SmallVectorTest : public testing::Test { protected: typedef SmallVector<Constructable, 4> VectorType; VectorType theVector; VectorType otherVector; void SetUp() { Constructable::reset(); } void assertEmpty(VectorType & v) { // Size tests EXPECT_EQ(0u, v.size()); EXPECT_TRUE(v.empty()); // Iterator tests EXPECT_TRUE(v.begin() == v.end()); } // Assert that theVector contains the specified values, in order. void assertValuesInOrder(VectorType & v, size_t size, ...) { EXPECT_EQ(size, v.size()); va_list ap; va_start(ap, size); for (size_t i = 0; i < size; ++i) { int value = va_arg(ap, int); EXPECT_EQ(value, v[i].getValue()); } va_end(ap); } // Generate a sequence of values to initialize the vector. void makeSequence(VectorType & v, int start, int end) { for (int i = start; i <= end; ++i) { v.push_back(Constructable(i)); } } }; // New vector test. TEST_F(SmallVectorTest, EmptyVectorTest) { SCOPED_TRACE("EmptyVectorTest"); assertEmpty(theVector); EXPECT_TRUE(theVector.rbegin() == theVector.rend()); EXPECT_EQ(0, Constructable::getNumConstructorCalls()); EXPECT_EQ(0, Constructable::getNumDestructorCalls()); } // Simple insertions and deletions. TEST_F(SmallVectorTest, PushPopTest) { SCOPED_TRACE("PushPopTest"); // Push an element theVector.push_back(Constructable(1)); // Size tests assertValuesInOrder(theVector, 1u, 1); EXPECT_FALSE(theVector.begin() == theVector.end()); EXPECT_FALSE(theVector.empty()); // Push another element theVector.push_back(Constructable(2)); assertValuesInOrder(theVector, 2u, 1, 2); // Pop one element theVector.pop_back(); assertValuesInOrder(theVector, 1u, 1); // Pop another element theVector.pop_back(); assertEmpty(theVector); // Check number of constructor calls. Should be 2 for each list element, // one for the argument to push_back, and one for the list element itself. EXPECT_EQ(4, Constructable::getNumConstructorCalls()); EXPECT_EQ(4, Constructable::getNumDestructorCalls()); } // Clear test. TEST_F(SmallVectorTest, ClearTest) { SCOPED_TRACE("ClearTest"); makeSequence(theVector, 1, 2); theVector.clear(); assertEmpty(theVector); EXPECT_EQ(4, Constructable::getNumConstructorCalls()); EXPECT_EQ(4, Constructable::getNumDestructorCalls()); } // Resize smaller test. TEST_F(SmallVectorTest, ResizeShrinkTest) { SCOPED_TRACE("ResizeShrinkTest"); makeSequence(theVector, 1, 3); theVector.resize(1); assertValuesInOrder(theVector, 1u, 1); EXPECT_EQ(6, Constructable::getNumConstructorCalls()); EXPECT_EQ(5, Constructable::getNumDestructorCalls()); } // Resize bigger test. TEST_F(SmallVectorTest, ResizeGrowTest) { SCOPED_TRACE("ResizeGrowTest"); theVector.resize(2); // XXX: I don't know where the extra construct/destruct is coming from. EXPECT_EQ(3, Constructable::getNumConstructorCalls()); EXPECT_EQ(1, Constructable::getNumDestructorCalls()); EXPECT_EQ(2u, theVector.size()); } // Resize with fill value. TEST_F(SmallVectorTest, ResizeFillTest) { SCOPED_TRACE("ResizeFillTest"); theVector.resize(3, Constructable(77)); assertValuesInOrder(theVector, 3u, 77, 77, 77); } // Overflow past fixed size. TEST_F(SmallVectorTest, OverflowTest) { SCOPED_TRACE("OverflowTest"); // Push more elements than the fixed size makeSequence(theVector, 1, 10); // test size and values EXPECT_EQ(10u, theVector.size()); for (int i = 0; i < 10; ++i) { EXPECT_EQ(i+1, theVector[i].getValue()); } // Now resize back to fixed size theVector.resize(1); assertValuesInOrder(theVector, 1u, 1); } // Iteration tests. TEST_F(SmallVectorTest, IterationTest) { makeSequence(theVector, 1, 2); // Forward Iteration VectorType::iterator it = theVector.begin(); EXPECT_TRUE(*it == theVector.front()); EXPECT_TRUE(*it == theVector[0]); EXPECT_EQ(1, it->getValue()); ++it; EXPECT_TRUE(*it == theVector[1]); EXPECT_TRUE(*it == theVector.back()); EXPECT_EQ(2, it->getValue()); ++it; EXPECT_TRUE(it == theVector.end()); --it; EXPECT_TRUE(*it == theVector[1]); EXPECT_EQ(2, it->getValue()); --it; EXPECT_TRUE(*it == theVector[0]); EXPECT_EQ(1, it->getValue()); // Reverse Iteration VectorType::reverse_iterator rit = theVector.rbegin(); EXPECT_TRUE(*rit == theVector[1]); EXPECT_EQ(2, rit->getValue()); ++rit; EXPECT_TRUE(*rit == theVector[0]); EXPECT_EQ(1, rit->getValue()); ++rit; EXPECT_TRUE(rit == theVector.rend()); --rit; EXPECT_TRUE(*rit == theVector[0]); EXPECT_EQ(1, rit->getValue()); --rit; EXPECT_TRUE(*rit == theVector[1]); EXPECT_EQ(2, rit->getValue()); } // Swap test. TEST_F(SmallVectorTest, SwapTest) { SCOPED_TRACE("SwapTest"); makeSequence(theVector, 1, 2); std::swap(theVector, otherVector); assertEmpty(theVector); assertValuesInOrder(otherVector, 2u, 1, 2); } // Append test TEST_F(SmallVectorTest, AppendTest) { SCOPED_TRACE("AppendTest"); makeSequence(otherVector, 2, 3); theVector.push_back(Constructable(1)); theVector.append(otherVector.begin(), otherVector.end()); assertValuesInOrder(theVector, 3u, 1, 2, 3); } // Append repeated test TEST_F(SmallVectorTest, AppendRepeatedTest) { SCOPED_TRACE("AppendRepeatedTest"); theVector.push_back(Constructable(1)); theVector.append(2, Constructable(77)); assertValuesInOrder(theVector, 3u, 1, 77, 77); } // Assign test TEST_F(SmallVectorTest, AssignTest) { SCOPED_TRACE("AssignTest"); theVector.push_back(Constructable(1)); theVector.assign(2, Constructable(77)); assertValuesInOrder(theVector, 2u, 77, 77); } // Erase a single element TEST_F(SmallVectorTest, EraseTest) { SCOPED_TRACE("EraseTest"); makeSequence(theVector, 1, 3); theVector.erase(theVector.begin()); assertValuesInOrder(theVector, 2u, 2, 3); } // Erase a range of elements TEST_F(SmallVectorTest, EraseRangeTest) { SCOPED_TRACE("EraseRangeTest"); makeSequence(theVector, 1, 3); theVector.erase(theVector.begin(), theVector.begin() + 2); assertValuesInOrder(theVector, 1u, 3); } // Insert a single element. TEST_F(SmallVectorTest, InsertTest) { SCOPED_TRACE("InsertTest"); makeSequence(theVector, 1, 3); theVector.insert(theVector.begin() + 1, Constructable(77)); assertValuesInOrder(theVector, 4u, 1, 77, 2, 3); } // Insert repeated elements. TEST_F(SmallVectorTest, InsertRepeatedTest) { SCOPED_TRACE("InsertRepeatedTest"); makeSequence(theVector, 1, 3); theVector.insert(theVector.begin() + 1, 3, Constructable(77)); assertValuesInOrder(theVector, 6u, 1, 77, 77, 77, 2, 3); } // Insert range. TEST_F(SmallVectorTest, InsertRangeTest) { SCOPED_TRACE("InsertRepeatedTest"); makeSequence(theVector, 1, 3); theVector.insert(theVector.begin() + 1, 3, Constructable(77)); assertValuesInOrder(theVector, 6u, 1, 77, 77, 77, 2, 3); } // Comparison tests. TEST_F(SmallVectorTest, ComparisonTest) { SCOPED_TRACE("ComparisonTest"); makeSequence(theVector, 1, 3); makeSequence(otherVector, 1, 3); EXPECT_TRUE(theVector == otherVector); EXPECT_FALSE(theVector != otherVector); otherVector.clear(); makeSequence(otherVector, 2, 4); EXPECT_FALSE(theVector == otherVector); EXPECT_TRUE(theVector != otherVector); } // Constant vector tests. TEST_F(SmallVectorTest, ConstVectorTest) { const VectorType constVector; EXPECT_EQ(0u, constVector.size()); EXPECT_TRUE(constVector.empty()); EXPECT_TRUE(constVector.begin() == constVector.end()); } } <|endoftext|>
<commit_before>//===- unittest/Tooling/ToolingTest.cpp - Tooling unit tests --------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "clang/AST/ASTConsumer.h" #include "clang/AST/DeclCXX.h" #include "clang/AST/DeclGroup.h" #include "clang/Frontend/ASTUnit.h" #include "clang/Frontend/CompilerInstance.h" #include "clang/Frontend/FrontendAction.h" #include "clang/Frontend/FrontendActions.h" #include "clang/Tooling/CompilationDatabase.h" #include "clang/Tooling/Tooling.h" #include "llvm/ADT/STLExtras.h" #include "llvm/Config/config.h" #include "gtest/gtest.h" #include <string> namespace clang { namespace tooling { namespace { /// Takes an ast consumer and returns it from CreateASTConsumer. This only /// works with single translation unit compilations. class TestAction : public clang::ASTFrontendAction { public: /// Takes ownership of TestConsumer. explicit TestAction(clang::ASTConsumer *TestConsumer) : TestConsumer(TestConsumer) {} protected: virtual clang::ASTConsumer* CreateASTConsumer( clang::CompilerInstance& compiler, StringRef dummy) { /// TestConsumer will be deleted by the framework calling us. return TestConsumer; } private: clang::ASTConsumer * const TestConsumer; }; class FindTopLevelDeclConsumer : public clang::ASTConsumer { public: explicit FindTopLevelDeclConsumer(bool *FoundTopLevelDecl) : FoundTopLevelDecl(FoundTopLevelDecl) {} virtual bool HandleTopLevelDecl(clang::DeclGroupRef DeclGroup) { *FoundTopLevelDecl = true; return true; } private: bool * const FoundTopLevelDecl; }; } // end namespace TEST(runToolOnCode, FindsNoTopLevelDeclOnEmptyCode) { bool FoundTopLevelDecl = false; EXPECT_TRUE(runToolOnCode( new TestAction(new FindTopLevelDeclConsumer(&FoundTopLevelDecl)), "")); EXPECT_FALSE(FoundTopLevelDecl); } namespace { class FindClassDeclXConsumer : public clang::ASTConsumer { public: FindClassDeclXConsumer(bool *FoundClassDeclX) : FoundClassDeclX(FoundClassDeclX) {} virtual bool HandleTopLevelDecl(clang::DeclGroupRef GroupRef) { if (CXXRecordDecl* Record = dyn_cast<clang::CXXRecordDecl>( *GroupRef.begin())) { if (Record->getName() == "X") { *FoundClassDeclX = true; } } return true; } private: bool *FoundClassDeclX; }; bool FindClassDeclX(ASTUnit *AST) { for (std::vector<Decl *>::iterator i = AST->top_level_begin(), e = AST->top_level_end(); i != e; ++i) { if (CXXRecordDecl* Record = dyn_cast<clang::CXXRecordDecl>(*i)) { if (Record->getName() == "X") { return true; } } } return false; } } // end namespace TEST(runToolOnCode, FindsClassDecl) { bool FoundClassDeclX = false; EXPECT_TRUE(runToolOnCode(new TestAction( new FindClassDeclXConsumer(&FoundClassDeclX)), "class X;")); EXPECT_TRUE(FoundClassDeclX); FoundClassDeclX = false; EXPECT_TRUE(runToolOnCode(new TestAction( new FindClassDeclXConsumer(&FoundClassDeclX)), "class Y;")); EXPECT_FALSE(FoundClassDeclX); } TEST(buildASTFromCode, FindsClassDecl) { std::unique_ptr<ASTUnit> AST(buildASTFromCode("class X;")); ASSERT_TRUE(AST.get()); EXPECT_TRUE(FindClassDeclX(AST.get())); AST.reset(buildASTFromCode("class Y;")); ASSERT_TRUE(AST.get()); EXPECT_FALSE(FindClassDeclX(AST.get())); } TEST(newFrontendActionFactory, CreatesFrontendActionFactoryFromType) { std::unique_ptr<FrontendActionFactory> Factory( newFrontendActionFactory<SyntaxOnlyAction>()); std::unique_ptr<FrontendAction> Action(Factory->create()); EXPECT_TRUE(Action.get() != NULL); } struct IndependentFrontendActionCreator { ASTConsumer *newASTConsumer() { return new FindTopLevelDeclConsumer(NULL); } }; TEST(newFrontendActionFactory, CreatesFrontendActionFactoryFromFactoryType) { IndependentFrontendActionCreator Creator; std::unique_ptr<FrontendActionFactory> Factory( newFrontendActionFactory(&Creator)); std::unique_ptr<FrontendAction> Action(Factory->create()); EXPECT_TRUE(Action.get() != NULL); } TEST(ToolInvocation, TestMapVirtualFile) { IntrusiveRefCntPtr<clang::FileManager> Files( new clang::FileManager(clang::FileSystemOptions())); std::vector<std::string> Args; Args.push_back("tool-executable"); Args.push_back("-Idef"); Args.push_back("-fsyntax-only"); Args.push_back("test.cpp"); clang::tooling::ToolInvocation Invocation(Args, new SyntaxOnlyAction, Files.getPtr()); Invocation.mapVirtualFile("test.cpp", "#include <abc>\n"); Invocation.mapVirtualFile("def/abc", "\n"); EXPECT_TRUE(Invocation.run()); } TEST(ToolInvocation, TestVirtualModulesCompilation) { // FIXME: Currently, this only tests that we don't exit with an error if a // mapped module.map is found on the include path. In the future, expand this // test to run a full modules enabled compilation, so we make sure we can // rerun modules compilations with a virtual file system. IntrusiveRefCntPtr<clang::FileManager> Files( new clang::FileManager(clang::FileSystemOptions())); std::vector<std::string> Args; Args.push_back("tool-executable"); Args.push_back("-Idef"); Args.push_back("-fsyntax-only"); Args.push_back("test.cpp"); clang::tooling::ToolInvocation Invocation(Args, new SyntaxOnlyAction, Files.getPtr()); Invocation.mapVirtualFile("test.cpp", "#include <abc>\n"); Invocation.mapVirtualFile("def/abc", "\n"); // Add a module.map file in the include directory of our header, so we trigger // the module.map header search logic. Invocation.mapVirtualFile("def/module.map", "\n"); EXPECT_TRUE(Invocation.run()); } struct VerifyEndCallback : public SourceFileCallbacks { VerifyEndCallback() : BeginCalled(0), EndCalled(0), Matched(false) {} virtual bool handleBeginSource(CompilerInstance &CI, StringRef Filename) override { ++BeginCalled; return true; } virtual void handleEndSource() { ++EndCalled; } ASTConsumer *newASTConsumer() { return new FindTopLevelDeclConsumer(&Matched); } unsigned BeginCalled; unsigned EndCalled; bool Matched; }; #if !defined(LLVM_ON_WIN32) TEST(newFrontendActionFactory, InjectsSourceFileCallbacks) { VerifyEndCallback EndCallback; FixedCompilationDatabase Compilations("/", std::vector<std::string>()); std::vector<std::string> Sources; Sources.push_back("/a.cc"); Sources.push_back("/b.cc"); ClangTool Tool(Compilations, Sources); Tool.mapVirtualFile("/a.cc", "void a() {}"); Tool.mapVirtualFile("/b.cc", "void b() {}"); Tool.run(newFrontendActionFactory(&EndCallback, &EndCallback)); EXPECT_TRUE(EndCallback.Matched); EXPECT_EQ(2u, EndCallback.BeginCalled); EXPECT_EQ(2u, EndCallback.EndCalled); } #endif struct SkipBodyConsumer : public clang::ASTConsumer { /// Skip the 'skipMe' function. virtual bool shouldSkipFunctionBody(Decl *D) { FunctionDecl *F = dyn_cast<FunctionDecl>(D); return F && F->getNameAsString() == "skipMe"; } }; struct SkipBodyAction : public clang::ASTFrontendAction { virtual ASTConsumer *CreateASTConsumer(CompilerInstance &Compiler, StringRef) { Compiler.getFrontendOpts().SkipFunctionBodies = true; return new SkipBodyConsumer; } }; TEST(runToolOnCode, TestSkipFunctionBody) { EXPECT_TRUE(runToolOnCode(new SkipBodyAction, "int skipMe() { an_error_here }")); EXPECT_FALSE(runToolOnCode(new SkipBodyAction, "int skipMeNot() { an_error_here }")); } TEST(runToolOnCodeWithArgs, TestNoDepFile) { llvm::SmallString<32> DepFilePath; ASSERT_FALSE( llvm::sys::fs::createTemporaryFile("depfile", "d", DepFilePath)); std::vector<std::string> Args; Args.push_back("-MMD"); Args.push_back("-MT"); Args.push_back(DepFilePath.str()); Args.push_back("-MF"); Args.push_back(DepFilePath.str()); EXPECT_TRUE(runToolOnCodeWithArgs(new SkipBodyAction, "", Args)); EXPECT_FALSE(llvm::sys::fs::exists(DepFilePath.str())); EXPECT_FALSE(llvm::sys::fs::remove(DepFilePath.str())); } struct CheckSyntaxOnlyAdjuster: public ArgumentsAdjuster { bool &Found; bool &Ran; CheckSyntaxOnlyAdjuster(bool &Found, bool &Ran) : Found(Found), Ran(Ran) { } virtual CommandLineArguments Adjust(const CommandLineArguments &Args) override { Ran = true; for (unsigned I = 0, E = Args.size(); I != E; ++I) { if (Args[I] == "-fsyntax-only") { Found = true; break; } } return Args; } }; TEST(ClangToolTest, ArgumentAdjusters) { FixedCompilationDatabase Compilations("/", std::vector<std::string>()); ClangTool Tool(Compilations, std::vector<std::string>(1, "/a.cc")); Tool.mapVirtualFile("/a.cc", "void a() {}"); bool Found = false; bool Ran = false; Tool.appendArgumentsAdjuster(new CheckSyntaxOnlyAdjuster(Found, Ran)); Tool.run(newFrontendActionFactory<SyntaxOnlyAction>()); EXPECT_TRUE(Ran); EXPECT_TRUE(Found); Ran = Found = false; Tool.clearArgumentsAdjusters(); Tool.appendArgumentsAdjuster(new CheckSyntaxOnlyAdjuster(Found, Ran)); Tool.appendArgumentsAdjuster(new ClangSyntaxOnlyAdjuster()); Tool.run(newFrontendActionFactory<SyntaxOnlyAction>()); EXPECT_TRUE(Ran); EXPECT_FALSE(Found); } #ifndef LLVM_ON_WIN32 TEST(ClangToolTest, BuildASTs) { FixedCompilationDatabase Compilations("/", std::vector<std::string>()); std::vector<std::string> Sources; Sources.push_back("/a.cc"); Sources.push_back("/b.cc"); ClangTool Tool(Compilations, Sources); Tool.mapVirtualFile("/a.cc", "void a() {}"); Tool.mapVirtualFile("/b.cc", "void b() {}"); std::vector<ASTUnit *> ASTs; EXPECT_EQ(0, Tool.buildASTs(ASTs)); EXPECT_EQ(2u, ASTs.size()); llvm::DeleteContainerPointers(ASTs); } struct TestDiagnosticConsumer : public DiagnosticConsumer { TestDiagnosticConsumer() : NumDiagnosticsSeen(0) {} virtual void HandleDiagnostic(DiagnosticsEngine::Level DiagLevel, const Diagnostic &Info) { ++NumDiagnosticsSeen; } unsigned NumDiagnosticsSeen; }; TEST(ClangToolTest, InjectDiagnosticConsumer) { FixedCompilationDatabase Compilations("/", std::vector<std::string>()); ClangTool Tool(Compilations, std::vector<std::string>(1, "/a.cc")); Tool.mapVirtualFile("/a.cc", "int x = undeclared;"); TestDiagnosticConsumer Consumer; Tool.setDiagnosticConsumer(&Consumer); Tool.run(newFrontendActionFactory<SyntaxOnlyAction>()); EXPECT_EQ(1u, Consumer.NumDiagnosticsSeen); } TEST(ClangToolTest, InjectDiagnosticConsumerInBuildASTs) { FixedCompilationDatabase Compilations("/", std::vector<std::string>()); ClangTool Tool(Compilations, std::vector<std::string>(1, "/a.cc")); Tool.mapVirtualFile("/a.cc", "int x = undeclared;"); TestDiagnosticConsumer Consumer; Tool.setDiagnosticConsumer(&Consumer); std::vector<ASTUnit*> ASTs; Tool.buildASTs(ASTs); EXPECT_EQ(1u, ASTs.size()); EXPECT_EQ(1u, Consumer.NumDiagnosticsSeen); } #endif } // end namespace tooling } // end namespace clang <commit_msg>Fix four more test-only leaks found by LSan.<commit_after>//===- unittest/Tooling/ToolingTest.cpp - Tooling unit tests --------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "clang/AST/ASTConsumer.h" #include "clang/AST/DeclCXX.h" #include "clang/AST/DeclGroup.h" #include "clang/Frontend/ASTUnit.h" #include "clang/Frontend/CompilerInstance.h" #include "clang/Frontend/FrontendAction.h" #include "clang/Frontend/FrontendActions.h" #include "clang/Tooling/CompilationDatabase.h" #include "clang/Tooling/Tooling.h" #include "llvm/ADT/STLExtras.h" #include "llvm/Config/config.h" #include "gtest/gtest.h" #include <string> namespace clang { namespace tooling { namespace { /// Takes an ast consumer and returns it from CreateASTConsumer. This only /// works with single translation unit compilations. class TestAction : public clang::ASTFrontendAction { public: /// Takes ownership of TestConsumer. explicit TestAction(clang::ASTConsumer *TestConsumer) : TestConsumer(TestConsumer) {} protected: virtual clang::ASTConsumer* CreateASTConsumer( clang::CompilerInstance& compiler, StringRef dummy) { /// TestConsumer will be deleted by the framework calling us. return TestConsumer; } private: clang::ASTConsumer * const TestConsumer; }; class FindTopLevelDeclConsumer : public clang::ASTConsumer { public: explicit FindTopLevelDeclConsumer(bool *FoundTopLevelDecl) : FoundTopLevelDecl(FoundTopLevelDecl) {} virtual bool HandleTopLevelDecl(clang::DeclGroupRef DeclGroup) { *FoundTopLevelDecl = true; return true; } private: bool * const FoundTopLevelDecl; }; } // end namespace TEST(runToolOnCode, FindsNoTopLevelDeclOnEmptyCode) { bool FoundTopLevelDecl = false; EXPECT_TRUE(runToolOnCode( new TestAction(new FindTopLevelDeclConsumer(&FoundTopLevelDecl)), "")); EXPECT_FALSE(FoundTopLevelDecl); } namespace { class FindClassDeclXConsumer : public clang::ASTConsumer { public: FindClassDeclXConsumer(bool *FoundClassDeclX) : FoundClassDeclX(FoundClassDeclX) {} virtual bool HandleTopLevelDecl(clang::DeclGroupRef GroupRef) { if (CXXRecordDecl* Record = dyn_cast<clang::CXXRecordDecl>( *GroupRef.begin())) { if (Record->getName() == "X") { *FoundClassDeclX = true; } } return true; } private: bool *FoundClassDeclX; }; bool FindClassDeclX(ASTUnit *AST) { for (std::vector<Decl *>::iterator i = AST->top_level_begin(), e = AST->top_level_end(); i != e; ++i) { if (CXXRecordDecl* Record = dyn_cast<clang::CXXRecordDecl>(*i)) { if (Record->getName() == "X") { return true; } } } return false; } } // end namespace TEST(runToolOnCode, FindsClassDecl) { bool FoundClassDeclX = false; EXPECT_TRUE(runToolOnCode(new TestAction( new FindClassDeclXConsumer(&FoundClassDeclX)), "class X;")); EXPECT_TRUE(FoundClassDeclX); FoundClassDeclX = false; EXPECT_TRUE(runToolOnCode(new TestAction( new FindClassDeclXConsumer(&FoundClassDeclX)), "class Y;")); EXPECT_FALSE(FoundClassDeclX); } TEST(buildASTFromCode, FindsClassDecl) { std::unique_ptr<ASTUnit> AST(buildASTFromCode("class X;")); ASSERT_TRUE(AST.get()); EXPECT_TRUE(FindClassDeclX(AST.get())); AST.reset(buildASTFromCode("class Y;")); ASSERT_TRUE(AST.get()); EXPECT_FALSE(FindClassDeclX(AST.get())); } TEST(newFrontendActionFactory, CreatesFrontendActionFactoryFromType) { std::unique_ptr<FrontendActionFactory> Factory( newFrontendActionFactory<SyntaxOnlyAction>()); std::unique_ptr<FrontendAction> Action(Factory->create()); EXPECT_TRUE(Action.get() != NULL); } struct IndependentFrontendActionCreator { ASTConsumer *newASTConsumer() { return new FindTopLevelDeclConsumer(NULL); } }; TEST(newFrontendActionFactory, CreatesFrontendActionFactoryFromFactoryType) { IndependentFrontendActionCreator Creator; std::unique_ptr<FrontendActionFactory> Factory( newFrontendActionFactory(&Creator)); std::unique_ptr<FrontendAction> Action(Factory->create()); EXPECT_TRUE(Action.get() != NULL); } TEST(ToolInvocation, TestMapVirtualFile) { IntrusiveRefCntPtr<clang::FileManager> Files( new clang::FileManager(clang::FileSystemOptions())); std::vector<std::string> Args; Args.push_back("tool-executable"); Args.push_back("-Idef"); Args.push_back("-fsyntax-only"); Args.push_back("test.cpp"); clang::tooling::ToolInvocation Invocation(Args, new SyntaxOnlyAction, Files.getPtr()); Invocation.mapVirtualFile("test.cpp", "#include <abc>\n"); Invocation.mapVirtualFile("def/abc", "\n"); EXPECT_TRUE(Invocation.run()); } TEST(ToolInvocation, TestVirtualModulesCompilation) { // FIXME: Currently, this only tests that we don't exit with an error if a // mapped module.map is found on the include path. In the future, expand this // test to run a full modules enabled compilation, so we make sure we can // rerun modules compilations with a virtual file system. IntrusiveRefCntPtr<clang::FileManager> Files( new clang::FileManager(clang::FileSystemOptions())); std::vector<std::string> Args; Args.push_back("tool-executable"); Args.push_back("-Idef"); Args.push_back("-fsyntax-only"); Args.push_back("test.cpp"); clang::tooling::ToolInvocation Invocation(Args, new SyntaxOnlyAction, Files.getPtr()); Invocation.mapVirtualFile("test.cpp", "#include <abc>\n"); Invocation.mapVirtualFile("def/abc", "\n"); // Add a module.map file in the include directory of our header, so we trigger // the module.map header search logic. Invocation.mapVirtualFile("def/module.map", "\n"); EXPECT_TRUE(Invocation.run()); } struct VerifyEndCallback : public SourceFileCallbacks { VerifyEndCallback() : BeginCalled(0), EndCalled(0), Matched(false) {} virtual bool handleBeginSource(CompilerInstance &CI, StringRef Filename) override { ++BeginCalled; return true; } virtual void handleEndSource() { ++EndCalled; } ASTConsumer *newASTConsumer() { return new FindTopLevelDeclConsumer(&Matched); } unsigned BeginCalled; unsigned EndCalled; bool Matched; }; #if !defined(LLVM_ON_WIN32) TEST(newFrontendActionFactory, InjectsSourceFileCallbacks) { VerifyEndCallback EndCallback; FixedCompilationDatabase Compilations("/", std::vector<std::string>()); std::vector<std::string> Sources; Sources.push_back("/a.cc"); Sources.push_back("/b.cc"); ClangTool Tool(Compilations, Sources); Tool.mapVirtualFile("/a.cc", "void a() {}"); Tool.mapVirtualFile("/b.cc", "void b() {}"); std::unique_ptr<FrontendActionFactory> Action( newFrontendActionFactory(&EndCallback, &EndCallback)); Tool.run(Action.get()); EXPECT_TRUE(EndCallback.Matched); EXPECT_EQ(2u, EndCallback.BeginCalled); EXPECT_EQ(2u, EndCallback.EndCalled); } #endif struct SkipBodyConsumer : public clang::ASTConsumer { /// Skip the 'skipMe' function. virtual bool shouldSkipFunctionBody(Decl *D) { FunctionDecl *F = dyn_cast<FunctionDecl>(D); return F && F->getNameAsString() == "skipMe"; } }; struct SkipBodyAction : public clang::ASTFrontendAction { virtual ASTConsumer *CreateASTConsumer(CompilerInstance &Compiler, StringRef) { Compiler.getFrontendOpts().SkipFunctionBodies = true; return new SkipBodyConsumer; } }; TEST(runToolOnCode, TestSkipFunctionBody) { EXPECT_TRUE(runToolOnCode(new SkipBodyAction, "int skipMe() { an_error_here }")); EXPECT_FALSE(runToolOnCode(new SkipBodyAction, "int skipMeNot() { an_error_here }")); } TEST(runToolOnCodeWithArgs, TestNoDepFile) { llvm::SmallString<32> DepFilePath; ASSERT_FALSE( llvm::sys::fs::createTemporaryFile("depfile", "d", DepFilePath)); std::vector<std::string> Args; Args.push_back("-MMD"); Args.push_back("-MT"); Args.push_back(DepFilePath.str()); Args.push_back("-MF"); Args.push_back(DepFilePath.str()); EXPECT_TRUE(runToolOnCodeWithArgs(new SkipBodyAction, "", Args)); EXPECT_FALSE(llvm::sys::fs::exists(DepFilePath.str())); EXPECT_FALSE(llvm::sys::fs::remove(DepFilePath.str())); } struct CheckSyntaxOnlyAdjuster: public ArgumentsAdjuster { bool &Found; bool &Ran; CheckSyntaxOnlyAdjuster(bool &Found, bool &Ran) : Found(Found), Ran(Ran) { } virtual CommandLineArguments Adjust(const CommandLineArguments &Args) override { Ran = true; for (unsigned I = 0, E = Args.size(); I != E; ++I) { if (Args[I] == "-fsyntax-only") { Found = true; break; } } return Args; } }; TEST(ClangToolTest, ArgumentAdjusters) { FixedCompilationDatabase Compilations("/", std::vector<std::string>()); ClangTool Tool(Compilations, std::vector<std::string>(1, "/a.cc")); Tool.mapVirtualFile("/a.cc", "void a() {}"); std::unique_ptr<FrontendActionFactory> Action( newFrontendActionFactory<SyntaxOnlyAction>()); bool Found = false; bool Ran = false; Tool.appendArgumentsAdjuster(new CheckSyntaxOnlyAdjuster(Found, Ran)); Tool.run(Action.get()); EXPECT_TRUE(Ran); EXPECT_TRUE(Found); Ran = Found = false; Tool.clearArgumentsAdjusters(); Tool.appendArgumentsAdjuster(new CheckSyntaxOnlyAdjuster(Found, Ran)); Tool.appendArgumentsAdjuster(new ClangSyntaxOnlyAdjuster()); Tool.run(Action.get()); EXPECT_TRUE(Ran); EXPECT_FALSE(Found); } #ifndef LLVM_ON_WIN32 TEST(ClangToolTest, BuildASTs) { FixedCompilationDatabase Compilations("/", std::vector<std::string>()); std::vector<std::string> Sources; Sources.push_back("/a.cc"); Sources.push_back("/b.cc"); ClangTool Tool(Compilations, Sources); Tool.mapVirtualFile("/a.cc", "void a() {}"); Tool.mapVirtualFile("/b.cc", "void b() {}"); std::vector<ASTUnit *> ASTs; EXPECT_EQ(0, Tool.buildASTs(ASTs)); EXPECT_EQ(2u, ASTs.size()); llvm::DeleteContainerPointers(ASTs); } struct TestDiagnosticConsumer : public DiagnosticConsumer { TestDiagnosticConsumer() : NumDiagnosticsSeen(0) {} virtual void HandleDiagnostic(DiagnosticsEngine::Level DiagLevel, const Diagnostic &Info) { ++NumDiagnosticsSeen; } unsigned NumDiagnosticsSeen; }; TEST(ClangToolTest, InjectDiagnosticConsumer) { FixedCompilationDatabase Compilations("/", std::vector<std::string>()); ClangTool Tool(Compilations, std::vector<std::string>(1, "/a.cc")); Tool.mapVirtualFile("/a.cc", "int x = undeclared;"); TestDiagnosticConsumer Consumer; Tool.setDiagnosticConsumer(&Consumer); std::unique_ptr<FrontendActionFactory> Action( newFrontendActionFactory<SyntaxOnlyAction>()); Tool.run(Action.get()); EXPECT_EQ(1u, Consumer.NumDiagnosticsSeen); } TEST(ClangToolTest, InjectDiagnosticConsumerInBuildASTs) { FixedCompilationDatabase Compilations("/", std::vector<std::string>()); ClangTool Tool(Compilations, std::vector<std::string>(1, "/a.cc")); Tool.mapVirtualFile("/a.cc", "int x = undeclared;"); TestDiagnosticConsumer Consumer; Tool.setDiagnosticConsumer(&Consumer); std::vector<ASTUnit*> ASTs; Tool.buildASTs(ASTs); EXPECT_EQ(1u, ASTs.size()); EXPECT_EQ(1u, Consumer.NumDiagnosticsSeen); } #endif } // end namespace tooling } // end namespace clang <|endoftext|>
<commit_before>// MediaInfo_Internal - All info about media files // Copyright (C) 2002-2010 MediaArea.net SARL, Info@MediaArea.net // // 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 3 of the License, or // 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, see <http://www.gnu.org/licenses/>. // //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ //--------------------------------------------------------------------------- // For user: you can disable or enable it //#define MEDIAINFO_DEBUG //--------------------------------------------------------------------------- //--------------------------------------------------------------------------- // Compilation conditions #include "MediaInfo/Setup.h" #ifdef __BORLANDC__ #pragma hdrstop #endif //--------------------------------------------------------------------------- //--------------------------------------------------------------------------- #include "MediaInfo/Reader/Reader_File.h" #include "MediaInfo/File__Analyze.h" #include "ZenLib/FileName.h" #include "ZenLib/File.h" using namespace ZenLib; using namespace std; //--------------------------------------------------------------------------- // Debug stuff #ifdef MEDIAINFO_DEBUG int64u Reader_File_Offset=0; int64u Reader_File_BytesRead_Total=0; int64u Reader_File_BytesRead=0; int64u Reader_File_Count=1; #include <iostream> #endif // MEDIAINFO_DEBUG //--------------------------------------------------------------------------- namespace MediaInfoLib { const size_t Buffer_NormalSize=/*188*7;//*/64*1024; const size_t Buffer_NoJump=128*1024; //--------------------------------------------------------------------------- size_t Reader_File::Format_Test(MediaInfo_Internal* MI, const String &File_Name) { //With Parser MultipleParsing /* MI->Open_Buffer_Init((int64u)-1, File_Name); if (Format_Test_PerParser(MI, File_Name)) return 1; return 0; //There is a problem */ //Get the Extension Ztring Extension=FileName::Extension_Get(File_Name); Extension.MakeLowerCase(); //Search the theorical format from extension InfoMap &FormatList=MediaInfoLib::Config.Format_Get(); InfoMap::iterator Format=FormatList.begin(); while (Format!=FormatList.end()) { const Ztring &Extensions=FormatList.Get(Format->first, InfoFormat_Extensions); if (Extensions.find(Extension)!=Error) { if(Extension.size()==Extensions.size()) break; //Only one extenion in the list if(Extensions.find(Extension+_T(" "))!=Error || Extensions.find(_T(" ")+Extension)!=Error) break; } Format++; } if (Format!=FormatList.end()) { const Ztring &Parser=Format->second(InfoFormat_Parser); if (MI->SelectFromExtension(Parser)) { //Test the theorical format if (Format_Test_PerParser(MI, File_Name)>0) return 1; } } size_t ToReturn=MI->ListFormats(File_Name); return ToReturn; } //--------------------------------------------------------------------------- size_t Reader_File::Format_Test_PerParser(MediaInfo_Internal* MI, const String &File_Name) { //Opening the file File F; F.Open(File_Name); if (!F.Opened_Get()) return 0; //Buffer size_t Buffer_Size_Max=Buffer_NormalSize; int8u* Buffer=new int8u[Buffer_Size_Max]; //Parser MI->Open_Buffer_Init(F.Size_Get(), File_Name); //Test the format with buffer bool StopAfterFilled=MI->Config.File_StopAfterFilled_Get(); std::bitset<32> Status; do { //Seek (if needed) if (MI->Open_Buffer_Continue_GoTo_Get()!=(int64u)-1) { #ifdef MEDIAINFO_DEBUG std::cout<<std::hex<<Reader_File_Offset<<" - "<<Reader_File_Offset+Reader_File_BytesRead<<" : "<<std::dec<<Reader_File_BytesRead<<" bytes"<<std::endl; Reader_File_Offset=MI->Open_Buffer_Continue_GoTo_Get(); Reader_File_BytesRead=0; Reader_File_Count++; #endif //MEDIAINFO_DEBUG if (MI->Open_Buffer_Continue_GoTo_Get()>=F.Size_Get()) break; //Seek requested, but on a file bigger in theory than what is in the real file, we can't do this if (!(MI->Open_Buffer_Continue_GoTo_Get()>F.Position_Get() && MI->Open_Buffer_Continue_GoTo_Get()<F.Position_Get()+Buffer_NoJump)) //No smal jumps { if (!F.GoTo(MI->Open_Buffer_Continue_GoTo_Get())) break; //File is not seekable MI->Open_Buffer_Init((int64u)-1, F.Position_Get()); } } //Buffering size_t Buffer_Size=F.Read(Buffer, Buffer_Size_Max); if (Buffer_Size==0) break; //Problem while reading #ifdef MEDIAINFO_DEBUG Reader_File_BytesRead_Total+=Buffer_Size; Reader_File_BytesRead+=Buffer_Size; #endif //MEDIAINFO_DEBUG //Parser Status=MI->Open_Buffer_Continue(Buffer, Buffer_Size); //Threading if (MI->IsTerminating()) break; //Termination is requested } while (!(Status[File__Analyze::IsFinished] || (StopAfterFilled && Status[File__Analyze::IsFilled]))); if (F.Size_Get()==0) //If Size==0, Status is never updated Status=MI->Open_Buffer_Continue(NULL, 0); #ifdef MEDIAINFO_DEBUG std::cout<<std::hex<<Reader_File_Offset<<" - "<<Reader_File_Offset+Reader_File_BytesRead<<" : "<<std::dec<<Reader_File_BytesRead<<" bytes"<<std::endl; std::cout<<"Total: "<<std::dec<<Reader_File_BytesRead_Total<<" bytes in "<<Reader_File_Count<<" blocks"<<std::endl; #endif //MEDIAINFO_DEBUG //File F.Close(); //Buffer delete[] Buffer; //Buffer=NULL; //Is this file detected? if (!Status[File__Analyze::IsAccepted]) return 0; MI->Open_Buffer_Finalize(); return 1; } } //NameSpace <commit_msg><commit_after>// MediaInfo_Internal - All info about media files // Copyright (C) 2002-2010 MediaArea.net SARL, Info@MediaArea.net // // 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 3 of the License, or // 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, see <http://www.gnu.org/licenses/>. // //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ //--------------------------------------------------------------------------- // For user: you can disable or enable it //#define MEDIAINFO_DEBUG //--------------------------------------------------------------------------- //--------------------------------------------------------------------------- // Compilation conditions #include "MediaInfo/Setup.h" #ifdef __BORLANDC__ #pragma hdrstop #endif //--------------------------------------------------------------------------- //--------------------------------------------------------------------------- #include "MediaInfo/Reader/Reader_File.h" #include "MediaInfo/File__Analyze.h" #include "ZenLib/FileName.h" #include "ZenLib/File.h" using namespace ZenLib; using namespace std; //--------------------------------------------------------------------------- // Debug stuff #ifdef MEDIAINFO_DEBUG int64u Reader_File_Offset=0; int64u Reader_File_BytesRead_Total=0; int64u Reader_File_BytesRead=0; int64u Reader_File_Count=1; #include <iostream> #endif // MEDIAINFO_DEBUG //--------------------------------------------------------------------------- namespace MediaInfoLib { const size_t Buffer_NormalSize=/*188*7;//*/64*1024; const size_t Buffer_NoJump=128*1024; //--------------------------------------------------------------------------- size_t Reader_File::Format_Test(MediaInfo_Internal* MI, const String &File_Name) { #if MEDIAINFO_EVENTS { struct MediaInfo_Event_General_Start_0 Event; Event.EventCode=MediaInfo_EventCode_Create(MediaInfo_Parser_None, MediaInfo_Event_General_Start, 0); Event.Stream_Size=File::Size_Get(File_Name); MI->Config.Event_Send((const int8u*)&Event, sizeof(MediaInfo_Event_General_Start_0)); } #endif //MEDIAINFO_EVENTS //With Parser MultipleParsing /* MI->Open_Buffer_Init((int64u)-1, File_Name); if (Format_Test_PerParser(MI, File_Name)) return 1; return 0; //There is a problem */ //Get the Extension Ztring Extension=FileName::Extension_Get(File_Name); Extension.MakeLowerCase(); //Search the theorical format from extension InfoMap &FormatList=MediaInfoLib::Config.Format_Get(); InfoMap::iterator Format=FormatList.begin(); while (Format!=FormatList.end()) { const Ztring &Extensions=FormatList.Get(Format->first, InfoFormat_Extensions); if (Extensions.find(Extension)!=Error) { if(Extension.size()==Extensions.size()) break; //Only one extenion in the list if(Extensions.find(Extension+_T(" "))!=Error || Extensions.find(_T(" ")+Extension)!=Error) break; } Format++; } if (Format!=FormatList.end()) { const Ztring &Parser=Format->second(InfoFormat_Parser); if (MI->SelectFromExtension(Parser)) { //Test the theorical format if (Format_Test_PerParser(MI, File_Name)>0) return 1; } } size_t ToReturn=MI->ListFormats(File_Name); return ToReturn; } //--------------------------------------------------------------------------- size_t Reader_File::Format_Test_PerParser(MediaInfo_Internal* MI, const String &File_Name) { //Opening the file File F; F.Open(File_Name); if (!F.Opened_Get()) return 0; //Buffer size_t Buffer_Size_Max=Buffer_NormalSize; int8u* Buffer=new int8u[Buffer_Size_Max]; //Parser MI->Open_Buffer_Init(F.Size_Get(), File_Name); //Test the format with buffer bool StopAfterFilled=MI->Config.File_StopAfterFilled_Get(); std::bitset<32> Status; do { //Seek (if needed) if (MI->Open_Buffer_Continue_GoTo_Get()!=(int64u)-1) { #ifdef MEDIAINFO_DEBUG std::cout<<std::hex<<Reader_File_Offset<<" - "<<Reader_File_Offset+Reader_File_BytesRead<<" : "<<std::dec<<Reader_File_BytesRead<<" bytes"<<std::endl; Reader_File_Offset=MI->Open_Buffer_Continue_GoTo_Get(); Reader_File_BytesRead=0; Reader_File_Count++; #endif //MEDIAINFO_DEBUG if (MI->Open_Buffer_Continue_GoTo_Get()>=F.Size_Get()) break; //Seek requested, but on a file bigger in theory than what is in the real file, we can't do this if (!(MI->Open_Buffer_Continue_GoTo_Get()>F.Position_Get() && MI->Open_Buffer_Continue_GoTo_Get()<F.Position_Get()+Buffer_NoJump)) //No smal jumps { if (!F.GoTo(MI->Open_Buffer_Continue_GoTo_Get())) break; //File is not seekable MI->Open_Buffer_Init((int64u)-1, F.Position_Get()); } } //Buffering size_t Buffer_Size=F.Read(Buffer, Buffer_Size_Max); if (Buffer_Size==0) break; //Problem while reading #ifdef MEDIAINFO_DEBUG Reader_File_BytesRead_Total+=Buffer_Size; Reader_File_BytesRead+=Buffer_Size; #endif //MEDIAINFO_DEBUG //Parser Status=MI->Open_Buffer_Continue(Buffer, Buffer_Size); //Threading if (MI->IsTerminating()) break; //Termination is requested } while (!(Status[File__Analyze::IsFinished] || (StopAfterFilled && Status[File__Analyze::IsFilled]))); if (F.Size_Get()==0) //If Size==0, Status is never updated Status=MI->Open_Buffer_Continue(NULL, 0); #ifdef MEDIAINFO_DEBUG std::cout<<std::hex<<Reader_File_Offset<<" - "<<Reader_File_Offset+Reader_File_BytesRead<<" : "<<std::dec<<Reader_File_BytesRead<<" bytes"<<std::endl; std::cout<<"Total: "<<std::dec<<Reader_File_BytesRead_Total<<" bytes in "<<Reader_File_Count<<" blocks"<<std::endl; #endif //MEDIAINFO_DEBUG //File F.Close(); //Buffer delete[] Buffer; //Buffer=NULL; //Is this file detected? if (!Status[File__Analyze::IsAccepted]) return 0; MI->Open_Buffer_Finalize(); return 1; } } //NameSpace <|endoftext|>
<commit_before>/* * Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies) * * 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; see the file COPYING.LIB. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. * */ #include "config.h" #include "core/html/HTMLSummaryElement.h" #include "bindings/core/v8/ExceptionStatePlaceholder.h" #include "core/HTMLNames.h" #include "core/events/KeyboardEvent.h" #include "core/dom/NodeRenderingTraversal.h" #include "core/dom/shadow/ShadowRoot.h" #include "core/html/HTMLContentElement.h" #include "core/html/HTMLDetailsElement.h" #include "core/html/shadow/DetailsMarkerControl.h" #include "core/html/shadow/ShadowElementNames.h" #include "core/rendering/RenderBlockFlow.h" namespace blink { using namespace HTMLNames; PassRefPtrWillBeRawPtr<HTMLSummaryElement> HTMLSummaryElement::create(Document& document) { RefPtrWillBeRawPtr<HTMLSummaryElement> summary = adoptRefWillBeNoop(new HTMLSummaryElement(document)); summary->ensureUserAgentShadowRoot(); return summary.release(); } HTMLSummaryElement::HTMLSummaryElement(Document& document) : HTMLElement(summaryTag, document) { } RenderObject* HTMLSummaryElement::createRenderer(RenderStyle*) { return new RenderBlockFlow(this); } void HTMLSummaryElement::didAddUserAgentShadowRoot(ShadowRoot& root) { RefPtr<DetailsMarkerControl> markerControl = DetailsMarkerControl::create(document()); markerControl->setIdAttribute(ShadowElementNames::detailsMarker()); root.appendChild(markerControl); root.appendChild(HTMLContentElement::create(document())); } HTMLDetailsElement* HTMLSummaryElement::detailsElement() const { Node* parent = NodeRenderingTraversal::parent(*this); if (isHTMLDetailsElement(parent)) return toHTMLDetailsElement(parent); return nullptr; } Element* HTMLSummaryElement::markerControl() { return ensureUserAgentShadowRoot().getElementById(ShadowElementNames::detailsMarker()); } bool HTMLSummaryElement::isMainSummary() const { if (HTMLDetailsElement* details = detailsElement()) return details->findMainSummary() == this; return false; } static bool isClickableControl(Node* node) { if (!node->isElementNode()) return false; Element* element = toElement(node); if (element->isFormControlElement()) return true; Element* host = element->shadowHost(); return host && host->isFormControlElement(); } bool HTMLSummaryElement::supportsFocus() const { return isMainSummary(); } void HTMLSummaryElement::defaultEventHandler(Event* event) { if (isMainSummary() && renderer()) { if (event->type() == EventTypeNames::DOMActivate && !isClickableControl(event->target()->toNode())) { if (HTMLDetailsElement* details = detailsElement()) details->toggleOpen(); event->setDefaultHandled(); return; } if (event->isKeyboardEvent()) { if (event->type() == EventTypeNames::keydown && toKeyboardEvent(event)->keyIdentifier() == "U+0020") { setActive(true); // No setDefaultHandled() - IE dispatches a keypress in this case. return; } if (event->type() == EventTypeNames::keypress) { switch (toKeyboardEvent(event)->charCode()) { case '\r': dispatchSimulatedClick(event); event->setDefaultHandled(); return; case ' ': // Prevent scrolling down the page. event->setDefaultHandled(); return; } } if (event->type() == EventTypeNames::keyup && toKeyboardEvent(event)->keyIdentifier() == "U+0020") { if (active()) dispatchSimulatedClick(event); event->setDefaultHandled(); return; } } } HTMLElement::defaultEventHandler(event); } bool HTMLSummaryElement::willRespondToMouseClickEvents() { if (isMainSummary() && renderer()) return true; return HTMLElement::willRespondToMouseClickEvents(); } } <commit_msg>Oilpan: Build fix after r186445<commit_after>/* * Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies) * * 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; see the file COPYING.LIB. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. * */ #include "config.h" #include "core/html/HTMLSummaryElement.h" #include "bindings/core/v8/ExceptionStatePlaceholder.h" #include "core/HTMLNames.h" #include "core/events/KeyboardEvent.h" #include "core/dom/NodeRenderingTraversal.h" #include "core/dom/shadow/ShadowRoot.h" #include "core/html/HTMLContentElement.h" #include "core/html/HTMLDetailsElement.h" #include "core/html/shadow/DetailsMarkerControl.h" #include "core/html/shadow/ShadowElementNames.h" #include "core/rendering/RenderBlockFlow.h" namespace blink { using namespace HTMLNames; PassRefPtrWillBeRawPtr<HTMLSummaryElement> HTMLSummaryElement::create(Document& document) { RefPtrWillBeRawPtr<HTMLSummaryElement> summary = adoptRefWillBeNoop(new HTMLSummaryElement(document)); summary->ensureUserAgentShadowRoot(); return summary.release(); } HTMLSummaryElement::HTMLSummaryElement(Document& document) : HTMLElement(summaryTag, document) { } RenderObject* HTMLSummaryElement::createRenderer(RenderStyle*) { return new RenderBlockFlow(this); } void HTMLSummaryElement::didAddUserAgentShadowRoot(ShadowRoot& root) { RefPtrWillBeRawPtr<DetailsMarkerControl> markerControl = DetailsMarkerControl::create(document()); markerControl->setIdAttribute(ShadowElementNames::detailsMarker()); root.appendChild(markerControl); root.appendChild(HTMLContentElement::create(document())); } HTMLDetailsElement* HTMLSummaryElement::detailsElement() const { Node* parent = NodeRenderingTraversal::parent(*this); if (isHTMLDetailsElement(parent)) return toHTMLDetailsElement(parent); return nullptr; } Element* HTMLSummaryElement::markerControl() { return ensureUserAgentShadowRoot().getElementById(ShadowElementNames::detailsMarker()); } bool HTMLSummaryElement::isMainSummary() const { if (HTMLDetailsElement* details = detailsElement()) return details->findMainSummary() == this; return false; } static bool isClickableControl(Node* node) { if (!node->isElementNode()) return false; Element* element = toElement(node); if (element->isFormControlElement()) return true; Element* host = element->shadowHost(); return host && host->isFormControlElement(); } bool HTMLSummaryElement::supportsFocus() const { return isMainSummary(); } void HTMLSummaryElement::defaultEventHandler(Event* event) { if (isMainSummary() && renderer()) { if (event->type() == EventTypeNames::DOMActivate && !isClickableControl(event->target()->toNode())) { if (HTMLDetailsElement* details = detailsElement()) details->toggleOpen(); event->setDefaultHandled(); return; } if (event->isKeyboardEvent()) { if (event->type() == EventTypeNames::keydown && toKeyboardEvent(event)->keyIdentifier() == "U+0020") { setActive(true); // No setDefaultHandled() - IE dispatches a keypress in this case. return; } if (event->type() == EventTypeNames::keypress) { switch (toKeyboardEvent(event)->charCode()) { case '\r': dispatchSimulatedClick(event); event->setDefaultHandled(); return; case ' ': // Prevent scrolling down the page. event->setDefaultHandled(); return; } } if (event->type() == EventTypeNames::keyup && toKeyboardEvent(event)->keyIdentifier() == "U+0020") { if (active()) dispatchSimulatedClick(event); event->setDefaultHandled(); return; } } } HTMLElement::defaultEventHandler(event); } bool HTMLSummaryElement::willRespondToMouseClickEvents() { if (isMainSummary() && renderer()) return true; return HTMLElement::willRespondToMouseClickEvents(); } } <|endoftext|>
<commit_before>#include <iostream> #include <iomanip> #include <string> #include <memory> #include <chrono> #include <windows.h> #include <psapi.h> //GetModuleFileNameEx #include <TlHelp32.h> // Setting DLL access controls #include <AccCtrl.h> #include <Aclapi.h> #include <Sddl.h> // UWP #include <atlbase.h> #include <appmodel.h> // IPC #include <UWP/DumperIPC.hpp> const wchar_t* DLLFile = L"UWPDumper.dll"; void SetAccessControl( const std::wstring& ExecutableName, const wchar_t* AccessString ); bool DLLInjectRemote(uint32_t ProcessID, const std::wstring& DLLpath); std::wstring GetRunningDirectory(); using ThreadCallback = bool(*)( std::uint32_t ThreadID, void* Data ); void IterateThreads(ThreadCallback ThreadProc, std::uint32_t ProcessID, void* Data) { void* hSnapShot = CreateToolhelp32Snapshot( TH32CS_SNAPTHREAD, ProcessID ); if( hSnapShot == INVALID_HANDLE_VALUE ) { return; } THREADENTRY32 ThreadEntry = { 0 }; ThreadEntry.dwSize = sizeof(THREADENTRY32); Thread32First(hSnapShot, &ThreadEntry); do { if( ThreadEntry.th32OwnerProcessID == ProcessID ) { const bool Continue = ThreadProc( ThreadEntry.th32ThreadID, Data ); if( Continue == false ) { break; } } } while( Thread32Next(hSnapShot, &ThreadEntry) ); CloseHandle(hSnapShot); } int main() { // Enable VT100 const auto Handle = GetStdHandle(STD_OUTPUT_HANDLE); DWORD ConsoleMode; GetConsoleMode( Handle, &ConsoleMode ); SetConsoleMode( Handle, ConsoleMode | ENABLE_VIRTUAL_TERMINAL_PROCESSING ); SetConsoleOutputCP(437); std::wcout << "\033[92mUWPInjector Build date (" << __DATE__ << " : " << __TIME__ << ')' << std::endl; std::wcout << "\033[96m\t-https://github.com/Wunkolo/UWPDumper\n"; std::wcout << "\033[95m" << std::wstring(80, '-') << std::endl; std::uint32_t ProcessID = 0; IPC::SetClientProcess(GetCurrentProcessId()); std::cout << "\033[93mCurrently running UWP Apps:" << std::endl; void* ProcessSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0); PROCESSENTRY32 ProcessEntry; ProcessEntry.dwSize = sizeof(PROCESSENTRY32); if( Process32First(ProcessSnapshot, &ProcessEntry) ) { while( Process32Next(ProcessSnapshot, &ProcessEntry) ) { void* ProcessHandle = OpenProcess( PROCESS_QUERY_LIMITED_INFORMATION, false, ProcessEntry.th32ProcessID ); if( ProcessHandle ) { std::uint32_t NameLength = 0; std::int32_t ProcessCode = GetPackageFamilyName( ProcessHandle, &NameLength, nullptr ); if( NameLength ) { std::wcout << "\033[92m" << std::setw(12) << ProcessEntry.th32ProcessID; std::wcout << "\033[96m" << " | " << ProcessEntry.szExeFile << " :\n\t\t-"; std::unique_ptr<wchar_t[]> PackageName(new wchar_t[NameLength]()); ProcessCode = GetPackageFamilyName( ProcessHandle, &NameLength, PackageName.get() ); if( ProcessCode != ERROR_SUCCESS ) { std::wcout << "GetPackageFamilyName Error: " << ProcessCode; } std::wcout << PackageName.get() << std::endl; PackageName.reset(); } } CloseHandle(ProcessHandle); } } else { std::cout << "\033[91mUnable to iterate active processes" << std::endl; system("pause"); return EXIT_FAILURE; } std::cout << "\033[93mEnter ProcessID: \033[92m"; std::cin >> ProcessID; SetAccessControl(GetRunningDirectory() + L'\\' + DLLFile, L"S-1-15-2-1"); IPC::SetTargetProcess(ProcessID); std::cout << "\033[93mInjecting into remote process: "; if( !DLLInjectRemote(ProcessID, GetRunningDirectory() + L'\\' + DLLFile) ) { std::cout << "\033[91mFailed" << std::endl; system("pause"); return EXIT_FAILURE; } std::cout << "\033[92mSuccess!" << std::endl; std::cout << "\033[93mWaiting for remote thread IPC:" << std::endl; std::chrono::high_resolution_clock::time_point ThreadTimeout = std::chrono::high_resolution_clock::now() + std::chrono::seconds(5); while( IPC::GetTargetThread() == IPC::InvalidThread ) { if( std::chrono::high_resolution_clock::now() >= ThreadTimeout ) { std::cout << "\033[91mRemote thread wait timeout: Unable to find target thread" << std::endl; system("pause"); return EXIT_FAILURE; } } std::cout << "Remote Dumper thread found: 0x" << std::hex << IPC::GetTargetThread() << std::endl; std::cout << "\033[0m" << std::flush; while( IPC::GetTargetThread() != IPC::InvalidThread ) { while( IPC::MessageCount() > 0 ) { std::wcout << IPC::PopMessage() << "\033[0m"; } } system("pause"); return EXIT_SUCCESS; } void SetAccessControl(const std::wstring& ExecutableName, const wchar_t* AccessString) { PSECURITY_DESCRIPTOR SecurityDescriptor = nullptr; EXPLICIT_ACCESSW ExplicitAccess = { 0 }; ACL* AccessControlCurrent = nullptr; ACL* AccessControlNew = nullptr; SECURITY_INFORMATION SecurityInfo = DACL_SECURITY_INFORMATION; PSID SecurityIdentifier = nullptr; if( GetNamedSecurityInfoW( ExecutableName.c_str(), SE_FILE_OBJECT, DACL_SECURITY_INFORMATION, nullptr, nullptr, &AccessControlCurrent, nullptr, &SecurityDescriptor) == ERROR_SUCCESS ) { ConvertStringSidToSidW(AccessString, &SecurityIdentifier); if( SecurityIdentifier != nullptr ) { ExplicitAccess.grfAccessPermissions = GENERIC_READ | GENERIC_EXECUTE; ExplicitAccess.grfAccessMode = SET_ACCESS; ExplicitAccess.grfInheritance = SUB_CONTAINERS_AND_OBJECTS_INHERIT; ExplicitAccess.Trustee.TrusteeForm = TRUSTEE_IS_SID; ExplicitAccess.Trustee.TrusteeType = TRUSTEE_IS_WELL_KNOWN_GROUP; ExplicitAccess.Trustee.ptstrName = reinterpret_cast<wchar_t*>(SecurityIdentifier); if( SetEntriesInAclW( 1, &ExplicitAccess, AccessControlCurrent, &AccessControlNew) == ERROR_SUCCESS ) { SetNamedSecurityInfoW( const_cast<wchar_t*>(ExecutableName.c_str()), SE_FILE_OBJECT, SecurityInfo, nullptr, nullptr, AccessControlNew, nullptr ); } } } if( SecurityDescriptor ) { LocalFree(reinterpret_cast<HLOCAL>(SecurityDescriptor)); } if( AccessControlNew ) { LocalFree(reinterpret_cast<HLOCAL>(AccessControlNew)); } } bool DLLInjectRemote(uint32_t ProcessID, const std::wstring& DLLpath) { const std::size_t DLLPathSize = ((DLLpath.size() + 1) * sizeof(wchar_t)); std::uint32_t Result; if( !ProcessID ) { std::wcout << "Invalid Process ID: " << ProcessID << std::endl; return false; } if( GetFileAttributesW(DLLpath.c_str()) == INVALID_FILE_ATTRIBUTES ) { std::wcout << "DLL file: " << DLLpath << " does not exists" << std::endl; return false; } SetAccessControl(DLLpath, L"S-1-15-2-1"); void* ProcLoadLibrary = reinterpret_cast<void*>( GetProcAddress(GetModuleHandleW(L"kernel32.dll"), "LoadLibraryW")); if( !ProcLoadLibrary ) { std::wcout << "Unable to find LoadLibraryW procedure" << std::endl; return false; } void* Process = OpenProcess(PROCESS_ALL_ACCESS, false, ProcessID); if( Process == nullptr ) { std::wcout << "Unable to open process ID" << ProcessID << " for writing" << std::endl; return false; } void* VirtualAlloc = reinterpret_cast<void*>( VirtualAllocEx( Process, nullptr, DLLPathSize, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE ) ); if( VirtualAlloc == nullptr ) { std::wcout << "Unable to remotely allocate memory" << std::endl; CloseHandle(Process); return false; } std::size_t BytesWritten = 0; Result = WriteProcessMemory( Process, VirtualAlloc, DLLpath.data(), DLLPathSize, &BytesWritten ); if( Result == 0 ) { std::wcout << "Unable to write process memory" << std::endl; CloseHandle(Process); return false; } if( BytesWritten != DLLPathSize ) { std::wcout << "Failed to write remote DLL path name" << std::endl; CloseHandle(Process); return false; } void* RemoteThread = CreateRemoteThread( Process, nullptr, 0, reinterpret_cast<LPTHREAD_START_ROUTINE>(ProcLoadLibrary), VirtualAlloc, 0, nullptr ); // Wait for remote thread to finish if( RemoteThread ) { // Explicitly wait for LoadLibraryW to complete before releasing memory // avoids causing a remote memory leak WaitForSingleObject(RemoteThread, INFINITE); CloseHandle(RemoteThread); } else { // Failed to create thread std::wcout << "Unable to create remote thread" << std::endl; } VirtualFreeEx(Process, VirtualAlloc, 0, MEM_RELEASE); CloseHandle(Process); return true; } std::wstring GetRunningDirectory() { wchar_t RunPath[MAX_PATH]; GetModuleFileNameW(GetModuleHandleW(nullptr), RunPath, MAX_PATH); PathRemoveFileSpecW(RunPath); return std::wstring(RunPath); } <commit_msg>Add VT100 line drawing characters<commit_after>#include <iostream> #include <iomanip> #include <string> #include <memory> #include <chrono> #include <windows.h> #include <psapi.h> //GetModuleFileNameEx #include <TlHelp32.h> // Setting DLL access controls #include <AccCtrl.h> #include <Aclapi.h> #include <Sddl.h> // UWP #include <atlbase.h> #include <appmodel.h> // IPC #include <UWP/DumperIPC.hpp> const wchar_t* DLLFile = L"UWPDumper.dll"; void SetAccessControl( const std::wstring& ExecutableName, const wchar_t* AccessString ); bool DLLInjectRemote(uint32_t ProcessID, const std::wstring& DLLpath); std::wstring GetRunningDirectory(); using ThreadCallback = bool(*)( std::uint32_t ThreadID, void* Data ); void IterateThreads(ThreadCallback ThreadProc, std::uint32_t ProcessID, void* Data) { void* hSnapShot = CreateToolhelp32Snapshot( TH32CS_SNAPTHREAD, ProcessID ); if( hSnapShot == INVALID_HANDLE_VALUE ) { return; } THREADENTRY32 ThreadEntry = { 0 }; ThreadEntry.dwSize = sizeof(THREADENTRY32); Thread32First(hSnapShot, &ThreadEntry); do { if( ThreadEntry.th32OwnerProcessID == ProcessID ) { const bool Continue = ThreadProc( ThreadEntry.th32ThreadID, Data ); if( Continue == false ) { break; } } } while( Thread32Next(hSnapShot, &ThreadEntry) ); CloseHandle(hSnapShot); } int main() { // Enable VT100 DWORD ConsoleMode; GetConsoleMode( GetStdHandle(STD_OUTPUT_HANDLE), &ConsoleMode ); SetConsoleMode( GetStdHandle(STD_OUTPUT_HANDLE), ConsoleMode | ENABLE_VIRTUAL_TERMINAL_PROCESSING ); SetConsoleOutputCP(437); std::wcout << "\033[92mUWPInjector Build date (" << __DATE__ << " : " << __TIME__ << ')' << std::endl; std::wcout << "\033[96m\t\033(0m\033(Bhttps://github.com/Wunkolo/UWPDumper\n"; std::wcout << "\033[95m\033(0" << std::wstring(80, 'q') << "\033(B" << std::endl; std::uint32_t ProcessID = 0; IPC::SetClientProcess(GetCurrentProcessId()); std::cout << "\033[93mCurrently running UWP Apps:" << std::endl; void* ProcessSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0); PROCESSENTRY32 ProcessEntry; ProcessEntry.dwSize = sizeof(PROCESSENTRY32); if( Process32First(ProcessSnapshot, &ProcessEntry) ) { while( Process32Next(ProcessSnapshot, &ProcessEntry) ) { void* ProcessHandle = OpenProcess( PROCESS_QUERY_LIMITED_INFORMATION, false, ProcessEntry.th32ProcessID ); if( ProcessHandle ) { std::uint32_t NameLength = 0; std::int32_t ProcessCode = GetPackageFamilyName( ProcessHandle, &NameLength, nullptr ); if( NameLength ) { std::wcout << "\033[92m" << std::setw(12) << ProcessEntry.th32ProcessID; std::wcout << "\033[96m" << " \033(0x\033(B " << ProcessEntry.szExeFile << " :\n\t\t\033(0m\033(B"; std::unique_ptr<wchar_t[]> PackageName(new wchar_t[NameLength]()); ProcessCode = GetPackageFamilyName( ProcessHandle, &NameLength, PackageName.get() ); if( ProcessCode != ERROR_SUCCESS ) { std::wcout << "GetPackageFamilyName Error: " << ProcessCode; } std::wcout << PackageName.get() << std::endl; PackageName.reset(); } } CloseHandle(ProcessHandle); } } else { std::cout << "\033[91mUnable to iterate active processes" << std::endl; system("pause"); return EXIT_FAILURE; } std::cout << "\033[93mEnter ProcessID: \033[92m"; std::cin >> ProcessID; SetAccessControl(GetRunningDirectory() + L'\\' + DLLFile, L"S-1-15-2-1"); IPC::SetTargetProcess(ProcessID); std::cout << "\033[93mInjecting into remote process: "; if( !DLLInjectRemote(ProcessID, GetRunningDirectory() + L'\\' + DLLFile) ) { std::cout << "\033[91mFailed" << std::endl; system("pause"); return EXIT_FAILURE; } std::cout << "\033[92mSuccess!" << std::endl; std::cout << "\033[93mWaiting for remote thread IPC:" << std::endl; std::chrono::high_resolution_clock::time_point ThreadTimeout = std::chrono::high_resolution_clock::now() + std::chrono::seconds(5); while( IPC::GetTargetThread() == IPC::InvalidThread ) { if( std::chrono::high_resolution_clock::now() >= ThreadTimeout ) { std::cout << "\033[91mRemote thread wait timeout: Unable to find target thread" << std::endl; system("pause"); return EXIT_FAILURE; } } std::cout << "Remote Dumper thread found: 0x" << std::hex << IPC::GetTargetThread() << std::endl; std::cout << "\033[0m" << std::flush; while( IPC::GetTargetThread() != IPC::InvalidThread ) { while( IPC::MessageCount() > 0 ) { std::wcout << IPC::PopMessage() << "\033[0m"; } } system("pause"); return EXIT_SUCCESS; } void SetAccessControl(const std::wstring& ExecutableName, const wchar_t* AccessString) { PSECURITY_DESCRIPTOR SecurityDescriptor = nullptr; EXPLICIT_ACCESSW ExplicitAccess = { 0 }; ACL* AccessControlCurrent = nullptr; ACL* AccessControlNew = nullptr; SECURITY_INFORMATION SecurityInfo = DACL_SECURITY_INFORMATION; PSID SecurityIdentifier = nullptr; if( GetNamedSecurityInfoW( ExecutableName.c_str(), SE_FILE_OBJECT, DACL_SECURITY_INFORMATION, nullptr, nullptr, &AccessControlCurrent, nullptr, &SecurityDescriptor ) == ERROR_SUCCESS ) { ConvertStringSidToSidW(AccessString, &SecurityIdentifier); if( SecurityIdentifier != nullptr ) { ExplicitAccess.grfAccessPermissions = GENERIC_READ | GENERIC_EXECUTE; ExplicitAccess.grfAccessMode = SET_ACCESS; ExplicitAccess.grfInheritance = SUB_CONTAINERS_AND_OBJECTS_INHERIT; ExplicitAccess.Trustee.TrusteeForm = TRUSTEE_IS_SID; ExplicitAccess.Trustee.TrusteeType = TRUSTEE_IS_WELL_KNOWN_GROUP; ExplicitAccess.Trustee.ptstrName = reinterpret_cast<wchar_t*>(SecurityIdentifier); if( SetEntriesInAclW( 1, &ExplicitAccess, AccessControlCurrent, &AccessControlNew ) == ERROR_SUCCESS ) { SetNamedSecurityInfoW( const_cast<wchar_t*>(ExecutableName.c_str()), SE_FILE_OBJECT, SecurityInfo, nullptr, nullptr, AccessControlNew, nullptr ); } } } if( SecurityDescriptor ) { LocalFree(reinterpret_cast<HLOCAL>(SecurityDescriptor)); } if( AccessControlNew ) { LocalFree(reinterpret_cast<HLOCAL>(AccessControlNew)); } } bool DLLInjectRemote(uint32_t ProcessID, const std::wstring& DLLpath) { const std::size_t DLLPathSize = ((DLLpath.size() + 1) * sizeof(wchar_t)); std::uint32_t Result; if( !ProcessID ) { std::wcout << "Invalid Process ID: " << ProcessID << std::endl; return false; } if( GetFileAttributesW(DLLpath.c_str()) == INVALID_FILE_ATTRIBUTES ) { std::wcout << "DLL file: " << DLLpath << " does not exists" << std::endl; return false; } SetAccessControl(DLLpath, L"S-1-15-2-1"); void* ProcLoadLibrary = reinterpret_cast<void*>( GetProcAddress(GetModuleHandleW(L"kernel32.dll"), "LoadLibraryW") ); if( !ProcLoadLibrary ) { std::wcout << "Unable to find LoadLibraryW procedure" << std::endl; return false; } void* Process = OpenProcess(PROCESS_ALL_ACCESS, false, ProcessID); if( Process == nullptr ) { std::wcout << "Unable to open process ID" << ProcessID << " for writing" << std::endl; return false; } void* VirtualAlloc = reinterpret_cast<void*>( VirtualAllocEx( Process, nullptr, DLLPathSize, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE ) ); if( VirtualAlloc == nullptr ) { std::wcout << "Unable to remotely allocate memory" << std::endl; CloseHandle(Process); return false; } std::size_t BytesWritten = 0; Result = WriteProcessMemory( Process, VirtualAlloc, DLLpath.data(), DLLPathSize, &BytesWritten ); if( Result == 0 ) { std::wcout << "Unable to write process memory" << std::endl; CloseHandle(Process); return false; } if( BytesWritten != DLLPathSize ) { std::wcout << "Failed to write remote DLL path name" << std::endl; CloseHandle(Process); return false; } void* RemoteThread = CreateRemoteThread( Process, nullptr, 0, reinterpret_cast<LPTHREAD_START_ROUTINE>(ProcLoadLibrary), VirtualAlloc, 0, nullptr ); // Wait for remote thread to finish if( RemoteThread ) { // Explicitly wait for LoadLibraryW to complete before releasing memory // avoids causing a remote memory leak WaitForSingleObject(RemoteThread, INFINITE); CloseHandle(RemoteThread); } else { // Failed to create thread std::wcout << "Unable to create remote thread" << std::endl; } VirtualFreeEx(Process, VirtualAlloc, 0, MEM_RELEASE); CloseHandle(Process); return true; } std::wstring GetRunningDirectory() { wchar_t RunPath[MAX_PATH]; GetModuleFileNameW(GetModuleHandleW(nullptr), RunPath, MAX_PATH); PathRemoveFileSpecW(RunPath); return std::wstring(RunPath); } <|endoftext|>
<commit_before>// ********************************************************************************** // OLED display management source file for remora project // ********************************************************************************** // Creative Commons Attrib Share-Alike License // You are free to use/extend but please abide with the CC-BY-SA license: // http://creativecommons.org/licenses/by-sa/4.0/ // // Written by Charles-Henri Hallard (http://hallard.me) // // History : V1.00 2015-01-22 - First release // // 15/09/2015 Charles-Henri Hallard : Ajout compatibilité ESP8266 // // All text above must be included in any redistribution. // ********************************************************************************** #include "display.h" // Instantiate OLED (no reset pin) Adafruit_SSD1306 display(-1); // Différents état de l'affichage possible const char * screen_name[] = {"RF", "System", "Teleinfo"}; screen_e screen_state; /* ====================================================================== Function: displaySplash Purpose : display setup splash screen OLED screen Input : - Output : - Comments: - ====================================================================== */ void display_splash(void) { display.clearDisplay() ; display.setTextSize(1); display.setTextColor(WHITE); display.setCursor(0,0); display.setTextSize(2); display.print(" REMORA\n"); display.print("Fil Pilote"); display.display(); } /* ====================================================================== Function: displaySys Purpose : display Téléinfo related information on OLED screen Input : - Output : - Comments: - ====================================================================== */ void displayTeleinfo(void) { uint percent = 0; // Effacer le buffer de l'affichage display.clearDisplay(); display.setTextSize(1); display.setTextColor(WHITE); display.setCursor(0,0); // si en heure pleine inverser le texte sur le compteur HP if (ptec == PTEC_HP ) display.setTextColor(BLACK, WHITE); // 'inverted' text display.print("Pleines "); display.printf("%09ld\n", myindexHP); display.setTextColor(WHITE); // normaltext // si en heure creuse inverser le texte sur le compteur HC if (ptec == PTEC_HC ) display.setTextColor(BLACK, WHITE); // 'inverted' text display.print("Creuses "); display.printf("%09ld\n", myindexHC); display.setTextColor(WHITE); // normaltext // Poucentrage de la puissance totale percent = (uint) myiInst * 100 / myisousc ; //Serial.print("myiInst="); Serial.print(myiInst); //Serial.print(" myisousc="); Serial.print(myisousc); //Serial.print(" percent="); Serial.println(percent); // Information additionelles display.printf("%d W %d%% %3d A", mypApp, percent, myiInst); // etat des fils pilotes display.setCursor(0,32); display.setTextSize(2); #ifdef SPARK display.printf("%02d:%02d:%02d",Time.hour(),Time.minute(),Time.second()); #endif display.setCursor(0,48); display.printf("%s %c", etatFP, etatrelais+'0' ); // Bargraphe de puissance display.drawVerticalBargraph(114,0,12,40,1, percent); display.setTextColor(BLACK, WHITE); // 'inverted' text } /* ====================================================================== Function: displaySys Purpose : display system related information on OLED screen Input : - Output : - Comments: - ====================================================================== */ void displaySys(void) { // To DO } /* ====================================================================== Function: displayRf Purpose : display RF related information on OLED screen Input : - Output : - Comments: - ====================================================================== */ void displayRf(void) {/* int16_t percent; display.printf("RF69 G%d I%d", NETWORK_ID, NODE_ID); // rssi range 0 (0%) to 115 (100%) percent = ((module.rssi+115) * 100) / 115; //displayClearline(current_line); //display.setCursor(0,current_line); //display.print(F("[")); //display.print(module.size); display.printf("G%d I%d %d%%\n", module.groupid, module.nodeid,percent); display.printf("[%02X] ", module.size); byte n = module.size; uint8_t * p = module.data; // Max 4 data per line on LCD if (n>12) n=12; for (byte i = 0; i < n; ++i) display.printf("%02X ", *p++); //display.drawHorizontalBargraph(106,current_line+1, 22, 6, 1, percent); display.printf("%d%% ", percent); */ } /* ====================================================================== Function: display_setup Purpose : prepare and init stuff, configuration, .. Input : - Output : true if OLED module found, false otherwise Comments: - ====================================================================== */ bool display_setup(void) { bool ret = false; Serial.print("Initializing OLED..."); // Par defaut affichage des infos de téléinfo screen_state = screen_teleinfo; // Init et detection des modules I2C if (!i2c_detect(OLED_I2C_ADDRESS)) { Serial.println("Not found!"); } else { Serial.println("OK!"); // initialize with the I2C addr for the 128x64 display.begin(OLED_I2C_ADDRESS); display.clearDisplay() ; display.display(); ret = true; } return (ret); } /* ====================================================================== Function: display_loop Purpose : main loop for OLED display Input : - Output : - Comments: - ====================================================================== */ void display_loop(void) { display.setCursor(0,0); if (screen_state==screen_sys) displaySys(); else if (screen_state==screen_rf) displayRf(); else if (screen_state==screen_teleinfo) displayTeleinfo(); // Affichage physique sur l'écran display.display(); } <commit_msg>Heartbeat si pas de Teleinfo<commit_after>// ********************************************************************************** // OLED display management source file for remora project // ********************************************************************************** // Creative Commons Attrib Share-Alike License // You are free to use/extend but please abide with the CC-BY-SA license: // http://creativecommons.org/licenses/by-sa/4.0/ // // Written by Charles-Henri Hallard (http://hallard.me) // // History : V1.00 2015-01-22 - First release // // 15/09/2015 Charles-Henri Hallard : Ajout compatibilité ESP8266 // // All text above must be included in any redistribution. // ********************************************************************************** #include "display.h" // Instantiate OLED (no reset pin) Adafruit_SSD1306 display(-1); // Différents état de l'affichage possible const char * screen_name[] = {"RF", "System", "Teleinfo"}; screen_e screen_state; /* ====================================================================== Function: displaySplash Purpose : display setup splash screen OLED screen Input : - Output : - Comments: - ====================================================================== */ void display_splash(void) { display.clearDisplay() ; display.setTextSize(1); display.setTextColor(WHITE); display.setCursor(0,0); display.setTextSize(2); display.print(" REMORA\n"); display.print("Fil Pilote"); display.display(); } /* ====================================================================== Function: displaySys Purpose : display Téléinfo related information on OLED screen Input : - Output : - Comments: - ====================================================================== */ void displayTeleinfo(void) { uint percent = 0; // Effacer le buffer de l'affichage display.clearDisplay(); display.setTextSize(1); display.setTextColor(WHITE); display.setCursor(0,0); // si en heure pleine inverser le texte sur le compteur HP if (ptec == PTEC_HP ) display.setTextColor(BLACK, WHITE); // 'inverted' text display.print("Pleines "); display.printf("%09ld\n", myindexHP); display.setTextColor(WHITE); // normaltext // si en heure creuse inverser le texte sur le compteur HC if (ptec == PTEC_HC ) display.setTextColor(BLACK, WHITE); // 'inverted' text display.print("Creuses "); display.printf("%09ld\n", myindexHC); display.setTextColor(WHITE); // normaltext // Poucentrage de la puissance totale percent = (uint) myiInst * 100 / myisousc ; //Serial.print("myiInst="); Serial.print(myiInst); //Serial.print(" myisousc="); Serial.print(myisousc); //Serial.print(" percent="); Serial.println(percent); // Information additionelles display.printf("%d W %d%% %3d A", mypApp, percent, myiInst); // etat des fils pilotes display.setCursor(0,32); display.setTextSize(2); #ifdef SPARK display.printf("%02d:%02d:%02d",Time.hour(),Time.minute(),Time.second()); #endif display.setCursor(0,48); display.printf("%s %c", etatFP, etatrelais+'0' ); // Bargraphe de puissance display.drawVerticalBargraph(114,0,12,40,1, percent); display.setTextColor(BLACK, WHITE); // 'inverted' text } /* ====================================================================== Function: displaySys Purpose : display system related information on OLED screen Input : - Output : - Comments: - ====================================================================== */ void displaySys(void) { // To DO } /* ====================================================================== Function: displayRf Purpose : display RF related information on OLED screen Input : - Output : - Comments: - ====================================================================== */ void displayRf(void) {/* int16_t percent; display.printf("RF69 G%d I%d", NETWORK_ID, NODE_ID); // rssi range 0 (0%) to 115 (100%) percent = ((module.rssi+115) * 100) / 115; //displayClearline(current_line); //display.setCursor(0,current_line); //display.print(F("[")); //display.print(module.size); display.printf("G%d I%d %d%%\n", module.groupid, module.nodeid,percent); display.printf("[%02X] ", module.size); byte n = module.size; uint8_t * p = module.data; // Max 4 data per line on LCD if (n>12) n=12; for (byte i = 0; i < n; ++i) display.printf("%02X ", *p++); //display.drawHorizontalBargraph(106,current_line+1, 22, 6, 1, percent); display.printf("%d%% ", percent); */ } /* ====================================================================== Function: display_setup Purpose : prepare and init stuff, configuration, .. Input : - Output : true if OLED module found, false otherwise Comments: - ====================================================================== */ bool display_setup(void) { bool ret = false; Serial.print("Initializing OLED..."); // Par defaut affichage des infos de téléinfo screen_state = screen_teleinfo; // Init et detection des modules I2C if (!i2c_detect(OLED_I2C_ADDRESS)) { Serial.println("Not found!"); } else { Serial.println("OK!"); // initialize with the I2C addr for the 128x64 display.begin(OLED_I2C_ADDRESS); display.clearDisplay() ; display.display(); ret = true; } return (ret); } /* ====================================================================== Function: display_loop Purpose : main loop for OLED display Input : - Output : - Comments: - ====================================================================== */ void display_loop(void) { // Si pas de heartbeat via la teleinfo, le faire // via l'affichage #ifndef MOD_TELEINFO LedRGBON(COLOR_BLUE); #endif display.setCursor(0,0); if (screen_state==screen_sys) displaySys(); else if (screen_state==screen_rf) displayRf(); else if (screen_state==screen_teleinfo) displayTeleinfo(); // Affichage physique sur l'écran display.display(); #ifndef MOD_TELEINFO LedRGBOFF(); #endif } <|endoftext|>
<commit_before>#include "clock.h" #include <errno.h> #include <time.h> namespace RPiClock { int32_t setDelayNs(const int32_t durationNs) { const int32_t startNs = getNowNs(); if (startNs == -1) { return -1; } while (1) { int32_t stopNs = getNowNs(); if (stopNs == -1) { return -1; } if (getDurationNs(startNs, stopNs) >= durationNs) { break; } } return 0; } int32_t getDurationNs(const int32_t startNs, const int32_t stopNs) { int32_t durationNs = stopNs - startNs; if (durationNs < 0) { durationNs += 1000000000; } return durationNs; } int32_t getNowNs(void) { #ifndef __MACH__ struct timespec now; if (clock_gettime(CLOCK_REALTIME, &now) == -1) { return -1; } return now.tv_nsec; #else errno = EPERM; return -1; #endif } } <commit_msg>Update src/clock.cc<commit_after>#include "clock.h" #include <time.h> #ifdef __MACH__ #include <errno.h> #endif namespace RPiClock { int32_t setDelayNs(const int32_t durationNs) { const int32_t startNs = getNowNs(); if (startNs == -1) { return -1; } while (1) { int32_t stopNs = getNowNs(); if (stopNs == -1) { return -1; } if (getDurationNs(startNs, stopNs) >= durationNs) { break; } } return 0; } int32_t getDurationNs(const int32_t startNs, const int32_t stopNs) { int32_t durationNs = stopNs - startNs; if (durationNs < 0) { durationNs += 1000000000; } return durationNs; } int32_t getNowNs(void) { #ifndef __MACH__ struct timespec now; if (clock_gettime(CLOCK_REALTIME, &now) == -1) { return -1; } return now.tv_nsec; #else errno = EPERM; return -1; #endif } } <|endoftext|>
<commit_before>// Print each number in the range specified by two integers. #include <iostream> int main() { int val_small = 0, val_big = 0; std::cout << "please input two integers:"; std::cin >> val_small >> val_big; if (val_small > val_big) { std::swap(val_small,val_big); } int temp = val_small; // preserve the value of val_small! while (temp <= val_big) { std::cout << temp++ << std::endl; } return 0; } <commit_msg>Update ex1_11.cpp<commit_after>// Print each number in the range specified by two integers. #include <iostream> int main() { int small = 0, big = 0; std::cout << "please input two integers:\n"; std::cin >> small >> big; if (small > big) std::swap(small, big); for (int curr = small; curr != big; ++curr) std::cout << curr; return 0; } <|endoftext|>
<commit_before>/* @Copyright Barrett Adair 2015-2017 Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt) */ #ifndef BOOST_CLBL_TRTS_REMOVE_MEMBER_CONST_HPP #define BOOST_CLBL_TRTS_REMOVE_MEMBER_CONST_HPP #include <boost/callable_traits/detail/core.hpp> namespace boost { namespace callable_traits { //[ remove_member_const_hpp /*` [section:ref_remove_member_const remove_member_const] [heading Header] ``#include <boost/callable_traits/remove_member_const.hpp>`` [heading Definition] */ template<typename T> using remove_member_const_t = //see below //<- detail::try_but_fail_if_invalid< typename detail::traits<T>::remove_member_const, member_qualifiers_are_illegal_for_this_type>; namespace detail { template<typename T, typename = std::false_type> struct remove_member_const_impl {}; template<typename T> struct remove_member_const_impl <T, typename std::is_same< remove_member_const_t<T>, detail::dummy>::type> { using type = remove_member_const_t<T>; }; } //-> template<typename T> struct remove_member_const : detail::remove_member_const_impl<T> {}; //<- }} // namespace boost::callable_traits //-> /*` [heading Constraints] * `T` must be a function type or a member function pointer type * If `T` is a pointer, it may not be cv/ref qualified [heading Behavior] * A substitution failure occurs if the constraints are violated. * Removes the member `const` qualifier from `T`, if present. [heading Input/Output Examples] [table [[`T`] [`remove_member_const_t<T>`]] [[`int() const`] [`int()`]] [[`int(foo::*)() const`] [`int(foo::*)()`]] [[`int(foo::*)() const &`] [`int(foo::*)() &`]] [[`int(foo::*)() const &&`] [`int(foo::*)() &&`]] [[`int(foo::*)() const`] [`int(foo::*)()`]] [[`int(foo::*)() const volatile`] [`int(foo::*)() volatile`]] [[`int`] [(substitution failure)]] [[`int (&)()`] [(substitution failure)]] [[`int (*)()`] [(substitution failure)]] [[`int foo::*`] [(substitution failure)]] [[`int (foo::* const)()`] [(substitution failure)]] ] [heading Example Program] [import ../example/remove_member_const.cpp] [remove_member_const] [endsect] */ //] #endif // #ifndef BOOST_CLBL_TRTS_REMOVE_MEMBER_CONST_HPP <commit_msg>Delete remove_member_const.hpp<commit_after><|endoftext|>
<commit_before>/**************************************************************************** * Copyright (c) 2012-2018 by the DataTransferKit authors * * All rights reserved. * * * * This file is part of the DataTransferKit library. DataTransferKit is * * distributed under a BSD 3-clause license. For the licensing terms see * * the LICENSE file in the top-level directory. * * * * SPDX-License-Identifier: BSD-3-Clause * ****************************************************************************/ /*! * \file tstMapInterface.cpp * \author Stuart Slattery * \brief DTK view unit tests. */ //---------------------------------------------------------------------------// #include <DTK_C_API.h> #include <DTK_DBC.hpp> #include <DTK_ParallelTraits.hpp> #include <Teuchos_DefaultComm.hpp> #include <Teuchos_DefaultMpiComm.hpp> #include <Teuchos_UnitTestHarness.hpp> #include <Kokkos_Core.hpp> #include <memory> //---------------------------------------------------------------------------// // User implementation template <class Space> struct TestUserData { Kokkos::View<double * [3], Space> coords; Kokkos::View<double *, Space> field; TestUserData( const int size ) : coords( "coords", size ) , field( "field", size ) { } }; template <class Space> void nodeListSize( void *user_data, unsigned *space_dim, size_t *local_num_nodes ) { TestUserData<Space> *data = static_cast<TestUserData<Space> *>( user_data ); *space_dim = data->coords.extent( 1 ); *local_num_nodes = data->coords.extent( 0 ); } template <class Space> void nodeListData( void *user_data, Coordinate *coords ) { TestUserData<Space> *data = static_cast<TestUserData<Space> *>( user_data ); int num_node = data->coords.extent( 0 ); for ( unsigned n = 0; n < data->coords.extent( 0 ); ++n ) for ( unsigned d = 0; d < data->coords.extent( 1 ); ++d ) coords[num_node * d + n] = data->coords( n, d ); } template <class Space> void fieldSize( void *user_data, const char *field_name, unsigned *field_dimension, size_t *local_num_dofs ) { TestUserData<Space> *data = static_cast<TestUserData<Space> *>( user_data ); *field_dimension = 1; *local_num_dofs = data->field.extent( 0 ); } template <class Space> void pullField( void *user_data, const char *, double *field_dofs ) { TestUserData<Space> *data = static_cast<TestUserData<Space> *>( user_data ); for ( unsigned i = 0; i < data->field.extent( 0 ); ++i ) field_dofs[i] = data->field( i ); } template <class Space> void pushField( void *user_data, const char *, const double *field_dofs ) { TestUserData<Space> *data = static_cast<TestUserData<Space> *>( user_data ); for ( unsigned i = 0; i < data->field.extent( 0 ); ++i ) data->field( i ) = field_dofs[i]; } //---------------------------------------------------------------------------// // Test execution space enumeration selector. template <class Space> struct SpaceSelector; #if defined( KOKKOS_ENABLE_SERIAL ) template <> struct SpaceSelector<DataTransferKit::Serial> { static constexpr DTK_ExecutionSpace value() { return DTK_SERIAL; } }; #endif #if defined( KOKKOS_ENABLE_OPENMP ) template <> struct SpaceSelector<DataTransferKit::OpenMP> { static constexpr DTK_ExecutionSpace value() { return DTK_OPENMP; } }; #endif #if defined( KOKKOS_ENABLE_SERIAL ) || defined( KOKKOS_ENABLE_OPENMP ) template <> struct SpaceSelector<DataTransferKit::HostSpace> { static constexpr DTK_MemorySpace value() { return DTK_HOST_SPACE; } }; #endif #if defined( KOKKOS_ENABLE_CUDA ) template <> struct SpaceSelector<DataTransferKit::Cuda> { static constexpr DTK_ExecutionSpace value() { return DTK_CUDA; } }; template <> struct SpaceSelector<DataTransferKit::CudaUVMSpace> { static constexpr DTK_MemorySpace value() { return DTK_CUDAUVM_SPACE; } }; #endif //---------------------------------------------------------------------------// // Run the test. template <class MapSpace, class SourceSpace, class TargetSpace> void test( bool &success, Teuchos::FancyOStream &out ) { // Initialize DTK. The test harness initializes kokkos already. DTK_initialize(); TEST_EQUALITY( errno, DTK_SUCCESS ); // Check error handling on a bad map. DTK_MapHandle bad_handle = nullptr; DTK_applyMap( bad_handle, "bad", "bad" ); TEST_EQUALITY( errno, DTK_INVALID_HANDLE ); DTK_destroyMap( bad_handle ); TEST_EQUALITY( errno, DTK_INVALID_HANDLE ); // Get the communicator auto teuchos_comm = Teuchos::DefaultComm<int>::getComm(); // Create a source and target data set. int num_point = 1000; auto src_data = std::make_shared<TestUserData<SourceSpace>>( num_point ); auto tgt_data = std::make_shared<TestUserData<TargetSpace>>( num_point ); // Assign source and target points and some field data. Make the points // the same for now to test the nearest neighbor operator. Invert the rank // though so at least they live on different processors. int comm_rank = teuchos_comm->getRank(); int inverse_rank = teuchos_comm->getSize() - comm_rank - 1; for ( int p = 0; p < num_point; ++p ) { for ( int d = 0; d < 3; ++d ) { src_data->coords( p, d ) = 1.0 * p + comm_rank * num_point; tgt_data->coords( p, d ) = 1.0 * p + inverse_rank * num_point; } src_data->field( p ) = 1.0 * p + comm_rank * num_point; tgt_data->field( p ) = 0.0; } // Create the source user application instance. auto src_handle = DTK_createUserApplication( SpaceSelector<SourceSpace>::value() ); TEST_EQUALITY( errno, DTK_SUCCESS ); DTK_setUserFunction( src_handle, DTK_NODE_LIST_SIZE_FUNCTION, ( void ( * )() ) & nodeListSize<SourceSpace>, src_data.get() ); TEST_EQUALITY( errno, DTK_SUCCESS ); DTK_setUserFunction( src_handle, DTK_NODE_LIST_DATA_FUNCTION, ( void ( * )() ) & nodeListData<SourceSpace>, src_data.get() ); TEST_EQUALITY( errno, DTK_SUCCESS ); DTK_setUserFunction( src_handle, DTK_FIELD_SIZE_FUNCTION, ( void ( * )() ) & fieldSize<SourceSpace>, src_data.get() ); TEST_EQUALITY( errno, DTK_SUCCESS ); DTK_setUserFunction( src_handle, DTK_PULL_FIELD_DATA_FUNCTION, ( void ( * )() ) & pullField<SourceSpace>, src_data.get() ); TEST_EQUALITY( errno, DTK_SUCCESS ); // Create the target user application instance. auto tgt_handle = DTK_createUserApplication( SpaceSelector<TargetSpace>::value() ); TEST_EQUALITY( errno, DTK_SUCCESS ); DTK_setUserFunction( tgt_handle, DTK_NODE_LIST_SIZE_FUNCTION, ( void ( * )() ) & nodeListSize<TargetSpace>, tgt_data.get() ); TEST_EQUALITY( errno, DTK_SUCCESS ); DTK_setUserFunction( tgt_handle, DTK_NODE_LIST_DATA_FUNCTION, ( void ( * )() ) & nodeListData<TargetSpace>, tgt_data.get() ); TEST_EQUALITY( errno, DTK_SUCCESS ); DTK_setUserFunction( tgt_handle, DTK_FIELD_SIZE_FUNCTION, ( void ( * )() ) & fieldSize<TargetSpace>, tgt_data.get() ); TEST_EQUALITY( errno, DTK_SUCCESS ); DTK_setUserFunction( tgt_handle, DTK_PUSH_FIELD_DATA_FUNCTION, ( void ( * )() ) & pushField<TargetSpace>, tgt_data.get() ); TEST_EQUALITY( errno, DTK_SUCCESS ); auto comm = Teuchos::getRawMpiComm( *teuchos_comm ); // Check valid syntax in map create for ( std::string const options : { R"({ "Map Type": "Nearest Neighbor" })", R"({ "Map Type": "NN" })", R"({ "Map Type": "Moving Least Squares" })", R"({ "Map Type": "MLS" })", R"({ "Map Type": "MLS", "Order": "Linear" })", R"({ "Map Type": "MLS", "Order": "1" })", R"({ "Map Type": "MLS", "Order": 1 })", // doesn't have to be // double quoted R"({ "Map Type": "MLS", "Order": "Quadratic" })", R"({ "Map Type": "MLS", "Order": "2" })", } ) { auto map_handle = DTK_createMap( SpaceSelector<MapSpace>::value(), comm, src_handle, tgt_handle, options.c_str() ); TEST_EQUALITY( errno, DTK_SUCCESS ); DTK_destroyMap( map_handle ); TEST_EQUALITY( errno, DTK_SUCCESS ); } // Check invalid syntax in map create for ( std::string const options : { R"({ "Map Type": "Nearest Neighbor " })", // trailing whitespace R"({ "Map Type": "nearest neighbor" })", // first letter not // capitalized R"({ "Map Type": "mls" })", // lowercase alias not defined R"("Map Type": "Moving Least Squares")", // missing surrounding // curly brackets R"({ "Map Type"="Moving Least Squares" })", // equal sign instead // of colon R"({ "Map Type": "Moving Least Squares"; "hello": "world")", // semicolon // instead // of // comma R"({ })", // empty JSON object R"({ "hello": "world"})", // "Map Type" is missing R"({ "map type": "MLS"})", // first letter not capitalized } ) { TEST_THROW( DTK_createMap( SpaceSelector<MapSpace>::value(), comm, src_handle, tgt_handle, options.c_str() ), DataTransferKit::DataTransferKitException ); } // Check map apply for ( std::string const options : { R"({ "Map Type": "Nearest Neighbor" })", R"({ "Map Type": "Moving Least Squares" })", } ) { auto map_handle = DTK_createMap( SpaceSelector<MapSpace>::value(), comm, src_handle, tgt_handle, options.c_str() ); TEST_EQUALITY( errno, DTK_SUCCESS ); DTK_applyMap( map_handle, "dummy", "dummy" ); TEST_EQUALITY( errno, DTK_SUCCESS ); double const relative_tolerance = 1e-14; // NOTE adding the same value to both lhs and rhs to resolve floating // point comparison issues with zero using Teuchos assertion macro double const shift_from_zero = 3.14; for ( int p = 0; p < num_point; ++p ) { TEST_FLOATING_EQUALITY( tgt_data->field( p ) + shift_from_zero, 1.0 * p + inverse_rank * num_point + shift_from_zero, relative_tolerance ); } DTK_destroyMap( map_handle ); TEST_EQUALITY( errno, DTK_SUCCESS ); } DTK_destroyUserApplication( src_handle ); TEST_EQUALITY( errno, DTK_SUCCESS ); DTK_destroyUserApplication( tgt_handle ); TEST_EQUALITY( errno, DTK_SUCCESS ); DTK_finalize(); TEST_EQUALITY( errno, DTK_SUCCESS ); } //---------------------------------------------------------------------------// // TESTS //---------------------------------------------------------------------------// #if defined( KOKKOS_ENABLE_SERIAL ) TEUCHOS_UNIT_TEST( MapInterface, Serial ) { test<DataTransferKit::Serial, DataTransferKit::HostSpace, DataTransferKit::HostSpace>( success, out ); } #endif //---------------------------------------------------------------------------// #if defined( KOKKOS_ENABLE_OPENMP ) TEUCHOS_UNIT_TEST( MapInterface, OpenMP ) { test<DataTransferKit::OpenMP, DataTransferKit::HostSpace, DataTransferKit::HostSpace>( success, out ); } #endif //---------------------------------------------------------------------------// #if defined( KOKKOS_ENABLE_CUDA ) TEUCHOS_UNIT_TEST( MapInterface, Cuda ) { test<DataTransferKit::Cuda, DataTransferKit::CudaUVMSpace, DataTransferKit::CudaUVMSpace>( success, out ); } #endif //---------------------------------------------------------------------------// #if defined( KOKKOS_ENABLE_SERIAL ) && defined( KOKKOS_ENABLE_CUDA ) TEUCHOS_UNIT_TEST( MapInterface, SerialAndCuda ) { test<DataTransferKit::Serial, DataTransferKit::CudaUVMSpace, DataTransferKit::CudaUVMSpace>( success, out ); test<DataTransferKit::Serial, DataTransferKit::HostSpace, DataTransferKit::CudaUVMSpace>( success, out ); test<DataTransferKit::Serial, DataTransferKit::CudaUVMSpace, DataTransferKit::HostSpace>( success, out ); } #endif //---------------------------------------------------------------------------// #if defined( KOKKOS_ENABLE_OPENMP ) && defined( KOKKOS_ENABLE_CUDA ) TEUCHOS_UNIT_TEST( MapInterface, OpenmpAndCuda ) { test<DataTransferKit::OpenMP, DataTransferKit::CudaUVMSpace, DataTransferKit::CudaUVMSpace>( success, out ); test<DataTransferKit::OpenMP, DataTransferKit::HostSpace, DataTransferKit::CudaUVMSpace>( success, out ); test<DataTransferKit::OpenMP, DataTransferKit::CudaUVMSpace, DataTransferKit::HostSpace>( success, out ); } #endif //---------------------------------------------------------------------------// #if ( defined( KOKKOS_ENABLE_SERIAL ) || defined( KOKKOS_ENABLE_OPENMP ) ) && \ defined( KOKKOS_ENABLE_CUDA ) TEUCHOS_UNIT_TEST( MapInterface, HostAndCuda ) { test<DataTransferKit::Cuda, DataTransferKit::HostSpace, DataTransferKit::CudaUVMSpace>( success, out ); test<DataTransferKit::Cuda, DataTransferKit::CudaUVMSpace, DataTransferKit::HostSpace>( success, out ); } #endif //---------------------------------------------------------------------------// // end tstMapInterface.cpp //---------------------------------------------------------------------------// <commit_msg>More tests with invalid options arg to map creation<commit_after>/**************************************************************************** * Copyright (c) 2012-2018 by the DataTransferKit authors * * All rights reserved. * * * * This file is part of the DataTransferKit library. DataTransferKit is * * distributed under a BSD 3-clause license. For the licensing terms see * * the LICENSE file in the top-level directory. * * * * SPDX-License-Identifier: BSD-3-Clause * ****************************************************************************/ /*! * \file tstMapInterface.cpp * \author Stuart Slattery * \brief DTK view unit tests. */ //---------------------------------------------------------------------------// #include <DTK_C_API.h> #include <DTK_DBC.hpp> #include <DTK_ParallelTraits.hpp> #include <Teuchos_DefaultComm.hpp> #include <Teuchos_DefaultMpiComm.hpp> #include <Teuchos_UnitTestHarness.hpp> #include <Kokkos_Core.hpp> #include <memory> //---------------------------------------------------------------------------// // User implementation template <class Space> struct TestUserData { Kokkos::View<double * [3], Space> coords; Kokkos::View<double *, Space> field; TestUserData( const int size ) : coords( "coords", size ) , field( "field", size ) { } }; template <class Space> void nodeListSize( void *user_data, unsigned *space_dim, size_t *local_num_nodes ) { TestUserData<Space> *data = static_cast<TestUserData<Space> *>( user_data ); *space_dim = data->coords.extent( 1 ); *local_num_nodes = data->coords.extent( 0 ); } template <class Space> void nodeListData( void *user_data, Coordinate *coords ) { TestUserData<Space> *data = static_cast<TestUserData<Space> *>( user_data ); int num_node = data->coords.extent( 0 ); for ( unsigned n = 0; n < data->coords.extent( 0 ); ++n ) for ( unsigned d = 0; d < data->coords.extent( 1 ); ++d ) coords[num_node * d + n] = data->coords( n, d ); } template <class Space> void fieldSize( void *user_data, const char *field_name, unsigned *field_dimension, size_t *local_num_dofs ) { TestUserData<Space> *data = static_cast<TestUserData<Space> *>( user_data ); *field_dimension = 1; *local_num_dofs = data->field.extent( 0 ); } template <class Space> void pullField( void *user_data, const char *, double *field_dofs ) { TestUserData<Space> *data = static_cast<TestUserData<Space> *>( user_data ); for ( unsigned i = 0; i < data->field.extent( 0 ); ++i ) field_dofs[i] = data->field( i ); } template <class Space> void pushField( void *user_data, const char *, const double *field_dofs ) { TestUserData<Space> *data = static_cast<TestUserData<Space> *>( user_data ); for ( unsigned i = 0; i < data->field.extent( 0 ); ++i ) data->field( i ) = field_dofs[i]; } //---------------------------------------------------------------------------// // Test execution space enumeration selector. template <class Space> struct SpaceSelector; #if defined( KOKKOS_ENABLE_SERIAL ) template <> struct SpaceSelector<DataTransferKit::Serial> { static constexpr DTK_ExecutionSpace value() { return DTK_SERIAL; } }; #endif #if defined( KOKKOS_ENABLE_OPENMP ) template <> struct SpaceSelector<DataTransferKit::OpenMP> { static constexpr DTK_ExecutionSpace value() { return DTK_OPENMP; } }; #endif #if defined( KOKKOS_ENABLE_SERIAL ) || defined( KOKKOS_ENABLE_OPENMP ) template <> struct SpaceSelector<DataTransferKit::HostSpace> { static constexpr DTK_MemorySpace value() { return DTK_HOST_SPACE; } }; #endif #if defined( KOKKOS_ENABLE_CUDA ) template <> struct SpaceSelector<DataTransferKit::Cuda> { static constexpr DTK_ExecutionSpace value() { return DTK_CUDA; } }; template <> struct SpaceSelector<DataTransferKit::CudaUVMSpace> { static constexpr DTK_MemorySpace value() { return DTK_CUDAUVM_SPACE; } }; #endif //---------------------------------------------------------------------------// // Run the test. template <class MapSpace, class SourceSpace, class TargetSpace> void test( bool &success, Teuchos::FancyOStream &out ) { // Initialize DTK. The test harness initializes kokkos already. DTK_initialize(); TEST_EQUALITY( errno, DTK_SUCCESS ); // Check error handling on a bad map. DTK_MapHandle bad_handle = nullptr; DTK_applyMap( bad_handle, "bad", "bad" ); TEST_EQUALITY( errno, DTK_INVALID_HANDLE ); DTK_destroyMap( bad_handle ); TEST_EQUALITY( errno, DTK_INVALID_HANDLE ); // Get the communicator auto teuchos_comm = Teuchos::DefaultComm<int>::getComm(); // Create a source and target data set. int num_point = 1000; auto src_data = std::make_shared<TestUserData<SourceSpace>>( num_point ); auto tgt_data = std::make_shared<TestUserData<TargetSpace>>( num_point ); // Assign source and target points and some field data. Make the points // the same for now to test the nearest neighbor operator. Invert the rank // though so at least they live on different processors. int comm_rank = teuchos_comm->getRank(); int inverse_rank = teuchos_comm->getSize() - comm_rank - 1; for ( int p = 0; p < num_point; ++p ) { for ( int d = 0; d < 3; ++d ) { src_data->coords( p, d ) = 1.0 * p + comm_rank * num_point; tgt_data->coords( p, d ) = 1.0 * p + inverse_rank * num_point; } src_data->field( p ) = 1.0 * p + comm_rank * num_point; tgt_data->field( p ) = 0.0; } // Create the source user application instance. auto src_handle = DTK_createUserApplication( SpaceSelector<SourceSpace>::value() ); TEST_EQUALITY( errno, DTK_SUCCESS ); DTK_setUserFunction( src_handle, DTK_NODE_LIST_SIZE_FUNCTION, ( void ( * )() ) & nodeListSize<SourceSpace>, src_data.get() ); TEST_EQUALITY( errno, DTK_SUCCESS ); DTK_setUserFunction( src_handle, DTK_NODE_LIST_DATA_FUNCTION, ( void ( * )() ) & nodeListData<SourceSpace>, src_data.get() ); TEST_EQUALITY( errno, DTK_SUCCESS ); DTK_setUserFunction( src_handle, DTK_FIELD_SIZE_FUNCTION, ( void ( * )() ) & fieldSize<SourceSpace>, src_data.get() ); TEST_EQUALITY( errno, DTK_SUCCESS ); DTK_setUserFunction( src_handle, DTK_PULL_FIELD_DATA_FUNCTION, ( void ( * )() ) & pullField<SourceSpace>, src_data.get() ); TEST_EQUALITY( errno, DTK_SUCCESS ); // Create the target user application instance. auto tgt_handle = DTK_createUserApplication( SpaceSelector<TargetSpace>::value() ); TEST_EQUALITY( errno, DTK_SUCCESS ); DTK_setUserFunction( tgt_handle, DTK_NODE_LIST_SIZE_FUNCTION, ( void ( * )() ) & nodeListSize<TargetSpace>, tgt_data.get() ); TEST_EQUALITY( errno, DTK_SUCCESS ); DTK_setUserFunction( tgt_handle, DTK_NODE_LIST_DATA_FUNCTION, ( void ( * )() ) & nodeListData<TargetSpace>, tgt_data.get() ); TEST_EQUALITY( errno, DTK_SUCCESS ); DTK_setUserFunction( tgt_handle, DTK_FIELD_SIZE_FUNCTION, ( void ( * )() ) & fieldSize<TargetSpace>, tgt_data.get() ); TEST_EQUALITY( errno, DTK_SUCCESS ); DTK_setUserFunction( tgt_handle, DTK_PUSH_FIELD_DATA_FUNCTION, ( void ( * )() ) & pushField<TargetSpace>, tgt_data.get() ); TEST_EQUALITY( errno, DTK_SUCCESS ); auto comm = Teuchos::getRawMpiComm( *teuchos_comm ); // Check valid syntax in map create for ( std::string const options : { R"({ "Map Type": "Nearest Neighbor" })", R"({ "Map Type": "NN" })", R"({ "Map Type": "Moving Least Squares" })", R"({ "Map Type": "MLS" })", R"({ "Map Type": "MLS", "Order": "Linear" })", R"({ "Map Type": "MLS", "Order": "1" })", R"({ "Map Type": "MLS", "Order": 1 })", // doesn't have to be // double quoted R"({ "Map Type": "MLS", "Order": "Quadratic" })", R"({ "Map Type": "MLS", "Order": "2" })", } ) { auto map_handle = DTK_createMap( SpaceSelector<MapSpace>::value(), comm, src_handle, tgt_handle, options.c_str() ); TEST_EQUALITY( errno, DTK_SUCCESS ); DTK_destroyMap( map_handle ); TEST_EQUALITY( errno, DTK_SUCCESS ); } // Check invalid syntax in map create for ( std::string const options : { R"({ "Map Type": "Nearest Neighbor " })", // trailing whitespace R"({ "Map Type": "nearest neighbor" })", // first letter not // capitalized R"({ "Map Type": "mls" })", // lowercase alias not defined R"("Map Type": "Moving Least Squares")", // missing surrounding // curly brackets R"({ "Map Type"="Moving Least Squares" })", // equal sign instead // of colon R"({ "Map Type": "Moving Least Squares"; "hello": "world")", // semicolon // instead // of // comma R"({ })", // empty JSON object R"({ "hello": "world"})", // "Map Type" is missing R"({ "map type": "MLS"})", // first letter not capitalized R"({ "Map Type": 3.14 })", // bad data R"({ "Map Type": "Is Not Defined Anywhere" })", // invalid value R"({ "Map Type": "MLS", "Order": 3 })", // order 3 not available R"({ "Map Type": "MLS", "Order": "Invalid" })", } ) { TEST_THROW( DTK_createMap( SpaceSelector<MapSpace>::value(), comm, src_handle, tgt_handle, options.c_str() ), DataTransferKit::DataTransferKitException ); } // Check map apply for ( std::string const options : { R"({ "Map Type": "Nearest Neighbor" })", R"({ "Map Type": "Moving Least Squares" })", } ) { auto map_handle = DTK_createMap( SpaceSelector<MapSpace>::value(), comm, src_handle, tgt_handle, options.c_str() ); TEST_EQUALITY( errno, DTK_SUCCESS ); DTK_applyMap( map_handle, "dummy", "dummy" ); TEST_EQUALITY( errno, DTK_SUCCESS ); double const relative_tolerance = 1e-14; // NOTE adding the same value to both lhs and rhs to resolve floating // point comparison issues with zero using Teuchos assertion macro double const shift_from_zero = 3.14; for ( int p = 0; p < num_point; ++p ) { TEST_FLOATING_EQUALITY( tgt_data->field( p ) + shift_from_zero, 1.0 * p + inverse_rank * num_point + shift_from_zero, relative_tolerance ); } DTK_destroyMap( map_handle ); TEST_EQUALITY( errno, DTK_SUCCESS ); } DTK_destroyUserApplication( src_handle ); TEST_EQUALITY( errno, DTK_SUCCESS ); DTK_destroyUserApplication( tgt_handle ); TEST_EQUALITY( errno, DTK_SUCCESS ); DTK_finalize(); TEST_EQUALITY( errno, DTK_SUCCESS ); } //---------------------------------------------------------------------------// // TESTS //---------------------------------------------------------------------------// #if defined( KOKKOS_ENABLE_SERIAL ) TEUCHOS_UNIT_TEST( MapInterface, Serial ) { test<DataTransferKit::Serial, DataTransferKit::HostSpace, DataTransferKit::HostSpace>( success, out ); } #endif //---------------------------------------------------------------------------// #if defined( KOKKOS_ENABLE_OPENMP ) TEUCHOS_UNIT_TEST( MapInterface, OpenMP ) { test<DataTransferKit::OpenMP, DataTransferKit::HostSpace, DataTransferKit::HostSpace>( success, out ); } #endif //---------------------------------------------------------------------------// #if defined( KOKKOS_ENABLE_CUDA ) TEUCHOS_UNIT_TEST( MapInterface, Cuda ) { test<DataTransferKit::Cuda, DataTransferKit::CudaUVMSpace, DataTransferKit::CudaUVMSpace>( success, out ); } #endif //---------------------------------------------------------------------------// #if defined( KOKKOS_ENABLE_SERIAL ) && defined( KOKKOS_ENABLE_CUDA ) TEUCHOS_UNIT_TEST( MapInterface, SerialAndCuda ) { test<DataTransferKit::Serial, DataTransferKit::CudaUVMSpace, DataTransferKit::CudaUVMSpace>( success, out ); test<DataTransferKit::Serial, DataTransferKit::HostSpace, DataTransferKit::CudaUVMSpace>( success, out ); test<DataTransferKit::Serial, DataTransferKit::CudaUVMSpace, DataTransferKit::HostSpace>( success, out ); } #endif //---------------------------------------------------------------------------// #if defined( KOKKOS_ENABLE_OPENMP ) && defined( KOKKOS_ENABLE_CUDA ) TEUCHOS_UNIT_TEST( MapInterface, OpenmpAndCuda ) { test<DataTransferKit::OpenMP, DataTransferKit::CudaUVMSpace, DataTransferKit::CudaUVMSpace>( success, out ); test<DataTransferKit::OpenMP, DataTransferKit::HostSpace, DataTransferKit::CudaUVMSpace>( success, out ); test<DataTransferKit::OpenMP, DataTransferKit::CudaUVMSpace, DataTransferKit::HostSpace>( success, out ); } #endif //---------------------------------------------------------------------------// #if ( defined( KOKKOS_ENABLE_SERIAL ) || defined( KOKKOS_ENABLE_OPENMP ) ) && \ defined( KOKKOS_ENABLE_CUDA ) TEUCHOS_UNIT_TEST( MapInterface, HostAndCuda ) { test<DataTransferKit::Cuda, DataTransferKit::HostSpace, DataTransferKit::CudaUVMSpace>( success, out ); test<DataTransferKit::Cuda, DataTransferKit::CudaUVMSpace, DataTransferKit::HostSpace>( success, out ); } #endif //---------------------------------------------------------------------------// // end tstMapInterface.cpp //---------------------------------------------------------------------------// <|endoftext|>