text
stringlengths
54
60.6k
<commit_before>// //#include <unistd.h> #include <cstdio> #include <cstdlib> #include <string> #include <ctime> #include <algorithm> #include <cmath> #include "GPIOClass.h" using namespace std; void Pulse(GPIOClass* pin, double cycles); void Wait(double seconds); clock_t timer; double time_to_complete; double resolution = 10000; #define PI 4*atan(1) int main (int argc, char *argv[]) { string type = argv[1]; transform(type.begin(), type.end(), type.begin(), :: tolower); // lets assume that the way to run this is // pwm.exe [rising/falling/sine/constant] if (argc != 2) { cout << "Usage: pwm [rising/falling/sine/constant/blink]" << endl; return -1; } while (time_to_complete <= 0) { cout << "Input How Long To Run (in seconds)" << endl; cin >> time_to_complete; } GPIOClass* out1 = new GPIOClass("4"); GPIOClass* in2 = new GPIOClass("17"); out1->export_gpio(); in2->export_gpio(); out1->setdir_gpio("out"); in2->setdir_gpio("in"); cout << "Pins are setup." << endl; // avoiding flickering will be at 100hz // aka turn on and off 100 times a sec // a cycle of 0 is off // a cycle of 100 is on if (type == "rising") { clock_t finish = clock() + time_to_complete * CLOCKS_PER_SEC; double t = time_to_complete; while (clock() < finish) { // pulse for however long we need to to achieve brightness. t -= 1; cout << sin((PI/2) * (1/t)) << endl; Pulse(out1, sin((PI/2) * (1/t))); Wait(sin((PI/2) * (1/t))); } } if (type == "falling") { } if (type == "sine") { } if (type == "constant") { out1->setval_gpio("1"); // turn the pin on Wait(time_to_complete); // sleep for number of cycles / 1/100 sec //cout << "Waiting during pulse" << endl; out1->setval_gpio("0"); // turn the pin off } if (type == "blink") { // aka. TESTR clock_t finish = clock() + time_to_complete * CLOCKS_PER_SEC; while (clock() < finish) { // pulse for however long we need to to achieve brightness. Pulse(out1, 1 * resolution); Wait(0.5); } } cout << "Done." << endl; } //1 cycle is 1/100th of a second //100 cycles is 1 sec void Pulse(GPIOClass* pin, double cycles) { bool running = true; while (running) { pin->setval_gpio("1"); // turn the pin on Wait(cycles / resolution); // sleep for number of cycles / 1/100 sec //cout << "Waiting during pulse" << endl; pin->setval_gpio("0"); // turn the pin off running = false; // this is unnessesary but could be useful if modified a bit. } } void Wait ( double seconds ) { clock_t endwait; endwait = clock () + seconds * CLOCKS_PER_SEC ; while (clock() < endwait) {} } <commit_msg>Update pwm.cpp<commit_after>// //#include <unistd.h> #include <cstdio> #include <cstdlib> #include <string> #include <ctime> #include <algorithm> #include <cmath> #include "GPIOClass.h" using namespace std; void Pulse(GPIOClass* pin, double cycles); void Wait(double seconds); clock_t timer; double time_to_complete; double resolution = 10000; #define PI 4*atan(1) int main (int argc, char *argv[]) { string type = argv[1]; transform(type.begin(), type.end(), type.begin(), :: tolower); // lets assume that the way to run this is // pwm.exe [rising/falling/sine/constant] if (argc != 2) { cout << "Usage: pwm [rising/falling/sine/constant/blink]" << endl; return -1; } while (time_to_complete <= 0) { cout << "Input How Long To Run (in seconds)" << endl; cin >> time_to_complete; } GPIOClass* out1 = new GPIOClass("4"); GPIOClass* in2 = new GPIOClass("17"); out1->export_gpio(); in2->export_gpio(); out1->setdir_gpio("out"); in2->setdir_gpio("in"); cout << "Pins are setup." << endl; // avoiding flickering will be at 100hz // aka turn on and off 100 times a sec // a cycle of 0 is off // a cycle of 100 is on if (type == "rising") { clock_t finish = clock() + time_to_complete * CLOCKS_PER_SEC; double t = time_to_complete; while (clock() < finish) { // pulse for however long we need to to achieve brightness. t -= 1; //cout << sin((PI/2) * (1/t)) << endl; Pulse(out1, sin((PI/2) * (1/t))); Wait(sin((PI/2) * (1/t))); } } if (type == "falling") { } if (type == "sine") { } if (type == "constant") { out1->setval_gpio("1"); // turn the pin on Wait(time_to_complete); // sleep for number of cycles / 1/100 sec //cout << "Waiting during pulse" << endl; out1->setval_gpio("0"); // turn the pin off } if (type == "blink") { // aka. TESTR clock_t finish = clock() + time_to_complete * CLOCKS_PER_SEC; while (clock() < finish) { // pulse for however long we need to to achieve brightness. Pulse(out1, 1 * resolution); Wait(0.5); } } cout << "Done." << endl; } //1 cycle is 1/100th of a second //100 cycles is 1 sec void Pulse(GPIOClass* pin, double cycles) { bool running = true; while (running) { pin->setval_gpio("1"); // turn the pin on Wait(cycles / resolution); // sleep for number of cycles / 1/100 sec //cout << "Waiting during pulse" << endl; pin->setval_gpio("0"); // turn the pin off running = false; // this is unnessesary but could be useful if modified a bit. } } void Wait ( double seconds ) { clock_t endwait; endwait = clock () + seconds * CLOCKS_PER_SEC ; while (clock() < endwait) {} } <|endoftext|>
<commit_before>/** \file extract_normdata_translations.cc * \brief Extract IxTheo and MACS translations from the normdata file and write it to * language specific text files * \author Johannes Riedl */ /* Copyright (C) 2016, Library of the University of Tübingen This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* The German term is found in Field 150 Currently there are two different kinds of translations: IxTheo-Translations with the following definitions: 710: Körperschaft - fremdsprachige Äquivalenz 711: Konferenz - fremdsprachige Äquivalenz 700: Person - fremdsprachige Äquivalenz 730: Titel - fremdsprachige Äquivalenz 750: Sachbegriff - fremdsprachige Äquivalenz 751: Geografikum - fremdsprachige Äquivalenz LoC/Rameau Translations: 700: Person - Bevorzugter Name in einem anderen Datenbestand 710: Körperschaft - Bevorzugter Name in einem anderen Datenbestand 711: Konferenz - Bevorzugte Benennung in einem anderen Datenbestand 730: Einheitstitel - Bevorzugter Name in einem anderen Datenbestand 750: Sachbegriff - Bevorzugte Benennung in einem anderen Datenbestand 751: Geografikum - Bevorzugter Name in einem anderen Datenbestand */ #include <iostream> #include <vector> #include <cstdlib> #include "Compiler.h" #include "MarcUtil.h" #include "MediaTypeUtil.h" #include "StringUtil.h" #include "Subfields.h" #include "util.h" // Languages to handle const unsigned int NUMBER_OF_LANGUAGES = 2; const std::vector<std::string> languages_to_create{ "en", "fr" }; enum languages { en, fr }; void Usage() { std::cerr << "Usage: " << ::progname << " norm_data_marc_input extracted_translations\n"; std::exit(EXIT_FAILURE); } void AugmentIxTheoTagWithLanguage(const MarcUtil::Record &record, const std::string &tag, std::vector<std::string> * const translations) { auto ixtheo_pos = std::find(translations->begin(), translations->end(), "IxTheo"); if (ixtheo_pos != translations->end()) { std::vector<std::string> ixtheo_lang_code; record.extractSubfields(tag, "9", &ixtheo_lang_codes); bool already_found_ixtheo_translation(false); for (const auto &lang_code : ixtheo_lang_codes) { if (lang_code[0] != 'L') continue; if (already_found_ixtheo_translation) continue; if (lang_code.find("eng") != std::string::npos and *ixtheo_pos != "IxTheo_eng") { *ixtheo_pos += + "_eng"; already_found_ixtheo_translation = true; } else if (lang_code.find("fra") != std::string::npos and *ixtheo_pos != "IxTheo_fra") { *ixtheo_pos += "_fra"; already_found_ixtheo_translation = true; } else Warning("Unsupported language code \"" + lang_code + "\" for PPN " + record.getFields()[0]); } } } void ExtractTranslations(File* const marc_norm_input, const std::string german_term_field_spec, const std::string translation_field_spec, std::map<std::string, std::string> term_to_translation_maps[]) { std::set<std::string> german_tags_and_subfield_codes; if (unlikely(StringUtil::Split(german_term_field_spec, ':', &german_tags_and_subfield_codes) < 1)) Error("ExtractTranslations: Need at least one translation field"); std::set<std::string> translation_tags_and_subfield_codes; if (unlikely(StringUtil::Split(translation_field_spec, ':', &translation_tags_and_subfield_codes) < 1)) Error("ExtractTranslations: Need at least one translation field"); unsigned count(0); while (const MarcUtil::Record record = MarcUtil::Record::XmlFactory(marc_norm_input)) { std::vector<std::string> german_terms; // Determine the German term we will have translations for for (const auto tag_and_subfields : german_tags_and_subfield_codes) { const std::string tag(tag_and_subfields.substr(0, 3)); const std::string subfields(tag_and_subfields.substr(3)); std::vector<std::string> german_term_for_one_field; record.extractSubfields(tag, subfields, &german_term_for_one_field); // We may get the german term from only one field if (german_terms.size() > 1) Warning("We have german terms in more than one field for PPN: " + record.getFields()[0]); if (not german_term_for_one_field.empty()) german_terms = german_term_for_one_field; } std::vector<std::string> all_translations; // Extract all additional translations for (auto tag_and_subfields : translation_tags_and_subfield_codes) { const std::string tag(tag_and_subfields.substr(0, 3)); const std::string subfields(tag_and_subfields.substr(3)); std::vector<std::string> translations; record.extractSubfields(tag, subfields, &translations); // For IxTheo-Translations add the language code in the same field AugmentIxTheoTagWithLanguage(record, tag, &translations); all_translations.insert(all_translations.end(), translations.begin(), translations.end()); } for (auto it = all_translations.begin(); it != all_translations.end(); ++it) { if (*it == "IxTheo_eng") { term_to_translation_maps[en].emplace(StringUtil::Join(german_terms, ' '), *(it + 1)); ++it; } else if (*it == "IxTheo_fra") { term_to_translation_maps[fr].emplace(StringUtil::Join(german_terms, ' '), *(it + 1)); ++it; } else if (*it == "lcsh") { term_to_translation_maps[en].emplace(StringUtil::Join(german_terms, ' '), *(it + 1)); ++it; } else if (*it == "ram") { term_to_translation_maps[fr].emplace(StringUtil::Join(german_terms, ' '), *(it + 1)); ++it; } } } ++count; } std::unique_ptr<File> OpenInputFile(const std::string &filename) { std::string mode("r"); if (MediaTypeUtil::GetFileMediaType(filename) == "application/lz4") mode += "u"; std::unique_ptr<File> file(new File(filename, mode)); if (file->fail()) Error("can't open \"" + filename + "\" for reading!"); return file; } int main(int argc, char **argv) { ::progname = argv[0]; if (argc != 3) Usage(); const std::string norm_data_marc_input_filename(argv[1]); std::unique_ptr<File> norm_data_marc_input(OpenInputFile(norm_data_marc_input_filename)); const std::string extracted_translations_filename(argv[2]); if (unlikely(norm_data_marc_input_filename == extracted_translations_filename)) Error("Norm data input file name equals output file name!"); std::string output_mode("w"); if (norm_data_marc_input->isCompressingOrUncompressing()) output_mode += 'c'; // Create a file for each language std::vector<std::string> output_file_components; if (unlikely(StringUtil::Split(extracted_translations_filename, ".", &output_file_components) < 1)) Error("extracted_translations_filename " + extracted_translations_filename + " is not valid"); File *lang_files[NUMBER_OF_LANGUAGES]; unsigned i(0); // Derive output components from given input filename std::string extension = (output_file_components.size() > 1) ? output_file_components.back() : ""; std::string basename; if (not extension.empty()) output_file_components.pop_back(); basename = StringUtil::Join(output_file_components, "."); // Assemble output filename for (auto lang : languages_to_create) { lang = StringUtil::Trim(lang); std::string lang_file_name_str = (extension != "") ? basename + "_" + lang + "." + extension : basename + "_" + lang; lang_files[i] = new File(lang_file_name_str, output_mode); if (lang_files[i]->fail()) Error("can't open \"" + lang_file_name_str + "\" for writing!"); ++i; } try { std::map<std::string, std::string> term_to_translation_maps[NUMBER_OF_LANGUAGES]; ExtractTranslations(norm_data_marc_input.get(), "100a:150a", "750a2", term_to_translation_maps); for (auto line : term_to_translation_maps[en]) { *(lang_files[en]) << line.first << "|" << line.second << "\n"; } for (auto line : term_to_translation_maps[fr]) { *(lang_files[fr]) << line.first << "|" << line.second << "\n"; } } catch (const std::exception &x) { Error("caught exception: " + std::string(x.what())); } } <commit_msg>Desired changes<commit_after>/** \file extract_normdata_translations.cc * \brief Extract IxTheo and MACS translations from the normdata file and write it to * language specific text files * \author Johannes Riedl */ /* Copyright (C) 2016, Library of the University of Tübingen This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* The German term is found in Field 150 Currently there are two different kinds of translations: IxTheo-Translations with the following definitions: 710: Körperschaft - fremdsprachige Äquivalenz 711: Konferenz - fremdsprachige Äquivalenz 700: Person - fremdsprachige Äquivalenz 730: Titel - fremdsprachige Äquivalenz 750: Sachbegriff - fremdsprachige Äquivalenz 751: Geografikum - fremdsprachige Äquivalenz LoC/Rameau Translations: 700: Person - Bevorzugter Name in einem anderen Datenbestand 710: Körperschaft - Bevorzugter Name in einem anderen Datenbestand 711: Konferenz - Bevorzugte Benennung in einem anderen Datenbestand 730: Einheitstitel - Bevorzugter Name in einem anderen Datenbestand 750: Sachbegriff - Bevorzugte Benennung in einem anderen Datenbestand 751: Geografikum - Bevorzugter Name in einem anderen Datenbestand */ #include <iostream> #include <vector> #include <cstdlib> #include "Compiler.h" #include "MarcUtil.h" #include "MediaTypeUtil.h" #include "StringUtil.h" #include "Subfields.h" #include "util.h" // Languages to handle const unsigned int NUMBER_OF_LANGUAGES = 2; const std::vector<std::string> languages_to_create{ "en", "fr" }; enum languages { EN, FR }; void Usage() { std::cerr << "Usage: " << ::progname << " norm_data_marc_input extracted_translations\n"; std::exit(EXIT_FAILURE); } void AugmentIxTheoTagWithLanguage(const MarcUtil::Record &record, const std::string &tag, std::vector<std::string> * const translations) { auto ixtheo_pos(std::find(translations->begin(), translations->end(), "IxTheo")); if (ixtheo_pos != translations->end()) { std::vector<std::string> ixtheo_lang_codes; record.extractSubfields(tag, "9", &ixtheo_lang_codes); bool already_found_ixtheo_translation(false); for (const auto &lang_code : ixtheo_lang_codes) { if (lang_code[0] != 'L') continue; if (already_found_ixtheo_translation) continue; if (lang_code.find("eng") != std::string::npos and *ixtheo_pos != "IxTheo_eng") { *ixtheo_pos += + "_eng"; already_found_ixtheo_translation = true; } else if (lang_code.find("fra") != std::string::npos and *ixtheo_pos != "IxTheo_fra") { *ixtheo_pos += "_fra"; already_found_ixtheo_translation = true; } else Warning("Unsupported language code \"" + lang_code + "\" for PPN " + record.getFields()[0]); } } } void ExtractTranslations(File* const marc_norm_input, const std::string german_term_field_spec, const std::string translation_field_spec, std::map<std::string, std::string> term_to_translation_maps[]) { std::set<std::string> german_tags_and_subfield_codes; if (unlikely(StringUtil::Split(german_term_field_spec, ':', &german_tags_and_subfield_codes) < 1)) Error("ExtractTranslations: Need at least one translation field"); std::set<std::string> translation_tags_and_subfield_codes; if (unlikely(StringUtil::Split(translation_field_spec, ':', &translation_tags_and_subfield_codes) < 1)) Error("ExtractTranslations: Need at least one translation field"); unsigned count(0); while (const MarcUtil::Record record = MarcUtil::Record::XmlFactory(marc_norm_input)) { std::vector<std::string> german_terms; // Determine the German term we will have translations for for (const auto tag_and_subfields : german_tags_and_subfield_codes) { const std::string tag(tag_and_subfields.substr(0, 3)); const std::string subfields(tag_and_subfields.substr(3)); std::vector<std::string> german_term_for_one_field; record.extractSubfields(tag, subfields, &german_term_for_one_field); // We may get the german term from only one field if (german_terms.size() > 1) Warning("We have german terms in more than one field for PPN: " + record.getFields()[0]); if (not german_term_for_one_field.empty()) german_terms = german_term_for_one_field; } std::vector<std::string> all_translations; // Extract all additional translations for (auto tag_and_subfields : translation_tags_and_subfield_codes) { const std::string tag(tag_and_subfields.substr(0, 3)); const std::string subfields(tag_and_subfields.substr(3)); std::vector<std::string> translations; record.extractSubfields(tag, subfields, &translations); // For IxTheo-Translations add the language code in the same field AugmentIxTheoTagWithLanguage(record, tag, &translations); all_translations.insert(all_translations.end(), translations.begin(), translations.end()); } for (auto it = all_translations.begin(); it != all_translations.end(); ++it) { if (*it == "IxTheo_eng") { term_to_translation_maps[EN].emplace(StringUtil::Join(german_terms, ' '), *(it + 1)); ++it; } else if (*it == "IxTheo_fra") { term_to_translation_maps[FR].emplace(StringUtil::Join(german_terms, ' '), *(it + 1)); ++it; } else if (*it == "lcsh") { term_to_translation_maps[EN].emplace(StringUtil::Join(german_terms, ' '), *(it + 1)); ++it; } else if (*it == "ram") { term_to_translation_maps[FR].emplace(StringUtil::Join(german_terms, ' '), *(it + 1)); ++it; } } } ++count; } std::unique_ptr<File> OpenInputFile(const std::string &filename) { std::string mode("r"); if (MediaTypeUtil::GetFileMediaType(filename) == "application/lz4") mode += "u"; std::unique_ptr<File> file(new File(filename, mode)); if (file->fail()) Error("can't open \"" + filename + "\" for reading!"); return file; } int main(int argc, char **argv) { ::progname = argv[0]; if (argc != 3) Usage(); const std::string norm_data_marc_input_filename(argv[1]); std::unique_ptr<File> norm_data_marc_input(OpenInputFile(norm_data_marc_input_filename)); const std::string extracted_translations_filename(argv[2]); if (unlikely(norm_data_marc_input_filename == extracted_translations_filename)) Error("Norm data input file name equals output file name!"); std::string output_mode("w"); if (norm_data_marc_input->isCompressingOrUncompressing()) output_mode += 'c'; // Create a file for each language std::vector<std::string> output_file_components; if (unlikely(StringUtil::Split(extracted_translations_filename, ".", &output_file_components) < 1)) Error("extracted_translations_filename " + extracted_translations_filename + " is not valid"); File *lang_files[NUMBER_OF_LANGUAGES]; unsigned i(0); // Derive output components from given input filename std::string extension = (output_file_components.size() > 1) ? output_file_components.back() : ""; std::string basename; if (not extension.empty()) output_file_components.pop_back(); basename = StringUtil::Join(output_file_components, "."); // Assemble output filename for (auto lang : languages_to_create) { lang = StringUtil::Trim(lang); std::string lang_file_name_str = (extension != "") ? basename + "_" + lang + "." + extension : basename + "_" + lang; lang_files[i] = new File(lang_file_name_str, output_mode); if (lang_files[i]->fail()) Error("can't open \"" + lang_file_name_str + "\" for writing!"); ++i; } try { std::map<std::string, std::string> term_to_translation_maps[NUMBER_OF_LANGUAGES]; ExtractTranslations(norm_data_marc_input.get(), "100a:150a", "750a2", term_to_translation_maps); for (auto line : term_to_translation_maps[EN]) { *(lang_files[EN]) << line.first << "|" << line.second << "\n"; } for (auto line : term_to_translation_maps[FR]) { *(lang_files[FR]) << line.first << "|" << line.second << "\n"; } } catch (const std::exception &x) { Error("caught exception: " + std::string(x.what())); } } <|endoftext|>
<commit_before>/**************************************************************************** ** ** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies). ** Contact: http://www.qt-project.org/legal ** ** This file is part of Qt Creator. ** ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Digia. For licensing terms and ** conditions see http://qt.digia.com/licensing. For further information ** use the contact form at http://qt.digia.com/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Digia gives you certain additional ** rights. These rights are described in the Digia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ****************************************************************************/ #include "branchdialog.h" #include "branchadddialog.h" #include "branchcheckoutdialog.h" #include "branchmodel.h" #include "gitclient.h" #include "gitplugin.h" #include "gitutils.h" #include "ui_branchdialog.h" #include "stashdialog.h" // Label helpers #include <utils/qtcassert.h> #include <utils/execmenu.h> #include <vcsbase/vcsbaseoutputwindow.h> #include <coreplugin/documentmanager.h> #include <QAction> #include <QItemSelectionModel> #include <QMessageBox> #include <QList> #include <QMenu> #include <QDebug> namespace Git { namespace Internal { BranchDialog::BranchDialog(QWidget *parent) : QDialog(parent), m_ui(new Ui::BranchDialog), m_model(new BranchModel(GitPlugin::instance()->gitClient(), this)) { setModal(false); setWindowFlags(windowFlags() & ~Qt::WindowContextHelpButtonHint); setAttribute(Qt::WA_DeleteOnClose, true); // Do not update unnecessarily m_ui->setupUi(this); connect(m_ui->refreshButton, SIGNAL(clicked()), this, SLOT(refresh())); connect(m_ui->addButton, SIGNAL(clicked()), this, SLOT(add())); connect(m_ui->checkoutButton, SIGNAL(clicked()), this, SLOT(checkout())); connect(m_ui->removeButton, SIGNAL(clicked()), this, SLOT(remove())); connect(m_ui->renameButton, SIGNAL(clicked()), this, SLOT(rename())); connect(m_ui->diffButton, SIGNAL(clicked()), this, SLOT(diff())); connect(m_ui->logButton, SIGNAL(clicked()), this, SLOT(log())); connect(m_ui->resetButton, SIGNAL(clicked()), this, SLOT(reset())); connect(m_ui->mergeButton, SIGNAL(clicked()), this, SLOT(merge())); connect(m_ui->rebaseButton, SIGNAL(clicked()), this, SLOT(rebase())); connect(m_ui->cherryPickButton, SIGNAL(clicked()), this, SLOT(cherryPick())); connect(m_ui->trackButton, SIGNAL(clicked()), this, SLOT(setRemoteTracking())); m_ui->branchView->setModel(m_model); connect(m_ui->branchView->selectionModel(), SIGNAL(selectionChanged(QItemSelection,QItemSelection)), this, SLOT(enableButtons())); enableButtons(); } BranchDialog::~BranchDialog() { delete m_ui; } void BranchDialog::refresh(const QString &repository, bool force) { if (m_repository == repository && !force) return; m_repository = repository; m_ui->repositoryLabel->setText(StashDialog::msgRepositoryLabel(m_repository)); QString errorMessage; if (!m_model->refresh(m_repository, &errorMessage)) VcsBase::VcsBaseOutputWindow::instance()->appendError(errorMessage); m_ui->branchView->expandAll(); } void BranchDialog::refreshIfSame(const QString &repository) { if (m_repository == repository) refresh(); } void BranchDialog::enableButtons() { QModelIndex idx = selectedIndex(); QModelIndex currentBranch = m_model->currentBranch(); const bool hasSelection = idx.isValid(); const bool currentSelected = hasSelection && idx == currentBranch; const bool isLocal = m_model->isLocal(idx); const bool isLeaf = m_model->isLeaf(idx); const bool isTag = m_model->isTag(idx); const bool hasActions = hasSelection && isLeaf; const bool currentLocal = m_model->isLocal(currentBranch); m_ui->removeButton->setEnabled(hasActions && !currentSelected && (isLocal || isTag)); m_ui->renameButton->setEnabled(hasActions && (isLocal || isTag)); m_ui->logButton->setEnabled(hasActions); m_ui->diffButton->setEnabled(hasActions); m_ui->checkoutButton->setEnabled(hasActions && !currentSelected); m_ui->rebaseButton->setEnabled(hasActions && !currentSelected); m_ui->resetButton->setEnabled(hasActions && currentLocal && !currentSelected); m_ui->mergeButton->setEnabled(hasActions && !currentSelected); m_ui->cherryPickButton->setEnabled(hasActions && !currentSelected); m_ui->trackButton->setEnabled(hasActions && currentLocal && !currentSelected && !isTag); } void BranchDialog::refresh() { refresh(m_repository, true); } void BranchDialog::add() { QModelIndex trackedIndex = selectedIndex(); QString trackedBranch = m_model->fullName(trackedIndex); if (trackedBranch.isEmpty()) { trackedIndex = m_model->currentBranch(); trackedBranch = m_model->fullName(trackedIndex); } const bool isLocal = m_model->isLocal(trackedIndex); const bool isTag = m_model->isTag(trackedIndex); QStringList localNames = m_model->localBranchNames(); QString suggestedNameBase = trackedBranch.mid(trackedBranch.lastIndexOf(QLatin1Char('/')) + 1); QString suggestedName = suggestedNameBase; int i = 2; while (localNames.contains(suggestedName)) { suggestedName = suggestedNameBase + QString::number(i); ++i; } BranchAddDialog branchAddDialog(localNames, true, this); branchAddDialog.setBranchName(suggestedName); branchAddDialog.setTrackedBranchName(isTag ? QString() : trackedBranch, !isLocal); if (branchAddDialog.exec() == QDialog::Accepted && m_model) { QModelIndex idx = m_model->addBranch(branchAddDialog.branchName(), branchAddDialog.track(), trackedIndex); if (!idx.isValid()) return; m_ui->branchView->selectionModel()->select(idx, QItemSelectionModel::Clear | QItemSelectionModel::Select | QItemSelectionModel::Current); m_ui->branchView->scrollTo(idx); if (QMessageBox::question(this, tr("Checkout"), tr("Checkout branch?"), QMessageBox::Yes | QMessageBox::No) == QMessageBox::Yes) checkout(); } } void BranchDialog::checkout() { if (!Core::DocumentManager::saveAllModifiedDocuments()) return; QModelIndex idx = selectedIndex(); const QString currentBranch = m_model->fullName(m_model->currentBranch()); const QString nextBranch = m_model->fullName(idx); const QString popMessageStart = QCoreApplication::applicationName() + QLatin1String(" ") + nextBranch + QLatin1String("-AutoStash "); BranchCheckoutDialog branchCheckoutDialog(this, currentBranch, nextBranch); GitClient *gitClient = GitPlugin::instance()->gitClient(); if (gitClient->gitStatus(m_repository, StatusMode(NoUntracked | NoSubmodules)) != GitClient::StatusChanged) branchCheckoutDialog.foundNoLocalChanges(); QList<Stash> stashes; gitClient->synchronousStashList(m_repository, &stashes); foreach (const Stash &stash, stashes) { if (stash.message.startsWith(popMessageStart)) { branchCheckoutDialog.foundStashForNextBranch(); break; } } if (!branchCheckoutDialog.hasLocalChanges() && !branchCheckoutDialog.hasStashForNextBranch()) { // No local changes and no Auto Stash - no need to open dialog m_model->checkoutBranch(idx); } else if (branchCheckoutDialog.exec() == QDialog::Accepted && m_model) { if (branchCheckoutDialog.makeStashOfCurrentBranch()) { if (gitClient->synchronousStash(m_repository, currentBranch + QLatin1String("-AutoStash")).isEmpty()) { return; } } else if (branchCheckoutDialog.moveLocalChangesToNextBranch()) { if (!gitClient->beginStashScope(m_repository, QLatin1String("Checkout"), NoPrompt)) return; } else if (branchCheckoutDialog.discardLocalChanges()) { if (!gitClient->synchronousReset(m_repository)) return; } m_model->checkoutBranch(idx); QString stashName; gitClient->synchronousStashList(m_repository, &stashes); foreach (const Stash &stash, stashes) { if (stash.message.startsWith(popMessageStart)) { stashName = stash.name; break; } } if (branchCheckoutDialog.moveLocalChangesToNextBranch()) gitClient->endStashScope(m_repository); else if (branchCheckoutDialog.popStashOfNextBranch()) gitClient->synchronousStashRestore(m_repository, stashName, true); } enableButtons(); } /* Prompt to delete a local branch and do so. */ void BranchDialog::remove() { QModelIndex selected = selectedIndex(); QTC_CHECK(selected != m_model->currentBranch()); // otherwise the button would not be enabled! QString branchName = m_model->fullName(selected); if (branchName.isEmpty()) return; const bool isTag = m_model->isTag(selected); const bool wasMerged = isTag ? true : m_model->branchIsMerged(selected); QString message; if (isTag) message = tr("Would you like to delete the tag \"%1\"?").arg(branchName); else if (wasMerged) message = tr("Would you like to delete the branch \"%1\"?").arg(branchName); else message = tr("Would you like to delete the <b>unmerged</b> branch \"%1\"?").arg(branchName); if (QMessageBox::question(this, isTag ? tr("Delete Tag") : tr("Delete Branch"), message, QMessageBox::Yes | QMessageBox::No, wasMerged ? QMessageBox::Yes : QMessageBox::No) == QMessageBox::Yes) { if (isTag) m_model->removeTag(selected); else m_model->removeBranch(selected); } } void BranchDialog::rename() { QModelIndex selected = selectedIndex(); QTC_CHECK(selected != m_model->currentBranch()); // otherwise the button would not be enabled! const bool isTag = m_model->isTag(selected); QTC_CHECK(m_model->isLocal(selected) || isTag); QString oldName = m_model->fullName(selected); QStringList localNames; if (!isTag) localNames = m_model->localBranchNames(); BranchAddDialog branchAddDialog(localNames, false, this); if (isTag) branchAddDialog.setWindowTitle(tr("Rename Tag")); branchAddDialog.setBranchName(oldName); branchAddDialog.setTrackedBranchName(QString(), false); branchAddDialog.exec(); if (branchAddDialog.result() == QDialog::Accepted && m_model) { if (branchAddDialog.branchName() == oldName) return; if (isTag) m_model->renameTag(oldName, branchAddDialog.branchName()); else m_model->renameBranch(oldName, branchAddDialog.branchName()); refresh(); } enableButtons(); } void BranchDialog::diff() { QString fullName = m_model->fullName(selectedIndex(), true); if (fullName.isEmpty()) return; // Do not pass working dir by reference since it might change GitPlugin::instance()->gitClient()->diffBranch(QString(m_repository), QStringList(), fullName); } void BranchDialog::log() { QString branchName = m_model->fullName(selectedIndex(), true); if (branchName.isEmpty()) return; // Do not pass working dir by reference since it might change GitPlugin::instance()->gitClient()->log(QString(m_repository), QString(), false, QStringList(branchName)); } void BranchDialog::reset() { QString currentName = m_model->fullName(m_model->currentBranch()); QString branchName = m_model->fullName(selectedIndex()); if (currentName.isEmpty() || branchName.isEmpty()) return; if (QMessageBox::question(this, tr("Git Reset"), tr("Hard reset branch \"%1\" to \"%2\"?") .arg(currentName).arg(branchName), QMessageBox::Yes, QMessageBox::No) == QMessageBox::Yes) { GitPlugin::instance()->gitClient()->reset(QString(m_repository), QLatin1String("--hard"), branchName); } } void BranchDialog::merge() { if (!Core::DocumentManager::saveAllModifiedDocuments()) return; QModelIndex idx = selectedIndex(); QTC_CHECK(idx != m_model->currentBranch()); // otherwise the button would not be enabled! const QString branch = m_model->fullName(idx, true); GitClient *client = GitPlugin::instance()->gitClient(); bool allowFastForward = true; if (client->isFastForwardMerge(m_repository, branch)) { QMenu popup; QAction *fastForward = popup.addAction(tr("Fast-Forward")); popup.addAction(tr("No Fast-Forward")); QAction *chosen = Utils::execMenuAtWidget(&popup, m_ui->mergeButton); if (!chosen) return; allowFastForward = (chosen == fastForward); } if (client->beginStashScope(m_repository, QLatin1String("merge"), AllowUnstashed)) client->synchronousMerge(m_repository, branch, allowFastForward); } void BranchDialog::rebase() { if (!Core::DocumentManager::saveAllModifiedDocuments()) return; QModelIndex idx = selectedIndex(); QTC_CHECK(idx != m_model->currentBranch()); // otherwise the button would not be enabled! const QString baseBranch = m_model->fullName(idx, true); GitClient *client = GitPlugin::instance()->gitClient(); if (client->beginStashScope(m_repository, QLatin1String("rebase"))) client->rebase(m_repository, baseBranch); } void BranchDialog::cherryPick() { if (!Core::DocumentManager::saveAllModifiedDocuments()) return; QModelIndex idx = selectedIndex(); QTC_CHECK(idx != m_model->currentBranch()); // otherwise the button would not be enabled! const QString branch = m_model->fullName(idx, true); GitPlugin::instance()->gitClient()->synchronousCherryPick(m_repository, branch); } void BranchDialog::setRemoteTracking() { m_model->setRemoteTracking(selectedIndex()); } QModelIndex BranchDialog::selectedIndex() { QModelIndexList selected = m_ui->branchView->selectionModel()->selectedIndexes(); if (selected.isEmpty()) return QModelIndex(); return selected.at(0); } } // namespace Internal } // namespace Git <commit_msg>Git: Remove redundant null validation<commit_after>/**************************************************************************** ** ** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies). ** Contact: http://www.qt-project.org/legal ** ** This file is part of Qt Creator. ** ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Digia. For licensing terms and ** conditions see http://qt.digia.com/licensing. For further information ** use the contact form at http://qt.digia.com/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Digia gives you certain additional ** rights. These rights are described in the Digia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ****************************************************************************/ #include "branchdialog.h" #include "branchadddialog.h" #include "branchcheckoutdialog.h" #include "branchmodel.h" #include "gitclient.h" #include "gitplugin.h" #include "gitutils.h" #include "ui_branchdialog.h" #include "stashdialog.h" // Label helpers #include <utils/qtcassert.h> #include <utils/execmenu.h> #include <vcsbase/vcsbaseoutputwindow.h> #include <coreplugin/documentmanager.h> #include <QAction> #include <QItemSelectionModel> #include <QMessageBox> #include <QList> #include <QMenu> #include <QDebug> namespace Git { namespace Internal { BranchDialog::BranchDialog(QWidget *parent) : QDialog(parent), m_ui(new Ui::BranchDialog), m_model(new BranchModel(GitPlugin::instance()->gitClient(), this)) { setModal(false); setWindowFlags(windowFlags() & ~Qt::WindowContextHelpButtonHint); setAttribute(Qt::WA_DeleteOnClose, true); // Do not update unnecessarily m_ui->setupUi(this); connect(m_ui->refreshButton, SIGNAL(clicked()), this, SLOT(refresh())); connect(m_ui->addButton, SIGNAL(clicked()), this, SLOT(add())); connect(m_ui->checkoutButton, SIGNAL(clicked()), this, SLOT(checkout())); connect(m_ui->removeButton, SIGNAL(clicked()), this, SLOT(remove())); connect(m_ui->renameButton, SIGNAL(clicked()), this, SLOT(rename())); connect(m_ui->diffButton, SIGNAL(clicked()), this, SLOT(diff())); connect(m_ui->logButton, SIGNAL(clicked()), this, SLOT(log())); connect(m_ui->resetButton, SIGNAL(clicked()), this, SLOT(reset())); connect(m_ui->mergeButton, SIGNAL(clicked()), this, SLOT(merge())); connect(m_ui->rebaseButton, SIGNAL(clicked()), this, SLOT(rebase())); connect(m_ui->cherryPickButton, SIGNAL(clicked()), this, SLOT(cherryPick())); connect(m_ui->trackButton, SIGNAL(clicked()), this, SLOT(setRemoteTracking())); m_ui->branchView->setModel(m_model); connect(m_ui->branchView->selectionModel(), SIGNAL(selectionChanged(QItemSelection,QItemSelection)), this, SLOT(enableButtons())); enableButtons(); } BranchDialog::~BranchDialog() { delete m_ui; } void BranchDialog::refresh(const QString &repository, bool force) { if (m_repository == repository && !force) return; m_repository = repository; m_ui->repositoryLabel->setText(StashDialog::msgRepositoryLabel(m_repository)); QString errorMessage; if (!m_model->refresh(m_repository, &errorMessage)) VcsBase::VcsBaseOutputWindow::instance()->appendError(errorMessage); m_ui->branchView->expandAll(); } void BranchDialog::refreshIfSame(const QString &repository) { if (m_repository == repository) refresh(); } void BranchDialog::enableButtons() { QModelIndex idx = selectedIndex(); QModelIndex currentBranch = m_model->currentBranch(); const bool hasSelection = idx.isValid(); const bool currentSelected = hasSelection && idx == currentBranch; const bool isLocal = m_model->isLocal(idx); const bool isLeaf = m_model->isLeaf(idx); const bool isTag = m_model->isTag(idx); const bool hasActions = hasSelection && isLeaf; const bool currentLocal = m_model->isLocal(currentBranch); m_ui->removeButton->setEnabled(hasActions && !currentSelected && (isLocal || isTag)); m_ui->renameButton->setEnabled(hasActions && (isLocal || isTag)); m_ui->logButton->setEnabled(hasActions); m_ui->diffButton->setEnabled(hasActions); m_ui->checkoutButton->setEnabled(hasActions && !currentSelected); m_ui->rebaseButton->setEnabled(hasActions && !currentSelected); m_ui->resetButton->setEnabled(hasActions && currentLocal && !currentSelected); m_ui->mergeButton->setEnabled(hasActions && !currentSelected); m_ui->cherryPickButton->setEnabled(hasActions && !currentSelected); m_ui->trackButton->setEnabled(hasActions && currentLocal && !currentSelected && !isTag); } void BranchDialog::refresh() { refresh(m_repository, true); } void BranchDialog::add() { QModelIndex trackedIndex = selectedIndex(); QString trackedBranch = m_model->fullName(trackedIndex); if (trackedBranch.isEmpty()) { trackedIndex = m_model->currentBranch(); trackedBranch = m_model->fullName(trackedIndex); } const bool isLocal = m_model->isLocal(trackedIndex); const bool isTag = m_model->isTag(trackedIndex); QStringList localNames = m_model->localBranchNames(); QString suggestedNameBase = trackedBranch.mid(trackedBranch.lastIndexOf(QLatin1Char('/')) + 1); QString suggestedName = suggestedNameBase; int i = 2; while (localNames.contains(suggestedName)) { suggestedName = suggestedNameBase + QString::number(i); ++i; } BranchAddDialog branchAddDialog(localNames, true, this); branchAddDialog.setBranchName(suggestedName); branchAddDialog.setTrackedBranchName(isTag ? QString() : trackedBranch, !isLocal); if (branchAddDialog.exec() == QDialog::Accepted) { QModelIndex idx = m_model->addBranch(branchAddDialog.branchName(), branchAddDialog.track(), trackedIndex); if (!idx.isValid()) return; m_ui->branchView->selectionModel()->select(idx, QItemSelectionModel::Clear | QItemSelectionModel::Select | QItemSelectionModel::Current); m_ui->branchView->scrollTo(idx); if (QMessageBox::question(this, tr("Checkout"), tr("Checkout branch?"), QMessageBox::Yes | QMessageBox::No) == QMessageBox::Yes) checkout(); } } void BranchDialog::checkout() { if (!Core::DocumentManager::saveAllModifiedDocuments()) return; QModelIndex idx = selectedIndex(); const QString currentBranch = m_model->fullName(m_model->currentBranch()); const QString nextBranch = m_model->fullName(idx); const QString popMessageStart = QCoreApplication::applicationName() + QLatin1String(" ") + nextBranch + QLatin1String("-AutoStash "); BranchCheckoutDialog branchCheckoutDialog(this, currentBranch, nextBranch); GitClient *gitClient = GitPlugin::instance()->gitClient(); if (gitClient->gitStatus(m_repository, StatusMode(NoUntracked | NoSubmodules)) != GitClient::StatusChanged) branchCheckoutDialog.foundNoLocalChanges(); QList<Stash> stashes; gitClient->synchronousStashList(m_repository, &stashes); foreach (const Stash &stash, stashes) { if (stash.message.startsWith(popMessageStart)) { branchCheckoutDialog.foundStashForNextBranch(); break; } } if (!branchCheckoutDialog.hasLocalChanges() && !branchCheckoutDialog.hasStashForNextBranch()) { // No local changes and no Auto Stash - no need to open dialog m_model->checkoutBranch(idx); } else if (branchCheckoutDialog.exec() == QDialog::Accepted && m_model) { if (branchCheckoutDialog.makeStashOfCurrentBranch()) { if (gitClient->synchronousStash(m_repository, currentBranch + QLatin1String("-AutoStash")).isEmpty()) { return; } } else if (branchCheckoutDialog.moveLocalChangesToNextBranch()) { if (!gitClient->beginStashScope(m_repository, QLatin1String("Checkout"), NoPrompt)) return; } else if (branchCheckoutDialog.discardLocalChanges()) { if (!gitClient->synchronousReset(m_repository)) return; } m_model->checkoutBranch(idx); QString stashName; gitClient->synchronousStashList(m_repository, &stashes); foreach (const Stash &stash, stashes) { if (stash.message.startsWith(popMessageStart)) { stashName = stash.name; break; } } if (branchCheckoutDialog.moveLocalChangesToNextBranch()) gitClient->endStashScope(m_repository); else if (branchCheckoutDialog.popStashOfNextBranch()) gitClient->synchronousStashRestore(m_repository, stashName, true); } enableButtons(); } /* Prompt to delete a local branch and do so. */ void BranchDialog::remove() { QModelIndex selected = selectedIndex(); QTC_CHECK(selected != m_model->currentBranch()); // otherwise the button would not be enabled! QString branchName = m_model->fullName(selected); if (branchName.isEmpty()) return; const bool isTag = m_model->isTag(selected); const bool wasMerged = isTag ? true : m_model->branchIsMerged(selected); QString message; if (isTag) message = tr("Would you like to delete the tag \"%1\"?").arg(branchName); else if (wasMerged) message = tr("Would you like to delete the branch \"%1\"?").arg(branchName); else message = tr("Would you like to delete the <b>unmerged</b> branch \"%1\"?").arg(branchName); if (QMessageBox::question(this, isTag ? tr("Delete Tag") : tr("Delete Branch"), message, QMessageBox::Yes | QMessageBox::No, wasMerged ? QMessageBox::Yes : QMessageBox::No) == QMessageBox::Yes) { if (isTag) m_model->removeTag(selected); else m_model->removeBranch(selected); } } void BranchDialog::rename() { QModelIndex selected = selectedIndex(); QTC_CHECK(selected != m_model->currentBranch()); // otherwise the button would not be enabled! const bool isTag = m_model->isTag(selected); QTC_CHECK(m_model->isLocal(selected) || isTag); QString oldName = m_model->fullName(selected); QStringList localNames; if (!isTag) localNames = m_model->localBranchNames(); BranchAddDialog branchAddDialog(localNames, false, this); if (isTag) branchAddDialog.setWindowTitle(tr("Rename Tag")); branchAddDialog.setBranchName(oldName); branchAddDialog.setTrackedBranchName(QString(), false); branchAddDialog.exec(); if (branchAddDialog.result() == QDialog::Accepted && m_model) { if (branchAddDialog.branchName() == oldName) return; if (isTag) m_model->renameTag(oldName, branchAddDialog.branchName()); else m_model->renameBranch(oldName, branchAddDialog.branchName()); refresh(); } enableButtons(); } void BranchDialog::diff() { QString fullName = m_model->fullName(selectedIndex(), true); if (fullName.isEmpty()) return; // Do not pass working dir by reference since it might change GitPlugin::instance()->gitClient()->diffBranch(QString(m_repository), QStringList(), fullName); } void BranchDialog::log() { QString branchName = m_model->fullName(selectedIndex(), true); if (branchName.isEmpty()) return; // Do not pass working dir by reference since it might change GitPlugin::instance()->gitClient()->log(QString(m_repository), QString(), false, QStringList(branchName)); } void BranchDialog::reset() { QString currentName = m_model->fullName(m_model->currentBranch()); QString branchName = m_model->fullName(selectedIndex()); if (currentName.isEmpty() || branchName.isEmpty()) return; if (QMessageBox::question(this, tr("Git Reset"), tr("Hard reset branch \"%1\" to \"%2\"?") .arg(currentName).arg(branchName), QMessageBox::Yes, QMessageBox::No) == QMessageBox::Yes) { GitPlugin::instance()->gitClient()->reset(QString(m_repository), QLatin1String("--hard"), branchName); } } void BranchDialog::merge() { if (!Core::DocumentManager::saveAllModifiedDocuments()) return; QModelIndex idx = selectedIndex(); QTC_CHECK(idx != m_model->currentBranch()); // otherwise the button would not be enabled! const QString branch = m_model->fullName(idx, true); GitClient *client = GitPlugin::instance()->gitClient(); bool allowFastForward = true; if (client->isFastForwardMerge(m_repository, branch)) { QMenu popup; QAction *fastForward = popup.addAction(tr("Fast-Forward")); popup.addAction(tr("No Fast-Forward")); QAction *chosen = Utils::execMenuAtWidget(&popup, m_ui->mergeButton); if (!chosen) return; allowFastForward = (chosen == fastForward); } if (client->beginStashScope(m_repository, QLatin1String("merge"), AllowUnstashed)) client->synchronousMerge(m_repository, branch, allowFastForward); } void BranchDialog::rebase() { if (!Core::DocumentManager::saveAllModifiedDocuments()) return; QModelIndex idx = selectedIndex(); QTC_CHECK(idx != m_model->currentBranch()); // otherwise the button would not be enabled! const QString baseBranch = m_model->fullName(idx, true); GitClient *client = GitPlugin::instance()->gitClient(); if (client->beginStashScope(m_repository, QLatin1String("rebase"))) client->rebase(m_repository, baseBranch); } void BranchDialog::cherryPick() { if (!Core::DocumentManager::saveAllModifiedDocuments()) return; QModelIndex idx = selectedIndex(); QTC_CHECK(idx != m_model->currentBranch()); // otherwise the button would not be enabled! const QString branch = m_model->fullName(idx, true); GitPlugin::instance()->gitClient()->synchronousCherryPick(m_repository, branch); } void BranchDialog::setRemoteTracking() { m_model->setRemoteTracking(selectedIndex()); } QModelIndex BranchDialog::selectedIndex() { QModelIndexList selected = m_ui->branchView->selectionModel()->selectedIndexes(); if (selected.isEmpty()) return QModelIndex(); return selected.at(0); } } // namespace Internal } // namespace Git <|endoftext|>
<commit_before>#ifndef STAN_MATH_PRIM_META_COMPILER_ATTRIBUTES_HPP #define STAN_MATH_PRIM_META_COMPILER_ATTRIBUTES_HPP #ifdef __GNUC__ #define likely(x) __builtin_expect(!!(x), 1) #define unlikely(x) __builtin_expect(!!(x), 0) #ifdef __has_attribute #if __has_attribute (noinline) && __has_attribute (cold) #define STAN_COLD_PATH __attribute__((noinline, cold)) #endif #endif #else #define likely(x) (x) #define unlikely(x) (x) #define STAN_COLD_PATH #endif #ifndef STAN_NO_RANGE_AND_SIZE_CHECK #ifdef STAN_NDEBUG #define STAN_NO_RANGE_AND_SIZE_CHECK return #endif #else #define STAN_NO_RANGE_AND_SIZE_CHECK #endif #endif <commit_msg>update docs<commit_after>#ifndef STAN_MATH_PRIM_META_COMPILER_ATTRIBUTES_HPP #define STAN_MATH_PRIM_META_COMPILER_ATTRIBUTES_HPP #ifdef __GNUC__ #define likely(x) __builtin_expect(!!(x), 1) #define unlikely(x) __builtin_expect(!!(x), 0) #ifdef __has_attribute #if __has_attribute (noinline) && __has_attribute (cold) /** * Functions tagged with this attribute are not inlined and moved * to a cold branch to tell the CPU to not attempt to pre-fetch * the associated function. */ #define STAN_COLD_PATH __attribute__((noinline, cold)) #endif #endif #else #define likely(x) (x) #define unlikely(x) (x) #define STAN_COLD_PATH #endif /** * Turns all range and size checks into no-ops */ #ifndef STAN_NO_RANGE_AND_SIZE_CHECK #ifdef STAN_NDEBUG #define STAN_NO_RANGE_AND_SIZE_CHECK return #endif #else #define STAN_NO_RANGE_AND_SIZE_CHECK #endif #endif <|endoftext|>
<commit_before>// bslstl_function_cpp03.t.cpp -*-C++-*- // Automatically generated file. **DO NOT EDIT** //============================================================================= // TEST PLAN //----------------------------------------------------------------------------- // This component is the C++03 translation of a C++11 component, generated by // the 'sim_cpp11_features.pl' program. If the original test driver contains // any specially delimited regions of C++11 code, then this generated file // contains the C++03 equivalent, i.e., with variadic templates expanded and // rvalue-references replaced by 'bslmf::MovableRef' objects. The test driver // code in this file is designed to be '#include'd into the original test // driver when compiling with a C++03 compiler. If there are no specially // delimited regions of C++11 code, then this test driver is a minimal 'main' // program that tests nothing and is not '#include'd in the original. // // Generated on Thu Oct 21 10:11:37 2021 // Command line: sim_cpp11_features.pl bslstl_function.t.cpp // Expanded test driver only when compiling bslstl_function.cpp #ifdef COMPILING_BSLSTL_FUNCTION_T_CPP // No C++03 Expansion #else // if ! defined(COMPILING_BSLSTL_FUNCTION_T_CPP) // Trivial program when not compiling bslstl_function.t.cpp int main() { return -1; } #endif // defined(COMPILING_BSLSTL_FUNCTION_T_CPP) // ---------------------------------------------------------------------------- // Copyright 2021 Bloomberg Finance L.P. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ----------------------------- END-OF-FILE ---------------------------------- <commit_msg>Remove function _cpp03.t.cpp<commit_after><|endoftext|>
<commit_before>/**************************************************************************** ** ** Copyright (C) 2012 - 2013 Jolla Ltd. ** Contact: http://jolla.com/ ** ** This file is part of Qt Creator. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** Other Usage ** ** Alternatively, this file may be used in accordance with the terms and ** conditions contained in a signed written agreement between you and Digia. ** ****************************************************************************/ #include "merqtversion.h" #include "merconstants.h" #include "mersdkmanager.h" #include "mervirtualboxmanager.h" #include <utils/environment.h> #include <qtsupport/qtkitinformation.h> #include <projectexplorer/projectexplorerconstants.h> #include <projectexplorer/toolchain.h> #include <utils/qtcassert.h> #include <QCoreApplication> #include <QFileInfo> #include <QDir> using namespace ProjectExplorer; namespace Mer { namespace Internal { MerQtVersion::MerQtVersion() : QtSupport::BaseQtVersion() { } MerQtVersion::MerQtVersion(const Utils::FileName &path, bool isAutodetected, const QString &autodetectionSource) : QtSupport::BaseQtVersion(path, isAutodetected, autodetectionSource) { } MerQtVersion::~MerQtVersion() { } void MerQtVersion::setVirtualMachineName(const QString &name) { m_vmName = name; } QString MerQtVersion::virtualMachineName() const { return m_vmName; } void MerQtVersion::setTargetName(const QString &name) { m_targetName = name; } QString MerQtVersion::targetName() const { return m_targetName; } QString MerQtVersion::type() const { return QLatin1String(Constants::MER_QT); } MerQtVersion *MerQtVersion::clone() const { return new MerQtVersion(*this); } QList<Abi> MerQtVersion::detectQtAbis() const { return qtAbisFromLibrary(qtCorePath(versionInfo(), qtVersionString())); } QString MerQtVersion::description() const { return QCoreApplication::translate("QtVersion", "Mer ", "Qt Version is meant for Mer"); } bool MerQtVersion::supportsShadowBuilds() const { return false; } QString MerQtVersion::platformName() const { return QLatin1String(Constants::MER_PLATFORM); } QString MerQtVersion::platformDisplayName() const { return QLatin1String(Constants::MER_PLATFORM_TR); } QVariantMap MerQtVersion::toMap() const { QVariantMap data = BaseQtVersion::toMap(); data.insert(QLatin1String(Constants::VIRTUAL_MACHINE), m_vmName); data.insert(QLatin1String(Constants::SB2_TARGET_NAME), m_targetName); return data; } void MerQtVersion::fromMap(const QVariantMap &data) { BaseQtVersion::fromMap(data); m_vmName = data.value(QLatin1String(Constants::VIRTUAL_MACHINE)).toString(); m_targetName = data.value(QLatin1String(Constants::SB2_TARGET_NAME)).toString(); } QList<Task> MerQtVersion::validateKit(const Kit *kit) { QList<Task> result = BaseQtVersion::validateKit(kit); if (!result.isEmpty()) return result; BaseQtVersion *version = QtSupport::QtKitInformation::qtVersion(kit); QTC_ASSERT(version == this, return result); ToolChain *tc = ToolChainKitInformation::toolChain(kit); if (!tc) { const QString message = QCoreApplication::translate("QtVersion", "No available toolchains found to build " "for Qt version '%1'.").arg(version->displayName()); result << Task(Task::Error, message, Utils::FileName(), -1, Core::Id(ProjectExplorer::Constants::TASK_CATEGORY_BUILDSYSTEM)); } else if (!MerSdkManager::validateKit(kit)) { const QString message = QCoreApplication::translate("QtVersion", "This Qt version '%1' does not match Mer SDK or toolchain."). arg(version->displayName()); result << Task(Task::Error, message, Utils::FileName(), -1, Core::Id(ProjectExplorer::Constants::TASK_CATEGORY_BUILDSYSTEM)); } return result; } QList<ProjectExplorer::Task> MerQtVersion::reportIssuesImpl(const QString &proFile, const QString &buildDir) const { QList<ProjectExplorer::Task> results; // Exctracting the VM name out of the qmake wrapper path const QString merSDKVMName = qmakeCommand().parentDir().parentDir().toFileInfo().baseName(); const VirtualMachineInfo vmInfo = MerVirtualBoxManager::fetchVirtualMachineInfo(merSDKVMName); if (vmInfo.sharedHome.isEmpty()) return results; const QString proFileClean = QDir::cleanPath(proFile); const QString sharedHomeClean = QDir::cleanPath(vmInfo.sharedHome); if (!proFileClean.startsWith(sharedHomeClean)) { ProjectExplorer::Task task(ProjectExplorer::Task::Error, QCoreApplication::translate("QtVersion", "Project is outside of shared " "home '%1'") .arg(QDir::toNativeSeparators(vmInfo.sharedHome)), Utils::FileName(), -1, Core::Id()); results.append(task); } results.append(BaseQtVersion::reportIssuesImpl(proFile, buildDir)); return results; } Core::FeatureSet MerQtVersion::availableFeatures() const { Core::FeatureSet features = BaseQtVersion::availableFeatures(); features |= Core::FeatureSet(Constants::SAILFISHOS_FEATURE); return features; } } // namespace Interal } // namespace Mer <commit_msg>Jolla: Support shadow build<commit_after>/**************************************************************************** ** ** Copyright (C) 2012 - 2013 Jolla Ltd. ** Contact: http://jolla.com/ ** ** This file is part of Qt Creator. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** Other Usage ** ** Alternatively, this file may be used in accordance with the terms and ** conditions contained in a signed written agreement between you and Digia. ** ****************************************************************************/ #include "merqtversion.h" #include "merconstants.h" #include "mersdkmanager.h" #include "mervirtualboxmanager.h" #include <utils/environment.h> #include <qtsupport/qtkitinformation.h> #include <projectexplorer/projectexplorerconstants.h> #include <projectexplorer/toolchain.h> #include <utils/qtcassert.h> #include <QCoreApplication> #include <QFileInfo> #include <QDir> using namespace ProjectExplorer; namespace Mer { namespace Internal { MerQtVersion::MerQtVersion() : QtSupport::BaseQtVersion() { } MerQtVersion::MerQtVersion(const Utils::FileName &path, bool isAutodetected, const QString &autodetectionSource) : QtSupport::BaseQtVersion(path, isAutodetected, autodetectionSource) { } MerQtVersion::~MerQtVersion() { } void MerQtVersion::setVirtualMachineName(const QString &name) { m_vmName = name; } QString MerQtVersion::virtualMachineName() const { return m_vmName; } void MerQtVersion::setTargetName(const QString &name) { m_targetName = name; } QString MerQtVersion::targetName() const { return m_targetName; } QString MerQtVersion::type() const { return QLatin1String(Constants::MER_QT); } MerQtVersion *MerQtVersion::clone() const { return new MerQtVersion(*this); } QList<Abi> MerQtVersion::detectQtAbis() const { return qtAbisFromLibrary(qtCorePath(versionInfo(), qtVersionString())); } QString MerQtVersion::description() const { return QCoreApplication::translate("QtVersion", "Mer ", "Qt Version is meant for Mer"); } bool MerQtVersion::supportsShadowBuilds() const { return true; } QString MerQtVersion::platformName() const { return QLatin1String(Constants::MER_PLATFORM); } QString MerQtVersion::platformDisplayName() const { return QLatin1String(Constants::MER_PLATFORM_TR); } QVariantMap MerQtVersion::toMap() const { QVariantMap data = BaseQtVersion::toMap(); data.insert(QLatin1String(Constants::VIRTUAL_MACHINE), m_vmName); data.insert(QLatin1String(Constants::SB2_TARGET_NAME), m_targetName); return data; } void MerQtVersion::fromMap(const QVariantMap &data) { BaseQtVersion::fromMap(data); m_vmName = data.value(QLatin1String(Constants::VIRTUAL_MACHINE)).toString(); m_targetName = data.value(QLatin1String(Constants::SB2_TARGET_NAME)).toString(); } QList<Task> MerQtVersion::validateKit(const Kit *kit) { QList<Task> result = BaseQtVersion::validateKit(kit); if (!result.isEmpty()) return result; BaseQtVersion *version = QtSupport::QtKitInformation::qtVersion(kit); QTC_ASSERT(version == this, return result); ToolChain *tc = ToolChainKitInformation::toolChain(kit); if (!tc) { const QString message = QCoreApplication::translate("QtVersion", "No available toolchains found to build " "for Qt version '%1'.").arg(version->displayName()); result << Task(Task::Error, message, Utils::FileName(), -1, Core::Id(ProjectExplorer::Constants::TASK_CATEGORY_BUILDSYSTEM)); } else if (!MerSdkManager::validateKit(kit)) { const QString message = QCoreApplication::translate("QtVersion", "This Qt version '%1' does not match Mer SDK or toolchain."). arg(version->displayName()); result << Task(Task::Error, message, Utils::FileName(), -1, Core::Id(ProjectExplorer::Constants::TASK_CATEGORY_BUILDSYSTEM)); } return result; } QList<ProjectExplorer::Task> MerQtVersion::reportIssuesImpl(const QString &proFile, const QString &buildDir) const { QList<ProjectExplorer::Task> results; // Exctracting the VM name out of the qmake wrapper path const QString merSDKVMName = qmakeCommand().parentDir().parentDir().toFileInfo().baseName(); const VirtualMachineInfo vmInfo = MerVirtualBoxManager::fetchVirtualMachineInfo(merSDKVMName); if (vmInfo.sharedHome.isEmpty()) return results; const QString proFileClean = QDir::cleanPath(proFile); const QString sharedHomeClean = QDir::cleanPath(vmInfo.sharedHome); if (!proFileClean.startsWith(sharedHomeClean)) { ProjectExplorer::Task task(ProjectExplorer::Task::Error, QCoreApplication::translate("QtVersion", "Project is outside of shared " "home '%1'") .arg(QDir::toNativeSeparators(vmInfo.sharedHome)), Utils::FileName(), -1, Core::Id()); results.append(task); } results.append(BaseQtVersion::reportIssuesImpl(proFile, buildDir)); return results; } Core::FeatureSet MerQtVersion::availableFeatures() const { Core::FeatureSet features = BaseQtVersion::availableFeatures(); features |= Core::FeatureSet(Constants::SAILFISHOS_FEATURE); return features; } } // namespace Interal } // namespace Mer <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: cupsmgr.hxx,v $ * * $Revision: 1.8 $ * * last change: $Author: hr $ $Date: 2006-06-19 10:22:34 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef _PSPRINT_CUPSMGR_HXX_ #define _PSPRINT_CUPSMGR_HXX_ #include <psprint/printerinfomanager.hxx> #include <osl/module.h> #include <osl/thread.h> #include <osl/mutex.hxx> namespace psp { class CUPSWrapper; class PPDParser; struct FPtrHash { size_t operator()(const FILE* pPtr) const { return (size_t)pPtr; } }; class CUPSManager : public PrinterInfoManager { CUPSWrapper* m_pCUPSWrapper; std::hash_map< FILE*, rtl::OString, FPtrHash > m_aSpoolFiles; int m_nDests; void* m_pDests; bool m_bNewDests; std::hash_map< rtl::OUString, int, rtl::OUStringHash > m_aCUPSDestMap; std::hash_map< rtl::OUString, PPDContext, rtl::OUStringHash > m_aDefaultContexts; rtl::OString m_aUser; // this is a security risk, but the CUPS API demands // to deliver a pointer to a static buffer containing // the password, so this cannot be helped rtl::OString m_aPassword; osl::Mutex m_aCUPSMutex; oslThread m_aDestThread; CUPSManager( CUPSWrapper* ); virtual ~CUPSManager(); virtual void initialize(); void getOptionsFromDocumentSetup( const JobData& rJob, int& rNumOptions, void** rOptions ) const; void runDests(); public: // public for stub static void runDestThread(void* pMgr); static CUPSManager* tryLoadCUPS(); const PPDParser* createCUPSParser( const rtl::OUString& rPrinter ); // wraps cupsGetPPD, so unlink after use ! const char* authenticateUser( const char* ); virtual FILE* startSpool( const rtl::OUString& rPrinterName ); virtual int endSpool( const rtl::OUString& rPrinterName, const rtl::OUString& rJobTitle, FILE* pFile, const JobData& rDocumentJobData ); virtual void setupJobContextData( JobData& rData ); // changes the info about a named printer virtual void changePrinterInfo( const ::rtl::OUString& rPrinter, const PrinterInfo& rNewInfo ); // check if the printer configuration has changed virtual bool checkPrintersChanged(); // members for administration (->padmin) // disable for CUPS virtual bool addPrinter( const rtl::OUString& rPrinterName, const ::rtl::OUString& rDriverName ); virtual bool removePrinter( const rtl::OUString& rPrinterName, bool bCheckOnly = false ); virtual bool writePrinterConfig(); virtual bool setDefaultPrinter( const rtl::OUString& rPrinterName ); virtual bool addOrRemovePossible() const; }; } // namespace psp #endif <commit_msg>INTEGRATION: CWS vcl60 (1.7.62); FILE MERGED 2006/06/27 09:12:31 pl 1.7.62.2: RESYNC: (1.7-1.8); FILE MERGED 2006/06/20 11:20:17 pl 1.7.62.1: #i62663# method to wait on asynchronous printer detection<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: cupsmgr.hxx,v $ * * $Revision: 1.9 $ * * last change: $Author: obo $ $Date: 2006-07-10 16:29:13 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef _PSPRINT_CUPSMGR_HXX_ #define _PSPRINT_CUPSMGR_HXX_ #include <psprint/printerinfomanager.hxx> #include <osl/module.h> #include <osl/thread.h> #include <osl/mutex.hxx> namespace psp { class CUPSWrapper; class PPDParser; struct FPtrHash { size_t operator()(const FILE* pPtr) const { return (size_t)pPtr; } }; class CUPSManager : public PrinterInfoManager { CUPSWrapper* m_pCUPSWrapper; std::hash_map< FILE*, rtl::OString, FPtrHash > m_aSpoolFiles; int m_nDests; void* m_pDests; bool m_bNewDests; std::hash_map< rtl::OUString, int, rtl::OUStringHash > m_aCUPSDestMap; std::hash_map< rtl::OUString, PPDContext, rtl::OUStringHash > m_aDefaultContexts; rtl::OString m_aUser; // this is a security risk, but the CUPS API demands // to deliver a pointer to a static buffer containing // the password, so this cannot be helped rtl::OString m_aPassword; osl::Mutex m_aCUPSMutex; oslThread m_aDestThread; CUPSManager( CUPSWrapper* ); virtual ~CUPSManager(); virtual void initialize(); void getOptionsFromDocumentSetup( const JobData& rJob, int& rNumOptions, void** rOptions ) const; void runDests(); public: // public for stub static void runDestThread(void* pMgr); static CUPSManager* tryLoadCUPS(); const PPDParser* createCUPSParser( const rtl::OUString& rPrinter ); // wraps cupsGetPPD, so unlink after use ! const char* authenticateUser( const char* ); virtual FILE* startSpool( const rtl::OUString& rPrinterName ); virtual int endSpool( const rtl::OUString& rPrinterName, const rtl::OUString& rJobTitle, FILE* pFile, const JobData& rDocumentJobData ); virtual void setupJobContextData( JobData& rData ); // changes the info about a named printer virtual void changePrinterInfo( const ::rtl::OUString& rPrinter, const PrinterInfo& rNewInfo ); // check if the printer configuration has changed virtual bool checkPrintersChanged( bool bWait ); // members for administration (->padmin) // disable for CUPS virtual bool addPrinter( const rtl::OUString& rPrinterName, const ::rtl::OUString& rDriverName ); virtual bool removePrinter( const rtl::OUString& rPrinterName, bool bCheckOnly = false ); virtual bool writePrinterConfig(); virtual bool setDefaultPrinter( const rtl::OUString& rPrinterName ); virtual bool addOrRemovePossible() const; }; } // namespace psp #endif <|endoftext|>
<commit_before>#include "libnanocv/nanocv.h" #include "libnanocv/tasks/task_synthetic_shapes.h" #include "libnanocv/util/thread.h" #include "libnanocv/util/measure.hpp" #include "libnanocv/util/tabulator.h" #include "libnanocv/trainers/batch.h" #include "libnanocv/trainers/minibatch.h" #include "libnanocv/trainers/stochastic.h" using namespace ncv; template < typename ttrainer > void test_optimizer(const task_t& task, ttrainer trainer, const string_t& name, tabulator_t& table) { const size_t cmd_trials = 16; stats_t<scalar_t> tvalues; stats_t<scalar_t> vvalues; stats_t<scalar_t> terrors; stats_t<scalar_t> verrors; const size_t usec = ncv::measure_robustly_usec([&] () { sampler_t tsampler(task); tsampler.setup(sampler_t::atype::annotated); sampler_t vsampler(task); tsampler.split(80, vsampler); const trainer_result_t result = trainer(tsampler, vsampler); tvalues(result.m_opt_state.m_tvalue); vvalues(result.m_opt_state.m_vvalue); terrors(result.m_opt_state.m_terror_avg); verrors(result.m_opt_state.m_verror_avg); log_info() << "done (" << name << ") ..."; }, cmd_trials); table.append(name) << tvalues.avg() << terrors.avg() << vvalues.avg() << verrors.avg() << (usec / 1000); } void test_optimizers( const task_t& task, const model_t& model, const loss_t& loss, const string_t& criterion, const string_t& config_name) { const size_t cmd_iterations = 32; const size_t cmd_epochs = cmd_iterations; const scalar_t cmd_epsilon = 1e-4; const bool verbose = false; // batch optimizers const auto batch_optimizers = { batch_optimizer::GD, batch_optimizer::CGD, batch_optimizer::LBFGS }; // minibatch optimizers const auto minibatch_optimizers = { batch_optimizer::GD, batch_optimizer::CGD, batch_optimizer::LBFGS }; // stochastic optimizers const auto stochastic_optimizers = { stochastic_optimizer::SG, stochastic_optimizer::SGA, stochastic_optimizer::SIA, stochastic_optimizer::AG, stochastic_optimizer::ADAGRAD, stochastic_optimizer::ADADELTA }; // run optimizers and collect results tabulator_t table("optimizer\\"); table.header() << "train loss" << "train error" << "valid loss" << "valid error" << "time [msec]"; for (batch_optimizer optimizer : batch_optimizers) { test_optimizer(task, [&] (const sampler_t& tsampler, const sampler_t& vsampler) { return ncv::batch_train( model, task, tsampler, vsampler, ncv::n_threads(), loss, criterion, optimizer, cmd_iterations, cmd_epsilon, verbose); }, "batch [" + text::to_string(optimizer) + "]", table); } for (batch_optimizer optimizer : minibatch_optimizers) { test_optimizer(task, [&] (const sampler_t& tsampler, const sampler_t& vsampler) { return ncv::minibatch_train( model, task, tsampler, vsampler, ncv::n_threads(), loss, criterion, optimizer, cmd_epochs, cmd_epsilon, verbose); }, "minibatch [" + text::to_string(optimizer) + "]", table); } for (stochastic_optimizer optimizer : stochastic_optimizers) { test_optimizer(task, [&] (const sampler_t& tsampler, const sampler_t& vsampler) { return ncv::stochastic_train( model, task, tsampler, vsampler, ncv::n_threads(), loss, criterion, optimizer, cmd_epochs, verbose); }, "stochastic [" + text::to_string(optimizer) + "]", table); } table.print(std::cout); } int main(int argc, char *argv[]) { ncv::init(); const size_t cmd_samples = 8 * 1024; const size_t cmd_rows = 16; const size_t cmd_cols = 16; const size_t cmd_outputs = 4; synthetic_shapes_task_t task( "rows=" + text::to_string(cmd_rows) + "," + "cols=" + text::to_string(cmd_cols) + "," + "color=luma" + "," + "dims=" + text::to_string(cmd_outputs) + "," + "size=" + text::to_string(cmd_samples)); task.load(""); task.describe(); const string_t lmodel0; const string_t lmodel1 = lmodel0 + "linear:dims=32;act-snorm;"; const string_t lmodel2 = lmodel1 + "linear:dims=32;act-snorm;"; const string_t lmodel3 = lmodel2 + "linear:dims=32;act-snorm;"; string_t cmodel; cmodel = cmodel + "conv:dims=8,rows=5,cols=5;pool-max;act-snorm;"; cmodel = cmodel + "conv:dims=8,rows=3,cols=3;act-snorm;"; const string_t outlayer = "linear:dims=" + text::to_string(cmd_outputs) + ";"; strings_t cmd_networks = { lmodel0 + outlayer, lmodel1 + outlayer, lmodel2 + outlayer, lmodel3 + outlayer, cmodel + outlayer }; const strings_t cmd_losses = { "classnll", "logistic" }; //loss_manager_t::instance().ids(); const strings_t cmd_criteria = criterion_manager_t::instance().ids(); // vary the model for (const string_t& cmd_network : cmd_networks) { log_info() << "<<< running network [" << cmd_network << "] ..."; const rmodel_t model = model_manager_t::instance().get("forward-network", cmd_network); assert(model); model->resize(task, true); // vary the loss for (const string_t& cmd_loss : cmd_losses) { log_info() << "<<< running loss [" << cmd_loss << "] ..."; const rloss_t loss = loss_manager_t::instance().get(cmd_loss); assert(loss); // vary the criteria for (const string_t& cmd_criterion : cmd_criteria) { log_info() << "<<< running criterion [" << cmd_criterion << "] ..."; test_optimizers(task, *model, *loss, cmd_criterion, "loss [" + cmd_loss + "], criterion [" + cmd_criterion + "]"); } } log_info(); } // OK log_info() << done; return EXIT_SUCCESS; } <commit_msg>comment<commit_after>#include "libnanocv/nanocv.h" #include "libnanocv/tasks/task_synthetic_shapes.h" #include "libnanocv/util/thread.h" #include "libnanocv/util/measure.hpp" #include "libnanocv/util/tabulator.h" #include "libnanocv/trainers/batch.h" #include "libnanocv/trainers/minibatch.h" #include "libnanocv/trainers/stochastic.h" using namespace ncv; template < typename ttrainer > void test_optimizer(const task_t& task, ttrainer trainer, const string_t& name, tabulator_t& table) { const size_t cmd_trials = 16; stats_t<scalar_t> tvalues; stats_t<scalar_t> vvalues; stats_t<scalar_t> terrors; stats_t<scalar_t> verrors; const size_t usec = ncv::measure_robustly_usec([&] () { // const timer_t timer; sampler_t tsampler(task); tsampler.setup(sampler_t::atype::annotated); sampler_t vsampler(task); tsampler.split(80, vsampler); const trainer_result_t result = trainer(tsampler, vsampler); tvalues(result.m_opt_state.m_tvalue); vvalues(result.m_opt_state.m_vvalue); terrors(result.m_opt_state.m_terror_avg); verrors(result.m_opt_state.m_verror_avg); // log_info() << "done (" << name << ") in " << timer.elapsed() << " ..."; }, cmd_trials); table.append(name) << tvalues.avg() << terrors.avg() << vvalues.avg() << verrors.avg() << (usec / 1000); } void test_optimizers( const task_t& task, const model_t& model, const loss_t& loss, const string_t& criterion, const string_t& config_name) { const size_t cmd_iterations = 32; const size_t cmd_epochs = cmd_iterations; const scalar_t cmd_epsilon = 1e-4; const bool verbose = false; // batch optimizers const auto batch_optimizers = { batch_optimizer::GD, batch_optimizer::CGD, batch_optimizer::LBFGS }; // minibatch optimizers const auto minibatch_optimizers = { batch_optimizer::GD, batch_optimizer::CGD, batch_optimizer::LBFGS }; // stochastic optimizers const auto stochastic_optimizers = { stochastic_optimizer::SG, stochastic_optimizer::SGA, stochastic_optimizer::SIA, stochastic_optimizer::AG, stochastic_optimizer::ADAGRAD, stochastic_optimizer::ADADELTA }; // run optimizers and collect results tabulator_t table("optimizer\\"); table.header() << "train loss" << "train error" << "valid loss" << "valid error" << "time [msec]"; for (batch_optimizer optimizer : batch_optimizers) { test_optimizer(task, [&] (const sampler_t& tsampler, const sampler_t& vsampler) { return ncv::batch_train( model, task, tsampler, vsampler, ncv::n_threads(), loss, criterion, optimizer, cmd_iterations, cmd_epsilon, verbose); }, "batch [" + text::to_string(optimizer) + "]", table); } for (batch_optimizer optimizer : minibatch_optimizers) { test_optimizer(task, [&] (const sampler_t& tsampler, const sampler_t& vsampler) { return ncv::minibatch_train( model, task, tsampler, vsampler, ncv::n_threads(), loss, criterion, optimizer, cmd_epochs, cmd_epsilon, verbose); }, "minibatch [" + text::to_string(optimizer) + "]", table); } for (stochastic_optimizer optimizer : stochastic_optimizers) { test_optimizer(task, [&] (const sampler_t& tsampler, const sampler_t& vsampler) { return ncv::stochastic_train( model, task, tsampler, vsampler, ncv::n_threads(), loss, criterion, optimizer, cmd_epochs, verbose); }, "stochastic [" + text::to_string(optimizer) + "]", table); } table.print(std::cout); } int main(int argc, char *argv[]) { ncv::init(); const size_t cmd_samples = 8 * 1024; const size_t cmd_rows = 16; const size_t cmd_cols = 16; const size_t cmd_outputs = 4; synthetic_shapes_task_t task( "rows=" + text::to_string(cmd_rows) + "," + "cols=" + text::to_string(cmd_cols) + "," + "color=luma" + "," + "dims=" + text::to_string(cmd_outputs) + "," + "size=" + text::to_string(cmd_samples)); task.load(""); task.describe(); const string_t lmodel0; const string_t lmodel1 = lmodel0 + "linear:dims=32;act-snorm;"; const string_t lmodel2 = lmodel1 + "linear:dims=32;act-snorm;"; const string_t lmodel3 = lmodel2 + "linear:dims=32;act-snorm;"; string_t cmodel; cmodel = cmodel + "conv:dims=8,rows=5,cols=5;pool-max;act-snorm;"; cmodel = cmodel + "conv:dims=8,rows=3,cols=3;act-snorm;"; const string_t outlayer = "linear:dims=" + text::to_string(cmd_outputs) + ";"; strings_t cmd_networks = { lmodel0 + outlayer, lmodel1 + outlayer, lmodel2 + outlayer, lmodel3 + outlayer, cmodel + outlayer }; const strings_t cmd_losses = { "classnll", "logistic" }; //loss_manager_t::instance().ids(); const strings_t cmd_criteria = criterion_manager_t::instance().ids(); // vary the model for (const string_t& cmd_network : cmd_networks) { log_info() << "<<< running network [" << cmd_network << "] ..."; const rmodel_t model = model_manager_t::instance().get("forward-network", cmd_network); assert(model); model->resize(task, true); // vary the loss for (const string_t& cmd_loss : cmd_losses) { log_info() << "<<< running loss [" << cmd_loss << "] ..."; const rloss_t loss = loss_manager_t::instance().get(cmd_loss); assert(loss); // vary the criteria for (const string_t& cmd_criterion : cmd_criteria) { log_info() << "<<< running criterion [" << cmd_criterion << "] ..."; test_optimizers(task, *model, *loss, cmd_criterion, "loss [" + cmd_loss + "], criterion [" + cmd_criterion + "]"); } } log_info(); } // OK log_info() << done; return EXIT_SUCCESS; } <|endoftext|>
<commit_before>/* * Copyright (C) 2007-2008 Martin Pieuchot * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 * USA */ #include "wx/ogre/control.h" #include "ParticleUniverseEditor.h" #include "i6engine/utils/i6eSystemParameters.h" #include "OGRE/OgreRenderWindow.h" #include "OGRE/OgreRoot.h" #ifdef __WXGTK20__ extern "C" { #if ISIXE_MPLATFORM == ISIXE_MPLATFORM_LINUX #include <gdk/gdkx.h> #include <gtk/gtk.h> #endif } #endif unsigned int wxOgreControl::instances = 0; BEGIN_EVENT_TABLE(wxOgreControl, wxControl) EVT_MOUSE_EVENTS (wxOgreControl::OnMouseMove) EVT_ERASE_BACKGROUND(wxOgreControl::OnEraseBackground) EVT_PAINT (wxOgreControl::OnPaint) EVT_SIZE (wxOgreControl::OnSize) EVT_IDLE (wxOgreControl::OnIdle) END_EVENT_TABLE() IMPLEMENT_DYNAMIC_CLASS(wxOgreControl, wxControl) wxOgreControl::wxOgreControl() { Init(); } wxOgreControl::wxOgreControl(wxWindow * parent, wxWindowID id, const wxPoint & pos, const wxSize & size, long style, const wxValidator & val, const wxString & name) /*: wxControl(parent, id, pos, size, style, val, name) */: _sceneManager(nullptr), _camera(nullptr), _callbackFrame(nullptr), _root(nullptr), _renderWindow(nullptr), _viewport(nullptr), _lastX(0), _lastY(0) { Init(); Create(parent, id, pos, size, style, val, name); } wxOgreControl::~wxOgreControl() { Destroy(); } bool wxOgreControl::Create(wxWindow * parent, wxWindowID id, const wxPoint & pos, const wxSize & size, long style, const wxValidator & val, const wxString & name) { wxString instance_name = name + wxString::Format(wxT("%u"), instances); if (!wxControl::Create(parent, id, pos, size, style, val, instance_name)) { wxFAIL_MSG(_("wxOgreControl creation failed")); return false; } return true; } void wxOgreControl::Init() { _camera = nullptr; _renderWindow = nullptr; _viewport = nullptr; _lastX = 0; _lastY = 0; _root = Ogre::Root::getSingletonPtr(); instances++; } bool wxOgreControl::Destroy() { if (_camera) { _sceneManager->destroyCamera(_camera); _camera = 0; } /* Don't delete the SceneManager, it can be used by others. */ _sceneManager = nullptr; if (_viewport) { _renderWindow->removeAllViewports(); _viewport = nullptr; } DestroyRenderWindow(); return true; } void wxOgreControl::Update() { _root->renderOneFrame(); } void wxOgreControl::OnPaint(wxPaintEvent & WXUNUSED(event)) { wxPaintDC dc(this); Update(); } void wxOgreControl::OnEraseBackground(wxEraseEvent & WXUNUSED(event)) { Update(); } void wxOgreControl::OnSize(wxSizeEvent & WXUNUSED(event)) { if (_renderWindow) { int width, height; GetSize(&width, &height); _renderWindow->resize(static_cast<unsigned int>(width), static_cast<unsigned int>(height)); _renderWindow->windowMovedOrResized(); } #ifdef __WXGTK20__ // Fix because it is not automaticaly done with gtk+ if (_viewport) { _viewport->_updateDimensions(); } #endif // Let Ogre know the window has been resized; // Set the aspect ratio for the new size; // if (_camera) // _camera->setAspectRatio(ParticleUniverse::Real(width) / ParticleUniverse::Real(height)); } void wxOgreControl::OnIdle(wxIdleEvent & WXUNUSED(event)) { if (GetSize() != GetParent()->GetSize()) { SetSize(GetParent()->GetSize()); // This is needed to auto resize so it always fits its parent } Refresh(); } void wxOgreControl::AddViewport(Ogre::Camera * cam, int ZOrder, float left, float top, float width, float height) { if (_viewport) { _renderWindow->removeAllViewports(); } if (_renderWindow) { _viewport = _renderWindow->addViewport(cam, ZOrder, left, top, width, height); } } Ogre::RenderWindow* wxOgreControl::CreateRenderWindow(const Ogre::String & name) { if (!_root->isInitialised()) { _renderWindow = _root->initialise(false); } SetBackgroundStyle(wxBG_STYLE_SYSTEM); Ogre::NameValuePairList params; GetParentWindowHandle(params); try { int w, h; GetSize(&w, &h); _renderWindow = _root->createRenderWindow(name, w, h, false, &params); _renderWindow->setActive(true); // Even if we are not always using Ogre's // rendering loop, set it as AutoUpdated // in case of... _renderWindow->setAutoUpdated(true); } catch (Ogre::Exception & e) { wxOgreExceptionBox(e); } return _renderWindow; } void wxOgreControl::DestroyRenderWindow() { if (_renderWindow) { _root->detachRenderTarget(_renderWindow); _renderWindow = 0; SetBackgroundStyle(wxBG_STYLE_SYSTEM); } } void wxOgreControl::setCallbackFrame(ParticleUniverseEditorFrame * frame) { _callbackFrame = frame; } void wxOgreControl::GetParentWindowHandle(Ogre::NameValuePairList & pl) { #ifdef __WXMSW__ pl["externalWindowHandle"] = all2std(size_t(GetHandle())); #elif defined(__WXGTK20__) /* * Ok here is the most important comment about the GTK+ * part of this lib. * * Why we don't use GetHandle() here? Because it returns a * generic GtkWidget* that isn't one of the internals used * by wxGTK and can't be passed to the GTK_PIZZA() macro. * * This becomes a problem when we need to know the window ID * of the current widget. If you know Gtk+ you may want to use * gtk_widget_get_window() but in that case it doesn't return * the good pointer and the Ogre render window will be painted * under the background of this wxControl. * * Look at "wx/gtk/win_gtk.c" for more detailes. * * UPDATE: after changing to wxWidgets 3.0, GTK_PIZZA diesn't exist anymore * GDK_WINDOW_XWINDOW( widget->window ); should do the job (according to a forum post) */ GtkWidget * widget = m_wxwindow; /* May prevent from flickering */ gtk_widget_set_double_buffered(widget, false); /* * The frame need to be realize unless the parent * is already shown. */ gtk_widget_realize(widget); Window window = GDK_WINDOW_XWINDOW(widget->window); // Window is a typedef for XID, which is a typedef for unsigned int #if WXOGRE_OGRE_VER < 150 /* Get the display */ Display * display = GDK_WINDOW_XDISPLAY(gdkWin); /* Get the Screen */ unsigned int screen = DefaultScreen(display); pl["externalWindowHandle"] = all2std((unsigned long)display) + ":" + all2std(screen) + ":" + all2std(window); #else // WXOGRE_OGRE_VER < 150 pl["externalWindowHandle"] = all2std(window); #endif #else # error Not supported on this platform. #endif } Ogre::SceneManager * wxOgreControl::CreateSceneManager(const Ogre::String & tn, const Ogre::String & name) { SetSceneManager(Ogre::Root::getSingleton().createSceneManager(tn, name)); return _sceneManager; } Ogre::SceneManager * wxOgreControl::CreateSceneManager(Ogre::SceneTypeMask tm, const Ogre::String & name) { SetSceneManager(Ogre::Root::getSingleton().createSceneManager(tm, name)); return _sceneManager; } void wxOgreControl::SetSceneManager(Ogre::SceneManager * sm) { SetCamera(sm->createCamera("MainCamera")); _sceneManager = sm; } Ogre::SceneManager * wxOgreControl::GetSceneManager() { return _sceneManager; } void wxOgreControl::SetCamera(Ogre::Camera * cam) { if (_camera) { _sceneManager->destroyCamera(_camera); } int width, height; GetSize(&width, &height); _camera = cam; _camera->setAspectRatio(ParticleUniverse::Real(width) / ParticleUniverse::Real(height)); AddViewport(_camera); } void wxOgreControl::RotateCamera(float relX, float relY, float relZ) { if (_camera) { _camera->roll(Ogre::Radian(relZ)); _camera->yaw(Ogre::Radian(relY)); _camera->pitch(Ogre::Radian(relX)); } } void wxOgreControl::TranslateCamera(float x, float y, float z) { if (_camera) { _camera->moveRelative(Ogre::Vector3(x, y, z)); } } void wxOgreControl::SetPolygonMode(const Ogre::PolygonMode & pm) { if (_camera) { _camera->setPolygonMode(pm); } } void wxOgreControl::ProcessSelection(const wxPoint & pt) { } void wxOgreControl::OnMouseMove(wxMouseEvent & event) { if (!_callbackFrame) { return; } _callbackFrame->OnMouseMoveCallback(event); Refresh(); } <commit_msg>ISIXE-1531 fixed renderwindow on Linux<commit_after>/* * Copyright (C) 2007-2008 Martin Pieuchot * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 * USA */ #include "wx/ogre/control.h" #include "ParticleUniverseEditor.h" #include "i6engine/utils/i6eSystemParameters.h" #include "OGRE/OgreRenderWindow.h" #include "OGRE/OgreRoot.h" #ifdef __WXGTK20__ extern "C" { #if ISIXE_MPLATFORM == ISIXE_MPLATFORM_LINUX #include <gdk/gdkx.h> #include <gtk/gtk.h> #endif } #endif unsigned int wxOgreControl::instances = 0; BEGIN_EVENT_TABLE(wxOgreControl, wxControl) EVT_MOUSE_EVENTS (wxOgreControl::OnMouseMove) EVT_ERASE_BACKGROUND(wxOgreControl::OnEraseBackground) EVT_PAINT (wxOgreControl::OnPaint) EVT_SIZE (wxOgreControl::OnSize) EVT_IDLE (wxOgreControl::OnIdle) END_EVENT_TABLE() IMPLEMENT_DYNAMIC_CLASS(wxOgreControl, wxControl) wxOgreControl::wxOgreControl() { Init(); } wxOgreControl::wxOgreControl(wxWindow * parent, wxWindowID id, const wxPoint & pos, const wxSize & size, long style, const wxValidator & val, const wxString & name) /*: wxControl(parent, id, pos, size, style, val, name) */: _sceneManager(nullptr), _camera(nullptr), _callbackFrame(nullptr), _root(nullptr), _renderWindow(nullptr), _viewport(nullptr), _lastX(0), _lastY(0) { Init(); Create(parent, id, pos, size, style, val, name); } wxOgreControl::~wxOgreControl() { Destroy(); } bool wxOgreControl::Create(wxWindow * parent, wxWindowID id, const wxPoint & pos, const wxSize & size, long style, const wxValidator & val, const wxString & name) { wxString instance_name = name + wxString::Format(wxT("%u"), instances); if (!wxControl::Create(parent, id, pos, size, style, val, instance_name)) { wxFAIL_MSG(_("wxOgreControl creation failed")); return false; } return true; } void wxOgreControl::Init() { _camera = nullptr; _renderWindow = nullptr; _viewport = nullptr; _lastX = 0; _lastY = 0; _root = Ogre::Root::getSingletonPtr(); instances++; } bool wxOgreControl::Destroy() { if (_camera) { _sceneManager->destroyCamera(_camera); _camera = 0; } /* Don't delete the SceneManager, it can be used by others. */ _sceneManager = nullptr; if (_viewport) { _renderWindow->removeAllViewports(); _viewport = nullptr; } DestroyRenderWindow(); return true; } void wxOgreControl::Update() { _root->renderOneFrame(); _root->_fireFrameStarted(); if (_renderWindow) { _renderWindow->update(); } _root->_updateAllRenderTargets(); _root->_fireFrameEnded(); } void wxOgreControl::OnPaint(wxPaintEvent & WXUNUSED(event)) { wxPaintDC dc(this); Update(); } void wxOgreControl::OnEraseBackground(wxEraseEvent & WXUNUSED(event)) { Update(); } void wxOgreControl::OnSize(wxSizeEvent & WXUNUSED(event)) { if (_renderWindow) { int width, height; GetSize(&width, &height); _renderWindow->resize(static_cast<unsigned int>(width), static_cast<unsigned int>(height)); _renderWindow->windowMovedOrResized(); } #ifdef __WXGTK20__ // Fix because it is not automaticaly done with gtk+ if (_viewport) { _viewport->_updateDimensions(); } #endif // Let Ogre know the window has been resized; // Set the aspect ratio for the new size; // if (_camera) // _camera->setAspectRatio(ParticleUniverse::Real(width) / ParticleUniverse::Real(height)); } void wxOgreControl::OnIdle(wxIdleEvent & WXUNUSED(event)) { if (GetSize() != GetParent()->GetSize()) { SetSize(GetParent()->GetSize()); // This is needed to auto resize so it always fits its parent } Refresh(); } void wxOgreControl::AddViewport(Ogre::Camera * cam, int ZOrder, float left, float top, float width, float height) { if (_viewport) { _renderWindow->removeAllViewports(); } if (_renderWindow) { _viewport = _renderWindow->addViewport(cam, ZOrder, left, top, width, height); } } Ogre::RenderWindow* wxOgreControl::CreateRenderWindow(const Ogre::String & name) { if (!_root->isInitialised()) { _renderWindow = _root->initialise(false); } SetBackgroundStyle(wxBG_STYLE_PAINT); Ogre::NameValuePairList params; GetParentWindowHandle(params); try { int w, h; GetSize(&w, &h); _renderWindow = _root->createRenderWindow(name, w, h, false, &params); _renderWindow->setActive(true); // Even if we are not always using Ogre's // rendering loop, set it as AutoUpdated // in case of... _renderWindow->setAutoUpdated(true); } catch (Ogre::Exception & e) { wxOgreExceptionBox(e); } return _renderWindow; } void wxOgreControl::DestroyRenderWindow() { if (_renderWindow) { _root->detachRenderTarget(_renderWindow); _renderWindow = 0; SetBackgroundStyle(wxBG_STYLE_SYSTEM); } } void wxOgreControl::setCallbackFrame(ParticleUniverseEditorFrame * frame) { _callbackFrame = frame; } void wxOgreControl::GetParentWindowHandle(Ogre::NameValuePairList & pl) { #ifdef __WXMSW__ pl["externalWindowHandle"] = all2std(size_t(GetHandle())); #elif defined(__WXGTK20__) /* * Ok here is the most important comment about the GTK+ * part of this lib. * * Why we don't use GetHandle() here? Because it returns a * generic GtkWidget* that isn't one of the internals used * by wxGTK and can't be passed to the GTK_PIZZA() macro. * * This becomes a problem when we need to know the window ID * of the current widget. If you know Gtk+ you may want to use * gtk_widget_get_window() but in that case it doesn't return * the good pointer and the Ogre render window will be painted * under the background of this wxControl. * * Look at "wx/gtk/win_gtk.c" for more detailes. * * UPDATE: after changing to wxWidgets 3.0, GTK_PIZZA diesn't exist anymore * GDK_WINDOW_XWINDOW( widget->window ); should do the job (according to a forum post) */ GtkWidget * widget = m_wxwindow; /* May prevent from flickering */ gtk_widget_set_double_buffered(widget, false); /* * The frame need to be realize unless the parent * is already shown. */ gtk_widget_realize(widget); Window window = GDK_WINDOW_XWINDOW(widget->window); // Window is a typedef for XID, which is a typedef for unsigned int #if WXOGRE_OGRE_VER < 150 /* Get the display */ Display * display = GDK_WINDOW_XDISPLAY(gdkWin); /* Get the Screen */ unsigned int screen = DefaultScreen(display); pl["externalWindowHandle"] = all2std((unsigned long)display) + ":" + all2std(screen) + ":" + all2std(window); #else // WXOGRE_OGRE_VER < 150 pl["externalWindowHandle"] = all2std(window); #endif #else # error Not supported on this platform. #endif } Ogre::SceneManager * wxOgreControl::CreateSceneManager(const Ogre::String & tn, const Ogre::String & name) { SetSceneManager(Ogre::Root::getSingleton().createSceneManager(tn, name)); return _sceneManager; } Ogre::SceneManager * wxOgreControl::CreateSceneManager(Ogre::SceneTypeMask tm, const Ogre::String & name) { SetSceneManager(Ogre::Root::getSingleton().createSceneManager(tm, name)); return _sceneManager; } void wxOgreControl::SetSceneManager(Ogre::SceneManager * sm) { SetCamera(sm->createCamera("MainCamera")); _sceneManager = sm; } Ogre::SceneManager * wxOgreControl::GetSceneManager() { return _sceneManager; } void wxOgreControl::SetCamera(Ogre::Camera * cam) { if (_camera) { _sceneManager->destroyCamera(_camera); } int width, height; GetSize(&width, &height); _camera = cam; _camera->setAspectRatio(ParticleUniverse::Real(width) / ParticleUniverse::Real(height)); AddViewport(_camera); } void wxOgreControl::RotateCamera(float relX, float relY, float relZ) { if (_camera) { _camera->roll(Ogre::Radian(relZ)); _camera->yaw(Ogre::Radian(relY)); _camera->pitch(Ogre::Radian(relX)); } } void wxOgreControl::TranslateCamera(float x, float y, float z) { if (_camera) { _camera->moveRelative(Ogre::Vector3(x, y, z)); } } void wxOgreControl::SetPolygonMode(const Ogre::PolygonMode & pm) { if (_camera) { _camera->setPolygonMode(pm); } } void wxOgreControl::ProcessSelection(const wxPoint & pt) { } void wxOgreControl::OnMouseMove(wxMouseEvent & event) { if (!_callbackFrame) { return; } _callbackFrame->OnMouseMoveCallback(event); Refresh(); } <|endoftext|>
<commit_before>#include "../domain.h" #include <memory> #include <gtest/gtest.h> #include "../../test_helpers/gmock_wrapper.h" #include "../../domain/tests/mesh_mock.h" #include "../../domain/tests/finite_element_mock.h" using ::testing::_; class DomainTest : public ::testing::Test { protected: std::unique_ptr<bart::domain::MeshI<2>> mesh_ptr; std::unique_ptr<bart::domain::FiniteElementI<2>> fe_ptr; std::unique_ptr<bart::domain::MeshMock<2>> mesh_mock; std::unique_ptr<bart::domain::FiniteElementMock<2>> fe_mock; void SetUp() override; void MocksToPointers() { mesh_ptr = std::move(mesh_mock); fe_ptr = std::move(fe_mock); }; }; void DomainTest::SetUp() { mesh_mock = std::make_unique<bart::domain::MeshMock<2>>(); fe_mock = std::make_unique<bart::domain::FiniteElementMock<2>>(); } TEST_F(DomainTest, Constructor) { EXPECT_CALL(*mesh_mock, FillTriangulation(_)); EXPECT_CALL(*mesh_mock, FillMaterialID(_)); EXPECT_CALL(*mesh_mock, has_material_mapping()). WillOnce(::testing::Return(true)); EXPECT_CALL(*mesh_mock, FillBoundaryID(_)); MocksToPointers(); bart::problem::Domain<2> test_domain(mesh_ptr, fe_ptr); EXPECT_EQ(mesh_ptr, nullptr); EXPECT_EQ(fe_ptr, nullptr); } <commit_msg>added NiceMock for mesh in DomainTest, added test to ensure throws error if material mapping isn't initialized<commit_after>#include "../domain.h" #include <memory> #include <gtest/gtest.h> #include "../../test_helpers/gmock_wrapper.h" #include "../../domain/tests/mesh_mock.h" #include "../../domain/tests/finite_element_mock.h" using ::testing::_; using ::testing::NiceMock; class DomainTest : public ::testing::Test { protected: std::unique_ptr<bart::domain::MeshI<2>> mesh_ptr; std::unique_ptr<bart::domain::MeshI<2>> nice_mesh_ptr; std::unique_ptr<bart::domain::FiniteElementI<2>> fe_ptr; std::unique_ptr<bart::domain::MeshMock<2>> mesh_mock; std::unique_ptr<NiceMock<bart::domain::MeshMock<2>>> nice_mesh_mock; std::unique_ptr<bart::domain::FiniteElementMock<2>> fe_mock; void SetUp() override; void MocksToPointers() { mesh_ptr = std::move(mesh_mock); nice_mesh_ptr = std::move(nice_mesh_mock); fe_ptr = std::move(fe_mock); }; }; void DomainTest::SetUp() { mesh_mock = std::make_unique<bart::domain::MeshMock<2>>(); nice_mesh_mock = std::make_unique<NiceMock<bart::domain::MeshMock<2>>>(); fe_mock = std::make_unique<bart::domain::FiniteElementMock<2>>(); } TEST_F(DomainTest, Constructor) { EXPECT_CALL(*mesh_mock, FillTriangulation(_)); EXPECT_CALL(*mesh_mock, FillMaterialID(_)); EXPECT_CALL(*mesh_mock, has_material_mapping()). WillOnce(::testing::Return(true)); EXPECT_CALL(*mesh_mock, FillBoundaryID(_)); MocksToPointers(); bart::problem::Domain<2> test_domain(mesh_ptr, fe_ptr); EXPECT_EQ(mesh_ptr, nullptr); EXPECT_EQ(fe_ptr, nullptr); } TEST_F(DomainTest, ConstructorErrorMaterialMapping) { EXPECT_CALL(*nice_mesh_mock, has_material_mapping()). WillOnce(::testing::Return(false)); MocksToPointers(); EXPECT_ANY_THROW({ bart::problem::Domain<2> test_domain(nice_mesh_ptr, fe_ptr); }); } <|endoftext|>
<commit_before>// Copyright 2015 The Crashpad Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "handler/mac/crash_report_exception_handler.h" #include <vector> #include "base/logging.h" #include "base/mac/mach_logging.h" #include "base/mac/scoped_mach_port.h" #include "base/strings/stringprintf.h" #include "client/settings.h" #include "minidump/minidump_file_writer.h" #include "snapshot/crashpad_info_client_options.h" #include "snapshot/mac/process_snapshot_mac.h" #include "util/file/file_writer.h" #include "util/mach/exc_client_variants.h" #include "util/mach/exception_behaviors.h" #include "util/mach/exception_types.h" #include "util/mach/mach_extensions.h" #include "util/mach/mach_message.h" #include "util/mach/scoped_task_suspend.h" #include "util/mach/symbolic_constants_mach.h" #include "util/misc/tri_state.h" #include "util/misc/uuid.h" namespace crashpad { CrashReportExceptionHandler::CrashReportExceptionHandler( CrashReportDatabase* database, CrashReportUploadThread* upload_thread, const std::map<std::string, std::string>* process_annotations) : database_(database), upload_thread_(upload_thread), process_annotations_(process_annotations) { } CrashReportExceptionHandler::~CrashReportExceptionHandler() { } kern_return_t CrashReportExceptionHandler::CatchMachException( exception_behavior_t behavior, exception_handler_t exception_port, thread_t thread, task_t task, exception_type_t exception, const mach_exception_data_type_t* code, mach_msg_type_number_t code_count, thread_state_flavor_t* flavor, ConstThreadState old_state, mach_msg_type_number_t old_state_count, thread_state_t new_state, mach_msg_type_number_t* new_state_count, const mach_msg_trailer_t* trailer, bool* destroy_complex_request) { *destroy_complex_request = true; // The expected behavior is EXCEPTION_STATE_IDENTITY | MACH_EXCEPTION_CODES, // but it’s possible to deal with any exception behavior as long as it // carries identity information (valid thread and task ports). if (!ExceptionBehaviorHasIdentity(behavior)) { LOG(ERROR) << base::StringPrintf( "unexpected exception behavior %s, rejecting", ExceptionBehaviorToString( behavior, kUseFullName | kUnknownIsNumeric | kUseOr).c_str()); return KERN_FAILURE; } else if (behavior != (EXCEPTION_STATE_IDENTITY | kMachExceptionCodes)) { LOG(WARNING) << base::StringPrintf( "unexpected exception behavior %s, proceeding", ExceptionBehaviorToString( behavior, kUseFullName | kUnknownIsNumeric | kUseOr).c_str()); } if (task == mach_task_self()) { LOG(ERROR) << "cannot suspend myself"; return KERN_FAILURE; } ScopedTaskSuspend suspend(task); ProcessSnapshotMac process_snapshot; if (!process_snapshot.Initialize(task)) { return KERN_FAILURE; } // Check for suspicious message sources. A suspicious exception message comes // from a source other than the kernel or the process that the exception // purportedly occurred in. // // TODO(mark): Consider exceptions outside of the range (0, 32) from the // kernel to be suspicious, and exceptions other than kMachExceptionSimulated // from the process itself to be suspicious. const pid_t pid = process_snapshot.ProcessID(); pid_t audit_pid = AuditPIDFromMachMessageTrailer(trailer); if (audit_pid != -1 && audit_pid != 0) { if (audit_pid != pid) { LOG(WARNING) << "exception for pid " << pid << " sent by pid " << audit_pid; } } if (IsExceptionNonfatalResource(exception, code[0], pid)) { // Swallow non-fatal resource exceptions. // // Normally, all EXC_RESOURCE exceptions go to the host-level EXC_RESOURCE // handler, com.apple.ReportCrash.root, which invokes spindump to handle // them. These non-fatal exceptions are never user-visible and are not // currently of interest to Crashpad. Returning success here gets the // process going again quickly, without generating a crash report. // // Alternatively, this could return KERN_FAILURE to let the exception go to // the host-level handler, but there doesn’t seem to be much value in doing // so. ExcServerCopyState( behavior, old_state, old_state_count, new_state, new_state_count); return ExcServerSuccessfulReturnValue(exception, behavior, false); } CrashpadInfoClientOptions client_options; process_snapshot.GetCrashpadOptions(&client_options); if (client_options.crashpad_handler_behavior != TriState::kDisabled) { if (!process_snapshot.InitializeException(behavior, thread, exception, code, code_count, *flavor, old_state, old_state_count)) { return KERN_FAILURE; } UUID client_id; Settings* const settings = database_->GetSettings(); if (settings) { // If GetSettings() or GetClientID() fails, something else will log a // message and client_id will be left at its default value, all zeroes, // which is appropriate. settings->GetClientID(&client_id); } process_snapshot.SetClientID(client_id); process_snapshot.SetAnnotationsSimpleMap(*process_annotations_); CrashReportDatabase::NewReport* new_report; CrashReportDatabase::OperationStatus database_status = database_->PrepareNewCrashReport(&new_report); if (database_status != CrashReportDatabase::kNoError) { return KERN_FAILURE; } process_snapshot.SetReportID(new_report->uuid); CrashReportDatabase::CallErrorWritingCrashReport call_error_writing_crash_report(database_, new_report); WeakFileHandleFileWriter file_writer(new_report->handle); MinidumpFileWriter minidump; minidump.InitializeFromSnapshot(&process_snapshot); if (!minidump.WriteEverything(&file_writer)) { return KERN_FAILURE; } call_error_writing_crash_report.Disarm(); UUID uuid; database_status = database_->FinishedWritingCrashReport(new_report, &uuid); if (database_status != CrashReportDatabase::kNoError) { return KERN_FAILURE; } upload_thread_->ReportPending(); } if (client_options.system_crash_reporter_forwarding != TriState::kDisabled && (exception == EXC_CRASH || exception == EXC_RESOURCE || exception == EXC_GUARD)) { // Don’t forward simulated exceptions such as kMachExceptionSimulated to the // system crash reporter. Only forward the types of exceptions that it would // receive under normal conditions. Although the system crash reporter is // able to deal with other exceptions including simulated ones, forwarding // them to the system crash reporter could present the system’s crash UI for // processes that haven’t actually crashed, and could result in reports not // actually associated with crashes being sent to the operating system // vendor. // // Note that normally, EXC_RESOURCE and EXC_GUARD exceptions are sent to the // system-level com.apple.ReportCrash.Root job, and not to the user-level // job that they are forwarded to here. base::mac::ScopedMachSendRight system_crash_reporter_handler(SystemCrashReporterHandler()); if (system_crash_reporter_handler) { // Make copies of mutable out parameters so that the system crash reporter // can’t influence the state returned by this method. thread_state_flavor_t flavor_forward = *flavor; mach_msg_type_number_t new_state_forward_count = *new_state_count; std::vector<natural_t> new_state_forward( new_state, new_state + new_state_forward_count); // The system crash reporter requires the behavior to be // EXCEPTION_STATE_IDENTITY | MACH_EXCEPTION_CODES. It uses the identity // parameters but doesn’t appear to use the state parameters, including // |flavor|, and doesn’t care if they are 0 or invalid. As long as an // identity is available (checked above), any other exception behavior is // converted to what the system crash reporter wants, with the caveat that // problems may arise if the state wasn’t available and the system crash // reporter changes in the future to use it. However, normally, the state // will be available. kern_return_t kr = UniversalExceptionRaise( EXCEPTION_STATE_IDENTITY | MACH_EXCEPTION_CODES, system_crash_reporter_handler, thread, task, exception, code, code_count, &flavor_forward, old_state, old_state_count, new_state_forward_count ? &new_state_forward[0] : nullptr, &new_state_forward_count); MACH_LOG_IF(WARNING, kr != KERN_SUCCESS, kr) << "UniversalExceptionRaise"; } } ExcServerCopyState( behavior, old_state, old_state_count, new_state, new_state_count); return ExcServerSuccessfulReturnValue(exception, behavior, false); } } // namespace crashpad <commit_msg>mac: Revise incorrect comments about EXC_RESOURCE and EXC_GUARD<commit_after>// Copyright 2015 The Crashpad Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "handler/mac/crash_report_exception_handler.h" #include <vector> #include "base/logging.h" #include "base/mac/mach_logging.h" #include "base/mac/scoped_mach_port.h" #include "base/strings/stringprintf.h" #include "client/settings.h" #include "minidump/minidump_file_writer.h" #include "snapshot/crashpad_info_client_options.h" #include "snapshot/mac/process_snapshot_mac.h" #include "util/file/file_writer.h" #include "util/mach/exc_client_variants.h" #include "util/mach/exception_behaviors.h" #include "util/mach/exception_types.h" #include "util/mach/mach_extensions.h" #include "util/mach/mach_message.h" #include "util/mach/scoped_task_suspend.h" #include "util/mach/symbolic_constants_mach.h" #include "util/misc/tri_state.h" #include "util/misc/uuid.h" namespace crashpad { CrashReportExceptionHandler::CrashReportExceptionHandler( CrashReportDatabase* database, CrashReportUploadThread* upload_thread, const std::map<std::string, std::string>* process_annotations) : database_(database), upload_thread_(upload_thread), process_annotations_(process_annotations) { } CrashReportExceptionHandler::~CrashReportExceptionHandler() { } kern_return_t CrashReportExceptionHandler::CatchMachException( exception_behavior_t behavior, exception_handler_t exception_port, thread_t thread, task_t task, exception_type_t exception, const mach_exception_data_type_t* code, mach_msg_type_number_t code_count, thread_state_flavor_t* flavor, ConstThreadState old_state, mach_msg_type_number_t old_state_count, thread_state_t new_state, mach_msg_type_number_t* new_state_count, const mach_msg_trailer_t* trailer, bool* destroy_complex_request) { *destroy_complex_request = true; // The expected behavior is EXCEPTION_STATE_IDENTITY | MACH_EXCEPTION_CODES, // but it’s possible to deal with any exception behavior as long as it // carries identity information (valid thread and task ports). if (!ExceptionBehaviorHasIdentity(behavior)) { LOG(ERROR) << base::StringPrintf( "unexpected exception behavior %s, rejecting", ExceptionBehaviorToString( behavior, kUseFullName | kUnknownIsNumeric | kUseOr).c_str()); return KERN_FAILURE; } else if (behavior != (EXCEPTION_STATE_IDENTITY | kMachExceptionCodes)) { LOG(WARNING) << base::StringPrintf( "unexpected exception behavior %s, proceeding", ExceptionBehaviorToString( behavior, kUseFullName | kUnknownIsNumeric | kUseOr).c_str()); } if (task == mach_task_self()) { LOG(ERROR) << "cannot suspend myself"; return KERN_FAILURE; } ScopedTaskSuspend suspend(task); ProcessSnapshotMac process_snapshot; if (!process_snapshot.Initialize(task)) { return KERN_FAILURE; } // Check for suspicious message sources. A suspicious exception message comes // from a source other than the kernel or the process that the exception // purportedly occurred in. // // TODO(mark): Consider exceptions outside of the range (0, 32) from the // kernel to be suspicious, and exceptions other than kMachExceptionSimulated // from the process itself to be suspicious. const pid_t pid = process_snapshot.ProcessID(); pid_t audit_pid = AuditPIDFromMachMessageTrailer(trailer); if (audit_pid != -1 && audit_pid != 0) { if (audit_pid != pid) { LOG(WARNING) << "exception for pid " << pid << " sent by pid " << audit_pid; } } CrashpadInfoClientOptions client_options; process_snapshot.GetCrashpadOptions(&client_options); if (client_options.crashpad_handler_behavior != TriState::kDisabled && !IsExceptionNonfatalResource(exception, code[0], pid)) { // Non-fatal resource exceptions are never user-visible and are not // currently of interest to Crashpad. if (!process_snapshot.InitializeException(behavior, thread, exception, code, code_count, *flavor, old_state, old_state_count)) { return KERN_FAILURE; } UUID client_id; Settings* const settings = database_->GetSettings(); if (settings) { // If GetSettings() or GetClientID() fails, something else will log a // message and client_id will be left at its default value, all zeroes, // which is appropriate. settings->GetClientID(&client_id); } process_snapshot.SetClientID(client_id); process_snapshot.SetAnnotationsSimpleMap(*process_annotations_); CrashReportDatabase::NewReport* new_report; CrashReportDatabase::OperationStatus database_status = database_->PrepareNewCrashReport(&new_report); if (database_status != CrashReportDatabase::kNoError) { return KERN_FAILURE; } process_snapshot.SetReportID(new_report->uuid); CrashReportDatabase::CallErrorWritingCrashReport call_error_writing_crash_report(database_, new_report); WeakFileHandleFileWriter file_writer(new_report->handle); MinidumpFileWriter minidump; minidump.InitializeFromSnapshot(&process_snapshot); if (!minidump.WriteEverything(&file_writer)) { return KERN_FAILURE; } call_error_writing_crash_report.Disarm(); UUID uuid; database_status = database_->FinishedWritingCrashReport(new_report, &uuid); if (database_status != CrashReportDatabase::kNoError) { return KERN_FAILURE; } upload_thread_->ReportPending(); } if (client_options.system_crash_reporter_forwarding != TriState::kDisabled && (exception == EXC_CRASH || exception == EXC_RESOURCE || exception == EXC_GUARD)) { // Don’t forward simulated exceptions such as kMachExceptionSimulated to the // system crash reporter. Only forward the types of exceptions that it would // receive under normal conditions. Although the system crash reporter is // able to deal with other exceptions including simulated ones, forwarding // them to the system crash reporter could present the system’s crash UI for // processes that haven’t actually crashed, and could result in reports not // actually associated with crashes being sent to the operating system // vendor. base::mac::ScopedMachSendRight system_crash_reporter_handler(SystemCrashReporterHandler()); if (system_crash_reporter_handler) { // Make copies of mutable out parameters so that the system crash reporter // can’t influence the state returned by this method. thread_state_flavor_t flavor_forward = *flavor; mach_msg_type_number_t new_state_forward_count = *new_state_count; std::vector<natural_t> new_state_forward( new_state, new_state + new_state_forward_count); // The system crash reporter requires the behavior to be // EXCEPTION_STATE_IDENTITY | MACH_EXCEPTION_CODES. It uses the identity // parameters but doesn’t appear to use the state parameters, including // |flavor|, and doesn’t care if they are 0 or invalid. As long as an // identity is available (checked above), any other exception behavior is // converted to what the system crash reporter wants, with the caveat that // problems may arise if the state wasn’t available and the system crash // reporter changes in the future to use it. However, normally, the state // will be available. kern_return_t kr = UniversalExceptionRaise( EXCEPTION_STATE_IDENTITY | MACH_EXCEPTION_CODES, system_crash_reporter_handler, thread, task, exception, code, code_count, &flavor_forward, old_state, old_state_count, new_state_forward_count ? &new_state_forward[0] : nullptr, &new_state_forward_count); MACH_LOG_IF(WARNING, kr != KERN_SUCCESS, kr) << "UniversalExceptionRaise"; } } ExcServerCopyState( behavior, old_state, old_state_count, new_state, new_state_count); return ExcServerSuccessfulReturnValue(exception, behavior, false); } } // namespace crashpad <|endoftext|>
<commit_before>// Copyright (c) 2012, Sergey Zolotarev // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // 2. Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR // ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; // // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND // ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include <cassert> #include <cstddef> #include <fstream> #include <map> #include <string> #include "configreader.h" #include "jit.h" #include "jump-x86.h" #include "plugin.h" #include "pluginversion.h" #ifdef WIN32 #include <Windows.h> #else #ifndef _GNU_SOURCE #define _GNU_SOURCE 1 // for dladdr() #endif #include <dlfcn.h> #endif static void **amx_exports; typedef void (*logprintf_t)(const char *format, ...); static logprintf_t logprintf; typedef std::map<AMX*, jit::Frontend*> JitMap; static JitMap jit_map; static JumpX86 amx_Exec_hook; static JumpX86 amx_GetAddr_hook; static cell *opcode_list = 0; static ConfigReader server_cfg("server.cfg"); static int AMXAPI amx_GetAddr_JIT(AMX *amx, cell amx_addr, cell **phys_addr) { AMX_HEADER *hdr = reinterpret_cast<AMX_HEADER*>(amx->base); *phys_addr = reinterpret_cast<cell*>(amx->base + hdr->dat + amx_addr); return AMX_ERR_NONE; } const char *GetPublicName(AMX *amx, int index) { AMX_HEADER *hdr = reinterpret_cast<AMX_HEADER*>(amx->base); AMX_FUNCSTUBNT *publics = reinterpret_cast<AMX_FUNCSTUBNT*>(hdr->publics + amx->base); if (index >=0 && index < ((hdr->natives - hdr->publics) / hdr->defsize)) { return reinterpret_cast<char*>(amx->base + publics[index].nameofs); } else if (index == AMX_EXEC_MAIN) { return "main"; } return 0; } static int AMXAPI amx_Exec_JIT(AMX *amx, cell *retval, int index) { #if defined __GNUC__ if ((amx->flags & AMX_FLAG_BROWSE) == AMX_FLAG_BROWSE) { // amx_BrowseRelocate() wants the opcode list. assert(::opcode_list != 0); *retval = reinterpret_cast<cell>(::opcode_list); return AMX_ERR_NONE; } #endif jit::Frontend *jit = jit_map[amx]; try { return jit->CallPublicFunction(index, retval); } catch (const jit::InstructionError &e) { cell ip = reinterpret_cast<cell>(e.GetInstruction().GetIP()); cell address = ip - reinterpret_cast<cell>(jit->GetAmxCode()); try { throw; } catch (const jit::InvalidInstructionError &) { logprintf("[jit] Error: Invalid instruction at address %08x", address); } catch (const jit::UnsupportedInstructionError &) { logprintf("[jit] Error: Unsupported instruction at address %08x", address); } } catch (...) { logprintf("[jit] Error: Unknown error"); throw; } return AMX_ERR_NONE; } static std::string GetModuleNameBySymbol(void *symbol) { char module[FILENAME_MAX] = ""; if (symbol != 0) { #ifdef WIN32 MEMORY_BASIC_INFORMATION mbi; VirtualQuery(symbol, &mbi, sizeof(mbi)); GetModuleFileName((HMODULE)mbi.AllocationBase, module, FILENAME_MAX); #else Dl_info info; dladdr(symbol, &info); strcpy(module, info.dli_fname); #endif } return std::string(module); } static std::string GetFileName(const std::string &path) { std::string::size_type lastSep = path.find_last_of("/\\"); if (lastSep != std::string::npos) { return path.substr(lastSep + 1); } return path; } PLUGIN_EXPORT unsigned int PLUGIN_CALL Supports() { return SUPPORTS_VERSION | SUPPORTS_AMX_NATIVES; } PLUGIN_EXPORT bool PLUGIN_CALL Load(void **ppData) { logprintf = (logprintf_t)ppData[PLUGIN_DATA_LOGPRINTF]; ::amx_exports = reinterpret_cast<void**>(ppData[PLUGIN_DATA_AMX_EXPORTS]); void *funAddr = JumpX86::GetTargetAddress(::amx_exports[PLUGIN_AMX_EXPORT_Exec]); if (funAddr != 0) { std::string module = GetFileName(GetModuleNameBySymbol(funAddr)); if (!module.empty() && module != "samp-server.exe" && module != "samp03svr") { logprintf(" jit::Frontend must be loaded before %s", module.c_str()); return false; } } std::size_t stack_size = server_cfg.GetOption("jit_stack", 0); if (stack_size != 0) { jit::Frontend::SetStackSize(stack_size); } logprintf(" jit::Frontend plugin v%s is OK.", PLUGIN_VERSION_STRING); return true; } PLUGIN_EXPORT void PLUGIN_CALL Unload() { for (JitMap::iterator it = jit_map.begin(); it != jit_map.end(); ++it) { delete it->second; } } PLUGIN_EXPORT int PLUGIN_CALL AmxLoad(AMX *amx) { typedef int (AMXAPI *amx_Exec_t)(AMX *amx, cell *retval, int index); amx_Exec_t amx_Exec = (amx_Exec_t)::amx_exports[PLUGIN_AMX_EXPORT_Exec]; typedef int (AMXAPI *amx_GetAddr_t)(AMX *amx, cell amx_addr, cell **phys_addr); amx_GetAddr_t amx_GetAddr = (amx_GetAddr_t)::amx_exports[PLUGIN_AMX_EXPORT_GetAddr]; #if defined __GNUC__ // Get opcode list before we hook amx_Exec(). if (::opcode_list == 0) { amx->flags |= AMX_FLAG_BROWSE; amx_Exec(amx, reinterpret_cast<cell*>(&opcode_list), 0); amx->flags &= ~AMX_FLAG_BROWSE; } #endif if (!amx_Exec_hook.IsInstalled()) { amx_Exec_hook.Install( (void*)amx_Exec, (void*)amx_Exec_JIT); } if (!amx_GetAddr_hook.IsInstalled()) { amx_GetAddr_hook.Install( (void*)amx_GetAddr, (void*)amx_GetAddr_JIT); } jit::Frontend *jit = new jit::Frontend(amx, ::opcode_list); jit_map.insert(std::make_pair(amx, jit)); return AMX_ERR_NONE; } PLUGIN_EXPORT int PLUGIN_CALL AmxUnload(AMX *amx) { JitMap::iterator it = jit_map.find(amx); if (it != jit_map.end()) { delete it->second; jit_map.erase(it); } return AMX_ERR_NONE; } <commit_msg>Dump first few cells in instruction errors for debugging<commit_after>// Copyright (c) 2012, Sergey Zolotarev // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // 2. Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR // ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; // // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND // ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include <cassert> #include <cstddef> #include <fstream> #include <map> #include <string> #include "configreader.h" #include "jit.h" #include "jump-x86.h" #include "plugin.h" #include "pluginversion.h" #ifdef WIN32 #include <Windows.h> #else #ifndef _GNU_SOURCE #define _GNU_SOURCE 1 // for dladdr() #endif #include <dlfcn.h> #endif static void **amx_exports; typedef void (*logprintf_t)(const char *format, ...); static logprintf_t logprintf; typedef std::map<AMX*, jit::Frontend*> JitMap; static JitMap jit_map; static JumpX86 amx_Exec_hook; static JumpX86 amx_GetAddr_hook; static cell *opcode_list = 0; static ConfigReader server_cfg("server.cfg"); static int AMXAPI amx_GetAddr_JIT(AMX *amx, cell amx_addr, cell **phys_addr) { AMX_HEADER *hdr = reinterpret_cast<AMX_HEADER*>(amx->base); *phys_addr = reinterpret_cast<cell*>(amx->base + hdr->dat + amx_addr); return AMX_ERR_NONE; } const char *GetPublicName(AMX *amx, int index) { AMX_HEADER *hdr = reinterpret_cast<AMX_HEADER*>(amx->base); AMX_FUNCSTUBNT *publics = reinterpret_cast<AMX_FUNCSTUBNT*>(hdr->publics + amx->base); if (index >=0 && index < ((hdr->natives - hdr->publics) / hdr->defsize)) { return reinterpret_cast<char*>(amx->base + publics[index].nameofs); } else if (index == AMX_EXEC_MAIN) { return "main"; } return 0; } static int AMXAPI amx_Exec_JIT(AMX *amx, cell *retval, int index) { #if defined __GNUC__ if ((amx->flags & AMX_FLAG_BROWSE) == AMX_FLAG_BROWSE) { // amx_BrowseRelocate() wants the opcode list. assert(::opcode_list != 0); *retval = reinterpret_cast<cell>(::opcode_list); return AMX_ERR_NONE; } #endif jit::Frontend *jit = jit_map[amx]; try { return jit->CallPublicFunction(index, retval); } catch (const jit::InstructionError &e) { const jit::AmxInstruction &instr = e.GetInstruction(); cell address = reinterpret_cast<cell>(instr.GetIP()) - reinterpret_cast<cell>(jit->GetAmxCode()); try { throw; } catch (const jit::InvalidInstructionError &) { logprintf("[jit] Error: Invalid instruction at address %08x:", address); } catch (const jit::UnsupportedInstructionError &) { logprintf("[jit] Error: Unsupported instruction at address %08x:", address); } // Dump first 4 cells for debugging... const cell *ip = instr.GetIP(); logprintf(" %08x %08x %08x %08x", *ip, *(ip + 1), *(ip + 2), *(ip + 3)); } catch (...) { logprintf("[jit] Error: Unknown error"); throw; } return AMX_ERR_NONE; } static std::string GetModuleNameBySymbol(void *symbol) { char module[FILENAME_MAX] = ""; if (symbol != 0) { #ifdef WIN32 MEMORY_BASIC_INFORMATION mbi; VirtualQuery(symbol, &mbi, sizeof(mbi)); GetModuleFileName((HMODULE)mbi.AllocationBase, module, FILENAME_MAX); #else Dl_info info; dladdr(symbol, &info); strcpy(module, info.dli_fname); #endif } return std::string(module); } static std::string GetFileName(const std::string &path) { std::string::size_type lastSep = path.find_last_of("/\\"); if (lastSep != std::string::npos) { return path.substr(lastSep + 1); } return path; } PLUGIN_EXPORT unsigned int PLUGIN_CALL Supports() { return SUPPORTS_VERSION | SUPPORTS_AMX_NATIVES; } PLUGIN_EXPORT bool PLUGIN_CALL Load(void **ppData) { logprintf = (logprintf_t)ppData[PLUGIN_DATA_LOGPRINTF]; ::amx_exports = reinterpret_cast<void**>(ppData[PLUGIN_DATA_AMX_EXPORTS]); void *funAddr = JumpX86::GetTargetAddress(::amx_exports[PLUGIN_AMX_EXPORT_Exec]); if (funAddr != 0) { std::string module = GetFileName(GetModuleNameBySymbol(funAddr)); if (!module.empty() && module != "samp-server.exe" && module != "samp03svr") { logprintf(" jit::Frontend must be loaded before %s", module.c_str()); return false; } } std::size_t stack_size = server_cfg.GetOption("jit_stack", 0); if (stack_size != 0) { jit::Frontend::SetStackSize(stack_size); } logprintf(" jit::Frontend plugin v%s is OK.", PLUGIN_VERSION_STRING); return true; } PLUGIN_EXPORT void PLUGIN_CALL Unload() { for (JitMap::iterator it = jit_map.begin(); it != jit_map.end(); ++it) { delete it->second; } } PLUGIN_EXPORT int PLUGIN_CALL AmxLoad(AMX *amx) { typedef int (AMXAPI *amx_Exec_t)(AMX *amx, cell *retval, int index); amx_Exec_t amx_Exec = (amx_Exec_t)::amx_exports[PLUGIN_AMX_EXPORT_Exec]; typedef int (AMXAPI *amx_GetAddr_t)(AMX *amx, cell amx_addr, cell **phys_addr); amx_GetAddr_t amx_GetAddr = (amx_GetAddr_t)::amx_exports[PLUGIN_AMX_EXPORT_GetAddr]; #if defined __GNUC__ // Get opcode list before we hook amx_Exec(). if (::opcode_list == 0) { amx->flags |= AMX_FLAG_BROWSE; amx_Exec(amx, reinterpret_cast<cell*>(&opcode_list), 0); amx->flags &= ~AMX_FLAG_BROWSE; } #endif if (!amx_Exec_hook.IsInstalled()) { amx_Exec_hook.Install( (void*)amx_Exec, (void*)amx_Exec_JIT); } if (!amx_GetAddr_hook.IsInstalled()) { amx_GetAddr_hook.Install( (void*)amx_GetAddr, (void*)amx_GetAddr_JIT); } jit::Frontend *jit = new jit::Frontend(amx, ::opcode_list); jit_map.insert(std::make_pair(amx, jit)); return AMX_ERR_NONE; } PLUGIN_EXPORT int PLUGIN_CALL AmxUnload(AMX *amx) { JitMap::iterator it = jit_map.find(amx); if (it != jit_map.end()) { delete it->second; jit_map.erase(it); } return AMX_ERR_NONE; } <|endoftext|>
<commit_before>// Copyright (c) 2011 - 2019, GS Group, https://github.com/GSGroup // Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, // provided that the above copyright notice and this permission notice appear in all copies. // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. // IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, // WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. #include <stingraykit/serialization/Serialization.h> #include <stingraykit/serialization/SettingsValue.h> namespace stingray { SettingsValue* ObjectIStream::Get(const std::string &name) { SettingsValueMap &map = _root->get<SettingsValueMap>(); SettingsValueMap::iterator i = map.find(name); return (i != map.end())? i->second.get(): NULL; } void ObjectIStream::for_each(const function<void (SettingsValue&)> &func) { SettingsValueList &list = _root->get<SettingsValueList>(); for(SettingsValueList::iterator i = list.begin(); i != list.end(); ++i) { func(**i); } } void ObjectIStream::for_each_kv(const function<void (const std::string &, SettingsValue&)> &func) { SettingsValueMap &map = _root->get<SettingsValueMap>(); for(SettingsValueMap::iterator i = map.begin(); i != map.end(); ++i) { func(i->first, *i->second); } } s64 ObjectIStream::GetInt() { return _root->get<s64>(); } bool ObjectIStream::is_null() const { return _root->contains<EmptyType>(); } bool ObjectIStream::is_array() const { return _root->contains<SettingsValueList>(); } void ObjectIStream::deserialize(std::string &str) { str = _root->get<std::string>(); } void ObjectIStream::deserialize(bool &value) { value = _root->get<bool>(); } void ObjectIStream::deserialize(double &value) { value = _root->contains<FloatString>() ? _root->get<FloatString>().ToDouble() : GetInt(); } void ObjectIStream::deserialize(FloatString &value) { value = _root->contains<FloatString>() ? _root->get<FloatString>() : FloatString(GetInt()); } void ObjectIStream::deserialize(std::vector<u8> & data) { if (_root->contains<ByteArray>()) { ConstByteData storage = _root->get<ByteArray>().GetByteData(); data.assign(storage.begin(), storage.end()); } else if (_root->contains<std::string>()) UnpackBinaryEncoding(data, _root->get<std::string>()); else STINGRAYKIT_THROW("invalid type for binary data value: " + TypeInfo(_root->type()).ToString()); } static inline u8 xdigit(char c) { if (c >= '0' && c <= '9') return c - '0'; c |= 0x20; //lowercasing if (c >= 'a' && c <= 'f') return c - 'a' + 10; STINGRAYKIT_THROW(std::runtime_error(std::string("invalid hex digit") + c)); } void ObjectIStream::UnpackBinaryEncoding(std::vector<u8> & data, const std::string & str) { if (str.size() < 4 || str.compare(0, 4, "hex=") != 0) STINGRAYKIT_THROW(std::runtime_error("invalid binary encoding")); data.resize((str.size() - 4) / 2); std::vector<u8>::iterator dst = data.begin(); for(std::string::const_iterator i = str.begin() + 4; i != str.end(); ) { u8 h = xdigit(*i++) << 4; if (i == str.end()) STINGRAYKIT_THROW(std::runtime_error("half-byte in hex dump")); *dst++ = xdigit(*i++) | h; } } } <commit_msg>ByteData: remove excessive GetByteData calls from assignments to ByteData<commit_after>// Copyright (c) 2011 - 2019, GS Group, https://github.com/GSGroup // Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, // provided that the above copyright notice and this permission notice appear in all copies. // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. // IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, // WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. #include <stingraykit/serialization/Serialization.h> #include <stingraykit/serialization/SettingsValue.h> namespace stingray { SettingsValue* ObjectIStream::Get(const std::string &name) { SettingsValueMap &map = _root->get<SettingsValueMap>(); SettingsValueMap::iterator i = map.find(name); return (i != map.end())? i->second.get(): NULL; } void ObjectIStream::for_each(const function<void (SettingsValue&)> &func) { SettingsValueList &list = _root->get<SettingsValueList>(); for(SettingsValueList::iterator i = list.begin(); i != list.end(); ++i) { func(**i); } } void ObjectIStream::for_each_kv(const function<void (const std::string &, SettingsValue&)> &func) { SettingsValueMap &map = _root->get<SettingsValueMap>(); for(SettingsValueMap::iterator i = map.begin(); i != map.end(); ++i) { func(i->first, *i->second); } } s64 ObjectIStream::GetInt() { return _root->get<s64>(); } bool ObjectIStream::is_null() const { return _root->contains<EmptyType>(); } bool ObjectIStream::is_array() const { return _root->contains<SettingsValueList>(); } void ObjectIStream::deserialize(std::string &str) { str = _root->get<std::string>(); } void ObjectIStream::deserialize(bool &value) { value = _root->get<bool>(); } void ObjectIStream::deserialize(double &value) { value = _root->contains<FloatString>() ? _root->get<FloatString>().ToDouble() : GetInt(); } void ObjectIStream::deserialize(FloatString &value) { value = _root->contains<FloatString>() ? _root->get<FloatString>() : FloatString(GetInt()); } void ObjectIStream::deserialize(std::vector<u8> & data) { if (_root->contains<ByteArray>()) { ConstByteData storage = _root->get<ByteArray>(); data.assign(storage.begin(), storage.end()); } else if (_root->contains<std::string>()) UnpackBinaryEncoding(data, _root->get<std::string>()); else STINGRAYKIT_THROW("invalid type for binary data value: " + TypeInfo(_root->type()).ToString()); } static inline u8 xdigit(char c) { if (c >= '0' && c <= '9') return c - '0'; c |= 0x20; //lowercasing if (c >= 'a' && c <= 'f') return c - 'a' + 10; STINGRAYKIT_THROW(std::runtime_error(std::string("invalid hex digit") + c)); } void ObjectIStream::UnpackBinaryEncoding(std::vector<u8> & data, const std::string & str) { if (str.size() < 4 || str.compare(0, 4, "hex=") != 0) STINGRAYKIT_THROW(std::runtime_error("invalid binary encoding")); data.resize((str.size() - 4) / 2); std::vector<u8>::iterator dst = data.begin(); for(std::string::const_iterator i = str.begin() + 4; i != str.end(); ) { u8 h = xdigit(*i++) << 4; if (i == str.end()) STINGRAYKIT_THROW(std::runtime_error("half-byte in hex dump")); *dst++ = xdigit(*i++) | h; } } } <|endoftext|>
<commit_before>#include "cellmlplugin.h" #include "coreutils.h" #include "cellml-api-cxx-support.hpp" #include "CellMLBootstrap.hpp" #include "IfaceCellML_APISPEC.hxx" #include "IfaceCIS.hxx" #include "CISBootstrap.hpp" #include <QDebug> #include <QDir> #include <QThread> #include <QUrl> namespace OpenCOR { namespace CellML { PLUGININFO_FUNC CellMLPluginInfo() { Descriptions descriptions; descriptions.insert("en", "A plugin to use the <a href=\"http://www.cellml.org/tools/api/\">CellML API</a>"); descriptions.insert("fr", "Une extension pour utiliser l'<a href=\"http://www.cellml.org/tools/api/\">API CellML</a>"); return PluginInfo(PluginInfo::V001, PluginInfo::General, PluginInfo::Api, false, QStringList(), descriptions); } Q_EXPORT_PLUGIN2(CellML, CellMLPlugin) class SleeperThread : public QThread { public: static void msleep(unsigned long msecs) { QThread::msleep(msecs); } }; class TestProgressObserver : public iface::cellml_services::IntegrationProgressObserver { public: TestProgressObserver(iface::cellml_services::CellMLCompiledModel *pCompiledModel) : mCompiledModel(pCompiledModel), mCodeInformation(pCompiledModel->codeInformation()), mRefCount(1), mFinished(false) { iface::cellml_services::ComputationTargetIterator *cti = mCodeInformation->iterateTargets(); bool first = true; mHeader = QString(); while (true) { iface::cellml_services::ComputationTarget* ct = cti->nextComputationTarget(); if (!ct) break; if ( ((ct->type() == iface::cellml_services::STATE_VARIABLE) || (ct->type() == iface::cellml_services::ALGEBRAIC) || (ct->type() == iface::cellml_services::VARIABLE_OF_INTEGRATION)) && (ct->degree() == 0)) { if (!first) mHeader += ","; else first = false; mHeader += QString::fromWCharArray(ct->variable()->name()); } } } virtual void add_ref() throw(std::exception &) { ++mRefCount; } virtual void release_ref() throw(std::exception &) { --mRefCount; if (!mRefCount) delete this; } virtual char * objid() throw (std::exception &) { return strdup("singletonTestProgressObserver"); } virtual void * query_interface(const char *pIface) throw (std::exception &) { if (!strcmp(pIface, "xpcom::IObject")) return static_cast<iface::XPCOM::IObject *>(this); else if (!strcmp(pIface, "cellml_services::IntegrationProgressObserver")) return static_cast<iface::cellml_services::IntegrationProgressObserver *> (this); return 0; } virtual void computedConstants(uint32_t, double *pValues) throw (std::exception &) { iface::cellml_services::ComputationTargetIterator *targetsIter = mCodeInformation->iterateTargets(); qDebug(" Computed constants..."); while (true) { iface::cellml_services::ComputationTarget *target = targetsIter->nextComputationTarget(); if (!target) break; if ( (target->type() == iface::cellml_services::CONSTANT) && !target->degree()) qDebug(" %s = %g", QString::fromWCharArray(target->variable()->name()).toLatin1().constData(), pValues[target->assignedIndex()]); } } virtual void results(uint32_t pNbOfValues, double *pValues) throw (std::exception&) { static bool needInit = true; if (needInit) { qDebug(" Results..."); qDebug(" %s", mHeader.toLatin1().constData()); needInit = false; } uint32_t rateIndexCount = mCodeInformation->rateIndexCount(); uint32_t recSize = 2*rateIndexCount +mCodeInformation->algebraicIndexCount() +1; if (!recSize) return; for (uint32_t i = 0; i < pNbOfValues; i += recSize) { bool first = true; iface::cellml_services::ComputationTargetIterator *targetsIter = mCodeInformation->iterateTargets(); QString values = QString(); while (true) { iface::cellml_services::ComputationTarget *target = targetsIter->nextComputationTarget(); if (!target) break; if (target->degree()) continue; uint32_t varOff = 0; switch (target->type()) { case iface::cellml_services::STATE_VARIABLE: varOff = 1+target->assignedIndex(); break; case iface::cellml_services::VARIABLE_OF_INTEGRATION: varOff = 0; break; case iface::cellml_services::ALGEBRAIC: varOff = 1+2*rateIndexCount+target->assignedIndex(); break; default: continue; } if (!first) values += ","; else first = false; values += QString::number(pValues[i+varOff]); } qDebug(" %s", values.toLatin1().constData()); } } virtual void done() throw (std::exception &) { mFinished = true; } virtual void failed(const char *pErrorMsg) throw (std::exception &) { qDebug("ERROR: integration failed (%s).", pErrorMsg); mFinished = true; } bool finished() { return mFinished; } private: iface::cellml_services::CellMLCompiledModel *mCompiledModel; iface::cellml_services::CodeInformation *mCodeInformation; uint32_t mRefCount; bool mFinished; QString mHeader; }; void CellMLPlugin::initialize() { // Fetch a bootstrap object iface::cellml_api::CellMLBootstrap *cbs = CreateCellMLBootstrap(); // Retrieve the model loader iface::cellml_api::DOMModelLoader *ml = cbs->modelLoader(); // Load our test CellML model and return its cmeta:id // Note: we do this within a try...catch statement since we might get an // exception... QString testCellmlModelFileName = QDir::tempPath()+QDir::separator()+"test_cellml_model.cellml"; Core::saveResourceAs(":test_cellml_model", testCellmlModelFileName); qDebug("Loading the model..."); iface::cellml_api::Model *model; try { model = ml->loadFromURL(QUrl::fromLocalFile(testCellmlModelFileName).toString().toStdWString().c_str()); } catch (iface::cellml_api::CellMLException &) { qDebug("ERROR: %s.", QString::fromWCharArray(ml->lastErrorMessage()).toLatin1().constData()); return; } qDebug(); qDebug("Retrieving some model properties..."); // Retrieve the model's name qDebug(" Model '%s'", QString::fromWCharArray(model->name()).toLatin1().constData()); // Go through the model's components and their respective variables iface::cellml_api::CellMLComponentSet *comps = model->modelComponents(); iface::cellml_api::CellMLComponentIterator *compsIter = comps->iterateComponents(); for (int i = 0; i < comps->length(); i++) { iface::cellml_api::CellMLComponent *comp = compsIter->nextComponent(); qDebug(" Component '%s'", QString::fromWCharArray(comp->name()).toLatin1().constData()); iface::cellml_api::CellMLVariableSet *vars = comp->variables(); iface::cellml_api::CellMLVariableIterator *varsIter = vars->iterateVariables(); for(int j = 0; j < vars->length(); ++j) qDebug(" Variable '%s'", QString::fromStdWString(varsIter->nextVariable()->name()).toLatin1().constData()); } // Go through the model's connections and information iface::cellml_api::ConnectionSet *conns = model->connections(); iface::cellml_api::ConnectionIterator *connsIter = conns->iterateConnections(); for (int i = 0; i < conns->length(); i++) { iface::cellml_api::Connection *conn = connsIter->nextConnection(); iface::cellml_api::MapComponents *compMap = conn->componentMapping(); qDebug(" Connection between '%s' and '%s'", QString::fromStdWString(compMap->firstComponentName()).toLatin1().constData(), QString::fromStdWString(compMap->secondComponentName()).toLatin1().constData()); iface::cellml_api::MapVariablesSet *varMaps = conn->variableMappings(); iface::cellml_api::MapVariablesIterator *varMapsIter = varMaps->iterateMapVariables(); for(int j = 0; j < varMaps->length(); ++j) { iface::cellml_api::MapVariables *mapVars = varMapsIter->nextMapVariables(); qDebug(" For variables '%s' and '%s'", QString::fromStdWString(mapVars->firstVariableName()).toLatin1().constData(), QString::fromStdWString(mapVars->secondVariableName()).toLatin1().constData()); } } // Run the model qDebug(); qDebug("Running the model..."); iface::cellml_services::CellMLIntegrationService* cis = CreateIntegrationService(); iface::cellml_services::ODESolverCompiledModel* compiledModel = 0; qDebug(" Compiling the model..."); try { compiledModel = cis->compileModelODE(model); } catch (iface::cellml_api::CellMLException &) { qDebug("ERROR: %s.", QString::fromWCharArray(cis->lastError()).toLatin1().constData()); return; } catch (...) { qDebug("ERROR: unexpected exception calling compileModel."); return; } qDebug(" Creating the ODE solver run..."); iface::cellml_services::ODESolverRun *odeSolverRun = cis->createODEIntegrationRun(compiledModel); TestProgressObserver* progressObserver = new TestProgressObserver(compiledModel); odeSolverRun->setProgressObserver(progressObserver); odeSolverRun->stepType(iface::cellml_services::BDF_IMPLICIT_1_5_SOLVE); odeSolverRun->setResultRange(0, 50, 0); odeSolverRun->setTabulationStepControl(1, true); odeSolverRun->start(); while (!progressObserver->finished()) SleeperThread::msleep(1000); // All done... qDebug(); qDebug("All done..."); QFile::remove(testCellmlModelFileName); } QList<FileType> CellMLPlugin::fileTypes() const { // Return the CellML file type that the CellML plugin supports return QList<FileType>() << FileType(qobject_cast<FileInterface *>(this), CellmlMimeType, "cellml"); } QString CellMLPlugin::fileTypeDescription(const QString &mMimeType) const { // Return the description for the requested Mime type, that is as long as it // is for the CellML Mime type if (!mMimeType.compare(CellmlMimeType)) return tr("CellML File"); else // Not a Mime type that we can recognise, so... return FileInterface::fileTypeDescription(mMimeType); } } } <commit_msg>Was delaying things unnecessarily in our CellML test.<commit_after>#include "cellmlplugin.h" #include "coreutils.h" #include "cellml-api-cxx-support.hpp" #include "CellMLBootstrap.hpp" #include "IfaceCellML_APISPEC.hxx" #include "IfaceCIS.hxx" #include "CISBootstrap.hpp" #include <QDebug> #include <QDir> #include <QThread> #include <QUrl> namespace OpenCOR { namespace CellML { PLUGININFO_FUNC CellMLPluginInfo() { Descriptions descriptions; descriptions.insert("en", "A plugin to use the <a href=\"http://www.cellml.org/tools/api/\">CellML API</a>"); descriptions.insert("fr", "Une extension pour utiliser l'<a href=\"http://www.cellml.org/tools/api/\">API CellML</a>"); return PluginInfo(PluginInfo::V001, PluginInfo::General, PluginInfo::Api, false, QStringList(), descriptions); } Q_EXPORT_PLUGIN2(CellML, CellMLPlugin) class SleeperThread : public QThread { public: static void msleep(unsigned long msecs) { QThread::msleep(msecs); } }; class TestProgressObserver : public iface::cellml_services::IntegrationProgressObserver { public: TestProgressObserver(iface::cellml_services::CellMLCompiledModel *pCompiledModel) : mCompiledModel(pCompiledModel), mCodeInformation(pCompiledModel->codeInformation()), mRefCount(1), mFinished(false) { iface::cellml_services::ComputationTargetIterator *cti = mCodeInformation->iterateTargets(); bool first = true; mHeader = QString(); while (true) { iface::cellml_services::ComputationTarget* ct = cti->nextComputationTarget(); if (!ct) break; if ( ((ct->type() == iface::cellml_services::STATE_VARIABLE) || (ct->type() == iface::cellml_services::ALGEBRAIC) || (ct->type() == iface::cellml_services::VARIABLE_OF_INTEGRATION)) && (ct->degree() == 0)) { if (!first) mHeader += ","; else first = false; mHeader += QString::fromWCharArray(ct->variable()->name()); } } } virtual void add_ref() throw(std::exception &) { ++mRefCount; } virtual void release_ref() throw(std::exception &) { --mRefCount; if (!mRefCount) delete this; } virtual char * objid() throw (std::exception &) { return strdup("singletonTestProgressObserver"); } virtual void * query_interface(const char *pIface) throw (std::exception &) { if (!strcmp(pIface, "xpcom::IObject")) return static_cast<iface::XPCOM::IObject *>(this); else if (!strcmp(pIface, "cellml_services::IntegrationProgressObserver")) return static_cast<iface::cellml_services::IntegrationProgressObserver *> (this); return 0; } virtual void computedConstants(uint32_t, double *pValues) throw (std::exception &) { iface::cellml_services::ComputationTargetIterator *targetsIter = mCodeInformation->iterateTargets(); qDebug(" Computed constants..."); while (true) { iface::cellml_services::ComputationTarget *target = targetsIter->nextComputationTarget(); if (!target) break; if ( (target->type() == iface::cellml_services::CONSTANT) && !target->degree()) qDebug(" %s = %g", QString::fromWCharArray(target->variable()->name()).toLatin1().constData(), pValues[target->assignedIndex()]); } } virtual void results(uint32_t pNbOfValues, double *pValues) throw (std::exception&) { static bool needInit = true; if (needInit) { qDebug(" Results..."); qDebug(" %s", mHeader.toLatin1().constData()); needInit = false; } uint32_t rateIndexCount = mCodeInformation->rateIndexCount(); uint32_t recSize = 2*rateIndexCount +mCodeInformation->algebraicIndexCount() +1; if (!recSize) return; for (uint32_t i = 0; i < pNbOfValues; i += recSize) { bool first = true; iface::cellml_services::ComputationTargetIterator *targetsIter = mCodeInformation->iterateTargets(); QString values = QString(); while (true) { iface::cellml_services::ComputationTarget *target = targetsIter->nextComputationTarget(); if (!target) break; if (target->degree()) continue; uint32_t varOff = 0; switch (target->type()) { case iface::cellml_services::STATE_VARIABLE: varOff = 1+target->assignedIndex(); break; case iface::cellml_services::VARIABLE_OF_INTEGRATION: varOff = 0; break; case iface::cellml_services::ALGEBRAIC: varOff = 1+2*rateIndexCount+target->assignedIndex(); break; default: continue; } if (!first) values += ","; else first = false; values += QString::number(pValues[i+varOff]); } qDebug(" %s", values.toLatin1().constData()); } } virtual void done() throw (std::exception &) { mFinished = true; } virtual void failed(const char *pErrorMsg) throw (std::exception &) { qDebug("ERROR: integration failed (%s).", pErrorMsg); mFinished = true; } bool finished() { return mFinished; } private: iface::cellml_services::CellMLCompiledModel *mCompiledModel; iface::cellml_services::CodeInformation *mCodeInformation; uint32_t mRefCount; bool mFinished; QString mHeader; }; void CellMLPlugin::initialize() { // Fetch a bootstrap object iface::cellml_api::CellMLBootstrap *cbs = CreateCellMLBootstrap(); // Retrieve the model loader iface::cellml_api::DOMModelLoader *ml = cbs->modelLoader(); // Load our test CellML model and return its cmeta:id // Note: we do this within a try...catch statement since we might get an // exception... QString testCellmlModelFileName = QDir::tempPath()+QDir::separator()+"test_cellml_model.cellml"; Core::saveResourceAs(":test_cellml_model", testCellmlModelFileName); qDebug("Loading the model..."); iface::cellml_api::Model *model; try { model = ml->loadFromURL(QUrl::fromLocalFile(testCellmlModelFileName).toString().toStdWString().c_str()); } catch (iface::cellml_api::CellMLException &) { qDebug("ERROR: %s.", QString::fromWCharArray(ml->lastErrorMessage()).toLatin1().constData()); return; } qDebug(); qDebug("Retrieving some model properties..."); // Retrieve the model's name qDebug(" Model '%s'", QString::fromWCharArray(model->name()).toLatin1().constData()); // Go through the model's components and their respective variables iface::cellml_api::CellMLComponentSet *comps = model->modelComponents(); iface::cellml_api::CellMLComponentIterator *compsIter = comps->iterateComponents(); for (int i = 0; i < comps->length(); i++) { iface::cellml_api::CellMLComponent *comp = compsIter->nextComponent(); qDebug(" Component '%s'", QString::fromWCharArray(comp->name()).toLatin1().constData()); iface::cellml_api::CellMLVariableSet *vars = comp->variables(); iface::cellml_api::CellMLVariableIterator *varsIter = vars->iterateVariables(); for(int j = 0; j < vars->length(); ++j) qDebug(" Variable '%s'", QString::fromStdWString(varsIter->nextVariable()->name()).toLatin1().constData()); } // Go through the model's connections and information iface::cellml_api::ConnectionSet *conns = model->connections(); iface::cellml_api::ConnectionIterator *connsIter = conns->iterateConnections(); for (int i = 0; i < conns->length(); i++) { iface::cellml_api::Connection *conn = connsIter->nextConnection(); iface::cellml_api::MapComponents *compMap = conn->componentMapping(); qDebug(" Connection between '%s' and '%s'", QString::fromStdWString(compMap->firstComponentName()).toLatin1().constData(), QString::fromStdWString(compMap->secondComponentName()).toLatin1().constData()); iface::cellml_api::MapVariablesSet *varMaps = conn->variableMappings(); iface::cellml_api::MapVariablesIterator *varMapsIter = varMaps->iterateMapVariables(); for(int j = 0; j < varMaps->length(); ++j) { iface::cellml_api::MapVariables *mapVars = varMapsIter->nextMapVariables(); qDebug(" For variables '%s' and '%s'", QString::fromStdWString(mapVars->firstVariableName()).toLatin1().constData(), QString::fromStdWString(mapVars->secondVariableName()).toLatin1().constData()); } } // Run the model qDebug(); qDebug("Running the model..."); iface::cellml_services::CellMLIntegrationService* cis = CreateIntegrationService(); iface::cellml_services::ODESolverCompiledModel* compiledModel = 0; qDebug(" Compiling the model..."); try { compiledModel = cis->compileModelODE(model); } catch (iface::cellml_api::CellMLException &) { qDebug("ERROR: %s.", QString::fromWCharArray(cis->lastError()).toLatin1().constData()); return; } catch (...) { qDebug("ERROR: unexpected exception calling compileModel."); return; } qDebug(" Creating the ODE solver run..."); iface::cellml_services::ODESolverRun *odeSolverRun = cis->createODEIntegrationRun(compiledModel); TestProgressObserver* progressObserver = new TestProgressObserver(compiledModel); odeSolverRun->setProgressObserver(progressObserver); odeSolverRun->stepType(iface::cellml_services::BDF_IMPLICIT_1_5_SOLVE); odeSolverRun->setResultRange(0, 50, 0); odeSolverRun->setTabulationStepControl(1, true); odeSolverRun->start(); while (!progressObserver->finished()) SleeperThread::msleep(1); // All done... qDebug(); qDebug("All done..."); QFile::remove(testCellmlModelFileName); } QList<FileType> CellMLPlugin::fileTypes() const { // Return the CellML file type that the CellML plugin supports return QList<FileType>() << FileType(qobject_cast<FileInterface *>(this), CellmlMimeType, "cellml"); } QString CellMLPlugin::fileTypeDescription(const QString &mMimeType) const { // Return the description for the requested Mime type, that is as long as it // is for the CellML Mime type if (!mMimeType.compare(CellmlMimeType)) return tr("CellML File"); else // Not a Mime type that we can recognise, so... return FileInterface::fileTypeDescription(mMimeType); } } } <|endoftext|>
<commit_before>/************************************************************************** ** ** This file is part of Qt Creator ** ** Copyright (c) 2012 Nokia Corporation and/or its subsidiary(-ies). ** ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** ** GNU Lesser General Public License Usage ** ** This file may be used under the terms of the GNU Lesser General Public ** License version 2.1 as published by the Free Software Foundation and ** appearing in the file LICENSE.LGPL included in the packaging of this file. ** Please review the following information to ensure the GNU Lesser General ** Public License version 2.1 requirements will be met: ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** Other Usage ** ** Alternatively, this file may be used in accordance with the terms and ** conditions contained in a signed written agreement between you and Nokia. ** ** If you have questions regarding the use of this file, please contact ** Nokia at qt-info@nokia.com. ** **************************************************************************/ #include "qtmessagelogwindow.h" #include "qtmessagelogview.h" #include "qtmessageloghandler.h" #include "qtmessagelogitemdelegate.h" #include "debuggerstringutils.h" #include "qtmessagelogproxymodel.h" #include <utils/statuslabel.h> #include <utils/styledbar.h> #include <utils/savedaction.h> #include <coreplugin/icore.h> #include <coreplugin/coreconstants.h> #include <coreplugin/findplaceholder.h> #include <aggregation/aggregate.h> #include <find/treeviewfind.h> #include <QSettings> #include <QHBoxLayout> #include <QVBoxLayout> #include <QToolButton> static const char CONSOLE[] = "Console"; static const char SHOW_LOG[] = "showLog"; static const char SHOW_WARNING[] = "showWarning"; static const char SHOW_ERROR[] = "showError"; namespace Debugger { namespace Internal { ///////////////////////////////////////////////////////////////////// // // QtMessageLogWindow // ///////////////////////////////////////////////////////////////////// QtMessageLogWindow::QtMessageLogWindow(QWidget *parent) : QWidget(parent) { setWindowTitle(tr(CONSOLE)); setObjectName(_(CONSOLE)); const int statusBarHeight = 25; QVBoxLayout *vbox = new QVBoxLayout(this); vbox->setMargin(0); vbox->setSpacing(0); QWidget *statusbarContainer = new QWidget(); statusbarContainer->setFixedHeight(statusBarHeight); QHBoxLayout *hbox = new QHBoxLayout(statusbarContainer); hbox->setMargin(0); const int spacing = 7; //Status Label m_statusLabel = new Utils::StatusLabel; hbox->addSpacing(spacing); hbox->addWidget(m_statusLabel); hbox->addWidget(new Utils::StyledSeparator); hbox->addSpacing(spacing); const int buttonWidth = 25; //Filters QToolButton *button = new QToolButton(this); button->setAutoRaise(true); button->setFixedWidth(buttonWidth); m_showLogAction = new Utils::SavedAction(this); m_showLogAction->setDefaultValue(true); m_showLogAction->setSettingsKey(_(CONSOLE), _(SHOW_LOG)); m_showLogAction->setText(tr("Log")); m_showLogAction->setCheckable(true); m_showLogAction->setIcon(QIcon(_(":/debugger/images/log.png"))); button->setDefaultAction(m_showLogAction); hbox->addWidget(button); hbox->addSpacing(spacing); button = new QToolButton(this); button->setAutoRaise(true); button->setFixedWidth(buttonWidth); m_showWarningAction = new Utils::SavedAction(this); m_showWarningAction->setDefaultValue(true); m_showWarningAction->setSettingsKey(_(CONSOLE), _(SHOW_WARNING)); m_showWarningAction->setText(tr("Warning")); m_showWarningAction->setCheckable(true); m_showWarningAction->setIcon(QIcon(_(":/debugger/images/warning.png"))); button->setDefaultAction(m_showWarningAction); hbox->addWidget(button); hbox->addSpacing(spacing); button = new QToolButton(this); button->setAutoRaise(true); button->setFixedWidth(buttonWidth); m_showErrorAction = new Utils::SavedAction(this); m_showErrorAction->setDefaultValue(true); m_showErrorAction->setSettingsKey(_(CONSOLE), _(SHOW_ERROR)); m_showErrorAction->setText(tr("Error")); m_showErrorAction->setCheckable(true); m_showErrorAction->setIcon(QIcon(_(":/debugger/images/error.png"))); button->setDefaultAction(m_showErrorAction); hbox->addWidget(button); hbox->addSpacing(spacing); //Clear Button button = new QToolButton; button->setAutoRaise(true); button->setFixedWidth(buttonWidth); m_clearAction = new QAction(tr("Clear Console"), this); m_clearAction->setIcon(QIcon(_(Core::Constants::ICON_CLEAN_PANE))); button->setDefaultAction(m_clearAction); hbox->addWidget(button); hbox->addSpacing(spacing); m_treeView = new QtMessageLogView(this); m_treeView->setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::MinimumExpanding); m_proxyModel = new QtMessageLogProxyModel(this); connect(m_showLogAction, SIGNAL(toggled(bool)), m_proxyModel, SLOT(setShowLogs(bool))); connect(m_showWarningAction, SIGNAL(toggled(bool)), m_proxyModel, SLOT(setShowWarnings(bool))); connect(m_showErrorAction, SIGNAL(toggled(bool)), m_proxyModel, SLOT(setShowErrors(bool))); m_treeView->setModel(m_proxyModel); connect(m_proxyModel, SIGNAL(setCurrentIndex(QModelIndex,QItemSelectionModel::SelectionFlags)), m_treeView->selectionModel(), SLOT(setCurrentIndex(QModelIndex,QItemSelectionModel::SelectionFlags))); connect(m_proxyModel, SIGNAL(scrollToBottom()), m_treeView, SLOT(onScrollToBottom())); m_itemDelegate = new QtMessageLogItemDelegate(this); connect(m_treeView->selectionModel(), SIGNAL(currentChanged(QModelIndex,QModelIndex)), m_itemDelegate, SLOT(currentChanged(QModelIndex,QModelIndex))); m_treeView->setItemDelegate(m_itemDelegate); vbox->addWidget(statusbarContainer); vbox->addWidget(m_treeView); vbox->addWidget(new Core::FindToolBarPlaceHolder(this)); readSettings(); connect(Core::ICore::instance(), SIGNAL(saveSettingsRequested()), SLOT(writeSettings())); Aggregation::Aggregate *aggregate = new Aggregation::Aggregate(); aggregate->add(m_treeView); aggregate->add(new Find::TreeViewFind(m_treeView)); } QtMessageLogWindow::~QtMessageLogWindow() { writeSettings(); } void QtMessageLogWindow::readSettings() { QSettings *settings = Core::ICore::settings(); m_showLogAction->readSettings(settings); m_showWarningAction->readSettings(settings); m_showErrorAction->readSettings(settings); } void QtMessageLogWindow::showStatus(const QString &context, int timeout) { m_statusLabel->showStatusMessage(context, timeout); } void QtMessageLogWindow::writeSettings() const { QSettings *settings = Core::ICore::settings(); m_showLogAction->writeSettings(settings); m_showWarningAction->writeSettings(settings); m_showErrorAction->writeSettings(settings); } void QtMessageLogWindow::setModel(QAbstractItemModel *model) { m_proxyModel->setSourceModel(model); QtMessageLogHandler *handler = qobject_cast<QtMessageLogHandler *>(model); m_itemDelegate->setItemModel(handler); connect(m_clearAction, SIGNAL(triggered()), handler, SLOT(clear())); connect(handler, SIGNAL(selectEditableRow(QModelIndex,QItemSelectionModel::SelectionFlags)), m_proxyModel, SLOT(selectEditableRow(QModelIndex,QItemSelectionModel::SelectionFlags))); //Scroll to bottom when rows matching current filter settings are inserted //Not connecting rowsRemoved as the only way to remove rows is to clear the //model which will automatically reset the view. connect(handler, SIGNAL(rowsInserted(QModelIndex,int,int)), m_proxyModel, SLOT(onRowsInserted(QModelIndex,int,int))); } } // namespace Internal } // namespace Debugger <commit_msg>ScriptConsole: Crash FIX<commit_after>/************************************************************************** ** ** This file is part of Qt Creator ** ** Copyright (c) 2012 Nokia Corporation and/or its subsidiary(-ies). ** ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** ** GNU Lesser General Public License Usage ** ** This file may be used under the terms of the GNU Lesser General Public ** License version 2.1 as published by the Free Software Foundation and ** appearing in the file LICENSE.LGPL included in the packaging of this file. ** Please review the following information to ensure the GNU Lesser General ** Public License version 2.1 requirements will be met: ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** Other Usage ** ** Alternatively, this file may be used in accordance with the terms and ** conditions contained in a signed written agreement between you and Nokia. ** ** If you have questions regarding the use of this file, please contact ** Nokia at qt-info@nokia.com. ** **************************************************************************/ #include "qtmessagelogwindow.h" #include "qtmessagelogview.h" #include "qtmessageloghandler.h" #include "qtmessagelogitemdelegate.h" #include "debuggerstringutils.h" #include "qtmessagelogproxymodel.h" #include <utils/statuslabel.h> #include <utils/styledbar.h> #include <utils/savedaction.h> #include <coreplugin/icore.h> #include <coreplugin/coreconstants.h> #include <coreplugin/findplaceholder.h> #include <aggregation/aggregate.h> #include <find/treeviewfind.h> #include <QSettings> #include <QHBoxLayout> #include <QVBoxLayout> #include <QToolButton> static const char CONSOLE[] = "Console"; static const char SHOW_LOG[] = "showLog"; static const char SHOW_WARNING[] = "showWarning"; static const char SHOW_ERROR[] = "showError"; namespace Debugger { namespace Internal { ///////////////////////////////////////////////////////////////////// // // QtMessageLogWindow // ///////////////////////////////////////////////////////////////////// QtMessageLogWindow::QtMessageLogWindow(QWidget *parent) : QWidget(parent) { setWindowTitle(tr(CONSOLE)); setObjectName(_(CONSOLE)); const int statusBarHeight = 25; QVBoxLayout *vbox = new QVBoxLayout(this); vbox->setMargin(0); vbox->setSpacing(0); QWidget *statusbarContainer = new QWidget(); statusbarContainer->setFixedHeight(statusBarHeight); QHBoxLayout *hbox = new QHBoxLayout(statusbarContainer); hbox->setMargin(0); const int spacing = 7; //Status Label m_statusLabel = new Utils::StatusLabel; hbox->addSpacing(spacing); hbox->addWidget(m_statusLabel); hbox->addWidget(new Utils::StyledSeparator); hbox->addSpacing(spacing); const int buttonWidth = 25; //Filters QToolButton *button = new QToolButton(this); button->setAutoRaise(true); button->setFixedWidth(buttonWidth); m_showLogAction = new Utils::SavedAction(this); m_showLogAction->setDefaultValue(true); m_showLogAction->setSettingsKey(_(CONSOLE), _(SHOW_LOG)); m_showLogAction->setText(tr("Log")); m_showLogAction->setCheckable(true); m_showLogAction->setIcon(QIcon(_(":/debugger/images/log.png"))); button->setDefaultAction(m_showLogAction); hbox->addWidget(button); hbox->addSpacing(spacing); button = new QToolButton(this); button->setAutoRaise(true); button->setFixedWidth(buttonWidth); m_showWarningAction = new Utils::SavedAction(this); m_showWarningAction->setDefaultValue(true); m_showWarningAction->setSettingsKey(_(CONSOLE), _(SHOW_WARNING)); m_showWarningAction->setText(tr("Warning")); m_showWarningAction->setCheckable(true); m_showWarningAction->setIcon(QIcon(_(":/debugger/images/warning.png"))); button->setDefaultAction(m_showWarningAction); hbox->addWidget(button); hbox->addSpacing(spacing); button = new QToolButton(this); button->setAutoRaise(true); button->setFixedWidth(buttonWidth); m_showErrorAction = new Utils::SavedAction(this); m_showErrorAction->setDefaultValue(true); m_showErrorAction->setSettingsKey(_(CONSOLE), _(SHOW_ERROR)); m_showErrorAction->setText(tr("Error")); m_showErrorAction->setCheckable(true); m_showErrorAction->setIcon(QIcon(_(":/debugger/images/error.png"))); button->setDefaultAction(m_showErrorAction); hbox->addWidget(button); hbox->addSpacing(spacing); //Clear Button button = new QToolButton; button->setAutoRaise(true); button->setFixedWidth(buttonWidth); m_clearAction = new QAction(tr("Clear Console"), this); m_clearAction->setIcon(QIcon(_(Core::Constants::ICON_CLEAN_PANE))); button->setDefaultAction(m_clearAction); hbox->addWidget(button); hbox->addSpacing(spacing); m_treeView = new QtMessageLogView(this); m_treeView->setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::MinimumExpanding); m_proxyModel = new QtMessageLogProxyModel(this); connect(m_showLogAction, SIGNAL(toggled(bool)), m_proxyModel, SLOT(setShowLogs(bool))); connect(m_showWarningAction, SIGNAL(toggled(bool)), m_proxyModel, SLOT(setShowWarnings(bool))); connect(m_showErrorAction, SIGNAL(toggled(bool)), m_proxyModel, SLOT(setShowErrors(bool))); m_treeView->setModel(m_proxyModel); connect(m_proxyModel, SIGNAL(setCurrentIndex(QModelIndex,QItemSelectionModel::SelectionFlags)), m_treeView->selectionModel(), SLOT(setCurrentIndex(QModelIndex,QItemSelectionModel::SelectionFlags))); connect(m_proxyModel, SIGNAL(scrollToBottom()), m_treeView, SLOT(onScrollToBottom())); m_itemDelegate = new QtMessageLogItemDelegate(this); connect(m_treeView->selectionModel(), SIGNAL(currentChanged(QModelIndex,QModelIndex)), m_itemDelegate, SLOT(currentChanged(QModelIndex,QModelIndex))); m_treeView->setItemDelegate(m_itemDelegate); vbox->addWidget(statusbarContainer); vbox->addWidget(m_treeView); vbox->addWidget(new Core::FindToolBarPlaceHolder(this)); readSettings(); connect(Core::ICore::instance(), SIGNAL(saveSettingsRequested()), SLOT(writeSettings())); Aggregation::Aggregate *aggregate = new Aggregation::Aggregate(); aggregate->add(m_treeView); aggregate->add(new Find::TreeViewFind(m_treeView)); } QtMessageLogWindow::~QtMessageLogWindow() { writeSettings(); } void QtMessageLogWindow::readSettings() { QSettings *settings = Core::ICore::settings(); m_showLogAction->readSettings(settings); m_showWarningAction->readSettings(settings); m_showErrorAction->readSettings(settings); } void QtMessageLogWindow::showStatus(const QString &context, int timeout) { m_statusLabel->showStatusMessage(context, timeout); } void QtMessageLogWindow::writeSettings() const { QSettings *settings = Core::ICore::settings(); m_showLogAction->writeSettings(settings); m_showWarningAction->writeSettings(settings); m_showErrorAction->writeSettings(settings); } void QtMessageLogWindow::setModel(QAbstractItemModel *model) { QtMessageLogHandler *oldHandler = qobject_cast<QtMessageLogHandler *>( m_proxyModel->sourceModel()); if (oldHandler) { disconnect(m_clearAction, SIGNAL(triggered()), oldHandler, SLOT(clear())); disconnect(oldHandler, SIGNAL(selectEditableRow( QModelIndex,QItemSelectionModel::SelectionFlags)), m_proxyModel, SLOT(selectEditableRow( QModelIndex,QItemSelectionModel::SelectionFlags))); disconnect(oldHandler, SIGNAL(rowsInserted(QModelIndex,int,int)), m_proxyModel, SLOT(onRowsInserted(QModelIndex,int,int))); } QtMessageLogHandler *newHandler = qobject_cast<QtMessageLogHandler *>(model); m_proxyModel->setSourceModel(newHandler); m_itemDelegate->setItemModel(newHandler); if (newHandler) { connect(m_clearAction, SIGNAL(triggered()), newHandler, SLOT(clear())); connect(newHandler, SIGNAL(selectEditableRow( QModelIndex,QItemSelectionModel::SelectionFlags)), m_proxyModel, SLOT(selectEditableRow( QModelIndex,QItemSelectionModel::SelectionFlags))); //Scroll to bottom when rows matching current filter settings are inserted //Not connecting rowsRemoved as the only way to remove rows is to clear the //model which will automatically reset the view. connect(newHandler, SIGNAL(rowsInserted(QModelIndex,int,int)), m_proxyModel, SLOT(onRowsInserted(QModelIndex,int,int))); } } } // namespace Internal } // namespace Debugger <|endoftext|>
<commit_before>/**************************************************************************** ** ** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies). ** Contact: http://www.qt-project.org/legal ** ** This file is part of Qt Creator. ** ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Digia. For licensing terms and ** conditions see http://qt.digia.com/licensing. For further information ** use the contact form at http://qt.digia.com/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Digia gives you certain additional ** rights. These rights are described in the Digia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ****************************************************************************/ #include "qtkitconfigwidget.h" #include "qtsupportconstants.h" #include "qtkitinformation.h" #include "qtversionmanager.h" #include <coreplugin/icore.h> #include <projectexplorer/projectexplorerconstants.h> #include <utils/qtcassert.h> #include <QComboBox> #include <QPushButton> namespace QtSupport { namespace Internal { QtKitConfigWidget::QtKitConfigWidget(ProjectExplorer::Kit *k, bool sticky) : KitConfigWidget(k, sticky) { m_combo = new QComboBox; m_combo->addItem(tr("None"), -1); QtVersionManager *mgr = QtVersionManager::instance(); QList<BaseQtVersion *> versions = mgr->validVersions(); QList<int> versionIds; foreach (BaseQtVersion *v, versions) versionIds.append(v->uniqueId()); versionsChanged(versionIds, QList<int>(), QList<int>()); m_manageButton = new QPushButton(tr("Manage...")); refresh(); m_combo->setToolTip(toolTip()); connect(m_combo, SIGNAL(currentIndexChanged(int)), this, SLOT(currentWasChanged(int))); connect(mgr, SIGNAL(qtVersionsChanged(QList<int>,QList<int>,QList<int>)), this, SLOT(versionsChanged(QList<int>,QList<int>,QList<int>))); connect(m_manageButton, SIGNAL(clicked()), this, SLOT(manageQtVersions())); } QString QtKitConfigWidget::displayName() const { return tr("Qt version:"); } QString QtKitConfigWidget::toolTip() const { return tr("The Qt library to use for all projects using this kit.<br>" "A Qt version is required for qmake-based projects " "and optional when using other build systems."); } void QtKitConfigWidget::makeReadOnly() { m_combo->setEnabled(false); } void QtKitConfigWidget::refresh() { m_combo->setCurrentIndex(findQtVersion(QtKitInformation::qtVersionId(m_kit))); } QWidget *QtKitConfigWidget::mainWidget() const { return m_combo; } QWidget *QtKitConfigWidget::buttonWidget() const { return m_manageButton; } void QtKitConfigWidget::versionsChanged(const QList<int> &added, const QList<int> &removed, const QList<int> &changed) { QtVersionManager *mgr = QtVersionManager::instance(); foreach (const int id, added) { BaseQtVersion *v = mgr->version(id); QTC_CHECK(v); QTC_CHECK(findQtVersion(id) < 0); m_combo->addItem(v->displayName(), id); } foreach (const int id, removed) { int pos = findQtVersion(id); QTC_CHECK(pos >= 0); m_combo->removeItem(pos); } foreach (const int id, changed) { BaseQtVersion *v = mgr->version(id); int pos = findQtVersion(id); QTC_CHECK(pos >= 0); m_combo->setItemText(pos, v->displayName()); } } void QtKitConfigWidget::manageQtVersions() { Core::ICore::showOptionsDialog(ProjectExplorer::Constants::PROJECTEXPLORER_SETTINGS_CATEGORY, Constants::QTVERSION_SETTINGS_PAGE_ID); } void QtKitConfigWidget::currentWasChanged(int idx) { QtKitInformation::setQtVersionId(m_kit, m_combo->itemData(idx).toInt()); } int QtKitConfigWidget::findQtVersion(const int id) const { for (int i = 0; i < m_combo->count(); ++i) { if (id == m_combo->itemData(i).toInt()) return i; } return -1; } } // namespace Internal } // namespace QtSupport <commit_msg>QtKitConfigWidget: Do not warn when invalid Qt versions are changed<commit_after>/**************************************************************************** ** ** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies). ** Contact: http://www.qt-project.org/legal ** ** This file is part of Qt Creator. ** ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Digia. For licensing terms and ** conditions see http://qt.digia.com/licensing. For further information ** use the contact form at http://qt.digia.com/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Digia gives you certain additional ** rights. These rights are described in the Digia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ****************************************************************************/ #include "qtkitconfigwidget.h" #include "qtsupportconstants.h" #include "qtkitinformation.h" #include "qtversionmanager.h" #include <coreplugin/icore.h> #include <projectexplorer/projectexplorerconstants.h> #include <utils/qtcassert.h> #include <QComboBox> #include <QPushButton> namespace QtSupport { namespace Internal { QtKitConfigWidget::QtKitConfigWidget(ProjectExplorer::Kit *k, bool sticky) : KitConfigWidget(k, sticky) { m_combo = new QComboBox; m_combo->addItem(tr("None"), -1); QtVersionManager *mgr = QtVersionManager::instance(); QList<BaseQtVersion *> versions = mgr->versions(); QList<int> versionIds; foreach (BaseQtVersion *v, versions) versionIds.append(v->uniqueId()); versionsChanged(versionIds, QList<int>(), QList<int>()); m_manageButton = new QPushButton(tr("Manage...")); refresh(); m_combo->setToolTip(toolTip()); connect(m_combo, SIGNAL(currentIndexChanged(int)), this, SLOT(currentWasChanged(int))); connect(mgr, SIGNAL(qtVersionsChanged(QList<int>,QList<int>,QList<int>)), this, SLOT(versionsChanged(QList<int>,QList<int>,QList<int>))); connect(m_manageButton, SIGNAL(clicked()), this, SLOT(manageQtVersions())); } QString QtKitConfigWidget::displayName() const { return tr("Qt version:"); } QString QtKitConfigWidget::toolTip() const { return tr("The Qt library to use for all projects using this kit.<br>" "A Qt version is required for qmake-based projects " "and optional when using other build systems."); } void QtKitConfigWidget::makeReadOnly() { m_combo->setEnabled(false); } void QtKitConfigWidget::refresh() { m_combo->setCurrentIndex(findQtVersion(QtKitInformation::qtVersionId(m_kit))); } QWidget *QtKitConfigWidget::mainWidget() const { return m_combo; } QWidget *QtKitConfigWidget::buttonWidget() const { return m_manageButton; } void QtKitConfigWidget::versionsChanged(const QList<int> &added, const QList<int> &removed, const QList<int> &changed) { QtVersionManager *mgr = QtVersionManager::instance(); foreach (const int id, added) { BaseQtVersion *v = mgr->version(id); QTC_CHECK(v); if (!v->isValid()) continue; QTC_CHECK(findQtVersion(id) < 0); m_combo->addItem(v->displayName(), id); } foreach (const int id, removed) { int pos = findQtVersion(id); if (pos >= 0) // We do not include invalid Qt versions, so do not try to remove those. m_combo->removeItem(pos); } foreach (const int id, changed) { BaseQtVersion *v = mgr->version(id); int pos = findQtVersion(id); if (pos >= 0) // We do not include invalid Qt versions, so do not try to remove those. m_combo->setItemText(pos, v->displayName()); } } void QtKitConfigWidget::manageQtVersions() { Core::ICore::showOptionsDialog(ProjectExplorer::Constants::PROJECTEXPLORER_SETTINGS_CATEGORY, Constants::QTVERSION_SETTINGS_PAGE_ID); } void QtKitConfigWidget::currentWasChanged(int idx) { QtKitInformation::setQtVersionId(m_kit, m_combo->itemData(idx).toInt()); } int QtKitConfigWidget::findQtVersion(const int id) const { for (int i = 0; i < m_combo->count(); ++i) { if (id == m_combo->itemData(i).toInt()) return i; } return -1; } } // namespace Internal } // namespace QtSupport <|endoftext|>
<commit_before>/**************************************************************************** ** ** Copyright (C) 2015 The Qt Company Ltd. ** Contact: http://www.qt.io/licensing ** ** This file is part of Qt Creator. ** ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and The Qt Company. For licensing terms and ** conditions see http://www.qt.io/terms-conditions. For further information ** use the contact form at http://www.qt.io/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 or version 3 as published by the Free ** Software Foundation and appearing in the file LICENSE.LGPLv21 and ** LICENSE.LGPLv3 included in the packaging of this file. Please review the ** following information to ensure the GNU Lesser General Public License ** requirements will be met: https://www.gnu.org/licenses/lgpl.html and ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, The Qt Company gives you certain additional ** rights. These rights are described in The Qt Company LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ****************************************************************************/ #include "snippet.h" #include <coreplugin/id.h> #include <QLatin1Char> #include <QLatin1String> #include <QTextDocument> using namespace TextEditor; const char NOMANGLER_ID[] = "TextEditor::NoMangler"; const char UCMANGLER_ID[] = "TextEditor::UppercaseMangler"; const char LCMANGLER_ID[] = "TextEditor::LowercaseMangler"; const char TCMANGLER_ID[] = "TextEditor::TitlecaseMangler"; Q_DECLARE_METATYPE(QList<int>) // -------------------------------------------------------------------- // Manglers: // -------------------------------------------------------------------- class UppercaseMangler : public NameMangler { public: Core::Id id() const { return UCMANGLER_ID; } QString mangle(const QString &unmangled) const { return unmangled.toUpper(); } }; class LowercaseMangler : public NameMangler { public: Core::Id id() const { return LCMANGLER_ID; } QString mangle(const QString &unmangled) const { return unmangled.toLower(); } }; class TitlecaseMangler : public NameMangler { public: Core::Id id() const { return TCMANGLER_ID; } QString mangle(const QString &unmangled) const { QString result = unmangled; if (!result.isEmpty()) result[0] = unmangled.at(0).toTitleCase(); return result; } }; // -------------------------------------------------------------------- // Snippet: // -------------------------------------------------------------------- const QChar Snippet::kVariableDelimiter(QLatin1Char('$')); Snippet::Snippet(const QString &groupId, const QString &id) : m_isRemoved(false), m_isModified(false), m_groupId(groupId), m_id(id) {} Snippet::~Snippet() {} const QString &Snippet::id() const { return m_id; } const QString &Snippet::groupId() const { return m_groupId; } bool Snippet::isBuiltIn() const { return !m_id.isEmpty(); } void Snippet::setTrigger(const QString &trigger) { m_trigger = trigger; } const QString &Snippet::trigger() const { return m_trigger; } void Snippet::setContent(const QString &content) { m_content = content; } const QString &Snippet::content() const { return m_content; } void Snippet::setComplement(const QString &complement) { m_complement = complement; } const QString &Snippet::complement() const { return m_complement; } void Snippet::setIsRemoved(bool removed) { m_isRemoved = removed; } bool Snippet::isRemoved() const { return m_isRemoved; } void Snippet::setIsModified(bool modified) { m_isModified = modified; } bool Snippet::isModified() const { return m_isModified; } QString Snippet::generateTip() const { static const QLatin1Char kNewLine('\n'); static const QLatin1Char kSpace(' '); static const QLatin1String kBr("<br>"); static const QLatin1String kNbsp("&nbsp;"); static const QLatin1String kNoBr("<nobr>"); static const QLatin1String kOpenBold("<b>"); static const QLatin1String kCloseBold("</b>"); static const QLatin1String kEllipsis("..."); QString escapedContent(m_content.toHtmlEscaped()); escapedContent.replace(kNewLine, kBr); escapedContent.replace(kSpace, kNbsp); QString tip(kNoBr); int count = 0; for (int i = 0; i < escapedContent.count(); ++i) { if (escapedContent.at(i) != kVariableDelimiter) { tip += escapedContent.at(i); continue; } if (++count % 2) { tip += kOpenBold; } else { if (escapedContent.at(i-1) == kVariableDelimiter) tip += kEllipsis; tip += kCloseBold; } } return tip; } Snippet::ParsedSnippet Snippet::parse(const QString &snippet) { static UppercaseMangler ucMangler; static LowercaseMangler lcMangler; static TitlecaseMangler tcMangler; Snippet::ParsedSnippet result; result.success = true; const int count = snippet.count(); bool success = true; int start = -1; NameMangler *mangler = 0; result.text.reserve(count); for (int i = 0; i < count; ++i) { QChar current = snippet.at(i); QChar next = (i + 1) < count ? snippet.at(i + 1) : QChar(); if (current == Snippet::kVariableDelimiter) { if (start < 0) { // start delimiter: start = result.text.count(); } else { int length = result.text.count() - start; result.ranges << ParsedSnippet::Range(start, length, mangler); mangler = 0; start = -1; } continue; } if (mangler) { success = false; break; } if (current == QLatin1Char(':') && start >= 0) { if (mangler != 0) { success = false; break; } if (next == QLatin1Char('l')) { mangler = &lcMangler; } else if (next == QLatin1Char('u')) { mangler = &ucMangler; } else if (next == QLatin1Char('c')) { mangler = &tcMangler; } else { success = false; break; } ++i; continue; } if (current == QLatin1Char('\\')) { if (next.isNull()) { success = false; break; } result.text.append(next); ++i; continue; } result.text.append(current); } if (start >= 0) success = false; result.success = success; if (!success) { result.ranges.clear(); result.text = snippet; } return result; } #ifdef WITH_TESTS # include <QTest> # include "../texteditorplugin.h" void Internal::TextEditorPlugin::testSnippetParsing_data() { QTest::addColumn<QString>("input"); QTest::addColumn<QString>("text"); QTest::addColumn<bool>("success"); QTest::addColumn<QList<int> >("ranges_start"); QTest::addColumn<QList<int> >("ranges_length"); QTest::addColumn<QList<Core::Id> >("ranges_mangler"); QTest::newRow("no input") << QString() << QString() << true << (QList<int>()) << (QList<int>()) << (QList<Core::Id>()); QTest::newRow("empty input") << QString::fromLatin1("") << QString::fromLatin1("") << true << (QList<int>()) << (QList<int>()) << (QList<Core::Id>()); QTest::newRow("simple identifier") << QString::fromLatin1("$tESt$") << QString::fromLatin1("tESt") << true << (QList<int>() << 0) << (QList<int>() << 4) << (QList<Core::Id>() << NOMANGLER_ID); QTest::newRow("simple identifier with lc") << QString::fromLatin1("$tESt:l$") << QString::fromLatin1("tESt") << true << (QList<int>() << 0) << (QList<int>() << 4) << (QList<Core::Id>() << LCMANGLER_ID); QTest::newRow("simple identifier with uc") << QString::fromLatin1("$tESt:u$") << QString::fromLatin1("tESt") << true << (QList<int>() << 0) << (QList<int>() << 4) << (QList<Core::Id>() << UCMANGLER_ID); QTest::newRow("simple identifier with tc") << QString::fromLatin1("$tESt:c$") << QString::fromLatin1("tESt") << true << (QList<int>() << 0) << (QList<int>() << 4) << (QList<Core::Id>() << TCMANGLER_ID); QTest::newRow("escaped string") << QString::fromLatin1("\\$test\\$") << QString::fromLatin1("$test$") << true << (QList<int>()) << (QList<int>()) << (QList<Core::Id>()); QTest::newRow("escaped escape") << QString::fromLatin1("\\\\$test\\\\$") << QString::fromLatin1("\\test\\") << true << (QList<int>() << 1) << (QList<int>() << 5) << (QList<Core::Id>() << NOMANGLER_ID); QTest::newRow("Q_PROPERTY") << QString::fromLatin1("Q_PROPERTY($type$ $name$ READ $name$ WRITE set$name:c$ NOTIFY $name$Changed)") << QString::fromLatin1("Q_PROPERTY(type name READ name WRITE setname NOTIFY nameChanged)") << true << (QList<int>() << 11 << 16 << 26 << 40 << 52) << (QList<int>() << 4 << 4 << 4 << 4 << 4) << (QList<Core::Id>() << NOMANGLER_ID << NOMANGLER_ID << NOMANGLER_ID << TCMANGLER_ID << NOMANGLER_ID); QTest::newRow("broken escape") << QString::fromLatin1("\\\\$test\\\\$\\") << QString::fromLatin1("\\\\$test\\\\$\\") << false << (QList<int>()) << (QList<int>()) << (QList<Core::Id>()); QTest::newRow("open identifier") << QString::fromLatin1("$test") << QString::fromLatin1("$test") << false << (QList<int>()) << (QList<int>()) << (QList<Core::Id>()); QTest::newRow("wrong mangler") << QString::fromLatin1("$test:X$") << QString::fromLatin1("$test:X$") << false << (QList<int>()) << (QList<int>()) << (QList<Core::Id>()); QTest::newRow("multiline with :") << QString::fromLatin1("class $name$\n" "{\n" "public:\n" " $name$() {}\n" "};") << QString::fromLatin1("class name\n" "{\n" "public:\n" " name() {}\n" "};") << true << (QList<int>() << 6 << 25) << (QList<int>() << 4 << 4) << (QList<Core::Id>() << NOMANGLER_ID << NOMANGLER_ID); } void Internal::TextEditorPlugin::testSnippetParsing() { QFETCH(QString, input); QFETCH(QString, text); QFETCH(bool, success); QFETCH(QList<int>, ranges_start); QFETCH(QList<int>, ranges_length); QFETCH(QList<Core::Id>, ranges_mangler); Q_ASSERT(ranges_start.count() == ranges_length.count()); // sanity check for the test data Q_ASSERT(ranges_start.count() == ranges_mangler.count()); // sanity check for the test data Snippet::ParsedSnippet result = Snippet::parse(input); QCOMPARE(result.text, text); QCOMPARE(result.success, success); QCOMPARE(result.ranges.count(), ranges_start.count()); for (int i = 0; i < ranges_start.count(); ++i) { QCOMPARE(result.ranges.at(i).start, ranges_start.at(i)); QCOMPARE(result.ranges.at(i).length, ranges_length.at(i)); Core::Id id = NOMANGLER_ID; if (result.ranges.at(i).mangler) id = result.ranges.at(i).mangler->id(); QCOMPARE(id, ranges_mangler.at(i)); } } #endif <commit_msg>TextEditor: Fix unused variable warning on release build<commit_after>/**************************************************************************** ** ** Copyright (C) 2015 The Qt Company Ltd. ** Contact: http://www.qt.io/licensing ** ** This file is part of Qt Creator. ** ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and The Qt Company. For licensing terms and ** conditions see http://www.qt.io/terms-conditions. For further information ** use the contact form at http://www.qt.io/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 or version 3 as published by the Free ** Software Foundation and appearing in the file LICENSE.LGPLv21 and ** LICENSE.LGPLv3 included in the packaging of this file. Please review the ** following information to ensure the GNU Lesser General Public License ** requirements will be met: https://www.gnu.org/licenses/lgpl.html and ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, The Qt Company gives you certain additional ** rights. These rights are described in The Qt Company LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ****************************************************************************/ #include "snippet.h" #include <coreplugin/id.h> #include <QLatin1Char> #include <QLatin1String> #include <QTextDocument> using namespace TextEditor; const char UCMANGLER_ID[] = "TextEditor::UppercaseMangler"; const char LCMANGLER_ID[] = "TextEditor::LowercaseMangler"; const char TCMANGLER_ID[] = "TextEditor::TitlecaseMangler"; Q_DECLARE_METATYPE(QList<int>) // -------------------------------------------------------------------- // Manglers: // -------------------------------------------------------------------- class UppercaseMangler : public NameMangler { public: Core::Id id() const { return UCMANGLER_ID; } QString mangle(const QString &unmangled) const { return unmangled.toUpper(); } }; class LowercaseMangler : public NameMangler { public: Core::Id id() const { return LCMANGLER_ID; } QString mangle(const QString &unmangled) const { return unmangled.toLower(); } }; class TitlecaseMangler : public NameMangler { public: Core::Id id() const { return TCMANGLER_ID; } QString mangle(const QString &unmangled) const { QString result = unmangled; if (!result.isEmpty()) result[0] = unmangled.at(0).toTitleCase(); return result; } }; // -------------------------------------------------------------------- // Snippet: // -------------------------------------------------------------------- const QChar Snippet::kVariableDelimiter(QLatin1Char('$')); Snippet::Snippet(const QString &groupId, const QString &id) : m_isRemoved(false), m_isModified(false), m_groupId(groupId), m_id(id) {} Snippet::~Snippet() {} const QString &Snippet::id() const { return m_id; } const QString &Snippet::groupId() const { return m_groupId; } bool Snippet::isBuiltIn() const { return !m_id.isEmpty(); } void Snippet::setTrigger(const QString &trigger) { m_trigger = trigger; } const QString &Snippet::trigger() const { return m_trigger; } void Snippet::setContent(const QString &content) { m_content = content; } const QString &Snippet::content() const { return m_content; } void Snippet::setComplement(const QString &complement) { m_complement = complement; } const QString &Snippet::complement() const { return m_complement; } void Snippet::setIsRemoved(bool removed) { m_isRemoved = removed; } bool Snippet::isRemoved() const { return m_isRemoved; } void Snippet::setIsModified(bool modified) { m_isModified = modified; } bool Snippet::isModified() const { return m_isModified; } QString Snippet::generateTip() const { static const QLatin1Char kNewLine('\n'); static const QLatin1Char kSpace(' '); static const QLatin1String kBr("<br>"); static const QLatin1String kNbsp("&nbsp;"); static const QLatin1String kNoBr("<nobr>"); static const QLatin1String kOpenBold("<b>"); static const QLatin1String kCloseBold("</b>"); static const QLatin1String kEllipsis("..."); QString escapedContent(m_content.toHtmlEscaped()); escapedContent.replace(kNewLine, kBr); escapedContent.replace(kSpace, kNbsp); QString tip(kNoBr); int count = 0; for (int i = 0; i < escapedContent.count(); ++i) { if (escapedContent.at(i) != kVariableDelimiter) { tip += escapedContent.at(i); continue; } if (++count % 2) { tip += kOpenBold; } else { if (escapedContent.at(i-1) == kVariableDelimiter) tip += kEllipsis; tip += kCloseBold; } } return tip; } Snippet::ParsedSnippet Snippet::parse(const QString &snippet) { static UppercaseMangler ucMangler; static LowercaseMangler lcMangler; static TitlecaseMangler tcMangler; Snippet::ParsedSnippet result; result.success = true; const int count = snippet.count(); bool success = true; int start = -1; NameMangler *mangler = 0; result.text.reserve(count); for (int i = 0; i < count; ++i) { QChar current = snippet.at(i); QChar next = (i + 1) < count ? snippet.at(i + 1) : QChar(); if (current == Snippet::kVariableDelimiter) { if (start < 0) { // start delimiter: start = result.text.count(); } else { int length = result.text.count() - start; result.ranges << ParsedSnippet::Range(start, length, mangler); mangler = 0; start = -1; } continue; } if (mangler) { success = false; break; } if (current == QLatin1Char(':') && start >= 0) { if (mangler != 0) { success = false; break; } if (next == QLatin1Char('l')) { mangler = &lcMangler; } else if (next == QLatin1Char('u')) { mangler = &ucMangler; } else if (next == QLatin1Char('c')) { mangler = &tcMangler; } else { success = false; break; } ++i; continue; } if (current == QLatin1Char('\\')) { if (next.isNull()) { success = false; break; } result.text.append(next); ++i; continue; } result.text.append(current); } if (start >= 0) success = false; result.success = success; if (!success) { result.ranges.clear(); result.text = snippet; } return result; } #ifdef WITH_TESTS # include <QTest> # include "../texteditorplugin.h" const char NOMANGLER_ID[] = "TextEditor::NoMangler"; void Internal::TextEditorPlugin::testSnippetParsing_data() { QTest::addColumn<QString>("input"); QTest::addColumn<QString>("text"); QTest::addColumn<bool>("success"); QTest::addColumn<QList<int> >("ranges_start"); QTest::addColumn<QList<int> >("ranges_length"); QTest::addColumn<QList<Core::Id> >("ranges_mangler"); QTest::newRow("no input") << QString() << QString() << true << (QList<int>()) << (QList<int>()) << (QList<Core::Id>()); QTest::newRow("empty input") << QString::fromLatin1("") << QString::fromLatin1("") << true << (QList<int>()) << (QList<int>()) << (QList<Core::Id>()); QTest::newRow("simple identifier") << QString::fromLatin1("$tESt$") << QString::fromLatin1("tESt") << true << (QList<int>() << 0) << (QList<int>() << 4) << (QList<Core::Id>() << NOMANGLER_ID); QTest::newRow("simple identifier with lc") << QString::fromLatin1("$tESt:l$") << QString::fromLatin1("tESt") << true << (QList<int>() << 0) << (QList<int>() << 4) << (QList<Core::Id>() << LCMANGLER_ID); QTest::newRow("simple identifier with uc") << QString::fromLatin1("$tESt:u$") << QString::fromLatin1("tESt") << true << (QList<int>() << 0) << (QList<int>() << 4) << (QList<Core::Id>() << UCMANGLER_ID); QTest::newRow("simple identifier with tc") << QString::fromLatin1("$tESt:c$") << QString::fromLatin1("tESt") << true << (QList<int>() << 0) << (QList<int>() << 4) << (QList<Core::Id>() << TCMANGLER_ID); QTest::newRow("escaped string") << QString::fromLatin1("\\$test\\$") << QString::fromLatin1("$test$") << true << (QList<int>()) << (QList<int>()) << (QList<Core::Id>()); QTest::newRow("escaped escape") << QString::fromLatin1("\\\\$test\\\\$") << QString::fromLatin1("\\test\\") << true << (QList<int>() << 1) << (QList<int>() << 5) << (QList<Core::Id>() << NOMANGLER_ID); QTest::newRow("Q_PROPERTY") << QString::fromLatin1("Q_PROPERTY($type$ $name$ READ $name$ WRITE set$name:c$ NOTIFY $name$Changed)") << QString::fromLatin1("Q_PROPERTY(type name READ name WRITE setname NOTIFY nameChanged)") << true << (QList<int>() << 11 << 16 << 26 << 40 << 52) << (QList<int>() << 4 << 4 << 4 << 4 << 4) << (QList<Core::Id>() << NOMANGLER_ID << NOMANGLER_ID << NOMANGLER_ID << TCMANGLER_ID << NOMANGLER_ID); QTest::newRow("broken escape") << QString::fromLatin1("\\\\$test\\\\$\\") << QString::fromLatin1("\\\\$test\\\\$\\") << false << (QList<int>()) << (QList<int>()) << (QList<Core::Id>()); QTest::newRow("open identifier") << QString::fromLatin1("$test") << QString::fromLatin1("$test") << false << (QList<int>()) << (QList<int>()) << (QList<Core::Id>()); QTest::newRow("wrong mangler") << QString::fromLatin1("$test:X$") << QString::fromLatin1("$test:X$") << false << (QList<int>()) << (QList<int>()) << (QList<Core::Id>()); QTest::newRow("multiline with :") << QString::fromLatin1("class $name$\n" "{\n" "public:\n" " $name$() {}\n" "};") << QString::fromLatin1("class name\n" "{\n" "public:\n" " name() {}\n" "};") << true << (QList<int>() << 6 << 25) << (QList<int>() << 4 << 4) << (QList<Core::Id>() << NOMANGLER_ID << NOMANGLER_ID); } void Internal::TextEditorPlugin::testSnippetParsing() { QFETCH(QString, input); QFETCH(QString, text); QFETCH(bool, success); QFETCH(QList<int>, ranges_start); QFETCH(QList<int>, ranges_length); QFETCH(QList<Core::Id>, ranges_mangler); Q_ASSERT(ranges_start.count() == ranges_length.count()); // sanity check for the test data Q_ASSERT(ranges_start.count() == ranges_mangler.count()); // sanity check for the test data Snippet::ParsedSnippet result = Snippet::parse(input); QCOMPARE(result.text, text); QCOMPARE(result.success, success); QCOMPARE(result.ranges.count(), ranges_start.count()); for (int i = 0; i < ranges_start.count(); ++i) { QCOMPARE(result.ranges.at(i).start, ranges_start.at(i)); QCOMPARE(result.ranges.at(i).length, ranges_length.at(i)); Core::Id id = NOMANGLER_ID; if (result.ranges.at(i).mangler) id = result.ranges.at(i).mangler->id(); QCOMPARE(id, ranges_mangler.at(i)); } } #endif <|endoftext|>
<commit_before>/* * Copyright 2013 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "SkFontConfigInterface.h" #include "SkFontConfigTypeface.h" #include "SkFontDescriptor.h" #include "SkFontMgr.h" #include "SkFontMgr_FontConfigInterface.h" #include "SkFontStyle.h" #include "SkMakeUnique.h" #include "SkMutex.h" #include "SkString.h" #include "SkTypeface.h" #include "SkTypefaceCache.h" #include "SkResourceCache.h" #include <new> SkStreamAsset* SkTypeface_FCI::onOpenStream(int* ttcIndex) const { *ttcIndex = this->getIdentity().fTTCIndex; if (fFontData) { SkStreamAsset* stream = fFontData->getStream(); if (!stream) { return nullptr; } return stream->duplicate().release(); } return fFCI->openStream(this->getIdentity()); } std::unique_ptr<SkFontData> SkTypeface_FCI::onMakeFontData() const { if (fFontData) { return skstd::make_unique<SkFontData>(*fFontData); } const SkFontConfigInterface::FontIdentity& id = this->getIdentity(); return skstd::make_unique<SkFontData>(std::unique_ptr<SkStreamAsset>(fFCI->openStream(id)), id.fTTCIndex, nullptr, 0); } void SkTypeface_FCI::onGetFontDescriptor(SkFontDescriptor* desc, bool* isLocalStream) const { SkString name; this->getFamilyName(&name); desc->setFamilyName(name.c_str()); desc->setStyle(this->fontStyle()); *isLocalStream = SkToBool(fFontData); } /////////////////////////////////////////////////////////////////////////////// class SkFontStyleSet_FCI : public SkFontStyleSet { public: SkFontStyleSet_FCI() {} int count() override { return 0; } void getStyle(int index, SkFontStyle*, SkString* style) override { SkASSERT(false); } SkTypeface* createTypeface(int index) override { SkASSERT(false); return nullptr; } SkTypeface* matchStyle(const SkFontStyle& pattern) override { return nullptr; } }; /////////////////////////////////////////////////////////////////////////////// class SkFontRequestCache { public: struct Request : public SkResourceCache::Key { private: Request(const char* name, size_t nameLen, const SkFontStyle& style) : fStyle(style) { /** Pointer to just after the last field of this class. */ char* content = const_cast<char*>(SkTAfter<const char>(&this->fStyle)); // No holes. SkASSERT(SkTAddOffset<char>(this, sizeof(SkResourceCache::Key) + keySize) == content); // Has a size divisible by size of uint32_t. SkASSERT((content - reinterpret_cast<char*>(this)) % sizeof(uint32_t) == 0); size_t contentLen = SkAlign4(nameLen); sk_careful_memcpy(content, name, nameLen); sk_bzero(content + nameLen, contentLen - nameLen); this->init(nullptr, 0, keySize + contentLen); } const SkFontStyle fStyle; /** The sum of the sizes of the fields of this class. */ static const size_t keySize = sizeof(fStyle); public: static Request* Create(const char* name, const SkFontStyle& style) { size_t nameLen = name ? strlen(name) : 0; size_t contentLen = SkAlign4(nameLen); char* storage = new char[sizeof(Request) + contentLen]; return new (storage) Request(name, nameLen, style); } void operator delete(void* storage) { delete[] reinterpret_cast<char*>(storage); } }; private: struct Result : public SkResourceCache::Rec { Result(Request* request, SkTypeface* typeface) : fRequest(request) , fFace(SkSafeRef(typeface)) {} Result(Result&&) = default; Result& operator=(Result&&) = default; const Key& getKey() const override { return *fRequest; } size_t bytesUsed() const override { return fRequest->size() + sizeof(fFace); } const char* getCategory() const override { return "request_cache"; } SkDiscardableMemory* diagnostic_only_getDiscardable() const override { return nullptr; } std::unique_ptr<Request> fRequest; sk_sp<SkTypeface> fFace; }; SkResourceCache fCachedResults; public: SkFontRequestCache(size_t maxSize) : fCachedResults(maxSize) {} /** Takes ownership of request. It will be deleted when no longer needed. */ void add(SkTypeface* face, Request* request) { fCachedResults.add(new Result(request, face)); } /** Does not take ownership of request. */ SkTypeface* findAndRef(Request* request) { SkTypeface* face = nullptr; fCachedResults.find(*request, [](const SkResourceCache::Rec& rec, void* context) -> bool { const Result& result = static_cast<const Result&>(rec); SkTypeface** face = static_cast<SkTypeface**>(context); *face = result.fFace.get(); return true; }, &face); return SkSafeRef(face); } }; /////////////////////////////////////////////////////////////////////////////// static bool find_by_FontIdentity(SkTypeface* cachedTypeface, void* ctx) { typedef SkFontConfigInterface::FontIdentity FontIdentity; SkTypeface_FCI* cachedFCTypeface = static_cast<SkTypeface_FCI*>(cachedTypeface); FontIdentity* identity = static_cast<FontIdentity*>(ctx); return cachedFCTypeface->getIdentity() == *identity; } /////////////////////////////////////////////////////////////////////////////// class SkFontMgr_FCI : public SkFontMgr { sk_sp<SkFontConfigInterface> fFCI; SkTypeface_FreeType::Scanner fScanner; mutable SkMutex fMutex; mutable SkTypefaceCache fTFCache; // The value of maxSize here is a compromise between cache hits and cache size. // See https://crbug.com/424082#63 for reason for current size. static const size_t kMaxSize = 1 << 15; mutable SkFontRequestCache fCache; public: SkFontMgr_FCI(sk_sp<SkFontConfigInterface> fci) : fFCI(std::move(fci)) , fCache(kMaxSize) {} protected: int onCountFamilies() const override { SK_ABORT("Not implemented."); return 0; } void onGetFamilyName(int index, SkString* familyName) const override { SK_ABORT("Not implemented."); } SkFontStyleSet* onCreateStyleSet(int index) const override { SK_ABORT("Not implemented."); return nullptr; } SkFontStyleSet* onMatchFamily(const char familyName[]) const override { SK_ABORT("Not implemented."); return new SkFontStyleSet_FCI(); } SkTypeface* onMatchFamilyStyle(const char familyName[], const SkFontStyle&) const override { SK_ABORT("Not implemented."); return nullptr; } SkTypeface* onMatchFamilyStyleCharacter(const char familyName[], const SkFontStyle&, const char* bcp47[], int bcp47Count, SkUnichar character) const override { SK_ABORT("Not implemented."); return nullptr; } SkTypeface* onMatchFaceStyle(const SkTypeface*, const SkFontStyle&) const override { SK_ABORT("Not implemented."); return nullptr; } sk_sp<SkTypeface> onMakeFromData(sk_sp<SkData>, int ttcIndex) const override { SK_ABORT("Not implemented."); return nullptr; } sk_sp<SkTypeface> onMakeFromStreamIndex(std::unique_ptr<SkStreamAsset> stream, int ttcIndex) const override { const size_t length = stream->getLength(); if (!length) { return nullptr; } if (length >= 1024 * 1024 * 1024) { return nullptr; // don't accept too large fonts (>= 1GB) for safety. } // TODO should the caller give us the style or should we get it from freetype? SkString name; SkFontStyle style; bool isFixedPitch = false; if (!fScanner.scanFont(stream.get(), 0, &name, &style, &isFixedPitch, nullptr)) { return nullptr; } auto fontData = skstd::make_unique<SkFontData>(std::move(stream), ttcIndex, nullptr, 0); return sk_sp<SkTypeface>(SkTypeface_FCI::Create(std::move(fontData), std::move(name), style, isFixedPitch)); } sk_sp<SkTypeface> onMakeFromStreamArgs(std::unique_ptr<SkStreamAsset> stream, const SkFontArguments& args) const override { using Scanner = SkTypeface_FreeType::Scanner; const size_t length = stream->getLength(); if (!length) { return nullptr; } if (length >= 1024 * 1024 * 1024) { return nullptr; // don't accept too large fonts (>= 1GB) for safety. } bool isFixedPitch; SkFontStyle style; SkString name; Scanner::AxisDefinitions axisDefinitions; if (!fScanner.scanFont(stream.get(), args.getCollectionIndex(), &name, &style, &isFixedPitch, &axisDefinitions)) { return nullptr; } SkAutoSTMalloc<4, SkFixed> axisValues(axisDefinitions.count()); Scanner::computeAxisValues(axisDefinitions, args.getVariationDesignPosition(), axisValues, name); auto fontData = skstd::make_unique<SkFontData>(std::move(stream), args.getCollectionIndex(), axisValues.get(), axisDefinitions.count()); return sk_sp<SkTypeface>(SkTypeface_FCI::Create(std::move(fontData), std::move(name), style, isFixedPitch)); } sk_sp<SkTypeface> onMakeFromFile(const char path[], int ttcIndex) const override { std::unique_ptr<SkStreamAsset> stream = SkStream::MakeFromFile(path); return stream ? this->makeFromStream(std::move(stream), ttcIndex) : nullptr; } sk_sp<SkTypeface> onLegacyMakeTypeface(const char requestedFamilyName[], SkFontStyle requestedStyle) const override { SkAutoMutexAcquire ama(fMutex); // Check if this request is already in the request cache. using Request = SkFontRequestCache::Request; std::unique_ptr<Request> request(Request::Create(requestedFamilyName, requestedStyle)); SkTypeface* face = fCache.findAndRef(request.get()); if (face) { return sk_sp<SkTypeface>(face); } SkFontConfigInterface::FontIdentity identity; SkString outFamilyName; SkFontStyle outStyle; if (!fFCI->matchFamilyName(requestedFamilyName, requestedStyle, &identity, &outFamilyName, &outStyle)) { return nullptr; } // Check if a typeface with this FontIdentity is already in the FontIdentity cache. face = fTFCache.findByProcAndRef(find_by_FontIdentity, &identity); if (!face) { face = SkTypeface_FCI::Create(fFCI, identity, std::move(outFamilyName), outStyle); // Add this FontIdentity to the FontIdentity cache. fTFCache.add(face); } // Add this request to the request cache. fCache.add(face, request.release()); return sk_sp<SkTypeface>(face); } }; SK_API sk_sp<SkFontMgr> SkFontMgr_New_FCI(sk_sp<SkFontConfigInterface> fci) { SkASSERT(fci); return sk_make_sp<SkFontMgr_FCI>(std::move(fci)); } <commit_msg>Implement SkFontMgr_FontConfigInterface::onMatchFamilyStyle<commit_after>/* * Copyright 2013 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "SkFontConfigInterface.h" #include "SkFontConfigTypeface.h" #include "SkFontDescriptor.h" #include "SkFontMgr.h" #include "SkFontMgr_FontConfigInterface.h" #include "SkFontStyle.h" #include "SkMakeUnique.h" #include "SkMutex.h" #include "SkString.h" #include "SkTypeface.h" #include "SkTypefaceCache.h" #include "SkResourceCache.h" #include <new> SkStreamAsset* SkTypeface_FCI::onOpenStream(int* ttcIndex) const { *ttcIndex = this->getIdentity().fTTCIndex; if (fFontData) { SkStreamAsset* stream = fFontData->getStream(); if (!stream) { return nullptr; } return stream->duplicate().release(); } return fFCI->openStream(this->getIdentity()); } std::unique_ptr<SkFontData> SkTypeface_FCI::onMakeFontData() const { if (fFontData) { return skstd::make_unique<SkFontData>(*fFontData); } const SkFontConfigInterface::FontIdentity& id = this->getIdentity(); return skstd::make_unique<SkFontData>(std::unique_ptr<SkStreamAsset>(fFCI->openStream(id)), id.fTTCIndex, nullptr, 0); } void SkTypeface_FCI::onGetFontDescriptor(SkFontDescriptor* desc, bool* isLocalStream) const { SkString name; this->getFamilyName(&name); desc->setFamilyName(name.c_str()); desc->setStyle(this->fontStyle()); *isLocalStream = SkToBool(fFontData); } /////////////////////////////////////////////////////////////////////////////// class SkFontStyleSet_FCI : public SkFontStyleSet { public: SkFontStyleSet_FCI() {} int count() override { return 0; } void getStyle(int index, SkFontStyle*, SkString* style) override { SkASSERT(false); } SkTypeface* createTypeface(int index) override { SkASSERT(false); return nullptr; } SkTypeface* matchStyle(const SkFontStyle& pattern) override { return nullptr; } }; /////////////////////////////////////////////////////////////////////////////// class SkFontRequestCache { public: struct Request : public SkResourceCache::Key { private: Request(const char* name, size_t nameLen, const SkFontStyle& style) : fStyle(style) { /** Pointer to just after the last field of this class. */ char* content = const_cast<char*>(SkTAfter<const char>(&this->fStyle)); // No holes. SkASSERT(SkTAddOffset<char>(this, sizeof(SkResourceCache::Key) + keySize) == content); // Has a size divisible by size of uint32_t. SkASSERT((content - reinterpret_cast<char*>(this)) % sizeof(uint32_t) == 0); size_t contentLen = SkAlign4(nameLen); sk_careful_memcpy(content, name, nameLen); sk_bzero(content + nameLen, contentLen - nameLen); this->init(nullptr, 0, keySize + contentLen); } const SkFontStyle fStyle; /** The sum of the sizes of the fields of this class. */ static const size_t keySize = sizeof(fStyle); public: static Request* Create(const char* name, const SkFontStyle& style) { size_t nameLen = name ? strlen(name) : 0; size_t contentLen = SkAlign4(nameLen); char* storage = new char[sizeof(Request) + contentLen]; return new (storage) Request(name, nameLen, style); } void operator delete(void* storage) { delete[] reinterpret_cast<char*>(storage); } }; private: struct Result : public SkResourceCache::Rec { Result(Request* request, SkTypeface* typeface) : fRequest(request) , fFace(SkSafeRef(typeface)) {} Result(Result&&) = default; Result& operator=(Result&&) = default; const Key& getKey() const override { return *fRequest; } size_t bytesUsed() const override { return fRequest->size() + sizeof(fFace); } const char* getCategory() const override { return "request_cache"; } SkDiscardableMemory* diagnostic_only_getDiscardable() const override { return nullptr; } std::unique_ptr<Request> fRequest; sk_sp<SkTypeface> fFace; }; SkResourceCache fCachedResults; public: SkFontRequestCache(size_t maxSize) : fCachedResults(maxSize) {} /** Takes ownership of request. It will be deleted when no longer needed. */ void add(SkTypeface* face, Request* request) { fCachedResults.add(new Result(request, face)); } /** Does not take ownership of request. */ SkTypeface* findAndRef(Request* request) { SkTypeface* face = nullptr; fCachedResults.find(*request, [](const SkResourceCache::Rec& rec, void* context) -> bool { const Result& result = static_cast<const Result&>(rec); SkTypeface** face = static_cast<SkTypeface**>(context); *face = result.fFace.get(); return true; }, &face); return SkSafeRef(face); } }; /////////////////////////////////////////////////////////////////////////////// static bool find_by_FontIdentity(SkTypeface* cachedTypeface, void* ctx) { typedef SkFontConfigInterface::FontIdentity FontIdentity; SkTypeface_FCI* cachedFCTypeface = static_cast<SkTypeface_FCI*>(cachedTypeface); FontIdentity* identity = static_cast<FontIdentity*>(ctx); return cachedFCTypeface->getIdentity() == *identity; } /////////////////////////////////////////////////////////////////////////////// class SkFontMgr_FCI : public SkFontMgr { sk_sp<SkFontConfigInterface> fFCI; SkTypeface_FreeType::Scanner fScanner; mutable SkMutex fMutex; mutable SkTypefaceCache fTFCache; // The value of maxSize here is a compromise between cache hits and cache size. // See https://crbug.com/424082#63 for reason for current size. static const size_t kMaxSize = 1 << 15; mutable SkFontRequestCache fCache; public: SkFontMgr_FCI(sk_sp<SkFontConfigInterface> fci) : fFCI(std::move(fci)) , fCache(kMaxSize) {} protected: int onCountFamilies() const override { SK_ABORT("Not implemented."); return 0; } void onGetFamilyName(int index, SkString* familyName) const override { SK_ABORT("Not implemented."); } SkFontStyleSet* onCreateStyleSet(int index) const override { SK_ABORT("Not implemented."); return nullptr; } SkFontStyleSet* onMatchFamily(const char familyName[]) const override { SK_ABORT("Not implemented."); return new SkFontStyleSet_FCI(); } SkTypeface* onMatchFamilyStyle(const char requestedFamilyName[], const SkFontStyle& requestedStyle) const override { SkAutoMutexAcquire ama(fMutex); SkFontConfigInterface::FontIdentity identity; SkString outFamilyName; SkFontStyle outStyle; if (!fFCI->matchFamilyName(requestedFamilyName, requestedStyle, &identity, &outFamilyName, &outStyle)) { return nullptr; } // Check if a typeface with this FontIdentity is already in the FontIdentity cache. SkTypeface* face = fTFCache.findByProcAndRef(find_by_FontIdentity, &identity); if (!face) { face = SkTypeface_FCI::Create(fFCI, identity, std::move(outFamilyName), outStyle); // Add this FontIdentity to the FontIdentity cache. fTFCache.add(face); } return face; } SkTypeface* onMatchFamilyStyleCharacter(const char familyName[], const SkFontStyle&, const char* bcp47[], int bcp47Count, SkUnichar character) const override { SK_ABORT("Not implemented."); return nullptr; } SkTypeface* onMatchFaceStyle(const SkTypeface*, const SkFontStyle&) const override { SK_ABORT("Not implemented."); return nullptr; } sk_sp<SkTypeface> onMakeFromData(sk_sp<SkData>, int ttcIndex) const override { SK_ABORT("Not implemented."); return nullptr; } sk_sp<SkTypeface> onMakeFromStreamIndex(std::unique_ptr<SkStreamAsset> stream, int ttcIndex) const override { const size_t length = stream->getLength(); if (!length) { return nullptr; } if (length >= 1024 * 1024 * 1024) { return nullptr; // don't accept too large fonts (>= 1GB) for safety. } // TODO should the caller give us the style or should we get it from freetype? SkString name; SkFontStyle style; bool isFixedPitch = false; if (!fScanner.scanFont(stream.get(), 0, &name, &style, &isFixedPitch, nullptr)) { return nullptr; } auto fontData = skstd::make_unique<SkFontData>(std::move(stream), ttcIndex, nullptr, 0); return sk_sp<SkTypeface>(SkTypeface_FCI::Create(std::move(fontData), std::move(name), style, isFixedPitch)); } sk_sp<SkTypeface> onMakeFromStreamArgs(std::unique_ptr<SkStreamAsset> stream, const SkFontArguments& args) const override { using Scanner = SkTypeface_FreeType::Scanner; const size_t length = stream->getLength(); if (!length) { return nullptr; } if (length >= 1024 * 1024 * 1024) { return nullptr; // don't accept too large fonts (>= 1GB) for safety. } bool isFixedPitch; SkFontStyle style; SkString name; Scanner::AxisDefinitions axisDefinitions; if (!fScanner.scanFont(stream.get(), args.getCollectionIndex(), &name, &style, &isFixedPitch, &axisDefinitions)) { return nullptr; } SkAutoSTMalloc<4, SkFixed> axisValues(axisDefinitions.count()); Scanner::computeAxisValues(axisDefinitions, args.getVariationDesignPosition(), axisValues, name); auto fontData = skstd::make_unique<SkFontData>(std::move(stream), args.getCollectionIndex(), axisValues.get(), axisDefinitions.count()); return sk_sp<SkTypeface>(SkTypeface_FCI::Create(std::move(fontData), std::move(name), style, isFixedPitch)); } sk_sp<SkTypeface> onMakeFromFile(const char path[], int ttcIndex) const override { std::unique_ptr<SkStreamAsset> stream = SkStream::MakeFromFile(path); return stream ? this->makeFromStream(std::move(stream), ttcIndex) : nullptr; } sk_sp<SkTypeface> onLegacyMakeTypeface(const char requestedFamilyName[], SkFontStyle requestedStyle) const override { SkAutoMutexAcquire ama(fMutex); // Check if this request is already in the request cache. using Request = SkFontRequestCache::Request; std::unique_ptr<Request> request(Request::Create(requestedFamilyName, requestedStyle)); SkTypeface* face = fCache.findAndRef(request.get()); if (face) { return sk_sp<SkTypeface>(face); } SkFontConfigInterface::FontIdentity identity; SkString outFamilyName; SkFontStyle outStyle; if (!fFCI->matchFamilyName(requestedFamilyName, requestedStyle, &identity, &outFamilyName, &outStyle)) { return nullptr; } // Check if a typeface with this FontIdentity is already in the FontIdentity cache. face = fTFCache.findByProcAndRef(find_by_FontIdentity, &identity); if (!face) { face = SkTypeface_FCI::Create(fFCI, identity, std::move(outFamilyName), outStyle); // Add this FontIdentity to the FontIdentity cache. fTFCache.add(face); } // Add this request to the request cache. fCache.add(face, request.release()); return sk_sp<SkTypeface>(face); } }; SK_API sk_sp<SkFontMgr> SkFontMgr_New_FCI(sk_sp<SkFontConfigInterface> fci) { SkASSERT(fci); return sk_make_sp<SkFontMgr_FCI>(std::move(fci)); } <|endoftext|>
<commit_before>/*-------------neuralnet.cpp--------------------------------------------------// * * Neural Net -- A computational model of a neural network * * Purpose: Before building a purely analog circuit with the BIAS project, we * decided to first develop a computational model of how we expect the * circuit to work in a very algorithmic way. * * Notes: Even though this logic will later be used by the primary BIAS code, * very little analog logic was used in the following script. Rather, * this script was meant to strengthen our own understanding of our * neural system. * * Please let me know if you need any further information! * James Schloss * *-----------------------------------------------------------------------------*/ #include <iostream> #include <vector> #include <time.h> #include <cstdlib> #include <cmath> /*----------------------------------------------------------------------------// * STRUCTURES / FUNCTIONS *-----------------------------------------------------------------------------*/ using namespace std; const int n = 5, tw = 10; // structure for synaptic crossbars struct grid{ double weight[n][n]; vector <vector <bool> > prefire; vector <vector <bool> > postfire; }; // function for filling our synaptic crossbar grid fill_grid(); // function for hebbian learning / weight alteration grid hebbian(grid data, double timestep, double tau); // function for neuron charge collection grid neurosum(grid data, vector <double> thresh, double tau, double timestep); /*----------------------------------------------------------------------------// * MAIN *-----------------------------------------------------------------------------*/ int main(void){ srand(time(NULL)); vector <double> thresh; double tau = 0.2, timestep = 0.1; grid data = fill_grid(); for (int i = 0; i < n; i++){ for (int j = 0; j < n; j++){ cout << data.weight[i][j] << '\t'; } cout << endl << endl; for (int k = 0; k < tw; k++){ cout << data.prefire[i][k]; } cout << endl; } for (int i = 0; i < n; i ++){ thresh.push_back((rand() % 1000 * 0.001) * 10 * n); } data = neurosum(data, thresh, tau, timestep); cout << "Here are our sums: " << endl; for (int i = 0; i < n; i++){ cout << data.postfire[0][i] << endl; } return 0; } /*----------------------------------------------------------------------------// * SUBROUTINES *-----------------------------------------------------------------------------*/ // function for filling our synaptic crossbar grid fill_grid(){ grid data; vector<bool> rn(n,false); // creating initial weights and firing pattern in time window for (int i = 0; i < n; i++){ for (int j = 0; j < n; j++){ data.weight[i][j] = rand() % 1000 * 0.005; } } for (int i = 0; i < tw; i++){ for (int j = 0; j < n; j++){ rn[j] = round(rand() % 10 / 10.0); } data.prefire.push_back(rn); } return data; } // function for hebbian learning / weight alteration // For now, we will assume that each output neuron is attached directly to // its corresponding row. Sure, this is not an ideal situation, but... meh. // // The initial firing pattern of everything will be random. // Because of the way hebbian learning works, we will update the weights twice: // Once after the postsynaptic neuron fires (+weight change) // Again after the presynaptic neuron fires (-weight change) grid hebbian(grid data, double timestep, double tau){ double history[n][n]; vector <bool> rn(n,false); // Following above, positive first, then negative for (int i = 0; i < n; i++){ for (int j = 0; j < n; j++){ history[i][j] = 0; // positive if (data.postfire[i][data.postfire[i].size()] == 1){ for (int k = 0; k < tw; k++){ if (data.prefire[i][k] == 1){ history[i][j] += tw - k; } } } // Here we are updating the prefire, we will need to change the // weights negatively. rn[i] = round(rand() % 10 / 10.0); } } data.prefire.erase(data.prefire.begin()); data.prefire.push_back(rn); for (int i = 0; i < n; i++){ for (int j = 0; j < n; j++){ if (rn[i] == 1){ for (int k = 0; k < tw; k++){ history[i][j] -= tw - k; } } } } for (int i = 0; i < n; i++){ for (int j = 0; j < n; j++){ data.weight[i][j] = exp(history[i][j]); } } return data; } // function for neuron charge collection grid neurosum(grid data, vector <double> thresh, double tau, double timestep){ vector <bool> sum(tw, false); vector<double> cumulative(n, false); double pt_cumulative = 0, t; for (int i = 0; i < n; i++){ cumulative[i] = 0; for (int j = 0; j < n; j++){ pt_cumulative = 0; for (unsigned int k = 0; k < data.prefire.size(); k++){ t = k * timestep; pt_cumulative += data.prefire[i][k] * exp(-(t * tau)); } cumulative[i] += pt_cumulative; } } for (int i = 0; i < n; i++){ if (cumulative[i] > thresh[i]) { sum[i] = 1; } else{ sum[i] = 0; } } data.postfire.push_back(sum); return data; } <commit_msg>fixed a bug that kept the weights from updating negatively.<commit_after>/*-------------neuralnet.cpp--------------------------------------------------// * * Neural Net -- A computational model of a neural network * * Purpose: Before building a purely analog circuit with the BIAS project, we * decided to first develop a computational model of how we expect the * circuit to work in a very algorithmic way. * * Notes: Even though this logic will later be used by the primary BIAS code, * very little analog logic was used in the following script. Rather, * this script was meant to strengthen our own understanding of our * neural system. * * Please let me know if you need any further information! * James Schloss * *-----------------------------------------------------------------------------*/ #include <iostream> #include <vector> #include <time.h> #include <cstdlib> #include <cmath> /*----------------------------------------------------------------------------// * STRUCTURES / FUNCTIONS *-----------------------------------------------------------------------------*/ using namespace std; const int n = 5, tw = 10; // structure for synaptic crossbars struct grid{ double weight[n][n]; vector <vector <bool> > prefire; vector <vector <bool> > postfire; }; // function for filling our synaptic crossbar grid fill_grid(); // function for hebbian learning / weight alteration grid hebbian(grid data, double timestep, double tau); // function for neuron charge collection grid neurosum(grid data, vector <double> thresh, double tau, double timestep); /*----------------------------------------------------------------------------// * MAIN *-----------------------------------------------------------------------------*/ int main(void){ srand(time(NULL)); vector <double> thresh; double tau = 0.2, timestep = 0.1; grid data = fill_grid(); for (int i = 0; i < n; i++){ for (int j = 0; j < n; j++){ cout << data.weight[i][j] << '\t'; } cout << endl << endl; for (int k = 0; k < tw; k++){ cout << data.prefire[i][k]; } cout << endl; } for (int i = 0; i < n; i ++){ thresh.push_back((rand() % 1000 * 0.001) * 10 * n); } data = neurosum(data, thresh, tau, timestep); cout << "Here are our sums: " << endl; for (int i = 0; i < n; i++){ cout << data.postfire[0][i] << endl; } return 0; } /*----------------------------------------------------------------------------// * SUBROUTINES *-----------------------------------------------------------------------------*/ // function for filling our synaptic crossbar grid fill_grid(){ grid data; vector<bool> rn(n,false); // creating initial weights and firing pattern in time window for (int i = 0; i < n; i++){ for (int j = 0; j < n; j++){ data.weight[i][j] = rand() % 1000 * 0.005; } } for (int i = 0; i < tw; i++){ for (int j = 0; j < n; j++){ rn[j] = round(rand() % 10 / 10.0); } data.prefire.push_back(rn); } return data; } // function for hebbian learning / weight alteration // For now, we will assume that each output neuron is attached directly to // its corresponding row. Sure, this is not an ideal situation, but... meh. // // The initial firing pattern of everything will be random. // Because of the way hebbian learning works, we will update the weights twice: // Once after the postsynaptic neuron fires (+weight change) // Again after the presynaptic neuron fires (-weight change) grid hebbian(grid data, double timestep, double tau){ double history[n][n]; vector <bool> rn(n,false); // Following above, positive first, then negative for (int i = 0; i < n; i++){ for (int j = 0; j < n; j++){ history[i][j] = 0; // positive if (data.postfire[i][data.postfire[i].size()] == 1){ for (int k = 0; k < tw; k++){ if (data.prefire[i][k] == 1){ history[i][j] += tw - k; } } } // Here we are updating the prefire, we will need to change the // weights negatively. rn[i] = round(rand() % 10 / 10.0); } } data.prefire.erase(data.prefire.begin()); data.prefire.push_back(rn); for (int i = 0; i < n; i++){ for (int j = 0; j < n; j++){ if (rn[i] == 1){ for (int k = 0; k < tw; k++){ if (data.postfire[i][k] == 1){ history[i][j] -= tw - k; } } } } } for (int i = 0; i < n; i++){ for (int j = 0; j < n; j++){ data.weight[i][j] = exp(history[i][j]); } } return data; } // function for neuron charge collection grid neurosum(grid data, vector <double> thresh, double tau, double timestep){ vector <bool> sum(tw, false); vector<double> cumulative(n, false); double pt_cumulative = 0, t; for (int i = 0; i < n; i++){ cumulative[i] = 0; for (int j = 0; j < n; j++){ pt_cumulative = 0; for (unsigned int k = 0; k < data.prefire.size(); k++){ t = k * timestep; pt_cumulative += data.prefire[i][k] * exp(-(t * tau)); } cumulative[i] += pt_cumulative; } } for (int i = 0; i < n; i++){ if (cumulative[i] > thresh[i]) { sum[i] = 1; } else{ sum[i] = 0; } } data.postfire.push_back(sum); return data; } <|endoftext|>
<commit_before>//------------------------------------------------------------------------------ // oryol-shdc //------------------------------------------------------------------------------ #include "ExportUtil/CmdLineArgs.h" #include "ExportUtil/Log.h" #include "spirv_hlsl.hpp" #include "spirv_msl.hpp" #include "pystring.h" #include "cJSON.h" #include <stdio.h> using namespace OryolTools; using namespace spv; using namespace spirv_cross; using namespace std; //------------------------------------------------------------------------------ vector<uint32_t> read_spirv_file(const string& path) { FILE* fp = fopen(path.c_str(), "rb"); if (!fp) { Log::Fatal("Failed to open SPIRV file '%s'\n", path.c_str()); } fseek(fp, 0, SEEK_END); long len = ftell(fp) / sizeof(uint32_t); fseek(fp, 0, SEEK_SET); vector<uint32_t> spirv(len); if (fread(spirv.data(), sizeof(uint32_t), len, fp) != size_t(len)) { Log::Fatal("Error reading SPIRV file '%s'\n", path.c_str()); } fclose(fp); return spirv; } //------------------------------------------------------------------------------ void write_source_file(const string& path, const string& content) { FILE* fp = fopen(path.c_str(), "w"); if (!fp) { Log::Fatal("Failed to open '%s' for writing\n", path.c_str()); } fwrite(content.c_str(), 1, content.length(), fp); fclose(fp); } //------------------------------------------------------------------------------ const char* type_to_uniform_type(const SPIRType& type) { if (type.basetype == SPIRType::Float) { if (type.columns == 1) { // scalar or vec switch (type.vecsize) { case 1: return "float"; case 2: return "vec2"; case 3: return "vec3"; case 4: return "vec4"; } } else { // a matrix if ((type.vecsize == 2) && (type.columns == 2)) { return "mat2"; } else if ((type.vecsize == 3) && (type.columns == 3)) { return "mat3"; } else if ((type.vecsize == 4) && (type.columns == 4)) { return "mat4"; } } } else if (type.basetype == SPIRType::Int) { return "int"; } else if (type.basetype == SPIRType::Boolean) { return "bool"; } Log::Fatal("Invalid member type in uniform block! (expected: float, vec2, vec3, vec4, mat2, mat3, mat4, int, bool)\n"); return nullptr; } //------------------------------------------------------------------------------ const char* type_to_attr_format(const SPIRType& type) { if (type.basetype == SPIRType::Float && type.columns == 1) { switch (type.vecsize) { case 1: return "float"; case 2: return "vec2"; case 3: return "vec3"; case 4: return "vec4"; } } Log::Fatal("Invalid vertex attribute type! (expected: float, vec2, vec3, vec4)\n"); return nullptr; } //------------------------------------------------------------------------------ cJSON* extract_resource_info(Compiler* compiler) { cJSON* root = cJSON_CreateObject(); // shader stage const char* stage_str = nullptr; switch (compiler->get_execution_model()) { case ExecutionModelVertex: stage_str = "vs"; break; case ExecutionModelFragment: stage_str = "fs"; break; default: break; } if (stage_str) { cJSON_AddItemToObject(root, "stage", cJSON_CreateString(stage_str)); } else { Log::Fatal("only vertex- or fragment-shaders allowed!\n"); } // uniform blocks int ub_slot = 0; ShaderResources res = compiler->get_shader_resources(); cJSON* ub_array = cJSON_CreateArray(); cJSON_AddItemToObject(root, "uniform_blocks", ub_array); for (const Resource& ub_res : res.uniform_buffers) { const SPIRType& ub_type = compiler->get_type(ub_res.base_type_id); cJSON* ub = cJSON_CreateObject(); cJSON_AddItemToArray(ub_array, ub); cJSON_AddItemToObject(ub, "type", cJSON_CreateString(ub_res.name.c_str())); cJSON_AddItemToObject(ub, "name", cJSON_CreateString(compiler->get_name(ub_res.id).c_str())); cJSON_AddItemToObject(ub, "slot", cJSON_CreateNumber(ub_slot++)); cJSON* ub_members = cJSON_CreateArray(); cJSON_AddItemToObject(ub, "members", ub_members); for (int m_index = 0; m_index < int(ub_type.member_types.size()); m_index++) { cJSON* ub_member = cJSON_CreateObject(); cJSON_AddItemToArray(ub_members, ub_member); string m_name = compiler->get_member_name(ub_res.base_type_id, m_index); const SPIRType& m_type = compiler->get_type(ub_type.member_types[m_index]); const char* m_type_str = type_to_uniform_type(m_type); cJSON_AddItemToObject(ub_member, "name", cJSON_CreateString(m_name.c_str())); cJSON_AddItemToObject(ub_member, "type", cJSON_CreateString(m_type_str)); int num = 1; if (m_type.array.size() > 0) { num = m_type.array[0]; } cJSON_AddItemToObject(ub_member, "num", cJSON_CreateNumber(num)); } } // textures int tex_slot = 0; cJSON* tex_array = cJSON_CreateArray(); cJSON_AddItemToObject(root, "textures", tex_array); for (const Resource& img_res : res.sampled_images) { const SPIRType& img_type = compiler->get_type(img_res.type_id); cJSON* tex = cJSON_CreateObject(); cJSON_AddItemToArray(tex_array, tex); const char* tex_type_str = nullptr; if (img_type.image.arrayed) { if (img_type.image.dim == Dim2D) { tex_type_str = "sampler2DArray"; } } else { switch (img_type.image.dim) { case Dim2D: tex_type_str = "sampler2D"; break; case DimCube: tex_type_str = "samplerCube"; break; case Dim3D: tex_type_str = "sampler3D"; break; default: break; } } if (!tex_type_str) { Log::Fatal("Invalid texture type! (expected: 2D, Cube, 3D or 2D-array)\n"); } cJSON_AddItemToObject(tex, "name", cJSON_CreateString(img_res.name.c_str())); cJSON_AddItemToObject(tex, "type", cJSON_CreateString(tex_type_str)); cJSON_AddItemToObject(tex, "slot", cJSON_CreateNumber(tex_slot++)); } // stage inputs cJSON* inputs_array = cJSON_CreateArray(); cJSON_AddItemToObject(root, "inputs", inputs_array); for (const Resource& stage_input : res.stage_inputs) { cJSON* input = cJSON_CreateObject(); cJSON_AddItemToArray(inputs_array, input); const SPIRType& type = compiler->get_type(stage_input.base_type_id); const char* type_str = type_to_attr_format(type); cJSON_AddItemToObject(input, "name", cJSON_CreateString(stage_input.name.c_str())); cJSON_AddItemToObject(input, "type", cJSON_CreateString(type_str)); if (compiler->get_execution_model() == ExecutionModelVertex) { uint32_t loc = compiler->get_decoration(stage_input.id, DecorationLocation); cJSON_AddItemToObject(input, "slot", cJSON_CreateNumber(loc)); } } // stage outputs cJSON* outputs_array = cJSON_CreateArray(); cJSON_AddItemToObject(root, "outputs", outputs_array); for (const Resource& stage_output : res.stage_outputs) { cJSON* output = cJSON_CreateObject(); cJSON_AddItemToArray(outputs_array, output); const SPIRType& type = compiler->get_type(stage_output.base_type_id); const char* type_str = type_to_attr_format(type); cJSON_AddItemToObject(output, "name", cJSON_CreateString(stage_output.name.c_str())); cJSON_AddItemToObject(output, "type", cJSON_CreateString(type_str)); } return root; } //------------------------------------------------------------------------------ void fix_vertex_attr_locations(Compiler* compiler) { if (compiler->get_execution_model() == ExecutionModelVertex) { ShaderResources res = compiler->get_shader_resources(); for (const auto& input : res.stage_inputs) { int loc = -1; if (input.name == "position") loc = 0; else if (input.name == "normal") loc = 1; else if (input.name == "texcoord0") loc = 2; else if (input.name == "texcoord1") loc = 3; else if (input.name == "texcoord2") loc = 4; else if (input.name == "texcoord3") loc = 5; else if (input.name == "tangent") loc = 6; else if (input.name == "binormal") loc = 7; else if (input.name == "weights") loc = 8; else if (input.name == "indices") loc = 9; else if (input.name == "color0") loc = 10; else if (input.name == "color1") loc = 11; else if (input.name == "instance0") loc = 12; else if (input.name == "instance1") loc = 13; else if (input.name == "instance2") loc = 14; else if (input.name == "instance3") loc = 15; if (-1 != loc) { compiler->set_decoration(input.id, DecorationLocation, (uint32_t)loc); } } } } //------------------------------------------------------------------------------ void to_reflection_json(const vector<uint32_t>& spirv, const string& base_path) { CompilerGLSL compiler(spirv); fix_vertex_attr_locations(&compiler); cJSON* json = extract_resource_info(&compiler); char* json_raw_str = cJSON_Print(json); string json_str(json_raw_str); std::free(json_raw_str); cJSON_Delete(json); write_source_file(base_path + ".json", json_str); } //------------------------------------------------------------------------------ void to_glsl_100(const vector<uint32_t>& spirv, const string& base_path) { CompilerGLSL compiler(spirv); auto opts = compiler.get_options(); opts.version = 100; opts.es = true; compiler.set_options(opts); fix_vertex_attr_locations(&compiler); string src = compiler.compile(); if (src.empty()) { Log::Fatal("Failed to compile GLSL v100 source for '%s'!\n", base_path.c_str()); } else { write_source_file(base_path + ".glsl100.glsl", src); } } //------------------------------------------------------------------------------ void to_glsl_120(const vector<uint32_t>& spirv, const string& base_path) { CompilerGLSL compiler(spirv); auto opts = compiler.get_options(); opts.version = 120; opts.es = false; compiler.set_options(opts); fix_vertex_attr_locations(&compiler); string src = compiler.compile(); if (src.empty()) { Log::Fatal("Failed to compile GLSL v120 source for '%s'!\n", base_path.c_str()); } else { write_source_file(base_path + ".glsl120.glsl", src); } } //------------------------------------------------------------------------------ void to_glsl_es3(const vector<uint32_t>& spirv, const string& base_path) { CompilerGLSL compiler(spirv); auto opts = compiler.get_options(); opts.version = 300; opts.es = true; compiler.set_options(opts); fix_vertex_attr_locations(&compiler); string src = compiler.compile(); if (src.empty()) { Log::Fatal("Failed to compile GLSL es3 source for '%s'!\n", base_path.c_str()); } else { write_source_file(base_path + ".glsles3.glsl", src); } } //------------------------------------------------------------------------------ void to_glsl_330(const vector<uint32_t>& spirv, const string& base_path) { CompilerGLSL compiler(spirv); auto opts = compiler.get_options(); opts.version = 330; opts.es = false; compiler.set_options(opts); fix_vertex_attr_locations(&compiler); string src = compiler.compile(); if (src.empty()) { Log::Fatal("Failed to compile GLSL v330 source for '%s'!\n", base_path.c_str()); } else { write_source_file(base_path + ".glsl330.glsl", src); } } //------------------------------------------------------------------------------ void to_hlsl_sm5(const vector<uint32_t>& spirv, const string& base_path) { CompilerHLSL compiler(spirv); auto opts = compiler.get_options(); opts.shader_model = 50; compiler.set_options(opts); fix_vertex_attr_locations(&compiler); string src = compiler.compile(); if (src.empty()) { Log::Fatal("Failed to compile HLSL5 source for '%s'!\n", base_path.c_str()); } else { write_source_file(base_path + ".hlsl", src); } } //------------------------------------------------------------------------------ void to_mlsl(const vector<uint32_t>& spirv, const string& base_path) { CompilerMSL compiler(spirv); fix_vertex_attr_locations(&compiler); string src = compiler.compile(); if (src.empty()) { Log::Fatal("Failed to compile MetalSL source for '%s'!\n", base_path.c_str()); } else { write_source_file(base_path + ".metal", src); } } //------------------------------------------------------------------------------ int main(int argc, const char** argv) { CmdLineArgs args; args.AddBool("-help", "show help"); args.AddString("-spirv", "SPIR-V input file", ""); if (!args.Parse(argc, argv)) { Log::Warn("Failed to parse args!\n"); return 10; } if (args.HasArg("-help")) { Log::Info("Oryol SPIR-V to GLSL/HLSL/MSL cross-compiler\n" "Based on SPIRV-Cross: https://github.com/KhronosGroup/SPIRV-Cross\n"); args.ShowHelp(); return 0; } string spirv_path = args.GetString("-spirv"); if (spirv_path.empty()) { Log::Fatal("-spirv arg expected"); } // load SPIRV byte code auto spirv = read_spirv_file(spirv_path); // ...translate and write to output files... string base_path, ext; pystring::os::path::splitext(base_path, ext, spirv_path); to_reflection_json(spirv, base_path); to_glsl_100(spirv, base_path); to_glsl_120(spirv, base_path); to_glsl_es3(spirv, base_path); to_glsl_330(spirv, base_path); // to_hlsl_sm5(spirv, base_path); // to_mlsl(spirv, base_path); return 0; } <commit_msg>shdc: simplify saving glsl variants<commit_after>//------------------------------------------------------------------------------ // oryol-shdc //------------------------------------------------------------------------------ #include "ExportUtil/CmdLineArgs.h" #include "ExportUtil/Log.h" #include "spirv_hlsl.hpp" #include "spirv_msl.hpp" #include "pystring.h" #include "cJSON.h" #include <stdio.h> using namespace OryolTools; using namespace spv; using namespace spirv_cross; using namespace std; //------------------------------------------------------------------------------ vector<uint32_t> read_spirv_file(const string& path) { FILE* fp = fopen(path.c_str(), "rb"); if (!fp) { Log::Fatal("Failed to open SPIRV file '%s'\n", path.c_str()); } fseek(fp, 0, SEEK_END); long len = ftell(fp) / sizeof(uint32_t); fseek(fp, 0, SEEK_SET); vector<uint32_t> spirv(len); if (fread(spirv.data(), sizeof(uint32_t), len, fp) != size_t(len)) { Log::Fatal("Error reading SPIRV file '%s'\n", path.c_str()); } fclose(fp); return spirv; } //------------------------------------------------------------------------------ void write_source_file(const string& path, const string& content) { FILE* fp = fopen(path.c_str(), "w"); if (!fp) { Log::Fatal("Failed to open '%s' for writing\n", path.c_str()); } fwrite(content.c_str(), 1, content.length(), fp); fclose(fp); } //------------------------------------------------------------------------------ const char* type_to_uniform_type(const SPIRType& type) { if (type.basetype == SPIRType::Float) { if (type.columns == 1) { // scalar or vec switch (type.vecsize) { case 1: return "float"; case 2: return "vec2"; case 3: return "vec3"; case 4: return "vec4"; } } else { // a matrix if ((type.vecsize == 2) && (type.columns == 2)) { return "mat2"; } else if ((type.vecsize == 3) && (type.columns == 3)) { return "mat3"; } else if ((type.vecsize == 4) && (type.columns == 4)) { return "mat4"; } } } else if (type.basetype == SPIRType::Int) { return "int"; } else if (type.basetype == SPIRType::Boolean) { return "bool"; } Log::Fatal("Invalid member type in uniform block! (expected: float, vec2, vec3, vec4, mat2, mat3, mat4, int, bool)\n"); return nullptr; } //------------------------------------------------------------------------------ const char* type_to_attr_format(const SPIRType& type) { if (type.basetype == SPIRType::Float && type.columns == 1) { switch (type.vecsize) { case 1: return "float"; case 2: return "vec2"; case 3: return "vec3"; case 4: return "vec4"; } } Log::Fatal("Invalid vertex attribute type! (expected: float, vec2, vec3, vec4)\n"); return nullptr; } //------------------------------------------------------------------------------ cJSON* extract_resource_info(Compiler* compiler) { cJSON* root = cJSON_CreateObject(); // shader stage const char* stage_str = nullptr; switch (compiler->get_execution_model()) { case ExecutionModelVertex: stage_str = "vs"; break; case ExecutionModelFragment: stage_str = "fs"; break; default: break; } if (stage_str) { cJSON_AddItemToObject(root, "stage", cJSON_CreateString(stage_str)); } else { Log::Fatal("only vertex- or fragment-shaders allowed!\n"); } // uniform blocks int ub_slot = 0; ShaderResources res = compiler->get_shader_resources(); cJSON* ub_array = cJSON_CreateArray(); cJSON_AddItemToObject(root, "uniform_blocks", ub_array); for (const Resource& ub_res : res.uniform_buffers) { const SPIRType& ub_type = compiler->get_type(ub_res.base_type_id); cJSON* ub = cJSON_CreateObject(); cJSON_AddItemToArray(ub_array, ub); cJSON_AddItemToObject(ub, "type", cJSON_CreateString(ub_res.name.c_str())); cJSON_AddItemToObject(ub, "name", cJSON_CreateString(compiler->get_name(ub_res.id).c_str())); cJSON_AddItemToObject(ub, "slot", cJSON_CreateNumber(ub_slot++)); cJSON* ub_members = cJSON_CreateArray(); cJSON_AddItemToObject(ub, "members", ub_members); for (int m_index = 0; m_index < int(ub_type.member_types.size()); m_index++) { cJSON* ub_member = cJSON_CreateObject(); cJSON_AddItemToArray(ub_members, ub_member); string m_name = compiler->get_member_name(ub_res.base_type_id, m_index); const SPIRType& m_type = compiler->get_type(ub_type.member_types[m_index]); const char* m_type_str = type_to_uniform_type(m_type); cJSON_AddItemToObject(ub_member, "name", cJSON_CreateString(m_name.c_str())); cJSON_AddItemToObject(ub_member, "type", cJSON_CreateString(m_type_str)); int num = 1; if (m_type.array.size() > 0) { num = m_type.array[0]; } cJSON_AddItemToObject(ub_member, "num", cJSON_CreateNumber(num)); } } // textures int tex_slot = 0; cJSON* tex_array = cJSON_CreateArray(); cJSON_AddItemToObject(root, "textures", tex_array); for (const Resource& img_res : res.sampled_images) { const SPIRType& img_type = compiler->get_type(img_res.type_id); cJSON* tex = cJSON_CreateObject(); cJSON_AddItemToArray(tex_array, tex); const char* tex_type_str = nullptr; if (img_type.image.arrayed) { if (img_type.image.dim == Dim2D) { tex_type_str = "sampler2DArray"; } } else { switch (img_type.image.dim) { case Dim2D: tex_type_str = "sampler2D"; break; case DimCube: tex_type_str = "samplerCube"; break; case Dim3D: tex_type_str = "sampler3D"; break; default: break; } } if (!tex_type_str) { Log::Fatal("Invalid texture type! (expected: 2D, Cube, 3D or 2D-array)\n"); } cJSON_AddItemToObject(tex, "name", cJSON_CreateString(img_res.name.c_str())); cJSON_AddItemToObject(tex, "type", cJSON_CreateString(tex_type_str)); cJSON_AddItemToObject(tex, "slot", cJSON_CreateNumber(tex_slot++)); } // stage inputs cJSON* inputs_array = cJSON_CreateArray(); cJSON_AddItemToObject(root, "inputs", inputs_array); for (const Resource& stage_input : res.stage_inputs) { cJSON* input = cJSON_CreateObject(); cJSON_AddItemToArray(inputs_array, input); const SPIRType& type = compiler->get_type(stage_input.base_type_id); const char* type_str = type_to_attr_format(type); cJSON_AddItemToObject(input, "name", cJSON_CreateString(stage_input.name.c_str())); cJSON_AddItemToObject(input, "type", cJSON_CreateString(type_str)); if (compiler->get_execution_model() == ExecutionModelVertex) { uint32_t loc = compiler->get_decoration(stage_input.id, DecorationLocation); cJSON_AddItemToObject(input, "slot", cJSON_CreateNumber(loc)); } } // stage outputs cJSON* outputs_array = cJSON_CreateArray(); cJSON_AddItemToObject(root, "outputs", outputs_array); for (const Resource& stage_output : res.stage_outputs) { cJSON* output = cJSON_CreateObject(); cJSON_AddItemToArray(outputs_array, output); const SPIRType& type = compiler->get_type(stage_output.base_type_id); const char* type_str = type_to_attr_format(type); cJSON_AddItemToObject(output, "name", cJSON_CreateString(stage_output.name.c_str())); cJSON_AddItemToObject(output, "type", cJSON_CreateString(type_str)); } return root; } //------------------------------------------------------------------------------ void fix_vertex_attr_locations(Compiler* compiler) { if (compiler->get_execution_model() == ExecutionModelVertex) { ShaderResources res = compiler->get_shader_resources(); for (const auto& input : res.stage_inputs) { int loc = -1; if (input.name == "position") loc = 0; else if (input.name == "normal") loc = 1; else if (input.name == "texcoord0") loc = 2; else if (input.name == "texcoord1") loc = 3; else if (input.name == "texcoord2") loc = 4; else if (input.name == "texcoord3") loc = 5; else if (input.name == "tangent") loc = 6; else if (input.name == "binormal") loc = 7; else if (input.name == "weights") loc = 8; else if (input.name == "indices") loc = 9; else if (input.name == "color0") loc = 10; else if (input.name == "color1") loc = 11; else if (input.name == "instance0") loc = 12; else if (input.name == "instance1") loc = 13; else if (input.name == "instance2") loc = 14; else if (input.name == "instance3") loc = 15; if (-1 != loc) { compiler->set_decoration(input.id, DecorationLocation, (uint32_t)loc); } } } } //------------------------------------------------------------------------------ void to_reflection_json(const vector<uint32_t>& spirv, const string& base_path) { CompilerGLSL compiler(spirv); fix_vertex_attr_locations(&compiler); cJSON* json = extract_resource_info(&compiler); char* json_raw_str = cJSON_Print(json); string json_str(json_raw_str); std::free(json_raw_str); cJSON_Delete(json); write_source_file(base_path + ".json", json_str); } //------------------------------------------------------------------------------ void to_glsl(const vector<uint32_t>& spirv, const string& base_path, const string& file_ext, uint32_t version, bool is_es) { CompilerGLSL compiler(spirv); auto opts = compiler.get_options(); opts.version = version; opts.es = is_es; opts.vertex.fixup_clipspace = false; compiler.set_options(opts); fix_vertex_attr_locations(&compiler); string src = compiler.compile(); if (src.empty()) { Log::Fatal("Failed to compile GLSL v100 source for '%s'!\n", base_path.c_str()); } else { write_source_file(base_path + file_ext, src); } } //------------------------------------------------------------------------------ void to_hlsl_sm5(const vector<uint32_t>& spirv, const string& base_path) { CompilerHLSL compiler(spirv); auto opts = compiler.get_options(); opts.shader_model = 50; compiler.set_options(opts); fix_vertex_attr_locations(&compiler); string src = compiler.compile(); if (src.empty()) { Log::Fatal("Failed to compile HLSL5 source for '%s'!\n", base_path.c_str()); } else { write_source_file(base_path + ".hlsl", src); } } //------------------------------------------------------------------------------ void to_mlsl(const vector<uint32_t>& spirv, const string& base_path) { CompilerMSL compiler(spirv); fix_vertex_attr_locations(&compiler); string src = compiler.compile(); if (src.empty()) { Log::Fatal("Failed to compile MetalSL source for '%s'!\n", base_path.c_str()); } else { write_source_file(base_path + ".metal", src); } } //------------------------------------------------------------------------------ int main(int argc, const char** argv) { CmdLineArgs args; args.AddBool("-help", "show help"); args.AddString("-spirv", "SPIR-V input file", ""); if (!args.Parse(argc, argv)) { Log::Warn("Failed to parse args!\n"); return 10; } if (args.HasArg("-help")) { Log::Info("Oryol SPIR-V to GLSL/HLSL/MSL cross-compiler\n" "Based on SPIRV-Cross: https://github.com/KhronosGroup/SPIRV-Cross\n"); args.ShowHelp(); return 0; } string spirv_path = args.GetString("-spirv"); if (spirv_path.empty()) { Log::Fatal("-spirv arg expected"); } // load SPIRV byte code auto spirv = read_spirv_file(spirv_path); // ...translate and write to output files... string base_path, ext; pystring::os::path::splitext(base_path, ext, spirv_path); to_reflection_json(spirv, base_path); to_glsl(spirv, base_path, ".glsl100.glsl", 100, true); to_glsl(spirv, base_path, ".glsl120.glsl", 120, false); to_glsl(spirv, base_path, ".glsles3.glsl", 300, true); to_glsl(spirv, base_path, ".glsl330.glsl", 330, false); // to_hlsl_sm5(spirv, base_path); // to_mlsl(spirv, base_path); return 0; } <|endoftext|>
<commit_before>/* Copyright (c) 2006, Arvid Norberg All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef ROUTING_TABLE_HPP #define ROUTING_TABLE_HPP #include <vector> #include <deque> #include <boost/cstdint.hpp> #include <boost/date_time/posix_time/posix_time.hpp> #include <boost/iterator/iterator_facade.hpp> #include <boost/iterator/iterator_categories.hpp> #include <boost/utility.hpp> #include <boost/tuple/tuple.hpp> #include <boost/array.hpp> #include <libtorrent/kademlia/logging.hpp> #include <libtorrent/kademlia/node_id.hpp> #include <libtorrent/kademlia/node_entry.hpp> #include <libtorrent/session_settings.hpp> namespace pt = boost::posix_time; namespace libtorrent { namespace dht { using asio::ip::udp; //TORRENT_DECLARE_LOG(table); typedef std::deque<node_entry> bucket_t; // differences in the implementation from the description in // the paper: // // * The routing table tree is not allocated dynamically, there // are always 160 buckets. // * Nodes are not marked as being stale, they keep a counter // that tells how many times in a row they have failed. When // a new node is to be inserted, the node that has failed // the most times is replaced. If none of the nodes in the // bucket has failed, then it is put in the replacement // cache (just like in the paper). class routing_table; namespace aux { // Iterates over a flattened routing_table structure. class routing_table_iterator : public boost::iterator_facade< routing_table_iterator , node_entry const , boost::forward_traversal_tag > { public: routing_table_iterator() { } private: friend class libtorrent::dht::routing_table; friend class boost::iterator_core_access; typedef boost::array<std::pair<bucket_t, bucket_t>, 160>::const_iterator bucket_iterator_t; routing_table_iterator( bucket_iterator_t begin , bucket_iterator_t end) : m_bucket_iterator(begin) , m_bucket_end(end) , m_iterator(begin != end ? begin->first.begin() : bucket_t::iterator()) { if (m_bucket_iterator == m_bucket_end) return; while (m_iterator == m_bucket_iterator->first.end()) { if (++m_bucket_iterator == m_bucket_end) break; m_iterator = m_bucket_iterator->first.begin(); } } bool equal(routing_table_iterator const& other) const { return m_bucket_iterator == other.m_bucket_iterator && (m_bucket_iterator == m_bucket_end || m_iterator == other.m_iterator); } void increment() { assert(m_bucket_iterator != m_bucket_end); ++m_iterator; while (m_iterator == m_bucket_iterator->first.end()) { if (++m_bucket_iterator == m_bucket_end) break; m_iterator = m_bucket_iterator->first.begin(); } } node_entry const& dereference() const { assert(m_bucket_iterator != m_bucket_end); return *m_iterator; } bucket_iterator_t m_bucket_iterator; bucket_iterator_t m_bucket_end; bucket_t::const_iterator m_iterator; }; } // namespace aux class routing_table { public: typedef aux::routing_table_iterator iterator; typedef iterator const_iterator; routing_table(node_id const& id, int bucket_size , dht_settings const& settings); void node_failed(node_id const& id); // adds an endpoint that will never be added to // the routing table void add_router_node(udp::endpoint router); // iterates over the router nodes added typedef std::set<udp::endpoint>::const_iterator router_iterator; router_iterator router_begin() const { return m_router_nodes.begin(); } router_iterator router_end() const { return m_router_nodes.end(); } // this function is called every time the node sees // a sign of a node being alive. This node will either // be inserted in the k-buckets or be moved to the top // of its bucket. bool node_seen(node_id const& id, udp::endpoint addr); // returns time when the given bucket needs another refresh. // if the given bucket is empty but there are nodes // in a bucket closer to us, or if the bucket is non-empty and // the time from the last activity is more than 15 minutes boost::posix_time::ptime next_refresh(int bucket); // fills the vector with the count nodes from our buckets that // are nearest to the given id. void find_node(node_id const& id, std::vector<node_entry>& l , bool include_self, int count = 0); // returns true if the given node would be placed in a bucket // that is not full. If the node already exists in the table // this function returns false bool need_node(node_id const& id); // this will set the given bucket's latest activity // to the current time void touch_bucket(int bucket); int bucket_size(int bucket) { assert(bucket >= 0 && bucket < 160); return (int)m_buckets[bucket].first.size(); } int bucket_size() const { return m_bucket_size; } iterator begin() const; iterator end() const; boost::tuple<int, int> size() const; // returns true if there are no working nodes // in the routing table bool need_bootstrap() const; void replacement_cache(bucket_t& nodes) const; // used for debug and monitoring purposes. This will print out // the state of the routing table to the given stream void print_state(std::ostream& os) const; private: // constant called k in paper int m_bucket_size; dht_settings const& m_settings; // 160 (k-bucket, replacement cache) pairs typedef boost::array<std::pair<bucket_t, bucket_t>, 160> table_t; table_t m_buckets; // timestamps of the last activity in each bucket typedef boost::array<boost::posix_time::ptime, 160> table_activity_t; table_activity_t m_bucket_activity; node_id m_id; // our own node id // this is a set of all the endpoints that have // been identified as router nodes. They will // be used in searches, but they will never // be added to the routing table. std::set<udp::endpoint> m_router_nodes; // this is the lowest bucket index with nodes in it int m_lowest_active_bucket; }; } } // namespace libtorrent::dht #endif // ROUTING_TABLE_HPP <commit_msg>added missing include of set.hpp<commit_after>/* Copyright (c) 2006, Arvid Norberg All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef ROUTING_TABLE_HPP #define ROUTING_TABLE_HPP #include <vector> #include <deque> #include <boost/cstdint.hpp> #include <boost/date_time/posix_time/posix_time.hpp> #include <boost/iterator/iterator_facade.hpp> #include <boost/iterator/iterator_categories.hpp> #include <boost/utility.hpp> #include <boost/tuple/tuple.hpp> #include <boost/array.hpp> #include <set.hpp> #include <libtorrent/kademlia/logging.hpp> #include <libtorrent/kademlia/node_id.hpp> #include <libtorrent/kademlia/node_entry.hpp> #include <libtorrent/session_settings.hpp> namespace pt = boost::posix_time; namespace libtorrent { namespace dht { using asio::ip::udp; //TORRENT_DECLARE_LOG(table); typedef std::deque<node_entry> bucket_t; // differences in the implementation from the description in // the paper: // // * The routing table tree is not allocated dynamically, there // are always 160 buckets. // * Nodes are not marked as being stale, they keep a counter // that tells how many times in a row they have failed. When // a new node is to be inserted, the node that has failed // the most times is replaced. If none of the nodes in the // bucket has failed, then it is put in the replacement // cache (just like in the paper). class routing_table; namespace aux { // Iterates over a flattened routing_table structure. class routing_table_iterator : public boost::iterator_facade< routing_table_iterator , node_entry const , boost::forward_traversal_tag > { public: routing_table_iterator() { } private: friend class libtorrent::dht::routing_table; friend class boost::iterator_core_access; typedef boost::array<std::pair<bucket_t, bucket_t>, 160>::const_iterator bucket_iterator_t; routing_table_iterator( bucket_iterator_t begin , bucket_iterator_t end) : m_bucket_iterator(begin) , m_bucket_end(end) , m_iterator(begin != end ? begin->first.begin() : bucket_t::iterator()) { if (m_bucket_iterator == m_bucket_end) return; while (m_iterator == m_bucket_iterator->first.end()) { if (++m_bucket_iterator == m_bucket_end) break; m_iterator = m_bucket_iterator->first.begin(); } } bool equal(routing_table_iterator const& other) const { return m_bucket_iterator == other.m_bucket_iterator && (m_bucket_iterator == m_bucket_end || m_iterator == other.m_iterator); } void increment() { assert(m_bucket_iterator != m_bucket_end); ++m_iterator; while (m_iterator == m_bucket_iterator->first.end()) { if (++m_bucket_iterator == m_bucket_end) break; m_iterator = m_bucket_iterator->first.begin(); } } node_entry const& dereference() const { assert(m_bucket_iterator != m_bucket_end); return *m_iterator; } bucket_iterator_t m_bucket_iterator; bucket_iterator_t m_bucket_end; bucket_t::const_iterator m_iterator; }; } // namespace aux class routing_table { public: typedef aux::routing_table_iterator iterator; typedef iterator const_iterator; routing_table(node_id const& id, int bucket_size , dht_settings const& settings); void node_failed(node_id const& id); // adds an endpoint that will never be added to // the routing table void add_router_node(udp::endpoint router); // iterates over the router nodes added typedef std::set<udp::endpoint>::const_iterator router_iterator; router_iterator router_begin() const { return m_router_nodes.begin(); } router_iterator router_end() const { return m_router_nodes.end(); } // this function is called every time the node sees // a sign of a node being alive. This node will either // be inserted in the k-buckets or be moved to the top // of its bucket. bool node_seen(node_id const& id, udp::endpoint addr); // returns time when the given bucket needs another refresh. // if the given bucket is empty but there are nodes // in a bucket closer to us, or if the bucket is non-empty and // the time from the last activity is more than 15 minutes boost::posix_time::ptime next_refresh(int bucket); // fills the vector with the count nodes from our buckets that // are nearest to the given id. void find_node(node_id const& id, std::vector<node_entry>& l , bool include_self, int count = 0); // returns true if the given node would be placed in a bucket // that is not full. If the node already exists in the table // this function returns false bool need_node(node_id const& id); // this will set the given bucket's latest activity // to the current time void touch_bucket(int bucket); int bucket_size(int bucket) { assert(bucket >= 0 && bucket < 160); return (int)m_buckets[bucket].first.size(); } int bucket_size() const { return m_bucket_size; } iterator begin() const; iterator end() const; boost::tuple<int, int> size() const; // returns true if there are no working nodes // in the routing table bool need_bootstrap() const; void replacement_cache(bucket_t& nodes) const; // used for debug and monitoring purposes. This will print out // the state of the routing table to the given stream void print_state(std::ostream& os) const; private: // constant called k in paper int m_bucket_size; dht_settings const& m_settings; // 160 (k-bucket, replacement cache) pairs typedef boost::array<std::pair<bucket_t, bucket_t>, 160> table_t; table_t m_buckets; // timestamps of the last activity in each bucket typedef boost::array<boost::posix_time::ptime, 160> table_activity_t; table_activity_t m_bucket_activity; node_id m_id; // our own node id // this is a set of all the endpoints that have // been identified as router nodes. They will // be used in searches, but they will never // be added to the routing table. std::set<udp::endpoint> m_router_nodes; // this is the lowest bucket index with nodes in it int m_lowest_active_bucket; }; } } // namespace libtorrent::dht #endif // ROUTING_TABLE_HPP <|endoftext|>
<commit_before>/** @addtogroup Synchronization * @{ * \copyright TU Dresden ZIH. All rights reserved. * \authors Martin Flehmig, Marc Hartung, Marcus Walther * \date Oct 2015 */ #ifndef INCLUDE_SYNCHRONIZATION_SERIALDATAHISTORY_HPP_ #define INCLUDE_SYNCHRONIZATION_SERIALDATAHISTORY_HPP_ #include "Stdafx.hpp" #include "BasicTypedefs.hpp" #include "synchronization/SubHistory.hpp" #include "synchronization/AbstractDataHistory.hpp" #include "synchronization/HistoryEntry.hpp" namespace Synchronization { /** * @todo We should move the handling of the writer to this class */ class SerialDataHistory : public AbstractDataHistory { public: /** * Creaete SerialDataHistory element from parameters. * @param numFmus Number of FMUs. * @param numConns Number of connections between the FMUs. */ //SerialDataHistory(size_type numFmus, size_type numConns, InterpolationSPtr interpol); SerialDataHistory(const Initialization::HistoryPlan & in); /** * Destroy the object. */ ~SerialDataHistory(); void addFmu(FMI::AbstractFmu * fmu, std::vector<ConnectionSPtr> & connList) override; /** * Deletes all entries in the [num]-th sub-history, which are older than [tIn] * @param tIn Point_type of time determine which entries should be deleted * @param id Determines which subhistory should be cleaned. */ void deleteOlderThan(real_type tIn, size_type id) override; /** * Inserts a HistoryEntryPtr into the num-th subhistory * @param in The entry which should be inserted into the history * @param id The number of sub-history in which the entry should be inserted * @return If false, the Entry couldn't be saved. This can happen, when too much data is already stored in the history. True on success. */ bool_type insert(const HistoryEntry & in, size_type id, WriteInfo write) override; FMI::ValueCollection getInputValues(const size_type & id, const real_type & time) override; /** * Getter for a const sub-history element. * Sub history should only be changed by the DataHistory, not by any other class. This ensures, that the DataHistory alone takes care about thread-safety. * @param id Id of the subhistory which should be returned. * @return Returns sub-history according to the passed id */ const RingBufferSubHistory & getHistory(size_type id) const override; /** * Getter for a const sub-history element. * Sub history should only be changed by the DataHistory, not by any other class. This ensures, that the DataHistory alone takes care about thread-safety. * @param id Id of the subhistory which should be returned. * @return Returns sub-history according to the passed id */ const RingBufferSubHistory & getInputHistory(size_type id) const override; /** * Compares the latest entries of all sub-histories and returns the time of the oldest entry. * @return The saved timestamp of the FMU which is is slowest in time at the moment */ real_type getOldestSubHistoryTime() override; /** * Determines if enough data is collected, to write values of the observed FMUs in to a file. * If all FMUs passed a point_type of time, where data should be written to a file, the function returns true and getWriteOutput() returns than necessary data. * @return true, if all FMUs passed a write output time point. */ bool_type hasWriteOutput() override; /** * Returns data which should be written to file. * @return A tuple with a valid timestamp and a non-empty vector, where each element points to a ValueCollection if hasWriteOutput() was called before and returned true. * If no data can't be written at the called time, it returns a std::numeric_limits<value_type>::max() as timestamp in the tuple. */ tuple<real_type, vector<FMI::ValueCollection> > getWriteOutput() override; private: struct WriteCollectionLine { size_type count; bool_type isEvent; vector<FMI::ValueCollection> data; }; typedef std::map<real_type, WriteCollectionLine> WriteStack; typedef pair<real_type, WriteCollectionLine> WriteStackPair; typedef list<tuple<real_type,vector<FMI::ValueCollection> > > WriteList; WriteStack _toWriteStack; WriteList _readyToWrite; void popWriteStack(); }; } /* namespace Synchronization */ #endif /* INCLUDE_SYNCHRONIZATION_SERIALDATAHISTORY_HPP_ */ /** * @} */ <commit_msg>Remove unused include<commit_after>/** @addtogroup Synchronization * @{ * \copyright TU Dresden ZIH. All rights reserved. * \authors Martin Flehmig, Marc Hartung, Marcus Walther * \date Oct 2015 */ #ifndef INCLUDE_SYNCHRONIZATION_SERIALDATAHISTORY_HPP_ #define INCLUDE_SYNCHRONIZATION_SERIALDATAHISTORY_HPP_ #include "Stdafx.hpp" #include "BasicTypedefs.hpp" //#include "synchronization/SubHistory.hpp" #include "synchronization/AbstractDataHistory.hpp" #include "synchronization/HistoryEntry.hpp" namespace Synchronization { /** * @todo We should move the handling of the writer to this class */ class SerialDataHistory : public AbstractDataHistory { public: /** * Creaete SerialDataHistory element from parameters. * @param numFmus Number of FMUs. * @param numConns Number of connections between the FMUs. */ //SerialDataHistory(size_type numFmus, size_type numConns, InterpolationSPtr interpol); SerialDataHistory(const Initialization::HistoryPlan & in); /** * Destroy the object. */ ~SerialDataHistory(); void addFmu(FMI::AbstractFmu * fmu, std::vector<ConnectionSPtr> & connList) override; /** * Deletes all entries in the [num]-th sub-history, which are older than [tIn] * @param tIn Point_type of time determine which entries should be deleted * @param id Determines which subhistory should be cleaned. */ void deleteOlderThan(real_type tIn, size_type id) override; /** * Inserts a HistoryEntryPtr into the num-th subhistory * @param in The entry which should be inserted into the history * @param id The number of sub-history in which the entry should be inserted * @return If false, the Entry couldn't be saved. This can happen, when too much data is already stored in the history. True on success. */ bool_type insert(const HistoryEntry & in, size_type id, WriteInfo write) override; FMI::ValueCollection getInputValues(const size_type & id, const real_type & time) override; /** * Getter for a const sub-history element. * Sub history should only be changed by the DataHistory, not by any other class. This ensures, that the DataHistory alone takes care about thread-safety. * @param id Id of the subhistory which should be returned. * @return Returns sub-history according to the passed id */ const RingBufferSubHistory & getHistory(size_type id) const override; /** * Getter for a const sub-history element. * Sub history should only be changed by the DataHistory, not by any other class. This ensures, that the DataHistory alone takes care about thread-safety. * @param id Id of the subhistory which should be returned. * @return Returns sub-history according to the passed id */ const RingBufferSubHistory & getInputHistory(size_type id) const override; /** * Compares the latest entries of all sub-histories and returns the time of the oldest entry. * @return The saved timestamp of the FMU which is is slowest in time at the moment */ real_type getOldestSubHistoryTime() override; /** * Determines if enough data is collected, to write values of the observed FMUs in to a file. * If all FMUs passed a point_type of time, where data should be written to a file, the function returns true and getWriteOutput() returns than necessary data. * @return true, if all FMUs passed a write output time point. */ bool_type hasWriteOutput() override; /** * Returns data which should be written to file. * @return A tuple with a valid timestamp and a non-empty vector, where each element points to a ValueCollection if hasWriteOutput() was called before and returned true. * If no data can't be written at the called time, it returns a std::numeric_limits<value_type>::max() as timestamp in the tuple. */ tuple<real_type, vector<FMI::ValueCollection> > getWriteOutput() override; private: struct WriteCollectionLine { size_type count; bool_type isEvent; vector<FMI::ValueCollection> data; }; typedef std::map<real_type, WriteCollectionLine> WriteStack; typedef pair<real_type, WriteCollectionLine> WriteStackPair; typedef list<tuple<real_type,vector<FMI::ValueCollection> > > WriteList; WriteStack _toWriteStack; WriteList _readyToWrite; void popWriteStack(); }; } /* namespace Synchronization */ #endif /* INCLUDE_SYNCHRONIZATION_SERIALDATAHISTORY_HPP_ */ /** * @} */ <|endoftext|>
<commit_before>#include "os/win32/win32.h" #include <windowsx.h> #include <assert.h> #include "GL/glew.h" #include "GL/wglew.h" Sigma::event::KeyboardInputSystem IOpSys::KeyboardEventSystem; // Handles keyboard events Sigma::event::MouseInputSystem IOpSys::MouseEventSystem; // Handles keyboard events double IOpSys::curDelta; int win32::keyUp[256]; int win32::mousePos[2]; win32::~win32() { wglMakeCurrent(this->hdc, 0); // Remove the rendering context from our device context wglDeleteContext(this->hrc); // Delete our rendering context ReleaseDC(this->hwnd, this->hdc); // Release the device context from our window } void win32::ToggleFullscreen() { if (this->fullscreen) { SetWindowLongPtr(this->hwnd, GWL_STYLE, WS_OVERLAPPED | WS_CAPTION | WS_SYSMENU | WS_MINIMIZEBOX | WS_VISIBLE); MoveWindow(this->hwnd, this->windowedSize.left, this->windowedSize.top, this->windowedSize.right - this->windowedSize.left, this->windowedSize.bottom - this->windowedSize.top, TRUE); } else { // Save the current windowed position GetWindowRect(this->hwnd, &this->windowedSize); SetWindowLongPtr(this->hwnd, GWL_STYLE, WS_SYSMENU | WS_POPUP | WS_CLIPCHILDREN | WS_CLIPSIBLINGS | WS_VISIBLE); // Get the monitor info about the monitor the window is most over. HMONITOR hmon = MonitorFromWindow(this->hwnd, MONITOR_DEFAULTTONEAREST); MONITORINFO monInfo; monInfo.cbSize = sizeof(MONITORINFO); GetMonitorInfo(hmon, &monInfo); // Move the window and resize it to take up the whole monitor MoveWindow(this->hwnd, monInfo.rcMonitor.left, monInfo.rcMonitor.top, monInfo.rcMonitor.right - monInfo.rcMonitor.left, monInfo.rcMonitor.bottom - monInfo.rcMonitor.top, TRUE); } this->fullscreen = !this->fullscreen; } void* win32::CreateGraphicsWindow(const unsigned int width, const unsigned int height) { WNDCLASS windowClass; //HWND hwnd; DWORD dwExStyle = WS_EX_APPWINDOW | WS_EX_WINDOWEDGE; hInstance = GetModuleHandle(NULL); windowClass.style = CS_HREDRAW | CS_VREDRAW | CS_OWNDC; windowClass.lpfnWndProc = (WNDPROC) WndProc; windowClass.cbClsExtra = 0; windowClass.cbWndExtra = 0; windowClass.hInstance = hInstance; windowClass.hIcon = LoadIcon(NULL, IDI_WINLOGO); windowClass.hCursor = LoadCursor(NULL, IDC_ARROW); windowClass.hbrBackground = NULL; windowClass.lpszMenuName = NULL; windowClass.lpszClassName = "GL Test Window"; this->windowedSize.left = 50; this->windowedSize.top = 50; this->windowedSize.right = width+50; this->windowedSize.bottom = height+50; AdjustWindowRectEx(&this->windowedSize, WS_OVERLAPPED | WS_CAPTION | WS_SYSMENU | WS_MINIMIZEBOX, false, dwExStyle); if (!RegisterClass(&windowClass)) { return false; } this->hwnd = CreateWindowEx(dwExStyle, windowClass.lpszClassName, windowClass.lpszClassName, WS_OVERLAPPED | WS_CAPTION | WS_SYSMENU | WS_MINIMIZEBOX, this->windowedSize.left, this->windowedSize.top, this->windowedSize.right - this->windowedSize.left, this->windowedSize.bottom - this->windowedSize.top, NULL, NULL, hInstance, NULL); assert(this->hwnd != 0); // Now that we have created the window to the size we want, we must get the correct client size and store that. GetClientRect(this->hwnd, &this->windowedSize); ShowWindow(this->hwnd, SW_SHOW); UpdateWindow(this->hwnd); POINT midwindow = {512,384}; ClientToScreen(this->hwnd, &midwindow); SetCursorPos(midwindow.x, midwindow.y); StartOpengGL(); return this->hdc; } bool win32::mouselook = false; LRESULT CALLBACK win32::WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) { bool mouseMoved = false; POINT midwindow = {512,384}; switch (message) { case WM_KEYUP: KeyboardEventSystem.KeyUp(wParam); keyUp[wParam] = 1; return 0; break; case WM_KEYDOWN: KeyboardEventSystem.KeyDown(wParam); return 0; break; case WM_CHAR: KeyboardEventSystem.CharDown(wParam); return 0; break; case WM_MOUSEMOVE: if (mouselook) { mouseMoved = true; if ((abs(GET_X_LPARAM(lParam) - midwindow.x) > 2) && (abs(GET_Y_LPARAM(lParam) - midwindow.y) > 2)) { MouseEventSystem.MouseMove((GET_X_LPARAM(lParam) - midwindow.x) / 1024.0f * 500.0f, (GET_Y_LPARAM(lParam) - midwindow.y) / 768.0f * 500.0f); } else if (abs(GET_X_LPARAM(lParam) - midwindow.x) > 2) { MouseEventSystem.MouseMove((GET_X_LPARAM(lParam) - midwindow.x) / 1024.0f * 500.0f, 0.0f); } else if (abs(GET_Y_LPARAM(lParam) - midwindow.y) > 2) { MouseEventSystem.MouseMove(0.0f, (GET_Y_LPARAM(lParam) - midwindow.y) / 768.0f * 500.0f); } else { mouseMoved = false; } ClientToScreen(hWnd, &midwindow); SetCursorPos(midwindow.x, midwindow.y); } break; case WM_LBUTTONDOWN: MouseEventSystem.MouseDown(Sigma::event::BUTTON::LEFT, GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam)); break; case WM_LBUTTONUP: MouseEventSystem.MouseUp(Sigma::event::BUTTON::LEFT, GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam)); break; case WM_RBUTTONDOWN: ShowCursor(false); mouselook = true; SetCursorPos(midwindow.x, midwindow.y); break; case WM_RBUTTONUP: ShowCursor(true); mouselook = false; break; case WM_DESTROY: PostQuitMessage(0); break; } if (!mouseMoved) { MouseEventSystem.MouseMove(0.f, 0.f); } return DefWindowProc(hWnd, message, wParam, lParam); } bool win32::MessageLoop() { MSG msg; ZeroMemory(keyUp, sizeof(keyUp)); if (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE)) { // If we have a message to process, process it if (msg.message == WM_QUIT) { return false; } else { TranslateMessage(&msg); DispatchMessage(&msg); } } Sleep(1); return true; } bool win32::SetupTimer() { LARGE_INTEGER li; if(!QueryPerformanceFrequency(&li)) { return false; } this->frequency = static_cast<double>(li.QuadPart)/1000.0; QueryPerformanceCounter(&li); this->lastTime = li.QuadPart; return true; } double win32::GetDeltaTime() { LARGE_INTEGER li; QueryPerformanceCounter(&li); double delta = static_cast<double>(li.QuadPart - this->lastTime); this->lastTime = li.QuadPart; return this->curDelta = delta/this->frequency; } bool win32::KeyDown(int key, bool focused) { if (focused) { if (this->hwnd != GetFocus()) { return false; } } short k = GetKeyState(key); return (k & 0x80) > 0 ? true : false; } const int* win32::StartOpengGL() { this->fullscreen = false; this->OpenGLVersion[0] = -1; this->OpenGLVersion[1] = -1; this->hdc = GetDC(this->hwnd); // Get the device context for our window PIXELFORMATDESCRIPTOR pfd; memset(&pfd, 0, sizeof(PIXELFORMATDESCRIPTOR)); pfd.nSize = sizeof(PIXELFORMATDESCRIPTOR); pfd.nVersion = 1; pfd.dwFlags = PFD_DOUBLEBUFFER | PFD_SUPPORT_OPENGL | PFD_DRAW_TO_WINDOW; pfd.iPixelType = PFD_TYPE_RGBA; pfd.cColorBits = 32; pfd.cDepthBits = 32; pfd.iLayerType = PFD_MAIN_PLANE; int nPixelFormat = ChoosePixelFormat(this->hdc, &pfd); if (nPixelFormat == 0) { return this->OpenGLVersion; } BOOL bResult = SetPixelFormat (this->hdc, nPixelFormat, &pfd); if (!bResult) { return this->OpenGLVersion; } HGLRC tempContext = wglCreateContext(this->hdc); if(!tempContext) { assert(0 && "Failed to create temp context!"); } if(!wglMakeCurrent(this->hdc, tempContext)) { assert(0 && "Invalid temp context, cannot make current!"); } int attribs[] = { WGL_CONTEXT_MAJOR_VERSION_ARB, 3, WGL_CONTEXT_MINOR_VERSION_ARB, 1, 0,0,0 }; PFNWGLCREATECONTEXTATTRIBSARBPROC wglCreateContextAttribsARB = (PFNWGLCREATECONTEXTATTRIBSARBPROC)wglGetProcAddress("wglCreateContextAttribsARB"); if (!wglCreateContextAttribsARB) { assert(0 && "Unable to create GL 3.x context."); //It's not possible to make a GL 3.x context. Use the old style context (GL 2.1 and before) this->hrc = tempContext; } else { this->hrc = wglCreateContextAttribsARB(this->hdc, 0, attribs); } if (!this->hrc) { assert(0 && "Failed to make context!"); } if (!wglMakeCurrent(this->hdc, this->hrc)) { assert(0 && "Invalid context, cannot make current!"); } else { wglDeleteContext(tempContext); } GLuint error = glewInit(); if (error != GLEW_OK) { return OpenGLVersion; } //Checking GL version const GLubyte *GLVersionString = glGetString(GL_VERSION); //Or better yet, use the GL3 way to get the version number glGetIntegerv(GL_MAJOR_VERSION, &OpenGLVersion[0]); glGetIntegerv(GL_MINOR_VERSION, &OpenGLVersion[1]); // Set options for depth tests. glEnable(GL_DEPTH_TEST); glDepthFunc(GL_LESS); return OpenGLVersion; } void win32::Present(int fbo_id) { SwapBuffers(this->hdc); // Swap buffers so we can see our rendering. } bool win32::KeyReleased(int key, bool focused /*= false*/) { if (focused) { if (this->hwnd != GetFocus()) { return false; } } return (keyUp[key] != 0 ? true : false); } bool win32::KeyUp(int key, bool focused /*= false */) { if (focused) { if (this->hwnd != GetFocus()) { return false; } } short k = GetKeyState(key); return (k & 0x80) > 0 ? false : true; } unsigned int win32::GetWindowWidth() { if (fullscreen) { // Get the monitor info about the monitor the window is most over. HMONITOR hmon = MonitorFromWindow(this->hwnd, MONITOR_DEFAULTTONEAREST); MONITORINFO monInfo; monInfo.cbSize = sizeof(MONITORINFO); GetMonitorInfo(hmon, &monInfo); return monInfo.rcMonitor.right - monInfo.rcMonitor.left; } else { return this->windowedSize.right - this->windowedSize.left; } } unsigned int win32::GetWindowHeight() { if (fullscreen) { // Get the monitor info about the monitor the window is most over. HMONITOR hmon = MonitorFromWindow(this->hwnd, MONITOR_DEFAULTTONEAREST); MONITORINFO monInfo; monInfo.cbSize = sizeof(MONITORINFO); GetMonitorInfo(hmon, &monInfo); return monInfo.rcMonitor.bottom - monInfo.rcMonitor.top; } else { return this->windowedSize.bottom - this->windowedSize.top; } } void IOpSys::Quit() { PostQuitMessage(0); } <commit_msg>Removed hard coding from win32 WndPRoc<commit_after>#include "os/win32/win32.h" #include <windowsx.h> #include <assert.h> #include "GL/glew.h" #include "GL/wglew.h" Sigma::event::KeyboardInputSystem IOpSys::KeyboardEventSystem; // Handles keyboard events Sigma::event::MouseInputSystem IOpSys::MouseEventSystem; // Handles keyboard events double IOpSys::curDelta; int win32::keyUp[256]; int win32::mousePos[2]; win32::~win32() { wglMakeCurrent(this->hdc, 0); // Remove the rendering context from our device context wglDeleteContext(this->hrc); // Delete our rendering context ReleaseDC(this->hwnd, this->hdc); // Release the device context from our window } void win32::ToggleFullscreen() { if (this->fullscreen) { SetWindowLongPtr(this->hwnd, GWL_STYLE, WS_OVERLAPPED | WS_CAPTION | WS_SYSMENU | WS_MINIMIZEBOX | WS_VISIBLE); MoveWindow(this->hwnd, this->windowedSize.left, this->windowedSize.top, this->windowedSize.right - this->windowedSize.left, this->windowedSize.bottom - this->windowedSize.top, TRUE); } else { // Save the current windowed position GetWindowRect(this->hwnd, &this->windowedSize); SetWindowLongPtr(this->hwnd, GWL_STYLE, WS_SYSMENU | WS_POPUP | WS_CLIPCHILDREN | WS_CLIPSIBLINGS | WS_VISIBLE); // Get the monitor info about the monitor the window is most over. HMONITOR hmon = MonitorFromWindow(this->hwnd, MONITOR_DEFAULTTONEAREST); MONITORINFO monInfo; monInfo.cbSize = sizeof(MONITORINFO); GetMonitorInfo(hmon, &monInfo); // Move the window and resize it to take up the whole monitor MoveWindow(this->hwnd, monInfo.rcMonitor.left, monInfo.rcMonitor.top, monInfo.rcMonitor.right - monInfo.rcMonitor.left, monInfo.rcMonitor.bottom - monInfo.rcMonitor.top, TRUE); } this->fullscreen = !this->fullscreen; } void* win32::CreateGraphicsWindow(const unsigned int width, const unsigned int height) { WNDCLASS windowClass; //HWND hwnd; DWORD dwExStyle = WS_EX_APPWINDOW | WS_EX_WINDOWEDGE; hInstance = GetModuleHandle(NULL); windowClass.style = CS_HREDRAW | CS_VREDRAW | CS_OWNDC; windowClass.lpfnWndProc = (WNDPROC) WndProc; windowClass.cbClsExtra = 0; windowClass.cbWndExtra = 0; windowClass.hInstance = hInstance; windowClass.hIcon = LoadIcon(NULL, IDI_WINLOGO); windowClass.hCursor = LoadCursor(NULL, IDC_ARROW); windowClass.hbrBackground = NULL; windowClass.lpszMenuName = NULL; windowClass.lpszClassName = "GL Test Window"; this->windowedSize.left = 50; this->windowedSize.top = 50; this->windowedSize.right = width+50; this->windowedSize.bottom = height+50; AdjustWindowRectEx(&this->windowedSize, WS_OVERLAPPED | WS_CAPTION | WS_SYSMENU | WS_MINIMIZEBOX, false, dwExStyle); if (!RegisterClass(&windowClass)) { return false; } this->hwnd = CreateWindowEx(dwExStyle, windowClass.lpszClassName, windowClass.lpszClassName, WS_OVERLAPPED | WS_CAPTION | WS_SYSMENU | WS_MINIMIZEBOX, this->windowedSize.left, this->windowedSize.top, this->windowedSize.right - this->windowedSize.left, this->windowedSize.bottom - this->windowedSize.top, NULL, NULL, hInstance, NULL); assert(this->hwnd != 0); // Now that we have created the window to the size we want, we must get the correct client size and store that. GetClientRect(this->hwnd, &this->windowedSize); ShowWindow(this->hwnd, SW_SHOW); UpdateWindow(this->hwnd); StartOpengGL(); return this->hdc; } bool win32::mouselook = false; LRESULT CALLBACK win32::WndProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam) { bool mouseMoved = false; RECT windowSize; GetClientRect(hwnd, &windowSize); unsigned int windowWidth = windowSize.right - windowSize.left; unsigned int windowHeight = windowSize.bottom - windowSize.top; POINT midwindow = {windowWidth / 2, windowHeight / 2}; switch (message) { case WM_KEYUP: KeyboardEventSystem.KeyUp(wParam); keyUp[wParam] = 1; return 0; break; case WM_KEYDOWN: KeyboardEventSystem.KeyDown(wParam); return 0; break; case WM_CHAR: KeyboardEventSystem.CharDown(wParam); return 0; break; case WM_MOUSEMOVE: if (mouselook) { mouseMoved = true; if ((abs(GET_X_LPARAM(lParam) - midwindow.x) > 2) && (abs(GET_Y_LPARAM(lParam) - midwindow.y) > 2)) { MouseEventSystem.MouseMove((GET_X_LPARAM(lParam) - midwindow.x) / static_cast<float>(windowHeight) * 500.0f, (GET_Y_LPARAM(lParam) - midwindow.y) / static_cast<float>(windowWidth) * 500.0f); } else if (abs(GET_X_LPARAM(lParam) - midwindow.x) > 2) { MouseEventSystem.MouseMove((GET_X_LPARAM(lParam) - midwindow.x) / static_cast<float>(windowHeight) * 500.0f, 0.0f); } else if (abs(GET_Y_LPARAM(lParam) - midwindow.y) > 2) { MouseEventSystem.MouseMove(0.0f, (GET_Y_LPARAM(lParam) - midwindow.y) / static_cast<float>(windowWidth) * 500.0f); } else { mouseMoved = false; } ClientToScreen(hwnd, &midwindow); SetCursorPos(midwindow.x, midwindow.y); } break; case WM_LBUTTONDOWN: MouseEventSystem.MouseDown(Sigma::event::BUTTON::LEFT, static_cast<float>(GET_X_LPARAM(lParam)) / static_cast<float>(windowWidth), static_cast<float>(GET_Y_LPARAM(lParam)) / static_cast<float>(windowHeight)); break; case WM_LBUTTONUP: MouseEventSystem.MouseUp(Sigma::event::BUTTON::LEFT,static_cast<float>( GET_X_LPARAM(lParam)) / static_cast<float>(windowWidth), static_cast<float>(GET_Y_LPARAM(lParam)) / static_cast<float>(windowHeight)); break; case WM_RBUTTONDOWN: ShowCursor(false); mouselook = true; ClientToScreen(hwnd, &midwindow); SetCursorPos(midwindow.x, midwindow.y); break; case WM_RBUTTONUP: ShowCursor(true); mouselook = false; break; case WM_DESTROY: PostQuitMessage(0); break; } if (!mouseMoved) { MouseEventSystem.MouseMove(0.f, 0.f); } return DefWindowProc(hwnd, message, wParam, lParam); } bool win32::MessageLoop() { MSG msg; ZeroMemory(keyUp, sizeof(keyUp)); if (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE)) { // If we have a message to process, process it if (msg.message == WM_QUIT) { return false; } else { TranslateMessage(&msg); DispatchMessage(&msg); } } Sleep(1); return true; } bool win32::SetupTimer() { LARGE_INTEGER li; if(!QueryPerformanceFrequency(&li)) { return false; } this->frequency = static_cast<double>(li.QuadPart)/1000.0; QueryPerformanceCounter(&li); this->lastTime = li.QuadPart; return true; } double win32::GetDeltaTime() { LARGE_INTEGER li; QueryPerformanceCounter(&li); double delta = static_cast<double>(li.QuadPart - this->lastTime); this->lastTime = li.QuadPart; return this->curDelta = delta/this->frequency; } bool win32::KeyDown(int key, bool focused) { if (focused) { if (this->hwnd != GetFocus()) { return false; } } short k = GetKeyState(key); return (k & 0x80) > 0 ? true : false; } const int* win32::StartOpengGL() { this->fullscreen = false; this->OpenGLVersion[0] = -1; this->OpenGLVersion[1] = -1; this->hdc = GetDC(this->hwnd); // Get the device context for our window PIXELFORMATDESCRIPTOR pfd; memset(&pfd, 0, sizeof(PIXELFORMATDESCRIPTOR)); pfd.nSize = sizeof(PIXELFORMATDESCRIPTOR); pfd.nVersion = 1; pfd.dwFlags = PFD_DOUBLEBUFFER | PFD_SUPPORT_OPENGL | PFD_DRAW_TO_WINDOW; pfd.iPixelType = PFD_TYPE_RGBA; pfd.cColorBits = 32; pfd.cDepthBits = 32; pfd.iLayerType = PFD_MAIN_PLANE; int nPixelFormat = ChoosePixelFormat(this->hdc, &pfd); if (nPixelFormat == 0) { return this->OpenGLVersion; } BOOL bResult = SetPixelFormat (this->hdc, nPixelFormat, &pfd); if (!bResult) { return this->OpenGLVersion; } HGLRC tempContext = wglCreateContext(this->hdc); if(!tempContext) { assert(0 && "Failed to create temp context!"); } if(!wglMakeCurrent(this->hdc, tempContext)) { assert(0 && "Invalid temp context, cannot make current!"); } int attribs[] = { WGL_CONTEXT_MAJOR_VERSION_ARB, 3, WGL_CONTEXT_MINOR_VERSION_ARB, 1, 0,0,0 }; PFNWGLCREATECONTEXTATTRIBSARBPROC wglCreateContextAttribsARB = (PFNWGLCREATECONTEXTATTRIBSARBPROC)wglGetProcAddress("wglCreateContextAttribsARB"); if (!wglCreateContextAttribsARB) { assert(0 && "Unable to create GL 3.x context."); //It's not possible to make a GL 3.x context. Use the old style context (GL 2.1 and before) this->hrc = tempContext; } else { this->hrc = wglCreateContextAttribsARB(this->hdc, 0, attribs); } if (!this->hrc) { assert(0 && "Failed to make context!"); } if (!wglMakeCurrent(this->hdc, this->hrc)) { assert(0 && "Invalid context, cannot make current!"); } else { wglDeleteContext(tempContext); } GLuint error = glewInit(); if (error != GLEW_OK) { return OpenGLVersion; } //Checking GL version const GLubyte *GLVersionString = glGetString(GL_VERSION); //Or better yet, use the GL3 way to get the version number glGetIntegerv(GL_MAJOR_VERSION, &OpenGLVersion[0]); glGetIntegerv(GL_MINOR_VERSION, &OpenGLVersion[1]); // Set options for depth tests. glEnable(GL_DEPTH_TEST); glDepthFunc(GL_LESS); return OpenGLVersion; } void win32::Present(int fbo_id) { SwapBuffers(this->hdc); // Swap buffers so we can see our rendering. } bool win32::KeyReleased(int key, bool focused /*= false*/) { if (focused) { if (this->hwnd != GetFocus()) { return false; } } return (keyUp[key] != 0 ? true : false); } bool win32::KeyUp(int key, bool focused /*= false */) { if (focused) { if (this->hwnd != GetFocus()) { return false; } } short k = GetKeyState(key); return (k & 0x80) > 0 ? false : true; } unsigned int win32::GetWindowWidth() { if (fullscreen) { // Get the monitor info about the monitor the window is most over. HMONITOR hmon = MonitorFromWindow(this->hwnd, MONITOR_DEFAULTTONEAREST); MONITORINFO monInfo; monInfo.cbSize = sizeof(MONITORINFO); GetMonitorInfo(hmon, &monInfo); return monInfo.rcMonitor.right - monInfo.rcMonitor.left; } else { return this->windowedSize.right - this->windowedSize.left; } } unsigned int win32::GetWindowHeight() { if (fullscreen) { // Get the monitor info about the monitor the window is most over. HMONITOR hmon = MonitorFromWindow(this->hwnd, MONITOR_DEFAULTTONEAREST); MONITORINFO monInfo; monInfo.cbSize = sizeof(MONITORINFO); GetMonitorInfo(hmon, &monInfo); return monInfo.rcMonitor.bottom - monInfo.rcMonitor.top; } else { return this->windowedSize.bottom - this->windowedSize.top; } } void IOpSys::Quit() { PostQuitMessage(0); } <|endoftext|>
<commit_before>/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2005 Robert Osfield * * This library is open source and may be redistributed and/or modified under * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or * (at your option) any later version. The full license is in LICENSE file * included with this distribution, and on the openscenegraph.org website. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * OpenSceneGraph Public License for more details. */ #include <osg/Referenced> #include <osg/Notify> #include <typeinfo> #include <memory> #include <OpenThreads/ScopedLock> #include <OpenThreads/Mutex> #ifndef OSG_JAVA_BUILD namespace osg { static bool s_useThreadSafeReferenceCounting = getenv("OSG_THREAD_SAFE_REF_UNREF")!=0; static std::auto_ptr<DeleteHandler> s_deleteHandler(0); void Referenced::setThreadSafeReferenceCounting(bool enableThreadSafeReferenceCounting) { s_useThreadSafeReferenceCounting = enableThreadSafeReferenceCounting; } bool Referenced::getThreadSafeReferenceCounting() { return s_useThreadSafeReferenceCounting; } void Referenced::setDeleteHandler(DeleteHandler* handler) { s_deleteHandler.reset(handler); } DeleteHandler* Referenced::getDeleteHandler() { return s_deleteHandler.get(); } Referenced::Referenced() { if (s_useThreadSafeReferenceCounting) _refMutex = new OpenThreads::Mutex; else _refMutex = 0; _refCount=0; } Referenced::Referenced(const Referenced&) { if (s_useThreadSafeReferenceCounting) _refMutex = new OpenThreads::Mutex; else _refMutex = 0; _refCount=0; } Referenced::~Referenced() { if (_refCount>0) { notify(WARN)<<"Warning: deleting still referenced object "<<this<<" of type '"<<typeid(this).name()<<"'"<<std::endl; notify(WARN)<<" the final reference count was "<<_refCount<<", memory corruption possible."<<std::endl; } if (_refMutex) { OpenThreads::Mutex* tmpMutexPtr = _refMutex; _refMutex = 0; delete tmpMutexPtr; } } void Referenced::setThreadSafeRefUnref(bool threadSafe) { if (threadSafe) { if (!_refMutex) { // we want thread safe ref()/unref() so assing a mutex _refMutex = new OpenThreads::Mutex; } } else { if (_refMutex) { // we don't want thread safe ref()/unref() so remove any assigned mutex OpenThreads::Mutex* tmpMutexPtr = _refMutex; _refMutex = 0; delete tmpMutexPtr; } } } /* void Referenced::ref() const { if (_refMutex) { OpenThreads::ScopedLock<OpenThreads::Mutex> lock(*_refMutex); ++_refCount; } else { ++_refCount; } } void Referenced::unref() const { bool needDelete = false; if (_refMutex) { OpenThreads::ScopedLock<OpenThreads::Mutex> lock(*_refMutex); --_refCount; needDelete = _refCount<=0; } else { --_refCount; needDelete = _refCount<=0; } if (needDelete) { if (getDeleteHandler()) getDeleteHandler()->requestDelete(this); else delete this; } } */ void Referenced::unref_nodelete() const { if (_refMutex) { OpenThreads::ScopedLock<OpenThreads::Mutex> lock(*_refMutex); --_refCount; } else { --_refCount; } } }; // end of namespace osg #endif //OSG_JAVA_BUILD <commit_msg>Added env var report.<commit_after>/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2005 Robert Osfield * * This library is open source and may be redistributed and/or modified under * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or * (at your option) any later version. The full license is in LICENSE file * included with this distribution, and on the openscenegraph.org website. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * OpenSceneGraph Public License for more details. */ #include <osg/Referenced> #include <osg/Notify> #include <osg/ApplicationUsage> #include <typeinfo> #include <memory> #include <OpenThreads/ScopedLock> #include <OpenThreads/Mutex> #ifndef OSG_JAVA_BUILD namespace osg { static bool s_useThreadSafeReferenceCounting = getenv("OSG_THREAD_SAFE_REF_UNREF")!=0; static std::auto_ptr<DeleteHandler> s_deleteHandler(0); static ApplicationUsageProxy Referenced_e0(ApplicationUsage::ENVIRONMENTAL_VARIABLE,"OSG_THREAD_SAFE_REF_UNREF",""); void Referenced::setThreadSafeReferenceCounting(bool enableThreadSafeReferenceCounting) { s_useThreadSafeReferenceCounting = enableThreadSafeReferenceCounting; } bool Referenced::getThreadSafeReferenceCounting() { return s_useThreadSafeReferenceCounting; } void Referenced::setDeleteHandler(DeleteHandler* handler) { s_deleteHandler.reset(handler); } DeleteHandler* Referenced::getDeleteHandler() { return s_deleteHandler.get(); } Referenced::Referenced() { if (s_useThreadSafeReferenceCounting) _refMutex = new OpenThreads::Mutex; else _refMutex = 0; _refCount=0; } Referenced::Referenced(const Referenced&) { if (s_useThreadSafeReferenceCounting) _refMutex = new OpenThreads::Mutex; else _refMutex = 0; _refCount=0; } Referenced::~Referenced() { if (_refCount>0) { notify(WARN)<<"Warning: deleting still referenced object "<<this<<" of type '"<<typeid(this).name()<<"'"<<std::endl; notify(WARN)<<" the final reference count was "<<_refCount<<", memory corruption possible."<<std::endl; } if (_refMutex) { OpenThreads::Mutex* tmpMutexPtr = _refMutex; _refMutex = 0; delete tmpMutexPtr; } } void Referenced::setThreadSafeRefUnref(bool threadSafe) { if (threadSafe) { if (!_refMutex) { // we want thread safe ref()/unref() so assing a mutex _refMutex = new OpenThreads::Mutex; } } else { if (_refMutex) { // we don't want thread safe ref()/unref() so remove any assigned mutex OpenThreads::Mutex* tmpMutexPtr = _refMutex; _refMutex = 0; delete tmpMutexPtr; } } } /* void Referenced::ref() const { if (_refMutex) { OpenThreads::ScopedLock<OpenThreads::Mutex> lock(*_refMutex); ++_refCount; } else { ++_refCount; } } void Referenced::unref() const { bool needDelete = false; if (_refMutex) { OpenThreads::ScopedLock<OpenThreads::Mutex> lock(*_refMutex); --_refCount; needDelete = _refCount<=0; } else { --_refCount; needDelete = _refCount<=0; } if (needDelete) { if (getDeleteHandler()) getDeleteHandler()->requestDelete(this); else delete this; } } */ void Referenced::unref_nodelete() const { if (_refMutex) { OpenThreads::ScopedLock<OpenThreads::Mutex> lock(*_refMutex); --_refCount; } else { --_refCount; } } }; // end of namespace osg #endif //OSG_JAVA_BUILD <|endoftext|>
<commit_before>/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2014 Robert Osfield * * This library is open source and may be redistributed and/or modified under * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or * (at your option) any later version. The full license is in LICENSE file * included with this distribution, and on the openscenegraph.org website. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * OpenSceneGraph Public License for more details. */ #include <osgUI/ComboBox> #include <osgText/String> #include <osgText/Font> #include <osgText/Text> #include <osg/Notify> #include <osg/io_utils> using namespace osgUI; ComboBox::ComboBox() { } ComboBox::ComboBox(const osgUI::ComboBox& combobox, const osg::CopyOp& copyop): Widget(combobox, copyop), _items(combobox._items) { } bool ComboBox::handleImplementation(osgGA::EventVisitor* ev, osgGA::Event* event) { // OSG_NOTICE<<"ComboBox::handleImplementation"<<std::endl; osgGA::GUIEventAdapter* ea = event->asGUIEventAdapter(); if (!ea) return false; switch(ea->getEventType()) { case(osgGA::GUIEventAdapter::SCROLL): OSG_NOTICE<<"Scroll "<<std::endl; if (ea->getScrollingMotion()==osgGA::GUIEventAdapter::SCROLL_DOWN) { OSG_NOTICE<<"Scroll Down`"<<std::endl; if (getCurrentItem()<getNumItems()-1) setCurrentItem(getCurrentItem()+1); } else if (ea->getScrollingMotion()==osgGA::GUIEventAdapter::SCROLL_UP) { OSG_NOTICE<<"Scroll Up`"<<std::endl; if (getCurrentItem()>0) setCurrentItem(getCurrentItem()-1); } break; case(osgGA::GUIEventAdapter::PUSH): OSG_NOTICE<<"Button pressed "<<std::endl; break; case(osgGA::GUIEventAdapter::RELEASE): OSG_NOTICE<<"Button release "<<std::endl; break; default: break; } return false; } void ComboBox::enterImplementation() { OSG_NOTICE<<"ComboBox enter"<<std::endl; } void ComboBox::leaveImplementation() { OSG_NOTICE<<"ComboBox leave"<<std::endl; } void ComboBox::setCurrentItem(unsigned int i) { OSG_NOTICE << "ComboBox::setCurrentItem("<<i<<")"<<std::endl; _currentItem = i; if (_switch.valid()) _switch->setSingleChildOn(_currentItem); } void ComboBox::createGraphicsImplementation() { if (_switch.valid() && _switch->getNumChildren()==_items.size()) { OSG_NOTICE<<"Need to update existing scene graph"<<std::endl; _graphicsInitialized = true; } else { OSG_NOTICE<<"ComboBox::createGraphicsImplementation()"<<std::endl; Widget::createGraphicsImplementation(); Style* style = (getStyle()!=0) ? getStyle() : Style::instance().get(); _switch = new osg::Switch; addChild(_switch.get()); if (!_items.empty()) { for(Items::iterator itr = _items.begin(); itr != _items.end(); ++itr) { Item* item = itr->get(); OSG_NOTICE<<"Creating item "<<item->getText()<<", "<<item->getColor()<<std::endl; osg::ref_ptr<osg::Group> group = new osg::Group; if (item->getColor().a()!=0.0f) group->addChild( style->createPanel(_extents, item->getColor()) ); if (!item->getText().empty()) group->addChild( style->createText(_extents, getAlignmentSettings(), getTextSettings(), item->getText()) ); _switch->addChild(group.get()); } } else { _switch->addChild( style->createPanel(_extents, osg::Vec4(1.0f,1.0f,1.0f,1.0f)) ); } _switch->setSingleChildOn(_currentItem); } } <commit_msg>Added handling of up/down key to ComboBox<commit_after>/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2014 Robert Osfield * * This library is open source and may be redistributed and/or modified under * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or * (at your option) any later version. The full license is in LICENSE file * included with this distribution, and on the openscenegraph.org website. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * OpenSceneGraph Public License for more details. */ #include <osgUI/ComboBox> #include <osgText/String> #include <osgText/Font> #include <osgText/Text> #include <osg/Notify> #include <osg/io_utils> using namespace osgUI; ComboBox::ComboBox() { } ComboBox::ComboBox(const osgUI::ComboBox& combobox, const osg::CopyOp& copyop): Widget(combobox, copyop), _items(combobox._items) { } bool ComboBox::handleImplementation(osgGA::EventVisitor* ev, osgGA::Event* event) { // OSG_NOTICE<<"ComboBox::handleImplementation"<<std::endl; osgGA::GUIEventAdapter* ea = event->asGUIEventAdapter(); if (!ea) return false; switch(ea->getEventType()) { case(osgGA::GUIEventAdapter::SCROLL): if (ea->getScrollingMotion()==osgGA::GUIEventAdapter::SCROLL_DOWN) { if (getCurrentItem()<getNumItems()-1) setCurrentItem(getCurrentItem()+1); return true; } else if (ea->getScrollingMotion()==osgGA::GUIEventAdapter::SCROLL_UP) { if (getCurrentItem()>0) setCurrentItem(getCurrentItem()-1); return true; } break; case(osgGA::GUIEventAdapter::KEYDOWN): if (ea->getKey()==osgGA::GUIEventAdapter::KEY_Down) { if (getCurrentItem()<getNumItems()-1) setCurrentItem(getCurrentItem()+1); return true; } else if (ea->getKey()==osgGA::GUIEventAdapter::KEY_Up) { if (getCurrentItem()>0) setCurrentItem(getCurrentItem()-1); return true; } break; case(osgGA::GUIEventAdapter::PUSH): OSG_NOTICE<<"Button pressed "<<std::endl; break; case(osgGA::GUIEventAdapter::RELEASE): OSG_NOTICE<<"Button release "<<std::endl; break; default: break; } return false; } void ComboBox::enterImplementation() { OSG_NOTICE<<"ComboBox enter"<<std::endl; } void ComboBox::leaveImplementation() { OSG_NOTICE<<"ComboBox leave"<<std::endl; } void ComboBox::setCurrentItem(unsigned int i) { OSG_NOTICE << "ComboBox::setCurrentItem("<<i<<")"<<std::endl; _currentItem = i; if (_switch.valid()) _switch->setSingleChildOn(_currentItem); } void ComboBox::createGraphicsImplementation() { if (_switch.valid() && _switch->getNumChildren()==_items.size()) { OSG_NOTICE<<"Need to update existing scene graph"<<std::endl; _graphicsInitialized = true; } else { OSG_NOTICE<<"ComboBox::createGraphicsImplementation()"<<std::endl; Widget::createGraphicsImplementation(); Style* style = (getStyle()!=0) ? getStyle() : Style::instance().get(); _switch = new osg::Switch; addChild(_switch.get()); if (!_items.empty()) { for(Items::iterator itr = _items.begin(); itr != _items.end(); ++itr) { Item* item = itr->get(); OSG_NOTICE<<"Creating item "<<item->getText()<<", "<<item->getColor()<<std::endl; osg::ref_ptr<osg::Group> group = new osg::Group; if (item->getColor().a()!=0.0f) group->addChild( style->createPanel(_extents, item->getColor()) ); if (!item->getText().empty()) group->addChild( style->createText(_extents, getAlignmentSettings(), getTextSettings(), item->getText()) ); _switch->addChild(group.get()); } } else { _switch->addChild( style->createPanel(_extents, osg::Vec4(1.0f,1.0f,1.0f,1.0f)) ); } _switch->setSingleChildOn(_currentItem); } } <|endoftext|>
<commit_before>/** * @file llnotificationscripthandler.cpp * @brief Notification Handler Class for Simple Notifications and Notification Tips * * $LicenseInfo:firstyear=2000&license=viewerlgpl$ * Second Life Viewer Source Code * Copyright (C) 2010, Linden Research, Inc. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; * version 2.1 of the License only. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * * Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA * $/LicenseInfo$ */ #include "llviewerprecompiledheaders.h" // must be first include #include "llnotificationhandler.h" #include "lltoastnotifypanel.h" #include "llviewercontrol.h" #include "llviewerwindow.h" #include "llnotificationmanager.h" #include "llnotifications.h" #include "llscriptfloater.h" using namespace LLNotificationsUI; //-------------------------------------------------------------------------- LLScriptHandler::LLScriptHandler() : LLSysHandler("Notifications", "notify") { // Getting a Channel for our notifications LLScreenChannel* channel = LLChannelManager::getInstance()->createNotificationChannel(); if(channel) { channel->setControlHovering(true); mChannel = channel->getHandle(); } } //-------------------------------------------------------------------------- LLScriptHandler::~LLScriptHandler() { } //-------------------------------------------------------------------------- void LLScriptHandler::initChannel() { S32 channel_right_bound = gViewerWindow->getWorldViewRectScaled().mRight - gSavedSettings.getS32("NotificationChannelRightMargin"); S32 channel_width = gSavedSettings.getS32("NotifyBoxWidth"); mChannel.get()->init(channel_right_bound - channel_width, channel_right_bound); } //-------------------------------------------------------------------------- bool LLScriptHandler::processNotification(const LLNotificationPtr& notification) { if(mChannel.isDead()) { return false; } // arrange a channel on a screen if(!mChannel.get()->getVisible()) { initChannel(); } if (notification->canLogToIM()) { LLHandlerUtil::logToIMP2P(notification); } if(notification->hasFormElements() && !notification->canShowToast()) { LLScriptFloaterManager::getInstance()->onAddNotification(notification->getID()); } else { LLToastPanel* notify_box = LLToastPanel::buidPanelFromNotification(notification); LLToast::Params p; p.notif_id = notification->getID(); p.notification = notification; p.panel = notify_box; p.on_delete_toast = boost::bind(&LLScriptHandler::onDeleteToast, this, _1); LLScreenChannel* channel = dynamic_cast<LLScreenChannel*>(mChannel.get()); if(channel) { channel->addToast(p); } } return false; } void LLScriptHandler::onDelete( LLNotificationPtr notification ) { if(notification->hasFormElements()) { LLScriptFloaterManager::getInstance()->onRemoveNotification(notification->getID()); } else { mChannel.get()->removeToastByNotificationID(notification->getID()); } } //-------------------------------------------------------------------------- void LLScriptHandler::onDeleteToast(LLToast* toast) { // send a signal to a listener to let him perform some action // in this case listener is a SysWellWindow and it will remove a corresponding item from its list LLNotificationPtr notification = LLNotifications::getInstance()->find(toast->getNotificationID()); if( notification && notification->hasFormElements()) { LLScriptFloaterManager::getInstance()->onRemoveNotification(notification->getID()); } } <commit_msg>CHUI-309 FIXED Use onRemoveNotification only for "LoadWebPage", "ScriptDialog" and "ScriptDialogGroup" notifications<commit_after>/** * @file llnotificationscripthandler.cpp * @brief Notification Handler Class for Simple Notifications and Notification Tips * * $LicenseInfo:firstyear=2000&license=viewerlgpl$ * Second Life Viewer Source Code * Copyright (C) 2010, Linden Research, Inc. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; * version 2.1 of the License only. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * * Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA * $/LicenseInfo$ */ #include "llviewerprecompiledheaders.h" // must be first include #include "llnotificationhandler.h" #include "lltoastnotifypanel.h" #include "llviewercontrol.h" #include "llviewerwindow.h" #include "llnotificationmanager.h" #include "llnotifications.h" #include "llscriptfloater.h" using namespace LLNotificationsUI; //-------------------------------------------------------------------------- LLScriptHandler::LLScriptHandler() : LLSysHandler("Notifications", "notify") { // Getting a Channel for our notifications LLScreenChannel* channel = LLChannelManager::getInstance()->createNotificationChannel(); if(channel) { channel->setControlHovering(true); mChannel = channel->getHandle(); } } //-------------------------------------------------------------------------- LLScriptHandler::~LLScriptHandler() { } //-------------------------------------------------------------------------- void LLScriptHandler::initChannel() { S32 channel_right_bound = gViewerWindow->getWorldViewRectScaled().mRight - gSavedSettings.getS32("NotificationChannelRightMargin"); S32 channel_width = gSavedSettings.getS32("NotifyBoxWidth"); mChannel.get()->init(channel_right_bound - channel_width, channel_right_bound); } //-------------------------------------------------------------------------- bool LLScriptHandler::processNotification(const LLNotificationPtr& notification) { if(mChannel.isDead()) { return false; } // arrange a channel on a screen if(!mChannel.get()->getVisible()) { initChannel(); } if (notification->canLogToIM()) { LLHandlerUtil::logToIMP2P(notification); } if(notification->hasFormElements() && !notification->canShowToast()) { LLScriptFloaterManager::getInstance()->onAddNotification(notification->getID()); } else { LLToastPanel* notify_box = LLToastPanel::buidPanelFromNotification(notification); LLToast::Params p; p.notif_id = notification->getID(); p.notification = notification; p.panel = notify_box; p.on_delete_toast = boost::bind(&LLScriptHandler::onDeleteToast, this, _1); LLScreenChannel* channel = dynamic_cast<LLScreenChannel*>(mChannel.get()); if(channel) { channel->addToast(p); } } return false; } void LLScriptHandler::onDelete( LLNotificationPtr notification ) { if(notification->hasFormElements() && !notification->canShowToast()) { LLScriptFloaterManager::getInstance()->onRemoveNotification(notification->getID()); } else { mChannel.get()->removeToastByNotificationID(notification->getID()); } } //-------------------------------------------------------------------------- void LLScriptHandler::onDeleteToast(LLToast* toast) { // send a signal to a listener to let him perform some action // in this case listener is a SysWellWindow and it will remove a corresponding item from its list LLNotificationPtr notification = LLNotifications::getInstance()->find(toast->getNotificationID()); if( notification && notification->hasFormElements() && !notification->canShowToast()) { LLScriptFloaterManager::getInstance()->onRemoveNotification(notification->getID()); } } <|endoftext|>
<commit_before>/** * @file llviewerhelputil_test.cpp * @brief LLViewerHelpUtil tests * @author Tofu Linden * * $LicenseInfo:firstyear=2001&license=viewergpl$ * * Copyright (c) 2001-2009, Linden Research, Inc. * * Second Life Viewer Source Code * The source code in this file ("Source Code") is provided by Linden Lab * to you under the terms of the GNU General Public License, version 2.0 * ("GPL"), unless you have obtained a separate licensing agreement * ("Other License"), formally executed by you and Linden Lab. Terms of * the GPL can be found in doc/GPL-license.txt in this distribution, or * online at http://secondlifegrid.net/programs/open_source/licensing/gplv2 * * There are special exceptions to the terms and conditions of the GPL as * it is applied to this Source Code. View the full text of the exception * in the file doc/FLOSS-exception.txt in this software distribution, or * online at * http://secondlifegrid.net/programs/open_source/licensing/flossexception * * By copying, modifying or distributing this software, you acknowledge * that you have read and understood your obligations described above, * and agree to abide by those obligations. * * ALL LINDEN LAB SOURCE CODE IS PROVIDED "AS IS." LINDEN LAB MAKES NO * WARRANTIES, EXPRESS, IMPLIED OR OTHERWISE, REGARDING ITS ACCURACY, * COMPLETENESS OR PERFORMANCE. * $/LicenseInfo$ */ // Precompiled header #include "../llviewerprecompiledheaders.h" #include "../test/lltut.h" #include "../llviewerhelputil.h" #include "../llweb.h" #include "llcontrol.h" #include <iostream> // values for all of the supported substitutions parameters static std::string gHelpURL; static std::string gVersion; static std::string gChannel; static std::string gLanguage; static std::string gGrid; static std::string gOS; //---------------------------------------------------------------------------- // Mock objects for the dependencies of the code we're testing LLControlGroup::LLControlGroup(const std::string& name) : LLInstanceTracker<LLControlGroup, std::string>(name) {} LLControlGroup::~LLControlGroup() {} BOOL LLControlGroup::declareString(const std::string& name, const std::string& initial_val, const std::string& comment, BOOL persist) {return TRUE;} void LLControlGroup::setString(const std::string& name, const std::string& val){} std::string LLControlGroup::getString(const std::string& name) { if (name == "HelpURLFormat") return gHelpURL; return ""; } LLControlGroup gSavedSettings("test"); static void substitute_string(std::string &input, const std::string &search, const std::string &replace) { size_t pos = input.find(search); while (pos != std::string::npos) { input = input.replace(pos, search.size(), replace); pos = input.find(search); } } class LLAgent { public: LLAgent() {} ~LLAgent() {} #ifdef __GNUC__ __attribute__ ((noinline)) #endif BOOL isGodlike() const { return FALSE; } private: int dummy; }; LLAgent gAgent; std::string LLWeb::expandURLSubstitutions(const std::string &url, const LLSD &default_subs) { (void)gAgent.isGodlike(); // ref symbol to stop compiler from stripping it std::string new_url = url; substitute_string(new_url, "[TOPIC]", default_subs["TOPIC"].asString()); substitute_string(new_url, "[VERSION]", gVersion); substitute_string(new_url, "[CHANNEL]", gChannel); substitute_string(new_url, "[LANGUAGE]", gLanguage); substitute_string(new_url, "[GRID]", gGrid); substitute_string(new_url, "[OS]", gOS); return new_url; } //---------------------------------------------------------------------------- namespace tut { struct viewerhelputil { }; typedef test_group<viewerhelputil> viewerhelputil_t; typedef viewerhelputil_t::object viewerhelputil_object_t; tut::viewerhelputil_t tut_viewerhelputil("viewerhelputil"); template<> template<> void viewerhelputil_object_t::test<1>() { std::string topic("test_topic"); std::string subresult; gHelpURL = "fooformat"; subresult = LLViewerHelpUtil::buildHelpURL(topic); ensure_equals("no substitution tags", subresult, "fooformat"); gHelpURL = ""; subresult = LLViewerHelpUtil::buildHelpURL(topic); ensure_equals("blank substitution format", subresult, ""); gHelpURL = "[TOPIC]"; subresult = LLViewerHelpUtil::buildHelpURL(topic); ensure_equals("topic name", subresult, "test_topic"); gHelpURL = "[LANGUAGE]"; gLanguage = ""; subresult = LLViewerHelpUtil::buildHelpURL(topic); ensure_equals("simple substitution with blank", subresult, ""); gHelpURL = "[LANGUAGE]"; gLanguage = "Esperanto"; subresult = LLViewerHelpUtil::buildHelpURL(topic); ensure_equals("simple substitution", subresult, "Esperanto"); gHelpURL = "http://secondlife.com/[LANGUAGE]"; gLanguage = "Gaelic"; subresult = LLViewerHelpUtil::buildHelpURL(topic); ensure_equals("simple substitution with url", subresult, "http://secondlife.com/Gaelic"); gHelpURL = "[XXX]"; subresult = LLViewerHelpUtil::buildHelpURL(topic); ensure_equals("unknown substitution", subresult, "[XXX]"); gHelpURL = "[LANGUAGE]/[LANGUAGE]"; gLanguage = "Esperanto"; subresult = LLViewerHelpUtil::buildHelpURL(topic); ensure_equals("multiple substitution", subresult, "Esperanto/Esperanto"); gHelpURL = "http://[CHANNEL]/[VERSION]/[LANGUAGE]/[OS]/[GRID]/[XXX]"; gChannel = "Second Life Test"; gVersion = "2.0"; gLanguage = "gaelic"; gOS = "AmigaOS 2.1"; gGrid = "mysim"; subresult = LLViewerHelpUtil::buildHelpURL(topic); ensure_equals("complex substitution", subresult, "http://Second Life Test/2.0/gaelic/AmigaOS 2.1/mysim/[XXX]"); } } <commit_msg>CID-328<commit_after>/** * @file llviewerhelputil_test.cpp * @brief LLViewerHelpUtil tests * @author Tofu Linden * * $LicenseInfo:firstyear=2001&license=viewergpl$ * * Copyright (c) 2001-2009, Linden Research, Inc. * * Second Life Viewer Source Code * The source code in this file ("Source Code") is provided by Linden Lab * to you under the terms of the GNU General Public License, version 2.0 * ("GPL"), unless you have obtained a separate licensing agreement * ("Other License"), formally executed by you and Linden Lab. Terms of * the GPL can be found in doc/GPL-license.txt in this distribution, or * online at http://secondlifegrid.net/programs/open_source/licensing/gplv2 * * There are special exceptions to the terms and conditions of the GPL as * it is applied to this Source Code. View the full text of the exception * in the file doc/FLOSS-exception.txt in this software distribution, or * online at * http://secondlifegrid.net/programs/open_source/licensing/flossexception * * By copying, modifying or distributing this software, you acknowledge * that you have read and understood your obligations described above, * and agree to abide by those obligations. * * ALL LINDEN LAB SOURCE CODE IS PROVIDED "AS IS." LINDEN LAB MAKES NO * WARRANTIES, EXPRESS, IMPLIED OR OTHERWISE, REGARDING ITS ACCURACY, * COMPLETENESS OR PERFORMANCE. * $/LicenseInfo$ */ // Precompiled header #include "../llviewerprecompiledheaders.h" #include "../test/lltut.h" #include "../llviewerhelputil.h" #include "../llweb.h" #include "llcontrol.h" #include <iostream> // values for all of the supported substitutions parameters static std::string gHelpURL; static std::string gVersion; static std::string gChannel; static std::string gLanguage; static std::string gGrid; static std::string gOS; //---------------------------------------------------------------------------- // Mock objects for the dependencies of the code we're testing LLControlGroup::LLControlGroup(const std::string& name) : LLInstanceTracker<LLControlGroup, std::string>(name) {} LLControlGroup::~LLControlGroup() {} BOOL LLControlGroup::declareString(const std::string& name, const std::string& initial_val, const std::string& comment, BOOL persist) {return TRUE;} void LLControlGroup::setString(const std::string& name, const std::string& val){} std::string LLControlGroup::getString(const std::string& name) { if (name == "HelpURLFormat") return gHelpURL; return ""; } LLControlGroup gSavedSettings("test"); static void substitute_string(std::string &input, const std::string &search, const std::string &replace) { size_t pos = input.find(search); while (pos != std::string::npos) { input = input.replace(pos, search.size(), replace); pos = input.find(search); } } class LLAgent { public: LLAgent() {} ~LLAgent() {} #ifdef __GNUC__ __attribute__ ((noinline)) #endif BOOL isGodlike() const { return FALSE; } }; LLAgent gAgent; std::string LLWeb::expandURLSubstitutions(const std::string &url, const LLSD &default_subs) { (void)gAgent.isGodlike(); // ref symbol to stop compiler from stripping it std::string new_url = url; substitute_string(new_url, "[TOPIC]", default_subs["TOPIC"].asString()); substitute_string(new_url, "[VERSION]", gVersion); substitute_string(new_url, "[CHANNEL]", gChannel); substitute_string(new_url, "[LANGUAGE]", gLanguage); substitute_string(new_url, "[GRID]", gGrid); substitute_string(new_url, "[OS]", gOS); return new_url; } //---------------------------------------------------------------------------- namespace tut { struct viewerhelputil { }; typedef test_group<viewerhelputil> viewerhelputil_t; typedef viewerhelputil_t::object viewerhelputil_object_t; tut::viewerhelputil_t tut_viewerhelputil("viewerhelputil"); template<> template<> void viewerhelputil_object_t::test<1>() { std::string topic("test_topic"); std::string subresult; gHelpURL = "fooformat"; subresult = LLViewerHelpUtil::buildHelpURL(topic); ensure_equals("no substitution tags", subresult, "fooformat"); gHelpURL = ""; subresult = LLViewerHelpUtil::buildHelpURL(topic); ensure_equals("blank substitution format", subresult, ""); gHelpURL = "[TOPIC]"; subresult = LLViewerHelpUtil::buildHelpURL(topic); ensure_equals("topic name", subresult, "test_topic"); gHelpURL = "[LANGUAGE]"; gLanguage = ""; subresult = LLViewerHelpUtil::buildHelpURL(topic); ensure_equals("simple substitution with blank", subresult, ""); gHelpURL = "[LANGUAGE]"; gLanguage = "Esperanto"; subresult = LLViewerHelpUtil::buildHelpURL(topic); ensure_equals("simple substitution", subresult, "Esperanto"); gHelpURL = "http://secondlife.com/[LANGUAGE]"; gLanguage = "Gaelic"; subresult = LLViewerHelpUtil::buildHelpURL(topic); ensure_equals("simple substitution with url", subresult, "http://secondlife.com/Gaelic"); gHelpURL = "[XXX]"; subresult = LLViewerHelpUtil::buildHelpURL(topic); ensure_equals("unknown substitution", subresult, "[XXX]"); gHelpURL = "[LANGUAGE]/[LANGUAGE]"; gLanguage = "Esperanto"; subresult = LLViewerHelpUtil::buildHelpURL(topic); ensure_equals("multiple substitution", subresult, "Esperanto/Esperanto"); gHelpURL = "http://[CHANNEL]/[VERSION]/[LANGUAGE]/[OS]/[GRID]/[XXX]"; gChannel = "Second Life Test"; gVersion = "2.0"; gLanguage = "gaelic"; gOS = "AmigaOS 2.1"; gGrid = "mysim"; subresult = LLViewerHelpUtil::buildHelpURL(topic); ensure_equals("complex substitution", subresult, "http://Second Life Test/2.0/gaelic/AmigaOS 2.1/mysim/[XXX]"); } } <|endoftext|>
<commit_before>/************************************************************************* * * Copyright 2016 Realm Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * **************************************************************************/ #ifndef REALM_COLUMN_TYPE_TRAITS_HPP #define REALM_COLUMN_TYPE_TRAITS_HPP #include <realm/column_fwd.hpp> #include <realm/column_type.hpp> #include <realm/data_type.hpp> #include <realm/array.hpp> namespace realm { struct ObjKey; class Timestamp; class OldDateTime; class ArraySmallBlobs; class ArrayString; class ArrayStringShort; class ArrayBinary; class ArrayTimestamp; class ArrayInteger; class ArrayRef; class ArrayIntNull; class ArrayBool; class ArrayBoolNull; class ArrayKey; class ArrayKeyNonNullable; template <class> class BasicArray; template <class> class BasicArrayNull; template <class T> struct ColumnTypeTraits; template <class T, Action action> struct AggregateResultType { using result_type = T; }; template <class T, Action action> struct AggregateResultType<util::Optional<T>, action> { using result_type = T; }; template <> struct AggregateResultType<float, act_Sum> { using result_type = double; }; template <> struct ColumnTypeTraits<int64_t> { using leaf_type = ArrayInteger; using cluster_leaf_type = ArrayInteger; using sum_type = int64_t; using minmax_type = int64_t; static const DataType id = type_Int; static const ColumnType column_id = col_type_Int; static const ColumnType real_column_type = col_type_Int; }; template <> struct ColumnTypeTraits<ref_type> { using cluster_leaf_type = ArrayRef; static const DataType id = type_Int; static const ColumnType column_id = col_type_Int; }; template <> struct ColumnTypeTraits<util::Optional<int64_t>> { using leaf_type = ArrayIntNull; using cluster_leaf_type = ArrayIntNull; using sum_type = int64_t; using minmax_type = int64_t; static const DataType id = type_Int; static const ColumnType column_id = col_type_Int; static const ColumnType real_column_type = col_type_Int; }; template <> struct ColumnTypeTraits<bool> { using cluster_leaf_type = ArrayBool; static const DataType id = type_Bool; static const ColumnType column_id = col_type_Bool; }; template <> struct ColumnTypeTraits<util::Optional<bool>> { using cluster_leaf_type = ArrayBoolNull; static const DataType id = type_Bool; static const ColumnType column_id = col_type_Bool; }; template <> struct ColumnTypeTraits<ObjKey> { using cluster_leaf_type = ArrayKey; static const DataType id = type_Link; static const ColumnType column_id = col_type_Link; }; template <> struct ColumnTypeTraits<float> { using cluster_leaf_type = BasicArray<float>; using sum_type = double; using minmax_type = float; static const DataType id = type_Float; static const ColumnType column_id = col_type_Float; static const ColumnType real_column_type = col_type_Float; }; template <> struct ColumnTypeTraits<util::Optional<float>> { using cluster_leaf_type = BasicArrayNull<float>; using sum_type = double; using minmax_type = float; static const DataType id = type_Float; static const ColumnType column_id = col_type_Float; static const ColumnType real_column_type = col_type_Float; }; template <> struct ColumnTypeTraits<double> { using cluster_leaf_type = BasicArray<double>; using sum_type = double; using minmax_type = double; static const DataType id = type_Double; static const ColumnType column_id = col_type_Double; static const ColumnType real_column_type = col_type_Double; }; template <> struct ColumnTypeTraits<util::Optional<double>> { using cluster_leaf_type = BasicArrayNull<double>; using sum_type = double; using minmax_type = double; static const DataType id = type_Double; static const ColumnType column_id = col_type_Double; static const ColumnType real_column_type = col_type_Double; }; template <> struct ColumnTypeTraits<Timestamp> { using cluster_leaf_type = ArrayTimestamp; using minmax_type = Timestamp; static const DataType id = type_Timestamp; static const ColumnType column_id = col_type_Timestamp; }; template <> struct ColumnTypeTraits<StringData> { using cluster_leaf_type = ArrayString; using no_sum_type = double; static const DataType id = type_String; static const ColumnType column_id = col_type_String; }; template <> struct ColumnTypeTraits<BinaryData> { using leaf_type = ArraySmallBlobs; using cluster_leaf_type = ArrayBinary; static const DataType id = type_Binary; static const ColumnType column_id = col_type_Binary; static const ColumnType real_column_type = col_type_Binary; }; template <DataType, bool Nullable> struct GetLeafType; template <> struct GetLeafType<type_Int, false> { using type = ArrayInteger; }; template <> struct GetLeafType<type_Int, true> { using type = ArrayIntNull; }; template <bool N> struct GetLeafType<type_Float, N> { // FIXME: Null definition using type = BasicArray<float>; }; template <bool N> struct GetLeafType<type_Double, N> { // FIXME: Null definition using type = BasicArray<double>; }; template <bool N> struct GetLeafType<type_Timestamp, N> { // FIXME: Null definition using type = ArrayTimestamp; }; } #endif // REALM_COLUMN_TYPE_TRAITS_HPP <commit_msg>Update column_type_traits.hpp<commit_after>/************************************************************************* * * Copyright 2016 Realm Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * **************************************************************************/ #ifndef REALM_COLUMN_TYPE_TRAITS_HPP #define REALM_COLUMN_TYPE_TRAITS_HPP #include <realm/column_fwd.hpp> #include <realm/column_type.hpp> #include <realm/data_type.hpp> #include <realm/array.hpp> namespace realm { struct ObjKey; class Timestamp; class OldDateTime; class ArraySmallBlobs; class ArrayString; class ArrayStringShort; class ArrayBinary; class ArrayTimestamp; class ArrayInteger; class ArrayRef; class ArrayIntNull; class ArrayBool; class ArrayBoolNull; class ArrayKey; class ArrayKeyNonNullable; template <class> class BasicArray; template <class> class BasicArrayNull; template <class T> struct ColumnTypeTraits; template <class T, Action action> struct AggregateResultType { using result_type = T; }; template <class T, Action action> struct AggregateResultType<util::Optional<T>, action> { using result_type = T; }; template <> struct AggregateResultType<float, act_Sum> { using result_type = double; }; template <> struct ColumnTypeTraits<int64_t> { using leaf_type = ArrayInteger; using cluster_leaf_type = ArrayInteger; using sum_type = int64_t; using minmax_type = int64_t; static const DataType id = type_Int; static const ColumnType column_id = col_type_Int; static const ColumnType real_column_type = col_type_Int; }; template <> struct ColumnTypeTraits<ref_type> { using cluster_leaf_type = ArrayRef; static const DataType id = type_Int; static const ColumnType column_id = col_type_Int; }; template <> struct ColumnTypeTraits<util::Optional<int64_t>> { using leaf_type = ArrayIntNull; using cluster_leaf_type = ArrayIntNull; using sum_type = int64_t; using minmax_type = int64_t; static const DataType id = type_Int; static const ColumnType column_id = col_type_Int; static const ColumnType real_column_type = col_type_Int; }; template <> struct ColumnTypeTraits<bool> { using cluster_leaf_type = ArrayBool; static const DataType id = type_Bool; static const ColumnType column_id = col_type_Bool; }; template <> struct ColumnTypeTraits<util::Optional<bool>> { using cluster_leaf_type = ArrayBoolNull; static const DataType id = type_Bool; static const ColumnType column_id = col_type_Bool; }; template <> struct ColumnTypeTraits<ObjKey> { using cluster_leaf_type = ArrayKey; static const DataType id = type_Link; static const ColumnType column_id = col_type_Link; }; template <> struct ColumnTypeTraits<float> { using cluster_leaf_type = BasicArray<float>; using sum_type = double; using minmax_type = float; static const DataType id = type_Float; static const ColumnType column_id = col_type_Float; static const ColumnType real_column_type = col_type_Float; }; template <> struct ColumnTypeTraits<util::Optional<float>> { using cluster_leaf_type = BasicArrayNull<float>; using sum_type = double; using minmax_type = float; static const DataType id = type_Float; static const ColumnType column_id = col_type_Float; static const ColumnType real_column_type = col_type_Float; }; template <> struct ColumnTypeTraits<double> { using cluster_leaf_type = BasicArray<double>; using sum_type = double; using minmax_type = double; static const DataType id = type_Double; static const ColumnType column_id = col_type_Double; static const ColumnType real_column_type = col_type_Double; }; template <> struct ColumnTypeTraits<util::Optional<double>> { using cluster_leaf_type = BasicArrayNull<double>; using sum_type = double; using minmax_type = double; static const DataType id = type_Double; static const ColumnType column_id = col_type_Double; static const ColumnType real_column_type = col_type_Double; }; template <> struct ColumnTypeTraits<Timestamp> { using cluster_leaf_type = ArrayTimestamp; using minmax_type = Timestamp; static const DataType id = type_Timestamp; static const ColumnType column_id = col_type_Timestamp; }; template <> struct ColumnTypeTraits<StringData> { using cluster_leaf_type = ArrayString; static const DataType id = type_String; static const ColumnType column_id = col_type_String; }; template <> struct ColumnTypeTraits<BinaryData> { using leaf_type = ArraySmallBlobs; using cluster_leaf_type = ArrayBinary; static const DataType id = type_Binary; static const ColumnType column_id = col_type_Binary; static const ColumnType real_column_type = col_type_Binary; }; template <DataType, bool Nullable> struct GetLeafType; template <> struct GetLeafType<type_Int, false> { using type = ArrayInteger; }; template <> struct GetLeafType<type_Int, true> { using type = ArrayIntNull; }; template <bool N> struct GetLeafType<type_Float, N> { // FIXME: Null definition using type = BasicArray<float>; }; template <bool N> struct GetLeafType<type_Double, N> { // FIXME: Null definition using type = BasicArray<double>; }; template <bool N> struct GetLeafType<type_Timestamp, N> { // FIXME: Null definition using type = ArrayTimestamp; }; } #endif // REALM_COLUMN_TYPE_TRAITS_HPP <|endoftext|>
<commit_before>#include <new> #include <limits> #include <algorithm> #include <stdexcept> #include <realm/util/safe_int_ops.hpp> #include <realm/util/string_buffer.hpp> using namespace realm; using namespace realm::util; char StringBuffer::m_zero = 0; void StringBuffer::append(const char* data, size_t size) { size_t new_size = m_size; if (int_add_with_overflow_detect(new_size, size)) throw util::BufferSizeOverflow(); reserve(new_size); // Throws std::copy(data, data+size, m_buffer.data()+m_size); m_size = new_size; m_buffer[new_size] = 0; // Add zero termination } void StringBuffer::reallocate(size_t min_capacity) { size_t min_capacity_2 = min_capacity; // Make space for zero termination if (int_add_with_overflow_detect(min_capacity_2, 1)) throw util::BufferSizeOverflow(); size_t new_capacity = m_buffer.size(); if (int_multiply_with_overflow_detect(new_capacity, 2)) new_capacity = std::numeric_limits<size_t>::max(); if (new_capacity < min_capacity_2) new_capacity = min_capacity_2; m_buffer.resize(new_capacity, 0, m_size, 0); // Throws } <commit_msg>Ignore untestable line<commit_after>#include <new> #include <limits> #include <algorithm> #include <stdexcept> #include <realm/util/safe_int_ops.hpp> #include <realm/util/string_buffer.hpp> using namespace realm; using namespace realm::util; char StringBuffer::m_zero = 0; void StringBuffer::append(const char* data, size_t size) { size_t new_size = m_size; if (int_add_with_overflow_detect(new_size, size)) throw util::BufferSizeOverflow(); reserve(new_size); // Throws std::copy(data, data+size, m_buffer.data()+m_size); m_size = new_size; m_buffer[new_size] = 0; // Add zero termination } void StringBuffer::reallocate(size_t min_capacity) { size_t min_capacity_2 = min_capacity; // Make space for zero termination if (int_add_with_overflow_detect(min_capacity_2, 1)) throw util::BufferSizeOverflow(); size_t new_capacity = m_buffer.size(); if (int_multiply_with_overflow_detect(new_capacity, 2)) new_capacity = std::numeric_limits<size_t>::max(); // LCOV_EXCL_LINE if (new_capacity < min_capacity_2) new_capacity = min_capacity_2; m_buffer.resize(new_capacity, 0, m_size, 0); // Throws } <|endoftext|>
<commit_before>//http://codeforces.com/problemset/problem/601/A #include <iostream> #include <string> #include <vector> #include <algorithm> using namespace std; int main(int argc, char const *argv[]) { return 0; } <commit_msg>adding<commit_after>//http://codeforces.com/problemset/problem/601/A #include <iostream> #include <string> #include <vector> #include <algorithm> using namespace std; int main(int argc, char const *argv[]) { return 0; } <|endoftext|>
<commit_before>/* Copyright 2019 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include <memory> #include <string> #include <vector> #include "pybind11/pybind11.h" #include "pybind11/stl.h" #include "tensorflow/core/lib/core/error_codes.pb.h" #include "tensorflow/core/lib/core/errors.h" #include "tensorflow/core/lib/core/status.h" #include "tensorflow/core/lib/io/buffered_inputstream.h" #include "tensorflow/core/lib/io/random_inputstream.h" #include "tensorflow/core/platform/env.h" #include "tensorflow/core/platform/file_statistics.h" #include "tensorflow/core/platform/file_system.h" #include "tensorflow/core/platform/stringpiece.h" #include "tensorflow/core/platform/tstring.h" #include "tensorflow/python/lib/core/pybind11_absl.h" #include "tensorflow/python/lib/core/pybind11_status.h" namespace { namespace py = pybind11; PYBIND11_MODULE(_pywrap_file_io, m) { m.def("FileExists", [](const std::string& filename) { tensorflow::Status status; { py::gil_scoped_release release; status = tensorflow::Env::Default()->FileExists(filename); } tensorflow::MaybeRaiseRegisteredFromStatusWithGIL(status); }); m.def("DeleteFile", [](const std::string& filename) { py::gil_scoped_release release; tensorflow::Status status = tensorflow::Env::Default()->DeleteFile(filename); tensorflow::MaybeRaiseRegisteredFromStatusWithGIL(status); }); m.def("ReadFileToString", [](const std::string& filename) { std::string data; py::gil_scoped_release release; const auto status = ReadFileToString(tensorflow::Env::Default(), filename, &data); pybind11::gil_scoped_acquire acquire; tensorflow::MaybeRaiseRegisteredFromStatus(status); return py::bytes(data); }); m.def("WriteStringToFile", [](const std::string& filename, tensorflow::StringPiece data) { py::gil_scoped_release release; const auto status = WriteStringToFile(tensorflow::Env::Default(), filename, data); tensorflow::MaybeRaiseRegisteredFromStatusWithGIL(status); }); m.def("GetChildren", [](const std::string& dirname) { std::vector<std::string> results; py::gil_scoped_release release; const auto status = tensorflow::Env::Default()->GetChildren(dirname, &results); pybind11::gil_scoped_acquire acquire; tensorflow::MaybeRaiseRegisteredFromStatus(status); return results; }); m.def("GetMatchingFiles", [](const std::string& pattern) { std::vector<std::string> results; py::gil_scoped_release release; const auto status = tensorflow::Env::Default()->GetMatchingPaths(pattern, &results); pybind11::gil_scoped_acquire acquire; tensorflow::MaybeRaiseRegisteredFromStatus(status); return results; }); m.def("CreateDir", [](const std::string& dirname) { py::gil_scoped_release release; const auto status = tensorflow::Env::Default()->CreateDir(dirname); if (tensorflow::errors::IsAlreadyExists(status)) { return; } tensorflow::MaybeRaiseRegisteredFromStatusWithGIL(status); }); m.def("RecursivelyCreateDir", [](const std::string& dirname) { py::gil_scoped_release release; const auto status = tensorflow::Env::Default()->RecursivelyCreateDir(dirname); tensorflow::MaybeRaiseRegisteredFromStatusWithGIL(status); }); m.def("CopyFile", [](const std::string& src, const std::string& target, bool overwrite) { py::gil_scoped_release release; auto* env = tensorflow::Env::Default(); tensorflow::Status status; if (!overwrite && env->FileExists(target).ok()) { status = tensorflow::errors::AlreadyExists("file already exists"); } else { status = env->CopyFile(src, target); } tensorflow::MaybeRaiseRegisteredFromStatusWithGIL(status); }); m.def("RenameFile", [](const std::string& src, const std::string& target, bool overwrite) { py::gil_scoped_release release; auto* env = tensorflow::Env::Default(); tensorflow::Status status; if (!overwrite && env->FileExists(target).ok()) { status = tensorflow::errors::AlreadyExists("file already exists"); } else { status = env->RenameFile(src, target); } tensorflow::MaybeRaiseRegisteredFromStatusWithGIL(status); }); m.def("DeleteRecursively", [](const std::string& dirname) { py::gil_scoped_release release; tensorflow::int64 undeleted_files; tensorflow::int64 undeleted_dirs; auto status = tensorflow::Env::Default()->DeleteRecursively( dirname, &undeleted_files, &undeleted_dirs); if (status.ok() && (undeleted_files > 0 || undeleted_dirs > 0)) { status = tensorflow::errors::PermissionDenied("could not fully delete dir"); } tensorflow::MaybeRaiseRegisteredFromStatusWithGIL(status); }); m.def("IsDirectory", [](const std::string& dirname) { py::gil_scoped_release release; const auto status = tensorflow::Env::Default()->IsDirectory(dirname); // FAILED_PRECONDITION response means path exists but isn't a dir. if (tensorflow::errors::IsFailedPrecondition(status)) { return false; } tensorflow::MaybeRaiseRegisteredFromStatusWithGIL(status); return true; }); m.def("HasAtomicMove", [](const std::string& path) { py::gil_scoped_release release; bool has_atomic_move; const auto status = tensorflow::Env::Default()->HasAtomicMove(path, &has_atomic_move); tensorflow::MaybeRaiseRegisteredFromStatusWithGIL(status); return has_atomic_move; }); py::class_<tensorflow::FileStatistics>(m, "FileStatistics") .def_readonly("length", &tensorflow::FileStatistics::length) .def_readonly("mtime_nsec", &tensorflow::FileStatistics::mtime_nsec) .def_readonly("is_directory", &tensorflow::FileStatistics::is_directory); m.def("Stat", [](const std::string& filename) { py::gil_scoped_release release; std::unique_ptr<tensorflow::FileStatistics> self( new tensorflow::FileStatistics); const auto status = tensorflow::Env::Default()->Stat(filename, self.get()); py::gil_scoped_acquire acquire; tensorflow::MaybeRaiseRegisteredFromStatus(status); return self.release(); }); using tensorflow::WritableFile; py::class_<WritableFile>(m, "WritableFile") .def(py::init([](const std::string& filename, const std::string& mode) { py::gil_scoped_release release; auto* env = tensorflow::Env::Default(); std::unique_ptr<WritableFile> self; const auto status = mode.find("a") == std::string::npos ? env->NewWritableFile(filename, &self) : env->NewAppendableFile(filename, &self); py::gil_scoped_acquire acquire; tensorflow::MaybeRaiseRegisteredFromStatus(status); return self.release(); })) .def("append", [](WritableFile* self, tensorflow::StringPiece data) { const auto status = self->Append(data); tensorflow::MaybeRaiseRegisteredFromStatusWithGIL(status); }) // TODO(slebedev): Make WritableFile::Tell const and change self // to be a reference. .def("tell", [](WritableFile* self) { tensorflow::int64 pos = -1; py::gil_scoped_release release; const auto status = self->Tell(&pos); tensorflow::MaybeRaiseRegisteredFromStatusWithGIL(status); return pos; }) .def("flush", [](WritableFile* self) { py::gil_scoped_release release; tensorflow::MaybeRaiseRegisteredFromStatusWithGIL(self->Flush()); }) .def("close", [](WritableFile* self) { py::gil_scoped_release release; tensorflow::MaybeRaiseRegisteredFromStatusWithGIL(self->Close()); }); using tensorflow::io::BufferedInputStream; py::class_<BufferedInputStream>(m, "BufferedInputStream") .def(py::init([](const std::string& filename, size_t buffer_size) { py::gil_scoped_release release; std::unique_ptr<tensorflow::RandomAccessFile> file; const auto status = tensorflow::Env::Default()->NewRandomAccessFile(filename, &file); tensorflow::MaybeRaiseRegisteredFromStatusWithGIL(status); std::unique_ptr<tensorflow::io::RandomAccessInputStream> input_stream( new tensorflow::io::RandomAccessInputStream(file.release(), /*owns_file=*/true)); py::gil_scoped_acquire acquire; return new BufferedInputStream(input_stream.release(), buffer_size, /*owns_input_stream=*/true); })) .def("read", [](BufferedInputStream* self, tensorflow::int64 bytes_to_read) { py::gil_scoped_release release; tensorflow::tstring result; const auto status = self->ReadNBytes(bytes_to_read, &result); if (!status.ok() && !tensorflow::errors::IsOutOfRange(status)) { result.clear(); tensorflow::MaybeRaiseRegisteredFromStatusWithGIL(status); } py::gil_scoped_acquire acquire; return py::bytes(result); }) .def("readline", [](BufferedInputStream* self) { py::gil_scoped_release release; auto output = self->ReadLineAsString(); py::gil_scoped_acquire acquire; return py::bytes(output); }) .def("seek", [](BufferedInputStream* self, tensorflow::int64 pos) { py::gil_scoped_release release; tensorflow::MaybeRaiseRegisteredFromStatusWithGIL(self->Seek(pos)); }) .def("tell", [](BufferedInputStream* self) { py::gil_scoped_release release; return self->Tell(); }); } } // namespace <commit_msg>Add Transactional API python bindings<commit_after>/* Copyright 2019 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include <memory> #include <string> #include <vector> #include "pybind11/pybind11.h" #include "pybind11/stl.h" #include "tensorflow/core/lib/core/error_codes.pb.h" #include "tensorflow/core/lib/core/errors.h" #include "tensorflow/core/lib/core/status.h" #include "tensorflow/core/lib/io/buffered_inputstream.h" #include "tensorflow/core/lib/io/random_inputstream.h" #include "tensorflow/core/platform/env.h" #include "tensorflow/core/platform/file_statistics.h" #include "tensorflow/core/platform/file_system.h" #include "tensorflow/core/platform/stringpiece.h" #include "tensorflow/core/platform/tstring.h" #include "tensorflow/python/lib/core/pybind11_absl.h" #include "tensorflow/python/lib/core/pybind11_status.h" namespace tensorflow { struct PyTransactionToken { TransactionToken* token_; }; inline TransactionToken* TokenFromPyToken(PyTransactionToken* t) { return (t ? t->token_ : nullptr); } } // namespace tensorflow namespace { namespace py = pybind11; PYBIND11_MODULE(_pywrap_file_io, m) { using tensorflow::PyTransactionToken; using tensorflow::TransactionToken; py::class_<PyTransactionToken>(m, "TransactionToken") .def("__repr__", [](const PyTransactionToken* t) { if (t->token_) { return std::string(t->token_->owner->DecodeTransaction(t->token_)); } return std::string("Invalid token!"); }); m.def( "FileExists", [](const std::string& filename, PyTransactionToken* token) { tensorflow::Status status; { py::gil_scoped_release release; status = tensorflow::Env::Default()->FileExists(filename); } tensorflow::MaybeRaiseRegisteredFromStatusWithGIL(status); }, py::arg("filename"), py::arg("token") = (PyTransactionToken*)nullptr); m.def( "DeleteFile", [](const std::string& filename, PyTransactionToken* token) { py::gil_scoped_release release; tensorflow::Status status = tensorflow::Env::Default()->DeleteFile(filename); tensorflow::MaybeRaiseRegisteredFromStatusWithGIL(status); }, py::arg("filename"), py::arg("token") = (PyTransactionToken*)nullptr); m.def( "ReadFileToString", [](const std::string& filename, PyTransactionToken* token) { std::string data; py::gil_scoped_release release; const auto status = ReadFileToString(tensorflow::Env::Default(), filename, &data); pybind11::gil_scoped_acquire acquire; tensorflow::MaybeRaiseRegisteredFromStatus(status); return py::bytes(data); }, py::arg("filename"), py::arg("token") = (PyTransactionToken*)nullptr); m.def( "WriteStringToFile", [](const std::string& filename, tensorflow::StringPiece data, PyTransactionToken* token) { py::gil_scoped_release release; const auto status = WriteStringToFile(tensorflow::Env::Default(), filename, data); tensorflow::MaybeRaiseRegisteredFromStatusWithGIL(status); }, py::arg("filename"), py::arg("data"), py::arg("token") = (PyTransactionToken*)nullptr); m.def( "GetChildren", [](const std::string& dirname, PyTransactionToken* token) { std::vector<std::string> results; py::gil_scoped_release release; const auto status = tensorflow::Env::Default()->GetChildren(dirname, &results); pybind11::gil_scoped_acquire acquire; tensorflow::MaybeRaiseRegisteredFromStatus(status); return results; }, py::arg("dirname"), py::arg("token") = (PyTransactionToken*)nullptr); m.def( "GetMatchingFiles", [](const std::string& pattern, PyTransactionToken* token) { std::vector<std::string> results; py::gil_scoped_release release; const auto status = tensorflow::Env::Default()->GetMatchingPaths(pattern, &results); pybind11::gil_scoped_acquire acquire; tensorflow::MaybeRaiseRegisteredFromStatus(status); return results; }, py::arg("pattern"), py::arg("token") = (PyTransactionToken*)nullptr); m.def( "CreateDir", [](const std::string& dirname, PyTransactionToken* token) { py::gil_scoped_release release; const auto status = tensorflow::Env::Default()->CreateDir(dirname); if (tensorflow::errors::IsAlreadyExists(status)) { return; } tensorflow::MaybeRaiseRegisteredFromStatusWithGIL(status); }, py::arg("dirname"), py::arg("token") = (PyTransactionToken*)nullptr); m.def( "RecursivelyCreateDir", [](const std::string& dirname, PyTransactionToken* token) { py::gil_scoped_release release; const auto status = tensorflow::Env::Default()->RecursivelyCreateDir(dirname); tensorflow::MaybeRaiseRegisteredFromStatusWithGIL(status); }, py::arg("dirname"), py::arg("token") = (PyTransactionToken*)nullptr); m.def( "CopyFile", [](const std::string& src, const std::string& target, bool overwrite, PyTransactionToken* token) { py::gil_scoped_release release; auto* env = tensorflow::Env::Default(); tensorflow::Status status; if (!overwrite && env->FileExists(target).ok()) { status = tensorflow::errors::AlreadyExists("file already exists"); } else { status = env->CopyFile(src, target); } tensorflow::MaybeRaiseRegisteredFromStatusWithGIL(status); }, py::arg("src"), py::arg("target"), py::arg("overwrite"), py::arg("token") = (PyTransactionToken*)nullptr); m.def( "RenameFile", [](const std::string& src, const std::string& target, bool overwrite, PyTransactionToken* token) { py::gil_scoped_release release; auto* env = tensorflow::Env::Default(); tensorflow::Status status; if (!overwrite && env->FileExists(target).ok()) { status = tensorflow::errors::AlreadyExists("file already exists"); } else { status = env->RenameFile(src, target); } tensorflow::MaybeRaiseRegisteredFromStatusWithGIL(status); }, py::arg("src"), py::arg("target"), py::arg("overwrite"), py::arg("token") = (PyTransactionToken*)nullptr); m.def( "DeleteRecursively", [](const std::string& dirname, PyTransactionToken* token) { py::gil_scoped_release release; tensorflow::int64 undeleted_files; tensorflow::int64 undeleted_dirs; auto status = tensorflow::Env::Default()->DeleteRecursively( dirname, &undeleted_files, &undeleted_dirs); if (status.ok() && (undeleted_files > 0 || undeleted_dirs > 0)) { status = tensorflow::errors::PermissionDenied( "could not fully delete dir"); } tensorflow::MaybeRaiseRegisteredFromStatusWithGIL(status); }, py::arg("dirname"), py::arg("token") = (PyTransactionToken*)nullptr); m.def( "IsDirectory", [](const std::string& dirname, PyTransactionToken* token) { py::gil_scoped_release release; const auto status = tensorflow::Env::Default()->IsDirectory(dirname); // FAILED_PRECONDITION response means path exists but isn't a dir. if (tensorflow::errors::IsFailedPrecondition(status)) { return false; } tensorflow::MaybeRaiseRegisteredFromStatusWithGIL(status); return true; }, py::arg("dirname"), py::arg("token") = (PyTransactionToken*)nullptr); m.def("HasAtomicMove", [](const std::string& path) { py::gil_scoped_release release; bool has_atomic_move; const auto status = tensorflow::Env::Default()->HasAtomicMove(path, &has_atomic_move); tensorflow::MaybeRaiseRegisteredFromStatusWithGIL(status); return has_atomic_move; }); py::class_<tensorflow::FileStatistics>(m, "FileStatistics") .def_readonly("length", &tensorflow::FileStatistics::length) .def_readonly("mtime_nsec", &tensorflow::FileStatistics::mtime_nsec) .def_readonly("is_directory", &tensorflow::FileStatistics::is_directory); m.def( "Stat", [](const std::string& filename, PyTransactionToken* token) { py::gil_scoped_release release; std::unique_ptr<tensorflow::FileStatistics> self( new tensorflow::FileStatistics); const auto status = tensorflow::Env::Default()->Stat(filename, self.get()); py::gil_scoped_acquire acquire; tensorflow::MaybeRaiseRegisteredFromStatus(status); return self.release(); }, py::arg("filename"), py::arg("token") = (PyTransactionToken*)nullptr); using tensorflow::WritableFile; py::class_<WritableFile>(m, "WritableFile") .def(py::init([](const std::string& filename, const std::string& mode, PyTransactionToken* token) { py::gil_scoped_release release; auto* env = tensorflow::Env::Default(); std::unique_ptr<WritableFile> self; const auto status = mode.find("a") == std::string::npos ? env->NewWritableFile(filename, &self) : env->NewAppendableFile(filename, &self); py::gil_scoped_acquire acquire; tensorflow::MaybeRaiseRegisteredFromStatus(status); return self.release(); }), py::arg("filename"), py::arg("mode"), py::arg("token") = (PyTransactionToken*)nullptr) .def("append", [](WritableFile* self, tensorflow::StringPiece data) { const auto status = self->Append(data); tensorflow::MaybeRaiseRegisteredFromStatusWithGIL(status); }) // TODO(slebedev): Make WritableFile::Tell const and change self // to be a reference. .def("tell", [](WritableFile* self) { tensorflow::int64 pos = -1; py::gil_scoped_release release; const auto status = self->Tell(&pos); tensorflow::MaybeRaiseRegisteredFromStatusWithGIL(status); return pos; }) .def("flush", [](WritableFile* self) { py::gil_scoped_release release; tensorflow::MaybeRaiseRegisteredFromStatusWithGIL(self->Flush()); }) .def("close", [](WritableFile* self) { py::gil_scoped_release release; tensorflow::MaybeRaiseRegisteredFromStatusWithGIL(self->Close()); }); using tensorflow::io::BufferedInputStream; py::class_<BufferedInputStream>(m, "BufferedInputStream") .def(py::init([](const std::string& filename, size_t buffer_size, PyTransactionToken* token) { py::gil_scoped_release release; std::unique_ptr<tensorflow::RandomAccessFile> file; const auto status = tensorflow::Env::Default()->NewRandomAccessFile(filename, &file); tensorflow::MaybeRaiseRegisteredFromStatusWithGIL(status); std::unique_ptr<tensorflow::io::RandomAccessInputStream> input_stream(new tensorflow::io::RandomAccessInputStream( file.release(), /*owns_file=*/true)); py::gil_scoped_acquire acquire; return new BufferedInputStream(input_stream.release(), buffer_size, /*owns_input_stream=*/true); }), py::arg("filename"), py::arg("buffer_size"), py::arg("token") = (PyTransactionToken*)nullptr) .def("read", [](BufferedInputStream* self, tensorflow::int64 bytes_to_read) { py::gil_scoped_release release; tensorflow::tstring result; const auto status = self->ReadNBytes(bytes_to_read, &result); if (!status.ok() && !tensorflow::errors::IsOutOfRange(status)) { result.clear(); tensorflow::MaybeRaiseRegisteredFromStatusWithGIL(status); } py::gil_scoped_acquire acquire; return py::bytes(result); }) .def("readline", [](BufferedInputStream* self) { py::gil_scoped_release release; auto output = self->ReadLineAsString(); py::gil_scoped_acquire acquire; return py::bytes(output); }) .def("seek", [](BufferedInputStream* self, tensorflow::int64 pos) { py::gil_scoped_release release; tensorflow::MaybeRaiseRegisteredFromStatusWithGIL(self->Seek(pos)); }) .def("tell", [](BufferedInputStream* self) { py::gil_scoped_release release; return self->Tell(); }); } } // namespace <|endoftext|>
<commit_before>// REQUIRES: system-windows // RUN: %check_clang_tidy %s hicpp-no-assembler %t void f() { _asm { mov al, 2; // CHECK-MESSAGES: :[[@LINE-2]]:3: warning: do not use inline assembler in safety-critical code [hicpp-no-assembler] } } <commit_msg>[clang-tidy] Marking hicpp-no-assembler-msvc unsupported on Windows<commit_after>// REQUIRES: system-windows // FIXME: Re-enable test on windows (PR36855) // UNSUPPORTED: system-windows // RUN: %check_clang_tidy %s hicpp-no-assembler %t void f() { _asm { mov al, 2; // CHECK-MESSAGES: :[[@LINE-2]]:3: warning: do not use inline assembler in safety-critical code [hicpp-no-assembler] } } <|endoftext|>
<commit_before>// RUN: %check_clang_tidy %s misc-unused-using-decls %t // ----- Definitions ----- template <typename T> class vector {}; namespace n { class A; class B; class C; class D; class D { public: static int i; }; template <typename T> class E {}; template <typename T> class F {}; class G { public: static void func() {} }; class H { public: static int i; }; class I { public: static int ii; }; template <typename T> class J {}; class Base { public: void f(); }; D UsedInstance; D UnusedInstance; int UsedFunc() { return 1; } int UnusedFunc() { return 1; } template <typename T> int UsedTemplateFunc() { return 1; } template <typename T> int UnusedTemplateFunc() { return 1; } template <typename T> int UsedInTemplateFunc() { return 1; } class ostream { public: ostream &operator<<(ostream &(*PF)(ostream &)); }; extern ostream cout; ostream &endl(ostream &os); } // ----- Using declarations ----- // eol-comments aren't removed (yet) using n::A; // A // CHECK-MESSAGES: :[[@LINE-1]]:10: warning: using decl 'A' is unused // CHECK-FIXES: {{^}}// A using n::B; using n::C; using n::D; using n::E; // E // CHECK-MESSAGES: :[[@LINE-1]]:10: warning: using decl 'E' is unused // CHECK-FIXES: {{^}}// E using n::F; using n::G; using n::H; using n::I; int I::ii = 1; class Derived : public n::Base { public: using Base::f; }; using n::UsedInstance; using n::UsedFunc; using n::UsedTemplateFunc; using n::UnusedInstance; // UnusedInstance // CHECK-MESSAGES: :[[@LINE-1]]:10: warning: using decl 'UnusedInstance' is unused // CHECK-FIXES: {{^}}// UnusedInstance using n::UnusedFunc; // UnusedFunc // CHECK-MESSAGES: :[[@LINE-1]]:10: warning: using decl 'UnusedFunc' is unused // CHECK-FIXES: {{^}}// UnusedFunc using n::cout; using n::endl; using n::UsedInTemplateFunc; using n::J; template <typename T> void Callee() { J<T> j; UsedInTemplateFunc<T>(); } #define DEFINE_INT(name) \ namespace INT { \ static const int _##name = 1; \ } \ using INT::_##name DEFINE_INT(test); #undef DEFIND_INT // ----- Usages ----- void f(B b); void g() { vector<C> data; D::i = 1; F<int> f; void (*func)() = &G::func; int *i = &H::i; UsedInstance.i; UsedFunc(); UsedTemplateFunc<int>(); cout << endl; } <commit_msg>[clang-tidy] Fix misc-unused-using-decls test failure in windows buildbot.<commit_after>// RUN: %check_clang_tidy %s misc-unused-using-decls %t -- -- -fno-delayed-template-parsing // ----- Definitions ----- template <typename T> class vector {}; namespace n { class A; class B; class C; class D; class D { public: static int i; }; template <typename T> class E {}; template <typename T> class F {}; class G { public: static void func() {} }; class H { public: static int i; }; class I { public: static int ii; }; template <typename T> class J {}; class Base { public: void f(); }; D UsedInstance; D UnusedInstance; int UsedFunc() { return 1; } int UnusedFunc() { return 1; } template <typename T> int UsedTemplateFunc() { return 1; } template <typename T> int UnusedTemplateFunc() { return 1; } template <typename T> int UsedInTemplateFunc() { return 1; } class ostream { public: ostream &operator<<(ostream &(*PF)(ostream &)); }; extern ostream cout; ostream &endl(ostream &os); } // ----- Using declarations ----- // eol-comments aren't removed (yet) using n::A; // A // CHECK-MESSAGES: :[[@LINE-1]]:10: warning: using decl 'A' is unused // CHECK-FIXES: {{^}}// A using n::B; using n::C; using n::D; using n::E; // E // CHECK-MESSAGES: :[[@LINE-1]]:10: warning: using decl 'E' is unused // CHECK-FIXES: {{^}}// E using n::F; using n::G; using n::H; using n::I; int I::ii = 1; class Derived : public n::Base { public: using Base::f; }; using n::UsedInstance; using n::UsedFunc; using n::UsedTemplateFunc; using n::UnusedInstance; // UnusedInstance // CHECK-MESSAGES: :[[@LINE-1]]:10: warning: using decl 'UnusedInstance' is unused // CHECK-FIXES: {{^}}// UnusedInstance using n::UnusedFunc; // UnusedFunc // CHECK-MESSAGES: :[[@LINE-1]]:10: warning: using decl 'UnusedFunc' is unused // CHECK-FIXES: {{^}}// UnusedFunc using n::cout; using n::endl; using n::UsedInTemplateFunc; using n::J; template <typename T> void Callee() { J<T> j; UsedInTemplateFunc<T>(); } #define DEFINE_INT(name) \ namespace INT { \ static const int _##name = 1; \ } \ using INT::_##name DEFINE_INT(test); #undef DEFIND_INT // ----- Usages ----- void f(B b); void g() { vector<C> data; D::i = 1; F<int> f; void (*func)() = &G::func; int *i = &H::i; UsedInstance.i; UsedFunc(); UsedTemplateFunc<int>(); cout << endl; } <|endoftext|>
<commit_before>#pragma once /* * Author(s): * - Chris Kilner <ckilner@aldebaran-robotics.com> * - Cedric Gestes <gestes@aldebaran-robotics.com> * - Herve Cuche <hcuche@aldebaran-robotics.com> * * Copyright (C) 2010, 2011 Aldebaran Robotics */ /** @file * @brief Convenient log macro */ #ifndef LOG_HPP_ # define LOG_HPP_ # include <map> # include <string> # include <iostream> # include <sstream> # include <cstdarg> # include <cstdio> #include <boost/function/function_fwd.hpp> #include <qi/config.hpp> #include <qi/os.hpp> /** * \def qiLogDebug * Log in debug mode. Not compile on release. */ #ifdef NO_QI_DEBUG # define qiLogDebug(...) #else # define qiLogDebug(...) qi::log::LogStream(qi::log::debug, __FILE__, __FUNCTION__, __LINE__, __VA_ARGS__).self() #endif /** * \def qiLogVerbose * Log in verbose mode. This mode isn't show by default but always compile. */ #ifdef NO_QI_VERBOSE # define qiLogVerbose(...) #else # define qiLogVerbose(...) qi::log::LogStream(qi::log::verbose, __FILE__, __FUNCTION__, __LINE__, __VA_ARGS__).self() #endif /** * \def qiLogInfo * Log in info mode. */ #ifdef NO_QI_INFO # define qiLogInfo(...) #else # define qiLogInfo(...) qi::log::LogStream(qi::log::info, __FILE__, __FUNCTION__, __LINE__, __VA_ARGS__).self() #endif /** * \def qiLogWarning * Log in warning mode. */ #ifdef NO_QI_WARNING # define qiLogWarning(...) #else # define qiLogWarning(...) qi::log::LogStream(qi::log::warning, __FILE__, __FUNCTION__, __LINE__, __VA_ARGS__).self() #endif /** * \def qiLogError * Log in error mode. */ #ifdef NO_QI_ERROR # define qiLogError(...) #else # define qiLogError(...) qi::log::LogStream(qi::log::error, __FILE__, __FUNCTION__, __LINE__, __VA_ARGS__).self() #endif /** * \def qiLogFatal * Log in fatal mode. */ #ifdef NO_QI_FATAL # define qiLogFatal(...) #else # define qiLogFatal(...) qi::log::LogStream(qi::log::fatal, __FILE__, __FUNCTION__, __LINE__, __VA_ARGS__).self() #endif /** * \namespace qi::log * \brief log implementation. */ namespace qi { namespace log { class LogStream; /** * \enum LogLevel * \brief seven log levels display. */ enum QI_API LogLevel { silent = 0, fatal, error, warning, info, verbose, debug, }; /** * \typedef logFuncHandler * \brief Boost delegate to log function (verb, category, * message, file, function, line, date). */ typedef boost::function7<void, const qi::log::LogLevel, const qi::os::timeval, const char*, const char*, const char*, const char*, int> logFuncHandler; /** * \brief Log function * * You should call qiLog* macro. * * @param verb { debug = 6, verbose=5, info = 4, warning = 3, error = 2, fatal = 1, silent = 0 } * @param category Log category. * @param msg Log message. * @param file __FILE__ * @param function __FUNCTION__ * @param line __LINE__ */ QI_API void log(const qi::log::LogLevel verb, const char *category, const char *msg, const char *file = "", const char *fct = "", const int line = 0); /** * \brief Convert log verbosity to char* * @param verb { debug = 6, verbose=5, info = 4, warning = 3, error = 2, fatal = 1, silent = 0 } * * \return [SILENT], [FATAL], [ERROR], * [WARN ], [INFO ], [VERB ], * [DEBUG] */ QI_API const char* logLevelToString(const qi::log::LogLevel verb); /** * \brief Convert string to log verbosity * @param verb debug, verbose, info, * warning, error, fatal, * silent * * \return Log level verbosity */ QI_API const qi::log::LogLevel stringToLogLevel(const char* verb); /** * \brief Set log verbosity. * * If you don't want any log use silent mode. * * @param lv maximal verbosity shown */ QI_API void setVerbosity(const qi::log::LogLevel lv); /** * \brief Get log verbosity. * @return Maximal verbosity display. */ QI_API qi::log::LogLevel verbosity(); /** * \brief Set log context. * * Display log context (line, function, file). * * @param ctx Value to set context. * 0: none, 1: categories, 2: date, 3: file+line, * 4: date+categories, 5: date+line+file, * 6: categories+line+file, * 7: all (date+categories+line+file+function) */ QI_API void setContext(int ctx); /** * \brief Get log context. * @return true if active, false otherwise. */ QI_API int context(); /** * \brief Set synchronous logs. * * @param sync Value to set context. */ QI_API void setSynchronousLog(bool sync); /** * \brief Add log handler. * * @param fct Boost delegate to log handler function. * @param name name of the handler, this is the one used to remove handler (prefer lowcase). */ QI_API void addLogHandler(const std::string& name, qi::log::logFuncHandler fct); /** * \brief remove log handler. * * @param name name of the handler. */ QI_API void removeLogHandler(const std::string& name); /** \class LogStream log.hpp "qi/log.hpp" */ class LogStream: public std::stringstream { public: /** * \brief LogStream. Copy Ctor. * @param rhs LogStream. */ LogStream(const LogStream &rhs) : _logLevel(rhs._logLevel) , _category(rhs._category) , _file(rhs._file) , _function(rhs._function) , _line(rhs._line) { } /** * \brief LogStream assignment operator. * @param rhs LogStream. */ const LogStream &operator=(const LogStream &rhs) { _logLevel = rhs._logLevel; _category = rhs._category; _file = rhs._file; _function = rhs._function; _line = rhs._line; return *this; } /** * \brief LogStream. Will log at object destruction * @param level { debug = 6, verbose=5, info = 4, warning = 3, error = 2, fatal = 1, silent = 0 } * @param file __FILE__ * @param function __FUNCTION__ * @param line __LINE__ * @param category log category */ LogStream(const LogLevel level, const char *file, const char *function, const int line, const char *category) : _logLevel(level) , _category(category) , _file(file) , _function(function) , _line(line) { } /** * \brief LogStream. Will log at object destruction * @param level { debug = 6, verbose=5, info = 4, warning = 3, error = 2, fatal = 1, silent = 0 } * @param file __FILE__ * @param function __FUNCTION__ * @param line __LINE__ * @param category log category * @param fmt message format. */ LogStream(const LogLevel level, const char *file, const char *function, const int line, const char *category, const char *fmt, ...) : _logLevel(level) , _category(category) , _file(file) , _function(function) , _line(line) { char buffer[2048]; va_list vl; va_start(vl, fmt); #ifdef _MSC_VER vsnprintf_s(buffer, 2048, 2047, fmt, vl); #else vsnprintf(buffer, 2048, fmt, vl); #endif buffer[2047] = 0; va_end(vl); *this << buffer; } /** \brief Destructor */ ~LogStream() { qi::log::log(_logLevel, _category, this->str().c_str(), _file, _function, _line); } /** \brief Necessary to work with an anonymous object */ LogStream& self() { return *this; } private: LogLevel _logLevel; const char *_category; const char *_file; const char *_function; int _line; }; } } #endif // !LOG_HPP_ <commit_msg>libqi: log: disable qiLogDebug in release build<commit_after>#pragma once /* * Author(s): * - Chris Kilner <ckilner@aldebaran-robotics.com> * - Cedric Gestes <gestes@aldebaran-robotics.com> * - Herve Cuche <hcuche@aldebaran-robotics.com> * * Copyright (C) 2010, 2011 Aldebaran Robotics */ /** @file * @brief Convenient log macro */ #ifndef LOG_HPP_ # define LOG_HPP_ # include <map> # include <string> # include <iostream> # include <sstream> # include <cstdarg> # include <cstdio> #include <boost/function/function_fwd.hpp> #include <qi/config.hpp> #include <qi/os.hpp> /** * \def qiLogDebug * Log in debug mode. Not compile on release. */ #if defined(NO_QI_DEBUG) || defined(NDEBUG) # define qiLogDebug(...) qi::log::detail::NullStream(__VA_ARGS__).self() #else # define qiLogDebug(...) qi::log::LogStream(qi::log::debug, __FILE__, __FUNCTION__, __LINE__, __VA_ARGS__).self() #endif /** * \def qiLogVerbose * Log in verbose mode. This mode isn't show by default but always compile. */ #ifdef NO_QI_VERBOSE # define qiLogVerbose(...) qi::log::detail::NullStream(__VA_ARGS__).self() #else # define qiLogVerbose(...) qi::log::LogStream(qi::log::verbose, __FILE__, __FUNCTION__, __LINE__, __VA_ARGS__).self() #endif /** * \def qiLogInfo * Log in info mode. */ #ifdef NO_QI_INFO # define qiLogInfo(...) qi::log::detail::NullStream(__VA_ARGS__).self() #else # define qiLogInfo(...) qi::log::LogStream(qi::log::info, __FILE__, __FUNCTION__, __LINE__, __VA_ARGS__).self() #endif /** * \def qiLogWarning * Log in warning mode. */ #ifdef NO_QI_WARNING # define qiLogWarning(...) qi::log::detail::NullStream(__VA_ARGS__).self() #else # define qiLogWarning(...) qi::log::LogStream(qi::log::warning, __FILE__, __FUNCTION__, __LINE__, __VA_ARGS__).self() #endif /** * \def qiLogError * Log in error mode. */ #ifdef NO_QI_ERROR # define qiLogError(...) qi::log::detail::NullStream(__VA_ARGS__).self() #else # define qiLogError(...) qi::log::LogStream(qi::log::error, __FILE__, __FUNCTION__, __LINE__, __VA_ARGS__).self() #endif /** * \def qiLogFatal * Log in fatal mode. */ #ifdef NO_QI_FATAL # define qiLogFatal(...) qi::log::detail::NullStream(__VA_ARGS__).self() #else # define qiLogFatal(...) qi::log::LogStream(qi::log::fatal, __FILE__, __FUNCTION__, __LINE__, __VA_ARGS__).self() #endif /** * \namespace qi::log * \brief log implementation. */ namespace qi { namespace log { namespace detail { // simple NullStream that do nothing class NullStream { public: NullStream(char *, ...) { } NullStream &self() { return *this; } template <typename T> NullStream& operator<<(const T& val) { return self(); } NullStream& operator<<(std::ostream& (*f)(std::ostream&)) { return self(); } }; }; /** * \enum LogLevel * \brief seven log levels display. */ enum QI_API LogLevel { silent = 0, fatal, error, warning, info, verbose, debug, }; /** * \typedef logFuncHandler * \brief Boost delegate to log function (verb, category, * message, file, function, line, date). */ typedef boost::function7<void, const qi::log::LogLevel, const qi::os::timeval, const char*, const char*, const char*, const char*, int> logFuncHandler; /** * \brief Log function * * You should call qiLog* macro. * * @param verb { debug = 6, verbose=5, info = 4, warning = 3, error = 2, fatal = 1, silent = 0 } * @param category Log category. * @param msg Log message. * @param file __FILE__ * @param function __FUNCTION__ * @param line __LINE__ */ QI_API void log(const qi::log::LogLevel verb, const char *category, const char *msg, const char *file = "", const char *fct = "", const int line = 0); /** * \brief Convert log verbosity to char* * @param verb { debug = 6, verbose=5, info = 4, warning = 3, error = 2, fatal = 1, silent = 0 } * * \return [SILENT], [FATAL], [ERROR], * [WARN ], [INFO ], [VERB ], * [DEBUG] */ QI_API const char* logLevelToString(const qi::log::LogLevel verb); /** * \brief Convert string to log verbosity * @param verb debug, verbose, info, * warning, error, fatal, * silent * * \return Log level verbosity */ QI_API const qi::log::LogLevel stringToLogLevel(const char* verb); /** * \brief Set log verbosity. * * If you don't want any log use silent mode. * * @param lv maximal verbosity shown */ QI_API void setVerbosity(const qi::log::LogLevel lv); /** * \brief Get log verbosity. * @return Maximal verbosity display. */ QI_API qi::log::LogLevel verbosity(); /** * \brief Set log context. * * Display log context (line, function, file). * * @param ctx Value to set context. * 0: none, 1: categories, 2: date, 3: file+line, * 4: date+categories, 5: date+line+file, * 6: categories+line+file, * 7: all (date+categories+line+file+function) */ QI_API void setContext(int ctx); /** * \brief Get log context. * @return true if active, false otherwise. */ QI_API int context(); /** * \brief Set synchronous logs. * * @param sync Value to set context. */ QI_API void setSynchronousLog(bool sync); /** * \brief Add log handler. * * @param fct Boost delegate to log handler function. * @param name name of the handler, this is the one used to remove handler (prefer lowcase). */ QI_API void addLogHandler(const std::string& name, qi::log::logFuncHandler fct); /** * \brief remove log handler. * * @param name name of the handler. */ QI_API void removeLogHandler(const std::string& name); /** \class LogStream log.hpp "qi/log.hpp" */ class LogStream: public std::stringstream { public: /** * \brief LogStream. Copy Ctor. * @param rhs LogStream. */ LogStream(const LogStream &rhs) : _logLevel(rhs._logLevel) , _category(rhs._category) , _file(rhs._file) , _function(rhs._function) , _line(rhs._line) { } /** * \brief LogStream assignment operator. * @param rhs LogStream. */ const LogStream &operator=(const LogStream &rhs) { _logLevel = rhs._logLevel; _category = rhs._category; _file = rhs._file; _function = rhs._function; _line = rhs._line; return *this; } /** * \brief LogStream. Will log at object destruction * @param level { debug = 6, verbose=5, info = 4, warning = 3, error = 2, fatal = 1, silent = 0 } * @param file __FILE__ * @param function __FUNCTION__ * @param line __LINE__ * @param category log category */ LogStream(const LogLevel level, const char *file, const char *function, const int line, const char *category) : _logLevel(level) , _category(category) , _file(file) , _function(function) , _line(line) { } /** * \brief LogStream. Will log at object destruction * @param level { debug = 6, verbose=5, info = 4, warning = 3, error = 2, fatal = 1, silent = 0 } * @param file __FILE__ * @param function __FUNCTION__ * @param line __LINE__ * @param category log category * @param fmt message format. */ LogStream(const LogLevel level, const char *file, const char *function, const int line, const char *category, const char *fmt, ...) : _logLevel(level) , _category(category) , _file(file) , _function(function) , _line(line) { char buffer[2048]; va_list vl; va_start(vl, fmt); #ifdef _MSC_VER vsnprintf_s(buffer, 2048, 2047, fmt, vl); #else vsnprintf(buffer, 2048, fmt, vl); #endif buffer[2047] = 0; va_end(vl); *this << buffer; } /** \brief Destructor */ ~LogStream() { qi::log::log(_logLevel, _category, this->str().c_str(), _file, _function, _line); } /** \brief Necessary to work with an anonymous object */ LogStream& self() { return *this; } private: LogLevel _logLevel; const char *_category; const char *_file; const char *_function; int _line; }; } } #endif // !LOG_HPP_ <|endoftext|>
<commit_before>/******************************************************* * Copyright (c) 2014, ArrayFire * All rights reserved. * * This file is distributed under 3-clause BSD license. * The complete license agreement can be obtained at: * http://arrayfire.com/licenses/BSD-3-Clause ********************************************************/ #include <stdio.h> #include <iostream> #include <arrayfire.h> #include <cmath> #include <cstdlib> #define WIDTH 400 // Width of image #define HEIGHT 400 // Width of image using namespace af; using std::abs; array complex_grid(int width, int height, float zoom, float center[2]) { // Generate sequences of length width, height array X = (iota(dim4(1, height), dim4(width , 1)) - (float)height / 2.0) / zoom + center[0]; array Y = (iota(dim4(width , 1), dim4(1, height)) - (float)width / 2.0) / zoom + center[1]; // Return the locations as a complex grid return complex(X, Y); } array mandelbrot(const array &in, int iter, float maxval) { array C = in; array Z = C; array mag = constant(0, C.dims()); for (int ii = 1; ii < iter; ii++) { // Do the calculation Z = Z * Z + C; // Get indices where abs(Z) crosses maxval array cond = (abs(Z) > maxval).as(f32); mag = af::max(mag, cond * ii); // If abs(Z) cross maxval, turn off those locations C = C * (1 - cond); Z = Z * (1 - cond); // Ensuring the JIT does not become too large C.eval(); Z.eval(); } // Normalize return mag / maxval; } array normalize(array a) { float mx = af::max<float>(a); float mn = af::min<float>(a); return (a-mn)/(mx-mn); } int main(int argc, char **argv) { int device = argc > 1 ? atoi(argv[1]) : 0; int iter = argc > 2 ? atoi(argv[2]) : 100; bool console = argc > 2 ? argv[2][0] == '-' : false; try { af::setDevice(device); info(); printf("** ArrayFire Fractals Demo **\n"); af::Window wnd(WIDTH, HEIGHT, "Fractal Demo"); wnd.setColorMap(AF_COLORMAP_SPECTRUM); float center[] = {-0.75, 0.1}; // Keep zomming out for each frame for (int i = 10; i < 400; i++) { int zoom = i * i; if(!(i % 10)) printf("iteration: %d zoom: %d\n", i, zoom); fflush(stdout); // Generate the grid at the current zoom factor array c = complex_grid(WIDTH, HEIGHT, zoom, center); iter =sqrt(abs(2*sqrt(abs(1-sqrt(5*zoom)))))*100; // Generate the mandelbrot image array mag = mandelbrot(c, iter, 1000); if(!console) { if (wnd.close()) break; array mag_norm = normalize(mag); wnd.image(mag_norm); } } } catch (af::exception &e) { fprintf(stderr, "%s\n", e.what()); throw; } return 0; } <commit_msg>BUGFIX Fractal example failing because JIT tree was too long<commit_after>/******************************************************* * Copyright (c) 2014, ArrayFire * All rights reserved. * * This file is distributed under 3-clause BSD license. * The complete license agreement can be obtained at: * http://arrayfire.com/licenses/BSD-3-Clause ********************************************************/ #include <stdio.h> #include <iostream> #include <arrayfire.h> #include <cmath> #include <cstdlib> #define WIDTH 400 // Width of image #define HEIGHT 400 // Width of image using namespace af; using std::abs; array complex_grid(int width, int height, float zoom, float center[2]) { // Generate sequences of length width, height array X = (iota(dim4(1, height), dim4(width , 1)) - (float)height / 2.0) / zoom + center[0]; array Y = (iota(dim4(width , 1), dim4(1, height)) - (float)width / 2.0) / zoom + center[1]; // Return the locations as a complex grid return complex(X, Y); } array mandelbrot(const array &in, int iter, float maxval) { array C = in; array Z = C; array mag = constant(0, C.dims()); for (int ii = 1; ii < iter; ii++) { // Do the calculation Z = Z * Z + C; // Get indices where abs(Z) crosses maxval array cond = (abs(Z) > maxval).as(f32); mag = af::max(mag, cond * ii); // If abs(Z) cross maxval, turn off those locations C = C * (1 - cond); Z = Z * (1 - cond); // Ensuring the JIT does not become too large af::eval(C, Z); mag.eval(); } // Normalize return mag / maxval; } array normalize(array a) { float mx = af::max<float>(a); float mn = af::min<float>(a); return (a-mn)/(mx-mn); } int main(int argc, char **argv) { int device = argc > 1 ? atoi(argv[1]) : 0; int iter = argc > 2 ? atoi(argv[2]) : 100; bool console = argc > 2 ? argv[2][0] == '-' : false; try { af::setDevice(device); info(); printf("** ArrayFire Fractals Demo **\n"); af::Window wnd(WIDTH, HEIGHT, "Fractal Demo"); wnd.setColorMap(AF_COLORMAP_SPECTRUM); float center[] = {-0.75, 0.1}; // Keep zomming out for each frame for (int i = 10; i < 400; i++) { int zoom = i * i; if(!(i % 10)) printf("iteration: %d zoom: %d\n", i, zoom); fflush(stdout); // Generate the grid at the current zoom factor array c = complex_grid(WIDTH, HEIGHT, zoom, center); iter =sqrt(abs(2*sqrt(abs(1-sqrt(5*zoom)))))*100; // Generate the mandelbrot image array mag = mandelbrot(c, iter, 1000); if(!console) { if (wnd.close()) break; array mag_norm = normalize(mag); wnd.image(mag_norm); } } } catch (af::exception &e) { fprintf(stderr, "%s\n", e.what()); throw; } return 0; } <|endoftext|>
<commit_before>/* Copyright 2015 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include <unordered_map> #include <vector> #include "tensorflow/core/kernels/save_restore_tensor.h" #include "tensorflow/core/framework/op_kernel.h" #include "tensorflow/core/framework/register_types.h" #include "tensorflow/core/framework/types.h" #include "tensorflow/core/kernels/bounds_check.h" #include "tensorflow/core/lib/gtl/array_slice.h" #include "tensorflow/core/lib/strings/strcat.h" #include "tensorflow/core/lib/strings/stringprintf.h" #include "tensorflow/core/platform/logging.h" #include "tensorflow/core/platform/types.h" #include "tensorflow/core/util/tensor_bundle/tensor_bundle.h" #include "tensorflow/core/util/tensor_slice_reader.h" #include "tensorflow/core/util/tensor_slice_reader_cache.h" #include "tensorflow/core/util/tensor_slice_writer.h" namespace tensorflow { void SaveTensors( OpKernelContext* context, checkpoint::TensorSliceWriter::CreateBuilderFunction builder_func, bool save_slices) { const Tensor& filename_t = context->input(0); { const int64 size = filename_t.NumElements(); OP_REQUIRES( context, size == 1, errors::InvalidArgument( "Input 0 (filename) must be a string scalar; got a tensor of ", size, "elements")); } // Path, names, and slices if save_slices is true. const int kFixedInputs = save_slices ? 3 : 2; const Tensor& tensor_names_t = context->input(1); OP_REQUIRES(context, FastBoundsCheck(tensor_names_t.NumElements() + kFixedInputs, std::numeric_limits<int>::max()), errors::InvalidArgument("Too many inputs to SaveTensors")); const int N = static_cast<int>(tensor_names_t.NumElements()); const string* tensor_shapes_and_slices_ptr = nullptr; if (save_slices) { const Tensor& tensor_shapes_and_slices_t = context->input(2); OP_REQUIRES( context, tensor_shapes_and_slices_t.NumElements() == static_cast<int64>(N), errors::InvalidArgument("Expected ", N, " elements for the tensor " "shapes and slices but got ", tensor_shapes_and_slices_t.NumElements())); tensor_shapes_and_slices_ptr = tensor_shapes_and_slices_t.flat<string>().data(); } OP_REQUIRES(context, context->num_inputs() == N + kFixedInputs, errors::InvalidArgument("Expected totally ", N + kFixedInputs, " inputs as input #1 (which is a string " "tensor of saved names) contains ", N, " names, but received ", context->num_inputs(), " inputs")); VLOG(1) << "About to save tensors to file " << filename_t.flat<string>()(0) << "..."; checkpoint::TensorSliceWriter writer(filename_t.flat<string>()(0), builder_func); Status s; auto tensor_names_flat = tensor_names_t.flat<string>(); for (int i = 0; i < N; ++i) { const string& name = tensor_names_flat(i); const Tensor& input = context->input(i + kFixedInputs); TensorShape shape(input.shape()); TensorSlice slice(input.dims()); if (save_slices && !tensor_shapes_and_slices_ptr[i].empty()) { const string& shape_spec = tensor_shapes_and_slices_ptr[i]; TensorShape slice_shape; OP_REQUIRES_OK(context, checkpoint::ParseShapeAndSlice( shape_spec, &shape, &slice, &slice_shape)); OP_REQUIRES(context, slice_shape.IsSameSize(input.shape()), errors::InvalidArgument("Slice in shape_and_slice " "specification does not match the " "shape of the tensor to save: ", shape_spec, ", tensor: ", input.shape().DebugString())); } #define WRITER_ADD(T) \ case DataTypeToEnum<T>::value: \ s = writer.Add(name, shape, slice, input.flat<T>().data()); \ break; switch (input.dtype()) { TF_CALL_POD_STRING_TYPES(WRITER_ADD) TF_CALL_QUANTIZED_TYPES(WRITER_ADD) default: context->SetStatus(errors::Unimplemented("Saving data type ", DataTypeString(input.dtype()), " not yet supported")); return; } #undef WRITER_ADD if (!s.ok()) { context->SetStatus(s); return; } } s = writer.Finish(); if (!s.ok()) { context->SetStatus(s); } } void RestoreTensor(OpKernelContext* context, checkpoint::TensorSliceReader::OpenTableFunction open_func, int preferred_shard, bool restore_slice) { const Tensor& file_pattern_t = context->input(0); { const int64 size = file_pattern_t.NumElements(); OP_REQUIRES( context, size == 1, errors::InvalidArgument( "Input 0 (file_pattern) must be a string scalar; got a tensor of ", size, "elements")); } const string& file_pattern = file_pattern_t.flat<string>()(0); const Tensor& tensor_name_t = context->input(1); { const int64 size = tensor_name_t.NumElements(); OP_REQUIRES( context, size == 1, errors::InvalidArgument( "Input 1 (tensor_name) must be a string scalar; got a tensor of ", size, "elements")); } const string& tensor_name = tensor_name_t.flat<string>()(0); const string* tensor_shape_and_slice_ptr = nullptr; if (restore_slice) { const Tensor& tensor_shape_and_slice_t = context->input(2); OP_REQUIRES( context, tensor_shape_and_slice_t.NumElements() == 1, errors::InvalidArgument("Expected 1 element for the tensor " "shape and slice but got ", tensor_shape_and_slice_t.NumElements())); tensor_shape_and_slice_ptr = tensor_shape_and_slice_t.flat<string>().data(); } // If we cannot find a cached reader we will allocate our own. std::unique_ptr<checkpoint::TensorSliceReader> allocated_reader; const checkpoint::TensorSliceReader* reader = context->slice_reader_cache()->GetReader(file_pattern, open_func, preferred_shard); if (!reader) { allocated_reader.reset(new checkpoint::TensorSliceReader( file_pattern, open_func, preferred_shard)); reader = allocated_reader.get(); } OP_REQUIRES_OK(context, CHECK_NOTNULL(reader)->status()); // Get the shape and type from the save file. DataType type; TensorShape saved_shape; OP_REQUIRES( context, reader->HasTensor(tensor_name, &saved_shape, &type), errors::NotFound("Tensor name \"", tensor_name, "\" not found in checkpoint files ", file_pattern)); OP_REQUIRES( context, type == context->expected_output_dtype(0), errors::InvalidArgument("Expected to restore a tensor of type ", DataTypeString(context->expected_output_dtype(0)), ", got a tensor of type ", DataTypeString(type), " instead: tensor_name = ", tensor_name)); // Shape of the output and slice to load. TensorShape output_shape(saved_shape); TensorSlice slice_to_load(saved_shape.dims()); if (restore_slice && !tensor_shape_and_slice_ptr[0].empty()) { const string& shape_spec = tensor_shape_and_slice_ptr[0]; TensorShape parsed_shape; OP_REQUIRES_OK( context, checkpoint::ParseShapeAndSlice(shape_spec, &parsed_shape, &slice_to_load, &output_shape)); OP_REQUIRES( context, parsed_shape.IsSameSize(saved_shape), errors::InvalidArgument( "Shape in shape_and_slice spec does not match the shape in the " "save file: ", parsed_shape.DebugString(), ", save file shape: ", saved_shape.DebugString())); } Tensor* t = nullptr; OP_REQUIRES_OK(context, context->allocate_output(0, output_shape, &t)); if (output_shape.num_elements() == 0) return; #define READER_COPY(T) \ case DataTypeToEnum<T>::value: \ reader->CopySliceData(tensor_name, slice_to_load, t->flat<T>().data()); \ break; switch (type) { TF_CALL_POD_STRING_TYPES(READER_COPY) TF_CALL_QUANTIZED_TYPES(READER_COPY) default: context->SetStatus(errors::Unimplemented( "Restoring data type ", DataTypeString(type), " not yet supported")); } #undef READER_COPY } Status RestoreTensorsV2(OpKernelContext* context, const Tensor& prefix, const Tensor& tensor_names, const Tensor& shape_and_slices, gtl::ArraySlice<DataType> dtypes) { const string& prefix_string = prefix.scalar<string>()(); const auto& tensor_names_flat = tensor_names.flat<string>(); const auto& shape_and_slices_flat = shape_and_slices.flat<string>(); BundleReader reader(Env::Default(), prefix_string); TF_RETURN_IF_ERROR(reader.status()); // TODO(zongheng): potential optimization: one Seek() in first lookup. // TODO(zongheng): consider measuring speed and issuing concurrent lookups // within a fixed memory budget. TensorShape restored_full_shape; Tensor* restored_tensor = nullptr; for (size_t i = 0; i < tensor_names_flat.size(); ++i) { const string& tensor_name = tensor_names_flat(i); const string& shape_and_slice = shape_and_slices_flat(i); TF_RETURN_IF_ERROR( reader.LookupTensorShape(tensor_name, &restored_full_shape)); if (shape_and_slice.empty()) { // Lookup the full tensor. TF_RETURN_IF_ERROR( context->allocate_output(i, restored_full_shape, &restored_tensor)); TF_RETURN_IF_ERROR(reader.Lookup(tensor_name, restored_tensor)); } else { // Lookup the slice. TensorShape parsed_full_shape; TensorSlice parsed_slice; TensorShape parsed_slice_shape; TF_RETURN_IF_ERROR( checkpoint::ParseShapeAndSlice(shape_and_slice, &parsed_full_shape, &parsed_slice, &parsed_slice_shape)); if (!restored_full_shape.IsSameSize(parsed_full_shape)) { return errors::InvalidArgument( "Shape in shape_and_slice spec ", parsed_full_shape.DebugString(), " does not match the shape stored in checkpoint: ", restored_full_shape.DebugString()); } TF_RETURN_IF_ERROR( context->allocate_output(i, parsed_slice_shape, &restored_tensor)); TF_RETURN_IF_ERROR( reader.LookupSlice(tensor_name, parsed_slice, restored_tensor)); } if (dtypes[i] != restored_tensor->dtype()) { return errors::InvalidArgument("Expected dtype ", DataTypeString(dtypes[i]), " does not equal restored dtype ", DataTypeString(restored_tensor->dtype())); } } return Status::OK(); } } // namespace tensorflow <commit_msg>Add var name to errors on variable restore. Change: 152963830<commit_after>/* Copyright 2015 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include <unordered_map> #include <vector> #include "tensorflow/core/kernels/save_restore_tensor.h" #include "tensorflow/core/framework/op_kernel.h" #include "tensorflow/core/framework/register_types.h" #include "tensorflow/core/framework/types.h" #include "tensorflow/core/kernels/bounds_check.h" #include "tensorflow/core/lib/gtl/array_slice.h" #include "tensorflow/core/lib/strings/strcat.h" #include "tensorflow/core/lib/strings/stringprintf.h" #include "tensorflow/core/platform/logging.h" #include "tensorflow/core/platform/types.h" #include "tensorflow/core/util/tensor_bundle/tensor_bundle.h" #include "tensorflow/core/util/tensor_slice_reader.h" #include "tensorflow/core/util/tensor_slice_reader_cache.h" #include "tensorflow/core/util/tensor_slice_writer.h" namespace tensorflow { void SaveTensors( OpKernelContext* context, checkpoint::TensorSliceWriter::CreateBuilderFunction builder_func, bool save_slices) { const Tensor& filename_t = context->input(0); { const int64 size = filename_t.NumElements(); OP_REQUIRES( context, size == 1, errors::InvalidArgument( "Input 0 (filename) must be a string scalar; got a tensor of ", size, "elements")); } // Path, names, and slices if save_slices is true. const int kFixedInputs = save_slices ? 3 : 2; const Tensor& tensor_names_t = context->input(1); OP_REQUIRES(context, FastBoundsCheck(tensor_names_t.NumElements() + kFixedInputs, std::numeric_limits<int>::max()), errors::InvalidArgument("Too many inputs to SaveTensors")); const int N = static_cast<int>(tensor_names_t.NumElements()); const string* tensor_shapes_and_slices_ptr = nullptr; if (save_slices) { const Tensor& tensor_shapes_and_slices_t = context->input(2); OP_REQUIRES( context, tensor_shapes_and_slices_t.NumElements() == static_cast<int64>(N), errors::InvalidArgument("Expected ", N, " elements for the tensor " "shapes and slices but got ", tensor_shapes_and_slices_t.NumElements())); tensor_shapes_and_slices_ptr = tensor_shapes_and_slices_t.flat<string>().data(); } OP_REQUIRES(context, context->num_inputs() == N + kFixedInputs, errors::InvalidArgument("Expected totally ", N + kFixedInputs, " inputs as input #1 (which is a string " "tensor of saved names) contains ", N, " names, but received ", context->num_inputs(), " inputs")); VLOG(1) << "About to save tensors to file " << filename_t.flat<string>()(0) << "..."; checkpoint::TensorSliceWriter writer(filename_t.flat<string>()(0), builder_func); Status s; auto tensor_names_flat = tensor_names_t.flat<string>(); for (int i = 0; i < N; ++i) { const string& name = tensor_names_flat(i); const Tensor& input = context->input(i + kFixedInputs); TensorShape shape(input.shape()); TensorSlice slice(input.dims()); if (save_slices && !tensor_shapes_and_slices_ptr[i].empty()) { const string& shape_spec = tensor_shapes_and_slices_ptr[i]; TensorShape slice_shape; OP_REQUIRES_OK(context, checkpoint::ParseShapeAndSlice( shape_spec, &shape, &slice, &slice_shape)); OP_REQUIRES(context, slice_shape.IsSameSize(input.shape()), errors::InvalidArgument("Slice in shape_and_slice " "specification does not match the " "shape of the tensor to save: ", shape_spec, ", tensor: ", input.shape().DebugString())); } #define WRITER_ADD(T) \ case DataTypeToEnum<T>::value: \ s = writer.Add(name, shape, slice, input.flat<T>().data()); \ break; switch (input.dtype()) { TF_CALL_POD_STRING_TYPES(WRITER_ADD) TF_CALL_QUANTIZED_TYPES(WRITER_ADD) default: context->SetStatus(errors::Unimplemented("Saving data type ", DataTypeString(input.dtype()), " not yet supported")); return; } #undef WRITER_ADD if (!s.ok()) { context->SetStatus(s); return; } } s = writer.Finish(); if (!s.ok()) { context->SetStatus(s); } } void RestoreTensor(OpKernelContext* context, checkpoint::TensorSliceReader::OpenTableFunction open_func, int preferred_shard, bool restore_slice) { const Tensor& file_pattern_t = context->input(0); { const int64 size = file_pattern_t.NumElements(); OP_REQUIRES( context, size == 1, errors::InvalidArgument( "Input 0 (file_pattern) must be a string scalar; got a tensor of ", size, "elements")); } const string& file_pattern = file_pattern_t.flat<string>()(0); const Tensor& tensor_name_t = context->input(1); { const int64 size = tensor_name_t.NumElements(); OP_REQUIRES( context, size == 1, errors::InvalidArgument( "Input 1 (tensor_name) must be a string scalar; got a tensor of ", size, "elements")); } const string& tensor_name = tensor_name_t.flat<string>()(0); const string* tensor_shape_and_slice_ptr = nullptr; if (restore_slice) { const Tensor& tensor_shape_and_slice_t = context->input(2); OP_REQUIRES( context, tensor_shape_and_slice_t.NumElements() == 1, errors::InvalidArgument("Expected 1 element for the tensor " "shape and slice but got ", tensor_shape_and_slice_t.NumElements())); tensor_shape_and_slice_ptr = tensor_shape_and_slice_t.flat<string>().data(); } // If we cannot find a cached reader we will allocate our own. std::unique_ptr<checkpoint::TensorSliceReader> allocated_reader; const checkpoint::TensorSliceReader* reader = context->slice_reader_cache()->GetReader(file_pattern, open_func, preferred_shard); if (!reader) { allocated_reader.reset(new checkpoint::TensorSliceReader( file_pattern, open_func, preferred_shard)); reader = allocated_reader.get(); } OP_REQUIRES_OK(context, CHECK_NOTNULL(reader)->status()); // Get the shape and type from the save file. DataType type; TensorShape saved_shape; OP_REQUIRES( context, reader->HasTensor(tensor_name, &saved_shape, &type), errors::NotFound("Tensor name \"", tensor_name, "\" not found in checkpoint files ", file_pattern)); OP_REQUIRES( context, type == context->expected_output_dtype(0), errors::InvalidArgument("Expected to restore a tensor of type ", DataTypeString(context->expected_output_dtype(0)), ", got a tensor of type ", DataTypeString(type), " instead: tensor_name = ", tensor_name)); // Shape of the output and slice to load. TensorShape output_shape(saved_shape); TensorSlice slice_to_load(saved_shape.dims()); if (restore_slice && !tensor_shape_and_slice_ptr[0].empty()) { const string& shape_spec = tensor_shape_and_slice_ptr[0]; TensorShape parsed_shape; OP_REQUIRES_OK( context, checkpoint::ParseShapeAndSlice(shape_spec, &parsed_shape, &slice_to_load, &output_shape)); OP_REQUIRES( context, parsed_shape.IsSameSize(saved_shape), errors::InvalidArgument( "Shape in shape_and_slice spec does not match the shape in the " "save file: ", parsed_shape.DebugString(), ", save file shape: ", saved_shape.DebugString())); } Tensor* t = nullptr; OP_REQUIRES_OK(context, context->allocate_output(0, output_shape, &t)); if (output_shape.num_elements() == 0) return; #define READER_COPY(T) \ case DataTypeToEnum<T>::value: \ reader->CopySliceData(tensor_name, slice_to_load, t->flat<T>().data()); \ break; switch (type) { TF_CALL_POD_STRING_TYPES(READER_COPY) TF_CALL_QUANTIZED_TYPES(READER_COPY) default: context->SetStatus(errors::Unimplemented( "Restoring data type ", DataTypeString(type), " not yet supported")); } #undef READER_COPY } Status RestoreTensorsV2(OpKernelContext* context, const Tensor& prefix, const Tensor& tensor_names, const Tensor& shape_and_slices, gtl::ArraySlice<DataType> dtypes) { const string& prefix_string = prefix.scalar<string>()(); const auto& tensor_names_flat = tensor_names.flat<string>(); const auto& shape_and_slices_flat = shape_and_slices.flat<string>(); BundleReader reader(Env::Default(), prefix_string); TF_RETURN_IF_ERROR(reader.status()); // TODO(zongheng): potential optimization: one Seek() in first lookup. // TODO(zongheng): consider measuring speed and issuing concurrent lookups // within a fixed memory budget. TensorShape restored_full_shape; Tensor* restored_tensor = nullptr; for (size_t i = 0; i < tensor_names_flat.size(); ++i) { const string& tensor_name = tensor_names_flat(i); const string& shape_and_slice = shape_and_slices_flat(i); TF_RETURN_IF_ERROR( reader.LookupTensorShape(tensor_name, &restored_full_shape)); if (shape_and_slice.empty()) { // Lookup the full tensor. TF_RETURN_IF_ERROR( context->allocate_output(i, restored_full_shape, &restored_tensor)); TF_RETURN_IF_ERROR(reader.Lookup(tensor_name, restored_tensor)); } else { // Lookup the slice. TensorShape parsed_full_shape; TensorSlice parsed_slice; TensorShape parsed_slice_shape; TF_RETURN_IF_ERROR( checkpoint::ParseShapeAndSlice(shape_and_slice, &parsed_full_shape, &parsed_slice, &parsed_slice_shape)); if (!restored_full_shape.IsSameSize(parsed_full_shape)) { return errors::InvalidArgument( "tensor_name = ", tensor_name, "; shape in shape_and_slice spec ", parsed_full_shape.DebugString(), " does not match the shape stored in checkpoint: ", restored_full_shape.DebugString()); } TF_RETURN_IF_ERROR( context->allocate_output(i, parsed_slice_shape, &restored_tensor)); TF_RETURN_IF_ERROR( reader.LookupSlice(tensor_name, parsed_slice, restored_tensor)); } if (dtypes[i] != restored_tensor->dtype()) { return errors::InvalidArgument( "tensor_name = ", tensor_name, "; expected dtype ", DataTypeString(dtypes[i]), " does not equal restored dtype ", DataTypeString(restored_tensor->dtype())); } } return Status::OK(); } } // namespace tensorflow <|endoftext|>
<commit_before>/* * The MIT License (MIT) * * Copyright (c) 2016 nyorain * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ ///\file ///\brief Includes all stable nytl headers. #pragma once #ifndef NYTL_INCLUDE_NYTL_HPP #define NYTL_INCLUDE_NYTL_HPP #include <nytl/any.hpp> #include <nytl/cache.hpp> #include <nytl/callback.hpp> #include <nytl/clone.hpp> #include <nytl/connection.hpp> #include <nytl/convert.hpp> #include <nytl/compFunc.hpp> #include <nytl/dynVec.hpp> #include <nytl/flags.hpp> #include <nytl/functionTraits.hpp> #include <nytl/line.hpp> #include <nytl/log.hpp> #include <nytl/mat.hpp> #include <nytl/misc.hpp> #include <nytl/nonCopyable.hpp> #include <nytl/observe.hpp> #include <nytl/rect.hpp> #include <nytl/rectRegion.hpp> #include <nytl/referenced.hpp> #include <nytl/refVec.hpp> #include <nytl/scalar.hpp> #include <nytl/simplex.hpp> #include <nytl/stringParam.hpp> #include <nytl/system.hpp> #include <nytl/time.hpp> #include <nytl/tmp.hpp> #include <nytl/transform.hpp> #include <nytl/triangle.hpp> #include <nytl/typemap.hpp> #include <nytl/vec.hpp> #endif //header guard <commit_msg>fixes nytl.hpp<commit_after>/* * The MIT License (MIT) * * Copyright (c) 2016 nyorain * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ ///\file ///\brief Includes all stable nytl headers. #pragma once #ifndef NYTL_INCLUDE_NYTL_HPP #define NYTL_INCLUDE_NYTL_HPP #include <nytl/cache.hpp> #include <nytl/callback.hpp> #include <nytl/clone.hpp> #include <nytl/connection.hpp> #include <nytl/convert.hpp> #include <nytl/compFunc.hpp> #include <nytl/dynVec.hpp> #include <nytl/flags.hpp> #include <nytl/functionTraits.hpp> #include <nytl/line.hpp> #include <nytl/log.hpp> #include <nytl/mat.hpp> #include <nytl/misc.hpp> #include <nytl/nonCopyable.hpp> #include <nytl/observe.hpp> #include <nytl/rect.hpp> #include <nytl/rectRegion.hpp> #include <nytl/referenced.hpp> #include <nytl/refVec.hpp> #include <nytl/scalar.hpp> #include <nytl/scope.hpp> #include <nytl/simplex.hpp> #include <nytl/stringParam.hpp> #include <nytl/system.hpp> #include <nytl/time.hpp> #include <nytl/tmp.hpp> #include <nytl/transform.hpp> #include <nytl/triangle.hpp> #include <nytl/typemap.hpp> #include <nytl/vec.hpp> #endif //header guard <|endoftext|>
<commit_before>// https://github.com/KubaO/stackoverflown/tree/master/questions/local-pipe-32317081 // This project is compatible with Qt 4 and Qt 5 #include <QtTest> #include <private/qiodevice_p.h> #include <private/qringbuffer_p.h> #include <algorithm> #include <climits> #ifndef Q_DECL_OVERRIDE #define Q_DECL_OVERRIDE #endif class AppPipePrivate : public QIODevicePrivate { public: #if QT_VERSION < QT_VERSION_CHECK(5,7,0) QRingBuffer buffer; QRingBuffer writeBuffer; int writeBufferChunkSize; #endif const QByteArray *writeData; AppPipePrivate() : writeData(0) { writeBufferChunkSize = 4096; } }; /// A simple point-to-point intra-process pipe. The other endpoint can live in any /// thread. class AppPipe : public QIODevice { Q_OBJECT Q_DECLARE_PRIVATE(AppPipe) static inline int intLen(qint64 len) { return std::min(len, qint64(INT_MAX)); } Q_SLOT void _a_write(const QByteArray &data) { Q_D(AppPipe); if (!(d->openMode & QIODevice::ReadOnly)) return; // We must be readable. d->buffer.append(data); // This is a chunk shipped from the source. emit hasIncoming(data); emit readyRead(); } void hasOutgoingLong(const char *data, qint64 len) { while (len) { int const size = intLen(len); emit hasOutgoing(QByteArray(data, size)); data += size; len -= size; } } public: AppPipe(QIODevice::OpenMode mode, QObject *parent = 0) : QIODevice(*new AppPipePrivate, parent) { open(mode); } AppPipe(AppPipe *other, QIODevice::OpenMode mode, QObject *parent = 0) : QIODevice(*new AppPipePrivate, parent) { open(mode); addOther(other); } AppPipe(AppPipe *other, QObject *parent = 0) : QIODevice(*new AppPipePrivate, parent) { addOther(other); } ~AppPipe() Q_DECL_OVERRIDE {} void addOther(AppPipe *other) { if (other) { connect(this, SIGNAL(hasOutgoing(QByteArray)), other, SLOT(_a_write(QByteArray)), Qt::UniqueConnection); connect(other, SIGNAL(hasOutgoing(QByteArray)), this, SLOT(_a_write(QByteArray)), Qt::UniqueConnection); } } void removeOther(AppPipe *other) { disconnect(this, SIGNAL(hasOutgoing(QByteArray)), other, SLOT(_a_write(QByteArray))); disconnect(other, SIGNAL(hasOutgoing(QByteArray)), this, SLOT(_a_write(QByteArray))); } void flush() { Q_D(AppPipe); while (!d->writeBuffer.isEmpty()) { QByteArray const data = d->writeBuffer.read(); emit hasOutgoing(data); emit bytesWritten(data.size()); } } void close() Q_DECL_OVERRIDE { Q_D(AppPipe); flush(); QIODevice::close(); d->buffer.clear(); } qint64 write(const QByteArray &data) { // This is an optional optimization. The base method works OK. Q_D(AppPipe); QScopedValueRollback<const QByteArray*> back(d->writeData); if (!(d->openMode & Text)) d->writeData = &data; return QIODevice::write(data); } qint64 writeData(const char *data, qint64 len) Q_DECL_OVERRIDE { Q_D(AppPipe); bool buffered = !(d->openMode & Unbuffered); if (buffered && (d->writeBuffer.size() + len) > d->writeBufferChunkSize) flush(); if (!buffered || len > d->writeBufferChunkSize || (len == d->writeBufferChunkSize && d->writeBuffer.isEmpty())) { if (d->writeData && d->writeData->data() == data && d->writeData->size() == len) emit hasOutgoing(*d->writeData); else hasOutgoingLong(data, len); } else memcpy(d->writeBuffer.reserve(len), data, len); return len; } bool isSequential() const Q_DECL_OVERRIDE { return true; } Q_SIGNAL void hasOutgoing(const QByteArray &); Q_SIGNAL void hasIncoming(const QByteArray &); #if QT_VERSION >= QT_VERSION_CHECK(5,7,0) // all the data is in the read buffer already qint64 readData(char *, qint64) Q_DECL_OVERRIDE { return 0; } #else qint64 readData(char *data, qint64 len) Q_DECL_OVERRIDE { Q_D(AppPipe); qint64 hadRead = 0; while (len && !d->buffer.isEmpty()) { int size = d->buffer.read(data, intLen(len)); hadRead += size; data += size; len -= size; } return hadRead; } bool canReadLine() const Q_DECL_OVERRIDE { Q_D(const AppPipe); return d->buffer.indexOf('\n') != -1 || QIODevice::canReadLine(); } qint64 bytesAvailable() const Q_DECL_OVERRIDE { Q_D(const AppPipe); return QIODevice::bytesAvailable() + d->buffer.size(); } qint64 bytesToWrite() const Q_DECL_OVERRIDE { Q_D(const AppPipe); return QIODevice::bytesToWrite() + d->writeBuffer.size(); } #endif }; class TestAppPipe : public QObject { Q_OBJECT QByteArray data1, data2; struct PipePair { AppPipe end1, end2; PipePair(QIODevice::OpenMode mode = QIODevice::NotOpen) : end1(QIODevice::ReadWrite | mode), end2(&end1, QIODevice::ReadWrite | mode) {} }; Q_SLOT void initTestCase() { data1 = randomData(); data2 = randomData(); } Q_SLOT void sizes() { QCOMPARE(sizeof(AppPipe), sizeof(QIODevice)); } Q_SLOT void basic() { PipePair p; QVERIFY(p.end1.isOpen() && p.end1.isWritable() && p.end1.isReadable()); QVERIFY(p.end2.isOpen() && p.end2.isWritable() && p.end2.isReadable()); static const char hello[] = "Hello There!"; p.end1.write(hello); p.end1.flush(); QCOMPARE(p.end2.readAll(), QByteArray(hello)); } static QByteArray randomData(int const size = 1024*1024*32) { QByteArray data; data.resize(size); char *const d = data.data(); for (char *p = d+data.size()-1; p >= d; --p) *p = qrand(); Q_ASSERT(data.size() == size); return data; } static void randomChunkWrite(AppPipe *dev, const QByteArray &payload) { for (int written = 0, left = payload.size(); left; ) { int const chunk = std::min(qrand() % 82931, left); dev->write(payload.mid(written, chunk)); left -= chunk; written += chunk; } dev->flush(); } void runBigData(PipePair &p) { Q_ASSERT(!data1.isEmpty() && !data2.isEmpty()); randomChunkWrite(&p.end1, data1); randomChunkWrite(&p.end2, data2); QCOMPARE(p.end1.bytesAvailable(), qint64(data2.size())); QCOMPARE(p.end2.bytesAvailable(), qint64(data1.size())); QCOMPARE(p.end1.readAll(), data2); QCOMPARE(p.end2.readAll(), data1); } Q_SLOT void bigDataBuffered() { PipePair p; runBigData(p); } Q_SLOT void bigDataUnbuffered() { PipePair p(QIODevice::Unbuffered); runBigData(p); } Q_SLOT void cleanupTestCase() { data1.clear(); data2.clear(); } }; QTEST_MAIN(TestAppPipe) #include "main.moc" <commit_msg>Tweak test names.<commit_after>// https://github.com/KubaO/stackoverflown/tree/master/questions/local-pipe-32317081 // This project is compatible with Qt 4 and Qt 5 #include <QtCore> #include <private/qiodevice_p.h> #include <private/qringbuffer_p.h> #include <algorithm> #include <climits> #ifndef Q_DECL_OVERRIDE #define Q_DECL_OVERRIDE #endif class AppPipePrivate : public QIODevicePrivate { public: #if QT_VERSION < QT_VERSION_CHECK(5,7,0) QRingBuffer buffer; QRingBuffer writeBuffer; int writeBufferChunkSize; #endif const QByteArray *writeData; AppPipePrivate() : writeData(0) { writeBufferChunkSize = 4096; } }; /// A simple point-to-point intra-process pipe. The other endpoint can live in any /// thread. class AppPipe : public QIODevice { Q_OBJECT Q_DECLARE_PRIVATE(AppPipe) static inline int intLen(qint64 len) { return std::min(len, qint64(INT_MAX)); } Q_SLOT void _a_write(const QByteArray &data) { Q_D(AppPipe); if (!(d->openMode & QIODevice::ReadOnly)) return; // We must be readable. d->buffer.append(data); // This is a chunk shipped from the source. emit hasIncoming(data); emit readyRead(); } void hasOutgoingLong(const char *data, qint64 len) { while (len) { int const size = intLen(len); emit hasOutgoing(QByteArray(data, size)); data += size; len -= size; } } public: AppPipe(QIODevice::OpenMode mode, QObject *parent = 0) : QIODevice(*new AppPipePrivate, parent) { open(mode); } AppPipe(AppPipe *other, QIODevice::OpenMode mode, QObject *parent = 0) : QIODevice(*new AppPipePrivate, parent) { open(mode); addOther(other); } AppPipe(AppPipe *other, QObject *parent = 0) : QIODevice(*new AppPipePrivate, parent) { addOther(other); } ~AppPipe() Q_DECL_OVERRIDE {} void addOther(AppPipe *other) { if (other) { connect(this, SIGNAL(hasOutgoing(QByteArray)), other, SLOT(_a_write(QByteArray)), Qt::UniqueConnection); connect(other, SIGNAL(hasOutgoing(QByteArray)), this, SLOT(_a_write(QByteArray)), Qt::UniqueConnection); } } void removeOther(AppPipe *other) { disconnect(this, SIGNAL(hasOutgoing(QByteArray)), other, SLOT(_a_write(QByteArray))); disconnect(other, SIGNAL(hasOutgoing(QByteArray)), this, SLOT(_a_write(QByteArray))); } void flush() { Q_D(AppPipe); while (!d->writeBuffer.isEmpty()) { QByteArray const data = d->writeBuffer.read(); emit hasOutgoing(data); emit bytesWritten(data.size()); } } void close() Q_DECL_OVERRIDE { Q_D(AppPipe); flush(); QIODevice::close(); d->buffer.clear(); } qint64 write(const QByteArray &data) { // This is an optional optimization. The base method works OK. Q_D(AppPipe); QScopedValueRollback<const QByteArray*> back(d->writeData); if (!(d->openMode & Text)) d->writeData = &data; return QIODevice::write(data); } qint64 writeData(const char *data, qint64 len) Q_DECL_OVERRIDE { Q_D(AppPipe); bool buffered = !(d->openMode & Unbuffered); if (buffered && (d->writeBuffer.size() + len) > d->writeBufferChunkSize) flush(); if (!buffered || len > d->writeBufferChunkSize || (len == d->writeBufferChunkSize && d->writeBuffer.isEmpty())) { if (d->writeData && d->writeData->data() == data && d->writeData->size() == len) emit hasOutgoing(*d->writeData); else hasOutgoingLong(data, len); } else memcpy(d->writeBuffer.reserve(len), data, len); return len; } bool isSequential() const Q_DECL_OVERRIDE { return true; } Q_SIGNAL void hasOutgoing(const QByteArray &); Q_SIGNAL void hasIncoming(const QByteArray &); #if QT_VERSION >= QT_VERSION_CHECK(5,7,0) // all the data is in the read buffer already qint64 readData(char *, qint64) Q_DECL_OVERRIDE { return 0; } #else qint64 readData(char *data, qint64 len) Q_DECL_OVERRIDE { Q_D(AppPipe); qint64 hadRead = 0; while (len && !d->buffer.isEmpty()) { int size = d->buffer.read(data, intLen(len)); hadRead += size; data += size; len -= size; } return hadRead; } bool canReadLine() const Q_DECL_OVERRIDE { Q_D(const AppPipe); return d->buffer.indexOf('\n') != -1 || QIODevice::canReadLine(); } qint64 bytesAvailable() const Q_DECL_OVERRIDE { Q_D(const AppPipe); return QIODevice::bytesAvailable() + d->buffer.size(); } qint64 bytesToWrite() const Q_DECL_OVERRIDE { Q_D(const AppPipe); return QIODevice::bytesToWrite() + d->writeBuffer.size(); } #endif }; #include <QtTest> class TestAppPipe : public QObject { Q_OBJECT QByteArray data1, data2; struct PipePair { AppPipe end1, end2; PipePair(QIODevice::OpenMode mode = QIODevice::NotOpen) : end1(QIODevice::ReadWrite | mode), end2(&end1, QIODevice::ReadWrite | mode) {} }; Q_SLOT void initTestCase() { data1 = randomData(); data2 = randomData(); } Q_SLOT void hasQIODeviceSize() { QCOMPARE(sizeof(AppPipe), sizeof(QIODevice)); } Q_SLOT void transfersBasicData() { PipePair p; QVERIFY(p.end1.isOpen() && p.end1.isWritable() && p.end1.isReadable()); QVERIFY(p.end2.isOpen() && p.end2.isWritable() && p.end2.isReadable()); static const char hello[] = "Hello There!"; p.end1.write(hello); p.end1.flush(); QCOMPARE(p.end2.readAll(), QByteArray(hello)); } static QByteArray randomData(int const size = 1024*1024*32) { QByteArray data; data.resize(size); char *const d = data.data(); for (char *p = d+data.size()-1; p >= d; --p) *p = qrand(); Q_ASSERT(data.size() == size); return data; } static void randomChunkWrite(AppPipe *dev, const QByteArray &payload) { for (int written = 0, left = payload.size(); left; ) { int const chunk = std::min(qrand() % 82931, left); dev->write(payload.mid(written, chunk)); left -= chunk; written += chunk; } dev->flush(); } void runBigData(PipePair &p) { Q_ASSERT(!data1.isEmpty() && !data2.isEmpty()); randomChunkWrite(&p.end1, data1); randomChunkWrite(&p.end2, data2); QCOMPARE(p.end1.bytesAvailable(), qint64(data2.size())); QCOMPARE(p.end2.bytesAvailable(), qint64(data1.size())); QCOMPARE(p.end1.readAll(), data2); QCOMPARE(p.end2.readAll(), data1); } Q_SLOT void transfersBigDataBuffered() { PipePair p; runBigData(p); } Q_SLOT void transfersBigDataUnbuffered() { PipePair p(QIODevice::Unbuffered); runBigData(p); } Q_SLOT void cleanupTestCase() { data1.clear(); data2.clear(); } }; QTEST_MAIN(TestAppPipe) #include "main.moc" <|endoftext|>
<commit_before>//===--- InstructionDeleter.cpp - InstructionDeleter utility --------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2021 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// #include "swift/SIL/SILFunction.h" #include "swift/SILOptimizer/Utils/ConstExpr.h" #include "swift/SILOptimizer/Utils/DebugOptUtils.h" #include "swift/SILOptimizer/Utils/InstructionDeleter.h" #include "swift/SILOptimizer/Utils/InstOptUtils.h" using namespace swift; static bool hasOnlyIncidentalUses(SILInstruction *inst, bool disallowDebugUses = false) { for (SILValue result : inst->getResults()) { for (Operand *use : result->getUses()) { SILInstruction *user = use->getUser(); if (!isIncidentalUse(user)) return false; if (disallowDebugUses && user->isDebugInstruction()) return false; } } return true; } /// A scope-affecting instruction is an instruction which may end the scope of /// its operand or may produce scoped results that require cleaning up. E.g. /// begin_borrow, begin_access, copy_value, a call that produces a owned value /// are scoped instructions. The scope of the results of the first two /// instructions end with an end_borrow/acess instruction, while those of the /// latter two end with a consuming operation like destroy_value instruction. /// These instruction may also end the scope of its operand e.g. a call could /// consume owned arguments thereby ending its scope. Dead-code eliminating a /// scope-affecting instruction requires fixing the lifetime of the non-trivial /// operands of the instruction and requires cleaning up the end-of-scope uses /// of non-trivial results. /// /// \param inst instruction that checked for liveness. /// /// TODO: Handle partial_apply [stack] which has a dealloc_stack user. static bool isScopeAffectingInstructionDead(SILInstruction *inst, bool fixLifetime) { SILFunction *fun = inst->getFunction(); assert(fun && "Instruction has no function."); // Only support ownership SIL for scoped instructions. if (!fun->hasOwnership()) { return false; } // If the instruction has any use other than end of scope use or destroy_value // use, bail out. if (!hasOnlyEndOfScopeOrEndOfLifetimeUses(inst)) { return false; } // If inst is a copy or beginning of scope, inst is dead, since we know that // it is used only in a destroy_value or end-of-scope instruction. if (getSingleValueCopyOrCast(inst)) return true; switch (inst->getKind()) { case SILInstructionKind::LoadBorrowInst: { // A load_borrow only used in an end_borrow is dead. return true; } case SILInstructionKind::LoadInst: { LoadOwnershipQualifier loadOwnershipQual = cast<LoadInst>(inst)->getOwnershipQualifier(); // If the load creates a copy, it is dead, since we know that if at all it // is used, it is only in a destroy_value instruction. return (loadOwnershipQual == LoadOwnershipQualifier::Copy || loadOwnershipQual == LoadOwnershipQualifier::Trivial); // TODO: we can handle load [take] but we would have to know that the // operand has been consumed. Note that OperandOwnershipKind map does not // say this for load. } case SILInstructionKind::PartialApplyInst: { bool onlyTrivialArgs = true; for (auto &arg : cast<PartialApplyInst>(inst)->getArgumentOperands()) { auto argTy = arg.get()->getType(); // Non-stack partial apply captures that are passed by address are always // captured at +1 by the closure contrext, regardless of the calling // convention. // // TODO: When on-stack partial applies are also handled, then their +0 // address arguments can be ignored. // // FIXME: Even with fixLifetimes enabled, InstructionDeleter does not know // how to cleanup arguments captured by address. This should be as simple // as inserting a destroy_addr. But the analagous code in // tryDeleteDeadClosure() and keepArgsOfPartialApplyAlive() mysteriously // creates new alloc_stack's and invalidates stack nesting. So we // conservatively bail-out until we understand why that hack exists. if (argTy.isAddress()) return false; onlyTrivialArgs &= argTy.isTrivial(*fun); } // Partial applies that are only used in destroys cannot have any effect on // the program state, provided the values they capture are explicitly // destroyed, which only happens when fixLifetime is true. return onlyTrivialArgs || fixLifetime; } case SILInstructionKind::StructInst: case SILInstructionKind::EnumInst: case SILInstructionKind::TupleInst: case SILInstructionKind::ConvertFunctionInst: case SILInstructionKind::DestructureStructInst: case SILInstructionKind::DestructureTupleInst: { // All these ownership forwarding instructions that are only used in // destroys are dead provided the values they consume are destroyed // explicitly. return true; } case SILInstructionKind::ApplyInst: { // The following property holds for constant-evaluable functions that do // not take arguments of generic type: // 1. they do not create objects having deinitializers with global // side effects, as they can only create objects consisting of trivial // values, (non-generic) arrays and strings. // 2. they do not use global variables or call arbitrary functions with // side effects. // The above two properties imply that a value returned by a constant // evaluable function does not have a deinitializer with global side // effects. Therefore, the deinitializer can be sinked. // // A generic, read-only constant evaluable call only reads and/or // destroys its (non-generic) parameters. It therefore cannot have any // side effects (note that parameters being non-generic have value // semantics). Therefore, the constant evaluable call can be removed // provided the parameter lifetimes are handled correctly, which is taken // care of by the function: \c deleteInstruction. FullApplySite applySite(cast<ApplyInst>(inst)); return isReadOnlyConstantEvaluableCall(applySite); } default: { return false; } } } bool InstructionDeleter::trackIfDead(SILInstruction *inst) { bool fixLifetime = inst->getFunction()->hasOwnership(); if (isInstructionTriviallyDead(inst) || isScopeAffectingInstructionDead(inst, fixLifetime)) { assert(!isIncidentalUse(inst) && !isa<DestroyValueInst>(inst) && "Incidental uses cannot be removed in isolation. " "They would be removed iff the operand is dead"); getCallbacks().notifyWillBeDeleted(inst); deadInstructions.insert(inst); return true; } return false; } void InstructionDeleter::forceTrackAsDead(SILInstruction *inst) { bool disallowDebugUses = inst->getFunction()->getEffectiveOptimizationMode() <= OptimizationMode::NoOptimization; assert(hasOnlyIncidentalUses(inst, disallowDebugUses)); getCallbacks().notifyWillBeDeleted(inst); deadInstructions.insert(inst); } /// Force-delete \p inst and all its uses. /// /// \p fixLifetimes causes new destroys to be inserted after dropping /// operands. /// /// \p forceDeleteUsers allows deleting an instruction with non-incidental, /// non-destoy uses, such as a store. /// /// Does not call callbacks.notifyWillBeDeleted for \p inst. But does /// for any other instructions that become dead as a result. /// /// Carefully orchestrated steps for deleting an instruction with its uses: /// /// Recursively gather the instruction's uses into the toDeleteInsts set and /// dropping the operand for each use traversed. /// /// For the remaining operands, insert destroys for consuming operands and track /// newly dead operand definitions. /// /// Finally, erase the instruction. void InstructionDeleter::deleteWithUses(SILInstruction *inst, bool fixLifetimes, bool forceDeleteUsers) { // Cannot fix operand lifetimes in non-ownership SIL. assert(!fixLifetimes || inst->getFunction()->hasOwnership()); // Recursively visit all uses while growing toDeleteInsts in def-use order and // dropping dead operands. SmallVector<SILInstruction *, 4> toDeleteInsts; toDeleteInsts.push_back(inst); swift::salvageDebugInfo(inst); for (unsigned idx = 0; idx < toDeleteInsts.size(); ++idx) { for (SILValue result : toDeleteInsts[idx]->getResults()) { // Temporary use vector to avoid iterator invalidation. auto uses = llvm::to_vector<4>(result->getUses()); for (Operand *use : uses) { SILInstruction *user = use->getUser(); assert(forceDeleteUsers || isIncidentalUse(user) || isa<DestroyValueInst>(user)); assert(!isa<BranchInst>(user) && "can't delete phis"); toDeleteInsts.push_back(user); swift::salvageDebugInfo(user); use->drop(); } } } // Process the remaining operands. Insert destroys for consuming // operands. Track newly dead operand values. for (auto *inst : toDeleteInsts) { for (Operand &operand : inst->getAllOperands()) { SILValue operandValue = operand.get(); // Check for dead operands, which are dropped above. if (!operandValue) continue; if (fixLifetimes && operand.isConsuming()) { SILBuilderWithScope builder(inst); auto *dvi = builder.createDestroyValue(inst->getLoc(), operandValue); getCallbacks().createdNewInst(dvi); } auto *operDef = operandValue->getDefiningInstruction(); operand.drop(); if (operDef) { trackIfDead(operDef); } } inst->dropNonOperandReferences(); deadInstructions.remove(inst); getCallbacks().deleteInst(inst, false /*notify when deleting*/); } } void InstructionDeleter::cleanupDeadInstructions() { while (!deadInstructions.empty()) { SmallVector<SILInstruction *, 8> currentDeadInsts(deadInstructions.begin(), deadInstructions.end()); // Though deadInstructions is cleared here, calls to deleteInstruction may // append to deadInstructions. So we need to iterate until this it is empty. deadInstructions.clear(); for (SILInstruction *deadInst : currentDeadInsts) { // deadInst will not have been deleted in the previous iterations, // because, by definition, deleteInstruction will only delete an earlier // instruction and its incidental/destroy uses. The former cannot be // deadInst as deadInstructions is a set vector, and the latter cannot be // in deadInstructions as they are incidental uses which are never added // to deadInstructions. deleteWithUses(deadInst, /*fixLifetimes*/ deadInst->getFunction()->hasOwnership()); } } } bool InstructionDeleter::deleteIfDead(SILInstruction *inst) { bool fixLifetime = inst->getFunction()->hasOwnership(); if (isInstructionTriviallyDead(inst) || isScopeAffectingInstructionDead(inst, fixLifetime)) { getCallbacks().notifyWillBeDeleted(inst); deleteWithUses(inst, fixLifetime); return true; } return false; } void InstructionDeleter::forceDeleteAndFixLifetimes(SILInstruction *inst) { SILFunction *fun = inst->getFunction(); bool disallowDebugUses = fun->getEffectiveOptimizationMode() <= OptimizationMode::NoOptimization; assert(hasOnlyIncidentalUses(inst, disallowDebugUses)); deleteWithUses(inst, /*fixLifetimes*/ fun->hasOwnership()); } void InstructionDeleter::forceDelete(SILInstruction *inst) { bool disallowDebugUses = inst->getFunction()->getEffectiveOptimizationMode() <= OptimizationMode::NoOptimization; assert(hasOnlyIncidentalUses(inst, disallowDebugUses)); deleteWithUses(inst, /*fixLifetimes*/ false); } void InstructionDeleter::recursivelyDeleteUsersIfDead(SILInstruction *inst) { SmallVector<SILInstruction *, 8> users; for (SILValue result : inst->getResults()) for (Operand *use : result->getUses()) users.push_back(use->getUser()); for (SILInstruction *user : users) recursivelyDeleteUsersIfDead(user); deleteIfDead(inst); } void InstructionDeleter::recursivelyForceDeleteUsersAndFixLifetimes( SILInstruction *inst) { for (SILValue result : inst->getResults()) { while (!result->use_empty()) { SILInstruction *user = result->use_begin()->getUser(); recursivelyForceDeleteUsersAndFixLifetimes(user); } } if (isIncidentalUse(inst) || isa<DestroyValueInst>(inst)) { forceDelete(inst); return; } forceDeleteAndFixLifetimes(inst); } void swift::eliminateDeadInstruction(SILInstruction *inst, InstModCallbacks callbacks) { InstructionDeleter deleter(std::move(callbacks)); deleter.trackIfDead(inst); deleter.cleanupDeadInstructions(); } void swift::recursivelyDeleteTriviallyDeadInstructions( ArrayRef<SILInstruction *> ia, bool force, InstModCallbacks callbacks) { // Delete these instruction and others that become dead after it's deleted. llvm::SmallPtrSet<SILInstruction *, 8> deadInsts; for (auto *inst : ia) { // If the instruction is not dead and force is false, do nothing. if (force || isInstructionTriviallyDead(inst)) deadInsts.insert(inst); } llvm::SmallPtrSet<SILInstruction *, 8> nextInsts; while (!deadInsts.empty()) { for (auto inst : deadInsts) { // Call the callback before we mutate the to be deleted instruction in any // way. callbacks.notifyWillBeDeleted(inst); // Check if any of the operands will become dead as well. MutableArrayRef<Operand> operands = inst->getAllOperands(); for (Operand &operand : operands) { SILValue operandVal = operand.get(); if (!operandVal) continue; // Remove the reference from the instruction being deleted to this // operand. operand.drop(); // If the operand is an instruction that is only used by the instruction // being deleted, delete it. if (auto *operandValInst = operandVal->getDefiningInstruction()) if (!deadInsts.count(operandValInst) && isInstructionTriviallyDead(operandValInst)) nextInsts.insert(operandValInst); } // If we have a function ref inst, we need to especially drop its function // argument so that it gets a proper ref decrement. if (auto *fri = dyn_cast<FunctionRefBaseInst>(inst)) fri->dropReferencedFunction(); } for (auto inst : deadInsts) { // This will remove this instruction and all its uses. eraseFromParentWithDebugInsts(inst, callbacks); } nextInsts.swap(deadInsts); nextInsts.clear(); } } <commit_msg>Rename InstructionDeleter disallowDebugUses to preserveDebugInfo<commit_after>//===--- InstructionDeleter.cpp - InstructionDeleter utility --------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2021 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// #include "swift/SIL/SILFunction.h" #include "swift/SILOptimizer/Utils/ConstExpr.h" #include "swift/SILOptimizer/Utils/DebugOptUtils.h" #include "swift/SILOptimizer/Utils/InstructionDeleter.h" #include "swift/SILOptimizer/Utils/InstOptUtils.h" using namespace swift; static bool hasOnlyIncidentalUses(SILInstruction *inst, bool preserveDebugInfo = false) { for (SILValue result : inst->getResults()) { for (Operand *use : result->getUses()) { SILInstruction *user = use->getUser(); if (!isIncidentalUse(user)) return false; if (preserveDebugInfo && user->isDebugInstruction()) return false; } } return true; } /// A scope-affecting instruction is an instruction which may end the scope of /// its operand or may produce scoped results that require cleaning up. E.g. /// begin_borrow, begin_access, copy_value, a call that produces a owned value /// are scoped instructions. The scope of the results of the first two /// instructions end with an end_borrow/acess instruction, while those of the /// latter two end with a consuming operation like destroy_value instruction. /// These instruction may also end the scope of its operand e.g. a call could /// consume owned arguments thereby ending its scope. Dead-code eliminating a /// scope-affecting instruction requires fixing the lifetime of the non-trivial /// operands of the instruction and requires cleaning up the end-of-scope uses /// of non-trivial results. /// /// \param inst instruction that checked for liveness. /// /// TODO: Handle partial_apply [stack] which has a dealloc_stack user. static bool isScopeAffectingInstructionDead(SILInstruction *inst, bool fixLifetime) { SILFunction *fun = inst->getFunction(); assert(fun && "Instruction has no function."); // Only support ownership SIL for scoped instructions. if (!fun->hasOwnership()) { return false; } // If the instruction has any use other than end of scope use or destroy_value // use, bail out. if (!hasOnlyEndOfScopeOrEndOfLifetimeUses(inst)) { return false; } // If inst is a copy or beginning of scope, inst is dead, since we know that // it is used only in a destroy_value or end-of-scope instruction. if (getSingleValueCopyOrCast(inst)) return true; switch (inst->getKind()) { case SILInstructionKind::LoadBorrowInst: { // A load_borrow only used in an end_borrow is dead. return true; } case SILInstructionKind::LoadInst: { LoadOwnershipQualifier loadOwnershipQual = cast<LoadInst>(inst)->getOwnershipQualifier(); // If the load creates a copy, it is dead, since we know that if at all it // is used, it is only in a destroy_value instruction. return (loadOwnershipQual == LoadOwnershipQualifier::Copy || loadOwnershipQual == LoadOwnershipQualifier::Trivial); // TODO: we can handle load [take] but we would have to know that the // operand has been consumed. Note that OperandOwnershipKind map does not // say this for load. } case SILInstructionKind::PartialApplyInst: { bool onlyTrivialArgs = true; for (auto &arg : cast<PartialApplyInst>(inst)->getArgumentOperands()) { auto argTy = arg.get()->getType(); // Non-stack partial apply captures that are passed by address are always // captured at +1 by the closure contrext, regardless of the calling // convention. // // TODO: When on-stack partial applies are also handled, then their +0 // address arguments can be ignored. // // FIXME: Even with fixLifetimes enabled, InstructionDeleter does not know // how to cleanup arguments captured by address. This should be as simple // as inserting a destroy_addr. But the analagous code in // tryDeleteDeadClosure() and keepArgsOfPartialApplyAlive() mysteriously // creates new alloc_stack's and invalidates stack nesting. So we // conservatively bail-out until we understand why that hack exists. if (argTy.isAddress()) return false; onlyTrivialArgs &= argTy.isTrivial(*fun); } // Partial applies that are only used in destroys cannot have any effect on // the program state, provided the values they capture are explicitly // destroyed, which only happens when fixLifetime is true. return onlyTrivialArgs || fixLifetime; } case SILInstructionKind::StructInst: case SILInstructionKind::EnumInst: case SILInstructionKind::TupleInst: case SILInstructionKind::ConvertFunctionInst: case SILInstructionKind::DestructureStructInst: case SILInstructionKind::DestructureTupleInst: { // All these ownership forwarding instructions that are only used in // destroys are dead provided the values they consume are destroyed // explicitly. return true; } case SILInstructionKind::ApplyInst: { // The following property holds for constant-evaluable functions that do // not take arguments of generic type: // 1. they do not create objects having deinitializers with global // side effects, as they can only create objects consisting of trivial // values, (non-generic) arrays and strings. // 2. they do not use global variables or call arbitrary functions with // side effects. // The above two properties imply that a value returned by a constant // evaluable function does not have a deinitializer with global side // effects. Therefore, the deinitializer can be sinked. // // A generic, read-only constant evaluable call only reads and/or // destroys its (non-generic) parameters. It therefore cannot have any // side effects (note that parameters being non-generic have value // semantics). Therefore, the constant evaluable call can be removed // provided the parameter lifetimes are handled correctly, which is taken // care of by the function: \c deleteInstruction. FullApplySite applySite(cast<ApplyInst>(inst)); return isReadOnlyConstantEvaluableCall(applySite); } default: { return false; } } } bool InstructionDeleter::trackIfDead(SILInstruction *inst) { bool fixLifetime = inst->getFunction()->hasOwnership(); if (isInstructionTriviallyDead(inst) || isScopeAffectingInstructionDead(inst, fixLifetime)) { assert(!isIncidentalUse(inst) && !isa<DestroyValueInst>(inst) && "Incidental uses cannot be removed in isolation. " "They would be removed iff the operand is dead"); getCallbacks().notifyWillBeDeleted(inst); deadInstructions.insert(inst); return true; } return false; } void InstructionDeleter::forceTrackAsDead(SILInstruction *inst) { bool preserveDebugInfo = inst->getFunction()->getEffectiveOptimizationMode() <= OptimizationMode::NoOptimization; assert(hasOnlyIncidentalUses(inst, preserveDebugInfo)); getCallbacks().notifyWillBeDeleted(inst); deadInstructions.insert(inst); } /// Force-delete \p inst and all its uses. /// /// \p fixLifetimes causes new destroys to be inserted after dropping /// operands. /// /// \p forceDeleteUsers allows deleting an instruction with non-incidental, /// non-destoy uses, such as a store. /// /// Does not call callbacks.notifyWillBeDeleted for \p inst. But does /// for any other instructions that become dead as a result. /// /// Carefully orchestrated steps for deleting an instruction with its uses: /// /// Recursively gather the instruction's uses into the toDeleteInsts set and /// dropping the operand for each use traversed. /// /// For the remaining operands, insert destroys for consuming operands and track /// newly dead operand definitions. /// /// Finally, erase the instruction. void InstructionDeleter::deleteWithUses(SILInstruction *inst, bool fixLifetimes, bool forceDeleteUsers) { // Cannot fix operand lifetimes in non-ownership SIL. assert(!fixLifetimes || inst->getFunction()->hasOwnership()); // Recursively visit all uses while growing toDeleteInsts in def-use order and // dropping dead operands. SmallVector<SILInstruction *, 4> toDeleteInsts; toDeleteInsts.push_back(inst); swift::salvageDebugInfo(inst); for (unsigned idx = 0; idx < toDeleteInsts.size(); ++idx) { for (SILValue result : toDeleteInsts[idx]->getResults()) { // Temporary use vector to avoid iterator invalidation. auto uses = llvm::to_vector<4>(result->getUses()); for (Operand *use : uses) { SILInstruction *user = use->getUser(); assert(forceDeleteUsers || isIncidentalUse(user) || isa<DestroyValueInst>(user)); assert(!isa<BranchInst>(user) && "can't delete phis"); toDeleteInsts.push_back(user); swift::salvageDebugInfo(user); use->drop(); } } } // Process the remaining operands. Insert destroys for consuming // operands. Track newly dead operand values. for (auto *inst : toDeleteInsts) { for (Operand &operand : inst->getAllOperands()) { SILValue operandValue = operand.get(); // Check for dead operands, which are dropped above. if (!operandValue) continue; if (fixLifetimes && operand.isConsuming()) { SILBuilderWithScope builder(inst); auto *dvi = builder.createDestroyValue(inst->getLoc(), operandValue); getCallbacks().createdNewInst(dvi); } auto *operDef = operandValue->getDefiningInstruction(); operand.drop(); if (operDef) { trackIfDead(operDef); } } inst->dropNonOperandReferences(); deadInstructions.remove(inst); getCallbacks().deleteInst(inst, false /*notify when deleting*/); } } void InstructionDeleter::cleanupDeadInstructions() { while (!deadInstructions.empty()) { SmallVector<SILInstruction *, 8> currentDeadInsts(deadInstructions.begin(), deadInstructions.end()); // Though deadInstructions is cleared here, calls to deleteInstruction may // append to deadInstructions. So we need to iterate until this it is empty. deadInstructions.clear(); for (SILInstruction *deadInst : currentDeadInsts) { // deadInst will not have been deleted in the previous iterations, // because, by definition, deleteInstruction will only delete an earlier // instruction and its incidental/destroy uses. The former cannot be // deadInst as deadInstructions is a set vector, and the latter cannot be // in deadInstructions as they are incidental uses which are never added // to deadInstructions. deleteWithUses(deadInst, /*fixLifetimes*/ deadInst->getFunction()->hasOwnership()); } } } bool InstructionDeleter::deleteIfDead(SILInstruction *inst) { bool fixLifetime = inst->getFunction()->hasOwnership(); if (isInstructionTriviallyDead(inst) || isScopeAffectingInstructionDead(inst, fixLifetime)) { getCallbacks().notifyWillBeDeleted(inst); deleteWithUses(inst, fixLifetime); return true; } return false; } void InstructionDeleter::forceDeleteAndFixLifetimes(SILInstruction *inst) { SILFunction *fun = inst->getFunction(); bool preserveDebugInfo = fun->getEffectiveOptimizationMode() <= OptimizationMode::NoOptimization; assert(hasOnlyIncidentalUses(inst, preserveDebugInfo)); deleteWithUses(inst, /*fixLifetimes*/ fun->hasOwnership()); } void InstructionDeleter::forceDelete(SILInstruction *inst) { bool preserveDebugInfo = inst->getFunction()->getEffectiveOptimizationMode() <= OptimizationMode::NoOptimization; assert(hasOnlyIncidentalUses(inst, preserveDebugInfo)); deleteWithUses(inst, /*fixLifetimes*/ false); } void InstructionDeleter::recursivelyDeleteUsersIfDead(SILInstruction *inst) { SmallVector<SILInstruction *, 8> users; for (SILValue result : inst->getResults()) for (Operand *use : result->getUses()) users.push_back(use->getUser()); for (SILInstruction *user : users) recursivelyDeleteUsersIfDead(user); deleteIfDead(inst); } void InstructionDeleter::recursivelyForceDeleteUsersAndFixLifetimes( SILInstruction *inst) { for (SILValue result : inst->getResults()) { while (!result->use_empty()) { SILInstruction *user = result->use_begin()->getUser(); recursivelyForceDeleteUsersAndFixLifetimes(user); } } if (isIncidentalUse(inst) || isa<DestroyValueInst>(inst)) { forceDelete(inst); return; } forceDeleteAndFixLifetimes(inst); } void swift::eliminateDeadInstruction(SILInstruction *inst, InstModCallbacks callbacks) { InstructionDeleter deleter(std::move(callbacks)); deleter.trackIfDead(inst); deleter.cleanupDeadInstructions(); } void swift::recursivelyDeleteTriviallyDeadInstructions( ArrayRef<SILInstruction *> ia, bool force, InstModCallbacks callbacks) { // Delete these instruction and others that become dead after it's deleted. llvm::SmallPtrSet<SILInstruction *, 8> deadInsts; for (auto *inst : ia) { // If the instruction is not dead and force is false, do nothing. if (force || isInstructionTriviallyDead(inst)) deadInsts.insert(inst); } llvm::SmallPtrSet<SILInstruction *, 8> nextInsts; while (!deadInsts.empty()) { for (auto inst : deadInsts) { // Call the callback before we mutate the to be deleted instruction in any // way. callbacks.notifyWillBeDeleted(inst); // Check if any of the operands will become dead as well. MutableArrayRef<Operand> operands = inst->getAllOperands(); for (Operand &operand : operands) { SILValue operandVal = operand.get(); if (!operandVal) continue; // Remove the reference from the instruction being deleted to this // operand. operand.drop(); // If the operand is an instruction that is only used by the instruction // being deleted, delete it. if (auto *operandValInst = operandVal->getDefiningInstruction()) if (!deadInsts.count(operandValInst) && isInstructionTriviallyDead(operandValInst)) nextInsts.insert(operandValInst); } // If we have a function ref inst, we need to especially drop its function // argument so that it gets a proper ref decrement. if (auto *fri = dyn_cast<FunctionRefBaseInst>(inst)) fri->dropReferencedFunction(); } for (auto inst : deadInsts) { // This will remove this instruction and all its uses. eraseFromParentWithDebugInsts(inst, callbacks); } nextInsts.swap(deadInsts); nextInsts.clear(); } } <|endoftext|>
<commit_before>/* * Copyright (c) 2006, Mathieu Champlon * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met : * * . Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * . Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * . Neither the name of the copyright holders nor the names of the * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE THE COPYRIGHT * OWNERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "xeumeuleu_test_pch.h" #include <xeumeuleu/xml.hpp> // ----------------------------------------------------------------------------- // Name: read_attribute_from_root_level_throws_an_exception // Created: MCO 2006-01-03 // ----------------------------------------------------------------------------- BOOST_AUTO_TEST_CASE( read_attribute_from_root_level_throws_an_exception ) { xml::xistringstream xis( "<element attribute='12'/>" ); int value; BOOST_CHECK_THROW( xis >> xml::attribute( "attribute", value ), xml::exception ); } // ----------------------------------------------------------------------------- // Name: read_unexisting_attribute_throws_an_exception // Created: MCO 2006-01-03 // ----------------------------------------------------------------------------- BOOST_AUTO_TEST_CASE( read_unexisting_attribute_throws_an_exception ) { xml::xistringstream xis( "<element attribute='the attribute value'/>" ); std::string value; xis >> xml::start( "element" ); BOOST_CHECK_THROW( xis >> xml::attribute( "unexisting_attribute", value ), xml::exception ); } // ----------------------------------------------------------------------------- // Name: add_attribute_at_root_level_throws_an_exception // Created: MCO 2006-01-03 // ----------------------------------------------------------------------------- BOOST_AUTO_TEST_CASE( add_attribute_at_root_level_throws_an_exception ) { xml::xostringstream xos; BOOST_CHECK_THROW( xos << xml::attribute( "attribute", 12 ), xml::exception ); } namespace { template< typename T > std::string write( const T& value ) { xml::xostringstream xos; xos << xml::start( "element" ) << xml::attribute( "attribute", value ) << xml::end; return xos.str(); } std::string format( const std::string& value ) { return "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\" ?>\n" "<element attribute=\"" + value + "\"/>\n"; } } // ----------------------------------------------------------------------------- // Name: add_attribute_on_element_makes_a_valid_document // Created: MCO 2006-01-03 // ----------------------------------------------------------------------------- BOOST_AUTO_TEST_CASE( add_attribute_on_element_makes_a_valid_document ) { BOOST_CHECK_EQUAL( format( "12" ), write< short >( 12 ) ); BOOST_CHECK_EQUAL( format( "12" ), write< int >( 12 ) ); BOOST_CHECK_EQUAL( format( "12" ), write< long >( 12 ) ); BOOST_CHECK_EQUAL( format( "12" ), write< long long >( 12 ) ); BOOST_CHECK_EQUAL( format( "12" ), write< float >( 12 ) ); BOOST_CHECK_EQUAL( format( "12" ), write< double >( 12 ) ); BOOST_CHECK_EQUAL( format( "12" ), write< long double >( 12 ) ); BOOST_CHECK_EQUAL( format( "12" ), write< unsigned short >( 12 ) ); BOOST_CHECK_EQUAL( format( "12" ), write< unsigned int >( 12 ) ); BOOST_CHECK_EQUAL( format( "12" ), write< unsigned long >( 12 ) ); BOOST_CHECK_EQUAL( format( "12" ), write< unsigned long long >( 12 ) ); BOOST_CHECK_EQUAL( format( " the attribute value " ), write< std::string >( " the attribute value " ) ); } namespace { template< typename T > T read( const std::string& value ) { xml::xistringstream xis( "<element attribute=\"" + value + "\"/>" ); T result; xis >> xml::start( "element" ) >> xml::attribute( "attribute", result ); return result; } } // ----------------------------------------------------------------------------- // Name: read_attribute_from_element_retrieves_value // Created: MCO 2006-01-03 // ----------------------------------------------------------------------------- BOOST_AUTO_TEST_CASE( read_attribute_from_element_retrieves_value ) { BOOST_CHECK_EQUAL( 12, read< short >( "12" ) ); BOOST_CHECK_EQUAL( 12, read< int >( "12" ) ); BOOST_CHECK_EQUAL( 12, read< long >( "12" ) ); BOOST_CHECK_EQUAL( 12, read< long long >( "12" ) ); BOOST_CHECK_EQUAL( 12.f, read< float >( "12" ) ); BOOST_CHECK_EQUAL( 12, read< double >( "12" ) ); BOOST_CHECK_EQUAL( 12, read< long double >( "12" ) ); BOOST_CHECK_EQUAL( 12u, read< unsigned short >( "12" ) ); BOOST_CHECK_EQUAL( 12u, read< unsigned int >( "12" ) ); BOOST_CHECK_EQUAL( 12u, read< unsigned long >( "12" ) ); BOOST_CHECK_EQUAL( 12u, read< unsigned long long >( "12" ) ); BOOST_CHECK_EQUAL( " the attribute value ", read< std::string >( " the attribute value " ) ); } // ----------------------------------------------------------------------------- // Name: read_attribute_directly_is_valid // Created: MCO 2006-01-03 // ----------------------------------------------------------------------------- BOOST_AUTO_TEST_CASE( read_attribute_directly_is_valid ) { xml::xistringstream xis( "<element attribute='the attribute value'/>" ); xis >> xml::start( "element" ); BOOST_CHECK_EQUAL( "the attribute value", xis.attribute< std::string >( "attribute" ) ); } // ----------------------------------------------------------------------------- // Name: read_attribute_directly_with_default_value_is_valid // Created: MCO 2006-01-03 // ----------------------------------------------------------------------------- BOOST_AUTO_TEST_CASE( read_attribute_directly_with_default_value_is_valid ) { xml::xistringstream xis( "<element attribute='the attribute value'/>" ); xis >> xml::start( "element" ); const std::string value = "the default value"; BOOST_CHECK_EQUAL( "the attribute value", xis.attribute( "attribute", value ) ); } // ----------------------------------------------------------------------------- // Name: read_unexisting_attribute_directly_with_default_value_is_valid // Created: MCO 2006-01-03 // ----------------------------------------------------------------------------- BOOST_AUTO_TEST_CASE( read_unexisting_attribute_directly_with_default_value_is_valid ) { xml::xistringstream xis( "<element/>" ); xis >> xml::start( "element" ); const std::string value = "the default value"; BOOST_CHECK_EQUAL( value, xis.attribute( "attribute", value ) ); } // ----------------------------------------------------------------------------- // Name: read_from_root_attribute_directly_with_default_value_is_valid // Created: MCO 2006-01-03 // ----------------------------------------------------------------------------- BOOST_AUTO_TEST_CASE( read_from_root_attribute_directly_with_default_value_is_valid ) { xml::xistringstream xis( "<element/>" ); const std::string value = "the default value"; BOOST_CHECK_EQUAL( value, xis.attribute( "attribute", value ) ); } // ----------------------------------------------------------------------------- // Name: read_attribute_in_namespace_is_valid // Created: MCO 2008-11-23 // ----------------------------------------------------------------------------- BOOST_AUTO_TEST_CASE( read_attribute_in_namespace_is_valid ) { xml::xistringstream xis( "<element xmlns:ns='http://www.example.org' ns:attribute='the attribute value'/>" ); const std::string expected = "the attribute value"; std::string actual; xis >> xml::start( "element" ) >> xml::attribute( "ns:attribute", actual ); BOOST_CHECK_EQUAL( expected, actual ); } // ----------------------------------------------------------------------------- // Name: writing_the_same_attribute_twice_yields_the_second_value_overwriting_the_first // Created: MCO 2008-14-03 // ----------------------------------------------------------------------------- BOOST_AUTO_TEST_CASE( writing_the_same_attribute_twice_yields_the_second_value_overwriting_the_first ) { xml::xostringstream xos; xos << xml::start( "root" ) << xml::attribute( "attribute", "the first value" ) << xml::attribute( "attribute", "the second value" ) << xml::end; const std::string expected = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\" ?>\n" "<root attribute=\"the second value\"/>\n"; BOOST_CHECK_EQUAL( expected, xos.str() ); } namespace { class user_type { public: friend xml::xistream& operator>>( xml::xistream& xis, user_type& /*u*/ ) { return xis; } friend xml::xostream& operator<<( xml::xostream& xos, const user_type& /*u*/ ) { return xos; } }; } // ----------------------------------------------------------------------------- // Name: reading_attribute_can_be_specialized_for_user_types // Created: MCO 2009-05-30 // ----------------------------------------------------------------------------- BOOST_AUTO_TEST_CASE( reading_attribute_can_be_specialized_for_user_types ) { xml::xistringstream xis( "<root attribute=''/>" ); user_type u; xis >> xml::start( "root" ) >> xml::attribute( "attribute", u ); } // ----------------------------------------------------------------------------- // Name: writing_attribute_can_be_specialized_for_user_types // Created: MCO 2009-11-14 // ----------------------------------------------------------------------------- BOOST_AUTO_TEST_CASE( writing_attribute_can_be_specialized_for_user_types ) { xml::xostringstream xos; user_type u; xos << xml::start( "root" ) << xml::attribute( "attribute", u ); } // ----------------------------------------------------------------------------- // Name: writing_attribute_can_be_specialized_for_const_user_types // Created: MCO 2009-11-14 // ----------------------------------------------------------------------------- BOOST_AUTO_TEST_CASE( writing_attribute_can_be_specialized_for_const_user_types ) { xml::xostringstream xos; const user_type u; xos << xml::start( "root" ) << xml::attribute( "attribute", u ); } // ----------------------------------------------------------------------------- // Name: direct_reading_attribute_can_be_specialized_for_user_types // Created: MCO 2009-11-25 // ----------------------------------------------------------------------------- BOOST_AUTO_TEST_CASE( direct_reading_attribute_can_be_specialized_for_user_types ) { xml::xistringstream xis( "<root attribute=''/>" ); xis >> xml::start( "root" ); xis.attribute< user_type >( "attribute" ); } <commit_msg>Fix for gcc<commit_after>/* * Copyright (c) 2006, Mathieu Champlon * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met : * * . Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * . Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * . Neither the name of the copyright holders nor the names of the * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE THE COPYRIGHT * OWNERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "xeumeuleu_test_pch.h" #include <xeumeuleu/xml.hpp> // ----------------------------------------------------------------------------- // Name: read_attribute_from_root_level_throws_an_exception // Created: MCO 2006-01-03 // ----------------------------------------------------------------------------- BOOST_AUTO_TEST_CASE( read_attribute_from_root_level_throws_an_exception ) { xml::xistringstream xis( "<element attribute='12'/>" ); int value; BOOST_CHECK_THROW( xis >> xml::attribute( "attribute", value ), xml::exception ); } // ----------------------------------------------------------------------------- // Name: read_unexisting_attribute_throws_an_exception // Created: MCO 2006-01-03 // ----------------------------------------------------------------------------- BOOST_AUTO_TEST_CASE( read_unexisting_attribute_throws_an_exception ) { xml::xistringstream xis( "<element attribute='the attribute value'/>" ); std::string value; xis >> xml::start( "element" ); BOOST_CHECK_THROW( xis >> xml::attribute( "unexisting_attribute", value ), xml::exception ); } // ----------------------------------------------------------------------------- // Name: add_attribute_at_root_level_throws_an_exception // Created: MCO 2006-01-03 // ----------------------------------------------------------------------------- BOOST_AUTO_TEST_CASE( add_attribute_at_root_level_throws_an_exception ) { xml::xostringstream xos; BOOST_CHECK_THROW( xos << xml::attribute( "attribute", 12 ), xml::exception ); } namespace { template< typename T > std::string write( const T& value ) { xml::xostringstream xos; xos << xml::start( "element" ) << xml::attribute( "attribute", value ) << xml::end; return xos.str(); } std::string format( const std::string& value ) { return "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\" ?>\n" "<element attribute=\"" + value + "\"/>\n"; } } // ----------------------------------------------------------------------------- // Name: add_attribute_on_element_makes_a_valid_document // Created: MCO 2006-01-03 // ----------------------------------------------------------------------------- BOOST_AUTO_TEST_CASE( add_attribute_on_element_makes_a_valid_document ) { BOOST_CHECK_EQUAL( format( "12" ), write< short >( 12 ) ); BOOST_CHECK_EQUAL( format( "12" ), write< int >( 12 ) ); BOOST_CHECK_EQUAL( format( "12" ), write< long >( 12 ) ); BOOST_CHECK_EQUAL( format( "12" ), write< long long >( 12 ) ); BOOST_CHECK_EQUAL( format( "12" ), write< float >( 12 ) ); BOOST_CHECK_EQUAL( format( "12" ), write< double >( 12 ) ); BOOST_CHECK_EQUAL( format( "12" ), write< long double >( 12 ) ); BOOST_CHECK_EQUAL( format( "12" ), write< unsigned short >( 12 ) ); BOOST_CHECK_EQUAL( format( "12" ), write< unsigned int >( 12 ) ); BOOST_CHECK_EQUAL( format( "12" ), write< unsigned long >( 12 ) ); BOOST_CHECK_EQUAL( format( "12" ), write< unsigned long long >( 12 ) ); BOOST_CHECK_EQUAL( format( " the attribute value " ), write< std::string >( " the attribute value " ) ); } namespace { template< typename T > T read( const std::string& value ) { xml::xistringstream xis( "<element attribute=\"" + value + "\"/>" ); T result; xis >> xml::start( "element" ) >> xml::attribute( "attribute", result ); return result; } } // ----------------------------------------------------------------------------- // Name: read_attribute_from_element_retrieves_value // Created: MCO 2006-01-03 // ----------------------------------------------------------------------------- BOOST_AUTO_TEST_CASE( read_attribute_from_element_retrieves_value ) { BOOST_CHECK_EQUAL( 12, read< short >( "12" ) ); BOOST_CHECK_EQUAL( 12, read< int >( "12" ) ); BOOST_CHECK_EQUAL( 12, read< long >( "12" ) ); BOOST_CHECK_EQUAL( 12, read< long long >( "12" ) ); BOOST_CHECK_EQUAL( 12.f, read< float >( "12" ) ); BOOST_CHECK_EQUAL( 12, read< double >( "12" ) ); BOOST_CHECK_EQUAL( 12, read< long double >( "12" ) ); BOOST_CHECK_EQUAL( 12u, read< unsigned short >( "12" ) ); BOOST_CHECK_EQUAL( 12u, read< unsigned int >( "12" ) ); BOOST_CHECK_EQUAL( 12u, read< unsigned long >( "12" ) ); BOOST_CHECK_EQUAL( 12u, read< unsigned long long >( "12" ) ); BOOST_CHECK_EQUAL( " the attribute value ", read< std::string >( " the attribute value " ) ); } // ----------------------------------------------------------------------------- // Name: read_attribute_directly_is_valid // Created: MCO 2006-01-03 // ----------------------------------------------------------------------------- BOOST_AUTO_TEST_CASE( read_attribute_directly_is_valid ) { xml::xistringstream xis( "<element attribute='the attribute value'/>" ); xis >> xml::start( "element" ); BOOST_CHECK_EQUAL( "the attribute value", xis.attribute< std::string >( "attribute" ) ); } // ----------------------------------------------------------------------------- // Name: read_attribute_directly_with_default_value_is_valid // Created: MCO 2006-01-03 // ----------------------------------------------------------------------------- BOOST_AUTO_TEST_CASE( read_attribute_directly_with_default_value_is_valid ) { xml::xistringstream xis( "<element attribute='the attribute value'/>" ); xis >> xml::start( "element" ); const std::string value = "the default value"; BOOST_CHECK_EQUAL( "the attribute value", xis.attribute( "attribute", value ) ); } // ----------------------------------------------------------------------------- // Name: read_unexisting_attribute_directly_with_default_value_is_valid // Created: MCO 2006-01-03 // ----------------------------------------------------------------------------- BOOST_AUTO_TEST_CASE( read_unexisting_attribute_directly_with_default_value_is_valid ) { xml::xistringstream xis( "<element/>" ); xis >> xml::start( "element" ); const std::string value = "the default value"; BOOST_CHECK_EQUAL( value, xis.attribute( "attribute", value ) ); } // ----------------------------------------------------------------------------- // Name: read_from_root_attribute_directly_with_default_value_is_valid // Created: MCO 2006-01-03 // ----------------------------------------------------------------------------- BOOST_AUTO_TEST_CASE( read_from_root_attribute_directly_with_default_value_is_valid ) { xml::xistringstream xis( "<element/>" ); const std::string value = "the default value"; BOOST_CHECK_EQUAL( value, xis.attribute( "attribute", value ) ); } // ----------------------------------------------------------------------------- // Name: read_attribute_in_namespace_is_valid // Created: MCO 2008-11-23 // ----------------------------------------------------------------------------- BOOST_AUTO_TEST_CASE( read_attribute_in_namespace_is_valid ) { xml::xistringstream xis( "<element xmlns:ns='http://www.example.org' ns:attribute='the attribute value'/>" ); const std::string expected = "the attribute value"; std::string actual; xis >> xml::start( "element" ) >> xml::attribute( "ns:attribute", actual ); BOOST_CHECK_EQUAL( expected, actual ); } // ----------------------------------------------------------------------------- // Name: writing_the_same_attribute_twice_yields_the_second_value_overwriting_the_first // Created: MCO 2008-14-03 // ----------------------------------------------------------------------------- BOOST_AUTO_TEST_CASE( writing_the_same_attribute_twice_yields_the_second_value_overwriting_the_first ) { xml::xostringstream xos; xos << xml::start( "root" ) << xml::attribute( "attribute", "the first value" ) << xml::attribute( "attribute", "the second value" ) << xml::end; const std::string expected = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\" ?>\n" "<root attribute=\"the second value\"/>\n"; BOOST_CHECK_EQUAL( expected, xos.str() ); } namespace { class user_type { public: friend xml::xistream& operator>>( xml::xistream& xis, user_type& /*u*/ ) { return xis; } friend xml::xostream& operator<<( xml::xostream& xos, const user_type& /*u*/ ) { return xos; } }; } // ----------------------------------------------------------------------------- // Name: reading_attribute_can_be_specialized_for_user_types // Created: MCO 2009-05-30 // ----------------------------------------------------------------------------- BOOST_AUTO_TEST_CASE( reading_attribute_can_be_specialized_for_user_types ) { xml::xistringstream xis( "<root attribute=''/>" ); user_type u; xis >> xml::start( "root" ) >> xml::attribute( "attribute", u ); } // ----------------------------------------------------------------------------- // Name: writing_attribute_can_be_specialized_for_user_types // Created: MCO 2009-11-14 // ----------------------------------------------------------------------------- BOOST_AUTO_TEST_CASE( writing_attribute_can_be_specialized_for_user_types ) { xml::xostringstream xos; user_type u; xos << xml::start( "root" ) << xml::attribute( "attribute", u ); } // ----------------------------------------------------------------------------- // Name: writing_attribute_can_be_specialized_for_const_user_types // Created: MCO 2009-11-14 // ----------------------------------------------------------------------------- BOOST_AUTO_TEST_CASE( writing_attribute_can_be_specialized_for_const_user_types ) { xml::xostringstream xos; const user_type u = user_type(); xos << xml::start( "root" ) << xml::attribute( "attribute", u ); } // ----------------------------------------------------------------------------- // Name: direct_reading_attribute_can_be_specialized_for_user_types // Created: MCO 2009-11-25 // ----------------------------------------------------------------------------- BOOST_AUTO_TEST_CASE( direct_reading_attribute_can_be_specialized_for_user_types ) { xml::xistringstream xis( "<root attribute=''/>" ); xis >> xml::start( "root" ); xis.attribute< user_type >( "attribute" ); } <|endoftext|>
<commit_before>/** @file iterativeSolvers.cpp @brief Example on how the solve a system of linear equation with the MINRES, GMRes and CG method. This file is part of the G+Smo library. This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. Author(s): J. Sogn */ #include <iostream> #include <gismo.h> using namespace gismo; //Create a tri-diagonal matrix with -1 of the off diagonals and 2 in the diagonal. //This matrix is equivalent to discretizing the 1D Poisson equation with homogenius //Dirichlet boundary condition using a finite difference method. It is a SPD matrix. //The solution is sin(pi*x); void poissonDiscretization(gsSparseMatrix<> &mat, gsMatrix<> &rhs, index_t N) { rhs.setZero(N,1); mat.resize(N,N); mat.setZero(); real_t meshSize = 1./(N+1); real_t pi = M_PI; //Reserving space in the sparse matrix (Speeds up the assemble time of the matrix) gsVector<int> reserve = gsVector<int>::Constant(N,3);//Reserve 3 non-zero entry per column mat.reserve( reserve ); mat(0,0) = 2; mat(0,1) = -1; mat(N-1, N-1) = 2; mat(N-1, N-2) = -1; for (index_t k = 1; k < N-1; ++k) { mat(k,k) = 2; mat(k,k-1) = -1; mat(k,k+1) = -1; } for (index_t k = 0; k < N; ++k) { rhs(k,0) = pi*pi*meshSize*meshSize*math::cos(meshSize*(1+k)*pi); } //Compress the matrix mat.makeCompressed(); } //Print out information of the iterative solver void gsIterativeSolverInfo(const gsIterativeSolver &method, std::string methodName, real_t time) { gsInfo << methodName +": System size : " << method.size() << "\n"; gsInfo << methodName +": Tolerance : " << method.tolerance() << "\n"; gsInfo << methodName +": Residual error : " << method.error() << "\n"; gsInfo << methodName +": Number of iterations: " << method.iterations() << "\n"; gsInfo << methodName +": Time to solve: : " << time << "\n"; } int main(int argc, char *argv[]) { //Size of linear system index_t N = 200; if (argc >= 2) N = atoi(argv[1]); gsSparseMatrix<> mat; gsMatrix<> rhs; //Assemble the 1D Poisson equation poissonDiscretization(mat, rhs, N); //The minimal residual implementation requires a preconditioner. //We initialize an identity preconditioner (does nothing). gsIdentityPreconditioner preConMat(N); //Maximum number of iterations index_t maxIters = 3*N; //Tolerance real_t tol = math::pow(10.0, - REAL_DIG * 0.75); ///----------------------GISMO-SOLVERS----------------------/// gsInfo << "Testing G+Smo's solvers:\n"; //Initialize the MinRes solver gsMinimalResidual MinRes(mat,maxIters,tol); //Create the initial guess gsMatrix<> x0; x0.setZero(N,1); //Solve system with given preconditioner (solution is stored in x0) gsInfo << "\nMinRes: Started solving..." << "\n"; gsStopwatch clock; MinRes.solve(rhs,x0,preConMat); gsIterativeSolverInfo(MinRes, "MinRes", clock.stop()); //Initialize the CG solver gsGMRes GMResSolver(mat,maxIters,tol); //Set the initial guess to zero x0.setZero(N,1); if (N < 200) { //Solve system with given preconditioner (solution is stored in x0) gsInfo << "\nGMRes: Started solving..." << "\n"; clock.restart(); GMResSolver.solve(rhs,x0,preConMat); gsIterativeSolverInfo(GMResSolver, "GMRes", clock.stop()); } else gsInfo << "\nSkipping GMRes due to high number of iterations...\n"; //Initialize the CG solver gsConjugateGradient CGSolver(mat,maxIters,tol); //Set the initial guess to zero x0.setZero(N,1); //Solve system with given preconditioner (solution is stored in x0) gsInfo << "\nCG: Started solving..." << "\n"; clock.restart(); CGSolver.solve(rhs,x0,preConMat); gsIterativeSolverInfo(CGSolver, "CG", clock.stop()); ///----------------------EIGEN-ITERATIVE-SOLVERS----------------------/// gsInfo << "Testing Eigen's interative solvers:\n"; gsSparseSolver<>::CGIdentity EigenCGIsolver; EigenCGIsolver.setMaxIterations(maxIters); EigenCGIsolver.setTolerance(tol); gsInfo << "\nEigen's CG identity preconditioner: Started solving..." << "\n"; clock.restart(); EigenCGIsolver.compute(mat); x0 = EigenCGIsolver.solve(rhs); gsInfo << "Eigen's CG: Tolerance : " << EigenCGIsolver.tolerance() << "\n"; gsInfo << "Eigen's CG: Residual error : " << EigenCGIsolver.error() << "\n"; gsInfo << "Eigen's CG: Number of iterations: " << EigenCGIsolver.iterations() << "\n"; gsInfo << "Eigen's CG: Time to solve : " << clock.stop() << "\n"; gsSparseSolver<>::CGDiagonal EigenCGDsolver; EigenCGDsolver.setMaxIterations(maxIters); EigenCGDsolver.setTolerance(tol); gsInfo << "\nEigen's CG diagonal preconditioner: Started solving..." << "\n"; clock.restart(); EigenCGDsolver.compute(mat); x0 = EigenCGDsolver.solve(rhs); gsInfo << "Eigen's CG: Tolerance : " << EigenCGDsolver.tolerance() << "\n"; gsInfo << "Eigen's CG: Residual error : " << EigenCGDsolver.error() << "\n"; gsInfo << "Eigen's CG: Number of iterations: " << EigenCGDsolver.iterations() << "\n"; gsInfo << "Eigen's CG: Time to solve : " << clock.stop() << "\n"; gsSparseSolver<>::BiCGSTABIdentity EigenBCGIsolver; EigenBCGIsolver.setMaxIterations(maxIters); EigenBCGIsolver.setTolerance(tol); gsInfo << "\nEigen's bi conjugate gradient stabilized solver identity preconditioner: Started solving..." << "\n"; clock.restart(); EigenBCGIsolver.compute(mat); x0 = EigenBCGIsolver.solve(rhs); gsInfo << "Eigen's BiCGSTAB: Tolerance : " << EigenBCGIsolver.tolerance() << "\n"; gsInfo << "Eigen's BiCGSTAB: Residual error : " << EigenBCGIsolver.error() << "\n"; gsInfo << "Eigen's BiCGSTAB: Number of iterations: " << EigenBCGIsolver.iterations() << "\n"; gsInfo << "Eigen's BiCGSTAB: Time to solve : " << clock.stop() << "\n"; gsSparseSolver<>::BiCGSTABDiagonal EigenBCGDsolver; EigenBCGDsolver.setMaxIterations(maxIters); EigenBCGDsolver.setTolerance(tol); gsInfo << "\nEigen's bi conjugate gradient stabilized solver diagonal preconditioner: Started solving..." << "\n"; clock.restart(); EigenBCGDsolver.compute(mat); x0 = EigenBCGDsolver.solve(rhs); gsInfo << "Eigen's BiCGSTAB: Tolerance : " << EigenBCGDsolver.tolerance() << "\n"; gsInfo << "Eigen's BiCGSTAB: Residual error : " << EigenBCGDsolver.error() << "\n"; gsInfo << "Eigen's BiCGSTAB: Number of iterations: " << EigenBCGDsolver.iterations() << "\n"; gsInfo << "Eigen's BiCGSTAB: Time to solve : " << clock.stop() << "\n"; gsSparseSolver<>::BiCGSTABILUT EigenBCGILUsolver; EigenBCGILUsolver.setMaxIterations(maxIters); EigenBCGILUsolver.setTolerance(tol); gsInfo << "\nEigen's bi conjugate gradient stabilized solver ILU preconditioner: Started solving..." << "\n"; clock.restart(); EigenBCGILUsolver.compute(mat); x0 = EigenBCGILUsolver.solve(rhs); gsInfo << "Eigen's BiCGSTAB: Tolerance : " << EigenBCGILUsolver.tolerance() << "\n"; gsInfo << "Eigen's BiCGSTAB: Residual error : " << EigenBCGILUsolver.error() << "\n"; gsInfo << "Eigen's BiCGSTAB: Number of iterations: " << EigenBCGILUsolver.iterations() << "\n"; gsInfo << "Eigen's BiCGSTAB: Time to solve : " << clock.stop() << "\n"; ///----------------------EIGEN-DIRECT-SOLVERS----------------------/// gsSparseSolver<>::SimplicialLDLT EigenSLDLTsolver; gsInfo << "\nEigen's Simplicial LDLT: Started solving..." << "\n"; clock.restart(); EigenSLDLTsolver.compute(mat); x0 = EigenSLDLTsolver.solve(rhs); gsInfo << "Eigen's Simplicial LDLT: Time to solve : " << clock.stop() << "\n"; gsSparseSolver<>::QR solverQR; gsInfo << "\nEigen's QR: Started solving..." << "\n"; clock.restart(); solverQR.compute(mat); x0 = solverQR.solve(rhs); gsInfo << "Eigen's QR: Time to solve : " << clock.stop() << "\n"; gsSparseSolver<>::LU solverLU; gsInfo << "\nEigen's LU: Started solving..." << "\n"; clock.restart(); solverLU.compute(mat); x0 = solverLU.solve(rhs); gsInfo << "Eigen's LU: Time to solve : " << clock.stop() << "\n"; int result = (MinRes.error()<tol)?0:1; result += (CGSolver.error()<tol)?0:1; return result; } <commit_msg>Turning of failing test. The problem is reported in bugreport #34<commit_after>/** @file iterativeSolvers.cpp @brief Example on how the solve a system of linear equation with the MINRES, GMRes and CG method. This file is part of the G+Smo library. This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. Author(s): J. Sogn */ #include <iostream> #include <gismo.h> using namespace gismo; //Create a tri-diagonal matrix with -1 of the off diagonals and 2 in the diagonal. //This matrix is equivalent to discretizing the 1D Poisson equation with homogenius //Dirichlet boundary condition using a finite difference method. It is a SPD matrix. //The solution is sin(pi*x); void poissonDiscretization(gsSparseMatrix<> &mat, gsMatrix<> &rhs, index_t N) { rhs.setZero(N,1); mat.resize(N,N); mat.setZero(); real_t meshSize = 1./(N+1); real_t pi = M_PI; //Reserving space in the sparse matrix (Speeds up the assemble time of the matrix) gsVector<int> reserve = gsVector<int>::Constant(N,3);//Reserve 3 non-zero entry per column mat.reserve( reserve ); mat(0,0) = 2; mat(0,1) = -1; mat(N-1, N-1) = 2; mat(N-1, N-2) = -1; for (index_t k = 1; k < N-1; ++k) { mat(k,k) = 2; mat(k,k-1) = -1; mat(k,k+1) = -1; } for (index_t k = 0; k < N; ++k) { rhs(k,0) = pi*pi*meshSize*meshSize*math::cos(meshSize*(1+k)*pi); } //Compress the matrix mat.makeCompressed(); } //Print out information of the iterative solver void gsIterativeSolverInfo(const gsIterativeSolver &method, std::string methodName, real_t time) { gsInfo << methodName +": System size : " << method.size() << "\n"; gsInfo << methodName +": Tolerance : " << method.tolerance() << "\n"; gsInfo << methodName +": Residual error : " << method.error() << "\n"; gsInfo << methodName +": Number of iterations: " << method.iterations() << "\n"; gsInfo << methodName +": Time to solve: : " << time << "\n"; } int main(int argc, char *argv[]) { //Size of linear system index_t N = 200; if (argc >= 2) N = atoi(argv[1]); gsSparseMatrix<> mat; gsMatrix<> rhs; //Assemble the 1D Poisson equation poissonDiscretization(mat, rhs, N); //The minimal residual implementation requires a preconditioner. //We initialize an identity preconditioner (does nothing). gsIdentityPreconditioner preConMat(N); //Maximum number of iterations index_t maxIters = 3*N; //Tolerance real_t tol = math::pow(10.0, - REAL_DIG * 0.75); ///----------------------GISMO-SOLVERS----------------------/// gsInfo << "Testing G+Smo's solvers:\n"; //Initialize the MinRes solver gsMinimalResidual MinRes(mat,maxIters,tol); //Create the initial guess gsMatrix<> x0; x0.setZero(N,1); //Solve system with given preconditioner (solution is stored in x0) gsInfo << "\nMinRes: Started solving..." << "\n"; gsStopwatch clock; MinRes.solve(rhs,x0,preConMat); gsIterativeSolverInfo(MinRes, "MinRes", clock.stop()); //Initialize the CG solver gsGMRes GMResSolver(mat,maxIters,tol); //Set the initial guess to zero x0.setZero(N,1); if (N < 200) { //Solve system with given preconditioner (solution is stored in x0) gsInfo << "\nGMRes: Started solving..." << "\n"; clock.restart(); GMResSolver.solve(rhs,x0,preConMat); gsIterativeSolverInfo(GMResSolver, "GMRes", clock.stop()); } else gsInfo << "\nSkipping GMRes due to high number of iterations...\n"; //Initialize the CG solver gsConjugateGradient CGSolver(mat,maxIters,tol); //Set the initial guess to zero x0.setZero(N,1); //Solve system with given preconditioner (solution is stored in x0) gsInfo << "\nCG: Started solving..." << "\n"; clock.restart(); CGSolver.solve(rhs,x0,preConMat); gsIterativeSolverInfo(CGSolver, "CG", clock.stop()); ///----------------------EIGEN-ITERATIVE-SOLVERS----------------------/// gsInfo << "Testing Eigen's interative solvers:\n"; gsSparseSolver<>::CGIdentity EigenCGIsolver; EigenCGIsolver.setMaxIterations(maxIters); EigenCGIsolver.setTolerance(tol); gsInfo << "\nEigen's CG identity preconditioner: Started solving..." << "\n"; clock.restart(); EigenCGIsolver.compute(mat); x0 = EigenCGIsolver.solve(rhs); gsInfo << "Eigen's CG: Tolerance : " << EigenCGIsolver.tolerance() << "\n"; gsInfo << "Eigen's CG: Residual error : " << EigenCGIsolver.error() << "\n"; gsInfo << "Eigen's CG: Number of iterations: " << EigenCGIsolver.iterations() << "\n"; gsInfo << "Eigen's CG: Time to solve : " << clock.stop() << "\n"; gsSparseSolver<>::CGDiagonal EigenCGDsolver; EigenCGDsolver.setMaxIterations(maxIters); EigenCGDsolver.setTolerance(tol); gsInfo << "\nEigen's CG diagonal preconditioner: Started solving..." << "\n"; clock.restart(); EigenCGDsolver.compute(mat); x0 = EigenCGDsolver.solve(rhs); gsInfo << "Eigen's CG: Tolerance : " << EigenCGDsolver.tolerance() << "\n"; gsInfo << "Eigen's CG: Residual error : " << EigenCGDsolver.error() << "\n"; gsInfo << "Eigen's CG: Number of iterations: " << EigenCGDsolver.iterations() << "\n"; gsInfo << "Eigen's CG: Time to solve : " << clock.stop() << "\n"; gsSparseSolver<>::BiCGSTABIdentity EigenBCGIsolver; EigenBCGIsolver.setMaxIterations(maxIters); EigenBCGIsolver.setTolerance(tol); gsInfo << "\nEigen's bi conjugate gradient stabilized solver identity preconditioner: Started solving..." << "\n"; clock.restart(); EigenBCGIsolver.compute(mat); x0 = EigenBCGIsolver.solve(rhs); gsInfo << "Eigen's BiCGSTAB: Tolerance : " << EigenBCGIsolver.tolerance() << "\n"; gsInfo << "Eigen's BiCGSTAB: Residual error : " << EigenBCGIsolver.error() << "\n"; gsInfo << "Eigen's BiCGSTAB: Number of iterations: " << EigenBCGIsolver.iterations() << "\n"; gsInfo << "Eigen's BiCGSTAB: Time to solve : " << clock.stop() << "\n"; gsSparseSolver<>::BiCGSTABDiagonal EigenBCGDsolver; EigenBCGDsolver.setMaxIterations(maxIters); EigenBCGDsolver.setTolerance(tol); gsInfo << "\nEigen's bi conjugate gradient stabilized solver diagonal preconditioner: Started solving..." << "\n"; clock.restart(); EigenBCGDsolver.compute(mat); x0 = EigenBCGDsolver.solve(rhs); gsInfo << "Eigen's BiCGSTAB: Tolerance : " << EigenBCGDsolver.tolerance() << "\n"; gsInfo << "Eigen's BiCGSTAB: Residual error : " << EigenBCGDsolver.error() << "\n"; gsInfo << "Eigen's BiCGSTAB: Number of iterations: " << EigenBCGDsolver.iterations() << "\n"; gsInfo << "Eigen's BiCGSTAB: Time to solve : " << clock.stop() << "\n"; gsSparseSolver<>::BiCGSTABILUT EigenBCGILUsolver; //EigenBCGILUsolver.preconditioner().setFillfactor(1); EigenBCGILUsolver.setMaxIterations(maxIters); EigenBCGILUsolver.setTolerance(tol); gsInfo << "\nEigen's bi conjugate gradient stabilized solver ILU preconditioner: Started solving..." << "\n"; clock.restart(); EigenBCGILUsolver.compute(mat); x0 = EigenBCGILUsolver.solve(rhs); gsInfo << "Eigen's BiCGSTAB: Tolerance : " << EigenBCGILUsolver.tolerance() << "\n"; gsInfo << "Eigen's BiCGSTAB: Residual error : " << EigenBCGILUsolver.error() << "\n"; gsInfo << "Eigen's BiCGSTAB: Number of iterations: " << EigenBCGILUsolver.iterations() << "\n"; gsInfo << "Eigen's BiCGSTAB: Time to solve : " << clock.stop() << "\n"; ///----------------------EIGEN-DIRECT-SOLVERS----------------------/// gsSparseSolver<>::SimplicialLDLT EigenSLDLTsolver; gsInfo << "\nEigen's Simplicial LDLT: Started solving..." << "\n"; clock.restart(); EigenSLDLTsolver.compute(mat); x0 = EigenSLDLTsolver.solve(rhs); gsInfo << "Eigen's Simplicial LDLT: Time to solve : " << clock.stop() << "\n"; gsSparseSolver<>::QR solverQR; gsInfo << "\nEigen's QR: Started solving..." << "\n"; clock.restart(); solverQR.compute(mat); x0 = solverQR.solve(rhs); gsInfo << "Eigen's QR: Time to solve : " << clock.stop() << "\n"; gsSparseSolver<>::LU solverLU; gsInfo << "\nEigen's LU: Started solving..." << "\n"; clock.restart(); solverLU.compute(mat); x0 = solverLU.solve(rhs); gsInfo << "Eigen's LU: Time to solve : " << clock.stop() << "\n"; return 0; } <|endoftext|>
<commit_before>// -*- Mode: C++; tab-width: 2; -*- // vi: set ts=2: // #include <BALL/FORMAT/molFileFactory.h> #include <BALL/FORMAT/genericMolFile.h> #include <BALL/FORMAT/dockResultFile.h> #include <BALL/FORMAT/commandlineParser.h> #include <BALL/KERNEL/molecule.h> #include "version.h" using namespace BALL; using namespace std; void validateParameters(CommandlineParser& params) { // we need at least one of the following: no, ligands_per_file // TODO: move this "one of the following parameters" logic to CommandlineParser! if (!params.has("no") && !params.has("ligands_per_file")) { Log.error() << "One of the parameters 'no' and 'ligands_per_file' is required." << endl; exit(1); } if (params.has("no") && params.has("ligands_per_file")) { Log.error() << "At most one of the parameters 'no' and 'ligands_per_file' is required. You have provided both." << endl; exit(1); } // TODO: move this to CommandlineParser... using 'registerParameterRestrictions' does not seem to be working if (params.has("no")) { if (params.get("no").toInt() < 1) { Log.error() << "The provided value for parameter 'no', " << params.get("no").toInt() << ", is invalid. Values must be greater or equal to 1." << endl; exit(1); } } String ligandsPerFile = params.get("ligands_per_file"); if (ligandsPerFile != CommandlineParser::NOT_FOUND) { if (params.get("ligands_per_file").toInt() < 1) { Log.error() << "The provided value for parameter 'ligands_per_file', " << params.get("ligands_per_file").toInt() << ", is invalid. Values must be greater or equal to 1." << endl; exit(1); } } String outputNamePattern = params.get("output_name_pattern"); if (outputNamePattern != CommandlineParser::NOT_FOUND) { // count the number of '%d' and exit if the name is different to one string::size_type firstPlaceholder = outputNamePattern.find("%d"); string::size_type lastPlaceholder = outputNamePattern.rfind("%d"); // if there is more than one %d, it means that the index of the first and last occurrences are different // if there is not a single %d, then the index of both first and last occurrences must be npos if (firstPlaceholder != lastPlaceholder || firstPlaceholder == String::npos) { Log.error() << "The provided value for output_name_pattern '" << outputNamePattern << "' is invalid." << endl; exit(1); } } } String getFileFormat(String& fileName) { // locate the first dot, from right to left int dotIndex = fileName.find_last_of('.'); if (dotIndex < 0) { return ""; } return fileName.substr(dotIndex + 1, fileName.length() - dotIndex - 1); } String getOutputFileFormat(CommandlineParser& parameters) { // give preference to the 'output_format' parameter, // if not found, then use the format of the input file String format = parameters.get("output_format"); if (format != CommandlineParser::NOT_FOUND) { return format; } String inputFile = parameters.get("i"); return getFileFormat(inputFile); } String getOutputFileName(CommandlineParser& parameters, int index) { String outputNamePattern = parameters.get("output_name_pattern"); String outputFileName; if (outputNamePattern != CommandlineParser::NOT_FOUND) { outputNamePattern.substituteAll("%d", String(index)); outputFileName = outputNamePattern; } else { String inputFileName = parameters.get("i"); String extension = '.' + getFileFormat(inputFileName); // if invoked with -i ligands.sdf, output name will be ligands_<index>.sdf outputFileName = inputFileName.before(extension) + "_" + String(index) + extension; } return outputFileName; } int main(int argc, char* argv[]) { CommandlineParser parpars("LigandFileSplitter", "split molecule files", VERSION, String(__DATE__), "Preparation"); parpars.registerParameter("i", "input molecule file", INFILE, true); parpars.registerParameter("no", "no. of splits to be created", BALL::INT, false); parpars.registerParameter("ligands_per_file", "max. number of ligands to output to a file", BALL::INT, false); parpars.registerParameter("output_name_pattern", "pattern that will be used to generate the names of the output files, see notes and examples below.", BALL::STRING, false); parpars.registerParameter("o", "output filenames; if none are specified, input filename postfixed with IDs will be used", OUTFILELIST, false); parpars.registerParameter("output_format", "format of the output filenames, see notes and examples below.", BALL::STRING, false); String man = "LigandFileSplitter splits a molecule file into a given number of subsets.\n" "Note that the molecules are not sorted in any way for this.\n\n" "Examples:\n\n" "$ LigandFileSplitter -i Trypsin_actives.sdf -no 3\n" " will split the input file Trypsin_actives.sdf in three files named Trypsin_actives_0.sdf, Trypsin_actives_1.sdf and Trypsin_actives_2.sdf\n\n" "$ LigandFileSplitter -i ligands.sdf -ligands_per_file 4\n" " will split the input file ligands.sdf in as many files needed to fit at most 4 ligands per file.\n" " The files will be named ligands_0.sdf, ligands_1.sdf ... ligands_N.sdf\n\n" "$ LigandFileSplitter -i ligands.sdf -ligands_per_file 5 -output_name_pattern split_ligands-%d.sdf\n" " will split the input file ligands.sdf in as many files needed to fit at most 5 ligands per file.\n" " The files will be named split_ligands-0.sdf, split_ligands-1.sdf, ... , split_ligands-N.sdf\n" " and they will have sdf format.\n\n" "$ LigandFileSplitter -i ligands.sdf -output_name_pattern split_ligands.mol2_%d -output_format mol2 -no 100\n" " will split the input file ligands.sdf in 100 files using the following names:\n" " split_ligands.mol2_0, split_ligands.mol2_1, ... , split_ligands.mol2_99\n" " The output files will have mol2 format. If the 'output_format' parameter is not given, then the ouput files\n" " will have the same format as the input file (sdf).\n\n" "NOTE:\n" " output_name_pattern accepts a printf-like pattern, expecting exactly one decimal integer placeholder, %d.\n" " The following are valid patterns: output_ligand.sdf_%d, split_%d.mol, %d_lig.drf\n" " The following are invalid patterns: output_%f.sdf, ligands.drf_%u, %d_lig_%d.mol, molecules.sdf\n" " If you want the output files to have a different format than the given input file, use the 'output_format' parameter."; parpars.setToolManual(man); parpars.setSupportedFormats("i","mol2,sdf,drf"); parpars.setSupportedFormats("o","mol2,sdf,drf"); parpars.setOutputFormatSource("o","i"); parpars.parse(argc, argv); validateParameters(parpars); GenericMolFile* input = MolFileFactory::open(parpars.get("i")); // Determine number of molecules in input files. // In case of DockResultFiles, we do not need to process all contained molecules in order to achieve this; we can simply count the result-section entries. int no_compounds = 0; DockResultFile* drf_input = dynamic_cast<DockResultFile*>(input); if (drf_input) { no_compounds = drf_input->countConformations(); Log.level(10)<<"\rinput-file contains "<<no_compounds<<" conformations."<<endl; } else { for (Molecule* mol = input->read(); mol; mol = input->read()) { no_compounds++; delete mol; if (no_compounds%50 == 0) { Log.level(10)<<"\r"<<no_compounds<<" molecules"; Log.flush(); } } Log.level(10)<<"\rinput-file contains "<<no_compounds<<" molecules."<<endl; } input->close(); delete input; // if ligands_per_file was provided, simply insert the parameter 'no' with a proper value int numberOfFiles = -1; if (parpars.has("ligands_per_file")) { int ligandsPerFile = parpars.get("ligands_per_file").toInt(); // we know the number of ligands per file and the number of input ligands, so: numberOfFiles = no_compounds / ligandsPerFile; if ((numberOfFiles * ligandsPerFile) < no_compounds) { numberOfFiles++; } } input = MolFileFactory::open(parpars.get("i")); drf_input = dynamic_cast<DockResultFile*>(input); if (drf_input) drf_input->selectAllResultsForInput(); // if numberOfFiles != -1, it means that ligands_per_file was set int no_splits = numberOfFiles == -1 ? parpars.get("no").toInt() : numberOfFiles; vector<String> output_files; if (parpars.has("o")) { list<String> l = parpars.getList("o"); for (list<String>::iterator it = l.begin(); it!=l.end(); it++) { output_files.push_back(*it); } } int comp_per_split = no_compounds/no_splits; int remainer = no_compounds-(comp_per_split*no_splits); int written_compounds = 0; Log.level(10)<<endl<<"will now write split-files :"<<endl; for (int i = 0; i < no_splits; i++) { String filename; GenericMolFile* output; if ((int)output_files.size() > i) { filename = output_files[i]; // honor the use of "output_format" String format = parpars.get("output_format"); if (format != CommandlineParser::NOT_FOUND) { output = MolFileFactory::open(filename, ios::out, format); } else { output = MolFileFactory::open(filename, ios::out, input); } } else { filename = getOutputFileName(parpars, i); output = MolFileFactory::open(filename, ios::out, getOutputFileFormat(parpars)); } DockResultFile* drf_output = dynamic_cast<DockResultFile*>(output); if (drf_input && drf_output) drf_output->disableAutomaticResultCreation(); HashSet < String > conformation_IDs; int written_compounds_current_split = 0; for (int j = 0; j < comp_per_split || (i == no_splits-1&&written_compounds<no_compounds); j++) { Molecule* mol = input->read(); if (!mol) break; if (drf_input && drf_output && mol->hasProperty("Conformation_input_UID")) { conformation_IDs.insert(mol->getProperty("Conformation_input_UID").toString()); } *output << *mol; delete mol; written_compounds++; written_compounds_current_split++; if (written_compounds_current_split%50 == 0) { Log.level(20)<<"\r"<<filename<<": "<<written_compounds_current_split; Log.flush(); } } if (drf_input && drf_output) { const vector<Result*>* results = drf_input->getResults(); for (Size i = 0; i < results->size(); i++) { Result* new_res = new Result(*(*results)[i], conformation_IDs); drf_output->addResult(new_res); } } // evenly distribute remaining compounds if (remainer > 1 && i == no_splits-1-remainer) { comp_per_split++; } Log.level(20)<<"\r"<<filename<<": "<<written_compounds_current_split<<endl; delete output; } delete input; return 0; } <commit_msg>Fixed debug compiling of LigandFileSplitter<commit_after>// -*- Mode: C++; tab-width: 2; -*- // vi: set ts=2: // #include <BALL/FORMAT/molFileFactory.h> #include <BALL/FORMAT/genericMolFile.h> #include <BALL/FORMAT/dockResultFile.h> #include <BALL/FORMAT/commandlineParser.h> #include <BALL/KERNEL/molecule.h> #include "version.h" using namespace BALL; using namespace std; void validateParameters(CommandlineParser& params) { // we need at least one of the following: no, ligands_per_file // TODO: move this "one of the following parameters" logic to CommandlineParser! if (!params.has("no") && !params.has("ligands_per_file")) { Log.error() << "One of the parameters 'no' and 'ligands_per_file' is required." << endl; exit(1); } if (params.has("no") && params.has("ligands_per_file")) { Log.error() << "At most one of the parameters 'no' and 'ligands_per_file' is required. You have provided both." << endl; exit(1); } // TODO: move this to CommandlineParser... using 'registerParameterRestrictions' does not seem to be working if (params.has("no")) { if (params.get("no").toInt() < 1) { Log.error() << "The provided value for parameter 'no', " << params.get("no").toInt() << ", is invalid. Values must be greater or equal to 1." << endl; exit(1); } } String ligandsPerFile = params.get("ligands_per_file"); if (ligandsPerFile != CommandlineParser::NOT_FOUND) { if (params.get("ligands_per_file").toInt() < 1) { Log.error() << "The provided value for parameter 'ligands_per_file', " << params.get("ligands_per_file").toInt() << ", is invalid. Values must be greater or equal to 1." << endl; exit(1); } } String outputNamePattern = params.get("output_name_pattern"); if (outputNamePattern != CommandlineParser::NOT_FOUND) { // count the number of '%d' and exit if the name is different to one string::size_type firstPlaceholder = outputNamePattern.find("%d"); string::size_type lastPlaceholder = outputNamePattern.rfind("%d"); // if there is more than one %d, it means that the index of the first and last occurrences are different // if there is not a single %d, then the index of both first and last occurrences must be npos if (firstPlaceholder != lastPlaceholder || firstPlaceholder == String::npos) { Log.error() << "The provided value for output_name_pattern '" << outputNamePattern << "' is invalid." << endl; exit(1); } } } String getFileFormat(String& fileName) { // locate the first dot, from right to left int dotIndex = fileName.find_last_of('.'); if (dotIndex < 0) { return ""; } return fileName.substr(dotIndex + 1, fileName.length() - dotIndex - 1); } String getOutputFileFormat(CommandlineParser& parameters) { // give preference to the 'output_format' parameter, // if not found, then use the format of the input file String format = parameters.get("output_format"); if (format != CommandlineParser::NOT_FOUND) { return format; } String inputFile = parameters.get("i"); return getFileFormat(inputFile); } String getOutputFileName(CommandlineParser& parameters, int index) { String outputNamePattern = parameters.get("output_name_pattern"); String outputFileName; if (outputNamePattern != CommandlineParser::NOT_FOUND) { outputNamePattern.substituteAll("%d", String(index)); outputFileName = outputNamePattern; } else { String inputFileName = parameters.get("i"); String extension = '.' + getFileFormat(inputFileName); // if invoked with -i ligands.sdf, output name will be ligands_<index>.sdf outputFileName = inputFileName.before(extension) + String("_") + String(index) + extension; } return outputFileName; } int main(int argc, char* argv[]) { CommandlineParser parpars("LigandFileSplitter", "split molecule files", VERSION, String(__DATE__), "Preparation"); parpars.registerParameter("i", "input molecule file", INFILE, true); parpars.registerParameter("no", "no. of splits to be created", BALL::INT, false); parpars.registerParameter("ligands_per_file", "max. number of ligands to output to a file", BALL::INT, false); parpars.registerParameter("output_name_pattern", "pattern that will be used to generate the names of the output files, see notes and examples below.", BALL::STRING, false); parpars.registerParameter("o", "output filenames; if none are specified, input filename postfixed with IDs will be used", OUTFILELIST, false); parpars.registerParameter("output_format", "format of the output filenames, see notes and examples below.", BALL::STRING, false); String man = "LigandFileSplitter splits a molecule file into a given number of subsets.\n" "Note that the molecules are not sorted in any way for this.\n\n" "Examples:\n\n" "$ LigandFileSplitter -i Trypsin_actives.sdf -no 3\n" " will split the input file Trypsin_actives.sdf in three files named Trypsin_actives_0.sdf, Trypsin_actives_1.sdf and Trypsin_actives_2.sdf\n\n" "$ LigandFileSplitter -i ligands.sdf -ligands_per_file 4\n" " will split the input file ligands.sdf in as many files needed to fit at most 4 ligands per file.\n" " The files will be named ligands_0.sdf, ligands_1.sdf ... ligands_N.sdf\n\n" "$ LigandFileSplitter -i ligands.sdf -ligands_per_file 5 -output_name_pattern split_ligands-%d.sdf\n" " will split the input file ligands.sdf in as many files needed to fit at most 5 ligands per file.\n" " The files will be named split_ligands-0.sdf, split_ligands-1.sdf, ... , split_ligands-N.sdf\n" " and they will have sdf format.\n\n" "$ LigandFileSplitter -i ligands.sdf -output_name_pattern split_ligands.mol2_%d -output_format mol2 -no 100\n" " will split the input file ligands.sdf in 100 files using the following names:\n" " split_ligands.mol2_0, split_ligands.mol2_1, ... , split_ligands.mol2_99\n" " The output files will have mol2 format. If the 'output_format' parameter is not given, then the ouput files\n" " will have the same format as the input file (sdf).\n\n" "NOTE:\n" " output_name_pattern accepts a printf-like pattern, expecting exactly one decimal integer placeholder, %d.\n" " The following are valid patterns: output_ligand.sdf_%d, split_%d.mol, %d_lig.drf\n" " The following are invalid patterns: output_%f.sdf, ligands.drf_%u, %d_lig_%d.mol, molecules.sdf\n" " If you want the output files to have a different format than the given input file, use the 'output_format' parameter."; parpars.setToolManual(man); parpars.setSupportedFormats("i","mol2,sdf,drf"); parpars.setSupportedFormats("o","mol2,sdf,drf"); parpars.setOutputFormatSource("o","i"); parpars.parse(argc, argv); validateParameters(parpars); GenericMolFile* input = MolFileFactory::open(parpars.get("i")); // Determine number of molecules in input files. // In case of DockResultFiles, we do not need to process all contained molecules in order to achieve this; we can simply count the result-section entries. int no_compounds = 0; DockResultFile* drf_input = dynamic_cast<DockResultFile*>(input); if (drf_input) { no_compounds = drf_input->countConformations(); Log.level(10)<<"\rinput-file contains "<<no_compounds<<" conformations."<<endl; } else { for (Molecule* mol = input->read(); mol; mol = input->read()) { no_compounds++; delete mol; if (no_compounds%50 == 0) { Log.level(10)<<"\r"<<no_compounds<<" molecules"; Log.flush(); } } Log.level(10)<<"\rinput-file contains "<<no_compounds<<" molecules."<<endl; } input->close(); delete input; // if ligands_per_file was provided, simply insert the parameter 'no' with a proper value int numberOfFiles = -1; if (parpars.has("ligands_per_file")) { int ligandsPerFile = parpars.get("ligands_per_file").toInt(); // we know the number of ligands per file and the number of input ligands, so: numberOfFiles = no_compounds / ligandsPerFile; if ((numberOfFiles * ligandsPerFile) < no_compounds) { numberOfFiles++; } } input = MolFileFactory::open(parpars.get("i")); drf_input = dynamic_cast<DockResultFile*>(input); if (drf_input) drf_input->selectAllResultsForInput(); // if numberOfFiles != -1, it means that ligands_per_file was set int no_splits = numberOfFiles == -1 ? parpars.get("no").toInt() : numberOfFiles; vector<String> output_files; if (parpars.has("o")) { list<String> l = parpars.getList("o"); for (list<String>::iterator it = l.begin(); it!=l.end(); it++) { output_files.push_back(*it); } } int comp_per_split = no_compounds/no_splits; int remainer = no_compounds-(comp_per_split*no_splits); int written_compounds = 0; Log.level(10)<<endl<<"will now write split-files :"<<endl; for (int i = 0; i < no_splits; i++) { String filename; GenericMolFile* output; if ((int)output_files.size() > i) { filename = output_files[i]; // honor the use of "output_format" String format = parpars.get("output_format"); if (format != CommandlineParser::NOT_FOUND) { output = MolFileFactory::open(filename, ios::out, format); } else { output = MolFileFactory::open(filename, ios::out, input); } } else { filename = getOutputFileName(parpars, i); output = MolFileFactory::open(filename, ios::out, getOutputFileFormat(parpars)); } DockResultFile* drf_output = dynamic_cast<DockResultFile*>(output); if (drf_input && drf_output) drf_output->disableAutomaticResultCreation(); HashSet < String > conformation_IDs; int written_compounds_current_split = 0; for (int j = 0; j < comp_per_split || (i == no_splits-1&&written_compounds<no_compounds); j++) { Molecule* mol = input->read(); if (!mol) break; if (drf_input && drf_output && mol->hasProperty("Conformation_input_UID")) { conformation_IDs.insert(mol->getProperty("Conformation_input_UID").toString()); } *output << *mol; delete mol; written_compounds++; written_compounds_current_split++; if (written_compounds_current_split%50 == 0) { Log.level(20)<<"\r"<<filename<<": "<<written_compounds_current_split; Log.flush(); } } if (drf_input && drf_output) { const vector<Result*>* results = drf_input->getResults(); for (Size i = 0; i < results->size(); i++) { Result* new_res = new Result(*(*results)[i], conformation_IDs); drf_output->addResult(new_res); } } // evenly distribute remaining compounds if (remainer > 1 && i == no_splits-1-remainer) { comp_per_split++; } Log.level(20)<<"\r"<<filename<<": "<<written_compounds_current_split<<endl; delete output; } delete input; return 0; } <|endoftext|>
<commit_before>/* * Java Genetic Algorithm Library (@__identifier__@). * Copyright (c) @__year__@ Franz Wilhelmstötter * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * * Author: * Franz Wilhelmstötter (franz.wilhelmstoetter@gmx.at) * */ #include <cstdlib> #include <iostream> #include <iomanip> #include <sstream> #include <fstream> #include <vector> #include <trng/lcg64_shift.hpp> /** * @author <a href="mailto:franz.wilhelmstoetter@gmx.at">Franz Wilhelmstötter</a> * @version <em>$Date: 2012-12-19 $</em> */ template<class Random> class TRNGRandomOutput { public: TRNGRandomOutput( unsigned long long seed, unsigned int splitp, unsigned int splits, unsigned long long jump, unsigned int jump2 ) { _random.seed(seed); _random.split(splitp, splits); _random.jump(jump); _random.jump2(jump2); std::stringstream name; name << seed << "-"; name << splitp << "-" << splits << "-"; name << jump << "-"; name << jump2; _fileName = name.str(); } ~TRNGRandomOutput() { } std::string next() { std::stringstream out; out << static_cast<long long>(_random()); return out.str(); } std::string fileName() { return _fileName; } private: Random _random; std::string _fileName; }; template<class Random> void write(const std::string& dir, TRNGRandomOutput<Random>& random, std::size_t numbers) { std::string file = dir + "/" + random.fileName(); std::fstream out(file.c_str(), std::fstream::out); for (std::size_t i = 0; i < numbers; ++i) { out << random.next() << std::endl; } out.close(); } int main(void) { int count = 0; for (unsigned long long seed = 0; seed < 2; ++seed) { for (unsigned int splitp = 5; splitp < 10; splitp += 3) { for (unsigned int splits = 0; splits < splitp; splits += 2) { for (unsigned long long jump = 0; jump < 2; ++jump) { for (unsigned int jump2 = 0; jump2 < 64; jump2 += 23) { std::cout << "{new Long(" << static_cast<long long>(seed*74236788222246L) << "L), " << "new Integer(" << static_cast<long long>(splitp) << "), " << "new Integer(" << static_cast<long long>(splits) << "), " << "new Long(" << static_cast<long long>(jump*948392782247324L) << "L), " << "new Integer(" << static_cast<long long>(jump2) << ")}," << std::endl; TRNGRandomOutput<trng::lcg64_shift> random( seed*74236788222246L, splitp, splits, jump*948392782247324L, jump2 ); write<trng::lcg64_shift>("output", random, 150); } } } } } return 0; } <commit_msg>Some code cleanup.<commit_after>/* * Java Genetic Algorithm Library (@__identifier__@). * Copyright (c) @__year__@ Franz Wilhelmstötter * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * * Author: * Franz Wilhelmstötter (franz.wilhelmstoetter@gmx.at) * */ #include <cstdlib> #include <iostream> #include <iomanip> #include <sstream> #include <fstream> #include <vector> #include <trng/lcg64_shift.hpp> /** * @author <a href="mailto:franz.wilhelmstoetter@gmx.at">Franz Wilhelmstötter</a> * @version <em>$Date: 2013-12-08 $</em> */ template<class Random> class TRNGRandomOutput { public: TRNGRandomOutput( unsigned long long seed, unsigned int splitp, unsigned int splits, unsigned long long jump, unsigned int jump2 ) { _random.seed(seed); _random.split(splitp, splits); _random.jump(jump); _random.jump2(jump2); std::stringstream name; name << seed << "-"; name << splitp << "-" << splits << "-"; name << jump << "-"; name << jump2; _fileName = name.str(); } ~TRNGRandomOutput() { } std::string next() { std::stringstream out; out << static_cast<long long>(_random()); return out.str(); } std::string fileName() { return _fileName; } private: Random _random; std::string _fileName; }; template<class Random> void write(const std::string& dir, TRNGRandomOutput<Random>& random, std::size_t numbers) { std::string file = dir + "/" + random.fileName(); std::fstream out(file.c_str(), std::fstream::out); for (std::size_t i = 0; i < numbers; ++i) { out << random.next() << std::endl; } out.close(); } int main(void) { int count = 0; for (unsigned long long seed = 0; seed < 2; ++seed) { for (unsigned int splitp = 5; splitp < 10; splitp += 3) { for (unsigned int splits = 0; splits < splitp; splits += 2) { for (unsigned long long jump = 0; jump < 2; ++jump) { for (unsigned int jump2 = 0; jump2 < 64; jump2 += 23) { std::cout << "{new Long(" << static_cast<long long>(seed*74236788222246L) << "L), " << "new Integer(" << static_cast<long long>(splitp) << "), " << "new Integer(" << static_cast<long long>(splits) << "), " << "new Long(" << static_cast<long long>(jump*948392782247324L) << "L), " << "new Integer(" << static_cast<long long>(jump2) << ")}," << std::endl; TRNGRandomOutput<trng::lcg64_shift> random( seed*74236788222246L, splitp, splits, jump*948392782247324L, jump2 ); write<trng::lcg64_shift>("output", random, 150); } } } } } return 0; } <|endoftext|>
<commit_before>/****************************************************************************** * The MIT License (MIT) * * Copyright (c) 2015-2016 Baldur Karlsson * Copyright (c) 2014 Crytek * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. ******************************************************************************/ #include "os/os_specific.h" #include <execinfo.h> #include <stdio.h> #include <string.h> #include <vector> #include <map> void *renderdocBase = NULL; void *renderdocEnd = NULL; class LinuxCallstack : public Callstack::Stackwalk { public: LinuxCallstack() { RDCEraseEl(addrs); numLevels = 0; Collect(); } LinuxCallstack(uint64_t *calls, size_t num) { Set(calls, num); } ~LinuxCallstack() {} void Set(uint64_t *calls, size_t num) { numLevels = num; for(int i=0; i < numLevels; i++) addrs[i] = calls[i]; } size_t NumLevels() const { return size_t(numLevels); } const uint64_t *GetAddrs() const { return addrs; } private: LinuxCallstack(const Callstack::Stackwalk &other); void Collect() { void *addrs_ptr[ARRAY_COUNT(addrs)]; numLevels = backtrace(addrs_ptr, ARRAY_COUNT(addrs)); int offs = 0; // if we want to trim levels of the stack, we can do that here // by incrementing offs and decrementing numLevels while(numLevels > 0 && addrs_ptr[offs] >= renderdocBase && addrs_ptr[offs] < renderdocEnd) { offs++; numLevels--; } for(int i=0; i < numLevels; i++) addrs[i] = (uint64_t)addrs_ptr[i+offs]; } uint64_t addrs[128]; int numLevels; }; namespace Callstack { void Init() { // look for our own line FILE *f = FileIO::fopen("/proc/self/maps", "r"); while(!feof(f)) { char line[512] = {0}; if(fgets(line, 511, f)) { if(strstr(line, "librenderdoc") && strstr(line, "r-xp")) { sscanf(line, "%p-%p", &renderdocBase, &renderdocEnd); break; } } } FileIO::fclose(f); } Stackwalk *Collect() { return new LinuxCallstack(); } Stackwalk *Create() { return new LinuxCallstack(NULL, 0); } bool GetLoadedModules(char *&buf, size_t &size) { // we just dump the whole file rather than pre-parsing, that way we can improve // parsing without needing to recapture FILE *f = FileIO::fopen("/proc/self/maps", "r"); if(buf) { buf[0] = 'L'; buf[1] = 'N'; buf[2] = 'U'; buf[3] = 'X'; buf[4] = 'C'; buf[5] = 'A'; buf[6] = 'L'; buf[7] = 'L'; } size += 8; char dummy[512]; while(!feof(f)) { char *readbuf = buf ? buf + size : dummy; size += FileIO::fread(readbuf, 1, 512, f); } FileIO::fclose(f); return true; } struct LookupModule { uint64_t base; uint64_t end; char path[2048]; }; class LinuxResolver : public Callstack::StackResolver { public: LinuxResolver(vector<LookupModule> modules) { m_Modules = modules; } Callstack::AddressDetails GetAddr(uint64_t addr) { EnsureCached(addr); return m_Cache[addr]; } private: void EnsureCached(uint64_t addr) { auto it = m_Cache.insert(std::pair<uint64_t, Callstack::AddressDetails>(addr, Callstack::AddressDetails())); if(!it.second) return; Callstack::AddressDetails &ret = it.first->second; ret.filename = "Unknown"; ret.line = 0; ret.function = StringFormat::Fmt("0x%08llx", addr); for(size_t i=0; i < m_Modules.size(); i++) { if(addr >= m_Modules[i].base && addr < m_Modules[i].end) { uint64_t relative = addr - m_Modules[i].base; string cmd = StringFormat::Fmt("addr2line -j.text -fCe \"%s\" 0x%llx", m_Modules[i].path, relative); FILE *f = ::popen(cmd.c_str(), "r"); char result[2048] = {0}; fread(result, 1, 2047, f); fclose(f); char *line2 = strchr(result, '\n'); if(line2) { *line2 = 0; line2++; } ret.function = result; if(line2) { char *last = line2 + strlen(line2) - 1; uint32_t mul = 1; ret.line = 0; while(*last >= '0' && *last <= '9') { ret.line += mul * (uint32_t(*last)-uint32_t('0')); *last = 0; last--; mul *= 10; } if(*last == ':') *last = 0; ret.filename = line2; } break; } } } std::vector<LookupModule> m_Modules; std::map<uint64_t, Callstack::AddressDetails> m_Cache; }; StackResolver *MakeResolver(char *moduleDB, size_t DBSize, string pdbSearchPaths, volatile bool *killSignal) { // we look in the original locations for the files, we don't prompt if we can't // find the file, or the file doesn't have symbols (and we don't validate that // the file is the right version). A good option for doing this would be // http://github.com/mlabbe/nativefiledialog bool valid = true; if(memcmp(moduleDB, "LNUXCALL", 8)) { RDCWARN("Can't load callstack resolve for this log. Possibly from another platform?"); valid = false; } char *search = moduleDB+8; vector<LookupModule> modules; while(valid && search && size_t(search-moduleDB) < DBSize) { if(killSignal && *killSignal) break; // find .text segments { long unsigned int base = 0, end = 0; int inode = 0; int offs = 0; // base-end perms offset devid inode offs int num = sscanf(search, "%lx-%lx r-xp %*x %*x:%*x %d %n", &base, &end, &inode, &offs); // we don't care about inode actually, we ust use it to verify that // we read all 3 params (and so perms == r-xp) if(num == 3 && offs > 0) { LookupModule mod = {0}; mod.base = (uint64_t)base; mod.end = (uint64_t)end; search += offs; while(size_t(search-moduleDB) < DBSize && (*search == ' ' || *search == '\t')) search++; if(size_t(search-moduleDB) < DBSize && *search != '[' && *search != 0 && *search != '\n') { size_t n = ARRAY_COUNT(mod.path)-1; mod.path[n] = 0; for(size_t i=0; i < n; i++) { if(search[i] == 0 || search[i] == '\n') { mod.path[i] = 0; break; } if(search + i >= moduleDB + DBSize) { mod.path[i] = 0; break; } mod.path[i] = search[i]; } // addr2line wants offsets relative to text section, have to find offset of .text section in this // mmapped section int textoffs = 0; string cmd = StringFormat::Fmt("readelf -WS \"%s\"", mod.path); FILE *f = ::popen(cmd.c_str(), "r"); char result[4096] = {0}; fread(result, 1, 4095, f); fclose(f); // find .text line char *find = strstr(result, ".text"); if(find) { find += 5; while(isalpha(*find) || isspace(*find)) find++; // virtual address is listed first, we want the offset sscanf(find, "%*x %x", &textoffs); mod.base += textoffs; modules.push_back(mod); } } } } if(search >= (char *)(moduleDB+DBSize)) break; search = strchr(search, '\n'); if(search) search++; } return new LinuxResolver(modules); } }; <commit_msg>Fix crash if fopen "/proc/self/maps" returns NULL<commit_after>/****************************************************************************** * The MIT License (MIT) * * Copyright (c) 2015-2016 Baldur Karlsson * Copyright (c) 2014 Crytek * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. ******************************************************************************/ #include "os/os_specific.h" #include <execinfo.h> #include <stdio.h> #include <string.h> #include <vector> #include <map> void *renderdocBase = NULL; void *renderdocEnd = NULL; class LinuxCallstack : public Callstack::Stackwalk { public: LinuxCallstack() { RDCEraseEl(addrs); numLevels = 0; Collect(); } LinuxCallstack(uint64_t *calls, size_t num) { Set(calls, num); } ~LinuxCallstack() {} void Set(uint64_t *calls, size_t num) { numLevels = num; for(int i=0; i < numLevels; i++) addrs[i] = calls[i]; } size_t NumLevels() const { return size_t(numLevels); } const uint64_t *GetAddrs() const { return addrs; } private: LinuxCallstack(const Callstack::Stackwalk &other); void Collect() { void *addrs_ptr[ARRAY_COUNT(addrs)]; numLevels = backtrace(addrs_ptr, ARRAY_COUNT(addrs)); int offs = 0; // if we want to trim levels of the stack, we can do that here // by incrementing offs and decrementing numLevels while(numLevels > 0 && addrs_ptr[offs] >= renderdocBase && addrs_ptr[offs] < renderdocEnd) { offs++; numLevels--; } for(int i=0; i < numLevels; i++) addrs[i] = (uint64_t)addrs_ptr[i+offs]; } uint64_t addrs[128]; int numLevels; }; namespace Callstack { void Init() { // look for our own line FILE *f = FileIO::fopen("/proc/self/maps", "r"); if (f) { while(!feof(f)) { char line[512] = {0}; if(fgets(line, 511, f)) { if(strstr(line, "librenderdoc") && strstr(line, "r-xp")) { sscanf(line, "%p-%p", &renderdocBase, &renderdocEnd); break; } } } FileIO::fclose(f); } } Stackwalk *Collect() { return new LinuxCallstack(); } Stackwalk *Create() { return new LinuxCallstack(NULL, 0); } bool GetLoadedModules(char *&buf, size_t &size) { // we just dump the whole file rather than pre-parsing, that way we can improve // parsing without needing to recapture FILE *f = FileIO::fopen("/proc/self/maps", "r"); if(buf) { buf[0] = 'L'; buf[1] = 'N'; buf[2] = 'U'; buf[3] = 'X'; buf[4] = 'C'; buf[5] = 'A'; buf[6] = 'L'; buf[7] = 'L'; } size += 8; char dummy[512]; while(!feof(f)) { char *readbuf = buf ? buf + size : dummy; size += FileIO::fread(readbuf, 1, 512, f); } FileIO::fclose(f); return true; } struct LookupModule { uint64_t base; uint64_t end; char path[2048]; }; class LinuxResolver : public Callstack::StackResolver { public: LinuxResolver(vector<LookupModule> modules) { m_Modules = modules; } Callstack::AddressDetails GetAddr(uint64_t addr) { EnsureCached(addr); return m_Cache[addr]; } private: void EnsureCached(uint64_t addr) { auto it = m_Cache.insert(std::pair<uint64_t, Callstack::AddressDetails>(addr, Callstack::AddressDetails())); if(!it.second) return; Callstack::AddressDetails &ret = it.first->second; ret.filename = "Unknown"; ret.line = 0; ret.function = StringFormat::Fmt("0x%08llx", addr); for(size_t i=0; i < m_Modules.size(); i++) { if(addr >= m_Modules[i].base && addr < m_Modules[i].end) { uint64_t relative = addr - m_Modules[i].base; string cmd = StringFormat::Fmt("addr2line -j.text -fCe \"%s\" 0x%llx", m_Modules[i].path, relative); FILE *f = ::popen(cmd.c_str(), "r"); char result[2048] = {0}; fread(result, 1, 2047, f); fclose(f); char *line2 = strchr(result, '\n'); if(line2) { *line2 = 0; line2++; } ret.function = result; if(line2) { char *last = line2 + strlen(line2) - 1; uint32_t mul = 1; ret.line = 0; while(*last >= '0' && *last <= '9') { ret.line += mul * (uint32_t(*last)-uint32_t('0')); *last = 0; last--; mul *= 10; } if(*last == ':') *last = 0; ret.filename = line2; } break; } } } std::vector<LookupModule> m_Modules; std::map<uint64_t, Callstack::AddressDetails> m_Cache; }; StackResolver *MakeResolver(char *moduleDB, size_t DBSize, string pdbSearchPaths, volatile bool *killSignal) { // we look in the original locations for the files, we don't prompt if we can't // find the file, or the file doesn't have symbols (and we don't validate that // the file is the right version). A good option for doing this would be // http://github.com/mlabbe/nativefiledialog bool valid = true; if(memcmp(moduleDB, "LNUXCALL", 8)) { RDCWARN("Can't load callstack resolve for this log. Possibly from another platform?"); valid = false; } char *search = moduleDB+8; vector<LookupModule> modules; while(valid && search && size_t(search-moduleDB) < DBSize) { if(killSignal && *killSignal) break; // find .text segments { long unsigned int base = 0, end = 0; int inode = 0; int offs = 0; // base-end perms offset devid inode offs int num = sscanf(search, "%lx-%lx r-xp %*x %*x:%*x %d %n", &base, &end, &inode, &offs); // we don't care about inode actually, we ust use it to verify that // we read all 3 params (and so perms == r-xp) if(num == 3 && offs > 0) { LookupModule mod = {0}; mod.base = (uint64_t)base; mod.end = (uint64_t)end; search += offs; while(size_t(search-moduleDB) < DBSize && (*search == ' ' || *search == '\t')) search++; if(size_t(search-moduleDB) < DBSize && *search != '[' && *search != 0 && *search != '\n') { size_t n = ARRAY_COUNT(mod.path)-1; mod.path[n] = 0; for(size_t i=0; i < n; i++) { if(search[i] == 0 || search[i] == '\n') { mod.path[i] = 0; break; } if(search + i >= moduleDB + DBSize) { mod.path[i] = 0; break; } mod.path[i] = search[i]; } // addr2line wants offsets relative to text section, have to find offset of .text section in this // mmapped section int textoffs = 0; string cmd = StringFormat::Fmt("readelf -WS \"%s\"", mod.path); FILE *f = ::popen(cmd.c_str(), "r"); char result[4096] = {0}; fread(result, 1, 4095, f); fclose(f); // find .text line char *find = strstr(result, ".text"); if(find) { find += 5; while(isalpha(*find) || isspace(*find)) find++; // virtual address is listed first, we want the offset sscanf(find, "%*x %x", &textoffs); mod.base += textoffs; modules.push_back(mod); } } } } if(search >= (char *)(moduleDB+DBSize)) break; search = strchr(search, '\n'); if(search) search++; } return new LinuxResolver(modules); } }; <|endoftext|>
<commit_before>// Copyright Contributors to the OpenVDB Project // SPDX-License-Identifier: MPL-2.0 #include <cppunit/extensions/HelperMacros.h> #include <openvdb/openvdb.h> #include <openvdb/tree/Tree.h> #include <openvdb/tree/LeafNode.h> #include <openvdb/Types.h> #include <openvdb/Exceptions.h> class TestGridBbox: public CppUnit::TestCase { public: CPPUNIT_TEST_SUITE(TestGridBbox); CPPUNIT_TEST(testLeafBbox); CPPUNIT_TEST(testGridBbox); CPPUNIT_TEST_SUITE_END(); void testLeafBbox(); void testGridBbox(); }; CPPUNIT_TEST_SUITE_REGISTRATION(TestGridBbox); //////////////////////////////////////// void TestGridBbox::testLeafBbox() { openvdb::FloatTree tree(/*fillValue=*/256.0f); openvdb::CoordBBox bbox; CPPUNIT_ASSERT(!tree.evalLeafBoundingBox(bbox)); // Add values to buffer zero. tree.setValue(openvdb::Coord( 0, 9, 9), 2.0); tree.setValue(openvdb::Coord(100, 35, 800), 2.5); // Coordinates in CoordBBox are inclusive! CPPUNIT_ASSERT(tree.evalLeafBoundingBox(bbox)); CPPUNIT_ASSERT_EQUAL(openvdb::Coord(0, 8, 8), bbox.min()); CPPUNIT_ASSERT_EQUAL(openvdb::Coord(104-1, 40-1, 808-1), bbox.max()); // Test negative coordinates. tree.setValue(openvdb::Coord(-100, -35, -800), 2.5); CPPUNIT_ASSERT(tree.evalLeafBoundingBox(bbox)); CPPUNIT_ASSERT_EQUAL(openvdb::Coord(-104, -40, -800), bbox.min()); CPPUNIT_ASSERT_EQUAL(openvdb::Coord(104-1, 40-1, 808-1), bbox.max()); } void TestGridBbox::testGridBbox() { openvdb::FloatTree tree(/*fillValue=*/256.0f); openvdb::CoordBBox bbox; CPPUNIT_ASSERT(!tree.evalActiveVoxelBoundingBox(bbox)); // Add values to buffer zero. tree.setValue(openvdb::Coord( 1, 0, 0), 1.5); tree.setValue(openvdb::Coord( 0, 12, 8), 2.0); tree.setValue(openvdb::Coord( 1, 35, 800), 2.5); tree.setValue(openvdb::Coord(100, 0, 16), 3.0); tree.setValue(openvdb::Coord( 1, 0, 16), 3.5); // Coordinates in CoordBBox are inclusive! CPPUNIT_ASSERT(tree.evalActiveVoxelBoundingBox(bbox)); CPPUNIT_ASSERT_EQUAL(openvdb::Coord( 0, 0, 0), bbox.min()); CPPUNIT_ASSERT_EQUAL(openvdb::Coord(100, 35, 800), bbox.max()); // Test negative coordinates. tree.setValue(openvdb::Coord(-100, -35, -800), 2.5); CPPUNIT_ASSERT(tree.evalActiveVoxelBoundingBox(bbox)); CPPUNIT_ASSERT_EQUAL(openvdb::Coord(-100, -35, -800), bbox.min()); CPPUNIT_ASSERT_EQUAL(openvdb::Coord(100, 35, 800), bbox.max()); } <commit_msg>Attempt to verify that empty but not empty trees return false for their bounding boxes.<commit_after>// Copyright Contributors to the OpenVDB Project // SPDX-License-Identifier: MPL-2.0 #include <cppunit/extensions/HelperMacros.h> #include <openvdb/openvdb.h> #include <openvdb/tree/Tree.h> #include <openvdb/tree/LeafNode.h> #include <openvdb/Types.h> #include <openvdb/Exceptions.h> class TestGridBbox: public CppUnit::TestCase { public: CPPUNIT_TEST_SUITE(TestGridBbox); CPPUNIT_TEST(testLeafBbox); CPPUNIT_TEST(testGridBbox); CPPUNIT_TEST_SUITE_END(); void testLeafBbox(); void testGridBbox(); }; CPPUNIT_TEST_SUITE_REGISTRATION(TestGridBbox); //////////////////////////////////////// void TestGridBbox::testLeafBbox() { openvdb::FloatTree tree(/*fillValue=*/256.0f); openvdb::CoordBBox bbox; CPPUNIT_ASSERT(!tree.evalLeafBoundingBox(bbox)); // Add values to buffer zero. tree.setValue(openvdb::Coord( 0, 9, 9), 2.0); tree.setValue(openvdb::Coord(100, 35, 800), 2.5); // Coordinates in CoordBBox are inclusive! CPPUNIT_ASSERT(tree.evalLeafBoundingBox(bbox)); CPPUNIT_ASSERT_EQUAL(openvdb::Coord(0, 8, 8), bbox.min()); CPPUNIT_ASSERT_EQUAL(openvdb::Coord(104-1, 40-1, 808-1), bbox.max()); // Test negative coordinates. tree.setValue(openvdb::Coord(-100, -35, -800), 2.5); CPPUNIT_ASSERT(tree.evalLeafBoundingBox(bbox)); CPPUNIT_ASSERT_EQUAL(openvdb::Coord(-104, -40, -800), bbox.min()); CPPUNIT_ASSERT_EQUAL(openvdb::Coord(104-1, 40-1, 808-1), bbox.max()); // Clear the tree without trimming. tree.setValueOff(openvdb::Coord( 0, 9, 9)); tree.setValueOff(openvdb::Coord(100, 35, 800)); tree.setValueOff(openvdb::Coord(-100, -35, -800)); CPPUNIT_ASSERT(!tree.evalLeafBoundingBox(bbox)); } void TestGridBbox::testGridBbox() { openvdb::FloatTree tree(/*fillValue=*/256.0f); openvdb::CoordBBox bbox; CPPUNIT_ASSERT(!tree.evalActiveVoxelBoundingBox(bbox)); // Add values to buffer zero. tree.setValue(openvdb::Coord( 1, 0, 0), 1.5); tree.setValue(openvdb::Coord( 0, 12, 8), 2.0); tree.setValue(openvdb::Coord( 1, 35, 800), 2.5); tree.setValue(openvdb::Coord(100, 0, 16), 3.0); tree.setValue(openvdb::Coord( 1, 0, 16), 3.5); // Coordinates in CoordBBox are inclusive! CPPUNIT_ASSERT(tree.evalActiveVoxelBoundingBox(bbox)); CPPUNIT_ASSERT_EQUAL(openvdb::Coord( 0, 0, 0), bbox.min()); CPPUNIT_ASSERT_EQUAL(openvdb::Coord(100, 35, 800), bbox.max()); // Test negative coordinates. tree.setValue(openvdb::Coord(-100, -35, -800), 2.5); CPPUNIT_ASSERT(tree.evalActiveVoxelBoundingBox(bbox)); CPPUNIT_ASSERT_EQUAL(openvdb::Coord(-100, -35, -800), bbox.min()); CPPUNIT_ASSERT_EQUAL(openvdb::Coord(100, 35, 800), bbox.max()); // Clear the tree without trimming. tree.setValueOff(openvdb::Coord( 1, 0, 0)); tree.setValueOff(openvdb::Coord( 0, 12, 8)); tree.setValueOff(openvdb::Coord( 1, 35, 800)); tree.setValueOff(openvdb::Coord(100, 0, 16)); tree.setValueOff(openvdb::Coord( 1, 0, 16)); tree.setValueOff(openvdb::Coord(-100, -35, -800)); CPPUNIT_ASSERT(!tree.evalActiveVoxelBoundingBox(bbox)); } <|endoftext|>
<commit_before>// https://www.youtube.com/watch?v=uwv1uvi1OTU #include <cstdio> #include <type_traits> #include <vector> // https://en.wikipedia.org/wiki/Special_member_functions#Signatures struct S { S(int) { puts("S(int)"); } // Default constructor S() { puts("S()"); } // Copy constructor S(S const &) { puts("S(S const&"); } // Move constructor S(S &&) noexcept { puts("S(&&)"); } // Copy assignment operator S &operator=(S const &) { puts("operator=(S const&)"); return *this; } // Move assignment operator S &operator=(S &&) noexcept { puts("operator=(S &&)"); return *this; } // Destructor ~S() { puts("~S()"); } }; int main() { static_assert(std::is_nothrow_move_constructible_v<S>); std::vector<S> vec; // vec.push_back(S(3)); vec.emplace_back(3); }<commit_msg>(style) Struct 'S' has a constructor with 1 argument that is not explicit.<commit_after>// https://www.youtube.com/watch?v=uwv1uvi1OTU #include <cstdio> #include <type_traits> #include <vector> // https://en.wikipedia.org/wiki/Special_member_functions#Signatures struct S { explicit S(int) { puts("S(int)"); } // Default constructor S() { puts("S()"); } // Copy constructor S(S const &) { puts("S(S const&"); } // Move constructor S(S &&) noexcept { puts("S(&&)"); } // Copy assignment operator S &operator=(S const &) { puts("operator=(S const&)"); return *this; } // Move assignment operator S &operator=(S &&) noexcept { puts("operator=(S &&)"); return *this; } // Destructor ~S() { puts("~S()"); } }; int main() { static_assert(std::is_nothrow_move_constructible_v<S>); std::vector<S> vec; // vec.push_back(S(3)); vec.emplace_back(3); }<|endoftext|>
<commit_before>// // Copyright (C) 2013 // Alessio Sclocco <a.sclocco@vu.nl> // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. // #include <iostream> using std::cout; using std::cerr; using std::endl; using std::fixed; #include <string> using std::string; #include <vector> using std::vector; #include <exception> using std::exception; #include <fstream> using std::ofstream; #include <iomanip> using std::setprecision; #include <limits> using std::numeric_limits; #include <cmath> #include <ArgumentList.hpp> using isa::utils::ArgumentList; #include <Observation.hpp> using AstroData::Observation; #include <InitializeOpenCL.hpp> using isa::OpenCL::initializeOpenCL; #include <CLData.hpp> using isa::OpenCL::CLData; #include <utils.hpp> using isa::utils::toStringValue; #include <SNR.hpp> using PulsarSearch::SNR; #include <Timer.hpp> using isa::utils::Timer; typedef float dataType; const string typeName("float"); int main(int argc, char * argv[]) { unsigned int nrIterations = 0; unsigned int clPlatformID = 0; unsigned int clDeviceID = 0; unsigned int minThreads = 0; unsigned int maxThreadsPerBlock = 0; unsigned int maxRows = 0; Observation< dataType > observation("SNRTuning", typeName); CLData< dataType > * foldedData = new CLData< dataType >("FoldedData", true); CLData< dataType > * SNRData = new CLData< dataType >("SNRData", true); try { ArgumentList args(argc, argv); clPlatformID = args.getSwitchArgument< unsigned int >("-opencl_platform"); clDeviceID = args.getSwitchArgument< unsigned int >("-opencl_device"); nrIterations = args.getSwitchArgument< unsigned int >("-iterations"); observation.setPadding(args.getSwitchArgument< unsigned int >("-padding")); minThreads = args.getSwitchArgument< unsigned int >("-min_threads"); maxThreadsPerBlock = args.getSwitchArgument< unsigned int >("-max_threads"); maxRows = args.getSwitchArgument< unsigned int >("-max_rows"); observation.setNrDMs(args.getSwitchArgument< unsigned int >("-dms")); observation.setNrPeriods(args.getSwitchArgument< unsigned int >("-periods")); observation.setNrBins(args.getSwitchArgument< unsigned int >("-bins")); } catch ( EmptyCommandLine err ) { cerr << argv[0] << " -iterations ... -opencl_platform ... -opencl_device ... -padding ... -min_threads ... -max_threads ... -max_rows ... -dms ... -periods ... -bins ..." << endl; return 1; } catch ( exception & err ) { cerr << err.what() << endl; return 1; } cl::Context * clContext = new cl::Context(); vector< cl::Platform > * clPlatforms = new vector< cl::Platform >(); vector< cl::Device > * clDevices = new vector< cl::Device >(); vector< vector< cl::CommandQueue > > * clQueues = new vector< vector < cl::CommandQueue > >(); initializeOpenCL(clPlatformID, 1, clPlatforms, clContext, clDevices, clQueues); cout << fixed << endl; cout << "# nrDMs nrPeriods nrBins nrDMsPerBlock nrPeriodsPerBlock GFLOP/s err time err GB/s err " << endl << endl; // Allocate memory foldedData->allocateHostData(observation.getNrPaddedDMs() * observation.getNrBins() * observation.getNrPeriods()); SNRData->allocateHostData(observation.getNrPaddedDMs() * observation.getNrPeriods()); foldedData->setCLContext(clContext); foldedData->setCLQueue(&((clQueues->at(clDeviceID)).at(0))); SNRData->setCLContext(clContext); SNRData->setCLQueue(&((clQueues->at(clDeviceID)).at(0))); try { foldedData->allocateDeviceData(); foldedData->copyHostToDevice(); SNRData->allocateDeviceData(); } catch ( OpenCLError err ) { cerr << err.what() << endl; } // Find the parameters vector< unsigned int > DMsPerBlock; for ( unsigned int DMs = minThreads; DMs <= maxThreadsPerBlock; DMs += minThreads ) { if ( (observation.getNrPaddedDMs() % DMs) == 0 ) { DMsPerBlock.push_back(DMs); } } vector< unsigned int > periodsPerBlock; for ( unsigned int periods = 1; periods <= maxThreadsPerBlock; periods++ ) { if ( (observation.getNrPeriods() % periods) == 0 ) { periodsPerBlock.push_back(periods); } } for ( vector< unsigned int >::iterator DMs = DMsPerBlock.begin(); DMs != DMsPerBlock.end(); DMs++ ) { for ( vector< unsigned int >::iterator periods = periodsPerBlock.begin(); periods != periodsPerBlock.end(); periods++ ) { if ( (*DMs * *periods) > maxThreadsPerBlock ) { break; } double Acur[2] = {0.0, 0.0}; double Aold[2] = {0.0, 0.0}; double Vcur[2] = {0.0, 0.0}; double Vold[2] = {0.0, 0.0}; try { // Generate kernel SNR< dataType > clSNR("clSNR", typeName); clSNR.bindOpenCL(clContext, &(clDevices->at(clDeviceID)), &((clQueues->at(clDeviceID)).at(0))); clSNR.setObservation(&observation); clSNR.setNrDMsPerBlock(*DMs); clSNR.setNrPeriodsPerBlock(*periods); clSNR.setPulsarPipeline(); clSNR.generateCode(); // Warming up clSNR(foldedData, SNRData); (clSNR.getTimer()).reset(); // Measurements for ( unsigned int iteration = 0; iteration < nrIterations; iteration++ ) { clSNR(foldedData, SNRData); if ( iteration == 0 ) { Acur[0] = clSNR.getGFLOP() / clSNR.getTimer().getLastRunTime(); Acur[1] = clSNR.getGB() / clSNR.getTimer().getLastRunTime(); } else { Aold[0] = Acur[0]; Vold[0] = Vcur[0]; Acur[0] = Aold[0] + (((clSNR.getGFLOP() / clSNR.getTimer().getLastRunTime()) - Aold[0]) / (iteration + 1)); Vcur[0] = Vold[0] + (((clSNR.getGFLOP() / clSNR.getTimer().getLastRunTime()) - Aold[0]) * ((clSNR.getGFLOP() / clSNR.getTimer().getLastRunTime()) - Acur[0])); Aold[1] = Acur[1]; Vold[1] = Vcur[1]; Acur[1] = Aold[1] + (((clSNR.getGB() / clSNR.getTimer().getLastRunTime()) - Aold[1]) / (iteration + 1)); Vcur[1] = Vold[1] + (((clSNR.getGB() / clSNR.getTimer().getLastRunTime()) - Aold[1]) * ((clSNR.getGB() / clSNR.getTimer().getLastRunTime()) - Acur[1])); } } Vcur[0] = sqrt(Vcur[0] / nrIterations); Vcur[1] = sqrt(Vcur[1] / nrIterations); cout << nrDMs << " " << nrPeriods << " " << observation.getNrBins() << " " << *DMs << " " << *periods << " " << setprecision(3) << Acur[0] << " " << Vcur[0] << " " << setprecision(6) << clSNR.getTimer().getAverageTime() << " " << clSNR.getTimer().getStdDev() << " " << setprecision(3) << Acur[1] << " " << Vcur[1] << endl; } catch ( OpenCLError err ) { cerr << err.what() << endl; continue; } } } cout << endl; return 0; } <commit_msg>Fixed a small mistake.<commit_after>// // Copyright (C) 2013 // Alessio Sclocco <a.sclocco@vu.nl> // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. // #include <iostream> using std::cout; using std::cerr; using std::endl; using std::fixed; #include <string> using std::string; #include <vector> using std::vector; #include <exception> using std::exception; #include <fstream> using std::ofstream; #include <iomanip> using std::setprecision; #include <limits> using std::numeric_limits; #include <cmath> #include <ArgumentList.hpp> using isa::utils::ArgumentList; #include <Observation.hpp> using AstroData::Observation; #include <InitializeOpenCL.hpp> using isa::OpenCL::initializeOpenCL; #include <CLData.hpp> using isa::OpenCL::CLData; #include <utils.hpp> using isa::utils::toStringValue; #include <SNR.hpp> using PulsarSearch::SNR; #include <Timer.hpp> using isa::utils::Timer; typedef float dataType; const string typeName("float"); int main(int argc, char * argv[]) { unsigned int nrIterations = 0; unsigned int clPlatformID = 0; unsigned int clDeviceID = 0; unsigned int minThreads = 0; unsigned int maxThreadsPerBlock = 0; unsigned int maxRows = 0; Observation< dataType > observation("SNRTuning", typeName); CLData< dataType > * foldedData = new CLData< dataType >("FoldedData", true); CLData< dataType > * SNRData = new CLData< dataType >("SNRData", true); try { ArgumentList args(argc, argv); clPlatformID = args.getSwitchArgument< unsigned int >("-opencl_platform"); clDeviceID = args.getSwitchArgument< unsigned int >("-opencl_device"); nrIterations = args.getSwitchArgument< unsigned int >("-iterations"); observation.setPadding(args.getSwitchArgument< unsigned int >("-padding")); minThreads = args.getSwitchArgument< unsigned int >("-min_threads"); maxThreadsPerBlock = args.getSwitchArgument< unsigned int >("-max_threads"); maxRows = args.getSwitchArgument< unsigned int >("-max_rows"); observation.setNrDMs(args.getSwitchArgument< unsigned int >("-dms")); observation.setNrPeriods(args.getSwitchArgument< unsigned int >("-periods")); observation.setNrBins(args.getSwitchArgument< unsigned int >("-bins")); } catch ( EmptyCommandLine err ) { cerr << argv[0] << " -iterations ... -opencl_platform ... -opencl_device ... -padding ... -min_threads ... -max_threads ... -max_rows ... -dms ... -periods ... -bins ..." << endl; return 1; } catch ( exception & err ) { cerr << err.what() << endl; return 1; } cl::Context * clContext = new cl::Context(); vector< cl::Platform > * clPlatforms = new vector< cl::Platform >(); vector< cl::Device > * clDevices = new vector< cl::Device >(); vector< vector< cl::CommandQueue > > * clQueues = new vector< vector < cl::CommandQueue > >(); initializeOpenCL(clPlatformID, 1, clPlatforms, clContext, clDevices, clQueues); cout << fixed << endl; cout << "# nrDMs nrPeriods nrBins nrDMsPerBlock nrPeriodsPerBlock GFLOP/s err time err GB/s err " << endl << endl; // Allocate memory foldedData->allocateHostData(observation.getNrPaddedDMs() * observation.getNrBins() * observation.getNrPeriods()); SNRData->allocateHostData(observation.getNrPaddedDMs() * observation.getNrPeriods()); foldedData->setCLContext(clContext); foldedData->setCLQueue(&((clQueues->at(clDeviceID)).at(0))); SNRData->setCLContext(clContext); SNRData->setCLQueue(&((clQueues->at(clDeviceID)).at(0))); try { foldedData->allocateDeviceData(); foldedData->copyHostToDevice(); SNRData->allocateDeviceData(); } catch ( OpenCLError err ) { cerr << err.what() << endl; } // Find the parameters vector< unsigned int > DMsPerBlock; for ( unsigned int DMs = minThreads; DMs <= maxThreadsPerBlock; DMs += minThreads ) { if ( (observation.getNrPaddedDMs() % DMs) == 0 ) { DMsPerBlock.push_back(DMs); } } vector< unsigned int > periodsPerBlock; for ( unsigned int periods = 1; periods <= maxThreadsPerBlock; periods++ ) { if ( (observation.getNrPeriods() % periods) == 0 ) { periodsPerBlock.push_back(periods); } } for ( vector< unsigned int >::iterator DMs = DMsPerBlock.begin(); DMs != DMsPerBlock.end(); DMs++ ) { for ( vector< unsigned int >::iterator periods = periodsPerBlock.begin(); periods != periodsPerBlock.end(); periods++ ) { if ( (*DMs * *periods) > maxThreadsPerBlock ) { break; } double Acur[2] = {0.0, 0.0}; double Aold[2] = {0.0, 0.0}; double Vcur[2] = {0.0, 0.0}; double Vold[2] = {0.0, 0.0}; try { // Generate kernel SNR< dataType > clSNR("clSNR", typeName); clSNR.bindOpenCL(clContext, &(clDevices->at(clDeviceID)), &((clQueues->at(clDeviceID)).at(0))); clSNR.setObservation(&observation); clSNR.setNrDMsPerBlock(*DMs); clSNR.setNrPeriodsPerBlock(*periods); clSNR.setPulsarPipeline(); clSNR.generateCode(); // Warming up clSNR(foldedData, SNRData); (clSNR.getTimer()).reset(); // Measurements for ( unsigned int iteration = 0; iteration < nrIterations; iteration++ ) { clSNR(foldedData, SNRData); if ( iteration == 0 ) { Acur[0] = clSNR.getGFLOP() / clSNR.getTimer().getLastRunTime(); Acur[1] = clSNR.getGB() / clSNR.getTimer().getLastRunTime(); } else { Aold[0] = Acur[0]; Vold[0] = Vcur[0]; Acur[0] = Aold[0] + (((clSNR.getGFLOP() / clSNR.getTimer().getLastRunTime()) - Aold[0]) / (iteration + 1)); Vcur[0] = Vold[0] + (((clSNR.getGFLOP() / clSNR.getTimer().getLastRunTime()) - Aold[0]) * ((clSNR.getGFLOP() / clSNR.getTimer().getLastRunTime()) - Acur[0])); Aold[1] = Acur[1]; Vold[1] = Vcur[1]; Acur[1] = Aold[1] + (((clSNR.getGB() / clSNR.getTimer().getLastRunTime()) - Aold[1]) / (iteration + 1)); Vcur[1] = Vold[1] + (((clSNR.getGB() / clSNR.getTimer().getLastRunTime()) - Aold[1]) * ((clSNR.getGB() / clSNR.getTimer().getLastRunTime()) - Acur[1])); } } Vcur[0] = sqrt(Vcur[0] / nrIterations); Vcur[1] = sqrt(Vcur[1] / nrIterations); cout << observation.getNrDMs() << " " << observation.getNrPeriods() << " " << observation.getNrBins() << " " << *DMs << " " << *periods << " " << setprecision(3) << Acur[0] << " " << Vcur[0] << " " << setprecision(6) << clSNR.getTimer().getAverageTime() << " " << clSNR.getTimer().getStdDev() << " " << setprecision(3) << Acur[1] << " " << Vcur[1] << endl; } catch ( OpenCLError err ) { cerr << err.what() << endl; continue; } } } cout << endl; return 0; } <|endoftext|>
<commit_before>#include <stan/math/prim.hpp> #include <test/unit/math/prim/prob/vector_rng_test_helper.hpp> #include <test/unit/math/prim/prob/VectorIntRNGTestRig.hpp> #include <gtest/gtest.h> #include <boost/random/mersenne_twister.hpp> #include <boost/math/distributions.hpp> #include <limits> #include <vector> #include <string> class NegativeBinomialTestRig : public VectorIntRNGTestRig { public: NegativeBinomialTestRig() : VectorIntRNGTestRig(10000, 10, {0, 1, 2, 3, 4, 5, 6}, {0.1, 1.7, 3.99}, {1, 2, 3}, {-2.1, -0.5, 0.0}, {-3, -1, 0}, {0.1, 1.1, 4.99}, {1, 2, 3}, {-3.0, -2.0, 0.0}, {-3, -1, 0}) {} template <typename T1, typename T2, typename T3, typename T_rng> auto generate_samples(const T1& alpha, const T2& beta, const T3&, T_rng& rng) const { return stan::math::neg_binomial_rng(alpha, beta, rng); } template <typename T1> double pmf(int y, T1 alpha, double beta, double) const { return std::exp(stan::math::neg_binomial_lpmf(y, alpha, beta)); } }; TEST(ProbDistributionsNegativeBinomial, errorCheck) { check_dist_throws_all_types(NegativeBinomialTestRig()); } TEST(ProbDistributionsNegativeBinomial, distributionCheck) { check_counts_real_real(NegativeBinomialTestRig()); } TEST(ProbDistributionsNegBinomial, error_check) { boost::random::mt19937 rng; EXPECT_NO_THROW(stan::math::neg_binomial_rng(6, 2, rng)); EXPECT_NO_THROW(stan::math::neg_binomial_rng(0.5, 1, rng)); EXPECT_NO_THROW(stan::math::neg_binomial_rng(1e9, 1, rng)); EXPECT_THROW(stan::math::neg_binomial_rng(0, -2, rng), std::domain_error); EXPECT_THROW(stan::math::neg_binomial_rng(6, -2, rng), std::domain_error); EXPECT_THROW(stan::math::neg_binomial_rng(-6, -0.1, rng), std::domain_error); EXPECT_THROW( stan::math::neg_binomial_rng(stan::math::positive_infinity(), 2, rng), std::domain_error); EXPECT_THROW( stan::math::neg_binomial_rng(stan::math::positive_infinity(), 6, rng), std::domain_error); EXPECT_THROW( stan::math::neg_binomial_rng(2, stan::math::positive_infinity(), rng), std::domain_error); std::string error_msg; error_msg = "neg_binomial_rng: Random number that " "came from gamma distribution is"; try { stan::math::neg_binomial_rng(1e10, 1, rng); FAIL() << "neg_binomial_rng should have thrown" << std::endl; } catch (const std::exception& e) { if (std::string(e.what()).find(error_msg) == std::string::npos) FAIL() << "Error message is different than expected" << std::endl << "EXPECTED: " << error_msg << std::endl << "FOUND: " << e.what() << std::endl; SUCCEED(); } } void expected_bin_sizes(double* expect, const int K, const int N, const double alpha, const double beta) { double p = 0; for (int i = 0; i < K; i++) { expect[i] = N * std::exp(stan::math::neg_binomial_log(i, alpha, beta)); p += std::exp(stan::math::neg_binomial_log(i, alpha, beta)); } expect[K - 1] = N * (1.0 - p); } TEST(ProbDistributionsNegBinomial, chiSquareGoodnessFitTest) { boost::random::mt19937 rng; double p = 0.6; double alpha = 5; double beta = p / (1 - p); int N = 1000; int K = stan::math::round(2 * std::pow(N, (1 - p))); boost::math::chi_squared mydist(K - 1); int loc[K - 1]; for (int i = 1; i < K; i++) loc[i - 1] = i - 1; int count = 0; double bin[K]; double expect[K]; for (int i = 0; i < K; i++) bin[i] = 0; expected_bin_sizes(expect, K, N, alpha, beta); while (count < N) { int a = stan::math::neg_binomial_rng(alpha, beta, rng); int i = 0; while (i < K - 1 && a > loc[i]) ++i; ++bin[i]; count++; } double chi = 0; for (int j = 0; j < K; j++) chi += ((bin[j] - expect[j]) * (bin[j] - expect[j]) / expect[j]); EXPECT_LT(chi, boost::math::quantile(boost::math::complement(mydist, 1e-6))); } TEST(ProbDistributionsNegBinomial, chiSquareGoodnessFitTest2) { boost::random::mt19937 rng; double p = 0.8; double alpha = 2.4; double beta = p / (1 - p); int N = 1000; int K = stan::math::round(2 * std::pow(N, (1 - p))); boost::math::chi_squared mydist(K - 1); int loc[K - 1]; for (int i = 1; i < K; i++) loc[i - 1] = i - 1; int count = 0; double bin[K]; double expect[K]; for (int i = 0; i < K; i++) bin[i] = 0; expected_bin_sizes(expect, K, N, alpha, beta); while (count < N) { int a = stan::math::neg_binomial_rng(alpha, beta, rng); int i = 0; while (i < K - 1 && a > loc[i]) ++i; ++bin[i]; count++; } double chi = 0; for (int j = 0; j < K; j++) chi += ((bin[j] - expect[j]) * (bin[j] - expect[j]) / expect[j]); EXPECT_LT(chi, boost::math::quantile(boost::math::complement(mydist, 1e-6))); } TEST(ProbDistributionsNegBinomial, chiSquareGoodnessFitTest3) { boost::random::mt19937 rng; double p = 0.2; double alpha = 0.4; double beta = p / (1 - p); int N = 1000; int K = stan::math::round(2 * std::pow(N, (1 - p))); boost::math::chi_squared mydist(K - 1); int loc[K - 1]; for (int i = 1; i < K; i++) loc[i - 1] = i - 1; int count = 0; double bin[K]; double expect[K]; for (int i = 0; i < K; i++) bin[i] = 0; expected_bin_sizes(expect, K, N, alpha, beta); while (count < N) { int a = stan::math::neg_binomial_rng(alpha, beta, rng); int i = 0; while (i < K - 1 && a > loc[i]) ++i; ++bin[i]; count++; } double chi = 0; for (int j = 0; j < K; j++) chi += ((bin[j] - expect[j]) * (bin[j] - expect[j]) / expect[j]); EXPECT_LT(chi, boost::math::quantile(boost::math::complement(mydist, 1e-6))); } TEST(ProbDistributionsNegBinomial, extreme_values) { std::vector<int> n_to_test = {1, 5, 100, 12985, 1968422}; std::vector<double> beta_to_test = {1e-5, 0.1, 8, 713, 28311, 19850054}; double alpha_cutoff = stan::math::internal::neg_binomial_alpha_cutoff; for (double beta : beta_to_test) { for (int n : n_to_test) { // Test just before cutoff double logp = stan::math::neg_binomial_lpmf<false>(n, alpha_cutoff - 1e-8, beta); EXPECT_LT(logp, 0) << "n = " << n << ", alpha = " << (alpha_cutoff - 1e-8) << ", beta = " << beta; // Test across a range of alpha for (double alpha = 1e12; alpha < 1e22; alpha *= 10) { double logp = stan::math::neg_binomial_lpmf<false>(n, alpha, beta); EXPECT_LT(logp, 0) << "n = " << n << ", alpha = " << alpha << ", beta = " << beta; } } } } TEST(ProbDistributionsNegBinomial, poissonCutoff) { double alpha_cutoff = stan::math::internal::neg_binomial_alpha_cutoff; std::vector<double> beta_to_test = {2.345e-5, 0.2, 13, 150, 1621, 18432, 73582345}; std::vector<int> n_to_test = {0, 3, 16, 24, 181, 2132, 121358, 865422242}; for (double beta : beta_to_test) { for (int n : n_to_test) { double before_cutoff = stan::math::neg_binomial_lpmf(n, alpha_cutoff - 1e-8, beta); double after_cutoff = stan::math::neg_binomial_lpmf(n, alpha_cutoff + 1e-8, beta); double relative_error_at_cutoff = log(before_cutoff / after_cutoff); EXPECT_NEAR(relative_error_at_cutoff, 0, 1e-8) << "neg_binomial_lpmf changes too much around alpha cutoff for n = " << n << ", beta = " << beta << ", cutoff = " << alpha_cutoff << " value at cutoff - 1e-8: " << before_cutoff << ", value at cutoff + 1e-8: " << after_cutoff; } } } <commit_msg>Use long double in test to avoid precision loss (Issue #1763)<commit_after>#include <stan/math/prim.hpp> #include <test/unit/math/prim/prob/vector_rng_test_helper.hpp> #include <test/unit/math/prim/prob/VectorIntRNGTestRig.hpp> #include <gtest/gtest.h> #include <boost/random/mersenne_twister.hpp> #include <boost/math/distributions.hpp> #include <limits> #include <vector> #include <string> class NegativeBinomialTestRig : public VectorIntRNGTestRig { public: NegativeBinomialTestRig() : VectorIntRNGTestRig(10000, 10, {0, 1, 2, 3, 4, 5, 6}, {0.1, 1.7, 3.99}, {1, 2, 3}, {-2.1, -0.5, 0.0}, {-3, -1, 0}, {0.1, 1.1, 4.99}, {1, 2, 3}, {-3.0, -2.0, 0.0}, {-3, -1, 0}) {} template <typename T1, typename T2, typename T3, typename T_rng> auto generate_samples(const T1& alpha, const T2& beta, const T3&, T_rng& rng) const { return stan::math::neg_binomial_rng(alpha, beta, rng); } template <typename T1> double pmf(int y, T1 alpha, double beta, double) const { return std::exp(stan::math::neg_binomial_lpmf(y, alpha, beta)); } }; TEST(ProbDistributionsNegativeBinomial, errorCheck) { check_dist_throws_all_types(NegativeBinomialTestRig()); } TEST(ProbDistributionsNegativeBinomial, distributionCheck) { check_counts_real_real(NegativeBinomialTestRig()); } TEST(ProbDistributionsNegBinomial, error_check) { boost::random::mt19937 rng; EXPECT_NO_THROW(stan::math::neg_binomial_rng(6, 2, rng)); EXPECT_NO_THROW(stan::math::neg_binomial_rng(0.5, 1, rng)); EXPECT_NO_THROW(stan::math::neg_binomial_rng(1e9, 1, rng)); EXPECT_THROW(stan::math::neg_binomial_rng(0, -2, rng), std::domain_error); EXPECT_THROW(stan::math::neg_binomial_rng(6, -2, rng), std::domain_error); EXPECT_THROW(stan::math::neg_binomial_rng(-6, -0.1, rng), std::domain_error); EXPECT_THROW( stan::math::neg_binomial_rng(stan::math::positive_infinity(), 2, rng), std::domain_error); EXPECT_THROW( stan::math::neg_binomial_rng(stan::math::positive_infinity(), 6, rng), std::domain_error); EXPECT_THROW( stan::math::neg_binomial_rng(2, stan::math::positive_infinity(), rng), std::domain_error); std::string error_msg; error_msg = "neg_binomial_rng: Random number that " "came from gamma distribution is"; try { stan::math::neg_binomial_rng(1e10, 1, rng); FAIL() << "neg_binomial_rng should have thrown" << std::endl; } catch (const std::exception& e) { if (std::string(e.what()).find(error_msg) == std::string::npos) FAIL() << "Error message is different than expected" << std::endl << "EXPECTED: " << error_msg << std::endl << "FOUND: " << e.what() << std::endl; SUCCEED(); } } void expected_bin_sizes(double* expect, const int K, const int N, const double alpha, const double beta) { long double p = 0; for (int i = 0; i < K; i++) { expect[i] = N * std::exp(stan::math::neg_binomial_log(i, alpha, beta)); p += std::exp(stan::math::neg_binomial_log(i, alpha, beta)); } expect[K - 1] = N * static_cast<double>(1.0 - p); } TEST(ProbDistributionsNegBinomial, chiSquareGoodnessFitTest) { boost::random::mt19937 rng; double p = 0.6; double alpha = 5; double beta = p / (1 - p); int N = 1000; int K = stan::math::round(2 * std::pow(N, (1 - p))); boost::math::chi_squared mydist(K - 1); int loc[K - 1]; for (int i = 1; i < K; i++) loc[i - 1] = i - 1; int count = 0; double bin[K]; double expect[K]; for (int i = 0; i < K; i++) bin[i] = 0; expected_bin_sizes(expect, K, N, alpha, beta); while (count < N) { int a = stan::math::neg_binomial_rng(alpha, beta, rng); int i = 0; while (i < K - 1 && a > loc[i]) ++i; ++bin[i]; count++; } double chi = 0; for (int j = 0; j < K; j++) chi += ((bin[j] - expect[j]) * (bin[j] - expect[j]) / expect[j]); EXPECT_LT(chi, boost::math::quantile(boost::math::complement(mydist, 1e-6))); } TEST(ProbDistributionsNegBinomial, chiSquareGoodnessFitTest2) { boost::random::mt19937 rng; double p = 0.8; double alpha = 2.4; double beta = p / (1 - p); int N = 1000; int K = stan::math::round(2 * std::pow(N, (1 - p))); boost::math::chi_squared mydist(K - 1); int loc[K - 1]; for (int i = 1; i < K; i++) loc[i - 1] = i - 1; int count = 0; double bin[K]; double expect[K]; for (int i = 0; i < K; i++) bin[i] = 0; expected_bin_sizes(expect, K, N, alpha, beta); while (count < N) { int a = stan::math::neg_binomial_rng(alpha, beta, rng); int i = 0; while (i < K - 1 && a > loc[i]) ++i; ++bin[i]; count++; } double chi = 0; for (int j = 0; j < K; j++) chi += ((bin[j] - expect[j]) * (bin[j] - expect[j]) / expect[j]); EXPECT_LT(chi, boost::math::quantile(boost::math::complement(mydist, 1e-6))); } TEST(ProbDistributionsNegBinomial, chiSquareGoodnessFitTest3) { boost::random::mt19937 rng; double p = 0.2; double alpha = 0.4; double beta = p / (1 - p); int N = 1000; int K = stan::math::round(2 * std::pow(N, (1 - p))); boost::math::chi_squared mydist(K - 1); int loc[K - 1]; for (int i = 1; i < K; i++) loc[i - 1] = i - 1; int count = 0; double bin[K]; double expect[K]; for (int i = 0; i < K; i++) bin[i] = 0; expected_bin_sizes(expect, K, N, alpha, beta); while (count < N) { int a = stan::math::neg_binomial_rng(alpha, beta, rng); int i = 0; while (i < K - 1 && a > loc[i]) ++i; ++bin[i]; count++; } double chi = 0; for (int j = 0; j < K; j++) chi += ((bin[j] - expect[j]) * (bin[j] - expect[j]) / expect[j]); EXPECT_LT(chi, boost::math::quantile(boost::math::complement(mydist, 1e-6))); } TEST(ProbDistributionsNegBinomial, extreme_values) { std::vector<int> n_to_test = {1, 5, 100, 12985, 1968422}; std::vector<double> beta_to_test = {1e-5, 0.1, 8, 713, 28311, 19850054}; double alpha_cutoff = stan::math::internal::neg_binomial_alpha_cutoff; for (double beta : beta_to_test) { for (int n : n_to_test) { // Test just before cutoff double logp = stan::math::neg_binomial_lpmf<false>(n, alpha_cutoff - 1e-8, beta); EXPECT_LT(logp, 0) << "n = " << n << ", alpha = " << (alpha_cutoff - 1e-8) << ", beta = " << beta; // Test across a range of alpha for (double alpha = 1e12; alpha < 1e22; alpha *= 10) { double logp = stan::math::neg_binomial_lpmf<false>(n, alpha, beta); EXPECT_LT(logp, 0) << "n = " << n << ", alpha = " << alpha << ", beta = " << beta; } } } } TEST(ProbDistributionsNegBinomial, poissonCutoff) { double alpha_cutoff = stan::math::internal::neg_binomial_alpha_cutoff; std::vector<double> beta_to_test = {2.345e-5, 0.2, 13, 150, 1621, 18432, 73582345}; std::vector<int> n_to_test = {0, 3, 16, 24, 181, 2132, 121358, 865422242}; for (double beta : beta_to_test) { for (int n : n_to_test) { double before_cutoff = stan::math::neg_binomial_lpmf(n, alpha_cutoff - 1e-8, beta); double after_cutoff = stan::math::neg_binomial_lpmf(n, alpha_cutoff + 1e-8, beta); double relative_error_at_cutoff = log(before_cutoff / after_cutoff); EXPECT_NEAR(relative_error_at_cutoff, 0, 1e-8) << "neg_binomial_lpmf changes too much around alpha cutoff for n = " << n << ", beta = " << beta << ", cutoff = " << alpha_cutoff << " value at cutoff - 1e-8: " << before_cutoff << ", value at cutoff + 1e-8: " << after_cutoff; } } } <|endoftext|>
<commit_before>/** * @file * @copyright defined in eos/LICENSE.txt */ #pragma once #include <eosio/chain/action.hpp> #include <eosio/chain/action_receipt.hpp> #include <eosio/chain/block.hpp> namespace eosio { namespace chain { struct base_action_trace { base_action_trace( const action_receipt& r ):receipt(r){} base_action_trace(){} action_receipt receipt; action act; fc::microseconds elapsed; uint64_t cpu_usage = 0; string console; uint64_t total_cpu_usage = 0; /// total of inline_traces[x].cpu_usage + cpu_usage transaction_id_type trx_id; ///< the transaction that generated this action }; struct action_trace : public base_action_trace { using base_action_trace::base_action_trace; vector<action_trace> inline_traces; }; struct transaction_trace; using transaction_trace_ptr = std::shared_ptr<transaction_trace>; struct transaction_trace { transaction_id_type id; fc::optional<transaction_receipt_header> receipt; fc::microseconds elapsed; uint64_t net_usage = 0; bool scheduled = false; vector<action_trace> action_traces; ///< disposable transaction_trace_ptr failed_dtrx_trace; fc::optional<fc::exception> except; std::exception_ptr except_ptr; }; struct block_trace { fc::microseconds elapsed; uint64_t billed_cpu_usage_us; vector<transaction_trace_ptr> trx_traces; }; using block_trace_ptr = std::shared_ptr<block_trace>; } } /// namespace eosio::chain FC_REFLECT( eosio::chain::base_action_trace, (receipt)(act)(elapsed)(cpu_usage)(console)(total_cpu_usage)(trx_id) ) FC_REFLECT_DERIVED( eosio::chain::action_trace, (eosio::chain::base_action_trace), (inline_traces) ) FC_REFLECT( eosio::chain::transaction_trace, (id)(receipt)(elapsed)(net_usage)(scheduled) (action_traces)(failed_dtrx_trace)(except) ) FC_REFLECT( eosio::chain::block_trace, (elapsed)(billed_cpu_usage_us)(trx_traces) ) <commit_msg>Remove unused block_trace<commit_after>/** * @file * @copyright defined in eos/LICENSE.txt */ #pragma once #include <eosio/chain/action.hpp> #include <eosio/chain/action_receipt.hpp> #include <eosio/chain/block.hpp> namespace eosio { namespace chain { struct base_action_trace { base_action_trace( const action_receipt& r ):receipt(r){} base_action_trace(){} action_receipt receipt; action act; fc::microseconds elapsed; uint64_t cpu_usage = 0; string console; uint64_t total_cpu_usage = 0; /// total of inline_traces[x].cpu_usage + cpu_usage transaction_id_type trx_id; ///< the transaction that generated this action }; struct action_trace : public base_action_trace { using base_action_trace::base_action_trace; vector<action_trace> inline_traces; }; struct transaction_trace; using transaction_trace_ptr = std::shared_ptr<transaction_trace>; struct transaction_trace { transaction_id_type id; fc::optional<transaction_receipt_header> receipt; fc::microseconds elapsed; uint64_t net_usage = 0; bool scheduled = false; vector<action_trace> action_traces; ///< disposable transaction_trace_ptr failed_dtrx_trace; fc::optional<fc::exception> except; std::exception_ptr except_ptr; }; } } /// namespace eosio::chain FC_REFLECT( eosio::chain::base_action_trace, (receipt)(act)(elapsed)(cpu_usage)(console)(total_cpu_usage)(trx_id) ) FC_REFLECT_DERIVED( eosio::chain::action_trace, (eosio::chain::base_action_trace), (inline_traces) ) FC_REFLECT( eosio::chain::transaction_trace, (id)(receipt)(elapsed)(net_usage)(scheduled) (action_traces)(failed_dtrx_trace)(except) ) <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: pickerhistory.cxx,v $ * * $Revision: 1.5 $ * * last change: $Author: obo $ $Date: 2006-09-17 14:49:57 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_svtools.hxx" #ifndef SVTOOLS_PICKERHISTORY_HXX #include "pickerhistory.hxx" #endif #ifndef SVTOOLS_PICKERHISTORYACCESS_HXX #include "pickerhistoryaccess.hxx" #endif #ifndef _CPPUHELPER_WEAKREF_HXX_ #include <cppuhelper/weakref.hxx> #endif #include <vector> //......................................................................... namespace svt { //......................................................................... using namespace ::com::sun::star::uno; namespace { typedef ::com::sun::star::uno::WeakReference< XInterface > InterfaceAdapter; typedef ::std::vector< InterfaceAdapter > InterfaceArray; // ---------------------------------------------------------------- InterfaceArray& getFolderPickerHistory() { static InterfaceArray s_aHistory; return s_aHistory; } // ---------------------------------------------------------------- InterfaceArray& getFilePickerHistory() { static InterfaceArray s_aHistory; return s_aHistory; } // ---------------------------------------------------------------- void implPushBackPicker( InterfaceArray& _rHistory, const Reference< XInterface >& _rxPicker ) { if ( !_rxPicker.is() ) return; //============================================================= // first, check which of the objects we hold in s_aHistory can be removed { InterfaceArray aCleanedHistory; for ( InterfaceArray::const_iterator aLoop = _rHistory.begin(); aLoop != _rHistory.end(); ++aLoop ) { Reference< XInterface > xCurrent( aLoop->get() ); if ( xCurrent.is() ) { if ( aCleanedHistory.empty() ) // make some room, assume that all interfaces (from here on) are valie aCleanedHistory.reserve( _rHistory.size() - ( aLoop - _rHistory.begin() ) ); aCleanedHistory.push_back( InterfaceAdapter( xCurrent ) ); } } _rHistory.swap( aCleanedHistory ); } //============================================================= // then push_back the picker _rHistory.push_back( InterfaceAdapter( _rxPicker ) ); } //----------------------------------------------------------------- Reference< XInterface > implGetTopMostPicker( const InterfaceArray& _rHistory ) { Reference< XInterface > xTopMostAlive; //============================================================= // search the first picker which is still alive ... for ( InterfaceArray::const_reverse_iterator aLoop = _rHistory.rbegin(); ( aLoop != _rHistory.rend() ) && !xTopMostAlive.is(); ++aLoop ) { xTopMostAlive = aLoop->get(); } return xTopMostAlive; } } //--------------------------------------------------------------------- Reference< XInterface > GetTopMostFolderPicker( ) { return implGetTopMostPicker( getFolderPickerHistory() ); } //--------------------------------------------------------------------- Reference< XInterface > GetTopMostFilePicker( ) { return implGetTopMostPicker( getFilePickerHistory() ); } //--------------------------------------------------------------------- void addFolderPicker( const Reference< XInterface >& _rxPicker ) { implPushBackPicker( getFolderPickerHistory(), _rxPicker ); } //--------------------------------------------------------------------- void addFilePicker( const Reference< XInterface >& _rxPicker ) { implPushBackPicker( getFilePickerHistory(), _rxPicker ); } //......................................................................... } // namespace svt //......................................................................... <commit_msg>INTEGRATION: CWS changefileheader (1.5.450); FILE MERGED 2008/04/01 15:45:03 thb 1.5.450.3: #i85898# Stripping all external header guards 2008/04/01 12:43:33 thb 1.5.450.2: #i85898# Stripping all external header guards 2008/03/31 13:01:53 rt 1.5.450.1: #i87441# Change license header to LPGL v3.<commit_after>/************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2008 by Sun Microsystems, Inc. * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: pickerhistory.cxx,v $ * $Revision: 1.6 $ * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_svtools.hxx" #include "pickerhistory.hxx" #include "pickerhistoryaccess.hxx" #include <cppuhelper/weakref.hxx> #include <vector> //......................................................................... namespace svt { //......................................................................... using namespace ::com::sun::star::uno; namespace { typedef ::com::sun::star::uno::WeakReference< XInterface > InterfaceAdapter; typedef ::std::vector< InterfaceAdapter > InterfaceArray; // ---------------------------------------------------------------- InterfaceArray& getFolderPickerHistory() { static InterfaceArray s_aHistory; return s_aHistory; } // ---------------------------------------------------------------- InterfaceArray& getFilePickerHistory() { static InterfaceArray s_aHistory; return s_aHistory; } // ---------------------------------------------------------------- void implPushBackPicker( InterfaceArray& _rHistory, const Reference< XInterface >& _rxPicker ) { if ( !_rxPicker.is() ) return; //============================================================= // first, check which of the objects we hold in s_aHistory can be removed { InterfaceArray aCleanedHistory; for ( InterfaceArray::const_iterator aLoop = _rHistory.begin(); aLoop != _rHistory.end(); ++aLoop ) { Reference< XInterface > xCurrent( aLoop->get() ); if ( xCurrent.is() ) { if ( aCleanedHistory.empty() ) // make some room, assume that all interfaces (from here on) are valie aCleanedHistory.reserve( _rHistory.size() - ( aLoop - _rHistory.begin() ) ); aCleanedHistory.push_back( InterfaceAdapter( xCurrent ) ); } } _rHistory.swap( aCleanedHistory ); } //============================================================= // then push_back the picker _rHistory.push_back( InterfaceAdapter( _rxPicker ) ); } //----------------------------------------------------------------- Reference< XInterface > implGetTopMostPicker( const InterfaceArray& _rHistory ) { Reference< XInterface > xTopMostAlive; //============================================================= // search the first picker which is still alive ... for ( InterfaceArray::const_reverse_iterator aLoop = _rHistory.rbegin(); ( aLoop != _rHistory.rend() ) && !xTopMostAlive.is(); ++aLoop ) { xTopMostAlive = aLoop->get(); } return xTopMostAlive; } } //--------------------------------------------------------------------- Reference< XInterface > GetTopMostFolderPicker( ) { return implGetTopMostPicker( getFolderPickerHistory() ); } //--------------------------------------------------------------------- Reference< XInterface > GetTopMostFilePicker( ) { return implGetTopMostPicker( getFilePickerHistory() ); } //--------------------------------------------------------------------- void addFolderPicker( const Reference< XInterface >& _rxPicker ) { implPushBackPicker( getFolderPickerHistory(), _rxPicker ); } //--------------------------------------------------------------------- void addFilePicker( const Reference< XInterface >& _rxPicker ) { implPushBackPicker( getFilePickerHistory(), _rxPicker ); } //......................................................................... } // namespace svt //......................................................................... <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: dsntypes.cxx,v $ * * $Revision: 1.4 $ * * last change: $Author: oj $ $Date: 2000-11-21 15:02:06 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc.. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef _DBAUI_DSNTYPES_HXX_ #include "dsntypes.hxx" #endif #ifndef _DBU_RESOURCE_HRC_ #include "dbu_resource.hrc" #endif #ifndef _DBAUI_MODULE_DBU_HXX_ #include "moduledbu.hxx" #endif #ifndef _DBU_MISCRES_HRC_ #include "dbumiscres.hrc" #endif //......................................................................... namespace dbaui { //......................................................................... //========================================================================= //= ODsnTypeCollection //========================================================================= //------------------------------------------------------------------------- ODsnTypeCollection::ODsnTypeCollection() :Resource(ModuleRes(RSC_DATASOURCE_TYPES)) #ifdef DBG_UTIL ,m_nLivingIterators(0) #endif { String sConnectionTypes = String(ResId(STR_CONNTYPES)); String sConnectionTypeNames = String(ResId(STR_CONNUINAMES)); DBG_ASSERT(sConnectionTypes.GetTokenCount(';') == sConnectionTypeNames.GetTokenCount(';'), "ODsnTypeCollection::ODsnTypeCollection : invalid resources !"); String sCurrentType; for (sal_Int32 i=0; i<sConnectionTypeNames.GetTokenCount(); ++i) { m_aDsnTypesDisplayNames.push_back(sConnectionTypeNames.GetToken(i)); sCurrentType = sConnectionTypes.GetToken(i); m_aDsnPrefixes.push_back(sCurrentType); m_aDsnTypes.push_back(implDetermineType(sCurrentType)); } FreeResource(); } //------------------------------------------------------------------------- ODsnTypeCollection::~ODsnTypeCollection() { DBG_ASSERT(0 == m_nLivingIterators, "ODsnTypeCollection::~ODsnTypeCollection : there are still living iterator objects!"); } //------------------------------------------------------------------------- DATASOURCE_TYPE ODsnTypeCollection::getType(const String& _rDsn) { return implDetermineType(_rDsn); } //------------------------------------------------------------------------- String ODsnTypeCollection::getTypeDisplayName(DATASOURCE_TYPE _eType) { String sDisplayName; sal_Int32 nIndex = implDetermineTypeIndex(_eType); if ((nIndex >= 0) && (nIndex < m_aDsnTypesDisplayNames.size())) sDisplayName = m_aDsnTypesDisplayNames[nIndex]; return sDisplayName; } //------------------------------------------------------------------------- String ODsnTypeCollection::getDatasourcePrefix(DATASOURCE_TYPE _eType) { String sPrefix; sal_Int32 nIndex = implDetermineTypeIndex(_eType); if ((nIndex >= 0) && (nIndex < m_aDsnPrefixes.size())) sPrefix = m_aDsnPrefixes[nIndex]; return sPrefix; } //------------------------------------------------------------------------- String ODsnTypeCollection::cutPrefix(const String& _rDsn) { DATASOURCE_TYPE eType = getType(_rDsn); String sPrefix = getDatasourcePrefix(eType); return _rDsn.Copy(sPrefix.Len()); } //------------------------------------------------------------------------- String ODsnTypeCollection::getTypeDisplayName(const String& _rDsn) { return getTypeDisplayName(implDetermineType(_rDsn)); } //------------------------------------------------------------------------- sal_Bool ODsnTypeCollection::hasAuthentication(DATASOURCE_TYPE _eType) { switch (_eType) { case DST_ADABAS: case DST_JDBC: case DST_ODBC: return sal_True; break; case DST_DBASE: case DST_TEXT: default: return sal_False; } } //------------------------------------------------------------------------- DATASOURCE_TYPE ODsnTypeCollection::implDetermineType(const String& _rDsn) { sal_Int32 nSeparator = _rDsn.Search((sal_Unicode)':'); if (STRING_NOTFOUND == nSeparator) { // there should be at least one such separator DBG_ERROR("ODsnTypeCollection::implDetermineType : missing the colon !"); return DST_UNKNOWN; } // find first : if (_rDsn.EqualsIgnoreCaseAscii("jdbc", 0, nSeparator)) return DST_JDBC; // find second : nSeparator = _rDsn.Search((sal_Unicode)':', nSeparator + 1); if (STRING_NOTFOUND == nSeparator) { // at the moment only jdbc is allowed to have just one separator DBG_ERROR("ODsnTypeCollection::implDetermineType : missing the second colon !"); return DST_UNKNOWN; } if (_rDsn.EqualsIgnoreCaseAscii("sdbc:adabas", 0, nSeparator)) return DST_ADABAS; if (_rDsn.EqualsIgnoreCaseAscii("sdbc:odbc", 0, nSeparator)) return DST_ODBC; if (_rDsn.EqualsIgnoreCaseAscii("sdbc:dbase", 0, nSeparator)) return DST_DBASE; if (_rDsn.EqualsIgnoreCaseAscii("sdbc:flat:", 0, nSeparator)) return DST_TEXT; // find third : nSeparator = _rDsn.Search((sal_Unicode)':', nSeparator + 1); if (STRING_NOTFOUND == nSeparator) { DBG_ERROR("ODsnTypeCollection::implDetermineType : missing the third colon !"); return DST_UNKNOWN; } DBG_ERROR("ODsnTypeCollection::implDetermineType : unrecognized data source type !"); return DST_UNKNOWN; } //------------------------------------------------------------------------- sal_Int32 ODsnTypeCollection::implDetermineTypeIndex(DATASOURCE_TYPE _eType) { DBG_ASSERT( (m_aDsnTypesDisplayNames.size() == m_aDsnPrefixes.size()) && (m_aDsnTypesDisplayNames.size() == m_aDsnTypes.size()), "ODsnTypeCollection::implDetermineTypeIndex : inconsistent structures !"); // the type of the datasource described by the DSN string if (DST_UNKNOWN == _eType) { DBG_ERROR("ODsnTypeCollection::implDetermineTypeIndex : invalid argument !"); return -1; } // search this type in our arrays sal_Int32 nIndex = 0; ConstTypeVectorIterator aSearch = m_aDsnTypes.begin(); for (; aSearch != m_aDsnTypes.end(); ++nIndex, ++aSearch) if (*aSearch == _eType) return nIndex; DBG_ERROR("ODsnTypeCollection::implDetermineTypeIndex : recognized the DSN schema, but did not find the type!"); return -1; } //------------------------------------------------------------------------- sal_Int32 ODsnTypeCollection::implDetermineTypeIndex(const String& _rDsn) { return implDetermineTypeIndex(implDetermineType(_rDsn)); } //------------------------------------------------------------------------- ODsnTypeCollection::TypeIterator ODsnTypeCollection::begin() const { return TypeIterator(this, 0); } //------------------------------------------------------------------------- ODsnTypeCollection::TypeIterator ODsnTypeCollection::end() const { return TypeIterator(this, m_aDsnTypes.size()); } //========================================================================= //= ODsnTypeCollection::TypeIterator //========================================================================= //------------------------------------------------------------------------- ODsnTypeCollection::TypeIterator::TypeIterator(const ODsnTypeCollection* _pContainer, sal_Int32 _nInitialPos) :m_pContainer(_pContainer) ,m_nPosition(_nInitialPos) { DBG_ASSERT(m_pContainer, "ODsnTypeCollection::TypeIterator::TypeIterator : invalid container!"); #ifdef DBG_UTIL ++const_cast<ODsnTypeCollection*>(m_pContainer)->m_nLivingIterators; #endif } //------------------------------------------------------------------------- ODsnTypeCollection::TypeIterator::TypeIterator(const TypeIterator& _rSource) :m_pContainer(_rSource.m_pContainer) ,m_nPosition(_rSource.m_nPosition) { #ifdef DBG_UTIL ++const_cast<ODsnTypeCollection*>(m_pContainer)->m_nLivingIterators; #endif } //------------------------------------------------------------------------- ODsnTypeCollection::TypeIterator::~TypeIterator() { #ifdef DBG_UTIL --const_cast<ODsnTypeCollection*>(m_pContainer)->m_nLivingIterators; #endif } //------------------------------------------------------------------------- DATASOURCE_TYPE ODsnTypeCollection::TypeIterator::getType() const { DBG_ASSERT(m_nPosition < m_pContainer->m_aDsnTypes.size(), "ODsnTypeCollection::TypeIterator::getType : invalid position!"); return m_pContainer->m_aDsnTypes[m_nPosition]; } //------------------------------------------------------------------------- String ODsnTypeCollection::TypeIterator::getPrefix() const { DBG_ASSERT(m_nPosition < m_pContainer->m_aDsnPrefixes.size(), "ODsnTypeCollection::TypeIterator::getPrefix : invalid position!"); return m_pContainer->m_aDsnPrefixes[m_nPosition]; } //------------------------------------------------------------------------- String ODsnTypeCollection::TypeIterator::getDisplayName() const { DBG_ASSERT(m_nPosition < m_pContainer->m_aDsnTypesDisplayNames.size(), "ODsnTypeCollection::TypeIterator::getDisplayName : invalid position!"); return m_pContainer->m_aDsnTypesDisplayNames[m_nPosition]; } //------------------------------------------------------------------------- const ODsnTypeCollection::TypeIterator& ODsnTypeCollection::TypeIterator::operator++() { DBG_ASSERT(m_nPosition < m_pContainer->m_aDsnTypes.size(), "ODsnTypeCollection::TypeIterator::operator++ : invalid position!"); if (m_nPosition < m_pContainer->m_aDsnTypes.size()) ++m_nPosition; return *this; } //------------------------------------------------------------------------- const ODsnTypeCollection::TypeIterator& ODsnTypeCollection::TypeIterator::operator--() { DBG_ASSERT(m_nPosition >= 0, "ODsnTypeCollection::TypeIterator::operator-- : invalid position!"); if (m_nPosition >= 0) --m_nPosition; return *this; } //------------------------------------------------------------------------- bool operator==(const ODsnTypeCollection::TypeIterator& lhs, const ODsnTypeCollection::TypeIterator& rhs) { return (lhs.m_pContainer == rhs.m_pContainer) && (lhs.m_nPosition == rhs.m_nPosition); } //========================================================================= //= DbuTypeCollectionItem //========================================================================= TYPEINIT1(DbuTypeCollectionItem, SfxPoolItem); //------------------------------------------------------------------------- DbuTypeCollectionItem::DbuTypeCollectionItem(sal_Int16 _nWhich, ODsnTypeCollection* _pCollection) :SfxPoolItem(_nWhich) ,m_pCollection(_pCollection) { } //------------------------------------------------------------------------- DbuTypeCollectionItem::DbuTypeCollectionItem(const DbuTypeCollectionItem& _rSource) :SfxPoolItem(_rSource) ,m_pCollection(_rSource.getCollection()) { } //------------------------------------------------------------------------- int DbuTypeCollectionItem::operator==(const SfxPoolItem& _rItem) const { DbuTypeCollectionItem* pCompare = PTR_CAST(DbuTypeCollectionItem, &_rItem); return pCompare && (pCompare->getCollection() == getCollection()); } //------------------------------------------------------------------------- SfxPoolItem* DbuTypeCollectionItem::Clone(SfxItemPool* _pPool) const { return new DbuTypeCollectionItem(*this); } //......................................................................... } // namespace dbaui //......................................................................... /************************************************************************* * history: * $Log: not supported by cvs2svn $ * Revision 1.3 2000/10/30 07:59:18 fs * + hasAuthentification(DATASOURCE_TYPE) * * Revision 1.2 2000/10/20 07:01:39 fs * sdbc:text -> sdbc:flat:file * * Revision 1.1 2000/10/05 10:09:11 fs * initial checkin * * * Revision 1.0 26.09.00 08:05:35 fs ************************************************************************/ <commit_msg>#81485# +DST_ADO<commit_after>/************************************************************************* * * $RCSfile: dsntypes.cxx,v $ * * $Revision: 1.5 $ * * last change: $Author: fs $ $Date: 2001-01-04 11:20:23 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc.. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef _DBAUI_DSNTYPES_HXX_ #include "dsntypes.hxx" #endif #ifndef _DBU_RESOURCE_HRC_ #include "dbu_resource.hrc" #endif #ifndef _DBAUI_MODULE_DBU_HXX_ #include "moduledbu.hxx" #endif #ifndef _DBU_MISCRES_HRC_ #include "dbumiscres.hrc" #endif //......................................................................... namespace dbaui { //......................................................................... //========================================================================= //= ODsnTypeCollection //========================================================================= //------------------------------------------------------------------------- ODsnTypeCollection::ODsnTypeCollection() :Resource(ModuleRes(RSC_DATASOURCE_TYPES)) #ifdef DBG_UTIL ,m_nLivingIterators(0) #endif { String sConnectionTypes = String(ResId(STR_CONNTYPES)); String sConnectionTypeNames = String(ResId(STR_CONNUINAMES)); DBG_ASSERT(sConnectionTypes.GetTokenCount(';') == sConnectionTypeNames.GetTokenCount(';'), "ODsnTypeCollection::ODsnTypeCollection : invalid resources !"); String sCurrentType; for (sal_Int32 i=0; i<sConnectionTypeNames.GetTokenCount(); ++i) { m_aDsnTypesDisplayNames.push_back(sConnectionTypeNames.GetToken(i)); sCurrentType = sConnectionTypes.GetToken(i); m_aDsnPrefixes.push_back(sCurrentType); m_aDsnTypes.push_back(implDetermineType(sCurrentType)); } FreeResource(); } //------------------------------------------------------------------------- ODsnTypeCollection::~ODsnTypeCollection() { DBG_ASSERT(0 == m_nLivingIterators, "ODsnTypeCollection::~ODsnTypeCollection : there are still living iterator objects!"); } //------------------------------------------------------------------------- DATASOURCE_TYPE ODsnTypeCollection::getType(const String& _rDsn) { return implDetermineType(_rDsn); } //------------------------------------------------------------------------- String ODsnTypeCollection::getTypeDisplayName(DATASOURCE_TYPE _eType) { String sDisplayName; sal_Int32 nIndex = implDetermineTypeIndex(_eType); if ((nIndex >= 0) && (nIndex < m_aDsnTypesDisplayNames.size())) sDisplayName = m_aDsnTypesDisplayNames[nIndex]; return sDisplayName; } //------------------------------------------------------------------------- String ODsnTypeCollection::getDatasourcePrefix(DATASOURCE_TYPE _eType) { String sPrefix; sal_Int32 nIndex = implDetermineTypeIndex(_eType); if ((nIndex >= 0) && (nIndex < m_aDsnPrefixes.size())) sPrefix = m_aDsnPrefixes[nIndex]; return sPrefix; } //------------------------------------------------------------------------- String ODsnTypeCollection::cutPrefix(const String& _rDsn) { DATASOURCE_TYPE eType = getType(_rDsn); String sPrefix = getDatasourcePrefix(eType); return _rDsn.Copy(sPrefix.Len()); } //------------------------------------------------------------------------- String ODsnTypeCollection::getTypeDisplayName(const String& _rDsn) { return getTypeDisplayName(implDetermineType(_rDsn)); } //------------------------------------------------------------------------- sal_Bool ODsnTypeCollection::hasAuthentication(DATASOURCE_TYPE _eType) { switch (_eType) { case DST_ADABAS: case DST_JDBC: case DST_ODBC: case DST_ADO: return sal_True; break; case DST_DBASE: case DST_TEXT: default: return sal_False; } } //------------------------------------------------------------------------- DATASOURCE_TYPE ODsnTypeCollection::implDetermineType(const String& _rDsn) { sal_Int32 nSeparator = _rDsn.Search((sal_Unicode)':'); if (STRING_NOTFOUND == nSeparator) { // there should be at least one such separator DBG_ERROR("ODsnTypeCollection::implDetermineType : missing the colon !"); return DST_UNKNOWN; } // find first : if (_rDsn.EqualsIgnoreCaseAscii("jdbc", 0, nSeparator)) return DST_JDBC; // find second : nSeparator = _rDsn.Search((sal_Unicode)':', nSeparator + 1); if (STRING_NOTFOUND == nSeparator) { // at the moment only jdbc is allowed to have just one separator DBG_ERROR("ODsnTypeCollection::implDetermineType : missing the second colon !"); return DST_UNKNOWN; } if (_rDsn.EqualsIgnoreCaseAscii("sdbc:adabas", 0, nSeparator)) return DST_ADABAS; if (_rDsn.EqualsIgnoreCaseAscii("sdbc:odbc", 0, nSeparator)) return DST_ODBC; if (_rDsn.EqualsIgnoreCaseAscii("sdbc:dbase", 0, nSeparator)) return DST_DBASE; if (_rDsn.EqualsIgnoreCaseAscii("sdbc:ado:", 0, nSeparator)) return DST_ADO; if (_rDsn.EqualsIgnoreCaseAscii("sdbc:flat:", 0, nSeparator)) return DST_TEXT; // find third : nSeparator = _rDsn.Search((sal_Unicode)':', nSeparator + 1); if (STRING_NOTFOUND == nSeparator) { DBG_ERROR("ODsnTypeCollection::implDetermineType : missing the third colon !"); return DST_UNKNOWN; } DBG_ERROR("ODsnTypeCollection::implDetermineType : unrecognized data source type !"); return DST_UNKNOWN; } //------------------------------------------------------------------------- sal_Int32 ODsnTypeCollection::implDetermineTypeIndex(DATASOURCE_TYPE _eType) { DBG_ASSERT( (m_aDsnTypesDisplayNames.size() == m_aDsnPrefixes.size()) && (m_aDsnTypesDisplayNames.size() == m_aDsnTypes.size()), "ODsnTypeCollection::implDetermineTypeIndex : inconsistent structures !"); // the type of the datasource described by the DSN string if (DST_UNKNOWN == _eType) { DBG_ERROR("ODsnTypeCollection::implDetermineTypeIndex : invalid argument !"); return -1; } // search this type in our arrays sal_Int32 nIndex = 0; ConstTypeVectorIterator aSearch = m_aDsnTypes.begin(); for (; aSearch != m_aDsnTypes.end(); ++nIndex, ++aSearch) if (*aSearch == _eType) return nIndex; DBG_ERROR("ODsnTypeCollection::implDetermineTypeIndex : recognized the DSN schema, but did not find the type!"); return -1; } //------------------------------------------------------------------------- sal_Int32 ODsnTypeCollection::implDetermineTypeIndex(const String& _rDsn) { return implDetermineTypeIndex(implDetermineType(_rDsn)); } //------------------------------------------------------------------------- ODsnTypeCollection::TypeIterator ODsnTypeCollection::begin() const { return TypeIterator(this, 0); } //------------------------------------------------------------------------- ODsnTypeCollection::TypeIterator ODsnTypeCollection::end() const { return TypeIterator(this, m_aDsnTypes.size()); } //========================================================================= //= ODsnTypeCollection::TypeIterator //========================================================================= //------------------------------------------------------------------------- ODsnTypeCollection::TypeIterator::TypeIterator(const ODsnTypeCollection* _pContainer, sal_Int32 _nInitialPos) :m_pContainer(_pContainer) ,m_nPosition(_nInitialPos) { DBG_ASSERT(m_pContainer, "ODsnTypeCollection::TypeIterator::TypeIterator : invalid container!"); #ifdef DBG_UTIL ++const_cast<ODsnTypeCollection*>(m_pContainer)->m_nLivingIterators; #endif } //------------------------------------------------------------------------- ODsnTypeCollection::TypeIterator::TypeIterator(const TypeIterator& _rSource) :m_pContainer(_rSource.m_pContainer) ,m_nPosition(_rSource.m_nPosition) { #ifdef DBG_UTIL ++const_cast<ODsnTypeCollection*>(m_pContainer)->m_nLivingIterators; #endif } //------------------------------------------------------------------------- ODsnTypeCollection::TypeIterator::~TypeIterator() { #ifdef DBG_UTIL --const_cast<ODsnTypeCollection*>(m_pContainer)->m_nLivingIterators; #endif } //------------------------------------------------------------------------- DATASOURCE_TYPE ODsnTypeCollection::TypeIterator::getType() const { DBG_ASSERT(m_nPosition < m_pContainer->m_aDsnTypes.size(), "ODsnTypeCollection::TypeIterator::getType : invalid position!"); return m_pContainer->m_aDsnTypes[m_nPosition]; } //------------------------------------------------------------------------- String ODsnTypeCollection::TypeIterator::getPrefix() const { DBG_ASSERT(m_nPosition < m_pContainer->m_aDsnPrefixes.size(), "ODsnTypeCollection::TypeIterator::getPrefix : invalid position!"); return m_pContainer->m_aDsnPrefixes[m_nPosition]; } //------------------------------------------------------------------------- String ODsnTypeCollection::TypeIterator::getDisplayName() const { DBG_ASSERT(m_nPosition < m_pContainer->m_aDsnTypesDisplayNames.size(), "ODsnTypeCollection::TypeIterator::getDisplayName : invalid position!"); return m_pContainer->m_aDsnTypesDisplayNames[m_nPosition]; } //------------------------------------------------------------------------- const ODsnTypeCollection::TypeIterator& ODsnTypeCollection::TypeIterator::operator++() { DBG_ASSERT(m_nPosition < m_pContainer->m_aDsnTypes.size(), "ODsnTypeCollection::TypeIterator::operator++ : invalid position!"); if (m_nPosition < m_pContainer->m_aDsnTypes.size()) ++m_nPosition; return *this; } //------------------------------------------------------------------------- const ODsnTypeCollection::TypeIterator& ODsnTypeCollection::TypeIterator::operator--() { DBG_ASSERT(m_nPosition >= 0, "ODsnTypeCollection::TypeIterator::operator-- : invalid position!"); if (m_nPosition >= 0) --m_nPosition; return *this; } //------------------------------------------------------------------------- bool operator==(const ODsnTypeCollection::TypeIterator& lhs, const ODsnTypeCollection::TypeIterator& rhs) { return (lhs.m_pContainer == rhs.m_pContainer) && (lhs.m_nPosition == rhs.m_nPosition); } //========================================================================= //= DbuTypeCollectionItem //========================================================================= TYPEINIT1(DbuTypeCollectionItem, SfxPoolItem); //------------------------------------------------------------------------- DbuTypeCollectionItem::DbuTypeCollectionItem(sal_Int16 _nWhich, ODsnTypeCollection* _pCollection) :SfxPoolItem(_nWhich) ,m_pCollection(_pCollection) { } //------------------------------------------------------------------------- DbuTypeCollectionItem::DbuTypeCollectionItem(const DbuTypeCollectionItem& _rSource) :SfxPoolItem(_rSource) ,m_pCollection(_rSource.getCollection()) { } //------------------------------------------------------------------------- int DbuTypeCollectionItem::operator==(const SfxPoolItem& _rItem) const { DbuTypeCollectionItem* pCompare = PTR_CAST(DbuTypeCollectionItem, &_rItem); return pCompare && (pCompare->getCollection() == getCollection()); } //------------------------------------------------------------------------- SfxPoolItem* DbuTypeCollectionItem::Clone(SfxItemPool* _pPool) const { return new DbuTypeCollectionItem(*this); } //......................................................................... } // namespace dbaui //......................................................................... /************************************************************************* * history: * $Log: not supported by cvs2svn $ * Revision 1.4 2000/11/21 15:02:06 oj * #80549# wrong dsn for text * * Revision 1.3 2000/10/30 07:59:18 fs * + hasAuthentification(DATASOURCE_TYPE) * * Revision 1.2 2000/10/20 07:01:39 fs * sdbc:text -> sdbc:flat:file * * Revision 1.1 2000/10/05 10:09:11 fs * initial checkin * * * Revision 1.0 26.09.00 08:05:35 fs ************************************************************************/ <|endoftext|>
<commit_before>// This file is part of the dune-hdd project: // http://users.dune-project.org/projects/dune-hdd // Copyright holders: Felix Schindler // License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause) #ifndef DUNE_STUFF_TEST_MAIN_CATCH_EXCEPTIONS # define DUNE_STUFF_TEST_MAIN_CATCH_EXCEPTIONS #endif #ifndef DUNE_STUFF_TEST_MAIN_ENABLE_INFO_LOGGING # define DUNE_STUFF_TEST_MAIN_ENABLE_INFO_LOGGING #endif #define DUNE_HDD_LINEARELLIPTIC_TESTCASES_BASE_DISABLE_WARNING // This one has to come first (includes the config.h)! #include <dune/stuff/test/main.hxx> #include <vector> #include <string> #include <map> #if HAVE_ALUGRID #include <dune/grid/alugrid.hh> #include <dune/pymor/parameters/base.hh> #include <dune/hdd/playground/linearelliptic/testcases/OS2014.hh> #include "linearelliptic-block-swipdg.hh" #include "linearelliptic-block-swipdg-expectations.hh" using namespace Dune; using namespace HDD; typedef ALUGrid< 2, 2, simplex, conforming > GridType; typedef LinearElliptic::TestCases::OS2014::ParametricBlockConvergence< GridType > SmoothTestCaseType; typedef LinearElliptic::Tests::BlockSWIPDGStudy< SmoothTestCaseType > SmoothStudyType; template< class TestCaseType > void print_parameter_information(const TestCaseType& test_case) { const auto& parameters = test_case.parameters(); const auto& problem = test_case.problem(); for (auto parameter : parameters) EXPECT_EQ(parameter.second.type(), problem.parameter_type()) << " id: " << parameter.first << ", parameter: " << parameter.second; const auto& diffusion_factor = *problem.diffusion_factor(); const auto& diffusion_tensor = *problem.diffusion_tensor(); const auto& force = *problem.force(); const auto& dirichlet = *problem.dirichlet(); const auto& neumann = *problem.neumann(); EXPECT_TRUE(diffusion_factor.parametric()); EXPECT_FALSE(diffusion_tensor.parametric()); EXPECT_FALSE(force.parametric()); EXPECT_FALSE(dirichlet.parametric()); EXPECT_FALSE(neumann.parametric()); DSC_LOG_INFO << "| mu = " << parameters.at("mu") << "\n" << "| mu_bar = " << parameters.at("mu_bar") << "\n" << "| mu_hat = " << parameters.at("mu_hat") << "\n" << "| mu_minimizing = " << parameters.at("mu_minimizing") << "\n"; const double alpha = diffusion_factor.alpha(parameters.at("mu"), parameters.at("mu_hat")); const double gamma = diffusion_factor.gamma(parameters.at("mu"), parameters.at("mu_hat")); DSC_LOG_INFO << "| alpha(mu, mu_hat)^-1/2 = " << std::setprecision(2) << std::scientific << 1.0/std::sqrt(alpha) << "\n" << "| gamma_tilde(mu, mu_hat)^2 = " << std::setprecision(2) << std::scientific << std::max(std::sqrt(gamma), 1.0/std::sqrt(alpha)) << "\n" << "+==================================================================+\n"; } // ... print_parameter_information(...) template< class TestCaseType, class StudyType > void run_eoc_study(const std::string partitioning, const std::vector< std::string >& only_these_norms, const std::map< std::string, Pymor::Parameter >& parameters, const bool print_header, const std::string visualization) { const TestCaseType test_case(parameters, partitioning); if (print_header) test_case.print_header(DSC_LOG_INFO); print_parameter_information(test_case); StudyType study(test_case, only_these_norms, {}, visualization); Stuff::Test::check_eoc_study_for_success(study, study.run_eoc(DSC_LOG_INFO)); } // ... parametric_block_convergence_study(...) TEST(OS2014_parametric_convergence_study, eta_DF_comparison) { const std::string partitioning = "[4 4 1]"; const std::vector< std::string > only_these_norms = {"eta_DF_OS2014", "eta_DF_OS2014_*", "eta_OS2014", "eta_OS2014_*", "eff_OS2014_mu", "eff_OS2014_*_mu"}; const std::string visualization_prefix = "parametric_block_convergence_study_eta_DF_comparison"; bool print_header = true; for (auto mu_hat_value : {0.1, 0.5, 1.0}) { const auto mu_hat = Pymor::Parameter("mu", mu_hat_value); for (auto mu_value : {0.1, 0.3, 0.5, 0.75, 1.0}) { const auto mu = Pymor::Parameter("mu", mu_value); const auto mu_bar = mu; run_eoc_study< SmoothTestCaseType, SmoothStudyType >(partitioning, only_these_norms, {{"mu_hat", mu_hat}, {"mu_bar", mu_bar}, {"mu", mu}, {"mu_minimizing", Pymor::Parameter("mu", 0.1)}}, print_header, visualization_prefix); if (print_header) print_header = false; } } } // TEST(OS2014_parametric_convergence_study, eta_DF_comparison) extern template class Dune::HDD::LinearElliptic::Tests::BlockSWIPDGStudyExpectations< SmoothTestCaseType >; #else // HAVE_ALUGRID TEST(DISABLED_OS2014_parametric_convergence_study, eta_DF_comparison) {} #endif // HAVE_ALUGRID <commit_msg>[test.OS2014_parametric_convergence_study] disable visualization<commit_after>// This file is part of the dune-hdd project: // http://users.dune-project.org/projects/dune-hdd // Copyright holders: Felix Schindler // License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause) #ifndef DUNE_STUFF_TEST_MAIN_CATCH_EXCEPTIONS # define DUNE_STUFF_TEST_MAIN_CATCH_EXCEPTIONS #endif #ifndef DUNE_STUFF_TEST_MAIN_ENABLE_INFO_LOGGING # define DUNE_STUFF_TEST_MAIN_ENABLE_INFO_LOGGING #endif #define DUNE_HDD_LINEARELLIPTIC_TESTCASES_BASE_DISABLE_WARNING // This one has to come first (includes the config.h)! #include <dune/stuff/test/main.hxx> #include <vector> #include <string> #include <map> #if HAVE_ALUGRID #include <dune/grid/alugrid.hh> #include <dune/pymor/parameters/base.hh> #include <dune/hdd/playground/linearelliptic/testcases/OS2014.hh> #include "linearelliptic-block-swipdg.hh" #include "linearelliptic-block-swipdg-expectations.hh" using namespace Dune; using namespace HDD; typedef ALUGrid< 2, 2, simplex, conforming > GridType; typedef LinearElliptic::TestCases::OS2014::ParametricBlockConvergence< GridType > SmoothTestCaseType; typedef LinearElliptic::Tests::BlockSWIPDGStudy< SmoothTestCaseType > SmoothStudyType; template< class TestCaseType > void print_parameter_information(const TestCaseType& test_case) { const auto& parameters = test_case.parameters(); const auto& problem = test_case.problem(); for (auto parameter : parameters) EXPECT_EQ(parameter.second.type(), problem.parameter_type()) << " id: " << parameter.first << ", parameter: " << parameter.second; const auto& diffusion_factor = *problem.diffusion_factor(); const auto& diffusion_tensor = *problem.diffusion_tensor(); const auto& force = *problem.force(); const auto& dirichlet = *problem.dirichlet(); const auto& neumann = *problem.neumann(); EXPECT_TRUE(diffusion_factor.parametric()); EXPECT_FALSE(diffusion_tensor.parametric()); EXPECT_FALSE(force.parametric()); EXPECT_FALSE(dirichlet.parametric()); EXPECT_FALSE(neumann.parametric()); DSC_LOG_INFO << "| mu = " << parameters.at("mu") << "\n" << "| mu_bar = " << parameters.at("mu_bar") << "\n" << "| mu_hat = " << parameters.at("mu_hat") << "\n" << "| mu_minimizing = " << parameters.at("mu_minimizing") << "\n"; const double alpha = diffusion_factor.alpha(parameters.at("mu"), parameters.at("mu_hat")); const double gamma = diffusion_factor.gamma(parameters.at("mu"), parameters.at("mu_hat")); DSC_LOG_INFO << "| alpha(mu, mu_hat)^-1/2 = " << std::setprecision(2) << std::scientific << 1.0/std::sqrt(alpha) << "\n" << "| gamma_tilde(mu, mu_hat)^2 = " << std::setprecision(2) << std::scientific << std::max(std::sqrt(gamma), 1.0/std::sqrt(alpha)) << "\n" << "+==================================================================+\n"; } // ... print_parameter_information(...) template< class TestCaseType, class StudyType > void run_eoc_study(const std::string partitioning, const std::vector< std::string >& only_these_norms, const std::map< std::string, Pymor::Parameter >& parameters, const bool print_header, const std::string visualization) { const TestCaseType test_case(parameters, partitioning); if (print_header) test_case.print_header(DSC_LOG_INFO); print_parameter_information(test_case); StudyType study(test_case, only_these_norms, {}, visualization); Stuff::Test::check_eoc_study_for_success(study, study.run_eoc(DSC_LOG_INFO)); } // ... parametric_block_convergence_study(...) TEST(OS2014_parametric_convergence_study, eta_DF_comparison) { const std::string partitioning = "[4 4 1]"; const std::vector< std::string > only_these_norms = {"eta_DF_OS2014", "eta_DF_OS2014_*", "eta_OS2014", "eta_OS2014_*", "eff_OS2014_mu", "eff_OS2014_*_mu"}; const std::string visualization_prefix = ""; //"parametric_block_convergence_study_eta_DF_comparison"; bool print_header = true; for (auto mu_hat_value : {0.1, 0.5, 1.0}) { const auto mu_hat = Pymor::Parameter("mu", mu_hat_value); for (auto mu_value : {0.1, 0.3, 0.5, 0.75, 1.0}) { const auto mu = Pymor::Parameter("mu", mu_value); const auto mu_bar = mu; run_eoc_study< SmoothTestCaseType, SmoothStudyType >(partitioning, only_these_norms, {{"mu_hat", mu_hat}, {"mu_bar", mu_bar}, {"mu", mu}, {"mu_minimizing", Pymor::Parameter("mu", 0.1)}}, print_header, visualization_prefix); if (print_header) print_header = false; } } } // TEST(OS2014_parametric_convergence_study, eta_DF_comparison) extern template class Dune::HDD::LinearElliptic::Tests::BlockSWIPDGStudyExpectations< SmoothTestCaseType >; #else // HAVE_ALUGRID TEST(DISABLED_OS2014_parametric_convergence_study, eta_DF_comparison) {} #endif // HAVE_ALUGRID <|endoftext|>
<commit_before>// Check that with empty ASAN_OPTIONS, ASan reports on Linux don't crash // the process (abort_on_error=0). See also Darwin/abort_on_error.cc. // RUN: %clangxx_asan %s -o %t // Intentionally don't inherit the default ASAN_OPTIONS. // RUN: ASAN_OPTIONS="" not run %t 2>&1 | FileCheck %s // When we use lit's default ASAN_OPTIONS, we shouldn't crash either. On Linux // lit doesn't set ASAN_OPTIONS anyway. // RUN: not %run %t 2>&1 | FileCheck %s #include <stdlib.h> int main() { char *x = (char*)malloc(10 * sizeof(char)); free(x); return x[5]; // CHECK: {{.*ERROR: AddressSanitizer: heap-use-after-free on address}} } <commit_msg>Fix typo from r243418. Should fix the failing `abort_on_error.cc` test. See http://reviews.llvm.org/D7203<commit_after>// Check that with empty ASAN_OPTIONS, ASan reports on Linux don't crash // the process (abort_on_error=0). See also Darwin/abort_on_error.cc. // RUN: %clangxx_asan %s -o %t // Intentionally don't inherit the default ASAN_OPTIONS. // RUN: ASAN_OPTIONS="" not %run %t 2>&1 | FileCheck %s // When we use lit's default ASAN_OPTIONS, we shouldn't crash either. On Linux // lit doesn't set ASAN_OPTIONS anyway. // RUN: not %run %t 2>&1 | FileCheck %s #include <stdlib.h> int main() { char *x = (char*)malloc(10 * sizeof(char)); free(x); return x[5]; // CHECK: {{.*ERROR: AddressSanitizer: heap-use-after-free on address}} } <|endoftext|>
<commit_before>#include <stdlib.h> #include <stdio.h> #include <vector> #include <string> #include <sstream> #include <iostream> #include <stdexcept> #include <Eigen/Geometry> #include <ros/ros.h> #include <moveit_msgs/GetPlanningScene.h> #include <urdf_model/model.h> #include <moveit/robot_model_loader/robot_model_loader.h> #include <moveit/planning_scene/planning_scene.h> #include "trajectory_verifier/CheckTrajectoryValidity.h" #include "trajectory_verifier/BatchCheckTrajectoryValidity.h" class TrajectoryVerifier { protected: std::shared_ptr<planning_scene::PlanningScene> planning_scene_ptr_; ros::NodeHandle nh_; ros::ServiceClient planning_scene_client_; ros::ServiceServer trajectory_validity_server_; ros::ServiceServer batch_trajectory_validity_server_; public: TrajectoryVerifier(ros::NodeHandle& nh, const std::string& planning_scene_service, const std::string& trajectory_validity_service, const std::string& batch_trajectory_validity_service) : nh_(nh) { robot_model_loader::RobotModelLoader loader; planning_scene_ptr_.reset(); planning_scene_ptr_ = std::shared_ptr<planning_scene::PlanningScene>(new planning_scene::PlanningScene(loader.getModel())); planning_scene_client_ = nh.serviceClient<moveit_msgs::GetPlanningScene>(planning_scene_service); trajectory_validity_server_ = nh.advertiseService(trajectory_validity_service, &TrajectoryVerifier::CheckTrajectoryValidityCB, this); batch_trajectory_validity_server_ = nh.advertiseService(batch_trajectory_validity_service, &TrajectoryVerifier::BatchCheckTrajectoryValidityCB, this); } void Loop() { ros::Rate spin_rate(10.0); while (ros::ok()) { ros::spinOnce(); spin_rate.sleep(); } } bool UpdateInternalPlanningScene() { try { // Update the planning scene moveit_msgs::GetPlanningSceneRequest ps_req; ps_req.components.components = moveit_msgs::PlanningSceneComponents::WORLD_OBJECT_NAMES | moveit_msgs::PlanningSceneComponents::WORLD_OBJECT_GEOMETRY | moveit_msgs::PlanningSceneComponents::OCTOMAP | moveit_msgs::PlanningSceneComponents::ROBOT_STATE_ATTACHED_OBJECTS | moveit_msgs::PlanningSceneComponents::ALLOWED_COLLISION_MATRIX; moveit_msgs::GetPlanningSceneResponse ps_res; planning_scene_client_.call(ps_req, ps_res); moveit_msgs::PlanningScene& planning_scene_state = ps_res.scene; planning_scene_ptr_->usePlanningSceneMsg(planning_scene_state); return true; } catch (...) { ROS_ERROR("Failed updating planning scene"); return false; } } trajectory_verifier::CheckTrajectoryValidityResult CheckTrajectoryValidity(const trajectory_verifier::CheckTrajectoryValidityQuery& query) { trajectory_verifier::CheckTrajectoryValidityResult result; result.status = trajectory_verifier::CheckTrajectoryValidityResult::SUCCESS; // Safety check the trajectory first if (query.initial_state.name.size() != query.initial_state.position.size()) { ROS_ERROR("Initial state is invalid"); result.status |= trajectory_verifier::CheckTrajectoryValidityResult::INVALID_PARAMETERS; } else { collision_detection::CollisionRequest col_req; collision_detection::CollisionResult col_res; robot_state::RobotState& robot_state = planning_scene_ptr_->getCurrentStateNonConst(); // Set the initial state for (size_t jdx = 0; jdx < query.initial_state.name.size(); jdx++) { robot_state.setJointPositions(query.initial_state.name[jdx], &(query.initial_state.position[jdx])); } // Loop through the trajectory const std::vector<std::string>& trajectory_joint_names = query.trajectory.joint_names; for (size_t idx = 0; idx < query.trajectory.points.size(); idx++) { const trajectory_msgs::JointTrajectoryPoint& current_point = query.trajectory.points[idx]; if (current_point.positions.size() == trajectory_joint_names.size()) { // Update the robot state for (size_t jdx = 0; jdx < trajectory_joint_names.size(); jdx++) { robot_state.setJointPositions(trajectory_joint_names[jdx], &(current_point.positions[jdx])); } // Check for collisions (if check_type > 0, we also check environemnt collisions if (query.check_type > 0) { col_res.clear(); planning_scene_ptr_->checkCollision(col_req, col_res); if (col_res.collision) { ROS_WARN("Trajectory invalid due to environment collision at state %zu of %zu", idx + 1, query.trajectory.points.size()); result.status |= trajectory_verifier::CheckTrajectoryValidityResult::ENVIRONMENT_COLLISION; break; } } else { col_res.clear(); planning_scene_ptr_->checkSelfCollision(col_req, col_res); if (col_res.collision) { ROS_WARN("Trajectory invalid due to self collision at state %zu of %zu", idx + 1, query.trajectory.points.size()); result.status |= trajectory_verifier::CheckTrajectoryValidityResult::SELF_COLLISION; break; } } } else { result.status |= trajectory_verifier::CheckTrajectoryValidityResult::INVALID_PARAMETERS; break; } } } // Return the result return result; } bool CheckTrajectoryValidityCB(trajectory_verifier::CheckTrajectoryValidity::Request& req, trajectory_verifier::CheckTrajectoryValidity::Response& res) { ROS_INFO("Processing trajectory validity service..."); ROS_INFO("Updating planning scene..."); bool got_planning_scene = UpdateInternalPlanningScene(); if (!got_planning_scene) { res.result.status = trajectory_verifier::CheckTrajectoryValidityResult::PLANNING_SCENE_UPDATE_FAILED; } ROS_INFO("Checking trajectory validity..."); res.result = CheckTrajectoryValidity(req.query); ROS_INFO("...done"); return true; } bool BatchCheckTrajectoryValidityCB(trajectory_verifier::BatchCheckTrajectoryValidity::Request& req, trajectory_verifier::BatchCheckTrajectoryValidity::Response& res) { ROS_INFO("Processing batch trajectory validity service..."); ROS_INFO("Updating planning scene..."); bool got_planning_scene = UpdateInternalPlanningScene(); ROS_INFO("Checking trajectory validity for %zu trajectories", req.queries.size()); res.results.resize(req.queries.size()); for (size_t idx = 0; idx < req.queries.size(); idx++) { if (!got_planning_scene) { res.results[idx].status = trajectory_verifier::CheckTrajectoryValidityResult::PLANNING_SCENE_UPDATE_FAILED; } else { res.results[idx] = CheckTrajectoryValidity(req.queries[idx]); } } ROS_INFO("...done"); return true; } }; int main(int argc, char** argv) { ros::init(argc, argv, "trajectory_verifier"); ROS_INFO("Starting trajectory verifier..."); ros::NodeHandle nh; ros::NodeHandle nhp("~"); std::string planning_scene_service; std::string trajectory_validity_service; std::string batch_trajectory_validity_service; nhp.param(std::string("planning_scene_service"), planning_scene_service, std::string("get_planning_scene")); nhp.param(std::string("trajectory_validity_service"), trajectory_validity_service, std::string("check_trajectory_validity")); nhp.param(std::string("batch_trajectory_validity_service"), batch_trajectory_validity_service, std::string("batch_check_trajectory_validity")); TrajectoryVerifier verifier(nh, planning_scene_service, trajectory_validity_service, batch_trajectory_validity_service); ROS_INFO("...startup complete"); verifier.Loop(); return 0; } <commit_msg>Updated planning scene lookup<commit_after>#include <stdlib.h> #include <stdio.h> #include <vector> #include <string> #include <sstream> #include <iostream> #include <stdexcept> #include <Eigen/Geometry> #include <ros/ros.h> #include <moveit_msgs/GetPlanningScene.h> #include <urdf_model/model.h> #include <moveit/robot_model_loader/robot_model_loader.h> #include <moveit/planning_scene/planning_scene.h> #include "trajectory_verifier/CheckTrajectoryValidity.h" #include "trajectory_verifier/BatchCheckTrajectoryValidity.h" class TrajectoryVerifier { protected: std::shared_ptr<planning_scene::PlanningScene> planning_scene_ptr_; ros::NodeHandle nh_; ros::ServiceClient planning_scene_client_; ros::ServiceServer trajectory_validity_server_; ros::ServiceServer batch_trajectory_validity_server_; public: TrajectoryVerifier(ros::NodeHandle& nh, const std::string& planning_scene_service, const std::string& trajectory_validity_service, const std::string& batch_trajectory_validity_service) : nh_(nh) { robot_model_loader::RobotModelLoader loader; planning_scene_ptr_.reset(); planning_scene_ptr_ = std::shared_ptr<planning_scene::PlanningScene>(new planning_scene::PlanningScene(loader.getModel())); planning_scene_client_ = nh.serviceClient<moveit_msgs::GetPlanningScene>(planning_scene_service); trajectory_validity_server_ = nh.advertiseService(trajectory_validity_service, &TrajectoryVerifier::CheckTrajectoryValidityCB, this); batch_trajectory_validity_server_ = nh.advertiseService(batch_trajectory_validity_service, &TrajectoryVerifier::BatchCheckTrajectoryValidityCB, this); } void Loop() { ros::Rate spin_rate(10.0); while (ros::ok()) { ros::spinOnce(); spin_rate.sleep(); } } bool UpdateInternalPlanningScene() { try { // Update the planning scene moveit_msgs::GetPlanningSceneRequest ps_req; ps_req.components.components = moveit_msgs::PlanningSceneComponents::WORLD_OBJECT_NAMES | moveit_msgs::PlanningSceneComponents::WORLD_OBJECT_GEOMETRY | moveit_msgs::PlanningSceneComponents::OCTOMAP | moveit_msgs::PlanningSceneComponents::ROBOT_STATE | moveit_msgs::PlanningSceneComponents::ROBOT_STATE_ATTACHED_OBJECTS | moveit_msgs::PlanningSceneComponents::ALLOWED_COLLISION_MATRIX | moveit_msgs::PlanningSceneComponents::SCENE_SETTINGS | moveit_msgs::PlanningSceneComponents::TRANSFORMS | moveit_msgs::PlanningSceneComponents::OBJECT_COLORS | moveit_msgs::PlanningSceneComponents::LINK_PADDING_AND_SCALING; moveit_msgs::GetPlanningSceneResponse ps_res; planning_scene_client_.call(ps_req, ps_res); moveit_msgs::PlanningScene& planning_scene_state = ps_res.scene; planning_scene_ptr_->usePlanningSceneMsg(planning_scene_state); return true; } catch (...) { ROS_ERROR("Failed updating planning scene"); return false; } } trajectory_verifier::CheckTrajectoryValidityResult CheckTrajectoryValidity(const trajectory_verifier::CheckTrajectoryValidityQuery& query) { trajectory_verifier::CheckTrajectoryValidityResult result; result.status = trajectory_verifier::CheckTrajectoryValidityResult::SUCCESS; // Safety check the trajectory first if (query.initial_state.name.size() != query.initial_state.position.size()) { ROS_ERROR("Initial state is invalid"); result.status |= trajectory_verifier::CheckTrajectoryValidityResult::INVALID_PARAMETERS; } else { collision_detection::CollisionRequest col_req; collision_detection::CollisionResult col_res; robot_state::RobotState& robot_state = planning_scene_ptr_->getCurrentStateNonConst(); // Set the initial state for (size_t jdx = 0; jdx < query.initial_state.name.size(); jdx++) { robot_state.setJointPositions(query.initial_state.name[jdx], &(query.initial_state.position[jdx])); } // Loop through the trajectory const std::vector<std::string>& trajectory_joint_names = query.trajectory.joint_names; for (size_t idx = 0; idx < query.trajectory.points.size(); idx++) { const trajectory_msgs::JointTrajectoryPoint& current_point = query.trajectory.points[idx]; if (current_point.positions.size() == trajectory_joint_names.size()) { // Update the robot state for (size_t jdx = 0; jdx < trajectory_joint_names.size(); jdx++) { robot_state.setJointPositions(trajectory_joint_names[jdx], &(current_point.positions[jdx])); } // Check for collisions (if check_type > 0, we also check environemnt collisions if (query.check_type > 0) { col_res.clear(); planning_scene_ptr_->checkCollision(col_req, col_res); if (col_res.collision) { ROS_WARN("Trajectory invalid due to environment collision at state %zu of %zu", idx + 1, query.trajectory.points.size()); result.status |= trajectory_verifier::CheckTrajectoryValidityResult::ENVIRONMENT_COLLISION; break; } } else { col_res.clear(); planning_scene_ptr_->checkSelfCollision(col_req, col_res); if (col_res.collision) { ROS_WARN("Trajectory invalid due to self collision at state %zu of %zu", idx + 1, query.trajectory.points.size()); result.status |= trajectory_verifier::CheckTrajectoryValidityResult::SELF_COLLISION; break; } } } else { result.status |= trajectory_verifier::CheckTrajectoryValidityResult::INVALID_PARAMETERS; break; } } } // Return the result return result; } bool CheckTrajectoryValidityCB(trajectory_verifier::CheckTrajectoryValidity::Request& req, trajectory_verifier::CheckTrajectoryValidity::Response& res) { ROS_INFO("Processing trajectory validity service..."); ROS_INFO("Updating planning scene..."); bool got_planning_scene = UpdateInternalPlanningScene(); if (!got_planning_scene) { res.result.status = trajectory_verifier::CheckTrajectoryValidityResult::PLANNING_SCENE_UPDATE_FAILED; } ROS_INFO("Checking trajectory validity..."); res.result = CheckTrajectoryValidity(req.query); ROS_INFO("...done"); return true; } bool BatchCheckTrajectoryValidityCB(trajectory_verifier::BatchCheckTrajectoryValidity::Request& req, trajectory_verifier::BatchCheckTrajectoryValidity::Response& res) { ROS_INFO("Processing batch trajectory validity service..."); ROS_INFO("Updating planning scene..."); bool got_planning_scene = UpdateInternalPlanningScene(); ROS_INFO("Checking trajectory validity for %zu trajectories", req.queries.size()); res.results.resize(req.queries.size()); for (size_t idx = 0; idx < req.queries.size(); idx++) { if (!got_planning_scene) { res.results[idx].status = trajectory_verifier::CheckTrajectoryValidityResult::PLANNING_SCENE_UPDATE_FAILED; } else { res.results[idx] = CheckTrajectoryValidity(req.queries[idx]); } } ROS_INFO("...done"); return true; } }; int main(int argc, char** argv) { ros::init(argc, argv, "trajectory_verifier"); ROS_INFO("Starting trajectory verifier..."); ros::NodeHandle nh; ros::NodeHandle nhp("~"); std::string planning_scene_service; std::string trajectory_validity_service; std::string batch_trajectory_validity_service; nhp.param(std::string("planning_scene_service"), planning_scene_service, std::string("get_planning_scene")); nhp.param(std::string("trajectory_validity_service"), trajectory_validity_service, std::string("check_trajectory_validity")); nhp.param(std::string("batch_trajectory_validity_service"), batch_trajectory_validity_service, std::string("batch_check_trajectory_validity")); TrajectoryVerifier verifier(nh, planning_scene_service, trajectory_validity_service, batch_trajectory_validity_service); ROS_INFO("...startup complete"); verifier.Loop(); return 0; } <|endoftext|>
<commit_before>#include "treeapprox_binsearch.h" #include <cstdio> #include <vector> #include "gtest/gtest.h" using std::vector; using treeapprox::binsearch_options; using treeapprox::treeapprox_binsearch; template <typename T, size_t N> T* begin(T(&arr)[N]) { return &arr[0]; } template <typename T, size_t N> T* end(T(&arr)[N]) { return &arr[0]+N; } void WriteToStderr(const char* s) { fprintf(stderr, s); fflush(stderr); } void CheckResult(const vector<bool>& expected_result, const vector<bool>& result) { ASSERT_EQ(expected_result.size(), result.size()); for (size_t ii = 0; ii < expected_result.size(); ++ii) { EXPECT_EQ(expected_result[ii], result[ii]) << "Support mismatch at index " << ii; } } void RunAlgo(const vector<double>& x, size_t d, size_t k_low, size_t k_high, const vector<bool>& expected_result) { binsearch_options opts; opts.verbose = true; opts.output_function = WriteToStderr; vector<bool> result; double llow; double lhigh; size_t numiter; ASSERT_TRUE(treeapprox_binsearch(x, d, k_low, k_high, opts, &result, &llow, &lhigh, &numiter)); CheckResult(expected_result, result); } // d = 2 TEST(TreeapproxBinsearchTest, SimpleBinaryTest) { const double x2[] = {1, 1, 0, 1, 1, 0, 0}; const bool res2[] = {1, 1, 0, 1, 1, 0, 0}; vector<double> x(begin(x2), end(x2)); vector<bool> res(begin(res2), end(res2)); RunAlgo(x, 2, 4, 5, res); } TEST(TreeapproxBinsearchTest, SimpleBinaryTest2) { const double x2[] = {10, 10, 7, 10, 10, 7, 7}; const bool res2[] = {1, 1, 0, 1, 1, 0, 0}; vector<double> x(begin(x2), end(x2)); vector<bool> res(begin(res2), end(res2)); RunAlgo(x, 2, 4, 5, res); } TEST(TreeapproxBinsearchTest, EmptyParentTest) { const double x2[] = {1, 0, 0, 0, 0, 1, 1}; const bool res2[] = {1, 0, 1, 0, 0, 1, 1}; vector<double> x(begin(x2), end(x2)); vector<bool> res(begin(res2), end(res2)); RunAlgo(x, 2, 4, 5, res); } TEST(TreeapproxBinsearchTest, NotConvexTest) { const double x2[] = {1, 0, 0, 2, 3, 0, 0}; const bool res2[] = {0, 0, 0, 0, 0, 0, 0}; vector<double> x(begin(x2), end(x2)); vector<bool> res(begin(res2), end(res2)); RunAlgo(x, 2, 3, 3, res); } TEST(TreeapproxBinsearchTest, NotConvexTest2) { const double x2[] = {1, 0, 0, 2, 3, 0, 0}; const bool res2[] = {1, 1, 0, 1, 1, 0, 0}; vector<double> x(begin(x2), end(x2)); vector<bool> res(begin(res2), end(res2)); RunAlgo(x, 2, 3, 4, res); } // d = 3 TEST(TreeapproxBinsearchTest, SimpleBinaryTestD3) { const double x2[] = {1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0}; const bool res2[] = {1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0}; vector<double> x(begin(x2), end(x2)); vector<bool> res(begin(res2), end(res2)); RunAlgo(x, 3, 4, 5, res); } TEST(TreeapproxBinsearchTest, SimpleBinaryTest2D3) { const double x2[] = {10, 10, 7, 7, 10, 10, 7, 7, 7, 7, 7, 7, 7}; const bool res2[] = {1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0}; vector<double> x(begin(x2), end(x2)); vector<bool> res(begin(res2), end(res2)); RunAlgo(x, 3, 4, 5, res); } TEST(TreeapproxBinsearchTest, EmptyParentTestD3) { const double x2[] = {1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0}; const bool res2[] = {1, 0, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0}; vector<double> x(begin(x2), end(x2)); vector<bool> res(begin(res2), end(res2)); RunAlgo(x, 3, 4, 5, res); } TEST(TreeapproxBinsearchTest, NotConvexTestD3) { const double x2[] = {1, 0, 0, 0, 2, 3, 0, 0, 0, 0, 0, 0, 0}; const bool res2[] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; vector<double> x(begin(x2), end(x2)); vector<bool> res(begin(res2), end(res2)); RunAlgo(x, 3, 3, 3, res); } TEST(TreeapproxBinsearchTest, NotConvexTest2D3) { const double x2[] = {1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 3}; const bool res2[] = {1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 1}; vector<double> x(begin(x2), end(x2)); vector<bool> res(begin(res2), end(res2)); RunAlgo(x, 3, 3, 4, res); } int main(int argc, char **argv) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); } <commit_msg>tests for d=4<commit_after>#include "treeapprox_binsearch.h" #include <cstdio> #include <vector> #include "gtest/gtest.h" using std::vector; using treeapprox::binsearch_options; using treeapprox::treeapprox_binsearch; template <typename T, size_t N> T* begin(T(&arr)[N]) { return &arr[0]; } template <typename T, size_t N> T* end(T(&arr)[N]) { return &arr[0]+N; } void WriteToStderr(const char* s) { fprintf(stderr, s); fflush(stderr); } void CheckResult(const vector<bool>& expected_result, const vector<bool>& result) { ASSERT_EQ(expected_result.size(), result.size()); for (size_t ii = 0; ii < expected_result.size(); ++ii) { EXPECT_EQ(expected_result[ii], result[ii]) << "Support mismatch at index " << ii; } } void RunAlgo(const vector<double>& x, size_t d, size_t k_low, size_t k_high, const vector<bool>& expected_result) { binsearch_options opts; opts.verbose = true; opts.output_function = WriteToStderr; vector<bool> result; double llow; double lhigh; size_t numiter; ASSERT_TRUE(treeapprox_binsearch(x, d, k_low, k_high, opts, &result, &llow, &lhigh, &numiter)); CheckResult(expected_result, result); } // d = 2 TEST(TreeapproxBinsearchTest, SimpleBinaryTest) { const double x2[] = {1, 1, 0, 1, 1, 0, 0}; const bool res2[] = {1, 1, 0, 1, 1, 0, 0}; vector<double> x(begin(x2), end(x2)); vector<bool> res(begin(res2), end(res2)); RunAlgo(x, 2, 4, 5, res); } TEST(TreeapproxBinsearchTest, SimpleBinaryTest2) { const double x2[] = {10, 10, 7, 10, 10, 7, 7}; const bool res2[] = {1, 1, 0, 1, 1, 0, 0}; vector<double> x(begin(x2), end(x2)); vector<bool> res(begin(res2), end(res2)); RunAlgo(x, 2, 4, 5, res); } TEST(TreeapproxBinsearchTest, EmptyParentTest) { const double x2[] = {1, 0, 0, 0, 0, 1, 1}; const bool res2[] = {1, 0, 1, 0, 0, 1, 1}; vector<double> x(begin(x2), end(x2)); vector<bool> res(begin(res2), end(res2)); RunAlgo(x, 2, 4, 5, res); } TEST(TreeapproxBinsearchTest, NotConvexTest) { const double x2[] = {1, 0, 0, 2, 3, 0, 0}; const bool res2[] = {0, 0, 0, 0, 0, 0, 0}; vector<double> x(begin(x2), end(x2)); vector<bool> res(begin(res2), end(res2)); RunAlgo(x, 2, 3, 3, res); } TEST(TreeapproxBinsearchTest, NotConvexTest2) { const double x2[] = {1, 0, 0, 2, 3, 0, 0}; const bool res2[] = {1, 1, 0, 1, 1, 0, 0}; vector<double> x(begin(x2), end(x2)); vector<bool> res(begin(res2), end(res2)); RunAlgo(x, 2, 3, 4, res); } // d = 3 TEST(TreeapproxBinsearchTest, SimpleBinaryTestD3) { const double x2[] = {1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0}; const bool res2[] = {1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0}; vector<double> x(begin(x2), end(x2)); vector<bool> res(begin(res2), end(res2)); RunAlgo(x, 3, 4, 5, res); } TEST(TreeapproxBinsearchTest, SimpleBinaryTest2D3) { const double x2[] = {10, 10, 7, 7, 10, 10, 7, 7, 7, 7, 7, 7, 7}; const bool res2[] = {1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0}; vector<double> x(begin(x2), end(x2)); vector<bool> res(begin(res2), end(res2)); RunAlgo(x, 3, 4, 5, res); } TEST(TreeapproxBinsearchTest, EmptyParentTestD3) { const double x2[] = {1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0}; const bool res2[] = {1, 0, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0}; vector<double> x(begin(x2), end(x2)); vector<bool> res(begin(res2), end(res2)); RunAlgo(x, 3, 4, 5, res); } TEST(TreeapproxBinsearchTest, NotConvexTestD3) { const double x2[] = {1, 0, 0, 0, 2, 3, 0, 0, 0, 0, 0, 0, 0}; const bool res2[] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; vector<double> x(begin(x2), end(x2)); vector<bool> res(begin(res2), end(res2)); RunAlgo(x, 3, 3, 3, res); } TEST(TreeapproxBinsearchTest, NotConvexTest2D3) { const double x2[] = {1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 3}; const bool res2[] = {1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 1}; vector<double> x(begin(x2), end(x2)); vector<bool> res(begin(res2), end(res2)); RunAlgo(x, 3, 3, 4, res); } // d = 4 TEST(TreeapproxBinsearchTest, SimpleBinaryTestD4) { const double x2[] = {1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; const bool res2[] = {1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; vector<double> x(begin(x2), end(x2)); vector<bool> res(begin(res2), end(res2)); RunAlgo(x, 4, 4, 5, res); } TEST(TreeapproxBinsearchTest, SimpleBinaryTest2D4) { const double x2[] = {10, 7, 10, 7, 7, 7, 7, 7, 7, 10, 10, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7}; const bool res2[] = {1, 0, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; vector<double> x(begin(x2), end(x2)); vector<bool> res(begin(res2), end(res2)); RunAlgo(x, 4, 4, 5, res); } TEST(TreeapproxBinsearchTest, EmptyParentTestD4) { const double x2[] = {1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0}; const bool res2[] = {1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0}; vector<double> x(begin(x2), end(x2)); vector<bool> res(begin(res2), end(res2)); RunAlgo(x, 4, 4, 5, res); } TEST(TreeapproxBinsearchTest, NotConvexTestD4) { const double x2[] = {1, 0, 0, 0, 0, 2, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; const bool res2[] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; vector<double> x(begin(x2), end(x2)); vector<bool> res(begin(res2), end(res2)); RunAlgo(x, 4, 3, 3, res); } TEST(TreeapproxBinsearchTest, NotConvexTest2D4) { const double x2[] = {1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 3, 0, 0, 0, 0, 0, 0, 0, 0}; const bool res2[] = {1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0}; vector<double> x(begin(x2), end(x2)); vector<bool> res(begin(res2), end(res2)); RunAlgo(x, 4, 3, 4, res); } int main(int argc, char **argv) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); } <|endoftext|>
<commit_before>#include "screens/item_details.hpp" #include "../string.hpp" namespace bookwyrm::tui::screen { item_details::item_details(const core::item &item, int padding_top) : base(padding_top, default_padding_bot, 0, 0), item_(item) { } bool item_details::action(const int ch) { std::ignore = ch; /* No actions for this screen yet. */ return false; } void item_details::paint() { print_borders(); print_details(); } std::string item_details::footer_info() const { return fmt::format("DEBUG: padding top: {}, height: {}", padding_top_, get_height()); } int item_details::scrollpercent() const { /* stub */ return 42; } void item_details::print_borders() { const auto print_line = [this](int y) { for (int x = 0; x < get_width(); x++) print(x, y, rune::em_dash); }; print_line(0); print_line(get_height() - 1); } void item_details::print_details() { const std::string uris = vector_to_string(item_.misc.mirrors); using pair = std::pair<std::string, std::reference_wrapper<const std::string>>; std::string authors = vector_to_string(item_.nonexacts.authors); const std::string year = std::invoke([year = item_.exacts.year]() { const std::string str = std::to_string(year); return (str == "-1" ? "N/A" : std::move(str)); }); const std::vector<pair> v = { {"Title", item_.nonexacts.title}, {"Serie", item_.nonexacts.series}, {"Authors", authors}, {"Year", year}, {"Publisher", item_.nonexacts.publisher}, {"Extension", item_.exacts.extension}, {"Mirrors", uris}, {"Source", item_.misc.origin_plugin}, // include filesize here // and print it red if the item is gigabytes large }; /* Find the longest string... */ size_t len = 0; for (const auto &p : v) len = std::max(p.first.length(), len); /* * ... which we use to distance field title and field value. * (A magic 4 added to x to emulate a tab). */ int y = 1; for (const auto &p : v) { print(0, y, p.first + ':', attribute::bold); print(static_cast<int>(len + 4), y++, p.second.get()); /* How many lines did the string take up? */ if (int lines = (static_cast<int>(len + 4) + p.second.get().length()) / get_width(); lines > 1) { y += lines; } } } void item_details::print_desc(int &y, std::string str) { int x = 0; const auto words = split_string(str); auto word_fits = [this, &x](const std::string &str) -> bool { return static_cast<size_t>(get_width() - x) > str.length(); }; for (auto word = words.cbegin(); word != words.cend(); ++word) { if (!word_fits(*word)) { if (y == get_height() - 1) { /* No more lines to draw on; can't fit any more. */ if (word != words.cend() - 1) { /* We haven't printed the whole description yet. */ /* * Make sure the dots are printed in the screen. * Subtracts an additional 1 to overwrite the space * from the last word. */ print(word_fits("...") ? --x : x - 4, y, "..."); } return; } ++y; x = 0; } print(x, y, *word + ' '); x += static_cast<int>(word->length()) + 1; } } } // namespace bookwyrm::tui::screen <commit_msg>feat(tui): print all item fields when viewing details<commit_after>#include "screens/item_details.hpp" #include "../string.hpp" namespace bookwyrm::tui::screen { item_details::item_details(const core::item &item, int padding_top) : base(padding_top, default_padding_bot, 0, 0), item_(item) { } bool item_details::action(const int ch) { std::ignore = ch; /* No actions for this screen yet. */ return false; } void item_details::paint() { print_borders(); print_details(); } std::string item_details::footer_info() const { return fmt::format("DEBUG: padding top: {}, height: {}", padding_top_, get_height()); } int item_details::scrollpercent() const { /* stub */ return 42; } void item_details::print_borders() { const auto print_line = [this](int y) { for (int x = 0; x < get_width(); x++) print(x, y, rune::em_dash); }; print_line(0); print_line(get_height() - 1); } void item_details::print_details() { auto to_str = [](int i) -> const std::string { return (i == core::empty) ? "" : std::to_string(i); }; // clang-format off const std::string authors = vector_to_string(item_.nonexacts.authors), uris = vector_to_string(item_.misc.mirrors), isbns = vector_to_string(item_.misc.isbns), year = to_str(item_.exacts.year), size = to_str(item_.exacts.size) + " B", // size is recorded in bytes pages = to_str(item_.exacts.pages), volume = to_str(item_.exacts.volume), number = to_str(item_.exacts.number); // clang-format on using pair = std::pair<std::string, std::reference_wrapper<const std::string>>; const std::vector<pair> v = { {"Authors", authors}, {"Title", item_.nonexacts.title}, {"Serie", item_.nonexacts.series}, {"Publisher", item_.nonexacts.publisher}, {"Edition", item_.nonexacts.edition}, {"Year", year}, {"Journal", item_.nonexacts.journal}, {"Extension", item_.exacts.extension}, {"Size", size}, // TODO: print as read if very large {"Pages", pages}, {"Volume", volume}, {"Number", number}, {"Mirrors", uris}, {"Source", item_.misc.origin_plugin}, {"ISBNs", isbns}, }; /* Find the longest string... */ size_t len = 0; for (const auto &p : v) len = std::max(p.first.length(), len); /* * ... which we use to distance field title and field value. * (A magic 4 added to x to emulate a tab). */ int y = 1; for (const auto &p : v) { print(0, y, p.first + ':', attribute::bold); print(static_cast<int>(len + 4), y++, p.second.get()); /* How many lines did the string take up? */ if (int lines = (static_cast<int>(len + 4) + p.second.get().length()) / get_width(); lines > 1) { y += lines; } } } void item_details::print_desc(int &y, std::string str) { int x = 0; const auto words = split_string(str); auto word_fits = [this, &x](const std::string &str) -> bool { return static_cast<size_t>(get_width() - x) > str.length(); }; for (auto word = words.cbegin(); word != words.cend(); ++word) { if (!word_fits(*word)) { if (y == get_height() - 1) { /* No more lines to draw on; can't fit any more. */ if (word != words.cend() - 1) { /* We haven't printed the whole description yet. */ /* * Make sure the dots are printed in the screen. * Subtracts an additional 1 to overwrite the space * from the last word. */ print(word_fits("...") ? --x : x - 4, y, "..."); } return; } ++y; x = 0; } print(x, y, *word + ' '); x += static_cast<int>(word->length()) + 1; } } } // namespace bookwyrm::tui::screen <|endoftext|>
<commit_before>// This is a work in progress. // C.M.Cantalupo #ifndef sorter_threaded_hpp #define sorter_threaded_hpp #include "sorter_threaded.hpp" #include "partition_wall.hpp" #include "partition.hpp" #include "partition_gang.hpp" void SorterThreaded::sort(std::vector<double>::iterator begin, std::vector<double>::iterator end) { // To achieve parallelism here we will choose a set of pivots from // the list to be sorted. Here we will just choose the first elements // in the vector. The number of pivots will determine the number of // tasks to be done: one more task than the number of pivots. // // For simplicity here we will choose the number of tasks to be // a factor of the number of threads. This will be determined // by the class attribute taskFactor_. // // We need to break down the main scaling dimension of the problem, // the length of the input vector. The first thing that we want to // do with the input is to partition it into intervals bounded by // the pivots. This can be done with the std::set.upper_bound() to // partition the input vector. In the end we want taskFactor_ times // the number of threads jobs and we need one fewer pivot than that // to do so. Bundle up the pivots with a stack and put them in a // std::set along with a dummy pivot for the end. We will // call this class "PartitionWall." The set provides a upper_bound // bound function so we need to overload less than. // try { SorterThreadedHelper::PartitionGang gang(begin, end, numThreads_, taskFactor_); gang.fillPartitions(); gang.fillOutput(); gang.sortOutput(); } catch (SorterThreadedException& e) { if(e.error == SorterThreadedException::TooFewPivots) std::sort(begin, end); else throw(e); } } SorterThreaded::SorterThreaded(size_t taskFactor, size_t numThreads) : taskFactor_(taskFactor), numThreads_(numThreads) {} #endif #if 0 // Sorry for the procedural mess below. Need to rethink algorithm // in terms of objects. int numThreads = omp_get_max_num_threads(); #pragma omp parallel default (none) private () firstprivate() shared (sharedPartition) { size_t threadID = omp_get_thread_num(); size_t numTasks = numThreads*TASK_FACTOR_; size_t numPivots = numTasks - 1; size_t vecLen = std::distance(begin, end); std::vector<T>::iterator pivotsEnd = begin + numPivots; std::vector<SorterThread> bundled(numPivots); for (itIn = begin, i = 0; itIn < pivotsEnd; ++itIn, ++i) { bundled[i].value = *itIn; } sort(bundled); for (i = 0; i < bundled.size(); i++) { bundled[i].index = i; } // Put the bundled pivots in a set std::set<T> pivots(bundled.begin(), bundled.end()); // Break up the input vector into number of threads chunks std::vector<T>::iterator chunkBegin; std::vector<T>::iterator chunkEnd; SorterThread::chunk(pastPivots, end, numThreads, threadID, chunkBegin, chunkEnd); std::vector<std::stack<T>> partition(numTasks); // Partition the input into private stacks for (it = chunkBegin; it < chunkEnd; ++it) { partition[pivots.lower_bound(*it).index].push(*it); } std::vector<std::vector<T>> sharedPartition(numThreads); // Combine the private stacks into shared memory for (i = 0; i < TASK_FACTOR_; i++) { for (j = 0; j < numThreads; j++) { outBin = i * TASK_FACTOR_ + (j + threadID) % numThreads; while (!partition[outBin].empty()) { sharedPartition[outBin].push(partition[outBin].pop()); } omp_barrier(); } } // Farm out the shared stacks to local threads myWork for (i = 0; i < numTasks; i++) { std::vector<T> myWork(sharedPartition[i]); sort(myWork); } // Recombine the sorted chunks if (threadID == 0) { for (pivotIt = pivots.begin(), resultIt = begin; pivotIt < pivots.end(); ++pivotIt, ++resultIt) { *resultIt = *pivotIt; for (i = 0; i < numThreads; i++) { if (i == threadID) { for (workIt = myWork.begin(); workIt < myWork.end(); ++workIt, ++resultIt) *resultIt = *workIt; } } } } void SorterThread::chunk(std::vector<T>::iterator begin, std::vector<T>::iterator end, size_t numChunk, size_t chunkIndex, std::vector<T>::iterator chunkBegin, std::vector<T>::iterator chunkEnd) { size_t chunkSize = (vecLen - numPivots) / numThreads; int slop = (vecLen - numThreads - 1) % numThreads; if ( threadID < slop ) { myChunkBegin = pastPivots + threadID * (chunkSize + 1); } else { myChunkBegin = pastPivots + slop * (chunkSize + 1); myChunkBegin += (threadID - slop) * (chunkSize); } if ( threadID < slop ) { myChunkEnd = } else { myChunkBegin = pastPivots + slop * (chunkSize + 1); myChunkBegin += (threadID - slop) * (chunkSize); } int slop = vecLen % numThreads; std::vector<std::vector<T>::iterator>::chunks(numThreads); for ( std::vector<T>::iterator inputIt = pastPivots, i = 0 i < numThreads; inputIt += chunkSize, ++i) { if (i == slop) { --chunkSize } chunks[i] = inputIt; } } // } } #endif // endo of #if 0 to block out mess <commit_msg>got rid of extra dependencies<commit_after>// This is a work in progress. // C.M.Cantalupo #ifndef sorter_threaded_hpp #define sorter_threaded_hpp #include "sorter_threaded.hpp" #include "partition_gang.hpp" void SorterThreaded::sort(std::vector<double>::iterator begin, std::vector<double>::iterator end) { // To achieve parallelism here we will choose a set of pivots from // the list to be sorted. Here we will just choose the first elements // in the vector. The number of pivots will determine the number of // tasks to be done: one more task than the number of pivots. // // For simplicity here we will choose the number of tasks to be // a factor of the number of threads. This will be determined // by the class attribute taskFactor_. // // We need to break down the main scaling dimension of the problem, // the length of the input vector. The first thing that we want to // do with the input is to partition it into intervals bounded by // the pivots. This can be done with the std::set.upper_bound() to // partition the input vector. In the end we want taskFactor_ times // the number of threads jobs and we need one fewer pivot than that // to do so. Bundle up the pivots with a stack and put them in a // std::set along with a dummy pivot for the end. We will // call this class "PartitionWall." The set provides a upper_bound // bound function so we need to overload less than. // try { SorterThreadedHelper::PartitionGang gang(begin, end, numThreads_, taskFactor_); gang.fillPartitions(); gang.fillOutput(); gang.sortOutput(); } catch (SorterThreadedException& e) { if(e.error == SorterThreadedException::TooFewPivots) std::sort(begin, end); else throw(e); } } SorterThreaded::SorterThreaded(size_t taskFactor, size_t numThreads) : taskFactor_(taskFactor), numThreads_(numThreads) {} #endif #if 0 // Sorry for the procedural mess below. Need to rethink algorithm // in terms of objects. int numThreads = omp_get_max_num_threads(); #pragma omp parallel default (none) private () firstprivate() shared (sharedPartition) { size_t threadID = omp_get_thread_num(); size_t numTasks = numThreads*TASK_FACTOR_; size_t numPivots = numTasks - 1; size_t vecLen = std::distance(begin, end); std::vector<T>::iterator pivotsEnd = begin + numPivots; std::vector<SorterThread> bundled(numPivots); for (itIn = begin, i = 0; itIn < pivotsEnd; ++itIn, ++i) { bundled[i].value = *itIn; } sort(bundled); for (i = 0; i < bundled.size(); i++) { bundled[i].index = i; } // Put the bundled pivots in a set std::set<T> pivots(bundled.begin(), bundled.end()); // Break up the input vector into number of threads chunks std::vector<T>::iterator chunkBegin; std::vector<T>::iterator chunkEnd; SorterThread::chunk(pastPivots, end, numThreads, threadID, chunkBegin, chunkEnd); std::vector<std::stack<T>> partition(numTasks); // Partition the input into private stacks for (it = chunkBegin; it < chunkEnd; ++it) { partition[pivots.lower_bound(*it).index].push(*it); } std::vector<std::vector<T>> sharedPartition(numThreads); // Combine the private stacks into shared memory for (i = 0; i < TASK_FACTOR_; i++) { for (j = 0; j < numThreads; j++) { outBin = i * TASK_FACTOR_ + (j + threadID) % numThreads; while (!partition[outBin].empty()) { sharedPartition[outBin].push(partition[outBin].pop()); } omp_barrier(); } } // Farm out the shared stacks to local threads myWork for (i = 0; i < numTasks; i++) { std::vector<T> myWork(sharedPartition[i]); sort(myWork); } // Recombine the sorted chunks if (threadID == 0) { for (pivotIt = pivots.begin(), resultIt = begin; pivotIt < pivots.end(); ++pivotIt, ++resultIt) { *resultIt = *pivotIt; for (i = 0; i < numThreads; i++) { if (i == threadID) { for (workIt = myWork.begin(); workIt < myWork.end(); ++workIt, ++resultIt) *resultIt = *workIt; } } } } void SorterThread::chunk(std::vector<T>::iterator begin, std::vector<T>::iterator end, size_t numChunk, size_t chunkIndex, std::vector<T>::iterator chunkBegin, std::vector<T>::iterator chunkEnd) { size_t chunkSize = (vecLen - numPivots) / numThreads; int slop = (vecLen - numThreads - 1) % numThreads; if ( threadID < slop ) { myChunkBegin = pastPivots + threadID * (chunkSize + 1); } else { myChunkBegin = pastPivots + slop * (chunkSize + 1); myChunkBegin += (threadID - slop) * (chunkSize); } if ( threadID < slop ) { myChunkEnd = } else { myChunkBegin = pastPivots + slop * (chunkSize + 1); myChunkBegin += (threadID - slop) * (chunkSize); } int slop = vecLen % numThreads; std::vector<std::vector<T>::iterator>::chunks(numThreads); for ( std::vector<T>::iterator inputIt = pastPivots, i = 0 i < numThreads; inputIt += chunkSize, ++i) { if (i == slop) { --chunkSize } chunks[i] = inputIt; } } // } } #endif // endo of #if 0 to block out mess <|endoftext|>
<commit_before>/* predictor.C * * Copyright (C) 2009 Marcel Schumann * * This file is part of QuEasy -- A Toolbox for Automated QSAR Model * Construction and Validation. * QuEasy is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or (at * your option) any later version. * * QuEasy is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see <http://www.gnu.org/licenses/>. */ #include <BALL/FORMAT/commandlineParser.h> #include <BALL/QSAR/registry.h> #include <BALL/QSAR/configIO.h> #include <fstream> #include "version.h" using namespace BALL::QSAR; using namespace BALL; using namespace std; void startPrediction(PredictionConfiguration& conf, QSARData* q, String* data_filename); void startPrediction(ifstream& in, QSARData* q, String* data_filename) { PredictionConfiguration conf = ConfigIO::readPredictionConfiguration(&in); if(conf.done) return; // stop processing this section startPrediction(conf,q,data_filename); } void startPrediction(PredictionConfiguration& conf, QSARData* q, String* data_filename) { bool created_data_object=0; if(q==NULL || data_filename==NULL || conf.data!=*data_filename) { if(q==NULL) { q = new QSARData; created_data_object=1; } q->readFromFile(conf.data); if(data_filename) *data_filename = conf.data; } Registry reg; Model* m; String model_type; ifstream model_input(conf.model.c_str()); // read model-abbreviation if(!model_input) { Log.error()<<"Error: Model-file '"<<conf.model<<"' does not exist!!"<<endl; return; } getline(model_input,model_type); getline(model_input,model_type); model_type = model_type.getField(0,"\t"); model_input.close(); RegistryEntry* entry = reg.getEntry(model_type); if(!entry->kernel) { m = (*entry->create)(*q); } else { // parameters irrelevant; will be overwritten by those read from file m = (*entry->createKernel1)(*q,1,1, -1); } m->readFromFile(conf.model.c_str()); // do NOT train again (done by ModelCreator) !! m->model_val->selectStat(conf.statistic); m->model_val->testInputData(1); // calculate prediction quality m->model_val->setCVRes(m->model_val->getFitRes()); m->model_val->saveToFile(conf.output); ofstream out(conf.output.c_str(),ios::app); out<<endl<<"[Predictions]"<<endl; int no_act = q->getNoResponseVariables(); int no_cols = no_act; if(conf.print_expected) { no_cols*=2; out<<"# format: predition0, expectation0, ..."<<endl; } out<<"expected_values = "<<conf.print_expected<<endl; out<<"dimensions = "<<q->getNoSubstances()<<" "<<no_cols<<endl; for(unsigned int i=0;i<q->getNoSubstances();i++) { vector<double>* v = q->getSubstance(i); // get UNcentered descriptor-vector of test compound Eigen::VectorXd res = m->predict(*v,1); // transform val. data according to centering of training data delete v; vector<double>* exp = q->getActivity(i); // get UNcentered response value vector //for(int j=1; j<=res.getSize();j++) getSize is part of MATH/LinAlg and was replaced by rows() in Eigen for(int j=1; j<=res.rows();j++) { out<<res(j)<<"\t"; if(conf.print_expected) { out<<(*exp)[j-1]<<"\t"; } } delete exp; out<<endl; } if(created_data_object) delete q; delete m; } #ifndef EXT_MAIN int main(int argc, char* argv[]) { CommandlineParser par("Predictor","predict activities with QSAR model", VERSION ,String(__DATE__), "QuEasy (QSAR)"); par.registerParameter("i","input mod-file",INFILE,true); par.registerParameter("dat","data-file containing prediction data set",INFILE,true); par.registerParameter("o","output text file",OUTFILE,true); String man = "This tool predictes the response values of compounds in the given data-file using the specified QSAR model.\n\nInput of this tool is a model-file as generated by ModelCreator or FeatureSelector and a data-file generated by InputReader.\n\nOutput of this tool (as specified by '-o') is a text file containing the predicted and, if any, the expected response values in one column each.\nIf you would prefer to use molecule files (sdf,mol2,drf) for input and output, please use the tool MolPredictor instead of this one."; par.setToolManual(man); par.setSupportedFormats("i","mod"); par.setSupportedFormats("dat","dat"); par.setSupportedFormats("o","txt"); par.parse(argc,argv); Registry reg; PredictionConfiguration conf; conf.model = par.get("i"); conf.data = par.get("dat"); conf.output = par.get("o"); conf.print_expected = true; startPrediction(conf,0,0); } #endif <commit_msg>deleted invalid licensing<commit_after>// -*- Mode: C++; tab-width: 2; -*- // vi: set ts=2: // #include <BALL/FORMAT/commandlineParser.h> #include <BALL/QSAR/registry.h> #include <BALL/QSAR/configIO.h> #include <fstream> #include "version.h" using namespace BALL::QSAR; using namespace BALL; using namespace std; void startPrediction(PredictionConfiguration& conf, QSARData* q, String* data_filename); void startPrediction(ifstream& in, QSARData* q, String* data_filename) { PredictionConfiguration conf = ConfigIO::readPredictionConfiguration(&in); if(conf.done) return; // stop processing this section startPrediction(conf,q,data_filename); } void startPrediction(PredictionConfiguration& conf, QSARData* q, String* data_filename) { bool created_data_object=0; if(q==NULL || data_filename==NULL || conf.data!=*data_filename) { if(q==NULL) { q = new QSARData; created_data_object=1; } q->readFromFile(conf.data); if(data_filename) *data_filename = conf.data; } Registry reg; Model* m; String model_type; ifstream model_input(conf.model.c_str()); // read model-abbreviation if(!model_input) { Log.error()<<"Error: Model-file '"<<conf.model<<"' does not exist!!"<<endl; return; } getline(model_input,model_type); getline(model_input,model_type); model_type = model_type.getField(0,"\t"); model_input.close(); RegistryEntry* entry = reg.getEntry(model_type); if(!entry->kernel) { m = (*entry->create)(*q); } else { // parameters irrelevant; will be overwritten by those read from file m = (*entry->createKernel1)(*q,1,1, -1); } m->readFromFile(conf.model.c_str()); // do NOT train again (done by ModelCreator) !! m->model_val->selectStat(conf.statistic); m->model_val->testInputData(1); // calculate prediction quality m->model_val->setCVRes(m->model_val->getFitRes()); m->model_val->saveToFile(conf.output); ofstream out(conf.output.c_str(),ios::app); out<<endl<<"[Predictions]"<<endl; int no_act = q->getNoResponseVariables(); int no_cols = no_act; if(conf.print_expected) { no_cols*=2; out<<"# format: predition0, expectation0, ..."<<endl; } out<<"expected_values = "<<conf.print_expected<<endl; out<<"dimensions = "<<q->getNoSubstances()<<" "<<no_cols<<endl; for(unsigned int i=0;i<q->getNoSubstances();i++) { vector<double>* v = q->getSubstance(i); // get UNcentered descriptor-vector of test compound Eigen::VectorXd res = m->predict(*v,1); // transform val. data according to centering of training data delete v; vector<double>* exp = q->getActivity(i); // get UNcentered response value vector //for(int j=1; j<=res.getSize();j++) getSize is part of MATH/LinAlg and was replaced by rows() in Eigen for(int j=1; j<=res.rows();j++) { out<<res(j)<<"\t"; if(conf.print_expected) { out<<(*exp)[j-1]<<"\t"; } } delete exp; out<<endl; } if(created_data_object) delete q; delete m; } #ifndef EXT_MAIN int main(int argc, char* argv[]) { CommandlineParser par("Predictor","predict activities with QSAR model", VERSION ,String(__DATE__), "QuEasy (QSAR)"); par.registerParameter("i","input mod-file",INFILE,true); par.registerParameter("dat","data-file containing prediction data set",INFILE,true); par.registerParameter("o","output text file",OUTFILE,true); String man = "This tool predictes the response values of compounds in the given data-file using the specified QSAR model.\n\nInput of this tool is a model-file as generated by ModelCreator or FeatureSelector and a data-file generated by InputReader.\n\nOutput of this tool (as specified by '-o') is a text file containing the predicted and, if any, the expected response values in one column each.\nIf you would prefer to use molecule files (sdf,mol2,drf) for input and output, please use the tool MolPredictor instead of this one."; par.setToolManual(man); par.setSupportedFormats("i","mod"); par.setSupportedFormats("dat","dat"); par.setSupportedFormats("o","txt"); par.parse(argc,argv); Registry reg; PredictionConfiguration conf; conf.model = par.get("i"); conf.data = par.get("dat"); conf.output = par.get("o"); conf.print_expected = true; startPrediction(conf,0,0); } #endif <|endoftext|>
<commit_before>#include <stdio.h> #include "geom.h" #include "time.h" #include "bigtest.h" #include "io.h" /** * Run relate between two large geometries to test the performance * of the sweepline intersection detection algorithm */ void run(int nPts, GeometryFactory *fact) { clock_t startTime, endTime; double size=100.0; double armLen=50.0; int nArms=10; Polygon *poly=GeometryTestFactory::createSineStar(fact,0.0,0.0,size,armLen,nArms,nPts); Polygon *box=GeometryTestFactory::createSineStar(fact,0.0,size/2,size,armLen,nArms,nPts); // Polygon *box=GeometryTestFactory::createBox(fact,0,0,1,100.0); startTime=clock(); poly->intersects(box); endTime=clock(); double totalTime=(double)(endTime-startTime); printf( "n Pts: %i Executed in %6.0f ms.\n",nPts,totalTime); // cout << "n Pts: " << nPts << " Executed in " << totalTime << endl; } void main(int argC, char* argV[]) { GeometryFactory *fact=new GeometryFactory(); run(1000,fact); run(2000,fact); run(4000,fact); run(8000,fact); run(16000,fact); run(32000,fact); run(64000,fact); run(128000,fact); run(256000,fact); run(512000,fact); run(1024000,fact); cout << "Done" << endl; } <commit_msg>Fixed main() return type.<commit_after>#include <stdio.h> #include "geom.h" #include "time.h" #include "bigtest.h" #include "io.h" /** * Run relate between two large geometries to test the performance * of the sweepline intersection detection algorithm */ void run(int nPts, GeometryFactory *fact) { clock_t startTime, endTime; double size=100.0; double armLen=50.0; int nArms=10; Polygon *poly=GeometryTestFactory::createSineStar(fact,0.0,0.0,size,armLen,nArms,nPts); Polygon *box=GeometryTestFactory::createSineStar(fact,0.0,size/2,size,armLen,nArms,nPts); // Polygon *box=GeometryTestFactory::createBox(fact,0,0,1,100.0); startTime=clock(); poly->intersects(box); endTime=clock(); double totalTime=(double)(endTime-startTime); printf( "n Pts: %i Executed in %6.0f ms.\n",nPts,totalTime); // cout << "n Pts: " << nPts << " Executed in " << totalTime << endl; } int main(int argC, char* argV[]) { GeometryFactory *fact=new GeometryFactory(); run(1000,fact); run(2000,fact); run(4000,fact); run(8000,fact); run(16000,fact); run(32000,fact); run(64000,fact); run(128000,fact); run(256000,fact); run(512000,fact); run(1024000,fact); cout << "Done" << endl; } <|endoftext|>
<commit_before>// Time: O(n) // Space: O(n) class Solution { public: /** * @param nums: a vector of integers * @return: the maximum difference */ int maximumGap(vector<int> nums) { if (nums.size() < 2) { return 0; } // Init bucket. int max_val = *max_element(nums.cbegin(), nums.cend()); int min_val = *min_element(nums.cbegin(), nums.cend()); int gap = max(1, static_cast<int>((max_val - min_val) / (nums.size() - 1))); map<int, array<int, 2>> bucket; typedef enum {MIN, MAX} ValueType; // Find the bucket where the n should be put. for (const auto& n : nums) { // min_val / max_val is in the first / last bucket. if (n == max_val || n == min_val) { continue ; } int i = (n - min_val) / gap; bucket[i][MIN] = min(!bucket[i][MIN] ? INT_MAX : bucket[i][MIN], n); bucket[i][MAX] = max(!bucket[i][MAX] ? INT_MIN : bucket[i][MAX], n); } // Count each bucket gap between the first and the last bucket. int max_gap = 0, pre_bucket_max = min_val; for (auto& kvp : bucket) { max_gap = max(max_gap, kvp.second[MIN] - pre_bucket_max); pre_bucket_max = (kvp.second)[MAX]; } // Count the last bucket. max_gap = max(max_gap, max_val - pre_bucket_max); return max_gap; } }; <commit_msg>Update maximum-gap.cpp<commit_after>// Time: O(n) // Space: O(n) class Solution { public: /** * @param nums: a vector of integers * @return: the maximum difference */ int maximumGap(vector<int> nums) { if (nums.size() < 2) { return 0; } // Init bucket. int max_val = *max_element(nums.cbegin(), nums.cend()); int min_val = *min_element(nums.cbegin(), nums.cend()); int gap = max(1, static_cast<int>((max_val - min_val) / (nums.size() - 1))); map<int, array<int, 2>> bucket; typedef enum {MIN, MAX} ValueType; // Find the bucket where the n should be put. for (const auto& n : nums) { // min_val / max_val is in the first / last bucket. if (n == max_val || n == min_val) { continue ; } int i = (n - min_val) / gap; bucket[i][MIN] = min(!bucket[i][MIN] ? INT_MAX : bucket[i][MIN], n); bucket[i][MAX] = max(!bucket[i][MAX] ? INT_MIN : bucket[i][MAX], n); } // Count each bucket gap between the first and the last bucket. int max_gap = 0, pre_bucket_max = min_val; for (auto& kvp : bucket) { max_gap = max(max_gap, kvp.second[MIN] - pre_bucket_max); pre_bucket_max = (kvp.second)[MAX]; } // Count the last bucket. max_gap = max(max_gap, max_val - pre_bucket_max); return max_gap; } }; <|endoftext|>
<commit_before>#include "unittest/gtest.hpp" #include "clustering/immediate_consistency/branch/broadcaster.hpp" #include "clustering/immediate_consistency/branch/listener.hpp" #include "clustering/immediate_consistency/branch/replier.hpp" #include "clustering/immediate_consistency/query/master.hpp" #include "clustering/immediate_consistency/query/namespace_interface.hpp" #include "rpc/mailbox/mailbox.hpp" #include "unittest/clustering_utils.hpp" #include "unittest/dummy_metadata_controller.hpp" #include "mock/dummy_protocol.hpp" #include "unittest/unittest_utils.hpp" namespace unittest { /* The `ReadWrite` test sends some reads and writes to some shards via a `cluster_namespace_interface_t`. */ static void run_read_write_test() { /* Set up a cluster so mailboxes can be created */ simple_mailbox_cluster_t cluster; /* Set up metadata meeting-places */ branch_history_t<dummy_protocol_t> initial_branch_metadata; dummy_semilattice_controller_t<branch_history_t<dummy_protocol_t> > branch_history_controller(initial_branch_metadata); /* Set up a branch */ test_store_t initial_store; cond_t interruptor; broadcaster_t<dummy_protocol_t> broadcaster( cluster.get_mailbox_manager(), branch_history_controller.get_view(), &initial_store.store, &interruptor ); simple_directory_manager_t<boost::optional<broadcaster_business_card_t<dummy_protocol_t> > > broadcaster_metadata_controller(&cluster, boost::optional<broadcaster_business_card_t<dummy_protocol_t> >( broadcaster.get_business_card() )); listener_t<dummy_protocol_t> initial_listener( cluster.get_mailbox_manager(), broadcaster_metadata_controller.get_root_view()-> get_peer_view(cluster.get_connectivity_service()->get_me()), branch_history_controller.get_view(), &broadcaster, &interruptor ); replier_t<dummy_protocol_t> initial_replier(&initial_listener); /* Set up a metadata meeting-place for masters */ std::map<master_id_t, master_business_card_t<dummy_protocol_t> > initial_master_metadata; simple_directory_manager_t<std::map<master_id_t, master_business_card_t<dummy_protocol_t> > > master_metadata_controller(&cluster, initial_master_metadata); /* Set up a master */ master_t<dummy_protocol_t> master(cluster.get_mailbox_manager(), master_metadata_controller.get_root_view(), a_thru_z_region(), &broadcaster); /* Set up a namespace dispatcher */ cluster_namespace_interface_t<dummy_protocol_t> namespace_interface(cluster.get_mailbox_manager(), master_metadata_controller.get_root_view()); /* Send some writes to the namespace */ order_source_t order_source; std::map<std::string, std::string> inserter_state; test_inserter_t inserter( &namespace_interface, &order_source, &inserter_state); nap(100); inserter.stop(); /* Now send some reads */ for (std::map<std::string, std::string>::iterator it = inserter.values_inserted->begin(); it != inserter.values_inserted->end(); it++) { dummy_protocol_t::read_t r; r.keys.keys.insert((*it).first); cond_t interruptor; dummy_protocol_t::read_response_t resp = namespace_interface.read(r, order_source.check_in("unittest"), &interruptor); EXPECT_EQ((*it).second, resp.values[(*it).first]); } } TEST(ClusteringNamespace, ReadWrite) { run_in_thread_pool(&run_read_write_test); } } /* namespace unittest */ <commit_msg>Fix a compiler error that somehow crept through.<commit_after>#include "unittest/gtest.hpp" #include "clustering/immediate_consistency/branch/broadcaster.hpp" #include "clustering/immediate_consistency/branch/listener.hpp" #include "clustering/immediate_consistency/branch/replier.hpp" #include "clustering/immediate_consistency/query/master.hpp" #include "clustering/immediate_consistency/query/namespace_interface.hpp" #include "rpc/mailbox/mailbox.hpp" #include "unittest/clustering_utils.hpp" #include "unittest/dummy_metadata_controller.hpp" #include "mock/dummy_protocol.hpp" #include "unittest/unittest_utils.hpp" namespace unittest { /* The `ReadWrite` test sends some reads and writes to some shards via a `cluster_namespace_interface_t`. */ static void run_read_write_test() { /* Set up a cluster so mailboxes can be created */ simple_mailbox_cluster_t cluster; /* Set up metadata meeting-places */ branch_history_t<dummy_protocol_t> initial_branch_metadata; dummy_semilattice_controller_t<branch_history_t<dummy_protocol_t> > branch_history_controller(initial_branch_metadata); /* Set up a branch */ test_store_t<dummy_protocol_t> initial_store; cond_t interruptor; broadcaster_t<dummy_protocol_t> broadcaster( cluster.get_mailbox_manager(), branch_history_controller.get_view(), &initial_store.store, &interruptor ); simple_directory_manager_t<boost::optional<broadcaster_business_card_t<dummy_protocol_t> > > broadcaster_metadata_controller(&cluster, boost::optional<broadcaster_business_card_t<dummy_protocol_t> >( broadcaster.get_business_card() )); listener_t<dummy_protocol_t> initial_listener( cluster.get_mailbox_manager(), broadcaster_metadata_controller.get_root_view()-> get_peer_view(cluster.get_connectivity_service()->get_me()), branch_history_controller.get_view(), &broadcaster, &interruptor ); replier_t<dummy_protocol_t> initial_replier(&initial_listener); /* Set up a metadata meeting-place for masters */ std::map<master_id_t, master_business_card_t<dummy_protocol_t> > initial_master_metadata; simple_directory_manager_t<std::map<master_id_t, master_business_card_t<dummy_protocol_t> > > master_metadata_controller(&cluster, initial_master_metadata); /* Set up a master */ master_t<dummy_protocol_t> master(cluster.get_mailbox_manager(), master_metadata_controller.get_root_view(), a_thru_z_region(), &broadcaster); /* Set up a namespace dispatcher */ cluster_namespace_interface_t<dummy_protocol_t> namespace_interface(cluster.get_mailbox_manager(), master_metadata_controller.get_root_view()); /* Send some writes to the namespace */ order_source_t order_source; std::map<std::string, std::string> inserter_state; test_inserter_t inserter( &namespace_interface, &order_source, &inserter_state); nap(100); inserter.stop(); /* Now send some reads */ for (std::map<std::string, std::string>::iterator it = inserter.values_inserted->begin(); it != inserter.values_inserted->end(); it++) { dummy_protocol_t::read_t r; r.keys.keys.insert((*it).first); cond_t interruptor; dummy_protocol_t::read_response_t resp = namespace_interface.read(r, order_source.check_in("unittest"), &interruptor); EXPECT_EQ((*it).second, resp.values[(*it).first]); } } TEST(ClusteringNamespace, ReadWrite) { run_in_thread_pool(&run_read_write_test); } } /* namespace unittest */ <|endoftext|>
<commit_before>#include "any.hpp" #include "dyn_lib.hpp" #include <gtest/gtest.h> struct A { explicit A(int i) : m_i(i) {} int m_i; }; TEST(any, readme_example) { static_any<32> a; // on g++ 5.x sizeof(std::string) is 32 static_assert(sizeof(a) == 32 + sizeof(std::ptrdiff_t), "impossible"); a = 1234; ASSERT_EQ(1234, a.get<int>()); a = std::string("Hello world"); ASSERT_EQ(std::string("Hello world"), a.get<std::string>()); struct A { explicit A(long i = 0, double d = .0) : i_(i), d_(d) {} long i_; double d_; }; a = A(12, .34); } TEST(any, test_sizeof) { static_any<16> a; ASSERT_EQ(16 + sizeof(std::ptrdiff_t), sizeof(a)); } TEST(any, capacity) { static_any<32> a; ASSERT_EQ(32, a.capacity()); a = std::string("hello world"); ASSERT_EQ(32, a.capacity()); a.reset(); ASSERT_EQ(32, a.capacity()); } TEST(any, size) { static_any<32> a; ASSERT_EQ(0, a.size()); a = 1234; ASSERT_EQ(sizeof(1234), a.size()); a = std::string("foobar"); ASSERT_EQ(sizeof(std::string), a.size()); a.reset(); ASSERT_EQ(0, a.size()); } struct CallCounter { CallCounter() { default_constructions++; } CallCounter(const CallCounter&) { copy_constructions++; } CallCounter(CallCounter&&) { move_constructions++; } ~CallCounter() { destructions++; } static void reset_counters() { default_constructions = 0; copy_constructions = 0; move_constructions = 0; destructions = 0; } static int default_constructions; static int copy_constructions; static int move_constructions; static int destructions; }; int CallCounter::default_constructions = 0; int CallCounter::copy_constructions = 0; int CallCounter::move_constructions = 0; int CallCounter::destructions = 0; TEST(any, default_constructed_is_empty) { static_any<16> a; ASSERT_TRUE(a.empty()); } TEST(any, contructed_with_param_non_empty) { static_any<16> a(77); // will contain integer ASSERT_FALSE(a.empty()); } TEST(any, has) { static_any<16> a(77); // will contain integer ASSERT_TRUE(a.has<int>()); ASSERT_FALSE(a.has<double>()); } TEST(any, move_construct) { CallCounter::reset_counters(); CallCounter counter; static_any<16> a(std::move(counter)); ASSERT_EQ(1, CallCounter::default_constructions); ASSERT_EQ(0, CallCounter::copy_constructions); ASSERT_EQ(1, CallCounter::move_constructions); ASSERT_EQ(0, CallCounter::destructions); } TEST(any, copy_construct) { CallCounter::reset_counters(); CallCounter counter; static_any<16> a(counter); ASSERT_EQ(1, CallCounter::default_constructions); ASSERT_EQ(1, CallCounter::copy_constructions); ASSERT_EQ(0, CallCounter::move_constructions); ASSERT_EQ(0, CallCounter::destructions); } TEST(any, destruction) { CallCounter::reset_counters(); CallCounter counter; { static_any<16> a(counter); } ASSERT_EQ(1, CallCounter::destructions); } TEST(any, reset_destruction) { CallCounter::reset_counters(); CallCounter counter; static_any<16> a(counter); a.reset(); ASSERT_EQ(1, CallCounter::destructions); } TEST(any, copy_assignment) { CallCounter::reset_counters(); CallCounter counter; static_any<16> a(1); a = counter; ASSERT_EQ(1, CallCounter::default_constructions); ASSERT_EQ(1, CallCounter::copy_constructions); ASSERT_EQ(0, CallCounter::move_constructions); } TEST(any, move_assignment) { CallCounter::reset_counters(); CallCounter counter; static_any<16> a; a = std::move(counter); ASSERT_EQ(1, CallCounter::default_constructions); ASSERT_EQ(0, CallCounter::copy_constructions); ASSERT_EQ(1, CallCounter::move_constructions); } TEST(any, reassignment) { CallCounter::reset_counters(); CallCounter counter; static_any<16> a(counter); a = counter; ASSERT_EQ(1, CallCounter::default_constructions); ASSERT_EQ(2, CallCounter::copy_constructions); ASSERT_EQ(0, CallCounter::move_constructions); ASSERT_EQ(1, CallCounter::destructions); } TEST(any, not_empty_after_assignment) { static_any<16> a; ASSERT_TRUE(a.empty()); a = 7; ASSERT_FALSE(a.empty()); } TEST(any, different_type_after_assignment) { static_any<16> a(7); ASSERT_TRUE(a.has<int>()); ASSERT_FALSE(a.has<double>()); a = 3.14; ASSERT_FALSE(a.has<int>()); ASSERT_TRUE(a.has<double>()); } TEST(any, get_good_type) { static_any<16> a(7); auto i = a.get<int>(); ASSERT_EQ(7, i); } TEST(any, get_bad_type) { static_any<16> a(7); EXPECT_THROW(a.get<double>(), std::bad_cast); } TEST(any, get_empty) { static_any<16> a; EXPECT_THROW(a.get<double>(), std::bad_cast); } TEST(any, cast_empty) { static_any<16> a; EXPECT_THROW(any_cast<int>(a), std::bad_cast); } TEST(any, mutable_get) { static_any<16> a(7); a.get<int>() = 6; const static_any<16>& const_ref = a; auto i = const_ref.get<int>(); ASSERT_EQ(6, i); } TEST(any, any_to_any_copy_uninitialized) { static_any<16> a; static_any<16> b(a); ASSERT_TRUE(a.empty()); ASSERT_TRUE(b.empty()); } TEST(any, any_to_any_copy_construction) { static_any<16> a(7); static_any<16> b(a); ASSERT_EQ(7, a.get<int>()); ASSERT_EQ(7, b.get<int>()); } TEST(any, any_to_any_assignment) { static_any<32> a(std::string("Hello")); static_any<32> b; ASSERT_TRUE(b.empty()); b = a; ASSERT_FALSE(b.empty()); ASSERT_EQ("Hello", b.get<std::string>()); ASSERT_EQ("Hello", a.get<std::string>()); } TEST(any, any_to_any_move_construction) { static_any<32> a(std::string("Hello")); static_any<32> b = std::move(a); ASSERT_FALSE(a.empty()); ASSERT_FALSE(b.empty()); ASSERT_EQ("Hello", b.get<std::string>()); } TEST(any, any_to_bigger_any) { static_any<16> a(1); ASSERT_EQ(1, a.get<int>()); static_any<32> b(2); b = a; ASSERT_EQ(1, b.get<int>()); } TEST(any, any_to_bigger_any_copy) { static_any<16> a(1); ASSERT_EQ(1, a.get<int>()); static_any<32> b = a; ASSERT_EQ(1, b.get<int>()); } struct InitCtor { int x = 1; int y = 2; InitCtor() = default; InitCtor(int x, int y) : x(x), y(y) {} }; TEST(any, emplace_no_params) { static_any<32> a; a.emplace<InitCtor>(); ASSERT_FALSE(a.empty()); EXPECT_EQ(1, a.get<InitCtor>().x); EXPECT_EQ(2, a.get<InitCtor>().y); } TEST(any, emplace_params) { static_any<32> a; a.emplace<InitCtor>(77, 88); ASSERT_FALSE(a.empty()); EXPECT_EQ(77, a.get<InitCtor>().x); EXPECT_EQ(88, a.get<InitCtor>().y); } TEST(any, destroyed_after_emplace) { CallCounter::reset_counters(); { static_any<32> a; a.emplace<CallCounter>(); } EXPECT_EQ(1, CallCounter::default_constructions); EXPECT_EQ(1, CallCounter::destructions); } TEST(any, any_cast_pointer_correct_type) { static_any<16> a(7); ASSERT_EQ(7, *any_cast<int>(&a)); } TEST(any, any_cast_pointer_constness) { static_any<16> a(7); const auto* a2 = &a; auto* pv = any_cast<int>(&a); auto* pv2 = any_cast<int>(a2); ASSERT_FALSE(std::is_const<std::remove_pointer<decltype(pv)>::type>::value); ASSERT_TRUE(std::is_const<std::remove_pointer<decltype(pv2)>::type>::value); ASSERT_EQ(7, *pv); ASSERT_EQ(7, *pv2); } TEST(any, any_cast_pointer_wrong_type) { static_any<16> a(7); ASSERT_EQ(nullptr, any_cast<float>(&a)); } TEST(any, any_cast_reference_correct_type) { static_any<16> a(7); ASSERT_EQ(7, any_cast<int>(a)); } TEST(any, any_cast_reference_constness) { static_any<16> a(7); const auto& a2 = a; auto& pv = any_cast<int>(a); auto& pv2 = any_cast<int>(a2); ASSERT_FALSE(std::is_const<std::remove_reference<decltype(pv)>::type>::value); ASSERT_TRUE(std::is_const<std::remove_reference<decltype(pv2)>::type>::value); ASSERT_EQ(7, pv); ASSERT_EQ(7, pv2); } TEST(any, any_cast_reference_wrong_type) { static_any<16> a(7); EXPECT_THROW(any_cast<float>(a), bad_any_cast); } TEST(any, any_cast_reference_wrong_type_from_to) { static_any<16> a(7); try { auto f = any_cast<float>(a); FAIL(); ASSERT_EQ(.1234, f); // to avoid a warning, never reached } catch(bad_any_cast& ex) { ASSERT_EQ(typeid(int), ex.stored_type()); ASSERT_EQ(typeid(float), ex.target_type()); } } TEST(any, query_type) { static_any<32> a(7); ASSERT_EQ(typeid(int), a.type()); a = std::string("f00"); ASSERT_EQ(typeid(std::string), a.type()); } TEST(any, reset_empty) { static_any<16> a(7); ASSERT_FALSE(a.empty()); a.reset(); ASSERT_TRUE(a.empty()); } TEST(any, reset_has) { static_any<16> a(7); ASSERT_TRUE(a.has<int>()); a.reset(); ASSERT_FALSE(a.has<int>()); } TEST(any, type_identification_across_dll) { auto a = get_any_with_int(7); EXPECT_TRUE(a.has<int>()); EXPECT_FALSE(a.has<std::string>()); EXPECT_EQ(7, a.get<int>()); EXPECT_THROW(a.get<std::string>(), bad_any_cast); } TEST(any_t, simple) { static_any_t<16> a(7); ASSERT_EQ(7, a.get<int>()); } <commit_msg>Exception basic guarantees: unit tests move ctor<commit_after>#include "any.hpp" #include "dyn_lib.hpp" #include <gtest/gtest.h> struct A { explicit A(int i) : m_i(i) {} int m_i; }; TEST(any, readme_example) { static_any<32> a; // on g++ 5.x sizeof(std::string) is 32 static_assert(sizeof(a) == 32 + sizeof(std::ptrdiff_t), "impossible"); a = 1234; ASSERT_EQ(1234, a.get<int>()); a = std::string("Hello world"); ASSERT_EQ(std::string("Hello world"), a.get<std::string>()); struct A { explicit A(long i = 0, double d = .0) : i_(i), d_(d) {} long i_; double d_; }; a = A(12, .34); } TEST(any, test_sizeof) { static_any<16> a; ASSERT_EQ(16 + sizeof(std::ptrdiff_t), sizeof(a)); } TEST(any, capacity) { static_any<32> a; ASSERT_EQ(32, a.capacity()); a = std::string("hello world"); ASSERT_EQ(32, a.capacity()); a.reset(); ASSERT_EQ(32, a.capacity()); } TEST(any, size) { static_any<32> a; ASSERT_EQ(0, a.size()); a = 1234; ASSERT_EQ(sizeof(1234), a.size()); a = std::string("foobar"); ASSERT_EQ(sizeof(std::string), a.size()); a.reset(); ASSERT_EQ(0, a.size()); } struct CallCounter { CallCounter() { default_constructions++; } CallCounter(const CallCounter&) { copy_constructions++; } CallCounter(CallCounter&&) { move_constructions++; } ~CallCounter() { destructions++; } static void reset_counters() { default_constructions = 0; copy_constructions = 0; move_constructions = 0; destructions = 0; } static int default_constructions; static int copy_constructions; static int move_constructions; static int destructions; }; int CallCounter::default_constructions = 0; int CallCounter::copy_constructions = 0; int CallCounter::move_constructions = 0; int CallCounter::destructions = 0; TEST(any, default_constructed_is_empty) { static_any<16> a; ASSERT_TRUE(a.empty()); } TEST(any, contructed_with_param_non_empty) { static_any<16> a(77); // will contain integer ASSERT_FALSE(a.empty()); } TEST(any, has) { static_any<16> a(77); // will contain integer ASSERT_TRUE(a.has<int>()); ASSERT_FALSE(a.has<double>()); } TEST(any, move_construct) { CallCounter::reset_counters(); CallCounter counter; static_any<16> a(std::move(counter)); ASSERT_EQ(1, CallCounter::default_constructions); ASSERT_EQ(0, CallCounter::copy_constructions); ASSERT_EQ(1, CallCounter::move_constructions); ASSERT_EQ(0, CallCounter::destructions); } TEST(any, copy_construct) { CallCounter::reset_counters(); CallCounter counter; static_any<16> a(counter); ASSERT_EQ(1, CallCounter::default_constructions); ASSERT_EQ(1, CallCounter::copy_constructions); ASSERT_EQ(0, CallCounter::move_constructions); ASSERT_EQ(0, CallCounter::destructions); } TEST(any, destruction) { CallCounter::reset_counters(); CallCounter counter; { static_any<16> a(counter); } ASSERT_EQ(1, CallCounter::destructions); } TEST(any, reset_destruction) { CallCounter::reset_counters(); CallCounter counter; static_any<16> a(counter); a.reset(); ASSERT_EQ(1, CallCounter::destructions); } TEST(any, copy_assignment) { CallCounter::reset_counters(); CallCounter counter; static_any<16> a(1); a = counter; ASSERT_EQ(1, CallCounter::default_constructions); ASSERT_EQ(1, CallCounter::copy_constructions); ASSERT_EQ(0, CallCounter::move_constructions); } TEST(any, move_assignment) { CallCounter::reset_counters(); CallCounter counter; static_any<16> a; a = std::move(counter); ASSERT_EQ(1, CallCounter::default_constructions); ASSERT_EQ(0, CallCounter::copy_constructions); ASSERT_EQ(1, CallCounter::move_constructions); } TEST(any, reassignment) { CallCounter::reset_counters(); CallCounter counter; static_any<16> a(counter); a = counter; ASSERT_EQ(1, CallCounter::default_constructions); ASSERT_EQ(2, CallCounter::copy_constructions); ASSERT_EQ(0, CallCounter::move_constructions); ASSERT_EQ(1, CallCounter::destructions); } TEST(any, not_empty_after_assignment) { static_any<16> a; ASSERT_TRUE(a.empty()); a = 7; ASSERT_FALSE(a.empty()); } TEST(any, different_type_after_assignment) { static_any<16> a(7); ASSERT_TRUE(a.has<int>()); ASSERT_FALSE(a.has<double>()); a = 3.14; ASSERT_FALSE(a.has<int>()); ASSERT_TRUE(a.has<double>()); } TEST(any, get_good_type) { static_any<16> a(7); auto i = a.get<int>(); ASSERT_EQ(7, i); } TEST(any, get_bad_type) { static_any<16> a(7); EXPECT_THROW(a.get<double>(), std::bad_cast); } TEST(any, get_empty) { static_any<16> a; EXPECT_THROW(a.get<double>(), std::bad_cast); } TEST(any, cast_empty) { static_any<16> a; EXPECT_THROW(any_cast<int>(a), std::bad_cast); } TEST(any, mutable_get) { static_any<16> a(7); a.get<int>() = 6; const static_any<16>& const_ref = a; auto i = const_ref.get<int>(); ASSERT_EQ(6, i); } TEST(any, any_to_any_copy_uninitialized) { static_any<16> a; static_any<16> b(a); ASSERT_TRUE(a.empty()); ASSERT_TRUE(b.empty()); } TEST(any, any_to_any_copy_construction) { static_any<16> a(7); static_any<16> b(a); ASSERT_EQ(7, a.get<int>()); ASSERT_EQ(7, b.get<int>()); } TEST(any, any_to_any_assignment) { static_any<32> a(std::string("Hello")); static_any<32> b; ASSERT_TRUE(b.empty()); b = a; ASSERT_FALSE(b.empty()); ASSERT_EQ("Hello", b.get<std::string>()); ASSERT_EQ("Hello", a.get<std::string>()); } TEST(any, any_to_any_move_construction) { static_any<32> a(std::string("Hello")); static_any<32> b = std::move(a); ASSERT_FALSE(a.empty()); ASSERT_FALSE(b.empty()); ASSERT_EQ("Hello", b.get<std::string>()); } TEST(any, any_to_bigger_any) { static_any<16> a(1); ASSERT_EQ(1, a.get<int>()); static_any<32> b(2); b = a; ASSERT_EQ(1, b.get<int>()); } TEST(any, any_to_bigger_any_copy) { static_any<16> a(1); ASSERT_EQ(1, a.get<int>()); static_any<32> b = a; ASSERT_EQ(1, b.get<int>()); } struct InitCtor { int x = 1; int y = 2; InitCtor() = default; InitCtor(int x, int y) : x(x), y(y) {} }; TEST(any, emplace_no_params) { static_any<32> a; a.emplace<InitCtor>(); ASSERT_FALSE(a.empty()); EXPECT_EQ(1, a.get<InitCtor>().x); EXPECT_EQ(2, a.get<InitCtor>().y); } TEST(any, emplace_params) { static_any<32> a; a.emplace<InitCtor>(77, 88); ASSERT_FALSE(a.empty()); EXPECT_EQ(77, a.get<InitCtor>().x); EXPECT_EQ(88, a.get<InitCtor>().y); } TEST(any, destroyed_after_emplace) { CallCounter::reset_counters(); { static_any<32> a; a.emplace<CallCounter>(); } EXPECT_EQ(1, CallCounter::default_constructions); EXPECT_EQ(1, CallCounter::destructions); } TEST(any, any_cast_pointer_correct_type) { static_any<16> a(7); ASSERT_EQ(7, *any_cast<int>(&a)); } TEST(any, any_cast_pointer_constness) { static_any<16> a(7); const auto* a2 = &a; auto* pv = any_cast<int>(&a); auto* pv2 = any_cast<int>(a2); ASSERT_FALSE(std::is_const<std::remove_pointer<decltype(pv)>::type>::value); ASSERT_TRUE(std::is_const<std::remove_pointer<decltype(pv2)>::type>::value); ASSERT_EQ(7, *pv); ASSERT_EQ(7, *pv2); } TEST(any, any_cast_pointer_wrong_type) { static_any<16> a(7); ASSERT_EQ(nullptr, any_cast<float>(&a)); } TEST(any, any_cast_reference_correct_type) { static_any<16> a(7); ASSERT_EQ(7, any_cast<int>(a)); } TEST(any, any_cast_reference_constness) { static_any<16> a(7); const auto& a2 = a; auto& pv = any_cast<int>(a); auto& pv2 = any_cast<int>(a2); ASSERT_FALSE(std::is_const<std::remove_reference<decltype(pv)>::type>::value); ASSERT_TRUE(std::is_const<std::remove_reference<decltype(pv2)>::type>::value); ASSERT_EQ(7, pv); ASSERT_EQ(7, pv2); } TEST(any, any_cast_reference_wrong_type) { static_any<16> a(7); EXPECT_THROW(any_cast<float>(a), bad_any_cast); } TEST(any, any_cast_reference_wrong_type_from_to) { static_any<16> a(7); try { auto f = any_cast<float>(a); FAIL(); ASSERT_EQ(.1234, f); // to avoid a warning, never reached } catch(bad_any_cast& ex) { ASSERT_EQ(typeid(int), ex.stored_type()); ASSERT_EQ(typeid(float), ex.target_type()); } } TEST(any, query_type) { static_any<32> a(7); ASSERT_EQ(typeid(int), a.type()); a = std::string("f00"); ASSERT_EQ(typeid(std::string), a.type()); } TEST(any, reset_empty) { static_any<16> a(7); ASSERT_FALSE(a.empty()); a.reset(); ASSERT_TRUE(a.empty()); } TEST(any, reset_has) { static_any<16> a(7); ASSERT_TRUE(a.has<int>()); a.reset(); ASSERT_FALSE(a.has<int>()); } TEST(any, type_identification_across_dll) { auto a = get_any_with_int(7); EXPECT_TRUE(a.has<int>()); EXPECT_FALSE(a.has<std::string>()); EXPECT_EQ(7, a.get<int>()); EXPECT_THROW(a.get<std::string>(), bad_any_cast); } TEST(any_t, simple) { static_any_t<16> a(7); ASSERT_EQ(7, a.get<int>()); } struct Unsafe { Unsafe() =default; Unsafe(const Unsafe&) { throw 123; } }; TEST(any_exception, move) { static_any<16> a; EXPECT_THROW(a = Unsafe(), int); EXPECT_TRUE(a.empty()); } <|endoftext|>
<commit_before>/***************************************************************************** * Project: RooFit * * * * This code was autogenerated by RooClassFactory * *****************************************************************************/ /** \class RooParamHistFunc * \ingroup Roofit * A histogram function that assigns scale parameters to every bin. Instead of the bare bin contents, * it therefore yields: * \f[ * \gamma_{i} * \mathrm{bin}_i * \f] * * The \f$ \gamma_i \f$ can therefore be used to parametrise statistical uncertainties of the histogram * template. In conjuction with a constraint term, this can be used to implement the Barlow-Beeston method. * The constraint can be implemented using RooHistConstraint. * * See also the tutorial rf709_BarlowBeeston.C */ #include "Riostream.h" #include "RooParamHistFunc.h" #include "RooAbsReal.h" #include "RooAbsCategory.h" #include "RooRealVar.h" #include "RooHelpers.h" #include <math.h> #include "TMath.h" using namespace std ; ClassImp(RooParamHistFunc); //////////////////////////////////////////////////////////////////////////////// /// Populate x with observables RooParamHistFunc::RooParamHistFunc(const char *name, const char *title, RooDataHist& dh, Bool_t paramRelative) : RooAbsReal(name,title), _x("x","x",this), _p("p","p",this), _dh(dh), _relParam(paramRelative) { _x.add(*_dh.get()) ; // Now populate p with parameters RooArgSet allVars ; for (Int_t i=0 ; i<_dh.numEntries() ; i++) { _dh.get(i) ; const char* vname = Form("%s_gamma_bin_%i",GetName(),i) ; RooRealVar* var = new RooRealVar(vname,vname,0,1000) ; var->setVal(_relParam ? 1 : _dh.weight()) ; var->setError(_relParam ? 1 / sqrt(_dh.weight()) : sqrt(_dh.weight())); var->setConstant(kTRUE) ; allVars.add(*var) ; _p.add(*var) ; } addOwnedComponents(allVars) ; } //////////////////////////////////////////////////////////////////////////////// /// Populate x with observables RooParamHistFunc::RooParamHistFunc(const char *name, const char *title, const RooAbsArg& /*x*/, RooDataHist& dh, Bool_t paramRelative) : RooAbsReal(name,title), _x("x","x",this), _p("p","p",this), _dh(dh), _relParam(paramRelative) { _x.add(*_dh.get()) ; // Now populate p with parameters RooArgSet allVars ; for (Int_t i=0 ; i<_dh.numEntries() ; i++) { _dh.get(i) ; const char* vname = Form("%s_gamma_bin_%i",GetName(),i) ; RooRealVar* var = new RooRealVar(vname,vname,0,1000) ; var->setVal(_relParam ? 1 : _dh.weight()) ; var->setError(_relParam ? 1 / sqrt(_dh.weight()) : sqrt(_dh.weight())); var->setConstant(kTRUE) ; allVars.add(*var) ; _p.add(*var) ; } addOwnedComponents(allVars) ; } //////////////////////////////////////////////////////////////////////////////// RooParamHistFunc::RooParamHistFunc(const char *name, const char *title, RooDataHist& dh, const RooParamHistFunc& paramSource, Bool_t paramRelative) : RooAbsReal(name,title), _x("x","x",this), _p("p","p",this), _dh(dh), _relParam(paramRelative) { // Populate x with observables _x.add(*_dh.get()) ; // Now populate p with existing parameters _p.add(paramSource._p) ; } //////////////////////////////////////////////////////////////////////////////// RooParamHistFunc::RooParamHistFunc(const RooParamHistFunc& other, const char* name) : RooAbsReal(other,name), _x("x",this,other._x), _p("p",this,other._p), _dh(other._dh), _relParam(other._relParam) { } //////////////////////////////////////////////////////////////////////////////// Double_t RooParamHistFunc::evaluate() const { Int_t idx = ((RooDataHist&)_dh).getIndex(_x,kTRUE) ; Double_t ret = ((RooAbsReal*)_p.at(idx))->getVal() ; if (_relParam) { Double_t nom = getNominal(idx) ; ret *= nom ; } return ret ; } //////////////////////////////////////////////////////////////////////////////// Double_t RooParamHistFunc::getActual(Int_t ibin) { return ((RooAbsReal&)_p[ibin]).getVal() ; } //////////////////////////////////////////////////////////////////////////////// void RooParamHistFunc::setActual(Int_t ibin, Double_t newVal) { ((RooRealVar&)_p[ibin]).setVal(newVal) ; } //////////////////////////////////////////////////////////////////////////////// Double_t RooParamHistFunc::getNominal(Int_t ibin) const { _dh.get(ibin) ; return _dh.weight() ; } //////////////////////////////////////////////////////////////////////////////// Double_t RooParamHistFunc::getNominalError(Int_t ibin) const { _dh.get(ibin) ; return _dh.weightError() ; } //////////////////////////////////////////////////////////////////////////////// /// Return sampling hint for making curves of (projections) of this function /// as the recursive division strategy of RooCurve cannot deal efficiently /// with the vertical lines that occur in a non-interpolated histogram list<Double_t>* RooParamHistFunc::plotSamplingHint(RooAbsRealLValue& obs, Double_t xlo, Double_t xhi) const { // Check that observable is in dataset, if not no hint is generated RooAbsLValue* lvarg = dynamic_cast<RooAbsLValue*>(_dh.get()->find(obs.GetName())) ; if (!lvarg) { return 0 ; } // Retrieve position of all bin boundaries const RooAbsBinning* binning = lvarg->getBinningPtr(0) ; Double_t* boundaries = binning->array() ; list<Double_t>* hint = new list<Double_t> ; // Widen range slightly xlo = xlo - 0.01*(xhi-xlo) ; xhi = xhi + 0.01*(xhi-xlo) ; Double_t delta = (xhi-xlo)*1e-8 ; // Construct array with pairs of points positioned epsilon to the left and // right of the bin boundaries for (Int_t i=0 ; i<binning->numBoundaries() ; i++) { if (boundaries[i]>=xlo && boundaries[i]<=xhi) { hint->push_back(boundaries[i]-delta) ; hint->push_back(boundaries[i]+delta) ; } } return hint ; } //////////////////////////////////////////////////////////////////////////////// /// Return sampling hint for making curves of (projections) of this function /// as the recursive division strategy of RooCurve cannot deal efficiently /// with the vertical lines that occur in a non-interpolated histogram std::list<Double_t>* RooParamHistFunc::binBoundaries(RooAbsRealLValue& obs, Double_t xlo, Double_t xhi) const { // Check that observable is in dataset, if not no hint is generated RooAbsLValue* lvarg = dynamic_cast<RooAbsLValue*>(_dh.get()->find(obs.GetName())) ; if (!lvarg) { return 0 ; } // Retrieve position of all bin boundaries const RooAbsBinning* binning = lvarg->getBinningPtr(0) ; Double_t* boundaries = binning->array() ; list<Double_t>* hint = new list<Double_t> ; // Construct array with pairs of points positioned epsilon to the left and // right of the bin boundaries for (Int_t i=0 ; i<binning->numBoundaries() ; i++) { if (boundaries[i]>=xlo && boundaries[i]<=xhi) { hint->push_back(boundaries[i]) ; } } return hint ; } //////////////////////////////////////////////////////////////////////////////// /// Advertise that all integrals can be handled internally. Int_t RooParamHistFunc::getAnalyticalIntegralWN(RooArgSet& allVars, RooArgSet& analVars, const RooArgSet* /*normSet*/, const char* /*rangeName*/) const { // Simplest scenario, integrate over all dependents RooAbsCollection *allVarsCommon = allVars.selectCommon(_x) ; Bool_t intAllObs = (allVarsCommon->getSize()==_x.getSize()) ; delete allVarsCommon ; if (intAllObs && matchArgs(allVars,analVars,_x)) { return 1 ; } return 0 ; } //////////////////////////////////////////////////////////////////////////////// /// Implement analytical integrations by doing appropriate weighting from component integrals /// functions to integrators of components Double_t RooParamHistFunc::analyticalIntegralWN(Int_t code, const RooArgSet* /*normSet2*/,const char* rangeName) const { // Supports only the scenario of integration over all dependents R__ASSERT(code==1) ; // The logic for summing over the histogram is borrowed from RooHistPdf with some differences: // // - a lambda function is used to inject the parameters for bin scaling into the RooDataHist::sum method // // - for simplicity, there is no check for the possibility of full-range integration with another overload of // RooDataHist::sum std::map<const RooAbsArg*, std::pair<double, double> > ranges; for (const auto obs : _x) { ranges[obs] = RooHelpers::getRangeOrBinningInterval(obs, rangeName); } auto getBinScale = [&](int iBin){ return static_cast<const RooAbsReal&>(_p[iBin]).getVal(); }; auto integrationSet = _dh.get(); RooArgSet sliceSet{}; return const_cast<RooDataHist&>(_dh).sum(*integrationSet, sliceSet, true, false, ranges, getBinScale); } <commit_msg>[RF] Fix the integration of a cloned RooParamHistFunc with range<commit_after>/***************************************************************************** * Project: RooFit * * * * This code was autogenerated by RooClassFactory * *****************************************************************************/ /** \class RooParamHistFunc * \ingroup Roofit * A histogram function that assigns scale parameters to every bin. Instead of the bare bin contents, * it therefore yields: * \f[ * \gamma_{i} * \mathrm{bin}_i * \f] * * The \f$ \gamma_i \f$ can therefore be used to parametrise statistical uncertainties of the histogram * template. In conjuction with a constraint term, this can be used to implement the Barlow-Beeston method. * The constraint can be implemented using RooHistConstraint. * * See also the tutorial rf709_BarlowBeeston.C */ #include "Riostream.h" #include "RooParamHistFunc.h" #include "RooAbsReal.h" #include "RooAbsCategory.h" #include "RooRealVar.h" #include "RooHelpers.h" #include <math.h> #include "TMath.h" using namespace std ; ClassImp(RooParamHistFunc); //////////////////////////////////////////////////////////////////////////////// /// Populate x with observables RooParamHistFunc::RooParamHistFunc(const char *name, const char *title, RooDataHist& dh, Bool_t paramRelative) : RooAbsReal(name,title), _x("x","x",this), _p("p","p",this), _dh(dh), _relParam(paramRelative) { _x.add(*_dh.get()) ; // Now populate p with parameters RooArgSet allVars ; for (Int_t i=0 ; i<_dh.numEntries() ; i++) { _dh.get(i) ; const char* vname = Form("%s_gamma_bin_%i",GetName(),i) ; RooRealVar* var = new RooRealVar(vname,vname,0,1000) ; var->setVal(_relParam ? 1 : _dh.weight()) ; var->setError(_relParam ? 1 / sqrt(_dh.weight()) : sqrt(_dh.weight())); var->setConstant(kTRUE) ; allVars.add(*var) ; _p.add(*var) ; } addOwnedComponents(allVars) ; } //////////////////////////////////////////////////////////////////////////////// /// Populate x with observables RooParamHistFunc::RooParamHistFunc(const char *name, const char *title, const RooAbsArg& /*x*/, RooDataHist& dh, Bool_t paramRelative) : RooAbsReal(name,title), _x("x","x",this), _p("p","p",this), _dh(dh), _relParam(paramRelative) { _x.add(*_dh.get()) ; // Now populate p with parameters RooArgSet allVars ; for (Int_t i=0 ; i<_dh.numEntries() ; i++) { _dh.get(i) ; const char* vname = Form("%s_gamma_bin_%i",GetName(),i) ; RooRealVar* var = new RooRealVar(vname,vname,0,1000) ; var->setVal(_relParam ? 1 : _dh.weight()) ; var->setError(_relParam ? 1 / sqrt(_dh.weight()) : sqrt(_dh.weight())); var->setConstant(kTRUE) ; allVars.add(*var) ; _p.add(*var) ; } addOwnedComponents(allVars) ; } //////////////////////////////////////////////////////////////////////////////// RooParamHistFunc::RooParamHistFunc(const char *name, const char *title, RooDataHist& dh, const RooParamHistFunc& paramSource, Bool_t paramRelative) : RooAbsReal(name,title), _x("x","x",this), _p("p","p",this), _dh(dh), _relParam(paramRelative) { // Populate x with observables _x.add(*_dh.get()) ; // Now populate p with existing parameters _p.add(paramSource._p) ; } //////////////////////////////////////////////////////////////////////////////// RooParamHistFunc::RooParamHistFunc(const RooParamHistFunc& other, const char* name) : RooAbsReal(other,name), _x("x",this,other._x), _p("p",this,other._p), _dh(other._dh), _relParam(other._relParam) { } //////////////////////////////////////////////////////////////////////////////// Double_t RooParamHistFunc::evaluate() const { Int_t idx = ((RooDataHist&)_dh).getIndex(_x,kTRUE) ; Double_t ret = ((RooAbsReal*)_p.at(idx))->getVal() ; if (_relParam) { Double_t nom = getNominal(idx) ; ret *= nom ; } return ret ; } //////////////////////////////////////////////////////////////////////////////// Double_t RooParamHistFunc::getActual(Int_t ibin) { return ((RooAbsReal&)_p[ibin]).getVal() ; } //////////////////////////////////////////////////////////////////////////////// void RooParamHistFunc::setActual(Int_t ibin, Double_t newVal) { ((RooRealVar&)_p[ibin]).setVal(newVal) ; } //////////////////////////////////////////////////////////////////////////////// Double_t RooParamHistFunc::getNominal(Int_t ibin) const { _dh.get(ibin) ; return _dh.weight() ; } //////////////////////////////////////////////////////////////////////////////// Double_t RooParamHistFunc::getNominalError(Int_t ibin) const { _dh.get(ibin) ; return _dh.weightError() ; } //////////////////////////////////////////////////////////////////////////////// /// Return sampling hint for making curves of (projections) of this function /// as the recursive division strategy of RooCurve cannot deal efficiently /// with the vertical lines that occur in a non-interpolated histogram list<Double_t>* RooParamHistFunc::plotSamplingHint(RooAbsRealLValue& obs, Double_t xlo, Double_t xhi) const { // Check that observable is in dataset, if not no hint is generated RooAbsLValue* lvarg = dynamic_cast<RooAbsLValue*>(_dh.get()->find(obs.GetName())) ; if (!lvarg) { return 0 ; } // Retrieve position of all bin boundaries const RooAbsBinning* binning = lvarg->getBinningPtr(0) ; Double_t* boundaries = binning->array() ; list<Double_t>* hint = new list<Double_t> ; // Widen range slightly xlo = xlo - 0.01*(xhi-xlo) ; xhi = xhi + 0.01*(xhi-xlo) ; Double_t delta = (xhi-xlo)*1e-8 ; // Construct array with pairs of points positioned epsilon to the left and // right of the bin boundaries for (Int_t i=0 ; i<binning->numBoundaries() ; i++) { if (boundaries[i]>=xlo && boundaries[i]<=xhi) { hint->push_back(boundaries[i]-delta) ; hint->push_back(boundaries[i]+delta) ; } } return hint ; } //////////////////////////////////////////////////////////////////////////////// /// Return sampling hint for making curves of (projections) of this function /// as the recursive division strategy of RooCurve cannot deal efficiently /// with the vertical lines that occur in a non-interpolated histogram std::list<Double_t>* RooParamHistFunc::binBoundaries(RooAbsRealLValue& obs, Double_t xlo, Double_t xhi) const { // Check that observable is in dataset, if not no hint is generated RooAbsLValue* lvarg = dynamic_cast<RooAbsLValue*>(_dh.get()->find(obs.GetName())) ; if (!lvarg) { return 0 ; } // Retrieve position of all bin boundaries const RooAbsBinning* binning = lvarg->getBinningPtr(0) ; Double_t* boundaries = binning->array() ; list<Double_t>* hint = new list<Double_t> ; // Construct array with pairs of points positioned epsilon to the left and // right of the bin boundaries for (Int_t i=0 ; i<binning->numBoundaries() ; i++) { if (boundaries[i]>=xlo && boundaries[i]<=xhi) { hint->push_back(boundaries[i]) ; } } return hint ; } //////////////////////////////////////////////////////////////////////////////// /// Advertise that all integrals can be handled internally. Int_t RooParamHistFunc::getAnalyticalIntegralWN(RooArgSet& allVars, RooArgSet& analVars, const RooArgSet* /*normSet*/, const char* /*rangeName*/) const { // Simplest scenario, integrate over all dependents RooAbsCollection *allVarsCommon = allVars.selectCommon(_x) ; Bool_t intAllObs = (allVarsCommon->getSize()==_x.getSize()) ; delete allVarsCommon ; if (intAllObs && matchArgs(allVars,analVars,_x)) { return 1 ; } return 0 ; } //////////////////////////////////////////////////////////////////////////////// /// Implement analytical integrations by doing appropriate weighting from component integrals /// functions to integrators of components Double_t RooParamHistFunc::analyticalIntegralWN(Int_t code, const RooArgSet* /*normSet2*/,const char* rangeName) const { // Supports only the scenario of integration over all dependents R__ASSERT(code==1) ; // The logic for summing over the histogram is borrowed from RooHistPdf with some differences: // // - a lambda function is used to inject the parameters for bin scaling into the RooDataHist::sum method // // - for simplicity, there is no check for the possibility of full-range integration with another overload of // RooDataHist::sum std::map<const RooAbsArg*, std::pair<double, double> > ranges; for (const auto obs : _x) { ranges[obs] = RooHelpers::getRangeOrBinningInterval(obs, rangeName); } auto getBinScale = [&](int iBin){ return static_cast<const RooAbsReal&>(_p[iBin]).getVal(); }; RooArgSet sliceSet{}; return const_cast<RooDataHist&>(_dh).sum(_x, sliceSet, true, false, ranges, getBinScale); } <|endoftext|>
<commit_before>/* * ChronoGraph.cpp * * Copyright (C) 2010 by Universitaet Stuttgart (VIS). * Alle Rechte vorbehalten. */ #include "stdafx.h" #define _USE_MATH_DEFINES #include "vislib/graphics/gl/IncludeAllGL.h" #include "mmcore/view/special/ChronoGraph.h" #include "mmcore/CoreInstance.h" #include "vislib/math/mathfunctions.h" #include <cmath> using namespace megamol::core; /* * view::special::ChronoGraph::ChronoGraph */ view::special::ChronoGraph::ChronoGraph() : view::Renderer2DModule() { // intentionally empty } /* * view::special::ChronoGraph::~ChronoGraph */ view::special::ChronoGraph::~ChronoGraph() { this->Release(); } /* * view::special::ChronoGraph::create */ bool view::special::ChronoGraph::create(void) { // intentionally empty return true; } /* * view::special::ChronoGraph::GetExtents */ bool view::special::ChronoGraph::GetExtents(view::CallRender2D& call) { call.SetBoundingBox(-1.0f, -1.0f, 1.0f, 1.0f); return true; } /* * view::special::ChronoGraph::Render */ bool view::special::ChronoGraph::Render(view::CallRender2D& call) { ::glEnable(GL_LINE_SMOOTH); ::glEnable(GL_BLEND); ::glBlendFunc(GL_SRC_ALPHA, GL_ONE); float time = static_cast<float>(call.InstanceTime()); this->renderInfoGrid(time, call.GetBoundingBox().Left(), call.GetBoundingBox().Bottom(), call.GetBoundingBox().Width(), call.GetBoundingBox().Height()); this->renderInfoCircle(time, call.GetBoundingBox().Left(), call.GetBoundingBox().Bottom(), call.GetBoundingBox().Width(), call.GetBoundingBox().Height()); this->renderInfoCircle(time, -1.0f, -1.0f, 2.0f, 2.0f); ::glDisable(GL_LINE_SMOOTH); ::glDisable(GL_BLEND); return true; } /* * view::special::ChronoGraph::release */ void view::special::ChronoGraph::release(void) { // intentionally empty } /* * view::special::ChronoGraph::renderInfoGrid */ void view::special::ChronoGraph::renderInfoGrid(float time, float x, float y, float w, float h) { const int steps = 10; float a; ::glEnable(GL_LINE_SMOOTH); ::glLineWidth(1.2f); ::glColor4ub(255, 255, 255, 64); ::glBegin(GL_LINES); for (int i = 0; i <= steps; i++){ a = static_cast<float>(i) / static_cast<float>(steps); ::glVertex2f(x, y + h * a); ::glVertex2f(x + w, y + h * a); ::glVertex2f(x + w * a, y); ::glVertex2f(x + w * a, y + h); } ::glEnd(); ::glDisable(GL_LINE_SMOOTH); ::glLineWidth(1.0f); ::glBegin(GL_LINES); a = ::fabsf(::fmodf(time, 20.0f) * 0.1f - 1.0f); ::glColor4ub(255, 255, 255, 191); ::glVertex2f(x, y + h * a); ::glVertex2f(x + w, y + h * a); ::glVertex2f(x + w * a, y); ::glVertex2f(x + w * a, y + h); ::glEnd(); } /* * view::special::ChronoGraph::renderInfoCircle */ void view::special::ChronoGraph::renderInfoCircle(float time, float x, float y, float w, float h) { const int steps = 100; float a, cx, cy, px, py; float rad = 0.5f * vislib::math::Min(::fabs(w), ::fabs(h)); ::glEnable(GL_LINE_SMOOTH); ::glLineWidth(1.2f); ::glColor4ub(255, 255, 255, 64); ::glBegin(GL_LINE_LOOP); for (int i = 0; i < steps; i++){ a = 2.0f * static_cast<float>(M_PI) * static_cast<float>(i) / static_cast<float>(steps); ::glVertex2f(x + w * 0.5f + rad * ::cosf(a), y + h * 0.5f + rad * ::sinf(a)); } ::glEnd(); ::glBegin(GL_LINES); //rad = 0.5f * ::sqrtf(w * w + h * h); ::glColor4ub(255, 255, 255, 191); a = -2.0f * static_cast<float>(M_PI) * 0.01f * ::fmodf(time, 100.0f); w *= 0.5f; h *= 0.5f; cx = x + w; cy = y + h; ::glVertex2f(cx, cy); px = rad * ::cosf(a); py = rad * ::sinf(a); if (::abs(px) > w) { rad = ::abs(w / ::cosf(a)); px = rad * ::cosf(a); py = rad * ::sinf(a); } if (::abs(py) > h) { rad = ::abs(h / ::sinf(a)); px = rad * ::cosf(a); py = rad * ::sinf(a); } ::glVertex2f(cx + px, cy + py); ::glEnd(); ::glDisable(GL_LINE_SMOOTH); } <commit_msg>trying to code around current gcc features<commit_after>/* * ChronoGraph.cpp * * Copyright (C) 2010 by Universitaet Stuttgart (VIS). * Alle Rechte vorbehalten. */ #include "stdafx.h" #define _USE_MATH_DEFINES #include "vislib/graphics/gl/IncludeAllGL.h" #include "mmcore/view/special/ChronoGraph.h" #include "mmcore/CoreInstance.h" #include "vislib/math/mathfunctions.h" #include <cmath> using namespace megamol::core; /* * view::special::ChronoGraph::ChronoGraph */ view::special::ChronoGraph::ChronoGraph() : view::Renderer2DModule() { // intentionally empty } /* * view::special::ChronoGraph::~ChronoGraph */ view::special::ChronoGraph::~ChronoGraph() { this->Release(); } /* * view::special::ChronoGraph::create */ bool view::special::ChronoGraph::create(void) { // intentionally empty return true; } /* * view::special::ChronoGraph::GetExtents */ bool view::special::ChronoGraph::GetExtents(view::CallRender2D& call) { call.SetBoundingBox(-1.0f, -1.0f, 1.0f, 1.0f); return true; } /* * view::special::ChronoGraph::Render */ bool view::special::ChronoGraph::Render(view::CallRender2D& call) { ::glEnable(GL_LINE_SMOOTH); ::glEnable(GL_BLEND); ::glBlendFunc(GL_SRC_ALPHA, GL_ONE); float time = static_cast<float>(call.InstanceTime()); this->renderInfoGrid(time, call.GetBoundingBox().Left(), call.GetBoundingBox().Bottom(), call.GetBoundingBox().Width(), call.GetBoundingBox().Height()); this->renderInfoCircle(time, call.GetBoundingBox().Left(), call.GetBoundingBox().Bottom(), call.GetBoundingBox().Width(), call.GetBoundingBox().Height()); this->renderInfoCircle(time, -1.0f, -1.0f, 2.0f, 2.0f); ::glDisable(GL_LINE_SMOOTH); ::glDisable(GL_BLEND); return true; } /* * view::special::ChronoGraph::release */ void view::special::ChronoGraph::release(void) { // intentionally empty } /* * view::special::ChronoGraph::renderInfoGrid */ void view::special::ChronoGraph::renderInfoGrid(float time, float x, float y, float w, float h) { const int steps = 10; float a; ::glEnable(GL_LINE_SMOOTH); ::glLineWidth(1.2f); ::glColor4ub(255, 255, 255, 64); ::glBegin(GL_LINES); for (int i = 0; i <= steps; i++){ a = static_cast<float>(i) / static_cast<float>(steps); ::glVertex2f(x, y + h * a); ::glVertex2f(x + w, y + h * a); ::glVertex2f(x + w * a, y); ::glVertex2f(x + w * a, y + h); } ::glEnd(); ::glDisable(GL_LINE_SMOOTH); ::glLineWidth(1.0f); ::glBegin(GL_LINES); a = ::fabsf(::fmodf(time, 20.0f) * 0.1f - 1.0f); ::glColor4ub(255, 255, 255, 191); ::glVertex2f(x, y + h * a); ::glVertex2f(x + w, y + h * a); ::glVertex2f(x + w * a, y); ::glVertex2f(x + w * a, y + h); ::glEnd(); } /* * view::special::ChronoGraph::renderInfoCircle */ void view::special::ChronoGraph::renderInfoCircle(float time, float x, float y, float w, float h) { const int steps = 100; float a, cx, cy, px, py; float rad = 0.5f * vislib::math::Min(::fabs(w), ::fabs(h)); ::glEnable(GL_LINE_SMOOTH); ::glLineWidth(1.2f); ::glColor4ub(255, 255, 255, 64); ::glBegin(GL_LINE_LOOP); for (int i = 0; i < steps; i++){ a = 2.0f * static_cast<float>(M_PI) * static_cast<float>(i) / static_cast<float>(steps); ::glVertex2f(x + w * 0.5f + rad * ::cosf(a), y + h * 0.5f + rad * ::sinf(a)); } ::glEnd(); ::glBegin(GL_LINES); //rad = 0.5f * ::sqrtf(w * w + h * h); ::glColor4ub(255, 255, 255, 191); a = -2.0f * static_cast<float>(M_PI) * 0.01f * ::fmodf(time, 100.0f); w *= 0.5f; h *= 0.5f; cx = x + w; cy = y + h; ::glVertex2f(cx, cy); px = rad * ::cosf(a); py = rad * ::sinf(a); if (std::abs(px) > w) { rad = std::abs(w / ::cosf(a)); px = rad * ::cosf(a); py = rad * ::sinf(a); } if (std::abs(py) > h) { rad = std::abs(h / ::sinf(a)); px = rad * ::cosf(a); py = rad * ::sinf(a); } ::glVertex2f(cx + px, cy + py); ::glEnd(); ::glDisable(GL_LINE_SMOOTH); } <|endoftext|>
<commit_before>/** * Conflicting Intervals/Appointments (Google) * O(nlogn) solution to count conflicts (sorting + binary search) * O(n**2) for printing all possible conflicting pairs */ #include <bits/stdc++.h> // using GCC/G++ #include "custom/prettyprint.hpp" // G++11 only using namespace std; struct Interval { int index, start, end; }; ostream& operator << (ostream &stream, const Interval &it) { return stream << "[#" << it.index << ": " << it.start << " to " << it.end << "]"; } vector<pair<Interval, Interval>> conflictingAppointments(vector<Interval> &appointments) { vector<pair<Interval, Interval>> result; auto comp = [](const Interval &a, const Interval &b) -> bool { return a.start == b.start ? a.index < b.index : a.start < b.start; }; sort(appointments.begin(), appointments.end(), comp); for(int i=0; i<appointments.size(); i++) { int lo = i+1, hi = appointments.size()-1, curr; while(lo <= hi) { int mid = lo + (hi-lo)/2; if(appointments[mid].start >= appointments[i].end) hi = mid-1; else curr = mid, lo = mid + 1; } for(int j = i+1; j <= curr; j++) result.emplace_back(appointments[i], appointments[j]); } return result; } int main() { vector<Interval> appointments = { {0, 1, 5}, {1, 3, 7}, {2, 2, 6}, {3, 10, 15}, {4, 5, 6}, {5, 4, 100} }; cout << "Appointments are: " << appointments << endl; cout << "Conflicting appointments are:" << endl; for(auto&& tup: conflictingAppointments(appointments)) cout << tup.first << " conflicts with " << tup.second << endl; return 0; } <commit_msg>Some quick fixes.<commit_after>/** * Conflicting Intervals/Appointments (Google) * O(nlogn) solution to count conflicts (sorting + binary search) * O(n**2) for printing all possible conflicting pairs */ #include <bits/stdc++.h> // using GCC/G++ #include "custom/prettyprint.hpp" // G++11 only using namespace std; struct Interval { int index, start, end; }; ostream& operator << (ostream &stream, const Interval &it) { return stream << "[#" << it.index << ": " << it.start << " to " << it.end << "]"; } vector<pair<Interval, Interval>> conflictingAppointments(vector<Interval> &appointments) { vector<pair<Interval, Interval>> result; auto comp = [](const Interval &a, const Interval &b) -> bool { return a.start == b.start ? a.index < b.index : a.start < b.start; }; sort(appointments.begin(), appointments.end(), comp); for(int i=0; i<appointments.size(); i++) { int lo = i+1, hi = appointments.size()-1, curr = i; while(lo <= hi) { int mid = lo + (hi-lo)/2; if(appointments[mid].start >= appointments[i].end) hi = mid-1; else curr = mid, lo = mid + 1; } for(int j = i+1; j <= curr; j++) result.emplace_back(appointments[i], appointments[j]); } return result; } int main() { vector<Interval> appointments = { {0, 1, 5}, {1, 3, 7}, {2, 2, 6}, {3, 10, 15}, {4, 5, 6}, {5, 4, 100} }; cout << "Appointments are: " << appointments << endl; cout << "Conflicting appointments are:" << endl; for(auto&& tup: conflictingAppointments(appointments)) cout << tup.first << " conflicts with " << tup.second << endl; return 0; } <|endoftext|>
<commit_before> #include "stdio.h" #include <iostream> #include <boost/shared_ptr.hpp> #include <boost/enable_shared_from_this.hpp> #include <ext/hash_map> using boost::enable_shared_from_this; using namespace std; using namespace __gnu_cxx; struct eqstr { bool operator()(const char* s1, const char* s2) const { return strcmp(s1, s2) == 0; } }; struct test { int x,y; }; //template <class Tk, cl> // class cons { // public: // typedef boost::shared_ptr< hash_map<const char*, int> > ptr; // cons(T a, ptr b) { // car = a; // cdr = b; // } // ptr cdr; // // static ptr null; // = ptr((cons<T>*)0); // }; typedef boost::shared_ptr< hash_map<const char*, int> > hashptr; int main() { hash_map<const char*, int, hash<const char*>, eqstr> months; months["january"] = 31; months["february"] = 28; months["march"] = 31; months["april"] = 30; months["may"] = 31; months["june"] = 30; months["july"] = 31; months["august"] = 31; months["september"] = 30; months["october"] = 31; months["november"] = 30; months["december"] = 31; cout << "september -> " << months["september"] << endl; cout << "april -> " << months["april"] << endl; cout << "june -> " << months["june"] << endl; cout << "november -> " << months["november"] << endl; // hashptr boosted = hashptr(new hash_map<const char*, int>() ); hashptr boosted(new hash_map<const char*, int>() ); (*boosted)["foo"] = 399; (*boosted)["bar"] = 3988; cout << "lookup -> " << (*boosted)["foo"] << endl; cout << "lookup2 -> " << (*boosted)["baz"] << endl; cout << "lookup3 -> " << (*boosted)["bar"] << endl; boost::shared_ptr< hash_map<test, int> > foo(new hash_map<test, int> ); test s; s.x = 99; s.y = 98; (*boosted)[(const char*)&s] = 12345; // (*foo)[s] = 12345; cout << "dangerous I think: " << (*boosted)[(const char*)&s] << endl; s.y += 100; cout << "Now increment y field: (doesn't affect)" << (*boosted)[(const char*)&s] << endl; s.y -= 100; s.x++; cout << "Now increment x field: " << (*boosted)[(const char*)&s] << endl; s.x--; cout << "Now decrement again: " << (*boosted)[(const char*)&s] << endl; } // int main(int argc, char** argv) { // } <commit_msg>having trouble with hash maps<commit_after> #include "stdio.h" #include <iostream> #include <boost/shared_ptr.hpp> #include <boost/enable_shared_from_this.hpp> //#include <boost/hash/hash.hpp> #include <boost/functional/hash.hpp> //#include <boost/hash.hpp> //#include <boost/tuple/tuple.hpp> #include "boost/tuple/tuple_comparison.hpp" #include "boost/tuple/tuple_io.hpp" #include <ext/hash_map> using boost::enable_shared_from_this; //using boost::tuples; //using boost::hash; using namespace std; using namespace __gnu_cxx; struct eqstr { bool operator()(const char* s1, const char* s2) const { return strcmp(s1, s2) == 0; } }; static size_t myhash(unsigned char* ptr, int size) { size_t hash = 5381; int c; for(int i=0; i<size; i++) hash = ((hash << 5) + hash) + ptr[i]; /* hash * 33 + c */ return hash; } struct test { int x,y; }; struct hashtest { size_t operator()(struct test tup) { //return myhash((unsigned char*)&tup, sizeof(struct test)); return 0; } }; struct eqtest { bool operator()(struct test tup1, struct test tup2) { //myhash((unsigned char*)&tup, sizeof(struct test)); return 1; } }; //template <class Tk, cl> // class cons { // public: // typedef boost::shared_ptr< hash_map<const char*, int> > ptr; // cons(T a, ptr b) { // car = a; // cdr = b; // } // ptr cdr; // // static ptr null; // = ptr((cons<T>*)0); // }; typedef boost::shared_ptr< hash_map<const char*, int> > hashptr; int main() { hash_map<const char*, int, hash<const char*> > months; months["january"] = 31; months["february"] = 28; months["march"] = 31; months["april"] = 30; months["may"] = 31; months["june"] = 30; months["july"] = 31; months["august"] = 31; months["september"] = 30; months["october"] = 31; months["november"] = 30; months["december"] = 31; cout << "september -> " << months["september"] << endl; cout << "april -> " << months["april"] << endl; cout << "june -> " << months["june"] << endl; cout << "november -> " << months["november"] << endl; // hashptr boosted = hashptr(new hash_map<const char*, int>() ); hashptr boosted(new hash_map<const char*, int>() ); (*boosted)["foo"] = 399; (*boosted)["bar"] = 3988; cout << "lookup -> " << (*boosted)["foo"] << endl; cout << "lookup2 -> " << (*boosted)["baz"] << endl; cout << "lookup3 -> " << (*boosted)["bar"] << endl; boost::shared_ptr< hash_map<struct test, int> > foo(new hash_map<struct test, int> ); test s; s.x = 99; s.y = 98; (*boosted)[(const char*)&s] = 12345; cout << "\n Testing const char* casting... \n"; cout << "dangerous I think: " << (*boosted)[(const char*)&s] << endl; s.y += 100; cout << "Now increment y field: (doesn't affect) " << (*boosted)[(const char*)&s] << endl; s.y -= 100; s.x++; cout << "Now increment x field: " << (*boosted)[(const char*)&s] << endl; s.x--; cout << "Now decrement again: " << (*boosted)[(const char*)&s] << endl; boost::shared_ptr< hash_map<struct test, int> > foo2(new hash_map<struct test, int> ); boost::hash<int> inthash; boost::hash<struct test> testhash; boost::hash< boost::tuple<int,char> > tuphash; boost::tuple<int,char> mytup(1,'a'); cout << "Here's a tup: " << mytup << endl; // This doesn't work. Big template related error. // (*foo)[s] = 12345; printf("\nInt hash: %d\n", inthash(35)); //printf("\ntest hash: %d\n", testhash(s)); // FAILS //printf("\nTup hash: %d\n", tuphash(mytup)); // FAILS // Ok, now doing manually: //hash_map<struct test, int, hashtest, eqtest > manual; hash_map<struct test, int, hashtest, eqtest > manual; manual[s] = 3295; //hash_map<int, int, hash<int>, equal_to<int> > manual; //manual[s.x] = 3295; } // int main(int argc, char** argv) { // } <|endoftext|>
<commit_before> #include "neighborhoods.h" // apply valid and feasable move to the current solution (this) void Neighborhoods::applyMove(const Move& m) { switch (m.getmtype()) { case Move::Ins: { // Get a copy of the node we are going to remove // remove if from v1 Vehicle& v1 = fleet[m.getvid1()]; Trashnode n1 = v1[m.getpos1()]; // TODO can be ref? v1.remove(m.getpos1()); // Get a reference to vid2 Vehicle& v2 = fleet[m.getvid2()]; // and insert n1 at the appropriate location v2.insert(n1, m.getpos2()); } break; case Move::IntraSw: { Vehicle& v1 = fleet[m.getvid1()]; v1.swap(m.getpos1(), m.getpos2()); } break; case Move::InterSw: { Vehicle& v1 = fleet[m.getvid1()]; Vehicle& v2 = fleet[m.getvid2()]; v1.swap(v2, m.getpos1(), m.getpos2()); } break; } } // make or simulate making the move and check if the modified // route(s) are feasable bool Neighborhoods::isNotFeasible(const Move& m) const { switch (m.getmtype()) { case Move::Ins: { // remove a node will not make the path infeasible // so we only need to check on inserting it // copy the vehicle and the node // so we can change it and then throw it away Vehicle v1 = fleet[m.getvid1()]; assert( m.getvid2()<fleet.size() ); Vehicle v2 = fleet[m.getvid2()]; assert( m.getpos1()<v1.size() ); Trashnode n1 = v1[m.getpos1()]; if (not v2.insert(n1, m.getpos2())) return true; if (not v2.feasable()) return true; } break; case Move::IntraSw: { Vehicle v1 = fleet[m.getvid1()]; if (not v1.swap(m.getpos1(), m.getpos2())) return true; if (not v1.feasable()) return true; } break; case Move::InterSw: { Vehicle v1 = fleet[m.getvid1()]; Vehicle v2 = fleet[m.getvid2()]; if (not v1.swap(v2, m.getpos1(), m.getpos2())) return true; if (not v1.feasable() or not v2.feasable()) return true; } break; default: return true; } return false; } // make or simulate making the move and return the savings // that it will generate. This would be equivalent to // savings = oldsolution.getcost() - newsolution.getcost() double Neighborhoods::getMoveSavings(const Move& m) const { // TODO: improve this, this is probably very inefficient // for example IF we combined the savings calc with isNotFeasible() // we can get the savings from the new paths we made. // we would want to v1.remove(m.getpos1) to get that cost double oldCost = getCost(); // make a copy of the current solution // we dont what to modify this as we are const Neighborhoods newsol = *this; newsol.applyMove(m); double newCost = newsol.getCost(); return oldCost - newCost; } // this should be dumb and fast as it is called a HUGE number of times // The Ins move is defined as follows: // mtype = Move::Ins // vid1 - vehicle from // nid1 - node id in vehicle 1 // pos1 - postion of nid1 in vid1 // vid2 - destination vehicle // nid2 = -1 unused // pos2 - position to insert nid1 in vid2 // // Algorithm // for every pickup node in every vehicle // create Move objects for moving that node to every position // in every other route if the Move would be feasable // void Neighborhoods::getInsNeighborhood(std::deque<Move>& moves) const { moves.clear(); // iterate through the vechicles (vi, vj) for (int vi=0; vi<fleet.size(); vi++) { for (int vj=0; vj<fleet.size(); vj++) { if (vi==vj) continue; // iterate through the positions of each path (pi, pj) // dont exchange the depot in position 0 for (int pi=1; pi<fleet[vi].size(); pi++) { // dont try to move the dump if(fleet[vi][pi].isdump()) continue; // allow the node to be inserted at the end of the route also // hence <= for (int pj=1; pj<=fleet[vj].size(); pj++) { // we can't break because we might have multiple dumps // if we could get the position of the next dump // we could jump pj forward to it if (fleet[vj].deltaCargoGeneratesCV(fleet[vi][pi], pj)) continue; // if we check TWC we can break out if pj/->pi if (fleet[vj].deltaTimeGeneratesTV(fleet[vi][pi], pj)) break; // create a move with a dummy savings value Move m(Move::Ins, fleet[vi][pi].getnid(), // nid1 -1, // nid2 vi, // vid1 vj, // vid2 pi, // pos1 pj, // pos2 0.0); // dummy savings // we check two feasable conditions above but // isNotFeasible tests if the move is possible // or rejected by the lower level move methods // TODO see if removing this changes the results if (isNotFeasible(m)) continue; // compute the savings and set it in the move m.setsavings(getMoveSavings(m)); moves.push_back(m); } } } } } // this should be dumb and fast as it is called a HUGE number of times // IntraSw move is defined as follows: // mtype = Move::IntraSw // vid1 - vehicle we are changing // nid1 - node id 1 that we are swapping // pos1 - position of nid1 in vid1 // vid2 = -1 unused // nid2 - node id 2 that will get swapped with node id 1 // pos2 - position of nid2 in vid1 // // Algorithm // for every vehicle // for every pickup node // try to swap that node to every other position // within its original vehicle // void Neighborhoods::getIntraSwNeighborhood(std::deque<Move>& moves) const { moves.clear(); // iterate through each vehicle (vi) for (int vi=0; vi<fleet.size(); vi++) { // iterate through the nodes in the path (pi, pj) // dont exchange the depot in position 0 for (int pi=1; pi<fleet[vi].size(); pi++) { // dont try to move the dump if(fleet[vi][pi].isdump()) continue; // since we are swapping node, swap(i,j) == swap(j,i) // we only need to search forward for (int pj=pi+1; pj<fleet[vi].size(); pj++) { // dont try to move the dump if(fleet[vi][pj].isdump()) continue; // create a move with a dummy savings value Move m(Move::IntraSw, fleet[vi][pi].getnid(), // nid1 fleet[vi][pj].getnid(), // nid2 vi, // vid1 -1, // vid2 pi, // pos1 pj, // pos2 0.0); // dummy savings if (isNotFeasible(m)) continue; m.setsavings(getMoveSavings(m)); moves.push_back(m); } } } } // this should be dumb and fast as it is called a HUGE number of times // The InterSw move is defined as follows: // mtype = Move::InterSw // vid1 - vehicle 1 // nid1 - node id in vehicle 1 // pos1 - postion of nid1 in vid1 // vid2 - vehicle 2 // nid2 = node id in vehicle 2 // pos2 - position od nid2 in vid2 // void Neighborhoods::getInterSwNeighborhood(std::deque<Move>& moves) const { moves.clear(); // iterate through the vechicles (vi, vj) for (int vi=0; vi<fleet.size(); vi++) { for (int vj=0; vj<fleet.size(); vj++) { if (vi==vj) continue; // iterate through the positions of each path (pi, pj) // dont exchange the depot in position 0 for (int pi=1; pi<fleet[vi].size(); pi++) { // dont try to move the dump if(fleet[vi][pi].isdump()) continue; for (int pj=1; pj<fleet[vj].size(); pj++) { // dont try to move the dump if(fleet[vj][pj].isdump()) continue; // create a move with a dummy savings value Move m(Move::Ins, fleet[vi][pi].getnid(), // nid1 fleet[vj][pj].getnid(), // nid2 vi, // vid1 vj, // vid2 pi, // pos1 pj, // pos2 0.0); // dummy savings if (isNotFeasible(m)) continue; double savings = getMoveSavings(m); m.setsavings(savings); moves.push_back(m); } } } } } ////////////////////VIcky's part of the file void Neighborhoods::v_getInsNeighborhood(std::deque<Move>& moves, double factor) { #ifndef TESTED std::cout<<"Entering Neighborhoods::v_getInsNeighborhood"<<fleet.size()<<" trucks \n"; #endif assert (feasable()); moves.clear(); double savings; // iterate through the vechicles (vi, vj) for (int fromTruck=0; fromTruck<fleet.size(); fromTruck++) { for (int toTruck=0; toTruck<fleet.size(); toTruck++) { if (fromTruck==toTruck) continue; for (int fromPos=1; fromPos<fleet[fromTruck].size(); fromPos++) { if ( not fleet[fromTruck].eval_erase(fromPos,savings) ) continue; //for whatever reason erasing a node makes the truck infeasable if(fleet[fromTruck][fromPos].isdump()) continue; // skiping dump fleet[toTruck].eval_insertMoveDumps( fleet[fromTruck][fromPos], moves, fromTruck, fromPos, toTruck, savings, factor ); } } } #ifndef TESTED std::cout<<"EXIT Neighborhoods::v_getInsNeighborhood"<<moves.size()<<" MOVES found total \n"; #endif } <commit_msg>added assertions in Neighborhoods::applyMove<commit_after> #include "neighborhoods.h" // apply valid and feasable move to the current solution (this) void Neighborhoods::applyMove(const Move& m) { switch (m.getmtype()) { case Move::Ins: { // Get a copy of the node we are going to remove // remove if from v1 Vehicle& v1 = fleet[m.getvid1()]; Trashnode n1 = v1[m.getpos1()]; // TODO can be ref? v1.remove(m.getpos1()); // Get a reference to vid2 Vehicle& v2 = fleet[m.getvid2()]; // and insert n1 at the appropriate location v2.insert(n1, m.getpos2()); assert( fleet[m.getvid1()].feasable() ); assert( fleet[m.getvid2()].feasable() ); } break; case Move::IntraSw: { Vehicle& v1 = fleet[m.getvid1()]; v1.swap(m.getpos1(), m.getpos2()); assert( fleet[m.getvid1()].feasable() ); } break; case Move::InterSw: { Vehicle& v1 = fleet[m.getvid1()]; Vehicle& v2 = fleet[m.getvid2()]; v1.swap(v2, m.getpos1(), m.getpos2()); assert( fleet[m.getvid1()].feasable() ); assert( fleet[m.getvid2()].feasable() ); } break; } } // make or simulate making the move and check if the modified // route(s) are feasable bool Neighborhoods::isNotFeasible(const Move& m) const { switch (m.getmtype()) { case Move::Ins: { // remove a node will not make the path infeasible // so we only need to check on inserting it // copy the vehicle and the node // so we can change it and then throw it away Vehicle v1 = fleet[m.getvid1()]; assert( m.getvid2()<fleet.size() ); Vehicle v2 = fleet[m.getvid2()]; assert( m.getpos1()<v1.size() ); Trashnode n1 = v1[m.getpos1()]; if (not v2.insert(n1, m.getpos2())) return true; if (not v2.feasable()) return true; } break; case Move::IntraSw: { Vehicle v1 = fleet[m.getvid1()]; if (not v1.swap(m.getpos1(), m.getpos2())) return true; if (not v1.feasable()) return true; } break; case Move::InterSw: { Vehicle v1 = fleet[m.getvid1()]; Vehicle v2 = fleet[m.getvid2()]; if (not v1.swap(v2, m.getpos1(), m.getpos2())) return true; if (not v1.feasable() or not v2.feasable()) return true; } break; default: return true; } return false; } // make or simulate making the move and return the savings // that it will generate. This would be equivalent to // savings = oldsolution.getcost() - newsolution.getcost() double Neighborhoods::getMoveSavings(const Move& m) const { // TODO: improve this, this is probably very inefficient // for example IF we combined the savings calc with isNotFeasible() // we can get the savings from the new paths we made. // we would want to v1.remove(m.getpos1) to get that cost double oldCost = getCost(); // make a copy of the current solution // we dont what to modify this as we are const Neighborhoods newsol = *this; newsol.applyMove(m); double newCost = newsol.getCost(); return oldCost - newCost; } // this should be dumb and fast as it is called a HUGE number of times // The Ins move is defined as follows: // mtype = Move::Ins // vid1 - vehicle from // nid1 - node id in vehicle 1 // pos1 - postion of nid1 in vid1 // vid2 - destination vehicle // nid2 = -1 unused // pos2 - position to insert nid1 in vid2 // // Algorithm // for every pickup node in every vehicle // create Move objects for moving that node to every position // in every other route if the Move would be feasable // void Neighborhoods::getInsNeighborhood(std::deque<Move>& moves) const { moves.clear(); // iterate through the vechicles (vi, vj) for (int vi=0; vi<fleet.size(); vi++) { for (int vj=0; vj<fleet.size(); vj++) { if (vi==vj) continue; // iterate through the positions of each path (pi, pj) // dont exchange the depot in position 0 for (int pi=1; pi<fleet[vi].size(); pi++) { // dont try to move the dump if(fleet[vi][pi].isdump()) continue; // allow the node to be inserted at the end of the route also // hence <= for (int pj=1; pj<=fleet[vj].size(); pj++) { // we can't break because we might have multiple dumps // if we could get the position of the next dump // we could jump pj forward to it if (fleet[vj].deltaCargoGeneratesCV(fleet[vi][pi], pj)) continue; // if we check TWC we can break out if pj/->pi if (fleet[vj].deltaTimeGeneratesTV(fleet[vi][pi], pj)) break; // create a move with a dummy savings value Move m(Move::Ins, fleet[vi][pi].getnid(), // nid1 -1, // nid2 vi, // vid1 vj, // vid2 pi, // pos1 pj, // pos2 0.0); // dummy savings // we check two feasable conditions above but // isNotFeasible tests if the move is possible // or rejected by the lower level move methods // TODO see if removing this changes the results if (isNotFeasible(m)) continue; // compute the savings and set it in the move m.setsavings(getMoveSavings(m)); moves.push_back(m); } } } } } // this should be dumb and fast as it is called a HUGE number of times // IntraSw move is defined as follows: // mtype = Move::IntraSw // vid1 - vehicle we are changing // nid1 - node id 1 that we are swapping // pos1 - position of nid1 in vid1 // vid2 = -1 unused // nid2 - node id 2 that will get swapped with node id 1 // pos2 - position of nid2 in vid1 // // Algorithm // for every vehicle // for every pickup node // try to swap that node to every other position // within its original vehicle // void Neighborhoods::getIntraSwNeighborhood(std::deque<Move>& moves) const { moves.clear(); // iterate through each vehicle (vi) for (int vi=0; vi<fleet.size(); vi++) { // iterate through the nodes in the path (pi, pj) // dont exchange the depot in position 0 for (int pi=1; pi<fleet[vi].size(); pi++) { // dont try to move the dump if(fleet[vi][pi].isdump()) continue; // since we are swapping node, swap(i,j) == swap(j,i) // we only need to search forward for (int pj=pi+1; pj<fleet[vi].size(); pj++) { // dont try to move the dump if(fleet[vi][pj].isdump()) continue; // create a move with a dummy savings value Move m(Move::IntraSw, fleet[vi][pi].getnid(), // nid1 fleet[vi][pj].getnid(), // nid2 vi, // vid1 -1, // vid2 pi, // pos1 pj, // pos2 0.0); // dummy savings if (isNotFeasible(m)) continue; m.setsavings(getMoveSavings(m)); moves.push_back(m); } } } } // this should be dumb and fast as it is called a HUGE number of times // The InterSw move is defined as follows: // mtype = Move::InterSw // vid1 - vehicle 1 // nid1 - node id in vehicle 1 // pos1 - postion of nid1 in vid1 // vid2 - vehicle 2 // nid2 = node id in vehicle 2 // pos2 - position od nid2 in vid2 // void Neighborhoods::getInterSwNeighborhood(std::deque<Move>& moves) const { moves.clear(); // iterate through the vechicles (vi, vj) for (int vi=0; vi<fleet.size(); vi++) { for (int vj=0; vj<fleet.size(); vj++) { if (vi==vj) continue; // iterate through the positions of each path (pi, pj) // dont exchange the depot in position 0 for (int pi=1; pi<fleet[vi].size(); pi++) { // dont try to move the dump if(fleet[vi][pi].isdump()) continue; for (int pj=1; pj<fleet[vj].size(); pj++) { // dont try to move the dump if(fleet[vj][pj].isdump()) continue; // create a move with a dummy savings value Move m(Move::Ins, fleet[vi][pi].getnid(), // nid1 fleet[vj][pj].getnid(), // nid2 vi, // vid1 vj, // vid2 pi, // pos1 pj, // pos2 0.0); // dummy savings if (isNotFeasible(m)) continue; double savings = getMoveSavings(m); m.setsavings(savings); moves.push_back(m); } } } } } ////////////////////VIcky's part of the file void Neighborhoods::v_getInsNeighborhood(std::deque<Move>& moves, double factor) { #ifndef TESTED std::cout<<"Entering Neighborhoods::v_getInsNeighborhood"<<fleet.size()<<" trucks \n"; #endif assert (feasable()); moves.clear(); double savings; // iterate through the vechicles (vi, vj) for (int fromTruck=0; fromTruck<fleet.size(); fromTruck++) { for (int toTruck=0; toTruck<fleet.size(); toTruck++) { if (fromTruck==toTruck) continue; for (int fromPos=1; fromPos<fleet[fromTruck].size(); fromPos++) { if ( not fleet[fromTruck].eval_erase(fromPos,savings) ) continue; //for whatever reason erasing a node makes the truck infeasable if(fleet[fromTruck][fromPos].isdump()) continue; // skiping dump fleet[toTruck].eval_insertMoveDumps( fleet[fromTruck][fromPos], moves, fromTruck, fromPos, toTruck, savings, factor ); } } } #ifndef TESTED std::cout<<"EXIT Neighborhoods::v_getInsNeighborhood"<<moves.size()<<" MOVES found total \n"; #endif } <|endoftext|>
<commit_before>#include "../ParserTestsBase.h" #include "compiler/constructs/DataType.h" class ParserTests_Operators : public ParserTestsBase { }; TEST_F(ParserTests_Operators, MultiplyExpression) { FunctionDefinitionNode* node = this->parseSingleFunction("def test(Int x, Int y)\n" " x * y\n" "end\n"); OperatorNode* opNode = dynamic_cast<OperatorNode*>(node->childAtIndex(0)); ASSERT_EQ("Multiplication Operator", opNode->nodeName()); ASSERT_EQ("x", dynamic_cast<VariableNode*>(opNode->childAtIndex(0))->name()); ASSERT_EQ("y", dynamic_cast<VariableNode*>(opNode->childAtIndex(1))->name()); } TEST_F(ParserTests_Operators, DivisionExpression) { FunctionDefinitionNode* node = this->parseSingleFunction("def test(Int x, Int y)\n" " x / y\n" "end\n"); OperatorNode* opNode = dynamic_cast<OperatorNode*>(node->childAtIndex(0)); ASSERT_EQ("Division Operator", opNode->nodeName()); ASSERT_EQ("x", dynamic_cast<VariableNode*>(opNode->childAtIndex(0))->name()); ASSERT_EQ("y", dynamic_cast<VariableNode*>(opNode->childAtIndex(1))->name()); } TEST_F(ParserTests_Operators, AssignmentExpression) { FunctionDefinitionNode* node = this->parseSingleFunction("def test()\n" " Int x\n" " Int y\n" " x = y\n" "end\n"); // root -> function ASSERT_EQ("Variable Declaration", node->childAtIndex(0)->nodeName()); ASSERT_EQ("x", node->childAtIndex(0)->name()); ASSERT_EQ(DataType::Kind::Integer, node->childAtIndex(0)->dataType().kind()); ASSERT_EQ("Variable Declaration", node->childAtIndex(1)->nodeName()); ASSERT_EQ("y", node->childAtIndex(1)->name()); ASSERT_EQ(DataType::Kind::Integer, node->childAtIndex(1)->dataType().kind()); OperatorNode* opNode = dynamic_cast<OperatorNode*>(node->childAtIndex(2)); ASSERT_EQ("Assign Operator", opNode->nodeName()); ASSERT_EQ("Local Variable", opNode->childAtIndex(0)->nodeName()); ASSERT_EQ("x", dynamic_cast<VariableNode*>(opNode->childAtIndex(0))->name()); ASSERT_EQ("Local Variable", opNode->childAtIndex(1)->nodeName()); ASSERT_EQ("y", dynamic_cast<VariableNode*>(opNode->childAtIndex(1))->name()); } TEST_F(ParserTests_Operators, SelfAssignmentExpression) { ASTNode* node = this->parseSingleFunction("def test(Int a)\n" " a = a\n" "end\n"); ASSERT_EQ("Assign Operator", node->childAtIndex(0)->nodeName()); } TEST_F(ParserTests_Operators, AdditionExpression) { FunctionDefinitionNode* node = this->parseSingleFunction("def test(Int x, Int y)\n" " x + y\n" "end\n"); OperatorNode* opNode = dynamic_cast<OperatorNode*>(node->childAtIndex(0)); ASSERT_EQ("Addition Operator", opNode->nodeName()); ASSERT_EQ("x", dynamic_cast<VariableNode*>(opNode->childAtIndex(0))->name()); ASSERT_EQ("y", dynamic_cast<VariableNode*>(opNode->childAtIndex(1))->name()); } TEST_F(ParserTests_Operators, SubtractionExpression) { FunctionDefinitionNode* node = this->parseSingleFunction("def test(Int x, Int y)\n" " x - y\n" "end\n"); OperatorNode* opNode = dynamic_cast<OperatorNode*>(node->childAtIndex(0)); ASSERT_EQ("Subtraction Operator", opNode->nodeName()); ASSERT_EQ("x", dynamic_cast<VariableNode*>(opNode->childAtIndex(0))->name()); ASSERT_EQ("y", dynamic_cast<VariableNode*>(opNode->childAtIndex(1))->name()); } TEST_F(ParserTests_Operators, ParenthesisExpression) { FunctionDefinitionNode* node = this->parseSingleFunction("def test(Int x, Int y)\n" " x = (x - y) * y\n" "end\n"); OperatorNode* opNode = dynamic_cast<OperatorNode*>(node->childAtIndex(0)); ASSERT_EQ("Assign Operator", opNode->nodeName()); opNode = dynamic_cast<OperatorNode*>(opNode->childAtIndex(1)); ASSERT_EQ("Multiplication Operator", opNode->nodeName()); ASSERT_EQ("y", dynamic_cast<VariableNode*>(opNode->childAtIndex(1))->name()); opNode = dynamic_cast<OperatorNode*>(opNode->childAtIndex(0)); ASSERT_EQ("Subtraction Operator", opNode->nodeName()); ASSERT_EQ("x", dynamic_cast<VariableNode*>(opNode->childAtIndex(0))->name()); ASSERT_EQ("y", dynamic_cast<VariableNode*>(opNode->childAtIndex(1))->name()); } TEST_F(ParserTests_Operators, DereferenceOperator) { FunctionDefinitionNode* node = this->parseSingleFunction("def test(*Int x)\n" " *x\n" "end\n"); OperatorNode* opNode = dynamic_cast<OperatorNode*>(node->childAtIndex(0)); ASSERT_EQ("Dereference Operator", opNode->nodeName()); ASSERT_EQ(DataType::Kind::Integer, opNode->dataType().kind()); ASSERT_EQ("x", dynamic_cast<VariableNode*>(opNode->childAtIndex(0))->name()); } TEST_F(ParserTests_Operators, AddressOfOperator) { FunctionDefinitionNode* node = this->parseSingleFunction("def test(Int x)\n" " &x\n" "end\n"); OperatorNode* opNode = dynamic_cast<OperatorNode*>(node->childAtIndex(0)); ASSERT_EQ("Address Of Operator", opNode->nodeName()); ASSERT_EQ("x", dynamic_cast<VariableNode*>(opNode->childAtIndex(0))->name()); } TEST_F(ParserTests_Operators, AssignToDereference) { FunctionDefinitionNode* node = this->parseSingleFunction("def test(*Int x, *Int y)\n" " *x = *y\n" "end\n"); OperatorNode* opNode = dynamic_cast<OperatorNode*>(node->childAtIndex(0)); ASSERT_EQ("Assign Operator", opNode->nodeName()); ASSERT_EQ("Dereference Operator", opNode->childAtIndex(0)->nodeName()); ASSERT_EQ("x", dynamic_cast<VariableNode*>(opNode->childAtIndex(0)->childAtIndex(0))->name()); ASSERT_EQ("Dereference Operator", opNode->childAtIndex(1)->nodeName()); ASSERT_EQ("y", dynamic_cast<VariableNode*>(opNode->childAtIndex(1)->childAtIndex(0))->name()); } TEST_F(ParserTests_Operators, MemberAccessOperator) { ASTNode* node = this->parseNodeWithBodies("struct MyStruct\n" " Int a\n" "end\n" "def test(MyStruct value, Int b)\n" " value.a = b\n" "end\n"); node = node->childAtIndex(1)->childAtIndex(0); ASSERT_EQ("Assign Operator", node->nodeName()); ASSERT_EQ("b", dynamic_cast<VariableNode*>(node->childAtIndex(1))->name()); node = node->childAtIndex(0); ASSERT_EQ("Member Access Operator", node->nodeName()); ASSERT_EQ("a", dynamic_cast<MemberAccessNode*>(node)->name()); ASSERT_FALSE(dynamic_cast<MemberAccessNode*>(node)->indirect()); ASSERT_EQ(DataType::Kind::Integer, node->dataType().kind()); node = node->childAtIndex(0); ASSERT_EQ("Local Variable", node->nodeName()); ASSERT_EQ("value", dynamic_cast<VariableNode*>(node)->name()); } TEST_F(ParserTests_Operators, IndirectMemberAccessOperator) { ASTNode* node = this->parseNodeWithBodies("struct MyStruct\n" " Int a\n" "end\n" "def test(*MyStruct value, Int b)\n" " value->a = b\n" "end\n"); node = node->childAtIndex(1)->childAtIndex(0); ASSERT_EQ("Assign Operator", node->nodeName()); ASSERT_EQ("b", dynamic_cast<VariableNode*>(node->childAtIndex(1))->name()); node = node->childAtIndex(0); ASSERT_EQ("Member Access Operator", node->nodeName()); ASSERT_EQ("a", dynamic_cast<MemberAccessNode*>(node)->name()); ASSERT_TRUE(dynamic_cast<MemberAccessNode*>(node)->indirect()); ASSERT_EQ(DataType::Kind::Integer, node->dataType().kind()); node = node->childAtIndex(0); ASSERT_EQ("Local Variable", node->nodeName()); ASSERT_EQ("value", dynamic_cast<VariableNode*>(node)->name()); } TEST_F(ParserTests_Operators, AddressOfAndArrowPrecedence) { ASTNode* node = this->parseNodeWithBodies("struct MyStruct\n" " Int x\n" "end\n" "def test(*MyStruct a, Int b)\n" " b = &a->x\n" "end\n"); node = node->childAtIndex(1)->childAtIndex(0); ASSERT_EQ("Assign Operator", node->nodeName()); ASSERT_EQ("Local Variable", node->childAtIndex(0)->nodeName()); ASSERT_EQ("b", dynamic_cast<VariableNode*>(node->childAtIndex(0))->name()); node = node->childAtIndex(1); ASSERT_EQ("Address Of Operator", node->nodeName()); node = node->childAtIndex(0); ASSERT_EQ("Member Access Operator", node->nodeName()); ASSERT_EQ("x", dynamic_cast<MemberAccessNode*>(node)->name()); node = node->childAtIndex(0); ASSERT_EQ("Local Variable", node->nodeName()); ASSERT_EQ("a", dynamic_cast<VariableNode*>(node)->name()); } TEST_F(ParserTests_Operators, IndexerOperator) { ASTNode* node = this->parseSingleFunction("def test([5]Int x, Int y)\n" " x[y] = y\n" "end\n"); node = node->childAtIndex(0); ASSERT_EQ("Assign Operator", node->nodeName()); ASSERT_EQ("Local Variable", node->childAtIndex(1)->nodeName()); ASSERT_EQ("y", dynamic_cast<VariableNode*>(node->childAtIndex(1))->name()); node = node->childAtIndex(0); ASSERT_EQ("Indexer Operator", node->nodeName()); ASSERT_EQ("Local Variable", node->childAtIndex(0)->nodeName()); ASSERT_EQ("x", dynamic_cast<VariableNode*>(node->childAtIndex(0))->name()); ASSERT_EQ("Local Variable", node->childAtIndex(1)->nodeName()); ASSERT_EQ("y", dynamic_cast<VariableNode*>(node->childAtIndex(1))->name()); } TEST_F(ParserTests_Operators, EqualOperator) { ASTNode* node = this->parseSingleFunction("def test(Int x)\n" " x == x\n" "end\n"); node = node->childAtIndex(0); ASSERT_EQ("Equal Operator", node->nodeName()); } TEST_F(ParserTests_Operators, NotEqualOperator) { ASTNode* node = this->parseSingleFunction("def test(Int x)\n" " x != x\n" "end\n"); node = node->childAtIndex(0); ASSERT_EQ("Not-Equal Operator", node->nodeName()); } TEST_F(ParserTests_Operators, TernaryConditionalOperator) { ASTNode* node = this->parseSingleFunction("def test(Int a, Int b, Int c)\n" " a = (a == b) ? b : c\n" "end\n"); node = node->childAtIndex(0); ASSERT_EQ("Assign Operator", node->nodeName()); node = node->childAtIndex(1); ASSERT_EQ("Ternary Conditional Operator", node->nodeName()); ASSERT_EQ("Local Variable", node->childAtIndex(1)->nodeName()); ASSERT_EQ("b", dynamic_cast<VariableNode*>(node->childAtIndex(1))->name()); ASSERT_EQ("Local Variable", node->childAtIndex(2)->nodeName()); ASSERT_EQ("c", dynamic_cast<VariableNode*>(node->childAtIndex(2))->name()); } TEST_F(ParserTests_Operators, TernaryCompareAndSwapOperator) { ASTNode* node = this->parseSingleFunction("def test(Int a, Int b, Int c)\n" " a cas b : c\n" "end\n"); node = node->childAtIndex(0); ASSERT_EQ("CAS Operator", node->nodeName()); ASSERT_EQ("Local Variable", node->childAtIndex(0)->nodeName()); ASSERT_EQ("a", dynamic_cast<VariableNode*>(node->childAtIndex(0))->name()); ASSERT_EQ("Local Variable", node->childAtIndex(1)->nodeName()); ASSERT_EQ("b", dynamic_cast<VariableNode*>(node->childAtIndex(1))->name()); ASSERT_EQ("Local Variable", node->childAtIndex(2)->nodeName()); ASSERT_EQ("c", dynamic_cast<VariableNode*>(node->childAtIndex(2))->name()); } TEST_F(ParserTests_Operators, CompoundAdditionAssignmentOperator) { ASTNode* node = this->parseSingleFunction("def test(Int a, Int b)\n" " a += b\n" "end\n"); node = node->childAtIndex(0); ASSERT_EQ("Add-Assign Operator", node->nodeName()); } TEST_F(ParserTests_Operators, CompoundBitwiseOrAssignmentOperator) { ASTNode* node = this->parseSingleFunction("def test(Int a, Int b)\n" " a |= b\n" "end\n"); node = node->childAtIndex(0); ASSERT_EQ("Bitwise Or-Assign Operator", node->nodeName()); } TEST_F(ParserTests_Operators, PrecedenceTest) { ASTNode* node = this->parseSingleFunction("def test(Int x, Int y, Int z)\n" " x = x * y + z\n" "end\n"); node = node->childAtIndex(0); ASSERT_EQ("Assign Operator", node->nodeName()); // addition node = node->childAtIndex(1); ASSERT_EQ("Addition Operator", node->nodeName()); // multiplication node = node->childAtIndex(0); ASSERT_EQ("Multiplication Operator", node->nodeName()); } TEST_F(ParserTests_Operators, OrAssignmentOperator) { ASTNode* node = this->parseSingleFunction("def test(Int a, Int b)\n" " a ||= b\n" "end\n"); node = node->childAtIndex(0); ASSERT_EQ("Or-Assign Operator", node->nodeName()); } TEST_F(ParserTests_Operators, UnaryMinusOperator) { ASTNode* node = this->parseSingleFunction("def test(Int a)\n" " a = -a\n" "end\n"); node = node->childAtIndex(0); ASSERT_EQ("Assign Operator", node->nodeName()); node = node->childAtIndex(1); ASSERT_EQ("Unary Minus Operator", node->nodeName()); } TEST_F(ParserTests_Operators, UnaryNotOperator) { ASTNode* node = this->parseSingleFunction("def test(Bool a)\n" " a = !a\n" "end\n"); node = node->childAtIndex(0); ASSERT_EQ("Assign Operator", node->nodeName()); node = node->childAtIndex(1); ASSERT_EQ("Not Operator", node->nodeName()); } <commit_msg>Add a test for indirect member access for optional types.<commit_after>#include "../ParserTestsBase.h" #include "compiler/constructs/DataType.h" class ParserTests_Operators : public ParserTestsBase { }; TEST_F(ParserTests_Operators, MultiplyExpression) { FunctionDefinitionNode* node = this->parseSingleFunction("def test(Int x, Int y)\n" " x * y\n" "end\n"); OperatorNode* opNode = dynamic_cast<OperatorNode*>(node->childAtIndex(0)); ASSERT_EQ("Multiplication Operator", opNode->nodeName()); ASSERT_EQ("x", dynamic_cast<VariableNode*>(opNode->childAtIndex(0))->name()); ASSERT_EQ("y", dynamic_cast<VariableNode*>(opNode->childAtIndex(1))->name()); } TEST_F(ParserTests_Operators, DivisionExpression) { FunctionDefinitionNode* node = this->parseSingleFunction("def test(Int x, Int y)\n" " x / y\n" "end\n"); OperatorNode* opNode = dynamic_cast<OperatorNode*>(node->childAtIndex(0)); ASSERT_EQ("Division Operator", opNode->nodeName()); ASSERT_EQ("x", dynamic_cast<VariableNode*>(opNode->childAtIndex(0))->name()); ASSERT_EQ("y", dynamic_cast<VariableNode*>(opNode->childAtIndex(1))->name()); } TEST_F(ParserTests_Operators, AssignmentExpression) { FunctionDefinitionNode* node = this->parseSingleFunction("def test()\n" " Int x\n" " Int y\n" " x = y\n" "end\n"); // root -> function ASSERT_EQ("Variable Declaration", node->childAtIndex(0)->nodeName()); ASSERT_EQ("x", node->childAtIndex(0)->name()); ASSERT_EQ(DataType::Kind::Integer, node->childAtIndex(0)->dataType().kind()); ASSERT_EQ("Variable Declaration", node->childAtIndex(1)->nodeName()); ASSERT_EQ("y", node->childAtIndex(1)->name()); ASSERT_EQ(DataType::Kind::Integer, node->childAtIndex(1)->dataType().kind()); OperatorNode* opNode = dynamic_cast<OperatorNode*>(node->childAtIndex(2)); ASSERT_EQ("Assign Operator", opNode->nodeName()); ASSERT_EQ("Local Variable", opNode->childAtIndex(0)->nodeName()); ASSERT_EQ("x", dynamic_cast<VariableNode*>(opNode->childAtIndex(0))->name()); ASSERT_EQ("Local Variable", opNode->childAtIndex(1)->nodeName()); ASSERT_EQ("y", dynamic_cast<VariableNode*>(opNode->childAtIndex(1))->name()); } TEST_F(ParserTests_Operators, SelfAssignmentExpression) { ASTNode* node = this->parseSingleFunction("def test(Int a)\n" " a = a\n" "end\n"); ASSERT_EQ("Assign Operator", node->childAtIndex(0)->nodeName()); } TEST_F(ParserTests_Operators, AdditionExpression) { FunctionDefinitionNode* node = this->parseSingleFunction("def test(Int x, Int y)\n" " x + y\n" "end\n"); OperatorNode* opNode = dynamic_cast<OperatorNode*>(node->childAtIndex(0)); ASSERT_EQ("Addition Operator", opNode->nodeName()); ASSERT_EQ("x", dynamic_cast<VariableNode*>(opNode->childAtIndex(0))->name()); ASSERT_EQ("y", dynamic_cast<VariableNode*>(opNode->childAtIndex(1))->name()); } TEST_F(ParserTests_Operators, SubtractionExpression) { FunctionDefinitionNode* node = this->parseSingleFunction("def test(Int x, Int y)\n" " x - y\n" "end\n"); OperatorNode* opNode = dynamic_cast<OperatorNode*>(node->childAtIndex(0)); ASSERT_EQ("Subtraction Operator", opNode->nodeName()); ASSERT_EQ("x", dynamic_cast<VariableNode*>(opNode->childAtIndex(0))->name()); ASSERT_EQ("y", dynamic_cast<VariableNode*>(opNode->childAtIndex(1))->name()); } TEST_F(ParserTests_Operators, ParenthesisExpression) { FunctionDefinitionNode* node = this->parseSingleFunction("def test(Int x, Int y)\n" " x = (x - y) * y\n" "end\n"); OperatorNode* opNode = dynamic_cast<OperatorNode*>(node->childAtIndex(0)); ASSERT_EQ("Assign Operator", opNode->nodeName()); opNode = dynamic_cast<OperatorNode*>(opNode->childAtIndex(1)); ASSERT_EQ("Multiplication Operator", opNode->nodeName()); ASSERT_EQ("y", dynamic_cast<VariableNode*>(opNode->childAtIndex(1))->name()); opNode = dynamic_cast<OperatorNode*>(opNode->childAtIndex(0)); ASSERT_EQ("Subtraction Operator", opNode->nodeName()); ASSERT_EQ("x", dynamic_cast<VariableNode*>(opNode->childAtIndex(0))->name()); ASSERT_EQ("y", dynamic_cast<VariableNode*>(opNode->childAtIndex(1))->name()); } TEST_F(ParserTests_Operators, DereferenceOperator) { FunctionDefinitionNode* node = this->parseSingleFunction("def test(*Int x)\n" " *x\n" "end\n"); OperatorNode* opNode = dynamic_cast<OperatorNode*>(node->childAtIndex(0)); ASSERT_EQ("Dereference Operator", opNode->nodeName()); ASSERT_EQ(DataType::Kind::Integer, opNode->dataType().kind()); ASSERT_EQ("x", dynamic_cast<VariableNode*>(opNode->childAtIndex(0))->name()); } TEST_F(ParserTests_Operators, AddressOfOperator) { FunctionDefinitionNode* node = this->parseSingleFunction("def test(Int x)\n" " &x\n" "end\n"); OperatorNode* opNode = dynamic_cast<OperatorNode*>(node->childAtIndex(0)); ASSERT_EQ("Address Of Operator", opNode->nodeName()); ASSERT_EQ("x", dynamic_cast<VariableNode*>(opNode->childAtIndex(0))->name()); } TEST_F(ParserTests_Operators, AssignToDereference) { FunctionDefinitionNode* node = this->parseSingleFunction("def test(*Int x, *Int y)\n" " *x = *y\n" "end\n"); OperatorNode* opNode = dynamic_cast<OperatorNode*>(node->childAtIndex(0)); ASSERT_EQ("Assign Operator", opNode->nodeName()); ASSERT_EQ("Dereference Operator", opNode->childAtIndex(0)->nodeName()); ASSERT_EQ("x", dynamic_cast<VariableNode*>(opNode->childAtIndex(0)->childAtIndex(0))->name()); ASSERT_EQ("Dereference Operator", opNode->childAtIndex(1)->nodeName()); ASSERT_EQ("y", dynamic_cast<VariableNode*>(opNode->childAtIndex(1)->childAtIndex(0))->name()); } TEST_F(ParserTests_Operators, MemberAccessOperator) { ASTNode* node = this->parseNodeWithBodies("struct MyStruct\n" " Int a\n" "end\n" "def test(MyStruct value, Int b)\n" " value.a = b\n" "end\n"); node = node->childAtIndex(1)->childAtIndex(0); ASSERT_EQ("Assign Operator", node->nodeName()); ASSERT_EQ("b", dynamic_cast<VariableNode*>(node->childAtIndex(1))->name()); node = node->childAtIndex(0); ASSERT_EQ("Member Access Operator", node->nodeName()); ASSERT_EQ("a", dynamic_cast<MemberAccessNode*>(node)->name()); ASSERT_FALSE(dynamic_cast<MemberAccessNode*>(node)->indirect()); ASSERT_EQ(DataType::Kind::Integer, node->dataType().kind()); node = node->childAtIndex(0); ASSERT_EQ("Local Variable", node->nodeName()); ASSERT_EQ("value", dynamic_cast<VariableNode*>(node)->name()); } TEST_F(ParserTests_Operators, IndirectMemberAccessOperator) { ASTNode* node = this->parseNodeWithBodies("struct MyStruct\n" " Int a\n" "end\n" "def test(*MyStruct value, Int b)\n" " value->a = b\n" "end\n"); node = node->childAtIndex(1)->childAtIndex(0); ASSERT_EQ("Assign Operator", node->nodeName()); ASSERT_EQ("b", dynamic_cast<VariableNode*>(node->childAtIndex(1))->name()); node = node->childAtIndex(0); ASSERT_EQ("Member Access Operator", node->nodeName()); ASSERT_EQ("a", dynamic_cast<MemberAccessNode*>(node)->name()); ASSERT_TRUE(dynamic_cast<MemberAccessNode*>(node)->indirect()); ASSERT_EQ(DataType::Kind::Integer, node->dataType().kind()); node = node->childAtIndex(0); ASSERT_EQ("Local Variable", node->nodeName()); ASSERT_EQ("value", dynamic_cast<VariableNode*>(node)->name()); } TEST_F(ParserTests_Operators, IndirectMemberAccessOperatorOnOptional) { ASTNode* node = this->parseNodeWithBodies("struct MyStruct\n" " Int a\n" "end\n" "def test(MyStruct? value, Int b)\n" " value->a = b\n" "end\n"); node = node->childAtIndex(1)->childAtIndex(0); ASSERT_EQ("Assign Operator", node->nodeName()); ASSERT_EQ("b", dynamic_cast<VariableNode*>(node->childAtIndex(1))->name()); node = node->childAtIndex(0); ASSERT_EQ("Member Access Operator", node->nodeName()); ASSERT_EQ("a", dynamic_cast<MemberAccessNode*>(node)->name()); ASSERT_TRUE(dynamic_cast<MemberAccessNode*>(node)->indirect()); ASSERT_EQ(DataType::Kind::Integer, node->dataType().kind()); node = node->childAtIndex(0); ASSERT_EQ("Local Variable", node->nodeName()); ASSERT_EQ("value", dynamic_cast<VariableNode*>(node)->name()); } TEST_F(ParserTests_Operators, AddressOfAndArrowPrecedence) { ASTNode* node = this->parseNodeWithBodies("struct MyStruct\n" " Int x\n" "end\n" "def test(*MyStruct a, Int b)\n" " b = &a->x\n" "end\n"); node = node->childAtIndex(1)->childAtIndex(0); ASSERT_EQ("Assign Operator", node->nodeName()); ASSERT_EQ("Local Variable", node->childAtIndex(0)->nodeName()); ASSERT_EQ("b", dynamic_cast<VariableNode*>(node->childAtIndex(0))->name()); node = node->childAtIndex(1); ASSERT_EQ("Address Of Operator", node->nodeName()); node = node->childAtIndex(0); ASSERT_EQ("Member Access Operator", node->nodeName()); ASSERT_EQ("x", dynamic_cast<MemberAccessNode*>(node)->name()); node = node->childAtIndex(0); ASSERT_EQ("Local Variable", node->nodeName()); ASSERT_EQ("a", dynamic_cast<VariableNode*>(node)->name()); } TEST_F(ParserTests_Operators, IndexerOperator) { ASTNode* node = this->parseSingleFunction("def test([5]Int x, Int y)\n" " x[y] = y\n" "end\n"); node = node->childAtIndex(0); ASSERT_EQ("Assign Operator", node->nodeName()); ASSERT_EQ("Local Variable", node->childAtIndex(1)->nodeName()); ASSERT_EQ("y", dynamic_cast<VariableNode*>(node->childAtIndex(1))->name()); node = node->childAtIndex(0); ASSERT_EQ("Indexer Operator", node->nodeName()); ASSERT_EQ("Local Variable", node->childAtIndex(0)->nodeName()); ASSERT_EQ("x", dynamic_cast<VariableNode*>(node->childAtIndex(0))->name()); ASSERT_EQ("Local Variable", node->childAtIndex(1)->nodeName()); ASSERT_EQ("y", dynamic_cast<VariableNode*>(node->childAtIndex(1))->name()); } TEST_F(ParserTests_Operators, EqualOperator) { ASTNode* node = this->parseSingleFunction("def test(Int x)\n" " x == x\n" "end\n"); node = node->childAtIndex(0); ASSERT_EQ("Equal Operator", node->nodeName()); } TEST_F(ParserTests_Operators, NotEqualOperator) { ASTNode* node = this->parseSingleFunction("def test(Int x)\n" " x != x\n" "end\n"); node = node->childAtIndex(0); ASSERT_EQ("Not-Equal Operator", node->nodeName()); } TEST_F(ParserTests_Operators, TernaryConditionalOperator) { ASTNode* node = this->parseSingleFunction("def test(Int a, Int b, Int c)\n" " a = (a == b) ? b : c\n" "end\n"); node = node->childAtIndex(0); ASSERT_EQ("Assign Operator", node->nodeName()); node = node->childAtIndex(1); ASSERT_EQ("Ternary Conditional Operator", node->nodeName()); ASSERT_EQ("Local Variable", node->childAtIndex(1)->nodeName()); ASSERT_EQ("b", dynamic_cast<VariableNode*>(node->childAtIndex(1))->name()); ASSERT_EQ("Local Variable", node->childAtIndex(2)->nodeName()); ASSERT_EQ("c", dynamic_cast<VariableNode*>(node->childAtIndex(2))->name()); } TEST_F(ParserTests_Operators, TernaryCompareAndSwapOperator) { ASTNode* node = this->parseSingleFunction("def test(Int a, Int b, Int c)\n" " a cas b : c\n" "end\n"); node = node->childAtIndex(0); ASSERT_EQ("CAS Operator", node->nodeName()); ASSERT_EQ("Local Variable", node->childAtIndex(0)->nodeName()); ASSERT_EQ("a", dynamic_cast<VariableNode*>(node->childAtIndex(0))->name()); ASSERT_EQ("Local Variable", node->childAtIndex(1)->nodeName()); ASSERT_EQ("b", dynamic_cast<VariableNode*>(node->childAtIndex(1))->name()); ASSERT_EQ("Local Variable", node->childAtIndex(2)->nodeName()); ASSERT_EQ("c", dynamic_cast<VariableNode*>(node->childAtIndex(2))->name()); } TEST_F(ParserTests_Operators, CompoundAdditionAssignmentOperator) { ASTNode* node = this->parseSingleFunction("def test(Int a, Int b)\n" " a += b\n" "end\n"); node = node->childAtIndex(0); ASSERT_EQ("Add-Assign Operator", node->nodeName()); } TEST_F(ParserTests_Operators, CompoundBitwiseOrAssignmentOperator) { ASTNode* node = this->parseSingleFunction("def test(Int a, Int b)\n" " a |= b\n" "end\n"); node = node->childAtIndex(0); ASSERT_EQ("Bitwise Or-Assign Operator", node->nodeName()); } TEST_F(ParserTests_Operators, PrecedenceTest) { ASTNode* node = this->parseSingleFunction("def test(Int x, Int y, Int z)\n" " x = x * y + z\n" "end\n"); node = node->childAtIndex(0); ASSERT_EQ("Assign Operator", node->nodeName()); // addition node = node->childAtIndex(1); ASSERT_EQ("Addition Operator", node->nodeName()); // multiplication node = node->childAtIndex(0); ASSERT_EQ("Multiplication Operator", node->nodeName()); } TEST_F(ParserTests_Operators, OrAssignmentOperator) { ASTNode* node = this->parseSingleFunction("def test(Int a, Int b)\n" " a ||= b\n" "end\n"); node = node->childAtIndex(0); ASSERT_EQ("Or-Assign Operator", node->nodeName()); } TEST_F(ParserTests_Operators, UnaryMinusOperator) { ASTNode* node = this->parseSingleFunction("def test(Int a)\n" " a = -a\n" "end\n"); node = node->childAtIndex(0); ASSERT_EQ("Assign Operator", node->nodeName()); node = node->childAtIndex(1); ASSERT_EQ("Unary Minus Operator", node->nodeName()); } TEST_F(ParserTests_Operators, UnaryNotOperator) { ASTNode* node = this->parseSingleFunction("def test(Bool a)\n" " a = !a\n" "end\n"); node = node->childAtIndex(0); ASSERT_EQ("Assign Operator", node->nodeName()); node = node->childAtIndex(1); ASSERT_EQ("Not Operator", node->nodeName()); } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: vclunohelper.hxx,v $ * * $Revision: 1.4 $ * * last change: $Author: kz $ $Date: 2004-10-04 17:34:45 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef _TOOLKIT_HELPER_VCLUNOHELPER_HXX_ #define _TOOLKIT_HELPER_VCLUNOHELPER_HXX_ #ifndef _COM_SUN_STAR_UNO_REFERENCE_H_ #include <com/sun/star/uno/Reference.h> #endif #ifndef _COM_SUN_STAR_UNO_SEQUENCE_H_ #include <com/sun/star/uno/Sequence.h> #endif namespace com { namespace sun { namespace star { namespace uno { class XInterface; }}}} namespace com { namespace sun { namespace star { namespace awt { class XBitmap; class XWindow; class XWindow2; class XWindowPeer; class XGraphics; class XRegion; class XDevice; class XPointer; class XToolkit; class XFont; class XControlContainer; struct SimpleFontMetric; struct FontDescriptor; struct Rectangle; }}}} #include <vcl/bitmapex.hxx> #include <vcl/region.hxx> #include <vcl/metric.hxx> #include <vcl/mapunit.hxx> #include <tools/poly.hxx> class Window; class OutputDevice; // ---------------------------------------------------- // class VclUnoHelper // ---------------------------------------------------- class VCLUnoHelper { public: // Toolkit static ::com::sun::star::uno::Reference< ::com::sun::star::awt::XToolkit> CreateToolkit(); // Bitmap static BitmapEx GetBitmap( const ::com::sun::star::uno::Reference< ::com::sun::star::awt::XBitmap>& rxBitmap ); static ::com::sun::star::uno::Reference< ::com::sun::star::awt::XBitmap> CreateBitmap( const BitmapEx& rBitmap ); // Window static Window* GetWindow( const ::com::sun::star::uno::Reference< ::com::sun::star::awt::XWindow>& rxWindow ); static Window* GetWindow( const ::com::sun::star::uno::Reference< ::com::sun::star::awt::XWindow2>& rxWindow2 ); static Window* GetWindow( const ::com::sun::star::uno::Reference< ::com::sun::star::awt::XWindowPeer>& rxWindowPeer ); static ::com::sun::star::uno::Reference< ::com::sun::star::awt::XWindow> GetInterface( Window* pWindow ); // OutputDevice static OutputDevice* GetOutputDevice( const ::com::sun::star::uno::Reference< ::com::sun::star::awt::XDevice>& rxDevice ); static OutputDevice* GetOutputDevice( const ::com::sun::star::uno::Reference< ::com::sun::star::awt::XGraphics>& rxGraphics ); // Region static Region GetRegion( const ::com::sun::star::uno::Reference< ::com::sun::star::awt::XRegion >& rxRegion ); // Pointer static ::com::sun::star::uno::Reference< ::com::sun::star::awt::XPointer> CreatePointer(); // Polygon static Polygon CreatePolygon( const ::com::sun::star::uno::Sequence< sal_Int32 >& DataX, const ::com::sun::star::uno::Sequence< sal_Int32 >& DataY ); // Font static ::com::sun::star::awt::FontDescriptor CreateFontDescriptor( const Font& rFont ); static Font CreateFont( const ::com::sun::star::awt::FontDescriptor& rDescr, const Font& rInitFont ); static Font CreateFont( const ::com::sun::star::uno::Reference< ::com::sun::star::awt::XFont >& rxFont ); static ::com::sun::star::awt::SimpleFontMetric CreateFontMetric( const FontMetric& rFontMetric ); static float ConvertFontWidth( FontWidth eWidth ); static FontWidth ConvertFontWidth( float f ); static float ConvertFontWeight( FontWeight eWeight ); static FontWeight ConvertFontWeight( float f ); // Rectangle static sal_Bool IsZero( ::com::sun::star::awt::Rectangle rRect ); static ::com::sun::star::uno::Reference< ::com::sun::star::awt::XControlContainer> CreateControlContainer( Window* pWindow ); // MapUnits static MapUnit UnoEmbed2VCLMapUnit( sal_Int32 nUnoEmbedMapUnit ); static sal_Int32 VCL2UnoEmbedMapUnit( MapUnit nVCLMapUnit ); }; #endif // _TOOLKIT_HELPER_VCLUNOHELPER_HXX_ <commit_msg>INTEGRATION: CWS sb25 (1.4.26); FILE MERGED 2004/11/25 18:14:43 mt 1.4.26.1: #i37760# Less exports...<commit_after>/************************************************************************* * * $RCSfile: vclunohelper.hxx,v $ * * $Revision: 1.5 $ * * last change: $Author: rt $ $Date: 2005-01-11 14:06:23 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef _TOOLKIT_HELPER_VCLUNOHELPER_HXX_ #define _TOOLKIT_HELPER_VCLUNOHELPER_HXX_ #ifndef TOOLKIT_DLLAPI_H #include <toolkit/dllapi.h> #endif #ifndef _COM_SUN_STAR_UNO_REFERENCE_H_ #include <com/sun/star/uno/Reference.h> #endif #ifndef _COM_SUN_STAR_UNO_SEQUENCE_H_ #include <com/sun/star/uno/Sequence.h> #endif namespace com { namespace sun { namespace star { namespace uno { class XInterface; }}}} namespace com { namespace sun { namespace star { namespace awt { class XBitmap; class XWindow; class XWindow2; class XWindowPeer; class XGraphics; class XRegion; class XDevice; class XPointer; class XToolkit; class XFont; class XControlContainer; struct SimpleFontMetric; struct FontDescriptor; struct Rectangle; }}}} #include <vcl/bitmapex.hxx> #include <vcl/region.hxx> #include <vcl/metric.hxx> #include <vcl/mapunit.hxx> #include <tools/poly.hxx> class Window; class OutputDevice; // ---------------------------------------------------- // class VclUnoHelper // ---------------------------------------------------- class TOOLKIT_DLLPUBLIC VCLUnoHelper { public: // Toolkit static ::com::sun::star::uno::Reference< ::com::sun::star::awt::XToolkit> CreateToolkit(); // Bitmap static BitmapEx GetBitmap( const ::com::sun::star::uno::Reference< ::com::sun::star::awt::XBitmap>& rxBitmap ); static ::com::sun::star::uno::Reference< ::com::sun::star::awt::XBitmap> CreateBitmap( const BitmapEx& rBitmap ); // Window static Window* GetWindow( const ::com::sun::star::uno::Reference< ::com::sun::star::awt::XWindow>& rxWindow ); static Window* GetWindow( const ::com::sun::star::uno::Reference< ::com::sun::star::awt::XWindow2>& rxWindow2 ); static Window* GetWindow( const ::com::sun::star::uno::Reference< ::com::sun::star::awt::XWindowPeer>& rxWindowPeer ); static ::com::sun::star::uno::Reference< ::com::sun::star::awt::XWindow> GetInterface( Window* pWindow ); // OutputDevice static OutputDevice* GetOutputDevice( const ::com::sun::star::uno::Reference< ::com::sun::star::awt::XDevice>& rxDevice ); static OutputDevice* GetOutputDevice( const ::com::sun::star::uno::Reference< ::com::sun::star::awt::XGraphics>& rxGraphics ); // Region static Region GetRegion( const ::com::sun::star::uno::Reference< ::com::sun::star::awt::XRegion >& rxRegion ); // Pointer static ::com::sun::star::uno::Reference< ::com::sun::star::awt::XPointer> CreatePointer(); // Polygon static Polygon CreatePolygon( const ::com::sun::star::uno::Sequence< sal_Int32 >& DataX, const ::com::sun::star::uno::Sequence< sal_Int32 >& DataY ); // Font static ::com::sun::star::awt::FontDescriptor CreateFontDescriptor( const Font& rFont ); static Font CreateFont( const ::com::sun::star::awt::FontDescriptor& rDescr, const Font& rInitFont ); static Font CreateFont( const ::com::sun::star::uno::Reference< ::com::sun::star::awt::XFont >& rxFont ); static ::com::sun::star::awt::SimpleFontMetric CreateFontMetric( const FontMetric& rFontMetric ); static float ConvertFontWidth( FontWidth eWidth ); static FontWidth ConvertFontWidth( float f ); static float ConvertFontWeight( FontWeight eWeight ); static FontWeight ConvertFontWeight( float f ); // Rectangle static sal_Bool IsZero( ::com::sun::star::awt::Rectangle rRect ); static ::com::sun::star::uno::Reference< ::com::sun::star::awt::XControlContainer> CreateControlContainer( Window* pWindow ); // MapUnits static MapUnit UnoEmbed2VCLMapUnit( sal_Int32 nUnoEmbedMapUnit ); static sal_Int32 VCL2UnoEmbedMapUnit( MapUnit nVCLMapUnit ); }; #endif // _TOOLKIT_HELPER_VCLUNOHELPER_HXX_ <|endoftext|>
<commit_before>/* * SharedMemoryController.cpp * * Created on: 31 May 2016 * Author: gnx91527 */ #include <SharedMemoryController.h> namespace filewriter { /** Constructor. * The constructor sets up logging used within the class. */ SharedMemoryController::SharedMemoryController(boost::shared_ptr<FrameReceiver::IpcReactor> reactor, const std::string& rxEndPoint, const std::string& txEndPoint) : reactor_(reactor), rxChannel_(ZMQ_SUB), txChannel_(ZMQ_PUB) { // Setup logging for the class logger_ = Logger::getLogger("SharedMemoryController"); logger_->setLevel(Level::getAll()); LOG4CXX_TRACE(logger_, "SharedMemoryController constructor."); // Connect the frame ready channel try { LOG4CXX_DEBUG(logger_, "Connecting RX Channel to endpoint: " << rxEndPoint); rxChannel_.connect(rxEndPoint.c_str()); rxChannel_.subscribe(""); } catch (zmq::error_t& e) { //std::stringstream ss; //ss << "RX channel connect to endpoint " << config_.rx_channel_endpoint_ << " failed: " << e.what(); // TODO: What to do here, I think throw it up throw std::runtime_error(e.what()); } // Add the Frame Ready channel to the reactor reactor_->register_channel(rxChannel_, boost::bind(&SharedMemoryController::handleRxChannel, this)); // Now connect the frame release response channel try { LOG4CXX_DEBUG(logger_, "Connecting TX Channel to endpoint: " << txEndPoint); txChannel_.connect(txEndPoint.c_str()); } catch (zmq::error_t& e) { //std::stringstream ss; //ss << "RX channel connect to endpoint " << config_.rx_channel_endpoint_ << " failed: " << e.what(); // TODO: What to do here, I think throw it up throw std::runtime_error(e.what()); } } SharedMemoryController::~SharedMemoryController() { LOG4CXX_TRACE(logger_, "SharedMemoryController destructor."); } /** setSharedMemoryParser * Takes a shared pointer to a shared memory parser and stores it in * a member variable. * * \param[in] smp - shared pointer to a SharedMemoryParser object. */ void SharedMemoryController::setSharedMemoryParser(boost::shared_ptr<SharedMemoryParser> smp) { smp_ = smp; } void SharedMemoryController::handleRxChannel() { // Receive a message from the main thread channel std::string rxMsgEncoded = rxChannel_.recv(); LOG4CXX_DEBUG(logger_, "RX thread called with message: " << rxMsgEncoded); // Parse and handle the message try { FrameReceiver::IpcMessage rxMsg(rxMsgEncoded.c_str()); if ((rxMsg.get_msg_type() == FrameReceiver::IpcMessage::MsgTypeNotify) && (rxMsg.get_msg_val() == FrameReceiver::IpcMessage::MsgValNotifyFrameReady)){ int bufferID = rxMsg.get_param<int>("buffer_id", -1); if (bufferID != -1){ // Create a frame object and copy in the raw frame data boost::shared_ptr<Frame> frame; frame = boost::shared_ptr<Frame>(new Frame("raw")); smp_->get_frame((*frame), bufferID); // Loop over registered callbacks, placing the frame onto each queue std::map<std::string, boost::shared_ptr<IFrameCallback> >::iterator cbIter; for (cbIter = callbacks_.begin(); cbIter != callbacks_.end(); ++cbIter){ cbIter->second->getWorkQueue()->add(frame); } // We want to send the notify frame release message back to the frameReceiver FrameReceiver::IpcMessage txMsg(FrameReceiver::IpcMessage::MsgTypeNotify, FrameReceiver::IpcMessage::MsgValNotifyFrameRelease); txMsg.set_param("frame", rxMsg.get_param<int>("frame")); txMsg.set_param("buffer_id", rxMsg.get_param<int>("buffer_id")); LOG4CXX_DEBUG(logger_, "Sending response: " << txMsg.encode()); // Now publish the release message, to notify the frame receiver that we are // finished with that block of shared memory txChannel_.send(txMsg.encode()); } else { LOG4CXX_ERROR(logger_, "RX thread received empty frame notification with buffer ID"); } } else { LOG4CXX_ERROR(logger_, "RX thread got unexpected message: " << rxMsgEncoded); //IpcMessage rx_reply; //rx_reply.set_msg_type(IpcMessage::MsgTypeNack); //rx_reply.set_msg_val(rx_msg.get_msg_val()); //TODO add error in params //rx_channel_.send(rx_reply.encode()); } } catch (FrameReceiver::IpcMessageException& e) { LOG4CXX_ERROR(logger_, "Error decoding control channel request: " << e.what()); } } void SharedMemoryController::registerCallback(const std::string& name, boost::shared_ptr<IFrameCallback> cb) { // Check if we own the callback already if (callbacks_.count(name) == 0){ // Record the callback pointer callbacks_[name] = cb; // Confirm registration cb->confirmRegistration("frame_receiver"); } } void SharedMemoryController::removeCallback(const std::string& name) { boost::shared_ptr<IFrameCallback> cb; if (callbacks_.count(name) > 0){ // Get the pointer cb = callbacks_[name]; // Remove the callback from the map callbacks_.erase(name); // Confirm removal cb->confirmRemoval("frame_receiver"); } } } /* namespace filewriter */ <commit_msg>Set the frame number when a new frame is created in SharedMemoryController.<commit_after>/* * SharedMemoryController.cpp * * Created on: 31 May 2016 * Author: gnx91527 */ #include <SharedMemoryController.h> namespace filewriter { /** Constructor. * The constructor sets up logging used within the class. */ SharedMemoryController::SharedMemoryController(boost::shared_ptr<FrameReceiver::IpcReactor> reactor, const std::string& rxEndPoint, const std::string& txEndPoint) : reactor_(reactor), rxChannel_(ZMQ_SUB), txChannel_(ZMQ_PUB) { // Setup logging for the class logger_ = Logger::getLogger("SharedMemoryController"); logger_->setLevel(Level::getAll()); LOG4CXX_TRACE(logger_, "SharedMemoryController constructor."); // Connect the frame ready channel try { LOG4CXX_DEBUG(logger_, "Connecting RX Channel to endpoint: " << rxEndPoint); rxChannel_.connect(rxEndPoint.c_str()); rxChannel_.subscribe(""); } catch (zmq::error_t& e) { //std::stringstream ss; //ss << "RX channel connect to endpoint " << config_.rx_channel_endpoint_ << " failed: " << e.what(); // TODO: What to do here, I think throw it up throw std::runtime_error(e.what()); } // Add the Frame Ready channel to the reactor reactor_->register_channel(rxChannel_, boost::bind(&SharedMemoryController::handleRxChannel, this)); // Now connect the frame release response channel try { LOG4CXX_DEBUG(logger_, "Connecting TX Channel to endpoint: " << txEndPoint); txChannel_.connect(txEndPoint.c_str()); } catch (zmq::error_t& e) { //std::stringstream ss; //ss << "RX channel connect to endpoint " << config_.rx_channel_endpoint_ << " failed: " << e.what(); // TODO: What to do here, I think throw it up throw std::runtime_error(e.what()); } } SharedMemoryController::~SharedMemoryController() { LOG4CXX_TRACE(logger_, "SharedMemoryController destructor."); } /** setSharedMemoryParser * Takes a shared pointer to a shared memory parser and stores it in * a member variable. * * \param[in] smp - shared pointer to a SharedMemoryParser object. */ void SharedMemoryController::setSharedMemoryParser(boost::shared_ptr<SharedMemoryParser> smp) { smp_ = smp; } void SharedMemoryController::handleRxChannel() { // Receive a message from the main thread channel std::string rxMsgEncoded = rxChannel_.recv(); LOG4CXX_DEBUG(logger_, "RX thread called with message: " << rxMsgEncoded); // Parse and handle the message try { FrameReceiver::IpcMessage rxMsg(rxMsgEncoded.c_str()); if ((rxMsg.get_msg_type() == FrameReceiver::IpcMessage::MsgTypeNotify) && (rxMsg.get_msg_val() == FrameReceiver::IpcMessage::MsgValNotifyFrameReady)){ int bufferID = rxMsg.get_param<int>("buffer_id", -1); if (bufferID != -1){ // Create a frame object and copy in the raw frame data boost::shared_ptr<Frame> frame; frame = boost::shared_ptr<Frame>(new Frame("raw")); smp_->get_frame((*frame), bufferID); // Set the frame number frame->set_frame_number(rxMsg.get_param<int>("frame", 0)); // Loop over registered callbacks, placing the frame onto each queue std::map<std::string, boost::shared_ptr<IFrameCallback> >::iterator cbIter; for (cbIter = callbacks_.begin(); cbIter != callbacks_.end(); ++cbIter){ cbIter->second->getWorkQueue()->add(frame); } // We want to send the notify frame release message back to the frameReceiver FrameReceiver::IpcMessage txMsg(FrameReceiver::IpcMessage::MsgTypeNotify, FrameReceiver::IpcMessage::MsgValNotifyFrameRelease); txMsg.set_param("frame", rxMsg.get_param<int>("frame")); txMsg.set_param("buffer_id", rxMsg.get_param<int>("buffer_id")); LOG4CXX_DEBUG(logger_, "Sending response: " << txMsg.encode()); // Now publish the release message, to notify the frame receiver that we are // finished with that block of shared memory txChannel_.send(txMsg.encode()); } else { LOG4CXX_ERROR(logger_, "RX thread received empty frame notification with buffer ID"); } } else { LOG4CXX_ERROR(logger_, "RX thread got unexpected message: " << rxMsgEncoded); //IpcMessage rx_reply; //rx_reply.set_msg_type(IpcMessage::MsgTypeNack); //rx_reply.set_msg_val(rx_msg.get_msg_val()); //TODO add error in params //rx_channel_.send(rx_reply.encode()); } } catch (FrameReceiver::IpcMessageException& e) { LOG4CXX_ERROR(logger_, "Error decoding control channel request: " << e.what()); } } void SharedMemoryController::registerCallback(const std::string& name, boost::shared_ptr<IFrameCallback> cb) { // Check if we own the callback already if (callbacks_.count(name) == 0){ // Record the callback pointer callbacks_[name] = cb; // Confirm registration cb->confirmRegistration("frame_receiver"); } } void SharedMemoryController::removeCallback(const std::string& name) { boost::shared_ptr<IFrameCallback> cb; if (callbacks_.count(name) > 0){ // Get the pointer cb = callbacks_[name]; // Remove the callback from the map callbacks_.erase(name); // Confirm removal cb->confirmRemoval("frame_receiver"); } } } /* namespace filewriter */ <|endoftext|>
<commit_before>#include "upperlayer.hpp" #include <map> #include <utility> #include <vector> #include <algorithm> #include <ostream> #include <cassert> #include <functional> #include <initializer_list> #include <boost/asio.hpp> #include "upperlayer_properties.hpp" #include "upperlayer_statemachine.hpp" namespace upperlayer { namespace { using uchar = unsigned char; std::size_t be_char_to_16b(std::vector<uchar> bs) { assert(bs.size() == 2); std::size_t sz = 0; sz |= (static_cast<std::size_t>(bs[0]) << 8); sz |= (static_cast<std::size_t>(bs[1])); return sz; } std::size_t be_char_to_32b(std::vector<uchar> bs) { assert(bs.size() == 4); std::size_t sz = 0; sz |= (static_cast<std::size_t>(bs[0]) << 24); sz |= (static_cast<std::size_t>(bs[1]) << 16); sz |= (static_cast<std::size_t>(bs[2]) << 8); sz |= (static_cast<std::size_t>(bs[3])); return sz; } } scx::scx(std::initializer_list<std::pair<TYPE, std::function<void(scx*, std::unique_ptr<property>)>>> l): statem {}, handlers {} { for (const auto p : l) { handlers[p.first] = p.second; } } scx::~scx() { } void scx::send(property* p) { auto pdu = p->make_pdu(); auto ptype = get_type(pdu); if (statem.transition(ptype, false) != statemachine::CONN_STATE::INV) { boost::asio::async_write(sock(), boost::asio::buffer(pdu), [=](const boost::system::error_code& error, std::size_t bytes) { } ); } } void scx::do_read() { static std::vector<unsigned char> size(6); // watch for scope static std::vector<unsigned char> rem_data; static std::vector<unsigned char> compl_data; boost::asio::async_read(sock(), boost::asio::buffer(size), boost::asio::transfer_exactly(6), [=](const boost::system::error_code& error, std::size_t bytes) { assert(bytes == 6); std::size_t len = be_char_to_32b({size.begin()+2, size.begin()+6}); rem_data.resize(len); boost::asio::async_read(sock(), boost::asio::buffer(rem_data), boost::asio::transfer_exactly(len), [=](const boost::system::error_code& error, std::size_t bytes) { compl_data.reserve(size.size() + rem_data.size()); compl_data.insert(compl_data.end(), size.begin(), size.end()); compl_data.insert(compl_data.end(), rem_data.begin(), rem_data.end()); auto pdutype = get_type(compl_data); //state = transition_table_received_pdus[std::make_pair(state, pdutype)]; statem.transition(pdutype, true); // call appropriate handler handlers[pdutype](this, make_property(compl_data)); size.clear(); rem_data.clear(); compl_data.clear(); size.resize(6); // be ready for new incoming data if (get_state() != statemachine::CONN_STATE::STA2) { do_read(); } } ); } ); } void scx::run() { io_s().run(); } void scx::inject(TYPE t, std::function<void (scx*, std::unique_ptr<property>)> f) { handlers[t] = f; } statemachine::CONN_STATE scx::get_state() { return statem.get_state(); } scp::scp(short port, std::initializer_list<std::pair<TYPE, std::function<void(scx*, std::unique_ptr<property>)>>> l): scx {l}, io_service(), socket(io_service), acptr(io_service, boost::asio::ip::tcp::endpoint(boost::asio::ip::tcp::v4(), port)) { //acptr.accept(socket); acptr.async_accept(socket, [this](boost::system::error_code ec) { if (!ec) { do_read(); } } ); } scu::scu(std::string host, std::string port, std::initializer_list<std::pair<TYPE, std::function<void(scx*, std::unique_ptr<property>)>>> l): scx{l}, io_service(), resolver(io_service), query(host, port), endpoint_iterator(resolver.resolve(query)), socket(io_service) { boost::asio::ip::tcp::resolver::iterator end; boost::system::error_code error = boost::asio::error::host_not_found; while(error && endpoint_iterator != end) { socket.close(); socket.connect(*endpoint_iterator++, error); } assert(!error); } boost::asio::ip::tcp::socket&scp::sock() { return socket; } boost::asio::io_service&scp::io_s() { return io_service; } scp::~scp() { switch (get_state()) { case statemachine::CONN_STATE::STA2: break; default: { a_abort ab; boost::asio::write(sock(), boost::asio::buffer(ab.make_pdu())); } } } boost::asio::ip::tcp::socket& scu::sock() { return socket; } boost::asio::io_service& scu::io_s() { return io_service; } scu::~scu() { switch (get_state()) { case statemachine::CONN_STATE::STA2: break; default: { a_abort ab; boost::asio::write(sock(), boost::asio::buffer(ab.make_pdu())); } } } } <commit_msg>use shared_pointers in do_read() to keep the buffers in a valid state when async_read()s callback function is invoked<commit_after>#include "upperlayer.hpp" #include <map> #include <utility> #include <vector> #include <algorithm> #include <ostream> #include <cassert> #include <functional> #include <initializer_list> #include <boost/asio.hpp> #include "upperlayer_properties.hpp" #include "upperlayer_statemachine.hpp" namespace upperlayer { namespace { using uchar = unsigned char; std::size_t be_char_to_16b(std::vector<uchar> bs) { assert(bs.size() == 2); std::size_t sz = 0; sz |= (static_cast<std::size_t>(bs[0]) << 8); sz |= (static_cast<std::size_t>(bs[1])); return sz; } std::size_t be_char_to_32b(std::vector<uchar> bs) { assert(bs.size() == 4); std::size_t sz = 0; sz |= (static_cast<std::size_t>(bs[0]) << 24); sz |= (static_cast<std::size_t>(bs[1]) << 16); sz |= (static_cast<std::size_t>(bs[2]) << 8); sz |= (static_cast<std::size_t>(bs[3])); return sz; } } scx::scx(std::initializer_list<std::pair<TYPE, std::function<void(scx*, std::unique_ptr<property>)>>> l): statem {}, handlers {} { for (const auto p : l) { handlers[p.first] = p.second; } } scx::~scx() { } void scx::send(property* p) { auto pdu = p->make_pdu(); auto ptype = get_type(pdu); if (statem.transition(ptype, false) != statemachine::CONN_STATE::INV) { boost::asio::async_write(sock(), boost::asio::buffer(pdu), [=](const boost::system::error_code& error, std::size_t bytes) { } ); } } void scx::do_read() { auto size = std::make_shared<std::vector<unsigned char>>(6); auto rem_data = std::make_shared<std::vector<unsigned char>>(); auto compl_data = std::make_shared<std::vector<unsigned char>>(); boost::asio::async_read(sock(), boost::asio::buffer(*size), boost::asio::transfer_exactly(6), [=](const boost::system::error_code& error, std::size_t bytes) { assert(bytes == 6); std::size_t len = be_char_to_32b({size->begin()+2, size->begin()+6}); rem_data->resize(len); boost::asio::async_read(sock(), boost::asio::buffer(*rem_data), boost::asio::transfer_exactly(len), [=](const boost::system::error_code& error, std::size_t bytes) { compl_data->reserve(size->size() + rem_data->size()); compl_data->insert(compl_data->end(), size->begin(), size->end()); compl_data->insert(compl_data->end(), rem_data->begin(), rem_data->end()); auto pdutype = get_type(*compl_data); //state = transition_table_received_pdus[std::make_pair(state, pdutype)]; statem.transition(pdutype, true); // call appropriate handler handlers[pdutype](this, make_property(*compl_data)); // be ready for new incoming data if (get_state() != statemachine::CONN_STATE::STA2) { do_read(); } } ); } ); } void scx::run() { io_s().run(); } void scx::inject(TYPE t, std::function<void (scx*, std::unique_ptr<property>)> f) { handlers[t] = f; } statemachine::CONN_STATE scx::get_state() { return statem.get_state(); } scp::scp(short port, std::initializer_list<std::pair<TYPE, std::function<void(scx*, std::unique_ptr<property>)>>> l): scx {l}, io_service(), socket(io_service), acptr(io_service, boost::asio::ip::tcp::endpoint(boost::asio::ip::tcp::v4(), port)) { //acptr.accept(socket); acptr.async_accept(socket, [this](boost::system::error_code ec) { if (!ec) { do_read(); } } ); } scu::scu(std::string host, std::string port, std::initializer_list<std::pair<TYPE, std::function<void(scx*, std::unique_ptr<property>)>>> l): scx{l}, io_service(), resolver(io_service), query(host, port), endpoint_iterator(resolver.resolve(query)), socket(io_service) { boost::asio::ip::tcp::resolver::iterator end; boost::system::error_code error = boost::asio::error::host_not_found; while(error && endpoint_iterator != end) { socket.close(); socket.connect(*endpoint_iterator++, error); } assert(!error); } boost::asio::ip::tcp::socket&scp::sock() { return socket; } boost::asio::io_service&scp::io_s() { return io_service; } scp::~scp() { switch (get_state()) { case statemachine::CONN_STATE::STA2: break; default: { a_abort ab; boost::asio::write(sock(), boost::asio::buffer(ab.make_pdu())); } } } boost::asio::ip::tcp::socket& scu::sock() { return socket; } boost::asio::io_service& scu::io_s() { return io_service; } scu::~scu() { switch (get_state()) { case statemachine::CONN_STATE::STA2: break; default: { a_abort ab; boost::asio::write(sock(), boost::asio::buffer(ab.make_pdu())); } } } } <|endoftext|>
<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "sandbox/win/tests/common/controller.h" #include <string> #include "base/process.h" #include "base/process_util.h" #include "base/sys_string_conversions.h" #include "base/win/windows_version.h" #include "sandbox/win/src/sandbox_factory.h" namespace { static const int kDefaultTimeout = 10000; // Constructs a full path to a file inside the system32 folder. std::wstring MakePathToSys32(const wchar_t* name, bool is_obj_man_path) { wchar_t windows_path[MAX_PATH] = {0}; if (0 == ::GetSystemWindowsDirectoryW(windows_path, MAX_PATH)) return std::wstring(); std::wstring full_path(windows_path); if (full_path.empty()) return full_path; if (is_obj_man_path) full_path.insert(0, L"\\??\\"); full_path += L"\\system32\\"; full_path += name; return full_path; } // Constructs a full path to a file inside the syswow64 folder. std::wstring MakePathToSysWow64(const wchar_t* name, bool is_obj_man_path) { wchar_t windows_path[MAX_PATH] = {0}; if (0 == ::GetSystemWindowsDirectoryW(windows_path, MAX_PATH)) return std::wstring(); std::wstring full_path(windows_path); if (full_path.empty()) return full_path; if (is_obj_man_path) full_path.insert(0, L"\\??\\"); full_path += L"\\SysWOW64\\"; full_path += name; return full_path; } bool IsProcessRunning(HANDLE process) { DWORD exit_code = 0; if (::GetExitCodeProcess(process, &exit_code)) return exit_code == STILL_ACTIVE; return false; } } // namespace namespace sandbox { std::wstring MakePathToSys(const wchar_t* name, bool is_obj_man_path) { return (base::win::OSInfo::GetInstance()->wow64_status() == base::win::OSInfo::WOW64_ENABLED) ? MakePathToSysWow64(name, is_obj_man_path) : MakePathToSys32(name, is_obj_man_path); } BrokerServices* GetBroker() { static BrokerServices* broker = SandboxFactory::GetBrokerServices(); static bool is_initialized = false; if (!broker) { return NULL; } if (!is_initialized) { if (SBOX_ALL_OK != broker->Init()) return NULL; is_initialized = true; } return broker; } TestRunner::TestRunner(JobLevel job_level, TokenLevel startup_token, TokenLevel main_token) : is_init_(false), is_async_(false), no_sandbox_(false), target_process_id_(0) { Init(job_level, startup_token, main_token); } TestRunner::TestRunner() : is_init_(false), is_async_(false), no_sandbox_(false), target_process_id_(0) { Init(JOB_LOCKDOWN, USER_RESTRICTED_SAME_ACCESS, USER_LOCKDOWN); } void TestRunner::Init(JobLevel job_level, TokenLevel startup_token, TokenLevel main_token) { broker_ = NULL; policy_ = NULL; timeout_ = kDefaultTimeout; state_ = AFTER_REVERT; is_async_= false; kill_on_destruction_ = true; target_process_id_ = 0; broker_ = GetBroker(); if (!broker_) return; policy_ = broker_->CreatePolicy(); if (!policy_) return; policy_->SetJobLevel(job_level, 0); policy_->SetTokenLevel(startup_token, main_token); is_init_ = true; } TargetPolicy* TestRunner::GetPolicy() { return policy_; } TestRunner::~TestRunner() { if (target_process_ && kill_on_destruction_) ::TerminateProcess(target_process_, 0); if (policy_) policy_->Release(); } bool TestRunner::AddRule(TargetPolicy::SubSystem subsystem, TargetPolicy::Semantics semantics, const wchar_t* pattern) { if (!is_init_) return false; return (SBOX_ALL_OK == policy_->AddRule(subsystem, semantics, pattern)); } bool TestRunner::AddRuleSys32(TargetPolicy::Semantics semantics, const wchar_t* pattern) { if (!is_init_) return false; std::wstring win32_path = MakePathToSys32(pattern, false); if (win32_path.empty()) return false; if (!AddRule(TargetPolicy::SUBSYS_FILES, semantics, win32_path.c_str())) return false; if (base::win::OSInfo::GetInstance()->wow64_status() != base::win::OSInfo::WOW64_ENABLED) return true; win32_path = MakePathToSysWow64(pattern, false); if (win32_path.empty()) return false; return AddRule(TargetPolicy::SUBSYS_FILES, semantics, win32_path.c_str()); } bool TestRunner::AddFsRule(TargetPolicy::Semantics semantics, const wchar_t* pattern) { if (!is_init_) return false; return AddRule(TargetPolicy::SUBSYS_FILES, semantics, pattern); } int TestRunner::RunTest(const wchar_t* command) { if (MAX_STATE > 10) return SBOX_TEST_INVALID_PARAMETER; wchar_t state_number[2]; state_number[0] = L'0' + state_; state_number[1] = L'\0'; std::wstring full_command(state_number); full_command += L" "; full_command += command; return InternalRunTest(full_command.c_str()); } int TestRunner::InternalRunTest(const wchar_t* command) { if (!is_init_) return SBOX_TEST_FAILED_TO_RUN_TEST; // For simplicity TestRunner supports only one process per instance. if (target_process_) { if (IsProcessRunning(target_process_)) return SBOX_TEST_FAILED_TO_RUN_TEST; target_process_.Close(); target_process_id_ = 0; } // Get the path to the sandboxed process. wchar_t prog_name[MAX_PATH]; GetModuleFileNameW(NULL, prog_name, MAX_PATH); // Launch the sandboxed process. ResultCode result = SBOX_ALL_OK; PROCESS_INFORMATION target = {0}; std::wstring arguments(L"\""); arguments += prog_name; arguments += L"\" -child"; arguments += no_sandbox_ ? L"-no-sandbox " : L" "; arguments += command; if (no_sandbox_) { STARTUPINFO startup_info = {sizeof(STARTUPINFO)}; if (!::CreateProcessW(prog_name, &arguments[0], NULL, NULL, FALSE, 0, NULL, NULL, &startup_info, &target)) { return SBOX_ERROR_GENERIC; } broker_->AddTargetPeer(target.hProcess); } else { result = broker_->SpawnTarget(prog_name, arguments.c_str(), policy_, &target); } if (SBOX_ALL_OK != result) return SBOX_TEST_FAILED_TO_RUN_TEST; ::ResumeThread(target.hThread); // For an asynchronous run we don't bother waiting. if (is_async_) { target_process_.Set(target.hProcess); target_process_id_ = target.dwProcessId; ::CloseHandle(target.hThread); return SBOX_TEST_SUCCEEDED; } if (::IsDebuggerPresent()) { // Don't kill the target process on a time-out while we are debugging. timeout_ = INFINITE; } if (WAIT_TIMEOUT == ::WaitForSingleObject(target.hProcess, timeout_)) { ::TerminateProcess(target.hProcess, SBOX_TEST_TIMED_OUT); ::CloseHandle(target.hProcess); ::CloseHandle(target.hThread); return SBOX_TEST_TIMED_OUT; } DWORD exit_code = SBOX_TEST_LAST_RESULT; if (!::GetExitCodeProcess(target.hProcess, &exit_code)) { ::CloseHandle(target.hProcess); ::CloseHandle(target.hThread); return SBOX_TEST_FAILED_TO_RUN_TEST; } ::CloseHandle(target.hProcess); ::CloseHandle(target.hThread); return exit_code; } void TestRunner::SetTimeout(DWORD timeout_ms) { timeout_ = timeout_ms; } void TestRunner::SetTestState(SboxTestsState desired_state) { state_ = desired_state; } // This is the main procedure for the target (child) application. We'll find out // the target test and call it. // We expect the arguments to be: // argv[1] = "-child" // argv[2] = SboxTestsState when to run the command // argv[3] = command to run // argv[4...] = command arguments. int DispatchCall(int argc, wchar_t **argv) { if (argc < 4) return SBOX_TEST_INVALID_PARAMETER; // We hard code two tests to avoid dispatch failures. if (0 == _wcsicmp(argv[3], L"wait")) { Sleep(INFINITE); return SBOX_TEST_TIMED_OUT; } if (0 == _wcsicmp(argv[3], L"ping")) return SBOX_TEST_PING_OK; SboxTestsState state = static_cast<SboxTestsState>(_wtoi(argv[2])); if ((state <= MIN_STATE) || (state >= MAX_STATE)) return SBOX_TEST_INVALID_PARAMETER; HMODULE module; if (!GetModuleHandleEx(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT, reinterpret_cast<wchar_t*>(&DispatchCall), &module)) return SBOX_TEST_FAILED_TO_EXECUTE_COMMAND; std::string command_name = base::SysWideToMultiByte(argv[3], CP_UTF8); CommandFunction command = reinterpret_cast<CommandFunction>( ::GetProcAddress(module, command_name.c_str())); if (!command) return SBOX_TEST_FAILED_TO_EXECUTE_COMMAND; if (BEFORE_INIT == state) return command(argc - 4, argv + 4); else if (EVERY_STATE == state) command(argc - 4, argv + 4); TargetServices* target = SandboxFactory::GetTargetServices(); if (target) { if (SBOX_ALL_OK != target->Init()) return SBOX_TEST_FAILED_TO_EXECUTE_COMMAND; if (BEFORE_REVERT == state) return command(argc - 4, argv + 4); else if (EVERY_STATE == state) command(argc - 4, argv + 4); target->LowerToken(); } else if (0 != _wcsicmp(argv[1], L"-child-no-sandbox")) { return SBOX_TEST_FAILED_TO_EXECUTE_COMMAND; } return command(argc - 4, argv + 4); } } // namespace sandbox <commit_msg>Sandbox: Increase the default timeout of multiprocess tests to 1 minute.<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "sandbox/win/tests/common/controller.h" #include <string> #include "base/process.h" #include "base/process_util.h" #include "base/sys_string_conversions.h" #include "base/win/windows_version.h" #include "sandbox/win/src/sandbox_factory.h" namespace { static const int kDefaultTimeout = 60000; // Constructs a full path to a file inside the system32 folder. std::wstring MakePathToSys32(const wchar_t* name, bool is_obj_man_path) { wchar_t windows_path[MAX_PATH] = {0}; if (0 == ::GetSystemWindowsDirectoryW(windows_path, MAX_PATH)) return std::wstring(); std::wstring full_path(windows_path); if (full_path.empty()) return full_path; if (is_obj_man_path) full_path.insert(0, L"\\??\\"); full_path += L"\\system32\\"; full_path += name; return full_path; } // Constructs a full path to a file inside the syswow64 folder. std::wstring MakePathToSysWow64(const wchar_t* name, bool is_obj_man_path) { wchar_t windows_path[MAX_PATH] = {0}; if (0 == ::GetSystemWindowsDirectoryW(windows_path, MAX_PATH)) return std::wstring(); std::wstring full_path(windows_path); if (full_path.empty()) return full_path; if (is_obj_man_path) full_path.insert(0, L"\\??\\"); full_path += L"\\SysWOW64\\"; full_path += name; return full_path; } bool IsProcessRunning(HANDLE process) { DWORD exit_code = 0; if (::GetExitCodeProcess(process, &exit_code)) return exit_code == STILL_ACTIVE; return false; } } // namespace namespace sandbox { std::wstring MakePathToSys(const wchar_t* name, bool is_obj_man_path) { return (base::win::OSInfo::GetInstance()->wow64_status() == base::win::OSInfo::WOW64_ENABLED) ? MakePathToSysWow64(name, is_obj_man_path) : MakePathToSys32(name, is_obj_man_path); } BrokerServices* GetBroker() { static BrokerServices* broker = SandboxFactory::GetBrokerServices(); static bool is_initialized = false; if (!broker) { return NULL; } if (!is_initialized) { if (SBOX_ALL_OK != broker->Init()) return NULL; is_initialized = true; } return broker; } TestRunner::TestRunner(JobLevel job_level, TokenLevel startup_token, TokenLevel main_token) : is_init_(false), is_async_(false), no_sandbox_(false), target_process_id_(0) { Init(job_level, startup_token, main_token); } TestRunner::TestRunner() : is_init_(false), is_async_(false), no_sandbox_(false), target_process_id_(0) { Init(JOB_LOCKDOWN, USER_RESTRICTED_SAME_ACCESS, USER_LOCKDOWN); } void TestRunner::Init(JobLevel job_level, TokenLevel startup_token, TokenLevel main_token) { broker_ = NULL; policy_ = NULL; timeout_ = kDefaultTimeout; state_ = AFTER_REVERT; is_async_= false; kill_on_destruction_ = true; target_process_id_ = 0; broker_ = GetBroker(); if (!broker_) return; policy_ = broker_->CreatePolicy(); if (!policy_) return; policy_->SetJobLevel(job_level, 0); policy_->SetTokenLevel(startup_token, main_token); is_init_ = true; } TargetPolicy* TestRunner::GetPolicy() { return policy_; } TestRunner::~TestRunner() { if (target_process_ && kill_on_destruction_) ::TerminateProcess(target_process_, 0); if (policy_) policy_->Release(); } bool TestRunner::AddRule(TargetPolicy::SubSystem subsystem, TargetPolicy::Semantics semantics, const wchar_t* pattern) { if (!is_init_) return false; return (SBOX_ALL_OK == policy_->AddRule(subsystem, semantics, pattern)); } bool TestRunner::AddRuleSys32(TargetPolicy::Semantics semantics, const wchar_t* pattern) { if (!is_init_) return false; std::wstring win32_path = MakePathToSys32(pattern, false); if (win32_path.empty()) return false; if (!AddRule(TargetPolicy::SUBSYS_FILES, semantics, win32_path.c_str())) return false; if (base::win::OSInfo::GetInstance()->wow64_status() != base::win::OSInfo::WOW64_ENABLED) return true; win32_path = MakePathToSysWow64(pattern, false); if (win32_path.empty()) return false; return AddRule(TargetPolicy::SUBSYS_FILES, semantics, win32_path.c_str()); } bool TestRunner::AddFsRule(TargetPolicy::Semantics semantics, const wchar_t* pattern) { if (!is_init_) return false; return AddRule(TargetPolicy::SUBSYS_FILES, semantics, pattern); } int TestRunner::RunTest(const wchar_t* command) { if (MAX_STATE > 10) return SBOX_TEST_INVALID_PARAMETER; wchar_t state_number[2]; state_number[0] = L'0' + state_; state_number[1] = L'\0'; std::wstring full_command(state_number); full_command += L" "; full_command += command; return InternalRunTest(full_command.c_str()); } int TestRunner::InternalRunTest(const wchar_t* command) { if (!is_init_) return SBOX_TEST_FAILED_TO_RUN_TEST; // For simplicity TestRunner supports only one process per instance. if (target_process_) { if (IsProcessRunning(target_process_)) return SBOX_TEST_FAILED_TO_RUN_TEST; target_process_.Close(); target_process_id_ = 0; } // Get the path to the sandboxed process. wchar_t prog_name[MAX_PATH]; GetModuleFileNameW(NULL, prog_name, MAX_PATH); // Launch the sandboxed process. ResultCode result = SBOX_ALL_OK; PROCESS_INFORMATION target = {0}; std::wstring arguments(L"\""); arguments += prog_name; arguments += L"\" -child"; arguments += no_sandbox_ ? L"-no-sandbox " : L" "; arguments += command; if (no_sandbox_) { STARTUPINFO startup_info = {sizeof(STARTUPINFO)}; if (!::CreateProcessW(prog_name, &arguments[0], NULL, NULL, FALSE, 0, NULL, NULL, &startup_info, &target)) { return SBOX_ERROR_GENERIC; } broker_->AddTargetPeer(target.hProcess); } else { result = broker_->SpawnTarget(prog_name, arguments.c_str(), policy_, &target); } if (SBOX_ALL_OK != result) return SBOX_TEST_FAILED_TO_RUN_TEST; ::ResumeThread(target.hThread); // For an asynchronous run we don't bother waiting. if (is_async_) { target_process_.Set(target.hProcess); target_process_id_ = target.dwProcessId; ::CloseHandle(target.hThread); return SBOX_TEST_SUCCEEDED; } if (::IsDebuggerPresent()) { // Don't kill the target process on a time-out while we are debugging. timeout_ = INFINITE; } if (WAIT_TIMEOUT == ::WaitForSingleObject(target.hProcess, timeout_)) { ::TerminateProcess(target.hProcess, SBOX_TEST_TIMED_OUT); ::CloseHandle(target.hProcess); ::CloseHandle(target.hThread); return SBOX_TEST_TIMED_OUT; } DWORD exit_code = SBOX_TEST_LAST_RESULT; if (!::GetExitCodeProcess(target.hProcess, &exit_code)) { ::CloseHandle(target.hProcess); ::CloseHandle(target.hThread); return SBOX_TEST_FAILED_TO_RUN_TEST; } ::CloseHandle(target.hProcess); ::CloseHandle(target.hThread); return exit_code; } void TestRunner::SetTimeout(DWORD timeout_ms) { timeout_ = timeout_ms; } void TestRunner::SetTestState(SboxTestsState desired_state) { state_ = desired_state; } // This is the main procedure for the target (child) application. We'll find out // the target test and call it. // We expect the arguments to be: // argv[1] = "-child" // argv[2] = SboxTestsState when to run the command // argv[3] = command to run // argv[4...] = command arguments. int DispatchCall(int argc, wchar_t **argv) { if (argc < 4) return SBOX_TEST_INVALID_PARAMETER; // We hard code two tests to avoid dispatch failures. if (0 == _wcsicmp(argv[3], L"wait")) { Sleep(INFINITE); return SBOX_TEST_TIMED_OUT; } if (0 == _wcsicmp(argv[3], L"ping")) return SBOX_TEST_PING_OK; SboxTestsState state = static_cast<SboxTestsState>(_wtoi(argv[2])); if ((state <= MIN_STATE) || (state >= MAX_STATE)) return SBOX_TEST_INVALID_PARAMETER; HMODULE module; if (!GetModuleHandleEx(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT, reinterpret_cast<wchar_t*>(&DispatchCall), &module)) return SBOX_TEST_FAILED_TO_EXECUTE_COMMAND; std::string command_name = base::SysWideToMultiByte(argv[3], CP_UTF8); CommandFunction command = reinterpret_cast<CommandFunction>( ::GetProcAddress(module, command_name.c_str())); if (!command) return SBOX_TEST_FAILED_TO_EXECUTE_COMMAND; if (BEFORE_INIT == state) return command(argc - 4, argv + 4); else if (EVERY_STATE == state) command(argc - 4, argv + 4); TargetServices* target = SandboxFactory::GetTargetServices(); if (target) { if (SBOX_ALL_OK != target->Init()) return SBOX_TEST_FAILED_TO_EXECUTE_COMMAND; if (BEFORE_REVERT == state) return command(argc - 4, argv + 4); else if (EVERY_STATE == state) command(argc - 4, argv + 4); target->LowerToken(); } else if (0 != _wcsicmp(argv[1], L"-child-no-sandbox")) { return SBOX_TEST_FAILED_TO_EXECUTE_COMMAND; } return command(argc - 4, argv + 4); } } // namespace sandbox <|endoftext|>
<commit_before>#ifndef AB_MEMORY_HPP_ #define AB_MEMORY_HPP_ #include <Pith/Address.hpp> #include <Pith/Assert.hpp> #include <Pith/Page.hpp> #include <Pith/Result.hpp> #include <cstdint> namespace Ab { struct MemoryConfig { Pith::Span<Pith::Page> reservedPages_; std::size_t initialPageCount_; inline auto verify() const -> void { PITH_ASSERT(reservedPages_.length() <= initialPageCount_); } }; enum class MemoryState { DEAD, ACTIVE }; enum class MemoryError { SUCCESS, ERROR }; class Memory { public: static constexpr inline auto defaultConfig() -> const MemoryConfig& { return defaultConfig_; } inline constexpr Memory() : reservedPages_{nullptr, 0}, activePageCount_{0}, state_{MemoryState::DEAD} {}; ~Memory(); inline auto init(const MemoryConfig& config) -> MemoryError; inline auto kill() -> void; inline auto grow(std::size_t n = 1) -> MemoryError; inline auto activePages() const -> Pith::Span<Pith::Page> { return Pith::Span<Pith::Page>{reservedPages().value(), activePageCount_}; } inline auto reservedPages() const -> const Pith::Span<Pith::Page>& { return reservedPages_; } private: static constexpr const MemoryConfig defaultConfig_{ {nullptr, Pith::mebibytes(1)}, // reservedPages_ 1 // initialPageCount_ }; Pith::Span<Pith::Page> reservedPages_; std::size_t activePageCount_; MemoryState state_; }; inline Memory::~Memory() { PITH_ASSERT(state_ == MemoryState::DEAD); } inline auto Memory::init(const MemoryConfig& config) -> MemoryError { PITH_ASSERT(state_ == MemoryState::DEAD); config.verify(); auto result = Pith::Page::map(config.reservedPages_); if (!result) { return MemoryError::ERROR; } reservedPages_.value(result()); reservedPages_.length(config.reservedPages_.length()); int error = Pith::Page::setPermissions( activePages(), Pith::Page::Permission::READ | Pith::Page::Permission::WRITE); if (error != 0) { PITH_ASSERT(Pith::Page::unmap(reservedPages_) == 0); return MemoryError::ERROR; } state_ = MemoryState::ACTIVE; return MemoryError::SUCCESS; } inline auto Memory::kill() -> void { PITH_ASSERT(state_ == MemoryState::ACTIVE); state_ = MemoryState::DEAD; PITH_ASSERT(Pith::Page::unmap(reservedPages_) == 0); } inline auto Memory::grow(std::size_t n) -> MemoryError { PITH_ASSERT(state_ == MemoryState::ACTIVE); if (activePageCount_ + n > reservedPages().length()) { return MemoryError::ERROR; } Pith::Span<Pith::Page> newPages{activePages().end(), n}; int perm = Pith::Page::Permission::READ | Pith::Page::Permission::WRITE; auto result = Pith::Page::map(newPages, perm); PITH_ASSERT(result); activePageCount_ += n; return MemoryError::SUCCESS; } } // namespace Ab #endif // AB_MEMORY_HPP_ <commit_msg>Fix busted comparison<commit_after>#ifndef AB_MEMORY_HPP_ #define AB_MEMORY_HPP_ #include <Pith/Address.hpp> #include <Pith/Assert.hpp> #include <Pith/Page.hpp> #include <Pith/Result.hpp> #include <cstdint> namespace Ab { struct MemoryConfig { Pith::Span<Pith::Page> reservedPages_; std::size_t initialPageCount_; inline auto verify() const -> void { PITH_ASSERT(reservedPages_.length() >= initialPageCount_); } }; enum class MemoryState { DEAD, ACTIVE }; enum class MemoryError { SUCCESS, ERROR }; class Memory { public: static constexpr inline auto defaultConfig() -> const MemoryConfig& { return defaultConfig_; } inline constexpr Memory() : reservedPages_{nullptr, 0}, activePageCount_{0}, state_{MemoryState::DEAD} {}; ~Memory(); inline auto init(const MemoryConfig& config) -> MemoryError; inline auto kill() -> void; inline auto grow(std::size_t n = 1) -> MemoryError; inline auto activePages() const -> Pith::Span<Pith::Page> { return Pith::Span<Pith::Page>{reservedPages().value(), activePageCount_}; } inline auto reservedPages() const -> const Pith::Span<Pith::Page>& { return reservedPages_; } private: static constexpr const MemoryConfig defaultConfig_{ {nullptr, Pith::mebibytes(1)}, // reservedPages_ 1 // initialPageCount_ }; Pith::Span<Pith::Page> reservedPages_; std::size_t activePageCount_; MemoryState state_; }; inline Memory::~Memory() { PITH_ASSERT(state_ == MemoryState::DEAD); } inline auto Memory::init(const MemoryConfig& config) -> MemoryError { PITH_ASSERT(state_ == MemoryState::DEAD); config.verify(); auto result = Pith::Page::map(config.reservedPages_); if (!result) { return MemoryError::ERROR; } reservedPages_.value(result()); reservedPages_.length(config.reservedPages_.length()); int error = Pith::Page::setPermissions( activePages(), Pith::Page::Permission::READ | Pith::Page::Permission::WRITE); if (error != 0) { PITH_ASSERT(Pith::Page::unmap(reservedPages_) == 0); return MemoryError::ERROR; } state_ = MemoryState::ACTIVE; return MemoryError::SUCCESS; } inline auto Memory::kill() -> void { PITH_ASSERT(state_ == MemoryState::ACTIVE); state_ = MemoryState::DEAD; PITH_ASSERT(Pith::Page::unmap(reservedPages_) == 0); } inline auto Memory::grow(std::size_t n) -> MemoryError { PITH_ASSERT(state_ == MemoryState::ACTIVE); if (activePageCount_ + n > reservedPages().length()) { return MemoryError::ERROR; } Pith::Span<Pith::Page> newPages{activePages().end(), n}; int perm = Pith::Page::Permission::READ | Pith::Page::Permission::WRITE; auto result = Pith::Page::map(newPages, perm); PITH_ASSERT(result); activePageCount_ += n; return MemoryError::SUCCESS; } } // namespace Ab #endif // AB_MEMORY_HPP_ <|endoftext|>
<commit_before>#include "FpsStat.h" #include "common/color_config.h" #include "common/Vector.h" #include "render/LabelNew.h" #include "view/Screen.h" #include <sstream> namespace d2d { FpsStat::FpsStat(float interval) { m_interval = interval * CLOCKS_PER_SEC; m_last_time = 0; m_tot_cost = m_count = 0; } void FpsStat::Begin() { m_last_time = clock(); } void FpsStat::End() { if (m_tot_cost > m_interval || m_count > 60) { { float dt = (float)m_tot_cost / m_count; std::stringstream ss; ss << dt; m_time = "cost: "+ss.str()+" ms"; } { int fps = m_count * CLOCKS_PER_SEC / m_tot_cost; std::stringstream ss; ss << fps; m_fps = "fps: "+ss.str(); } m_tot_cost = m_count = 0; } clock_t curr = clock(); m_tot_cost += (curr - m_last_time); ++m_count; } void FpsStat::DrawTime(const Screen& scr) const { Draw(scr, m_time); } void FpsStat::DrawFPS(const Screen& scr) const { Draw(scr, m_fps); } void FpsStat::Draw(const Screen& scr, const std::string& str) const { LabelStyle style; style.has_edge = false; style.font_size = 20; style.width = 100; style.height = 50; style.color = LIGHT_RED; style.align_hori = HAT_LEFT; style.align_vert = VAT_TOP; const Vector& size = scr.GetSize(); Vector pos; pos.x = -size.x * 0.4f; pos.y = size.y * 0.45f; LabelNew::Print(Screen(size.x, size.y), m_time.c_str(), pos, style); } }<commit_msg>[FIXED] FpsStat除零错误<commit_after>#include "FpsStat.h" #include "common/color_config.h" #include "common/Vector.h" #include "render/LabelNew.h" #include "view/Screen.h" #include <sstream> namespace d2d { FpsStat::FpsStat(float interval) { m_interval = interval * CLOCKS_PER_SEC; m_last_time = 0; m_tot_cost = m_count = 0; } void FpsStat::Begin() { m_last_time = clock(); } void FpsStat::End() { if (m_tot_cost > m_interval || m_count > 60) { if (m_count != 0) { float dt = (float)m_tot_cost / m_count; std::stringstream ss; ss << dt; m_time = "cost: "+ss.str()+" ms"; } if (m_tot_cost != 0) { int fps = m_count * CLOCKS_PER_SEC / m_tot_cost; std::stringstream ss; ss << fps; m_fps = "fps: "+ss.str(); } m_tot_cost = m_count = 0; } clock_t curr = clock(); m_tot_cost += (curr - m_last_time); ++m_count; } void FpsStat::DrawTime(const Screen& scr) const { Draw(scr, m_time); } void FpsStat::DrawFPS(const Screen& scr) const { Draw(scr, m_fps); } void FpsStat::Draw(const Screen& scr, const std::string& str) const { LabelStyle style; style.has_edge = false; style.font_size = 20; style.width = 100; style.height = 50; style.color = LIGHT_RED; style.align_hori = HAT_LEFT; style.align_vert = VAT_TOP; const Vector& size = scr.GetSize(); Vector pos; pos.x = -size.x * 0.4f; pos.y = size.y * 0.45f; LabelNew::Print(Screen(size.x, size.y), m_time.c_str(), pos, style); } }<|endoftext|>
<commit_before>// Author: Enrico Guiraud, 2021 /************************************************************************* * Copyright (C) 1995-2021, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ #ifndef ROOT_RDF_RSAMPLEINFO #define ROOT_RDF_RSAMPLEINFO #include <ROOT/RStringView.hxx> #include <Rtypes.h> #include <functional> #include <stdexcept> #include <string> namespace ROOT { namespace RDF { /// This type represents a sample identifier, to be used in conjunction with RDataFrame features such as /// DefinePerSample() and per-sample callbacks. /// /// When the input data comes from a TTree, the string representation of RSampleInfo (which is returned by AsString() /// and that can be queried e.g. with Contains()) is of the form "<filename>/<treename>". /// /// In multi-thread runs, different tasks might process different entry ranges of the same sample, /// so RSampleInfo also provides methods to inspect which part of a sample is being taken into consideration. class RSampleInfo { // Currently backed by a simple string, might change in the future as we get usage experience. std::string fID; std::pair<ULong64_t, ULong64_t> fEntryRange; public: explicit RSampleInfo(std::string_view id, std::pair<ULong64_t, ULong64_t> entryRange) : fID(id), fEntryRange(entryRange) { } RSampleInfo() = default; RSampleInfo(const RSampleInfo &) = default; RSampleInfo &operator=(const RSampleInfo &) = default; RSampleInfo(RSampleInfo &&) = default; RSampleInfo &operator=(RSampleInfo &&) = default; ~RSampleInfo() = default; /// Check whether the sample name contains the given substring. bool Contains(std::string_view substr) const { // C++14 needs the conversion from std::string_view to std::string return fID.find(std::string(substr)) != std::string::npos; } /// Check whether the sample name is empty. /// /// This is the case e.g. when using a RDataFrame with no input data, constructed as `RDataFrame(nEntries)`. bool Empty() const { return fID.empty(); } /// Return a string representation of the sample name. /// /// The representation is of the form "<filename>/<treename>" if the input data comes from a TTree or a TChain. const std::string &AsString() const { return fID; } /// Return the entry range in this sample that is being taken into consideration. /// /// Multiple multi-threading tasks might process different entry ranges of the same sample. std::pair<ULong64_t, ULong64_t> EntryRange() const { return fEntryRange; } /// Return the number of entries of this sample that is being taken into consideration. ULong64_t NEntries() const { return fEntryRange.second - fEntryRange.first; } bool operator==(const RSampleInfo &other) const { return fID == other.fID; } bool operator!=(const RSampleInfo &other) const { return !(*this == other); } }; /// The type of a data-block callback, registered with a RDataFrame computation graph via e.g. /// DefinePerSample() or by certain actions (e.g. Snapshot()). using SampleCallback_t = std::function<void(unsigned int, const ROOT::RDF::RSampleInfo &)>; } // namespace RDF } // namespace ROOT #endif <commit_msg>[NFC][DF] Remove obsolete comment<commit_after>// Author: Enrico Guiraud, 2021 /************************************************************************* * Copyright (C) 1995-2021, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ #ifndef ROOT_RDF_RSAMPLEINFO #define ROOT_RDF_RSAMPLEINFO #include <ROOT/RStringView.hxx> #include <Rtypes.h> #include <functional> #include <stdexcept> #include <string> namespace ROOT { namespace RDF { /// This type represents a sample identifier, to be used in conjunction with RDataFrame features such as /// DefinePerSample() and per-sample callbacks. /// /// When the input data comes from a TTree, the string representation of RSampleInfo (which is returned by AsString() /// and that can be queried e.g. with Contains()) is of the form "<filename>/<treename>". /// /// In multi-thread runs, different tasks might process different entry ranges of the same sample, /// so RSampleInfo also provides methods to inspect which part of a sample is being taken into consideration. class RSampleInfo { std::string fID; std::pair<ULong64_t, ULong64_t> fEntryRange; public: explicit RSampleInfo(std::string_view id, std::pair<ULong64_t, ULong64_t> entryRange) : fID(id), fEntryRange(entryRange) { } RSampleInfo() = default; RSampleInfo(const RSampleInfo &) = default; RSampleInfo &operator=(const RSampleInfo &) = default; RSampleInfo(RSampleInfo &&) = default; RSampleInfo &operator=(RSampleInfo &&) = default; ~RSampleInfo() = default; /// Check whether the sample name contains the given substring. bool Contains(std::string_view substr) const { // C++14 needs the conversion from std::string_view to std::string return fID.find(std::string(substr)) != std::string::npos; } /// Check whether the sample name is empty. /// /// This is the case e.g. when using a RDataFrame with no input data, constructed as `RDataFrame(nEntries)`. bool Empty() const { return fID.empty(); } /// Return a string representation of the sample name. /// /// The representation is of the form "<filename>/<treename>" if the input data comes from a TTree or a TChain. const std::string &AsString() const { return fID; } /// Return the entry range in this sample that is being taken into consideration. /// /// Multiple multi-threading tasks might process different entry ranges of the same sample. std::pair<ULong64_t, ULong64_t> EntryRange() const { return fEntryRange; } /// Return the number of entries of this sample that is being taken into consideration. ULong64_t NEntries() const { return fEntryRange.second - fEntryRange.first; } bool operator==(const RSampleInfo &other) const { return fID == other.fID; } bool operator!=(const RSampleInfo &other) const { return !(*this == other); } }; /// The type of a data-block callback, registered with a RDataFrame computation graph via e.g. /// DefinePerSample() or by certain actions (e.g. Snapshot()). using SampleCallback_t = std::function<void(unsigned int, const ROOT::RDF::RSampleInfo &)>; } // namespace RDF } // namespace ROOT #endif <|endoftext|>
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* * Version: MPL 1.1 / GPLv3+ / LGPLv3+ * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License or as specified alternatively below. You may obtain a copy of * the License at http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * Major Contributor(s): * Copyright (C) 2012 Kohei Yoshida <kohei.yoshida@suse.com> * * All Rights Reserved. * * For minor contributions see the git repository. * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 3 or later (the "GPLv3+"), or * the GNU Lesser General Public License Version 3 or later (the "LGPLv3+"), * in which case the provisions of the GPLv3+ or the LGPLv3+ are applicable * instead of those above. */ #include "calcoptionsdlg.hxx" #include "calcoptionsdlg.hrc" #include "scresid.hxx" #include "svtools/svlbitm.hxx" namespace { class OptionString : public SvLBoxString { rtl::OUString maDesc; rtl::OUString maValue; public: OptionString(const rtl::OUString& rDesc, const rtl::OUString& rValue) : maDesc(rDesc), maValue(rValue) {} virtual void Paint(const Point& rPos, SvLBox& rDev, sal_uInt16 nFlags, SvLBoxEntry* pEntry); }; void OptionString::Paint(const Point& rPos, SvLBox& rDev, sal_uInt16 /*nFlags*/, SvLBoxEntry* /*pEntry*/) { Point aPos = rPos; rtl::OUString aDesc = maDesc + rtl::OUString(": "); rDev.DrawText(aPos, aDesc); aPos.X() += rDev.GetTextWidth(aDesc); Font aOldFont = rDev.GetFont(); Font aFont = aOldFont; aFont.SetWeight(WEIGHT_BOLD); rDev.SetFont(aFont); rDev.DrawText(aPos, maValue); rDev.SetFont(aOldFont); } formula::FormulaGrammar::AddressConvention toAddressConvention(sal_uInt16 nPos) { switch (nPos) { case 1: return formula::FormulaGrammar::CONV_OOO; case 2: return formula::FormulaGrammar::CONV_XL_A1; case 3: return formula::FormulaGrammar::CONV_XL_R1C1; case 0: default: ; } return formula::FormulaGrammar::CONV_UNSPECIFIED; } } ScCalcOptionsDialog::ScCalcOptionsDialog(Window* pParent, const ScCalcConfig& rConfig) : ModalDialog(pParent, ScResId(RID_SCDLG_FORMULA_CALCOPTIONS)), maLbSettings(this, ScResId(LB_SETTINGS)), maFtOptionEditCaption(this, ScResId(FT_OPTION_EDIT_CAPTION)), maLbOptionEdit(this, ScResId(LB_OPTION_EDIT)), maBtnTrue(this, ScResId(BTN_OPTION_TRUE)), maBtnFalse(this, ScResId(BTN_OPTION_FALSE)), maFlAnnotation(this, ScResId(FL_ANNOTATION)), maFtAnnotation(this, ScResId(FT_ANNOTATION)), maBtnOK(this, ScResId(BTN_OK)), maBtnCancel(this, ScResId(BTN_CANCEL)), maTrue(ScResId(STR_TRUE).toString()), maFalse(ScResId(STR_FALSE).toString()), maCalcA1(ScResId(SCSTR_FORMULA_SYNTAX_CALC_A1).toString()), maExcelA1(ScResId(SCSTR_FORMULA_SYNTAX_XL_A1).toString()), maExcelR1C1(ScResId(SCSTR_FORMULA_SYNTAX_XL_R1C1).toString()), maCaptionStringRefSyntax(ScResId(STR_STRING_REF_SYNTAX_CAPTION).toString()), maDescStringRefSyntax(ScResId(STR_STRING_REF_SYNTAX_DESC).toString()), maUseFormulaSyntax(ScResId(STR_USE_FORMULA_SYNTAX).toString()), maCaptionEmptyStringAsZero(ScResId(STR_EMPTY_STRING_AS_ZERO_CAPTION).toString()), maDescEmptyStringAsZero(ScResId(STR_EMPTY_STRING_AS_ZERO_DESC).toString()), maConfig(rConfig) { maLbSettings.SetStyle(maLbSettings.GetStyle() | WB_CLIPCHILDREN | WB_FORCE_MAKEVISIBLE); maLbSettings.SetHighlightRange(); Link aLink = LINK(this, ScCalcOptionsDialog, SettingsSelHdl); maLbSettings.SetSelectHdl(aLink); maLbOptionEdit.SetSelectHdl(aLink); aLink = LINK(this, ScCalcOptionsDialog, BtnToggleHdl); maBtnTrue.SetToggleHdl(aLink); // Set handler only to the 'True' button. maBtnTrue.SetText(maTrue); maBtnFalse.SetText(maFalse); FillOptionsList(); FreeResource(); SelectionChanged(); } ScCalcOptionsDialog::~ScCalcOptionsDialog() {} const ScCalcConfig& ScCalcOptionsDialog::GetConfig() const { return maConfig; } void ScCalcOptionsDialog::FillOptionsList() { maLbSettings.SetUpdateMode(false); maLbSettings.Clear(); SvLBoxTreeList* pModel = maLbSettings.GetModel(); { // Syntax for INDIRECT function. SvLBoxEntry* pEntry = new SvLBoxEntry; pEntry->AddItem(new SvLBoxString(pEntry, 0, rtl::OUString())); pEntry->AddItem(new SvLBoxContextBmp(pEntry, 0, Image(), Image(), 0)); OptionString* pItem = new OptionString( maCaptionStringRefSyntax, toString(maConfig.meStringRefAddressSyntax)); pEntry->AddItem(pItem); pModel->Insert(pEntry); } { // Treat empty string as zero. SvLBoxEntry* pEntry = new SvLBoxEntry; pEntry->AddItem(new SvLBoxString(pEntry, 0, rtl::OUString())); pEntry->AddItem(new SvLBoxContextBmp(pEntry, 0, Image(), Image(), 0)); OptionString* pItem = new OptionString( maCaptionEmptyStringAsZero, toString(maConfig.mbEmptyStringAsZero)); pEntry->AddItem(pItem); pModel->Insert(pEntry); } maLbSettings.SetUpdateMode(true); } void ScCalcOptionsDialog::SelectionChanged() { sal_uInt16 nSelectedPos = maLbSettings.GetSelectEntryPos(); switch (nSelectedPos) { case 0: { // Formula syntax for INDIRECT function. maBtnTrue.Hide(); maBtnFalse.Hide(); maLbOptionEdit.Show(); maLbOptionEdit.Clear(); maLbOptionEdit.InsertEntry(maUseFormulaSyntax); maLbOptionEdit.InsertEntry(maCalcA1); maLbOptionEdit.InsertEntry(maExcelA1); maLbOptionEdit.InsertEntry(maExcelR1C1); switch (maConfig.meStringRefAddressSyntax) { case formula::FormulaGrammar::CONV_OOO: maLbOptionEdit.SelectEntryPos(1); break; case formula::FormulaGrammar::CONV_XL_A1: maLbOptionEdit.SelectEntryPos(2); break; case formula::FormulaGrammar::CONV_XL_R1C1: maLbOptionEdit.SelectEntryPos(3); break; case formula::FormulaGrammar::CONV_UNSPECIFIED: default: maLbOptionEdit.SelectEntryPos(0); } maFtAnnotation.SetText(maDescStringRefSyntax); } break; case 1: { // Treat empty string as zero. maLbOptionEdit.Hide(); maBtnTrue.Show(); maBtnFalse.Show(); if (maConfig.mbEmptyStringAsZero) { maBtnTrue.Check(true); maBtnFalse.Check(false); } else { maBtnTrue.Check(false); maBtnFalse.Check(true); } } break; default: ; } } void ScCalcOptionsDialog::ListOptionValueChanged() { sal_uInt16 nSelected = maLbSettings.GetSelectEntryPos(); switch (nSelected) { case 0: { // Formula syntax for INDIRECT function. sal_uInt16 nPos = maLbOptionEdit.GetSelectEntryPos(); maConfig.meStringRefAddressSyntax = toAddressConvention(nPos); maLbSettings.SetUpdateMode(false); SvLBoxTreeList* pModel = maLbSettings.GetModel(); SvLBoxEntry* pEntry = pModel->GetEntry(NULL, 0); if (!pEntry) return; OptionString* pItem = new OptionString( maCaptionStringRefSyntax, toString(maConfig.meStringRefAddressSyntax)); pEntry->ReplaceItem(pItem, 2); maLbSettings.SetUpdateMode(true); } break; default: ; } } void ScCalcOptionsDialog::RadioValueChanged() { sal_uInt16 nSelected = maLbSettings.GetSelectEntryPos(); switch (nSelected) { case 1: { // Treat empty string as zero. maConfig.mbEmptyStringAsZero = maBtnTrue.IsChecked(); maLbSettings.SetUpdateMode(false); SvLBoxTreeList* pModel = maLbSettings.GetModel(); SvLBoxEntry* pEntry = pModel->GetEntry(NULL, 1); if (!pEntry) return; OptionString* pItem = new OptionString( maCaptionEmptyStringAsZero, toString(maConfig.mbEmptyStringAsZero)); pEntry->ReplaceItem(pItem, 2); maLbSettings.SetUpdateMode(true); } break; default: ; } } rtl::OUString ScCalcOptionsDialog::toString(formula::FormulaGrammar::AddressConvention eConv) const { switch (eConv) { case formula::FormulaGrammar::CONV_OOO: return maCalcA1; case formula::FormulaGrammar::CONV_XL_A1: return maExcelA1; case formula::FormulaGrammar::CONV_XL_R1C1: return maExcelR1C1; case formula::FormulaGrammar::CONV_UNSPECIFIED: default: ; } return maUseFormulaSyntax; } rtl::OUString ScCalcOptionsDialog::toString(bool bVal) const { return bVal ? maTrue : maFalse; } IMPL_LINK(ScCalcOptionsDialog, SettingsSelHdl, Control*, pCtrl) { if (pCtrl == &maLbSettings) SelectionChanged(); else if (pCtrl == &maLbOptionEdit) ListOptionValueChanged(); return 0; } IMPL_LINK(ScCalcOptionsDialog, BtnToggleHdl, RadioButton*, pBtn) { RadioValueChanged(); return 0; } /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <commit_msg>Let's not forget to set the description for this option.<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* * Version: MPL 1.1 / GPLv3+ / LGPLv3+ * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License or as specified alternatively below. You may obtain a copy of * the License at http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * Major Contributor(s): * Copyright (C) 2012 Kohei Yoshida <kohei.yoshida@suse.com> * * All Rights Reserved. * * For minor contributions see the git repository. * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 3 or later (the "GPLv3+"), or * the GNU Lesser General Public License Version 3 or later (the "LGPLv3+"), * in which case the provisions of the GPLv3+ or the LGPLv3+ are applicable * instead of those above. */ #include "calcoptionsdlg.hxx" #include "calcoptionsdlg.hrc" #include "scresid.hxx" #include "svtools/svlbitm.hxx" namespace { class OptionString : public SvLBoxString { rtl::OUString maDesc; rtl::OUString maValue; public: OptionString(const rtl::OUString& rDesc, const rtl::OUString& rValue) : maDesc(rDesc), maValue(rValue) {} virtual void Paint(const Point& rPos, SvLBox& rDev, sal_uInt16 nFlags, SvLBoxEntry* pEntry); }; void OptionString::Paint(const Point& rPos, SvLBox& rDev, sal_uInt16 /*nFlags*/, SvLBoxEntry* /*pEntry*/) { Point aPos = rPos; rtl::OUString aDesc = maDesc + rtl::OUString(": "); rDev.DrawText(aPos, aDesc); aPos.X() += rDev.GetTextWidth(aDesc); Font aOldFont = rDev.GetFont(); Font aFont = aOldFont; aFont.SetWeight(WEIGHT_BOLD); rDev.SetFont(aFont); rDev.DrawText(aPos, maValue); rDev.SetFont(aOldFont); } formula::FormulaGrammar::AddressConvention toAddressConvention(sal_uInt16 nPos) { switch (nPos) { case 1: return formula::FormulaGrammar::CONV_OOO; case 2: return formula::FormulaGrammar::CONV_XL_A1; case 3: return formula::FormulaGrammar::CONV_XL_R1C1; case 0: default: ; } return formula::FormulaGrammar::CONV_UNSPECIFIED; } } ScCalcOptionsDialog::ScCalcOptionsDialog(Window* pParent, const ScCalcConfig& rConfig) : ModalDialog(pParent, ScResId(RID_SCDLG_FORMULA_CALCOPTIONS)), maLbSettings(this, ScResId(LB_SETTINGS)), maFtOptionEditCaption(this, ScResId(FT_OPTION_EDIT_CAPTION)), maLbOptionEdit(this, ScResId(LB_OPTION_EDIT)), maBtnTrue(this, ScResId(BTN_OPTION_TRUE)), maBtnFalse(this, ScResId(BTN_OPTION_FALSE)), maFlAnnotation(this, ScResId(FL_ANNOTATION)), maFtAnnotation(this, ScResId(FT_ANNOTATION)), maBtnOK(this, ScResId(BTN_OK)), maBtnCancel(this, ScResId(BTN_CANCEL)), maTrue(ScResId(STR_TRUE).toString()), maFalse(ScResId(STR_FALSE).toString()), maCalcA1(ScResId(SCSTR_FORMULA_SYNTAX_CALC_A1).toString()), maExcelA1(ScResId(SCSTR_FORMULA_SYNTAX_XL_A1).toString()), maExcelR1C1(ScResId(SCSTR_FORMULA_SYNTAX_XL_R1C1).toString()), maCaptionStringRefSyntax(ScResId(STR_STRING_REF_SYNTAX_CAPTION).toString()), maDescStringRefSyntax(ScResId(STR_STRING_REF_SYNTAX_DESC).toString()), maUseFormulaSyntax(ScResId(STR_USE_FORMULA_SYNTAX).toString()), maCaptionEmptyStringAsZero(ScResId(STR_EMPTY_STRING_AS_ZERO_CAPTION).toString()), maDescEmptyStringAsZero(ScResId(STR_EMPTY_STRING_AS_ZERO_DESC).toString()), maConfig(rConfig) { maLbSettings.SetStyle(maLbSettings.GetStyle() | WB_CLIPCHILDREN | WB_FORCE_MAKEVISIBLE); maLbSettings.SetHighlightRange(); Link aLink = LINK(this, ScCalcOptionsDialog, SettingsSelHdl); maLbSettings.SetSelectHdl(aLink); maLbOptionEdit.SetSelectHdl(aLink); aLink = LINK(this, ScCalcOptionsDialog, BtnToggleHdl); maBtnTrue.SetToggleHdl(aLink); // Set handler only to the 'True' button. maBtnTrue.SetText(maTrue); maBtnFalse.SetText(maFalse); FillOptionsList(); FreeResource(); SelectionChanged(); } ScCalcOptionsDialog::~ScCalcOptionsDialog() {} const ScCalcConfig& ScCalcOptionsDialog::GetConfig() const { return maConfig; } void ScCalcOptionsDialog::FillOptionsList() { maLbSettings.SetUpdateMode(false); maLbSettings.Clear(); SvLBoxTreeList* pModel = maLbSettings.GetModel(); { // Syntax for INDIRECT function. SvLBoxEntry* pEntry = new SvLBoxEntry; pEntry->AddItem(new SvLBoxString(pEntry, 0, rtl::OUString())); pEntry->AddItem(new SvLBoxContextBmp(pEntry, 0, Image(), Image(), 0)); OptionString* pItem = new OptionString( maCaptionStringRefSyntax, toString(maConfig.meStringRefAddressSyntax)); pEntry->AddItem(pItem); pModel->Insert(pEntry); } { // Treat empty string as zero. SvLBoxEntry* pEntry = new SvLBoxEntry; pEntry->AddItem(new SvLBoxString(pEntry, 0, rtl::OUString())); pEntry->AddItem(new SvLBoxContextBmp(pEntry, 0, Image(), Image(), 0)); OptionString* pItem = new OptionString( maCaptionEmptyStringAsZero, toString(maConfig.mbEmptyStringAsZero)); pEntry->AddItem(pItem); pModel->Insert(pEntry); } maLbSettings.SetUpdateMode(true); } void ScCalcOptionsDialog::SelectionChanged() { sal_uInt16 nSelectedPos = maLbSettings.GetSelectEntryPos(); switch (nSelectedPos) { case 0: { // Formula syntax for INDIRECT function. maBtnTrue.Hide(); maBtnFalse.Hide(); maLbOptionEdit.Show(); maLbOptionEdit.Clear(); maLbOptionEdit.InsertEntry(maUseFormulaSyntax); maLbOptionEdit.InsertEntry(maCalcA1); maLbOptionEdit.InsertEntry(maExcelA1); maLbOptionEdit.InsertEntry(maExcelR1C1); switch (maConfig.meStringRefAddressSyntax) { case formula::FormulaGrammar::CONV_OOO: maLbOptionEdit.SelectEntryPos(1); break; case formula::FormulaGrammar::CONV_XL_A1: maLbOptionEdit.SelectEntryPos(2); break; case formula::FormulaGrammar::CONV_XL_R1C1: maLbOptionEdit.SelectEntryPos(3); break; case formula::FormulaGrammar::CONV_UNSPECIFIED: default: maLbOptionEdit.SelectEntryPos(0); } maFtAnnotation.SetText(maDescStringRefSyntax); } break; case 1: { // Treat empty string as zero. maLbOptionEdit.Hide(); maBtnTrue.Show(); maBtnFalse.Show(); if (maConfig.mbEmptyStringAsZero) { maBtnTrue.Check(true); maBtnFalse.Check(false); } else { maBtnTrue.Check(false); maBtnFalse.Check(true); } maFtAnnotation.SetText(maDescEmptyStringAsZero); } break; default: ; } } void ScCalcOptionsDialog::ListOptionValueChanged() { sal_uInt16 nSelected = maLbSettings.GetSelectEntryPos(); switch (nSelected) { case 0: { // Formula syntax for INDIRECT function. sal_uInt16 nPos = maLbOptionEdit.GetSelectEntryPos(); maConfig.meStringRefAddressSyntax = toAddressConvention(nPos); maLbSettings.SetUpdateMode(false); SvLBoxTreeList* pModel = maLbSettings.GetModel(); SvLBoxEntry* pEntry = pModel->GetEntry(NULL, 0); if (!pEntry) return; OptionString* pItem = new OptionString( maCaptionStringRefSyntax, toString(maConfig.meStringRefAddressSyntax)); pEntry->ReplaceItem(pItem, 2); maLbSettings.SetUpdateMode(true); } break; default: ; } } void ScCalcOptionsDialog::RadioValueChanged() { sal_uInt16 nSelected = maLbSettings.GetSelectEntryPos(); switch (nSelected) { case 1: { // Treat empty string as zero. maConfig.mbEmptyStringAsZero = maBtnTrue.IsChecked(); maLbSettings.SetUpdateMode(false); SvLBoxTreeList* pModel = maLbSettings.GetModel(); SvLBoxEntry* pEntry = pModel->GetEntry(NULL, 1); if (!pEntry) return; OptionString* pItem = new OptionString( maCaptionEmptyStringAsZero, toString(maConfig.mbEmptyStringAsZero)); pEntry->ReplaceItem(pItem, 2); maLbSettings.SetUpdateMode(true); } break; default: ; } } rtl::OUString ScCalcOptionsDialog::toString(formula::FormulaGrammar::AddressConvention eConv) const { switch (eConv) { case formula::FormulaGrammar::CONV_OOO: return maCalcA1; case formula::FormulaGrammar::CONV_XL_A1: return maExcelA1; case formula::FormulaGrammar::CONV_XL_R1C1: return maExcelR1C1; case formula::FormulaGrammar::CONV_UNSPECIFIED: default: ; } return maUseFormulaSyntax; } rtl::OUString ScCalcOptionsDialog::toString(bool bVal) const { return bVal ? maTrue : maFalse; } IMPL_LINK(ScCalcOptionsDialog, SettingsSelHdl, Control*, pCtrl) { if (pCtrl == &maLbSettings) SelectionChanged(); else if (pCtrl == &maLbOptionEdit) ListOptionValueChanged(); return 0; } IMPL_LINK(ScCalcOptionsDialog, BtnToggleHdl, RadioButton*, pBtn) { RadioValueChanged(); return 0; } /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <|endoftext|>
<commit_before>// This file is part of OpenCV project. // It is subject to the license terms in the LICENSE file found in the top-level directory // of this distribution and at http://opencv.org/license.html. // // Copyright (C) 2018 Intel Corporation #ifndef OPENCV_GAPI_OWN_MAT_HPP #define OPENCV_GAPI_OWN_MAT_HPP #include <opencv2/gapi/opencv_includes.hpp> #include <opencv2/gapi/own/types.hpp> #include <opencv2/gapi/own/scalar.hpp> #include <opencv2/gapi/own/saturate.hpp> #include <opencv2/gapi/own/assert.hpp> #include <memory> //std::shared_ptr #include <cstring> //std::memcpy #include <numeric> //std::accumulate #include <opencv2/gapi/util/throw.hpp> namespace cv { namespace gapi { namespace own { namespace detail { template <typename T, unsigned char channels> void assign_row(void* ptr, int cols, Scalar const& s) { auto p = static_cast<T*>(ptr); for (int c = 0; c < cols; c++) { for (int ch = 0; ch < channels; ch++) { p[c * channels + ch] = saturate<T>(s[ch], roundd); } } } inline size_t default_step(int type, int cols) { return CV_ELEM_SIZE(type) * cols; } //Matrix header, i.e. fields that are unique to each Mat object. //Devoted class is needed to implement custom behavior on move (erasing state of moved from object) struct MatHeader{ enum { AUTO_STEP = 0}; enum { TYPE_MASK = 0x00000FFF }; MatHeader() = default; MatHeader(int _rows, int _cols, int type, void* _data, size_t _step) : flags((type & TYPE_MASK)), rows(_rows), cols(_cols), data((uchar*)_data), step(_step == AUTO_STEP ? detail::default_step(type, _cols) : _step) {} MatHeader(const std::vector<int> &_dims, int type, void* _data) : flags((type & TYPE_MASK)), data((uchar*)_data), step(0), dims(_dims) {} MatHeader(const MatHeader& ) = default; MatHeader(MatHeader&& src) : MatHeader(src) // reuse copy constructor here { MatHeader empty; //give it a name to call copy(not move) assignment below src = empty; } MatHeader& operator=(const MatHeader& ) = default; MatHeader& operator=(MatHeader&& src) { *this = src; //calling a copy assignment here, not move one MatHeader empty; //give it a name to call copy(not move) assignment below src = empty; return *this; } /*! includes several bit-fields: - depth - number of channels */ int flags = 0; //! the number of rows and columns or (-1, -1) when the matrix has more than 2 dimensions int rows = 0, cols = 0; //! pointer to the data uchar* data = nullptr; size_t step = 0; //! dimensions (ND-case) std::vector<int> dims; }; } // namespace detail //concise version of cv::Mat suitable for GAPI needs (used when no dependence on OpenCV is required) class Mat : public detail::MatHeader{ public: Mat() = default; /** @overload @param _rows Number of rows in a 2D array. @param _cols Number of columns in a 2D array. @param _type Array type. Use CV_8UC1, ..., CV_64FC4 to create 1-4 channel matrices, or CV_8UC(n), ..., CV_64FC(n) to create multi-channel (up to CV_CN_MAX channels) matrices. @param _data Pointer to the user data. Matrix constructors that take data and step parameters do not allocate matrix data. Instead, they just initialize the matrix header that points to the specified data, which means that no data is copied. This operation is very efficient and can be used to process external data using OpenCV functions. The external data is not automatically deallocated, so you should take care of it. @param _step Number of bytes each matrix row occupies. The value should include the padding bytes at the end of each row, if any. If the parameter is missing (set to AUTO_STEP ), no padding is assumed and the actual step is calculated as cols*elemSize(). See Mat::elemSize. */ Mat(int _rows, int _cols, int _type, void* _data, size_t _step = AUTO_STEP) : MatHeader (_rows, _cols, _type, _data, _step) {} Mat(const std::vector<int> &_dims, int _type, void* _data) : MatHeader (_dims, _type, _data) {} Mat(std::vector<int> &&_dims, int _type, void* _data) : MatHeader (std::move(_dims), _type, _data) {} Mat(Mat const& src, const Rect& roi ) : Mat(src) { rows = roi.height; cols = roi.width; data = ptr(roi.y, roi.x); } Mat(Mat const& src) = default; Mat(Mat&& src) = default; Mat& operator=(Mat const& src) = default; Mat& operator=(Mat&& src) = default; /** @brief Sets all or some of the array elements to the specified value. @param s Assigned scalar converted to the actual array type. */ Mat& operator = (const Scalar& s) { constexpr unsigned max_channels = 4; //Scalar can't fit more than 4 using func_p_t = void (*)(void*, int, Scalar const&); using detail::assign_row; #define TABLE_ENTRY(type) {assign_row<type, 1>, assign_row<type, 2>, assign_row<type, 3>, assign_row<type, 4>} static constexpr func_p_t func_tbl[][max_channels] = { TABLE_ENTRY(uchar), TABLE_ENTRY(schar), TABLE_ENTRY(ushort), TABLE_ENTRY(short), TABLE_ENTRY(int), TABLE_ENTRY(float), TABLE_ENTRY(double) }; #undef TABLE_ENTRY static_assert(CV_8U == 0 && CV_8S == 1 && CV_16U == 2 && CV_16S == 3 && CV_32S == 4 && CV_32F == 5 && CV_64F == 6, "OCV type ids used as indexes to array, thus exact numbers are important!" ); const auto depth = static_cast<unsigned int>(this->depth()); GAPI_Assert(depth < sizeof(func_tbl)/sizeof(func_tbl[0])); if (dims.empty()) { const auto channels = static_cast<unsigned int>(this->channels()); GAPI_Assert(channels <= max_channels); auto* f = func_tbl[depth][channels - 1]; for (int r = 0; r < rows; ++r) { (*f)(static_cast<void *>(ptr(r)), cols, s ); } } else { auto* f = func_tbl[depth][0]; // FIXME: better to refactor assign_row to use std::size_t by default (*f)(static_cast<void *>(data), static_cast<int>(total()), s); } return *this; } /** @brief Returns the matrix element size in bytes. The method returns the matrix element size in bytes. For example, if the matrix type is CV_16SC3 , the method returns 3\*sizeof(short) or 6. */ size_t elemSize() const { return CV_ELEM_SIZE(type()); } /** @brief Returns the type of a matrix element. The method returns a matrix element type. This is an identifier compatible with the CvMat type system, like CV_16SC3 or 16-bit signed 3-channel array, and so on. */ int type() const {return CV_MAT_TYPE(flags);} /** @brief Returns the depth of a matrix element. The method returns the identifier of the matrix element depth (the type of each individual channel). For example, for a 16-bit signed element array, the method returns CV_16S . A complete list of matrix types contains the following values: - CV_8U - 8-bit unsigned integers ( 0..255 ) - CV_8S - 8-bit signed integers ( -128..127 ) - CV_16U - 16-bit unsigned integers ( 0..65535 ) - CV_16S - 16-bit signed integers ( -32768..32767 ) - CV_32S - 32-bit signed integers ( -2147483648..2147483647 ) - CV_32F - 32-bit floating-point numbers ( -FLT_MAX..FLT_MAX, INF, NAN ) - CV_64F - 64-bit floating-point numbers ( -DBL_MAX..DBL_MAX, INF, NAN ) */ int depth() const {return CV_MAT_DEPTH(flags);} /** @brief Returns the number of matrix channels. The method returns the number of matrix channels. If matrix is N-dimensional, -1 is returned. */ int channels() const {return dims.empty() ? CV_MAT_CN(flags) : -1;} /** @param _rows New number of rows. @param _cols New number of columns. @param _type New matrix type. */ void create(int _rows, int _cols, int _type) { create(Size{_cols, _rows}, _type); } /** @overload @param _size Alternative new matrix size specification: Size(cols, rows) @param _type New matrix type. */ void create(Size _size, int _type) { if (_size != Size{cols, rows} ) { Mat tmp{_size.height, _size.width, _type, nullptr}; tmp.memory.reset(new uchar[ tmp.step * tmp.rows], [](uchar * p){delete[] p;}); tmp.data = tmp.memory.get(); *this = std::move(tmp); } } void create(const std::vector<int> &_dims, int _type) { // FIXME: make a proper reallocation-on-demands // WARNING: no tensor views, so no strides Mat tmp{_dims, _type, nullptr}; // FIXME: this accumulate duplicates a lot const auto sz = std::accumulate(_dims.begin(), _dims.end(), 1, std::multiplies<int>()); tmp.memory.reset(new uchar[CV_ELEM_SIZE(_type)*sz], [](uchar * p){delete[] p;}); tmp.data = tmp.memory.get(); *this = std::move(tmp); } /** @brief Copies the matrix to another one. The method copies the matrix data to another matrix. Before copying the data, the method invokes : @code m.create(this->size(), this->type()); @endcode so that the destination matrix is reallocated if needed. While m.copyTo(m); works flawlessly, the function does not handle the case of a partial overlap between the source and the destination matrices. */ void copyTo(Mat& dst) const { if (dims.empty()) { dst.create(rows, cols, type()); for (int r = 0; r < rows; ++r) { std::copy_n(ptr(r), detail::default_step(type(),cols), dst.ptr(r)); } } else { dst.create(dims, depth()); std::copy_n(data, total()*elemSize(), data); } } /** @brief Returns true if the array has no elements. The method returns true if Mat::total() is 0 or if Mat::data is NULL. Because of pop_back() and resize() methods `M.total() == 0` does not imply that `M.data == NULL`. */ bool empty() const; /** @brief Returns the total number of array elements. The method returns the number of array elements (a number of pixels if the array represents an image). */ size_t total() const { return static_cast<std::size_t> (dims.empty() ? (rows * cols) : std::accumulate(dims.begin(), dims.end(), 1, std::multiplies<int>())); } /** @overload @param roi Extracted submatrix specified as a rectangle. */ Mat operator()( const Rect& roi ) const { return Mat{*this, roi}; } /** @brief Returns a pointer to the specified matrix row. The methods return `uchar*` or typed pointer to the specified matrix row. See the sample in Mat::isContinuous to know how to use these methods. @param row Index along the dimension 0 @param col Index along the dimension 1 */ uchar* ptr(int row, int col = 0) { return const_cast<uchar*>(const_cast<const Mat*>(this)->ptr(row,col)); } /** @overload */ const uchar* ptr(int row, int col = 0) const { return data + step * row + CV_ELEM_SIZE(type()) * col; } private: //actual memory allocated for storage, or nullptr if object is non owning view to over memory std::shared_ptr<uchar> memory; }; } //namespace own } //namespace gapi } //namespace cv #endif /* OPENCV_GAPI_OWN_MAT_HPP */ <commit_msg>add empty implementation<commit_after>// This file is part of OpenCV project. // It is subject to the license terms in the LICENSE file found in the top-level directory // of this distribution and at http://opencv.org/license.html. // // Copyright (C) 2018 Intel Corporation #ifndef OPENCV_GAPI_OWN_MAT_HPP #define OPENCV_GAPI_OWN_MAT_HPP #include <opencv2/gapi/opencv_includes.hpp> #include <opencv2/gapi/own/types.hpp> #include <opencv2/gapi/own/scalar.hpp> #include <opencv2/gapi/own/saturate.hpp> #include <opencv2/gapi/own/assert.hpp> #include <memory> //std::shared_ptr #include <cstring> //std::memcpy #include <numeric> //std::accumulate #include <opencv2/gapi/util/throw.hpp> namespace cv { namespace gapi { namespace own { namespace detail { template <typename T, unsigned char channels> void assign_row(void* ptr, int cols, Scalar const& s) { auto p = static_cast<T*>(ptr); for (int c = 0; c < cols; c++) { for (int ch = 0; ch < channels; ch++) { p[c * channels + ch] = saturate<T>(s[ch], roundd); } } } inline size_t default_step(int type, int cols) { return CV_ELEM_SIZE(type) * cols; } //Matrix header, i.e. fields that are unique to each Mat object. //Devoted class is needed to implement custom behavior on move (erasing state of moved from object) struct MatHeader{ enum { AUTO_STEP = 0}; enum { TYPE_MASK = 0x00000FFF }; MatHeader() = default; MatHeader(int _rows, int _cols, int type, void* _data, size_t _step) : flags((type & TYPE_MASK)), rows(_rows), cols(_cols), data((uchar*)_data), step(_step == AUTO_STEP ? detail::default_step(type, _cols) : _step) {} MatHeader(const std::vector<int> &_dims, int type, void* _data) : flags((type & TYPE_MASK)), data((uchar*)_data), step(0), dims(_dims) {} MatHeader(const MatHeader& ) = default; MatHeader(MatHeader&& src) : MatHeader(src) // reuse copy constructor here { MatHeader empty; //give it a name to call copy(not move) assignment below src = empty; } MatHeader& operator=(const MatHeader& ) = default; MatHeader& operator=(MatHeader&& src) { *this = src; //calling a copy assignment here, not move one MatHeader empty; //give it a name to call copy(not move) assignment below src = empty; return *this; } /*! includes several bit-fields: - depth - number of channels */ int flags = 0; //! the number of rows and columns or (-1, -1) when the matrix has more than 2 dimensions int rows = 0, cols = 0; //! pointer to the data uchar* data = nullptr; size_t step = 0; //! dimensions (ND-case) std::vector<int> dims; }; } // namespace detail //concise version of cv::Mat suitable for GAPI needs (used when no dependence on OpenCV is required) class Mat : public detail::MatHeader{ public: Mat() = default; /** @overload @param _rows Number of rows in a 2D array. @param _cols Number of columns in a 2D array. @param _type Array type. Use CV_8UC1, ..., CV_64FC4 to create 1-4 channel matrices, or CV_8UC(n), ..., CV_64FC(n) to create multi-channel (up to CV_CN_MAX channels) matrices. @param _data Pointer to the user data. Matrix constructors that take data and step parameters do not allocate matrix data. Instead, they just initialize the matrix header that points to the specified data, which means that no data is copied. This operation is very efficient and can be used to process external data using OpenCV functions. The external data is not automatically deallocated, so you should take care of it. @param _step Number of bytes each matrix row occupies. The value should include the padding bytes at the end of each row, if any. If the parameter is missing (set to AUTO_STEP ), no padding is assumed and the actual step is calculated as cols*elemSize(). See Mat::elemSize. */ Mat(int _rows, int _cols, int _type, void* _data, size_t _step = AUTO_STEP) : MatHeader (_rows, _cols, _type, _data, _step) {} Mat(const std::vector<int> &_dims, int _type, void* _data) : MatHeader (_dims, _type, _data) {} Mat(std::vector<int> &&_dims, int _type, void* _data) : MatHeader (std::move(_dims), _type, _data) {} Mat(Mat const& src, const Rect& roi ) : Mat(src) { rows = roi.height; cols = roi.width; data = ptr(roi.y, roi.x); } Mat(Mat const& src) = default; Mat(Mat&& src) = default; Mat& operator=(Mat const& src) = default; Mat& operator=(Mat&& src) = default; /** @brief Sets all or some of the array elements to the specified value. @param s Assigned scalar converted to the actual array type. */ Mat& operator = (const Scalar& s) { constexpr unsigned max_channels = 4; //Scalar can't fit more than 4 using func_p_t = void (*)(void*, int, Scalar const&); using detail::assign_row; #define TABLE_ENTRY(type) {assign_row<type, 1>, assign_row<type, 2>, assign_row<type, 3>, assign_row<type, 4>} static constexpr func_p_t func_tbl[][max_channels] = { TABLE_ENTRY(uchar), TABLE_ENTRY(schar), TABLE_ENTRY(ushort), TABLE_ENTRY(short), TABLE_ENTRY(int), TABLE_ENTRY(float), TABLE_ENTRY(double) }; #undef TABLE_ENTRY static_assert(CV_8U == 0 && CV_8S == 1 && CV_16U == 2 && CV_16S == 3 && CV_32S == 4 && CV_32F == 5 && CV_64F == 6, "OCV type ids used as indexes to array, thus exact numbers are important!" ); const auto depth = static_cast<unsigned int>(this->depth()); GAPI_Assert(depth < sizeof(func_tbl)/sizeof(func_tbl[0])); if (dims.empty()) { const auto channels = static_cast<unsigned int>(this->channels()); GAPI_Assert(channels <= max_channels); auto* f = func_tbl[depth][channels - 1]; for (int r = 0; r < rows; ++r) { (*f)(static_cast<void *>(ptr(r)), cols, s ); } } else { auto* f = func_tbl[depth][0]; // FIXME: better to refactor assign_row to use std::size_t by default (*f)(static_cast<void *>(data), static_cast<int>(total()), s); } return *this; } /** @brief Returns the matrix element size in bytes. The method returns the matrix element size in bytes. For example, if the matrix type is CV_16SC3 , the method returns 3\*sizeof(short) or 6. */ size_t elemSize() const { return CV_ELEM_SIZE(type()); } /** @brief Returns the type of a matrix element. The method returns a matrix element type. This is an identifier compatible with the CvMat type system, like CV_16SC3 or 16-bit signed 3-channel array, and so on. */ int type() const {return CV_MAT_TYPE(flags);} /** @brief Returns the depth of a matrix element. The method returns the identifier of the matrix element depth (the type of each individual channel). For example, for a 16-bit signed element array, the method returns CV_16S . A complete list of matrix types contains the following values: - CV_8U - 8-bit unsigned integers ( 0..255 ) - CV_8S - 8-bit signed integers ( -128..127 ) - CV_16U - 16-bit unsigned integers ( 0..65535 ) - CV_16S - 16-bit signed integers ( -32768..32767 ) - CV_32S - 32-bit signed integers ( -2147483648..2147483647 ) - CV_32F - 32-bit floating-point numbers ( -FLT_MAX..FLT_MAX, INF, NAN ) - CV_64F - 64-bit floating-point numbers ( -DBL_MAX..DBL_MAX, INF, NAN ) */ int depth() const {return CV_MAT_DEPTH(flags);} /** @brief Returns the number of matrix channels. The method returns the number of matrix channels. If matrix is N-dimensional, -1 is returned. */ int channels() const {return dims.empty() ? CV_MAT_CN(flags) : -1;} /** @param _rows New number of rows. @param _cols New number of columns. @param _type New matrix type. */ void create(int _rows, int _cols, int _type) { create(Size{_cols, _rows}, _type); } /** @overload @param _size Alternative new matrix size specification: Size(cols, rows) @param _type New matrix type. */ void create(Size _size, int _type) { if (_size != Size{cols, rows} ) { Mat tmp{_size.height, _size.width, _type, nullptr}; tmp.memory.reset(new uchar[ tmp.step * tmp.rows], [](uchar * p){delete[] p;}); tmp.data = tmp.memory.get(); *this = std::move(tmp); } } void create(const std::vector<int> &_dims, int _type) { // FIXME: make a proper reallocation-on-demands // WARNING: no tensor views, so no strides Mat tmp{_dims, _type, nullptr}; // FIXME: this accumulate duplicates a lot const auto sz = std::accumulate(_dims.begin(), _dims.end(), 1, std::multiplies<int>()); tmp.memory.reset(new uchar[CV_ELEM_SIZE(_type)*sz], [](uchar * p){delete[] p;}); tmp.data = tmp.memory.get(); *this = std::move(tmp); } /** @brief Copies the matrix to another one. The method copies the matrix data to another matrix. Before copying the data, the method invokes : @code m.create(this->size(), this->type()); @endcode so that the destination matrix is reallocated if needed. While m.copyTo(m); works flawlessly, the function does not handle the case of a partial overlap between the source and the destination matrices. */ void copyTo(Mat& dst) const { if (dims.empty()) { dst.create(rows, cols, type()); for (int r = 0; r < rows; ++r) { std::copy_n(ptr(r), detail::default_step(type(),cols), dst.ptr(r)); } } else { dst.create(dims, depth()); std::copy_n(data, total()*elemSize(), data); } } /** @brief Returns true if the array has no elements. The method returns true if Mat::total() is 0 or if Mat::data is NULL. Because of pop_back() and resize() methods `M.total() == 0` does not imply that `M.data == NULL`. */ bool empty() const { return data == 0 || total() == 0 || dims.empty(); } /** @brief Returns the total number of array elements. The method returns the number of array elements (a number of pixels if the array represents an image). */ size_t total() const { return static_cast<std::size_t> (dims.empty() ? (rows * cols) : std::accumulate(dims.begin(), dims.end(), 1, std::multiplies<int>())); } /** @overload @param roi Extracted submatrix specified as a rectangle. */ Mat operator()( const Rect& roi ) const { return Mat{*this, roi}; } /** @brief Returns a pointer to the specified matrix row. The methods return `uchar*` or typed pointer to the specified matrix row. See the sample in Mat::isContinuous to know how to use these methods. @param row Index along the dimension 0 @param col Index along the dimension 1 */ uchar* ptr(int row, int col = 0) { return const_cast<uchar*>(const_cast<const Mat*>(this)->ptr(row,col)); } /** @overload */ const uchar* ptr(int row, int col = 0) const { return data + step * row + CV_ELEM_SIZE(type()) * col; } private: //actual memory allocated for storage, or nullptr if object is non owning view to over memory std::shared_ptr<uchar> memory; }; } //namespace own } //namespace gapi } //namespace cv #endif /* OPENCV_GAPI_OWN_MAT_HPP */ <|endoftext|>
<commit_before>/* * Copyright (C) 2019 pengjian.uestc @ gmail.com */ /* * SPDX-License-Identifier: AGPL-3.0-or-later */ #include <seastar/core/coroutine.hh> #include "redis/keyspace_utils.hh" #include "schema_builder.hh" #include "types.hh" #include "exceptions/exceptions.hh" #include "cql3/statements/ks_prop_defs.hh" #include "seastar/core/future.hh" #include <memory> #include "log.hh" #include "db/query_context.hh" #include "auth/service.hh" #include "service/migration_manager.hh" #include "service/storage_proxy.hh" #include "service/client_state.hh" #include "transport/server.hh" #include "db/system_keyspace.hh" #include "schema.hh" #include "gms/gossiper.hh" #include <seastar/core/print.hh> #include "db/config.hh" #include "data_dictionary/keyspace_metadata.hh" using namespace seastar; namespace redis { static logging::logger logger("keyspace_utils"); schema_ptr strings_schema(sstring ks_name) { schema_builder builder(generate_legacy_id(ks_name, redis::STRINGs), ks_name, redis::STRINGs, // partition key {{"pkey", utf8_type}}, // clustering key {}, // regular columns {{"data", utf8_type}}, // static columns {}, // regular column name type utf8_type, // comment "save STRINGs for redis" ); builder.set_gc_grace_seconds(0); builder.with(schema_builder::compact_storage::yes); builder.with_version(db::system_keyspace::generate_schema_version(builder.uuid())); return builder.build(schema_builder::compact_storage::yes); } schema_ptr lists_schema(sstring ks_name) { schema_builder builder(generate_legacy_id(ks_name, redis::LISTs), ks_name, redis::LISTs, // partition key {{"pkey", utf8_type}}, // clustering key {{"ckey", bytes_type}}, // regular columns {{"data", utf8_type}}, // static columns {}, // regular column name type utf8_type, // comment "save LISTs for redis" ); builder.set_gc_grace_seconds(0); builder.with(schema_builder::compact_storage::yes); builder.with_version(db::system_keyspace::generate_schema_version(builder.uuid())); return builder.build(schema_builder::compact_storage::yes); } schema_ptr hashes_schema(sstring ks_name) { schema_builder builder(generate_legacy_id(ks_name, redis::HASHes), ks_name, redis::HASHes, // partition key {{"pkey", utf8_type}}, // clustering key {{"ckey", utf8_type}}, // regular columns {{"data", utf8_type}}, // static columns {}, // regular column name type utf8_type, // comment "save HASHes for redis" ); builder.set_gc_grace_seconds(0); builder.with(schema_builder::compact_storage::yes); builder.with_version(db::system_keyspace::generate_schema_version(builder.uuid())); return builder.build(schema_builder::compact_storage::yes); } schema_ptr sets_schema(sstring ks_name) { schema_builder builder(generate_legacy_id(ks_name, redis::SETs), ks_name, redis::SETs, // partition key {{"pkey", utf8_type}}, // clustering key {{"ckey", utf8_type}}, // regular columns {}, // static columns {}, // regular column name type utf8_type, // comment "save SETs for redis" ); builder.set_gc_grace_seconds(0); builder.with(schema_builder::compact_storage::yes); builder.with_version(db::system_keyspace::generate_schema_version(builder.uuid())); return builder.build(schema_builder::compact_storage::yes); } schema_ptr zsets_schema(sstring ks_name) { schema_builder builder(generate_legacy_id(ks_name, redis::ZSETs), ks_name, redis::ZSETs, // partition key {{"pkey", utf8_type}}, // clustering key {{"ckey", double_type}}, // regular columns {{"data", utf8_type}}, // static columns {}, // regular column name type utf8_type, // comment "save ZSETs for redis" ); builder.set_gc_grace_seconds(0); builder.with(schema_builder::compact_storage::yes); builder.with_version(db::system_keyspace::generate_schema_version(builder.uuid())); return builder.build(schema_builder::compact_storage::yes); } future<> create_keyspace_if_not_exists_impl(seastar::sharded<service::storage_proxy>& proxy, data_dictionary::database db, seastar::sharded<service::migration_manager>& mm, db::config& config, int default_replication_factor) { assert(this_shard_id() == 0); auto keyspace_replication_strategy_options = config.redis_keyspace_replication_strategy_options(); if (!keyspace_replication_strategy_options.contains("class")) { keyspace_replication_strategy_options["class"] = "SimpleStrategy"; keyspace_replication_strategy_options["replication_factor"] = fmt::format("{}", default_replication_factor); } auto keyspace_gen = [&proxy, db, &mm, &config, keyspace_replication_strategy_options = std::move(keyspace_replication_strategy_options)] (sstring name) -> future<> { auto& mml = mm.local(); auto& proxyl = proxy.local(); if (db.has_keyspace(name)) { co_return; } auto attrs = make_shared<cql3::statements::ks_prop_defs>(); attrs->add_property(cql3::statements::ks_prop_defs::KW_DURABLE_WRITES, "true"); std::map<sstring, sstring> replication_properties; for (auto&& option : keyspace_replication_strategy_options) { replication_properties.emplace(option.first, option.second); } attrs->add_property(cql3::statements::ks_prop_defs::KW_REPLICATION, replication_properties); attrs->validate(); const auto& tm = *proxyl.get_token_metadata_ptr(); co_return co_await mml.announce(mml.prepare_new_keyspace_announcement(attrs->as_ks_metadata(name, tm))); }; auto table_gen = [&proxy, db, &mm] (sstring ks_name, sstring cf_name, schema_ptr schema) -> future<> { auto& mml= mm.local(); auto& proxyl = proxy.local(); if (db.has_schema(ks_name, cf_name)) { co_return; } logger.info("Create keyspace: {}, table: {} for redis.", ks_name, cf_name); co_return co_await mml.announce(co_await mml.prepare_new_column_family_announcement(schema)); }; co_await mm.local().schema_read_barrier(); // create default databases for redis. co_return co_await parallel_for_each(boost::irange<unsigned>(0, config.redis_database_count()), [keyspace_gen = std::move(keyspace_gen), table_gen = std::move(table_gen)] (auto c) { auto ks_name = fmt::format("REDIS_{}", c); return keyspace_gen(ks_name).then([ks_name, table_gen] { return when_all_succeed( table_gen(ks_name, redis::STRINGs, strings_schema(ks_name)), table_gen(ks_name, redis::LISTs, lists_schema(ks_name)), table_gen(ks_name, redis::SETs, sets_schema(ks_name)), table_gen(ks_name, redis::HASHes, hashes_schema(ks_name)), table_gen(ks_name, redis::ZSETs, zsets_schema(ks_name)) ).discard_result(); }); }); } future<> maybe_create_keyspace(seastar::sharded<service::storage_proxy>& proxy, data_dictionary::database db, seastar::sharded<service::migration_manager>& mm, db::config& config, sharded<gms::gossiper>& gossiper) { return gms::get_up_endpoint_count(gossiper.local()).then([&proxy, db, &mm, &config] (auto live_endpoint_count) { int replication_factor = 3; if (live_endpoint_count < replication_factor) { replication_factor = 1; logger.warn("Creating keyspace for redis with unsafe, live endpoint nodes count: {}.", live_endpoint_count); } return create_keyspace_if_not_exists_impl(proxy, db, mm, config, replication_factor); }); } } <commit_msg>redis: check for tables existence before creating<commit_after>/* * Copyright (C) 2019 pengjian.uestc @ gmail.com */ /* * SPDX-License-Identifier: AGPL-3.0-or-later */ #include <seastar/core/coroutine.hh> #include "redis/keyspace_utils.hh" #include "schema_builder.hh" #include "types.hh" #include "exceptions/exceptions.hh" #include "cql3/statements/ks_prop_defs.hh" #include "seastar/core/future.hh" #include <memory> #include "log.hh" #include "db/query_context.hh" #include "auth/service.hh" #include "service/migration_manager.hh" #include "service/storage_proxy.hh" #include "service/client_state.hh" #include "transport/server.hh" #include "db/system_keyspace.hh" #include "schema.hh" #include "gms/gossiper.hh" #include <seastar/core/print.hh> #include "db/config.hh" #include "data_dictionary/keyspace_metadata.hh" #include <boost/algorithm/cxx11/all_of.hpp> using namespace seastar; namespace redis { static logging::logger logger("keyspace_utils"); schema_ptr strings_schema(sstring ks_name) { schema_builder builder(generate_legacy_id(ks_name, redis::STRINGs), ks_name, redis::STRINGs, // partition key {{"pkey", utf8_type}}, // clustering key {}, // regular columns {{"data", utf8_type}}, // static columns {}, // regular column name type utf8_type, // comment "save STRINGs for redis" ); builder.set_gc_grace_seconds(0); builder.with(schema_builder::compact_storage::yes); builder.with_version(db::system_keyspace::generate_schema_version(builder.uuid())); return builder.build(schema_builder::compact_storage::yes); } schema_ptr lists_schema(sstring ks_name) { schema_builder builder(generate_legacy_id(ks_name, redis::LISTs), ks_name, redis::LISTs, // partition key {{"pkey", utf8_type}}, // clustering key {{"ckey", bytes_type}}, // regular columns {{"data", utf8_type}}, // static columns {}, // regular column name type utf8_type, // comment "save LISTs for redis" ); builder.set_gc_grace_seconds(0); builder.with(schema_builder::compact_storage::yes); builder.with_version(db::system_keyspace::generate_schema_version(builder.uuid())); return builder.build(schema_builder::compact_storage::yes); } schema_ptr hashes_schema(sstring ks_name) { schema_builder builder(generate_legacy_id(ks_name, redis::HASHes), ks_name, redis::HASHes, // partition key {{"pkey", utf8_type}}, // clustering key {{"ckey", utf8_type}}, // regular columns {{"data", utf8_type}}, // static columns {}, // regular column name type utf8_type, // comment "save HASHes for redis" ); builder.set_gc_grace_seconds(0); builder.with(schema_builder::compact_storage::yes); builder.with_version(db::system_keyspace::generate_schema_version(builder.uuid())); return builder.build(schema_builder::compact_storage::yes); } schema_ptr sets_schema(sstring ks_name) { schema_builder builder(generate_legacy_id(ks_name, redis::SETs), ks_name, redis::SETs, // partition key {{"pkey", utf8_type}}, // clustering key {{"ckey", utf8_type}}, // regular columns {}, // static columns {}, // regular column name type utf8_type, // comment "save SETs for redis" ); builder.set_gc_grace_seconds(0); builder.with(schema_builder::compact_storage::yes); builder.with_version(db::system_keyspace::generate_schema_version(builder.uuid())); return builder.build(schema_builder::compact_storage::yes); } schema_ptr zsets_schema(sstring ks_name) { schema_builder builder(generate_legacy_id(ks_name, redis::ZSETs), ks_name, redis::ZSETs, // partition key {{"pkey", utf8_type}}, // clustering key {{"ckey", double_type}}, // regular columns {{"data", utf8_type}}, // static columns {}, // regular column name type utf8_type, // comment "save ZSETs for redis" ); builder.set_gc_grace_seconds(0); builder.with(schema_builder::compact_storage::yes); builder.with_version(db::system_keyspace::generate_schema_version(builder.uuid())); return builder.build(schema_builder::compact_storage::yes); } future<> create_keyspace_if_not_exists_impl(seastar::sharded<service::storage_proxy>& proxy, data_dictionary::database db, seastar::sharded<service::migration_manager>& mm, db::config& config, int default_replication_factor) { assert(this_shard_id() == 0); auto keyspace_replication_strategy_options = config.redis_keyspace_replication_strategy_options(); if (!keyspace_replication_strategy_options.contains("class")) { keyspace_replication_strategy_options["class"] = "SimpleStrategy"; keyspace_replication_strategy_options["replication_factor"] = fmt::format("{}", default_replication_factor); } auto keyspace_gen = [&proxy, db, &mm, &config, keyspace_replication_strategy_options = std::move(keyspace_replication_strategy_options)] (sstring name) -> future<> { auto& mml = mm.local(); auto& proxyl = proxy.local(); if (db.has_keyspace(name)) { co_return; } auto attrs = make_shared<cql3::statements::ks_prop_defs>(); attrs->add_property(cql3::statements::ks_prop_defs::KW_DURABLE_WRITES, "true"); std::map<sstring, sstring> replication_properties; for (auto&& option : keyspace_replication_strategy_options) { replication_properties.emplace(option.first, option.second); } attrs->add_property(cql3::statements::ks_prop_defs::KW_REPLICATION, replication_properties); attrs->validate(); const auto& tm = *proxyl.get_token_metadata_ptr(); co_return co_await mml.announce(mml.prepare_new_keyspace_announcement(attrs->as_ks_metadata(name, tm))); }; auto table_gen = [&proxy, db, &mm] (sstring ks_name, sstring cf_name, schema_ptr schema) -> future<> { auto& mml= mm.local(); auto& proxyl = proxy.local(); if (db.has_schema(ks_name, cf_name)) { co_return; } logger.info("Create keyspace: {}, table: {} for redis.", ks_name, cf_name); co_return co_await mml.announce(co_await mml.prepare_new_column_family_announcement(schema)); }; struct table { const char* name; std::function<schema_ptr(sstring)> schema; }; static std::array tables{table{redis::STRINGs, strings_schema}, table{redis::LISTs, lists_schema}, table{redis::SETs, sets_schema}, table{redis::HASHes, hashes_schema}, table{redis::ZSETs, zsets_schema}}; bool schema_ok = boost::algorithm::all_of(boost::irange<unsigned>(0, config.redis_database_count()) | boost::adaptors::transformed([] (unsigned i) { return fmt::format("REDIS_{}", i); }), [&] (auto ks_name) { auto check = [&] (table t) { return db.has_schema(ks_name, t.name); }; return db.has_keyspace(ks_name) && boost::algorithm::all_of(tables, check); }); if (schema_ok) { logger.info("Redis schema is already up-to-date"); co_return; // if schema is created already do nothing } co_await mm.local().schema_read_barrier(); // create default databases for redis. co_return co_await parallel_for_each(boost::irange<unsigned>(0, config.redis_database_count()), [keyspace_gen = std::move(keyspace_gen), table_gen = std::move(table_gen)] (auto c) { auto ks_name = fmt::format("REDIS_{}", c); return keyspace_gen(ks_name).then([ks_name, table_gen] { return parallel_for_each(tables, [ks_name, table_gen] (table t) { return table_gen(ks_name, t.name, t.schema(ks_name)); }).discard_result(); }); }); } future<> maybe_create_keyspace(seastar::sharded<service::storage_proxy>& proxy, data_dictionary::database db, seastar::sharded<service::migration_manager>& mm, db::config& config, sharded<gms::gossiper>& gossiper) { return gms::get_up_endpoint_count(gossiper.local()).then([&proxy, db, &mm, &config] (auto live_endpoint_count) { int replication_factor = 3; if (live_endpoint_count < replication_factor) { replication_factor = 1; logger.warn("Creating keyspace for redis with unsafe, live endpoint nodes count: {}.", live_endpoint_count); } return create_keyspace_if_not_exists_impl(proxy, db, mm, config, replication_factor); }); } } <|endoftext|>
<commit_before>//===-- DynamicLoader.cpp ---------------------------------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // C Includes // C++ Includes // Other libraries and framework includes // Project includes #include "lldb/Target/DynamicLoader.h" #include "lldb/Core/Module.h" #include "lldb/Core/ModuleSpec.h" #include "lldb/Core/PluginManager.h" #include "lldb/Core/Section.h" #include "lldb/Target/MemoryRegionInfo.h" #include "lldb/Target/Process.h" #include "lldb/Target/Target.h" #include "lldb/lldb-private.h" using namespace lldb; using namespace lldb_private; DynamicLoader *DynamicLoader::FindPlugin(Process *process, const char *plugin_name) { DynamicLoaderCreateInstance create_callback = nullptr; if (plugin_name) { ConstString const_plugin_name(plugin_name); create_callback = PluginManager::GetDynamicLoaderCreateCallbackForPluginName( const_plugin_name); if (create_callback) { std::unique_ptr<DynamicLoader> instance_ap( create_callback(process, true)); if (instance_ap) return instance_ap.release(); } } else { for (uint32_t idx = 0; (create_callback = PluginManager::GetDynamicLoaderCreateCallbackAtIndex(idx)) != nullptr; ++idx) { std::unique_ptr<DynamicLoader> instance_ap( create_callback(process, false)); if (instance_ap) return instance_ap.release(); } } return nullptr; } DynamicLoader::DynamicLoader(Process *process) : m_process(process) {} DynamicLoader::~DynamicLoader() = default; //---------------------------------------------------------------------- // Accessosors to the global setting as to whether to stop at image // (shared library) loading/unloading. //---------------------------------------------------------------------- bool DynamicLoader::GetStopWhenImagesChange() const { return m_process->GetStopOnSharedLibraryEvents(); } void DynamicLoader::SetStopWhenImagesChange(bool stop) { m_process->SetStopOnSharedLibraryEvents(stop); } ModuleSP DynamicLoader::GetTargetExecutable() { Target &target = m_process->GetTarget(); ModuleSP executable = target.GetExecutableModule(); if (executable) { if (executable->GetFileSpec().Exists()) { ModuleSpec module_spec(executable->GetFileSpec(), executable->GetArchitecture()); ModuleSP module_sp(new Module(module_spec)); // Check if the executable has changed and set it to the target executable // if they differ. if (module_sp && module_sp->GetUUID().IsValid() && executable->GetUUID().IsValid()) { if (module_sp->GetUUID() != executable->GetUUID()) executable.reset(); } else if (executable->FileHasChanged()) { executable.reset(); } if (!executable) { executable = target.GetSharedModule(module_spec); if (executable.get() != target.GetExecutableModulePointer()) { // Don't load dependent images since we are in dyld where we will know // and find out about all images that are loaded const bool get_dependent_images = false; target.SetExecutableModule(executable, get_dependent_images); } } } } return executable; } void DynamicLoader::UpdateLoadedSections(ModuleSP module, addr_t link_map_addr, addr_t base_addr, bool base_addr_is_offset) { UpdateLoadedSectionsCommon(module, base_addr, base_addr_is_offset); } void DynamicLoader::UpdateLoadedSectionsCommon(ModuleSP module, addr_t base_addr, bool base_addr_is_offset) { bool changed; module->SetLoadAddress(m_process->GetTarget(), base_addr, base_addr_is_offset, changed); } void DynamicLoader::UnloadSections(const ModuleSP module) { UnloadSectionsCommon(module); } void DynamicLoader::UnloadSectionsCommon(const ModuleSP module) { Target &target = m_process->GetTarget(); const SectionList *sections = GetSectionListFromModule(module); assert(sections && "SectionList missing from unloaded module."); const size_t num_sections = sections->GetSize(); for (size_t i = 0; i < num_sections; ++i) { SectionSP section_sp(sections->GetSectionAtIndex(i)); target.SetSectionUnloaded(section_sp); } } const SectionList * DynamicLoader::GetSectionListFromModule(const ModuleSP module) const { SectionList *sections = nullptr; if (module) { ObjectFile *obj_file = module->GetObjectFile(); if (obj_file != nullptr) { sections = obj_file->GetSectionList(); } } return sections; } ModuleSP DynamicLoader::LoadModuleAtAddress(const FileSpec &file, addr_t link_map_addr, addr_t base_addr, bool base_addr_is_offset) { Target &target = m_process->GetTarget(); ModuleList &modules = target.GetImages(); ModuleSpec module_spec(file, target.GetArchitecture()); ModuleSP module_sp; if ((module_sp = modules.FindFirstModule(module_spec))) { UpdateLoadedSections(module_sp, link_map_addr, base_addr, base_addr_is_offset); return module_sp; } if ((module_sp = target.GetSharedModule(module_spec))) { UpdateLoadedSections(module_sp, link_map_addr, base_addr, base_addr_is_offset); return module_sp; } bool check_alternative_file_name = true; if (base_addr_is_offset) { // Try to fetch the load address of the file from the process as we need // absolute load // address to read the file out of the memory instead of a load bias. bool is_loaded = false; lldb::addr_t load_addr; Error error = m_process->GetFileLoadAddress(file, is_loaded, load_addr); if (error.Success() && is_loaded) { check_alternative_file_name = false; base_addr = load_addr; } } // We failed to find the module based on its name. Lets try to check if we can // find a // different name based on the memory region info. if (check_alternative_file_name) { MemoryRegionInfo memory_info; Error error = m_process->GetMemoryRegionInfo(base_addr, memory_info); if (error.Success() && memory_info.GetMapped() && memory_info.GetRange().GetRangeBase() == base_addr) { ModuleSpec new_module_spec( FileSpec(memory_info.GetName().AsCString(), false), target.GetArchitecture()); if ((module_sp = modules.FindFirstModule(new_module_spec))) { UpdateLoadedSections(module_sp, link_map_addr, base_addr, false); return module_sp; } if ((module_sp = target.GetSharedModule(new_module_spec))) { UpdateLoadedSections(module_sp, link_map_addr, base_addr, false); return module_sp; } } } if ((module_sp = m_process->ReadModuleFromMemory(file, base_addr))) { UpdateLoadedSections(module_sp, link_map_addr, base_addr, false); target.GetImages().AppendIfNeeded(module_sp); } return module_sp; } int64_t DynamicLoader::ReadUnsignedIntWithSizeInBytes(addr_t addr, int size_in_bytes) { Error error; uint64_t value = m_process->ReadUnsignedIntegerFromMemory(addr, size_in_bytes, 0, error); if (error.Fail()) return -1; else return (int64_t)value; } addr_t DynamicLoader::ReadPointer(addr_t addr) { Error error; addr_t value = m_process->ReadPointerFromMemory(addr, error); if (error.Fail()) return LLDB_INVALID_ADDRESS; else return value; } void DynamicLoader::LoadOperatingSystemPlugin(bool flush) { if (m_process) m_process->LoadOperatingSystemPlugin(flush); } <commit_msg>[LLDB][MIPS] Check if memory_info.GetName() is empty before finding corresponding module.<commit_after>//===-- DynamicLoader.cpp ---------------------------------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // C Includes // C++ Includes // Other libraries and framework includes // Project includes #include "lldb/Target/DynamicLoader.h" #include "lldb/Core/Module.h" #include "lldb/Core/ModuleSpec.h" #include "lldb/Core/PluginManager.h" #include "lldb/Core/Section.h" #include "lldb/Target/MemoryRegionInfo.h" #include "lldb/Target/Process.h" #include "lldb/Target/Target.h" #include "lldb/lldb-private.h" using namespace lldb; using namespace lldb_private; DynamicLoader *DynamicLoader::FindPlugin(Process *process, const char *plugin_name) { DynamicLoaderCreateInstance create_callback = nullptr; if (plugin_name) { ConstString const_plugin_name(plugin_name); create_callback = PluginManager::GetDynamicLoaderCreateCallbackForPluginName( const_plugin_name); if (create_callback) { std::unique_ptr<DynamicLoader> instance_ap( create_callback(process, true)); if (instance_ap) return instance_ap.release(); } } else { for (uint32_t idx = 0; (create_callback = PluginManager::GetDynamicLoaderCreateCallbackAtIndex(idx)) != nullptr; ++idx) { std::unique_ptr<DynamicLoader> instance_ap( create_callback(process, false)); if (instance_ap) return instance_ap.release(); } } return nullptr; } DynamicLoader::DynamicLoader(Process *process) : m_process(process) {} DynamicLoader::~DynamicLoader() = default; //---------------------------------------------------------------------- // Accessosors to the global setting as to whether to stop at image // (shared library) loading/unloading. //---------------------------------------------------------------------- bool DynamicLoader::GetStopWhenImagesChange() const { return m_process->GetStopOnSharedLibraryEvents(); } void DynamicLoader::SetStopWhenImagesChange(bool stop) { m_process->SetStopOnSharedLibraryEvents(stop); } ModuleSP DynamicLoader::GetTargetExecutable() { Target &target = m_process->GetTarget(); ModuleSP executable = target.GetExecutableModule(); if (executable) { if (executable->GetFileSpec().Exists()) { ModuleSpec module_spec(executable->GetFileSpec(), executable->GetArchitecture()); ModuleSP module_sp(new Module(module_spec)); // Check if the executable has changed and set it to the target executable // if they differ. if (module_sp && module_sp->GetUUID().IsValid() && executable->GetUUID().IsValid()) { if (module_sp->GetUUID() != executable->GetUUID()) executable.reset(); } else if (executable->FileHasChanged()) { executable.reset(); } if (!executable) { executable = target.GetSharedModule(module_spec); if (executable.get() != target.GetExecutableModulePointer()) { // Don't load dependent images since we are in dyld where we will know // and find out about all images that are loaded const bool get_dependent_images = false; target.SetExecutableModule(executable, get_dependent_images); } } } } return executable; } void DynamicLoader::UpdateLoadedSections(ModuleSP module, addr_t link_map_addr, addr_t base_addr, bool base_addr_is_offset) { UpdateLoadedSectionsCommon(module, base_addr, base_addr_is_offset); } void DynamicLoader::UpdateLoadedSectionsCommon(ModuleSP module, addr_t base_addr, bool base_addr_is_offset) { bool changed; module->SetLoadAddress(m_process->GetTarget(), base_addr, base_addr_is_offset, changed); } void DynamicLoader::UnloadSections(const ModuleSP module) { UnloadSectionsCommon(module); } void DynamicLoader::UnloadSectionsCommon(const ModuleSP module) { Target &target = m_process->GetTarget(); const SectionList *sections = GetSectionListFromModule(module); assert(sections && "SectionList missing from unloaded module."); const size_t num_sections = sections->GetSize(); for (size_t i = 0; i < num_sections; ++i) { SectionSP section_sp(sections->GetSectionAtIndex(i)); target.SetSectionUnloaded(section_sp); } } const SectionList * DynamicLoader::GetSectionListFromModule(const ModuleSP module) const { SectionList *sections = nullptr; if (module) { ObjectFile *obj_file = module->GetObjectFile(); if (obj_file != nullptr) { sections = obj_file->GetSectionList(); } } return sections; } ModuleSP DynamicLoader::LoadModuleAtAddress(const FileSpec &file, addr_t link_map_addr, addr_t base_addr, bool base_addr_is_offset) { Target &target = m_process->GetTarget(); ModuleList &modules = target.GetImages(); ModuleSpec module_spec(file, target.GetArchitecture()); ModuleSP module_sp; if ((module_sp = modules.FindFirstModule(module_spec))) { UpdateLoadedSections(module_sp, link_map_addr, base_addr, base_addr_is_offset); return module_sp; } if ((module_sp = target.GetSharedModule(module_spec))) { UpdateLoadedSections(module_sp, link_map_addr, base_addr, base_addr_is_offset); return module_sp; } bool check_alternative_file_name = true; if (base_addr_is_offset) { // Try to fetch the load address of the file from the process as we need // absolute load // address to read the file out of the memory instead of a load bias. bool is_loaded = false; lldb::addr_t load_addr; Error error = m_process->GetFileLoadAddress(file, is_loaded, load_addr); if (error.Success() && is_loaded) { check_alternative_file_name = false; base_addr = load_addr; } } // We failed to find the module based on its name. Lets try to check if we can // find a // different name based on the memory region info. if (check_alternative_file_name) { MemoryRegionInfo memory_info; Error error = m_process->GetMemoryRegionInfo(base_addr, memory_info); if (error.Success() && memory_info.GetMapped() && memory_info.GetRange().GetRangeBase() == base_addr && !(memory_info.GetName().IsEmpty())) { ModuleSpec new_module_spec( FileSpec(memory_info.GetName().AsCString(), false), target.GetArchitecture()); if ((module_sp = modules.FindFirstModule(new_module_spec))) { UpdateLoadedSections(module_sp, link_map_addr, base_addr, false); return module_sp; } if ((module_sp = target.GetSharedModule(new_module_spec))) { UpdateLoadedSections(module_sp, link_map_addr, base_addr, false); return module_sp; } } } if ((module_sp = m_process->ReadModuleFromMemory(file, base_addr))) { UpdateLoadedSections(module_sp, link_map_addr, base_addr, false); target.GetImages().AppendIfNeeded(module_sp); } return module_sp; } int64_t DynamicLoader::ReadUnsignedIntWithSizeInBytes(addr_t addr, int size_in_bytes) { Error error; uint64_t value = m_process->ReadUnsignedIntegerFromMemory(addr, size_in_bytes, 0, error); if (error.Fail()) return -1; else return (int64_t)value; } addr_t DynamicLoader::ReadPointer(addr_t addr) { Error error; addr_t value = m_process->ReadPointerFromMemory(addr, error); if (error.Fail()) return LLDB_INVALID_ADDRESS; else return value; } void DynamicLoader::LoadOperatingSystemPlugin(bool flush) { if (m_process) m_process->LoadOperatingSystemPlugin(flush); } <|endoftext|>
<commit_before>#include <cassert> #include <vector> #include <TacoGL/get.h> #include <TacoGL/Framebuffer.h> using namespace gl; using namespace TacoGL; //=========// // Manager // //=========// FramebufferManager::FramebufferManager() { } FramebufferManager::~FramebufferManager() { } bool FramebufferManager::isAvaible(GLenum target) const { return m_target.find(target) == m_target.end(); } bool FramebufferManager::isBinded(GLuint framebufferId) const { return m_binding.find(framebufferId) != m_binding.end(); } GLenum FramebufferManager::getTarget(GLuint framebufferId) const { assert(isBinded(framebufferId)); return m_binding.at(framebufferId); } void FramebufferManager::bind(GLenum target, GLuint framebufferId) { assert(isAvaible(target)); glBindFramebuffer(target, framebufferId); m_target.insert(target); m_binding.emplace(framebufferId, target); } void FramebufferManager::unbind(GLuint framebufferId) { assert(isBinded(framebufferId)); GLenum target = getTarget(framebufferId); glBindFramebuffer(target, 0); m_target.erase(target); m_binding.erase(framebufferId); } //=============// // Framebuffer // //=============// size_t Framebuffer::getMaxDrawBuffers() { return get<GL_MAX_DRAW_BUFFERS, size_t>(); } Framebuffer::Framebuffer() { glGenFramebuffers(1, &m_id); } Framebuffer::~Framebuffer() { glDeleteFramebuffers(1, &m_id); } bool Framebuffer::isBinded() const { return s_manager.isBinded(m_id); } gl::GLenum Framebuffer::getTarget() const { return s_manager.getTarget(m_id); } void Framebuffer::bind(GLenum target) { s_manager.bind(target, m_id); } void Framebuffer::unbind() { s_manager.unbind(m_id); } void Framebuffer::setDrawBuffers(size_t count) { assert(isBinded()); std::vector<GLenum> buffers(count); for (int i = 0; i < count; ++i) { buffers[i] = static_cast<GLenum>(static_cast<GLuint>(GL_COLOR_ATTACHMENT0) + i); } glDrawBuffers(count, buffers.data()); } void Framebuffer::attachTexture( gl::GLenum attachment, const Texture &texture, size_t level ) { assert(isBinded()); glFramebufferTexture( getTarget(), attachment, texture.getId(), level ); } void Framebuffer::attachTexture( gl::GLenum attachment, GLenum textarget, const Texture &texture, size_t level ) { assert(isBinded()); glFramebufferTexture2D( getTarget(), attachment, textarget, texture.getId(), level ); } void Framebuffer::attachTextureLayer( gl::GLenum attachment, const Texture &texture, size_t level, size_t layer ) { assert(isBinded()); glFramebufferTextureLayer( getTarget(), attachment, texture.getId(), level, layer ); } void Framebuffer::attachRenderbuffer( gl::GLenum attachment, const Renderbuffer &renderbuffer ) { assert(isBinded()); glFramebufferRenderbuffer( getTarget(), attachment, GL_RENDERBUFFER, renderbuffer.getId() ); } <commit_msg>correction<commit_after>#include <cassert> #include <vector> #include <TacoGL/get.h> #include <TacoGL/Framebuffer.h> using namespace gl; using namespace TacoGL; //=========// // Manager // //=========// FramebufferManager::FramebufferManager() { } FramebufferManager::~FramebufferManager() { } bool FramebufferManager::isAvaible(GLenum target) const { return m_target.find(target) == m_target.end(); } bool FramebufferManager::isBinded(GLuint framebufferId) const { return m_binding.find(framebufferId) != m_binding.end(); } GLenum FramebufferManager::getTarget(GLuint framebufferId) const { assert(isBinded(framebufferId)); return m_binding.at(framebufferId); } void FramebufferManager::bind(GLenum target, GLuint framebufferId) { assert(isAvaible(target)); glBindFramebuffer(target, framebufferId); m_target.insert(target); m_binding.emplace(framebufferId, target); } void FramebufferManager::unbind(GLuint framebufferId) { assert(isBinded(framebufferId)); GLenum target = getTarget(framebufferId); glBindFramebuffer(target, 0); m_target.erase(target); m_binding.erase(framebufferId); } //=============// // Framebuffer // //=============// FramebufferManager Framebuffer::s_manager; size_t Framebuffer::getMaxDrawBuffers() { return get<GL_MAX_DRAW_BUFFERS, size_t>(); } Framebuffer::Framebuffer() { glGenFramebuffers(1, &m_id); } Framebuffer::~Framebuffer() { glDeleteFramebuffers(1, &m_id); } bool Framebuffer::isBinded() const { return s_manager.isBinded(m_id); } gl::GLenum Framebuffer::getTarget() const { return s_manager.getTarget(m_id); } void Framebuffer::bind(GLenum target) { s_manager.bind(target, m_id); } void Framebuffer::unbind() { s_manager.unbind(m_id); } void Framebuffer::setDrawBuffers(size_t count) { assert(isBinded()); std::vector<GLenum> buffers(count); for (int i = 0; i < count; ++i) { buffers[i] = static_cast<GLenum>(static_cast<GLuint>(GL_COLOR_ATTACHMENT0) + i); } glDrawBuffers(count, buffers.data()); } void Framebuffer::attachTexture( gl::GLenum attachment, const Texture &texture, size_t level ) { assert(isBinded()); glFramebufferTexture( getTarget(), attachment, texture.getId(), level ); } void Framebuffer::attachTexture( gl::GLenum attachment, GLenum textarget, const Texture &texture, size_t level ) { assert(isBinded()); glFramebufferTexture2D( getTarget(), attachment, textarget, texture.getId(), level ); } void Framebuffer::attachTextureLayer( gl::GLenum attachment, const Texture &texture, size_t level, size_t layer ) { assert(isBinded()); glFramebufferTextureLayer( getTarget(), attachment, texture.getId(), level, layer ); } void Framebuffer::attachRenderbuffer( gl::GLenum attachment, const Renderbuffer &renderbuffer ) { assert(isBinded()); glFramebufferRenderbuffer( getTarget(), attachment, GL_RENDERBUFFER, renderbuffer.getId() ); } <|endoftext|>
<commit_before>#include "main.hpp" #include "WaveEffect.hpp" constexpr const char *WaveEffect::Name; const char *WaveEffect::getName() const { return Name; } const char *WaveEffect::getDescriptiveName() const { return "Wave"; } const char *WaveEffect::getDescription() const { return "A wave passes through the particles from left to right over the " "screen"; } void WaveEffect::loadConfig(const json &json) { multiplier = json.value("multiplier", 1.f); amplitude = json.value("amplitude", .05f); } void WaveEffect::saveConfig(json &json) const { json.emplace("multiplier", multiplier); json.emplace("amplitude", amplitude); } void WaveEffect::randomizeConfig() {} void WaveEffect::registerEffect(Uniforms &uniforms, ShaderBuilder &vertexShader, ShaderBuilder &fragmentShader) const { vertexShader.appendMainBody( TEMPLATE(R"glsl( { // goes from 0 (leftmost, begin) to 2 (leftmost, end) // but `reached` + `notOver` clamp it to 0 to 1 float x = 2 * ${time} - initialPosition.x; float ease = 1.; if ((${rep} == 0 && x <= 0.5) || (${rep} == ${repetitions} - 1 && x >= 0.5)) { // The ease function is a cos spanning two negative peaks with a positive peak // in between. This is is then translated (+1, /2) to go from 0 to 1 // Finally, because this will lower the actual peak height of `curve` // a compensation factor of 1.25 is applied ease = (cos((x * 2 - 1) * PI) + 1) * .5 * 1.25; } // Closed formula (with ease): (cos((x*2-1)*π)+1)/2 * sin(x*3*π-0.5*π)/0.8 float curve = sin(x * ${multiplier} * 3. * PI - .5 * PI); float phase = ease * curve; float reached = (x >= 0.) ? 1. : 0.; if (${rep} != 0) { reached = 1.; } float notOver = (x <= 1.) ? 1. : 0.; if (${rep} != ${instance.repetitions} - 1) { notOver = 1.; } position.y += phase * reached * notOver * ${amplitude}; } )glsl") .compile({ UNIFORM("time", GLSLType::Float, [this](const RenderProps &props) { return UniformValue( glm::fract((props.state.clock.getTime() - timeBegin) / getPeriod())); }), UNIFORM("rep", GLSLType::Float, [this](const RenderProps &props) { return UniformValue( std::floor((props.state.clock.getTime() - timeBegin) / getPeriod())); }), UNIFORM("multiplier", GLSLType::Float, [this](const RenderProps &props) { return UniformValue(multiplier); }), UNIFORM("amplitude", GLSLType::Float, [this](const RenderProps &props) { return UniformValue(amplitude); }), UNIFORM("repetitions", GLSLType::Float, [this](const RenderProps &props) { return UniformValue(repetitions); }), }) .c_str()); } <commit_msg>Fix broken Wave effect introduced in 1ff72b482054e499e9557e471bfb4c5070ac5f62<commit_after>#include "main.hpp" #include "WaveEffect.hpp" constexpr const char *WaveEffect::Name; const char *WaveEffect::getName() const { return Name; } const char *WaveEffect::getDescriptiveName() const { return "Wave"; } const char *WaveEffect::getDescription() const { return "A wave passes through the particles from left to right over the " "screen"; } void WaveEffect::loadConfig(const json &json) { multiplier = json.value("multiplier", 1.f); amplitude = json.value("amplitude", .05f); } void WaveEffect::saveConfig(json &json) const { json.emplace("multiplier", multiplier); json.emplace("amplitude", amplitude); } void WaveEffect::randomizeConfig() {} void WaveEffect::registerEffect(Uniforms &uniforms, ShaderBuilder &vertexShader, ShaderBuilder &fragmentShader) const { vertexShader.appendMainBody( TEMPLATE(R"glsl( { // goes from 0 (leftmost, begin) to 2 (leftmost, end) // but `reached` + `notOver` clamp it to 0 to 1 float x = 2 * ${time} - initialPosition.x; float ease = 1.; if ((${rep} == 0 && x <= 0.5) || (${rep} == ${repetitions} - 1 && x >= 0.5)) { // The ease function is a cos spanning two negative peaks with a positive peak // in between. This is is then translated (+1, /2) to go from 0 to 1 // Finally, because this will lower the actual peak height of `curve` // a compensation factor of 1.25 is applied ease = (cos((x * 2 - 1) * PI) + 1) * .5 * 1.25; } // Closed formula (with ease): (cos((x*2-1)*π)+1)/2 * sin(x*3*π-0.5*π)/0.8 float curve = sin(x * ${multiplier} * 3. * PI - .5 * PI); float phase = ease * curve; float reached = (x >= 0.) ? 1. : 0.; if (${rep} != 0) { reached = 1.; } float notOver = (x <= 1.) ? 1. : 0.; if (${rep} != ${repetitions} - 1) { notOver = 1.; } position.y += phase * reached * notOver * ${amplitude}; } )glsl") .compile({ UNIFORM("time", GLSLType::Float, [this](const RenderProps &props) { return UniformValue( glm::fract((props.state.clock.getTime() - timeBegin) / getPeriod())); }), UNIFORM("rep", GLSLType::Float, [this](const RenderProps &props) { return UniformValue( std::floor((props.state.clock.getTime() - timeBegin) / getPeriod())); }), UNIFORM("multiplier", GLSLType::Float, [this](const RenderProps &props) { return UniformValue(multiplier); }), UNIFORM("amplitude", GLSLType::Float, [this](const RenderProps &props) { return UniformValue(amplitude); }), UNIFORM("repetitions", GLSLType::Float, [this](const RenderProps &props) { return UniformValue(repetitions); }), }) .c_str()); } <|endoftext|>
<commit_before>/** @file @brief Implementation @date 2015 @author Sensics, Inc. <http://sensics.com/osvr> */ // Copyright 2015 Sensics, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Internal Includes #include "LED.h" #include "HDKLedIdentifier.h" #include "IdentifierHelpers.h" // Library/third-party includes // - none // Standard includes // - none #undef OSVR_LED_IDENTIFICATION_EARLY_OUT namespace osvr { namespace vbtracker { OsvrHdkLedIdentifier::~OsvrHdkLedIdentifier() {} // Convert from string encoding representations into lists // of boolean values for use in comparison. OsvrHdkLedIdentifier::OsvrHdkLedIdentifier( const PatternStringList &PATTERNS) { // Ensure that we have at least one entry in our list and // find the length of the first entry. if (PATTERNS.size() == 0) { d_length = 0; return; } d_length = PATTERNS[0].size(); // Decode each string into a new list of boolean values, making // sure each have the correct length. for (size_t i = 0; i < PATTERNS.size(); i++) { // Make sure the pattern is the correct length. if (PATTERNS[i].size() != d_length) { d_patterns.clear(); d_length = 0; return; } // Make a wrapped pattern, which is the original pattern plus // a second copy of the pattern that has all but the last // character in it. This will enable use to use the string // find() routine to see if any shift of the pattern is a // match. std::string wrapped = PATTERNS[i] + PATTERNS[i]; wrapped.pop_back(); // Add the pattern to the vector of lists. d_patterns.push_back(wrapped); } // std::cout << "XXX d_length = " << d_length << ", num patterns = " << // d_patterns.size() << std::endl; } int OsvrHdkLedIdentifier::getId(int currentId, std::list<float> &brightnesses, bool & lastBright) const { // If we don't have at least the required number of frames of data, we // don't know anything. if (brightnesses.size() < d_length) { return Led::SENTINEL_NO_IDENTIFIER_OBJECT_OR_INSUFFICIENT_DATA; } // We only care about the d_length most-recent levels. truncateBrightnessListTo(brightnesses, d_length); // Compute the minimum and maximum brightness values. If // they are too close to each other, we have a light rather // than an LED. If not, compute a threshold to separate the // 0's and 1's. Brightness minVal, maxVal; std::tie(minVal, maxVal) = findMinMaxBrightness(brightnesses); // Brightness is currently actually keypoint diameter (radius?) in // pixels, and it's being under-estimated by OpenCV. static const double TODO_MIN_BRIGHTNESS_DIFF = 0.3; if (maxVal - minVal <= TODO_MIN_BRIGHTNESS_DIFF) { return Led::SENTINEL_INSUFFICIENT_EXTREMA_DIFFERENCE; } const auto threshold = (minVal + maxVal) / 2; // Set the `lastBright` out variable lastBright = brightnesses.back() >= threshold; #ifdef OSVR_LED_IDENTIFICATION_EARLY_OUT if (currentId >= 0) { // Early out if we already have identified this LED. return currentId; } #endif // Get a list of boolean values for 0's and 1's using // the threshold computed above. auto bits = getBitsUsingThreshold(brightnesses, threshold); // Search through the available patterns to see if the passed-in // pattern matches any of them. If so, return that pattern. We // need to check all potential rotations of the pattern, since we // don't know when the code started. For the HDK, the codes are // rotationally invariant. We do this by making wrapped strings // and seeing if the pattern shows up anywhe in them, relying on // the std::string find method to do efficiently. for (size_t i = 0; i < d_patterns.size(); i++) { if (d_patterns[i].find(bits) != std::string::npos) { return static_cast<int>(i); } } // No pattern recognized and we should have recognized one, so return // a low negative. We've used -2 so return -3. return Led::SENTINEL_NO_PATTERN_RECOGNIZED_DESPITE_SUFFICIENT_DATA; } } // End namespace vbtracker } // End namespace osvr <commit_msg>Make the LED identifier more robust to handle "turned-off" beacon patterns.<commit_after>/** @file @brief Implementation @date 2015 @author Sensics, Inc. <http://sensics.com/osvr> */ // Copyright 2015 Sensics, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Internal Includes #include "LED.h" #include "HDKLedIdentifier.h" #include "IdentifierHelpers.h" // Library/third-party includes // - none // Standard includes // - none #undef OSVR_LED_IDENTIFICATION_EARLY_OUT namespace osvr { namespace vbtracker { static const auto VALIDCHARS = "*."; OsvrHdkLedIdentifier::~OsvrHdkLedIdentifier() {} // Convert from string encoding representations into lists // of boolean values for use in comparison. OsvrHdkLedIdentifier::OsvrHdkLedIdentifier( const PatternStringList &PATTERNS) { // Ensure that we have at least one entry in our list and // find the length of the first valid entry. d_length = 0; if (PATTERNS.empty()) { return; } for (auto &pat : PATTERNS) { if (!pat.empty() && pat.find_first_not_of(VALIDCHARS) == pat.npos) { // All characters in this pattern are valid - we can consider // this to be a valid pattern and thus establish the size. d_length = pat.length(); break; } } if (0 == d_length) { // If we still have 0 as the pattern length, return. return; } // Decode each string into a new list of boolean values, making // sure each have the correct length. for (auto &pat : PATTERNS) { if (pat.empty() || pat.find_first_not_of(VALIDCHARS) != pat.npos) { // This is an intentionally disabled beacon/pattern. d_patterns.emplace_back(); continue; } // Make sure the pattern is the correct length. if (pat.size() != d_length) { throw std::runtime_error("Got a pattern of incorrect length!"); } // Make a wrapped pattern, which is the original pattern plus // a second copy of the pattern that has all but the last // character in it. This will enable use to use the string // find() routine to see if any shift of the pattern is a // match. auto wrapped = pat + pat; wrapped.pop_back(); d_patterns.push_back(std::move(wrapped)); } } int OsvrHdkLedIdentifier::getId(int currentId, std::list<float> &brightnesses, bool &lastBright) const { // If we don't have at least the required number of frames of data, we // don't know anything. if (brightnesses.size() < d_length) { return Led::SENTINEL_NO_IDENTIFIER_OBJECT_OR_INSUFFICIENT_DATA; } // We only care about the d_length most-recent levels. truncateBrightnessListTo(brightnesses, d_length); // Compute the minimum and maximum brightness values. If // they are too close to each other, we have a light rather // than an LED. If not, compute a threshold to separate the // 0's and 1's. Brightness minVal, maxVal; std::tie(minVal, maxVal) = findMinMaxBrightness(brightnesses); // Brightness is currently actually keypoint diameter (radius?) in // pixels, and it's being under-estimated by OpenCV. static const double TODO_MIN_BRIGHTNESS_DIFF = 0.3; if (maxVal - minVal <= TODO_MIN_BRIGHTNESS_DIFF) { return Led::SENTINEL_INSUFFICIENT_EXTREMA_DIFFERENCE; } const auto threshold = (minVal + maxVal) / 2; // Set the `lastBright` out variable lastBright = brightnesses.back() >= threshold; #ifdef OSVR_LED_IDENTIFICATION_EARLY_OUT if (currentId >= 0) { // Early out if we already have identified this LED. return currentId; } #endif // Get a list of boolean values for 0's and 1's using // the threshold computed above. auto bits = getBitsUsingThreshold(brightnesses, threshold); // Search through the available patterns to see if the passed-in // pattern matches any of them. If so, return that pattern. We // need to check all potential rotations of the pattern, since we // don't know when the code started. For the HDK, the codes are // rotationally invariant. We do this by making wrapped strings // and seeing if the pattern shows up anywhe in them, relying on // the std::string find method to do efficiently. for (size_t i = 0; i < d_patterns.size(); i++) { if (d_patterns[i].empty()) { /// Skip turned-off patterns. continue; } if (d_patterns[i].find(bits) != std::string::npos) { return static_cast<int>(i); } } // No pattern recognized and we should have recognized one, so return // a low negative. We've used -2 so return -3. return Led::SENTINEL_NO_PATTERN_RECOGNIZED_DESPITE_SUFFICIENT_DATA; } } // End namespace vbtracker } // End namespace osvr <|endoftext|>
<commit_before>#include "SimpleFilterAudioProcessor.h" #include <ostream> using namespace std; SimpleFilterAudioProcessor::SimpleFilterAudioProcessor() : Parameterized({ {"gain_in", make_shared<Parameter<double>>("Input Gain (dB)", 0.0, -24.0, 24.0)}, {"freq", make_shared<WarpedParameter<double>>("Filter Frequency", 500, 100.0, 20000.0, 700.0)}, {"dist", make_shared<WarpedParameter<double>>("Distortion", 1.0, 1.0, 1000.0, 10.0)} }), filter(), filterDelayBuffer(2, 5) { for (auto &param : *parameters) { parameterIds.push_back(param.first); param.second->addListener(this); } filter.setRipple(0.9691); } void SimpleFilterAudioProcessor::updateFilterTheta() { filter.setTheta(calculateFilterTheta(getSampleRate())); } double SimpleFilterAudioProcessor::calculateFilterTheta(double sampleRate) { double freq = Parameterized::getParameter<double>("freq")->getValue(); return (freq / (sampleRate / 2)) * double_Pi; } void SimpleFilterAudioProcessor::prepareToPlay(double sampleRate, int samplesPerBlock) { filterDelayBuffer.clear(); updateFilterTheta(); } void SimpleFilterAudioProcessor::releaseResources() { filterDelayBuffer.clear(); } void SimpleFilterAudioProcessor::processBlock (AudioSampleBuffer& buffer, MidiBuffer& midiMessages) { const int numSamples = buffer.getNumSamples(); float gain_in = Decibels::decibelsToGain(Parameterized::getParameter<double>("gain_in")->getValue()); double dist = Parameterized::getParameter<double>("dist")->getValue(); // apply input gain/dist for (int channel = 0; channel < getNumInputChannels(); channel++) { float* channelData = buffer.getSampleData(channel); for (int i = 0; i < numSamples; i++) { // apply gain channelData[i] *= gain_in; // apply dist if (dist >= 1.0) { channelData[i] = 2.0 / (1.0 + pow(dist, -channelData[i])) - 1.0; } } } shared_ptr<vector<double>> coefficientsB = filter.getCoefficientsB(); double filterDCGain = filter.getDCGain(); for (int channel = 0; channel < getNumInputChannels(); channel++) { float* channelData = buffer.getSampleData(channel); float* filterDelayData = filterDelayBuffer.getSampleData( jmin(channel, filterDelayBuffer.getNumChannels() - 1)); for (int i = 0; i < numSamples; i++) { for (int j = filterDelayBuffer.getNumSamples() - 1; j > 0; j--) { filterDelayData[j] = filterDelayData[j - 1]; } float out = channelData[i] / filterDCGain; for (vector<double>::size_type i = 1; i < coefficientsB->size(); i++) { // start at 1 for filterDelayData coefficients because index 0 is the one // we are currently calculating (and after shift it's the same // as the one at index 1), so it's impossible to have a value for it out -= filterDelayData[i] * coefficientsB->at(i); } filterDelayData[0] = out; channelData[i] = filterDelayData[0]; } } // clear extra channels for (int i = getNumInputChannels(); i < getNumOutputChannels(); i++) { buffer.clear(i, 0, buffer.getNumSamples()); } } void SimpleFilterAudioProcessor::parameterValueChanged(ParameterBase* param) { if (param == Parameterized::getParameter("freq").get()) { updateFilterTheta(); } } int SimpleFilterAudioProcessor::getNumParameters() { return parameterIds.size(); } float SimpleFilterAudioProcessor::getParameter(int index) { if (index < 0 || index >= parameterIds.size()) { return 0.0f; } return (*parameters)[parameterIds[index]]->getFloatValueLinear(); } void SimpleFilterAudioProcessor::setParameter(int index, float newValue) { if (index < 0 || index >= parameterIds.size()) { return; } (*parameters)[parameterIds[index]]->setFloatValueLinear(newValue); } const String SimpleFilterAudioProcessor::getParameterName(int index) { if (index < 0 || index >= parameterIds.size()) { return String::empty; } return String(parameterIds[index] + + " (" + (*parameters)[parameterIds[index]]->getName() + ')'); } const String SimpleFilterAudioProcessor::getParameterText(int index) { if (index < 0 && index > parameterIds.size()) { return String::empty; } return (*parameters)[parameterIds[index]]->getValueText(); } void SimpleFilterAudioProcessor::getStateInformation(MemoryBlock& destData) { XmlElement xml(JucePlugin_Name "_settings"); for (const String& paramId : parameterIds) { xml.setAttribute(paramId, (*parameters)[paramId]->getFloatValueLinear()); } copyXmlToBinary(xml, destData); } void SimpleFilterAudioProcessor::setStateInformation(const void* data, int sizeInBytes) { ScopedPointer<XmlElement> xmlState(getXmlFromBinary(data, sizeInBytes)); if (xmlState != nullptr) { if (xmlState->hasTagName(JucePlugin_Name "_settings")) { for (const String& paramId : parameterIds) { float prevValue = (*parameters)[paramId]->getFloatValueLinear(); float newValue = (float) xmlState->getDoubleAttribute(paramId, prevValue); (*parameters)[paramId]->setFloatValueLinear(newValue); } } } } AudioProcessor* JUCE_CALLTYPE createPluginFilter() { return new SimpleFilterAudioProcessor(); } <commit_msg>SimpleFilter: tweak dist off condition<commit_after>#include "SimpleFilterAudioProcessor.h" #include <ostream> using namespace std; SimpleFilterAudioProcessor::SimpleFilterAudioProcessor() : Parameterized({ {"gain_in", make_shared<Parameter<double>>("Input Gain (dB)", 0.0, -24.0, 24.0)}, {"freq", make_shared<WarpedParameter<double>>("Filter Frequency", 500, 100.0, 20000.0, 700.0)}, {"dist", make_shared<WarpedParameter<double>>("Distortion", 1.0, 1.0, 1000.0, 10.0)} }), filter(), filterDelayBuffer(2, 5) { for (auto &param : *parameters) { parameterIds.push_back(param.first); param.second->addListener(this); } filter.setRipple(0.9691); } void SimpleFilterAudioProcessor::updateFilterTheta() { filter.setTheta(calculateFilterTheta(getSampleRate())); } double SimpleFilterAudioProcessor::calculateFilterTheta(double sampleRate) { double freq = Parameterized::getParameter<double>("freq")->getValue(); return (freq / (sampleRate / 2)) * double_Pi; } void SimpleFilterAudioProcessor::prepareToPlay(double sampleRate, int samplesPerBlock) { filterDelayBuffer.clear(); updateFilterTheta(); } void SimpleFilterAudioProcessor::releaseResources() { filterDelayBuffer.clear(); } void SimpleFilterAudioProcessor::processBlock (AudioSampleBuffer& buffer, MidiBuffer& midiMessages) { const int numSamples = buffer.getNumSamples(); float gain_in = Decibels::decibelsToGain(Parameterized::getParameter<double>("gain_in")->getValue()); double dist = Parameterized::getParameter<double>("dist")->getValue(); // apply input gain/dist for (int channel = 0; channel < getNumInputChannels(); channel++) { float* channelData = buffer.getSampleData(channel); for (int i = 0; i < numSamples; i++) { // apply gain channelData[i] *= gain_in; // apply dist if (dist >= 1.0 + numeric_limits<double>::epsilon()) { channelData[i] = 2.0 / (1.0 + pow(dist, -channelData[i])) - 1.0; } } } shared_ptr<vector<double>> coefficientsB = filter.getCoefficientsB(); double filterDCGain = filter.getDCGain(); for (int channel = 0; channel < getNumInputChannels(); channel++) { float* channelData = buffer.getSampleData(channel); float* filterDelayData = filterDelayBuffer.getSampleData( jmin(channel, filterDelayBuffer.getNumChannels() - 1)); for (int i = 0; i < numSamples; i++) { for (int j = filterDelayBuffer.getNumSamples() - 1; j > 0; j--) { filterDelayData[j] = filterDelayData[j - 1]; } float out = channelData[i] / filterDCGain; for (vector<double>::size_type i = 1; i < coefficientsB->size(); i++) { // start at 1 for filterDelayData coefficients because index 0 is the one // we are currently calculating (and after shift it's the same // as the one at index 1), so it's impossible to have a value for it out -= filterDelayData[i] * coefficientsB->at(i); } filterDelayData[0] = out; channelData[i] = filterDelayData[0]; } } // clear extra channels for (int i = getNumInputChannels(); i < getNumOutputChannels(); i++) { buffer.clear(i, 0, buffer.getNumSamples()); } } void SimpleFilterAudioProcessor::parameterValueChanged(ParameterBase* param) { if (param == Parameterized::getParameter("freq").get()) { updateFilterTheta(); } } int SimpleFilterAudioProcessor::getNumParameters() { return parameterIds.size(); } float SimpleFilterAudioProcessor::getParameter(int index) { if (index < 0 || index >= parameterIds.size()) { return 0.0f; } return (*parameters)[parameterIds[index]]->getFloatValueLinear(); } void SimpleFilterAudioProcessor::setParameter(int index, float newValue) { if (index < 0 || index >= parameterIds.size()) { return; } (*parameters)[parameterIds[index]]->setFloatValueLinear(newValue); } const String SimpleFilterAudioProcessor::getParameterName(int index) { if (index < 0 || index >= parameterIds.size()) { return String::empty; } return String(parameterIds[index] + + " (" + (*parameters)[parameterIds[index]]->getName() + ')'); } const String SimpleFilterAudioProcessor::getParameterText(int index) { if (index < 0 && index > parameterIds.size()) { return String::empty; } return (*parameters)[parameterIds[index]]->getValueText(); } void SimpleFilterAudioProcessor::getStateInformation(MemoryBlock& destData) { XmlElement xml(JucePlugin_Name "_settings"); for (const String& paramId : parameterIds) { xml.setAttribute(paramId, (*parameters)[paramId]->getFloatValueLinear()); } copyXmlToBinary(xml, destData); } void SimpleFilterAudioProcessor::setStateInformation(const void* data, int sizeInBytes) { ScopedPointer<XmlElement> xmlState(getXmlFromBinary(data, sizeInBytes)); if (xmlState != nullptr) { if (xmlState->hasTagName(JucePlugin_Name "_settings")) { for (const String& paramId : parameterIds) { float prevValue = (*parameters)[paramId]->getFloatValueLinear(); float newValue = (float) xmlState->getDoubleAttribute(paramId, prevValue); (*parameters)[paramId]->setFloatValueLinear(newValue); } } } } AudioProcessor* JUCE_CALLTYPE createPluginFilter() { return new SimpleFilterAudioProcessor(); } <|endoftext|>
<commit_before>// $Id$ /* Copyright (c) 2007-2009, Trustees of The Leland Stanford Junior University All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. Neither the name of the Stanford University nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /*router.cpp * *The base class of either iq router or event router *contains a list of channels and other router configuration variables * *The older version of the simulator uses an array of flits and credit to *simulate the channels. Newer version ueses flitchannel and credit channel *which can better model channel delay * *The older version of the simulator also uses vc_router and chaos router *which are replaced by iq rotuer and event router in the present form */ #include "booksim.hpp" #include <iostream> #include <assert.h> #include "router.hpp" //////////////////Sub router types////////////////////// #include "iq_router_baseline.hpp" #include "iq_router_combined.hpp" #include "iq_router_split.hpp" #include "event_router.hpp" #include "chaos_router.hpp" #include "MECSRouter.hpp" /////////////////////////////////////////////////////// Router::Router( const Configuration& config, Module *parent, const string & name, int id, int inputs, int outputs ) : Module( parent, name ), _id( id ), _inputs( inputs ), _outputs( outputs ) { _st_prepare_delay = config.GetInt( "st_prepare_delay" ); _st_final_delay = config.GetInt( "st_final_delay" ); _credit_delay = config.GetInt( "credit_delay" ); _input_speedup = config.GetInt( "input_speedup" ); _output_speedup = config.GetInt( "output_speedup" ); _input_channels = new vector<FlitChannel *>; _input_credits = new vector<CreditChannel *>; _output_channels = new vector<FlitChannel *>; _output_credits = new vector<CreditChannel *>; _channel_faults = new vector<bool>; } Router::~Router( ) { delete _input_channels; delete _input_credits; delete _output_channels; delete _output_credits; delete _channel_faults; } Credit *Router::_NewCredit( int vcs ) { Credit *c = Credit::New(vcs); } void Router::_RetireCredit( Credit *c ) { c->Free(); } void Router::AddInputChannel( FlitChannel *channel, CreditChannel *backchannel ) { _input_channels->push_back( channel ); _input_credits->push_back( backchannel ); channel->SetSink( this ) ; } void Router::AddOutputChannel( FlitChannel *channel, CreditChannel *backchannel ) { _output_channels->push_back( channel ); _output_credits->push_back( backchannel ); _channel_faults->push_back( false ); channel->SetSource( this ) ; } int Router::GetID( ) const { return _id; } void Router::OutChannelFault( int c, bool fault ) { assert( ( c >= 0 ) && ( (unsigned int)c < _channel_faults->size( ) ) ); (*_channel_faults)[c] = fault; } bool Router::IsFaultyOutput( int c ) const { assert( ( c >= 0 ) && ( (unsigned int)c < _channel_faults->size( ) ) ); return (*_channel_faults)[c]; } /*Router constructor*/ Router *Router::NewRouter( const Configuration& config, Module *parent, string name, int id, int inputs, int outputs ) { Router *r; string type; string topo; config.GetStr( "router", type ); config.GetStr( "topology", topo); if ( type == "iq" ) { if(topo == "MECS"){ r = new MECSRouter( config, parent, name, id, inputs, outputs); } else { r = new IQRouterBaseline( config, parent, name, id, inputs, outputs ); } } else if ( type == "iq_combined" ) { r = new IQRouterCombined( config, parent, name, id, inputs, outputs ); } else if ( type == "iq_split" ) { r = new IQRouterSplit( config, parent, name, id, inputs, outputs ); } else if ( type == "event" ) { r = new EventRouter( config, parent, name, id, inputs, outputs ); } else if ( type == "chaos" ) { r = new ChaosRouter( config, parent, name, id, inputs, outputs ); } else { cout << "Unknown router type " << type << endl; } /*For additional router, add another else if statement*/ /*Original booksim specifies the router using "flow_control" *we now simply call these types. */ return r; } <commit_msg>add missing return statement<commit_after>// $Id$ /* Copyright (c) 2007-2009, Trustees of The Leland Stanford Junior University All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. Neither the name of the Stanford University nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /*router.cpp * *The base class of either iq router or event router *contains a list of channels and other router configuration variables * *The older version of the simulator uses an array of flits and credit to *simulate the channels. Newer version ueses flitchannel and credit channel *which can better model channel delay * *The older version of the simulator also uses vc_router and chaos router *which are replaced by iq rotuer and event router in the present form */ #include "booksim.hpp" #include <iostream> #include <assert.h> #include "router.hpp" //////////////////Sub router types////////////////////// #include "iq_router_baseline.hpp" #include "iq_router_combined.hpp" #include "iq_router_split.hpp" #include "event_router.hpp" #include "chaos_router.hpp" #include "MECSRouter.hpp" /////////////////////////////////////////////////////// Router::Router( const Configuration& config, Module *parent, const string & name, int id, int inputs, int outputs ) : Module( parent, name ), _id( id ), _inputs( inputs ), _outputs( outputs ) { _st_prepare_delay = config.GetInt( "st_prepare_delay" ); _st_final_delay = config.GetInt( "st_final_delay" ); _credit_delay = config.GetInt( "credit_delay" ); _input_speedup = config.GetInt( "input_speedup" ); _output_speedup = config.GetInt( "output_speedup" ); _input_channels = new vector<FlitChannel *>; _input_credits = new vector<CreditChannel *>; _output_channels = new vector<FlitChannel *>; _output_credits = new vector<CreditChannel *>; _channel_faults = new vector<bool>; } Router::~Router( ) { delete _input_channels; delete _input_credits; delete _output_channels; delete _output_credits; delete _channel_faults; } Credit *Router::_NewCredit( int vcs ) { return Credit::New(vcs); } void Router::_RetireCredit( Credit *c ) { c->Free(); } void Router::AddInputChannel( FlitChannel *channel, CreditChannel *backchannel ) { _input_channels->push_back( channel ); _input_credits->push_back( backchannel ); channel->SetSink( this ) ; } void Router::AddOutputChannel( FlitChannel *channel, CreditChannel *backchannel ) { _output_channels->push_back( channel ); _output_credits->push_back( backchannel ); _channel_faults->push_back( false ); channel->SetSource( this ) ; } int Router::GetID( ) const { return _id; } void Router::OutChannelFault( int c, bool fault ) { assert( ( c >= 0 ) && ( (unsigned int)c < _channel_faults->size( ) ) ); (*_channel_faults)[c] = fault; } bool Router::IsFaultyOutput( int c ) const { assert( ( c >= 0 ) && ( (unsigned int)c < _channel_faults->size( ) ) ); return (*_channel_faults)[c]; } /*Router constructor*/ Router *Router::NewRouter( const Configuration& config, Module *parent, string name, int id, int inputs, int outputs ) { Router *r; string type; string topo; config.GetStr( "router", type ); config.GetStr( "topology", topo); if ( type == "iq" ) { if(topo == "MECS"){ r = new MECSRouter( config, parent, name, id, inputs, outputs); } else { r = new IQRouterBaseline( config, parent, name, id, inputs, outputs ); } } else if ( type == "iq_combined" ) { r = new IQRouterCombined( config, parent, name, id, inputs, outputs ); } else if ( type == "iq_split" ) { r = new IQRouterSplit( config, parent, name, id, inputs, outputs ); } else if ( type == "event" ) { r = new EventRouter( config, parent, name, id, inputs, outputs ); } else if ( type == "chaos" ) { r = new ChaosRouter( config, parent, name, id, inputs, outputs ); } else { cout << "Unknown router type " << type << endl; } /*For additional router, add another else if statement*/ /*Original booksim specifies the router using "flow_control" *we now simply call these types. */ return r; } <|endoftext|>
<commit_before>/* * File: RawClient.cpp * Author: Paolo D'Apice * * Created on December 31, 2011, 2:46 PM */ #include "net/sf1r/Errors.hpp" #include "RawClient.hpp" #include <boost/array.hpp> #include <glog/logging.h> #include <sys/time.h> #include <boost/bind.hpp> NS_IZENELIB_SF1R_BEGIN namespace bs = boost::system; using ba::ip::tcp; using std::string; #define CONNECT_TIMEOUT 5 #define RW_TIMEOUT 20 namespace { /** * Size of unsigned integer (32 bits). */ const size_t UINT_SIZE = sizeof(uint32_t); /** * Header size, i.e. two unsigned values for: * - sequence number * - message length */ const size_t HEADER_SIZE = 2 * UINT_SIZE; } uint32_t RawClient::idSequence = 0; RawClient::RawClient(ba::io_service& service, const std::string& host, const std::string& port, const size_t timeout, const string& zkpath) : socket(service), deadline_(service), io_service_(service), status(Idle), is_aborted_(false), path(zkpath), id(++idSequence) { try { deadline_.expires_at(boost::posix_time::pos_infin); DLOG(INFO) << "configuring socket ..."; // TODO: windows? struct timeval tv; tv.tv_sec = timeout; tv.tv_usec = 0; setsockopt(socket.native(), SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof (tv)); setsockopt(socket.native(), SOL_SOCKET, SO_SNDTIMEO, &tv, sizeof (tv)); DLOG(INFO) << "connecting to [" << host << ":" << port << "] (" << id << ") ..."; connect_with_timeout(host, port); DLOG(INFO) << "connected (" << id << ")"; } catch (bs::system_error& e) { status = Invalid; LOG(ERROR) << "create rawclient error"; LOG(ERROR) << e.what(); throw NetworkError(e.what()); } CHECK_EQ(Idle, status) << "not Idle (" << id << ")"; DLOG(INFO) << "Correctly instantiated (" << id << ")"; } RawClient::~RawClient() { clear_timeout(); CHECK_NE(Busy, status); try { DLOG(INFO) << "closing (" << id << ") ..."; if (socket.is_open()) socket.shutdown(socket.shutdown_both); socket.close(); LOG(INFO) << "connection closed (" << id << ")"; } catch (bs::system_error& e) { LOG(WARNING) << e.what(); } LOG(INFO) << "Correctly destroyed (" << id << ")"; } void async_cb(const bs::error_code& error, std::size_t bytes, bs::error_code* ret_ec) { *ret_ec = error; } void RawClient::prepare_timeout(int sec) { deadline_.expires_from_now(boost::posix_time::seconds(sec)); check_deadline(); } void RawClient::clear_timeout() { if (!is_aborted_) { // delete while socket is still open, we need wake up timeout event // to make sure timeout handler removed. is_aborted_ = true; deadline_.expires_at(deadline_timer::traits_type::now()); io_service_.run_one(); } // no active async handler, reset io_service to get ready for next run_one. io_service_.reset(); } void RawClient::connect_with_timeout(const std::string& host, const std::string& port) { try { ba::ip::tcp::resolver resolver(io_service_); ba::ip::tcp::resolver::query query(host, port); tcp::resolver::iterator iter = resolver.resolve(query); prepare_timeout(CONNECT_TIMEOUT); bs::error_code ec = ba::error::would_block; ba::async_connect(socket, iter, boost::bind(&async_cb, _1, 0, &ec)); do io_service_.run_one(); while (ec == ba::error::would_block); if (ec || !socket.is_open()) { throw bs::system_error(ec ? ec : ba::error::operation_aborted); } } catch(const bs::system_error& e) { clear_timeout(); throw; } } size_t RawClient::read_with_timeout(const ba::mutable_buffers_1& buf) { deadline_.expires_from_now(boost::posix_time::seconds(RW_TIMEOUT + ba::buffer_size(buf)/1024/1024)); bs::error_code ec = ba::error::would_block; ba::async_read(socket, buf, boost::bind(&async_cb, _1, _2, &ec)); do io_service_.run_one(); while(ec == ba::error::would_block); if (ec) { throw bs::system_error(ec); } return ba::buffer_size(buf); } size_t RawClient::write_with_timeout(const boost::array<ba::const_buffer,3>& buffers) { deadline_.expires_from_now(boost::posix_time::seconds(RW_TIMEOUT)); bs::error_code ec = ba::error::would_block; ba::async_write(socket, buffers, boost::bind(&async_cb, _1, _2, &ec)); do io_service_.run_one(); while(ec == ba::error::would_block); if (ec) { throw bs::system_error(ec); } return ba::buffer_size(buffers); } void RawClient::check_deadline() { if (deadline_.expires_at() <= deadline_timer::traits_type::now()) { if (is_aborted_) { //Clear timeout by hand here. Not a deadline. return; } LOG(INFO) << "deadline for : " << path; boost::system::error_code ignored_ec; is_aborted_ = true; try { if (socket.is_open() && status != Invalid) { status = Invalid; socket.shutdown(ba::ip::tcp::socket::shutdown_both, ignored_ec); socket.close(ignored_ec); } // There is no longer an active deadline. The expiry is set to infinity. deadline_.expires_at(boost::posix_time::pos_infin); } catch(const bs::system_error& e) { LOG(ERROR) << "check_deadline error : " << e.what(); } } else { is_aborted_ = false; deadline_.async_wait(boost::bind(&RawClient::check_deadline, this)); } } bool RawClient::isConnected() { // is the socket open? if (not socket.is_open()) { LOG(WARNING) << "Socket is not open"; return false; } // is the endpoint active? try { socket.remote_endpoint(); } catch (bs::system_error& e) { LOG(WARNING) << "Endpoint error: " << e.what(); return false; } return true; } void RawClient::sendRequest(const uint32_t& sequence, const string& data) { if (not isConnected()) { // TODO: keep alive? status = Invalid; throw NetworkError("Not connected in RawClient"); } CHECK_EQ(Idle, status) << "not Idle (" << id << ")"; status = Busy; DLOG(INFO) << "Sending raw request (" << id << "): [" << sequence << ", " << data.length() << ", " << data << "] ..."; uint32_t seq = htonl(sequence); uint32_t len = htonl(data.length()); boost::array<ba::const_buffer,3> buffers; buffers[0] = ba::buffer(&seq, UINT_SIZE); buffers[1] = ba::buffer(&len, UINT_SIZE); buffers[2] = ba::buffer(data); size_t n = 0; try { n += write_with_timeout(buffers); } catch (bs::system_error& e) { status = Invalid; LOG(ERROR) << "write request to socket error"; LOG(ERROR) << e.what(); throw NetworkError(e.what()); } if (n != HEADER_SIZE + data.length()) { status = Invalid; throw ServerError("write: Write size mismatch"); } // do not change the status CHECK_EQ(Busy, status) << "not Busy (" << id << ")"; DLOG(INFO) << "Request sent (" << n << " bytes)."; } Response RawClient::getResponse() { if (not isConnected()) { // TODO: keep alive? status = Invalid; throw NetworkError("Not connected in RawClient"); } CHECK_EQ(Busy, status) << "not Busy (" << id << ")"; // do not change the status DLOG(INFO) << "Receiving response (" << id << ") ..."; char header[HEADER_SIZE]; size_t n = 0; try { n += read_with_timeout(ba::buffer(header)); } catch (bs::system_error& e) { status = Invalid; LOG(ERROR) << "get response head from socket error"; LOG(ERROR) << e.what(); throw NetworkError(e.what()); } if (n != sizeof(HEADER_SIZE)) { status = Invalid; throw ServerError("Read size mismatch"); } uint32_t sequence, length; memcpy(&sequence, header, UINT_SIZE); memcpy(&length, header + UINT_SIZE, UINT_SIZE); sequence = ntohl(sequence); length = ntohl(length); static const uint32_t small_response_size = 1024*4; static char stack_array[small_response_size]; char *data = NULL; if (length > small_response_size) { data = new char[length]; } else { data = stack_array; } try { n = read_with_timeout(ba::buffer(data, length)); } catch (bs::system_error& e) { status = Invalid; LOG(ERROR) << "get response body from socket error"; LOG(ERROR) << e.what(); if (length > small_response_size) delete[] data; throw NetworkError(e.what()); } catch(...) { if (length > small_response_size) delete[] data; throw; } if (n != length) { status = Invalid; if (length > small_response_size) delete[] data; throw ServerError("Read size mismatch"); } string response(data, length - 1); // skip the final '\0' DLOG(INFO) << "Response (" << id << "): [" << sequence << ", " << length << ", " << response << "]"; LOG(INFO) << "Response received (" << n + HEADER_SIZE << " bytes)"; if (length > small_response_size) delete[] data; status = Idle; return boost::make_tuple(sequence, response); } NS_IZENELIB_SF1R_END <commit_msg>cancel the read/write on socket do not set invalid state<commit_after>/* * File: RawClient.cpp * Author: Paolo D'Apice * * Created on December 31, 2011, 2:46 PM */ #include "net/sf1r/Errors.hpp" #include "RawClient.hpp" #include <boost/array.hpp> #include <glog/logging.h> #include <sys/time.h> #include <boost/bind.hpp> NS_IZENELIB_SF1R_BEGIN namespace bs = boost::system; using ba::ip::tcp; using std::string; #define CONNECT_TIMEOUT 5 #define RW_TIMEOUT 20 namespace { /** * Size of unsigned integer (32 bits). */ const size_t UINT_SIZE = sizeof(uint32_t); /** * Header size, i.e. two unsigned values for: * - sequence number * - message length */ const size_t HEADER_SIZE = 2 * UINT_SIZE; } uint32_t RawClient::idSequence = 0; RawClient::RawClient(ba::io_service& service, const std::string& host, const std::string& port, const size_t timeout, const string& zkpath) : socket(service), deadline_(service), io_service_(service), status(Idle), is_aborted_(false), path(zkpath), id(++idSequence) { try { deadline_.expires_at(boost::posix_time::pos_infin); DLOG(INFO) << "configuring socket ..."; // TODO: windows? struct timeval tv; tv.tv_sec = timeout; tv.tv_usec = 0; setsockopt(socket.native(), SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof (tv)); setsockopt(socket.native(), SOL_SOCKET, SO_SNDTIMEO, &tv, sizeof (tv)); DLOG(INFO) << "connecting to [" << host << ":" << port << "] (" << id << ") ..."; connect_with_timeout(host, port); DLOG(INFO) << "connected (" << id << ")"; } catch (bs::system_error& e) { status = Invalid; LOG(ERROR) << "create rawclient error"; LOG(ERROR) << e.what(); throw NetworkError(e.what()); } CHECK_EQ(Idle, status) << "not Idle (" << id << ")"; DLOG(INFO) << "Correctly instantiated (" << id << ")"; } RawClient::~RawClient() { clear_timeout(); CHECK_NE(Busy, status); try { DLOG(INFO) << "closing (" << id << ") ..."; if (socket.is_open()) socket.shutdown(socket.shutdown_both); socket.close(); LOG(INFO) << "connection closed (" << id << ")"; } catch (bs::system_error& e) { LOG(WARNING) << e.what(); } LOG(INFO) << "Correctly destroyed (" << id << ")"; } void async_cb(const bs::error_code& error, std::size_t bytes, bs::error_code* ret_ec) { *ret_ec = error; } void RawClient::prepare_timeout(int sec) { deadline_.expires_from_now(boost::posix_time::seconds(sec)); check_deadline(); } void RawClient::clear_timeout() { if (!is_aborted_) { // delete while socket is still open, we need wake up timeout event // to make sure timeout handler removed. is_aborted_ = true; deadline_.expires_at(deadline_timer::traits_type::now()); io_service_.run_one(); } // no active async handler, reset io_service to get ready for next run_one. io_service_.reset(); } void RawClient::connect_with_timeout(const std::string& host, const std::string& port) { try { ba::ip::tcp::resolver resolver(io_service_); ba::ip::tcp::resolver::query query(host, port); tcp::resolver::iterator iter = resolver.resolve(query); prepare_timeout(CONNECT_TIMEOUT); bs::error_code ec = ba::error::would_block; ba::async_connect(socket, iter, boost::bind(&async_cb, _1, 0, &ec)); do io_service_.run_one(); while (ec == ba::error::would_block); if (ec || !socket.is_open()) { throw bs::system_error(ec ? ec : ba::error::operation_aborted); } } catch(const bs::system_error& e) { clear_timeout(); throw; } } size_t RawClient::read_with_timeout(const ba::mutable_buffers_1& buf) { deadline_.expires_from_now(boost::posix_time::seconds(RW_TIMEOUT + ba::buffer_size(buf)/1024/1024)); bs::error_code ec = ba::error::would_block; ba::async_read(socket, buf, boost::bind(&async_cb, _1, _2, &ec)); do io_service_.run_one(); while(ec == ba::error::would_block); if (ec) { throw bs::system_error(ec); } return ba::buffer_size(buf); } size_t RawClient::write_with_timeout(const boost::array<ba::const_buffer,3>& buffers) { deadline_.expires_from_now(boost::posix_time::seconds(RW_TIMEOUT)); bs::error_code ec = ba::error::would_block; ba::async_write(socket, buffers, boost::bind(&async_cb, _1, _2, &ec)); do io_service_.run_one(); while(ec == ba::error::would_block); if (ec) { throw bs::system_error(ec); } return ba::buffer_size(buffers); } void RawClient::check_deadline() { if (deadline_.expires_at() <= deadline_timer::traits_type::now()) { if (is_aborted_) { //Clear timeout by hand here. Not a deadline. return; } LOG(INFO) << "deadline for : " << path; boost::system::error_code ignored_ec; is_aborted_ = true; try { if (socket.is_open() && status != Invalid) { //status = Invalid; //socket.shutdown(ba::ip::tcp::socket::shutdown_both, ignored_ec); //socket.close(ignored_ec); socket.cancel(); } // There is no longer an active deadline. The expiry is set to infinity. deadline_.expires_at(boost::posix_time::pos_infin); } catch(const bs::system_error& e) { LOG(ERROR) << "check_deadline error : " << e.what(); } } else { is_aborted_ = false; deadline_.async_wait(boost::bind(&RawClient::check_deadline, this)); } } bool RawClient::isConnected() { // is the socket open? if (not socket.is_open()) { LOG(WARNING) << "Socket is not open"; return false; } // is the endpoint active? try { socket.remote_endpoint(); } catch (bs::system_error& e) { LOG(WARNING) << "Endpoint error: " << e.what(); return false; } return true; } void RawClient::sendRequest(const uint32_t& sequence, const string& data) { if (not isConnected()) { // TODO: keep alive? status = Invalid; throw NetworkError("Not connected in RawClient"); } CHECK_EQ(Idle, status) << "not Idle (" << id << ")"; status = Busy; DLOG(INFO) << "Sending raw request (" << id << "): [" << sequence << ", " << data.length() << ", " << data << "] ..."; uint32_t seq = htonl(sequence); uint32_t len = htonl(data.length()); boost::array<ba::const_buffer,3> buffers; buffers[0] = ba::buffer(&seq, UINT_SIZE); buffers[1] = ba::buffer(&len, UINT_SIZE); buffers[2] = ba::buffer(data); size_t n = 0; try { n += write_with_timeout(buffers); } catch (bs::system_error& e) { if (e.code() != ba::error::operation_aborted) status = Invalid; LOG(ERROR) << "write request to socket error"; LOG(ERROR) << e.what(); throw NetworkError(e.what()); } if (n != HEADER_SIZE + data.length()) { status = Invalid; throw ServerError("write: Write size mismatch"); } // do not change the status CHECK_EQ(Busy, status) << "not Busy (" << id << ")"; DLOG(INFO) << "Request sent (" << n << " bytes)."; } Response RawClient::getResponse() { if (not isConnected()) { // TODO: keep alive? status = Invalid; throw NetworkError("Not connected in RawClient"); } CHECK_EQ(Busy, status) << "not Busy (" << id << ")"; // do not change the status DLOG(INFO) << "Receiving response (" << id << ") ..."; char header[HEADER_SIZE]; size_t n = 0; try { n += read_with_timeout(ba::buffer(header)); } catch (bs::system_error& e) { if (e.code() != ba::error::operation_aborted) status = Invalid; LOG(ERROR) << "get response head from socket error"; LOG(ERROR) << e.what(); throw NetworkError(e.what()); } if (n != sizeof(HEADER_SIZE)) { status = Invalid; throw ServerError("Read size mismatch"); } uint32_t sequence, length; memcpy(&sequence, header, UINT_SIZE); memcpy(&length, header + UINT_SIZE, UINT_SIZE); sequence = ntohl(sequence); length = ntohl(length); static const uint32_t small_response_size = 1024*4; static char stack_array[small_response_size]; char *data = NULL; if (length > small_response_size) { data = new char[length]; } else { data = stack_array; } try { n = read_with_timeout(ba::buffer(data, length)); } catch (bs::system_error& e) { if (e.code() != ba::error::operation_aborted) status = Invalid; LOG(ERROR) << "get response body from socket error"; LOG(ERROR) << e.what(); if (length > small_response_size) delete[] data; throw NetworkError(e.what()); } catch(...) { if (length > small_response_size) delete[] data; throw; } if (n != length) { status = Invalid; if (length > small_response_size) delete[] data; throw ServerError("Read size mismatch"); } string response(data, length - 1); // skip the final '\0' DLOG(INFO) << "Response (" << id << "): [" << sequence << ", " << length << ", " << response << "]"; LOG(INFO) << "Response received (" << n + HEADER_SIZE << " bytes)"; if (length > small_response_size) delete[] data; status = Idle; return boost::make_tuple(sequence, response); } NS_IZENELIB_SF1R_END <|endoftext|>
<commit_before>// // Aspia Project // Copyright (C) 2020 Dmitry Chapyshev <dmitry@aspia.ru> // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <https://www.gnu.org/licenses/>. // #include "router/session_host.h" #include "base/logging.h" #include "base/stl_util.h" #include "base/crypto/generic_hash.h" #include "base/crypto/random.h" #include "base/net/network_channel.h" #include "router/database.h" #include "router/server.h" namespace router { namespace { const size_t kHostKeySize = 512; } // namespace SessionHost::SessionHost() : Session(proto::ROUTER_SESSION_HOST) { // Nothing } SessionHost::~SessionHost() = default; bool SessionHost::hasHostId(base::HostId host_id) const { return base::contains(host_id_list_, host_id); } void SessionHost::sendConnectionOffer(const proto::ConnectionOffer& offer) { proto::RouterToHost message; message.mutable_connection_offer()->CopyFrom(offer); sendMessage(message); } void SessionHost::onSessionReady() { // Nothing } void SessionHost::onMessageReceived(const base::ByteArray& buffer) { proto::HostToRouter message; if (!base::parse(buffer, &message)) { LOG(LS_ERROR) << "Could not read message from host"; return; } if (message.has_host_id_request()) { readHostIdRequest(message.host_id_request()); } else if (message.has_reset_host_id()) { readResetHostId(message.reset_host_id()); } else { if (host_id_list_.empty()) { LOG(LS_ERROR) << "Request could not be processed (host ID not assigned yet)"; return; } LOG(LS_WARNING) << "Unhandled message from host"; } } void SessionHost::onMessageWritten(size_t /* pending */) { // Nothing } void SessionHost::readHostIdRequest(const proto::HostIdRequest& host_id_request) { std::unique_ptr<Database> database = openDatabase(); if (!database) { LOG(LS_ERROR) << "Failed to connect to database"; return; } proto::RouterToHost message; proto::HostIdResponse* host_id_response = message.mutable_host_id_response(); base::ByteArray key_hash; if (host_id_request.type() == proto::HostIdRequest::NEW_ID) { // Generate new key. std::string key = base::Random::string(kHostKeySize); // Calculate hash for key. key_hash = base::GenericHash::hash(base::GenericHash::Type::BLAKE2b512, key); if (!database->addHost(key_hash)) { LOG(LS_ERROR) << "Unable to add host"; return; } host_id_response->set_key(std::move(key)); } else if (host_id_request.type() == proto::HostIdRequest::EXISTING_ID) { // Using existing key. key_hash = base::GenericHash::hash( base::GenericHash::Type::BLAKE2b512, host_id_request.key()); } else { LOG(LS_ERROR) << "Unknown request type: " << host_id_request.type(); return; } base::HostId host_id = database->hostId(key_hash); if (host_id == base::kInvalidHostId) { LOG(LS_ERROR) << "Failed to get host ID"; return; } host_id_list_.emplace_back(host_id); // Notify the server that the ID has been assigned. server().onHostSessionWithId(this); host_id_response->set_host_id(host_id); sendMessage(message); } void SessionHost::readResetHostId(const proto::ResetHostId& reset_host_id) { base::HostId host_id = reset_host_id.host_id(); if (host_id == base::kInvalidHostId) { LOG(LS_ERROR) << "Invalid host ID"; return; } if (host_id_list_.empty()) { LOG(LS_ERROR) << "Empty host ID list"; return; } for (auto it = host_id_list_.begin(); it != host_id_list_.end(); ++it) { if (*it == host_id) { LOG(LS_INFO) << "Host ID " << host_id << " remove from list"; host_id_list_.erase(it); return; } } LOG(LS_WARNING) << "Host ID " << host_id << " NOT found in list"; } } // namespace router <commit_msg>Cleanup.<commit_after>// // Aspia Project // Copyright (C) 2020 Dmitry Chapyshev <dmitry@aspia.ru> // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <https://www.gnu.org/licenses/>. // #include "router/session_host.h" #include "base/logging.h" #include "base/stl_util.h" #include "base/crypto/generic_hash.h" #include "base/crypto/random.h" #include "base/net/network_channel.h" #include "router/database.h" #include "router/server.h" namespace router { namespace { const size_t kHostKeySize = 512; } // namespace SessionHost::SessionHost() : Session(proto::ROUTER_SESSION_HOST) { // Nothing } SessionHost::~SessionHost() = default; bool SessionHost::hasHostId(base::HostId host_id) const { return base::contains(host_id_list_, host_id); } void SessionHost::sendConnectionOffer(const proto::ConnectionOffer& offer) { proto::RouterToHost message; message.mutable_connection_offer()->CopyFrom(offer); sendMessage(message); } void SessionHost::onSessionReady() { // Nothing } void SessionHost::onMessageReceived(const base::ByteArray& buffer) { proto::HostToRouter message; if (!base::parse(buffer, &message)) { LOG(LS_ERROR) << "Could not read message from host"; return; } if (message.has_host_id_request()) { readHostIdRequest(message.host_id_request()); } else if (message.has_reset_host_id()) { readResetHostId(message.reset_host_id()); } else { LOG(LS_WARNING) << "Unhandled message from host"; } } void SessionHost::onMessageWritten(size_t /* pending */) { // Nothing } void SessionHost::readHostIdRequest(const proto::HostIdRequest& host_id_request) { std::unique_ptr<Database> database = openDatabase(); if (!database) { LOG(LS_ERROR) << "Failed to connect to database"; return; } proto::RouterToHost message; proto::HostIdResponse* host_id_response = message.mutable_host_id_response(); base::ByteArray key_hash; if (host_id_request.type() == proto::HostIdRequest::NEW_ID) { // Generate new key. std::string key = base::Random::string(kHostKeySize); // Calculate hash for key. key_hash = base::GenericHash::hash(base::GenericHash::Type::BLAKE2b512, key); if (!database->addHost(key_hash)) { LOG(LS_ERROR) << "Unable to add host"; return; } host_id_response->set_key(std::move(key)); } else if (host_id_request.type() == proto::HostIdRequest::EXISTING_ID) { // Using existing key. key_hash = base::GenericHash::hash( base::GenericHash::Type::BLAKE2b512, host_id_request.key()); } else { LOG(LS_ERROR) << "Unknown request type: " << host_id_request.type(); return; } base::HostId host_id = database->hostId(key_hash); if (host_id == base::kInvalidHostId) { LOG(LS_ERROR) << "Failed to get host ID"; return; } host_id_list_.emplace_back(host_id); // Notify the server that the ID has been assigned. server().onHostSessionWithId(this); host_id_response->set_host_id(host_id); sendMessage(message); } void SessionHost::readResetHostId(const proto::ResetHostId& reset_host_id) { base::HostId host_id = reset_host_id.host_id(); if (host_id == base::kInvalidHostId) { LOG(LS_ERROR) << "Invalid host ID"; return; } if (host_id_list_.empty()) { LOG(LS_ERROR) << "Empty host ID list"; return; } for (auto it = host_id_list_.begin(); it != host_id_list_.end(); ++it) { if (*it == host_id) { LOG(LS_INFO) << "Host ID " << host_id << " remove from list"; host_id_list_.erase(it); return; } } LOG(LS_WARNING) << "Host ID " << host_id << " NOT found in list"; } } // namespace router <|endoftext|>
<commit_before>/* Copyright © 2001-2014, Canal TP and/or its affiliates. All rights reserved. This file is part of Navitia, the software to build cool stuff with public transport. Hope you'll enjoy and contribute to this project, powered by Canal TP (www.canaltp.fr). Help us simplify mobility and open public transport: a non ending quest to the responsive locomotion way of traveling! LICENCE: This program is free software; you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. Stay tuned using twitter @navitia IRC #navitia on freenode https://groups.google.com/d/forum/navitia www.navitia.io */ #include "dataraptor.h" #include "routing.h" #include "routing/raptor_utils.h" #include <boost/range/algorithm_ext.hpp> namespace navitia { namespace routing { void dataRAPTOR::Connections::load(const type::PT_Data &data) { forward_connections.assign(data.stop_points.size(), {}); backward_connections.assign(data.stop_points.size(), {}); for (const auto* conn: data.stop_point_connections) { forward_connections.at(conn->departure->idx).push_back( {DateTime(conn->duration), conn->destination->idx}); backward_connections.at(conn->destination->idx).push_back( {DateTime(conn->duration), conn->departure->idx}); } for (auto& conns: forward_connections) { conns.shrink_to_fit(); } for (auto& conns: backward_connections) { conns.shrink_to_fit(); } } void dataRAPTOR::JppsFromSp::load(const type::PT_Data &data) { jpps_from_sp.assign(data.stop_points.size(), {}); for (const auto* sp: data.stop_points) { for (const auto* jpp: sp->journey_pattern_point_list) { jpps_from_sp.at(sp->idx).push_back({jpp->idx, jpp->journey_pattern->idx, jpp->order}); } } for (auto& jpps: jpps_from_sp) { jpps.shrink_to_fit(); } } void dataRAPTOR::JppsFromSp::filter_jpps(const boost::dynamic_bitset<>& valid_jpps) { for (auto& jpps: jpps_from_sp) { boost::remove_erase_if(jpps, [&](const JppIdxOrder& jpp) { return !valid_jpps[jpp.idx]; }); } } void dataRAPTOR::load(const type::PT_Data &data) { labels_const.init_inf(data.journey_pattern_points.size()); labels_const_reverse.init_min(data.journey_pattern_points.size()); connections.load(data); jpps_from_sp.load(data); typedef std::unordered_map<navitia::type::idx_t, vector_idx> idx_vector_idx; idx_vector_idx ridx_journey_pattern; arrival_times.clear(); departure_times.clear(); st_forward.clear(); st_backward.clear(); first_stop_time.clear(); for(int i=0; i<=365; ++i) { jp_validity_patterns.push_back(boost::dynamic_bitset<>(data.journey_patterns.size())); } for(int i=0; i<=365; ++i) { jp_adapted_validity_pattern.push_back(boost::dynamic_bitset<>(data.journey_patterns.size())); } for(const type::JourneyPattern* journey_pattern : data.journey_patterns) { first_stop_time.push_back(arrival_times.size()); nb_trips.push_back(journey_pattern->discrete_vehicle_journey_list.size()); //we group all descrete stop times from all journey_pattern_point //the frequency stop times are not considered here, they are search for a different way in best_stop_time for(unsigned int i=0; i < journey_pattern->journey_pattern_point_list.size(); ++i) { std::vector<const type::StopTime*> vec_st; for(const auto& vj : journey_pattern->discrete_vehicle_journey_list) { assert(vj->stop_time_list[i].journey_pattern_point == journey_pattern->journey_pattern_point_list[i]); vec_st.push_back(&vj->stop_time_list[i]); } std::sort(vec_st.begin(), vec_st.end(), [&](const type::StopTime* st1, const type::StopTime* st2)->bool{ uint32_t time1 = DateTimeUtils::hour(st1->departure_time); uint32_t time2 = DateTimeUtils::hour(st2->departure_time); if(time1 == time2) { const auto& st1_first = st1->vehicle_journey->stop_time_list.front(); const auto& st2_first = st2->vehicle_journey->stop_time_list.front(); if(st1_first.departure_time == st2_first.departure_time) { return st1_first.vehicle_journey->idx < st2_first.vehicle_journey->idx; } return st1_first.departure_time < st2_first.departure_time; } return time1 < time2;}); st_forward.insert(st_forward.end(), vec_st.begin(), vec_st.end()); for(auto st : vec_st) { departure_times.push_back(DateTimeUtils::hour(st->departure_time)); } std::sort(vec_st.begin(), vec_st.end(), [&](const type::StopTime* st1, const type::StopTime* st2)->bool{ uint32_t time1 = DateTimeUtils::hour(st1->arrival_time); uint32_t time2 = DateTimeUtils::hour(st2->arrival_time); if(time1 == time2) { const auto& st1_first = st1->vehicle_journey->stop_time_list.front(); const auto& st2_first = st2->vehicle_journey->stop_time_list.front(); if(st1_first.arrival_time == st2_first.arrival_time) { return st1_first.vehicle_journey->idx > st2_first.vehicle_journey->idx; } return st1_first.arrival_time > st2_first.arrival_time; } return time1 > time2;}); st_backward.insert(st_backward.end(), vec_st.begin(), vec_st.end()); for(auto st : vec_st) { arrival_times.push_back(DateTimeUtils::hour(st->arrival_time)); } } // On dit que le journey pattern est valide en date j s'il y a au moins une circulation à j-1/j+1 for(int i=0; i<=365; ++i) { journey_pattern->for_each_vehicle_journey([&](const nt::VehicleJourney& vj) { if(vj.validity_pattern->check2(i)) { jp_validity_patterns[i].set(journey_pattern->idx); return false; } return true; }); } // On dit que le journey pattern est valide en date j s'il y a au moins une circulation à j-1/j+1 for(int i=0; i<=365; ++i) { journey_pattern->for_each_vehicle_journey([&](const nt::VehicleJourney& vj) { if(vj.adapted_validity_pattern->check2(i)) { jp_adapted_validity_pattern[i].set(journey_pattern->idx); return false; } return true; }); } } } }} <commit_msg>raptor: fix compil with old gcc<commit_after>/* Copyright © 2001-2014, Canal TP and/or its affiliates. All rights reserved. This file is part of Navitia, the software to build cool stuff with public transport. Hope you'll enjoy and contribute to this project, powered by Canal TP (www.canaltp.fr). Help us simplify mobility and open public transport: a non ending quest to the responsive locomotion way of traveling! LICENCE: This program is free software; you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. Stay tuned using twitter @navitia IRC #navitia on freenode https://groups.google.com/d/forum/navitia www.navitia.io */ #include "dataraptor.h" #include "routing.h" #include "routing/raptor_utils.h" #include <boost/range/algorithm_ext.hpp> namespace navitia { namespace routing { void dataRAPTOR::Connections::load(const type::PT_Data &data) { forward_connections.assign(data.stop_points.size(), std::vector<Connection>()); backward_connections.assign(data.stop_points.size(), std::vector<Connection>()); for (const auto* conn: data.stop_point_connections) { forward_connections.at(conn->departure->idx).push_back( {DateTime(conn->duration), conn->destination->idx}); backward_connections.at(conn->destination->idx).push_back( {DateTime(conn->duration), conn->departure->idx}); } for (auto& conns: forward_connections) { conns.shrink_to_fit(); } for (auto& conns: backward_connections) { conns.shrink_to_fit(); } } void dataRAPTOR::JppsFromSp::load(const type::PT_Data &data) { jpps_from_sp.assign(data.stop_points.size(), std::vector<JppIdxOrder>()); for (const auto* sp: data.stop_points) { for (const auto* jpp: sp->journey_pattern_point_list) { jpps_from_sp.at(sp->idx).push_back({jpp->idx, jpp->journey_pattern->idx, jpp->order}); } } for (auto& jpps: jpps_from_sp) { jpps.shrink_to_fit(); } } void dataRAPTOR::JppsFromSp::filter_jpps(const boost::dynamic_bitset<>& valid_jpps) { for (auto& jpps: jpps_from_sp) { boost::remove_erase_if(jpps, [&](const JppIdxOrder& jpp) { return !valid_jpps[jpp.idx]; }); } } void dataRAPTOR::load(const type::PT_Data &data) { labels_const.init_inf(data.journey_pattern_points.size()); labels_const_reverse.init_min(data.journey_pattern_points.size()); connections.load(data); jpps_from_sp.load(data); typedef std::unordered_map<navitia::type::idx_t, vector_idx> idx_vector_idx; idx_vector_idx ridx_journey_pattern; arrival_times.clear(); departure_times.clear(); st_forward.clear(); st_backward.clear(); first_stop_time.clear(); for(int i=0; i<=365; ++i) { jp_validity_patterns.push_back(boost::dynamic_bitset<>(data.journey_patterns.size())); } for(int i=0; i<=365; ++i) { jp_adapted_validity_pattern.push_back(boost::dynamic_bitset<>(data.journey_patterns.size())); } for(const type::JourneyPattern* journey_pattern : data.journey_patterns) { first_stop_time.push_back(arrival_times.size()); nb_trips.push_back(journey_pattern->discrete_vehicle_journey_list.size()); //we group all descrete stop times from all journey_pattern_point //the frequency stop times are not considered here, they are search for a different way in best_stop_time for(unsigned int i=0; i < journey_pattern->journey_pattern_point_list.size(); ++i) { std::vector<const type::StopTime*> vec_st; for(const auto& vj : journey_pattern->discrete_vehicle_journey_list) { assert(vj->stop_time_list[i].journey_pattern_point == journey_pattern->journey_pattern_point_list[i]); vec_st.push_back(&vj->stop_time_list[i]); } std::sort(vec_st.begin(), vec_st.end(), [&](const type::StopTime* st1, const type::StopTime* st2)->bool{ uint32_t time1 = DateTimeUtils::hour(st1->departure_time); uint32_t time2 = DateTimeUtils::hour(st2->departure_time); if(time1 == time2) { const auto& st1_first = st1->vehicle_journey->stop_time_list.front(); const auto& st2_first = st2->vehicle_journey->stop_time_list.front(); if(st1_first.departure_time == st2_first.departure_time) { return st1_first.vehicle_journey->idx < st2_first.vehicle_journey->idx; } return st1_first.departure_time < st2_first.departure_time; } return time1 < time2;}); st_forward.insert(st_forward.end(), vec_st.begin(), vec_st.end()); for(auto st : vec_st) { departure_times.push_back(DateTimeUtils::hour(st->departure_time)); } std::sort(vec_st.begin(), vec_st.end(), [&](const type::StopTime* st1, const type::StopTime* st2)->bool{ uint32_t time1 = DateTimeUtils::hour(st1->arrival_time); uint32_t time2 = DateTimeUtils::hour(st2->arrival_time); if(time1 == time2) { const auto& st1_first = st1->vehicle_journey->stop_time_list.front(); const auto& st2_first = st2->vehicle_journey->stop_time_list.front(); if(st1_first.arrival_time == st2_first.arrival_time) { return st1_first.vehicle_journey->idx > st2_first.vehicle_journey->idx; } return st1_first.arrival_time > st2_first.arrival_time; } return time1 > time2;}); st_backward.insert(st_backward.end(), vec_st.begin(), vec_st.end()); for(auto st : vec_st) { arrival_times.push_back(DateTimeUtils::hour(st->arrival_time)); } } // On dit que le journey pattern est valide en date j s'il y a au moins une circulation à j-1/j+1 for(int i=0; i<=365; ++i) { journey_pattern->for_each_vehicle_journey([&](const nt::VehicleJourney& vj) { if(vj.validity_pattern->check2(i)) { jp_validity_patterns[i].set(journey_pattern->idx); return false; } return true; }); } // On dit que le journey pattern est valide en date j s'il y a au moins une circulation à j-1/j+1 for(int i=0; i<=365; ++i) { journey_pattern->for_each_vehicle_journey([&](const nt::VehicleJourney& vj) { if(vj.adapted_validity_pattern->check2(i)) { jp_adapted_validity_pattern[i].set(journey_pattern->idx); return false; } return true; }); } } } }} <|endoftext|>
<commit_before>/*************************************************** This is a library for the CAP1188 I2C/SPI 8-chan Capacitive Sensor Designed specifically to work with the CAP1188 sensor from Adafruit ----> https://www.adafruit.com/products/1602 These sensors use I2C/SPI to communicate, 2+ pins are required to interface Adafruit invests time and resources providing this open source code, please support Adafruit and open-source hardware by purchasing products from Adafruit! Written by Limor Fried/Ladyada for Adafruit Industries. BSD license, all text above must be included in any redistribution ****************************************************/ #include "Adafruit_CAP1188.h" // byte mySPCR, SPCRback; byte _i2caddr; char _resetpin; bool _i2c = true; Adafruit_CAP1188::Adafruit_CAP1188(char resetpin) { //I2C _resetpin = resetpin; _i2c = true; } // Adafruit_CAP1188::Adafruit_CAP1188(char cspin, char resetpin) { //Hardware SPI // _cs = cspin; // _resetpin = resetpin; // _clk = -1; // _i2c = false; // } // Adafruit_CAP1188::Adafruit_CAP1188(char clkpin, char misopin, // char mosipin,char cspin, // char resetpin) { //Software SPI // _cs = cspin; // _resetpin = resetpin; // _clk = clkpin; // _miso = misopin; // _mosi = mosipin; // _i2c = false; // } boolean Adafruit_CAP1188::begin(byte i2caddr) { if (_i2c) { Wire.begin(); _i2caddr = i2caddr; } // else if (_clk == -1) { //Hardware SPI // digitalWrite(_cs, HIGH); // SPCRback = SPCR; // SPI.begin(); // SPI.setClockDivider(SPI_CLOCK_DIV8); // SPI.setDataMode(SPI_MODE0); // mySPCR = SPCR; // SPCR = SPCRback; // } else { //Sofware SPI // pinMode(_clk, OUTPUT); // pinMode(_mosi, OUTPUT); // pinMode(_cs, OUTPUT); // digitalWrite(_cs, HIGH); // digitalWrite(_clk, HIGH); // } if (_resetpin != -1) { pinMode(_resetpin, OUTPUT); digitalWrite(_resetpin, LOW); delay(100); digitalWrite(_resetpin, HIGH); delay(100); digitalWrite(_resetpin, LOW); delay(100); } readRegister(CAP1188_PRODID); // Useful debugging info Serial.print("Product ID: 0x"); Serial.println(readRegister(CAP1188_PRODID), HEX); Serial.print("Manuf. ID: 0x"); Serial.println(readRegister(CAP1188_MANUID), HEX); Serial.print("Revision: 0x"); Serial.println(readRegister(CAP1188_REV), HEX); if ( (readRegister(CAP1188_PRODID) != 0x50) || (readRegister(CAP1188_MANUID) != 0x5D) || (readRegister(CAP1188_REV) != 0x83)) { return false; } // allow multiple touches writeRegister(CAP1188_MTBLK, 0); // Have LEDs follow touches writeRegister(CAP1188_LEDLINK, 0xFF); // speed up a bit writeRegister(CAP1188_STANDBYCFG, 0x30); return true; } byte Adafruit_CAP1188::touched(void) { byte t = readRegister(CAP1188_SENINPUTSTATUS); if (t) { writeRegister(CAP1188_MAIN, readRegister(CAP1188_MAIN) & ~CAP1188_MAIN_INT); } return t; } void Adafruit_CAP1188::LEDpolarity(byte x) { writeRegister(CAP1188_LEDPOL, x); } /*********************************************************************/ /**************************************************************************/ /*! @brief Abstract away platform differences in Arduino wire library */ /**************************************************************************/ static byte i2cread(void) { // #if ARDUINO >= 100 return Wire.read(); // #else // return Wire.receive(); // #endif } /**************************************************************************/ /*! @brief Abstract away platform differences in Arduino wire library */ /**************************************************************************/ static void i2cwrite(byte x) { // #if ARDUINO >= 100 Wire.write((byte)x); // #else // Wire.send(x); // #endif } /**************************************************************************/ /*! @brief Reads 8-bits from the specified register */ /**************************************************************************/ // byte Adafruit_CAP1188::spixfer(byte data) { // if (_clk == -1) { //Serial.println("Hardware SPI"); // return SPI.transfer(data); // } else { //Serial.println("Software SPI"); // byte reply = 0; // for (int i=7; i>=0; i--) { // reply <<= 1; // digitalWrite(_clk, LOW); // digitalWrite(_mosi, data & (1<<i)); // digitalWrite(_clk, HIGH); // if (digitalRead(_miso)) // reply |= 1; // } // return reply; // } // } byte Adafruit_CAP1188::readRegister(byte reg) { if (_i2c) { Wire.beginTransmission(_i2caddr); i2cwrite(reg); Wire.endTransmission(); Wire.requestFrom(_i2caddr, 1); return (i2cread()); } // else { // if (_clk == -1) { // SPCRback = SPCR; // SPCR = mySPCR; // } // digitalWrite(_cs, LOW); //set address // spixfer(0x7D); // spixfer(reg); // digitalWrite(_cs, HIGH); // digitalWrite(_cs, LOW); // spixfer(0x7F); // byte reply = spixfer(0); // digitalWrite(_cs, HIGH); // if (_clk == -1) { // SPCR = SPCRback; // } // return reply; // } else { return 0; } } /**************************************************************************/ /*! @brief Writes 8-bits to the specified destination register */ /**************************************************************************/ void Adafruit_CAP1188::writeRegister(byte reg, byte value) { if (_i2c) { Wire.beginTransmission(_i2caddr); i2cwrite((byte)reg); i2cwrite((byte)(value)); Wire.endTransmission(); } // else { // if (_clk == -1) { // SPCRback = SPCR; // SPCR = mySPCR; // } // digitalWrite(_cs, LOW); //set address // spixfer(0x7D); // spixfer(reg); // digitalWrite(_cs, HIGH); // digitalWrite(_cs, LOW); // spixfer(0x7E); // spixfer(value); // digitalWrite(_cs, HIGH); // if (_clk == -1) { // SPCR = SPCRback; // } // } } <commit_msg>Update Adafruit_CAP1188.cpp<commit_after>/*************************************************** This is a library for the CAP1188 I2C/SPI 8-chan Capacitive Sensor Designed specifically to work with the CAP1188 sensor from Adafruit ----> https://www.adafruit.com/products/1602 These sensors use I2C/SPI to communicate, 2+ pins are required to interface Adafruit invests time and resources providing this open source code, please support Adafruit and open-source hardware by purchasing products from Adafruit! Written by Limor Fried/Ladyada for Adafruit Industries. BSD license, all text above must be included in any redistribution ****************************************************/ // #include "Adafruit_CAP1188.h" // byte mySPCR, SPCRback; byte _i2caddr; char _resetpin; bool _i2c = true; Adafruit_CAP1188::Adafruit_CAP1188(char resetpin) { //I2C _resetpin = resetpin; _i2c = true; } // Adafruit_CAP1188::Adafruit_CAP1188(char cspin, char resetpin) { //Hardware SPI // _cs = cspin; // _resetpin = resetpin; // _clk = -1; // _i2c = false; // } // Adafruit_CAP1188::Adafruit_CAP1188(char clkpin, char misopin, // char mosipin,char cspin, // char resetpin) { //Software SPI // _cs = cspin; // _resetpin = resetpin; // _clk = clkpin; // _miso = misopin; // _mosi = mosipin; // _i2c = false; // } boolean Adafruit_CAP1188::begin(byte i2caddr) { if (_i2c) { Wire.begin(); _i2caddr = i2caddr; } // else if (_clk == -1) { //Hardware SPI // digitalWrite(_cs, HIGH); // SPCRback = SPCR; // SPI.begin(); // SPI.setClockDivider(SPI_CLOCK_DIV8); // SPI.setDataMode(SPI_MODE0); // mySPCR = SPCR; // SPCR = SPCRback; // } else { //Sofware SPI // pinMode(_clk, OUTPUT); // pinMode(_mosi, OUTPUT); // pinMode(_cs, OUTPUT); // digitalWrite(_cs, HIGH); // digitalWrite(_clk, HIGH); // } if (_resetpin != -1) { pinMode(_resetpin, OUTPUT); digitalWrite(_resetpin, LOW); delay(100); digitalWrite(_resetpin, HIGH); delay(100); digitalWrite(_resetpin, LOW); delay(100); } readRegister(CAP1188_PRODID); // Useful debugging info Serial.print("Product ID: 0x"); Serial.println(readRegister(CAP1188_PRODID), HEX); Serial.print("Manuf. ID: 0x"); Serial.println(readRegister(CAP1188_MANUID), HEX); Serial.print("Revision: 0x"); Serial.println(readRegister(CAP1188_REV), HEX); if ( (readRegister(CAP1188_PRODID) != 0x50) || (readRegister(CAP1188_MANUID) != 0x5D) || (readRegister(CAP1188_REV) != 0x83)) { return false; } // allow multiple touches writeRegister(CAP1188_MTBLK, 0); // Have LEDs follow touches writeRegister(CAP1188_LEDLINK, 0xFF); // speed up a bit writeRegister(CAP1188_STANDBYCFG, 0x30); return true; } byte Adafruit_CAP1188::touched(void) { byte t = readRegister(CAP1188_SENINPUTSTATUS); if (t) { writeRegister(CAP1188_MAIN, readRegister(CAP1188_MAIN) & ~CAP1188_MAIN_INT); } return t; } void Adafruit_CAP1188::LEDpolarity(byte x) { writeRegister(CAP1188_LEDPOL, x); } /*********************************************************************/ /**************************************************************************/ /*! @brief Abstract away platform differences in Arduino wire library */ /**************************************************************************/ static byte i2cread(void) { // #if ARDUINO >= 100 return Wire.read(); // #else // return Wire.receive(); // #endif } /**************************************************************************/ /*! @brief Abstract away platform differences in Arduino wire library */ /**************************************************************************/ static void i2cwrite(byte x) { // #if ARDUINO >= 100 Wire.write((byte)x); // #else // Wire.send(x); // #endif } /**************************************************************************/ /*! @brief Reads 8-bits from the specified register */ /**************************************************************************/ // byte Adafruit_CAP1188::spixfer(byte data) { // if (_clk == -1) { //Serial.println("Hardware SPI"); // return SPI.transfer(data); // } else { //Serial.println("Software SPI"); // byte reply = 0; // for (int i=7; i>=0; i--) { // reply <<= 1; // digitalWrite(_clk, LOW); // digitalWrite(_mosi, data & (1<<i)); // digitalWrite(_clk, HIGH); // if (digitalRead(_miso)) // reply |= 1; // } // return reply; // } // } byte Adafruit_CAP1188::readRegister(byte reg) { if (_i2c) { Wire.beginTransmission(_i2caddr); i2cwrite(reg); Wire.endTransmission(); Wire.requestFrom(_i2caddr, 1); return (i2cread()); } // else { // if (_clk == -1) { // SPCRback = SPCR; // SPCR = mySPCR; // } // digitalWrite(_cs, LOW); //set address // spixfer(0x7D); // spixfer(reg); // digitalWrite(_cs, HIGH); // digitalWrite(_cs, LOW); // spixfer(0x7F); // byte reply = spixfer(0); // digitalWrite(_cs, HIGH); // if (_clk == -1) { // SPCR = SPCRback; // } // return reply; // } else { return 0; } } /**************************************************************************/ /*! @brief Writes 8-bits to the specified destination register */ /**************************************************************************/ void Adafruit_CAP1188::writeRegister(byte reg, byte value) { if (_i2c) { Wire.beginTransmission(_i2caddr); i2cwrite((byte)reg); i2cwrite((byte)(value)); Wire.endTransmission(); } // else { // if (_clk == -1) { // SPCRback = SPCR; // SPCR = mySPCR; // } // digitalWrite(_cs, LOW); //set address // spixfer(0x7D); // spixfer(reg); // digitalWrite(_cs, HIGH); // digitalWrite(_cs, LOW); // spixfer(0x7E); // spixfer(value); // digitalWrite(_cs, HIGH); // if (_clk == -1) { // SPCR = SPCRback; // } // } } <|endoftext|>
<commit_before>#include <seqan/seeds.h> #include <seqan/file.h> #include <fstream> using namespace seqan; using namespace std; template <typename TSeedSet, typename TSegment, typename TSize> TSize findSeeds(TSeedSet & seedset, TSegment const & seg_0, TSegment const & seg_1, TSize q, TSize q_min) { //add all common q-grams into seetset typedef Index< TSegment, Index_QGram<SimpleShape > > TQGramIndex; TQGramIndex index_qgram(seg_1); while ((length(seedset) == 0) && (q >= q_min)) { resize(indexShape(index_qgram), q); typedef Finder<TQGramIndex> TFinder; TFinder finder(index_qgram); int q_gram_count = length(seg_0)-q+1; for (int i = 0; i < q_gram_count; ++i) { while (find(finder, infix(seg_0, i, i+q))) { typedef typename Position<TFinder>::Type TPosition; TPosition pos = position(finder); if (!addSeed(seedset, beginPosition(seg_0)+i, beginPosition(seg_1)+pos, q, 0, Merge())) if (!addSeed(seedset, beginPosition(seg_0)+i, beginPosition(seg_1)+pos, q, host(seg_0), host(seg_1), 5, Chaos())) addSeed(seedset, beginPosition(seg_0)+i, beginPosition(seg_1)+pos, q, Single()); } clear(finder); } --q; } return q; } template <typename TSeed, typename TSegment, typename TSize, typename TScoring, typename TScore> void lagan(list<TSeed> & chain, TSegment const & seg_0, TSegment const & seg_1, TSize q, TSize q_min, TSize limit, TSize gaps_max, TScoring scoring_scheme, TScore score_min) { if (((TSize)length(seg_0) <= gaps_max) && ((TSize)length(seg_1) <= gaps_max)) return; //Step 1: find seeds typedef typename Value<TSeed>::Type TPosition; typedef SeedSet<TPosition, SimpleSeed, DefaultScore> TSeedSet; TSeedSet seedset(limit, score_min, scoring_scheme); q = findSeeds(seedset, seg_0, seg_1, q, q_min); if (!length(seedset)) return; //Step 2: global chaining globalChaining(seedset, chain); clear(seedset); //Step 3: recursively fill gaps if (q > q_min) { list<TSeed> subchain; typedef typename list<TSeed>::iterator TIterator; TIterator it = chain.begin(); TIterator it2 = it; ++it2; lagan(subchain, infix(host(seg_0), beginPosition(seg_0), leftDim0(*it)), infix(host(seg_1), beginPosition(seg_1), leftDim1(*it)), q, q_min, limit, gaps_max, scoring_scheme, score_min); chain.splice(it, subchain); while(it2 != chain.end()) { lagan(subchain, infix(host(seg_0), rightDim0(*it), leftDim0(*it2)), infix(host(seg_1), rightDim1(*it), leftDim1(*it2)), q, q_min, limit, gaps_max, scoring_scheme, score_min); chain.splice(it2, subchain); it = it2; ++it2; } lagan(subchain, infix(host(seg_0), rightDim0(*it), endPosition(seg_0)), infix(host(seg_1), rightDim1(*it), endPosition(seg_1)), q, q_min, limit, gaps_max, scoring_scheme, score_min); chain.splice(it2, subchain); } } template <typename TString> void loadFile(char const * filename, TString & str) { //load file into str fstream fstrm; fstrm.open(filename, ios_base::in | ios_base::binary); if (fstrm.fail()) { cout << "error: " << filename << " not found" << endl; return; } read(fstrm, str, Fasta()); fstrm.close(); } int main() { //load sequences typedef String<Dna> TString; TString str_0; loadFile("lagan1.fasta", str_0); TString str_1; loadFile("lagan2.fasta", str_1); //call lagan if ((length(str_0) > 0) && (length(str_1) > 0)) { typedef Seed<int, SimpleSeed> TSeed; list<TSeed> chain; //Step 1 to 3 lagan(chain, infix(str_0, 0, length(str_0)), infix(str_1, 0, length(str_1)), 13, 8, 6, 200, SimpleScore(3,-2,-1,-3), 30); //Step 4: banded alignment Align<TString, ArrayGaps> alignment; resize(rows(alignment), 2); setSource(row(alignment, 0), str_0); setSource(row(alignment, 1), str_1); int score = bandedChainAlignment(chain, 7, alignment, SimpleScore(3,-2,-1,-3)); //cout << "Score: " << score << endl; cout << alignment << endl; } else { cout << "Error - File problem" << endl; } } <commit_msg>Further improvements of lagan.cpp demo<commit_after>#include <fstream> #include <seqan/seeds.h> #include <seqan/file.h> using namespace seqan; using namespace std; template <typename TSeed, typename TSegment, typename TSize, typename TScoring, typename TScore> void laganChaining(list<TSeed> & chain, TSegment const & a, TSegment const & b, TSize q, TSize q_min, TSize limit, TSize gaps_max, TScoring scoring_scheme, TScore score_min) { if (((TSize)length(a) <= gaps_max) && ((TSize)length(b) <= gaps_max)) return; //Step 1: find seeds typedef typename Value<TSeed>::Type TPosition; typedef SeedSet<TPosition, SimpleSeed, DefaultScore> TSeedSet; TSeedSet seedset(limit, score_min, scoring_scheme); typedef Index< TSegment, Index_QGram<SimpleShape > > TQGramIndex; TQGramIndex index_qgram(b); typedef Finder<TQGramIndex> TFinder; TFinder finder(index_qgram); while (length(seedset) == 0) { if (q <= q_min) return; resize(indexShape(index_qgram), q); for (int i = 0; i < length(a)-q+1; ++i) { while (find(finder, infix(a, i, i+q))) { typedef typename Position<TFinder>::Type TPosition; TPosition a_pos = beginPosition(a)+i; TPosition b_pos = beginPosition(b)+position(finder); if (!addSeed(seedset, a_pos, b_pos, q, 0, Merge())) if (!addSeed(seedset, a_pos, b_pos, q, host(a), host(b), 5, Chaos())) addSeed(seedset, a_pos, b_pos, q, Single()); } clear(finder); } --q; } //Step 2: global chaining globalChaining(seedset, chain); clear(seedset); //Step 3: recursively fill gaps if (q > q_min) { list<TSeed> subchain; typedef typename list<TSeed>::iterator TIterator; TIterator it = chain.begin(); TIterator it2 = it; ++it2; laganChaining(subchain, infix(host(a), beginPosition(a), leftDim0(*it)), infix(host(b), beginPosition(b), leftDim1(*it)), q, q_min, limit, gaps_max, scoring_scheme, score_min); chain.splice(it, subchain); while(it2 != chain.end()) { laganChaining(subchain, infix(host(a), rightDim0(*it), leftDim0(*it2)), infix(host(b), rightDim1(*it), leftDim1(*it2)), q, q_min, limit, gaps_max, scoring_scheme, score_min); chain.splice(it2, subchain); it = it2; ++it2; } laganChaining(subchain, infix(host(a), rightDim0(*it), endPosition(a)), infix(host(b), rightDim1(*it), endPosition(b)), q, q_min, limit, gaps_max, scoring_scheme, score_min); chain.splice(it2, subchain); } } int main() { //load sequences typedef String<Dna> TString; TString a = String<Dna, FileReader<Fasta> >("lagan1.fasta"); TString b = String<Dna, FileReader<Fasta> >("lagan2.fasta"); //call lagan if ((length(a) > 0) && (length(b) > 0)) { typedef Seed<int, SimpleSeed> TSeed; list<TSeed> chain; //Step 1 to 3 laganChaining(chain, infix(a, 0, length(a)), infix(b, 0, length(b)), 13, 8, 6, 200, SimpleScore(3,-2,-1,-3), 30); //Step 4: banded alignment Align<TString, ArrayGaps> alignment; resize(rows(alignment), 2); setSource(row(alignment, 0), a); setSource(row(alignment, 1), b); int score = bandedChainAlignment(chain, 7, alignment, SimpleScore(3,-2,-1,-3)); cout << "Score: " << score << endl; cout << alignment << endl; } else { cout << "Error - File problem" << endl; } return 0; } <|endoftext|>
<commit_before>/* * Copyright (C) 2013 midnightBITS * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use, copy, * modify, merge, publish, distribute, sublicense, and/or sell copies * of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ #include "pch.h" #include <handlers.hpp> #include <utils.hpp> #include "api_handler.hpp" #include "json.hpp" namespace json { struct Subscriptions { db::CursorPtr folders; db::CursorPtr feeds; }; JSON_CURSOR_RULE(Folders) { JSON_CURSOR_LL(id, 0); JSON_CURSOR_TEXT(title, 1); JSON_CURSOR_LL(parent, 2); } JSON_CURSOR_RULE(Feeds) { JSON_CURSOR_LL(id, 0); JSON_CURSOR_TEXT(title, 1); JSON_CURSOR_TEXT(url, 2); JSON_CURSOR_LL(parent, 3); JSON_CURSOR_LL(unread, 4); } JSON_RULE(Subscriptions) { JSON_ADD_CURSOR(folders, Folders); JSON_ADD_CURSOR(feeds, Feeds); } }; namespace FastCGI { namespace app { namespace api { class Subscription: public APIOperation { public: void render(SessionPtr session, Request& request, PageTranslation& tr) { db::ConnectionPtr db = request.dbConn(); auto folders = db->prepare("SELECT _id, name, parent FROM folder WHERE user_id=?"); if (!folders || !folders->bind(0, session->getId())) { FLOG << (folders ? folders->errorMessage() : db->errorMessage()); request.on500(); } auto feeds = db->prepare("SELECT feed_id, feed, feed_url, folder_id, count FROM ordered_stats WHERE user_id=? AND type=0"); if (!feeds || !feeds->bind(0, session->getId())) { FLOG << (feeds ? feeds->errorMessage() : db->errorMessage()); request.on500(); } json::Subscriptions subs; subs.folders = folders->query(); if (!subs.folders) { FLOG << folders->errorMessage(); request.on500(); } subs.feeds = feeds->query(); if (!subs.feeds) { FLOG << feeds->errorMessage(); request.on500(); } request.setHeader("Content-Type", "application/json; charset=utf-8"); json::render(request, subs); } const char** getVariables() const { static const char* vars[] = { nullptr }; return vars; } }; }}} // FastCGI::app::api REGISTER_OPERATION("subscription", FastCGI::app::api::Subscription); <commit_msg>Adding unread and starred to the subscription API<commit_after>/* * Copyright (C) 2013 midnightBITS * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use, copy, * modify, merge, publish, distribute, sublicense, and/or sell copies * of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ #include "pch.h" #include <handlers.hpp> #include <utils.hpp> #include "api_handler.hpp" #include "json.hpp" namespace json { struct Subscriptions { db::CursorPtr folders; db::CursorPtr feeds; db::CursorPtr unread; db::CursorPtr starred; }; JSON_CURSOR_RULE(Folders) { JSON_CURSOR_LL(id, 0); JSON_CURSOR_TEXT(title, 1); JSON_CURSOR_LL(parent, 2); } JSON_CURSOR_RULE(Feeds) { JSON_CURSOR_LL(id, 0); JSON_CURSOR_TEXT(title, 1); JSON_CURSOR_TEXT(url, 2); JSON_CURSOR_LL(parent, 3); JSON_CURSOR_LL(unread, 4); } struct State: CursorJson<State> { State(const db::CursorPtr& c); bool entryIsScalar() const { return true; } }; State::State(const db::CursorPtr& c): CursorJson<State>(c) { JSON_CURSOR_LL(value, 0); }; JSON_RULE(Subscriptions) { JSON_ADD_CURSOR(folders, Folders); JSON_ADD_CURSOR(feeds, Feeds); JSON_ADD_CURSOR(unread, State); JSON_ADD_CURSOR(starred, State); } }; #define SELECT(stmt, QUERY) \ auto stmt = db->prepare(QUERY); \ if (!stmt || !stmt->bind(0, session->getId())) \ { \ FLOG << (stmt ? stmt->errorMessage() : db->errorMessage()); \ request.on500(); \ } \ \ subs.stmt = stmt->query(); \ if (!subs.stmt) \ { \ FLOG << stmt->errorMessage(); \ request.on500(); \ } namespace FastCGI { namespace app { namespace api { class Subscription: public APIOperation { public: void render(SessionPtr session, Request& request, PageTranslation& tr) { db::ConnectionPtr db = request.dbConn(); json::Subscriptions subs; SELECT(folders, "SELECT _id, name, parent FROM folder WHERE user_id=?"); SELECT(feeds, "SELECT feed_id, feed, feed_url, folder_id, count FROM ordered_stats WHERE user_id=? AND type=0"); SELECT(unread, "SELECT entry_id FROM state WHERE user_id=? AND type=0 ORDER BY entry_id ASC"); SELECT(starred, "SELECT entry_id FROM state WHERE user_id=? AND type=1 ORDER BY entry_id ASC"); request.setHeader("Content-Type", "application/json; charset=utf-8"); json::render(request, subs); } const char** getVariables() const { static const char* vars[] = { nullptr }; return vars; } }; }}} // FastCGI::app::api REGISTER_OPERATION("subscription", FastCGI::app::api::Subscription); <|endoftext|>
<commit_before>#include <LibUtilities/BasicUtils/SessionReader.h> #include <LibUtilities/Communication/Comm.h> #include <MultiRegions/ExpList2D.h> #include <vtkPolyDataReader.h> #include <vtkPolyData.h> #include <vtkPointData.h> #include <vtkPoints.h> #include <vtkCellArray.h> #include <vtkCellDataToPointData.h> #include <vtkContourFilter.h> // Usage: VtkToFld session.xml input.vtk output.fld #include <boost/unordered_set.hpp> struct Vertex { Vertex(double pX, double pY, double pZ, double pScalar, double factor) : x((int)floor(pX*factor)), y((int)floor(pY*factor)), z((int)floor(pZ*factor)), scalar(pScalar) {} int x; int y; int z; double scalar; bool operator=(const Vertex& v) { return (x == v.x && y == v.y && z == v.z); } }; typedef boost::shared_ptr<Vertex> VertexSharedPtr; struct VertexHash : std::unary_function<VertexSharedPtr, std::size_t> { std::size_t operator()(VertexSharedPtr const& p) const { std::size_t seed = 0; boost::hash_combine(seed, p -> x); boost::hash_combine(seed, p -> y); boost::hash_combine(seed, p -> z); return seed; } }; typedef boost::unordered_set<VertexSharedPtr, VertexHash> VertexSet; bool operator==(const VertexSharedPtr& v1, const VertexSharedPtr& v2) { return v1->operator=(*v2); } int main(int argc, char* argv[]) { MultiRegions::ExpList2DSharedPtr Exp; std::vector<std::string> vFilenames; vFilenames.push_back(std::string(argv[1])); LibUtilities::SessionReaderSharedPtr vSession = LibUtilities::SessionReader::CreateInstance(2, argv, vFilenames); try { const double factor = atof(argv[4]); //---------------------------------------------- // Read in mesh from input file SpatialDomains::MeshGraphSharedPtr graph2D = MemoryManager<SpatialDomains::MeshGraph2D>::AllocateSharedPtr(vSession); //---------------------------------------------- //---------------------------------------------- // Define Expansion Exp = MemoryManager<MultiRegions::ExpList2D>:: AllocateSharedPtr(vSession,graph2D); //---------------------------------------------- //---------------------------------------------- // Set up coordinates of mesh int coordim = Exp->GetCoordim(0); int nq = Exp->GetNpoints(); Array<OneD, NekDouble> xc0(nq,0.0); Array<OneD, NekDouble> xc1(nq,0.0); Array<OneD, NekDouble> xc2(nq,0.0); switch(coordim) { case 2: Exp->GetCoords(xc0,xc1); break; case 3: Exp->GetCoords(xc0,xc1,xc2); break; default: ASSERTL0(false,"Coordim not valid"); break; } //---------------------------------------------- vtkPolyDataReader *vtkMeshReader = vtkPolyDataReader::New(); vtkMeshReader->SetFileName(argv[2]); vtkMeshReader->Update(); vtkPolyData *vtkMesh = vtkMeshReader->GetOutput(); vtkCellDataToPointData* c2p = vtkCellDataToPointData::New(); c2p->SetInput(vtkMesh); c2p->PassCellDataOn(); c2p->Update(); vtkPolyData *vtkDataAtPoints = c2p->GetPolyDataOutput(); vtkPoints *vtkPoints = vtkMesh->GetPoints(); vtkCellArray *vtkPolys = vtkMesh->GetPolys(); ASSERTL0(vtkPoints, "ERROR: cannot get points from mesh."); ASSERTL0(vtkPolys, "ERROR: cannot get polygons from mesh."); VertexSet points; VertexSet::iterator vIter; double p[3]; double val; double x, y, z; int coeff_idx; int i,j; // Build up an unordered set of vertices from the VTK file. For each // vertex a hashed value of the coordinates is generated to within a // given tolerance. for (i = 0; i < vtkPoints->GetNumberOfPoints(); ++i) { vtkPoints->GetPoint(i,p); val = vtkDataAtPoints->GetPointData()->GetScalars("Image_Intensity")->GetTuple1(i); boost::shared_ptr<Vertex> v(new Vertex(p[0],p[1],p[2],val,factor)); points.insert(v); } // Now process each vertex of each element in the mesh for (i = 0; i < Exp->GetNumElmts(); ++i) { StdRegions::StdExpansionSharedPtr e = Exp->GetExp(i); for (j = 0; j < e->GetNverts(); ++j) { // Get the index of the coefficient corresponding to this vertex coeff_idx = Exp->GetCoeff_Offset(i) + e->GetVertexMap(j); // Get the coordinates of the vertex SpatialDomains::VertexComponentSharedPtr vert = e->GetGeom2D()->GetVertex(j); vert->GetCoords(x,y,z); // Look up the vertex in the VertexSet boost::shared_ptr<Vertex> v(new Vertex(x,y,z,0.0,factor)); vIter = points.find(v); // If not found, maybe the tolerance should be reduced? // If found, record the scalar value from the VTK file in the // corresponding coefficient. if (vIter == points.end()) { cerr << "Vertex " << i << " not found." << x << ", " << y << ", " << z << endl; cerr << v->x << ", " << v->y << ", " << v->z << endl; } else { Exp->UpdateCoeffs()[coeff_idx] = (*vIter)->scalar; } } } Exp->SetPhysState(false); //----------------------------------------------- // Write solution to file string out(argv[3]); if (vSession->GetComm()->GetSize() > 1) { out += "." + boost::lexical_cast<string>(vSession->GetComm()->GetRank()); } std::vector<SpatialDomains::FieldDefinitionsSharedPtr> FieldDef = Exp->GetFieldDefinitions(); std::vector<std::vector<NekDouble> > FieldData(FieldDef.size()); for(i = 0; i < FieldDef.size(); ++i) { FieldDef[i]->m_fields.push_back("intensity"); Exp->AppendFieldData(FieldDef[i], FieldData[i]); } graph2D->Write(out, FieldDef, FieldData); //----------------------------------------------- } catch (...) { cout << "An error occurred." << endl; } } <commit_msg>Added missing include in VtkToFld.<commit_after>#include <LibUtilities/BasicUtils/SessionReader.h> #include <LibUtilities/Communication/Comm.h> #include <SpatialDomains/MeshGraph2D.h> #include <MultiRegions/ExpList2D.h> #include <vtkPolyDataReader.h> #include <vtkPolyData.h> #include <vtkPointData.h> #include <vtkPoints.h> #include <vtkCellArray.h> #include <vtkCellDataToPointData.h> #include <vtkContourFilter.h> // Usage: VtkToFld session.xml input.vtk output.fld #include <boost/unordered_set.hpp> struct Vertex { Vertex(double pX, double pY, double pZ, double pScalar, double factor) : x((int)floor(pX*factor)), y((int)floor(pY*factor)), z((int)floor(pZ*factor)), scalar(pScalar) {} int x; int y; int z; double scalar; bool operator=(const Vertex& v) { return (x == v.x && y == v.y && z == v.z); } }; typedef boost::shared_ptr<Vertex> VertexSharedPtr; struct VertexHash : std::unary_function<VertexSharedPtr, std::size_t> { std::size_t operator()(VertexSharedPtr const& p) const { std::size_t seed = 0; boost::hash_combine(seed, p -> x); boost::hash_combine(seed, p -> y); boost::hash_combine(seed, p -> z); return seed; } }; typedef boost::unordered_set<VertexSharedPtr, VertexHash> VertexSet; bool operator==(const VertexSharedPtr& v1, const VertexSharedPtr& v2) { return v1->operator=(*v2); } int main(int argc, char* argv[]) { MultiRegions::ExpList2DSharedPtr Exp; std::vector<std::string> vFilenames; vFilenames.push_back(std::string(argv[1])); LibUtilities::SessionReaderSharedPtr vSession = LibUtilities::SessionReader::CreateInstance(2, argv, vFilenames); try { const double factor = atof(argv[4]); //---------------------------------------------- // Read in mesh from input file SpatialDomains::MeshGraphSharedPtr graph2D = MemoryManager<SpatialDomains::MeshGraph2D>::AllocateSharedPtr(vSession); //---------------------------------------------- //---------------------------------------------- // Define Expansion Exp = MemoryManager<MultiRegions::ExpList2D>:: AllocateSharedPtr(vSession,graph2D); //---------------------------------------------- //---------------------------------------------- // Set up coordinates of mesh int coordim = Exp->GetCoordim(0); int nq = Exp->GetNpoints(); Array<OneD, NekDouble> xc0(nq,0.0); Array<OneD, NekDouble> xc1(nq,0.0); Array<OneD, NekDouble> xc2(nq,0.0); switch(coordim) { case 2: Exp->GetCoords(xc0,xc1); break; case 3: Exp->GetCoords(xc0,xc1,xc2); break; default: ASSERTL0(false,"Coordim not valid"); break; } //---------------------------------------------- vtkPolyDataReader *vtkMeshReader = vtkPolyDataReader::New(); vtkMeshReader->SetFileName(argv[2]); vtkMeshReader->Update(); vtkPolyData *vtkMesh = vtkMeshReader->GetOutput(); vtkCellDataToPointData* c2p = vtkCellDataToPointData::New(); c2p->SetInput(vtkMesh); c2p->PassCellDataOn(); c2p->Update(); vtkPolyData *vtkDataAtPoints = c2p->GetPolyDataOutput(); vtkPoints *vtkPoints = vtkMesh->GetPoints(); vtkCellArray *vtkPolys = vtkMesh->GetPolys(); ASSERTL0(vtkPoints, "ERROR: cannot get points from mesh."); ASSERTL0(vtkPolys, "ERROR: cannot get polygons from mesh."); VertexSet points; VertexSet::iterator vIter; double p[3]; double val; double x, y, z; int coeff_idx; int i,j; // Build up an unordered set of vertices from the VTK file. For each // vertex a hashed value of the coordinates is generated to within a // given tolerance. for (i = 0; i < vtkPoints->GetNumberOfPoints(); ++i) { vtkPoints->GetPoint(i,p); val = vtkDataAtPoints->GetPointData()->GetScalars("Image_Intensity")->GetTuple1(i); boost::shared_ptr<Vertex> v(new Vertex(p[0],p[1],p[2],val,factor)); points.insert(v); } // Now process each vertex of each element in the mesh for (i = 0; i < Exp->GetNumElmts(); ++i) { StdRegions::StdExpansionSharedPtr e = Exp->GetExp(i); for (j = 0; j < e->GetNverts(); ++j) { // Get the index of the coefficient corresponding to this vertex coeff_idx = Exp->GetCoeff_Offset(i) + e->GetVertexMap(j); // Get the coordinates of the vertex SpatialDomains::VertexComponentSharedPtr vert = e->GetGeom2D()->GetVertex(j); vert->GetCoords(x,y,z); // Look up the vertex in the VertexSet boost::shared_ptr<Vertex> v(new Vertex(x,y,z,0.0,factor)); vIter = points.find(v); // If not found, maybe the tolerance should be reduced? // If found, record the scalar value from the VTK file in the // corresponding coefficient. if (vIter == points.end()) { cerr << "Vertex " << i << " not found." << x << ", " << y << ", " << z << endl; cerr << v->x << ", " << v->y << ", " << v->z << endl; } else { Exp->UpdateCoeffs()[coeff_idx] = (*vIter)->scalar; } } } Exp->SetPhysState(false); //----------------------------------------------- // Write solution to file string out(argv[3]); if (vSession->GetComm()->GetSize() > 1) { out += "." + boost::lexical_cast<string>(vSession->GetComm()->GetRank()); } std::vector<SpatialDomains::FieldDefinitionsSharedPtr> FieldDef = Exp->GetFieldDefinitions(); std::vector<std::vector<NekDouble> > FieldData(FieldDef.size()); for(i = 0; i < FieldDef.size(); ++i) { FieldDef[i]->m_fields.push_back("intensity"); Exp->AppendFieldData(FieldDef[i], FieldData[i]); } graph2D->Write(out, FieldDef, FieldData); //----------------------------------------------- } catch (...) { cout << "An error occurred." << endl; } } <|endoftext|>
<commit_before>/************************************************************************* * * * I|*j^3Cl|a "+!*% qt Nd gW * * l]{y+l?MM* !#Wla\NNP NW MM I| * * PW ?E| tWg Wg sC! AW ~@v~ * * NC ?M! yN| WW MK MW@K1Y%M@ RM #Q QP@tim * * CM| |WQCljAE| MD Mg RN cM~ NM WQ MQ * * #M aQ? MW M3 Mg Q( HQ YR IM| * * Dq {Ql MH iMX Mg MM QP QM Eg * * !EWNaPRag2$ +M" $WNaHaN% MQE$%EXW QQ CM %M%a$D * * * * Website: https://github.com/zpublic/zpublic * * * ************************************************************************/ /** * @file * @brief ע */ #pragma once #include "win_utils_header.h" #include <shlwapi.h> namespace zl { namespace WinUtils { /** * @brief ע, ,д,ɾ */ class ZLRegister { private: HKEY m_hKey; public: ZLRegister(); ZLRegister(ZLRegister& rhs); explicit ZLRegister(HKEY hKey); ~ZLRegister(); ZLRegister& operator=(ZLRegister& rhs); operator HKEY() const; public: /** * @brief ע * @see ˵μMSDNRegCreateKeyEx * @return ɹTRUE, ʧFALSE */ BOOL Create( HKEY hKey, LPCTSTR lpSubKey, REGSAM samDesired = KEY_READ | KEY_WRITE, LPTSTR lpClass = NULL, DWORD dwOptions = REG_OPTION_NON_VOLATILE, LPSECURITY_ATTRIBUTES lpSecAttr = NULL, LPDWORD lpdwDisposition = NULL); /** * @brief ע * @param[in] hKey * @param[in] lpSubKey ע· * @param[in] samDesired Ȩ * @param[in] bCreateIfNotExist עʱ, Ƿ񴴽 */ BOOL Open( HKEY hKey, LPCTSTR lpSubKey, REGSAM samDesired = KEY_READ | KEY_WRITE, BOOL bCreateIfNotExist = FALSE); public: // д BOOL SetBinaryValue(LPCTSTR lpValueName, const void* pValue, ULONG nBytes); BOOL SetDwordValue(LPCTSTR lpValueName, DWORD dwValue); BOOL SetQwordValue(LPCTSTR lpValueName, ULONGLONG qwValue); BOOL SetSzValue(LPCTSTR lpValueName, LPCTSTR lpValue); BOOL SetExpandSzValue(LPCTSTR lpValueName, LPCTSTR lpValue); BOOL SetMultiSzValue(LPCTSTR lpValueName, LPCTSTR lpValue); BOOL SetMultiSzValue(LPCTSTR lpValueName, const std::vector<CString> &vecValueLine); public: // BOOL GetBinaryValue(LPCTSTR pszValueName, void* pValue, ULONG* pnBytes); BOOL GetDwordValue(LPCTSTR lpValueName, DWORD& dwValue); BOOL GetQwordValue(LPCTSTR lpValueName, ULONGLONG& qwValue); BOOL GetStringValue(LPCTSTR lpValueName, CString& sValue); BOOL GetMultiSzValue(LPCTSTR lpValueName, LPTSTR lpValue, ULONG* pnChars); BOOL GetMultiSzValue(LPCTSTR lpValueName, std::vector<CString>& vecValues); public: // ɾ BOOL DelValue(LPCTSTR lpValueName); BOOL DelSubKey(LPCTSTR lpSubKey); static BOOL DelKey(HKEY hKey, LPCTSTR lpSubKey); public: void Attach(HKEY hKey); HKEY Detach(); void Close(); private: void ZLRegister::_ParseDNTString(LPCTSTR lpString, std::vector<CString>& vecResult) const; }; inline ZLRegister::ZLRegister() : m_hKey(NULL) {} inline ZLRegister::ZLRegister( ZLRegister& rhs ) { Attach(rhs.Detach()); } inline ZLRegister::ZLRegister( HKEY hKey ) : m_hKey(hKey) {} inline ZLRegister::~ZLRegister() { Close(); } inline void ZLRegister::Attach( HKEY hKey ) { m_hKey = hKey; } inline HKEY ZLRegister::Detach() { HKEY hKey = m_hKey; m_hKey = NULL; return hKey; } inline void ZLRegister::Close() { if (m_hKey != NULL) { ::RegCloseKey(m_hKey); m_hKey = NULL; } } inline ZLRegister& ZLRegister::operator=( ZLRegister& rhs ) { if(m_hKey!=rhs.m_hKey) { Close(); Attach( rhs.Detach() ); } return (*this); } inline ZLRegister::operator HKEY() const { return m_hKey; } inline BOOL ZLRegister::SetDwordValue( LPCTSTR lpValueName, DWORD dwValue ) { if (ERROR_SUCCESS == ::RegSetValueEx(m_hKey, lpValueName, NULL, REG_DWORD, reinterpret_cast<const BYTE*>(&dwValue), sizeof(DWORD))) { return TRUE; } return FALSE; } inline BOOL ZLRegister::SetQwordValue( LPCTSTR lpValueName, ULONGLONG qwValue ) { if (ERROR_SUCCESS == ::RegSetValueEx(m_hKey, lpValueName, NULL, REG_QWORD, reinterpret_cast<const BYTE*>(&qwValue), sizeof(ULONGLONG))) { return TRUE; } return FALSE; } inline BOOL ZLRegister::SetBinaryValue( LPCTSTR lpValueName, const void* pValue, ULONG nBytes ) { if (ERROR_SUCCESS == ::RegSetValueEx(m_hKey, lpValueName, NULL, REG_BINARY, reinterpret_cast<const BYTE*>(pValue), nBytes)) { return TRUE; } return FALSE; } inline BOOL ZLRegister::SetSzValue( LPCTSTR lpValueName, LPCTSTR lpValue ) { if (ERROR_SUCCESS == ::RegSetValueEx(m_hKey, lpValueName, NULL, REG_SZ, reinterpret_cast<const BYTE*>(lpValue), (lstrlen(lpValue)+1)*sizeof(TCHAR))) { return TRUE; } return FALSE; } inline BOOL ZLRegister::SetExpandSzValue( LPCTSTR lpValueName, LPCTSTR lpValue ) { if (ERROR_SUCCESS == ::RegSetValueEx(m_hKey, lpValueName, NULL, REG_EXPAND_SZ, reinterpret_cast<const BYTE*>(lpValue), (lstrlen(lpValue)+1)*sizeof(TCHAR))) { return TRUE; } return FALSE; } inline BOOL ZLRegister::SetMultiSzValue( LPCTSTR lpValueName, LPCTSTR lpValue ) { LPCTSTR pszTemp; ULONG nBytes; ULONG nLength; // ַС(bytes) nBytes = 0; pszTemp = lpValue; do { nLength = lstrlen(pszTemp)+1; pszTemp += nLength; nBytes += nLength * sizeof(TCHAR); } while (nLength != 1); if (ERROR_SUCCESS == ::RegSetValueEx(m_hKey, lpValueName, NULL, REG_MULTI_SZ, reinterpret_cast<const BYTE*>(lpValue), nBytes)) { return TRUE; } return FALSE; } inline BOOL ZLRegister::SetMultiSzValue( LPCTSTR lpValueName, const std::vector<CString> &vecValueLine ) { std::wstring sValue; for (size_t i=0; i<vecValueLine.size(); ++i) { sValue += vecValueLine[i]; sValue.push_back(0); } sValue.push_back(0); sValue.push_back(0); return SetMultiSzValue(lpValueName, sValue.c_str()); } inline BOOL ZLRegister::GetBinaryValue(LPCTSTR lpValueName, void* pValue, ULONG* pnBytes) { DWORD dwType = REG_NONE; LONG lRes = ::RegQueryValueEx(m_hKey, lpValueName, NULL, &dwType, reinterpret_cast<LPBYTE>(pValue), pnBytes); if (lRes != ERROR_SUCCESS) return FALSE; if (dwType != REG_BINARY) return FALSE; return TRUE; } inline BOOL ZLRegister::GetDwordValue( LPCTSTR lpValueName, DWORD& dwValue ) { DWORD dwType = REG_NONE; ULONG nBytes = sizeof(DWORD); LONG lRet = ::RegQueryValueEx(m_hKey, lpValueName, NULL, &dwType, reinterpret_cast<LPBYTE>(&dwValue), &nBytes); if ((ERROR_SUCCESS==lRet) && (REG_DWORD==dwType)) { return TRUE; } return FALSE; } inline BOOL ZLRegister::GetQwordValue( LPCTSTR lpValueName, ULONGLONG& qwValue ) { DWORD dwType; ULONG nBytes = sizeof(ULONGLONG); LONG lRet = ::RegQueryValueEx(m_hKey, lpValueName, NULL, &dwType, reinterpret_cast<LPBYTE>(&qwValue), &nBytes); if ((ERROR_SUCCESS==lRet) && (REG_QWORD==dwType)) { return TRUE; } return FALSE; } inline BOOL ZLRegister::GetStringValue( LPCTSTR lpValueName, CString& sValue ) { BOOL bReturn = FALSE; LPTSTR lpValueBuf = NULL; // ȡֵͺʹС DWORD dwType = REG_NONE; ULONG ulBytes = 0; ULONG lRet = ::RegQueryValueEx(m_hKey, lpValueName, NULL, &dwType, NULL, &ulBytes); if (ERROR_SUCCESS != lRet) goto Exit0; if ((REG_SZ!=dwType) && (REG_EXPAND_SZ!=dwType)) goto Exit0; if (NULL == (lpValueBuf = (LPTSTR)malloc(ulBytes))) goto Exit0; // ȡֵ memset(lpValueBuf, 0, ulBytes); lRet = ::RegQueryValueEx(m_hKey, lpValueName, NULL, &dwType, reinterpret_cast<LPBYTE>(lpValueBuf), &ulBytes); if (ERROR_SUCCESS != lRet) goto Exit0; sValue = lpValueBuf; bReturn = TRUE; Exit0: if (lpValueBuf) free(lpValueBuf); return bReturn; } inline BOOL ZLRegister::GetMultiSzValue(LPCTSTR lpValueName, LPTSTR lpValue, ULONG* pnChars) { DWORD dwType; ULONG nBytes; if (lpValue != NULL && *pnChars < 2) return FALSE; nBytes = (*pnChars)*sizeof(TCHAR); *pnChars = 0; LONG lRes = ::RegQueryValueEx(m_hKey, lpValueName, NULL, &dwType, reinterpret_cast<LPBYTE>(lpValue), &nBytes); if (lRes != ERROR_SUCCESS) return FALSE; if (dwType != REG_MULTI_SZ) return FALSE; if (lpValue != NULL && (nBytes % sizeof(TCHAR) != 0 || nBytes / sizeof(TCHAR) < 1 || lpValue[nBytes / sizeof(TCHAR) -1] != 0 || ((nBytes/sizeof(TCHAR))>1 && lpValue[nBytes / sizeof(TCHAR) - 2] != 0))) return FALSE; *pnChars = nBytes/sizeof(TCHAR); return TRUE; } inline BOOL ZLRegister::GetMultiSzValue( LPCTSTR lpValueName, std::vector<CString>& vecValues ) { BOOL bReturn = FALSE; ULONG ulChars = 0; if (GetMultiSzValue(lpValueName, NULL, &ulChars)) // ȡС { TCHAR* pValue = new TCHAR[ulChars]; bReturn = GetMultiSzValue(lpValueName, pValue, &ulChars); _ParseDNTString(pValue, vecValues); } return bReturn; } inline BOOL ZLRegister::Create( HKEY hKey, LPCTSTR lpSubKey, REGSAM samDesired, LPTSTR lpClass, DWORD dwOptions, LPSECURITY_ATTRIBUTES lpSecAttr, LPDWORD lpdwDisposition) { HKEY hKeyResult = NULL; DWORD dwDisposition = 0; LONG lRet = RegCreateKeyEx(hKey, lpSubKey, 0, lpClass, dwOptions, samDesired, lpSecAttr, &hKeyResult, &dwDisposition); if (lpdwDisposition != NULL) *lpdwDisposition = dwDisposition; if (lRet == ERROR_SUCCESS) { Close(); m_hKey = hKeyResult; return TRUE; } return FALSE; } inline BOOL ZLRegister::Open( HKEY hKey, LPCTSTR lpSubKey, REGSAM samDesired, BOOL bCreateIfNotExist) { BOOL bReturn = FALSE; HKEY hKeyResult = NULL; LONG lRet = RegOpenKeyEx(hKey, lpSubKey, 0, samDesired, &hKeyResult); if (lRet == ERROR_SUCCESS) { Close(); m_hKey = hKeyResult; bReturn = TRUE; } else if (bCreateIfNotExist) { bReturn = Create(hKey, lpSubKey, samDesired); } return bReturn; } inline BOOL ZLRegister::DelSubKey( LPCTSTR lpSubKey ) { if (ERROR_SUCCESS == ::SHDeleteKey(m_hKey, lpSubKey)) return TRUE; return FALSE; } inline BOOL ZLRegister::DelValue( LPCTSTR lpValueName ) { if (ERROR_SUCCESS == ::RegDeleteValue(m_hKey, lpValueName)) return TRUE; return FALSE; } inline BOOL ZLRegister::DelKey( HKEY hKey, LPCTSTR lpSubKey ) { if (ERROR_SUCCESS == ::SHDeleteKey(hKey, lpSubKey)) return TRUE; return FALSE; } // Parse a "double null terminated string" to std::vector inline void ZLRegister::_ParseDNTString(LPCTSTR lpString, std::vector<CString>& vecResult) const { vecResult.clear(); if (NULL == lpString) return; LPCTSTR psTemp = lpString; DWORD dwLen = (DWORD)_tcslen(psTemp); while (dwLen > 0) { vecResult.push_back(psTemp); psTemp = &psTemp[dwLen + 1]; dwLen = (DWORD)_tcslen(psTemp); } } } }<commit_msg>* z_win_utils 修改一处内存泄漏BUG<commit_after>/************************************************************************* * * * I|*j^3Cl|a "+!*% qt Nd gW * * l]{y+l?MM* !#Wla\NNP NW MM I| * * PW ?E| tWg Wg sC! AW ~@v~ * * NC ?M! yN| WW MK MW@K1Y%M@ RM #Q QP@tim * * CM| |WQCljAE| MD Mg RN cM~ NM WQ MQ * * #M aQ? MW M3 Mg Q( HQ YR IM| * * Dq {Ql MH iMX Mg MM QP QM Eg * * !EWNaPRag2$ +M" $WNaHaN% MQE$%EXW QQ CM %M%a$D * * * * Website: https://github.com/zpublic/zpublic * * * ************************************************************************/ /** * @file * @brief ע */ #pragma once #include "win_utils_header.h" #include <shlwapi.h> namespace zl { namespace WinUtils { /** * @brief ע, ,д,ɾ */ class ZLRegister { private: HKEY m_hKey; public: ZLRegister(); ZLRegister(ZLRegister& rhs); explicit ZLRegister(HKEY hKey); ~ZLRegister(); ZLRegister& operator=(ZLRegister& rhs); operator HKEY() const; public: /** * @brief ע * @see ˵μMSDNRegCreateKeyEx * @return ɹTRUE, ʧFALSE */ BOOL Create( HKEY hKey, LPCTSTR lpSubKey, REGSAM samDesired = KEY_READ | KEY_WRITE, LPTSTR lpClass = NULL, DWORD dwOptions = REG_OPTION_NON_VOLATILE, LPSECURITY_ATTRIBUTES lpSecAttr = NULL, LPDWORD lpdwDisposition = NULL); /** * @brief ע * @param[in] hKey * @param[in] lpSubKey ע· * @param[in] samDesired Ȩ * @param[in] bCreateIfNotExist עʱ, Ƿ񴴽 */ BOOL Open( HKEY hKey, LPCTSTR lpSubKey, REGSAM samDesired = KEY_READ | KEY_WRITE, BOOL bCreateIfNotExist = FALSE); public: // д BOOL SetBinaryValue(LPCTSTR lpValueName, const void* pValue, ULONG nBytes); BOOL SetDwordValue(LPCTSTR lpValueName, DWORD dwValue); BOOL SetQwordValue(LPCTSTR lpValueName, ULONGLONG qwValue); BOOL SetSzValue(LPCTSTR lpValueName, LPCTSTR lpValue); BOOL SetExpandSzValue(LPCTSTR lpValueName, LPCTSTR lpValue); BOOL SetMultiSzValue(LPCTSTR lpValueName, LPCTSTR lpValue); BOOL SetMultiSzValue(LPCTSTR lpValueName, const std::vector<CString> &vecValueLine); public: // BOOL GetBinaryValue(LPCTSTR pszValueName, void* pValue, ULONG* pnBytes); BOOL GetDwordValue(LPCTSTR lpValueName, DWORD& dwValue); BOOL GetQwordValue(LPCTSTR lpValueName, ULONGLONG& qwValue); BOOL GetStringValue(LPCTSTR lpValueName, CString& sValue); BOOL GetMultiSzValue(LPCTSTR lpValueName, LPTSTR lpValue, ULONG* pnChars); BOOL GetMultiSzValue(LPCTSTR lpValueName, std::vector<CString>& vecValues); public: // ɾ BOOL DelValue(LPCTSTR lpValueName); BOOL DelSubKey(LPCTSTR lpSubKey); static BOOL DelKey(HKEY hKey, LPCTSTR lpSubKey); public: void Attach(HKEY hKey); HKEY Detach(); void Close(); private: void ZLRegister::_ParseDNTString(LPCTSTR lpString, std::vector<CString>& vecResult) const; }; inline ZLRegister::ZLRegister() : m_hKey(NULL) {} inline ZLRegister::ZLRegister( ZLRegister& rhs ) { Attach(rhs.Detach()); } inline ZLRegister::ZLRegister( HKEY hKey ) : m_hKey(hKey) {} inline ZLRegister::~ZLRegister() { Close(); } inline void ZLRegister::Attach( HKEY hKey ) { m_hKey = hKey; } inline HKEY ZLRegister::Detach() { HKEY hKey = m_hKey; m_hKey = NULL; return hKey; } inline void ZLRegister::Close() { if (m_hKey != NULL) { ::RegCloseKey(m_hKey); m_hKey = NULL; } } inline ZLRegister& ZLRegister::operator=( ZLRegister& rhs ) { if(m_hKey!=rhs.m_hKey) { Close(); Attach( rhs.Detach() ); } return (*this); } inline ZLRegister::operator HKEY() const { return m_hKey; } inline BOOL ZLRegister::SetDwordValue( LPCTSTR lpValueName, DWORD dwValue ) { if (ERROR_SUCCESS == ::RegSetValueEx(m_hKey, lpValueName, NULL, REG_DWORD, reinterpret_cast<const BYTE*>(&dwValue), sizeof(DWORD))) { return TRUE; } return FALSE; } inline BOOL ZLRegister::SetQwordValue( LPCTSTR lpValueName, ULONGLONG qwValue ) { if (ERROR_SUCCESS == ::RegSetValueEx(m_hKey, lpValueName, NULL, REG_QWORD, reinterpret_cast<const BYTE*>(&qwValue), sizeof(ULONGLONG))) { return TRUE; } return FALSE; } inline BOOL ZLRegister::SetBinaryValue( LPCTSTR lpValueName, const void* pValue, ULONG nBytes ) { if (ERROR_SUCCESS == ::RegSetValueEx(m_hKey, lpValueName, NULL, REG_BINARY, reinterpret_cast<const BYTE*>(pValue), nBytes)) { return TRUE; } return FALSE; } inline BOOL ZLRegister::SetSzValue( LPCTSTR lpValueName, LPCTSTR lpValue ) { if (ERROR_SUCCESS == ::RegSetValueEx(m_hKey, lpValueName, NULL, REG_SZ, reinterpret_cast<const BYTE*>(lpValue), (lstrlen(lpValue)+1)*sizeof(TCHAR))) { return TRUE; } return FALSE; } inline BOOL ZLRegister::SetExpandSzValue( LPCTSTR lpValueName, LPCTSTR lpValue ) { if (ERROR_SUCCESS == ::RegSetValueEx(m_hKey, lpValueName, NULL, REG_EXPAND_SZ, reinterpret_cast<const BYTE*>(lpValue), (lstrlen(lpValue)+1)*sizeof(TCHAR))) { return TRUE; } return FALSE; } inline BOOL ZLRegister::SetMultiSzValue( LPCTSTR lpValueName, LPCTSTR lpValue ) { LPCTSTR pszTemp; ULONG nBytes; ULONG nLength; // ַС(bytes) nBytes = 0; pszTemp = lpValue; do { nLength = lstrlen(pszTemp)+1; pszTemp += nLength; nBytes += nLength * sizeof(TCHAR); } while (nLength != 1); if (ERROR_SUCCESS == ::RegSetValueEx(m_hKey, lpValueName, NULL, REG_MULTI_SZ, reinterpret_cast<const BYTE*>(lpValue), nBytes)) { return TRUE; } return FALSE; } inline BOOL ZLRegister::SetMultiSzValue( LPCTSTR lpValueName, const std::vector<CString> &vecValueLine ) { std::wstring sValue; for (size_t i=0; i<vecValueLine.size(); ++i) { sValue += vecValueLine[i]; sValue.push_back(0); } sValue.push_back(0); sValue.push_back(0); return SetMultiSzValue(lpValueName, sValue.c_str()); } inline BOOL ZLRegister::GetBinaryValue(LPCTSTR lpValueName, void* pValue, ULONG* pnBytes) { DWORD dwType = REG_NONE; LONG lRes = ::RegQueryValueEx(m_hKey, lpValueName, NULL, &dwType, reinterpret_cast<LPBYTE>(pValue), pnBytes); if (lRes != ERROR_SUCCESS) return FALSE; if (dwType != REG_BINARY) return FALSE; return TRUE; } inline BOOL ZLRegister::GetDwordValue( LPCTSTR lpValueName, DWORD& dwValue ) { DWORD dwType = REG_NONE; ULONG nBytes = sizeof(DWORD); LONG lRet = ::RegQueryValueEx(m_hKey, lpValueName, NULL, &dwType, reinterpret_cast<LPBYTE>(&dwValue), &nBytes); if ((ERROR_SUCCESS==lRet) && (REG_DWORD==dwType)) { return TRUE; } return FALSE; } inline BOOL ZLRegister::GetQwordValue( LPCTSTR lpValueName, ULONGLONG& qwValue ) { DWORD dwType; ULONG nBytes = sizeof(ULONGLONG); LONG lRet = ::RegQueryValueEx(m_hKey, lpValueName, NULL, &dwType, reinterpret_cast<LPBYTE>(&qwValue), &nBytes); if ((ERROR_SUCCESS==lRet) && (REG_QWORD==dwType)) { return TRUE; } return FALSE; } inline BOOL ZLRegister::GetStringValue( LPCTSTR lpValueName, CString& sValue ) { BOOL bReturn = FALSE; LPTSTR lpValueBuf = NULL; // ȡֵͺʹС DWORD dwType = REG_NONE; ULONG ulBytes = 0; ULONG lRet = ::RegQueryValueEx(m_hKey, lpValueName, NULL, &dwType, NULL, &ulBytes); if (ERROR_SUCCESS != lRet) goto Exit0; if ((REG_SZ!=dwType) && (REG_EXPAND_SZ!=dwType)) goto Exit0; if (NULL == (lpValueBuf = (LPTSTR)malloc(ulBytes))) goto Exit0; // ȡֵ memset(lpValueBuf, 0, ulBytes); lRet = ::RegQueryValueEx(m_hKey, lpValueName, NULL, &dwType, reinterpret_cast<LPBYTE>(lpValueBuf), &ulBytes); if (ERROR_SUCCESS != lRet) goto Exit0; sValue = lpValueBuf; bReturn = TRUE; Exit0: if (lpValueBuf) free(lpValueBuf); return bReturn; } inline BOOL ZLRegister::GetMultiSzValue(LPCTSTR lpValueName, LPTSTR lpValue, ULONG* pnChars) { DWORD dwType; ULONG nBytes; if (lpValue != NULL && *pnChars < 2) return FALSE; nBytes = (*pnChars)*sizeof(TCHAR); *pnChars = 0; LONG lRes = ::RegQueryValueEx(m_hKey, lpValueName, NULL, &dwType, reinterpret_cast<LPBYTE>(lpValue), &nBytes); if (lRes != ERROR_SUCCESS) return FALSE; if (dwType != REG_MULTI_SZ) return FALSE; if (lpValue != NULL && (nBytes % sizeof(TCHAR) != 0 || nBytes / sizeof(TCHAR) < 1 || lpValue[nBytes / sizeof(TCHAR) -1] != 0 || ((nBytes/sizeof(TCHAR))>1 && lpValue[nBytes / sizeof(TCHAR) - 2] != 0))) return FALSE; *pnChars = nBytes/sizeof(TCHAR); return TRUE; } inline BOOL ZLRegister::GetMultiSzValue( LPCTSTR lpValueName, std::vector<CString>& vecValues ) { BOOL bReturn = FALSE; ULONG ulChars = 0; if (GetMultiSzValue(lpValueName, NULL, &ulChars)) // ȡС { TCHAR* pValue = new TCHAR[ulChars]; bReturn = GetMultiSzValue(lpValueName, pValue, &ulChars); _ParseDNTString(pValue, vecValues); delete pValue; } return bReturn; } inline BOOL ZLRegister::Create( HKEY hKey, LPCTSTR lpSubKey, REGSAM samDesired, LPTSTR lpClass, DWORD dwOptions, LPSECURITY_ATTRIBUTES lpSecAttr, LPDWORD lpdwDisposition) { HKEY hKeyResult = NULL; DWORD dwDisposition = 0; LONG lRet = RegCreateKeyEx(hKey, lpSubKey, 0, lpClass, dwOptions, samDesired, lpSecAttr, &hKeyResult, &dwDisposition); if (lpdwDisposition != NULL) *lpdwDisposition = dwDisposition; if (lRet == ERROR_SUCCESS) { Close(); m_hKey = hKeyResult; return TRUE; } return FALSE; } inline BOOL ZLRegister::Open( HKEY hKey, LPCTSTR lpSubKey, REGSAM samDesired, BOOL bCreateIfNotExist) { BOOL bReturn = FALSE; HKEY hKeyResult = NULL; LONG lRet = RegOpenKeyEx(hKey, lpSubKey, 0, samDesired, &hKeyResult); if (lRet == ERROR_SUCCESS) { Close(); m_hKey = hKeyResult; bReturn = TRUE; } else if (bCreateIfNotExist) { bReturn = Create(hKey, lpSubKey, samDesired); } return bReturn; } inline BOOL ZLRegister::DelSubKey( LPCTSTR lpSubKey ) { if (ERROR_SUCCESS == ::SHDeleteKey(m_hKey, lpSubKey)) return TRUE; return FALSE; } inline BOOL ZLRegister::DelValue( LPCTSTR lpValueName ) { if (ERROR_SUCCESS == ::RegDeleteValue(m_hKey, lpValueName)) return TRUE; return FALSE; } inline BOOL ZLRegister::DelKey( HKEY hKey, LPCTSTR lpSubKey ) { if (ERROR_SUCCESS == ::SHDeleteKey(hKey, lpSubKey)) return TRUE; return FALSE; } // Parse a "double null terminated string" to std::vector inline void ZLRegister::_ParseDNTString(LPCTSTR lpString, std::vector<CString>& vecResult) const { vecResult.clear(); if (NULL == lpString) return; LPCTSTR psTemp = lpString; DWORD dwLen = (DWORD)_tcslen(psTemp); while (dwLen > 0) { vecResult.push_back(psTemp); psTemp = &psTemp[dwLen + 1]; dwLen = (DWORD)_tcslen(psTemp); } } } }<|endoftext|>
<commit_before>// @(#)root/alien:$Name: $:$Id: TAlienFile.cxx,v 1.13 2005/10/27 10:00:41 rdm Exp $ // Author: Andreas Peters 11/09/2003 /************************************************************************* * Copyright (C) 1995-2003, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ ////////////////////////////////////////////////////////////////////////// // // // TAlienFile // // // // A TAlienFile is like a normal TFile except that it reads and writes // // its data via an AliEn service. // // Filenames are standard URL format with protocol "alien". // // The following are valid TAlienFile URL's: // // // // alien:///alice/cern.ch/user/p/peters/test.root // // alien://alien.cern.ch/alice/cern.ch/user/p/peters/test.root // // // ////////////////////////////////////////////////////////////////////////// #include "TAlienFile.h" #include "TAlienResult.h" #include "TAlien.h" #include "TROOT.h" #include "TObjString.h" #include "TMap.h" #include "TObjArray.h" #include "TString.h" #include "Rtypes.h" #include "TSystem.h" #include "TVirtualMutex.h" #include "TProcessUUID.h" #include "TArchiveFile.h" ClassImp(TAlienFile) //______________________________________________________________________________ TAlienFile::TAlienFile(const char *url, Option_t *option, const char *ftitle, Int_t compress) : fUrl(url) { // Create an Alien File Object. An AliEn File is the same as a TFile // except that it is being accessed via an Alien service. The url // argument must be of the form: alien:/[machine]/path/file.root // Using the option access, another access protocol (PFN) can be // specified for an LFN e.g.: // "alien:///alice/test.root" // If you want to write a file on specific storage element use the syntax // "alien:///alice/test.root?&se=Alice::CERN::Storage" // The default SE is specified by the enviroment variable alien_CLOSE_SE // // The URL option "?locate=1" can be appended to a URL to use the TAlienFile // interface to locate a file which is accessed by a logical file name. // The file name is replaced by an TURL containing the file catalogue // authorization envelope. This can be used f.e. to get file access authorization // through a client to be used on a PROOF cluster reading data from // authorization-envelope enabled xrootd servers. The "locate" option // enforces only the retrieval of the access envelope but does not // create a physical connection to an xrootd server. // // If the file specified in the URL does not exist, is not accessable // or can not be created the kZombie bit will be set in the TAlienFile // object. Use IsZombie() to see if the file is accessable. // For a description of the option and other arguments see the TFile ctor. // The preferred interface to this constructor is via TFile::Open(). TUrl lUrl(url); TString name(TString("alien://")+TString(lUrl.GetFile())); SetName(name); TFile::TFile(name, "NET", ftitle, compress); fOption = option; TString newurl = AccessURL(lUrl.GetUrl(), fOption, ftitle, compress); Bool_t lLocate = kFALSE; // get the options and check if this is just to prelocate the file .... TString urloptions=lUrl.GetOptions(); TObjArray *objOptions = urloptions.Tokenize("&"); for (Int_t n = 0; n < objOptions->GetEntries(); n++) { TString loption = ((TObjString*)objOptions->At(n))->GetName(); TObjArray *objTags = loption.Tokenize("="); if (objTags->GetEntries() == 2) { TString key = ((TObjString*)objTags->At(0))->GetName(); TString value = ((TObjString*)objTags->At(1))->GetName(); if ( (key == "locate") && (value == "1") ) { lLocate=kTRUE; } } delete objTags; } delete objOptions; if (lLocate) { SetName(newurl); return; } TUrl nUrl(newurl.Data()); TString oldopt; TString newopt; if (newurl == "") goto zombie; oldopt = lUrl.GetOptions(); newopt = nUrl.GetOptions(); // add the original options from the alien URL nUrl.SetOptions(newopt + TString("&") + oldopt + TString("&")); fSubFile = TFile::Open(nUrl.GetUrl(), fOption, ftitle, compress); if ((!fSubFile) || (fSubFile->IsZombie())) { Error("TAlienFile", "cannot open %s!", url); goto zombie; } // gFile would point now to fSubFile, but we don't want that gFile=this; return; zombie: // error in file opening occured, make this object a zombie MakeZombie(); gDirectory = gROOT; return; } //______________________________________________________________________________ TString TAlienFile::AccessURL(const char *url, Option_t *option, const char *, Int_t) { TString stmp; Bool_t create; Bool_t recreate; Bool_t update; Bool_t read; TUrl purl(url); // find out the storage element and the lfn from the given url TString storageelement=""; TString file = purl.GetFile(); Bool_t publicaccess=kFALSE; storageelement = gSystem->Getenv("alien_CLOSE_SE"); // get the options and set the storage element TString urloptions=purl.GetOptions(); TObjArray *objOptions = urloptions.Tokenize("&"); for (Int_t n = 0; n < objOptions->GetEntries(); n++) { TString loption = ((TObjString*)objOptions->At(n))->GetName(); TObjArray *objTags = loption.Tokenize("="); if (objTags->GetEntries() == 2) { TString key = ((TObjString*)objTags->At(0))->GetName(); TString value = ((TObjString*)objTags->At(1))->GetName(); if ( (key == "se") || (key == "SE") || (key == "Se") ) { storageelement = value; } if ((key == "publicaccess") || (key == "PublicAccess") || (key == "PUBLICACCESS")) { if (atoi( value.Data())) publicaccess = kTRUE; } } delete objTags; } delete objOptions; fOption = option; fOption.ToUpper(); fSubFile = 0; TObjString* urlStr=0; TObjString* authzStr=0; TString command; TIterator* iter = 0; TObject* object = 0; TGridResult* result; TAlienResult* alienResult; TList* list; TString newurl; if (fOption == "NEW") fOption = "CREATE"; create = (fOption == "CREATE") ? kTRUE : kFALSE; recreate = (fOption == "RECREATE") ? kTRUE : kFALSE; update = (fOption == "UPDATE") ? kTRUE : kFALSE; read = (fOption == "READ") ? kTRUE : kFALSE; if (!create && !recreate && !update && !read) { read = kTRUE; fOption = "READ"; } if (create || recreate || update) { fWritable=kTRUE; } if (recreate) { fOption = "CREATE"; create = kTRUE; } ///////////////////////////////////////////////////////////////////////////////////////// // first get an active Grid connection if (!gGrid) { // no TAlien existing .... Error("TAlienFile", "no active GRID connection found"); goto zombie2; } else { if ((strcmp(gGrid->GetGrid(), "alien"))) { Error("TAlienFile", "you don't have an active <alien> grid!"); goto zombie2; } } ///////////////////////////////////////////////////////////////////////////////////////// // get the authorization from the catalogue if (read) { // get the read access if (publicaccess) command = TString("access -p read "); else command = TString("access read "); } if (create) { command = TString("access write-once "); } if (recreate) { command = TString("access write-version "); } if (update) { command = TString("access write-version "); } command += file; if (fWritable) { // append the storage element environment variable command += " "; command += storageelement; } fLfn = file; result = gGrid->Command(command.Data(),kFALSE,TAlien::kOUTPUT); alienResult = dynamic_cast<TAlienResult*>(result); list = dynamic_cast<TList*>(alienResult); if (!list) { if (result) { delete result; } Error("TAlienFile", "cannot get the access envelope for %s",purl.GetUrl()); goto zombie2; } iter = list->MakeIterator(); object = 0; while ((object = iter->Next()) != 0) { TMap* map = dynamic_cast<TMap*>(object); TObject* urlObject = map->GetValue("url"); urlStr = dynamic_cast<TObjString*>(urlObject); TObject* authzObject = map->GetValue("envelope"); authzStr = dynamic_cast<TObjString*>(authzObject); // there is only one result line .... in case it is at all .... break; } if ((!urlStr) || (!authzStr)) { if (fWritable) { Error("TAlienFile", "didn't get the authorization to write %s",purl.GetUrl()); } else { Error("TAlienFile", "didn't get the authorization to read %s",purl.GetUrl()); } Info("TAlienFile","Command::Stdout !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!"); gGrid->Stdout(); Info("TAlienFile","Command::Stderr !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!"); gGrid->Stderr(); Info("TAlienFile","End of Output !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!"); delete iter; delete result; goto zombie2; } delete iter; delete result; fAuthz = authzStr->GetName(); newurl = urlStr->GetName(); stmp = purl.GetAnchor(); if (stmp != "") { newurl += "#"; newurl += purl.GetAnchor(); } newurl += TString("?&authz="); newurl += authzStr->GetName(); return newurl; zombie2: // error in file opening occured, make this object a zombie return ""; } //______________________________________________________________________________ TAlienFile::~TAlienFile() { // TAlienFile file dtor. if (fSubFile) { Close(); delete fSubFile; } fSubFile = 0; gFile = 0; gDirectory = gROOT; if (gDebug) Info("~TAlienFile", "dtor called for %s", GetName()); } //______________________________________________________________________________ Bool_t TAlienFile::ReadBuffer(char *buf, Int_t len) { // Read specified byte range. // Returns kTRUE in case of error. if (fSubFile) return fSubFile->ReadBuffer(buf, len); return kTRUE; } //______________________________________________________________________________ Bool_t TAlienFile::WriteBuffer(const char *buf, Int_t len) { // Write specified byte range // Returns kTRUE in case of error. if (fSubFile) return fSubFile->WriteBuffer(buf, len); return kTRUE; } //______________________________________________________________________________ void TAlienFile::Seek(Long64_t offset, ERelativeTo pos) { // Seek into file. if (fSubFile) { fSubFile->Seek(offset, pos); } } //______________________________________________________________________________ void TAlienFile::Close(Option_t *option) { // Close file. // set GCLIENT_EXTRA_ARG environment gSystem->Setenv("GCLIENT_EXTRA_ARG",fAuthz.Data()); // commit the envelope TString command("commit "); command += (Long_t)fSubFile->GetSize(); command += " "; command += fLfn; if (fSubFile) { fSubFile->Close(option); } TGridResult* result = gGrid->Command(command, kFALSE,TAlien::kOUTPUT); TAlienResult* alienResult = dynamic_cast<TAlienResult*>(result); TList* list = dynamic_cast<TList*>(alienResult); if (!list) { if (result) { delete result; } Error("Close", "cannot commit envelope for %s", fLfn.Data()); } TIterator* iter = list->MakeIterator(); TObject* object = 0; if (fWritable) { while ((object = iter->Next()) != 0) { TMap* map = dynamic_cast<TMap*>(object); TObject* commitObject = map->GetValue(fLfn.Data()); if (commitObject) { TObjString* commitStr = dynamic_cast<TObjString*>(commitObject); if (!(strcmp(commitStr->GetName(),"1"))) { // the file has been committed break; } } Error("Close", "cannot register %s!", fLfn.Data()); // there is only one result line .... in case it is at all .... break; } delete iter; delete result; } gSystem->Unsetenv("GCLIENT_EXTRA_ARG"); } <commit_msg>From Andreas: performance improvement when closing read-only files.<commit_after>// @(#)root/alien:$Name: $:$Id: TAlienFile.cxx,v 1.14 2005/12/09 16:24:34 rdm Exp $ // Author: Andreas Peters 11/09/2003 /************************************************************************* * Copyright (C) 1995-2003, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ ////////////////////////////////////////////////////////////////////////// // // // TAlienFile // // // // A TAlienFile is like a normal TFile except that it reads and writes // // its data via an AliEn service. // // Filenames are standard URL format with protocol "alien". // // The following are valid TAlienFile URL's: // // // // alien:///alice/cern.ch/user/p/peters/test.root // // alien://alien.cern.ch/alice/cern.ch/user/p/peters/test.root // // // ////////////////////////////////////////////////////////////////////////// #include "TAlienFile.h" #include "TAlienResult.h" #include "TAlien.h" #include "TROOT.h" #include "TObjString.h" #include "TMap.h" #include "TObjArray.h" #include "TString.h" #include "Rtypes.h" #include "TSystem.h" #include "TVirtualMutex.h" #include "TProcessUUID.h" #include "TArchiveFile.h" ClassImp(TAlienFile) //______________________________________________________________________________ TAlienFile::TAlienFile(const char *url, Option_t *option, const char *ftitle, Int_t compress) : fUrl(url) { // Create an Alien File Object. An AliEn File is the same as a TFile // except that it is being accessed via an Alien service. The url // argument must be of the form: alien:/[machine]/path/file.root // Using the option access, another access protocol (PFN) can be // specified for an LFN e.g.: // "alien:///alice/test.root" // If you want to write a file on specific storage element use the syntax // "alien:///alice/test.root?&se=Alice::CERN::Storage" // The default SE is specified by the enviroment variable alien_CLOSE_SE // // The URL option "?locate=1" can be appended to a URL to use the TAlienFile // interface to locate a file which is accessed by a logical file name. // The file name is replaced by an TURL containing the file catalogue // authorization envelope. This can be used f.e. to get file access authorization // through a client to be used on a PROOF cluster reading data from // authorization-envelope enabled xrootd servers. The "locate" option // enforces only the retrieval of the access envelope but does not // create a physical connection to an xrootd server. // // If the file specified in the URL does not exist, is not accessable // or can not be created the kZombie bit will be set in the TAlienFile // object. Use IsZombie() to see if the file is accessable. // For a description of the option and other arguments see the TFile ctor. // The preferred interface to this constructor is via TFile::Open(). TUrl lUrl(url); TString name(TString("alien://")+TString(lUrl.GetFile())); SetName(name); TFile::TFile(name, "NET", ftitle, compress); fOption = option; TString newurl = AccessURL(lUrl.GetUrl(), fOption, ftitle, compress); Bool_t lLocate = kFALSE; // get the options and check if this is just to prelocate the file .... TString urloptions=lUrl.GetOptions(); TObjArray *objOptions = urloptions.Tokenize("&"); for (Int_t n = 0; n < objOptions->GetEntries(); n++) { TString loption = ((TObjString*)objOptions->At(n))->GetName(); TObjArray *objTags = loption.Tokenize("="); if (objTags->GetEntries() == 2) { TString key = ((TObjString*)objTags->At(0))->GetName(); TString value = ((TObjString*)objTags->At(1))->GetName(); if ( (key == "locate") && (value == "1") ) { lLocate=kTRUE; } } delete objTags; } delete objOptions; if (lLocate) { SetName(newurl); return; } TUrl nUrl(newurl.Data()); TString oldopt; TString newopt; if (newurl == "") goto zombie; oldopt = lUrl.GetOptions(); newopt = nUrl.GetOptions(); // add the original options from the alien URL nUrl.SetOptions(newopt + TString("&") + oldopt + TString("&")); fSubFile = TFile::Open(nUrl.GetUrl(), fOption, ftitle, compress); if ((!fSubFile) || (fSubFile->IsZombie())) { Error("TAlienFile", "cannot open %s!", url); goto zombie; } // gFile would point now to fSubFile, but we don't want that gFile=this; return; zombie: // error in file opening occured, make this object a zombie MakeZombie(); gDirectory = gROOT; return; } //______________________________________________________________________________ TString TAlienFile::AccessURL(const char *url, Option_t *option, const char *, Int_t) { TString stmp; Bool_t create; Bool_t recreate; Bool_t update; Bool_t read; TUrl purl(url); // find out the storage element and the lfn from the given url TString storageelement=""; TString file = purl.GetFile(); Bool_t publicaccess=kFALSE; storageelement = gSystem->Getenv("alien_CLOSE_SE"); // get the options and set the storage element TString urloptions=purl.GetOptions(); TObjArray *objOptions = urloptions.Tokenize("&"); for (Int_t n = 0; n < objOptions->GetEntries(); n++) { TString loption = ((TObjString*)objOptions->At(n))->GetName(); TObjArray *objTags = loption.Tokenize("="); if (objTags->GetEntries() == 2) { TString key = ((TObjString*)objTags->At(0))->GetName(); TString value = ((TObjString*)objTags->At(1))->GetName(); if ( (key == "se") || (key == "SE") || (key == "Se") ) { storageelement = value; } if ((key == "publicaccess") || (key == "PublicAccess") || (key == "PUBLICACCESS")) { if (atoi( value.Data())) publicaccess = kTRUE; } } delete objTags; } delete objOptions; fOption = option; fOption.ToUpper(); fSubFile = 0; TObjString* urlStr=0; TObjString* authzStr=0; TString command; TIterator* iter = 0; TObject* object = 0; TGridResult* result; TAlienResult* alienResult; TList* list; TString newurl; if (fOption == "NEW") fOption = "CREATE"; create = (fOption == "CREATE") ? kTRUE : kFALSE; recreate = (fOption == "RECREATE") ? kTRUE : kFALSE; update = (fOption == "UPDATE") ? kTRUE : kFALSE; read = (fOption == "READ") ? kTRUE : kFALSE; if (!create && !recreate && !update && !read) { read = kTRUE; fOption = "READ"; } if (create || recreate || update) { fWritable=kTRUE; } if (recreate) { fOption = "CREATE"; create = kTRUE; } ///////////////////////////////////////////////////////////////////////////////////////// // first get an active Grid connection if (!gGrid) { // no TAlien existing .... Error("TAlienFile", "no active GRID connection found"); goto zombie2; } else { if ((strcmp(gGrid->GetGrid(), "alien"))) { Error("TAlienFile", "you don't have an active <alien> grid!"); goto zombie2; } } ///////////////////////////////////////////////////////////////////////////////////////// // get the authorization from the catalogue if (read) { // get the read access if (publicaccess) command = TString("access -p read "); else command = TString("access read "); } if (create) { command = TString("access write-once "); } if (recreate) { command = TString("access write-version "); } if (update) { command = TString("access write-version "); } command += file; if (fWritable) { // append the storage element environment variable command += " "; command += storageelement; } fLfn = file; result = gGrid->Command(command.Data(),kFALSE,TAlien::kOUTPUT); alienResult = dynamic_cast<TAlienResult*>(result); list = dynamic_cast<TList*>(alienResult); if (!list) { if (result) { delete result; } Error("TAlienFile", "cannot get the access envelope for %s",purl.GetUrl()); goto zombie2; } iter = list->MakeIterator(); object = 0; while ((object = iter->Next()) != 0) { TMap* map = dynamic_cast<TMap*>(object); TObject* urlObject = map->GetValue("url"); urlStr = dynamic_cast<TObjString*>(urlObject); TObject* authzObject = map->GetValue("envelope"); authzStr = dynamic_cast<TObjString*>(authzObject); // there is only one result line .... in case it is at all .... break; } if ((!urlStr) || (!authzStr)) { if (fWritable) { Error("TAlienFile", "didn't get the authorization to write %s",purl.GetUrl()); } else { Error("TAlienFile", "didn't get the authorization to read %s",purl.GetUrl()); } Info("TAlienFile","Command::Stdout !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!"); gGrid->Stdout(); Info("TAlienFile","Command::Stderr !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!"); gGrid->Stderr(); Info("TAlienFile","End of Output !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!"); delete iter; delete result; goto zombie2; } delete iter; delete result; fAuthz = authzStr->GetName(); newurl = urlStr->GetName(); stmp = purl.GetAnchor(); if (stmp != "") { newurl += "#"; newurl += purl.GetAnchor(); } newurl += TString("?&authz="); newurl += authzStr->GetName(); return newurl; zombie2: // error in file opening occured, make this object a zombie return ""; } //______________________________________________________________________________ TAlienFile::~TAlienFile() { // TAlienFile file dtor. if (fSubFile) { Close(); delete fSubFile; } fSubFile = 0; gFile = 0; gDirectory = gROOT; if (gDebug) Info("~TAlienFile", "dtor called for %s", GetName()); } //______________________________________________________________________________ Bool_t TAlienFile::ReadBuffer(char *buf, Int_t len) { // Read specified byte range. // Returns kTRUE in case of error. if (fSubFile) return fSubFile->ReadBuffer(buf, len); return kTRUE; } //______________________________________________________________________________ Bool_t TAlienFile::WriteBuffer(const char *buf, Int_t len) { // Write specified byte range // Returns kTRUE in case of error. if (fSubFile) return fSubFile->WriteBuffer(buf, len); return kTRUE; } //______________________________________________________________________________ void TAlienFile::Seek(Long64_t offset, ERelativeTo pos) { // Seek into file. if (fSubFile) { fSubFile->Seek(offset, pos); } } //______________________________________________________________________________ void TAlienFile::Close(Option_t *option) { // Close file. if (fOption == "READ") return; // set GCLIENT_EXTRA_ARG environment gSystem->Setenv("GCLIENT_EXTRA_ARG",fAuthz.Data()); // commit the envelope TString command("commit "); command += (Long_t)fSubFile->GetSize(); command += " "; command += fLfn; if (fSubFile) { fSubFile->Close(option); } TGridResult* result = gGrid->Command(command, kFALSE,TAlien::kOUTPUT); TAlienResult* alienResult = dynamic_cast<TAlienResult*>(result); TList* list = dynamic_cast<TList*>(alienResult); if (!list) { if (result) { delete result; } Error("Close", "cannot commit envelope for %s", fLfn.Data()); } TIterator* iter = list->MakeIterator(); TObject* object = 0; if (fWritable) { while ((object = iter->Next()) != 0) { TMap* map = dynamic_cast<TMap*>(object); TObject* commitObject = map->GetValue(fLfn.Data()); if (commitObject) { TObjString* commitStr = dynamic_cast<TObjString*>(commitObject); if (!(strcmp(commitStr->GetName(),"1"))) { // the file has been committed break; } } Error("Close", "cannot register %s!", fLfn.Data()); // there is only one result line .... in case it is at all .... break; } delete iter; delete result; } gSystem->Unsetenv("GCLIENT_EXTRA_ARG"); } <|endoftext|>
<commit_before>#include "vm.hpp" #include "vm/object_utils.hpp" #include "builtin/array.hpp" #include "builtin/fixnum.hpp" #include "builtin/io.hpp" #include "objectmemory.hpp" #include "primitives.hpp" #include "capi/capi.hpp" #include "capi/include/ruby.h" #include <fcntl.h> using namespace rubinius; using namespace rubinius::capi; namespace rubinius { namespace capi { IO* capi_get_io(NativeMethodEnvironment* env, VALUE io_handle) { Handle* handle = Handle::from(io_handle); handle->flush(env); env->check_tracked_handle(handle, false); return c_as<IO>(handle->object()); } static const char* flags_modestr(int oflags) { #ifdef O_BINARY # define MODE_BINARY(a,b) ((oflags & O_BINARY) ? (b) : (a)) #else # define MODE_BINARY(a,b) (a) #endif int accmode = oflags & (O_RDONLY|O_WRONLY|O_RDWR); if (oflags & O_APPEND) { if (accmode == O_WRONLY) { return MODE_BINARY("a", "ab"); } if (accmode == O_RDWR) { return MODE_BINARY("a+", "ab+"); } } switch (oflags & (O_RDONLY|O_WRONLY|O_RDWR)) { case O_RDONLY: return MODE_BINARY("r", "rb"); case O_WRONLY: return MODE_BINARY("w", "wb"); case O_RDWR: return MODE_BINARY("r+", "rb+"); } return NULL; } RIO* Handle::as_rio(NativeMethodEnvironment* env) { if(type_ != cRIO) { IO* io_obj = c_as<IO>(object()); int fd = (int)io_obj->descriptor()->to_native(); if(fd == -1) { rb_raise(rb_eIOError, "%s (%d)", strerror(errno), errno); } FILE* f = fdopen(fd, flags_modestr(io_obj->mode()->to_native())); if(!f) { fprintf(stderr, "Error convert fd (%d) to lowlevel IO: %s (%d)", fd, strerror(errno), errno); rb_raise(rb_eTypeError, "unable to convert fd (%d) to lowlevel IO: %s (%d)", fd, strerror(errno), errno); } RIO* rf = new RIO; rf->handle = as_value(); rf->fd = fd; rf->f = f; // Disable all buffering so that it doesn't get out of sync with // the normal IO buffer. setvbuf(rf->f, 0, _IONBF, 0); type_ = cRIO; as_.rio = rf; } return as_.rio; } bool Handle::rio_close() { if(type_ != cRIO) return true; RIO* rio = as_.rio; bool ok = (fclose(rio->f) == 0); rio->f = NULL; return ok; } } } extern "C" { struct RIO* capi_rio_struct(VALUE io_handle) { NativeMethodEnvironment* env = NativeMethodEnvironment::get(); return Handle::from(io_handle)->as_rio(env); } void rb_eof_error() { rb_raise(rb_eEOFError, "end of file reached"); } VALUE rb_io_write(VALUE io, VALUE str) { return rb_funcall(io, rb_intern("write"), 1, str); } VALUE rb_io_close(VALUE io) { return rb_funcall(io, rb_intern("close"), 0); } int rb_io_fd(VALUE io_handle) { NativeMethodEnvironment* env = NativeMethodEnvironment::get(); IO* io = c_as<IO>(env->get_object(io_handle)); return io->descriptor()->to_native(); } int rb_io_wait_readable(int fd) { bool retry = false; switch(errno) { case EINTR: #ifdef ERESTART case ERESTART: #endif retry = true; break; case EAGAIN: #if defined(EWOULDBLOCK) && EWOULDBLOCK != EAGAIN case EWOULDBLOCK: #endif break; default: // this is the MRI api. If errno is not on of these, say to the caller // "um, i guess nothing more to do?" return Qfalse; } fd_set fds; FD_ZERO(&fds); FD_SET(fd, &fds); int ready = 0; NativeMethodEnvironment* env = NativeMethodEnvironment::get(); GlobalLock::UnlockGuard guard(env); while(!ready) { ready = select(fd+1, &fds, 0, 0, 0); if(!retry) break; } return Qtrue; } int rb_io_wait_writable(int fd) { bool retry = false; switch(errno) { case EINTR: #ifdef ERESTART case ERESTART: #endif retry = true; break; case EAGAIN: #if defined(EWOULDBLOCK) && EWOULDBLOCK != EAGAIN case EWOULDBLOCK: #endif break; default: // this is the MRI api. If errno is not on of these, say to the caller // "um, i guess nothing more to do?" return Qfalse; } fd_set fds; FD_ZERO(&fds); FD_SET(fd, &fds); int ready = 0; NativeMethodEnvironment* env = NativeMethodEnvironment::get(); GlobalLock::UnlockGuard guard(env); while(!ready) { ready = select(fd+1, 0, &fds, 0, 0); if(!retry) break; } return Qtrue; } /* * rb_thread_wait_fd actually waits until a read is * available on the given fd */ void rb_thread_wait_fd(int fd) { fd_set fds; FD_ZERO(&fds); FD_SET(fd, &fds); int ready = 0; NativeMethodEnvironment* env = NativeMethodEnvironment::get(); GlobalLock::UnlockGuard guard(env); while(!ready) { ready = select(fd+1, &fds, 0, 0, 0); } } /* * rb_thread_fd_writable waits until the given fd * is available for writing */ void rb_thread_fd_writable(int fd) { fd_set fds; FD_ZERO(&fds); FD_SET(fd, &fds); int ready = 0; NativeMethodEnvironment* env = NativeMethodEnvironment::get(); GlobalLock::UnlockGuard guard(env); while(!ready) { ready = select(fd+1, 0, &fds, 0, 0); } } void rb_io_set_nonblock(rb_io_t* iot) { VALUE io_handle = iot->handle; NativeMethodEnvironment* env = NativeMethodEnvironment::get(); IO* io = c_as<IO>(env->get_object(io_handle)); io->set_nonblock(env->state()); } void rb_io_check_closed(rb_io_t* iot) { VALUE io_handle = iot->handle; NativeMethodEnvironment* env = NativeMethodEnvironment::get(); IO* io = c_as<IO>(env->get_object(io_handle)); if(io->descriptor()->to_native() == -1) { rb_raise(rb_eIOError, "closed stream"); } } void rb_io_check_readable(rb_io_t* iot) { VALUE io_handle = iot->handle; NativeMethodEnvironment* env = NativeMethodEnvironment::get(); IO* io = c_as<IO>(env->get_object(io_handle)); if ((io->mode()->to_native() & O_ACCMODE) != O_RDONLY) { rb_raise(rb_eIOError, "not opened for reading"); } } void rb_io_check_writable(rb_io_t* iot) { VALUE io_handle = iot->handle; NativeMethodEnvironment* env = NativeMethodEnvironment::get(); IO* io = c_as<IO>(env->get_object(io_handle)); if ((io->mode()->to_native() & O_ACCMODE) != O_WRONLY) { rb_raise(rb_eIOError, "not opened for writing"); } } } <commit_msg>fix rb_io_check_readable/rb_io_check_writeable to accept O_RDWR also<commit_after>#include "vm.hpp" #include "vm/object_utils.hpp" #include "builtin/array.hpp" #include "builtin/fixnum.hpp" #include "builtin/io.hpp" #include "objectmemory.hpp" #include "primitives.hpp" #include "capi/capi.hpp" #include "capi/include/ruby.h" #include <fcntl.h> using namespace rubinius; using namespace rubinius::capi; namespace rubinius { namespace capi { IO* capi_get_io(NativeMethodEnvironment* env, VALUE io_handle) { Handle* handle = Handle::from(io_handle); handle->flush(env); env->check_tracked_handle(handle, false); return c_as<IO>(handle->object()); } static const char* flags_modestr(int oflags) { #ifdef O_BINARY # define MODE_BINARY(a,b) ((oflags & O_BINARY) ? (b) : (a)) #else # define MODE_BINARY(a,b) (a) #endif int accmode = oflags & (O_RDONLY|O_WRONLY|O_RDWR); if (oflags & O_APPEND) { if (accmode == O_WRONLY) { return MODE_BINARY("a", "ab"); } if (accmode == O_RDWR) { return MODE_BINARY("a+", "ab+"); } } switch (oflags & (O_RDONLY|O_WRONLY|O_RDWR)) { case O_RDONLY: return MODE_BINARY("r", "rb"); case O_WRONLY: return MODE_BINARY("w", "wb"); case O_RDWR: return MODE_BINARY("r+", "rb+"); } return NULL; } RIO* Handle::as_rio(NativeMethodEnvironment* env) { if(type_ != cRIO) { IO* io_obj = c_as<IO>(object()); int fd = (int)io_obj->descriptor()->to_native(); if(fd == -1) { rb_raise(rb_eIOError, "%s (%d)", strerror(errno), errno); } FILE* f = fdopen(fd, flags_modestr(io_obj->mode()->to_native())); if(!f) { fprintf(stderr, "Error convert fd (%d) to lowlevel IO: %s (%d)", fd, strerror(errno), errno); rb_raise(rb_eTypeError, "unable to convert fd (%d) to lowlevel IO: %s (%d)", fd, strerror(errno), errno); } RIO* rf = new RIO; rf->handle = as_value(); rf->fd = fd; rf->f = f; // Disable all buffering so that it doesn't get out of sync with // the normal IO buffer. setvbuf(rf->f, 0, _IONBF, 0); type_ = cRIO; as_.rio = rf; } return as_.rio; } bool Handle::rio_close() { if(type_ != cRIO) return true; RIO* rio = as_.rio; bool ok = (fclose(rio->f) == 0); rio->f = NULL; return ok; } } } extern "C" { struct RIO* capi_rio_struct(VALUE io_handle) { NativeMethodEnvironment* env = NativeMethodEnvironment::get(); return Handle::from(io_handle)->as_rio(env); } void rb_eof_error() { rb_raise(rb_eEOFError, "end of file reached"); } VALUE rb_io_write(VALUE io, VALUE str) { return rb_funcall(io, rb_intern("write"), 1, str); } VALUE rb_io_close(VALUE io) { return rb_funcall(io, rb_intern("close"), 0); } int rb_io_fd(VALUE io_handle) { NativeMethodEnvironment* env = NativeMethodEnvironment::get(); IO* io = c_as<IO>(env->get_object(io_handle)); return io->descriptor()->to_native(); } int rb_io_wait_readable(int fd) { bool retry = false; switch(errno) { case EINTR: #ifdef ERESTART case ERESTART: #endif retry = true; break; case EAGAIN: #if defined(EWOULDBLOCK) && EWOULDBLOCK != EAGAIN case EWOULDBLOCK: #endif break; default: // this is the MRI api. If errno is not on of these, say to the caller // "um, i guess nothing more to do?" return Qfalse; } fd_set fds; FD_ZERO(&fds); FD_SET(fd, &fds); int ready = 0; NativeMethodEnvironment* env = NativeMethodEnvironment::get(); GlobalLock::UnlockGuard guard(env); while(!ready) { ready = select(fd+1, &fds, 0, 0, 0); if(!retry) break; } return Qtrue; } int rb_io_wait_writable(int fd) { bool retry = false; switch(errno) { case EINTR: #ifdef ERESTART case ERESTART: #endif retry = true; break; case EAGAIN: #if defined(EWOULDBLOCK) && EWOULDBLOCK != EAGAIN case EWOULDBLOCK: #endif break; default: // this is the MRI api. If errno is not on of these, say to the caller // "um, i guess nothing more to do?" return Qfalse; } fd_set fds; FD_ZERO(&fds); FD_SET(fd, &fds); int ready = 0; NativeMethodEnvironment* env = NativeMethodEnvironment::get(); GlobalLock::UnlockGuard guard(env); while(!ready) { ready = select(fd+1, 0, &fds, 0, 0); if(!retry) break; } return Qtrue; } /* * rb_thread_wait_fd actually waits until a read is * available on the given fd */ void rb_thread_wait_fd(int fd) { fd_set fds; FD_ZERO(&fds); FD_SET(fd, &fds); int ready = 0; NativeMethodEnvironment* env = NativeMethodEnvironment::get(); GlobalLock::UnlockGuard guard(env); while(!ready) { ready = select(fd+1, &fds, 0, 0, 0); } } /* * rb_thread_fd_writable waits until the given fd * is available for writing */ void rb_thread_fd_writable(int fd) { fd_set fds; FD_ZERO(&fds); FD_SET(fd, &fds); int ready = 0; NativeMethodEnvironment* env = NativeMethodEnvironment::get(); GlobalLock::UnlockGuard guard(env); while(!ready) { ready = select(fd+1, 0, &fds, 0, 0); } } void rb_io_set_nonblock(rb_io_t* iot) { VALUE io_handle = iot->handle; NativeMethodEnvironment* env = NativeMethodEnvironment::get(); IO* io = c_as<IO>(env->get_object(io_handle)); io->set_nonblock(env->state()); } void rb_io_check_closed(rb_io_t* iot) { VALUE io_handle = iot->handle; NativeMethodEnvironment* env = NativeMethodEnvironment::get(); IO* io = c_as<IO>(env->get_object(io_handle)); if(io->descriptor()->to_native() == -1) { rb_raise(rb_eIOError, "closed stream"); } } void rb_io_check_readable(rb_io_t* iot) { VALUE io_handle = iot->handle; NativeMethodEnvironment* env = NativeMethodEnvironment::get(); IO* io = c_as<IO>(env->get_object(io_handle)); int io_mode = io->mode()->to_native() & O_ACCMODE; if (!(O_RDONLY == io_mode || O_RDWR == io_mode)) { rb_raise(rb_eIOError, "not opened for reading"); } } void rb_io_check_writable(rb_io_t* iot) { VALUE io_handle = iot->handle; NativeMethodEnvironment* env = NativeMethodEnvironment::get(); IO* io = c_as<IO>(env->get_object(io_handle)); int io_mode = io->mode()->to_native() & O_ACCMODE; if (!(O_WRONLY == io_mode || O_RDWR == io_mode)) { rb_raise(rb_eIOError, "not opened for writing"); } } } <|endoftext|>
<commit_before>#include "ROOT/RDataFrame.hxx" #include "TChain.h" #include "TEntryList.h" #include "TFile.h" #include "TROOT.h" #include "TSystem.h" #include "TTree.h" #include "gtest/gtest.h" #include <vector> // Write to disk file filename with TTree "t" with nEntries of branch "e" assuming integer values [0..nEntries). void MakeInputFile(const std::string &filename, int nEntries) { const auto treename = "t"; auto d = ROOT::RDataFrame(nEntries) .Define("e", [](ULong64_t e) { return int(e); }, {"rdfentry_"}) .Snapshot<int>(treename, filename, {"e"}); } class RMTRAII { bool fIsMT; public: RMTRAII(bool isMT) : fIsMT(isMT) { if (fIsMT) ROOT::EnableImplicitMT(); } ~RMTRAII() { if (fIsMT) ROOT::DisableImplicitMT(); } }; void TestTreeWithEntryList(bool isMT = false) { const auto nEntries = 10; const auto treename = "t"; const auto filename = "rdfentrylist.root"; MakeInputFile(filename, nEntries); RMTRAII gomt(isMT); TEntryList elist("e", "e", treename, filename); elist.Enter(0); elist.Enter(nEntries - 1); TFile f(filename); auto t = f.Get<TTree>(treename); t->SetEntryList(&elist); auto entries = ROOT::RDataFrame(*t).Take<int>("e"); EXPECT_EQ(*entries, std::vector<int>({0, nEntries - 1})); gSystem->Unlink(filename); } void TestChainWithEntryList(bool isMT = false) { const auto nEntries = 10; const auto treename = "t"; const auto file1 = "rdfentrylist1.root"; const auto file2 = "rdfentrylist2.root"; MakeInputFile(file1, nEntries); MakeInputFile(file2, nEntries); RMTRAII gomt(isMT); TEntryList elist1("e", "e", treename, file1); elist1.Enter(0); elist1.Enter(nEntries - 1); TEntryList elist2("e", "e", treename, file2); elist2.Enter(0); elist2.Enter(nEntries - 1); // make a TEntryList that contains two TEntryLists in its list of TEntryLists, // as required by TChain (see TEntryList's doc) TEntryList elists; elists.Add(&elist1); elists.Add(&elist2); TChain c(treename); c.Add(file1, nEntries); c.Add(file2, nEntries); c.SetEntryList(&elists); auto entries = ROOT::RDataFrame(c).Take<int>("e"); EXPECT_EQ(*entries, std::vector<int>({0, nEntries - 1, 0, nEntries - 1})); gSystem->Unlink(file1); gSystem->Unlink(file2); } TEST(RDFEntryList, Chain) { TestChainWithEntryList(); } TEST(RDFEntryList, Tree) { TestTreeWithEntryList(); } #ifdef R__USE_IMT TEST(RDFEntryList, ChainMT) { TestChainWithEntryList(true); } TEST(RDFEntryList, TreeMT) { TestTreeWithEntryList(true); } #endif <commit_msg>[DF] Do not assume a certain entry order in MT tests<commit_after>#include "ROOT/RDataFrame.hxx" #include "TChain.h" #include "TEntryList.h" #include "TFile.h" #include "TROOT.h" #include "TSystem.h" #include "TTree.h" #include "gtest/gtest.h" #include <algorithm> // std::sort #include <vector> // Write to disk file filename with TTree "t" with nEntries of branch "e" assuming integer values [0..nEntries). void MakeInputFile(const std::string &filename, int nEntries) { const auto treename = "t"; auto d = ROOT::RDataFrame(nEntries) .Define("e", [](ULong64_t e) { return int(e); }, {"rdfentry_"}) .Snapshot<int>(treename, filename, {"e"}); } class RMTRAII { bool fIsMT; public: RMTRAII(bool isMT) : fIsMT(isMT) { if (fIsMT) ROOT::EnableImplicitMT(); } ~RMTRAII() { if (fIsMT) ROOT::DisableImplicitMT(); } }; void TestTreeWithEntryList(bool isMT = false) { const auto nEntries = 10; const auto treename = "t"; const auto filename = "rdfentrylist.root"; MakeInputFile(filename, nEntries); RMTRAII gomt(isMT); TEntryList elist("e", "e", treename, filename); elist.Enter(0); elist.Enter(nEntries - 1); TFile f(filename); auto t = f.Get<TTree>(treename); t->SetEntryList(&elist); auto entries = ROOT::RDataFrame(*t).Take<int>("e").GetValue(); std::sort(entries.begin(), entries.end()); // could be out of order in MT runs EXPECT_EQ(entries, std::vector<int>({0, nEntries - 1})); gSystem->Unlink(filename); } void TestChainWithEntryList(bool isMT = false) { const auto nEntries = 10; const auto treename = "t"; const auto file1 = "rdfentrylist1.root"; const auto file2 = "rdfentrylist2.root"; MakeInputFile(file1, nEntries); MakeInputFile(file2, nEntries); RMTRAII gomt(isMT); TEntryList elist1("e", "e", treename, file1); elist1.Enter(0); elist1.Enter(nEntries - 1); TEntryList elist2("e", "e", treename, file2); elist2.Enter(0); elist2.Enter(nEntries - 1); // make a TEntryList that contains two TEntryLists in its list of TEntryLists, // as required by TChain (see TEntryList's doc) TEntryList elists; elists.Add(&elist1); elists.Add(&elist2); TChain c(treename); c.Add(file1, nEntries); c.Add(file2, nEntries); c.SetEntryList(&elists); auto entries = ROOT::RDataFrame(c).Take<int>("e").GetValue(); std::sort(entries.begin(), entries.end()); // could be out of order in MT runs EXPECT_EQ(entries, std::vector<int>({0, 0, nEntries - 1, nEntries - 1})); gSystem->Unlink(file1); gSystem->Unlink(file2); } TEST(RDFEntryList, Chain) { TestChainWithEntryList(); } TEST(RDFEntryList, Tree) { TestTreeWithEntryList(); } #ifdef R__USE_IMT TEST(RDFEntryList, ChainMT) { TestChainWithEntryList(true); } TEST(RDFEntryList, TreeMT) { TestTreeWithEntryList(true); } #endif <|endoftext|>
<commit_before>/* Copyright © 2001-2014, Canal TP and/or its affiliates. All rights reserved. This file is part of Navitia, the software to build cool stuff with public transport. Hope you'll enjoy and contribute to this project, powered by Canal TP (www.canaltp.fr). Help us simplify mobility and open public transport: a non ending quest to the responsive locomotion way of traveling! LICENCE: This program is free software; you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. Stay tuned using twitter @navitia IRC #navitia on freenode https://groups.google.com/d/forum/navitia www.navitia.io */ #include "geopal_parser.h" #include "data_cleaner.h" namespace ed { namespace connectors { GeopalParserException::~GeopalParserException() noexcept {} GeopalParser::GeopalParser(const std::string& path, const ed::connectors::ConvCoord& conv_coord): path(path), conv_coord(conv_coord) { logger = log4cplus::Logger::getInstance("log"); try{ boost::filesystem::path directory(this->path); boost::filesystem::directory_iterator iter(directory), end; for(;iter != end; ++iter){ if (iter->path().extension() == ".txt"){ std::string file_name = iter->path().filename().string(); this->files.push_back(file_name); } } }catch( const boost::filesystem::filesystem_error& e){ throw GeopalParserException("GeopalParser : Error " + e.code().message()); } } bool GeopalParser::starts_with(std::string filename, const std::string& prefex){ return boost::algorithm::starts_with(filename, prefex); } void GeopalParser::fill(){ this->fill_admins(); LOG4CPLUS_INFO(logger, "Admin count: " << this->data.admins.size()); this->fill_nodes(); LOG4CPLUS_INFO(logger, "Noeud count: " << this->data.nodes.size()); this->fill_ways_edges(); LOG4CPLUS_INFO(logger, "Way count: " << this->data.ways.size()); LOG4CPLUS_INFO(logger, "Edge count: " << this->data.edges.size()); LOG4CPLUS_INFO(logger, "begin: data cleaning"); data_cleaner cleaner(data); cleaner.clean(); LOG4CPLUS_INFO(logger, "End: data cleaning"); this->fill_house_numbers(); LOG4CPLUS_INFO(logger, "House number count: " << this->data.house_numbers.size()); } ed::types::Node* GeopalParser::add_node(const navitia::type::GeographicalCoord& coord, const std::string& uri){ ed::types::Node* node = new ed::types::Node; node->id = this->data.nodes.size() + 1; node->coord = this->conv_coord.convert_to(coord); this->data.nodes[uri] = node; return node; } void GeopalParser::fill_nodes(){ for(const std::string file_name : this->files){ if(!this->starts_with(file_name, "adresse")){ continue; } CsvReader reader(this->path + "/" + file_name, ';', true, true); if(!reader.is_open()) { throw GeopalParserException("Error on open file " + reader.filename); } std::vector<std::string> mandatory_headers = {"code_insee", "code_post", "x_adresse", "y_adresse"}; if(!reader.validate(mandatory_headers)) { throw GeopalParserException("Impossible to parse file " + reader.filename + " . Not find column : " + reader.missing_headers(mandatory_headers)); } int insee_c = reader.get_pos_col("code_insee"); int code_post_c = reader.get_pos_col("code_post"); int x_c = reader.get_pos_col("x_adresse"); int y_c = reader.get_pos_col("y_adresse"); while(!reader.eof()){ std::vector<std::string> row = reader.next(); std::string uri; if (reader.is_valid(x_c, row) && reader.is_valid(y_c, row) && reader.is_valid(insee_c, row)){ uri = row[x_c] + row[y_c]; auto adm = this->data.admins.find(row[insee_c]); if (adm != this->data.admins.end()){ if(reader.is_valid(code_post_c, row)){ adm->second->postcode = row[code_post_c]; } auto nd = this->data.nodes.find(uri); if(nd == this->data.nodes.end()) this->add_node(navitia::type::GeographicalCoord(str_to_double(row[x_c]), str_to_double(row[y_c])), uri); } } } } } void GeopalParser::fill_admins(){ for(const std::string file_name : this->files){ if (! this->starts_with(file_name, "commune")){ continue; } CsvReader reader(this->path + "/" + file_name, ';', true, true); if(!reader.is_open()) { throw GeopalParserException("Error on open file " + reader.filename); } std::vector<std::string> mandatory_headers = {"nom" , "code_insee", "x_commune", "y_commune"}; if(!reader.validate(mandatory_headers)) { throw GeopalParserException("Impossible to parse file " + reader.filename +" . Not find column : " + reader.missing_headers(mandatory_headers)); } int name_c = reader.get_pos_col("nom"); int insee_c = reader.get_pos_col("code_insee"); int x_c = reader.get_pos_col("x_commune"); int y_c = reader.get_pos_col("y_commune"); while(!reader.eof()){ std::vector<std::string> row = reader.next(); if (reader.is_valid(insee_c, row) && reader.is_valid(x_c, row) && reader.is_valid(y_c, row)){ auto itm = this->data.admins.find(row[insee_c]); if(itm == this->data.admins.end()){ ed::types::Admin* admin = new ed::types::Admin; admin->insee = row[insee_c]; admin->id = this->data.admins.size() + 1; if (reader.is_valid(name_c, row)) admin->name = row[name_c]; admin->coord = this->conv_coord.convert_to(navitia::type::GeographicalCoord(str_to_double(row[x_c]), str_to_double(row[y_c]))); this->data.admins[admin->insee] = admin; } } } } } void GeopalParser::fill_ways_edges(){ for(const std::string file_name : this->files){ if (! this->starts_with(file_name, "route_a")){ continue; } CsvReader reader(this->path + "/" + file_name, ';', true, true); if(!reader.is_open()) { throw GeopalParserException("Error on open file " + reader.filename); } std::vector<std::string> mandatory_headers = {"id", "x_debut" , "y_debut", "x_fin", "y_fin", "longueur", "inseecom_g", "inseecom_d"}; if(!reader.validate(mandatory_headers)) { throw GeopalParserException("Impossible to parse file " + reader.filename +" . Not find column : " + reader.missing_headers(mandatory_headers)); } int nom_voie_d = reader.get_pos_col("nom_voie_d"); int x1 = reader.get_pos_col("x_debut"); int y1 = reader.get_pos_col("y_debut"); int x2 = reader.get_pos_col("x_fin"); int y2 = reader.get_pos_col("y_fin"); int l = reader.get_pos_col("longueur"); int inseecom_d = reader.get_pos_col("inseecom_d"); int id = reader.get_pos_col("id"); while(!reader.eof()){ std::vector<std::string> row = reader.next(); if (reader.is_valid(x1, row) && reader.is_valid(y1, row) && reader.is_valid(x2, row) && reader.is_valid(y2, row) && reader.is_valid(inseecom_d, row) && reader.is_valid(id, row)){ auto admin = this->data.admins.find(row[inseecom_d]); if(admin != this->data.admins.end()){ std::string source = row[x1] + row[y1]; std::string target = row[x2] + row[y2]; ed::types::Node* source_node; ed::types::Node* target_node; auto source_it = this->data.nodes.find(source); auto target_it = this->data.nodes.find(target); if(source_it == this->data.nodes.end()){ source_node = this->add_node(navitia::type::GeographicalCoord(str_to_double(row[x1]), str_to_double(row[y1])), source); }else{ source_node = source_it->second; } if(target_it == this->data.nodes.end()){ target_node = this->add_node(navitia::type::GeographicalCoord(str_to_double(row[x2]), str_to_double(row[y2])), target); }else{ target_node = target_it->second; } ed::types::Way* current_way = nullptr; std::string wayd_uri = row[id]; auto way = this->data.ways.find(wayd_uri); if(way == this->data.ways.end()){ ed::types::Way* wy = new ed::types::Way; wy->admin = admin->second; admin->second->is_used = true; wy->id = this->data.ways.size() + 1; if(reader.is_valid(nom_voie_d, row)){ wy->name = row[nom_voie_d]; } wy->type =""; wy->uri = wayd_uri; this->data.ways[wayd_uri] = wy; current_way = wy; }else{ current_way = way->second; } auto edge = this->data.edges.find(wayd_uri); if(edge == this->data.edges.end()){ ed::types::Edge* edg = new ed::types::Edge; edg->source = source_node; edg->source->is_used = true; edg->target = target_node; edg->target->is_used = true; if(reader.is_valid(l, row)){ edg->length = str_to_int(row[l]); } edg->way = current_way; this->data.edges[wayd_uri]= edg; current_way->edges.push_back(edg); } } } } } } void GeopalParser::fill_house_numbers(){ for(const std::string file_name : this->files){ if (! this->starts_with(file_name, "adresse")){ continue; } CsvReader reader(this->path + "/" + file_name, ';', true, true); if(!reader.is_open()) { throw GeopalParserException("Error on open file " + reader.filename); } std::vector<std::string> mandatory_headers = {"id_tr", "numero", "nom_voie", "code_insee", "x_adresse", "y_adresse"}; if(!reader.validate(mandatory_headers)) { throw GeopalParserException("Impossible to parse file " + reader.filename +" . Not find column : " + reader.missing_headers(mandatory_headers)); } int insee_c = reader.get_pos_col("code_insee"); int nom_voie_c = reader.get_pos_col("nom_voie"); int numero_c = reader.get_pos_col("numero"); int x_c = reader.get_pos_col("x_adresse"); int y_c = reader.get_pos_col("y_adresse"); int id_tr = reader.get_pos_col("id_tr"); while(!reader.eof()){ std::vector<std::string> row = reader.next(); if (reader.is_valid(x_c, row) && reader.is_valid(y_c, row) && reader.is_valid(insee_c, row) && reader.is_valid(numero_c, row) && reader.is_valid(nom_voie_c, row) && reader.is_valid(id_tr, row)){ std::string way_uri = row[id_tr]; auto it = this->data.fusion_ways.find(way_uri); if(it != this->data.fusion_ways.end()){ std::string hn_uri = row[x_c] + row[y_c] + row[numero_c]; auto hn = this->data.house_numbers.find(hn_uri); if (hn == this-> data.house_numbers.end()){ ed::types::HouseNumber current_hn; current_hn.coord = this->conv_coord.convert_to(navitia::type::GeographicalCoord(str_to_double(row[x_c]), str_to_double(row[y_c]))); current_hn.number = row[numero_c]; current_hn.way = it->second; this->data.house_numbers[hn_uri] = current_hn; } } } } } } } }//namespace <commit_msg>geopal: remove doublon of nodes<commit_after>/* Copyright © 2001-2014, Canal TP and/or its affiliates. All rights reserved. This file is part of Navitia, the software to build cool stuff with public transport. Hope you'll enjoy and contribute to this project, powered by Canal TP (www.canaltp.fr). Help us simplify mobility and open public transport: a non ending quest to the responsive locomotion way of traveling! LICENCE: This program is free software; you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. Stay tuned using twitter @navitia IRC #navitia on freenode https://groups.google.com/d/forum/navitia www.navitia.io */ #include "geopal_parser.h" #include "data_cleaner.h" namespace ed { namespace connectors { GeopalParserException::~GeopalParserException() noexcept {} GeopalParser::GeopalParser(const std::string& path, const ed::connectors::ConvCoord& conv_coord): path(path), conv_coord(conv_coord) { logger = log4cplus::Logger::getInstance("log"); try{ boost::filesystem::path directory(this->path); boost::filesystem::directory_iterator iter(directory), end; for(;iter != end; ++iter){ if (iter->path().extension() == ".txt"){ std::string file_name = iter->path().filename().string(); this->files.push_back(file_name); } } }catch( const boost::filesystem::filesystem_error& e){ throw GeopalParserException("GeopalParser : Error " + e.code().message()); } } bool GeopalParser::starts_with(std::string filename, const std::string& prefex){ return boost::algorithm::starts_with(filename, prefex); } void GeopalParser::fill(){ this->fill_admins(); LOG4CPLUS_INFO(logger, "Admin count: " << this->data.admins.size()); this->fill_nodes(); LOG4CPLUS_INFO(logger, "Noeud count: " << this->data.nodes.size()); this->fill_ways_edges(); LOG4CPLUS_INFO(logger, "Way count: " << this->data.ways.size()); LOG4CPLUS_INFO(logger, "Edge count: " << this->data.edges.size()); LOG4CPLUS_INFO(logger, "begin: data cleaning"); data_cleaner cleaner(data); cleaner.clean(); LOG4CPLUS_INFO(logger, "End: data cleaning"); this->fill_house_numbers(); LOG4CPLUS_INFO(logger, "House number count: " << this->data.house_numbers.size()); } ed::types::Node* GeopalParser::add_node(const navitia::type::GeographicalCoord& coord, const std::string& uri){ ed::types::Node* node = new ed::types::Node; node->id = this->data.nodes.size() + 1; node->coord = this->conv_coord.convert_to(coord); this->data.nodes[uri] = node; return node; } void GeopalParser::fill_nodes(){ for(const std::string file_name : this->files){ if(!this->starts_with(file_name, "adresse")){ continue; } CsvReader reader(this->path + "/" + file_name, ';', true, true); if(!reader.is_open()) { throw GeopalParserException("Error on open file " + reader.filename); } std::vector<std::string> mandatory_headers = {"code_insee", "code_post", "x_adresse", "y_adresse"}; if(!reader.validate(mandatory_headers)) { throw GeopalParserException("Impossible to parse file " + reader.filename + " . Not find column : " + reader.missing_headers(mandatory_headers)); } int insee_c = reader.get_pos_col("code_insee"); int code_post_c = reader.get_pos_col("code_post"); int x_c = reader.get_pos_col("x_adresse"); int y_c = reader.get_pos_col("y_adresse"); while(!reader.eof()){ std::vector<std::string> row = reader.next(); std::string uri; if (reader.is_valid(x_c, row) && reader.is_valid(y_c, row) && reader.is_valid(insee_c, row)){ uri = row[x_c] + row[y_c]; auto adm = this->data.admins.find(row[insee_c]); if (adm != this->data.admins.end()){ if(reader.is_valid(code_post_c, row)){ adm->second->postcode = row[code_post_c]; } auto nd = this->data.nodes.find(uri); if(nd == this->data.nodes.end()) this->add_node(navitia::type::GeographicalCoord(str_to_double(row[x_c]), str_to_double(row[y_c])), uri); } } } } } void GeopalParser::fill_admins(){ for(const std::string file_name : this->files){ if (! this->starts_with(file_name, "commune")){ continue; } CsvReader reader(this->path + "/" + file_name, ';', true, true); if(!reader.is_open()) { throw GeopalParserException("Error on open file " + reader.filename); } std::vector<std::string> mandatory_headers = {"nom" , "code_insee", "x_commune", "y_commune"}; if(!reader.validate(mandatory_headers)) { throw GeopalParserException("Impossible to parse file " + reader.filename +" . Not find column : " + reader.missing_headers(mandatory_headers)); } int name_c = reader.get_pos_col("nom"); int insee_c = reader.get_pos_col("code_insee"); int x_c = reader.get_pos_col("x_commune"); int y_c = reader.get_pos_col("y_commune"); while(!reader.eof()){ std::vector<std::string> row = reader.next(); if (reader.is_valid(insee_c, row) && reader.is_valid(x_c, row) && reader.is_valid(y_c, row)){ auto itm = this->data.admins.find(row[insee_c]); if(itm == this->data.admins.end()){ ed::types::Admin* admin = new ed::types::Admin; admin->insee = row[insee_c]; admin->id = this->data.admins.size() + 1; if (reader.is_valid(name_c, row)) admin->name = row[name_c]; admin->coord = this->conv_coord.convert_to(navitia::type::GeographicalCoord(str_to_double(row[x_c]), str_to_double(row[y_c]))); this->data.admins[admin->insee] = admin; } } } } } void GeopalParser::fill_ways_edges(){ for(const std::string file_name : this->files){ if (! this->starts_with(file_name, "route_a")){ continue; } CsvReader reader(this->path + "/" + file_name, ';', true, true); if(!reader.is_open()) { throw GeopalParserException("Error on open file " + reader.filename); } std::vector<std::string> mandatory_headers = {"id", "x_debut" , "y_debut", "x_fin", "y_fin", "longueur", "inseecom_g", "inseecom_d"}; if(!reader.validate(mandatory_headers)) { throw GeopalParserException("Impossible to parse file " + reader.filename +" . Not find column : " + reader.missing_headers(mandatory_headers)); } int nom_voie_d = reader.get_pos_col("nom_voie_d"); int x1 = reader.get_pos_col("x_debut"); int y1 = reader.get_pos_col("y_debut"); int x2 = reader.get_pos_col("x_fin"); int y2 = reader.get_pos_col("y_fin"); int l = reader.get_pos_col("longueur"); int inseecom_d = reader.get_pos_col("inseecom_d"); int id = reader.get_pos_col("id"); while(!reader.eof()){ std::vector<std::string> row = reader.next(); if (reader.is_valid(x1, row) && reader.is_valid(y1, row) && reader.is_valid(x2, row) && reader.is_valid(y2, row) && reader.is_valid(inseecom_d, row) && reader.is_valid(id, row)){ auto admin = this->data.admins.find(row[inseecom_d]); if(admin != this->data.admins.end()){ std::string source = row[x1] + row[y1]; std::string target = row[x2] + row[y2]; ed::types::Node* source_node; ed::types::Node* target_node; auto source_it = this->data.nodes.find(source); if(source_it == this->data.nodes.end()){ source_node = this->add_node(navitia::type::GeographicalCoord(str_to_double(row[x1]), str_to_double(row[y1])), source); }else{ source_node = source_it->second; } auto target_it = this->data.nodes.find(target); if(target_it == this->data.nodes.end()){ target_node = this->add_node(navitia::type::GeographicalCoord(str_to_double(row[x2]), str_to_double(row[y2])), target); }else{ target_node = target_it->second; } ed::types::Way* current_way = nullptr; std::string wayd_uri = row[id]; auto way = this->data.ways.find(wayd_uri); if(way == this->data.ways.end()){ ed::types::Way* wy = new ed::types::Way; wy->admin = admin->second; admin->second->is_used = true; wy->id = this->data.ways.size() + 1; if(reader.is_valid(nom_voie_d, row)){ wy->name = row[nom_voie_d]; } wy->type =""; wy->uri = wayd_uri; this->data.ways[wayd_uri] = wy; current_way = wy; }else{ current_way = way->second; } auto edge = this->data.edges.find(wayd_uri); if(edge == this->data.edges.end()){ ed::types::Edge* edg = new ed::types::Edge; edg->source = source_node; edg->source->is_used = true; edg->target = target_node; edg->target->is_used = true; if(reader.is_valid(l, row)){ edg->length = str_to_int(row[l]); } edg->way = current_way; this->data.edges[wayd_uri]= edg; current_way->edges.push_back(edg); } } } } } } void GeopalParser::fill_house_numbers(){ for(const std::string file_name : this->files){ if (! this->starts_with(file_name, "adresse")){ continue; } CsvReader reader(this->path + "/" + file_name, ';', true, true); if(!reader.is_open()) { throw GeopalParserException("Error on open file " + reader.filename); } std::vector<std::string> mandatory_headers = {"id_tr", "numero", "nom_voie", "code_insee", "x_adresse", "y_adresse"}; if(!reader.validate(mandatory_headers)) { throw GeopalParserException("Impossible to parse file " + reader.filename +" . Not find column : " + reader.missing_headers(mandatory_headers)); } int insee_c = reader.get_pos_col("code_insee"); int nom_voie_c = reader.get_pos_col("nom_voie"); int numero_c = reader.get_pos_col("numero"); int x_c = reader.get_pos_col("x_adresse"); int y_c = reader.get_pos_col("y_adresse"); int id_tr = reader.get_pos_col("id_tr"); while(!reader.eof()){ std::vector<std::string> row = reader.next(); if (reader.is_valid(x_c, row) && reader.is_valid(y_c, row) && reader.is_valid(insee_c, row) && reader.is_valid(numero_c, row) && reader.is_valid(nom_voie_c, row) && reader.is_valid(id_tr, row)){ std::string way_uri = row[id_tr]; auto it = this->data.fusion_ways.find(way_uri); if(it != this->data.fusion_ways.end()){ std::string hn_uri = row[x_c] + row[y_c] + row[numero_c]; auto hn = this->data.house_numbers.find(hn_uri); if (hn == this-> data.house_numbers.end()){ ed::types::HouseNumber current_hn; current_hn.coord = this->conv_coord.convert_to(navitia::type::GeographicalCoord(str_to_double(row[x_c]), str_to_double(row[y_c]))); current_hn.number = row[numero_c]; current_hn.way = it->second; this->data.house_numbers[hn_uri] = current_hn; } } } } } } } }//namespace <|endoftext|>
<commit_before>#include "FROG/Collision/BoxCollider.hpp" #include "FROG/Transform.hpp" namespace frog{ BoxCollider::BoxCollider(const sf::Vector2f& dimensions, const sf::Vector2f& _gap, std::function<void(Collision)> fun ) : Collider(fun), gap(_gap) { rectangle.setSize( dimensions ); rectangle.setOrigin( gap ); } BoxCollider::~BoxCollider() { } sf::FloatRect BoxCollider::getBoundingBox() const { return rectangle.getGlobalBounds(); } float BoxCollider::getXMin() const { return rectangle.getGlobalBounds().left; } float BoxCollider::getYMin() const { return rectangle.getGlobalBounds().top; } float BoxCollider::getXMax() const { return rectangle.getGlobalBounds().left + rectangle.getGlobalBounds().width; } float BoxCollider::getYMax() const { return rectangle.getGlobalBounds().top + rectangle.getGlobalBounds().height; } void BoxCollider::update(const ComponentHolder& parent) { auto t = parent.getComponent<Transform>("TRANSFORM"); // centering the box at the origin of the parent /* auto pos = t->getPosition() - t->getOrigin(); gap.x *= t->getScale().x; gap.x *= t->getScale().y; box.left = pos.x + gap.x; box.top = pos.y + gap.y; box.width = t->getScale().x * dimensions.x; box.height = t->getScale().y * dimensions.y; */ rectangle.setOrigin( t->getOrigin() + gap); rectangle.setScale( t->getScale() ); rectangle.setPosition( t->getPosition() ); rectangle.setRotation( t->getRotation() ); } void BoxCollider::resize(const sf::Vector2f& newsize) { rectangle.setSize(newsize); } void BoxCollider::setGap(const sf::Vector2f& newgap) { gap = newgap; } BoxCollider::PTR BoxCollider::create(const sf::Vector2f& dimensions, const sf::Vector2f& gap, std::function<void(Collision)> fun) { return PTR(new BoxCollider(dimensions, gap, fun) ); } } <commit_msg>possible optimization<commit_after>#include "FROG/Collision/BoxCollider.hpp" #include "FROG/Transform.hpp" namespace frog{ BoxCollider::BoxCollider(const sf::Vector2f& dimensions, const sf::Vector2f& _gap, std::function<void(Collision)> fun ) : Collider(fun), gap(_gap) { rectangle.setSize( dimensions ); rectangle.setOrigin( gap ); } BoxCollider::~BoxCollider() { } sf::FloatRect BoxCollider::getBoundingBox() const { return rectangle.getGlobalBounds(); } float BoxCollider::getXMin() const { return rectangle.getGlobalBounds().left; } float BoxCollider::getYMin() const { return rectangle.getGlobalBounds().top; } float BoxCollider::getXMax() const { auto gb = rectangle.getGlobalBounds(); return gb.left + gb.width; } float BoxCollider::getYMax() const { auto gb = rectangle.getGlobalBounds(); return gb.top + gb.height; } void BoxCollider::update(const ComponentHolder& parent) { auto t = parent.getComponent<Transform>("TRANSFORM"); // centering the box at the origin of the parent /* auto pos = t->getPosition() - t->getOrigin(); gap.x *= t->getScale().x; gap.x *= t->getScale().y; box.left = pos.x + gap.x; box.top = pos.y + gap.y; box.width = t->getScale().x * dimensions.x; box.height = t->getScale().y * dimensions.y; */ rectangle.setOrigin( t->getOrigin() + gap); rectangle.setScale( t->getScale() ); rectangle.setPosition( t->getPosition() ); rectangle.setRotation( t->getRotation() ); } void BoxCollider::resize(const sf::Vector2f& newsize) { rectangle.setSize(newsize); } void BoxCollider::setGap(const sf::Vector2f& newgap) { gap = newgap; } BoxCollider::PTR BoxCollider::create(const sf::Vector2f& dimensions, const sf::Vector2f& gap, std::function<void(Collision)> fun) { return PTR(new BoxCollider(dimensions, gap, fun) ); } } <|endoftext|>
<commit_before>/* * C S O U N D V S T * * A VST plugin version of Csound, with Python scripting. * * L I C E N S E * * This software is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #ifndef CROSSPLATFORM_H #define CROSSPLATFORM_H #include "Platform.hpp" #ifdef SWIG %module CsoundAC %{ #include "CppSound.hpp" #include <string> #include <vector> #include <cstdarg> #include <ctime> %} #else #include "CppSound.hpp" #include <string> #include <vector> #include <cstdarg> #include <ctime> #endif namespace csound { class SILENCE_PUBLIC Logger { public: Logger(); virtual ~Logger(); virtual void write(const char *text); }; typedef void (*MessageCallbackType)(CSOUND *csound, int attribute, const char *format, va_list marker); /** * Abstraction layer for a minimal set of system services. */ class SILENCE_PUBLIC System { static void *userdata_; static int messageLevel; static void (*messageCallback)(CSOUND *csound, int attribute, const char *format, va_list valist); static FILE *logfile; public: enum Level { ERROR_LEVEL = 1, WARNING_LEVEL = 2, INFORMATION_LEVEL = 4, DEBUGGING_LEVEL = 8 }; /** * Parses a filename into its component parts, which are returned in the arguments. * On Unix and Linux, "drive" is always empty. */ static void parsePathname(const std::string pathname, std::string &drive, std::string &base, std::string &file, std::string &extension); /** * Opens a shared library; useful for loading plugins. */ static int openLibrary(void **library, std::string filename); /** * Returns the address of a symbol (function or object) in a shared library; * useful for loading plugin functions. */ static void *getSymbol(void *library, std::string name); /** * Closes a shared library. */ static void closeLibrary(void *library); /** * Lists filenames in a directory; * useful for locating plugins. */ static std::vector<std::string> getFilenames(std::string directoryName); /** * Lists directory names in a directory; * useful for locating plugins. */ static std::vector<std::string> getDirectoryNames(std::string directoryName); /** * Creates a new thread. */ static void *createThread(void (*threadRoutine)(void *threadData), void *data, int priority); /** * Creates a thread lock. */ static void *createThreadLock(); /** * Waits on a thread lock. * Zero timeout means infinite timeout. */ static void waitThreadLock(void *lock, size_t timeoutMilliseconds = 0); /** * Releases a thread lock. */ static void notifyThreadLock(void *lock); /** * Destroys a thread lock. */ static void destroyThreadLock(void *lock); /** * Sets message level, returns old message level. */ static int setMessageLevel(int messageLevel); /** * Yields to the next waiting thread. */ static void yieldThread(); /** * Returns current system message level. */ static int getMessageLevel(); /** * Sets userdata for message printing. */ static void setUserdata(void *userdata); /** * Returns userdata for message printing. */ static void *getUserdata(); /** * Set a stream for printing messages to * (in addition to callback, stderr, etc.). */ static void setLogfile(FILE *logfile); /** * Return the stream, if any, used for * printing messages to. */ static FILE *getLogfile(); #ifndef SWIG /** * Prints a message if the ERROR_LEVEL flag is set. */ static void error(CSOUND *csound, const char *format,...); /** * Prints a message if the ERROR_LEVEL flag is set. */ static void error(const char *format,...); /** * Prints a message if the WARNNING_LEVEL flag is set. */ static void warn(CSOUND *csound, const char *format,...); /** * Prints a message if the WARNNING_LEVEL flag is set. */ static void warn(const char *format,...); /** * Prints a message if the INFORMATION_LEVEL flag is set. */ static void inform(CSOUND *csound, const char *format,...); /** * Prints a message if the INFORMATION_LEVEL flag is set. */ static void inform(const char *format,...); /** * Prints a message if the DEBUGGING_LEVEL flag is set. */ static void debug(CSOUND *csound, const char *format,...); /** * Prints a message if the DEBUGGING_LEVEL flag is set. */ static void debug(const char *format,...); /** * Prints a message. */ static void message(CSOUND *csound, const char *format,...); /** * Prints a message. */ static void message(const char *format,...); /** * Prints a message. */ static void message(CSOUND *csound, const char *format, va_list valist); /** * Prints a message. */ PUBLIC static void message(const char *format, va_list valist); /** * Prints a message. */ static void message(CSOUND *csound, int level, const char *format,...); /** * Prints a message. */ static void message(CSOUND *csound, int attribute, const char *format, va_list valist); /** * Sets message callback. */ static void setMessageCallback(MessageCallbackType messageCallback_); /** * Return the message callback, or null if none. */ static MessageCallbackType getMessageCallback(); #endif /** * Execute a system command or program. */ static int execute(const char *command); /** * Open a file using the operating system shell. */ static int shellOpen(const char *filename, const char *command = "open"); /** * Returns the standard filename extension for a shared library, * such as "dll" or "so". */ static std::string getSharedLibraryExtension(); /** * Starts timing. */ static clock_t startTiming(); /** * Stop timing, and return elapsed seonds. */ static double stopTiming(clock_t startedAt); /** * Sleep the indicated number of milliseconds. */ static void sleep(double milliseconds); /** * Make some sort of noticeable sound. */ static void beep(); }; /** * Encapsulates a thread monitor, such as a Windows event handle. */ class SILENCE_PUBLIC ThreadLock { void *lock; public: ThreadLock(); virtual ~ThreadLock(); /** * Creates and initializes the monitor. * The monitor is in a non-notified or unsignaled state. */ virtual void open(); /** * Destroys the monitor. */ virtual void close(); /** * Returns whether the monitor is open. */ virtual bool isOpen(); /** * Waits until the monitor is notified by another thread. * Zero timeout means infinite timeout. */ virtual void startWait(size_t timeoutMilliseconds = 0); /** * Releases one thread that is waiting on the monitor. */ virtual void endWait(); }; } #endif <commit_msg>#ifdef for MSVC.<commit_after>/* * C S O U N D V S T * * A VST plugin version of Csound, with Python scripting. * * L I C E N S E * * This software is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #ifndef CROSSPLATFORM_H #define CROSSPLATFORM_H #include "Platform.hpp" #ifdef SWIG %module CsoundAC %{ #include "CppSound.hpp" #include <string> #include <vector> #include <cstdarg> #include <ctime> %} #else #include "CppSound.hpp" #include <string> #include <vector> #include <cstdarg> #include <ctime> #endif namespace csound { class SILENCE_PUBLIC Logger { public: Logger(); virtual ~Logger(); virtual void write(const char *text); }; typedef void (*MessageCallbackType)(CSOUND *csound, int attribute, const char *format, va_list marker); /** * Abstraction layer for a minimal set of system services. */ class SILENCE_PUBLIC System { static void *userdata_; static int messageLevel; static void (*messageCallback)(CSOUND *csound, int attribute, const char *format, va_list valist); static FILE *logfile; public: enum Level { ERROR_LEVEL = 1, WARNING_LEVEL = 2, INFORMATION_LEVEL = 4, DEBUGGING_LEVEL = 8 }; /** * Parses a filename into its component parts, which are returned in the arguments. * On Unix and Linux, "drive" is always empty. */ static void parsePathname(const std::string pathname, std::string &drive, std::string &base, std::string &file, std::string &extension); /** * Opens a shared library; useful for loading plugins. */ static int openLibrary(void **library, std::string filename); /** * Returns the address of a symbol (function or object) in a shared library; * useful for loading plugin functions. */ static void *getSymbol(void *library, std::string name); /** * Closes a shared library. */ static void closeLibrary(void *library); /** * Lists filenames in a directory; * useful for locating plugins. */ static std::vector<std::string> getFilenames(std::string directoryName); /** * Lists directory names in a directory; * useful for locating plugins. */ static std::vector<std::string> getDirectoryNames(std::string directoryName); /** * Creates a new thread. */ static void *createThread(void (*threadRoutine)(void *threadData), void *data, int priority); /** * Creates a thread lock. */ static void *createThreadLock(); /** * Waits on a thread lock. * Zero timeout means infinite timeout. */ static void waitThreadLock(void *lock, size_t timeoutMilliseconds = 0); /** * Releases a thread lock. */ static void notifyThreadLock(void *lock); /** * Destroys a thread lock. */ static void destroyThreadLock(void *lock); /** * Sets message level, returns old message level. */ static int setMessageLevel(int messageLevel); /** * Yields to the next waiting thread. */ static void yieldThread(); /** * Returns current system message level. */ static int getMessageLevel(); /** * Sets userdata for message printing. */ static void setUserdata(void *userdata); /** * Returns userdata for message printing. */ static void *getUserdata(); /** * Set a stream for printing messages to * (in addition to callback, stderr, etc.). */ static void setLogfile(FILE *logfile); /** * Return the stream, if any, used for * printing messages to. */ static FILE *getLogfile(); #ifndef SWIG /** * Prints a message if the ERROR_LEVEL flag is set. */ static void error(CSOUND *csound, const char *format,...); /** * Prints a message if the ERROR_LEVEL flag is set. */ static void error(const char *format,...); /** * Prints a message if the WARNNING_LEVEL flag is set. */ static void warn(CSOUND *csound, const char *format,...); /** * Prints a message if the WARNNING_LEVEL flag is set. */ static void warn(const char *format,...); /** * Prints a message if the INFORMATION_LEVEL flag is set. */ static void inform(CSOUND *csound, const char *format,...); /** * Prints a message if the INFORMATION_LEVEL flag is set. */ static void inform(const char *format,...); /** * Prints a message if the DEBUGGING_LEVEL flag is set. */ static void debug(CSOUND *csound, const char *format,...); /** * Prints a message if the DEBUGGING_LEVEL flag is set. */ static void debug(const char *format,...); /** * Prints a message. */ static void message(CSOUND *csound, const char *format,...); /** * Prints a message. */ static void message(const char *format,...); /** * Prints a message. */ static void message(CSOUND *csound, const char *format, va_list valist); /** * Prints a message. */ #if defined(_MSC_VER) static void message(const char *format, va_list valist); #else PUBLIC static void message(const char *format, va_list valist); #endif /** * Prints a message. */ static void message(CSOUND *csound, int level, const char *format,...); /** * Prints a message. */ static void message(CSOUND *csound, int attribute, const char *format, va_list valist); /** * Sets message callback. */ static void setMessageCallback(MessageCallbackType messageCallback_); /** * Return the message callback, or null if none. */ static MessageCallbackType getMessageCallback(); #endif /** * Execute a system command or program. */ static int execute(const char *command); /** * Open a file using the operating system shell. */ static int shellOpen(const char *filename, const char *command = "open"); /** * Returns the standard filename extension for a shared library, * such as "dll" or "so". */ static std::string getSharedLibraryExtension(); /** * Starts timing. */ static clock_t startTiming(); /** * Stop timing, and return elapsed seonds. */ static double stopTiming(clock_t startedAt); /** * Sleep the indicated number of milliseconds. */ static void sleep(double milliseconds); /** * Make some sort of noticeable sound. */ static void beep(); }; /** * Encapsulates a thread monitor, such as a Windows event handle. */ class SILENCE_PUBLIC ThreadLock { void *lock; public: ThreadLock(); virtual ~ThreadLock(); /** * Creates and initializes the monitor. * The monitor is in a non-notified or unsignaled state. */ virtual void open(); /** * Destroys the monitor. */ virtual void close(); /** * Returns whether the monitor is open. */ virtual bool isOpen(); /** * Waits until the monitor is notified by another thread. * Zero timeout means infinite timeout. */ virtual void startWait(size_t timeoutMilliseconds = 0); /** * Releases one thread that is waiting on the monitor. */ virtual void endWait(); }; } #endif <|endoftext|>
<commit_before>// Copyright (c) 2011-2014 The Bitcoin Core developers // Copyright (c) 2019 The PIVX developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. // // Unit tests for denial-of-service detection/prevention code // #include "test/test_pivx.h" #include "arith_uint256.h" #include "keystore.h" #include "net_processing.h" #include "net.h" #include "pubkey.h" #include "pow.h" #include "script/sign.h" #include "serialize.h" #include "util/system.h" #include "validation.h" #include <stdint.h> #include <boost/test/unit_test.hpp> // Tests this internal-to-validation.cpp method: extern bool AddOrphanTx(const CTransactionRef& tx, NodeId peer); extern void EraseOrphansFor(NodeId peer); extern unsigned int LimitOrphanTxSize(unsigned int nMaxOrphans); struct COrphanTx { CTransactionRef tx; NodeId fromPeer; int64_t nTimeExpire; }; extern RecursiveMutex g_cs_orphans; extern std::map<uint256, COrphanTx> mapOrphanTransactions GUARDED_BY(g_cs_orphans); CService ip(uint32_t i) { struct in_addr s; s.s_addr = i; return CService(CNetAddr(s), Params().GetDefaultPort()); } static NodeId id = 0; BOOST_FIXTURE_TEST_SUITE(DoS_tests, TestingSetup) void misbehave(NodeId id, int value) { LOCK(cs_main); Misbehaving(id, value); // Should get banned } BOOST_AUTO_TEST_CASE(DoS_banning) { std::atomic<bool> interruptDummy(false); connman->ClearBanned(); CAddress addr1(ip(0xa0b0c001), NODE_NONE); CNode dummyNode1(id++, NODE_NETWORK, 0, INVALID_SOCKET, addr1, 0, 0, "", true); dummyNode1.SetSendVersion(PROTOCOL_VERSION); peerLogic->InitializeNode(&dummyNode1); dummyNode1.nVersion = 1; dummyNode1.fSuccessfullyConnected = true; misbehave(dummyNode1.GetId(), 100); // Should get banned peerLogic->SendMessages(&dummyNode1, interruptDummy); BOOST_CHECK(connman->IsBanned(addr1)); BOOST_CHECK(!connman->IsBanned(ip(0xa0b0c001|0x0000ff00))); // Different IP, not banned CAddress addr2(ip(0xa0b0c002), NODE_NONE); CNode dummyNode2(id++, NODE_NETWORK, 0, INVALID_SOCKET, addr2, 1, 1, "", true); dummyNode2.SetSendVersion(PROTOCOL_VERSION); peerLogic->InitializeNode(&dummyNode2); dummyNode2.nVersion = 1; dummyNode2.fSuccessfullyConnected = true; misbehave(dummyNode2.GetId(), 50); peerLogic->SendMessages(&dummyNode2, interruptDummy); BOOST_CHECK(!connman->IsBanned(addr2)); // 2 not banned yet... BOOST_CHECK(connman->IsBanned(addr1)); // ... but 1 still should be misbehave(dummyNode2.GetId(), 50); peerLogic->SendMessages(&dummyNode2, interruptDummy); BOOST_CHECK(connman->IsBanned(addr2)); } BOOST_AUTO_TEST_CASE(DoS_banscore) { std::atomic<bool> interruptDummy(false); connman->ClearBanned(); gArgs.ForceSetArg("-banscore", "111"); // because 11 is my favorite number CAddress addr1(ip(0xa0b0c001), NODE_NONE); CNode dummyNode1(id++, NODE_NETWORK, 0, INVALID_SOCKET, addr1, 3, 1, "", true); dummyNode1.SetSendVersion(PROTOCOL_VERSION); peerLogic->InitializeNode(&dummyNode1); dummyNode1.nVersion = 1; dummyNode1.fSuccessfullyConnected = true; misbehave(dummyNode1.GetId(), 100); peerLogic->SendMessages(&dummyNode1, interruptDummy); BOOST_CHECK(!connman->IsBanned(addr1)); misbehave(dummyNode1.GetId(), 10); peerLogic->SendMessages(&dummyNode1, interruptDummy); BOOST_CHECK(!connman->IsBanned(addr1)); misbehave(dummyNode1.GetId(), 1); peerLogic->SendMessages(&dummyNode1, interruptDummy); BOOST_CHECK(connman->IsBanned(addr1)); gArgs.ForceSetArg("-banscore", std::to_string(DEFAULT_BANSCORE_THRESHOLD)); } BOOST_AUTO_TEST_CASE(DoS_bantime) { std::atomic<bool> interruptDummy(false); connman->ClearBanned(); int64_t nStartTime = GetTime(); SetMockTime(nStartTime); // Overrides future calls to GetTime() CAddress addr(ip(0xa0b0c001), NODE_NONE); CNode dummyNode(id++, NODE_NETWORK, 0, INVALID_SOCKET, addr, 4, 4, "", true); dummyNode.SetSendVersion(PROTOCOL_VERSION); peerLogic->InitializeNode(&dummyNode); dummyNode.nVersion = 1; dummyNode.fSuccessfullyConnected = true; misbehave(dummyNode.GetId(), 100); peerLogic->SendMessages(&dummyNode, interruptDummy); BOOST_CHECK(connman->IsBanned(addr)); SetMockTime(nStartTime+60*60); BOOST_CHECK(connman->IsBanned(addr)); SetMockTime(nStartTime+60*60*24+1); BOOST_CHECK(!connman->IsBanned(addr)); } CTransactionRef RandomOrphan() { std::map<uint256, COrphanTx>::iterator it; LOCK2(cs_main, g_cs_orphans); it = mapOrphanTransactions.lower_bound(InsecureRand256()); if (it == mapOrphanTransactions.end()) it = mapOrphanTransactions.begin(); return it->second.tx; } static void MakeNewKeyWithFastRandomContext(CKey& key) { std::vector<unsigned char> keydata; keydata = insecure_rand_ctx.randbytes(32); key.Set(keydata.data(), keydata.data() + keydata.size(), /*fCompressedIn*/ true); assert(key.IsValid()); } BOOST_AUTO_TEST_CASE(DoS_mapOrphans) { // This test had non-deterministic coverage due to // randomly selected seeds. // This seed is chosen so that all branches of the function // ecdsa_signature_parse_der_lax are executed during this test. // Specifically branches that run only when an ECDSA // signature's R and S values have leading zeros. insecure_rand_ctx = FastRandomContext(ArithToUint256(arith_uint256(33))); CKey key; MakeNewKeyWithFastRandomContext(key); CBasicKeyStore keystore; keystore.AddKey(key); // 50 orphan transactions: for (int i = 0; i < 50; i++) { CMutableTransaction tx; tx.vin.resize(1); tx.vin[0].prevout.n = 0; tx.vin[0].prevout.hash = InsecureRand256(); tx.vin[0].scriptSig << OP_1; tx.vout.resize(1); tx.vout[0].nValue = 1*CENT; tx.vout[0].scriptPubKey = GetScriptForDestination(key.GetPubKey().GetID()); AddOrphanTx(MakeTransactionRef(tx), i); } // ... and 50 that depend on other orphans: for (int i = 0; i < 50; i++) { CTransactionRef txPrev = RandomOrphan(); CMutableTransaction tx; tx.vin.resize(1); tx.vin[0].prevout.n = 0; tx.vin[0].prevout.hash = txPrev->GetHash(); tx.vout.resize(1); tx.vout[0].nValue = 1*CENT; tx.vout[0].scriptPubKey = GetScriptForDestination(key.GetPubKey().GetID()); SignSignature(keystore, *txPrev, tx, 0, SIGHASH_ALL); AddOrphanTx(MakeTransactionRef(tx), i); } // This really-big orphan should be ignored: for (int i = 0; i < 10; i++) { CTransactionRef txPrev = RandomOrphan(); CMutableTransaction tx; tx.vout.resize(1); tx.vout[0].nValue = 1*CENT; tx.vout[0].scriptPubKey = GetScriptForDestination(key.GetPubKey().GetID()); tx.vin.resize(2777); for (unsigned int j = 0; j < tx.vin.size(); j++) { tx.vin[j].prevout.n = j; tx.vin[j].prevout.hash = txPrev->GetHash(); } SignSignature(keystore, *txPrev, tx, 0, SIGHASH_ALL); // Re-use same signature for other inputs // (they don't have to be valid for this test) for (unsigned int j = 1; j < tx.vin.size(); j++) tx.vin[j].scriptSig = tx.vin[0].scriptSig; BOOST_CHECK(!AddOrphanTx(MakeTransactionRef(tx), i)); } LOCK2(cs_main, g_cs_orphans); // Test EraseOrphansFor: for (NodeId i = 0; i < 3; i++) { size_t sizeBefore = mapOrphanTransactions.size(); EraseOrphansFor(i); BOOST_CHECK(mapOrphanTransactions.size() < sizeBefore); } // Test LimitOrphanTxSize() function: LimitOrphanTxSize(40); BOOST_CHECK(mapOrphanTransactions.size() <= 40); LimitOrphanTxSize(10); BOOST_CHECK(mapOrphanTransactions.size() <= 10); LimitOrphanTxSize(0); BOOST_CHECK(mapOrphanTransactions.empty()); } BOOST_AUTO_TEST_SUITE_END() <commit_msg>Test: Add missing SendMessages required cs locks<commit_after>// Copyright (c) 2011-2014 The Bitcoin Core developers // Copyright (c) 2019 The PIVX developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. // // Unit tests for denial-of-service detection/prevention code // #include "test/test_pivx.h" #include "arith_uint256.h" #include "keystore.h" #include "net_processing.h" #include "net.h" #include "pubkey.h" #include "pow.h" #include "script/sign.h" #include "serialize.h" #include "util/system.h" #include "validation.h" #include <stdint.h> #include <boost/test/unit_test.hpp> // Tests this internal-to-validation.cpp method: extern bool AddOrphanTx(const CTransactionRef& tx, NodeId peer); extern void EraseOrphansFor(NodeId peer); extern unsigned int LimitOrphanTxSize(unsigned int nMaxOrphans); struct COrphanTx { CTransactionRef tx; NodeId fromPeer; int64_t nTimeExpire; }; extern RecursiveMutex g_cs_orphans; extern std::map<uint256, COrphanTx> mapOrphanTransactions GUARDED_BY(g_cs_orphans); CService ip(uint32_t i) { struct in_addr s; s.s_addr = i; return CService(CNetAddr(s), Params().GetDefaultPort()); } static NodeId id = 0; BOOST_FIXTURE_TEST_SUITE(DoS_tests, TestingSetup) void misbehave(NodeId id, int value) { LOCK(cs_main); Misbehaving(id, value); // Should get banned } BOOST_AUTO_TEST_CASE(DoS_banning) { std::atomic<bool> interruptDummy(false); connman->ClearBanned(); CAddress addr1(ip(0xa0b0c001), NODE_NONE); CNode dummyNode1(id++, NODE_NETWORK, 0, INVALID_SOCKET, addr1, 0, 0, "", true); dummyNode1.SetSendVersion(PROTOCOL_VERSION); peerLogic->InitializeNode(&dummyNode1); dummyNode1.nVersion = 1; dummyNode1.fSuccessfullyConnected = true; misbehave(dummyNode1.GetId(), 100); // Should get banned { LOCK2(cs_main, dummyNode1.cs_sendProcessing); peerLogic->SendMessages(&dummyNode1, interruptDummy); } BOOST_CHECK(connman->IsBanned(addr1)); BOOST_CHECK(!connman->IsBanned(ip(0xa0b0c001|0x0000ff00))); // Different IP, not banned CAddress addr2(ip(0xa0b0c002), NODE_NONE); CNode dummyNode2(id++, NODE_NETWORK, 0, INVALID_SOCKET, addr2, 1, 1, "", true); dummyNode2.SetSendVersion(PROTOCOL_VERSION); peerLogic->InitializeNode(&dummyNode2); dummyNode2.nVersion = 1; dummyNode2.fSuccessfullyConnected = true; misbehave(dummyNode2.GetId(), 50); { LOCK2(cs_main, dummyNode2.cs_sendProcessing); peerLogic->SendMessages(&dummyNode2, interruptDummy); } BOOST_CHECK(!connman->IsBanned(addr2)); // 2 not banned yet... BOOST_CHECK(connman->IsBanned(addr1)); // ... but 1 still should be misbehave(dummyNode2.GetId(), 50); { LOCK2(cs_main, dummyNode2.cs_sendProcessing); peerLogic->SendMessages(&dummyNode2, interruptDummy); } BOOST_CHECK(connman->IsBanned(addr2)); } BOOST_AUTO_TEST_CASE(DoS_banscore) { std::atomic<bool> interruptDummy(false); connman->ClearBanned(); gArgs.ForceSetArg("-banscore", "111"); // because 11 is my favorite number CAddress addr1(ip(0xa0b0c001), NODE_NONE); CNode dummyNode1(id++, NODE_NETWORK, 0, INVALID_SOCKET, addr1, 3, 1, "", true); dummyNode1.SetSendVersion(PROTOCOL_VERSION); peerLogic->InitializeNode(&dummyNode1); dummyNode1.nVersion = 1; dummyNode1.fSuccessfullyConnected = true; misbehave(dummyNode1.GetId(), 100); { LOCK2(cs_main, dummyNode1.cs_sendProcessing); peerLogic->SendMessages(&dummyNode1, interruptDummy); } BOOST_CHECK(!connman->IsBanned(addr1)); misbehave(dummyNode1.GetId(), 10); { LOCK2(cs_main, dummyNode1.cs_sendProcessing); peerLogic->SendMessages(&dummyNode1, interruptDummy); } BOOST_CHECK(!connman->IsBanned(addr1)); misbehave(dummyNode1.GetId(), 1); { LOCK2(cs_main, dummyNode1.cs_sendProcessing); peerLogic->SendMessages(&dummyNode1, interruptDummy); } BOOST_CHECK(connman->IsBanned(addr1)); gArgs.ForceSetArg("-banscore", std::to_string(DEFAULT_BANSCORE_THRESHOLD)); } BOOST_AUTO_TEST_CASE(DoS_bantime) { std::atomic<bool> interruptDummy(false); connman->ClearBanned(); int64_t nStartTime = GetTime(); SetMockTime(nStartTime); // Overrides future calls to GetTime() CAddress addr(ip(0xa0b0c001), NODE_NONE); CNode dummyNode(id++, NODE_NETWORK, 0, INVALID_SOCKET, addr, 4, 4, "", true); dummyNode.SetSendVersion(PROTOCOL_VERSION); peerLogic->InitializeNode(&dummyNode); dummyNode.nVersion = 1; dummyNode.fSuccessfullyConnected = true; misbehave(dummyNode.GetId(), 100); { LOCK2(cs_main, dummyNode.cs_sendProcessing); peerLogic->SendMessages(&dummyNode, interruptDummy); } BOOST_CHECK(connman->IsBanned(addr)); SetMockTime(nStartTime+60*60); BOOST_CHECK(connman->IsBanned(addr)); SetMockTime(nStartTime+60*60*24+1); BOOST_CHECK(!connman->IsBanned(addr)); } CTransactionRef RandomOrphan() { std::map<uint256, COrphanTx>::iterator it; LOCK2(cs_main, g_cs_orphans); it = mapOrphanTransactions.lower_bound(InsecureRand256()); if (it == mapOrphanTransactions.end()) it = mapOrphanTransactions.begin(); return it->second.tx; } static void MakeNewKeyWithFastRandomContext(CKey& key) { std::vector<unsigned char> keydata; keydata = insecure_rand_ctx.randbytes(32); key.Set(keydata.data(), keydata.data() + keydata.size(), /*fCompressedIn*/ true); assert(key.IsValid()); } BOOST_AUTO_TEST_CASE(DoS_mapOrphans) { // This test had non-deterministic coverage due to // randomly selected seeds. // This seed is chosen so that all branches of the function // ecdsa_signature_parse_der_lax are executed during this test. // Specifically branches that run only when an ECDSA // signature's R and S values have leading zeros. insecure_rand_ctx = FastRandomContext(ArithToUint256(arith_uint256(33))); CKey key; MakeNewKeyWithFastRandomContext(key); CBasicKeyStore keystore; keystore.AddKey(key); // 50 orphan transactions: for (int i = 0; i < 50; i++) { CMutableTransaction tx; tx.vin.resize(1); tx.vin[0].prevout.n = 0; tx.vin[0].prevout.hash = InsecureRand256(); tx.vin[0].scriptSig << OP_1; tx.vout.resize(1); tx.vout[0].nValue = 1*CENT; tx.vout[0].scriptPubKey = GetScriptForDestination(key.GetPubKey().GetID()); AddOrphanTx(MakeTransactionRef(tx), i); } // ... and 50 that depend on other orphans: for (int i = 0; i < 50; i++) { CTransactionRef txPrev = RandomOrphan(); CMutableTransaction tx; tx.vin.resize(1); tx.vin[0].prevout.n = 0; tx.vin[0].prevout.hash = txPrev->GetHash(); tx.vout.resize(1); tx.vout[0].nValue = 1*CENT; tx.vout[0].scriptPubKey = GetScriptForDestination(key.GetPubKey().GetID()); SignSignature(keystore, *txPrev, tx, 0, SIGHASH_ALL); AddOrphanTx(MakeTransactionRef(tx), i); } // This really-big orphan should be ignored: for (int i = 0; i < 10; i++) { CTransactionRef txPrev = RandomOrphan(); CMutableTransaction tx; tx.vout.resize(1); tx.vout[0].nValue = 1*CENT; tx.vout[0].scriptPubKey = GetScriptForDestination(key.GetPubKey().GetID()); tx.vin.resize(2777); for (unsigned int j = 0; j < tx.vin.size(); j++) { tx.vin[j].prevout.n = j; tx.vin[j].prevout.hash = txPrev->GetHash(); } SignSignature(keystore, *txPrev, tx, 0, SIGHASH_ALL); // Re-use same signature for other inputs // (they don't have to be valid for this test) for (unsigned int j = 1; j < tx.vin.size(); j++) tx.vin[j].scriptSig = tx.vin[0].scriptSig; BOOST_CHECK(!AddOrphanTx(MakeTransactionRef(tx), i)); } LOCK2(cs_main, g_cs_orphans); // Test EraseOrphansFor: for (NodeId i = 0; i < 3; i++) { size_t sizeBefore = mapOrphanTransactions.size(); EraseOrphansFor(i); BOOST_CHECK(mapOrphanTransactions.size() < sizeBefore); } // Test LimitOrphanTxSize() function: LimitOrphanTxSize(40); BOOST_CHECK(mapOrphanTransactions.size() <= 40); LimitOrphanTxSize(10); BOOST_CHECK(mapOrphanTransactions.size() <= 10); LimitOrphanTxSize(0); BOOST_CHECK(mapOrphanTransactions.empty()); } BOOST_AUTO_TEST_SUITE_END() <|endoftext|>
<commit_before>// This file is part of the dune-gdt project: // http://users.dune-project.org/projects/dune-gdt // Copyright holders: Felix Schindler // License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause) #ifndef DUNE_GDT_PROLONGATIONS_HH #define DUNE_GDT_PROLONGATIONS_HH #include <vector> #include <limits> #include <boost/numeric/conversion/cast.hpp> #include <dune/common/dynmatrix.hh> #include <dune/stuff/common/type_utils.hh> #include <dune/stuff/common/vector.hh> #include <dune/stuff/functions/interfaces.hh> #include <dune/stuff/grid/boundaryinfo.hh> #include <dune/stuff/grid/intersection.hh> #include <dune/stuff/la/container.hh> #include <dune/stuff/la/solver.hh> #include <dune/geometry/quadraturerules.hh> #include <dune/stuff/grid/search.hh> #include <dune/gdt/exceptions.hh> #include <dune/gdt/discretefunction/default.hh> #include <dune/gdt/spaces/cg/fem.hh> #include <dune/gdt/spaces/cg/pdelab.hh> #include <dune/gdt/spaces/fv/defaultproduct.hh> namespace Dune { namespace GDT { namespace Spaces { namespace DG { template <class GridPartImp, int polynomialOrder, class RangeFieldImp, size_t rangeDim, size_t rangeDimCols> class FemBased; } template <class SpaceImp> class Block; } namespace Operators { /** * \note The automatic detection of the right integration order might fail, so you might want to specify * over_integrate. The reason is that in order to locally evaluate the source we first have to create a * quadrature, the correct order of wich we guess by taking the sources order on the first entity. * \note We would have liked to do something like this and match on implementations of SpaceInterface:\code template< class T, class VS, class GPR, int pR, class RR, size_t rR, size_t rCR, class VR > void apply(const ConstDiscreteFunction< SpaceInterface< T >, VS >& source, DiscreteFunction< Spaces::DG::FemBased< GPR, pR, RR, rR, rCR >, VR >& range) const { static_assert(Dune::AlwaysFalse< T >::value, "Not implemented for this combination of source and range!"); }\endcode * but that gave compile errors (the compiler just could not match the first argument for whatever reason). This * is why we need all combinations of spaces below which are just compile time checks and forwards. * * \todo refactor like projections, drop note above */ template <class GridViewType> class L2Prolongation { typedef typename GridViewType::template Codim<0>::Entity EntityType; typedef typename GridViewType::ctype DomainFieldType; static const size_t dimDomain = GridViewType::dimension; public: L2Prolongation(const GridViewType& grid_view) : grid_view_(grid_view) { } // Source: Spaces::CG::FemBased // Range: Spaces::DG::FemBased template <class GPS, int pS, class RS, size_t rS, size_t rCS, class VS, class GPR, int pR, class RR, size_t rR, size_t rCR, class VR> void apply(const ConstDiscreteFunction<Spaces::CG::FemBased<GPS, pS, RS, rS, rCS>, VS>& /*source*/, DiscreteFunction<Spaces::DG::FemBased<GPR, pR, RR, rR, rCR>, VR>& /*range*/) const { static_assert(Dune::AlwaysFalse<GPS>::value, "Not implemented for this combination of source and range!"); } template <class GPS, int pS, class R, size_t r, size_t rC, class VS, class GPR, int pR, class VR> inline void apply(const ConstDiscreteFunction<Spaces::CG::FemBased<GPS, pS, R, r, rC>, VS>& source, DiscreteFunction<Spaces::DG::FemBased<GPR, pR, R, r, rC>, VR>& range) const { prolong_onto_dg_fem_localfunctions_wrapper(source, range); } // Source: Spaces::DG::FemBased // Range: Spaces::DG::FemBased template <class GPS, int pS, class RS, size_t rS, size_t rCS, class VS, class GPR, int pR, class RR, size_t rR, size_t rCR, class VR> void apply(const ConstDiscreteFunction<Spaces::DG::FemBased<GPS, pS, RS, rS, rCS>, VS>& /*source*/, DiscreteFunction<Spaces::DG::FemBased<GPR, pR, RR, rR, rCR>, VR>& /*range*/) const { static_assert(Dune::AlwaysFalse<GPS>::value, "Not implemented for this combination of source and range!"); } template <class GPS, int pS, class R, size_t r, size_t rC, class VS, class GPR, int pR, class VR> inline void apply(const ConstDiscreteFunction<Spaces::DG::FemBased<GPS, pS, R, r, rC>, VS>& source, DiscreteFunction<Spaces::DG::FemBased<GPR, pR, R, r, rC>, VR>& range) const { prolong_onto_dg_fem_localfunctions_wrapper(source, range); } template <class GPS, int pS, class R, size_t r, size_t rC, class VS, class GPR, int pR, class VR> inline void apply(const ConstDiscreteFunction<Spaces::Block<Spaces::DG::FemBased<GPS, pS, R, r, rC>>, VS>& source, DiscreteFunction<Spaces::Block<Spaces::DG::FemBased<GPR, pR, R, r, rC>>, VR>& range) const { prolong_onto_dg_fem_localfunctions_wrapper(source, range); } template <class GPS, int pS, class R, size_t r, size_t rC, class VS, class GPR, int pR, class VR> inline void apply(const ConstDiscreteFunction<Spaces::Block<Spaces::DG::FemBased<GPS, pS, R, r, rC>>, VS>& source, DiscreteFunction<Spaces::DG::FemBased<GPR, pR, R, r, rC>, VR>& range) const { prolong_onto_dg_fem_localfunctions_wrapper(source, range); } template <class GVS, class RS, size_t rS, size_t rCS, class VS, class GVR, class RR, size_t rR, size_t rCR, class VR> inline void apply(const ConstDiscreteFunction<Spaces::FV::DefaultProduct<GVS, RS, rS, rCS>, VS>& source, DiscreteFunction<Spaces::FV::DefaultProduct<GVR, RR, rR, rCR>, VR>& range) const { prolong_onto_fv(source, range); } private: template <class SourceFunctionType, class RangeFunctionType> void prolong_onto_dg_fem_localfunctions_wrapper(const SourceFunctionType& source, RangeFunctionType& range) const { typedef typename RangeFunctionType::DomainType DomainType; typedef typename RangeFunctionType::RangeType RangeType; typedef typename RangeFunctionType::RangeFieldType RangeFieldType; typedef typename Stuff::LA::Container<RangeFieldType, Stuff::LA::default_dense_backend>::MatrixType LocalMatrixType; typedef typename Stuff::LA::Container<RangeFieldType, Stuff::LA::default_dense_backend>::VectorType LocalVectorType; // clear range.vector() *= 0.0; // create search in the source grid part typedef typename SourceFunctionType::SpaceType::GridViewType SourceGridViewType; typedef Stuff::Grid::EntityInlevelSearch<SourceGridViewType> EntitySearch; EntitySearch entity_search(source.space().grid_view()); // guess the polynomial order of the source by hoping that they are the same for all entities const size_t source_order = source.local_function(*source.space().grid_view().template begin<0>())->order(); // walk the grid RangeType source_value(0); std::vector<RangeType> basis_values(range.space().mapper().maxNumDofs()); const auto entity_it_end = grid_view_.template end<0>(); for (auto entity_it = grid_view_.template begin<0>(); entity_it != entity_it_end; ++entity_it) { // prepare const auto& entity = *entity_it; const auto local_basis = range.space().base_function_set(entity); auto local_range = range.local_discrete_function(entity); LocalMatrixType local_matrix(local_basis.size(), local_basis.size(), RangeFieldType(0)); LocalVectorType local_vector(local_basis.size(), RangeFieldType(0)); LocalVectorType local_DoFs(local_basis.size(), RangeFieldType(0)); // create quadrature const auto integrand_order = std::max(source_order, local_basis.order()) + local_basis.order(); const auto& quadrature = QuadratureRules<DomainFieldType, dimDomain>::rule(entity.type(), boost::numeric_cast<int>(integrand_order)); // get global quadrature points std::vector<DomainType> quadrature_points; for (const auto& quadrature_point : quadrature) quadrature_points.emplace_back(entity.geometry().global(quadrature_point.position())); // get source entities const auto source_entity_ptr_unique_ptrs = entity_search(quadrature_points); assert(source_entity_ptr_unique_ptrs.size() >= quadrature_points.size()); // loop over all quadrature points size_t pp = 0; for (const auto& quadrature_point : quadrature) { const auto local_point = quadrature_point.position(); const auto quadrature_weight = quadrature_point.weight(); const auto integration_element = entity.geometry().integrationElement(local_point); // evaluate source const auto& source_entity_ptr_unique_ptr = source_entity_ptr_unique_ptrs[pp]; if (source_entity_ptr_unique_ptr) { const auto source_entity_ptr = *source_entity_ptr_unique_ptr; const auto& source_entity = *source_entity_ptr; const auto local_source = source.local_function(source_entity); local_source->evaluate(source_entity.geometry().local(entity.geometry().global(local_point)), source_value); } else source_value *= 0.0; // evaluate local_basis.evaluate(local_point, basis_values); // compute integrals for (size_t ii = 0; ii < local_basis.size(); ++ii) { local_vector[ii] += integration_element * quadrature_weight * (source_value * basis_values[ii]); for (size_t jj = 0; jj < local_basis.size(); ++jj) { local_matrix.add_to_entry( ii, jj, integration_element * quadrature_weight * (basis_values[ii] * basis_values[jj])); } } ++pp; } // loop over all quadrature points // compute local DoFs try { Stuff::LA::Solver<LocalMatrixType>(local_matrix).apply(local_vector, local_DoFs); } catch (Stuff::Exceptions::linear_solver_failed& ee) { DUNE_THROW(Exceptions::prolongation_error, "L2 prolongation failed because a local matrix could not be inverted!\n\n" << "This was the original error: " << ee.what()); } // set local DoFs auto local_range_vector = local_range->vector(); assert(local_range_vector.size() == local_DoFs.size()); for (size_t ii = 0; ii < local_range_vector.size(); ++ii) local_range_vector.set(ii, local_DoFs.get_entry(ii)); } // walk the grid } // ... prolong_onto_dg_fem_localfunctions_wrapper(...) template <class SourceFunctionType, class RangeFunctionType> void prolong_onto_fv(const SourceFunctionType& source, RangeFunctionType& range) const { typedef typename RangeFunctionType::DomainType DomainType; typedef typename RangeFunctionType::RangeType RangeType; // create search in the source grid part typedef typename SourceFunctionType::SpaceType::GridViewType SourceGridViewType; typedef Stuff::Grid::EntityInlevelSearch<SourceGridViewType> EntitySearch; EntitySearch entity_search(source.space().grid_view()); // walk the grid RangeType source_value(0); const auto entity_it_end = grid_view_.template end<0>(); for (auto entity_it = grid_view_.template begin<0>(); entity_it != entity_it_end; ++entity_it) { const auto& entity = *entity_it; auto local_range = range.local_discrete_function(entity); // get global quadrature points std::vector<DomainType> quadrature_points(1, entity.geometry().center()); // get source entities const auto source_entity_ptr_unique_ptrs = entity_search(quadrature_points); assert(source_entity_ptr_unique_ptrs.size() >= 1); const auto& source_entity_unique_ptr = source_entity_ptr_unique_ptrs[0]; if (source_entity_unique_ptr) { const auto source_entity_ptr = *source_entity_unique_ptr; const auto local_source = source.local_function(*source_entity_ptr); local_source->evaluate(source_entity_ptr->geometry().local(entity.geometry().center()), source_value); } else source_value *= 0.0; // set local DoFs auto local_range_vector = local_range->vector(); assert(local_range_vector.size() == RangeFunctionType::dimRange); for (size_t ii = 0; ii < RangeFunctionType::dimRange; ++ii) local_range_vector.set(ii, source_value[ii]); } // walk the grid } // ... prolong_onto_fv(...) const GridViewType& grid_view_; }; // class L2Prolongation /** * \note We would have liked to do something like this and match on implementations of SpaceInterface:\code template< class T, class VS, class GPR, int pR, class RR, size_t rR, size_t rCR, class VR > void apply(const ConstDiscreteFunction< SpaceInterface< T >, VS >& source, DiscreteFunction< Spaces::CG::FemBased< GPR, pR, RR, rR, rCR >, VR >& range) const { static_assert(Dune::AlwaysFalse< T >::value, "Not implemented for this combination of source and range!"); }\endcode * but that gave compile errors (the compiler just could not match the first argument for whatever reason). This * is why we need all combinations of spaces below which are just compile time checks and forwards. * * \todo refactor like projections, drop note above */ template <class GridViewType> class LagrangeProlongation { public: typedef typename GridViewType::ctype DomainFieldType; static const size_t dimDomain = GridViewType::dimension; LagrangeProlongation(const GridViewType& grid_view) : grid_view_(grid_view) { } // Source: Spaces::CG::FemBased // Range: Spaces::CG::FemBased template <class GPS, int pS, class RS, size_t rS, size_t rCS, class VS, class GPR, int pR, class RR, size_t rR, size_t rCR, class VR> void apply(const ConstDiscreteFunction<Spaces::CG::FemBased<GPS, pS, RS, rS, rCS>, VS>& /*source*/, DiscreteFunction<Spaces::CG::FemBased<GPR, pR, RR, rR, rCR>, VR>& /*range*/) const { static_assert(Dune::AlwaysFalse<GPS>::value, "Not implemented for this combination of source and range!"); } template <class GPS, int pS, class R, size_t r, class VS, class GPR, int pR, class VR> inline void apply(const ConstDiscreteFunction<Spaces::CG::FemBased<GPS, pS, R, r, 1>, VS>& source, DiscreteFunction<Spaces::CG::FemBased<GPR, pR, R, r, 1>, VR>& range) const { redirect_to_appropriate_apply(source, range); } // Source: Spaces::DG::FemBased // Range: Spaces::CG::FemBased template <class GPS, int pS, class RS, size_t rS, size_t rCS, class VS, class GPR, int pR, class RR, size_t rR, size_t rCR, class VR> void apply(const ConstDiscreteFunction<Spaces::DG::FemBased<GPS, pS, RS, rS, rCS>, VS>& /*source*/, DiscreteFunction<Spaces::CG::FemBased<GPR, pR, RR, rR, rCR>, VR>& /*range*/) const { static_assert(Dune::AlwaysFalse<GPS>::value, "Not implemented for this combination of source and range!"); } template <class GPS, int pS, class R, size_t r, class VS, class GPR, int pR, class VR> inline void apply(const ConstDiscreteFunction<Spaces::DG::FemBased<GPS, pS, R, r, 1>, VS>& source, DiscreteFunction<Spaces::CG::FemBased<GPR, pR, R, r, 1>, VR>& range) const { redirect_to_appropriate_apply(source, range); } // Source: Spaces::CG::PdelabBased // Range: Spaces::CG::PdelabBased template <class GPS, int pS, class RS, size_t rS, size_t rCS, class VS, class GPR, int pR, class RR, size_t rR, size_t rCR, class VR> void apply(const ConstDiscreteFunction<Spaces::CG::PdelabBased<GPS, pS, RS, rS, rCS>, VS>& /*source*/, DiscreteFunction<Spaces::CG::PdelabBased<GPR, pR, RR, rR, rCR>, VR>& /*range*/) const { static_assert(Dune::AlwaysFalse<GPS>::value, "Not implemented for this combination of source and range!"); } template <class GPS, int pS, class R, size_t r, size_t rC, class VS, class GPR, class VR> inline void apply(const ConstDiscreteFunction<Spaces::CG::PdelabBased<GPS, pS, R, r, rC>, VS>& source, DiscreteFunction<Spaces::CG::PdelabBased<GPR, 1, R, r, rC>, VR>& range) const { redirect_to_appropriate_apply(source, range); } private: template <class SourceType, class RangeType> void redirect_to_appropriate_apply(const SourceType& source, RangeType& range) const { // create search in the source grid part typedef typename SourceType::SpaceType::GridViewType SourceGridViewType; typedef Stuff::Grid::EntityInlevelSearch<SourceGridViewType> EntitySearch; EntitySearch entity_search(source.space().grid_view()); // set all range dofs to infinity const auto infinity = std::numeric_limits<typename RangeType::RangeFieldType>::infinity(); for (size_t ii = 0; ii < range.vector().size(); ++ii) range.vector().set_entry(ii, infinity); // walk the grid const auto entity_it_end = grid_view_.template end<0>(); for (auto entity_it = grid_view_.template begin<0>(); entity_it != entity_it_end; ++entity_it) { const auto& entity = *entity_it; // get global lagrange point coordinates const auto lagrange_point_set = range.space().lagrange_points(entity); typedef FieldVector<typename SourceGridViewType::ctype, SourceGridViewType::dimension> DomainType; std::vector<DomainType> lagrange_points(lagrange_point_set.size()); for (size_t ii = 0; ii < lagrange_point_set.size(); ++ii) lagrange_points[ii] = entity.geometry().global(lagrange_point_set[ii]); // get source entities const auto source_entity_ptrs = entity_search(lagrange_points); assert(source_entity_ptrs.size() == lagrange_points.size()); // get range auto local_range = range.local_discrete_function(entity); auto local_range_DoF_vector = local_range->vector(); // do the actual work (see below) apply_local(source, lagrange_points, source_entity_ptrs, local_range_DoF_vector); } // walk the grid } // ... redirect_to_appropriate_apply(...) template <class SourceType, class LagrangePointsType, class EntityPointers, class LocalDoFVectorType> void apply_local(const SourceType& source, const LagrangePointsType& lagrange_points, const EntityPointers& source_entity_ptr_unique_ptrs, LocalDoFVectorType& range_DoF_vector) const { static const size_t dimRange = SourceType::dimRange; size_t kk = 0; assert(source_entity_ptr_unique_ptrs.size() >= lagrange_points.size()); for (size_t ii = 0; ii < lagrange_points.size(); ++ii) { if (std::isinf(range_DoF_vector.get(kk))) { const auto& global_point = lagrange_points[ii]; // evaluate source function const auto& source_entity_ptr_unique_ptr = source_entity_ptr_unique_ptrs[ii]; if (source_entity_ptr_unique_ptr) { const auto source_entity_ptr = *source_entity_ptr_unique_ptr; const auto& source_entity = *source_entity_ptr; const auto local_source_point = source_entity.geometry().local(global_point); const auto local_source = source.local_function(source_entity); const auto source_value = local_source->evaluate(local_source_point); for (size_t jj = 0; jj < dimRange; ++jj, ++kk) range_DoF_vector.set(kk, source_value[jj]); } else for (size_t jj = 0; jj < dimRange; ++jj, ++kk) range_DoF_vector.set(kk, 0.0); } else kk += dimRange; } } // ... apply_local(...) const GridViewType& grid_view_; }; // class LagrangeProlongation template <class GridViewType> class Prolongation { public: typedef typename GridViewType::ctype DomainFieldType; static const size_t dimDomain = GridViewType::dimension; Prolongation(const GridViewType& grid_view) : l2_prolongation_operator_(grid_view) , lagrange_prolongation_operator_(grid_view) { } template <class SourceType, class RangeType> void apply(const SourceType& source, RangeType& range) const { redirect_to_appropriate_operator(source, range); } private: template <class GPS, int pS, class RS, size_t rS, size_t rCS, class VS, class GPR, int pR, class RR, size_t rR, size_t rCR, class VR> inline void redirect_to_appropriate_operator(const ConstDiscreteFunction<Spaces::CG::FemBased<GPS, pS, RS, rS, rCS>, VS>& source, DiscreteFunction<Spaces::DG::FemBased<GPR, pR, RR, rR, rCR>, VR>& range) const { l2_prolongation_operator_.apply(source, range); } template <class GPS, int pS, class RS, size_t rS, size_t rCS, class VS, class GPR, int pR, class RR, size_t rR, size_t rCR, class VR> inline void redirect_to_appropriate_operator(const ConstDiscreteFunction<Spaces::DG::FemBased<GPS, pS, RS, rS, rCS>, VS>& source, DiscreteFunction<Spaces::DG::FemBased<GPR, pR, RR, rR, rCR>, VR>& range) const { l2_prolongation_operator_.apply(source, range); } template <class GPS, int pS, class RS, size_t rS, size_t rCS, class VS, class GPR, int pR, class RR, size_t rR, size_t rCR, class VR> inline void redirect_to_appropriate_operator( const ConstDiscreteFunction<Spaces::Block<Spaces::DG::FemBased<GPS, pS, RS, rS, rCS>>, VS>& source, DiscreteFunction<Spaces::Block<Spaces::DG::FemBased<GPR, pR, RR, rR, rCR>>, VR>& range) const { l2_prolongation_operator_.apply(source, range); } template <class GPS, int pS, class RS, size_t rS, size_t rCS, class VS, class GPR, int pR, class RR, size_t rR, size_t rCR, class VR> inline void redirect_to_appropriate_operator( const ConstDiscreteFunction<Spaces::Block<Spaces::DG::FemBased<GPS, pS, RS, rS, rCS>>, VS>& source, DiscreteFunction<Spaces::DG::FemBased<GPR, pR, RR, rR, rCR>, VR>& range) const { l2_prolongation_operator_.apply(source, range); } template <class GPS, int pS, class RS, size_t rS, size_t rCS, class VS, class GPR, int pR, class RR, size_t rR, size_t rCR, class VR> inline void redirect_to_appropriate_operator(const ConstDiscreteFunction<Spaces::CG::FemBased<GPS, pS, RS, rS, rCS>, VS>& source, DiscreteFunction<Spaces::CG::FemBased<GPR, pR, RR, rR, rCR>, VR>& range) const { lagrange_prolongation_operator_.apply(source, range); } template <class GPS, int pS, class RS, size_t rS, size_t rCS, class VS, class GPR, int pR, class RR, size_t rR, size_t rCR, class VR> inline void redirect_to_appropriate_operator(const ConstDiscreteFunction<Spaces::DG::FemBased<GPS, pS, RS, rS, rCS>, VS>& source, DiscreteFunction<Spaces::CG::FemBased<GPR, pR, RR, rR, rCR>, VR>& range) const { lagrange_prolongation_operator_.apply(source, range); } template <class GPS, int pS, class RS, size_t rS, size_t rCS, class VS, class GPR, int pR, class RR, size_t rR, size_t rCR, class VR> inline void redirect_to_appropriate_operator( const ConstDiscreteFunction<Spaces::CG::PdelabBased<GPS, pS, RS, rS, rCS>, VS>& source, DiscreteFunction<Spaces::CG::PdelabBased<GPR, pR, RR, rR, rCR>, VR>& range) const { lagrange_prolongation_operator_.apply(source, range); } template <class GVS, class RS, size_t rS, size_t rCS, class VS, class GVR, class RR, size_t rR, size_t rCR, class VR> inline void redirect_to_appropriate_operator( const ConstDiscreteFunction<Spaces::FV::DefaultProduct<GVS, RS, rS, rCS>, VS>& source, DiscreteFunction<Spaces::FV::DefaultProduct<GVR, RR, rR, rCR>, VR>& range) const { l2_prolongation_operator_.apply(source, range); } const L2Prolongation<GridViewType> l2_prolongation_operator_; const LagrangeProlongation<GridViewType> lagrange_prolongation_operator_; }; // class Prolongation template <class GridViewType, class SourceType, class RangeType> void prolong(const GridViewType& grid_view, const SourceType& source, RangeType& range) { const Prolongation<GridViewType> prolongation_operator(grid_view); prolongation_operator.apply(source, range); } template <class SourceType, class RangeType> void prolong(const SourceType& source, RangeType& range) { const Prolongation<typename RangeType::SpaceType::GridViewType> prolongation_operator(range.space().grid_view()); prolongation_operator.apply(source, range); } } // namespace Operators } // namespace GDT } // namespace Dune #endif // DUNE_GDT_PROLONGATIONS_HH <commit_msg>[prolongations] refactor<commit_after>// This file is part of the dune-gdt project: // http://users.dune-project.org/projects/dune-gdt // Copyright holders: Felix Schindler // License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause) #ifndef DUNE_GDT_PROLONGATIONS_HH #define DUNE_GDT_PROLONGATIONS_HH #include <dune/stuff/grid/layers.hh> #include <dune/gdt/discretefunction/default.hh> #include <dune/gdt/spaces/interface.hh> #include <dune/gdt/spaces/cg/interface.hh> #include "prolongations/l2.hh" #include "prolongations/lagrange.hh" namespace Dune { namespace GDT { template <class GridViewType, class SourceSpaceType, class SourceVectorType, class RangeSpaceType, class RangeVectorType> typename std::enable_if<Stuff::Grid::is_grid_layer<GridViewType>::value && is_cg_space<RangeSpaceType>::value, void>::type prolong(const GridViewType& grid_view, const ConstDiscreteFunction<SourceSpaceType, SourceVectorType>& source, DiscreteFunction<RangeSpaceType, RangeVectorType>& range, const size_t /*over_integrate*/ = 0) { prolong_lagrange(grid_view, source, range); } template <class GridViewType, class SourceSpaceType, class SourceVectorType, class RangeSpaceType, class RangeVectorType> typename std::enable_if<Stuff::Grid::is_grid_layer<GridViewType>::value && !is_cg_space<RangeSpaceType>::value, void>::type prolong(const GridViewType& grid_view, const ConstDiscreteFunction<SourceSpaceType, SourceVectorType>& source, DiscreteFunction<RangeSpaceType, RangeVectorType>& range, const size_t over_integrate = 0) { prolong_l2(grid_view, source, range, over_integrate); } template <class SourceSpaceType, class SourceVectorType, class RangeSpaceType, class RangeVectorType> typename std::enable_if<is_cg_space<RangeSpaceType>::value, void>::type prolong(const ConstDiscreteFunction<SourceSpaceType, SourceVectorType>& source, DiscreteFunction<RangeSpaceType, RangeVectorType>& range, const size_t /*over_integrate*/ = 0) { prolong_lagrange(source, range); } template <class SourceSpaceType, class SourceVectorType, class RangeSpaceType, class RangeVectorType> typename std::enable_if<!is_cg_space<RangeSpaceType>::value, void>::type prolong(const ConstDiscreteFunction<SourceSpaceType, SourceVectorType>& source, DiscreteFunction<RangeSpaceType, RangeVectorType>& range, const size_t over_integrate = 0) { prolong_l2(source, range, over_integrate); } } // namespace GDT } // namespace Dune #endif // DUNE_GDT_PROLONGATIONS_HH <|endoftext|>