{"text":"\/*=========================================================================\n\n Program: ORFEO Toolbox\n Language: C++\n Date: $Date$\n Version: $Revision$\n\n\n Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.\n See OTBCopyright.txt for details.\n\n\n This software is distributed WITHOUT ANY WARRANTY; without even\n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n PURPOSE. See the above copyright notices for more information.\n\n=========================================================================*\/\n\n#include \"otbImage.h\"\n#include \"otbDrawLineSpatialObjectListFilter.h\"\n#include \"otbLineSpatialObjectList.h\"\n\n#include \"otbImageFileReader.h\"\n#include \"otbImageFileWriter.h\"\n\n\/\/ Software Guide : BeginCommandLineArgs\n\/\/ INPUTS: {QB_Suburb.png}\n\/\/ OUTPUTS: {QB_SuburbLSD.png}\n\/\/ Software Guide : EndCommandLineArgs\n\n\/\/ Software Guide : BeginLatex\n\/\/\n\/\/ This example illustrates the use of the\n\/\/ \\doxygen{otb}{LineSegmentDetector}\\cite{LSD}, also known as {\\em Lucy in the\n\/\/ Sky with Diamonds}.\n\/\/\n\/\/ The first step required to use this filter is to include its header file.\n\/\/\n\/\/ Software Guide : EndLatex\n\n\/\/ Software Guide : BeginCodeSnippet\n#include \"otbLineSegmentDetector.h\"\n\/\/ Software Guide : EndCodeSnippet\n\nint main( int argc, char * argv[] )\n{\n const char * infname = argv[1];\n const char * outfname = argv[2];\n \n typedef unsigned char InputPixelType;\n typedef double PrecisionType;\n const unsigned int Dimension = 2;\n \n\n\/\/ Software Guide : BeginLatex\n\/\/\n\/\/ As usual, we start by defining the types for the input image and\n\/\/ the image file reader.\n\/\/\n\/\/ Software Guide : EndLatex\n\n\/\/ Software Guide : BeginCodeSnippet \n typedef otb::Image< InputPixelType, Dimension > ImageType;\n typedef otb::ImageFileReader ReaderType;\n\/\/ Software Guide : EndCodeSnippet \n\/\/ Software Guide : BeginLatex\n\/\/\n\/\/ We instantiate the reader and set the file name for the input image.\n\/\/\n\/\/ Software Guide : EndLatex\n\n\/\/ Software Guide : BeginCodeSnippet \n\n ReaderType::Pointer reader = ReaderType::New();\n reader->SetFileName(infname);\n\/\/ Software Guide : EndCodeSnippet \n\/\/ Software Guide : BeginLatex\n\/\/\n\/\/ We define now the type for the segment detector filter. It is\n\/\/ templated over the input image type and the precision with which\n\/\/ the coordinates of the detected segments will be given. It is\n\/\/ recommended to set this precision to a real type. The output of the\n\/\/ filter will be a list of \\doxygen{itk}{LineSpatialObject}s.\n\/\/\n\/\/ Software Guide : EndLatex\n\n\/\/ Software Guide : BeginCodeSnippet \n \n typedef otb::LineSegmentDetector LsdFilterType;\n\n\n \n LsdFilterType::Pointer lsdFilter = LsdFilterType::New();\n\n \/\/ Software Guide : EndCodeSnippet \n\/\/ Software Guide : BeginLatex\n\/\/\n\/\/ In order to be able to display the results, we will draw the\n\/\/ detected segments on top of the input image. For this matter, we\n\/\/ will use the \\doxygen{otb}{DrawLineSpatialObjectListFilter} which\n\/\/ is templated over the input and output image types.\n\/\/\n\/\/ Software Guide : EndLatex\n\n\/\/ Software Guide : BeginCodeSnippet \n\n\n typedef otb::DrawLineSpatialObjectListFilter< ImageType,\n ImageType > DrawLineListType;\n DrawLineListType::Pointer drawLineFilter = DrawLineListType::New();\n\n\n \/\/ Software Guide : EndCodeSnippet \n\/\/ Software Guide : BeginLatex\n\/\/\n\/\/ We can now define the type for the writer, instantiate it and set\n\/\/ the file name for the output image.\n\/\/\n\/\/ Software Guide : EndLatex\n\n\/\/ Software Guide : BeginCodeSnippet \n\n typedef otb::ImageFileWriter WriterType;\n WriterType::Pointer writer = WriterType::New();\n writer->SetFileName(outfname);\n\n \/\/ Software Guide : EndCodeSnippet \n\/\/ Software Guide : BeginLatex\n\/\/\n\/\/ We plug the pipeline.\n\/\/\n\/\/ Software Guide : EndLatex\n\n\/\/ Software Guide : BeginCodeSnippet \n\n lsdFilter->SetInput(reader->GetOutput());\n writer->SetInput(drawLineFilter->GetOutput());\n\n drawLineFilter->SetInput(reader->GetOutput());\n drawLineFilter->SetInputLineSpatialObjectList(lsdFilter->GetOutput());\n\n \/\/ Software Guide : EndCodeSnippet \n\/\/ Software Guide : BeginLatex\n\/\/\n\/\/ Before calling the \\code{Update()} method of the writer in order to\n\/\/ trigger the pipeline execution, we call the\n\/\/ \\doxygen{GenerateOutputInformation()} of the reader, so the LSD\n\/\/ filter gets the information about image size and spacing.\n\/\/\n\/\/ Software Guide : EndLatex\n\n\/\/ Software Guide : BeginCodeSnippet \n\n reader->GenerateOutputInformation();\n writer->Update();\n\n \/\/ Software Guide : EndCodeSnippet \n\n \/\/ Software Guide : BeginLatex\n \/\/ Figure~\\ref{fig:LSD} shows the result of applying the line segment\n \/\/ detection to a small patch extracted from a VHR image.\n \/\/ \\begin{figure}\n \/\/ \\center\n \/\/ \\includegraphics[width=0.35\\textwidth]{QB_Suburb.eps}\n \/\/ \\includegraphics[width=0.35\\textwidth]{QB_SuburbLSD.eps}\n \/\/ \\itkcaption[LSD Application]{Result of applying the\n \/\/ \\doxygen{otb}{LineSegmentDetector} to a VHR image of a suburb.}\n \/\/ \\label{fig:LSD}\n \/\/ \\end{figure}\n \/\/\n \/\/ Software Guide : EndLatex\n\n \n return EXIT_SUCCESS;\n}\n\nENH LSD Example Test : Specify value to draw the lines over the image\/*=========================================================================\n\n Program: ORFEO Toolbox\n Language: C++\n Date: $Date$\n Version: $Revision$\n\n\n Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.\n See OTBCopyright.txt for details.\n\n\n This software is distributed WITHOUT ANY WARRANTY; without even\n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n PURPOSE. See the above copyright notices for more information.\n\n=========================================================================*\/\n\n#include \"otbImage.h\"\n#include \"otbDrawLineSpatialObjectListFilter.h\"\n#include \"otbLineSpatialObjectList.h\"\n\n#include \"otbImageFileReader.h\"\n#include \"otbImageFileWriter.h\"\n\n\/\/ Software Guide : BeginCommandLineArgs\n\/\/ INPUTS: {QB_Suburb.png}\n\/\/ OUTPUTS: {QB_SuburbLSD.png}\n\/\/ Software Guide : EndCommandLineArgs\n\n\/\/ Software Guide : BeginLatex\n\/\/\n\/\/ This example illustrates the use of the\n\/\/ \\doxygen{otb}{LineSegmentDetector}\\cite{LSD}, also known as {\\em Lucy in the\n\/\/ Sky with Diamonds}.\n\/\/\n\/\/ The first step required to use this filter is to include its header file.\n\/\/\n\/\/ Software Guide : EndLatex\n\n\/\/ Software Guide : BeginCodeSnippet\n#include \"otbLineSegmentDetector.h\"\n\/\/ Software Guide : EndCodeSnippet\n\nint main( int argc, char * argv[] )\n{\n const char * infname = argv[1];\n const char * outfname = argv[2];\n \n typedef unsigned char InputPixelType;\n typedef double PrecisionType;\n const unsigned int Dimension = 2;\n \n\n\/\/ Software Guide : BeginLatex\n\/\/\n\/\/ As usual, we start by defining the types for the input image and\n\/\/ the image file reader.\n\/\/\n\/\/ Software Guide : EndLatex\n\n\/\/ Software Guide : BeginCodeSnippet \n typedef otb::Image< InputPixelType, Dimension > ImageType;\n typedef otb::ImageFileReader ReaderType;\n\/\/ Software Guide : EndCodeSnippet \n\/\/ Software Guide : BeginLatex\n\/\/\n\/\/ We instantiate the reader and set the file name for the input image.\n\/\/\n\/\/ Software Guide : EndLatex\n\n\/\/ Software Guide : BeginCodeSnippet \n\n ReaderType::Pointer reader = ReaderType::New();\n reader->SetFileName(infname);\n\/\/ Software Guide : EndCodeSnippet \n\/\/ Software Guide : BeginLatex\n\/\/\n\/\/ We define now the type for the segment detector filter. It is\n\/\/ templated over the input image type and the precision with which\n\/\/ the coordinates of the detected segments will be given. It is\n\/\/ recommended to set this precision to a real type. The output of the\n\/\/ filter will be a list of \\doxygen{itk}{LineSpatialObject}s.\n\/\/\n\/\/ Software Guide : EndLatex\n\n\/\/ Software Guide : BeginCodeSnippet \n \n typedef otb::LineSegmentDetector LsdFilterType;\n\n\n \n LsdFilterType::Pointer lsdFilter = LsdFilterType::New();\n\n \/\/ Software Guide : EndCodeSnippet \n\/\/ Software Guide : BeginLatex\n\/\/\n\/\/ In order to be able to display the results, we will draw the\n\/\/ detected segments on top of the input image. For this matter, we\n\/\/ will use the \\doxygen{otb}{DrawLineSpatialObjectListFilter} which\n\/\/ is templated over the input and output image types.\n\/\/\n\/\/ Software Guide : EndLatex\n\n\/\/ Software Guide : BeginCodeSnippet \n\n\n typedef otb::DrawLineSpatialObjectListFilter< ImageType,\n ImageType > DrawLineListType;\n DrawLineListType::Pointer drawLineFilter = DrawLineListType::New();\n\n\n \/\/ Software Guide : EndCodeSnippet \n\/\/ Software Guide : BeginLatex\n\/\/\n\/\/ We can now define the type for the writer, instantiate it and set\n\/\/ the file name for the output image.\n\/\/\n\/\/ Software Guide : EndLatex\n\n\/\/ Software Guide : BeginCodeSnippet \n\n typedef otb::ImageFileWriter WriterType;\n WriterType::Pointer writer = WriterType::New();\n writer->SetFileName(outfname);\n\n \/\/ Software Guide : EndCodeSnippet \n\/\/ Software Guide : BeginLatex\n\/\/\n\/\/ We plug the pipeline.\n\/\/\n\/\/ Software Guide : EndLatex\n\n\/\/ Software Guide : BeginCodeSnippet \n\n lsdFilter->SetInput(reader->GetOutput());\n writer->SetInput(drawLineFilter->GetOutput());\n\n drawLineFilter->SetInput(reader->GetOutput());\n drawLineFilter->SetInputLineSpatialObjectList(lsdFilter->GetOutput());\n drawLineFilter->SetValue(1000);\n\n \/\/ Software Guide : EndCodeSnippet \n\/\/ Software Guide : BeginLatex\n\/\/\n\/\/ Before calling the \\code{Update()} method of the writer in order to\n\/\/ trigger the pipeline execution, we call the\n\/\/ \\doxygen{GenerateOutputInformation()} of the reader, so the LSD\n\/\/ filter gets the information about image size and spacing.\n\/\/\n\/\/ Software Guide : EndLatex\n\n\/\/ Software Guide : BeginCodeSnippet \n\n reader->GenerateOutputInformation();\n writer->Update();\n\n \/\/ Software Guide : EndCodeSnippet \n\n \/\/ Software Guide : BeginLatex\n \/\/ Figure~\\ref{fig:LSD} shows the result of applying the line segment\n \/\/ detection to a small patch extracted from a VHR image.\n \/\/ \\begin{figure}\n \/\/ \\center\n \/\/ \\includegraphics[width=0.35\\textwidth]{QB_Suburb.eps}\n \/\/ \\includegraphics[width=0.35\\textwidth]{QB_SuburbLSD.eps}\n \/\/ \\itkcaption[LSD Application]{Result of applying the\n \/\/ \\doxygen{otb}{LineSegmentDetector} to a VHR image of a suburb.}\n \/\/ \\label{fig:LSD}\n \/\/ \\end{figure}\n \/\/\n \/\/ Software Guide : EndLatex\n\n \n return EXIT_SUCCESS;\n}\n\n<|endoftext|>"} {"text":"#ifndef _DEFINES_H_\n#define _DEFINES_H_\n\n#define MAX_ROUNDS 1\n#define BOARD_W 10\n#define BOARD_H 10\n\n#define ATTACKERS_ALLOC 40\n#define DEFENDERS_ALLOC 100\n\n#define ATTACK_HEALTH 200\n#define ATTACK_POWER 50\n#define ATTACK_SPEED 1\n\n#define DEFENSE_HEALTH 100\n#define DEFENSE_POWER 10\n#define DEFENSE_SPEED 1\n\n#define PLAYER_HEALTH 1000\n#define PLAYER_POWER 1000\n#define PLAYER_SPEED 0\n\n\/\/ Where the attackers will respawn. This is relative to the board coordinates.\n#define RESPAWN_X 0\n#define RESPAWN_Y 0\n\n\/\/ The player's tower coordinate. The tower NEVER moves.\n#define PLAYER_X (BOARD_W - 1)\n#define PLAYER_Y (BOARD_H - 1)\n\n#define WINDOW_W 800\n#define WINDOW_H 600\n#define WINDOW_BPP 32\n\n#define GRID_W ((float)WINDOW_W \/ BOARD_W)\n#define GRID_H ((float)WINDOW_H \/ BOARD_H)\n\n\/\/ Score points.\n\n#define ADD_DESTROY_POINTS 150 \t\/\/ Give points for each enemy destroyed.\n#define ADD_LIFE_POINTS 3 \t\t\/\/ Give points for each life point kept.\n\n#define SUB_NUMBER_OF_TOWERS 20\t\/\/ Take points for each tower put.\n#define SUB_RESPAWN_BLOCK 2000\t\/\/ Penalize for blocking the respawn point with a tower.\n#define SUB_BLOCK_PATH 7000\t\/\/ Penalize for blocking all the paths from respawn to player's tower.\n#define SUB_TOWER_DESTROYED 4500 \/\/ Penalize for losing the game.\n\n\/\/ This value depends on the previous values.\n#define MAX_VALUE 8760\n#define MIN_VALUE -11500\n\n#define POPULATION_SIZE 100\n#define CHROM_LENGTH 100\n\n#endif \/\/_DEFINES_H_\nDefense tower attack power decreased from 10 to 8.#ifndef _DEFINES_H_\n#define _DEFINES_H_\n\n#define MAX_ROUNDS 1\n#define BOARD_W 10\n#define BOARD_H 10\n\n#define ATTACKERS_ALLOC 40\n#define DEFENDERS_ALLOC 100\n\n#define ATTACK_HEALTH 200\n#define ATTACK_POWER 50\n#define ATTACK_SPEED 1\n\n#define DEFENSE_HEALTH 100\n#define DEFENSE_POWER 8\n#define DEFENSE_SPEED 1\n\n#define PLAYER_HEALTH 1000\n#define PLAYER_POWER 1000\n#define PLAYER_SPEED 0\n\n\/\/ Where the attackers will respawn. This is relative to the board coordinates.\n#define RESPAWN_X 0\n#define RESPAWN_Y 0\n\n\/\/ The player's tower coordinate. The tower NEVER moves.\n#define PLAYER_X (BOARD_W - 1)\n#define PLAYER_Y (BOARD_H - 1)\n\n#define WINDOW_W 800\n#define WINDOW_H 600\n#define WINDOW_BPP 32\n\n#define GRID_W ((float)WINDOW_W \/ BOARD_W)\n#define GRID_H ((float)WINDOW_H \/ BOARD_H)\n\n\/\/ Score points.\n\n#define ADD_DESTROY_POINTS 150 \t\/\/ Give points for each enemy destroyed.\n#define ADD_LIFE_POINTS 3 \t\t\/\/ Give points for each life point kept.\n\n#define SUB_NUMBER_OF_TOWERS 20\t\/\/ Take points for each tower put.\n#define SUB_RESPAWN_BLOCK 2000\t\/\/ Penalize for blocking the respawn point with a tower.\n#define SUB_BLOCK_PATH 7000\t\/\/ Penalize for blocking all the paths from respawn to player's tower.\n#define SUB_TOWER_DESTROYED 4500 \/\/ Penalize for losing the game.\n\n\/\/ This value depends on the previous values.\n#define MAX_VALUE 8760\n#define MIN_VALUE -11500\n\n#define POPULATION_SIZE 100\n#define CHROM_LENGTH 100\n\n#endif \/\/_DEFINES_H_\n<|endoftext|>"} {"text":"\/***********************************************\n * Author: Jun Jiang - jiangjun4@sina.com\n * Create: 2017-08-19 18:50\n * Last modified : 2017-08-19 18:50\n * Filename : DNN.cpp\n * Description : \n **********************************************\/\n#include \"dnn\/DNN.h\"\n#include \"dnn\/Layer.h\"\n#include \"utils\/Log.h\"\n#include \"utils\/Shuffler.h\"\n#include \n\n\nnamespace abcdl{\nnamespace dnn{\n\nvoid DNN::train(const abcdl::algebra::Mat& train_data,\n const abcdl::algebra::Mat& train_label,\n const abcdl::algebra::Mat& test_data,\n const abcdl::algebra::Mat& test_label){\n LOG(INFO) << \"dnn start training...\";\n\n size_t layer_size = _layers.size();\n size_t num_train_data = train_data.rows();\n\n CHECK(num_train_data == train_label.rows());\n CHECK(train_data.cols() == _layers[0]->get_input_dim());\n CHECK(train_label.cols() == _layers[_layers.size() -1]->get_output_dim());\n\n abcdl::utils::Shuffler shuffler(num_train_data);\n abcdl::algebra::Mat data;\n abcdl::algebra::Mat label;\n\n for(size_t i = 0; i != _epoch; i++){\n shuffler.shuffle();\n for(size_t j = 0; j != num_train_data; j++){\n train_data.get_row(&data, shuffler.get_row(j));\n train_label.get_row(&label, shuffler.get_row(j));\n\n for(size_t k = 0; k != layer_size; k++){\n if(k == 0){\n ((InputLayer*)_layers[k])->set_x(data);\n }\n _layers[k]->forward(_layers[k-1]);\n }\n\n for(size_t k = layer_size - 1; k > 0; k--){\n if(k == layer_size - 1){\n ((OutputLayer*)_layers[k])->set_y(label);\n _layers[k]->backward(_layers[k-1], nullptr);\n }else{\n _layers[k]->backward(_layers[k-1], _layers[k+1]);\n }\n \n \/\/mini_batch_update\n if(j % _batch_size == _batch_size - 1 || j == num_train_data - 1){\n _layers[k]->update_gradient(j % _batch_size + 1, _alpha, _lamda);\n }\n }\n\n if(j % 100 == 0){\n printf(\"Epoch[%ld\/%ld] Train[%ld\/%ld]\\r\", i + 1, _epoch, j, num_train_data);\n }\n }\n\n if(test_data.rows() > 0){\n size_t num = evaluate(test_data, test_label);\n printf(\"Epoch[%ld][%ld\/%ld] rate[%f]\\n\", i + 1, num, test_data.rows(), num\/(real)test_data.rows());\n }\n }\n}\n\nsize_t DNN::evaluate(const abcdl::algebra::Mat& test_data, const abcdl::algebra::Mat& test_label){\n CHECK(test_data.cols() == _layers[0]->get_input_dim());\n CHECK(test_data.rows() == test_label.rows());\n CHECK(test_label.cols() == _layers[_layers.size() - 1]->get_output_dim());\n\n size_t rows = test_data.rows();\n size_t predict_num = 0;\n abcdl::algebra::Mat mat;\n\n for(size_t i = 0; i != rows; i++){\n predict(mat, test_data.get_row(i));\n if(mat.argmax() == test_label.get_row(i).argmax()){\n ++predict_num;\n }\n }\n return predict_num;\n}\n\nvoid DNN::predict(abcdl::algebra::Mat& result, const abcdl::algebra::Mat& predict_data){\n CHECK(predict_data.cols() == _layers[0]->get_input_dim());\n size_t layer_size = _layers.size();\n for(size_t k = 0; k != layer_size; k++){\n if(k == 0){\n ((InputLayer*)_layers[k])->set_x(predict_data);\n }\n _layers[k]->forward(_layers[k-1]);\n }\n result = _layers[layer_size - 1]->get_activate_data();\n}\n\nbool DNN::load_model(const std::string& path){\n std::vector models;\n if(!_model_loader.read(path, &models, \"DNNMODEL\") || models.size() % 2 != 0){\n for(auto& model : models){\n delete model;\n }\n models.clear();\n return false;\n }\n\n for(auto& layer : _layers){\n delete layer;\n }\n _layers.clear();\n\n for(size_t i = 0; i != models.size() \/ 2; i++){\n if(i == 0){\n _layers.push_back(new InputLayer(models[0]->rows()));\n }\n if(i == models.size() \/ 2 - 1){\n _layers.push_back(new OutputLayer(models[i * 2]->rows(), models[i * 2]->cols(), new SigmoidActivateFunc(), new CrossEntropyCost(), *models[i * 2], *models[i * 2 + 1]));\n }else{\n _layers.push_back(new FullConnLayer(models[i * 2]->rows(), models[i * 2]->cols(), new SigmoidActivateFunc(), *models[i * 2], *models[i * 2 + 1]));\n }\n }\n\n for(auto& model : models){\n delete model;\n }\n models.clear();\n return true;\n}\nbool DNN::write_model(const std::string& path){\n std::vector models;\n for(size_t i = 1; i != _layers.size(); i++){\n models.push_back(&_layers[i]->get_weight());\n models.push_back(&_layers[i]->get_bias());\n }\n return _model_loader.write(models, path, \"DNNMODEL\", false);\n}\n\n}\/\/namespace dnn\n}\/\/namespace abcdl\nrun time stat\/***********************************************\n * Author: Jun Jiang - jiangjun4@sina.com\n * Create: 2017-08-19 18:50\n * Last modified : 2017-08-19 18:50\n * Filename : DNN.cpp\n * Description : \n **********************************************\/\n#include \"dnn\/DNN.h\"\n#include \"dnn\/Layer.h\"\n#include \"utils\/Log.h\"\n#include \"utils\/Shuffler.h\"\n#include \n\n\nnamespace abcdl{\nnamespace dnn{\n\nvoid DNN::train(const abcdl::algebra::Mat& train_data,\n const abcdl::algebra::Mat& train_label,\n const abcdl::algebra::Mat& test_data,\n const abcdl::algebra::Mat& test_label){\n LOG(INFO) << \"dnn start training...\";\n\n size_t layer_size = _layers.size();\n size_t num_train_data = train_data.rows();\n\n CHECK(num_train_data == train_label.rows());\n CHECK(train_data.cols() == _layers[0]->get_input_dim());\n CHECK(train_label.cols() == _layers[_layers.size() -1]->get_output_dim());\n\n abcdl::algebra::Mat data;\n abcdl::algebra::Mat label;\n abcdl::utils::Shuffler shuffler(num_train_data);\n auto now = []{return std::chrono::system_clock::now();};\n\n for(size_t i = 0; i != _epoch; i++){\n \n shuffler.shuffle();\n auto start_time = now();\n\n for(size_t j = 0; j != num_train_data; j++){\n train_data.get_row(&data, shuffler.get_row(j));\n train_label.get_row(&label, shuffler.get_row(j));\n\n for(size_t k = 0; k != layer_size; k++){\n if(k == 0){\n ((InputLayer*)_layers[k])->set_x(data);\n }\n _layers[k]->forward(_layers[k-1]);\n }\n\n for(size_t k = layer_size - 1; k > 0; k--){\n if(k == layer_size - 1){\n ((OutputLayer*)_layers[k])->set_y(label);\n _layers[k]->backward(_layers[k-1], nullptr);\n }else{\n _layers[k]->backward(_layers[k-1], _layers[k+1]);\n }\n \n \/\/mini_batch_update\n if(j % _batch_size == _batch_size - 1 || j == num_train_data - 1){\n _layers[k]->update_gradient(j % _batch_size + 1, _alpha, _lamda);\n }\n }\n\n if(j % 100 == 0){\n printf(\"Epoch[%ld\/%ld] Train[%ld\/%ld]\\r\", i + 1, _epoch, j, num_train_data);\n }\n }\n\n auto train_time = now();\n printf(\"Epoch [%ld] training run time:[%ld]ms\\n\", i, std::chrono::duration_cast(train_time - start_time).count());\n\n if(test_data.rows() > 0){\n size_t num = evaluate(test_data, test_label);\n printf(\"Epoch[%ld][%ld\/%ld] rate[%f]\\n\", i + 1, num, test_data.rows(), num\/(real)test_data.rows());\n \t printf(\"Epoch[%ld] predict run time:[%ld]ms\\n\", i, std::chrono::duration_cast(now() - train_time).count());\n }\n }\n}\n\nsize_t DNN::evaluate(const abcdl::algebra::Mat& test_data, const abcdl::algebra::Mat& test_label){\n CHECK(test_data.cols() == _layers[0]->get_input_dim());\n CHECK(test_data.rows() == test_label.rows());\n CHECK(test_label.cols() == _layers[_layers.size() - 1]->get_output_dim());\n\n size_t rows = test_data.rows();\n size_t predict_num = 0;\n abcdl::algebra::Mat mat;\n\n for(size_t i = 0; i != rows; i++){\n predict(mat, test_data.get_row(i));\n if(mat.argmax() == test_label.get_row(i).argmax()){\n ++predict_num;\n }\n }\n return predict_num;\n}\n\nvoid DNN::predict(abcdl::algebra::Mat& result, const abcdl::algebra::Mat& predict_data){\n CHECK(predict_data.cols() == _layers[0]->get_input_dim());\n size_t layer_size = _layers.size();\n for(size_t k = 0; k != layer_size; k++){\n if(k == 0){\n ((InputLayer*)_layers[k])->set_x(predict_data);\n }\n _layers[k]->forward(_layers[k-1]);\n }\n result = _layers[layer_size - 1]->get_activate_data();\n}\n\nbool DNN::load_model(const std::string& path){\n std::vector models;\n if(!_model_loader.read(path, &models, \"DNNMODEL\") || models.size() % 2 != 0){\n for(auto& model : models){\n delete model;\n }\n models.clear();\n return false;\n }\n\n for(auto& layer : _layers){\n delete layer;\n }\n _layers.clear();\n\n for(size_t i = 0; i != models.size() \/ 2; i++){\n if(i == 0){\n _layers.push_back(new InputLayer(models[0]->rows()));\n }\n if(i == models.size() \/ 2 - 1){\n _layers.push_back(new OutputLayer(models[i * 2]->rows(), models[i * 2]->cols(), new SigmoidActivateFunc(), new CrossEntropyCost(), *models[i * 2], *models[i * 2 + 1]));\n }else{\n _layers.push_back(new FullConnLayer(models[i * 2]->rows(), models[i * 2]->cols(), new SigmoidActivateFunc(), *models[i * 2], *models[i * 2 + 1]));\n }\n }\n\n for(auto& model : models){\n delete model;\n }\n models.clear();\n return true;\n}\nbool DNN::write_model(const std::string& path){\n std::vector models;\n for(size_t i = 1; i != _layers.size(); i++){\n models.push_back(&_layers[i]->get_weight());\n models.push_back(&_layers[i]->get_bias());\n }\n return _model_loader.write(models, path, \"DNNMODEL\", false);\n}\n\n}\/\/namespace dnn\n}\/\/namespace abcdl\n<|endoftext|>"} {"text":"#include \n#include \n#include \n\n#include \n\n#include \"..\/..\/src\/HTMLParser\/HTMLTokenizer.hpp\"\n#include \"..\/..\/src\/HTMLParser\/tokens\/StartToken.hpp\"\n#include \"..\/..\/src\/HTMLParser\/tokens\/DoctypeToken.hpp\"\n#include \"..\/..\/src\/HTMLParser\/tokens\/EndToken.hpp\"\n#include \"..\/..\/src\/HTMLParser\/tokens\/CommentToken.hpp\"\n#include \"..\/..\/src\/HTMLParser\/tokens\/CharacterToken.hpp\"\n\nTEST_CASE(\"HTML tokenization\")\n{\n std::map empty_map;\n SECTION(\"Manually creating tokens\")\n {\n SECTION(\"Manually creating doctype token\")\n {\n DoctypeToken doctype_token = DoctypeToken();\n CHECK_FALSE(doctype_token.quirks_required());\n CHECK_FALSE(doctype_token.is_name_set());\n CHECK_FALSE(doctype_token.is_public_identifier_set());\n CHECK_FALSE(doctype_token.is_system_identifier_set());\n }\n\n SECTION(\"Manually creating HTML root token\")\n {\n StartToken html_token = StartToken();\n\n CHECK_FALSE(html_token.is_self_closing());\n CHECK(html_token.get_attributes() == empty_map);\n CHECK(html_token.get_tag_name() == L\"\");\n }\n }\n\n SECTION(\"Creating tokens with tokenizer\")\n {\n HTMLTokenizer tokenizer;\n\n SECTION(\"Creating doctype tokens with tokenizer\")\n {\n SECTION(\"Normal doctype token\")\n {\n auto doctype_token = \n tokenizer.create_token_from_string(L\"\");\n\n REQUIRE(doctype_token->is_doctype_token());\n CHECK_FALSE(doctype_token->quirks_required());\n CHECK(doctype_token->is_name_set());\n CHECK(doctype_token->get_tag_name() == L\"html\");\n }\n\n SECTION(\"Doctype name not set\")\n {\n auto doctype_token = \n tokenizer.create_token_from_string(L\"\");\n\n REQUIRE(doctype_token->is_doctype_token());\n CHECK(doctype_token->quirks_required());\n CHECK_FALSE(doctype_token->is_name_set());\n }\n\n SECTION(\"Correctly handles extra identifiers\")\n {\n std::wstring long_doctype = L\"\";\n std::shared_ptr doctype_token = \n tokenizer.create_token_from_string(long_doctype);\n\n REQUIRE(doctype_token->is_doctype_token());\n CHECK(doctype_token->quirks_required());\n CHECK(doctype_token->get_tag_name() == L\"html\");\n CHECK(doctype_token->is_name_set());\n }\n }\n\n SECTION(\"Creating start tokens with tokenizer\")\n {\n std::map lang_map = {{L\"lang\", L\"en\"}};\n\n SECTION(\"Creating html root token with tokenizer\")\n {\n std::shared_ptr token = \n tokenizer.create_token_from_string(L\"\");\n std::map attributes_map = \n token->get_attributes();\n\n REQUIRE(token->is_start_token());\n CHECK_FALSE(token->is_self_closing());\n CHECK(token->contains_attribute(L\"lang\"));\n CHECK(token->get_attribute_value(L\"lang\") == L\"en\");\n CHECK(token->get_tag_name() == L\"html\");\n }\n\n SECTION(\"Creating self-closing tag with tokenizer\")\n {\n std::shared_ptr token = \n tokenizer.create_token_from_string(L\"\");\n\n REQUIRE(token->is_start_token());\n CHECK(token->is_self_closing());\n CHECK(token->get_tag_name() == L\"br\");\n }\n\n SECTION(\"Tag with multiple attributes\")\n {\n std::shared_ptr token = \n tokenizer.create_token_from_string(\n L\"\");\n std::map attributes_map = \n token->get_attributes();\n\n REQUIRE(token->is_start_token());\n CHECK(token->get_tag_name() == L\"img\");\n CHECK_FALSE(token->is_self_closing());\n CHECK(token->contains_attribute(L\"src\"));\n CHECK(token->contains_attribute(L\"width\"));\n CHECK(token->contains_attribute(L\"height\"));\n CHECK(token->get_attribute_value(L\"src\") == L\"example.png\");\n CHECK(token->get_attribute_value(L\"width\") == L\"10\");\n CHECK(token->get_attribute_value(L\"height\") == L\"20\");\n }\n\n SECTION(\"Tag with repeated attributes\")\n {\n std::shared_ptr token = \n tokenizer.create_token_from_string(\n L\"\");\n\n REQUIRE(token->is_start_token());\n CHECK(token->get_tag_name() == L\"html\");\n CHECK(token->contains_attribute(L\"lang\"));\n CHECK(token->get_attribute_value(L\"lang\") == L\"en\");\n CHECK_FALSE(token->get_attribute_value(L\"lang\") == L\"br\");\n CHECK_FALSE(token->is_self_closing());\n }\n\n SECTION(\"Capitalization in attribute name\/value\")\n {\n std::shared_ptr token = \n tokenizer.create_token_from_string(L\"\");\n\n REQUIRE(token->is_start_token());\n CHECK(token->get_tag_name() == L\"html\");\n CHECK(token->contains_attribute(L\"lang\"));\n CHECK(token->get_attribute_value(L\"lang\") == L\"en\");\n CHECK_FALSE(token->contains_attribute(L\"lAnG\"));\n CHECK_FALSE(token->is_self_closing());\n }\n\n SECTION(\"Self-closing tag with attributes\")\n {\n std::shared_ptr token = \n tokenizer.create_token_from_string(\n L\"\");\n\n REQUIRE(token->is_start_token());\n CHECK(token->get_tag_name() == L\"area\");\n CHECK(token->is_self_closing());\n CHECK(token->contains_attribute(L\"shape\"));\n CHECK(token->get_attribute_value(L\"shape\") == L\"circle\");\n }\n }\n\n SECTION(\"Creating end tags with tokenizer\")\n {\n std::shared_ptr token = \n tokenizer.create_token_from_string(L\"<\/p>\");\n\n REQUIRE(token->is_end_token());\n CHECK(token->get_tag_name() == L\"p\");\n CHECK_FALSE(token->is_self_closing());\n }\n\n SECTION(\"Creating character tokens with tokenizer\")\n {\n std::shared_ptr token = \n tokenizer.create_token_from_string(L\"a\");\n\n REQUIRE(token->is_char_token());\n CHECK(token->get_char() == L'a');\n CHECK_FALSE(token->is_self_closing());\n }\n\n SECTION(\"Creating comment tags with tokenizer\")\n {\n SECTION(\"Normal comment\")\n {\n std::shared_ptr token = \n tokenizer.create_token_from_string(\n L\"\");\n\n REQUIRE(token->is_comment_token());\n CHECK(token->get_data() == L\"This is a comment\");\n }\n\n SECTION(\"Comment with no data\")\n {\n std::shared_ptr token = \n tokenizer.create_token_from_string(L\"\");\n\n REQUIRE(token->is_comment_token());\n CHECK(token->get_data() == L\"\");\n }\n\n SECTION(\"Comment with hyphen in data\")\n {\n std::shared_ptr token = \n tokenizer.create_token_from_string(L\"\");\n\n REQUIRE(token->is_comment_token());\n CHECK(token->get_data() == L\"Test-string\");\n }\n\n SECTION(\"Comment with hyphen before data\")\n {\n std::shared_ptr token = \n tokenizer.create_token_from_string(L\"\");\n\n REQUIRE(token->is_comment_token());\n CHECK(token->get_data() == L\"-Test string\");\n }\n\n SECTION(\"Comment with two hyphens in the middle\")\n {\n std::shared_ptr token = \n tokenizer.create_token_from_string(L\"\");\n\n REQUIRE(token->is_comment_token());\n CHECK(token->get_data() == L\"Test--string\");\n }\n\n SECTION(\"Comment with exclamation mark and hyphens in the middle\")\n {\n std::shared_ptr token = \n tokenizer.create_token_from_string(\n L\"\");\n\n REQUIRE(token->is_comment_token());\n CHECK(token->get_data() == L\"Test--!string\");\n }\n }\n }\n\n SECTION(\"Tokenizing multi-tag strings\")\n {\n HTMLTokenizer tokenizer;\n\n SECTION(\"Well-formatted minimal string\")\n {\n std::vector> tokens = \n tokenizer.tokenize_string(\n L\"<\/head><\/body><\/html>\");\n\n std::vector>::iterator it = \n tokens.begin();\n CHECK((*it)->is_doctype_token());\n CHECK((*it)->get_tag_name() == L\"html\");\n std::advance(it, 1);\n CHECK((*it)->is_start_token());\n CHECK((*it)->get_tag_name() == L\"html\");\n std::advance(it, 1);\n CHECK((*it)->is_start_token());\n CHECK((*it)->get_tag_name() == L\"head\");\n std::advance(it, 1);\n CHECK((*it)->get_tag_name() == L\"head\");\n CHECK((*it)->is_end_token());\n std::advance(it, 1);\n CHECK((*it)->is_start_token());\n CHECK((*it)->get_tag_name() == L\"body\");\n std::advance(it, 1);\n CHECK((*it)->get_tag_name() == L\"body\");\n CHECK((*it)->is_end_token());\n std::advance(it, 1);\n CHECK((*it)->get_tag_name() == L\"html\");\n CHECK((*it)->is_end_token());\n }\n\n\n SECTION(\"Well-formatted string with character tokens\")\n {\n std::vector> tokens = \n tokenizer.tokenize_string(\n L\"<\/head>Test<\/body><\/html>\");\n\n std::vector>::iterator it = \n tokens.begin();\n CHECK((*it)->is_doctype_token());\n CHECK((*it)->get_tag_name() == L\"html\");\n std::advance(it, 1);\n CHECK((*it)->is_start_token());\n CHECK((*it)->get_tag_name() == L\"html\");\n std::advance(it, 1);\n CHECK((*it)->is_start_token());\n CHECK((*it)->get_tag_name() == L\"head\");\n std::advance(it, 1);\n CHECK((*it)->get_tag_name() == L\"head\");\n CHECK((*it)->is_end_token());\n std::advance(it, 1);\n CHECK((*it)->is_start_token());\n CHECK((*it)->get_tag_name() == L\"body\");\n std::advance(it, 1);\n CHECK((*it)->get_char() == L'T');\n CHECK((*it)->is_char_token());\n std::advance(it, 1);\n CHECK((*it)->get_char() == L'e');\n CHECK((*it)->is_char_token());\n std::advance(it, 1);\n CHECK((*it)->get_char() == L's');\n CHECK((*it)->is_char_token());\n std::advance(it, 1);\n CHECK((*it)->get_char() == L't');\n CHECK((*it)->is_char_token());\n std::advance(it, 1);\n CHECK((*it)->get_tag_name() == L\"body\");\n CHECK((*it)->is_end_token());\n std::advance(it, 1);\n CHECK((*it)->get_tag_name() == L\"html\");\n CHECK((*it)->is_end_token());\n }\n }\n}\nTest tokenizing with newlines inside of tags#include \n#include \n#include \n\n#include \n\n#include \"..\/..\/src\/HTMLParser\/HTMLTokenizer.hpp\"\n#include \"..\/..\/src\/HTMLParser\/tokens\/StartToken.hpp\"\n#include \"..\/..\/src\/HTMLParser\/tokens\/DoctypeToken.hpp\"\n#include \"..\/..\/src\/HTMLParser\/tokens\/EndToken.hpp\"\n#include \"..\/..\/src\/HTMLParser\/tokens\/CommentToken.hpp\"\n#include \"..\/..\/src\/HTMLParser\/tokens\/CharacterToken.hpp\"\n\nTEST_CASE(\"HTML tokenization\")\n{\n std::map empty_map;\n SECTION(\"Manually creating tokens\")\n {\n SECTION(\"Manually creating doctype token\")\n {\n DoctypeToken doctype_token = DoctypeToken();\n CHECK_FALSE(doctype_token.quirks_required());\n CHECK_FALSE(doctype_token.is_name_set());\n CHECK_FALSE(doctype_token.is_public_identifier_set());\n CHECK_FALSE(doctype_token.is_system_identifier_set());\n }\n\n SECTION(\"Manually creating HTML root token\")\n {\n StartToken html_token = StartToken();\n\n CHECK_FALSE(html_token.is_self_closing());\n CHECK(html_token.get_attributes() == empty_map);\n CHECK(html_token.get_tag_name() == L\"\");\n }\n }\n\n SECTION(\"Creating tokens with tokenizer\")\n {\n HTMLTokenizer tokenizer;\n\n SECTION(\"Creating doctype tokens with tokenizer\")\n {\n SECTION(\"Normal doctype token\")\n {\n auto doctype_token = \n tokenizer.create_token_from_string(L\"\");\n\n REQUIRE(doctype_token->is_doctype_token());\n CHECK_FALSE(doctype_token->quirks_required());\n CHECK(doctype_token->is_name_set());\n CHECK(doctype_token->get_tag_name() == L\"html\");\n }\n\n SECTION(\"Doctype name not set\")\n {\n auto doctype_token = \n tokenizer.create_token_from_string(L\"\");\n\n REQUIRE(doctype_token->is_doctype_token());\n CHECK(doctype_token->quirks_required());\n CHECK_FALSE(doctype_token->is_name_set());\n }\n\n SECTION(\"Correctly handles extra identifiers\")\n {\n std::wstring long_doctype = L\"\";\n std::shared_ptr doctype_token = \n tokenizer.create_token_from_string(long_doctype);\n\n REQUIRE(doctype_token->is_doctype_token());\n CHECK(doctype_token->quirks_required());\n CHECK(doctype_token->get_tag_name() == L\"html\");\n CHECK(doctype_token->is_name_set());\n }\n }\n\n SECTION(\"Creating start tokens with tokenizer\")\n {\n std::map lang_map = {{L\"lang\", L\"en\"}};\n\n SECTION(\"Creating html root token with tokenizer\")\n {\n std::shared_ptr token = \n tokenizer.create_token_from_string(L\"\");\n std::map attributes_map = \n token->get_attributes();\n\n REQUIRE(token->is_start_token());\n CHECK_FALSE(token->is_self_closing());\n CHECK(token->contains_attribute(L\"lang\"));\n CHECK(token->get_attribute_value(L\"lang\") == L\"en\");\n CHECK(token->get_tag_name() == L\"html\");\n }\n\n SECTION(\"Creating self-closing tag with tokenizer\")\n {\n std::shared_ptr token = \n tokenizer.create_token_from_string(L\"\");\n\n REQUIRE(token->is_start_token());\n CHECK(token->is_self_closing());\n CHECK(token->get_tag_name() == L\"br\");\n }\n\n SECTION(\"Tag with multiple attributes\")\n {\n std::shared_ptr token = \n tokenizer.create_token_from_string(\n L\"\");\n std::map attributes_map = \n token->get_attributes();\n\n REQUIRE(token->is_start_token());\n CHECK(token->get_tag_name() == L\"img\");\n CHECK_FALSE(token->is_self_closing());\n CHECK(token->contains_attribute(L\"src\"));\n CHECK(token->contains_attribute(L\"width\"));\n CHECK(token->contains_attribute(L\"height\"));\n CHECK(token->get_attribute_value(L\"src\") == L\"example.png\");\n CHECK(token->get_attribute_value(L\"width\") == L\"10\");\n CHECK(token->get_attribute_value(L\"height\") == L\"20\");\n }\n\n SECTION(\"Tag with repeated attributes\")\n {\n std::shared_ptr token = \n tokenizer.create_token_from_string(\n L\"\");\n\n REQUIRE(token->is_start_token());\n CHECK(token->get_tag_name() == L\"html\");\n CHECK(token->contains_attribute(L\"lang\"));\n CHECK(token->get_attribute_value(L\"lang\") == L\"en\");\n CHECK_FALSE(token->get_attribute_value(L\"lang\") == L\"br\");\n CHECK_FALSE(token->is_self_closing());\n }\n\n SECTION(\"Capitalization in attribute name\/value\")\n {\n std::shared_ptr token = \n tokenizer.create_token_from_string(L\"\");\n\n REQUIRE(token->is_start_token());\n CHECK(token->get_tag_name() == L\"html\");\n CHECK(token->contains_attribute(L\"lang\"));\n CHECK(token->get_attribute_value(L\"lang\") == L\"en\");\n CHECK_FALSE(token->contains_attribute(L\"lAnG\"));\n CHECK_FALSE(token->is_self_closing());\n }\n\n SECTION(\"Self-closing tag with attributes\")\n {\n std::shared_ptr token = \n tokenizer.create_token_from_string(\n L\"\");\n\n REQUIRE(token->is_start_token());\n CHECK(token->get_tag_name() == L\"area\");\n CHECK(token->is_self_closing());\n CHECK(token->contains_attribute(L\"shape\"));\n CHECK(token->get_attribute_value(L\"shape\") == L\"circle\");\n }\n\n SECTION(\"Newline inside of tag\")\n {\n auto token = \n tokenizer.create_token_from_string(L\"\");\n REQUIRE(token->is_start_token());\n CHECK(token->get_tag_name() == L\"html\");\n CHECK(token->contains_attribute(L\"lang\"));\n CHECK(token->get_attribute_value(L\"lang\") == L\"en\");\n CHECK_FALSE(token->is_self_closing());\n }\n }\n\n SECTION(\"Creating end tags with tokenizer\")\n {\n std::shared_ptr token = \n tokenizer.create_token_from_string(L\"<\/p>\");\n\n REQUIRE(token->is_end_token());\n CHECK(token->get_tag_name() == L\"p\");\n CHECK_FALSE(token->is_self_closing());\n\n SECTION(\"Newline inside of tag\")\n {\n auto token = \n tokenizer.create_token_from_string(L\"<\/p\\n>\");\n REQUIRE(token->is_end_token());\n CHECK(token->get_tag_name() == L\"p\");\n CHECK_FALSE(token->is_self_closing());\n }\n }\n\n SECTION(\"Creating character tokens with tokenizer\")\n {\n std::shared_ptr token = \n tokenizer.create_token_from_string(L\"a\");\n\n REQUIRE(token->is_char_token());\n CHECK(token->get_char() == L'a');\n CHECK_FALSE(token->is_self_closing());\n }\n\n SECTION(\"Creating comment tags with tokenizer\")\n {\n SECTION(\"Normal comment\")\n {\n std::shared_ptr token = \n tokenizer.create_token_from_string(\n L\"\");\n\n REQUIRE(token->is_comment_token());\n CHECK(token->get_data() == L\"This is a comment\");\n }\n\n SECTION(\"Normal comment with newline\")\n {\n std::shared_ptr token = \n tokenizer.create_token_from_string(\n L\"\");\n\n REQUIRE(token->is_comment_token());\n CHECK(token->get_data() == L\"This is\\na comment\");\n }\n\n SECTION(\"Comment with no data\")\n {\n std::shared_ptr token = \n tokenizer.create_token_from_string(L\"\");\n\n REQUIRE(token->is_comment_token());\n CHECK(token->get_data() == L\"\");\n }\n\n SECTION(\"Comment with hyphen in data\")\n {\n std::shared_ptr token = \n tokenizer.create_token_from_string(L\"\");\n\n REQUIRE(token->is_comment_token());\n CHECK(token->get_data() == L\"Test-string\");\n }\n\n SECTION(\"Comment with hyphen before data\")\n {\n std::shared_ptr token = \n tokenizer.create_token_from_string(L\"\");\n\n REQUIRE(token->is_comment_token());\n CHECK(token->get_data() == L\"-Test string\");\n }\n\n SECTION(\"Comment with two hyphens in the middle\")\n {\n std::shared_ptr token = \n tokenizer.create_token_from_string(L\"\");\n\n REQUIRE(token->is_comment_token());\n CHECK(token->get_data() == L\"Test--string\");\n }\n\n SECTION(\"Comment with exclamation mark and hyphens in the middle\")\n {\n std::shared_ptr token = \n tokenizer.create_token_from_string(\n L\"\");\n\n REQUIRE(token->is_comment_token());\n CHECK(token->get_data() == L\"Test--!string\");\n }\n }\n }\n\n SECTION(\"Tokenizing multi-tag strings\")\n {\n HTMLTokenizer tokenizer;\n\n SECTION(\"Well-formatted minimal string\")\n {\n std::vector> tokens = \n tokenizer.tokenize_string(\n L\"<\/head><\/body><\/html>\");\n\n std::vector>::iterator it = \n tokens.begin();\n CHECK((*it)->is_doctype_token());\n CHECK((*it)->get_tag_name() == L\"html\");\n std::advance(it, 1);\n CHECK((*it)->is_start_token());\n CHECK((*it)->get_tag_name() == L\"html\");\n std::advance(it, 1);\n CHECK((*it)->is_start_token());\n CHECK((*it)->get_tag_name() == L\"head\");\n std::advance(it, 1);\n CHECK((*it)->get_tag_name() == L\"head\");\n CHECK((*it)->is_end_token());\n std::advance(it, 1);\n CHECK((*it)->is_start_token());\n CHECK((*it)->get_tag_name() == L\"body\");\n std::advance(it, 1);\n CHECK((*it)->get_tag_name() == L\"body\");\n CHECK((*it)->is_end_token());\n std::advance(it, 1);\n CHECK((*it)->get_tag_name() == L\"html\");\n CHECK((*it)->is_end_token());\n }\n\n\n SECTION(\"Well-formatted string with character tokens\")\n {\n std::vector> tokens = \n tokenizer.tokenize_string(\n L\"<\/head>Test<\/body><\/html>\");\n\n std::vector>::iterator it = \n tokens.begin();\n CHECK((*it)->is_doctype_token());\n CHECK((*it)->get_tag_name() == L\"html\");\n std::advance(it, 1);\n CHECK((*it)->is_start_token());\n CHECK((*it)->get_tag_name() == L\"html\");\n std::advance(it, 1);\n CHECK((*it)->is_start_token());\n CHECK((*it)->get_tag_name() == L\"head\");\n std::advance(it, 1);\n CHECK((*it)->get_tag_name() == L\"head\");\n CHECK((*it)->is_end_token());\n std::advance(it, 1);\n CHECK((*it)->is_start_token());\n CHECK((*it)->get_tag_name() == L\"body\");\n std::advance(it, 1);\n CHECK((*it)->get_char() == L'T');\n CHECK((*it)->is_char_token());\n std::advance(it, 1);\n CHECK((*it)->get_char() == L'e');\n CHECK((*it)->is_char_token());\n std::advance(it, 1);\n CHECK((*it)->get_char() == L's');\n CHECK((*it)->is_char_token());\n std::advance(it, 1);\n CHECK((*it)->get_char() == L't');\n CHECK((*it)->is_char_token());\n std::advance(it, 1);\n CHECK((*it)->get_tag_name() == L\"body\");\n CHECK((*it)->is_end_token());\n std::advance(it, 1);\n CHECK((*it)->get_tag_name() == L\"html\");\n CHECK((*it)->is_end_token());\n }\n }\n}\n<|endoftext|>"} {"text":"\/*\n * Copyright 2014 Facebook, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \n#include \n#include \n#include \n#include \n\n#if GOOGLE_PERFTOOLS_REGISTER_THREAD\n# include \"base\/Profiler.h\"\n#endif\n\n#include \n#include \n#include \n\n#include \n\n#include \n\n#include \n\nnamespace apache { namespace thrift { namespace concurrency {\n\nusing std::shared_ptr;\nusing std::weak_ptr;\n\nconst PosixThreadFactory::POLICY PosixThreadFactory::kDefaultPolicy;\nconst PosixThreadFactory::PRIORITY PosixThreadFactory::kDefaultPriority;\nconst int PosixThreadFactory::kDefaultStackSizeMB;\n\n\/\/ global set to track the ids of live threads.\nstd::set liveThreadIds;\nMutex liveThreadIdMutex;\n\nvoid addLiveThreadId(pthread_t tid) {\n Guard g(liveThreadIdMutex);\n liveThreadIds.insert(tid);\n}\n\nvoid removeLiveThreadId(pthread_t tid) {\n Guard g(liveThreadIdMutex);\n liveThreadIds.erase(tid);\n}\n\nvoid getLiveThreadIds(std::set* tids) {\n Guard g(liveThreadIdMutex);\n for (std::set::const_iterator it = liveThreadIds.begin();\n it != liveThreadIds.end(); ++it) {\n tids->insert(*it);\n }\n}\n\n\n\/\/ push our given name upstream into pthreads\nbool PthreadThread::updateName() {\n if (!pthread_ || name_.empty()) {\n return false;\n }\n return setPosixThreadName(pthread_, name_);\n}\n\nPthreadThread::PthreadThread(int policy, int priority, int stackSize,\n bool detached,\n shared_ptr runnable) :\n pthread_(0),\n state_(uninitialized),\n policy_(policy),\n priority_(priority),\n stackSize_(stackSize),\n detached_(detached) {\n\n this->Thread::runnable(runnable);\n}\n\nPthreadThread::~PthreadThread() {\n \/* Nothing references this thread, if is is not detached, do a join\n now, otherwise the thread-id and, possibly, other resources will\n be leaked. *\/\n if(!detached_) {\n try {\n join();\n } catch(...) {\n \/\/ We're really hosed.\n }\n }\n removeLiveThreadId(pthread_);\n}\n\nvoid PthreadThread::start() {\n Guard g(stateLock_);\n\n if (state_ != uninitialized) {\n return;\n }\n\n pthread_attr_t thread_attr;\n if (pthread_attr_init(&thread_attr) != 0) {\n throw SystemResourceException(\"pthread_attr_init failed\");\n }\n\n if(pthread_attr_setdetachstate(&thread_attr,\n detached_ ?\n PTHREAD_CREATE_DETACHED :\n PTHREAD_CREATE_JOINABLE) != 0) {\n throw SystemResourceException(\"pthread_attr_setdetachstate failed\");\n }\n\n \/\/ Set thread stack size\n if (pthread_attr_setstacksize(&thread_attr, MB * stackSize_) != 0) {\n throw SystemResourceException(\"pthread_attr_setstacksize failed\");\n }\n\n \/\/ Create reference\n shared_ptr* selfRef = new shared_ptr();\n *selfRef = self_.lock();\n\n state_ = starting;\n\n if (pthread_create(&pthread_, &thread_attr, threadMain, (void*)selfRef) != 0) {\n throw SystemResourceException(\"pthread_create failed\");\n }\n\n \/\/ Now that we have a thread, we can set the name we've been given, if any.\n updateName();\n addLiveThreadId(pthread_);\n}\n\nvoid PthreadThread::join() {\n Guard g(stateLock_);\n STATE join_state = state_;\n\n\n if (!detached_ && join_state != uninitialized) {\n void* ignore;\n \/* XXX\n If join fails it is most likely due to the fact\n that the last reference was the thread itself and cannot\n join. This results in leaked threads and will eventually\n cause the process to run out of thread resources.\n We're beyond the point of throwing an exception. Not clear how\n best to handle this. *\/\n int res = pthread_join(pthread_, &ignore);\n detached_ = (res == 0);\n if (res != 0) {\n LOG(ERROR) << \"PthreadThread::join(): fail with code \" << res;\n }\n } else {\n LOG(ERROR) << \"PthreadThread::join(): detached thread\";\n }\n}\n\nThread::id_t PthreadThread::getId() {\n return (Thread::id_t)pthread_;\n}\n\nshared_ptr PthreadThread::runnable() const {\n return Thread::runnable();\n}\n\nvoid PthreadThread::runnable(shared_ptr value) {\n Thread::runnable(value);\n}\n\nvoid PthreadThread::weakRef(shared_ptr self) {\n assert(self.get() == this);\n self_ = weak_ptr(self);\n}\n\nbool PthreadThread::setName(const std::string& name) {\n Guard g(stateLock_);\n name_ = name;\n return updateName();\n}\n\nvoid* PthreadThread::threadMain(void* arg) {\n shared_ptr thread = *(shared_ptr*)arg;\n delete reinterpret_cast*>(arg);\n\n if (thread == nullptr) {\n return (void*)0;\n }\n\n#if GOOGLE_PERFTOOLS_REGISTER_THREAD\n ProfilerRegisterThread();\n#endif\n \/\/ Using pthread_attr_setschedparam() at thread creation doesn't actually\n \/\/ change the new thread's priority for some reason... Other people on the\n \/\/ 'net also complain about it. The solution is to set priority inside the\n \/\/ new thread's threadMain.\n if (thread->policy_ == SCHED_FIFO || thread->policy_ == SCHED_RR) {\n struct sched_param sched_param;\n sched_param.sched_priority = thread->priority_;\n int err =\n pthread_setschedparam(pthread_self(), thread->policy_, &sched_param);\n if (err != 0) {\n VLOG(1) << \"pthread_setschedparam failed (are you root?) with error \" <<\n err, strerror(err);\n }\n } else if (thread->policy_ == SCHED_OTHER) {\n if (setpriority(PRIO_PROCESS, 0, thread->priority_) != 0) {\n VLOG(1) << \"setpriority failed (are you root?) with error \" <<\n errno, strerror(errno);\n }\n }\n\n thread->runnable()->run();\n\n return (void*)0;\n}\n\nint PosixThreadFactory::Impl::toPthreadPolicy(POLICY policy) {\n switch (policy) {\n case OTHER:\n return SCHED_OTHER;\n case FIFO:\n return SCHED_FIFO;\n case ROUND_ROBIN:\n return SCHED_RR;\n }\n return SCHED_OTHER;\n}\n\nint PosixThreadFactory::Impl::toPthreadPriority(\n POLICY policy, PRIORITY priority) {\n int pthread_policy = toPthreadPolicy(policy);\n int min_priority = 0;\n int max_priority = 0;\n if (pthread_policy == SCHED_FIFO || pthread_policy == SCHED_RR) {\n#ifdef THRIFT_HAVE_SCHED_GET_PRIORITY_MIN\n min_priority = sched_get_priority_min(pthread_policy);\n#endif\n#ifdef THRIFT_HAVE_SCHED_GET_PRIORITY_MAX\n max_priority = sched_get_priority_max(pthread_policy);\n#endif\n } else if (pthread_policy == SCHED_OTHER) {\n min_priority = 19;\n max_priority = -20;\n }\n int quanta = HIGHEST - LOWEST;\n float stepsperquanta = (float)(max_priority - min_priority) \/ quanta;\n\n if (priority <= HIGHEST) {\n return (int)(min_priority + stepsperquanta * priority);\n } else {\n \/\/ should never get here for priority increments.\n assert(false);\n return (int)(min_priority + stepsperquanta * NORMAL);\n }\n}\n\nPosixThreadFactory::Impl::Impl(\n POLICY policy, PRIORITY priority, int stackSize, DetachState detached) :\n policy_(policy),\n priority_(priority),\n stackSize_(stackSize),\n detached_(detached) {}\n\nshared_ptr PosixThreadFactory::Impl::newThread(\n const shared_ptr& runnable,\n PosixThreadFactory::DetachState detachState) const {\n shared_ptr result = shared_ptr(\n new PthreadThread(toPthreadPolicy(policy_),\n toPthreadPriority(policy_, priority_), stackSize_,\n detachState == DETACHED, runnable));\n result->weakRef(result);\n runnable->thread(result);\n return result;\n}\n\nint PosixThreadFactory::Impl::getStackSize() const {\n return stackSize_;\n}\n\nvoid PosixThreadFactory::Impl::setStackSize(int value) {\n stackSize_ = value;\n}\n\nPosixThreadFactory::PRIORITY PosixThreadFactory::Impl::getPriority()\n const {\n return priority_;\n}\n\n\/**\n * Sets priority.\n *\n * XXX\n * Need to handle incremental priorities properly.\n *\/\nvoid PosixThreadFactory::Impl::setPriority(PRIORITY value) {\n priority_ = value;\n}\n\nPosixThreadFactory::DetachState PosixThreadFactory::Impl::getDetachState()\n const {\n return detached_;\n}\n\nvoid PosixThreadFactory::Impl::setDetachState(DetachState value) {\n detached_ = value;\n}\n\nThread::id_t PosixThreadFactory::Impl::getCurrentThreadId() const {\n return static_cast(pthread_self());\n}\n\n\nPosixThreadFactory::PosixThreadFactory(POLICY policy, PRIORITY priority,\n int stackSize, bool detached)\n : impl_(new PosixThreadFactory::Impl(policy, priority, stackSize,\n detached ? DETACHED : ATTACHED)) {\n}\n\nPosixThreadFactory::PosixThreadFactory(DetachState detached)\n : impl_(new PosixThreadFactory::Impl(kDefaultPolicy, kDefaultPriority,\n kDefaultStackSizeMB, detached)) {\n}\n\nshared_ptr PosixThreadFactory::newThread(\n const shared_ptr& runnable) const {\n return impl_->newThread(runnable, impl_->getDetachState());\n}\n\nshared_ptr PosixThreadFactory::newThread(\n const shared_ptr& runnable,\n DetachState detachState) const {\n return impl_->newThread(runnable, detachState);\n}\n\nint PosixThreadFactory::getStackSize() const { return impl_->getStackSize(); }\n\nvoid PosixThreadFactory::setStackSize(int value) { impl_->setStackSize(value); }\n\nPosixThreadFactory::PRIORITY PosixThreadFactory::getPriority() const { return impl_->getPriority(); }\n\nvoid PosixThreadFactory::setPriority(PosixThreadFactory::PRIORITY value) { impl_->setPriority(value); }\n\nbool PosixThreadFactory::isDetached() const {\n return impl_->getDetachState() == DETACHED;\n}\n\nvoid PosixThreadFactory::setDetached(bool value) {\n impl_->setDetachState(value ? DETACHED : ATTACHED);\n}\n\nvoid PosixThreadFactory::setDetached(DetachState value) {\n impl_->setDetachState(value);\n}\n\nThread::id_t PosixThreadFactory::getCurrentThreadId() const { return impl_->getCurrentThreadId(); }\n\n}}} \/\/ apache::thrift::concurrency\nReduce references to thrift spinlock part 1\/*\n * Copyright 2014 Facebook, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \n#include \n#include \n#include \n\n#if GOOGLE_PERFTOOLS_REGISTER_THREAD\n# include \"base\/Profiler.h\"\n#endif\n\n#include \n#include \n#include \n\n#include \n\n#include \n\n#include \n\nnamespace apache { namespace thrift { namespace concurrency {\n\nusing std::shared_ptr;\nusing std::weak_ptr;\n\nconst PosixThreadFactory::POLICY PosixThreadFactory::kDefaultPolicy;\nconst PosixThreadFactory::PRIORITY PosixThreadFactory::kDefaultPriority;\nconst int PosixThreadFactory::kDefaultStackSizeMB;\n\n\/\/ global set to track the ids of live threads.\nstd::set liveThreadIds;\nMutex liveThreadIdMutex;\n\nvoid addLiveThreadId(pthread_t tid) {\n Guard g(liveThreadIdMutex);\n liveThreadIds.insert(tid);\n}\n\nvoid removeLiveThreadId(pthread_t tid) {\n Guard g(liveThreadIdMutex);\n liveThreadIds.erase(tid);\n}\n\nvoid getLiveThreadIds(std::set* tids) {\n Guard g(liveThreadIdMutex);\n for (std::set::const_iterator it = liveThreadIds.begin();\n it != liveThreadIds.end(); ++it) {\n tids->insert(*it);\n }\n}\n\n\n\/\/ push our given name upstream into pthreads\nbool PthreadThread::updateName() {\n if (!pthread_ || name_.empty()) {\n return false;\n }\n return setPosixThreadName(pthread_, name_);\n}\n\nPthreadThread::PthreadThread(int policy, int priority, int stackSize,\n bool detached,\n shared_ptr runnable) :\n pthread_(0),\n state_(uninitialized),\n policy_(policy),\n priority_(priority),\n stackSize_(stackSize),\n detached_(detached) {\n\n this->Thread::runnable(runnable);\n}\n\nPthreadThread::~PthreadThread() {\n \/* Nothing references this thread, if is is not detached, do a join\n now, otherwise the thread-id and, possibly, other resources will\n be leaked. *\/\n if(!detached_) {\n try {\n join();\n } catch(...) {\n \/\/ We're really hosed.\n }\n }\n removeLiveThreadId(pthread_);\n}\n\nvoid PthreadThread::start() {\n Guard g(stateLock_);\n\n if (state_ != uninitialized) {\n return;\n }\n\n pthread_attr_t thread_attr;\n if (pthread_attr_init(&thread_attr) != 0) {\n throw SystemResourceException(\"pthread_attr_init failed\");\n }\n\n if(pthread_attr_setdetachstate(&thread_attr,\n detached_ ?\n PTHREAD_CREATE_DETACHED :\n PTHREAD_CREATE_JOINABLE) != 0) {\n throw SystemResourceException(\"pthread_attr_setdetachstate failed\");\n }\n\n \/\/ Set thread stack size\n if (pthread_attr_setstacksize(&thread_attr, MB * stackSize_) != 0) {\n throw SystemResourceException(\"pthread_attr_setstacksize failed\");\n }\n\n \/\/ Create reference\n shared_ptr* selfRef = new shared_ptr();\n *selfRef = self_.lock();\n\n state_ = starting;\n\n if (pthread_create(&pthread_, &thread_attr, threadMain, (void*)selfRef) != 0) {\n throw SystemResourceException(\"pthread_create failed\");\n }\n\n \/\/ Now that we have a thread, we can set the name we've been given, if any.\n updateName();\n addLiveThreadId(pthread_);\n}\n\nvoid PthreadThread::join() {\n Guard g(stateLock_);\n STATE join_state = state_;\n\n\n if (!detached_ && join_state != uninitialized) {\n void* ignore;\n \/* XXX\n If join fails it is most likely due to the fact\n that the last reference was the thread itself and cannot\n join. This results in leaked threads and will eventually\n cause the process to run out of thread resources.\n We're beyond the point of throwing an exception. Not clear how\n best to handle this. *\/\n int res = pthread_join(pthread_, &ignore);\n detached_ = (res == 0);\n if (res != 0) {\n LOG(ERROR) << \"PthreadThread::join(): fail with code \" << res;\n }\n } else {\n LOG(ERROR) << \"PthreadThread::join(): detached thread\";\n }\n}\n\nThread::id_t PthreadThread::getId() {\n return (Thread::id_t)pthread_;\n}\n\nshared_ptr PthreadThread::runnable() const {\n return Thread::runnable();\n}\n\nvoid PthreadThread::runnable(shared_ptr value) {\n Thread::runnable(value);\n}\n\nvoid PthreadThread::weakRef(shared_ptr self) {\n assert(self.get() == this);\n self_ = weak_ptr(self);\n}\n\nbool PthreadThread::setName(const std::string& name) {\n Guard g(stateLock_);\n name_ = name;\n return updateName();\n}\n\nvoid* PthreadThread::threadMain(void* arg) {\n shared_ptr thread = *(shared_ptr*)arg;\n delete reinterpret_cast*>(arg);\n\n if (thread == nullptr) {\n return (void*)0;\n }\n\n#if GOOGLE_PERFTOOLS_REGISTER_THREAD\n ProfilerRegisterThread();\n#endif\n \/\/ Using pthread_attr_setschedparam() at thread creation doesn't actually\n \/\/ change the new thread's priority for some reason... Other people on the\n \/\/ 'net also complain about it. The solution is to set priority inside the\n \/\/ new thread's threadMain.\n if (thread->policy_ == SCHED_FIFO || thread->policy_ == SCHED_RR) {\n struct sched_param sched_param;\n sched_param.sched_priority = thread->priority_;\n int err =\n pthread_setschedparam(pthread_self(), thread->policy_, &sched_param);\n if (err != 0) {\n VLOG(1) << \"pthread_setschedparam failed (are you root?) with error \" <<\n err, strerror(err);\n }\n } else if (thread->policy_ == SCHED_OTHER) {\n if (setpriority(PRIO_PROCESS, 0, thread->priority_) != 0) {\n VLOG(1) << \"setpriority failed (are you root?) with error \" <<\n errno, strerror(errno);\n }\n }\n\n thread->runnable()->run();\n\n return (void*)0;\n}\n\nint PosixThreadFactory::Impl::toPthreadPolicy(POLICY policy) {\n switch (policy) {\n case OTHER:\n return SCHED_OTHER;\n case FIFO:\n return SCHED_FIFO;\n case ROUND_ROBIN:\n return SCHED_RR;\n }\n return SCHED_OTHER;\n}\n\nint PosixThreadFactory::Impl::toPthreadPriority(\n POLICY policy, PRIORITY priority) {\n int pthread_policy = toPthreadPolicy(policy);\n int min_priority = 0;\n int max_priority = 0;\n if (pthread_policy == SCHED_FIFO || pthread_policy == SCHED_RR) {\n#ifdef THRIFT_HAVE_SCHED_GET_PRIORITY_MIN\n min_priority = sched_get_priority_min(pthread_policy);\n#endif\n#ifdef THRIFT_HAVE_SCHED_GET_PRIORITY_MAX\n max_priority = sched_get_priority_max(pthread_policy);\n#endif\n } else if (pthread_policy == SCHED_OTHER) {\n min_priority = 19;\n max_priority = -20;\n }\n int quanta = HIGHEST - LOWEST;\n float stepsperquanta = (float)(max_priority - min_priority) \/ quanta;\n\n if (priority <= HIGHEST) {\n return (int)(min_priority + stepsperquanta * priority);\n } else {\n \/\/ should never get here for priority increments.\n assert(false);\n return (int)(min_priority + stepsperquanta * NORMAL);\n }\n}\n\nPosixThreadFactory::Impl::Impl(\n POLICY policy, PRIORITY priority, int stackSize, DetachState detached) :\n policy_(policy),\n priority_(priority),\n stackSize_(stackSize),\n detached_(detached) {}\n\nshared_ptr PosixThreadFactory::Impl::newThread(\n const shared_ptr& runnable,\n PosixThreadFactory::DetachState detachState) const {\n shared_ptr result = shared_ptr(\n new PthreadThread(toPthreadPolicy(policy_),\n toPthreadPriority(policy_, priority_), stackSize_,\n detachState == DETACHED, runnable));\n result->weakRef(result);\n runnable->thread(result);\n return result;\n}\n\nint PosixThreadFactory::Impl::getStackSize() const {\n return stackSize_;\n}\n\nvoid PosixThreadFactory::Impl::setStackSize(int value) {\n stackSize_ = value;\n}\n\nPosixThreadFactory::PRIORITY PosixThreadFactory::Impl::getPriority()\n const {\n return priority_;\n}\n\n\/**\n * Sets priority.\n *\n * XXX\n * Need to handle incremental priorities properly.\n *\/\nvoid PosixThreadFactory::Impl::setPriority(PRIORITY value) {\n priority_ = value;\n}\n\nPosixThreadFactory::DetachState PosixThreadFactory::Impl::getDetachState()\n const {\n return detached_;\n}\n\nvoid PosixThreadFactory::Impl::setDetachState(DetachState value) {\n detached_ = value;\n}\n\nThread::id_t PosixThreadFactory::Impl::getCurrentThreadId() const {\n return static_cast(pthread_self());\n}\n\n\nPosixThreadFactory::PosixThreadFactory(POLICY policy, PRIORITY priority,\n int stackSize, bool detached)\n : impl_(new PosixThreadFactory::Impl(policy, priority, stackSize,\n detached ? DETACHED : ATTACHED)) {\n}\n\nPosixThreadFactory::PosixThreadFactory(DetachState detached)\n : impl_(new PosixThreadFactory::Impl(kDefaultPolicy, kDefaultPriority,\n kDefaultStackSizeMB, detached)) {\n}\n\nshared_ptr PosixThreadFactory::newThread(\n const shared_ptr& runnable) const {\n return impl_->newThread(runnable, impl_->getDetachState());\n}\n\nshared_ptr PosixThreadFactory::newThread(\n const shared_ptr& runnable,\n DetachState detachState) const {\n return impl_->newThread(runnable, detachState);\n}\n\nint PosixThreadFactory::getStackSize() const { return impl_->getStackSize(); }\n\nvoid PosixThreadFactory::setStackSize(int value) { impl_->setStackSize(value); }\n\nPosixThreadFactory::PRIORITY PosixThreadFactory::getPriority() const { return impl_->getPriority(); }\n\nvoid PosixThreadFactory::setPriority(PosixThreadFactory::PRIORITY value) { impl_->setPriority(value); }\n\nbool PosixThreadFactory::isDetached() const {\n return impl_->getDetachState() == DETACHED;\n}\n\nvoid PosixThreadFactory::setDetached(bool value) {\n impl_->setDetachState(value ? DETACHED : ATTACHED);\n}\n\nvoid PosixThreadFactory::setDetached(DetachState value) {\n impl_->setDetachState(value);\n}\n\nThread::id_t PosixThreadFactory::getCurrentThreadId() const { return impl_->getCurrentThreadId(); }\n\n}}} \/\/ apache::thrift::concurrency\n<|endoftext|>"} {"text":"#include \"fetcher.h\"\n\n\/\/ TODO: Move this to config.h!\n#ifdef __linux__\n#define USE_OPENSSL\n#endif\n\n\/\/ TODO: Make a crypto interface and remove ifdefs!\n#ifdef USE_OPENSSL\n#include \n#include \n#include \n#else\n#include \n#include \n#include \n#endif\n\n#include \n#include \n#include \n\n#include \n#include \n\nnamespace lastpass\n{\n\nnamespace\n{\n\nclass Xml\n{\npublic:\n explicit Xml(std::string const &text): document_(nullptr)\n {\n document_ = xmlReadMemory(text.c_str(), text.size(), \"\", nullptr, 0);\n if (document_ == nullptr)\n throw std::runtime_error(\"Failed to parse XML\");\n }\n\n ~Xml()\n {\n xmlFreeDoc(document_);\n }\n\n std::string get_attribute(std::string const &xpath) const\n {\n std::unique_ptrcontext(\n xmlXPathNewContext(document_),\n &xmlXPathFreeContext);\n if (context.get() == nullptr)\n return \"\";\n\n std::unique_ptrresult(\n xmlXPathEvalExpression(reinterpret_cast(xpath.c_str()), context.get()),\n &xmlXPathFreeObject);\n if (result.get() == nullptr)\n return \"\";\n\n xmlNodeSet const *nodes = result->nodesetval;\n if (nodes == nullptr ||\n nodes->nodeNr <= 0 ||\n nodes->nodeTab[0]->type != XML_ATTRIBUTE_NODE)\n return \"\";\n\n return reinterpret_cast(((xmlAttrPtr)nodes->nodeTab[0])->children->content);\n }\n\nprivate:\n xmlDocPtr document_;\n};\n\n}\n\nSession Fetcher::login(std::string const &username, std::string const &password, WebClient &web_client)\n{\n return login(username, password, request_iteration_count(username, web_client), web_client);\n}\n\nSession Fetcher::login(std::string const &username, std::string const &password, int iteration_count, WebClient &web_client)\n{\n auto response = web_client.post(\"https:\/\/lastpass.com\/login.php\", {\n {\"method\", \"mobile\"},\n {\"web\", \"1\"},\n {\"xml\", \"1\"},\n {\"username\", username},\n {\"hash\", make_hash(username, password, iteration_count)},\n {\"iterations\", std::to_string(iteration_count)}\n });\n Xml xml(response);\n auto id = xml.get_attribute(\"\/\/ok\/@sessionid\");\n\n if (id.empty())\n throw std::runtime_error(\"Failed to login\");\n\n \/\/ TODO: Handle errors here!\n\n return {id, iteration_count};\n}\n\nBlob Fetcher::fetch(Session const &session, WebClient &web_client)\n{\n auto response = web_client.get(\"https:\/\/lastpass.com\/getaccts.php\",\n {{\"mobile\", \"1\"}, {\"b64\", \"1\"}, {\"hash\", \"0.0\"}},\n {{\"PHPSESSID\", session.id()}});\n\n return {to_bytes(response), session.key_iteration_count()};\n}\n\nint Fetcher::request_iteration_count(std::string const &username, WebClient &web_client)\n{\n return std::stoi(web_client.post(\"https:\/\/lastpass.com\/iterations.php\", {{\"email\", username}}));\n}\n\nstd::vector Fetcher::make_key(std::string const &username, std::string const &password, int iteration_count)\n{\n return iteration_count == 1\n ? sha256(username + password)\n : pbkdf2_sha256(to_bytes(password), to_bytes(username), iteration_count, 32);\n}\n\nstd::string Fetcher::make_hash(std::string const &username, std::string const &password, int iteration_count)\n{\n auto key = make_key(username, password, iteration_count);\n return iteration_count == 1\n ? to_hex(sha256(to_hex(key) + password))\n : to_hex(pbkdf2_sha256(key, to_bytes(password), 1, 32));\n}\n\nstd::vector Fetcher::pbkdf2_sha256(std::vector const &password,\n std::vector const &salt,\n int iteration_count,\n size_t size)\n{\n static_assert(sizeof(uint8_t) == sizeof(char), \"uint8_t should be the same size as char\");\n\n std::vector key(size);\n\n#ifdef USE_OPENSSL\n PKCS5_PBKDF2_HMAC(reinterpret_cast(password.data()),\n password.size(),\n salt.data(),\n salt.size(),\n iteration_count,\n EVP_sha256(),\n size,\n &key[0]);\n#else\n CCKeyDerivationPBKDF(kCCPBKDF2,\n reinterpret_cast(password.data()),\n password.size(),\n salt.data(),\n salt.size(),\n kCCPRFHmacAlgSHA256,\n iteration_count,\n &key[0],\n size);\n#endif\n\n return key;\n}\n\nstd::vector Fetcher::sha256(std::string const &text)\n{\n#ifdef USE_OPENSSL\n std::vector hash(SHA256_DIGEST_LENGTH);\n SHA256_CTX sha256;\n SHA256_Init(&sha256);\n SHA256_Update(&sha256, text.c_str(), text.size());\n SHA256_Final(&hash[0], &sha256);\n#else\n std::vector hash(CC_SHA256_DIGEST_LENGTH);\n CC_SHA256(text.c_str(), text.size(), &hash[0]);\n#endif\n\n return hash;\n}\n\nstd::vector Fetcher::to_bytes(std::string const &text)\n{\n std::vector bytes(text.size());\n std::copy(text.begin(), text.end(), bytes.begin());\n return bytes;\n}\n\nstd::string Fetcher::to_hex(std::vector const &bytes)\n{\n static char const hex_chars[16] = {'0', '1', '2', '3', '4', '5', '6', '7',\n '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};\n\n std::string hex;\n hex.reserve(bytes.size() * 2);\n\n for (auto i: bytes)\n {\n hex += hex_chars[i \/ 16];\n hex += hex_chars[i % 16];\n }\n\n return hex;\n}\n\nstd::vector Fetcher::decode_base64(std::string const &base64_text)\n{\n \/\/ The size is the upper bound, the actual size could be smaller.\n \/\/ After decoding we need to trim unused space.\n std::vector decoded(base64_text.size() * 3 \/ 4);\n\n#ifdef USE_OPENSSL\n BIO *context = BIO_push(BIO_new(BIO_f_base64(),\n BIO_new_mem_buf((void *)base64_text.c_str(), base64_text.size()));\n BIO_set_flags(context, BIO_FLAGS_BASE64_NO_NL | BIO_FLAGS_MEM_RDONLY);\n size_t actual_size = BIO_read(context, decoded.data(), decoded.size());\n BIO_free_all(context);\n#else\n size_t actual_size = b64_pton(base64_text.c_str(), decoded.data(), decoded.size());\n#endif\n\n decoded.resize(actual_size);\n return decoded;\n}\n\n}\nAnother fix for OpenSSL base64#include \"fetcher.h\"\n\n\/\/ TODO: Move this to config.h!\n#ifdef __linux__\n#define USE_OPENSSL\n#endif\n\n\/\/ TODO: Make a crypto interface and remove ifdefs!\n#ifdef USE_OPENSSL\n#include \n#include \n#include \n#else\n#include \n#include \n#include \n#endif\n\n#include \n#include \n#include \n\n#include \n#include \n\nnamespace lastpass\n{\n\nnamespace\n{\n\nclass Xml\n{\npublic:\n explicit Xml(std::string const &text): document_(nullptr)\n {\n document_ = xmlReadMemory(text.c_str(), text.size(), \"\", nullptr, 0);\n if (document_ == nullptr)\n throw std::runtime_error(\"Failed to parse XML\");\n }\n\n ~Xml()\n {\n xmlFreeDoc(document_);\n }\n\n std::string get_attribute(std::string const &xpath) const\n {\n std::unique_ptrcontext(\n xmlXPathNewContext(document_),\n &xmlXPathFreeContext);\n if (context.get() == nullptr)\n return \"\";\n\n std::unique_ptrresult(\n xmlXPathEvalExpression(reinterpret_cast(xpath.c_str()), context.get()),\n &xmlXPathFreeObject);\n if (result.get() == nullptr)\n return \"\";\n\n xmlNodeSet const *nodes = result->nodesetval;\n if (nodes == nullptr ||\n nodes->nodeNr <= 0 ||\n nodes->nodeTab[0]->type != XML_ATTRIBUTE_NODE)\n return \"\";\n\n return reinterpret_cast(((xmlAttrPtr)nodes->nodeTab[0])->children->content);\n }\n\nprivate:\n xmlDocPtr document_;\n};\n\n}\n\nSession Fetcher::login(std::string const &username, std::string const &password, WebClient &web_client)\n{\n return login(username, password, request_iteration_count(username, web_client), web_client);\n}\n\nSession Fetcher::login(std::string const &username, std::string const &password, int iteration_count, WebClient &web_client)\n{\n auto response = web_client.post(\"https:\/\/lastpass.com\/login.php\", {\n {\"method\", \"mobile\"},\n {\"web\", \"1\"},\n {\"xml\", \"1\"},\n {\"username\", username},\n {\"hash\", make_hash(username, password, iteration_count)},\n {\"iterations\", std::to_string(iteration_count)}\n });\n Xml xml(response);\n auto id = xml.get_attribute(\"\/\/ok\/@sessionid\");\n\n if (id.empty())\n throw std::runtime_error(\"Failed to login\");\n\n \/\/ TODO: Handle errors here!\n\n return {id, iteration_count};\n}\n\nBlob Fetcher::fetch(Session const &session, WebClient &web_client)\n{\n auto response = web_client.get(\"https:\/\/lastpass.com\/getaccts.php\",\n {{\"mobile\", \"1\"}, {\"b64\", \"1\"}, {\"hash\", \"0.0\"}},\n {{\"PHPSESSID\", session.id()}});\n\n return {to_bytes(response), session.key_iteration_count()};\n}\n\nint Fetcher::request_iteration_count(std::string const &username, WebClient &web_client)\n{\n return std::stoi(web_client.post(\"https:\/\/lastpass.com\/iterations.php\", {{\"email\", username}}));\n}\n\nstd::vector Fetcher::make_key(std::string const &username, std::string const &password, int iteration_count)\n{\n return iteration_count == 1\n ? sha256(username + password)\n : pbkdf2_sha256(to_bytes(password), to_bytes(username), iteration_count, 32);\n}\n\nstd::string Fetcher::make_hash(std::string const &username, std::string const &password, int iteration_count)\n{\n auto key = make_key(username, password, iteration_count);\n return iteration_count == 1\n ? to_hex(sha256(to_hex(key) + password))\n : to_hex(pbkdf2_sha256(key, to_bytes(password), 1, 32));\n}\n\nstd::vector Fetcher::pbkdf2_sha256(std::vector const &password,\n std::vector const &salt,\n int iteration_count,\n size_t size)\n{\n static_assert(sizeof(uint8_t) == sizeof(char), \"uint8_t should be the same size as char\");\n\n std::vector key(size);\n\n#ifdef USE_OPENSSL\n PKCS5_PBKDF2_HMAC(reinterpret_cast(password.data()),\n password.size(),\n salt.data(),\n salt.size(),\n iteration_count,\n EVP_sha256(),\n size,\n &key[0]);\n#else\n CCKeyDerivationPBKDF(kCCPBKDF2,\n reinterpret_cast(password.data()),\n password.size(),\n salt.data(),\n salt.size(),\n kCCPRFHmacAlgSHA256,\n iteration_count,\n &key[0],\n size);\n#endif\n\n return key;\n}\n\nstd::vector Fetcher::sha256(std::string const &text)\n{\n#ifdef USE_OPENSSL\n std::vector hash(SHA256_DIGEST_LENGTH);\n SHA256_CTX sha256;\n SHA256_Init(&sha256);\n SHA256_Update(&sha256, text.c_str(), text.size());\n SHA256_Final(&hash[0], &sha256);\n#else\n std::vector hash(CC_SHA256_DIGEST_LENGTH);\n CC_SHA256(text.c_str(), text.size(), &hash[0]);\n#endif\n\n return hash;\n}\n\nstd::vector Fetcher::to_bytes(std::string const &text)\n{\n std::vector bytes(text.size());\n std::copy(text.begin(), text.end(), bytes.begin());\n return bytes;\n}\n\nstd::string Fetcher::to_hex(std::vector const &bytes)\n{\n static char const hex_chars[16] = {'0', '1', '2', '3', '4', '5', '6', '7',\n '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};\n\n std::string hex;\n hex.reserve(bytes.size() * 2);\n\n for (auto i: bytes)\n {\n hex += hex_chars[i \/ 16];\n hex += hex_chars[i % 16];\n }\n\n return hex;\n}\n\nstd::vector Fetcher::decode_base64(std::string const &base64_text)\n{\n \/\/ The size is the upper bound, the actual size could be smaller.\n \/\/ After decoding we need to trim unused space.\n std::vector decoded(base64_text.size() * 3 \/ 4);\n\n#ifdef USE_OPENSSL\n BIO *context = BIO_push(BIO_new(BIO_f_base64()),\n BIO_new_mem_buf((void *)base64_text.c_str(), base64_text.size()));\n BIO_set_flags(context, BIO_FLAGS_BASE64_NO_NL | BIO_FLAGS_MEM_RDONLY);\n size_t actual_size = BIO_read(context, decoded.data(), decoded.size());\n BIO_free_all(context);\n#else\n size_t actual_size = b64_pton(base64_text.c_str(), decoded.data(), decoded.size());\n#endif\n\n decoded.resize(actual_size);\n return decoded;\n}\n\n}\n<|endoftext|>"} {"text":"\/*===================================================================\n\nThe Medical Imaging Interaction Toolkit (MITK)\n\nCopyright (c) German Cancer Research Center,\nDivision of Medical and Biological Informatics.\nAll rights reserved.\n\nThis software is distributed WITHOUT ANY WARRANTY; without\neven the implied warranty of MERCHANTABILITY or FITNESS FOR\nA PARTICULAR PURPOSE.\n\nSee LICENSE.txt or http:\/\/www.mitk.org for details.\n\n===================================================================*\/\n\n#include \"QmitkNavigationToolCreationWidget.h\"\n\n\/\/mitk headers\n#include \"mitkTrackingTypes.h\"\n#include \n#include \n#include \"mitkNavigationData.h\"\n#include \"mitkRenderingManager.h\"\n\n\/\/qt headers\n#include \n#include \n#include \n\n\/\/poco headers\n#include \n\n\/\/ vtk\n#include \n#include \"vtkConeSource.h\"\n\nconst std::string QmitkNavigationToolCreationWidget::VIEW_ID = \"org.mitk.views.navigationtoolcreationwizardwidget\";\n\nQmitkNavigationToolCreationWidget::QmitkNavigationToolCreationWidget(QWidget* parent, Qt::WindowFlags f)\n: QWidget(parent, f)\n{\n m_Controls = NULL;\n m_AdvancedWidget = new QmitkNavigationToolCreationAdvancedWidget(this);\n m_AdvancedWidget->setWindowFlags(Qt::Tool | Qt::WindowStaysOnTopHint);\n m_AdvancedWidget->setWindowTitle(\"Tool Creation Advanced Options\");\n m_AdvancedWidget->setModal(false);\n CreateQtPartControl(this);\n CreateConnections();\n}\n\nQmitkNavigationToolCreationWidget::~QmitkNavigationToolCreationWidget()\n{\n delete m_AdvancedWidget;\n}\n\nvoid QmitkNavigationToolCreationWidget::CreateQtPartControl(QWidget *parent)\n{\n if (!m_Controls)\n {\n \/\/ create GUI widgets\n m_Controls = new Ui::QmitkNavigationToolCreationWidgetControls;\n m_Controls->setupUi(parent);\n }\n}\n\nvoid QmitkNavigationToolCreationWidget::CreateConnections()\n{\n if ( m_Controls )\n {\n connect( (QObject*)(m_Controls->m_cancel), SIGNAL(clicked()), this, SLOT(OnCancel()) );\n connect( (QObject*)(m_Controls->m_finished), SIGNAL(clicked()), this, SLOT(OnFinished()) );\n connect( (QObject*)(m_Controls->m_LoadSurface), SIGNAL(clicked()), this, SLOT(OnLoadSurface()) );\n connect( (QObject*)(m_Controls->m_LoadCalibrationFile), SIGNAL(clicked()), this, SLOT(OnLoadCalibrationFile()) );\n connect( (QObject*)(m_Controls->m_ShowAdvancedOptionsPB), SIGNAL(toggled(bool)), this, SLOT(OnShowAdvancedOptions(bool)) );\n connect( (QObject*)(m_AdvancedWidget), SIGNAL(DialogCloseRequested()), this, SLOT(OnProcessDialogCloseRequest()) );\n connect( (QObject*)(m_AdvancedWidget), SIGNAL(RetrieveDataForManualToolTipManipulation()), this, SLOT(OnRetrieveDataForManualTooltipManipulation()) );\n }\n}\n\nvoid QmitkNavigationToolCreationWidget::Initialize(mitk::DataStorage* dataStorage, std::string supposedIdentifier, std::string supposedName)\n{\n m_DataStorage = dataStorage;\n\n \/\/initialize UI components\n m_Controls->m_SurfaceChooser->SetDataStorage(m_DataStorage);\n m_Controls->m_SurfaceChooser->SetAutoSelectNewItems(true);\n m_Controls->m_SurfaceChooser->SetPredicate(mitk::NodePredicateDataType::New(\"Surface\"));\n\n \/\/set default data\n m_Controls->m_ToolNameEdit->setText(supposedName.c_str());\n m_Controls->m_CalibrationFileName->setText(\"none\");\n m_Controls->m_Surface_Use_Sphere->setChecked(true);\n m_AdvancedWidget->SetDataStorage(m_DataStorage);\n\n}\n\nvoid QmitkNavigationToolCreationWidget::SetTrackingDeviceType(mitk::TrackingDeviceType type, bool changeable)\n{\n switch(type)\n {\n case mitk::NDIAurora:\n m_Controls->m_TrackingDeviceTypeChooser->setCurrentIndex(0);break;\n case mitk::NDIPolaris:\n m_Controls->m_TrackingDeviceTypeChooser->setCurrentIndex(1);break;\n case mitk::ClaronMicron:\n m_Controls->m_TrackingDeviceTypeChooser->setCurrentIndex(2);break;\n default:\n m_Controls->m_TrackingDeviceTypeChooser->setCurrentIndex(0);\n }\n m_Controls->m_TrackingDeviceTypeChooser->setEnabled(changeable);\n}\n\nmitk::NavigationTool::Pointer QmitkNavigationToolCreationWidget::GetCreatedTool()\n{\n return m_CreatedTool;\n}\n\n\/\/##################################################################################\n\/\/############################## slots ############################\n\/\/##################################################################################\n\nvoid QmitkNavigationToolCreationWidget::OnFinished()\n{\n \/\/here we create a new tool\n m_CreatedTool = mitk::NavigationTool::New();\n\n \/\/create DataNode...\n mitk::DataNode::Pointer newNode = mitk::DataNode::New();\n if(m_Controls->m_Surface_Use_Sphere->isChecked())\n {\n \/\/create small sphere and use it as surface\n mitk::Surface::Pointer mySphere = mitk::Surface::New();\n vtkConeSource *vtkData = vtkConeSource::New();\n vtkData->SetAngle(5.0);\n vtkData->SetResolution(50);\n vtkData->SetHeight(6.0f);\n vtkData->SetRadius(2.0f);\n vtkData->SetCenter(0.0, 0.0, 0.0);\n vtkData->Update();\n mySphere->SetVtkPolyData(vtkData->GetOutput());\n vtkData->Delete();\n newNode->SetData(mySphere);\n }\n else\n {\n newNode->SetData(m_Controls->m_SurfaceChooser->GetSelectedNode()->GetData());\n }\n newNode->SetName(m_Controls->m_ToolNameEdit->text().toLatin1());\n\n m_CreatedTool->SetDataNode(newNode);\n\n \/\/fill NavigationTool object\n m_CreatedTool->SetCalibrationFile(m_Controls->m_CalibrationFileName->text().toAscii().data());\n m_CreatedTool->SetIdentifier(m_Controls->m_IdentifierEdit->text().toAscii().data());\n m_CreatedTool->SetSerialNumber(m_Controls->m_SerialNumberEdit->text().toAscii().data());\n\n \/\/Tracking Device\n if (m_Controls->m_TrackingDeviceTypeChooser->currentText()==\"NDI Aurora\") m_CreatedTool->SetTrackingDeviceType(mitk::NDIAurora);\n else if (m_Controls->m_TrackingDeviceTypeChooser->currentText()==\"NDI Polaris\") m_CreatedTool->SetTrackingDeviceType(mitk::NDIPolaris);\n else if (m_Controls->m_TrackingDeviceTypeChooser->currentText()==\"Claron Technology Micron Tracker\") m_CreatedTool->SetTrackingDeviceType(mitk::ClaronMicron);\n else m_CreatedTool->SetTrackingDeviceType(mitk::TrackingSystemNotSpecified);\n\n \/\/ToolType\n if (m_Controls->m_ToolTypeChooser->currentText()==\"Instrument\") m_CreatedTool->SetType(mitk::NavigationTool::Instrument);\n else if (m_Controls->m_ToolTypeChooser->currentText()==\"Fiducial\") m_CreatedTool->SetType(mitk::NavigationTool::Fiducial);\n else if (m_Controls->m_ToolTypeChooser->currentText()==\"Skinmarker\") m_CreatedTool->SetType(mitk::NavigationTool::Skinmarker);\n else m_CreatedTool->SetType(mitk::NavigationTool::Unknown);\n\n mitk::NavigationData::Pointer tempND = mitk::NavigationData::New(m_AdvancedWidget->GetManipulatedToolTip());\n m_CreatedTool->SetToolTipOrientation(tempND->GetOrientation());\n m_CreatedTool->SetToolTipPosition(tempND->GetPosition());\n\n emit NavigationToolFinished();\n}\n\nvoid QmitkNavigationToolCreationWidget::OnCancel()\n{\n m_CreatedTool = NULL;\n\n emit Canceled();\n}\n\nvoid QmitkNavigationToolCreationWidget::OnLoadSurface()\n{\n std::string filename = QFileDialog::getOpenFileName(NULL,tr(\"Open Surface\"), \"\/\", \"*.stl\").toLatin1().data();\n mitk::STLFileReader::Pointer stlReader = mitk::STLFileReader::New();\n try\n {\n stlReader->SetFileName( filename.c_str() );\n stlReader->Update();\n }\n catch (...)\n {\n }\n\n if ( stlReader->GetOutput() == NULL );\n else\n {\n mitk::DataNode::Pointer newNode = mitk::DataNode::New();\n newNode->SetName(filename);\n newNode->SetData(stlReader->GetOutput());\n m_DataStorage->Add(newNode);\n }\n}\n\nvoid QmitkNavigationToolCreationWidget::OnLoadCalibrationFile()\n{\n m_Controls->m_CalibrationFileName->setText(QFileDialog::getOpenFileName(NULL,tr(\"Open Calibration File\"), \"\/\", \"*.*\"));\n}\n\nvoid QmitkNavigationToolCreationWidget::SetDefaultData(mitk::NavigationTool::Pointer DefaultTool)\n{\n m_Controls->m_ToolNameEdit->setText(QString(DefaultTool->GetDataNode()->GetName().c_str()));\n m_Controls->m_IdentifierEdit->setText(QString(DefaultTool->GetIdentifier().c_str()));\n m_Controls->m_SerialNumberEdit->setText(QString(DefaultTool->GetSerialNumber().c_str()));\n m_AdvancedWidget->SetDefaultTooltip( DefaultTool->GetToolTipTransform() );\n switch(DefaultTool->GetTrackingDeviceType())\n {\n case mitk::NDIAurora:\n m_Controls->m_TrackingDeviceTypeChooser->setCurrentIndex(0);break;\n case mitk::NDIPolaris:\n m_Controls->m_TrackingDeviceTypeChooser->setCurrentIndex(1);break;\n case mitk::ClaronMicron:\n m_Controls->m_TrackingDeviceTypeChooser->setCurrentIndex(2);break;\n default:\n m_Controls->m_TrackingDeviceTypeChooser->setCurrentIndex(0);\n }\n m_Controls->m_CalibrationFileName->setText(QString(DefaultTool->GetCalibrationFile().c_str()));\n m_Controls->m_Surface_Use_Other->setChecked(true);\n switch(DefaultTool->GetType())\n {\n case mitk::NavigationTool::Instrument:\n m_Controls->m_ToolTypeChooser->setCurrentIndex(0); break;\n case mitk::NavigationTool::Fiducial:\n m_Controls->m_ToolTypeChooser->setCurrentIndex(1); break;\n case mitk::NavigationTool::Skinmarker:\n m_Controls->m_ToolTypeChooser->setCurrentIndex(2); break;\n case mitk::NavigationTool::Unknown:\n m_Controls->m_ToolTypeChooser->setCurrentIndex(3); break;\n }\n\n m_Controls->m_SurfaceChooser->SetSelectedNode(DefaultTool->GetDataNode());\n\n}\n\n\n\n\/\/##################################################################################\n\/\/############################## internal help methods #############################\n\/\/##################################################################################\nvoid QmitkNavigationToolCreationWidget::MessageBox(std::string s)\n{\n QMessageBox msgBox;\n msgBox.setText(s.c_str());\n msgBox.exec();\n}\n\nvoid QmitkNavigationToolCreationWidget::OnShowAdvancedOptions(bool state)\n{\n if(state)\n {\n m_AdvancedWidget->show();\n m_AdvancedWidget->SetDefaultTooltip(m_AdvancedWidget->GetManipulatedToolTip()); \/\/use the last one, if there is one\n m_AdvancedWidget->ReInitialize();\n\n \/\/ reinit the views with the new nodes\n mitk::DataStorage::SetOfObjects::ConstPointer rs = m_DataStorage->GetAll();\n mitk::TimeGeometry::Pointer bounds = m_DataStorage->ComputeBoundingGeometry3D(rs, \"visible\"); \/\/ initialize the views to the bounding geometry\n mitk::RenderingManager::GetInstance()->InitializeViews(bounds);\n }\n else\n {\n m_AdvancedWidget->hide();\n }\n}\n\nvoid QmitkNavigationToolCreationWidget::OnProcessDialogCloseRequest()\n{\n m_AdvancedWidget->hide();\n m_Controls->m_ShowAdvancedOptionsPB->setChecked(false);\n}\n\nvoid QmitkNavigationToolCreationWidget::OnRetrieveDataForManualTooltipManipulation()\n{\n if(m_Controls->m_Surface_Use_Sphere->isChecked())\n {\n m_AdvancedWidget->SetToolTipSurface(true);\n }\n else\n {\n m_AdvancedWidget->SetToolTipSurface(false,\n dynamic_cast(m_Controls->m_SurfaceChooser->GetSelectedNode().GetPointer()));\n }\n}\nSupposedIdentifier is added as default text in Initialize.\/*===================================================================\n\nThe Medical Imaging Interaction Toolkit (MITK)\n\nCopyright (c) German Cancer Research Center,\nDivision of Medical and Biological Informatics.\nAll rights reserved.\n\nThis software is distributed WITHOUT ANY WARRANTY; without\neven the implied warranty of MERCHANTABILITY or FITNESS FOR\nA PARTICULAR PURPOSE.\n\nSee LICENSE.txt or http:\/\/www.mitk.org for details.\n\n===================================================================*\/\n\n#include \"QmitkNavigationToolCreationWidget.h\"\n\n\/\/mitk headers\n#include \"mitkTrackingTypes.h\"\n#include \n#include \n#include \"mitkNavigationData.h\"\n#include \"mitkRenderingManager.h\"\n\n\/\/qt headers\n#include \n#include \n#include \n\n\/\/poco headers\n#include \n\n\/\/ vtk\n#include \n#include \"vtkConeSource.h\"\n\nconst std::string QmitkNavigationToolCreationWidget::VIEW_ID = \"org.mitk.views.navigationtoolcreationwizardwidget\";\n\nQmitkNavigationToolCreationWidget::QmitkNavigationToolCreationWidget(QWidget* parent, Qt::WindowFlags f)\n: QWidget(parent, f)\n{\n m_Controls = NULL;\n m_AdvancedWidget = new QmitkNavigationToolCreationAdvancedWidget(this);\n m_AdvancedWidget->setWindowFlags(Qt::Tool | Qt::WindowStaysOnTopHint);\n m_AdvancedWidget->setWindowTitle(\"Tool Creation Advanced Options\");\n m_AdvancedWidget->setModal(false);\n CreateQtPartControl(this);\n CreateConnections();\n}\n\nQmitkNavigationToolCreationWidget::~QmitkNavigationToolCreationWidget()\n{\n delete m_AdvancedWidget;\n}\n\nvoid QmitkNavigationToolCreationWidget::CreateQtPartControl(QWidget *parent)\n{\n if (!m_Controls)\n {\n \/\/ create GUI widgets\n m_Controls = new Ui::QmitkNavigationToolCreationWidgetControls;\n m_Controls->setupUi(parent);\n }\n}\n\nvoid QmitkNavigationToolCreationWidget::CreateConnections()\n{\n if ( m_Controls )\n {\n connect( (QObject*)(m_Controls->m_cancel), SIGNAL(clicked()), this, SLOT(OnCancel()) );\n connect( (QObject*)(m_Controls->m_finished), SIGNAL(clicked()), this, SLOT(OnFinished()) );\n connect( (QObject*)(m_Controls->m_LoadSurface), SIGNAL(clicked()), this, SLOT(OnLoadSurface()) );\n connect( (QObject*)(m_Controls->m_LoadCalibrationFile), SIGNAL(clicked()), this, SLOT(OnLoadCalibrationFile()) );\n connect( (QObject*)(m_Controls->m_ShowAdvancedOptionsPB), SIGNAL(toggled(bool)), this, SLOT(OnShowAdvancedOptions(bool)) );\n connect( (QObject*)(m_AdvancedWidget), SIGNAL(DialogCloseRequested()), this, SLOT(OnProcessDialogCloseRequest()) );\n connect( (QObject*)(m_AdvancedWidget), SIGNAL(RetrieveDataForManualToolTipManipulation()), this, SLOT(OnRetrieveDataForManualTooltipManipulation()) );\n }\n}\n\nvoid QmitkNavigationToolCreationWidget::Initialize(mitk::DataStorage* dataStorage, std::string supposedIdentifier, std::string supposedName)\n{\n m_DataStorage = dataStorage;\n\n \/\/initialize UI components\n m_Controls->m_SurfaceChooser->SetDataStorage(m_DataStorage);\n m_Controls->m_SurfaceChooser->SetAutoSelectNewItems(true);\n m_Controls->m_SurfaceChooser->SetPredicate(mitk::NodePredicateDataType::New(\"Surface\"));\n\n \/\/set default data\n m_Controls->m_ToolNameEdit->setText(supposedName.c_str());\n m_Controls->m_CalibrationFileName->setText(\"none\");\n m_Controls->m_Surface_Use_Sphere->setChecked(true);\n m_AdvancedWidget->SetDataStorage(m_DataStorage);\n m_Controls->m_IdentifierEdit->setText(supposedIdentifier.c_str());\n\n}\n\nvoid QmitkNavigationToolCreationWidget::SetTrackingDeviceType(mitk::TrackingDeviceType type, bool changeable)\n{\n switch(type)\n {\n case mitk::NDIAurora:\n m_Controls->m_TrackingDeviceTypeChooser->setCurrentIndex(0);break;\n case mitk::NDIPolaris:\n m_Controls->m_TrackingDeviceTypeChooser->setCurrentIndex(1);break;\n case mitk::ClaronMicron:\n m_Controls->m_TrackingDeviceTypeChooser->setCurrentIndex(2);break;\n default:\n m_Controls->m_TrackingDeviceTypeChooser->setCurrentIndex(0);\n }\n m_Controls->m_TrackingDeviceTypeChooser->setEnabled(changeable);\n}\n\nmitk::NavigationTool::Pointer QmitkNavigationToolCreationWidget::GetCreatedTool()\n{\n return m_CreatedTool;\n}\n\n\/\/##################################################################################\n\/\/############################## slots ############################\n\/\/##################################################################################\n\nvoid QmitkNavigationToolCreationWidget::OnFinished()\n{\n \/\/here we create a new tool\n m_CreatedTool = mitk::NavigationTool::New();\n\n \/\/create DataNode...\n mitk::DataNode::Pointer newNode = mitk::DataNode::New();\n if(m_Controls->m_Surface_Use_Sphere->isChecked())\n {\n \/\/create small sphere and use it as surface\n mitk::Surface::Pointer mySphere = mitk::Surface::New();\n vtkConeSource *vtkData = vtkConeSource::New();\n vtkData->SetAngle(5.0);\n vtkData->SetResolution(50);\n vtkData->SetHeight(6.0f);\n vtkData->SetRadius(2.0f);\n vtkData->SetCenter(0.0, 0.0, 0.0);\n vtkData->Update();\n mySphere->SetVtkPolyData(vtkData->GetOutput());\n vtkData->Delete();\n newNode->SetData(mySphere);\n }\n else\n {\n newNode->SetData(m_Controls->m_SurfaceChooser->GetSelectedNode()->GetData());\n }\n newNode->SetName(m_Controls->m_ToolNameEdit->text().toLatin1());\n\n m_CreatedTool->SetDataNode(newNode);\n\n \/\/fill NavigationTool object\n m_CreatedTool->SetCalibrationFile(m_Controls->m_CalibrationFileName->text().toAscii().data());\n m_CreatedTool->SetIdentifier(m_Controls->m_IdentifierEdit->text().toAscii().data());\n m_CreatedTool->SetSerialNumber(m_Controls->m_SerialNumberEdit->text().toAscii().data());\n\n \/\/Tracking Device\n if (m_Controls->m_TrackingDeviceTypeChooser->currentText()==\"NDI Aurora\") m_CreatedTool->SetTrackingDeviceType(mitk::NDIAurora);\n else if (m_Controls->m_TrackingDeviceTypeChooser->currentText()==\"NDI Polaris\") m_CreatedTool->SetTrackingDeviceType(mitk::NDIPolaris);\n else if (m_Controls->m_TrackingDeviceTypeChooser->currentText()==\"Claron Technology Micron Tracker\") m_CreatedTool->SetTrackingDeviceType(mitk::ClaronMicron);\n else m_CreatedTool->SetTrackingDeviceType(mitk::TrackingSystemNotSpecified);\n\n \/\/ToolType\n if (m_Controls->m_ToolTypeChooser->currentText()==\"Instrument\") m_CreatedTool->SetType(mitk::NavigationTool::Instrument);\n else if (m_Controls->m_ToolTypeChooser->currentText()==\"Fiducial\") m_CreatedTool->SetType(mitk::NavigationTool::Fiducial);\n else if (m_Controls->m_ToolTypeChooser->currentText()==\"Skinmarker\") m_CreatedTool->SetType(mitk::NavigationTool::Skinmarker);\n else m_CreatedTool->SetType(mitk::NavigationTool::Unknown);\n\n mitk::NavigationData::Pointer tempND = mitk::NavigationData::New(m_AdvancedWidget->GetManipulatedToolTip());\n m_CreatedTool->SetToolTipOrientation(tempND->GetOrientation());\n m_CreatedTool->SetToolTipPosition(tempND->GetPosition());\n\n emit NavigationToolFinished();\n}\n\nvoid QmitkNavigationToolCreationWidget::OnCancel()\n{\n m_CreatedTool = NULL;\n\n emit Canceled();\n}\n\nvoid QmitkNavigationToolCreationWidget::OnLoadSurface()\n{\n std::string filename = QFileDialog::getOpenFileName(NULL,tr(\"Open Surface\"), \"\/\", \"*.stl\").toLatin1().data();\n mitk::STLFileReader::Pointer stlReader = mitk::STLFileReader::New();\n try\n {\n stlReader->SetFileName( filename.c_str() );\n stlReader->Update();\n }\n catch (...)\n {\n }\n\n if ( stlReader->GetOutput() == NULL );\n else\n {\n mitk::DataNode::Pointer newNode = mitk::DataNode::New();\n newNode->SetName(filename);\n newNode->SetData(stlReader->GetOutput());\n m_DataStorage->Add(newNode);\n }\n}\n\nvoid QmitkNavigationToolCreationWidget::OnLoadCalibrationFile()\n{\n m_Controls->m_CalibrationFileName->setText(QFileDialog::getOpenFileName(NULL,tr(\"Open Calibration File\"), \"\/\", \"*.*\"));\n}\n\nvoid QmitkNavigationToolCreationWidget::SetDefaultData(mitk::NavigationTool::Pointer DefaultTool)\n{\n m_Controls->m_ToolNameEdit->setText(QString(DefaultTool->GetDataNode()->GetName().c_str()));\n m_Controls->m_IdentifierEdit->setText(QString(DefaultTool->GetIdentifier().c_str()));\n m_Controls->m_SerialNumberEdit->setText(QString(DefaultTool->GetSerialNumber().c_str()));\n m_AdvancedWidget->SetDefaultTooltip( DefaultTool->GetToolTipTransform() );\n switch(DefaultTool->GetTrackingDeviceType())\n {\n case mitk::NDIAurora:\n m_Controls->m_TrackingDeviceTypeChooser->setCurrentIndex(0);break;\n case mitk::NDIPolaris:\n m_Controls->m_TrackingDeviceTypeChooser->setCurrentIndex(1);break;\n case mitk::ClaronMicron:\n m_Controls->m_TrackingDeviceTypeChooser->setCurrentIndex(2);break;\n default:\n m_Controls->m_TrackingDeviceTypeChooser->setCurrentIndex(0);\n }\n m_Controls->m_CalibrationFileName->setText(QString(DefaultTool->GetCalibrationFile().c_str()));\n m_Controls->m_Surface_Use_Other->setChecked(true);\n switch(DefaultTool->GetType())\n {\n case mitk::NavigationTool::Instrument:\n m_Controls->m_ToolTypeChooser->setCurrentIndex(0); break;\n case mitk::NavigationTool::Fiducial:\n m_Controls->m_ToolTypeChooser->setCurrentIndex(1); break;\n case mitk::NavigationTool::Skinmarker:\n m_Controls->m_ToolTypeChooser->setCurrentIndex(2); break;\n case mitk::NavigationTool::Unknown:\n m_Controls->m_ToolTypeChooser->setCurrentIndex(3); break;\n }\n\n m_Controls->m_SurfaceChooser->SetSelectedNode(DefaultTool->GetDataNode());\n\n}\n\n\n\n\/\/##################################################################################\n\/\/############################## internal help methods #############################\n\/\/##################################################################################\nvoid QmitkNavigationToolCreationWidget::MessageBox(std::string s)\n{\n QMessageBox msgBox;\n msgBox.setText(s.c_str());\n msgBox.exec();\n}\n\nvoid QmitkNavigationToolCreationWidget::OnShowAdvancedOptions(bool state)\n{\n if(state)\n {\n m_AdvancedWidget->show();\n m_AdvancedWidget->SetDefaultTooltip(m_AdvancedWidget->GetManipulatedToolTip()); \/\/use the last one, if there is one\n m_AdvancedWidget->ReInitialize();\n\n \/\/ reinit the views with the new nodes\n mitk::DataStorage::SetOfObjects::ConstPointer rs = m_DataStorage->GetAll();\n mitk::TimeGeometry::Pointer bounds = m_DataStorage->ComputeBoundingGeometry3D(rs, \"visible\"); \/\/ initialize the views to the bounding geometry\n mitk::RenderingManager::GetInstance()->InitializeViews(bounds);\n }\n else\n {\n m_AdvancedWidget->hide();\n }\n}\n\nvoid QmitkNavigationToolCreationWidget::OnProcessDialogCloseRequest()\n{\n m_AdvancedWidget->hide();\n m_Controls->m_ShowAdvancedOptionsPB->setChecked(false);\n}\n\nvoid QmitkNavigationToolCreationWidget::OnRetrieveDataForManualTooltipManipulation()\n{\n if(m_Controls->m_Surface_Use_Sphere->isChecked())\n {\n m_AdvancedWidget->SetToolTipSurface(true);\n }\n else\n {\n m_AdvancedWidget->SetToolTipSurface(false,\n dynamic_cast(m_Controls->m_SurfaceChooser->GetSelectedNode().GetPointer()));\n }\n}\n<|endoftext|>"} {"text":"\/*===================================================================\n\nThe Medical Imaging Interaction Toolkit (MITK)\n\nCopyright (c) German Cancer Research Center,\nDivision of Medical and Biological Informatics.\nAll rights reserved.\n\nThis software is distributed WITHOUT ANY WARRANTY; without\neven the implied warranty of MERCHANTABILITY or FITNESS FOR\nA PARTICULAR PURPOSE.\n\nSee LICENSE.txt or http:\/\/www.mitk.org for details.\n\n===================================================================*\/\n\n#include \"mitkCorrectorTool2D.h\"\n#include \"mitkCorrectorAlgorithm.h\"\n\n#include \"mitkToolManager.h\"\n#include \"mitkBaseRenderer.h\"\n#include \"mitkRenderingManager.h\"\n\n#include \"mitkCorrectorTool2D.xpm\"\n\n\/\/ us\n#include \"mitkModule.h\"\n#include \"mitkModuleResource.h\"\n#include \n\nnamespace mitk {\n MITK_TOOL_MACRO(Segmentation_EXPORT, CorrectorTool2D, \"Correction tool\");\n}\n\nmitk::CorrectorTool2D::CorrectorTool2D(int paintingPixelValue)\n:FeedbackContourTool(\"PressMoveRelease\"),\n m_PaintingPixelValue(paintingPixelValue)\n{\n \/\/ great magic numbers\n CONNECT_ACTION( 80, OnMousePressed );\n CONNECT_ACTION( 90, OnMouseMoved );\n CONNECT_ACTION( 42, OnMouseReleased );\n\n GetFeedbackContour()->SetIsClosed( false ); \/\/ don't close the contour to a polygon\n}\n\nmitk::CorrectorTool2D::~CorrectorTool2D()\n{\n}\n\nconst char** mitk::CorrectorTool2D::GetXPM() const\n{\n return mitkCorrectorTool2D_xpm;\n}\n\nmitk::ModuleResource mitk::CorrectorTool2D::GetIconResource() const\n{\n Module* module = GetModuleContext()->GetModule();\n ModuleResource resource = module->GetResource(\"Correction_48x48.png\");\n return resource;\n}\n\nmitk::ModuleResource mitk::CorrectorTool2D::GetCursorIconResource() const\n{\n Module* module = GetModuleContext()->GetModule();\n ModuleResource resource = module->GetResource(\"Correction_Cursor_32x32.png\");\n return resource;\n}\n\nconst char* mitk::CorrectorTool2D::GetName() const\n{\n return \"Correction\";\n}\n\nvoid mitk::CorrectorTool2D::Activated()\n{\n Superclass::Activated();\n}\n\nvoid mitk::CorrectorTool2D::Deactivated()\n{\n Superclass::Deactivated();\n}\n\nbool mitk::CorrectorTool2D::OnMousePressed (Action* action, const StateEvent* stateEvent)\n{\n const PositionEvent* positionEvent = dynamic_cast(stateEvent->GetEvent());\n if (!positionEvent) return false;\n\n m_LastEventSender = positionEvent->GetSender();\n m_LastEventSlice = m_LastEventSender->GetSlice();\n\n if ( FeedbackContourTool::CanHandleEvent(stateEvent) < 1.0 ) return false;\n\n ContourModel* contour = FeedbackContourTool::GetFeedbackContour();\n contour->Clear(positionEvent->GetSender()->GetTimeStep());\n contour->AddVertex( positionEvent->GetWorldPosition() );\n\n FeedbackContourTool::SetFeedbackContourVisible(true);\n\n return true;\n}\n\nbool mitk::CorrectorTool2D::OnMouseMoved (Action* action, const StateEvent* stateEvent)\n{\n if ( FeedbackContourTool::CanHandleEvent(stateEvent) < 1.0 ) return false;\n\n const PositionEvent* positionEvent = dynamic_cast(stateEvent->GetEvent());\n if (!positionEvent) return false;\n\n ContourModel* contour = FeedbackContourTool::GetFeedbackContour();\n contour->AddVertex( positionEvent->GetWorldPosition() );\n\n assert( positionEvent->GetSender()->GetRenderWindow() );\n mitk::RenderingManager::GetInstance()->RequestUpdate( positionEvent->GetSender()->GetRenderWindow() );\n\n return true;\n}\n\nbool mitk::CorrectorTool2D::OnMouseReleased(Action* action, const StateEvent* stateEvent)\n{\n \/\/ 1. Hide the feedback contour, find out which slice the user clicked, find out which slice of the toolmanager's working image corresponds to that\n FeedbackContourTool::SetFeedbackContourVisible(false);\n\n const PositionEvent* positionEvent = dynamic_cast(stateEvent->GetEvent());\n if (!positionEvent) return false;\n\n assert( positionEvent->GetSender()->GetRenderWindow() );\n mitk::RenderingManager::GetInstance()->RequestUpdate( positionEvent->GetSender()->GetRenderWindow() );\n\n if ( FeedbackContourTool::CanHandleEvent(stateEvent) < 1.0 ) return false;\n\n DataNode* workingNode( m_ToolManager->GetWorkingData(0) );\n if (!workingNode) return false;\n\n Image* image = dynamic_cast(workingNode->GetData());\n const PlaneGeometry* planeGeometry( dynamic_cast (positionEvent->GetSender()->GetCurrentWorldGeometry2D() ) );\n if ( !image || !planeGeometry ) return false;\n\n \/\/ 2. Slice is known, now we try to get it as a 2D image and project the contour into index coordinates of this slice\n m_WorkingSlice = FeedbackContourTool::GetAffectedImageSliceAs2DImage( positionEvent, image );\n\n if ( m_WorkingSlice.IsNull() )\n {\n MITK_ERROR << \"Unable to extract slice.\" << std::endl;\n return false;\n }\n\n CorrectorAlgorithm::Pointer algorithm = CorrectorAlgorithm::New();\n algorithm->SetInput( m_WorkingSlice );\n algorithm->SetContour( FeedbackContourTool::GetFeedbackContour() );\n try\n {\n algorithm->UpdateLargestPossibleRegion();\n }\n catch ( std::exception& e )\n {\n MITK_ERROR << \"Caught exception '\" << e.what() << \"'\" << std::endl;\n }\n\n mitk::Image::Pointer resultSlice = mitk::Image::New();\n resultSlice->Initialize(algorithm->GetOutput());\n resultSlice->SetVolume(algorithm->GetOutput()->GetData());\n\n this->WriteBackSegmentationResult(positionEvent, resultSlice);\n\n return true;\n}\n\n4D contour support for CorrectorTool\/*===================================================================\n\nThe Medical Imaging Interaction Toolkit (MITK)\n\nCopyright (c) German Cancer Research Center,\nDivision of Medical and Biological Informatics.\nAll rights reserved.\n\nThis software is distributed WITHOUT ANY WARRANTY; without\neven the implied warranty of MERCHANTABILITY or FITNESS FOR\nA PARTICULAR PURPOSE.\n\nSee LICENSE.txt or http:\/\/www.mitk.org for details.\n\n===================================================================*\/\n\n#include \"mitkCorrectorTool2D.h\"\n#include \"mitkCorrectorAlgorithm.h\"\n\n#include \"mitkToolManager.h\"\n#include \"mitkBaseRenderer.h\"\n#include \"mitkRenderingManager.h\"\n\n#include \"mitkCorrectorTool2D.xpm\"\n\n\/\/ us\n#include \"mitkModule.h\"\n#include \"mitkModuleResource.h\"\n#include \n\nnamespace mitk {\n MITK_TOOL_MACRO(Segmentation_EXPORT, CorrectorTool2D, \"Correction tool\");\n}\n\nmitk::CorrectorTool2D::CorrectorTool2D(int paintingPixelValue)\n:FeedbackContourTool(\"PressMoveRelease\"),\n m_PaintingPixelValue(paintingPixelValue)\n{\n \/\/ great magic numbers\n CONNECT_ACTION( 80, OnMousePressed );\n CONNECT_ACTION( 90, OnMouseMoved );\n CONNECT_ACTION( 42, OnMouseReleased );\n\n GetFeedbackContour()->SetIsClosed( false ); \/\/ don't close the contour to a polygon\n}\n\nmitk::CorrectorTool2D::~CorrectorTool2D()\n{\n}\n\nconst char** mitk::CorrectorTool2D::GetXPM() const\n{\n return mitkCorrectorTool2D_xpm;\n}\n\nmitk::ModuleResource mitk::CorrectorTool2D::GetIconResource() const\n{\n Module* module = GetModuleContext()->GetModule();\n ModuleResource resource = module->GetResource(\"Correction_48x48.png\");\n return resource;\n}\n\nmitk::ModuleResource mitk::CorrectorTool2D::GetCursorIconResource() const\n{\n Module* module = GetModuleContext()->GetModule();\n ModuleResource resource = module->GetResource(\"Correction_Cursor_32x32.png\");\n return resource;\n}\n\nconst char* mitk::CorrectorTool2D::GetName() const\n{\n return \"Correction\";\n}\n\nvoid mitk::CorrectorTool2D::Activated()\n{\n Superclass::Activated();\n}\n\nvoid mitk::CorrectorTool2D::Deactivated()\n{\n Superclass::Deactivated();\n}\n\nbool mitk::CorrectorTool2D::OnMousePressed (Action* action, const StateEvent* stateEvent)\n{\n const PositionEvent* positionEvent = dynamic_cast(stateEvent->GetEvent());\n if (!positionEvent) return false;\n\n m_LastEventSender = positionEvent->GetSender();\n m_LastEventSlice = m_LastEventSender->GetSlice();\n\n if ( FeedbackContourTool::CanHandleEvent(stateEvent) < 1.0 ) return false;\n\n int timestep = positionEvent->GetSender()->GetTimeStep();\n ContourModel* contour = FeedbackContourTool::GetFeedbackContour();\n contour->Clear();\n contour->Expand(timestep);\n contour->SetIsClosed(false, timestep);\n contour->AddVertex( positionEvent->GetWorldPosition(), timestep );\n\n FeedbackContourTool::SetFeedbackContourVisible(true);\n\n return true;\n}\n\nbool mitk::CorrectorTool2D::OnMouseMoved (Action* action, const StateEvent* stateEvent)\n{\n if ( FeedbackContourTool::CanHandleEvent(stateEvent) < 1.0 ) return false;\n\n const PositionEvent* positionEvent = dynamic_cast(stateEvent->GetEvent());\n if (!positionEvent) return false;\n\n int timestep = positionEvent->GetSender()->GetTimeStep();\n ContourModel* contour = FeedbackContourTool::GetFeedbackContour();\n contour->AddVertex( positionEvent->GetWorldPosition(), timestep );\n\n assert( positionEvent->GetSender()->GetRenderWindow() );\n mitk::RenderingManager::GetInstance()->RequestUpdate( positionEvent->GetSender()->GetRenderWindow() );\n\n return true;\n}\n\nbool mitk::CorrectorTool2D::OnMouseReleased(Action* action, const StateEvent* stateEvent)\n{\n \/\/ 1. Hide the feedback contour, find out which slice the user clicked, find out which slice of the toolmanager's working image corresponds to that\n FeedbackContourTool::SetFeedbackContourVisible(false);\n\n const PositionEvent* positionEvent = dynamic_cast(stateEvent->GetEvent());\n if (!positionEvent) return false;\n\n assert( positionEvent->GetSender()->GetRenderWindow() );\n mitk::RenderingManager::GetInstance()->RequestUpdate( positionEvent->GetSender()->GetRenderWindow() );\n\n if ( FeedbackContourTool::CanHandleEvent(stateEvent) < 1.0 ) return false;\n\n DataNode* workingNode( m_ToolManager->GetWorkingData(0) );\n if (!workingNode) return false;\n\n Image* image = dynamic_cast(workingNode->GetData());\n const PlaneGeometry* planeGeometry( dynamic_cast (positionEvent->GetSender()->GetCurrentWorldGeometry2D() ) );\n if ( !image || !planeGeometry ) return false;\n\n \/\/ 2. Slice is known, now we try to get it as a 2D image and project the contour into index coordinates of this slice\n m_WorkingSlice = FeedbackContourTool::GetAffectedImageSliceAs2DImage( positionEvent, image );\n\n if ( m_WorkingSlice.IsNull() )\n {\n MITK_ERROR << \"Unable to extract slice.\" << std::endl;\n return false;\n }\n\n mitk::ContourModel::Pointer singleTimestepContour = mitk::ContourModel::New();\n\n mitk::ContourModel::VertexIterator it = FeedbackContourTool::GetFeedbackContour()->Begin();\n mitk::ContourModel::VertexIterator end = FeedbackContourTool::GetFeedbackContour()->End();\n\n while(it!=end)\n {\n singleTimestepContour->AddVertex((*it)->Coordinates);\n }\n\n CorrectorAlgorithm::Pointer algorithm = CorrectorAlgorithm::New();\n algorithm->SetInput( m_WorkingSlice );\n algorithm->SetContour( singleTimestepContour );\n try\n {\n algorithm->UpdateLargestPossibleRegion();\n }\n catch ( std::exception& e )\n {\n MITK_ERROR << \"Caught exception '\" << e.what() << \"'\" << std::endl;\n }\n\n mitk::Image::Pointer resultSlice = mitk::Image::New();\n resultSlice->Initialize(algorithm->GetOutput());\n resultSlice->SetVolume(algorithm->GetOutput()->GetData());\n\n this->WriteBackSegmentationResult(positionEvent, resultSlice);\n\n return true;\n}\n\n<|endoftext|>"} {"text":"Added prologue and epilogue to the assembly visitor in comments.<|endoftext|>"} {"text":"\/\/ $Id: mesh_refinement_flagging.C,v 1.16 2005-05-03 23:22:24 roystgnr Exp $\n\n\/\/ The libMesh Finite Element Library.\n\/\/ Copyright (C) 2002-2005 Benjamin S. Kirk, John W. Peterson\n \n\/\/ This library is free software; you can redistribute it and\/or\n\/\/ modify it under the terms of the GNU Lesser General Public\n\/\/ License as published by the Free Software Foundation; either\n\/\/ version 2.1 of the License, or (at your option) any later version.\n \n\/\/ This library is distributed in the hope that it will be useful,\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n\/\/ Lesser General Public License for more details.\n \n\/\/ You should have received a copy of the GNU Lesser General Public\n\/\/ License along with this library; if not, write to the Free Software\n\/\/ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n\n\n\n\/\/ Local includes\n#include \"libmesh_config.h\"\n\n\/\/ only compile these functions if the user requests AMR support\n#ifdef ENABLE_AMR\n\n\/\/ C++ includes\n#include \/\/ for std::sort\n\n\/\/ Local includes\n#include \"error_vector.h\"\n#include \"mesh_refinement.h\"\n#include \"mesh_base.h\"\n#include \"elem.h\"\n\n\n\n\/\/-----------------------------------------------------------------\n\/\/ Mesh refinement methods\nvoid MeshRefinement::flag_elements_by_error_fraction (const ErrorVector& error_per_cell_in,\n\t\t\t\t\t\t const Real refine_fraction,\n\t\t\t\t\t\t const Real coarsen_fraction,\n\t\t\t\t\t\t const unsigned int max_level)\n{\n \/\/ Copy the input error_per_cell so that we can modify it\n ErrorVector error_per_cell (error_per_cell_in);\n \n \/\/ Check for valid fractions..\n \/\/ The fraction values must be in [0,1]\n assert (refine_fraction >= 0.); assert (refine_fraction <= 1.);\n assert (coarsen_fraction >= 0.); assert (coarsen_fraction <= 1.);\n\n \/\/ Clean up the refinement flags. These could be left\n \/\/ over from previous refinement steps.\n this->clean_refinement_flags();\n \n\n\/\/ \/\/ Set the error_per_cell to zero for elements at the\n\/\/ \/\/ maximum allowable refinement level\n\/\/ {\n\/\/ active_elem_iterator elem_it (_mesh.elements_begin());\n\/\/ const active_elem_iterator elem_end(_mesh.elements_end());\n\n\/\/ for (; elem_it != elem_end; ++elem_it)\n\/\/ {\n\/\/ \tElem* elem = *elem_it;\n\/\/ \tconst unsigned int id = elem->id();\n\/\/ \tconst unsigned int level = elem->level();\n\n\/\/ \tassert (id < error_per_cell.size());\n \n\/\/ \tif (level >= max_level)\n\/\/ \t error_per_cell[id] = 0.;\n\/\/ }\n\/\/ }\n \n \/\/ Get the minimum, maximum, and delta error values\n \/\/ for the elements\n const Real error_max = error_per_cell.maximum();\n const Real error_min = error_per_cell.minimum();\n const Real error_delta = (error_max - error_min);\n\n\n \/\/ Compute the cutoff values for coarsening and refinement\n const Real refine_cutoff = (1.- refine_fraction)*error_max;\n const Real coarsen_cutoff = coarsen_fraction*error_delta + error_min;\n\n\/\/ \/\/ Print information about the error\n\/\/ std::cout << \" Error Information:\" << std::endl\n\/\/ \t << \" ------------------\" << std::endl\n\/\/ \t << \" min: \" << error_min << std::endl\n\/\/ \t << \" max: \" << error_max << std::endl\n\/\/ \t << \" delta: \" << error_delta << std::endl\n\/\/ \t << \" refine_cutoff: \" << refine_cutoff << std::endl\n\/\/ \t << \" coarsen_cutoff: \" << coarsen_cutoff << std::endl;\n \n \n\n \/\/ Loop over the elements and flag them for coarsening or\n \/\/ refinement based on the element error\n\/\/ active_elem_iterator elem_it (_mesh.elements_begin());\n\/\/ const active_elem_iterator elem_end(_mesh.elements_end());\n\n MeshBase::element_iterator elem_it = _mesh.active_elements_begin();\n const MeshBase::element_iterator elem_end = _mesh.active_elements_end(); \n\n for (; elem_it != elem_end; ++elem_it)\n {\n Elem* elem = *elem_it;\n const unsigned int id = elem->id();\n\n assert (id < error_per_cell.size());\n \n const float elem_error = error_per_cell[id];\n\n \/\/ Flag the element for coarsening if its error\n \/\/ is <= coarsen_fraction*delta + error_min\n if (elem_error <= coarsen_cutoff)\n\t{\n\t elem->set_refinement_flag(Elem::COARSEN);\n\t}\n \n \/\/ Flag the element for refinement if its error\n \/\/ is >= refinement_cutoff.\n if (elem_error >= refine_cutoff)\n\tif (elem->level() < max_level)\n\t elem->set_refinement_flag(Elem::REFINE);\n }\n}\n\n\n\nvoid MeshRefinement::flag_elements_by_elem_fraction (const ErrorVector& error_per_cell_in,\n\t\t\t\t\t\t const Real refine_fraction,\n\t\t\t\t\t\t const Real coarsen_fraction,\n\t\t\t\t\t\t const unsigned int max_level)\n{\n \/\/ Copy the input error_per_cell so that we can modify it\n ErrorVector error_per_cell (error_per_cell_in);\n \n \/\/ Check for valid fractions..\n \/\/ The fraction values must be in [0,1]\n assert (refine_fraction >= 0.); assert (refine_fraction <= 1.);\n assert (coarsen_fraction >= 0.); assert (coarsen_fraction <= 1.);\n\n \/\/ The number of active elements in the mesh\n const unsigned int n_active_elem = _mesh.n_elem();\n\n \/\/ The number of elements to flag for coarsening\n const unsigned int n_elem_coarsen = static_cast(coarsen_fraction * n_active_elem);\n\n \/\/ The number of elements to flag for refinement\n const unsigned int n_elem_refine = static_cast(refine_fraction * n_active_elem);\n\n\n \n \/\/ Clean up the refinement flags. These could be left\n \/\/ over from previous refinement steps.\n this->clean_refinement_flags();\n\n\n\n\/\/ \/\/ Set the error_per_cell to zero for elements at the\n\/\/ \/\/ maximum allowable refinement level\n\/\/ {\n\/\/ active_elem_iterator elem_it (_mesh.elements_begin());\n\/\/ const active_elem_iterator elem_end(_mesh.elements_end());\n\n\/\/ for (; elem_it != elem_end; ++elem_it)\n\/\/ {\n\/\/ \tElem* elem = *elem_it;\n\/\/ \tconst unsigned int id = elem->id();\n\/\/ \tconst unsigned int level = elem->level();\n\n\/\/ \tassert (id < error_per_cell.size());\n \n\/\/ \tif (level >= max_level)\n\/\/ \t error_per_cell[id] = 0.;\n\/\/ }\n\/\/ }\n \n \/\/ This vector stores the error and element number for all the\n \/\/ active elements. It will be sorted and the top & bottom\n \/\/ elements will then be flagged for coarsening & refinement\n std::vector sorted_error;\n\n sorted_error.reserve (n_active_elem);\n\n \/\/ Loop over the active elements and create the entry\n \/\/ in the sorted_error vector\n\/\/ const_active_elem_iterator elem_it (_mesh.const_elements_begin());\n\/\/ const const_active_elem_iterator elem_end(_mesh.const_elements_end());\n\n MeshBase::element_iterator elem_it = _mesh.active_elements_begin();\n const MeshBase::element_iterator elem_end = _mesh.active_elements_end(); \n\n for (; elem_it != elem_end; ++elem_it)\n {\n const Elem* elem = *elem_it;\n const unsigned int elem_number = elem->id();\n const float elem_error = error_per_cell[elem_number];\n\n sorted_error.push_back (elem_error);\n }\n\n \/\/ Now sort the sorted_error vector\n std::sort (sorted_error.begin(), sorted_error.end());\n \n\n float\n top_error= 0., bottom_error = 0.,\n min_error= 0., max_error = 0.;\n\n \/\/ Get the maximum error value corresponding to the\n \/\/ bottom n_elem_coarsen elements\n {\n std::vector::iterator\n it = sorted_error.begin();\n\n min_error = *it;\n \n std::advance (it, n_elem_coarsen);\n\n bottom_error = *it;\n }\n\n \n \/\/ Get the minimum error value corresponding to the\n \/\/ top n_elem_refine elements\n {\n std::vector::reverse_iterator\n it = sorted_error.rbegin();\n\n max_error = *it;\n \n std::advance (it, n_elem_refine);\n\n top_error = *it;\n }\n\n assert (max_error >= min_error);\n const Real delta = max_error - min_error; \n const Real top_frac = (max_error - top_error)\/max_error;\n const Real bottom_frac = (bottom_error - min_error)\/delta;\n \n \n\n \/\/ Call the other refinement scheme\n this->flag_elements_by_error_fraction (error_per_cell, top_frac,\n\t\t\t\t\t bottom_frac, max_level);\n}\n\n\n\nvoid MeshRefinement::flag_elements_by_mean_stddev (const ErrorVector& error_per_cell_in,\n\t\t\t\t\t\t const Real refine_fraction,\n\t\t\t\t\t\t const Real coarsen_fraction,\n\t\t\t\t\t\t const unsigned int max_level)\n{\n \/\/ Copy the input error_per_cell so that we can modify it\n ErrorVector error_per_cell (error_per_cell_in);\n \n\/\/ \/\/ Set the error_per_cell to zero for elements at the\n\/\/ \/\/ maximum allowable refinement level\n\/\/ {\n\/\/ active_elem_iterator elem_it (_mesh.elements_begin());\n\/\/ const active_elem_iterator elem_end(_mesh.elements_end());\n\n\/\/ for (; elem_it != elem_end; ++elem_it)\n\/\/ {\n\/\/ \tElem* elem = *elem_it;\n\/\/ \tconst unsigned int id = elem->id();\n\/\/ \tconst unsigned int level = elem->level();\n\n\/\/ \tassert (id < error_per_cell.size());\n \n\/\/ \tif (level >= max_level)\n\/\/ \t error_per_cell[id] = 0.;\n\/\/ }\n\/\/ }\n \n \/\/ Get the mean value from the error vector\n const Real mean = error_per_cell.mean();\n \n \/\/ Get the standard deviation. This equals the\n \/\/ square-root of the variance\n const Real stddev = std::sqrt (error_per_cell.variance());\n \n \/\/ Check for valid fractions\n assert (refine_fraction >= 0.);\n assert (coarsen_fraction >= 0.);\n\n \/\/ The refine and coarsen cutoff\n const Real refine_cutoff = mean + refine_fraction * stddev;\n const Real coarsen_cutoff = std::max(mean - coarsen_fraction * stddev, 0.);\n \n \/\/ Loop over the elements and flag them for coarsening or\n \/\/ refinement based on the element error\n MeshBase::element_iterator elem_it = _mesh.active_elements_begin();\n const MeshBase::element_iterator elem_end = _mesh.active_elements_end(); \n\n for (; elem_it != elem_end; ++elem_it)\n {\n Elem* elem = *elem_it;\n const unsigned int id = elem->id();\n\n assert (id < error_per_cell.size());\n \n const float elem_error = error_per_cell[id];\n\n \/\/ Possibly flag the element for coarsening ...\n if (elem_error <= coarsen_cutoff)\n\telem->set_refinement_flag(Elem::COARSEN);\n \n \/\/ ... or refinement\n if ((elem_error >= refine_cutoff) && (elem->level() < max_level))\n\telem->set_refinement_flag(Elem::REFINE);\n }\n}\n\n\n\nvoid MeshRefinement::clean_refinement_flags ()\n{\n \/\/ Possibly clean up the refinement flags from\n \/\/ a previous step\n\/\/ elem_iterator elem_it (_mesh.elements_begin());\n\/\/ const elem_iterator elem_end(_mesh.elements_end());\n\n MeshBase::element_iterator elem_it = _mesh.elements_begin();\n const MeshBase::element_iterator elem_end = _mesh.elements_end(); \n\n for ( ; elem_it != elem_end; ++elem_it)\n {\n if ((*elem_it)->active())\n (*elem_it)->set_refinement_flag(Elem::DO_NOTHING);\n else\n (*elem_it)->set_refinement_flag(Elem::INACTIVE);\n }\n}\n\n#endif\nBugfix for \"all elements have identical error\" case - yes, this actually happened to me.\/\/ $Id: mesh_refinement_flagging.C,v 1.17 2005-12-13 21:15:46 roystgnr Exp $\n\n\/\/ The libMesh Finite Element Library.\n\/\/ Copyright (C) 2002-2005 Benjamin S. Kirk, John W. Peterson\n \n\/\/ This library is free software; you can redistribute it and\/or\n\/\/ modify it under the terms of the GNU Lesser General Public\n\/\/ License as published by the Free Software Foundation; either\n\/\/ version 2.1 of the License, or (at your option) any later version.\n \n\/\/ This library is distributed in the hope that it will be useful,\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n\/\/ Lesser General Public License for more details.\n \n\/\/ You should have received a copy of the GNU Lesser General Public\n\/\/ License along with this library; if not, write to the Free Software\n\/\/ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n\n\n\n\/\/ Local includes\n#include \"libmesh_config.h\"\n\n\/\/ only compile these functions if the user requests AMR support\n#ifdef ENABLE_AMR\n\n\/\/ C++ includes\n#include \/\/ for std::sort\n\n\/\/ Local includes\n#include \"error_vector.h\"\n#include \"mesh_refinement.h\"\n#include \"mesh_base.h\"\n#include \"elem.h\"\n\n\n\n\/\/-----------------------------------------------------------------\n\/\/ Mesh refinement methods\nvoid MeshRefinement::flag_elements_by_error_fraction (const ErrorVector& error_per_cell_in,\n\t\t\t\t\t\t const Real refine_fraction,\n\t\t\t\t\t\t const Real coarsen_fraction,\n\t\t\t\t\t\t const unsigned int max_level)\n{\n \/\/ Copy the input error_per_cell so that we can modify it\n ErrorVector error_per_cell (error_per_cell_in);\n \n \/\/ Check for valid fractions..\n \/\/ The fraction values must be in [0,1]\n assert (refine_fraction >= 0.); assert (refine_fraction <= 1.);\n assert (coarsen_fraction >= 0.); assert (coarsen_fraction <= 1.);\n\n \/\/ Clean up the refinement flags. These could be left\n \/\/ over from previous refinement steps.\n this->clean_refinement_flags();\n \n\n\/\/ \/\/ Set the error_per_cell to zero for elements at the\n\/\/ \/\/ maximum allowable refinement level\n\/\/ {\n\/\/ active_elem_iterator elem_it (_mesh.elements_begin());\n\/\/ const active_elem_iterator elem_end(_mesh.elements_end());\n\n\/\/ for (; elem_it != elem_end; ++elem_it)\n\/\/ {\n\/\/ \tElem* elem = *elem_it;\n\/\/ \tconst unsigned int id = elem->id();\n\/\/ \tconst unsigned int level = elem->level();\n\n\/\/ \tassert (id < error_per_cell.size());\n \n\/\/ \tif (level >= max_level)\n\/\/ \t error_per_cell[id] = 0.;\n\/\/ }\n\/\/ }\n \n \/\/ Get the minimum, maximum, and delta error values\n \/\/ for the elements\n const Real error_max = error_per_cell.maximum();\n const Real error_min = error_per_cell.minimum();\n const Real error_delta = (error_max - error_min);\n\n\n \/\/ Compute the cutoff values for coarsening and refinement\n const Real refine_cutoff = (1.- refine_fraction)*error_max;\n const Real coarsen_cutoff = coarsen_fraction*error_delta + error_min;\n\n\/\/ \/\/ Print information about the error\n\/\/ std::cout << \" Error Information:\" << std::endl\n\/\/ \t << \" ------------------\" << std::endl\n\/\/ \t << \" min: \" << error_min << std::endl\n\/\/ \t << \" max: \" << error_max << std::endl\n\/\/ \t << \" delta: \" << error_delta << std::endl\n\/\/ \t << \" refine_cutoff: \" << refine_cutoff << std::endl\n\/\/ \t << \" coarsen_cutoff: \" << coarsen_cutoff << std::endl;\n \n \n\n \/\/ Loop over the elements and flag them for coarsening or\n \/\/ refinement based on the element error\n\/\/ active_elem_iterator elem_it (_mesh.elements_begin());\n\/\/ const active_elem_iterator elem_end(_mesh.elements_end());\n\n MeshBase::element_iterator elem_it = _mesh.active_elements_begin();\n const MeshBase::element_iterator elem_end = _mesh.active_elements_end(); \n\n for (; elem_it != elem_end; ++elem_it)\n {\n Elem* elem = *elem_it;\n const unsigned int id = elem->id();\n\n assert (id < error_per_cell.size());\n \n const float elem_error = error_per_cell[id];\n\n \/\/ Flag the element for coarsening if its error\n \/\/ is <= coarsen_fraction*delta + error_min\n if (elem_error <= coarsen_cutoff)\n\t{\n\t elem->set_refinement_flag(Elem::COARSEN);\n\t}\n \n \/\/ Flag the element for refinement if its error\n \/\/ is >= refinement_cutoff.\n if (elem_error >= refine_cutoff)\n\tif (elem->level() < max_level)\n\t elem->set_refinement_flag(Elem::REFINE);\n }\n}\n\n\n\nvoid MeshRefinement::flag_elements_by_elem_fraction (const ErrorVector& error_per_cell_in,\n\t\t\t\t\t\t const Real refine_fraction,\n\t\t\t\t\t\t const Real coarsen_fraction,\n\t\t\t\t\t\t const unsigned int max_level)\n{\n \/\/ Copy the input error_per_cell so that we can modify it\n ErrorVector error_per_cell (error_per_cell_in);\n \n \/\/ Check for valid fractions..\n \/\/ The fraction values must be in [0,1]\n assert (refine_fraction >= 0.); assert (refine_fraction <= 1.);\n assert (coarsen_fraction >= 0.); assert (coarsen_fraction <= 1.);\n\n \/\/ The number of active elements in the mesh\n const unsigned int n_active_elem = _mesh.n_elem();\n\n \/\/ The number of elements to flag for coarsening\n const unsigned int n_elem_coarsen = static_cast(coarsen_fraction * n_active_elem);\n\n \/\/ The number of elements to flag for refinement\n const unsigned int n_elem_refine = static_cast(refine_fraction * n_active_elem);\n\n\n \n \/\/ Clean up the refinement flags. These could be left\n \/\/ over from previous refinement steps.\n this->clean_refinement_flags();\n\n\n\n\/\/ \/\/ Set the error_per_cell to zero for elements at the\n\/\/ \/\/ maximum allowable refinement level\n\/\/ {\n\/\/ active_elem_iterator elem_it (_mesh.elements_begin());\n\/\/ const active_elem_iterator elem_end(_mesh.elements_end());\n\n\/\/ for (; elem_it != elem_end; ++elem_it)\n\/\/ {\n\/\/ \tElem* elem = *elem_it;\n\/\/ \tconst unsigned int id = elem->id();\n\/\/ \tconst unsigned int level = elem->level();\n\n\/\/ \tassert (id < error_per_cell.size());\n \n\/\/ \tif (level >= max_level)\n\/\/ \t error_per_cell[id] = 0.;\n\/\/ }\n\/\/ }\n \n \/\/ This vector stores the error and element number for all the\n \/\/ active elements. It will be sorted and the top & bottom\n \/\/ elements will then be flagged for coarsening & refinement\n std::vector sorted_error;\n\n sorted_error.reserve (n_active_elem);\n\n \/\/ Loop over the active elements and create the entry\n \/\/ in the sorted_error vector\n\/\/ const_active_elem_iterator elem_it (_mesh.const_elements_begin());\n\/\/ const const_active_elem_iterator elem_end(_mesh.const_elements_end());\n\n MeshBase::element_iterator elem_it = _mesh.active_elements_begin();\n const MeshBase::element_iterator elem_end = _mesh.active_elements_end(); \n\n for (; elem_it != elem_end; ++elem_it)\n {\n const Elem* elem = *elem_it;\n const unsigned int elem_number = elem->id();\n const float elem_error = error_per_cell[elem_number];\n\n sorted_error.push_back (elem_error);\n }\n\n \/\/ Now sort the sorted_error vector\n std::sort (sorted_error.begin(), sorted_error.end());\n \n\n float\n top_error= 0., bottom_error = 0.,\n min_error= 0., max_error = 0.;\n\n \/\/ Get the maximum error value corresponding to the\n \/\/ bottom n_elem_coarsen elements\n {\n std::vector::iterator\n it = sorted_error.begin();\n\n min_error = *it;\n \n std::advance (it, n_elem_coarsen);\n\n bottom_error = *it;\n }\n\n \n \/\/ Get the minimum error value corresponding to the\n \/\/ top n_elem_refine elements\n {\n std::vector::reverse_iterator\n it = sorted_error.rbegin();\n\n max_error = *it;\n \n std::advance (it, n_elem_refine);\n\n top_error = *it;\n }\n\n assert (max_error >= min_error);\n const Real delta = max_error - min_error; \n const Real top_frac = (max_error - top_error)\/max_error;\n const Real bottom_frac = (bottom_error - min_error)\/delta;\n \n \n \/\/ Call the other refinement scheme\n \/\/ If all elements have the same error value, refine them all\n if (!delta)\n this->flag_elements_by_error_fraction (error_per_cell, 1.,\n\t\t\t\t\t 0., max_level);\n \/\/ Otherwise, refine the calculated fractions\n else\n this->flag_elements_by_error_fraction (error_per_cell, top_frac,\n\t\t\t\t\t bottom_frac, max_level);\n}\n\n\n\nvoid MeshRefinement::flag_elements_by_mean_stddev (const ErrorVector& error_per_cell_in,\n\t\t\t\t\t\t const Real refine_fraction,\n\t\t\t\t\t\t const Real coarsen_fraction,\n\t\t\t\t\t\t const unsigned int max_level)\n{\n \/\/ Copy the input error_per_cell so that we can modify it\n ErrorVector error_per_cell (error_per_cell_in);\n \n\/\/ \/\/ Set the error_per_cell to zero for elements at the\n\/\/ \/\/ maximum allowable refinement level\n\/\/ {\n\/\/ active_elem_iterator elem_it (_mesh.elements_begin());\n\/\/ const active_elem_iterator elem_end(_mesh.elements_end());\n\n\/\/ for (; elem_it != elem_end; ++elem_it)\n\/\/ {\n\/\/ \tElem* elem = *elem_it;\n\/\/ \tconst unsigned int id = elem->id();\n\/\/ \tconst unsigned int level = elem->level();\n\n\/\/ \tassert (id < error_per_cell.size());\n \n\/\/ \tif (level >= max_level)\n\/\/ \t error_per_cell[id] = 0.;\n\/\/ }\n\/\/ }\n \n \/\/ Get the mean value from the error vector\n const Real mean = error_per_cell.mean();\n \n \/\/ Get the standard deviation. This equals the\n \/\/ square-root of the variance\n const Real stddev = std::sqrt (error_per_cell.variance());\n \n \/\/ Check for valid fractions\n assert (refine_fraction >= 0.);\n assert (coarsen_fraction >= 0.);\n\n \/\/ The refine and coarsen cutoff\n const Real refine_cutoff = mean + refine_fraction * stddev;\n const Real coarsen_cutoff = std::max(mean - coarsen_fraction * stddev, 0.);\n \n \/\/ Loop over the elements and flag them for coarsening or\n \/\/ refinement based on the element error\n MeshBase::element_iterator elem_it = _mesh.active_elements_begin();\n const MeshBase::element_iterator elem_end = _mesh.active_elements_end(); \n\n for (; elem_it != elem_end; ++elem_it)\n {\n Elem* elem = *elem_it;\n const unsigned int id = elem->id();\n\n assert (id < error_per_cell.size());\n \n const float elem_error = error_per_cell[id];\n\n \/\/ Possibly flag the element for coarsening ...\n if (elem_error <= coarsen_cutoff)\n\telem->set_refinement_flag(Elem::COARSEN);\n \n \/\/ ... or refinement\n if ((elem_error >= refine_cutoff) && (elem->level() < max_level))\n\telem->set_refinement_flag(Elem::REFINE);\n }\n}\n\n\n\nvoid MeshRefinement::clean_refinement_flags ()\n{\n \/\/ Possibly clean up the refinement flags from\n \/\/ a previous step\n\/\/ elem_iterator elem_it (_mesh.elements_begin());\n\/\/ const elem_iterator elem_end(_mesh.elements_end());\n\n MeshBase::element_iterator elem_it = _mesh.elements_begin();\n const MeshBase::element_iterator elem_end = _mesh.elements_end(); \n\n for ( ; elem_it != elem_end; ++elem_it)\n {\n if ((*elem_it)->active())\n (*elem_it)->set_refinement_flag(Elem::DO_NOTHING);\n else\n (*elem_it)->set_refinement_flag(Elem::INACTIVE);\n }\n}\n\n#endif\n<|endoftext|>"} {"text":"\/\/ Author: Enrico Guiraud, Danilo Piparo CERN 09\/2017\n\n\/*************************************************************************\n * Copyright (C) 1995-2018, Rene Brun and Fons Rademakers. *\n * All rights reserved. *\n * *\n * For the licensing terms see $ROOTSYS\/LICENSE. *\n * For the list of contributors see $ROOTSYS\/README\/CREDITS. *\n *************************************************************************\/\n\n#ifndef ROOT_RDATASOURCE\n#define ROOT_RDATASOURCE\n\n#include \"ROOT\/RStringView.hxx\"\n#include \"RtypesCore.h\" \/\/ ULong64_t\n#include \"TString.h\"\n\n#include \/\/ std::transform\n#include \n#include \n#include \n\nnamespace ROOT {\nnamespace RDF {\nclass RDataSource;\n}\n}\n\n\/\/\/ Print a RDataSource at the prompt\nnamespace cling {\nstd::string printValue(ROOT::RDF::RDataSource *ds);\n} \/\/ namespace cling\n\nnamespace ROOT {\n\nnamespace Internal {\nnamespace TDS {\n\n\/\/\/ Mother class of TTypedPointerHolder. The instances\n\/\/\/ of this class can be put in a container. Upon destruction,\n\/\/\/ the correct deletion of the pointer is performed in the\n\/\/\/ derived class.\nclass TPointerHolder {\nprotected:\n void *fPointer{nullptr};\n\npublic:\n TPointerHolder(void *ptr) : fPointer(ptr) {}\n void *GetPointer() { return fPointer; }\n void *GetPointerAddr() { return &fPointer; }\n virtual TPointerHolder *GetDeepCopy() = 0;\n virtual ~TPointerHolder(){};\n};\n\n\/\/\/ Class to wrap a pointer and delete the memory associated to it\n\/\/\/ correctly\ntemplate \nclass TTypedPointerHolder final : public TPointerHolder {\npublic:\n TTypedPointerHolder(T *ptr) : TPointerHolder((void *)ptr) {}\n\n virtual TPointerHolder *GetDeepCopy()\n {\n const auto typedPtr = static_cast(fPointer);\n return new TTypedPointerHolder(new T(*typedPtr));\n }\n\n ~TTypedPointerHolder() { delete static_cast(fPointer); }\n};\n\n} \/\/ ns TDS\n} \/\/ ns Internal\n\nnamespace RDF {\n\n\/\/ clang-format off\n\/**\n\\class ROOT::RDF::RDataSource\n\\ingroup dataframe\n\\brief RDataSource defines an API that RDataFrame can use to read arbitrary data formats.\n\nA concrete RDataSource implementation (i.e. a class that inherits from RDataSource and implements all of its pure\nmethods) provides an adaptor that RDataFrame can leverage to read any kind of tabular data formats.\nRDataFrame calls into RDataSource to retrieve information about the data, retrieve (thread-local) readers or \"cursors\"\nfor selected columns and to advance the readers to the desired data entry.\n\nThe sequence of calls that RDataFrame (or any other client of a RDataSource) performs is the following:\n\n - SetNSlots() : inform RDataSource of the desired level of parallelism\n - GetColumnReaders() : retrieve from RDataSource per-thread readers for the desired columns\n - Initialise() : inform RDataSource that an event-loop is about to start\n - GetEntryRanges() : retrieve from RDataSource a set of ranges of entries that can be processed concurrently\n - InitSlot() : inform RDataSource that a certain thread is about to start working on a certain range of entries\n - SetEntry() : inform RDataSource that a certain thread is about to start working on a certain entry\n - FinaliseSlot() : inform RDataSource that a certain thread finished working on a certain range of entries\n - Finalise() : inform RDataSource that an event-loop finished\n\nRDataSource implementations must support running multiple event-loops consecutively (although sequentially) on the same dataset.\n - \\b SetNSlots() is called once per RDataSource object, typically when it is associated to a RDataFrame.\n - \\b GetColumnReaders() can be called several times, potentially with the same arguments, also in-between event-loops, but not during an event-loop.\n - \\b Initialise() and \\b Finalise() are called once per event-loop, right before starting and right after finishing.\n - \\b InitSlot(), \\b SetEntry(), and \\b FinaliseSlot() can be called concurrently from multiple threads, multiple times per event-loop.\n*\/\nclass RDataSource {\n \/\/ clang-format on\nprotected:\n using Record_t = std::vector;\n friend std::string cling::printValue(::ROOT::RDF::RDataSource *);\n\n virtual std::string AsString() { return \"generic data source\"; };\n\npublic:\n virtual ~RDataSource() = default;\n\n \/\/ clang-format off\n \/\/\/ \\brief Inform RDataSource of the number of processing slots (i.e. worker threads) used by the associated RDataFrame.\n \/\/\/ Slots numbers are used to simplify parallel execution: RDataFrame guarantees that different threads will always\n \/\/\/ pass different slot values when calling methods concurrently.\n \/\/ clang-format on\n virtual void SetNSlots(unsigned int nSlots) = 0;\n\n \/\/ clang-format off\n \/\/\/ \\brief Returns a reference to the collection of the dataset's column names\n \/\/ clang-format on\n virtual const std::vector &GetColumnNames() const = 0;\n\n \/\/\/ \\brief Checks if the dataset has a certain column\n \/\/\/ \\param[in] columnName The name of the column\n virtual bool HasColumn(std::string_view) const = 0;\n\n \/\/ clang-format off\n \/\/\/ \\brief Type of a column as a string, e.g. `GetTypeName(\"x\") == \"double\"`. Required for jitting e.g. `df.Filter(\"x>0\")`.\n \/\/\/ \\param[in] columnName The name of the column\n \/\/ clang-format on\n virtual std::string GetTypeName(std::string_view) const = 0;\n\n \/\/ clang-format off\n \/\/\/ Called at most once per column by RDF. Return vector of pointers to pointers to column values - one per slot.\n \/\/\/ \\tparam T The type of the data stored in the column\n \/\/\/ \\param[in] columnName The name of the column\n \/\/\/\n \/\/\/ These pointers are veritable cursors: it's a responsibility of the RDataSource implementation that they point to\n \/\/\/ the \"right\" memory region.\n \/\/ clang-format on\n template \n std::vector GetColumnReaders(std::string_view columnName)\n {\n auto typeErasedVec = GetColumnReadersImpl(columnName, typeid(T));\n std::vector typedVec(typeErasedVec.size());\n std::transform(typeErasedVec.begin(), typeErasedVec.end(), typedVec.begin(),\n [](void *p) { return static_cast(p); });\n return typedVec;\n }\n\n \/\/ clang-format off\n \/\/\/ \\brief Return ranges of entries to distribute to tasks.\n \/\/\/ They are required to be contiguous intervals with no entries skipped. Supposing a dataset with nEntries, the\n \/\/\/ intervals must start at 0 and end at nEntries, e.g. [0-5],[5-10] for 10 entries.\n \/\/ clang-format on\n virtual std::vector> GetEntryRanges() = 0;\n\n \/\/ clang-format off\n \/\/\/ \\brief Advance the \"cursors\" returned by GetColumnReaders to the selected entry for a particular slot.\n \/\/\/ \\param[in] slot The data processing slot that needs to be considered\n \/\/\/ \\param[in] entry The entry which needs to be pointed to by the reader pointers\n \/\/\/ Slots are adopted to accommodate parallel data processing. \n \/\/\/ Different workers will loop over different ranges and\n \/\/\/ will be labelled by different \"slot\" values.\n \/\/\/ Returns *true* if the entry has to be processed, *false* otherwise.\n \/\/ clang-format on\n virtual bool SetEntry(unsigned int slot, ULong64_t entry) = 0;\n\n \/\/ clang-format off\n \/\/\/ \\brief Convenience method called before starting an event-loop.\n \/\/\/ This method might be called multiple times over the lifetime of a RDataSource, since\n \/\/\/ users can run multiple event-loops with the same RDataFrame.\n \/\/\/ Ideally, `Initialise` should set the state of the RDataSource so that multiple identical event-loops\n \/\/\/ will produce identical results.\n \/\/ clang-format on\n virtual void Initialise() {}\n\n \/\/ clang-format off\n \/\/\/ \\brief Convenience method called at the start of the data processing associated to a slot.\n \/\/\/ \\param[in] slot The data processing slot wihch needs to be initialised\n \/\/\/ \\param[in] firstEntry The first entry of the range that the task will process.\n \/\/\/ This method might be called multiple times per thread per event-loop.\n \/\/ clang-format on\n virtual void InitSlot(unsigned int \/*slot*\/, ULong64_t \/*firstEntry*\/) {}\n\n \/\/ clang-format off\n \/\/\/ \\brief Convenience method called at the end of the data processing associated to a slot.\n \/\/\/ \\param[in] slot The data processing slot wihch needs to be finalised\n \/\/\/ This method might be called multiple times per thread per event-loop.\n \/\/ clang-format on\n virtual void FinaliseSlot(unsigned int \/*slot*\/) {}\n\n \/\/ clang-format off\n \/\/\/ \\brief Convenience method called after concluding an event-loop.\n \/\/\/ See Initialise for more details.\n \/\/ clang-format on\n virtual void Finalise() {}\n\n virtual std::string GetDataSourceType() = 0;\n\nprotected:\n \/\/\/ type-erased vector of pointers to pointers to column values - one per slot\n virtual Record_t GetColumnReadersImpl(std::string_view name, const std::type_info &) = 0;\n};\n\n} \/\/ ns RDF\n\n} \/\/ ns ROOT\n\n\/\/\/ Print a RDataSource at the prompt\nnamespace cling {\ninline std::string printValue(ROOT::RDF::RDataSource *ds)\n{\n return ds->AsString();\n}\n} \/\/ namespace cling\n\n#endif \/\/ ROOT_TDATASOURCE\n[DF] Improve DS GetEntryRanges method doc\/\/ Author: Enrico Guiraud, Danilo Piparo CERN 09\/2017\n\n\/*************************************************************************\n * Copyright (C) 1995-2018, Rene Brun and Fons Rademakers. *\n * All rights reserved. *\n * *\n * For the licensing terms see $ROOTSYS\/LICENSE. *\n * For the list of contributors see $ROOTSYS\/README\/CREDITS. *\n *************************************************************************\/\n\n#ifndef ROOT_RDATASOURCE\n#define ROOT_RDATASOURCE\n\n#include \"ROOT\/RStringView.hxx\"\n#include \"RtypesCore.h\" \/\/ ULong64_t\n#include \"TString.h\"\n\n#include \/\/ std::transform\n#include \n#include \n#include \n\nnamespace ROOT {\nnamespace RDF {\nclass RDataSource;\n}\n}\n\n\/\/\/ Print a RDataSource at the prompt\nnamespace cling {\nstd::string printValue(ROOT::RDF::RDataSource *ds);\n} \/\/ namespace cling\n\nnamespace ROOT {\n\nnamespace Internal {\nnamespace TDS {\n\n\/\/\/ Mother class of TTypedPointerHolder. The instances\n\/\/\/ of this class can be put in a container. Upon destruction,\n\/\/\/ the correct deletion of the pointer is performed in the\n\/\/\/ derived class.\nclass TPointerHolder {\nprotected:\n void *fPointer{nullptr};\n\npublic:\n TPointerHolder(void *ptr) : fPointer(ptr) {}\n void *GetPointer() { return fPointer; }\n void *GetPointerAddr() { return &fPointer; }\n virtual TPointerHolder *GetDeepCopy() = 0;\n virtual ~TPointerHolder(){};\n};\n\n\/\/\/ Class to wrap a pointer and delete the memory associated to it\n\/\/\/ correctly\ntemplate \nclass TTypedPointerHolder final : public TPointerHolder {\npublic:\n TTypedPointerHolder(T *ptr) : TPointerHolder((void *)ptr) {}\n\n virtual TPointerHolder *GetDeepCopy()\n {\n const auto typedPtr = static_cast(fPointer);\n return new TTypedPointerHolder(new T(*typedPtr));\n }\n\n ~TTypedPointerHolder() { delete static_cast(fPointer); }\n};\n\n} \/\/ ns TDS\n} \/\/ ns Internal\n\nnamespace RDF {\n\n\/\/ clang-format off\n\/**\n\\class ROOT::RDF::RDataSource\n\\ingroup dataframe\n\\brief RDataSource defines an API that RDataFrame can use to read arbitrary data formats.\n\nA concrete RDataSource implementation (i.e. a class that inherits from RDataSource and implements all of its pure\nmethods) provides an adaptor that RDataFrame can leverage to read any kind of tabular data formats.\nRDataFrame calls into RDataSource to retrieve information about the data, retrieve (thread-local) readers or \"cursors\"\nfor selected columns and to advance the readers to the desired data entry.\n\nThe sequence of calls that RDataFrame (or any other client of a RDataSource) performs is the following:\n\n - SetNSlots() : inform RDataSource of the desired level of parallelism\n - GetColumnReaders() : retrieve from RDataSource per-thread readers for the desired columns\n - Initialise() : inform RDataSource that an event-loop is about to start\n - GetEntryRanges() : retrieve from RDataSource a set of ranges of entries that can be processed concurrently\n - InitSlot() : inform RDataSource that a certain thread is about to start working on a certain range of entries\n - SetEntry() : inform RDataSource that a certain thread is about to start working on a certain entry\n - FinaliseSlot() : inform RDataSource that a certain thread finished working on a certain range of entries\n - Finalise() : inform RDataSource that an event-loop finished\n\nRDataSource implementations must support running multiple event-loops consecutively (although sequentially) on the same dataset.\n - \\b SetNSlots() is called once per RDataSource object, typically when it is associated to a RDataFrame.\n - \\b GetColumnReaders() can be called several times, potentially with the same arguments, also in-between event-loops, but not during an event-loop.\n - \\b Initialise() and \\b Finalise() are called once per event-loop, right before starting and right after finishing.\n - \\b InitSlot(), \\b SetEntry(), and \\b FinaliseSlot() can be called concurrently from multiple threads, multiple times per event-loop.\n*\/\nclass RDataSource {\n \/\/ clang-format on\nprotected:\n using Record_t = std::vector;\n friend std::string cling::printValue(::ROOT::RDF::RDataSource *);\n\n virtual std::string AsString() { return \"generic data source\"; };\n\npublic:\n virtual ~RDataSource() = default;\n\n \/\/ clang-format off\n \/\/\/ \\brief Inform RDataSource of the number of processing slots (i.e. worker threads) used by the associated RDataFrame.\n \/\/\/ Slots numbers are used to simplify parallel execution: RDataFrame guarantees that different threads will always\n \/\/\/ pass different slot values when calling methods concurrently.\n \/\/ clang-format on\n virtual void SetNSlots(unsigned int nSlots) = 0;\n\n \/\/ clang-format off\n \/\/\/ \\brief Returns a reference to the collection of the dataset's column names\n \/\/ clang-format on\n virtual const std::vector &GetColumnNames() const = 0;\n\n \/\/\/ \\brief Checks if the dataset has a certain column\n \/\/\/ \\param[in] columnName The name of the column\n virtual bool HasColumn(std::string_view) const = 0;\n\n \/\/ clang-format off\n \/\/\/ \\brief Type of a column as a string, e.g. `GetTypeName(\"x\") == \"double\"`. Required for jitting e.g. `df.Filter(\"x>0\")`.\n \/\/\/ \\param[in] columnName The name of the column\n \/\/ clang-format on\n virtual std::string GetTypeName(std::string_view) const = 0;\n\n \/\/ clang-format off\n \/\/\/ Called at most once per column by RDF. Return vector of pointers to pointers to column values - one per slot.\n \/\/\/ \\tparam T The type of the data stored in the column\n \/\/\/ \\param[in] columnName The name of the column\n \/\/\/\n \/\/\/ These pointers are veritable cursors: it's a responsibility of the RDataSource implementation that they point to\n \/\/\/ the \"right\" memory region.\n \/\/ clang-format on\n template \n std::vector GetColumnReaders(std::string_view columnName)\n {\n auto typeErasedVec = GetColumnReadersImpl(columnName, typeid(T));\n std::vector typedVec(typeErasedVec.size());\n std::transform(typeErasedVec.begin(), typeErasedVec.end(), typedVec.begin(),\n [](void *p) { return static_cast(p); });\n return typedVec;\n }\n\n \/\/ clang-format off\n \/\/\/ \\brief Return ranges of entries to distribute to tasks.\n \/\/\/ They are required to be contiguous intervals with no entries skipped. Supposing a dataset with nEntries, the\n \/\/\/ intervals must start at 0 and end at nEntries, e.g. [0-5],[5-10] for 10 entries.\n \/\/\/ Returning an empty collection of ranges signals to RDataFrame that the processing can stop.\n \/\/ clang-format on\n virtual std::vector> GetEntryRanges() = 0;\n\n \/\/ clang-format off\n \/\/\/ \\brief Advance the \"cursors\" returned by GetColumnReaders to the selected entry for a particular slot.\n \/\/\/ \\param[in] slot The data processing slot that needs to be considered\n \/\/\/ \\param[in] entry The entry which needs to be pointed to by the reader pointers\n \/\/\/ Slots are adopted to accommodate parallel data processing. \n \/\/\/ Different workers will loop over different ranges and\n \/\/\/ will be labelled by different \"slot\" values.\n \/\/\/ Returns *true* if the entry has to be processed, *false* otherwise.\n \/\/ clang-format on\n virtual bool SetEntry(unsigned int slot, ULong64_t entry) = 0;\n\n \/\/ clang-format off\n \/\/\/ \\brief Convenience method called before starting an event-loop.\n \/\/\/ This method might be called multiple times over the lifetime of a RDataSource, since\n \/\/\/ users can run multiple event-loops with the same RDataFrame.\n \/\/\/ Ideally, `Initialise` should set the state of the RDataSource so that multiple identical event-loops\n \/\/\/ will produce identical results.\n \/\/ clang-format on\n virtual void Initialise() {}\n\n \/\/ clang-format off\n \/\/\/ \\brief Convenience method called at the start of the data processing associated to a slot.\n \/\/\/ \\param[in] slot The data processing slot wihch needs to be initialised\n \/\/\/ \\param[in] firstEntry The first entry of the range that the task will process.\n \/\/\/ This method might be called multiple times per thread per event-loop.\n \/\/ clang-format on\n virtual void InitSlot(unsigned int \/*slot*\/, ULong64_t \/*firstEntry*\/) {}\n\n \/\/ clang-format off\n \/\/\/ \\brief Convenience method called at the end of the data processing associated to a slot.\n \/\/\/ \\param[in] slot The data processing slot wihch needs to be finalised\n \/\/\/ This method might be called multiple times per thread per event-loop.\n \/\/ clang-format on\n virtual void FinaliseSlot(unsigned int \/*slot*\/) {}\n\n \/\/ clang-format off\n \/\/\/ \\brief Convenience method called after concluding an event-loop.\n \/\/\/ See Initialise for more details.\n \/\/ clang-format on\n virtual void Finalise() {}\n\n virtual std::string GetDataSourceType() = 0;\n\nprotected:\n \/\/\/ type-erased vector of pointers to pointers to column values - one per slot\n virtual Record_t GetColumnReadersImpl(std::string_view name, const std::type_info &) = 0;\n};\n\n} \/\/ ns RDF\n\n} \/\/ ns ROOT\n\n\/\/\/ Print a RDataSource at the prompt\nnamespace cling {\ninline std::string printValue(ROOT::RDF::RDataSource *ds)\n{\n return ds->AsString();\n}\n} \/\/ namespace cling\n\n#endif \/\/ ROOT_TDATASOURCE\n<|endoftext|>"} {"text":"\/\/ Copyright 2016 Benjamin Glatzel\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n\/\/ Precompiled header file\n#include \"stdafx_vulkan.h\"\n#include \"stdafx.h\"\n\nnamespace Intrinsic\n{\nnamespace Renderer\n{\nnamespace Vulkan\n{\nnamespace RenderPass\n{\nnamespace\n{\nResources::ImageRef _lightingBufferImageRef;\nResources::ImageRef _lightingBufferTransparentsImageRef;\nResources::FramebufferRef _framebufferRef;\nResources::FramebufferRef _framebufferTransparentsRef;\nResources::RenderPassRef _renderPassRef;\nResources::PipelineRef _pipelineRef;\nResources::DrawCallRef _drawCallRef;\nResources::DrawCallRef _drawCallTransparentsRef;\n\n\/\/ <-\n\nstruct PerInstanceData\n{\n glm::mat4 viewMatrix;\n glm::mat4 invProjectionMatrix;\n glm::mat4 invViewMatrix;\n\n glm::mat4 shadowViewProjMatrix[_INTR_MAX_SHADOW_MAP_COUNT];\n} _perInstanceData;\n\n\/\/ <-\n\nvoid renderLighting(Resources::FramebufferRef p_FramebufferRef,\n Resources::DrawCallRef p_DrawCall,\n Resources::ImageRef p_LightingBufferRef,\n Components::CameraRef p_CameraRef)\n{\n using namespace Resources;\n\n \/\/ Update per instance data\n {\n _perInstanceData.invProjectionMatrix =\n Components::CameraManager::_inverseProjectionMatrix(p_CameraRef);\n _perInstanceData.viewMatrix =\n Components::CameraManager::_viewMatrix(p_CameraRef);\n _perInstanceData.invViewMatrix =\n Components::CameraManager::_inverseViewMatrix(p_CameraRef);\n\n const _INTR_ARRAY(Core::Resources::FrustumRef)& shadowFrustums =\n RenderProcess::Default::_shadowFrustums[p_CameraRef];\n\n for (uint32_t i = 0u; i < shadowFrustums.size(); ++i)\n {\n Core::Resources::FrustumRef shadowFrustumRef = shadowFrustums[i];\n\n \/\/ Transform from camera view space => light proj. space\n _perInstanceData.shadowViewProjMatrix[i] =\n Core::Resources::FrustumManager::_viewProjectionMatrix(\n shadowFrustumRef) *\n Components::CameraManager::_inverseViewMatrix(p_CameraRef);\n }\n\n DrawCallRefArray dcsToUpdate = {p_DrawCall};\n DrawCallManager::allocateAndUpdateUniformMemory(\n dcsToUpdate, nullptr, 0u, &_perInstanceData, sizeof(PerInstanceData));\n }\n\n VkCommandBuffer primaryCmdBuffer = RenderSystem::getPrimaryCommandBuffer();\n\n ImageManager::insertImageMemoryBarrier(\n p_LightingBufferRef, VK_IMAGE_LAYOUT_UNDEFINED,\n VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL);\n\n RenderSystem::beginRenderPass(_renderPassRef, p_FramebufferRef,\n VK_SUBPASS_CONTENTS_INLINE);\n {\n RenderSystem::dispatchDrawCall(p_DrawCall, primaryCmdBuffer);\n }\n RenderSystem::endRenderPass(_renderPassRef);\n\n ImageManager::insertImageMemoryBarrier(\n p_LightingBufferRef, VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL,\n VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL);\n}\n}\n\nvoid Lighting::init()\n{\n using namespace Resources;\n\n PipelineRefArray pipelinesToCreate;\n PipelineLayoutRefArray pipelineLayoutsToCreate;\n RenderPassRefArray renderpassesToCreate;\n\n \/\/ Pipeline layout\n PipelineLayoutRef pipelineLayout;\n {\n pipelineLayout = PipelineLayoutManager::createPipelineLayout(_N(Lighting));\n PipelineLayoutManager::resetToDefault(pipelineLayout);\n\n GpuProgramManager::reflectPipelineLayout(\n 8u, {Resources::GpuProgramManager::getResourceByName(\"lighting.frag\")},\n pipelineLayout);\n }\n pipelineLayoutsToCreate.push_back(pipelineLayout);\n\n \/\/ Render passes\n {\n _renderPassRef = RenderPassManager::createRenderPass(_N(Lighting));\n RenderPassManager::resetToDefault(_renderPassRef);\n\n AttachmentDescription colorAttachment = {Format::kR16G16B16A16Float, 0u};\n\n RenderPassManager::_descAttachments(_renderPassRef)\n .push_back(colorAttachment);\n }\n renderpassesToCreate.push_back(_renderPassRef);\n\n \/\/ Pipelines\n {\n _pipelineRef = PipelineManager::createPipeline(_N(Lighting));\n PipelineManager::resetToDefault(_pipelineRef);\n\n PipelineManager::_descFragmentProgram(_pipelineRef) =\n GpuProgramManager::getResourceByName(\"lighting.frag\");\n PipelineManager::_descVertexProgram(_pipelineRef) =\n GpuProgramManager::getResourceByName(\"fullscreen_triangle.vert\");\n PipelineManager::_descRenderPass(_pipelineRef) = _renderPassRef;\n PipelineManager::_descPipelineLayout(_pipelineRef) = pipelineLayout;\n PipelineManager::_descVertexLayout(_pipelineRef) = Dod::Ref();\n PipelineManager::_descDepthStencilState(_pipelineRef) =\n DepthStencilStates::kDefaultNoDepthTestAndWrite;\n }\n pipelinesToCreate.push_back(_pipelineRef);\n\n PipelineLayoutManager::createResources(pipelineLayoutsToCreate);\n RenderPassManager::createResources(renderpassesToCreate);\n PipelineManager::createResources(pipelinesToCreate);\n}\n\n\/\/ <-\n\nvoid Lighting::onReinitRendering()\n{\n using namespace Resources;\n\n ImageRefArray imgsToDestroy;\n ImageRefArray imgsToCreate;\n FramebufferRefArray framebuffersToDestroy;\n FramebufferRefArray framebuffersToCreate;\n DrawCallRefArray drawCallsToDestroy;\n DrawCallRefArray drawcallsToCreate;\n\n \/\/ Cleanup old resources\n {\n if (_drawCallRef.isValid())\n drawCallsToDestroy.push_back(_drawCallRef);\n if (_drawCallTransparentsRef.isValid())\n drawCallsToDestroy.push_back(_drawCallTransparentsRef);\n\n if (_framebufferRef.isValid())\n framebuffersToDestroy.push_back(_framebufferRef);\n if (_framebufferTransparentsRef.isValid())\n framebuffersToDestroy.push_back(_framebufferTransparentsRef);\n\n if (_lightingBufferImageRef.isValid())\n imgsToDestroy.push_back(_lightingBufferImageRef);\n if (_lightingBufferTransparentsImageRef.isValid())\n imgsToDestroy.push_back(_lightingBufferTransparentsImageRef);\n\n FramebufferManager::destroyFramebuffersAndResources(framebuffersToDestroy);\n DrawCallManager::destroyDrawCallsAndResources(drawCallsToDestroy);\n ImageManager::destroyImagesAndResources(imgsToDestroy);\n }\n\n glm::uvec3 dim = glm::uvec3(RenderSystem::_backbufferDimensions.x,\n RenderSystem::_backbufferDimensions.y, 1u);\n\n _lightingBufferImageRef = ImageManager::createImage(_N(LightBuffer));\n {\n ImageManager::resetToDefault(_lightingBufferImageRef);\n ImageManager::addResourceFlags(\n _lightingBufferImageRef,\n Dod::Resources::ResourceFlags::kResourceVolatile);\n ImageManager::_descMemoryPoolType(_lightingBufferImageRef) =\n MemoryPoolType::kResolutionDependentImages;\n\n ImageManager::_descDimensions(_lightingBufferImageRef) = dim;\n ImageManager::_descImageFormat(_lightingBufferImageRef) =\n Format::kR16G16B16A16Float;\n ImageManager::_descImageType(_lightingBufferImageRef) = ImageType::kTexture;\n }\n imgsToCreate.push_back(_lightingBufferImageRef);\n\n _lightingBufferTransparentsImageRef =\n ImageManager::createImage(_N(LightBufferTransparents));\n {\n ImageManager::resetToDefault(_lightingBufferTransparentsImageRef);\n ImageManager::addResourceFlags(\n _lightingBufferTransparentsImageRef,\n Dod::Resources::ResourceFlags::kResourceVolatile);\n ImageManager::_descMemoryPoolType(_lightingBufferTransparentsImageRef) =\n MemoryPoolType::kResolutionDependentImages;\n\n ImageManager::_descDimensions(_lightingBufferTransparentsImageRef) = dim;\n ImageManager::_descImageFormat(_lightingBufferTransparentsImageRef) =\n Format::kR16G16B16A16Float;\n ImageManager::_descImageType(_lightingBufferTransparentsImageRef) =\n ImageType::kTexture;\n }\n imgsToCreate.push_back(_lightingBufferTransparentsImageRef);\n\n ImageManager::createResources(imgsToCreate);\n\n _framebufferRef = FramebufferManager::createFramebuffer(_N(Lighting));\n {\n FramebufferManager::resetToDefault(_framebufferRef);\n FramebufferManager::addResourceFlags(\n _framebufferRef, Dod::Resources::ResourceFlags::kResourceVolatile);\n\n FramebufferManager::_descAttachedImages(_framebufferRef)\n .push_back(_lightingBufferImageRef);\n\n FramebufferManager::_descDimensions(_framebufferRef) =\n glm::uvec2(RenderSystem::_backbufferDimensions.x,\n RenderSystem::_backbufferDimensions.y);\n FramebufferManager::_descRenderPass(_framebufferRef) = _renderPassRef;\n\n framebuffersToCreate.push_back(_framebufferRef);\n }\n\n _framebufferTransparentsRef =\n FramebufferManager::createFramebuffer(_N(LightingTransparents));\n {\n FramebufferManager::resetToDefault(_framebufferTransparentsRef);\n FramebufferManager::addResourceFlags(\n _framebufferTransparentsRef,\n Dod::Resources::ResourceFlags::kResourceVolatile);\n\n FramebufferManager::_descAttachedImages(_framebufferTransparentsRef)\n .push_back(_lightingBufferTransparentsImageRef);\n\n FramebufferManager::_descDimensions(_framebufferTransparentsRef) =\n glm::uvec2(RenderSystem::_backbufferDimensions.x,\n RenderSystem::_backbufferDimensions.y);\n FramebufferManager::_descRenderPass(_framebufferTransparentsRef) =\n _renderPassRef;\n\n framebuffersToCreate.push_back(_framebufferTransparentsRef);\n }\n\n FramebufferManager::createResources(framebuffersToCreate);\n\n \/\/ Draw calls\n _drawCallRef = DrawCallManager::createDrawCall(_N(Lighting));\n {\n DrawCallManager::resetToDefault(_drawCallRef);\n DrawCallManager::addResourceFlags(\n _drawCallRef, Dod::Resources::ResourceFlags::kResourceVolatile);\n\n DrawCallManager::_descPipeline(_drawCallRef) = _pipelineRef;\n DrawCallManager::_descVertexCount(_drawCallRef) = 3u;\n\n DrawCallManager::bindBuffer(\n _drawCallRef, _N(PerInstance), GpuProgramType::kFragment,\n UniformManager::_perInstanceUniformBuffer,\n UboType::kPerInstanceFragment, sizeof(PerInstanceData));\n DrawCallManager::bindImage(\n _drawCallRef, _N(albedoTex), GpuProgramType::kFragment,\n ImageManager::getResourceByName(_N(GBufferAlbedo)),\n Samplers::kLinearClamp);\n DrawCallManager::bindImage(\n _drawCallRef, _N(normalTex), GpuProgramType::kFragment,\n ImageManager::getResourceByName(_N(GBufferNormal)),\n Samplers::kLinearClamp);\n DrawCallManager::bindImage(\n _drawCallRef, _N(parameter0Tex), GpuProgramType::kFragment,\n ImageManager::getResourceByName(_N(GBufferParameter0)),\n Samplers::kLinearClamp);\n DrawCallManager::bindImage(\n _drawCallRef, _N(depthTex), GpuProgramType::kFragment,\n ImageManager::getResourceByName(_N(GBufferDepth)),\n Samplers::kNearestClamp);\n DrawCallManager::bindImage(\n _drawCallRef, _N(ssaoTex), GpuProgramType::kFragment,\n ImageManager::getResourceByName(_N(SSAO)), Samplers::kNearestClamp);\n DrawCallManager::bindImage(_drawCallRef, _N(irradianceTex),\n GpuProgramType::kFragment,\n ImageManager::getResourceByName(\n _N(GCanyon_C_YumaPoint_3k_cube_irradiance)),\n Samplers::kLinearClamp);\n DrawCallManager::bindImage(_drawCallRef, _N(specularTex),\n GpuProgramType::kFragment,\n ImageManager::getResourceByName(\n _N(GCanyon_C_YumaPoint_3k_cube_specular)),\n Samplers::kLinearClamp);\n DrawCallManager::bindImage(\n _drawCallRef, _N(shadowBufferTex), GpuProgramType::kFragment,\n ImageManager::getResourceByName(_N(ShadowBuffer)), Samplers::kShadow);\n DrawCallManager::bindBuffer(\n _drawCallRef, _N(MaterialBuffer), GpuProgramType::kFragment,\n MaterialBuffer::_materialBuffer, UboType::kInvalidUbo,\n BufferManager::_descSizeInBytes(MaterialBuffer::_materialBuffer));\n }\n\n drawcallsToCreate.push_back(_drawCallRef);\n\n _drawCallTransparentsRef =\n DrawCallManager::createDrawCall(_N(LightingTransparents));\n {\n DrawCallManager::resetToDefault(_drawCallTransparentsRef);\n DrawCallManager::addResourceFlags(\n _drawCallTransparentsRef,\n Dod::Resources::ResourceFlags::kResourceVolatile);\n\n DrawCallManager::_descPipeline(_drawCallTransparentsRef) = _pipelineRef;\n DrawCallManager::_descVertexCount(_drawCallTransparentsRef) = 3u;\n\n DrawCallManager::bindBuffer(\n _drawCallTransparentsRef, _N(PerInstance), GpuProgramType::kFragment,\n UniformManager::_perInstanceUniformBuffer,\n UboType::kPerInstanceFragment, sizeof(PerInstanceData));\n DrawCallManager::bindImage(\n _drawCallTransparentsRef, _N(albedoTex), GpuProgramType::kFragment,\n ImageManager::getResourceByName(_N(GBufferTransparentsAlbedo)),\n Samplers::kLinearClamp);\n DrawCallManager::bindImage(\n _drawCallTransparentsRef, _N(normalTex), GpuProgramType::kFragment,\n ImageManager::getResourceByName(_N(GBufferTransparentsNormal)),\n Samplers::kLinearClamp);\n DrawCallManager::bindImage(\n _drawCallTransparentsRef, _N(parameter0Tex), GpuProgramType::kFragment,\n ImageManager::getResourceByName(_N(GBufferTransparentsParameter0)),\n Samplers::kLinearClamp);\n DrawCallManager::bindImage(\n _drawCallTransparentsRef, _N(depthTex), GpuProgramType::kFragment,\n ImageManager::getResourceByName(_N(GBufferTransparentsDepth)),\n Samplers::kNearestClamp);\n DrawCallManager::bindImage(\n _drawCallTransparentsRef, _N(ssaoTex), GpuProgramType::kFragment,\n ImageManager::getResourceByName(_N(SSAO)), Samplers::kLinearClamp);\n DrawCallManager::bindImage(_drawCallTransparentsRef, _N(irradianceTex),\n GpuProgramType::kFragment,\n ImageManager::getResourceByName(\n _N(GCanyon_C_YumaPoint_3k_cube_irradiance)),\n Samplers::kLinearClamp);\n DrawCallManager::bindImage(_drawCallTransparentsRef, _N(specularTex),\n GpuProgramType::kFragment,\n ImageManager::getResourceByName(\n _N(GCanyon_C_YumaPoint_3k_cube_specular)),\n Samplers::kLinearClamp);\n DrawCallManager::bindImage(\n _drawCallTransparentsRef, _N(shadowBufferTex),\n GpuProgramType::kFragment,\n ImageManager::getResourceByName(_N(ShadowBuffer)), Samplers::kShadow);\n DrawCallManager::bindBuffer(\n _drawCallTransparentsRef, _N(MaterialBuffer), GpuProgramType::kFragment,\n MaterialBuffer::_materialBuffer, UboType::kInvalidUbo,\n BufferManager::_descSizeInBytes(MaterialBuffer::_materialBuffer));\n }\n drawcallsToCreate.push_back(_drawCallTransparentsRef);\n\n DrawCallManager::createResources(drawcallsToCreate);\n}\n\n\/\/ <-\n\nvoid Lighting::destroy() {}\n\n\/\/ <-\n\nvoid Lighting::render(float p_DeltaT, Components::CameraRef p_CameraRef)\n{\n _INTR_PROFILE_CPU(\"Render Pass\", \"Render Lighting\");\n _INTR_PROFILE_GPU(\"Render Lighting\");\n\n renderLighting(_framebufferRef, _drawCallRef, _lightingBufferImageRef,\n p_CameraRef);\n renderLighting(_framebufferTransparentsRef, _drawCallTransparentsRef,\n _lightingBufferTransparentsImageRef, p_CameraRef);\n}\n}\n}\n}\n}\nSample linearly in the lighting pass\/\/ Copyright 2016 Benjamin Glatzel\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n\/\/ Precompiled header file\n#include \"stdafx_vulkan.h\"\n#include \"stdafx.h\"\n\nnamespace Intrinsic\n{\nnamespace Renderer\n{\nnamespace Vulkan\n{\nnamespace RenderPass\n{\nnamespace\n{\nResources::ImageRef _lightingBufferImageRef;\nResources::ImageRef _lightingBufferTransparentsImageRef;\nResources::FramebufferRef _framebufferRef;\nResources::FramebufferRef _framebufferTransparentsRef;\nResources::RenderPassRef _renderPassRef;\nResources::PipelineRef _pipelineRef;\nResources::DrawCallRef _drawCallRef;\nResources::DrawCallRef _drawCallTransparentsRef;\n\n\/\/ <-\n\nstruct PerInstanceData\n{\n glm::mat4 viewMatrix;\n glm::mat4 invProjectionMatrix;\n glm::mat4 invViewMatrix;\n\n glm::mat4 shadowViewProjMatrix[_INTR_MAX_SHADOW_MAP_COUNT];\n} _perInstanceData;\n\n\/\/ <-\n\nvoid renderLighting(Resources::FramebufferRef p_FramebufferRef,\n Resources::DrawCallRef p_DrawCall,\n Resources::ImageRef p_LightingBufferRef,\n Components::CameraRef p_CameraRef)\n{\n using namespace Resources;\n\n \/\/ Update per instance data\n {\n _perInstanceData.invProjectionMatrix =\n Components::CameraManager::_inverseProjectionMatrix(p_CameraRef);\n _perInstanceData.viewMatrix =\n Components::CameraManager::_viewMatrix(p_CameraRef);\n _perInstanceData.invViewMatrix =\n Components::CameraManager::_inverseViewMatrix(p_CameraRef);\n\n const _INTR_ARRAY(Core::Resources::FrustumRef)& shadowFrustums =\n RenderProcess::Default::_shadowFrustums[p_CameraRef];\n\n for (uint32_t i = 0u; i < shadowFrustums.size(); ++i)\n {\n Core::Resources::FrustumRef shadowFrustumRef = shadowFrustums[i];\n\n \/\/ Transform from camera view space => light proj. space\n _perInstanceData.shadowViewProjMatrix[i] =\n Core::Resources::FrustumManager::_viewProjectionMatrix(\n shadowFrustumRef) *\n Components::CameraManager::_inverseViewMatrix(p_CameraRef);\n }\n\n DrawCallRefArray dcsToUpdate = {p_DrawCall};\n DrawCallManager::allocateAndUpdateUniformMemory(\n dcsToUpdate, nullptr, 0u, &_perInstanceData, sizeof(PerInstanceData));\n }\n\n VkCommandBuffer primaryCmdBuffer = RenderSystem::getPrimaryCommandBuffer();\n\n ImageManager::insertImageMemoryBarrier(\n p_LightingBufferRef, VK_IMAGE_LAYOUT_UNDEFINED,\n VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL);\n\n RenderSystem::beginRenderPass(_renderPassRef, p_FramebufferRef,\n VK_SUBPASS_CONTENTS_INLINE);\n {\n RenderSystem::dispatchDrawCall(p_DrawCall, primaryCmdBuffer);\n }\n RenderSystem::endRenderPass(_renderPassRef);\n\n ImageManager::insertImageMemoryBarrier(\n p_LightingBufferRef, VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL,\n VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL);\n}\n}\n\nvoid Lighting::init()\n{\n using namespace Resources;\n\n PipelineRefArray pipelinesToCreate;\n PipelineLayoutRefArray pipelineLayoutsToCreate;\n RenderPassRefArray renderpassesToCreate;\n\n \/\/ Pipeline layout\n PipelineLayoutRef pipelineLayout;\n {\n pipelineLayout = PipelineLayoutManager::createPipelineLayout(_N(Lighting));\n PipelineLayoutManager::resetToDefault(pipelineLayout);\n\n GpuProgramManager::reflectPipelineLayout(\n 8u, {Resources::GpuProgramManager::getResourceByName(\"lighting.frag\")},\n pipelineLayout);\n }\n pipelineLayoutsToCreate.push_back(pipelineLayout);\n\n \/\/ Render passes\n {\n _renderPassRef = RenderPassManager::createRenderPass(_N(Lighting));\n RenderPassManager::resetToDefault(_renderPassRef);\n\n AttachmentDescription colorAttachment = {Format::kR16G16B16A16Float, 0u};\n\n RenderPassManager::_descAttachments(_renderPassRef)\n .push_back(colorAttachment);\n }\n renderpassesToCreate.push_back(_renderPassRef);\n\n \/\/ Pipelines\n {\n _pipelineRef = PipelineManager::createPipeline(_N(Lighting));\n PipelineManager::resetToDefault(_pipelineRef);\n\n PipelineManager::_descFragmentProgram(_pipelineRef) =\n GpuProgramManager::getResourceByName(\"lighting.frag\");\n PipelineManager::_descVertexProgram(_pipelineRef) =\n GpuProgramManager::getResourceByName(\"fullscreen_triangle.vert\");\n PipelineManager::_descRenderPass(_pipelineRef) = _renderPassRef;\n PipelineManager::_descPipelineLayout(_pipelineRef) = pipelineLayout;\n PipelineManager::_descVertexLayout(_pipelineRef) = Dod::Ref();\n PipelineManager::_descDepthStencilState(_pipelineRef) =\n DepthStencilStates::kDefaultNoDepthTestAndWrite;\n }\n pipelinesToCreate.push_back(_pipelineRef);\n\n PipelineLayoutManager::createResources(pipelineLayoutsToCreate);\n RenderPassManager::createResources(renderpassesToCreate);\n PipelineManager::createResources(pipelinesToCreate);\n}\n\n\/\/ <-\n\nvoid Lighting::onReinitRendering()\n{\n using namespace Resources;\n\n ImageRefArray imgsToDestroy;\n ImageRefArray imgsToCreate;\n FramebufferRefArray framebuffersToDestroy;\n FramebufferRefArray framebuffersToCreate;\n DrawCallRefArray drawCallsToDestroy;\n DrawCallRefArray drawcallsToCreate;\n\n \/\/ Cleanup old resources\n {\n if (_drawCallRef.isValid())\n drawCallsToDestroy.push_back(_drawCallRef);\n if (_drawCallTransparentsRef.isValid())\n drawCallsToDestroy.push_back(_drawCallTransparentsRef);\n\n if (_framebufferRef.isValid())\n framebuffersToDestroy.push_back(_framebufferRef);\n if (_framebufferTransparentsRef.isValid())\n framebuffersToDestroy.push_back(_framebufferTransparentsRef);\n\n if (_lightingBufferImageRef.isValid())\n imgsToDestroy.push_back(_lightingBufferImageRef);\n if (_lightingBufferTransparentsImageRef.isValid())\n imgsToDestroy.push_back(_lightingBufferTransparentsImageRef);\n\n FramebufferManager::destroyFramebuffersAndResources(framebuffersToDestroy);\n DrawCallManager::destroyDrawCallsAndResources(drawCallsToDestroy);\n ImageManager::destroyImagesAndResources(imgsToDestroy);\n }\n\n glm::uvec3 dim = glm::uvec3(RenderSystem::_backbufferDimensions.x,\n RenderSystem::_backbufferDimensions.y, 1u);\n\n _lightingBufferImageRef = ImageManager::createImage(_N(LightBuffer));\n {\n ImageManager::resetToDefault(_lightingBufferImageRef);\n ImageManager::addResourceFlags(\n _lightingBufferImageRef,\n Dod::Resources::ResourceFlags::kResourceVolatile);\n ImageManager::_descMemoryPoolType(_lightingBufferImageRef) =\n MemoryPoolType::kResolutionDependentImages;\n\n ImageManager::_descDimensions(_lightingBufferImageRef) = dim;\n ImageManager::_descImageFormat(_lightingBufferImageRef) =\n Format::kR16G16B16A16Float;\n ImageManager::_descImageType(_lightingBufferImageRef) = ImageType::kTexture;\n }\n imgsToCreate.push_back(_lightingBufferImageRef);\n\n _lightingBufferTransparentsImageRef =\n ImageManager::createImage(_N(LightBufferTransparents));\n {\n ImageManager::resetToDefault(_lightingBufferTransparentsImageRef);\n ImageManager::addResourceFlags(\n _lightingBufferTransparentsImageRef,\n Dod::Resources::ResourceFlags::kResourceVolatile);\n ImageManager::_descMemoryPoolType(_lightingBufferTransparentsImageRef) =\n MemoryPoolType::kResolutionDependentImages;\n\n ImageManager::_descDimensions(_lightingBufferTransparentsImageRef) = dim;\n ImageManager::_descImageFormat(_lightingBufferTransparentsImageRef) =\n Format::kR16G16B16A16Float;\n ImageManager::_descImageType(_lightingBufferTransparentsImageRef) =\n ImageType::kTexture;\n }\n imgsToCreate.push_back(_lightingBufferTransparentsImageRef);\n\n ImageManager::createResources(imgsToCreate);\n\n _framebufferRef = FramebufferManager::createFramebuffer(_N(Lighting));\n {\n FramebufferManager::resetToDefault(_framebufferRef);\n FramebufferManager::addResourceFlags(\n _framebufferRef, Dod::Resources::ResourceFlags::kResourceVolatile);\n\n FramebufferManager::_descAttachedImages(_framebufferRef)\n .push_back(_lightingBufferImageRef);\n\n FramebufferManager::_descDimensions(_framebufferRef) =\n glm::uvec2(RenderSystem::_backbufferDimensions.x,\n RenderSystem::_backbufferDimensions.y);\n FramebufferManager::_descRenderPass(_framebufferRef) = _renderPassRef;\n\n framebuffersToCreate.push_back(_framebufferRef);\n }\n\n _framebufferTransparentsRef =\n FramebufferManager::createFramebuffer(_N(LightingTransparents));\n {\n FramebufferManager::resetToDefault(_framebufferTransparentsRef);\n FramebufferManager::addResourceFlags(\n _framebufferTransparentsRef,\n Dod::Resources::ResourceFlags::kResourceVolatile);\n\n FramebufferManager::_descAttachedImages(_framebufferTransparentsRef)\n .push_back(_lightingBufferTransparentsImageRef);\n\n FramebufferManager::_descDimensions(_framebufferTransparentsRef) =\n glm::uvec2(RenderSystem::_backbufferDimensions.x,\n RenderSystem::_backbufferDimensions.y);\n FramebufferManager::_descRenderPass(_framebufferTransparentsRef) =\n _renderPassRef;\n\n framebuffersToCreate.push_back(_framebufferTransparentsRef);\n }\n\n FramebufferManager::createResources(framebuffersToCreate);\n\n \/\/ Draw calls\n _drawCallRef = DrawCallManager::createDrawCall(_N(Lighting));\n {\n DrawCallManager::resetToDefault(_drawCallRef);\n DrawCallManager::addResourceFlags(\n _drawCallRef, Dod::Resources::ResourceFlags::kResourceVolatile);\n\n DrawCallManager::_descPipeline(_drawCallRef) = _pipelineRef;\n DrawCallManager::_descVertexCount(_drawCallRef) = 3u;\n\n DrawCallManager::bindBuffer(\n _drawCallRef, _N(PerInstance), GpuProgramType::kFragment,\n UniformManager::_perInstanceUniformBuffer,\n UboType::kPerInstanceFragment, sizeof(PerInstanceData));\n DrawCallManager::bindImage(\n _drawCallRef, _N(albedoTex), GpuProgramType::kFragment,\n ImageManager::getResourceByName(_N(GBufferAlbedo)),\n Samplers::kLinearClamp);\n DrawCallManager::bindImage(\n _drawCallRef, _N(normalTex), GpuProgramType::kFragment,\n ImageManager::getResourceByName(_N(GBufferNormal)),\n Samplers::kLinearClamp);\n DrawCallManager::bindImage(\n _drawCallRef, _N(parameter0Tex), GpuProgramType::kFragment,\n ImageManager::getResourceByName(_N(GBufferParameter0)),\n Samplers::kLinearClamp);\n DrawCallManager::bindImage(\n _drawCallRef, _N(depthTex), GpuProgramType::kFragment,\n ImageManager::getResourceByName(_N(GBufferDepth)),\n Samplers::kNearestClamp);\n DrawCallManager::bindImage(\n _drawCallRef, _N(ssaoTex), GpuProgramType::kFragment,\n ImageManager::getResourceByName(_N(SSAO)), Samplers::kLinearClamp);\n DrawCallManager::bindImage(_drawCallRef, _N(irradianceTex),\n GpuProgramType::kFragment,\n ImageManager::getResourceByName(\n _N(GCanyon_C_YumaPoint_3k_cube_irradiance)),\n Samplers::kLinearClamp);\n DrawCallManager::bindImage(_drawCallRef, _N(specularTex),\n GpuProgramType::kFragment,\n ImageManager::getResourceByName(\n _N(GCanyon_C_YumaPoint_3k_cube_specular)),\n Samplers::kLinearClamp);\n DrawCallManager::bindImage(\n _drawCallRef, _N(shadowBufferTex), GpuProgramType::kFragment,\n ImageManager::getResourceByName(_N(ShadowBuffer)), Samplers::kShadow);\n DrawCallManager::bindBuffer(\n _drawCallRef, _N(MaterialBuffer), GpuProgramType::kFragment,\n MaterialBuffer::_materialBuffer, UboType::kInvalidUbo,\n BufferManager::_descSizeInBytes(MaterialBuffer::_materialBuffer));\n }\n\n drawcallsToCreate.push_back(_drawCallRef);\n\n _drawCallTransparentsRef =\n DrawCallManager::createDrawCall(_N(LightingTransparents));\n {\n DrawCallManager::resetToDefault(_drawCallTransparentsRef);\n DrawCallManager::addResourceFlags(\n _drawCallTransparentsRef,\n Dod::Resources::ResourceFlags::kResourceVolatile);\n\n DrawCallManager::_descPipeline(_drawCallTransparentsRef) = _pipelineRef;\n DrawCallManager::_descVertexCount(_drawCallTransparentsRef) = 3u;\n\n DrawCallManager::bindBuffer(\n _drawCallTransparentsRef, _N(PerInstance), GpuProgramType::kFragment,\n UniformManager::_perInstanceUniformBuffer,\n UboType::kPerInstanceFragment, sizeof(PerInstanceData));\n DrawCallManager::bindImage(\n _drawCallTransparentsRef, _N(albedoTex), GpuProgramType::kFragment,\n ImageManager::getResourceByName(_N(GBufferTransparentsAlbedo)),\n Samplers::kLinearClamp);\n DrawCallManager::bindImage(\n _drawCallTransparentsRef, _N(normalTex), GpuProgramType::kFragment,\n ImageManager::getResourceByName(_N(GBufferTransparentsNormal)),\n Samplers::kLinearClamp);\n DrawCallManager::bindImage(\n _drawCallTransparentsRef, _N(parameter0Tex), GpuProgramType::kFragment,\n ImageManager::getResourceByName(_N(GBufferTransparentsParameter0)),\n Samplers::kLinearClamp);\n DrawCallManager::bindImage(\n _drawCallTransparentsRef, _N(depthTex), GpuProgramType::kFragment,\n ImageManager::getResourceByName(_N(GBufferTransparentsDepth)),\n Samplers::kNearestClamp);\n DrawCallManager::bindImage(\n _drawCallTransparentsRef, _N(ssaoTex), GpuProgramType::kFragment,\n ImageManager::getResourceByName(_N(SSAO)), Samplers::kLinearClamp);\n DrawCallManager::bindImage(_drawCallTransparentsRef, _N(irradianceTex),\n GpuProgramType::kFragment,\n ImageManager::getResourceByName(\n _N(GCanyon_C_YumaPoint_3k_cube_irradiance)),\n Samplers::kLinearClamp);\n DrawCallManager::bindImage(_drawCallTransparentsRef, _N(specularTex),\n GpuProgramType::kFragment,\n ImageManager::getResourceByName(\n _N(GCanyon_C_YumaPoint_3k_cube_specular)),\n Samplers::kLinearClamp);\n DrawCallManager::bindImage(\n _drawCallTransparentsRef, _N(shadowBufferTex),\n GpuProgramType::kFragment,\n ImageManager::getResourceByName(_N(ShadowBuffer)), Samplers::kShadow);\n DrawCallManager::bindBuffer(\n _drawCallTransparentsRef, _N(MaterialBuffer), GpuProgramType::kFragment,\n MaterialBuffer::_materialBuffer, UboType::kInvalidUbo,\n BufferManager::_descSizeInBytes(MaterialBuffer::_materialBuffer));\n }\n drawcallsToCreate.push_back(_drawCallTransparentsRef);\n\n DrawCallManager::createResources(drawcallsToCreate);\n}\n\n\/\/ <-\n\nvoid Lighting::destroy() {}\n\n\/\/ <-\n\nvoid Lighting::render(float p_DeltaT, Components::CameraRef p_CameraRef)\n{\n _INTR_PROFILE_CPU(\"Render Pass\", \"Render Lighting\");\n _INTR_PROFILE_GPU(\"Render Lighting\");\n\n renderLighting(_framebufferRef, _drawCallRef, _lightingBufferImageRef,\n p_CameraRef);\n renderLighting(_framebufferTransparentsRef, _drawCallTransparentsRef,\n _lightingBufferTransparentsImageRef, p_CameraRef);\n}\n}\n}\n}\n}\n<|endoftext|>"} {"text":"\/*\n * Copyright(c) Sophist Solutions, Inc. 1990-2011. All rights reserved\n *\/\n#include\t\"..\/..\/..\/StroikaPreComp.h\"\n\n#if\t\tqHasFeature_libcurl\n#include\t\n#endif\n\n#include\t\"..\/..\/..\/Characters\/Format.h\"\n#include\t\"..\/..\/..\/Execution\/Exceptions.h\"\n\n#include\t\"Client_libcurl.h\"\n\nusing\tnamespace\tStroika::Foundation;\nusing\tnamespace\tStroika::Foundation::Characters;\nusing\tnamespace\tStroika::Foundation::IO;\nusing\tnamespace\tStroika::Foundation::IO::Network;\nusing\tnamespace\tStroika::Foundation::IO::Network::Transfer;\n\n\n\n\n\n#if\t\tqHasFeature_libcurl\nnamespace\t{\n\tstruct\tModuleInit_ {\n\t\tModuleInit_ ()\n\t\t{\n\t\t\tcurl_global_init (CURL_GLOBAL_ALL);\n\t\t}\n\t};\n}\n#endif\n\n\n\n\n#if\t\tqHasFeature_libcurl\nnamespace\t{\n\twstring\tmkExceptMsg_ (LibCurlException::CURLcode ccode)\n\t\t{\n\t\t\treturn String::FromUTF8 (curl_easy_strerror (static_cast<::CURLcode> (ccode))).As ();\n\t\t}\n}\n\n\/*\n ********************************************************************************\n ************************ Transfer::LibCurlException ****************************\n ********************************************************************************\n *\/\nLibCurlException::LibCurlException (CURLcode ccode)\n\t: StringException (mkExceptMsg_ (ccode))\n\t, fCurlCode_ (ccode)\n{\n}\n\nvoid\tLibCurlException::DoThrowIfError (CURLcode status)\n{\n\tif (status != 0) {\n\t\tExecution::DoThrow (LibCurlException (status));\n\t}\n}\n#endif\n\n\n\n\n\n\n\n\n#if\t\tqHasFeature_libcurl\n\/*\n ********************************************************************************\n ********************* Transfer::IConnection_LibCurl ****************************\n ********************************************************************************\n *\/\nIConnection_LibCurl::IConnection_LibCurl ()\n\t: fCurlHandle_ (curl_easy_init ())\n\t, fCURLCache_URL_ ()\n\t, fResponseData_ ()\n\t, fSavedHeaders_ (nullptr)\n{\n}\n\nIConnection_LibCurl::~IConnection_LibCurl ()\n{\n\tif (fCurlHandle_ != nullptr) {\n\t\tcurl_easy_cleanup (fCurlHandle_);\n\t}\n\tif (fSavedHeaders_ != nullptr) {\n\t\tcurl_slist_free_all (fSavedHeaders_);\n\t\tfSavedHeaders_ = nullptr;\n\t}\n}\n\nURL\t\tIConnection_LibCurl::GetURL () const override\n{\n\t\/\/ needs work... - not sure this is safe - may need to cache orig... instead of reparsing...\n\treturn URL (String::FromUTF8 (fCURLCache_URL_).As ());\n}\n\nvoid\tIConnection_LibCurl::SetURL (const URL& url) override\n{\n\tMakeHandleIfNeeded_ ();\n\tfCURLCache_URL_ = String (url.GetURL ()).AsUTF8 ();\n\tLibCurlException::DoThrowIfError (::curl_easy_setopt (fCurlHandle_, CURLOPT_URL, fCURLCache_URL_.c_str ()));\n}\n\nvoid\tIConnection_LibCurl::Close ()\toverride\n{\n\tif (fCurlHandle_ != nullptr) {\n\t\tLibCurlException::DoThrowIfError (::curl_easy_cleanup (fCurlHandle_));\n\t\tfCurlHandle_ = nullptr;\n\t}\n}\n\nsize_t\tIConnection_LibCurl::ResponseWriteHandler_ (void* ptr, size_t size, size_t nmemb, void* userP)\n{\n\treturn reinterpret_cast (userP)->ResponseWriteHandler_ (reinterpret_cast (ptr), size * nmemb);\n}\n\nsize_t\tIConnection_LibCurl::ResponseWriteHandler_ (const Byte* ptr, size_t nBytes)\n{\n\tfResponseData_.insert (ptr, ptr + nBytes);\n\treturn nBytes;\n}\n\nsize_t\tIConnection_LibCurl::ResponseHeaderWriteHandler_ (void* ptr, size_t size, size_t nmemb, void* userP)\n{\n\treturn reinterpret_cast (userP)->ResponseHeaderWriteHandler_ (reinterpret_cast (ptr), size * nmemb);\n}\n\nsize_t\tIConnection_LibCurl::ResponseHeaderWriteHandler_ (const Byte* ptr, size_t nBytes)\n{\n\tstring tmp (reinterpret_cast (ptr), nBytes);\n\tstring::size_type i = tmp.find (':');\n\tString\tfrom;\n\tString\tto;\n\tif (i == string::npos) {\n\t\tfrom = String::FromUTF8 (tmp);\n\t}\n\telse {\n\t\tfrom = String::FromUTF8 (tmp.substr (0, i));\n\t\tto = String::FromUTF8 (tmp.substr (i+1));\n\t}\n\tfrom = from.Trim ();\n\tto = to.Trim ();\n\tfResponseHeaders_[from] = to;\n\treturn nBytes;\n}\n\nResponse\tIConnection_LibCurl::SendAndRequest (const Request& request)\toverride\n{\n\tMakeHandleIfNeeded_ ();\n\tfResponseData_.clear ();\n\tfResponseHeaders_.clear ();\n\n\t\/\/grab useragent from request headers...\n\t\/\/curl_easy_setopt (fCurlHandle_, CURLOPT_USERAGENT, \"libcurl-agent\/1.0\");\n\n\t\/\/ grab initial headers and do POST\/etc based on args in request...\n\tcurl_slist*\ttmpH\t=\tcurl_slist_append (nullptr, \"Expect: \");\t\/\/tmphack - really iterate over requst headers - with a few exceptions...\n\tLibCurlException::DoThrowIfError (::curl_easy_setopt (fCurlHandle_, CURLOPT_HTTPHEADER, tmpH));\n\tif (fSavedHeaders_ != nullptr) {\n\t\tcurl_slist_free_all (fSavedHeaders_);\n\t\tfSavedHeaders_ = nullptr;\n\t}\n\tfSavedHeaders_ = tmpH;\n\n\tLibCurlException::DoThrowIfError (:: curl_easy_perform (fCurlHandle_));\n\n\tResponse\tresponse;\n\tresponse.fData = fResponseData_;\n\n\tlong\tresultCode\t=\t0;\n\tLibCurlException::DoThrowIfError (::curl_easy_getinfo (fCurlHandle_, CURLINFO_RESPONSE_CODE, &resultCode));\n\tresponse.fStatus = resultCode;\n\tresponse.fHeaders = fResponseHeaders_;\n\tresponse.fData = fResponseData_;\n\treturn response;\n}\n\nvoid\tIConnection_LibCurl::MakeHandleIfNeeded_ ()\n{\n\tif (fCurlHandle_ == nullptr) {\n\t\tfCurlHandle_ = curl_easy_init ();\n\t\tLibCurlException::DoThrowIfError (::curl_easy_setopt (fCurlHandle_, CURLOPT_URL, fCURLCache_URL_.c_str ()));\n\t}\n}\n#endif\n\nmore minor cleanups to Client_libcurl\/*\n * Copyright(c) Sophist Solutions, Inc. 1990-2011. All rights reserved\n *\/\n#include\t\"..\/..\/..\/StroikaPreComp.h\"\n\n#if\t\tqHasFeature_libcurl\n#include\t\n#endif\n\n#include\t\"..\/..\/..\/Characters\/Format.h\"\n#include\t\"..\/..\/..\/Execution\/Exceptions.h\"\n\n#include\t\"Client_libcurl.h\"\n\nusing\tnamespace\tStroika::Foundation;\nusing\tnamespace\tStroika::Foundation::Characters;\nusing\tnamespace\tStroika::Foundation::IO;\nusing\tnamespace\tStroika::Foundation::IO::Network;\nusing\tnamespace\tStroika::Foundation::IO::Network::Transfer;\n\n\n\n\n\n#if\t\tqHasFeature_libcurl\nnamespace\t{\n\tstruct\tModuleInit_ {\n\t\tModuleInit_ ()\n\t\t{\n\t\t\tcurl_global_init (CURL_GLOBAL_ALL);\n\t\t}\n\t};\n}\n#endif\n\n\n\n\n#if\t\tqHasFeature_libcurl\nnamespace\t{\n\twstring\tmkExceptMsg_ (LibCurlException::CURLcode ccode)\n\t\t{\n\t\t\treturn String::FromUTF8 (curl_easy_strerror (static_cast (ccode))).As ();\n\t\t}\n}\n\n\/*\n ********************************************************************************\n ************************ Transfer::LibCurlException ****************************\n ********************************************************************************\n *\/\nLibCurlException::LibCurlException (CURLcode ccode)\n\t: StringException (mkExceptMsg_ (ccode))\n\t, fCurlCode_ (ccode)\n{\n}\n\nvoid\tLibCurlException::DoThrowIfError (CURLcode status)\n{\n\tif (status != CURLE_OK) {\n\t\tExecution::DoThrow (LibCurlException (status));\n\t}\n}\n#endif\n\n\n\n\n\n\n\n\n#if\t\tqHasFeature_libcurl\n\/*\n ********************************************************************************\n ********************* Transfer::IConnection_LibCurl ****************************\n ********************************************************************************\n *\/\nIConnection_LibCurl::IConnection_LibCurl ()\n\t: fCurlHandle_ (curl_easy_init ())\n\t, fCURLCache_URL_ ()\n\t, fResponseData_ ()\n\t, fSavedHeaders_ (nullptr)\n{\n}\n\nIConnection_LibCurl::~IConnection_LibCurl ()\n{\n\tif (fCurlHandle_ != nullptr) {\n\t\tcurl_easy_cleanup (fCurlHandle_);\n\t}\n\tif (fSavedHeaders_ != nullptr) {\n\t\tcurl_slist_free_all (fSavedHeaders_);\n\t\tfSavedHeaders_ = nullptr;\n\t}\n}\n\nURL\t\tIConnection_LibCurl::GetURL () const override\n{\n\t\/\/ needs work... - not sure this is safe - may need to cache orig... instead of reparsing...\n\treturn URL (String::FromUTF8 (fCURLCache_URL_).As ());\n}\n\nvoid\tIConnection_LibCurl::SetURL (const URL& url) override\n{\n\tMakeHandleIfNeeded_ ();\n\tfCURLCache_URL_ = String (url.GetURL ()).AsUTF8 ();\n\tLibCurlException::DoThrowIfError (::curl_easy_setopt (fCurlHandle_, CURLOPT_URL, fCURLCache_URL_.c_str ()));\n}\n\nvoid\tIConnection_LibCurl::Close ()\toverride\n{\n\tif (fCurlHandle_ != nullptr) {\n\t\t::curl_easy_cleanup (fCurlHandle_);\n\t\tfCurlHandle_ = nullptr;\n\t}\n}\n\nsize_t\tIConnection_LibCurl::ResponseWriteHandler_ (void* ptr, size_t size, size_t nmemb, void* userP)\n{\n\treturn reinterpret_cast (userP)->ResponseWriteHandler_ (reinterpret_cast (ptr), size * nmemb);\n}\n\nsize_t\tIConnection_LibCurl::ResponseWriteHandler_ (const Byte* ptr, size_t nBytes)\n{\n\tfResponseData_.insert (fResponseData_.end (), ptr, ptr + nBytes);\n\treturn nBytes;\n}\n\nsize_t\tIConnection_LibCurl::ResponseHeaderWriteHandler_ (void* ptr, size_t size, size_t nmemb, void* userP)\n{\n\treturn reinterpret_cast (userP)->ResponseHeaderWriteHandler_ (reinterpret_cast (ptr), size * nmemb);\n}\n\nsize_t\tIConnection_LibCurl::ResponseHeaderWriteHandler_ (const Byte* ptr, size_t nBytes)\n{\n\tstring tmp (reinterpret_cast (ptr), nBytes);\n\tstring::size_type i = tmp.find (':');\n\tString\tfrom;\n\tString\tto;\n\tif (i == string::npos) {\n\t\tfrom = String::FromUTF8 (tmp);\n\t}\n\telse {\n\t\tfrom = String::FromUTF8 (tmp.substr (0, i));\n\t\tto = String::FromUTF8 (tmp.substr (i+1));\n\t}\n\tfrom = from.Trim ();\n\tto = to.Trim ();\n\tfResponseHeaders_[from] = to;\n\treturn nBytes;\n}\n\nResponse\tIConnection_LibCurl::SendAndRequest (const Request& request)\toverride\n{\n\tMakeHandleIfNeeded_ ();\n\tfResponseData_.clear ();\n\tfResponseHeaders_.clear ();\n\n\t\/\/grab useragent from request headers...\n\t\/\/curl_easy_setopt (fCurlHandle_, CURLOPT_USERAGENT, \"libcurl-agent\/1.0\");\n\n\t\/\/ grab initial headers and do POST\/etc based on args in request...\n\tcurl_slist*\ttmpH\t=\tcurl_slist_append (nullptr, \"Expect: \");\t\/\/tmphack - really iterate over requst headers - with a few exceptions...\n\tLibCurlException::DoThrowIfError (::curl_easy_setopt (fCurlHandle_, CURLOPT_HTTPHEADER, tmpH));\n\tif (fSavedHeaders_ != nullptr) {\n\t\tcurl_slist_free_all (fSavedHeaders_);\n\t\tfSavedHeaders_ = nullptr;\n\t}\n\tfSavedHeaders_ = tmpH;\n\n\tLibCurlException::DoThrowIfError (:: curl_easy_perform (fCurlHandle_));\n\n\tResponse\tresponse;\n\tresponse.fData = fResponseData_;\n\n\tlong\tresultCode\t=\t0;\n\tLibCurlException::DoThrowIfError (::curl_easy_getinfo (fCurlHandle_, CURLINFO_RESPONSE_CODE, &resultCode));\n\tresponse.fStatus = resultCode;\n\tresponse.fHeaders = fResponseHeaders_;\n\tresponse.fData = fResponseData_;\n\treturn response;\n}\n\nvoid\tIConnection_LibCurl::MakeHandleIfNeeded_ ()\n{\n\tif (fCurlHandle_ == nullptr) {\n\t\tfCurlHandle_ = curl_easy_init ();\n\t\tLibCurlException::DoThrowIfError (::curl_easy_setopt (fCurlHandle_, CURLOPT_URL, fCURLCache_URL_.c_str ()));\n\t}\n}\n#endif\n\n<|endoftext|>"} {"text":"\/* Copyright 2017 The TensorFlow Authors. All Rights Reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n==============================================================================*\/\n\n\/\/ See docs in ..\/ops\/math_ops.cc.\n\n\/\/ This file uses MKL CBLAS xGEMM for acceleration of TF Matrix-Matrix\n\/\/ Multiplication (MatMul) operations.\n\/\/ We currently register this kernel only for MKL supported data\n\/\/ types (float, double, complex64, complex128). The macro INTEL_MKL is defined\n\/\/ by the build system only when MKL is chosen as an option at configure stage\n\/\/ and when it is undefined at build time, this file becomes an empty\n\/\/ compilation unit\n\n\n#if defined(INTEL_MKL)\n\n#include \"tensorflow\/core\/framework\/op.h\"\n#include \"tensorflow\/core\/framework\/op_kernel.h\"\n#include \"tensorflow\/core\/framework\/register_types.h\"\n#include \"tensorflow\/core\/kernels\/fill_functor.h\"\n\n\/\/This header file is part of MKL ML, need equivalent file in MKL DNN\n#ifndef DO_NOT_USE_ML\n#include \"mkl_cblas.h\"\n#else\n#include \"mkldnn.h\"\n#endif\n\nnamespace tensorflow {\n\ntypedef Eigen::ThreadPoolDevice CPUDevice;\n\ntemplate \nclass MklMatMulOp : public OpKernel {\n public:\n explicit MklMatMulOp(OpKernelConstruction* ctx) : OpKernel(ctx) {\n OP_REQUIRES_OK(ctx, ctx->GetAttr(\"transpose_a\", &transpose_a_));\n OP_REQUIRES_OK(ctx, ctx->GetAttr(\"transpose_b\", &transpose_b_));\n }\n\n void Compute(OpKernelContext* ctx) override {\n const Tensor& a = ctx->input(0);\n const Tensor& b = ctx->input(1);\n\n \/\/ Check that the dimensions of the two matrices are valid.\n OP_REQUIRES(ctx, TensorShapeUtils::IsMatrix(a.shape()),\n errors::InvalidArgument(\"In[0] is not a matrix\"));\n OP_REQUIRES(ctx, TensorShapeUtils::IsMatrix(b.shape()),\n errors::InvalidArgument(\"In[1] is not a matrix\"));\n Eigen::array, 1> dim_pair;\n dim_pair[0].first = transpose_a_ ? 0 : 1;\n dim_pair[0].second = transpose_b_ ? 1 : 0;\n\n OP_REQUIRES(\n ctx, a.dim_size(dim_pair[0].first) == b.dim_size(dim_pair[0].second),\n errors::InvalidArgument(\n \"Matrix size-incompatible: In[0]: \", a.shape().DebugString(),\n \", In[1]: \", b.shape().DebugString()));\n int a_dim_remaining = 1 - dim_pair[0].first;\n int b_dim_remaining = 1 - dim_pair[0].second;\n TensorShape out_shape(\n {a.dim_size(a_dim_remaining), b.dim_size(b_dim_remaining)});\n Tensor* out = nullptr;\n OP_REQUIRES_OK(ctx, ctx->allocate_output(0, out_shape, &out));\n\n if (out->NumElements() == 0) {\n \/\/ If a has shape [0, x] or b has shape [x, 0], the output shape\n \/\/ is a 0-element matrix, so there is nothing to do.\n return;\n }\n\n if (a.NumElements() == 0 || b.NumElements() == 0) {\n \/\/ If a has shape [x, 0] and b has shape [0, y], the\n \/\/ output shape is [x, y] where x and y are non-zero, so we fill\n \/\/ the output with zeros.\n functor::SetZeroFunctor f;\n f(ctx->eigen_device(), out->flat());\n return;\n }\n\n const int m = a.dim_size(1 - dim_pair[0].first);\n const int k = a.dim_size(dim_pair[0].first);\n const int n = b.dim_size(1 - dim_pair[0].second);\n bool transpose_a = dim_pair[0].first == 0;\n bool transpose_b = dim_pair[0].second == 1;\n\n auto a_ptr = (a.template flat().data());\n auto b_ptr = (b.template flat().data());\n auto c_ptr = (out->template flat().data());\n\n MklBlasGemm(transpose_a, transpose_b, m, n, k, a_ptr, transpose_a ? m : k,\n b_ptr, transpose_b ? k : n, c_ptr, n);\n }\n\n private:\n bool transpose_a_;\n bool transpose_b_;\n \/\/ --------------------------------------------------------------------------\n \/\/\n \/\/ @brief Matrix-Matrix Multiplication with FP32 tensors, a, b, c using CBLAS\n \/\/ interface. c = op(a) * op(b)\n \/\/\n \/\/ @param transa Specifies the form of op(a) used in MatMul. If transa is\n \/\/ true, then op(a) = a^T, otherwise op(a) = a\n \/\/\n \/\/ @param transb Specifies the form of op(b) used in MatMul. If transb is\n \/\/ true, then op(b) = b^T, otherwise op(b) = b\n \/\/\n \/\/ @param m Specifies the number of rows of the matrix op(a) and of the\n \/\/ matrix c. The value of m must be at least zero.\n \/\/\n \/\/ @param n Specifies the number of columns of the matrix op(b) and the\n \/\/ number of columns of the matrix c. The value of n must be at least zero.\n \/\/\n \/\/ @param k Specifies the number of columns of the matrix op(a) and the\n \/\/ number of rows of the matrix op(b)\n \/\/\n \/\/ @param a Address of matrix a\n \/\/\n \/\/ @param lda Leading dimension of 'a' matrix. This is set at calling site\n \/\/ depending on transa parameter. Since TF uses row-major\n \/\/ layout, leading dimension is the stride between consecutive rows\n \/\/ lda = max(1,k) when transa is false, otherwise lda = max(1,m)\n \/\/\n \/\/ @param b Address of matrix b\n \/\/\n \/\/ @param ldb Leading dimension of 'b' matrix. This is set at calling site\n \/\/ depending on transb parameter. Since TF uses row-major\n \/\/ layout, leading dimension is the stride between consecutive rows\n \/\/ ldb = max(1,n) when transb is false, otherwise ldb = max(1,k)\n \/\/\n \/\/ @param c Address of matrix c\n \/\/\n \/\/ @param ldc Leading dimension of 'c' matrix. Since TF uses row-major\n \/\/ layout, leading dimension is the stride between consecutive rows, max(1,n)\n \/\/\n \/\/ --------------------------------------------------------------------------\n void MklBlasGemm(bool transa, bool transb, const int m, const int n,\n const int k, const float* a, const int lda, const float* b,\n const int ldb, float* c, const int ldc) {\n \/\/ BLAS GEMM API defines Matrix Multiplication as c = alpha * op(a) * op(b)\n \/\/ + beta * c.\n \/\/ Since TF MatMul does not have parameters for alpha, beta, we set them to\n \/\/ 1.0 and 0.0 respectively.\n const float alpha = 1.0f;\n const float beta = 0.0f;\n#if defined(DO_NOT_USE_ML)\n const char* const ftrans[] = { \"N\", \"T\", \"C\"};\n int index_transa = transa? 1 : 0 ;\n int index_transb = transb? 1 : 0 ;\n VLOG(2) << \"MKL DNN SGEMM called\";\n \/\/Using the fortran api of mkldnn\n \/\/Since TF is in row major layout,reversing the order of A and B\n mkldnn_sgemm(ftrans[index_transb], ftrans[index_transa],\n &n, &m, &k, &alpha, b, &ldb, a, &lda, &beta, c, &ldc);\n#else\n cblas_sgemm(CblasRowMajor, transa ? CblasTrans : CblasNoTrans,\n transb ? CblasTrans : CblasNoTrans, m, n, k, alpha, a, lda, b,\n ldb, beta, c, ldc);\n#endif\n }\n\n \/\/ MKLDNN only supports SGEMM\n#ifndef DO_NOT_USE_ML\n\n \/\/ Matrix-Matrix Multiplication with FP64 tensors. For detailed info about\n \/\/ parameters, look at FP32 function description.\n void MklBlasGemm(bool transa, bool transb, const int m, const int n,\n const int k, const double* a, const int lda, const double* b,\n const int ldb, double* c, const int ldc) {\n const double alpha = 1.0;\n const double beta = 0.0;\n cblas_dgemm(CblasRowMajor, transa ? CblasTrans : CblasNoTrans,\n transb ? CblasTrans : CblasNoTrans, m, n, k, alpha, a, lda, b,\n ldb, beta, c, ldc);\n }\n\n \/\/ Matrix-Matrix Multiplication with Complex64 (std::complex) tensors.\n \/\/ For detailed info about parameters, look at FP32 function description.\n void MklBlasGemm(bool transa, bool transb, const int m, const int n,\n const int k, const complex64* a, const int lda,\n const complex64* b, const int ldb, complex64* c,\n int const ldc) {\n const MKL_Complex8 alpha = {1.0f, 0.0f};\n const MKL_Complex8 beta = {0.0f, 0.0f};\n cblas_cgemm(CblasRowMajor, transa ? CblasTrans : CblasNoTrans,\n transb ? CblasTrans : CblasNoTrans, m, n, k, &alpha,\n reinterpret_cast(a), lda,\n reinterpret_cast(b), ldb, &beta,\n reinterpret_cast(c), ldc);\n }\n\n \/\/ Matrix-Matrix Multiplication with Complex128 (std::complex)\n \/\/ tensors. For detailed info about parameters, look at FP32 function\n \/\/ description.\n void MklBlasGemm(bool transa, bool transb, const int m, const int n,\n const int k, const complex128* a, const int lda,\n const complex128* b, const int ldb, complex128* c,\n const int ldc) {\n const MKL_Complex16 alpha = {1.0, 0.0};\n const MKL_Complex16 beta = {0.0, 0.0};\n cblas_zgemm(CblasRowMajor, transa ? CblasTrans : CblasNoTrans,\n transb ? CblasTrans : CblasNoTrans, m, n, k, &alpha,\n reinterpret_cast(a), lda,\n reinterpret_cast(b), ldb, &beta,\n reinterpret_cast(c), ldc);\n }\n#endif\n};\n\n#define REGISTER_CPU(T) \\\n REGISTER_KERNEL_BUILDER( \\\n Name(\"MatMul\").Device(DEVICE_CPU).TypeConstraint(\"T\"), \\\n MklMatMulOp);\n\n\/\/ TODO(inteltf) Consider template specialization when adding\/removing\n\/\/ additional types\nTF_CALL_float(REGISTER_CPU);\n\n#ifndef DO_NOT_USE_ML\nTF_CALL_double(REGISTER_CPU);\nTF_CALL_complex64(REGISTER_CPU);\nTF_CALL_complex128(REGISTER_CPU);\n#endif\n\n} \/\/ namespace tensorflow\n#endif \/\/ INTEL_MKL\nRemoved unnecessary comment\/* Copyright 2017 The TensorFlow Authors. All Rights Reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n==============================================================================*\/\n\n\/\/ See docs in ..\/ops\/math_ops.cc.\n\n\/\/ This file uses MKL CBLAS xGEMM for acceleration of TF Matrix-Matrix\n\/\/ Multiplication (MatMul) operations.\n\/\/ We currently register this kernel only for MKL supported data\n\/\/ types (float, double, complex64, complex128). The macro INTEL_MKL is defined\n\/\/ by the build system only when MKL is chosen as an option at configure stage\n\/\/ and when it is undefined at build time, this file becomes an empty\n\/\/ compilation unit\n\n\n#if defined(INTEL_MKL)\n\n#include \"tensorflow\/core\/framework\/op.h\"\n#include \"tensorflow\/core\/framework\/op_kernel.h\"\n#include \"tensorflow\/core\/framework\/register_types.h\"\n#include \"tensorflow\/core\/kernels\/fill_functor.h\"\n\n#ifndef DO_NOT_USE_ML\n#include \"mkl_cblas.h\"\n#else\n#include \"mkldnn.h\"\n#endif\n\nnamespace tensorflow {\n\ntypedef Eigen::ThreadPoolDevice CPUDevice;\n\ntemplate \nclass MklMatMulOp : public OpKernel {\n public:\n explicit MklMatMulOp(OpKernelConstruction* ctx) : OpKernel(ctx) {\n OP_REQUIRES_OK(ctx, ctx->GetAttr(\"transpose_a\", &transpose_a_));\n OP_REQUIRES_OK(ctx, ctx->GetAttr(\"transpose_b\", &transpose_b_));\n }\n\n void Compute(OpKernelContext* ctx) override {\n const Tensor& a = ctx->input(0);\n const Tensor& b = ctx->input(1);\n\n \/\/ Check that the dimensions of the two matrices are valid.\n OP_REQUIRES(ctx, TensorShapeUtils::IsMatrix(a.shape()),\n errors::InvalidArgument(\"In[0] is not a matrix\"));\n OP_REQUIRES(ctx, TensorShapeUtils::IsMatrix(b.shape()),\n errors::InvalidArgument(\"In[1] is not a matrix\"));\n Eigen::array, 1> dim_pair;\n dim_pair[0].first = transpose_a_ ? 0 : 1;\n dim_pair[0].second = transpose_b_ ? 1 : 0;\n\n OP_REQUIRES(\n ctx, a.dim_size(dim_pair[0].first) == b.dim_size(dim_pair[0].second),\n errors::InvalidArgument(\n \"Matrix size-incompatible: In[0]: \", a.shape().DebugString(),\n \", In[1]: \", b.shape().DebugString()));\n int a_dim_remaining = 1 - dim_pair[0].first;\n int b_dim_remaining = 1 - dim_pair[0].second;\n TensorShape out_shape(\n {a.dim_size(a_dim_remaining), b.dim_size(b_dim_remaining)});\n Tensor* out = nullptr;\n OP_REQUIRES_OK(ctx, ctx->allocate_output(0, out_shape, &out));\n\n if (out->NumElements() == 0) {\n \/\/ If a has shape [0, x] or b has shape [x, 0], the output shape\n \/\/ is a 0-element matrix, so there is nothing to do.\n return;\n }\n\n if (a.NumElements() == 0 || b.NumElements() == 0) {\n \/\/ If a has shape [x, 0] and b has shape [0, y], the\n \/\/ output shape is [x, y] where x and y are non-zero, so we fill\n \/\/ the output with zeros.\n functor::SetZeroFunctor f;\n f(ctx->eigen_device(), out->flat());\n return;\n }\n\n const int m = a.dim_size(1 - dim_pair[0].first);\n const int k = a.dim_size(dim_pair[0].first);\n const int n = b.dim_size(1 - dim_pair[0].second);\n bool transpose_a = dim_pair[0].first == 0;\n bool transpose_b = dim_pair[0].second == 1;\n\n auto a_ptr = (a.template flat().data());\n auto b_ptr = (b.template flat().data());\n auto c_ptr = (out->template flat().data());\n\n MklBlasGemm(transpose_a, transpose_b, m, n, k, a_ptr, transpose_a ? m : k,\n b_ptr, transpose_b ? k : n, c_ptr, n);\n }\n\n private:\n bool transpose_a_;\n bool transpose_b_;\n \/\/ --------------------------------------------------------------------------\n \/\/\n \/\/ @brief Matrix-Matrix Multiplication with FP32 tensors, a, b, c using CBLAS\n \/\/ interface. c = op(a) * op(b)\n \/\/\n \/\/ @param transa Specifies the form of op(a) used in MatMul. If transa is\n \/\/ true, then op(a) = a^T, otherwise op(a) = a\n \/\/\n \/\/ @param transb Specifies the form of op(b) used in MatMul. If transb is\n \/\/ true, then op(b) = b^T, otherwise op(b) = b\n \/\/\n \/\/ @param m Specifies the number of rows of the matrix op(a) and of the\n \/\/ matrix c. The value of m must be at least zero.\n \/\/\n \/\/ @param n Specifies the number of columns of the matrix op(b) and the\n \/\/ number of columns of the matrix c. The value of n must be at least zero.\n \/\/\n \/\/ @param k Specifies the number of columns of the matrix op(a) and the\n \/\/ number of rows of the matrix op(b)\n \/\/\n \/\/ @param a Address of matrix a\n \/\/\n \/\/ @param lda Leading dimension of 'a' matrix. This is set at calling site\n \/\/ depending on transa parameter. Since TF uses row-major\n \/\/ layout, leading dimension is the stride between consecutive rows\n \/\/ lda = max(1,k) when transa is false, otherwise lda = max(1,m)\n \/\/\n \/\/ @param b Address of matrix b\n \/\/\n \/\/ @param ldb Leading dimension of 'b' matrix. This is set at calling site\n \/\/ depending on transb parameter. Since TF uses row-major\n \/\/ layout, leading dimension is the stride between consecutive rows\n \/\/ ldb = max(1,n) when transb is false, otherwise ldb = max(1,k)\n \/\/\n \/\/ @param c Address of matrix c\n \/\/\n \/\/ @param ldc Leading dimension of 'c' matrix. Since TF uses row-major\n \/\/ layout, leading dimension is the stride between consecutive rows, max(1,n)\n \/\/\n \/\/ --------------------------------------------------------------------------\n void MklBlasGemm(bool transa, bool transb, const int m, const int n,\n const int k, const float* a, const int lda, const float* b,\n const int ldb, float* c, const int ldc) {\n \/\/ BLAS GEMM API defines Matrix Multiplication as c = alpha * op(a) * op(b)\n \/\/ + beta * c.\n \/\/ Since TF MatMul does not have parameters for alpha, beta, we set them to\n \/\/ 1.0 and 0.0 respectively.\n const float alpha = 1.0f;\n const float beta = 0.0f;\n#if defined(DO_NOT_USE_ML)\n const char* const ftrans[] = { \"N\", \"T\", \"C\"};\n int index_transa = transa? 1 : 0 ;\n int index_transb = transb? 1 : 0 ;\n VLOG(2) << \"MKL DNN SGEMM called\";\n \/\/Using the fortran api of mkldnn\n \/\/Since TF is in row major layout,reversing the order of A and B\n mkldnn_sgemm(ftrans[index_transb], ftrans[index_transa],\n &n, &m, &k, &alpha, b, &ldb, a, &lda, &beta, c, &ldc);\n#else\n cblas_sgemm(CblasRowMajor, transa ? CblasTrans : CblasNoTrans,\n transb ? CblasTrans : CblasNoTrans, m, n, k, alpha, a, lda, b,\n ldb, beta, c, ldc);\n#endif\n }\n\n \/\/ MKLDNN only supports SGEMM\n#ifndef DO_NOT_USE_ML\n\n \/\/ Matrix-Matrix Multiplication with FP64 tensors. For detailed info about\n \/\/ parameters, look at FP32 function description.\n void MklBlasGemm(bool transa, bool transb, const int m, const int n,\n const int k, const double* a, const int lda, const double* b,\n const int ldb, double* c, const int ldc) {\n const double alpha = 1.0;\n const double beta = 0.0;\n cblas_dgemm(CblasRowMajor, transa ? CblasTrans : CblasNoTrans,\n transb ? CblasTrans : CblasNoTrans, m, n, k, alpha, a, lda, b,\n ldb, beta, c, ldc);\n }\n\n \/\/ Matrix-Matrix Multiplication with Complex64 (std::complex) tensors.\n \/\/ For detailed info about parameters, look at FP32 function description.\n void MklBlasGemm(bool transa, bool transb, const int m, const int n,\n const int k, const complex64* a, const int lda,\n const complex64* b, const int ldb, complex64* c,\n int const ldc) {\n const MKL_Complex8 alpha = {1.0f, 0.0f};\n const MKL_Complex8 beta = {0.0f, 0.0f};\n cblas_cgemm(CblasRowMajor, transa ? CblasTrans : CblasNoTrans,\n transb ? CblasTrans : CblasNoTrans, m, n, k, &alpha,\n reinterpret_cast(a), lda,\n reinterpret_cast(b), ldb, &beta,\n reinterpret_cast(c), ldc);\n }\n\n \/\/ Matrix-Matrix Multiplication with Complex128 (std::complex)\n \/\/ tensors. For detailed info about parameters, look at FP32 function\n \/\/ description.\n void MklBlasGemm(bool transa, bool transb, const int m, const int n,\n const int k, const complex128* a, const int lda,\n const complex128* b, const int ldb, complex128* c,\n const int ldc) {\n const MKL_Complex16 alpha = {1.0, 0.0};\n const MKL_Complex16 beta = {0.0, 0.0};\n cblas_zgemm(CblasRowMajor, transa ? CblasTrans : CblasNoTrans,\n transb ? CblasTrans : CblasNoTrans, m, n, k, &alpha,\n reinterpret_cast(a), lda,\n reinterpret_cast(b), ldb, &beta,\n reinterpret_cast(c), ldc);\n }\n#endif\n};\n\n#define REGISTER_CPU(T) \\\n REGISTER_KERNEL_BUILDER( \\\n Name(\"MatMul\").Device(DEVICE_CPU).TypeConstraint(\"T\"), \\\n MklMatMulOp);\n\n\/\/ TODO(inteltf) Consider template specialization when adding\/removing\n\/\/ additional types\nTF_CALL_float(REGISTER_CPU);\n\n#ifndef DO_NOT_USE_ML\nTF_CALL_double(REGISTER_CPU);\nTF_CALL_complex64(REGISTER_CPU);\nTF_CALL_complex128(REGISTER_CPU);\n#endif\n\n} \/\/ namespace tensorflow\n#endif \/\/ INTEL_MKL\n<|endoftext|>"} {"text":"\/* Copyright 2016 The TensorFlow Authors. All Rights Reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n==============================================================================*\/\n\n#include \"tensorflow\/core\/framework\/op_kernel.h\"\n#include \"tensorflow\/core\/framework\/register_types.h\"\n#include \"tensorflow\/core\/framework\/tensor.h\"\n#include \"tensorflow\/core\/framework\/tensor_util.h\"\n#include \"tensorflow\/core\/framework\/types.h\"\n#include \"tensorflow\/core\/util\/sparse\/sparse_tensor.h\"\n\nnamespace tensorflow {\n\ntemplate \nclass SparseAddOp : public OpKernel {\n public:\n explicit SparseAddOp(OpKernelConstruction *ctx) : OpKernel(ctx) {}\n\n void Compute(OpKernelContext *ctx) override {\n \/\/ (0) validations\n const Tensor *a_indices, *b_indices, *a_values_t, *b_values_t, *a_shape,\n *b_shape, *thresh_t;\n\n OP_REQUIRES_OK(ctx, ctx->input(\"a_indices\", &a_indices));\n OP_REQUIRES_OK(ctx, ctx->input(\"b_indices\", &b_indices));\n OP_REQUIRES(ctx,\n TensorShapeUtils::IsMatrix(a_indices->shape()) &&\n TensorShapeUtils::IsMatrix(b_indices->shape()),\n errors::InvalidArgument(\n \"Input indices should be matrices but received shapes: \",\n a_indices->shape().DebugString(), \" and \",\n b_indices->shape().DebugString()));\n const int64 a_nnz = a_indices->dim_size(0);\n const int64 b_nnz = b_indices->dim_size(0);\n\n OP_REQUIRES_OK(ctx, ctx->input(\"a_values\", &a_values_t));\n OP_REQUIRES_OK(ctx, ctx->input(\"b_values\", &b_values_t));\n\n OP_REQUIRES(ctx,\n TensorShapeUtils::IsVector(a_values_t->shape()) &&\n TensorShapeUtils::IsVector(b_values_t->shape()),\n errors::InvalidArgument(\n \"Input values should be vectors but received shapes: \",\n a_values_t->shape().DebugString(), \" and \",\n b_values_t->shape().DebugString()));\n auto a_values = ctx->input(1).vec();\n auto b_values = ctx->input(4).vec();\n OP_REQUIRES(\n ctx, a_values.size() == a_nnz && b_values.size() == b_nnz,\n errors::InvalidArgument(\"Expected \", a_nnz, \" and \", b_nnz,\n \" non-empty input values, got \",\n a_values.size(), \" and \", b_values.size()));\n\n OP_REQUIRES_OK(ctx, ctx->input(\"a_shape\", &a_shape));\n OP_REQUIRES_OK(ctx, ctx->input(\"b_shape\", &b_shape));\n OP_REQUIRES(ctx,\n TensorShapeUtils::IsVector(a_shape->shape()) &&\n TensorShapeUtils::IsVector(b_shape->shape()),\n errors::InvalidArgument(\n \"Input shapes should be a vector but received shapes \",\n a_shape->shape().DebugString(), \" and \",\n b_shape->shape().DebugString()));\n OP_REQUIRES(\n ctx, a_shape->IsSameSize(*b_shape),\n errors::InvalidArgument(\n \"Operands do not have the same ranks; got shapes: \",\n a_shape->SummarizeValue(10), \" and \", b_shape->SummarizeValue(10)));\n const auto a_shape_flat = a_shape->flat();\n const auto b_shape_flat = b_shape->flat();\n for (int i = 0; i < a_shape->NumElements(); ++i) {\n OP_REQUIRES(ctx, a_shape_flat(i) == b_shape_flat(i),\n errors::InvalidArgument(\n \"Operands' shapes do not match: got \", a_shape_flat(i),\n \" and \", b_shape_flat(i), \" for dimension \", i));\n }\n\n OP_REQUIRES_OK(ctx, ctx->input(\"thresh\", &thresh_t));\n OP_REQUIRES(ctx, TensorShapeUtils::IsScalar(thresh_t->shape()),\n errors::InvalidArgument(\n \"The magnitude threshold must be a scalar: got shape \",\n thresh_t->shape().DebugString()));\n \/\/ std::abs() so that it works for complex{64,128} values as well\n const Treal thresh = thresh_t->scalar()();\n\n \/\/ (1) do a pass over inputs, and append values and indices to vectors\n auto a_indices_mat = a_indices->matrix();\n auto b_indices_mat = b_indices->matrix();\n std::vector> entries_to_copy; \/\/ from_a?, idx\n entries_to_copy.reserve(a_nnz + b_nnz);\n std::vector out_values;\n const int num_dims = a_shape->dim_size(0);\n\n \/\/ The input and output sparse tensors are assumed to be ordered along\n \/\/ increasing dimension number.\n int64 i = 0, j = 0;\n T s;\n while (i < a_nnz && j < b_nnz) {\n switch (sparse::DimComparator::cmp(a_indices_mat, b_indices_mat, i, j,\n num_dims)) {\n case -1:\n entries_to_copy.emplace_back(true, i);\n out_values.push_back(a_values(i));\n ++i;\n break;\n case 0:\n s = a_values(i) + b_values(j);\n if (thresh <= std::abs(s)) {\n entries_to_copy.emplace_back(true, i);\n out_values.push_back(s);\n }\n ++i;\n ++j;\n break;\n case 1:\n entries_to_copy.emplace_back(false, j);\n out_values.push_back(b_values(j));\n ++j;\n break;\n }\n }\n\n#define HANDLE_LEFTOVERS(A_OR_B, IDX, IS_A) \\\n while (IDX < A_OR_B##_nnz) { \\\n entries_to_copy.emplace_back(IS_A, IDX); \\\n out_values.push_back(A_OR_B##_values(IDX)); \\\n ++IDX; \\\n }\n\n \/\/ at most one of these calls appends new values\n HANDLE_LEFTOVERS(a, i, true);\n HANDLE_LEFTOVERS(b, j, false);\n#undef HANDLE_LEFTOVERS\n\n \/\/ (2) allocate and fill output tensors\n const int64 sum_nnz = out_values.size();\n Tensor *out_indices_t, *out_values_t;\n OP_REQUIRES_OK(ctx,\n ctx->allocate_output(0, TensorShape({sum_nnz, num_dims}),\n &out_indices_t));\n OP_REQUIRES_OK(\n ctx, ctx->allocate_output(1, TensorShape({sum_nnz}), &out_values_t));\n auto out_indices_mat = out_indices_t->matrix();\n auto out_values_flat = out_values_t->vec();\n\n for (i = 0; i < sum_nnz; ++i) {\n const bool from_a = entries_to_copy[i].first;\n const int64 idx = entries_to_copy[i].second;\n out_indices_mat.chip<0>(i) =\n from_a ? a_indices_mat.chip<0>(idx) : b_indices_mat.chip<0>(idx);\n }\n std::copy_n(out_values.begin(), sum_nnz, &out_values_flat(0));\n ctx->set_output(2, *a_shape);\n }\n};\n\n#define REGISTER_KERNELS(type, thresh_type) \\\n REGISTER_KERNEL_BUILDER( \\\n Name(\"SparseAdd\").Device(DEVICE_CPU).TypeConstraint(\"T\"), \\\n SparseAddOp)\n\n\/\/ The list below is equivalent to TF_CALL_REAL_NUMBER_TYPES, minus uint8. This\n\/\/ is because std::abs() on uint8 does not compile.\nREGISTER_KERNELS(float, float);\nREGISTER_KERNELS(double, double);\nREGISTER_KERNELS(int64, int64);\nREGISTER_KERNELS(int32, int32);\nREGISTER_KERNELS(int16, int16);\nREGISTER_KERNELS(int8, int8);\nREGISTER_KERNELS(complex64, float);\nREGISTER_KERNELS(complex128, double);\n#undef REGISTER_KERNELS\n} \/\/ namespace tensorflow\nFixing nondeterministic nullptr access.\/* Copyright 2016 The TensorFlow Authors. All Rights Reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n==============================================================================*\/\n\n#include \"tensorflow\/core\/framework\/op_kernel.h\"\n#include \"tensorflow\/core\/framework\/register_types.h\"\n#include \"tensorflow\/core\/framework\/tensor.h\"\n#include \"tensorflow\/core\/framework\/tensor_util.h\"\n#include \"tensorflow\/core\/framework\/types.h\"\n#include \"tensorflow\/core\/util\/sparse\/sparse_tensor.h\"\n\nnamespace tensorflow {\n\ntemplate \nclass SparseAddOp : public OpKernel {\n public:\n explicit SparseAddOp(OpKernelConstruction *ctx) : OpKernel(ctx) {}\n\n void Compute(OpKernelContext *ctx) override {\n \/\/ (0) validations\n const Tensor *a_indices, *b_indices, *a_values_t, *b_values_t, *a_shape,\n *b_shape, *thresh_t;\n\n OP_REQUIRES_OK(ctx, ctx->input(\"a_indices\", &a_indices));\n OP_REQUIRES_OK(ctx, ctx->input(\"b_indices\", &b_indices));\n OP_REQUIRES(ctx,\n TensorShapeUtils::IsMatrix(a_indices->shape()) &&\n TensorShapeUtils::IsMatrix(b_indices->shape()),\n errors::InvalidArgument(\n \"Input indices should be matrices but received shapes: \",\n a_indices->shape().DebugString(), \" and \",\n b_indices->shape().DebugString()));\n const int64 a_nnz = a_indices->dim_size(0);\n const int64 b_nnz = b_indices->dim_size(0);\n\n OP_REQUIRES_OK(ctx, ctx->input(\"a_values\", &a_values_t));\n OP_REQUIRES_OK(ctx, ctx->input(\"b_values\", &b_values_t));\n\n OP_REQUIRES(ctx,\n TensorShapeUtils::IsVector(a_values_t->shape()) &&\n TensorShapeUtils::IsVector(b_values_t->shape()),\n errors::InvalidArgument(\n \"Input values should be vectors but received shapes: \",\n a_values_t->shape().DebugString(), \" and \",\n b_values_t->shape().DebugString()));\n auto a_values = ctx->input(1).vec();\n auto b_values = ctx->input(4).vec();\n OP_REQUIRES(\n ctx, a_values.size() == a_nnz && b_values.size() == b_nnz,\n errors::InvalidArgument(\"Expected \", a_nnz, \" and \", b_nnz,\n \" non-empty input values, got \",\n a_values.size(), \" and \", b_values.size()));\n\n OP_REQUIRES_OK(ctx, ctx->input(\"a_shape\", &a_shape));\n OP_REQUIRES_OK(ctx, ctx->input(\"b_shape\", &b_shape));\n OP_REQUIRES(ctx,\n TensorShapeUtils::IsVector(a_shape->shape()) &&\n TensorShapeUtils::IsVector(b_shape->shape()),\n errors::InvalidArgument(\n \"Input shapes should be a vector but received shapes \",\n a_shape->shape().DebugString(), \" and \",\n b_shape->shape().DebugString()));\n OP_REQUIRES(\n ctx, a_shape->IsSameSize(*b_shape),\n errors::InvalidArgument(\n \"Operands do not have the same ranks; got shapes: \",\n a_shape->SummarizeValue(10), \" and \", b_shape->SummarizeValue(10)));\n const auto a_shape_flat = a_shape->flat();\n const auto b_shape_flat = b_shape->flat();\n for (int i = 0; i < a_shape->NumElements(); ++i) {\n OP_REQUIRES(ctx, a_shape_flat(i) == b_shape_flat(i),\n errors::InvalidArgument(\n \"Operands' shapes do not match: got \", a_shape_flat(i),\n \" and \", b_shape_flat(i), \" for dimension \", i));\n }\n\n OP_REQUIRES_OK(ctx, ctx->input(\"thresh\", &thresh_t));\n OP_REQUIRES(ctx, TensorShapeUtils::IsScalar(thresh_t->shape()),\n errors::InvalidArgument(\n \"The magnitude threshold must be a scalar: got shape \",\n thresh_t->shape().DebugString()));\n \/\/ std::abs() so that it works for complex{64,128} values as well\n const Treal thresh = thresh_t->scalar()();\n\n \/\/ (1) do a pass over inputs, and append values and indices to vectors\n auto a_indices_mat = a_indices->matrix();\n auto b_indices_mat = b_indices->matrix();\n std::vector> entries_to_copy; \/\/ from_a?, idx\n entries_to_copy.reserve(a_nnz + b_nnz);\n std::vector out_values;\n const int num_dims = a_shape->dim_size(0);\n\n \/\/ The input and output sparse tensors are assumed to be ordered along\n \/\/ increasing dimension number.\n int64 i = 0, j = 0;\n T s;\n while (i < a_nnz && j < b_nnz) {\n switch (sparse::DimComparator::cmp(a_indices_mat, b_indices_mat, i, j,\n num_dims)) {\n case -1:\n entries_to_copy.emplace_back(true, i);\n out_values.push_back(a_values(i));\n ++i;\n break;\n case 0:\n s = a_values(i) + b_values(j);\n if (thresh <= std::abs(s)) {\n entries_to_copy.emplace_back(true, i);\n out_values.push_back(s);\n }\n ++i;\n ++j;\n break;\n case 1:\n entries_to_copy.emplace_back(false, j);\n out_values.push_back(b_values(j));\n ++j;\n break;\n }\n }\n\n#define HANDLE_LEFTOVERS(A_OR_B, IDX, IS_A) \\\n while (IDX < A_OR_B##_nnz) { \\\n entries_to_copy.emplace_back(IS_A, IDX); \\\n out_values.push_back(A_OR_B##_values(IDX)); \\\n ++IDX; \\\n }\n\n \/\/ at most one of these calls appends new values\n HANDLE_LEFTOVERS(a, i, true);\n HANDLE_LEFTOVERS(b, j, false);\n#undef HANDLE_LEFTOVERS\n\n \/\/ (2) allocate and fill output tensors\n const int64 sum_nnz = out_values.size();\n Tensor *out_indices_t, *out_values_t;\n OP_REQUIRES_OK(ctx,\n ctx->allocate_output(0, TensorShape({sum_nnz, num_dims}),\n &out_indices_t));\n OP_REQUIRES_OK(\n ctx, ctx->allocate_output(1, TensorShape({sum_nnz}), &out_values_t));\n auto out_indices_mat = out_indices_t->matrix();\n auto out_values_flat = out_values_t->vec();\n\n for (i = 0; i < sum_nnz; ++i) {\n const bool from_a = entries_to_copy[i].first;\n const int64 idx = entries_to_copy[i].second;\n out_indices_mat.chip<0>(i) =\n from_a ? a_indices_mat.chip<0>(idx) : b_indices_mat.chip<0>(idx);\n }\n if (sum_nnz > 0) {\n std::copy_n(out_values.begin(), sum_nnz, &out_values_flat(0));\n }\n ctx->set_output(2, *a_shape);\n }\n};\n\n#define REGISTER_KERNELS(type, thresh_type) \\\n REGISTER_KERNEL_BUILDER( \\\n Name(\"SparseAdd\").Device(DEVICE_CPU).TypeConstraint(\"T\"), \\\n SparseAddOp)\n\n\/\/ The list below is equivalent to TF_CALL_REAL_NUMBER_TYPES, minus uint8. This\n\/\/ is because std::abs() on uint8 does not compile.\nREGISTER_KERNELS(float, float);\nREGISTER_KERNELS(double, double);\nREGISTER_KERNELS(int64, int64);\nREGISTER_KERNELS(int32, int32);\nREGISTER_KERNELS(int16, int16);\nREGISTER_KERNELS(int8, int8);\nREGISTER_KERNELS(complex64, float);\nREGISTER_KERNELS(complex128, double);\n#undef REGISTER_KERNELS\n} \/\/ namespace tensorflow\n<|endoftext|>"} {"text":"\/\/ Copyright by Contributors\n#include \n\n#include \"..\/helpers.h\"\n\nTEST(Objective, LinearRegressionGPair) {\n xgboost::ObjFunction * obj = xgboost::ObjFunction::Create(\"reg:linear\");\n std::vector > args;\n obj->Configure(args);\n CheckObjFunction(obj,\n {0, 0.1, 0.9, 1, 0, 0.1, 0.9, 1},\n {0, 0, 0, 0, 1, 1, 1, 1},\n {1, 1, 1, 1, 1, 1, 1, 1},\n {0, 0.1, 0.9, 1.0, -1.0, -0.9, -0.1, 0},\n {1, 1, 1, 1, 1, 1, 1, 1});\n\n ASSERT_NO_THROW(obj->DefaultEvalMetric());\n}\n\nTEST(Objective, LogisticRegressionGPair) {\n xgboost::ObjFunction * obj = xgboost::ObjFunction::Create(\"reg:logistic\");\n std::vector > args;\n obj->Configure(args);\n CheckObjFunction(obj,\n { 0, 0.1, 0.9, 1, 0, 0.1, 0.9, 1},\n { 0, 0, 0, 0, 1, 1, 1, 1},\n { 1, 1, 1, 1, 1, 1, 1, 1},\n { 0.5, 0.52, 0.71, 0.73, -0.5, -0.47, -0.28, -0.26},\n {0.25, 0.24, 0.20, 0.19, 0.25, 0.24, 0.20, 0.19});\n}\n\nTEST(Objective, LogisticRegressionBasic) {\n xgboost::ObjFunction * obj = xgboost::ObjFunction::Create(\"reg:logistic\");\n std::vector > args;\n obj->Configure(args);\n\n \/\/ test label validation\n EXPECT_ANY_THROW(CheckObjFunction(obj, {0}, {10}, {1}, {0}, {0}))\n << \"Expected error when label not in range [0,1] for LogisticRegression\";\n\n \/\/ test ProbToMargin\n EXPECT_NEAR(obj->ProbToMargin(0.1), -2.197, 0.01);\n EXPECT_NEAR(obj->ProbToMargin(0.5), 0, 0.01);\n EXPECT_NEAR(obj->ProbToMargin(0.9), 2.197, 0.01);\n EXPECT_ANY_THROW(obj->ProbToMargin(10))\n << \"Expected error when base_score not in range [0,1] for LogisticRegression\";\n\n \/\/ test PredTransform\n std::vector preds = {0, 0.1, 0.5, 0.9, 1};\n std::vector out_preds = {0.5, 0.524, 0.622, 0.710, 0.731};\n obj->PredTransform(&preds);\n for (int i = 0; i < preds.size(); ++i) {\n EXPECT_NEAR(preds[i], out_preds[i], 0.01);\n }\n}\n\nTEST(Objective, LogisticRawGPair) {\n xgboost::ObjFunction * obj = xgboost::ObjFunction::Create(\"binary:logitraw\");\n std::vector > args;\n obj->Configure(args);\n CheckObjFunction(obj,\n { 0, 0.1, 0.9, 1, 0, 0.1, 0.9, 1},\n { 0, 0, 0, 0, 1, 1, 1, 1},\n { 1, 1, 1, 1, 1, 1, 1, 1},\n { 0.5, 0.52, 0.71, 0.73, -0.5, -0.47, -0.28, -0.26},\n {0.25, 0.24, 0.20, 0.19, 0.25, 0.24, 0.20, 0.19});\n}\n\nTEST(Objective, PoissonRegressionGPair) {\n xgboost::ObjFunction * obj = xgboost::ObjFunction::Create(\"count:poisson\");\n std::vector > args;\n args.push_back(std::make_pair(\"max_delta_step\", \"0.1\"));\n obj->Configure(args);\n CheckObjFunction(obj,\n { 0, 0.1, 0.9, 1, 0, 0.1, 0.9, 1},\n { 0, 0, 0, 0, 1, 1, 1, 1},\n { 1, 1, 1, 1, 1, 1, 1, 1},\n { 1, 1.10, 2.45, 2.71, 0, 0.10, 1.45, 1.71},\n {1.10, 1.22, 2.71, 3.00, 1.10, 1.22, 2.71, 3.00});\n}\n\nTEST(Objective, PoissonRegressionBasic) {\n xgboost::ObjFunction * obj = xgboost::ObjFunction::Create(\"count:poisson\");\n std::vector > args;\n obj->Configure(args);\n\n \/\/ test label validation\n EXPECT_ANY_THROW(CheckObjFunction(obj, {0}, {-1}, {1}, {0}, {0}))\n << \"Expected error when label < 0 for PoissonRegression\";\n\n \/\/ test ProbToMargin\n EXPECT_NEAR(obj->ProbToMargin(0.1), -2.30, 0.01);\n EXPECT_NEAR(obj->ProbToMargin(0.5), -0.69, 0.01);\n EXPECT_NEAR(obj->ProbToMargin(0.9), -0.10, 0.01);\n\n \/\/ test PredTransform\n std::vector preds = {0, 0.1, 0.5, 0.9, 1};\n std::vector out_preds = {1, 1.10, 1.64, 2.45, 2.71};\n obj->PredTransform(&preds);\n for (int i = 0; i < preds.size(); ++i) {\n EXPECT_NEAR(preds[i], out_preds[i], 0.01);\n }\n}\ntests\/cpp: Add tests for GammaRegression\/\/ Copyright by Contributors\n#include \n\n#include \"..\/helpers.h\"\n\nTEST(Objective, LinearRegressionGPair) {\n xgboost::ObjFunction * obj = xgboost::ObjFunction::Create(\"reg:linear\");\n std::vector > args;\n obj->Configure(args);\n CheckObjFunction(obj,\n {0, 0.1, 0.9, 1, 0, 0.1, 0.9, 1},\n {0, 0, 0, 0, 1, 1, 1, 1},\n {1, 1, 1, 1, 1, 1, 1, 1},\n {0, 0.1, 0.9, 1.0, -1.0, -0.9, -0.1, 0},\n {1, 1, 1, 1, 1, 1, 1, 1});\n\n ASSERT_NO_THROW(obj->DefaultEvalMetric());\n}\n\nTEST(Objective, LogisticRegressionGPair) {\n xgboost::ObjFunction * obj = xgboost::ObjFunction::Create(\"reg:logistic\");\n std::vector > args;\n obj->Configure(args);\n CheckObjFunction(obj,\n { 0, 0.1, 0.9, 1, 0, 0.1, 0.9, 1},\n { 0, 0, 0, 0, 1, 1, 1, 1},\n { 1, 1, 1, 1, 1, 1, 1, 1},\n { 0.5, 0.52, 0.71, 0.73, -0.5, -0.47, -0.28, -0.26},\n {0.25, 0.24, 0.20, 0.19, 0.25, 0.24, 0.20, 0.19});\n}\n\nTEST(Objective, LogisticRegressionBasic) {\n xgboost::ObjFunction * obj = xgboost::ObjFunction::Create(\"reg:logistic\");\n std::vector > args;\n obj->Configure(args);\n\n \/\/ test label validation\n EXPECT_ANY_THROW(CheckObjFunction(obj, {0}, {10}, {1}, {0}, {0}))\n << \"Expected error when label not in range [0,1] for LogisticRegression\";\n\n \/\/ test ProbToMargin\n EXPECT_NEAR(obj->ProbToMargin(0.1), -2.197, 0.01);\n EXPECT_NEAR(obj->ProbToMargin(0.5), 0, 0.01);\n EXPECT_NEAR(obj->ProbToMargin(0.9), 2.197, 0.01);\n EXPECT_ANY_THROW(obj->ProbToMargin(10))\n << \"Expected error when base_score not in range [0,1] for LogisticRegression\";\n\n \/\/ test PredTransform\n std::vector preds = {0, 0.1, 0.5, 0.9, 1};\n std::vector out_preds = {0.5, 0.524, 0.622, 0.710, 0.731};\n obj->PredTransform(&preds);\n for (int i = 0; i < preds.size(); ++i) {\n EXPECT_NEAR(preds[i], out_preds[i], 0.01);\n }\n}\n\nTEST(Objective, LogisticRawGPair) {\n xgboost::ObjFunction * obj = xgboost::ObjFunction::Create(\"binary:logitraw\");\n std::vector > args;\n obj->Configure(args);\n CheckObjFunction(obj,\n { 0, 0.1, 0.9, 1, 0, 0.1, 0.9, 1},\n { 0, 0, 0, 0, 1, 1, 1, 1},\n { 1, 1, 1, 1, 1, 1, 1, 1},\n { 0.5, 0.52, 0.71, 0.73, -0.5, -0.47, -0.28, -0.26},\n {0.25, 0.24, 0.20, 0.19, 0.25, 0.24, 0.20, 0.19});\n}\n\nTEST(Objective, PoissonRegressionGPair) {\n xgboost::ObjFunction * obj = xgboost::ObjFunction::Create(\"count:poisson\");\n std::vector > args;\n args.push_back(std::make_pair(\"max_delta_step\", \"0.1\"));\n obj->Configure(args);\n CheckObjFunction(obj,\n { 0, 0.1, 0.9, 1, 0, 0.1, 0.9, 1},\n { 0, 0, 0, 0, 1, 1, 1, 1},\n { 1, 1, 1, 1, 1, 1, 1, 1},\n { 1, 1.10, 2.45, 2.71, 0, 0.10, 1.45, 1.71},\n {1.10, 1.22, 2.71, 3.00, 1.10, 1.22, 2.71, 3.00});\n}\n\nTEST(Objective, PoissonRegressionBasic) {\n xgboost::ObjFunction * obj = xgboost::ObjFunction::Create(\"count:poisson\");\n std::vector > args;\n obj->Configure(args);\n\n \/\/ test label validation\n EXPECT_ANY_THROW(CheckObjFunction(obj, {0}, {-1}, {1}, {0}, {0}))\n << \"Expected error when label < 0 for PoissonRegression\";\n\n \/\/ test ProbToMargin\n EXPECT_NEAR(obj->ProbToMargin(0.1), -2.30, 0.01);\n EXPECT_NEAR(obj->ProbToMargin(0.5), -0.69, 0.01);\n EXPECT_NEAR(obj->ProbToMargin(0.9), -0.10, 0.01);\n\n \/\/ test PredTransform\n std::vector preds = {0, 0.1, 0.5, 0.9, 1};\n std::vector out_preds = {1, 1.10, 1.64, 2.45, 2.71};\n obj->PredTransform(&preds);\n for (int i = 0; i < preds.size(); ++i) {\n EXPECT_NEAR(preds[i], out_preds[i], 0.01);\n }\n}\n\nTEST(Objective, GammaRegressionGPair) {\n xgboost::ObjFunction * obj = xgboost::ObjFunction::Create(\"reg:gamma\");\n std::vector > args;\n obj->Configure(args);\n CheckObjFunction(obj,\n {0, 0.1, 0.9, 1, 0, 0.1, 0.9, 1},\n {0, 0, 0, 0, 1, 1, 1, 1},\n {1, 1, 1, 1, 1, 1, 1, 1},\n {1, 1, 1, 1, 0, 0.09, 0.59, 0.63},\n {0, 0, 0, 0, 1, 0.90, 0.40, 0.36});\n}\n\nTEST(Objective, GammaRegressionBasic) {\n xgboost::ObjFunction * obj = xgboost::ObjFunction::Create(\"reg:gamma\");\n std::vector > args;\n obj->Configure(args);\n\n \/\/ test label validation\n EXPECT_ANY_THROW(CheckObjFunction(obj, {0}, {-1}, {1}, {0}, {0}))\n << \"Expected error when label < 0 for GammaRegression\";\n\n \/\/ test ProbToMargin\n EXPECT_NEAR(obj->ProbToMargin(0.1), -2.30, 0.01);\n EXPECT_NEAR(obj->ProbToMargin(0.5), -0.69, 0.01);\n EXPECT_NEAR(obj->ProbToMargin(0.9), -0.10, 0.01);\n\n \/\/ test PredTransform\n std::vector preds = {0, 0.1, 0.5, 0.9, 1};\n std::vector out_preds = {1, 1.10, 1.64, 2.45, 2.71};\n obj->PredTransform(&preds);\n for (int i = 0; i < preds.size(); ++i) {\n EXPECT_NEAR(preds[i], out_preds[i], 0.01);\n }\n}\n<|endoftext|>"} {"text":"\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ Peloton\n\/\/\n\/\/ expression_test.cpp\n\/\/\n\/\/ Identification: test\/expression\/expressionutil_test.cpp\n\/\/\n\/\/ Copyright (c) 2015-16, Carnegie Mellon University Database Group\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \n#include \n#include \n#include \n\n#include \"common\/harness.h\"\n#include \"common\/logger.h\"\n\n#include \"type\/value.h\"\n#include \"type\/value_factory.h\"\n#include \"expression\/abstract_expression.h\"\n#include \"expression\/expression_util.h\"\n\nusing ::testing::NotNull;\nusing ::testing::Return;\n\nnamespace peloton {\n\nnamespace test {\n\nclass ExpressionUtilTests : public PelotonTest {};\n\nstd::string CONSTANT_VALUE_STRING1 = \"ABC\";\nstd::string CONSTANT_VALUE_STRING2 = \"XYZ\";\n\nexpression::AbstractExpression* createExpTree() {\n auto exp1 = expression::ExpressionUtil::ConstantValueFactory(\n type::ValueFactory::GetIntegerValue(1));\n auto exp2 = expression::ExpressionUtil::ConstantValueFactory(\n type::ValueFactory::GetIntegerValue(1));\n auto exp3 = expression::ExpressionUtil::ComparisonFactory(\n ExpressionType::COMPARE_EQUAL, exp1, exp2);\n\n auto exp4 = expression::ExpressionUtil::ConstantValueFactory(\n type::ValueFactory::GetVarcharValue(CONSTANT_VALUE_STRING1));\n auto exp5 = expression::ExpressionUtil::ConstantValueFactory(\n type::ValueFactory::GetVarcharValue(CONSTANT_VALUE_STRING2));\n auto exp6 = expression::ExpressionUtil::ComparisonFactory(\n ExpressionType::COMPARE_NOTEQUAL, exp4, exp5);\n\n auto root = expression::ExpressionUtil::ConjunctionFactory(\n ExpressionType::CONJUNCTION_AND, exp3, exp6);\n return (root);\n}\n\n\/\/ Make sure that we can traverse a tree\nTEST_F(ExpressionUtilTests, GetInfoTest) {\n auto root = createExpTree();\n std::string info = expression::ExpressionUtil::GetInfo(root);\n\n \/\/ Just make sure that it has our constant strings\n EXPECT_TRUE(info.size() > 0);\n EXPECT_NE(std::string::npos, info.find(CONSTANT_VALUE_STRING1));\n EXPECT_NE(std::string::npos, info.find(CONSTANT_VALUE_STRING2));\n\n delete root;\n}\n\nTEST_F(ExpressionUtilTests, ExtractJoinColTest) {\n \/\/ Table1.a = Table2.b\n auto expr1 =\n expression::ExpressionUtil::TupleValueFactory(type::Type::INTEGER, 0, 1);\n auto expr2 =\n expression::ExpressionUtil::TupleValueFactory(type::Type::INTEGER, 1, 0);\n auto expr3 = expression::ExpressionUtil::ComparisonFactory(\n ExpressionType::COMPARE_EQUAL, expr1, expr2);\n\n \/\/ Table1.c < Table2.d\n auto expr4 =\n expression::ExpressionUtil::TupleValueFactory(type::Type::INTEGER, 0, 0);\n auto expr5 =\n expression::ExpressionUtil::TupleValueFactory(type::Type::INTEGER, 1, 1);\n auto expr6 = expression::ExpressionUtil::ComparisonFactory(\n ExpressionType::COMPARE_LESSTHAN, expr4, expr5);\n\n \/\/ Table1.a = 3\n auto expr7 =\n expression::ExpressionUtil::TupleValueFactory(type::Type::INTEGER, 0, 1);\n auto expr8 = expression::ExpressionUtil::ConstantValueFactory(\n type::ValueFactory::GetIntegerValue(3));\n auto expr9 = expression::ExpressionUtil::ComparisonFactory(\n ExpressionType::COMPARE_EQUAL, expr7, expr8);\n\n \/\/ Table1.c = Table2.d\n auto expr10 =\n expression::ExpressionUtil::TupleValueFactory(type::Type::INTEGER, 0, 0);\n auto expr11 =\n expression::ExpressionUtil::TupleValueFactory(type::Type::INTEGER, 1, 1);\n auto expr12 = expression::ExpressionUtil::ComparisonFactory(\n ExpressionType::COMPARE_EQUAL, expr10, expr11);\n\n std::vector> l_column_ids,\n r_column_ids;\n \/\/ Table1.a = Table2.b -> nullptr\n auto ret_expr1 = expression::ExpressionUtil::ExtractJoinColumns(\n l_column_ids, r_column_ids, expr3, true);\n EXPECT_EQ(nullptr, ret_expr1);\n EXPECT_EQ(1, l_column_ids.size());\n\n \/\/ (Table1.a = Table2.b) AND (Table1.c < Table2.d) -> (Table1.c < Table2.d)\n auto expr13 = expression::ExpressionUtil::ConjunctionFactory(\n ExpressionType::CONJUNCTION_AND, expr3, expr6);\n l_column_ids.clear();\n r_column_ids.clear();\n auto ret_expr2 = expression::ExpressionUtil::ExtractJoinColumns(\n l_column_ids, r_column_ids, expr13, true);\n\n EXPECT_EQ(ExpressionType::COMPARE_LESSTHAN, ret_expr2->GetExpressionType());\n EXPECT_EQ(ExpressionType::VALUE_TUPLE,\n ret_expr2->GetChild(0)->GetExpressionType());\n EXPECT_EQ(ExpressionType::VALUE_TUPLE,\n ret_expr2->GetChild(1)->GetExpressionType());\n\n EXPECT_EQ(1, l_column_ids.size());\n EXPECT_EQ(1, reinterpret_cast(\n l_column_ids[0].get())->GetColumnId());\n EXPECT_EQ(0, reinterpret_cast(\n r_column_ids[0].get())->GetColumnId());\n\n \/\/ Table1.a = Table2.b\n auto expr14 =\n expression::ExpressionUtil::TupleValueFactory(type::Type::INTEGER, 0, 1);\n auto expr15 =\n expression::ExpressionUtil::TupleValueFactory(type::Type::INTEGER, 1, 0);\n auto expr16 = expression::ExpressionUtil::ComparisonFactory(\n ExpressionType::COMPARE_EQUAL, expr14, expr15);\n \/\/ ((Table1.a = Table2.b AND Table1.c = Table2.d) AND Table1.a = 3) ->\n \/\/ Table1.a = 3\n auto expr17 = expression::ExpressionUtil::ConjunctionFactory(\n ExpressionType::CONJUNCTION_AND, expr16, expr12);\n\n auto expr18 = expression::ExpressionUtil::ConjunctionFactory(\n ExpressionType::CONJUNCTION_AND, expr17, expr9);\n\n l_column_ids.clear();\n r_column_ids.clear();\n auto ret_expr3 = expression::ExpressionUtil::ExtractJoinColumns(\n l_column_ids, r_column_ids, expr18, true);\n\n EXPECT_EQ(2, l_column_ids.size());\n EXPECT_EQ(1, reinterpret_cast(\n l_column_ids[0].get())->GetColumnId());\n EXPECT_EQ(0, reinterpret_cast(\n r_column_ids[0].get())->GetColumnId());\n EXPECT_EQ(0, reinterpret_cast(\n l_column_ids[1].get())->GetColumnId());\n EXPECT_EQ(1, reinterpret_cast(\n r_column_ids[1].get())->GetColumnId());\n\n EXPECT_EQ(ExpressionType::COMPARE_EQUAL, ret_expr3->GetExpressionType());\n EXPECT_EQ(ExpressionType::VALUE_TUPLE,\n ret_expr3->GetChild(0)->GetExpressionType());\n EXPECT_EQ(ExpressionType::VALUE_CONSTANT,\n ret_expr3->GetChild(1)->GetExpressionType());\n\n if (ret_expr1 != nullptr) delete ret_expr1;\n delete ret_expr2;\n delete ret_expr3;\n delete expr18;\n delete expr13;\n}\n} \/\/ namespace test\n} \/\/ namespace peloton\nFix expression_util_test\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ Peloton\n\/\/\n\/\/ expression_test.cpp\n\/\/\n\/\/ Identification: test\/expression\/expressionutil_test.cpp\n\/\/\n\/\/ Copyright (c) 2015-16, Carnegie Mellon University Database Group\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \n#include \n#include \n#include \n\n#include \"common\/harness.h\"\n#include \"common\/logger.h\"\n\n#include \"type\/value.h\"\n#include \"type\/value_factory.h\"\n#include \"expression\/abstract_expression.h\"\n#include \"expression\/expression_util.h\"\n\nusing ::testing::NotNull;\nusing ::testing::Return;\n\nnamespace peloton {\n\nnamespace test {\n\nclass ExpressionUtilTests : public PelotonTest {};\n\nstd::string CONSTANT_VALUE_STRING1 = \"ABC\";\nstd::string CONSTANT_VALUE_STRING2 = \"XYZ\";\n\nexpression::AbstractExpression* createExpTree() {\n auto exp1 = expression::ExpressionUtil::ConstantValueFactory(\n type::ValueFactory::GetIntegerValue(1));\n auto exp2 = expression::ExpressionUtil::ConstantValueFactory(\n type::ValueFactory::GetIntegerValue(1));\n auto exp3 = expression::ExpressionUtil::ComparisonFactory(\n ExpressionType::COMPARE_EQUAL, exp1, exp2);\n\n auto exp4 = expression::ExpressionUtil::ConstantValueFactory(\n type::ValueFactory::GetVarcharValue(CONSTANT_VALUE_STRING1));\n auto exp5 = expression::ExpressionUtil::ConstantValueFactory(\n type::ValueFactory::GetVarcharValue(CONSTANT_VALUE_STRING2));\n auto exp6 = expression::ExpressionUtil::ComparisonFactory(\n ExpressionType::COMPARE_NOTEQUAL, exp4, exp5);\n\n auto root = expression::ExpressionUtil::ConjunctionFactory(\n ExpressionType::CONJUNCTION_AND, exp3, exp6);\n return (root);\n}\n\n\/\/ Make sure that we can traverse a tree\nTEST_F(ExpressionUtilTests, GetInfoTest) {\n auto root = createExpTree();\n std::string info = expression::ExpressionUtil::GetInfo(root);\n\n \/\/ Just make sure that it has our constant strings\n EXPECT_TRUE(info.size() > 0);\n EXPECT_NE(std::string::npos, info.find(CONSTANT_VALUE_STRING1));\n EXPECT_NE(std::string::npos, info.find(CONSTANT_VALUE_STRING2));\n\n delete root;\n}\n\nTEST_F(ExpressionUtilTests, ExtractJoinColTest) {\n \/\/ Table1.a = Table2.b\n auto expr1 =\n expression::ExpressionUtil::TupleValueFactory(type::Type::INTEGER, 0, 1);\n auto expr2 =\n expression::ExpressionUtil::TupleValueFactory(type::Type::INTEGER, 1, 0);\n auto expr3 = expression::ExpressionUtil::ComparisonFactory(\n ExpressionType::COMPARE_EQUAL, expr1, expr2);\n\n \/\/ Table1.c < Table2.d\n auto expr4 =\n expression::ExpressionUtil::TupleValueFactory(type::Type::INTEGER, 0, 0);\n auto expr5 =\n expression::ExpressionUtil::TupleValueFactory(type::Type::INTEGER, 1, 1);\n auto expr6 = expression::ExpressionUtil::ComparisonFactory(\n ExpressionType::COMPARE_LESSTHAN, expr4, expr5);\n\n \/\/ Table1.a = 3\n auto expr7 =\n expression::ExpressionUtil::TupleValueFactory(type::Type::INTEGER, 0, 1);\n auto expr8 = expression::ExpressionUtil::ConstantValueFactory(\n type::ValueFactory::GetIntegerValue(3));\n auto expr9 = expression::ExpressionUtil::ComparisonFactory(\n ExpressionType::COMPARE_EQUAL, expr7, expr8);\n\n \/\/ Table1.c = Table2.d\n auto expr10 =\n expression::ExpressionUtil::TupleValueFactory(type::Type::INTEGER, 0, 0);\n auto expr11 =\n expression::ExpressionUtil::TupleValueFactory(type::Type::INTEGER, 1, 1);\n auto expr12 = expression::ExpressionUtil::ComparisonFactory(\n ExpressionType::COMPARE_EQUAL, expr10, expr11);\n\n std::vector> l_column_ids,\n r_column_ids;\n \/\/ Table1.a = Table2.b -> nullptr\n auto ret_expr1 = expression::ExpressionUtil::ExtractJoinColumns(\n l_column_ids, r_column_ids, expr3);\n EXPECT_EQ(nullptr, ret_expr1);\n EXPECT_EQ(1, l_column_ids.size());\n\n \/\/ (Table1.a = Table2.b) AND (Table1.c < Table2.d) -> (Table1.c < Table2.d)\n auto expr13 = expression::ExpressionUtil::ConjunctionFactory(\n ExpressionType::CONJUNCTION_AND, expr3, expr6);\n l_column_ids.clear();\n r_column_ids.clear();\n auto ret_expr2 = expression::ExpressionUtil::ExtractJoinColumns(\n l_column_ids, r_column_ids, expr13);\n\n EXPECT_EQ(ExpressionType::COMPARE_LESSTHAN, ret_expr2->GetExpressionType());\n EXPECT_EQ(ExpressionType::VALUE_TUPLE,\n ret_expr2->GetChild(0)->GetExpressionType());\n EXPECT_EQ(ExpressionType::VALUE_TUPLE,\n ret_expr2->GetChild(1)->GetExpressionType());\n\n EXPECT_EQ(1, l_column_ids.size());\n EXPECT_EQ(1, reinterpret_cast(\n l_column_ids[0].get())->GetColumnId());\n EXPECT_EQ(0, reinterpret_cast(\n r_column_ids[0].get())->GetColumnId());\n\n \/\/ Table1.a = Table2.b\n auto expr14 =\n expression::ExpressionUtil::TupleValueFactory(type::Type::INTEGER, 0, 1);\n auto expr15 =\n expression::ExpressionUtil::TupleValueFactory(type::Type::INTEGER, 1, 0);\n auto expr16 = expression::ExpressionUtil::ComparisonFactory(\n ExpressionType::COMPARE_EQUAL, expr14, expr15);\n \/\/ ((Table1.a = Table2.b AND Table1.c = Table2.d) AND Table1.a = 3) ->\n \/\/ Table1.a = 3\n auto expr17 = expression::ExpressionUtil::ConjunctionFactory(\n ExpressionType::CONJUNCTION_AND, expr16, expr12);\n\n auto expr18 = expression::ExpressionUtil::ConjunctionFactory(\n ExpressionType::CONJUNCTION_AND, expr17, expr9);\n\n l_column_ids.clear();\n r_column_ids.clear();\n auto ret_expr3 = expression::ExpressionUtil::ExtractJoinColumns(\n l_column_ids, r_column_ids, expr18);\n\n EXPECT_EQ(2, l_column_ids.size());\n EXPECT_EQ(1, reinterpret_cast(\n l_column_ids[0].get())->GetColumnId());\n EXPECT_EQ(0, reinterpret_cast(\n r_column_ids[0].get())->GetColumnId());\n EXPECT_EQ(0, reinterpret_cast(\n l_column_ids[1].get())->GetColumnId());\n EXPECT_EQ(1, reinterpret_cast(\n r_column_ids[1].get())->GetColumnId());\n\n EXPECT_EQ(ExpressionType::COMPARE_EQUAL, ret_expr3->GetExpressionType());\n EXPECT_EQ(ExpressionType::VALUE_TUPLE,\n ret_expr3->GetChild(0)->GetExpressionType());\n EXPECT_EQ(ExpressionType::VALUE_CONSTANT,\n ret_expr3->GetChild(1)->GetExpressionType());\n\n if (ret_expr1 != nullptr) delete ret_expr1;\n delete ret_expr2;\n delete ret_expr3;\n delete expr18;\n delete expr13;\n}\n} \/\/ namespace test\n} \/\/ namespace peloton\n<|endoftext|>"} {"text":"#ifndef DOMLSParserFilter_HEADER_GUARD_\n#define DOMLSParserFilter_HEADER_GUARD_\n\n\/*\n * Copyright 2002,2004 The Apache Software Foundation.\n * \n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * \n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n * \n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n\/*\n * $Id$\n *\/\n\n\/**\n *\n * DOMLSParserFilter.hpp: interface for the DOMLSParserFilter class.\n *\n * DOMLSParserFilter provide applications the ability to examine nodes\n * as they are being created during the parse process.\n *\n * DOMLSParserFilter lets the application decide what nodes should be\n * in the output DOM tree or not.\n *\n * @since DOM Level 3\n *\/\n\n\nXERCES_CPP_NAMESPACE_BEGIN\n\n\nclass CDOM_EXPORT DOMLSParserFilter {\nprotected:\n \/\/ -----------------------------------------------------------------------\n \/\/ Hidden constructors\n \/\/ -----------------------------------------------------------------------\n \/** @name Hidden constructors *\/\n \/\/@{ \n DOMLSParserFilter() {};\n \/\/@}\n\nprivate:\n \/\/ -----------------------------------------------------------------------\n \/\/ Unimplemented constructors and operators\n \/\/ -----------------------------------------------------------------------\n \/** @name Unimplemented constructors and operators *\/\n \/\/@{\n DOMLSParserFilter(const DOMLSParserFilter &);\n DOMLSParserFilter & operator = (const DOMLSParserFilter &);\n \/\/@}\n\n\npublic:\n \/\/ -----------------------------------------------------------------------\n \/\/ All constructors are hidden, just the destructor is available\n \/\/ -----------------------------------------------------------------------\n \/** @name Destructor *\/\n \/\/@{\n \/**\n * Destructor\n *\n *\/\n virtual ~DOMLSParserFilter() {};\n \/\/@}\n\n \/\/ -----------------------------------------------------------------------\n \/\/ Class Types\n \/\/ -----------------------------------------------------------------------\n \/** @name Public Contants *\/\n \/\/@{\n \/**\n * Constants returned by acceptNode.\n *\n *

FILTER_ACCEPT:<\/code>\n * Accept the node.<\/p>\n *\n *

FILTER_REJECT:<\/code>\n * Reject the node and its children.<\/p>\n *\n *

FILTER_SKIP:<\/code>\n * Skip this single node. The children of this node will still be considered.<\/p>\n *\n *

FILTER_INTERRUPT:<\/code>\n * Interrupt the normal processing of the document.<\/p>\n *\n * @since DOM Level 3\n *\/\n enum FilterAction {FILTER_ACCEPT = 1,\n FILTER_REJECT = 2,\n FILTER_SKIP = 3,\n FILTER_INTERRUPT = 4};\n\n \/\/ -----------------------------------------------------------------------\n \/\/ Virtual DOMLSParserFilter interface\n \/\/ -----------------------------------------------------------------------\n \/** @name Functions introduced in DOM Level 3 *\/\n \/\/@{\n\t \/**\n * This method will be called by the parser at the completion of the parsing of each node. \n * The node and all of its descendants will exist and be complete. The parent node will also exist, \n * although it may be incomplete, i.e. it may have additional children that have not yet been parsed. \n * Attribute nodes are never passed to this function.\n * From within this method, the new node may be freely modified - children may be added or removed, \n * text nodes modified, etc. The state of the rest of the document outside this node is not defined, \n * and the affect of any attempt to navigate to, or to modify any other part of the document is undefined.\n * For validating parsers, the checks are made on the original document, before any modification by the \n * filter. No validity checks are made on any document modifications made by the filter.\n * If this new node is rejected, the parser might reuse the new node and any of its descendants. \n *\n * @param node The newly constructed element. At the time this method is called, the element is complete - \n * it has all of its children (and their children, recursively) and attributes, and is attached \n * as a child to its parent.\n * @return One of the FilterAction enum\n *\/\n virtual short acceptNode(DOMNode* node) = 0;\n\n\t \/**\n * The parser will call this method after each DOMElement<\/code> start tag has been scanned, \n * but before the remainder of the DOMElement<\/code> is processed. The intent is to allow the element, \n * including any children, to be efficiently skipped. Note that only element nodes are passed to the \n * startElement function.\n * The element node passed to startElement for filtering will include all of the attributes, but none \n * of the children nodes. The DOMElement<\/code> may not yet be in place in the document being \n * constructed (it may not have a parent node.)\n * A startElement filter function may access or change the attributes for the DOMElement<\/code>. \n * Changing namespace declarations will have no effect on namespace resolution by the parser.\n *\n * @param node The newly encountered element. At the time this method is called, the element is incomplete - \n * it will have its attributes, but no children.\n * @return One of the FilterAction enum\n *\/\n virtual short startElement(DOMElement* node) = 0;\n\n \/**\n * Tells the DOMLSParser<\/code> what types of nodes to show to the method DOMLSParserFilter::acceptNode<\/code>. \n * If a node is not shown to the filter using this attribute, it is automatically included in the DOM document being built. \n * See DOMNodeFilter<\/code> for definition of the constants. The constants SHOW_ATTRIBUTE, SHOW_DOCUMENT, \n * SHOW_DOCUMENT_TYPE, SHOW_NOTATION, SHOW_ENTITY, and SHOW_DOCUMENT_FRAGMENT are meaningless here. \n * Those nodes will never be passed to DOMLSParserFilter::acceptNode.\n *\n * @return The constants of what types of nodes to show.\n * @since DOM Level 3\n *\/\n virtual unsigned long getWhatToShow() const = 0;\n\n \/\/@}\n\nprivate:\n\n};\n\nXERCES_CPP_NAMESPACE_END\n\n#endif\nadded forward declaration of DOMNode and DOMElement - needed since the header files are not included#ifndef DOMLSParserFilter_HEADER_GUARD_\n#define DOMLSParserFilter_HEADER_GUARD_\n\n\/*\n * Copyright 2002,2004 The Apache Software Foundation.\n * \n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * \n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n * \n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n\/*\n * $Id$\n *\/\n\n\/**\n *\n * DOMLSParserFilter.hpp: interface for the DOMLSParserFilter class.\n *\n * DOMLSParserFilter provide applications the ability to examine nodes\n * as they are being created during the parse process.\n *\n * DOMLSParserFilter lets the application decide what nodes should be\n * in the output DOM tree or not.\n *\n * @since DOM Level 3\n *\/\n\n\nXERCES_CPP_NAMESPACE_BEGIN\n\nclass DOMElement;\nclass DOMNode;\n\nclass CDOM_EXPORT DOMLSParserFilter {\nprotected:\n \/\/ -----------------------------------------------------------------------\n \/\/ Hidden constructors\n \/\/ -----------------------------------------------------------------------\n \/** @name Hidden constructors *\/\n \/\/@{ \n DOMLSParserFilter() {};\n \/\/@}\n\nprivate:\n \/\/ -----------------------------------------------------------------------\n \/\/ Unimplemented constructors and operators\n \/\/ -----------------------------------------------------------------------\n \/** @name Unimplemented constructors and operators *\/\n \/\/@{\n DOMLSParserFilter(const DOMLSParserFilter &);\n DOMLSParserFilter & operator = (const DOMLSParserFilter &);\n \/\/@}\n\n\npublic:\n \/\/ -----------------------------------------------------------------------\n \/\/ All constructors are hidden, just the destructor is available\n \/\/ -----------------------------------------------------------------------\n \/** @name Destructor *\/\n \/\/@{\n \/**\n * Destructor\n *\n *\/\n virtual ~DOMLSParserFilter() {};\n \/\/@}\n\n \/\/ -----------------------------------------------------------------------\n \/\/ Class Types\n \/\/ -----------------------------------------------------------------------\n \/** @name Public Contants *\/\n \/\/@{\n \/**\n * Constants returned by acceptNode.\n *\n *

FILTER_ACCEPT:<\/code>\n * Accept the node.<\/p>\n *\n *

FILTER_REJECT:<\/code>\n * Reject the node and its children.<\/p>\n *\n *

FILTER_SKIP:<\/code>\n * Skip this single node. The children of this node will still be considered.<\/p>\n *\n *

FILTER_INTERRUPT:<\/code>\n * Interrupt the normal processing of the document.<\/p>\n *\n * @since DOM Level 3\n *\/\n enum FilterAction {FILTER_ACCEPT = 1,\n FILTER_REJECT = 2,\n FILTER_SKIP = 3,\n FILTER_INTERRUPT = 4};\n\n \/\/ -----------------------------------------------------------------------\n \/\/ Virtual DOMLSParserFilter interface\n \/\/ -----------------------------------------------------------------------\n \/** @name Functions introduced in DOM Level 3 *\/\n \/\/@{\n\t \/**\n * This method will be called by the parser at the completion of the parsing of each node. \n * The node and all of its descendants will exist and be complete. The parent node will also exist, \n * although it may be incomplete, i.e. it may have additional children that have not yet been parsed. \n * Attribute nodes are never passed to this function.\n * From within this method, the new node may be freely modified - children may be added or removed, \n * text nodes modified, etc. The state of the rest of the document outside this node is not defined, \n * and the affect of any attempt to navigate to, or to modify any other part of the document is undefined.\n * For validating parsers, the checks are made on the original document, before any modification by the \n * filter. No validity checks are made on any document modifications made by the filter.\n * If this new node is rejected, the parser might reuse the new node and any of its descendants. \n *\n * @param node The newly constructed element. At the time this method is called, the element is complete - \n * it has all of its children (and their children, recursively) and attributes, and is attached \n * as a child to its parent.\n * @return One of the FilterAction enum\n *\/\n virtual short acceptNode(DOMNode* node) = 0;\n\n\t \/**\n * The parser will call this method after each DOMElement<\/code> start tag has been scanned, \n * but before the remainder of the DOMElement<\/code> is processed. The intent is to allow the element, \n * including any children, to be efficiently skipped. Note that only element nodes are passed to the \n * startElement function.\n * The element node passed to startElement for filtering will include all of the attributes, but none \n * of the children nodes. The DOMElement<\/code> may not yet be in place in the document being \n * constructed (it may not have a parent node.)\n * A startElement filter function may access or change the attributes for the DOMElement<\/code>. \n * Changing namespace declarations will have no effect on namespace resolution by the parser.\n *\n * @param node The newly encountered element. At the time this method is called, the element is incomplete - \n * it will have its attributes, but no children.\n * @return One of the FilterAction enum\n *\/\n virtual short startElement(DOMElement* node) = 0;\n\n \/**\n * Tells the DOMLSParser<\/code> what types of nodes to show to the method DOMLSParserFilter::acceptNode<\/code>. \n * If a node is not shown to the filter using this attribute, it is automatically included in the DOM document being built. \n * See DOMNodeFilter<\/code> for definition of the constants. The constants SHOW_ATTRIBUTE, SHOW_DOCUMENT, \n * SHOW_DOCUMENT_TYPE, SHOW_NOTATION, SHOW_ENTITY, and SHOW_DOCUMENT_FRAGMENT are meaningless here. \n * Those nodes will never be passed to DOMLSParserFilter::acceptNode.\n *\n * @return The constants of what types of nodes to show.\n * @since DOM Level 3\n *\/\n virtual unsigned long getWhatToShow() const = 0;\n\n \/\/@}\n\nprivate:\n\n};\n\nXERCES_CPP_NAMESPACE_END\n\n#endif\n<|endoftext|>"} {"text":"\/*\n * This file is a part of Xpiks - cross platform application for\n * keywording and uploading images for microstocks\n * Copyright (C) 2014-2017 Taras Kushnir \n *\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n *\/\n\n#include \"stringhelper.h\"\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \"..\/Common\/defines.h\"\n#include \"..\/Helpers\/indiceshelper.h\"\n\n#if defined(Q_OS_WIN)\n#define NOMINMAX\n#include \n#pragma comment(lib, \"ws2_32.lib\")\n#elif defined(Q_OS_MAC)\n #include \n#elif defined(Q_OS_LINUX)\n#include \n#endif\n\n#define SYNONYMS_DISTANCE 3\n\nnamespace Helpers {\n void foreachPart(const QString &text,\n const std::function &isSeparatorPred,\n const std::function &pred,\n const std::function &action)\n {\n int i = 0;\n const int size = text.size();\n int lastStart = -1;\n\n while (i < size) {\n QChar c = text[i];\n if (isSeparatorPred(c)) {\n if (lastStart != -1) {\n int wordLength = i - lastStart;\n QString word = text.mid(lastStart, wordLength);\n\n if (pred(word)) {\n action(lastStart, wordLength, word);\n }\n\n lastStart = -1;\n }\n } else {\n if (lastStart == -1) {\n lastStart = i;\n }\n }\n\n i++;\n }\n\n if (lastStart != -1) {\n int wordLength = size - lastStart;\n QString word = text.mid(lastStart, wordLength);\n\n if (pred(word)) {\n action(lastStart, wordLength, word);\n }\n }\n }\n\n void foreachWord(const QString &text,\n const std::function &pred,\n const std::function &action)\n {\n foreachPart(text,\n [](const QChar &c) { return c.isSpace() || isPunctuation(c); },\n pred, action);\n }\n\n bool isLeftWordBound(const QString &text, int index, bool skipWordBounds=false) {\n if (index == 0) { return true; }\n\n QChar curr = text[index];\n QChar prev = text[index - 1];\n\n const bool currIsSeparator = isPunctuation(curr) || curr.isSpace();\n const bool prevIsSeparator = isPunctuation(prev) || prev.isSpace();\n\n return (skipWordBounds || !currIsSeparator) && (prevIsSeparator);\n }\n\n bool isRightWordBound(const QString &text, int lastIndex, int index, bool skipWordBounds=false) {\n if (index == lastIndex) { return true; }\n\n QChar curr = text[index];\n QChar next = text[index + 1];\n\n const bool currIsSeparator = isPunctuation(curr) || curr.isSpace();\n const bool nextIsSeparator = isPunctuation(next) || next.isSpace();\n\n return (skipWordBounds || !currIsSeparator) && (nextIsSeparator);\n }\n\n bool isAWholeWord(const QString &text, int start, int length, bool onlyCheckBounds=false) {\n if (text.isEmpty()) { return false; }\n\n if (!isLeftWordBound(text, start, onlyCheckBounds)) { return false; }\n const int lastIndex = text.size() - 1;\n if (!isRightWordBound(text, lastIndex, start + length - 1, onlyCheckBounds)) { return false; }\n\n return true;\n }\n\n QString replaceWholeWords(const QString &text, const QString &replaceWhat,\n const QString &replaceTo, Qt::CaseSensitivity caseSensitivity) {\n int pos = 0;\n const int size = replaceWhat.size();\n std::vector > hits;\n hits.reserve(std::max(text.length() \/ replaceWhat.length(), 10));\n\n while (pos != -1) {\n pos = text.indexOf(replaceWhat, pos, caseSensitivity);\n if (pos >= 0) {\n if (isAWholeWord(text, pos, size, true)) {\n hits.emplace_back(std::make_pair(pos, size));\n }\n\n pos += size;\n }\n }\n\n if (hits.empty()) { return text; }\n\n QString result;\n result.reserve(text.length());\n\n int lastStart = 0;\n for (auto &hit: hits) {\n if (hit.first > lastStart) {\n result.append(text.mid(lastStart, hit.first - lastStart));\n }\n\n result.append(replaceTo);\n lastStart = hit.first + hit.second;\n }\n\n if (lastStart < text.length() - 1) {\n result.append(text.mid(lastStart));\n }\n\n return result;\n }\n\n bool containsWholeWords(const QString &haystack, const QString &needle, Qt::CaseSensitivity caseSensitivity) {\n bool anyHit = false;\n\n int pos = 0;\n const int size = needle.size();\n\n while (pos != -1) {\n pos = haystack.indexOf(needle, pos, caseSensitivity);\n if (pos >= 0) {\n if (isAWholeWord(haystack, pos, size, true)) {\n anyHit = true;\n break;\n }\n\n pos += size;\n }\n }\n\n return anyHit;\n }\n\n#if (QT_VERSION >= QT_VERSION_CHECK(5, 4, 0))\n QString getLastNLines(const QString &text, int N) {\n QString result;\n\n QVector items = text.splitRef(QRegExp(\"[\\r\\n]\"), QString::SkipEmptyParts);\n\n const int length = items.length();\n\n if (length > 0) {\n int startIndex = length - N;\n if (startIndex < 0) {\n startIndex = 0;\n }\n\n int pos = items[startIndex].position();\n result = text.right(text.length() - pos);\n } else {\n result = text;\n }\n\n return result;\n }\n\n#else\n QString getLastNLines(const QString &text, int N) {\n QString result;\n QStringList lastNLines;\n\n QStringList items = text.split(QRegExp(\"[\\r\\n]\"), QString::SkipEmptyParts);\n\n int length = items.length();\n\n if (length > 0) {\n int startIndex = length - N;\n if (startIndex < 0) {\n startIndex = 0;\n }\n\n for (int pos = startIndex; pos < length; pos++) {\n lastNLines.append(items[pos]);\n }\n\n result = lastNLines.join(\"\\n\");\n } else {\n result = text;\n }\n\n return result;\n }\n\n#endif\n\n void splitText(const QString &text, QStringList &parts) {\n foreachWord(text,\n [](const QString&) { return true; },\n [&parts](int, int, const QString &word) { parts.append(word); });\n }\n\n void splitKeywords(const QString &text, const QVector &separators, QStringList &parts) {\n foreachPart(text,\n [&separators](const QChar &c) { return separators.contains(c); },\n [](const QString&) { return true; },\n [&parts](int, int, const QString &word) { parts.append(word); });\n }\n\n std::string string_format(const std::string fmt, ...) {\n int size = ((int)fmt.size()) * 2 + 50; \/\/ Use a rubric appropriate for your code\n std::string str;\n va_list ap;\n while (1) { \/\/ Maximum two passes on a POSIX system...\n str.resize(size);\n va_start(ap, fmt);\n int n = vsnprintf((char *)str.data(), size, fmt.c_str(), ap);\n va_end(ap);\n if (n > -1 && n < size) { \/\/ Everything worked\n str.resize(n);\n return str;\n }\n if (n > -1) \/\/ Needed size returned\n size = n + 1; \/\/ For null char\n else\n size *= 2; \/\/ Guess at a larger size (OS specific)\n }\n\n return str;\n }\n\n unsigned int levensteinDistance(const QString &a, const QString &b) {\n const unsigned int lengthA = a.size(), lengthB = b.size();\n std::vector costs(lengthB + 1), prevCosts(lengthB + 1);\n const unsigned int prevCostsSize = (unsigned int)prevCosts.size();\n\n for (unsigned int i = 0; i < prevCostsSize; i++) {\n prevCosts[i] = i;\n }\n\n for (unsigned int i = 0; i < lengthA; i++) {\n costs[0] = i + 1;\n\n for (unsigned int j = 0; j < lengthB; j++) {\n costs[j + 1] = std::min(\n std::min(prevCosts[1 + j] + 1, costs[j] + 1),\n prevCosts[j] + (a[i] == b[j] ? 0 : 1));\n }\n\n costs.swap(prevCosts);\n }\n\n unsigned int result = prevCosts[lengthB];\n return result;\n }\n\n int levensteinPercentage(const QString &s1, const QString &s2) {\n int maxLength = std::max(s1.length(), s2.length());\n\n unsigned int distance = levensteinDistance(s1.toLower(), s2.toLower());\n int reverseDistance = maxLength - (int)distance;\n\n if (reverseDistance == 0) { return 0; }\n\n int percent = (reverseDistance * 100) \/ maxLength;\n return percent;\n }\n\n bool is7BitAscii(const QByteArray &s) {\n bool anyFault = false;\n const int size = s.size();\n\n for (int i = 0; i < size; i++) {\n int c = s[i];\n if (c < 0 || c >= 128) {\n anyFault = true;\n break;\n }\n }\n\n return !anyFault;\n }\n\n bool isPunctuation(const QChar &c) {\n return c.isPunct() && c != QChar('\/');\n }\n\n void extendSegmentToWordBoundaries(const QString &text, std::pair &segment) {\n int left = segment.first;\n while (!isLeftWordBound(text, left)) { left--; }\n\n int right = segment.second;\n const int lastIndex = text.size() - 1;\n while (!isRightWordBound(text, lastIndex, right)) { right++; }\n\n segment.first = left;\n segment.second = right;\n }\n\n std::pair getSegmentFromHit(const QString &text, int hit, int radius) {\n int left = hit;\n while (!isLeftWordBound(text, left)) { left--; }\n\n int right = hit;\n const int lastIndex = text.size() - 1;\n while (!isRightWordBound(text, lastIndex, right)) { right++; }\n\n int first = std::max(0, left - radius);\n int second = std::min(lastIndex, right + radius);\n return std::make_pair(first, second);\n }\n\n QString getUnitedHitsString(const QString &text, const std::vector &hits, int radius) {\n std::vector > segments;\n segments.resize(hits.size());\n\n \/\/ create segment from each hit\n std::transform(hits.begin(), hits.end(), segments.begin(),\n [&text, radius](int hit) {\n return getSegmentFromHit(text, hit, radius);\n });\n\n for (auto &item: segments) {\n extendSegmentToWordBoundaries(text, item);\n }\n\n auto unitedSegments = Helpers::unionRanges(segments);\n\n QStringList entries;\n entries.reserve((int)unitedSegments.size());\n\n for (auto &element: unitedSegments) {\n entries.append(text.mid(element.first, element.second - element.first + 1));\n }\n\n QString result = entries.join(\" ... \");\n return result;\n }\n\n quint32 switcherHash(const QString &text) {\n QCryptographicHash hash(QCryptographicHash::Sha256);\n hash.addData(text.toUtf8());\n QByteArray result = hash.result();\n\n char *data = result.data();\n quint32 prefix = ntohl(*((quint32 *)data));\n return prefix;\n }\n\n bool areSemanticDuplicates(const QString &s1, const QString &s2) {\n if (QString::compare(s1, s2, Qt::CaseInsensitive) == 0) { return true; }\n\n const int length1 = s1.length();\n const int length2 = s2.length();\n\n const int diff = abs(length1 - length2);\n if (diff > SYNONYMS_DISTANCE) { return false; }\n\n const auto distance = Helpers::levensteinDistance(s1, s2);\n return distance <= SYNONYMS_DISTANCE;\n }\n}\nFixes for tests\/*\n * This file is a part of Xpiks - cross platform application for\n * keywording and uploading images for microstocks\n * Copyright (C) 2014-2017 Taras Kushnir \n *\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n *\/\n\n#include \"stringhelper.h\"\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \"..\/Common\/defines.h\"\n#include \"..\/Helpers\/indiceshelper.h\"\n\n#if defined(Q_OS_WIN)\n#define NOMINMAX\n#include \n#pragma comment(lib, \"ws2_32.lib\")\n#elif defined(Q_OS_MAC)\n #include \n#elif defined(Q_OS_LINUX)\n#include \n#endif\n\n#define SYNONYMS_DISTANCE 3\n\nnamespace Helpers {\n void foreachPart(const QString &text,\n const std::function &isSeparatorPred,\n const std::function &pred,\n const std::function &action)\n {\n int i = 0;\n const int size = text.size();\n int lastStart = -1;\n\n while (i < size) {\n QChar c = text[i];\n if (isSeparatorPred(c)) {\n if (lastStart != -1) {\n int wordLength = i - lastStart;\n QString word = text.mid(lastStart, wordLength);\n\n if (pred(word)) {\n action(lastStart, wordLength, word);\n }\n\n lastStart = -1;\n }\n } else {\n if (lastStart == -1) {\n lastStart = i;\n }\n }\n\n i++;\n }\n\n if (lastStart != -1) {\n int wordLength = size - lastStart;\n QString word = text.mid(lastStart, wordLength);\n\n if (pred(word)) {\n action(lastStart, wordLength, word);\n }\n }\n }\n\n void foreachWord(const QString &text,\n const std::function &pred,\n const std::function &action)\n {\n foreachPart(text,\n [](const QChar &c) { return c.isSpace() || isPunctuation(c); },\n pred, action);\n }\n\n bool isLeftWordBound(const QString &text, int index, bool skipWordBounds=false) {\n if (index == 0) { return true; }\n\n QChar curr = text[index];\n QChar prev = text[index - 1];\n\n const bool currIsSeparator = isPunctuation(curr) || curr.isSpace();\n const bool prevIsSeparator = isPunctuation(prev) || prev.isSpace();\n\n return (skipWordBounds || !currIsSeparator) && (prevIsSeparator);\n }\n\n bool isRightWordBound(const QString &text, int lastIndex, int index, bool skipWordBounds=false) {\n if (index == lastIndex) { return true; }\n\n QChar curr = text[index];\n QChar next = text[index + 1];\n\n const bool currIsSeparator = isPunctuation(curr) || curr.isSpace();\n const bool nextIsSeparator = isPunctuation(next) || next.isSpace();\n\n return (skipWordBounds || !currIsSeparator) && (nextIsSeparator);\n }\n\n bool isAWholeWord(const QString &text, int start, int length, bool onlyCheckBounds=false) {\n if (text.isEmpty()) { return false; }\n\n if (!isLeftWordBound(text, start, onlyCheckBounds)) { return false; }\n const int lastIndex = text.size() - 1;\n if (!isRightWordBound(text, lastIndex, start + length - 1, onlyCheckBounds)) { return false; }\n\n return true;\n }\n\n QString replaceWholeWords(const QString &text, const QString &replaceWhat,\n const QString &replaceTo, Qt::CaseSensitivity caseSensitivity) {\n int pos = 0;\n const int size = replaceWhat.size();\n std::vector > hits;\n hits.reserve(std::max(text.length() \/ replaceWhat.length(), 10));\n\n while (pos != -1) {\n pos = text.indexOf(replaceWhat, pos, caseSensitivity);\n if (pos >= 0) {\n if (isAWholeWord(text, pos, size, true)) {\n hits.emplace_back(std::make_pair(pos, size));\n }\n\n pos += size;\n }\n }\n\n if (hits.empty()) { return text; }\n\n QString result;\n result.reserve(text.length());\n\n int lastStart = 0;\n for (auto &hit: hits) {\n if (hit.first > lastStart) {\n result.append(text.mid(lastStart, hit.first - lastStart));\n }\n\n result.append(replaceTo);\n lastStart = hit.first + hit.second;\n }\n\n if (lastStart < text.length() - 1) {\n result.append(text.mid(lastStart));\n }\n\n return result;\n }\n\n bool containsWholeWords(const QString &haystack, const QString &needle, Qt::CaseSensitivity caseSensitivity) {\n bool anyHit = false;\n\n int pos = 0;\n const int size = needle.size();\n\n while (pos != -1) {\n pos = haystack.indexOf(needle, pos, caseSensitivity);\n if (pos >= 0) {\n if (isAWholeWord(haystack, pos, size, true)) {\n anyHit = true;\n break;\n }\n\n pos += size;\n }\n }\n\n return anyHit;\n }\n\n#if (QT_VERSION >= QT_VERSION_CHECK(5, 4, 0))\n QString getLastNLines(const QString &text, int N) {\n QString result;\n\n QVector items = text.splitRef(QRegExp(\"[\\r\\n]\"), QString::SkipEmptyParts);\n\n const int length = items.length();\n\n if (length > 0) {\n int startIndex = length - N;\n if (startIndex < 0) {\n startIndex = 0;\n }\n\n int pos = items[startIndex].position();\n result = text.right(text.length() - pos);\n } else {\n result = text;\n }\n\n return result;\n }\n\n#else\n QString getLastNLines(const QString &text, int N) {\n QString result;\n QStringList lastNLines;\n\n QStringList items = text.split(QRegExp(\"[\\r\\n]\"), QString::SkipEmptyParts);\n\n int length = items.length();\n\n if (length > 0) {\n int startIndex = length - N;\n if (startIndex < 0) {\n startIndex = 0;\n }\n\n for (int pos = startIndex; pos < length; pos++) {\n lastNLines.append(items[pos]);\n }\n\n result = lastNLines.join(\"\\n\");\n } else {\n result = text;\n }\n\n return result;\n }\n\n#endif\n\n void splitText(const QString &text, QStringList &parts) {\n foreachWord(text,\n [](const QString&) { return true; },\n [&parts](int, int, const QString &word) { parts.append(word); });\n }\n\n void splitKeywords(const QString &text, const QVector &separators, QStringList &parts) {\n foreachPart(text,\n [&separators](const QChar &c) { return separators.contains(c); },\n [](const QString&) { return true; },\n [&parts](int, int, const QString &word) { parts.append(word); });\n }\n\n std::string string_format(const std::string fmt, ...) {\n int size = ((int)fmt.size()) * 2 + 50; \/\/ Use a rubric appropriate for your code\n std::string str;\n va_list ap;\n while (1) { \/\/ Maximum two passes on a POSIX system...\n str.resize(size);\n va_start(ap, fmt);\n int n = vsnprintf((char *)str.data(), size, fmt.c_str(), ap);\n va_end(ap);\n if (n > -1 && n < size) { \/\/ Everything worked\n str.resize(n);\n return str;\n }\n if (n > -1) \/\/ Needed size returned\n size = n + 1; \/\/ For null char\n else\n size *= 2; \/\/ Guess at a larger size (OS specific)\n }\n\n return str;\n }\n\n unsigned int levensteinDistance(const QString &a, const QString &b) {\n const unsigned int lengthA = a.size(), lengthB = b.size();\n std::vector costs(lengthB + 1), prevCosts(lengthB + 1);\n const unsigned int prevCostsSize = (unsigned int)prevCosts.size();\n\n for (unsigned int i = 0; i < prevCostsSize; i++) {\n prevCosts[i] = i;\n }\n\n for (unsigned int i = 0; i < lengthA; i++) {\n costs[0] = i + 1;\n\n for (unsigned int j = 0; j < lengthB; j++) {\n costs[j + 1] = std::min(\n std::min(prevCosts[1 + j] + 1, costs[j] + 1),\n prevCosts[j] + (a[i] == b[j] ? 0 : 1));\n }\n\n costs.swap(prevCosts);\n }\n\n unsigned int result = prevCosts[lengthB];\n return result;\n }\n\n int levensteinPercentage(const QString &s1, const QString &s2) {\n int maxLength = std::max(s1.length(), s2.length());\n\n unsigned int distance = levensteinDistance(s1.toLower(), s2.toLower());\n int reverseDistance = maxLength - (int)distance;\n\n if (reverseDistance == 0) { return 0; }\n\n int percent = (reverseDistance * 100) \/ maxLength;\n return percent;\n }\n\n bool is7BitAscii(const QByteArray &s) {\n bool anyFault = false;\n const int size = s.size();\n\n for (int i = 0; i < size; i++) {\n int c = s[i];\n if (c < 0 || c >= 128) {\n anyFault = true;\n break;\n }\n }\n\n return !anyFault;\n }\n\n bool isPunctuation(const QChar &c) {\n return c.isPunct() && c != QChar('\/');\n }\n\n void extendSegmentToWordBoundaries(const QString &text, std::pair &segment) {\n int left = segment.first;\n while (!isLeftWordBound(text, left)) { left--; }\n\n int right = segment.second;\n const int lastIndex = text.size() - 1;\n while (!isRightWordBound(text, lastIndex, right)) { right++; }\n\n segment.first = left;\n segment.second = right;\n }\n\n std::pair getSegmentFromHit(const QString &text, int hit, int radius) {\n int left = hit;\n while (!isLeftWordBound(text, left)) { left--; }\n\n int right = hit;\n const int lastIndex = text.size() - 1;\n while (!isRightWordBound(text, lastIndex, right)) { right++; }\n\n int first = std::max(0, left - radius);\n int second = std::min(lastIndex, right + radius);\n return std::make_pair(first, second);\n }\n\n QString getUnitedHitsString(const QString &text, const std::vector &hits, int radius) {\n std::vector > segments;\n segments.resize(hits.size());\n\n \/\/ create segment from each hit\n std::transform(hits.begin(), hits.end(), segments.begin(),\n [&text, radius](int hit) {\n return getSegmentFromHit(text, hit, radius);\n });\n\n for (auto &item: segments) {\n extendSegmentToWordBoundaries(text, item);\n }\n\n auto unitedSegments = Helpers::unionRanges(segments);\n\n QStringList entries;\n entries.reserve((int)unitedSegments.size());\n\n for (auto &element: unitedSegments) {\n entries.append(text.mid(element.first, element.second - element.first + 1));\n }\n\n QString result = entries.join(\" ... \");\n return result;\n }\n\n quint32 switcherHash(const QString &text) {\n QCryptographicHash hash(QCryptographicHash::Sha256);\n hash.addData(text.toUtf8());\n QByteArray result = hash.result();\n\n char *data = result.data();\n quint32 prefix = ntohl(*((quint32 *)data));\n return prefix;\n }\n\n bool areSemanticDuplicates(const QString &s1, const QString &s2) {\n if (QString::compare(s1, s2, Qt::CaseInsensitive) == 0) { return true; }\n\n const int length1 = s1.length();\n const int length2 = s2.length();\n\n const int diff = abs(length1 - length2);\n if (diff > SYNONYMS_DISTANCE) { return false; }\n\n const auto distance = Helpers::levensteinDistance(s1.toLower(), s2.toLower());\n return distance <= SYNONYMS_DISTANCE;\n }\n}\n<|endoftext|>"} {"text":"\/\/ Copyright (C) 2012 Rhys Ulerich\n\/\/\n\/\/ This program is free software: you can redistribute it and\/or modify\n\/\/ it under the terms of the GNU General Public License as published by\n\/\/ the Free Software Foundation, either version 3 of the License, or\n\/\/ (at your option) any later version.\n\/\/\n\/\/ This program is distributed in the hope that it will be useful,\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n\/\/ GNU General Public License for more details.\n\/\/\n\/\/ You should have received a copy of the GNU General Public License\n\/\/ along with this program. If not, see .\n\n#include \"ar.hpp\"\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n\n\/** @file\n * A GNU Octave wrapper estimating the best AR(p) model given signal input.\n * Compare \\ref arsel.cpp.\n *\/\n\n\/\/ Compile-time defaults in the code also appearing in the help message\n#define DEFAULT_SUBMEAN true\n#define DEFAULT_MAXORDER 512\n#define STRINGIFY(x) STRINGIFY_HELPER(x)\n#define STRINGIFY_HELPER(x) #x\n\nDEFUN_DLD(\n arsel, args, nargout,\n \"\\t[A, mu, sigma2eps, eff_sigma2x, Neff, T0] = arsel (d, submean, maxorder)\\n\"\n \"\\tAutomatically fit an autoregressive model to an input signal.\\n\"\n \"\\t\\n\"\n \"\\tUse ar::burg_method followed by ar::best_model >\\n\"\n \"\\tto obtain the most likely autoregressive process for input signal d.\\n\"\n \"\\tThe sample mean of d will be subtracted whenever submean is true.\\n\"\n \"\\tModel orders zero through min(size(d), maxorder) will be considered.\\n\"\n \"\\t\\n\"\n \"\\tThe filter()-ready process parameters are returned in A, the sample mean\\n\"\n \"\\tin mu, and the innovation variance \\\\sigma^2_\\\\epsilon in sigma2eps.\\n\"\n \"\\tGiven the observed autocorrelation structure, a decorrelation time T0 is\\n\"\n \"\\tcomputed and used to estimate the effective signal variance eff_sigma2x.\\n\"\n \"\\tThe number of effectively independent samples is returned in Neff.\\n\"\n \"\\t\\n\"\n \"\\tOne may simulate N samples from the fitted process by calling:\\n\"\n \"\\t\\n\"\n \"\\t\\tx = mu + filter([1], A, sqrt(sigma2eps)*randn(N,1));\\n\"\n \"\\t\\n\"\n \"\\tWhen not supplied, submean defaults to \" STRINGIFY(DEFAULT_SUBMEAN) \".\\n\"\n \"\\tWhen not supplied, maxorder defaults to \" STRINGIFY(DEFAULT_MAXORDER) \".\\n\"\n \"\\tWhen no output arguments are requested, all details are displayed.\\n\"\n)\n{\n std::size_t maxorder = DEFAULT_MAXORDER;\n bool submean = DEFAULT_SUBMEAN;\n RowVector data;\n switch (args.length())\n {\n case 3:\n maxorder = args(2).ulong_value();\n case 2:\n submean = args(1).bool_value();\n case 1:\n data = args(0).row_vector_value();\n break;\n default:\n error(\"Invalid call to arsel. Correct usage is: \");\n case 0:\n print_usage();\n return octave_value();\n }\n\n \/\/ How much data will we be processing?\n const size_t N = data.dims().numel();\n if (!N) {\n error(\"arsel: input signal d must have nonzero length\");\n return octave_value();\n }\n\n \/\/ Use burg_method to estimate a hierarchy of AR models from input data\n double mu;\n std::vector params, sigma2e, gain, autocor;\n params .reserve(maxorder*(maxorder + 1)\/2);\n sigma2e.reserve(maxorder + 1);\n gain .reserve(maxorder + 1);\n autocor.reserve(maxorder + 1);\n ar::burg_method(data.fortran_vec(), data.fortran_vec() + N,\n mu, maxorder,\n std::back_inserter(params),\n std::back_inserter(sigma2e),\n std::back_inserter(gain),\n std::back_inserter(autocor),\n submean, \/* output hierarchy? *\/ true);\n\n \/\/ Keep only best model according to CIC accounting for subtract_mean.\n if (submean) {\n ar::best_model > >(\n N, params, sigma2e, gain, autocor);\n } else {\n ar::best_model > >(\n N, params, sigma2e, gain, autocor);\n }\n\n \/\/ Compute decorrelation time from the estimated autocorrelation model\n double T0 = std::numeric_limits::quiet_NaN();\n if (nargout == 0 || nargout > 2) {\n ar::predictor p = ar::autocorrelation(\n params.begin(), params.end(), gain[0], autocor.begin());\n T0 = ar::decorrelation_time(N, p, \/* abs(rho) *\/ true);\n }\n\n \/\/ Prepare autoregressive process parameters for Octave's filter function\n RowVector A(params.size() + 1, \/* leading one *\/ 1);\n std::copy(params.begin(), params.end(), A.fortran_vec() + 1);\n\n \/\/ Prepare output: [A, mu, sigma2eps, eff_sigma2x, Neff, T0]\n octave_value_list retval;\n std::list names;\n switch (nargout == 0 ? std::numeric_limits::max() : nargout)\n {\n default:\n if (nargout) warning(\"arsel: too many output values requested\");\n case 6:\n retval.prepend(T0);\n names.push_front(\"T0\");\n case 5:\n retval.prepend(N \/ T0);\n names.push_front(\"Neff\");\n case 4:\n retval.prepend((N*gain[0]*sigma2e[0]) \/ (N - T0));\n names.push_front(\"eff_sigma2x\");\n case 3:\n retval.prepend(sigma2e[0]);\n names.push_front(\"sigma2eps\");\n case 2:\n retval.prepend(mu);\n names.push_front(\"mu\");\n case 1:\n retval.prepend(A);\n names.push_front(\"A\");\n break;\n case 0:\n panic_impossible();\n }\n retval.stash_name_tags(names);\n\n \/\/ Provide no results whenever errors are detected\n if (error_state) retval.resize(0);\n\n \/\/ FIXME Use Octave's default stream (?) instead of std::cout\n \/\/ Display results to user when no output was requested\n if (!nargout) {\n int i = 0;\n while (names.size()) {\n retval(i++).print_with_name(std::cout, names.front());\n names.pop_front();\n }\n retval.resize(0);\n }\n\n return retval;\n}\nReturn struct on 0 nargout\/\/ Copyright (C) 2012 Rhys Ulerich\n\/\/\n\/\/ This program is free software: you can redistribute it and\/or modify\n\/\/ it under the terms of the GNU General Public License as published by\n\/\/ the Free Software Foundation, either version 3 of the License, or\n\/\/ (at your option) any later version.\n\/\/\n\/\/ This program is distributed in the hope that it will be useful,\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n\/\/ GNU General Public License for more details.\n\/\/\n\/\/ You should have received a copy of the GNU General Public License\n\/\/ along with this program. If not, see .\n\n#include \"ar.hpp\"\n\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n\n\/** @file\n * A GNU Octave wrapper estimating the best AR(p) model given signal input.\n * Compare \\ref arsel.cpp.\n *\/\n\n\/\/ Compile-time defaults in the code also appearing in the help message\n#define DEFAULT_SUBMEAN true\n#define DEFAULT_MAXORDER 512\n#define STRINGIFY(x) STRINGIFY_HELPER(x)\n#define STRINGIFY_HELPER(x) #x\n\nDEFUN_DLD(\n arsel, args, nargout,\n \"\\t[A, mu, sigma2eps, eff_sigma2x, Neff, T0] = arsel (d, submean, maxorder)\\n\"\n \"\\tAutomatically fit an autoregressive model to an input signal.\\n\"\n \"\\t\\n\"\n \"\\tUse ar::burg_method followed by ar::best_model >\\n\"\n \"\\tto obtain the most likely autoregressive process for input signal d.\\n\"\n \"\\tThe sample mean of d will be subtracted whenever submean is true.\\n\"\n \"\\tModel orders zero through min(size(d), maxorder) will be considered.\\n\"\n \"\\t\\n\"\n \"\\tThe filter()-ready process parameters are returned in A, the sample mean\\n\"\n \"\\tin mu, and the innovation variance \\\\sigma^2_\\\\epsilon in sigma2eps.\\n\"\n \"\\tGiven the observed autocorrelation structure, a decorrelation time T0 is\\n\"\n \"\\tcomputed and used to estimate the effective signal variance eff_sigma2x.\\n\"\n \"\\tThe number of effectively independent samples is returned in Neff.\\n\"\n \"\\t\\n\"\n \"\\tOne may simulate N samples from the fitted process by calling:\\n\"\n \"\\t\\n\"\n \"\\t\\tx = mu + filter([1], A, sqrt(sigma2eps)*randn(N,1));\\n\"\n \"\\t\\n\"\n \"\\tWhen not supplied, submean defaults to \" STRINGIFY(DEFAULT_SUBMEAN) \".\\n\"\n \"\\tWhen not supplied, maxorder defaults to \" STRINGIFY(DEFAULT_MAXORDER) \".\\n\"\n \"\\tWhen no outputs are requested, a struct with all outputs is returned.\\n\"\n)\n{\n std::size_t maxorder = DEFAULT_MAXORDER;\n bool submean = DEFAULT_SUBMEAN;\n RowVector data;\n switch (args.length())\n {\n case 3:\n maxorder = args(2).ulong_value();\n case 2:\n submean = args(1).bool_value();\n case 1:\n data = args(0).row_vector_value();\n break;\n default:\n error(\"Invalid call to arsel. Correct usage is: \");\n case 0:\n print_usage();\n return octave_value();\n }\n\n \/\/ How much data will we be processing?\n const size_t N = data.dims().numel();\n if (!N)\n {\n error(\"arsel: input signal d must have nonzero length\");\n return octave_value();\n }\n\n \/\/ Use burg_method to estimate a hierarchy of AR models from input data\n double mu;\n std::vector params, sigma2e, gain, autocor;\n params .reserve(maxorder*(maxorder + 1)\/2);\n sigma2e.reserve(maxorder + 1);\n gain .reserve(maxorder + 1);\n autocor.reserve(maxorder + 1);\n ar::burg_method(data.fortran_vec(), data.fortran_vec() + N,\n mu, maxorder,\n std::back_inserter(params),\n std::back_inserter(sigma2e),\n std::back_inserter(gain),\n std::back_inserter(autocor),\n submean, \/* output hierarchy? *\/ true);\n\n \/\/ Keep only best model according to CIC accounting for subtract_mean.\n if (submean)\n {\n ar::best_model > >(\n N, params, sigma2e, gain, autocor);\n }\n else\n {\n ar::best_model > >(\n N, params, sigma2e, gain, autocor);\n }\n\n \/\/ Compute decorrelation time from the estimated autocorrelation model\n double T0 = std::numeric_limits::quiet_NaN();\n if (nargout == 0 || nargout > 2)\n {\n ar::predictor p = ar::autocorrelation(\n params.begin(), params.end(), gain[0], autocor.begin());\n T0 = ar::decorrelation_time(N, p, \/* abs(rho) *\/ true);\n }\n\n \/\/ Prepare autoregressive process parameters for Octave's filter function\n RowVector A(params.size() + 1, \/* leading one *\/ 1);\n std::copy(params.begin(), params.end(), A.fortran_vec() + 1);\n\n \/\/ Prepare output: [A, mu, sigma2eps, eff_sigma2x, Neff, T0]\n octave_value_list result;\n std::list names;\n switch (nargout == 0 ? std::numeric_limits::max() : nargout)\n {\n default:\n if (nargout) warning(\"arsel: too many output values requested\");\n case 6:\n names.push_front(\"T0\");\n result.prepend(T0);\n case 5:\n names.push_front(\"Neff\");\n result.prepend(N \/ T0);\n case 4:\n names.push_front(\"eff_sigma2x\");\n result.prepend((N*gain[0]*sigma2e[0]) \/ (N - T0));\n case 3:\n names.push_front(\"sigma2eps\");\n result.prepend(sigma2e[0]);\n case 2:\n names.push_front(\"mu\");\n result.prepend(mu);\n case 1:\n names.push_front(\"A\");\n result.prepend(A);\n break;\n case 0:\n panic_impossible();\n }\n\n \/\/ Either return requested results in assignment-friendly fashion\n \/\/ or, when nothing was requested, return a struct to likely display.\n if (nargout)\n {\n result.stash_name_tags(names);\n }\n else \/\/ nargout == 0\n {\n Octave_map m;\n int i = 0;\n while (names.size()) {\n m.assign(names.front(), result(i++));\n names.pop_front();\n }\n result.resize(1);\n result(0) = m;\n }\n\n \/\/ Provide no results whenever an error was detected\n if (error_state)\n {\n warning(\"arsel: error detected; no results returned\");\n result.resize(0);\n }\n\n return result;\n}\n<|endoftext|>"} {"text":"\/*\n * Copyright 2008-2012 NVIDIA Corporation\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#pragma once\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nnamespace thrust\n{\nnamespace system\n{\nnamespace cuda\n{\nnamespace detail\n{\nnamespace trivial_copy_detail\n{\n\n\ntemplate\n cudaMemcpyKind cuda_memcpy_kind(const thrust::cuda::execution_policy &,\n const thrust::cpp::execution_policy &)\n{\n return cudaMemcpyDeviceToHost;\n} \/\/ end cuda_memcpy_kind()\n\n\ntemplate\n cudaMemcpyKind cuda_memcpy_kind(const thrust::cpp::execution_policy &,\n const thrust::cuda::execution_policy &)\n{\n return cudaMemcpyHostToDevice;\n} \/\/ end cuda_memcpy_kind()\n\n\n} \/\/ end namespace trivial_copy_detail\n\n\ntemplate\n__host__ __device__\nvoid trivial_copy_n(execution_policy &exec,\n RandomAccessIterator1 first,\n Size n,\n RandomAccessIterator2 result)\n{\n typedef typename thrust::iterator_value::type T;\n\n#ifndef __CUDA_ARCH__\n void *dst = thrust::raw_pointer_cast(&*result);\n const void *src = thrust::raw_pointer_cast(&*first);\n\n throw_on_error(cudaMemcpy(dst, src, n * sizeof(T), cudaMemcpyDeviceToDevice), \"cudaMemcpy in trivial_copy_n\");\n#else\n \/\/ XXX transform is implemented with zip_iterator, which freaks out when the zipped iterators have unrelated system tags\n \/\/ force both iterators' system tags to DerivedPolicy\n thrust::transform(exec,\n thrust::reinterpret_tag(first), thrust::reinterpret_tag(first + n),\n thrust::reinterpret_tag(result),\n thrust::identity());\n#endif\n}\n\n\ntemplate\nvoid trivial_copy_n(cross_system &systems,\n RandomAccessIterator1 first,\n Size n,\n RandomAccessIterator2 result)\n{\n typedef typename thrust::iterator_value::type T;\n\n void *dst = thrust::raw_pointer_cast(&*result);\n const void *src = thrust::raw_pointer_cast(&*first);\n\n cudaMemcpyKind kind = trivial_copy_detail::cuda_memcpy_kind(thrust::detail::derived_cast(systems.system1), thrust::detail::derived_cast(systems.system2));\n\n throw_on_error(cudaMemcpy(dst, src, n * sizeof(T), kind), \"cudaMemcpy in trivial_copy_n\");\n}\n\n\n} \/\/ end namespace detail\n} \/\/ end namespace cuda\n} \/\/ end namespace system\n} \/\/ end namespace thrust\n\nAdd missing #include\/*\n * Copyright 2008-2012 NVIDIA Corporation\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#pragma once\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nnamespace thrust\n{\nnamespace system\n{\nnamespace cuda\n{\nnamespace detail\n{\nnamespace trivial_copy_detail\n{\n\n\ntemplate\n cudaMemcpyKind cuda_memcpy_kind(const thrust::cuda::execution_policy &,\n const thrust::cpp::execution_policy &)\n{\n return cudaMemcpyDeviceToHost;\n} \/\/ end cuda_memcpy_kind()\n\n\ntemplate\n cudaMemcpyKind cuda_memcpy_kind(const thrust::cpp::execution_policy &,\n const thrust::cuda::execution_policy &)\n{\n return cudaMemcpyHostToDevice;\n} \/\/ end cuda_memcpy_kind()\n\n\n} \/\/ end namespace trivial_copy_detail\n\n\ntemplate\n__host__ __device__\nvoid trivial_copy_n(execution_policy &exec,\n RandomAccessIterator1 first,\n Size n,\n RandomAccessIterator2 result)\n{\n typedef typename thrust::iterator_value::type T;\n\n#ifndef __CUDA_ARCH__\n void *dst = thrust::raw_pointer_cast(&*result);\n const void *src = thrust::raw_pointer_cast(&*first);\n\n throw_on_error(cudaMemcpy(dst, src, n * sizeof(T), cudaMemcpyDeviceToDevice), \"cudaMemcpy in trivial_copy_n\");\n#else\n \/\/ XXX transform is implemented with zip_iterator, which freaks out when the zipped iterators have unrelated system tags\n \/\/ force both iterators' system tags to DerivedPolicy\n thrust::transform(exec,\n thrust::reinterpret_tag(first), thrust::reinterpret_tag(first + n),\n thrust::reinterpret_tag(result),\n thrust::identity());\n#endif\n}\n\n\ntemplate\nvoid trivial_copy_n(cross_system &systems,\n RandomAccessIterator1 first,\n Size n,\n RandomAccessIterator2 result)\n{\n typedef typename thrust::iterator_value::type T;\n\n void *dst = thrust::raw_pointer_cast(&*result);\n const void *src = thrust::raw_pointer_cast(&*first);\n\n cudaMemcpyKind kind = trivial_copy_detail::cuda_memcpy_kind(thrust::detail::derived_cast(systems.system1), thrust::detail::derived_cast(systems.system2));\n\n throw_on_error(cudaMemcpy(dst, src, n * sizeof(T), kind), \"cudaMemcpy in trivial_copy_n\");\n}\n\n\n} \/\/ end namespace detail\n} \/\/ end namespace cuda\n} \/\/ end namespace system\n} \/\/ end namespace thrust\n\n<|endoftext|>"} {"text":"\/*\n** Copyright 2011 Merethis\n** This file is part of Centreon Broker.\n**\n** Centreon Broker is free software: you can redistribute it and\/or\n** modify it under the terms of the GNU General Public License version 2\n** as published by the Free Software Foundation.\n**\n** Centreon Broker is distributed in the hope that it will be useful,\n** but WITHOUT ANY WARRANTY; without even the implied warranty of\n** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n** General Public License for more details.\n**\n** You should have received a copy of the GNU General Public License\n** along with Centreon Broker. If not, see\n** .\n*\/\n\n#include \n#include \"com\/centreon\/broker\/exceptions\/msg.hh\"\n#include \"com\/centreon\/broker\/storage\/connector.hh\"\n#include \"com\/centreon\/broker\/storage\/factory.hh\"\n\nusing namespace com::centreon::broker;\nusing namespace com::centreon::broker::storage;\n\n\/**************************************\n* *\n* Static Objects *\n* *\n**************************************\/\n\n\/**\n * Find a parameter in configuration.\n *\n * @param[in] cfg Configuration object.\n * @param[in] key Property to get.\n *\n * @return Property value.\n *\/\nstatic QString const& find_param(config::endpoint const& cfg,\n QString const& key) {\n QMap::const_iterator it(cfg.params.find(key));\n if (cfg.params.end() == it)\n throw (exceptions::msg() << \"storage: no '\" << key\n\t << \"' defined for endpoint '\" << cfg.name << \"'\");\n return (it.value());\n}\n\n\/**************************************\n* *\n* Public Methods *\n* *\n**************************************\/\n\n\/**\n * Default constructor.\n *\/\nfactory::factory() {}\n\n\/**\n * Copy constructor.\n *\n * @param[in] f Object to copy.\n *\/\nfactory::factory(factory const& f) : io::factory(f) {}\n\n\/**\n * Destructor.\n *\/\nfactory::~factory() {}\n\n\/**\n * Assignment operator.\n *\n * @param[in] f Object to copy.\n *\n * @return This object.\n *\/\nfactory& factory::operator=(factory const& f) {\n io::factory::operator=(f);\n return (*this);\n}\n\n\/**\n * Clone this object.\n *\n * @return Exact copy of this factory.\n *\/\nio::factory* factory::clone() const {\n return (new factory(*this));\n}\n\n\/**\n * Check if a configuration match the storage layer.\n *\n * @param[in] cfg Endpoint configuration.\n * @param[in] is_input true if endpoint should act as input.\n * @param[in] is_output true if endpoint should act as output.\n *\n * @return true if the configuration matches the storage layer.\n *\/\nbool factory::has_endpoint(config::endpoint const& cfg, \n bool is_input,\n bool is_output) const {\n (void)is_input;\n (void)is_output;\n return (cfg.type == \"storage\");\n}\n\n\/**\n * Build a storage endpoint from a configuration.\n *\n * @param[in] cfg Endpoint configuration.\n * @param[in] is_input true if endpoint should act as input.\n * @param[in] is_output true if endpoint should act as output.\n * @param[out] is_acceptor Will be set to false.\n *\n * @return Endpoint matching the given configuration.\n *\/\nio::endpoint* factory::new_endpoint(config::endpoint const& cfg,\n bool is_input,\n bool is_output,\n bool& is_acceptor) const {\n (void)is_output;\n\n \/\/ Check that endpoint should not be an input.\n if (is_input)\n throw (exceptions::msg()\n << \"storage: cannot create an input endpoint\");\n\n \/\/ Find lengths.\n unsigned int interval_length(find_param(cfg, \"interval\").toUInt());\n unsigned int rrd_length(find_param(cfg, \"length\").toUInt());\n\n \/\/ Find storage DB parameters.\n QString type(find_param(cfg, \"db_type\"));\n QString host(find_param(cfg, \"db_host\"));\n unsigned short port(find_param(cfg, \"db_port\").toUShort());\n QString user(find_param(cfg, \"db_user\"));\n QString password(find_param(cfg, \"db_password\"));\n QString name(find_param(cfg, \"db_name\"));\n\n \/\/ Connector.\n QScopedPointer c(new storage::connector);\n c->connect_to(type,\n host,\n port,\n user,\n password,\n name,\n rrd_length,\n interval_length);\n is_acceptor = false;\n return (c.take());\n}\nFix configuration parsing in storage module.\/*\n** Copyright 2011 Merethis\n** This file is part of Centreon Broker.\n**\n** Centreon Broker is free software: you can redistribute it and\/or\n** modify it under the terms of the GNU General Public License version 2\n** as published by the Free Software Foundation.\n**\n** Centreon Broker is distributed in the hope that it will be useful,\n** but WITHOUT ANY WARRANTY; without even the implied warranty of\n** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n** General Public License for more details.\n**\n** You should have received a copy of the GNU General Public License\n** along with Centreon Broker. If not, see\n** .\n*\/\n\n#include \n#include \"com\/centreon\/broker\/exceptions\/msg.hh\"\n#include \"com\/centreon\/broker\/storage\/connector.hh\"\n#include \"com\/centreon\/broker\/storage\/factory.hh\"\n\nusing namespace com::centreon::broker;\nusing namespace com::centreon::broker::storage;\n\n\/**************************************\n* *\n* Static Objects *\n* *\n**************************************\/\n\n\/**\n * Find a parameter in configuration.\n *\n * @param[in] cfg Configuration object.\n * @param[in] key Property to get.\n *\n * @return Property value.\n *\/\nstatic QString const& find_param(config::endpoint const& cfg,\n QString const& key) {\n QMap::const_iterator it(cfg.params.find(key));\n if (cfg.params.end() == it)\n throw (exceptions::msg() << \"storage: no '\" << key\n\t << \"' defined for endpoint '\" << cfg.name << \"'\");\n return (it.value());\n}\n\n\/**************************************\n* *\n* Public Methods *\n* *\n**************************************\/\n\n\/**\n * Default constructor.\n *\/\nfactory::factory() {}\n\n\/**\n * Copy constructor.\n *\n * @param[in] f Object to copy.\n *\/\nfactory::factory(factory const& f) : io::factory(f) {}\n\n\/**\n * Destructor.\n *\/\nfactory::~factory() {}\n\n\/**\n * Assignment operator.\n *\n * @param[in] f Object to copy.\n *\n * @return This object.\n *\/\nfactory& factory::operator=(factory const& f) {\n io::factory::operator=(f);\n return (*this);\n}\n\n\/**\n * Clone this object.\n *\n * @return Exact copy of this factory.\n *\/\nio::factory* factory::clone() const {\n return (new factory(*this));\n}\n\n\/**\n * Check if a configuration match the storage layer.\n *\n * @param[in] cfg Endpoint configuration.\n * @param[in] is_input true if endpoint should act as input.\n * @param[in] is_output true if endpoint should act as output.\n *\n * @return true if the configuration matches the storage layer.\n *\/\nbool factory::has_endpoint(config::endpoint const& cfg, \n bool is_input,\n bool is_output) const {\n (void)is_input;\n return (is_output && (cfg.type == \"storage\"));\n}\n\n\/**\n * Build a storage endpoint from a configuration.\n *\n * @param[in] cfg Endpoint configuration.\n * @param[in] is_input true if endpoint should act as input.\n * @param[in] is_output true if endpoint should act as output.\n * @param[out] is_acceptor Will be set to false.\n *\n * @return Endpoint matching the given configuration.\n *\/\nio::endpoint* factory::new_endpoint(config::endpoint const& cfg,\n bool is_input,\n bool is_output,\n bool& is_acceptor) const {\n (void)is_input;\n (void)is_output;\n\n \/\/ Find lengths.\n unsigned int interval_length(find_param(cfg, \"interval\").toUInt());\n unsigned int rrd_length(find_param(cfg, \"length\").toUInt());\n\n \/\/ Find storage DB parameters.\n QString type(find_param(cfg, \"db_type\"));\n QString host(find_param(cfg, \"db_host\"));\n unsigned short port(find_param(cfg, \"db_port\").toUShort());\n QString user(find_param(cfg, \"db_user\"));\n QString password(find_param(cfg, \"db_password\"));\n QString name(find_param(cfg, \"db_name\"));\n\n \/\/ Connector.\n QScopedPointer c(new storage::connector);\n c->connect_to(type,\n host,\n port,\n user,\n password,\n name,\n rrd_length,\n interval_length);\n is_acceptor = false;\n return (c.take());\n}\n<|endoftext|>"} {"text":"\/*******************************************************************************\n * Copyright (c) 2015 Matthijs Kooijman\n * All rights reserved. This program and the accompanying materials\n * are made available under the terms of the Eclipse Public License v1.0\n * which accompanies this distribution, and is available at\n * http:\/\/www.eclipse.org\/legal\/epl-v10.html\n *\n * This the HAL to run LMIC on top of the Arduino environment.\n *******************************************************************************\/\n\n#include \n#include \n#include \"..\/lmic.h\"\n#include \"hal.h\"\n#include \n\n\/\/ -----------------------------------------------------------------------------\n\/\/ I\/O\n\nstatic void hal_io_init () {\n \/\/ NSS and DIO0 are required, DIO1 is required for LoRa, DIO2 for FSK\n ASSERT(lmic_pins.nss != LMIC_UNUSED_PIN);\n ASSERT(lmic_pins.dio[0] != LMIC_UNUSED_PIN);\n ASSERT(lmic_pins.dio[1] != LMIC_UNUSED_PIN || lmic_pins.dio[2] != LMIC_UNUSED_PIN);\n\n pinMode(lmic_pins.nss, OUTPUT);\n if (lmic_pins.rxtx != LMIC_UNUSED_PIN)\n pinMode(lmic_pins.rxtx, OUTPUT);\n if (lmic_pins.rst != LMIC_UNUSED_PIN)\n pinMode(lmic_pins.rst, OUTPUT);\n\n pinMode(lmic_pins.dio[0], INPUT);\n if (lmic_pins.dio[1] != LMIC_UNUSED_PIN)\n pinMode(lmic_pins.dio[1], INPUT);\n if (lmic_pins.dio[2] != LMIC_UNUSED_PIN)\n pinMode(lmic_pins.dio[2], INPUT);\n}\n\n\/\/ val == 1 => tx 1\nvoid hal_pin_rxtx (u1_t val) {\n if (lmic_pins.rxtx != LMIC_UNUSED_PIN)\n digitalWrite(lmic_pins.rxtx, val);\n}\n\n\/\/ set radio RST pin to given value (or keep floating!)\nvoid hal_pin_rst (u1_t val) {\n if (lmic_pins.rst == LMIC_UNUSED_PIN)\n return;\n\n if(val == 0 || val == 1) { \/\/ drive pin\n pinMode(lmic_pins.rst, OUTPUT);\n digitalWrite(lmic_pins.rst, val);\n } else { \/\/ keep pin floating\n pinMode(lmic_pins.rst, INPUT);\n }\n}\n\nstatic bool dio_states[NUM_DIO] = {0};\n\nstatic void hal_io_check() {\n uint8_t i;\n for (i = 0; i < NUM_DIO; ++i) {\n if (lmic_pins.dio[i] == LMIC_UNUSED_PIN)\n continue;\n\n if (dio_states[i] != digitalRead(lmic_pins.dio[i])) {\n dio_states[i] = !dio_states[i];\n if (dio_states[i])\n radio_irq_handler(i);\n }\n }\n}\n\n\/\/ -----------------------------------------------------------------------------\n\/\/ SPI\n\nstatic const SPISettings settings(10E6, MSBFIRST, SPI_MODE0);\n\nstatic void hal_spi_init () {\n SPI.begin();\n}\n\nvoid hal_pin_nss (u1_t val) {\n if (!val)\n SPI.beginTransaction(settings);\n else\n SPI.endTransaction();\n\n \/\/Serial.println(val?\">>\":\"<<\");\n digitalWrite(lmic_pins.nss, val);\n}\n\n\/\/ perform SPI transaction with radio\nu1_t hal_spi (u1_t out) {\n u1_t res = SPI.transfer(out);\n\/*\n Serial.print(\">\");\n Serial.print(out, HEX);\n Serial.print(\"<\");\n Serial.println(res, HEX);\n *\/\n return res;\n}\n\n\/\/ -----------------------------------------------------------------------------\n\/\/ TIME\n\nstatic void hal_time_init () {\n \/\/ Nothing to do\n}\n\nu4_t hal_ticks () {\n \/\/ Because micros() is scaled down in this function, micros() will\n \/\/ overflow before the tick timer should, causing the tick timer to\n \/\/ miss a significant part of its values if not corrected. To fix\n \/\/ this, the \"overflow\" serves as an overflow area for the micros()\n \/\/ counter. It consists of three parts:\n \/\/ - The US_PER_OSTICK upper bits are effectively an extension for\n \/\/ the micros() counter and are added to the result of this\n \/\/ function.\n \/\/ - The next bit overlaps with the most significant bit of\n \/\/ micros(). This is used to detect micros() overflows.\n \/\/ - The remaining bits are always zero.\n \/\/\n \/\/ By comparing the overlapping bit with the corresponding bit in\n \/\/ the micros() return value, overflows can be detected and the\n \/\/ upper bits are incremented. This is done using some clever\n \/\/ bitwise operations, to remove the need for comparisons and a\n \/\/ jumps, which should result in efficient code. By avoiding shifts\n \/\/ other than by multiples of 8 as much as possible, this is also\n \/\/ efficient on AVR (which only has 1-bit shifts).\n static uint8_t overflow = 0;\n\n \/\/ Scaled down timestamp. The top US_PER_OSTICK_EXPONENT bits are 0,\n \/\/ the others will be the lower bits of our return value.\n uint32_t scaled = micros() >> US_PER_OSTICK_EXPONENT;\n \/\/ Most significant byte of scaled\n uint8_t msb = scaled >> 24;\n \/\/ Mask pointing to the overlapping bit in msb and overflow.\n const uint8_t mask = (1 << (7 - US_PER_OSTICK_EXPONENT));\n \/\/ Update overflow. If the overlapping bit is different\n \/\/ between overflow and msb, it is added to the stored value,\n \/\/ so the overlapping bit becomes equal again and, if it changed\n \/\/ from 1 to 0, the upper bits are incremented.\n overflow += (msb ^ overflow) & mask;\n\n \/\/ Return the scaled value with the upper bits of stored added. The\n \/\/ overlapping bit will be equal and the lower bits will be 0, so\n \/\/ bitwise or is a no-op for them.\n return scaled | ((uint32_t)overflow << 24);\n\n \/\/ 0 leads to correct, but overly complex code (it could just return\n \/\/ micros() unmodified), 8 leaves no room for the overlapping bit.\n static_assert(US_PER_OSTICK_EXPONENT > 0 && US_PER_OSTICK_EXPONENT < 8, \"Invalid US_PER_OSTICK_EXPONENT value\");\n}\n\n\/\/ Returns the number of ticks until time. Negative values indicate that\n\/\/ time has already passed.\nstatic s4_t delta_time(u4_t time) {\n return (s4_t)(time - hal_ticks());\n}\n\nvoid hal_waitUntil (u4_t time) {\n s4_t delta = delta_time(time);\n \/\/ From delayMicroseconds docs: Currently, the largest value that\n \/\/ will produce an accurate delay is 16383.\n while (delta > (16000 \/ US_PER_OSTICK)) {\n delay(16);\n delta -= (16000 \/ US_PER_OSTICK);\n }\n if (delta > 0)\n delayMicroseconds(delta * US_PER_OSTICK);\n}\n\n\/\/ check and rewind for target time\nu1_t hal_checkTimer (u4_t time) {\n \/\/ No need to schedule wakeup, since we're not sleeping\n return delta_time(time) <= 0;\n}\n\nstatic uint8_t irqlevel = 0;\n\nvoid hal_disableIRQs () {\n noInterrupts();\n irqlevel++;\n}\n\nvoid hal_enableIRQs () {\n if(--irqlevel == 0) {\n interrupts();\n\n \/\/ Instead of using proper interrupts (which are a bit tricky\n \/\/ and\/or not available on all pins on AVR), just poll the pin\n \/\/ values. Since os_runloop disables and re-enables interrupts,\n \/\/ putting this here makes sure we check at least once every\n \/\/ loop.\n \/\/\n \/\/ As an additional bonus, this prevents the can of worms that\n \/\/ we would otherwise get for running SPI transfers inside ISRs\n hal_io_check();\n }\n}\n\nvoid hal_sleep () {\n \/\/ Not implemented\n}\n\n\/\/ -----------------------------------------------------------------------------\n\n#if defined(LMIC_PRINTF_TO)\nstatic int uart_putchar (char c, FILE *)\n{\n LMIC_PRINTF_TO.write(c) ;\n return 0 ;\n}\n\nvoid hal_printf_init() {\n \/\/ create a FILE structure to reference our UART output function\n static FILE uartout;\n memset(&uartout, 0, sizeof(uartout));\n\n \/\/ fill in the UART file descriptor with pointer to writer.\n fdev_setup_stream (&uartout, uart_putchar, NULL, _FDEV_SETUP_WRITE);\n\n \/\/ The uart is the standard output device STDOUT.\n stdout = &uartout ;\n}\n#endif \/\/ defined(LMIC_PRINTF_TO)\n\nvoid hal_init () {\n \/\/ configure radio I\/O and interrupt handler\n hal_io_init();\n \/\/ configure radio SPI\n hal_spi_init();\n \/\/ configure timer and interrupt handler\n hal_time_init();\n#if defined(LMIC_PRINTF_TO)\n \/\/ printf support\n hal_printf_init();\n#endif\n}\n\nvoid hal_failed (const char *file, u2_t line) {\n#if defined(LMIC_FAILURE_TO)\n LMIC_FAILURE_TO.println(\"FAILURE \");\n LMIC_FAILURE_TO.print(file);\n LMIC_FAILURE_TO.print(':');\n LMIC_FAILURE_TO.println(line);\n LMIC_FAILURE_TO.flush();\n#endif\n hal_disableIRQs();\n while(1);\n}\nMake default SPI freq 1MHz\/*******************************************************************************\n * Copyright (c) 2015 Matthijs Kooijman\n * All rights reserved. This program and the accompanying materials\n * are made available under the terms of the Eclipse Public License v1.0\n * which accompanies this distribution, and is available at\n * http:\/\/www.eclipse.org\/legal\/epl-v10.html\n *\n * This the HAL to run LMIC on top of the Arduino environment.\n *******************************************************************************\/\n\n#include \n#include \n#include \"..\/lmic.h\"\n#include \"hal.h\"\n#include \n\n\/\/ -----------------------------------------------------------------------------\n\/\/ I\/O\n\nstatic void hal_io_init () {\n \/\/ NSS and DIO0 are required, DIO1 is required for LoRa, DIO2 for FSK\n ASSERT(lmic_pins.nss != LMIC_UNUSED_PIN);\n ASSERT(lmic_pins.dio[0] != LMIC_UNUSED_PIN);\n ASSERT(lmic_pins.dio[1] != LMIC_UNUSED_PIN || lmic_pins.dio[2] != LMIC_UNUSED_PIN);\n\n pinMode(lmic_pins.nss, OUTPUT);\n if (lmic_pins.rxtx != LMIC_UNUSED_PIN)\n pinMode(lmic_pins.rxtx, OUTPUT);\n if (lmic_pins.rst != LMIC_UNUSED_PIN)\n pinMode(lmic_pins.rst, OUTPUT);\n\n pinMode(lmic_pins.dio[0], INPUT);\n if (lmic_pins.dio[1] != LMIC_UNUSED_PIN)\n pinMode(lmic_pins.dio[1], INPUT);\n if (lmic_pins.dio[2] != LMIC_UNUSED_PIN)\n pinMode(lmic_pins.dio[2], INPUT);\n}\n\n\/\/ val == 1 => tx 1\nvoid hal_pin_rxtx (u1_t val) {\n if (lmic_pins.rxtx != LMIC_UNUSED_PIN)\n digitalWrite(lmic_pins.rxtx, val);\n}\n\n\/\/ set radio RST pin to given value (or keep floating!)\nvoid hal_pin_rst (u1_t val) {\n if (lmic_pins.rst == LMIC_UNUSED_PIN)\n return;\n\n if(val == 0 || val == 1) { \/\/ drive pin\n pinMode(lmic_pins.rst, OUTPUT);\n digitalWrite(lmic_pins.rst, val);\n } else { \/\/ keep pin floating\n pinMode(lmic_pins.rst, INPUT);\n }\n}\n\nstatic bool dio_states[NUM_DIO] = {0};\n\nstatic void hal_io_check() {\n uint8_t i;\n for (i = 0; i < NUM_DIO; ++i) {\n if (lmic_pins.dio[i] == LMIC_UNUSED_PIN)\n continue;\n\n if (dio_states[i] != digitalRead(lmic_pins.dio[i])) {\n dio_states[i] = !dio_states[i];\n if (dio_states[i])\n radio_irq_handler(i);\n }\n }\n}\n\n\/\/ -----------------------------------------------------------------------------\n\/\/ SPI\n\nstatic const SPISettings settings(1E6, MSBFIRST, SPI_MODE0);\n\nstatic void hal_spi_init () {\n SPI.begin();\n}\n\nvoid hal_pin_nss (u1_t val) {\n if (!val)\n SPI.beginTransaction(settings);\n else\n SPI.endTransaction();\n\n \/\/Serial.println(val?\">>\":\"<<\");\n digitalWrite(lmic_pins.nss, val);\n}\n\n\/\/ perform SPI transaction with radio\nu1_t hal_spi (u1_t out) {\n u1_t res = SPI.transfer(out);\n\/*\n Serial.print(\">\");\n Serial.print(out, HEX);\n Serial.print(\"<\");\n Serial.println(res, HEX);\n *\/\n return res;\n}\n\n\/\/ -----------------------------------------------------------------------------\n\/\/ TIME\n\nstatic void hal_time_init () {\n \/\/ Nothing to do\n}\n\nu4_t hal_ticks () {\n \/\/ Because micros() is scaled down in this function, micros() will\n \/\/ overflow before the tick timer should, causing the tick timer to\n \/\/ miss a significant part of its values if not corrected. To fix\n \/\/ this, the \"overflow\" serves as an overflow area for the micros()\n \/\/ counter. It consists of three parts:\n \/\/ - The US_PER_OSTICK upper bits are effectively an extension for\n \/\/ the micros() counter and are added to the result of this\n \/\/ function.\n \/\/ - The next bit overlaps with the most significant bit of\n \/\/ micros(). This is used to detect micros() overflows.\n \/\/ - The remaining bits are always zero.\n \/\/\n \/\/ By comparing the overlapping bit with the corresponding bit in\n \/\/ the micros() return value, overflows can be detected and the\n \/\/ upper bits are incremented. This is done using some clever\n \/\/ bitwise operations, to remove the need for comparisons and a\n \/\/ jumps, which should result in efficient code. By avoiding shifts\n \/\/ other than by multiples of 8 as much as possible, this is also\n \/\/ efficient on AVR (which only has 1-bit shifts).\n static uint8_t overflow = 0;\n\n \/\/ Scaled down timestamp. The top US_PER_OSTICK_EXPONENT bits are 0,\n \/\/ the others will be the lower bits of our return value.\n uint32_t scaled = micros() >> US_PER_OSTICK_EXPONENT;\n \/\/ Most significant byte of scaled\n uint8_t msb = scaled >> 24;\n \/\/ Mask pointing to the overlapping bit in msb and overflow.\n const uint8_t mask = (1 << (7 - US_PER_OSTICK_EXPONENT));\n \/\/ Update overflow. If the overlapping bit is different\n \/\/ between overflow and msb, it is added to the stored value,\n \/\/ so the overlapping bit becomes equal again and, if it changed\n \/\/ from 1 to 0, the upper bits are incremented.\n overflow += (msb ^ overflow) & mask;\n\n \/\/ Return the scaled value with the upper bits of stored added. The\n \/\/ overlapping bit will be equal and the lower bits will be 0, so\n \/\/ bitwise or is a no-op for them.\n return scaled | ((uint32_t)overflow << 24);\n\n \/\/ 0 leads to correct, but overly complex code (it could just return\n \/\/ micros() unmodified), 8 leaves no room for the overlapping bit.\n static_assert(US_PER_OSTICK_EXPONENT > 0 && US_PER_OSTICK_EXPONENT < 8, \"Invalid US_PER_OSTICK_EXPONENT value\");\n}\n\n\/\/ Returns the number of ticks until time. Negative values indicate that\n\/\/ time has already passed.\nstatic s4_t delta_time(u4_t time) {\n return (s4_t)(time - hal_ticks());\n}\n\nvoid hal_waitUntil (u4_t time) {\n s4_t delta = delta_time(time);\n \/\/ From delayMicroseconds docs: Currently, the largest value that\n \/\/ will produce an accurate delay is 16383.\n while (delta > (16000 \/ US_PER_OSTICK)) {\n delay(16);\n delta -= (16000 \/ US_PER_OSTICK);\n }\n if (delta > 0)\n delayMicroseconds(delta * US_PER_OSTICK);\n}\n\n\/\/ check and rewind for target time\nu1_t hal_checkTimer (u4_t time) {\n \/\/ No need to schedule wakeup, since we're not sleeping\n return delta_time(time) <= 0;\n}\n\nstatic uint8_t irqlevel = 0;\n\nvoid hal_disableIRQs () {\n noInterrupts();\n irqlevel++;\n}\n\nvoid hal_enableIRQs () {\n if(--irqlevel == 0) {\n interrupts();\n\n \/\/ Instead of using proper interrupts (which are a bit tricky\n \/\/ and\/or not available on all pins on AVR), just poll the pin\n \/\/ values. Since os_runloop disables and re-enables interrupts,\n \/\/ putting this here makes sure we check at least once every\n \/\/ loop.\n \/\/\n \/\/ As an additional bonus, this prevents the can of worms that\n \/\/ we would otherwise get for running SPI transfers inside ISRs\n hal_io_check();\n }\n}\n\nvoid hal_sleep () {\n \/\/ Not implemented\n}\n\n\/\/ -----------------------------------------------------------------------------\n\n#if defined(LMIC_PRINTF_TO)\nstatic int uart_putchar (char c, FILE *)\n{\n LMIC_PRINTF_TO.write(c) ;\n return 0 ;\n}\n\nvoid hal_printf_init() {\n \/\/ create a FILE structure to reference our UART output function\n static FILE uartout;\n memset(&uartout, 0, sizeof(uartout));\n\n \/\/ fill in the UART file descriptor with pointer to writer.\n fdev_setup_stream (&uartout, uart_putchar, NULL, _FDEV_SETUP_WRITE);\n\n \/\/ The uart is the standard output device STDOUT.\n stdout = &uartout ;\n}\n#endif \/\/ defined(LMIC_PRINTF_TO)\n\nvoid hal_init () {\n \/\/ configure radio I\/O and interrupt handler\n hal_io_init();\n \/\/ configure radio SPI\n hal_spi_init();\n \/\/ configure timer and interrupt handler\n hal_time_init();\n#if defined(LMIC_PRINTF_TO)\n \/\/ printf support\n hal_printf_init();\n#endif\n}\n\nvoid hal_failed (const char *file, u2_t line) {\n#if defined(LMIC_FAILURE_TO)\n LMIC_FAILURE_TO.println(\"FAILURE \");\n LMIC_FAILURE_TO.print(file);\n LMIC_FAILURE_TO.print(':');\n LMIC_FAILURE_TO.println(line);\n LMIC_FAILURE_TO.flush();\n#endif\n hal_disableIRQs();\n while(1);\n}\n<|endoftext|>"} {"text":"\/*===================================================================\n\nThe Medical Imaging Interaction Toolkit (MITK)\n\nCopyright (c) German Cancer Research Center,\nDivision of Medical and Biological Informatics.\nAll rights reserved.\n\nThis software is distributed WITHOUT ANY WARRANTY; without\neven the implied warranty of MERCHANTABILITY or FITNESS FOR\nA PARTICULAR PURPOSE.\n\nSee LICENSE.txt or http:\/\/www.mitk.org for details.\n\n===================================================================*\/\n\n#include \n#include \n#include \n#include \n#include \n\n\/**Documentation\n * test for the class \"mitkTractAnalyzer\".\n *\/\nint mitkTractAnalyzerTest(int argc , char* argv[])\n{\n\n MITK_TEST_BEGIN(\"TractAnalyzer\");\n\n \/\/ Load image\n typedef itk::Image FloatImageType;\n typedef itk::ImageFileReader ImageReaderType;\n\n ImageReaderType::Pointer reader = ImageReaderType::New();\n\n reader->SetFileName(argv[1]);\n reader->Update();\n FloatImageType::Pointer itkImage = reader->GetOutput();\n mitk::Image::Pointer mitkImage = mitk::Image::New();\n\n mitk::CastToMitkImage(itkImage, mitkImage);\n\n\n \/\/ load point set\n\n mitk::PointSetReader::Pointer pointSetReader = mitk::PointSetReader::New();\n pointSetReader->SetFileName(argv[2]);\n pointSetReader->Update();\n\n mitk::PointSet::Pointer pointSet = pointSetReader->GetOutput();\n\n\n\n mitk::TractAnalyzer analyzer;\n\n analyzer.SetInputImage(mitkImage);\n analyzer.SetThreshold(0.2);\n analyzer.SetPointSet(pointSet);\n analyzer.MakeRoi();\n\n mitk::TbssRoiImage::Pointer tbssRoi = analyzer.GetRoiImage();\n\n\n\n \/\/ load reference roi\n mitk::NrrdTbssRoiImageReader::Pointer roiReader = mitk::NrrdTbssRoiImageReader::New();\n roiReader->SetFileName(argv[3]);\n roiReader->Update();\n\n mitk::TbssRoiImage* referenceRoi = roiReader->GetOutput(0);\n\n\n \/\/ compare point sets of tbssRoi and reference roi\n\n std::vector< itk::Index<3> > roi = tbssRoi->GetRoi();\n std::vector< itk::Index<3> > refRoi = referenceRoi->GetRoi();\n\n bool equalSize(roi.size() == refRoi.size());\n MITK_TEST_CONDITION(equalSize, \"Size of skeleton and control skeleton are the same.\");\n\n\n\n if(equalSize)\n {\n bool samePath = true;\n for(int t=0; t ix = roi.at(t);\n itk::Index<3> refIx = refRoi.at(t);\n\n if(ix != refIx)\n {\n samePath = false;\n }\n }\n\n MITK_TEST_CONDITION(samePath, \"Calculated ROI matches reference ROI.\");\n }\n\n\n MITK_TEST_END();\n}\nCOMP: new macro\/*===================================================================\n\nThe Medical Imaging Interaction Toolkit (MITK)\n\nCopyright (c) German Cancer Research Center,\nDivision of Medical and Biological Informatics.\nAll rights reserved.\n\nThis software is distributed WITHOUT ANY WARRANTY; without\neven the implied warranty of MERCHANTABILITY or FITNESS FOR\nA PARTICULAR PURPOSE.\n\nSee LICENSE.txt or http:\/\/www.mitk.org for details.\n\n===================================================================*\/\n\n#include \n#include \n#include \n#include \n#include \n\n\/**Documentation\n * test for the class \"mitkTractAnalyzer\".\n *\/\nint mitkTractAnalyzerTest(int argc , char* argv[])\n{\n\n MITK_TEST_BEGIN(\"TractAnalyzer\");\n\n \/\/ Load image\n typedef itk::Image FloatImageType;\n typedef itk::ImageFileReader ImageReaderType;\n\n ImageReaderType::Pointer reader = ImageReaderType::New();\n\n reader->SetFileName(argv[1]);\n reader->Update();\n FloatImageType::Pointer itkImage = reader->GetOutput();\n mitk::Image::Pointer mitkImage = mitk::Image::New();\n\n mitk::CastToMitkImage(itkImage, mitkImage);\n\n\n \/\/ load point set\n\n mitk::PointSetReader::Pointer pointSetReader = mitk::PointSetReader::New();\n pointSetReader->SetFileName(argv[2]);\n pointSetReader->Update();\n\n mitk::PointSet::Pointer pointSet = pointSetReader->GetOutput();\n\n\n\n mitk::TractAnalyzer analyzer;\n\n analyzer.SetInputImage(mitkImage);\n analyzer.SetThreshold(0.2);\n analyzer.SetPointSet(pointSet);\n analyzer.MakeRoi();\n\n mitk::TbssRoiImage::Pointer tbssRoi = analyzer.GetRoiImage();\n\n\n\n \/\/ load reference roi\n mitk::NrrdTbssRoiImageReader::Pointer roiReader = mitk::NrrdTbssRoiImageReader::New();\n roiReader->SetFileName(argv[3]);\n roiReader->Update();\n\n mitk::TbssRoiImage* referenceRoi = roiReader->GetOutput(0);\n\n\n \/\/ compare point sets of tbssRoi and reference roi\n\n std::vector< itk::Index<3> > roi = tbssRoi->GetRoi();\n std::vector< itk::Index<3> > refRoi = referenceRoi->GetRoi();\n\n bool equalSize(roi.size() == refRoi.size());\n\n MITK_TEST_EQUAL(roi.size(), refRoi.size(), \"Size of roi and control roi are the same.\");\n\n if(equalSize)\n {\n bool samePath = true;\n for(int t=0; t ix = roi.at(t);\n itk::Index<3> refIx = refRoi.at(t);\n\n if(ix != refIx)\n {\n samePath = false;\n }\n }\n\n MITK_TEST_CONDITION(samePath, \"Calculated ROI matches reference ROI.\");\n }\n\n\n MITK_TEST_END();\n}\n<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * $RCSfile: unocontrolbase.cxx,v $\n *\n * $Revision: 1.3 $\n *\n * last change: $Author: hr $ $Date: 2003-03-27 17:03:21 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#ifndef _COM_SUN_STAR_AWT_XLAYOUTCONSTRAINS_HPP_\n#include \n#endif\n#ifndef _COM_SUN_STAR_AWT_XTEXTLAYOUTCONSTRAINS_HPP_\n#include \n#endif\n\n#include \n#include \n\n#include \n\n\/\/ ----------------------------------------------------\n\/\/ class UnoControlBase\n\/\/ ----------------------------------------------------\n\nsal_Bool UnoControlBase::ImplHasProperty( sal_uInt16 nPropId )\n{\n ::rtl::OUString aPropName( GetPropertyName( nPropId ) );\n return ImplHasProperty( aPropName );\n}\n\nsal_Bool UnoControlBase::ImplHasProperty( const ::rtl::OUString& aPropertyName )\n{\n ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet > xPSet( mxModel, ::com::sun::star::uno::UNO_QUERY );\n ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySetInfo > xInfo = xPSet->getPropertySetInfo();\n return xInfo->hasPropertyByName( aPropertyName );\n}\n\nvoid UnoControlBase::ImplSetPropertyValue( const ::rtl::OUString& aPropertyName, const ::com::sun::star::uno::Any& aValue, sal_Bool bUpdateThis )\n{\n \/\/ Model ggf. schon abgemeldet, aber ein Event schlaegt noch zu...\n if ( mxModel.is() )\n {\n ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet > xPSet( mxModel, ::com::sun::star::uno::UNO_QUERY );\n if ( !bUpdateThis )\n StartUpdatingModel();\n xPSet->setPropertyValue( aPropertyName, aValue );\n if ( !bUpdateThis )\n EndUpdatingModel();\n }\n}\n\n::com::sun::star::uno::Any UnoControlBase::ImplGetPropertyValue( const ::rtl::OUString& aPropertyName )\n{\n ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet > xPSet( mxModel, ::com::sun::star::uno::UNO_QUERY );\n return xPSet->getPropertyValue( aPropertyName );\n}\n\nsal_Bool UnoControlBase::ImplGetPropertyValue_BOOL( sal_uInt16 nProp )\n{\n sal_Bool b = sal_False;\n if ( mxModel.is() )\n {\n ::com::sun::star::uno::Any aVal = ImplGetPropertyValue( GetPropertyName( nProp ) );\n aVal >>= b;\n }\n return b;\n}\n\nsal_Int16 UnoControlBase::ImplGetPropertyValue_INT16( sal_uInt16 nProp )\n{\n sal_Int16 n = 0;\n if ( mxModel.is() )\n {\n ::com::sun::star::uno::Any aVal = ImplGetPropertyValue( GetPropertyName( nProp ) );\n aVal >>= n;\n }\n return n;\n}\n\nsal_uInt16 UnoControlBase::ImplGetPropertyValue_UINT16( sal_uInt16 nProp )\n{\n sal_uInt16 n = 0;\n if ( mxModel.is() )\n {\n ::com::sun::star::uno::Any aVal = ImplGetPropertyValue( GetPropertyName( nProp ) );\n aVal >>= n;\n }\n return n;\n}\n\nsal_Int32 UnoControlBase::ImplGetPropertyValue_INT32( sal_uInt16 nProp )\n{\n sal_Int32 n = 0;\n if ( mxModel.is() )\n {\n ::com::sun::star::uno::Any aVal = ImplGetPropertyValue( GetPropertyName( nProp ) );\n aVal >>= n;\n }\n return n;\n}\n\nsal_uInt32 UnoControlBase::ImplGetPropertyValue_UINT32( sal_uInt16 nProp )\n{\n sal_uInt32 n = 0;\n if ( mxModel.is() )\n {\n ::com::sun::star::uno::Any aVal = ImplGetPropertyValue( GetPropertyName( nProp ) );\n aVal >>= n;\n }\n return n;\n}\n\ndouble UnoControlBase::ImplGetPropertyValue_DOUBLE( sal_uInt16 nProp )\n{\n double n = 0;\n if ( mxModel.is() )\n {\n ::com::sun::star::uno::Any aVal = ImplGetPropertyValue( GetPropertyName( nProp ) );\n aVal >>= n;\n }\n return n;\n}\n\n::rtl::OUString UnoControlBase::ImplGetPropertyValue_UString( sal_uInt16 nProp )\n{\n ::rtl::OUString aStr;\n if ( mxModel.is() )\n {\n ::com::sun::star::uno::Any aVal = ImplGetPropertyValue( GetPropertyName( nProp ) );\n aVal >>= aStr;\n }\n return aStr;\n}\n\n::com::sun::star::awt::Size UnoControlBase::Impl_getMinimumSize()\n{\n ::com::sun::star::awt::Size aSz;\n ::com::sun::star::uno::Reference< ::com::sun::star::awt::XWindowPeer > xP = ImplGetCompatiblePeer( sal_True );\n DBG_ASSERT( xP.is(), \"Layout: No Peer!\" );\n if ( xP.is() )\n {\n ::com::sun::star::uno::Reference< ::com::sun::star::awt::XLayoutConstrains > xL( xP, ::com::sun::star::uno::UNO_QUERY );\n if ( xL.is() )\n aSz = xL->getMinimumSize();\n\n if ( !getPeer().is() || ( getPeer() != xP ) )\n xP->dispose();\n }\n return aSz;\n}\n\n::com::sun::star::awt::Size UnoControlBase::Impl_getPreferredSize()\n{\n ::com::sun::star::awt::Size aSz;\n ::com::sun::star::uno::Reference< ::com::sun::star::awt::XWindowPeer > xP = ImplGetCompatiblePeer( sal_True );\n DBG_ASSERT( xP.is(), \"Layout: No Peer!\" );\n if ( xP.is() )\n {\n ::com::sun::star::uno::Reference< ::com::sun::star::awt::XLayoutConstrains > xL( xP, ::com::sun::star::uno::UNO_QUERY );\n if ( xL.is() )\n aSz = xL->getPreferredSize();\n\n if ( !getPeer().is() || ( getPeer() != xP ) )\n xP->dispose();\n }\n return aSz;\n}\n\n::com::sun::star::awt::Size UnoControlBase::Impl_calcAdjustedSize( const ::com::sun::star::awt::Size& rNewSize )\n{\n ::com::sun::star::awt::Size aSz;\n ::com::sun::star::uno::Reference< ::com::sun::star::awt::XWindowPeer > xP = ImplGetCompatiblePeer( sal_True );\n DBG_ASSERT( xP.is(), \"Layout: No Peer!\" );\n if ( xP.is() )\n {\n ::com::sun::star::uno::Reference< ::com::sun::star::awt::XLayoutConstrains > xL( xP, ::com::sun::star::uno::UNO_QUERY );\n if ( xL.is() )\n aSz = xL->calcAdjustedSize( rNewSize );\n\n if ( !getPeer().is() || ( getPeer() != xP ) )\n xP->dispose();\n }\n return aSz;\n}\n\n::com::sun::star::awt::Size UnoControlBase::Impl_getMinimumSize( sal_Int16 nCols, sal_Int16 nLines )\n{\n ::com::sun::star::awt::Size aSz;\n ::com::sun::star::uno::Reference< ::com::sun::star::awt::XWindowPeer > xP = ImplGetCompatiblePeer( sal_True );\n DBG_ASSERT( xP.is(), \"Layout: No Peer!\" );\n if ( xP.is() )\n {\n ::com::sun::star::uno::Reference< ::com::sun::star::awt::XTextLayoutConstrains > xL( xP, ::com::sun::star::uno::UNO_QUERY );\n if ( xL.is() )\n aSz = xL->getMinimumSize( nCols, nLines );\n\n if ( !getPeer().is() || ( getPeer() != xP ) )\n xP->dispose();\n }\n return aSz;\n}\n\nvoid UnoControlBase::Impl_getColumnsAndLines( sal_Int16& nCols, sal_Int16& nLines )\n{\n ::com::sun::star::uno::Reference< ::com::sun::star::awt::XWindowPeer > xP = ImplGetCompatiblePeer( sal_True );\n DBG_ASSERT( xP.is(), \"Layout: No Peer!\" );\n if ( xP.is() )\n {\n ::com::sun::star::uno::Reference< ::com::sun::star::awt::XTextLayoutConstrains > xL( xP, ::com::sun::star::uno::UNO_QUERY );\n if ( xL.is() )\n xL->getColumnsAndLines( nCols, nLines );\n\n if ( !getPeer().is() || ( getPeer() != xP ) )\n xP->dispose();\n }\n}\n\n\n\nINTEGRATION: CWS frmcontrols03 (1.3.128); FILE MERGED 2004\/03\/02 08:05:34 fs 1.3.128.1: #i24387# ImplHasProperty: allow to be called when the model is still NULL\/*************************************************************************\n *\n * $RCSfile: unocontrolbase.cxx,v $\n *\n * $Revision: 1.4 $\n *\n * last change: $Author: rt $ $Date: 2004-05-07 16:17:33 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#ifndef _COM_SUN_STAR_AWT_XLAYOUTCONSTRAINS_HPP_\n#include \n#endif\n#ifndef _COM_SUN_STAR_AWT_XTEXTLAYOUTCONSTRAINS_HPP_\n#include \n#endif\n\n#include \n#include \n\n#include \n\n\/\/ ----------------------------------------------------\n\/\/ class UnoControlBase\n\/\/ ----------------------------------------------------\n\nsal_Bool UnoControlBase::ImplHasProperty( sal_uInt16 nPropId )\n{\n ::rtl::OUString aPropName( GetPropertyName( nPropId ) );\n return ImplHasProperty( aPropName );\n}\n\nsal_Bool UnoControlBase::ImplHasProperty( const ::rtl::OUString& aPropertyName )\n{\n ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet > xPSet( mxModel, ::com::sun::star::uno::UNO_QUERY );\n if ( !xPSet.is() )\n return sal_False;\n ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySetInfo > xInfo = xPSet->getPropertySetInfo();\n if ( !xInfo.is() )\n return sal_False;\n\n return xInfo->hasPropertyByName( aPropertyName );\n}\n\nvoid UnoControlBase::ImplSetPropertyValue( const ::rtl::OUString& aPropertyName, const ::com::sun::star::uno::Any& aValue, sal_Bool bUpdateThis )\n{\n \/\/ Model ggf. schon abgemeldet, aber ein Event schlaegt noch zu...\n if ( mxModel.is() )\n {\n ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet > xPSet( mxModel, ::com::sun::star::uno::UNO_QUERY );\n if ( !bUpdateThis )\n StartUpdatingModel();\n xPSet->setPropertyValue( aPropertyName, aValue );\n if ( !bUpdateThis )\n EndUpdatingModel();\n }\n}\n\n::com::sun::star::uno::Any UnoControlBase::ImplGetPropertyValue( const ::rtl::OUString& aPropertyName )\n{\n ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet > xPSet( mxModel, ::com::sun::star::uno::UNO_QUERY );\n return xPSet->getPropertyValue( aPropertyName );\n}\n\nsal_Bool UnoControlBase::ImplGetPropertyValue_BOOL( sal_uInt16 nProp )\n{\n sal_Bool b = sal_False;\n if ( mxModel.is() )\n {\n ::com::sun::star::uno::Any aVal = ImplGetPropertyValue( GetPropertyName( nProp ) );\n aVal >>= b;\n }\n return b;\n}\n\nsal_Int16 UnoControlBase::ImplGetPropertyValue_INT16( sal_uInt16 nProp )\n{\n sal_Int16 n = 0;\n if ( mxModel.is() )\n {\n ::com::sun::star::uno::Any aVal = ImplGetPropertyValue( GetPropertyName( nProp ) );\n aVal >>= n;\n }\n return n;\n}\n\nsal_uInt16 UnoControlBase::ImplGetPropertyValue_UINT16( sal_uInt16 nProp )\n{\n sal_uInt16 n = 0;\n if ( mxModel.is() )\n {\n ::com::sun::star::uno::Any aVal = ImplGetPropertyValue( GetPropertyName( nProp ) );\n aVal >>= n;\n }\n return n;\n}\n\nsal_Int32 UnoControlBase::ImplGetPropertyValue_INT32( sal_uInt16 nProp )\n{\n sal_Int32 n = 0;\n if ( mxModel.is() )\n {\n ::com::sun::star::uno::Any aVal = ImplGetPropertyValue( GetPropertyName( nProp ) );\n aVal >>= n;\n }\n return n;\n}\n\nsal_uInt32 UnoControlBase::ImplGetPropertyValue_UINT32( sal_uInt16 nProp )\n{\n sal_uInt32 n = 0;\n if ( mxModel.is() )\n {\n ::com::sun::star::uno::Any aVal = ImplGetPropertyValue( GetPropertyName( nProp ) );\n aVal >>= n;\n }\n return n;\n}\n\ndouble UnoControlBase::ImplGetPropertyValue_DOUBLE( sal_uInt16 nProp )\n{\n double n = 0;\n if ( mxModel.is() )\n {\n ::com::sun::star::uno::Any aVal = ImplGetPropertyValue( GetPropertyName( nProp ) );\n aVal >>= n;\n }\n return n;\n}\n\n::rtl::OUString UnoControlBase::ImplGetPropertyValue_UString( sal_uInt16 nProp )\n{\n ::rtl::OUString aStr;\n if ( mxModel.is() )\n {\n ::com::sun::star::uno::Any aVal = ImplGetPropertyValue( GetPropertyName( nProp ) );\n aVal >>= aStr;\n }\n return aStr;\n}\n\n::com::sun::star::awt::Size UnoControlBase::Impl_getMinimumSize()\n{\n ::com::sun::star::awt::Size aSz;\n ::com::sun::star::uno::Reference< ::com::sun::star::awt::XWindowPeer > xP = ImplGetCompatiblePeer( sal_True );\n DBG_ASSERT( xP.is(), \"Layout: No Peer!\" );\n if ( xP.is() )\n {\n ::com::sun::star::uno::Reference< ::com::sun::star::awt::XLayoutConstrains > xL( xP, ::com::sun::star::uno::UNO_QUERY );\n if ( xL.is() )\n aSz = xL->getMinimumSize();\n\n if ( !getPeer().is() || ( getPeer() != xP ) )\n xP->dispose();\n }\n return aSz;\n}\n\n::com::sun::star::awt::Size UnoControlBase::Impl_getPreferredSize()\n{\n ::com::sun::star::awt::Size aSz;\n ::com::sun::star::uno::Reference< ::com::sun::star::awt::XWindowPeer > xP = ImplGetCompatiblePeer( sal_True );\n DBG_ASSERT( xP.is(), \"Layout: No Peer!\" );\n if ( xP.is() )\n {\n ::com::sun::star::uno::Reference< ::com::sun::star::awt::XLayoutConstrains > xL( xP, ::com::sun::star::uno::UNO_QUERY );\n if ( xL.is() )\n aSz = xL->getPreferredSize();\n\n if ( !getPeer().is() || ( getPeer() != xP ) )\n xP->dispose();\n }\n return aSz;\n}\n\n::com::sun::star::awt::Size UnoControlBase::Impl_calcAdjustedSize( const ::com::sun::star::awt::Size& rNewSize )\n{\n ::com::sun::star::awt::Size aSz;\n ::com::sun::star::uno::Reference< ::com::sun::star::awt::XWindowPeer > xP = ImplGetCompatiblePeer( sal_True );\n DBG_ASSERT( xP.is(), \"Layout: No Peer!\" );\n if ( xP.is() )\n {\n ::com::sun::star::uno::Reference< ::com::sun::star::awt::XLayoutConstrains > xL( xP, ::com::sun::star::uno::UNO_QUERY );\n if ( xL.is() )\n aSz = xL->calcAdjustedSize( rNewSize );\n\n if ( !getPeer().is() || ( getPeer() != xP ) )\n xP->dispose();\n }\n return aSz;\n}\n\n::com::sun::star::awt::Size UnoControlBase::Impl_getMinimumSize( sal_Int16 nCols, sal_Int16 nLines )\n{\n ::com::sun::star::awt::Size aSz;\n ::com::sun::star::uno::Reference< ::com::sun::star::awt::XWindowPeer > xP = ImplGetCompatiblePeer( sal_True );\n DBG_ASSERT( xP.is(), \"Layout: No Peer!\" );\n if ( xP.is() )\n {\n ::com::sun::star::uno::Reference< ::com::sun::star::awt::XTextLayoutConstrains > xL( xP, ::com::sun::star::uno::UNO_QUERY );\n if ( xL.is() )\n aSz = xL->getMinimumSize( nCols, nLines );\n\n if ( !getPeer().is() || ( getPeer() != xP ) )\n xP->dispose();\n }\n return aSz;\n}\n\nvoid UnoControlBase::Impl_getColumnsAndLines( sal_Int16& nCols, sal_Int16& nLines )\n{\n ::com::sun::star::uno::Reference< ::com::sun::star::awt::XWindowPeer > xP = ImplGetCompatiblePeer( sal_True );\n DBG_ASSERT( xP.is(), \"Layout: No Peer!\" );\n if ( xP.is() )\n {\n ::com::sun::star::uno::Reference< ::com::sun::star::awt::XTextLayoutConstrains > xL( xP, ::com::sun::star::uno::UNO_QUERY );\n if ( xL.is() )\n xL->getColumnsAndLines( nCols, nLines );\n\n if ( !getPeer().is() || ( getPeer() != xP ) )\n xP->dispose();\n }\n}\n\n\n\n<|endoftext|>"} {"text":"\/*===================================================================\n\nThe Medical Imaging Interaction Toolkit (MITK)\n\nCopyright (c) German Cancer Research Center,\nDivision of Medical and Biological Informatics.\nAll rights reserved.\n\nThis software is distributed WITHOUT ANY WARRANTY; without\neven the implied warranty of MERCHANTABILITY or FITNESS FOR\nA PARTICULAR PURPOSE.\n\nSee LICENSE.txt or http:\/\/www.mitk.org for details.\n\n===================================================================*\/\n\n#include \"mitkGetPropertyService.h\"\n#include \"QmitkAddNewPropertyDialog.h\"\n#include \"QmitkPropertiesPreferencePage.h\"\n#include \"QmitkPropertyItemDelegate.h\"\n#include \"QmitkPropertyItemModel.h\"\n#include \"QmitkPropertyItemSortFilterProxyModel.h\"\n#include \"QmitkPropertyTreeView.h\"\n#include \n#include \n#include \n#include \n#include \n\nconst std::string QmitkPropertyTreeView::VIEW_ID = \"org.mitk.views.properties\";\n\nQmitkPropertyTreeView::QmitkPropertyTreeView()\n : m_Parent(NULL),\n m_PropertyNameChangedTag(0),\n m_PropertyAliases(NULL),\n m_PropertyDescriptions(NULL),\n m_ShowAliasesInDescription(true),\n m_DeveloperMode(false),\n m_ProxyModel(NULL),\n m_Model(NULL),\n m_Delegate(NULL),\n m_Renderer(NULL)\n{\n}\n\nQmitkPropertyTreeView::~QmitkPropertyTreeView()\n{\n}\n\nvoid QmitkPropertyTreeView::CreateQtPartControl(QWidget* parent)\n{\n m_Parent = parent;\n\n m_Controls.setupUi(parent);\n\n m_Controls.propertyListComboBox->addItem(\"independent\");\n\n mitk::IRenderWindowPart* renderWindowPart = this->GetRenderWindowPart();\n\n if (renderWindowPart != NULL)\n {\n QHash renderWindows = renderWindowPart->GetQmitkRenderWindows();\n\n Q_FOREACH(QString renderWindow, renderWindows.keys())\n {\n m_Controls.propertyListComboBox->addItem(renderWindow);\n }\n }\n\n m_Controls.newButton->setEnabled(false);\n\n m_Controls.description->hide();\n m_Controls.propertyListLabel->hide();\n m_Controls.propertyListComboBox->hide();\n m_Controls.newButton->hide();\n\n m_ProxyModel = new QmitkPropertyItemSortFilterProxyModel(m_Controls.treeView);\n m_Model = new QmitkPropertyItemModel(m_ProxyModel);\n\n m_ProxyModel->setSourceModel(m_Model);\n m_ProxyModel->setFilterCaseSensitivity(Qt::CaseInsensitive);\n m_ProxyModel->setSortCaseSensitivity(Qt::CaseInsensitive);\n m_ProxyModel->setDynamicSortFilter(true);\n\n m_Delegate = new QmitkPropertyItemDelegate(m_Controls.treeView);\n\n m_Controls.treeView->setItemDelegateForColumn(1, m_Delegate);\n m_Controls.treeView->setModel(m_ProxyModel);\n m_Controls.treeView->setColumnWidth(0, 160);\n m_Controls.treeView->sortByColumn(0, Qt::AscendingOrder);\n m_Controls.treeView->setSelectionBehavior(QAbstractItemView::SelectRows);\n m_Controls.treeView->setSelectionMode(QAbstractItemView::SingleSelection);\n m_Controls.treeView->setEditTriggers(QAbstractItemView::SelectedClicked | QAbstractItemView::DoubleClicked);\n\n connect(m_Controls.filterLineEdit, SIGNAL(textChanged(const QString&)), this, SLOT(OnFilterTextChanged(const QString&)));\n connect(m_Controls.propertyListComboBox, SIGNAL(currentIndexChanged(int)), this, SLOT(OnPropertyListChanged(int)));\n connect(m_Controls.newButton, SIGNAL(clicked()), this, SLOT(OnAddNewProperty()));\n connect(m_Controls.treeView->selectionModel(), SIGNAL(currentRowChanged(const QModelIndex&, const QModelIndex&)), this, SLOT(OnCurrentRowChanged(const QModelIndex&, const QModelIndex&)));\n connect(m_Model, SIGNAL(modelReset()), this, SLOT(OnModelReset()));\n}\n\nQString QmitkPropertyTreeView::GetPropertyNameOrAlias(const QModelIndex& index)\n{\n QString propertyName;\n\n if (index.isValid())\n {\n QModelIndex current = index;\n\n while (current.isValid())\n {\n QString name = m_ProxyModel->data(m_ProxyModel->index(current.row(), 0, current.parent())).toString();\n\n propertyName.prepend(propertyName.isEmpty()\n ? name\n : name.append('.'));\n\n current = current.parent();\n }\n }\n\n return propertyName;\n}\n\nvoid QmitkPropertyTreeView::OnCurrentRowChanged(const QModelIndex& current, const QModelIndex&)\n{\n if (m_PropertyDescriptions != NULL && current.isValid())\n {\n QString name = this->GetPropertyNameOrAlias(current);\n\n if (!name.isEmpty())\n {\n QString alias;\n bool isTrueName = true;\n\n if (m_PropertyAliases != NULL)\n {\n std::string trueName = m_PropertyAliases->GetPropertyName(name.toStdString());\n\n if (trueName.empty() && !m_SelectionClassName.empty())\n trueName = m_PropertyAliases->GetPropertyName(name.toStdString(), m_SelectionClassName);\n\n if (!trueName.empty())\n {\n alias = name;\n name = QString::fromStdString(trueName);\n isTrueName = false;\n }\n }\n\n QString description = QString::fromStdString(m_PropertyDescriptions->GetDescription(name.toStdString()));\n std::vector aliases;\n\n if (!isTrueName && m_PropertyAliases != NULL)\n {\n aliases = m_PropertyAliases->GetAliases(name.toStdString(), m_SelectionClassName);\n\n if (aliases.empty() && !m_SelectionClassName.empty())\n aliases = m_PropertyAliases->GetAliases(name.toStdString());\n }\n\n if (!description.isEmpty() || !aliases.empty())\n {\n QString customizedDescription;\n\n if (m_ShowAliasesInDescription && !aliases.empty())\n {\n customizedDescription = \"

\" + name + \"<\/h3>\";\n\n std::size_t numAliases = aliases.size();\n std::size_t lastAlias = numAliases - 1;\n\n for (std::size_t i = 0; i < numAliases; ++i)\n {\n customizedDescription += i != lastAlias\n ? \"
\"\n : \"
\";\n\n customizedDescription += QString::fromStdString(aliases[i]) + \"<\/h5>\";\n }\n }\n else\n {\n customizedDescription = \"

\" + name + \"<\/h3>\";\n }\n\n if (!description.isEmpty())\n customizedDescription += description;\n\n m_Controls.description->setText(customizedDescription);\n m_Controls.description->show();\n\n return;\n }\n }\n }\n\n m_Controls.description->hide();\n}\n\nvoid QmitkPropertyTreeView::OnFilterTextChanged(const QString& filter)\n{\n m_ProxyModel->setFilterWildcard(filter);\n\n if (filter.isEmpty())\n m_Controls.treeView->collapseAll();\n else\n m_Controls.treeView->expandAll();\n}\n\nvoid QmitkPropertyTreeView::OnModelReset()\n{\n m_Controls.description->hide();\n}\n\nvoid QmitkPropertyTreeView::OnPreferencesChanged(const berry::IBerryPreferences* preferences)\n{\n bool showAliases = preferences->GetBool(QmitkPropertiesPreferencePage::SHOW_ALIASES, true);\n bool showDescriptions = preferences->GetBool(QmitkPropertiesPreferencePage::SHOW_DESCRIPTIONS, true);\n bool showAliasesInDescription = preferences->GetBool(QmitkPropertiesPreferencePage::SHOW_ALIASES_IN_DESCRIPTION, true);\n bool developerMode = preferences->GetBool(QmitkPropertiesPreferencePage::DEVELOPER_MODE, false);\n\n bool updateAliases = showAliases != (m_PropertyAliases != NULL);\n bool updateDescriptions = showDescriptions != (m_PropertyDescriptions != NULL);\n bool updateAliasesInDescription = showAliasesInDescription != m_ShowAliasesInDescription;\n bool updateDeveloperMode = developerMode != m_DeveloperMode;\n\n if (updateAliases)\n m_PropertyAliases = showAliases\n ? mitk::GetPropertyService()\n : NULL;\n\n if (updateDescriptions)\n m_PropertyDescriptions = showDescriptions\n ? mitk::GetPropertyService()\n : NULL;\n\n if (updateAliasesInDescription)\n m_ShowAliasesInDescription = showAliasesInDescription;\n\n if (updateDescriptions || updateAliasesInDescription)\n {\n QModelIndexList selection = m_Controls.treeView->selectionModel()->selectedRows();\n\n if (!selection.isEmpty())\n this->OnCurrentRowChanged(selection[0], selection[0]);\n }\n\n if (updateDeveloperMode)\n {\n m_DeveloperMode = developerMode;\n\n if (!developerMode)\n m_Controls.propertyListComboBox->setCurrentIndex(0);\n\n m_Controls.propertyListLabel->setVisible(developerMode);\n m_Controls.propertyListComboBox->setVisible(developerMode);\n m_Controls.newButton->setVisible(developerMode);\n }\n\n m_Model->OnPreferencesChanged(preferences);\n}\n\nvoid QmitkPropertyTreeView::OnPropertyNameChanged(const itk::EventObject&)\n{\n mitk::PropertyList* propertyList = m_Model->GetPropertyList();\n\n if (propertyList != NULL)\n {\n mitk::BaseProperty* nameProperty = propertyList->GetProperty(\"name\");\n\n if (nameProperty != NULL)\n {\n std::ostringstream partName;\n partName << \"Properties (\" << nameProperty->GetValueAsString() << ')';\n this->SetPartName(partName.str());\n }\n }\n}\n\nvoid QmitkPropertyTreeView::OnSelectionChanged(berry::IWorkbenchPart::Pointer, const QList& nodes)\n{\n mitk::PropertyList* propertyList = m_Model->GetPropertyList();\n\n if (propertyList != NULL)\n {\n mitk::BaseProperty* nameProperty = propertyList->GetProperty(\"name\");\n\n if (nameProperty != NULL)\n nameProperty->RemoveObserver(m_PropertyNameChangedTag);\n\n m_PropertyNameChangedTag = 0;\n }\n\n if (nodes.empty() || nodes.front().IsNull())\n {\n m_SelectedNode = NULL;\n\n this->SetPartName(\"Properties\");\n m_Model->SetPropertyList(NULL);\n m_Delegate->SetPropertyList(NULL);\n\n m_Controls.newButton->setEnabled(false);\n }\n else\n {\n m_SelectedNode = nodes.front();\n\n QString selectionClassName = m_SelectedNode->GetData() != NULL\n ? m_SelectedNode->GetData()->GetNameOfClass()\n : \"\";\n\n m_SelectionClassName = selectionClassName.toStdString();\n m_Model->SetPropertyList(m_SelectedNode->GetPropertyList(m_Renderer), selectionClassName);\n m_Delegate->SetPropertyList(m_SelectedNode->GetPropertyList(m_Renderer));\n OnPropertyNameChanged(itk::ModifiedEvent());\n\n mitk::BaseProperty* nameProperty = m_SelectedNode->GetProperty(\"name\");\n\n if (nameProperty != NULL)\n {\n itk::ReceptorMemberCommand::Pointer command = itk::ReceptorMemberCommand::New();\n command->SetCallbackFunction(this, &QmitkPropertyTreeView::OnPropertyNameChanged);\n m_PropertyNameChangedTag = nameProperty->AddObserver(itk::ModifiedEvent(), command);\n }\n\n m_Controls.newButton->setEnabled(true);\n }\n\n if (!m_ProxyModel->filterRegExp().isEmpty())\n m_Controls.treeView->expandAll();\n}\n\nvoid QmitkPropertyTreeView::SetFocus()\n{\n m_Controls.filterLineEdit->setFocus();\n}\n\nvoid QmitkPropertyTreeView::RenderWindowPartActivated(mitk::IRenderWindowPart* renderWindowPart)\n{\n if (m_Controls.propertyListComboBox->count() == 1)\n {\n QHash renderWindows = this->GetRenderWindowPart()->GetQmitkRenderWindows();\n\n Q_FOREACH(QString renderWindow, renderWindows.keys())\n {\n m_Controls.propertyListComboBox->addItem(renderWindow);\n }\n }\n}\n\nvoid QmitkPropertyTreeView::RenderWindowPartDeactivated(mitk::IRenderWindowPart*)\n{\n if (m_Controls.propertyListComboBox->count() > 1)\n {\n m_Controls.propertyListComboBox->clear();\n m_Controls.propertyListComboBox->addItem(\"independent\");\n }\n}\n\nvoid QmitkPropertyTreeView::OnPropertyListChanged(int index)\n{\n if (index == -1)\n return;\n\n QString renderer = m_Controls.propertyListComboBox->itemText(index);\n\n m_Renderer = renderer != \"independent\"\n ? this->GetRenderWindowPart()->GetQmitkRenderWindow(renderer)->GetRenderer()\n : NULL;\n\n QList nodes;\n\n if (m_SelectedNode.IsNotNull())\n nodes << m_SelectedNode;\n\n berry::IWorkbenchPart::Pointer workbenchPart;\n\n this->OnSelectionChanged(workbenchPart, nodes);\n}\n\nvoid QmitkPropertyTreeView::OnAddNewProperty()\n{\n QmitkAddNewPropertyDialog dialog(m_SelectedNode, m_Renderer, m_Parent);\n\n if (dialog.exec() == QDialog::Accepted)\n this->m_Model->Update();\n}\nMade base data properties available in developer mode of Properties view.\/*===================================================================\n\nThe Medical Imaging Interaction Toolkit (MITK)\n\nCopyright (c) German Cancer Research Center,\nDivision of Medical and Biological Informatics.\nAll rights reserved.\n\nThis software is distributed WITHOUT ANY WARRANTY; without\neven the implied warranty of MERCHANTABILITY or FITNESS FOR\nA PARTICULAR PURPOSE.\n\nSee LICENSE.txt or http:\/\/www.mitk.org for details.\n\n===================================================================*\/\n\n#include \"mitkGetPropertyService.h\"\n#include \"QmitkAddNewPropertyDialog.h\"\n#include \"QmitkPropertiesPreferencePage.h\"\n#include \"QmitkPropertyItemDelegate.h\"\n#include \"QmitkPropertyItemModel.h\"\n#include \"QmitkPropertyItemSortFilterProxyModel.h\"\n#include \"QmitkPropertyTreeView.h\"\n#include \n#include \n#include \n#include \n#include \n\nconst std::string QmitkPropertyTreeView::VIEW_ID = \"org.mitk.views.properties\";\n\nQmitkPropertyTreeView::QmitkPropertyTreeView()\n : m_Parent(NULL),\n m_PropertyNameChangedTag(0),\n m_PropertyAliases(NULL),\n m_PropertyDescriptions(NULL),\n m_ShowAliasesInDescription(true),\n m_DeveloperMode(false),\n m_ProxyModel(NULL),\n m_Model(NULL),\n m_Delegate(NULL),\n m_Renderer(NULL)\n{\n}\n\nQmitkPropertyTreeView::~QmitkPropertyTreeView()\n{\n}\n\nvoid QmitkPropertyTreeView::CreateQtPartControl(QWidget* parent)\n{\n m_Parent = parent;\n\n m_Controls.setupUi(parent);\n\n m_Controls.propertyListComboBox->addItem(\"Data node: common\");\n\n mitk::IRenderWindowPart* renderWindowPart = this->GetRenderWindowPart();\n\n if (renderWindowPart != NULL)\n {\n QHash renderWindows = renderWindowPart->GetQmitkRenderWindows();\n\n Q_FOREACH(QString renderWindow, renderWindows.keys())\n {\n m_Controls.propertyListComboBox->addItem(QString(\"Data node: \") + renderWindow);\n }\n }\n\n m_Controls.propertyListComboBox->addItem(\"Base data\");\n\n m_Controls.newButton->setEnabled(false);\n\n m_Controls.description->hide();\n m_Controls.propertyListLabel->hide();\n m_Controls.propertyListComboBox->hide();\n m_Controls.newButton->hide();\n\n m_ProxyModel = new QmitkPropertyItemSortFilterProxyModel(m_Controls.treeView);\n m_Model = new QmitkPropertyItemModel(m_ProxyModel);\n\n m_ProxyModel->setSourceModel(m_Model);\n m_ProxyModel->setFilterCaseSensitivity(Qt::CaseInsensitive);\n m_ProxyModel->setSortCaseSensitivity(Qt::CaseInsensitive);\n m_ProxyModel->setDynamicSortFilter(true);\n\n m_Delegate = new QmitkPropertyItemDelegate(m_Controls.treeView);\n\n m_Controls.treeView->setItemDelegateForColumn(1, m_Delegate);\n m_Controls.treeView->setModel(m_ProxyModel);\n m_Controls.treeView->setColumnWidth(0, 160);\n m_Controls.treeView->sortByColumn(0, Qt::AscendingOrder);\n m_Controls.treeView->setSelectionBehavior(QAbstractItemView::SelectRows);\n m_Controls.treeView->setSelectionMode(QAbstractItemView::SingleSelection);\n m_Controls.treeView->setEditTriggers(QAbstractItemView::SelectedClicked | QAbstractItemView::DoubleClicked);\n\n connect(m_Controls.filterLineEdit, SIGNAL(textChanged(const QString&)), this, SLOT(OnFilterTextChanged(const QString&)));\n connect(m_Controls.propertyListComboBox, SIGNAL(currentIndexChanged(int)), this, SLOT(OnPropertyListChanged(int)));\n connect(m_Controls.newButton, SIGNAL(clicked()), this, SLOT(OnAddNewProperty()));\n connect(m_Controls.treeView->selectionModel(), SIGNAL(currentRowChanged(const QModelIndex&, const QModelIndex&)), this, SLOT(OnCurrentRowChanged(const QModelIndex&, const QModelIndex&)));\n connect(m_Model, SIGNAL(modelReset()), this, SLOT(OnModelReset()));\n}\n\nQString QmitkPropertyTreeView::GetPropertyNameOrAlias(const QModelIndex& index)\n{\n QString propertyName;\n\n if (index.isValid())\n {\n QModelIndex current = index;\n\n while (current.isValid())\n {\n QString name = m_ProxyModel->data(m_ProxyModel->index(current.row(), 0, current.parent())).toString();\n\n propertyName.prepend(propertyName.isEmpty()\n ? name\n : name.append('.'));\n\n current = current.parent();\n }\n }\n\n return propertyName;\n}\n\nvoid QmitkPropertyTreeView::OnCurrentRowChanged(const QModelIndex& current, const QModelIndex&)\n{\n if (m_PropertyDescriptions != NULL && current.isValid())\n {\n QString name = this->GetPropertyNameOrAlias(current);\n\n if (!name.isEmpty())\n {\n QString alias;\n bool isTrueName = true;\n\n if (m_PropertyAliases != NULL)\n {\n std::string trueName = m_PropertyAliases->GetPropertyName(name.toStdString());\n\n if (trueName.empty() && !m_SelectionClassName.empty())\n trueName = m_PropertyAliases->GetPropertyName(name.toStdString(), m_SelectionClassName);\n\n if (!trueName.empty())\n {\n alias = name;\n name = QString::fromStdString(trueName);\n isTrueName = false;\n }\n }\n\n QString description = QString::fromStdString(m_PropertyDescriptions->GetDescription(name.toStdString()));\n std::vector aliases;\n\n if (!isTrueName && m_PropertyAliases != NULL)\n {\n aliases = m_PropertyAliases->GetAliases(name.toStdString(), m_SelectionClassName);\n\n if (aliases.empty() && !m_SelectionClassName.empty())\n aliases = m_PropertyAliases->GetAliases(name.toStdString());\n }\n\n if (!description.isEmpty() || !aliases.empty())\n {\n QString customizedDescription;\n\n if (m_ShowAliasesInDescription && !aliases.empty())\n {\n customizedDescription = \"

\" + name + \"<\/h3>\";\n\n std::size_t numAliases = aliases.size();\n std::size_t lastAlias = numAliases - 1;\n\n for (std::size_t i = 0; i < numAliases; ++i)\n {\n customizedDescription += i != lastAlias\n ? \"

\"\n : \"
\";\n\n customizedDescription += QString::fromStdString(aliases[i]) + \"<\/h5>\";\n }\n }\n else\n {\n customizedDescription = \"

\" + name + \"<\/h3>\";\n }\n\n if (!description.isEmpty())\n customizedDescription += description;\n\n m_Controls.description->setText(customizedDescription);\n m_Controls.description->show();\n\n return;\n }\n }\n }\n\n m_Controls.description->hide();\n}\n\nvoid QmitkPropertyTreeView::OnFilterTextChanged(const QString& filter)\n{\n m_ProxyModel->setFilterWildcard(filter);\n\n if (filter.isEmpty())\n m_Controls.treeView->collapseAll();\n else\n m_Controls.treeView->expandAll();\n}\n\nvoid QmitkPropertyTreeView::OnModelReset()\n{\n m_Controls.description->hide();\n}\n\nvoid QmitkPropertyTreeView::OnPreferencesChanged(const berry::IBerryPreferences* preferences)\n{\n bool showAliases = preferences->GetBool(QmitkPropertiesPreferencePage::SHOW_ALIASES, true);\n bool showDescriptions = preferences->GetBool(QmitkPropertiesPreferencePage::SHOW_DESCRIPTIONS, true);\n bool showAliasesInDescription = preferences->GetBool(QmitkPropertiesPreferencePage::SHOW_ALIASES_IN_DESCRIPTION, true);\n bool developerMode = preferences->GetBool(QmitkPropertiesPreferencePage::DEVELOPER_MODE, false);\n\n bool updateAliases = showAliases != (m_PropertyAliases != NULL);\n bool updateDescriptions = showDescriptions != (m_PropertyDescriptions != NULL);\n bool updateAliasesInDescription = showAliasesInDescription != m_ShowAliasesInDescription;\n bool updateDeveloperMode = developerMode != m_DeveloperMode;\n\n if (updateAliases)\n m_PropertyAliases = showAliases\n ? mitk::GetPropertyService()\n : NULL;\n\n if (updateDescriptions)\n m_PropertyDescriptions = showDescriptions\n ? mitk::GetPropertyService()\n : NULL;\n\n if (updateAliasesInDescription)\n m_ShowAliasesInDescription = showAliasesInDescription;\n\n if (updateDescriptions || updateAliasesInDescription)\n {\n QModelIndexList selection = m_Controls.treeView->selectionModel()->selectedRows();\n\n if (!selection.isEmpty())\n this->OnCurrentRowChanged(selection[0], selection[0]);\n }\n\n if (updateDeveloperMode)\n {\n m_DeveloperMode = developerMode;\n\n if (!developerMode)\n m_Controls.propertyListComboBox->setCurrentIndex(0);\n\n m_Controls.propertyListLabel->setVisible(developerMode);\n m_Controls.propertyListComboBox->setVisible(developerMode);\n m_Controls.newButton->setVisible(developerMode);\n }\n\n m_Model->OnPreferencesChanged(preferences);\n}\n\nvoid QmitkPropertyTreeView::OnPropertyNameChanged(const itk::EventObject&)\n{\n mitk::PropertyList* propertyList = m_Model->GetPropertyList();\n\n if (propertyList != NULL)\n {\n mitk::BaseProperty* nameProperty = propertyList->GetProperty(\"name\");\n\n if (nameProperty != NULL)\n {\n std::ostringstream partName;\n partName << \"Properties (\" << nameProperty->GetValueAsString() << ')';\n this->SetPartName(partName.str());\n }\n }\n}\n\nvoid QmitkPropertyTreeView::OnSelectionChanged(berry::IWorkbenchPart::Pointer, const QList& nodes)\n{\n mitk::PropertyList* propertyList = m_Model->GetPropertyList();\n\n if (propertyList != NULL)\n {\n mitk::BaseProperty* nameProperty = propertyList->GetProperty(\"name\");\n\n if (nameProperty != NULL)\n nameProperty->RemoveObserver(m_PropertyNameChangedTag);\n\n m_PropertyNameChangedTag = 0;\n }\n\n if (nodes.empty() || nodes.front().IsNull())\n {\n m_SelectedNode = NULL;\n\n this->SetPartName(\"Properties\");\n m_Model->SetPropertyList(NULL);\n m_Delegate->SetPropertyList(NULL);\n\n m_Controls.newButton->setEnabled(false);\n }\n else\n {\n m_SelectedNode = nodes.front();\n\n QString selectionClassName = m_SelectedNode->GetData() != NULL\n ? m_SelectedNode->GetData()->GetNameOfClass()\n : \"\";\n\n m_SelectionClassName = selectionClassName.toStdString();\n\n mitk::PropertyList::Pointer propertyList;\n\n if (m_Renderer == NULL && m_Controls.propertyListComboBox->currentText() == \"Base data\")\n {\n propertyList = m_SelectedNode->GetData() != NULL\n ? m_SelectedNode->GetData()->GetPropertyList()\n : NULL;\n }\n else\n {\n propertyList = m_SelectedNode->GetPropertyList(m_Renderer);\n }\n\n m_Model->SetPropertyList(propertyList, selectionClassName);\n m_Delegate->SetPropertyList(propertyList);\n\n OnPropertyNameChanged(itk::ModifiedEvent());\n\n mitk::BaseProperty* nameProperty = m_SelectedNode->GetProperty(\"name\");\n\n if (nameProperty != NULL)\n {\n itk::ReceptorMemberCommand::Pointer command = itk::ReceptorMemberCommand::New();\n command->SetCallbackFunction(this, &QmitkPropertyTreeView::OnPropertyNameChanged);\n m_PropertyNameChangedTag = nameProperty->AddObserver(itk::ModifiedEvent(), command);\n }\n\n m_Controls.newButton->setEnabled(true);\n }\n\n if (!m_ProxyModel->filterRegExp().isEmpty())\n m_Controls.treeView->expandAll();\n}\n\nvoid QmitkPropertyTreeView::SetFocus()\n{\n m_Controls.filterLineEdit->setFocus();\n}\n\nvoid QmitkPropertyTreeView::RenderWindowPartActivated(mitk::IRenderWindowPart* renderWindowPart)\n{\n if (m_Controls.propertyListComboBox->count() == 2)\n {\n QHash renderWindows = this->GetRenderWindowPart()->GetQmitkRenderWindows();\n\n Q_FOREACH(QString renderWindow, renderWindows.keys())\n {\n m_Controls.propertyListComboBox->insertItem(m_Controls.propertyListComboBox->count() - 1, QString(\"Data node: \") + renderWindow);\n }\n }\n}\n\nvoid QmitkPropertyTreeView::RenderWindowPartDeactivated(mitk::IRenderWindowPart*)\n{\n if (m_Controls.propertyListComboBox->count() > 2)\n {\n m_Controls.propertyListComboBox->clear();\n m_Controls.propertyListComboBox->addItem(\"Data node: common\");\n m_Controls.propertyListComboBox->addItem(\"Base data\");\n }\n}\n\nvoid QmitkPropertyTreeView::OnPropertyListChanged(int index)\n{\n if (index == -1)\n return;\n\n QString renderer = m_Controls.propertyListComboBox->itemText(index);\n\n if (renderer.startsWith(\"Data node: \"))\n renderer = QString::fromStdString(renderer.toStdString().substr(11));\n\n m_Renderer = renderer != \"common\" && renderer != \"Base data\"\n ? this->GetRenderWindowPart()->GetQmitkRenderWindow(renderer)->GetRenderer()\n : NULL;\n\n QList nodes;\n\n if (m_SelectedNode.IsNotNull())\n nodes << m_SelectedNode;\n\n berry::IWorkbenchPart::Pointer workbenchPart;\n\n this->OnSelectionChanged(workbenchPart, nodes);\n}\n\nvoid QmitkPropertyTreeView::OnAddNewProperty()\n{\n QmitkAddNewPropertyDialog dialog(m_SelectedNode, m_Renderer, m_Parent);\n\n if (dialog.exec() == QDialog::Accepted)\n this->m_Model->Update();\n}\n<|endoftext|>"} {"text":"\/*********************************************************************\n* Software License Agreement (BSD License)\n*\n* Copyright (c) 2008, Willow Garage, Inc.\n* All rights reserved.\n*\n* Redistribution and use in source and binary forms, with or without\n* modification, are permitted provided that the following conditions\n* are met:\n*\n* * Redistributions of source code must retain the above copyright\n* notice, this list of conditions and the following disclaimer.\n* * Redistributions in binary form must reproduce the above\n* copyright notice, this list of conditions and the following\n* disclaimer in the documentation and\/or other materials provided\n* with the distribution.\n* * Neither the name of Willow Garage, Inc. nor the names of its\n* contributors may be used to endorse or promote products derived\n* from this software without specific prior written permission.\n*\n* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n* \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n* POSSIBILITY OF SUCH DAMAGE.\n********************************************************************\/\n\n#include \"rosrecord\/Recorder.h\"\n\n#include \"rosrecord\/constants.h\"\n\n#include \n#include \n#include \n\n#include \n#include \n#include \n\nusing namespace ros::record;\n\nros::record::Recorder::Recorder()\n : file_header_pos_(0), index_data_pos_(0), header_buf_(NULL), header_buf_len_(0), header_buf_size_(0),\n message_buf_(NULL), message_buf_len_(0), message_buf_size_(0), logging_enabled_(true)\n{\n}\n\nros::record::Recorder::~Recorder()\n{\n close();\n}\n\nconst void* ros::record::Recorder::getHeaderBuffer()\n{\n return header_buf_;\n}\n\nunsigned int ros::record::Recorder::getHeaderBufferLength()\n{\n return header_buf_len_;\n}\n\nvoid ros::record::Recorder::resetHeaderBuffer()\n{\n header_buf_len_ = 0;\n}\n\nvoid ros::record::Recorder::writeFieldToHeaderBuffer(const std::string& name, const void* value, unsigned int value_len)\n{\n \/\/ Do a little buffer-size management.\n unsigned int new_len = header_buf_len_ + name.size() + 1 + 4 + value_len;\n if (header_buf_size_ < new_len)\n {\n if (header_buf_size_ == 0)\n header_buf_size_ = new_len;\n else\n {\n while (header_buf_size_ < new_len)\n header_buf_size_ *= 2;\n }\n header_buf_ = (unsigned char*) realloc(header_buf_, header_buf_size_);\n ROS_ASSERT(header_buf_);\n }\n\n \/\/ Copy in the data as\n \/\/ =\n \/\/ where is a 4-byte little-endian integer.\n \/\/\n \/\/ (see http:\/\/pr.willowgarage.com\/wiki\/ROS\/LogFormat)\n memcpy(header_buf_ + header_buf_len_, name.c_str(), name.size());\n header_buf_len_ += name.size();\n header_buf_[header_buf_len_] = FIELD_DELIM;\n header_buf_len_ += 1;\n memcpy(header_buf_ + header_buf_len_, &value_len, 4);\n header_buf_len_ += 4;\n memcpy(header_buf_ + header_buf_len_, value, value_len);\n header_buf_len_ += value_len;\n}\n\nbool ros::record::Recorder::open(const std::string& file_name, bool random_access)\n{\n if (!openFile(file_name, random_access))\n return false;\n\n writeVersion();\n writeFileHeader();\n\n return true;\n}\n\nbool ros::record::Recorder::openFile(const std::string& file_name, bool random_access)\n{\n file_name_ = file_name;\n\n std::string ext = boost::filesystem::extension(file_name);\n\n store_index_ = !(ext == \".gz\" || ext == \".bz2\");\n if (store_index_ && random_access)\n record_file_.open(file_name.c_str(), std::ios::in | std::ios::out | std::ios::binary);\n else\n record_file_.open(file_name.c_str(), std::ios::out | std::ios::binary | std::ios::app);\n\n if (record_file_.fail())\n {\n ROS_FATAL(\"rosrecord::Record: Failed to open file: %s\", file_name.c_str());\n return false;\n }\n\n \/\/ Removing compression until we work out how to play nicely with index: JML\n \/*\n if (ext == \".gz\")\n record_stream_.push(boost::iostreams::gzip_compressor());\n else if (ext == \".bz2\")\n record_stream_.push(boost::iostreams::bzip2_compressor());\n *\/\n record_stream_.push(record_file_);\n\n check_disk_next_ = ros::WallTime::now() + ros::WallDuration().fromSec(20.0);\n warn_next_ = ros::WallTime();\n\n record_pos_ = 0;\n\n checkDisk();\n\n return true;\n}\n\npos_t ros::record::Recorder::getOffset()\n{\n return record_pos_;\n}\n\nvoid ros::record::Recorder::close()\n{\n if (!record_file_.is_open())\n return;\n\n if (store_index_)\n writeIndex();\n\n topics_recorded_.clear();\n topic_indexes_.clear();\n\n closeFile();\n}\n\nvoid ros::record::Recorder::closeFile()\n{\n \/\/ Unfortunately closing this possibly enormous file takes a while\n \/\/ (especially over NFS) and handling of a SIGINT while a file is\n \/\/ closing leads to a double free. So, we disable signals while\n \/\/ we close the file.\n\n \/\/ Darwin doesn't have sighandler_t; I hope that sig_t on Linux does\n \/\/ the right thing.\n \/\/sighandler_t old = signal(SIGINT, SIG_IGN);\n sig_t old = signal(SIGINT, SIG_IGN);\n if (record_file_.is_open())\n {\n while (!record_stream_.empty())\n record_stream_.pop();\n record_file_.close();\n }\n signal(SIGINT, old);\n}\n\nvoid ros::record::Recorder::writeVersion()\n{\n std::string version = std::string(\"#ROSRECORD V\") + VERSION + std::string(\"\\n\");\n write(version);\n}\n\nbool ros::record::Recorder::checkDisk()\n{\n struct statvfs fiData;\n\n if ((statvfs(file_name_.c_str(), &fiData)) < 0)\n {\n ROS_WARN(\"rosrecord::Record: Failed to check filesystem stats.\");\n }\n else\n {\n unsigned long long free_space = 0;\n\n free_space = (unsigned long long)(fiData.f_bsize) * (unsigned long long)(fiData.f_bavail);\n\n if (free_space < 1073741824ull)\n {\n ROS_ERROR(\"rosrecord::Record: Less than 1GB of space free on disk with %s. Disabling logging.\", file_name_.c_str());\n logging_enabled_ = false;\n return false;\n }\n else if (free_space < 5368709120ull)\n {\n ROS_WARN(\"rosrecord::Record: Less than 5GB of space free on disk with %s.\", file_name_.c_str());\n }\n else\n {\n logging_enabled_ = true;\n }\n }\n return true;\n}\n\nbool ros::record::Recorder::record(std::string topic_name, ros::Message::ConstPtr msg, ros::Time time)\n{\n if (!logging_enabled_)\n {\n ros::WallTime nowtime = ros::WallTime::now();\n if (nowtime > warn_next_)\n {\n warn_next_ = nowtime + ros::WallDuration().fromSec(5.0);\n ROS_WARN(\"Not logging message because logging disabled. Most likely cause is a full disk.\");\n }\n return false;\n }\n\n bool needs_def_written = false;\n std::map::iterator key;\n {\n boost::mutex::scoped_lock lock(topics_recorded_mutex_);\n\n key = topics_recorded_.find(topic_name);\n\n if (key == topics_recorded_.end())\n {\n MsgInfo& info = topics_recorded_[topic_name];\n info.msg_def = msg->__getMessageDefinition();\n info.datatype = msg->__getDataType();\n info.md5sum = msg->__getMD5Sum();\n\n key = topics_recorded_.find(topic_name);\n\n topic_indexes_[topic_name] = std::vector();\n\n needs_def_written = true;\n }\n }\n const MsgInfo& msg_info = key->second;\n\n {\n boost::mutex::scoped_lock lock(check_disk_mutex_);\n\n if (ros::WallTime::now() > check_disk_next_)\n {\n check_disk_next_ = check_disk_next_ + ros::WallDuration().fromSec(20.0);\n\n if (!checkDisk())\n return false;\n }\n }\n\n {\n boost::mutex::scoped_lock lock(record_mutex_);\n\n \/\/ Assemble the header in memory first, because we need to write its length first.\n\n \/\/ Add to topic index\n IndexEntry index_entry;\n index_entry.sec = time.sec;\n index_entry.nsec = time.nsec;\n index_entry.pos = record_pos_;\n topic_indexes_[topic_name].push_back(index_entry);\n\n \/\/ Write a message definition record, if necessary\n if (needs_def_written)\n {\n M_string header;\n header[OP_FIELD_NAME] = std::string((char*)&OP_MSG_DEF, 1);\n header[TOPIC_FIELD_NAME] = topic_name;\n header[MD5_FIELD_NAME] = msg_info.md5sum;\n header[TYPE_FIELD_NAME] = msg_info.datatype;\n header[DEF_FIELD_NAME] = msg_info.msg_def;\n writeHeader(header, 0);\n }\n\n \/\/ Serialize the message into the message buffer\n if (message_buf_size_ < msg->__serialized_length)\n {\n if (message_buf_size_ == 0)\n message_buf_size_ = msg->__serialized_length;\n else\n {\n while (message_buf_size_ < msg->__serialized_length)\n message_buf_size_ *= 2;\n }\n message_buf_ = (unsigned char*)realloc(message_buf_, message_buf_size_);\n ROS_ASSERT(message_buf_);\n }\n msg->serialize(message_buf_, 0);\n\n \/\/ Write a message instance record\n M_string header;\n header[OP_FIELD_NAME] = std::string((char*)&OP_MSG_DATA, 1);\n header[TOPIC_FIELD_NAME] = topic_name;\n header[MD5_FIELD_NAME] = msg_info.md5sum;\n header[TYPE_FIELD_NAME] = msg_info.datatype;\n header[SEC_FIELD_NAME] = std::string((char*)&time.sec, 4);\n header[NSEC_FIELD_NAME] = std::string((char*)&time.nsec, 4);\n writeRecord(header, (char*)message_buf_, msg->__serialized_length);\n if (record_file_.fail())\n {\n ROS_FATAL(\"rosrecord::Record: could not write to file. Check permissions and diskspace\\n\");\n return false;\n }\n }\n\n return true;\n}\n\nvoid ros::record::Recorder::writeFileHeader()\n{\n boost::mutex::scoped_lock lock(record_mutex_);\n\n \/\/ Remember position of file header record\n file_header_pos_ = record_pos_;\n\n \/\/ Write file header record\n M_string header;\n header[OP_FIELD_NAME] = std::string((char*)&OP_FILE_HEADER, 1);\n header[INDEX_POS_FIELD_NAME] = std::string((char*)&index_data_pos_, 8);\n\n boost::shared_array header_buffer;\n uint32_t header_len;\n Header::write(header, header_buffer, header_len);\n uint32_t data_len = 0;\n if (header_len < FILE_HEADER_LENGTH)\n data_len = FILE_HEADER_LENGTH - header_len;\n write((char*)&header_len, 4);\n write((char*)header_buffer.get(), header_len);\n write((char*)&data_len, 4);\n\n \/\/ Pad the file header record out\n if (data_len > 0)\n {\n std::string padding;\n padding.resize(data_len, ' ');\n write(padding);\n }\n}\n\nvoid ros::record::Recorder::writeIndex()\n{\n\t{\n\t\tboost::mutex::scoped_lock lock(record_mutex_);\n\n\t\t\/\/ Remember position of first index record\n\t\tindex_data_pos_ = record_pos_;\n\n\t\tfor (std::map >::const_iterator i = topic_indexes_.begin(); i != topic_indexes_.end(); i++)\n\t\t{\n\t\t\tconst std::string& topic_name = i->first;\n\t\t\tconst std::vector& topic_index = i->second;\n\n\t\t\tuint32_t topic_index_size = topic_index.size();\n\n\t const MsgInfo& msg_info = topics_recorded_[topic_name];\n\n\t \/\/ Write the index record header\n\t\t\tM_string header;\n\t\t\theader[OP_FIELD_NAME] = std::string((char*)&OP_INDEX_DATA, 1);\n\t\t\theader[TOPIC_FIELD_NAME] = topic_name;\n\t header[TYPE_FIELD_NAME] = msg_info.datatype;\n\t\t\theader[VER_FIELD_NAME] = std::string((char*)&INDEX_VERSION, 4);\n\t\t\theader[COUNT_FIELD_NAME] = std::string((char*)&topic_index_size, 4);\n\n\t\t\tuint32_t data_len = topic_index_size * sizeof(IndexEntry);\n\t\t\twriteHeader(header, data_len);\n\n\t\t\t\/\/ Write the index record data (pairs of timestamp and position in file)\n\t\t\tfor (std::vector::const_iterator j = topic_index.begin(); j != topic_index.end(); j++)\n\t\t\t{\n\t\t\t\tconst IndexEntry& index_entry = *j;\n\t\t\t\twrite((char*)&index_entry.sec, 4);\n\t\t\t\twrite((char*)&index_entry.nsec, 4);\n\t\t\t\twrite((char*)&index_entry.pos, 8);\n\t\t\t}\n\t\t}\n\t}\n\n\t\/\/ Re-open the file for random access, and rewrite the file header to point to the first index data message\n closeFile();\n openFile(file_name_, true);\n seek(file_header_pos_);\n writeFileHeader();\n}\n\n\/\/\n\nvoid ros::record::Recorder::writeRecord(const M_string& fields, const char* data, uint32_t data_len)\n{\n writeHeader(fields, data_len);\n write(data, data_len);\n}\n\nvoid ros::record::Recorder::writeHeader(const M_string& fields, uint32_t data_len)\n{\n boost::shared_array header_buffer;\n uint32_t header_len;\n Header::write(fields, header_buffer, header_len);\n\n write((char*)&header_len, 4);\n write((char*)header_buffer.get(), header_len);\n write((char*)&data_len, 4);\n}\n\nvoid ros::record::Recorder::write(const char* s, std::streamsize n)\n{\n record_stream_.write(s, n);\n record_pos_ += n;\n}\n\nvoid ros::record::Recorder::write(const std::string& s)\n{\n write(s.c_str(), s.length());\n}\n\nvoid ros::record::Recorder::seek(pos_t pos)\n{\n record_file_.seekp(pos, std::ios_base::beg);\n record_pos_ = pos;\n}\nFixing rosrecord so it no longer depends on __serialized_length.\/*********************************************************************\n* Software License Agreement (BSD License)\n*\n* Copyright (c) 2008, Willow Garage, Inc.\n* All rights reserved.\n*\n* Redistribution and use in source and binary forms, with or without\n* modification, are permitted provided that the following conditions\n* are met:\n*\n* * Redistributions of source code must retain the above copyright\n* notice, this list of conditions and the following disclaimer.\n* * Redistributions in binary form must reproduce the above\n* copyright notice, this list of conditions and the following\n* disclaimer in the documentation and\/or other materials provided\n* with the distribution.\n* * Neither the name of Willow Garage, Inc. nor the names of its\n* contributors may be used to endorse or promote products derived\n* from this software without specific prior written permission.\n*\n* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n* \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n* POSSIBILITY OF SUCH DAMAGE.\n********************************************************************\/\n\n#include \"rosrecord\/Recorder.h\"\n\n#include \"rosrecord\/constants.h\"\n\n#include \n#include \n#include \n\n#include \n#include \n#include \n\nusing namespace ros::record;\n\nros::record::Recorder::Recorder()\n : file_header_pos_(0), index_data_pos_(0), header_buf_(NULL), header_buf_len_(0), header_buf_size_(0),\n message_buf_(NULL), message_buf_len_(0), message_buf_size_(0), logging_enabled_(true)\n{\n}\n\nros::record::Recorder::~Recorder()\n{\n close();\n}\n\nconst void* ros::record::Recorder::getHeaderBuffer()\n{\n return header_buf_;\n}\n\nunsigned int ros::record::Recorder::getHeaderBufferLength()\n{\n return header_buf_len_;\n}\n\nvoid ros::record::Recorder::resetHeaderBuffer()\n{\n header_buf_len_ = 0;\n}\n\nvoid ros::record::Recorder::writeFieldToHeaderBuffer(const std::string& name, const void* value, unsigned int value_len)\n{\n \/\/ Do a little buffer-size management.\n unsigned int new_len = header_buf_len_ + name.size() + 1 + 4 + value_len;\n if (header_buf_size_ < new_len)\n {\n if (header_buf_size_ == 0)\n header_buf_size_ = new_len;\n else\n {\n while (header_buf_size_ < new_len)\n header_buf_size_ *= 2;\n }\n header_buf_ = (unsigned char*) realloc(header_buf_, header_buf_size_);\n ROS_ASSERT(header_buf_);\n }\n\n \/\/ Copy in the data as\n \/\/ =\n \/\/ where is a 4-byte little-endian integer.\n \/\/\n \/\/ (see http:\/\/pr.willowgarage.com\/wiki\/ROS\/LogFormat)\n memcpy(header_buf_ + header_buf_len_, name.c_str(), name.size());\n header_buf_len_ += name.size();\n header_buf_[header_buf_len_] = FIELD_DELIM;\n header_buf_len_ += 1;\n memcpy(header_buf_ + header_buf_len_, &value_len, 4);\n header_buf_len_ += 4;\n memcpy(header_buf_ + header_buf_len_, value, value_len);\n header_buf_len_ += value_len;\n}\n\nbool ros::record::Recorder::open(const std::string& file_name, bool random_access)\n{\n if (!openFile(file_name, random_access))\n return false;\n\n writeVersion();\n writeFileHeader();\n\n return true;\n}\n\nbool ros::record::Recorder::openFile(const std::string& file_name, bool random_access)\n{\n file_name_ = file_name;\n\n std::string ext = boost::filesystem::extension(file_name);\n\n store_index_ = !(ext == \".gz\" || ext == \".bz2\");\n if (store_index_ && random_access)\n record_file_.open(file_name.c_str(), std::ios::in | std::ios::out | std::ios::binary);\n else\n record_file_.open(file_name.c_str(), std::ios::out | std::ios::binary | std::ios::app);\n\n if (record_file_.fail())\n {\n ROS_FATAL(\"rosrecord::Record: Failed to open file: %s\", file_name.c_str());\n return false;\n }\n\n \/\/ Removing compression until we work out how to play nicely with index: JML\n \/*\n if (ext == \".gz\")\n record_stream_.push(boost::iostreams::gzip_compressor());\n else if (ext == \".bz2\")\n record_stream_.push(boost::iostreams::bzip2_compressor());\n *\/\n record_stream_.push(record_file_);\n\n check_disk_next_ = ros::WallTime::now() + ros::WallDuration().fromSec(20.0);\n warn_next_ = ros::WallTime();\n\n record_pos_ = 0;\n\n checkDisk();\n\n return true;\n}\n\npos_t ros::record::Recorder::getOffset()\n{\n return record_pos_;\n}\n\nvoid ros::record::Recorder::close()\n{\n if (!record_file_.is_open())\n return;\n\n if (store_index_)\n writeIndex();\n\n topics_recorded_.clear();\n topic_indexes_.clear();\n\n closeFile();\n}\n\nvoid ros::record::Recorder::closeFile()\n{\n \/\/ Unfortunately closing this possibly enormous file takes a while\n \/\/ (especially over NFS) and handling of a SIGINT while a file is\n \/\/ closing leads to a double free. So, we disable signals while\n \/\/ we close the file.\n\n \/\/ Darwin doesn't have sighandler_t; I hope that sig_t on Linux does\n \/\/ the right thing.\n \/\/sighandler_t old = signal(SIGINT, SIG_IGN);\n sig_t old = signal(SIGINT, SIG_IGN);\n if (record_file_.is_open())\n {\n while (!record_stream_.empty())\n record_stream_.pop();\n record_file_.close();\n }\n signal(SIGINT, old);\n}\n\nvoid ros::record::Recorder::writeVersion()\n{\n std::string version = std::string(\"#ROSRECORD V\") + VERSION + std::string(\"\\n\");\n write(version);\n}\n\nbool ros::record::Recorder::checkDisk()\n{\n struct statvfs fiData;\n\n if ((statvfs(file_name_.c_str(), &fiData)) < 0)\n {\n ROS_WARN(\"rosrecord::Record: Failed to check filesystem stats.\");\n }\n else\n {\n unsigned long long free_space = 0;\n\n free_space = (unsigned long long)(fiData.f_bsize) * (unsigned long long)(fiData.f_bavail);\n\n if (free_space < 1073741824ull)\n {\n ROS_ERROR(\"rosrecord::Record: Less than 1GB of space free on disk with %s. Disabling logging.\", file_name_.c_str());\n logging_enabled_ = false;\n return false;\n }\n else if (free_space < 5368709120ull)\n {\n ROS_WARN(\"rosrecord::Record: Less than 5GB of space free on disk with %s.\", file_name_.c_str());\n }\n else\n {\n logging_enabled_ = true;\n }\n }\n return true;\n}\n\nbool ros::record::Recorder::record(std::string topic_name, ros::Message::ConstPtr msg, ros::Time time)\n{\n if (!logging_enabled_)\n {\n ros::WallTime nowtime = ros::WallTime::now();\n if (nowtime > warn_next_)\n {\n warn_next_ = nowtime + ros::WallDuration().fromSec(5.0);\n ROS_WARN(\"Not logging message because logging disabled. Most likely cause is a full disk.\");\n }\n return false;\n }\n\n bool needs_def_written = false;\n std::map::iterator key;\n {\n boost::mutex::scoped_lock lock(topics_recorded_mutex_);\n\n key = topics_recorded_.find(topic_name);\n\n if (key == topics_recorded_.end())\n {\n MsgInfo& info = topics_recorded_[topic_name];\n info.msg_def = msg->__getMessageDefinition();\n info.datatype = msg->__getDataType();\n info.md5sum = msg->__getMD5Sum();\n\n key = topics_recorded_.find(topic_name);\n\n topic_indexes_[topic_name] = std::vector();\n\n needs_def_written = true;\n }\n }\n const MsgInfo& msg_info = key->second;\n\n {\n boost::mutex::scoped_lock lock(check_disk_mutex_);\n\n if (ros::WallTime::now() > check_disk_next_)\n {\n check_disk_next_ = check_disk_next_ + ros::WallDuration().fromSec(20.0);\n\n if (!checkDisk())\n return false;\n }\n }\n\n {\n boost::mutex::scoped_lock lock(record_mutex_);\n\n \/\/ Assemble the header in memory first, because we need to write its length first.\n\n \/\/ Add to topic index\n IndexEntry index_entry;\n index_entry.sec = time.sec;\n index_entry.nsec = time.nsec;\n index_entry.pos = record_pos_;\n topic_indexes_[topic_name].push_back(index_entry);\n\n \/\/ Write a message definition record, if necessary\n if (needs_def_written)\n {\n M_string header;\n header[OP_FIELD_NAME] = std::string((char*)&OP_MSG_DEF, 1);\n header[TOPIC_FIELD_NAME] = topic_name;\n header[MD5_FIELD_NAME] = msg_info.md5sum;\n header[TYPE_FIELD_NAME] = msg_info.datatype;\n header[DEF_FIELD_NAME] = msg_info.msg_def;\n writeHeader(header, 0);\n }\n\n \/\/ Serialize the message into the message buffer\n if (message_buf_size_ < msg->serializationLength())\n {\n if (message_buf_size_ == 0)\n message_buf_size_ = msg->serializationLength();\n else\n {\n while (message_buf_size_ < msg->serializationLength())\n message_buf_size_ *= 2;\n }\n message_buf_ = (unsigned char*)realloc(message_buf_, message_buf_size_);\n ROS_ASSERT(message_buf_);\n }\n msg->serialize(message_buf_, 0);\n\n \/\/ Write a message instance record\n M_string header;\n header[OP_FIELD_NAME] = std::string((char*)&OP_MSG_DATA, 1);\n header[TOPIC_FIELD_NAME] = topic_name;\n header[MD5_FIELD_NAME] = msg_info.md5sum;\n header[TYPE_FIELD_NAME] = msg_info.datatype;\n header[SEC_FIELD_NAME] = std::string((char*)&time.sec, 4);\n header[NSEC_FIELD_NAME] = std::string((char*)&time.nsec, 4);\n writeRecord(header, (char*)message_buf_, msg->serializationLength());\n if (record_file_.fail())\n {\n ROS_FATAL(\"rosrecord::Record: could not write to file. Check permissions and diskspace\\n\");\n return false;\n }\n }\n\n return true;\n}\n\nvoid ros::record::Recorder::writeFileHeader()\n{\n boost::mutex::scoped_lock lock(record_mutex_);\n\n \/\/ Remember position of file header record\n file_header_pos_ = record_pos_;\n\n \/\/ Write file header record\n M_string header;\n header[OP_FIELD_NAME] = std::string((char*)&OP_FILE_HEADER, 1);\n header[INDEX_POS_FIELD_NAME] = std::string((char*)&index_data_pos_, 8);\n\n boost::shared_array header_buffer;\n uint32_t header_len;\n Header::write(header, header_buffer, header_len);\n uint32_t data_len = 0;\n if (header_len < FILE_HEADER_LENGTH)\n data_len = FILE_HEADER_LENGTH - header_len;\n write((char*)&header_len, 4);\n write((char*)header_buffer.get(), header_len);\n write((char*)&data_len, 4);\n\n \/\/ Pad the file header record out\n if (data_len > 0)\n {\n std::string padding;\n padding.resize(data_len, ' ');\n write(padding);\n }\n}\n\nvoid ros::record::Recorder::writeIndex()\n{\n\t{\n\t\tboost::mutex::scoped_lock lock(record_mutex_);\n\n\t\t\/\/ Remember position of first index record\n\t\tindex_data_pos_ = record_pos_;\n\n\t\tfor (std::map >::const_iterator i = topic_indexes_.begin(); i != topic_indexes_.end(); i++)\n\t\t{\n\t\t\tconst std::string& topic_name = i->first;\n\t\t\tconst std::vector& topic_index = i->second;\n\n\t\t\tuint32_t topic_index_size = topic_index.size();\n\n\t const MsgInfo& msg_info = topics_recorded_[topic_name];\n\n\t \/\/ Write the index record header\n\t\t\tM_string header;\n\t\t\theader[OP_FIELD_NAME] = std::string((char*)&OP_INDEX_DATA, 1);\n\t\t\theader[TOPIC_FIELD_NAME] = topic_name;\n\t header[TYPE_FIELD_NAME] = msg_info.datatype;\n\t\t\theader[VER_FIELD_NAME] = std::string((char*)&INDEX_VERSION, 4);\n\t\t\theader[COUNT_FIELD_NAME] = std::string((char*)&topic_index_size, 4);\n\n\t\t\tuint32_t data_len = topic_index_size * sizeof(IndexEntry);\n\t\t\twriteHeader(header, data_len);\n\n\t\t\t\/\/ Write the index record data (pairs of timestamp and position in file)\n\t\t\tfor (std::vector::const_iterator j = topic_index.begin(); j != topic_index.end(); j++)\n\t\t\t{\n\t\t\t\tconst IndexEntry& index_entry = *j;\n\t\t\t\twrite((char*)&index_entry.sec, 4);\n\t\t\t\twrite((char*)&index_entry.nsec, 4);\n\t\t\t\twrite((char*)&index_entry.pos, 8);\n\t\t\t}\n\t\t}\n\t}\n\n\t\/\/ Re-open the file for random access, and rewrite the file header to point to the first index data message\n closeFile();\n openFile(file_name_, true);\n seek(file_header_pos_);\n writeFileHeader();\n}\n\n\/\/\n\nvoid ros::record::Recorder::writeRecord(const M_string& fields, const char* data, uint32_t data_len)\n{\n writeHeader(fields, data_len);\n write(data, data_len);\n}\n\nvoid ros::record::Recorder::writeHeader(const M_string& fields, uint32_t data_len)\n{\n boost::shared_array header_buffer;\n uint32_t header_len;\n Header::write(fields, header_buffer, header_len);\n\n write((char*)&header_len, 4);\n write((char*)header_buffer.get(), header_len);\n write((char*)&data_len, 4);\n}\n\nvoid ros::record::Recorder::write(const char* s, std::streamsize n)\n{\n record_stream_.write(s, n);\n record_pos_ += n;\n}\n\nvoid ros::record::Recorder::write(const std::string& s)\n{\n write(s.c_str(), s.length());\n}\n\nvoid ros::record::Recorder::seek(pos_t pos)\n{\n record_file_.seekp(pos, std::ios_base::beg);\n record_pos_ = pos;\n}\n<|endoftext|>"} {"text":"\n#include \n#include \n#include \n\n#include \n#include \n\n#ifndef HPCG_NOMPI\n#include \n#endif\n\n#include \"hpcg.hpp\"\n\nstd::ofstream HPCG_fout;\n\nstatic int\nstartswith(const char *s, const char *prefix) {\n size_t n = strlen( prefix );\n if (strncmp( s, prefix, n ))\n return 0;\n return 1;\n}\n\nint\nHPCG_Init(int *argc_p, char ***argv_p, HPCG_Params & params) {\n int argc = *argc_p;\n char **argv = *argv_p;\n char fname[80];\n int i, j, iparams[3];\n char cparams[3][6] = {\"--nx=\", \"--ny=\", \"--nz=\"};\n time_t rawtime;\n tm *ptm;\n\n \/* for sequential and some MPI implementations it's OK to read first three args *\/\n for (i = 0; i < 3; ++i)\n if (argc <= i+1 || sscanf(argv[i+1], \"%d\", iparams+i) != 1 || iparams[i] < 10) iparams[i] = 0;\n\n \/* for some MPI environments, command line arguments may get complicated so we need a prefix *\/\n for (i = 1; i <= argc && argv[i]; ++i)\n for (j = 0; j < 3; ++j)\n if (startswith(argv[i], cparams[j]))\n if (sscanf(argv[i]+strlen(cparams[j]), \"%d\", iparams+j) != 1 || iparams[j] < 10) iparams[j] = 0;\n\n if (! iparams[0] && ! iparams[1] && ! iparams[2]) { \/* no geometry arguments on the command line *\/\n FILE *f = fopen(\"hpcg.dat\", \"r\");\n if (f) {\n for (i = 0; i < 3; ++i)\n if (fscanf(f, \"%d\", iparams+i) != 1 || iparams[i] < 10) iparams[i] = 0;\n\n fclose(f);\n }\n }\n\n for (i = 0; i < 3; ++i) {\n if (iparams[i] < 10)\n for (j = 1; j <= 2; ++j)\n if (iparams[(i+j)%3] > iparams[i])\n iparams[i] = iparams[(i+j)%3];\n if (iparams[i] < 10)\n iparams[i] = 10;\n }\n\n#ifndef HPCG_NOMPI\n MPI_Bcast( iparams, 3, MPI_INT, 0, MPI_COMM_WORLD );\n#endif\n\n params.nx = iparams[0];\n params.ny = iparams[1];\n params.nz = iparams[2];\n\n#ifdef HPCG_NOMPI\n params.comm_rank = 0;\n params.comm_size = 1;\n#else\n MPI_Comm_rank( MPI_COMM_WORLD, ¶ms.comm_rank );\n MPI_Comm_size( MPI_COMM_WORLD, ¶ms.comm_size );\n#endif\n\n#ifdef HPCG_NOOPENMP\n params.numThreads = 1;\n#else\n#pragma omp parallel\n params.numThreads = omp_get_num_threads();\n#endif\n\n time ( &rawtime );\n ptm = localtime(&rawtime);\n sprintf( fname, \"hpcg_log_%04d%02d%02d_%02d:%02d:%02d.txt\",\n 1900 + ptm->tm_year, ptm->tm_mon+1, ptm->tm_mday, ptm->tm_hour, ptm->tm_min, ptm->tm_sec );\n\n if (0 == params.comm_rank)\n HPCG_fout.open(fname);\n else {\n#if defined(HPCG_DEBUG) || defined(HPCG_DETAILEDDEBUG)\n char local[15];\n sprintf( local, \"%d_\", params.comm_rank );\n sprintf( fname, \"hpcg_log_%s%04d%02d%02d_%02d:%02d:%02d.txt\", local,\n 1900 + ptm->tm_year, ptm->tm_mon+1, ptm->tm_mday, ptm->tm_hour, ptm->tm_min, ptm->tm_sec );\n HPCG_fout.open(fname);\n#else\n HPCG_fout.open(\"\/dev\/null\");\n#endif\n }\n\n return 0;\n}\nAdding the omp.h include to this file, since it is needed to set the number of threads in the params struct.\n#include \n#include \n#include \n\n#include \n#include \n\n#ifndef HPCG_NOMPI\n#include \n#endif\n\n#ifndef HPCG_NOOPENMP\n#include \n#endif\n\n#include \"hpcg.hpp\"\n\nstd::ofstream HPCG_fout;\n\nstatic int\nstartswith(const char *s, const char *prefix) {\n size_t n = strlen( prefix );\n if (strncmp( s, prefix, n ))\n return 0;\n return 1;\n}\n\nint\nHPCG_Init(int *argc_p, char ***argv_p, HPCG_Params & params) {\n int argc = *argc_p;\n char **argv = *argv_p;\n char fname[80];\n int i, j, iparams[3];\n char cparams[3][6] = {\"--nx=\", \"--ny=\", \"--nz=\"};\n time_t rawtime;\n tm *ptm;\n\n \/* for sequential and some MPI implementations it's OK to read first three args *\/\n for (i = 0; i < 3; ++i)\n if (argc <= i+1 || sscanf(argv[i+1], \"%d\", iparams+i) != 1 || iparams[i] < 10) iparams[i] = 0;\n\n \/* for some MPI environments, command line arguments may get complicated so we need a prefix *\/\n for (i = 1; i <= argc && argv[i]; ++i)\n for (j = 0; j < 3; ++j)\n if (startswith(argv[i], cparams[j]))\n if (sscanf(argv[i]+strlen(cparams[j]), \"%d\", iparams+j) != 1 || iparams[j] < 10) iparams[j] = 0;\n\n if (! iparams[0] && ! iparams[1] && ! iparams[2]) { \/* no geometry arguments on the command line *\/\n FILE *f = fopen(\"hpcg.dat\", \"r\");\n if (f) {\n for (i = 0; i < 3; ++i)\n if (fscanf(f, \"%d\", iparams+i) != 1 || iparams[i] < 10) iparams[i] = 0;\n\n fclose(f);\n }\n }\n\n for (i = 0; i < 3; ++i) {\n if (iparams[i] < 10)\n for (j = 1; j <= 2; ++j)\n if (iparams[(i+j)%3] > iparams[i])\n iparams[i] = iparams[(i+j)%3];\n if (iparams[i] < 10)\n iparams[i] = 10;\n }\n\n#ifndef HPCG_NOMPI\n MPI_Bcast( iparams, 3, MPI_INT, 0, MPI_COMM_WORLD );\n#endif\n\n params.nx = iparams[0];\n params.ny = iparams[1];\n params.nz = iparams[2];\n\n#ifdef HPCG_NOMPI\n params.comm_rank = 0;\n params.comm_size = 1;\n#else\n MPI_Comm_rank( MPI_COMM_WORLD, ¶ms.comm_rank );\n MPI_Comm_size( MPI_COMM_WORLD, ¶ms.comm_size );\n#endif\n\n#ifdef HPCG_NOOPENMP\n params.numThreads = 1;\n#else\n#pragma omp parallel\n params.numThreads = omp_get_num_threads();\n#endif\n\n time ( &rawtime );\n ptm = localtime(&rawtime);\n sprintf( fname, \"hpcg_log_%04d%02d%02d_%02d:%02d:%02d.txt\",\n 1900 + ptm->tm_year, ptm->tm_mon+1, ptm->tm_mday, ptm->tm_hour, ptm->tm_min, ptm->tm_sec );\n\n if (0 == params.comm_rank)\n HPCG_fout.open(fname);\n else {\n#if defined(HPCG_DEBUG) || defined(HPCG_DETAILEDDEBUG)\n char local[15];\n sprintf( local, \"%d_\", params.comm_rank );\n sprintf( fname, \"hpcg_log_%s%04d%02d%02d_%02d:%02d:%02d.txt\", local,\n 1900 + ptm->tm_year, ptm->tm_mon+1, ptm->tm_mday, ptm->tm_hour, ptm->tm_min, ptm->tm_sec );\n HPCG_fout.open(fname);\n#else\n HPCG_fout.open(\"\/dev\/null\");\n#endif\n }\n\n return 0;\n}\n<|endoftext|>"} {"text":"#include \n#ifdef ALLEGRO_WINDOWS\n#include \n#endif\n\n#ifndef ALLEGRO_WINDOWS\n#include \n#include \n#endif\n\n#include \"globals.h\"\n#include \"init.h\"\n#include \n#include \"network\/network.h\"\n\n#include \n#include \"dumb\/include\/dumb.h\"\n#include \"dumb\/include\/aldumb.h\"\n#include \"loadpng\/loadpng.h\"\n#include \"util\/bitmap.h\"\n#include \"configuration.h\"\n#include \"script\/script.h\"\n\nusing namespace std;\n\nvolatile int Global::speed_counter = 0;\nvolatile int Global::second_counter = 0;\n\n\/* the original engine was running at 90 ticks per second, but we dont\n * need to render that fast, so TICS_PER_SECOND is really fps and\n * LOGIC_MULTIPLIER will be used to adjust the speed counter to its\n * original value.\n *\/\nstatic const int TICS_PER_SECOND = 40;\nconst double Global::LOGIC_MULTIPLIER = (double) 90 \/ (double) TICS_PER_SECOND;\n \n\npthread_mutex_t Global::loading_screen_mutex;\nbool Global::done_loading = false;\n\nconst int Global::WINDOWED = GFX_AUTODETECT_WINDOWED;\nconst int Global::FULLSCREEN = GFX_AUTODETECT_FULLSCREEN;\n\nvoid inc_speed_counter() {\n\tGlobal::speed_counter += 1;\n}\nEND_OF_FUNCTION( inc_speed_counter );\n\nvoid inc_second_counter() {\n\tGlobal::second_counter += 1;\n}\nEND_OF_FUNCTION( inc_second_counter );\n\n#ifndef ALLEGRO_WINDOWS\nstatic void handleSigSegV(int i, siginfo_t * sig, void * data){\n Bitmap::setGfxModeText();\n allegro_exit();\n \/* write to a log file or something because sigsegv shouldn't\n * normally happen.\n *\/\n exit(0);\n}\n#else\n#endif\n\n\/* catch a socket being closed prematurely on unix *\/\n#ifndef ALLEGRO_WINDOWS\nstatic void handleSigPipe( int i, siginfo_t * sig, void * data ){\n}\n\n\/*\nstatic void handleSigUsr1( int i, siginfo_t * sig, void * data ){\n\tpthread_exit( NULL );\n}\n*\/\n#endif\n\nstatic void registerSignals(){\n#ifndef ALLEGRO_WINDOWS\n\tstruct sigaction action;\n\tmemset( &action, 0, sizeof(struct sigaction) );\n\taction.sa_sigaction = handleSigPipe;\n\tsigaction( SIGPIPE, &action, NULL );\n\n\tmemset( &action, 0, sizeof(struct sigaction) );\n\taction.sa_sigaction = handleSigSegV;\n\tsigaction( SIGSEGV, &action, NULL );\n\n\t\/*\n\taction.sa_sigaction = handleSigUsr1;\n\tsigaction( SIGUSR1, &action, NULL );\n\t*\/\n#endif\n}\n\nstatic void close_paintown(){\n Bitmap::setGfxModeText();\n allegro_exit();\n exit(0);\n}\nEND_OF_FUNCTION(close_paintown)\n\nbool Global::init( int gfx ){\n\n\tostream & out = Global::debug( 0 );\n\tout << \"-- BEGIN init --\" << endl;\n out << \"Paintown version \" << Global::getVersionString() << endl;\n\tout << \"Allegro version: \" << ALLEGRO_VERSION_STR << endl;\n\tout <<\"Allegro init: \"<warn the user that he\/she is ugly#include \n#ifdef ALLEGRO_WINDOWS\n#include \n#endif\n\n#ifndef ALLEGRO_WINDOWS\n#include \n#include \n#endif\n\n#warning you are ugly\n\n#include \"globals.h\"\n#include \"init.h\"\n#include \n#include \"network\/network.h\"\n\n#include \n#include \"dumb\/include\/dumb.h\"\n#include \"dumb\/include\/aldumb.h\"\n#include \"loadpng\/loadpng.h\"\n#include \"util\/bitmap.h\"\n#include \"configuration.h\"\n#include \"script\/script.h\"\n\nusing namespace std;\n\nvolatile int Global::speed_counter = 0;\nvolatile int Global::second_counter = 0;\n\n\/* the original engine was running at 90 ticks per second, but we dont\n * need to render that fast, so TICS_PER_SECOND is really fps and\n * LOGIC_MULTIPLIER will be used to adjust the speed counter to its\n * original value.\n *\/\nstatic const int TICS_PER_SECOND = 40;\nconst double Global::LOGIC_MULTIPLIER = (double) 90 \/ (double) TICS_PER_SECOND;\n \n\npthread_mutex_t Global::loading_screen_mutex;\nbool Global::done_loading = false;\n\nconst int Global::WINDOWED = GFX_AUTODETECT_WINDOWED;\nconst int Global::FULLSCREEN = GFX_AUTODETECT_FULLSCREEN;\n\nvoid inc_speed_counter() {\n\tGlobal::speed_counter += 1;\n}\nEND_OF_FUNCTION( inc_speed_counter );\n\nvoid inc_second_counter() {\n\tGlobal::second_counter += 1;\n}\nEND_OF_FUNCTION( inc_second_counter );\n\n#ifndef ALLEGRO_WINDOWS\nstatic void handleSigSegV(int i, siginfo_t * sig, void * data){\n Bitmap::setGfxModeText();\n allegro_exit();\n \/* write to a log file or something because sigsegv shouldn't\n * normally happen.\n *\/\n exit(0);\n}\n#else\n#endif\n\n\/* catch a socket being closed prematurely on unix *\/\n#ifndef ALLEGRO_WINDOWS\nstatic void handleSigPipe( int i, siginfo_t * sig, void * data ){\n}\n\n\/*\nstatic void handleSigUsr1( int i, siginfo_t * sig, void * data ){\n\tpthread_exit( NULL );\n}\n*\/\n#endif\n\nstatic void registerSignals(){\n#ifndef ALLEGRO_WINDOWS\n\tstruct sigaction action;\n\tmemset( &action, 0, sizeof(struct sigaction) );\n\taction.sa_sigaction = handleSigPipe;\n\tsigaction( SIGPIPE, &action, NULL );\n\n\tmemset( &action, 0, sizeof(struct sigaction) );\n\taction.sa_sigaction = handleSigSegV;\n\tsigaction( SIGSEGV, &action, NULL );\n\n\t\/*\n\taction.sa_sigaction = handleSigUsr1;\n\tsigaction( SIGUSR1, &action, NULL );\n\t*\/\n#endif\n}\n\nstatic void close_paintown(){\n Bitmap::setGfxModeText();\n allegro_exit();\n exit(0);\n}\nEND_OF_FUNCTION(close_paintown)\n\nbool Global::init( int gfx ){\n\n\tostream & out = Global::debug( 0 );\n\tout << \"-- BEGIN init --\" << endl;\n out << \"Paintown version \" << Global::getVersionString() << endl;\n\tout << \"Allegro version: \" << ALLEGRO_VERSION_STR << endl;\n\tout <<\"Allegro init: \"<"} {"text":"\/*\n * Handler for HTTP requests.\n *\n * author: Max Kellermann \n *\/\n\n#include \"lb_http.hxx\"\n#include \"lb_instance.hxx\"\n#include \"lb_connection.hxx\"\n#include \"lb_config.hxx\"\n#include \"lb_session.hxx\"\n#include \"lb_cookie.hxx\"\n#include \"lb_jvm_route.hxx\"\n#include \"lb_headers.hxx\"\n#include \"lb_log.hxx\"\n#include \"ssl\/ssl_filter.hxx\"\n#include \"address_sticky.hxx\"\n#include \"http_server\/http_server.hxx\"\n#include \"http_server\/Request.hxx\"\n#include \"http_server\/Handler.hxx\"\n#include \"http_client.hxx\"\n#include \"tcp_stock.hxx\"\n#include \"tcp_balancer.hxx\"\n#include \"header_writer.hxx\"\n#include \"http_response.hxx\"\n#include \"http_headers.hxx\"\n#include \"stock\/GetHandler.hxx\"\n#include \"stock\/Item.hxx\"\n#include \"stock\/Lease.hxx\"\n#include \"access_log.hxx\"\n#include \"strmap.hxx\"\n#include \"failure.hxx\"\n#include \"bulldog.h\"\n#include \"pool.hxx\"\n#include \"net\/SocketAddress.hxx\"\n#include \"istream\/istream.hxx\"\n#include \"istream\/UnusedHoldPtr.hxx\"\n#include \"gerrno.h\"\n#include \"util\/Cancellable.hxx\"\n\n#include \n#include \n\nstruct LbRequest final\n : Cancellable, StockGetHandler, HttpResponseHandler {\n\n LbConnection &connection;\n const LbClusterConfig *cluster;\n\n TcpBalancer &balancer;\n\n HttpServerRequest &request;\n\n \/**\n * The request body.\n *\/\n UnusedHoldIstreamPtr body;\n\n CancellablePointer cancel_ptr;\n\n StockItem *stock_item;\n\n unsigned new_cookie = 0;\n\n LbRequest(LbConnection &_connection, TcpBalancer &_balancer,\n HttpServerRequest &_request,\n CancellablePointer &_cancel_ptr)\n :connection(_connection),\n balancer(_balancer),\n request(_request),\n body(request.pool, request.body) {\n _cancel_ptr = *this;\n }\n\n void Destroy() {\n DeleteFromPool(request.pool, this);\n }\n\n \/* virtual methods from class Cancellable *\/\n void Cancel() override {\n body.Clear();\n CancellablePointer c(std::move(cancel_ptr));\n Destroy();\n c.Cancel();\n }\n\n \/* virtual methods from class StockGetHandler *\/\n void OnStockItemReady(StockItem &item) override;\n void OnStockItemError(GError *error) override;\n\n \/* virtual methods from class HttpResponseHandler *\/\n void OnHttpResponse(http_status_t status, StringMap &&headers,\n Istream *body) override;\n void OnHttpError(GError *error) override;\n};\n\nstatic bool\nsend_fallback(HttpServerRequest *request,\n const LbFallbackConfig *fallback)\n{\n if (!fallback->IsDefined())\n return false;\n\n http_server_simple_response(*request, fallback->status,\n fallback->location.empty() ? nullptr : fallback->location.c_str(),\n fallback->message.empty() ? nullptr : fallback->message.c_str());\n return true;\n}\n\n\/**\n * Generate a cookie for sticky worker selection. Return only worker\n * numbers that are not known to be failing. Returns 0 on total\n * failure.\n *\/\nstatic unsigned\ngenerate_cookie(const AddressList *list)\n{\n assert(list->GetSize() >= 2);\n\n const unsigned first = lb_cookie_generate(list->GetSize());\n\n unsigned i = first;\n do {\n assert(i >= 1 && i <= list->GetSize());\n const SocketAddress address = list->addresses[i % list->GetSize()];\n if (failure_get_status(address) == FAILURE_OK &&\n bulldog_check(address.GetAddress(), address.GetSize()) &&\n !bulldog_is_fading(address.GetAddress(), address.GetSize()))\n return i;\n\n i = lb_cookie_next(list->GetSize(), i);\n } while (i != first);\n\n \/* all nodes have failed *\/\n return first;\n}\n\n\/**\n * Is the specified error a server failure, that justifies\n * blacklisting the server for a while?\n *\/\nstatic bool\nis_server_failure(GError *error)\n{\n return error->domain == http_client_quark() &&\n error->code != HTTP_CLIENT_UNSPECIFIED;\n}\n\n\/*\n * HTTP response handler\n *\n *\/\n\nvoid\nLbRequest::OnHttpResponse(http_status_t status, StringMap &&_headers,\n Istream *response_body)\n{\n HttpHeaders headers(std::move(_headers));\n\n if (request.method == HTTP_METHOD_HEAD)\n \/* pass Content-Length, even though there is no response body\n (RFC 2616 14.13) *\/\n headers.MoveToBuffer(\"content-length\");\n\n if (new_cookie != 0) {\n char buffer[64];\n \/* \"Discard\" must be last, to work around an Android bug*\/\n snprintf(buffer, sizeof(buffer),\n \"beng_lb_node=0-%x; HttpOnly; Path=\/; Version=1; Discard\",\n new_cookie);\n\n headers.Write(\"cookie2\", \"$Version=\\\"1\\\"\");\n headers.Write(\"set-cookie\", buffer);\n }\n\n http_server_response(&request, status, std::move(headers), response_body);\n Destroy();\n}\n\nvoid\nLbRequest::OnHttpError(GError *error)\n{\n if (is_server_failure(error))\n failure_add(tcp_stock_item_get_address(*stock_item));\n\n lb_connection_log_gerror(2, &connection, \"Error\", error);\n\n if (!send_fallback(&request, &cluster->fallback)) {\n const char *msg = connection.listener.verbose_response\n ? error->message\n : \"Server failure\";\n\n http_server_send_message(&request, HTTP_STATUS_BAD_GATEWAY, msg);\n }\n\n g_error_free(error);\n Destroy();\n}\n\n\/*\n * stock callback\n *\n *\/\n\nvoid\nLbRequest::OnStockItemReady(StockItem &item)\n{\n stock_item = &item;\n\n const char *peer_subject = connection.ssl_filter != nullptr\n ? ssl_filter_get_peer_subject(connection.ssl_filter)\n : nullptr;\n const char *peer_issuer_subject = connection.ssl_filter != nullptr\n ? ssl_filter_get_peer_issuer_subject(connection.ssl_filter)\n : nullptr;\n\n auto &headers = request.headers;\n lb_forward_request_headers(request.pool, headers,\n request.local_host_and_port,\n request.remote_host,\n peer_subject, peer_issuer_subject,\n cluster->mangle_via);\n\n auto *lease = NewFromPool(request.pool, item);\n\n http_client_request(request.pool,\n connection.instance.event_loop,\n tcp_stock_item_get(item),\n tcp_stock_item_get_domain(item) == AF_LOCAL\n ? FdType::FD_SOCKET : FdType::FD_TCP,\n *lease,\n item.GetStockName(),\n NULL, NULL,\n request.method, request.uri,\n HttpHeaders(std::move(headers)),\n body.Steal(), true,\n *this, cancel_ptr);\n}\n\nvoid\nLbRequest::OnStockItemError(GError *error)\n{\n lb_connection_log_gerror(2, &connection, \"Connect error\", error);\n\n body.Clear();\n\n if (!send_fallback(&request, &cluster->fallback)) {\n const char *msg = connection.listener.verbose_response\n ? error->message\n : \"Connection failure\";\n\n http_server_send_message(&request, HTTP_STATUS_BAD_GATEWAY,\n msg);\n }\n\n g_error_free(error);\n}\n\n\/*\n * http connection handler\n *\n *\/\n\nvoid\nLbConnection::HandleHttpRequest(HttpServerRequest &request,\n CancellablePointer &cancel_ptr)\n{\n ++instance.http_request_counter;\n\n request_start_time = std::chrono::steady_clock::now();\n\n const auto &goto_ = listener.destination.FindRequestLeaf(request);\n if (goto_.status != http_status_t(0)) {\n http_server_simple_response(request, goto_.status, nullptr, nullptr);\n return;\n }\n\n const auto request2 =\n NewFromPool(request.pool,\n *this, *instance.tcp_balancer,\n request, cancel_ptr);\n const auto *cluster = request2->cluster = goto_.cluster;\n\n SocketAddress bind_address = SocketAddress::Null();\n const bool transparent_source = cluster->transparent_source;\n if (transparent_source) {\n bind_address = request.remote_address;\n\n \/* reset the port to 0 to allow the kernel to choose one *\/\n if (bind_address.GetFamily() == AF_INET) {\n struct sockaddr_in *s_in = (struct sockaddr_in *)\n p_memdup(&request.pool, bind_address.GetAddress(),\n bind_address.GetSize());\n s_in->sin_port = 0;\n bind_address = SocketAddress((const struct sockaddr *)s_in,\n bind_address.GetSize());\n } else if (bind_address.GetFamily() == AF_INET6) {\n struct sockaddr_in6 *s_in = (struct sockaddr_in6 *)\n p_memdup(&request.pool, bind_address.GetAddress(),\n bind_address.GetSize());\n s_in->sin6_port = 0;\n bind_address = SocketAddress((const struct sockaddr *)s_in,\n bind_address.GetSize());\n }\n }\n\n if (cluster->HasZeroConf()) {\n \/* TODO: generalize the Zeroconf code, implement sticky *\/\n\n auto *cluster2 = instance.clusters.Find(cluster->name);\n if (cluster2 == nullptr) {\n http_server_send_message(&request,\n HTTP_STATUS_INTERNAL_SERVER_ERROR,\n \"Zeroconf cluster not found\");\n return;\n }\n\n const auto member = cluster2->Pick();\n if (member.first == nullptr) {\n http_server_send_message(&request,\n HTTP_STATUS_INTERNAL_SERVER_ERROR,\n \"Zeroconf cluster is empty\");\n return;\n }\n\n assert(member.second.IsDefined());\n\n tcp_stock_get(instance.tcp_stock, &request.pool, member.first,\n transparent_source, bind_address,\n member.second,\n 20,\n *request2, request2->cancel_ptr);\n\n return;\n }\n\n \/* prepare for the balancer *\/\n\n unsigned session_sticky = 0;\n switch (cluster->address_list.sticky_mode) {\n case StickyMode::NONE:\n case StickyMode::FAILOVER:\n \/* these modes require no preparation; they are handled\n completely by balancer_get() *\/\n break;\n\n case StickyMode::SOURCE_IP:\n \/* calculate session_sticky from remote address *\/\n session_sticky = socket_address_sticky(request.remote_address);\n break;\n\n case StickyMode::SESSION_MODULO:\n \/* calculate session_sticky from beng-proxy session id *\/\n session_sticky = lb_session_get(request.headers,\n cluster->session_cookie.c_str());\n break;\n\n case StickyMode::COOKIE:\n \/* calculate session_sticky from beng-lb cookie *\/\n session_sticky = lb_cookie_get(request.headers);\n if (session_sticky == 0)\n request2->new_cookie = session_sticky =\n generate_cookie(&cluster->address_list);\n\n break;\n\n case StickyMode::JVM_ROUTE:\n \/* calculate session_sticky from JSESSIONID cookie suffix *\/\n session_sticky = lb_jvm_route_get(request.headers, *cluster);\n break;\n }\n\n tcp_balancer_get(request2->balancer, request.pool,\n transparent_source,\n bind_address,\n session_sticky,\n cluster->address_list,\n 20,\n *request2, request2->cancel_ptr);\n}\n\nvoid\nLbConnection::LogHttpRequest(HttpServerRequest &request,\n http_status_t status, int64_t length,\n uint64_t bytes_received, uint64_t bytes_sent)\n{\n access_log(&request, nullptr,\n request.headers.Get(\"referer\"),\n request.headers.Get(\"user-agent\"),\n status, length,\n bytes_received, bytes_sent,\n std::chrono::steady_clock::now() - request_start_time);\n}\n\nvoid\nLbConnection::HttpConnectionError(GError *error)\n{\n int level = 2;\n\n if (error->domain == errno_quark() && error->code == ECONNRESET)\n level = 4;\n\n lb_connection_log_gerror(level, this, \"Error\", error);\n g_error_free(error);\n\n assert(http != nullptr);\n http = nullptr;\n\n lb_connection_remove(this);\n}\n\nvoid\nLbConnection::HttpConnectionClosed()\n{\n assert(http != nullptr);\n http = nullptr;\n\n lb_connection_remove(this);\n}\nlb_http: convert pointers to references\/*\n * Handler for HTTP requests.\n *\n * author: Max Kellermann \n *\/\n\n#include \"lb_http.hxx\"\n#include \"lb_instance.hxx\"\n#include \"lb_connection.hxx\"\n#include \"lb_config.hxx\"\n#include \"lb_session.hxx\"\n#include \"lb_cookie.hxx\"\n#include \"lb_jvm_route.hxx\"\n#include \"lb_headers.hxx\"\n#include \"lb_log.hxx\"\n#include \"ssl\/ssl_filter.hxx\"\n#include \"address_sticky.hxx\"\n#include \"http_server\/http_server.hxx\"\n#include \"http_server\/Request.hxx\"\n#include \"http_server\/Handler.hxx\"\n#include \"http_client.hxx\"\n#include \"tcp_stock.hxx\"\n#include \"tcp_balancer.hxx\"\n#include \"header_writer.hxx\"\n#include \"http_response.hxx\"\n#include \"http_headers.hxx\"\n#include \"stock\/GetHandler.hxx\"\n#include \"stock\/Item.hxx\"\n#include \"stock\/Lease.hxx\"\n#include \"access_log.hxx\"\n#include \"strmap.hxx\"\n#include \"failure.hxx\"\n#include \"bulldog.h\"\n#include \"pool.hxx\"\n#include \"net\/SocketAddress.hxx\"\n#include \"istream\/istream.hxx\"\n#include \"istream\/UnusedHoldPtr.hxx\"\n#include \"gerrno.h\"\n#include \"util\/Cancellable.hxx\"\n\n#include \n#include \n\nstruct LbRequest final\n : Cancellable, StockGetHandler, HttpResponseHandler {\n\n LbConnection &connection;\n const LbClusterConfig *cluster;\n\n TcpBalancer &balancer;\n\n HttpServerRequest &request;\n\n \/**\n * The request body.\n *\/\n UnusedHoldIstreamPtr body;\n\n CancellablePointer cancel_ptr;\n\n StockItem *stock_item;\n\n unsigned new_cookie = 0;\n\n LbRequest(LbConnection &_connection, TcpBalancer &_balancer,\n HttpServerRequest &_request,\n CancellablePointer &_cancel_ptr)\n :connection(_connection),\n balancer(_balancer),\n request(_request),\n body(request.pool, request.body) {\n _cancel_ptr = *this;\n }\n\n void Destroy() {\n DeleteFromPool(request.pool, this);\n }\n\n \/* virtual methods from class Cancellable *\/\n void Cancel() override {\n body.Clear();\n CancellablePointer c(std::move(cancel_ptr));\n Destroy();\n c.Cancel();\n }\n\n \/* virtual methods from class StockGetHandler *\/\n void OnStockItemReady(StockItem &item) override;\n void OnStockItemError(GError *error) override;\n\n \/* virtual methods from class HttpResponseHandler *\/\n void OnHttpResponse(http_status_t status, StringMap &&headers,\n Istream *body) override;\n void OnHttpError(GError *error) override;\n};\n\nstatic bool\nsend_fallback(HttpServerRequest &request,\n const LbFallbackConfig &fallback)\n{\n if (!fallback.IsDefined())\n return false;\n\n http_server_simple_response(request, fallback.status,\n fallback.location.empty() ? nullptr : fallback.location.c_str(),\n fallback.message.empty() ? nullptr : fallback.message.c_str());\n return true;\n}\n\n\/**\n * Generate a cookie for sticky worker selection. Return only worker\n * numbers that are not known to be failing. Returns 0 on total\n * failure.\n *\/\nstatic unsigned\ngenerate_cookie(const AddressList *list)\n{\n assert(list->GetSize() >= 2);\n\n const unsigned first = lb_cookie_generate(list->GetSize());\n\n unsigned i = first;\n do {\n assert(i >= 1 && i <= list->GetSize());\n const SocketAddress address = list->addresses[i % list->GetSize()];\n if (failure_get_status(address) == FAILURE_OK &&\n bulldog_check(address.GetAddress(), address.GetSize()) &&\n !bulldog_is_fading(address.GetAddress(), address.GetSize()))\n return i;\n\n i = lb_cookie_next(list->GetSize(), i);\n } while (i != first);\n\n \/* all nodes have failed *\/\n return first;\n}\n\n\/**\n * Is the specified error a server failure, that justifies\n * blacklisting the server for a while?\n *\/\nstatic bool\nis_server_failure(GError *error)\n{\n return error->domain == http_client_quark() &&\n error->code != HTTP_CLIENT_UNSPECIFIED;\n}\n\n\/*\n * HTTP response handler\n *\n *\/\n\nvoid\nLbRequest::OnHttpResponse(http_status_t status, StringMap &&_headers,\n Istream *response_body)\n{\n HttpHeaders headers(std::move(_headers));\n\n if (request.method == HTTP_METHOD_HEAD)\n \/* pass Content-Length, even though there is no response body\n (RFC 2616 14.13) *\/\n headers.MoveToBuffer(\"content-length\");\n\n if (new_cookie != 0) {\n char buffer[64];\n \/* \"Discard\" must be last, to work around an Android bug*\/\n snprintf(buffer, sizeof(buffer),\n \"beng_lb_node=0-%x; HttpOnly; Path=\/; Version=1; Discard\",\n new_cookie);\n\n headers.Write(\"cookie2\", \"$Version=\\\"1\\\"\");\n headers.Write(\"set-cookie\", buffer);\n }\n\n http_server_response(&request, status, std::move(headers), response_body);\n Destroy();\n}\n\nvoid\nLbRequest::OnHttpError(GError *error)\n{\n if (is_server_failure(error))\n failure_add(tcp_stock_item_get_address(*stock_item));\n\n lb_connection_log_gerror(2, &connection, \"Error\", error);\n\n if (!send_fallback(request, cluster->fallback)) {\n const char *msg = connection.listener.verbose_response\n ? error->message\n : \"Server failure\";\n\n http_server_send_message(&request, HTTP_STATUS_BAD_GATEWAY, msg);\n }\n\n g_error_free(error);\n Destroy();\n}\n\n\/*\n * stock callback\n *\n *\/\n\nvoid\nLbRequest::OnStockItemReady(StockItem &item)\n{\n stock_item = &item;\n\n const char *peer_subject = connection.ssl_filter != nullptr\n ? ssl_filter_get_peer_subject(connection.ssl_filter)\n : nullptr;\n const char *peer_issuer_subject = connection.ssl_filter != nullptr\n ? ssl_filter_get_peer_issuer_subject(connection.ssl_filter)\n : nullptr;\n\n auto &headers = request.headers;\n lb_forward_request_headers(request.pool, headers,\n request.local_host_and_port,\n request.remote_host,\n peer_subject, peer_issuer_subject,\n cluster->mangle_via);\n\n auto *lease = NewFromPool(request.pool, item);\n\n http_client_request(request.pool,\n connection.instance.event_loop,\n tcp_stock_item_get(item),\n tcp_stock_item_get_domain(item) == AF_LOCAL\n ? FdType::FD_SOCKET : FdType::FD_TCP,\n *lease,\n item.GetStockName(),\n NULL, NULL,\n request.method, request.uri,\n HttpHeaders(std::move(headers)),\n body.Steal(), true,\n *this, cancel_ptr);\n}\n\nvoid\nLbRequest::OnStockItemError(GError *error)\n{\n lb_connection_log_gerror(2, &connection, \"Connect error\", error);\n\n body.Clear();\n\n if (!send_fallback(request, cluster->fallback)) {\n const char *msg = connection.listener.verbose_response\n ? error->message\n : \"Connection failure\";\n\n http_server_send_message(&request, HTTP_STATUS_BAD_GATEWAY,\n msg);\n }\n\n g_error_free(error);\n}\n\n\/*\n * http connection handler\n *\n *\/\n\nvoid\nLbConnection::HandleHttpRequest(HttpServerRequest &request,\n CancellablePointer &cancel_ptr)\n{\n ++instance.http_request_counter;\n\n request_start_time = std::chrono::steady_clock::now();\n\n const auto &goto_ = listener.destination.FindRequestLeaf(request);\n if (goto_.status != http_status_t(0)) {\n http_server_simple_response(request, goto_.status, nullptr, nullptr);\n return;\n }\n\n const auto request2 =\n NewFromPool(request.pool,\n *this, *instance.tcp_balancer,\n request, cancel_ptr);\n const auto *cluster = request2->cluster = goto_.cluster;\n\n SocketAddress bind_address = SocketAddress::Null();\n const bool transparent_source = cluster->transparent_source;\n if (transparent_source) {\n bind_address = request.remote_address;\n\n \/* reset the port to 0 to allow the kernel to choose one *\/\n if (bind_address.GetFamily() == AF_INET) {\n struct sockaddr_in *s_in = (struct sockaddr_in *)\n p_memdup(&request.pool, bind_address.GetAddress(),\n bind_address.GetSize());\n s_in->sin_port = 0;\n bind_address = SocketAddress((const struct sockaddr *)s_in,\n bind_address.GetSize());\n } else if (bind_address.GetFamily() == AF_INET6) {\n struct sockaddr_in6 *s_in = (struct sockaddr_in6 *)\n p_memdup(&request.pool, bind_address.GetAddress(),\n bind_address.GetSize());\n s_in->sin6_port = 0;\n bind_address = SocketAddress((const struct sockaddr *)s_in,\n bind_address.GetSize());\n }\n }\n\n if (cluster->HasZeroConf()) {\n \/* TODO: generalize the Zeroconf code, implement sticky *\/\n\n auto *cluster2 = instance.clusters.Find(cluster->name);\n if (cluster2 == nullptr) {\n http_server_send_message(&request,\n HTTP_STATUS_INTERNAL_SERVER_ERROR,\n \"Zeroconf cluster not found\");\n return;\n }\n\n const auto member = cluster2->Pick();\n if (member.first == nullptr) {\n http_server_send_message(&request,\n HTTP_STATUS_INTERNAL_SERVER_ERROR,\n \"Zeroconf cluster is empty\");\n return;\n }\n\n assert(member.second.IsDefined());\n\n tcp_stock_get(instance.tcp_stock, &request.pool, member.first,\n transparent_source, bind_address,\n member.second,\n 20,\n *request2, request2->cancel_ptr);\n\n return;\n }\n\n \/* prepare for the balancer *\/\n\n unsigned session_sticky = 0;\n switch (cluster->address_list.sticky_mode) {\n case StickyMode::NONE:\n case StickyMode::FAILOVER:\n \/* these modes require no preparation; they are handled\n completely by balancer_get() *\/\n break;\n\n case StickyMode::SOURCE_IP:\n \/* calculate session_sticky from remote address *\/\n session_sticky = socket_address_sticky(request.remote_address);\n break;\n\n case StickyMode::SESSION_MODULO:\n \/* calculate session_sticky from beng-proxy session id *\/\n session_sticky = lb_session_get(request.headers,\n cluster->session_cookie.c_str());\n break;\n\n case StickyMode::COOKIE:\n \/* calculate session_sticky from beng-lb cookie *\/\n session_sticky = lb_cookie_get(request.headers);\n if (session_sticky == 0)\n request2->new_cookie = session_sticky =\n generate_cookie(&cluster->address_list);\n\n break;\n\n case StickyMode::JVM_ROUTE:\n \/* calculate session_sticky from JSESSIONID cookie suffix *\/\n session_sticky = lb_jvm_route_get(request.headers, *cluster);\n break;\n }\n\n tcp_balancer_get(request2->balancer, request.pool,\n transparent_source,\n bind_address,\n session_sticky,\n cluster->address_list,\n 20,\n *request2, request2->cancel_ptr);\n}\n\nvoid\nLbConnection::LogHttpRequest(HttpServerRequest &request,\n http_status_t status, int64_t length,\n uint64_t bytes_received, uint64_t bytes_sent)\n{\n access_log(&request, nullptr,\n request.headers.Get(\"referer\"),\n request.headers.Get(\"user-agent\"),\n status, length,\n bytes_received, bytes_sent,\n std::chrono::steady_clock::now() - request_start_time);\n}\n\nvoid\nLbConnection::HttpConnectionError(GError *error)\n{\n int level = 2;\n\n if (error->domain == errno_quark() && error->code == ECONNRESET)\n level = 4;\n\n lb_connection_log_gerror(level, this, \"Error\", error);\n g_error_free(error);\n\n assert(http != nullptr);\n http = nullptr;\n\n lb_connection_remove(this);\n}\n\nvoid\nLbConnection::HttpConnectionClosed()\n{\n assert(http != nullptr);\n http = nullptr;\n\n lb_connection_remove(this);\n}\n<|endoftext|>"} {"text":"\/\/ This file is part of the dune-gdt project:\n\/\/ https:\/\/github.com\/dune-community\/dune-gdt\n\/\/ Copyright 2010-2018 dune-gdt developers and contributors. All rights reserved.\n\/\/ License: Dual licensed as BSD 2-Clause License (http:\/\/opensource.org\/licenses\/BSD-2-Clause)\n\/\/ or GPL-2.0+ (http:\/\/opensource.org\/licenses\/gpl-license)\n\/\/ with \"runtime exception\" (http:\/\/www.dune-project.org\/license.html)\n\/\/ Authors:\n\/\/ Felix Schindler (2013 - 2017)\n\/\/ Rene Milk (2014, 2016)\n\/\/ Tobias Leibner (2014, 2016)\n\n#ifndef DUNE_GDT_SPACES_CONSTRAINTS_HH\n#define DUNE_GDT_SPACES_CONSTRAINTS_HH\n\n#include \n\n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n\nnamespace Dune {\nnamespace GDT {\nnamespace internal {\n\n\n\/\/\/\/ forward, needed for friendlyness\n\/\/ template \n\/\/ class ConstraintsWrapper;\n\n\n} \/\/ namespace internal\n\n\n\/**\n * \\brief CRTP interface for all implementations of constraints.\n *\n * We need this interface for template matching in the SystemAssembler.\n *\/\n\/\/ template \n\/\/ class ConstraintsInterface : public XT::CRTPInterface, Traits>\n\/\/{\n\/\/ public:\n\/\/ typedef typename Traits::derived_type derived_type;\n\/\/}; \/\/ class ConstraintsInterface\n\n\n\/\/\/\/ forward\n\/\/ template \n\/\/ class DirichletConstraints;\n\n\n\/\/ namespace internal {\n\n\n\/\/ template \n\/\/ class DirichletConstraintsTraits\n\/\/{\n\/\/ public:\n\/\/ typedef DirichletConstraints derived_type;\n\/\/};\n\n\n\/\/} \/\/ namespace internal\n\ntemplate \nstruct setUnion\n{\n std::set operator()(const std::set& a, const std::set& b)\n {\n std::set result = a;\n result.insert(b.begin(), b.end());\n return result;\n }\n};\n\n\ntemplate \nclass DirichletConstraints\n : public Dune::XT::Grid::ElementFunctor,\n public XT::Common::\n ThreadResultPropagator, std::set, setUnion>\n{\n using ThisType = DirichletConstraints;\n using BaseType = XT::Grid::ElementFunctor;\n using Propagator = XT::Common::ThreadResultPropagator, setUnion>;\n friend Propagator;\n\npublic:\n using BoundaryInfoType = XT::Grid::BoundaryInfo;\n using ElementType = typename ThisType::ElementType;\n using GridView = typename SpaceType::GridViewType;\n static const constexpr size_t d = SpaceType::d;\n static const constexpr size_t r = SpaceType::r;\n static const constexpr size_t rC = SpaceType::rC;\n using R = typename SpaceType::R;\n\n DirichletConstraints(const BoundaryInfoType& bnd_info, const SpaceType& space, const bool set = true)\n : Propagator(this)\n , boundary_info_(bnd_info)\n , space_(space)\n , set_(set)\n {\n }\n\n void apply_local(const ElementType& element) override final\n {\n std::set local_DoFs;\n const auto& fe = space_.finite_element(element.type());\n const auto& reference_element = ReferenceElements::general(element.geometry().type());\n const auto local_key_indices = fe.coefficients().local_key_indices();\n const auto intersection_it_end = space_.grid_view().iend(element);\n for (auto intersection_it = space_.grid_view().ibegin(element); intersection_it != intersection_it_end;\n ++intersection_it) {\n \/\/ only work on dirichlet ones\n const auto& intersection = *intersection_it;\n \/\/ actual dirichlet intersections + process boundaries for parallel runs\n if (boundary_info_.type(intersection) == XT::Grid::DirichletBoundary()\n || (!intersection.neighbor() && !intersection.boundary())) {\n const auto intersection_index = intersection.indexInInside();\n for (const auto& local_DoF : local_key_indices[1][intersection_index])\n local_DoFs.insert(local_DoF);\n for (int ii = 0; ii < reference_element.size(intersection_index, 1, d); ++ii) {\n const auto element_vertex_id = reference_element.subEntity(intersection_index, 1, ii, d);\n for (const auto& local_DoF : local_key_indices[d][element_vertex_id])\n local_DoFs.insert(local_DoF);\n }\n }\n }\n if (local_DoFs.size() > 0) {\n for (const auto& local_DoF : local_DoFs) {\n dirichlet_DoFs_.insert(space_.mapper().global_index(element, local_DoF));\n }\n }\n }\n\n const BoundaryInfoType& boundary_info() const\n {\n return boundary_info_;\n }\n\n const std::set& dirichlet_DoFs() const\n {\n return dirichlet_DoFs_;\n }\n\n template \n void apply(XT::LA::MatrixInterface& matrix) const\n {\n if (set_) {\n for (const auto& DoF : dirichlet_DoFs_)\n matrix.unit_row(DoF);\n } else {\n for (const auto& DoF : dirichlet_DoFs_)\n matrix.clear_row(DoF);\n }\n } \/\/ ... apply(...)\n\n template \n void apply(XT::LA::VectorInterface& vector) const\n {\n for (const auto& DoF : dirichlet_DoFs_)\n vector[DoF] = 0.0;\n }\n\n template \n void apply(XT::LA::MatrixInterface& matrix, XT::LA::VectorInterface& vector) const\n {\n if (set_) {\n for (const auto& DoF : dirichlet_DoFs_) {\n matrix.unit_row(DoF);\n matrix.unit_col(DoF);\n vector[DoF] = 0.0;\n }\n } else {\n for (const auto& DoF : dirichlet_DoFs_) {\n matrix.clear_row(DoF);\n vector[DoF] = 0.0;\n }\n }\n } \/\/ ... apply(...)\n\n void finalize() override\n {\n this->finalize_imp();\n }\n\n BaseType* copy() override\n {\n return Propagator::copy_imp();\n }\n\n std::set result() const\n {\n return dirichlet_DoFs_;\n }\n\n void set_result(std::set res)\n {\n dirichlet_DoFs_ = res;\n }\n\n\nprivate:\n const BoundaryInfoType& boundary_info_;\n const SpaceInterface& space_;\n \/\/ const size_t size_;\n const bool set_;\n std::set dirichlet_DoFs_;\n \/\/ std::mutex mutex_;\n}; \/\/ class DirichletConstraints\n\n\n} \/\/ namespace GDT\n} \/\/ namespace Dune\n\n#endif \/\/ DUNE_GDT_SPACES_CONSTRAINTS_HH\n[constraints] first draft of Dirichletconstraints\/\/ This file is part of the dune-gdt project:\n\/\/ https:\/\/github.com\/dune-community\/dune-gdt\n\/\/ Copyright 2010-2018 dune-gdt developers and contributors. All rights reserved.\n\/\/ License: Dual licensed as BSD 2-Clause License (http:\/\/opensource.org\/licenses\/BSD-2-Clause)\n\/\/ or GPL-2.0+ (http:\/\/opensource.org\/licenses\/gpl-license)\n\/\/ with \"runtime exception\" (http:\/\/www.dune-project.org\/license.html)\n\/\/ Authors:\n\/\/ Felix Schindler (2013 - 2017)\n\/\/ Rene Milk (2014, 2016)\n\/\/ Tobias Leibner (2014, 2016)\n\n#ifndef DUNE_GDT_SPACES_CONSTRAINTS_HH\n#define DUNE_GDT_SPACES_CONSTRAINTS_HH\n\n#include \n\n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n\nnamespace Dune {\nnamespace GDT {\nnamespace internal {\n\n\ntemplate \nstruct setUnion\n{\n std::set operator()(const std::set& a, const std::set& b)\n {\n std::set result = a;\n result.insert(b.begin(), b.end());\n return result;\n }\n};\n\n\n} \/\/ namespace internal\n\n\ntemplate \nclass DirichletConstraints\n : public Dune::XT::Grid::ElementFunctor,\n public XT::Common::ThreadResultPropagator,\n std::set,\n internal::setUnion>\n{\n using ThisType = DirichletConstraints;\n using BaseType = XT::Grid::ElementFunctor;\n using Propagator = XT::Common::ThreadResultPropagator, internal::setUnion>;\n friend Propagator;\n\npublic:\n using BoundaryInfoType = XT::Grid::BoundaryInfo;\n using ElementType = typename ThisType::ElementType;\n using GridView = typename SpaceType::GridViewType;\n static const constexpr size_t d = SpaceType::d;\n static const constexpr size_t r = SpaceType::r;\n static const constexpr size_t rC = SpaceType::rC;\n using R = typename SpaceType::R;\n\n DirichletConstraints(const BoundaryInfoType& bnd_info, const SpaceType& space, const bool set = true)\n : Propagator(this)\n , boundary_info_(bnd_info)\n , space_(space)\n , set_(set)\n {\n }\n\n void apply_local(const ElementType& element) override final\n {\n std::set local_DoFs;\n const auto& fe = space_.finite_element(element.type());\n const auto& reference_element = ReferenceElements::general(element.geometry().type());\n const auto local_key_indices = fe.coefficients().local_key_indices();\n const auto intersection_it_end = space_.grid_view().iend(element);\n for (auto intersection_it = space_.grid_view().ibegin(element); intersection_it != intersection_it_end;\n ++intersection_it) {\n \/\/ only work on dirichlet ones\n const auto& intersection = *intersection_it;\n \/\/ actual dirichlet intersections + process boundaries for parallel runs\n if (boundary_info_.type(intersection) == XT::Grid::DirichletBoundary()\n || (!intersection.neighbor() && !intersection.boundary())) {\n const auto intersection_index = intersection.indexInInside();\n for (const auto& local_DoF : local_key_indices[1][intersection_index])\n local_DoFs.insert(local_DoF);\n for (int ii = 0; ii < reference_element.size(intersection_index, 1, d); ++ii) {\n const auto element_vertex_id = reference_element.subEntity(intersection_index, 1, ii, d);\n for (const auto& local_DoF : local_key_indices[d][element_vertex_id])\n local_DoFs.insert(local_DoF);\n }\n }\n }\n if (local_DoFs.size() > 0) {\n for (const auto& local_DoF : local_DoFs) {\n dirichlet_DoFs_.insert(space_.mapper().global_index(element, local_DoF));\n }\n }\n }\n\n const BoundaryInfoType& boundary_info() const\n {\n return boundary_info_;\n }\n\n const std::set& dirichlet_DoFs() const\n {\n return dirichlet_DoFs_;\n }\n\n template \n void apply(XT::LA::MatrixInterface& matrix) const\n {\n if (set_) {\n for (const auto& DoF : dirichlet_DoFs_)\n matrix.unit_row(DoF);\n } else {\n for (const auto& DoF : dirichlet_DoFs_)\n matrix.clear_row(DoF);\n }\n } \/\/ ... apply(...)\n\n template \n void apply(XT::LA::VectorInterface& vector) const\n {\n for (const auto& DoF : dirichlet_DoFs_)\n vector[DoF] = 0.0;\n }\n\n template \n void apply(XT::LA::MatrixInterface& matrix, XT::LA::VectorInterface& vector) const\n {\n if (set_) {\n for (const auto& DoF : dirichlet_DoFs_) {\n matrix.unit_row(DoF);\n matrix.unit_col(DoF);\n vector[DoF] = 0.0;\n }\n } else {\n for (const auto& DoF : dirichlet_DoFs_) {\n matrix.clear_row(DoF);\n vector[DoF] = 0.0;\n }\n }\n } \/\/ ... apply(...)\n\n void finalize() override\n {\n this->finalize_imp();\n }\n\n BaseType* copy() override\n {\n return Propagator::copy_imp();\n }\n\n std::set result() const\n {\n return dirichlet_DoFs_;\n }\n\n void set_result(std::set res)\n {\n dirichlet_DoFs_ = res;\n }\n\nprivate:\n const BoundaryInfoType& boundary_info_;\n const SpaceInterface& space_;\n const bool set_;\n std::set dirichlet_DoFs_;\n}; \/\/ class DirichletConstraints\n\n\n} \/\/ namespace GDT\n} \/\/ namespace Dune\n\n#endif \/\/ DUNE_GDT_SPACES_CONSTRAINTS_HH\n<|endoftext|>"} {"text":"#ifndef DUNE_STUFF_FUNCTION_PRODUCT_HH\n#define DUNE_STUFF_FUNCTION_PRODUCT_HH\n\n#include \n#include \n\n#include \n\n#include \"interface.hh\"\n\nnamespace Dune {\nnamespace Stuff {\nnamespace Function {\n\n\n\/\/ forward, to allow for specialization\ntemplate< class LeftFactorDomainFieldImp, int dimDomainLeftFactor, class LeftFactorRangeFieldImp, int dimRangeLeftFactor,\n class RightFactorDomainFieldImp, int dimDomainRightFactor, class RightFactorRangeFieldImp, int dimRangeRightFactor >\nclass Product{\npublic:\n Product() = delete;\n};\n\n\ntemplate< class DomainFieldImp, int domainDim, class RangeFieldImp >\nclass Product< DomainFieldImp, domainDim, RangeFieldImp, 1,\n DomainFieldImp, domainDim, RangeFieldImp, 1 >\n : public Interface< DomainFieldImp, domainDim, RangeFieldImp, 1 >\n{\npublic:\n typedef Product< DomainFieldImp, domainDim, RangeFieldImp, 1,\n DomainFieldImp, domainDim, RangeFieldImp, 1 > ThisType;\n typedef Interface< DomainFieldImp, domainDim, RangeFieldImp, 1 > BaseType;\n\n typedef Interface< DomainFieldImp, domainDim, RangeFieldImp, 1 > LeftFactorType;\n typedef Interface< DomainFieldImp, domainDim, RangeFieldImp, 1 > RightFactorType;\n\n typedef typename BaseType::DomainFieldType DomainFieldType;\n static const int dimDomain = BaseType::dimDomain;\n typedef typename BaseType::DomainType DomainType;\n\n typedef typename BaseType::RangeFieldType RangeFieldType;\n static const int dimRange = BaseType::dimRange;\n typedef typename BaseType::RangeType RangeType;\n\n typedef typename BaseType::ParamFieldType ParamFieldType;\n static const int maxParamDim = BaseType::maxParamDim;\n typedef typename BaseType::ParamType ParamType;\n\n typedef typename BaseType::ComponentType ComponentType;\n typedef typename BaseType::CoefficientType CoefficientType;\n\n static std::string id()\n {\n return BaseType::id() + \".product\";\n }\n\n Product(const Dune::shared_ptr< const LeftFactorType > _leftFactor,\n const Dune::shared_ptr< const RightFactorType > _rightFactor)\n : leftFactor_(_leftFactor)\n , rightFactor_(_rightFactor)\n , leftParametric_(leftFactor_->parametric())\n , rightParametric_(rightFactor_->parametric())\n , leftSeparable_(leftParametric_ ? leftFactor_->separable() : false)\n , rightSeparable_(rightParametric_ ? rightFactor_->separable() : false)\n , name_(\"product of '\" + leftFactor_->name() + \"' and '\" + rightFactor_->name())\n , order_((leftFactor_->order() >= 0 && rightFactor_->order() >= 0)\n ? (leftFactor_->order() + rightFactor_->order())\n : -1)\n {\n \/\/ sanity checks\n if (leftParametric_ && rightParametric_)\n DUNE_THROW(Dune::InvalidStateException,\n \"\\n\" << Dune::Stuff::Common::colorStringRed(\"ERROR:\")\n << \" only one factor may be parametric!\");\n \/\/ build up components\n if (leftSeparable_) {\n for (size_t qq = 0; qq < leftFactor_->numComponents(); ++qq)\n components_.push_back(Dune::make_shared< ThisType >(leftFactor_->components()[qq], rightFactor_));\n } else if (rightSeparable_) {\n for (size_t qq = 0; qq < rightFactor_->numComponents(); ++qq)\n components_.push_back(Dune::make_shared< ThisType >(leftFactor_, rightFactor_->components()[qq]));\n }\n } \/\/ Product\n\n Dune::shared_ptr< const LeftFactorType > leftFactor() const\n {\n return leftFactor_;\n }\n\n Dune::shared_ptr< const RightFactorType > rightFactor() const\n {\n return rightFactor_;\n }\n\n virtual bool parametric() const\n {\n return leftParametric_ || rightParametric_;\n }\n\n virtual std::string name() const\n {\n return name_;\n }\n\n virtual int order() const\n {\n return order_;\n }\n\n virtual void evaluate(const DomainType& x, RangeType& ret) const\n {\n if (parametric())\n DUNE_THROW(Dune::InvalidStateException,\n \"\\n\" << Dune::Stuff::Common::colorStringRed(\"ERROR:\")\n << \" nonparametric evaluate() called for a parametric function!\");\n else {\n leftFactor_->evaluate(x, ret);\n RangeType tmp(0);\n rightFactor_->evaluate(x, tmp);\n ret[0] *= tmp[0];\n }\n } \/\/ ... evaluate(...)\n\n virtual void evaluate(const DomainType& x, const ParamType& mu, RangeType& ret) const\n {\n if (!parametric())\n DUNE_THROW(Dune::InvalidStateException,\n \"\\n\" << Dune::Stuff::Common::colorStringRed(\"ERROR:\")\n << \" parametric evaluate() called for a nonparametric function!\");\n RangeType leftValue(0);\n RangeType rightValue(0);\n if (leftParametric_)\n leftFactor_->evaluate(x, mu, leftValue);\n else\n leftFactor_->evaluate(x, leftValue);\n if (rightParametric_)\n rightFactor_->evaluate(x, mu, rightValue);\n else\n rightFactor_->evaluate(x, rightValue);\n ret[0] = leftValue[0];\n ret[0] *= rightValue[0];\n } \/\/ ... evaluate(...)\n\n virtual size_t paramSize() const\n {\n if (leftParametric_)\n return leftFactor_->paramSize();\n else if (rightParametric_)\n return rightFactor_->paramSize();\n else\n return 0;\n } \/\/ ... paramSize(...)\n\n virtual const std::vector< ParamType >& paramRange() const\n {\n if (!parametric())\n DUNE_THROW(Dune::InvalidStateException,\n \"\\n\" << Dune::Stuff::Common::colorStringRed(\"ERROR:\")\n << \" paramRange() called for a nonparametric function!\");\n if (leftParametric_)\n return leftFactor_->paramRange();\n else\n return rightFactor_->paramRange();\n } \/\/ ... paramRange(...)\n\n virtual const std::vector< std::string >& paramExplanation() const\n {\n if (!parametric())\n DUNE_THROW(Dune::InvalidStateException,\n \"\\n\" << Dune::Stuff::Common::colorStringRed(\"ERROR:\")\n << \" paramExplanation() called for a nonparametric function!\");\n if (leftParametric_)\n return leftFactor_->paramExplanation();\n else\n return rightFactor_->paramExplanation();\n } \/\/ ... paramExplanation(...)\n\n virtual bool separable() const\n {\n if (!parametric())\n DUNE_THROW(Dune::InvalidStateException,\n \"\\n\" << Dune::Stuff::Common::colorStringRed(\"ERROR:\")\n << \" separable() called for a nonparametric function!\");\n return leftSeparable_ || rightSeparable_;\n } \/\/ ... separable(...)\n\n virtual size_t numComponents() const\n {\n if (!separable())\n DUNE_THROW(Dune::InvalidStateException,\n \"\\n\" << Dune::Stuff::Common::colorStringRed(\"ERROR:\")\n << \" numComponents() called for a nonseparable function!\");\n return components_.size();\n } \/\/ ... numComponents(...)\n\n virtual const std::vector< Dune::shared_ptr< const ComponentType > >& components() const\n {\n if (!separable())\n DUNE_THROW(Dune::InvalidStateException,\n \"\\n\" << Dune::Stuff::Common::colorStringRed(\"ERROR:\")\n << \" components() called for a nonseparable function!\");\n return components_;\n } \/\/ ... components(...)\n\n virtual size_t numCoefficients() const\n {\n if (!separable())\n DUNE_THROW(Dune::InvalidStateException,\n \"\\n\" << Dune::Stuff::Common::colorStringRed(\"ERROR:\")\n << \" numCoefficients() called for a nonseparable function!\");\n if (leftSeparable_)\n return leftFactor_->numCoefficients();\n else\n return rightFactor_->numCoefficients();\n } \/\/ ... numCoefficients(...)\n\n virtual const std::vector< Dune::shared_ptr< const CoefficientType > >& coefficients() const\n {\n if (!separable())\n DUNE_THROW(Dune::InvalidStateException,\n \"\\n\" << Dune::Stuff::Common::colorStringRed(\"ERROR:\")\n << \" coefficients() called for a nonseparable function!\");\n if (leftSeparable_)\n return leftFactor_->coefficients();\n else\n return rightFactor_->coefficients();\n } \/\/ ... coefficients(...)\n\nprivate:\n const Dune::shared_ptr< const LeftFactorType > leftFactor_;\n const Dune::shared_ptr< const RightFactorType > rightFactor_;\n const bool leftParametric_;\n const bool rightParametric_;\n const bool leftSeparable_;\n const bool rightSeparable_;\n const std::string name_;\n const int order_;\n std::vector< Dune::shared_ptr< const ComponentType > > components_;\n}; \/\/ class Product< ..., ... >\n\n} \/\/ namespace Function\n} \/\/ namespace Stuff\n} \/\/ namespace Dune\n\n#endif \/\/ DUNE_STUFF_FUNCTION_PRODUCT_HH\n[function.product] update#ifndef DUNE_STUFF_FUNCTION_PRODUCT_HH\n#define DUNE_STUFF_FUNCTION_PRODUCT_HH\n\n#include \n\n#include \n\n#include \n\n#include \"interface.hh\"\n\nnamespace Dune {\nnamespace Stuff {\n\n\n\/\/ forward, to allow for specialization\ntemplate< class LeftFactorDomainFieldImp, int dimDomainLeftFactor, class LeftFactorRangeFieldImp, int dimRangeLeftFactor,\n class RightFactorDomainFieldImp, int dimDomainRightFactor, class RightFactorRangeFieldImp, int dimRangeRightFactor >\nclass FunctionProduct{\npublic:\n FunctionProduct() = delete;\n};\n\n\ntemplate< class DomainFieldImp, int domainDim, class RangeFieldImp >\nclass FunctionProduct< DomainFieldImp, domainDim, RangeFieldImp, 1,\n DomainFieldImp, domainDim, RangeFieldImp, 1 >\n : public FunctionInterface< DomainFieldImp, domainDim, RangeFieldImp, 1 >\n{\npublic:\n typedef FunctionProduct< DomainFieldImp, domainDim, RangeFieldImp, 1,\n DomainFieldImp, domainDim, RangeFieldImp, 1 > ThisType;\n typedef FunctionInterface< DomainFieldImp, domainDim, RangeFieldImp, 1 > BaseType;\n\n typedef FunctionInterface< DomainFieldImp, domainDim, RangeFieldImp, 1 > LeftFactorType;\n typedef FunctionInterface< DomainFieldImp, domainDim, RangeFieldImp, 1 > RightFactorType;\n\n typedef typename BaseType::DomainFieldType DomainFieldType;\n static const int dimDomain = BaseType::dimDomain;\n typedef typename BaseType::DomainType DomainType;\n\n typedef typename BaseType::RangeFieldType RangeFieldType;\n static const int dimRange = BaseType::dimRange;\n typedef typename BaseType::RangeType RangeType;\n\n typedef typename BaseType::ParamFieldType ParamFieldType;\n static const int maxParamDim = BaseType::maxParamDim;\n typedef typename BaseType::ParamType ParamType;\n\n typedef typename BaseType::ComponentType ComponentType;\n typedef typename BaseType::CoefficientType CoefficientType;\n\n static std::string id()\n {\n return BaseType::id() + \".product\";\n }\n\n FunctionProduct(const std::shared_ptr< const LeftFactorType > _leftFactor,\n const std::shared_ptr< const RightFactorType > _rightFactor)\n : leftFactor_(_leftFactor)\n , rightFactor_(_rightFactor)\n , leftParametric_(leftFactor_->parametric())\n , rightParametric_(rightFactor_->parametric())\n , leftSeparable_(leftParametric_ ? leftFactor_->affineparametric() : false)\n , rightSeparable_(rightParametric_ ? rightFactor_->affineparametric() : false)\n , name_(\"product of '\" + leftFactor_->name() + \"' and '\" + rightFactor_->name())\n , order_((leftFactor_->order() >= 0 && rightFactor_->order() >= 0)\n ? (leftFactor_->order() + rightFactor_->order())\n : -1)\n {\n \/\/ sanity checks\n if (leftParametric_ && rightParametric_)\n DUNE_THROW(Dune::InvalidStateException,\n \"\\n\" << Dune::Stuff::Common::colorStringRed(\"ERROR:\")\n << \" only one factor may be parametric!\");\n \/\/ build up components\n if (leftSeparable_) {\n for (size_t qq = 0; qq < leftFactor_->numComponents(); ++qq)\n components_.push_back(std::make_shared< ThisType >(leftFactor_->components()[qq], rightFactor_));\n } else if (rightSeparable_) {\n for (size_t qq = 0; qq < rightFactor_->numComponents(); ++qq)\n components_.push_back(std::make_shared< ThisType >(leftFactor_, rightFactor_->components()[qq]));\n }\n } \/\/ Product\n\n std::shared_ptr< const LeftFactorType > leftFactor() const\n {\n return leftFactor_;\n }\n\n std::shared_ptr< const RightFactorType > rightFactor() const\n {\n return rightFactor_;\n }\n\n virtual bool parametric() const\n {\n return leftParametric_ || rightParametric_;\n }\n\n virtual std::string name() const\n {\n return name_;\n }\n\n virtual int order() const\n {\n return order_;\n }\n\n virtual void evaluate(const DomainType& x, RangeType& ret) const\n {\n if (parametric())\n DUNE_THROW(Dune::InvalidStateException,\n \"\\n\" << Dune::Stuff::Common::colorStringRed(\"ERROR:\")\n << \" nonparametric evaluate() called for a parametric function!\");\n else {\n leftFactor_->evaluate(x, ret);\n RangeType tmp(0);\n rightFactor_->evaluate(x, tmp);\n ret[0] *= tmp[0];\n }\n } \/\/ ... evaluate(...)\n\n virtual void evaluate(const DomainType& x, const ParamType& mu, RangeType& ret) const\n {\n if (!parametric())\n DUNE_THROW(Dune::InvalidStateException,\n \"\\n\" << Dune::Stuff::Common::colorStringRed(\"ERROR:\")\n << \" parametric evaluate() called for a nonparametric function!\");\n RangeType leftValue(0);\n RangeType rightValue(0);\n if (leftParametric_)\n leftFactor_->evaluate(x, mu, leftValue);\n else\n leftFactor_->evaluate(x, leftValue);\n if (rightParametric_)\n rightFactor_->evaluate(x, mu, rightValue);\n else\n rightFactor_->evaluate(x, rightValue);\n ret[0] = leftValue[0];\n ret[0] *= rightValue[0];\n } \/\/ ... evaluate(...)\n\n virtual size_t paramSize() const\n {\n if (leftParametric_)\n return leftFactor_->paramSize();\n else if (rightParametric_)\n return rightFactor_->paramSize();\n else\n return 0;\n } \/\/ ... paramSize(...)\n\n virtual const std::vector< ParamType >& paramRange() const\n {\n if (!parametric())\n DUNE_THROW(Dune::InvalidStateException,\n \"\\n\" << Dune::Stuff::Common::colorStringRed(\"ERROR:\")\n << \" paramRange() called for a nonparametric function!\");\n if (leftParametric_)\n return leftFactor_->paramRange();\n else\n return rightFactor_->paramRange();\n } \/\/ ... paramRange(...)\n\n virtual const std::vector< std::string >& paramExplanation() const\n {\n if (!parametric())\n DUNE_THROW(Dune::InvalidStateException,\n \"\\n\" << Dune::Stuff::Common::colorStringRed(\"ERROR:\")\n << \" paramExplanation() called for a nonparametric function!\");\n if (leftParametric_)\n return leftFactor_->paramExplanation();\n else\n return rightFactor_->paramExplanation();\n } \/\/ ... paramExplanation(...)\n\n virtual bool affineparametric() const\n {\n if (!parametric())\n DUNE_THROW(Dune::InvalidStateException,\n \"\\n\" << Dune::Stuff::Common::colorStringRed(\"ERROR:\")\n << \" affineparametric() called for a nonparametric function!\");\n return leftSeparable_ || rightSeparable_;\n } \/\/ ... affineparametric(...)\n\n virtual size_t numComponents() const\n {\n if (!affineparametric())\n DUNE_THROW(Dune::InvalidStateException,\n \"\\n\" << Dune::Stuff::Common::colorStringRed(\"ERROR:\")\n << \" numComponents() called for a nonaffineparametric function!\");\n return components_.size();\n } \/\/ ... numComponents(...)\n\n virtual const std::vector< std::shared_ptr< const ComponentType > >& components() const\n {\n if (!affineparametric())\n DUNE_THROW(Dune::InvalidStateException,\n \"\\n\" << Dune::Stuff::Common::colorStringRed(\"ERROR:\")\n << \" components() called for a nonaffineparametric function!\");\n return components_;\n } \/\/ ... components(...)\n\n virtual size_t numCoefficients() const\n {\n if (!affineparametric())\n DUNE_THROW(Dune::InvalidStateException,\n \"\\n\" << Dune::Stuff::Common::colorStringRed(\"ERROR:\")\n << \" numCoefficients() called for a nonaffineparametric function!\");\n if (leftSeparable_)\n return leftFactor_->numCoefficients();\n else\n return rightFactor_->numCoefficients();\n } \/\/ ... numCoefficients(...)\n\n virtual const std::vector< std::shared_ptr< const CoefficientType > >& coefficients() const\n {\n if (!affineparametric())\n DUNE_THROW(Dune::InvalidStateException,\n \"\\n\" << Dune::Stuff::Common::colorStringRed(\"ERROR:\")\n << \" coefficients() called for a nonaffineparametric function!\");\n if (leftSeparable_)\n return leftFactor_->coefficients();\n else\n return rightFactor_->coefficients();\n } \/\/ ... coefficients(...)\n\nprivate:\n const std::shared_ptr< const LeftFactorType > leftFactor_;\n const std::shared_ptr< const RightFactorType > rightFactor_;\n const bool leftParametric_;\n const bool rightParametric_;\n const bool leftSeparable_;\n const bool rightSeparable_;\n const std::string name_;\n const int order_;\n std::vector< std::shared_ptr< const ComponentType > > components_;\n}; \/\/ class FunctionProduct< ..., ... >\n\n} \/\/ namespace Stuff\n} \/\/ namespace Dune\n\n#endif \/\/ DUNE_STUFF_FUNCTION_PRODUCT_HH\n<|endoftext|>"} {"text":"\/\/ @(#)root\/auth:$Name: $:$Id: TAFS.cxx,v 1.1 2007\/01\/23 11:31:33 rdm Exp $\n\/\/ Author: G. Ganis, Nov 2006\n\n\/*************************************************************************\n * Copyright (C) 1995-2007, Rene Brun and Fons Rademakers. *\n * All rights reserved. *\n * *\n * For the licensing terms see $ROOTSYS\/LICENSE. *\n * For the list of contributors see $ROOTSYS\/README\/CREDITS. *\n *************************************************************************\/\n\n#ifndef WIN32\n# include \n#else\n# define ssize_t int\n# include \n# include \n#endif\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ \/\/\n\/\/ TAFS \/\/\n\/\/ \/\/\n\/\/ Utility class to acquire and handle an AFS tokens. \/\/\n\/\/ Interface to libTAFS.so. \/\/\n\/\/ \/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \"AFSAuth.h\"\n#include \"TAFS.h\"\n#include \"TError.h\"\n#include \"TPluginManager.h\"\n#include \"TROOT.h\"\n#include \"TString.h\"\n#include \"TSystem.h\"\n#include \"Varargs.h\"\n#include \"Getline.h\"\n\nBool_t TAFS::fgUsePwdDialog = kTRUE;\nTPluginHandler *TAFS::fgPasswdDialog = (TPluginHandler *)(-1);\n\nClassImp(TAFS)\n\n\/\/ Hook to the constructor. This is needed to avoid using the plugin manager\n\/\/ which may create problems in multi-threaded environments.\nextern \"C\" {\n TAFS *GetTAFS(const char *f, const char *u, Int_t lf) {\n TAFS *afs = new TAFS(f, u, lf);\n return (afs->Verify() > 0 ? afs : 0); \n }\n}\n\n\/\/________________________________________________________________________\nTAFS::TAFS(const char *fpw, const char *user, int life)\n{\n \/\/ Constructor: get AFS token for usr using credentials from file 'fpw'.\n \/\/ If 'usr' is undefined the current user is used.\n \/\/ If 'fpw' is undefined the caller is prompt for a password.\n\n \/\/ Used to test validity\n fToken = 0;\n\n \/\/ Determine the user\n TString usr = (user && strlen(user) > 0) ? user : \"\";\n if (usr.IsNull()) {\n UserGroup_t *u = gSystem->GetUserInfo();\n if (u) {\n usr = (const char *) u->fUser;\n delete u;\n } else {\n Info(\"TAFS\",\"user undefined\");\n return;\n }\n }\n\n \/\/ Find credentials\n char *pw = 0;\n Int_t pwlen = 0;\n if (fpw) {\n \/\/ Reading credentials from file\n struct stat st;\n if (!stat(fpw, &st)) {\n pwlen = st.st_size;\n \/\/ Open the file for reading\n Int_t fd = open(fpw, O_RDONLY);\n if (fd > 0) {\n pw = new char[pwlen];\n if (read(fd, pw, pwlen) != pwlen) {\n delete [] pw;\n pw = 0;\n pwlen = 0;\n }\n }\n }\n \/\/ Notify failure\n if (!pw) {\n Info(\"TAFS\",\"could not read credentials from %s\", fpw);\n }\n }\n\n \/\/ Prompt for credentials if not yet found\n if (!pw) {\n\n TString prompt = Form(\"AFS password for %s@%s\", usr.Data(), AFSLocalCell());\n\n \/\/ Init the dialog box, if needed\n if (fgUsePwdDialog) {\n if (fgPasswdDialog == (TPluginHandler *)(-1)) {\n if (!gROOT->IsBatch()) {\n if ((fgPasswdDialog =\n gROOT->GetPluginManager()->FindHandler(\"TGPasswdDialog\")))\n if (fgPasswdDialog->LoadPlugin() == -1) {\n fgPasswdDialog = 0;\n Warning(\"TAFS\",\n \"could not load plugin for the password dialog box\");\n }\n } else\n fgPasswdDialog = 0;\n }\n } else {\n fgPasswdDialog = 0;\n }\n\n \/\/ Get the password now\n char buf[128];\n pw = buf;\n if (fgPasswdDialog) {\n \/\/ Use graphic dialog\n fgPasswdDialog->ExecPlugin(3, prompt.Data(), buf, 128);\n \/\/ Wait until the user is done\n while (gROOT->IsInterrupted())\n gSystem->DispatchOneEvent(kFALSE);\n } else {\n Gl_config(\"noecho\", 1);\n pw = Getline((char *) prompt.Data());\n Gl_config(\"noecho\", 0);\n }\n\n \/\/ Final checks\n if (pw[0]) {\n if (pw[strlen(pw)-1] == '\\n')\n pw[strlen(pw) - 1] = 0; \/\/ get rid of \\n\n }\n }\n\n \/\/ Now get the token\n char *emsg;\n if (!(fToken = GetAFSToken(usr, pw, pwlen, life, &emsg))) {\n Info(\"TAFS\", \"token acquisition failed: %s\", emsg);\n return;\n }\n\n \/\/ Success\n return;\n}\n\n\/\/________________________________________________________________________\nTAFS::~TAFS()\n{\n \/\/ Destructor\n\n if (fToken)\n DeleteAFSToken(fToken);\n}\n\n\/\/________________________________________________________________________\nInt_t TAFS::Verify()\n{\n \/\/ Return seconds to expiration (negative means expired)\n\n return (fToken ? VerifyAFSToken(fToken) : -1);\n}\n\n\/\/________________________________________________________________________\nvoid TAFS::SetUsePwdDialog(Bool_t on)\n{\n \/\/ Switch on\/off usage of password dialog box\n\n fgUsePwdDialog = on;\n}\nFrom Gerri: fix a potential memory leak.\/\/ @(#)root\/auth:$Name: $:$Id: TAFS.cxx,v 1.2 2007\/01\/24 08:09:03 brun Exp $\n\/\/ Author: G. Ganis, Nov 2006\n\n\/*************************************************************************\n * Copyright (C) 1995-2007, Rene Brun and Fons Rademakers. *\n * All rights reserved. *\n * *\n * For the licensing terms see $ROOTSYS\/LICENSE. *\n * For the list of contributors see $ROOTSYS\/README\/CREDITS. *\n *************************************************************************\/\n\n#ifndef WIN32\n# include \n#else\n# define ssize_t int\n# include \n# include \n#endif\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ \/\/\n\/\/ TAFS \/\/\n\/\/ \/\/\n\/\/ Utility class to acquire and handle an AFS tokens. \/\/\n\/\/ Interface to libTAFS.so. \/\/\n\/\/ \/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \"AFSAuth.h\"\n#include \"TAFS.h\"\n#include \"TError.h\"\n#include \"TPluginManager.h\"\n#include \"TROOT.h\"\n#include \"TString.h\"\n#include \"TSystem.h\"\n#include \"Varargs.h\"\n#include \"Getline.h\"\n\nBool_t TAFS::fgUsePwdDialog = kTRUE;\nTPluginHandler *TAFS::fgPasswdDialog = (TPluginHandler *)(-1);\n\nClassImp(TAFS)\n\n\/\/ Hook to the constructor. This is needed to avoid using the plugin manager\n\/\/ which may create problems in multi-threaded environments.\nextern \"C\" {\n TAFS *GetTAFS(const char *f, const char *u, Int_t lf) {\n \/\/ Create and instance and return it only if valid\n TAFS *afs = new TAFS(f, u, lf);\n if (afs->Verify())\n return afs;\n delete afs;\n return 0;\n }\n}\n\n\/\/________________________________________________________________________\nTAFS::TAFS(const char *fpw, const char *user, int life)\n{\n \/\/ Constructor: get AFS token for usr using credentials from file 'fpw'.\n \/\/ If 'usr' is undefined the current user is used.\n \/\/ If 'fpw' is undefined the caller is prompt for a password.\n\n \/\/ Used to test validity\n fToken = 0;\n\n \/\/ Determine the user\n TString usr = (user && strlen(user) > 0) ? user : \"\";\n if (usr.IsNull()) {\n UserGroup_t *u = gSystem->GetUserInfo();\n if (u) {\n usr = (const char *) u->fUser;\n delete u;\n } else {\n Info(\"TAFS\",\"user undefined\");\n return;\n }\n }\n\n \/\/ Find credentials\n char *pw = 0;\n Int_t pwlen = 0;\n if (fpw) {\n \/\/ Reading credentials from file\n struct stat st;\n if (!stat(fpw, &st)) {\n pwlen = st.st_size;\n \/\/ Open the file for reading\n Int_t fd = open(fpw, O_RDONLY);\n if (fd > 0) {\n pw = new char[pwlen];\n if (read(fd, pw, pwlen) != pwlen) {\n delete [] pw;\n pw = 0;\n pwlen = 0;\n }\n }\n }\n \/\/ Notify failure\n if (!pw) {\n Info(\"TAFS\",\"could not read credentials from %s\", fpw);\n }\n }\n\n \/\/ Prompt for credentials if not yet found\n if (!pw) {\n\n TString prompt = Form(\"AFS password for %s@%s\", usr.Data(), AFSLocalCell());\n\n \/\/ Init the dialog box, if needed\n if (fgUsePwdDialog) {\n if (fgPasswdDialog == (TPluginHandler *)(-1)) {\n if (!gROOT->IsBatch()) {\n if ((fgPasswdDialog =\n gROOT->GetPluginManager()->FindHandler(\"TGPasswdDialog\")))\n if (fgPasswdDialog->LoadPlugin() == -1) {\n fgPasswdDialog = 0;\n Warning(\"TAFS\",\n \"could not load plugin for the password dialog box\");\n }\n } else\n fgPasswdDialog = 0;\n }\n } else {\n fgPasswdDialog = 0;\n }\n\n \/\/ Get the password now\n char buf[128];\n pw = buf;\n if (fgPasswdDialog) {\n \/\/ Use graphic dialog\n fgPasswdDialog->ExecPlugin(3, prompt.Data(), buf, 128);\n \/\/ Wait until the user is done\n while (gROOT->IsInterrupted())\n gSystem->DispatchOneEvent(kFALSE);\n } else {\n Gl_config(\"noecho\", 1);\n pw = Getline((char *) prompt.Data());\n Gl_config(\"noecho\", 0);\n }\n\n \/\/ Final checks\n if (pw[0]) {\n if (pw[strlen(pw)-1] == '\\n')\n pw[strlen(pw) - 1] = 0; \/\/ get rid of \\n\n }\n }\n\n \/\/ Now get the token\n char *emsg;\n if (!(fToken = GetAFSToken(usr, pw, pwlen, life, &emsg))) {\n Info(\"TAFS\", \"token acquisition failed: %s\", emsg);\n return;\n }\n\n \/\/ Success\n return;\n}\n\n\/\/________________________________________________________________________\nTAFS::~TAFS()\n{\n \/\/ Destructor\n\n if (fToken)\n DeleteAFSToken(fToken);\n}\n\n\/\/________________________________________________________________________\nInt_t TAFS::Verify()\n{\n \/\/ Return seconds to expiration (negative means expired)\n\n return (fToken ? VerifyAFSToken(fToken) : -1);\n}\n\n\/\/________________________________________________________________________\nvoid TAFS::SetUsePwdDialog(Bool_t on)\n{\n \/\/ Switch on\/off usage of password dialog box\n\n fgUsePwdDialog = on;\n}\n<|endoftext|>"} {"text":"#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"DICOMLoaderVTK.h\"\n\n\nint main( int argc, char** argv )\t\n{\n\t\/\/ TODO: global path??\n\tstd::string inputFilename = \"c:\\\\DatenE\\\\02WiSe1718\\\\03SMMIA\\\\Projekt\\\\data\\\\p01\\\\0_pre\\\\00_data\\\\export0001.dcm\";\n\tstd::string directory = \"c:\\\\DatenE\\\\02WiSe1718\\\\03SMMIA\\\\Projekt\\\\data\\\\p01\\\\0_pre\\\\00_data\";\n\t\n\tDICOMLoaderVTK::loadDICOM(inputFilename);\n\n\tDICOMLoaderVTK::loadDICOMSeries(directory);\n\n return 0;\n}\nuninteressante Änderung die verwurfen werden soll#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"DICOMLoaderVTK.h\"\n\n\nint main( int argc, char** argv )\t\n{\n\t\/\/ TODO: global path??\n\tstd::string inputFilename = \"c:\\\\Users\\\\lifak\\\\Documents\\\\Studium\\\\09_Master_Wi1718\\\\SM-MIA\\\\data\\\\p01\\\\0_pre\\\\00_data\\\\export0001.dcm\";\n\tstd::string directory = \"c:\\\\Users\\\\lifak\\\\Documents\\\\Studium\\\\09_Master_Wi1718\\\\SM-MIA\\\\data\\\\p01\\\\0_pre\\\\00_data\";\n\t\n\tDICOMLoaderVTK::loadDICOM(inputFilename);\n\n\tDICOMLoaderVTK::loadDICOMSeries(directory);\n\n return 0;\n}\n<|endoftext|>"} {"text":"#include \n#include \n#include \n#include \n\nusing namespace std;\n\n\/\/ Good diagram: https:\/\/engmrk.com\/wp-content\/uploads\/2018\/09\/Image-Architecture-of-Convolutional-Neural-Network.png\n\nclass Layer {\n public:\n vector>> h(vector>> x);\n\n \/\/ Helper function\n static void rand_init(vector> matrix, int height, int width) {\n for (int i = 0; i < height; i++) {\n for (int j = 0; j < width; j++) {\n \/\/ use numbers between -100 and 100\n double n = (double)rand() \/ RAND_MAX; \/\/ scales rand() to [0, 1].\n n = n * 200 - 100;\n matrix[i][j] = n; \/\/ (possibly) change to use float to save memory\n }\n }\n }\n};\n\nclass Conv : public Layer {\n public:\n int num_input_channels;\n int num_filters;\n vector size_per_filter;\n vector stride_per_filter;\n\n vector>> filters;\n Conv(int num_input_channels, int num_filters, vector size_per_filter, vector stride_per_filter) {\n \/\/ TODO: Check if there is a better way to save these.\n num_input_channels = num_input_channels;\n num_filters = num_filters;\n size_per_filter = size_per_filter;\n stride_per_filter = stride_per_filter;\n\n for (int filter_num; filter_num < num_filters; filter_num++) {\n \/\/ Filters are square\n int height = size_per_filter[filter_num];\n int width = size_per_filter[filter_num];\n\n vector> filter;\n Layer().rand_init(filter, height, width);\n filters[filter_num] = filter;\n }\n }\n\n vector>> h(vector>> a) {\n \/\/ Input and output is height x width x num_channels\n \/\/ First filter adds to the output of the first channel only, etc.\n\n \/\/ feature map (or activation map) is the output of one filter (or kernel or detector)\n vector>> output_block;\n int num_filters = filters.size();\n for (int i = 0; i < num_filters; i++) { \/\/ Should be embarrassingly parallel\n vector> feature_map = convolve(a, filters[i], stride_per_filter[i]);\n }\n }\n\n \/\/ static because this is a self-contained method\n vector> static convolve(vector>> a, vector> filter, int stride) {\n \/\/ a is height x width x num_channels\n \/\/ Let's say a is 10x10x3 and filter is 3x3\n \/\/ The first convolutional step will use a's top left corner block of size 3x3x3\n \/\/ For each (i, j, [1, 2, 3]) section of a, we use the same (i, j)th weight of filter to flatten it\n \/\/ In other words, we do a[i][j][1]*w + a[i][j][2]*w + a[i][j][3]*w.\n \/\/ This produces a 3x3x1 which we then element-wise multiply with filter which is also 3x3x1 to\n \/\/ produce 3x3x1 multiplications. These are then all added together to produce one output per\n \/\/ convolutional step.\n \/\/ Reference:\n \/\/ https:\/\/stats.stackexchange.com\/questions\/335321\/in-a-convolutional-neural-network-cnn-when-convolving-the-image-is-the-opera\n\n int height = a.size();\n int width = a[0].size();\n int depth = a[0][0].size();\n\n vector> feature_map;\n int depth_of_a = a.size();\n for (int depth = 0; depth < depth_of_a; depth++) {\n vector> feature_map_per_depth = _convole(a[depth], filter, stride);\n }\n\n \/\/TODO\n }\n\n vector> static _convole(vector> a, vector> filter, int stride) {\n \/\/TODO\n }\n};\n\nclass Pool : public Layer {};\n\nclass Act : public Layer {};\n\nclass Dense : public Layer {};\n\nclass ConvNet {\n public:\n vector layers;\n ConvNet(vector layers) { layers = layers; }\n\n int h(vector>> x) { \/\/ Returns an int, a classification\n vector>> a = x;\n for (Layer layer : layers) {\n vector>> a = layer.h(a);\n }\n \/\/ Convert the final output into a classification\n }\n};\n\nint main() {\n \/\/ TEST\n cout << \"Starting test...\\n\";\n\n int num_images = 100;\n vector>>> X; \/\/ num_images x height x width x num_channels\n int Y[num_images]; \/\/ labels for each example\n\n \/\/ Randomly initialize X and Y\n for (int i = 0; i < num_images; i++) {\n for (int j = 0; j < 28; j++) {\n for (int k = 0; k < 28; k++) {\n \/\/ use numbers from 0 to 255\n X[i][j][k][1] = rand() % 255;\n }\n }\n Y[i] = rand() % 10; \/\/ TODO: Maybe decrease number of classes for the test?\n }\n\n \/\/ Look at first 2 \"images\"\n for (int i = 0; i < 2; i++) {\n for (int j = 0; j < 28; j++) {\n for (int k = 0; k < 28; k++) {\n cout << X[j][k][i][1] << \",\";\n }\n cout << endl;\n }\n cout << endl;\n }\n\n \/\/ Intialize model\n \/\/ Compound literal, (vector[]), helps initialize an array in function call\n ConvNet model = ConvNet(vector{Conv(1, 4, (vector){3, 3, 5, 5}, (vector){1, 1, 2, 2})});\n\n \/\/ Do a forward pass with the first \"image\"\n model.h(X[1]);\n\n cout << \"Test finished!\\n\";\n\n \/\/ Main\n\n return 0;\n}\nAdded test function signature#include \n#include \n#include \n#include \n\nusing namespace std;\n\n\/\/ Good diagram: https:\/\/engmrk.com\/wp-content\/uploads\/2018\/09\/Image-Architecture-of-Convolutional-Neural-Network.png\n\nclass Layer {\n public:\n vector>> h(vector>> x);\n\n \/\/ Helper function\n static void rand_init(vector> matrix, int height, int width) {\n for (int i = 0; i < height; i++) {\n for (int j = 0; j < width; j++) {\n \/\/ use numbers between -100 and 100\n double n = (double)rand() \/ RAND_MAX; \/\/ scales rand() to [0, 1].\n n = n * 200 - 100;\n matrix[i][j] = n; \/\/ (possibly) change to use float to save memory\n }\n }\n }\n};\n\nclass Conv : public Layer {\n public:\n int num_input_channels;\n int num_filters;\n vector size_per_filter;\n vector stride_per_filter;\n\n vector>> filters;\n Conv(int num_input_channels, int num_filters, vector size_per_filter, vector stride_per_filter) {\n \/\/ TODO: Check if there is a better way to save these.\n num_input_channels = num_input_channels;\n num_filters = num_filters;\n size_per_filter = size_per_filter;\n stride_per_filter = stride_per_filter;\n\n for (int filter_num; filter_num < num_filters; filter_num++) {\n \/\/ Filters are square\n int height = size_per_filter[filter_num];\n int width = size_per_filter[filter_num];\n\n vector> filter;\n Layer().rand_init(filter, height, width);\n filters[filter_num] = filter;\n }\n }\n\n vector>> h(vector>> a) {\n \/\/ Input and output is height x width x num_channels\n \/\/ First filter adds to the output of the first channel only, etc.\n\n \/\/ feature map (or activation map) is the output of one filter (or kernel or detector)\n vector>> output_block;\n int num_filters = filters.size();\n for (int i = 0; i < num_filters; i++) { \/\/ Should be embarrassingly parallel\n vector> feature_map = convolve(a, filters[i], stride_per_filter[i]);\n }\n }\n\n \/\/ static because this is a self-contained method\n vector> static convolve(vector>> a, vector> filter, int stride) {\n \/\/ a is height x width x num_channels\n \/\/ Let's say a is 10x10x3 and filter is 3x3\n \/\/ The first convolutional step will use a's top left corner block of size 3x3x3\n \/\/ For each (i, j, [1, 2, 3]) section of a, we use the same (i, j)th weight of filter to flatten it\n \/\/ In other words, we do a[i][j][1]*w + a[i][j][2]*w + a[i][j][3]*w.\n \/\/ This produces a 3x3x1 which we then element-wise multiply with filter which is also 3x3x1 to\n \/\/ produce 3x3x1 multiplications. These are then all added together to produce one output per\n \/\/ convolutional step.\n \/\/ Reference:\n \/\/ https:\/\/stats.stackexchange.com\/questions\/335321\/in-a-convolutional-neural-network-cnn-when-convolving-the-image-is-the-opera\n\n int height = a.size();\n int width = a[0].size();\n int depth = a[0][0].size();\n\n vector> feature_map;\n int depth_of_a = a.size();\n for (int depth = 0; depth < depth_of_a; depth++) {\n vector> feature_map_per_depth = _convole(a[depth], filter, stride);\n }\n\n \/\/ TODO\n }\n\n vector> static _convole(vector> a, vector> filter, int stride) {\n \/\/ TODO\n }\n\n vector> static _convole_test() {\n \n }\n};\n\nclass Pool : public Layer {};\n\nclass Act : public Layer {};\n\nclass Dense : public Layer {};\n\nclass ConvNet {\n public:\n vector layers;\n ConvNet(vector layers) { layers = layers; }\n\n int h(vector>> x) { \/\/ Returns an int, a classification\n vector>> a = x;\n for (Layer layer : layers) {\n vector>> a = layer.h(a);\n }\n \/\/ Convert the final output into a classification\n }\n};\n\nint main() {\n \/\/ TEST\n cout << \"Starting test...\\n\";\n\n int num_images = 100;\n vector>>> X; \/\/ num_images x height x width x num_channels\n int Y[num_images]; \/\/ labels for each example\n\n \/\/ Randomly initialize X and Y\n for (int i = 0; i < num_images; i++) {\n for (int j = 0; j < 28; j++) {\n for (int k = 0; k < 28; k++) {\n \/\/ use numbers from 0 to 255\n X[i][j][k][1] = rand() % 255;\n }\n }\n Y[i] = rand() % 10; \/\/ TODO: Maybe decrease number of classes for the test?\n }\n\n \/\/ Look at first 2 \"images\"\n for (int i = 0; i < 2; i++) {\n for (int j = 0; j < 28; j++) {\n for (int k = 0; k < 28; k++) {\n cout << X[j][k][i][1] << \",\";\n }\n cout << endl;\n }\n cout << endl;\n }\n\n \/\/ Intialize model\n \/\/ Compound literal, (vector[]), helps initialize an array in function call\n ConvNet model = ConvNet(vector{Conv(1, 4, (vector){3, 3, 5, 5}, (vector){1, 1, 2, 2})});\n\n \/\/ Do a forward pass with the first \"image\"\n model.h(X[1]);\n\n cout << \"Test finished!\\n\";\n\n \/\/ Main\n\n return 0;\n}\n<|endoftext|>"} {"text":"#include \n#include \n#include \n#include \n#include \"Cube.hpp\"\n\nint8_t *cpdb;\nint8_t *e1pdb;\nint8_t *e2pdb;\n\n\/*\n Cantidad de movimientos por defecto a realizar para desordenar el cubo.\n Si se pasa por parametros a main un numero entre 0 y 18 al procedimiento se\n utilizara ese valor, de lo contrario se utilizara este.\n\n El valor por defecto corresponde al ultimo valor en el que IDA* corre en\n menos de un minuto sin utilizar heuristica.\n *\/\nint PROBLEM_LEVELS = 6;\n\n\/*\n Definicion para el valor de retorno de la funcion recursiva utilizado en IDA*:\n Un par que contiene una cola de enteros para el plan de ejecucion, donde cada\n entero representa un movimiento, y un entero para representar el valor t del\n nivel que esta cubriendo el algoritmo en un momento dado.\n *\/\ntypedef std::pair *,int> Par;\n\n\/*\n Funcion que carga la PDB en memoria y la almacena en una variable global,\n para luego ser utilizada en la funcion h_value.\n No implementada.\n *\/\nvoid load_pdb(std::string folder, int edges_type){\n int CORNERS_MAX = 264539520;\n int EDGES_MAX = 42577920; \/\/ 510935040 (edges of 7)\n FILE *file;\n\n \/\/ the default behaviour is edges_type == 1 (42577920)\n if (edges_type == 2) {\n EDGES_MAX = 510935040;\n }\n\n cpdb = new int8_t[CORNERS_MAX];\n e1pdb = new int8_t[EDGES_MAX];\n e2pdb = new int8_t[EDGES_MAX];\n\n file = fopen(std::string(folder + \"cPDB.bin\").c_str(), \"rb\");\n if (file == NULL) {\n error(\"readPDBs | file 'cPDB.bin' did not open correctly\", __LINE__, __FILE__);\n throw -1;\n }\n fread(cpdb, sizeof(int8_t), CORNERS_MAX, file);\n fclose(file);\n\n file = fopen(std::string(folder + \"e1PDB.bin\").c_str(), \"rb\");\n if (file == NULL) {\n error(\"readPDBs | file 'e1PDB.bin' did not open correctly\", __LINE__, __FILE__);\n throw -1;\n }\n fread(e1pdb, sizeof(int8_t), EDGES_MAX, file);\n fclose(file);\n\n file = fopen(std::string(folder + \"e2PDB.bin\").c_str(), \"rb\");\n if (file == NULL) {\n error(\"readPDBs | file 'e2PDB.bin' did not open correctly\", __LINE__, __FILE__);\n throw -1;\n }\n fread(e2pdb, sizeof(int8_t), EDGES_MAX, file);\n fclose(file);\n}\n\n\nint h_value(Cube * c) {\n int *corners;\n int *edges;\n int values[3]; \/\/ 0 corens | 1 edges1 | 2 edges2\n\n corners = c->get_corners;\n edges = c->get_edges;\n\n int c_val = rank(8, corners, 0, 8, 3);\n int e1_val = rank(12, edges, 0, 6, 2);;\n int e2_val = rank(12, edges, 6, 6, 2);;\n\n values[0] = cpdb[c_val];\n values[1] = e1pdb[e1_val];\n values[2] = e2pdb[e2_val];\n\n \/\/ std::max returns an iterator, thus the *.\n return *std::max_element(values, values+3);\n}\n\n\n\/*\n Funcion que retorna un Cube desordenado mediante movimientos random\n sobre un cubo en su estado goal.\n*\/\nCube* make_root_node(int levels) {\n Cube *c = new Cube;\n int i;\n std::queue *succ;\n for (i = 0; i < levels; i++) {\n succ = c->succ();\n int j;\n srand(time(NULL));\n int random_succesor = rand() % (succ->size() - 1);\n for (j = 0; j < random_succesor; j++) {\n \/*\n Se eliminan sucesores de la cola y se realiza\n el movimiento correspondiente al sucesor que quede al principio\n de la cola.\n *\/\n delete(succ->front());\n succ->pop();\n }\n delete(c);\n c = succ->front();\n succ->pop();\n\n \/\/ Loop para liberar memoria de los que queda en succ\n int tmp = succ->size();\n for (j = 0; j < tmp ; j++) {\n delete(succ->front());\n succ->pop();\n }\n delete(succ);\n }\n std::cout << \"Se utilizara como comienzo el cubo: \" << c->to_string() << std::endl;\n c->reset_last();\n return c;\n}\n\nbool is_goal(Cube *c) {\n \/*\n Funcion que dado un Cube determina si este esta en su estado goal.\n *\/\n\n \/\/ Esta implementacion podria ser mas eficiente\n if (c == NULL)\n return false;\n Cube *goal = new Cube;\n if (goal->equals(c)) {\n delete(goal);\n return true;\n }\n delete(goal);\n return false;\n}\n\nstd::queue* extract_solution(Cube *n) {\n \/*\n Funcion que retorna el plan de ejecucion una vez hallado el goal.\n No implementada.\n *\/\n std::cout << \"Encontre el goal.\" << std::endl;\n std::queue *plan = new std::queue;\n int i;\n for (i = 0; i < 10 ; i++)\n plan->push(i);\n return plan;\n}\n\n \/*\n Funcion que chequea si las condiciones de parada de la funcion bounded_dfs\n se cumplen. Las condiciones son que el nivel actual del IDA* dado por t fue\n sobrepasado o que el goal ha sido encontrado.\n *\/\n\nPar* chequear_cond_parada(Cube* n, int g, int t) {\n Par* par_retorno = new Par;\n\n if ((g + h_value(n)) > t) {\n par_retorno->first = NULL;\n par_retorno->second = g + h_value(n);\n return par_retorno;\n }\n\n std::queue *plan;\n if (is_goal(n)) {\n plan = extract_solution(n);\n std::cout << \"Goal encontrado cuando t valia: \" << t << std::endl;\n par_retorno->first = plan;\n par_retorno->second = g;\n return par_retorno;\n }\n\n delete(par_retorno);\n\n return NULL;\n}\n\nPar* bounded_dfs(Cube*, int, int);\n\n\nPar* avanzar_dfs(Cube* n, int g, int t) {\n \/*\n Funcion que realiza la expansion del bounded en los sucesores del nodo n\n *\/\n Par* par_retorno = NULL;\n\n std::queue *plan;\n int new_t = std::numeric_limits::max(); \/\/ Infinito\n\n std::queue *succ = n->succ(); \/\/ Lista de sucesores a expandir\n int tmp;\n int succ_size = succ->size();\n\n for (tmp = 0; tmp < succ_size; tmp++) {\n delete(par_retorno);\n par_retorno = bounded_dfs(succ->front(), g + 1 , t);\n delete(succ->front());\n succ->pop();\n\n if (par_retorno->first != NULL) {\n \/\/Free memory and return\n int unused_size = succ->size();\n int j;\n\n for (j = 0; j < unused_size; j++) {\n delete(succ->front());\n succ->pop();\n }\n\n delete(succ);\n\n return par_retorno;\n }\n new_t = std::min(new_t, par_retorno->second);\n }\n par_retorno->first = NULL;\n par_retorno->second = new_t;\n delete(succ);\n return par_retorno;\n\n}\n\n\n \/*\n Funcion recursiva que realiza la busqueda del goal para el nivel dado por\n a partir del nodo con costo .\n *\/\n\nPar* bounded_dfs(Cube* n, int g, int t) {\n Par* par_retorno = chequear_cond_parada(n,g,t);\n\n if (par_retorno != NULL) {\n \/\/Hubo exito en las condiciones de parada\n return par_retorno;\n }\n\n delete(par_retorno);\n\n return avanzar_dfs(n,g,t);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n \/*\n Funcion principal del algoritmo IDA*.\n *\/\n\nstd::queue* IDA() {\n Cube* n = make_root_node(PROBLEM_LEVELS);\n int t = h_value(n);\n int max_int = std::numeric_limits::max(); \/\/ Infinite.\n Par* pair;\n\n std::queue* plan;\n\n while (t != max_int) {\n pair = bounded_dfs(n, 0, t);\n plan = pair->first;\n t = pair->second;\n\n if (pair->first != NULL) {\n \/\/ Se consugio una solucion\n delete(n);\n delete(pair);\n\n return plan;\n }\n\n delete(pair);\n }\n\n delete(n);\n delete(pair);\n return NULL;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid validar_entrada(int argc, char const *argv[]) {\n \/*\n Validar parametro de entrada para cantidad de movimientos para desordenar.\n *\/\n if (argc > 1) {\n int argv_int = atoi(argv[1]);\n if (0 <= argv_int && argv_int < 18)\n PROBLEM_LEVELS = argv_int;\n else{\n std::cout << \"Advertencia: \"<< argv_int;\n std::cout << \": valor invalido para cantidad de movimientos para desordenar. \";\n std::cout << \"Utilizando valor por defecto.\" << std::endl;\n }\n }\n}\n\nint main(int argc, char const *argv[]) {\n validar_entrada(argc, argv);\n load_pdb(\"..\/pdbs\/\", 1);\n\n std::queue *plan = IDA();\n\n if (plan != NULL) {\n \/\/Se consigio una solucion\n std::cout << \"Plan encontrado: \" << std::endl;\n int i;\n int plan_size = plan->size();\n for (i = 0; i < plan_size; i++) {\n \/\/Mostrar plan encontrado.\n std::cout << plan->front() << \" \";\n plan->pop();\n }\n std::cout << std::endl;\n }\n else {\n \/\/No se consigio solucion\n std::cout << \"Plan no encontrado\" << std::endl;\n }\n delete(plan);\n return 0;\n}\nError en h_value (get_corners)#include \n#include \n#include \n#include \n#include \"Cube.hpp\"\n\nint8_t *cpdb;\nint8_t *e1pdb;\nint8_t *e2pdb;\n\n\/*\n Cantidad de movimientos por defecto a realizar para desordenar el cubo.\n Si se pasa por parametros a main un numero entre 0 y 18 al procedimiento se\n utilizara ese valor, de lo contrario se utilizara este.\n\n El valor por defecto corresponde al ultimo valor en el que IDA* corre en\n menos de un minuto sin utilizar heuristica.\n *\/\nint PROBLEM_LEVELS = 6;\n\n\/*\n Definicion para el valor de retorno de la funcion recursiva utilizado en IDA*:\n Un par que contiene una cola de enteros para el plan de ejecucion, donde cada\n entero representa un movimiento, y un entero para representar el valor t del\n nivel que esta cubriendo el algoritmo en un momento dado.\n *\/\ntypedef std::pair *,int> Par;\n\n\/*\n Funcion que carga la PDB en memoria y la almacena en una variable global,\n para luego ser utilizada en la funcion h_value.\n No implementada.\n *\/\nvoid load_pdb(std::string folder, int edges_type){\n int CORNERS_MAX = 264539520;\n int EDGES_MAX = 42577920; \/\/ 510935040 (edges of 7)\n FILE *file;\n\n \/\/ the default behaviour is edges_type == 1 (42577920)\n if (edges_type == 2) {\n EDGES_MAX = 510935040;\n }\n\n cpdb = new int8_t[CORNERS_MAX];\n e1pdb = new int8_t[EDGES_MAX];\n e2pdb = new int8_t[EDGES_MAX];\n\n file = fopen(std::string(folder + \"cPDB.bin\").c_str(), \"rb\");\n if (file == NULL) {\n error(\"readPDBs | file 'cPDB.bin' did not open correctly\", __LINE__, __FILE__);\n throw -1;\n }\n fread(cpdb, sizeof(int8_t), CORNERS_MAX, file);\n fclose(file);\n\n file = fopen(std::string(folder + \"e1PDB.bin\").c_str(), \"rb\");\n if (file == NULL) {\n error(\"readPDBs | file 'e1PDB.bin' did not open correctly\", __LINE__, __FILE__);\n throw -1;\n }\n fread(e1pdb, sizeof(int8_t), EDGES_MAX, file);\n fclose(file);\n\n file = fopen(std::string(folder + \"e2PDB.bin\").c_str(), \"rb\");\n if (file == NULL) {\n error(\"readPDBs | file 'e2PDB.bin' did not open correctly\", __LINE__, __FILE__);\n throw -1;\n }\n fread(e2pdb, sizeof(int8_t), EDGES_MAX, file);\n fclose(file);\n}\n\n\nint h_value(Cube * c) {\n int *corners;\n int *edges;\n int values[3]; \/\/ 0 corens | 1 edges1 | 2 edges2\n\n corners = c->get_corners();\n edges = c->get_edges();\n\n int c_val = rank(8, corners, 0, 8, 3);\n int e1_val = rank(12, edges, 0, 6, 2);;\n int e2_val = rank(12, edges, 6, 6, 2);;\n\n values[0] = cpdb[c_val];\n values[1] = e1pdb[e1_val];\n values[2] = e2pdb[e2_val];\n\n \/\/ std::max returns an iterator, thus the *.\n return *std::max_element(values, values+3);\n}\n\n\n\/*\n Funcion que retorna un Cube desordenado mediante movimientos random\n sobre un cubo en su estado goal.\n*\/\nCube* make_root_node(int levels) {\n Cube *c = new Cube;\n int i;\n std::queue *succ;\n for (i = 0; i < levels; i++) {\n succ = c->succ();\n int j;\n srand(time(NULL));\n int random_succesor = rand() % (succ->size() - 1);\n for (j = 0; j < random_succesor; j++) {\n \/*\n Se eliminan sucesores de la cola y se realiza\n el movimiento correspondiente al sucesor que quede al principio\n de la cola.\n *\/\n delete(succ->front());\n succ->pop();\n }\n delete(c);\n c = succ->front();\n succ->pop();\n\n \/\/ Loop para liberar memoria de los que queda en succ\n int tmp = succ->size();\n for (j = 0; j < tmp ; j++) {\n delete(succ->front());\n succ->pop();\n }\n delete(succ);\n }\n std::cout << \"Se utilizara como comienzo el cubo: \" << c->to_string() << std::endl;\n c->reset_last();\n return c;\n}\n\nbool is_goal(Cube *c) {\n \/*\n Funcion que dado un Cube determina si este esta en su estado goal.\n *\/\n\n \/\/ Esta implementacion podria ser mas eficiente\n if (c == NULL)\n return false;\n Cube *goal = new Cube;\n if (goal->equals(c)) {\n delete(goal);\n return true;\n }\n delete(goal);\n return false;\n}\n\nstd::queue* extract_solution(Cube *n) {\n \/*\n Funcion que retorna el plan de ejecucion una vez hallado el goal.\n No implementada.\n *\/\n std::cout << \"Encontre el goal.\" << std::endl;\n std::queue *plan = new std::queue;\n int i;\n for (i = 0; i < 10 ; i++)\n plan->push(i);\n return plan;\n}\n\n \/*\n Funcion que chequea si las condiciones de parada de la funcion bounded_dfs\n se cumplen. Las condiciones son que el nivel actual del IDA* dado por t fue\n sobrepasado o que el goal ha sido encontrado.\n *\/\n\nPar* chequear_cond_parada(Cube* n, int g, int t) {\n Par* par_retorno = new Par;\n\n if ((g + h_value(n)) > t) {\n par_retorno->first = NULL;\n par_retorno->second = g + h_value(n);\n return par_retorno;\n }\n\n std::queue *plan;\n if (is_goal(n)) {\n plan = extract_solution(n);\n std::cout << \"Goal encontrado cuando t valia: \" << t << std::endl;\n par_retorno->first = plan;\n par_retorno->second = g;\n return par_retorno;\n }\n\n delete(par_retorno);\n\n return NULL;\n}\n\nPar* bounded_dfs(Cube*, int, int);\n\n\nPar* avanzar_dfs(Cube* n, int g, int t) {\n \/*\n Funcion que realiza la expansion del bounded en los sucesores del nodo n\n *\/\n Par* par_retorno = NULL;\n\n std::queue *plan;\n int new_t = std::numeric_limits::max(); \/\/ Infinito\n\n std::queue *succ = n->succ(); \/\/ Lista de sucesores a expandir\n int tmp;\n int succ_size = succ->size();\n\n for (tmp = 0; tmp < succ_size; tmp++) {\n delete(par_retorno);\n par_retorno = bounded_dfs(succ->front(), g + 1 , t);\n delete(succ->front());\n succ->pop();\n\n if (par_retorno->first != NULL) {\n \/\/Free memory and return\n int unused_size = succ->size();\n int j;\n\n for (j = 0; j < unused_size; j++) {\n delete(succ->front());\n succ->pop();\n }\n\n delete(succ);\n\n return par_retorno;\n }\n new_t = std::min(new_t, par_retorno->second);\n }\n par_retorno->first = NULL;\n par_retorno->second = new_t;\n delete(succ);\n return par_retorno;\n\n}\n\n\n \/*\n Funcion recursiva que realiza la busqueda del goal para el nivel dado por\n a partir del nodo con costo .\n *\/\n\nPar* bounded_dfs(Cube* n, int g, int t) {\n Par* par_retorno = chequear_cond_parada(n,g,t);\n\n if (par_retorno != NULL) {\n \/\/Hubo exito en las condiciones de parada\n return par_retorno;\n }\n\n delete(par_retorno);\n\n return avanzar_dfs(n,g,t);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n \/*\n Funcion principal del algoritmo IDA*.\n *\/\n\nstd::queue* IDA() {\n Cube* n = make_root_node(PROBLEM_LEVELS);\n int t = h_value(n);\n int max_int = std::numeric_limits::max(); \/\/ Infinite.\n Par* pair;\n\n std::queue* plan;\n\n while (t != max_int) {\n pair = bounded_dfs(n, 0, t);\n plan = pair->first;\n t = pair->second;\n\n if (pair->first != NULL) {\n \/\/ Se consugio una solucion\n delete(n);\n delete(pair);\n\n return plan;\n }\n\n delete(pair);\n }\n\n delete(n);\n delete(pair);\n return NULL;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid validar_entrada(int argc, char const *argv[]) {\n \/*\n Validar parametro de entrada para cantidad de movimientos para desordenar.\n *\/\n if (argc > 1) {\n int argv_int = atoi(argv[1]);\n if (0 <= argv_int && argv_int < 18)\n PROBLEM_LEVELS = argv_int;\n else{\n std::cout << \"Advertencia: \"<< argv_int;\n std::cout << \": valor invalido para cantidad de movimientos para desordenar. \";\n std::cout << \"Utilizando valor por defecto.\" << std::endl;\n }\n }\n}\n\nint main(int argc, char const *argv[]) {\n validar_entrada(argc, argv);\n load_pdb(\"..\/pdbs\/\", 1);\n\n std::queue *plan = IDA();\n\n if (plan != NULL) {\n \/\/Se consigio una solucion\n std::cout << \"Plan encontrado: \" << std::endl;\n int i;\n int plan_size = plan->size();\n for (i = 0; i < plan_size; i++) {\n \/\/Mostrar plan encontrado.\n std::cout << plan->front() << \" \";\n plan->pop();\n }\n std::cout << std::endl;\n }\n else {\n \/\/No se consigio solucion\n std::cout << \"Plan no encontrado\" << std::endl;\n }\n delete(plan);\n return 0;\n}\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2006-2009 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"config.h\"\n\n#include \"base\/compiler_specific.h\"\n\nMSVC_PUSH_WARNING_LEVEL(0);\n#include \"ContextMenu.h\"\n#include \"Document.h\"\n#include \"DocumentLoader.h\"\n#include \"Editor.h\"\n#include \"EventHandler.h\"\n#include \"FrameLoader.h\"\n#include \"FrameView.h\"\n#include \"HitTestResult.h\"\n#include \"HTMLMediaElement.h\"\n#include \"HTMLNames.h\"\n#include \"KURL.h\"\n#include \"Widget.h\"\nMSVC_POP_WARNING();\n#undef LOG\n\n#include \"webkit\/glue\/context_menu_client_impl.h\"\n\n#include \"base\/string_util.h\"\n#include \"webkit\/api\/public\/WebURL.h\"\n#include \"webkit\/api\/public\/WebURLResponse.h\"\n#include \"webkit\/glue\/context_menu.h\"\n#include \"webkit\/glue\/glue_util.h\"\n#include \"webkit\/glue\/webdatasource_impl.h\"\n#include \"webkit\/glue\/webview_impl.h\"\n\n#include \"base\/word_iterator.h\"\n\nusing WebKit::WebDataSource;\n\nnamespace {\n\n\/\/ Helper function to determine whether text is a single word or a sentence.\nbool IsASingleWord(const std::wstring& text) {\n WordIterator iter(text, WordIterator::BREAK_WORD);\n int word_count = 0;\n if (!iter.Init()) return false;\n while (iter.Advance()) {\n if (iter.IsWord()) {\n word_count++;\n if (word_count > 1) \/\/ More than one word.\n return false;\n }\n }\n\n \/\/ Check for 0 words.\n if (!word_count)\n return false;\n\n \/\/ Has a single word.\n return true;\n}\n\n\/\/ Helper function to get misspelled word on which context menu\n\/\/ is to be evolked. This function also sets the word on which context menu\n\/\/ has been evoked to be the selected word, as required. This function changes\n\/\/ the selection only when there were no selected characters.\nstd::wstring GetMisspelledWord(const WebCore::ContextMenu* default_menu,\n WebCore::Frame* selected_frame) {\n std::wstring misspelled_word_string;\n\n \/\/ First select from selectedText to check for multiple word selection.\n misspelled_word_string = CollapseWhitespace(\n webkit_glue::StringToStdWString(selected_frame->selectedText()),\n false);\n\n \/\/ If some texts were already selected, we don't change the selection.\n if (!misspelled_word_string.empty()) {\n \/\/ Don't provide suggestions for multiple words.\n if (!IsASingleWord(misspelled_word_string))\n return L\"\";\n else\n return misspelled_word_string;\n }\n\n WebCore::HitTestResult hit_test_result = selected_frame->eventHandler()->\n hitTestResultAtPoint(default_menu->hitTestResult().point(), true);\n WebCore::Node* inner_node = hit_test_result.innerNode();\n WebCore::VisiblePosition pos(inner_node->renderer()->positionForPoint(\n hit_test_result.localPoint()));\n\n WebCore::VisibleSelection selection;\n if (pos.isNotNull()) {\n selection = WebCore::VisibleSelection(pos);\n selection.expandUsingGranularity(WebCore::WordGranularity);\n }\n\n if (selection.isRange()) {\n selected_frame->setSelectionGranularity(WebCore::WordGranularity);\n }\n\n if (selected_frame->shouldChangeSelection(selection))\n selected_frame->selection()->setSelection(selection);\n\n misspelled_word_string = CollapseWhitespace(\n webkit_glue::StringToStdWString(selected_frame->selectedText()),\n false);\n\n \/\/ If misspelled word is empty, then that portion should not be selected.\n \/\/ Set the selection to that position only, and do not expand.\n if (misspelled_word_string.empty()) {\n selection = WebCore::VisibleSelection(pos);\n selected_frame->selection()->setSelection(selection);\n }\n\n return misspelled_word_string;\n}\n\n} \/\/ namespace\n\nContextMenuClientImpl::~ContextMenuClientImpl() {\n}\n\nvoid ContextMenuClientImpl::contextMenuDestroyed() {\n delete this;\n}\n\n\/\/ Figure out the URL of a page or subframe. Returns |page_type| as the type,\n\/\/ which indicates page or subframe, or ContextNodeType::NONE if the URL could not\n\/\/ be determined for some reason.\nstatic ContextNodeType GetTypeAndURLFromFrame(\n WebCore::Frame* frame,\n GURL* url,\n ContextNodeType page_node_type) {\n ContextNodeType node_type;\n if (frame) {\n WebCore::DocumentLoader* dl = frame->loader()->documentLoader();\n if (dl) {\n WebDataSource* ds = WebDataSourceImpl::FromLoader(dl);\n if (ds) {\n node_type = page_node_type;\n *url = ds->hasUnreachableURL() ? ds->unreachableURL()\n : ds->request().url();\n }\n }\n }\n return node_type;\n}\n\nWebCore::PlatformMenuDescription\n ContextMenuClientImpl::getCustomMenuFromDefaultItems(\n WebCore::ContextMenu* default_menu) {\n \/\/ Displaying the context menu in this function is a big hack as we don't\n \/\/ have context, i.e. whether this is being invoked via a script or in\n \/\/ response to user input (Mouse event WM_RBUTTONDOWN,\n \/\/ Keyboard events KeyVK_APPS, Shift+F10). Check if this is being invoked\n \/\/ in response to the above input events before popping up the context menu.\n if (!webview_->context_menu_allowed())\n return NULL;\n\n WebCore::HitTestResult r = default_menu->hitTestResult();\n WebCore::Frame* selected_frame = r.innerNonSharedNode()->document()->frame();\n\n WebCore::IntPoint menu_point =\n selected_frame->view()->contentsToWindow(r.point());\n\n ContextNodeType node_type;\n\n \/\/ Links, Images, Media tags, and Image\/Media-Links take preference over\n \/\/ all else.\n WebCore::KURL link_url = r.absoluteLinkURL();\n if (!link_url.isEmpty()) {\n node_type.type |= ContextNodeType::LINK;\n }\n\n WebCore::KURL src_url;\n\n ContextMenuMediaParams media_params;\n\n if (!r.absoluteImageURL().isEmpty()) {\n src_url = r.absoluteImageURL();\n node_type.type |= ContextNodeType::IMAGE;\n } else if (!r.absoluteMediaURL().isEmpty()) {\n src_url = r.absoluteMediaURL();\n\n \/\/ We know that if absoluteMediaURL() is not empty, then this is a media\n \/\/ element.\n WebCore::HTMLMediaElement* media_element =\n static_cast(r.innerNonSharedNode());\n if (media_element->hasTagName(WebCore::HTMLNames::videoTag)) {\n node_type.type |= ContextNodeType::VIDEO;\n } else if (media_element->hasTagName(WebCore::HTMLNames::audioTag)) {\n node_type.type |= ContextNodeType::AUDIO;\n }\n\n if (media_element->paused()) {\n media_params.player_state |= ContextMenuMediaParams::PAUSED;\n }\n if (media_element->muted()) {\n media_params.player_state |= ContextMenuMediaParams::MUTED;\n }\n if (media_element->loop()) {\n media_params.player_state |= ContextMenuMediaParams::LOOP;\n }\n if (media_element->supportsSave()) {\n media_params.player_state |= ContextMenuMediaParams::CAN_SAVE;\n }\n \/\/ TODO(ajwong): Report error states in the media player.\n }\n\n \/\/ If it's not a link, an image, a media element, or an image\/media link,\n \/\/ show a selection menu or a more generic page menu.\n std::wstring selection_text_string;\n std::wstring misspelled_word_string;\n GURL frame_url;\n GURL page_url;\n std::string security_info;\n\n std::string frame_charset = WideToASCII(\n webkit_glue::StringToStdWString(selected_frame->loader()->encoding()));\n \/\/ Send the frame and page URLs in any case.\n ContextNodeType frame_node = ContextNodeType(ContextNodeType::NONE);\n ContextNodeType page_node =\n GetTypeAndURLFromFrame(webview_->main_frame()->frame(),\n &page_url,\n ContextNodeType(ContextNodeType::PAGE));\n if (selected_frame != webview_->main_frame()->frame()) {\n frame_node =\n GetTypeAndURLFromFrame(selected_frame,\n &frame_url,\n ContextNodeType(ContextNodeType::FRAME));\n }\n\n if (r.isSelected()) {\n node_type.type |= ContextNodeType::SELECTION;\n selection_text_string = CollapseWhitespace(\n webkit_glue::StringToStdWString(selected_frame->selectedText()),\n false);\n }\n\n if (r.isContentEditable()) {\n node_type.type |= ContextNodeType::EDITABLE;\n if (webview_->GetFocusedWebCoreFrame()->editor()->\n isContinuousSpellCheckingEnabled()) {\n misspelled_word_string = GetMisspelledWord(default_menu,\n selected_frame);\n }\n }\n\n if (node_type.type == ContextNodeType::NONE) {\n if (selected_frame != webview_->main_frame()->frame()) {\n node_type = frame_node;\n } else {\n node_type = page_node;\n }\n }\n\n \/\/ Now retrieve the security info.\n WebCore::DocumentLoader* dl = selected_frame->loader()->documentLoader();\n WebDataSource* ds = WebDataSourceImpl::FromLoader(dl);\n if (ds)\n security_info = ds->response().securityInfo();\n\n int edit_flags = ContextNodeType::CAN_DO_NONE;\n if (webview_->GetFocusedWebCoreFrame()->editor()->canUndo())\n edit_flags |= ContextNodeType::CAN_UNDO;\n if (webview_->GetFocusedWebCoreFrame()->editor()->canRedo())\n edit_flags |= ContextNodeType::CAN_REDO;\n if (webview_->GetFocusedWebCoreFrame()->editor()->canCut())\n edit_flags |= ContextNodeType::CAN_CUT;\n if (webview_->GetFocusedWebCoreFrame()->editor()->canCopy())\n edit_flags |= ContextNodeType::CAN_COPY;\n if (webview_->GetFocusedWebCoreFrame()->editor()->canPaste())\n edit_flags |= ContextNodeType::CAN_PASTE;\n if (webview_->GetFocusedWebCoreFrame()->editor()->canDelete())\n edit_flags |= ContextNodeType::CAN_DELETE;\n \/\/ We can always select all...\n edit_flags |= ContextNodeType::CAN_SELECT_ALL;\n\n WebViewDelegate* d = webview_->delegate();\n if (d) {\n d->ShowContextMenu(webview_,\n node_type,\n menu_point.x(),\n menu_point.y(),\n webkit_glue::KURLToGURL(link_url),\n webkit_glue::KURLToGURL(src_url),\n page_url,\n frame_url,\n media_params,\n selection_text_string,\n misspelled_word_string,\n edit_flags,\n security_info,\n frame_charset);\n }\n return NULL;\n}\n\nvoid ContextMenuClientImpl::contextMenuItemSelected(\n WebCore::ContextMenuItem*, const WebCore::ContextMenu*) {\n}\n\nvoid ContextMenuClientImpl::downloadURL(const WebCore::KURL&) {\n}\n\nvoid ContextMenuClientImpl::copyImageToClipboard(const WebCore::HitTestResult&) {\n}\n\nvoid ContextMenuClientImpl::searchWithGoogle(const WebCore::Frame*) {\n}\n\nvoid ContextMenuClientImpl::lookUpInDictionary(WebCore::Frame*) {\n}\n\nvoid ContextMenuClientImpl::speak(const WebCore::String&) {\n}\n\nbool ContextMenuClientImpl::isSpeaking() {\n return false;\n}\n\nvoid ContextMenuClientImpl::stopSpeaking() {\n}\n\nbool ContextMenuClientImpl::shouldIncludeInspectElementItem() {\n return false; \/\/ TODO(jackson): Eventually include the inspector context menu item\n}\n\n#if defined(OS_MACOSX)\nvoid ContextMenuClientImpl::searchWithSpotlight() {\n \/\/ TODO(pinkerton): write this\n}\n#endif\nDisable playback controls if audio\/video element has errored.\/\/ Copyright (c) 2006-2009 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"config.h\"\n\n#include \"base\/compiler_specific.h\"\n\nMSVC_PUSH_WARNING_LEVEL(0);\n#include \"ContextMenu.h\"\n#include \"Document.h\"\n#include \"DocumentLoader.h\"\n#include \"Editor.h\"\n#include \"EventHandler.h\"\n#include \"FrameLoader.h\"\n#include \"FrameView.h\"\n#include \"HitTestResult.h\"\n#include \"HTMLMediaElement.h\"\n#include \"HTMLNames.h\"\n#include \"KURL.h\"\n#include \"MediaError.h\"\n#include \"Widget.h\"\nMSVC_POP_WARNING();\n#undef LOG\n\n#include \"webkit\/glue\/context_menu_client_impl.h\"\n\n#include \"base\/string_util.h\"\n#include \"webkit\/api\/public\/WebURL.h\"\n#include \"webkit\/api\/public\/WebURLResponse.h\"\n#include \"webkit\/glue\/context_menu.h\"\n#include \"webkit\/glue\/glue_util.h\"\n#include \"webkit\/glue\/webdatasource_impl.h\"\n#include \"webkit\/glue\/webview_impl.h\"\n\n#include \"base\/word_iterator.h\"\n\nusing WebKit::WebDataSource;\n\nnamespace {\n\n\/\/ Helper function to determine whether text is a single word or a sentence.\nbool IsASingleWord(const std::wstring& text) {\n WordIterator iter(text, WordIterator::BREAK_WORD);\n int word_count = 0;\n if (!iter.Init()) return false;\n while (iter.Advance()) {\n if (iter.IsWord()) {\n word_count++;\n if (word_count > 1) \/\/ More than one word.\n return false;\n }\n }\n\n \/\/ Check for 0 words.\n if (!word_count)\n return false;\n\n \/\/ Has a single word.\n return true;\n}\n\n\/\/ Helper function to get misspelled word on which context menu\n\/\/ is to be evolked. This function also sets the word on which context menu\n\/\/ has been evoked to be the selected word, as required. This function changes\n\/\/ the selection only when there were no selected characters.\nstd::wstring GetMisspelledWord(const WebCore::ContextMenu* default_menu,\n WebCore::Frame* selected_frame) {\n std::wstring misspelled_word_string;\n\n \/\/ First select from selectedText to check for multiple word selection.\n misspelled_word_string = CollapseWhitespace(\n webkit_glue::StringToStdWString(selected_frame->selectedText()),\n false);\n\n \/\/ If some texts were already selected, we don't change the selection.\n if (!misspelled_word_string.empty()) {\n \/\/ Don't provide suggestions for multiple words.\n if (!IsASingleWord(misspelled_word_string))\n return L\"\";\n else\n return misspelled_word_string;\n }\n\n WebCore::HitTestResult hit_test_result = selected_frame->eventHandler()->\n hitTestResultAtPoint(default_menu->hitTestResult().point(), true);\n WebCore::Node* inner_node = hit_test_result.innerNode();\n WebCore::VisiblePosition pos(inner_node->renderer()->positionForPoint(\n hit_test_result.localPoint()));\n\n WebCore::VisibleSelection selection;\n if (pos.isNotNull()) {\n selection = WebCore::VisibleSelection(pos);\n selection.expandUsingGranularity(WebCore::WordGranularity);\n }\n\n if (selection.isRange()) {\n selected_frame->setSelectionGranularity(WebCore::WordGranularity);\n }\n\n if (selected_frame->shouldChangeSelection(selection))\n selected_frame->selection()->setSelection(selection);\n\n misspelled_word_string = CollapseWhitespace(\n webkit_glue::StringToStdWString(selected_frame->selectedText()),\n false);\n\n \/\/ If misspelled word is empty, then that portion should not be selected.\n \/\/ Set the selection to that position only, and do not expand.\n if (misspelled_word_string.empty()) {\n selection = WebCore::VisibleSelection(pos);\n selected_frame->selection()->setSelection(selection);\n }\n\n return misspelled_word_string;\n}\n\n} \/\/ namespace\n\nContextMenuClientImpl::~ContextMenuClientImpl() {\n}\n\nvoid ContextMenuClientImpl::contextMenuDestroyed() {\n delete this;\n}\n\n\/\/ Figure out the URL of a page or subframe. Returns |page_type| as the type,\n\/\/ which indicates page or subframe, or ContextNodeType::NONE if the URL could not\n\/\/ be determined for some reason.\nstatic ContextNodeType GetTypeAndURLFromFrame(\n WebCore::Frame* frame,\n GURL* url,\n ContextNodeType page_node_type) {\n ContextNodeType node_type;\n if (frame) {\n WebCore::DocumentLoader* dl = frame->loader()->documentLoader();\n if (dl) {\n WebDataSource* ds = WebDataSourceImpl::FromLoader(dl);\n if (ds) {\n node_type = page_node_type;\n *url = ds->hasUnreachableURL() ? ds->unreachableURL()\n : ds->request().url();\n }\n }\n }\n return node_type;\n}\n\nWebCore::PlatformMenuDescription\n ContextMenuClientImpl::getCustomMenuFromDefaultItems(\n WebCore::ContextMenu* default_menu) {\n \/\/ Displaying the context menu in this function is a big hack as we don't\n \/\/ have context, i.e. whether this is being invoked via a script or in\n \/\/ response to user input (Mouse event WM_RBUTTONDOWN,\n \/\/ Keyboard events KeyVK_APPS, Shift+F10). Check if this is being invoked\n \/\/ in response to the above input events before popping up the context menu.\n if (!webview_->context_menu_allowed())\n return NULL;\n\n WebCore::HitTestResult r = default_menu->hitTestResult();\n WebCore::Frame* selected_frame = r.innerNonSharedNode()->document()->frame();\n\n WebCore::IntPoint menu_point =\n selected_frame->view()->contentsToWindow(r.point());\n\n ContextNodeType node_type;\n\n \/\/ Links, Images, Media tags, and Image\/Media-Links take preference over\n \/\/ all else.\n WebCore::KURL link_url = r.absoluteLinkURL();\n if (!link_url.isEmpty()) {\n node_type.type |= ContextNodeType::LINK;\n }\n\n WebCore::KURL src_url;\n\n ContextMenuMediaParams media_params;\n\n if (!r.absoluteImageURL().isEmpty()) {\n src_url = r.absoluteImageURL();\n node_type.type |= ContextNodeType::IMAGE;\n } else if (!r.absoluteMediaURL().isEmpty()) {\n src_url = r.absoluteMediaURL();\n\n \/\/ We know that if absoluteMediaURL() is not empty, then this is a media\n \/\/ element.\n WebCore::HTMLMediaElement* media_element =\n static_cast(r.innerNonSharedNode());\n if (media_element->hasTagName(WebCore::HTMLNames::videoTag)) {\n node_type.type |= ContextNodeType::VIDEO;\n } else if (media_element->hasTagName(WebCore::HTMLNames::audioTag)) {\n node_type.type |= ContextNodeType::AUDIO;\n }\n\n if (media_element->error()) {\n media_params.player_state |= ContextMenuMediaParams::IN_ERROR;\n }\n if (media_element->paused()) {\n media_params.player_state |= ContextMenuMediaParams::PAUSED;\n }\n if (media_element->muted()) {\n media_params.player_state |= ContextMenuMediaParams::MUTED;\n }\n if (media_element->loop()) {\n media_params.player_state |= ContextMenuMediaParams::LOOP;\n }\n if (media_element->supportsSave()) {\n media_params.player_state |= ContextMenuMediaParams::CAN_SAVE;\n }\n }\n\n \/\/ If it's not a link, an image, a media element, or an image\/media link,\n \/\/ show a selection menu or a more generic page menu.\n std::wstring selection_text_string;\n std::wstring misspelled_word_string;\n GURL frame_url;\n GURL page_url;\n std::string security_info;\n\n std::string frame_charset = WideToASCII(\n webkit_glue::StringToStdWString(selected_frame->loader()->encoding()));\n \/\/ Send the frame and page URLs in any case.\n ContextNodeType frame_node = ContextNodeType(ContextNodeType::NONE);\n ContextNodeType page_node =\n GetTypeAndURLFromFrame(webview_->main_frame()->frame(),\n &page_url,\n ContextNodeType(ContextNodeType::PAGE));\n if (selected_frame != webview_->main_frame()->frame()) {\n frame_node =\n GetTypeAndURLFromFrame(selected_frame,\n &frame_url,\n ContextNodeType(ContextNodeType::FRAME));\n }\n\n if (r.isSelected()) {\n node_type.type |= ContextNodeType::SELECTION;\n selection_text_string = CollapseWhitespace(\n webkit_glue::StringToStdWString(selected_frame->selectedText()),\n false);\n }\n\n if (r.isContentEditable()) {\n node_type.type |= ContextNodeType::EDITABLE;\n if (webview_->GetFocusedWebCoreFrame()->editor()->\n isContinuousSpellCheckingEnabled()) {\n misspelled_word_string = GetMisspelledWord(default_menu,\n selected_frame);\n }\n }\n\n if (node_type.type == ContextNodeType::NONE) {\n if (selected_frame != webview_->main_frame()->frame()) {\n node_type = frame_node;\n } else {\n node_type = page_node;\n }\n }\n\n \/\/ Now retrieve the security info.\n WebCore::DocumentLoader* dl = selected_frame->loader()->documentLoader();\n WebDataSource* ds = WebDataSourceImpl::FromLoader(dl);\n if (ds)\n security_info = ds->response().securityInfo();\n\n int edit_flags = ContextNodeType::CAN_DO_NONE;\n if (webview_->GetFocusedWebCoreFrame()->editor()->canUndo())\n edit_flags |= ContextNodeType::CAN_UNDO;\n if (webview_->GetFocusedWebCoreFrame()->editor()->canRedo())\n edit_flags |= ContextNodeType::CAN_REDO;\n if (webview_->GetFocusedWebCoreFrame()->editor()->canCut())\n edit_flags |= ContextNodeType::CAN_CUT;\n if (webview_->GetFocusedWebCoreFrame()->editor()->canCopy())\n edit_flags |= ContextNodeType::CAN_COPY;\n if (webview_->GetFocusedWebCoreFrame()->editor()->canPaste())\n edit_flags |= ContextNodeType::CAN_PASTE;\n if (webview_->GetFocusedWebCoreFrame()->editor()->canDelete())\n edit_flags |= ContextNodeType::CAN_DELETE;\n \/\/ We can always select all...\n edit_flags |= ContextNodeType::CAN_SELECT_ALL;\n\n WebViewDelegate* d = webview_->delegate();\n if (d) {\n d->ShowContextMenu(webview_,\n node_type,\n menu_point.x(),\n menu_point.y(),\n webkit_glue::KURLToGURL(link_url),\n webkit_glue::KURLToGURL(src_url),\n page_url,\n frame_url,\n media_params,\n selection_text_string,\n misspelled_word_string,\n edit_flags,\n security_info,\n frame_charset);\n }\n return NULL;\n}\n\nvoid ContextMenuClientImpl::contextMenuItemSelected(\n WebCore::ContextMenuItem*, const WebCore::ContextMenu*) {\n}\n\nvoid ContextMenuClientImpl::downloadURL(const WebCore::KURL&) {\n}\n\nvoid ContextMenuClientImpl::copyImageToClipboard(const WebCore::HitTestResult&) {\n}\n\nvoid ContextMenuClientImpl::searchWithGoogle(const WebCore::Frame*) {\n}\n\nvoid ContextMenuClientImpl::lookUpInDictionary(WebCore::Frame*) {\n}\n\nvoid ContextMenuClientImpl::speak(const WebCore::String&) {\n}\n\nbool ContextMenuClientImpl::isSpeaking() {\n return false;\n}\n\nvoid ContextMenuClientImpl::stopSpeaking() {\n}\n\nbool ContextMenuClientImpl::shouldIncludeInspectElementItem() {\n return false; \/\/ TODO(jackson): Eventually include the inspector context menu item\n}\n\n#if defined(OS_MACOSX)\nvoid ContextMenuClientImpl::searchWithSpotlight() {\n \/\/ TODO(pinkerton): write this\n}\n#endif\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \n\n#include \"base\/file_path.h\"\n#include \"base\/file_util.h\"\n#include \"base\/path_service.h\"\n#include \"base\/string_util.h\"\n#include \"net\/base\/escape.h\"\n#include \"testing\/gtest\/include\/gtest\/gtest.h\"\n#include \"third_party\/WebKit\/WebKit\/chromium\/public\/WebData.h\"\n#include \"third_party\/WebKit\/WebKit\/chromium\/public\/WebFrame.h\"\n#include \"third_party\/WebKit\/WebKit\/chromium\/public\/WebInputEvent.h\"\n#include \"third_party\/WebKit\/WebKit\/chromium\/public\/WebScriptSource.h\"\n#include \"third_party\/WebKit\/WebKit\/chromium\/public\/WebView.h\"\n#include \"webkit\/tools\/test_shell\/test_shell.h\"\n#include \"webkit\/tools\/test_shell\/test_shell_test.h\"\n\nusing WebKit::WebFrame;\nusing WebKit::WebScriptSource;\nusing WebKit::WebString;\n\n#if defined(OS_WIN)\n#define TEST_PLUGIN_NAME \"npapi_test_plugin.dll\"\n#elif defined(OS_MACOSX)\n#define TEST_PLUGIN_NAME \"npapi_test_plugin.plugin\"\n#elif defined(OS_POSIX)\n#define TEST_PLUGIN_NAME \"libnpapi_test_plugin.so\"\n#endif\n\n#if defined(OS_MACOSX)\n#define TEST_PLUGIN_DIRECTORY \"PlugIns\"\n#else\n#define TEST_PLUGIN_DIRECTORY \"plugins\"\n#endif\n\n\/\/ Ignore these until 64-bit plugin build is fixed. http:\/\/crbug.com\/18337\n#if !defined(ARCH_CPU_64_BITS)\n\/\/ Provides functionality for creating plugin tests.\nclass PluginTest : public TestShellTest {\n public:\n PluginTest() {\n FilePath executable_directory;\n PathService::Get(base::DIR_EXE, &executable_directory);\n plugin_src_ = executable_directory.AppendASCII(TEST_PLUGIN_NAME);\n CHECK(file_util::PathExists(plugin_src_));\n\n plugin_file_path_ = executable_directory.AppendASCII(TEST_PLUGIN_DIRECTORY);\n file_util::CreateDirectory(plugin_file_path_);\n\n plugin_file_path_ = plugin_file_path_.AppendASCII(TEST_PLUGIN_NAME);\n }\n\n void CopyTestPlugin() {\n \/\/ On Linux, we need to delete before copying because if the plugin is a\n \/\/ hard link, the copy will fail.\n DeleteTestPlugin();\n ASSERT_TRUE(file_util::CopyDirectory(plugin_src_, plugin_file_path_, true));\n }\n\n void DeleteTestPlugin() {\n file_util::Delete(plugin_file_path_, true);\n }\n\n virtual void SetUp() {\n CopyTestPlugin();\n TestShellTest::SetUp();\n }\n\n virtual void TearDown() {\n DeleteTestPlugin();\n TestShellTest::TearDown();\n }\n\n FilePath plugin_src_;\n FilePath plugin_file_path_;\n};\n\n\/\/ Tests navigator.plugins.refresh() works.\nTEST_F(PluginTest, Refresh) {\n std::string html = \"\\\n
Test running....<\/div>\\\n