text
stringlengths
54
60.6k
<commit_before>/** * @file TextPlot.cpp * * A simple console-based data plotter. * * This file is part of the Aquila DSP library. * Aquila is free software, licensed under the MIT/X11 License. A copy of * the license is provided with the library in the LICENSE file. * * @package Aquila * @version 3.0.0-dev * @author Zbigniew Siciarz * @date 2007-2013 * @license http://www.opensource.org/licenses/mit-license.php MIT * @since 3.0.0 */ #include "TextPlot.h" #include <boost/scoped_array.hpp> namespace Aquila { /** * Creates the plot object. * * @param title plot title (optional, default is "Data plot") * @param out where to output the plot data (default is std::cout) */ TextPlot::TextPlot(const std::string &title, std::ostream &out): m_title(title), m_out(out), m_width(64), m_height(16) { } /** * "Draws" the plot to the output stream. * * @param plot internal plot data */ void TextPlot::drawPlotMatrix(const PlotMatrixType &plot) { const std::size_t length = plot.size(); m_out << "\n" << m_title << "\n"; // output the plot data, flushing only at the end for (unsigned int y = 0; y < m_height; ++y) { for (unsigned int x = 0; x < length; ++x) { m_out << plot[x][y]; } m_out << "\n"; } m_out.flush(); } /** * A shorthand for plotting only the first half of magnitude spectrum. * * @param spectrum an array of complex numbers * @param length size of the spectrum (total, not half!) */ void TextPlot::plotSpectrum(Aquila::ComplexType spectrum[], std::size_t length) { boost::scoped_array<double> absSpectrum(new double[length/2]); for (std::size_t i = 0; i < length/2; ++i) { absSpectrum[i] = std::abs(spectrum[i]); } plot(absSpectrum.get(), length/2); } } <commit_msg>Using unique_ptr in TextPlot.<commit_after>/** * @file TextPlot.cpp * * A simple console-based data plotter. * * This file is part of the Aquila DSP library. * Aquila is free software, licensed under the MIT/X11 License. A copy of * the license is provided with the library in the LICENSE file. * * @package Aquila * @version 3.0.0-dev * @author Zbigniew Siciarz * @date 2007-2013 * @license http://www.opensource.org/licenses/mit-license.php MIT * @since 3.0.0 */ #include "TextPlot.h" #include <memory> namespace Aquila { /** * Creates the plot object. * * @param title plot title (optional, default is "Data plot") * @param out where to output the plot data (default is std::cout) */ TextPlot::TextPlot(const std::string &title, std::ostream &out): m_title(title), m_out(out), m_width(64), m_height(16) { } /** * "Draws" the plot to the output stream. * * @param plot internal plot data */ void TextPlot::drawPlotMatrix(const PlotMatrixType &plot) { const std::size_t length = plot.size(); m_out << "\n" << m_title << "\n"; // output the plot data, flushing only at the end for (unsigned int y = 0; y < m_height; ++y) { for (unsigned int x = 0; x < length; ++x) { m_out << plot[x][y]; } m_out << "\n"; } m_out.flush(); } /** * A shorthand for plotting only the first half of magnitude spectrum. * * @param spectrum an array of complex numbers * @param length size of the spectrum (total, not half!) */ void TextPlot::plotSpectrum(Aquila::ComplexType spectrum[], std::size_t length) { std::unique_ptr<double[]> absSpectrum(new double[length/2]); for (std::size_t i = 0; i < length/2; ++i) { absSpectrum[i] = std::abs(spectrum[i]); } plot(absSpectrum.get(), length/2); } } <|endoftext|>
<commit_before> #include "U8Gettext.h" #include <Arduino.h> #define ENSURE(condition) do { if (!(condition)) {Serial.println("ENSURE failed at: "#condition); while(1); } } while(0) #define SIZE_OF_ARRAY(array) (sizeof((array))/sizeof((array)[0])) #define PTR_OFFSET_BYTES(ptr, nBytes) ((void*)(((char *)(ptr)) + (nBytes))) #define PTR_OFFSET_BETWEEN(ptrBegin, ptrEnd) ((char*)(ptrEnd) - (char*)(ptrBegin)) extern const size_t gU8GettextLanguagesLength; extern const U8GettextLanguage gU8GettextLanguages[]; static const U8GettextLanguage * sLanguageInstance = NULL; const char *U8GettextSetLanguage(const char *language) { const char * oldLanguage = sU8GettextLanguage; sU8GettextLanguage = language; return oldLanguage; } const char *U8GettextGetLanguage() { if (sLanguageInstance) { return sLanguageInstance->language; } // If you have not set any langauge, it return empty string. So that // it won't cause program crash if any other function invoke this // function without set language. return ""; } const char *U8Gettext(const char *str) { uint16_t i = 0; const U8GettextTranslation *translation = NULL; if (!sLanguageInstance) { return str; } translation = sLanguageInstance->translations; for(i = 0; i < sLanguageInstance->translationCount; ++i, ++translation) { // Slowest way to find translation if(0 == strcmp(str, translation->msgId)) { return translation->msgStr; } } // Can't find any translations! return str; } <commit_msg>Search and set language instance during U8GettextSetLanguage<commit_after> #include "U8Gettext.h" #include <Arduino.h> #define ENSURE(condition) do { if (!(condition)) {Serial.println("ENSURE failed at: "#condition); while(1); } } while(0) #define SIZE_OF_ARRAY(array) (sizeof((array))/sizeof((array)[0])) #define PTR_OFFSET_BYTES(ptr, nBytes) ((void*)(((char *)(ptr)) + (nBytes))) #define PTR_OFFSET_BETWEEN(ptrBegin, ptrEnd) ((char*)(ptrEnd) - (char*)(ptrBegin)) extern const size_t gU8GettextLanguagesLength; extern const U8GettextLanguage gU8GettextLanguages[]; static const U8GettextLanguage * sLanguageInstance = NULL; const char *U8GettextSetLanguage(const char *language) { uint16_t i = 0; const char * oldLanguage = ""; const U8GettextLanguage * languageInstance = NULL; if (sLanguageInstance) { oldLanguage = sLanguageInstance->language; } languageInstance = gU8GettextLanguages; for(i = 0; i < gU8GettextLanguagesLength; ++i, ++languageInstance) { // Set the language instance by specific language if(0 == strcmp(language, languageInstance->language)) { sLanguageInstance = languageInstance; break; } } return oldLanguage; } const char *U8GettextGetLanguage() { if (sLanguageInstance) { return sLanguageInstance->language; } // If you have not set any langauge, it return empty string. So that // it won't cause program crash if any other function invoke this // function without set language. return ""; } const char *U8Gettext(const char *str) { uint16_t i = 0; const U8GettextTranslation *translation = NULL; if (!sLanguageInstance) { return str; } translation = sLanguageInstance->translations; for(i = 0; i < sLanguageInstance->translationCount; ++i, ++translation) { // Slowest way to find translation if(0 == strcmp(str, translation->msgId)) { return translation->msgStr; } } // Can't find any translations! return str; } <|endoftext|>
<commit_before>// Licensed to the Apache Software Foundation (ASF) under one // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <iostream> #include <queue> #include <string> #include <mesos/mesos.hpp> #include <mesos/executor/executor.hpp> #include <mesos/v1/executor.hpp> #include <mesos/v1/mesos.hpp> #include <process/clock.hpp> #include <process/defer.hpp> #include <process/delay.hpp> #include <process/id.hpp> #include <process/owned.hpp> #include <process/process.hpp> #include <stout/linkedhashmap.hpp> #include <stout/option.hpp> #include <stout/os.hpp> #include <stout/uuid.hpp> #include "internal/devolve.hpp" #include "internal/evolve.hpp" using mesos::executor::Call; using mesos::executor::Event; using mesos::v1::executor::Mesos; using process::Clock; using process::Owned; using std::cout; using std::cerr; using std::endl; using std::queue; using std::string; namespace mesos { namespace internal { class DefaultExecutor : public process::Process<DefaultExecutor> { public: DefaultExecutor( const FrameworkID& _frameworkId, const ExecutorID& _executorId) : ProcessBase(process::ID::generate("default-executor")), state(DISCONNECTED), launched(false), frameworkInfo(None()), frameworkId(_frameworkId), executorId(_executorId), taskGroup(None()) {} virtual ~DefaultExecutor() = default; void connected() { state = CONNECTED; doReliableRegistration(); } void disconnected() { state = DISCONNECTED; } void received(const Event& event) { cout << "Received " << event.type() << " event" << endl; switch (event.type()) { case Event::SUBSCRIBED: { cout << "Subscribed executor on " << event.subscribed().slave_info().hostname() << endl; frameworkInfo = event.subscribed().framework_info(); state = SUBSCRIBED; break; } case Event::LAUNCH: { cerr << "LAUNCH event is not supported" << endl; // Shut down because this is unexpected; `LAUNCH` event // should never go to the default executor. // // TODO(anand): Invoke `shutdown()`. break; } case Event::LAUNCH_GROUP: { launchGroup(event.launch_group().task_group()); break; } case Event::KILL: { killTask(event.kill().task_id()); break; } case Event::ACKNOWLEDGED: { // Remove the corresponding update. updates.erase(UUID::fromBytes(event.acknowledged().uuid()).get()); // Remove the corresponding task. tasks.erase(event.acknowledged().task_id()); break; } case Event::SHUTDOWN: { // TODO(anand): Implement this. break; } case Event::MESSAGE: { break; } case Event::ERROR: { cerr << "Error: " << event.error().message() << endl; break; } case Event::UNKNOWN: { LOG(WARNING) << "Received an UNKNOWN event and ignored"; break; } } } protected: virtual void initialize() { mesos.reset(new Mesos( ContentType::PROTOBUF, defer(self(), &Self::connected), defer(self(), &Self::disconnected), defer(self(), [this](queue<v1::executor::Event> events) { while(!events.empty()) { const v1::executor::Event& event = events.front(); received(devolve(event)); events.pop(); } }))); } void doReliableRegistration() { if (state == SUBSCRIBED || state == DISCONNECTED) { return; } Call call; call.set_type(Call::SUBSCRIBE); call.mutable_framework_id()->CopyFrom(frameworkId); call.mutable_executor_id()->CopyFrom(executorId); Call::Subscribe* subscribe = call.mutable_subscribe(); // Send all unacknowledged updates. foreach (const Call::Update& update, updates.values()) { subscribe->add_unacknowledged_updates()->MergeFrom(update); } // Send the unacknowledged tasks. foreach (const TaskInfo& task, tasks.values()) { subscribe->add_unacknowledged_tasks()->MergeFrom(task); } mesos->send(evolve(call)); delay(Seconds(1), self(), &Self::doReliableRegistration); } void launchGroup(const TaskGroupInfo& _taskGroup) { CHECK_EQ(SUBSCRIBED, state); if (launched) { foreach (const TaskInfo& task, _taskGroup.tasks()) { update( task.task_id(), TASK_FAILED, "Attempted to run multiple task groups using a " "\"default\" executor"); } return; } launched = true; taskGroup = _taskGroup; foreach (const TaskInfo& task, taskGroup->tasks()) { tasks[task.task_id()] = task; } // Send a TASK_RUNNING status update followed immediately by a // TASK_FINISHED update. // // TODO(anand): Eventually, we need to invoke the `LAUNCH_NESTED_CONTAINER` // call via the Agent API. foreach (const TaskInfo& task, taskGroup->tasks()) { update(task.task_id(), TASK_RUNNING); } } void killTask(const TaskID& taskId) { CHECK_EQ(SUBSCRIBED, state); cout << "Received kill for task '" << taskId << "'" << endl; // Send TASK_KILLED updates for all tasks in the group. // // TODO(vinod): We need to send `KILL_NESTED_CONTAINER` call to the Agent // API for each of the tasks and wait for `WAIT_NESTED_CONTAINER` responses. CHECK_SOME(taskGroup); // Should not get a `KILL` before `LAUNCH_GROUP`. foreach (const TaskInfo& task, taskGroup->tasks()) { update(task.task_id(), TASK_KILLED); } // TODO(qianzhang): Remove this hack since the executor now receives // acknowledgements for status updates. The executor can terminate // after it receives an ACK for a terminal status update. os::sleep(Seconds(1)); terminate(self()); } private: void update( const TaskID& taskId, const TaskState& state, const Option<string>& message = None()) { UUID uuid = UUID::random(); TaskStatus status; status.mutable_task_id()->CopyFrom(taskId); status.mutable_executor_id()->CopyFrom(executorId); status.set_state(state); status.set_source(TaskStatus::SOURCE_EXECUTOR); status.set_uuid(uuid.toBytes()); status.set_timestamp(Clock::now().secs()); if (message.isSome()) { status.set_message(message.get()); } // TODO(vinod): Implement health checks. status.set_healthy(true); Call call; call.set_type(Call::UPDATE); call.mutable_framework_id()->CopyFrom(frameworkId); call.mutable_executor_id()->CopyFrom(executorId); call.mutable_update()->mutable_status()->CopyFrom(status); // Capture the status update. updates[uuid] = call.update(); mesos->send(evolve(call)); } enum State { CONNECTED, DISCONNECTED, SUBSCRIBED } state; bool launched; Option<FrameworkInfo> frameworkInfo; const FrameworkID frameworkId; const ExecutorID executorId; Owned<Mesos> mesos; Option<TaskGroupInfo> taskGroup; LinkedHashMap<UUID, Call::Update> updates; // Unacknowledged updates. LinkedHashMap<TaskID, TaskInfo> tasks; // Unacknowledged tasks. }; } // namespace internal { } // namespace mesos { int main(int argc, char** argv) { mesos::FrameworkID frameworkId; mesos::ExecutorID executorId; Option<string> value = os::getenv("MESOS_FRAMEWORK_ID"); if (value.isNone()) { EXIT(EXIT_FAILURE) << "Expecting 'MESOS_FRAMEWORK_ID' to be set in the environment"; } frameworkId.set_value(value.get()); value = os::getenv("MESOS_EXECUTOR_ID"); if (value.isNone()) { EXIT(EXIT_FAILURE) << "Expecting 'MESOS_EXECUTOR_ID' to be set in the environment"; } executorId.set_value(value.get()); Owned<mesos::internal::DefaultExecutor> executor( new mesos::internal::DefaultExecutor( frameworkId, executorId)); process::spawn(executor.get()); process::wait(executor.get()); return EXIT_SUCCESS; } <commit_msg>Added support for reading agent API URL in default executor.<commit_after>// Licensed to the Apache Software Foundation (ASF) under one // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <iostream> #include <queue> #include <string> #include <mesos/mesos.hpp> #include <mesos/executor/executor.hpp> #include <mesos/v1/executor.hpp> #include <mesos/v1/mesos.hpp> #include <process/clock.hpp> #include <process/defer.hpp> #include <process/delay.hpp> #include <process/id.hpp> #include <process/owned.hpp> #include <process/process.hpp> #include <stout/linkedhashmap.hpp> #include <stout/option.hpp> #include <stout/os.hpp> #include <stout/uuid.hpp> #include "internal/devolve.hpp" #include "internal/evolve.hpp" using mesos::executor::Call; using mesos::executor::Event; using mesos::v1::executor::Mesos; using process::Clock; using process::Owned; using process::UPID; using process::http::URL; using std::cout; using std::cerr; using std::endl; using std::queue; using std::string; namespace mesos { namespace internal { class DefaultExecutor : public process::Process<DefaultExecutor> { public: DefaultExecutor( const FrameworkID& _frameworkId, const ExecutorID& _executorId, const ::URL& _agent) : ProcessBase(process::ID::generate("default-executor")), state(DISCONNECTED), launched(false), frameworkInfo(None()), frameworkId(_frameworkId), executorId(_executorId), taskGroup(None()), agent(_agent) {} virtual ~DefaultExecutor() = default; void connected() { state = CONNECTED; doReliableRegistration(); } void disconnected() { state = DISCONNECTED; } void received(const Event& event) { cout << "Received " << event.type() << " event" << endl; switch (event.type()) { case Event::SUBSCRIBED: { cout << "Subscribed executor on " << event.subscribed().slave_info().hostname() << endl; frameworkInfo = event.subscribed().framework_info(); state = SUBSCRIBED; break; } case Event::LAUNCH: { cerr << "LAUNCH event is not supported" << endl; // Shut down because this is unexpected; `LAUNCH` event // should never go to the default executor. // // TODO(anand): Invoke `shutdown()`. break; } case Event::LAUNCH_GROUP: { launchGroup(event.launch_group().task_group()); break; } case Event::KILL: { killTask(event.kill().task_id()); break; } case Event::ACKNOWLEDGED: { // Remove the corresponding update. updates.erase(UUID::fromBytes(event.acknowledged().uuid()).get()); // Remove the corresponding task. tasks.erase(event.acknowledged().task_id()); break; } case Event::SHUTDOWN: { // TODO(anand): Implement this. break; } case Event::MESSAGE: { break; } case Event::ERROR: { cerr << "Error: " << event.error().message() << endl; break; } case Event::UNKNOWN: { LOG(WARNING) << "Received an UNKNOWN event and ignored"; break; } } } protected: virtual void initialize() { mesos.reset(new Mesos( ContentType::PROTOBUF, defer(self(), &Self::connected), defer(self(), &Self::disconnected), defer(self(), [this](queue<v1::executor::Event> events) { while(!events.empty()) { const v1::executor::Event& event = events.front(); received(devolve(event)); events.pop(); } }))); } void doReliableRegistration() { if (state == SUBSCRIBED || state == DISCONNECTED) { return; } Call call; call.set_type(Call::SUBSCRIBE); call.mutable_framework_id()->CopyFrom(frameworkId); call.mutable_executor_id()->CopyFrom(executorId); Call::Subscribe* subscribe = call.mutable_subscribe(); // Send all unacknowledged updates. foreach (const Call::Update& update, updates.values()) { subscribe->add_unacknowledged_updates()->MergeFrom(update); } // Send the unacknowledged tasks. foreach (const TaskInfo& task, tasks.values()) { subscribe->add_unacknowledged_tasks()->MergeFrom(task); } mesos->send(evolve(call)); delay(Seconds(1), self(), &Self::doReliableRegistration); } void launchGroup(const TaskGroupInfo& _taskGroup) { CHECK_EQ(SUBSCRIBED, state); if (launched) { foreach (const TaskInfo& task, _taskGroup.tasks()) { update( task.task_id(), TASK_FAILED, "Attempted to run multiple task groups using a " "\"default\" executor"); } return; } launched = true; taskGroup = _taskGroup; foreach (const TaskInfo& task, taskGroup->tasks()) { tasks[task.task_id()] = task; } // Send a TASK_RUNNING status update followed immediately by a // TASK_FINISHED update. // // TODO(anand): Eventually, we need to invoke the `LAUNCH_NESTED_CONTAINER` // call via the Agent API. foreach (const TaskInfo& task, taskGroup->tasks()) { update(task.task_id(), TASK_RUNNING); } } void killTask(const TaskID& taskId) { CHECK_EQ(SUBSCRIBED, state); cout << "Received kill for task '" << taskId << "'" << endl; // Send TASK_KILLED updates for all tasks in the group. // // TODO(vinod): We need to send `KILL_NESTED_CONTAINER` call to the Agent // API for each of the tasks and wait for `WAIT_NESTED_CONTAINER` responses. CHECK_SOME(taskGroup); // Should not get a `KILL` before `LAUNCH_GROUP`. foreach (const TaskInfo& task, taskGroup->tasks()) { update(task.task_id(), TASK_KILLED); } // TODO(qianzhang): Remove this hack since the executor now receives // acknowledgements for status updates. The executor can terminate // after it receives an ACK for a terminal status update. os::sleep(Seconds(1)); terminate(self()); } private: void update( const TaskID& taskId, const TaskState& state, const Option<string>& message = None()) { UUID uuid = UUID::random(); TaskStatus status; status.mutable_task_id()->CopyFrom(taskId); status.mutable_executor_id()->CopyFrom(executorId); status.set_state(state); status.set_source(TaskStatus::SOURCE_EXECUTOR); status.set_uuid(uuid.toBytes()); status.set_timestamp(Clock::now().secs()); if (message.isSome()) { status.set_message(message.get()); } // TODO(vinod): Implement health checks. status.set_healthy(true); Call call; call.set_type(Call::UPDATE); call.mutable_framework_id()->CopyFrom(frameworkId); call.mutable_executor_id()->CopyFrom(executorId); call.mutable_update()->mutable_status()->CopyFrom(status); // Capture the status update. updates[uuid] = call.update(); mesos->send(evolve(call)); } enum State { CONNECTED, DISCONNECTED, SUBSCRIBED } state; bool launched; Option<FrameworkInfo> frameworkInfo; const FrameworkID frameworkId; const ExecutorID executorId; Owned<Mesos> mesos; Option<TaskGroupInfo> taskGroup; const ::URL agent; // Agent API URL. LinkedHashMap<UUID, Call::Update> updates; // Unacknowledged updates. LinkedHashMap<TaskID, TaskInfo> tasks; // Unacknowledged tasks. }; } // namespace internal { } // namespace mesos { int main(int argc, char** argv) { mesos::FrameworkID frameworkId; mesos::ExecutorID executorId; string scheme = "http"; // Default scheme. ::URL agent; Option<string> value = os::getenv("MESOS_FRAMEWORK_ID"); if (value.isNone()) { EXIT(EXIT_FAILURE) << "Expecting 'MESOS_FRAMEWORK_ID' to be set in the environment"; } frameworkId.set_value(value.get()); value = os::getenv("MESOS_EXECUTOR_ID"); if (value.isNone()) { EXIT(EXIT_FAILURE) << "Expecting 'MESOS_EXECUTOR_ID' to be set in the environment"; } executorId.set_value(value.get()); value = os::getenv("SSL_ENABLED"); if (value.isSome() && (value.get() == "1" || value.get() == "true")) { scheme = "https"; } value = os::getenv("MESOS_SLAVE_PID"); if (value.isNone()) { EXIT(EXIT_FAILURE) << "Expecting 'MESOS_SLAVE_PID' to be set in the environment"; } UPID upid(value.get()); CHECK(upid) << "Failed to parse MESOS_SLAVE_PID '" << value.get() << "'"; agent = ::URL( scheme, upid.address.ip, upid.address.port, upid.id + "/api/v1"); Owned<mesos::internal::DefaultExecutor> executor( new mesos::internal::DefaultExecutor( frameworkId, executorId, agent)); process::spawn(executor.get()); process::wait(executor.get()); return EXIT_SUCCESS; } <|endoftext|>
<commit_before>// Copyright (c) 2011 The LevelDB Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. See the AUTHORS file for names of contributors. #include "leveldb/db.h" #include <errno.h> #include <fcntl.h> #include <sys/stat.h> #include <sys/types.h> #include "leveldb/cache.h" #include "leveldb/env.h" #include "leveldb/table.h" #include "leveldb/write_batch.h" #include "db/db_impl.h" #include "db/filename.h" #include "db/log_format.h" #include "db/version_set.h" #include "util/logging.h" #include "util/testharness.h" #include "util/testutil.h" namespace leveldb { static const int kValueSize = 1000; class CorruptionTest { public: test::ErrorEnv env_; std::string dbname_; Cache* tiny_cache_; Options options_; DB* db_; CorruptionTest() { tiny_cache_ = NewLRUCache(100); options_.env = &env_; options_.block_cache = tiny_cache_; dbname_ = test::TmpDir() + "/db_test"; DestroyDB(dbname_, options_); db_ = NULL; options_.create_if_missing = true; Reopen(); options_.create_if_missing = false; } ~CorruptionTest() { delete db_; DestroyDB(dbname_, Options()); delete tiny_cache_; } Status TryReopen() { delete db_; db_ = NULL; return DB::Open(options_, dbname_, &db_); } void Reopen() { ASSERT_OK(TryReopen()); } void RepairDB() { delete db_; db_ = NULL; ASSERT_OK(::leveldb::RepairDB(dbname_, options_)); } void Build(int n) { std::string key_space, value_space; WriteBatch batch; for (int i = 0; i < n; i++) { //if ((i % 100) == 0) fprintf(stderr, "@ %d of %d\n", i, n); Slice key = Key(i, &key_space); batch.Clear(); batch.Put(key, Value(i, &value_space)); WriteOptions options; // Corrupt() doesn't work without this sync on windows; stat reports 0 for // the file size. if (i == n - 1) { options.sync = true; } ASSERT_OK(db_->Write(options, &batch)); } } void Check(int min_expected, int max_expected) { int next_expected = 0; int missed = 0; int bad_keys = 0; int bad_values = 0; int correct = 0; std::string value_space; Iterator* iter = db_->NewIterator(ReadOptions()); for (iter->SeekToFirst(); iter->Valid(); iter->Next()) { uint64_t key; Slice in(iter->key()); if (in == "" || in == "~") { // Ignore boundary keys. continue; } if (!ConsumeDecimalNumber(&in, &key) || !in.empty() || key < next_expected) { bad_keys++; continue; } missed += (key - next_expected); next_expected = key + 1; if (iter->value() != Value(key, &value_space)) { bad_values++; } else { correct++; } } delete iter; fprintf(stderr, "expected=%d..%d; got=%d; bad_keys=%d; bad_values=%d; missed=%d\n", min_expected, max_expected, correct, bad_keys, bad_values, missed); ASSERT_LE(min_expected, correct); ASSERT_GE(max_expected, correct); } void Corrupt(FileType filetype, int offset, int bytes_to_corrupt) { // Pick file to corrupt std::vector<std::string> filenames; ASSERT_OK(env_.GetChildren(dbname_, &filenames)); uint64_t number; FileType type; std::string fname; int picked_number = -1; for (size_t i = 0; i < filenames.size(); i++) { if (ParseFileName(filenames[i], &number, &type) && type == filetype && int(number) > picked_number) { // Pick latest file fname = dbname_ + "/" + filenames[i]; picked_number = number; } } ASSERT_TRUE(!fname.empty()) << filetype; struct stat sbuf; if (stat(fname.c_str(), &sbuf) != 0) { const char* msg = strerror(errno); ASSERT_TRUE(false) << fname << ": " << msg; } if (offset < 0) { // Relative to end of file; make it absolute if (-offset > sbuf.st_size) { offset = 0; } else { offset = sbuf.st_size + offset; } } if (offset > sbuf.st_size) { offset = sbuf.st_size; } if (offset + bytes_to_corrupt > sbuf.st_size) { bytes_to_corrupt = sbuf.st_size - offset; } // Do it std::string contents; Status s = ReadFileToString(Env::Default(), fname, &contents); ASSERT_TRUE(s.ok()) << s.ToString(); for (int i = 0; i < bytes_to_corrupt; i++) { contents[i + offset] ^= 0x80; } s = WriteStringToFile(Env::Default(), contents, fname); ASSERT_TRUE(s.ok()) << s.ToString(); } int Property(const std::string& name) { std::string property; int result; if (db_->GetProperty(name, &property) && sscanf(property.c_str(), "%d", &result) == 1) { return result; } else { return -1; } } // Return the ith key Slice Key(int i, std::string* storage) { char buf[100]; snprintf(buf, sizeof(buf), "%016d", i); storage->assign(buf, strlen(buf)); return Slice(*storage); } // Return the value to associate with the specified key Slice Value(int k, std::string* storage) { Random r(k); return test::RandomString(&r, kValueSize, storage); } }; TEST(CorruptionTest, Recovery) { Build(100); Check(100, 100); Corrupt(kLogFile, 19, 1); // WriteBatch tag for first record Corrupt(kLogFile, log::kBlockSize + 1000, 1); // Somewhere in second block Reopen(); // The 64 records in the first two log blocks are completely lost. Check(36, 36); } TEST(CorruptionTest, RecoverWriteError) { env_.writable_file_error_ = true; Status s = TryReopen(); ASSERT_TRUE(!s.ok()); } TEST(CorruptionTest, NewFileErrorDuringWrite) { // Do enough writing to force minor compaction env_.writable_file_error_ = true; const int num = 3 + (Options().write_buffer_size / kValueSize); std::string value_storage; Status s; for (int i = 0; s.ok() && i < num; i++) { WriteBatch batch; batch.Put("a", Value(100, &value_storage)); s = db_->Write(WriteOptions(), &batch); } ASSERT_TRUE(!s.ok()); ASSERT_GE(env_.num_writable_file_errors_, 1); env_.writable_file_error_ = false; Reopen(); } TEST(CorruptionTest, TableFile) { Build(100); DBImpl* dbi = reinterpret_cast<DBImpl*>(db_); dbi->TEST_CompactMemTable(); dbi->TEST_CompactRange(0, NULL, NULL); dbi->TEST_CompactRange(1, NULL, NULL); Corrupt(kTableFile, 100, 1); Check(90, 99); } TEST(CorruptionTest, TableFileRepair) { options_.block_size = 2 * kValueSize; // Limit scope of corruption options_.paranoid_checks = true; Reopen(); Build(100); DBImpl* dbi = reinterpret_cast<DBImpl*>(db_); dbi->TEST_CompactMemTable(); dbi->TEST_CompactRange(0, NULL, NULL); dbi->TEST_CompactRange(1, NULL, NULL); Corrupt(kTableFile, 100, 1); RepairDB(); Reopen(); Check(95, 99); } TEST(CorruptionTest, TableFileIndexData) { Build(10000); // Enough to build multiple Tables DBImpl* dbi = reinterpret_cast<DBImpl*>(db_); dbi->TEST_CompactMemTable(); Corrupt(kTableFile, -2000, 500); Reopen(); Check(5000, 1983); } TEST(CorruptionTest, MissingDescriptor) { Build(1000); RepairDB(); Reopen(); Check(1000, 1000); } TEST(CorruptionTest, SequenceNumberRecovery) { ASSERT_OK(db_->Put(WriteOptions(), "foo", "v1")); ASSERT_OK(db_->Put(WriteOptions(), "foo", "v2")); ASSERT_OK(db_->Put(WriteOptions(), "foo", "v3")); ASSERT_OK(db_->Put(WriteOptions(), "foo", "v4")); ASSERT_OK(db_->Put(WriteOptions(), "foo", "v5")); RepairDB(); Reopen(); std::string v; ASSERT_OK(db_->Get(ReadOptions(), "foo", &v)); ASSERT_EQ("v5", v); // Write something. If sequence number was not recovered properly, // it will be hidden by an earlier write. ASSERT_OK(db_->Put(WriteOptions(), "foo", "v6")); ASSERT_OK(db_->Get(ReadOptions(), "foo", &v)); ASSERT_EQ("v6", v); Reopen(); ASSERT_OK(db_->Get(ReadOptions(), "foo", &v)); ASSERT_EQ("v6", v); } TEST(CorruptionTest, CorruptedDescriptor) { ASSERT_OK(db_->Put(WriteOptions(), "foo", "hello")); DBImpl* dbi = reinterpret_cast<DBImpl*>(db_); dbi->TEST_CompactMemTable(); dbi->TEST_CompactRange(0, NULL, NULL); Corrupt(kDescriptorFile, 0, 1000); Status s = TryReopen(); ASSERT_TRUE(!s.ok()); RepairDB(); Reopen(); std::string v; ASSERT_OK(db_->Get(ReadOptions(), "foo", &v)); ASSERT_EQ("hello", v); } TEST(CorruptionTest, CompactionInputError) { Build(10); DBImpl* dbi = reinterpret_cast<DBImpl*>(db_); dbi->TEST_CompactMemTable(); const int last = config::kMaxMemCompactLevel; ASSERT_EQ(1, Property("leveldb.num-files-at-level" + NumberToString(last))); Corrupt(kTableFile, 100, 1); Check(5, 9); // Force compactions by writing lots of values Build(10000); Check(10000, 10000); } TEST(CorruptionTest, CompactionInputErrorParanoid) { options_.paranoid_checks = true; options_.write_buffer_size = 512 << 10; Reopen(); DBImpl* dbi = reinterpret_cast<DBImpl*>(db_); // Make multiple inputs so we need to compact. for (int i = 0; i < 2; i++) { Build(10); dbi->TEST_CompactMemTable(); Corrupt(kTableFile, 100, 1); env_.SleepForMicroseconds(100000); } dbi->CompactRange(NULL, NULL); // Write must fail because of corrupted table std::string tmp1, tmp2; Status s = db_->Put(WriteOptions(), Key(5, &tmp1), Value(5, &tmp2)); ASSERT_TRUE(!s.ok()) << "write did not fail in corrupted paranoid db"; } TEST(CorruptionTest, UnrelatedKeys) { Build(10); DBImpl* dbi = reinterpret_cast<DBImpl*>(db_); dbi->TEST_CompactMemTable(); Corrupt(kTableFile, 100, 1); std::string tmp1, tmp2; ASSERT_OK(db_->Put(WriteOptions(), Key(1000, &tmp1), Value(1000, &tmp2))); std::string v; ASSERT_OK(db_->Get(ReadOptions(), Key(1000, &tmp1), &v)); ASSERT_EQ(Value(1000, &tmp2).ToString(), v); dbi->TEST_CompactMemTable(); ASSERT_OK(db_->Get(ReadOptions(), Key(1000, &tmp1), &v)); ASSERT_EQ(Value(1000, &tmp2).ToString(), v); } } // namespace leveldb int main(int argc, char** argv) { return leveldb::test::RunAllTests(); } <commit_msg>Update corruption_test.cc<commit_after>// Copyright (c) 2011 The LevelDB Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. See the AUTHORS file for names of contributors. #include "leveldb/db.h" #include <errno.h> #include <fcntl.h> #include <sys/stat.h> #include <sys/types.h> #include "leveldb/cache.h" #include "leveldb/env.h" #include "leveldb/table.h" #include "leveldb/write_batch.h" #include "db/db_impl.h" #include "db/filename.h" #include "db/log_format.h" #include "db/version_set.h" #include "util/logging.h" #include "util/testharness.h" #include "util/testutil.h" namespace leveldb { static const int kValueSize = 1000; class CorruptionTest { public: test::ErrorEnv env_; std::string dbname_; Cache* tiny_cache_; Options options_; DB* db_; CorruptionTest() { tiny_cache_ = NewLRUCache(100); options_.env = &env_; options_.block_cache = tiny_cache_; dbname_ = test::TmpDir() + "/db_test"; DestroyDB(dbname_, options_); db_ = NULL; options_.create_if_missing = true; Reopen(); options_.create_if_missing = false; } ~CorruptionTest() { delete db_; DestroyDB(dbname_, Options()); delete tiny_cache_; } Status TryReopen() { delete db_; db_ = NULL; return DB::Open(options_, dbname_, &db_); } void Reopen() { ASSERT_OK(TryReopen()); } void RepairDB() { delete db_; db_ = NULL; ASSERT_OK(::leveldb::RepairDB(dbname_, options_)); } void Build(int n) { std::string key_space, value_space; WriteBatch batch; for (int i = 0; i < n; i++) { //if ((i % 100) == 0) fprintf(stderr, "@ %d of %d\n", i, n); Slice key = Key(i, &key_space); batch.Clear(); batch.Put(key, Value(i, &value_space)); WriteOptions options; // Corrupt() doesn't work without this sync on windows; stat reports 0 for // the file size. if (i == n - 1) { options.sync = true; } ASSERT_OK(db_->Write(options, &batch)); } } void Check(int min_expected, int max_expected) { int next_expected = 0; int missed = 0; int bad_keys = 0; int bad_values = 0; int correct = 0; std::string value_space; Iterator* iter = db_->NewIterator(ReadOptions()); for (iter->SeekToFirst(); iter->Valid(); iter->Next()) { uint64_t key; Slice in(iter->key()); if (in == "" || in == "~") { // Ignore boundary keys. continue; } if (!ConsumeDecimalNumber(&in, &key) || !in.empty() || key < next_expected) { bad_keys++; continue; } missed += (key - next_expected); next_expected = key + 1; if (iter->value() != Value(key, &value_space)) { bad_values++; } else { correct++; } } delete iter; fprintf(stderr, "expected=%d..%d; got=%d; bad_keys=%d; bad_values=%d; missed=%d\n", min_expected, max_expected, correct, bad_keys, bad_values, missed); ASSERT_LE(min_expected, correct); ASSERT_GE(max_expected, correct); } void Corrupt(FileType filetype, int offset, int bytes_to_corrupt) { // Pick file to corrupt std::vector<std::string> filenames; ASSERT_OK(env_.GetChildren(dbname_, &filenames)); uint64_t number; FileType type; std::string fname; int picked_number = -1; for (size_t i = 0; i < filenames.size(); i++) { if (ParseFileName(filenames[i], &number, &type) && type == filetype && int(number) > picked_number) { // Pick latest file fname = dbname_ + "/" + filenames[i]; picked_number = number; } } ASSERT_TRUE(!fname.empty()) << filetype; struct stat sbuf; if (stat(fname.c_str(), &sbuf) != 0) { const char* msg = strerror(errno); ASSERT_TRUE(false) << fname << ": " << msg; } if (offset < 0) { // Relative to end of file; make it absolute if (-offset > sbuf.st_size) { offset = 0; } else { offset = sbuf.st_size + offset; } } if (offset > sbuf.st_size) { offset = sbuf.st_size; } if (offset + bytes_to_corrupt > sbuf.st_size) { bytes_to_corrupt = sbuf.st_size - offset; } // Do it std::string contents; Status s = ReadFileToString(Env::Default(), fname, &contents); ASSERT_TRUE(s.ok()) << s.ToString(); for (int i = 0; i < bytes_to_corrupt; i++) { contents[i + offset] ^= 0x80; } s = WriteStringToFile(Env::Default(), contents, fname); ASSERT_TRUE(s.ok()) << s.ToString(); } int Property(const std::string& name) { std::string property; int result; if (db_->GetProperty(name, &property) && sscanf(property.c_str(), "%d", &result) == 1) { return result; } else { return -1; } } // Return the ith key Slice Key(int i, std::string* storage) { char buf[100]; snprintf(buf, sizeof(buf), "%016d", i); storage->assign(buf, strlen(buf)); return Slice(*storage); } // Return the value to associate with the specified key Slice Value(int k, std::string* storage) { Random r(k); return test::RandomString(&r, kValueSize, storage); } }; TEST(CorruptionTest, Recovery) { Build(100); Check(100, 100); Corrupt(kLogFile, 19, 1); // WriteBatch tag for first record Corrupt(kLogFile, log::kBlockSize + 1000, 1); // Somewhere in second block Reopen(); // The 64 records in the first two log blocks are completely lost. Check(36, 36); } TEST(CorruptionTest, RecoverWriteError) { env_.writable_file_error_ = true; Status s = TryReopen(); ASSERT_TRUE(!s.ok()); } TEST(CorruptionTest, NewFileErrorDuringWrite) { // Do enough writing to force minor compaction env_.writable_file_error_ = true; const int num = 3 + (Options().write_buffer_size / kValueSize); std::string value_storage; Status s; for (int i = 0; s.ok() && i < num; i++) { WriteBatch batch; batch.Put("a", Value(100, &value_storage)); s = db_->Write(WriteOptions(), &batch); } ASSERT_TRUE(!s.ok()); ASSERT_GE(env_.num_writable_file_errors_, 1); env_.writable_file_error_ = false; Reopen(); } TEST(CorruptionTest, TableFile) { Build(100); DBImpl* dbi = reinterpret_cast<DBImpl*>(db_); dbi->TEST_CompactMemTable(); dbi->TEST_CompactRange(0, NULL, NULL); dbi->TEST_CompactRange(1, NULL, NULL); Corrupt(kTableFile, 100, 1); Check(90, 99); } TEST(CorruptionTest, TableFileRepair) { options_.block_size = 2 * kValueSize; // Limit scope of corruption options_.paranoid_checks = true; Reopen(); Build(100); DBImpl* dbi = reinterpret_cast<DBImpl*>(db_); dbi->TEST_CompactMemTable(); dbi->TEST_CompactRange(0, NULL, NULL); dbi->TEST_CompactRange(1, NULL, NULL); Corrupt(kTableFile, 100, 1); RepairDB(); Reopen(); Check(95, 99); } TEST(CorruptionTest, TableFileIndexData) { Build(10000); // Enough to build multiple Tables DBImpl* dbi = reinterpret_cast<DBImpl*>(db_); dbi->TEST_CompactMemTable(); Corrupt(kTableFile, -2000, 500); Reopen(); Check(5000, 9999); } TEST(CorruptionTest, MissingDescriptor) { Build(1000); RepairDB(); Reopen(); Check(1000, 1000); } TEST(CorruptionTest, SequenceNumberRecovery) { ASSERT_OK(db_->Put(WriteOptions(), "foo", "v1")); ASSERT_OK(db_->Put(WriteOptions(), "foo", "v2")); ASSERT_OK(db_->Put(WriteOptions(), "foo", "v3")); ASSERT_OK(db_->Put(WriteOptions(), "foo", "v4")); ASSERT_OK(db_->Put(WriteOptions(), "foo", "v5")); RepairDB(); Reopen(); std::string v; ASSERT_OK(db_->Get(ReadOptions(), "foo", &v)); ASSERT_EQ("v5", v); // Write something. If sequence number was not recovered properly, // it will be hidden by an earlier write. ASSERT_OK(db_->Put(WriteOptions(), "foo", "v6")); ASSERT_OK(db_->Get(ReadOptions(), "foo", &v)); ASSERT_EQ("v6", v); Reopen(); ASSERT_OK(db_->Get(ReadOptions(), "foo", &v)); ASSERT_EQ("v6", v); } TEST(CorruptionTest, CorruptedDescriptor) { ASSERT_OK(db_->Put(WriteOptions(), "foo", "hello")); DBImpl* dbi = reinterpret_cast<DBImpl*>(db_); dbi->TEST_CompactMemTable(); dbi->TEST_CompactRange(0, NULL, NULL); Corrupt(kDescriptorFile, 0, 1000); Status s = TryReopen(); ASSERT_TRUE(!s.ok()); RepairDB(); Reopen(); std::string v; ASSERT_OK(db_->Get(ReadOptions(), "foo", &v)); ASSERT_EQ("hello", v); } TEST(CorruptionTest, CompactionInputError) { Build(10); DBImpl* dbi = reinterpret_cast<DBImpl*>(db_); dbi->TEST_CompactMemTable(); const int last = config::kMaxMemCompactLevel; ASSERT_EQ(1, Property("leveldb.num-files-at-level" + NumberToString(last))); Corrupt(kTableFile, 100, 1); Check(5, 9); // Force compactions by writing lots of values Build(10000); Check(10000, 10000); } TEST(CorruptionTest, CompactionInputErrorParanoid) { options_.paranoid_checks = true; options_.write_buffer_size = 512 << 10; Reopen(); DBImpl* dbi = reinterpret_cast<DBImpl*>(db_); // Make multiple inputs so we need to compact. for (int i = 0; i < 2; i++) { Build(10); dbi->TEST_CompactMemTable(); Corrupt(kTableFile, 100, 1); env_.SleepForMicroseconds(100000); } dbi->CompactRange(NULL, NULL); // Write must fail because of corrupted table std::string tmp1, tmp2; Status s = db_->Put(WriteOptions(), Key(5, &tmp1), Value(5, &tmp2)); ASSERT_TRUE(!s.ok()) << "write did not fail in corrupted paranoid db"; } TEST(CorruptionTest, UnrelatedKeys) { Build(10); DBImpl* dbi = reinterpret_cast<DBImpl*>(db_); dbi->TEST_CompactMemTable(); Corrupt(kTableFile, 100, 1); std::string tmp1, tmp2; ASSERT_OK(db_->Put(WriteOptions(), Key(1000, &tmp1), Value(1000, &tmp2))); std::string v; ASSERT_OK(db_->Get(ReadOptions(), Key(1000, &tmp1), &v)); ASSERT_EQ(Value(1000, &tmp2).ToString(), v); dbi->TEST_CompactMemTable(); ASSERT_OK(db_->Get(ReadOptions(), Key(1000, &tmp1), &v)); ASSERT_EQ(Value(1000, &tmp2).ToString(), v); } } // namespace leveldb int main(int argc, char** argv) { return leveldb::test::RunAllTests(); } <|endoftext|>
<commit_before>/* * 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. * * Written (W) 1999-2009 Soeren Sonnenburg * Written (W) 1999-2008 Gunnar Raetsch * Written (W) 2006-2007 Mikio L. Braun * Written (W) 2008 Jochen Garcke * Copyright (C) 1999-2009 Fraunhofer Institute FIRST and Max-Planck-Society */ #include <shogun/lib/config.h> #ifdef HAVE_LAPACK #include <shogun/mathematics/lapack.h> #include <shogun/lib/common.h> #include <shogun/io/SGIO.h> using namespace shogun; #if defined(HAVE_MKL) || defined(HAVE_ACML) #define DSYEV dsyev #define DGESVD dgesvd #define DPOSV dposv #define DPOTRF dpotrf #define DPOTRI dpotri #define DGETRI dgetri #define DGETRF dgetrf #define DGEQRF dgeqrf #define DORGQR dorgqr #define DSYEVR dsyevr #define DPOTRS dpotrs #else #define DSYEV dsyev_ #define DGESVD dgesvd_ #define DPOSV dposv_ #define DPOTRF dpotrf_ #define DPOTRI dpotri_ #define DGETRI dgetri_ #define DGETRF dgetrf_ #define DGEQRF dgeqrf_ #define DORGQR dorgqr_ #define DSYEVR dsyevr_ #define DGETRS dgetrs_ #define DPOTRS dpotrs_ #endif #ifndef HAVE_ATLAS int clapack_dpotrf(const CBLAS_ORDER Order, const CBLAS_UPLO Uplo, const int N, double *A, const int LDA) { char uplo = 'U'; int info = 0; if (Order==CblasRowMajor) {//A is symmetric, we switch Uplo to get result for CblasRowMajor if (Uplo==CblasUpper) uplo='L'; } else if (Uplo==CblasLower) { uplo='L'; } #ifdef HAVE_ACML DPOTRF(uplo, N, A, LDA, &info); #else int n=N; int lda=LDA; DPOTRF(&uplo, &n, A, &lda, &info); #endif return info; } #undef DPOTRF int clapack_dpotri(const CBLAS_ORDER Order, const CBLAS_UPLO Uplo, const int N, double *A, const int LDA) { char uplo = 'U'; int info = 0; if (Order==CblasRowMajor) {//A is symmetric, we switch Uplo to get result for CblasRowMajor if (Uplo==CblasUpper) uplo='L'; } else if (Uplo==CblasLower) { uplo='L'; } #ifdef HAVE_ACML DPOTRI(uplo, N, A, LDA, &info); #else int n=N; int lda=LDA; DPOTRI(&uplo, &n, A, &lda, &info); #endif return info; } #undef DPOTRI /* DPOSV computes the solution to a real system of linear equations * A * X = B, * where A is an N-by-N symmetric positive definite matrix and X and B * are N-by-NRHS matrices */ int clapack_dposv(const CBLAS_ORDER Order, const CBLAS_UPLO Uplo, const int N, const int NRHS, double *A, const int lda, double *B, const int ldb) { char uplo = 'U'; int info=0; if (Order==CblasRowMajor) {//A is symmetric, we switch Uplo to achieve CblasColMajor if (Uplo==CblasUpper) uplo='L'; } else if (Uplo==CblasLower) { uplo='L'; } #ifdef HAVE_ACML DPOSV(uplo,N,NRHS,A,lda,B,ldb,&info); #else int n=N; int nrhs=NRHS; int LDA=lda; int LDB=ldb; DPOSV(&uplo, &n, &nrhs, A, &LDA, B, &LDB, &info); #endif return info; } #undef DPOSV int clapack_dgetrf(const CBLAS_ORDER Order, const int M, const int N, double *A, const int lda, int *ipiv) { // no rowmajor? int info=0; #ifdef HAVE_ACML DGETRF(M,N,A,lda,ipiv,&info); #else int m=M; int n=N; int LDA=lda; DGETRF(&m,&n,A,&LDA,ipiv,&info); #endif return info; } #undef DGETRF // order not supported (yet?) int clapack_dgetri(const CBLAS_ORDER Order, const int N, double *A, const int lda, int* ipiv) { int info=0; double* work = SG_MALLOC(double, 1); #ifdef HAVE_ACML int lwork = -1; DGETRI(N,A,lda,ipiv,work,lwork,&info); lwork = (int) work[0]; SG_FREE(work); work = SG_MALLOC(double, lwork); DGETRI(N,A,lda,ipiv,work,lwork,&info); #else int n=N; int LDA=lda; int lwork = -1; DGETRI(&n,A,&LDA,ipiv,work,&lwork,&info); lwork = (int) work[0]; SG_FREE(work); work = SG_MALLOC(double, lwork); DGETRI(&n,A,&LDA,ipiv,work,&lwork,&info); #endif return info; } #undef DGETRI // order not supported (yet?) int clapack_dgetrs(const CBLAS_ORDER Order, const CBLAS_TRANSPOSE Transpose, const int N, const int NRHS, double *A, const int lda, int *ipiv, double *B, const int ldb) { int info = 0; char trans = 'N'; if (Transpose==CblasTrans) { trans = 'T'; } #ifdef HAVE_ACML DGETRS(trans,N,NRHS,A,lda,ipiv,B,ldb,info); #else int n=N; int nrhs=NRHS; int LDA=lda; int LDB=ldb; DGETRS(&trans,&n,&nrhs,A,&LDA,ipiv,B,&LDB,&info); #endif return info; } #undef DGETRS // order not supported (yet?) int clapack_dpotrs(const enum CBLAS_ORDER Order, const enum CBLAS_UPLO Uplo, const int N, const int NRHS, double *A, const int lda, double *B, const int ldb) { int info=0; char uplo = 'U'; if (Uplo==CblasLower) { uplo = 'L'; } #ifdef HAVE_ACML DPOTRS(uplo,N,NRHS,A,lda,B,ldb,info); #else int n=N; int nrhs=NRHS; int LDA=lda; int LDB=ldb; DPOTRS(&uplo,&n,&nrhs,A,&LDA,B,&LDB,&info); #endif return info; } #undef DPOTRS #endif //HAVE_ATLAS namespace shogun { void wrap_dsyev(char jobz, char uplo, int n, double *a, int lda, double *w, int *info) { #ifdef HAVE_ACML DSYEV(jobz, uplo, n, a, lda, w, info); #else int lwork=-1; double work1; DSYEV(&jobz, &uplo, &n, a, &lda, w, &work1, &lwork, info); ASSERT(*info==0); ASSERT(work1>0); lwork=(int) work1; double* work=SG_MALLOC(double, lwork); DSYEV(&jobz, &uplo, &n, a, &lda, w, work, &lwork, info); SG_FREE(work); #endif } #undef DSYEV void wrap_dgesvd(char jobu, char jobvt, int m, int n, double *a, int lda, double *sing, double *u, int ldu, double *vt, int ldvt, int *info) { #ifdef HAVE_ACML DGESVD(jobu, jobvt, m, n, a, lda, sing, u, ldu, vt, ldvt, info); #else int lwork=-1; double work1; DGESVD(&jobu, &jobvt, &m, &n, a, &lda, sing, u, &ldu, vt, &ldvt, &work1, &lwork, info); ASSERT(*info==0); ASSERT(work1>0); lwork=(int) work1; double* work=SG_MALLOC(double, lwork); DGESVD(&jobu, &jobvt, &m, &n, a, &lda, sing, u, &ldu, vt, &ldvt, work, &lwork, info); SG_FREE(work); #endif } #undef DGESVD void wrap_dgeqrf(int m, int n, double *a, int lda, double *tau, int *info) { #ifdef HAVE_ACML DGEQRF(m, n, a, lda, tau, info); #else int lwork = -1; double* work = SG_MALLOC(double, 1); DGEQRF(&m, &n, a, &lda, tau, work, &lwork, info); ASSERT(*info==0); lwork = (int) work[0]; ASSERT(lwork>0) SG_FREE(work); work = SG_MALLOC(double, lwork); DGEQRF(&m, &n, a, &lda, tau, work, &lwork, info); SG_FREE(work); #endif } #undef DGEQRF void wrap_dorgqr(int m, int n, int k, double *a, int lda, double *tau, int *info) { #ifdef HAVE_ACML DORGQR(m, n, k, a, lda, tau, info); #else int lwork = -1; double* work = SG_MALLOC(double, 1); DORGQR(&m, &n, &k, a, &lda, tau, work, &lwork, info); ASSERT(*info==0); lwork = (int) work[0]; ASSERT(lwork>0); SG_FREE(work); work = SG_MALLOC(double, lwork); DORGQR(&m, &n, &k, a, &lda, tau, work, &lwork, info); SG_FREE(work); #endif } #undef DORGQR void wrap_dsyevr(char jobz, char uplo, int n, double *a, int lda, int il, int ul, double *eigenvalues, double *eigenvectors, int *info) { int m; double vl,vu; double abstol = 0.0; char I = 'I'; int* isuppz = SG_MALLOC(int, n); #ifdef HAVE_ACML DSYEVR(jobz,I,uplo,n,a,lda,vl,vu,il,ul,abstol,m, eigenvalues,eigenvectors,n,isuppz,info); #else int lwork = -1; int liwork = -1; double* work = SG_MALLOC(double, 1); int* iwork = SG_MALLOC(int, 1); DSYEVR(&jobz,&I,&uplo,&n,a,&lda,&vl,&vu,&il,&ul,&abstol, &m,eigenvalues,eigenvectors,&n,isuppz, work,&lwork,iwork,&liwork,info); ASSERT(*info==0); lwork = (int)work[0]; liwork = iwork[0]; SG_FREE(work); SG_FREE(iwork); work = SG_MALLOC(double, lwork); iwork = SG_MALLOC(int, liwork); DSYEVR(&jobz,&I,&uplo,&n,a,&lda,&vl,&vu,&il,&ul,&abstol, &m,eigenvalues,eigenvectors,&n,isuppz, work,&lwork,iwork,&liwork,info); ASSERT(*info==0); SG_FREE(work); SG_FREE(iwork); SG_FREE(isuppz); #endif } #undef DSYEVR } #endif //HAVE_LAPACK <commit_msg>Added forgotten DGETRS define<commit_after>/* * 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. * * Written (W) 1999-2009 Soeren Sonnenburg * Written (W) 1999-2008 Gunnar Raetsch * Written (W) 2006-2007 Mikio L. Braun * Written (W) 2008 Jochen Garcke * Copyright (C) 1999-2009 Fraunhofer Institute FIRST and Max-Planck-Society */ #include <shogun/lib/config.h> #ifdef HAVE_LAPACK #include <shogun/mathematics/lapack.h> #include <shogun/lib/common.h> #include <shogun/io/SGIO.h> using namespace shogun; #if defined(HAVE_MKL) || defined(HAVE_ACML) #define DSYEV dsyev #define DGESVD dgesvd #define DPOSV dposv #define DPOTRF dpotrf #define DPOTRI dpotri #define DGETRI dgetri #define DGETRF dgetrf #define DGEQRF dgeqrf #define DORGQR dorgqr #define DSYEVR dsyevr #define DPOTRS dpotrs #define DGETRS dgetrs #else #define DSYEV dsyev_ #define DGESVD dgesvd_ #define DPOSV dposv_ #define DPOTRF dpotrf_ #define DPOTRI dpotri_ #define DGETRI dgetri_ #define DGETRF dgetrf_ #define DGEQRF dgeqrf_ #define DORGQR dorgqr_ #define DSYEVR dsyevr_ #define DGETRS dgetrs_ #define DPOTRS dpotrs_ #endif #ifndef HAVE_ATLAS int clapack_dpotrf(const CBLAS_ORDER Order, const CBLAS_UPLO Uplo, const int N, double *A, const int LDA) { char uplo = 'U'; int info = 0; if (Order==CblasRowMajor) {//A is symmetric, we switch Uplo to get result for CblasRowMajor if (Uplo==CblasUpper) uplo='L'; } else if (Uplo==CblasLower) { uplo='L'; } #ifdef HAVE_ACML DPOTRF(uplo, N, A, LDA, &info); #else int n=N; int lda=LDA; DPOTRF(&uplo, &n, A, &lda, &info); #endif return info; } #undef DPOTRF int clapack_dpotri(const CBLAS_ORDER Order, const CBLAS_UPLO Uplo, const int N, double *A, const int LDA) { char uplo = 'U'; int info = 0; if (Order==CblasRowMajor) {//A is symmetric, we switch Uplo to get result for CblasRowMajor if (Uplo==CblasUpper) uplo='L'; } else if (Uplo==CblasLower) { uplo='L'; } #ifdef HAVE_ACML DPOTRI(uplo, N, A, LDA, &info); #else int n=N; int lda=LDA; DPOTRI(&uplo, &n, A, &lda, &info); #endif return info; } #undef DPOTRI /* DPOSV computes the solution to a real system of linear equations * A * X = B, * where A is an N-by-N symmetric positive definite matrix and X and B * are N-by-NRHS matrices */ int clapack_dposv(const CBLAS_ORDER Order, const CBLAS_UPLO Uplo, const int N, const int NRHS, double *A, const int lda, double *B, const int ldb) { char uplo = 'U'; int info=0; if (Order==CblasRowMajor) {//A is symmetric, we switch Uplo to achieve CblasColMajor if (Uplo==CblasUpper) uplo='L'; } else if (Uplo==CblasLower) { uplo='L'; } #ifdef HAVE_ACML DPOSV(uplo,N,NRHS,A,lda,B,ldb,&info); #else int n=N; int nrhs=NRHS; int LDA=lda; int LDB=ldb; DPOSV(&uplo, &n, &nrhs, A, &LDA, B, &LDB, &info); #endif return info; } #undef DPOSV int clapack_dgetrf(const CBLAS_ORDER Order, const int M, const int N, double *A, const int lda, int *ipiv) { // no rowmajor? int info=0; #ifdef HAVE_ACML DGETRF(M,N,A,lda,ipiv,&info); #else int m=M; int n=N; int LDA=lda; DGETRF(&m,&n,A,&LDA,ipiv,&info); #endif return info; } #undef DGETRF // order not supported (yet?) int clapack_dgetri(const CBLAS_ORDER Order, const int N, double *A, const int lda, int* ipiv) { int info=0; double* work = SG_MALLOC(double, 1); #ifdef HAVE_ACML int lwork = -1; DGETRI(N,A,lda,ipiv,work,lwork,&info); lwork = (int) work[0]; SG_FREE(work); work = SG_MALLOC(double, lwork); DGETRI(N,A,lda,ipiv,work,lwork,&info); #else int n=N; int LDA=lda; int lwork = -1; DGETRI(&n,A,&LDA,ipiv,work,&lwork,&info); lwork = (int) work[0]; SG_FREE(work); work = SG_MALLOC(double, lwork); DGETRI(&n,A,&LDA,ipiv,work,&lwork,&info); #endif return info; } #undef DGETRI // order not supported (yet?) int clapack_dgetrs(const CBLAS_ORDER Order, const CBLAS_TRANSPOSE Transpose, const int N, const int NRHS, double *A, const int lda, int *ipiv, double *B, const int ldb) { int info = 0; char trans = 'N'; if (Transpose==CblasTrans) { trans = 'T'; } #ifdef HAVE_ACML DGETRS(trans,N,NRHS,A,lda,ipiv,B,ldb,info); #else int n=N; int nrhs=NRHS; int LDA=lda; int LDB=ldb; DGETRS(&trans,&n,&nrhs,A,&LDA,ipiv,B,&LDB,&info); #endif return info; } #undef DGETRS // order not supported (yet?) int clapack_dpotrs(const enum CBLAS_ORDER Order, const enum CBLAS_UPLO Uplo, const int N, const int NRHS, double *A, const int lda, double *B, const int ldb) { int info=0; char uplo = 'U'; if (Uplo==CblasLower) { uplo = 'L'; } #ifdef HAVE_ACML DPOTRS(uplo,N,NRHS,A,lda,B,ldb,info); #else int n=N; int nrhs=NRHS; int LDA=lda; int LDB=ldb; DPOTRS(&uplo,&n,&nrhs,A,&LDA,B,&LDB,&info); #endif return info; } #undef DPOTRS #endif //HAVE_ATLAS namespace shogun { void wrap_dsyev(char jobz, char uplo, int n, double *a, int lda, double *w, int *info) { #ifdef HAVE_ACML DSYEV(jobz, uplo, n, a, lda, w, info); #else int lwork=-1; double work1; DSYEV(&jobz, &uplo, &n, a, &lda, w, &work1, &lwork, info); ASSERT(*info==0); ASSERT(work1>0); lwork=(int) work1; double* work=SG_MALLOC(double, lwork); DSYEV(&jobz, &uplo, &n, a, &lda, w, work, &lwork, info); SG_FREE(work); #endif } #undef DSYEV void wrap_dgesvd(char jobu, char jobvt, int m, int n, double *a, int lda, double *sing, double *u, int ldu, double *vt, int ldvt, int *info) { #ifdef HAVE_ACML DGESVD(jobu, jobvt, m, n, a, lda, sing, u, ldu, vt, ldvt, info); #else int lwork=-1; double work1; DGESVD(&jobu, &jobvt, &m, &n, a, &lda, sing, u, &ldu, vt, &ldvt, &work1, &lwork, info); ASSERT(*info==0); ASSERT(work1>0); lwork=(int) work1; double* work=SG_MALLOC(double, lwork); DGESVD(&jobu, &jobvt, &m, &n, a, &lda, sing, u, &ldu, vt, &ldvt, work, &lwork, info); SG_FREE(work); #endif } #undef DGESVD void wrap_dgeqrf(int m, int n, double *a, int lda, double *tau, int *info) { #ifdef HAVE_ACML DGEQRF(m, n, a, lda, tau, info); #else int lwork = -1; double* work = SG_MALLOC(double, 1); DGEQRF(&m, &n, a, &lda, tau, work, &lwork, info); ASSERT(*info==0); lwork = (int) work[0]; ASSERT(lwork>0) SG_FREE(work); work = SG_MALLOC(double, lwork); DGEQRF(&m, &n, a, &lda, tau, work, &lwork, info); SG_FREE(work); #endif } #undef DGEQRF void wrap_dorgqr(int m, int n, int k, double *a, int lda, double *tau, int *info) { #ifdef HAVE_ACML DORGQR(m, n, k, a, lda, tau, info); #else int lwork = -1; double* work = SG_MALLOC(double, 1); DORGQR(&m, &n, &k, a, &lda, tau, work, &lwork, info); ASSERT(*info==0); lwork = (int) work[0]; ASSERT(lwork>0); SG_FREE(work); work = SG_MALLOC(double, lwork); DORGQR(&m, &n, &k, a, &lda, tau, work, &lwork, info); SG_FREE(work); #endif } #undef DORGQR void wrap_dsyevr(char jobz, char uplo, int n, double *a, int lda, int il, int ul, double *eigenvalues, double *eigenvectors, int *info) { int m; double vl,vu; double abstol = 0.0; char I = 'I'; int* isuppz = SG_MALLOC(int, n); #ifdef HAVE_ACML DSYEVR(jobz,I,uplo,n,a,lda,vl,vu,il,ul,abstol,m, eigenvalues,eigenvectors,n,isuppz,info); #else int lwork = -1; int liwork = -1; double* work = SG_MALLOC(double, 1); int* iwork = SG_MALLOC(int, 1); DSYEVR(&jobz,&I,&uplo,&n,a,&lda,&vl,&vu,&il,&ul,&abstol, &m,eigenvalues,eigenvectors,&n,isuppz, work,&lwork,iwork,&liwork,info); ASSERT(*info==0); lwork = (int)work[0]; liwork = iwork[0]; SG_FREE(work); SG_FREE(iwork); work = SG_MALLOC(double, lwork); iwork = SG_MALLOC(int, liwork); DSYEVR(&jobz,&I,&uplo,&n,a,&lda,&vl,&vu,&il,&ul,&abstol, &m,eigenvalues,eigenvectors,&n,isuppz, work,&lwork,iwork,&liwork,info); ASSERT(*info==0); SG_FREE(work); SG_FREE(iwork); SG_FREE(isuppz); #endif } #undef DSYEVR } #endif //HAVE_LAPACK <|endoftext|>
<commit_before>// // This file is part of the Marble Virtual Globe. // // This program is free software licensed under the GNU LGPL. You can // find a copy of this license in LICENSE.txt in the top directory of // the source code. // // Copyright 2006-2007 Torsten Rahn <[email protected]> // Copyright 2007 Inge Wallin <[email protected]> // Copyright 2010 Bastian Holst <[email protected]> // #include "MarbleThemeSelectView.h" #include "MarbleDirs.h" #include "MapWizard.h" #include "MarbleDebug.h" #include <QtGui/QResizeEvent> #include <QtGui/QMenu> #include <QtGui/QMessageBox> #include <QtCore/QFileInfo> #include <QtCore/QFile> #include <QtCore/QDir> using namespace Marble; class MarbleThemeSelectView::Private { public: explicit Private( MarbleThemeSelectView * const parent ); void deleteDirectory( const QString& path ); void deleteDataDirectories( const QString& path ); void deletePreview( const QString& path ); QString currentThemeName(); QString currentThemePath(); private: MarbleThemeSelectView *m_parent; }; MarbleThemeSelectView::Private::Private( MarbleThemeSelectView * const parent ) : m_parent( parent ) { } void MarbleThemeSelectView::Private::deleteDirectory( const QString& path ) { QDir directory( path ); foreach( QString filename, directory.entryList( QDir::Files | QDir::NoDotAndDotDot ) ) QFile( path + filename ).remove(); QDir().rmdir( path ); } void MarbleThemeSelectView::Private::deleteDataDirectories( const QString& path ) { QDir directoryv( path ); foreach( QString filename, directoryv.entryList( QDir::AllEntries | QDir::NoDotAndDotDot ) ) { QString filepath = path + "/" + filename; QFile file( filepath ); if( QFileInfo( filepath ).isDir() && filename.contains( QRegExp( "^[0-9]+$" ) ) ) { deleteDataDirectories( filepath ); QDir().rmdir( filepath ); } else if( filename.contains( QRegExp( "^[0-9]\\..+" ) ) ) file.remove(); } } void MarbleThemeSelectView::Private::deletePreview( const QString& path ) { QDir directoryv( path, "preview.*" ); foreach( QString filename, directoryv.entryList() ) QFile( path + "/" + filename ).remove(); } QString MarbleThemeSelectView::Private::currentThemeName() { QModelIndex index = m_parent->currentIndex(); const QAbstractItemModel *model = index.model(); QModelIndex columnIndex = model->index( index.row(), 0, QModelIndex() ); return ( model->data( columnIndex )).toString(); } QString MarbleThemeSelectView::Private::currentThemePath() { QModelIndex index = m_parent-> currentIndex(); const QAbstractItemModel *model = index.model(); QModelIndex columnIndex = model->index( index.row(), 1, QModelIndex() ); return ( model->data( columnIndex )).toString(); } MarbleThemeSelectView::MarbleThemeSelectView(QWidget *parent) : QListView( parent ), d( new Private( this ) ) { setViewMode( QListView::IconMode ); setFlow( QListView::LeftToRight ); setWrapping( true ); setMovement( QListView::Static ); setResizeMode( QListView::Fixed ); setUniformItemSizes( true ); setHorizontalScrollBarPolicy( Qt::ScrollBarAlwaysOff ); setEditTriggers( QAbstractItemView::NoEditTriggers ); setIconSize( QSize( 136,136 ) ); setSelectionMode( QAbstractItemView::SingleSelection ); connect( this, SIGNAL( pressed( QModelIndex ) ), SLOT( selectedMapTheme( QModelIndex ) ) ); connect( this, SIGNAL( customContextMenuRequested( QPoint ) ), SLOT( showContextMenu( QPoint ) ) ); } MarbleThemeSelectView::~MarbleThemeSelectView() { delete d; } void MarbleThemeSelectView::resizeEvent( QResizeEvent *event ) { QListView::resizeEvent(event); QSize size = gridSize(); size.setWidth( event->size().width() ); setGridSize(size); } void MarbleThemeSelectView::selectedMapTheme( QModelIndex index ) { const QAbstractItemModel *model = index.model(); QModelIndex columnIndex = model->index( index.row(), 1, QModelIndex() ); QString currentmaptheme = ( model->data( columnIndex )).toString(); mDebug() << currentmaptheme; emit selectMapTheme( currentmaptheme ); } void MarbleThemeSelectView::mapWizard() { emit showMapWizard(); } void MarbleThemeSelectView::uploadDialog() { emit showUploadDialog(); } void MarbleThemeSelectView::showContextMenu( const QPoint& pos ) { QMenu menu; menu.addAction( "&Create a New Map...", this, SLOT( mapWizard() ) ); if( QFileInfo( MarbleDirs::localPath() + "/maps/" + d->currentThemePath() ).exists() ) menu.addAction( tr( "&Delete Map Theme" ), this, SLOT( deleteMap() ) ); menu.addAction( "&Upload Map...", this, SLOT( uploadDialog() ) ); menu.exec( mapToGlobal( pos ) ); } void MarbleThemeSelectView::deleteMap() { if(QMessageBox::warning( this, tr( "" ), tr( "Are you sure that you want to delete \"%1\"?" ).arg( d->currentThemeName() ), QMessageBox::Yes | QMessageBox::No) == QMessageBox::Yes ) { QDir mapthemedir( QFileInfo( MarbleDirs::localPath() + "/maps/" + d->currentThemePath()).path()); d->deleteDirectory( mapthemedir.path() + "/legend/" ); d->deleteDataDirectories( mapthemedir.path() + "/" ); d->deletePreview( mapthemedir.path() + "/" ); QFile( MarbleDirs::localPath() + "/maps/" + d->currentThemePath()).remove(); QFile( mapthemedir.path() + "/legend.html" ).remove(); QDir().rmdir( mapthemedir.path() ); } } #include "MarbleThemeSelectView.moc" <commit_msg>Smaller icons and list mode for improvied usability on small screen devices.<commit_after>// // This file is part of the Marble Virtual Globe. // // This program is free software licensed under the GNU LGPL. You can // find a copy of this license in LICENSE.txt in the top directory of // the source code. // // Copyright 2006-2007 Torsten Rahn <[email protected]> // Copyright 2007 Inge Wallin <[email protected]> // Copyright 2010 Bastian Holst <[email protected]> // #include "MarbleThemeSelectView.h" #include "global.h" #include "MarbleDirs.h" #include "MapWizard.h" #include "MarbleDebug.h" #include <QtCore/QFileInfo> #include <QtCore/QFile> #include <QtCore/QDir> #include <QtGui/QResizeEvent> #include <QtGui/QMenu> #include <QtGui/QMessageBox> using namespace Marble; class MarbleThemeSelectView::Private { public: explicit Private( MarbleThemeSelectView * const parent ); void deleteDirectory( const QString& path ); void deleteDataDirectories( const QString& path ); void deletePreview( const QString& path ); QString currentThemeName(); QString currentThemePath(); private: MarbleThemeSelectView *m_parent; }; MarbleThemeSelectView::Private::Private( MarbleThemeSelectView * const parent ) : m_parent( parent ) { } void MarbleThemeSelectView::Private::deleteDirectory( const QString& path ) { QDir directory( path ); foreach( QString filename, directory.entryList( QDir::Files | QDir::NoDotAndDotDot ) ) QFile( path + filename ).remove(); QDir().rmdir( path ); } void MarbleThemeSelectView::Private::deleteDataDirectories( const QString& path ) { QDir directoryv( path ); foreach( QString filename, directoryv.entryList( QDir::AllEntries | QDir::NoDotAndDotDot ) ) { QString filepath = path + "/" + filename; QFile file( filepath ); if( QFileInfo( filepath ).isDir() && filename.contains( QRegExp( "^[0-9]+$" ) ) ) { deleteDataDirectories( filepath ); QDir().rmdir( filepath ); } else if( filename.contains( QRegExp( "^[0-9]\\..+" ) ) ) file.remove(); } } void MarbleThemeSelectView::Private::deletePreview( const QString& path ) { QDir directoryv( path, "preview.*" ); foreach( QString filename, directoryv.entryList() ) QFile( path + "/" + filename ).remove(); } QString MarbleThemeSelectView::Private::currentThemeName() { QModelIndex index = m_parent->currentIndex(); const QAbstractItemModel *model = index.model(); QModelIndex columnIndex = model->index( index.row(), 0, QModelIndex() ); return ( model->data( columnIndex )).toString(); } QString MarbleThemeSelectView::Private::currentThemePath() { QModelIndex index = m_parent-> currentIndex(); const QAbstractItemModel *model = index.model(); QModelIndex columnIndex = model->index( index.row(), 1, QModelIndex() ); return ( model->data( columnIndex )).toString(); } MarbleThemeSelectView::MarbleThemeSelectView(QWidget *parent) : QListView( parent ), d( new Private( this ) ) { bool const smallScreen = MarbleGlobal::getInstance()->profiles() & MarbleGlobal::SmallScreen; if ( smallScreen ) { setViewMode( QListView::ListMode ); setIconSize( QSize( 64, 64 ) ); } else { setViewMode( QListView::IconMode ); setIconSize( QSize( 136, 136 ) ); } setFlow( QListView::LeftToRight ); setWrapping( true ); setMovement( QListView::Static ); setResizeMode( QListView::Fixed ); setUniformItemSizes( true ); setHorizontalScrollBarPolicy( Qt::ScrollBarAlwaysOff ); setEditTriggers( QAbstractItemView::NoEditTriggers ); setSelectionMode( QAbstractItemView::SingleSelection ); connect( this, SIGNAL( pressed( QModelIndex ) ), SLOT( selectedMapTheme( QModelIndex ) ) ); connect( this, SIGNAL( customContextMenuRequested( QPoint ) ), SLOT( showContextMenu( QPoint ) ) ); } MarbleThemeSelectView::~MarbleThemeSelectView() { delete d; } void MarbleThemeSelectView::resizeEvent( QResizeEvent *event ) { QListView::resizeEvent(event); QSize size = gridSize(); size.setWidth( event->size().width() ); setGridSize(size); } void MarbleThemeSelectView::selectedMapTheme( QModelIndex index ) { const QAbstractItemModel *model = index.model(); QModelIndex columnIndex = model->index( index.row(), 1, QModelIndex() ); QString currentmaptheme = ( model->data( columnIndex )).toString(); mDebug() << currentmaptheme; emit selectMapTheme( currentmaptheme ); } void MarbleThemeSelectView::mapWizard() { emit showMapWizard(); } void MarbleThemeSelectView::uploadDialog() { emit showUploadDialog(); } void MarbleThemeSelectView::showContextMenu( const QPoint& pos ) { QMenu menu; menu.addAction( "&Create a New Map...", this, SLOT( mapWizard() ) ); if( QFileInfo( MarbleDirs::localPath() + "/maps/" + d->currentThemePath() ).exists() ) menu.addAction( tr( "&Delete Map Theme" ), this, SLOT( deleteMap() ) ); menu.addAction( "&Upload Map...", this, SLOT( uploadDialog() ) ); menu.exec( mapToGlobal( pos ) ); } void MarbleThemeSelectView::deleteMap() { if(QMessageBox::warning( this, tr( "" ), tr( "Are you sure that you want to delete \"%1\"?" ).arg( d->currentThemeName() ), QMessageBox::Yes | QMessageBox::No) == QMessageBox::Yes ) { QDir mapthemedir( QFileInfo( MarbleDirs::localPath() + "/maps/" + d->currentThemePath()).path()); d->deleteDirectory( mapthemedir.path() + "/legend/" ); d->deleteDataDirectories( mapthemedir.path() + "/" ); d->deletePreview( mapthemedir.path() + "/" ); QFile( MarbleDirs::localPath() + "/maps/" + d->currentThemePath()).remove(); QFile( mapthemedir.path() + "/legend.html" ).remove(); QDir().rmdir( mapthemedir.path() ); } } #include "MarbleThemeSelectView.moc" <|endoftext|>
<commit_before>// Copyright (c) 2010 Satoshi Nakamoto // Copyright (c) 2009-2012 The Bitcoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "main.h" #include "bitcoinrpc.h" #include "pow_control.h" using namespace json_spirit; using namespace std; extern void TxToJSON(const CTransaction& tx, const uint256 hashBlock, json_spirit::Object& entry); extern enum Checkpoints::CPMode CheckpointsMode; double GetDifficulty(const CBlockIndex* blockindex) { // Floating point number that is a multiple of the minimum difficulty, // minimum difficulty = 1.0. if (blockindex == NULL) { if (pindexBest == NULL) return 1.0; else blockindex = GetLastBlockIndex(pindexBest, false); } int nShift = (blockindex->nBits >> 24) & 0xff; double dDiff = (double)0x0000ffff / (double)(blockindex->nBits & 0x00ffffff); while (nShift < 29) { dDiff *= 256.0; nShift++; } while (nShift > 29) { dDiff /= 256.0; nShift--; } return dDiff; } double GetPoWMHashPS() { if (pindexBest->nHeight >= LAST_POW_BLOCK) return 0; int nPoWInterval = 72; int64_t nTargetSpacingWorkMin = 30, nTargetSpacingWork = 30; CBlockIndex* pindex = pindexGenesisBlock; CBlockIndex* pindexPrevWork = pindexGenesisBlock; while (pindex) { if (pindex->IsProofOfWork()) { int64_t nActualSpacingWork = pindex->GetBlockTime() - pindexPrevWork->GetBlockTime(); nTargetSpacingWork = ((nPoWInterval - 1) * nTargetSpacingWork + nActualSpacingWork + nActualSpacingWork) / (nPoWInterval + 1); nTargetSpacingWork = max(nTargetSpacingWork, nTargetSpacingWorkMin); pindexPrevWork = pindex; } pindex = pindex->pnext; } return GetDifficulty() * 4294.967296 / nTargetSpacingWork; } double GetPoSKernelPS() { int nPoSInterval = 72; double dStakeKernelsTriedAvg = 0; int nStakesHandled = 0, nStakesTime = 0; CBlockIndex* pindex = pindexBest;; CBlockIndex* pindexPrevStake = NULL; while (pindex && nStakesHandled < nPoSInterval) { if (pindex->IsProofOfStake()) { dStakeKernelsTriedAvg += GetDifficulty(pindex) * 4294967296.0; nStakesTime += pindexPrevStake ? (pindexPrevStake->nTime - pindex->nTime) : 0; pindexPrevStake = pindex; nStakesHandled++; } pindex = pindex->pprev; } return nStakesTime ? dStakeKernelsTriedAvg / nStakesTime : 0; } Object blockToJSON(const CBlock& block, const CBlockIndex* blockindex, bool fPrintTransactionDetail) { Object result; result.push_back(Pair("hash", block.GetHash().GetHex())); CMerkleTx txGen(block.vtx[0]); txGen.SetMerkleBranch(&block); result.push_back(Pair("confirmations", (int)txGen.GetDepthInMainChain())); result.push_back(Pair("size", (int)::GetSerializeSize(block, SER_NETWORK, PROTOCOL_VERSION))); result.push_back(Pair("height", blockindex->nHeight)); result.push_back(Pair("version", block.nVersion)); result.push_back(Pair("merkleroot", block.hashMerkleRoot.GetHex())); result.push_back(Pair("mint", ValueFromAmount(blockindex->nMint))); result.push_back(Pair("time", (boost::int64_t)block.GetBlockTime())); result.push_back(Pair("nonce", (boost::uint64_t)block.nNonce)); result.push_back(Pair("bits", HexBits(block.nBits))); result.push_back(Pair("difficulty", GetDifficulty(blockindex))); result.push_back(Pair("blocktrust", leftTrim(blockindex->GetBlockTrust().GetHex(), '0'))); result.push_back(Pair("chaintrust", leftTrim(blockindex->nChainTrust.GetHex(), '0'))); if (blockindex->pprev) result.push_back(Pair("previousblockhash", blockindex->pprev->GetBlockHash().GetHex())); if (blockindex->pnext) result.push_back(Pair("nextblockhash", blockindex->pnext->GetBlockHash().GetHex())); result.push_back(Pair("flags", strprintf("%s%s", blockindex->IsProofOfStake()? "proof-of-stake" : "proof-of-work", blockindex->GeneratedStakeModifier()? " stake-modifier": ""))); result.push_back(Pair("proofhash", blockindex->IsProofOfStake()? blockindex->hashProofOfStake.GetHex() : blockindex->GetBlockHash().GetHex())); result.push_back(Pair("entropybit", (int)blockindex->GetStakeEntropyBit())); result.push_back(Pair("modifier", strprintf("%016"PRIx64, blockindex->nStakeModifier))); result.push_back(Pair("modifierchecksum", strprintf("%08x", blockindex->nStakeModifierChecksum))); Array txinfo; BOOST_FOREACH (const CTransaction& tx, block.vtx) { if (fPrintTransactionDetail) { Object entry; entry.push_back(Pair("txid", tx.GetHash().GetHex())); TxToJSON(tx, 0, entry); txinfo.push_back(entry); } else txinfo.push_back(tx.GetHash().GetHex()); } result.push_back(Pair("tx", txinfo)); if (block.IsProofOfStake()) result.push_back(Pair("signature", HexStr(block.vchBlockSig.begin(), block.vchBlockSig.end()))); return result; } Value getbestblockhash(const Array& params, bool fHelp) { if (fHelp || params.size() != 0) throw runtime_error( "getbestblockhash\n" "Returns the hash of the best block in the longest block chain."); return hashBestChain.GetHex(); } Value getblockcount(const Array& params, bool fHelp) { if (fHelp || params.size() != 0) throw runtime_error( "getblockcount\n" "Returns the number of blocks in the longest block chain."); return nBestHeight; } Value getdifficulty(const Array& params, bool fHelp) { if (fHelp || params.size() != 0) throw runtime_error( "getdifficulty\n" "Returns the difficulty as a multiple of the minimum difficulty."); Object obj; obj.push_back(Pair("proof-of-work", GetDifficulty())); obj.push_back(Pair("proof-of-stake", GetDifficulty(GetLastBlockIndex(pindexBest, true)))); obj.push_back(Pair("search-interval", (int)nLastCoinStakeSearchInterval)); return obj; } Value settxfee(const Array& params, bool fHelp) { if (fHelp || params.size() < 1 || params.size() > 1 || AmountFromValue(params[0]) < MIN_TX_FEE) throw runtime_error( "settxfee <amount>\n" "<amount> is a real and is rounded to the nearest 0.01"); nTransactionFee = AmountFromValue(params[0]); nTransactionFee = (nTransactionFee / CENT) * CENT; // round to cent return true; } Value getrawmempool(const Array& params, bool fHelp) { if (fHelp || params.size() != 0) throw runtime_error( "getrawmempool\n" "Returns all transaction ids in memory pool."); vector<uint256> vtxid; mempool.queryHashes(vtxid); Array a; BOOST_FOREACH(const uint256& hash, vtxid) a.push_back(hash.ToString()); return a; } Value getblockhash(const Array& params, bool fHelp) { if (fHelp || params.size() != 1) throw runtime_error( "getblockhash <index>\n" "Returns hash of block in best-block-chain at <index>."); int nHeight = params[0].get_int(); if (nHeight < 0 || nHeight > nBestHeight) throw runtime_error("Block number out of range."); CBlockIndex* pblockindex = FindBlockByHeight(nHeight); return pblockindex->phashBlock->GetHex(); } Value getblock(const Array& params, bool fHelp) { if (fHelp || params.size() < 1 || params.size() > 2) throw runtime_error( "getblock <hash> [txinfo]\n" "txinfo optional to print more detailed tx info\n" "Returns details of a block with given block-hash."); std::string strHash = params[0].get_str(); uint256 hash(strHash); if (mapBlockIndex.count(hash) == 0) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found"); CBlock block; CBlockIndex* pblockindex = mapBlockIndex[hash]; block.ReadFromDisk(pblockindex, true); return blockToJSON(block, pblockindex, params.size() > 1 ? params[1].get_bool() : false); } Value getblockbynumber(const Array& params, bool fHelp) { if (fHelp || params.size() < 1 || params.size() > 2) throw runtime_error( "getblock <number> [txinfo]\n" "txinfo optional to print more detailed tx info\n" "Returns details of a block with given block-number."); int nHeight = params[0].get_int(); if (nHeight < 0 || nHeight > nBestHeight) throw runtime_error("Block number out of range."); CBlock block; CBlockIndex* pblockindex = mapBlockIndex[hashBestChain]; while (pblockindex->nHeight > nHeight) pblockindex = pblockindex->pprev; uint256 hash = *pblockindex->phashBlock; pblockindex = mapBlockIndex[hash]; block.ReadFromDisk(pblockindex, true); return blockToJSON(block, pblockindex, params.size() > 1 ? params[1].get_bool() : false); } // britcoin: get information of sync-checkpoint Value getcheckpoint(const Array& params, bool fHelp) { if (fHelp || params.size() != 0) throw runtime_error( "getcheckpoint\n" "Show info of synchronized checkpoint.\n"); Object result; CBlockIndex* pindexCheckpoint; result.push_back(Pair("synccheckpoint", Checkpoints::hashSyncCheckpoint.ToString().c_str())); pindexCheckpoint = mapBlockIndex[Checkpoints::hashSyncCheckpoint]; result.push_back(Pair("height", pindexCheckpoint->nHeight)); result.push_back(Pair("timestamp", DateTimeStrFormat(pindexCheckpoint->GetBlockTime()).c_str())); // Check that the block satisfies synchronized checkpoint if (CheckpointsMode == Checkpoints::STRICT) result.push_back(Pair("policy", "strict")); if (CheckpointsMode == Checkpoints::ADVISORY) result.push_back(Pair("policy", "advisory")); if (CheckpointsMode == Checkpoints::PERMISSIVE) result.push_back(Pair("policy", "permissive")); if (mapArgs.count("-checkpointkey")) result.push_back(Pair("checkpointmaster", true)); return result; } <commit_msg>Another change from boostcoin<commit_after>// Copyright (c) 2010 Satoshi Nakamoto // Copyright (c) 2009-2012 The Bitcoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "main.h" #include "bitcoinrpc.h" #include "pow_control.h" using namespace json_spirit; using namespace std; extern void TxToJSON(const CTransaction& tx, const uint256 hashBlock, json_spirit::Object& entry); extern enum Checkpoints::CPMode CheckpointsMode; double GetDifficulty(const CBlockIndex* blockindex) { // Floating point number that is a multiple of the minimum difficulty, // minimum difficulty = 1.0. if (blockindex == NULL) { if (pindexBest == NULL) return 1.0; else blockindex = GetLastBlockIndex(pindexBest, false); } int nShift = (blockindex->nBits >> 24) & 0xff; double dDiff = (double)0x0000ffff / (double)(blockindex->nBits & 0x00ffffff); while (nShift < 29) { dDiff *= 256.0; nShift++; } while (nShift > 29) { dDiff /= 256.0; nShift--; } return dDiff; } double GetPoWMHashPS() { // code taken from boostcoin if (GetBoolArg("-testnet")){ if (pindexBest->nHeight >= PoW1_End_TestNet && pindexBest->nHeight < PoW2_Start_TestNet){ return 0; } else if (pindexBest->nHeight > PoW2_End_TestNet){ return 0; } }else { if (pindexBest->nHeight >= PoW1_End && pindexBest->nHeight < PoW2_Start){ return 0; } else if (pindexBest->nHeight > PoW2_End){ return 0; } } // end code taken from boostcoin int nPoWInterval = 72; int64_t nTargetSpacingWorkMin = 30, nTargetSpacingWork = 30; CBlockIndex* pindex = pindexGenesisBlock; CBlockIndex* pindexPrevWork = pindexGenesisBlock; while (pindex) { if (pindex->IsProofOfWork()) { int64_t nActualSpacingWork = pindex->GetBlockTime() - pindexPrevWork->GetBlockTime(); nTargetSpacingWork = ((nPoWInterval - 1) * nTargetSpacingWork + nActualSpacingWork + nActualSpacingWork) / (nPoWInterval + 1); nTargetSpacingWork = max(nTargetSpacingWork, nTargetSpacingWorkMin); pindexPrevWork = pindex; } pindex = pindex->pnext; } return GetDifficulty() * 4294.967296 / nTargetSpacingWork; } double GetPoSKernelPS() { int nPoSInterval = 72; double dStakeKernelsTriedAvg = 0; int nStakesHandled = 0, nStakesTime = 0; CBlockIndex* pindex = pindexBest;; CBlockIndex* pindexPrevStake = NULL; while (pindex && nStakesHandled < nPoSInterval) { if (pindex->IsProofOfStake()) { dStakeKernelsTriedAvg += GetDifficulty(pindex) * 4294967296.0; nStakesTime += pindexPrevStake ? (pindexPrevStake->nTime - pindex->nTime) : 0; pindexPrevStake = pindex; nStakesHandled++; } pindex = pindex->pprev; } return nStakesTime ? dStakeKernelsTriedAvg / nStakesTime : 0; } Object blockToJSON(const CBlock& block, const CBlockIndex* blockindex, bool fPrintTransactionDetail) { Object result; result.push_back(Pair("hash", block.GetHash().GetHex())); CMerkleTx txGen(block.vtx[0]); txGen.SetMerkleBranch(&block); result.push_back(Pair("confirmations", (int)txGen.GetDepthInMainChain())); result.push_back(Pair("size", (int)::GetSerializeSize(block, SER_NETWORK, PROTOCOL_VERSION))); result.push_back(Pair("height", blockindex->nHeight)); result.push_back(Pair("version", block.nVersion)); result.push_back(Pair("merkleroot", block.hashMerkleRoot.GetHex())); result.push_back(Pair("mint", ValueFromAmount(blockindex->nMint))); result.push_back(Pair("time", (boost::int64_t)block.GetBlockTime())); result.push_back(Pair("nonce", (boost::uint64_t)block.nNonce)); result.push_back(Pair("bits", HexBits(block.nBits))); result.push_back(Pair("difficulty", GetDifficulty(blockindex))); result.push_back(Pair("blocktrust", leftTrim(blockindex->GetBlockTrust().GetHex(), '0'))); result.push_back(Pair("chaintrust", leftTrim(blockindex->nChainTrust.GetHex(), '0'))); if (blockindex->pprev) result.push_back(Pair("previousblockhash", blockindex->pprev->GetBlockHash().GetHex())); if (blockindex->pnext) result.push_back(Pair("nextblockhash", blockindex->pnext->GetBlockHash().GetHex())); result.push_back(Pair("flags", strprintf("%s%s", blockindex->IsProofOfStake()? "proof-of-stake" : "proof-of-work", blockindex->GeneratedStakeModifier()? " stake-modifier": ""))); result.push_back(Pair("proofhash", blockindex->IsProofOfStake()? blockindex->hashProofOfStake.GetHex() : blockindex->GetBlockHash().GetHex())); result.push_back(Pair("entropybit", (int)blockindex->GetStakeEntropyBit())); result.push_back(Pair("modifier", strprintf("%016"PRIx64, blockindex->nStakeModifier))); result.push_back(Pair("modifierchecksum", strprintf("%08x", blockindex->nStakeModifierChecksum))); Array txinfo; BOOST_FOREACH (const CTransaction& tx, block.vtx) { if (fPrintTransactionDetail) { Object entry; entry.push_back(Pair("txid", tx.GetHash().GetHex())); TxToJSON(tx, 0, entry); txinfo.push_back(entry); } else txinfo.push_back(tx.GetHash().GetHex()); } result.push_back(Pair("tx", txinfo)); if (block.IsProofOfStake()) result.push_back(Pair("signature", HexStr(block.vchBlockSig.begin(), block.vchBlockSig.end()))); return result; } Value getbestblockhash(const Array& params, bool fHelp) { if (fHelp || params.size() != 0) throw runtime_error( "getbestblockhash\n" "Returns the hash of the best block in the longest block chain."); return hashBestChain.GetHex(); } Value getblockcount(const Array& params, bool fHelp) { if (fHelp || params.size() != 0) throw runtime_error( "getblockcount\n" "Returns the number of blocks in the longest block chain."); return nBestHeight; } Value getdifficulty(const Array& params, bool fHelp) { if (fHelp || params.size() != 0) throw runtime_error( "getdifficulty\n" "Returns the difficulty as a multiple of the minimum difficulty."); Object obj; obj.push_back(Pair("proof-of-work", GetDifficulty())); obj.push_back(Pair("proof-of-stake", GetDifficulty(GetLastBlockIndex(pindexBest, true)))); obj.push_back(Pair("search-interval", (int)nLastCoinStakeSearchInterval)); return obj; } Value settxfee(const Array& params, bool fHelp) { if (fHelp || params.size() < 1 || params.size() > 1 || AmountFromValue(params[0]) < MIN_TX_FEE) throw runtime_error( "settxfee <amount>\n" "<amount> is a real and is rounded to the nearest 0.01"); nTransactionFee = AmountFromValue(params[0]); nTransactionFee = (nTransactionFee / CENT) * CENT; // round to cent return true; } Value getrawmempool(const Array& params, bool fHelp) { if (fHelp || params.size() != 0) throw runtime_error( "getrawmempool\n" "Returns all transaction ids in memory pool."); vector<uint256> vtxid; mempool.queryHashes(vtxid); Array a; BOOST_FOREACH(const uint256& hash, vtxid) a.push_back(hash.ToString()); return a; } Value getblockhash(const Array& params, bool fHelp) { if (fHelp || params.size() != 1) throw runtime_error( "getblockhash <index>\n" "Returns hash of block in best-block-chain at <index>."); int nHeight = params[0].get_int(); if (nHeight < 0 || nHeight > nBestHeight) throw runtime_error("Block number out of range."); CBlockIndex* pblockindex = FindBlockByHeight(nHeight); return pblockindex->phashBlock->GetHex(); } Value getblock(const Array& params, bool fHelp) { if (fHelp || params.size() < 1 || params.size() > 2) throw runtime_error( "getblock <hash> [txinfo]\n" "txinfo optional to print more detailed tx info\n" "Returns details of a block with given block-hash."); std::string strHash = params[0].get_str(); uint256 hash(strHash); if (mapBlockIndex.count(hash) == 0) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found"); CBlock block; CBlockIndex* pblockindex = mapBlockIndex[hash]; block.ReadFromDisk(pblockindex, true); return blockToJSON(block, pblockindex, params.size() > 1 ? params[1].get_bool() : false); } Value getblockbynumber(const Array& params, bool fHelp) { if (fHelp || params.size() < 1 || params.size() > 2) throw runtime_error( "getblock <number> [txinfo]\n" "txinfo optional to print more detailed tx info\n" "Returns details of a block with given block-number."); int nHeight = params[0].get_int(); if (nHeight < 0 || nHeight > nBestHeight) throw runtime_error("Block number out of range."); CBlock block; CBlockIndex* pblockindex = mapBlockIndex[hashBestChain]; while (pblockindex->nHeight > nHeight) pblockindex = pblockindex->pprev; uint256 hash = *pblockindex->phashBlock; pblockindex = mapBlockIndex[hash]; block.ReadFromDisk(pblockindex, true); return blockToJSON(block, pblockindex, params.size() > 1 ? params[1].get_bool() : false); } // britcoin: get information of sync-checkpoint Value getcheckpoint(const Array& params, bool fHelp) { if (fHelp || params.size() != 0) throw runtime_error( "getcheckpoint\n" "Show info of synchronized checkpoint.\n"); Object result; CBlockIndex* pindexCheckpoint; result.push_back(Pair("synccheckpoint", Checkpoints::hashSyncCheckpoint.ToString().c_str())); pindexCheckpoint = mapBlockIndex[Checkpoints::hashSyncCheckpoint]; result.push_back(Pair("height", pindexCheckpoint->nHeight)); result.push_back(Pair("timestamp", DateTimeStrFormat(pindexCheckpoint->GetBlockTime()).c_str())); // Check that the block satisfies synchronized checkpoint if (CheckpointsMode == Checkpoints::STRICT) result.push_back(Pair("policy", "strict")); if (CheckpointsMode == Checkpoints::ADVISORY) result.push_back(Pair("policy", "advisory")); if (CheckpointsMode == Checkpoints::PERMISSIVE) result.push_back(Pair("policy", "permissive")); if (mapArgs.count("-checkpointkey")) result.push_back(Pair("checkpointmaster", true)); return result; } <|endoftext|>
<commit_before>/** * Copyright (c) 2015 - The CM Authors <[email protected]> * All Rights Reserved. * * This file is CONFIDENTIAL -- Distribution or duplication of this material or * the information contained herein is strictly forbidden unless prior written * permission is obtained. */ #include "tracker/tracker.h" #include <fnord/base/exception.h> #include <fnord/base/inspect.h> #include <fnord/net/http/cookies.h> #include "fnord/net/http/httprequest.h" #include "fnord/net/http/httpresponse.h" #include "fnord/net/http/status.h" #include "fnord/base/random.h" #include "fnord/logging/logger.h" #include "customernamespace.h" #include "tracker/logjoinservice.h" /** * mandatory params: * v -- pixel ver. -- value: 1 * c -- clickid -- format "<uid>~<eventid>", e.g. "f97650cb~b28c61d5c" * e -- eventtype -- format "{q,v}" (query, visit) * * params for eventtype=q (query): * is -- item ids -- format "<setid>~<itemid>~<pos>,..." * * params for eventtype=v (visit): * i -- itemid -- format "<setid>~<itemid>" * */ namespace cm { const unsigned char pixel_gif[42] = { 0x47, 0x49, 0x46, 0x38, 0x39, 0x61, 0x01, 0x00, 0x01, 0x00, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0x21, 0xf9, 0x04, 0x01, 0x00, 0x00, 0x00, 0x00, 0x2c, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x01, 0x00, 0x00, 0x02, 0x01, 0x44, 0x00, 0x3b }; Tracker::Tracker( fnord::comm::FeedFactory* feed_factory) { feed_ = feed_factory->getFeed("cm.tracker.log"); } bool Tracker::isReservedParam(const std::string p) { return p == "c" || p == "e" || p == "i" || p == "is"; } void Tracker::handleHTTPRequest( fnord::http::HTTPRequest* request, fnord::http::HTTPResponse* response) { /* find namespace */ CustomerNamespace* ns = nullptr; const auto hostname = request->getHeader("host"); auto ns_iter = vhosts_.find(hostname); if (ns_iter == vhosts_.end()) { response->setStatus(fnord::http::kStatusNotFound); response->addBody("not found"); return; } else { ns = ns_iter->second; } fnord::URI uri(request->uri()); if (uri.path() == "/t.js") { response->setStatus(fnord::http::kStatusOK); response->addHeader("Content-Type", "application/javascript"); response->addHeader("Cache-Control", "no-cache, no-store, must-revalidate"); response->addHeader("Pragma", "no-cache"); response->addHeader("Expires", "0"); response->addBody(fnord::StringUtil::format( "__cmhost='$0'; __cmuid='$1'; __cmcid='$2'; $3", hostname, rnd_.hex128(), rnd_.hex64(), ns->trackingJS())); return; } if (uri.path() == "/t.gif") { try { recordLogLine(ns, uri.query()); } catch (const std::exception& e) { auto msg = fnord::StringUtil::format( "invalid tracking pixel url: $0", uri.query()); fnord::log::Logger::get()->logException(fnord::log::kDebug, msg, e); } response->setStatus(fnord::http::kStatusOK); response->addHeader("Content-Type", "image/gif"); response->addHeader("Cache-Control", "no-cache, no-store, must-revalidate"); response->addHeader("Pragma", "no-cache"); response->addHeader("Expires", "0"); response->addBody((void *) &pixel_gif, sizeof(pixel_gif)); return; } response->setStatus(fnord::http::kStatusNotFound); response->addBody("not found"); } void Tracker::addCustomer(CustomerNamespace* customer) { for (const auto& vhost : customer->vhosts()) { if (vhosts_.count(vhost) != 0) { RAISEF(kRuntimeError, "hostname is already registered: $0", vhost); } vhosts_[vhost] = customer; } } void Tracker::recordLogLine( CustomerNamespace* customer, const std::string& logline) { fnord::URI::ParamList params; fnord::URI::parseQueryString(logline, &params); std::string pixel_ver; if (!fnord::URI::getParam(params, "v", &pixel_ver)) { RAISE(kRuntimeError, "missing v parameter"); } try { if (std::stoi(pixel_ver) < kMinPixelVersion) { RAISEF(kRuntimeError, "pixel version too old: $0", pixel_ver); } } catch (const std::exception& e) { RAISEF(kRuntimeError, "invalid pixel version: $0", pixel_ver); } auto pos = feed_->append(logline); fnord::iputs("write to feed @$0 => $1", pos, logline); } } // namespace cm <commit_msg>log time/customer<commit_after>/** * Copyright (c) 2015 - The CM Authors <[email protected]> * All Rights Reserved. * * This file is CONFIDENTIAL -- Distribution or duplication of this material or * the information contained herein is strictly forbidden unless prior written * permission is obtained. */ #include "tracker/tracker.h" #include <fnord/base/exception.h> #include <fnord/base/inspect.h> #include <fnord/base/wallclock.h> #include <fnord/net/http/cookies.h> #include "fnord/net/http/httprequest.h" #include "fnord/net/http/httpresponse.h" #include "fnord/net/http/status.h" #include "fnord/base/random.h" #include "fnord/logging/logger.h" #include "customernamespace.h" #include "tracker/logjoinservice.h" /** * mandatory params: * v -- pixel ver. -- value: 1 * c -- clickid -- format "<uid>~<eventid>", e.g. "f97650cb~b28c61d5c" * e -- eventtype -- format "{q,v}" (query, visit) * * params for eventtype=q (query): * is -- item ids -- format "<setid>~<itemid>~<pos>,..." * * params for eventtype=v (visit): * i -- itemid -- format "<setid>~<itemid>" * */ namespace cm { const unsigned char pixel_gif[42] = { 0x47, 0x49, 0x46, 0x38, 0x39, 0x61, 0x01, 0x00, 0x01, 0x00, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0x21, 0xf9, 0x04, 0x01, 0x00, 0x00, 0x00, 0x00, 0x2c, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x01, 0x00, 0x00, 0x02, 0x01, 0x44, 0x00, 0x3b }; Tracker::Tracker( fnord::comm::FeedFactory* feed_factory) { feed_ = feed_factory->getFeed("cm.tracker.log"); } bool Tracker::isReservedParam(const std::string p) { return p == "c" || p == "e" || p == "i" || p == "is"; } void Tracker::handleHTTPRequest( fnord::http::HTTPRequest* request, fnord::http::HTTPResponse* response) { /* find namespace */ CustomerNamespace* ns = nullptr; const auto hostname = request->getHeader("host"); auto ns_iter = vhosts_.find(hostname); if (ns_iter == vhosts_.end()) { response->setStatus(fnord::http::kStatusNotFound); response->addBody("not found"); return; } else { ns = ns_iter->second; } fnord::URI uri(request->uri()); if (uri.path() == "/t.js") { response->setStatus(fnord::http::kStatusOK); response->addHeader("Content-Type", "application/javascript"); response->addHeader("Cache-Control", "no-cache, no-store, must-revalidate"); response->addHeader("Pragma", "no-cache"); response->addHeader("Expires", "0"); response->addBody(fnord::StringUtil::format( "__cmhost='$0'; __cmuid='$1'; __cmcid='$2'; $3", hostname, rnd_.hex128(), rnd_.hex64(), ns->trackingJS())); return; } if (uri.path() == "/t.gif") { try { recordLogLine(ns, uri.query()); } catch (const std::exception& e) { auto msg = fnord::StringUtil::format( "invalid tracking pixel url: $0", uri.query()); fnord::log::Logger::get()->logException(fnord::log::kDebug, msg, e); } response->setStatus(fnord::http::kStatusOK); response->addHeader("Content-Type", "image/gif"); response->addHeader("Cache-Control", "no-cache, no-store, must-revalidate"); response->addHeader("Pragma", "no-cache"); response->addHeader("Expires", "0"); response->addBody((void *) &pixel_gif, sizeof(pixel_gif)); return; } response->setStatus(fnord::http::kStatusNotFound); response->addBody("not found"); } void Tracker::addCustomer(CustomerNamespace* customer) { for (const auto& vhost : customer->vhosts()) { if (vhosts_.count(vhost) != 0) { RAISEF(kRuntimeError, "hostname is already registered: $0", vhost); } vhosts_[vhost] = customer; } } void Tracker::recordLogLine( CustomerNamespace* customer, const std::string& logline) { fnord::URI::ParamList params; fnord::URI::parseQueryString(logline, &params); std::string pixel_ver; if (!fnord::URI::getParam(params, "v", &pixel_ver)) { RAISE(kRuntimeError, "missing v parameter"); } try { if (std::stoi(pixel_ver) < kMinPixelVersion) { RAISEF(kRuntimeError, "pixel version too old: $0", pixel_ver); } } catch (const std::exception& e) { RAISEF(kRuntimeError, "invalid pixel version: $0", pixel_ver); } auto feedline = fnord::StringUtil::format( "$0|$1|$2", customer->key(), fnord::WallClock::unixSeconds(), logline); auto pos = feed_->append(feedline); fnord::iputs("write to feed @$0 => $1", pos, feedline); } } // namespace cm <|endoftext|>
<commit_before>#include <iostream> #include <cstring> #include <cassert> #include "ataxx.hpp" #include "search.hpp" #include "movegen.hpp" #include "move.hpp" #include "makemove.hpp" #include "hashtable.hpp" #include "pv.hpp" #include "searchinfo.hpp" #include "eval.hpp" #include "score.hpp" #include "zobrist.hpp" #include "sorting.hpp" #include "next-move.hpp" #include "searchstack.hpp" #include "other.hpp" int reduction(const int move_num, const int depth) { assert(move_num >= 0); assert(depth >= 0); if(move_num < 2 || depth < 3) { return 0; } if(move_num < 6) { return 1; } else if(move_num < 12) { return depth / 3; } else { return depth / 2; } } int alphabeta_search(const Position &pos, search_info &info, search_stack *ss, PV &pv, int alpha, int beta, int depth) { assert(ss != NULL); assert(depth >= 0); assert(beta >= alpha); if(depth == 0 || info.depth >= MAX_DEPTH) { info.leaf_nodes++; return eval(pos); } if(info.nodes != 0) { // Stop searching if we've ran out of time if(*info.stop == true || clock() >= info.end) { return 0; } // Send an update on what we're doing if(info.nodes % 2000000 == 0) { double time_spent = (double)(clock() - info.start)/CLOCKS_PER_SEC; std::cout << "info" << " nps " << (uint64_t)(info.nodes/time_spent) << std::endl; } } int alpha_original = alpha; uint64_t key = generate_key(pos); Move tt_move = NO_MOVE; bool pvnode = (beta - alpha == 1); if(info.tt) { // Check the hash table Entry entry = probe(info.tt, key); if(key == entry.key) { tt_move = get_move(entry); #ifndef NDEBUG info.hash_hits++; if(legal_move(pos, tt_move) == false) { info.hash_collisions++; } #endif if(get_depth(entry) >= depth && legal_move(pos, tt_move) == true) { switch(get_flag(entry)) { case EXACT: pv.num_moves = 1; pv.moves[0] = tt_move; return get_eval(entry); break; case LOWERBOUND: alpha = (alpha > get_eval(entry) ? alpha : get_eval(entry)); break; case UPPERBOUND: beta = (beta < get_eval(entry) ? beta : get_eval(entry)); break; default: assert(false); break; } if(alpha >= beta) { pv.num_moves = 1; pv.moves[0] = tt_move; return get_eval(entry); } } } } #ifdef NULLMOVE #define R (2) if(ss->nullmove && depth > 2 && !pvnode) { PV new_pv; Position new_pos = pos; new_pos.turn = !new_pos.turn; (ss+1)->nullmove = false; int score = -alphabeta_search(new_pos, info, ss+1, new_pv, -beta, -beta+1, depth-1-R); if(score >= beta) { return score; } } (ss+1)->nullmove = true; #endif PV new_pv; Move best_move = NO_MOVE; int best_score = -INF; Move moves[256]; int num_moves = movegen(pos, moves); // Score moves int scores[256] = {0}; for(int n = 0; n < num_moves; ++n) { if(moves[n] == tt_move) { scores[n] = 10001; } #ifdef KILLER_MOVES else if(moves[n] == ss->killer) { scores[n] = 10000; } #endif else { scores[n] = count_captures(pos, moves[n]); scores[n] += (is_single(moves[n]) ? 1 : 0); } } #ifdef IID if(tt_move == NO_MOVE && depth > 5) { int score = -alphabeta_search(pos, info, ss+1, new_pv, -beta, -alpha, depth-3); for(int n = 0; n < num_moves; ++n) { if(moves[n] == new_pv.moves[0]) { scores[n] = 10001; break; } } } #endif int move_num = 0; Move move = NO_MOVE; while(next_move(moves, num_moves, move, scores)) { assert(move != NO_MOVE); Position new_pos = pos; makemove(new_pos, move); info.nodes++; #ifdef FUTILITY_PRUNING int material = 100*(popcountll(new_pos.pieces[new_pos.turn]) - popcountll(new_pos.pieces[!new_pos.turn])); if(move_num > 0 && depth < 3 && -material + 100 < alpha) { continue; } #endif #ifdef LMR int r = reduction(move_num, depth); int score = -alphabeta_search(new_pos, info, ss+1, new_pv, -alpha-1, -alpha, depth-1-r); // Re-search if(score > alpha) { score = -alphabeta_search(new_pos, info, ss+1, new_pv, -beta, -alpha, depth-1); } #else int score = -alphabeta_search(new_pos, info, ss+1, new_pv, -beta, -alpha, depth-1); #endif if(score > best_score) { best_move = move; best_score = score; } if(score > alpha) { alpha = score; // Update PV pv.moves[0] = move; memcpy(pv.moves + 1, new_pv.moves, new_pv.num_moves * sizeof(Move)); pv.num_moves = new_pv.num_moves + 1; } if(alpha >= beta) { #ifdef KILLER_MOVES if(count_captures(pos, move) == 0) { ss->killer = move; } #endif #ifndef NDEBUG info.cutoffs[move_num]++; int num_captured = count_captures(pos, move); info.capture_cutoffs[num_captured]++; if(is_single(move) == true) { info.single_cutoffs++; } else { info.double_cutoffs++; } #endif break; } move_num++; } if(num_moves == 0) { int val = score(pos); if(val > 0) { return INF - ss->ply; } else if(val < 0) { return -INF + ss->ply; } else { return (*info.options).contempt; } } if(info.tt) { uint8_t flag; if(best_score <= alpha_original) { flag = UPPERBOUND; } else if(best_score >= beta) { flag = LOWERBOUND; } else { flag = EXACT; } add(info.tt, key, depth, best_score, best_move, flag); } #ifndef NDEBUG if(info.tt) { Entry test_entry = probe(info.tt, key); assert(test_entry.key == key); assert(test_entry.depth == depth); assert(test_entry.eval == best_score); assert(test_entry.move == best_move); assert(test_entry.flag == flag); } #endif return best_score; } <commit_msg>Debug fix<commit_after>#include <iostream> #include <cstring> #include <cassert> #include "ataxx.hpp" #include "search.hpp" #include "movegen.hpp" #include "move.hpp" #include "makemove.hpp" #include "hashtable.hpp" #include "pv.hpp" #include "searchinfo.hpp" #include "eval.hpp" #include "score.hpp" #include "zobrist.hpp" #include "sorting.hpp" #include "next-move.hpp" #include "searchstack.hpp" #include "other.hpp" int reduction(const int move_num, const int depth) { assert(move_num >= 0); assert(depth >= 0); if(move_num < 2 || depth < 3) { return 0; } if(move_num < 6) { return 1; } else if(move_num < 12) { return depth / 3; } else { return depth / 2; } } int alphabeta_search(const Position &pos, search_info &info, search_stack *ss, PV &pv, int alpha, int beta, int depth) { assert(ss != NULL); assert(depth >= 0); assert(beta >= alpha); if(depth == 0 || info.depth >= MAX_DEPTH) { info.leaf_nodes++; return eval(pos); } if(info.nodes != 0) { // Stop searching if we've ran out of time if(*info.stop == true || clock() >= info.end) { return 0; } // Send an update on what we're doing if(info.nodes % 2000000 == 0) { double time_spent = (double)(clock() - info.start)/CLOCKS_PER_SEC; std::cout << "info" << " nps " << (uint64_t)(info.nodes/time_spent) << std::endl; } } int alpha_original = alpha; uint64_t key = generate_key(pos); Move tt_move = NO_MOVE; bool pvnode = (beta - alpha == 1); if(info.tt) { // Check the hash table Entry entry = probe(info.tt, key); if(key == entry.key) { tt_move = get_move(entry); #ifndef NDEBUG info.hash_hits++; if(legal_move(pos, tt_move) == false) { info.hash_collisions++; } #endif if(get_depth(entry) >= depth && legal_move(pos, tt_move) == true) { switch(get_flag(entry)) { case EXACT: pv.num_moves = 1; pv.moves[0] = tt_move; return get_eval(entry); break; case LOWERBOUND: alpha = (alpha > get_eval(entry) ? alpha : get_eval(entry)); break; case UPPERBOUND: beta = (beta < get_eval(entry) ? beta : get_eval(entry)); break; default: assert(false); break; } if(alpha >= beta) { pv.num_moves = 1; pv.moves[0] = tt_move; return get_eval(entry); } } } } #ifdef NULLMOVE #define R (2) if(ss->nullmove && depth > 2 && !pvnode) { PV new_pv; Position new_pos = pos; new_pos.turn = !new_pos.turn; (ss+1)->nullmove = false; int score = -alphabeta_search(new_pos, info, ss+1, new_pv, -beta, -beta+1, depth-1-R); if(score >= beta) { return score; } } (ss+1)->nullmove = true; #endif PV new_pv; Move best_move = NO_MOVE; int best_score = -INF; Move moves[256]; int num_moves = movegen(pos, moves); // Score moves int scores[256] = {0}; for(int n = 0; n < num_moves; ++n) { if(moves[n] == tt_move) { scores[n] = 10001; } #ifdef KILLER_MOVES else if(moves[n] == ss->killer) { scores[n] = 10000; } #endif else { scores[n] = count_captures(pos, moves[n]); scores[n] += (is_single(moves[n]) ? 1 : 0); } } #ifdef IID if(tt_move == NO_MOVE && depth > 5) { int score = -alphabeta_search(pos, info, ss+1, new_pv, -beta, -alpha, depth-3); for(int n = 0; n < num_moves; ++n) { if(moves[n] == new_pv.moves[0]) { scores[n] = 10001; break; } } } #endif int move_num = 0; Move move = NO_MOVE; while(next_move(moves, num_moves, move, scores)) { assert(move != NO_MOVE); Position new_pos = pos; makemove(new_pos, move); info.nodes++; #ifdef FUTILITY_PRUNING int material = 100*(popcountll(new_pos.pieces[new_pos.turn]) - popcountll(new_pos.pieces[!new_pos.turn])); if(move_num > 0 && depth < 3 && -material + 100 < alpha) { continue; } #endif #ifdef LMR int r = reduction(move_num, depth); int score = -alphabeta_search(new_pos, info, ss+1, new_pv, -alpha-1, -alpha, depth-1-r); // Re-search if(score > alpha) { score = -alphabeta_search(new_pos, info, ss+1, new_pv, -beta, -alpha, depth-1); } #else int score = -alphabeta_search(new_pos, info, ss+1, new_pv, -beta, -alpha, depth-1); #endif if(score > best_score) { best_move = move; best_score = score; } if(score > alpha) { alpha = score; // Update PV pv.moves[0] = move; memcpy(pv.moves + 1, new_pv.moves, new_pv.num_moves * sizeof(Move)); pv.num_moves = new_pv.num_moves + 1; } if(alpha >= beta) { #ifdef KILLER_MOVES if(count_captures(pos, move) == 0) { ss->killer = move; } #endif #ifndef NDEBUG info.cutoffs[move_num]++; int num_captured = count_captures(pos, move); info.capture_cutoffs[num_captured]++; if(is_single(move) == true) { info.single_cutoffs++; } else { info.double_cutoffs++; } #endif break; } move_num++; } if(num_moves == 0) { int val = score(pos); if(val > 0) { return INF - ss->ply; } else if(val < 0) { return -INF + ss->ply; } else { return (*info.options).contempt; } } uint8_t flag; if(info.tt) { if(best_score <= alpha_original) { flag = UPPERBOUND; } else if(best_score >= beta) { flag = LOWERBOUND; } else { flag = EXACT; } add(info.tt, key, depth, best_score, best_move, flag); } #ifndef NDEBUG if(info.tt) { Entry test_entry = probe(info.tt, key); assert(test_entry.key == key); assert(test_entry.depth == depth); assert(test_entry.eval == best_score); assert(test_entry.move == best_move); assert(test_entry.flag == flag); } #endif return best_score; } <|endoftext|>
<commit_before>#include <paths.h> #include <sys/stat.h> #include <stdio.h> #include <cerrno> #include <cstring> #include <iostream> #include <fstream> #include <unordered_map> #include <string> #include <stdio.h> #include <string.h> #include <sstream> #include "../os.h" #include "../../base/logger.h" #include <mntent.h> #include <dirent.h> #include <sys/utsname.h> #ifndef NDEBUG #include <valgrind/memcheck.h> #endif #ifdef USE_DISK_MODEL #define PARSE_ID_FUNC parse_disk_id #define ID_FOLDER "/dev/disk/by-id/" #else #define PARSE_ID_FUNC parseUUID #define ID_FOLDER "/dev/disk/by-uuid/" #endif #ifdef USE_DBUS #include <dbus-1.0/dbus/dbus.h> #endif /** *Usually uuid are hex number separated by "-". this method read up to 8 hex *numbers skipping - characters. *@param uuid uuid as read in /dev/disk/by-uuid *@param buffer_out: unsigned char buffer[8] output buffer for result */ static void parseUUID(const char *uuid, unsigned char *buffer_out, unsigned int out_size) { unsigned int i, j; char *hexuuid; unsigned char cur_character; // remove characters not in hex set size_t len = strlen(uuid); hexuuid = (char *)malloc(sizeof(char) * len); memset(buffer_out, 0, out_size); memset(hexuuid, 0, sizeof(char) * len); for (i = 0, j = 0; i < len; i++) { if (isxdigit(uuid[i])) { hexuuid[j] = uuid[i]; j++; } else { // skip continue; } } if (j % 2 == 1) { hexuuid[j++] = '0'; } hexuuid[j] = '\0'; for (i = 0; i < j / 2; i++) { sscanf(&hexuuid[i * 2], "%2hhx", &cur_character); buffer_out[i % out_size] = buffer_out[i % out_size] ^ cur_character; } free(hexuuid); } static void parse_disk_id(const char *uuid, unsigned char *buffer_out, size_t out_size) { unsigned int i; size_t len = strlen(uuid); memset(buffer_out, 0, out_size); for (i = 0; i < len; i++) { buffer_out[i % out_size] = buffer_out[i % out_size] ^ uuid[i]; } } /** * int id; char device[MAX_PATH]; unsigned char disk_sn[8]; char label[255]; int preferred; * @param blkidfile * @param diskInfos_out * @return */ static std::string getAttribute(const std::string &source, const std::string &attrName) { std::string attr_namefull = attrName + "=\""; std::size_t startpos = source.find(attr_namefull) + attr_namefull.size(); std::size_t endpos = source.find("\"", startpos); return source.substr(startpos, endpos - startpos); } FUNCTION_RETURN parse_blkid(const std::string &blkid_file_content, std::vector<DiskInfo> &diskInfos_out) { DiskInfo diskInfo; int diskNum = 0; for (std::size_t oldpos = 0, pos = 0; (pos = blkid_file_content.find("</device>", oldpos)) != std::string::npos; oldpos = pos + 1) { std::string cur_dev = blkid_file_content.substr(oldpos, pos); diskInfo.id = diskNum++; std::string device = cur_dev.substr(cur_dev.find_last_of(">") + 1); strncpy(diskInfo.device, device.c_str(), MAX_PATH); std::string label = getAttribute(cur_dev, "PARTLABEL"); strncpy(diskInfo.label, label.c_str(), 255); std::string disk_sn = getAttribute(cur_dev, "UUID"); parseUUID(disk_sn.c_str(), diskInfo.disk_sn, sizeof(diskInfo.disk_sn)); std::string disk_type = getAttribute(cur_dev, "TYPE"); // unlikely that somebody put the swap on a removable disk. // this is a first rough guess on what can be a preferred disk for blkid devices // just in case /etc/fstab can't be accessed or it is not up to date. diskInfo.preferred = (disk_type == "swap"); diskInfos_out.push_back(diskInfo); } return FUNCTION_RETURN::FUNC_RET_OK; } #define BLKID_LOCATIONS {"/run/blkid/blkid.tab", "/etc/blkid.tab"}; static FUNCTION_RETURN getDiskInfos_blkid(std::vector<DiskInfo> &diskInfos) { const char *strs[] = BLKID_LOCATIONS; bool can_read = false; std::stringstream buffer; for (int i = 0; i < sizeof(strs) / sizeof(const char *); i++) { const char *location = strs[i]; std::ifstream t(location); if (t.is_open()) { buffer << t.rdbuf(); can_read = true; break; } } if (!can_read) { return FUNCTION_RETURN::FUNC_RET_NOT_AVAIL; } return parse_blkid(buffer.str(), diskInfos); } #define MAX_UNITS 40 FUNCTION_RETURN getDiskInfos_dev(std::vector<DiskInfo> &diskInfos) { struct dirent *dir = NULL; struct stat sym_stat; FUNCTION_RETURN result; DIR *disk_by_uuid_dir = opendir(ID_FOLDER); if (disk_by_uuid_dir == nullptr) { LOG_DEBUG("Open " ID_FOLDER " fail"); } else { const std::string base_dir(ID_FOLDER "/"); while ((dir = readdir(disk_by_uuid_dir)) != nullptr && diskInfos.size() < MAX_UNITS) { if (strcmp(dir->d_name, ".") == 0 || strcmp(dir->d_name, "..") == 0 || strncmp(dir->d_name, "usb", 3) == 0) { continue; } std::string cur_dir = base_dir + dir->d_name; if (stat(cur_dir.c_str(), &sym_stat) == 0) { DiskInfo tmpDiskInfo; tmpDiskInfo.id = sym_stat.st_ino; ssize_t len = ::readlink(cur_dir.c_str(), tmpDiskInfo.device, sizeof(tmpDiskInfo.device) - 1); if (len != -1) { tmpDiskInfo.device[len] = '\0'; PARSE_ID_FUNC(dir->d_name, tmpDiskInfo.disk_sn, sizeof(tmpDiskInfo.disk_sn)); tmpDiskInfo.sn_initialized = true; tmpDiskInfo.label_initialized = false; tmpDiskInfo.preferred = false; bool found = false; for (auto diskInfo : diskInfos) { if (tmpDiskInfo.id == diskInfo.id) { found = true; break; } } if (!found) { diskInfos.push_back(tmpDiskInfo); } } else { LOG_DEBUG("Error %s during readlink of %s", std::strerror(errno), cur_dir.c_str()); } } else { LOG_DEBUG("Error %s during stat of %s", std::strerror(errno), cur_dir.c_str()); } } closedir(disk_by_uuid_dir); } result = diskInfos.size() > 0 ? FUNCTION_RETURN::FUNC_RET_OK : FUNCTION_RETURN::FUNC_RET_NOT_AVAIL; const std::string label_dir("/dev/disk/by-label"); DIR *disk_by_label = opendir(label_dir.c_str()); if (disk_by_label != nullptr) { while ((dir = readdir(disk_by_label)) != nullptr) { if (strcmp(dir->d_name, ".") == 0 || strcmp(dir->d_name, "..") == 0) { continue; } std::string cur_disk_label = label_dir + "/" + dir->d_name; if (stat(cur_disk_label.c_str(), &sym_stat) == 0) { bool found = false; for (auto diskInfo : diskInfos) { if (((int)sym_stat.st_ino) == diskInfo.id) { strncpy(diskInfo.label, dir->d_name, 255 - 1); diskInfo.label_initialized = true; break; } } } else { LOG_DEBUG("Stat %s for fail:F %s", cur_disk_label, std::strerror(errno)); } } closedir(disk_by_label); } else { LOG_DEBUG("Open %s for reading disk labels fail", label_dir); } return result; } /** * Try to determine removable devices: as a first guess removable devices doesn't have * an entry in /etc/fstab * * @param diskInfos */ static void set_preferred_disks(std::vector<DiskInfo> &diskInfos) { FILE *fstabFile = setmntent("/etc/fstab", "r"); if (fstabFile == nullptr) { /*fstab not accessible*/ return; } struct mntent *ent; while (nullptr != (ent = getmntent(fstabFile))) { bool found = false; for (auto disk_info : diskInfos) { if (strcmp(ent->mnt_fsname, disk_info.device) == 0) { disk_info.preferred = true; break; } } } endmntent(fstabFile); return; } /** * First try to read disk_infos from /dev/disk/by-id folder, if fails try to use * blkid cache to see what's in there, then try to exclude removable disks * looking at /etc/fstab * @param diskInfos_out vector used to output the disk informations * @return */ FUNCTION_RETURN getDiskInfos(std::vector<DiskInfo> &disk_infos) { FUNCTION_RETURN result = getDiskInfos_dev(disk_infos); if (result != FUNCTION_RETURN::FUNC_RET_OK) { result = getDiskInfos_blkid(disk_infos); } if (result == FUNCTION_RETURN::FUNC_RET_OK) { set_preferred_disks(disk_infos); } return result; } FUNCTION_RETURN getMachineName(unsigned char identifier[6]) { static struct utsname u; if (uname(&u) < 0) { return FUNC_RET_ERROR; } memcpy(identifier, u.nodename, 6); return FUNC_RET_OK; } FUNCTION_RETURN getOsSpecificIdentifier(unsigned char identifier[6]) { #if USE_DBUS char *dbus_id = dbus_get_local_machine_id(); if (dbus_id == NULL) { return FUNC_RET_ERROR; } memcpy(identifier, dbus_id, 6); dbus_free(dbus_id); return FUNC_RET_OK; #else return FUNC_RET_NOT_AVAIL; #endif } FUNCTION_RETURN getModuleName(char buffer[MAX_PATH]) { FUNCTION_RETURN result; char path[MAX_PATH] = {0}; char proc_path[MAX_PATH], pidStr[64]; pid_t pid = getpid(); sprintf(pidStr, "%d", pid); strcpy(proc_path, "/proc/"); strcat(proc_path, pidStr); strcat(proc_path, "/exe"); int ch = readlink(proc_path, path, MAX_PATH - 1); if (ch != -1) { path[ch] = '\0'; strncpy(buffer, path, ch); result = FUNC_RET_OK; } else { result = FUNC_RET_ERROR; } return result; } <commit_msg>better logging<commit_after>#include <paths.h> #include <sys/stat.h> #include <stdio.h> #include <cerrno> #include <cstring> #include <iostream> #include <fstream> #include <unordered_map> #include <string> #include <stdio.h> #include <string.h> #include <sstream> #include "../os.h" #include "../../base/logger.h" #include <mntent.h> #include <dirent.h> #include <sys/utsname.h> #ifndef NDEBUG #include <valgrind/memcheck.h> #endif #ifdef USE_DISK_MODEL #define PARSE_ID_FUNC parse_disk_id #define ID_FOLDER "/dev/disk/by-id" #else #define PARSE_ID_FUNC parseUUID #define ID_FOLDER "/dev/disk/by-uuid" #endif #ifdef USE_DBUS #include <dbus-1.0/dbus/dbus.h> #endif /** *Usually uuid are hex number separated by "-". this method read up to 8 hex *numbers skipping - characters. *@param uuid uuid as read in /dev/disk/by-uuid *@param buffer_out: unsigned char buffer[8] output buffer for result */ static void parseUUID(const char *uuid, unsigned char *buffer_out, unsigned int out_size) { unsigned int i, j; char *hexuuid; unsigned char cur_character; // remove characters not in hex set size_t len = strlen(uuid); hexuuid = (char *)malloc(sizeof(char) * len); memset(buffer_out, 0, out_size); memset(hexuuid, 0, sizeof(char) * len); for (i = 0, j = 0; i < len; i++) { if (isxdigit(uuid[i])) { hexuuid[j] = uuid[i]; j++; } else { // skip continue; } } if (j % 2 == 1) { hexuuid[j++] = '0'; } hexuuid[j] = '\0'; for (i = 0; i < j / 2; i++) { sscanf(&hexuuid[i * 2], "%2hhx", &cur_character); buffer_out[i % out_size] = buffer_out[i % out_size] ^ cur_character; } free(hexuuid); } static void parse_disk_id(const char *uuid, unsigned char *buffer_out, size_t out_size) { unsigned int i; size_t len = strlen(uuid); memset(buffer_out, 0, out_size); for (i = 0; i < len; i++) { buffer_out[i % out_size] = buffer_out[i % out_size] ^ uuid[i]; } } /** * int id; char device[MAX_PATH]; unsigned char disk_sn[8]; char label[255]; int preferred; * @param blkidfile * @param diskInfos_out * @return */ static std::string getAttribute(const std::string &source, const std::string &attrName) { std::string attr_namefull = attrName + "=\""; std::size_t startpos = source.find(attr_namefull) + attr_namefull.size(); std::size_t endpos = source.find("\"", startpos); return source.substr(startpos, endpos - startpos); } FUNCTION_RETURN parse_blkid(const std::string &blkid_file_content, std::vector<DiskInfo> &diskInfos_out) { DiskInfo diskInfo; int diskNum = 0; for (std::size_t oldpos = 0, pos = 0; (pos = blkid_file_content.find("</device>", oldpos)) != std::string::npos; oldpos = pos + 1) { std::string cur_dev = blkid_file_content.substr(oldpos, pos); diskInfo.id = diskNum++; std::string device = cur_dev.substr(cur_dev.find_last_of(">") + 1); strncpy(diskInfo.device, device.c_str(), MAX_PATH); std::string label = getAttribute(cur_dev, "PARTLABEL"); strncpy(diskInfo.label, label.c_str(), 255); std::string disk_sn = getAttribute(cur_dev, "UUID"); parseUUID(disk_sn.c_str(), diskInfo.disk_sn, sizeof(diskInfo.disk_sn)); std::string disk_type = getAttribute(cur_dev, "TYPE"); // unlikely that somebody put the swap on a removable disk. // this is a first rough guess on what can be a preferred disk for blkid devices // just in case /etc/fstab can't be accessed or it is not up to date. diskInfo.preferred = (disk_type == "swap"); diskInfos_out.push_back(diskInfo); } return FUNCTION_RETURN::FUNC_RET_OK; } #define BLKID_LOCATIONS {"/run/blkid/blkid.tab", "/etc/blkid.tab"}; static FUNCTION_RETURN getDiskInfos_blkid(std::vector<DiskInfo> &diskInfos) { const char *strs[] = BLKID_LOCATIONS; bool can_read = false; std::stringstream buffer; for (int i = 0; i < sizeof(strs) / sizeof(const char *); i++) { const char *location = strs[i]; std::ifstream t(location); if (t.is_open()) { buffer << t.rdbuf(); can_read = true; break; } } if (!can_read) { return FUNCTION_RETURN::FUNC_RET_NOT_AVAIL; } return parse_blkid(buffer.str(), diskInfos); } #define MAX_UNITS 40 FUNCTION_RETURN getDiskInfos_dev(std::vector<DiskInfo> &diskInfos) { struct dirent *dir = NULL; struct stat sym_stat; FUNCTION_RETURN result; DIR *disk_by_uuid_dir = opendir(ID_FOLDER); if (disk_by_uuid_dir == nullptr) { LOG_DEBUG("Open " ID_FOLDER " fail: %s", std::strerror(errno)); } else { const std::string base_dir(ID_FOLDER "/"); while ((dir = readdir(disk_by_uuid_dir)) != nullptr && diskInfos.size() < MAX_UNITS) { if (strcmp(dir->d_name, ".") == 0 || strcmp(dir->d_name, "..") == 0 || strncmp(dir->d_name, "usb", 3) == 0) { continue; } std::string cur_dir = base_dir + dir->d_name; if (stat(cur_dir.c_str(), &sym_stat) == 0) { DiskInfo tmpDiskInfo; tmpDiskInfo.id = sym_stat.st_ino; ssize_t len = ::readlink(cur_dir.c_str(), tmpDiskInfo.device, sizeof(tmpDiskInfo.device) - 1); if (len != -1) { tmpDiskInfo.device[len] = '\0'; PARSE_ID_FUNC(dir->d_name, tmpDiskInfo.disk_sn, sizeof(tmpDiskInfo.disk_sn)); tmpDiskInfo.sn_initialized = true; tmpDiskInfo.label_initialized = false; tmpDiskInfo.preferred = false; bool found = false; for (auto diskInfo : diskInfos) { if (tmpDiskInfo.id == diskInfo.id) { found = true; break; } } if (!found) { LOG_DEBUG("Found disk inode %d device %s, sn %s", sym_stat.st_ino, tmpDiskInfo.device, dir->d_name); diskInfos.push_back(tmpDiskInfo); } } else { LOG_DEBUG("Error %s during readlink of %s", std::strerror(errno), cur_dir.c_str()); } } else { LOG_DEBUG("Error %s during stat of %s", std::strerror(errno), cur_dir.c_str()); } } closedir(disk_by_uuid_dir); } result = diskInfos.size() > 0 ? FUNCTION_RETURN::FUNC_RET_OK : FUNCTION_RETURN::FUNC_RET_NOT_AVAIL; const std::string label_dir("/dev/disk/by-label"); DIR *disk_by_label = opendir(label_dir.c_str()); if (disk_by_label != nullptr) { while ((dir = readdir(disk_by_label)) != nullptr) { if (strcmp(dir->d_name, ".") == 0 || strcmp(dir->d_name, "..") == 0) { continue; } std::string cur_disk_label = label_dir + "/" + dir->d_name; if (stat(cur_disk_label.c_str(), &sym_stat) == 0) { bool found = false; for (auto diskInfo : diskInfos) { if (((int)sym_stat.st_ino) == diskInfo.id) { strncpy(diskInfo.label, dir->d_name, 255 - 1); diskInfo.label_initialized = true; break; } } } else { LOG_DEBUG("Stat %s for fail:F %s", cur_disk_label.c_str(), std::strerror(errno)); } } closedir(disk_by_label); } else { LOG_DEBUG("Open %s for reading disk labels fail: %s", label_dir.c_str(), std::strerror(errno)); } return result; } /** * Try to determine removable devices: as a first guess removable devices doesn't have * an entry in /etc/fstab * * @param diskInfos */ static void set_preferred_disks(std::vector<DiskInfo> &diskInfos) { FILE *fstabFile = setmntent("/etc/fstab", "r"); if (fstabFile == nullptr) { /*fstab not accessible*/ return; } struct mntent *ent; while (nullptr != (ent = getmntent(fstabFile))) { bool found = false; for (auto disk_info : diskInfos) { if (strcmp(ent->mnt_fsname, disk_info.device) == 0) { disk_info.preferred = true; break; } } } endmntent(fstabFile); return; } /** * First try to read disk_infos from /dev/disk/by-id folder, if fails try to use * blkid cache to see what's in there, then try to exclude removable disks * looking at /etc/fstab * @param diskInfos_out vector used to output the disk informations * @return */ FUNCTION_RETURN getDiskInfos(std::vector<DiskInfo> &disk_infos) { FUNCTION_RETURN result = getDiskInfos_dev(disk_infos); if (result != FUNCTION_RETURN::FUNC_RET_OK) { result = getDiskInfos_blkid(disk_infos); } if (result == FUNCTION_RETURN::FUNC_RET_OK) { set_preferred_disks(disk_infos); } return result; } FUNCTION_RETURN getMachineName(unsigned char identifier[6]) { static struct utsname u; if (uname(&u) < 0) { return FUNC_RET_ERROR; } memcpy(identifier, u.nodename, 6); return FUNC_RET_OK; } FUNCTION_RETURN getOsSpecificIdentifier(unsigned char identifier[6]) { #if USE_DBUS char *dbus_id = dbus_get_local_machine_id(); if (dbus_id == NULL) { return FUNC_RET_ERROR; } memcpy(identifier, dbus_id, 6); dbus_free(dbus_id); return FUNC_RET_OK; #else return FUNC_RET_NOT_AVAIL; #endif } FUNCTION_RETURN getModuleName(char buffer[MAX_PATH]) { FUNCTION_RETURN result; char path[MAX_PATH] = {0}; char proc_path[MAX_PATH], pidStr[64]; pid_t pid = getpid(); sprintf(pidStr, "%d", pid); strcpy(proc_path, "/proc/"); strcat(proc_path, pidStr); strcat(proc_path, "/exe"); int ch = readlink(proc_path, path, MAX_PATH - 1); if (ch != -1) { path[ch] = '\0'; strncpy(buffer, path, ch); result = FUNC_RET_OK; } else { result = FUNC_RET_ERROR; } return result; } <|endoftext|>
<commit_before>/* * The Apache Software License, Version 1.1 * * Copyright (c) 1999-2000 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "Xerces" and "Apache Software Foundation" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact apache\@apache.org. * * 5. Products derived from this software may not be called "Apache", * nor may "Apache" appear in their name, without prior written * permission of the Apache Software Foundation. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation, and was * originally based on software copyright (c) 1999, International * Business Machines, Inc., http://www.ibm.com . For more information * on the Apache Software Foundation, please see * <http://www.apache.org/>. */ /* * $Log$ * Revision 1.15 2000/09/21 00:54:18 aruna1 * OS2 related changes given by Bill Schindler * * Revision 1.14 2000/08/01 18:26:02 aruna1 * Tru64 support added * * Revision 1.13 2000/07/18 18:25:58 andyh * Mac OS update. * Contributed by James Berry <[email protected]> * * Revision 1.12 2000/04/04 20:11:29 abagchi * Added PTX support * * Revision 1.11 2000/03/02 19:54:37 roddey * This checkin includes many changes done while waiting for the * 1.1.0 code to be finished. I can't list them all here, but a list is * available elsewhere. * * Revision 1.10 2000/03/02 01:51:00 aruna1 * Sun CC 5.0 related changes * * Revision 1.9 2000/02/24 20:05:23 abagchi * Swat for removing Log from API docs * * Revision 1.8 2000/02/22 01:00:10 aruna1 * GNUGDefs references removed. Now only GCCDefs is used instead * * Revision 1.7 2000/02/06 07:48:00 rahulj * Year 2K copyright swat. * * Revision 1.6 2000/02/01 23:43:22 abagchi * AS/400 related change * * Revision 1.5 2000/01/21 22:12:29 abagchi * OS390 Change: changed OE390 to OS390 * * Revision 1.4 1999/12/18 00:47:01 rahulj * Merged in some changes for OS390. * * Revision 1.3 1999/12/17 01:28:53 rahulj * Merged in changes submitted for UnixWare 7 port. Platform * specific files are still missing. * * Revision 1.2 1999/12/01 17:16:16 rahulj * Added support for IRIX 6.5.5 using SGI MIPSpro C++ 7.3 and 7.21 generating 32 bit objects. Changes submitted by Marc Stuessel * * Revision 1.1.1.1 1999/11/09 01:03:55 twl * Initial checkin * * Revision 1.2 1999/11/08 20:45:03 rahul * Swat for adding in Product name and CVS comment log variable. * */ #ifndef AUTOSENSE_HPP #define AUTOSENSE_HPP // --------------------------------------------------------------------------- // This section attempts to auto detect the operating system. It will set // up XercesC specific defines that are used by the rest of the code. // --------------------------------------------------------------------------- #if defined(_AIX) #define XML_AIX #define XML_UNIX #elif defined(_SEQUENT_) #define XML_PTX #define XML_UNIX #elif defined(_HP_UX) || defined(__hpux) || defined(_HPUX_SOURCE) #define XML_HPUX #define XML_UNIX #elif defined(SOLARIS) || defined(__SVR4) || defined(UNIXWARE) #if defined(UNIXWARE) #define XML_UNIXWARE #define XML_CSET #define XML_SCOCC #define XML_UNIX #else #define XML_SOLARIS #define XML_UNIX #endif #elif defined(__linux__) #define XML_LINUX #define XML_UNIX #elif defined(IRIX) #define XML_IRIX #define XML_UNIX #elif defined(__MVS__) #define XML_OS390 #define XML_UNIX #elif defined(EXM_OS390) #define XML_OS390 #define XML_UNIX #elif defined(__OS400__) #define XML_AS400 #define XML_UNIX #elif defined(__OS2__) #define XML_OS2 #elif defined(__TANDEM) #define XML_TANDEM #define XML_UNIX #define XML_CSET #elif defined(_WIN32) || defined(WIN32) #define XML_WIN32 #ifndef WIN32 #define WIN32 #endif #elif defined(__WINDOWS__) // IBM VisualAge special handling #if defined(__32BIT__) #define XML_WIN32 #else #define XML_WIN16 #endif #elif defined(__MSDXML__) #define XML_DOS #elif defined(macintosh) #define XML_MACOS #elif defined(MACOSX) #define XML_MACOSX #elif defined(__alpha) && defined(__osf__) #define XML_TRU64 #else #error Code requires port to host OS! #endif // --------------------------------------------------------------------------- // This section attempts to autodetect the compiler being used. It will set // up Xerces specific defines that can be used by the rest of the code. // --------------------------------------------------------------------------- #if defined(_MSC_VER) #define XML_VISUALCPP #elif defined(__BORLANDC__) #define XML_BORLAND #elif defined(__xlC__) #define XML_CSET #elif defined(XML_SOLARIS) || defined(XML_UNIXWARE) #if defined(__SUNPRO_CC) & __SUNPRO_CC >=0x500 #define XML_SUNCC5 #elif defined(__SUNPRO_CC) & __SUNPRO_CC <0x500 #define XML_SUNCC #elif defined(_EDG_RUNTIME_USES_NAMESPACES) #define XML_SOLARIS_KAICC #elif defined(__GNUG__) #define XML_GCC #endif #elif defined (__GNUG__) || defined(__linux__) #define XML_GCC #elif defined(XML_HPUX) #if defined(EXM_HPUX) #define XML_HPUX_KAICC #elif (__cplusplus == 1) #define XML_HPUX_CC #elif (__cplusplus == 199707 || __cplusplus == 199711) #define XML_HPUX_aCC #endif #elif defined(XML_IRIX) #define XML_MIPSPRO_CC #elif defined(XML_PTX) #define XML_PTX_CC #elif defined(XML_TANDEM) #define XML_TANDEMCC #elif defined(__MVS__) && defined(__cplusplus) #define XML_MVSCPP #elif defined(EXM_OS390) && defined(__cplusplus) #define XML_MVSCPP #elif defined(__IBMC__) || defined(__IBMCPP__) #if defined(XML_WIN32) #define XML_IBMVAW32 #elif defined(XML_OS2) #define XML_IBMVAOS2 #if (__IBMC__ >= 400 || __IBMCPP__ >= 400) #define XML_IBMVA4_OS2 #endif #endif #elif defined(XML_TRU64) && defined(__DECCXX) #define XML_DECCXX #elif defined(__MWERKS__) #define XML_METROWERKS #elif defined(__OS400__) #else #error Code requires port to current development environment #endif #endif <commit_msg>Modify sensing of Mac OS X. PR: Obtained from: Submitted by: Reviewed by: PR: Obtained from: Submitted by: Reviewed by:<commit_after>/* * The Apache Software License, Version 1.1 * * Copyright (c) 1999-2000 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "Xerces" and "Apache Software Foundation" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact apache\@apache.org. * * 5. Products derived from this software may not be called "Apache", * nor may "Apache" appear in their name, without prior written * permission of the Apache Software Foundation. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation, and was * originally based on software copyright (c) 1999, International * Business Machines, Inc., http://www.ibm.com . For more information * on the Apache Software Foundation, please see * <http://www.apache.org/>. */ /* * $Log$ * Revision 1.16 2000/10/09 18:15:43 jberry * Modify sensing of Mac OS X. * PR: * Obtained from: * Submitted by: * Reviewed by: * PR: * Obtained from: * Submitted by: * Reviewed by: * * Revision 1.15 2000/09/21 00:54:18 aruna1 * OS2 related changes given by Bill Schindler * * Revision 1.14 2000/08/01 18:26:02 aruna1 * Tru64 support added * * Revision 1.13 2000/07/18 18:25:58 andyh * Mac OS update. * Contributed by James Berry <[email protected]> * * Revision 1.12 2000/04/04 20:11:29 abagchi * Added PTX support * * Revision 1.11 2000/03/02 19:54:37 roddey * This checkin includes many changes done while waiting for the * 1.1.0 code to be finished. I can't list them all here, but a list is * available elsewhere. * * Revision 1.10 2000/03/02 01:51:00 aruna1 * Sun CC 5.0 related changes * * Revision 1.9 2000/02/24 20:05:23 abagchi * Swat for removing Log from API docs * * Revision 1.8 2000/02/22 01:00:10 aruna1 * GNUGDefs references removed. Now only GCCDefs is used instead * * Revision 1.7 2000/02/06 07:48:00 rahulj * Year 2K copyright swat. * * Revision 1.6 2000/02/01 23:43:22 abagchi * AS/400 related change * * Revision 1.5 2000/01/21 22:12:29 abagchi * OS390 Change: changed OE390 to OS390 * * Revision 1.4 1999/12/18 00:47:01 rahulj * Merged in some changes for OS390. * * Revision 1.3 1999/12/17 01:28:53 rahulj * Merged in changes submitted for UnixWare 7 port. Platform * specific files are still missing. * * Revision 1.2 1999/12/01 17:16:16 rahulj * Added support for IRIX 6.5.5 using SGI MIPSpro C++ 7.3 and 7.21 generating 32 bit objects. Changes submitted by Marc Stuessel * * Revision 1.1.1.1 1999/11/09 01:03:55 twl * Initial checkin * * Revision 1.2 1999/11/08 20:45:03 rahul * Swat for adding in Product name and CVS comment log variable. * */ #ifndef AUTOSENSE_HPP #define AUTOSENSE_HPP // --------------------------------------------------------------------------- // This section attempts to auto detect the operating system. It will set // up XercesC specific defines that are used by the rest of the code. // --------------------------------------------------------------------------- #if defined(_AIX) #define XML_AIX #define XML_UNIX #elif defined(_SEQUENT_) #define XML_PTX #define XML_UNIX #elif defined(_HP_UX) || defined(__hpux) || defined(_HPUX_SOURCE) #define XML_HPUX #define XML_UNIX #elif defined(SOLARIS) || defined(__SVR4) || defined(UNIXWARE) #if defined(UNIXWARE) #define XML_UNIXWARE #define XML_CSET #define XML_SCOCC #define XML_UNIX #else #define XML_SOLARIS #define XML_UNIX #endif #elif defined(__linux__) #define XML_LINUX #define XML_UNIX #elif defined(IRIX) #define XML_IRIX #define XML_UNIX #elif defined(__MVS__) #define XML_OS390 #define XML_UNIX #elif defined(EXM_OS390) #define XML_OS390 #define XML_UNIX #elif defined(__OS400__) #define XML_AS400 #define XML_UNIX #elif defined(__OS2__) #define XML_OS2 #elif defined(__TANDEM) #define XML_TANDEM #define XML_UNIX #define XML_CSET #elif defined(_WIN32) || defined(WIN32) #define XML_WIN32 #ifndef WIN32 #define WIN32 #endif #elif defined(__WINDOWS__) // IBM VisualAge special handling #if defined(__32BIT__) #define XML_WIN32 #else #define XML_WIN16 #endif #elif defined(__MSDXML__) #define XML_DOS #elif defined(macintosh) #define XML_MACOS #elif defined(__APPLE__) && defined(__MACH__) #define XML_MACOSX #elif defined(__alpha) && defined(__osf__) #define XML_TRU64 #else #error Code requires port to host OS! #endif // --------------------------------------------------------------------------- // This section attempts to autodetect the compiler being used. It will set // up Xerces specific defines that can be used by the rest of the code. // --------------------------------------------------------------------------- #if defined(_MSC_VER) #define XML_VISUALCPP #elif defined(__BORLANDC__) #define XML_BORLAND #elif defined(__xlC__) #define XML_CSET #elif defined(XML_SOLARIS) || defined(XML_UNIXWARE) #if defined(__SUNPRO_CC) & __SUNPRO_CC >=0x500 #define XML_SUNCC5 #elif defined(__SUNPRO_CC) & __SUNPRO_CC <0x500 #define XML_SUNCC #elif defined(_EDG_RUNTIME_USES_NAMESPACES) #define XML_SOLARIS_KAICC #elif defined(__GNUG__) #define XML_GCC #endif #elif defined (__GNUG__) || defined(__linux__) #define XML_GCC #elif defined(XML_HPUX) #if defined(EXM_HPUX) #define XML_HPUX_KAICC #elif (__cplusplus == 1) #define XML_HPUX_CC #elif (__cplusplus == 199707 || __cplusplus == 199711) #define XML_HPUX_aCC #endif #elif defined(XML_IRIX) #define XML_MIPSPRO_CC #elif defined(XML_PTX) #define XML_PTX_CC #elif defined(XML_TANDEM) #define XML_TANDEMCC #elif defined(__MVS__) && defined(__cplusplus) #define XML_MVSCPP #elif defined(EXM_OS390) && defined(__cplusplus) #define XML_MVSCPP #elif defined(__IBMC__) || defined(__IBMCPP__) #if defined(XML_WIN32) #define XML_IBMVAW32 #elif defined(XML_OS2) #define XML_IBMVAOS2 #if (__IBMC__ >= 400 || __IBMCPP__ >= 400) #define XML_IBMVA4_OS2 #endif #endif #elif defined(XML_TRU64) && defined(__DECCXX) #define XML_DECCXX #elif defined(__MWERKS__) #define XML_METROWERKS #elif defined(__OS400__) #else #error Code requires port to current development environment #endif #endif <|endoftext|>
<commit_before>/************************************************************************** ** ** This file is part of Qt Creator ** ** Copyright (c) 2012 Nokia Corporation and/or its subsidiary(-ies). ** ** Contact: Nokia Corporation ([email protected]) ** ** ** 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 [email protected]. ** **************************************************************************/ #include "syssocket.h" // this should be the first header included #include "servicebrowser_p.h" #include <QCoreApplication> #include <QDebug> #include <QFileInfo> #include <QString> #include <QStringList> #include <QProcess> #ifdef Q_OS_LINUX #define EMBEDDED_LIB #endif #ifdef Q_OS_WIN32 #define EMBEDDED_LIB #endif #ifdef EMBEDDED_LIB #define PID_FILE "/tmp/mdnsd.pid" #define MDNS_UDS_SERVERPATH "/tmp/mdnsd" #include "embed/dnssd_ipc.c" #include "embed/dnssd_clientlib.c" #include "embed/dnssd_clientstub.c" #ifdef Q_OS_WIN #include "embed/DebugServices.c" #endif namespace ZeroConf { namespace Internal { // represents a zero conf library exposing the dns-sd interface class EmbeddedZConfLib : public ZConfLib { public: QString daemonPath; EmbeddedZConfLib(const QString &daemonPath, ZConfLib::Ptr fallBack) : ZConfLib(fallBack), daemonPath(daemonPath) { if (daemonPath.isEmpty()) m_maxErrors = 0; if (!daemonPath.isEmpty() && daemonPath.at(0) != '/' && daemonPath.at(0) != '.') this->daemonPath = QCoreApplication::applicationDirPath() + QChar('/') + daemonPath; } ~EmbeddedZConfLib() { } QString name() { return QString::fromLatin1("EmbeddedZeroConfLib@%1").arg(size_t(this), 0, 16); } bool tryStartDaemon() { if (!daemonPath.isEmpty()) { QFileInfo dPath(daemonPath); QProcess killall; bool killAllFailed = false; #ifdef Q_OS_WIN QString cmd = QLating1String("taskill /im ") + dPath.fileName() + QLatin1String(" /f /t"); #else QString cmd = QLatin1String("killall ") + dPath.fileName() + QLatin1String(" 2> /dev/null"); #endif killall.start(cmd); if (!killall.waitForStarted()) { killAllFailed = true; } else { killall.closeWriteChannel(); killall.waitForFinished(); } if (killAllFailed) { this->setError(false,ZConfLib::tr("zeroconf failed to kill other daemons with '%1'").arg(cmd)); if (DEBUG_ZEROCONF) qDebug() << name() << " had an error trying to kill other daemons with " << cmd; } if (QProcess::startDetached(daemonPath)) { QThread::yieldCurrentThread(); // sleep a bit? if (DEBUG_ZEROCONF) qDebug() << name() << " started " << daemonPath; return true; } else { this->setError(true, ZConfLib::tr("%1 failed starting embedded daemon at %2") .arg(name()).arg(daemonPath)); } } return false; } void refDeallocate(DNSServiceRef sdRef) { embeddedLib::DNSServiceRefDeallocate(sdRef); } void browserDeallocate(BrowserRef *bRef) { if (bRef){ embeddedLib::DNSServiceRefDeallocate(*reinterpret_cast<DNSServiceRef*>(bRef)); *bRef = 0; } } void stopConnection(ConnectionRef cRef) { int sock = refSockFD(cRef); if (sock>0) shutdown(sock, SHUT_RDWR); } void destroyConnection(ConnectionRef *sdRef) { if (sdRef) { embeddedLib::DNSServiceRefDeallocate(*reinterpret_cast<DNSServiceRef*>(sdRef)); *sdRef = 0; } } DNSServiceErrorType resolve(ConnectionRef cRef, DNSServiceRef *sdRef, uint32_t interfaceIndex, ZK_IP_Protocol /* protocol */, const char *name, const char *regtype, const char *domain, ServiceGatherer *gatherer) { *sdRef = reinterpret_cast<DNSServiceRef>(cRef); return embeddedLib::DNSServiceResolve(sdRef, kDNSServiceFlagsShareConnection // | kDNSServiceFlagsSuppressUnusable | kDNSServiceFlagsTimeout, interfaceIndex, name, regtype, domain, &cServiceResolveReply, gatherer); } DNSServiceErrorType queryRecord(ConnectionRef cRef, DNSServiceRef *sdRef, uint32_t interfaceIndex, const char *fullname, ServiceGatherer *gatherer) { *sdRef = reinterpret_cast<DNSServiceRef>(cRef); return embeddedLib::DNSServiceQueryRecord(sdRef, kDNSServiceFlagsShareConnection // | kDNSServiceFlagsSuppressUnusable | kDNSServiceFlagsTimeout, interfaceIndex, fullname, kDNSServiceType_TXT, kDNSServiceClass_IN, &cTxtRecordReply , gatherer); } DNSServiceErrorType getAddrInfo(ConnectionRef cRef, DNSServiceRef *sdRef, uint32_t interfaceIndex, DNSServiceProtocol protocol, const char *hostname, ServiceGatherer *gatherer) { *sdRef = reinterpret_cast<DNSServiceRef>(cRef); return embeddedLib::DNSServiceGetAddrInfo(sdRef, kDNSServiceFlagsShareConnection // | kDNSServiceFlagsSuppressUnusable | kDNSServiceFlagsTimeout, interfaceIndex, protocol, hostname, &cAddrReply, gatherer); } DNSServiceErrorType reconfirmRecord(ConnectionRef /*cRef*/, uint32_t /*interfaceIndex*/, const char * /*name*/, const char * /*type*/, const char * /*domain*/, const char * /*fullname*/) { // reload and force update with in the callback with // embeddedLib::DNSServiceReconfirmRecord(flags, interfaceIndex, fullname, rrtype, // rrclass, rdlen, rdata); return kDNSServiceErr_Unsupported; } DNSServiceErrorType browse(ConnectionRef cRef, BrowserRef *bRef, uint32_t interfaceIndex, const char *regtype, const char *domain, /* may be NULL */ ServiceBrowserPrivate *browser) { DNSServiceRef *sdRef = reinterpret_cast<DNSServiceRef *>(bRef); *sdRef = reinterpret_cast<DNSServiceRef>(cRef); return embeddedLib::DNSServiceBrowse(sdRef, kDNSServiceFlagsShareConnection /* | kDNSServiceFlagsSuppressUnusable */, interfaceIndex, regtype, domain, &cBrowseReply, browser); } DNSServiceErrorType getProperty(const char *property, void *result, uint32_t *size) { return embeddedLib::DNSServiceGetProperty(property, result, size); } RunLoopStatus processOneEventBlock(ConnectionRef cRef) { if (embeddedLib::DNSServiceProcessResult(reinterpret_cast<DNSServiceRef>(cRef)) != kDNSServiceErr_NoError) return ProcessedError; return ProcessedOk; } DNSServiceErrorType createConnection(MainConnection *, ConnectionRef *sdRef) { return embeddedLib::DNSServiceCreateConnection(reinterpret_cast<DNSServiceRef*>(sdRef)); } int refSockFD(ConnectionRef sdRef) { return embeddedLib::DNSServiceRefSockFD(reinterpret_cast<DNSServiceRef>(sdRef)); } }; ZConfLib::Ptr ZConfLib::createEmbeddedLib(const QString &daemonPath, const ZConfLib::Ptr &fallback) { return ZConfLib::Ptr(new EmbeddedZConfLib(daemonPath, fallback)); } } // namespace Internal } // namespace ZeroConf #else // no embedded lib namespace ZeroConf { namespace Internal { ZConfLib::Ptr ZConfLib::createEmbeddedLib(const QString &, const ZConfLib::Ptr &fallback) { return fallback; } } // namespace Internal } // namespace ZeroConf #endif <commit_msg>zeroconf: fixing typo<commit_after>/************************************************************************** ** ** This file is part of Qt Creator ** ** Copyright (c) 2012 Nokia Corporation and/or its subsidiary(-ies). ** ** Contact: Nokia Corporation ([email protected]) ** ** ** 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 [email protected]. ** **************************************************************************/ #include "syssocket.h" // this should be the first header included #include "servicebrowser_p.h" #include <QCoreApplication> #include <QDebug> #include <QFileInfo> #include <QString> #include <QStringList> #include <QProcess> #ifdef Q_OS_LINUX #define EMBEDDED_LIB #endif #ifdef Q_OS_WIN32 #define EMBEDDED_LIB #endif #ifdef EMBEDDED_LIB #define PID_FILE "/tmp/mdnsd.pid" #define MDNS_UDS_SERVERPATH "/tmp/mdnsd" #include "embed/dnssd_ipc.c" #include "embed/dnssd_clientlib.c" #include "embed/dnssd_clientstub.c" #ifdef Q_OS_WIN #include "embed/DebugServices.c" #endif namespace ZeroConf { namespace Internal { // represents a zero conf library exposing the dns-sd interface class EmbeddedZConfLib : public ZConfLib { public: QString daemonPath; EmbeddedZConfLib(const QString &daemonPath, ZConfLib::Ptr fallBack) : ZConfLib(fallBack), daemonPath(daemonPath) { if (daemonPath.isEmpty()) m_maxErrors = 0; if (!daemonPath.isEmpty() && daemonPath.at(0) != '/' && daemonPath.at(0) != '.') this->daemonPath = QCoreApplication::applicationDirPath() + QChar('/') + daemonPath; } ~EmbeddedZConfLib() { } QString name() { return QString::fromLatin1("EmbeddedZeroConfLib@%1").arg(size_t(this), 0, 16); } bool tryStartDaemon() { if (!daemonPath.isEmpty()) { QFileInfo dPath(daemonPath); QProcess killall; bool killAllFailed = false; #ifdef Q_OS_WIN QString cmd = QLatin1String("taskill /im ") + dPath.fileName() + QLatin1String(" /f /t"); #else QString cmd = QLatin1String("killall ") + dPath.fileName() + QLatin1String(" 2> /dev/null"); #endif killall.start(cmd); if (!killall.waitForStarted()) { killAllFailed = true; } else { killall.closeWriteChannel(); killall.waitForFinished(); } if (killAllFailed) { this->setError(false,ZConfLib::tr("zeroconf failed to kill other daemons with '%1'").arg(cmd)); if (DEBUG_ZEROCONF) qDebug() << name() << " had an error trying to kill other daemons with " << cmd; } if (QProcess::startDetached(daemonPath)) { QThread::yieldCurrentThread(); // sleep a bit? if (DEBUG_ZEROCONF) qDebug() << name() << " started " << daemonPath; return true; } else { this->setError(true, ZConfLib::tr("%1 failed starting embedded daemon at %2") .arg(name()).arg(daemonPath)); } } return false; } void refDeallocate(DNSServiceRef sdRef) { embeddedLib::DNSServiceRefDeallocate(sdRef); } void browserDeallocate(BrowserRef *bRef) { if (bRef){ embeddedLib::DNSServiceRefDeallocate(*reinterpret_cast<DNSServiceRef*>(bRef)); *bRef = 0; } } void stopConnection(ConnectionRef cRef) { int sock = refSockFD(cRef); if (sock>0) shutdown(sock, SHUT_RDWR); } void destroyConnection(ConnectionRef *sdRef) { if (sdRef) { embeddedLib::DNSServiceRefDeallocate(*reinterpret_cast<DNSServiceRef*>(sdRef)); *sdRef = 0; } } DNSServiceErrorType resolve(ConnectionRef cRef, DNSServiceRef *sdRef, uint32_t interfaceIndex, ZK_IP_Protocol /* protocol */, const char *name, const char *regtype, const char *domain, ServiceGatherer *gatherer) { *sdRef = reinterpret_cast<DNSServiceRef>(cRef); return embeddedLib::DNSServiceResolve(sdRef, kDNSServiceFlagsShareConnection // | kDNSServiceFlagsSuppressUnusable | kDNSServiceFlagsTimeout, interfaceIndex, name, regtype, domain, &cServiceResolveReply, gatherer); } DNSServiceErrorType queryRecord(ConnectionRef cRef, DNSServiceRef *sdRef, uint32_t interfaceIndex, const char *fullname, ServiceGatherer *gatherer) { *sdRef = reinterpret_cast<DNSServiceRef>(cRef); return embeddedLib::DNSServiceQueryRecord(sdRef, kDNSServiceFlagsShareConnection // | kDNSServiceFlagsSuppressUnusable | kDNSServiceFlagsTimeout, interfaceIndex, fullname, kDNSServiceType_TXT, kDNSServiceClass_IN, &cTxtRecordReply , gatherer); } DNSServiceErrorType getAddrInfo(ConnectionRef cRef, DNSServiceRef *sdRef, uint32_t interfaceIndex, DNSServiceProtocol protocol, const char *hostname, ServiceGatherer *gatherer) { *sdRef = reinterpret_cast<DNSServiceRef>(cRef); return embeddedLib::DNSServiceGetAddrInfo(sdRef, kDNSServiceFlagsShareConnection // | kDNSServiceFlagsSuppressUnusable | kDNSServiceFlagsTimeout, interfaceIndex, protocol, hostname, &cAddrReply, gatherer); } DNSServiceErrorType reconfirmRecord(ConnectionRef /*cRef*/, uint32_t /*interfaceIndex*/, const char * /*name*/, const char * /*type*/, const char * /*domain*/, const char * /*fullname*/) { // reload and force update with in the callback with // embeddedLib::DNSServiceReconfirmRecord(flags, interfaceIndex, fullname, rrtype, // rrclass, rdlen, rdata); return kDNSServiceErr_Unsupported; } DNSServiceErrorType browse(ConnectionRef cRef, BrowserRef *bRef, uint32_t interfaceIndex, const char *regtype, const char *domain, /* may be NULL */ ServiceBrowserPrivate *browser) { DNSServiceRef *sdRef = reinterpret_cast<DNSServiceRef *>(bRef); *sdRef = reinterpret_cast<DNSServiceRef>(cRef); return embeddedLib::DNSServiceBrowse(sdRef, kDNSServiceFlagsShareConnection /* | kDNSServiceFlagsSuppressUnusable */, interfaceIndex, regtype, domain, &cBrowseReply, browser); } DNSServiceErrorType getProperty(const char *property, void *result, uint32_t *size) { return embeddedLib::DNSServiceGetProperty(property, result, size); } RunLoopStatus processOneEventBlock(ConnectionRef cRef) { if (embeddedLib::DNSServiceProcessResult(reinterpret_cast<DNSServiceRef>(cRef)) != kDNSServiceErr_NoError) return ProcessedError; return ProcessedOk; } DNSServiceErrorType createConnection(MainConnection *, ConnectionRef *sdRef) { return embeddedLib::DNSServiceCreateConnection(reinterpret_cast<DNSServiceRef*>(sdRef)); } int refSockFD(ConnectionRef sdRef) { return embeddedLib::DNSServiceRefSockFD(reinterpret_cast<DNSServiceRef>(sdRef)); } }; ZConfLib::Ptr ZConfLib::createEmbeddedLib(const QString &daemonPath, const ZConfLib::Ptr &fallback) { return ZConfLib::Ptr(new EmbeddedZConfLib(daemonPath, fallback)); } } // namespace Internal } // namespace ZeroConf #else // no embedded lib namespace ZeroConf { namespace Internal { ZConfLib::Ptr ZConfLib::createEmbeddedLib(const QString &, const ZConfLib::Ptr &fallback) { return fallback; } } // namespace Internal } // namespace ZeroConf #endif <|endoftext|>
<commit_before>/* Copyright 2013 Larry Gritz and the other authors and contributors. 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 software's owners 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. (This is the Modified BSD License) */ #include <OpenEXR/half.h> #include <cmath> #include <iostream> #include <stdexcept> #include "OpenImageIO/imagebuf.h" #include "OpenImageIO/imagebufalgo.h" #include "OpenImageIO/imagebufalgo_util.h" #include "OpenImageIO/dassert.h" #include "OpenImageIO/thread.h" OIIO_NAMESPACE_BEGIN // Helper for flatten: identify channels in the spec that are important to // deciphering deep images. Return true if appropriate alphas were found. static bool find_deep_channels (const ImageSpec &spec, int &alpha_channel, int &RA_channel, int &GA_channel, int &BA_channel, int &R_channel, int &G_channel, int &B_channel, int &Z_channel, int &Zback_channel) { static const char *names[] = { "A", "RA", "GA", "BA", "R", "G", "B", "Z", "Zback", NULL }; int *chans[] = { &alpha_channel, &RA_channel, &GA_channel, &BA_channel, &R_channel, &G_channel, &B_channel, &Z_channel, &Zback_channel }; for (int i = 0; names[i]; ++i) *chans[i] = -1; for (int c = 0, e = int(spec.channelnames.size()); c < e; ++c) { for (int i = 0; names[i]; ++i) { if (spec.channelnames[c] == names[i]) { *chans[i] = c; break; } } } if (Zback_channel < 0) Zback_channel = Z_channel; return (alpha_channel >= 0 || (RA_channel >= 0 && GA_channel >= 0 && BA_channel >= 0)); } // FIXME -- NOT CORRECT! This code assumes sorted, non-overlapping samples. // That is not a valid assumption in general. We will come back to fix this. template<class DSTTYPE> static bool flatten_ (ImageBuf &dst, const ImageBuf &src, ROI roi, int nthreads) { if (nthreads != 1 && roi.npixels() >= 1000) { // Possible multiple thread case -- recurse via parallel_image ImageBufAlgo::parallel_image ( OIIO::bind(flatten_<DSTTYPE>, OIIO::ref(dst), OIIO::cref(src), _1 /*roi*/, 1 /*nthreads*/), roi, nthreads); return true; } const ImageSpec &srcspec (src.spec()); int nc = srcspec.nchannels; int alpha_channel, RA_channel, GA_channel, BA_channel; int R_channel, G_channel, B_channel; int Z_channel, Zback_channel; if (! find_deep_channels (srcspec, alpha_channel, RA_channel, GA_channel, BA_channel, R_channel, G_channel, B_channel, Z_channel, Zback_channel)) { dst.error ("No alpha channel could be identified"); return false; } ASSERT (alpha_channel >= 0 || (RA_channel >= 0 && GA_channel >= 0 && BA_channel >= 0)); float *val = ALLOCA (float, nc); float &RAval (RA_channel >= 0 ? val[RA_channel] : val[alpha_channel]); float &GAval (GA_channel >= 0 ? val[GA_channel] : val[alpha_channel]); float &BAval (BA_channel >= 0 ? val[BA_channel] : val[alpha_channel]); for (ImageBuf::Iterator<DSTTYPE> r (dst, roi); !r.done(); ++r) { int x = r.x(), y = r.y(), z = r.z(); int samps = src.deep_samples (x, y, z); // Clear accumulated values for this pixel (0 for colors, big for Z) memset (val, 0, nc*sizeof(float)); if (Z_channel >= 0 && samps == 0) val[Z_channel] = 1.0e30; if (Zback_channel >= 0 && samps == 0) val[Zback_channel] = 1.0e30; for (int s = 0; s < samps; ++s) { float RA = RAval, GA = GAval, BA = BAval; // make copies float alpha = (RA + GA + BA) / 3.0f; if (alpha >= 1.0f) break; for (int c = 0; c < nc; ++c) { float v = src.deep_value (x, y, z, c, s); if (c == Z_channel || c == Zback_channel) val[c] *= alpha; // because Z are not premultiplied float a; if (c == R_channel) a = RA; else if (c == G_channel) a = GA; else if (c == B_channel) a = BA; else a = alpha; val[c] += (1.0f - a) * v; } } for (int c = roi.chbegin; c < roi.chend; ++c) r[c] = val[c]; } return true; } bool ImageBufAlgo::flatten (ImageBuf &dst, const ImageBuf &src, ROI roi, int nthreads) { if (! src.deep()) { // For some reason, we were asked to flatten an already-flat image. // So just copy it. return dst.copy (src); } // Construct an ideal spec for dst, which is like src but not deep. ImageSpec force_spec = src.spec(); force_spec.deep = false; force_spec.channelformats.clear(); if (! IBAprep (roi, &dst, &src, NULL, &force_spec, IBAprep_SUPPORT_DEEP)) return false; if (dst.spec().deep) { dst.error ("Cannot flatten to a deep image"); return false; } const ImageSpec &srcspec (src.spec()); int alpha_channel, RA_channel, GA_channel, BA_channel; int R_channel, G_channel, B_channel, Z_channel, Zback_channel; if (! find_deep_channels (srcspec, alpha_channel, RA_channel, GA_channel, BA_channel, R_channel, G_channel, B_channel, Z_channel, Zback_channel)) { dst.error ("No alpha channel could be identified"); return false; } bool ok; OIIO_DISPATCH_TYPES (ok, "flatten", flatten_, dst.spec().format, dst, src, roi, nthreads); return ok; } bool ImageBufAlgo::deepen (ImageBuf &dst, const ImageBuf &src, float zvalue, ROI roi, int nthreads) { if (src.deep()) { // For some reason, we were asked to deepen an already-deep image. // So just copy it. return dst.copy (src); // FIXME: once paste works for deep files, this should really be // return paste (dst, roi.xbegin, roi.ybegin, roi.zbegin, roi.chbegin, // src, roi, nthreads); } // Construct an ideal spec for dst, which is like src but deep. const ImageSpec &srcspec (src.spec()); int nc = srcspec.nchannels; int zback_channel = -1; ImageSpec force_spec = srcspec; force_spec.deep = true; force_spec.set_format (TypeDesc::FLOAT); force_spec.channelformats.clear(); for (int c = 0; c < nc; ++c) { if (force_spec.channelnames[c] == "Z") force_spec.z_channel = c; else if (force_spec.channelnames[c] == "Zback") zback_channel = c; } bool add_z_channel = (force_spec.z_channel < 0); if (add_z_channel) { // No z channel? Make one. force_spec.z_channel = force_spec.nchannels++; force_spec.channelnames.push_back ("Z"); } if (! IBAprep (roi, &dst, &src, NULL, &force_spec, IBAprep_SUPPORT_DEEP)) return false; if (! dst.deep()) { dst.error ("Cannot deepen to a flat image"); return false; } float *pixel = OIIO_ALLOCA (float, nc); // First, figure out which pixels get a sample and which do not for (int z = roi.zbegin; z < roi.zend; ++z) for (int y = roi.ybegin; y < roi.yend; ++y) for (int x = roi.xbegin; x < roi.xend; ++x) { bool has_sample = false; src.getpixel (x, y, z, pixel); for (int c = 0; c < nc; ++c) if (c != force_spec.z_channel && c != zback_channel && pixel[c] != 0.0f) { has_sample = true; break; } if (! has_sample && ! add_z_channel) for (int c = 0; c < nc; ++c) if ((c == force_spec.z_channel || c == zback_channel) && (pixel[c] != 0.0f && pixel[c] < 1e30)) { has_sample = true; break; } if (has_sample) dst.set_deep_samples (x, y, z, 1); } dst.deep_alloc (); // Now actually set the values for (int z = roi.zbegin; z < roi.zend; ++z) for (int y = roi.ybegin; y < roi.yend; ++y) for (int x = roi.xbegin; x < roi.xend; ++x) { if (dst.deep_samples (x, y, z) == 0) continue; for (int c = 0; c < nc; ++c) dst.set_deep_value (x, y, z, c, 0 /*sample*/, src.getchannel (x, y, z, c)); if (add_z_channel) dst.set_deep_value (x, y, z, nc, 0, zvalue); } bool ok = true; // FIXME -- the above doesn't split into threads. Someday, it should // be refactored like this: // OIIO_DISPATCH_COMMON_TYPES2 (ok, "deepen", deepen_, // dst.spec().format, srcspec.format, // dst, src, add_z_channel, z, roi, nthreads); return ok; } OIIO_NAMESPACE_END <commit_msg>Deep OpenEXR: recognize newer AR/AG/AB channel name convention.<commit_after>/* Copyright 2013 Larry Gritz and the other authors and contributors. 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 software's owners 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. (This is the Modified BSD License) */ #include <OpenEXR/half.h> #include <cmath> #include <iostream> #include <stdexcept> #include "OpenImageIO/imagebuf.h" #include "OpenImageIO/imagebufalgo.h" #include "OpenImageIO/imagebufalgo_util.h" #include "OpenImageIO/dassert.h" #include "OpenImageIO/thread.h" OIIO_NAMESPACE_BEGIN // Helper for flatten: identify channels in the spec that are important to // deciphering deep images. Return true if appropriate alphas were found. static bool find_deep_channels (const ImageSpec &spec, int &alpha_channel, int &AR_channel, int &AG_channel, int &AB_channel, int &R_channel, int &G_channel, int &B_channel, int &Z_channel, int &Zback_channel) { static const char *names[] = { "A", "RA", "GA", "BA", // old OpenEXR recommendation "AR", "AG", "AB", // new OpenEXR recommendation "R", "G", "B", "Z", "Zback", NULL }; int *chans[] = { &alpha_channel, &AR_channel, &AG_channel, &AB_channel, &AR_channel, &AG_channel, &AB_channel, &R_channel, &G_channel, &B_channel, &Z_channel, &Zback_channel }; for (int i = 0; names[i]; ++i) *chans[i] = -1; for (int c = 0, e = int(spec.channelnames.size()); c < e; ++c) { for (int i = 0; names[i]; ++i) { if (spec.channelnames[c] == names[i]) { *chans[i] = c; break; } } } if (Zback_channel < 0) Zback_channel = Z_channel; return (alpha_channel >= 0 || (AR_channel >= 0 && AG_channel >= 0 && AB_channel >= 0)); } // FIXME -- NOT CORRECT! This code assumes sorted, non-overlapping samples. // That is not a valid assumption in general. We will come back to fix this. template<class DSTTYPE> static bool flatten_ (ImageBuf &dst, const ImageBuf &src, ROI roi, int nthreads) { if (nthreads != 1 && roi.npixels() >= 1000) { // Possible multiple thread case -- recurse via parallel_image ImageBufAlgo::parallel_image ( OIIO::bind(flatten_<DSTTYPE>, OIIO::ref(dst), OIIO::cref(src), _1 /*roi*/, 1 /*nthreads*/), roi, nthreads); return true; } const ImageSpec &srcspec (src.spec()); int nc = srcspec.nchannels; int alpha_channel, AR_channel, AG_channel, AB_channel; int R_channel, G_channel, B_channel; int Z_channel, Zback_channel; if (! find_deep_channels (srcspec, alpha_channel, AR_channel, AG_channel, AB_channel, R_channel, G_channel, B_channel, Z_channel, Zback_channel)) { dst.error ("No alpha channel could be identified"); return false; } ASSERT (alpha_channel >= 0 || (AR_channel >= 0 && AG_channel >= 0 && AB_channel >= 0)); float *val = ALLOCA (float, nc); float &ARval (AR_channel >= 0 ? val[AR_channel] : val[alpha_channel]); float &AGval (AG_channel >= 0 ? val[AG_channel] : val[alpha_channel]); float &ABval (AB_channel >= 0 ? val[AB_channel] : val[alpha_channel]); for (ImageBuf::Iterator<DSTTYPE> r (dst, roi); !r.done(); ++r) { int x = r.x(), y = r.y(), z = r.z(); int samps = src.deep_samples (x, y, z); // Clear accumulated values for this pixel (0 for colors, big for Z) memset (val, 0, nc*sizeof(float)); if (Z_channel >= 0 && samps == 0) val[Z_channel] = 1.0e30; if (Zback_channel >= 0 && samps == 0) val[Zback_channel] = 1.0e30; for (int s = 0; s < samps; ++s) { float AR = ARval, AG = AGval, AB = ABval; // make copies float alpha = (AR + AG + AB) / 3.0f; if (alpha >= 1.0f) break; for (int c = 0; c < nc; ++c) { float v = src.deep_value (x, y, z, c, s); if (c == Z_channel || c == Zback_channel) val[c] *= alpha; // because Z are not premultiplied float a; if (c == R_channel) a = AR; else if (c == G_channel) a = AG; else if (c == B_channel) a = AB; else a = alpha; val[c] += (1.0f - a) * v; } } for (int c = roi.chbegin; c < roi.chend; ++c) r[c] = val[c]; } return true; } bool ImageBufAlgo::flatten (ImageBuf &dst, const ImageBuf &src, ROI roi, int nthreads) { if (! src.deep()) { // For some reason, we were asked to flatten an already-flat image. // So just copy it. return dst.copy (src); } // Construct an ideal spec for dst, which is like src but not deep. ImageSpec force_spec = src.spec(); force_spec.deep = false; force_spec.channelformats.clear(); if (! IBAprep (roi, &dst, &src, NULL, &force_spec, IBAprep_SUPPORT_DEEP)) return false; if (dst.spec().deep) { dst.error ("Cannot flatten to a deep image"); return false; } const ImageSpec &srcspec (src.spec()); int alpha_channel, AR_channel, AG_channel, AB_channel; int R_channel, G_channel, B_channel, Z_channel, Zback_channel; if (! find_deep_channels (srcspec, alpha_channel, AR_channel, AG_channel, AB_channel, R_channel, G_channel, B_channel, Z_channel, Zback_channel)) { dst.error ("No alpha channel could be identified"); return false; } bool ok; OIIO_DISPATCH_TYPES (ok, "flatten", flatten_, dst.spec().format, dst, src, roi, nthreads); return ok; } bool ImageBufAlgo::deepen (ImageBuf &dst, const ImageBuf &src, float zvalue, ROI roi, int nthreads) { if (src.deep()) { // For some reason, we were asked to deepen an already-deep image. // So just copy it. return dst.copy (src); // FIXME: once paste works for deep files, this should really be // return paste (dst, roi.xbegin, roi.ybegin, roi.zbegin, roi.chbegin, // src, roi, nthreads); } // Construct an ideal spec for dst, which is like src but deep. const ImageSpec &srcspec (src.spec()); int nc = srcspec.nchannels; int zback_channel = -1; ImageSpec force_spec = srcspec; force_spec.deep = true; force_spec.set_format (TypeDesc::FLOAT); force_spec.channelformats.clear(); for (int c = 0; c < nc; ++c) { if (force_spec.channelnames[c] == "Z") force_spec.z_channel = c; else if (force_spec.channelnames[c] == "Zback") zback_channel = c; } bool add_z_channel = (force_spec.z_channel < 0); if (add_z_channel) { // No z channel? Make one. force_spec.z_channel = force_spec.nchannels++; force_spec.channelnames.push_back ("Z"); } if (! IBAprep (roi, &dst, &src, NULL, &force_spec, IBAprep_SUPPORT_DEEP)) return false; if (! dst.deep()) { dst.error ("Cannot deepen to a flat image"); return false; } float *pixel = OIIO_ALLOCA (float, nc); // First, figure out which pixels get a sample and which do not for (int z = roi.zbegin; z < roi.zend; ++z) for (int y = roi.ybegin; y < roi.yend; ++y) for (int x = roi.xbegin; x < roi.xend; ++x) { bool has_sample = false; src.getpixel (x, y, z, pixel); for (int c = 0; c < nc; ++c) if (c != force_spec.z_channel && c != zback_channel && pixel[c] != 0.0f) { has_sample = true; break; } if (! has_sample && ! add_z_channel) for (int c = 0; c < nc; ++c) if ((c == force_spec.z_channel || c == zback_channel) && (pixel[c] != 0.0f && pixel[c] < 1e30)) { has_sample = true; break; } if (has_sample) dst.set_deep_samples (x, y, z, 1); } dst.deep_alloc (); // Now actually set the values for (int z = roi.zbegin; z < roi.zend; ++z) for (int y = roi.ybegin; y < roi.yend; ++y) for (int x = roi.xbegin; x < roi.xend; ++x) { if (dst.deep_samples (x, y, z) == 0) continue; for (int c = 0; c < nc; ++c) dst.set_deep_value (x, y, z, c, 0 /*sample*/, src.getchannel (x, y, z, c)); if (add_z_channel) dst.set_deep_value (x, y, z, nc, 0, zvalue); } bool ok = true; // FIXME -- the above doesn't split into threads. Someday, it should // be refactored like this: // OIIO_DISPATCH_COMMON_TYPES2 (ok, "deepen", deepen_, // dst.spec().format, srcspec.format, // dst, src, add_z_channel, z, roi, nthreads); return ok; } OIIO_NAMESPACE_END <|endoftext|>
<commit_before>/* Copyright (c) 2013 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Leonardo de Moura */ #include <pthread.h> #include <memory.h> #include <iostream> #include "util/thread.h" #include "util/exception.h" #if !defined(LEAN_USE_SPLIT_STACK) #if defined(LEAN_WINDOWS) // no extra included needed so far #elif defined(__APPLE__) #include <sys/resource.h> // NOLINT #else #include <sys/time.h> // NOLINT #include <sys/resource.h> // NOLINT #endif #define LEAN_MIN_STACK_SPACE 128*1024 // 128 Kb namespace lean { void throw_get_stack_size_failed() { throw exception("failed to retrieve thread stack size"); } #if defined(LEAN_WINDOWS) size_t get_stack_size(int ) { return LEAN_WIN_STACK_SIZE; } #elif defined (__APPLE__) size_t get_stack_size(int main) { if (main) { // Retrieve stack size of the main thread. struct rlimit curr; if (getrlimit(RLIMIT_STACK, &curr) != 0) { throw_get_stack_size_failed(); } return curr.rlim_max; } else { #if defined(LEAN_MULTI_THREAD) // This branch retrieves the default thread size for pthread threads. // This is *not* the stack size of the main thread. pthread_attr_t attr; memset (&attr, 0, sizeof(attr)); pthread_attr_init(&attr); size_t result; if (pthread_attr_getstacksize(&attr, &result) != 0) { throw_get_stack_size_failed(); } return result; #else return 0; #endif } } #else size_t get_stack_size(int main) { if (main) { // Retrieve stack size of the main thread. struct rlimit curr; if (getrlimit(RLIMIT_STACK, &curr) != 0) { throw_get_stack_size_failed(); } return curr.rlim_cur; } else { #if defined(LEAN_MULTI_THREAD) pthread_attr_t attr; memset (&attr, 0, sizeof(attr)); if (pthread_getattr_np(pthread_self(), &attr) != 0) { throw_get_stack_size_failed(); } void * ptr; size_t result; if (pthread_attr_getstack (&attr, &ptr, &result) != 0) { throw_get_stack_size_failed(); } if (pthread_attr_destroy(&attr) != 0) { throw_get_stack_size_failed(); } return result; #else return 0; #endif } } #endif static bool g_stack_info_init = false; MK_THREAD_LOCAL_GET(size_t, get_g_stack_size, 0); MK_THREAD_LOCAL_GET(size_t, get_g_stack_base, 0); void save_stack_info(bool main) { g_stack_info_init = true; get_g_stack_size() = get_stack_size(main); char x; get_g_stack_base() = reinterpret_cast<size_t>(&x); } size_t get_used_stack_size() { char y; size_t curr_stack = reinterpret_cast<size_t>(&y); return get_g_stack_base() - curr_stack; } size_t get_available_stack_size() { size_t sz = get_used_stack_size(); if (sz > get_g_stack_size()) return 0; else return get_g_stack_size() - sz; } void check_stack(char const * component_name) { if (g_stack_info_init && get_used_stack_size() + LEAN_MIN_STACK_SPACE > get_g_stack_size()) throw stack_space_exception(component_name); } } #endif <commit_msg>fix(util/stackinfo): on OSX Boost does not seem to be based on pthread library<commit_after>/* Copyright (c) 2013 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Leonardo de Moura */ #include <pthread.h> #include <memory.h> #include <iostream> #include "util/thread.h" #include "util/exception.h" #if !defined(LEAN_USE_SPLIT_STACK) #if defined(LEAN_WINDOWS) // no extra included needed so far #elif defined(__APPLE__) #include <sys/resource.h> // NOLINT #else #include <sys/time.h> // NOLINT #include <sys/resource.h> // NOLINT #endif #define LEAN_MIN_STACK_SPACE 128*1024 // 128 Kb namespace lean { void throw_get_stack_size_failed() { throw exception("failed to retrieve thread stack size"); } #if defined(LEAN_WINDOWS) size_t get_stack_size(int ) { return LEAN_WIN_STACK_SIZE; } #elif defined (__APPLE__) size_t get_stack_size(int main) { if (main) { // Retrieve stack size of the main thread. struct rlimit curr; if (getrlimit(RLIMIT_STACK, &curr) != 0) { throw_get_stack_size_failed(); } return curr.rlim_max; } else { #if defined(LEAN_MULTI_THREAD) { #if defined(LEAN_USE_BOOST) // Boost does seems to be based on pthread on OSX return get_thread_attributes().get_stack_size(); #else // This branch retrieves the default thread size for pthread threads. // This is *not* the stack size of the main thread. pthread_attr_t attr; memset (&attr, 0, sizeof(attr)); pthread_attr_init(&attr); size_t result; if (pthread_attr_getstacksize(&attr, &result) != 0) { throw_get_stack_size_failed(); } return result; #endif } #else return 0; #endif } } #else size_t get_stack_size(int main) { if (main) { // Retrieve stack size of the main thread. struct rlimit curr; if (getrlimit(RLIMIT_STACK, &curr) != 0) { throw_get_stack_size_failed(); } return curr.rlim_cur; } else { #if defined(LEAN_MULTI_THREAD) pthread_attr_t attr; memset (&attr, 0, sizeof(attr)); if (pthread_getattr_np(pthread_self(), &attr) != 0) { throw_get_stack_size_failed(); } void * ptr; size_t result; if (pthread_attr_getstack (&attr, &ptr, &result) != 0) { throw_get_stack_size_failed(); } if (pthread_attr_destroy(&attr) != 0) { throw_get_stack_size_failed(); } return result; #else return 0; #endif } } #endif static bool g_stack_info_init = false; MK_THREAD_LOCAL_GET(size_t, get_g_stack_size, 0); MK_THREAD_LOCAL_GET(size_t, get_g_stack_base, 0); void save_stack_info(bool main) { g_stack_info_init = true; get_g_stack_size() = get_stack_size(main); char x; get_g_stack_base() = reinterpret_cast<size_t>(&x); } size_t get_used_stack_size() { char y; size_t curr_stack = reinterpret_cast<size_t>(&y); return get_g_stack_base() - curr_stack; } size_t get_available_stack_size() { size_t sz = get_used_stack_size(); if (sz > get_g_stack_size()) return 0; else return get_g_stack_size() - sz; } void check_stack(char const * component_name) { if (g_stack_info_init && get_used_stack_size() + LEAN_MIN_STACK_SPACE > get_g_stack_size()) throw stack_space_exception(component_name); } } #endif <|endoftext|>
<commit_before>/* yqlcpp is a lightweight C++ API for performing Yahoo Query Language queries. At this time it is intended to be a simple interface with minimal error checking and no concern for thread safety. Built on top of and requires libcurl. Author: Kevin Hawkins <[email protected]> Copyright (c) 2014 Kevin Hawkins. All rights reserved. https://github.com/kevindhawkins/yqlcpp Licensed under the MIT license. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifndef __YQLCPP_H #define __YQLCPP_H #include <string> #include <fstream> #include <curl/curl.h> namespace yqlcpp { const std::string baseUrl = "http://query.yahooapis.com/v1/public/yql"; const std::string envCmd = "&env=store://datatables.org/alltableswithkeys"; class yqlquery { public: enum class yqlformat { JSON, XML }; yqlquery(const std::string& cmd, const yqlformat& format = yqlformat::JSON) : m_command(cmd) { m_curl = curl_easy_init(); m_format = formatToStr(format); } virtual ~yqlquery() { curl_easy_cleanup(m_curl); } //!< Execute the YQL query. bool execute() { if (m_curl) { std::string strRequest = "q=" + m_command + envCmd + "&format=" + m_format; curl_easy_setopt(m_curl, CURLOPT_URL, baseUrl.c_str()); curl_easy_setopt(m_curl, CURLOPT_POST, 1); curl_easy_setopt(m_curl, CURLOPT_POSTFIELDS, strRequest.c_str()); curl_easy_setopt(m_curl, CURLOPT_WRITEFUNCTION, responseWriter); CURLcode result = curl_easy_perform(m_curl); return (result == CURLE_OK); } return false; } //!< Get the YQL query response as a string. std::string getResponse() { return (*m_response); } //!< Write the YQL response to a file. void toFile(const std::string& filename) { if (m_response) { std::ofstream out(filename); out << (*m_response); out.close(); } } private: yqlquery() {} CURL* m_curl; //!< Our curl handle. std::string m_command; //!< Query command sent to YQL. std::string m_format; //!< Format of the response data. static std::string* m_response; //!< Response data, provided and managed by curl. /////////////////////////////////////////////////////////////////////// //!< Writes curl response data to the response string. static size_t responseWriter(char* contents, size_t size, size_t nmemb, std::string* data) { if (data) { size_t realSize = size * nmemb; data->append(contents, realSize); m_response = data; return realSize; } return 0; } /////////////////////////////////////////////////////////////////////// std::string formatToStr(const yqlformat& format) { switch(format) { case yqlformat::JSON: return "json"; case yqlformat::XML: return "xml"; default: return "json"; } } }; std::string* yqlquery::m_response = NULL; } #endif <commit_msg>Cleanup tabs<commit_after>/* yqlcpp is a lightweight C++ API for performing Yahoo Query Language queries. At this time it is intended to be a simple interface with minimal error checking and no concern for thread safety. Built on top of and requires libcurl. Author: Kevin Hawkins <[email protected]> Copyright (c) 2014 Kevin Hawkins. All rights reserved. https://github.com/kevindhawkins/yqlcpp Licensed under the MIT license. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifndef __YQLCPP_H #define __YQLCPP_H #include <string> #include <fstream> #include <curl/curl.h> namespace yqlcpp { const std::string baseUrl = "http://query.yahooapis.com/v1/public/yql"; const std::string envCmd = "&env=store://datatables.org/alltableswithkeys"; class yqlquery { public: enum class yqlformat { JSON, XML }; yqlquery(const std::string& cmd, const yqlformat& format = yqlformat::JSON) : m_command(cmd) { m_curl = curl_easy_init(); m_format = formatToStr(format); } virtual ~yqlquery() { curl_easy_cleanup(m_curl); } //!< Execute the YQL query. bool execute() { if (m_curl) { std::string strRequest = "q=" + m_command + envCmd + "&format=" + m_format; curl_easy_setopt(m_curl, CURLOPT_URL, baseUrl.c_str()); curl_easy_setopt(m_curl, CURLOPT_POST, 1); curl_easy_setopt(m_curl, CURLOPT_POSTFIELDS, strRequest.c_str()); curl_easy_setopt(m_curl, CURLOPT_WRITEFUNCTION, responseWriter); CURLcode result = curl_easy_perform(m_curl); return (result == CURLE_OK); } return false; } //!< Get the YQL query response as a string. std::string getResponse() { return (*m_response); } //!< Write the YQL response to a file. void toFile(const std::string& filename) { if (m_response) { std::ofstream out(filename); out << (*m_response); out.close(); } } private: yqlquery() {} CURL* m_curl; //!< Our curl handle. std::string m_command; //!< Query command sent to YQL. std::string m_format; //!< Format of the response data. static std::string* m_response; //!< Response data, provided and managed by curl. /////////////////////////////////////////////////////////////////////// //!< Writes curl response data to the response string. static size_t responseWriter(char* contents, size_t size, size_t nmemb, std::string* data) { if (data) { size_t realSize = size * nmemb; data->append(contents, realSize); m_response = data; return realSize; } return 0; } /////////////////////////////////////////////////////////////////////// std::string formatToStr(const yqlformat& format) { switch(format) { case yqlformat::JSON: return "json"; case yqlformat::XML: return "xml"; default: return "json"; } } }; std::string* yqlquery::m_response = NULL; } #endif <|endoftext|>
<commit_before>// $Id: directory.C,v 1.11 2000/06/27 09:08:52 oliver Exp $ #include <dirent.h> #include <stdio.h> #include <string.h> #include <sys/stat.h> #include <sys/types.h> #include <unistd.h> #include <iostream> #include <errno.h> #include <BALL/SYSTEM/directory.h> namespace BALL { Directory::Directory() { dir_ = 0; dirent_ = 0; char* buffer_; if ((buffer_ = ::getcwd(NULL, 64)) != NULL) directory_path_ = buffer_; else directory_path_ = ""; } Directory::Directory(const String& directory_path, bool set_current) { if (!set(directory_path, set_current)) directory_path_ = ""; } Directory::Directory(const Directory& directory) { set(directory); } Directory::~Directory() { if (dir_ != 0) ::closedir(dir_); } void Directory::swap(Directory& directory) { DIR* temp_dir = dir_; dir_ = directory.dir_; directory.dir_ = temp_dir; dirent* temp_dirent = dirent_; dirent_ = directory.dirent_; directory.dirent_ = temp_dirent; backup_path_.swap(directory.backup_path_); directory_path_.swap(directory.directory_path_); } bool Directory::getFirstEntry(String& entry) { synchronize_(); if (dir_ != 0) ::closedir(dir_); dir_ = ::opendir(directory_path_.data()); if (dir_ == 0) return desynchronize_(false); dirent_ = ::readdir(dir_); if (dirent_ == 0) { ::closedir(dir_); dir_ = 0; return desynchronize_(false); } else { entry = dirent_->d_name; return desynchronize_(true); } } bool Directory::getNextEntry(String& entry) { synchronize_(); if (dir_ == 0) dir_ = ::opendir(directory_path_.data()); if (dir_ == 0) return desynchronize_(false); dirent_ = ::readdir(dir_); if (dirent_ == 0) { ::closedir(dir_); dir_ = 0; return desynchronize_(false); } entry = dirent_->d_name; return desynchronize_(true); } Size Directory::countItems() { synchronize_(); Size size = 0; DIR* dir = ::opendir(directory_path_.data()); if (dir == 0) { desynchronize_(); return 0; } while(::readdir(dir) != 0) ++size; ::closedir(dir); desynchronize_(); return (size - 2); } // ignore current (.) and parent directory entry (..) Size Directory::countFiles() { synchronize_(); struct stat stats; Size size = 0; dirent* myDirent; DIR* dir = ::opendir(directory_path_.data()); if (dir == 0) { desynchronize_(); return 0; } while((myDirent = ::readdir(dir)) != 0) { if (lstat(myDirent->d_name, &stats) < 0) continue; if (S_ISDIR(stats.st_mode) == 0) ++size; } ::closedir(dir); desynchronize_(); return size; } Size Directory::countDirectories() { synchronize_(); struct stat stats; Size size = 0; dirent* myDirent; DIR *dir = ::opendir(directory_path_.data()); if (dir == 0) { desynchronize_(); return 0; } while((myDirent = ::readdir(dir)) != 0) { if (lstat(myDirent->d_name, &stats) < 0) continue; if (S_ISDIR(stats.st_mode) != 0) ++size; } ::closedir(dir); desynchronize_(); return (size - 2); } // ignore current (.) and parent directory entry (..) bool Directory::isCurrent() const { char* buffer_; if ((buffer_ = ::getcwd(NULL, 64)) == 0) return false; return (buffer_ == directory_path_); } bool Directory::has(const String& item) //const { synchronize_(); String entry; while (getNextEntry(entry)) { if (entry == item) return desynchronize_(true); } return desynchronize_(false); } bool Directory::find(const String& item, String& filepath) { if (has(item)) { filepath = directory_path_; return true; // no sync needed... } synchronize_(); struct stat stats; dirent* myDirent; Directory directory; String s; DIR* dir = ::opendir(FileSystem::CURRENT_DIRECTORY); if (dir == 0) return desynchronize_(false); while((myDirent = ::readdir(dir)) != 0) { if (lstat(myDirent->d_name, &stats) < 0) continue; if (S_ISDIR(stats.st_mode) != 0 && strcmp(myDirent->d_name, FileSystem::CURRENT_DIRECTORY) != 0 && strcmp(myDirent->d_name, FileSystem::PARENT_DIRECTORY ) != 0) { directory =Directory(myDirent->d_name); if (directory.find(item, s)) { filepath = s; ::closedir(dir); return desynchronize_(true); } } } ::closedir(dir); return desynchronize_(false); } bool Directory::set(const String& directory_path, bool set_current) { dir_ = 0; dirent_ = 0; backup_path_ = ""; char* buffer_; if (directory_path[0] == '/') //absolute path { directory_path_ = directory_path; FileSystem::canonizePath(directory_path_); return isValid(); } if ((buffer_ = ::getcwd(NULL, 64)) != NULL) { directory_path_ = buffer_; directory_path_ += FileSystem::PATH_SEPARATOR; directory_path_ += directory_path; FileSystem::canonizePath(directory_path_); if (directory_path_.hasSuffix(String(FileSystem::PATH_SEPARATOR))) { directory_path_.truncate(directory_path_.size() - 1); } } else { directory_path_ = ""; return false; } if (!isValid()) return false; if (set_current) return (::chdir(directory_path_.data()) == 0); return true; } bool Directory::remove() { synchronize_(); if (::chdir("..") != 0) return desynchronize_(false); bool result1 = (::rmdir(directory_path_.data()) == 0); bool result2; if (backup_path_ != "") { result2 = ::chdir(backup_path_.data()); backup_path_ = ""; } dir_ = 0; dirent_ = 0; directory_path_ = ""; return (result1 && result2); } bool Directory::renameTo(String new_path) { synchronize_(); FileSystem::canonizePath(new_path); if (::chdir("..") != 0) return desynchronize_(false); if (::rename(directory_path_.data(), new_path.data()) == 0) { directory_path_ = new_path; return desynchronize_(true); } return desynchronize_(false); } # ifdef BALL_NO_INLINE_FUNCTIONS # include <BALL/SYSTEM/directory.iC> # endif } // namespace BALL <commit_msg>fixed:redefinition of default argument Directory::Directory(const String& directory_path, bool set_current = false)<commit_after>// $Id: directory.C,v 1.12 2000/06/27 10:40:51 amoll Exp $ #include <dirent.h> #include <stdio.h> #include <string.h> #include <sys/stat.h> #include <sys/types.h> #include <unistd.h> #include <iostream> #include <errno.h> #include <BALL/SYSTEM/directory.h> namespace BALL { Directory::Directory() { dir_ = 0; dirent_ = 0; char* buffer_; if ((buffer_ = ::getcwd(NULL, 64)) != NULL) directory_path_ = buffer_; else directory_path_ = ""; } Directory::Directory(const String& directory_path, bool set_current) { if (!set(directory_path, set_current)) directory_path_ = ""; } Directory::Directory(const Directory& directory) { set(directory); } Directory::~Directory() { if (dir_ != 0) ::closedir(dir_); } void Directory::swap(Directory& directory) { DIR* temp_dir = dir_; dir_ = directory.dir_; directory.dir_ = temp_dir; dirent* temp_dirent = dirent_; dirent_ = directory.dirent_; directory.dirent_ = temp_dirent; backup_path_.swap(directory.backup_path_); directory_path_.swap(directory.directory_path_); } bool Directory::getFirstEntry(String& entry) { synchronize_(); if (dir_ != 0) ::closedir(dir_); dir_ = ::opendir(directory_path_.data()); if (dir_ == 0) return desynchronize_(false); dirent_ = ::readdir(dir_); if (dirent_ == 0) { ::closedir(dir_); dir_ = 0; return desynchronize_(false); } else { entry = dirent_->d_name; return desynchronize_(true); } } bool Directory::getNextEntry(String& entry) { synchronize_(); if (dir_ == 0) dir_ = ::opendir(directory_path_.data()); if (dir_ == 0) return desynchronize_(false); dirent_ = ::readdir(dir_); if (dirent_ == 0) { ::closedir(dir_); dir_ = 0; return desynchronize_(false); } entry = dirent_->d_name; return desynchronize_(true); } Size Directory::countItems() { synchronize_(); Size size = 0; DIR* dir = ::opendir(directory_path_.data()); if (dir == 0) { desynchronize_(); return 0; } while(::readdir(dir) != 0) ++size; ::closedir(dir); desynchronize_(); return (size - 2); } // ignore current (.) and parent directory entry (..) Size Directory::countFiles() { synchronize_(); struct stat stats; Size size = 0; dirent* myDirent; DIR* dir = ::opendir(directory_path_.data()); if (dir == 0) { desynchronize_(); return 0; } while((myDirent = ::readdir(dir)) != 0) { if (lstat(myDirent->d_name, &stats) < 0) continue; if (S_ISDIR(stats.st_mode) == 0) ++size; } ::closedir(dir); desynchronize_(); return size; } Size Directory::countDirectories() { synchronize_(); struct stat stats; Size size = 0; dirent* myDirent; DIR *dir = ::opendir(directory_path_.data()); if (dir == 0) { desynchronize_(); return 0; } while((myDirent = ::readdir(dir)) != 0) { if (lstat(myDirent->d_name, &stats) < 0) continue; if (S_ISDIR(stats.st_mode) != 0) ++size; } ::closedir(dir); desynchronize_(); return (size - 2); } // ignore current (.) and parent directory entry (..) bool Directory::isCurrent() const { char* buffer_; if ((buffer_ = ::getcwd(NULL, 64)) == 0) return false; return (buffer_ == directory_path_); } bool Directory::has(const String& item) //const { synchronize_(); String entry; while (getNextEntry(entry)) { if (entry == item) return desynchronize_(true); } return desynchronize_(false); } bool Directory::find(const String& item, String& filepath) { if (has(item)) { filepath = directory_path_; return true; // no sync needed... } synchronize_(); struct stat stats; dirent* myDirent; Directory directory; String s; DIR* dir = ::opendir(FileSystem::CURRENT_DIRECTORY); if (dir == 0) return desynchronize_(false); while((myDirent = ::readdir(dir)) != 0) { if (lstat(myDirent->d_name, &stats) < 0) continue; if (S_ISDIR(stats.st_mode) != 0 && strcmp(myDirent->d_name, FileSystem::CURRENT_DIRECTORY) != 0 && strcmp(myDirent->d_name, FileSystem::PARENT_DIRECTORY ) != 0) { directory =Directory(myDirent->d_name); if (directory.find(item, s)) { filepath = s; ::closedir(dir); return desynchronize_(true); } } } ::closedir(dir); return desynchronize_(false); } bool Directory::set(const String& directory_path, bool set_current) { dir_ = 0; dirent_ = 0; backup_path_ = ""; char* buffer_; if (directory_path[0] == '/') //absolute path { directory_path_ = directory_path; FileSystem::canonizePath(directory_path_); return isValid(); } if ((buffer_ = ::getcwd(NULL, 64)) != NULL) { directory_path_ = buffer_; directory_path_ += FileSystem::PATH_SEPARATOR; directory_path_ += directory_path; FileSystem::canonizePath(directory_path_); if (directory_path_.hasSuffix(String(FileSystem::PATH_SEPARATOR))) { directory_path_.truncate(directory_path_.size() - 1); } } else { directory_path_ = ""; return false; } if (!isValid()) return false; if (set_current) return (::chdir(directory_path_.data()) == 0); return true; } bool Directory::remove() { synchronize_(); if (::chdir("..") != 0) return desynchronize_(false); bool result1 = (::rmdir(directory_path_.data()) == 0); bool result2; if (backup_path_ != "") { result2 = ::chdir(backup_path_.data()); backup_path_ = ""; } dir_ = 0; dirent_ = 0; directory_path_ = ""; return (result1 && result2); } bool Directory::renameTo(String new_path) { synchronize_(); FileSystem::canonizePath(new_path); if (::chdir("..") != 0) return desynchronize_(false); if (::rename(directory_path_.data(), new_path.data()) == 0) { directory_path_ = new_path; return desynchronize_(true); } return desynchronize_(false); } # ifdef BALL_NO_INLINE_FUNCTIONS # include <BALL/SYSTEM/directory.iC> # endif } // namespace BALL <|endoftext|>
<commit_before>#include <thread> #include <chrono> #include <stdexcept> #include <cctype> #include <algorithm> #include <vector> #include <map> #include <sstream> #include "ogrsf_frmts.h" #include "common/config.h" #include "common/stringutils.h" #include "server/worker.h" using namespace Batyr; struct OgrField { std::string name; unsigned int index; OGRFieldType type; }; typedef std::map<std::string, OgrField> OgrFieldMap; Worker::Worker(Configuration::Ptr _configuration, std::shared_ptr<JobStorage> _jobs) : logger(Poco::Logger::get("Worker")), configuration(_configuration), jobs(_jobs), db(_configuration) { poco_debug(logger, "Creating Worker"); } Worker::~Worker() { poco_debug(logger, "Destroying Worker"); } void Worker::pull(Job::Ptr job) { if (job->getFilter().empty()) { poco_information(logger, "pulling layer \""+job->getLayerName()+"\""); } else { poco_information(logger, "pulling layer \""+job->getLayerName()+"\" using filter \""+job->getFilter()+"\""); } auto layer = configuration->getLayer(job->getLayerName()); // open the dataset std::unique_ptr<OGRDataSource, void (*)(OGRDataSource*)> ogrDataset( OGRSFDriverRegistrar::Open(layer->source.c_str(), false), OGRDataSource::DestroyDataSource); if (!ogrDataset) { throw WorkerError("Could not open dataset for layer \"" + layer->name + "\""); } // find the layer auto ogrLayer = ogrDataset->GetLayerByName(layer->source_layer.c_str()); if (ogrLayer == nullptr) { throw WorkerError("source_layer \"" +layer->source_layer+ "\" in dataset for layer \"" + layer->name + "\" not found"); } ogrLayer->ResetReading(); // TODO: set filter auto ogrFeatureDefn = ogrLayer->GetLayerDefn(); #if GDAL_VERSION_MAJOR > 1 if (ogrFeatureDefn->GetGeomFieldCount() != 1) { std::string msg = "The source provides " + std::to_string(ogrFeatureDefn->GetGeomFieldCount()) + "geometry fields. Currently only sources with on geoemtry field are supported"; throw WorkerError(msg); } #endif // collect the columns of the dataset OgrFieldMap ogrFields; for(int i=0; i<ogrFeatureDefn->GetFieldCount(); i++) { auto ogrFieldDefn = ogrFeatureDefn->GetFieldDefn(i); // lowercase column names -- TODO: this may cause problems when postgresqls column names // contain uppercase letters, but will do for a start std::string fieldNameCased = std::string(ogrFieldDefn->GetNameRef()); std::string fieldName; std::transform(fieldNameCased.begin(), fieldNameCased.end(), std::back_inserter(fieldName), ::tolower); #ifdef _DEBUG { std::string msg = "ogr layer provides the column " + fieldName; poco_debug(logger, msg.c_str()); } #endif auto entry = &ogrFields[fieldName]; entry->index = i; entry->type = ogrFieldDefn->GetType(); } // perform the work in an transaction if (auto transaction = db.getTransaction()) { int numPulled = 0; int numCreated = 0; int numUpdated = 0; int numDeleted = 0; // build a unique name for the temporary table std::string tempTableName = "batyr_" + job->getId(); // create a temp table to write the data to transaction->createTempTable(layer->target_table_schema, layer->target_table_name, tempTableName); // fetch the column list from the target_table as the tempTable // does not have the constraints of the original table auto tableFields = transaction->getTableFields(layer->target_table_schema, layer->target_table_name); // check if the requirements of the primary key are satisfied // TODO: allow overriding the primarykey from the configfile std::vector<std::string> primaryKeyColumns; std::string geometryColumn; std::vector<std::string> insertColumns; std::vector<std::string> updateColumns; for(auto tableFieldPair : tableFields) { if (tableFieldPair.second.isPrimaryKey) { primaryKeyColumns.push_back(tableFieldPair.second.name); } else { updateColumns.push_back(tableFieldPair.second.name); } if (tableFieldPair.second.pgTypeName == "geometry") { if (!geometryColumn.empty()) { throw WorkerError("Layer \"" + job->getLayerName() + "\" has multiple geometry columns. Currently only one is supported"); } geometryColumn = tableFieldPair.second.name; insertColumns.push_back(tableFieldPair.second.name); } if (ogrFields.find(tableFieldPair.second.name) != ogrFields.end()) { insertColumns.push_back(tableFieldPair.second.name); } } if (primaryKeyColumns.empty()) { throw WorkerError("Got no primarykey for layer \"" + job->getLayerName() + "\""); } std::vector<std::string> missingPrimaryKeysSource; for( auto primaryKeyCol : primaryKeyColumns) { if (ogrFields.find(primaryKeyCol) == ogrFields.end()) { missingPrimaryKeysSource.push_back(primaryKeyCol); } } if (!missingPrimaryKeysSource.empty()) { throw WorkerError("The source for layer \"" + job->getLayerName() + "\" is missing the following fields required "+ "by the primary key: " + StringUtils::join(missingPrimaryKeysSource, ", ")); } // prepare an insert query into the temporary table std::vector<std::string> insertQueryValues; unsigned int idxColumn = 1; for (std::string insertColumn : insertColumns) { std::stringstream colStream; colStream << "$" << idxColumn << "::" << tableFields[insertColumn].pgTypeName; insertQueryValues.push_back(colStream.str()); idxColumn++; } std::stringstream insertQueryStream; // TODO: include st_transform statement into insert if original table has a srid set in geometry_columns insertQueryStream << "insert into \"" << tempTableName << "\" (\"" << StringUtils::join(insertColumns, "\", \"") << "\") values (" << StringUtils::join(insertQueryValues, ", ") << ")"; poco_debug(logger, insertQueryStream.str().c_str()); std::string insertStmtName = "batyr_insert" + job->getId(); auto resInsertStmt = transaction->prepare(insertStmtName, insertQueryStream.str(), insertColumns.size(), NULL); OGRFeature * ogrFeature = 0; while( (ogrFeature = ogrLayer->GetNextFeature()) != nullptr) { std::vector<std::string> strValues; for (std::string insertColumn : insertColumns) { auto tableField = &tableFields[insertColumn]; if (tableField->pgTypeName == "geometry") { // TODO: Maybe use the implementation from OGRPGLayer::GeometryToHex GByte * buffer; auto ogrGeometry = ogrFeature->GetGeometryRef(); int bufferSize = ogrGeometry->WkbSize(); buffer = (GByte *) CPLMalloc(bufferSize); if (buffer == nullptr) { throw WorkerError("Unable to allocate memory to export geometry"); } if (ogrGeometry->exportToWkb(wkbNDR, buffer) != OGRERR_NONE) { OGRFree(buffer); throw WorkerError("Could not export the geometry from feature #" + std::to_string(numPulled)); } char * hexBuffer = CPLBinaryToHex(bufferSize, buffer); if (hexBuffer == nullptr) { OGRFree(buffer); throw WorkerError("Unable to allocate memory to convert geometry to hex"); } OGRFree(buffer); strValues.push_back(std::string(hexBuffer)); CPLFree(hexBuffer); } else { auto ogrField = &ogrFields[insertColumn]; switch (ogrField->type) { case OFTString: strValues.push_back(std::string(ogrFeature->GetFieldAsString(ogrField->index))); break; case OFTInteger: strValues.push_back(std::to_string(ogrFeature->GetFieldAsInteger(ogrField->index))); break; case OFTReal: strValues.push_back(std::to_string(ogrFeature->GetFieldAsDouble(ogrField->index))); break; // TODO: implment all of the OGRFieldType types default: throw WorkerError("Unsupported OGR field type: " + std::to_string(static_cast<int>(ogrField->type))); } } } // convert to an array of c strings std::vector<const char*> cStrValues; std::vector<int> cStrValueLenghts; std::transform(strValues.begin(), strValues.end(), std::back_inserter(cStrValues), [](std::string & s){ return s.c_str();}); std::transform(strValues.begin(), strValues.end(), std::back_inserter(cStrValueLenghts), [](std::string & s){ return s.length();}); transaction->execPrepared(insertStmtName, cStrValues.size(), &cStrValues[0], &cStrValueLenghts[0], NULL, 1); numPulled++; } job->setStatistics(numPulled, numCreated, numUpdated, numDeleted); // update the existing table only touching rows which have differences to prevent // slowdowns by triggers std::stringstream updateStmt; updateStmt << "update \"" << layer->target_table_schema << "\".\"" << layer->target_table_name << "\" " << " set "; bool firstIter = true; for (std::string updateColumn : updateColumns) { if (!firstIter) { updateStmt << ", "; } updateStmt << "\"" << updateColumn << "\" = \"" << tempTableName << "\".\"" << updateColumn << "\" "; firstIter = false; } updateStmt << " from \"" << tempTableName << "\"" << " where ("; firstIter = true; for (std::string primaryKeyColumn : primaryKeyColumns) { if (!firstIter) { updateStmt << " and "; } updateStmt << "\"" << layer->target_table_name << "\".\"" << primaryKeyColumn << "\" is not distinct from \"" << tempTableName << "\".\"" << primaryKeyColumn << "\""; firstIter = false; } updateStmt << ") and ("; firstIter = true; for (std::string updateColumn : updateColumns) { if (!firstIter) { updateStmt << " or "; } updateStmt << "(\"" << layer->target_table_name << "\".\"" << updateColumn << "\" is distinct from \"" << tempTableName << "\".\"" << updateColumn << "\")"; firstIter = false; } updateStmt << ")"; auto updateRes = transaction->exec(updateStmt.str()); numUpdated = std::atoi(PQcmdTuples(updateRes.get())); updateRes.reset(NULL); // immediately dispose the result // insert missing rows in the exisiting table std::stringstream insertMissingStmt; insertMissingStmt << "insert into \"" << layer->target_table_schema << "\".\"" << layer->target_table_name << "\" " << " ( \"" << StringUtils::join(insertColumns, "\", \"") << "\") " << " select \"" << StringUtils::join(insertColumns, "\", \"") << "\" " << " from \"" << tempTableName << "\"" << " where (\"" << StringUtils::join(primaryKeyColumns, "\", \"") << "\") not in (" << " select \"" << StringUtils::join(primaryKeyColumns, "\",\"") << "\" " << " from \"" << layer->target_table_schema << "\".\"" << layer->target_table_name << "\"" << ")"; auto insertMissingRes = transaction->exec(insertMissingStmt.str()); numCreated = std::atoi(PQcmdTuples(insertMissingRes.get())); insertMissingRes.reset(NULL); // immediately dispose the result // delete deprecated rows from the exisiting table // TODO: make this optional and skip when a filter is used std::stringstream deleteRemovedStmt; deleteRemovedStmt << "delete from \"" << layer->target_table_schema << "\".\"" << layer->target_table_name << "\" " << " where (\"" << StringUtils::join(primaryKeyColumns, "\", \"") << "\") not in (" << " select \"" << StringUtils::join(primaryKeyColumns, "\",\"") << "\" " << " from \"" << tempTableName << "\"" << ")"; auto deleteRemovedRes = transaction->exec(deleteRemovedStmt.str()); numDeleted = std::atoi(PQcmdTuples(deleteRemovedRes.get())); deleteRemovedRes.reset(NULL); // immediately dispose the result job->setStatus(Job::Status::FINISHED); job->setStatistics(numPulled, numCreated, numUpdated, numDeleted); } else { std::string msg("Could not start a database transaction"); poco_error(logger, msg.c_str()); job->setStatus(Job::Status::FAILED); job->setMessage(msg); } } void Worker::run() { while (true) { Job::Ptr job; try { bool got_job = jobs->pop(job); if (!got_job) { // no job means the queue recieved a quit command, so the worker // can be shut down break; } poco_debug(logger, "Got job from queue"); job->setStatus(Job::Status::IN_PROCESS); // check if we got a working database connection // or block until we got one size_t reconnectAttempts = 0; while(!db.reconnect(true)) { if (reconnectAttempts == 0) { // set job message to inform clients we are waiting here job->setMessage("Waiting to aquire a database connection"); } reconnectAttempts++; std::this_thread::sleep_for( std::chrono::milliseconds( SERVER_DB_RECONNECT_WAIT ) ); } pull(job); } catch (Batyr::Db::DbError &e) { poco_error(logger, e.what()); job->setStatus(Job::Status::FAILED); job->setMessage(e.what()); } catch (WorkerError &e) { poco_error(logger, e.what()); job->setStatus(Job::Status::FAILED); job->setMessage(e.what()); } catch (std::runtime_error &e) { poco_error(logger, e.what()); job->setStatus(Job::Status::FAILED); job->setMessage(e.what()); // do not know how this exception was caused as it // was not handled by one of the earlier catch blocks throw; } } poco_debug(logger, "leaving run method"); } <commit_msg>support for ogr attribute filters<commit_after>#include <thread> #include <chrono> #include <stdexcept> #include <cctype> #include <algorithm> #include <vector> #include <map> #include <sstream> #include "ogrsf_frmts.h" #include "common/config.h" #include "common/stringutils.h" #include "server/worker.h" using namespace Batyr; struct OgrField { std::string name; unsigned int index; OGRFieldType type; }; typedef std::map<std::string, OgrField> OgrFieldMap; Worker::Worker(Configuration::Ptr _configuration, std::shared_ptr<JobStorage> _jobs) : logger(Poco::Logger::get("Worker")), configuration(_configuration), jobs(_jobs), db(_configuration) { poco_debug(logger, "Creating Worker"); } Worker::~Worker() { poco_debug(logger, "Destroying Worker"); } void Worker::pull(Job::Ptr job) { if (job->getFilter().empty()) { poco_information(logger, "pulling layer \""+job->getLayerName()+"\""); } else { poco_information(logger, "pulling layer \""+job->getLayerName()+"\" using filter \""+job->getFilter()+"\""); } auto layer = configuration->getLayer(job->getLayerName()); // open the dataset std::unique_ptr<OGRDataSource, void (*)(OGRDataSource*)> ogrDataset( OGRSFDriverRegistrar::Open(layer->source.c_str(), false), OGRDataSource::DestroyDataSource); if (!ogrDataset) { throw WorkerError("Could not open dataset for layer \"" + layer->name + "\""); } // find the layer auto ogrLayer = ogrDataset->GetLayerByName(layer->source_layer.c_str()); if (ogrLayer == nullptr) { throw WorkerError("source_layer \"" +layer->source_layer+ "\" in dataset for layer \"" + layer->name + "\" not found"); } ogrLayer->ResetReading(); // set filter if set std::string filterString = job->getFilter(); if (!filterString.empty()) { CPLErrorReset(); if (ogrLayer->SetAttributeFilter(filterString.c_str()) != OGRERR_NONE) { std::stringstream msgstream; msgstream << "The given filter for layer \"" << layer->name << "\" is invalid"; if (CPLGetLastErrorMsg()) { msgstream << ": " << CPLGetLastErrorMsg(); } else { msgstream << "."; } msgstream << " The applied filter was [ " << filterString << " ]"; CPLErrorReset(); throw WorkerError(msgstream.str()); } } auto ogrFeatureDefn = ogrLayer->GetLayerDefn(); #if GDAL_VERSION_MAJOR > 1 if (ogrFeatureDefn->GetGeomFieldCount() != 1) { std::string msg = "The source provides " + std::to_string(ogrFeatureDefn->GetGeomFieldCount()) + "geometry fields. Currently only sources with on geoemtry field are supported"; throw WorkerError(msg); } #endif // collect the columns of the dataset OgrFieldMap ogrFields; for(int i=0; i<ogrFeatureDefn->GetFieldCount(); i++) { auto ogrFieldDefn = ogrFeatureDefn->GetFieldDefn(i); // lowercase column names -- TODO: this may cause problems when postgresqls column names // contain uppercase letters, but will do for a start std::string fieldNameCased = std::string(ogrFieldDefn->GetNameRef()); std::string fieldName; std::transform(fieldNameCased.begin(), fieldNameCased.end(), std::back_inserter(fieldName), ::tolower); #ifdef _DEBUG { std::string msg = "ogr layer provides the column " + fieldName; poco_debug(logger, msg.c_str()); } #endif auto entry = &ogrFields[fieldName]; entry->index = i; entry->type = ogrFieldDefn->GetType(); } // perform the work in an transaction if (auto transaction = db.getTransaction()) { int numPulled = 0; int numCreated = 0; int numUpdated = 0; int numDeleted = 0; // build a unique name for the temporary table std::string tempTableName = "batyr_" + job->getId(); // create a temp table to write the data to transaction->createTempTable(layer->target_table_schema, layer->target_table_name, tempTableName); // fetch the column list from the target_table as the tempTable // does not have the constraints of the original table auto tableFields = transaction->getTableFields(layer->target_table_schema, layer->target_table_name); // check if the requirements of the primary key are satisfied // TODO: allow overriding the primarykey from the configfile std::vector<std::string> primaryKeyColumns; std::string geometryColumn; std::vector<std::string> insertColumns; std::vector<std::string> updateColumns; for(auto tableFieldPair : tableFields) { if (tableFieldPair.second.isPrimaryKey) { primaryKeyColumns.push_back(tableFieldPair.second.name); } else { updateColumns.push_back(tableFieldPair.second.name); } if (tableFieldPair.second.pgTypeName == "geometry") { if (!geometryColumn.empty()) { throw WorkerError("Layer \"" + job->getLayerName() + "\" has multiple geometry columns. Currently only one is supported"); } geometryColumn = tableFieldPair.second.name; insertColumns.push_back(tableFieldPair.second.name); } if (ogrFields.find(tableFieldPair.second.name) != ogrFields.end()) { insertColumns.push_back(tableFieldPair.second.name); } } if (primaryKeyColumns.empty()) { throw WorkerError("Got no primarykey for layer \"" + job->getLayerName() + "\""); } std::vector<std::string> missingPrimaryKeysSource; for( auto primaryKeyCol : primaryKeyColumns) { if (ogrFields.find(primaryKeyCol) == ogrFields.end()) { missingPrimaryKeysSource.push_back(primaryKeyCol); } } if (!missingPrimaryKeysSource.empty()) { throw WorkerError("The source for layer \"" + job->getLayerName() + "\" is missing the following fields required "+ "by the primary key: " + StringUtils::join(missingPrimaryKeysSource, ", ")); } // prepare an insert query into the temporary table std::vector<std::string> insertQueryValues; unsigned int idxColumn = 1; for (std::string insertColumn : insertColumns) { std::stringstream colStream; colStream << "$" << idxColumn << "::" << tableFields[insertColumn].pgTypeName; insertQueryValues.push_back(colStream.str()); idxColumn++; } std::stringstream insertQueryStream; // TODO: include st_transform statement into insert if original table has a srid set in geometry_columns insertQueryStream << "insert into \"" << tempTableName << "\" (\"" << StringUtils::join(insertColumns, "\", \"") << "\") values (" << StringUtils::join(insertQueryValues, ", ") << ")"; poco_debug(logger, insertQueryStream.str().c_str()); std::string insertStmtName = "batyr_insert" + job->getId(); auto resInsertStmt = transaction->prepare(insertStmtName, insertQueryStream.str(), insertColumns.size(), NULL); OGRFeature * ogrFeature = 0; while( (ogrFeature = ogrLayer->GetNextFeature()) != nullptr) { std::vector<std::string> strValues; for (std::string insertColumn : insertColumns) { auto tableField = &tableFields[insertColumn]; if (tableField->pgTypeName == "geometry") { // TODO: Maybe use the implementation from OGRPGLayer::GeometryToHex GByte * buffer; auto ogrGeometry = ogrFeature->GetGeometryRef(); int bufferSize = ogrGeometry->WkbSize(); buffer = (GByte *) CPLMalloc(bufferSize); if (buffer == nullptr) { throw WorkerError("Unable to allocate memory to export geometry"); } if (ogrGeometry->exportToWkb(wkbNDR, buffer) != OGRERR_NONE) { OGRFree(buffer); throw WorkerError("Could not export the geometry from feature #" + std::to_string(numPulled)); } char * hexBuffer = CPLBinaryToHex(bufferSize, buffer); if (hexBuffer == nullptr) { OGRFree(buffer); throw WorkerError("Unable to allocate memory to convert geometry to hex"); } OGRFree(buffer); strValues.push_back(std::string(hexBuffer)); CPLFree(hexBuffer); } else { auto ogrField = &ogrFields[insertColumn]; switch (ogrField->type) { case OFTString: strValues.push_back(std::string(ogrFeature->GetFieldAsString(ogrField->index))); break; case OFTInteger: strValues.push_back(std::to_string(ogrFeature->GetFieldAsInteger(ogrField->index))); break; case OFTReal: strValues.push_back(std::to_string(ogrFeature->GetFieldAsDouble(ogrField->index))); break; // TODO: implment all of the OGRFieldType types default: throw WorkerError("Unsupported OGR field type: " + std::to_string(static_cast<int>(ogrField->type))); } } } // convert to an array of c strings std::vector<const char*> cStrValues; std::vector<int> cStrValueLenghts; std::transform(strValues.begin(), strValues.end(), std::back_inserter(cStrValues), [](std::string & s){ return s.c_str();}); std::transform(strValues.begin(), strValues.end(), std::back_inserter(cStrValueLenghts), [](std::string & s){ return s.length();}); transaction->execPrepared(insertStmtName, cStrValues.size(), &cStrValues[0], &cStrValueLenghts[0], NULL, 1); numPulled++; } job->setStatistics(numPulled, numCreated, numUpdated, numDeleted); // update the existing table only touching rows which have differences to prevent // slowdowns by triggers std::stringstream updateStmt; updateStmt << "update \"" << layer->target_table_schema << "\".\"" << layer->target_table_name << "\" " << " set "; bool firstIter = true; for (std::string updateColumn : updateColumns) { if (!firstIter) { updateStmt << ", "; } updateStmt << "\"" << updateColumn << "\" = \"" << tempTableName << "\".\"" << updateColumn << "\" "; firstIter = false; } updateStmt << " from \"" << tempTableName << "\"" << " where ("; firstIter = true; for (std::string primaryKeyColumn : primaryKeyColumns) { if (!firstIter) { updateStmt << " and "; } updateStmt << "\"" << layer->target_table_name << "\".\"" << primaryKeyColumn << "\" is not distinct from \"" << tempTableName << "\".\"" << primaryKeyColumn << "\""; firstIter = false; } updateStmt << ") and ("; firstIter = true; for (std::string updateColumn : updateColumns) { if (!firstIter) { updateStmt << " or "; } updateStmt << "(\"" << layer->target_table_name << "\".\"" << updateColumn << "\" is distinct from \"" << tempTableName << "\".\"" << updateColumn << "\")"; firstIter = false; } updateStmt << ")"; auto updateRes = transaction->exec(updateStmt.str()); numUpdated = std::atoi(PQcmdTuples(updateRes.get())); updateRes.reset(NULL); // immediately dispose the result // insert missing rows in the exisiting table std::stringstream insertMissingStmt; insertMissingStmt << "insert into \"" << layer->target_table_schema << "\".\"" << layer->target_table_name << "\" " << " ( \"" << StringUtils::join(insertColumns, "\", \"") << "\") " << " select \"" << StringUtils::join(insertColumns, "\", \"") << "\" " << " from \"" << tempTableName << "\"" << " where (\"" << StringUtils::join(primaryKeyColumns, "\", \"") << "\") not in (" << " select \"" << StringUtils::join(primaryKeyColumns, "\",\"") << "\" " << " from \"" << layer->target_table_schema << "\".\"" << layer->target_table_name << "\"" << ")"; auto insertMissingRes = transaction->exec(insertMissingStmt.str()); numCreated = std::atoi(PQcmdTuples(insertMissingRes.get())); insertMissingRes.reset(NULL); // immediately dispose the result // delete deprecated rows from the exisiting table // TODO: make this optional and skip when a filter is used std::stringstream deleteRemovedStmt; deleteRemovedStmt << "delete from \"" << layer->target_table_schema << "\".\"" << layer->target_table_name << "\" " << " where (\"" << StringUtils::join(primaryKeyColumns, "\", \"") << "\") not in (" << " select \"" << StringUtils::join(primaryKeyColumns, "\",\"") << "\" " << " from \"" << tempTableName << "\"" << ")"; auto deleteRemovedRes = transaction->exec(deleteRemovedStmt.str()); numDeleted = std::atoi(PQcmdTuples(deleteRemovedRes.get())); deleteRemovedRes.reset(NULL); // immediately dispose the result job->setStatus(Job::Status::FINISHED); job->setStatistics(numPulled, numCreated, numUpdated, numDeleted); } else { std::string msg("Could not start a database transaction"); poco_error(logger, msg.c_str()); job->setStatus(Job::Status::FAILED); job->setMessage(msg); } } void Worker::run() { while (true) { Job::Ptr job; try { bool got_job = jobs->pop(job); if (!got_job) { // no job means the queue recieved a quit command, so the worker // can be shut down break; } poco_debug(logger, "Got job from queue"); job->setStatus(Job::Status::IN_PROCESS); // check if we got a working database connection // or block until we got one size_t reconnectAttempts = 0; while(!db.reconnect(true)) { if (reconnectAttempts == 0) { // set job message to inform clients we are waiting here job->setMessage("Waiting to aquire a database connection"); } reconnectAttempts++; std::this_thread::sleep_for( std::chrono::milliseconds( SERVER_DB_RECONNECT_WAIT ) ); } pull(job); } catch (Batyr::Db::DbError &e) { poco_error(logger, e.what()); job->setStatus(Job::Status::FAILED); job->setMessage(e.what()); } catch (WorkerError &e) { poco_error(logger, e.what()); job->setStatus(Job::Status::FAILED); job->setMessage(e.what()); } catch (std::runtime_error &e) { poco_error(logger, e.what()); job->setStatus(Job::Status::FAILED); job->setMessage(e.what()); // do not know how this exception was caused as it // was not handled by one of the earlier catch blocks throw; } } poco_debug(logger, "leaving run method"); } <|endoftext|>
<commit_before>#include "adaptiverandom.h" #include <qmath.h> #include <cstdlib> namespace { AdaptiveRandom instance; } RpnOperand AdaptiveRandom::calculate(FunctionCalculator *calculator, QList<RpnOperand> actualArguments) { m_calculator = calculator; m_functionName = actualArguments[0].value.value<QString>(); m_sourcePoint = actualArguments[1].value.value<QList<Number> >(); if (m_calculator->functionArguments(m_functionName).size() != m_sourcePoint.size()) { THROW(EWrongParametersCount(QObject::tr("Source point"), m_calculator->functionArguments(m_functionName).size())); } m_acceleration = actualArguments[2].value.value<Number>(); m_decrease = actualArguments[3].value.value<Number>(); m_wrongStepsCount = actualArguments[4].value.value<Number>(); m_iterationsCount = actualArguments[5].value.value<Number>(); m_minimumStepSize = actualArguments[6].value.value<Number>(); m_stepSize = 1; // Initialize random srand(time(NULL)); RpnOperand result; result.type = RpnOperandVector; result.value = QVariant::fromValue(findMinimum()); return result; } QList<RpnArgument> AdaptiveRandom::requiredArguments() { QList<RpnArgument> arguments; arguments // NOTE: QVariant() shows that number of arguments is not fixed, maybe there is other way << RpnArgument(RpnOperandFunctionName, QString(), QVariant()) << RpnArgument(RpnOperandVector) << RpnArgument(RpnOperandNumber) << RpnArgument(RpnOperandNumber) << RpnArgument(RpnOperandNumber) << RpnArgument(RpnOperandNumber) << RpnArgument(RpnOperandNumber); return arguments; } QList<Number> AdaptiveRandom::findMinimum() { int failCount = 1; int iterationCount = 0; forever { QList<Number> randomPoint = generateRandomNumbers(m_sourcePoint.size(), -1, 1); QList<Number> currentPoint = sumListList( m_sourcePoint, productListNumber( quotientListNumber(randomPoint, modulusList(randomPoint)), m_stepSize ) ); if (countFunction(currentPoint) < countFunction(m_sourcePoint)) { QList<Number> newPoint = sumListList( m_sourcePoint, productListNumber( diffListList(currentPoint, m_sourcePoint), m_acceleration ) ); if (countFunction(newPoint) < countFunction(m_sourcePoint)) { m_sourcePoint = newPoint; m_stepSize *= m_acceleration; iterationCount++; if (iterationCount < m_iterationsCount) { failCount = 1; continue; } else { // Exit condition return m_sourcePoint; } } } if (failCount < m_wrongStepsCount) { failCount++; } else if (m_stepSize <= m_minimumStepSize) { // Exit condition return m_sourcePoint; } else { m_stepSize *= m_decrease; failCount = 1; } } } QList<Number> AdaptiveRandom::generateRandomNumbers(int count, Number lowerLimit, Number higherLimit) { QList<Number> result; for (int i = 0; i < count; i++) { result << getRandomNumber(qAbs(lowerLimit - higherLimit)) + lowerLimit; } return result; } // Return a random number between 0 and limit Number AdaptiveRandom::getRandomNumber(Number limit) { Number result; do { result = rand() / (RAND_MAX / (limit + 1)); } while (result > limit); return result; } QList<Number> AdaptiveRandom::productListNumber(QList<Number> list, Number number) { QList<Number> result; foreach (Number element, list) { result << element * number; } return result; } QList<Number> AdaptiveRandom::diffListList(QList<Number> source, QList<Number> subtractin) { QList<Number> result; for (int i = 0; i < source.size(); i++) { result << source[i] - subtractin[i]; } return result; } QList<Number> AdaptiveRandom::sumListList(QList<Number> source, QList<Number> item) { QList<Number> result; for (int i = 0; i < source.size(); i++) { result << source[i] + item[i]; } return result; } Number AdaptiveRandom::productListList(QList<Number> source, QList<Number> item) { Number result = 0; for (int i = 0; i < source.size(); i++) { result += source[i] * item[i]; } return result; } Number AdaptiveRandom::modulusList(QList<Number> list) { Number result = 0; foreach (Number element, list) { result += qPow(element, 2); } return qSqrt(result); } QList<Number> AdaptiveRandom::quotientListNumber(QList<Number> source, Number divisor) { QList<Number> result; foreach (Number element, source) { result << element / divisor; } return result; } Number AdaptiveRandom::countFunction(QList<Number> arguments) { QList<RpnOperand> functionArguments; foreach (Number argument, arguments) { RpnOperand functionArgument(RpnOperandNumber, argument); functionArguments << functionArgument; } RpnOperand result = m_calculator->calculate(m_functionName, functionArguments); return result.value.value<Number>(); } <commit_msg>Including ctime instead of cstdlib for using time() function, because MSVC won't find time() in cstdlib.<commit_after>#include "adaptiverandom.h" #include <qmath.h> #include <ctime> namespace { AdaptiveRandom instance; } RpnOperand AdaptiveRandom::calculate(FunctionCalculator *calculator, QList<RpnOperand> actualArguments) { m_calculator = calculator; m_functionName = actualArguments[0].value.value<QString>(); m_sourcePoint = actualArguments[1].value.value<QList<Number> >(); if (m_calculator->functionArguments(m_functionName).size() != m_sourcePoint.size()) { THROW(EWrongParametersCount(QObject::tr("Source point"), m_calculator->functionArguments(m_functionName).size())); } m_acceleration = actualArguments[2].value.value<Number>(); m_decrease = actualArguments[3].value.value<Number>(); m_wrongStepsCount = actualArguments[4].value.value<Number>(); m_iterationsCount = actualArguments[5].value.value<Number>(); m_minimumStepSize = actualArguments[6].value.value<Number>(); m_stepSize = 1; // Initialize random srand(time(NULL)); RpnOperand result; result.type = RpnOperandVector; result.value = QVariant::fromValue(findMinimum()); return result; } QList<RpnArgument> AdaptiveRandom::requiredArguments() { QList<RpnArgument> arguments; arguments // NOTE: QVariant() shows that number of arguments is not fixed, maybe there is other way << RpnArgument(RpnOperandFunctionName, QString(), QVariant()) << RpnArgument(RpnOperandVector) << RpnArgument(RpnOperandNumber) << RpnArgument(RpnOperandNumber) << RpnArgument(RpnOperandNumber) << RpnArgument(RpnOperandNumber) << RpnArgument(RpnOperandNumber); return arguments; } QList<Number> AdaptiveRandom::findMinimum() { int failCount = 1; int iterationCount = 0; forever { QList<Number> randomPoint = generateRandomNumbers(m_sourcePoint.size(), -1, 1); QList<Number> currentPoint = sumListList( m_sourcePoint, productListNumber( quotientListNumber(randomPoint, modulusList(randomPoint)), m_stepSize ) ); if (countFunction(currentPoint) < countFunction(m_sourcePoint)) { QList<Number> newPoint = sumListList( m_sourcePoint, productListNumber( diffListList(currentPoint, m_sourcePoint), m_acceleration ) ); if (countFunction(newPoint) < countFunction(m_sourcePoint)) { m_sourcePoint = newPoint; m_stepSize *= m_acceleration; iterationCount++; if (iterationCount < m_iterationsCount) { failCount = 1; continue; } else { // Exit condition return m_sourcePoint; } } } if (failCount < m_wrongStepsCount) { failCount++; } else if (m_stepSize <= m_minimumStepSize) { // Exit condition return m_sourcePoint; } else { m_stepSize *= m_decrease; failCount = 1; } } } QList<Number> AdaptiveRandom::generateRandomNumbers(int count, Number lowerLimit, Number higherLimit) { QList<Number> result; for (int i = 0; i < count; i++) { result << getRandomNumber(qAbs(lowerLimit - higherLimit)) + lowerLimit; } return result; } // Return a random number between 0 and limit Number AdaptiveRandom::getRandomNumber(Number limit) { Number result; do { result = rand() / (RAND_MAX / (limit + 1)); } while (result > limit); return result; } QList<Number> AdaptiveRandom::productListNumber(QList<Number> list, Number number) { QList<Number> result; foreach (Number element, list) { result << element * number; } return result; } QList<Number> AdaptiveRandom::diffListList(QList<Number> source, QList<Number> subtractin) { QList<Number> result; for (int i = 0; i < source.size(); i++) { result << source[i] - subtractin[i]; } return result; } QList<Number> AdaptiveRandom::sumListList(QList<Number> source, QList<Number> item) { QList<Number> result; for (int i = 0; i < source.size(); i++) { result << source[i] + item[i]; } return result; } Number AdaptiveRandom::productListList(QList<Number> source, QList<Number> item) { Number result = 0; for (int i = 0; i < source.size(); i++) { result += source[i] * item[i]; } return result; } Number AdaptiveRandom::modulusList(QList<Number> list) { Number result = 0; foreach (Number element, list) { result += qPow(element, 2); } return qSqrt(result); } QList<Number> AdaptiveRandom::quotientListNumber(QList<Number> source, Number divisor) { QList<Number> result; foreach (Number element, source) { result << element / divisor; } return result; } Number AdaptiveRandom::countFunction(QList<Number> arguments) { QList<RpnOperand> functionArguments; foreach (Number argument, arguments) { RpnOperand functionArgument(RpnOperandNumber, argument); functionArguments << functionArgument; } RpnOperand result = m_calculator->calculate(m_functionName, functionArguments); return result.value.value<Number>(); } <|endoftext|>
<commit_before>/* vcflib C++ library for parsing and manipulating VCF files Copyright © 2010-2020 Erik Garrison Copyright © 2020 Pjotr Prins This software is published under the MIT License. See the LICENSE file. */ #include "Variant.h" #include <set> using namespace std; using namespace vcflib; int main(int argc, char** argv) { if (argc == 2) { string h_flag = argv[1]; if (h_flag == "-h" || h_flag == "--help") { cerr << R"( List unique alleles For each record, remove any duplicate alternate alleles that may have resulted from merging separate VCF files. Usage: vcfuniqalleles <vcf file> Type: filter )"; exit(1); } } VariantCallFile variantFile; if (argc > 1) { string filename = argv[1]; variantFile.open(filename); } else { variantFile.open(std::cin); } if (!variantFile.is_open()) { return 1; } cout << variantFile.header << endl; string lastsn; long int lastpos; string lastref; vector<string> lastalt; Variant var(variantFile); while (variantFile.getNextVariant(var)) { set<string> alleles; vector<string> alleles_to_remove; for (vector<string>::iterator a = var.alt.begin(); a != var.alt.end(); ++a) { if (*a != var.ref) { if (alleles.find(*a) == alleles.end()) { alleles.insert(*a); } else { alleles_to_remove.push_back(*a); } } else { alleles_to_remove.push_back(*a); // same as ref } } for (vector<string>::iterator a = alleles_to_remove.begin(); a != alleles_to_remove.end(); ++a) { cerr << "removing " << *a << " from " << var.sequenceName << ":" << var.position << endl; var.removeAlt(*a); } cout << var << endl; } return 0; } <commit_msg>vcfuniqalleles: remove unused variables.<commit_after>/* vcflib C++ library for parsing and manipulating VCF files Copyright © 2010-2020 Erik Garrison Copyright © 2020 Pjotr Prins This software is published under the MIT License. See the LICENSE file. */ #include "Variant.h" #include <set> using namespace std; using namespace vcflib; int main(int argc, char** argv) { if (argc == 2) { string h_flag = argv[1]; if (h_flag == "-h" || h_flag == "--help") { cerr << R"( List unique alleles For each record, remove any duplicate alternate alleles that may have resulted from merging separate VCF files. Usage: vcfuniqalleles <vcf file> Type: filter )"; exit(1); } } VariantCallFile variantFile; if (argc > 1) { string filename = argv[1]; variantFile.open(filename); } else { variantFile.open(std::cin); } if (!variantFile.is_open()) { return 1; } cout << variantFile.header << endl; Variant var(variantFile); while (variantFile.getNextVariant(var)) { set<string> alleles; vector<string> alleles_to_remove; for (vector<string>::iterator a = var.alt.begin(); a != var.alt.end(); ++a) { if (*a != var.ref) { if (alleles.find(*a) == alleles.end()) { alleles.insert(*a); } else { alleles_to_remove.push_back(*a); } } else { alleles_to_remove.push_back(*a); // same as ref } } for (vector<string>::iterator a = alleles_to_remove.begin(); a != alleles_to_remove.end(); ++a) { cerr << "removing " << *a << " from " << var.sequenceName << ":" << var.position << endl; var.removeAlt(*a); } cout << var << endl; } return 0; } <|endoftext|>
<commit_before>#include "addgroupwindow.h" #include "functions.h" /** * Constructor of the AddGroupWindow class, generating its window. * @param favorites List of favorites tags, needed for coloration * @param parent The parent window */ AddGroupWindow::AddGroupWindow(QStringList sites, QStringList favorites, mainWindow *parent) : QWidget(parent), m_parent(parent), m_sites(sites) { QVBoxLayout *layout = new QVBoxLayout; QFormLayout *formLayout = new QFormLayout; m_comboSites = new QComboBox; m_comboSites->setMaxVisibleItems(20); m_comboSites->addItems(m_sites); formLayout->addRow(tr("&Site"), m_comboSites); m_lineTags = new TextEdit(favorites, this); m_lineTags->setContextMenuPolicy(Qt::CustomContextMenu); QStringList completion; QFile words("words.txt"); if (words.open(QIODevice::ReadOnly | QIODevice::Text)) { while (!words.atEnd()) { QByteArray line = words.readLine(); completion.append(QString(line).remove("\r\n").remove("\n").split(" ", QString::SkipEmptyParts)); } QCompleter *completer = new QCompleter(completion, this); completer->setCaseSensitivity(Qt::CaseInsensitive); m_lineTags->setCompleter(completer); } formLayout->addRow(tr("&Tags"), m_lineTags); m_spinPage = new QSpinBox; m_spinPage->setRange(1, 1000); m_spinPage->setValue(1); formLayout->addRow(tr("&Page"), m_spinPage); m_spinPP = new QSpinBox; m_spinPP->setRange(1, 1000); m_spinPP->setValue(100); formLayout->addRow(tr("&Images par page"), m_spinPP); m_spinLimit = new QSpinBox; m_spinLimit->setRange(1, 1000000); m_spinLimit->setValue(100); formLayout->addRow(tr("&Limite d'images"), m_spinLimit); m_comboDwl = new QComboBox; m_comboDwl->setMaxVisibleItems(20); m_comboDwl->addItems(QStringList() << tr("Oui") << tr("Non")); m_comboDwl->setCurrentIndex(1); formLayout->addRow(tr("&Tlcharger les image de la liste noire"), m_comboDwl); layout->addLayout(formLayout); QHBoxLayout *layoutButtons = new QHBoxLayout; QPushButton *buttonOk = new QPushButton(tr("Ok")); connect(buttonOk, SIGNAL(clicked()), this, SLOT(ok())); layoutButtons->addWidget(buttonOk); QPushButton *buttonClose = new QPushButton(tr("Fermer")); connect(buttonClose, SIGNAL(clicked()), this, SLOT(close())); layoutButtons->addWidget(buttonClose); layout->addLayout(layoutButtons); this->setLayout(layout); this->setWindowIcon(QIcon(":/images/icon.ico")); this->setWindowTitle(tr("Grabber")+" - "+tr("Ajouter groupe")); this->setWindowFlags(Qt::Window); this->resize(QSize(400, 0)); } /** * Relays the informations to the parent window. */ void AddGroupWindow::ok() { QSettings *settings = new QSettings(savePath("settings.ini"), QSettings::IniFormat); QStringList bools = QStringList() << "true" << "false"; QStringList values = QStringList() << m_lineTags->toPlainText() << QString::number(m_spinPage->value()) << QString::number(m_spinPP->value()) << QString::number(m_spinLimit->value()) << bools.at(m_comboDwl->currentIndex()) << m_sites.at(m_comboSites->currentIndex()) << "false" << settings->value("Save/filename").toString() << settings->value("Save/path").toString() << ""; m_parent->batchAddGroup(values); this->close(); } <commit_msg>Fixed addgroupwindow.cpp bug (remaining popular boolean removed)<commit_after>#include "addgroupwindow.h" #include "functions.h" /** * Constructor of the AddGroupWindow class, generating its window. * @param favorites List of favorites tags, needed for coloration * @param parent The parent window */ AddGroupWindow::AddGroupWindow(QStringList sites, QStringList favorites, mainWindow *parent) : QWidget(parent), m_parent(parent), m_sites(sites) { QVBoxLayout *layout = new QVBoxLayout; QFormLayout *formLayout = new QFormLayout; m_comboSites = new QComboBox; m_comboSites->setMaxVisibleItems(20); m_comboSites->addItems(m_sites); formLayout->addRow(tr("&Site"), m_comboSites); m_lineTags = new TextEdit(favorites, this); m_lineTags->setContextMenuPolicy(Qt::CustomContextMenu); QStringList completion; QFile words("words.txt"); if (words.open(QIODevice::ReadOnly | QIODevice::Text)) { while (!words.atEnd()) { QByteArray line = words.readLine(); completion.append(QString(line).remove("\r\n").remove("\n").split(" ", QString::SkipEmptyParts)); } QCompleter *completer = new QCompleter(completion, this); completer->setCaseSensitivity(Qt::CaseInsensitive); m_lineTags->setCompleter(completer); } formLayout->addRow(tr("&Tags"), m_lineTags); m_spinPage = new QSpinBox; m_spinPage->setRange(1, 1000); m_spinPage->setValue(1); formLayout->addRow(tr("&Page"), m_spinPage); m_spinPP = new QSpinBox; m_spinPP->setRange(1, 1000); m_spinPP->setValue(100); formLayout->addRow(tr("&Images par page"), m_spinPP); m_spinLimit = new QSpinBox; m_spinLimit->setRange(1, 1000000); m_spinLimit->setValue(100); formLayout->addRow(tr("&Limite d'images"), m_spinLimit); m_comboDwl = new QComboBox; m_comboDwl->setMaxVisibleItems(20); m_comboDwl->addItems(QStringList() << tr("Oui") << tr("Non")); m_comboDwl->setCurrentIndex(1); formLayout->addRow(tr("&Tlcharger les image de la liste noire"), m_comboDwl); layout->addLayout(formLayout); QHBoxLayout *layoutButtons = new QHBoxLayout; QPushButton *buttonOk = new QPushButton(tr("Ok")); connect(buttonOk, SIGNAL(clicked()), this, SLOT(ok())); layoutButtons->addWidget(buttonOk); QPushButton *buttonClose = new QPushButton(tr("Fermer")); connect(buttonClose, SIGNAL(clicked()), this, SLOT(close())); layoutButtons->addWidget(buttonClose); layout->addLayout(layoutButtons); this->setLayout(layout); this->setWindowIcon(QIcon(":/images/icon.ico")); this->setWindowTitle(tr("Grabber")+" - "+tr("Ajouter groupe")); this->setWindowFlags(Qt::Window); this->resize(QSize(400, 0)); } /** * Relays the informations to the parent window. */ void AddGroupWindow::ok() { QSettings *settings = new QSettings(savePath("settings.ini"), QSettings::IniFormat); QStringList bools = QStringList() << "true" << "false"; QStringList values = QStringList() << m_lineTags->toPlainText() << QString::number(m_spinPage->value()) << QString::number(m_spinPP->value()) << QString::number(m_spinLimit->value()) << bools.at(m_comboDwl->currentIndex()) << m_sites.at(m_comboSites->currentIndex()) << settings->value("Save/filename").toString() << settings->value("Save/path").toString() << ""; m_parent->batchAddGroup(values); this->close(); } <|endoftext|>
<commit_before>/******************************************************************************* * src/benchmark.cpp * * Copyright (C) 2017 Florian Kurpicz <[email protected]> * * All rights reserved. Published under the BSD-2 license in the LICENSE file. ******************************************************************************/ #include <tclap/CmdLine.h> #include <vector> #include "benchmark/algorithm.hpp" #include "util/alphabet_util.hpp" #include "util/file_util.hpp" #ifdef MALLOC_COUNT #include "benchmark/malloc_count.h" #endif // MALLOC_COUNT auto filter_parallel(bool only_parallel, bool is_parallel) { return (!only_parallel || is_parallel); } auto filter_sequential(bool sequential, bool is_parallel) { return (!sequential || !is_parallel); } auto filter_wavelet_type(bool is_tree, bool no_trees, bool no_matrices) { return (is_tree ? !no_trees : !no_matrices); } int32_t main(int32_t argc, char const* argv[]) { TCLAP::CmdLine cmd("Benchmark for wavelet tree (and matrix) construction", ' ', "0.2"); TCLAP::SwitchArg list_all_algorithms("l", "list", "Print the name and description of all registered algorithms", false); cmd.add(list_all_algorithms); TCLAP::MultiArg<std::string> file_path_arg("f", "file", "Path to the text file.", false, "string"); cmd.add(file_path_arg); TCLAP::ValueArg<std::string> filter_arg("n", "name", "Runs all algorithms that contain the <name> in their name", false, "", "string"); cmd.add(filter_arg); TCLAP::ValueArg<int32_t> word_width_arg("b", "byte", "Bytes per char in the input text.", false, 1, "uint8_t"); cmd.add(word_width_arg); TCLAP::ValueArg<int32_t> nr_runs_arg("r", "runs", "Number of repetitions of the construction algorithm.", false, 5, "int32_t"); cmd.add(nr_runs_arg); TCLAP::SwitchArg run_only_parallel_arg("p", "parallel", "Run only parallel construction algorithms.", false); cmd.add(run_only_parallel_arg); TCLAP::SwitchArg run_only_sequential_arg("s", "sequential", "Run only sequential construction algorithms.", false); cmd.add(run_only_sequential_arg); TCLAP::SwitchArg no_trees_arg("m", "no_trees", "Skip all wavelet trees construction algorithms.", false); cmd.add(no_trees_arg); TCLAP::SwitchArg no_matrices_arg("t", "no_matrices", "Skip all wavelet matrices construction algorithms.", false); cmd.add(no_matrices_arg); TCLAP::SwitchArg memory_arg("", "memory", "Compute peak memory during construction.", false); cmd.add(memory_arg); cmd.parse( argc, argv ); auto& algo_list = algorithm_list::get_algorithm_list(); if (list_all_algorithms.getValue()) { for (const auto& a : algo_list) { a->print_info(); } return 0; } const std::vector<std::string> file_paths = file_path_arg.getValue(); std::string filter = filter_arg.getValue(); const int32_t word_width = word_width_arg.getValue(); const int32_t nr_runs = nr_runs_arg.getValue(); const bool run_only_parallel = run_only_parallel_arg.getValue(); const bool run_only_sequential = run_only_sequential_arg.getValue(); const bool no_trees = no_trees_arg.getValue(); const bool no_matrices = no_matrices_arg.getValue(); const bool memory = memory_arg.getValue(); for (const auto& path : file_paths) { std::cout << std::endl << "Text: " << path << std::endl; void* txt_prt = nullptr; uint64_t text_size = 0; uint64_t max_char = 0; uint64_t levels = 0; std::vector<uint8_t> text_uint8; std::vector<uint16_t> text_uint16; std::vector<uint32_t> text_uint32; std::vector<uint64_t> text_uint64; #ifdef MALLOC_COUNT malloc_count_reset_peak(); #endif if (word_width == 1) { text_uint8 = file_to_vector<1>(path); text_size = text_uint8.size(); max_char = reduce_alphabet(text_uint8); levels = levels_for_max_char(max_char); txt_prt = &text_uint8; } else if (word_width == 2) { text_uint16 = file_to_vector<2>(path); text_size = text_uint16.size(); max_char = reduce_alphabet(text_uint16); levels = levels_for_max_char(max_char); txt_prt = &text_uint16; } else if (word_width == 4) { text_uint32 = file_to_vector<4>(path); text_size = text_uint32.size(); max_char = reduce_alphabet(text_uint32); levels = levels_for_max_char(max_char); txt_prt = &text_uint32; } else if (word_width == 8) { text_uint64 = file_to_vector<8>(path); text_size = text_uint64.size(); max_char = reduce_alphabet(text_uint64); levels = levels_for_max_char(max_char); txt_prt = &text_uint64; } else { std::cerr << "You entered an invalid number of bytes per character " "(parameter 'b')." << std::endl; return -1; } std::cout << "Characters: " << text_size << std::endl; #ifdef MALLOC_COUNT std::cout << "Memory peak text: " << malloc_count_peak() << ", MB: " << malloc_count_peak() / (1024 * 1024) << std::endl; #endif // MALLOC_COUNT for (const auto& a : algo_list) { if (filter == "" || (a->name().find(filter) != std::string::npos)) { if (a->word_width() == word_width) { if (filter_parallel(run_only_parallel, a->is_parallel())) { if (filter_sequential(run_only_sequential, a->is_parallel())) { if (filter_wavelet_type(a->is_tree(), no_trees, no_matrices)) { a->print_info(); if (memory) { #ifdef MALLOC_COUNT malloc_count_reset_peak(); a->memory_peak(txt_prt, text_size, levels); std::cout << malloc_count_peak() << ", MB: " << malloc_count_peak() / (1024 * 1024) << std::endl; #else std::cout << "Memory measurement is NOT enabled." << std::endl; #endif // MALLOC_COUNT } else { std::cout << a->median_time( txt_prt, text_size, levels, nr_runs) << std::endl; } } } } } } } } return 0; } /******************************************************************************/ <commit_msg>fix confusing memory output<commit_after>/******************************************************************************* * src/benchmark.cpp * * Copyright (C) 2017 Florian Kurpicz <[email protected]> * * All rights reserved. Published under the BSD-2 license in the LICENSE file. ******************************************************************************/ #include <tclap/CmdLine.h> #include <vector> #include "benchmark/algorithm.hpp" #include "util/alphabet_util.hpp" #include "util/file_util.hpp" #ifdef MALLOC_COUNT #include "benchmark/malloc_count.h" #endif // MALLOC_COUNT auto filter_parallel(bool only_parallel, bool is_parallel) { return (!only_parallel || is_parallel); } auto filter_sequential(bool sequential, bool is_parallel) { return (!sequential || !is_parallel); } auto filter_wavelet_type(bool is_tree, bool no_trees, bool no_matrices) { return (is_tree ? !no_trees : !no_matrices); } int32_t main(int32_t argc, char const* argv[]) { TCLAP::CmdLine cmd("Benchmark for wavelet tree (and matrix) construction", ' ', "0.2"); TCLAP::SwitchArg list_all_algorithms("l", "list", "Print the name and description of all registered algorithms", false); cmd.add(list_all_algorithms); TCLAP::MultiArg<std::string> file_path_arg("f", "file", "Path to the text file.", false, "string"); cmd.add(file_path_arg); TCLAP::ValueArg<std::string> filter_arg("n", "name", "Runs all algorithms that contain the <name> in their name", false, "", "string"); cmd.add(filter_arg); TCLAP::ValueArg<int32_t> word_width_arg("b", "byte", "Bytes per char in the input text.", false, 1, "uint8_t"); cmd.add(word_width_arg); TCLAP::ValueArg<int32_t> nr_runs_arg("r", "runs", "Number of repetitions of the construction algorithm.", false, 5, "int32_t"); cmd.add(nr_runs_arg); TCLAP::SwitchArg run_only_parallel_arg("p", "parallel", "Run only parallel construction algorithms.", false); cmd.add(run_only_parallel_arg); TCLAP::SwitchArg run_only_sequential_arg("s", "sequential", "Run only sequential construction algorithms.", false); cmd.add(run_only_sequential_arg); TCLAP::SwitchArg no_trees_arg("m", "no_trees", "Skip all wavelet trees construction algorithms.", false); cmd.add(no_trees_arg); TCLAP::SwitchArg no_matrices_arg("t", "no_matrices", "Skip all wavelet matrices construction algorithms.", false); cmd.add(no_matrices_arg); TCLAP::SwitchArg memory_arg("", "memory", "Compute peak memory during construction.", false); cmd.add(memory_arg); cmd.parse( argc, argv ); auto& algo_list = algorithm_list::get_algorithm_list(); if (list_all_algorithms.getValue()) { for (const auto& a : algo_list) { a->print_info(); } return 0; } const std::vector<std::string> file_paths = file_path_arg.getValue(); std::string filter = filter_arg.getValue(); const int32_t word_width = word_width_arg.getValue(); const int32_t nr_runs = nr_runs_arg.getValue(); const bool run_only_parallel = run_only_parallel_arg.getValue(); const bool run_only_sequential = run_only_sequential_arg.getValue(); const bool no_trees = no_trees_arg.getValue(); const bool no_matrices = no_matrices_arg.getValue(); const bool memory = memory_arg.getValue(); for (const auto& path : file_paths) { std::cout << std::endl << "Text: " << path << std::endl; void* txt_prt = nullptr; uint64_t text_size = 0; uint64_t max_char = 0; uint64_t levels = 0; std::vector<uint8_t> text_uint8; std::vector<uint16_t> text_uint16; std::vector<uint32_t> text_uint32; std::vector<uint64_t> text_uint64; #ifdef MALLOC_COUNT malloc_count_reset_peak(); #endif if (word_width == 1) { text_uint8 = file_to_vector<1>(path); text_size = text_uint8.size(); max_char = reduce_alphabet(text_uint8); levels = levels_for_max_char(max_char); txt_prt = &text_uint8; } else if (word_width == 2) { text_uint16 = file_to_vector<2>(path); text_size = text_uint16.size(); max_char = reduce_alphabet(text_uint16); levels = levels_for_max_char(max_char); txt_prt = &text_uint16; } else if (word_width == 4) { text_uint32 = file_to_vector<4>(path); text_size = text_uint32.size(); max_char = reduce_alphabet(text_uint32); levels = levels_for_max_char(max_char); txt_prt = &text_uint32; } else if (word_width == 8) { text_uint64 = file_to_vector<8>(path); text_size = text_uint64.size(); max_char = reduce_alphabet(text_uint64); levels = levels_for_max_char(max_char); txt_prt = &text_uint64; } else { std::cerr << "You entered an invalid number of bytes per character " "(parameter 'b')." << std::endl; return -1; } std::cout << "Characters: " << text_size << std::endl; #ifdef MALLOC_COUNT std::cout << "Memory peak text: " << malloc_count_peak() << ", MB: " << malloc_count_peak() / (1024 * 1024) << std::endl; #endif // MALLOC_COUNT for (const auto& a : algo_list) { if (filter == "" || (a->name().find(filter) != std::string::npos)) { if (a->word_width() == word_width) { if (filter_parallel(run_only_parallel, a->is_parallel())) { if (filter_sequential(run_only_sequential, a->is_parallel())) { if (filter_wavelet_type(a->is_tree(), no_trees, no_matrices)) { a->print_info(); if (memory) { #ifdef MALLOC_COUNT malloc_count_reset_peak(); a->memory_peak(txt_prt, text_size, levels); std::cout << "B: " << malloc_count_peak() << ", MB: " << malloc_count_peak() / (1024 * 1024) << std::endl; #else std::cout << "Memory measurement is NOT enabled." << std::endl; #endif // MALLOC_COUNT } else { std::cout << a->median_time( txt_prt, text_size, levels, nr_runs) << std::endl; } } } } } } } } return 0; } /******************************************************************************/ <|endoftext|>
<commit_before>#include "block_sync.h" namespace redsea { namespace { const unsigned kBitmask16 = 0x000FFFF; const unsigned kBitmask26 = 0x3FFFFFF; const unsigned kBitmask28 = 0xFFFFFFF; const unsigned kMaxErrorLength = 5; const std::vector<uint16_t> offset_words = {0x0FC, 0x198, 0x168, 0x350, 0x1B4}; const std::map<uint16_t,eOffset> offset_syndromes = {{0x3D8,OFFSET_A}, {0x3D4,OFFSET_B}, {0x25C,OFFSET_C}, {0x3CC,OFFSET_CI}, {0x258,OFFSET_D}}; const std::vector<uint16_t> block_number_for_offset = {0, 1, 2, 2, 3}; // Section B.1.1: '-- calculated by the modulo-two addition of all the rows of // the -- matrix for which the corresponding coefficient in the -- vector is 1.' uint32_t matrixMultiply(uint32_t vec, const std::vector<uint32_t>& matrix) { uint32_t result = 0; for (int k=0; k<(int)matrix.size(); k++) if ((vec >> k) & 0x01) result ^= matrix[matrix.size() - 1 - k]; return result; } // Section B.2.1: 'The calculation of the syndromes -- can easily be done by // multiplying each word with the parity matrix H.' uint32_t calcSyndrome(uint32_t vec) { static const std::vector<uint32_t> parity_check_matrix({ 0x200, 0x100, 0x080, 0x040, 0x020, 0x010, 0x008, 0x004, 0x002, 0x001, 0x2dc, 0x16e, 0x0b7, 0x287, 0x39f, 0x313, 0x355, 0x376, 0x1bb, 0x201, 0x3dc, 0x1ee, 0x0f7, 0x2a7, 0x38f, 0x31b }); return matrixMultiply(vec, parity_check_matrix); } eOffset nextOffsetFor(eOffset o) { static const std::map<eOffset,eOffset> next_offset({ {OFFSET_A,OFFSET_B}, {OFFSET_B,OFFSET_C}, {OFFSET_C,OFFSET_D}, {OFFSET_CI,OFFSET_D}, {OFFSET_D,OFFSET_A} }); return next_offset.at(o); } // Precompute mapping of syndromes to error vectors std::map<uint16_t,uint32_t> makeErrorLookupTable() { std::map<uint16_t,uint32_t> result; for (uint32_t e=1; e < (1<<kMaxErrorLength); e++) { for (unsigned shift=0; shift < 26; shift++) { uint32_t errvec = ((e << shift) & kBitmask26); uint32_t sy = calcSyndrome(errvec); result[sy] = errvec; } } return result; } } // namespace BlockStream::BlockStream(eInputType input_type) : bitcount_(0), prevbitcount_(0), left_to_read_(0), wideblock_(0), prevsync_(0), block_counter_(0), expected_offset_(OFFSET_A), received_offset_(OFFSET_INVALID), pi_(0), is_in_sync_(false), group_data_(4), has_block_(5), block_has_errors_(50), subcarrier_(), ascii_bits_(), error_lookup_(makeErrorLookupTable()), num_blocks_received_(0), input_type_(input_type), is_eof_(false) { } int BlockStream::getNextBit() { int result = 0; if (input_type_ == INPUT_MPX) { result = subcarrier_.getNextBit(); is_eof_ = subcarrier_.isEOF(); } else if (input_type_ == INPUT_ASCIIBITS) { result = ascii_bits_.getNextBit(); is_eof_ = ascii_bits_.isEOF(); } return result; } // Section B.2.2 uint32_t BlockStream::correctBurstErrors(uint32_t block) const { uint16_t synd_reg = calcSyndrome(block ^ offset_words[expected_offset_]); uint32_t corrected_block = block; if (error_lookup_.find(synd_reg) != error_lookup_.end()) { corrected_block = (block ^ offset_words[expected_offset_]) ^ (error_lookup_.at(synd_reg)); } return corrected_block; } // When a block can't be decoded, save the beginning of the group if possible void BlockStream::uncorrectable() { num_blocks_received_ = 0; for (eOffset o : {OFFSET_A, OFFSET_B, OFFSET_C, OFFSET_CI}) { if (has_block_[o]) { num_blocks_received_ = block_number_for_offset[o] + 1; } else { break; } } block_has_errors_[block_counter_ % block_has_errors_.size()] = true; unsigned num_erroneous_blocks = 0; for (bool e : block_has_errors_) { if (e) num_erroneous_blocks ++; } // Sync is lost when >45 out of last 50 blocks are erroneous (Section C.1.2) if (is_in_sync_ && num_erroneous_blocks > 45) { is_in_sync_ = false; for (unsigned i=0; i<block_has_errors_.size(); i++) block_has_errors_[i] = false; pi_ = 0x0000; } for (eOffset o : {OFFSET_A, OFFSET_B, OFFSET_C, OFFSET_CI, OFFSET_D}) has_block_[o] = false; } bool BlockStream::acquireSync() { if (is_in_sync_) return true; // Try to find the repeating offset sequence if (received_offset_ != OFFSET_INVALID) { int dist = bitcount_ - prevbitcount_; if (dist % 26 == 0 && dist <= 156 && (block_number_for_offset[prevsync_] + dist/26) % 4 == block_number_for_offset[received_offset_]) { is_in_sync_ = true; expected_offset_ = received_offset_; //printf(":sync!\n"); } else { prevbitcount_ = bitcount_; prevsync_ = received_offset_; } } return is_in_sync_; } Group BlockStream::getNextGroup() { num_blocks_received_ = 0; while (num_blocks_received_ == 0 && !isEOF()) { // Compensate for clock slip corrections bitcount_ += 26 - left_to_read_; // Read from radio for (int i=0; i < (is_in_sync_ ? (int)left_to_read_ : 1); i++,bitcount_++) { wideblock_ = (wideblock_ << 1) + getNextBit(); } left_to_read_ = 26; wideblock_ &= kBitmask28; uint32_t block = (wideblock_ >> 1) & kBitmask26; uint16_t syndrome = calcSyndrome(block); received_offset_ = (offset_syndromes.count(syndrome) > 0 ? offset_syndromes.at(syndrome) : OFFSET_INVALID); if (!acquireSync()) continue; block_counter_ ++; uint16_t message = block >> 10; if (expected_offset_ == OFFSET_C && received_offset_ == OFFSET_CI) expected_offset_ = OFFSET_CI; if ( received_offset_ != expected_offset_) { // If message is a correct PI, error was probably in check bits if (expected_offset_ == OFFSET_A && message == pi_ && pi_ != 0) { received_offset_ = OFFSET_A; //printf(":offset 0: ignoring error in check bits\n"); } else if (expected_offset_ == OFFSET_C && message == pi_ && pi_ != 0) { received_offset_ = OFFSET_CI; //printf(":offset 0: ignoring error in check bits\n"); // Detect & correct clock slips (Section C.1.2) } else if (expected_offset_ == OFFSET_A && pi_ != 0 && ((wideblock_ >> 12) & kBitmask16) == pi_) { message = pi_; wideblock_ >>= 1; received_offset_ = OFFSET_A; //printf(":offset 0: clock slip corrected\n"); } else if (expected_offset_ == OFFSET_A && pi_ != 0 && ((wideblock_ >> 10) & kBitmask16) == pi_) { message = pi_; wideblock_ = (wideblock_ << 1) + getNextBit(); received_offset_ = OFFSET_A; left_to_read_ = 25; //printf(":offset 0: clock slip corrected\n"); } else { block = correctBurstErrors(block); if (calcSyndrome(block) == 0x000) { message = block >> 10; received_offset_ = expected_offset_; } } // Still no valid syndrome if (received_offset_ != expected_offset_) uncorrectable(); } // Error-free block received if (received_offset_ == expected_offset_) { group_data_[block_number_for_offset[expected_offset_]] = message; has_block_[expected_offset_] = true; if (expected_offset_ == OFFSET_A) { pi_ = message; } // Complete group received if (has_block_[OFFSET_A] && has_block_[OFFSET_B] && (has_block_[OFFSET_C] || has_block_[OFFSET_CI]) && has_block_[OFFSET_D]) { num_blocks_received_ = 4; } } expected_offset_ = nextOffsetFor(expected_offset_); // End-of-group reset if (expected_offset_ == OFFSET_A) { for (eOffset o : {OFFSET_A, OFFSET_B, OFFSET_C, OFFSET_CI, OFFSET_D}) has_block_[o] = false; } } std::vector<uint16_t> result = group_data_; result.resize(num_blocks_received_); return Group(result); } bool BlockStream::isEOF() const { return is_eof_; } #ifdef DEBUG float BlockStream::getT() const { return subcarrier_.getT(); } #endif } // namespace redsea <commit_msg>only accept valid PI<commit_after>#include "block_sync.h" namespace redsea { namespace { const unsigned kBitmask16 = 0x000FFFF; const unsigned kBitmask26 = 0x3FFFFFF; const unsigned kBitmask28 = 0xFFFFFFF; const unsigned kMaxErrorLength = 5; const std::vector<uint16_t> offset_words = {0x0FC, 0x198, 0x168, 0x350, 0x1B4}; const std::map<uint16_t,eOffset> offset_syndromes = {{0x3D8,OFFSET_A}, {0x3D4,OFFSET_B}, {0x25C,OFFSET_C}, {0x3CC,OFFSET_CI}, {0x258,OFFSET_D}}; const std::vector<uint16_t> block_number_for_offset = {0, 1, 2, 2, 3}; // Section B.1.1: '-- calculated by the modulo-two addition of all the rows of // the -- matrix for which the corresponding coefficient in the -- vector is 1.' uint32_t matrixMultiply(uint32_t vec, const std::vector<uint32_t>& matrix) { uint32_t result = 0; for (int k=0; k<(int)matrix.size(); k++) if ((vec >> k) & 0x01) result ^= matrix[matrix.size() - 1 - k]; return result; } // Section B.2.1: 'The calculation of the syndromes -- can easily be done by // multiplying each word with the parity matrix H.' uint32_t calcSyndrome(uint32_t vec) { static const std::vector<uint32_t> parity_check_matrix({ 0x200, 0x100, 0x080, 0x040, 0x020, 0x010, 0x008, 0x004, 0x002, 0x001, 0x2dc, 0x16e, 0x0b7, 0x287, 0x39f, 0x313, 0x355, 0x376, 0x1bb, 0x201, 0x3dc, 0x1ee, 0x0f7, 0x2a7, 0x38f, 0x31b }); return matrixMultiply(vec, parity_check_matrix); } eOffset nextOffsetFor(eOffset o) { static const std::map<eOffset,eOffset> next_offset({ {OFFSET_A,OFFSET_B}, {OFFSET_B,OFFSET_C}, {OFFSET_C,OFFSET_D}, {OFFSET_CI,OFFSET_D}, {OFFSET_D,OFFSET_A} }); return next_offset.at(o); } // Precompute mapping of syndromes to error vectors std::map<uint16_t,uint32_t> makeErrorLookupTable() { std::map<uint16_t,uint32_t> result; for (uint32_t e=1; e < (1<<kMaxErrorLength); e++) { for (unsigned shift=0; shift < 26; shift++) { uint32_t errvec = ((e << shift) & kBitmask26); uint32_t sy = calcSyndrome(errvec); result[sy] = errvec; } } return result; } } // namespace BlockStream::BlockStream(eInputType input_type) : bitcount_(0), prevbitcount_(0), left_to_read_(0), wideblock_(0), prevsync_(0), block_counter_(0), expected_offset_(OFFSET_A), received_offset_(OFFSET_INVALID), pi_(0), is_in_sync_(false), group_data_(4), has_block_(5), block_has_errors_(50), subcarrier_(), ascii_bits_(), error_lookup_(makeErrorLookupTable()), num_blocks_received_(0), input_type_(input_type), is_eof_(false) { } int BlockStream::getNextBit() { int result = 0; if (input_type_ == INPUT_MPX) { result = subcarrier_.getNextBit(); is_eof_ = subcarrier_.isEOF(); } else if (input_type_ == INPUT_ASCIIBITS) { result = ascii_bits_.getNextBit(); is_eof_ = ascii_bits_.isEOF(); } return result; } // Section B.2.2 uint32_t BlockStream::correctBurstErrors(uint32_t block) const { uint16_t synd_reg = calcSyndrome(block ^ offset_words[expected_offset_]); uint32_t corrected_block = block; if (error_lookup_.find(synd_reg) != error_lookup_.end()) { corrected_block = (block ^ offset_words[expected_offset_]) ^ (error_lookup_.at(synd_reg)); } return corrected_block; } // When a block can't be decoded, save the beginning of the group if possible void BlockStream::uncorrectable() { num_blocks_received_ = 0; for (eOffset o : {OFFSET_A, OFFSET_B, OFFSET_C, OFFSET_CI}) { if (has_block_[o]) { num_blocks_received_ = block_number_for_offset[o] + 1; } else { break; } } block_has_errors_[block_counter_ % block_has_errors_.size()] = true; unsigned num_erroneous_blocks = 0; for (bool e : block_has_errors_) { if (e) num_erroneous_blocks ++; } // Sync is lost when >45 out of last 50 blocks are erroneous (Section C.1.2) if (is_in_sync_ && num_erroneous_blocks > 45) { is_in_sync_ = false; for (unsigned i=0; i<block_has_errors_.size(); i++) block_has_errors_[i] = false; pi_ = 0x0000; } for (eOffset o : {OFFSET_A, OFFSET_B, OFFSET_C, OFFSET_CI, OFFSET_D}) has_block_[o] = false; } bool BlockStream::acquireSync() { if (is_in_sync_) return true; // Try to find the repeating offset sequence if (received_offset_ != OFFSET_INVALID) { int dist = bitcount_ - prevbitcount_; if (dist % 26 == 0 && dist <= 156 && (block_number_for_offset[prevsync_] + dist/26) % 4 == block_number_for_offset[received_offset_]) { is_in_sync_ = true; expected_offset_ = received_offset_; //printf(":sync!\n"); } else { prevbitcount_ = bitcount_; prevsync_ = received_offset_; } } return is_in_sync_; } Group BlockStream::getNextGroup() { num_blocks_received_ = 0; while (num_blocks_received_ == 0 && !isEOF()) { // Compensate for clock slip corrections bitcount_ += 26 - left_to_read_; // Read from radio for (int i=0; i < (is_in_sync_ ? (int)left_to_read_ : 1); i++,bitcount_++) { wideblock_ = (wideblock_ << 1) + getNextBit(); } left_to_read_ = 26; wideblock_ &= kBitmask28; uint32_t block = (wideblock_ >> 1) & kBitmask26; uint16_t syndrome = calcSyndrome(block); received_offset_ = (offset_syndromes.count(syndrome) > 0 ? offset_syndromes.at(syndrome) : OFFSET_INVALID); if (!acquireSync()) continue; block_counter_ ++; uint16_t message = block >> 10; bool was_valid_word = true; if (expected_offset_ == OFFSET_C && received_offset_ == OFFSET_CI) expected_offset_ = OFFSET_CI; if ( received_offset_ != expected_offset_) { was_valid_word = false; // If message is a correct PI, error was probably in check bits if (expected_offset_ == OFFSET_A && message == pi_ && pi_ != 0) { received_offset_ = OFFSET_A; //printf(":offset 0: ignoring error in check bits\n"); } else if (expected_offset_ == OFFSET_C && message == pi_ && pi_ != 0) { received_offset_ = OFFSET_CI; //printf(":offset 0: ignoring error in check bits\n"); // Detect & correct clock slips (Section C.1.2) } else if (expected_offset_ == OFFSET_A && pi_ != 0 && ((wideblock_ >> 12) & kBitmask16) == pi_) { message = pi_; wideblock_ >>= 1; received_offset_ = OFFSET_A; //printf(":offset 0: clock slip corrected\n"); } else if (expected_offset_ == OFFSET_A && pi_ != 0 && ((wideblock_ >> 10) & kBitmask16) == pi_) { message = pi_; wideblock_ = (wideblock_ << 1) + getNextBit(); received_offset_ = OFFSET_A; left_to_read_ = 25; //printf(":offset 0: clock slip corrected\n"); } else { block = correctBurstErrors(block); if (calcSyndrome(block) == 0x000) { message = block >> 10; received_offset_ = expected_offset_; } } // Still no valid syndrome if (received_offset_ != expected_offset_) uncorrectable(); } // Error-free block received if (received_offset_ == expected_offset_) { group_data_[block_number_for_offset[expected_offset_]] = message; has_block_[expected_offset_] = true; if (expected_offset_ == OFFSET_A && was_valid_word) { pi_ = message; } // Complete group received if (has_block_[OFFSET_A] && has_block_[OFFSET_B] && (has_block_[OFFSET_C] || has_block_[OFFSET_CI]) && has_block_[OFFSET_D]) { num_blocks_received_ = 4; } } expected_offset_ = nextOffsetFor(expected_offset_); // End-of-group reset if (expected_offset_ == OFFSET_A) { for (eOffset o : {OFFSET_A, OFFSET_B, OFFSET_C, OFFSET_CI, OFFSET_D}) has_block_[o] = false; } } std::vector<uint16_t> result = group_data_; result.resize(num_blocks_received_); return Group(result); } bool BlockStream::isEOF() const { return is_eof_; } #ifdef DEBUG float BlockStream::getT() const { return subcarrier_.getT(); } #endif } // namespace redsea <|endoftext|>
<commit_before>/* * Copyright 2008 by Tommi Rantala <[email protected]> * * 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. */ /* * Implementation of the burstsort algorithm by Sinha, Zobel et al. * * @article{1041517, * author = {Ranjan Sinha and Justin Zobel}, * title = {Cache-conscious sorting of large sets of strings with dynamic tries}, * journal = {J. Exp. Algorithmics}, * volume = {9}, * year = {2004}, * issn = {1084-6654}, * pages = {1.5}, * doi = {http://doi.acm.org/10.1145/1005813.1041517}, * publisher = {ACM}, * address = {New York, NY, USA}, * } */ #include "util/get_char.h" #include <vector> #include <iostream> #include <bitset> #include "vector_bagwell.h" #include "vector_brodnik.h" #include "vector_block.h" #include <boost/array.hpp> using boost::array; // Unfortunately std::numeric_limits<T>::max() cannot be used as constant // values in template parameters. template <typename T> struct max {}; template <> struct max<unsigned char> { enum { value = 0x100 }; }; template <> struct max<uint16_t> { enum { value = 0x10000 }; }; template <typename CharT> struct TrieNode { // One subtree per alphabet. Points to either a 'TrieNode' or a // 'Bucket' node. Use the value from is_trie to know which one. array<void*, max<CharT>::value> buckets; // is_trie[i] equals true if buckets[i] points to a TrieNode // is_trie[i] equals false if buckets[i] points to a Bucket std::bitset<max<CharT>::value> is_trie; TrieNode() { buckets.assign(0); } }; // The burst algorithm as described by Sinha, Zobel et al. template <typename CharT> struct BurstSimple { template <typename BucketT> TrieNode<CharT>* operator()(const BucketT& bucket, size_t depth) const { TrieNode<CharT>* new_node = new TrieNode<CharT>; const unsigned bucket_size = bucket.size(); // Use a small cache to reduce memory stalls. Also cache the // string pointers, in case the indexing operation of the // container is expensive. unsigned i=0; for (; i < bucket_size-bucket_size%64; i+=64) { array<CharT, 64> cache; array<unsigned char*, 64> strings; for (unsigned j=0; j < 64; ++j) { strings[j] = bucket[i+j]; cache[j] = get_char<CharT>(strings[j], depth); } for (unsigned j=0; j < 64; ++j) { const CharT ch = cache[j]; BucketT* sub_bucket = static_cast<BucketT*>( new_node->buckets[ch]); if (not sub_bucket) { new_node->buckets[ch] = sub_bucket = new BucketT; } sub_bucket->push_back(strings[j]); } } for (; i < bucket_size; ++i) { unsigned char* ptr = bucket[i]; const CharT ch = get_char<CharT>(ptr, depth); BucketT* sub_bucket = static_cast<BucketT*>( new_node->buckets[ch]); if (not sub_bucket) { new_node->buckets[ch] = sub_bucket = new BucketT; } sub_bucket->push_back(ptr); } return new_node; } }; // Another burst variant: After bursting the bucket, immediately burst large // sub buckets in a recursive fashion. template <typename CharT> struct BurstRecursive { template <typename BucketT> TrieNode<CharT>* operator()(const BucketT& bucket, size_t depth) const { TrieNode<CharT>* new_node = BurstSimple<CharT>()(bucket, depth); const size_t threshold = std::max( //size_t(100), size_t(0.4f*bucket.size())); size_t(100), bucket.size()/2); for (unsigned i=0; i < max<CharT>::value; ++i) { assert(new_node->is_trie[i] == false); BucketT* sub_bucket = static_cast<BucketT*>( new_node->buckets[i]); if (not sub_bucket) continue; if (not is_end(i) and sub_bucket->size() > threshold) { new_node->buckets[i] = BurstRecursive<CharT>()(*sub_bucket, depth+sizeof(CharT)); delete sub_bucket; new_node->is_trie[i] = true; } } return new_node; } }; template <unsigned Threshold, typename BucketT, typename BurstImpl, typename CharT> static inline void insert(TrieNode<CharT>* root, unsigned char** strings, size_t n) { for (size_t i=0; i < n; ++i) { unsigned char* str = strings[i]; size_t depth = 0; CharT c = get_char<CharT>(str, 0); TrieNode<CharT>* node = root; while (node->is_trie[c]) { assert(not is_end(c)); node = static_cast<TrieNode<CharT>*>(node->buckets[c]); depth += sizeof(CharT); c = get_char<CharT>(str, depth); } BucketT* bucket = static_cast<BucketT*>(node->buckets[c]); if (not bucket) { node->buckets[c] = bucket = new BucketT; } bucket->push_back(str); if (is_end(c)) continue; if (bucket->size() > Threshold) { node->buckets[c] = BurstImpl()(*bucket, depth+sizeof(CharT)); node->is_trie[c] = true; delete bucket; } } } // Use a wrapper to std::copy(). I haven't implemented iterators for some of my // containers, instead they have optimized copy(bucket, dst). static inline void copy(const std::vector<unsigned char*>& bucket, unsigned char** dst) { std::copy(bucket.begin(), bucket.end(), dst); } // Traverses the trie and copies the strings back to the original string array. // Nodes and buckets are deleted from memory during the traversal. The root // node given to this function will also be deleted. template <typename BucketT, typename SmallSort, typename CharT> static unsigned char** traverse(TrieNode<CharT>* node, unsigned char** dst, size_t depth, SmallSort small_sort) { for (unsigned i=0; i < max<CharT>::value; ++i) { if (node->is_trie[i]) { dst = traverse<BucketT>( static_cast<TrieNode<CharT>*>(node->buckets[i]), dst, depth+sizeof(CharT), small_sort); } else { BucketT* bucket = static_cast<BucketT*>(node->buckets[i]); if (not bucket) continue; size_t bsize = bucket->size(); copy(*bucket, dst); if (not is_end(i)) small_sort(dst, bsize, depth); dst += bsize; delete bucket; } } delete node; return dst; } //#define SmallSort mkqsort #define SmallSort msd_CE2 void msd_CE2(unsigned char**, size_t, size_t); void burstsort_vector(unsigned char** strings, size_t n) { typedef unsigned char CharT; typedef std::vector<unsigned char*> BucketT; typedef BurstSimple<CharT> BurstImpl; //typedef BurstRecursive<CharT> BurstImpl; TrieNode<CharT>* root = new TrieNode<CharT>; insert<8000, BucketT, BurstImpl>(root, strings, n); traverse<BucketT>(root, strings, 0, SmallSort); } void burstsort_brodnik(unsigned char** strings, size_t n) { typedef unsigned char CharT; typedef vector_brodnik<unsigned char*> BucketT; typedef BurstSimple<CharT> BurstImpl; //typedef BurstRecursive<CharT> BurstImpl; TrieNode<CharT>* root = new TrieNode<CharT>; insert<16000, BucketT, BurstImpl>(root, strings, n); traverse<BucketT>(root, strings, 0, SmallSort); } void burstsort_bagwell(unsigned char** strings, size_t n) { typedef unsigned char CharT; typedef vector_bagwell<unsigned char*> BucketT; typedef BurstSimple<CharT> BurstImpl; //typedef BurstRecursive<CharT> BurstImpl; TrieNode<CharT>* root = new TrieNode<CharT>; insert<16000, BucketT, BurstImpl>(root, strings, n); traverse<BucketT>(root, strings, 0, SmallSort); } void burstsort_vector_block(unsigned char** strings, size_t n) { typedef unsigned char CharT; typedef vector_block<unsigned char*> BucketT; typedef BurstSimple<CharT> BurstImpl; //typedef BurstRecursive<CharT> BurstImpl; TrieNode<CharT>* root = new TrieNode<CharT>; insert<16000, BucketT, BurstImpl>(root, strings, n); traverse<BucketT>(root, strings, 0, SmallSort); } void burstsort_superalphabet_vector(unsigned char** strings, size_t n) { typedef uint16_t CharT; typedef std::vector<unsigned char*> BucketT; typedef BurstSimple<CharT> BurstImpl; //typedef BurstRecursive<CharT> BurstImpl; TrieNode<CharT>* root = new TrieNode<CharT>; insert<32000, BucketT, BurstImpl>(root, strings, n); traverse<BucketT>(root, strings, 0, SmallSort); } void burstsort_superalphabet_brodnik(unsigned char** strings, size_t n) { typedef uint16_t CharT; typedef vector_brodnik<unsigned char*> BucketT; typedef BurstSimple<CharT> BurstImpl; //typedef BurstRecursive<CharT> BurstImpl; TrieNode<CharT>* root = new TrieNode<CharT>; insert<32000, BucketT, BurstImpl>(root, strings, n); traverse<BucketT>(root, strings, 0, SmallSort); } void burstsort_superalphabet_bagwell(unsigned char** strings, size_t n) { typedef uint16_t CharT; typedef vector_bagwell<unsigned char*> BucketT; typedef BurstSimple<CharT> BurstImpl; //typedef BurstRecursive<CharT> BurstImpl; TrieNode<CharT>* root = new TrieNode<CharT>; insert<32000, BucketT, BurstImpl>(root, strings, n); traverse<BucketT>(root, strings, 0, SmallSort); } void burstsort_superalphabet_vector_block(unsigned char** strings, size_t n) { typedef uint16_t CharT; typedef vector_block<unsigned char*, 128> BucketT; typedef BurstSimple<CharT> BurstImpl; //typedef BurstRecursive<CharT> BurstImpl; TrieNode<CharT>* root = new TrieNode<CharT>; insert<32000, BucketT, BurstImpl>(root, strings, n); traverse<BucketT>(root, strings, 0, SmallSort); } <commit_msg>use mkqsort() as SmallSort<commit_after>/* * Copyright 2008 by Tommi Rantala <[email protected]> * * 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. */ /* * Implementation of the burstsort algorithm by Sinha, Zobel et al. * * @article{1041517, * author = {Ranjan Sinha and Justin Zobel}, * title = {Cache-conscious sorting of large sets of strings with dynamic tries}, * journal = {J. Exp. Algorithmics}, * volume = {9}, * year = {2004}, * issn = {1084-6654}, * pages = {1.5}, * doi = {http://doi.acm.org/10.1145/1005813.1041517}, * publisher = {ACM}, * address = {New York, NY, USA}, * } */ #include "util/get_char.h" #include <vector> #include <iostream> #include <bitset> #include "vector_bagwell.h" #include "vector_brodnik.h" #include "vector_block.h" #include <boost/array.hpp> using boost::array; // Unfortunately std::numeric_limits<T>::max() cannot be used as constant // values in template parameters. template <typename T> struct max {}; template <> struct max<unsigned char> { enum { value = 0x100 }; }; template <> struct max<uint16_t> { enum { value = 0x10000 }; }; template <typename CharT> struct TrieNode { // One subtree per alphabet. Points to either a 'TrieNode' or a // 'Bucket' node. Use the value from is_trie to know which one. array<void*, max<CharT>::value> buckets; // is_trie[i] equals true if buckets[i] points to a TrieNode // is_trie[i] equals false if buckets[i] points to a Bucket std::bitset<max<CharT>::value> is_trie; TrieNode() { buckets.assign(0); } }; // The burst algorithm as described by Sinha, Zobel et al. template <typename CharT> struct BurstSimple { template <typename BucketT> TrieNode<CharT>* operator()(const BucketT& bucket, size_t depth) const { TrieNode<CharT>* new_node = new TrieNode<CharT>; const unsigned bucket_size = bucket.size(); // Use a small cache to reduce memory stalls. Also cache the // string pointers, in case the indexing operation of the // container is expensive. unsigned i=0; for (; i < bucket_size-bucket_size%64; i+=64) { array<CharT, 64> cache; array<unsigned char*, 64> strings; for (unsigned j=0; j < 64; ++j) { strings[j] = bucket[i+j]; cache[j] = get_char<CharT>(strings[j], depth); } for (unsigned j=0; j < 64; ++j) { const CharT ch = cache[j]; BucketT* sub_bucket = static_cast<BucketT*>( new_node->buckets[ch]); if (not sub_bucket) { new_node->buckets[ch] = sub_bucket = new BucketT; } sub_bucket->push_back(strings[j]); } } for (; i < bucket_size; ++i) { unsigned char* ptr = bucket[i]; const CharT ch = get_char<CharT>(ptr, depth); BucketT* sub_bucket = static_cast<BucketT*>( new_node->buckets[ch]); if (not sub_bucket) { new_node->buckets[ch] = sub_bucket = new BucketT; } sub_bucket->push_back(ptr); } return new_node; } }; // Another burst variant: After bursting the bucket, immediately burst large // sub buckets in a recursive fashion. template <typename CharT> struct BurstRecursive { template <typename BucketT> TrieNode<CharT>* operator()(const BucketT& bucket, size_t depth) const { TrieNode<CharT>* new_node = BurstSimple<CharT>()(bucket, depth); const size_t threshold = std::max( //size_t(100), size_t(0.4f*bucket.size())); size_t(100), bucket.size()/2); for (unsigned i=0; i < max<CharT>::value; ++i) { assert(new_node->is_trie[i] == false); BucketT* sub_bucket = static_cast<BucketT*>( new_node->buckets[i]); if (not sub_bucket) continue; if (not is_end(i) and sub_bucket->size() > threshold) { new_node->buckets[i] = BurstRecursive<CharT>()(*sub_bucket, depth+sizeof(CharT)); delete sub_bucket; new_node->is_trie[i] = true; } } return new_node; } }; template <unsigned Threshold, typename BucketT, typename BurstImpl, typename CharT> static inline void insert(TrieNode<CharT>* root, unsigned char** strings, size_t n) { for (size_t i=0; i < n; ++i) { unsigned char* str = strings[i]; size_t depth = 0; CharT c = get_char<CharT>(str, 0); TrieNode<CharT>* node = root; while (node->is_trie[c]) { assert(not is_end(c)); node = static_cast<TrieNode<CharT>*>(node->buckets[c]); depth += sizeof(CharT); c = get_char<CharT>(str, depth); } BucketT* bucket = static_cast<BucketT*>(node->buckets[c]); if (not bucket) { node->buckets[c] = bucket = new BucketT; } bucket->push_back(str); if (is_end(c)) continue; if (bucket->size() > Threshold) { node->buckets[c] = BurstImpl()(*bucket, depth+sizeof(CharT)); node->is_trie[c] = true; delete bucket; } } } // Use a wrapper to std::copy(). I haven't implemented iterators for some of my // containers, instead they have optimized copy(bucket, dst). static inline void copy(const std::vector<unsigned char*>& bucket, unsigned char** dst) { std::copy(bucket.begin(), bucket.end(), dst); } // Traverses the trie and copies the strings back to the original string array. // Nodes and buckets are deleted from memory during the traversal. The root // node given to this function will also be deleted. template <typename BucketT, typename SmallSort, typename CharT> static unsigned char** traverse(TrieNode<CharT>* node, unsigned char** dst, size_t depth, SmallSort small_sort) { for (unsigned i=0; i < max<CharT>::value; ++i) { if (node->is_trie[i]) { dst = traverse<BucketT>( static_cast<TrieNode<CharT>*>(node->buckets[i]), dst, depth+sizeof(CharT), small_sort); } else { BucketT* bucket = static_cast<BucketT*>(node->buckets[i]); if (not bucket) continue; size_t bsize = bucket->size(); copy(*bucket, dst); if (not is_end(i)) small_sort(dst, bsize, depth); dst += bsize; delete bucket; } } delete node; return dst; } #define SmallSort mkqsort extern "C" void mkqsort(unsigned char**, int, int); //#define SmallSort msd_CE2 //void msd_CE2(unsigned char**, size_t, size_t); void burstsort_vector(unsigned char** strings, size_t n) { typedef unsigned char CharT; typedef std::vector<unsigned char*> BucketT; typedef BurstSimple<CharT> BurstImpl; //typedef BurstRecursive<CharT> BurstImpl; TrieNode<CharT>* root = new TrieNode<CharT>; insert<8000, BucketT, BurstImpl>(root, strings, n); traverse<BucketT>(root, strings, 0, SmallSort); } void burstsort_brodnik(unsigned char** strings, size_t n) { typedef unsigned char CharT; typedef vector_brodnik<unsigned char*> BucketT; typedef BurstSimple<CharT> BurstImpl; //typedef BurstRecursive<CharT> BurstImpl; TrieNode<CharT>* root = new TrieNode<CharT>; insert<16000, BucketT, BurstImpl>(root, strings, n); traverse<BucketT>(root, strings, 0, SmallSort); } void burstsort_bagwell(unsigned char** strings, size_t n) { typedef unsigned char CharT; typedef vector_bagwell<unsigned char*> BucketT; typedef BurstSimple<CharT> BurstImpl; //typedef BurstRecursive<CharT> BurstImpl; TrieNode<CharT>* root = new TrieNode<CharT>; insert<16000, BucketT, BurstImpl>(root, strings, n); traverse<BucketT>(root, strings, 0, SmallSort); } void burstsort_vector_block(unsigned char** strings, size_t n) { typedef unsigned char CharT; typedef vector_block<unsigned char*> BucketT; typedef BurstSimple<CharT> BurstImpl; //typedef BurstRecursive<CharT> BurstImpl; TrieNode<CharT>* root = new TrieNode<CharT>; insert<16000, BucketT, BurstImpl>(root, strings, n); traverse<BucketT>(root, strings, 0, SmallSort); } void burstsort_superalphabet_vector(unsigned char** strings, size_t n) { typedef uint16_t CharT; typedef std::vector<unsigned char*> BucketT; typedef BurstSimple<CharT> BurstImpl; //typedef BurstRecursive<CharT> BurstImpl; TrieNode<CharT>* root = new TrieNode<CharT>; insert<32000, BucketT, BurstImpl>(root, strings, n); traverse<BucketT>(root, strings, 0, SmallSort); } void burstsort_superalphabet_brodnik(unsigned char** strings, size_t n) { typedef uint16_t CharT; typedef vector_brodnik<unsigned char*> BucketT; typedef BurstSimple<CharT> BurstImpl; //typedef BurstRecursive<CharT> BurstImpl; TrieNode<CharT>* root = new TrieNode<CharT>; insert<32000, BucketT, BurstImpl>(root, strings, n); traverse<BucketT>(root, strings, 0, SmallSort); } void burstsort_superalphabet_bagwell(unsigned char** strings, size_t n) { typedef uint16_t CharT; typedef vector_bagwell<unsigned char*> BucketT; typedef BurstSimple<CharT> BurstImpl; //typedef BurstRecursive<CharT> BurstImpl; TrieNode<CharT>* root = new TrieNode<CharT>; insert<32000, BucketT, BurstImpl>(root, strings, n); traverse<BucketT>(root, strings, 0, SmallSort); } void burstsort_superalphabet_vector_block(unsigned char** strings, size_t n) { typedef uint16_t CharT; typedef vector_block<unsigned char*, 128> BucketT; typedef BurstSimple<CharT> BurstImpl; //typedef BurstRecursive<CharT> BurstImpl; TrieNode<CharT>* root = new TrieNode<CharT>; insert<32000, BucketT, BurstImpl>(root, strings, n); traverse<BucketT>(root, strings, 0, SmallSort); } <|endoftext|>
<commit_before>/* * _aaaa, _aa. sa, aaa _aaaa,_ ac .aa. .aa. .aa, _a, sa * .wWV!!!T |Wm; dQ[ $WF _mWT!"?Y ]QE :Q#: ]QW[ :WWk. ]Q[ dW * .jWf :WW: .dQ[ dQ[ .mW( )WE :Q#: .mSQh. :mWQa.]W[ dQ * |QW: :Wm; mQ[ dQ[ ]Qk )Qmi_aQW: <B:$Qc :WBWQ()W[ dQ * |W#: .ww ;WW; dQ[ dQ[ ....... ]Qk )QB?YYW#: jf ]Qp.:mE)Qm]Q[ )W * +WQ; :Wm |Wm; .mQ[ dQ[ :qgggggga ]Qm. ]WE :Q# :=QasuQm;:Wk 3QQW[ )Y * ]Wmi.:Wm +$Q; .mW( dQ[ !"!!"!!^ dQk, ._ ]WE :Q# :3D"!!$Qc.Wk -$WQ[ * "?????? ` "?!=m?! ??' -??????! -?! -?? -?' "?"-?" "??' "? * * Copyright (c) 2004 darkbits Js_./ * Per Larsson a.k.a finalman _RqZ{a<^_aa * Olof Naessn a.k.a jansem/yakslem _asww7!uY`> )\a// * _Qhm`] _f "'c 1!5m * Visit: http://guichan.darkbits.org )Qk<P ` _: :+' .' "{[ * .)j(] .d_/ '-( P . S * License: (BSD) <Td/Z <fP"5(\"??"\a. .L * Redistribution and use in source and _dV>ws?a-?' ._/L #' * binary forms, with or without )4d[#7r, . ' )d`)[ * modification, are permitted provided _Q-5'5W..j/?' -?!\)cam' * that the following conditions are met: j<<WP+k/);. _W=j f * 1. Redistributions of source code must .$%w\/]Q . ."' . mj$ * retain the above copyright notice, ]E.pYY(Q]>. a J@\ * this list of conditions and the j(]1u<sE"L,. . ./^ ]{a * following disclaimer. 4'_uomm\. )L);-4 (3= * 2. Redistributions in binary form must )_]X{Z('a_"a7'<a"a, ]"[ * reproduce the above copyright notice, #}<]m7`Za??4,P-"'7. ).m * this list of conditions and the ]d2e)Q(<Q( ?94 b- LQ/ * following disclaimer in the <B!</]C)d_, '(<' .f. =C+m * documentation and/or other materials .Z!=J ]e []('-4f _ ) -.)m]' * provided with the distribution. .w[5]' _[ /.)_-"+? _/ <W" * 3. Neither the name of darkbits nor the :$we` _! + _/ . j? * names of its contributors may be used =3)= _f (_yQmWW$#( " * to endorse or promote products derived - W, sQQQQmZQ#Wwa].. * from this software without specific (js, \[QQW$QWW#?!V"". * prior written permission. ]y:.<\.. . * -]n w/ ' [. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT )/ )/ ! * HOLDERS AND CONTRIBUTORS "AS IS" AND ANY < (; sac , ' * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, ]^ .- % * BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF c < r * MERCHANTABILITY AND FITNESS FOR A PARTICULAR aga< <La * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE 5% )P'-3L * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR _bQf` y`..)a * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, ,J?4P'.P"_(\?d'., * EXEMPLARY, OR CONSEQUENTIAL DAMAGES _Pa,)!f/<[]/ ?" * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT _2-..:. .r+_,.. . * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ?a.<%"' " -'.a_ _, * 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. */ /* * For comments regarding functions please see the header file. */ #include "guichan/widgets/button.hpp" #include "guichan/mouseinput.hpp" #include <iostream> namespace gcn { Button::Button() { addMouseListener(this); addKeyListener(this); adjustSize(); } // end Button Button::Button(const std::string& text) { mText = text; setFocusable(true); adjustSize(); x = 0; y = 0; mMove = false; addMouseListener(this); addKeyListener(this); } // end Button void Button::setText(const std::string& text) { mText = text; } // end setText void Button::draw(Graphics* graphics) { graphics->setFont(getFont()); if (hasFocus()) { Color c = getBackgroundColor() + 0x202020; graphics->setColor(c); graphics->fillRectangle(Rectangle(1, 1, getDimension().width-1, getDimension().height-1)); graphics->setColor(c+0x303030); graphics->drawLine(0, 0, getDimension().width-1, 0); graphics->drawLine(0, 1, 0, getDimension().height-1); graphics->setColor(c*0.3); graphics->drawLine(getDimension().width-1, 1, getDimension().width-1, getDimension().height-1); graphics->drawLine(1, getDimension().height-1, getDimension().width-1, getDimension().height-1); } else if (hasMouse()) { Color c = getBackgroundColor() + 0xff2090; graphics->setColor(c); graphics->fillRectangle(Rectangle(1, 1, getDimension().width-1, getDimension().height-1)); graphics->setColor(c+0x303030); graphics->drawLine(0, 0, getDimension().width-1, 0); graphics->drawLine(0, 1, 0, getDimension().height-1); graphics->setColor(c*0.3); graphics->drawLine(getDimension().width-1, 1, getDimension().width-1, getDimension().height-1); graphics->drawLine(1, getDimension().height-1, getDimension().width-1, getDimension().height-1); } else { graphics->setColor(getBackgroundColor()); graphics->fillRectangle(Rectangle(1, 1, getDimension().width-1, getDimension().height-1)); graphics->setColor(getBackgroundColor()+0x303030); graphics->drawLine(0, 0, getDimension().width-1, 0); graphics->drawLine(0, 1, 0, getDimension().height-1); graphics->setColor(getBackgroundColor()*0.3); graphics->drawLine(getDimension().width-1, 1, getDimension().width-1, getDimension().height-1); graphics->drawLine(1, getDimension().height-1, getDimension().width-1, getDimension().height-1); } graphics->drawText(mText, 4, 4); } // end draw void Button::adjustSize() { setWidth(getFont()->getWidth(mText) + 8); setHeight(getFont()->getHeight() + 8); } // end adjustSize void Button::mouseClick(int x, int y, int button, int count) { generateAction(); if( button == MouseInput::LEFT && count == 2) { mText = "Per died"; } else if( button == MouseInput::WHEEL_UP ) { mText = "Kill Per"; } adjustSize(); } void Button::mousePress(int x, int y, int button) { mMove = true; this->x = x; this->y = y; } void Button::mouseRelease(int x, int y, int button) { mMove = false; this->x = 0; this->y = 0; } void Button::mouseMotion(int x, int y) { int moveX = x - this->x; int moveY = y - this->y; if (mMove) { setPosition(getDimension().x + moveX, getDimension().y + moveY); } } void Button::lostFocus() { mMove = false; this->x = 0; this->y = 0; } void Button::keyPress(const Key& key) { if (key.getValue() == Key::ENTER) { generateAction(); mText = "Pushed"; adjustSize(); } } } // end gcn <commit_msg>Button now behaves as an button should.<commit_after>/* * _aaaa, _aa. sa, aaa _aaaa,_ ac .aa. .aa. .aa, _a, sa * .wWV!!!T |Wm; dQ[ $WF _mWT!"?Y ]QE :Q#: ]QW[ :WWk. ]Q[ dW * .jWf :WW: .dQ[ dQ[ .mW( )WE :Q#: .mSQh. :mWQa.]W[ dQ * |QW: :Wm; mQ[ dQ[ ]Qk )Qmi_aQW: <B:$Qc :WBWQ()W[ dQ * |W#: .ww ;WW; dQ[ dQ[ ....... ]Qk )QB?YYW#: jf ]Qp.:mE)Qm]Q[ )W * +WQ; :Wm |Wm; .mQ[ dQ[ :qgggggga ]Qm. ]WE :Q# :=QasuQm;:Wk 3QQW[ )Y * ]Wmi.:Wm +$Q; .mW( dQ[ !"!!"!!^ dQk, ._ ]WE :Q# :3D"!!$Qc.Wk -$WQ[ * "?????? ` "?!=m?! ??' -??????! -?! -?? -?' "?"-?" "??' "? * * Copyright (c) 2004 darkbits Js_./ * Per Larsson a.k.a finalman _RqZ{a<^_aa * Olof Naessn a.k.a jansem/yakslem _asww7!uY`> )\a// * _Qhm`] _f "'c 1!5m * Visit: http://guichan.darkbits.org )Qk<P ` _: :+' .' "{[ * .)j(] .d_/ '-( P . S * License: (BSD) <Td/Z <fP"5(\"??"\a. .L * Redistribution and use in source and _dV>ws?a-?' ._/L #' * binary forms, with or without )4d[#7r, . ' )d`)[ * modification, are permitted provided _Q-5'5W..j/?' -?!\)cam' * that the following conditions are met: j<<WP+k/);. _W=j f * 1. Redistributions of source code must .$%w\/]Q . ."' . mj$ * retain the above copyright notice, ]E.pYY(Q]>. a J@\ * this list of conditions and the j(]1u<sE"L,. . ./^ ]{a * following disclaimer. 4'_uomm\. )L);-4 (3= * 2. Redistributions in binary form must )_]X{Z('a_"a7'<a"a, ]"[ * reproduce the above copyright notice, #}<]m7`Za??4,P-"'7. ).m * this list of conditions and the ]d2e)Q(<Q( ?94 b- LQ/ * following disclaimer in the <B!</]C)d_, '(<' .f. =C+m * documentation and/or other materials .Z!=J ]e []('-4f _ ) -.)m]' * provided with the distribution. .w[5]' _[ /.)_-"+? _/ <W" * 3. Neither the name of darkbits nor the :$we` _! + _/ . j? * names of its contributors may be used =3)= _f (_yQmWW$#( " * to endorse or promote products derived - W, sQQQQmZQ#Wwa].. * from this software without specific (js, \[QQW$QWW#?!V"". * prior written permission. ]y:.<\.. . * -]n w/ ' [. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT )/ )/ ! * HOLDERS AND CONTRIBUTORS "AS IS" AND ANY < (; sac , ' * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, ]^ .- % * BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF c < r * MERCHANTABILITY AND FITNESS FOR A PARTICULAR aga< <La * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE 5% )P'-3L * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR _bQf` y`..)a * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, ,J?4P'.P"_(\?d'., * EXEMPLARY, OR CONSEQUENTIAL DAMAGES _Pa,)!f/<[]/ ?" * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT _2-..:. .r+_,.. . * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ?a.<%"' " -'.a_ _, * 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. */ /* * For comments regarding functions please see the header file. */ #include "guichan/widgets/button.hpp" #include "guichan/mouseinput.hpp" #include <iostream> namespace gcn { Button::Button() { addMouseListener(this); addKeyListener(this); adjustSize(); } // end Button Button::Button(const std::string& text) { mText = text; setFocusable(true); adjustSize(); mMouseDown = false; mKeyDown = false; addMouseListener(this); addKeyListener(this); } // end Button void Button::setText(const std::string& text) { mText = text; } // end setText void Button::draw(Graphics* graphics) { graphics->setFont(getFont()); Color faceColor = getBackgroundColor(); Color highlightColor, shadowColor; if ((hasMouse() && mMouseDown) || mKeyDown) { faceColor = getBackgroundColor() - 0x303030; highlightColor = faceColor - 0x303030; shadowColor = faceColor + 0x303030; } else { highlightColor = faceColor + 0x303030; shadowColor = faceColor - 0x303030; } graphics->setColor(faceColor); graphics->fillRectangle(Rectangle(1, 1, getDimension().width-1, getDimension().height-1)); graphics->setColor(highlightColor); graphics->drawLine(0, 0, getDimension().width-1, 0); graphics->drawLine(0, 1, 0, getDimension().height-1); graphics->setColor(shadowColor); graphics->drawLine(getDimension().width-1, 1, getDimension().width-1, getDimension().height-1); graphics->drawLine(1, getDimension().height-1, getDimension().width-1, getDimension().height-1); if ((hasMouse() && mMouseDown) || mKeyDown) { graphics->drawText(mText, 5, 5); } else { graphics->drawText(mText, 4, 4); if (hasFocus()) { graphics->setColor(getForegroundColor()); graphics->drawRectangle(Rectangle(2, 2, getDimension().width - 4, getDimension().height - 4)); } } } // end draw void Button::adjustSize() { setWidth(getFont()->getWidth(mText) + 8); setHeight(getFont()->getHeight() + 8); } // end adjustSize void Button::mouseClick(int x, int y, int button, int count) { if (button == MouseInput::LEFT) { generateAction(); } } // end mouseClick void Button::mousePress(int x, int y, int button) { if (button == MouseInput::LEFT) { mMouseDown = true; } } // end mousePress void Button::mouseRelease(int x, int y, int button) { if (button == MouseInput::LEFT) { mMouseDown = false; } } // end mouseRelease void Button::keyPress(const Key& key) { if (key.getValue() == Key::ENTER || key.getValue() == Key::SPACE) { mKeyDown = true; } } // end keyPress void Button::keyRelease(const Key& key) { if ((key.getValue() == Key::ENTER || key.getValue() == Key::SPACE) && mKeyDown) { mKeyDown = false; generateAction(); } } // end keyRelease void Button::lostFocus() { mMouseDown = false; mKeyDown = false; } // end lostFocus } // end gcn <|endoftext|>
<commit_before> #include "mesh_exporter.h" #include "material_exporter.h" #include "logger.h" #include <iostream> #include <sstream> #include <iomanip> #include <algorithm> #include <assimp/../../code/BoostWorkaround/boost/lexical_cast.hpp> namespace { void ExportScene(const char*, Assimp::IOSystem*, const aiScene*, const Assimp::ExportProperties*); } Assimp::Exporter::ExportFormatEntry Assimp2XML3D_desc = Assimp::Exporter::ExportFormatEntry( "xml", "XML representation of the scene, compatible for use with XML3D as an external asset.", "xml", ExportScene, 0u); namespace { void ExportScene(const char* file, Assimp::IOSystem* io, const aiScene* scene, const Assimp::ExportProperties*) { XML3DExporter exp(scene, file); exp.Export(); exp.writeFile(); } } XML3DExporter::XML3DExporter(const aiScene* ai, const char* file) { aiCopyScene(ai, &scene); filename = file; } XML3DExporter::~XML3DExporter() { doc.Clear(); aiFreeScene(scene); } void XML3DExporter::Export() { doc.InsertFirstChild(doc.NewDeclaration()); tinyxml2::XMLElement* xml3d = doc.NewElement("xml3d"); tinyxml2::XMLElement* defs = doc.NewElement("defs"); tinyxml2::XMLElement* asset = doc.NewElement("asset"); xml3d->InsertFirstChild(defs); xml3d->LinkEndChild(asset); doc.LinkEndChild(xml3d); std::string id(filename); id = id.substr(0, id.find_first_of('.')); asset->SetAttribute("id", id.c_str()); removeDummyMaterial(scene); if (scene->HasMeshes()) { for (unsigned int i = 0; i < scene->mNumMeshes; i++) { XML3DMeshExporter mexp(this, scene->mMeshes[i]); tinyxml2::XMLElement* data = mexp.getAssetData(); asset->InsertFirstChild(data); } } if (scene->HasMaterials()) { for (unsigned int i = 0; i < scene->mNumMaterials; i++) { XML3DMaterialExporter matExp(this, scene->mMaterials[i]); tinyxml2::XMLElement* material = matExp.getMaterial(); defs->LinkEndChild(material); mNumberOfMaterialsExported++; } } // Flatten scene hierarchy into a list of assetmeshes Export(asset, scene->mRootNode, aiMatrix4x4()); Logger::Info("Processed " + boost::lexical_cast<std::string>(mNumberOfMeshesExported) + " meshes and " + boost::lexical_cast<std::string>(mNumberOfMaterialsExported) + " materials."); } // Assimp will always generate a material even if it was instructed to ignore materials during the import process. // To prevent this material from being exported when the --no-material flag was set we implicitly remove it from the scene // by setting the material count to 0. void XML3DExporter::removeDummyMaterial(aiScene* scene) { if (scene->mNumMaterials == 1) { aiMaterial* mat = scene->mMaterials[0]; aiString name; mat->Get(AI_MATKEY_NAME, name); if (!strcmp(name.C_Str(), "Dummy_MaterialsRemoved")) { scene->mNumMaterials = 0; //Will cause HasMaterials to return false from now on } } } void XML3DExporter::Export(tinyxml2::XMLElement* parent, aiNode* an, const aiMatrix4x4& parentTransform) { // Flatten all non-mesh nodes while gathering the transformations aiMatrix4x4 t(an->mTransformation); t = parentTransform * t; for (unsigned int i = 0; i < an->mNumMeshes; i++) { XML3DMeshExporter mexp(this, scene->mMeshes[an->mMeshes[i]]); tinyxml2::XMLElement* mesh = mexp.getAssetMesh(&t); parent->LinkEndChild(mesh); mNumberOfMeshesExported++; } for (unsigned int i = 0; i < an->mNumChildren; i++) { Export(parent, an->mChildren[i], t); } } void XML3DExporter::writeFile() { doc.SaveFile(filename); } void XML3DExporter::stringToHTMLId(aiString& ai) { // Ensure the name is not empty and is safe to use as an HTML5 id string std::string str(ai.C_Str()); if (!(str.length() > 0)) { str = "_Generated_Name_" + boost::lexical_cast<std::string>(mChangedNamesCounter++); } std::replace(str.begin(), str.end(), ' ', '_'); if (usedNames.count(str) > 0) { str += "_" + boost::lexical_cast<std::string>(mChangedNamesCounter++); Logger::Warn("Renamed '" + str.substr(0, str.find_last_of("_")) + "' to '" + str + "' to avoid duplicate IDs"); } usedNames.emplace(str, 'x'); ai.Set(str); } <commit_msg>Add assetdata elements in ascending order to match assetmeshes<commit_after> #include "mesh_exporter.h" #include "material_exporter.h" #include "logger.h" #include <iostream> #include <sstream> #include <iomanip> #include <algorithm> #include <assimp/../../code/BoostWorkaround/boost/lexical_cast.hpp> namespace { void ExportScene(const char*, Assimp::IOSystem*, const aiScene*, const Assimp::ExportProperties*); } Assimp::Exporter::ExportFormatEntry Assimp2XML3D_desc = Assimp::Exporter::ExportFormatEntry( "xml", "XML representation of the scene, compatible for use with XML3D as an external asset.", "xml", ExportScene, 0u); namespace { void ExportScene(const char* file, Assimp::IOSystem* io, const aiScene* scene, const Assimp::ExportProperties*) { XML3DExporter exp(scene, file); exp.Export(); exp.writeFile(); } } XML3DExporter::XML3DExporter(const aiScene* ai, const char* file) { aiCopyScene(ai, &scene); filename = file; } XML3DExporter::~XML3DExporter() { doc.Clear(); aiFreeScene(scene); } void XML3DExporter::Export() { doc.InsertFirstChild(doc.NewDeclaration()); tinyxml2::XMLElement* xml3d = doc.NewElement("xml3d"); tinyxml2::XMLElement* defs = doc.NewElement("defs"); tinyxml2::XMLElement* asset = doc.NewElement("asset"); xml3d->InsertFirstChild(defs); xml3d->LinkEndChild(asset); doc.LinkEndChild(xml3d); std::string id(filename); id = id.substr(0, id.find_first_of('.')); asset->SetAttribute("id", id.c_str()); removeDummyMaterial(scene); if (scene->HasMeshes()) { for (unsigned int i = 0; i < scene->mNumMeshes; i++) { XML3DMeshExporter mexp(this, scene->mMeshes[i]); tinyxml2::XMLElement* data = mexp.getAssetData(); asset->LinkEndChild(data); } } if (scene->HasMaterials()) { for (unsigned int i = 0; i < scene->mNumMaterials; i++) { XML3DMaterialExporter matExp(this, scene->mMaterials[i]); tinyxml2::XMLElement* material = matExp.getMaterial(); defs->LinkEndChild(material); mNumberOfMaterialsExported++; } } // Flatten scene hierarchy into a list of assetmeshes Export(asset, scene->mRootNode, aiMatrix4x4()); Logger::Info("Processed " + boost::lexical_cast<std::string>(mNumberOfMeshesExported) + " meshes and " + boost::lexical_cast<std::string>(mNumberOfMaterialsExported) + " materials."); } // Assimp will always generate a material even if it was instructed to ignore materials during the import process. // To prevent this material from being exported when the --no-material flag was set we implicitly remove it from the scene // by setting the material count to 0. void XML3DExporter::removeDummyMaterial(aiScene* scene) { if (scene->mNumMaterials == 1) { aiMaterial* mat = scene->mMaterials[0]; aiString name; mat->Get(AI_MATKEY_NAME, name); if (!strcmp(name.C_Str(), "Dummy_MaterialsRemoved")) { scene->mNumMaterials = 0; //Will cause HasMaterials to return false from now on } } } void XML3DExporter::Export(tinyxml2::XMLElement* parent, aiNode* an, const aiMatrix4x4& parentTransform) { // Flatten all non-mesh nodes while gathering the transformations aiMatrix4x4 t(an->mTransformation); t = parentTransform * t; for (unsigned int i = 0; i < an->mNumMeshes; i++) { XML3DMeshExporter mexp(this, scene->mMeshes[an->mMeshes[i]]); tinyxml2::XMLElement* mesh = mexp.getAssetMesh(&t); parent->LinkEndChild(mesh); mNumberOfMeshesExported++; } for (unsigned int i = 0; i < an->mNumChildren; i++) { Export(parent, an->mChildren[i], t); } } void XML3DExporter::writeFile() { doc.SaveFile(filename); } void XML3DExporter::stringToHTMLId(aiString& ai) { // Ensure the name is not empty and is safe to use as an HTML5 id string std::string str(ai.C_Str()); if (!(str.length() > 0)) { str = "_Generated_Name_" + boost::lexical_cast<std::string>(mChangedNamesCounter++); } std::replace(str.begin(), str.end(), ' ', '_'); if (usedNames.count(str) > 0) { str += "_" + boost::lexical_cast<std::string>(mChangedNamesCounter++); Logger::Warn("Renamed '" + str.substr(0, str.find_last_of("_")) + "' to '" + str + "' to avoid duplicate IDs"); } usedNames.emplace(str, 'x'); ai.Set(str); } <|endoftext|>
<commit_before>/*! \file timestamp.cpp \brief Timestamp implementation \author Ivan Shynkarenka \date 26.01.2016 \copyright MIT License */ #include "time/timestamp.h" #include "errors/exceptions.h" #include <iostream> #if defined(__APPLE__) #include <mach/clock.h> #include <mach/mach.h> #include <mach/mach_time.h> #include <math.h> #include <time.h> #elif defined(unix) || defined(__unix) || defined(__unix__) #include <time.h> #elif defined(_WIN32) || defined(_WIN64) #include <windows.h> #endif namespace CppCommon { //! @cond INTERNALS namespace Internals { #if defined(__APPLE__) uint32_t CeilLog2(uint32_t x) { uint32_t result = 0; --x; while (x > 0) { ++result; x >>= 1; } return result; } // This function returns the rational number inside the given interval with // the smallest denominator (and smallest numerator breaks ties; correctness // proof neglects floating-point errors). mach_timebase_info_data_t BestFrac(double a, double b) { if (floor(a) < floor(b)) { mach_timebase_info_data_t rv = { (uint32_t)ceil(a), 1 }; return rv; } double m = floor(a); mach_timebase_info_data_t next = BestFrac(1 / (b - m), 1 / (a - m)); mach_timebase_info_data_t rv = { (int)m * next.numer + next.denom, next.numer }; return rv; } // This is just less than the smallest thing we can multiply numer by without // overflowing. CeilLog2(numer) = 64 - number of leading zeros of numer uint64_t GetExpressibleSpan(uint32_t numer, uint32_t denom) { uint64_t maxDiffWithoutOverflow = ((uint64_t)1 << (64 - CeilLog2(numer))) - 1; return maxDiffWithoutOverflow * numer / denom; } // The clock may run up to 0.1% faster or slower than the "exact" tick count. // However, although the bound on the error is the same as for the pragmatic // answer, the error is actually minimized over the given accuracy bound. uint64_t PrepareTimebaseInfo(mach_timebase_info_data_t& tb) { tb.numer = 0; tb.denom = 1; kern_return_t mtiStatus = mach_timebase_info(&tb); if (mtiStatus != KERN_SUCCESS) return 0; double frac = (double)tb.numer / tb.denom; uint64_t spanTarget = 315360000000000000llu; if (GetExpressibleSpan(tb.numer, tb.denom) >= spanTarget) return 0; for (double errorTarget = 1 / 1024.0; errorTarget > 0.000001;) { mach_timebase_info_data_t newFrac = BestFrac((1 - errorTarget) * frac, (1 + errorTarget) * frac); if (GetExpressibleSpan(newFrac.numer, newFrac.denom) < spanTarget) break; tb = newFrac; errorTarget = fabs((double)tb.numer / tb.denom - frac) / frac / 8; } return mach_absolute_time(); } #endif } // namespace Internals //! @endcond uint64_t Timestamp::utc() { #if defined(__APPLE__) clock_serv_t cclock; mach_timespec_t mts = { 0 }; mach_port_t host_port = mach_host_self(); if (host_port == MACH_PORT_NULL) throwex SystemException("Cannot get the current host port!"); kern_return_t result = host_get_clock_service(host_port, CALENDAR_CLOCK, &cclock); if (result != KERN_SUCCESS) throwex SystemException("Cannot get the current host clock service!"); result = clock_get_time(cclock, &mts); if (result != KERN_SUCCESS) throwex SystemException("Cannot get the current clock time!"); mach_port_t task_port = mach_task_self(); if (task_port == MACH_PORT_NULL) throwex SystemException("Cannot get the current task port!"); result = mach_port_deallocate(task_port, cclock); if (result != KERN_SUCCESS) throwex SystemException("Cannot release the current host clock service!"); uint64_t result1 = ((uint64_t)mts.tv_sec * 1000 * 1000 * 1000) + mts.tv_nsec; std::cerr << "Timestamp: " << result1 << std::endl; return result1; #elif defined(unix) || defined(__unix) || defined(__unix__) struct timespec timestamp; if (clock_gettime(CLOCK_REALTIME, &timestamp) != 0) throwex SystemException("Cannot get value of CLOCK_REALTIME timer!"); return (timestamp.tv_sec * 1000 * 1000 * 1000) + timestamp.tv_nsec; #elif defined(_WIN32) || defined(_WIN64) FILETIME ft; GetSystemTimePreciseAsFileTime(&ft); ULARGE_INTEGER result; result.LowPart = ft.dwLowDateTime; result.HighPart = ft.dwHighDateTime; return (result.QuadPart - 116444736000000000ull) * 100; #endif } uint64_t Timestamp::local() { #if defined(unix) || defined(__unix) || defined(__unix__) || defined(__APPLE__) uint64_t timestamp = utc(); // Adjust UTC time with local timezone offset struct tm local; time_t seconds = timestamp / (1000 * 1000 * 1000); if (localtime_r(&seconds, &local) != &local) throwex SystemException("Cannot convert CLOCK_REALTIME time to local date & time structure!"); return timestamp + (local.tm_gmtoff * 1000 * 1000 * 1000); #elif defined(_WIN32) || defined(_WIN64) FILETIME ft; GetSystemTimePreciseAsFileTime(&ft); FILETIME ft_local; if (!FileTimeToLocalFileTime(&ft, &ft_local)) throwex SystemException("Cannot convert UTC file time to local file time structure!"); ULARGE_INTEGER result; result.LowPart = ft_local.dwLowDateTime; result.HighPart = ft_local.dwHighDateTime; return (result.QuadPart - 116444736000000000ull) * 100; #endif } uint64_t Timestamp::nano() { #if defined(__APPLE__) static mach_timebase_info_data_t info; static uint64_t bias = Internals::PrepareTimebaseInfo(info); return (mach_absolute_time() - bias) * info.numer / info.denom; #elif defined(unix) || defined(__unix) || defined(__unix__) struct timespec timestamp = { 0 }; if (clock_gettime(CLOCK_MONOTONIC, &timestamp) != 0) throwex SystemException("Cannot get value of CLOCK_MONOTONIC timer!"); return (timestamp.tv_sec * 1000 * 1000 * 1000) + timestamp.tv_nsec; #elif defined(_WIN32) || defined(_WIN64) static uint64_t offset = 0; static LARGE_INTEGER first = { 0 }; static LARGE_INTEGER frequency = { 0 }; static bool initialized = false; static bool qpc = true; if (!initialized) { // Calculate timestamp offset FILETIME timestamp; GetSystemTimePreciseAsFileTime(&timestamp); ULARGE_INTEGER result; result.LowPart = timestamp.dwLowDateTime; result.HighPart = timestamp.dwHighDateTime; // Convert 01.01.1601 to 01.01.1970 result.QuadPart -= 116444736000000000ll; offset = result.QuadPart * 100; // Setup performance counter qpc = QueryPerformanceFrequency(&frequency) && QueryPerformanceCounter(&first); initialized = true; } if (qpc) { LARGE_INTEGER timestamp = { 0 }; QueryPerformanceCounter(&timestamp); timestamp.QuadPart -= first.QuadPart; return offset + ((timestamp.QuadPart * 1000 * 1000 * 1000) / frequency.QuadPart); } else return offset; #else #error Unsupported platform #endif } uint64_t Timestamp::rdts() { #if defined(_MSC_VER) return __rdtsc(); #elif defined(__i386__) uint64_t x; __asm__ volatile (".byte 0x0f, 0x31" : "=A" (x)); return x; #elif defined(__x86_64__) unsigned hi, lo; __asm__ __volatile__ ("rdtsc" : "=a"(lo), "=d"(hi)); return ((uint64_t)lo) | (((uint64_t)hi) << 32); #endif } } // namespace CppCommon <commit_msg>Fix OSX build<commit_after>/*! \file timestamp.cpp \brief Timestamp implementation \author Ivan Shynkarenka \date 26.01.2016 \copyright MIT License */ #include "time/timestamp.h" #include "errors/exceptions.h" #if defined(__APPLE__) #include <mach/clock.h> #include <mach/mach.h> #include <mach/mach_time.h> #include <math.h> #include <time.h> #elif defined(unix) || defined(__unix) || defined(__unix__) #include <time.h> #elif defined(_WIN32) || defined(_WIN64) #include <windows.h> #endif namespace CppCommon { //! @cond INTERNALS namespace Internals { #if defined(__APPLE__) uint32_t CeilLog2(uint32_t x) { uint32_t result = 0; --x; while (x > 0) { ++result; x >>= 1; } return result; } // This function returns the rational number inside the given interval with // the smallest denominator (and smallest numerator breaks ties; correctness // proof neglects floating-point errors). mach_timebase_info_data_t BestFrac(double a, double b) { if (floor(a) < floor(b)) { mach_timebase_info_data_t rv = { (uint32_t)ceil(a), 1 }; return rv; } double m = floor(a); mach_timebase_info_data_t next = BestFrac(1 / (b - m), 1 / (a - m)); mach_timebase_info_data_t rv = { (int)m * next.numer + next.denom, next.numer }; return rv; } // This is just less than the smallest thing we can multiply numer by without // overflowing. CeilLog2(numer) = 64 - number of leading zeros of numer uint64_t GetExpressibleSpan(uint32_t numer, uint32_t denom) { uint64_t maxDiffWithoutOverflow = ((uint64_t)1 << (64 - CeilLog2(numer))) - 1; return maxDiffWithoutOverflow * numer / denom; } // The clock may run up to 0.1% faster or slower than the "exact" tick count. // However, although the bound on the error is the same as for the pragmatic // answer, the error is actually minimized over the given accuracy bound. uint64_t PrepareTimebaseInfo(mach_timebase_info_data_t& tb) { tb.numer = 0; tb.denom = 1; kern_return_t mtiStatus = mach_timebase_info(&tb); if (mtiStatus != KERN_SUCCESS) return 0; double frac = (double)tb.numer / tb.denom; uint64_t spanTarget = 315360000000000000llu; if (GetExpressibleSpan(tb.numer, tb.denom) >= spanTarget) return 0; for (double errorTarget = 1 / 1024.0; errorTarget > 0.000001;) { mach_timebase_info_data_t newFrac = BestFrac((1 - errorTarget) * frac, (1 + errorTarget) * frac); if (GetExpressibleSpan(newFrac.numer, newFrac.denom) < spanTarget) break; tb = newFrac; errorTarget = fabs((double)tb.numer / tb.denom - frac) / frac / 8; } return mach_absolute_time(); } #endif } // namespace Internals //! @endcond uint64_t Timestamp::utc() { #if defined(__APPLE__) clock_serv_t cclock; mach_timespec_t mts = { 0 }; mach_port_t host_port = mach_host_self(); if (host_port == MACH_PORT_NULL) throwex SystemException("Cannot get the current host port!"); kern_return_t result = host_get_clock_service(host_port, CALENDAR_CLOCK, &cclock); if (result != KERN_SUCCESS) throwex SystemException("Cannot get the current host clock service!"); result = clock_get_time(cclock, &mts); if (result != KERN_SUCCESS) throwex SystemException("Cannot get the current clock time!"); mach_port_t task_port = mach_task_self(); if (task_port == MACH_PORT_NULL) throwex SystemException("Cannot get the current task port!"); result = mach_port_deallocate(task_port, cclock); if (result != KERN_SUCCESS) throwex SystemException("Cannot release the current host clock service!"); return ((uint64_t)mts.tv_sec * 1000 * 1000 * 1000) + mts.tv_nsec; #elif defined(unix) || defined(__unix) || defined(__unix__) struct timespec timestamp; if (clock_gettime(CLOCK_REALTIME, &timestamp) != 0) throwex SystemException("Cannot get value of CLOCK_REALTIME timer!"); return (timestamp.tv_sec * 1000 * 1000 * 1000) + timestamp.tv_nsec; #elif defined(_WIN32) || defined(_WIN64) FILETIME ft; GetSystemTimePreciseAsFileTime(&ft); ULARGE_INTEGER result; result.LowPart = ft.dwLowDateTime; result.HighPart = ft.dwHighDateTime; return (result.QuadPart - 116444736000000000ull) * 100; #endif } uint64_t Timestamp::local() { #if defined(unix) || defined(__unix) || defined(__unix__) || defined(__APPLE__) uint64_t timestamp = utc(); // Adjust UTC time with local timezone offset struct tm local; time_t seconds = timestamp / (1000 * 1000 * 1000); if (localtime_r(&seconds, &local) != &local) throwex SystemException("Cannot convert CLOCK_REALTIME time to local date & time structure!"); return timestamp + (local.tm_gmtoff * 1000 * 1000 * 1000); #elif defined(_WIN32) || defined(_WIN64) FILETIME ft; GetSystemTimePreciseAsFileTime(&ft); FILETIME ft_local; if (!FileTimeToLocalFileTime(&ft, &ft_local)) throwex SystemException("Cannot convert UTC file time to local file time structure!"); ULARGE_INTEGER result; result.LowPart = ft_local.dwLowDateTime; result.HighPart = ft_local.dwHighDateTime; return (result.QuadPart - 116444736000000000ull) * 100; #endif } uint64_t Timestamp::nano() { #if defined(__APPLE__) static mach_timebase_info_data_t info; static uint64_t bias = Internals::PrepareTimebaseInfo(info); return (mach_absolute_time() - bias) * info.numer / info.denom; #elif defined(unix) || defined(__unix) || defined(__unix__) struct timespec timestamp = { 0 }; if (clock_gettime(CLOCK_MONOTONIC, &timestamp) != 0) throwex SystemException("Cannot get value of CLOCK_MONOTONIC timer!"); return (timestamp.tv_sec * 1000 * 1000 * 1000) + timestamp.tv_nsec; #elif defined(_WIN32) || defined(_WIN64) static uint64_t offset = 0; static LARGE_INTEGER first = { 0 }; static LARGE_INTEGER frequency = { 0 }; static bool initialized = false; static bool qpc = true; if (!initialized) { // Calculate timestamp offset FILETIME timestamp; GetSystemTimePreciseAsFileTime(&timestamp); ULARGE_INTEGER result; result.LowPart = timestamp.dwLowDateTime; result.HighPart = timestamp.dwHighDateTime; // Convert 01.01.1601 to 01.01.1970 result.QuadPart -= 116444736000000000ll; offset = result.QuadPart * 100; // Setup performance counter qpc = QueryPerformanceFrequency(&frequency) && QueryPerformanceCounter(&first); initialized = true; } if (qpc) { LARGE_INTEGER timestamp = { 0 }; QueryPerformanceCounter(&timestamp); timestamp.QuadPart -= first.QuadPart; return offset + ((timestamp.QuadPart * 1000 * 1000 * 1000) / frequency.QuadPart); } else return offset; #else #error Unsupported platform #endif } uint64_t Timestamp::rdts() { #if defined(_MSC_VER) return __rdtsc(); #elif defined(__i386__) uint64_t x; __asm__ volatile (".byte 0x0f, 0x31" : "=A" (x)); return x; #elif defined(__x86_64__) unsigned hi, lo; __asm__ __volatile__ ("rdtsc" : "=a"(lo), "=d"(hi)); return ((uint64_t)lo) | (((uint64_t)hi) << 32); #endif } } // namespace CppCommon <|endoftext|>
<commit_before>/* Copyright (c) 2009-2013, Fortylines LLC 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 fortylines 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 Fortylines LLC ''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 Fortylines LLC 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 "document.hh" #include "checkstyle.hh" #include "markup.hh" #include "slice.hh" #include "decorator.hh" /** Check source files according to coding standards. Primary Author(s): Sebastien Mirolo <[email protected]> */ namespace { class errTokWriter : public tero::errTokListener { public: typedef std::map<int,std::string> annotationsType; annotationsType& annotations; boost::filesystem::path filename; bool record; int lineNum; std::string frag; public: explicit errTokWriter( annotationsType& a, const boost::filesystem::path& f ) : annotations(a), filename(f), record(false) {} void newline( const char *line, int first, int last ) { } void token( tero::errToken token, const char *line, int first, int last, bool fragment ) { if( fragment ) { frag += std::string(&line[first],last - first); } else { std::string tokval; if( !frag.empty() ) { tokval = frag + std::string(&line[first],last - first); frag = ""; } else { tokval = std::string(&line[first],last - first); } switch( token ) { case tero::errFilename: record = ( filename == boost::filesystem::path(tokval) ); break;; case tero::errLineNum: if( record ) { lineNum = atoi(tokval.c_str()); } break; case tero::errMessage: if( record ) { annotations[lineNum] += tokval; } break; default: /* Nothing to do excepts shutup gcc warnings. */ break; } } } }; }; // anonymous namespace tero { const char *licenseCodeTitles[] = { "unknown", "MIT", "BSD 2-Clause", "BSD 3-Clause", "Proprietary" }; void checker::cache() { static const boost::regex licenses_regex[] = { // MIT license // ----------- boost::regex( "\\s*Copyright \\(c\\) (\\d+(?:-\\d+)?), ([^#]*)" " 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\\.\\s*"), // BSD 2-Clause // ------------ boost::regex( "\\s*Copyright \\(c\\) (\\d+(?:-\\d+)?), ([^#]*)" " 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 HOLDER OR" " CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL," " EXEMPLARY, OR CONSEQUENTIAL DAMAGES \\(INCLUDING, BUT NOT LIMITED TO," " PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;" " OR BUSINESS INTERRUPTION\\) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY," " WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT \\(INCLUDING NEGLIGENCE OR" " OTHERWISE\\) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF" " ADVISED OF THE POSSIBILITY OF SUCH DAMAGE\\.\\s*"), // BSD 3-Clause // ------------ boost::regex( "\\s*Copyright \\(c\\) (\\d+(?:-\\d+)?), ([^#]*)" " All rights reserved\\." " Redistribution and use in source and binary forms, with or without" " modification, are permitted provided that the following conditions are met:" " 1\\. Redistributions of source code must retain the above copyright notice," " this list of conditions and the following disclaimer\\." " 2\\. Redistributions in binary form must reproduce the above copyright" " notice, this list of conditions and the following disclaimer in the" " documentation and/or other materials provided with the distribution\\." " 3\\. Neither the name of the copyright holder nor the names of its" " contributors may be used to endorse or promote products derived from this" " software without specific prior written permission\\." " THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"" " AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE" " IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE" " ARE DISCLAIMED\\. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE" " LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR" " CONSEQUENTIAL DAMAGES \\(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF" " SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS" " INTERRUPTION\\) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN" " CONTRACT, STRICT LIABILITY, OR TORT \\(INCLUDING NEGLIGENCE OR OTHERWISE\\)" " ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE" " POSSIBILITY OF SUCH DAMAGE\\.\\s*"), // Proprietary // ----------- boost::regex( "\\s*Copyright \\(c\\) (\\d+(?:-\\d+)?), ([^#]*)" " All rights reserved\\.\\s*"), }; boost::smatch m; std::string text = licenseText.str(); for( licenseCode license = MITLicense; license < 5; ++license ) { if( boost::regex_match(text, m, licenses_regex[license - 1]) ) { licenseType = license; dates = m.str(1); grantor = m.str(2); break; } } cached = true; } void checker::normalize( const char *line, int first, int last ) { std::string s(&line[first], &line[last]); if( state == start ) { boost::smatch m; if( !boost::regex_search(s, m, boost::regex("Copyright")) ) return; state = readLicense; } while( first < last ) { switch( state ) { case normalizeLicense: while( first < last && isspace(line[first]) ) ++first; state = readLicense; break; case readLicense: while( first < last && !isspace(line[first]) ) { licenseText << line[first++]; } licenseText << ' '; state = normalizeLicense; break; default: /* Nothing to do except prevent gcc from complaining. */ return; } } } cppChecker::cppChecker() : comment(emptyLine), tokenizer(*this) { } void cppChecker::newline(const char *line, int first, int last ) { switch( state ) { case readLicense: licenseText << ' '; state = normalizeLicense; break; default: /* Nothing to do except prevent gcc from complaining. */ break; } ++nbLines; if( comment == codeLine ) ++nbCodeLines; comment = emptyLine; } void cppChecker::token( cppToken token, const char *line, int first, int last, bool fragment ) { switch( token ) { case cppComment: normalize(line, first, last); if( (state == readLicense || state == normalizeLicense) && !fragment ) state = doneLicense; /* XXX we donot mark comment lines correctly but it does not matter because if there is any code on the line, it will be correctly marked as a "codeLine". */ if( fragment ) comment = commentLine; break; default: comment = codeLine; switch( state ) { case readLicense: state = doneLicense; break; default: /* Nothing to do except prevent gcc from complaining. */ break; } break; } } void shChecker::newline(const char *line, int first, int last ) { switch( state ) { case readLicense: licenseText << ' '; state = normalizeLicense; break; default: /* Nothing to do except prevent gcc from complaining. */ break; } ++nbLines; /* \todo count codeLines... */ } void shChecker::token( shToken token, const char *line, int first, int last, bool fragment ) { switch( token ) { case shComment: if( first < last && line[first] == '#' ) ++first; normalize(line, first, last); if( (state == readLicense || state == normalizeLicense) && !fragment ) state = doneLicense; break; case shCode: state = doneLicense; break; default: /* Nothing to do excepts shutup gcc warnings. */ break; } } void checkstyle::addDir( session& s, const boost::filesystem::path& pathname ) const { } void checkstyle::addFile( session& s, const boost::filesystem::path& pathname ) const { using namespace boost::filesystem; if( state == start ) { s.out() << html::p() << html::table(); s.out() << html::tr() << html::th() << html::th::end << html::th() << "license" << html::th::end << html::th() << "code lines" << html::th::end << html::th() << "total lines" << html::th::end << html::tr::end; state = toplevelFiles; } dispatchDoc::instance()->fetch(s,"check",s.asUrl(pathname)); } void checkstyle::flush( session& s ) const { if( state != start ) { s.out() << html::table::end << html::p::end; } } void checkstyleFetch( session& s, const url& name ) { checkstyle p; p.fetch(s,s.abspath(name)); } void lintAnnotate::init( session& s, const boost::filesystem::path& key, std::istream& info ) { errTokWriter w(super::annotations,key); errTokenizer tok(w); char buffer[4096]; while( !info.eof() ) { info.read(buffer,4096); tok.tokenize(buffer,info.gcount()); } } lintAnnotate::lintAnnotate( session& s, const boost::filesystem::path& key, std::istream& info ) : super() { init(s,key,info); } lintAnnotate::lintAnnotate( session& s, const boost::filesystem::path& key, std::istream& info, std::basic_ostream<char>& o ) : super(o) { init(s,key,info); } } <commit_msg>fix: casting enum to int<commit_after>/* Copyright (c) 2009-2013, Fortylines LLC 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 fortylines 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 Fortylines LLC ''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 Fortylines LLC 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 "document.hh" #include "checkstyle.hh" #include "markup.hh" #include "slice.hh" #include "decorator.hh" /** Check source files according to coding standards. Primary Author(s): Sebastien Mirolo <[email protected]> */ namespace { class errTokWriter : public tero::errTokListener { public: typedef std::map<int,std::string> annotationsType; annotationsType& annotations; boost::filesystem::path filename; bool record; int lineNum; std::string frag; public: explicit errTokWriter( annotationsType& a, const boost::filesystem::path& f ) : annotations(a), filename(f), record(false) {} void newline( const char *line, int first, int last ) { } void token( tero::errToken token, const char *line, int first, int last, bool fragment ) { if( fragment ) { frag += std::string(&line[first],last - first); } else { std::string tokval; if( !frag.empty() ) { tokval = frag + std::string(&line[first],last - first); frag = ""; } else { tokval = std::string(&line[first],last - first); } switch( token ) { case tero::errFilename: record = ( filename == boost::filesystem::path(tokval) ); break;; case tero::errLineNum: if( record ) { lineNum = atoi(tokval.c_str()); } break; case tero::errMessage: if( record ) { annotations[lineNum] += tokval; } break; default: /* Nothing to do excepts shutup gcc warnings. */ break; } } } }; }; // anonymous namespace tero { const char *licenseCodeTitles[] = { "unknown", "MIT", "BSD 2-Clause", "BSD 3-Clause", "Proprietary" }; void checker::cache() { static const boost::regex licenses_regex[] = { // MIT license // ----------- boost::regex( "\\s*Copyright \\(c\\) (\\d+(?:-\\d+)?), ([^#]*)" " 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\\.\\s*"), // BSD 2-Clause // ------------ boost::regex( "\\s*Copyright \\(c\\) (\\d+(?:-\\d+)?), ([^#]*)" " 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 HOLDER OR" " CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL," " EXEMPLARY, OR CONSEQUENTIAL DAMAGES \\(INCLUDING, BUT NOT LIMITED TO," " PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;" " OR BUSINESS INTERRUPTION\\) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY," " WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT \\(INCLUDING NEGLIGENCE OR" " OTHERWISE\\) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF" " ADVISED OF THE POSSIBILITY OF SUCH DAMAGE\\.\\s*"), // BSD 3-Clause // ------------ boost::regex( "\\s*Copyright \\(c\\) (\\d+(?:-\\d+)?), ([^#]*)" " All rights reserved\\." " Redistribution and use in source and binary forms, with or without" " modification, are permitted provided that the following conditions are met:" " 1\\. Redistributions of source code must retain the above copyright notice," " this list of conditions and the following disclaimer\\." " 2\\. Redistributions in binary form must reproduce the above copyright" " notice, this list of conditions and the following disclaimer in the" " documentation and/or other materials provided with the distribution\\." " 3\\. Neither the name of the copyright holder nor the names of its" " contributors may be used to endorse or promote products derived from this" " software without specific prior written permission\\." " THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"" " AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE" " IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE" " ARE DISCLAIMED\\. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE" " LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR" " CONSEQUENTIAL DAMAGES \\(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF" " SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS" " INTERRUPTION\\) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN" " CONTRACT, STRICT LIABILITY, OR TORT \\(INCLUDING NEGLIGENCE OR OTHERWISE\\)" " ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE" " POSSIBILITY OF SUCH DAMAGE\\.\\s*"), // Proprietary // ----------- boost::regex( "\\s*Copyright \\(c\\) (\\d+(?:-\\d+)?), ([^#]*)" " All rights reserved\\.\\s*"), }; boost::smatch m; std::string text = licenseText.str(); for( int license = MITLicense; license < 5; ++license ) { if( boost::regex_match(text, m, licenses_regex[license - 1]) ) { licenseType = (licenseCode)license; dates = m.str(1); grantor = m.str(2); break; } } cached = true; } void checker::normalize( const char *line, int first, int last ) { std::string s(&line[first], &line[last]); if( state == start ) { boost::smatch m; if( !boost::regex_search(s, m, boost::regex("Copyright")) ) return; state = readLicense; } while( first < last ) { switch( state ) { case normalizeLicense: while( first < last && isspace(line[first]) ) ++first; state = readLicense; break; case readLicense: while( first < last && !isspace(line[first]) ) { licenseText << line[first++]; } licenseText << ' '; state = normalizeLicense; break; default: /* Nothing to do except prevent gcc from complaining. */ return; } } } cppChecker::cppChecker() : comment(emptyLine), tokenizer(*this) { } void cppChecker::newline(const char *line, int first, int last ) { switch( state ) { case readLicense: licenseText << ' '; state = normalizeLicense; break; default: /* Nothing to do except prevent gcc from complaining. */ break; } ++nbLines; if( comment == codeLine ) ++nbCodeLines; comment = emptyLine; } void cppChecker::token( cppToken token, const char *line, int first, int last, bool fragment ) { switch( token ) { case cppComment: normalize(line, first, last); if( (state == readLicense || state == normalizeLicense) && !fragment ) state = doneLicense; /* XXX we donot mark comment lines correctly but it does not matter because if there is any code on the line, it will be correctly marked as a "codeLine". */ if( fragment ) comment = commentLine; break; default: comment = codeLine; switch( state ) { case readLicense: state = doneLicense; break; default: /* Nothing to do except prevent gcc from complaining. */ break; } break; } } void shChecker::newline(const char *line, int first, int last ) { switch( state ) { case readLicense: licenseText << ' '; state = normalizeLicense; break; default: /* Nothing to do except prevent gcc from complaining. */ break; } ++nbLines; /* \todo count codeLines... */ } void shChecker::token( shToken token, const char *line, int first, int last, bool fragment ) { switch( token ) { case shComment: if( first < last && line[first] == '#' ) ++first; normalize(line, first, last); if( (state == readLicense || state == normalizeLicense) && !fragment ) state = doneLicense; break; case shCode: state = doneLicense; break; default: /* Nothing to do excepts shutup gcc warnings. */ break; } } void checkstyle::addDir( session& s, const boost::filesystem::path& pathname ) const { } void checkstyle::addFile( session& s, const boost::filesystem::path& pathname ) const { using namespace boost::filesystem; if( state == start ) { s.out() << html::p() << html::table(); s.out() << html::tr() << html::th() << html::th::end << html::th() << "license" << html::th::end << html::th() << "code lines" << html::th::end << html::th() << "total lines" << html::th::end << html::tr::end; state = toplevelFiles; } dispatchDoc::instance()->fetch(s,"check",s.asUrl(pathname)); } void checkstyle::flush( session& s ) const { if( state != start ) { s.out() << html::table::end << html::p::end; } } void checkstyleFetch( session& s, const url& name ) { checkstyle p; p.fetch(s,s.abspath(name)); } void lintAnnotate::init( session& s, const boost::filesystem::path& key, std::istream& info ) { errTokWriter w(super::annotations,key); errTokenizer tok(w); char buffer[4096]; while( !info.eof() ) { info.read(buffer,4096); tok.tokenize(buffer,info.gcount()); } } lintAnnotate::lintAnnotate( session& s, const boost::filesystem::path& key, std::istream& info ) : super() { init(s,key,info); } lintAnnotate::lintAnnotate( session& s, const boost::filesystem::path& key, std::istream& info, std::basic_ostream<char>& o ) : super(o) { init(s,key,info); } } <|endoftext|>
<commit_before>/* * 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. * * As a special exception, you may use this file as part of a free * software library without restriction. Specifically, if other files * instantiate templates or use macros or inline functions from this * file, or you compile this file and link it with other files to * produce an executable, this file does not by itself cause the * resulting executable to be covered by the GNU General Public * License. This exception does not however invalidate any other * reasons why the executable file might be covered by the GNU Library * General Public License. * * 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 "clockimpl.h" #include <sys/time.h> #include <time.h> namespace cxxtools { ClockImpl::ClockImpl() {} ClockImpl::~ClockImpl() {} void ClockImpl::start() { #ifdef HAVE_CLOCK_GETTIME clock_gettime(CLOCK_MONOTONIC, &_startTime); #else gettimeofday( &_startTime, 0 ); #endif } Timespan ClockImpl::stop() const { #ifdef HAVE_CLOCK_GETTIME struct timespec stopTime; clock_gettime(CLOCK_MONOTONIC, &stopTime); time_t secs = stopTime.tv_sec - _startTime.tv_sec; suseconds_t usecs = (stopTime.tv_nsec - _startTime.tv_nsec) / 1000; #else struct timeval stopTime; gettimeofday( &stopTime, 0 ); time_t secs = stopTime.tv_sec - _startTime.tv_sec; suseconds_t usecs = stopTime.tv_usec - _startTime.tv_usec; #endif return Timespan(secs, usecs); } DateTime ClockImpl::getSystemTime() { struct timeval tod; gettimeofday(&tod, NULL); Date date(tod.tv_sec / 24 / 60 / 60); Time time; time.setTotalUSecs(tod.tv_usec); return DateTime(date, time); } DateTime ClockImpl::getLocalTime() { struct timeval tod; gettimeofday(&tod, NULL); struct tm tim; time_t sec = tod.tv_sec; localtime_r(&sec, &tim); return DateTime( tim.tm_year + 1900, tim.tm_mon + 1, tim.tm_mday, tim.tm_hour, tim.tm_min, tim.tm_sec, 0, tod.tv_usec); } Timespan ClockImpl::getSystemTicks() { struct timeval tv; gettimeofday( &tv, 0 ); return Timespan(tv.tv_sec, tv.tv_usec); } } // namespace System <commit_msg>fix cxxtools::Clock::getSystemTime<commit_after>/* * 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. * * As a special exception, you may use this file as part of a free * software library without restriction. Specifically, if other files * instantiate templates or use macros or inline functions from this * file, or you compile this file and link it with other files to * produce an executable, this file does not by itself cause the * resulting executable to be covered by the GNU General Public * License. This exception does not however invalidate any other * reasons why the executable file might be covered by the GNU Library * General Public License. * * 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 "clockimpl.h" #include <sys/time.h> #include <time.h> namespace cxxtools { ClockImpl::ClockImpl() {} ClockImpl::~ClockImpl() {} void ClockImpl::start() { #ifdef HAVE_CLOCK_GETTIME clock_gettime(CLOCK_MONOTONIC, &_startTime); #else gettimeofday( &_startTime, 0 ); #endif } Timespan ClockImpl::stop() const { #ifdef HAVE_CLOCK_GETTIME struct timespec stopTime; clock_gettime(CLOCK_MONOTONIC, &stopTime); time_t secs = stopTime.tv_sec - _startTime.tv_sec; suseconds_t usecs = (stopTime.tv_nsec - _startTime.tv_nsec) / 1000; #else struct timeval stopTime; gettimeofday( &stopTime, 0 ); time_t secs = stopTime.tv_sec - _startTime.tv_sec; suseconds_t usecs = stopTime.tv_usec - _startTime.tv_usec; #endif return Timespan(secs, usecs); } DateTime ClockImpl::getSystemTime() { struct timeval tod; gettimeofday(&tod, NULL); struct tm tim; time_t sec = tod.tv_sec; gmtime_r(&sec, &tim); return DateTime( tim.tm_year + 1900, tim.tm_mon + 1, tim.tm_mday, tim.tm_hour, tim.tm_min, tim.tm_sec, 0, tod.tv_usec); } DateTime ClockImpl::getLocalTime() { struct timeval tod; gettimeofday(&tod, NULL); struct tm tim; time_t sec = tod.tv_sec; localtime_r(&sec, &tim); return DateTime( tim.tm_year + 1900, tim.tm_mon + 1, tim.tm_mday, tim.tm_hour, tim.tm_min, tim.tm_sec, 0, tod.tv_usec); } Timespan ClockImpl::getSystemTicks() { struct timeval tv; gettimeofday( &tv, 0 ); return Timespan(tv.tv_sec, tv.tv_usec); } } // namespace System <|endoftext|>
<commit_before>/** * Copyright (c) 2015 - The CM Authors <[email protected]> * All Rights Reserved. * * This file is CONFIDENTIAL -- Distribution or duplication of this material or * the information contained herein is strictly forbidden unless prior written * permission is obtained. */ #include <stdlib.h> #include <unistd.h> #include <signal.h> #include "fnord-base/io/filerepository.h" #include "fnord-base/io/fileutil.h" #include "fnord-base/application.h" #include "fnord-base/logging.h" #include "fnord-base/random.h" #include "fnord-base/thread/eventloop.h" #include "fnord-base/thread/threadpool.h" #include "fnord-base/wallclock.h" #include "fnord-rpc/ServerGroup.h" #include "fnord-rpc/RPC.h" #include "fnord-rpc/RPCClient.h" #include "fnord-base/cli/flagparser.h" #include "fnord-json/json.h" #include "fnord-json/jsonrpc.h" #include "fnord-http/httprouter.h" #include "fnord-http/httpserver.h" #include "fnord-feeds/FeedService.h" #include "fnord-feeds/RemoteFeedFactory.h" #include "fnord-feeds/RemoteFeedReader.h" #include "fnord-base/stats/statsdagent.h" #include "fnord-http/httpconnectionpool.h" #include "fnord-mdb/MDB.h" #include <fnord-fts/fts.h> #include <fnord-fts/fts_common.h> #include "CustomerNamespace.h" #include "logjoin/LogJoin.h" #include "logjoin/LogJoinTarget.h" #include "logjoin/LogJoinUpload.h" #include "FeatureIndex.h" #include "DocStore.h" #include "IndexChangeRequest.h" #include "FeatureIndexWriter.h" #include "ItemRef.h" #include "common.h" #include "schemas.h" using namespace cm; using namespace fnord; std::atomic<bool> cm_logjoin_shutdown; fnord::thread::EventLoop ev; void quit(int n) { cm_logjoin_shutdown = true; } int main(int argc, const char** argv) { fnord::Application::init(); fnord::Application::logToStderr(); /* shutdown hook */ cm_logjoin_shutdown = false; struct sigaction sa; memset(&sa, 0, sizeof(struct sigaction)); sa.sa_handler = quit; sigaction(SIGTERM, &sa, NULL); sigaction(SIGQUIT, &sa, NULL); sigaction(SIGINT, &sa, NULL); fnord::cli::FlagParser flags; flags.defineFlag( "conf", cli::FlagParser::T_STRING, false, NULL, "./conf", "conf directory", "<path>"); flags.defineFlag( "datadir", cli::FlagParser::T_STRING, true, NULL, NULL, "data dir", "<path>"); flags.defineFlag( "index", cli::FlagParser::T_STRING, false, NULL, NULL, "index directory", "<path>"); flags.defineFlag( "feedserver_addr", fnord::cli::FlagParser::T_STRING, false, NULL, "http://localhost:8000", "feedserver addr", "<addr>"); flags.defineFlag( "statsd_addr", fnord::cli::FlagParser::T_STRING, false, NULL, "127.0.0.1:8192", "Statsd addr", "<addr>"); flags.defineFlag( "batch_size", fnord::cli::FlagParser::T_INTEGER, false, NULL, "2048", "batch_size", "<num>"); flags.defineFlag( "buffer_size", fnord::cli::FlagParser::T_INTEGER, false, NULL, "8192", "buffer_size", "<num>"); flags.defineFlag( "commit_size", fnord::cli::FlagParser::T_INTEGER, false, NULL, "1024", "commit_size", "<num>"); flags.defineFlag( "commit_interval", fnord::cli::FlagParser::T_INTEGER, false, NULL, "5", "commit_interval", "<num>"); flags.defineFlag( "db_size", fnord::cli::FlagParser::T_INTEGER, false, NULL, "128", "max sessiondb size", "<MB>"); flags.defineFlag( "no_dryrun", fnord::cli::FlagParser::T_SWITCH, false, NULL, NULL, "no dryrun", "<bool>"); flags.defineFlag( "nocache", fnord::cli::FlagParser::T_SWITCH, false, NULL, NULL, "no cache", "<bool>"); flags.defineFlag( "shard", fnord::cli::FlagParser::T_STRING, false, NULL, NULL, "shard", "<name>"); flags.defineFlag( "loglevel", fnord::cli::FlagParser::T_STRING, false, NULL, "INFO", "loglevel", "<level>"); flags.parseArgv(argc, argv); Logger::get()->setMinimumLogLevel( strToLogLevel(flags.getString("loglevel"))); /* schema... */ auto joined_sessions_schema = joinedSessionsSchema(); /* start event loop */ auto evloop_thread = std::thread([] { ev.run(); }); /* set up rpc client */ HTTPRPCClient rpc_client(&ev); http::HTTPConnectionPool http(&ev); /* start stats reporting */ fnord::stats::StatsdAgent statsd_agent( fnord::net::InetAddr::resolve(flags.getString("statsd_addr")), 10 * fnord::kMicrosPerSecond); statsd_agent.start(); /* get logjoin shard */ cm::LogJoinShardMap shard_map; auto shard = shard_map.getShard(flags.getString("shard")); /* set up logjoin */ auto dry_run = !flags.isSet("no_dryrun"); auto enable_cache = !flags.isSet("nocache"); size_t batch_size = flags.getInt("batch_size"); size_t buffer_size = flags.getInt("buffer_size"); size_t commit_size = flags.getInt("commit_size"); size_t commit_interval = flags.getInt("commit_interval"); fnord::logInfo( "cm.logjoin", "Starting cm-logjoin with:\n dry_run=$0\n batch_size=$1\n" \ " buffer_size=$2\n commit_size=$3\n commit_interval=$9\n" " max_dbsize=$4MB\n" \ " shard=$5\n shard_range=[$6, $7)\n shard_modulo=$8\n" \ " cache=$9", dry_run, batch_size, buffer_size, commit_size, flags.getInt("db_size"), shard.shard_name, shard.begin, shard.end, cm::LogJoinShard::modulo, commit_interval, enable_cache); /* open session db */ auto sessdb_path = FileUtil::joinPaths( flags.getString("datadir"), StringUtil::format("logjoin/$0/sessions_db", shard.shard_name)); FileUtil::mkdir_p(sessdb_path); auto sessdb = mdb::MDB::open(sessdb_path); sessdb->setMaxSize(1000000 * flags.getInt("db_size")); /* set up input feed reader */ feeds::RemoteFeedReader feed_reader(&rpc_client); feed_reader.setMaxSpread(10 * kMicrosPerSecond); HashMap<String, URI> input_feeds; input_feeds.emplace( "tracker_log.feedserver01.nue01.production.fnrd.net", URI("http://s01.nue01.production.fnrd.net:7001/rpc")); input_feeds.emplace( "tracker_log.feedserver02.nue01.production.fnrd.net", URI("http://s02.nue01.production.fnrd.net:7001/rpc")); /* setup time backfill */ feed_reader.setTimeBackfill([] (const feeds::FeedEntry& entry) -> DateTime { const auto& log_line = entry.data; auto c_end = log_line.find("|"); if (c_end == std::string::npos) return 0; auto t_end = log_line.find("|", c_end + 1); if (t_end == std::string::npos) return 0; auto timestr = log_line.substr(c_end + 1, t_end - c_end - 1); return std::stoul(timestr) * fnord::kMicrosPerSecond; }); /* open index */ auto index_path = FileUtil::joinPaths(flags.getString("index"), "db"); RefPtr<FeatureIndexWriter> index(new FeatureIndexWriter(index_path, true)); /* set up logjoin target */ fnord::fts::Analyzer analyzer(flags.getString("conf")); cm::LogJoinTarget logjoin_target( joined_sessions_schema, &analyzer, index, dry_run); /* set up logjoin upload */ cm::LogJoinUpload logjoin_upload( sessdb, flags.getString("feedserver_addr"), &http); /* setup logjoin */ cm::LogJoin logjoin(shard, dry_run, enable_cache, &logjoin_target); logjoin.exportStats("/cm-logjoin/global"); logjoin.exportStats(StringUtil::format("/cm-logjoin/$0", shard.shard_name)); fnord::stats::Counter<uint64_t> stat_stream_time_low; fnord::stats::Counter<uint64_t> stat_stream_time_high; fnord::stats::Counter<uint64_t> stat_active_sessions; fnord::stats::Counter<uint64_t> stat_dbsize; exportStat( StringUtil::format("/cm-logjoin/$0/stream_time_low", shard.shard_name), &stat_stream_time_low, fnord::stats::ExportMode::EXPORT_VALUE); exportStat( StringUtil::format("/cm-logjoin/$0/stream_time_high", shard.shard_name), &stat_stream_time_high, fnord::stats::ExportMode::EXPORT_VALUE); exportStat( StringUtil::format("/cm-logjoin/$0/active_sessions", shard.shard_name), &stat_active_sessions, fnord::stats::ExportMode::EXPORT_VALUE); exportStat( StringUtil::format("/cm-logjoin/$0/dbsize", shard.shard_name), &stat_dbsize, fnord::stats::ExportMode::EXPORT_VALUE); /* upload pending q */ if (!dry_run) { logjoin_upload.upload(); } /* resume from last offset */ auto txn = sessdb->startTransaction(true); try { logjoin.importTimeoutList(txn.get()); for (const auto& input_feed : input_feeds) { uint64_t offset = 0; auto last_offset = txn->get( StringUtil::format("__logjoin_offset~$0", input_feed.first)); if (!last_offset.isEmpty()) { offset = std::stoul(last_offset.get().toString()); } fnord::logInfo( "cm.logjoin", "Adding source feed:\n feed=$0\n url=$1\n offset: $2", input_feed.first, input_feed.second.toString(), offset); feed_reader.addSourceFeed( input_feed.second, input_feed.first, offset, batch_size, buffer_size); } txn->abort(); } catch (...) { txn->abort(); throw; } fnord::logInfo("cm.logjoin", "Resuming logjoin..."); DateTime last_flush; uint64_t rate_limit_micros = commit_interval * kMicrosPerSecond; for (;;) { auto begin = WallClock::unixMicros(); auto turbo = FileUtil::exists("/tmp/logjoin_turbo.enabled"); logjoin.setTurbo(turbo); feed_reader.fillBuffers(); auto txn = sessdb->startTransaction(); int i = 0; for (; i < commit_size; ++i) { auto entry = feed_reader.fetchNextEntry(); if (entry.isEmpty()) { break; } try { logjoin.insertLogline(entry.get().data, txn.get()); } catch (const std::exception& e) { fnord::logError("cm.logjoin", e, "invalid log line"); } } auto watermarks = feed_reader.watermarks(); auto etime = WallClock::now().unixMicros() - last_flush.unixMicros(); if (etime > rate_limit_micros) { last_flush = WallClock::now(); logjoin.flush(txn.get(), watermarks.first); } auto stream_offsets = feed_reader.streamOffsets(); String stream_offsets_str; for (const auto& soff : stream_offsets) { txn->update( StringUtil::format("__logjoin_offset~$0", soff.first), StringUtil::toString(soff.second)); stream_offsets_str += StringUtil::format("\n offset[$0]=$1", soff.first, soff.second); } fnord::logInfo( "cm.logjoin", "LogJoin comitting...\n stream_time=<$0 ... $1>\n" \ " active_sessions=$2\n flushed_sessions=$3\n " \ "flushed_queries=$4\n flushed_item_visits=$5\n turbo=$6\n " \ "cache_size=$7$8", watermarks.first, watermarks.second, logjoin.numSessions(), logjoin_target.num_sessions, logjoin_target.num_queries, logjoin_target.num_item_visits, turbo, logjoin.cacheSize(), stream_offsets_str); if (dry_run) { txn->abort(); } else { txn->commit(); try { logjoin_upload.upload(); } catch (const std::exception& e) { fnord::logError("cm.logjoin", e, "upload failed"); } } if (cm_logjoin_shutdown.load()) { break; } stat_stream_time_low.set(watermarks.first.unixMicros()); stat_stream_time_high.set(watermarks.second.unixMicros()); stat_active_sessions.set(logjoin.numSessions()); stat_dbsize.set(FileUtil::du_c(sessdb_path)); auto rtime = WallClock::unixMicros() - begin; if (rtime < kMicrosPerSecond) { begin = WallClock::unixMicros(); usleep(kMicrosPerSecond - rtime); } } ev.shutdown(); evloop_thread.join(); fnord::logInfo("cm.logjoin", "LogJoin exiting..."); //exit(0); // FIXPAUL return 0; } <commit_msg>flags<commit_after>/** * Copyright (c) 2015 - The CM Authors <[email protected]> * All Rights Reserved. * * This file is CONFIDENTIAL -- Distribution or duplication of this material or * the information contained herein is strictly forbidden unless prior written * permission is obtained. */ #include <stdlib.h> #include <unistd.h> #include <signal.h> #include "fnord-base/io/filerepository.h" #include "fnord-base/io/fileutil.h" #include "fnord-base/application.h" #include "fnord-base/logging.h" #include "fnord-base/random.h" #include "fnord-base/thread/eventloop.h" #include "fnord-base/thread/threadpool.h" #include "fnord-base/wallclock.h" #include "fnord-rpc/ServerGroup.h" #include "fnord-rpc/RPC.h" #include "fnord-rpc/RPCClient.h" #include "fnord-base/cli/flagparser.h" #include "fnord-json/json.h" #include "fnord-json/jsonrpc.h" #include "fnord-http/httprouter.h" #include "fnord-http/httpserver.h" #include "fnord-feeds/FeedService.h" #include "fnord-feeds/RemoteFeedFactory.h" #include "fnord-feeds/RemoteFeedReader.h" #include "fnord-base/stats/statsdagent.h" #include "fnord-http/httpconnectionpool.h" #include "fnord-mdb/MDB.h" #include <fnord-fts/fts.h> #include <fnord-fts/fts_common.h> #include "CustomerNamespace.h" #include "logjoin/LogJoin.h" #include "logjoin/LogJoinTarget.h" #include "logjoin/LogJoinUpload.h" #include "FeatureIndex.h" #include "DocStore.h" #include "IndexChangeRequest.h" #include "FeatureIndexWriter.h" #include "ItemRef.h" #include "common.h" #include "schemas.h" using namespace cm; using namespace fnord; std::atomic<bool> cm_logjoin_shutdown; fnord::thread::EventLoop ev; void quit(int n) { cm_logjoin_shutdown = true; } int main(int argc, const char** argv) { fnord::Application::init(); fnord::Application::logToStderr(); /* shutdown hook */ cm_logjoin_shutdown = false; struct sigaction sa; memset(&sa, 0, sizeof(struct sigaction)); sa.sa_handler = quit; sigaction(SIGTERM, &sa, NULL); sigaction(SIGQUIT, &sa, NULL); sigaction(SIGINT, &sa, NULL); fnord::cli::FlagParser flags; flags.defineFlag( "conf", cli::FlagParser::T_STRING, false, NULL, "./conf", "conf directory", "<path>"); flags.defineFlag( "datadir", cli::FlagParser::T_STRING, true, NULL, NULL, "data dir", "<path>"); flags.defineFlag( "index", cli::FlagParser::T_STRING, false, NULL, NULL, "index directory", "<path>"); flags.defineFlag( "publish_to", fnord::cli::FlagParser::T_STRING, false, NULL, "http://localhost:8000", "upload target url", "<addr>"); flags.defineFlag( "statsd_addr", fnord::cli::FlagParser::T_STRING, false, NULL, "127.0.0.1:8192", "Statsd addr", "<addr>"); flags.defineFlag( "batch_size", fnord::cli::FlagParser::T_INTEGER, false, NULL, "2048", "batch_size", "<num>"); flags.defineFlag( "buffer_size", fnord::cli::FlagParser::T_INTEGER, false, NULL, "8192", "buffer_size", "<num>"); flags.defineFlag( "commit_size", fnord::cli::FlagParser::T_INTEGER, false, NULL, "1024", "commit_size", "<num>"); flags.defineFlag( "commit_interval", fnord::cli::FlagParser::T_INTEGER, false, NULL, "5", "commit_interval", "<num>"); flags.defineFlag( "db_size", fnord::cli::FlagParser::T_INTEGER, false, NULL, "128", "max sessiondb size", "<MB>"); flags.defineFlag( "no_dryrun", fnord::cli::FlagParser::T_SWITCH, false, NULL, NULL, "no dryrun", "<bool>"); flags.defineFlag( "nocache", fnord::cli::FlagParser::T_SWITCH, false, NULL, NULL, "no cache", "<bool>"); flags.defineFlag( "shard", fnord::cli::FlagParser::T_STRING, false, NULL, NULL, "shard", "<name>"); flags.defineFlag( "loglevel", fnord::cli::FlagParser::T_STRING, false, NULL, "INFO", "loglevel", "<level>"); flags.parseArgv(argc, argv); Logger::get()->setMinimumLogLevel( strToLogLevel(flags.getString("loglevel"))); /* schema... */ auto joined_sessions_schema = joinedSessionsSchema(); /* start event loop */ auto evloop_thread = std::thread([] { ev.run(); }); /* set up rpc client */ HTTPRPCClient rpc_client(&ev); http::HTTPConnectionPool http(&ev); /* start stats reporting */ fnord::stats::StatsdAgent statsd_agent( fnord::net::InetAddr::resolve(flags.getString("statsd_addr")), 10 * fnord::kMicrosPerSecond); statsd_agent.start(); /* get logjoin shard */ cm::LogJoinShardMap shard_map; auto shard = shard_map.getShard(flags.getString("shard")); /* set up logjoin */ auto dry_run = !flags.isSet("no_dryrun"); auto enable_cache = !flags.isSet("nocache"); size_t batch_size = flags.getInt("batch_size"); size_t buffer_size = flags.getInt("buffer_size"); size_t commit_size = flags.getInt("commit_size"); size_t commit_interval = flags.getInt("commit_interval"); fnord::logInfo( "cm.logjoin", "Starting cm-logjoin with:\n dry_run=$0\n batch_size=$1\n" \ " buffer_size=$2\n commit_size=$3\n commit_interval=$9\n" " max_dbsize=$4MB\n" \ " shard=$5\n shard_range=[$6, $7)\n shard_modulo=$8\n" \ " cache=$9", dry_run, batch_size, buffer_size, commit_size, flags.getInt("db_size"), shard.shard_name, shard.begin, shard.end, cm::LogJoinShard::modulo, commit_interval, enable_cache); /* open session db */ auto sessdb_path = FileUtil::joinPaths( flags.getString("datadir"), StringUtil::format("logjoin/$0/sessions_db", shard.shard_name)); FileUtil::mkdir_p(sessdb_path); auto sessdb = mdb::MDB::open(sessdb_path); sessdb->setMaxSize(1000000 * flags.getInt("db_size")); /* set up input feed reader */ feeds::RemoteFeedReader feed_reader(&rpc_client); feed_reader.setMaxSpread(10 * kMicrosPerSecond); HashMap<String, URI> input_feeds; input_feeds.emplace( "tracker_log.feedserver01.nue01.production.fnrd.net", URI("http://s01.nue01.production.fnrd.net:7001/rpc")); input_feeds.emplace( "tracker_log.feedserver02.nue01.production.fnrd.net", URI("http://s02.nue01.production.fnrd.net:7001/rpc")); /* setup time backfill */ feed_reader.setTimeBackfill([] (const feeds::FeedEntry& entry) -> DateTime { const auto& log_line = entry.data; auto c_end = log_line.find("|"); if (c_end == std::string::npos) return 0; auto t_end = log_line.find("|", c_end + 1); if (t_end == std::string::npos) return 0; auto timestr = log_line.substr(c_end + 1, t_end - c_end - 1); return std::stoul(timestr) * fnord::kMicrosPerSecond; }); /* open index */ auto index_path = FileUtil::joinPaths(flags.getString("index"), "db"); RefPtr<FeatureIndexWriter> index(new FeatureIndexWriter(index_path, true)); /* set up logjoin target */ fnord::fts::Analyzer analyzer(flags.getString("conf")); cm::LogJoinTarget logjoin_target( joined_sessions_schema, &analyzer, index, dry_run); /* set up logjoin upload */ cm::LogJoinUpload logjoin_upload( sessdb, flags.getString("publish_to"), &http); /* setup logjoin */ cm::LogJoin logjoin(shard, dry_run, enable_cache, &logjoin_target); logjoin.exportStats("/cm-logjoin/global"); logjoin.exportStats(StringUtil::format("/cm-logjoin/$0", shard.shard_name)); fnord::stats::Counter<uint64_t> stat_stream_time_low; fnord::stats::Counter<uint64_t> stat_stream_time_high; fnord::stats::Counter<uint64_t> stat_active_sessions; fnord::stats::Counter<uint64_t> stat_dbsize; exportStat( StringUtil::format("/cm-logjoin/$0/stream_time_low", shard.shard_name), &stat_stream_time_low, fnord::stats::ExportMode::EXPORT_VALUE); exportStat( StringUtil::format("/cm-logjoin/$0/stream_time_high", shard.shard_name), &stat_stream_time_high, fnord::stats::ExportMode::EXPORT_VALUE); exportStat( StringUtil::format("/cm-logjoin/$0/active_sessions", shard.shard_name), &stat_active_sessions, fnord::stats::ExportMode::EXPORT_VALUE); exportStat( StringUtil::format("/cm-logjoin/$0/dbsize", shard.shard_name), &stat_dbsize, fnord::stats::ExportMode::EXPORT_VALUE); /* upload pending q */ if (!dry_run) { logjoin_upload.upload(); } /* resume from last offset */ auto txn = sessdb->startTransaction(true); try { logjoin.importTimeoutList(txn.get()); for (const auto& input_feed : input_feeds) { uint64_t offset = 0; auto last_offset = txn->get( StringUtil::format("__logjoin_offset~$0", input_feed.first)); if (!last_offset.isEmpty()) { offset = std::stoul(last_offset.get().toString()); } fnord::logInfo( "cm.logjoin", "Adding source feed:\n feed=$0\n url=$1\n offset: $2", input_feed.first, input_feed.second.toString(), offset); feed_reader.addSourceFeed( input_feed.second, input_feed.first, offset, batch_size, buffer_size); } txn->abort(); } catch (...) { txn->abort(); throw; } fnord::logInfo("cm.logjoin", "Resuming logjoin..."); DateTime last_flush; uint64_t rate_limit_micros = commit_interval * kMicrosPerSecond; for (;;) { auto begin = WallClock::unixMicros(); auto turbo = FileUtil::exists("/tmp/logjoin_turbo.enabled"); logjoin.setTurbo(turbo); feed_reader.fillBuffers(); auto txn = sessdb->startTransaction(); int i = 0; for (; i < commit_size; ++i) { auto entry = feed_reader.fetchNextEntry(); if (entry.isEmpty()) { break; } try { logjoin.insertLogline(entry.get().data, txn.get()); } catch (const std::exception& e) { fnord::logError("cm.logjoin", e, "invalid log line"); } } auto watermarks = feed_reader.watermarks(); auto etime = WallClock::now().unixMicros() - last_flush.unixMicros(); if (etime > rate_limit_micros) { last_flush = WallClock::now(); logjoin.flush(txn.get(), watermarks.first); } auto stream_offsets = feed_reader.streamOffsets(); String stream_offsets_str; for (const auto& soff : stream_offsets) { txn->update( StringUtil::format("__logjoin_offset~$0", soff.first), StringUtil::toString(soff.second)); stream_offsets_str += StringUtil::format("\n offset[$0]=$1", soff.first, soff.second); } fnord::logInfo( "cm.logjoin", "LogJoin comitting...\n stream_time=<$0 ... $1>\n" \ " active_sessions=$2\n flushed_sessions=$3\n " \ "flushed_queries=$4\n flushed_item_visits=$5\n turbo=$6\n " \ "cache_size=$7$8", watermarks.first, watermarks.second, logjoin.numSessions(), logjoin_target.num_sessions, logjoin_target.num_queries, logjoin_target.num_item_visits, turbo, logjoin.cacheSize(), stream_offsets_str); if (dry_run) { txn->abort(); } else { txn->commit(); try { logjoin_upload.upload(); } catch (const std::exception& e) { fnord::logError("cm.logjoin", e, "upload failed"); } } if (cm_logjoin_shutdown.load()) { break; } stat_stream_time_low.set(watermarks.first.unixMicros()); stat_stream_time_high.set(watermarks.second.unixMicros()); stat_active_sessions.set(logjoin.numSessions()); stat_dbsize.set(FileUtil::du_c(sessdb_path)); auto rtime = WallClock::unixMicros() - begin; if (rtime < kMicrosPerSecond) { begin = WallClock::unixMicros(); usleep(kMicrosPerSecond - rtime); } } ev.shutdown(); evloop_thread.join(); fnord::logInfo("cm.logjoin", "LogJoin exiting..."); //exit(0); // FIXPAUL return 0; } <|endoftext|>
<commit_before>/** * Copyright (c) 2015 - The CM Authors <[email protected]> * All Rights Reserved. * * This file is CONFIDENTIAL -- Distribution or duplication of this material or * the information contained herein is strictly forbidden unless prior written * permission is obtained. */ #include <stdlib.h> #include <unistd.h> #include <signal.h> #include "fnord-base/io/filerepository.h" #include "fnord-base/io/fileutil.h" #include "fnord-base/application.h" #include "fnord-base/logging.h" #include "fnord-base/random.h" #include "fnord-base/thread/eventloop.h" #include "fnord-base/thread/threadpool.h" #include "fnord-base/wallclock.h" #include "fnord-rpc/ServerGroup.h" #include "fnord-rpc/RPC.h" #include "fnord-rpc/RPCClient.h" #include "fnord-base/cli/flagparser.h" #include "fnord-json/json.h" #include "fnord-json/jsonrpc.h" #include "fnord-http/httprouter.h" #include "fnord-http/httpserver.h" #include "fnord-feeds/FeedService.h" #include "fnord-feeds/RemoteFeedFactory.h" #include "fnord-feeds/RemoteFeedReader.h" #include "fnord-base/stats/statsdagent.h" #include "fnord-http/httpconnectionpool.h" #include "fnord-mdb/MDB.h" #include <fnord-fts/fts.h> #include <fnord-fts/fts_common.h> #include "CustomerNamespace.h" #include "logjoin/LogJoin.h" #include "logjoin/LogJoinTarget.h" #include "logjoin/LogJoinUpload.h" #include "common.h" #include "schemas.h" using namespace cm; using namespace fnord; std::atomic<bool> cm_logjoin_shutdown; void quit(int n) { cm_logjoin_shutdown = true; } int main(int argc, const char** argv) { fnord::Application::init(); fnord::Application::logToStderr(); /* shutdown hook */ cm_logjoin_shutdown = false; struct sigaction sa; memset(&sa, 0, sizeof(struct sigaction)); sa.sa_handler = quit; sigaction(SIGTERM, &sa, NULL); sigaction(SIGQUIT, &sa, NULL); sigaction(SIGINT, &sa, NULL); fnord::cli::FlagParser flags; flags.defineFlag( "conf", cli::FlagParser::T_STRING, false, NULL, "./conf", "conf directory", "<path>"); flags.defineFlag( "cmdata", cli::FlagParser::T_STRING, true, NULL, NULL, "clickmatcher app data dir", "<path>"); flags.defineFlag( "feedserver_addr", fnord::cli::FlagParser::T_STRING, false, NULL, "http://localhost:8000", "feedserver addr", "<addr>"); flags.defineFlag( "statsd_addr", fnord::cli::FlagParser::T_STRING, false, NULL, "127.0.0.1:8192", "Statsd addr", "<addr>"); flags.defineFlag( "batch_size", fnord::cli::FlagParser::T_INTEGER, false, NULL, "2048", "batch_size", "<num>"); flags.defineFlag( "buffer_size", fnord::cli::FlagParser::T_INTEGER, false, NULL, "8192", "buffer_size", "<num>"); flags.defineFlag( "commit_size", fnord::cli::FlagParser::T_INTEGER, false, NULL, "1024", "commit_size", "<num>"); flags.defineFlag( "commit_interval", fnord::cli::FlagParser::T_INTEGER, false, NULL, "5", "commit_interval", "<num>"); flags.defineFlag( "db_size", fnord::cli::FlagParser::T_INTEGER, false, NULL, "128", "max sessiondb size", "<MB>"); flags.defineFlag( "no_dryrun", fnord::cli::FlagParser::T_SWITCH, false, NULL, NULL, "no dryrun", "<bool>"); flags.defineFlag( "loglevel", fnord::cli::FlagParser::T_STRING, false, NULL, "INFO", "loglevel", "<level>"); flags.defineFlag( "shard", fnord::cli::FlagParser::T_STRING, false, NULL, NULL, "shard", "<name>"); flags.parseArgv(argc, argv); Logger::get()->setMinimumLogLevel( strToLogLevel(flags.getString("loglevel"))); /* schema... */ auto joined_sessions_schema = joinedSessionsSchema(); //fnord::iputs("$0", joined_sessions_schema.toString()); /* set up cmdata */ auto cmdata_path = flags.getString("cmdata"); if (!FileUtil::isDirectory(cmdata_path)) { RAISEF(kIOError, "no such directory: $0", cmdata_path); } /* start event loop */ fnord::thread::EventLoop ev; auto evloop_thread = std::thread([&ev] { ev.run(); }); /* set up rpc client */ HTTPRPCClient rpc_client(&ev); http::HTTPConnectionPool http(&ev); /* start stats reporting */ fnord::stats::StatsdAgent statsd_agent( fnord::net::InetAddr::resolve(flags.getString("statsd_addr")), 10 * fnord::kMicrosPerSecond); statsd_agent.start(); /* get logjoin shard */ cm::LogJoinShardMap shard_map; auto shard = shard_map.getShard(flags.getString("shard")); /* set up logjoin */ auto dry_run = !flags.isSet("no_dryrun"); size_t batch_size = flags.getInt("batch_size"); size_t buffer_size = flags.getInt("buffer_size"); size_t commit_size = flags.getInt("commit_size"); size_t commit_interval = flags.getInt("commit_interval"); fnord::logInfo( "cm.logjoin", "Starting cm-logjoin with:\n dry_run=$0\n batch_size=$1\n" \ " buffer_size=$2\n commit_size=$3\n commit_interval=$9\n" " max_dbsize=$4MB\n" \ " shard=$5\n shard_range=[$6, $7)\n shard_modulo=$8", dry_run, batch_size, buffer_size, commit_size, flags.getInt("db_size"), shard.shard_name, shard.begin, shard.end, cm::LogJoinShard::modulo, commit_interval); /* open session db */ auto sessdb_path = FileUtil::joinPaths( cmdata_path, StringUtil::format("logjoin/$0/sessions_db", shard.shard_name)); FileUtil::mkdir_p(sessdb_path); auto sessdb = mdb::MDB::open(sessdb_path); sessdb->setMaxSize(1000000 * flags.getInt("db_size")); /* set up input feed reader */ feeds::RemoteFeedReader feed_reader(&rpc_client); feed_reader.setMaxSpread(10 * kMicrosPerSecond); HashMap<String, URI> input_feeds; //input_feeds.emplace( // "tracker_log.feedserver01.nue01.production.fnrd.net", // URI("http://s01.nue01.production.fnrd.net:7001/rpc")); input_feeds.emplace( "tracker_log.feedserver02.nue01.production.fnrd.net", URI("http://s02.nue01.production.fnrd.net:7001/rpc")); /* setup time backfill */ feed_reader.setTimeBackfill([] (const feeds::FeedEntry& entry) -> DateTime { const auto& log_line = entry.data; auto c_end = log_line.find("|"); if (c_end == std::string::npos) return 0; auto t_end = log_line.find("|", c_end + 1); if (t_end == std::string::npos) return 0; auto timestr = log_line.substr(c_end + 1, t_end - c_end - 1); return std::stoul(timestr) * fnord::kMicrosPerSecond; }); /* set up logjoin target */ fnord::fts::Analyzer analyzer(flags.getString("conf")); cm::LogJoinTarget logjoin_target(joined_sessions_schema, &analyzer); /* set up logjoin upload */ cm::LogJoinUpload logjoin_upload( sessdb, flags.getString("feedserver_addr"), &http); /* setup logjoin */ cm::LogJoin logjoin(shard, dry_run, &logjoin_target); logjoin.exportStats("/cm-logjoin/global"); logjoin.exportStats(StringUtil::format("/cm-logjoin/$0", shard.shard_name)); fnord::stats::Counter<uint64_t> stat_stream_time_low; fnord::stats::Counter<uint64_t> stat_stream_time_high; fnord::stats::Counter<uint64_t> stat_active_sessions; fnord::stats::Counter<uint64_t> stat_dbsize; exportStat( StringUtil::format("/cm-logjoin/$0/stream_time_low", shard.shard_name), &stat_stream_time_low, fnord::stats::ExportMode::EXPORT_VALUE); exportStat( StringUtil::format("/cm-logjoin/$0/stream_time_high", shard.shard_name), &stat_stream_time_high, fnord::stats::ExportMode::EXPORT_VALUE); exportStat( StringUtil::format("/cm-logjoin/$0/active_sessions", shard.shard_name), &stat_active_sessions, fnord::stats::ExportMode::EXPORT_VALUE); exportStat( StringUtil::format("/cm-logjoin/$0/dbsize", shard.shard_name), &stat_dbsize, fnord::stats::ExportMode::EXPORT_VALUE); /* upload pending q */ logjoin_upload.upload(); /* resume from last offset */ auto txn = sessdb->startTransaction(true); try { logjoin.importTimeoutList(txn.get()); for (const auto& input_feed : input_feeds) { uint64_t offset = 0; auto last_offset = txn->get( StringUtil::format("__logjoin_offset~$0", input_feed.first)); if (!last_offset.isEmpty()) { offset = std::stoul(last_offset.get().toString()); } fnord::logInfo( "cm.logjoin", "Adding source feed:\n feed=$0\n url=$1\n offset: $2", input_feed.first, input_feed.second.toString(), offset); feed_reader.addSourceFeed( input_feed.second, input_feed.first, offset, batch_size, buffer_size); } txn->abort(); } catch (...) { txn->abort(); throw; } fnord::logInfo("cm.logjoin", "Resuming logjoin..."); DateTime last_iter; uint64_t rate_limit_micros = commit_interval * kMicrosPerSecond; for (;;) { last_iter = WallClock::now(); feed_reader.fillBuffers(); auto txn = sessdb->startTransaction(); int i = 0; for (; i < commit_size; ++i) { auto entry = feed_reader.fetchNextEntry(); if (entry.isEmpty()) { break; } try { logjoin.insertLogline(entry.get().data, txn.get()); } catch (const std::exception& e) { fnord::logError("cm.logjoin", e, "invalid log line"); } } auto watermarks = feed_reader.watermarks(); logjoin.flush(txn.get(), watermarks.first); auto stream_offsets = feed_reader.streamOffsets(); String stream_offsets_str; for (const auto& soff : stream_offsets) { txn->update( StringUtil::format("__logjoin_offset~$0", soff.first), StringUtil::toString(soff.second)); stream_offsets_str += StringUtil::format("\n offset[$0]=$1", soff.first, soff.second); } fnord::logInfo( "cm.logjoin", "LogJoin comitting...\n stream_time=<$0 ... $1>\n" \ " active_sessions=$2\n flushed_sessions=$3\n " \ "flushed_queries=$4\n flushed_item_visits=$5$6", watermarks.first, watermarks.second, logjoin.numSessions(), logjoin_target.num_sessions, logjoin_target.num_queries, logjoin_target.num_item_visits, stream_offsets_str); txn->commit(); try { logjoin_upload.upload(); } catch (const std::exception& e) { fnord::logError("cm.logjoin", e, "upload failed"); } if (cm_logjoin_shutdown.load()) { break; } stat_stream_time_low.set(watermarks.first.unixMicros()); stat_stream_time_high.set(watermarks.second.unixMicros()); stat_active_sessions.set(logjoin.numSessions()); stat_dbsize.set(FileUtil::du_c(sessdb_path)); auto etime = WallClock::now().unixMicros() - last_iter.unixMicros(); if (i < 1 && etime < rate_limit_micros) { usleep(rate_limit_micros - etime); } } ev.shutdown(); //evloop_thread.join(); fnord::logInfo("cm.logjoin", "LogJoin exiting..."); exit(0); // FIXPAUL return 0; } <commit_msg>cleaning up<commit_after>/** * Copyright (c) 2015 - The CM Authors <[email protected]> * All Rights Reserved. * * This file is CONFIDENTIAL -- Distribution or duplication of this material or * the information contained herein is strictly forbidden unless prior written * permission is obtained. */ #include <stdlib.h> #include <unistd.h> #include <signal.h> #include "fnord-base/io/filerepository.h" #include "fnord-base/io/fileutil.h" #include "fnord-base/application.h" #include "fnord-base/logging.h" #include "fnord-base/random.h" #include "fnord-base/thread/eventloop.h" #include "fnord-base/thread/threadpool.h" #include "fnord-base/wallclock.h" #include "fnord-rpc/ServerGroup.h" #include "fnord-rpc/RPC.h" #include "fnord-rpc/RPCClient.h" #include "fnord-base/cli/flagparser.h" #include "fnord-json/json.h" #include "fnord-json/jsonrpc.h" #include "fnord-http/httprouter.h" #include "fnord-http/httpserver.h" #include "fnord-feeds/FeedService.h" #include "fnord-feeds/RemoteFeedFactory.h" #include "fnord-feeds/RemoteFeedReader.h" #include "fnord-base/stats/statsdagent.h" #include "fnord-http/httpconnectionpool.h" #include "fnord-mdb/MDB.h" #include <fnord-fts/fts.h> #include <fnord-fts/fts_common.h> #include "CustomerNamespace.h" #include "logjoin/LogJoin.h" #include "logjoin/LogJoinTarget.h" #include "logjoin/LogJoinUpload.h" #include "common.h" #include "schemas.h" using namespace cm; using namespace fnord; std::atomic<bool> cm_logjoin_shutdown; void quit(int n) { cm_logjoin_shutdown = true; } int main(int argc, const char** argv) { fnord::Application::init(); fnord::Application::logToStderr(); /* shutdown hook */ cm_logjoin_shutdown = false; struct sigaction sa; memset(&sa, 0, sizeof(struct sigaction)); sa.sa_handler = quit; sigaction(SIGTERM, &sa, NULL); sigaction(SIGQUIT, &sa, NULL); sigaction(SIGINT, &sa, NULL); fnord::cli::FlagParser flags; flags.defineFlag( "conf", cli::FlagParser::T_STRING, false, NULL, "./conf", "conf directory", "<path>"); flags.defineFlag( "cmdata", cli::FlagParser::T_STRING, true, NULL, NULL, "clickmatcher app data dir", "<path>"); flags.defineFlag( "feedserver_addr", fnord::cli::FlagParser::T_STRING, false, NULL, "http://localhost:8000", "feedserver addr", "<addr>"); flags.defineFlag( "statsd_addr", fnord::cli::FlagParser::T_STRING, false, NULL, "127.0.0.1:8192", "Statsd addr", "<addr>"); flags.defineFlag( "batch_size", fnord::cli::FlagParser::T_INTEGER, false, NULL, "2048", "batch_size", "<num>"); flags.defineFlag( "buffer_size", fnord::cli::FlagParser::T_INTEGER, false, NULL, "8192", "buffer_size", "<num>"); flags.defineFlag( "commit_size", fnord::cli::FlagParser::T_INTEGER, false, NULL, "1024", "commit_size", "<num>"); flags.defineFlag( "commit_interval", fnord::cli::FlagParser::T_INTEGER, false, NULL, "5", "commit_interval", "<num>"); flags.defineFlag( "db_size", fnord::cli::FlagParser::T_INTEGER, false, NULL, "128", "max sessiondb size", "<MB>"); flags.defineFlag( "no_dryrun", fnord::cli::FlagParser::T_SWITCH, false, NULL, NULL, "no dryrun", "<bool>"); flags.defineFlag( "loglevel", fnord::cli::FlagParser::T_STRING, false, NULL, "INFO", "loglevel", "<level>"); flags.defineFlag( "shard", fnord::cli::FlagParser::T_STRING, false, NULL, NULL, "shard", "<name>"); flags.parseArgv(argc, argv); Logger::get()->setMinimumLogLevel( strToLogLevel(flags.getString("loglevel"))); /* schema... */ auto joined_sessions_schema = joinedSessionsSchema(); /* set up cmdata */ auto cmdata_path = flags.getString("cmdata"); if (!FileUtil::isDirectory(cmdata_path)) { RAISEF(kIOError, "no such directory: $0", cmdata_path); } /* start event loop */ fnord::thread::EventLoop ev; auto evloop_thread = std::thread([&ev] { ev.run(); }); /* set up rpc client */ HTTPRPCClient rpc_client(&ev); http::HTTPConnectionPool http(&ev); /* start stats reporting */ fnord::stats::StatsdAgent statsd_agent( fnord::net::InetAddr::resolve(flags.getString("statsd_addr")), 10 * fnord::kMicrosPerSecond); statsd_agent.start(); /* get logjoin shard */ cm::LogJoinShardMap shard_map; auto shard = shard_map.getShard(flags.getString("shard")); /* set up logjoin */ auto dry_run = !flags.isSet("no_dryrun"); size_t batch_size = flags.getInt("batch_size"); size_t buffer_size = flags.getInt("buffer_size"); size_t commit_size = flags.getInt("commit_size"); size_t commit_interval = flags.getInt("commit_interval"); fnord::logInfo( "cm.logjoin", "Starting cm-logjoin with:\n dry_run=$0\n batch_size=$1\n" \ " buffer_size=$2\n commit_size=$3\n commit_interval=$9\n" " max_dbsize=$4MB\n" \ " shard=$5\n shard_range=[$6, $7)\n shard_modulo=$8", dry_run, batch_size, buffer_size, commit_size, flags.getInt("db_size"), shard.shard_name, shard.begin, shard.end, cm::LogJoinShard::modulo, commit_interval); /* open session db */ auto sessdb_path = FileUtil::joinPaths( cmdata_path, StringUtil::format("logjoin/$0/sessions_db", shard.shard_name)); FileUtil::mkdir_p(sessdb_path); auto sessdb = mdb::MDB::open(sessdb_path); sessdb->setMaxSize(1000000 * flags.getInt("db_size")); /* set up input feed reader */ feeds::RemoteFeedReader feed_reader(&rpc_client); feed_reader.setMaxSpread(10 * kMicrosPerSecond); HashMap<String, URI> input_feeds; input_feeds.emplace( "tracker_log.feedserver01.nue01.production.fnrd.net", URI("http://s01.nue01.production.fnrd.net:7001/rpc")); input_feeds.emplace( "tracker_log.feedserver02.nue01.production.fnrd.net", URI("http://s02.nue01.production.fnrd.net:7001/rpc")); /* setup time backfill */ feed_reader.setTimeBackfill([] (const feeds::FeedEntry& entry) -> DateTime { const auto& log_line = entry.data; auto c_end = log_line.find("|"); if (c_end == std::string::npos) return 0; auto t_end = log_line.find("|", c_end + 1); if (t_end == std::string::npos) return 0; auto timestr = log_line.substr(c_end + 1, t_end - c_end - 1); return std::stoul(timestr) * fnord::kMicrosPerSecond; }); /* set up logjoin target */ fnord::fts::Analyzer analyzer(flags.getString("conf")); cm::LogJoinTarget logjoin_target(joined_sessions_schema, &analyzer); /* set up logjoin upload */ cm::LogJoinUpload logjoin_upload( sessdb, flags.getString("feedserver_addr"), &http); /* setup logjoin */ cm::LogJoin logjoin(shard, dry_run, &logjoin_target); logjoin.exportStats("/cm-logjoin/global"); logjoin.exportStats(StringUtil::format("/cm-logjoin/$0", shard.shard_name)); fnord::stats::Counter<uint64_t> stat_stream_time_low; fnord::stats::Counter<uint64_t> stat_stream_time_high; fnord::stats::Counter<uint64_t> stat_active_sessions; fnord::stats::Counter<uint64_t> stat_dbsize; exportStat( StringUtil::format("/cm-logjoin/$0/stream_time_low", shard.shard_name), &stat_stream_time_low, fnord::stats::ExportMode::EXPORT_VALUE); exportStat( StringUtil::format("/cm-logjoin/$0/stream_time_high", shard.shard_name), &stat_stream_time_high, fnord::stats::ExportMode::EXPORT_VALUE); exportStat( StringUtil::format("/cm-logjoin/$0/active_sessions", shard.shard_name), &stat_active_sessions, fnord::stats::ExportMode::EXPORT_VALUE); exportStat( StringUtil::format("/cm-logjoin/$0/dbsize", shard.shard_name), &stat_dbsize, fnord::stats::ExportMode::EXPORT_VALUE); /* upload pending q */ logjoin_upload.upload(); /* resume from last offset */ auto txn = sessdb->startTransaction(true); try { logjoin.importTimeoutList(txn.get()); for (const auto& input_feed : input_feeds) { uint64_t offset = 0; auto last_offset = txn->get( StringUtil::format("__logjoin_offset~$0", input_feed.first)); if (!last_offset.isEmpty()) { offset = std::stoul(last_offset.get().toString()); } fnord::logInfo( "cm.logjoin", "Adding source feed:\n feed=$0\n url=$1\n offset: $2", input_feed.first, input_feed.second.toString(), offset); feed_reader.addSourceFeed( input_feed.second, input_feed.first, offset, batch_size, buffer_size); } txn->abort(); } catch (...) { txn->abort(); throw; } fnord::logInfo("cm.logjoin", "Resuming logjoin..."); DateTime last_iter; uint64_t rate_limit_micros = commit_interval * kMicrosPerSecond; for (;;) { last_iter = WallClock::now(); feed_reader.fillBuffers(); auto txn = sessdb->startTransaction(); int i = 0; for (; i < commit_size; ++i) { auto entry = feed_reader.fetchNextEntry(); if (entry.isEmpty()) { break; } try { logjoin.insertLogline(entry.get().data, txn.get()); } catch (const std::exception& e) { fnord::logError("cm.logjoin", e, "invalid log line"); } } auto watermarks = feed_reader.watermarks(); logjoin.flush(txn.get(), watermarks.first); auto stream_offsets = feed_reader.streamOffsets(); String stream_offsets_str; for (const auto& soff : stream_offsets) { txn->update( StringUtil::format("__logjoin_offset~$0", soff.first), StringUtil::toString(soff.second)); stream_offsets_str += StringUtil::format("\n offset[$0]=$1", soff.first, soff.second); } fnord::logInfo( "cm.logjoin", "LogJoin comitting...\n stream_time=<$0 ... $1>\n" \ " active_sessions=$2\n flushed_sessions=$3\n " \ "flushed_queries=$4\n flushed_item_visits=$5$6", watermarks.first, watermarks.second, logjoin.numSessions(), logjoin_target.num_sessions, logjoin_target.num_queries, logjoin_target.num_item_visits, stream_offsets_str); txn->commit(); try { logjoin_upload.upload(); } catch (const std::exception& e) { fnord::logError("cm.logjoin", e, "upload failed"); } if (cm_logjoin_shutdown.load()) { break; } stat_stream_time_low.set(watermarks.first.unixMicros()); stat_stream_time_high.set(watermarks.second.unixMicros()); stat_active_sessions.set(logjoin.numSessions()); stat_dbsize.set(FileUtil::du_c(sessdb_path)); auto etime = WallClock::now().unixMicros() - last_iter.unixMicros(); if (i < 1 && etime < rate_limit_micros) { usleep(rate_limit_micros - etime); } } ev.shutdown(); //evloop_thread.join(); fnord::logInfo("cm.logjoin", "LogJoin exiting..."); exit(0); // FIXPAUL return 0; } <|endoftext|>
<commit_before>/* Copyright (c) 2009-2011, Jack Poulson All rights reserved. This file is part of Elemental. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - Neither the name of the owner nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "elemental/environment.hpp" using namespace std; using namespace elemental; using namespace elemental::imports; elemental::Grid::Grid ( mpi::Comm comm ) { #ifndef RELEASE PushCallStack("Grid::Grid"); #endif _inGrid = true; // this is true by assumption for this constructor // Extract our rank, the underlying group, and the number of processes mpi::CommDup( comm, _viewingComm ); mpi::CommGroup( _viewingComm, _viewingGroup ); _viewingRank = mpi::CommRank( _viewingComm ); _p = mpi::CommSize( _viewingComm ); // All processes own the grid, so we have to trivially split _viewingGroup _owningGroup = _viewingGroup; _notOwningGroup = mpi::GROUP_EMPTY; _owningRank = _viewingRank; // Factor p _r = static_cast<int>(sqrt(static_cast<double>(_p))); while( _p % _r != 0 ) ++_r; _c = _p / _r; SetUpGrid(); #ifndef RELEASE PopCallStack(); #endif } elemental::Grid::Grid ( mpi::Comm comm, int r, int c ) { #ifndef RELEASE PushCallStack("Grid::Grid"); #endif _inGrid = true; // this is true by assumption for this constructor // Extract our rank, the underlying group, and the number of processes mpi::CommDup( comm, _viewingComm ); mpi::CommGroup( _viewingComm, _viewingGroup ); _viewingRank = mpi::CommRank( _viewingComm ); _p = mpi::CommSize( _viewingComm ); // All processes own the grid, so we have to trivially split _viewingGroup _owningGroup = _viewingGroup; _notOwningGroup = mpi::GROUP_EMPTY; _owningRank = _viewingRank; _r = r; _c = c; if( _r < 0 || _c < 0 ) throw logic_error( "Process grid dimensions must be non-negative." ); SetUpGrid(); #ifndef RELEASE PopCallStack(); #endif } elemental::Grid::Grid ( mpi::Comm viewingComm, mpi::Group owningGroup ) { #ifndef RELEASE PushCallStack("Grid::Grid"); #endif // Extract our rank and the underlying group from the viewing comm mpi::CommDup( viewingComm, _viewingComm ); mpi::CommGroup( _viewingComm, _viewingGroup ); _viewingRank = mpi::CommRank( _viewingComm ); // Extract our rank and the number of processes from the owning group _owningGroup = owningGroup; _p = mpi::GroupSize( _owningGroup ); _owningRank = mpi::GroupRank( _owningGroup ); _inGrid = ( _owningRank != mpi::UNDEFINED ); // Create the complement of the owning group mpi::GroupDifference( _viewingGroup, _owningGroup, _notOwningGroup ); // Factor p _r = static_cast<int>(sqrt(static_cast<double>(_p))); while( _p % _r != 0 ) ++_r; _c = _p / _r; SetUpGrid(); #ifndef RELEASE PopCallStack(); #endif } // Currently forces a columnMajor absolute rank on the grid elemental::Grid::Grid ( mpi::Comm viewingComm, mpi::Group owningGroup, int r, int c ) { #ifndef RELEASE PushCallStack("Grid::Grid"); #endif // Extract our rank and the underlying group from the viewing comm mpi::CommDup( viewingComm, _viewingComm ); mpi::CommGroup( _viewingComm, _viewingGroup ); _viewingRank = mpi::CommRank( _viewingComm ); // Extract our rank and the number of processes from the owning group _owningGroup = owningGroup; _p = mpi::GroupSize( _owningGroup ); _owningRank = mpi::GroupRank( _owningGroup ); _inGrid = ( _owningRank != mpi::UNDEFINED ); // Create the complement of the owning group mpi::GroupDifference( _viewingGroup, _owningGroup, _notOwningGroup ); _r = r; _c = c; if( _r < 0 || _c < 0 ) throw logic_error( "Process grid dimensions must be non-negative." ); SetUpGrid(); #ifndef RELEASE PopCallStack(); #endif } void elemental::Grid::SetUpGrid() { #ifndef RELEASE PushCallStack("Grid::SetUpGrid"); #endif if( _p != _r*_c ) { ostringstream msg; msg << "Number of processes must match grid size:\n" << " p=" << _p << ", (r,c)=(" << _r << "," << _c << ")"; throw logic_error( msg.str() ); } _gcd = utilities::GCD( _r, _c ); int lcm = _p / _gcd; #ifndef RELEASE if( _owningRank == 0 ) { cout << "Building process grid with:\n" << " p=" << _p << ", (r,c)=(" << _r << "," << _c << ")\n" << " gcd=" << _gcd << endl; } #endif // Split the viewing comm into the owning and not owning subsets if( _inGrid ) mpi::CommCreate( _viewingComm, _owningGroup, _owningComm ); else mpi::CommCreate( _viewingComm, _notOwningGroup, _notOwningComm ); if( _inGrid ) { // Create a cartesian communicator int dimensions[2] = { _c, _r }; int periods[2] = { true, true }; int reorder = false; mpi::CartCreate ( _owningComm, 2, dimensions, periods, reorder, _cartComm ); // Set up the MatrixCol and MatrixRow communicators int remainingDimensions[2]; remainingDimensions[0] = false; remainingDimensions[1] = true; mpi::CartSub( _cartComm, remainingDimensions, _matrixColComm ); remainingDimensions[0] = true; remainingDimensions[1] = false; mpi::CartSub( _cartComm, remainingDimensions, _matrixRowComm ); _matrixColRank = mpi::CommRank( _matrixColComm ); _matrixRowRank = mpi::CommRank( _matrixRowComm ); // Set up the VectorCol and VectorRow communicators _vectorColRank = _matrixColRank + _r*_matrixRowRank; _vectorRowRank = _matrixRowRank + _c*_matrixColRank; mpi::CommSplit( _cartComm, 0, _vectorColRank, _vectorColComm ); mpi::CommSplit( _cartComm, 0, _vectorRowRank, _vectorRowComm ); // Compute which diagonal 'path' we're in, and what our rank is, then // perform AllGather world to store everyone's info _diagPathsAndRanks.resize(2*_p); vector<int> myDiagPathAndRank(2); myDiagPathAndRank[0] = (_matrixRowRank+_r-_matrixColRank) % _gcd; int diagPathRank = 0; int row = 0; int col = myDiagPathAndRank[0]; for( int j=0; j<lcm; ++j ) { if( row == _matrixColRank && col == _matrixRowRank ) { myDiagPathAndRank[1] = diagPathRank; break; } else { row = (row + 1) % _r; col = (col + 1) % _c; ++diagPathRank; } } mpi::AllGather ( &myDiagPathAndRank[0], 2, &_diagPathsAndRanks[0], 2, _vectorColComm ); #ifndef RELEASE mpi::ErrorHandlerSet( _matrixColComm, mpi::ERRORS_RETURN ); mpi::ErrorHandlerSet( _matrixRowComm, mpi::ERRORS_RETURN ); mpi::ErrorHandlerSet( _vectorColComm, mpi::ERRORS_RETURN ); mpi::ErrorHandlerSet( _vectorRowComm, mpi::ERRORS_RETURN ); #endif } else { // diag paths and ranks are implicitly set to undefined _matrixColRank = mpi::UNDEFINED; _matrixRowRank = mpi::UNDEFINED; _vectorColRank = mpi::UNDEFINED; _vectorRowRank = mpi::UNDEFINED; } // Set up the map from the VC group to the _viewingGroup ranks. // Since the VC communicator preserves the ordering of the _owningGroup // ranks, we can simply translate from _owningGroup. std::vector<int> ranks(_p); for( int i=0; i<_p; ++i ) ranks[i] = i; _VCToViewingMap.resize(_p); mpi::GroupTranslateRanks ( _owningGroup, _p, &ranks[0], _viewingGroup, &_VCToViewingMap[0] ); #ifndef RELEASE PopCallStack(); #endif } elemental::Grid::~Grid() { if( !mpi::Finalized() ) { if( _inGrid ) { mpi::CommFree( _matrixColComm ); mpi::CommFree( _matrixRowComm ); mpi::CommFree( _vectorColComm ); mpi::CommFree( _vectorRowComm ); mpi::CommFree( _cartComm ); } if( _inGrid ) mpi::CommFree( _owningComm ); else mpi::CommFree( _notOwningComm ); if( _notOwningGroup != mpi::GROUP_EMPTY ) mpi::GroupFree( _notOwningGroup ); mpi::CommFree( _viewingComm ); } } <commit_msg>Removed illegal but functional use of MPI_Comm_create in favor of MPI_Comm_split.<commit_after>/* Copyright (c) 2009-2011, Jack Poulson All rights reserved. This file is part of Elemental. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - Neither the name of the owner nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "elemental/environment.hpp" using namespace std; using namespace elemental; using namespace elemental::imports; elemental::Grid::Grid ( mpi::Comm comm ) { #ifndef RELEASE PushCallStack("Grid::Grid"); #endif _inGrid = true; // this is true by assumption for this constructor // Extract our rank, the underlying group, and the number of processes mpi::CommDup( comm, _viewingComm ); mpi::CommGroup( _viewingComm, _viewingGroup ); _viewingRank = mpi::CommRank( _viewingComm ); _p = mpi::CommSize( _viewingComm ); // All processes own the grid, so we have to trivially split _viewingGroup _owningGroup = _viewingGroup; _notOwningGroup = mpi::GROUP_EMPTY; _owningRank = _viewingRank; // Factor p _r = static_cast<int>(sqrt(static_cast<double>(_p))); while( _p % _r != 0 ) ++_r; _c = _p / _r; SetUpGrid(); #ifndef RELEASE PopCallStack(); #endif } elemental::Grid::Grid ( mpi::Comm comm, int r, int c ) { #ifndef RELEASE PushCallStack("Grid::Grid"); #endif _inGrid = true; // this is true by assumption for this constructor // Extract our rank, the underlying group, and the number of processes mpi::CommDup( comm, _viewingComm ); mpi::CommGroup( _viewingComm, _viewingGroup ); _viewingRank = mpi::CommRank( _viewingComm ); _p = mpi::CommSize( _viewingComm ); // All processes own the grid, so we have to trivially split _viewingGroup _owningGroup = _viewingGroup; _notOwningGroup = mpi::GROUP_EMPTY; _owningRank = _viewingRank; _r = r; _c = c; if( _r < 0 || _c < 0 ) throw logic_error( "Process grid dimensions must be non-negative." ); SetUpGrid(); #ifndef RELEASE PopCallStack(); #endif } elemental::Grid::Grid ( mpi::Comm viewingComm, mpi::Group owningGroup ) { #ifndef RELEASE PushCallStack("Grid::Grid"); #endif // Extract our rank and the underlying group from the viewing comm mpi::CommDup( viewingComm, _viewingComm ); mpi::CommGroup( _viewingComm, _viewingGroup ); _viewingRank = mpi::CommRank( _viewingComm ); // Extract our rank and the number of processes from the owning group _owningGroup = owningGroup; _p = mpi::GroupSize( _owningGroup ); _owningRank = mpi::GroupRank( _owningGroup ); _inGrid = ( _owningRank != mpi::UNDEFINED ); // Create the complement of the owning group mpi::GroupDifference( _viewingGroup, _owningGroup, _notOwningGroup ); // Factor p _r = static_cast<int>(sqrt(static_cast<double>(_p))); while( _p % _r != 0 ) ++_r; _c = _p / _r; SetUpGrid(); #ifndef RELEASE PopCallStack(); #endif } // Currently forces a columnMajor absolute rank on the grid elemental::Grid::Grid ( mpi::Comm viewingComm, mpi::Group owningGroup, int r, int c ) { #ifndef RELEASE PushCallStack("Grid::Grid"); #endif // Extract our rank and the underlying group from the viewing comm mpi::CommDup( viewingComm, _viewingComm ); mpi::CommGroup( _viewingComm, _viewingGroup ); _viewingRank = mpi::CommRank( _viewingComm ); // Extract our rank and the number of processes from the owning group _owningGroup = owningGroup; _p = mpi::GroupSize( _owningGroup ); _owningRank = mpi::GroupRank( _owningGroup ); _inGrid = ( _owningRank != mpi::UNDEFINED ); // Create the complement of the owning group mpi::GroupDifference( _viewingGroup, _owningGroup, _notOwningGroup ); _r = r; _c = c; if( _r < 0 || _c < 0 ) throw logic_error( "Process grid dimensions must be non-negative." ); SetUpGrid(); #ifndef RELEASE PopCallStack(); #endif } void elemental::Grid::SetUpGrid() { #ifndef RELEASE PushCallStack("Grid::SetUpGrid"); #endif if( _p != _r*_c ) { ostringstream msg; msg << "Number of processes must match grid size:\n" << " p=" << _p << ", (r,c)=(" << _r << "," << _c << ")"; throw logic_error( msg.str() ); } _gcd = utilities::GCD( _r, _c ); int lcm = _p / _gcd; #ifndef RELEASE if( _owningRank == 0 ) { cout << "Building process grid with:\n" << " p=" << _p << ", (r,c)=(" << _r << "," << _c << ")\n" << " gcd=" << _gcd << endl; } #endif // Split the viewing comm into the owning and not owning subsets if( _inGrid ) mpi::CommSplit( _viewingComm, true, _owningRank, _owningComm ); else mpi::CommSplit( _viewingComm, false, 0, _notOwningComm ); if( _inGrid ) { // Create a cartesian communicator int dimensions[2] = { _c, _r }; int periods[2] = { true, true }; int reorder = false; mpi::CartCreate ( _owningComm, 2, dimensions, periods, reorder, _cartComm ); // Set up the MatrixCol and MatrixRow communicators int remainingDimensions[2]; remainingDimensions[0] = false; remainingDimensions[1] = true; mpi::CartSub( _cartComm, remainingDimensions, _matrixColComm ); remainingDimensions[0] = true; remainingDimensions[1] = false; mpi::CartSub( _cartComm, remainingDimensions, _matrixRowComm ); _matrixColRank = mpi::CommRank( _matrixColComm ); _matrixRowRank = mpi::CommRank( _matrixRowComm ); // Set up the VectorCol and VectorRow communicators _vectorColRank = _matrixColRank + _r*_matrixRowRank; _vectorRowRank = _matrixRowRank + _c*_matrixColRank; mpi::CommSplit( _cartComm, 0, _vectorColRank, _vectorColComm ); mpi::CommSplit( _cartComm, 0, _vectorRowRank, _vectorRowComm ); // Compute which diagonal 'path' we're in, and what our rank is, then // perform AllGather world to store everyone's info _diagPathsAndRanks.resize(2*_p); vector<int> myDiagPathAndRank(2); myDiagPathAndRank[0] = (_matrixRowRank+_r-_matrixColRank) % _gcd; int diagPathRank = 0; int row = 0; int col = myDiagPathAndRank[0]; for( int j=0; j<lcm; ++j ) { if( row == _matrixColRank && col == _matrixRowRank ) { myDiagPathAndRank[1] = diagPathRank; break; } else { row = (row + 1) % _r; col = (col + 1) % _c; ++diagPathRank; } } mpi::AllGather ( &myDiagPathAndRank[0], 2, &_diagPathsAndRanks[0], 2, _vectorColComm ); #ifndef RELEASE mpi::ErrorHandlerSet( _matrixColComm, mpi::ERRORS_RETURN ); mpi::ErrorHandlerSet( _matrixRowComm, mpi::ERRORS_RETURN ); mpi::ErrorHandlerSet( _vectorColComm, mpi::ERRORS_RETURN ); mpi::ErrorHandlerSet( _vectorRowComm, mpi::ERRORS_RETURN ); #endif } else { // diag paths and ranks are implicitly set to undefined _matrixColRank = mpi::UNDEFINED; _matrixRowRank = mpi::UNDEFINED; _vectorColRank = mpi::UNDEFINED; _vectorRowRank = mpi::UNDEFINED; } // Set up the map from the VC group to the _viewingGroup ranks. // Since the VC communicator preserves the ordering of the _owningGroup // ranks, we can simply translate from _owningGroup. std::vector<int> ranks(_p); for( int i=0; i<_p; ++i ) ranks[i] = i; _VCToViewingMap.resize(_p); mpi::GroupTranslateRanks ( _owningGroup, _p, &ranks[0], _viewingGroup, &_VCToViewingMap[0] ); #ifndef RELEASE PopCallStack(); #endif } elemental::Grid::~Grid() { if( !mpi::Finalized() ) { if( _inGrid ) { mpi::CommFree( _matrixColComm ); mpi::CommFree( _matrixRowComm ); mpi::CommFree( _vectorColComm ); mpi::CommFree( _vectorRowComm ); mpi::CommFree( _cartComm ); } if( _inGrid ) mpi::CommFree( _owningComm ); else mpi::CommFree( _notOwningComm ); if( _notOwningGroup != mpi::GROUP_EMPTY ) mpi::GroupFree( _notOwningGroup ); mpi::CommFree( _viewingComm ); } } <|endoftext|>
<commit_before>#include "dbmanager.h" #include <QtSql/QSqlQuery> #include <QTimeZone> #include <QDateTime> #include <QDebug> DBManager::DBManager(const QString& path, bool doCreate, QObject *parent) : QObject(parent) { qRegisterMetaType<QList<NoteData*> >("QList<NoteData*>"); m_db = QSqlDatabase::addDatabase("QSQLITE"); m_db.setDatabaseName(path); if (!m_db.open()){ qDebug() << "Error: connection with database fail"; }else{ qDebug() << "Database: connection ok"; } if(doCreate){ QSqlQuery query; QString active = "CREATE TABLE active_notes (" "id INTEGER PRIMARY KEY AUTOINCREMENT," "creation_date INTEGER NOT NULL DEFAULT (0)," "modification_date INTEGER NOT NULL DEFAULT (0)," "deletion_date INTEGER NOT NULL DEFAULT (0)," "content TEXT, " "full_title TEXT);"; query.exec(active); QString active_index = "CREATE UNIQUE INDEX active_index on active_notes (id ASC);"; query.exec(active_index); QString deleted = "CREATE TABLE deleted_notes (" "id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL," "creation_date INTEGER NOT NULL DEFAULT (0)," "modification_date INTEGER NOT NULL DEFAULT (0)," "deletion_date INTEGER NOT NULL DEFAULT (0)," "content TEXT," "full_title TEXT)"; query.exec(deleted); } } bool DBManager::isNoteExist(NoteData* note) { QSqlQuery query; int id = note->id().split('_')[1].toInt(); QString queryStr = QStringLiteral("SELECT EXISTS(SELECT 1 FROM active_notes WHERE id = %1 LIMIT 1 )") .arg(id); query.exec(queryStr); query.next(); return query.value(0).toInt() == 1; } QList<NoteData *> DBManager::getAllNotes() { QList<NoteData *> noteList; QSqlQuery query; query.prepare("SELECT * FROM active_notes"); bool status = query.exec(); if(status){ while(query.next()){ NoteData* note = new NoteData(this); int id = query.value(0).toInt(); qint64 epochDateTimeCreation = query.value(1).toLongLong(); QDateTime dateTimeCreation = QDateTime::fromMSecsSinceEpoch(epochDateTimeCreation, QTimeZone::systemTimeZone()); qint64 epochDateTimeModification= query.value(2).toLongLong(); QDateTime dateTimeModification = QDateTime::fromMSecsSinceEpoch(epochDateTimeModification, QTimeZone::systemTimeZone()); QString content = query.value(4).toString(); QString fullTitle = query.value(5).toString(); note->setId(QStringLiteral("noteID_%1").arg(id)); note->setCreationDateTime(dateTimeCreation); note->setLastModificationDateTime(dateTimeModification); note->setContent(content); note->setFullTitle(fullTitle); noteList.push_back(note); } emit notesReceived(noteList); } return noteList; } bool DBManager::addNote(NoteData* note) { QSqlQuery query; qint64 epochTimeDateCreated = note->creationDateTime().toMSecsSinceEpoch(); QString content = note->content().replace("'","''"); QString fullTitle = note->fullTitle().replace("'","''"); QString queryStr = QString("INSERT INTO active_notes (creation_date, modification_date, deletion_date, content, full_title) " "VALUES (%1, %1, -1, '%2', '%3');") .arg(epochTimeDateCreated) .arg(content) .arg(fullTitle); query.exec(queryStr); return (query.numRowsAffected() == 1); } bool DBManager::removeNote(NoteData* note) { QSqlQuery query; int id = note->id().split('_')[1].toInt(); QString queryStr = QStringLiteral("DELETE FROM active_notes " "WHERE id=%1") .arg(id); query.exec(queryStr); bool removed = (query.numRowsAffected() == 1); qint64 epochTimeDateCreated = note->creationDateTime().toMSecsSinceEpoch(); qint64 epochTimeDateModified = note->lastModificationdateTime().toMSecsSinceEpoch(); qint64 epochTimeDateDeleted = note->deletionDateTime().toMSecsSinceEpoch(); QString content = note->content().replace("'","''"); QString fullTitle = note->fullTitle().replace("'","''"); queryStr = QString("INSERT INTO deleted_notes " "VALUES (%1, %2, %3, %4, '%5', '%6');") .arg(id) .arg(epochTimeDateCreated) .arg(epochTimeDateModified) .arg(epochTimeDateDeleted) .arg(content) .arg(fullTitle); query.exec(queryStr); bool addedToTrashDB = (query.numRowsAffected() == 1); return (removed && addedToTrashDB); } bool DBManager::modifyNote(NoteData* note) { QSqlQuery query; int id = note->id().split('_')[1].toInt(); qint64 epochTimeDateModified = note->lastModificationdateTime().toMSecsSinceEpoch(); QString content = note->content().replace("'","''"); QString fullTitle = note->fullTitle().replace("'","''"); QString queryStr = QStringLiteral("UPDATE active_notes " "SET modification_date=%1, content='%2', full_title='%3' " "WHERE id=%4") .arg(epochTimeDateModified) .arg(content) .arg(fullTitle) .arg(id); query.exec(queryStr); return (query.numRowsAffected() == 1); } bool DBManager::migrateNote(NoteData* note) { QSqlQuery query; QString emptyStr; int id = note->id().split('_')[1].toInt(); qint64 epochTimeDateCreated = note->creationDateTime().toMSecsSinceEpoch(); qint64 epochTimeDateModified = note->lastModificationdateTime().toMSecsSinceEpoch(); QString content = note->content() .replace("'","''") .replace(QChar('\x0'), emptyStr); QString fullTitle = note->fullTitle() .replace("'","''") .replace(QChar('\x0'), emptyStr); QString queryStr = QString("INSERT INTO active_notes " "VALUES (%1, %2, %3, -1, '%4', '%5');") .arg(id) .arg(epochTimeDateCreated) .arg(epochTimeDateModified) .arg(content) .arg(fullTitle); query.exec(queryStr); return (query.numRowsAffected() == 1); } bool DBManager::migrateTrash(NoteData* note) { QSqlQuery query; QString emptyStr; int id = note->id().split('_')[1].toInt(); qint64 epochTimeDateCreated = note->creationDateTime().toMSecsSinceEpoch(); qint64 epochTimeDateModified = note->lastModificationdateTime().toMSecsSinceEpoch(); qint64 epochTimeDateDeleted = note->deletionDateTime().toMSecsSinceEpoch(); QString content = note->content() .replace("'","''") .replace(QChar('\x0'), emptyStr); QString fullTitle = note->fullTitle() .replace("'","''") .replace(QChar('\x0'), emptyStr); QString queryStr = QString("INSERT INTO deleted_notes " "VALUES (%1, %2, %3, %4, '%5', '%6');") .arg(id) .arg(epochTimeDateCreated) .arg(epochTimeDateModified) .arg(epochTimeDateDeleted) .arg(content) .arg(fullTitle); query.exec(queryStr); return (query.numRowsAffected() == 1); } int DBManager::getLastRowID() { QSqlQuery query; query.exec("SELECT seq from SQLITE_SEQUENCE WHERE name='active_notes';"); query.next(); return query.value(0).toInt(); } <commit_msg>Fix: saving modified note, having \x0 at the end, to database<commit_after>#include "dbmanager.h" #include <QtSql/QSqlQuery> #include <QTimeZone> #include <QDateTime> #include <QDebug> DBManager::DBManager(const QString& path, bool doCreate, QObject *parent) : QObject(parent) { qRegisterMetaType<QList<NoteData*> >("QList<NoteData*>"); m_db = QSqlDatabase::addDatabase("QSQLITE"); m_db.setDatabaseName(path); if (!m_db.open()){ qDebug() << "Error: connection with database fail"; }else{ qDebug() << "Database: connection ok"; } if(doCreate){ QSqlQuery query; QString active = "CREATE TABLE active_notes (" "id INTEGER PRIMARY KEY AUTOINCREMENT," "creation_date INTEGER NOT NULL DEFAULT (0)," "modification_date INTEGER NOT NULL DEFAULT (0)," "deletion_date INTEGER NOT NULL DEFAULT (0)," "content TEXT, " "full_title TEXT);"; query.exec(active); QString active_index = "CREATE UNIQUE INDEX active_index on active_notes (id ASC);"; query.exec(active_index); QString deleted = "CREATE TABLE deleted_notes (" "id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL," "creation_date INTEGER NOT NULL DEFAULT (0)," "modification_date INTEGER NOT NULL DEFAULT (0)," "deletion_date INTEGER NOT NULL DEFAULT (0)," "content TEXT," "full_title TEXT)"; query.exec(deleted); } } bool DBManager::isNoteExist(NoteData* note) { QSqlQuery query; int id = note->id().split('_')[1].toInt(); QString queryStr = QStringLiteral("SELECT EXISTS(SELECT 1 FROM active_notes WHERE id = %1 LIMIT 1 )") .arg(id); query.exec(queryStr); query.next(); return query.value(0).toInt() == 1; } QList<NoteData *> DBManager::getAllNotes() { QList<NoteData *> noteList; QSqlQuery query; query.prepare("SELECT * FROM active_notes"); bool status = query.exec(); if(status){ while(query.next()){ NoteData* note = new NoteData(this); int id = query.value(0).toInt(); qint64 epochDateTimeCreation = query.value(1).toLongLong(); QDateTime dateTimeCreation = QDateTime::fromMSecsSinceEpoch(epochDateTimeCreation, QTimeZone::systemTimeZone()); qint64 epochDateTimeModification= query.value(2).toLongLong(); QDateTime dateTimeModification = QDateTime::fromMSecsSinceEpoch(epochDateTimeModification, QTimeZone::systemTimeZone()); QString content = query.value(4).toString(); QString fullTitle = query.value(5).toString(); note->setId(QStringLiteral("noteID_%1").arg(id)); note->setCreationDateTime(dateTimeCreation); note->setLastModificationDateTime(dateTimeModification); note->setContent(content); note->setFullTitle(fullTitle); noteList.push_back(note); } emit notesReceived(noteList); } return noteList; } bool DBManager::addNote(NoteData* note) { QSqlQuery query; QString emptyStr; qint64 epochTimeDateCreated = note->creationDateTime() .toMSecsSinceEpoch(); QString content = note->content() .replace("'","''") .replace(QChar('\x0'), emptyStr); QString fullTitle = note->fullTitle() .replace("'","''") .replace(QChar('\x0'), emptyStr); QString queryStr = QString("INSERT INTO active_notes (creation_date, modification_date, deletion_date, content, full_title) " "VALUES (%1, %1, -1, '%2', '%3');") .arg(epochTimeDateCreated) .arg(content) .arg(fullTitle); query.exec(queryStr); return (query.numRowsAffected() == 1); } bool DBManager::removeNote(NoteData* note) { QSqlQuery query; QString emptyStr; int id = note->id().split('_')[1].toInt(); QString queryStr = QStringLiteral("DELETE FROM active_notes " "WHERE id=%1") .arg(id); query.exec(queryStr); bool removed = (query.numRowsAffected() == 1); qint64 epochTimeDateCreated = note->creationDateTime().toMSecsSinceEpoch(); qint64 epochTimeDateModified = note->lastModificationdateTime().toMSecsSinceEpoch(); qint64 epochTimeDateDeleted = note->deletionDateTime().toMSecsSinceEpoch(); QString content = note->content() .replace("'","''") .replace(QChar('\x0'), emptyStr); QString fullTitle = note->fullTitle() .replace("'","''") .replace(QChar('\x0'), emptyStr); queryStr = QString("INSERT INTO deleted_notes " "VALUES (%1, %2, %3, %4, '%5', '%6');") .arg(id) .arg(epochTimeDateCreated) .arg(epochTimeDateModified) .arg(epochTimeDateDeleted) .arg(content) .arg(fullTitle); query.exec(queryStr); bool addedToTrashDB = (query.numRowsAffected() == 1); return (removed && addedToTrashDB); } bool DBManager::modifyNote(NoteData* note) { QSqlQuery query; QString emptyStr; int id = note->id().split('_')[1].toInt(); qint64 epochTimeDateModified = note->lastModificationdateTime().toMSecsSinceEpoch(); QString content = note->content() .replace("'","''") .replace(QChar('\x0'), emptyStr); QString fullTitle = note->fullTitle() .replace("'","''") .replace(QChar('\x0'), emptyStr); QString queryStr = QStringLiteral("UPDATE active_notes " "SET modification_date=%1, content='%2', full_title='%3' " "WHERE id=%4") .arg(epochTimeDateModified) .arg(content) .arg(fullTitle) .arg(id); query.exec(queryStr); return (query.numRowsAffected() == 1); } bool DBManager::migrateNote(NoteData* note) { QSqlQuery query; QString emptyStr; int id = note->id().split('_')[1].toInt(); qint64 epochTimeDateCreated = note->creationDateTime().toMSecsSinceEpoch(); qint64 epochTimeDateModified = note->lastModificationdateTime().toMSecsSinceEpoch(); QString content = note->content() .replace("'","''") .replace(QChar('\x0'), emptyStr); QString fullTitle = note->fullTitle() .replace("'","''") .replace(QChar('\x0'), emptyStr); QString queryStr = QString("INSERT INTO active_notes " "VALUES (%1, %2, %3, -1, '%4', '%5');") .arg(id) .arg(epochTimeDateCreated) .arg(epochTimeDateModified) .arg(content) .arg(fullTitle); query.exec(queryStr); return (query.numRowsAffected() == 1); } bool DBManager::migrateTrash(NoteData* note) { QSqlQuery query; QString emptyStr; int id = note->id().split('_')[1].toInt(); qint64 epochTimeDateCreated = note->creationDateTime().toMSecsSinceEpoch(); qint64 epochTimeDateModified = note->lastModificationdateTime().toMSecsSinceEpoch(); qint64 epochTimeDateDeleted = note->deletionDateTime().toMSecsSinceEpoch(); QString content = note->content() .replace("'","''") .replace(QChar('\x0'), emptyStr); QString fullTitle = note->fullTitle() .replace("'","''") .replace(QChar('\x0'), emptyStr); QString queryStr = QString("INSERT INTO deleted_notes " "VALUES (%1, %2, %3, %4, '%5', '%6');") .arg(id) .arg(epochTimeDateCreated) .arg(epochTimeDateModified) .arg(epochTimeDateDeleted) .arg(content) .arg(fullTitle); query.exec(queryStr); return (query.numRowsAffected() == 1); } int DBManager::getLastRowID() { QSqlQuery query; query.exec("SELECT seq from SQLITE_SEQUENCE WHERE name='active_notes';"); query.next(); return query.value(0).toInt(); } <|endoftext|>
<commit_before>/* discovery.cpp -*- C++ -*- Rémi Attab ([email protected]), 26 Dec 2013 FreeBSD-style copyright and disclaimer apply Implementation of the node discovery database. */ #include "discovery.h" #include "pack.h" #include "lockless/bits.h" #include <set> #include <vector> #include <algorithm> #include <functional> namespace slick { /******************************************************************************/ /* ADDRESS */ /******************************************************************************/ template<> struct Pack<Address> { static size_t size(const Address& value) { return packedSizeAll(value.host, value.port); } static void pack(const Address& value, PackIt first, PackIt last) { packAll(first, last, value.host, value.port); } static Address unpack(ConstPackIt first, ConstPackIt last) { Address value; unpackAll(first, last, value.host, value.port); return std::move(value); } }; /******************************************************************************/ /* NODE */ /******************************************************************************/ bool DistributedDiscovery::Node:: operator<(const Node& other) const { size_t n = std::min(addrs.size(), other.addrs.size()); for (size_t i = 0; i < n; ++i) { if (addrs[i] < other.addrs[i]) return true; if (other.addrs[i] < addrs[i]) return false; } if (addrs.size() < other.addrs.size()) return true; if (other.addrs.size() < addrs.size()) return false; return expiration < other.expiration; } /******************************************************************************/ /* WATCH */ /******************************************************************************/ DistributedDiscovery::Watch:: Watch(WatchFn watch) : watch(std::move(watch)) { static std::atomic<WatchHandle> handleCounter{0}; handle = ++handleCounter; } /******************************************************************************/ /* LIST */ /******************************************************************************/ template<typename T> auto DistributedDiscovery::List<T>:: find(const T& value) -> iterator { auto res = std::equal_range(list.begin(), list.end(), value); return res.first == res.second ? list.end() : res.first; } template<typename T> bool DistributedDiscovery::List<T>:: count(const T& value) const { auto res = std::equal_range(list.begin(), list.end(), value); return res.first != res.second; } template<typename T> bool DistributedDiscovery::List<T>:: insert(T value) { if (count(value)) return false; list.emplace_back(std::move(value)); std::sort(list.begin(), list.end()); return true; } template<typename T> bool DistributedDiscovery::List<T>:: erase(const T& value) { auto res = std::equal_range(list.begin(), list.end(), value); if (res.first == res.second) return false; list.erase(res.first); return true; } /******************************************************************************/ /* PROTOCOL */ /******************************************************************************/ namespace msg { static const std::string Init = "_slick_disc_"; static constexpr uint32_t Version = 1; typedef uint16_t Type; static constexpr Type Keys = 1; static constexpr Type Query = 2; static constexpr Type Nodes = 3; static constexpr Type Get = 4; static constexpr Type Data = 5; } // namespace msg /******************************************************************************/ /* DISTRIBUTED DISCOVERY */ /******************************************************************************/ size_t DistributedDiscovery:: timerPeriod() { enum { BasePeriod = 60 }; std::uniform_int_distribution<size_t>dist(BasePeriod, BasePeriod * 2); return dist(rng); } DistributedDiscovery:: DistributedDiscovery(const std::vector<Address>& seed, Port port) : keyTTL_(DefaultKeyTTL), nodeTTL_(DefaultNodeTTL), rng(lockless::wall()), endpoint(port), timer(timerPeriod()) // \todo add randomness { using namespace std::placeholders; endpoint.onPayload = bind(&DistributedDiscovery::onPayload, this, _1, _2); endpoint.onNewConnection = bind(&DistributedDiscovery::onConnect, this, _1); endpoint.onLostConnection = bind(&DistributedDiscovery::onDisconnect, this, _1); poller.add(endpoint); retracts.onOperation = std::bind(&DistributedDiscovery::retract, this, _1); poller.add(retracts); publishes.onOperation = std::bind(&DistributedDiscovery::publish, this, _1, _2); poller.add(publishes); typedef void (DistributedDiscovery::*DiscoverFn) (const std::string&, Watch&&); DiscoverFn discoverFn = &DistributedDiscovery::discover; discovers.onOperation = std::bind(discoverFn, this, _1, _2); poller.add(discovers); forgets.onOperation = std::bind(&DistributedDiscovery::forget, this, _1, _2); poller.add(forgets); timer.onTimer = bind(&DistributedDiscovery::onTimer, this, _1); poller.add(timer); for (auto& addr : seed) nodes.insert(Node({ addr }, nodeTTL_)); } void DistributedDiscovery:: poll() { isPollThread.set(); poller.poll(); } void DistributedDiscovery:: shutdown() { isPollThread.unset(); retracts.poll(); publishes.poll(); discovers.poll(); forgets.poll(); } void DistributedDiscovery:: onPayload(ConnectionHandle handle, Payload&& data) { auto& conn = connections[handle]; auto it = data.cbegin(), last = data.cend(); if (!conn) it = onInit(conn, it, last); while (it != last) { msg::Type type; it = unpack(type, it, last); switch(type) { case msg::Keys: it = onKeys(conn, it, last); break; case msg::Query: it = onQuery(conn, it, last); break; case msg::Nodes: it = onNodes(conn, it, last); break; case msg::Get: it = onGet(conn, it, last); break; case msg::Data: it = onData(conn, it, last); break; default: assert(false); }; } } Discovery::WatchHandle DistributedDiscovery:: discover(const std::string& key, const WatchFn& fn) { Watch watch(fn); auto handle = watch.handle; discover(key, std::move(watch)); return handle; } void DistributedDiscovery:: discover(const std::string& key, Watch&& watch) { if (!isPollThread()) { discovers.defer(key, watch); return; } if (!watches.count(key)) { std::vector<QueryItem> items = { key }; endpoint.broadcast(packAll(msg::Query, endpoint.interfaces(), items)); } watches[key].insert(std::move(watch)); for (const auto& node : keys[key]) doGet(key, node.addrs); } void DistributedDiscovery:: forget(const std::string& key, WatchHandle handle) { if (!isPollThread()) { forgets.defer(key, handle); return; } auto& list = watches[key]; list.erase(Watch(handle)); if (list.empty()) watches.erase(key); } void DistributedDiscovery:: publish(const std::string& key, Payload&& data) { if (!isPollThread()) { publishes.defer(key, std::move(data)); return; } this->data[key] = std::move(data); std::vector<KeyItem> items; items.emplace_back(key, endpoint.interfaces(), keyTTL_); endpoint.broadcast(packAll(msg::Keys, items)); } void DistributedDiscovery:: retract(const std::string& key) { if (!isPollThread()) { retracts.defer(key); return; } data.erase(key); } void DistributedDiscovery:: onConnect(ConnectionHandle handle) { auto& conn = connections[handle]; conn.handle = handle; endpoint.send(handle, packAll(msg::Init, msg::Version)); } void DistributedDiscovery:: onDisconnect(ConnectionHandle handle) { connections.erase(handle); } ConstPackIt DistributedDiscovery:: onInit(ConnState& conn, ConstPackIt it, ConstPackIt last) { std::string init; it = unpackAll(it, last, init, conn.version); if (init != msg::Init) { endpoint.disconnect(conn.handle); return last; } assert(conn.version == msg::Version); if (!data.empty()) { std::vector<KeyItem> items; for (const auto& key : data) items.emplace_back(key.first, endpoint.interfaces(), keyTTL_); endpoint.send(conn.handle, packAll(msg::Keys, items)); } if (!watches.empty()) { std::vector<QueryItem> items; for (const auto& watch : watches) items.emplace_back(watch.first); auto msg = packAll(msg::Query, endpoint.interfaces(), items); endpoint.send(conn.handle, std::move(msg)); } if (!nodes.empty()) { std::vector<NodeItem> items; items.emplace_back(endpoint.interfaces(), nodeTTL_); double now = lockless::wall(); size_t picks = lockless::log2(nodes.size()); for (const auto& node : nodes.pickRandom(rng, picks)) items.emplace_back(node.addrs, node.ttl(now)); endpoint.send(conn.handle, packAll(msg::Nodes, items)); } return it; } ConstPackIt DistributedDiscovery:: onKeys(ConnState&, ConstPackIt it, ConstPackIt last) { std::vector<KeyItem> items; it = unpack(items, it, last); double now = lockless::wall(); std::vector<KeyItem> toForward; for (auto& item : items) { std::string key; NodeLocation node; size_t ttl; std::tie(key, node, ttl) = std::move(item); auto& list = keys[key]; Node value(node, ttl, now); auto it = list.find(value); if (it != list.end()) { it->setTTL(ttl, now); continue; } list.insert(value); toForward.emplace_back(key, node, ttl); if (watches.count(key)) doGet(key, node); } if (!toForward.empty()) endpoint.broadcast(packAll(msg::Keys, toForward)); return it; } ConstPackIt DistributedDiscovery:: onQuery(ConnState& conn, ConstPackIt it, ConstPackIt last) { NodeLocation node; std::vector<QueryItem> items; it = unpackAll(it, last, node, items); std::vector<QueryItem> toForward; for (const auto& key : items) { auto it = keys.find(key); if (it != keys.end()) { std::vector<KeyItem> items; for (const auto& node : it->second) { if (!node.ttl()) continue; items.emplace_back(key, node.addrs, node.ttl()); } endpoint.send(conn.handle, packAll(msg::Keys, items)); } else { keys[key] = List<Node>(); toForward.emplace_back(key); } } if (!toForward.empty()) endpoint.broadcast(packAll(msg::Query, toForward)); return it; } ConstPackIt DistributedDiscovery:: onNodes(ConnState&, ConstPackIt it, ConstPackIt last) { std::vector<NodeItem> items; it = unpack(items, it, last); double now = lockless::wall(); std::vector<NodeItem> toForward; for (auto& item : items) { NodeLocation node; size_t ttl; std::tie(node, ttl) = std::move(item); Node value(node, ttl, now); auto it = nodes.find(value); if (it != nodes.end()) { it->setTTL(ttl, now); continue; } nodes.insert(value); toForward.emplace_back(node, ttl); } if (!toForward.empty()) endpoint.broadcast(packAll(msg::Nodes, toForward)); return it; } void DistributedDiscovery:: doGet(const std::string& key, const std::vector<Address>& addrs) { ConnectionHandle handle = endpoint.connect(addrs); if (!handle) return; std::vector<std::string> items = { key }; endpoint.send(handle, packAll(msg::Get, items)); } ConstPackIt DistributedDiscovery:: onGet(ConnState& conn, ConstPackIt it, ConstPackIt last) { std::vector<std::string> items; it = unpack(items, it, last); std::vector<DataItem> reply; reply.reserve(items.size()); for (const auto& key : items) { auto it = data.find(key); if (it == data.end()) continue; reply.emplace_back(key, it->second); } if (!reply.empty()) endpoint.send(conn.handle, packAll(msg::Data, reply)); return it; } ConstPackIt DistributedDiscovery:: onData(ConnState&, ConstPackIt it, ConstPackIt last) { std::vector<DataItem> items; it = unpack(items, it, last); for (auto& item : items) { std::string key; Payload payload; std::tie(key, payload) = std::move(item); auto it = watches.find(key); if (it == watches.end()) continue; for (const auto& watch : it->second) watch.watch(watch.handle, payload); } return it; } void DistributedDiscovery:: onTimer(size_t) { expireNodes(nodes); expireKeys(); rotateConnections(); } void DistributedDiscovery:: expireNodes(List<Node>& list) { while (!list.empty()) { const auto& node = list.pickRandom(rng); if (node.ttl()) return; list.erase(node); } } void DistributedDiscovery:: expireKeys() { std::vector<std::string> toRemove; for (auto& key : keys) { auto& list = key.second; expireNodes(list); if (!list.empty()) continue; toRemove.emplace_back(key.first); } for (const auto& key : toRemove) keys.erase(key); } void DistributedDiscovery:: rotateConnections() { size_t targetSize = lockless::log2(nodes.size()); size_t disconnects = std::min(lockless::log2(targetSize), connections.size()); if (connections.size() - disconnects > targetSize) disconnects = connections.size() - targetSize; for (size_t i = 0; i < disconnects; ++i) { std::uniform_int_distribution<size_t> dist(0, connections.size() -1); auto it = connections.begin(); std::advance(it, dist(rng)); endpoint.disconnect(it->second.handle); } size_t connects = targetSize - connections.size(); for (const auto& node : nodes.pickRandom(rng, connects)) endpoint.connect(node.addrs); } } // slick <commit_msg>Query no longer propagates. Solves a lot of problems.<commit_after>/* discovery.cpp -*- C++ -*- Rémi Attab ([email protected]), 26 Dec 2013 FreeBSD-style copyright and disclaimer apply Implementation of the node discovery database. */ #include "discovery.h" #include "pack.h" #include "lockless/bits.h" #include <set> #include <vector> #include <algorithm> #include <functional> namespace slick { /******************************************************************************/ /* ADDRESS */ /******************************************************************************/ template<> struct Pack<Address> { static size_t size(const Address& value) { return packedSizeAll(value.host, value.port); } static void pack(const Address& value, PackIt first, PackIt last) { packAll(first, last, value.host, value.port); } static Address unpack(ConstPackIt first, ConstPackIt last) { Address value; unpackAll(first, last, value.host, value.port); return std::move(value); } }; /******************************************************************************/ /* NODE */ /******************************************************************************/ bool DistributedDiscovery::Node:: operator<(const Node& other) const { size_t n = std::min(addrs.size(), other.addrs.size()); for (size_t i = 0; i < n; ++i) { if (addrs[i] < other.addrs[i]) return true; if (other.addrs[i] < addrs[i]) return false; } if (addrs.size() < other.addrs.size()) return true; if (other.addrs.size() < addrs.size()) return false; return expiration < other.expiration; } /******************************************************************************/ /* WATCH */ /******************************************************************************/ DistributedDiscovery::Watch:: Watch(WatchFn watch) : watch(std::move(watch)) { static std::atomic<WatchHandle> handleCounter{0}; handle = ++handleCounter; } /******************************************************************************/ /* LIST */ /******************************************************************************/ template<typename T> auto DistributedDiscovery::List<T>:: find(const T& value) -> iterator { auto res = std::equal_range(list.begin(), list.end(), value); return res.first == res.second ? list.end() : res.first; } template<typename T> bool DistributedDiscovery::List<T>:: count(const T& value) const { auto res = std::equal_range(list.begin(), list.end(), value); return res.first != res.second; } template<typename T> bool DistributedDiscovery::List<T>:: insert(T value) { if (count(value)) return false; list.emplace_back(std::move(value)); std::sort(list.begin(), list.end()); return true; } template<typename T> bool DistributedDiscovery::List<T>:: erase(const T& value) { auto res = std::equal_range(list.begin(), list.end(), value); if (res.first == res.second) return false; list.erase(res.first); return true; } /******************************************************************************/ /* PROTOCOL */ /******************************************************************************/ namespace msg { static const std::string Init = "_slick_disc_"; static constexpr uint32_t Version = 1; typedef uint16_t Type; static constexpr Type Keys = 1; static constexpr Type Query = 2; static constexpr Type Nodes = 3; static constexpr Type Get = 4; static constexpr Type Data = 5; } // namespace msg /******************************************************************************/ /* DISTRIBUTED DISCOVERY */ /******************************************************************************/ size_t DistributedDiscovery:: timerPeriod() { enum { BasePeriod = 60 }; std::uniform_int_distribution<size_t>dist(BasePeriod, BasePeriod * 2); return dist(rng); } DistributedDiscovery:: DistributedDiscovery(const std::vector<Address>& seed, Port port) : keyTTL_(DefaultKeyTTL), nodeTTL_(DefaultNodeTTL), rng(lockless::wall()), endpoint(port), timer(timerPeriod()) // \todo add randomness { using namespace std::placeholders; endpoint.onPayload = bind(&DistributedDiscovery::onPayload, this, _1, _2); endpoint.onNewConnection = bind(&DistributedDiscovery::onConnect, this, _1); endpoint.onLostConnection = bind(&DistributedDiscovery::onDisconnect, this, _1); poller.add(endpoint); retracts.onOperation = std::bind(&DistributedDiscovery::retract, this, _1); poller.add(retracts); publishes.onOperation = std::bind(&DistributedDiscovery::publish, this, _1, _2); poller.add(publishes); typedef void (DistributedDiscovery::*DiscoverFn) (const std::string&, Watch&&); DiscoverFn discoverFn = &DistributedDiscovery::discover; discovers.onOperation = std::bind(discoverFn, this, _1, _2); poller.add(discovers); forgets.onOperation = std::bind(&DistributedDiscovery::forget, this, _1, _2); poller.add(forgets); timer.onTimer = bind(&DistributedDiscovery::onTimer, this, _1); poller.add(timer); for (auto& addr : seed) nodes.insert(Node({ addr }, nodeTTL_)); } void DistributedDiscovery:: poll() { isPollThread.set(); poller.poll(); } void DistributedDiscovery:: shutdown() { isPollThread.unset(); retracts.poll(); publishes.poll(); discovers.poll(); forgets.poll(); } void DistributedDiscovery:: onPayload(ConnectionHandle handle, Payload&& data) { auto& conn = connections[handle]; auto it = data.cbegin(), last = data.cend(); if (!conn) it = onInit(conn, it, last); while (it != last) { msg::Type type; it = unpack(type, it, last); switch(type) { case msg::Keys: it = onKeys(conn, it, last); break; case msg::Query: it = onQuery(conn, it, last); break; case msg::Nodes: it = onNodes(conn, it, last); break; case msg::Get: it = onGet(conn, it, last); break; case msg::Data: it = onData(conn, it, last); break; default: assert(false); }; } } Discovery::WatchHandle DistributedDiscovery:: discover(const std::string& key, const WatchFn& fn) { Watch watch(fn); auto handle = watch.handle; discover(key, std::move(watch)); return handle; } void DistributedDiscovery:: discover(const std::string& key, Watch&& watch) { if (!isPollThread()) { discovers.defer(key, watch); return; } if (!watches.count(key)) { std::vector<QueryItem> items = { key }; endpoint.broadcast(packAll(msg::Query, endpoint.interfaces(), items)); } watches[key].insert(std::move(watch)); for (const auto& node : keys[key]) doGet(key, node.addrs); } void DistributedDiscovery:: forget(const std::string& key, WatchHandle handle) { if (!isPollThread()) { forgets.defer(key, handle); return; } auto& list = watches[key]; list.erase(Watch(handle)); if (list.empty()) watches.erase(key); } void DistributedDiscovery:: publish(const std::string& key, Payload&& data) { if (!isPollThread()) { publishes.defer(key, std::move(data)); return; } this->data[key] = std::move(data); std::vector<KeyItem> items; items.emplace_back(key, endpoint.interfaces(), keyTTL_); endpoint.broadcast(packAll(msg::Keys, items)); } void DistributedDiscovery:: retract(const std::string& key) { if (!isPollThread()) { retracts.defer(key); return; } data.erase(key); } void DistributedDiscovery:: onConnect(ConnectionHandle handle) { auto& conn = connections[handle]; conn.handle = handle; endpoint.send(handle, packAll(msg::Init, msg::Version)); } void DistributedDiscovery:: onDisconnect(ConnectionHandle handle) { connections.erase(handle); } ConstPackIt DistributedDiscovery:: onInit(ConnState& conn, ConstPackIt it, ConstPackIt last) { std::string init; it = unpackAll(it, last, init, conn.version); if (init != msg::Init) { endpoint.disconnect(conn.handle); return last; } assert(conn.version == msg::Version); if (!data.empty()) { std::vector<KeyItem> items; for (const auto& key : data) items.emplace_back(key.first, endpoint.interfaces(), keyTTL_); endpoint.send(conn.handle, packAll(msg::Keys, items)); } if (!watches.empty()) { std::vector<QueryItem> items; for (const auto& watch : watches) items.emplace_back(watch.first); auto msg = packAll(msg::Query, endpoint.interfaces(), items); endpoint.send(conn.handle, std::move(msg)); } if (!nodes.empty()) { std::vector<NodeItem> items; items.emplace_back(endpoint.interfaces(), nodeTTL_); double now = lockless::wall(); size_t picks = lockless::log2(nodes.size()); for (const auto& node : nodes.pickRandom(rng, picks)) items.emplace_back(node.addrs, node.ttl(now)); endpoint.send(conn.handle, packAll(msg::Nodes, items)); } return it; } ConstPackIt DistributedDiscovery:: onKeys(ConnState&, ConstPackIt it, ConstPackIt last) { std::vector<KeyItem> items; it = unpack(items, it, last); double now = lockless::wall(); std::vector<KeyItem> toForward; for (auto& item : items) { std::string key; NodeLocation node; size_t ttl; std::tie(key, node, ttl) = std::move(item); auto& list = keys[key]; Node value(node, ttl, now); auto it = list.find(value); if (it != list.end()) { it->setTTL(ttl, now); continue; } list.insert(value); toForward.emplace_back(key, node, ttl); if (watches.count(key)) doGet(key, node); } if (!toForward.empty()) endpoint.broadcast(packAll(msg::Keys, toForward)); return it; } ConstPackIt DistributedDiscovery:: onQuery(ConnState& conn, ConstPackIt it, ConstPackIt last) { NodeLocation node; std::vector<QueryItem> items; it = unpackAll(it, last, node, items); for (const auto& key : items) { auto it = keys.find(key); if (it == keys.end()) continue; std::vector<KeyItem> items; for (const auto& node : it->second) { if (!node.ttl()) continue; items.emplace_back(key, node.addrs, node.ttl()); } endpoint.send(conn.handle, packAll(msg::Keys, items)); } return it; } ConstPackIt DistributedDiscovery:: onNodes(ConnState&, ConstPackIt it, ConstPackIt last) { std::vector<NodeItem> items; it = unpack(items, it, last); double now = lockless::wall(); std::vector<NodeItem> toForward; for (auto& item : items) { NodeLocation node; size_t ttl; std::tie(node, ttl) = std::move(item); Node value(node, ttl, now); auto it = nodes.find(value); if (it != nodes.end()) { it->setTTL(ttl, now); continue; } nodes.insert(value); toForward.emplace_back(node, ttl); } if (!toForward.empty()) endpoint.broadcast(packAll(msg::Nodes, toForward)); return it; } void DistributedDiscovery:: doGet(const std::string& key, const std::vector<Address>& addrs) { ConnectionHandle handle = endpoint.connect(addrs); if (!handle) return; std::vector<std::string> items = { key }; endpoint.send(handle, packAll(msg::Get, items)); } ConstPackIt DistributedDiscovery:: onGet(ConnState& conn, ConstPackIt it, ConstPackIt last) { std::vector<std::string> items; it = unpack(items, it, last); std::vector<DataItem> reply; reply.reserve(items.size()); for (const auto& key : items) { auto it = data.find(key); if (it == data.end()) continue; reply.emplace_back(key, it->second); } if (!reply.empty()) endpoint.send(conn.handle, packAll(msg::Data, reply)); return it; } ConstPackIt DistributedDiscovery:: onData(ConnState&, ConstPackIt it, ConstPackIt last) { std::vector<DataItem> items; it = unpack(items, it, last); for (auto& item : items) { std::string key; Payload payload; std::tie(key, payload) = std::move(item); auto it = watches.find(key); if (it == watches.end()) continue; for (const auto& watch : it->second) watch.watch(watch.handle, payload); } return it; } void DistributedDiscovery:: onTimer(size_t) { expireNodes(nodes); expireKeys(); rotateConnections(); } void DistributedDiscovery:: expireNodes(List<Node>& list) { while (!list.empty()) { const auto& node = list.pickRandom(rng); if (node.ttl()) return; list.erase(node); } } void DistributedDiscovery:: expireKeys() { std::vector<std::string> toRemove; for (auto& key : keys) { auto& list = key.second; expireNodes(list); if (!list.empty()) continue; toRemove.emplace_back(key.first); } for (const auto& key : toRemove) keys.erase(key); } void DistributedDiscovery:: rotateConnections() { size_t targetSize = lockless::log2(nodes.size()); size_t disconnects = std::min(lockless::log2(targetSize), connections.size()); if (connections.size() - disconnects > targetSize) disconnects = connections.size() - targetSize; for (size_t i = 0; i < disconnects; ++i) { std::uniform_int_distribution<size_t> dist(0, connections.size() -1); auto it = connections.begin(); std::advance(it, dist(rng)); endpoint.disconnect(it->second.handle); } size_t connects = targetSize - connections.size(); for (const auto& node : nodes.pickRandom(rng, connects)) endpoint.connect(node.addrs); } } // slick <|endoftext|>
<commit_before>#include <signal.h> #include <glog/logging.h> #include <iostream> #include <string> #include <sstream> #include <boost/bind.hpp> #include <mesos/executor.hpp> #include <process/process.hpp> #include <process/protobuf.hpp> #include "common/fatal.hpp" #include "common/lock.hpp" #include "common/logging.hpp" #include "common/type_utils.hpp" #include "common/uuid.hpp" #include "messages/messages.hpp" using namespace mesos; using namespace mesos::internal; using boost::bind; using boost::cref; using process::UPID; using std::string; namespace mesos { namespace internal { class ExecutorProcess : public ProtobufProcess<ExecutorProcess> { public: ExecutorProcess(const UPID& _slave, MesosExecutorDriver* _driver, Executor* _executor, const FrameworkID& _frameworkId, const ExecutorID& _executorId, bool _local) : slave(_slave), driver(_driver), executor(_executor), frameworkId(_frameworkId), executorId(_executorId), local(_local) { installProtobufHandler<ExecutorRegisteredMessage>( &ExecutorProcess::registered, &ExecutorRegisteredMessage::args); installProtobufHandler<RunTaskMessage>( &ExecutorProcess::runTask, &RunTaskMessage::task); installProtobufHandler<KillTaskMessage>( &ExecutorProcess::killTask, &KillTaskMessage::task_id); installProtobufHandler<FrameworkToExecutorMessage>( &ExecutorProcess::frameworkMessage, &FrameworkToExecutorMessage::slave_id, &FrameworkToExecutorMessage::framework_id, &FrameworkToExecutorMessage::executor_id, &FrameworkToExecutorMessage::data); installProtobufHandler<ShutdownMessage>( &ExecutorProcess::shutdown); installMessageHandler(process::EXITED, &ExecutorProcess::exited); } virtual ~ExecutorProcess() {} protected: virtual void operator () () { VLOG(1) << "Executor started at: " << self(); link(slave); // Register with slave. RegisterExecutorMessage message; message.mutable_framework_id()->MergeFrom(frameworkId); message.mutable_executor_id()->MergeFrom(executorId); send(slave, message); do { if (serve() == process::TERMINATE) break; } while (true); } void registered(const ExecutorArgs& args) { VLOG(1) << "Executor registered on slave " << args.slave_id(); slaveId = args.slave_id(); process::invoke(bind(&Executor::init, executor, driver, cref(args))); } void runTask(const TaskDescription& task) { VLOG(1) << "Executor asked to run task '" << task.task_id() << "'"; process::invoke(bind(&Executor::launchTask, executor, driver, cref(task))); } void killTask(const TaskID& taskId) { VLOG(1) << "Executor asked to kill task '" << taskId << "'"; process::invoke(bind(&Executor::killTask, executor, driver, cref(taskId))); } void frameworkMessage(const SlaveID& slaveId, const FrameworkID& frameworkId, const ExecutorID& executorId, const string& data) { VLOG(1) << "Executor received framework message"; process::invoke(bind(&Executor::frameworkMessage, executor, driver, cref(data))); } void shutdown() { VLOG(1) << "Executor asked to shutdown"; // TODO(benh): Any need to invoke driver.stop? process::invoke(bind(&Executor::shutdown, executor, driver)); if (!local) { exit(0); } else { process::terminate(self()); } } void exited() { VLOG(1) << "Slave exited, trying to shutdown"; // TODO: Pass an argument to shutdown to tell it this is abnormal? process::invoke(bind(&Executor::shutdown, executor, driver)); // This is a pretty bad state ... no slave is left. Rather // than exit lets kill our process group (which includes // ourself) hoping to clean up any processes this executor // launched itself. // TODO(benh): Maybe do a SIGTERM and then later do a SIGKILL? if (!local) { killpg(0, SIGKILL); } else { process::terminate(self()); } } private: friend class mesos::MesosExecutorDriver; UPID slave; MesosExecutorDriver* driver; Executor* executor; FrameworkID frameworkId; ExecutorID executorId; SlaveID slaveId; bool local; }; }} // namespace mesos { namespace internal { // Implementation of C++ API. MesosExecutorDriver::MesosExecutorDriver(Executor* _executor) : executor(_executor), running(false) { // Create mutex and condition variable pthread_mutexattr_t attr; pthread_mutexattr_init(&attr); pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE); pthread_mutex_init(&mutex, &attr); pthread_mutexattr_destroy(&attr); pthread_cond_init(&cond, 0); // TODO(benh): Initialize glog. // Initialize libprocess library (but not glog, done above). process::initialize(false); } MesosExecutorDriver::~MesosExecutorDriver() { // Just as in SchedulerProcess, we might wait here indefinitely if // MesosExecutorDriver::stop has not been invoked. process::wait(process->self()); delete process; pthread_mutex_destroy(&mutex); pthread_cond_destroy(&cond); } int MesosExecutorDriver::start() { Lock lock(&mutex); if (running) { return -1; } // Set stream buffering mode to flush on newlines so that we capture logs // from user processes even when output is redirected to a file. setvbuf(stdout, 0, _IOLBF, 0); setvbuf(stderr, 0, _IOLBF, 0); bool local; UPID slave; FrameworkID frameworkId; ExecutorID executorId; char* value; std::istringstream iss; /* Check if this is local (for example, for testing). */ value = getenv("MESOS_LOCAL"); if (value != NULL) { local = true; } else { local = false; } /* Get slave PID from environment. */ value = getenv("MESOS_SLAVE_PID"); if (value == NULL) { fatal("expecting MESOS_SLAVE_PID in environment"); } slave = UPID(value); if (!slave) { fatal("cannot parse MESOS_SLAVE_PID"); } /* Get framework ID from environment. */ value = getenv("MESOS_FRAMEWORK_ID"); if (value == NULL) { fatal("expecting MESOS_FRAMEWORK_ID in environment"); } frameworkId.set_value(value); /* Get executor ID from environment. */ value = getenv("MESOS_EXECUTOR_ID"); if (value == NULL) { fatal("expecting MESOS_EXECUTOR_ID in environment"); } executorId.set_value(value); process = new ExecutorProcess(slave, this, executor, frameworkId, executorId, local); process::spawn(process); running = true; return 0; } int MesosExecutorDriver::stop() { Lock lock(&mutex); if (!running) { return -1; } CHECK(process != NULL); process::terminate(process->self()); running = false; pthread_cond_signal(&cond); return 0; } int MesosExecutorDriver::join() { Lock lock(&mutex); while (running) { pthread_cond_wait(&cond, &mutex); } return 0; } int MesosExecutorDriver::run() { int ret = start(); return ret != 0 ? ret : join(); } int MesosExecutorDriver::sendStatusUpdate(const TaskStatus& status) { Lock lock(&mutex); if (!running) { //executor->error(this, EINVAL, "Executor has exited"); return -1; } CHECK(process != NULL); // TODO(benh): Do a dispatch to Executor first? StatusUpdateMessage message; StatusUpdate* update = message.mutable_update(); update->mutable_framework_id()->MergeFrom(process->frameworkId); update->mutable_executor_id()->MergeFrom(process->executorId); update->mutable_slave_id()->MergeFrom(process->slaveId); update->mutable_status()->MergeFrom(status); update->set_timestamp(process->elapsedTime()); update->set_uuid(UUID::random().toBytes()); message.set_reliable(false); process->send(process->slave, message); return 0; } int MesosExecutorDriver::sendFrameworkMessage(const string& data) { Lock lock(&mutex); if (!running) { //executor->error(this, EINVAL, "Executor has exited"); return -1; } CHECK(process != NULL); // TODO(benh): Do a dispatch to Executor first? ExecutorToFrameworkMessage message; message.mutable_slave_id()->MergeFrom(process->slaveId); message.mutable_framework_id()->MergeFrom(process->frameworkId); message.mutable_executor_id()->MergeFrom(process->executorId); message.set_data(data); process->send(process->slave, message); return 0; } <commit_msg>Made exec.cpp use namespace process like the others for readability.<commit_after>#include <signal.h> #include <glog/logging.h> #include <iostream> #include <string> #include <sstream> #include <boost/bind.hpp> #include <mesos/executor.hpp> #include <process/dispatch.hpp> #include <process/process.hpp> #include <process/protobuf.hpp> #include "common/fatal.hpp" #include "common/lock.hpp" #include "common/logging.hpp" #include "common/type_utils.hpp" #include "common/uuid.hpp" #include "messages/messages.hpp" using namespace mesos; using namespace mesos::internal; using namespace process; using boost::bind; using boost::cref; using std::string; namespace mesos { namespace internal { class ExecutorProcess : public ProtobufProcess<ExecutorProcess> { public: ExecutorProcess(const UPID& _slave, MesosExecutorDriver* _driver, Executor* _executor, const FrameworkID& _frameworkId, const ExecutorID& _executorId, bool _local) : slave(_slave), driver(_driver), executor(_executor), frameworkId(_frameworkId), executorId(_executorId), local(_local) { installProtobufHandler<ExecutorRegisteredMessage>( &ExecutorProcess::registered, &ExecutorRegisteredMessage::args); installProtobufHandler<RunTaskMessage>( &ExecutorProcess::runTask, &RunTaskMessage::task); installProtobufHandler<KillTaskMessage>( &ExecutorProcess::killTask, &KillTaskMessage::task_id); installProtobufHandler<FrameworkToExecutorMessage>( &ExecutorProcess::frameworkMessage, &FrameworkToExecutorMessage::slave_id, &FrameworkToExecutorMessage::framework_id, &FrameworkToExecutorMessage::executor_id, &FrameworkToExecutorMessage::data); installProtobufHandler<ShutdownMessage>( &ExecutorProcess::shutdown); installMessageHandler(EXITED, &ExecutorProcess::exited); } virtual ~ExecutorProcess() {} protected: virtual void operator () () { VLOG(1) << "Executor started at: " << self(); link(slave); // Register with slave. RegisterExecutorMessage message; message.mutable_framework_id()->MergeFrom(frameworkId); message.mutable_executor_id()->MergeFrom(executorId); send(slave, message); do { if (serve() == TERMINATE) break; } while (true); } void registered(const ExecutorArgs& args) { VLOG(1) << "Executor registered on slave " << args.slave_id(); slaveId = args.slave_id(); invoke(bind(&Executor::init, executor, driver, cref(args))); } void runTask(const TaskDescription& task) { VLOG(1) << "Executor asked to run task '" << task.task_id() << "'"; invoke(bind(&Executor::launchTask, executor, driver, cref(task))); } void killTask(const TaskID& taskId) { VLOG(1) << "Executor asked to kill task '" << taskId << "'"; invoke(bind(&Executor::killTask, executor, driver, cref(taskId))); } void frameworkMessage(const SlaveID& slaveId, const FrameworkID& frameworkId, const ExecutorID& executorId, const string& data) { VLOG(1) << "Executor received framework message"; invoke(bind(&Executor::frameworkMessage, executor, driver, cref(data))); } void shutdown() { VLOG(1) << "Executor asked to shutdown"; // TODO(benh): Any need to invoke driver.stop? invoke(bind(&Executor::shutdown, executor, driver)); if (!local) { exit(0); } else { terminate(this); } } void exited() { VLOG(1) << "Slave exited, trying to shutdown"; // TODO: Pass an argument to shutdown to tell it this is abnormal? invoke(bind(&Executor::shutdown, executor, driver)); // This is a pretty bad state ... no slave is left. Rather // than exit lets kill our process group (which includes // ourself) hoping to clean up any processes this executor // launched itself. // TODO(benh): Maybe do a SIGTERM and then later do a SIGKILL? if (!local) { killpg(0, SIGKILL); } else { terminate(this); } } void sendStatusUpdate(const TaskStatus& status) { StatusUpdateMessage message; StatusUpdate* update = message.mutable_update(); update->mutable_framework_id()->MergeFrom(frameworkId); update->mutable_executor_id()->MergeFrom(executorId); update->mutable_slave_id()->MergeFrom(slaveId); update->mutable_status()->MergeFrom(status); update->set_timestamp(elapsedTime()); update->set_uuid(UUID::random().toBytes()); message.set_reliable(false); send(slave, message); } void sendFrameworkMessage(const string& data) { ExecutorToFrameworkMessage message; message.mutable_slave_id()->MergeFrom(slaveId); message.mutable_framework_id()->MergeFrom(frameworkId); message.mutable_executor_id()->MergeFrom(executorId); message.set_data(data); send(slave, message); } private: friend class mesos::MesosExecutorDriver; UPID slave; MesosExecutorDriver* driver; Executor* executor; FrameworkID frameworkId; ExecutorID executorId; SlaveID slaveId; bool local; }; }} // namespace mesos { namespace internal { // Implementation of C++ API. MesosExecutorDriver::MesosExecutorDriver(Executor* _executor) : executor(_executor), running(false) { // Create mutex and condition variable pthread_mutexattr_t attr; pthread_mutexattr_init(&attr); pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE); pthread_mutex_init(&mutex, &attr); pthread_mutexattr_destroy(&attr); pthread_cond_init(&cond, 0); // TODO(benh): Initialize glog. // Initialize libprocess library (but not glog, done above). process::initialize(false); } MesosExecutorDriver::~MesosExecutorDriver() { // Just as in SchedulerProcess, we might wait here indefinitely if // MesosExecutorDriver::stop has not been invoked. wait(process); delete process; pthread_mutex_destroy(&mutex); pthread_cond_destroy(&cond); } int MesosExecutorDriver::start() { Lock lock(&mutex); if (running) { return -1; } // Set stream buffering mode to flush on newlines so that we capture logs // from user processes even when output is redirected to a file. setvbuf(stdout, 0, _IOLBF, 0); setvbuf(stderr, 0, _IOLBF, 0); bool local; UPID slave; FrameworkID frameworkId; ExecutorID executorId; char* value; std::istringstream iss; /* Check if this is local (for example, for testing). */ value = getenv("MESOS_LOCAL"); if (value != NULL) { local = true; } else { local = false; } /* Get slave PID from environment. */ value = getenv("MESOS_SLAVE_PID"); if (value == NULL) { fatal("expecting MESOS_SLAVE_PID in environment"); } slave = UPID(value); if (!slave) { fatal("cannot parse MESOS_SLAVE_PID"); } /* Get framework ID from environment. */ value = getenv("MESOS_FRAMEWORK_ID"); if (value == NULL) { fatal("expecting MESOS_FRAMEWORK_ID in environment"); } frameworkId.set_value(value); /* Get executor ID from environment. */ value = getenv("MESOS_EXECUTOR_ID"); if (value == NULL) { fatal("expecting MESOS_EXECUTOR_ID in environment"); } executorId.set_value(value); process = new ExecutorProcess(slave, this, executor, frameworkId, executorId, local); spawn(process); running = true; return 0; } int MesosExecutorDriver::stop() { Lock lock(&mutex); if (!running) { return -1; } CHECK(process != NULL); terminate(process); running = false; pthread_cond_signal(&cond); return 0; } int MesosExecutorDriver::join() { Lock lock(&mutex); while (running) { pthread_cond_wait(&cond, &mutex); } return 0; } int MesosExecutorDriver::run() { int ret = start(); return ret != 0 ? ret : join(); } int MesosExecutorDriver::sendStatusUpdate(const TaskStatus& status) { Lock lock(&mutex); if (!running) { //executor->error(this, EINVAL, "Executor has exited"); return -1; } CHECK(process != NULL); dispatch(process, &ExecutorProcess::sendStatusUpdate, status); return 0; } int MesosExecutorDriver::sendFrameworkMessage(const string& data) { Lock lock(&mutex); if (!running) { //executor->error(this, EINVAL, "Executor has exited"); return -1; } CHECK(process != NULL); dispatch(process, &ExecutorProcess::sendFrameworkMessage, data); return 0; } <|endoftext|>
<commit_before>/* Copyright (c) 2006-2014, 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. */ #include <boost/version.hpp> #include <boost/bind.hpp> #include "libtorrent/assert.hpp" #include "libtorrent/file_pool.hpp" #include "libtorrent/error_code.hpp" #include "libtorrent/file_storage.hpp" // for file_entry namespace libtorrent { file_pool::file_pool(int size) : m_size(size) , m_low_prio_io(true) { } file_pool::~file_pool() { } #ifdef TORRENT_WINDOWS void set_low_priority(file_handle const& f) { // file prio is only supported on vista and up // so load the functions dynamically typedef enum _FILE_INFO_BY_HANDLE_CLASS { FileBasicInfo, FileStandardInfo, FileNameInfo, FileRenameInfo, FileDispositionInfo, FileAllocationInfo, FileEndOfFileInfo, FileStreamInfo, FileCompressionInfo, FileAttributeTagInfo, FileIdBothDirectoryInfo, FileIdBothDirectoryRestartInfo, FileIoPriorityHintInfo, FileRemoteProtocolInfo, MaximumFileInfoByHandleClass } FILE_INFO_BY_HANDLE_CLASS, *PFILE_INFO_BY_HANDLE_CLASS; typedef enum _PRIORITY_HINT { IoPriorityHintVeryLow = 0, IoPriorityHintLow, IoPriorityHintNormal, MaximumIoPriorityHintType } PRIORITY_HINT; typedef struct _FILE_IO_PRIORITY_HINT_INFO { PRIORITY_HINT PriorityHint; } FILE_IO_PRIORITY_HINT_INFO, *PFILE_IO_PRIORITY_HINT_INFO; typedef BOOL (WINAPI *SetFileInformationByHandle_t)(HANDLE hFile, FILE_INFO_BY_HANDLE_CLASS FileInformationClass, LPVOID lpFileInformation, DWORD dwBufferSize); static SetFileInformationByHandle_t SetFileInformationByHandle = NULL; static bool failed_kernel_load = false; if (failed_kernel_load) return; if (SetFileInformationByHandle == NULL) { HMODULE kernel32 = LoadLibraryA("kernel32.dll"); if (kernel32 == NULL) { failed_kernel_load = true; return; } SetFileInformationByHandle = (SetFileInformationByHandle_t)GetProcAddress(kernel32, "SetFileInformationByHandle"); if (SetFileInformationByHandle == NULL) { failed_kernel_load = true; return; } } TORRENT_ASSERT(SetFileInformationByHandle); FILE_IO_PRIORITY_HINT_INFO io_hint; io_hint.PriorityHint = IoPriorityHintLow; SetFileInformationByHandle(f->native_handle(), FileIoPriorityHintInfo, &io_hint, sizeof(io_hint)); } #endif // TORRENT_WINDOWS file_handle file_pool::open_file(void* st, std::string const& p , int file_index, file_storage const& fs, int m, error_code& ec) { mutex::scoped_lock l(m_mutex); #if TORRENT_USE_ASSERTS // we're not allowed to open a file // from a deleted storage! TORRENT_ASSERT(std::find(m_deleted_storages.begin(), m_deleted_storages.end(), std::make_pair(fs.name(), (void const*)&fs)) == m_deleted_storages.end()); #endif TORRENT_ASSERT(st != 0); TORRENT_ASSERT(is_complete(p)); TORRENT_ASSERT((m & file::rw_mask) == file::read_only || (m & file::rw_mask) == file::read_write); file_set::iterator i = m_files.find(std::make_pair(st, file_index)); if (i != m_files.end()) { lru_file_entry& e = i->second; e.last_use = time_now(); if (e.key != st && ((e.mode & file::rw_mask) != file::read_only || (m & file::rw_mask) != file::read_only)) { // this means that another instance of the storage // is using the exact same file. #if BOOST_VERSION >= 103500 ec = errors::file_collision; #endif return file_handle(); } e.key = st; // if we asked for a file in write mode, // and the cached file is is not opened in // write mode, re-open it if ((((e.mode & file::rw_mask) != file::read_write) && ((m & file::rw_mask) == file::read_write)) || (e.mode & file::random_access) != (m & file::random_access)) { // close the file before we open it with // the new read/write privilages, since windows may // file opening a file twice. However, since there may // be outstanding operations on it, we can't close the // file, we can only delete our reference to it. // if this is the only reference to the file, it will be closed e.file_ptr = boost::make_shared<file>(); std::string full_path = fs.file_path(file_index, p); if (!e.file_ptr->open(full_path, m, ec)) { m_files.erase(i); return file_handle(); } #ifdef TORRENT_WINDOWS if (m_low_prio_io) set_low_priority(e.file_ptr); #endif TORRENT_ASSERT(e.file_ptr->is_open()); e.mode = m; } return e.file_ptr; } lru_file_entry e; e.file_ptr = boost::make_shared<file>(); if (!e.file_ptr) { ec = error_code(ENOMEM, get_posix_category()); return e.file_ptr; } std::string full_path = fs.file_path(file_index, p); if (!e.file_ptr->open(full_path, m, ec)) return file_handle(); #ifdef TORRENT_WINDOWS if (m_low_prio_io) set_low_priority(e.file_ptr); #endif e.mode = m; e.key = st; m_files.insert(std::make_pair(std::make_pair(st, file_index), e)); TORRENT_ASSERT(e.file_ptr->is_open()); file_handle file_ptr = e.file_ptr; // the file is not in our cache if ((int)m_files.size() >= m_size) { // the file cache is at its maximum size, close // the least recently used (lru) file from it remove_oldest(l); } return file_ptr; } void file_pool::get_status(std::vector<pool_file_status>* files, void* st) const { mutex::scoped_lock l(m_mutex); file_set::const_iterator start = m_files.lower_bound(std::make_pair(st, 0)); file_set::const_iterator end = m_files.upper_bound(std::make_pair(st, INT_MAX)); for (file_set::const_iterator i = start; i != end; ++i) { pool_file_status s; s.file_index = i->first.second; s.open_mode = i->second.mode; s.last_use = i->second.last_use; files->push_back(s); } } void file_pool::remove_oldest(mutex::scoped_lock& l) { file_set::iterator i = std::min_element(m_files.begin(), m_files.end() , boost::bind(&lru_file_entry::last_use, boost::bind(&file_set::value_type::second, _1)) < boost::bind(&lru_file_entry::last_use, boost::bind(&file_set::value_type::second, _2))); if (i == m_files.end()) return; file_handle file_ptr = i->second.file_ptr; m_files.erase(i); // closing a file may be long running operation (mac os x) l.unlock(); file_ptr.reset(); l.lock(); } void file_pool::release(void* st, int file_index) { mutex::scoped_lock l(m_mutex); file_set::iterator i = m_files.find(std::make_pair(st, file_index)); if (i == m_files.end()) return; file_handle file_ptr = i->second.file_ptr; m_files.erase(i); // closing a file may be long running operation (mac os x) l.unlock(); file_ptr.reset(); } // closes files belonging to the specified // storage. If 0 is passed, all files are closed void file_pool::release(void* st) { mutex::scoped_lock l(m_mutex); if (st == 0) { file_set tmp; tmp.swap(m_files); l.unlock(); return; } std::vector<file_handle> to_close; for (file_set::iterator i = m_files.begin(); i != m_files.end();) { if (i->second.key == st) { to_close.push_back(i->second.file_ptr); m_files.erase(i++); } else ++i; } l.unlock(); // the files are closed here } #if TORRENT_USE_ASSERTS void file_pool::mark_deleted(file_storage const& fs) { mutex::scoped_lock l(m_mutex); m_deleted_storages.push_back(std::make_pair(fs.name(), (void const*)&fs)); if(m_deleted_storages.size() > 100) m_deleted_storages.erase(m_deleted_storages.begin()); } bool file_pool::assert_idle_files(void* st) const { mutex::scoped_lock l(m_mutex); for (file_set::const_iterator i = m_files.begin(); i != m_files.end(); ++i) { if (i->second.key == st && !i->second.file_ptr.unique()) return false; } return true; } #endif void file_pool::resize(int size) { mutex::scoped_lock l(m_mutex); TORRENT_ASSERT(size > 0); if (size == m_size) return; m_size = size; if (int(m_files.size()) <= m_size) return; // close the least recently used files while (int(m_files.size()) > m_size) remove_oldest(l); } } <commit_msg>move closing of files outside of file pool mutex<commit_after>/* Copyright (c) 2006-2014, 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. */ #include <boost/version.hpp> #include <boost/bind.hpp> #include "libtorrent/assert.hpp" #include "libtorrent/file_pool.hpp" #include "libtorrent/error_code.hpp" #include "libtorrent/file_storage.hpp" // for file_entry namespace libtorrent { file_pool::file_pool(int size) : m_size(size) , m_low_prio_io(true) { } file_pool::~file_pool() { } #ifdef TORRENT_WINDOWS void set_low_priority(file_handle const& f) { // file prio is only supported on vista and up // so load the functions dynamically typedef enum _FILE_INFO_BY_HANDLE_CLASS { FileBasicInfo, FileStandardInfo, FileNameInfo, FileRenameInfo, FileDispositionInfo, FileAllocationInfo, FileEndOfFileInfo, FileStreamInfo, FileCompressionInfo, FileAttributeTagInfo, FileIdBothDirectoryInfo, FileIdBothDirectoryRestartInfo, FileIoPriorityHintInfo, FileRemoteProtocolInfo, MaximumFileInfoByHandleClass } FILE_INFO_BY_HANDLE_CLASS, *PFILE_INFO_BY_HANDLE_CLASS; typedef enum _PRIORITY_HINT { IoPriorityHintVeryLow = 0, IoPriorityHintLow, IoPriorityHintNormal, MaximumIoPriorityHintType } PRIORITY_HINT; typedef struct _FILE_IO_PRIORITY_HINT_INFO { PRIORITY_HINT PriorityHint; } FILE_IO_PRIORITY_HINT_INFO, *PFILE_IO_PRIORITY_HINT_INFO; typedef BOOL (WINAPI *SetFileInformationByHandle_t)(HANDLE hFile, FILE_INFO_BY_HANDLE_CLASS FileInformationClass, LPVOID lpFileInformation, DWORD dwBufferSize); static SetFileInformationByHandle_t SetFileInformationByHandle = NULL; static bool failed_kernel_load = false; if (failed_kernel_load) return; if (SetFileInformationByHandle == NULL) { HMODULE kernel32 = LoadLibraryA("kernel32.dll"); if (kernel32 == NULL) { failed_kernel_load = true; return; } SetFileInformationByHandle = (SetFileInformationByHandle_t)GetProcAddress(kernel32, "SetFileInformationByHandle"); if (SetFileInformationByHandle == NULL) { failed_kernel_load = true; return; } } TORRENT_ASSERT(SetFileInformationByHandle); FILE_IO_PRIORITY_HINT_INFO io_hint; io_hint.PriorityHint = IoPriorityHintLow; SetFileInformationByHandle(f->native_handle(), FileIoPriorityHintInfo, &io_hint, sizeof(io_hint)); } #endif // TORRENT_WINDOWS file_handle file_pool::open_file(void* st, std::string const& p , int file_index, file_storage const& fs, int m, error_code& ec) { // potentially used to hold a reference to a file object that's // about to be destructed. If we have such object we assign it to // this member to be destructed after we release the mutex. On some // operating systems (such as OSX) closing a file may take a long // time. We don't want to hold the mutex for that. file_handle defer_destruction; mutex::scoped_lock l(m_mutex); #if TORRENT_USE_ASSERTS // we're not allowed to open a file // from a deleted storage! TORRENT_ASSERT(std::find(m_deleted_storages.begin(), m_deleted_storages.end(), std::make_pair(fs.name(), (void const*)&fs)) == m_deleted_storages.end()); #endif TORRENT_ASSERT(st != 0); TORRENT_ASSERT(is_complete(p)); TORRENT_ASSERT((m & file::rw_mask) == file::read_only || (m & file::rw_mask) == file::read_write); file_set::iterator i = m_files.find(std::make_pair(st, file_index)); if (i != m_files.end()) { lru_file_entry& e = i->second; e.last_use = time_now(); if (e.key != st && ((e.mode & file::rw_mask) != file::read_only || (m & file::rw_mask) != file::read_only)) { // this means that another instance of the storage // is using the exact same file. #if BOOST_VERSION >= 103500 ec = errors::file_collision; #endif return file_handle(); } e.key = st; // if we asked for a file in write mode, // and the cached file is is not opened in // write mode, re-open it if ((((e.mode & file::rw_mask) != file::read_write) && ((m & file::rw_mask) == file::read_write)) || (e.mode & file::random_access) != (m & file::random_access)) { // close the file before we open it with // the new read/write privilages, since windows may // file opening a file twice. However, since there may // be outstanding operations on it, we can't close the // file, we can only delete our reference to it. // if this is the only reference to the file, it will be closed defer_destruction = e.file_ptr; e.file_ptr = boost::make_shared<file>(); std::string full_path = fs.file_path(file_index, p); if (!e.file_ptr->open(full_path, m, ec)) { m_files.erase(i); return file_handle(); } #ifdef TORRENT_WINDOWS if (m_low_prio_io) set_low_priority(e.file_ptr); #endif TORRENT_ASSERT(e.file_ptr->is_open()); e.mode = m; } return e.file_ptr; } lru_file_entry e; e.file_ptr = boost::make_shared<file>(); if (!e.file_ptr) { ec = error_code(ENOMEM, get_posix_category()); return e.file_ptr; } std::string full_path = fs.file_path(file_index, p); if (!e.file_ptr->open(full_path, m, ec)) return file_handle(); #ifdef TORRENT_WINDOWS if (m_low_prio_io) set_low_priority(e.file_ptr); #endif e.mode = m; e.key = st; m_files.insert(std::make_pair(std::make_pair(st, file_index), e)); TORRENT_ASSERT(e.file_ptr->is_open()); file_handle file_ptr = e.file_ptr; // the file is not in our cache if ((int)m_files.size() >= m_size) { // the file cache is at its maximum size, close // the least recently used (lru) file from it remove_oldest(l); } return file_ptr; } void file_pool::get_status(std::vector<pool_file_status>* files, void* st) const { mutex::scoped_lock l(m_mutex); file_set::const_iterator start = m_files.lower_bound(std::make_pair(st, 0)); file_set::const_iterator end = m_files.upper_bound(std::make_pair(st, INT_MAX)); for (file_set::const_iterator i = start; i != end; ++i) { pool_file_status s; s.file_index = i->first.second; s.open_mode = i->second.mode; s.last_use = i->second.last_use; files->push_back(s); } } void file_pool::remove_oldest(mutex::scoped_lock& l) { file_set::iterator i = std::min_element(m_files.begin(), m_files.end() , boost::bind(&lru_file_entry::last_use, boost::bind(&file_set::value_type::second, _1)) < boost::bind(&lru_file_entry::last_use, boost::bind(&file_set::value_type::second, _2))); if (i == m_files.end()) return; file_handle file_ptr = i->second.file_ptr; m_files.erase(i); // closing a file may be long running operation (mac os x) l.unlock(); file_ptr.reset(); l.lock(); } void file_pool::release(void* st, int file_index) { mutex::scoped_lock l(m_mutex); file_set::iterator i = m_files.find(std::make_pair(st, file_index)); if (i == m_files.end()) return; file_handle file_ptr = i->second.file_ptr; m_files.erase(i); // closing a file may be long running operation (mac os x) l.unlock(); file_ptr.reset(); } // closes files belonging to the specified // storage. If 0 is passed, all files are closed void file_pool::release(void* st) { mutex::scoped_lock l(m_mutex); if (st == 0) { file_set tmp; tmp.swap(m_files); l.unlock(); return; } std::vector<file_handle> to_close; for (file_set::iterator i = m_files.begin(); i != m_files.end();) { if (i->second.key == st) { to_close.push_back(i->second.file_ptr); m_files.erase(i++); } else ++i; } l.unlock(); // the files are closed here } #if TORRENT_USE_ASSERTS void file_pool::mark_deleted(file_storage const& fs) { mutex::scoped_lock l(m_mutex); m_deleted_storages.push_back(std::make_pair(fs.name(), (void const*)&fs)); if(m_deleted_storages.size() > 100) m_deleted_storages.erase(m_deleted_storages.begin()); } bool file_pool::assert_idle_files(void* st) const { mutex::scoped_lock l(m_mutex); for (file_set::const_iterator i = m_files.begin(); i != m_files.end(); ++i) { if (i->second.key == st && !i->second.file_ptr.unique()) return false; } return true; } #endif void file_pool::resize(int size) { mutex::scoped_lock l(m_mutex); TORRENT_ASSERT(size > 0); if (size == m_size) return; m_size = size; if (int(m_files.size()) <= m_size) return; // close the least recently used files while (int(m_files.size()) > m_size) remove_oldest(l); } } <|endoftext|>
<commit_before>//2014.03.28 - 2014.03.30 - 2014.03.31 Gustaf - CTG. /* EXERCISE 4-3 : For our dynamically allocated strings, create a function replaceString that takes three parameters, each of type arrayString: source, target, and replaceText. The function replaces every occurrence of target in source with replaceText. For example, if source points to an array containing "abcdabee", target points to "ab", and replaceText points to "xyz", then when the function ends, source should point to an array containing "xyzcdxyzee". === PLAN === OK - Diagram of the example. - Traverse (go over) the SOURCE string and identify the initial and final positions of the TARGET string. ok- Identify one character. ok- Identify two characters. ok- Identify three characters. ok- Identify four characters. - Identify lots of characters. */ #include <iostream> using namespace std; typedef char *arrayString; int main() { cout << "Variable-Length String Manipulation. TEST identify the limits." << endl; int ARRAY_SIZE = 9; int posIni = -1, posFinal = -1; arrayString a = new char[ARRAY_SIZE]; a[0] = 'a'; a[1] = 'b'; a[2] = 'c'; a[3] = 'd'; a[4] = 'a'; a[5] = 'b'; a[6] = 'e'; a[7] = 'e'; a[8] = 0; cout << "Initial string: " << a << endl << endl; // --- Identifying one character. cout << "Identifying one character." << endl; char targetChar = 0; targetChar = 'b'; for (int i = 0; i < ARRAY_SIZE; ++i) { if (a[i] == targetChar) { posIni = i; cout << "Target - index: " << targetChar << " - " << posIni << endl; cout << endl; } } // --- Identifying two contiguous characters. cout << "Identifying two contiguous character." << endl; char targetArray[2] = {'a', 'b'}; // char targetArray[2] = {'b', 'z'}; posIni = -1, posFinal = -1; for (int i = 0; i < ARRAY_SIZE; ++i) { // Find first char if ( (posIni == -1) && (a[i] == targetArray[0]) ) { posIni = i; } // Find second adjacent char, in next cicle. if ( (posIni != -1) && (i == (posIni + 1) ) && (a[i] == targetArray[1]) ) { posFinal = i; cout << "Target - index: " << targetArray[0] << " - " << posIni << endl; cout << "Target - index: " << targetArray[1] << " - " << posFinal << endl; cout << endl; posIni = -1, posFinal = -1; // Reset. } } // --- Identifying three contiguous characters. cout << "Identifying three contiguous character." << endl; char targetArrayThree[3] = {'a', 'b', 'c'}; // char targetArrayThree[3] = {'b', 'e', 'e'}; posIni = -1, posFinal = -1; for (int i = 0; i < ARRAY_SIZE; ++i) { // Find first char if ( (posIni == -1) && (a[i] == targetArrayThree[0]) ) { posIni = i; } // Check second adjacent character. if ( (posIni != -1) && (i == (posIni + 1)) ) { if (a[i] == targetArrayThree[1]) { posFinal = i; } if (a[i] != targetArrayThree[1]) { posIni = -1, posFinal = -1; // Reset. } } // Check third adjacent character. if ( (posIni != -1) && (posFinal != -1) && (i == (posFinal + 1)) ) { if (a[i] == targetArrayThree[2]) { posFinal = i; cout << "Target initial - index: " << targetArrayThree[0] << " - " << posIni << endl; cout << "Target final - index: " << targetArrayThree[2] << " - " << posFinal << endl; cout << endl; } posIni = -1, posFinal = -1; // Reset. } } // --- Identifying four contiguous characters. cout << "Identifying four contiguous character." << endl; char targetArrayFour[4] = {'a', 'b', 'c', 'd'}; // char targetArrayFour[4] = {'b', 'c', 'd', 'a'}; posIni = -1, posFinal = -1; for (int i = 0; i < ARRAY_SIZE; ++i) { // Find first char if ( (posIni == -1) && (posFinal == -1) ) { if (a[i] == targetArrayFour[0]) { posIni = i; } } // Check second adjacent character. if ( (posIni != -1) && (posFinal == -1) && (i == (posIni + 1)) ) { if (a[i] == targetArrayFour[1]) { posFinal = i; } if (a[i] != targetArrayFour[1]) { posIni = -1, posFinal = -1; // Reset. } } // Check third adjacent character. if ( (posIni != -1) && (posFinal != -1) && (i == (posIni + 2)) ) { if (a[i] == targetArrayFour[2]) { posFinal = i; } if (a[i] != targetArrayFour[2]) { posIni = -1, posFinal = -1; // Reset. } } // Check fourth adjacent character. if ( (posIni != -1) && (posFinal != -1) && (i == (posIni + 3)) ) { if (a[i] == targetArrayFour[3]) { posFinal = i; cout << "Target initial - index: " << targetArrayFour[0] << " - " << posIni << endl; cout << "Target final - index: " << targetArrayFour[3] << " - " << posFinal << endl; cout << endl; } posIni = -1, posFinal = -1; // Reset. } } delete a; // Free memory of the dinamic array. cout << endl; return 0; } <commit_msg>Chapter 04 exercice 4-3 partial progress. Test of identify one to lots of characters.<commit_after>//2014.03.28 - 2014.03.30 - 2014.03.31 - 2014.04.01 Gustaf - CTG. /* EXERCISE 4-3 : For our dynamically allocated strings, create a function replaceString that takes three parameters, each of type arrayString: source, target, and replaceText. The function replaces every occurrence of target in source with replaceText. For example, if source points to an array containing "abcdabee", target points to "ab", and replaceText points to "xyz", then when the function ends, source should point to an array containing "xyzcdxyzee". === PLAN === OK - Diagram of the example. OK - Traverse (go over) the SOURCE string and identify the initial and final positions of the TARGET string. ok- Identify one character. ok- Identify two characters. ok- Identify three characters. ok- Identify four characters. ok- Identify FROM one TO lots of characters. */ #include <iostream> using namespace std; typedef char *arrayString; int main() { cout << "Variable-Length String Manipulation. TEST identify the limits." << endl; int ARRAY_SIZE = 9; int posIni = -1, posFinal = -1; arrayString a = new char[ARRAY_SIZE]; a[0] = 'a'; a[1] = 'b'; a[2] = 'c'; a[3] = 'd'; a[4] = 'a'; a[5] = 'b'; a[6] = 'e'; a[7] = 'e'; a[8] = 0; cout << "Initial string: " << a << endl << endl; // --- Identifying one character. cout << "Identifying one character." << endl; char targetChar = 0; targetChar = 'b'; for (int i = 0; i < ARRAY_SIZE; ++i) { if (a[i] == targetChar) { posIni = i; cout << "Target - index: " << targetChar << " - " << posIni << endl; cout << endl; } } // --- Identifying two contiguous characters. cout << "Identifying two contiguous characters." << endl; char targetArray[2] = {'a', 'b'}; // char targetArray[2] = {'b', 'z'}; posIni = -1, posFinal = -1; for (int i = 0; i < ARRAY_SIZE; ++i) { // Find first char if ( (posIni == -1) && (a[i] == targetArray[0]) ) { posIni = i; } // Find second adjacent char, in next cicle. if ( (posIni != -1) && (i == (posIni + 1) ) && (a[i] == targetArray[1]) ) { posFinal = i; cout << "Target - index: " << targetArray[0] << " - " << posIni << endl; cout << "Target - index: " << targetArray[1] << " - " << posFinal << endl; cout << endl; posIni = -1, posFinal = -1; // Reset. } } // --- Identifying three contiguous characters. cout << "Identifying three contiguous characters." << endl; char targetArrayThree[3] = {'a', 'b', 'c'}; // char targetArrayThree[3] = {'b', 'e', 'e'}; posIni = -1, posFinal = -1; for (int i = 0; i < ARRAY_SIZE; ++i) { // Find first char if ( (posIni == -1) && (a[i] == targetArrayThree[0]) ) { posIni = i; } // Check second adjacent character. if ( (posIni != -1) && (i == (posIni + 1)) ) { if (a[i] == targetArrayThree[1]) { posFinal = i; } if (a[i] != targetArrayThree[1]) { posIni = -1, posFinal = -1; // Reset. } } // Check third adjacent character. if ( (posIni != -1) && (posFinal != -1) && (i == (posFinal + 1)) ) { if (a[i] == targetArrayThree[2]) { posFinal = i; cout << "Target initial - index: " << targetArrayThree[0] << " - " << posIni << endl; cout << "Target final - index: " << targetArrayThree[2] << " - " << posFinal << endl; cout << endl; } posIni = -1, posFinal = -1; // Reset. } } // --- Identifying four contiguous characters. cout << "Identifying four contiguous characters." << endl; char targetArrayFour[4] = {'a', 'b', 'c', 'd'}; // char targetArrayFour[4] = {'b', 'c', 'd', 'a'}; posIni = -1, posFinal = -1; for (int i = 0; i < ARRAY_SIZE; ++i) { // Find first char if ( (posIni == -1) && (posFinal == -1) ) { if (a[i] == targetArrayFour[0]) { posIni = i; } } // Check second adjacent character. if ( (posIni != -1) && (posFinal == -1) && (i == (posIni + 1)) ) { if (a[i] == targetArrayFour[1]) { posFinal = i; } if (a[i] != targetArrayFour[1]) { posIni = -1, posFinal = -1; // Reset. } } // Check third adjacent character. if ( (posIni != -1) && (posFinal != -1) && (i == (posIni + 2)) ) { if (a[i] == targetArrayFour[2]) { posFinal = i; } if (a[i] != targetArrayFour[2]) { posIni = -1, posFinal = -1; // Reset. } } // Check fourth adjacent character. if ( (posIni != -1) && (posFinal != -1) && (i == (posIni + 3)) ) { if (a[i] == targetArrayFour[3]) { posFinal = i; cout << "Target initial - index: " << targetArrayFour[0] << " - " << posIni << endl; cout << "Target final - index: " << targetArrayFour[3] << " - " << posFinal << endl; cout << endl; } posIni = -1, posFinal = -1; // Reset. } } // --- Identifying lots of contiguous characters. // const int TARGET_SIZE = 9; char targetArrayLots[TARGET_SIZE] = {'b', 'c', 'd', 'a', 'b', 'c', 'e', 'f', 'g'}; // const int TARGET_SIZE = 7; char targetArrayLots[TARGET_SIZE] = {'b', 'c', 'd', 'a', 'b', 'c', 'e'}; const int TARGET_SIZE = 3; char targetArrayLots[TARGET_SIZE] = {'a', 'b', 'c'}; // const int TARGET_SIZE = 2; char targetArrayLots[TARGET_SIZE] = {'a', 'b'}; // const int TARGET_SIZE = 1; char targetArrayLots[TARGET_SIZE] = {'b'}; cout << "Identifying " << TARGET_SIZE << " contiguous characters." << endl; a[0] = 'a'; a[1] = 'b'; a[2] = 'c'; a[3] = 'd'; a[4] = 'a'; a[5] = 'b'; a[6] = 'c'; a[7] = 'e'; a[8] = 0; cout << "Initial string: " << a << endl << endl; posIni = -1, posFinal = -1; for (int i = 0; i < ARRAY_SIZE; ++i) { // Find first character. if ( (posIni == -1) && (posFinal == -1) && (a[i] == targetArrayLots[0]) ) { posIni = i; // Handles special case of one character. if (TARGET_SIZE == 1) { cout << "Target initial/final - index: " << targetArrayLots[0] << " - " << posIni << endl; cout << endl; posIni = -1, posFinal = -1; // Reset. } // Handles cases from two characters until ... for (int j = 1; j < TARGET_SIZE; ++j) { // Check second adjacent character. if ( (posFinal == -1) && ( (i + j) == (posIni + j)) ) { if (a[i + j] == targetArrayLots[j]) { posFinal = i + j; } if (a[i + j] != targetArrayLots[j]) { posIni = -1, posFinal = -1; // Reset. } } // Check next adjacent character. BUT not the last. if ( (posFinal != -1) && ((i + j) == (posIni + j)) && (j <= (TARGET_SIZE - 2)) ) { if (a[i + j] == targetArrayLots[j]) { posFinal = i + j; } if (a[i + j] != targetArrayLots[j]) { posIni = -1, posFinal = -1; // Reset. } } // Check last adjacent character. if ( (posFinal != -1) && ((i + j) == (posIni + j)) && (j == (TARGET_SIZE - 1)) ) { if (a[i + j] == targetArrayLots[j]) { posFinal = i + j; cout << "Target initial - index: " << targetArrayLots[0] << " - " << posIni << endl; cout << "Target final - index: " << targetArrayLots[j] << " - " << posFinal << endl; cout << endl; } posIni = -1, posFinal = -1; // Reset. } } // internal for } // if that check the first character. } // external for delete a; // Free memory of the dynamic array. cout << endl; return 0; } <|endoftext|>
<commit_before>#include "sys/time.h" #include "gspan.h" #include "seperator.h" #include "database.h" namespace gspan { void GSpan::execute(const char *seperator_type, const char *file_path, double support) { _m_seperator = new Seperator(seperator_type); _m_file_path = file_path; _m_support = support; Input gspan_input; _m_seperator->seperate(_m_file_path, gspan_input); #ifdef DEBUG printf("seperate\n"); #endif if (GSPAN_SUCCESS != read_input(gspan_input)) { fprintf(stderr, "read input error!"); exit(GSPAN_ERROR); } #ifdef DEBUG printf("find_frequent\n"); #endif if (GSPAN_SUCCESS != find_frequent_nodes()) { fprintf(stderr, "find frequent nodes error!"); exit(GSPAN_ERROR); } if (GSPAN_SUCCESS != reconstruct(gspan_input)) { fprintf(stderr, "find frequent nodes error!"); exit(GSPAN_ERROR); } DataBase *database = DataBase::get_instance(); _m_graphs = database->get_graph(); timeval t1, t2; double elapsed_time = 0.0f; gettimeofday(&t1, NULL); #ifdef DEBUG printf("project\n"); #endif if (GSPAN_SUCCESS != project()) { fprintf(stderr, "projection nodes error!"); exit(GSPAN_ERROR); } gettimeofday(&t2, NULL); elapsed_time = (t2.tv_sec - t1.tv_sec) * 1000.0; elapsed_time += (t2.tv_usec - t1.tv_usec) / 1000.0; printf("elapsed time->execute %f\n", elapsed_time); } GSpanReturnCode GSpan::read_input(Input& input) { Graph graph; Vertice vertice; DataBase *database = DataBase::get_instance(); uint32_t graph_idx = 0; uint32_t edge_id = 0; double total_edge = 0.0f; double density = 0.0f; for (size_t i = 0; i < input.size(); ++i) { if (input[i][0] == "t") { if (i != 0) { total_edge += edge_id; if (vertice.size() != 0) { density += 2.0f * edge_id / (vertice.size() * (vertice.size() - 1)); } graph.set_nedges(edge_id); graph.set_vertice(vertice); edge_id = 0; database->push_graph(graph); graph.clear(); vertice.clear(); } char indicator, seperator; uint32_t idx; indicator = input[i][0][0]; seperator = input[i][1][0]; sscanf(input[i][2].c_str(), "%u", &idx); if (graph_idx != idx) { fprintf(stderr, "reading input warning! %u %u\n", graph_idx, idx); } graph.set_id(idx); ++graph_idx; } else if (input[i][0] == "v") { char indicator; uint32_t id, label; indicator = input[i][0][0]; sscanf(input[i][1].c_str(), "%u", &id); sscanf(input[i][2].c_str(), "%u", &label); struct vertex_t vertex; vertex.id = id; vertex.label = label; vertice.push_back(vertex); } else if (input[i][0] == "e") { char indicator; uint32_t from, to, label; indicator = input[i][0][0]; sscanf(input[i][1].c_str(), "%u", &from); sscanf(input[i][2].c_str(), "%u", &to); sscanf(input[i][3].c_str(), "%u", &label); struct edge_t edge; edge.from = from; edge.to = to; edge.label = label; edge.id = edge_id; ++edge_id; //first edge vertice[from].edges.push_back(edge); //second edge edge.from = to; edge.to = from; vertice[to].edges.push_back(edge); } else { fprintf(stderr, "reading input warning!"); } } graph.set_vertice(vertice); database->push_graph(graph); printf("average graph size : %f\n", total_edge / database->size()); printf("average density: %f\n", density / database->size()); _m_nsupport = static_cast<uint32_t>(graph_idx * _m_support); return GSPAN_SUCCESS; } }//namespace gspan <commit_msg>update unique label set<commit_after>#include "sys/time.h" #include "gspan.h" #include "seperator.h" #include "database.h" namespace gspan { void GSpan::execute(const char *seperator_type, const char *file_path, double support) { _m_seperator = new Seperator(seperator_type); _m_file_path = file_path; _m_support = support; Input gspan_input; _m_seperator->seperate(_m_file_path, gspan_input); #ifdef DEBUG printf("seperate\n"); #endif if (GSPAN_SUCCESS != read_input(gspan_input)) { fprintf(stderr, "read input error!"); exit(GSPAN_ERROR); } #ifdef DEBUG printf("find_frequent\n"); #endif if (GSPAN_SUCCESS != find_frequent_nodes()) { fprintf(stderr, "find frequent nodes error!"); exit(GSPAN_ERROR); } if (GSPAN_SUCCESS != reconstruct(gspan_input)) { fprintf(stderr, "find frequent nodes error!"); exit(GSPAN_ERROR); } DataBase *database = DataBase::get_instance(); _m_graphs = database->get_graph(); timeval t1, t2; double elapsed_time = 0.0f; gettimeofday(&t1, NULL); #ifdef DEBUG printf("project\n"); #endif if (GSPAN_SUCCESS != project()) { fprintf(stderr, "projection nodes error!"); exit(GSPAN_ERROR); } gettimeofday(&t2, NULL); elapsed_time = (t2.tv_sec - t1.tv_sec) * 1000.0; elapsed_time += (t2.tv_usec - t1.tv_usec) / 1000.0; printf("elapsed time->execute %f\n", elapsed_time); } GSpanReturnCode GSpan::read_input(Input& input) { Graph graph; Vertice vertice; DataBase *database = DataBase::get_instance(); uint32_t graph_idx = 0; uint32_t edge_id = 0; double total_edge = 0.0f; double density = 0.0f; std::vector<std::set<uint32_t> > edge_label_set; for (size_t i = 0; i < input.size(); ++i) { if (input[i][0] == "t") { if (i != 0) { total_edge += edge_id; if (vertice.size() != 0) { density += 2.0f * edge_id / (vertice.size() * (vertice.size() - 1)); } graph.set_nedges(edge_id); graph.set_vertice(vertice); edge_id = 0; database->push_graph(graph); graph.clear(); vertice.clear(); } edge_label_set.resize(edge_label_set.size() + 1); char indicator, seperator; uint32_t idx; indicator = input[i][0][0]; seperator = input[i][1][0]; sscanf(input[i][2].c_str(), "%u", &idx); if (graph_idx != idx) { fprintf(stderr, "reading input warning! %u %u\n", graph_idx, idx); } graph.set_id(idx); ++graph_idx; } else if (input[i][0] == "v") { char indicator; uint32_t id, label; indicator = input[i][0][0]; sscanf(input[i][1].c_str(), "%u", &id); sscanf(input[i][2].c_str(), "%u", &label); struct vertex_t vertex; vertex.id = id; vertex.label = label; vertice.push_back(vertex); } else if (input[i][0] == "e") { char indicator; uint32_t from, to, label; indicator = input[i][0][0]; sscanf(input[i][1].c_str(), "%u", &from); sscanf(input[i][2].c_str(), "%u", &to); sscanf(input[i][3].c_str(), "%u", &label); //add label edge_label_set[graph_idx - 1].insert(label); struct edge_t edge; edge.from = from; edge.to = to; edge.label = label; edge.id = edge_id; ++edge_id; //first edge vertice[from].edges.push_back(edge); //second edge edge.from = to; edge.to = from; vertice[to].edges.push_back(edge); } else { fprintf(stderr, "reading input warning!"); } } graph.set_vertice(vertice); database->push_graph(graph); printf("average graph size : %f\n", total_edge / database->size()); printf("average density: %f\n", density / database->size()); for (size_t i = 0; i < graph_idx; ++i) { for (size_t j = i + 1; j < graph_idx; ++j) { printf("unique edge label set of %zu and %zu \n", i, j); printf("%zu : \n", i); for (std::set<uint32_t>::iterator edge_iterator = edge_label_set[i].begin(); edge_iterator != edge_label_set[i].end(); ++edge_iterator) { if (edge_label_set[j].find(*edge_iterator) == edge_label_set[j].end()) { printf("%zu ", *edge_iterator); } } printf("\n"); printf("%zu : \n", j); for (std::set<uint32_t>::iterator edge_iterator = edge_label_set[j].begin(); edge_iterator != edge_label_set[j].end(); ++edge_iterator) { if (edge_label_set[i].find(*edge_iterator) == edge_label_set[i].end()) { printf("%zu ", *edge_iterator); } } printf("\n"); } } _m_nsupport = static_cast<uint32_t>(graph_idx * _m_support); return GSPAN_SUCCESS; } }//namespace gspan <|endoftext|>
<commit_before>/**************************************************************************** * * Copyright (c) 2012-2015 PX4 Development Team. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * 3. Neither the name PX4 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 _uORBTest_UnitTest_hpp_ #define _uORBTest_UnitTest_hpp_ #include "../uORBCommon.hpp" #include "../uORB.h" #include <px4_time.h> struct orb_test { int val; hrt_abstime time; }; ORB_DECLARE(orb_test); ORB_DECLARE(orb_multitest); struct orb_test_medium { int val; hrt_abstime time; char junk[64]; }; ORB_DECLARE(orb_test_medium); ORB_DECLARE(orb_test_medium_multi); ORB_DECLARE(orb_test_medium_queue); ORB_DECLARE(orb_test_medium_queue_poll); struct orb_test_large { int val; hrt_abstime time; char junk[512]; }; ORB_DECLARE(orb_test_large); namespace uORBTest { class UnitTest; } class uORBTest::UnitTest { public: // Singleton pattern static uORBTest::UnitTest &instance(); ~UnitTest() {} int test(); template<typename S> int latency_test(orb_id_t T, bool print); int info(); private: UnitTest() : pubsubtest_passed(false), pubsubtest_print(false) {} // Disallow copy UnitTest(const uORBTest::UnitTest &) {}; static int pubsubtest_threadEntry(char *const argv[]); int pubsublatency_main(void); static int pub_test_multi2_entry(char *const argv[]); int pub_test_multi2_main(); volatile bool _thread_should_exit; bool pubsubtest_passed; bool pubsubtest_print; int pubsubtest_res = OK; orb_advert_t _pfd[4]; ///< used for test_multi and test_multi_reversed int test_single(); /* These 3 depend on each other and must be called in this order */ int test_multi(); int test_multi_reversed(); int test_unadvertise(); int test_multi2(); /* queuing tests */ int test_queue(); static int pub_test_queue_entry(char *const argv[]); int pub_test_queue_main(); int test_queue_poll_notify(); volatile int _num_messages_sent = 0; int test_fail(const char *fmt, ...); int test_note(const char *fmt, ...); }; template<typename S> int uORBTest::UnitTest::latency_test(orb_id_t T, bool print) { test_note("---------------- LATENCY TEST ------------------"); S t; t.val = 308; t.time = hrt_absolute_time(); orb_advert_t pfd0 = orb_advertise(T, &t); if (pfd0 == nullptr) { return test_fail("orb_advertise failed (%i)", errno); } char *const args[1] = { NULL }; pubsubtest_print = print; pubsubtest_passed = false; /* test pub / sub latency */ // Can't pass a pointer in args, must be a null terminated // array of strings because the strings are copied to // prevent access if the caller data goes out of scope int pubsub_task = px4_task_spawn_cmd("uorb_latency", SCHED_DEFAULT, SCHED_PRIORITY_MAX - 5, 1500, (px4_main_t)&uORBTest::UnitTest::pubsubtest_threadEntry, args); /* give the test task some data */ while (!pubsubtest_passed) { t.val = 308; t.time = hrt_absolute_time(); if (PX4_OK != orb_publish(T, pfd0, &t)) { return test_fail("mult. pub0 timing fail"); } /* simulate >800 Hz system operation */ usleep(1000); } if (pubsub_task < 0) { return test_fail("failed launching task"); } orb_unadvertise(pfd0); return pubsubtest_res; } #endif // _uORBTest_UnitTest_hpp_ <commit_msg>uORB: Header cleanup<commit_after>/**************************************************************************** * * Copyright (c) 2012-2015 PX4 Development Team. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * 3. Neither the name PX4 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 _uORBTest_UnitTest_hpp_ #define _uORBTest_UnitTest_hpp_ #include "../uORBCommon.hpp" #include "../uORB.h" #include <px4_time.h> #include <px4_tasks.h> struct orb_test { int val; hrt_abstime time; }; ORB_DECLARE(orb_test); ORB_DECLARE(orb_multitest); struct orb_test_medium { int val; hrt_abstime time; char junk[64]; }; ORB_DECLARE(orb_test_medium); ORB_DECLARE(orb_test_medium_multi); ORB_DECLARE(orb_test_medium_queue); ORB_DECLARE(orb_test_medium_queue_poll); struct orb_test_large { int val; hrt_abstime time; char junk[512]; }; ORB_DECLARE(orb_test_large); namespace uORBTest { class UnitTest; } class uORBTest::UnitTest { public: // Singleton pattern static uORBTest::UnitTest &instance(); ~UnitTest() {} int test(); template<typename S> int latency_test(orb_id_t T, bool print); int info(); private: UnitTest() : pubsubtest_passed(false), pubsubtest_print(false) {} // Disallow copy UnitTest(const uORBTest::UnitTest &) {}; static int pubsubtest_threadEntry(char *const argv[]); int pubsublatency_main(void); static int pub_test_multi2_entry(char *const argv[]); int pub_test_multi2_main(); volatile bool _thread_should_exit; bool pubsubtest_passed; bool pubsubtest_print; int pubsubtest_res = OK; orb_advert_t _pfd[4]; ///< used for test_multi and test_multi_reversed int test_single(); /* These 3 depend on each other and must be called in this order */ int test_multi(); int test_multi_reversed(); int test_unadvertise(); int test_multi2(); /* queuing tests */ int test_queue(); static int pub_test_queue_entry(char *const argv[]); int pub_test_queue_main(); int test_queue_poll_notify(); volatile int _num_messages_sent = 0; int test_fail(const char *fmt, ...); int test_note(const char *fmt, ...); }; template<typename S> int uORBTest::UnitTest::latency_test(orb_id_t T, bool print) { test_note("---------------- LATENCY TEST ------------------"); S t; t.val = 308; t.time = hrt_absolute_time(); orb_advert_t pfd0 = orb_advertise(T, &t); if (pfd0 == nullptr) { return test_fail("orb_advertise failed (%i)", errno); } char *const args[1] = { NULL }; pubsubtest_print = print; pubsubtest_passed = false; /* test pub / sub latency */ // Can't pass a pointer in args, must be a null terminated // array of strings because the strings are copied to // prevent access if the caller data goes out of scope int pubsub_task = px4_task_spawn_cmd("uorb_latency", SCHED_DEFAULT, SCHED_PRIORITY_MAX - 5, 1500, (px4_main_t)&uORBTest::UnitTest::pubsubtest_threadEntry, args); /* give the test task some data */ while (!pubsubtest_passed) { t.val = 308; t.time = hrt_absolute_time(); if (PX4_OK != orb_publish(T, pfd0, &t)) { return test_fail("mult. pub0 timing fail"); } /* simulate >800 Hz system operation */ usleep(1000); } if (pubsub_task < 0) { return test_fail("failed launching task"); } orb_unadvertise(pfd0); return pubsubtest_res; } #endif // _uORBTest_UnitTest_hpp_ <|endoftext|>
<commit_before>/* Copyright 2015-2016 Samsung Electronics Co., Ltd. * * 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 "iotjs_env.h" #include <string.h> namespace iotjs { /** * Construct an instance of Environment. */ Environment::Environment() : _argc(0) , _argv(NULL) , _loop(NULL) , _state(kInitializing) { _config.memstat = false; _config.show_opcode = false; } /** * Release an instance of Environment. */ Environment::~Environment() { if (_argv) { // release command line argument strings. // _argv[0] and _argv[1] refer addresses in static memory space. // Ohters refer adresses in heap space that is need to be deallocated. for (int i = 2; i < _argc; ++i) { delete _argv[i]; } delete [] _argv; } } /** * Parse command line arguments */ bool Environment::ParseCommandLineArgument(int argc, char** argv) { // There must be at least two arguemnts. if (argc < 2) { fprintf(stderr, "usage: iotjs <js> [<iotjs arguments>] [-- <app arguments>]\n"); return false; } // Second argument should be IoT.js application. char* app = argv[1]; _argc = 2; // Parse IoT.js command line arguments. int i = 2; while (i < argc) { if (!strcmp(argv[i], "--")) { ++i; break; } if (!strcmp(argv[i], "--memstat")) { _config.memstat = true; } else if (!strcmp(argv[i], "--show-opcodes")) { _config.show_opcode = true; } else { fprintf(stderr, "unknown command line argument %s\n", argv[i]); return false; } ++i; } // Remaining arguments are for application. _argv = new char*[_argc + argc - i]; _argv[0] = argv[0]; _argv[1] = argv[1]; while (i < argc) { _argv[_argc] = new char[strlen(argv[i]) + 1]; strcpy(_argv[_argc], argv[i]); _argc++; i++; } return true; } } // namespace iotjs <commit_msg>Remove leftover dead code from command line parsing<commit_after>/* Copyright 2015-2016 Samsung Electronics Co., Ltd. * * 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 "iotjs_env.h" #include <string.h> namespace iotjs { /** * Construct an instance of Environment. */ Environment::Environment() : _argc(0) , _argv(NULL) , _loop(NULL) , _state(kInitializing) { _config.memstat = false; _config.show_opcode = false; } /** * Release an instance of Environment. */ Environment::~Environment() { if (_argv) { // release command line argument strings. // _argv[0] and _argv[1] refer addresses in static memory space. // Ohters refer adresses in heap space that is need to be deallocated. for (int i = 2; i < _argc; ++i) { delete _argv[i]; } delete [] _argv; } } /** * Parse command line arguments */ bool Environment::ParseCommandLineArgument(int argc, char** argv) { // There must be at least two arguemnts. if (argc < 2) { fprintf(stderr, "usage: iotjs <js> [<iotjs arguments>] [-- <app arguments>]\n"); return false; } // Parse IoT.js command line arguments. int i = 2; while (i < argc) { if (!strcmp(argv[i], "--")) { ++i; break; } if (!strcmp(argv[i], "--memstat")) { _config.memstat = true; } else if (!strcmp(argv[i], "--show-opcodes")) { _config.show_opcode = true; } else { fprintf(stderr, "unknown command line argument %s\n", argv[i]); return false; } ++i; } // Remaining arguments are for application. _argc = 2; _argv = new char*[_argc + argc - i]; _argv[0] = argv[0]; _argv[1] = argv[1]; while (i < argc) { _argv[_argc] = new char[strlen(argv[i]) + 1]; strcpy(_argv[_argc], argv[i]); _argc++; i++; } return true; } } // namespace iotjs <|endoftext|>
<commit_before>/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * Copyright (C) 2015 ScyllaDB * * Modified by ScyllaDB */ /* * This file is part of Scylla. * * Scylla 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. * * Scylla 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 Scylla. If not, see <http://www.gnu.org/licenses/>. */ #pragma once #include "locator/network_topology_strategy.hh" #include "db/consistency_level_type.hh" #include "db/read_repair_decision.hh" #include "exceptions/exceptions.hh" #include "utils/fb_utilities.hh" #include "gms/inet_address.hh" #include "database.hh" #include <iosfwd> #include <vector> namespace db { extern logging::logger cl_logger; size_t quorum_for(const keyspace& ks); size_t local_quorum_for(const keyspace& ks, const sstring& dc); size_t block_for_local_serial(keyspace& ks); size_t block_for_each_quorum(keyspace& ks); size_t block_for(keyspace& ks, consistency_level cl); bool is_datacenter_local(consistency_level l); bool is_local(gms::inet_address endpoint); template<typename Range> inline size_t count_local_endpoints(Range& live_endpoints) { return std::count_if(live_endpoints.begin(), live_endpoints.end(), is_local); } std::vector<gms::inet_address> filter_for_query(consistency_level cl, keyspace& ks, std::vector<gms::inet_address> live_endpoints, const std::vector<gms::inet_address>& preferred_endpoints, read_repair_decision read_repair, gms::inet_address* extra, column_family* cf); std::vector<gms::inet_address> filter_for_query(consistency_level cl, keyspace& ks, std::vector<gms::inet_address>& live_endpoints, const std::vector<gms::inet_address>& preferred_endpoints, column_family* cf); struct dc_node_count { size_t live = 0; size_t pending = 0; }; template <typename Range, typename PendingRange = std::array<gms::inet_address, 0>> inline std::unordered_map<sstring, dc_node_count> count_per_dc_endpoints( keyspace& ks, Range& live_endpoints, const PendingRange& pending_endpoints = std::array<gms::inet_address, 0>()) { using namespace locator; auto& rs = ks.get_replication_strategy(); auto& snitch_ptr = i_endpoint_snitch::get_local_snitch_ptr(); network_topology_strategy* nrs = static_cast<network_topology_strategy*>(&rs); std::unordered_map<sstring, dc_node_count> dc_endpoints; for (auto& dc : nrs->get_datacenters()) { dc_endpoints.emplace(dc, dc_node_count()); } // // Since live_endpoints are a subset of a get_natural_endpoints() output we // will never get any endpoints outside the dataceters from // nrs->get_datacenters(). // for (auto& endpoint : live_endpoints) { ++(dc_endpoints[snitch_ptr->get_datacenter(endpoint)].live); } for (auto& endpoint : pending_endpoints) { ++(dc_endpoints[snitch_ptr->get_datacenter(endpoint)].pending); } return dc_endpoints; } bool is_sufficient_live_nodes(consistency_level cl, keyspace& ks, const std::vector<gms::inet_address>& live_endpoints); template<typename Range, typename PendingRange> inline bool assure_sufficient_live_nodes_each_quorum( consistency_level cl, keyspace& ks, Range& live_endpoints, const PendingRange& pending_endpoints) { using namespace locator; auto& rs = ks.get_replication_strategy(); if (rs.get_type() == replication_strategy_type::network_topology) { for (auto& entry : count_per_dc_endpoints(ks, live_endpoints, pending_endpoints)) { auto dc_block_for = local_quorum_for(ks, entry.first); auto dc_live = entry.second.live; auto dc_pending = entry.second.pending; if (dc_live < dc_block_for + dc_pending) { throw exceptions::unavailable_exception(cl, dc_block_for, dc_live); } } return true; } return false; } template<typename Range, typename PendingRange = std::array<gms::inet_address, 0>> inline void assure_sufficient_live_nodes( consistency_level cl, keyspace& ks, Range& live_endpoints, const PendingRange& pending_endpoints = std::array<gms::inet_address, 0>()) { size_t need = block_for(ks, cl); auto adjust_live_for_error = [] (size_t live, size_t pending) { // DowngradingConsistencyRetryPolicy uses alive replicas count from Unavailable // exception to adjust CL for retry. When pending node is present CL is increased // by 1 internally, so reported number of live nodes has to be adjusted to take // this into account return pending <= live ? live - pending : 0; }; switch (cl) { case consistency_level::ANY: // local hint is acceptable, and local node is always live break; case consistency_level::LOCAL_ONE: if (count_local_endpoints(live_endpoints) < count_local_endpoints(pending_endpoints) + 1) { throw exceptions::unavailable_exception(cl, 1, 0); } break; case consistency_level::LOCAL_QUORUM: { size_t local_live = count_local_endpoints(live_endpoints); size_t pending = count_local_endpoints(pending_endpoints); if (local_live < need + pending) { cl_logger.debug("Local replicas {} are insufficient to satisfy LOCAL_QUORUM requirement of needed {} and pending {}", live_endpoints, local_live, pending); throw exceptions::unavailable_exception(cl, need, adjust_live_for_error(local_live, pending)); } break; } case consistency_level::EACH_QUORUM: if (assure_sufficient_live_nodes_each_quorum(cl, ks, live_endpoints, pending_endpoints)) { break; } // Fallthough on purpose for SimpleStrategy default: size_t live = live_endpoints.size(); size_t pending = pending_endpoints.size(); if (live < need + pending) { cl_logger.debug("Live nodes {} do not satisfy ConsistencyLevel ({} required, {} pending)", live, need, pending); throw exceptions::unavailable_exception(cl, need, adjust_live_for_error(live, pending)); } break; } } } <commit_msg>consistency_level: make it more const correct<commit_after>/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * Copyright (C) 2015 ScyllaDB * * Modified by ScyllaDB */ /* * This file is part of Scylla. * * Scylla 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. * * Scylla 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 Scylla. If not, see <http://www.gnu.org/licenses/>. */ #pragma once #include "locator/network_topology_strategy.hh" #include "db/consistency_level_type.hh" #include "db/read_repair_decision.hh" #include "exceptions/exceptions.hh" #include "utils/fb_utilities.hh" #include "gms/inet_address.hh" #include "database.hh" #include <iosfwd> #include <vector> namespace db { extern logging::logger cl_logger; size_t quorum_for(const keyspace& ks); size_t local_quorum_for(const keyspace& ks, const sstring& dc); size_t block_for_local_serial(keyspace& ks); size_t block_for_each_quorum(keyspace& ks); size_t block_for(keyspace& ks, consistency_level cl); bool is_datacenter_local(consistency_level l); bool is_local(gms::inet_address endpoint); template<typename Range> inline size_t count_local_endpoints(const Range& live_endpoints) { return std::count_if(live_endpoints.begin(), live_endpoints.end(), is_local); } std::vector<gms::inet_address> filter_for_query(consistency_level cl, keyspace& ks, std::vector<gms::inet_address> live_endpoints, const std::vector<gms::inet_address>& preferred_endpoints, read_repair_decision read_repair, gms::inet_address* extra, column_family* cf); std::vector<gms::inet_address> filter_for_query(consistency_level cl, keyspace& ks, std::vector<gms::inet_address>& live_endpoints, const std::vector<gms::inet_address>& preferred_endpoints, column_family* cf); struct dc_node_count { size_t live = 0; size_t pending = 0; }; template <typename Range, typename PendingRange = std::array<gms::inet_address, 0>> inline std::unordered_map<sstring, dc_node_count> count_per_dc_endpoints( keyspace& ks, const Range& live_endpoints, const PendingRange& pending_endpoints = std::array<gms::inet_address, 0>()) { using namespace locator; auto& rs = ks.get_replication_strategy(); auto& snitch_ptr = i_endpoint_snitch::get_local_snitch_ptr(); network_topology_strategy* nrs = static_cast<network_topology_strategy*>(&rs); std::unordered_map<sstring, dc_node_count> dc_endpoints; for (auto& dc : nrs->get_datacenters()) { dc_endpoints.emplace(dc, dc_node_count()); } // // Since live_endpoints are a subset of a get_natural_endpoints() output we // will never get any endpoints outside the dataceters from // nrs->get_datacenters(). // for (auto& endpoint : live_endpoints) { ++(dc_endpoints[snitch_ptr->get_datacenter(endpoint)].live); } for (auto& endpoint : pending_endpoints) { ++(dc_endpoints[snitch_ptr->get_datacenter(endpoint)].pending); } return dc_endpoints; } bool is_sufficient_live_nodes(consistency_level cl, keyspace& ks, const std::vector<gms::inet_address>& live_endpoints); template<typename Range, typename PendingRange> inline bool assure_sufficient_live_nodes_each_quorum( consistency_level cl, keyspace& ks, const Range& live_endpoints, const PendingRange& pending_endpoints) { using namespace locator; auto& rs = ks.get_replication_strategy(); if (rs.get_type() == replication_strategy_type::network_topology) { for (auto& entry : count_per_dc_endpoints(ks, live_endpoints, pending_endpoints)) { auto dc_block_for = local_quorum_for(ks, entry.first); auto dc_live = entry.second.live; auto dc_pending = entry.second.pending; if (dc_live < dc_block_for + dc_pending) { throw exceptions::unavailable_exception(cl, dc_block_for, dc_live); } } return true; } return false; } template<typename Range, typename PendingRange = std::array<gms::inet_address, 0>> inline void assure_sufficient_live_nodes( consistency_level cl, keyspace& ks, const Range& live_endpoints, const PendingRange& pending_endpoints = std::array<gms::inet_address, 0>()) { size_t need = block_for(ks, cl); auto adjust_live_for_error = [] (size_t live, size_t pending) { // DowngradingConsistencyRetryPolicy uses alive replicas count from Unavailable // exception to adjust CL for retry. When pending node is present CL is increased // by 1 internally, so reported number of live nodes has to be adjusted to take // this into account return pending <= live ? live - pending : 0; }; switch (cl) { case consistency_level::ANY: // local hint is acceptable, and local node is always live break; case consistency_level::LOCAL_ONE: if (count_local_endpoints(live_endpoints) < count_local_endpoints(pending_endpoints) + 1) { throw exceptions::unavailable_exception(cl, 1, 0); } break; case consistency_level::LOCAL_QUORUM: { size_t local_live = count_local_endpoints(live_endpoints); size_t pending = count_local_endpoints(pending_endpoints); if (local_live < need + pending) { cl_logger.debug("Local replicas {} are insufficient to satisfy LOCAL_QUORUM requirement of needed {} and pending {}", live_endpoints, local_live, pending); throw exceptions::unavailable_exception(cl, need, adjust_live_for_error(local_live, pending)); } break; } case consistency_level::EACH_QUORUM: if (assure_sufficient_live_nodes_each_quorum(cl, ks, live_endpoints, pending_endpoints)) { break; } // Fallthough on purpose for SimpleStrategy default: size_t live = live_endpoints.size(); size_t pending = pending_endpoints.size(); if (live < need + pending) { cl_logger.debug("Live nodes {} do not satisfy ConsistencyLevel ({} required, {} pending)", live, need, pending); throw exceptions::unavailable_exception(cl, need, adjust_live_for_error(live, pending)); } break; } } } <|endoftext|>
<commit_before>/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 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 <osgProducer/GraphicsContextImplementation> #include <osg/TextureRectangle> #include <osg/TextureCubeMap> #include <osg/Notify> using namespace osgProducer; namespace osgProducer { struct MyWindowingSystemInterface : public osg::GraphicsContext::WindowingSystemInterface { virtual unsigned int getNumScreens(const osg::GraphicsContext::ScreenIdentifier& /*screenIdentifier*/) { return Producer::RenderSurface::getNumberOfScreens(); } virtual void getScreenResolution(const osg::GraphicsContext::ScreenIdentifier& screenIdentifier, unsigned int& width, unsigned int& height) { osg::ref_ptr<Producer::RenderSurface> rs = new Producer::RenderSurface; rs->setHostName(screenIdentifier.hostName); rs->setDisplayNum(screenIdentifier.displayNum); rs->setScreenNum(screenIdentifier.screenNum); rs->getScreenSize(width, height); } virtual osg::GraphicsContext* createGraphicsContext(osg::GraphicsContext::Traits* traits) { return new GraphicsContextImplementation(traits); } }; struct RegisterWindowingSystemInterfaceProxy { RegisterWindowingSystemInterfaceProxy() { osg::GraphicsContext::setWindowingSystemInterface(new MyWindowingSystemInterface); } ~RegisterWindowingSystemInterfaceProxy() { osg::GraphicsContext::setWindowingSystemInterface(0); } }; RegisterWindowingSystemInterfaceProxy createWindowingSystemInterfaceProxy; }; GraphicsContextImplementation::GraphicsContextImplementation(Traits* traits) { _traits = traits; _rs = new Producer::RenderSurface; _rs->setWindowName(traits->windowName); _rs->setWindowRectangle(traits->x, traits->y, traits->width, traits->height); _rs->useBorder(traits->windowDecoration); _rs->setDisplayNum(traits->displayNum); _rs->setScreenNum(traits->screenNum); // set the visual chooser Producer::VisualChooser* rs_vc = _rs->getVisualChooser(); if (!rs_vc) { rs_vc = new Producer::VisualChooser; _rs->setVisualChooser(rs_vc); } rs_vc->setRedSize(_traits->red); rs_vc->setGreenSize(_traits->green); rs_vc->setBlueSize(_traits->blue); rs_vc->setAlphaSize(_traits->alpha); rs_vc->setDepthSize(_traits->depth); rs_vc->setStencilSize(_traits->stencil); if (_traits->doubleBuffer) rs_vc->useDoubleBuffer(); rs_vc->addAttribute( Producer::VisualChooser::RGBA ); // Always use UseGL rs_vc->addAttribute( Producer::VisualChooser::UseGL ); if (traits->pbuffer) { _rs->setDrawableType(Producer::RenderSurface::DrawableType_PBuffer); if (traits->target) { _rs->setRenderToTextureOptions(traits->mipMapGeneration ? Producer::RenderSurface::RequestSpaceForMipMaps : Producer::RenderSurface::RenderToTextureOptions_Default); _rs->setRenderToTextureMipMapLevel(traits->level); _rs->setRenderToTextureMode(traits->alpha>0 ? Producer::RenderSurface::RenderToRGBATexture : Producer::RenderSurface::RenderToRGBTexture); switch(traits->target) { case(GL_TEXTURE_1D) : _rs->setRenderToTextureTarget(Producer::RenderSurface::Texture1D); break; case(GL_TEXTURE_2D) : _rs->setRenderToTextureTarget(Producer::RenderSurface::Texture2D); break; case(GL_TEXTURE_3D) : osg::notify(osg::NOTICE)<<"PBuffer render to Texture3D not supported."<<std::endl; // not supported. // _rs->setRenderToTextureTarget(Producer::RenderSurface::Texture3D); break; case(GL_TEXTURE_RECTANGLE) : osg::notify(osg::NOTICE)<<"PBuffer render to TextureRectangle not supported."<<std::endl; // not supported. // _rs->setRenderToTextureTarget(Producer::RenderSurface::TextureRectangle); break; case(GL_TEXTURE_CUBE_MAP_POSITIVE_X) : case(GL_TEXTURE_CUBE_MAP_NEGATIVE_X) : case(GL_TEXTURE_CUBE_MAP_POSITIVE_Y) : case(GL_TEXTURE_CUBE_MAP_NEGATIVE_Y) : case(GL_TEXTURE_CUBE_MAP_POSITIVE_Z) : case(GL_TEXTURE_CUBE_MAP_NEGATIVE_Z) : _rs->setRenderToTextureTarget(Producer::RenderSurface::TextureCUBE); _rs->setRenderToTextureFace( Producer::RenderSurface::CubeMapFace(traits->target - GL_TEXTURE_CUBE_MAP_POSITIVE_X)); break; } } } GraphicsContextImplementation* sharedContext = dynamic_cast<GraphicsContextImplementation*>(traits->sharedContext); if (sharedContext) { // different graphics context so we have our own state. setState(new osg::State); if (sharedContext->getState()) { getState()->setContextID( sharedContext->getState()->getContextID() ); incrementContextIDUsageCount( sharedContext->getState()->getContextID() ); } else { getState()->setContextID( osg::GraphicsContext::createNewContextID() ); } // but we share texture objects etc. so we also share the same contextID //_rs->realize( 0, sharedContext->_rs->getGLContext() ); } else { // need to do something here.... setState( new osg::State ); getState()->setContextID( osg::GraphicsContext::createNewContextID() ); //_rs->realize(); } // _rs->useConfigEventThread(false); _closeOnDestruction = true; } GraphicsContextImplementation::GraphicsContextImplementation(Producer::RenderSurface* rs) { _rs = rs; _closeOnDestruction = false; _traits = new osg::GraphicsContext::Traits; _traits->windowName = _rs->getWindowName(); _traits->displayNum = _rs->getDisplayNum(); _traits->screenNum = _rs->getScreenNum(); } GraphicsContextImplementation::~GraphicsContextImplementation() { if (_closeOnDestruction) close(); } bool GraphicsContextImplementation::realizeImplementation() { if (_rs.valid()) { GraphicsContextImplementation* sharedContext = dynamic_cast<GraphicsContextImplementation*>(_traits->sharedContext); if (sharedContext) { _rs->realize( 0, sharedContext->_rs->getGLContext() ); } else { osg::notify(osg::NOTICE)<<"GraphicsContextImplementation::realize"<<std::endl; _rs->realize(); } return _rs->isRealized(); } else { return false; } } bool GraphicsContextImplementation::makeCurrentImplementation() { if (!_rs) { osg::notify(osg::NOTICE)<<"Error: GraphicsContextImplementation::makeCurrentImplementation() no RenderSurface."<<std::endl; return false; } if (!isRealized()) { osg::notify(osg::NOTICE)<<"Error: GraphicsContextImplementation::makeCurrentImplementation() not Realized."<<std::endl; return false; } // osg::notify(osg::INFO)<<"GraphicsContextImplementation::makeCurrentImplementation()"<<std::endl; _rs->setReadDrawable( 0 ); // comment out right now, as Producer's setReadDrawable() is doing a call for us. // _rs->makeCurrent(); return true; } bool GraphicsContextImplementation::makeContextCurrentImplementation(osg::GraphicsContext* readContext) { if (!_rs) return false; GraphicsContextImplementation* readContextImplemention = dynamic_cast<GraphicsContextImplementation*>(readContext); if (readContextImplemention) { _rs->setReadDrawable( readContextImplemention->getRenderSurface() ); } else { _rs->setReadDrawable( 0 ); } // comment out right now, as Producer's setReadDrawable() is doing a call for us. // _rs->makeCurrent(); return true; } bool GraphicsContextImplementation::releaseContextImplementation() { osg::notify(osg::NOTICE)<<"GraphicsContextImplementation::releaseContextImplementation(): not implemented - release not supported under Producer."<<std::endl; return false; } void GraphicsContextImplementation::closeImplementation() { if (!_rs) return; // close render surface by deleting it _rs = 0; } void GraphicsContextImplementation::bindPBufferToTextureImplementation(GLenum buffer) { if (!_rs) return; Producer::RenderSurface::BufferType bufferType = Producer::RenderSurface::FrontBuffer; switch(buffer) { case(GL_BACK): bufferType = Producer::RenderSurface::BackBuffer; break; case(GL_FRONT): bufferType = Producer::RenderSurface::FrontBuffer; break; default: bufferType = Producer::RenderSurface::FrontBuffer; break; } _rs->bindPBufferToTexture(bufferType); } void GraphicsContextImplementation::swapBuffersImplementation() { _rs->swapBuffers(); } <commit_msg>Removed the automatic registration of GraphicsContextImplementation.<commit_after>/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 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 <osgProducer/GraphicsContextImplementation> #include <osg/TextureRectangle> #include <osg/TextureCubeMap> #include <osg/Notify> using namespace osgProducer; #if 0 namespace osgProducer { struct MyWindowingSystemInterface : public osg::GraphicsContext::WindowingSystemInterface { virtual unsigned int getNumScreens(const osg::GraphicsContext::ScreenIdentifier& /*screenIdentifier*/) { return Producer::RenderSurface::getNumberOfScreens(); } virtual void getScreenResolution(const osg::GraphicsContext::ScreenIdentifier& screenIdentifier, unsigned int& width, unsigned int& height) { osg::ref_ptr<Producer::RenderSurface> rs = new Producer::RenderSurface; rs->setHostName(screenIdentifier.hostName); rs->setDisplayNum(screenIdentifier.displayNum); rs->setScreenNum(screenIdentifier.screenNum); rs->getScreenSize(width, height); } virtual osg::GraphicsContext* createGraphicsContext(osg::GraphicsContext::Traits* traits) { return new GraphicsContextImplementation(traits); } }; struct RegisterWindowingSystemInterfaceProxy { RegisterWindowingSystemInterfaceProxy() { osg::GraphicsContext::setWindowingSystemInterface(new MyWindowingSystemInterface); } ~RegisterWindowingSystemInterfaceProxy() { osg::GraphicsContext::setWindowingSystemInterface(0); } }; RegisterWindowingSystemInterfaceProxy createWindowingSystemInterfaceProxy; }; #endif GraphicsContextImplementation::GraphicsContextImplementation(Traits* traits) { _traits = traits; _rs = new Producer::RenderSurface; _rs->setWindowName(traits->windowName); _rs->setWindowRectangle(traits->x, traits->y, traits->width, traits->height); _rs->useBorder(traits->windowDecoration); _rs->setDisplayNum(traits->displayNum); _rs->setScreenNum(traits->screenNum); // set the visual chooser Producer::VisualChooser* rs_vc = _rs->getVisualChooser(); if (!rs_vc) { rs_vc = new Producer::VisualChooser; _rs->setVisualChooser(rs_vc); } rs_vc->setRedSize(_traits->red); rs_vc->setGreenSize(_traits->green); rs_vc->setBlueSize(_traits->blue); rs_vc->setAlphaSize(_traits->alpha); rs_vc->setDepthSize(_traits->depth); rs_vc->setStencilSize(_traits->stencil); if (_traits->doubleBuffer) rs_vc->useDoubleBuffer(); rs_vc->addAttribute( Producer::VisualChooser::RGBA ); // Always use UseGL rs_vc->addAttribute( Producer::VisualChooser::UseGL ); if (traits->pbuffer) { _rs->setDrawableType(Producer::RenderSurface::DrawableType_PBuffer); if (traits->target) { _rs->setRenderToTextureOptions(traits->mipMapGeneration ? Producer::RenderSurface::RequestSpaceForMipMaps : Producer::RenderSurface::RenderToTextureOptions_Default); _rs->setRenderToTextureMipMapLevel(traits->level); _rs->setRenderToTextureMode(traits->alpha>0 ? Producer::RenderSurface::RenderToRGBATexture : Producer::RenderSurface::RenderToRGBTexture); switch(traits->target) { case(GL_TEXTURE_1D) : _rs->setRenderToTextureTarget(Producer::RenderSurface::Texture1D); break; case(GL_TEXTURE_2D) : _rs->setRenderToTextureTarget(Producer::RenderSurface::Texture2D); break; case(GL_TEXTURE_3D) : osg::notify(osg::NOTICE)<<"PBuffer render to Texture3D not supported."<<std::endl; // not supported. // _rs->setRenderToTextureTarget(Producer::RenderSurface::Texture3D); break; case(GL_TEXTURE_RECTANGLE) : osg::notify(osg::NOTICE)<<"PBuffer render to TextureRectangle not supported."<<std::endl; // not supported. // _rs->setRenderToTextureTarget(Producer::RenderSurface::TextureRectangle); break; case(GL_TEXTURE_CUBE_MAP_POSITIVE_X) : case(GL_TEXTURE_CUBE_MAP_NEGATIVE_X) : case(GL_TEXTURE_CUBE_MAP_POSITIVE_Y) : case(GL_TEXTURE_CUBE_MAP_NEGATIVE_Y) : case(GL_TEXTURE_CUBE_MAP_POSITIVE_Z) : case(GL_TEXTURE_CUBE_MAP_NEGATIVE_Z) : _rs->setRenderToTextureTarget(Producer::RenderSurface::TextureCUBE); _rs->setRenderToTextureFace( Producer::RenderSurface::CubeMapFace(traits->target - GL_TEXTURE_CUBE_MAP_POSITIVE_X)); break; } } } GraphicsContextImplementation* sharedContext = dynamic_cast<GraphicsContextImplementation*>(traits->sharedContext); if (sharedContext) { // different graphics context so we have our own state. setState(new osg::State); if (sharedContext->getState()) { getState()->setContextID( sharedContext->getState()->getContextID() ); incrementContextIDUsageCount( sharedContext->getState()->getContextID() ); } else { getState()->setContextID( osg::GraphicsContext::createNewContextID() ); } // but we share texture objects etc. so we also share the same contextID //_rs->realize( 0, sharedContext->_rs->getGLContext() ); } else { // need to do something here.... setState( new osg::State ); getState()->setContextID( osg::GraphicsContext::createNewContextID() ); //_rs->realize(); } // _rs->useConfigEventThread(false); _closeOnDestruction = true; } GraphicsContextImplementation::GraphicsContextImplementation(Producer::RenderSurface* rs) { _rs = rs; _closeOnDestruction = false; _traits = new osg::GraphicsContext::Traits; _traits->windowName = _rs->getWindowName(); _traits->displayNum = _rs->getDisplayNum(); _traits->screenNum = _rs->getScreenNum(); } GraphicsContextImplementation::~GraphicsContextImplementation() { if (_closeOnDestruction) close(); } bool GraphicsContextImplementation::realizeImplementation() { if (_rs.valid()) { GraphicsContextImplementation* sharedContext = dynamic_cast<GraphicsContextImplementation*>(_traits->sharedContext); if (sharedContext) { _rs->realize( 0, sharedContext->_rs->getGLContext() ); } else { osg::notify(osg::NOTICE)<<"GraphicsContextImplementation::realize"<<std::endl; _rs->realize(); } return _rs->isRealized(); } else { return false; } } bool GraphicsContextImplementation::makeCurrentImplementation() { if (!_rs) { osg::notify(osg::NOTICE)<<"Error: GraphicsContextImplementation::makeCurrentImplementation() no RenderSurface."<<std::endl; return false; } if (!isRealized()) { osg::notify(osg::NOTICE)<<"Error: GraphicsContextImplementation::makeCurrentImplementation() not Realized."<<std::endl; return false; } // osg::notify(osg::INFO)<<"GraphicsContextImplementation::makeCurrentImplementation()"<<std::endl; _rs->setReadDrawable( 0 ); // comment out right now, as Producer's setReadDrawable() is doing a call for us. // _rs->makeCurrent(); return true; } bool GraphicsContextImplementation::makeContextCurrentImplementation(osg::GraphicsContext* readContext) { if (!_rs) return false; GraphicsContextImplementation* readContextImplemention = dynamic_cast<GraphicsContextImplementation*>(readContext); if (readContextImplemention) { _rs->setReadDrawable( readContextImplemention->getRenderSurface() ); } else { _rs->setReadDrawable( 0 ); } // comment out right now, as Producer's setReadDrawable() is doing a call for us. // _rs->makeCurrent(); return true; } bool GraphicsContextImplementation::releaseContextImplementation() { osg::notify(osg::NOTICE)<<"GraphicsContextImplementation::releaseContextImplementation(): not implemented - release not supported under Producer."<<std::endl; return false; } void GraphicsContextImplementation::closeImplementation() { if (!_rs) return; // close render surface by deleting it _rs = 0; } void GraphicsContextImplementation::bindPBufferToTextureImplementation(GLenum buffer) { if (!_rs) return; Producer::RenderSurface::BufferType bufferType = Producer::RenderSurface::FrontBuffer; switch(buffer) { case(GL_BACK): bufferType = Producer::RenderSurface::BackBuffer; break; case(GL_FRONT): bufferType = Producer::RenderSurface::FrontBuffer; break; default: bufferType = Producer::RenderSurface::FrontBuffer; break; } _rs->bindPBufferToTexture(bufferType); } void GraphicsContextImplementation::swapBuffersImplementation() { _rs->swapBuffers(); } <|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_SPACES_CONTINUOUSLAGRANGE_BASE_HH #define DUNE_GDT_SPACES_CONTINUOUSLAGRANGE_BASE_HH #include <type_traits> #include <dune/common/typetraits.hh> #include <dune/common/dynvector.hh> #include <dune/stuff/common/disable_warnings.hh> #if DUNE_VERSION_NEWER(DUNE_COMMON, 3, 9) // EXADUNE #include <dune/geometry/referenceelements.hh> #else #include <dune/geometry/genericreferenceelements.hh> #endif #include <dune/stuff/common/reenable_warnings.hh> #include <dune/stuff/common/exceptions.hh> #include "../interface.hh" namespace Dune { namespace GDT { namespace Spaces { // forward, to allow for specialization template <class ImpTraits, int domainDim, class RangeFieldImp, int rangeDim, int rangeDimCols = 1> class ContinuousLagrangeBase { static_assert(AlwaysFalse<ImpTraits>::value, "Untested for these dimensions!"); }; template <class ImpTraits, int domainDim, class RangeFieldImp, int rangeDim> class ContinuousLagrangeBase<ImpTraits, domainDim, RangeFieldImp, rangeDim, 1> : public SpaceInterface<ImpTraits> { typedef SpaceInterface<ImpTraits> BaseType; typedef ContinuousLagrangeBase<ImpTraits, domainDim, RangeFieldImp, rangeDim, 1> ThisType; static constexpr RangeFieldImp compare_tolerance_ = 1e-13; public: typedef ImpTraits Traits; using BaseType::polOrder; using typename BaseType::DomainFieldType; using BaseType::dimDomain; using typename BaseType::DomainType; typedef typename Traits::RangeFieldType RangeFieldType; using BaseType::dimRange; using BaseType::dimRangeCols; using typename BaseType::EntityType; using typename BaseType::IntersectionType; using typename BaseType::BoundaryInfoType; using typename BaseType::PatternType; virtual ~ContinuousLagrangeBase() { } using BaseType::compute_pattern; template <class G, class S> PatternType compute_pattern(const GridView<G>& local_grid_view, const SpaceInterface<S>& ansatz_space) const { return BaseType::compute_volume_pattern(local_grid_view, ansatz_space); } virtual std::vector<DomainType> lagrange_points(const EntityType& entity) const { // check static_assert(polOrder == 1, "Not tested for higher polynomial orders!"); if (dimRange != 1) DUNE_THROW(NotImplemented, "Does not work for higher dimensions"); assert(this->grid_view()->indexSet().contains(entity)); // get the basis and reference element const auto basis = this->base_function_set(entity); const auto& reference_element = ReferenceElements<DomainFieldType, dimDomain>::general(entity.type()); const int num_vertices = reference_element.size(dimDomain); assert(num_vertices >= 0); assert(size_t(num_vertices) == basis.size() && "This should not happen with polOrder 1!"); // prepare return vector std::vector<DomainType> local_vertices(num_vertices, DomainType(0)); if (this->tmp_basis_values_.size() < basis.size()) this->tmp_basis_values_.resize(basis.size()); // loop over all vertices for (int ii = 0; ii < num_vertices; ++ii) { // get the local coordinate of the iith vertex const auto local_vertex = reference_element.position(ii, dimDomain); // evaluate the basefunctionset basis.evaluate(local_vertex, this->tmp_basis_values_); // find the basis function that evaluates to one here (has to be only one!) size_t ones = 0; size_t zeros = 0; size_t failures = 0; for (size_t jj = 0; jj < basis.size(); ++jj) { if (std::abs(this->tmp_basis_values_[jj][0] - RangeFieldType(1)) < compare_tolerance_) { local_vertices[jj] = local_vertex; ++ones; } else if (std::abs(this->tmp_basis_values_[jj][0]) < compare_tolerance_) ++zeros; else ++failures; } assert(ones == 1 && zeros == (basis.size() - 1) && failures == 0 && "This must not happen for polOrder 1!"); } return local_vertices; } // ... lagrange_points(...) virtual std::set<size_t> local_dirichlet_DoFs(const EntityType& entity, const BoundaryInfoType& boundaryInfo) const { static_assert(polOrder == 1, "Not tested for higher polynomial orders!"); if (dimRange != 1) DUNE_THROW(NotImplemented, "Does not work for higher dimensions"); // check assert(this->grid_view()->indexSet().contains(entity)); // prepare std::set<size_t> localDirichletDofs; std::vector<DomainType> dirichlet_vertices; // get all dirichlet vertices of this entity, therefore // * loop over all intersections const auto intersection_it_end = this->grid_view()->iend(entity); for (auto intersection_it = this->grid_view()->ibegin(entity); intersection_it != intersection_it_end; ++intersection_it) { // only work on dirichlet ones const auto& intersection = *intersection_it; // actual dirichlet intersections + process boundaries for parallel runs if (boundaryInfo.dirichlet(intersection) || (!intersection.neighbor() && !intersection.boundary())) { // and get the vertices of the intersection const auto geometry = intersection.geometry(); for (int cc = 0; cc < geometry.corners(); ++cc) dirichlet_vertices.emplace_back(entity.geometry().local(geometry.corner(cc))); } // only work on dirichlet ones } // loop over all intersections // find the corresponding basis functions const auto basis = this->base_function_set(entity); if (this->tmp_basis_values_.size() < basis.size()) this->tmp_basis_values_.resize(basis.size()); for (size_t cc = 0; cc < dirichlet_vertices.size(); ++cc) { // find the basis function that evaluates to one here (has to be only one!) basis.evaluate(dirichlet_vertices[cc], this->tmp_basis_values_); size_t ones = 0; size_t zeros = 0; size_t failures = 0; for (size_t jj = 0; jj < basis.size(); ++jj) { if (std::abs(this->tmp_basis_values_[jj][0] - RangeFieldType(1)) < compare_tolerance_) { localDirichletDofs.insert(jj); ++ones; } else if (std::abs(this->tmp_basis_values_[jj][0]) < compare_tolerance_) ++zeros; else ++failures; } assert(ones == 1 && zeros == (basis.size() - 1) && failures == 0 && "This must not happen for polOrder 1!"); } return localDirichletDofs; } // ... local_dirichlet_DoFs(...) private: template <class C, bool set_row> struct DirichletConstraints; template <class C> struct DirichletConstraints<C, true> { static RangeFieldType value() { return RangeFieldType(1); } }; template <class C> struct DirichletConstraints<C, false> { static RangeFieldType value() { return RangeFieldType(0); } }; template <class T, bool set_row> void compute_local_constraints(const SpaceInterface<T>& other, const EntityType& entity, Constraints::Dirichlet<IntersectionType, RangeFieldType, set_row>& ret) const { // check static_assert(polOrder == 1, "Not tested for higher polynomial orders!"); if (dimRange != 1) DUNE_THROW(NotImplemented, "Does not work for higher dimensions"); assert(this->grid_view()->indexSet().contains(entity)); typedef DirichletConstraints<Constraints::Dirichlet<IntersectionType, RangeFieldType, set_row>, set_row> SetRow; const std::set<size_t> localDirichletDofs = this->local_dirichlet_DoFs(entity, ret.gridBoundary()); const size_t numRows = localDirichletDofs.size(); if (numRows > 0) { const size_t numCols = this->mapper().numDofs(entity); ret.setSize(numRows, numCols); this->mapper().globalIndices(entity, tmpMappedRows_); other.mapper().globalIndices(entity, tmpMappedCols_); size_t localRow = 0; const RangeFieldType zero(0); for (auto localDirichletDofIt = localDirichletDofs.begin(); localDirichletDofIt != localDirichletDofs.end(); ++localDirichletDofIt) { const size_t& localDirichletDofIndex = *localDirichletDofIt; ret.globalRow(localRow) = tmpMappedRows_[localDirichletDofIndex]; for (size_t jj = 0; jj < ret.cols(); ++jj) { ret.globalCol(jj) = tmpMappedCols_[jj]; if (tmpMappedCols_[jj] == tmpMappedRows_[localDirichletDofIndex]) ret.value(localRow, jj) = SetRow::value(); else ret.value(localRow, jj) = zero; } ++localRow; } } else { ret.setSize(0, 0); } } // ... compute_local_constraints(..., Dirichlet< ..., true >) public: template <bool set> void local_constraints(const EntityType& entity, Constraints::Dirichlet<IntersectionType, RangeFieldType, set>& ret) const { local_constraints(*this, entity, ret); } virtual void local_constraints(const ThisType& other, const EntityType& entity, Constraints::Dirichlet<IntersectionType, RangeFieldType, true>& ret) const { compute_local_constraints(other, entity, ret); } virtual void local_constraints(const ThisType& other, const EntityType& entity, Constraints::Dirichlet<IntersectionType, RangeFieldType, false>& ret) const { compute_local_constraints(other, entity, ret); } protected: mutable Dune::DynamicVector<size_t> tmpMappedRows_; mutable Dune::DynamicVector<size_t> tmpMappedCols_; }; // class ContinuousLagrangeBase } // namespace Spaces } // namespace GDT } // namespace Dune #endif // DUNE_GDT_SPACES_CONTINUOUSLAGRANGE_BASE_HH <commit_msg>[spaces.continuouslagrange.base] fix (clang) compile error<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_SPACES_CONTINUOUSLAGRANGE_BASE_HH #define DUNE_GDT_SPACES_CONTINUOUSLAGRANGE_BASE_HH #include <type_traits> #include <dune/common/typetraits.hh> #include <dune/common/dynvector.hh> #include <dune/common/version.hh> #include <dune/stuff/common/disable_warnings.hh> #if DUNE_VERSION_NEWER(DUNE_COMMON, 3, 9) // EXADUNE #include <dune/geometry/referenceelements.hh> #else #include <dune/geometry/genericreferenceelements.hh> #endif #include <dune/stuff/common/reenable_warnings.hh> #include <dune/stuff/common/exceptions.hh> #include "../interface.hh" namespace Dune { namespace GDT { namespace Spaces { // forward, to allow for specialization template <class ImpTraits, int domainDim, class RangeFieldImp, int rangeDim, int rangeDimCols = 1> class ContinuousLagrangeBase { static_assert(AlwaysFalse<ImpTraits>::value, "Untested for these dimensions!"); }; template <class ImpTraits, int domainDim, class RangeFieldImp, int rangeDim> class ContinuousLagrangeBase<ImpTraits, domainDim, RangeFieldImp, rangeDim, 1> : public SpaceInterface<ImpTraits> { typedef SpaceInterface<ImpTraits> BaseType; typedef ContinuousLagrangeBase<ImpTraits, domainDim, RangeFieldImp, rangeDim, 1> ThisType; static constexpr RangeFieldImp compare_tolerance_ = 1e-13; public: typedef ImpTraits Traits; using BaseType::polOrder; using typename BaseType::DomainFieldType; using BaseType::dimDomain; using typename BaseType::DomainType; typedef typename Traits::RangeFieldType RangeFieldType; using BaseType::dimRange; using BaseType::dimRangeCols; using typename BaseType::EntityType; using typename BaseType::IntersectionType; using typename BaseType::BoundaryInfoType; using typename BaseType::PatternType; virtual ~ContinuousLagrangeBase() { } using BaseType::compute_pattern; template <class G, class S> PatternType compute_pattern(const GridView<G>& local_grid_view, const SpaceInterface<S>& ansatz_space) const { return BaseType::compute_volume_pattern(local_grid_view, ansatz_space); } virtual std::vector<DomainType> lagrange_points(const EntityType& entity) const { // check static_assert(polOrder == 1, "Not tested for higher polynomial orders!"); if (dimRange != 1) DUNE_THROW(NotImplemented, "Does not work for higher dimensions"); assert(this->grid_view()->indexSet().contains(entity)); // get the basis and reference element const auto basis = this->base_function_set(entity); const auto& reference_element = ReferenceElements<DomainFieldType, dimDomain>::general(entity.type()); const int num_vertices = reference_element.size(dimDomain); assert(num_vertices >= 0); assert(size_t(num_vertices) == basis.size() && "This should not happen with polOrder 1!"); // prepare return vector std::vector<DomainType> local_vertices(num_vertices, DomainType(0)); if (this->tmp_basis_values_.size() < basis.size()) this->tmp_basis_values_.resize(basis.size()); // loop over all vertices for (int ii = 0; ii < num_vertices; ++ii) { // get the local coordinate of the iith vertex const auto local_vertex = reference_element.position(ii, dimDomain); // evaluate the basefunctionset basis.evaluate(local_vertex, this->tmp_basis_values_); // find the basis function that evaluates to one here (has to be only one!) size_t ones = 0; size_t zeros = 0; size_t failures = 0; for (size_t jj = 0; jj < basis.size(); ++jj) { if (std::abs(this->tmp_basis_values_[jj][0] - RangeFieldType(1)) < compare_tolerance_) { local_vertices[jj] = local_vertex; ++ones; } else if (std::abs(this->tmp_basis_values_[jj][0]) < compare_tolerance_) ++zeros; else ++failures; } assert(ones == 1 && zeros == (basis.size() - 1) && failures == 0 && "This must not happen for polOrder 1!"); } return local_vertices; } // ... lagrange_points(...) virtual std::set<size_t> local_dirichlet_DoFs(const EntityType& entity, const BoundaryInfoType& boundaryInfo) const { static_assert(polOrder == 1, "Not tested for higher polynomial orders!"); if (dimRange != 1) DUNE_THROW(NotImplemented, "Does not work for higher dimensions"); // check assert(this->grid_view()->indexSet().contains(entity)); // prepare std::set<size_t> localDirichletDofs; std::vector<DomainType> dirichlet_vertices; // get all dirichlet vertices of this entity, therefore // * loop over all intersections const auto intersection_it_end = this->grid_view()->iend(entity); for (auto intersection_it = this->grid_view()->ibegin(entity); intersection_it != intersection_it_end; ++intersection_it) { // only work on dirichlet ones const auto& intersection = *intersection_it; // actual dirichlet intersections + process boundaries for parallel runs if (boundaryInfo.dirichlet(intersection) || (!intersection.neighbor() && !intersection.boundary())) { // and get the vertices of the intersection const auto geometry = intersection.geometry(); for (int cc = 0; cc < geometry.corners(); ++cc) dirichlet_vertices.emplace_back(entity.geometry().local(geometry.corner(cc))); } // only work on dirichlet ones } // loop over all intersections // find the corresponding basis functions const auto basis = this->base_function_set(entity); if (this->tmp_basis_values_.size() < basis.size()) this->tmp_basis_values_.resize(basis.size()); for (size_t cc = 0; cc < dirichlet_vertices.size(); ++cc) { // find the basis function that evaluates to one here (has to be only one!) basis.evaluate(dirichlet_vertices[cc], this->tmp_basis_values_); size_t ones = 0; size_t zeros = 0; size_t failures = 0; for (size_t jj = 0; jj < basis.size(); ++jj) { if (std::abs(this->tmp_basis_values_[jj][0] - RangeFieldType(1)) < compare_tolerance_) { localDirichletDofs.insert(jj); ++ones; } else if (std::abs(this->tmp_basis_values_[jj][0]) < compare_tolerance_) ++zeros; else ++failures; } assert(ones == 1 && zeros == (basis.size() - 1) && failures == 0 && "This must not happen for polOrder 1!"); } return localDirichletDofs; } // ... local_dirichlet_DoFs(...) private: template <class C, bool set_row> struct DirichletConstraints; template <class C> struct DirichletConstraints<C, true> { static RangeFieldType value() { return RangeFieldType(1); } }; template <class C> struct DirichletConstraints<C, false> { static RangeFieldType value() { return RangeFieldType(0); } }; template <class T, bool set_row> void compute_local_constraints(const SpaceInterface<T>& other, const EntityType& entity, Constraints::Dirichlet<IntersectionType, RangeFieldType, set_row>& ret) const { // check static_assert(polOrder == 1, "Not tested for higher polynomial orders!"); if (dimRange != 1) DUNE_THROW(NotImplemented, "Does not work for higher dimensions"); assert(this->grid_view()->indexSet().contains(entity)); typedef DirichletConstraints<Constraints::Dirichlet<IntersectionType, RangeFieldType, set_row>, set_row> SetRow; const std::set<size_t> localDirichletDofs = this->local_dirichlet_DoFs(entity, ret.gridBoundary()); const size_t numRows = localDirichletDofs.size(); if (numRows > 0) { const size_t numCols = this->mapper().numDofs(entity); ret.setSize(numRows, numCols); this->mapper().globalIndices(entity, tmpMappedRows_); other.mapper().globalIndices(entity, tmpMappedCols_); size_t localRow = 0; const RangeFieldType zero(0); for (auto localDirichletDofIt = localDirichletDofs.begin(); localDirichletDofIt != localDirichletDofs.end(); ++localDirichletDofIt) { const size_t& localDirichletDofIndex = *localDirichletDofIt; ret.globalRow(localRow) = tmpMappedRows_[localDirichletDofIndex]; for (size_t jj = 0; jj < ret.cols(); ++jj) { ret.globalCol(jj) = tmpMappedCols_[jj]; if (tmpMappedCols_[jj] == tmpMappedRows_[localDirichletDofIndex]) ret.value(localRow, jj) = SetRow::value(); else ret.value(localRow, jj) = zero; } ++localRow; } } else { ret.setSize(0, 0); } } // ... compute_local_constraints(..., Dirichlet< ..., true >) public: template <bool set> void local_constraints(const EntityType& entity, Constraints::Dirichlet<IntersectionType, RangeFieldType, set>& ret) const { local_constraints(*this, entity, ret); } virtual void local_constraints(const ThisType& other, const EntityType& entity, Constraints::Dirichlet<IntersectionType, RangeFieldType, true>& ret) const { compute_local_constraints(other, entity, ret); } virtual void local_constraints(const ThisType& other, const EntityType& entity, Constraints::Dirichlet<IntersectionType, RangeFieldType, false>& ret) const { compute_local_constraints(other, entity, ret); } protected: mutable Dune::DynamicVector<size_t> tmpMappedRows_; mutable Dune::DynamicVector<size_t> tmpMappedCols_; }; // class ContinuousLagrangeBase } // namespace Spaces } // namespace GDT } // namespace Dune #endif // DUNE_GDT_SPACES_CONTINUOUSLAGRANGE_BASE_HH <|endoftext|>
<commit_before>/* * Copyright 2017-2019 Leonid Yuriev <[email protected]> * and other libmdbx authors: please see AUTHORS file. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted only as authorized by the OpenLDAP * Public License. * * A copy of this license is available in the file LICENSE in the * top-level directory of the distribution or, alternatively, at * <http://www.OpenLDAP.org/license.html>. */ #include "test.h" #include <cmath> #include <queue> static unsigned edge2window(uint64_t edge, unsigned window_max) { const double rnd = u64_to_double1(bleach64(edge)); const unsigned window = window_max - std::lrint(std::pow(window_max, rnd)); return window - (window > 0); } static unsigned edge2count(uint64_t edge, unsigned count_max) { const double rnd = u64_to_double1(prng64_map1_white(edge)); const unsigned count = std::lrint(std::pow(count_max, rnd)); return count; } bool testcase_ttl::run() { db_open(); txn_begin(false); MDBX_dbi dbi = db_table_open(true); int rc = mdbx_drop(txn_guard.get(), dbi, false); if (unlikely(rc != MDBX_SUCCESS)) failure_perror("mdbx_drop(delete=false)", rc); txn_end(false); /* LY: тест "эмуляцией time-to-live": * - организуется "скользящее окно", которое двигается вперед вдоль * числовой оси каждую транзакцию. * - по переднему краю "скользящего окна" записи добавляются в таблицу, * а по заднему удаляются. * - количество добавляемых/удаляемых записей псевдослучайно зависит * от номера транзакции, но с экспоненциальным распределением. * - размер "скользящего окна" также псевдослучайно зависит от номера * транзакции с "отрицательным" экспоненциальным распределением * MAX_WIDTH - exp(rnd(N)), при уменьшении окна сдвигается задний * край и удаляются записи позади него. * * Таким образом имитируется поведение таблицы с TTL: записи стохастически * добавляются и удаляются, но изредка происходят массивные удаления. */ /* LY: для параметризации используем подходящие параметры, которые не имеют * здесь смысла в первоначальном значении */ const unsigned window_max = (config.params.batch_read > 999) ? config.params.batch_read : 1000; const unsigned count_max = (config.params.batch_write > 999) ? config.params.batch_write : 1000; log_info("ttl: using `batch_read` value %u for window_max", window_max); log_info("ttl: using `batch_write` value %u for count_max", count_max); uint64_t seed = prng64_map2_white(config.params.keygen.seed) + config.actor_id; keyvalue_maker.setup(config.params, config.actor_id, 0 /* thread_number */); key = keygen::alloc(config.params.keylen_max); data = keygen::alloc(config.params.datalen_max); const unsigned insert_flags = (config.params.table_flags & MDBX_DUPSORT) ? MDBX_NODUPDATA : MDBX_NODUPDATA | MDBX_NOOVERWRITE; std::queue<std::pair<uint64_t, unsigned>> fifo; uint64_t serial = 0; while (should_continue()) { if (!txn_guard) txn_begin(false); const uint64_t salt = prng64_white(seed)/* mdbx_txn_id(txn_guard.get()) */; const unsigned window = edge2window(salt, window_max); log_trace("ttl: window %u at %" PRIu64, window, salt); while (fifo.size() > window) { uint64_t tail_serial = fifo.front().first; const unsigned tail_count = fifo.front().second; log_trace("ttl: pop-tail (serial %" PRIu64 ", count %u)", tail_serial, tail_count); fifo.pop(); for (unsigned n = 0; n < tail_count; ++n) { log_trace("ttl: remove-tail %" PRIu64, serial); generate_pair(tail_serial); int err = mdbx_del(txn_guard.get(), dbi, &key->value, &data->value); if (unlikely(err != MDBX_SUCCESS)) failure_perror("mdbx_del(tail)", err); if (unlikely(!keyvalue_maker.increment(tail_serial, 1))) failure("ttl: unexpected key-space overflow on the tail"); } } txn_restart(false, false); const unsigned head_count = edge2count(salt, count_max); fifo.push(std::make_pair(serial, head_count)); log_trace("ttl: push-head (serial %" PRIu64 ", count %u)", serial, head_count); for (unsigned n = 0; n < head_count; ++n) { log_trace("ttl: insert-head %" PRIu64, serial); generate_pair(serial); int err = mdbx_put(txn_guard.get(), dbi, &key->value, &data->value, insert_flags); if (unlikely(err != MDBX_SUCCESS)) failure_perror("mdbx_put(head)", err); if (unlikely(!keyvalue_maker.increment(serial, 1))) failure("uphill: unexpected key-space overflow"); } txn_end(false); report(1); } if (dbi) { if (config.params.drop_table && !mode_readonly()) { txn_begin(false); db_table_drop(dbi); txn_end(false); } else db_table_close(dbi); } return true; } <commit_msg>mdbx-test: refine 'ttl' testcase.<commit_after>/* * Copyright 2017-2019 Leonid Yuriev <[email protected]> * and other libmdbx authors: please see AUTHORS file. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted only as authorized by the OpenLDAP * Public License. * * A copy of this license is available in the file LICENSE in the * top-level directory of the distribution or, alternatively, at * <http://www.OpenLDAP.org/license.html>. */ #include "test.h" #include <cmath> #include <deque> static unsigned edge2window(uint64_t edge, unsigned window_max) { const double rnd = u64_to_double1(bleach64(edge)); const unsigned window = window_max - std::lrint(std::pow(window_max, rnd)); return window; } static unsigned edge2count(uint64_t edge, unsigned count_max) { const double rnd = u64_to_double1(prng64_map1_white(edge)); const unsigned count = std::lrint(std::pow(count_max, rnd)); return count; } bool testcase_ttl::run() { db_open(); txn_begin(false); MDBX_dbi dbi = db_table_open(true); db_table_clear(dbi); txn_end(false); /* LY: тест "эмуляцией time-to-live": * - организуется "скользящее окно", которое двигается вперед вдоль * числовой оси каждую транзакцию. * - по переднему краю "скользящего окна" записи добавляются в таблицу, * а по заднему удаляются. * - количество добавляемых/удаляемых записей псевдослучайно зависит * от номера транзакции, но с экспоненциальным распределением. * - размер "скользящего окна" также псевдослучайно зависит от номера * транзакции с "отрицательным" экспоненциальным распределением * MAX_WIDTH - exp(rnd(N)), при уменьшении окна сдвигается задний * край и удаляются записи позади него. * * Таким образом имитируется поведение таблицы с TTL: записи стохастически * добавляются и удаляются, но изредка происходят массивные удаления. */ /* LY: для параметризации используем подходящие параметры, которые не имеют * здесь смысла в первоначальном значении */ const unsigned window_max = (config.params.batch_read > 999) ? config.params.batch_read : 1000; const unsigned count_max = (config.params.batch_write > 999) ? config.params.batch_write : 1000; log_info("ttl: using `batch_read` value %u for window_max", window_max); log_info("ttl: using `batch_write` value %u for count_max", count_max); uint64_t seed = prng64_map2_white(config.params.keygen.seed) + config.actor_id; keyvalue_maker.setup(config.params, config.actor_id, 0 /* thread_number */); key = keygen::alloc(config.params.keylen_max); data = keygen::alloc(config.params.datalen_max); const unsigned insert_flags = (config.params.table_flags & MDBX_DUPSORT) ? MDBX_NODUPDATA : MDBX_NODUPDATA | MDBX_NOOVERWRITE; std::deque<std::pair<uint64_t, unsigned>> fifo; uint64_t serial = 0; while (should_continue()) { if (!txn_guard) txn_begin(false); const uint64_t salt = prng64_white(seed) /* mdbx_txn_id(txn_guard.get()) */; const unsigned window_width = edge2window(salt, window_max); const unsigned head_count = edge2count(salt, count_max); log_info("ttl: step #%zu (serial %" PRIu64 ", window %u, count %u) salt %" PRIu64, nops_completed, serial, window_width, head_count, salt); if (window_width) { while (fifo.size() > window_width) { uint64_t tail_serial = fifo.back().first; const unsigned tail_count = fifo.back().second; log_trace("ttl: pop-tail (serial %" PRIu64 ", count %u)", tail_serial, tail_count); fifo.pop_back(); for (unsigned n = 0; n < tail_count; ++n) { log_trace("ttl: remove-tail %" PRIu64, serial); generate_pair(tail_serial); int err = mdbx_del(txn_guard.get(), dbi, &key->value, &data->value); if (unlikely(err != MDBX_SUCCESS)) failure_perror("mdbx_del(tail)", err); if (unlikely(!keyvalue_maker.increment(tail_serial, 1))) failure("ttl: unexpected key-space overflow on the tail"); } } } else { log_trace("ttl: purge state"); db_table_clear(dbi); fifo.clear(); } txn_restart(false, false); fifo.push_front(std::make_pair(serial, head_count)); for (unsigned n = 0; n < head_count; ++n) { log_trace("ttl: insert-head %" PRIu64, serial); generate_pair(serial); int err = mdbx_put(txn_guard.get(), dbi, &key->value, &data->value, insert_flags); if (unlikely(err != MDBX_SUCCESS)) failure_perror("mdbx_put(head)", err); if (unlikely(!keyvalue_maker.increment(serial, 1))) failure("uphill: unexpected key-space overflow"); } txn_end(false); report(1); } if (dbi) { if (config.params.drop_table && !mode_readonly()) { txn_begin(false); db_table_drop(dbi); txn_end(false); } else db_table_close(dbi); } return true; } <|endoftext|>
<commit_before>//============================================================================================================= /** * @file natus.cpp * @author Lorenz Esch <[email protected]> * @version dev * @date June, 2018 * * @section LICENSE * * Copyright (C) 2018, Lorenz Esch. 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 MNE-CPP authors 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. * * * @brief Contains the definition of the Natus class. * */ //============================================================================================================= // INCLUDES //============================================================================================================= #include "natus.h" #include "natusproducer.h" #include "FormFiles/natussetup.h" #include <fiff/fiff.h> #include <scMeas/realtimemultisamplearray.h> //============================================================================================================= // QT INCLUDES //============================================================================================================= #include <QSettings> //============================================================================================================= // EIGEN INCLUDES //============================================================================================================= //============================================================================================================= // USED NAMESPACES //============================================================================================================= using namespace NATUSPLUGIN; using namespace SCSHAREDLIB; using namespace SCMEASLIB; using namespace FIFFLIB; using namespace Eigen; using namespace IOBUFFER; //============================================================================================================= // DEFINE MEMBER METHODS //============================================================================================================= Natus::Natus() : m_iSamplingFreq(2048) , m_iNumberChannels(46) , m_iSamplesPerBlock(256) , m_pFiffInfo(QSharedPointer<FiffInfo>::create()) , m_pRMTSA_Natus(PluginOutputData<RealTimeMultiSampleArray>::create(this, "Natus", "EEG output data")) , m_qStringResourcePath(qApp->applicationDirPath()+"/resources/mne_scan/plugins/natus/") { m_pRMTSA_Natus->data()->setName(this->getName());//Provide name to auto store widget settings } //============================================================================================================= Natus::~Natus() { //If the program is closed while the sampling is in process if(this->isRunning()) { this->stop(); } } //============================================================================================================= QSharedPointer<IPlugin> Natus::clone() const { QSharedPointer<Natus> pNatusClone(new Natus()); return pNatusClone; } //============================================================================================================= void Natus::init() { m_outputConnectors.append(m_pRMTSA_Natus); } //============================================================================================================= void Natus::unload() { } //============================================================================================================= void Natus::setUpFiffInfo() { //Clear old fiff info data m_pFiffInfo->clear(); //Set number of channels, sampling frequency and high/-lowpass m_pFiffInfo->nchan = m_iNumberChannels; m_pFiffInfo->sfreq = m_iSamplingFreq; m_pFiffInfo->highpass = 0.001f; m_pFiffInfo->lowpass = m_iSamplingFreq/2; //Set up the channel info QStringList QSLChNames; m_pFiffInfo->chs.clear(); for(int i = 0; i < m_pFiffInfo->nchan; ++i) { //Create information for each channel QString sChType; FiffChInfo fChInfo; // //EEG Channels // if(i <= m_pFiffInfo->nchan-2) // { //Set channel name sChType = QString("EEG "); if(i<10) { sChType.append("00"); } if(i>=10 && i<100) { sChType.append("0"); } fChInfo.ch_name = sChType.append(sChType.number(i)); //Set channel type fChInfo.kind = FIFFV_EEG_CH; //Set logno fChInfo.logNo = i; //Set coord frame fChInfo.coord_frame = FIFFV_COORD_HEAD; //Set unit fChInfo.unit = FIFF_UNIT_V; //Set EEG electrode location - Convert from mm to m fChInfo.eeg_loc(0,0) = 0; fChInfo.eeg_loc(1,0) = 0; fChInfo.eeg_loc(2,0) = 0; //Set EEG electrode direction - Convert from mm to m fChInfo.eeg_loc(0,1) = 0; fChInfo.eeg_loc(1,1) = 0; fChInfo.eeg_loc(2,1) = 0; //Also write the eeg electrode locations into the meg loc variable (mne_ex_read_raw() matlab function wants this) fChInfo.chpos.r0(0) = 0; fChInfo.chpos.r0(1) = 0; fChInfo.chpos.r0(2) = 0; fChInfo.chpos.ex(0) = 1; fChInfo.chpos.ex(1) = 0; fChInfo.chpos.ex(2) = 0; fChInfo.chpos.ey(0) = 0; fChInfo.chpos.ey(1) = 1; fChInfo.chpos.ey(2) = 0; fChInfo.chpos.ez(0) = 0; fChInfo.chpos.ez(1) = 0; fChInfo.chpos.ez(2) = 1; // } // //Digital input channel // if(i == m_pFiffInfo->nchan-1) // { // //Set channel type // fChInfo.kind = FIFFV_STIM_CH; // sChType = QString("STIM"); // fChInfo.ch_name = sChType; // } QSLChNames << sChType; m_pFiffInfo->chs.append(fChInfo); } //Set channel names in fiff_info_base m_pFiffInfo->ch_names = QSLChNames; //Set head projection m_pFiffInfo->dev_head_t.from = FIFFV_COORD_DEVICE; m_pFiffInfo->dev_head_t.to = FIFFV_COORD_HEAD; m_pFiffInfo->ctf_head_t.from = FIFFV_COORD_DEVICE; m_pFiffInfo->ctf_head_t.to = FIFFV_COORD_HEAD; } //============================================================================================================= bool Natus::start() { // Init circular buffer to transmit data from the producer to this thread if(!m_pCircularBuffer) { m_pCircularBuffer = QSharedPointer<CircularBuffer_Matrix_double>(new CircularBuffer_Matrix_double(10)); } //Setup fiff info before setting up the RMTSA because we need it to init the RTMSA setUpFiffInfo(); //Set the channel size of the RMTSA - this needs to be done here and NOT in the init() function because the user can change the number of channels during runtime m_pRMTSA_Natus->data()->initFromFiffInfo(m_pFiffInfo); m_pRMTSA_Natus->data()->setMultiArraySize(1); QThread::start(); // Start the producer m_pNatusProducer = QSharedPointer<NatusProducer>::create(m_iSamplesPerBlock, m_iNumberChannels); m_pNatusProducer->moveToThread(&m_pProducerThread); connect(m_pNatusProducer.data(), &NatusProducer::newDataAvailable, this, &Natus::onNewDataAvailable, Qt::DirectConnection); m_pProducerThread.start(); return true; } //============================================================================================================= bool Natus::stop() { requestInterruption(); wait(500); // Clear all data in the buffer connected to displays and other plugins m_pRMTSA_Natus->data()->clear(); m_pCircularBuffer->clear(); m_pProducerThread.quit(); m_pProducerThread.wait(); return true; } //============================================================================================================= IPlugin::PluginType Natus::getType() const { return _ISensor; } //============================================================================================================= QString Natus::getName() const { return "Natus EEG"; } //============================================================================================================= QWidget* Natus::setupWidget() { NatusSetup* widget = new NatusSetup(this);//widget is later destroyed by CentralWidget - so it has to be created everytime new //init properties dialog widget->initGui(); return widget; } //============================================================================================================= void Natus::onNewDataAvailable(const Eigen::MatrixXd &matData) { while(!m_pCircularBuffer->push(matData)) { //Do nothing until the circular buffer is ready to accept new data again } } //============================================================================================================= void Natus::run() { MatrixXd matData; while(!isInterruptionRequested()) { if(m_pCircularBuffer->pop(matData)) { //emit values if(!isInterruptionRequested()) { m_pRMTSA_Natus->data()->setValue(matData); } } } } <commit_msg>natus warnings<commit_after>//============================================================================================================= /** * @file natus.cpp * @author Lorenz Esch <[email protected]> * @version dev * @date June, 2018 * * @section LICENSE * * Copyright (C) 2018, Lorenz Esch. 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 MNE-CPP authors 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. * * * @brief Contains the definition of the Natus class. * */ //============================================================================================================= // INCLUDES //============================================================================================================= #include "natus.h" #include "natusproducer.h" #include "FormFiles/natussetup.h" #include <fiff/fiff.h> #include <scMeas/realtimemultisamplearray.h> //============================================================================================================= // QT INCLUDES //============================================================================================================= #include <QSettings> //============================================================================================================= // EIGEN INCLUDES //============================================================================================================= //============================================================================================================= // USED NAMESPACES //============================================================================================================= using namespace NATUSPLUGIN; using namespace SCSHAREDLIB; using namespace SCMEASLIB; using namespace FIFFLIB; using namespace Eigen; using namespace IOBUFFER; //============================================================================================================= // DEFINE MEMBER METHODS //============================================================================================================= Natus::Natus() : m_iSamplingFreq(2048) , m_iNumberChannels(46) , m_iSamplesPerBlock(256) , m_qStringResourcePath(qApp->applicationDirPath()+"/resources/mne_scan/plugins/natus/") , m_pRMTSA_Natus(PluginOutputData<RealTimeMultiSampleArray>::create(this, "Natus", "EEG output data")) , m_pFiffInfo(QSharedPointer<FiffInfo>::create()) { m_pRMTSA_Natus->data()->setName(this->getName());//Provide name to auto store widget settings } //============================================================================================================= Natus::~Natus() { //If the program is closed while the sampling is in process if(this->isRunning()) { this->stop(); } } //============================================================================================================= QSharedPointer<IPlugin> Natus::clone() const { QSharedPointer<IPlugin> pNatusClone(new Natus()); return pNatusClone; } //============================================================================================================= void Natus::init() { m_outputConnectors.append(m_pRMTSA_Natus); } //============================================================================================================= void Natus::unload() { } //============================================================================================================= void Natus::setUpFiffInfo() { //Clear old fiff info data m_pFiffInfo->clear(); //Set number of channels, sampling frequency and high/-lowpass m_pFiffInfo->nchan = m_iNumberChannels; m_pFiffInfo->sfreq = m_iSamplingFreq; m_pFiffInfo->highpass = 0.001f; m_pFiffInfo->lowpass = m_iSamplingFreq/2; //Set up the channel info QStringList QSLChNames; m_pFiffInfo->chs.clear(); for(int i = 0; i < m_pFiffInfo->nchan; ++i) { //Create information for each channel QString sChType; FiffChInfo fChInfo; // //EEG Channels // if(i <= m_pFiffInfo->nchan-2) // { //Set channel name sChType = QString("EEG "); if(i<10) { sChType.append("00"); } if(i>=10 && i<100) { sChType.append("0"); } fChInfo.ch_name = sChType.append(sChType.number(i)); //Set channel type fChInfo.kind = FIFFV_EEG_CH; //Set logno fChInfo.logNo = i; //Set coord frame fChInfo.coord_frame = FIFFV_COORD_HEAD; //Set unit fChInfo.unit = FIFF_UNIT_V; //Set EEG electrode location - Convert from mm to m fChInfo.eeg_loc(0,0) = 0; fChInfo.eeg_loc(1,0) = 0; fChInfo.eeg_loc(2,0) = 0; //Set EEG electrode direction - Convert from mm to m fChInfo.eeg_loc(0,1) = 0; fChInfo.eeg_loc(1,1) = 0; fChInfo.eeg_loc(2,1) = 0; //Also write the eeg electrode locations into the meg loc variable (mne_ex_read_raw() matlab function wants this) fChInfo.chpos.r0(0) = 0; fChInfo.chpos.r0(1) = 0; fChInfo.chpos.r0(2) = 0; fChInfo.chpos.ex(0) = 1; fChInfo.chpos.ex(1) = 0; fChInfo.chpos.ex(2) = 0; fChInfo.chpos.ey(0) = 0; fChInfo.chpos.ey(1) = 1; fChInfo.chpos.ey(2) = 0; fChInfo.chpos.ez(0) = 0; fChInfo.chpos.ez(1) = 0; fChInfo.chpos.ez(2) = 1; // } // //Digital input channel // if(i == m_pFiffInfo->nchan-1) // { // //Set channel type // fChInfo.kind = FIFFV_STIM_CH; // sChType = QString("STIM"); // fChInfo.ch_name = sChType; // } QSLChNames << sChType; m_pFiffInfo->chs.append(fChInfo); } //Set channel names in fiff_info_base m_pFiffInfo->ch_names = QSLChNames; //Set head projection m_pFiffInfo->dev_head_t.from = FIFFV_COORD_DEVICE; m_pFiffInfo->dev_head_t.to = FIFFV_COORD_HEAD; m_pFiffInfo->ctf_head_t.from = FIFFV_COORD_DEVICE; m_pFiffInfo->ctf_head_t.to = FIFFV_COORD_HEAD; } //============================================================================================================= bool Natus::start() { // Init circular buffer to transmit data from the producer to this thread if(!m_pCircularBuffer) { m_pCircularBuffer = QSharedPointer<CircularBuffer_Matrix_double>(new CircularBuffer_Matrix_double(10)); } //Setup fiff info before setting up the RMTSA because we need it to init the RTMSA setUpFiffInfo(); //Set the channel size of the RMTSA - this needs to be done here and NOT in the init() function because the user can change the number of channels during runtime m_pRMTSA_Natus->data()->initFromFiffInfo(m_pFiffInfo); m_pRMTSA_Natus->data()->setMultiArraySize(1); QThread::start(); // Start the producer m_pNatusProducer = QSharedPointer<NatusProducer>::create(m_iSamplesPerBlock, m_iNumberChannels); m_pNatusProducer->moveToThread(&m_pProducerThread); connect(m_pNatusProducer.data(), &NatusProducer::newDataAvailable, this, &Natus::onNewDataAvailable, Qt::DirectConnection); m_pProducerThread.start(); return true; } //============================================================================================================= bool Natus::stop() { requestInterruption(); wait(500); // Clear all data in the buffer connected to displays and other plugins m_pRMTSA_Natus->data()->clear(); m_pCircularBuffer->clear(); m_pProducerThread.quit(); m_pProducerThread.wait(); return true; } //============================================================================================================= IPlugin::PluginType Natus::getType() const { return _ISensor; } //============================================================================================================= QString Natus::getName() const { return "Natus EEG"; } //============================================================================================================= QWidget* Natus::setupWidget() { NatusSetup* widget = new NatusSetup(this);//widget is later destroyed by CentralWidget - so it has to be created everytime new //init properties dialog widget->initGui(); return widget; } //============================================================================================================= void Natus::onNewDataAvailable(const Eigen::MatrixXd &matData) { while(!m_pCircularBuffer->push(matData)) { //Do nothing until the circular buffer is ready to accept new data again } } //============================================================================================================= void Natus::run() { MatrixXd matData; while(!isInterruptionRequested()) { if(m_pCircularBuffer->pop(matData)) { //emit values if(!isInterruptionRequested()) { m_pRMTSA_Natus->data()->setValue(matData); } } } } <|endoftext|>
<commit_before>/*========================================================================= Program: Visualization Toolkit Module: vtkContourWidget.cxx Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ #include "vtkContourWidget.h" #include "vtkOrientedGlyphContourRepresentation.h" #include "vtkCommand.h" #include "vtkCallbackCommand.h" #include "vtkRenderWindowInteractor.h" #include "vtkObjectFactory.h" #include "vtkRenderer.h" #include "vtkWidgetCallbackMapper.h" #include "vtkSphereSource.h" #include "vtkProperty.h" #include "vtkEvent.h" #include "vtkWidgetEvent.h" #include <vtkstd/vector> #include <vtkstd/set> #include <vtkstd/algorithm> #include <vtkstd/iterator> vtkCxxRevisionMacro(vtkContourWidget, "1.3"); vtkStandardNewMacro(vtkContourWidget); //---------------------------------------------------------------------- vtkContourWidget::vtkContourWidget() { this->ManagesCursor = 0; this->WidgetState = vtkContourWidget::Start; this->CurrentHandle = 0; // These are the event callbacks supported by this widget this->CallbackMapper->SetCallbackMethod(vtkCommand::LeftButtonPressEvent, vtkWidgetEvent::Select, this, vtkContourWidget::SelectAction); this->CallbackMapper->SetCallbackMethod(vtkCommand::RightButtonPressEvent, vtkWidgetEvent::AddFinalPoint, this, vtkContourWidget::AddFinalPointAction); this->CallbackMapper->SetCallbackMethod(vtkCommand::MouseMoveEvent, vtkWidgetEvent::Move, this, vtkContourWidget::MoveAction); this->CallbackMapper->SetCallbackMethod(vtkCommand::LeftButtonReleaseEvent, vtkWidgetEvent::EndSelect, this, vtkContourWidget::EndSelectAction); this->CallbackMapper->SetCallbackMethod(vtkCommand::KeyPressEvent, vtkEvent::NoModifier, 46, 1, NULL, vtkWidgetEvent::Delete, this, vtkContourWidget::DeleteAction); this->CreateDefaultRepresentation(); } //---------------------------------------------------------------------- vtkContourWidget::~vtkContourWidget() { } //---------------------------------------------------------------------- void vtkContourWidget::CreateDefaultRepresentation() { if ( ! this->WidgetRep ) { vtkOrientedGlyphContourRepresentation *rep = vtkOrientedGlyphContourRepresentation::New(); this->WidgetRep = rep; vtkSphereSource *ss = vtkSphereSource::New(); ss->SetRadius(0.5); rep->SetActiveCursorShape( ss->GetOutput() ); ss->Delete(); rep->GetProperty()->SetColor(.25,1.0,.25); rep->GetActiveProperty()->SetRepresentationToSurface(); rep->GetActiveProperty()->SetAmbient(0.1); rep->GetActiveProperty()->SetDiffuse(0.9); rep->GetActiveProperty()->SetSpecular(0.0); } } //---------------------------------------------------------------------- void vtkContourWidget::ClearContour() { } //---------------------------------------------------------------------- void vtkContourWidget::SetEnabled(int enabling) { // The handle widgets are not actually enabled until they are placed. // The handle widgets take their representation from the vtkContourRepresentation. if ( enabling ) { if ( this->WidgetState == vtkContourWidget::Start ) { reinterpret_cast<vtkContourRepresentation*>(this->WidgetRep)->VisibilityOff(); } else { reinterpret_cast<vtkContourRepresentation*>(this->WidgetRep)->VisibilityOn(); } } this->Superclass::SetEnabled(enabling); } // The following methods are the callbacks that the measure widget responds to. //------------------------------------------------------------------------- void vtkContourWidget::SelectAction(vtkAbstractWidget *w) { vtkContourWidget *self = reinterpret_cast<vtkContourWidget*>(w); vtkContourRepresentation *rep = reinterpret_cast<vtkContourRepresentation*>(self->WidgetRep); int X = self->Interactor->GetEventPosition()[0]; int Y = self->Interactor->GetEventPosition()[1]; double pos[2]; pos[0] = X; pos[1] = Y; switch ( self->WidgetState ) { case vtkContourWidget::Start: case vtkContourWidget::Define: self->AddNode(); break; case vtkContourWidget::Manipulate: if ( rep->ActivateNode(X,Y) ) { self->StartInteraction(); rep->SetCurrentOperationToTranslate(); rep->StartWidgetInteraction(pos); self->EventCallbackCommand->SetAbortFlag(1); } else if ( rep->AddNodeOnContour( X, Y ) ) { if ( rep->ActivateNode(X,Y) ) { rep->SetCurrentOperationToTranslate(); rep->StartWidgetInteraction(pos); } self->EventCallbackCommand->SetAbortFlag(1); } break; } if ( rep->GetNeedToRender() ) { self->Render(); rep->NeedToRenderOff(); } } //------------------------------------------------------------------------- void vtkContourWidget::AddFinalPointAction(vtkAbstractWidget *w) { vtkContourWidget *self = reinterpret_cast<vtkContourWidget*>(w); vtkContourRepresentation *rep = reinterpret_cast<vtkContourRepresentation*>(self->WidgetRep); int X = self->Interactor->GetEventPosition()[0]; int Y = self->Interactor->GetEventPosition()[1]; double pos[2]; pos[0] = X; pos[1] = Y; if ( self->WidgetState == vtkContourWidget::Define && rep->GetNumberOfNodes() >= 1 ) { self->AddNode(); self->WidgetState = vtkContourWidget::Manipulate; self->EventCallbackCommand->SetAbortFlag(1); } if ( rep->GetNeedToRender() ) { self->Render(); rep->NeedToRenderOff(); } } //------------------------------------------------------------------------ void vtkContourWidget::AddNode() { int X = this->Interactor->GetEventPosition()[0]; int Y = this->Interactor->GetEventPosition()[1]; // If the rep already has at least 2 nodes, check how close we are to // the first if ( reinterpret_cast<vtkContourRepresentation*>(this->WidgetRep)-> GetNumberOfNodes() > 1 ) { int pixelTolerance2 = reinterpret_cast<vtkContourRepresentation*>(this->WidgetRep)-> GetPixelTolerance(); pixelTolerance2 *= pixelTolerance2; double displayPos[2]; if ( !reinterpret_cast<vtkContourRepresentation*>(this->WidgetRep)-> GetNthNodeDisplayPosition( 0, displayPos ) ) { vtkErrorMacro("Can't get first node display position!"); return; } if ( (X - displayPos[0]) * (X - displayPos[0]) + (Y - displayPos[1]) * (Y - displayPos[1]) < pixelTolerance2 ) { // yes - we have made a loop. Stop defining and switch to // manipulate mode this->WidgetState = vtkContourWidget::Manipulate; reinterpret_cast<vtkContourRepresentation*>(this->WidgetRep)->ClosedLoopOn(); this->EventCallbackCommand->SetAbortFlag(1); return; } } if ( reinterpret_cast<vtkContourRepresentation*>(this->WidgetRep)-> AddNodeAtDisplayPosition( X, Y ) ) { this->WidgetState = vtkContourWidget::Define; reinterpret_cast<vtkContourRepresentation*>(this->WidgetRep)->VisibilityOn(); this->EventCallbackCommand->SetAbortFlag(1); } } //------------------------------------------------------------------------- void vtkContourWidget::DeleteAction(vtkAbstractWidget *w) { vtkContourWidget *self = reinterpret_cast<vtkContourWidget*>(w); if ( self->WidgetState == vtkContourWidget::Start ) { return; } vtkContourRepresentation *rep = reinterpret_cast<vtkContourRepresentation*>(self->WidgetRep); if ( self->WidgetState == vtkContourWidget::Define ) { rep->DeleteLastNode(); } else { int X = self->Interactor->GetEventPosition()[0]; int Y = self->Interactor->GetEventPosition()[1]; rep->ActivateNode( X, Y ); rep->DeleteActiveNode(); rep->ActivateNode( X, Y ); if ( rep->GetNumberOfNodes() < 3 ) { rep->ClosedLoopOff(); self->WidgetState = vtkContourWidget::Define; } } if ( rep->GetNeedToRender() ) { self->Render(); rep->NeedToRenderOff(); } } //------------------------------------------------------------------------- void vtkContourWidget::MoveAction(vtkAbstractWidget *w) { vtkContourWidget *self = reinterpret_cast<vtkContourWidget*>(w); if ( self->WidgetState == vtkContourWidget::Start || self->WidgetState == vtkContourWidget::Define ) { return; } int X = self->Interactor->GetEventPosition()[0]; int Y = self->Interactor->GetEventPosition()[1]; vtkContourRepresentation *rep = reinterpret_cast<vtkContourRepresentation*>(self->WidgetRep); if ( rep->GetCurrentOperation() == vtkContourRepresentation::Inactive ) { reinterpret_cast<vtkContourRepresentation*>(self->WidgetRep)-> ComputeInteractionState( X, Y ); reinterpret_cast<vtkContourRepresentation*>(self->WidgetRep)-> ActivateNode( X, Y ); } else { double pos[2]; pos[0] = X; pos[1] = Y; self->WidgetRep->WidgetInteraction(pos); } self->Interaction(); if ( self->WidgetRep->GetNeedToRender() ) { self->Render(); self->WidgetRep->NeedToRenderOff(); } } //------------------------------------------------------------------------- void vtkContourWidget::EndSelectAction(vtkAbstractWidget *w) { vtkContourWidget *self = reinterpret_cast<vtkContourWidget*>(w); vtkContourRepresentation *rep = reinterpret_cast<vtkContourRepresentation*>(self->WidgetRep); // Do nothing if inactive if ( rep->GetCurrentOperation() == vtkContourRepresentation::Inactive ) { return; } rep->SetCurrentOperationToInactive(); self->EventCallbackCommand->SetAbortFlag(1); self->EndInteraction(); if ( self->WidgetRep->GetNeedToRender() ) { self->Render(); self->WidgetRep->NeedToRenderOff(); } } // These are callbacks that are active when the user is manipulating the // handles of the measure widget. //---------------------------------------------------------------------- void vtkContourWidget::StartInteraction() { this->Superclass::StartInteraction(); this->InvokeEvent(vtkCommand::StartInteractionEvent,NULL); } //---------------------------------------------------------------------- void vtkContourWidget::Interaction() { this->InvokeEvent(vtkCommand::InteractionEvent,NULL); } //---------------------------------------------------------------------- void vtkContourWidget::EndInteraction() { this->Superclass::EndInteraction(); this->InvokeEvent(vtkCommand::EndInteractionEvent,NULL); } //---------------------------------------------------------------------- void vtkContourWidget::PrintSelf(ostream& os, vtkIndent indent) { //Superclass typedef defined in vtkTypeMacro() found in vtkSetGet.h this->Superclass::PrintSelf(os,indent); } <commit_msg>BUG: Removed warnings<commit_after>/*========================================================================= Program: Visualization Toolkit Module: vtkContourWidget.cxx Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ #include "vtkContourWidget.h" #include "vtkOrientedGlyphContourRepresentation.h" #include "vtkCommand.h" #include "vtkCallbackCommand.h" #include "vtkRenderWindowInteractor.h" #include "vtkObjectFactory.h" #include "vtkRenderer.h" #include "vtkWidgetCallbackMapper.h" #include "vtkSphereSource.h" #include "vtkProperty.h" #include "vtkEvent.h" #include "vtkWidgetEvent.h" #include <vtkstd/vector> #include <vtkstd/set> #include <vtkstd/algorithm> #include <vtkstd/iterator> vtkCxxRevisionMacro(vtkContourWidget, "1.4"); vtkStandardNewMacro(vtkContourWidget); //---------------------------------------------------------------------- vtkContourWidget::vtkContourWidget() { this->ManagesCursor = 0; this->WidgetState = vtkContourWidget::Start; this->CurrentHandle = 0; // These are the event callbacks supported by this widget this->CallbackMapper->SetCallbackMethod(vtkCommand::LeftButtonPressEvent, vtkWidgetEvent::Select, this, vtkContourWidget::SelectAction); this->CallbackMapper->SetCallbackMethod(vtkCommand::RightButtonPressEvent, vtkWidgetEvent::AddFinalPoint, this, vtkContourWidget::AddFinalPointAction); this->CallbackMapper->SetCallbackMethod(vtkCommand::MouseMoveEvent, vtkWidgetEvent::Move, this, vtkContourWidget::MoveAction); this->CallbackMapper->SetCallbackMethod(vtkCommand::LeftButtonReleaseEvent, vtkWidgetEvent::EndSelect, this, vtkContourWidget::EndSelectAction); this->CallbackMapper->SetCallbackMethod(vtkCommand::KeyPressEvent, vtkEvent::NoModifier, 46, 1, NULL, vtkWidgetEvent::Delete, this, vtkContourWidget::DeleteAction); this->CreateDefaultRepresentation(); } //---------------------------------------------------------------------- vtkContourWidget::~vtkContourWidget() { } //---------------------------------------------------------------------- void vtkContourWidget::CreateDefaultRepresentation() { if ( ! this->WidgetRep ) { vtkOrientedGlyphContourRepresentation *rep = vtkOrientedGlyphContourRepresentation::New(); this->WidgetRep = rep; vtkSphereSource *ss = vtkSphereSource::New(); ss->SetRadius(0.5); rep->SetActiveCursorShape( ss->GetOutput() ); ss->Delete(); rep->GetProperty()->SetColor(.25,1.0,.25); rep->GetActiveProperty()->SetRepresentationToSurface(); rep->GetActiveProperty()->SetAmbient(0.1); rep->GetActiveProperty()->SetDiffuse(0.9); rep->GetActiveProperty()->SetSpecular(0.0); } } //---------------------------------------------------------------------- void vtkContourWidget::ClearContour() { } //---------------------------------------------------------------------- void vtkContourWidget::SetEnabled(int enabling) { // The handle widgets are not actually enabled until they are placed. // The handle widgets take their representation from the vtkContourRepresentation. if ( enabling ) { if ( this->WidgetState == vtkContourWidget::Start ) { reinterpret_cast<vtkContourRepresentation*>(this->WidgetRep)->VisibilityOff(); } else { reinterpret_cast<vtkContourRepresentation*>(this->WidgetRep)->VisibilityOn(); } } this->Superclass::SetEnabled(enabling); } // The following methods are the callbacks that the measure widget responds to. //------------------------------------------------------------------------- void vtkContourWidget::SelectAction(vtkAbstractWidget *w) { vtkContourWidget *self = reinterpret_cast<vtkContourWidget*>(w); vtkContourRepresentation *rep = reinterpret_cast<vtkContourRepresentation*>(self->WidgetRep); int X = self->Interactor->GetEventPosition()[0]; int Y = self->Interactor->GetEventPosition()[1]; double pos[2]; pos[0] = X; pos[1] = Y; switch ( self->WidgetState ) { case vtkContourWidget::Start: case vtkContourWidget::Define: self->AddNode(); break; case vtkContourWidget::Manipulate: if ( rep->ActivateNode(X,Y) ) { self->StartInteraction(); rep->SetCurrentOperationToTranslate(); rep->StartWidgetInteraction(pos); self->EventCallbackCommand->SetAbortFlag(1); } else if ( rep->AddNodeOnContour( X, Y ) ) { if ( rep->ActivateNode(X,Y) ) { rep->SetCurrentOperationToTranslate(); rep->StartWidgetInteraction(pos); } self->EventCallbackCommand->SetAbortFlag(1); } break; } if ( rep->GetNeedToRender() ) { self->Render(); rep->NeedToRenderOff(); } } //------------------------------------------------------------------------- void vtkContourWidget::AddFinalPointAction(vtkAbstractWidget *w) { vtkContourWidget *self = reinterpret_cast<vtkContourWidget*>(w); vtkContourRepresentation *rep = reinterpret_cast<vtkContourRepresentation*>(self->WidgetRep); if ( self->WidgetState == vtkContourWidget::Define && rep->GetNumberOfNodes() >= 1 ) { self->AddNode(); self->WidgetState = vtkContourWidget::Manipulate; self->EventCallbackCommand->SetAbortFlag(1); } if ( rep->GetNeedToRender() ) { self->Render(); rep->NeedToRenderOff(); } } //------------------------------------------------------------------------ void vtkContourWidget::AddNode() { int X = this->Interactor->GetEventPosition()[0]; int Y = this->Interactor->GetEventPosition()[1]; // If the rep already has at least 2 nodes, check how close we are to // the first if ( reinterpret_cast<vtkContourRepresentation*>(this->WidgetRep)-> GetNumberOfNodes() > 1 ) { int pixelTolerance2 = reinterpret_cast<vtkContourRepresentation*>(this->WidgetRep)-> GetPixelTolerance(); pixelTolerance2 *= pixelTolerance2; double displayPos[2]; if ( !reinterpret_cast<vtkContourRepresentation*>(this->WidgetRep)-> GetNthNodeDisplayPosition( 0, displayPos ) ) { vtkErrorMacro("Can't get first node display position!"); return; } if ( (X - displayPos[0]) * (X - displayPos[0]) + (Y - displayPos[1]) * (Y - displayPos[1]) < pixelTolerance2 ) { // yes - we have made a loop. Stop defining and switch to // manipulate mode this->WidgetState = vtkContourWidget::Manipulate; reinterpret_cast<vtkContourRepresentation*>(this->WidgetRep)->ClosedLoopOn(); this->EventCallbackCommand->SetAbortFlag(1); return; } } if ( reinterpret_cast<vtkContourRepresentation*>(this->WidgetRep)-> AddNodeAtDisplayPosition( X, Y ) ) { this->WidgetState = vtkContourWidget::Define; reinterpret_cast<vtkContourRepresentation*>(this->WidgetRep)->VisibilityOn(); this->EventCallbackCommand->SetAbortFlag(1); } } //------------------------------------------------------------------------- void vtkContourWidget::DeleteAction(vtkAbstractWidget *w) { vtkContourWidget *self = reinterpret_cast<vtkContourWidget*>(w); if ( self->WidgetState == vtkContourWidget::Start ) { return; } vtkContourRepresentation *rep = reinterpret_cast<vtkContourRepresentation*>(self->WidgetRep); if ( self->WidgetState == vtkContourWidget::Define ) { rep->DeleteLastNode(); } else { int X = self->Interactor->GetEventPosition()[0]; int Y = self->Interactor->GetEventPosition()[1]; rep->ActivateNode( X, Y ); rep->DeleteActiveNode(); rep->ActivateNode( X, Y ); if ( rep->GetNumberOfNodes() < 3 ) { rep->ClosedLoopOff(); self->WidgetState = vtkContourWidget::Define; } } if ( rep->GetNeedToRender() ) { self->Render(); rep->NeedToRenderOff(); } } //------------------------------------------------------------------------- void vtkContourWidget::MoveAction(vtkAbstractWidget *w) { vtkContourWidget *self = reinterpret_cast<vtkContourWidget*>(w); if ( self->WidgetState == vtkContourWidget::Start || self->WidgetState == vtkContourWidget::Define ) { return; } int X = self->Interactor->GetEventPosition()[0]; int Y = self->Interactor->GetEventPosition()[1]; vtkContourRepresentation *rep = reinterpret_cast<vtkContourRepresentation*>(self->WidgetRep); if ( rep->GetCurrentOperation() == vtkContourRepresentation::Inactive ) { reinterpret_cast<vtkContourRepresentation*>(self->WidgetRep)-> ComputeInteractionState( X, Y ); reinterpret_cast<vtkContourRepresentation*>(self->WidgetRep)-> ActivateNode( X, Y ); } else { double pos[2]; pos[0] = X; pos[1] = Y; self->WidgetRep->WidgetInteraction(pos); } self->Interaction(); if ( self->WidgetRep->GetNeedToRender() ) { self->Render(); self->WidgetRep->NeedToRenderOff(); } } //------------------------------------------------------------------------- void vtkContourWidget::EndSelectAction(vtkAbstractWidget *w) { vtkContourWidget *self = reinterpret_cast<vtkContourWidget*>(w); vtkContourRepresentation *rep = reinterpret_cast<vtkContourRepresentation*>(self->WidgetRep); // Do nothing if inactive if ( rep->GetCurrentOperation() == vtkContourRepresentation::Inactive ) { return; } rep->SetCurrentOperationToInactive(); self->EventCallbackCommand->SetAbortFlag(1); self->EndInteraction(); if ( self->WidgetRep->GetNeedToRender() ) { self->Render(); self->WidgetRep->NeedToRenderOff(); } } // These are callbacks that are active when the user is manipulating the // handles of the measure widget. //---------------------------------------------------------------------- void vtkContourWidget::StartInteraction() { this->Superclass::StartInteraction(); this->InvokeEvent(vtkCommand::StartInteractionEvent,NULL); } //---------------------------------------------------------------------- void vtkContourWidget::Interaction() { this->InvokeEvent(vtkCommand::InteractionEvent,NULL); } //---------------------------------------------------------------------- void vtkContourWidget::EndInteraction() { this->Superclass::EndInteraction(); this->InvokeEvent(vtkCommand::EndInteractionEvent,NULL); } //---------------------------------------------------------------------- void vtkContourWidget::PrintSelf(ostream& os, vtkIndent indent) { //Superclass typedef defined in vtkTypeMacro() found in vtkSetGet.h this->Superclass::PrintSelf(os,indent); } <|endoftext|>
<commit_before>// This file is part of the dune-stuff project: // https://github.com/wwu-numerik/dune-stuff/ // Copyright holders: Rene Milk, Felix Schindler // License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause) #ifndef DUNE_STUFF_PLAYGROUND_FUNCTIONS_ESV2007_HH #define DUNE_STUFF_PLAYGROUND_FUNCTIONS_ESV2007_HH #include <limits> #include <boost/numeric/conversion/cast.hpp> #if HAVE_EIGEN # include <Eigen/Eigenvalues> # include <dune/geometry/quadraturerules.hh> # include <dune/stuff/functions/ESV2007.hh> # include <dune/stuff/common/debug.hh> # include <dune/stuff/common/ranges.hh> namespace Dune { namespace Stuff { namespace Functions { namespace ESV2007 { template< class DiffusionFactorType, class DiffusionTensorType > class Cutoff : public LocalizableFunctionInterface< typename DiffusionFactorType::EntityType , typename DiffusionFactorType::DomainFieldType, DiffusionFactorType::dimDomain , typename DiffusionFactorType::RangeFieldType, 1, 1 > { static_assert(std::is_base_of< Tags::LocalizableFunction, DiffusionFactorType >::value, "DiffusionFactorType has to be tagged as a LocalizableFunction!"); static_assert(std::is_base_of< Tags::LocalizableFunction, DiffusionTensorType >::value, "DiffusionTensorType has to be tagged as a LocalizableFunction!"); typedef typename DiffusionFactorType::EntityType E_; typedef typename DiffusionFactorType::DomainFieldType D_; static const unsigned int d_ = DiffusionFactorType::dimDomain; typedef typename DiffusionFactorType::RangeFieldType R_; typedef LocalizableFunctionInterface< E_, D_, d_, R_, 1 > BaseType; typedef Cutoff< DiffusionFactorType, DiffusionTensorType > ThisType; static_assert(DiffusionFactorType::dimRange == 1, "The diffusion factor has to be scalar!"); static_assert(DiffusionFactorType::dimRangeCols == 1, "The diffusion factor has to be scalar!"); static_assert(std::is_same< typename DiffusionTensorType::EntityType, E_ >::value, "Types do not match!"); static_assert(std::is_same< typename DiffusionTensorType::DomainFieldType, D_ >::value, "Types do not match!"); static_assert(DiffusionTensorType::dimDomain == d_, "Dimensions do not match!"); static_assert(std::is_same< typename DiffusionTensorType::RangeFieldType, R_ >::value, "Types do not match!"); static_assert(DiffusionTensorType::dimRange == d_, "The diffusion tensor has to be a matrix!"); static_assert(DiffusionTensorType::dimRangeCols == d_, "The diffusion tensor has to be a matrix!"); class Localfunction : public LocalfunctionInterface< E_, D_, d_, R_, 1, 1 > { typedef LocalfunctionInterface< E_, D_, d_, R_, 1, 1 > BaseType; public: typedef typename BaseType::EntityType EntityType; typedef typename BaseType::DomainFieldType DomainFieldType; static const unsigned int dimDomain = BaseType::dimDomain; typedef typename BaseType::DomainType DomainType; typedef typename BaseType::RangeFieldType RangeFieldType; static const unsigned int dimRange = BaseType::dimRange; static const unsigned int dimRangeCols = BaseType::dimRangeCols; typedef typename BaseType::RangeType RangeType; typedef typename BaseType::JacobianRangeType JacobianRangeType; private: template< class DF, int r, int rR > struct ComputeDiffusionFactor { static_assert(AlwaysFalse< DF >::value, "Not implemented for these dimensions!"); }; template< class DF > struct ComputeDiffusionFactor< DF, 1, 1 > { /** * We try to find the minimum of a polynomial of given order by evaluating it at the points of a quadrature that * would integrate this polynomial exactly. * \todo These are just some heuristics and should be replaced by something proper. */ static RangeFieldType min_of(const DF& diffusion_factor, const EntityType& ent) { typename DF::RangeType tmp_value(0); RangeFieldType minimum = std::numeric_limits< RangeFieldType >::max(); const auto local_diffusion_factor = diffusion_factor.local_function(ent); const size_t ord = local_diffusion_factor->order(); assert(ord < std::numeric_limits< int >::max()); const auto& quadrature = QuadratureRules< DomainFieldType, dimDomain >::rule(ent.type(), int(ord)); const auto quad_point_it_end = quadrature.end(); for (auto quad_point_it = quadrature.begin(); quad_point_it != quad_point_it_end; ++quad_point_it) { local_diffusion_factor->evaluate(quad_point_it->position(), tmp_value); minimum = std::min(minimum, tmp_value[0]); } return minimum; } // ... min_of(...) }; // class ComputeDiffusionFactor< ..., 1, 1 > template< class DT, int r, int rR > struct ComputeDiffusionTensor { static_assert(AlwaysFalse< DT >::value, "Not implemented for these dimensions!"); }; template< class DT, int d > struct ComputeDiffusionTensor< DT, d, d > { static RangeFieldType min_eigenvalue_of(const DT& diffusion_tensor, const EntityType& ent) { #if !HAVE_EIGEN static_assert(AlwaysFalse< DT >::value, "You are missing eigen!"); #endif const auto local_diffusion_tensor = diffusion_tensor.local_function(ent); assert(local_diffusion_tensor->order() == 0); const auto& reference_element = ReferenceElements< DomainFieldType, dimDomain >::general(ent.type()); const Stuff::LA::EigenDenseMatrix< RangeFieldType > tensor = local_diffusion_tensor->evaluate(reference_element.position(0, 0)); ::Eigen::EigenSolver< typename Stuff::LA::EigenDenseMatrix< RangeFieldType >::BackendType > eigen_solver(tensor.backend()); assert(eigen_solver.info() == ::Eigen::Success); const auto eigenvalues = eigen_solver.eigenvalues(); // <- this should be an Eigen vector of std::complex RangeFieldType min_ev = std::numeric_limits< RangeFieldType >::max(); for (size_t ii = 0; ii < boost::numeric_cast< size_t >(eigenvalues.size()); ++ii) { // assert this is real assert(std::abs(eigenvalues[ii].imag()) < 1e-15); // assert that this eigenvalue is positive const RangeFieldType eigenvalue = eigenvalues[ii].real(); assert(eigenvalue > 1e-15); min_ev = std::min(min_ev, eigenvalue); } return min_ev; } // ... min_eigenvalue_of_(...) }; // class Compute< ..., d, d > public: Localfunction(const EntityType& ent, const DiffusionFactorType& diffusion_factor, const DiffusionTensorType& diffusion_tensor, const RangeFieldType poincare_constant) : BaseType(ent) , value_(0) { const RangeFieldType min_diffusion_factor = ComputeDiffusionFactor< DiffusionFactorType, DiffusionFactorType::dimRange, DiffusionFactorType::dimRangeCols >::min_of(diffusion_factor, ent); const RangeFieldType min_eigen_value_diffusion_tensor = ComputeDiffusionTensor< DiffusionTensorType, DiffusionTensorType::dimRange, DiffusionTensorType::dimRangeCols >::min_eigenvalue_of(diffusion_tensor, ent); assert(min_diffusion_factor > RangeFieldType(0)); assert(min_eigen_value_diffusion_tensor > RangeFieldType(0)); const DomainFieldType hh = compute_diameter_of_(ent); value_ = (poincare_constant * hh * hh) / (min_diffusion_factor * min_eigen_value_diffusion_tensor); } // Localfunction(...) Localfunction(const Localfunction& /*other*/) = delete; Localfunction& operator=(const Localfunction& /*other*/) = delete; virtual size_t order() const override final { return 0; } virtual void evaluate(const DomainType& UNUSED_UNLESS_DEBUG(xx), RangeType& ret) const override final { assert(this->is_a_valid_point(xx)); ret[0] = value_; } virtual void jacobian(const DomainType& UNUSED_UNLESS_DEBUG(xx), JacobianRangeType& ret) const override final { assert(this->is_a_valid_point(xx)); ret *= RangeFieldType(0); } private: static DomainFieldType compute_diameter_of_(const EntityType& ent) { DomainFieldType ret(0); for (auto cc : DSC::valueRange(ent.template count< dimDomain >())) { const auto vertex = ent.template subEntity< dimDomain >(cc)->geometry().center(); for (auto dd : DSC::valueRange(cc + 1, ent.template count< dimDomain >())) { const auto other_vertex = ent.template subEntity< dimDomain >(dd)->geometry().center(); const auto diff = vertex - other_vertex; ret = std::max(ret, diff.two_norm()); } } return ret; } // ... compute_diameter_of_(...) RangeFieldType value_; }; // class Localfunction public: typedef typename BaseType::EntityType EntityType; typedef typename BaseType::LocalfunctionType LocalfunctionType; typedef typename BaseType::DomainFieldType DomainFieldType; static const unsigned int dimDomain = BaseType::dimDomain; typedef typename BaseType::DomainType DomainType; typedef typename BaseType::RangeFieldType RangeFieldType; static const unsigned int dimRange = BaseType::dimRange; static const unsigned int dimRangeCols = BaseType::dimRangeCols; typedef typename BaseType::RangeType RangeType; static std::string static_id() { return BaseType::static_id() + ".ESV2007.cutoff"; } Cutoff(const DiffusionFactorType& diffusion_factor, const DiffusionTensorType& diffusion_tensor, const RangeFieldType poincare_constant = 1.0 / (M_PIl * M_PIl), const std::string nm = static_id()) : diffusion_factor_(diffusion_factor) , diffusion_tensor_(diffusion_tensor) , poincare_constant_(poincare_constant) , name_(nm) {} Cutoff(const ThisType& other) = default; ThisType& operator=(const ThisType& other) = delete; virtual ThisType* copy() const override final { return new ThisType(*this); } virtual std::string name() const override final { return name_; } virtual std::unique_ptr< LocalfunctionType > local_function(const EntityType& entity) const override final { return std::unique_ptr< Localfunction >(new Localfunction(entity, diffusion_factor_, diffusion_tensor_, poincare_constant_)); } private: const DiffusionFactorType& diffusion_factor_; const DiffusionTensorType& diffusion_tensor_; const RangeFieldType poincare_constant_; std::string name_; }; // class Cutoff } // namespace ESV2007 } // namespace Functions } // namespace Stuff } // namespace Dune #endif // HAVE_EIGEN #endif // DUNE_STUFF_PLAYGROUND_FUNCTIONS_ESV2007_HH <commit_msg>[functions.ESV2007] refs #10<commit_after>// This file is part of the dune-stuff project: // https://github.com/wwu-numerik/dune-stuff/ // Copyright holders: Rene Milk, Felix Schindler // License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause) #ifndef DUNE_STUFF_PLAYGROUND_FUNCTIONS_ESV2007_HH #define DUNE_STUFF_PLAYGROUND_FUNCTIONS_ESV2007_HH #include <limits> #include <boost/numeric/conversion/cast.hpp> #if HAVE_EIGEN # include <Eigen/Eigenvalues> # include <dune/geometry/quadraturerules.hh> # include <dune/stuff/functions/ESV2007.hh> # include <dune/stuff/common/debug.hh> # include <dune/stuff/common/ranges.hh> namespace Dune { namespace Stuff { namespace Functions { namespace ESV2007 { template< class DiffusionFactorType, class DiffusionTensorType > class Cutoff : public LocalizableFunctionInterface< typename DiffusionFactorType::EntityType , typename DiffusionFactorType::DomainFieldType, DiffusionFactorType::dimDomain , typename DiffusionFactorType::RangeFieldType, 1, 1 > { static_assert(std::is_base_of< Tags::LocalizableFunction, DiffusionFactorType >::value, "DiffusionFactorType has to be tagged as a LocalizableFunction!"); static_assert(std::is_base_of< Tags::LocalizableFunction, DiffusionTensorType >::value, "DiffusionTensorType has to be tagged as a LocalizableFunction!"); typedef typename DiffusionFactorType::EntityType E_; typedef typename DiffusionFactorType::DomainFieldType D_; static const unsigned int d_ = DiffusionFactorType::dimDomain; typedef typename DiffusionFactorType::RangeFieldType R_; typedef LocalizableFunctionInterface< E_, D_, d_, R_, 1 > BaseType; typedef Cutoff< DiffusionFactorType, DiffusionTensorType > ThisType; static_assert(DiffusionFactorType::dimRange == 1, "The diffusion factor has to be scalar!"); static_assert(DiffusionFactorType::dimRangeCols == 1, "The diffusion factor has to be scalar!"); static_assert(std::is_same< typename DiffusionTensorType::EntityType, E_ >::value, "Types do not match!"); static_assert(std::is_same< typename DiffusionTensorType::DomainFieldType, D_ >::value, "Types do not match!"); static_assert(DiffusionTensorType::dimDomain == d_, "Dimensions do not match!"); static_assert(std::is_same< typename DiffusionTensorType::RangeFieldType, R_ >::value, "Types do not match!"); static_assert(DiffusionTensorType::dimRange == d_, "The diffusion tensor has to be a matrix!"); static_assert(DiffusionTensorType::dimRangeCols == d_, "The diffusion tensor has to be a matrix!"); class Localfunction : public LocalfunctionInterface< E_, D_, d_, R_, 1, 1 > { typedef LocalfunctionInterface< E_, D_, d_, R_, 1, 1 > BaseType; public: typedef typename BaseType::EntityType EntityType; typedef typename BaseType::DomainFieldType DomainFieldType; static const unsigned int dimDomain = BaseType::dimDomain; typedef typename BaseType::DomainType DomainType; typedef typename BaseType::RangeFieldType RangeFieldType; static const unsigned int dimRange = BaseType::dimRange; static const unsigned int dimRangeCols = BaseType::dimRangeCols; typedef typename BaseType::RangeType RangeType; typedef typename BaseType::JacobianRangeType JacobianRangeType; private: template< class DF, int r, int rR > struct ComputeDiffusionFactor { static_assert(AlwaysFalse< DF >::value, "Not implemented for these dimensions!"); }; template< class DF > struct ComputeDiffusionFactor< DF, 1, 1 > { /** * We try to find the minimum of a polynomial of given order by evaluating it at the points of a quadrature that * would integrate this polynomial exactly. * \todo These are just some heuristics and should be replaced by something proper. */ static RangeFieldType min_of(const DF& diffusion_factor, const EntityType& ent) { typename DF::RangeType tmp_value(0); RangeFieldType minimum = std::numeric_limits< RangeFieldType >::max(); const auto local_diffusion_factor = diffusion_factor.local_function(ent); const size_t ord = local_diffusion_factor->order(); const auto& quadrature = QuadratureRules< DomainFieldType, dimDomain >::rule(ent.type(), boost::numeric_cast< int >(ord)); const auto quad_point_it_end = quadrature.end(); for (auto quad_point_it = quadrature.begin(); quad_point_it != quad_point_it_end; ++quad_point_it) { local_diffusion_factor->evaluate(quad_point_it->position(), tmp_value); minimum = std::min(minimum, tmp_value[0]); } return minimum; } // ... min_of(...) }; // class ComputeDiffusionFactor< ..., 1, 1 > template< class DT, int r, int rR > struct ComputeDiffusionTensor { static_assert(AlwaysFalse< DT >::value, "Not implemented for these dimensions!"); }; template< class DT, int d > struct ComputeDiffusionTensor< DT, d, d > { static RangeFieldType min_eigenvalue_of(const DT& diffusion_tensor, const EntityType& ent) { #if !HAVE_EIGEN static_assert(AlwaysFalse< DT >::value, "You are missing eigen!"); #endif const auto local_diffusion_tensor = diffusion_tensor.local_function(ent); assert(local_diffusion_tensor->order() == 0); const auto& reference_element = ReferenceElements< DomainFieldType, dimDomain >::general(ent.type()); const Stuff::LA::EigenDenseMatrix< RangeFieldType > tensor = local_diffusion_tensor->evaluate(reference_element.position(0, 0)); ::Eigen::EigenSolver< typename Stuff::LA::EigenDenseMatrix< RangeFieldType >::BackendType > eigen_solver(tensor.backend()); assert(eigen_solver.info() == ::Eigen::Success); const auto eigenvalues = eigen_solver.eigenvalues(); // <- this should be an Eigen vector of std::complex RangeFieldType min_ev = std::numeric_limits< RangeFieldType >::max(); for (size_t ii = 0; ii < boost::numeric_cast< size_t >(eigenvalues.size()); ++ii) { // assert this is real assert(std::abs(eigenvalues[ii].imag()) < 1e-15); // assert that this eigenvalue is positive const RangeFieldType eigenvalue = eigenvalues[ii].real(); assert(eigenvalue > 1e-15); min_ev = std::min(min_ev, eigenvalue); } return min_ev; } // ... min_eigenvalue_of_(...) }; // class Compute< ..., d, d > public: Localfunction(const EntityType& ent, const DiffusionFactorType& diffusion_factor, const DiffusionTensorType& diffusion_tensor, const RangeFieldType poincare_constant) : BaseType(ent) , value_(0) { const RangeFieldType min_diffusion_factor = ComputeDiffusionFactor< DiffusionFactorType, DiffusionFactorType::dimRange, DiffusionFactorType::dimRangeCols >::min_of(diffusion_factor, ent); const RangeFieldType min_eigen_value_diffusion_tensor = ComputeDiffusionTensor< DiffusionTensorType, DiffusionTensorType::dimRange, DiffusionTensorType::dimRangeCols >::min_eigenvalue_of(diffusion_tensor, ent); assert(min_diffusion_factor > RangeFieldType(0)); assert(min_eigen_value_diffusion_tensor > RangeFieldType(0)); const DomainFieldType hh = compute_diameter_of_(ent); value_ = (poincare_constant * hh * hh) / (min_diffusion_factor * min_eigen_value_diffusion_tensor); } // Localfunction(...) Localfunction(const Localfunction& /*other*/) = delete; Localfunction& operator=(const Localfunction& /*other*/) = delete; virtual size_t order() const override final { return 0; } virtual void evaluate(const DomainType& UNUSED_UNLESS_DEBUG(xx), RangeType& ret) const override final { assert(this->is_a_valid_point(xx)); ret[0] = value_; } virtual void jacobian(const DomainType& UNUSED_UNLESS_DEBUG(xx), JacobianRangeType& ret) const override final { assert(this->is_a_valid_point(xx)); ret *= RangeFieldType(0); } private: static DomainFieldType compute_diameter_of_(const EntityType& ent) { DomainFieldType ret(0); for (auto cc : DSC::valueRange(ent.template count< dimDomain >())) { const auto vertex = ent.template subEntity< dimDomain >(cc)->geometry().center(); for (auto dd : DSC::valueRange(cc + 1, ent.template count< dimDomain >())) { const auto other_vertex = ent.template subEntity< dimDomain >(dd)->geometry().center(); const auto diff = vertex - other_vertex; ret = std::max(ret, diff.two_norm()); } } return ret; } // ... compute_diameter_of_(...) RangeFieldType value_; }; // class Localfunction public: typedef typename BaseType::EntityType EntityType; typedef typename BaseType::LocalfunctionType LocalfunctionType; typedef typename BaseType::DomainFieldType DomainFieldType; static const unsigned int dimDomain = BaseType::dimDomain; typedef typename BaseType::DomainType DomainType; typedef typename BaseType::RangeFieldType RangeFieldType; static const unsigned int dimRange = BaseType::dimRange; static const unsigned int dimRangeCols = BaseType::dimRangeCols; typedef typename BaseType::RangeType RangeType; static std::string static_id() { return BaseType::static_id() + ".ESV2007.cutoff"; } Cutoff(const DiffusionFactorType& diffusion_factor, const DiffusionTensorType& diffusion_tensor, const RangeFieldType poincare_constant = 1.0 / (M_PIl * M_PIl), const std::string nm = static_id()) : diffusion_factor_(diffusion_factor) , diffusion_tensor_(diffusion_tensor) , poincare_constant_(poincare_constant) , name_(nm) {} Cutoff(const ThisType& other) = default; ThisType& operator=(const ThisType& other) = delete; virtual ThisType* copy() const override final { return new ThisType(*this); } virtual std::string name() const override final { return name_; } virtual std::unique_ptr< LocalfunctionType > local_function(const EntityType& entity) const override final { return std::unique_ptr< Localfunction >(new Localfunction(entity, diffusion_factor_, diffusion_tensor_, poincare_constant_)); } private: const DiffusionFactorType& diffusion_factor_; const DiffusionTensorType& diffusion_tensor_; const RangeFieldType poincare_constant_; std::string name_; }; // class Cutoff } // namespace ESV2007 } // namespace Functions } // namespace Stuff } // namespace Dune #endif // HAVE_EIGEN #endif // DUNE_STUFF_PLAYGROUND_FUNCTIONS_ESV2007_HH <|endoftext|>
<commit_before>// // XLCObjCppHelpers.hh // XLCUtils // // Created by Xiliang Chen on 14-4-27. // Copyright (c) 2014年 Xiliang Chen. All rights reserved. // #ifndef XLCUtils_XLCObjCppHelpers_hh #define XLCUtils_XLCObjCppHelpers_hh #include <type_traits> #include <ostream> #include <utility> #include <string> #include <typeinfo> #include <cxxabi.h> #ifndef __has_builtin // Optional of course. #define __has_builtin(x) 0 // Compatibility with non-clang compilers. #endif #ifndef __has_feature // Optional of course. #define __has_feature(x) 0 // Compatibility with non-clang compilers. #endif #ifndef __has_extension #define __has_extension __has_feature // Compatibility with pre-3.0 compilers. #endif namespace xlc { template <bool T, class U = void> using enable_if_t = typename std::enable_if<T, U>::type; // callable_traits namespace detail { template <class ReturnType, class... Args> struct callable_traits_base { using return_type = ReturnType; using argument_type = std::tuple<Args...>; template<std::size_t I> using arg = typename std::tuple_element<I, argument_type>::type; }; } template <class T> struct callable_traits : callable_traits<decltype(&T::operator())> {}; // lambda / functor template <class ClassType, class ReturnType, class... Args> struct callable_traits<ReturnType(ClassType::*)(Args...) const> : detail::callable_traits_base<ReturnType, Args...> {}; // function pointer template <class ReturnType, class... Args> struct callable_traits<ReturnType(Args...)> : detail::callable_traits_base<ReturnType, Args...> {}; template <class ReturnType, class... Args> struct callable_traits<ReturnType(*)(Args...)> : detail::callable_traits_base<ReturnType, Args...> {}; #if __has_extension(blocks) // block template <class ReturnType, class... Args> struct callable_traits<ReturnType(^)(Args...)> : detail::callable_traits_base<ReturnType, Args...> {}; #endif // is_pair template <class T> struct is_pair : std::false_type {}; template <class T1, class T2> struct is_pair<std::pair<T1, T2>> : std::true_type {}; // is_for_loopable namespace detail { namespace is_for_loopable { using std::begin; // enable ADL template<class T, class V = void> struct is_for_loopable : std::false_type { }; template<class T> struct is_for_loopable<T, typename xlc::enable_if_t<!std::is_void<decltype(begin(std::declval<T>()))>::value> > : std::true_type { }; template<class T, std::size_t N> struct is_for_loopable<T[N]> : std::true_type { }; } } using detail::is_for_loopable::is_for_loopable; // is_objc_class template<class T, class V = void> struct is_objc_class : std::false_type { }; #ifdef __OBJC__ template<class T> struct is_objc_class<T, typename std::enable_if<std::is_convertible<T, id>::value>::type > : std::true_type { }; #endif // type_description template <class T> std::string type_description() { bool is_lvalue_reference = std::is_lvalue_reference<T>::value; bool is_rvalue_reference = std::is_rvalue_reference<T>::value; bool is_const = std::is_const<typename std::remove_reference<T>::type>::value; std::unique_ptr<char, void(*)(void*)> name {abi::__cxa_demangle(typeid(T).name(), nullptr, nullptr, nullptr), std::free}; auto str = std::string(name.get()); if (is_const) { str += " const"; } if (is_lvalue_reference) { str += "&"; } if (is_rvalue_reference) { str += "&&"; } return str; }; } #ifdef __OBJC__ template < class T, class = typename xlc::enable_if_t<xlc::is_objc_class<T>::value> > std::ostream& operator<< (std::ostream& stream, T const & t) { stream << [[t description] UTF8String]; return stream; } #endif #endif <commit_msg>some minor fixes<commit_after>// // XLCObjCppHelpers.hh // XLCUtils // // Created by Xiliang Chen on 14-4-27. // Copyright (c) 2014年 Xiliang Chen. All rights reserved. // #ifndef XLCUtils_XLCObjCppHelpers_hh #define XLCUtils_XLCObjCppHelpers_hh #include <type_traits> #include <ostream> #include <utility> #include <string> #include <typeinfo> #include <memory> #include <cxxabi.h> #ifndef __has_builtin // Optional of course. #define __has_builtin(x) 0 // Compatibility with non-clang compilers. #endif #ifndef __has_feature // Optional of course. #define __has_feature(x) 0 // Compatibility with non-clang compilers. #endif #ifndef __has_extension #define __has_extension __has_feature // Compatibility with pre-3.0 compilers. #endif namespace xlc { template <bool T, class U = void> using enable_if_t = typename std::enable_if<T, U>::type; // callable_traits namespace detail { template <class ReturnType, class... Args> struct callable_traits_base { using return_type = ReturnType; using argument_type = std::tuple<Args...>; template<std::size_t I> using arg = typename std::tuple_element<I, argument_type>::type; }; } template <class T> struct callable_traits : callable_traits<decltype(&T::operator())> {}; // lambda / functor template <class ClassType, class ReturnType, class... Args> struct callable_traits<ReturnType(ClassType::*)(Args...) const> : detail::callable_traits_base<ReturnType, Args...> {}; // function pointer template <class ReturnType, class... Args> struct callable_traits<ReturnType(Args...)> : detail::callable_traits_base<ReturnType, Args...> {}; template <class ReturnType, class... Args> struct callable_traits<ReturnType(*)(Args...)> : detail::callable_traits_base<ReturnType, Args...> {}; #if __has_extension(blocks) // block template <class ReturnType, class... Args> struct callable_traits<ReturnType(^)(Args...)> : detail::callable_traits_base<ReturnType, Args...> {}; #endif // is_pair template <class T> struct is_pair : std::false_type {}; template <class T1, class T2> struct is_pair<std::pair<T1, T2>> : std::true_type {}; // is_for_loopable namespace detail { namespace is_for_loopable { using std::begin; // enable ADL template<class T, class V = void> struct is_for_loopable : std::false_type { }; template<class T> struct is_for_loopable<T, typename xlc::enable_if_t<!std::is_void<decltype(begin(std::declval<T>()))>::value> > : std::true_type { }; template<class T, std::size_t N> struct is_for_loopable<T[N]> : std::true_type { }; } } using detail::is_for_loopable::is_for_loopable; // is_objc_class template<class T, class V = void> struct is_objc_class : std::false_type { }; #ifdef __OBJC__ template<class T> struct is_objc_class<T, typename std::enable_if<std::is_convertible<T, id>::value>::type > : std::true_type { }; #endif // type_description template <class T> std::string type_description() { bool is_lvalue_reference = std::is_lvalue_reference<T>::value; bool is_rvalue_reference = std::is_rvalue_reference<T>::value; bool is_const = std::is_const<typename std::remove_reference<T>::type>::value; std::unique_ptr<char, void(*)(void*)> name {abi::__cxa_demangle(typeid(T).name(), nullptr, nullptr, nullptr), std::free}; auto str = std::string(name.get()); if (is_const) { str += " const"; } if (is_lvalue_reference) { str += "&"; } if (is_rvalue_reference) { str += "&&"; } return str; } } #ifdef __OBJC__ template < class T, class = typename xlc::enable_if_t<xlc::is_objc_class<T>::value> > std::ostream& operator<< (std::ostream& stream, T const & t) { stream << [[t description] UTF8String]; return stream; } #endif #endif <|endoftext|>
<commit_before>/** * The Seeks proxy and plugin framework are part of the SEEKS project. * Copyright (C) 2010 Emmanuel Benazera, [email protected] * * 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/>. */ #include "se_parser_yahoo_img.h" #include "img_search_snippet.h" #include "img_websearch_configuration.h" #include "miscutil.h" #include "encode.h" #include <iostream> using sp::miscutil; using sp::encode; namespace seeks_plugins { se_parser_yahoo_img::se_parser_yahoo_img() :se_parser(),_results_flag(false),_cite_flag(false) { } se_parser_yahoo_img::~se_parser_yahoo_img() { } void se_parser_yahoo_img::start_element(parser_context *pc, const xmlChar *name, const xmlChar **attributes) { const char *tag = (const char*)name; if (!_results_flag && strcasecmp(tag,"ul") == 0) { const char *a_id = se_parser::get_attribute((const char**)attributes,"id"); if (a_id && strcasecmp(a_id,"yschimg") == 0) { _results_flag = true; } } else if (_results_flag && strcasecmp(tag,"li") == 0) { // assert previous snippet if any. if (pc->_current_snippet) { if (0/* pc->_current_snippet->_title.empty() // consider the parsing did fail on the snippet. || pc->_current_snippet->_url.empty() || pc->_current_snippet->_cached.empty() */) { delete pc->_current_snippet; pc->_current_snippet = NULL; _count--; } else pc->_snippets->push_back(pc->_current_snippet); } img_search_snippet *sp = new img_search_snippet(_count+1); _count++; sp->_img_engine |= std::bitset<IMG_NSEs>(SE_YAHOO_IMG); pc->_current_snippet = sp; } else if (_results_flag && strcasecmp(tag,"a") == 0) { const char *a_href = se_parser::get_attribute((const char**)attributes,"href"); if (a_href) { std::string furl = a_href; size_t pos = furl.find("imgurl="); if (pos != std::string::npos && pos+7 < furl.size()) { std::string imgurl = furl.substr(pos+7); pos = imgurl.find("%26"); if (pos != std::string::npos) { imgurl = imgurl.substr(0,pos); imgurl = "http://" + imgurl; char *imgurl_str = encode::url_decode(imgurl.c_str()); pc->_current_snippet->set_url(imgurl_str); free(imgurl_str); } } } } else if (_results_flag && strcasecmp(tag,"img") == 0) { const char *a_src = se_parser::get_attribute((const char**)attributes,"src"); if (a_src) { pc->_current_snippet->_cached = a_src; } } else if (_results_flag && strcasecmp(tag,"cite") == 0) { _cite_flag = true; } } void se_parser_yahoo_img::characters(parser_context *pc, const xmlChar *chars, int length) { handle_characters(pc, chars, length); } void se_parser_yahoo_img::cdata(parser_context *pc, const xmlChar *chars, int length) { //handle_characters(pc, chars, length); } void se_parser_yahoo_img::handle_characters(parser_context *pc, const xmlChar *chars, int length) { if (_cite_flag) { std::string cite = std::string((char*)chars,length); _title += cite; } } void se_parser_yahoo_img::end_element(parser_context *pc, const xmlChar *name) { const char *tag = (const char*)name; if (!_results_flag) return; if (_results_flag && strcasecmp(tag,"ul") == 0) _results_flag = false; if (_results_flag && strcasecmp(tag,"cite") == 0) { _cite_flag = false; pc->_current_snippet->_title = _title; _title.clear(); } } } /* end of namespace. */ <commit_msg>fix to yahoo parser<commit_after>/** * The Seeks proxy and plugin framework are part of the SEEKS project. * Copyright (C) 2010 Emmanuel Benazera, [email protected] * * 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/>. */ #include "se_parser_yahoo_img.h" #include "img_search_snippet.h" #include "img_websearch_configuration.h" #include "miscutil.h" #include "encode.h" #include <iostream> using sp::miscutil; using sp::encode; namespace seeks_plugins { se_parser_yahoo_img::se_parser_yahoo_img() :se_parser(),_results_flag(false),_cite_flag(false) { } se_parser_yahoo_img::~se_parser_yahoo_img() { } void se_parser_yahoo_img::start_element(parser_context *pc, const xmlChar *name, const xmlChar **attributes) { const char *tag = (const char*)name; if (!_results_flag && strcasecmp(tag,"ul") == 0) { const char *a_id = se_parser::get_attribute((const char**)attributes,"id"); if (a_id && strcasecmp(a_id,"yschimg") == 0) { _results_flag = true; } } else if (_results_flag && strcasecmp(tag,"li") == 0) { // assert previous snippet if any. if (pc->_current_snippet) { if (0/* pc->_current_snippet->_title.empty() // consider the parsing did fail on the snippet. || pc->_current_snippet->_url.empty() || pc->_current_snippet->_cached.empty() */) { delete pc->_current_snippet; pc->_current_snippet = NULL; _count--; } else pc->_snippets->push_back(pc->_current_snippet); } img_search_snippet *sp = new img_search_snippet(_count+1); _count++; sp->_img_engine |= std::bitset<IMG_NSEs>(SE_YAHOO_IMG); pc->_current_snippet = sp; } else if (_results_flag && strcasecmp(tag,"a") == 0) { const char *a_href = se_parser::get_attribute((const char**)attributes,"href"); if (a_href) { std::string furl = a_href; size_t pos = furl.find("imgurl="); if (pos != std::string::npos && pos+7 < furl.size()) { std::string imgurl = furl.substr(pos+7); char *imgurl_str = encode::url_decode(imgurl.c_str()); imgurl = imgurl_str; free(imgurl_str); pos = imgurl.find("&"); if (pos != std::string::npos) { imgurl = imgurl.substr(0,pos); imgurl = "http://" + imgurl; pc->_current_snippet->set_url(imgurl); } } } } else if (_results_flag && strcasecmp(tag,"img") == 0) { const char *a_src = se_parser::get_attribute((const char**)attributes,"src"); if (a_src) { pc->_current_snippet->_cached = a_src; } } else if (_results_flag && strcasecmp(tag,"cite") == 0) { _cite_flag = true; } } void se_parser_yahoo_img::characters(parser_context *pc, const xmlChar *chars, int length) { handle_characters(pc, chars, length); } void se_parser_yahoo_img::cdata(parser_context *pc, const xmlChar *chars, int length) { //handle_characters(pc, chars, length); } void se_parser_yahoo_img::handle_characters(parser_context *pc, const xmlChar *chars, int length) { if (_cite_flag) { std::string cite = std::string((char*)chars,length); _title += cite; } } void se_parser_yahoo_img::end_element(parser_context *pc, const xmlChar *name) { const char *tag = (const char*)name; if (!_results_flag) return; if (_results_flag && strcasecmp(tag,"ul") == 0) _results_flag = false; if (_results_flag && strcasecmp(tag,"cite") == 0) { _cite_flag = false; pc->_current_snippet->_title = _title; _title.clear(); } } } /* end of namespace. */ <|endoftext|>
<commit_before>//===---- tools/extra/ToolTemplate.cpp - Template for refactoring tool ----===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements an empty refactoring tool using the clang tooling. // The goal is to lower the "barrier to entry" for writing refactoring tools. // // Usage: // tool-template <cmake-output-dir> <file1> <file2> ... // // Where <cmake-output-dir> is a CMake build directory in which a file named // compile_commands.json exists (enable -DCMAKE_EXPORT_COMPILE_COMMANDS in // CMake to get this output). // // <file1> ... specify the paths of files in the CMake source tree. This path // is looked up in the compile command database. If the path of a file is // absolute, it needs to point into CMake's source tree. If the path is // relative, the current working directory needs to be in the CMake source // tree and the file must be in a subdirectory of the current working // directory. "./" prefixes in the relative files will be automatically // removed, but the rest of a relative path must be a suffix of a path in // the compile command line database. // // For example, to use tool-template on all files in a subtree of the // source tree, use: // // /path/in/subtree $ find . -name '*.cpp'| // xargs tool-template /path/to/build // //===----------------------------------------------------------------------===// #include "clang/AST/ASTImporter.h" #include "clang/AST/RecursiveASTVisitor.h" #include "clang/Tooling/CommonOptionsParser.h" #include "clang/Frontend/ASTUnit.h" #include "clang/Frontend/TextDiagnosticPrinter.h" #include "llvm/Support/Signals.h" using namespace clang; using namespace clang::tooling; using namespace llvm; // Set up the command line options static cl::extrahelp CommonHelp(CommonOptionsParser::HelpMessage); static cl::OptionCategory ToolTemplateCategory("odr-check options"); typedef std::unique_ptr<ASTUnit> ASTUnitPtr; class TagDeclVisitor : public RecursiveASTVisitor<TagDeclVisitor> { public: TagDeclVisitor(ASTUnit& to, ASTUnit& from) : m_to(to) , m_from(from) , m_importer(to.getASTContext(), to.getFileManager(), from.getASTContext(), from.getFileManager(), false) { } void MergeASTs() { TraverseDecl(m_from.getASTContext().getTranslationUnitDecl()); } bool VisitTagDecl(TagDecl* fromDecl) { m_importer.Import(fromDecl); return true; } private: ASTUnit& m_to; ASTUnit& m_from; ASTImporter m_importer; }; int main(int argc, const char **argv) { llvm::sys::PrintStackTraceOnErrorSignal(); //CommonOptionsParser OptionsParser(argc, argv, ToolTemplateCategory); IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts = new DiagnosticOptions(); TextDiagnosticPrinter DiagnosticPrinter( llvm::errs(), &*DiagOpts); IntrusiveRefCntPtr<DiagnosticsEngine> Diagnostics = new DiagnosticsEngine( IntrusiveRefCntPtr<clang::DiagnosticIDs>(new DiagnosticIDs()), &*DiagOpts, &DiagnosticPrinter, false); std::vector<ASTUnitPtr> units; bool shouldDumpAST = false; ++argv; while (*argv) { const std::string arg = *argv; ++argv; if ("--should_dump_ast" == arg) { shouldDumpAST = true; continue; } llvm::errs() << "processing file [" << arg << "]...\n"; ASTUnitPtr unit = ASTUnit::LoadFromASTFile(arg, Diagnostics, FileSystemOptions()); if (unit) { units.push_back(std::move(unit)); } } if (units.empty()) { llvm::errs() << "not AST units found\n"; return 0; } auto front = units.begin(); auto next = front + 1; ASTUnit& to = **front; while (next != units.end()) { ASTUnit& from = **next; llvm::errs() << "merging AST [" << from.getASTFileName() << "] to [" << to.getASTFileName() << "]...\n"; TagDeclVisitor visitor(to, from); visitor.MergeASTs(); ++next; } if (shouldDumpAST) { llvm::errs() << "dumping final AST...\n"; ASTContext& finalContext = to.getASTContext(); finalContext.getTranslationUnitDecl()->dump(llvm::errs()); } return 0; } <commit_msg>Fixed issue with incorrect diagnostic printing<commit_after>//===---- tools/extra/ToolTemplate.cpp - Template for refactoring tool ----===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements an empty refactoring tool using the clang tooling. // The goal is to lower the "barrier to entry" for writing refactoring tools. // // Usage: // tool-template <cmake-output-dir> <file1> <file2> ... // // Where <cmake-output-dir> is a CMake build directory in which a file named // compile_commands.json exists (enable -DCMAKE_EXPORT_COMPILE_COMMANDS in // CMake to get this output). // // <file1> ... specify the paths of files in the CMake source tree. This path // is looked up in the compile command database. If the path of a file is // absolute, it needs to point into CMake's source tree. If the path is // relative, the current working directory needs to be in the CMake source // tree and the file must be in a subdirectory of the current working // directory. "./" prefixes in the relative files will be automatically // removed, but the rest of a relative path must be a suffix of a path in // the compile command line database. // // For example, to use tool-template on all files in a subtree of the // source tree, use: // // /path/in/subtree $ find . -name '*.cpp'| // xargs tool-template /path/to/build // //===----------------------------------------------------------------------===// #include "clang/AST/ASTImporter.h" #include "clang/AST/RecursiveASTVisitor.h" #include "clang/Tooling/CommonOptionsParser.h" #include "clang/Frontend/ASTUnit.h" #include "clang/Frontend/TextDiagnosticPrinter.h" #include "llvm/Support/Signals.h" using namespace clang; using namespace clang::tooling; using namespace llvm; // Set up the command line options static cl::extrahelp CommonHelp(CommonOptionsParser::HelpMessage); static cl::OptionCategory ToolTemplateCategory("odr-check options"); typedef std::unique_ptr<ASTUnit> ASTUnitPtr; class TagDeclVisitor : public RecursiveASTVisitor<TagDeclVisitor> { public: TagDeclVisitor(ASTUnit& to, ASTUnit& from) : m_to(to) , m_from(from) , m_importer(to.getASTContext(), to.getFileManager(), from.getASTContext(), from.getFileManager(), false) { } void MergeASTs() { TraverseDecl(m_from.getASTContext().getTranslationUnitDecl()); } bool VisitTagDecl(TagDecl* fromDecl) { m_importer.Import(fromDecl); return true; } private: ASTUnit& m_to; ASTUnit& m_from; ASTImporter m_importer; }; int main(int argc, const char **argv) { llvm::sys::PrintStackTraceOnErrorSignal(); //CommonOptionsParser OptionsParser(argc, argv, ToolTemplateCategory); std::vector<ASTUnitPtr> units; bool shouldDumpAST = false; ++argv; while (*argv) { const std::string arg = *argv; ++argv; if ("--should_dump_ast" == arg) { shouldDumpAST = true; continue; } IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts = new DiagnosticOptions(); std::unique_ptr<TextDiagnosticPrinter> DiagnosticPrinter = llvm::make_unique<TextDiagnosticPrinter>( llvm::errs(), &*DiagOpts); IntrusiveRefCntPtr<DiagnosticsEngine> Diagnostics = new DiagnosticsEngine( IntrusiveRefCntPtr<clang::DiagnosticIDs>(new DiagnosticIDs()), &*DiagOpts, DiagnosticPrinter.release()); llvm::errs() << "processing file [" << arg << "]...\n"; ASTUnitPtr unit = ASTUnit::LoadFromASTFile(arg, Diagnostics, FileSystemOptions()); if (unit) { units.push_back(std::move(unit)); } } if (units.empty()) { llvm::errs() << "not AST units found\n"; return 0; } auto front = units.begin(); auto next = front + 1; ASTUnit& to = **front; while (next != units.end()) { ASTUnit& from = **next; llvm::errs() << "merging AST [" << from.getASTFileName() << "] to [" << to.getASTFileName() << "]...\n"; TagDeclVisitor visitor(to, from); visitor.MergeASTs(); ++next; } if (shouldDumpAST) { llvm::errs() << "dumping final AST...\n"; ASTContext& finalContext = to.getASTContext(); finalContext.getTranslationUnitDecl()->dump(llvm::errs()); } return 0; } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: nodechangeimpl.hxx,v $ * * $Revision: 1.11 $ * * last change: $Author: rt $ $Date: 2005-09-08 04:30:33 $ * * 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 CONFIGMGR_CONFIGCHANGEIMPL_HXX_ #define CONFIGMGR_CONFIGCHANGEIMPL_HXX_ #ifndef CONFIGMGR_CONFIGEXCEPT_HXX_ #include "configexcept.hxx" #endif #ifndef CONFIGMGR_CONFIGPATH_HXX_ #include "configpath.hxx" #endif #ifndef CONFIGMGR_VIEWACCESS_HXX_ #include "viewaccess.hxx" #endif #ifndef _RTL_REF_HXX_ #include <rtl/ref.hxx> #endif #ifndef _SALHELPER_SIMPLEREFERENCEOBJECT_HXX_ #include <salhelper/simplereferenceobject.hxx> #endif #ifndef INCLUDED_VECTOR #include <vector> #define INCLUDED_VECTOR #endif #ifndef INCLUDED_MEMORY #include <memory> #define INCLUDED_MEMORY #endif namespace configmgr { class ISubtree; namespace view { class ViewTreeAccess; struct Node; struct GroupNode; struct SetNode; } //----------------------------------------------------------------------------- namespace configuration { //----------------------------------------------------------------------------- typedef com::sun::star::uno::Type UnoType; typedef com::sun::star::uno::Any UnoAny; //----------------------------------------------------------------------------- class ValueMemberNode; class ValueMemberUpdate; //----------------------------------------------------------------------------- class NodeChangeData; class NodeChangeLocation; class NodeChangeInformation; //----------------------------------------------------------------------------- typedef rtl::Reference<TreeImpl> TreeHolder; typedef rtl::Reference<ElementTreeImpl> ElementTreeHolder; //----------------------------------------------------------------------------- struct ElementTreeChange { Path::Component m_aElementName; ElementTreeHolder m_aAddedElement; ElementTreeHolder m_aRemovedElement; ElementTreeChange( Path::Component const& _aElementName, ElementTreeHolder const& _aAddedElement, ElementTreeHolder const& _aRemovedElement ) : m_aElementName(_aElementName) , m_aAddedElement(_aAddedElement) , m_aRemovedElement(_aRemovedElement) {} bool isChange() const { return !!(m_aAddedElement != m_aRemovedElement); } }; //----------------------------------------------------------------------------- /// represents a node position in some tree class NodeChangeImpl : public salhelper::SimpleReferenceObject { public: explicit NodeChangeImpl(bool bNoCheck = false); public: // related/affected nodes and trees /// the tree within which the change occurs TreeHolder getTargetTree() const; /// the node that is affected by the change NodeOffset getTargetNode() const; data::Accessor const& getDataAccessor() const { return m_aDataAccessor; } protected: /// setup the 'target' node that is to be affected or changed void setTarget(data::Accessor const& _aAccessor, TreeHolder const& _aAffectedTree, NodeOffset _nAffectedNode); void setTarget(view::Node _aAffectedNode); view::ViewTreeAccess getTargetView(); public: // getting information typedef sal_uInt32 ChangeCount; /*static const ChangeCount*/ enum { scCommonBase = ~0u }; /// checks, if this represents an actual change - with or without requiring a preceding test bool isChange(bool bAllowUntested) const; /// return the number of distict changes in this object ChangeCount getChangeDataCount() const; /// fills in base change location, returns whether it is set bool fillChangeLocation(NodeChangeLocation& rChange, ChangeCount _ix = scCommonBase) const; /// fills in pre- and post-change values, returns whether they may differ bool fillChangeData(NodeChangeData& rChange, ChangeCount _ix) const; /// fills in change location and values, returns whether data may be changed bool fillChangeInfo(NodeChangeInformation& rChange, ChangeCount _ix) const; /// test whether this really is a change to the stored 'changing' node void test(); /// apply this change to the stored 'changing' node void apply(); private: /// virtual hooks for some of the public methods /// return the number of distict changes in this object ChangeCount doGetChangeCount() const; /// the path from base to 'changing' node virtual RelativePath doGetChangingNodePath(ChangeCount _ix) const = 0; /// is the change really affecting a child (or children) of the affected node (true for values) virtual bool doIsChangingSubnode() const = 0; /// checks, if this represents an actual change (given whether the change has been applied or not) virtual bool doIsChange() const = 0; /// fills in pre- and post-change values, returns wether they differ virtual bool doFillChange(NodeChangeData& rChange, ChangeCount _ix) const = 0; /// dry-check whether this is a change virtual void doTest( view::Node const& rTarget) = 0; /// do apply the actual change virtual void doApply( view::Node const& rTarget) = 0; private: typedef sal_uInt16 State; data::Accessor m_aDataAccessor; TreeHolder m_aAffectedTree; NodeOffset m_nAffectedNode; State m_nState; void implApply(); view::Node implGetTarget(); }; //----------------------------------------------------------------------------- /// represents a node position in some tree class ValueChangeImpl : public NodeChangeImpl { Name m_aName; UnoAny m_aNewValue; UnoAny m_aOldValue; public: explicit ValueChangeImpl(); explicit ValueChangeImpl(UnoAny const& aNewValue); explicit ValueChangeImpl(UnoAny const& aNewValue, UnoAny const& aOldValue); ~ValueChangeImpl(); public: /// setup the 'target' node that is to be affected or changed void setTarget(view::GroupNode const& _aParentNode, Name const& sNodeName); void setTarget(data::Accessor const& _aAccessor, TreeHolder const& aAffectedTree, NodeOffset nParentNode, Name const& sNodeName); public: /// get the name of the value Name getValueName() const { return m_aName; } /// get the pre-change value (if known) UnoAny getOldValue() const { return m_aOldValue; } /// get the post-change value (if known) UnoAny getNewValue() const { return m_aNewValue; } protected: // override information items /// the path from base to 'affected' node - here is the name of the changing node virtual RelativePath doGetChangingNodePath(ChangeCount _ix) const; /// is the change really affecting a child of the affected node (true here) virtual bool doIsChangingSubnode() const; protected: // override change information items /// checks, if this represents an actual change (given whether the change has been applied or not) virtual bool doIsChange() const; /// fills in pre- and post-change values, returns wether they differ virtual bool doFillChange(NodeChangeData& rChange, ChangeCount _ix) const = 0; protected: // override apply functionality /// retrieve the old value from the given node virtual void doTest( view::Node const& rTarget); /// do apply the actual change virtual void doApply( view::Node const& rTarget); protected: // new overrideables /// extract the pre-change value from the target context virtual void preCheckValue(ValueMemberNode& rNode, UnoAny& rOld, UnoAny& rNew); /// extract the post-change value from the target context virtual void postCheckValue(ValueMemberNode& rNode, UnoAny& rNew); /// apply the new value to the target context virtual void doApplyChange(ValueMemberUpdate& rNode) = 0; }; //----------------------------------------------------------------------------- /// represents setting a value node to a given value class ValueReplaceImpl : public ValueChangeImpl { public: explicit ValueReplaceImpl(UnoAny const& aNewValue); explicit ValueReplaceImpl(UnoAny const& aNewValue, UnoAny const& aOldValue); protected: // implement: set the target to the new value virtual void doApplyChange( ValueMemberUpdate& rNode); /// fills in pre- and post-change values, returns wether they differ virtual bool doFillChange(NodeChangeData& rChange, ChangeCount _ix) const; // friend class SetReplaceValueImpl; }; //----------------------------------------------------------------------------- /// represents resetting a value node to its default value class ValueResetImpl : public ValueChangeImpl { bool m_bTargetIsDefault; public: explicit ValueResetImpl(); explicit ValueResetImpl(UnoAny const& aNewValue, UnoAny const& aOldValue); protected: // override: set the new value as well and check the default state virtual void preCheckValue(ValueMemberNode& rNode, UnoAny& rOld, UnoAny& rNew); /// checks, if this represents an actual change (given whether the change has been applied or not) virtual bool doIsChange() const; // implement: set the target to default virtual void doApplyChange( ValueMemberUpdate& rNode); /// fills in pre- and post-change values, returns wether they differ virtual bool doFillChange(NodeChangeData& rChange, ChangeCount _ix) const; }; //----------------------------------------------------------------------------- /// represents a change to a set (as a container) class SetChangeImpl : public NodeChangeImpl { public: explicit SetChangeImpl(bool bNoCheck = false); using NodeChangeImpl::setTarget; protected: /// virtual hooks for some of the public methods /// is the change really affecting a child of the affected node (false here) virtual bool doIsChangingSubnode() const; }; //----------------------------------------------------------------------------- class SetElementFactory; /// represents setting to its default state a set (as a container) class SetResetImpl : public SetChangeImpl { typedef std::vector< ElementTreeChange > TreeChanges; std::auto_ptr<ISubtree> m_aDefaultData; SetElementFactory& m_rElementFactory; TreeChanges m_aTreeChanges; public: explicit SetResetImpl( SetElementFactory& _rElementFactory, std::auto_ptr<ISubtree> _pDefaultData, bool _bNoCheck = false); ~SetResetImpl(); protected: /// virtual hooks for some of the public methods /// retrieve the count of elements affected ChangeCount doGetChangeCount() const; /// the path from base to 'affected' node virtual RelativePath doGetChangingNodePath(ChangeCount _ix) const; /// checks, if this represents an actual change (given whether the change has been applied or not) virtual bool doIsChange() const; /// fills in pre- and post-change values, returns wether they differ virtual bool doFillChange(NodeChangeData& rChange, ChangeCount _ix) const; /// retrieve the old value from the given node virtual void doTest( view::Node const& rTarget); /// do apply the actual change virtual void doApply( view::Node const& rTarget); }; //----------------------------------------------------------------------------- /// represents a change to an element of a set (as a container) class SetElementChangeImpl : public SetChangeImpl { Path::Component m_aName; public: explicit SetElementChangeImpl(Path::Component const& aName, bool bNoCheck = false); /// the name of the element being changed Path::Component getFullElementName() const { return m_aName; } /// the name of the element being changed Name getElementName() const { return m_aName.getName(); } protected: /// virtual hooks for some of the public methods /// the path from base to 'affected' node - use element name virtual RelativePath doGetChangingNodePath(ChangeCount _ix) const; /// retrieve the old value from the given node virtual void doTest( view::Node const& rTarget); /// do apply the actual change virtual void doApply( view::Node const& rTarget); private: /// new overridable: retrieve the old value from a properly typed node virtual void doTestElement(view::SetNode const& _aNode, Name const& aName) = 0; /// new overridable: apply the change to a properly typed node virtual void doApplyToElement(view::SetNode const& _aNode, Name const& aName) = 0; }; //----------------------------------------------------------------------------- /// represents an insertion into a set of trees class SetInsertImpl : public SetElementChangeImpl { ElementTreeHolder m_aNewTree; public: explicit SetInsertImpl(Path::Component const& aName, ElementTreeHolder const& aNewTree, bool bNoCheck = false); protected: /// checks, if this represents an actual change (given whether the change has been applied or not) virtual bool doIsChange() const; /// fills in pre- and post-change values, returns wether they differ virtual bool doFillChange(NodeChangeData& rChange, ChangeCount _ix) const; /// new overridable: retrieve the old value from a properly typed node virtual void doTestElement(view::SetNode const& _aNode, Name const& aName); /// new overridable: apply the change to a properly typed node virtual void doApplyToElement(view::SetNode const& _aNode, Name const& aName); }; //----------------------------------------------------------------------------- /// represents a substitution within a set of trees class SetReplaceImpl : public SetElementChangeImpl { ElementTreeHolder m_aNewTree; ElementTreeHolder m_aOldTree; public: explicit SetReplaceImpl(Path::Component const& aName, ElementTreeHolder const& aNewTree); explicit SetReplaceImpl(Path::Component const& aName, ElementTreeHolder const& aNewTree, ElementTreeHolder const& aOldTree); protected: /// checks, if this represents an actual change (given whether the change has been applied or not) virtual bool doIsChange() const; /// fills in pre- and post-change values, returns wether they differ virtual bool doFillChange(NodeChangeData& rChange, ChangeCount _ix) const; /// new overridable: retrieve the old value from a properly typed node virtual void doTestElement(view::SetNode const& _aNode, Name const& aName); /// new overridable: apply the change to a properly typed node virtual void doApplyToElement(view::SetNode const& _aNode, Name const& aName); }; //----------------------------------------------------------------------------- /// represents a removal from of a set of trees class SetRemoveImpl : public SetElementChangeImpl { ElementTreeHolder m_aOldTree; public: explicit SetRemoveImpl(Path::Component const& aName); explicit SetRemoveImpl(Path::Component const& aName, ElementTreeHolder const& aOldTree); protected: /// checks, if this represents an actual change (given whether the change has been applied or not) virtual bool doIsChange() const; /// fills in pre- and post-change values, returns wether they differ virtual bool doFillChange(NodeChangeData& rChange, ChangeCount _ix) const; /// new overridable: retrieve the old value from a properly typed node virtual void doTestElement(view::SetNode const& _aNode, Name const& aName); /// new overridable: apply the change to a properly typed node virtual void doApplyToElement(view::SetNode const& _aNode, Name const& aName); }; //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- } } #endif // CONFIGMGR_CONFIGCHANGEIMPL_HXX_ <commit_msg>INTEGRATION: CWS warnings01 (1.11.4); FILE MERGED 2005/11/01 12:47:37 cd 1.11.4.1: #i53898# Warning free code for sun solaris compiler<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: nodechangeimpl.hxx,v $ * * $Revision: 1.12 $ * * last change: $Author: hr $ $Date: 2006-06-19 23:32:49 $ * * 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 CONFIGMGR_CONFIGCHANGEIMPL_HXX_ #define CONFIGMGR_CONFIGCHANGEIMPL_HXX_ #ifndef CONFIGMGR_CONFIGEXCEPT_HXX_ #include "configexcept.hxx" #endif #ifndef CONFIGMGR_CONFIGPATH_HXX_ #include "configpath.hxx" #endif #ifndef CONFIGMGR_VIEWACCESS_HXX_ #include "viewaccess.hxx" #endif #ifndef _RTL_REF_HXX_ #include <rtl/ref.hxx> #endif #ifndef _SALHELPER_SIMPLEREFERENCEOBJECT_HXX_ #include <salhelper/simplereferenceobject.hxx> #endif #ifndef INCLUDED_VECTOR #include <vector> #define INCLUDED_VECTOR #endif #ifndef INCLUDED_MEMORY #include <memory> #define INCLUDED_MEMORY #endif namespace configmgr { class ISubtree; namespace view { class ViewTreeAccess; struct Node; struct GroupNode; struct SetNode; } //----------------------------------------------------------------------------- namespace configuration { //----------------------------------------------------------------------------- typedef com::sun::star::uno::Type UnoType; typedef com::sun::star::uno::Any UnoAny; //----------------------------------------------------------------------------- class ValueMemberNode; class ValueMemberUpdate; //----------------------------------------------------------------------------- class NodeChangeData; class NodeChangeLocation; class NodeChangeInformation; //----------------------------------------------------------------------------- typedef rtl::Reference<TreeImpl> TreeHolder; typedef rtl::Reference<ElementTreeImpl> ElementTreeHolder; //----------------------------------------------------------------------------- struct ElementTreeChange { Path::Component m_aElementName; ElementTreeHolder m_aAddedElement; ElementTreeHolder m_aRemovedElement; ElementTreeChange( Path::Component const& _aElementName, ElementTreeHolder const& _aAddedElement, ElementTreeHolder const& _aRemovedElement ) : m_aElementName(_aElementName) , m_aAddedElement(_aAddedElement) , m_aRemovedElement(_aRemovedElement) {} bool isChange() const { return !!(m_aAddedElement != m_aRemovedElement); } }; //----------------------------------------------------------------------------- /// represents a node position in some tree class NodeChangeImpl : public salhelper::SimpleReferenceObject { public: explicit NodeChangeImpl(bool bNoCheck = false); public: // related/affected nodes and trees /// the tree within which the change occurs TreeHolder getTargetTree() const; /// the node that is affected by the change NodeOffset getTargetNode() const; data::Accessor const& getDataAccessor() const { return m_aDataAccessor; } protected: /// setup the 'target' node that is to be affected or changed void setTarget(data::Accessor const& _aAccessor, TreeHolder const& _aAffectedTree, NodeOffset _nAffectedNode); void setTarget(view::Node _aAffectedNode); view::ViewTreeAccess getTargetView(); public: // getting information typedef sal_uInt32 ChangeCount; /*static const ChangeCount*/ enum { scCommonBase = ~0u }; /// checks, if this represents an actual change - with or without requiring a preceding test bool isChange(bool bAllowUntested) const; /// return the number of distict changes in this object ChangeCount getChangeDataCount() const; /// fills in base change location, returns whether it is set bool fillChangeLocation(NodeChangeLocation& rChange, ChangeCount _ix = scCommonBase) const; /// fills in pre- and post-change values, returns whether they may differ bool fillChangeData(NodeChangeData& rChange, ChangeCount _ix) const; /// fills in change location and values, returns whether data may be changed bool fillChangeInfo(NodeChangeInformation& rChange, ChangeCount _ix) const; /// test whether this really is a change to the stored 'changing' node void test(); /// apply this change to the stored 'changing' node void apply(); private: /// virtual hooks for some of the public methods /// return the number of distict changes in this object ChangeCount doGetChangeCount() const; /// the path from base to 'changing' node virtual RelativePath doGetChangingNodePath(ChangeCount _ix) const = 0; /// is the change really affecting a child (or children) of the affected node (true for values) virtual bool doIsChangingSubnode() const = 0; /// checks, if this represents an actual change (given whether the change has been applied or not) virtual bool doIsChange() const = 0; /// fills in pre- and post-change values, returns wether they differ virtual bool doFillChange(NodeChangeData& rChange, ChangeCount _ix) const = 0; /// dry-check whether this is a change virtual void doTest( view::Node const& rTarget) = 0; /// do apply the actual change virtual void doApply( view::Node const& rTarget) = 0; private: typedef sal_uInt16 State; data::Accessor m_aDataAccessor; TreeHolder m_aAffectedTree; NodeOffset m_nAffectedNode; State m_nState; void implApply(); view::Node implGetTarget(); }; //----------------------------------------------------------------------------- /// represents a node position in some tree class ValueChangeImpl : public NodeChangeImpl { Name m_aName; UnoAny m_aNewValue; UnoAny m_aOldValue; public: explicit ValueChangeImpl(); explicit ValueChangeImpl(UnoAny const& aNewValue); explicit ValueChangeImpl(UnoAny const& aNewValue, UnoAny const& aOldValue); ~ValueChangeImpl(); public: /// setup the 'target' node that is to be affected or changed void setTarget(view::GroupNode const& _aParentNode, Name const& sNodeName); void setTarget(data::Accessor const& _aAccessor, TreeHolder const& aAffectedTree, NodeOffset nParentNode, Name const& sNodeName); public: /// get the name of the value Name getValueName() const { return m_aName; } /// get the pre-change value (if known) UnoAny getOldValue() const { return m_aOldValue; } /// get the post-change value (if known) UnoAny getNewValue() const { return m_aNewValue; } protected: using NodeChangeImpl::setTarget; // override information items /// the path from base to 'affected' node - here is the name of the changing node virtual RelativePath doGetChangingNodePath(ChangeCount _ix) const; /// is the change really affecting a child of the affected node (true here) virtual bool doIsChangingSubnode() const; protected: // override change information items /// checks, if this represents an actual change (given whether the change has been applied or not) virtual bool doIsChange() const; /// fills in pre- and post-change values, returns wether they differ virtual bool doFillChange(NodeChangeData& rChange, ChangeCount _ix) const = 0; protected: // override apply functionality /// retrieve the old value from the given node virtual void doTest( view::Node const& rTarget); /// do apply the actual change virtual void doApply( view::Node const& rTarget); protected: // new overrideables /// extract the pre-change value from the target context virtual void preCheckValue(ValueMemberNode& rNode, UnoAny& rOld, UnoAny& rNew); /// extract the post-change value from the target context virtual void postCheckValue(ValueMemberNode& rNode, UnoAny& rNew); /// apply the new value to the target context virtual void doApplyChange(ValueMemberUpdate& rNode) = 0; }; //----------------------------------------------------------------------------- /// represents setting a value node to a given value class ValueReplaceImpl : public ValueChangeImpl { public: explicit ValueReplaceImpl(UnoAny const& aNewValue); explicit ValueReplaceImpl(UnoAny const& aNewValue, UnoAny const& aOldValue); protected: // implement: set the target to the new value virtual void doApplyChange( ValueMemberUpdate& rNode); /// fills in pre- and post-change values, returns wether they differ virtual bool doFillChange(NodeChangeData& rChange, ChangeCount _ix) const; // friend class SetReplaceValueImpl; }; //----------------------------------------------------------------------------- /// represents resetting a value node to its default value class ValueResetImpl : public ValueChangeImpl { bool m_bTargetIsDefault; public: explicit ValueResetImpl(); explicit ValueResetImpl(UnoAny const& aNewValue, UnoAny const& aOldValue); protected: // override: set the new value as well and check the default state virtual void preCheckValue(ValueMemberNode& rNode, UnoAny& rOld, UnoAny& rNew); /// checks, if this represents an actual change (given whether the change has been applied or not) virtual bool doIsChange() const; // implement: set the target to default virtual void doApplyChange( ValueMemberUpdate& rNode); /// fills in pre- and post-change values, returns wether they differ virtual bool doFillChange(NodeChangeData& rChange, ChangeCount _ix) const; }; //----------------------------------------------------------------------------- /// represents a change to a set (as a container) class SetChangeImpl : public NodeChangeImpl { public: explicit SetChangeImpl(bool bNoCheck = false); using NodeChangeImpl::setTarget; protected: /// virtual hooks for some of the public methods /// is the change really affecting a child of the affected node (false here) virtual bool doIsChangingSubnode() const; }; //----------------------------------------------------------------------------- class SetElementFactory; /// represents setting to its default state a set (as a container) class SetResetImpl : public SetChangeImpl { typedef std::vector< ElementTreeChange > TreeChanges; std::auto_ptr<ISubtree> m_aDefaultData; SetElementFactory& m_rElementFactory; TreeChanges m_aTreeChanges; public: explicit SetResetImpl( SetElementFactory& _rElementFactory, std::auto_ptr<ISubtree> _pDefaultData, bool _bNoCheck = false); ~SetResetImpl(); protected: /// virtual hooks for some of the public methods /// retrieve the count of elements affected ChangeCount doGetChangeCount() const; /// the path from base to 'affected' node virtual RelativePath doGetChangingNodePath(ChangeCount _ix) const; /// checks, if this represents an actual change (given whether the change has been applied or not) virtual bool doIsChange() const; /// fills in pre- and post-change values, returns wether they differ virtual bool doFillChange(NodeChangeData& rChange, ChangeCount _ix) const; /// retrieve the old value from the given node virtual void doTest( view::Node const& rTarget); /// do apply the actual change virtual void doApply( view::Node const& rTarget); }; //----------------------------------------------------------------------------- /// represents a change to an element of a set (as a container) class SetElementChangeImpl : public SetChangeImpl { Path::Component m_aName; public: explicit SetElementChangeImpl(Path::Component const& aName, bool bNoCheck = false); /// the name of the element being changed Path::Component getFullElementName() const { return m_aName; } /// the name of the element being changed Name getElementName() const { return m_aName.getName(); } protected: /// virtual hooks for some of the public methods /// the path from base to 'affected' node - use element name virtual RelativePath doGetChangingNodePath(ChangeCount _ix) const; /// retrieve the old value from the given node virtual void doTest( view::Node const& rTarget); /// do apply the actual change virtual void doApply( view::Node const& rTarget); private: /// new overridable: retrieve the old value from a properly typed node virtual void doTestElement(view::SetNode const& _aNode, Name const& aName) = 0; /// new overridable: apply the change to a properly typed node virtual void doApplyToElement(view::SetNode const& _aNode, Name const& aName) = 0; }; //----------------------------------------------------------------------------- /// represents an insertion into a set of trees class SetInsertImpl : public SetElementChangeImpl { ElementTreeHolder m_aNewTree; public: explicit SetInsertImpl(Path::Component const& aName, ElementTreeHolder const& aNewTree, bool bNoCheck = false); protected: /// checks, if this represents an actual change (given whether the change has been applied or not) virtual bool doIsChange() const; /// fills in pre- and post-change values, returns wether they differ virtual bool doFillChange(NodeChangeData& rChange, ChangeCount _ix) const; /// new overridable: retrieve the old value from a properly typed node virtual void doTestElement(view::SetNode const& _aNode, Name const& aName); /// new overridable: apply the change to a properly typed node virtual void doApplyToElement(view::SetNode const& _aNode, Name const& aName); }; //----------------------------------------------------------------------------- /// represents a substitution within a set of trees class SetReplaceImpl : public SetElementChangeImpl { ElementTreeHolder m_aNewTree; ElementTreeHolder m_aOldTree; public: explicit SetReplaceImpl(Path::Component const& aName, ElementTreeHolder const& aNewTree); explicit SetReplaceImpl(Path::Component const& aName, ElementTreeHolder const& aNewTree, ElementTreeHolder const& aOldTree); protected: /// checks, if this represents an actual change (given whether the change has been applied or not) virtual bool doIsChange() const; /// fills in pre- and post-change values, returns wether they differ virtual bool doFillChange(NodeChangeData& rChange, ChangeCount _ix) const; /// new overridable: retrieve the old value from a properly typed node virtual void doTestElement(view::SetNode const& _aNode, Name const& aName); /// new overridable: apply the change to a properly typed node virtual void doApplyToElement(view::SetNode const& _aNode, Name const& aName); }; //----------------------------------------------------------------------------- /// represents a removal from of a set of trees class SetRemoveImpl : public SetElementChangeImpl { ElementTreeHolder m_aOldTree; public: explicit SetRemoveImpl(Path::Component const& aName); explicit SetRemoveImpl(Path::Component const& aName, ElementTreeHolder const& aOldTree); protected: /// checks, if this represents an actual change (given whether the change has been applied or not) virtual bool doIsChange() const; /// fills in pre- and post-change values, returns wether they differ virtual bool doFillChange(NodeChangeData& rChange, ChangeCount _ix) const; /// new overridable: retrieve the old value from a properly typed node virtual void doTestElement(view::SetNode const& _aNode, Name const& aName); /// new overridable: apply the change to a properly typed node virtual void doApplyToElement(view::SetNode const& _aNode, Name const& aName); }; //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- } } #endif // CONFIGMGR_CONFIGCHANGEIMPL_HXX_ <|endoftext|>
<commit_before>/************************************************************************** ** ** This file is part of Qt Creator ** ** Copyright (c) 2011 Nokia Corporation and/or its subsidiary(-ies). ** ** Contact: Nokia Corporation ([email protected]) ** ** No Commercial Usage ** ** This file contains pre-release code and may not be distributed. ** You may use this file in accordance with the terms and conditions ** contained in the Technology Preview License Agreement accompanying ** this package. ** ** 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, 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. ** ** If you have questions regarding the use of this file, please contact ** Nokia at [email protected]. ** **************************************************************************/ #include "environmentwidget.h" #include <utils/detailswidget.h> #include <utils/environment.h> #include <utils/environmentmodel.h> #include <QtCore/QString> #include <QtGui/QHeaderView> #include <QtGui/QPushButton> #include <QtGui/QTableView> #include <QtGui/QTextDocument> // for Qt::escape #include <QtGui/QVBoxLayout> namespace ProjectExplorer { //// // EnvironmentWidget::EnvironmentWidget //// class EnvironmentWidgetPrivate { public: Utils::EnvironmentModel *m_model; QString m_baseEnvironmentText; Utils::DetailsWidget *m_detailsContainer; QTableView *m_environmentView; QPushButton *m_editButton; QPushButton *m_addButton; QPushButton *m_resetButton; QPushButton *m_unsetButton; }; EnvironmentWidget::EnvironmentWidget(QWidget *parent, QWidget *additionalDetailsWidget) : QWidget(parent), d(new EnvironmentWidgetPrivate) { d->m_model = new Utils::EnvironmentModel(); connect(d->m_model, SIGNAL(userChangesChanged()), this, SIGNAL(userChangesChanged())); connect(d->m_model, SIGNAL(modelReset()), this, SLOT(invalidateCurrentIndex())); connect(d->m_model, SIGNAL(focusIndex(QModelIndex)), this, SLOT(focusIndex(QModelIndex))); QVBoxLayout *vbox = new QVBoxLayout(this); vbox->setContentsMargins(0, 0, 0, 0); d->m_detailsContainer = new Utils::DetailsWidget(this); QWidget *details = new QWidget(d->m_detailsContainer); d->m_detailsContainer->setWidget(details); details->setVisible(false); QVBoxLayout *vbox2 = new QVBoxLayout(details); vbox2->setMargin(0); if (additionalDetailsWidget) vbox2->addWidget(additionalDetailsWidget); QHBoxLayout *horizontalLayout = new QHBoxLayout(); horizontalLayout->setMargin(0); d->m_environmentView = new QTableView(this); d->m_environmentView->setModel(d->m_model); d->m_environmentView->setMinimumHeight(400); d->m_environmentView->setGridStyle(Qt::NoPen); d->m_environmentView->horizontalHeader()->setStretchLastSection(true); d->m_environmentView->horizontalHeader()->setResizeMode(0, QHeaderView::ResizeToContents); d->m_environmentView->horizontalHeader()->setHighlightSections(false); d->m_environmentView->verticalHeader()->hide(); QFontMetrics fm(font()); d->m_environmentView->verticalHeader()->setDefaultSectionSize(qMax(static_cast<int>(fm.height() * 1.2), fm.height() + 4)); d->m_environmentView->setSelectionMode(QAbstractItemView::SingleSelection); horizontalLayout->addWidget(d->m_environmentView); QVBoxLayout *buttonLayout = new QVBoxLayout(); d->m_editButton = new QPushButton(this); d->m_editButton->setText(tr("&Edit")); buttonLayout->addWidget(d->m_editButton); d->m_addButton = new QPushButton(this); d->m_addButton->setText(tr("&Add")); buttonLayout->addWidget(d->m_addButton); d->m_resetButton = new QPushButton(this); d->m_resetButton->setEnabled(false); d->m_resetButton->setText(tr("&Reset")); buttonLayout->addWidget(d->m_resetButton); d->m_unsetButton = new QPushButton(this); d->m_unsetButton->setEnabled(false); d->m_unsetButton->setText(tr("&Unset")); buttonLayout->addWidget(d->m_unsetButton); QSpacerItem *verticalSpacer = new QSpacerItem(20, 40, QSizePolicy::Minimum, QSizePolicy::Expanding); buttonLayout->addItem(verticalSpacer); horizontalLayout->addLayout(buttonLayout); vbox2->addLayout(horizontalLayout); vbox->addWidget(d->m_detailsContainer); connect(d->m_model, SIGNAL(dataChanged(const QModelIndex&, const QModelIndex&)), this, SLOT(updateButtons())); connect(d->m_editButton, SIGNAL(clicked(bool)), this, SLOT(editEnvironmentButtonClicked())); connect(d->m_addButton, SIGNAL(clicked(bool)), this, SLOT(addEnvironmentButtonClicked())); connect(d->m_resetButton, SIGNAL(clicked(bool)), this, SLOT(removeEnvironmentButtonClicked())); connect(d->m_unsetButton, SIGNAL(clicked(bool)), this, SLOT(unsetEnvironmentButtonClicked())); connect(d->m_environmentView->selectionModel(), SIGNAL(currentChanged(QModelIndex,QModelIndex)), this, SLOT(environmentCurrentIndexChanged(QModelIndex))); connect(d->m_model, SIGNAL(userChangesChanged()), this, SLOT(updateSummaryText())); } EnvironmentWidget::~EnvironmentWidget() { delete d->m_model; d->m_model = 0; } void EnvironmentWidget::focusIndex(const QModelIndex &index) { d->m_environmentView->setCurrentIndex(index); d->m_environmentView->setFocus(); } void EnvironmentWidget::setBaseEnvironment(const Utils::Environment &env) { d->m_model->setBaseEnvironment(env); } void EnvironmentWidget::setBaseEnvironmentText(const QString &text) { d->m_baseEnvironmentText = text; updateSummaryText(); } QList<Utils::EnvironmentItem> EnvironmentWidget::userChanges() const { return d->m_model->userChanges(); } void EnvironmentWidget::setUserChanges(const QList<Utils::EnvironmentItem> &list) { d->m_model->setUserChanges(list); updateSummaryText(); } void EnvironmentWidget::updateSummaryText() { QString text; const QList<Utils::EnvironmentItem> &list = d->m_model->userChanges(); foreach (const Utils::EnvironmentItem &item, list) { if (item.name != Utils::EnvironmentModel::tr("<VARIABLE>")) { text.append("<br>"); if (item.unset) text.append(tr("Unset <b>%1</b>").arg(Qt::escape(item.name))); else text.append(tr("Set <b>%1</b> to <b>%2</b>").arg(Qt::escape(item.name), Qt::escape(item.value))); } } if (text.isEmpty()) text.prepend(tr("Using <b>%1</b>").arg(d->m_baseEnvironmentText)); else text.prepend(tr("Using <b>%1</b> and").arg(d->m_baseEnvironmentText)); d->m_detailsContainer->setSummaryText(text); } void EnvironmentWidget::updateButtons() { environmentCurrentIndexChanged(d->m_environmentView->currentIndex()); } void EnvironmentWidget::editEnvironmentButtonClicked() { d->m_environmentView->edit(d->m_environmentView->currentIndex()); } void EnvironmentWidget::addEnvironmentButtonClicked() { QModelIndex index = d->m_model->addVariable(); d->m_environmentView->setCurrentIndex(index); d->m_environmentView->edit(index); } void EnvironmentWidget::removeEnvironmentButtonClicked() { const QString &name = d->m_model->indexToVariable(d->m_environmentView->currentIndex()); d->m_model->resetVariable(name); } // unset in Merged Environment Mode means, unset if it comes from the base environment // or remove when it is just a change we added void EnvironmentWidget::unsetEnvironmentButtonClicked() { const QString &name = d->m_model->indexToVariable(d->m_environmentView->currentIndex()); if (!d->m_model->canReset(name)) d->m_model->resetVariable(name); else d->m_model->unsetVariable(name); } void EnvironmentWidget::environmentCurrentIndexChanged(const QModelIndex &current) { if (current.isValid()) { d->m_editButton->setEnabled(true); const QString &name = d->m_model->indexToVariable(current); bool modified = d->m_model->canReset(name) && d->m_model->changes(name); bool unset = d->m_model->canUnset(name); d->m_resetButton->setEnabled(modified || unset); d->m_unsetButton->setEnabled(!unset); } else { d->m_editButton->setEnabled(false); d->m_resetButton->setEnabled(false); d->m_unsetButton->setEnabled(false); } } void EnvironmentWidget::invalidateCurrentIndex() { environmentCurrentIndexChanged(QModelIndex()); } } // namespace ProjectExplorer <commit_msg>EnvironmentWidget: Sort the changes<commit_after>/************************************************************************** ** ** This file is part of Qt Creator ** ** Copyright (c) 2011 Nokia Corporation and/or its subsidiary(-ies). ** ** Contact: Nokia Corporation ([email protected]) ** ** No Commercial Usage ** ** This file contains pre-release code and may not be distributed. ** You may use this file in accordance with the terms and conditions ** contained in the Technology Preview License Agreement accompanying ** this package. ** ** 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, 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. ** ** If you have questions regarding the use of this file, please contact ** Nokia at [email protected]. ** **************************************************************************/ #include "environmentwidget.h" #include <utils/detailswidget.h> #include <utils/environment.h> #include <utils/environmentmodel.h> #include <QtCore/QString> #include <QtGui/QHeaderView> #include <QtGui/QPushButton> #include <QtGui/QTableView> #include <QtGui/QTextDocument> // for Qt::escape #include <QtGui/QVBoxLayout> namespace ProjectExplorer { //// // EnvironmentWidget::EnvironmentWidget //// class EnvironmentWidgetPrivate { public: Utils::EnvironmentModel *m_model; QString m_baseEnvironmentText; Utils::DetailsWidget *m_detailsContainer; QTableView *m_environmentView; QPushButton *m_editButton; QPushButton *m_addButton; QPushButton *m_resetButton; QPushButton *m_unsetButton; }; EnvironmentWidget::EnvironmentWidget(QWidget *parent, QWidget *additionalDetailsWidget) : QWidget(parent), d(new EnvironmentWidgetPrivate) { d->m_model = new Utils::EnvironmentModel(); connect(d->m_model, SIGNAL(userChangesChanged()), this, SIGNAL(userChangesChanged())); connect(d->m_model, SIGNAL(modelReset()), this, SLOT(invalidateCurrentIndex())); connect(d->m_model, SIGNAL(focusIndex(QModelIndex)), this, SLOT(focusIndex(QModelIndex))); QVBoxLayout *vbox = new QVBoxLayout(this); vbox->setContentsMargins(0, 0, 0, 0); d->m_detailsContainer = new Utils::DetailsWidget(this); QWidget *details = new QWidget(d->m_detailsContainer); d->m_detailsContainer->setWidget(details); details->setVisible(false); QVBoxLayout *vbox2 = new QVBoxLayout(details); vbox2->setMargin(0); if (additionalDetailsWidget) vbox2->addWidget(additionalDetailsWidget); QHBoxLayout *horizontalLayout = new QHBoxLayout(); horizontalLayout->setMargin(0); d->m_environmentView = new QTableView(this); d->m_environmentView->setModel(d->m_model); d->m_environmentView->setMinimumHeight(400); d->m_environmentView->setGridStyle(Qt::NoPen); d->m_environmentView->horizontalHeader()->setStretchLastSection(true); d->m_environmentView->horizontalHeader()->setResizeMode(0, QHeaderView::ResizeToContents); d->m_environmentView->horizontalHeader()->setHighlightSections(false); d->m_environmentView->verticalHeader()->hide(); QFontMetrics fm(font()); d->m_environmentView->verticalHeader()->setDefaultSectionSize(qMax(static_cast<int>(fm.height() * 1.2), fm.height() + 4)); d->m_environmentView->setSelectionMode(QAbstractItemView::SingleSelection); horizontalLayout->addWidget(d->m_environmentView); QVBoxLayout *buttonLayout = new QVBoxLayout(); d->m_editButton = new QPushButton(this); d->m_editButton->setText(tr("&Edit")); buttonLayout->addWidget(d->m_editButton); d->m_addButton = new QPushButton(this); d->m_addButton->setText(tr("&Add")); buttonLayout->addWidget(d->m_addButton); d->m_resetButton = new QPushButton(this); d->m_resetButton->setEnabled(false); d->m_resetButton->setText(tr("&Reset")); buttonLayout->addWidget(d->m_resetButton); d->m_unsetButton = new QPushButton(this); d->m_unsetButton->setEnabled(false); d->m_unsetButton->setText(tr("&Unset")); buttonLayout->addWidget(d->m_unsetButton); QSpacerItem *verticalSpacer = new QSpacerItem(20, 40, QSizePolicy::Minimum, QSizePolicy::Expanding); buttonLayout->addItem(verticalSpacer); horizontalLayout->addLayout(buttonLayout); vbox2->addLayout(horizontalLayout); vbox->addWidget(d->m_detailsContainer); connect(d->m_model, SIGNAL(dataChanged(const QModelIndex&, const QModelIndex&)), this, SLOT(updateButtons())); connect(d->m_editButton, SIGNAL(clicked(bool)), this, SLOT(editEnvironmentButtonClicked())); connect(d->m_addButton, SIGNAL(clicked(bool)), this, SLOT(addEnvironmentButtonClicked())); connect(d->m_resetButton, SIGNAL(clicked(bool)), this, SLOT(removeEnvironmentButtonClicked())); connect(d->m_unsetButton, SIGNAL(clicked(bool)), this, SLOT(unsetEnvironmentButtonClicked())); connect(d->m_environmentView->selectionModel(), SIGNAL(currentChanged(QModelIndex,QModelIndex)), this, SLOT(environmentCurrentIndexChanged(QModelIndex))); connect(d->m_model, SIGNAL(userChangesChanged()), this, SLOT(updateSummaryText())); } EnvironmentWidget::~EnvironmentWidget() { delete d->m_model; d->m_model = 0; } void EnvironmentWidget::focusIndex(const QModelIndex &index) { d->m_environmentView->setCurrentIndex(index); d->m_environmentView->setFocus(); } void EnvironmentWidget::setBaseEnvironment(const Utils::Environment &env) { d->m_model->setBaseEnvironment(env); } void EnvironmentWidget::setBaseEnvironmentText(const QString &text) { d->m_baseEnvironmentText = text; updateSummaryText(); } QList<Utils::EnvironmentItem> EnvironmentWidget::userChanges() const { return d->m_model->userChanges(); } void EnvironmentWidget::setUserChanges(const QList<Utils::EnvironmentItem> &list) { d->m_model->setUserChanges(list); updateSummaryText(); } bool sortEnvironmentItem(const Utils::EnvironmentItem &a, const Utils::EnvironmentItem &b) { return a.name < b.name; } void EnvironmentWidget::updateSummaryText() { QList<Utils::EnvironmentItem> list = d->m_model->userChanges(); qSort(list.begin(), list.end(), &sortEnvironmentItem); QString text; foreach (const Utils::EnvironmentItem &item, list) { if (item.name != Utils::EnvironmentModel::tr("<VARIABLE>")) { text.append("<br>"); if (item.unset) text.append(tr("Unset <b>%1</b>").arg(Qt::escape(item.name))); else text.append(tr("Set <b>%1</b> to <b>%2</b>").arg(Qt::escape(item.name), Qt::escape(item.value))); } } if (text.isEmpty()) text.prepend(tr("Using <b>%1</b>").arg(d->m_baseEnvironmentText)); else text.prepend(tr("Using <b>%1</b> and").arg(d->m_baseEnvironmentText)); d->m_detailsContainer->setSummaryText(text); } void EnvironmentWidget::updateButtons() { environmentCurrentIndexChanged(d->m_environmentView->currentIndex()); } void EnvironmentWidget::editEnvironmentButtonClicked() { d->m_environmentView->edit(d->m_environmentView->currentIndex()); } void EnvironmentWidget::addEnvironmentButtonClicked() { QModelIndex index = d->m_model->addVariable(); d->m_environmentView->setCurrentIndex(index); d->m_environmentView->edit(index); } void EnvironmentWidget::removeEnvironmentButtonClicked() { const QString &name = d->m_model->indexToVariable(d->m_environmentView->currentIndex()); d->m_model->resetVariable(name); } // unset in Merged Environment Mode means, unset if it comes from the base environment // or remove when it is just a change we added void EnvironmentWidget::unsetEnvironmentButtonClicked() { const QString &name = d->m_model->indexToVariable(d->m_environmentView->currentIndex()); if (!d->m_model->canReset(name)) d->m_model->resetVariable(name); else d->m_model->unsetVariable(name); } void EnvironmentWidget::environmentCurrentIndexChanged(const QModelIndex &current) { if (current.isValid()) { d->m_editButton->setEnabled(true); const QString &name = d->m_model->indexToVariable(current); bool modified = d->m_model->canReset(name) && d->m_model->changes(name); bool unset = d->m_model->canUnset(name); d->m_resetButton->setEnabled(modified || unset); d->m_unsetButton->setEnabled(!unset); } else { d->m_editButton->setEnabled(false); d->m_resetButton->setEnabled(false); d->m_unsetButton->setEnabled(false); } } void EnvironmentWidget::invalidateCurrentIndex() { environmentCurrentIndexChanged(QModelIndex()); } } // namespace ProjectExplorer <|endoftext|>
<commit_before>// // This file is part of the Marble Virtual Globe. // // This program is free software licensed under the GNU LGPL. You can // find a copy of this license in LICENSE.txt in the top directory of // the source code. // // Copyright 2013 Mohammed Nafees <[email protected]> // #include "ArrowDiscWidget.h" #include "MarbleWidget.h" #include <QtGui/QPainter> #include <QtGui/QMouseEvent> #include <QtGui/QPixmapCache> #include <QtGui/QPainterPath> namespace Marble { ArrowDiscWidget::ArrowDiscWidget( QWidget *parent ) : QWidget( parent ), m_arrowPressed( Qt::NoArrow ), m_repetitions( 0 ), m_marbleWidget( 0 ), m_imagePath( "marble/navigation/navigational_arrows" ) { setMouseTracking( true ); m_initialPressTimer.setSingleShot( true ); connect( &m_initialPressTimer, SIGNAL(timeout()), SLOT(startPressRepeat()) ); connect( &m_repeatPressTimer, SIGNAL(timeout()), SLOT(repeatPress()) ); } ArrowDiscWidget::~ArrowDiscWidget() { QPixmapCache::remove( "marble/navigation/navigational_arrows" ); QPixmapCache::remove( "marble/navigation/navigational_arrows_hover_bottom" ); QPixmapCache::remove( "marble/navigation/navigational_arrows_hover_left" ); QPixmapCache::remove( "marble/navigation/navigational_arrows_hover_right" ); QPixmapCache::remove( "marble/navigation/navigational_arrows_hover_top" ); QPixmapCache::remove( "marble/navigation/navigational_arrows_press_bottom" ); QPixmapCache::remove( "marble/navigation/navigational_arrows_press_left" ); QPixmapCache::remove( "marble/navigation/navigational_arrows_press_right" ); QPixmapCache::remove( "marble/navigation/navigational_arrows_press_top" ); } void ArrowDiscWidget::setMarbleWidget( MarbleWidget *marbleWidget ) { m_marbleWidget = marbleWidget; } QPixmap ArrowDiscWidget::pixmap( const QString &id ) { QPixmap result; if ( !QPixmapCache::find( id, result ) ) { result = QPixmap( QString( ":/%1.png" ).arg( id ) ); QPixmapCache::insert( id, result ); } return result; } void ArrowDiscWidget::mousePressEvent( QMouseEvent *mouseEvent ) { if ( mouseEvent->button() == Qt::LeftButton ) { if ( !m_initialPressTimer.isActive() && !m_repeatPressTimer.isActive() ) { m_repetitions = 0; m_initialPressTimer.start( 300 ); } m_arrowPressed = arrowUnderMouse( mouseEvent->pos() ); switch ( m_arrowPressed ) { case Qt::NoArrow: m_imagePath = "marble/navigation/navigational_arrows"; break; case Qt::UpArrow: m_imagePath = "marble/navigation/navigational_arrows_press_top"; m_marbleWidget->moveUp(); break; case Qt::DownArrow: m_imagePath = "marble/navigation/navigational_arrows_press_bottom"; m_marbleWidget->moveDown(); break; case Qt::LeftArrow: m_imagePath = "marble/navigation/navigational_arrows_press_left"; m_marbleWidget->moveLeft(); break; case Qt::RightArrow: m_imagePath = "marble/navigation/navigational_arrows_press_right"; m_marbleWidget->moveRight(); break; } } repaint(); } void ArrowDiscWidget::mouseReleaseEvent( QMouseEvent *mouseEvent ) { m_initialPressTimer.stop(); m_repeatPressTimer.stop(); mouseMoveEvent( mouseEvent ); } void ArrowDiscWidget::leaveEvent( QEvent* ) { if ( m_imagePath != "marble/navigation/navigational_arrows" ) { m_imagePath = "marble/navigation/navigational_arrows"; repaint(); } } void ArrowDiscWidget::startPressRepeat() { repeatPress(); if ( m_arrowPressed != Qt::NoArrow ) { m_repeatPressTimer.start( 100 ); } } void ArrowDiscWidget::repeatPress() { if ( m_repetitions <= 200 ) { ++m_repetitions; switch ( m_arrowPressed ) { case Qt::NoArrow: break; case Qt::UpArrow: m_marbleWidget->moveUp(); break; case Qt::DownArrow: m_marbleWidget->moveDown(); break; case Qt::LeftArrow: m_marbleWidget->moveLeft(); break; case Qt::RightArrow: m_marbleWidget->moveRight(); break; } } else { m_repeatPressTimer.stop(); } } void ArrowDiscWidget::mouseMoveEvent( QMouseEvent *mouseEvent ) { QString const oldPath = m_imagePath; switch ( arrowUnderMouse( mouseEvent->pos() ) ) { case Qt::NoArrow: m_imagePath = "marble/navigation/navigational_arrows"; break; case Qt::UpArrow: m_imagePath = "marble/navigation/navigational_arrows_hover_top"; m_arrowPressed = Qt::UpArrow; break; case Qt::DownArrow: m_imagePath = "marble/navigation/navigational_arrows_hover_bottom"; m_arrowPressed = Qt::DownArrow; break; case Qt::LeftArrow: m_imagePath = "marble/navigation/navigational_arrows_hover_left"; m_arrowPressed = Qt::LeftArrow; break; case Qt::RightArrow: m_imagePath = "marble/navigation/navigational_arrows_hover_right"; m_arrowPressed = Qt::RightArrow; break; } if ( m_imagePath != oldPath ) { repaint(); } } void ArrowDiscWidget::repaint() { emit repaintNeeded(); } Qt::ArrowType ArrowDiscWidget::arrowUnderMouse(const QPoint &position) const { const int min_radius_pow2 = 5*5; const int max_radius_pow2 = 28*28; // mouse coordinates relative to widget topleft int mx = position.x(); int my = position.y(); // center coordinates relative to widget topleft int cx = width()/2; int cy = height()/2; int px = mx - cx; int py = my - cy; int const distance_pow2 = px*px + py*py; if ( distance_pow2 >= min_radius_pow2 && distance_pow2 <= max_radius_pow2 ) { int const angle = int( atan2( py, px ) * RAD2DEG ); Q_ASSERT( -180 <= angle && angle <= 180 ); if ( angle >= 135 || angle < -135 ) { return Qt::LeftArrow; } else if ( angle < -45 ) { return Qt::UpArrow; } else if ( angle < 45 ) { return Qt::RightArrow; } else { return Qt::DownArrow; } } return Qt::NoArrow; } void ArrowDiscWidget::paintEvent( QPaintEvent * ) { Q_ASSERT( !pixmap( m_imagePath ).isNull() ); QPainter painter( this ); painter.drawPixmap( 0, 0, pixmap( m_imagePath ) ); painter.end(); } } #include "ArrowDiscWidget.moc" <commit_msg>Leaving the widget stops press repeats.<commit_after>// // This file is part of the Marble Virtual Globe. // // This program is free software licensed under the GNU LGPL. You can // find a copy of this license in LICENSE.txt in the top directory of // the source code. // // Copyright 2013 Mohammed Nafees <[email protected]> // #include "ArrowDiscWidget.h" #include "MarbleWidget.h" #include <QtGui/QPainter> #include <QtGui/QMouseEvent> #include <QtGui/QPixmapCache> #include <QtGui/QPainterPath> namespace Marble { ArrowDiscWidget::ArrowDiscWidget( QWidget *parent ) : QWidget( parent ), m_arrowPressed( Qt::NoArrow ), m_repetitions( 0 ), m_marbleWidget( 0 ), m_imagePath( "marble/navigation/navigational_arrows" ) { setMouseTracking( true ); m_initialPressTimer.setSingleShot( true ); connect( &m_initialPressTimer, SIGNAL(timeout()), SLOT(startPressRepeat()) ); connect( &m_repeatPressTimer, SIGNAL(timeout()), SLOT(repeatPress()) ); } ArrowDiscWidget::~ArrowDiscWidget() { QPixmapCache::remove( "marble/navigation/navigational_arrows" ); QPixmapCache::remove( "marble/navigation/navigational_arrows_hover_bottom" ); QPixmapCache::remove( "marble/navigation/navigational_arrows_hover_left" ); QPixmapCache::remove( "marble/navigation/navigational_arrows_hover_right" ); QPixmapCache::remove( "marble/navigation/navigational_arrows_hover_top" ); QPixmapCache::remove( "marble/navigation/navigational_arrows_press_bottom" ); QPixmapCache::remove( "marble/navigation/navigational_arrows_press_left" ); QPixmapCache::remove( "marble/navigation/navigational_arrows_press_right" ); QPixmapCache::remove( "marble/navigation/navigational_arrows_press_top" ); } void ArrowDiscWidget::setMarbleWidget( MarbleWidget *marbleWidget ) { m_marbleWidget = marbleWidget; } QPixmap ArrowDiscWidget::pixmap( const QString &id ) { QPixmap result; if ( !QPixmapCache::find( id, result ) ) { result = QPixmap( QString( ":/%1.png" ).arg( id ) ); QPixmapCache::insert( id, result ); } return result; } void ArrowDiscWidget::mousePressEvent( QMouseEvent *mouseEvent ) { if ( mouseEvent->button() == Qt::LeftButton ) { if ( !m_initialPressTimer.isActive() && !m_repeatPressTimer.isActive() ) { m_repetitions = 0; m_initialPressTimer.start( 300 ); } m_arrowPressed = arrowUnderMouse( mouseEvent->pos() ); switch ( m_arrowPressed ) { case Qt::NoArrow: m_imagePath = "marble/navigation/navigational_arrows"; break; case Qt::UpArrow: m_imagePath = "marble/navigation/navigational_arrows_press_top"; m_marbleWidget->moveUp(); break; case Qt::DownArrow: m_imagePath = "marble/navigation/navigational_arrows_press_bottom"; m_marbleWidget->moveDown(); break; case Qt::LeftArrow: m_imagePath = "marble/navigation/navigational_arrows_press_left"; m_marbleWidget->moveLeft(); break; case Qt::RightArrow: m_imagePath = "marble/navigation/navigational_arrows_press_right"; m_marbleWidget->moveRight(); break; } } repaint(); } void ArrowDiscWidget::mouseReleaseEvent( QMouseEvent *mouseEvent ) { m_initialPressTimer.stop(); m_repeatPressTimer.stop(); mouseMoveEvent( mouseEvent ); } void ArrowDiscWidget::leaveEvent( QEvent* ) { if ( m_imagePath != "marble/navigation/navigational_arrows" ) { m_imagePath = "marble/navigation/navigational_arrows"; repaint(); } m_initialPressTimer.stop(); m_repeatPressTimer.stop(); } void ArrowDiscWidget::startPressRepeat() { repeatPress(); if ( m_arrowPressed != Qt::NoArrow ) { m_repeatPressTimer.start( 100 ); } } void ArrowDiscWidget::repeatPress() { if ( m_repetitions <= 200 ) { ++m_repetitions; switch ( m_arrowPressed ) { case Qt::NoArrow: break; case Qt::UpArrow: m_marbleWidget->moveUp(); break; case Qt::DownArrow: m_marbleWidget->moveDown(); break; case Qt::LeftArrow: m_marbleWidget->moveLeft(); break; case Qt::RightArrow: m_marbleWidget->moveRight(); break; } } else { m_repeatPressTimer.stop(); } } void ArrowDiscWidget::mouseMoveEvent( QMouseEvent *mouseEvent ) { QString const oldPath = m_imagePath; switch ( arrowUnderMouse( mouseEvent->pos() ) ) { case Qt::NoArrow: m_imagePath = "marble/navigation/navigational_arrows"; break; case Qt::UpArrow: m_imagePath = "marble/navigation/navigational_arrows_hover_top"; m_arrowPressed = Qt::UpArrow; break; case Qt::DownArrow: m_imagePath = "marble/navigation/navigational_arrows_hover_bottom"; m_arrowPressed = Qt::DownArrow; break; case Qt::LeftArrow: m_imagePath = "marble/navigation/navigational_arrows_hover_left"; m_arrowPressed = Qt::LeftArrow; break; case Qt::RightArrow: m_imagePath = "marble/navigation/navigational_arrows_hover_right"; m_arrowPressed = Qt::RightArrow; break; } if ( m_imagePath != oldPath ) { repaint(); } } void ArrowDiscWidget::repaint() { emit repaintNeeded(); } Qt::ArrowType ArrowDiscWidget::arrowUnderMouse(const QPoint &position) const { const int min_radius_pow2 = 5*5; const int max_radius_pow2 = 28*28; // mouse coordinates relative to widget topleft int mx = position.x(); int my = position.y(); // center coordinates relative to widget topleft int cx = width()/2; int cy = height()/2; int px = mx - cx; int py = my - cy; int const distance_pow2 = px*px + py*py; if ( distance_pow2 >= min_radius_pow2 && distance_pow2 <= max_radius_pow2 ) { int const angle = int( atan2( py, px ) * RAD2DEG ); Q_ASSERT( -180 <= angle && angle <= 180 ); if ( angle >= 135 || angle < -135 ) { return Qt::LeftArrow; } else if ( angle < -45 ) { return Qt::UpArrow; } else if ( angle < 45 ) { return Qt::RightArrow; } else { return Qt::DownArrow; } } return Qt::NoArrow; } void ArrowDiscWidget::paintEvent( QPaintEvent * ) { Q_ASSERT( !pixmap( m_imagePath ).isNull() ); QPainter painter( this ); painter.drawPixmap( 0, 0, pixmap( m_imagePath ) ); painter.end(); } } #include "ArrowDiscWidget.moc" <|endoftext|>
<commit_before>/************************************************************************** ** ** This file is part of Qt Creator ** ** Copyright (c) 2011 Nokia Corporation and/or its subsidiary(-ies). ** ** Contact: Nokia Corporation ([email protected]) ** ** ** 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 [email protected]. ** **************************************************************************/ #include "snippeteditor.h" #include <texteditor/basetextdocument.h> #include <texteditor/texteditorconstants.h> #include <texteditor/normalindenter.h> #include <QtGui/QTextDocument> #include <QtGui/QFocusEvent> using namespace TextEditor; /*! \class TextEditor::SnippetEditorWidget \brief The SnippetEditorWidget class is a lightweight editor for code snippets with basic support for syntax highlighting, indentation, and others. \ingroup Snippets */ SnippetEditor::SnippetEditor(SnippetEditorWidget *editor) : BaseTextEditor(editor) { setContext(Core::Context(Constants::SNIPPET_EDITOR_ID, Constants::C_TEXTEDITOR)); } QString SnippetEditor::id() const { return Constants::SNIPPET_EDITOR_ID; } SnippetEditorWidget::SnippetEditorWidget(QWidget *parent) : BaseTextEditorWidget(parent) { setFrameStyle(QFrame::StyledPanel | QFrame::Sunken); setHighlightCurrentLine(false); setLineNumbersVisible(false); setParenthesesMatchingEnabled(true); } void SnippetEditorWidget::setSyntaxHighlighter(TextEditor::SyntaxHighlighter *highlighter) { baseTextDocument()->setSyntaxHighlighter(highlighter); } void SnippetEditorWidget::focusOutEvent(QFocusEvent *event) { if (event->reason() != Qt::ActiveWindowFocusReason && document()->isModified()) { document()->setModified(false); emit snippetContentChanged(); } } BaseTextEditor *SnippetEditorWidget::createEditor() { return new SnippetEditor(this); } <commit_msg>Pass focusOutEvent to the superclass<commit_after>/************************************************************************** ** ** This file is part of Qt Creator ** ** Copyright (c) 2011 Nokia Corporation and/or its subsidiary(-ies). ** ** Contact: Nokia Corporation ([email protected]) ** ** ** 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 [email protected]. ** **************************************************************************/ #include "snippeteditor.h" #include <texteditor/basetextdocument.h> #include <texteditor/texteditorconstants.h> #include <texteditor/normalindenter.h> #include <QtGui/QTextDocument> #include <QtGui/QFocusEvent> using namespace TextEditor; /*! \class TextEditor::SnippetEditorWidget \brief The SnippetEditorWidget class is a lightweight editor for code snippets with basic support for syntax highlighting, indentation, and others. \ingroup Snippets */ SnippetEditor::SnippetEditor(SnippetEditorWidget *editor) : BaseTextEditor(editor) { setContext(Core::Context(Constants::SNIPPET_EDITOR_ID, Constants::C_TEXTEDITOR)); } QString SnippetEditor::id() const { return Constants::SNIPPET_EDITOR_ID; } SnippetEditorWidget::SnippetEditorWidget(QWidget *parent) : BaseTextEditorWidget(parent) { setFrameStyle(QFrame::StyledPanel | QFrame::Sunken); setHighlightCurrentLine(false); setLineNumbersVisible(false); setParenthesesMatchingEnabled(true); } void SnippetEditorWidget::setSyntaxHighlighter(TextEditor::SyntaxHighlighter *highlighter) { baseTextDocument()->setSyntaxHighlighter(highlighter); } void SnippetEditorWidget::focusOutEvent(QFocusEvent *event) { if (event->reason() != Qt::ActiveWindowFocusReason && document()->isModified()) { document()->setModified(false); emit snippetContentChanged(); } BaseTextEditorWidget::focusOutEvent(event); } BaseTextEditor *SnippetEditorWidget::createEditor() { return new SnippetEditor(this); } <|endoftext|>
<commit_before>/**************************************************************************** ** ** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies). ** Contact: http://www.qt-project.org/ ** ** This file is part of the QtQml module of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** 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. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU General ** Public License version 3.0 as published by the Free Software Foundation ** and appearing in the file LICENSE.GPL included in the packaging of this ** file. Please review the following information to ensure the GNU General ** Public License version 3.0 requirements will be met: ** http://www.gnu.org/copyleft/gpl.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 Nokia. ** ** ** ** ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "private/qparallelanimationgroupjob_p.h" #include "private/qanimationjobutil_p.h" QT_BEGIN_NAMESPACE QParallelAnimationGroupJob::QParallelAnimationGroupJob() : QAnimationGroupJob() , m_previousLoop(0) , m_previousCurrentTime(0) { } QParallelAnimationGroupJob::~QParallelAnimationGroupJob() { } int QParallelAnimationGroupJob::duration() const { int ret = 0; for (QAbstractAnimationJob *animation = firstChild(); animation; animation = animation->nextSibling()) { int currentDuration = animation->totalDuration(); //this takes care of the case where a parallel animation group has controlled and uncontrolled //animations, and the uncontrolled stop before the controlled if (currentDuration == -1) currentDuration = uncontrolledAnimationFinishTime(animation); if (currentDuration == -1) return -1; // Undetermined length ret = qMax(ret, currentDuration); } return ret; } void QParallelAnimationGroupJob::updateCurrentTime(int /*currentTime*/) { if (!firstChild()) return; if (m_currentLoop > m_previousLoop) { // simulate completion of the loop int dura = duration(); if (dura > 0) { for (QAbstractAnimationJob *animation = firstChild(); animation; animation = animation->nextSibling()) { if (!animation->isStopped()) RETURN_IF_DELETED(animation->setCurrentTime(dura)); // will stop } } } else if (m_currentLoop < m_previousLoop) { // simulate completion of the loop seeking backwards for (QAbstractAnimationJob *animation = firstChild(); animation; animation = animation->nextSibling()) { //we need to make sure the animation is in the right state //and then rewind it applyGroupState(animation); RETURN_IF_DELETED(animation->setCurrentTime(0)); animation->stop(); } } // finally move into the actual time of the current loop for (QAbstractAnimationJob *animation = firstChild(); animation; animation = animation->nextSibling()) { const int dura = animation->totalDuration(); //if the loopcount is bigger we should always start all animations if (m_currentLoop > m_previousLoop //if we're at the end of the animation, we need to start it if it wasn't already started in this loop //this happens in Backward direction where not all animations are started at the same time || shouldAnimationStart(animation, m_previousCurrentTime > dura /*startIfAtEnd*/)) { applyGroupState(animation); } if (animation->state() == state()) { RETURN_IF_DELETED(animation->setCurrentTime(m_currentTime)); if (dura > 0 && m_currentTime > dura) animation->stop(); } } m_previousLoop = m_currentLoop; m_previousCurrentTime = m_currentTime; } void QParallelAnimationGroupJob::updateState(QAbstractAnimationJob::State newState, QAbstractAnimationJob::State oldState) { QAnimationGroupJob::updateState(newState, oldState); switch (newState) { case Stopped: for (QAbstractAnimationJob *animation = firstChild(); animation; animation = animation->nextSibling()) animation->stop(); break; case Paused: for (QAbstractAnimationJob *animation = firstChild(); animation; animation = animation->nextSibling()) if (animation->isRunning()) animation->pause(); break; case Running: for (QAbstractAnimationJob *animation = firstChild(); animation; animation = animation->nextSibling()) { if (oldState == Stopped) animation->stop(); resetUncontrolledAnimationFinishTime(animation); animation->setDirection(m_direction); if (shouldAnimationStart(animation, oldState == Stopped)) animation->start(); } break; } } bool QParallelAnimationGroupJob::shouldAnimationStart(QAbstractAnimationJob *animation, bool startIfAtEnd) const { const int dura = animation->totalDuration(); if (dura == -1) return uncontrolledAnimationFinishTime(animation) == -1; if (startIfAtEnd) return m_currentTime <= dura; if (m_direction == Forward) return m_currentTime < dura; else //direction == Backward return m_currentTime && m_currentTime <= dura; } void QParallelAnimationGroupJob::applyGroupState(QAbstractAnimationJob *animation) { switch (m_state) { case Running: animation->start(); break; case Paused: animation->pause(); break; case Stopped: default: break; } } void QParallelAnimationGroupJob::updateDirection(QAbstractAnimationJob::Direction direction) { //we need to update the direction of the current animation if (!isStopped()) { for (QAbstractAnimationJob *animation = firstChild(); animation; animation = animation->nextSibling()) { animation->setDirection(direction); } } else { if (direction == Forward) { m_previousLoop = 0; m_previousCurrentTime = 0; } else { // Looping backwards with loopCount == -1 does not really work well... m_previousLoop = (m_loopCount == -1 ? 0 : m_loopCount - 1); m_previousCurrentTime = duration(); } } } void QParallelAnimationGroupJob::uncontrolledAnimationFinished(QAbstractAnimationJob *animation) { Q_ASSERT(animation && (animation->duration() == -1 || animation->loopCount() < 0)); int uncontrolledRunningCount = 0; for (QAbstractAnimationJob *child = firstChild(); child; child = child->nextSibling()) { if (child == animation) { setUncontrolledAnimationFinishTime(animation, animation->currentTime()); } else if (child->duration() == -1 || child->loopCount() < 0) { if (uncontrolledAnimationFinishTime(child) == -1) ++uncontrolledRunningCount; } } if (uncontrolledRunningCount > 0) return; int maxDuration = 0; for (QAbstractAnimationJob *animation = firstChild(); animation; animation = animation->nextSibling()) maxDuration = qMax(maxDuration, animation->totalDuration()); if (m_currentTime >= maxDuration) stop(); } QT_END_NAMESPACE <commit_msg>Avoid using previously declared variables<commit_after>/**************************************************************************** ** ** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies). ** Contact: http://www.qt-project.org/ ** ** This file is part of the QtQml module of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** 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. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU General ** Public License version 3.0 as published by the Free Software Foundation ** and appearing in the file LICENSE.GPL included in the packaging of this ** file. Please review the following information to ensure the GNU General ** Public License version 3.0 requirements will be met: ** http://www.gnu.org/copyleft/gpl.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 Nokia. ** ** ** ** ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "private/qparallelanimationgroupjob_p.h" #include "private/qanimationjobutil_p.h" QT_BEGIN_NAMESPACE QParallelAnimationGroupJob::QParallelAnimationGroupJob() : QAnimationGroupJob() , m_previousLoop(0) , m_previousCurrentTime(0) { } QParallelAnimationGroupJob::~QParallelAnimationGroupJob() { } int QParallelAnimationGroupJob::duration() const { int ret = 0; for (QAbstractAnimationJob *animation = firstChild(); animation; animation = animation->nextSibling()) { int currentDuration = animation->totalDuration(); //this takes care of the case where a parallel animation group has controlled and uncontrolled //animations, and the uncontrolled stop before the controlled if (currentDuration == -1) currentDuration = uncontrolledAnimationFinishTime(animation); if (currentDuration == -1) return -1; // Undetermined length ret = qMax(ret, currentDuration); } return ret; } void QParallelAnimationGroupJob::updateCurrentTime(int /*currentTime*/) { if (!firstChild()) return; if (m_currentLoop > m_previousLoop) { // simulate completion of the loop int dura = duration(); if (dura > 0) { for (QAbstractAnimationJob *animation = firstChild(); animation; animation = animation->nextSibling()) { if (!animation->isStopped()) RETURN_IF_DELETED(animation->setCurrentTime(dura)); // will stop } } } else if (m_currentLoop < m_previousLoop) { // simulate completion of the loop seeking backwards for (QAbstractAnimationJob *animation = firstChild(); animation; animation = animation->nextSibling()) { //we need to make sure the animation is in the right state //and then rewind it applyGroupState(animation); RETURN_IF_DELETED(animation->setCurrentTime(0)); animation->stop(); } } // finally move into the actual time of the current loop for (QAbstractAnimationJob *animation = firstChild(); animation; animation = animation->nextSibling()) { const int dura = animation->totalDuration(); //if the loopcount is bigger we should always start all animations if (m_currentLoop > m_previousLoop //if we're at the end of the animation, we need to start it if it wasn't already started in this loop //this happens in Backward direction where not all animations are started at the same time || shouldAnimationStart(animation, m_previousCurrentTime > dura /*startIfAtEnd*/)) { applyGroupState(animation); } if (animation->state() == state()) { RETURN_IF_DELETED(animation->setCurrentTime(m_currentTime)); if (dura > 0 && m_currentTime > dura) animation->stop(); } } m_previousLoop = m_currentLoop; m_previousCurrentTime = m_currentTime; } void QParallelAnimationGroupJob::updateState(QAbstractAnimationJob::State newState, QAbstractAnimationJob::State oldState) { QAnimationGroupJob::updateState(newState, oldState); switch (newState) { case Stopped: for (QAbstractAnimationJob *animation = firstChild(); animation; animation = animation->nextSibling()) animation->stop(); break; case Paused: for (QAbstractAnimationJob *animation = firstChild(); animation; animation = animation->nextSibling()) if (animation->isRunning()) animation->pause(); break; case Running: for (QAbstractAnimationJob *animation = firstChild(); animation; animation = animation->nextSibling()) { if (oldState == Stopped) animation->stop(); resetUncontrolledAnimationFinishTime(animation); animation->setDirection(m_direction); if (shouldAnimationStart(animation, oldState == Stopped)) animation->start(); } break; } } bool QParallelAnimationGroupJob::shouldAnimationStart(QAbstractAnimationJob *animation, bool startIfAtEnd) const { const int dura = animation->totalDuration(); if (dura == -1) return uncontrolledAnimationFinishTime(animation) == -1; if (startIfAtEnd) return m_currentTime <= dura; if (m_direction == Forward) return m_currentTime < dura; else //direction == Backward return m_currentTime && m_currentTime <= dura; } void QParallelAnimationGroupJob::applyGroupState(QAbstractAnimationJob *animation) { switch (m_state) { case Running: animation->start(); break; case Paused: animation->pause(); break; case Stopped: default: break; } } void QParallelAnimationGroupJob::updateDirection(QAbstractAnimationJob::Direction direction) { //we need to update the direction of the current animation if (!isStopped()) { for (QAbstractAnimationJob *animation = firstChild(); animation; animation = animation->nextSibling()) { animation->setDirection(direction); } } else { if (direction == Forward) { m_previousLoop = 0; m_previousCurrentTime = 0; } else { // Looping backwards with loopCount == -1 does not really work well... m_previousLoop = (m_loopCount == -1 ? 0 : m_loopCount - 1); m_previousCurrentTime = duration(); } } } void QParallelAnimationGroupJob::uncontrolledAnimationFinished(QAbstractAnimationJob *animation) { Q_ASSERT(animation && (animation->duration() == -1 || animation->loopCount() < 0)); int uncontrolledRunningCount = 0; for (QAbstractAnimationJob *child = firstChild(); child; child = child->nextSibling()) { if (child == animation) { setUncontrolledAnimationFinishTime(animation, animation->currentTime()); } else if (child->duration() == -1 || child->loopCount() < 0) { if (uncontrolledAnimationFinishTime(child) == -1) ++uncontrolledRunningCount; } } if (uncontrolledRunningCount > 0) return; int maxDuration = 0; for (QAbstractAnimationJob *job = firstChild(); job; job = job->nextSibling()) maxDuration = qMax(maxDuration, job->totalDuration()); if (m_currentTime >= maxDuration) stop(); } QT_END_NAMESPACE <|endoftext|>
<commit_before>/**************************************************************************** ** ** This file is part of QtCompositor** ** ** Copyright © 2010 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** ** Contact: Nokia Corporation [email protected] ** ** You may use this file under the terms of the BSD license as follows: ** ** 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 Nokia Corporation and its Subsidiary(-ies) nor the ** names of its contributors may be used to endorse or promote products ** derived from this software without specific prior written permission. ** ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT ** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR ** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT ** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, ** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT ** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY ** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT ** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ** ****************************************************************************/ #include "wlselection.h" #include "wlcompositor.h" #include <wayland-util.h> #include <string.h> #include <unistd.h> #include <QtCore/QFile> #include <QtCore/QSocketNotifier> namespace Wayland { void Selection::send(struct wl_client *client, struct wl_selection_offer *offer, const char *mime_type, int fd) { Q_UNUSED(client); Selection *self = instance(); if (self->m_retainedSelection) { QByteArray data = self->m_retainedData.data(QString::fromLatin1(mime_type)); if (!data.isEmpty()) { QFile f; if (f.open(fd, QIODevice::WriteOnly)) f.write(data); } } else { struct wl_selection *selection = container_of(offer, struct wl_selection, selection_offer); wl_client_post_event(selection->client, &selection->resource.object, WL_SELECTION_SEND, mime_type, fd); } close(fd); } const struct wl_selection_offer_interface Selection::selectionOfferInterface = { Selection::send }; void Selection::selOffer(struct wl_client *client, struct wl_selection *selection, const char *type) { Q_UNUSED(client); Q_UNUSED(selection); instance()->m_offerList.append(QString::fromLatin1(type)); } void Selection::selActivate(struct wl_client *client, struct wl_selection *selection, struct wl_input_device *device, uint32_t time) { Q_UNUSED(client); Q_UNUSED(device); Q_UNUSED(time); Selection *self = Selection::instance(); selection->selection_offer.object.interface = &wl_selection_offer_interface; selection->selection_offer.object.implementation = (void (**)()) &selectionOfferInterface; wl_display *dpy = Compositor::instance()->wl_display(); wl_display_add_object(dpy, &selection->selection_offer.object); wl_display_add_global(dpy, &selection->selection_offer.object, 0); QList<struct wl_client *> clients = Compositor::instance()->clients(); if (self->m_currentSelection) { if (!clients.contains(self->m_currentSelection->client)) self->m_currentSelection = 0; else wl_client_post_event(self->m_currentSelection->client, &self->m_currentSelection->resource.object, WL_SELECTION_CANCELLED); } self->m_currentSelection = selection; if (self->m_currentOffer) { foreach (struct wl_client *client, clients) { wl_client_post_event(client, &self->m_currentOffer->object, WL_SELECTION_OFFER_KEYBOARD_FOCUS, 0); } } self->m_currentOffer = &selection->selection_offer; foreach (struct wl_client *client, clients) { wl_client_post_global(client, &selection->selection_offer.object); } foreach (struct wl_client *client, clients) { foreach (const QString &mimeType, self->m_offerList) { QByteArray mimeTypeBa = mimeType.toLatin1(); wl_client_post_event(client, &selection->selection_offer.object, WL_SELECTION_OFFER_OFFER, mimeTypeBa.constData()); } } foreach (struct wl_client *client, clients) { wl_client_post_event(client, &selection->selection_offer.object, WL_SELECTION_OFFER_KEYBOARD_FOCUS, selection->input_device); } if (self->m_retainedSelectionEnabled) { self->m_retainedData.clear(); self->m_retainedReadIndex = 0; self->retain(); } } void Selection::retain() { finishReadFromClient(); if (m_retainedReadIndex >= m_offerList.count()) { if (m_watchFunc) m_watchFunc(&m_retainedData, m_watchFuncParam); return; } QString mimeType = m_offerList.at(m_retainedReadIndex); m_retainedReadBuf.clear(); QByteArray mimeTypeBa = mimeType.toLatin1(); int fd[2]; if (pipe(fd) == -1) { qWarning("Clipboard: Failed to create pipe"); return; } wl_client_post_event(m_currentSelection->client, &m_currentSelection->resource.object, WL_SELECTION_SEND, mimeTypeBa.constData(), fd[1]); close(fd[1]); m_retainedReadNotifier = new QSocketNotifier(fd[0], QSocketNotifier::Read, this); connect(m_retainedReadNotifier, SIGNAL(activated(int)), SLOT(readFromClient(int))); } void Selection::finishReadFromClient() { if (m_retainedReadNotifier) { int fd = m_retainedReadNotifier->socket(); delete m_retainedReadNotifier; m_retainedReadNotifier = 0; close(fd); } } void Selection::readFromClient(int fd) { char buf[256]; int n = read(fd, buf, sizeof buf); if (n <= 0) { finishReadFromClient(); QString mimeType = m_offerList.at(m_retainedReadIndex); m_retainedData.setData(mimeType, m_retainedReadBuf); ++m_retainedReadIndex; retain(); } else { m_retainedReadBuf.append(buf, n); } } void Selection::selDestroy(struct wl_client *client, struct wl_selection *selection) { wl_resource_destroy(&selection->resource, client, Compositor::currentTimeMsecs()); } const struct wl_selection_interface Selection::selectionInterface = { Selection::selOffer, Selection::selActivate, Selection::selDestroy }; void Selection::destroySelection(struct wl_resource *resource, struct wl_client *client) { Q_UNUSED(client); struct wl_selection *selection = container_of(resource, struct wl_selection, resource); Selection *self = Selection::instance(); wl_display *dpy = Compositor::instance()->wl_display(); if (self->m_currentSelection == selection) self->m_currentSelection = 0; if (self->m_currentOffer == &selection->selection_offer) { self->m_currentOffer = 0; if (self->m_retainedSelectionEnabled) { if (self->m_retainedSelection) { wl_display_remove_global(dpy, &self->m_retainedSelection->selection_offer.object); delete self->m_retainedSelection; } self->m_retainedSelection = selection; return; } self->m_offerList.clear(); foreach (struct wl_client *client, Compositor::instance()->clients()) wl_client_post_event(client, &selection->selection_offer.object, WL_SELECTION_OFFER_KEYBOARD_FOCUS, 0); } wl_display_remove_global(dpy, &selection->selection_offer.object); delete selection; } void Selection::create(struct wl_client *client, uint32_t id) { delete m_retainedSelection; m_retainedSelection = 0; m_offerList.clear(); struct wl_selection *selection = new struct wl_selection; memset(selection, 0, sizeof *selection); selection->resource.object.id = id; selection->resource.object.interface = &wl_selection_interface; selection->resource.object.implementation = (void (**)()) &selectionInterface; selection->resource.destroy = destroySelection; selection->client = client; selection->input_device = Compositor::instance()->inputDevice(); wl_client_add_resource(client, &selection->resource); } void Selection::setRetainedSelection(bool enable) { m_retainedSelectionEnabled = enable; } void Selection::setRetainedSelectionWatcher(Watcher func, void *param) { m_watchFunc = func; m_watchFuncParam = param; } void Selection::onClientAdded(wl_client *client) { struct wl_selection *selection = m_currentSelection; struct wl_selection_offer *offer = m_currentOffer; if (m_retainedSelection) { selection = m_retainedSelection; offer = &m_retainedSelection->selection_offer; } if (selection && offer) { wl_client_post_event(client, &offer->object, WL_SELECTION_OFFER_KEYBOARD_FOCUS, 0); wl_client_post_global(client, &offer->object); foreach (const QString &mimeType, m_offerList) { QByteArray mimeTypeBa = mimeType.toLatin1(); wl_client_post_event(client, &offer->object, WL_SELECTION_OFFER_OFFER, mimeTypeBa.constData()); } wl_client_post_event(client, &offer->object, WL_SELECTION_OFFER_KEYBOARD_FOCUS, selection->input_device); } } Q_GLOBAL_STATIC(Selection, globalInstance) Selection *Selection::instance() { return globalInstance(); } Selection::Selection() : m_currentSelection(0), m_currentOffer(0), m_retainedReadNotifier(0), m_retainedSelection(0), m_retainedSelectionEnabled(false), m_watchFunc(0), m_watchFuncParam(0) { connect(Compositor::instance(), SIGNAL(clientAdded(wl_client*)), SLOT(onClientAdded(wl_client*))); } Selection::~Selection() { finishReadFromClient(); } } <commit_msg>Avoid post_global() whenever possible.<commit_after>/**************************************************************************** ** ** This file is part of QtCompositor** ** ** Copyright © 2010 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** ** Contact: Nokia Corporation [email protected] ** ** You may use this file under the terms of the BSD license as follows: ** ** 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 Nokia Corporation and its Subsidiary(-ies) nor the ** names of its contributors may be used to endorse or promote products ** derived from this software without specific prior written permission. ** ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT ** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR ** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT ** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, ** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT ** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY ** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT ** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ** ****************************************************************************/ #include "wlselection.h" #include "wlcompositor.h" #include <wayland-util.h> #include <string.h> #include <unistd.h> #include <QtCore/QFile> #include <QtCore/QSocketNotifier> namespace Wayland { void Selection::send(struct wl_client *client, struct wl_selection_offer *offer, const char *mime_type, int fd) { Q_UNUSED(client); Selection *self = instance(); if (self->m_retainedSelection) { QByteArray data = self->m_retainedData.data(QString::fromLatin1(mime_type)); if (!data.isEmpty()) { QFile f; if (f.open(fd, QIODevice::WriteOnly)) f.write(data); } } else { struct wl_selection *selection = container_of(offer, struct wl_selection, selection_offer); wl_client_post_event(selection->client, &selection->resource.object, WL_SELECTION_SEND, mime_type, fd); } close(fd); } const struct wl_selection_offer_interface Selection::selectionOfferInterface = { Selection::send }; void Selection::selOffer(struct wl_client *client, struct wl_selection *selection, const char *type) { Q_UNUSED(client); Q_UNUSED(selection); instance()->m_offerList.append(QString::fromLatin1(type)); } void Selection::selActivate(struct wl_client *client, struct wl_selection *selection, struct wl_input_device *device, uint32_t time) { Q_UNUSED(client); Q_UNUSED(device); Q_UNUSED(time); Selection *self = Selection::instance(); selection->selection_offer.object.interface = &wl_selection_offer_interface; selection->selection_offer.object.implementation = (void (**)()) &selectionOfferInterface; wl_display *dpy = Compositor::instance()->wl_display(); wl_display_add_object(dpy, &selection->selection_offer.object); wl_display_add_global(dpy, &selection->selection_offer.object, 0); QList<struct wl_client *> clients = Compositor::instance()->clients(); if (self->m_currentSelection) { if (!clients.contains(self->m_currentSelection->client)) self->m_currentSelection = 0; else wl_client_post_event(self->m_currentSelection->client, &self->m_currentSelection->resource.object, WL_SELECTION_CANCELLED); } self->m_currentSelection = selection; if (self->m_currentOffer) { foreach (struct wl_client *client, clients) { wl_client_post_event(client, &self->m_currentOffer->object, WL_SELECTION_OFFER_KEYBOARD_FOCUS, 0); } } self->m_currentOffer = &selection->selection_offer; foreach (struct wl_client *client, clients) { wl_client_post_global(client, &selection->selection_offer.object); } foreach (struct wl_client *client, clients) { foreach (const QString &mimeType, self->m_offerList) { QByteArray mimeTypeBa = mimeType.toLatin1(); wl_client_post_event(client, &selection->selection_offer.object, WL_SELECTION_OFFER_OFFER, mimeTypeBa.constData()); } } foreach (struct wl_client *client, clients) { wl_client_post_event(client, &selection->selection_offer.object, WL_SELECTION_OFFER_KEYBOARD_FOCUS, selection->input_device); } if (self->m_retainedSelectionEnabled) { self->m_retainedData.clear(); self->m_retainedReadIndex = 0; self->retain(); } } void Selection::retain() { finishReadFromClient(); if (m_retainedReadIndex >= m_offerList.count()) { if (m_watchFunc) m_watchFunc(&m_retainedData, m_watchFuncParam); return; } QString mimeType = m_offerList.at(m_retainedReadIndex); m_retainedReadBuf.clear(); QByteArray mimeTypeBa = mimeType.toLatin1(); int fd[2]; if (pipe(fd) == -1) { qWarning("Clipboard: Failed to create pipe"); return; } wl_client_post_event(m_currentSelection->client, &m_currentSelection->resource.object, WL_SELECTION_SEND, mimeTypeBa.constData(), fd[1]); close(fd[1]); m_retainedReadNotifier = new QSocketNotifier(fd[0], QSocketNotifier::Read, this); connect(m_retainedReadNotifier, SIGNAL(activated(int)), SLOT(readFromClient(int))); } void Selection::finishReadFromClient() { if (m_retainedReadNotifier) { int fd = m_retainedReadNotifier->socket(); delete m_retainedReadNotifier; m_retainedReadNotifier = 0; close(fd); } } void Selection::readFromClient(int fd) { char buf[256]; int n = read(fd, buf, sizeof buf); if (n <= 0) { finishReadFromClient(); QString mimeType = m_offerList.at(m_retainedReadIndex); m_retainedData.setData(mimeType, m_retainedReadBuf); ++m_retainedReadIndex; retain(); } else { m_retainedReadBuf.append(buf, n); } } void Selection::selDestroy(struct wl_client *client, struct wl_selection *selection) { wl_resource_destroy(&selection->resource, client, Compositor::currentTimeMsecs()); } const struct wl_selection_interface Selection::selectionInterface = { Selection::selOffer, Selection::selActivate, Selection::selDestroy }; void Selection::destroySelection(struct wl_resource *resource, struct wl_client *client) { Q_UNUSED(client); struct wl_selection *selection = container_of(resource, struct wl_selection, resource); Selection *self = Selection::instance(); wl_display *dpy = Compositor::instance()->wl_display(); if (self->m_currentSelection == selection) self->m_currentSelection = 0; if (self->m_currentOffer == &selection->selection_offer) { self->m_currentOffer = 0; if (self->m_retainedSelectionEnabled) { if (self->m_retainedSelection) { wl_display_remove_global(dpy, &self->m_retainedSelection->selection_offer.object); delete self->m_retainedSelection; } self->m_retainedSelection = selection; return; } self->m_offerList.clear(); foreach (struct wl_client *client, Compositor::instance()->clients()) wl_client_post_event(client, &selection->selection_offer.object, WL_SELECTION_OFFER_KEYBOARD_FOCUS, 0); } wl_display_remove_global(dpy, &selection->selection_offer.object); delete selection; } void Selection::create(struct wl_client *client, uint32_t id) { delete m_retainedSelection; m_retainedSelection = 0; m_offerList.clear(); struct wl_selection *selection = new struct wl_selection; memset(selection, 0, sizeof *selection); selection->resource.object.id = id; selection->resource.object.interface = &wl_selection_interface; selection->resource.object.implementation = (void (**)()) &selectionInterface; selection->resource.destroy = destroySelection; selection->client = client; selection->input_device = Compositor::instance()->inputDevice(); wl_client_add_resource(client, &selection->resource); } void Selection::setRetainedSelection(bool enable) { m_retainedSelectionEnabled = enable; } void Selection::setRetainedSelectionWatcher(Watcher func, void *param) { m_watchFunc = func; m_watchFuncParam = param; } void Selection::onClientAdded(wl_client *client) { struct wl_selection *selection = m_currentSelection; struct wl_selection_offer *offer = m_currentOffer; if (m_retainedSelection) { selection = m_retainedSelection; offer = &m_retainedSelection->selection_offer; } if (selection && offer) { foreach (const QString &mimeType, m_offerList) { QByteArray mimeTypeBa = mimeType.toLatin1(); wl_client_post_event(client, &offer->object, WL_SELECTION_OFFER_OFFER, mimeTypeBa.constData()); } wl_client_post_event(client, &offer->object, WL_SELECTION_OFFER_KEYBOARD_FOCUS, selection->input_device); } } Q_GLOBAL_STATIC(Selection, globalInstance) Selection *Selection::instance() { return globalInstance(); } Selection::Selection() : m_currentSelection(0), m_currentOffer(0), m_retainedReadNotifier(0), m_retainedSelection(0), m_retainedSelectionEnabled(false), m_watchFunc(0), m_watchFuncParam(0) { connect(Compositor::instance(), SIGNAL(clientAdded(wl_client*)), SLOT(onClientAdded(wl_client*))); } Selection::~Selection() { finishReadFromClient(); } } <|endoftext|>
<commit_before>/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2016 Artem Pavlenko * * 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 * *****************************************************************************/ #include <mapnik/label_collision_detector.hpp> #include <mapnik/svg/svg_storage.hpp> #include <mapnik/svg/svg_path_adapter.hpp> #include <mapnik/marker_cache.hpp> #include <mapnik/marker_helpers.hpp> #include <mapnik/geometry/geometry_type.hpp> #include <mapnik/renderer_common/render_markers_symbolizer.hpp> #include <mapnik/symbolizer.hpp> namespace mapnik { namespace detail { template <typename Detector, typename RendererType, typename ContextType> struct render_marker_symbolizer_visitor { using vector_dispatch_type = vector_markers_dispatch<Detector>; using raster_dispatch_type = raster_markers_dispatch<Detector>; render_marker_symbolizer_visitor(std::string const& filename, markers_symbolizer const& sym, mapnik::feature_impl & feature, proj_transform const& prj_trans, RendererType const& common, box2d<double> const& clip_box, ContextType & renderer_context) : filename_(filename), sym_(sym), feature_(feature), prj_trans_(prj_trans), common_(common), clip_box_(clip_box), renderer_context_(renderer_context) {} svg_attribute_type const& get_marker_attributes(svg_path_ptr const& stock_marker, svg_attribute_type & custom_attr) const { auto const& stock_attr = stock_marker->attributes(); if (push_explicit_style(stock_attr, custom_attr, sym_, feature_, common_.vars_)) return custom_attr; else return stock_attr; } template <typename Marker, typename Dispatch> void render_marker(Marker const& mark, Dispatch & rasterizer_dispatch) const { auto const& vars = common_.vars_; agg::trans_affine geom_tr; if (auto geometry_transform = get_optional<transform_type>(sym_, keys::geometry_transform)) { evaluate_transform(geom_tr, feature_, vars, *geometry_transform, common_.scale_factor_); } vertex_converter_type converter(clip_box_, sym_, common_.t_, prj_trans_, geom_tr, feature_, vars, common_.scale_factor_); bool clip = get<value_bool, keys::clip>(sym_, feature_, vars); double offset = get<value_double, keys::offset>(sym_, feature_, vars); double simplify_tolerance = get<value_double, keys::simplify_tolerance>(sym_, feature_, vars); double smooth = get<value_double, keys::smooth>(sym_, feature_, vars); if (clip) { geometry::geometry_types type = geometry::geometry_type(feature_.get_geometry()); switch (type) { case geometry::geometry_types::Polygon: case geometry::geometry_types::MultiPolygon: converter.template set<clip_poly_tag>(); break; case geometry::geometry_types::LineString: case geometry::geometry_types::MultiLineString: converter.template set<clip_line_tag>(); break; default: // silence warning: 4 enumeration values not handled in switch break; } } converter.template set<transform_tag>(); //always transform if (std::fabs(offset) > 0.0) converter.template set<offset_transform_tag>(); // parallel offset converter.template set<affine_transform_tag>(); // optional affine transform if (simplify_tolerance > 0.0) converter.template set<simplify_tag>(); // optional simplify converter if (smooth > 0.0) converter.template set<smooth_tag>(); // optional smooth converter apply_markers_multi(feature_, vars, converter, rasterizer_dispatch, sym_); } void operator() (marker_null const&) const {} void operator() (marker_svg const& mark) const { using namespace mapnik::svg; // https://github.com/mapnik/mapnik/issues/1316 bool snap_to_pixels = !mapnik::marker_cache::instance().is_uri(filename_); agg::trans_affine image_tr = agg::trans_affine_scaling(common_.scale_factor_); boost::optional<svg_path_ptr> const& stock_vector_marker = mark.get_data(); svg_path_ptr marker_ptr = *stock_vector_marker; bool is_ellipse = false; svg_attribute_type s_attributes; auto const& r_attributes = get_marker_attributes(*stock_vector_marker, s_attributes); // special case for simple ellipse markers // to allow for full control over rx/ry dimensions if (filename_ == "shape://ellipse" && (has_key(sym_,keys::width) || has_key(sym_,keys::height))) { marker_ptr = std::make_shared<svg_storage_type>(); is_ellipse = true; } else { box2d<double> const& bbox = mark.bounding_box(); setup_transform_scaling(image_tr, bbox.width(), bbox.height(), feature_, common_.vars_, sym_); } vertex_stl_adapter<svg_path_storage> stl_storage(marker_ptr->source()); svg_path_adapter svg_path(stl_storage); if (is_ellipse) { build_ellipse(sym_, feature_, common_.vars_, *marker_ptr, svg_path); } if (auto image_transform = get_optional<transform_type>(sym_, keys::image_transform)) { evaluate_transform(image_tr, feature_, common_.vars_, *image_transform, common_.scale_factor_); } vector_dispatch_type rasterizer_dispatch(marker_ptr, svg_path, r_attributes, image_tr, sym_, *common_.detector_, common_.scale_factor_, feature_, common_.vars_, snap_to_pixels, renderer_context_); render_marker(mark, rasterizer_dispatch); } void operator() (marker_rgba8 const& mark) const { agg::trans_affine image_tr = agg::trans_affine_scaling(common_.scale_factor_); setup_transform_scaling(image_tr, mark.width(), mark.height(), feature_, common_.vars_, sym_); auto image_transform = get_optional<transform_type>(sym_, keys::image_transform); if (image_transform) evaluate_transform(image_tr, feature_, common_.vars_, *image_transform, common_.scale_factor_); box2d<double> const& bbox = mark.bounding_box(); mapnik::image_rgba8 const& marker = mark.get_data(); // - clamp sizes to > 4 pixels of interactivity coord2d center = bbox.center(); agg::trans_affine_translation recenter(-center.x, -center.y); agg::trans_affine marker_trans = recenter * image_tr; raster_dispatch_type rasterizer_dispatch(marker, marker_trans, sym_, *common_.detector_, common_.scale_factor_, feature_, common_.vars_, renderer_context_); render_marker(mark, rasterizer_dispatch); } private: std::string const& filename_; markers_symbolizer const& sym_; mapnik::feature_impl & feature_; proj_transform const& prj_trans_; RendererType const& common_; box2d<double> const& clip_box_; ContextType & renderer_context_; }; } // namespace detail markers_dispatch_params::markers_dispatch_params(box2d<double> const& size, agg::trans_affine const& tr, symbolizer_base const& sym, feature_impl const& feature, attributes const& vars, double scale, bool snap) : placement_params{ size, tr, get<value_double, keys::spacing>(sym, feature, vars), get<value_double, keys::max_error>(sym, feature, vars), get<value_bool, keys::allow_overlap>(sym, feature, vars), get<value_bool, keys::avoid_edges>(sym, feature, vars), get<direction_enum, keys::direction>(sym, feature, vars)} , placement_method(get<marker_placement_enum, keys::markers_placement_type>(sym, feature, vars)) , ignore_placement(get<value_bool, keys::ignore_placement>(sym, feature, vars)) , snap_to_pixels(snap) , scale_factor(scale) , opacity(get<value_double, keys::opacity>(sym, feature, vars)) { placement_params.spacing *= scale; } void render_markers_symbolizer(markers_symbolizer const& sym, mapnik::feature_impl & feature, proj_transform const& prj_trans, renderer_common const& common, box2d<double> const& clip_box, markers_renderer_context & renderer_context) { using Detector = label_collision_detector4; using RendererType = renderer_common; using ContextType = markers_renderer_context; using VisitorType = detail::render_marker_symbolizer_visitor<Detector, RendererType, ContextType>; std::string filename = get<std::string>(sym, keys::file, feature, common.vars_, "shape://ellipse"); if (!filename.empty()) { auto mark = mapnik::marker_cache::instance().find(filename, true); VisitorType visitor(filename, sym, feature, prj_trans, common, clip_box, renderer_context); util::apply_visitor(visitor, *mark); } } } // namespace mapnik <commit_msg>strip boost::optional from non-optional marker ptr<commit_after>/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2016 Artem Pavlenko * * 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 * *****************************************************************************/ #include <mapnik/label_collision_detector.hpp> #include <mapnik/svg/svg_storage.hpp> #include <mapnik/svg/svg_path_adapter.hpp> #include <mapnik/marker_cache.hpp> #include <mapnik/marker_helpers.hpp> #include <mapnik/geometry/geometry_type.hpp> #include <mapnik/renderer_common/render_markers_symbolizer.hpp> #include <mapnik/symbolizer.hpp> namespace mapnik { namespace detail { template <typename Detector, typename RendererType, typename ContextType> struct render_marker_symbolizer_visitor { using vector_dispatch_type = vector_markers_dispatch<Detector>; using raster_dispatch_type = raster_markers_dispatch<Detector>; render_marker_symbolizer_visitor(std::string const& filename, markers_symbolizer const& sym, mapnik::feature_impl & feature, proj_transform const& prj_trans, RendererType const& common, box2d<double> const& clip_box, ContextType & renderer_context) : filename_(filename), sym_(sym), feature_(feature), prj_trans_(prj_trans), common_(common), clip_box_(clip_box), renderer_context_(renderer_context) {} svg_attribute_type const& get_marker_attributes(svg_path_ptr const& stock_marker, svg_attribute_type & custom_attr) const { auto const& stock_attr = stock_marker->attributes(); if (push_explicit_style(stock_attr, custom_attr, sym_, feature_, common_.vars_)) return custom_attr; else return stock_attr; } template <typename Marker, typename Dispatch> void render_marker(Marker const& mark, Dispatch & rasterizer_dispatch) const { auto const& vars = common_.vars_; agg::trans_affine geom_tr; if (auto geometry_transform = get_optional<transform_type>(sym_, keys::geometry_transform)) { evaluate_transform(geom_tr, feature_, vars, *geometry_transform, common_.scale_factor_); } vertex_converter_type converter(clip_box_, sym_, common_.t_, prj_trans_, geom_tr, feature_, vars, common_.scale_factor_); bool clip = get<value_bool, keys::clip>(sym_, feature_, vars); double offset = get<value_double, keys::offset>(sym_, feature_, vars); double simplify_tolerance = get<value_double, keys::simplify_tolerance>(sym_, feature_, vars); double smooth = get<value_double, keys::smooth>(sym_, feature_, vars); if (clip) { geometry::geometry_types type = geometry::geometry_type(feature_.get_geometry()); switch (type) { case geometry::geometry_types::Polygon: case geometry::geometry_types::MultiPolygon: converter.template set<clip_poly_tag>(); break; case geometry::geometry_types::LineString: case geometry::geometry_types::MultiLineString: converter.template set<clip_line_tag>(); break; default: // silence warning: 4 enumeration values not handled in switch break; } } converter.template set<transform_tag>(); //always transform if (std::fabs(offset) > 0.0) converter.template set<offset_transform_tag>(); // parallel offset converter.template set<affine_transform_tag>(); // optional affine transform if (simplify_tolerance > 0.0) converter.template set<simplify_tag>(); // optional simplify converter if (smooth > 0.0) converter.template set<smooth_tag>(); // optional smooth converter apply_markers_multi(feature_, vars, converter, rasterizer_dispatch, sym_); } void operator() (marker_null const&) const {} void operator() (marker_svg const& mark) const { using namespace mapnik::svg; // https://github.com/mapnik/mapnik/issues/1316 bool snap_to_pixels = !mapnik::marker_cache::instance().is_uri(filename_); agg::trans_affine image_tr = agg::trans_affine_scaling(common_.scale_factor_); svg_path_ptr stock_vector_marker = mark.get_data(); svg_path_ptr marker_ptr = stock_vector_marker; bool is_ellipse = false; svg_attribute_type s_attributes; auto const& r_attributes = get_marker_attributes(stock_vector_marker, s_attributes); // special case for simple ellipse markers // to allow for full control over rx/ry dimensions if (filename_ == "shape://ellipse" && (has_key(sym_,keys::width) || has_key(sym_,keys::height))) { marker_ptr = std::make_shared<svg_storage_type>(); is_ellipse = true; } else { box2d<double> const& bbox = mark.bounding_box(); setup_transform_scaling(image_tr, bbox.width(), bbox.height(), feature_, common_.vars_, sym_); } vertex_stl_adapter<svg_path_storage> stl_storage(marker_ptr->source()); svg_path_adapter svg_path(stl_storage); if (is_ellipse) { build_ellipse(sym_, feature_, common_.vars_, *marker_ptr, svg_path); } if (auto image_transform = get_optional<transform_type>(sym_, keys::image_transform)) { evaluate_transform(image_tr, feature_, common_.vars_, *image_transform, common_.scale_factor_); } vector_dispatch_type rasterizer_dispatch(marker_ptr, svg_path, r_attributes, image_tr, sym_, *common_.detector_, common_.scale_factor_, feature_, common_.vars_, snap_to_pixels, renderer_context_); render_marker(mark, rasterizer_dispatch); } void operator() (marker_rgba8 const& mark) const { agg::trans_affine image_tr = agg::trans_affine_scaling(common_.scale_factor_); setup_transform_scaling(image_tr, mark.width(), mark.height(), feature_, common_.vars_, sym_); auto image_transform = get_optional<transform_type>(sym_, keys::image_transform); if (image_transform) evaluate_transform(image_tr, feature_, common_.vars_, *image_transform, common_.scale_factor_); box2d<double> const& bbox = mark.bounding_box(); mapnik::image_rgba8 const& marker = mark.get_data(); // - clamp sizes to > 4 pixels of interactivity coord2d center = bbox.center(); agg::trans_affine_translation recenter(-center.x, -center.y); agg::trans_affine marker_trans = recenter * image_tr; raster_dispatch_type rasterizer_dispatch(marker, marker_trans, sym_, *common_.detector_, common_.scale_factor_, feature_, common_.vars_, renderer_context_); render_marker(mark, rasterizer_dispatch); } private: std::string const& filename_; markers_symbolizer const& sym_; mapnik::feature_impl & feature_; proj_transform const& prj_trans_; RendererType const& common_; box2d<double> const& clip_box_; ContextType & renderer_context_; }; } // namespace detail markers_dispatch_params::markers_dispatch_params(box2d<double> const& size, agg::trans_affine const& tr, symbolizer_base const& sym, feature_impl const& feature, attributes const& vars, double scale, bool snap) : placement_params{ size, tr, get<value_double, keys::spacing>(sym, feature, vars), get<value_double, keys::max_error>(sym, feature, vars), get<value_bool, keys::allow_overlap>(sym, feature, vars), get<value_bool, keys::avoid_edges>(sym, feature, vars), get<direction_enum, keys::direction>(sym, feature, vars)} , placement_method(get<marker_placement_enum, keys::markers_placement_type>(sym, feature, vars)) , ignore_placement(get<value_bool, keys::ignore_placement>(sym, feature, vars)) , snap_to_pixels(snap) , scale_factor(scale) , opacity(get<value_double, keys::opacity>(sym, feature, vars)) { placement_params.spacing *= scale; } void render_markers_symbolizer(markers_symbolizer const& sym, mapnik::feature_impl & feature, proj_transform const& prj_trans, renderer_common const& common, box2d<double> const& clip_box, markers_renderer_context & renderer_context) { using Detector = label_collision_detector4; using RendererType = renderer_common; using ContextType = markers_renderer_context; using VisitorType = detail::render_marker_symbolizer_visitor<Detector, RendererType, ContextType>; std::string filename = get<std::string>(sym, keys::file, feature, common.vars_, "shape://ellipse"); if (!filename.empty()) { auto mark = mapnik::marker_cache::instance().find(filename, true); VisitorType visitor(filename, sym, feature, prj_trans, common, clip_box, renderer_context); util::apply_visitor(visitor, *mark); } } } // namespace mapnik <|endoftext|>
<commit_before>// Copyright (c) 2011 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 "content/browser/plugin_data_remover_impl.h" #include "base/bind.h" #include "base/metrics/histogram.h" #include "base/synchronization/waitable_event.h" #include "base/version.h" #include "content/browser/plugin_process_host.h" #include "content/browser/plugin_service.h" #include "content/common/child_process_host_impl.h" #include "content/common/plugin_messages.h" #include "content/public/browser/browser_thread.h" #include "webkit/plugins/npapi/plugin_group.h" using content::BrowserThread; using content::ChildProcessHostImpl; namespace { const char kFlashMimeType[] = "application/x-shockwave-flash"; // The minimum Flash Player version that implements NPP_ClearSiteData. const char kMinFlashVersion[] = "10.3"; const int64 kRemovalTimeoutMs = 10000; const uint64 kClearAllData = 0; } // namespace namespace content { // static PluginDataRemover* PluginDataRemover::Create( const content::ResourceContext& resource_context) { return new PluginDataRemoverImpl(resource_context); } // static bool PluginDataRemover::IsSupported(webkit::WebPluginInfo* plugin) { bool allow_wildcard = false; std::vector<webkit::WebPluginInfo> plugins; PluginService::GetInstance()->GetPluginInfoArray( GURL(), kFlashMimeType, allow_wildcard, &plugins, NULL); std::vector<webkit::WebPluginInfo>::iterator plugin_it = plugins.begin(); if (plugin_it == plugins.end()) return false; scoped_ptr<Version> version( webkit::npapi::PluginGroup::CreateVersionFromString(plugin_it->version)); scoped_ptr<Version> min_version( Version::GetVersionFromString(kMinFlashVersion)); bool rv = version.get() && min_version->CompareTo(*version) == -1; if (rv) *plugin = *plugin_it; return rv; } } class PluginDataRemoverImpl::Context : public PluginProcessHost::Client, public IPC::Channel::Listener, public base::RefCountedThreadSafe<Context> { public: Context(const std::string& mime_type, base::Time begin_time, const content::ResourceContext& resource_context) : event_(new base::WaitableEvent(true, false)), begin_time_(begin_time), is_removing_(false), resource_context_(resource_context), channel_(NULL) { // Balanced in OnChannelOpened or OnError. Exactly one them will eventually // be called, so we need to keep this object around until then. AddRef(); remove_start_time_ = base::Time::Now(); BrowserThread::PostTask( BrowserThread::IO, FROM_HERE, base::Bind(&Context::Init, this, mime_type)); BrowserThread::PostDelayedTask( BrowserThread::IO, FROM_HERE, base::Bind(&Context::OnTimeout, this), kRemovalTimeoutMs); } virtual ~Context() { if (channel_) BrowserThread::DeleteSoon(BrowserThread::IO, FROM_HERE, channel_); } // PluginProcessHost::Client methods. virtual int ID() OVERRIDE { // Generate a unique identifier for this PluginProcessHostClient. return ChildProcessHostImpl::GenerateChildProcessUniqueId(); } virtual bool OffTheRecord() OVERRIDE { return false; } virtual const content::ResourceContext& GetResourceContext() OVERRIDE { return resource_context_; } virtual void SetPluginInfo(const webkit::WebPluginInfo& info) OVERRIDE { } virtual void OnFoundPluginProcessHost(PluginProcessHost* host) OVERRIDE { } virtual void OnSentPluginChannelRequest() OVERRIDE { } virtual void OnChannelOpened(const IPC::ChannelHandle& handle) OVERRIDE { ConnectToChannel(handle); // Balancing the AddRef call. Release(); } virtual void OnError() OVERRIDE { LOG(DFATAL) << "Couldn't open plugin channel"; SignalDone(); // Balancing the AddRef call. Release(); } // IPC::Channel::Listener methods. virtual bool OnMessageReceived(const IPC::Message& message) OVERRIDE { IPC_BEGIN_MESSAGE_MAP(Context, message) IPC_MESSAGE_HANDLER(PluginHostMsg_ClearSiteDataResult, OnClearSiteDataResult) IPC_MESSAGE_UNHANDLED_ERROR() IPC_END_MESSAGE_MAP() return true; } virtual void OnChannelError() OVERRIDE { if (is_removing_) { NOTREACHED() << "Channel error"; SignalDone(); } } base::WaitableEvent* event() { return event_.get(); } private: // Initialize on the IO thread. void Init(const std::string& mime_type) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO)); is_removing_ = true; PluginService::GetInstance()->OpenChannelToNpapiPlugin( 0, 0, GURL(), GURL(), mime_type, this); } // Connects the client side of a newly opened plug-in channel. void ConnectToChannel(const IPC::ChannelHandle& handle) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO)); // If we timed out, don't bother connecting. if (!is_removing_) return; DCHECK(!channel_); channel_ = new IPC::Channel(handle, IPC::Channel::MODE_CLIENT, this); if (!channel_->Connect()) { NOTREACHED() << "Couldn't connect to plugin"; SignalDone(); return; } if (!channel_->Send(new PluginMsg_ClearSiteData(std::string(), kClearAllData, begin_time_))) { NOTREACHED() << "Couldn't send ClearSiteData message"; SignalDone(); return; } } // Handles the PluginHostMsg_ClearSiteDataResult message. void OnClearSiteDataResult(bool success) { LOG_IF(ERROR, !success) << "ClearSiteData returned error"; UMA_HISTOGRAM_TIMES("ClearPluginData.time", base::Time::Now() - remove_start_time_); SignalDone(); } // Called when a timeout happens in order not to block the client // indefinitely. void OnTimeout() { LOG_IF(ERROR, is_removing_) << "Timed out"; SignalDone(); } // Signals that we are finished with removing data (successful or not). This // method is safe to call multiple times. void SignalDone() { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO)); if (!is_removing_) return; is_removing_ = false; event_->Signal(); } scoped_ptr<base::WaitableEvent> event_; // The point in time when we start removing data. base::Time remove_start_time_; // The point in time from which on we remove data. base::Time begin_time_; bool is_removing_; // The resource context for the profile. const content::ResourceContext& resource_context_; // We own the channel, but it's used on the IO thread, so it needs to be // deleted there. It's NULL until we have opened a connection to the plug-in // process. IPC::Channel* channel_; }; PluginDataRemoverImpl::PluginDataRemoverImpl( const content::ResourceContext& resource_context) : mime_type_(kFlashMimeType), resource_context_(resource_context) { } PluginDataRemoverImpl::~PluginDataRemoverImpl() { } base::WaitableEvent* PluginDataRemoverImpl::StartRemoving( base::Time begin_time) { DCHECK(!context_.get()); context_ = new Context(mime_type_, begin_time, resource_context_); return context_->event(); } <commit_msg>Make sure PluginDataRemoverImpl::Init is executed after the constructor has finished.<commit_after>// Copyright (c) 2011 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 "content/browser/plugin_data_remover_impl.h" #include "base/bind.h" #include "base/metrics/histogram.h" #include "base/synchronization/waitable_event.h" #include "base/version.h" #include "content/browser/plugin_process_host.h" #include "content/browser/plugin_service.h" #include "content/common/child_process_host_impl.h" #include "content/common/plugin_messages.h" #include "content/public/browser/browser_thread.h" #include "webkit/plugins/npapi/plugin_group.h" using content::BrowserThread; using content::ChildProcessHostImpl; namespace { const char kFlashMimeType[] = "application/x-shockwave-flash"; // The minimum Flash Player version that implements NPP_ClearSiteData. const char kMinFlashVersion[] = "10.3"; const int64 kRemovalTimeoutMs = 10000; const uint64 kClearAllData = 0; } // namespace namespace content { // static PluginDataRemover* PluginDataRemover::Create( const content::ResourceContext& resource_context) { return new PluginDataRemoverImpl(resource_context); } // static bool PluginDataRemover::IsSupported(webkit::WebPluginInfo* plugin) { bool allow_wildcard = false; std::vector<webkit::WebPluginInfo> plugins; PluginService::GetInstance()->GetPluginInfoArray( GURL(), kFlashMimeType, allow_wildcard, &plugins, NULL); std::vector<webkit::WebPluginInfo>::iterator plugin_it = plugins.begin(); if (plugin_it == plugins.end()) return false; scoped_ptr<Version> version( webkit::npapi::PluginGroup::CreateVersionFromString(plugin_it->version)); scoped_ptr<Version> min_version( Version::GetVersionFromString(kMinFlashVersion)); bool rv = version.get() && min_version->CompareTo(*version) == -1; if (rv) *plugin = *plugin_it; return rv; } } class PluginDataRemoverImpl::Context : public PluginProcessHost::Client, public IPC::Channel::Listener, public base::RefCountedThreadSafe<Context, BrowserThread::DeleteOnIOThread> { public: Context(base::Time begin_time, const content::ResourceContext& resource_context) : event_(new base::WaitableEvent(true, false)), begin_time_(begin_time), is_removing_(false), resource_context_(resource_context), channel_(NULL) { } virtual ~Context() { } void Init(const std::string& mime_type) { BrowserThread::PostTask( BrowserThread::IO, FROM_HERE, base::Bind(&Context::InitOnIOThread, this, mime_type)); BrowserThread::PostDelayedTask( BrowserThread::IO, FROM_HERE, base::Bind(&Context::OnTimeout, this), kRemovalTimeoutMs); } // Initialize on the IO thread. void InitOnIOThread(const std::string& mime_type) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO)); remove_start_time_ = base::Time::Now(); is_removing_ = true; // Balanced in OnChannelOpened or OnError. Exactly one them will eventually // be called, so we need to keep this object around until then. AddRef(); PluginService::GetInstance()->OpenChannelToNpapiPlugin( 0, 0, GURL(), GURL(), mime_type, this); } // Called when a timeout happens in order not to block the client // indefinitely. void OnTimeout() { LOG_IF(ERROR, is_removing_) << "Timed out"; SignalDone(); } // PluginProcessHost::Client methods. virtual int ID() OVERRIDE { // Generate a unique identifier for this PluginProcessHostClient. return ChildProcessHostImpl::GenerateChildProcessUniqueId(); } virtual bool OffTheRecord() OVERRIDE { return false; } virtual const content::ResourceContext& GetResourceContext() OVERRIDE { return resource_context_; } virtual void SetPluginInfo(const webkit::WebPluginInfo& info) OVERRIDE { } virtual void OnFoundPluginProcessHost(PluginProcessHost* host) OVERRIDE { } virtual void OnSentPluginChannelRequest() OVERRIDE { } virtual void OnChannelOpened(const IPC::ChannelHandle& handle) OVERRIDE { ConnectToChannel(handle); // Balancing the AddRef call. Release(); } virtual void OnError() OVERRIDE { LOG(DFATAL) << "Couldn't open plugin channel"; SignalDone(); // Balancing the AddRef call. Release(); } // IPC::Channel::Listener methods. virtual bool OnMessageReceived(const IPC::Message& message) OVERRIDE { IPC_BEGIN_MESSAGE_MAP(Context, message) IPC_MESSAGE_HANDLER(PluginHostMsg_ClearSiteDataResult, OnClearSiteDataResult) IPC_MESSAGE_UNHANDLED_ERROR() IPC_END_MESSAGE_MAP() return true; } virtual void OnChannelError() OVERRIDE { if (is_removing_) { NOTREACHED() << "Channel error"; SignalDone(); } } base::WaitableEvent* event() { return event_.get(); } private: // Connects the client side of a newly opened plug-in channel. void ConnectToChannel(const IPC::ChannelHandle& handle) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO)); // If we timed out, don't bother connecting. if (!is_removing_) return; DCHECK(!channel_.get()); channel_.reset(new IPC::Channel(handle, IPC::Channel::MODE_CLIENT, this)); if (!channel_->Connect()) { NOTREACHED() << "Couldn't connect to plugin"; SignalDone(); return; } if (!channel_->Send(new PluginMsg_ClearSiteData(std::string(), kClearAllData, begin_time_))) { NOTREACHED() << "Couldn't send ClearSiteData message"; SignalDone(); return; } } // Handles the PluginHostMsg_ClearSiteDataResult message. void OnClearSiteDataResult(bool success) { LOG_IF(ERROR, !success) << "ClearSiteData returned error"; UMA_HISTOGRAM_TIMES("ClearPluginData.time", base::Time::Now() - remove_start_time_); SignalDone(); } // Signals that we are finished with removing data (successful or not). This // method is safe to call multiple times. void SignalDone() { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO)); if (!is_removing_) return; is_removing_ = false; event_->Signal(); } scoped_ptr<base::WaitableEvent> event_; // The point in time when we start removing data. base::Time remove_start_time_; // The point in time from which on we remove data. base::Time begin_time_; bool is_removing_; // The resource context for the profile. const content::ResourceContext& resource_context_; // The channel is NULL until we have opened a connection to the plug-in // process. scoped_ptr<IPC::Channel> channel_; }; PluginDataRemoverImpl::PluginDataRemoverImpl( const content::ResourceContext& resource_context) : mime_type_(kFlashMimeType), resource_context_(resource_context) { } PluginDataRemoverImpl::~PluginDataRemoverImpl() { } base::WaitableEvent* PluginDataRemoverImpl::StartRemoving( base::Time begin_time) { DCHECK(!context_.get()); context_ = new Context(begin_time, resource_context_); context_->Init(mime_type_); return context_->event(); } <|endoftext|>
<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "content/browser/speech/speech_recognizer.h" #include "base/time.h" #include "chrome/browser/profiles/profile.h" #include "chrome/common/net/url_request_context_getter.h" #include "content/browser/browser_thread.h" using media::AudioInputController; using std::string; namespace { // The following constants are related to the volume level indicator shown in // the UI for recorded audio. // Multiplier used when new volume is greater than previous level. const float kUpSmoothingFactor = 1.0f; // Multiplier used when new volume is lesser than previous level. const float kDownSmoothingFactor = 0.7f; // RMS dB value of a maximum (unclipped) sine wave for int16 samples. const float kAudioMeterMaxDb = 90.31f; // This value corresponds to RMS dB for int16 with 6 most-significant-bits = 0. // Values lower than this will display as empty level-meter. const float kAudioMeterMinDb = 30.0f; const float kAudioMeterDbRange = kAudioMeterMaxDb - kAudioMeterMinDb; // Maximum level to draw to display unclipped meter. (1.0f displays clipping.) const float kAudioMeterRangeMaxUnclipped = 47.0f / 48.0f; // Returns true if more than 5% of the samples are at min or max value. bool Clipping(const int16* samples, int num_samples) { int clipping_samples = 0; const int kThreshold = num_samples / 20; for (int i = 0; i < num_samples; ++i) { if (samples[i] <= -32767 || samples[i] >= 32767) { if (++clipping_samples > kThreshold) return true; } } return false; } } // namespace namespace speech_input { const int SpeechRecognizer::kAudioSampleRate = 16000; const int SpeechRecognizer::kAudioPacketIntervalMs = 100; const int SpeechRecognizer::kNumAudioChannels = 1; const int SpeechRecognizer::kNumBitsPerAudioSample = 16; const int SpeechRecognizer::kNoSpeechTimeoutSec = 8; const int SpeechRecognizer::kEndpointerEstimationTimeMs = 300; SpeechRecognizer::SpeechRecognizer(Delegate* delegate, int caller_id, const std::string& language, const std::string& grammar, const std::string& hardware_info, const std::string& origin_url) : delegate_(delegate), caller_id_(caller_id), language_(language), grammar_(grammar), hardware_info_(hardware_info), origin_url_(origin_url), codec_(AudioEncoder::CODEC_SPEEX), encoder_(NULL), endpointer_(kAudioSampleRate), num_samples_recorded_(0), audio_level_(0.0f) { endpointer_.set_speech_input_complete_silence_length( base::Time::kMicrosecondsPerSecond / 2); endpointer_.set_long_speech_input_complete_silence_length( base::Time::kMicrosecondsPerSecond); endpointer_.set_long_speech_length(3 * base::Time::kMicrosecondsPerSecond); endpointer_.StartSession(); } SpeechRecognizer::~SpeechRecognizer() { // Recording should have stopped earlier due to the endpointer or // |StopRecording| being called. DCHECK(!audio_controller_.get()); DCHECK(!request_.get() || !request_->HasPendingRequest()); DCHECK(!encoder_.get()); endpointer_.EndSession(); } bool SpeechRecognizer::StartRecording() { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO)); DCHECK(!audio_controller_.get()); DCHECK(!request_.get() || !request_->HasPendingRequest()); DCHECK(!encoder_.get()); // The endpointer needs to estimate the environment/background noise before // starting to treat the audio as user input. In |HandleOnData| we wait until // such time has passed before switching to user input mode. endpointer_.SetEnvironmentEstimationMode(); encoder_.reset(AudioEncoder::Create(codec_, kAudioSampleRate, kNumBitsPerAudioSample)); int samples_per_packet = (kAudioSampleRate * kAudioPacketIntervalMs) / 1000; AudioParameters params(AudioParameters::AUDIO_PCM_LINEAR, kNumAudioChannels, kAudioSampleRate, kNumBitsPerAudioSample, samples_per_packet); audio_controller_ = AudioInputController::Create(this, params); DCHECK(audio_controller_.get()); VLOG(1) << "SpeechRecognizer starting record."; num_samples_recorded_ = 0; audio_controller_->Record(); return true; } void SpeechRecognizer::CancelRecognition() { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO)); DCHECK(audio_controller_.get() || request_.get()); // Stop recording if required. if (audio_controller_.get()) { VLOG(1) << "SpeechRecognizer stopping record."; audio_controller_->Close(); audio_controller_ = NULL; // Releases the ref ptr. } VLOG(1) << "SpeechRecognizer canceling recognition."; encoder_.reset(); request_.reset(); } void SpeechRecognizer::StopRecording() { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO)); // If audio recording has already stopped and we are in recognition phase, // silently ignore any more calls to stop recording. if (!audio_controller_.get()) return; VLOG(1) << "SpeechRecognizer stopping record."; audio_controller_->Close(); audio_controller_ = NULL; // Releases the ref ptr. delegate_->DidCompleteRecording(caller_id_); // UploadAudioChunk requires a non-empty final buffer. So we encode a packet // of silence in case encoder had no data already. std::vector<short> samples((kAudioSampleRate * kAudioPacketIntervalMs) / 1000); encoder_->Encode(&samples[0], samples.size()); encoder_->Flush(); string encoded_data; encoder_->GetEncodedDataAndClear(&encoded_data); DCHECK(!encoded_data.empty()); encoder_.reset(); // If we haven't got any audio yet end the recognition sequence here. if (request_ == NULL) { // Guard against the delegate freeing us until we finish our job. scoped_refptr<SpeechRecognizer> me(this); delegate_->DidCompleteRecognition(caller_id_); } else { request_->UploadAudioChunk(encoded_data, true /* is_last_chunk */); } } // Invoked in the audio thread. void SpeechRecognizer::OnError(AudioInputController* controller, int error_code) { BrowserThread::PostTask(BrowserThread::IO, FROM_HERE, NewRunnableMethod(this, &SpeechRecognizer::HandleOnError, error_code)); } void SpeechRecognizer::HandleOnError(int error_code) { LOG(WARNING) << "SpeechRecognizer::HandleOnError, code=" << error_code; // Check if we are still recording before canceling recognition, as // recording might have been stopped after this error was posted to the queue // by |OnError|. if (!audio_controller_.get()) return; InformErrorAndCancelRecognition(RECOGNIZER_ERROR_CAPTURE); } void SpeechRecognizer::OnData(AudioInputController* controller, const uint8* data, uint32 size) { if (size == 0) // This could happen when recording stops and is normal. return; string* str_data = new string(reinterpret_cast<const char*>(data), size); BrowserThread::PostTask(BrowserThread::IO, FROM_HERE, NewRunnableMethod(this, &SpeechRecognizer::HandleOnData, str_data)); } void SpeechRecognizer::HandleOnData(string* data) { // Check if we are still recording and if not discard this buffer, as // recording might have been stopped after this buffer was posted to the queue // by |OnData|. if (!audio_controller_.get()) { delete data; return; } const short* samples = reinterpret_cast<const short*>(data->data()); DCHECK((data->length() % sizeof(short)) == 0); int num_samples = data->length() / sizeof(short); encoder_->Encode(samples, num_samples); float rms; endpointer_.ProcessAudio(samples, num_samples, &rms); bool did_clip = Clipping(samples, num_samples); delete data; num_samples_recorded_ += num_samples; if (request_ == NULL) { // This was the first audio packet recorded, so start a request to the // server to send the data. request_.reset(new SpeechRecognitionRequest( Profile::GetDefaultRequestContext(), this)); request_->Start(language_, grammar_, hardware_info_, origin_url_, encoder_->mime_type()); } string encoded_data; encoder_->GetEncodedDataAndClear(&encoded_data); DCHECK(!encoded_data.empty()); request_->UploadAudioChunk(encoded_data, false /* is_last_chunk */); if (endpointer_.IsEstimatingEnvironment()) { // Check if we have gathered enough audio for the endpointer to do // environment estimation and should move on to detect speech/end of speech. if (num_samples_recorded_ >= (kEndpointerEstimationTimeMs * kAudioSampleRate) / 1000) { endpointer_.SetUserInputMode(); delegate_->DidCompleteEnvironmentEstimation(caller_id_); } return; // No more processing since we are still estimating environment. } // Check if we have waited too long without hearing any speech. if (!endpointer_.DidStartReceivingSpeech() && num_samples_recorded_ >= kNoSpeechTimeoutSec * kAudioSampleRate) { InformErrorAndCancelRecognition(RECOGNIZER_ERROR_NO_SPEECH); return; } // Calculate the input volume to display in the UI, smoothing towards the // new level. float level = (rms - kAudioMeterMinDb) / (kAudioMeterDbRange / kAudioMeterRangeMaxUnclipped); level = std::min(std::max(0.0f, level), kAudioMeterRangeMaxUnclipped); if (level > audio_level_) { audio_level_ += (level - audio_level_) * kUpSmoothingFactor; } else { audio_level_ += (level - audio_level_) * kDownSmoothingFactor; } float noise_level = (endpointer_.NoiseLevelDb() - kAudioMeterMinDb) / (kAudioMeterDbRange / kAudioMeterRangeMaxUnclipped); noise_level = std::min(std::max(0.0f, noise_level), kAudioMeterRangeMaxUnclipped); delegate_->SetInputVolume(caller_id_, did_clip ? 1.0f : audio_level_, noise_level); if (endpointer_.speech_input_complete()) { StopRecording(); } // TODO(satish): Once we have streaming POST, start sending the data received // here as POST chunks. } void SpeechRecognizer::SetRecognitionResult( bool error, const SpeechInputResultArray& result) { if (error || result.empty()) { InformErrorAndCancelRecognition(error ? RECOGNIZER_ERROR_NETWORK : RECOGNIZER_ERROR_NO_RESULTS); return; } delegate_->SetRecognitionResult(caller_id_, error, result); // Guard against the delegate freeing us until we finish our job. scoped_refptr<SpeechRecognizer> me(this); delegate_->DidCompleteRecognition(caller_id_); } void SpeechRecognizer::InformErrorAndCancelRecognition(ErrorCode error) { CancelRecognition(); // Guard against the delegate freeing us until we finish our job. scoped_refptr<SpeechRecognizer> me(this); delegate_->OnRecognizerError(caller_id_, error); } } // namespace speech_input <commit_msg>Switch from using Speex to FLAC for speech input requests.<commit_after>// Copyright (c) 2011 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 "content/browser/speech/speech_recognizer.h" #include "base/time.h" #include "chrome/browser/profiles/profile.h" #include "chrome/common/net/url_request_context_getter.h" #include "content/browser/browser_thread.h" using media::AudioInputController; using std::string; namespace { // The following constants are related to the volume level indicator shown in // the UI for recorded audio. // Multiplier used when new volume is greater than previous level. const float kUpSmoothingFactor = 1.0f; // Multiplier used when new volume is lesser than previous level. const float kDownSmoothingFactor = 0.7f; // RMS dB value of a maximum (unclipped) sine wave for int16 samples. const float kAudioMeterMaxDb = 90.31f; // This value corresponds to RMS dB for int16 with 6 most-significant-bits = 0. // Values lower than this will display as empty level-meter. const float kAudioMeterMinDb = 30.0f; const float kAudioMeterDbRange = kAudioMeterMaxDb - kAudioMeterMinDb; // Maximum level to draw to display unclipped meter. (1.0f displays clipping.) const float kAudioMeterRangeMaxUnclipped = 47.0f / 48.0f; // Returns true if more than 5% of the samples are at min or max value. bool Clipping(const int16* samples, int num_samples) { int clipping_samples = 0; const int kThreshold = num_samples / 20; for (int i = 0; i < num_samples; ++i) { if (samples[i] <= -32767 || samples[i] >= 32767) { if (++clipping_samples > kThreshold) return true; } } return false; } } // namespace namespace speech_input { const int SpeechRecognizer::kAudioSampleRate = 16000; const int SpeechRecognizer::kAudioPacketIntervalMs = 100; const int SpeechRecognizer::kNumAudioChannels = 1; const int SpeechRecognizer::kNumBitsPerAudioSample = 16; const int SpeechRecognizer::kNoSpeechTimeoutSec = 8; const int SpeechRecognizer::kEndpointerEstimationTimeMs = 300; SpeechRecognizer::SpeechRecognizer(Delegate* delegate, int caller_id, const std::string& language, const std::string& grammar, const std::string& hardware_info, const std::string& origin_url) : delegate_(delegate), caller_id_(caller_id), language_(language), grammar_(grammar), hardware_info_(hardware_info), origin_url_(origin_url), codec_(AudioEncoder::CODEC_FLAC), encoder_(NULL), endpointer_(kAudioSampleRate), num_samples_recorded_(0), audio_level_(0.0f) { endpointer_.set_speech_input_complete_silence_length( base::Time::kMicrosecondsPerSecond / 2); endpointer_.set_long_speech_input_complete_silence_length( base::Time::kMicrosecondsPerSecond); endpointer_.set_long_speech_length(3 * base::Time::kMicrosecondsPerSecond); endpointer_.StartSession(); } SpeechRecognizer::~SpeechRecognizer() { // Recording should have stopped earlier due to the endpointer or // |StopRecording| being called. DCHECK(!audio_controller_.get()); DCHECK(!request_.get() || !request_->HasPendingRequest()); DCHECK(!encoder_.get()); endpointer_.EndSession(); } bool SpeechRecognizer::StartRecording() { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO)); DCHECK(!audio_controller_.get()); DCHECK(!request_.get() || !request_->HasPendingRequest()); DCHECK(!encoder_.get()); // The endpointer needs to estimate the environment/background noise before // starting to treat the audio as user input. In |HandleOnData| we wait until // such time has passed before switching to user input mode. endpointer_.SetEnvironmentEstimationMode(); encoder_.reset(AudioEncoder::Create(codec_, kAudioSampleRate, kNumBitsPerAudioSample)); int samples_per_packet = (kAudioSampleRate * kAudioPacketIntervalMs) / 1000; AudioParameters params(AudioParameters::AUDIO_PCM_LINEAR, kNumAudioChannels, kAudioSampleRate, kNumBitsPerAudioSample, samples_per_packet); audio_controller_ = AudioInputController::Create(this, params); DCHECK(audio_controller_.get()); VLOG(1) << "SpeechRecognizer starting record."; num_samples_recorded_ = 0; audio_controller_->Record(); return true; } void SpeechRecognizer::CancelRecognition() { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO)); DCHECK(audio_controller_.get() || request_.get()); // Stop recording if required. if (audio_controller_.get()) { VLOG(1) << "SpeechRecognizer stopping record."; audio_controller_->Close(); audio_controller_ = NULL; // Releases the ref ptr. } VLOG(1) << "SpeechRecognizer canceling recognition."; encoder_.reset(); request_.reset(); } void SpeechRecognizer::StopRecording() { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO)); // If audio recording has already stopped and we are in recognition phase, // silently ignore any more calls to stop recording. if (!audio_controller_.get()) return; VLOG(1) << "SpeechRecognizer stopping record."; audio_controller_->Close(); audio_controller_ = NULL; // Releases the ref ptr. delegate_->DidCompleteRecording(caller_id_); // UploadAudioChunk requires a non-empty final buffer. So we encode a packet // of silence in case encoder had no data already. std::vector<short> samples((kAudioSampleRate * kAudioPacketIntervalMs) / 1000); encoder_->Encode(&samples[0], samples.size()); encoder_->Flush(); string encoded_data; encoder_->GetEncodedDataAndClear(&encoded_data); DCHECK(!encoded_data.empty()); encoder_.reset(); // If we haven't got any audio yet end the recognition sequence here. if (request_ == NULL) { // Guard against the delegate freeing us until we finish our job. scoped_refptr<SpeechRecognizer> me(this); delegate_->DidCompleteRecognition(caller_id_); } else { request_->UploadAudioChunk(encoded_data, true /* is_last_chunk */); } } // Invoked in the audio thread. void SpeechRecognizer::OnError(AudioInputController* controller, int error_code) { BrowserThread::PostTask(BrowserThread::IO, FROM_HERE, NewRunnableMethod(this, &SpeechRecognizer::HandleOnError, error_code)); } void SpeechRecognizer::HandleOnError(int error_code) { LOG(WARNING) << "SpeechRecognizer::HandleOnError, code=" << error_code; // Check if we are still recording before canceling recognition, as // recording might have been stopped after this error was posted to the queue // by |OnError|. if (!audio_controller_.get()) return; InformErrorAndCancelRecognition(RECOGNIZER_ERROR_CAPTURE); } void SpeechRecognizer::OnData(AudioInputController* controller, const uint8* data, uint32 size) { if (size == 0) // This could happen when recording stops and is normal. return; string* str_data = new string(reinterpret_cast<const char*>(data), size); BrowserThread::PostTask(BrowserThread::IO, FROM_HERE, NewRunnableMethod(this, &SpeechRecognizer::HandleOnData, str_data)); } void SpeechRecognizer::HandleOnData(string* data) { // Check if we are still recording and if not discard this buffer, as // recording might have been stopped after this buffer was posted to the queue // by |OnData|. if (!audio_controller_.get()) { delete data; return; } const short* samples = reinterpret_cast<const short*>(data->data()); DCHECK((data->length() % sizeof(short)) == 0); int num_samples = data->length() / sizeof(short); encoder_->Encode(samples, num_samples); float rms; endpointer_.ProcessAudio(samples, num_samples, &rms); bool did_clip = Clipping(samples, num_samples); delete data; num_samples_recorded_ += num_samples; if (request_ == NULL) { // This was the first audio packet recorded, so start a request to the // server to send the data. request_.reset(new SpeechRecognitionRequest( Profile::GetDefaultRequestContext(), this)); request_->Start(language_, grammar_, hardware_info_, origin_url_, encoder_->mime_type()); } string encoded_data; encoder_->GetEncodedDataAndClear(&encoded_data); DCHECK(!encoded_data.empty()); request_->UploadAudioChunk(encoded_data, false /* is_last_chunk */); if (endpointer_.IsEstimatingEnvironment()) { // Check if we have gathered enough audio for the endpointer to do // environment estimation and should move on to detect speech/end of speech. if (num_samples_recorded_ >= (kEndpointerEstimationTimeMs * kAudioSampleRate) / 1000) { endpointer_.SetUserInputMode(); delegate_->DidCompleteEnvironmentEstimation(caller_id_); } return; // No more processing since we are still estimating environment. } // Check if we have waited too long without hearing any speech. if (!endpointer_.DidStartReceivingSpeech() && num_samples_recorded_ >= kNoSpeechTimeoutSec * kAudioSampleRate) { InformErrorAndCancelRecognition(RECOGNIZER_ERROR_NO_SPEECH); return; } // Calculate the input volume to display in the UI, smoothing towards the // new level. float level = (rms - kAudioMeterMinDb) / (kAudioMeterDbRange / kAudioMeterRangeMaxUnclipped); level = std::min(std::max(0.0f, level), kAudioMeterRangeMaxUnclipped); if (level > audio_level_) { audio_level_ += (level - audio_level_) * kUpSmoothingFactor; } else { audio_level_ += (level - audio_level_) * kDownSmoothingFactor; } float noise_level = (endpointer_.NoiseLevelDb() - kAudioMeterMinDb) / (kAudioMeterDbRange / kAudioMeterRangeMaxUnclipped); noise_level = std::min(std::max(0.0f, noise_level), kAudioMeterRangeMaxUnclipped); delegate_->SetInputVolume(caller_id_, did_clip ? 1.0f : audio_level_, noise_level); if (endpointer_.speech_input_complete()) { StopRecording(); } // TODO(satish): Once we have streaming POST, start sending the data received // here as POST chunks. } void SpeechRecognizer::SetRecognitionResult( bool error, const SpeechInputResultArray& result) { if (error || result.empty()) { InformErrorAndCancelRecognition(error ? RECOGNIZER_ERROR_NETWORK : RECOGNIZER_ERROR_NO_RESULTS); return; } delegate_->SetRecognitionResult(caller_id_, error, result); // Guard against the delegate freeing us until we finish our job. scoped_refptr<SpeechRecognizer> me(this); delegate_->DidCompleteRecognition(caller_id_); } void SpeechRecognizer::InformErrorAndCancelRecognition(ErrorCode error) { CancelRecognition(); // Guard against the delegate freeing us until we finish our job. scoped_refptr<SpeechRecognizer> me(this); delegate_->OnRecognizerError(caller_id_, error); } } // namespace speech_input <|endoftext|>
<commit_before>/* This file is part of Strigi Desktop Search * * Copyright (C) 2006 Jos van den Oever <[email protected]> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public License * along with this library; see the file COPYING.LIB. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. */ #include "base64inputstream.h" #include <cstring> using namespace std; using namespace Strigi; /* code is based on public domain code at http://www.tug.org/ftp/vm/base64-decode.c */ class Base64InputStream::Private { public: Base64InputStream* const p; InputStream* input; const char* pos, * pend; int32_t bits; int32_t nleft; char bytestodo; char char_count; Private(Base64InputStream* p, InputStream* i); bool moreData(); int32_t fillBuffer(char* start, int32_t space); }; const unsigned char alphabet[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; bool inalphabet[256]; unsigned char decoder[133]; bool initializedAlphabet = false; void initialize(); string decode(const char* in, string::size_type length); void initialize() { if (!initializedAlphabet) { initializedAlphabet = true; // initialize the translation arrays for (int i=64; i<256; ++i) { inalphabet[i] = 0; } for (int i=0; i<64; ++i) { inalphabet[alphabet[i]] = true; decoder[alphabet[i]] = i; } } } Base64InputStream::Base64InputStream(InputStream* i) :p(new Private(this, i)) { } Base64InputStream::~Base64InputStream() { delete p; } Base64InputStream::Private::Private(Base64InputStream* bi, InputStream* i) :p(bi), input(i) { initialize(); nleft = 0; char_count = 0; bits = 0; bytestodo = 0; pos = pend = 0; } bool Base64InputStream::Private::moreData() { if (pos == pend) { int32_t nread = input->read(pos, 1, 0); if (nread < -1) { p->m_status = Error; p->m_error = input->error(); input = 0; return false; } if (nread <= 0) { input = 0; return false; } pend = pos + nread; } return true; } int32_t Base64InputStream::fillBuffer(char* start, int32_t space) { return p->fillBuffer(start, space); } int32_t Base64InputStream::Private::fillBuffer(char* start, int32_t space) { if (input == 0 && bytestodo == 0) return -1; // handle the bytes that were left over from the last call if (bytestodo) { switch (bytestodo) { case 3: *start = bits >> 16; break; case 2: *start = (bits >> 8) & 0xff; break; case 1: *start = bits & 0xff; bits = 0; char_count = 0; break; } bytestodo--; return 1; } const char* end = start + space; char* p = start; int32_t nwritten = 0; while (moreData()) { unsigned char c = *pos++; // = signals the end of the encoded block if (c == '=') { if (char_count == 2) { bytestodo = 1; bits >>= 10; } else if (char_count == 3) { bytestodo = 2; bits >>= 8; } input = 0; break; } // we ignore characters that do not fit if (!inalphabet[c]) { continue; } bits += decoder[c]; char_count++; if (char_count == 4) { if (p >= end) { bytestodo = 3; break; } *p++ = bits >> 16; if (p >= end) { bytestodo = 2; nwritten++; break; } *p++ = (bits >> 8) & 0xff; if (p >= end) { bytestodo = 1; nwritten += 2; break; } *p++ = bits & 0xff; bits = 0; char_count = 0; nwritten += 3; } else { bits <<= 6; } } if (nwritten == 0 && input == 0 && bytestodo == 0) { // printf("EOF\n"); nwritten = -1; } return nwritten; } string Base64InputStream::decode(const char* in, string::size_type length) { initialize(); string d; if (length%4) return d; initialize(); int32_t words = length/4; d.reserve(words*3); const unsigned char* c = (const unsigned char*)in; const unsigned char* e = c + length; if (in[length-1] == '=') { e -= 4; } char k, l, b[3]; for (; c < e; c += 4) { if (inalphabet[c[0]] && inalphabet[c[1]] && inalphabet[c[2]] && inalphabet[c[3]]) { k = decoder[c[1]]; l = decoder[c[2]]; b[0] = (decoder[c[0]] << 2) + (k >> 4); b[1] = (k << 4) + (l >> 2); b[2] = (l << 6) + (decoder[c[3]]); d.append(b, 3); } else { return string(); } } if (in[length-2] == '=') { if (inalphabet[c[0]] && inalphabet[c[1]]) { b[0] = (decoder[c[0]] << 2)+((decoder[c[1]] >> 4)); d.append(b, 1); } else { return string(); } } else if (in[length-1] == '=') { if (inalphabet[c[0]] && inalphabet[c[1]] && inalphabet[c[2]]) { k = decoder[c[1]]; b[0] = (decoder[c[0]] << 2) + (k >> 4); b[1] = (k << 4) + (decoder[c[2]] >> 2); d.append(b, 2); } else { return string(); } } return d; } <commit_msg>fix memory leak (CID 4060)<commit_after>/* This file is part of Strigi Desktop Search * * Copyright (C) 2006 Jos van den Oever <[email protected]> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public License * along with this library; see the file COPYING.LIB. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. */ #include "base64inputstream.h" #include <cstring> using namespace std; using namespace Strigi; /* code is based on public domain code at http://www.tug.org/ftp/vm/base64-decode.c */ class Base64InputStream::Private { public: Base64InputStream* const p; InputStream* input; const char* pos, * pend; int32_t bits; int32_t nleft; char bytestodo; char char_count; Private(Base64InputStream* p, InputStream* i); bool moreData(); int32_t fillBuffer(char* start, int32_t space); }; const unsigned char alphabet[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; bool inalphabet[256]; unsigned char decoder[133]; bool initializedAlphabet = false; void initialize(); string decode(const char* in, string::size_type length); void initialize() { if (!initializedAlphabet) { initializedAlphabet = true; // initialize the translation arrays for (int i=64; i<256; ++i) { inalphabet[i] = 0; } for (int i=0; i<64; ++i) { inalphabet[alphabet[i]] = true; decoder[alphabet[i]] = i; } } } Base64InputStream::Base64InputStream(InputStream* i) :p(new Private(this, i)) { } Base64InputStream::~Base64InputStream() { delete p; } Base64InputStream::Private::Private(Base64InputStream* bi, InputStream* i) :p(bi), input(i) { initialize(); nleft = 0; char_count = 0; bits = 0; bytestodo = 0; pos = pend = 0; } bool Base64InputStream::Private::moreData() { if (pos == pend) { int32_t nread = input->read(pos, 1, 0); if (nread < -1) { p->m_status = Error; p->m_error = input->error(); input = 0; return false; } if (nread <= 0) { input = 0; return false; } pend = pos + nread; } return true; } int32_t Base64InputStream::fillBuffer(char* start, int32_t space) { return p->fillBuffer(start, space); } int32_t Base64InputStream::Private::fillBuffer(char* start, int32_t space) { if (input == 0 && bytestodo == 0) return -1; // handle the bytes that were left over from the last call if (bytestodo) { switch (bytestodo) { case 3: *start = bits >> 16; break; case 2: *start = (bits >> 8) & 0xff; break; case 1: *start = bits & 0xff; bits = 0; char_count = 0; break; } bytestodo--; return 1; } const char* end = start + space; char* p = start; int32_t nwritten = 0; while (moreData()) { unsigned char c = *pos++; // = signals the end of the encoded block if (c == '=') { if (char_count == 2) { bytestodo = 1; bits >>= 10; } else if (char_count == 3) { bytestodo = 2; bits >>= 8; } input = 0; break; } // we ignore characters that do not fit if (!inalphabet[c]) { continue; } bits += decoder[c]; char_count++; if (char_count == 4) { if (p >= end) { bytestodo = 3; break; } *p++ = bits >> 16; if (p >= end) { bytestodo = 2; nwritten++; break; } *p++ = (bits >> 8) & 0xff; if (p >= end) { bytestodo = 1; nwritten += 2; break; } *p++ = bits & 0xff; bits = 0; char_count = 0; nwritten += 3; } else { bits <<= 6; } } if (nwritten == 0 && input == 0 && bytestodo == 0) { // printf("EOF\n"); nwritten = -1; } return nwritten; } string Base64InputStream::decode(const char* in, string::size_type length) { initialize(); string d; if (length%4) return d; initialize(); int32_t words = length/4; d.reserve(words*3); const unsigned char* c = (const unsigned char*)in; const unsigned char* e = c + length; if (in[length-1] == '=') { e -= 4; } char k, l, b[3]; for (; c < e; c += 4) { if (inalphabet[c[0]] && inalphabet[c[1]] && inalphabet[c[2]] && inalphabet[c[3]]) { k = decoder[c[1]]; l = decoder[c[2]]; b[0] = (decoder[c[0]] << 2) + (k >> 4); b[1] = (k << 4) + (l >> 2); b[2] = (l << 6) + (decoder[c[3]]); d.append(b, 3); } else { return string(); } } if (in[length-2] == '=') { if (inalphabet[c[0]] && inalphabet[c[1]]) { b[0] = (decoder[c[0]] << 2)+((decoder[c[1]] >> 4)); d.append(b, 1); } else { return string(); } } else if (in[length-1] == '=') { if (inalphabet[c[0]] && inalphabet[c[1]] && inalphabet[c[2]]) { k = decoder[c[1]]; b[0] = (decoder[c[0]] << 2) + (k >> 4); b[1] = (k << 4) + (decoder[c[2]] >> 2); d.append(b, 2); } else { return string(); } } return d; } <|endoftext|>
<commit_before>/** * @file max_ip_impl.hpp * @author Ryan Curtin * * Implementation of the MaxIP class (maximum inner product search). */ #ifndef __MLPACK_METHODS_MAXIP_MAX_IP_IMPL_HPP #define __MLPACK_METHODS_MAXIP_MAX_IP_IMPL_HPP // In case it hasn't yet been included. #include "max_ip.hpp" #include <mlpack/core/tree/traversers/single_cover_tree_traverser.hpp> #include "max_ip_rules.hpp" namespace mlpack { namespace maxip { template<typename KernelType> MaxIP<KernelType>::MaxIP(const arma::mat& referenceSet, bool single, bool naive) : referenceSet(referenceSet), querySet(referenceSet), // Gotta point it somewhere... queryTree(NULL), single(single), naive(naive) { Timer::Start("tree_building"); // Build the tree. Could we do this in the initialization list? if (naive) referenceTree = NULL; else referenceTree = new tree::CoverTree<IPMetric<KernelType> >(referenceSet); Timer::Stop("tree_building"); } template<typename KernelType> MaxIP<KernelType>::MaxIP(const arma::mat& referenceSet, const arma::mat& querySet, bool single, bool naive) : referenceSet(referenceSet), querySet(querySet), single(single), naive(naive) { Timer::Start("tree_building"); // Build the trees. Could we do this in the initialization lists? if (naive) referenceTree = NULL; else referenceTree = new tree::CoverTree<IPMetric<KernelType> >(referenceSet); if (single || naive) queryTree = NULL; else queryTree = new tree::CoverTree<IPMetric<KernelType> >(querySet); Timer::Stop("tree_building"); } template<typename KernelType> MaxIP<KernelType>::~MaxIP() { if (queryTree) delete queryTree; if (referenceTree) delete referenceTree; } template<typename KernelType> void MaxIP<KernelType>::Search(const size_t k, arma::Mat<size_t>& indices, arma::mat& products) { // No remapping will be necessary. indices.set_size(k, querySet.n_cols); products.set_size(k, querySet.n_cols); Timer::Start("computing_products"); // Naive implementation. if (naive) { // Simple double loop. Stupid, slow, but a good benchmark. for (size_t q = 0; q < querySet.n_cols; ++q) { for (size_t r = 0; r < referenceSet.n_cols; ++r) { const double eval = KernelType::Evaluate(querySet.unsafe_col(q), referenceSet.unsafe_col(r)); size_t insertPosition; for (insertPosition = 0; insertPosition < indices.n_rows; ++insertPosition) if (eval > products(insertPosition, q)) break; if (insertPosition < indices.n_rows) InsertNeighbor(indices, products, q, insertPosition, r, eval); } } Timer::Stop("computing_products"); return; } // Single-tree implementation. if (single) { // Calculate number of pruned nodes. size_t numPrunes = 0; // Precalculate query products ( || q || for all q). arma::vec queryProducts(querySet.n_cols); for (size_t queryIndex = 0; queryIndex < querySet.n_cols; ++queryIndex) queryProducts[queryIndex] = KernelType::Evaluate( querySet.unsafe_col(queryIndex), querySet.unsafe_col(queryIndex)); // Screw the CoverTreeTraverser, we'll implement it by hand. for (size_t queryIndex = 0; queryIndex < querySet.n_cols; ++queryIndex) { std::queue<tree::CoverTree<IPMetric<KernelType> >*> pointQueue; std::queue<size_t> parentQueue; std::queue<double> parentEvalQueue; pointQueue.push(referenceTree); parentQueue.push(size_t() - 1); // Has no parent. parentEvalQueue.push(0); // No possible parent evaluation. tree::CoverTree<IPMetric<KernelType> >* referenceNode; size_t currentParent; double currentParentEval; double eval; // Kernel evaluation. while (!pointQueue.empty()) { // Get the information for this node. referenceNode = pointQueue.front(); currentParent = parentQueue.front(); currentParentEval = parentEvalQueue.front(); pointQueue.pop(); parentQueue.pop(); parentEvalQueue.pop(); // See if this has the same parent. if (referenceNode->Point() == currentParent) { // We don't have to evaluate the kernel again. eval = currentParentEval; } else { // Evaluate the kernel. Then see if it is a result to keep. eval = KernelType::Evaluate(querySet.unsafe_col(queryIndex), referenceSet.unsafe_col(referenceNode->Point())); // Is the result good enough to be saved? if (eval > products(products.n_rows - 1, queryIndex)) { // Figure out where to insert. size_t insertPosition = 0; for ( ; insertPosition < products.n_rows - 1; ++insertPosition) if (eval > products(insertPosition, queryIndex)) break; // We are guaranteed that insertPosition is valid. InsertNeighbor(indices, products, queryIndex, insertPosition, referenceNode->Point(), eval); } } // Now discover if we can prune this node or not. double maxProduct = eval + std::pow(referenceNode->ExpansionConstant(), referenceNode->Scale() + 1) * queryProducts[queryIndex]; if (maxProduct > products(products.n_rows - 1, queryIndex)) { // We can't prune. So add our children. for (size_t i = 0; i < referenceNode->NumChildren(); ++i) { pointQueue.push(&(referenceNode->Child(i))); parentQueue.push(referenceNode->Point()); parentEvalQueue.push(eval); } } else { numPrunes++; } } } Log::Info << "Pruned " << numPrunes << " nodes." << std::endl; Timer::Stop("computing_products"); return; } // Double-tree implementation. Log::Fatal << "Dual-tree search not implemented yet... oops..." << std::endl; } /** * Helper function to insert a point into the neighbors and distances matrices. * * @param queryIndex Index of point whose neighbors we are inserting into. * @param pos Position in list to insert into. * @param neighbor Index of reference point which is being inserted. * @param distance Distance from query point to reference point. */ template<typename KernelType> void MaxIP<KernelType>::InsertNeighbor(arma::Mat<size_t>& indices, arma::mat& products, const size_t queryIndex, const size_t pos, const size_t neighbor, const double distance) { // We only memmove() if there is actually a need to shift something. if (pos < (products.n_rows - 1)) { int len = (products.n_rows - 1) - pos; memmove(products.colptr(queryIndex) + (pos + 1), products.colptr(queryIndex) + pos, sizeof(double) * len); memmove(indices.colptr(queryIndex) + (pos + 1), indices.colptr(queryIndex) + pos, sizeof(size_t) * len); } // Now put the new information in the right index. products(pos, queryIndex) = distance; indices(pos, queryIndex) = neighbor; } }; // namespace maxip }; // namespace mlpack #endif <commit_msg>This file doesn't exist. I didn't need it.<commit_after>/** * @file max_ip_impl.hpp * @author Ryan Curtin * * Implementation of the MaxIP class (maximum inner product search). */ #ifndef __MLPACK_METHODS_MAXIP_MAX_IP_IMPL_HPP #define __MLPACK_METHODS_MAXIP_MAX_IP_IMPL_HPP // In case it hasn't yet been included. #include "max_ip.hpp" #include "max_ip_rules.hpp" namespace mlpack { namespace maxip { template<typename KernelType> MaxIP<KernelType>::MaxIP(const arma::mat& referenceSet, bool single, bool naive) : referenceSet(referenceSet), querySet(referenceSet), // Gotta point it somewhere... queryTree(NULL), single(single), naive(naive) { Timer::Start("tree_building"); // Build the tree. Could we do this in the initialization list? if (naive) referenceTree = NULL; else referenceTree = new tree::CoverTree<IPMetric<KernelType> >(referenceSet); Timer::Stop("tree_building"); } template<typename KernelType> MaxIP<KernelType>::MaxIP(const arma::mat& referenceSet, const arma::mat& querySet, bool single, bool naive) : referenceSet(referenceSet), querySet(querySet), single(single), naive(naive) { Timer::Start("tree_building"); // Build the trees. Could we do this in the initialization lists? if (naive) referenceTree = NULL; else referenceTree = new tree::CoverTree<IPMetric<KernelType> >(referenceSet); if (single || naive) queryTree = NULL; else queryTree = new tree::CoverTree<IPMetric<KernelType> >(querySet); Timer::Stop("tree_building"); } template<typename KernelType> MaxIP<KernelType>::~MaxIP() { if (queryTree) delete queryTree; if (referenceTree) delete referenceTree; } template<typename KernelType> void MaxIP<KernelType>::Search(const size_t k, arma::Mat<size_t>& indices, arma::mat& products) { // No remapping will be necessary. indices.set_size(k, querySet.n_cols); products.set_size(k, querySet.n_cols); Timer::Start("computing_products"); // Naive implementation. if (naive) { // Simple double loop. Stupid, slow, but a good benchmark. for (size_t q = 0; q < querySet.n_cols; ++q) { for (size_t r = 0; r < referenceSet.n_cols; ++r) { const double eval = KernelType::Evaluate(querySet.unsafe_col(q), referenceSet.unsafe_col(r)); size_t insertPosition; for (insertPosition = 0; insertPosition < indices.n_rows; ++insertPosition) if (eval > products(insertPosition, q)) break; if (insertPosition < indices.n_rows) InsertNeighbor(indices, products, q, insertPosition, r, eval); } } Timer::Stop("computing_products"); return; } // Single-tree implementation. if (single) { // Calculate number of pruned nodes. size_t numPrunes = 0; // Precalculate query products ( || q || for all q). arma::vec queryProducts(querySet.n_cols); for (size_t queryIndex = 0; queryIndex < querySet.n_cols; ++queryIndex) queryProducts[queryIndex] = KernelType::Evaluate( querySet.unsafe_col(queryIndex), querySet.unsafe_col(queryIndex)); // Screw the CoverTreeTraverser, we'll implement it by hand. for (size_t queryIndex = 0; queryIndex < querySet.n_cols; ++queryIndex) { std::queue<tree::CoverTree<IPMetric<KernelType> >*> pointQueue; std::queue<size_t> parentQueue; std::queue<double> parentEvalQueue; pointQueue.push(referenceTree); parentQueue.push(size_t() - 1); // Has no parent. parentEvalQueue.push(0); // No possible parent evaluation. tree::CoverTree<IPMetric<KernelType> >* referenceNode; size_t currentParent; double currentParentEval; double eval; // Kernel evaluation. while (!pointQueue.empty()) { // Get the information for this node. referenceNode = pointQueue.front(); currentParent = parentQueue.front(); currentParentEval = parentEvalQueue.front(); pointQueue.pop(); parentQueue.pop(); parentEvalQueue.pop(); // See if this has the same parent. if (referenceNode->Point() == currentParent) { // We don't have to evaluate the kernel again. eval = currentParentEval; } else { // Evaluate the kernel. Then see if it is a result to keep. eval = KernelType::Evaluate(querySet.unsafe_col(queryIndex), referenceSet.unsafe_col(referenceNode->Point())); // Is the result good enough to be saved? if (eval > products(products.n_rows - 1, queryIndex)) { // Figure out where to insert. size_t insertPosition = 0; for ( ; insertPosition < products.n_rows - 1; ++insertPosition) if (eval > products(insertPosition, queryIndex)) break; // We are guaranteed that insertPosition is valid. InsertNeighbor(indices, products, queryIndex, insertPosition, referenceNode->Point(), eval); } } // Now discover if we can prune this node or not. double maxProduct = eval + std::pow(referenceNode->ExpansionConstant(), referenceNode->Scale() + 1) * queryProducts[queryIndex]; if (maxProduct > products(products.n_rows - 1, queryIndex)) { // We can't prune. So add our children. for (size_t i = 0; i < referenceNode->NumChildren(); ++i) { pointQueue.push(&(referenceNode->Child(i))); parentQueue.push(referenceNode->Point()); parentEvalQueue.push(eval); } } else { numPrunes++; } } } Log::Info << "Pruned " << numPrunes << " nodes." << std::endl; Timer::Stop("computing_products"); return; } // Double-tree implementation. Log::Fatal << "Dual-tree search not implemented yet... oops..." << std::endl; } /** * Helper function to insert a point into the neighbors and distances matrices. * * @param queryIndex Index of point whose neighbors we are inserting into. * @param pos Position in list to insert into. * @param neighbor Index of reference point which is being inserted. * @param distance Distance from query point to reference point. */ template<typename KernelType> void MaxIP<KernelType>::InsertNeighbor(arma::Mat<size_t>& indices, arma::mat& products, const size_t queryIndex, const size_t pos, const size_t neighbor, const double distance) { // We only memmove() if there is actually a need to shift something. if (pos < (products.n_rows - 1)) { int len = (products.n_rows - 1) - pos; memmove(products.colptr(queryIndex) + (pos + 1), products.colptr(queryIndex) + pos, sizeof(double) * len); memmove(indices.colptr(queryIndex) + (pos + 1), indices.colptr(queryIndex) + pos, sizeof(size_t) * len); } // Now put the new information in the right index. products(pos, queryIndex) = distance; indices(pos, queryIndex) = neighbor; } }; // namespace maxip }; // namespace mlpack #endif <|endoftext|>
<commit_before>// Copyright (c) 2012 Plenluno All rights reserved. #include <assert.h> #include <vector> #include "libj/js_regexp.h" #include "libj/undefined.h" #include "./glue/regexp.h" namespace libj { static glue::RegExp::U16String toU16String(String::CPtr str) { if (Type<char16_t>::id() == Type<uint16_t>::id()) { return str->toStdU16String(); } else { glue::RegExp::U16String s; std::u16string ss = str->toStdU16String(); for (size_t i = 0; i < ss.length(); i++) { s.push_back(ss[i]); } return s; } } class JsRegExpImpl : public JsRegExp { public: static Ptr create(String::CPtr pattern, UInt flags) { JsRegExpImpl* impl = new JsRegExpImpl(pattern, flags); if (impl->re_) { Ptr p(impl); return p; } else { return null(); } } Boolean global() const { return re_->global(); } Boolean ignoreCase() const { return re_->ignoreCase(); } Boolean multiline() const { return re_->multiline(); } String::CPtr source() const { return pattern_; } JsArray::Ptr exec(String::CPtr str) const { static const String::CPtr index = String::create("index"); static const String::CPtr input = String::create("input"); if (!str) { return JsArray::null(); } std::vector<int> captures; if (!re_->execute(toU16String(str), 0, captures)) { return JsArray::null(); } JsArray::Ptr res = JsArray::create(); Size len = captures.size(); assert(len > 0); for (Size i = 0; i < len; i += 2) { if (captures[i] >= 0 && captures[i+1] >= 0 && captures[i] < captures[i+1] && captures[i+1] <= static_cast<int>(str->length())) { res->add(str->substring(captures[i], captures[i+1])); } else { res->add(Undefined::instance()); } } res->setProperty(input, str); res->setProperty(index, captures[0]); return res; } Boolean test(String::CPtr str) const { return !!exec(str); } private: JsObject::Ptr obj_; String::CPtr pattern_; glue::RegExp* re_; JsRegExpImpl(String::CPtr pattern, UInt flags) : obj_(JsObject::create()) , pattern_(pattern) , re_(glue::RegExp::create(toU16String(pattern), flags)) {} public: ~JsRegExpImpl() { delete re_; } LIBJ_JS_OBJECT_IMPL(obj_); }; JsRegExp::Ptr JsRegExp::create(String::CPtr pattern, UInt flags) { return JsRegExpImpl::create(pattern, flags); } } // namespace libj <commit_msg>use LIBJ_USE_CXX11<commit_after>// Copyright (c) 2012 Plenluno All rights reserved. #include <assert.h> #include <vector> #include "libj/js_regexp.h" #include "libj/undefined.h" #include "./glue/regexp.h" namespace libj { static glue::RegExp::U16String toU16String(String::CPtr str) { #ifdef LIBJ_USE_CXX11 glue::RegExp::U16String s; std::u16string ss = str->toStdU16String(); for (size_t i = 0; i < ss.length(); i++) { s.push_back(ss[i]); } return s; #else return str->toStdU16String(); #endif } class JsRegExpImpl : public JsRegExp { public: static Ptr create(String::CPtr pattern, UInt flags) { JsRegExpImpl* impl = new JsRegExpImpl(pattern, flags); if (impl->re_) { Ptr p(impl); return p; } else { return null(); } } Boolean global() const { return re_->global(); } Boolean ignoreCase() const { return re_->ignoreCase(); } Boolean multiline() const { return re_->multiline(); } String::CPtr source() const { return pattern_; } JsArray::Ptr exec(String::CPtr str) const { static const String::CPtr index = String::create("index"); static const String::CPtr input = String::create("input"); if (!str) { return JsArray::null(); } std::vector<int> captures; if (!re_->execute(toU16String(str), 0, captures)) { return JsArray::null(); } JsArray::Ptr res = JsArray::create(); Size len = captures.size(); assert(len > 0); for (Size i = 0; i < len; i += 2) { if (captures[i] >= 0 && captures[i+1] >= 0 && captures[i] < captures[i+1] && captures[i+1] <= static_cast<int>(str->length())) { res->add(str->substring(captures[i], captures[i+1])); } else { res->add(Undefined::instance()); } } res->setProperty(input, str); res->setProperty(index, captures[0]); return res; } Boolean test(String::CPtr str) const { return !!exec(str); } private: JsObject::Ptr obj_; String::CPtr pattern_; glue::RegExp* re_; JsRegExpImpl(String::CPtr pattern, UInt flags) : obj_(JsObject::create()) , pattern_(pattern) , re_(glue::RegExp::create(toU16String(pattern), flags)) {} public: ~JsRegExpImpl() { delete re_; } LIBJ_JS_OBJECT_IMPL(obj_); }; JsRegExp::Ptr JsRegExp::create(String::CPtr pattern, UInt flags) { return JsRegExpImpl::create(pattern, flags); } } // namespace libj <|endoftext|>
<commit_before>/* * opencog/util/Logger.cc * * Copyright (C) 2002-2007 Novamente LLC * Copyright (C) 2008 by Singularity Institute for Artificial Intelligence * All Rights Reserved * * Written by Andre Senna <[email protected]> * Gustavo Gama <[email protected]> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License v3 as * published by the Free Software Foundation and including the exceptions * at http://opencog.org/wiki/Licenses * * 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 Affero General Public License * along with this program; if not, write to: * Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include "Logger.h" #include <execinfo.h> #include <stdlib.h> #include <stdarg.h> #include <time.h> #ifdef WIN32 #include <winsock2.h> #undef ERROR #undef DEBUG #else #include <sys/time.h> #endif #include <opencog/util/platform.h> using namespace opencog; // messages greater than this will be truncated #define MAX_PRINTF_STYLE_MESSAGE_SIZE (1<<15) const char* levelStrings[] = {"ERROR", "WARN", "INFO", "DEBUG", "FINE"}; Logger::~Logger() { if (f != NULL) fclose(f); } Logger::Logger(const std::string &fileName, Logger::Level level, bool timestampEnabled) { this->fileName.assign(fileName); this->currentLevel = level; this->timestampEnabled = timestampEnabled; this->printToStdout = false; this->logEnabled = true; this->f = NULL; pthread_mutex_init(&lock, NULL); } // ***********************************************/ // API void Logger::setLevel(Logger::Level newLevel) { currentLevel = newLevel; } Logger::Level Logger::getLevel() const { return currentLevel; } void Logger::setFilename(const std::string& s) { fileName.assign(s); if (f != NULL) fclose(f); f = NULL; enable(); } const std::string& Logger::getFilename() { return fileName; } void Logger::setTimestampFlag(bool flag) { timestampEnabled = flag; } void Logger::setPrintToStdoutFlag(bool flag) { printToStdout = flag; } void Logger::enable() { logEnabled = true; } void Logger::disable() { logEnabled = false; } static void prt_backtrace(FILE *fh) { #define BT_BUFSZ 50 void *bt_buf[BT_BUFSZ]; int stack_depth = backtrace(bt_buf, BT_BUFSZ); char **syms = backtrace_symbols(bt_buf, stack_depth); // Start printing at a bit into the stack, so as to avoid recording // the logger functions in the stack trace. for (int i=2; i< stack_depth; i++) { fprintf(fh, "%s\n", syms[i]); } free(syms); } void Logger::log(Logger::Level level, const std::string &txt) { if (!logEnabled) return; // delay opening the file until the first logging statement is issued; // this allows us to set the main logger's filename without creating // a useless log file with the default filename if (f == NULL) { if ((f = fopen(fileName.c_str(), "a")) == NULL) { fprintf(stderr, "[ERROR] Unable to open log file \"%s\"\n", fileName.c_str()); disable(); return; } else enable(); } if (level <= currentLevel) { pthread_mutex_lock(&lock); if (timestampEnabled) { char timestamp[64]; struct timeval stv; struct tm stm; ::gettimeofday(&stv, NULL); time_t t = stv.tv_sec; gmtime_r(&t, &stm); strftime(timestamp, sizeof(timestamp), "%F %T", &stm); fprintf(f, "[%s:%03ld] ", timestamp, stv.tv_usec / 1000); if (printToStdout) fprintf(stdout, "[%s:%03ld] ", timestamp, stv.tv_usec / 1000); } fprintf(f, "[%s] %s\n", getLevelString(level), txt.c_str()); if (printToStdout) fprintf(stdout, "[%s] %s\n", getLevelString(level), txt.c_str()); fflush(f); // Print a backtrace for warnings and errors. if (level <= WARN) { prt_backtrace(f); } fflush(f); pthread_mutex_unlock(&lock); } } void Logger::error(const std::string &txt) { log(ERROR, txt); } void Logger::warn (const std::string &txt) { log(WARN, txt); } void Logger::info (const std::string &txt) { log(INFO, txt); } void Logger::debug(const std::string &txt) { log(DEBUG, txt); } void Logger::fine (const std::string &txt) { log(FINE, txt); } void Logger::logva(Logger::Level level, const char *fmt, va_list args) { if (level <= currentLevel) { char buffer[MAX_PRINTF_STYLE_MESSAGE_SIZE]; vsnprintf(buffer, sizeof(buffer), fmt, args); std::string msg = buffer; log(level, msg); } } void Logger::log(Logger::Level level, const char *fmt, ...) { va_list args; va_start(args, fmt); logva(level, fmt, args); va_end(args); } void Logger::error(const char *fmt, ...) { va_list args; va_start(args, fmt); logva(ERROR, fmt, args); va_end(args); } void Logger::warn (const char *fmt, ...) { va_list args; va_start(args, fmt); logva(WARN, fmt, args); va_end(args); } void Logger::info (const char *fmt, ...) { va_list args; va_start(args, fmt); logva(INFO, fmt, args); va_end(args); } void Logger::debug(const char *fmt, ...) { va_list args; va_start(args, fmt); logva(DEBUG, fmt, args); va_end(args); } void Logger::fine (const char *fmt, ...) { va_list args; va_start(args, fmt); logva(FINE, fmt, args); va_end(args); } const char* Logger::getLevelString(const Logger::Level level) { return levelStrings[level]; } const Logger::Level Logger::getLevelFromString(const std::string& levelStr) { unsigned int nLevels = sizeof(levelStrings) / sizeof(levelStrings[0]); for (unsigned int i = 0; i < nLevels; ++i) { if (strcasecmp(levelStrings[i], levelStr.c_str()) == 0) return ((Logger::Level) i); } return ((Logger::Level) - 1); } // create and return the single instance Logger& opencog::logger() { static Logger instance; return instance; } <commit_msg>beutify the stack trace printing message just a little bit.<commit_after>/* * opencog/util/Logger.cc * * Copyright (C) 2002-2007 Novamente LLC * Copyright (C) 2008 by Singularity Institute for Artificial Intelligence * All Rights Reserved * * Written by Andre Senna <[email protected]> * Gustavo Gama <[email protected]> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License v3 as * published by the Free Software Foundation and including the exceptions * at http://opencog.org/wiki/Licenses * * 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 Affero General Public License * along with this program; if not, write to: * Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include "Logger.h" #include <execinfo.h> #include <stdlib.h> #include <stdarg.h> #include <time.h> #ifdef WIN32 #include <winsock2.h> #undef ERROR #undef DEBUG #else #include <sys/time.h> #endif #include <opencog/util/platform.h> using namespace opencog; // messages greater than this will be truncated #define MAX_PRINTF_STYLE_MESSAGE_SIZE (1<<15) const char* levelStrings[] = {"ERROR", "WARN", "INFO", "DEBUG", "FINE"}; Logger::~Logger() { if (f != NULL) fclose(f); } Logger::Logger(const std::string &fileName, Logger::Level level, bool timestampEnabled) { this->fileName.assign(fileName); this->currentLevel = level; this->timestampEnabled = timestampEnabled; this->printToStdout = false; this->logEnabled = true; this->f = NULL; pthread_mutex_init(&lock, NULL); } // ***********************************************/ // API void Logger::setLevel(Logger::Level newLevel) { currentLevel = newLevel; } Logger::Level Logger::getLevel() const { return currentLevel; } void Logger::setFilename(const std::string& s) { fileName.assign(s); if (f != NULL) fclose(f); f = NULL; enable(); } const std::string& Logger::getFilename() { return fileName; } void Logger::setTimestampFlag(bool flag) { timestampEnabled = flag; } void Logger::setPrintToStdoutFlag(bool flag) { printToStdout = flag; } void Logger::enable() { logEnabled = true; } void Logger::disable() { logEnabled = false; } static void prt_backtrace(FILE *fh) { #define BT_BUFSZ 50 void *bt_buf[BT_BUFSZ]; int stack_depth = backtrace(bt_buf, BT_BUFSZ); char **syms = backtrace_symbols(bt_buf, stack_depth); // Start printing at a bit into the stack, so as to avoid recording // the logger functions in the stack trace. fprintf(fh, "\tStack Trace:\n"); for (int i=2; i< stack_depth; i++) { fprintf(fh, "\t%d: %s\n", i, syms[i]); } fprintf(fh, "\n"); free(syms); } void Logger::log(Logger::Level level, const std::string &txt) { if (!logEnabled) return; // delay opening the file until the first logging statement is issued; // this allows us to set the main logger's filename without creating // a useless log file with the default filename if (f == NULL) { if ((f = fopen(fileName.c_str(), "a")) == NULL) { fprintf(stderr, "[ERROR] Unable to open log file \"%s\"\n", fileName.c_str()); disable(); return; } else enable(); } if (level <= currentLevel) { pthread_mutex_lock(&lock); if (timestampEnabled) { char timestamp[64]; struct timeval stv; struct tm stm; ::gettimeofday(&stv, NULL); time_t t = stv.tv_sec; gmtime_r(&t, &stm); strftime(timestamp, sizeof(timestamp), "%F %T", &stm); fprintf(f, "[%s:%03ld] ", timestamp, stv.tv_usec / 1000); if (printToStdout) fprintf(stdout, "[%s:%03ld] ", timestamp, stv.tv_usec / 1000); } fprintf(f, "[%s] %s\n", getLevelString(level), txt.c_str()); if (printToStdout) fprintf(stdout, "[%s] %s\n", getLevelString(level), txt.c_str()); fflush(f); // Print a backtrace for warnings and errors. if (level <= WARN) { prt_backtrace(f); } fflush(f); pthread_mutex_unlock(&lock); } } void Logger::error(const std::string &txt) { log(ERROR, txt); } void Logger::warn (const std::string &txt) { log(WARN, txt); } void Logger::info (const std::string &txt) { log(INFO, txt); } void Logger::debug(const std::string &txt) { log(DEBUG, txt); } void Logger::fine (const std::string &txt) { log(FINE, txt); } void Logger::logva(Logger::Level level, const char *fmt, va_list args) { if (level <= currentLevel) { char buffer[MAX_PRINTF_STYLE_MESSAGE_SIZE]; vsnprintf(buffer, sizeof(buffer), fmt, args); std::string msg = buffer; log(level, msg); } } void Logger::log(Logger::Level level, const char *fmt, ...) { va_list args; va_start(args, fmt); logva(level, fmt, args); va_end(args); } void Logger::error(const char *fmt, ...) { va_list args; va_start(args, fmt); logva(ERROR, fmt, args); va_end(args); } void Logger::warn (const char *fmt, ...) { va_list args; va_start(args, fmt); logva(WARN, fmt, args); va_end(args); } void Logger::info (const char *fmt, ...) { va_list args; va_start(args, fmt); logva(INFO, fmt, args); va_end(args); } void Logger::debug(const char *fmt, ...) { va_list args; va_start(args, fmt); logva(DEBUG, fmt, args); va_end(args); } void Logger::fine (const char *fmt, ...) { va_list args; va_start(args, fmt); logva(FINE, fmt, args); va_end(args); } const char* Logger::getLevelString(const Logger::Level level) { return levelStrings[level]; } const Logger::Level Logger::getLevelFromString(const std::string& levelStr) { unsigned int nLevels = sizeof(levelStrings) / sizeof(levelStrings[0]); for (unsigned int i = 0; i < nLevels; ++i) { if (strcasecmp(levelStrings[i], levelStr.c_str()) == 0) return ((Logger::Level) i); } return ((Logger::Level) - 1); } // create and return the single instance Logger& opencog::logger() { static Logger instance; return instance; } <|endoftext|>
<commit_before>/* * opencog/util/Logger.cc * * Copyright (C) 2002-2007 Novamente LLC * Copyright (C) 2008 by OpenCog Foundation * Copyright (C) 2009, 2011 Linas Vepstas * Copyright (C) 2010 OpenCog Foundation * All Rights Reserved * * Written by Andre Senna <[email protected]> * Gustavo Gama <[email protected]> * Joel Pitt <[email protected]> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License v3 as * published by the Free Software Foundation and including the exceptions * at http://opencog.org/wiki/Licenses * * 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 Affero General Public License * along with this program; if not, write to: * Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include "Logger.h" #include "Config.h" #include <pthread.h> #define pthread_yield sched_yield #ifndef WIN32 #include <cxxabi.h> #include <execinfo.h> #endif #include <iostream> #include <stdlib.h> #include <stdarg.h> #include <time.h> #include <sstream> #ifdef WIN32_NOT_UNIX #include <winsock2.h> #undef ERROR #undef DEBUG #else #include <sys/time.h> #endif #include <boost/algorithm/string.hpp> #include <opencog/util/platform.h> using namespace opencog; // messages greater than this will be truncated #define MAX_PRINTF_STYLE_MESSAGE_SIZE (1<<15) const char* levelStrings[] = {"NONE", "ERROR", "WARN", "INFO", "DEBUG", "FINE"}; #ifndef WIN32 /// @todo backtrace and backtrace_symbols is UNIX, we /// may need a WIN32 version static void prt_backtrace(std::ostringstream& oss) { #define BT_BUFSZ 50 void *bt_buf[BT_BUFSZ]; int stack_depth = backtrace(bt_buf, BT_BUFSZ); char **syms = backtrace_symbols(bt_buf, stack_depth); // Start printing at a bit into the stack, so as to avoid recording // the logger functions in the stack trace. oss << "\tStack Trace:\n"; for (int i=2; i < stack_depth; i++) { // Most things we'll print are mangled C++ names, // So demangle them, get them to pretty-print. char * begin = strchr(syms[i], '('); char * end = strchr(syms[i], '+'); if (!(begin && end) || end <= begin) { // Failed to pull apart the symbol names oss << "\t" << i << ": " << syms[i] << "\n"; } else { *begin = 0x0; oss << "\t" << i << ": " << syms[i] << " "; *begin = '('; size_t sz = 250; int status; char *fname = (char *) malloc(sz); *end = 0x0; char *rv = abi::__cxa_demangle(begin+1, fname, &sz, &status); *end = '+'; if (rv) fname = rv; // might have re-alloced oss << "(" << fname << " " << end << std::endl; free(fname); } } oss << std::endl; free(syms); } #endif Logger::~Logger() { #ifdef ASYNC_LOGGING // Wait for queue to empty flush(); stopWriteLoop(); #endif if (f != NULL) fclose(f); } #ifdef ASYNC_LOGGING void Logger::startWriteLoop() { pthread_mutex_lock(&lock); if (!writingLoopActive) { writingLoopActive = true; m_Thread = boost::thread(&Logger::writingLoop, this); } pthread_mutex_unlock(&lock); } void Logger::stopWriteLoop() { pthread_mutex_lock(&lock); pendingMessagesToWrite.cancel(); // rejoin thread m_Thread.join(); writingLoopActive = false; pthread_mutex_unlock(&lock); } void Logger::writingLoop() { try { while (true) { // Must not pop until *after* the message has been written, // as otherwise, the flush() call will race with the write, // causing flush to report an empty queue, even though the // message has not actually been written yet. std::string* msg; pendingMessagesToWrite.wait_and_get(msg); writeMsg(*msg); pendingMessagesToWrite.pop(); delete msg; } } catch (concurrent_queue< std::string* >::Canceled &e) { return; } } void Logger::flush() { while (!pendingMessagesToWrite.empty()) { pthread_yield(); usleep(100); } } #endif void Logger::writeMsg(std::string &msg) { pthread_mutex_lock(&lock); // delay opening the file until the first logging statement is issued; // this allows us to set the main logger's filename without creating // a useless log file with the default filename if (f == NULL) { if ((f = fopen(fileName.c_str(), "a")) == NULL) { fprintf(stderr, "[ERROR] Unable to open log file \"%s\"\n", fileName.c_str()); pthread_mutex_unlock(&lock); disable(); return; } else enable(); } // write to file fprintf(f, "%s", msg.c_str()); fflush(f); pthread_mutex_unlock(&lock); // write to stdout if (printToStdout) { std::cout << msg; std::cout.flush(); } } Logger::Logger(const std::string &fname, Logger::Level level, bool tsEnabled) : error(*this), warn(*this), info(*this), debug(*this), fine(*this) { this->fileName.assign(fname); this->currentLevel = level; this->backTraceLevel = getLevelFromString(opencog::config()["BACK_TRACE_LOG_LEVEL"]); this->timestampEnabled = tsEnabled; this->printToStdout = false; this->logEnabled = true; this->f = NULL; pthread_mutex_init(&lock, NULL); #ifdef ASYNC_LOGGING this->writingLoopActive = false; startWriteLoop(); #endif // ASYNC_LOGGING } Logger::Logger(const Logger& log) : error(*this), warn(*this), info(*this), debug(*this), fine(*this) { pthread_mutex_init(&lock, NULL); set(log); } Logger& Logger::operator=(const Logger& log) { #ifdef ASYNC_LOGGING this->stopWriteLoop(); pendingMessagesToWrite.cancel_reset(); #endif // ASYNC_LOGGING this->set(log); return *this; } void Logger::set(const Logger& log) { pthread_mutex_lock(&lock); this->fileName.assign(log.fileName); this->currentLevel = log.currentLevel; this->backTraceLevel = log.backTraceLevel; this->timestampEnabled = log.timestampEnabled; this->printToStdout = log.printToStdout; this->logEnabled = log.logEnabled; this->f = log.f; pthread_mutex_unlock(&lock); #ifdef ASYNC_LOGGING startWriteLoop(); #endif // ASYNC_LOGGING } // ***********************************************/ // API void Logger::setLevel(Logger::Level newLevel) { currentLevel = newLevel; } Logger::Level Logger::getLevel() const { return currentLevel; } void Logger::setBackTraceLevel(Logger::Level newLevel) { backTraceLevel = newLevel; } Logger::Level Logger::getBackTraceLevel() const { return backTraceLevel; } void Logger::setFilename(const std::string& s) { fileName.assign(s); pthread_mutex_lock(&lock); if (f != NULL) fclose(f); f = NULL; pthread_mutex_unlock(&lock); enable(); } const std::string& Logger::getFilename() { return fileName; } void Logger::setTimestampFlag(bool flag) { timestampEnabled = flag; } void Logger::setPrintToStdoutFlag(bool flag) { printToStdout = flag; } void Logger::setPrintErrorLevelStdout() { setPrintToStdoutFlag(true); setLevel(Logger::ERROR); } void Logger::enable() { logEnabled = true; } void Logger::disable() { logEnabled = false; } void Logger::log(Logger::Level level, const std::string &txt) { #ifdef ASYNC_LOGGING static const unsigned int max_queue_size_allowed = 1024; #endif static char timestamp[64]; static char timestampStr[256]; // Don't log if not enabled, or level is too low. if (!logEnabled) return; if (level > currentLevel) return; std::ostringstream oss; if (timestampEnabled) { struct timeval stv; struct tm stm; ::gettimeofday(&stv, NULL); time_t t = stv.tv_sec; gmtime_r(&t, &stm); strftime(timestamp, sizeof(timestamp), "%F %T", &stm); snprintf(timestampStr, sizeof(timestampStr), "[%s:%03ld] ",timestamp, stv.tv_usec / 1000); oss << timestampStr; } oss << "[" << getLevelString(level) << "] " << txt << std::endl; if (level <= backTraceLevel) { #ifndef WIN32 prt_backtrace(oss); #endif } #ifdef ASYNC_LOGGING pendingMessagesToWrite.push(new std::string(oss.str())); // If the queue gets too full, block until it's flushed to file or // stdout if (pendingMessagesToWrite.approx_size() > max_queue_size_allowed) { flush(); } #else std::string temp(oss.str()); writeMsg(temp); #endif } void Logger::logva(Logger::Level level, const char *fmt, va_list args) { if (level <= currentLevel) { char buffer[MAX_PRINTF_STYLE_MESSAGE_SIZE]; vsnprintf(buffer, sizeof(buffer), fmt, args); std::string msg = buffer; log(level, msg); } } void Logger::log(Logger::Level level, const char *fmt, ...) { va_list args; va_start(args, fmt); logva(level, fmt, args); va_end(args); } void Logger::Error::operator()(const char *fmt, ...) { va_list args; va_start(args, fmt); logger.logva(ERROR, fmt, args); va_end(args); } void Logger::Warn::operator()(const char *fmt, ...) { va_list args; va_start(args, fmt); logger.logva(WARN, fmt, args); va_end(args); } void Logger::Info::operator()(const char *fmt, ...) { va_list args; va_start(args, fmt); logger.logva(INFO, fmt, args); va_end(args); } void Logger::Debug::operator()(const char *fmt, ...) { va_list args; va_start(args, fmt); logger.logva(DEBUG, fmt, args); va_end(args); } void Logger::Fine::operator()(const char *fmt, ...) { va_list args; va_start(args, fmt); logger.logva(FINE, fmt, args); va_end(args); } bool Logger::isEnabled(Level level) const { return level <= currentLevel; } bool Logger::isErrorEnabled() const { return ERROR <= currentLevel; } bool Logger::isWarnEnabled() const { return WARN <= currentLevel; } bool Logger::isInfoEnabled() const { return INFO <= currentLevel; } bool Logger::isDebugEnabled() const { return DEBUG <= currentLevel; } bool Logger::isFineEnabled() const { return FINE <= currentLevel; } const char* Logger::getLevelString(const Logger::Level level) { if (level == BAD_LEVEL) return "Bad level"; else return levelStrings[level]; } const Logger::Level Logger::getLevelFromString(const std::string& levelStr) { unsigned int nLevels = sizeof(levelStrings) / sizeof(levelStrings[0]); for (unsigned int i = 0; i < nLevels; ++i) { if (boost::iequals(levelStrings[i], levelStr)) return (Logger::Level) i; } return BAD_LEVEL; } // create and return the single instance Logger& opencog::logger() { static Logger instance; return instance; } <commit_msg>logger: if we are going to do this OSX thing, lets do it correctly.<commit_after>/* * opencog/util/Logger.cc * * Copyright (C) 2002-2007 Novamente LLC * Copyright (C) 2008 by OpenCog Foundation * Copyright (C) 2009, 2011 Linas Vepstas * Copyright (C) 2010 OpenCog Foundation * All Rights Reserved * * Written by Andre Senna <[email protected]> * Gustavo Gama <[email protected]> * Joel Pitt <[email protected]> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License v3 as * published by the Free Software Foundation and including the exceptions * at http://opencog.org/wiki/Licenses * * 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 Affero General Public License * along with this program; if not, write to: * Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include "Logger.h" #include "Config.h" #ifndef WIN32 #include <cxxabi.h> #include <execinfo.h> #endif #include <iostream> #include <sstream> #include <pthread.h> #include <sched.h> #include <stdarg.h> #include <stdlib.h> #include <time.h> #ifdef WIN32_NOT_UNIX #include <winsock2.h> #undef ERROR #undef DEBUG #else #include <sys/time.h> #endif #include <boost/algorithm/string.hpp> #include <opencog/util/platform.h> using namespace opencog; // messages greater than this will be truncated #define MAX_PRINTF_STYLE_MESSAGE_SIZE (1<<15) const char* levelStrings[] = {"NONE", "ERROR", "WARN", "INFO", "DEBUG", "FINE"}; #ifndef WIN32 /// @todo backtrace and backtrace_symbols is UNIX, we /// may need a WIN32 version static void prt_backtrace(std::ostringstream& oss) { #define BT_BUFSZ 50 void *bt_buf[BT_BUFSZ]; int stack_depth = backtrace(bt_buf, BT_BUFSZ); char **syms = backtrace_symbols(bt_buf, stack_depth); // Start printing at a bit into the stack, so as to avoid recording // the logger functions in the stack trace. oss << "\tStack Trace:\n"; for (int i=2; i < stack_depth; i++) { // Most things we'll print are mangled C++ names, // So demangle them, get them to pretty-print. char * begin = strchr(syms[i], '('); char * end = strchr(syms[i], '+'); if (!(begin && end) || end <= begin) { // Failed to pull apart the symbol names oss << "\t" << i << ": " << syms[i] << "\n"; } else { *begin = 0x0; oss << "\t" << i << ": " << syms[i] << " "; *begin = '('; size_t sz = 250; int status; char *fname = (char *) malloc(sz); *end = 0x0; char *rv = abi::__cxa_demangle(begin+1, fname, &sz, &status); *end = '+'; if (rv) fname = rv; // might have re-alloced oss << "(" << fname << " " << end << std::endl; free(fname); } } oss << std::endl; free(syms); } #endif Logger::~Logger() { #ifdef ASYNC_LOGGING // Wait for queue to empty flush(); stopWriteLoop(); #endif if (f != NULL) fclose(f); } #ifdef ASYNC_LOGGING void Logger::startWriteLoop() { pthread_mutex_lock(&lock); if (!writingLoopActive) { writingLoopActive = true; m_Thread = boost::thread(&Logger::writingLoop, this); } pthread_mutex_unlock(&lock); } void Logger::stopWriteLoop() { pthread_mutex_lock(&lock); pendingMessagesToWrite.cancel(); // rejoin thread m_Thread.join(); writingLoopActive = false; pthread_mutex_unlock(&lock); } void Logger::writingLoop() { try { while (true) { // Must not pop until *after* the message has been written, // as otherwise, the flush() call will race with the write, // causing flush to report an empty queue, even though the // message has not actually been written yet. std::string* msg; pendingMessagesToWrite.wait_and_get(msg); writeMsg(*msg); pendingMessagesToWrite.pop(); delete msg; } } catch (concurrent_queue< std::string* >::Canceled &e) { return; } } void Logger::flush() { while (!pendingMessagesToWrite.empty()) { sched_yield(); usleep(100); } } #endif void Logger::writeMsg(std::string &msg) { pthread_mutex_lock(&lock); // delay opening the file until the first logging statement is issued; // this allows us to set the main logger's filename without creating // a useless log file with the default filename if (f == NULL) { if ((f = fopen(fileName.c_str(), "a")) == NULL) { fprintf(stderr, "[ERROR] Unable to open log file \"%s\"\n", fileName.c_str()); pthread_mutex_unlock(&lock); disable(); return; } else enable(); } // write to file fprintf(f, "%s", msg.c_str()); fflush(f); pthread_mutex_unlock(&lock); // write to stdout if (printToStdout) { std::cout << msg; std::cout.flush(); } } Logger::Logger(const std::string &fname, Logger::Level level, bool tsEnabled) : error(*this), warn(*this), info(*this), debug(*this), fine(*this) { this->fileName.assign(fname); this->currentLevel = level; this->backTraceLevel = getLevelFromString(opencog::config()["BACK_TRACE_LOG_LEVEL"]); this->timestampEnabled = tsEnabled; this->printToStdout = false; this->logEnabled = true; this->f = NULL; pthread_mutex_init(&lock, NULL); #ifdef ASYNC_LOGGING this->writingLoopActive = false; startWriteLoop(); #endif // ASYNC_LOGGING } Logger::Logger(const Logger& log) : error(*this), warn(*this), info(*this), debug(*this), fine(*this) { pthread_mutex_init(&lock, NULL); set(log); } Logger& Logger::operator=(const Logger& log) { #ifdef ASYNC_LOGGING this->stopWriteLoop(); pendingMessagesToWrite.cancel_reset(); #endif // ASYNC_LOGGING this->set(log); return *this; } void Logger::set(const Logger& log) { pthread_mutex_lock(&lock); this->fileName.assign(log.fileName); this->currentLevel = log.currentLevel; this->backTraceLevel = log.backTraceLevel; this->timestampEnabled = log.timestampEnabled; this->printToStdout = log.printToStdout; this->logEnabled = log.logEnabled; this->f = log.f; pthread_mutex_unlock(&lock); #ifdef ASYNC_LOGGING startWriteLoop(); #endif // ASYNC_LOGGING } // ***********************************************/ // API void Logger::setLevel(Logger::Level newLevel) { currentLevel = newLevel; } Logger::Level Logger::getLevel() const { return currentLevel; } void Logger::setBackTraceLevel(Logger::Level newLevel) { backTraceLevel = newLevel; } Logger::Level Logger::getBackTraceLevel() const { return backTraceLevel; } void Logger::setFilename(const std::string& s) { fileName.assign(s); pthread_mutex_lock(&lock); if (f != NULL) fclose(f); f = NULL; pthread_mutex_unlock(&lock); enable(); } const std::string& Logger::getFilename() { return fileName; } void Logger::setTimestampFlag(bool flag) { timestampEnabled = flag; } void Logger::setPrintToStdoutFlag(bool flag) { printToStdout = flag; } void Logger::setPrintErrorLevelStdout() { setPrintToStdoutFlag(true); setLevel(Logger::ERROR); } void Logger::enable() { logEnabled = true; } void Logger::disable() { logEnabled = false; } void Logger::log(Logger::Level level, const std::string &txt) { #ifdef ASYNC_LOGGING static const unsigned int max_queue_size_allowed = 1024; #endif static char timestamp[64]; static char timestampStr[256]; // Don't log if not enabled, or level is too low. if (!logEnabled) return; if (level > currentLevel) return; std::ostringstream oss; if (timestampEnabled) { struct timeval stv; struct tm stm; ::gettimeofday(&stv, NULL); time_t t = stv.tv_sec; gmtime_r(&t, &stm); strftime(timestamp, sizeof(timestamp), "%F %T", &stm); snprintf(timestampStr, sizeof(timestampStr), "[%s:%03ld] ",timestamp, stv.tv_usec / 1000); oss << timestampStr; } oss << "[" << getLevelString(level) << "] " << txt << std::endl; if (level <= backTraceLevel) { #ifndef WIN32 prt_backtrace(oss); #endif } #ifdef ASYNC_LOGGING pendingMessagesToWrite.push(new std::string(oss.str())); // If the queue gets too full, block until it's flushed to file or // stdout if (pendingMessagesToWrite.approx_size() > max_queue_size_allowed) { flush(); } #else std::string temp(oss.str()); writeMsg(temp); #endif } void Logger::logva(Logger::Level level, const char *fmt, va_list args) { if (level <= currentLevel) { char buffer[MAX_PRINTF_STYLE_MESSAGE_SIZE]; vsnprintf(buffer, sizeof(buffer), fmt, args); std::string msg = buffer; log(level, msg); } } void Logger::log(Logger::Level level, const char *fmt, ...) { va_list args; va_start(args, fmt); logva(level, fmt, args); va_end(args); } void Logger::Error::operator()(const char *fmt, ...) { va_list args; va_start(args, fmt); logger.logva(ERROR, fmt, args); va_end(args); } void Logger::Warn::operator()(const char *fmt, ...) { va_list args; va_start(args, fmt); logger.logva(WARN, fmt, args); va_end(args); } void Logger::Info::operator()(const char *fmt, ...) { va_list args; va_start(args, fmt); logger.logva(INFO, fmt, args); va_end(args); } void Logger::Debug::operator()(const char *fmt, ...) { va_list args; va_start(args, fmt); logger.logva(DEBUG, fmt, args); va_end(args); } void Logger::Fine::operator()(const char *fmt, ...) { va_list args; va_start(args, fmt); logger.logva(FINE, fmt, args); va_end(args); } bool Logger::isEnabled(Level level) const { return level <= currentLevel; } bool Logger::isErrorEnabled() const { return ERROR <= currentLevel; } bool Logger::isWarnEnabled() const { return WARN <= currentLevel; } bool Logger::isInfoEnabled() const { return INFO <= currentLevel; } bool Logger::isDebugEnabled() const { return DEBUG <= currentLevel; } bool Logger::isFineEnabled() const { return FINE <= currentLevel; } const char* Logger::getLevelString(const Logger::Level level) { if (level == BAD_LEVEL) return "Bad level"; else return levelStrings[level]; } const Logger::Level Logger::getLevelFromString(const std::string& levelStr) { unsigned int nLevels = sizeof(levelStrings) / sizeof(levelStrings[0]); for (unsigned int i = 0; i < nLevels; ++i) { if (boost::iequals(levelStrings[i], levelStr)) return (Logger::Level) i; } return BAD_LEVEL; } // create and return the single instance Logger& opencog::logger() { static Logger instance; return instance; } <|endoftext|>
<commit_before>/************************************************************************************ * * * Copyright (c) 2014, 2015 - 2016 Axel Menzel <[email protected]> * * * * This file is part of RTTR (Run Time Type Reflection) * * License: MIT License * * * * 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 "unit_tests/variant/test_enums.h" #include <catch/catch.hpp> #include <rttr/registration> using namespace rttr; RTTR_REGISTRATION { registration::enumeration<enum_int64_t>("enum_int64_t") ( value("VALUE_1", enum_int64_t::VALUE_1), value("VALUE_2", enum_int64_t::VALUE_2), value("VALUE_3", enum_int64_t::VALUE_3), value("VALUE_4", enum_int64_t::VALUE_4), value("VALUE_X", enum_int64_t::VALUE_NEG) ) ; } ///////////////////////////////////////////////////////////////////////////////////////// TEST_CASE("variant::to_string() - from empty", "[variant]") { variant var; bool ok = false; CHECK(var.to_string(&ok) == ""); CHECK(ok == false); } ///////////////////////////////////////////////////////////////////////////////////////// TEST_CASE("variant::to_string() - from bool", "[variant]") { variant var = true; REQUIRE(var.is_valid() == true); REQUIRE(var.can_convert<std::string>() == true); // true case bool ok = false; CHECK(var.to_string(&ok) == "true"); CHECK(ok == true); CHECK(var.convert<std::string>(&ok) == "true"); CHECK(ok == true); REQUIRE(var.convert(type::get<std::string>()) == true); CHECK(var.get_value<std::string>() == "true"); // false case var = false; CHECK(var.to_string(&ok) == "false"); CHECK(ok == true); CHECK(var.convert<std::string>(&ok) == "false"); CHECK(ok == true); REQUIRE(var.convert(type::get<std::string>()) == true); CHECK(var.get_value<std::string>() == "false"); } ///////////////////////////////////////////////////////////////////////////////////////// TEST_CASE("variant::to_string() - from char", "[variant]") { SECTION("valid conversion") { variant var = char('A'); REQUIRE(var.can_convert<std::string>() == true); bool ok = false; CHECK(var.to_string(&ok) == "A"); CHECK(ok == true); REQUIRE(var.convert(type::get<std::string>()) == true); CHECK(var.get_value<std::string>() == "A"); } SECTION("valid conversion negative") { variant var = char(-60); bool ok = false; CHECK(var.to_string(&ok) == ""); CHECK(ok == true); CHECK(var.convert(type::get<std::string>()) == true); } } ///////////////////////////////////////////////////////////////////////////////////////// TEST_CASE("variant::to_string() - from std::string", "[variant]") { variant var = std::string("23"); REQUIRE(var.can_convert<std::string>() == true); bool ok = false; CHECK(var.to_string(&ok) == "23"); CHECK(ok == true); var = std::string("-12"); CHECK(var.to_string() == "-12"); REQUIRE(var.convert(type::get<std::string>()) == true); CHECK(var.get_value<std::string>() == "-12"); } ///////////////////////////////////////////////////////////////////////////////////////// TEST_CASE("variant::to_string() - from int", "[variant]") { SECTION("conversion positive") { variant var = 2147483640; REQUIRE(var.can_convert<std::string>() == true); bool ok = false; CHECK(var.to_string(&ok) == "2147483640"); CHECK(ok == true); REQUIRE(var.convert(type::get<std::string>()) == true); CHECK(var.get_value<std::string>() == "2147483640"); } SECTION("conversion negative") { variant var = -2147483640; bool ok = false; CHECK(var.to_string(&ok) == "-2147483640"); CHECK(ok == true); CHECK(var.convert(type::get<std::string>()) == true); } } ///////////////////////////////////////////////////////////////////////////////////////// TEST_CASE("variant::to_string() - from float", "[variant]") { SECTION("conversion positive") { variant var = 214748.9f; REQUIRE(var.can_convert<std::string>() == true); bool ok = false; CHECK(var.to_string(&ok) == "214749"); CHECK(ok == true); REQUIRE(var.convert(type::get<std::string>()) == true); CHECK(var.get_value<std::string>() == "214749"); } SECTION("conversion negative") { variant var = -214748.9f; bool ok = false; CHECK(var.to_string(&ok) == "-214749"); CHECK(ok == true); CHECK(var.convert(type::get<std::string>()) == true); } } ///////////////////////////////////////////////////////////////////////////////////////// TEST_CASE("variant::to_string() - from double", "[variant]") { SECTION("conversion positive") { variant var = 5000000000.9; REQUIRE(var.can_convert<std::string>() == true); bool ok = false; CHECK(var.to_string(&ok) == "5000000000.9"); CHECK(ok == true); REQUIRE(var.convert(type::get<std::string>()) == true); CHECK(var.get_value<std::string>() == "5000000000.9"); } SECTION("conversion negative") { variant var = -5000000000.9; bool ok = false; CHECK(var.to_string(&ok) == "-5000000000.9"); CHECK(ok == true); CHECK(var.convert(type::get<std::string>()) == true); } } ///////////////////////////////////////////////////////////////////////////////////////// TEST_CASE("variant::to_string() - from int8_t", "[variant]") { SECTION("valid conversion positive") { variant var = int8_t(50); REQUIRE(var.can_convert<std::string>() == true); bool ok = false; CHECK(var.to_string(&ok) == "50"); CHECK(ok == true); REQUIRE(var.convert(type::get<std::string>()) == true); CHECK(var.get_value<std::string>() == "50"); } SECTION("valid conversion negative") { variant var = int8_t(-60); bool ok = false; CHECK(var.to_string(&ok) == "-60"); CHECK(ok == true); CHECK(var.convert(type::get<std::string>()) == true); } } ///////////////////////////////////////////////////////////////////////////////////////// TEST_CASE("variant::to_string() - from int16_t", "[variant]") { SECTION("valid conversion positive") { variant var = int16_t(32760); REQUIRE(var.can_convert<std::string>() == true); bool ok = false; CHECK(var.to_string(&ok) == "32760"); CHECK(ok == true); REQUIRE(var.convert(type::get<std::string>()) == true); CHECK(var.get_value<std::string>() == "32760"); } SECTION("valid conversion negative") { variant var = int16_t(-32760); bool ok = false; CHECK(var.to_string(&ok) == "-32760"); CHECK(ok == true); CHECK(var.convert(type::get<std::string>()) == true); } } ///////////////////////////////////////////////////////////////////////////////////////// TEST_CASE("variant::to_string() - from int32_t", "[variant]") { SECTION("valid conversion positive") { variant var = int32_t(2147483640); REQUIRE(var.can_convert<std::string>() == true); bool ok = false; CHECK(var.to_string(&ok) == "2147483640"); CHECK(ok == true); REQUIRE(var.convert(type::get<std::string>()) == true); CHECK(var.get_value<std::string>() == "2147483640"); } SECTION("valid conversion negative") { variant var = int32_t(-2147483640); bool ok = false; CHECK(var.to_string(&ok) == "-2147483640"); CHECK(ok == true); CHECK(var.convert(type::get<std::string>()) == true); } } ///////////////////////////////////////////////////////////////////////////////////////// TEST_CASE("variant::to_string() - from int64_t", "[variant]") { SECTION("valid conversion positive") { variant var = int64_t(9023372036854775807L); REQUIRE(var.can_convert<std::string>() == true); bool ok = false; CHECK(var.to_string(&ok) == "9023372036854775807"); CHECK(ok == true); CHECK(var.convert(type::get<std::string>()) == true); CHECK(var.get_value<std::string>() == "9023372036854775807"); } SECTION("valid conversion negative") { variant var = int64_t(-9023372036854775808L); bool ok = false; CHECK(var.to_string(&ok) == "-9023372036854775808"); CHECK(ok == true); CHECK(var.convert(type::get<std::string>()) == true); } } ///////////////////////////////////////////////////////////////////////////////////////// TEST_CASE("variant::to_string() - from uint8_t", "[variant]") { SECTION("valid conversion positive") { variant var = uint8_t(50); REQUIRE(var.can_convert<std::string>() == true); bool ok = false; CHECK(var.to_string(&ok) == "50"); CHECK(ok == true); REQUIRE(var.convert(type::get<std::string>()) == true); CHECK(var.get_value<std::string>() == "50"); } } ///////////////////////////////////////////////////////////////////////////////////////// TEST_CASE("variant::to_string() - from uint16_t", "[variant]") { SECTION("valid conversion positive") { variant var = uint16_t(32760); REQUIRE(var.can_convert<std::string>() == true); bool ok = false; CHECK(var.to_string(&ok) == "32760"); CHECK(ok == true); REQUIRE(var.convert(type::get<std::string>()) == true); CHECK(var.get_value<std::string>() == "32760"); } } ///////////////////////////////////////////////////////////////////////////////////////// TEST_CASE("variant::to_string() - from uint32_t", "[variant]") { SECTION("valid conversion positive") { variant var = uint32_t(32760); REQUIRE(var.can_convert<std::string>() == true); bool ok = false; CHECK(var.to_string(&ok) == "32760"); CHECK(ok == true); CHECK(var.convert(type::get<std::string>()) == true); CHECK(var.get_value<std::string>() == "32760"); } } ///////////////////////////////////////////////////////////////////////////////////////// TEST_CASE("variant::to_string() - from uint64_t", "[variant]") { SECTION("valid conversion positive") { variant var = uint64_t(2147483640); REQUIRE(var.can_convert<std::string>() == true); bool ok = false; CHECK(var.to_string(&ok) == "2147483640"); CHECK(ok == true); REQUIRE(var.convert(type::get<std::string>()) == true); CHECK(var.get_value<std::string>() == "2147483640"); } } ///////////////////////////////////////////////////////////////////////////////////////// enum class unregisterd_enum { VALUE_1 }; ///////////////////////////////////////////////////////////////////////////////////////// TEST_CASE("variant::to_string() - from enum", "[variant]") { SECTION("valid conversion") { variant var = enum_int64_t::VALUE_1; REQUIRE(var.can_convert<int64_t>() == true); bool ok = false; CHECK(var.to_string(&ok) == "VALUE_1"); CHECK(ok == true); REQUIRE(var.convert(type::get<std::string>()) == true); CHECK(var.get_value<std::string>() == "VALUE_1"); } SECTION("invalid conversion") { variant var = unregisterd_enum::VALUE_1; bool ok = false; CHECK(var.to_string(&ok) == ""); CHECK(ok == false); CHECK(var.convert(type::get<std::string>()) == false); } } ///////////////////////////////////////////////////////////////////////////////////////// <commit_msg>fixed compiler warning with clang: 'illegal character encoding in string literal [-Winvalid-source-encoding]'<commit_after>/************************************************************************************ * * * Copyright (c) 2014, 2015 - 2016 Axel Menzel <[email protected]> * * * * This file is part of RTTR (Run Time Type Reflection) * * License: MIT License * * * * 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 "unit_tests/variant/test_enums.h" #include <catch/catch.hpp> #include <rttr/registration> using namespace rttr; RTTR_REGISTRATION { registration::enumeration<enum_int64_t>("enum_int64_t") ( value("VALUE_1", enum_int64_t::VALUE_1), value("VALUE_2", enum_int64_t::VALUE_2), value("VALUE_3", enum_int64_t::VALUE_3), value("VALUE_4", enum_int64_t::VALUE_4), value("VALUE_X", enum_int64_t::VALUE_NEG) ) ; } ///////////////////////////////////////////////////////////////////////////////////////// TEST_CASE("variant::to_string() - from empty", "[variant]") { variant var; bool ok = false; CHECK(var.to_string(&ok) == ""); CHECK(ok == false); } ///////////////////////////////////////////////////////////////////////////////////////// TEST_CASE("variant::to_string() - from bool", "[variant]") { variant var = true; REQUIRE(var.is_valid() == true); REQUIRE(var.can_convert<std::string>() == true); // true case bool ok = false; CHECK(var.to_string(&ok) == "true"); CHECK(ok == true); CHECK(var.convert<std::string>(&ok) == "true"); CHECK(ok == true); REQUIRE(var.convert(type::get<std::string>()) == true); CHECK(var.get_value<std::string>() == "true"); // false case var = false; CHECK(var.to_string(&ok) == "false"); CHECK(ok == true); CHECK(var.convert<std::string>(&ok) == "false"); CHECK(ok == true); REQUIRE(var.convert(type::get<std::string>()) == true); CHECK(var.get_value<std::string>() == "false"); } ///////////////////////////////////////////////////////////////////////////////////////// TEST_CASE("variant::to_string() - from char", "[variant]") { SECTION("valid conversion") { variant var = char('A'); REQUIRE(var.can_convert<std::string>() == true); bool ok = false; CHECK(var.to_string(&ok) == "A"); CHECK(ok == true); REQUIRE(var.convert(type::get<std::string>()) == true); CHECK(var.get_value<std::string>() == "A"); } SECTION("valid conversion negative") { variant var = char(-60); bool ok = false; CHECK(var.to_string(&ok) == std::string(1, char(-60))); CHECK(ok == true); CHECK(var.convert(type::get<std::string>()) == true); } } ///////////////////////////////////////////////////////////////////////////////////////// TEST_CASE("variant::to_string() - from std::string", "[variant]") { variant var = std::string("23"); REQUIRE(var.can_convert<std::string>() == true); bool ok = false; CHECK(var.to_string(&ok) == "23"); CHECK(ok == true); var = std::string("-12"); CHECK(var.to_string() == "-12"); REQUIRE(var.convert(type::get<std::string>()) == true); CHECK(var.get_value<std::string>() == "-12"); } ///////////////////////////////////////////////////////////////////////////////////////// TEST_CASE("variant::to_string() - from int", "[variant]") { SECTION("conversion positive") { variant var = 2147483640; REQUIRE(var.can_convert<std::string>() == true); bool ok = false; CHECK(var.to_string(&ok) == "2147483640"); CHECK(ok == true); REQUIRE(var.convert(type::get<std::string>()) == true); CHECK(var.get_value<std::string>() == "2147483640"); } SECTION("conversion negative") { variant var = -2147483640; bool ok = false; CHECK(var.to_string(&ok) == "-2147483640"); CHECK(ok == true); CHECK(var.convert(type::get<std::string>()) == true); } } ///////////////////////////////////////////////////////////////////////////////////////// TEST_CASE("variant::to_string() - from float", "[variant]") { SECTION("conversion positive") { variant var = 214748.9f; REQUIRE(var.can_convert<std::string>() == true); bool ok = false; CHECK(var.to_string(&ok) == "214749"); CHECK(ok == true); REQUIRE(var.convert(type::get<std::string>()) == true); CHECK(var.get_value<std::string>() == "214749"); } SECTION("conversion negative") { variant var = -214748.9f; bool ok = false; CHECK(var.to_string(&ok) == "-214749"); CHECK(ok == true); CHECK(var.convert(type::get<std::string>()) == true); } } ///////////////////////////////////////////////////////////////////////////////////////// TEST_CASE("variant::to_string() - from double", "[variant]") { SECTION("conversion positive") { variant var = 5000000000.9; REQUIRE(var.can_convert<std::string>() == true); bool ok = false; CHECK(var.to_string(&ok) == "5000000000.9"); CHECK(ok == true); REQUIRE(var.convert(type::get<std::string>()) == true); CHECK(var.get_value<std::string>() == "5000000000.9"); } SECTION("conversion negative") { variant var = -5000000000.9; bool ok = false; CHECK(var.to_string(&ok) == "-5000000000.9"); CHECK(ok == true); CHECK(var.convert(type::get<std::string>()) == true); } } ///////////////////////////////////////////////////////////////////////////////////////// TEST_CASE("variant::to_string() - from int8_t", "[variant]") { SECTION("valid conversion positive") { variant var = int8_t(50); REQUIRE(var.can_convert<std::string>() == true); bool ok = false; CHECK(var.to_string(&ok) == "50"); CHECK(ok == true); REQUIRE(var.convert(type::get<std::string>()) == true); CHECK(var.get_value<std::string>() == "50"); } SECTION("valid conversion negative") { variant var = int8_t(-60); bool ok = false; CHECK(var.to_string(&ok) == "-60"); CHECK(ok == true); CHECK(var.convert(type::get<std::string>()) == true); } } ///////////////////////////////////////////////////////////////////////////////////////// TEST_CASE("variant::to_string() - from int16_t", "[variant]") { SECTION("valid conversion positive") { variant var = int16_t(32760); REQUIRE(var.can_convert<std::string>() == true); bool ok = false; CHECK(var.to_string(&ok) == "32760"); CHECK(ok == true); REQUIRE(var.convert(type::get<std::string>()) == true); CHECK(var.get_value<std::string>() == "32760"); } SECTION("valid conversion negative") { variant var = int16_t(-32760); bool ok = false; CHECK(var.to_string(&ok) == "-32760"); CHECK(ok == true); CHECK(var.convert(type::get<std::string>()) == true); } } ///////////////////////////////////////////////////////////////////////////////////////// TEST_CASE("variant::to_string() - from int32_t", "[variant]") { SECTION("valid conversion positive") { variant var = int32_t(2147483640); REQUIRE(var.can_convert<std::string>() == true); bool ok = false; CHECK(var.to_string(&ok) == "2147483640"); CHECK(ok == true); REQUIRE(var.convert(type::get<std::string>()) == true); CHECK(var.get_value<std::string>() == "2147483640"); } SECTION("valid conversion negative") { variant var = int32_t(-2147483640); bool ok = false; CHECK(var.to_string(&ok) == "-2147483640"); CHECK(ok == true); CHECK(var.convert(type::get<std::string>()) == true); } } ///////////////////////////////////////////////////////////////////////////////////////// TEST_CASE("variant::to_string() - from int64_t", "[variant]") { SECTION("valid conversion positive") { variant var = int64_t(9023372036854775807L); REQUIRE(var.can_convert<std::string>() == true); bool ok = false; CHECK(var.to_string(&ok) == "9023372036854775807"); CHECK(ok == true); CHECK(var.convert(type::get<std::string>()) == true); CHECK(var.get_value<std::string>() == "9023372036854775807"); } SECTION("valid conversion negative") { variant var = int64_t(-9023372036854775808L); bool ok = false; CHECK(var.to_string(&ok) == "-9023372036854775808"); CHECK(ok == true); CHECK(var.convert(type::get<std::string>()) == true); } } ///////////////////////////////////////////////////////////////////////////////////////// TEST_CASE("variant::to_string() - from uint8_t", "[variant]") { SECTION("valid conversion positive") { variant var = uint8_t(50); REQUIRE(var.can_convert<std::string>() == true); bool ok = false; CHECK(var.to_string(&ok) == "50"); CHECK(ok == true); REQUIRE(var.convert(type::get<std::string>()) == true); CHECK(var.get_value<std::string>() == "50"); } } ///////////////////////////////////////////////////////////////////////////////////////// TEST_CASE("variant::to_string() - from uint16_t", "[variant]") { SECTION("valid conversion positive") { variant var = uint16_t(32760); REQUIRE(var.can_convert<std::string>() == true); bool ok = false; CHECK(var.to_string(&ok) == "32760"); CHECK(ok == true); REQUIRE(var.convert(type::get<std::string>()) == true); CHECK(var.get_value<std::string>() == "32760"); } } ///////////////////////////////////////////////////////////////////////////////////////// TEST_CASE("variant::to_string() - from uint32_t", "[variant]") { SECTION("valid conversion positive") { variant var = uint32_t(32760); REQUIRE(var.can_convert<std::string>() == true); bool ok = false; CHECK(var.to_string(&ok) == "32760"); CHECK(ok == true); CHECK(var.convert(type::get<std::string>()) == true); CHECK(var.get_value<std::string>() == "32760"); } } ///////////////////////////////////////////////////////////////////////////////////////// TEST_CASE("variant::to_string() - from uint64_t", "[variant]") { SECTION("valid conversion positive") { variant var = uint64_t(2147483640); REQUIRE(var.can_convert<std::string>() == true); bool ok = false; CHECK(var.to_string(&ok) == "2147483640"); CHECK(ok == true); REQUIRE(var.convert(type::get<std::string>()) == true); CHECK(var.get_value<std::string>() == "2147483640"); } } ///////////////////////////////////////////////////////////////////////////////////////// enum class unregisterd_enum { VALUE_1 }; ///////////////////////////////////////////////////////////////////////////////////////// TEST_CASE("variant::to_string() - from enum", "[variant]") { SECTION("valid conversion") { variant var = enum_int64_t::VALUE_1; REQUIRE(var.can_convert<int64_t>() == true); bool ok = false; CHECK(var.to_string(&ok) == "VALUE_1"); CHECK(ok == true); REQUIRE(var.convert(type::get<std::string>()) == true); CHECK(var.get_value<std::string>() == "VALUE_1"); } SECTION("invalid conversion") { variant var = unregisterd_enum::VALUE_1; bool ok = false; CHECK(var.to_string(&ok) == ""); CHECK(ok == false); CHECK(var.convert(type::get<std::string>()) == false); } } ///////////////////////////////////////////////////////////////////////////////////////// <|endoftext|>
<commit_before>/************************************************************************** ** ** This file is part of Qt Creator ** ** Copyright (c) 2011 Nokia Corporation and/or its subsidiary(-ies). ** ** Contact: Nokia Corporation ([email protected]) ** ** ** 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 [email protected]. ** **************************************************************************/ /* A stub for Windows console processes (like nmake) that is able to terminate * its child process via a generated Ctrl-C event. * The termination is triggered by sending a custom message to the HWND of * this process. */ #ifndef WINVER #define WINVER 0x0501 #endif #ifndef _WIN32_WINNT #define _WIN32_WINNT 0x0501 #endif #define WIN32_LEAN_AND_MEAN #include <windows.h> #include <shellapi.h> #include <wchar.h> #include <cstdlib> #include <cstdio> const wchar_t szTitle[] = L"qtcbuildhelper"; const wchar_t szWindowClass[] = L"wcqtcbuildhelper"; UINT uiShutDownWindowMessage; HWND hwndMain = 0; LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM); BOOL WINAPI ctrlHandler(DWORD dwCtrlType); bool findFirst(const wchar_t *str, const size_t strLength, const size_t startPos, const wchar_t *chars, size_t &pos); bool startProcess(wchar_t pCommandLine[]); int main(int argc, char **) { if (argc < 2) { fprintf(stderr, "This is an internal helper of Qt Creator. Do not run it manually.\n"); return 1; } SetConsoleCtrlHandler(ctrlHandler, TRUE); uiShutDownWindowMessage = RegisterWindowMessage(L"qtcbuildhelper_shutdown"); WNDCLASSEX wcex; ZeroMemory(&wcex, sizeof(wcex)); wcex.cbSize = sizeof(wcex); wcex.lpfnWndProc = WndProc; wcex.hInstance = GetModuleHandle(0); wcex.lpszClassName = szWindowClass; if (!RegisterClassEx(&wcex)) return 1; hwndMain = CreateWindow(szWindowClass, szTitle, WS_DISABLED, 0, 0, 0, 0, NULL, NULL, wcex.hInstance, NULL); if (!hwndMain) return FALSE; // Get the command line and remove the call to this executable. // Note: We trust Qt Creator at this point to quote the call to this tool in a sensible way. // Strange things like C:\Q"t Crea"tor\bin\qtcbuildhelper.exe are not supported. wchar_t *strCommandLine = _wcsdup(GetCommandLine()); const size_t strCommandLineLength = wcslen(strCommandLine); size_t pos = 1; if (strCommandLine[0] == L'"') if (!findFirst(strCommandLine, strCommandLineLength, pos, L"\"", pos)) return 1; if (!findFirst(strCommandLine, strCommandLineLength, pos, L" \t", pos)) return 1; wmemmove_s(strCommandLine, strCommandLineLength, strCommandLine + pos + 2, strCommandLineLength - pos); bool bSuccess = startProcess(strCommandLine); free(strCommandLine); if (!bSuccess) return 1; MSG msg; while (GetMessage(&msg, NULL, 0, 0)) { TranslateMessage(&msg); DispatchMessage(&msg); } return (int) msg.wParam; } LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) { if (message == uiShutDownWindowMessage) { GenerateConsoleCtrlEvent(CTRL_C_EVENT, 0); PostQuitMessage(0); return 0; } switch (message) { case WM_DESTROY: PostQuitMessage(0); break; default: return DefWindowProc(hWnd, message, wParam, lParam); } return 0; } bool findFirst(const wchar_t *str, const size_t strLength, const size_t startPos, const wchar_t *chars, size_t &pos) { for (size_t i=startPos; i < strLength; ++i) { for (size_t j=0; chars[j]; ++j) { if (str[i] == chars[j]) { pos = i; return true; } } } return false; } BOOL WINAPI ctrlHandler(DWORD /*dwCtrlType*/) { PostMessage(hwndMain, WM_DESTROY, 0, 0); return TRUE; } DWORD WINAPI processWatcherThread(__in LPVOID lpParameter) { HANDLE hProcess = reinterpret_cast<HANDLE>(lpParameter); WaitForSingleObject(hProcess, INFINITE); PostMessage(hwndMain, WM_DESTROY, 0, 0); return 0; } bool startProcess(wchar_t *pCommandLine) { SECURITY_ATTRIBUTES sa; ZeroMemory(&sa, sizeof(sa)); sa.nLength = sizeof(sa); sa.bInheritHandle = TRUE; STARTUPINFO si; ZeroMemory(&si, sizeof(si)); si.cb = sizeof(si); PROCESS_INFORMATION pi; DWORD dwCreationFlags = 0; BOOL bSuccess = CreateProcess(NULL, pCommandLine, &sa, &sa, TRUE, dwCreationFlags, NULL, NULL, &si, &pi); if (!bSuccess) { fwprintf(stderr, L"qtcbuildhelper: Command line failed: %s\n", pCommandLine); return false; } HANDLE hThread = CreateThread(NULL, 0, processWatcherThread, reinterpret_cast<void*>(pi.hProcess), 0, NULL); if (!hThread) { fwprintf(stderr, L"qtcbuildhelper: The watch dog thread cannot be started.\n"); return false; } CloseHandle(hThread); return true; } <commit_msg>fixup for qtcbuildhelper usage (change Ib6f5be80)<commit_after>/************************************************************************** ** ** This file is part of Qt Creator ** ** Copyright (c) 2011 Nokia Corporation and/or its subsidiary(-ies). ** ** Contact: Nokia Corporation ([email protected]) ** ** ** 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 [email protected]. ** **************************************************************************/ /* A stub for Windows console processes (like nmake) that is able to terminate * its child process via a generated Ctrl-C event. * The termination is triggered by sending a custom message to the HWND of * this process. */ #ifndef WINVER #define WINVER 0x0501 #endif #ifndef _WIN32_WINNT #define _WIN32_WINNT 0x0501 #endif #define WIN32_LEAN_AND_MEAN #include <windows.h> #include <shellapi.h> #include <wchar.h> #include <cstdlib> #include <cstdio> const wchar_t szTitle[] = L"qtcbuildhelper"; const wchar_t szWindowClass[] = L"wcqtcbuildhelper"; UINT uiShutDownWindowMessage; HWND hwndMain = 0; LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM); BOOL WINAPI ctrlHandler(DWORD dwCtrlType); bool findFirst(const wchar_t *str, const size_t strLength, const size_t startPos, const wchar_t *chars, size_t &pos); bool startProcess(wchar_t pCommandLine[]); int main(int argc, char **) { if (argc < 2) { fprintf(stderr, "This is an internal helper of Qt Creator. Do not run it manually.\n"); return 1; } SetConsoleCtrlHandler(ctrlHandler, TRUE); uiShutDownWindowMessage = RegisterWindowMessage(L"qtcbuildhelper_shutdown"); WNDCLASSEX wcex; ZeroMemory(&wcex, sizeof(wcex)); wcex.cbSize = sizeof(wcex); wcex.lpfnWndProc = WndProc; wcex.hInstance = GetModuleHandle(0); wcex.lpszClassName = szWindowClass; if (!RegisterClassEx(&wcex)) return 1; hwndMain = CreateWindow(szWindowClass, szTitle, WS_DISABLED, 0, 0, 0, 0, NULL, NULL, wcex.hInstance, NULL); if (!hwndMain) return FALSE; // Get the command line and remove the call to this executable. // Note: We trust Qt Creator at this point to quote the call to this tool in a sensible way. // Strange things like C:\Q"t Crea"tor\bin\qtcbuildhelper.exe are not supported. wchar_t *strCommandLine = _wcsdup(GetCommandLine()); const size_t strCommandLineLength = wcslen(strCommandLine); size_t pos = 1; if (strCommandLine[0] == L'"') if (!findFirst(strCommandLine, strCommandLineLength, pos, L"\"", pos)) return 1; if (!findFirst(strCommandLine, strCommandLineLength, pos, L" \t", pos)) return 1; wmemmove_s(strCommandLine, strCommandLineLength, strCommandLine + pos + 1, strCommandLineLength - pos); bool bSuccess = startProcess(strCommandLine); free(strCommandLine); if (!bSuccess) return 1; MSG msg; while (GetMessage(&msg, NULL, 0, 0)) { TranslateMessage(&msg); DispatchMessage(&msg); } return (int) msg.wParam; } LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) { if (message == uiShutDownWindowMessage) { GenerateConsoleCtrlEvent(CTRL_C_EVENT, 0); PostQuitMessage(0); return 0; } switch (message) { case WM_DESTROY: PostQuitMessage(0); break; default: return DefWindowProc(hWnd, message, wParam, lParam); } return 0; } bool findFirst(const wchar_t *str, const size_t strLength, const size_t startPos, const wchar_t *chars, size_t &pos) { for (size_t i=startPos; i < strLength; ++i) { for (size_t j=0; chars[j]; ++j) { if (str[i] == chars[j]) { pos = i; return true; } } } return false; } BOOL WINAPI ctrlHandler(DWORD /*dwCtrlType*/) { PostMessage(hwndMain, WM_DESTROY, 0, 0); return TRUE; } DWORD WINAPI processWatcherThread(__in LPVOID lpParameter) { HANDLE hProcess = reinterpret_cast<HANDLE>(lpParameter); WaitForSingleObject(hProcess, INFINITE); PostMessage(hwndMain, WM_DESTROY, 0, 0); return 0; } bool startProcess(wchar_t *pCommandLine) { SECURITY_ATTRIBUTES sa; ZeroMemory(&sa, sizeof(sa)); sa.nLength = sizeof(sa); sa.bInheritHandle = TRUE; STARTUPINFO si; ZeroMemory(&si, sizeof(si)); si.cb = sizeof(si); PROCESS_INFORMATION pi; DWORD dwCreationFlags = 0; BOOL bSuccess = CreateProcess(NULL, pCommandLine, &sa, &sa, TRUE, dwCreationFlags, NULL, NULL, &si, &pi); if (!bSuccess) { fwprintf(stderr, L"qtcbuildhelper: Command line failed: %s\n", pCommandLine); return false; } HANDLE hThread = CreateThread(NULL, 0, processWatcherThread, reinterpret_cast<void*>(pi.hProcess), 0, NULL); if (!hThread) { fwprintf(stderr, L"qtcbuildhelper: The watch dog thread cannot be started.\n"); return false; } CloseHandle(hThread); return true; } <|endoftext|>
<commit_before>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/usr/diag/prdf/plat/mem/prdfMemChnlFailCache.H $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2018,2019 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* Licensed under the Apache License, Version 2.0 (the "License"); */ /* you may not use this file except in compliance with the License. */ /* You may obtain a copy of the License at */ /* */ /* http://www.apache.org/licenses/LICENSE-2.0 */ /* */ /* Unless required by applicable law or agreed to in writing, software */ /* distributed under the License is distributed on an "AS IS" BASIS, */ /* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */ /* implied. See the License for the specific language governing */ /* permissions and limitations under the License. */ /* */ /* IBM_PROLOG_END_TAG */ #include <map> #include <targeting/common/targetservice.H> #ifndef __prdfMemChnlFailCache_H #define __prdfMemChnlFailCache_H namespace PRDF { typedef std::map<TARGETING::TYPE, std::vector<uint64_t>> TargetScoms_t; TargetScoms_t chnlFailScomList = { { TARGETING::TYPE_MEMBUF, { // SCOMs 0x500F001C, // GLOBAL_CS_FIR 0x500F001B, // GLOBAL_RE_FIR 0x500F001A, // GLOBAL_SPA_FIR 0x01040000, // TP_CHIPLET_CS_FIR 0x01040001, // TP_CHIPLET_RE_FIR 0x01040002, // TP_CHIPLET_FIR_MASK 0x0104000A, // TP_LFIR 0x0104000D, // TP_LFIR_MASK 0x01040010, // TP_LFIR_ACT0 0x01040011, // TP_LFIR_ACT1 0x02040000, // NEST_CHIPLET_CS_FIR 0x02040001, // NEST_CHIPLET_RE_FIR 0x02040002, // NEST_CHIPLET_FIR_MASK 0x0204000A, // NEST_LFIR 0x0204000D, // NEST_LFIR_MASK 0x02040010, // NEST_LFIR_ACT0 0x02040011, // NEST_LFIR_ACT1 0x02010400, // DMIFIR 0x02010403, // DMIFIR_MASK 0x02010406, // DMIFIR_ACT0 0x02010407, // DMIFIR_ACT1 0x02010800, // MBIFIR 0x02010803, // MBIFIR_MASK 0x02010806, // MBIFIR_ACT0 0x02010807, // MBIFIR_ACT1 0x02011400, // MBSFIR 0x02011403, // MBSFIR_MASK 0x02011406, // MBSFIR_ACT0 0x02011407, // MBSFIR_ACT1 0x0201141e, // MBSSECUREFIR 0x02011440, // MBSECCFIR_0 0x02011443, // MBSECCFIR_0_MASK 0x02011446, // MBSECCFIR_0_ACT0 0x02011447, // MBSECCFIR_0_ACT1 0x02011480, // MBSECCFIR_1 0x02011483, // MBSECCFIR_1_MASK 0x02011486, // MBSECCFIR_1_ACT0 0x02011487, // MBSECCFIR_1_ACT1 0x020115c0, // SCACFIR 0x020115c3, // SCACFIR_MASK 0x020115c6, // SCACFIR_ACT0 0x020115c7, // SCACFIR_ACT1 0x02011600, // MCBISTFIR_0 0x02011603, // MCBISTFIR_0_MASK 0x02011606, // MCBISTFIR_0_ACT0 0x02011607, // MCBISTFIR_0_ACT1 0x02011700, // MCBISTFIR_1 0x02011703, // MCBISTFIR_1_MASK 0x02011706, // MCBISTFIR_1_ACT0 0x02011707, // MCBISTFIR_1_ACT1 0x03040000, // MEM_CHIPLET_CS_FIR 0x03040001, // MEM_CHIPLET_RE_FIR 0x03040002, // MEM_CHIPLET_FIR_MASK 0x03040004, // MEM_CHIPLET_SPA_FIR 0x03040007, // MEM_CHIPLET_SPA_FIR_MASK 0x0304000A, // MEM_LFIR 0x0304000D, // MEM_LFIR_MASK 0x03040010, // MEM_LFIR_ACT0 0x03040011, // MEM_LFIR_ACT1 0x01030009, // TP_ERROR_STATUS 0x02030009, // NEST_ERROR_STATUS 0x0201080F, // MBIERPT 0x02011413, // MBSCERR1 0x0201142C, // MBSCERR2 0x02011466, // MBA0_MBSECCERRPT_0 0x02011467, // MBA0_MBSECCERRPT_1 0x020114A6, // MBA1_MBSECCERRPT_0 0x020114A7, // MBA1_MBSECCERRPT_1 0x0201168f, // MBA0_MBXERRSTAT 0x0201178f, // MBA1_MBXERRSTAT 0x020115D4, // SENSORCACHEERRPT 0x03030009, // MEM_ERROR_STATUS } }, { TARGETING::TYPE_MBA, { 0x03010400, // MBACALFIR 0x03010403, // MBACALFIR_MASK 0x03010406, // MBACALFIR_ACT0 0x03010407, // MBACALFIR_ACT1 0x0301041b, // MBASECUREFIR 0x03010600, // MBAFIR 0x03010603, // MBAFIR_MASK 0x03010606, // MBAFIR_ACT0 0x03010607, // MBAFIR_ACT1 0x03010611, // MBASPA 0x03010614, // MBASPA_MASK 0x0301041A, // MBA_ERR_REPORT 0x030106E7, // MBA_MCBERRPTQ 0x800200900301143F, // MBADDRPHYFIR 0x800200930301143F, // MBADDRPHYFIR_MASK 0x800200960301143F, // MBADDRPHYFIR_ACT0 0x800200970301143F, // MBADDRPHYFIR_ACT1 0x8000D0060301143F, // DDRPHY_APB_FIR_ERR0_P0 0x8000D0070301143F, // DDRPHY_APB_FIR_ERR1_P0 0x8001D0060301143F, // DDRPHY_APB_FIR_ERR0_P1 0x8001D0070301143F, // DDRPHY_APB_FIR_ERR1_P1 } } }; } // namespace PRDF #endif // __prdfMemChnlFailCache_H <commit_msg>PRD: Update reg list in prdfMemChnlFailCache.H<commit_after>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/usr/diag/prdf/plat/mem/prdfMemChnlFailCache.H $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2018,2020 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* Licensed under the Apache License, Version 2.0 (the "License"); */ /* you may not use this file except in compliance with the License. */ /* You may obtain a copy of the License at */ /* */ /* http://www.apache.org/licenses/LICENSE-2.0 */ /* */ /* Unless required by applicable law or agreed to in writing, software */ /* distributed under the License is distributed on an "AS IS" BASIS, */ /* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */ /* implied. See the License for the specific language governing */ /* permissions and limitations under the License. */ /* */ /* IBM_PROLOG_END_TAG */ #include <map> #include <targeting/common/targetservice.H> #ifndef __prdfMemChnlFailCache_H #define __prdfMemChnlFailCache_H namespace PRDF { typedef std::map<TARGETING::TYPE, std::vector<uint64_t>> TargetScoms_t; TargetScoms_t chnlFailScomList = { { TARGETING::TYPE_OCMB_CHIP, { // SCOMs 0x08040000, // OCMB_CHIPLET_CS_FIR 0x08040001, // OCMB_CHIPLET_RE_FIR 0x08040002, // OCMB_CHIPLET_FIR_MASK 0x08040004, // OCMB_CHIPLET_SPA_FIR 0x08040007, // OCMB_CHIPLET_SPA_FIR_MASK 0x0804000a, // OCMB_LFIR 0x0804000d, // OCMB_LFIR_MASK 0x08040010, // OCMB_LFIR_ACT0 0x08040011, // OCMB_LFIR_ACT1 0x08010870, // MMIOFIR 0x08010873, // MMIOFIR_MASK 0x08010876, // MMIOFIR_ACT0 0x08010877, // MMIOFIR_ACT1 0x08011400, // SRQFIR 0x08011403, // SRQFIR_MASK 0x08011406, // SRQFIR_ACT0 0x08011407, // SRQFIR_ACT1 0x08011800, // MCBISTFIR 0x08011803, // MCBISTFIR_MASK 0x08011806, // MCBISTFIR_ACT0 0x08011807, // MCBISTFIR_ACT1 0x08011c00, // RDFFIR 0x08011c03, // RDFFIR_MASK 0x08011c06, // RDFFIR_ACT0 0x08011c07, // RDFFIR_ACT1 0x08012400, // TLXFIR 0x08012403, // TLXFIR_MASK 0x08012406, // TLXFIR_ACT0 0x08012407, // TLXFIR_ACT1 0x08012800, // OMIDLFIR 0x08012803, // OMIDLFIR_MASK 0x08012806, // OMIDLFIR_ACT0 0x08012807, // OMIDLFIR_ACT1 0x08011858, // OCMB_MBSSYMEC0 0x08011859, // OCMB_MBSSYMEC1 0x0801185A, // OCMB_MBSSYMEC2 0x0801185B, // OCMB_MBSSYMEC3 0x0801185C, // OCMB_MBSSYMEC4 0x0801185D, // OCMB_MBSSYMEC5 0x0801185E, // OCMB_MBSSYMEC6 0x0801185F, // OCMB_MBSSYMEC7 0x08011860, // OCMB_MBSSYMEC8 0x0801187E, // MBSEVR0 0x08011855, // MBSEC0 0x08011856, // MBSEC1 0x08011869, // MBSMSEC 0x08011857, // MBSTR 0x080118D6, // MCBAGRA 0x080118D7, // MCBMCAT 0x080118DB, // MCB_CNTL 0x080118DC, // MCB_CNTLSTAT 0x08011C10, // HW_MS0 0x08011C11, // HW_MS1 0x08011C12, // HW_MS2 0x08011C13, // HW_MS3 0x08011C14, // HW_MS4 0x08011C15, // HW_MS5 0x08011C16, // HW_MS6 0x08011C17, // HW_MS7 0x08011C18, // FW_MS0 0x08011C19, // FW_MS1 0x08011C1A, // FW_MS2 0x08011C1B, // FW_MS3 0x08011C1C, // FW_MS4 0x08011C1D, // FW_MS5 0x08011C1E, // FW_MS6 0x08011C1F, // FW_MS7 0x0801241C, // TLX_ERR0_REPORT 0x0801241D, // TLX_ERR1_REPORT 0x08012414, // TLX_ERR0_REPORT_MASK 0x08012415, // TLX_ERR1_REPORT_MASK 0x0801186A, // MBNCER 0x0801186B, // MBRCER 0x0801186C, // MBMPER 0x0801186D, // MBUER 0x0801186E, // MBAUER 0x08011415, // FARB0 0x08011C0C, // EXP_MSR 0x0801186F, // MC_ADDR_TRANS 0x08011870, // MC_ADDR_TRANS1 0x08011871, // MC_ADDR_TRANS2 } } }; } // namespace PRDF #endif // __prdfMemChnlFailCache_H <|endoftext|>
<commit_before>/* * The Apache Software License, Version 1.1 * * * Copyright (c) 2001 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "Xerces" and "Apache Software Foundation" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact [email protected]. * * 5. Products derived from this software may not be called "Apache", * nor may "Apache" appear in their name, without prior written * permission of the Apache Software Foundation. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation and was * originally based on software copyright (c) 2001, International * Business Machines, Inc., http://www.apache.org. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. */ /** * $Id$ */ #if !defined(GRAMMARRESOLVER_HPP) #define GRAMMARRESOLVER_HPP #include <xercesc/util/RefHashTableOf.hpp> #include <xercesc/util/StringPool.hpp> #include <xercesc/validators/common/Grammar.hpp> XERCES_CPP_NAMESPACE_BEGIN class DatatypeValidator; class DatatypeValidatorFactory; class XMLGrammarPool; class XMLGrammarDescription; class GrammarEntry; /** * This class embodies the representation of a Grammar pool Resolver. * This class is called from the validator. * */ class VALIDATORS_EXPORT GrammarResolver : public XMemory { public: /** @name Constructor and Destructor */ //@{ /** * * Default Constructor */ GrammarResolver( XMLGrammarPool* const gramPool , MemoryManager* const manager = XMLPlatformUtils::fgMemoryManager ); /** * Destructor */ ~GrammarResolver(); //@} /** @name Getter methods */ //@{ /** * Retrieve the DatatypeValidator * * @param uriStr the namespace URI * @param typeName the type name * @return the DatatypeValidator associated with namespace & type name */ DatatypeValidator* getDatatypeValidator(const XMLCh* const uriStr, const XMLCh* const typeName); /** * Retrieve the grammar that is associated with the specified namespace key * * @param gramDesc Namespace key into Grammar pool * @return Grammar abstraction associated with the NameSpace key. */ Grammar* getGrammar( XMLGrammarDescription* const gramDesc ) ; /** * Get an enumeration of Grammar in the Grammar pool * * @return enumeration of Grammar in Grammar pool */ RefHashTableOfEnumerator<GrammarEntry> getGrammarEnumerator() const; /** * Get a string pool of schema grammar element/attribute names/prefixes * (used by TraverseSchema) * * @return a string pool of schema grammar element/attribute names/prefixes */ XMLStringPool* getStringPool(); /** * Is the specified Namespace key in Grammar pool? * * @param nameSpaceKey Namespace key * @return True if Namespace key association is in the Grammar pool. */ bool containsNameSpace( const XMLCh* const nameSpaceKey ); inline XMLGrammarPool* const getGrammarPool() const; //@} /** @name Setter methods */ //@{ /** * Set the 'Grammar caching' flag */ void cacheGrammarFromParse(const bool newState); /** * Set the 'Use cached grammar' flag */ void useCachedGrammarInParse(const bool newState); //@} /** @name GrammarResolver methods */ //@{ /** * Add the Grammar with Namespace Key associated to the Grammar Pool. * The Grammar will be owned by the Grammar Pool. * * @param gramDesc Key to associate with Grammar abstraction * @param grammarToAdopt Grammar abstraction used by validator. */ void putGrammar(XMLGrammarDescription* const gramDesc , Grammar* const grammarToAdopt ); /** * Returns the Grammar with Namespace Key associated from the Grammar Pool * The Key entry is removed from the table (grammar is not deleted if * adopted - now owned by caller). * * @param gramDesc Key to associate with Grammar abstraction */ Grammar* orphanGrammar(XMLGrammarDescription* const gramDesc); /** * Cache the grammars in fGrammarBucket to fCachedGrammarRegistry. * If a grammar with the same key is already cached, an exception is * thrown and none of the grammars will be cached. */ void cacheGrammars(); /** * Reset internal Namespace/Grammar registry. */ void reset(); void resetCachedGrammar(); //@} private: XMLGrammarDescription* getGrammarDescription(const XMLCh* const); // ----------------------------------------------------------------------- // Private data members // // fStringPool The string pool used by TraverseSchema to store // element/attribute names and prefixes. // // fGrammarBucket The parsed Grammar Pool, if no caching option. // // fCachedGrammarRegistry The cached Grammar Pool. It represents a // mapping between Namespace and a Grammar // // fDataTypeReg DatatypeValidatorFactory registery // // fMemoryManager Pluggable memory manager for dynamic memory // allocation/deallocation // ----------------------------------------------------------------------- bool fCacheGrammar; bool fUseCachedGrammar; bool fGrammarPoolFromExternalApplication; XMLStringPool fStringPool; RefHashTableOf<GrammarEntry>* fGrammarBucket; DatatypeValidatorFactory* fDataTypeReg; MemoryManager* fMemoryManager; XMLGrammarPool* fGrammarPool; }; inline XMLStringPool* GrammarResolver::getStringPool() { return &fStringPool; } inline void GrammarResolver::useCachedGrammarInParse(const bool aValue) { fUseCachedGrammar = aValue; } inline XMLGrammarPool* const GrammarResolver::getGrammarPool() const { return fGrammarPool; } XERCES_CPP_NAMESPACE_END #endif <commit_msg>Stateless Grammar: getGrammarPoolMemoryManager()<commit_after>/* * The Apache Software License, Version 1.1 * * * Copyright (c) 2001 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "Xerces" and "Apache Software Foundation" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact [email protected]. * * 5. Products derived from this software may not be called "Apache", * nor may "Apache" appear in their name, without prior written * permission of the Apache Software Foundation. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation and was * originally based on software copyright (c) 2001, International * Business Machines, Inc., http://www.apache.org. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. */ /** * $Id$ */ #if !defined(GRAMMARRESOLVER_HPP) #define GRAMMARRESOLVER_HPP #include <xercesc/framework/XMLGrammarPool.hpp> #include <xercesc/util/RefHashTableOf.hpp> #include <xercesc/util/StringPool.hpp> #include <xercesc/validators/common/Grammar.hpp> XERCES_CPP_NAMESPACE_BEGIN class DatatypeValidator; class DatatypeValidatorFactory; class XMLGrammarDescription; class GrammarEntry; /** * This class embodies the representation of a Grammar pool Resolver. * This class is called from the validator. * */ class VALIDATORS_EXPORT GrammarResolver : public XMemory { public: /** @name Constructor and Destructor */ //@{ /** * * Default Constructor */ GrammarResolver( XMLGrammarPool* const gramPool , MemoryManager* const manager = XMLPlatformUtils::fgMemoryManager ); /** * Destructor */ ~GrammarResolver(); //@} /** @name Getter methods */ //@{ /** * Retrieve the DatatypeValidator * * @param uriStr the namespace URI * @param typeName the type name * @return the DatatypeValidator associated with namespace & type name */ DatatypeValidator* getDatatypeValidator(const XMLCh* const uriStr, const XMLCh* const typeName); /** * Retrieve the grammar that is associated with the specified namespace key * * @param gramDesc Namespace key into Grammar pool * @return Grammar abstraction associated with the NameSpace key. */ Grammar* getGrammar( XMLGrammarDescription* const gramDesc ) ; /** * Get an enumeration of Grammar in the Grammar pool * * @return enumeration of Grammar in Grammar pool */ RefHashTableOfEnumerator<GrammarEntry> getGrammarEnumerator() const; /** * Get a string pool of schema grammar element/attribute names/prefixes * (used by TraverseSchema) * * @return a string pool of schema grammar element/attribute names/prefixes */ XMLStringPool* getStringPool(); /** * Is the specified Namespace key in Grammar pool? * * @param nameSpaceKey Namespace key * @return True if Namespace key association is in the Grammar pool. */ bool containsNameSpace( const XMLCh* const nameSpaceKey ); inline XMLGrammarPool* const getGrammarPool() const; inline MemoryManager* const getGrammarPoolMemoryManager() const; //@} /** @name Setter methods */ //@{ /** * Set the 'Grammar caching' flag */ void cacheGrammarFromParse(const bool newState); /** * Set the 'Use cached grammar' flag */ void useCachedGrammarInParse(const bool newState); //@} /** @name GrammarResolver methods */ //@{ /** * Add the Grammar with Namespace Key associated to the Grammar Pool. * The Grammar will be owned by the Grammar Pool. * * @param gramDesc Key to associate with Grammar abstraction * @param grammarToAdopt Grammar abstraction used by validator. */ void putGrammar(XMLGrammarDescription* const gramDesc , Grammar* const grammarToAdopt ); /** * Returns the Grammar with Namespace Key associated from the Grammar Pool * The Key entry is removed from the table (grammar is not deleted if * adopted - now owned by caller). * * @param gramDesc Key to associate with Grammar abstraction */ Grammar* orphanGrammar(XMLGrammarDescription* const gramDesc); /** * Cache the grammars in fGrammarBucket to fCachedGrammarRegistry. * If a grammar with the same key is already cached, an exception is * thrown and none of the grammars will be cached. */ void cacheGrammars(); /** * Reset internal Namespace/Grammar registry. */ void reset(); void resetCachedGrammar(); //@} private: XMLGrammarDescription* getGrammarDescription(const XMLCh* const); // ----------------------------------------------------------------------- // Private data members // // fStringPool The string pool used by TraverseSchema to store // element/attribute names and prefixes. // // fGrammarBucket The parsed Grammar Pool, if no caching option. // // fCachedGrammarRegistry The cached Grammar Pool. It represents a // mapping between Namespace and a Grammar // // fDataTypeReg DatatypeValidatorFactory registery // // fMemoryManager Pluggable memory manager for dynamic memory // allocation/deallocation // ----------------------------------------------------------------------- bool fCacheGrammar; bool fUseCachedGrammar; bool fGrammarPoolFromExternalApplication; XMLStringPool fStringPool; RefHashTableOf<GrammarEntry>* fGrammarBucket; DatatypeValidatorFactory* fDataTypeReg; MemoryManager* fMemoryManager; XMLGrammarPool* fGrammarPool; }; inline XMLStringPool* GrammarResolver::getStringPool() { return &fStringPool; } inline void GrammarResolver::useCachedGrammarInParse(const bool aValue) { fUseCachedGrammar = aValue; } inline XMLGrammarPool* const GrammarResolver::getGrammarPool() const { return fGrammarPool; } inline MemoryManager* const GrammarResolver::getGrammarPoolMemoryManager() const { return fGrammarPool->getMemoryManager(); } XERCES_CPP_NAMESPACE_END #endif <|endoftext|>
<commit_before>/* * V1.cpp * * Created on: Jul 30, 2008 * Author: rasmussn */ #include "../include/pv_common.h" #include "../include/default_params.h" #include "../connections/PVConnection.h" #include "HyPerLayer.hpp" #include "V1.hpp" #include <assert.h> #include <float.h> #include <math.h> #include <stdio.h> #include <stdlib.h> #include <string.h> namespace PV { V1Params V1DefaultParams = { V_REST, V_EXC, V_INH, V_INHB, // V (mV) TAU_VMEM, TAU_EXC, TAU_INH, TAU_INHB, VTH_REST, TAU_VTH, DELTA_VTH, DELTA_VTH_DECAY, // tau (ms) 250, NOISE_AMP*( 1.0/TAU_EXC ) * ( ( TAU_INH * (V_REST-V_INH) + TAU_INHB * (V_REST-V_INHB) ) / (V_EXC-V_REST) ), 250, NOISE_AMP*1.0, 250, NOISE_AMP*1.0 // noise (G) }; V1::V1(const char* name, HyPerCol * hc) { initialize(name, hc, TypeV1Simple); } V1::V1(const char* name, HyPerCol * hc, PVLayerType type) { initialize(name, hc, type); } void V1::initialize(const char* name, HyPerCol * hc, PVLayerType type) { setParent(hc); init(name, type); setParams(parent->parameters(), &V1DefaultParams); pvlayer_setFuncs(clayer, (INIT_FN) &LIF2_init, (UPDATE_FN) &LIF2_update_exact_linear); hc->addLayer(this); } int V1::setParams(PVParams * params, V1Params * p) { const char * name = getName(); float dt = .001 * parent->getDeltaTime(); // seconds clayer->params = (float *) malloc(sizeof(*p)); memcpy(clayer->params, p, sizeof(*p)); clayer->numParams = sizeof(*p) / sizeof(float); assert(clayer->numParams == 18); V1Params * cp = (V1Params *) clayer->params; if (params->present(name, "Vrest")) cp->Vrest = params->value(name, "Vrest"); if (params->present(name, "Vexc")) cp->Vexc = params->value(name, "Vexc"); if (params->present(name, "Vinh")) cp->Vinh = params->value(name, "Vinh"); if (params->present(name, "VinhB")) cp->VinhB = params->value(name, "VinhB"); if (params->present(name, "tau")) cp->tau = params->value(name, "tau"); if (params->present(name, "tauE")) cp->tauE = params->value(name, "tauE"); if (params->present(name, "tauI")) cp->tauI = params->value(name, "tauI"); if (params->present(name, "tauIB")) cp->tauIB = params->value(name, "tauIB"); if (params->present(name, "VthRest")) cp->VthRest = params->value(name, "VthRest"); if (params->present(name, "tauVth")) cp->tauVth = params->value(name, "tauVth"); if (params->present(name, "deltaVth")) cp->deltaVth = params->value(name, "deltaVth"); if (params->present(name, "deltaVthDecay")) cp->deltaVthDecay = params->value(name, "deltaVthDecay"); if (params->present(name, "noiseAmpE")) cp->noiseAmpE = params->value(name, "noiseAmpE"); if (params->present(name, "noiseAmpI")) cp->noiseAmpI = params->value(name, "noiseAmpI"); if (params->present(name, "noiseAmpIB")) cp->noiseAmpIB = params->value(name, "noiseAmpIB"); if (params->present(name, "noiseFreqE")) { cp->noiseFreqE = params->value(name, "noiseFreqE"); if (dt * cp->noiseFreqE > 1.0) cp->noiseFreqE = 1.0 / dt; } if (params->present(name, "noiseFreqI")) { cp->noiseFreqI = params->value(name, "noiseFreqI"); if (dt * cp->noiseFreqI > 1.0) cp->noiseFreqI = 1.0 / dt; } if (params->present(name, "noiseFreqIB")) { cp->noiseFreqIB = params->value(name, "noiseFreqIB"); if (dt * cp->noiseFreqIB > 1.0) cp->noiseFreqIB = 1.0 / dt; } return 0; } int V1::updateState(float time, float dt) { PVParams * params = parent->parameters(); int spikingFlag = 1; pv_debug_info("[%d]: V1::updateState:", clayer->columnId); if (params->present(clayer->name, "spikingFlag")) { spikingFlag = params->value(clayer->name, "spikingFlag"); } if (spikingFlag != 0) { return LIF2_update_exact_linear(clayer, dt); } // just copy accumulation buffer to membrane potential // and activity buffer (nonspiking) pvdata_t * V = clayer->V; pvdata_t * phiExc = clayer->phi[PHI_EXC]; pvdata_t * phiInh = clayer->phi[PHI_INH]; pvdata_t * activity = clayer->activity->data; for (int k = 0; k < clayer->numNeurons; k++) { #ifdef EXTEND_BORDER_INDEX int kPhi = kIndexExtended(k, clayer->loc.nx, clayer->loc.ny, clayer->numFeatures, clayer->numBorder); #else int kPhi = k; #endif V[k] = phiExc[kPhi] - phiInh[kPhi]; activity[k] = V[k]; // reset accumulation buffers phiExc[kPhi] = 0.0; phiInh[kPhi] = 0.0; } return 0; } int V1::writeState(const char * path, float time) { HyPerLayer::writeState(path, time); #ifdef DEBUG_OUTPUT // print activity at center of image int sx = clayer->numFeatures; int sy = sx*clayer->loc.nx; pvdata_t * a = clayer->activity->data; int n = (int) (sy*(clayer->loc.ny/2 - 1) + sx*(clayer->loc.nx/2)); for (int f = 0; f < clayer->numFeatures; f++) { printf("f = %d, a[%d] = %f\n", f, n, a[n]); n += 1; } printf("\n"); n = (int) (sy*(clayer->loc.ny/2 - 1) + sx*(clayer->loc.nx/2)); n -= 8; for (int f = 0; f < clayer->numFeatures; f++) { printf("f = %d, a[%d] = %f\n", f, n, a[n]); n += 1; } #endif return 0; } int V1::findPostSynaptic(int dim, int maxSize, int col, // input: which layer, which neuron HyPerLayer *lSource, float pos[], // output: how many of our neurons are connected. // an array with their indices. // an array with their feature vectors. int* nNeurons, int nConnectedNeurons[], float *vPos) { return 0; } } // namespace PV <commit_msg>Removed deltaVthDecay (an experiment that should never have been committed).<commit_after>/* * V1.cpp * * Created on: Jul 30, 2008 * Author: rasmussn */ #include "../include/pv_common.h" #include "../include/default_params.h" #include "../connections/PVConnection.h" #include "HyPerLayer.hpp" #include "V1.hpp" #include <assert.h> #include <float.h> #include <math.h> #include <stdio.h> #include <stdlib.h> #include <string.h> namespace PV { V1Params V1DefaultParams = { V_REST, V_EXC, V_INH, V_INHB, // V (mV) TAU_VMEM, TAU_EXC, TAU_INH, TAU_INHB, VTH_REST, TAU_VTH, DELTA_VTH, // tau (ms) 250, NOISE_AMP*( 1.0/TAU_EXC ) * ( ( TAU_INH * (V_REST-V_INH) + TAU_INHB * (V_REST-V_INHB) ) / (V_EXC-V_REST) ), 250, NOISE_AMP*1.0, 250, NOISE_AMP*1.0 // noise (G) }; V1::V1(const char* name, HyPerCol * hc) { initialize(name, hc, TypeV1Simple); } V1::V1(const char* name, HyPerCol * hc, PVLayerType type) { initialize(name, hc, type); } void V1::initialize(const char* name, HyPerCol * hc, PVLayerType type) { setParent(hc); init(name, type); setParams(parent->parameters(), &V1DefaultParams); pvlayer_setFuncs(clayer, (INIT_FN) &LIF2_init, (UPDATE_FN) &LIF2_update_exact_linear); hc->addLayer(this); } int V1::setParams(PVParams * params, V1Params * p) { const char * name = getName(); float dt = .001 * parent->getDeltaTime(); // seconds clayer->params = (float *) malloc(sizeof(*p)); memcpy(clayer->params, p, sizeof(*p)); clayer->numParams = sizeof(*p) / sizeof(float); assert(clayer->numParams == 17); V1Params * cp = (V1Params *) clayer->params; if (params->present(name, "Vrest")) cp->Vrest = params->value(name, "Vrest"); if (params->present(name, "Vexc")) cp->Vexc = params->value(name, "Vexc"); if (params->present(name, "Vinh")) cp->Vinh = params->value(name, "Vinh"); if (params->present(name, "VinhB")) cp->VinhB = params->value(name, "VinhB"); if (params->present(name, "tau")) cp->tau = params->value(name, "tau"); if (params->present(name, "tauE")) cp->tauE = params->value(name, "tauE"); if (params->present(name, "tauI")) cp->tauI = params->value(name, "tauI"); if (params->present(name, "tauIB")) cp->tauIB = params->value(name, "tauIB"); if (params->present(name, "VthRest")) cp->VthRest = params->value(name, "VthRest"); if (params->present(name, "tauVth")) cp->tauVth = params->value(name, "tauVth"); if (params->present(name, "deltaVth")) cp->deltaVth = params->value(name, "deltaVth"); if (params->present(name, "noiseAmpE")) cp->noiseAmpE = params->value(name, "noiseAmpE"); if (params->present(name, "noiseAmpI")) cp->noiseAmpI = params->value(name, "noiseAmpI"); if (params->present(name, "noiseAmpIB")) cp->noiseAmpIB = params->value(name, "noiseAmpIB"); if (params->present(name, "noiseFreqE")) { cp->noiseFreqE = params->value(name, "noiseFreqE"); if (dt * cp->noiseFreqE > 1.0) cp->noiseFreqE = 1.0 / dt; } if (params->present(name, "noiseFreqI")) { cp->noiseFreqI = params->value(name, "noiseFreqI"); if (dt * cp->noiseFreqI > 1.0) cp->noiseFreqI = 1.0 / dt; } if (params->present(name, "noiseFreqIB")) { cp->noiseFreqIB = params->value(name, "noiseFreqIB"); if (dt * cp->noiseFreqIB > 1.0) cp->noiseFreqIB = 1.0 / dt; } return 0; } int V1::updateState(float time, float dt) { PVParams * params = parent->parameters(); int spikingFlag = 1; pv_debug_info("[%d]: V1::updateState:", clayer->columnId); if (params->present(clayer->name, "spikingFlag")) { spikingFlag = params->value(clayer->name, "spikingFlag"); } if (spikingFlag != 0) { return LIF2_update_exact_linear(clayer, dt); } // just copy accumulation buffer to membrane potential // and activity buffer (nonspiking) pvdata_t * V = clayer->V; pvdata_t * phiExc = clayer->phi[PHI_EXC]; pvdata_t * phiInh = clayer->phi[PHI_INH]; pvdata_t * activity = clayer->activity->data; for (int k = 0; k < clayer->numNeurons; k++) { #ifdef EXTEND_BORDER_INDEX int kPhi = kIndexExtended(k, clayer->loc.nx, clayer->loc.ny, clayer->numFeatures, clayer->numBorder); #else int kPhi = k; #endif V[k] = phiExc[kPhi] - phiInh[kPhi]; activity[k] = V[k]; // reset accumulation buffers phiExc[kPhi] = 0.0; phiInh[kPhi] = 0.0; } return 0; } int V1::writeState(const char * path, float time) { HyPerLayer::writeState(path, time); #ifdef DEBUG_OUTPUT // print activity at center of image int sx = clayer->numFeatures; int sy = sx*clayer->loc.nx; pvdata_t * a = clayer->activity->data; int n = (int) (sy*(clayer->loc.ny/2 - 1) + sx*(clayer->loc.nx/2)); for (int f = 0; f < clayer->numFeatures; f++) { printf("f = %d, a[%d] = %f\n", f, n, a[n]); n += 1; } printf("\n"); n = (int) (sy*(clayer->loc.ny/2 - 1) + sx*(clayer->loc.nx/2)); n -= 8; for (int f = 0; f < clayer->numFeatures; f++) { printf("f = %d, a[%d] = %f\n", f, n, a[n]); n += 1; } #endif return 0; } int V1::findPostSynaptic(int dim, int maxSize, int col, // input: which layer, which neuron HyPerLayer *lSource, float pos[], // output: how many of our neurons are connected. // an array with their indices. // an array with their feature vectors. int* nNeurons, int nConnectedNeurons[], float *vPos) { return 0; } } // namespace PV <|endoftext|>
<commit_before> /** * @ingroup tracking_algorithms * @file * Implementation of Correlation * * @author Manuel Huber <[email protected]> */ #include "Correlation.h" #ifdef HAVE_LAPACK namespace Ubitrack { namespace Calibration { double computeCorrelationDirect ( const std::vector< double >& left, const std::vector< double >& right) { double res = 0.0; size_t len = left.size() < right.size() ? left.size() : right.size(); double var1 = 0.0; double var2 = 0.0; double m1 = 0.0; double m2 = 0.0; for (int i=0; i<len; i++) { m1 += left[i]; m2 += right[i]; } m1 /= (double)(len); m2 /= (double)(len); for (int i=0; i<len; i++) { res += (left[i]-m1)*(right[i]-m2); var1 += (left[i]-m1)*(left[i]-m1); var2 += (right[i]-m2)*(right[i]-m2); } double denom = sqrt(var1*var2); return res/denom; } double computeCorrelation ( const std::vector< double >& left, const std::vector< double >& right) { if (left.size() == 0 && right.size() == 0) { return 1.0f; } return computeCorrelationDirect(left,right); } } } // namespace Ubitrack::Calibration #endif // HAVE_LAPACK <commit_msg>fixes to compile on linux<commit_after> /** * @ingroup tracking_algorithms * @file * Implementation of Correlation * * @author Manuel Huber <[email protected]> */ #include "Correlation.h" #include <math.h> #ifdef HAVE_LAPACK namespace Ubitrack { namespace Calibration { double computeCorrelationDirect ( const std::vector< double >& left, const std::vector< double >& right) { double res = 0.0; std::size_t len = left.size() < right.size() ? left.size() : right.size(); double var1 = 0.0; double var2 = 0.0; double m1 = 0.0; double m2 = 0.0; for (int i=0; i<len; i++) { m1 += left[i]; m2 += right[i]; } m1 /= (double)(len); m2 /= (double)(len); for (int i=0; i<len; i++) { res += (left[i]-m1)*(right[i]-m2); var1 += (left[i]-m1)*(left[i]-m1); var2 += (right[i]-m2)*(right[i]-m2); } double denom = sqrt(var1*var2); return res/denom; } double computeCorrelation ( const std::vector< double >& left, const std::vector< double >& right) { if (left.size() == 0 && right.size() == 0) { return 1.0f; } return computeCorrelationDirect(left,right); } } } // namespace Ubitrack::Calibration #endif // HAVE_LAPACK <|endoftext|>
<commit_before>#include <reactive/bridge.hpp> #include <reactive/consume.hpp> #include <boost/optional.hpp> #include <boost/test/unit_test.hpp> #include <lua.hpp> namespace Si { struct lua_deleter { void operator()(lua_State *L) const { lua_close(L); } }; std::unique_ptr<lua_State, lua_deleter> open_lua() { auto L = std::unique_ptr<lua_State, lua_deleter>(luaL_newstate()); if (!L) { throw std::bad_alloc(); } return L; } typedef rx::observer<int> yield_destination; static int yield(lua_State *L) { yield_destination &dest = *static_cast<yield_destination *>(lua_touserdata(L, lua_upvalueindex(1))); int element = lua_tointeger(L, 1); dest.got_element(element); return lua_yield(L, 0); } BOOST_AUTO_TEST_CASE(lua) { auto L = open_lua(); lua_State * const coro = lua_newthread(L.get()); BOOST_REQUIRE_EQUAL(0, luaL_loadstring(coro, "return function (yield) yield(4) yield(5) end")); if (0 != lua_pcall(coro, 0, 1, 0)) { throw std::runtime_error(lua_tostring(L.get(), -1)); } rx::bridge<int> yielded; // fn &yielded lua_pushlightuserdata(coro, &static_cast<yield_destination &>(yielded)); // fn yield[&yielded] lua_pushcclosure(coro, yield, 1); boost::optional<int> got; auto consumer = rx::consume<int>([&got](boost::optional<int> element) { BOOST_REQUIRE(element); got = element; }); { yielded.async_get_one(consumer); int rc = lua_resume(coro, 1); if (LUA_YIELD != rc) { throw std::runtime_error(lua_tostring(coro, -1)); } BOOST_CHECK_EQUAL(boost::make_optional(4), got); } { yielded.async_get_one(consumer); int rc = lua_resume(coro, 1); if (LUA_YIELD != rc) { throw std::runtime_error(lua_tostring(coro, -1)); } BOOST_CHECK_EQUAL(boost::make_optional(5), got); } } } <commit_msg>observable Lua thread in progress<commit_after>#include <reactive/bridge.hpp> #include <reactive/consume.hpp> #include <boost/optional.hpp> #include <boost/test/unit_test.hpp> #include <lua.hpp> namespace Si { struct lua_deleter { void operator()(lua_State *L) const { lua_close(L); } }; std::unique_ptr<lua_State, lua_deleter> open_lua() { auto L = std::unique_ptr<lua_State, lua_deleter>(luaL_newstate()); if (!L) { throw std::bad_alloc(); } return L; } typedef rx::observer<lua_Integer> yield_destination; static int yield(lua_State *L) { yield_destination &dest = *static_cast<yield_destination *>(lua_touserdata(L, lua_upvalueindex(1))); lua_Integer element = lua_tointeger(L, 1); dest.got_element(element); return lua_yield(L, 0); } BOOST_AUTO_TEST_CASE(lua) { auto L = open_lua(); lua_State * const coro = lua_newthread(L.get()); BOOST_REQUIRE_EQUAL(0, luaL_loadstring(coro, "return function (yield) yield(4) yield(5) end")); if (0 != lua_pcall(coro, 0, 1, 0)) { throw std::runtime_error(lua_tostring(L.get(), -1)); } rx::bridge<lua_Integer> yielded; lua_pushlightuserdata(coro, &static_cast<yield_destination &>(yielded)); lua_pushcclosure(coro, yield, 1); boost::optional<lua_Integer> got; auto consumer = rx::consume<lua_Integer>([&got](boost::optional<lua_Integer> element) { BOOST_REQUIRE(element); got = element; }); { yielded.async_get_one(consumer); int rc = lua_resume(coro, 1); if (LUA_YIELD != rc) { throw std::runtime_error(lua_tostring(coro, -1)); } BOOST_CHECK_EQUAL(boost::make_optional<lua_Integer>(4), got); } { yielded.async_get_one(consumer); int rc = lua_resume(coro, 1); if (LUA_YIELD != rc) { throw std::runtime_error(lua_tostring(coro, -1)); } BOOST_CHECK_EQUAL(boost::make_optional<lua_Integer>(5), got); } } } namespace rx { template <class Element, class ElementFromLua> struct lua_thread : public observable<Element> { using element_type = Element; explicit lua_thread(lua_State &thread, ElementFromLua from_lua) : s(std::make_shared<state>(thread, std::move(from_lua))) { } virtual void async_get_one(observer<element_type> &receiver) SILICIUM_OVERRIDE { s->receiver = &receiver; if (s->was_resumed) { lua_resume(s->thread, 0); } else { void *bound_state = lua_newuserdata(s->thread, sizeof(weak_state)); new (static_cast<weak_state *>(bound_state)) weak_state(s); //TODO __gc //TODO error handling lua_pushcclosure(s->thread, lua_thread::yield, 1); lua_resume(s->thread, 1); } } virtual void cancel() SILICIUM_OVERRIDE { s.reset(); } private: struct state { //TODO: keep the Lua thread alive lua_State *thread = nullptr; ElementFromLua from_lua; bool was_resumed = false; observer<element_type> *receiver = nullptr; explicit state(lua_State &thread, ElementFromLua from_lua) : thread(&thread) , from_lua(std::move(from_lua)) { } }; typedef std::weak_ptr<state> weak_state; std::shared_ptr<state> s; static int yield(lua_State *thread) { weak_state * const bound_state = static_cast<weak_state *>(lua_touserdata(thread, lua_upvalueindex(1))); std::shared_ptr<state> locked_state = bound_state->lock(); if (!locked_state) { return 0; } assert(locked_state->receiver); exchange(locked_state->receiver, nullptr)->got_element(locked_state->from_lua(*thread, -1)); return 0; } }; inline void swap_top(lua_State &lua) { lua_pushvalue(&lua, -2); lua_remove(&lua, -3); } template <class Element, class ElementFromLua> auto make_lua_thread(lua_State &parent, ElementFromLua &&from_lua) { lua_State * const coro = lua_newthread(&parent); lua_xmove(&parent, coro, 2); swap_top(*coro); return lua_thread<Element, typename std::decay<ElementFromLua>::type>(parent, std::forward<ElementFromLua>(from_lua)); } } namespace Si { BOOST_AUTO_TEST_CASE(lua_thread_observable) { auto L = open_lua(); BOOST_REQUIRE_EQUAL(0, luaL_loadstring(L.get(), "return function (yield) yield(4) yield(5) end")); if (0 != lua_pcall(L.get(), 0, 1, 0)) { throw std::runtime_error(lua_tostring(L.get(), -1)); } auto thread = rx::make_lua_thread<lua_Integer>(*L, [](lua_State &lua, int idx) -> lua_Integer { return lua_tointeger(&lua, idx); }); } } <|endoftext|>
<commit_before>// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #include "common.h" #include "eventpipeeventinstance.h" #include "eventpipejsonfile.h" #include "fastserializer.h" #include "sampleprofiler.h" #ifdef FEATURE_PERFTRACING EventPipeEventInstance::EventPipeEventInstance( EventPipeEvent &event, DWORD threadID, BYTE *pData, unsigned int length) { CONTRACTL { THROWS; GC_TRIGGERS; MODE_ANY; } CONTRACTL_END; #ifdef _DEBUG m_debugEventStart = 0xDEADBEEF; m_debugEventEnd = 0xCAFEBABE; #endif // _DEBUG m_pEvent = &event; m_threadID = threadID; m_pData = pData; m_dataLength = length; QueryPerformanceCounter(&m_timeStamp); if(event.NeedStack()) { EventPipe::WalkManagedStackForCurrentThread(m_stackContents); } #ifdef _DEBUG EnsureConsistency(); #endif // _DEBUG } StackContents* EventPipeEventInstance::GetStack() { LIMITED_METHOD_CONTRACT; return &m_stackContents; } EventPipeEvent* EventPipeEventInstance::GetEvent() const { LIMITED_METHOD_CONTRACT; return m_pEvent; } LARGE_INTEGER EventPipeEventInstance::GetTimeStamp() const { LIMITED_METHOD_CONTRACT; return m_timeStamp; } BYTE* EventPipeEventInstance::GetData() const { LIMITED_METHOD_CONTRACT; return m_pData; } unsigned int EventPipeEventInstance::GetLength() const { LIMITED_METHOD_CONTRACT; return m_dataLength; } void EventPipeEventInstance::FastSerialize(FastSerializer *pSerializer, StreamLabel metadataLabel) { CONTRACTL { THROWS; GC_TRIGGERS; MODE_ANY; } CONTRACTL_END; #ifdef _DEBUG // Useful for diagnosing serialization bugs. const unsigned int value = 0xDEADBEEF; pSerializer->WriteBuffer((BYTE*)&value, sizeof(value)); #endif // Calculate the size of the total payload so that it can be written to the file. unsigned int payloadLength = sizeof(metadataLabel) + sizeof(m_threadID) + // Thread ID sizeof(m_timeStamp) + // TimeStamp m_dataLength + // Event payload data length m_stackContents.GetSize(); // Stack payload size // Write the size of the event to the file. pSerializer->WriteBuffer((BYTE*)&payloadLength, sizeof(payloadLength)); // Write the metadata label. pSerializer->WriteBuffer((BYTE*)&metadataLabel, sizeof(metadataLabel)); // Write the thread ID. pSerializer->WriteBuffer((BYTE*)&m_threadID, sizeof(m_threadID)); // Write the timestamp. pSerializer->WriteBuffer((BYTE*)&m_timeStamp, sizeof(m_timeStamp)); // Write the event data payload. if(m_dataLength > 0) { pSerializer->WriteBuffer(m_pData, m_dataLength); } // Write the stack if present. if(m_stackContents.GetSize() > 0) { pSerializer->WriteBuffer(m_stackContents.GetPointer(), m_stackContents.GetSize()); } } #ifdef _DEBUG void EventPipeEventInstance::SerializeToJsonFile(EventPipeJsonFile *pFile) { CONTRACTL { NOTHROW; GC_NOTRIGGER; MODE_ANY; } CONTRACTL_END; if(pFile == NULL) { return; } EX_TRY { const unsigned int guidSize = 39; WCHAR wszProviderID[guidSize]; if(!StringFromGUID2(m_pEvent->GetProvider()->GetProviderID(), wszProviderID, guidSize)) { wszProviderID[0] = '\0'; } // Strip off the {}. StackScratchBuffer scratch; SString guidStr(&wszProviderID[1], guidSize-3); SString message; message.Printf("Provider=%s/EventID=%d/Version=%d", guidStr.GetANSI(scratch), m_pEvent->GetEventID(), m_pEvent->GetEventVersion()); pFile->WriteEvent(m_timeStamp, m_threadID, message, m_stackContents); } EX_CATCH{} EX_END_CATCH(SwallowAllExceptions); } #endif void EventPipeEventInstance::SetTimeStamp(LARGE_INTEGER timeStamp) { LIMITED_METHOD_CONTRACT; m_timeStamp = timeStamp; } #ifdef _DEBUG bool EventPipeEventInstance::EnsureConsistency() { CONTRACTL { NOTHROW; GC_NOTRIGGER; MODE_ANY; } CONTRACTL_END; // Validate event start. _ASSERTE(m_debugEventStart == 0xDEADBEEF); // Validate event end. _ASSERTE(m_debugEventEnd == 0xCAFEBABE); return true; } #endif // _DEBUG SampleProfilerEventInstance::SampleProfilerEventInstance(Thread *pThread) :EventPipeEventInstance(*SampleProfiler::s_pThreadTimeEvent, pThread->GetOSThreadId(), NULL, 0) { LIMITED_METHOD_CONTRACT; } #endif // FEATURE_PERFTRACING <commit_msg>Put the serialization marker under its own IFDEF. (#11568)<commit_after>// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #include "common.h" #include "eventpipeeventinstance.h" #include "eventpipejsonfile.h" #include "fastserializer.h" #include "sampleprofiler.h" #ifdef FEATURE_PERFTRACING EventPipeEventInstance::EventPipeEventInstance( EventPipeEvent &event, DWORD threadID, BYTE *pData, unsigned int length) { CONTRACTL { THROWS; GC_TRIGGERS; MODE_ANY; } CONTRACTL_END; #ifdef _DEBUG m_debugEventStart = 0xDEADBEEF; m_debugEventEnd = 0xCAFEBABE; #endif // _DEBUG m_pEvent = &event; m_threadID = threadID; m_pData = pData; m_dataLength = length; QueryPerformanceCounter(&m_timeStamp); if(event.NeedStack()) { EventPipe::WalkManagedStackForCurrentThread(m_stackContents); } #ifdef _DEBUG EnsureConsistency(); #endif // _DEBUG } StackContents* EventPipeEventInstance::GetStack() { LIMITED_METHOD_CONTRACT; return &m_stackContents; } EventPipeEvent* EventPipeEventInstance::GetEvent() const { LIMITED_METHOD_CONTRACT; return m_pEvent; } LARGE_INTEGER EventPipeEventInstance::GetTimeStamp() const { LIMITED_METHOD_CONTRACT; return m_timeStamp; } BYTE* EventPipeEventInstance::GetData() const { LIMITED_METHOD_CONTRACT; return m_pData; } unsigned int EventPipeEventInstance::GetLength() const { LIMITED_METHOD_CONTRACT; return m_dataLength; } void EventPipeEventInstance::FastSerialize(FastSerializer *pSerializer, StreamLabel metadataLabel) { CONTRACTL { THROWS; GC_TRIGGERS; MODE_ANY; } CONTRACTL_END; #ifdef EVENTPIPE_EVENT_MARKER // Useful for diagnosing serialization bugs. const unsigned int value = 0xDEADBEEF; pSerializer->WriteBuffer((BYTE*)&value, sizeof(value)); #endif // Calculate the size of the total payload so that it can be written to the file. unsigned int payloadLength = sizeof(metadataLabel) + sizeof(m_threadID) + // Thread ID sizeof(m_timeStamp) + // TimeStamp m_dataLength + // Event payload data length m_stackContents.GetSize(); // Stack payload size // Write the size of the event to the file. pSerializer->WriteBuffer((BYTE*)&payloadLength, sizeof(payloadLength)); // Write the metadata label. pSerializer->WriteBuffer((BYTE*)&metadataLabel, sizeof(metadataLabel)); // Write the thread ID. pSerializer->WriteBuffer((BYTE*)&m_threadID, sizeof(m_threadID)); // Write the timestamp. pSerializer->WriteBuffer((BYTE*)&m_timeStamp, sizeof(m_timeStamp)); // Write the event data payload. if(m_dataLength > 0) { pSerializer->WriteBuffer(m_pData, m_dataLength); } // Write the stack if present. if(m_stackContents.GetSize() > 0) { pSerializer->WriteBuffer(m_stackContents.GetPointer(), m_stackContents.GetSize()); } } #ifdef _DEBUG void EventPipeEventInstance::SerializeToJsonFile(EventPipeJsonFile *pFile) { CONTRACTL { NOTHROW; GC_NOTRIGGER; MODE_ANY; } CONTRACTL_END; if(pFile == NULL) { return; } EX_TRY { const unsigned int guidSize = 39; WCHAR wszProviderID[guidSize]; if(!StringFromGUID2(m_pEvent->GetProvider()->GetProviderID(), wszProviderID, guidSize)) { wszProviderID[0] = '\0'; } // Strip off the {}. StackScratchBuffer scratch; SString guidStr(&wszProviderID[1], guidSize-3); SString message; message.Printf("Provider=%s/EventID=%d/Version=%d", guidStr.GetANSI(scratch), m_pEvent->GetEventID(), m_pEvent->GetEventVersion()); pFile->WriteEvent(m_timeStamp, m_threadID, message, m_stackContents); } EX_CATCH{} EX_END_CATCH(SwallowAllExceptions); } #endif void EventPipeEventInstance::SetTimeStamp(LARGE_INTEGER timeStamp) { LIMITED_METHOD_CONTRACT; m_timeStamp = timeStamp; } #ifdef _DEBUG bool EventPipeEventInstance::EnsureConsistency() { CONTRACTL { NOTHROW; GC_NOTRIGGER; MODE_ANY; } CONTRACTL_END; // Validate event start. _ASSERTE(m_debugEventStart == 0xDEADBEEF); // Validate event end. _ASSERTE(m_debugEventEnd == 0xCAFEBABE); return true; } #endif // _DEBUG SampleProfilerEventInstance::SampleProfilerEventInstance(Thread *pThread) :EventPipeEventInstance(*SampleProfiler::s_pThreadTimeEvent, pThread->GetOSThreadId(), NULL, 0) { LIMITED_METHOD_CONTRACT; } #endif // FEATURE_PERFTRACING <|endoftext|>
<commit_before>#include <type_traits> #include <cassert> #include <map> #include <string> #include <duktape.h> #include <gtest/gtest.h> #include <entt/core/type_info.hpp> #include <entt/entity/registry.hpp> template<typename Type> struct tag { using type = Type; }; struct position { double x; double y; }; struct renderable {}; struct duktape_runtime { std::map<duk_uint_t, std::string> components; }; template<typename Comp> duk_ret_t set(duk_context *ctx, entt::registry &registry) { const entt::entity entity{duk_require_uint(ctx, 0)}; if constexpr(std::is_same_v<Comp, position>) { const auto x = duk_require_number(ctx, 2); const auto y = duk_require_number(ctx, 3); registry.assign_or_replace<position>(entity, x, y); } else if constexpr(std::is_same_v<Comp, duktape_runtime>) { const auto type = duk_require_uint(ctx, 1); duk_dup(ctx, 2); if(!registry.has<duktape_runtime>(entity)) { registry.assign<duktape_runtime>(entity).components[type] = duk_json_encode(ctx, -1); } else { registry.get<duktape_runtime>(entity).components[type] = duk_json_encode(ctx, -1); } duk_pop(ctx); } else { registry.assign_or_replace<Comp>(entity); } return 0; } template<typename Comp> duk_ret_t unset(duk_context *ctx, entt::registry &registry) { const entt::entity entity{duk_require_uint(ctx, 0)}; if constexpr(std::is_same_v<Comp, duktape_runtime>) { const auto type = duk_require_uint(ctx, 1); auto &components = registry.get<duktape_runtime>(entity).components; assert(components.find(type) != components.cend()); components.erase(type); if(components.empty()) { registry.remove<duktape_runtime>(entity); } } else { registry.remove<Comp>(entity); } return 0; } template<typename Comp> duk_ret_t has(duk_context *ctx, entt::registry &registry) { const entt::entity entity{duk_require_uint(ctx, 0)}; if constexpr(std::is_same_v<Comp, duktape_runtime>) { duk_push_boolean(ctx, registry.has<duktape_runtime>(entity)); if(registry.has<duktape_runtime>(entity)) { const auto type = duk_require_uint(ctx, 1); const auto &components = registry.get<duktape_runtime>(entity).components; duk_push_boolean(ctx, components.find(type) != components.cend()); } else { duk_push_false(ctx); } } else { duk_push_boolean(ctx, registry.has<Comp>(entity)); } return 1; } template<typename Comp> duk_ret_t get(duk_context *ctx, entt::registry &registry) { [[maybe_unused]] const entt::entity entity{duk_require_uint(ctx, 0)}; if constexpr(std::is_same_v<Comp, position>) { const auto &pos = registry.get<position>(entity); const auto idx = duk_push_object(ctx); duk_push_string(ctx, "x"); duk_push_number(ctx, pos.x); duk_def_prop(ctx, idx, DUK_DEFPROP_HAVE_VALUE); duk_push_string(ctx, "y"); duk_push_number(ctx, pos.y); duk_def_prop(ctx, idx, DUK_DEFPROP_HAVE_VALUE); } if constexpr(std::is_same_v<Comp, duktape_runtime>) { const auto type = duk_require_uint(ctx, 1); auto &runtime = registry.get<duktape_runtime>(entity); assert(runtime.components.find(type) != runtime.components.cend()); duk_push_string(ctx, runtime.components[type].c_str()); duk_json_decode(ctx, -1); } else { assert(registry.has<Comp>(entity)); duk_push_object(ctx); } return 1; } class duktape_registry { struct func_map { using func_type = duk_ret_t(*)(duk_context *, entt::registry &); func_type set; func_type unset; func_type has; func_type get; }; template<typename... Comp> void reg() { ((func[entt::type_info<Comp>::id()] = { &::set<Comp>, &::unset<Comp>, &::has<Comp>, &::get<Comp> }), ...); } static duktape_registry & instance(duk_context *ctx) { duk_push_this(ctx); duk_push_string(ctx, DUK_HIDDEN_SYMBOL("dreg")); duk_get_prop(ctx, -2); auto &dreg = *static_cast<duktape_registry *>(duk_require_pointer(ctx, -1)); duk_pop_2(ctx); return dreg; } template<func_map::func_type func_map::*Op> static duk_ret_t invoke(duk_context *ctx) { auto &dreg = instance(ctx); auto &func = dreg.func; auto &registry = dreg.registry; auto type = duk_require_uint(ctx, 1); const auto it = func.find(type); return (it == func.cend()) ? (func[entt::type_info<duktape_runtime>::id()].*Op)(ctx, registry) : (it->second.*Op)(ctx, registry); } public: duktape_registry(entt::registry &ref) : registry{ref} { reg<position, renderable, duktape_runtime>(); } static duk_ret_t identifier(duk_context *ctx) { static ENTT_ID_TYPE next{}; duk_push_uint(ctx, next++); return 1; } static duk_ret_t create(duk_context *ctx) { auto &dreg = instance(ctx); const auto entity = dreg.registry.create(); duk_push_uint(ctx, static_cast<std::underlying_type_t<entt::entity>>(entity)); return 1; } static duk_ret_t set(duk_context *ctx) { return invoke<&func_map::set>(ctx); } static duk_ret_t unset(duk_context *ctx) { return invoke<&func_map::unset>(ctx); } static duk_ret_t has(duk_context *ctx) { return invoke<&func_map::has>(ctx); } static duk_ret_t get(duk_context *ctx) { return invoke<&func_map::get>(ctx); } static duk_ret_t entities(duk_context *ctx) { const duk_idx_t nargs = duk_get_top(ctx); auto &dreg = instance(ctx); duk_push_array(ctx); std::vector<ENTT_ID_TYPE> components; std::vector<ENTT_ID_TYPE> runtime; for(duk_idx_t arg = 0; arg < nargs; arg++) { auto type = duk_require_uint(ctx, arg); if(dreg.func.find(type) == dreg.func.cend()) { if(runtime.empty()) { components.push_back(entt::type_info<duktape_runtime>::id()); } runtime.push_back(type); } else { components.push_back(type); } } auto view = dreg.registry.runtime_view(components.cbegin(), components.cend()); duk_uarridx_t pos = 0; for(const auto entity: view) { if(runtime.empty()) { duk_push_uint(ctx, static_cast<std::underlying_type_t<entt::entity>>(entity)); duk_put_prop_index(ctx, -2, pos++); } else { const auto &others = dreg.registry.get<duktape_runtime>(entity).components; const auto match = std::all_of(runtime.cbegin(), runtime.cend(), [&others](const auto type) { return others.find(type) != others.cend(); }); if(match) { duk_push_uint(ctx, static_cast<std::underlying_type_t<entt::entity>>(entity)); duk_put_prop_index(ctx, -2, pos++); } } } return 1; } private: std::map<duk_uint_t, func_map> func; entt::registry &registry; }; const duk_function_list_entry js_duktape_registry_methods[] = { { "identifier", &duktape_registry::identifier, 0 }, { "create", &duktape_registry::create, 0 }, { "set", &duktape_registry::set, DUK_VARARGS }, { "unset", &duktape_registry::unset, 2 }, { "has", &duktape_registry::has, 2 }, { "get", &duktape_registry::get, 2 }, { "entities", &duktape_registry::entities, DUK_VARARGS }, { nullptr, nullptr, 0 } }; void export_types(duk_context *context) { auto export_type = [idx = duk_push_object(context)](auto *ctx, auto type, const auto *name) { duk_push_string(ctx, name); duk_push_uint(ctx, entt::type_info<typename decltype(type)::type>::id()); duk_def_prop(ctx, idx, DUK_DEFPROP_HAVE_VALUE | DUK_DEFPROP_CLEAR_WRITABLE); }; export_type(context, tag<position>{}, "position"); export_type(context, tag<renderable>{}, "renderable"); duk_put_global_string(context, "Types"); } void export_duktape_registry(duk_context *ctx, duktape_registry &dreg) { auto idx = duk_push_object(ctx); duk_push_string(ctx, DUK_HIDDEN_SYMBOL("dreg")); duk_push_pointer(ctx, &dreg); duk_put_prop(ctx, idx); duk_put_function_list(ctx, idx, js_duktape_registry_methods); duk_put_global_string(ctx, "Registry"); } TEST(Mod, Duktape) { entt::registry registry; duktape_registry dreg{registry}; duk_context *ctx = duk_create_heap_default(); if(!ctx) { FAIL(); } export_types(ctx); export_duktape_registry(ctx, dreg); const char *s0 = "" "Types[\"PLAYING_CHARACTER\"] = Registry.identifier();" "Types[\"VELOCITY\"] = Registry.identifier();" ""; if(duk_peval_string(ctx, s0)) { FAIL(); } const auto e0 = registry.create(); registry.assign<position>(e0, 0., 0.); registry.assign<renderable>(e0); const auto e1 = registry.create(); registry.assign<position>(e1, 0., 0.); const char *s1 = "" "Registry.entities(Types.position, Types.renderable).forEach(function(entity) {" "Registry.set(entity, Types.position, 100., 100.);" "});" "var entity = Registry.create();" "Registry.set(entity, Types.position, 100., 100.);" "Registry.set(entity, Types.renderable);" ""; if(duk_peval_string(ctx, s1)) { FAIL(); } ASSERT_EQ(registry.view<duktape_runtime>().size(), 0u); ASSERT_EQ(registry.view<position>().size(), 3u); ASSERT_EQ(registry.view<renderable>().size(), 2u); registry.view<position>().each([&registry](auto entity, const auto &position) { ASSERT_FALSE(registry.has<duktape_runtime>(entity)); if(registry.has<renderable>(entity)) { ASSERT_EQ(position.x, 100.); ASSERT_EQ(position.y, 100.); } else { ASSERT_EQ(position.x, 0.); ASSERT_EQ(position.y, 0.); } }); const char *s2 = "" "Registry.entities(Types.position).forEach(function(entity) {" "if(!Registry.has(entity, Types.renderable)) {" "Registry.set(entity, Types.VELOCITY, { \"dx\": -100., \"dy\": -100. });" "Registry.set(entity, Types.PLAYING_CHARACTER, {});" "}" "});" ""; if(duk_peval_string(ctx, s2)) { FAIL(); } ASSERT_EQ(registry.view<duktape_runtime>().size(), 1u); ASSERT_EQ(registry.view<position>().size(), 3u); ASSERT_EQ(registry.view<renderable>().size(), 2u); registry.view<duktape_runtime>().each([](const duktape_runtime &runtime) { ASSERT_EQ(runtime.components.size(), 2u); }); const char *s3 = "" "Registry.entities(Types.position, Types.renderable, Types.VELOCITY, Types.PLAYING_CHARACTER).forEach(function(entity) {" "var velocity = Registry.get(entity, Types.VELOCITY);" "Registry.set(entity, Types.position, velocity.dx, velocity.dy)" "});" ""; if(duk_peval_string(ctx, s3)) { FAIL(); } ASSERT_EQ(registry.view<duktape_runtime>().size(), 1u); ASSERT_EQ(registry.view<position>().size(), 3u); ASSERT_EQ(registry.view<renderable>().size(), 2u); registry.view<position, renderable, duktape_runtime>().each([](const position &position, auto &&...) { ASSERT_EQ(position.x, -100.); ASSERT_EQ(position.y, -100.); }); const char *s4 = "" "Registry.entities(Types.VELOCITY, Types.PLAYING_CHARACTER).forEach(function(entity) {" "Registry.unset(entity, Types.VELOCITY);" "Registry.unset(entity, Types.PLAYING_CHARACTER);" "});" "Registry.entities(Types.position).forEach(function(entity) {" "Registry.unset(entity, Types.position);" "});" ""; if(duk_peval_string(ctx, s4)) { FAIL(); } ASSERT_EQ(registry.view<duktape_runtime>().size(), 0u); ASSERT_EQ(registry.view<position>().size(), 0u); ASSERT_EQ(registry.view<renderable>().size(), 2u); duk_destroy_heap(ctx); } <commit_msg>test: minor changes<commit_after>#include <type_traits> #include <cassert> #include <map> #include <string> #include <duktape.h> #include <gtest/gtest.h> #include <entt/core/type_info.hpp> #include <entt/entity/registry.hpp> template<typename Type> struct tag { using type = Type; }; struct position { double x; double y; }; struct renderable {}; struct duktape_runtime { std::map<duk_uint_t, std::string> components; }; template<typename Comp> duk_ret_t set(duk_context *ctx, entt::registry &registry) { const entt::entity entity{duk_require_uint(ctx, 0)}; if constexpr(std::is_same_v<Comp, position>) { const auto x = duk_require_number(ctx, 2); const auto y = duk_require_number(ctx, 3); registry.assign_or_replace<position>(entity, x, y); } else if constexpr(std::is_same_v<Comp, duktape_runtime>) { const auto type = duk_require_uint(ctx, 1); duk_dup(ctx, 2); if(!registry.has<duktape_runtime>(entity)) { registry.assign<duktape_runtime>(entity).components[type] = duk_json_encode(ctx, -1); } else { registry.get<duktape_runtime>(entity).components[type] = duk_json_encode(ctx, -1); } duk_pop(ctx); } else { registry.assign_or_replace<Comp>(entity); } return 0; } template<typename Comp> duk_ret_t unset(duk_context *ctx, entt::registry &registry) { const entt::entity entity{duk_require_uint(ctx, 0)}; if constexpr(std::is_same_v<Comp, duktape_runtime>) { const auto type = duk_require_uint(ctx, 1); auto &components = registry.get<duktape_runtime>(entity).components; assert(components.find(type) != components.cend()); components.erase(type); if(components.empty()) { registry.remove<duktape_runtime>(entity); } } else { registry.remove<Comp>(entity); } return 0; } template<typename Comp> duk_ret_t has(duk_context *ctx, entt::registry &registry) { const entt::entity entity{duk_require_uint(ctx, 0)}; if constexpr(std::is_same_v<Comp, duktape_runtime>) { duk_push_boolean(ctx, registry.has<duktape_runtime>(entity)); if(registry.has<duktape_runtime>(entity)) { const auto type = duk_require_uint(ctx, 1); const auto &components = registry.get<duktape_runtime>(entity).components; duk_push_boolean(ctx, components.find(type) != components.cend()); } else { duk_push_false(ctx); } } else { duk_push_boolean(ctx, registry.has<Comp>(entity)); } return 1; } template<typename Comp> duk_ret_t get(duk_context *ctx, entt::registry &registry) { [[maybe_unused]] const entt::entity entity{duk_require_uint(ctx, 0)}; if constexpr(std::is_same_v<Comp, position>) { const auto &pos = registry.get<position>(entity); const auto idx = duk_push_object(ctx); duk_push_string(ctx, "x"); duk_push_number(ctx, pos.x); duk_def_prop(ctx, idx, DUK_DEFPROP_HAVE_VALUE); duk_push_string(ctx, "y"); duk_push_number(ctx, pos.y); duk_def_prop(ctx, idx, DUK_DEFPROP_HAVE_VALUE); } if constexpr(std::is_same_v<Comp, duktape_runtime>) { const auto type = duk_require_uint(ctx, 1); auto &runtime = registry.get<duktape_runtime>(entity); assert(runtime.components.find(type) != runtime.components.cend()); duk_push_string(ctx, runtime.components[type].c_str()); duk_json_decode(ctx, -1); } else { assert(registry.has<Comp>(entity)); duk_push_object(ctx); } return 1; } class duktape_registry { struct func_map { using func_type = duk_ret_t(*)(duk_context *, entt::registry &); func_type set; func_type unset; func_type has; func_type get; }; template<typename... Comp> void reg() { ((func[entt::type_info<Comp>::id()] = { &::set<Comp>, &::unset<Comp>, &::has<Comp>, &::get<Comp> }), ...); } static duktape_registry & instance(duk_context *ctx) { duk_push_this(ctx); duk_push_string(ctx, DUK_HIDDEN_SYMBOL("dreg")); duk_get_prop(ctx, -2); auto &dreg = *static_cast<duktape_registry *>(duk_require_pointer(ctx, -1)); duk_pop_2(ctx); return dreg; } template<func_map::func_type func_map::*Op> static duk_ret_t invoke(duk_context *ctx) { auto &dreg = instance(ctx); auto &func = dreg.func; auto &registry = dreg.registry; auto type = duk_require_uint(ctx, 1); const auto it = func.find(type); return (it == func.cend()) ? (func[entt::type_info<duktape_runtime>::id()].*Op)(ctx, registry) : (it->second.*Op)(ctx, registry); } public: duktape_registry(entt::registry &ref) : registry{ref} { reg<position, renderable, duktape_runtime>(); } static duk_ret_t identifier(duk_context *ctx) { static ENTT_ID_TYPE next{1000u}; duk_push_uint(ctx, next++); return 1; } static duk_ret_t create(duk_context *ctx) { auto &dreg = instance(ctx); const auto entity = dreg.registry.create(); duk_push_uint(ctx, static_cast<std::underlying_type_t<entt::entity>>(entity)); return 1; } static duk_ret_t set(duk_context *ctx) { return invoke<&func_map::set>(ctx); } static duk_ret_t unset(duk_context *ctx) { return invoke<&func_map::unset>(ctx); } static duk_ret_t has(duk_context *ctx) { return invoke<&func_map::has>(ctx); } static duk_ret_t get(duk_context *ctx) { return invoke<&func_map::get>(ctx); } static duk_ret_t entities(duk_context *ctx) { const duk_idx_t nargs = duk_get_top(ctx); auto &dreg = instance(ctx); duk_push_array(ctx); std::vector<ENTT_ID_TYPE> components; std::vector<ENTT_ID_TYPE> runtime; for(duk_idx_t arg = 0; arg < nargs; arg++) { auto type = duk_require_uint(ctx, arg); if(dreg.func.find(type) == dreg.func.cend()) { if(runtime.empty()) { components.push_back(entt::type_info<duktape_runtime>::id()); } runtime.push_back(type); } else { components.push_back(type); } } auto view = dreg.registry.runtime_view(components.cbegin(), components.cend()); duk_uarridx_t pos = 0; for(const auto entity: view) { if(runtime.empty()) { duk_push_uint(ctx, static_cast<std::underlying_type_t<entt::entity>>(entity)); duk_put_prop_index(ctx, -2, pos++); } else { const auto &others = dreg.registry.get<duktape_runtime>(entity).components; const auto match = std::all_of(runtime.cbegin(), runtime.cend(), [&others](const auto type) { return others.find(type) != others.cend(); }); if(match) { duk_push_uint(ctx, static_cast<std::underlying_type_t<entt::entity>>(entity)); duk_put_prop_index(ctx, -2, pos++); } } } return 1; } private: std::map<duk_uint_t, func_map> func; entt::registry &registry; }; const duk_function_list_entry js_duktape_registry_methods[] = { { "identifier", &duktape_registry::identifier, 0 }, { "create", &duktape_registry::create, 0 }, { "set", &duktape_registry::set, DUK_VARARGS }, { "unset", &duktape_registry::unset, 2 }, { "has", &duktape_registry::has, 2 }, { "get", &duktape_registry::get, 2 }, { "entities", &duktape_registry::entities, DUK_VARARGS }, { nullptr, nullptr, 0 } }; void export_types(duk_context *context) { auto export_type = [idx = duk_push_object(context)](auto *ctx, auto type, const auto *name) { duk_push_string(ctx, name); duk_push_uint(ctx, entt::type_info<typename decltype(type)::type>::id()); duk_def_prop(ctx, idx, DUK_DEFPROP_HAVE_VALUE | DUK_DEFPROP_CLEAR_WRITABLE); }; export_type(context, tag<position>{}, "position"); export_type(context, tag<renderable>{}, "renderable"); duk_put_global_string(context, "Types"); } void export_duktape_registry(duk_context *ctx, duktape_registry &dreg) { auto idx = duk_push_object(ctx); duk_push_string(ctx, DUK_HIDDEN_SYMBOL("dreg")); duk_push_pointer(ctx, &dreg); duk_put_prop(ctx, idx); duk_put_function_list(ctx, idx, js_duktape_registry_methods); duk_put_global_string(ctx, "Registry"); } TEST(Mod, Duktape) { entt::registry registry; duktape_registry dreg{registry}; duk_context *ctx = duk_create_heap_default(); if(!ctx) { FAIL(); } export_types(ctx); export_duktape_registry(ctx, dreg); const char *s0 = "" "Types[\"PLAYING_CHARACTER\"] = Registry.identifier();" "Types[\"VELOCITY\"] = Registry.identifier();" ""; if(duk_peval_string(ctx, s0)) { FAIL(); } const auto e0 = registry.create(); registry.assign<position>(e0, 0., 0.); registry.assign<renderable>(e0); const auto e1 = registry.create(); registry.assign<position>(e1, 0., 0.); const char *s1 = "" "Registry.entities(Types.position, Types.renderable).forEach(function(entity) {" "Registry.set(entity, Types.position, 100., 100.);" "});" "var entity = Registry.create();" "Registry.set(entity, Types.position, 100., 100.);" "Registry.set(entity, Types.renderable);" ""; if(duk_peval_string(ctx, s1)) { FAIL(); } ASSERT_EQ(registry.view<duktape_runtime>().size(), 0u); ASSERT_EQ(registry.view<position>().size(), 3u); ASSERT_EQ(registry.view<renderable>().size(), 2u); registry.view<position>().each([&registry](auto entity, const auto &position) { ASSERT_FALSE(registry.has<duktape_runtime>(entity)); if(registry.has<renderable>(entity)) { ASSERT_EQ(position.x, 100.); ASSERT_EQ(position.y, 100.); } else { ASSERT_EQ(position.x, 0.); ASSERT_EQ(position.y, 0.); } }); const char *s2 = "" "Registry.entities(Types.position).forEach(function(entity) {" "if(!Registry.has(entity, Types.renderable)) {" "Registry.set(entity, Types.VELOCITY, { \"dx\": -100., \"dy\": -100. });" "Registry.set(entity, Types.PLAYING_CHARACTER, {});" "}" "});" ""; if(duk_peval_string(ctx, s2)) { FAIL(); } ASSERT_EQ(registry.view<duktape_runtime>().size(), 1u); ASSERT_EQ(registry.view<position>().size(), 3u); ASSERT_EQ(registry.view<renderable>().size(), 2u); registry.view<duktape_runtime>().each([](const duktape_runtime &runtime) { ASSERT_EQ(runtime.components.size(), 2u); }); const char *s3 = "" "Registry.entities(Types.position, Types.renderable, Types.VELOCITY, Types.PLAYING_CHARACTER).forEach(function(entity) {" "var velocity = Registry.get(entity, Types.VELOCITY);" "Registry.set(entity, Types.position, velocity.dx, velocity.dy)" "});" ""; if(duk_peval_string(ctx, s3)) { FAIL(); } ASSERT_EQ(registry.view<duktape_runtime>().size(), 1u); ASSERT_EQ(registry.view<position>().size(), 3u); ASSERT_EQ(registry.view<renderable>().size(), 2u); registry.view<position, renderable, duktape_runtime>().each([](const position &position, auto &&...) { ASSERT_EQ(position.x, -100.); ASSERT_EQ(position.y, -100.); }); const char *s4 = "" "Registry.entities(Types.VELOCITY, Types.PLAYING_CHARACTER).forEach(function(entity) {" "Registry.unset(entity, Types.VELOCITY);" "Registry.unset(entity, Types.PLAYING_CHARACTER);" "});" "Registry.entities(Types.position).forEach(function(entity) {" "Registry.unset(entity, Types.position);" "});" ""; if(duk_peval_string(ctx, s4)) { FAIL(); } ASSERT_EQ(registry.view<duktape_runtime>().size(), 0u); ASSERT_EQ(registry.view<position>().size(), 0u); ASSERT_EQ(registry.view<renderable>().size(), 2u); duk_destroy_heap(ctx); } <|endoftext|>
<commit_before>/* * Copyright 1999-2004 The Apache Software Foundation. * * 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. */ /** * @author Matthew Hoyt ([email protected]) */ #if !defined(XALANDEQUE_HEADER_GUARD_1357924680) #define XALANDEQUE_HEADER_GUARD_1357924680 // Base include file. Must be first. #include <xalanc/Include/PlatformDefinitions.hpp> #include <xalanc/Include/XalanVector.hpp> #include <xalanc/Include/XalanMemoryManagement.hpp> XALAN_CPP_NAMESPACE_BEGIN template <class Value> struct XalanDequeIteratorTraits { typedef Value value_type; typedef Value& reference; typedef Value* pointer; typedef const Value& const_reference; }; template <class Value> struct XalanDequeConstIteratorTraits { typedef Value value_type; typedef const Value& reference; typedef const Value* pointer; typedef const Value& const_reference; }; template <class XalanDequeTraits, class XalanDeque> struct XalanDequeIterator { typedef size_t size_type; typedef typename XalanDequeTraits::value_type value_type; typedef typename XalanDequeTraits::reference reference; typedef typename XalanDequeTraits::pointer pointer; typedef typename XalanDequeTraits::const_reference const_reference; typedef ptrdiff_t difference_type; typedef XalanDequeIterator<XalanDequeIteratorTraits<value_type>, XalanDeque> Iterator; typedef XALAN_STD_QUALIFIER random_access_iterator_tag iterator_category; XalanDequeIterator(XalanDeque* deque, size_type pos) : m_deque(deque), m_pos(pos) { } XalanDequeIterator(const Iterator & iterator) : m_deque(iterator.m_deque), m_pos(iterator.m_pos) { } XalanDequeIterator& operator=(const Iterator & iterator) { m_deque = iterator.m_deque; m_pos = iterator.m_pos; return *this; } XalanDequeIterator& operator++() { ++m_pos; return *this; } XalanDequeIterator operator++(int) { XalanDequeIterator temp = *this; ++m_pos; return temp; } XalanDequeIterator& operator--() { --m_pos; return *this; } pointer operator->() { return &(*m_deque[m_pos]); } reference operator*() { return (*m_deque)[m_pos]; } const_reference operator*() const { return (*m_deque)[m_pos]; } XalanDequeIterator operator+(difference_type difference) const { return XalanDequeIterator(m_deque, m_pos + difference); } XalanDequeIterator operator-(difference_type difference) const { return XalanDequeIterator(m_deque, m_pos - difference); } difference_type operator-(const XalanDequeIterator &theRhs) const { return m_pos - theRhs.m_pos; } bool operator==(const XalanDequeIterator & theRhs) const { return (theRhs.m_deque == m_deque) && theRhs.m_pos == m_pos; } bool operator!=(const XalanDequeIterator & theRhs) const { return !(theRhs == *this); } XalanDeque* m_deque; size_type m_pos; }; /** * Xalan implementation of deque */ template <class Type, class ConstructionTraits = MemoryManagedConstructionTraits<Type> > class XalanDeque { public: typedef size_t size_type; typedef Type value_type; typedef Type& reference; typedef const Type& const_reference; typedef XalanVector<Type, ConstructionTraits> BlockType; typedef XalanVector<BlockType*> BlockIndexType; typedef XalanDequeIterator<XalanDequeIteratorTraits<value_type>, XalanDeque> iterator; typedef XalanDequeIterator<XalanDequeConstIteratorTraits<value_type>, XalanDeque> const_iterator; #if defined(XALAN_HAS_STD_ITERATORS) typedef XALAN_STD_QUALIFIER reverse_iterator<iterator> reverse_iterator_; typedef XALAN_STD_QUALIFIER reverse_iterator<const_iterator> const_reverse_iterator_; #elif defined(XALAN_RW_NO_CLASS_PARTIAL_SPEC) typedef XALAN_STD_QUALIFIER reverse_iterator< iterator, XALAN_STD_QUALIFIER random_access_iterator_tag, value_type> reverse_iterator_; typedef XALAN_STD_QUALIFIER reverse_iterator< const_iterator, XALAN_STD_QUALIFIER random_access_iterator_tag, const value_type> const_reverse_iterator_; #else typedef XALAN_STD_QUALIFIER reverse_iterator<iterator, value_type> reverse_iterator_; typedef XALAN_STD_QUALIFIER reverse_iterator<const_iterator, value_type, const_reference> const_reverse_iterator_; #endif typedef reverse_iterator_ reverse_iterator; typedef const_reverse_iterator_ const_reverse_iterator; XalanDeque( MemoryManagerType& memoryManager, size_type initialSize = 0, size_type blockSize = 10) : m_memoryManager(&memoryManager), m_blockSize(blockSize), m_blockIndex(memoryManager, initialSize / blockSize + (initialSize % blockSize == 0 ? 0 : 1)), m_freeBlockVector(memoryManager) { typename ConstructionTraits::Constructor::ConstructableType defaultValue(*m_memoryManager); XALAN_STD_QUALIFIER fill_n(XALAN_STD_QUALIFIER back_inserter(*this), initialSize, defaultValue.value); } XalanDeque(const XalanDeque& theRhs, MemoryManagerType& memoryManager) : m_memoryManager(&memoryManager), m_blockSize(theRhs.m_blockSize), m_blockIndex(*theRhs.m_memoryManager, theRhs.size() / theRhs.m_blockSize + (theRhs.size() % theRhs.m_blockSize == 0 ? 0 : 1)), m_freeBlockVector(memoryManager) { XALAN_STD_QUALIFIER copy(theRhs.begin(), theRhs.end(), XALAN_STD_QUALIFIER back_inserter(*this)); } static XalanDeque* create( MemoryManagerType& theManager, size_type initialSize = 0, size_type blockSize = 10) { typedef XalanDeque ThisType; XalanMemMgrAutoPtr<ThisType, false> theGuard( theManager , (ThisType*)theManager.allocate(sizeof(ThisType))); ThisType* theResult = theGuard.get(); new (theResult) ThisType(theManager, initialSize, blockSize); theGuard.release(); return theResult; } ~XalanDeque() { clear(); typename BlockIndexType::iterator iter = m_freeBlockVector.begin(); while (iter != m_freeBlockVector.end()) { (*iter)->~XalanVector<Type, ConstructionTraits>(); deallocate(*iter); ++iter; } } iterator begin() { return iterator(this, 0); } const_iterator begin() const { return const_iterator(const_cast<XalanDeque*>(this), 0); } iterator end() { return iterator(this, size()); } const_iterator end() const { return const_iterator(const_cast<XalanDeque*>(this), size()); } const_reverse_iterator rbegin() const { return const_reverse_iterator(end()); } const_reverse_iterator rend() const { return const_reverse_iterator(begin()); } bool empty() const { return m_blockIndex.empty(); } size_type size() const { if (m_blockIndex.empty()) { return 0; } else { return (m_blockIndex.size() - 1) * m_blockSize + m_blockIndex.back()->size(); } } value_type& back() { return m_blockIndex.back()->back(); } value_type& operator[](size_type index) { BlockType & block = *(m_blockIndex[index / m_blockSize]); return block[index % m_blockSize]; } const value_type& operator[](size_type index) const { BlockType & block = *(m_blockIndex[index / m_blockSize]); return block[index % m_blockSize]; } void clear() { typename BlockIndexType::iterator iter = m_blockIndex.begin(); m_freeBlockVector.reserve(m_freeBlockVector.size() + m_blockIndex.size()); while (iter != m_blockIndex.end()) { (*iter)->clear(); m_freeBlockVector.push_back(*iter); ++iter; } m_blockIndex.clear(); } void push_back(const value_type & value) { if (m_blockIndex.empty() || m_blockIndex.back()->size() >= m_blockSize) { m_blockIndex.push_back(getNewBlock()); } m_blockIndex.back()->push_back(value); } void pop_back() { BlockType & lastBlock = *(m_blockIndex.back()); lastBlock.pop_back(); if (lastBlock.empty()) { m_freeBlockVector.push_back(&lastBlock); m_blockIndex.pop_back(); } } void resize(size_type newSize) { typename ConstructionTraits::Constructor::ConstructableType defaultValue(*m_memoryManager); if (newSize > size()) { for (size_type i = 0; i < newSize - size(); ++i) { push_back(defaultValue.value); } } else { for (size_type i = 0; i < size() - newSize; ++i) { pop_back(); } } } void swap(XalanDeque& theRhs) { MemoryManagerType* tempMemoryManager = m_memoryManager; m_memoryManager = theRhs.m_memoryManager; theRhs.m_memoryManager = tempMemoryManager; theRhs.m_blockIndex.swap(m_blockIndex); theRhs.m_freeBlockVector.swap(m_freeBlockVector); } XalanDeque & operator=(const XalanDeque & theRhs) { clear(); XALAN_STD_QUALIFIER copy(theRhs.begin(), theRhs.end(), XALAN_STD_QUALIFIER back_inserter(*this)); return *this; } MemoryManagerType& getMemoryManager() { assert (m_memoryManager != 0); return *m_memoryManager; } protected: BlockType* getNewBlock() { BlockType * newBlock; if (m_freeBlockVector.empty()) { newBlock = allocate(1); new (&*newBlock) BlockType(*m_memoryManager, m_blockSize); } else { newBlock = m_freeBlockVector.back(); m_freeBlockVector.pop_back(); } assert (newBlock != 0); return newBlock; } BlockType* allocate(size_type size) { const size_type theBytesNeeded = size * sizeof(BlockType); BlockType* pointer = (BlockType*)m_memoryManager->allocate(theBytesNeeded); assert(pointer != 0); return pointer; } void deallocate(BlockType* pointer) { m_memoryManager->deallocate(pointer); } MemoryManagerType* m_memoryManager; const size_type m_blockSize; BlockIndexType m_blockIndex; BlockIndexType m_freeBlockVector; private: // Not implemented XalanDeque(); XalanDeque(const XalanDeque&); }; XALAN_CPP_NAMESPACE_END #endif // XALANDEQUE_HEADER_GUARD_1357924680 <commit_msg>Fix to enable build on BC++B6<commit_after>/* * Copyright 1999-2004 The Apache Software Foundation. * * 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. */ /** * @author Matthew Hoyt ([email protected]) */ #if !defined(XALANDEQUE_HEADER_GUARD_1357924680) #define XALANDEQUE_HEADER_GUARD_1357924680 // Base include file. Must be first. #include <xalanc/Include/PlatformDefinitions.hpp> #include <xalanc/Include/XalanVector.hpp> #include <xalanc/Include/XalanMemoryManagement.hpp> XALAN_CPP_NAMESPACE_BEGIN template <class Value> struct XalanDequeIteratorTraits { typedef Value value_type; typedef Value& reference; typedef Value* pointer; typedef const Value& const_reference; }; template <class Value> struct XalanDequeConstIteratorTraits { typedef Value value_type; typedef const Value& reference; typedef const Value* pointer; typedef const Value& const_reference; }; template <class XalanDequeTraits, class XalanDeque> struct XalanDequeIterator { typedef size_t size_type; typedef typename XalanDequeTraits::value_type value_type; typedef typename XalanDequeTraits::reference reference; typedef typename XalanDequeTraits::pointer pointer; typedef typename XalanDequeTraits::const_reference const_reference; typedef ptrdiff_t difference_type; typedef XalanDequeIterator<XalanDequeIteratorTraits<value_type>, XalanDeque> Iterator; typedef XALAN_STD_QUALIFIER random_access_iterator_tag iterator_category; XalanDequeIterator(XalanDeque* deque, size_type pos) : m_deque(deque), m_pos(pos) { } XalanDequeIterator(const Iterator & iterator) : m_deque(iterator.m_deque), m_pos(iterator.m_pos) { } XalanDequeIterator& operator=(const Iterator & iterator) { m_deque = iterator.m_deque; m_pos = iterator.m_pos; return *this; } XalanDequeIterator& operator++() { ++m_pos; return *this; } XalanDequeIterator operator++(int) { XalanDequeIterator temp = *this; ++m_pos; return temp; } XalanDequeIterator& operator--() { --m_pos; return *this; } pointer operator->() { return &(*m_deque[m_pos]); } reference operator*() { return (*m_deque)[m_pos]; } const_reference operator*() const { return (*m_deque)[m_pos]; } XalanDequeIterator operator+(difference_type difference) const { return XalanDequeIterator(m_deque, m_pos + difference); } XalanDequeIterator operator-(difference_type difference) const { return XalanDequeIterator(m_deque, m_pos - difference); } difference_type operator-(const XalanDequeIterator &theRhs) const { return m_pos - theRhs.m_pos; } bool operator==(const XalanDequeIterator & theRhs) const { return (theRhs.m_deque == m_deque) && theRhs.m_pos == m_pos; } bool operator!=(const XalanDequeIterator & theRhs) const { return !(theRhs == *this); } XalanDeque* m_deque; size_type m_pos; }; /** * Xalan implementation of deque */ template <class Type, class ConstructionTraits = MemoryManagedConstructionTraits<Type> > class XalanDeque { public: typedef size_t size_type; typedef Type value_type; typedef Type& reference; typedef const Type& const_reference; typedef XalanVector<Type, ConstructionTraits> BlockType; typedef XalanVector<BlockType*> BlockIndexType; typedef XalanDeque<Type, ConstructionTraits> ThisType; typedef XalanDequeIterator<XalanDequeIteratorTraits<value_type>, ThisType> iterator; typedef XalanDequeIterator<XalanDequeConstIteratorTraits<value_type>, ThisType> const_iterator; #if defined(XALAN_HAS_STD_ITERATORS) typedef XALAN_STD_QUALIFIER reverse_iterator<iterator> reverse_iterator_; typedef XALAN_STD_QUALIFIER reverse_iterator<const_iterator> const_reverse_iterator_; #elif defined(XALAN_RW_NO_CLASS_PARTIAL_SPEC) typedef XALAN_STD_QUALIFIER reverse_iterator< iterator, XALAN_STD_QUALIFIER random_access_iterator_tag, value_type> reverse_iterator_; typedef XALAN_STD_QUALIFIER reverse_iterator< const_iterator, XALAN_STD_QUALIFIER random_access_iterator_tag, const value_type> const_reverse_iterator_; #else typedef XALAN_STD_QUALIFIER reverse_iterator<iterator, value_type> reverse_iterator_; typedef XALAN_STD_QUALIFIER reverse_iterator<const_iterator, value_type, const_reference> const_reverse_iterator_; #endif typedef reverse_iterator_ reverse_iterator; typedef const_reverse_iterator_ const_reverse_iterator; XalanDeque( MemoryManagerType& memoryManager, size_type initialSize = 0, size_type blockSize = 10) : m_memoryManager(&memoryManager), m_blockSize(blockSize), m_blockIndex(memoryManager, initialSize / blockSize + (initialSize % blockSize == 0 ? 0 : 1)), m_freeBlockVector(memoryManager) { typename ConstructionTraits::Constructor::ConstructableType defaultValue(*m_memoryManager); XALAN_STD_QUALIFIER fill_n(XALAN_STD_QUALIFIER back_inserter(*this), initialSize, defaultValue.value); } XalanDeque(const XalanDeque& theRhs, MemoryManagerType& memoryManager) : m_memoryManager(&memoryManager), m_blockSize(theRhs.m_blockSize), m_blockIndex(*theRhs.m_memoryManager, theRhs.size() / theRhs.m_blockSize + (theRhs.size() % theRhs.m_blockSize == 0 ? 0 : 1)), m_freeBlockVector(memoryManager) { XALAN_STD_QUALIFIER copy(theRhs.begin(), theRhs.end(), XALAN_STD_QUALIFIER back_inserter(*this)); } static XalanDeque* create( MemoryManagerType& theManager, size_type initialSize = 0, size_type blockSize = 10) { typedef XalanDeque ThisType; XalanMemMgrAutoPtr<ThisType, false> theGuard( theManager , (ThisType*)theManager.allocate(sizeof(ThisType))); ThisType* theResult = theGuard.get(); new (theResult) ThisType(theManager, initialSize, blockSize); theGuard.release(); return theResult; } ~XalanDeque() { clear(); typename BlockIndexType::iterator iter = m_freeBlockVector.begin(); while (iter != m_freeBlockVector.end()) { (*iter)->~XalanVector<Type, ConstructionTraits>(); deallocate(*iter); ++iter; } } iterator begin() { return iterator(this, 0); } const_iterator begin() const { return const_iterator(const_cast<XalanDeque*>(this), 0); } iterator end() { return iterator(this, size()); } const_iterator end() const { return const_iterator(const_cast<XalanDeque*>(this), size()); } const_reverse_iterator rbegin() const { return const_reverse_iterator(end()); } const_reverse_iterator rend() const { return const_reverse_iterator(begin()); } bool empty() const { return m_blockIndex.empty(); } size_type size() const { if (m_blockIndex.empty()) { return 0; } else { return (m_blockIndex.size() - 1) * m_blockSize + m_blockIndex.back()->size(); } } value_type& back() { return m_blockIndex.back()->back(); } value_type& operator[](size_type index) { BlockType & block = *(m_blockIndex[index / m_blockSize]); return block[index % m_blockSize]; } const value_type& operator[](size_type index) const { BlockType & block = *(m_blockIndex[index / m_blockSize]); return block[index % m_blockSize]; } void clear() { typename BlockIndexType::iterator iter = m_blockIndex.begin(); m_freeBlockVector.reserve(m_freeBlockVector.size() + m_blockIndex.size()); while (iter != m_blockIndex.end()) { (*iter)->clear(); m_freeBlockVector.push_back(*iter); ++iter; } m_blockIndex.clear(); } void push_back(const value_type & value) { if (m_blockIndex.empty() || m_blockIndex.back()->size() >= m_blockSize) { m_blockIndex.push_back(getNewBlock()); } m_blockIndex.back()->push_back(value); } void pop_back() { BlockType & lastBlock = *(m_blockIndex.back()); lastBlock.pop_back(); if (lastBlock.empty()) { m_freeBlockVector.push_back(&lastBlock); m_blockIndex.pop_back(); } } void resize(size_type newSize) { typename ConstructionTraits::Constructor::ConstructableType defaultValue(*m_memoryManager); if (newSize > size()) { for (size_type i = 0; i < newSize - size(); ++i) { push_back(defaultValue.value); } } else { for (size_type i = 0; i < size() - newSize; ++i) { pop_back(); } } } void swap(XalanDeque& theRhs) { MemoryManagerType* tempMemoryManager = m_memoryManager; m_memoryManager = theRhs.m_memoryManager; theRhs.m_memoryManager = tempMemoryManager; theRhs.m_blockIndex.swap(m_blockIndex); theRhs.m_freeBlockVector.swap(m_freeBlockVector); } XalanDeque & operator=(const XalanDeque & theRhs) { clear(); XALAN_STD_QUALIFIER copy(theRhs.begin(), theRhs.end(), XALAN_STD_QUALIFIER back_inserter(*this)); return *this; } MemoryManagerType& getMemoryManager() { assert (m_memoryManager != 0); return *m_memoryManager; } protected: BlockType* getNewBlock() { BlockType * newBlock; if (m_freeBlockVector.empty()) { newBlock = allocate(1); new (&*newBlock) BlockType(*m_memoryManager, m_blockSize); } else { newBlock = m_freeBlockVector.back(); m_freeBlockVector.pop_back(); } assert (newBlock != 0); return newBlock; } BlockType* allocate(size_type size) { const size_type theBytesNeeded = size * sizeof(BlockType); BlockType* pointer = (BlockType*)m_memoryManager->allocate(theBytesNeeded); assert(pointer != 0); return pointer; } void deallocate(BlockType* pointer) { m_memoryManager->deallocate(pointer); } MemoryManagerType* m_memoryManager; const size_type m_blockSize; BlockIndexType m_blockIndex; BlockIndexType m_freeBlockVector; private: // Not implemented XalanDeque(); XalanDeque(const XalanDeque&); }; XALAN_CPP_NAMESPACE_END #endif // XALANDEQUE_HEADER_GUARD_1357924680 <|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://www.qt.io/licensing. 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, 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 "kitmodel.h" #include "kit.h" #include "kitmanagerconfigwidget.h" #include "kitmanager.h" #include <coreplugin/coreconstants.h> #include <utils/algorithm.h> #include <utils/qtcassert.h> #include <QApplication> #include <QLayout> using namespace Utils; namespace ProjectExplorer { namespace Internal { class KitNode : public TreeItem { public: KitNode(Kit *k) { widget = KitManager::createConfigWidget(k); if (widget) { if (k && k->isAutoDetected()) widget->makeStickySubWidgetsReadOnly(); widget->setVisible(false); } } ~KitNode() { delete widget; } QVariant data(int, int role) const { static QIcon warningIcon(QString::fromLatin1(Core::Constants::ICON_WARNING)); static QIcon errorIcon(QString::fromLatin1(Core::Constants::ICON_ERROR)); if (widget) { if (role == Qt::FontRole) { QFont f = QApplication::font(); if (widget->isDirty()) f.setBold(!f.bold()); if (widget->isDefaultKit()) f.setItalic(f.style() != QFont::StyleItalic); return f; } if (role == Qt::DisplayRole) { QString baseName = widget->displayName(); if (widget->isDefaultKit()) //: Mark up a kit as the default one. baseName = KitModel::tr("%1 (default)").arg(baseName); return baseName; } if (role == Qt::DecorationRole) { if (!widget->isValid()) return errorIcon; if (widget->hasWarning()) return warningIcon; return QIcon(); } if (role == Qt::ToolTipRole) { return widget->validityMessage(); } } return QVariant(); } KitManagerConfigWidget *widget; }; // -------------------------------------------------------------------------- // KitModel // -------------------------------------------------------------------------- KitModel::KitModel(QBoxLayout *parentLayout, QObject *parent) : TreeModel(parent), m_parentLayout(parentLayout), m_defaultNode(0), m_keepUnique(true) { auto root = new TreeItem(QStringList(tr("Name"))); m_autoRoot = new TreeItem(QStringList(tr("Auto-detected"))); m_manualRoot = new TreeItem(QStringList(tr("Manual"))); root->appendChild(m_autoRoot); root->appendChild(m_manualRoot); setRootItem(root); foreach (Kit *k, KitManager::sortedKits()) addKit(k); changeDefaultKit(); connect(KitManager::instance(), &KitManager::kitAdded, this, &KitModel::addKit); connect(KitManager::instance(), &KitManager::kitUpdated, this, &KitModel::updateKit); connect(KitManager::instance(), &KitManager::unmanagedKitUpdated, this, &KitModel::updateKit); connect(KitManager::instance(), &KitManager::kitRemoved, this, &KitModel::removeKit); connect(KitManager::instance(), &KitManager::defaultkitChanged, this, &KitModel::changeDefaultKit); } Kit *KitModel::kit(const QModelIndex &index) { KitNode *n = kitNode(index); return n ? n->widget->workingCopy() : 0; } KitNode *KitModel::kitNode(const QModelIndex &index) { TreeItem *n = itemFromIndex(index); return n && n->level() == 2 ? static_cast<KitNode *>(n) : 0; } QModelIndex KitModel::indexOf(Kit *k) const { KitNode *n = findWorkingCopy(k); return indexFromItem(n); } void KitModel::setDefaultKit(const QModelIndex &index) { if (KitNode *n = kitNode(index)) setDefaultNode(n); } bool KitModel::isDefaultKit(Kit *k) const { return m_defaultNode && m_defaultNode->widget->workingCopy() == k; } KitManagerConfigWidget *KitModel::widget(const QModelIndex &index) { KitNode *n = kitNode(index); return n ? n->widget : 0; } void KitModel::validateKitNames() { QHash<QString, int> nameHash; foreach (KitNode *n, treeLevelItems<KitNode *>(2)) { const QString displayName = n->widget->displayName(); if (nameHash.contains(displayName)) ++nameHash[displayName]; else nameHash.insert(displayName, 1); } foreach (KitNode *n, treeLevelItems<KitNode *>(2)) { const QString displayName = n->widget->displayName(); n->widget->setHasUniqueName(nameHash.value(displayName) == 1); } } void KitModel::apply() { // Remove unused kits: foreach (KitNode *n, m_toRemoveList) n->widget->removeKit(); // Update kits: foreach (KitNode *n, treeLevelItems<KitNode *>(2)) { if (n->widget->isDirty()) { n->widget->apply(); n->update(); } } layoutChanged(); // Force update. } void KitModel::markForRemoval(Kit *k) { KitNode *node = findWorkingCopy(k); if (!node) return; if (node == m_defaultNode) { TreeItem *newDefault = m_autoRoot->firstChild(); if (!newDefault) newDefault = m_manualRoot->firstChild(); setDefaultNode(static_cast<KitNode *>(newDefault)); } removeItem(node); if (node->widget->configures(0)) delete node; else m_toRemoveList.append(node); } Kit *KitModel::markForAddition(Kit *baseKit) { KitNode *node = createNode(0); m_manualRoot->appendChild(node); Kit *k = node->widget->workingCopy(); KitGuard g(k); if (baseKit) { k->copyFrom(baseKit); k->setAutoDetected(false); // Make sure we have a manual kit! k->setSdkProvided(false); k->setUnexpandedDisplayName(tr("Clone of %1").arg(k->unexpandedDisplayName())); } else { k->setup(); } if (!m_defaultNode) setDefaultNode(node); return k; } KitNode *KitModel::findWorkingCopy(Kit *k) const { foreach (KitNode *n, treeLevelItems<KitNode *>(2)) { if (n->widget->workingCopy() == k) return n; } return 0; } KitNode *KitModel::createNode(Kit *k) { KitNode *node = new KitNode(k); m_parentLayout->addWidget(node->widget); connect(node->widget, &KitManagerConfigWidget::dirty, [node] { node->update(); }); return node; } void KitModel::setDefaultNode(KitNode *node) { if (m_defaultNode) { m_defaultNode->widget->setIsDefaultKit(false); m_defaultNode->update(); } m_defaultNode = node; if (m_defaultNode) { m_defaultNode->widget->setIsDefaultKit(true); m_defaultNode->update(); } } void KitModel::addKit(Kit *k) { foreach (TreeItem *n, m_manualRoot->children()) { // Was added by us if (static_cast<KitNode *>(n)->widget->configures(k)) return; } TreeItem *parent = k->isAutoDetected() ? m_autoRoot : m_manualRoot; parent->appendChild(createNode(k)); validateKitNames(); emit kitStateChanged(); } void KitModel::updateKit(Kit *) { validateKitNames(); emit kitStateChanged(); } void KitModel::removeKit(Kit *k) { QList<KitNode *> nodes = m_toRemoveList; foreach (KitNode *n, nodes) { if (n->widget->configures(k)) { m_toRemoveList.removeOne(n); if (m_defaultNode == n) m_defaultNode = 0; delete n; return; } } KitNode *node = 0; foreach (KitNode *n, treeLevelItems<KitNode *>(2)) { if (n->widget->configures(k)) { node = n; break; } } if (m_defaultNode == node) m_defaultNode = 0; removeItem(node); delete node; validateKitNames(); emit kitStateChanged(); } void KitModel::changeDefaultKit() { Kit *defaultKit = KitManager::defaultKit(); foreach (KitNode *n, treeLevelItems<KitNode *>(2)) { if (n->widget->configures(defaultKit)) { setDefaultNode(n); return; } } } } // namespace Internal } // namespace ProjectExplorer <commit_msg>KitModel: Fix crash on removing kits introduced in 7fd21d22a<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://www.qt.io/licensing. 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, 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 "kitmodel.h" #include "kit.h" #include "kitmanagerconfigwidget.h" #include "kitmanager.h" #include <coreplugin/coreconstants.h> #include <utils/algorithm.h> #include <utils/qtcassert.h> #include <QApplication> #include <QLayout> using namespace Utils; namespace ProjectExplorer { namespace Internal { class KitNode : public TreeItem { public: KitNode(Kit *k) { widget = KitManager::createConfigWidget(k); if (widget) { if (k && k->isAutoDetected()) widget->makeStickySubWidgetsReadOnly(); widget->setVisible(false); } } ~KitNode() { delete widget; } QVariant data(int, int role) const { static QIcon warningIcon(QString::fromLatin1(Core::Constants::ICON_WARNING)); static QIcon errorIcon(QString::fromLatin1(Core::Constants::ICON_ERROR)); if (widget) { if (role == Qt::FontRole) { QFont f = QApplication::font(); if (widget->isDirty()) f.setBold(!f.bold()); if (widget->isDefaultKit()) f.setItalic(f.style() != QFont::StyleItalic); return f; } if (role == Qt::DisplayRole) { QString baseName = widget->displayName(); if (widget->isDefaultKit()) //: Mark up a kit as the default one. baseName = KitModel::tr("%1 (default)").arg(baseName); return baseName; } if (role == Qt::DecorationRole) { if (!widget->isValid()) return errorIcon; if (widget->hasWarning()) return warningIcon; return QIcon(); } if (role == Qt::ToolTipRole) { return widget->validityMessage(); } } return QVariant(); } KitManagerConfigWidget *widget; }; // -------------------------------------------------------------------------- // KitModel // -------------------------------------------------------------------------- KitModel::KitModel(QBoxLayout *parentLayout, QObject *parent) : TreeModel(parent), m_parentLayout(parentLayout), m_defaultNode(0), m_keepUnique(true) { auto root = new TreeItem(QStringList(tr("Name"))); m_autoRoot = new TreeItem(QStringList(tr("Auto-detected"))); m_manualRoot = new TreeItem(QStringList(tr("Manual"))); root->appendChild(m_autoRoot); root->appendChild(m_manualRoot); setRootItem(root); foreach (Kit *k, KitManager::sortedKits()) addKit(k); changeDefaultKit(); connect(KitManager::instance(), &KitManager::kitAdded, this, &KitModel::addKit); connect(KitManager::instance(), &KitManager::kitUpdated, this, &KitModel::updateKit); connect(KitManager::instance(), &KitManager::unmanagedKitUpdated, this, &KitModel::updateKit); connect(KitManager::instance(), &KitManager::kitRemoved, this, &KitModel::removeKit); connect(KitManager::instance(), &KitManager::defaultkitChanged, this, &KitModel::changeDefaultKit); } Kit *KitModel::kit(const QModelIndex &index) { KitNode *n = kitNode(index); return n ? n->widget->workingCopy() : 0; } KitNode *KitModel::kitNode(const QModelIndex &index) { TreeItem *n = itemFromIndex(index); return n && n->level() == 2 ? static_cast<KitNode *>(n) : 0; } QModelIndex KitModel::indexOf(Kit *k) const { KitNode *n = findWorkingCopy(k); return indexFromItem(n); } void KitModel::setDefaultKit(const QModelIndex &index) { if (KitNode *n = kitNode(index)) setDefaultNode(n); } bool KitModel::isDefaultKit(Kit *k) const { return m_defaultNode && m_defaultNode->widget->workingCopy() == k; } KitManagerConfigWidget *KitModel::widget(const QModelIndex &index) { KitNode *n = kitNode(index); return n ? n->widget : 0; } void KitModel::validateKitNames() { QHash<QString, int> nameHash; foreach (KitNode *n, treeLevelItems<KitNode *>(2)) { const QString displayName = n->widget->displayName(); if (nameHash.contains(displayName)) ++nameHash[displayName]; else nameHash.insert(displayName, 1); } foreach (KitNode *n, treeLevelItems<KitNode *>(2)) { const QString displayName = n->widget->displayName(); n->widget->setHasUniqueName(nameHash.value(displayName) == 1); } } void KitModel::apply() { // Remove unused kits: foreach (KitNode *n, m_toRemoveList) n->widget->removeKit(); // Update kits: foreach (KitNode *n, treeLevelItems<KitNode *>(2)) { if (n->widget->isDirty()) { n->widget->apply(); n->update(); } } layoutChanged(); // Force update. } void KitModel::markForRemoval(Kit *k) { KitNode *node = findWorkingCopy(k); if (!node) return; if (node == m_defaultNode) { TreeItem *newDefault = m_autoRoot->firstChild(); if (!newDefault) newDefault = m_manualRoot->firstChild(); setDefaultNode(static_cast<KitNode *>(newDefault)); } removeItem(node); if (node->widget->configures(0)) delete node; else m_toRemoveList.append(node); } Kit *KitModel::markForAddition(Kit *baseKit) { KitNode *node = createNode(0); m_manualRoot->appendChild(node); Kit *k = node->widget->workingCopy(); KitGuard g(k); if (baseKit) { k->copyFrom(baseKit); k->setAutoDetected(false); // Make sure we have a manual kit! k->setSdkProvided(false); k->setUnexpandedDisplayName(tr("Clone of %1").arg(k->unexpandedDisplayName())); } else { k->setup(); } if (!m_defaultNode) setDefaultNode(node); return k; } KitNode *KitModel::findWorkingCopy(Kit *k) const { foreach (KitNode *n, treeLevelItems<KitNode *>(2)) { if (n->widget->workingCopy() == k) return n; } return 0; } KitNode *KitModel::createNode(Kit *k) { KitNode *node = new KitNode(k); m_parentLayout->addWidget(node->widget); connect(node->widget, &KitManagerConfigWidget::dirty, [this, node] { if (m_autoRoot->children().contains(node) || m_manualRoot->children().contains(node)) node->update(); }); return node; } void KitModel::setDefaultNode(KitNode *node) { if (m_defaultNode) { m_defaultNode->widget->setIsDefaultKit(false); m_defaultNode->update(); } m_defaultNode = node; if (m_defaultNode) { m_defaultNode->widget->setIsDefaultKit(true); m_defaultNode->update(); } } void KitModel::addKit(Kit *k) { foreach (TreeItem *n, m_manualRoot->children()) { // Was added by us if (static_cast<KitNode *>(n)->widget->configures(k)) return; } TreeItem *parent = k->isAutoDetected() ? m_autoRoot : m_manualRoot; parent->appendChild(createNode(k)); validateKitNames(); emit kitStateChanged(); } void KitModel::updateKit(Kit *) { validateKitNames(); emit kitStateChanged(); } void KitModel::removeKit(Kit *k) { QList<KitNode *> nodes = m_toRemoveList; foreach (KitNode *n, nodes) { if (n->widget->configures(k)) { m_toRemoveList.removeOne(n); if (m_defaultNode == n) m_defaultNode = 0; delete n; return; } } KitNode *node = 0; foreach (KitNode *n, treeLevelItems<KitNode *>(2)) { if (n->widget->configures(k)) { node = n; break; } } if (m_defaultNode == node) m_defaultNode = 0; removeItem(node); delete node; validateKitNames(); emit kitStateChanged(); } void KitModel::changeDefaultKit() { Kit *defaultKit = KitManager::defaultKit(); foreach (KitNode *n, treeLevelItems<KitNode *>(2)) { if (n->widget->configures(defaultKit)) { setDefaultNode(n); return; } } } } // namespace Internal } // namespace ProjectExplorer <|endoftext|>
<commit_before>// // This file is part of the Marble Desktop Globe. // // This program is free software licensed under the GNU LGPL. You can // find a copy of this license in LICENSE.txt in the top directory of // the source code. // // Copyright 2010 Dennis Nienhüser <[email protected]> // #include "signals.h" #include "MonavPlugin.h" #include "MonavRunner.h" #include "MarbleDirs.h" #include "MarbleDebug.h" #include "GeoDataLatLonBox.h" #include "GeoDataParser.h" #include "GeoDataDocument.h" #include <QtCore/QProcess> #include <QtCore/QDir> #include <QtCore/QDirIterator> #include <QtCore/QTimer> #include <QtNetwork/QLocalSocket> #include <unistd.h> namespace Marble { class MonavMap { public: QDir m_directory; GeoDataLatLonBox m_boundingBox; QVector<GeoDataLinearRing> m_tiles; void setDirectory( const QDir &dir ); bool containsPoint( const GeoDataCoordinates &point ) const; private: void parseBoundingBox( const QFileInfo &file ); }; class MonavPluginPrivate { public: QDir m_mapDir; QVector<MonavMap> m_maps; bool m_ownsServer; MonavPluginPrivate(); ~MonavPluginPrivate(); bool startDaemon(); void stopDaemon(); bool isDaemonRunning() const; void loadMaps(); static bool bordersFirst( const MonavMap &first, const MonavMap &second ); private: void loadMap( const QString &path ); }; void MonavMap::setDirectory( const QDir &dir ) { m_directory = dir; QFileInfo boundingBox( dir, dir.dirName() + ".kml" ); if ( boundingBox.exists() ) { parseBoundingBox( boundingBox ); } else { mDebug() << "No monav bounding box given for " << boundingBox.absoluteFilePath(); } } void MonavMap::parseBoundingBox( const QFileInfo &file ) { GeoDataLineString points; QFile input( file.absoluteFilePath() ); if ( input.open( QFile::ReadOnly ) ) { GeoDataParser parser( GeoData_KML ); if ( !parser.read( &input ) ) { mDebug() << "Could not parse file: " << parser.errorString(); return; } GeoDocument *doc = parser.releaseDocument(); GeoDataDocument *document = dynamic_cast<GeoDataDocument*>( doc ); QVector<GeoDataPlacemark*> placemarks = document->placemarkList(); if ( placemarks.size() == 1 ) { GeoDataPlacemark* placemark = placemarks.first(); GeoDataMultiGeometry* geometry = dynamic_cast<GeoDataMultiGeometry*>( placemark->geometry() ); for ( int i=0; geometry && i<geometry->size(); ++i ) { GeoDataLinearRing* poly = dynamic_cast<GeoDataLinearRing*>( geometry->child( i ) ); if ( poly ) { for ( int j=0; j<poly->size(); ++j ) { points << poly->at( j ); } m_tiles.push_back( *poly ); } } } else { mDebug() << "File " << file.absoluteFilePath() << " does not contain one placemark, but " << placemarks.size(); } } m_boundingBox = points.latLonAltBox(); } bool MonavMap::containsPoint( const GeoDataCoordinates &point ) const { // If we do not have a bounding box at all, we err on the safe side if ( m_tiles.isEmpty() ) { return true; } // Quick check for performance reasons if ( !m_boundingBox.contains( point ) ) { return false; } foreach( const GeoDataLinearRing &box, m_tiles ) { if ( box.contains( point ) ) { return true; } } return false; } MonavPluginPrivate::MonavPluginPrivate() : m_ownsServer( false ) { // nothing to do } MonavPluginPrivate::~MonavPluginPrivate() { stopDaemon(); } bool MonavPluginPrivate::isDaemonRunning() const { QLocalSocket socket; socket.connectToServer( "MoNavD" ); return socket.waitForConnected(); } bool MonavPluginPrivate::startDaemon() { if ( !isDaemonRunning() ) { QProcess process; if ( process.startDetached( "MoNavD" ) ) { m_ownsServer = true; // Give MoNavD up to one second to set up its server // Without that, the first route request would fail for ( int i = 0; i < 10; ++i ) { if ( isDaemonRunning() ) { break; } usleep( 100 * 1000 ); } return true; } return false; } return true; } void MonavPluginPrivate::stopDaemon() { if ( m_ownsServer ) { m_ownsServer = false; QProcess process; process.startDetached( "MoNavD", QStringList() << "-t" ); } } void MonavPluginPrivate::loadMaps() { QString base = MarbleDirs::localPath() + "/maps/earth/monav/"; loadMap( base ); QDir::Filters filters = QDir::AllDirs | QDir::Readable | QDir::NoDotAndDotDot; QDirIterator::IteratorFlags flags = QDirIterator::Subdirectories | QDirIterator::FollowSymlinks; QDirIterator iter( base, filters, flags ); while ( iter.hasNext() ) { iter.next(); loadMap( iter.filePath() ); } // Prefer maps where bounding boxes are known qSort( m_maps.begin(), m_maps.end(), MonavPluginPrivate::bordersFirst ); } void MonavPluginPrivate::loadMap( const QString &path ) { QDir mapDir( path ); QFileInfo pluginsFile( mapDir, "plugins.ini" ); if ( pluginsFile.exists() ) { MonavMap map; map.setDirectory( mapDir ); m_maps.append( map ); } } bool MonavPluginPrivate::bordersFirst( const MonavMap &first, const MonavMap &second ) { if ( !first.m_tiles.isEmpty() && second.m_tiles.isEmpty() ) { return true; } if ( first.m_tiles.isEmpty() && !second.m_tiles.isEmpty() ) { return false; } return first.m_directory.absolutePath() < second.m_directory.absolutePath(); } MonavPlugin::MonavPlugin( QObject *parent ) : RunnerPlugin( parent ), d( new MonavPluginPrivate ) { setSupportedCelestialBodies( QStringList() << "earth" ); setCanWorkOffline( true ); setName( tr( "Monav" ) ); setNameId( "monav" ); setDescription( tr( "Retrieves routes from monav" ) ); setGuiString( tr( "Monav Routing" ) ); // Check installation d->loadMaps(); bool const haveMap = !d->m_maps.isEmpty(); setCapabilities( haveMap ? Routing /*| ReverseGeocoding */ : None ); } MonavPlugin::~MonavPlugin() { delete d; } MarbleAbstractRunner* MonavPlugin::newRunner() const { if ( !d->startDaemon() ) { mDebug() << "Failed to connect to MoNavD daemon"; } return new MonavRunner( this ); } QString MonavPlugin::mapDirectoryForRequest( RouteRequest* request ) const { for ( int j=0; j<d->m_maps.size(); ++j ) { bool containsAllPoints = true; for ( int i = 0; i < request->size(); ++i ) { GeoDataCoordinates via = request->at( i ); if ( !d->m_maps[j].containsPoint( via ) ) { containsAllPoints = false; break; } } if ( containsAllPoints ) { if ( j ) { // Subsequent route requests will likely be in the same country qSwap( d->m_maps[0], d->m_maps[j] ); } // mDebug() << "Using " << d->m_maps.first().m_directory.dirName() << " as monav map"; return d->m_maps.first().m_directory.absolutePath(); } } return QString(); } } Q_EXPORT_PLUGIN2( MonavPlugin, Marble::MonavPlugin ) #include "MonavPlugin.moc" <commit_msg>Change sort order of maps from hasBBox/name to hasBBox/area. This has the advantage that smaller maps are automatically preferred, which is useful for overlapping maps (e.g. baden-wurttemberg vs germany vs europe) to prefer the smaller map and only fall back to the larger (slower) one if really needed.<commit_after>// // This file is part of the Marble Desktop Globe. // // This program is free software licensed under the GNU LGPL. You can // find a copy of this license in LICENSE.txt in the top directory of // the source code. // // Copyright 2010 Dennis Nienhüser <[email protected]> // #include "signals.h" #include "MonavPlugin.h" #include "MonavRunner.h" #include "MarbleDirs.h" #include "MarbleDebug.h" #include "GeoDataLatLonBox.h" #include "GeoDataParser.h" #include "GeoDataDocument.h" #include <QtCore/QProcess> #include <QtCore/QDir> #include <QtCore/QDirIterator> #include <QtCore/QTimer> #include <QtNetwork/QLocalSocket> #include <unistd.h> namespace Marble { class MonavMap { public: QDir m_directory; GeoDataLatLonBox m_boundingBox; QVector<GeoDataLinearRing> m_tiles; void setDirectory( const QDir &dir ); bool containsPoint( const GeoDataCoordinates &point ) const; private: void parseBoundingBox( const QFileInfo &file ); }; class MonavPluginPrivate { public: QDir m_mapDir; QVector<MonavMap> m_maps; bool m_ownsServer; MonavPluginPrivate(); ~MonavPluginPrivate(); bool startDaemon(); void stopDaemon(); bool isDaemonRunning() const; void loadMaps(); static bool areaLessThan( const MonavMap &first, const MonavMap &second ); private: void loadMap( const QString &path ); }; void MonavMap::setDirectory( const QDir &dir ) { m_directory = dir; QFileInfo boundingBox( dir, dir.dirName() + ".kml" ); if ( boundingBox.exists() ) { parseBoundingBox( boundingBox ); } else { mDebug() << "No monav bounding box given for " << boundingBox.absoluteFilePath(); } } void MonavMap::parseBoundingBox( const QFileInfo &file ) { GeoDataLineString points; QFile input( file.absoluteFilePath() ); if ( input.open( QFile::ReadOnly ) ) { GeoDataParser parser( GeoData_KML ); if ( !parser.read( &input ) ) { mDebug() << "Could not parse file: " << parser.errorString(); return; } GeoDocument *doc = parser.releaseDocument(); GeoDataDocument *document = dynamic_cast<GeoDataDocument*>( doc ); QVector<GeoDataPlacemark*> placemarks = document->placemarkList(); if ( placemarks.size() == 1 ) { GeoDataPlacemark* placemark = placemarks.first(); GeoDataMultiGeometry* geometry = dynamic_cast<GeoDataMultiGeometry*>( placemark->geometry() ); for ( int i=0; geometry && i<geometry->size(); ++i ) { GeoDataLinearRing* poly = dynamic_cast<GeoDataLinearRing*>( geometry->child( i ) ); if ( poly ) { for ( int j=0; j<poly->size(); ++j ) { points << poly->at( j ); } m_tiles.push_back( *poly ); } } } else { mDebug() << "File " << file.absoluteFilePath() << " does not contain one placemark, but " << placemarks.size(); } } m_boundingBox = points.latLonAltBox(); } bool MonavMap::containsPoint( const GeoDataCoordinates &point ) const { // If we do not have a bounding box at all, we err on the safe side if ( m_tiles.isEmpty() ) { return true; } // Quick check for performance reasons if ( !m_boundingBox.contains( point ) ) { return false; } foreach( const GeoDataLinearRing &box, m_tiles ) { if ( box.contains( point ) ) { return true; } } return false; } MonavPluginPrivate::MonavPluginPrivate() : m_ownsServer( false ) { // nothing to do } MonavPluginPrivate::~MonavPluginPrivate() { stopDaemon(); } bool MonavPluginPrivate::isDaemonRunning() const { QLocalSocket socket; socket.connectToServer( "MoNavD" ); return socket.waitForConnected(); } bool MonavPluginPrivate::startDaemon() { if ( !isDaemonRunning() ) { QProcess process; if ( process.startDetached( "MoNavD" ) ) { m_ownsServer = true; // Give MoNavD up to one second to set up its server // Without that, the first route request would fail for ( int i = 0; i < 10; ++i ) { if ( isDaemonRunning() ) { break; } usleep( 100 * 1000 ); } return true; } return false; } return true; } void MonavPluginPrivate::stopDaemon() { if ( m_ownsServer ) { m_ownsServer = false; QProcess process; process.startDetached( "MoNavD", QStringList() << "-t" ); } } void MonavPluginPrivate::loadMaps() { QString base = MarbleDirs::localPath() + "/maps/earth/monav/"; loadMap( base ); QDir::Filters filters = QDir::AllDirs | QDir::Readable | QDir::NoDotAndDotDot; QDirIterator::IteratorFlags flags = QDirIterator::Subdirectories | QDirIterator::FollowSymlinks; QDirIterator iter( base, filters, flags ); while ( iter.hasNext() ) { iter.next(); loadMap( iter.filePath() ); } // Prefer maps where bounding boxes are known qSort( m_maps.begin(), m_maps.end(), MonavPluginPrivate::areaLessThan ); } void MonavPluginPrivate::loadMap( const QString &path ) { QDir mapDir( path ); QFileInfo pluginsFile( mapDir, "plugins.ini" ); if ( pluginsFile.exists() ) { MonavMap map; map.setDirectory( mapDir ); m_maps.append( map ); } } bool MonavPluginPrivate::areaLessThan( const MonavMap &first, const MonavMap &second ) { if ( !first.m_tiles.isEmpty() && second.m_tiles.isEmpty() ) { return true; } if ( first.m_tiles.isEmpty() && !second.m_tiles.isEmpty() ) { return false; } qreal const areaOne = first.m_boundingBox.width() * first.m_boundingBox.height(); qreal const areaTwo = second.m_boundingBox.width() * second.m_boundingBox.height(); return areaOne < areaTwo; } MonavPlugin::MonavPlugin( QObject *parent ) : RunnerPlugin( parent ), d( new MonavPluginPrivate ) { setSupportedCelestialBodies( QStringList() << "earth" ); setCanWorkOffline( true ); setName( tr( "Monav" ) ); setNameId( "monav" ); setDescription( tr( "Retrieves routes from monav" ) ); setGuiString( tr( "Monav Routing" ) ); // Check installation d->loadMaps(); bool const haveMap = !d->m_maps.isEmpty(); setCapabilities( haveMap ? Routing /*| ReverseGeocoding */ : None ); } MonavPlugin::~MonavPlugin() { delete d; } MarbleAbstractRunner* MonavPlugin::newRunner() const { if ( !d->startDaemon() ) { mDebug() << "Failed to connect to MoNavD daemon"; } return new MonavRunner( this ); } QString MonavPlugin::mapDirectoryForRequest( RouteRequest* request ) const { for ( int j=0; j<d->m_maps.size(); ++j ) { bool containsAllPoints = true; for ( int i = 0; i < request->size(); ++i ) { GeoDataCoordinates via = request->at( i ); if ( !d->m_maps[j].containsPoint( via ) ) { containsAllPoints = false; break; } } if ( containsAllPoints ) { if ( j ) { // Subsequent route requests will likely be in the same country qSwap( d->m_maps[0], d->m_maps[j] ); } // mDebug() << "Using " << d->m_maps.first().m_directory.dirName() << " as monav map"; return d->m_maps.first().m_directory.absolutePath(); } } return QString(); } } Q_EXPORT_PLUGIN2( MonavPlugin, Marble::MonavPlugin ) #include "MonavPlugin.moc" <|endoftext|>
<commit_before>#include "RRealtimeTimer.h" #include "RScopedPointer.h" #include "RIsr.h" #include "RThread.h" #define RREALTIME_TIMER_WAIT_PASS(code) \ while(pdPASS != (code)) \ { \ RThread::yieldCurrentThread(); \ } static const int32_t sMaxDelayMS = static_cast<int32_t>(portMAX_DELAY) * portTICK_PERIOD_MS; RRealtimeTimer::RRealtimeTimer() : mHandle(NULL) , mIsSingleShot(false) , mExtended(0) #if (configUSE_16_BIT_TICKS == 1) , mExtendedCounter(0) #endif { // NOTE: Set timer run as idle task by default, but we can't set interval to // zero, otherwise the created timer will return to NULL, so we give value 1 . mHandle = xTimerCreate( "", 1, pdFALSE, // one-shot timer reinterpret_cast<void *>(0), _callback ); vTimerSetTimerID(mHandle, this); } RRealtimeTimer::~RRealtimeTimer() { RREALTIME_TIMER_WAIT_PASS(xTimerDelete(mHandle, portMAX_DELAY)); } int32_t RRealtimeTimer::interval() const { return static_cast<int32_t>(xTimerGetPeriod(mHandle)) * portTICK_PERIOD_MS #if (configUSE_16_BIT_TICKS == 1) * (mExtended + 1) #endif ; } bool RRealtimeTimer::isActive() const { return xTimerIsTimerActive(mHandle); } bool RRealtimeTimer::isSingleShot() const { return mIsSingleShot; } void RRealtimeTimer::setInterval(int32_t msec) { #if (configUSE_16_BIT_TICKS == 1) mExtended = static_cast<uint8_t>(msec / sMaxDelayMS); // A little trick to generate a fixed delay value, so that we needs not to // store the remainder msec /= (mExtended + 1); #endif msec /= portTICK_PERIOD_MS; if(msec <= 0) { msec = 1; } if(_rIsrExecuting()) { BaseType_t xHigherPriorityTaskWoken = pdFALSE; xTimerChangePeriodFromISR(mHandle, static_cast<rtime>(msec), &xHigherPriorityTaskWoken); // xTimerChangePeriod will cause timer start, so we need to stop it // immediately xHigherPriorityTaskWoken = pdFALSE; xTimerStopFromISR(mHandle, &xHigherPriorityTaskWoken); } else if(RThread::currentThreadId() == xTimerGetTimerDaemonTaskHandle()) { xTimerChangePeriod(mHandle, static_cast<rtime>(msec), 0); xTimerStop(mHandle, 0); } else { RREALTIME_TIMER_WAIT_PASS(xTimerChangePeriod( mHandle, static_cast<rtime>(msec), portMAX_DELAY)); RREALTIME_TIMER_WAIT_PASS(xTimerStop(mHandle, portMAX_DELAY)); } } void RRealtimeTimer::setSingleShot(bool singleShot) { mIsSingleShot = singleShot; } int RRealtimeTimer::timerId() const { // WARNING: We shorten handle to id value, but it may lead duplicate id values. return rShortenPtr(pvTimerGetTimerID(mHandle)); } void RRealtimeTimer::start() { #if (configUSE_16_BIT_TICKS == 1) mExtendedCounter.store(mExtended); #endif if(_rIsrExecuting()) { BaseType_t xHigherPriorityTaskWoken = pdFALSE; xTimerStartFromISR(mHandle, &xHigherPriorityTaskWoken); } else if(RThread::currentThreadId() == xTimerGetTimerDaemonTaskHandle()) { xTimerStart(mHandle, 0); } else { RREALTIME_TIMER_WAIT_PASS(xTimerStart(mHandle, portMAX_DELAY)); } } void RRealtimeTimer::start(int32_t msec) { setInterval(msec); start(); } void RRealtimeTimer::stop() { if(_rIsrExecuting()) { BaseType_t xHigherPriorityTaskWoken = pdFALSE; xTimerStopFromISR(mHandle, &xHigherPriorityTaskWoken); } else if(RThread::currentThreadId() == xTimerGetTimerDaemonTaskHandle()) { xTimerStop(mHandle, 0); } else { RREALTIME_TIMER_WAIT_PASS(xTimerStop(mHandle, portMAX_DELAY)); } } void RRealtimeTimer::run() { } bool RRealtimeTimer::_isRestartFromCallback() { return true; } void RRealtimeTimer::_redirectEvents() { } void RRealtimeTimer::_callback(TimerHandle_t handle) { auto self = static_cast<RRealtimeTimer *>(pvTimerGetTimerID(handle)); #if (configUSE_16_BIT_TICKS == 1) if(self->mExtendedCounter.addIfLargeThan(0, -1)) { // Do not use a block time if calling a timer API function from a // timer callback function, as doing so could cause a deadlock! xTimerStart(self->mHandle, 0); return; } #endif if(self->_isRestartFromCallback()) { self->run(); } else { // Do restart action inside event loop self->_redirectEvents(); return; } if(self->isSingleShot()) { return; } xTimerStart(self->mHandle, 0); } <commit_msg>Only compile freertos RRealtimeTimer when R_OS_FREERTOS defined<commit_after>#ifdef R_OS_FREERTOS #include "RRealtimeTimer.h" #include "RScopedPointer.h" #include "RIsr.h" #include "RThread.h" #define RREALTIME_TIMER_WAIT_PASS(code) \ while(pdPASS != (code)) \ { \ RThread::yieldCurrentThread(); \ } static const int32_t sMaxDelayMS = static_cast<int32_t>(portMAX_DELAY) * portTICK_PERIOD_MS; RRealtimeTimer::RRealtimeTimer() : mHandle(NULL) , mIsSingleShot(false) , mExtended(0) #if (configUSE_16_BIT_TICKS == 1) , mExtendedCounter(0) #endif { // NOTE: Set timer run as idle task by default, but we can't set interval to // zero, otherwise the created timer will return to NULL, so we give value 1 . mHandle = xTimerCreate( "", 1, pdFALSE, // one-shot timer reinterpret_cast<void *>(0), _callback ); vTimerSetTimerID(mHandle, this); } RRealtimeTimer::~RRealtimeTimer() { RREALTIME_TIMER_WAIT_PASS(xTimerDelete(mHandle, portMAX_DELAY)); } int32_t RRealtimeTimer::interval() const { return static_cast<int32_t>(xTimerGetPeriod(mHandle)) * portTICK_PERIOD_MS #if (configUSE_16_BIT_TICKS == 1) * (mExtended + 1) #endif ; } bool RRealtimeTimer::isActive() const { return xTimerIsTimerActive(mHandle); } bool RRealtimeTimer::isSingleShot() const { return mIsSingleShot; } void RRealtimeTimer::setInterval(int32_t msec) { #if (configUSE_16_BIT_TICKS == 1) mExtended = static_cast<uint8_t>(msec / sMaxDelayMS); // A little trick to generate a fixed delay value, so that we needs not to // store the remainder msec /= (mExtended + 1); #endif msec /= portTICK_PERIOD_MS; if(msec <= 0) { msec = 1; } if(_rIsrExecuting()) { BaseType_t xHigherPriorityTaskWoken = pdFALSE; xTimerChangePeriodFromISR(mHandle, static_cast<rtime>(msec), &xHigherPriorityTaskWoken); // xTimerChangePeriod will cause timer start, so we need to stop it // immediately xHigherPriorityTaskWoken = pdFALSE; xTimerStopFromISR(mHandle, &xHigherPriorityTaskWoken); } else if(RThread::currentThreadId() == xTimerGetTimerDaemonTaskHandle()) { xTimerChangePeriod(mHandle, static_cast<rtime>(msec), 0); xTimerStop(mHandle, 0); } else { RREALTIME_TIMER_WAIT_PASS(xTimerChangePeriod( mHandle, static_cast<rtime>(msec), portMAX_DELAY)); RREALTIME_TIMER_WAIT_PASS(xTimerStop(mHandle, portMAX_DELAY)); } } void RRealtimeTimer::setSingleShot(bool singleShot) { mIsSingleShot = singleShot; } int RRealtimeTimer::timerId() const { // WARNING: We shorten handle to id value, but it may lead duplicate id values. return rShortenPtr(pvTimerGetTimerID(mHandle)); } void RRealtimeTimer::start() { #if (configUSE_16_BIT_TICKS == 1) mExtendedCounter.store(mExtended); #endif if(_rIsrExecuting()) { BaseType_t xHigherPriorityTaskWoken = pdFALSE; xTimerStartFromISR(mHandle, &xHigherPriorityTaskWoken); } else if(RThread::currentThreadId() == xTimerGetTimerDaemonTaskHandle()) { xTimerStart(mHandle, 0); } else { RREALTIME_TIMER_WAIT_PASS(xTimerStart(mHandle, portMAX_DELAY)); } } void RRealtimeTimer::start(int32_t msec) { setInterval(msec); start(); } void RRealtimeTimer::stop() { if(_rIsrExecuting()) { BaseType_t xHigherPriorityTaskWoken = pdFALSE; xTimerStopFromISR(mHandle, &xHigherPriorityTaskWoken); } else if(RThread::currentThreadId() == xTimerGetTimerDaemonTaskHandle()) { xTimerStop(mHandle, 0); } else { RREALTIME_TIMER_WAIT_PASS(xTimerStop(mHandle, portMAX_DELAY)); } } void RRealtimeTimer::run() { } bool RRealtimeTimer::_isRestartFromCallback() { return true; } void RRealtimeTimer::_redirectEvents() { } void RRealtimeTimer::_callback(TimerHandle_t handle) { auto self = static_cast<RRealtimeTimer *>(pvTimerGetTimerID(handle)); #if (configUSE_16_BIT_TICKS == 1) if(self->mExtendedCounter.addIfLargeThan(0, -1)) { // Do not use a block time if calling a timer API function from a // timer callback function, as doing so could cause a deadlock! xTimerStart(self->mHandle, 0); return; } #endif if(self->_isRestartFromCallback()) { self->run(); } else { // Do restart action inside event loop self->_redirectEvents(); return; } if(self->isSingleShot()) { return; } xTimerStart(self->mHandle, 0); } #endif // #ifdef R_OS_FREERTOS <|endoftext|>
<commit_before>#include "TrackingWorker.hpp" #include <boost/chrono/duration.hpp> #include <ros/console.h> #include <opencv2/core/core.hpp> #include <map> #include "../../matlab/profiling.hpp" TrackingWorker::TrackingWorker(IPositionReceiver *receiver) : errorGraph(100, "Difference") { assert(receiver != 0); this->receiver = receiver; stop = false; std::map<int, cv::Scalar> colors; colors[0] = cv::Scalar(0, 255, 0); colors[1] = cv::Scalar(0, 255, 255); colors[2] = cv::Scalar(255, 0, 255); errorGraph.setColors(colors); thread = new boost::thread(boost::bind(&TrackingWorker::run, this)); } TrackingWorker::~TrackingWorker() { stop = true; thread->join(); } void TrackingWorker::run() { ROS_INFO("Started tracking thread"); bool receivedFirstPosition = false; int emptyCount = 0; while (!stop) { std::vector<CameraData> data = dequeue(); if (data.size() > 1) { emptyCount = 0; if (!receivedFirstPosition) { receivedFirstPosition = true; ROS_INFO("Found quadcopter %d", data[0].quadcopterId); } // ROS_DEBUG("Got info from camera %d: [%.2f, %.2f, %.2f]", data[0].camNo, data[0].cameraVector.getV1(), data[0].cameraVector.getV2(), data[0].cameraVector.getV3()); double latency = 0; double currentTime = getNanoTime(); for (std::vector<CameraData>::iterator it = data.begin(); it != data.end(); it++) { double newLatency = currentTime - it->time; if (newLatency > latency) { latency = newLatency; } } ROS_DEBUG("Latency is %.3fms", latency / 1e6); Vector position = tracker.updatePosition(data); for (size_t i = 0; i < data.size(); i++) { errorGraph.nextPoint(tracker.getDistance(), data[i].camNo); } if (position.isValid()) { // Invert x axis for controller // position.setV1(-position.getV1()); std::vector<Vector> positions; std::vector<int> ids; std::vector<int> updates; positions.push_back(position); ids.push_back(data[0].quadcopterId); updates.push_back(1); receiver->updatePositions(positions, ids, updates); } } else if (receivedFirstPosition) { emptyCount++; if (emptyCount == 50) { // TODO uncomment ROS_WARN("Position update buffer is empty!"); emptyCount = 0; } boost::mutex::scoped_lock lock(queueMutex); queueEmpty.wait(lock); } } ROS_INFO("Stopped tracking thread"); } void TrackingWorker::updatePosition(Vector cameraVector, int camNo, int quadcopterId, long int time) { CameraData data; data.cameraVector = cameraVector; data.camNo = camNo; data.quadcopterId = quadcopterId; data.valid = true; data.time = time; updatePosition(data); } void TrackingWorker::updatePosition(CameraData data) { enqueue(data); } void TrackingWorker::enqueue(CameraData data) { boost::mutex::scoped_lock lock(queueMutex); queue.enqueue(data); queueEmpty.notify_all(); } std::vector<CameraData> TrackingWorker::dequeue() { boost::mutex::scoped_lock lock(queueMutex); if (!dataAvailable()) { queueEmpty.timed_wait(lock, boost::get_system_time() + boost::posix_time::milliseconds(100)); } if (dataAvailable()) { return queue.dequeue(); } else { return std::vector<CameraData>(); } } bool TrackingWorker::dataAvailable() { return queue.dataAvailable(); } bool TrackingWorker::calibrate(ChessboardData *chessboard, int camNo) { return tracker.calibrate(chessboard, camNo); } Vector TrackingWorker::getCameraPosition(int camNo) { return tracker.getPosition(camNo); } Matrix TrackingWorker::getRotationMatrix(int camNo) { return tracker.getRotationMatrix(camNo); } cv::Mat TrackingWorker::getIntrinsicsMatrix(int camNo) { return tracker.getIntrinsicsMatrix(camNo); } cv::Mat TrackingWorker::getDistortionCoefficients(int camNo) { return tracker.getDistortionCoefficients(camNo); } void TrackingWorker::updateTrackingArea() { receiver->setTrackingArea(tracker.getTrackingArea()); } <commit_msg>Flip x values<commit_after>#include "TrackingWorker.hpp" #include <boost/chrono/duration.hpp> #include <ros/console.h> #include <opencv2/core/core.hpp> #include <map> #include "../../matlab/profiling.hpp" TrackingWorker::TrackingWorker(IPositionReceiver *receiver) : errorGraph(100, "Difference") { assert(receiver != 0); this->receiver = receiver; stop = false; std::map<int, cv::Scalar> colors; colors[0] = cv::Scalar(0, 255, 0); colors[1] = cv::Scalar(0, 255, 255); colors[2] = cv::Scalar(255, 0, 255); errorGraph.setColors(colors); thread = new boost::thread(boost::bind(&TrackingWorker::run, this)); } TrackingWorker::~TrackingWorker() { stop = true; thread->join(); } void TrackingWorker::run() { ROS_INFO("Started tracking thread"); bool receivedFirstPosition = false; int emptyCount = 0; while (!stop) { std::vector<CameraData> data = dequeue(); if (data.size() > 1) { emptyCount = 0; if (!receivedFirstPosition) { receivedFirstPosition = true; ROS_INFO("Found quadcopter %d", data[0].quadcopterId); } // ROS_DEBUG("Got info from camera %d: [%.2f, %.2f, %.2f]", data[0].camNo, data[0].cameraVector.getV1(), data[0].cameraVector.getV2(), data[0].cameraVector.getV3()); double latency = 0; double currentTime = getNanoTime(); for (std::vector<CameraData>::iterator it = data.begin(); it != data.end(); it++) { double newLatency = currentTime - it->time; if (newLatency > latency) { latency = newLatency; } } ROS_DEBUG("Latency is %.3fms", latency / 1e6); Vector position = tracker.updatePosition(data); for (size_t i = 0; i < data.size(); i++) { errorGraph.nextPoint(tracker.getDistance(), data[i].camNo); } if (position.isValid()) { // Invert x axis for controller position.setV1(-position.getV1()); std::vector<Vector> positions; std::vector<int> ids; std::vector<int> updates; positions.push_back(position); ids.push_back(data[0].quadcopterId); updates.push_back(1); receiver->updatePositions(positions, ids, updates); } } else if (receivedFirstPosition) { emptyCount++; if (emptyCount == 50) { // TODO uncomment ROS_WARN("Position update buffer is empty!"); emptyCount = 0; } boost::mutex::scoped_lock lock(queueMutex); queueEmpty.wait(lock); } } ROS_INFO("Stopped tracking thread"); } void TrackingWorker::updatePosition(Vector cameraVector, int camNo, int quadcopterId, long int time) { CameraData data; data.cameraVector = cameraVector; data.camNo = camNo; data.quadcopterId = quadcopterId; data.valid = true; data.time = time; updatePosition(data); } void TrackingWorker::updatePosition(CameraData data) { enqueue(data); } void TrackingWorker::enqueue(CameraData data) { boost::mutex::scoped_lock lock(queueMutex); queue.enqueue(data); queueEmpty.notify_all(); } std::vector<CameraData> TrackingWorker::dequeue() { boost::mutex::scoped_lock lock(queueMutex); if (!dataAvailable()) { queueEmpty.timed_wait(lock, boost::get_system_time() + boost::posix_time::milliseconds(100)); } if (dataAvailable()) { return queue.dequeue(); } else { return std::vector<CameraData>(); } } bool TrackingWorker::dataAvailable() { return queue.dataAvailable(); } bool TrackingWorker::calibrate(ChessboardData *chessboard, int camNo) { return tracker.calibrate(chessboard, camNo); } Vector TrackingWorker::getCameraPosition(int camNo) { return tracker.getPosition(camNo); } Matrix TrackingWorker::getRotationMatrix(int camNo) { return tracker.getRotationMatrix(camNo); } cv::Mat TrackingWorker::getIntrinsicsMatrix(int camNo) { return tracker.getIntrinsicsMatrix(camNo); } cv::Mat TrackingWorker::getDistortionCoefficients(int camNo) { return tracker.getDistortionCoefficients(camNo); } void TrackingWorker::updateTrackingArea() { receiver->setTrackingArea(tracker.getTrackingArea()); } <|endoftext|>
<commit_before>/* This file is part of VROOM. Copyright (c) 2015-2019, Julien Coupey. All rights reserved (see LICENSE). */ #include "problems/cvrp/operators/exchange.h" namespace vroom { namespace cvrp { Exchange::Exchange(const Input& input, const utils::SolutionState& sol_state, RawRoute& s_route, Index s_vehicle, Index s_rank, RawRoute& t_route, Index t_vehicle, Index t_rank) : Operator(input, sol_state, s_route, s_vehicle, s_rank, t_route, t_vehicle, t_rank) { assert(s_vehicle != t_vehicle); assert(s_route.size() >= 1); assert(t_route.size() >= 1); assert(s_rank < s_route.size()); assert(t_rank < t_route.size()); } void Exchange::compute_gain() { const auto& m = _input.get_matrix(); const auto& v_source = _input.vehicles[s_vehicle]; const auto& v_target = _input.vehicles[t_vehicle]; // For source vehicle, we consider the cost of replacing job at rank // s_rank with target job. Part of that cost (for adjacent // edges) is stored in _sol_state.edge_costs_around_node. Index s_index = _input.jobs[s_route[s_rank]].index(); Index t_index = _input.jobs[t_route[t_rank]].index(); // Determine costs added with target job. Gain new_previous_cost = 0; Gain new_next_cost = 0; if (s_rank == 0) { if (v_source.has_start()) { auto p_index = v_source.start.get().index(); new_previous_cost = m[p_index][t_index]; } } else { auto p_index = _input.jobs[s_route[s_rank - 1]].index(); new_previous_cost = m[p_index][t_index]; } if (s_rank == s_route.size() - 1) { if (v_source.has_end()) { auto n_index = v_source.end.get().index(); new_next_cost = m[t_index][n_index]; } } else { auto n_index = _input.jobs[s_route[s_rank + 1]].index(); new_next_cost = m[t_index][n_index]; } Gain s_gain = _sol_state.edge_costs_around_node[s_vehicle][s_rank] - new_previous_cost - new_next_cost; // For target vehicle, we consider the cost of replacing job at rank // t_rank with source job. Part of that cost (for adjacent // edges) is stored in _sol_state.edge_costs_around_node. // Determine costs added with source job. new_previous_cost = 0; new_next_cost = 0; if (t_rank == 0) { if (v_target.has_start()) { auto p_index = v_target.start.get().index(); new_previous_cost = m[p_index][s_index]; } } else { auto p_index = _input.jobs[t_route[t_rank - 1]].index(); new_previous_cost = m[p_index][s_index]; } if (t_rank == t_route.size() - 1) { if (v_target.has_end()) { auto n_index = v_target.end.get().index(); new_next_cost = m[s_index][n_index]; } } else { auto n_index = _input.jobs[t_route[t_rank + 1]].index(); new_next_cost = m[s_index][n_index]; } Gain t_gain = _sol_state.edge_costs_around_node[t_vehicle][t_rank] - new_previous_cost - new_next_cost; stored_gain = s_gain + t_gain; gain_computed = true; } bool Exchange::is_valid() { auto s_job_rank = s_route[s_rank]; auto t_job_rank = t_route[t_rank]; bool valid = _input.vehicle_ok_with_job(t_vehicle, s_job_rank); valid &= _input.vehicle_ok_with_job(s_vehicle, t_job_rank); valid &= (_sol_state.fwd_amounts[t_vehicle].back() - _input.jobs[t_job_rank].amount + _input.jobs[s_job_rank].amount <= _input.vehicles[t_vehicle].capacity); valid &= (_sol_state.fwd_amounts[s_vehicle].back() - _input.jobs[s_job_rank].amount + _input.jobs[t_job_rank].amount <= _input.vehicles[s_vehicle].capacity); return valid; } void Exchange::apply() { std::swap(s_route[s_rank], t_route[t_rank]); } std::vector<Index> Exchange::addition_candidates() const { return {s_vehicle, t_vehicle}; } std::vector<Index> Exchange::update_candidates() const { return {s_vehicle, t_vehicle}; } } // namespace cvrp } // namespace vroom <commit_msg>Update validity checks for Exchange.<commit_after>/* This file is part of VROOM. Copyright (c) 2015-2019, Julien Coupey. All rights reserved (see LICENSE). */ #include "problems/cvrp/operators/exchange.h" namespace vroom { namespace cvrp { Exchange::Exchange(const Input& input, const utils::SolutionState& sol_state, RawRoute& s_route, Index s_vehicle, Index s_rank, RawRoute& t_route, Index t_vehicle, Index t_rank) : Operator(input, sol_state, s_route, s_vehicle, s_rank, t_route, t_vehicle, t_rank) { assert(s_vehicle != t_vehicle); assert(s_route.size() >= 1); assert(t_route.size() >= 1); assert(s_rank < s_route.size()); assert(t_rank < t_route.size()); } void Exchange::compute_gain() { const auto& m = _input.get_matrix(); const auto& v_source = _input.vehicles[s_vehicle]; const auto& v_target = _input.vehicles[t_vehicle]; // For source vehicle, we consider the cost of replacing job at rank // s_rank with target job. Part of that cost (for adjacent // edges) is stored in _sol_state.edge_costs_around_node. Index s_index = _input.jobs[s_route[s_rank]].index(); Index t_index = _input.jobs[t_route[t_rank]].index(); // Determine costs added with target job. Gain new_previous_cost = 0; Gain new_next_cost = 0; if (s_rank == 0) { if (v_source.has_start()) { auto p_index = v_source.start.get().index(); new_previous_cost = m[p_index][t_index]; } } else { auto p_index = _input.jobs[s_route[s_rank - 1]].index(); new_previous_cost = m[p_index][t_index]; } if (s_rank == s_route.size() - 1) { if (v_source.has_end()) { auto n_index = v_source.end.get().index(); new_next_cost = m[t_index][n_index]; } } else { auto n_index = _input.jobs[s_route[s_rank + 1]].index(); new_next_cost = m[t_index][n_index]; } Gain s_gain = _sol_state.edge_costs_around_node[s_vehicle][s_rank] - new_previous_cost - new_next_cost; // For target vehicle, we consider the cost of replacing job at rank // t_rank with source job. Part of that cost (for adjacent // edges) is stored in _sol_state.edge_costs_around_node. // Determine costs added with source job. new_previous_cost = 0; new_next_cost = 0; if (t_rank == 0) { if (v_target.has_start()) { auto p_index = v_target.start.get().index(); new_previous_cost = m[p_index][s_index]; } } else { auto p_index = _input.jobs[t_route[t_rank - 1]].index(); new_previous_cost = m[p_index][s_index]; } if (t_rank == t_route.size() - 1) { if (v_target.has_end()) { auto n_index = v_target.end.get().index(); new_next_cost = m[s_index][n_index]; } } else { auto n_index = _input.jobs[t_route[t_rank + 1]].index(); new_next_cost = m[s_index][n_index]; } Gain t_gain = _sol_state.edge_costs_around_node[t_vehicle][t_rank] - new_previous_cost - new_next_cost; stored_gain = s_gain + t_gain; gain_computed = true; } bool Exchange::is_valid() { auto s_job_rank = s_route[s_rank]; auto t_job_rank = t_route[t_rank]; bool valid = _input.vehicle_ok_with_job(t_vehicle, s_job_rank); valid &= _input.vehicle_ok_with_job(s_vehicle, t_job_rank); valid &= target.is_valid_addition_for_capacity(_input, _input.jobs[s_route[s_rank]].pickup, _input.jobs[s_route[s_rank]].delivery, t_rank, t_rank + 1); valid &= source.is_valid_addition_for_capacity(_input, _input.jobs[t_route[t_rank]].pickup, _input.jobs[t_route[t_rank]].delivery, s_rank, s_rank + 1); return valid; } void Exchange::apply() { std::swap(s_route[s_rank], t_route[t_rank]); } std::vector<Index> Exchange::addition_candidates() const { return {s_vehicle, t_vehicle}; } std::vector<Index> Exchange::update_candidates() const { return {s_vehicle, t_vehicle}; } } // namespace cvrp } // namespace vroom <|endoftext|>
<commit_before>// // BatchEncoder - GetProgress WvUnpackDec // Copyright (C) 2005-2017 Wiesław Šoltés <[email protected]> // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; version 2 of the License. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // #include <stdio.h> #include <stdlib.h> #include <string.h> #include <memory.h> #include "GetProgress.h" int GetProgress(char *szLineBuff, int nLineLen) { // NOTE: // using my patched console encoder wvunpack.exe 4.31 // added fflush(...) after all fprintf(...) calls in WvUnpack project // because of delayed output from original console encoder int j; int nPos = 0; char szPercentage[32]; int nProgress = -1; memset(szPercentage, 0x00, sizeof(szPercentage)); // check if we have done the job // 'restored 2.wav in 2.86 secs (lossless, 26.56%)' if (nLineLen >= 7) { if (strncmp(szLineBuff, "restored", 8) == 0) { nProgress = 100; return nProgress; } } // search for: // 'restoring 2.wav, 20% done...' // find % (percentage) char for (j = 0; j < (int)nLineLen; j++) { if (szLineBuff[j] == '%') { nPos = j; break; } } if (nPos >= 3) { if (szLineBuff[nPos - 3] == ' ') // not a 100.0 % { if (szLineBuff[nPos - 2] == ' ') // 0 to 9 % { szPercentage[0] = szLineBuff[nPos - 1]; szPercentage[1] = '\0'; nProgress = atoi(szPercentage); return nProgress; } else if (szLineBuff[nPos - 2] >= '0' && szLineBuff[nPos - 2] <= '9') // 10 to 99 % { szPercentage[0] = szLineBuff[nPos - 2]; szPercentage[1] = szLineBuff[nPos - 1]; szPercentage[2] = '\0'; nProgress = atoi(szPercentage); return nProgress; } } else if (szLineBuff[nPos - 3] == '1') // 100.0 % { nProgress = 100; return nProgress; } } return -1; } <commit_msg>Update GetProgress.cpp<commit_after>// Copyright (c) Wiesław Šoltés. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. #include <stdio.h> #include <stdlib.h> #include <string.h> #include <memory.h> #include "GetProgress.h" int GetProgress(char *szLineBuff, int nLineLen) { // NOTE: // using my patched console encoder wvunpack.exe 4.31 // added fflush(...) after all fprintf(...) calls in WvUnpack project // because of delayed output from original console encoder int j; int nPos = 0; char szPercentage[32]; int nProgress = -1; memset(szPercentage, 0x00, sizeof(szPercentage)); // check if we have done the job // 'restored 2.wav in 2.86 secs (lossless, 26.56%)' if (nLineLen >= 7) { if (strncmp(szLineBuff, "restored", 8) == 0) { nProgress = 100; return nProgress; } } // search for: // 'restoring 2.wav, 20% done...' // find % (percentage) char for (j = 0; j < (int)nLineLen; j++) { if (szLineBuff[j] == '%') { nPos = j; break; } } if (nPos >= 3) { if (szLineBuff[nPos - 3] == ' ') // not a 100.0 % { if (szLineBuff[nPos - 2] == ' ') // 0 to 9 % { szPercentage[0] = szLineBuff[nPos - 1]; szPercentage[1] = '\0'; nProgress = atoi(szPercentage); return nProgress; } else if (szLineBuff[nPos - 2] >= '0' && szLineBuff[nPos - 2] <= '9') // 10 to 99 % { szPercentage[0] = szLineBuff[nPos - 2]; szPercentage[1] = szLineBuff[nPos - 1]; szPercentage[2] = '\0'; nProgress = atoi(szPercentage); return nProgress; } } else if (szLineBuff[nPos - 3] == '1') // 100.0 % { nProgress = 100; return nProgress; } } return -1; } <|endoftext|>
<commit_before>/* * Copyright (C) Alex Nekipelov ([email protected]) * License: MIT */ #ifndef REDISCLIENT_REDISCLIENTIMPL_CPP #define REDISCLIENT_REDISCLIENTIMPL_CPP #include <boost/asio/write.hpp> #include <algorithm> #include "redisclientimpl.h" namespace { static const char crlf[] = {'\r', '\n'}; inline void bufferAppend(std::vector<char> &vec, const std::string &s); inline void bufferAppend(std::vector<char> &vec, const char *s); inline void bufferAppend(std::vector<char> &vec, char c); template<size_t size> inline void bufferAppend(std::vector<char> &vec, const char (&s)[size]); inline void bufferAppend(std::vector<char> &vec, const redisclient::RedisBuffer &buf) { if (buf.data.type() == typeid(std::string)) bufferAppend(vec, boost::get<std::string>(buf.data)); else bufferAppend(vec, boost::get<std::vector<char>>(buf.data)); } inline void bufferAppend(std::vector<char> &vec, const std::string &s) { vec.insert(vec.end(), s.begin(), s.end()); } inline void bufferAppend(std::vector<char> &vec, const char *s) { vec.insert(vec.end(), s, s + strlen(s)); } inline void bufferAppend(std::vector<char> &vec, char c) { vec.resize(vec.size() + 1); vec[vec.size() - 1] = c; } template<size_t size> inline void bufferAppend(std::vector<char> &vec, const char (&s)[size]) { vec.insert(vec.end(), s, s + size); } } namespace redisclient { RedisClientImpl::RedisClientImpl(boost::asio::io_service &ioService) : strand(ioService), socket(ioService), bufSize(0), subscribeSeq(0), state(State::Unconnected) { } RedisClientImpl::~RedisClientImpl() { close(); } void RedisClientImpl::close() noexcept { if( state != State::Closed ) { boost::system::error_code ignored_ec; msgHandlers.clear(); socket.shutdown(boost::asio::ip::tcp::socket::shutdown_both, ignored_ec); socket.close(ignored_ec); state = State::Closed; } } RedisClientImpl::State RedisClientImpl::getState() const { return state; } void RedisClientImpl::processMessage() { socket.async_read_some(boost::asio::buffer(buf), std::bind(&RedisClientImpl::asyncRead, shared_from_this(), std::placeholders::_1, std::placeholders::_2)); } void RedisClientImpl::doProcessMessage(RedisValue v) { if( state == State::Subscribed ) { std::vector<RedisValue> result = v.toArray(); auto resultSize = result.size(); if( resultSize >= 3 ) { const RedisValue &command = result[0]; const RedisValue &queueName = result[(resultSize == 3)?1:2]; const RedisValue &value = result[(resultSize == 3)?2:3]; const RedisValue &pattern = (resultSize == 4) ? result[1] : queueName; std::string cmd = command.toString(); if( cmd == "message" || cmd == "pmessage" ) { SingleShotHandlersMap::iterator it = singleShotMsgHandlers.find(pattern.toString()); if( it != singleShotMsgHandlers.end() ) { strand.post(std::bind(it->second, value.toByteArray())); singleShotMsgHandlers.erase(it); } std::pair<MsgHandlersMap::iterator, MsgHandlersMap::iterator> pair = msgHandlers.equal_range(pattern.toString()); for(MsgHandlersMap::iterator handlerIt = pair.first; handlerIt != pair.second; ++handlerIt) { strand.post(std::bind(handlerIt->second.second, value.toByteArray())); } } else if( handlers.empty() == false && (cmd == "subscribe" || cmd == "unsubscribe" || cmd == "psubscribe" || cmd == "punsubscribe") ) { handlers.front()(std::move(v)); handlers.pop(); } else { std::stringstream ss; ss << "[RedisClient] invalid command: " << command.toString(); errorHandler(ss.str()); return; } } else { errorHandler("[RedisClient] Protocol error"); return; } } else { if( handlers.empty() == false ) { handlers.front()(std::move(v)); handlers.pop(); } else { std::stringstream ss; ss << "[RedisClient] unexpected message: " << v.inspect(); errorHandler(ss.str()); return; } } } void RedisClientImpl::asyncWrite(const boost::system::error_code &ec, size_t) { dataWrited.clear(); if( ec ) { errorHandler(ec.message()); return; } if( dataQueued.empty() == false ) { std::vector<boost::asio::const_buffer> buffers(dataQueued.size()); for(size_t i = 0; i < dataQueued.size(); ++i) { buffers[i] = boost::asio::buffer(dataQueued[i]); } std::swap(dataQueued, dataWrited); boost::asio::async_write(socket, buffers, std::bind(&RedisClientImpl::asyncWrite, shared_from_this(), std::placeholders::_1, std::placeholders::_2)); } } void RedisClientImpl::handleAsyncConnect(const boost::system::error_code &ec, const std::function<void(bool, const std::string &)> &handler) { if( !ec ) { boost::system::error_code ec2; // Ignore errors in set_option socket.set_option(boost::asio::ip::tcp::no_delay(true), ec2); state = State::Connected; handler(true, std::string()); processMessage(); } else { state = State::Unconnected; handler(false, ec.message()); } } std::vector<char> RedisClientImpl::makeCommand(const std::deque<RedisBuffer> &items) { std::vector<char> result; bufferAppend(result, '*'); bufferAppend(result, std::to_string(items.size())); bufferAppend<>(result, crlf); for(const auto &item: items) { bufferAppend(result, '$'); bufferAppend(result, std::to_string(item.size())); bufferAppend<>(result, crlf); bufferAppend(result, item); bufferAppend<>(result, crlf); } return result; } RedisValue RedisClientImpl::doSyncCommand(const std::deque<RedisBuffer> &command) { boost::system::error_code ec; std::vector<char> data = makeCommand(command); boost::asio::write(socket, boost::asio::buffer(data), boost::asio::transfer_all(), ec); if( ec ) { errorHandler(ec.message()); return RedisValue(); } return syncReadResponse(); } RedisValue RedisClientImpl::doSyncCommand(const std::deque<std::deque<RedisBuffer>> &commands) { boost::system::error_code ec; std::vector<std::vector<char>> data; std::vector<boost::asio::const_buffer> buffers; data.reserve(commands.size()); buffers.reserve(commands.size()); for(const auto &command: commands) { data.push_back(std::move(makeCommand(command))); buffers.push_back(boost::asio::buffer(data.back())); } boost::asio::write(socket, buffers, boost::asio::transfer_all(), ec); if( ec ) { errorHandler(ec.message()); return RedisValue(); } std::vector<RedisValue> responses; for(size_t i = 0; i < commands.size(); ++i) { responses.push_back(std::move(syncReadResponse())); } return RedisValue(std::move(responses)); } RedisValue RedisClientImpl::syncReadResponse() { for(;;) { if (bufSize == 0) { bufSize = socket.read_some(boost::asio::buffer(buf)); } for(size_t pos = 0; pos < bufSize;) { std::pair<size_t, RedisParser::ParseResult> result = redisParser.parse(buf.data() + pos, bufSize - pos); pos += result.first; ::memmove(buf.data(), buf.data() + pos, bufSize - pos); bufSize -= pos; if( result.second == RedisParser::Completed ) { return redisParser.result(); } else if( result.second == RedisParser::Incompleted ) { continue; } else { errorHandler("[RedisClient] Parser error"); return RedisValue(); } } } } void RedisClientImpl::doAsyncCommand(std::vector<char> buff, std::function<void(RedisValue)> handler) { handlers.push( std::move(handler) ); dataQueued.push_back(std::move(buff)); if( dataWrited.empty() ) { // start transmit process asyncWrite(boost::system::error_code(), 0); } } void RedisClientImpl::asyncRead(const boost::system::error_code &ec, const size_t size) { if( ec || size == 0 ) { if( state != State::Closed ) { errorHandler(ec.message()); } return; } for(size_t pos = 0; pos < size;) { std::pair<size_t, RedisParser::ParseResult> result = redisParser.parse(buf.data() + pos, size - pos); if( result.second == RedisParser::Completed ) { doProcessMessage(std::move(redisParser.result())); } else if( result.second == RedisParser::Incompleted ) { processMessage(); return; } else { errorHandler("[RedisClient] Parser error"); return; } pos += result.first; } processMessage(); } void RedisClientImpl::onRedisError(const RedisValue &v) { errorHandler(v.toString()); } void RedisClientImpl::defaulErrorHandler(const std::string &s) { throw std::runtime_error(s); } size_t RedisClientImpl::subscribe( const std::string &command, const std::string &channel, std::function<void(std::vector<char> msg)> msgHandler, std::function<void(RedisValue)> handler) { assert(state == State::Connected || state == State::Subscribed); if (state == State::Connected || state == State::Subscribed) { std::deque<RedisBuffer> items{ command, channel }; post(std::bind(&RedisClientImpl::doAsyncCommand, this, makeCommand(items), std::move(handler))); msgHandlers.insert(std::make_pair(channel, std::make_pair(subscribeSeq, std::move(msgHandler)))); state = State::Subscribed; return subscribeSeq++; } else { std::stringstream ss; ss << "RedisClientImpl::subscribe called with invalid state " << to_string(state); errorHandler(ss.str()); return 0; } } void RedisClientImpl::singleShotSubscribe( const std::string &command, const std::string &channel, std::function<void(std::vector<char> msg)> msgHandler, std::function<void(RedisValue)> handler) { assert(state == State::Connected || state == State::Subscribed); if (state == State::Connected || state == State::Subscribed) { std::deque<RedisBuffer> items{ command, channel }; post(std::bind(&RedisClientImpl::doAsyncCommand, this, makeCommand(items), std::move(handler))); singleShotMsgHandlers.insert(std::make_pair(channel, std::move(msgHandler))); state = State::Subscribed; } else { std::stringstream ss; ss << "RedisClientImpl::singleShotSubscribe called with invalid state " << to_string(state); errorHandler(ss.str()); } } void RedisClientImpl::unsubscribe(const std::string &command, size_t handleId, const std::string &channel, std::function<void(RedisValue)> handler) { #ifdef DEBUG static int recursion = 0; assert(recursion++ == 0); #endif assert(state == State::Connected || state == State::Subscribed); if (state == State::Connected || state == State::Subscribed) { // Remove subscribe-handler typedef RedisClientImpl::MsgHandlersMap::iterator iterator; std::pair<iterator, iterator> pair = msgHandlers.equal_range(channel); for (iterator it = pair.first; it != pair.second;) { if (it->second.first == handleId) { msgHandlers.erase(it++); } else { ++it; } } std::deque<RedisBuffer> items{ command, channel }; // Unsubscribe command for Redis post(std::bind(&RedisClientImpl::doAsyncCommand, this, makeCommand(items), handler)); } else { std::stringstream ss; ss << "RedisClientImpl::unsubscribe called with invalid state " << to_string(state); #ifdef DEBUG --recursion; #endif errorHandler(ss.str()); return; } #ifdef DEBUG --recursion; #endif } } #endif // REDISCLIENT_REDISCLIENTIMPL_CPP <commit_msg>Fix redundant std::move(). (#49)<commit_after>/* * Copyright (C) Alex Nekipelov ([email protected]) * License: MIT */ #ifndef REDISCLIENT_REDISCLIENTIMPL_CPP #define REDISCLIENT_REDISCLIENTIMPL_CPP #include <boost/asio/write.hpp> #include <algorithm> #include "redisclientimpl.h" namespace { static const char crlf[] = {'\r', '\n'}; inline void bufferAppend(std::vector<char> &vec, const std::string &s); inline void bufferAppend(std::vector<char> &vec, const char *s); inline void bufferAppend(std::vector<char> &vec, char c); template<size_t size> inline void bufferAppend(std::vector<char> &vec, const char (&s)[size]); inline void bufferAppend(std::vector<char> &vec, const redisclient::RedisBuffer &buf) { if (buf.data.type() == typeid(std::string)) bufferAppend(vec, boost::get<std::string>(buf.data)); else bufferAppend(vec, boost::get<std::vector<char>>(buf.data)); } inline void bufferAppend(std::vector<char> &vec, const std::string &s) { vec.insert(vec.end(), s.begin(), s.end()); } inline void bufferAppend(std::vector<char> &vec, const char *s) { vec.insert(vec.end(), s, s + strlen(s)); } inline void bufferAppend(std::vector<char> &vec, char c) { vec.resize(vec.size() + 1); vec[vec.size() - 1] = c; } template<size_t size> inline void bufferAppend(std::vector<char> &vec, const char (&s)[size]) { vec.insert(vec.end(), s, s + size); } } namespace redisclient { RedisClientImpl::RedisClientImpl(boost::asio::io_service &ioService) : strand(ioService), socket(ioService), bufSize(0), subscribeSeq(0), state(State::Unconnected) { } RedisClientImpl::~RedisClientImpl() { close(); } void RedisClientImpl::close() noexcept { if( state != State::Closed ) { boost::system::error_code ignored_ec; msgHandlers.clear(); socket.shutdown(boost::asio::ip::tcp::socket::shutdown_both, ignored_ec); socket.close(ignored_ec); state = State::Closed; } } RedisClientImpl::State RedisClientImpl::getState() const { return state; } void RedisClientImpl::processMessage() { socket.async_read_some(boost::asio::buffer(buf), std::bind(&RedisClientImpl::asyncRead, shared_from_this(), std::placeholders::_1, std::placeholders::_2)); } void RedisClientImpl::doProcessMessage(RedisValue v) { if( state == State::Subscribed ) { std::vector<RedisValue> result = v.toArray(); auto resultSize = result.size(); if( resultSize >= 3 ) { const RedisValue &command = result[0]; const RedisValue &queueName = result[(resultSize == 3)?1:2]; const RedisValue &value = result[(resultSize == 3)?2:3]; const RedisValue &pattern = (resultSize == 4) ? result[1] : queueName; std::string cmd = command.toString(); if( cmd == "message" || cmd == "pmessage" ) { SingleShotHandlersMap::iterator it = singleShotMsgHandlers.find(pattern.toString()); if( it != singleShotMsgHandlers.end() ) { strand.post(std::bind(it->second, value.toByteArray())); singleShotMsgHandlers.erase(it); } std::pair<MsgHandlersMap::iterator, MsgHandlersMap::iterator> pair = msgHandlers.equal_range(pattern.toString()); for(MsgHandlersMap::iterator handlerIt = pair.first; handlerIt != pair.second; ++handlerIt) { strand.post(std::bind(handlerIt->second.second, value.toByteArray())); } } else if( handlers.empty() == false && (cmd == "subscribe" || cmd == "unsubscribe" || cmd == "psubscribe" || cmd == "punsubscribe") ) { handlers.front()(std::move(v)); handlers.pop(); } else { std::stringstream ss; ss << "[RedisClient] invalid command: " << command.toString(); errorHandler(ss.str()); return; } } else { errorHandler("[RedisClient] Protocol error"); return; } } else { if( handlers.empty() == false ) { handlers.front()(std::move(v)); handlers.pop(); } else { std::stringstream ss; ss << "[RedisClient] unexpected message: " << v.inspect(); errorHandler(ss.str()); return; } } } void RedisClientImpl::asyncWrite(const boost::system::error_code &ec, size_t) { dataWrited.clear(); if( ec ) { errorHandler(ec.message()); return; } if( dataQueued.empty() == false ) { std::vector<boost::asio::const_buffer> buffers(dataQueued.size()); for(size_t i = 0; i < dataQueued.size(); ++i) { buffers[i] = boost::asio::buffer(dataQueued[i]); } std::swap(dataQueued, dataWrited); boost::asio::async_write(socket, buffers, std::bind(&RedisClientImpl::asyncWrite, shared_from_this(), std::placeholders::_1, std::placeholders::_2)); } } void RedisClientImpl::handleAsyncConnect(const boost::system::error_code &ec, const std::function<void(bool, const std::string &)> &handler) { if( !ec ) { boost::system::error_code ec2; // Ignore errors in set_option socket.set_option(boost::asio::ip::tcp::no_delay(true), ec2); state = State::Connected; handler(true, std::string()); processMessage(); } else { state = State::Unconnected; handler(false, ec.message()); } } std::vector<char> RedisClientImpl::makeCommand(const std::deque<RedisBuffer> &items) { std::vector<char> result; bufferAppend(result, '*'); bufferAppend(result, std::to_string(items.size())); bufferAppend<>(result, crlf); for(const auto &item: items) { bufferAppend(result, '$'); bufferAppend(result, std::to_string(item.size())); bufferAppend<>(result, crlf); bufferAppend(result, item); bufferAppend<>(result, crlf); } return result; } RedisValue RedisClientImpl::doSyncCommand(const std::deque<RedisBuffer> &command) { boost::system::error_code ec; std::vector<char> data = makeCommand(command); boost::asio::write(socket, boost::asio::buffer(data), boost::asio::transfer_all(), ec); if( ec ) { errorHandler(ec.message()); return RedisValue(); } return syncReadResponse(); } RedisValue RedisClientImpl::doSyncCommand(const std::deque<std::deque<RedisBuffer>> &commands) { boost::system::error_code ec; std::vector<std::vector<char>> data; std::vector<boost::asio::const_buffer> buffers; data.reserve(commands.size()); buffers.reserve(commands.size()); for(const auto &command: commands) { data.push_back(makeCommand(command)); buffers.push_back(boost::asio::buffer(data.back())); } boost::asio::write(socket, buffers, boost::asio::transfer_all(), ec); if( ec ) { errorHandler(ec.message()); return RedisValue(); } std::vector<RedisValue> responses; for(size_t i = 0; i < commands.size(); ++i) { responses.push_back(syncReadResponse()); } return RedisValue(std::move(responses)); } RedisValue RedisClientImpl::syncReadResponse() { for(;;) { if (bufSize == 0) { bufSize = socket.read_some(boost::asio::buffer(buf)); } for(size_t pos = 0; pos < bufSize;) { std::pair<size_t, RedisParser::ParseResult> result = redisParser.parse(buf.data() + pos, bufSize - pos); pos += result.first; ::memmove(buf.data(), buf.data() + pos, bufSize - pos); bufSize -= pos; if( result.second == RedisParser::Completed ) { return redisParser.result(); } else if( result.second == RedisParser::Incompleted ) { continue; } else { errorHandler("[RedisClient] Parser error"); return RedisValue(); } } } } void RedisClientImpl::doAsyncCommand(std::vector<char> buff, std::function<void(RedisValue)> handler) { handlers.push( std::move(handler) ); dataQueued.push_back(std::move(buff)); if( dataWrited.empty() ) { // start transmit process asyncWrite(boost::system::error_code(), 0); } } void RedisClientImpl::asyncRead(const boost::system::error_code &ec, const size_t size) { if( ec || size == 0 ) { if( state != State::Closed ) { errorHandler(ec.message()); } return; } for(size_t pos = 0; pos < size;) { std::pair<size_t, RedisParser::ParseResult> result = redisParser.parse(buf.data() + pos, size - pos); if( result.second == RedisParser::Completed ) { doProcessMessage(redisParser.result()); } else if( result.second == RedisParser::Incompleted ) { processMessage(); return; } else { errorHandler("[RedisClient] Parser error"); return; } pos += result.first; } processMessage(); } void RedisClientImpl::onRedisError(const RedisValue &v) { errorHandler(v.toString()); } void RedisClientImpl::defaulErrorHandler(const std::string &s) { throw std::runtime_error(s); } size_t RedisClientImpl::subscribe( const std::string &command, const std::string &channel, std::function<void(std::vector<char> msg)> msgHandler, std::function<void(RedisValue)> handler) { assert(state == State::Connected || state == State::Subscribed); if (state == State::Connected || state == State::Subscribed) { std::deque<RedisBuffer> items{ command, channel }; post(std::bind(&RedisClientImpl::doAsyncCommand, this, makeCommand(items), std::move(handler))); msgHandlers.insert(std::make_pair(channel, std::make_pair(subscribeSeq, std::move(msgHandler)))); state = State::Subscribed; return subscribeSeq++; } else { std::stringstream ss; ss << "RedisClientImpl::subscribe called with invalid state " << to_string(state); errorHandler(ss.str()); return 0; } } void RedisClientImpl::singleShotSubscribe( const std::string &command, const std::string &channel, std::function<void(std::vector<char> msg)> msgHandler, std::function<void(RedisValue)> handler) { assert(state == State::Connected || state == State::Subscribed); if (state == State::Connected || state == State::Subscribed) { std::deque<RedisBuffer> items{ command, channel }; post(std::bind(&RedisClientImpl::doAsyncCommand, this, makeCommand(items), std::move(handler))); singleShotMsgHandlers.insert(std::make_pair(channel, std::move(msgHandler))); state = State::Subscribed; } else { std::stringstream ss; ss << "RedisClientImpl::singleShotSubscribe called with invalid state " << to_string(state); errorHandler(ss.str()); } } void RedisClientImpl::unsubscribe(const std::string &command, size_t handleId, const std::string &channel, std::function<void(RedisValue)> handler) { #ifdef DEBUG static int recursion = 0; assert(recursion++ == 0); #endif assert(state == State::Connected || state == State::Subscribed); if (state == State::Connected || state == State::Subscribed) { // Remove subscribe-handler typedef RedisClientImpl::MsgHandlersMap::iterator iterator; std::pair<iterator, iterator> pair = msgHandlers.equal_range(channel); for (iterator it = pair.first; it != pair.second;) { if (it->second.first == handleId) { msgHandlers.erase(it++); } else { ++it; } } std::deque<RedisBuffer> items{ command, channel }; // Unsubscribe command for Redis post(std::bind(&RedisClientImpl::doAsyncCommand, this, makeCommand(items), handler)); } else { std::stringstream ss; ss << "RedisClientImpl::unsubscribe called with invalid state " << to_string(state); #ifdef DEBUG --recursion; #endif errorHandler(ss.str()); return; } #ifdef DEBUG --recursion; #endif } } #endif // REDISCLIENT_REDISCLIENTIMPL_CPP <|endoftext|>
<commit_before>/* * 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. * * Written (W) 1999-2012 Soeren Sonnenburg and Sergey Lisitsyn * One vs. One strategy written (W) 2012 Fernando José Iglesias García and Sergey Lisitsyn * Copyright (C) 1999-2012 Fraunhofer Institute FIRST and Max-Planck-Society */ #include <shogun/machine/MulticlassMachine.h> #include <shogun/base/Parameter.h> #include <shogun/features/Labels.h> using namespace shogun; CMulticlassMachine::CMulticlassMachine() : CMachine(), m_multiclass_strategy(ONE_VS_REST_STRATEGY), m_rejection_strategy(NULL) { register_parameters(); } CMulticlassMachine::CMulticlassMachine( EMulticlassStrategy strategy, CMachine* machine, CLabels* labs) : CMachine(), m_multiclass_strategy(strategy), m_rejection_strategy(NULL) { set_labels(labs); SG_REF(machine); m_machine = machine; register_parameters(); } CMulticlassMachine::~CMulticlassMachine() { SG_UNREF(m_rejection_strategy); SG_UNREF(m_machine); clear_machines(); } void CMulticlassMachine::register_parameters() { m_parameters->add((machine_int_t*)&m_multiclass_strategy,"m_multiclass_type"); m_parameters->add((CSGObject**)&m_machine, "m_machine"); m_parameters->add((CSGObject**)&m_rejection_strategy, "m_rejection_strategy"); m_parameters->add_vector((CSGObject***)&m_machines.vector,&m_machines.vlen, "m_machines"); } void CMulticlassMachine::clear_machines() { for(int32_t i=0; i<m_machines.vlen; i++) SG_UNREF(m_machines[i]); m_machines.destroy_vector(); } CLabels* CMulticlassMachine::apply(CFeatures* features) { init_machines_for_apply(features); return apply(); } CLabels* CMulticlassMachine::apply() { switch (m_multiclass_strategy) { case ONE_VS_REST_STRATEGY: return classify_one_vs_rest(); break; case ONE_VS_ONE_STRATEGY: return classify_one_vs_one(); break; default: SG_ERROR("Unknown multiclass strategy\n"); } return NULL; } bool CMulticlassMachine::train_machine(CFeatures* data) { if (!data && !is_ready()) SG_ERROR("Please provide training data.\n"); if (data) { init_machine_for_train(data); init_machines_for_apply(data); } switch (m_multiclass_strategy) { case ONE_VS_REST_STRATEGY: return train_one_vs_rest(); break; case ONE_VS_ONE_STRATEGY: return train_one_vs_one(); break; default: SG_ERROR("Unknown multiclass strategy\n"); } return NULL; } bool CMulticlassMachine::train_one_vs_rest() { int32_t num_classes = m_labels->get_num_classes(); int32_t num_vectors = get_num_rhs_vectors(); clear_machines(); m_machines = SGVector<CMachine*>(num_classes); CLabels* train_labels = new CLabels(num_vectors); SG_REF(train_labels); m_machine->set_labels(train_labels); for (int32_t i=0; i<num_classes; i++) { for (int32_t j=0; j<num_vectors; j++) { if (m_labels->get_int_label(j)==i) train_labels->set_label(j,+1.0); else train_labels->set_label(j,-1.0); } m_machine->train(); m_machines[i] = get_machine_from_trained(m_machine); } SG_UNREF(train_labels); return true; } bool CMulticlassMachine::train_one_vs_one() { int32_t num_classes = m_labels->get_num_classes(); int32_t num_vectors = get_num_rhs_vectors(); clear_machines(); m_machines = SGVector<CMachine*>(num_classes*(num_classes-1)/2); CLabels* train_labels = new CLabels(num_vectors); SG_REF(train_labels); m_machine->set_labels(train_labels); /** Number of vectors included in every subset */ int32_t tot = 0; for (int32_t i=0, c=0; i<num_classes; i++) { for (int32_t j=i+1; j<num_classes; j++) { /** TODO fix this, there must be a way not to allocate these guys on every * iteration */ SGVector<index_t> subset_labels(num_vectors); SGVector<index_t> subset_feats(num_vectors); tot = 0; for (int32_t k=0; k<num_vectors; k++) { if (m_labels->get_int_label(k)==i) { train_labels->set_label(k,-1.0); subset_labels[tot] = k; subset_feats[tot] = k; tot++; } else if (m_labels->get_int_label(k)==j) { train_labels->set_label(k,1.0); subset_labels[tot] = k; subset_feats[tot] = k; tot++; } } train_labels->set_subset( new CSubset( SGVector<index_t>(subset_labels.vector, tot) ) ); set_machine_subset( new CSubset( SGVector<index_t>(subset_feats.vector, tot) ) ); m_machine->train(); m_machines[c++] = get_machine_from_trained(m_machine); train_labels->remove_subset(); remove_machine_subset(); } } SG_PRINT(">>>> at the end of training num_machines = %d\n", get_num_machines()); SG_UNREF(train_labels); return true; } CLabels* CMulticlassMachine::classify_one_vs_rest() { int32_t num_classes = m_labels->get_num_classes(); int32_t num_machines = get_num_machines(); ASSERT(num_machines==num_classes); CLabels* result=NULL; if (is_ready()) { int32_t num_vectors = get_num_rhs_vectors(); result=new CLabels(num_vectors); SG_REF(result); ASSERT(num_vectors==result->get_num_labels()); CLabels** outputs=SG_MALLOC(CLabels*, num_machines); for (int32_t i=0; i<num_machines; i++) { ASSERT(m_machines[i]); outputs[i]=m_machines[i]->apply(); } SGVector<float64_t> outputs_for_i(num_machines); for (int32_t i=0; i<num_vectors; i++) { int32_t winner = 0; for (int32_t j=0; j<num_machines; j++) outputs_for_i[j] = outputs[j]->get_label(i); if (m_rejection_strategy && m_rejection_strategy->reject(outputs_for_i)) { winner=result->REJECTION_LABEL; } else { float64_t max_out = outputs[0]->get_label(i); for (int32_t j=1; j<num_machines; j++) { if (outputs_for_i[j]>max_out) { max_out = outputs_for_i[j]; winner = j; } } } result->set_label(i, winner); } outputs_for_i.destroy_vector(); for (int32_t i=0; i<num_machines; i++) SG_UNREF(outputs[i]); SG_FREE(outputs); } return result; } CLabels* CMulticlassMachine::classify_one_vs_one() { int32_t num_classes = m_labels->get_num_classes(); int32_t num_machines = get_num_machines(); SG_PRINT(">>>> at the beginning of classify num_machines = %d\n", num_machines); SG_PRINT(">>>> at the beginning of classify num_classes = %d\n", num_classes); if ( num_machines != num_classes*(num_classes-1)/2 ) SG_ERROR("Dimension mismatch in classify_one_vs_one between number \ of machines = %d and number of classes = %d\n", num_machines, num_classes); CLabels* result = NULL; if ( is_ready() ) { int32_t num_vectors = get_num_rhs_vectors(); result = new CLabels(num_vectors); SG_REF(result); ASSERT(num_vectors==result->get_num_labels()); CLabels** outputs=SG_MALLOC(CLabels*, num_machines); for (int32_t i=0; i<num_machines; i++) { ASSERT(m_machines[i]); outputs[i]=m_machines[i]->apply(); } SG_PRINT(">>>> Starting to go through the vectors\n"); SGVector<float64_t> votes(num_classes); for (int32_t v=0; v<num_vectors; v++) { int32_t s=0; votes.zero(); for (int32_t i=0; i<num_classes; i++) { for (int32_t j=i+1; j<num_classes; j++) { SG_PRINT(">>>> s = %d v = %d\n", s, v); if ( ! outputs[s] ) SG_ERROR(">>>>>> outputs[%d] is null!!!\n", s); if (outputs[s++]->get_label(v)>0) votes[i]++; else votes[j]++; } } SG_PRINT(">>>> votes counted\n"); int32_t winner=0; int32_t max_votes=votes[0]; for (int32_t i=1; i<num_classes; i++) { if (votes[i]>max_votes) { max_votes=votes[i]; winner=i; } } SG_PRINT(">>>> max_votes found\n"); result->set_label(v, winner); } SG_PRINT(">>>> Destroy votes\n"); votes.destroy_vector(); for (int32_t i=0; i<num_machines; i++) SG_UNREF(outputs[i]); SG_FREE(outputs); } return result; } float64_t CMulticlassMachine::apply(int32_t num) { SG_NOTIMPLEMENTED; return 0; } <commit_msg>- debug prints<commit_after>/* * 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. * * Written (W) 1999-2012 Soeren Sonnenburg and Sergey Lisitsyn * One vs. One strategy written (W) 2012 Fernando José Iglesias García and Sergey Lisitsyn * Copyright (C) 1999-2012 Fraunhofer Institute FIRST and Max-Planck-Society */ #include <shogun/machine/MulticlassMachine.h> #include <shogun/base/Parameter.h> #include <shogun/features/Labels.h> using namespace shogun; CMulticlassMachine::CMulticlassMachine() : CMachine(), m_multiclass_strategy(ONE_VS_REST_STRATEGY), m_rejection_strategy(NULL) { register_parameters(); } CMulticlassMachine::CMulticlassMachine( EMulticlassStrategy strategy, CMachine* machine, CLabels* labs) : CMachine(), m_multiclass_strategy(strategy), m_rejection_strategy(NULL) { set_labels(labs); SG_REF(machine); m_machine = machine; register_parameters(); } CMulticlassMachine::~CMulticlassMachine() { SG_UNREF(m_rejection_strategy); SG_UNREF(m_machine); clear_machines(); } void CMulticlassMachine::register_parameters() { m_parameters->add((machine_int_t*)&m_multiclass_strategy,"m_multiclass_type"); m_parameters->add((CSGObject**)&m_machine, "m_machine"); m_parameters->add((CSGObject**)&m_rejection_strategy, "m_rejection_strategy"); m_parameters->add_vector((CSGObject***)&m_machines.vector,&m_machines.vlen, "m_machines"); } void CMulticlassMachine::clear_machines() { for(int32_t i=0; i<m_machines.vlen; i++) SG_UNREF(m_machines[i]); m_machines.destroy_vector(); } CLabels* CMulticlassMachine::apply(CFeatures* features) { init_machines_for_apply(features); return apply(); } CLabels* CMulticlassMachine::apply() { switch (m_multiclass_strategy) { case ONE_VS_REST_STRATEGY: return classify_one_vs_rest(); break; case ONE_VS_ONE_STRATEGY: return classify_one_vs_one(); break; default: SG_ERROR("Unknown multiclass strategy\n"); } return NULL; } bool CMulticlassMachine::train_machine(CFeatures* data) { if (!data && !is_ready()) SG_ERROR("Please provide training data.\n"); if (data) { init_machine_for_train(data); init_machines_for_apply(data); } switch (m_multiclass_strategy) { case ONE_VS_REST_STRATEGY: return train_one_vs_rest(); break; case ONE_VS_ONE_STRATEGY: return train_one_vs_one(); break; default: SG_ERROR("Unknown multiclass strategy\n"); } return NULL; } bool CMulticlassMachine::train_one_vs_rest() { int32_t num_classes = m_labels->get_num_classes(); int32_t num_vectors = get_num_rhs_vectors(); clear_machines(); m_machines = SGVector<CMachine*>(num_classes); CLabels* train_labels = new CLabels(num_vectors); SG_REF(train_labels); m_machine->set_labels(train_labels); for (int32_t i=0; i<num_classes; i++) { for (int32_t j=0; j<num_vectors; j++) { if (m_labels->get_int_label(j)==i) train_labels->set_label(j,+1.0); else train_labels->set_label(j,-1.0); } m_machine->train(); m_machines[i] = get_machine_from_trained(m_machine); } SG_UNREF(train_labels); return true; } bool CMulticlassMachine::train_one_vs_one() { int32_t num_classes = m_labels->get_num_classes(); int32_t num_vectors = get_num_rhs_vectors(); clear_machines(); m_machines = SGVector<CMachine*>(num_classes*(num_classes-1)/2); CLabels* train_labels = new CLabels(num_vectors); SG_REF(train_labels); m_machine->set_labels(train_labels); /** Number of vectors included in every subset */ int32_t tot = 0; for (int32_t i=0, c=0; i<num_classes; i++) { for (int32_t j=i+1; j<num_classes; j++) { SGVector<index_t> subset_labels(num_vectors); SGVector<index_t> subset_feats(num_vectors); tot = 0; for (int32_t k=0; k<num_vectors; k++) { if (m_labels->get_int_label(k)==i) { train_labels->set_label(k,-1.0); subset_labels[tot] = k; subset_feats[tot] = k; tot++; } else if (m_labels->get_int_label(k)==j) { train_labels->set_label(k,1.0); subset_labels[tot] = k; subset_feats[tot] = k; tot++; } } train_labels->set_subset( new CSubset( SGVector<index_t>(subset_labels.vector, tot) ) ); set_machine_subset( new CSubset( SGVector<index_t>(subset_feats.vector, tot) ) ); m_machine->train(); m_machines[c++] = get_machine_from_trained(m_machine); train_labels->remove_subset(); remove_machine_subset(); } } SG_UNREF(train_labels); return true; } CLabels* CMulticlassMachine::classify_one_vs_rest() { int32_t num_classes = m_labels->get_num_classes(); int32_t num_machines = get_num_machines(); ASSERT(num_machines==num_classes); CLabels* result=NULL; if (is_ready()) { int32_t num_vectors = get_num_rhs_vectors(); result=new CLabels(num_vectors); SG_REF(result); ASSERT(num_vectors==result->get_num_labels()); CLabels** outputs=SG_MALLOC(CLabels*, num_machines); for (int32_t i=0; i<num_machines; i++) { ASSERT(m_machines[i]); outputs[i]=m_machines[i]->apply(); } SGVector<float64_t> outputs_for_i(num_machines); for (int32_t i=0; i<num_vectors; i++) { int32_t winner = 0; for (int32_t j=0; j<num_machines; j++) outputs_for_i[j] = outputs[j]->get_label(i); if (m_rejection_strategy && m_rejection_strategy->reject(outputs_for_i)) { winner=result->REJECTION_LABEL; } else { float64_t max_out = outputs[0]->get_label(i); for (int32_t j=1; j<num_machines; j++) { if (outputs_for_i[j]>max_out) { max_out = outputs_for_i[j]; winner = j; } } } result->set_label(i, winner); } outputs_for_i.destroy_vector(); for (int32_t i=0; i<num_machines; i++) SG_UNREF(outputs[i]); SG_FREE(outputs); } return result; } CLabels* CMulticlassMachine::classify_one_vs_one() { int32_t num_classes = m_labels->get_num_classes(); int32_t num_machines = get_num_machines(); if ( num_machines != num_classes*(num_classes-1)/2 ) SG_ERROR("Dimension mismatch in classify_one_vs_one between number \ of machines = %d and number of classes = %d\n", num_machines, num_classes); CLabels* result = NULL; if ( is_ready() ) { int32_t num_vectors = get_num_rhs_vectors(); result = new CLabels(num_vectors); SG_REF(result); ASSERT(num_vectors==result->get_num_labels()); CLabels** outputs=SG_MALLOC(CLabels*, num_machines); for (int32_t i=0; i<num_machines; i++) { ASSERT(m_machines[i]); outputs[i]=m_machines[i]->apply(); } SGVector<float64_t> votes(num_classes); for (int32_t v=0; v<num_vectors; v++) { int32_t s=0; votes.zero(); for (int32_t i=0; i<num_classes; i++) { for (int32_t j=i+1; j<num_classes; j++) { if ( ! outputs[s] ) SG_ERROR(">>>>>> outputs[%d] is null!!!\n", s); if (outputs[s++]->get_label(v)>0) votes[i]++; else votes[j]++; } } int32_t winner=0; int32_t max_votes=votes[0]; for (int32_t i=1; i<num_classes; i++) { if (votes[i]>max_votes) { max_votes=votes[i]; winner=i; } } result->set_label(v, winner); } votes.destroy_vector(); for (int32_t i=0; i<num_machines; i++) SG_UNREF(outputs[i]); SG_FREE(outputs); } return result; } float64_t CMulticlassMachine::apply(int32_t num) { SG_NOTIMPLEMENTED; return 0; } <|endoftext|>
<commit_before>#ifndef HMLIB_UTILITY_INC #define HMLIB_UTILITY_INC 100 # /*===utility=== 主にオブジェクトの操作等に関わる汎用クラス/マクロ類を宣言する v1_00/130717 hmLib_static_restrictを追加 template引数に宣言することで、template引数の実行条件に制約をかけるマクロ clone関数を追加 コピーコンストラクタ/コピーファンクタを呼び出してクローンを生成する exchange関数を追加 値を入れ替えつつ、前回の値を返す */ namespace hmLib{ namespace utility{ namespace _enabler{ extern void* enabler; } } } #define hmLib_static_restrict(condition) typename std::enable_if<condition>::type *& = hmLib::utility::_enabler::enabler namespace hmLib{ //クローン関数 template<typename T> T clone(const T& t_){return T(t_);} template<typename T, typename Fn> T clone(const T& t_,Fn Func){return Func(t_);} //値入れ替え関数 template<typename T, typename U> T exchange(T& obj, U&& new_val) { T old_val = std::move(obj); obj = std::forward<U>(new_val); return old_val; } } # #endif <commit_msg>utility.hpp missed std utility header<commit_after>#ifndef HMLIB_UTILITY_INC #define HMLIB_UTILITY_INC 100 # #include<utility> /*===utility=== 主にオブジェクトの操作等に関わる汎用クラス/マクロ類を宣言する v1_00/130717 hmLib_static_restrictを追加 template引数に宣言することで、template引数の実行条件に制約をかけるマクロ clone関数を追加 コピーコンストラクタ/コピーファンクタを呼び出してクローンを生成する exchange関数を追加 値を入れ替えつつ、前回の値を返す */ namespace hmLib{ namespace utility{ namespace _enabler{ extern void* enabler; } } } #define hmLib_static_restrict(condition) typename std::enable_if<condition>::type *& = hmLib::utility::_enabler::enabler namespace hmLib{ //クローン関数 template<typename T> T clone(const T& t_){return T(t_);} template<typename T, typename Fn> T clone(const T& t_,Fn Func){return Func(t_);} //値入れ替え関数 template<typename T, typename U> T exchange(T& obj, U&& new_val) { T old_val = std::move(obj); obj = std::forward<U>(new_val); return old_val; } } # #endif <|endoftext|>
<commit_before>/* * Copyright 2017 The Cartographer Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "cartographer/cloud/map_builder_server_interface.h" #include "cartographer/cloud/map_builder_server_options.h" #include "cartographer/mapping/map_builder.h" #include "cartographer/metrics/register.h" #include "gflags/gflags.h" #include "glog/logging.h" #if USE_PROMETHEUS #include "cartographer/cloud/metrics/prometheus/family_factory.h" #include "prometheus/exposer.h" #endif DEFINE_string(configuration_directory, "", "First directory in which configuration files are searched, " "second is always the Cartographer installation to allow " "including files from there."); DEFINE_string(configuration_basename, "", "Basename, i.e. not containing any directory prefix, of the " "configuration file."); namespace cartographer { namespace cloud { void Run(const std::string& configuration_directory, const std::string& configuration_basename) { #if USE_PROMETHEUS metrics::prometheus::FamilyFactory registry; ::cartographer::metrics::RegisterAllMetrics(&registry); RegisterMapBuilderServerMetrics(&registry); ::prometheus::Exposer exposer("0.0.0.0:9100"); exposer.RegisterCollectable(registry.GetCollectable()); LOG(INFO) << "Exposing metrics at http://localhost:9100/metrics"; #endif proto::MapBuilderServerOptions map_builder_server_options = LoadMapBuilderServerOptions(configuration_directory, configuration_basename); // TODO(gaschler): Remove this override when parameter is imported from lua // config. map_builder_server_options.mutable_map_builder_options() ->set_collate_by_trajectory(true); auto map_builder = common::make_unique<mapping::MapBuilder>( map_builder_server_options.map_builder_options()); std::unique_ptr<MapBuilderServerInterface> map_builder_server = CreateMapBuilderServer(map_builder_server_options, std::move(map_builder)); map_builder_server->Start(); map_builder_server->WaitForShutdown(); } } // namespace cloud } // namespace cartographer int main(int argc, char** argv) { google::InitGoogleLogging(argv[0]); FLAGS_logtostderr = true; google::SetUsageMessage( "\n\n" "This program offers a MapBuilder service via a gRPC interface.\n"); google::ParseCommandLineFlags(&argc, &argv, true); if (FLAGS_configuration_directory.empty() || FLAGS_configuration_basename.empty()) { google::ShowUsageWithFlagsRestrict(argv[0], "cloud_server"); return EXIT_FAILURE; } cartographer::cloud::Run(FLAGS_configuration_directory, FLAGS_configuration_basename); } <commit_msg>Fix usage message of map_builder_server_main.cc (#1302)<commit_after>/* * Copyright 2017 The Cartographer Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "cartographer/cloud/map_builder_server_interface.h" #include "cartographer/cloud/map_builder_server_options.h" #include "cartographer/mapping/map_builder.h" #include "cartographer/metrics/register.h" #include "gflags/gflags.h" #include "glog/logging.h" #if USE_PROMETHEUS #include "cartographer/cloud/metrics/prometheus/family_factory.h" #include "prometheus/exposer.h" #endif DEFINE_string(configuration_directory, "", "First directory in which configuration files are searched, " "second is always the Cartographer installation to allow " "including files from there."); DEFINE_string(configuration_basename, "", "Basename, i.e. not containing any directory prefix, of the " "configuration file."); namespace cartographer { namespace cloud { void Run(const std::string& configuration_directory, const std::string& configuration_basename) { #if USE_PROMETHEUS metrics::prometheus::FamilyFactory registry; ::cartographer::metrics::RegisterAllMetrics(&registry); RegisterMapBuilderServerMetrics(&registry); ::prometheus::Exposer exposer("0.0.0.0:9100"); exposer.RegisterCollectable(registry.GetCollectable()); LOG(INFO) << "Exposing metrics at http://localhost:9100/metrics"; #endif proto::MapBuilderServerOptions map_builder_server_options = LoadMapBuilderServerOptions(configuration_directory, configuration_basename); // TODO(gaschler): Remove this override when parameter is imported from lua // config. map_builder_server_options.mutable_map_builder_options() ->set_collate_by_trajectory(true); auto map_builder = common::make_unique<mapping::MapBuilder>( map_builder_server_options.map_builder_options()); std::unique_ptr<MapBuilderServerInterface> map_builder_server = CreateMapBuilderServer(map_builder_server_options, std::move(map_builder)); map_builder_server->Start(); map_builder_server->WaitForShutdown(); } } // namespace cloud } // namespace cartographer int main(int argc, char** argv) { google::InitGoogleLogging(argv[0]); FLAGS_logtostderr = true; google::SetUsageMessage( "\n\n" "This program offers a MapBuilder service via a gRPC interface.\n"); google::ParseCommandLineFlags(&argc, &argv, true); if (FLAGS_configuration_directory.empty() || FLAGS_configuration_basename.empty()) { google::ShowUsageWithFlagsRestrict(argv[0], "map_builder_server"); return EXIT_FAILURE; } cartographer::cloud::Run(FLAGS_configuration_directory, FLAGS_configuration_basename); } <|endoftext|>
<commit_before>/****************************************************************************** * This file is part of dirtsand. * * * * dirtsand 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. * * * * dirtsand 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 dirtsand. If not, see <http://www.gnu.org/licenses/>. * ******************************************************************************/ #include "settings.h" #include "errors.h" #include "streams.h" #include <string_theory/stdio> #include <vector> #include <cstdio> /* Constants configured via CMake */ uint32_t DS::Settings::BranchId() { return PRODUCT_BRANCH_ID; } uint32_t DS::Settings::BuildId() { return PRODUCT_BUILD_ID; } uint32_t DS::Settings::BuildType() { return PRODUCT_BUILD_TYPE; } const char* DS::Settings::ProductUuid() { return PRODUCT_UUID; } const char* DS::Settings::HoodUserName() { return HOOD_USER_NAME; } const char* DS::Settings::HoodInstanceName() { return HOOD_INST_NAME; } uint32_t DS::Settings::HoodPopThreshold() { return HOOD_POP_THRESHOLD; } static struct { /* Encryption */ uint8_t m_cryptKeys[DS::e_KeyMaxTypes][64]; uint32_t m_droidKey[4]; /* Servers */ // TODO: Allow multiple servers for load balancing ST::utf16_buffer m_fileServ; ST::utf16_buffer m_authServ; ST::string m_gameServ; /* Host configuration */ ST::string m_lobbyAddr, m_lobbyPort; ST::string m_statusAddr, m_statusPort; /* Data locations */ ST::string m_fileRoot, m_authRoot; ST::string m_sdlPath, m_agePath; ST::string m_settingsPath; /* Database */ ST::string m_dbHostname, m_dbPort, m_dbUsername, m_dbPassword, m_dbDbase; /* Misc */ bool m_statusEnabled; ST::string m_welcome; } s_settings; #define DS_LOADBLOB(outbuffer, fixedsize, params) \ { \ Blob data = Base64Decode(params[1]); \ if (data.size() != fixedsize) { \ ST::printf(stderr, "Invalid base64 blob size for {}: " \ "Expected {} bytes, got {} bytes\n", \ params[0], fixedsize, data.size()); \ return false; \ } \ memcpy(outbuffer, data.buffer(), fixedsize); \ } #define BUF_TO_UINT(bufptr) \ ((bufptr)[0] << 24) | ((bufptr)[1] << 16) | ((bufptr)[2] << 8) | (bufptr)[3] bool DS::Settings::LoadFrom(const ST::string& filename) { UseDefaults(); s_settings.m_settingsPath = filename; ssize_t slash = s_settings.m_settingsPath.find_last('/'); if (slash >= 0) s_settings.m_settingsPath = s_settings.m_settingsPath.left(slash); else s_settings.m_settingsPath = "."; FILE* cfgfile = fopen(filename.c_str(), "r"); if (!cfgfile) { ST::printf(stderr, "Cannot open {} for reading\n", filename); return false; } { char buffer[4096]; while (fgets(buffer, 4096, cfgfile)) { ST::string line = ST::string(buffer).before_first('#').trim(); if (line.empty()) continue; std::vector<ST::string> params = line.split('=', 1); if (params.size() != 2) { ST::printf(stderr, "Warning: Invalid config line: {}\n", line); continue; } // Clean any whitespace around the '=' params[0] = params[0].trim(); params[1] = params[1].trim(); if (params[0] == "Key.Auth.N") { DS_LOADBLOB(s_settings.m_cryptKeys[e_KeyAuth_N], 64, params); } else if (params[0] == "Key.Auth.K") { DS_LOADBLOB(s_settings.m_cryptKeys[e_KeyAuth_K], 64, params); } else if (params[0] == "Key.Game.N") { DS_LOADBLOB(s_settings.m_cryptKeys[e_KeyGame_N], 64, params); } else if (params[0] == "Key.Game.K") { DS_LOADBLOB(s_settings.m_cryptKeys[e_KeyGame_K], 64, params); } else if (params[0] == "Key.Gate.N") { DS_LOADBLOB(s_settings.m_cryptKeys[e_KeyGate_N], 64, params); } else if (params[0] == "Key.Gate.K") { DS_LOADBLOB(s_settings.m_cryptKeys[e_KeyGate_K], 64, params); } else if (params[0] == "Key.Droid") { Blob data = HexDecode(params[1]); if (data.size() != 16) { fprintf(stderr, "Invalid key size for Key.Droid: " "Expected 16 bytes, got %zu bytes\n", data.size()); return false; } s_settings.m_droidKey[0] = BUF_TO_UINT(data.buffer() ); s_settings.m_droidKey[1] = BUF_TO_UINT(data.buffer() + 4); s_settings.m_droidKey[2] = BUF_TO_UINT(data.buffer() + 8); s_settings.m_droidKey[3] = BUF_TO_UINT(data.buffer() + 12); } else if (params[0] == "File.Host") { s_settings.m_fileServ = params[1].to_utf16(); } else if (params[0] == "Auth.Host") { s_settings.m_authServ = params[1].to_utf16(); } else if (params[0] == "Game.Host") { s_settings.m_gameServ = params[1]; } else if (params[0] == "Lobby.Addr") { s_settings.m_lobbyAddr = params[1]; } else if (params[0] == "Lobby.Port") { s_settings.m_lobbyPort = params[1]; } else if (params[0] == "Status.Addr") { s_settings.m_statusAddr = params[1]; } else if (params[0] == "Status.Port") { s_settings.m_statusPort = params[1]; } else if (params[0] == "Status.Enabled") { s_settings.m_statusEnabled = params[1].to_bool(); } else if (params[0] == "File.Root") { s_settings.m_fileRoot = params[1]; if (s_settings.m_fileRoot.right(1) != "/") s_settings.m_fileRoot += "/"; } else if (params[0] == "Auth.Root") { s_settings.m_authRoot = params[1]; if (s_settings.m_authRoot.right(1) != "/") s_settings.m_authRoot += "/"; } else if (params[0] == "Sdl.Path") { s_settings.m_sdlPath = params[1]; } else if (params[0] == "Age.Path") { s_settings.m_agePath = params[1]; } else if (params[0] == "Db.Host") { s_settings.m_dbHostname = params[1]; } else if (params[0] == "Db.Port") { s_settings.m_dbPort = params[1]; } else if (params[0] == "Db.Username") { s_settings.m_dbUsername = params[1]; } else if (params[0] == "Db.Password") { s_settings.m_dbPassword = params[1]; } else if (params[0] == "Db.Database") { s_settings.m_dbDbase = params[1]; } else if (params[0] == "Welcome.Msg") { s_settings.m_welcome = params[1]; } else { ST::printf(stderr, "Warning: Unknown setting '{}' ignored\n", params[0]); } } } fclose(cfgfile); return true; } void DS::Settings::UseDefaults() { memset(s_settings.m_cryptKeys, 0, sizeof(s_settings.m_cryptKeys)); memset(s_settings.m_droidKey, 0, sizeof(s_settings.m_droidKey)); s_settings.m_authServ = ST_LITERAL("localhost").to_utf16(); s_settings.m_fileServ = ST_LITERAL("localhost").to_utf16(); s_settings.m_gameServ = ST_LITERAL("localhost"); s_settings.m_lobbyPort = ST_LITERAL("14617"); s_settings.m_statusPort = ST_LITERAL("8080"); s_settings.m_statusEnabled = true; s_settings.m_fileRoot = ST_LITERAL("./data"); s_settings.m_authRoot = ST_LITERAL("./authdata"); s_settings.m_sdlPath = ST_LITERAL("./SDL"); s_settings.m_agePath = ST_LITERAL("./ages"); s_settings.m_dbHostname = ST_LITERAL("localhost"); s_settings.m_dbPort = ST_LITERAL("5432"); s_settings.m_dbUsername = ST_LITERAL("dirtsand"); s_settings.m_dbPassword = ST::null; s_settings.m_dbDbase = ST_LITERAL("dirtsand"); } const uint8_t* DS::Settings::CryptKey(DS::KeyType key) { DS_ASSERT(static_cast<int>(key) >= 0 && static_cast<int>(key) < e_KeyMaxTypes); return s_settings.m_cryptKeys[key]; } const uint32_t* DS::Settings::DroidKey() { return s_settings.m_droidKey; } ST::utf16_buffer DS::Settings::FileServerAddress() { return s_settings.m_fileServ; } ST::utf16_buffer DS::Settings::AuthServerAddress() { return s_settings.m_authServ; } ST::string DS::Settings::GameServerAddress() { return s_settings.m_gameServ; } const char* DS::Settings::LobbyAddress() { return s_settings.m_lobbyAddr.empty() ? "127.0.0.1" /* Not useful for external connections */ : s_settings.m_lobbyAddr.c_str(); } const char* DS::Settings::LobbyPort() { return s_settings.m_lobbyPort.c_str(); } bool DS::Settings::StatusEnabled() { return s_settings.m_statusEnabled; } const char* DS::Settings::StatusAddress() { return s_settings.m_statusAddr.empty() ? "127.0.0.1" /* Not useful for external connections */ : s_settings.m_statusAddr.c_str(); } const char* DS::Settings::StatusPort() { return s_settings.m_statusPort.c_str(); } ST::string DS::Settings::FileRoot() { return s_settings.m_fileRoot; } ST::string DS::Settings::AuthRoot() { return s_settings.m_authRoot; } const char* DS::Settings::SdlPath() { return s_settings.m_sdlPath.c_str(); } const char* DS::Settings::AgePath() { return s_settings.m_agePath.c_str(); } ST::string DS::Settings::SettingsPath() { return s_settings.m_settingsPath; } const char* DS::Settings::DbHostname() { return s_settings.m_dbHostname.c_str(); } const char* DS::Settings::DbPort() { return s_settings.m_dbPort.c_str(); } const char* DS::Settings::DbUsername() { return s_settings.m_dbUsername.c_str(); } const char* DS::Settings::DbPassword() { return s_settings.m_dbPassword.c_str(); } const char* DS::Settings::DbDbaseName() { return s_settings.m_dbDbase.c_str(); } ST::string DS::Settings::WelcomeMsg() { return s_settings.m_welcome; } void DS::Settings::SetWelcomeMsg(const ST::string& welcome) { s_settings.m_welcome = welcome; } <commit_msg>Don't leak cfgfile handle when reading settings file.<commit_after>/****************************************************************************** * This file is part of dirtsand. * * * * dirtsand 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. * * * * dirtsand 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 dirtsand. If not, see <http://www.gnu.org/licenses/>. * ******************************************************************************/ #include "settings.h" #include "errors.h" #include "streams.h" #include <string_theory/stdio> #include <vector> #include <cstdio> #include <memory> /* Constants configured via CMake */ uint32_t DS::Settings::BranchId() { return PRODUCT_BRANCH_ID; } uint32_t DS::Settings::BuildId() { return PRODUCT_BUILD_ID; } uint32_t DS::Settings::BuildType() { return PRODUCT_BUILD_TYPE; } const char* DS::Settings::ProductUuid() { return PRODUCT_UUID; } const char* DS::Settings::HoodUserName() { return HOOD_USER_NAME; } const char* DS::Settings::HoodInstanceName() { return HOOD_INST_NAME; } uint32_t DS::Settings::HoodPopThreshold() { return HOOD_POP_THRESHOLD; } static struct { /* Encryption */ uint8_t m_cryptKeys[DS::e_KeyMaxTypes][64]; uint32_t m_droidKey[4]; /* Servers */ // TODO: Allow multiple servers for load balancing ST::utf16_buffer m_fileServ; ST::utf16_buffer m_authServ; ST::string m_gameServ; /* Host configuration */ ST::string m_lobbyAddr, m_lobbyPort; ST::string m_statusAddr, m_statusPort; /* Data locations */ ST::string m_fileRoot, m_authRoot; ST::string m_sdlPath, m_agePath; ST::string m_settingsPath; /* Database */ ST::string m_dbHostname, m_dbPort, m_dbUsername, m_dbPassword, m_dbDbase; /* Misc */ bool m_statusEnabled; ST::string m_welcome; } s_settings; #define DS_LOADBLOB(outbuffer, fixedsize, params) \ { \ Blob data = Base64Decode(params[1]); \ if (data.size() != fixedsize) { \ ST::printf(stderr, "Invalid base64 blob size for {}: " \ "Expected {} bytes, got {} bytes\n", \ params[0], fixedsize, data.size()); \ return false; \ } \ memcpy(outbuffer, data.buffer(), fixedsize); \ } #define BUF_TO_UINT(bufptr) \ ((bufptr)[0] << 24) | ((bufptr)[1] << 16) | ((bufptr)[2] << 8) | (bufptr)[3] bool DS::Settings::LoadFrom(const ST::string& filename) { UseDefaults(); s_settings.m_settingsPath = filename; ssize_t slash = s_settings.m_settingsPath.find_last('/'); if (slash >= 0) s_settings.m_settingsPath = s_settings.m_settingsPath.left(slash); else s_settings.m_settingsPath = "."; std::unique_ptr<FILE, decltype(&fclose)> cfgfile(fopen(filename.c_str(), "r"), &fclose); if (!cfgfile) { ST::printf(stderr, "Cannot open {} for reading\n", filename); return false; } { char buffer[4096]; while (fgets(buffer, 4096, cfgfile.get())) { ST::string line = ST::string(buffer).before_first('#').trim(); if (line.empty()) continue; std::vector<ST::string> params = line.split('=', 1); if (params.size() != 2) { ST::printf(stderr, "Warning: Invalid config line: {}\n", line); continue; } // Clean any whitespace around the '=' params[0] = params[0].trim(); params[1] = params[1].trim(); if (params[0] == "Key.Auth.N") { DS_LOADBLOB(s_settings.m_cryptKeys[e_KeyAuth_N], 64, params); } else if (params[0] == "Key.Auth.K") { DS_LOADBLOB(s_settings.m_cryptKeys[e_KeyAuth_K], 64, params); } else if (params[0] == "Key.Game.N") { DS_LOADBLOB(s_settings.m_cryptKeys[e_KeyGame_N], 64, params); } else if (params[0] == "Key.Game.K") { DS_LOADBLOB(s_settings.m_cryptKeys[e_KeyGame_K], 64, params); } else if (params[0] == "Key.Gate.N") { DS_LOADBLOB(s_settings.m_cryptKeys[e_KeyGate_N], 64, params); } else if (params[0] == "Key.Gate.K") { DS_LOADBLOB(s_settings.m_cryptKeys[e_KeyGate_K], 64, params); } else if (params[0] == "Key.Droid") { Blob data = HexDecode(params[1]); if (data.size() != 16) { fprintf(stderr, "Invalid key size for Key.Droid: " "Expected 16 bytes, got %zu bytes\n", data.size()); return false; } s_settings.m_droidKey[0] = BUF_TO_UINT(data.buffer() ); s_settings.m_droidKey[1] = BUF_TO_UINT(data.buffer() + 4); s_settings.m_droidKey[2] = BUF_TO_UINT(data.buffer() + 8); s_settings.m_droidKey[3] = BUF_TO_UINT(data.buffer() + 12); } else if (params[0] == "File.Host") { s_settings.m_fileServ = params[1].to_utf16(); } else if (params[0] == "Auth.Host") { s_settings.m_authServ = params[1].to_utf16(); } else if (params[0] == "Game.Host") { s_settings.m_gameServ = params[1]; } else if (params[0] == "Lobby.Addr") { s_settings.m_lobbyAddr = params[1]; } else if (params[0] == "Lobby.Port") { s_settings.m_lobbyPort = params[1]; } else if (params[0] == "Status.Addr") { s_settings.m_statusAddr = params[1]; } else if (params[0] == "Status.Port") { s_settings.m_statusPort = params[1]; } else if (params[0] == "Status.Enabled") { s_settings.m_statusEnabled = params[1].to_bool(); } else if (params[0] == "File.Root") { s_settings.m_fileRoot = params[1]; if (s_settings.m_fileRoot.right(1) != "/") s_settings.m_fileRoot += "/"; } else if (params[0] == "Auth.Root") { s_settings.m_authRoot = params[1]; if (s_settings.m_authRoot.right(1) != "/") s_settings.m_authRoot += "/"; } else if (params[0] == "Sdl.Path") { s_settings.m_sdlPath = params[1]; } else if (params[0] == "Age.Path") { s_settings.m_agePath = params[1]; } else if (params[0] == "Db.Host") { s_settings.m_dbHostname = params[1]; } else if (params[0] == "Db.Port") { s_settings.m_dbPort = params[1]; } else if (params[0] == "Db.Username") { s_settings.m_dbUsername = params[1]; } else if (params[0] == "Db.Password") { s_settings.m_dbPassword = params[1]; } else if (params[0] == "Db.Database") { s_settings.m_dbDbase = params[1]; } else if (params[0] == "Welcome.Msg") { s_settings.m_welcome = params[1]; } else { ST::printf(stderr, "Warning: Unknown setting '{}' ignored\n", params[0]); } } } return true; } void DS::Settings::UseDefaults() { memset(s_settings.m_cryptKeys, 0, sizeof(s_settings.m_cryptKeys)); memset(s_settings.m_droidKey, 0, sizeof(s_settings.m_droidKey)); s_settings.m_authServ = ST_LITERAL("localhost").to_utf16(); s_settings.m_fileServ = ST_LITERAL("localhost").to_utf16(); s_settings.m_gameServ = ST_LITERAL("localhost"); s_settings.m_lobbyPort = ST_LITERAL("14617"); s_settings.m_statusPort = ST_LITERAL("8080"); s_settings.m_statusEnabled = true; s_settings.m_fileRoot = ST_LITERAL("./data"); s_settings.m_authRoot = ST_LITERAL("./authdata"); s_settings.m_sdlPath = ST_LITERAL("./SDL"); s_settings.m_agePath = ST_LITERAL("./ages"); s_settings.m_dbHostname = ST_LITERAL("localhost"); s_settings.m_dbPort = ST_LITERAL("5432"); s_settings.m_dbUsername = ST_LITERAL("dirtsand"); s_settings.m_dbPassword = ST::null; s_settings.m_dbDbase = ST_LITERAL("dirtsand"); } const uint8_t* DS::Settings::CryptKey(DS::KeyType key) { DS_ASSERT(static_cast<int>(key) >= 0 && static_cast<int>(key) < e_KeyMaxTypes); return s_settings.m_cryptKeys[key]; } const uint32_t* DS::Settings::DroidKey() { return s_settings.m_droidKey; } ST::utf16_buffer DS::Settings::FileServerAddress() { return s_settings.m_fileServ; } ST::utf16_buffer DS::Settings::AuthServerAddress() { return s_settings.m_authServ; } ST::string DS::Settings::GameServerAddress() { return s_settings.m_gameServ; } const char* DS::Settings::LobbyAddress() { return s_settings.m_lobbyAddr.empty() ? "127.0.0.1" /* Not useful for external connections */ : s_settings.m_lobbyAddr.c_str(); } const char* DS::Settings::LobbyPort() { return s_settings.m_lobbyPort.c_str(); } bool DS::Settings::StatusEnabled() { return s_settings.m_statusEnabled; } const char* DS::Settings::StatusAddress() { return s_settings.m_statusAddr.empty() ? "127.0.0.1" /* Not useful for external connections */ : s_settings.m_statusAddr.c_str(); } const char* DS::Settings::StatusPort() { return s_settings.m_statusPort.c_str(); } ST::string DS::Settings::FileRoot() { return s_settings.m_fileRoot; } ST::string DS::Settings::AuthRoot() { return s_settings.m_authRoot; } const char* DS::Settings::SdlPath() { return s_settings.m_sdlPath.c_str(); } const char* DS::Settings::AgePath() { return s_settings.m_agePath.c_str(); } ST::string DS::Settings::SettingsPath() { return s_settings.m_settingsPath; } const char* DS::Settings::DbHostname() { return s_settings.m_dbHostname.c_str(); } const char* DS::Settings::DbPort() { return s_settings.m_dbPort.c_str(); } const char* DS::Settings::DbUsername() { return s_settings.m_dbUsername.c_str(); } const char* DS::Settings::DbPassword() { return s_settings.m_dbPassword.c_str(); } const char* DS::Settings::DbDbaseName() { return s_settings.m_dbDbase.c_str(); } ST::string DS::Settings::WelcomeMsg() { return s_settings.m_welcome; } void DS::Settings::SetWelcomeMsg(const ST::string& welcome) { s_settings.m_welcome = welcome; } <|endoftext|>
<commit_before>#include "ct_defs.h" #include "ctexceptions.h" #include <fstream> #include <string> #include <stdlib.h> #include "ctml.h" #include "../../include/pypath.h" using namespace Cantera; namespace ctml { static string pypath() { string s = "python"; #ifdef PYTHON_EXE s = string(PYTHON_EXE); return s; #else const char* py = getenv("PYTHON_CMD"); if (py) s = string(py); return s; #endif } static bool checkPython() { string path = tmpDir() + "/check.py"; ofstream f(path.c_str()); if (!f) { throw CanteraError("checkPython","cannot write to "+tmpDir()); } f << "from Cantera import *\n"; f.close(); string cmd = pypath() + " " + path + " &> " + tmpDir() + "/log"; int ierr = system(cmd.c_str()); if (ierr != 0) { string msg; msg = cmd + "\n\n########################################################################\n\n" "The Cantera Python interface is required in order to process\n" "Cantera input files, but it does not seem to be correctly installed.\n\n" "Check that you can invoke the Python interpreter with \n" "the command \"python\", and that typing \"from Cantera import *\"\n" "at the Python prompt does not produce an error. If Python on your system\n" "is invoked with some other command, set environment variable PYTHON_CMD\n" "to the full path to the Python interpreter. \n\n" "#########################################################################\n\n"; writelog(msg); return false; } return true; } void ct2ctml(const char* file) { string path = tmpDir()+"/.cttmp.py"; ofstream f(path.c_str()); if (!f) { throw CanteraError("ct2ctml","cannot write to "+tmpDir()); } f << "from Cantera import *\n" << "from Cantera.ctml_writer import *\n" << "import sys, os, os.path\n" << "file = \"" << file << "\"\n" << "base = os.path.basename(file)\n" << "root, ext = os.path.splitext(base)\n" << "dataset(root)\n" << "execfile(file)\n" << "write()\n"; f.close(); string cmd = pypath() + " " + path + " &> ct2ctml.log"; int ierr = system(cmd.c_str()); if (ierr != 0) { string msg = cmd; ifstream ferr("ct2ctml.log"); if (ferr) { char line[80]; while (!ferr.eof()) { //msg += "\n"; ferr.getline(line, 80); writelog(string(line)+"\n"); } ferr.close(); } bool pyok = checkPython(); if (!pyok) msg += "\nError in Python installation."; else msg += "\nCheck error messages above for syntax errors."; throw CanteraError("ct2ctml", "could not convert input file to CTML\n command line was: "+msg); } } /** * Get an CTML tree from a file, possibly preprocessing the file * first. */ void get_CTML_Tree(XML_Node* rootPtr, string file) { string ff; // find the input file on the Cantera search path string inname = findInputFile(file); if (inname == "") throw CanteraError("get_CTML_tree", "file "+file+" not found"); /** * Check whether or not the file is XML. If not, it will be first * processed with the preprocessor. */ int idot = file.find('.'); string ext = file.substr(idot,file.size()); if (ext != ".xml" && ext != ".ctml") { ct2ctml(file.c_str()); ff = file.substr(0,idot)+".xml"; } else ff = file; ifstream fin(ff.c_str()); rootPtr->build(fin); fin.close(); } } <commit_msg>Fixed an error in get_CTML_Tree() where the program wouldn't use the path where the file was found, but would assume the file was located in the current directory. This caused an empty ifstream to be send to build(), which then created an infinite loop (probably another error in build() that needs to be fixed).<commit_after>/** * @file ct2ctml.cpp * * $Author$ * $Revision$ * $Date$ */ // Copyright 2001 California Institute of Technology #include "ct_defs.h" #include "ctexceptions.h" #include <fstream> #include <string> #include <stdlib.h> #include "ctml.h" using namespace Cantera; namespace ctml { static string pypath() { string s = "python"; #ifdef PYTHON_EXE s = string(PYTHON_EXE); return s; #else const char* py = getenv("PYTHON_CMD"); if (py) s = string(py); return s; #endif } static bool checkPython() { string path = tmpDir() + "/check.py"; ofstream f(path.c_str()); if (!f) { throw CanteraError("checkPython","cannot write to "+tmpDir()); } f << "from Cantera import *\n"; f.close(); string cmd = pypath() + " " + path + " &> " + tmpDir() + "/log"; int ierr = system(cmd.c_str()); if (ierr != 0) { string msg; msg = cmd + "\n\n########################################################################\n\n" "The Cantera Python interface is required in order to process\n" "Cantera input files, but it does not seem to be correctly installed.\n\n" "Check that you can invoke the Python interpreter with \n" "the command \"python\", and that typing \"from Cantera import *\"\n" "at the Python prompt does not produce an error. If Python on your system\n" "is invoked with some other command, set environment variable PYTHON_CMD\n" "to the full path to the Python interpreter. \n\n" "#########################################################################\n\n"; writelog(msg); return false; } return true; } void ct2ctml(const char* file) { string path = tmpDir()+"/.cttmp.py"; ofstream f(path.c_str()); if (!f) { throw CanteraError("ct2ctml","cannot write to "+tmpDir()); } f << "from Cantera import *\n" << "from Cantera.ctml_writer import *\n" << "import sys, os, os.path\n" << "file = \"" << file << "\"\n" << "base = os.path.basename(file)\n" << "root, ext = os.path.splitext(base)\n" << "dataset(root)\n" << "execfile(file)\n" << "write()\n"; f.close(); string cmd = pypath() + " " + path + " &> ct2ctml.log"; int ierr = system(cmd.c_str()); if (ierr != 0) { string msg = cmd; ifstream ferr("ct2ctml.log"); if (ferr) { char line[80]; while (!ferr.eof()) { //msg += "\n"; ferr.getline(line, 80); writelog(string(line)+"\n"); } ferr.close(); } bool pyok = checkPython(); if (!pyok) msg += "\nError in Python installation."; else msg += "\nCheck error messages above for syntax errors."; throw CanteraError("ct2ctml", "could not convert input file to CTML\n " "command line was: " + msg); } } /** * Get an CTML tree from a file, possibly preprocessing the file * first. */ void get_CTML_Tree(XML_Node* rootPtr, string file) { string ff, ext = ""; // find the input file on the Cantera search path string inname = findInputFile(file); if (inname == "") throw CanteraError("get_CTML_tree", "file "+file+" not found"); /** * Check whether or not the file is XML. If not, it will be first * processed with the preprocessor. */ string::size_type idot = inname.rfind('.'); if (idot != string::npos) { ext = inname.substr(idot, inname.size()); } if (ext != ".xml" && ext != ".ctml") { ct2ctml(inname.c_str()); ff = inname.substr(0,idot) + ".xml"; } else { ff = inname; } ifstream fin(ff.c_str()); rootPtr->build(fin); fin.close(); } } <|endoftext|>
<commit_before>// Copyright 2008, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include "chrome/browser/google_url_tracker.h" #include "testing/gtest/include/gtest/gtest.h" class GoogleURLTrackerTest : public testing::Test { }; TEST_F(GoogleURLTrackerTest, CheckAndConvertURL) { static const struct { const char* const source_url; const bool can_convert; const char* const base_url; } data[] = { { "http://www.google.com/", true, "http://www.google.com/", }, { "http://google.fr/", true, "http://google.fr/", }, { "http://google.co.uk/", true, "http://google.co.uk/", }, { "http://www.google.com.by/", true, "http://www.google.com.by/", }, { "http://www.google.com/ig", true, "http://www.google.com/", }, { "http://www.google.com/intl/xx", true, "http://www.google.com/intl/xx", }, { "http://a.b.c.google.com/", true, "http://a.b.c.google.com/", }, { "http://www.yahoo.com/", false, "", }, { "http://google.evil.com/", false, "", }, { "http://google.com.com.com/", false, "", }, { "http://google/", false, "", }, }; for (size_t i = 0; i < arraysize(data); ++i) { GURL base_url; const bool can_convert = GoogleURLTracker::CheckAndConvertToGoogleBaseURL( GURL(data[i].source_url), &base_url); EXPECT_EQ(data[i].can_convert, can_convert); EXPECT_STREQ(data[i].base_url, base_url.spec().c_str()); } } <commit_msg>Save a few lines since I don't need a test fixture. This was just silly oversight on my part due to not having written a new unittest in a while.<commit_after>// Copyright 2008, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include "chrome/browser/google_url_tracker.h" #include "testing/gtest/include/gtest/gtest.h" TEST(GoogleURLTrackerTest, CheckAndConvertURL) { static const struct { const char* const source_url; const bool can_convert; const char* const base_url; } data[] = { { "http://www.google.com/", true, "http://www.google.com/", }, { "http://google.fr/", true, "http://google.fr/", }, { "http://google.co.uk/", true, "http://google.co.uk/", }, { "http://www.google.com.by/", true, "http://www.google.com.by/", }, { "http://www.google.com/ig", true, "http://www.google.com/", }, { "http://www.google.com/intl/xx", true, "http://www.google.com/intl/xx", }, { "http://a.b.c.google.com/", true, "http://a.b.c.google.com/", }, { "http://www.yahoo.com/", false, "", }, { "http://google.evil.com/", false, "", }, { "http://google.com.com.com/", false, "", }, { "http://google/", false, "", }, }; for (size_t i = 0; i < arraysize(data); ++i) { GURL base_url; const bool can_convert = GoogleURLTracker::CheckAndConvertToGoogleBaseURL( GURL(data[i].source_url), &base_url); EXPECT_EQ(data[i].can_convert, can_convert); EXPECT_STREQ(data[i].base_url, base_url.spec().c_str()); } } <|endoftext|>
<commit_before>// // MapData // InternetMap // #include "MapData.hpp" #include "Node.hpp" #include "DisplayLines.hpp" #include "Connection.hpp" #include "IndexBox.hpp" #include "MapDisplay.hpp" #include <sstream> #include <stdlib.h> #include <fstream> #include <assert.h> // TODO: figure out how to do this right #ifdef ANDROID #include "jsoncpp/json.h" #else #include "json.h" #endif static const char *ASNS_AT_TOP[] = {"13768", "23498", "3", "15169", "714", "32934", "7847"}; //Peer1, Cogeco, MIT, google, apple, facebook, NASA static const int NUM_ASNS_AT_TOP = 7; NodePointer MapData::nodeAtIndex(unsigned int index) { return nodes[index]; } void split( std::vector<std::string> & theStringVector, /* Altered/returned value */ const std::string & theString, const std::string & theDelimiter) { size_t start = 0, end = 0; while ( end != std::string::npos) { end = theString.find( theDelimiter, start); // If at end, use length=maxLength. Else use length=end-start. theStringVector.push_back( theString.substr( start, (end == std::string::npos) ? std::string::npos : end - start)); // If at end, use start=maxSize. Else use start=end+delimiter. start = ( ( end > (std::string::npos - theDelimiter.size()) ) ? std::string::npos : end + theDelimiter.size()); } } static const int MAX_TOKEN_SIZE = 256; const char* nextToken(const char* source, char* token, bool* lineEnd, char separator = ' ') { *lineEnd = false; while ((*source != separator) && (*source != '\n') && (*source != 0)) { *token++ = *source++; } *lineEnd |= *source == '\n'; *token = 0; if(*source != 0) { while ((*source == separator) || (*source == '\n')) { source++; *lineEnd |= *source == '\n'; } } return source; } void MapData::resetToDefault() { for(int i = 0; i < nodes.size(); i++) { Node* node = nodes[i].get(); node->timelineActive = node->activeDefault; if(node->activeDefault) { node->positionX = node->defaultPositionX; node->positionY = node->defaultPositionY; node->importance = node->defaultImportance; } } connections = defaultConnections; visualization->activate(nodes); createNodeBoxes(); } void MapData::loadFromString(const std::string& text) { // Connections an boxes are always fully regenerated connections.erase(connections.begin(), connections.end()); // Mark all nodes as inactive (they will be reactivated if they are in the current data set) for(int i = 0; i < nodes.size(); i++) { nodes[i]->timelineActive = false; } const char* sourceText = text.c_str(); char token[MAX_TOKEN_SIZE]; bool lineEnd; int numNodes, numConnections; bool firstLoad = nodes.size() == 0; // Grab header data (node and connection counts) sourceText = nextToken(sourceText, token, &lineEnd); numNodes = atof(token); sourceText = nextToken(sourceText, token, &lineEnd); numConnections = atof(token); if (nodes.size() == 0) { LOG("initializing nodes vector (total %d)", numNodes); nodes.reserve(numNodes); nodes.resize(NUM_ASNS_AT_TOP); //LOG("nodes.size: %ld", nodes.size()); } int missingNodes = 0; for (int i = 0; i < numNodes; i++) { // Grab asn sourceText = nextToken(sourceText, token, &lineEnd); // check for matching existing node NodePointer node = nodesByAsn[token]; if(node) { // already thre, just mark as active node->timelineActive = true; } else { // Not there, create missingNodes++; node = NodePointer(new Node()); node->asn = token; node->type = AS_UNKNOWN; node->timelineActive = true; //is it a special node? bool needInsert = false; for (int i=0; i<NUM_ASNS_AT_TOP; i++) { if (strcmp(token, ASNS_AT_TOP[i]) == 0) { node->index = i; needInsert = true; //LOG("found special at index %d", node->index); break; } } if (needInsert) { nodes[node->index] = node; } else { //regular nodes can just be appended. node->index = nodes.size(); nodes.push_back(node); } nodesByAsn[node->asn] = node; } // Refill data that is unique to a particualar timeline position sourceText = nextToken(sourceText, token, &lineEnd); if(node) { node->importance = atof(token); } sourceText = nextToken(sourceText, token, &lineEnd); if(node) { node->positionX = atof(token); } sourceText = nextToken(sourceText, token, &lineEnd); if(node) { node->positionY = atof(token); } if(node && firstLoad) { node->defaultPositionX = node->positionX; node->defaultPositionY = node->positionY; node->defaultImportance = node->importance; node->activeDefault = true; } } // Load connections for (int i = 0; i < numConnections; i++) { ConnectionPointer connection(new Connection()); sourceText = nextToken(sourceText, token, &lineEnd); connection->first = nodesByAsn[token]; sourceText = nextToken(sourceText, token, &lineEnd); connection->second = nodesByAsn[token]; if (connection->first && connection->second) { connection->first->connections.push_back(connection); connection->second->connections.push_back(connection); connections.push_back(connection); } } if(firstLoad) { defaultConnections = connections; } LOG("loaded data: %d nodes (this load), %d nodes (total), %d connections", missingNodes, (int)(nodes.size()), numConnections); visualization->activate(nodes); createNodeBoxes(); } void MapData::loadFromAttrString(const std::string& json){ std::map<std::string, int> asTypeDict; asTypeDict["abstained"] = AS_UNKNOWN; asTypeDict["t1"] = AS_T1; asTypeDict["t2"] = AS_T2; asTypeDict["comp"] = AS_COMP; asTypeDict["edu"] = AS_EDU; asTypeDict["ix"] = AS_IX; asTypeDict["nic"] = AS_NIC; std::map<int, std::string> friendlyTypeStrings; friendlyTypeStrings[(int)AS_UNKNOWN] = "Unknown Network Type"; friendlyTypeStrings[(int)AS_T1] = "Large ISP"; friendlyTypeStrings[(int)AS_T2] = "Small ISP"; friendlyTypeStrings[(int)AS_COMP] = "Customer Network"; friendlyTypeStrings[(int)AS_EDU] = "University"; friendlyTypeStrings[(int)AS_IX] = "Internet Exchange Point"; friendlyTypeStrings[(int)AS_NIC] = "Network Information Center"; std::vector<std::string> lines; split(lines, json, "\n"); for(unsigned int i = 0; i < lines.size(); i++) { std::string line = lines[i]; std::vector<std::string> aDesc; split(aDesc, line, "\t"); NodePointer node = nodesByAsn[aDesc[0]]; if(node){ node->type = asTypeDict[aDesc[7]]; node->typeString = friendlyTypeStrings[node->type]; node->rawTextDescription = aDesc[1]; } } // NSLog(@"attr load : %.2fms", ([NSDate timeIntervalSinceReferenceDate] - start) * 1000.0f); } void MapData::loadASInfo(const std::string& json){ Json::Value root; Json::Reader reader; bool success = reader.parse(json, root); if(success) { std::vector<std::string> members = root.getMemberNames(); for (unsigned int i = 0; i < members.size(); i++) { NodePointer node = nodesByAsn[members[i]]; if (node) { Json::Value as = root[members[i]]; // node->name = as[1].asString(); // node->rawTextDescription = as[5].asString(); // node->dateRegistered = as[3].asString(); // node->address = as[7].asString(); // node->city = as[8].asString(); // node->state = as[9].asString(); // node->postalCode = as[10].asString(); // node->country = as[11].asString(); // node->hasLatLong = true; // node->latitude = as[12].asFloat()*2.0*3.14159/360.0; // node->longitude = as[13].asFloat()*2.0*3.14159/360.0; node->rawTextDescription = as[0].asString(); node->hasLatLong = true; node->latitude = as[1].asFloat()*2.0*3.14159/360.0; node->longitude = as[2].asFloat()*2.0*3.14159/360.0; } } } } void MapData::loadUnified(const std::string& text) { const char* sourceText = text.c_str(); char token[MAX_TOKEN_SIZE]; bool lineEnd; int numNodes, numConnections; // Grab header data (node and connection counts) sourceText = nextToken(sourceText, token, &lineEnd); numNodes = atof(token); sourceText = nextToken(sourceText, token, &lineEnd); numConnections = atof(token); nodes.reserve(numNodes); for (int i = 0; i < numNodes; i++) { NodePointer node = NodePointer(new Node()); node->timelineActive = true; node->activeDefault = true; sourceText = nextToken(sourceText, token, &lineEnd, '\t'); node->asn = token; sourceText = nextToken(sourceText, token, &lineEnd, '\t'); if(token[0] != '?') { node->rawTextDescription = token; } sourceText = nextToken(sourceText, token, &lineEnd, '\t'); node->type = atoi(token); sourceText = nextToken(sourceText, token, &lineEnd, '\t'); node->hasLatLong = atoi(token); sourceText = nextToken(sourceText, token, &lineEnd, '\t'); node->latitude = atof(token); sourceText = nextToken(sourceText, token, &lineEnd, '\t'); node->longitude = atof(token); sourceText = nextToken(sourceText, token, &lineEnd, '\t'); node->positionX = node->defaultPositionX = atof(token); sourceText = nextToken(sourceText, token, &lineEnd, '\t'); node->positionY = node->defaultPositionY = atof(token); sourceText = nextToken(sourceText, token, &lineEnd, '\t'); node->importance = node->defaultImportance = atof(token); assert(lineEnd); node->index = nodes.size(); nodes.push_back(node); nodesByAsn[node->asn] = node; } // Load connections for (int i = 0; i < numConnections; i++) { ConnectionPointer connection(new Connection()); sourceText = nextToken(sourceText, token, &lineEnd); connection->first = nodesByAsn[token]; sourceText = nextToken(sourceText, token, &lineEnd); connection->second = nodesByAsn[token]; if (connection->first && connection->second) { connection->first->connections.push_back(connection); connection->second->connections.push_back(connection); connections.push_back(connection); } } defaultConnections = connections; LOG("loaded default data: %d nodes, %d connections", (int)(nodes.size()), numConnections); visualization->activate(nodes); createNodeBoxes(); } void MapData::createNodeBoxes() { boxesForNodes.erase(boxesForNodes.begin(), boxesForNodes.end()); for (int k = 0; k < numberOfCellsZ; k++) { float z = IndexBoxMinZ + boxSizeZWithoutOverlap*k; for (int j = 0; j < numberOfCellsY; j++) { float y = IndexBoxMinY + boxSizeYWithoutOverlap*j; for(int i = 0; i < numberOfCellsX; i++) { float x = IndexBoxMinX + boxSizeXWithoutOverlap*i; IndexBoxPointer box = IndexBoxPointer(new IndexBox()); box->setCenter(Point3(x+boxSizeXWithoutOverlap/2, y+boxSizeYWithoutOverlap/2, z+boxSizeZWithoutOverlap/2)); box->setMinCorner(Point3(x, y, z)); box->setMaxCorner(Point3(x+boxSizeXWithoutOverlap, y+boxSizeYWithoutOverlap, z+boxSizeZWithoutOverlap)); boxesForNodes.push_back(box); } } } for (unsigned int i = 0; i < nodes.size(); i++) { NodePointer ptrNode = nodes.at(i); if(ptrNode->isActive()) { Point3 pos = visualization->nodePosition(ptrNode); IndexBoxPointer box = indexBoxForPoint(pos); box->indices.insert(i); } } } IndexBoxPointer MapData::indexBoxForPoint(const Point3& point) { int posX = (int)fabsf((point.getX() + fabsf(IndexBoxMinX))/boxSizeXWithoutOverlap); int posY = (int)fabsf((point.getY() + fabsf(IndexBoxMinY))/boxSizeYWithoutOverlap); int posZ = (int)fabsf((point.getZ() + fabsf(IndexBoxMinZ))/boxSizeZWithoutOverlap); int posInArray = posX + (fabsf(IndexBoxMinX) + fabsf(IndexBoxMaxX))/boxSizeXWithoutOverlap*posY + (fabsf(IndexBoxMinX) + fabsf(IndexBoxMaxX))/boxSizeXWithoutOverlap*(fabsf(IndexBoxMinY)+fabsf(IndexBoxMaxY))/boxSizeYWithoutOverlap*posZ; return boxesForNodes[posInArray]; } void MapData::dumpUnified(void) { std::ofstream out("/Users/nigel/Downloads/unified.txt"); out << nodes.size() << std::endl; out << connections.size() << std::endl; for(int i = 0; i < nodes.size(); i++) { std::string desc = nodes[i]->rawTextDescription; if(desc.length() == 0) { desc = "?"; } out << nodes[i]->asn << "\t" << desc << "\t" << nodes[i]->type << "\t" << nodes[i]->hasLatLong << "\t" << nodes[i]->latitude << "\t" << nodes[i]->longitude << "\t" << nodes[i]->positionX << "\t" << nodes[i]->positionY << "\t" << nodes[i]->importance << "\t" << std::endl; } for(int i = 0; i < connections.size(); i++) { out << connections[i]->first->index << " " << connections[i]->second->index << std::endl; } } <commit_msg>Change "Customer Network" to "Organization Network"<commit_after>// // MapData // InternetMap // #include "MapData.hpp" #include "Node.hpp" #include "DisplayLines.hpp" #include "Connection.hpp" #include "IndexBox.hpp" #include "MapDisplay.hpp" #include <sstream> #include <stdlib.h> #include <fstream> #include <assert.h> // TODO: figure out how to do this right #ifdef ANDROID #include "jsoncpp/json.h" #else #include "json.h" #endif static const char *ASNS_AT_TOP[] = {"13768", "23498", "3", "15169", "714", "32934", "7847"}; //Peer1, Cogeco, MIT, google, apple, facebook, NASA static const int NUM_ASNS_AT_TOP = 7; NodePointer MapData::nodeAtIndex(unsigned int index) { return nodes[index]; } void split( std::vector<std::string> & theStringVector, /* Altered/returned value */ const std::string & theString, const std::string & theDelimiter) { size_t start = 0, end = 0; while ( end != std::string::npos) { end = theString.find( theDelimiter, start); // If at end, use length=maxLength. Else use length=end-start. theStringVector.push_back( theString.substr( start, (end == std::string::npos) ? std::string::npos : end - start)); // If at end, use start=maxSize. Else use start=end+delimiter. start = ( ( end > (std::string::npos - theDelimiter.size()) ) ? std::string::npos : end + theDelimiter.size()); } } static const int MAX_TOKEN_SIZE = 256; const char* nextToken(const char* source, char* token, bool* lineEnd, char separator = ' ') { *lineEnd = false; while ((*source != separator) && (*source != '\n') && (*source != 0)) { *token++ = *source++; } *lineEnd |= *source == '\n'; *token = 0; if(*source != 0) { while ((*source == separator) || (*source == '\n')) { source++; *lineEnd |= *source == '\n'; } } return source; } void MapData::resetToDefault() { for(int i = 0; i < nodes.size(); i++) { Node* node = nodes[i].get(); node->timelineActive = node->activeDefault; if(node->activeDefault) { node->positionX = node->defaultPositionX; node->positionY = node->defaultPositionY; node->importance = node->defaultImportance; } } connections = defaultConnections; visualization->activate(nodes); createNodeBoxes(); } void MapData::loadFromString(const std::string& text) { // Connections an boxes are always fully regenerated connections.erase(connections.begin(), connections.end()); // Mark all nodes as inactive (they will be reactivated if they are in the current data set) for(int i = 0; i < nodes.size(); i++) { nodes[i]->timelineActive = false; } const char* sourceText = text.c_str(); char token[MAX_TOKEN_SIZE]; bool lineEnd; int numNodes, numConnections; bool firstLoad = nodes.size() == 0; // Grab header data (node and connection counts) sourceText = nextToken(sourceText, token, &lineEnd); numNodes = atof(token); sourceText = nextToken(sourceText, token, &lineEnd); numConnections = atof(token); if (nodes.size() == 0) { LOG("initializing nodes vector (total %d)", numNodes); nodes.reserve(numNodes); nodes.resize(NUM_ASNS_AT_TOP); //LOG("nodes.size: %ld", nodes.size()); } int missingNodes = 0; for (int i = 0; i < numNodes; i++) { // Grab asn sourceText = nextToken(sourceText, token, &lineEnd); // check for matching existing node NodePointer node = nodesByAsn[token]; if(node) { // already thre, just mark as active node->timelineActive = true; } else { // Not there, create missingNodes++; node = NodePointer(new Node()); node->asn = token; node->type = AS_UNKNOWN; node->timelineActive = true; //is it a special node? bool needInsert = false; for (int i=0; i<NUM_ASNS_AT_TOP; i++) { if (strcmp(token, ASNS_AT_TOP[i]) == 0) { node->index = i; needInsert = true; //LOG("found special at index %d", node->index); break; } } if (needInsert) { nodes[node->index] = node; } else { //regular nodes can just be appended. node->index = nodes.size(); nodes.push_back(node); } nodesByAsn[node->asn] = node; } // Refill data that is unique to a particualar timeline position sourceText = nextToken(sourceText, token, &lineEnd); if(node) { node->importance = atof(token); } sourceText = nextToken(sourceText, token, &lineEnd); if(node) { node->positionX = atof(token); } sourceText = nextToken(sourceText, token, &lineEnd); if(node) { node->positionY = atof(token); } if(node && firstLoad) { node->defaultPositionX = node->positionX; node->defaultPositionY = node->positionY; node->defaultImportance = node->importance; node->activeDefault = true; } } // Load connections for (int i = 0; i < numConnections; i++) { ConnectionPointer connection(new Connection()); sourceText = nextToken(sourceText, token, &lineEnd); connection->first = nodesByAsn[token]; sourceText = nextToken(sourceText, token, &lineEnd); connection->second = nodesByAsn[token]; if (connection->first && connection->second) { connection->first->connections.push_back(connection); connection->second->connections.push_back(connection); connections.push_back(connection); } } if(firstLoad) { defaultConnections = connections; } LOG("loaded data: %d nodes (this load), %d nodes (total), %d connections", missingNodes, (int)(nodes.size()), numConnections); visualization->activate(nodes); createNodeBoxes(); } void MapData::loadFromAttrString(const std::string& json){ std::map<std::string, int> asTypeDict; asTypeDict["abstained"] = AS_UNKNOWN; asTypeDict["t1"] = AS_T1; asTypeDict["t2"] = AS_T2; asTypeDict["comp"] = AS_COMP; asTypeDict["edu"] = AS_EDU; asTypeDict["ix"] = AS_IX; asTypeDict["nic"] = AS_NIC; std::map<int, std::string> friendlyTypeStrings; friendlyTypeStrings[(int)AS_UNKNOWN] = "Unknown Network Type"; friendlyTypeStrings[(int)AS_T1] = "Large ISP"; friendlyTypeStrings[(int)AS_T2] = "Small ISP"; friendlyTypeStrings[(int)AS_COMP] = "Organization Network"; friendlyTypeStrings[(int)AS_EDU] = "University"; friendlyTypeStrings[(int)AS_IX] = "Internet Exchange Point"; friendlyTypeStrings[(int)AS_NIC] = "Network Information Center"; std::vector<std::string> lines; split(lines, json, "\n"); for(unsigned int i = 0; i < lines.size(); i++) { std::string line = lines[i]; std::vector<std::string> aDesc; split(aDesc, line, "\t"); NodePointer node = nodesByAsn[aDesc[0]]; if(node){ node->type = asTypeDict[aDesc[7]]; node->typeString = friendlyTypeStrings[node->type]; node->rawTextDescription = aDesc[1]; } } // NSLog(@"attr load : %.2fms", ([NSDate timeIntervalSinceReferenceDate] - start) * 1000.0f); } void MapData::loadASInfo(const std::string& json){ Json::Value root; Json::Reader reader; bool success = reader.parse(json, root); if(success) { std::vector<std::string> members = root.getMemberNames(); for (unsigned int i = 0; i < members.size(); i++) { NodePointer node = nodesByAsn[members[i]]; if (node) { Json::Value as = root[members[i]]; // node->name = as[1].asString(); // node->rawTextDescription = as[5].asString(); // node->dateRegistered = as[3].asString(); // node->address = as[7].asString(); // node->city = as[8].asString(); // node->state = as[9].asString(); // node->postalCode = as[10].asString(); // node->country = as[11].asString(); // node->hasLatLong = true; // node->latitude = as[12].asFloat()*2.0*3.14159/360.0; // node->longitude = as[13].asFloat()*2.0*3.14159/360.0; node->rawTextDescription = as[0].asString(); node->hasLatLong = true; node->latitude = as[1].asFloat()*2.0*3.14159/360.0; node->longitude = as[2].asFloat()*2.0*3.14159/360.0; } } } } void MapData::loadUnified(const std::string& text) { const char* sourceText = text.c_str(); char token[MAX_TOKEN_SIZE]; bool lineEnd; int numNodes, numConnections; // Grab header data (node and connection counts) sourceText = nextToken(sourceText, token, &lineEnd); numNodes = atof(token); sourceText = nextToken(sourceText, token, &lineEnd); numConnections = atof(token); nodes.reserve(numNodes); for (int i = 0; i < numNodes; i++) { NodePointer node = NodePointer(new Node()); node->timelineActive = true; node->activeDefault = true; sourceText = nextToken(sourceText, token, &lineEnd, '\t'); node->asn = token; sourceText = nextToken(sourceText, token, &lineEnd, '\t'); if(token[0] != '?') { node->rawTextDescription = token; } sourceText = nextToken(sourceText, token, &lineEnd, '\t'); node->type = atoi(token); sourceText = nextToken(sourceText, token, &lineEnd, '\t'); node->hasLatLong = atoi(token); sourceText = nextToken(sourceText, token, &lineEnd, '\t'); node->latitude = atof(token); sourceText = nextToken(sourceText, token, &lineEnd, '\t'); node->longitude = atof(token); sourceText = nextToken(sourceText, token, &lineEnd, '\t'); node->positionX = node->defaultPositionX = atof(token); sourceText = nextToken(sourceText, token, &lineEnd, '\t'); node->positionY = node->defaultPositionY = atof(token); sourceText = nextToken(sourceText, token, &lineEnd, '\t'); node->importance = node->defaultImportance = atof(token); assert(lineEnd); node->index = nodes.size(); nodes.push_back(node); nodesByAsn[node->asn] = node; } // Load connections for (int i = 0; i < numConnections; i++) { ConnectionPointer connection(new Connection()); sourceText = nextToken(sourceText, token, &lineEnd); connection->first = nodesByAsn[token]; sourceText = nextToken(sourceText, token, &lineEnd); connection->second = nodesByAsn[token]; if (connection->first && connection->second) { connection->first->connections.push_back(connection); connection->second->connections.push_back(connection); connections.push_back(connection); } } defaultConnections = connections; LOG("loaded default data: %d nodes, %d connections", (int)(nodes.size()), numConnections); visualization->activate(nodes); createNodeBoxes(); } void MapData::createNodeBoxes() { boxesForNodes.erase(boxesForNodes.begin(), boxesForNodes.end()); for (int k = 0; k < numberOfCellsZ; k++) { float z = IndexBoxMinZ + boxSizeZWithoutOverlap*k; for (int j = 0; j < numberOfCellsY; j++) { float y = IndexBoxMinY + boxSizeYWithoutOverlap*j; for(int i = 0; i < numberOfCellsX; i++) { float x = IndexBoxMinX + boxSizeXWithoutOverlap*i; IndexBoxPointer box = IndexBoxPointer(new IndexBox()); box->setCenter(Point3(x+boxSizeXWithoutOverlap/2, y+boxSizeYWithoutOverlap/2, z+boxSizeZWithoutOverlap/2)); box->setMinCorner(Point3(x, y, z)); box->setMaxCorner(Point3(x+boxSizeXWithoutOverlap, y+boxSizeYWithoutOverlap, z+boxSizeZWithoutOverlap)); boxesForNodes.push_back(box); } } } for (unsigned int i = 0; i < nodes.size(); i++) { NodePointer ptrNode = nodes.at(i); if(ptrNode->isActive()) { Point3 pos = visualization->nodePosition(ptrNode); IndexBoxPointer box = indexBoxForPoint(pos); box->indices.insert(i); } } } IndexBoxPointer MapData::indexBoxForPoint(const Point3& point) { int posX = (int)fabsf((point.getX() + fabsf(IndexBoxMinX))/boxSizeXWithoutOverlap); int posY = (int)fabsf((point.getY() + fabsf(IndexBoxMinY))/boxSizeYWithoutOverlap); int posZ = (int)fabsf((point.getZ() + fabsf(IndexBoxMinZ))/boxSizeZWithoutOverlap); int posInArray = posX + (fabsf(IndexBoxMinX) + fabsf(IndexBoxMaxX))/boxSizeXWithoutOverlap*posY + (fabsf(IndexBoxMinX) + fabsf(IndexBoxMaxX))/boxSizeXWithoutOverlap*(fabsf(IndexBoxMinY)+fabsf(IndexBoxMaxY))/boxSizeYWithoutOverlap*posZ; return boxesForNodes[posInArray]; } void MapData::dumpUnified(void) { std::ofstream out("/Users/nigel/Downloads/unified.txt"); out << nodes.size() << std::endl; out << connections.size() << std::endl; for(int i = 0; i < nodes.size(); i++) { std::string desc = nodes[i]->rawTextDescription; if(desc.length() == 0) { desc = "?"; } out << nodes[i]->asn << "\t" << desc << "\t" << nodes[i]->type << "\t" << nodes[i]->hasLatLong << "\t" << nodes[i]->latitude << "\t" << nodes[i]->longitude << "\t" << nodes[i]->positionX << "\t" << nodes[i]->positionY << "\t" << nodes[i]->importance << "\t" << std::endl; } for(int i = 0; i < connections.size(); i++) { out << connections[i]->first->index << " " << connections[i]->second->index << std::endl; } } <|endoftext|>
<commit_before>/*========================================================================= Program: Visualization Toolkit Module: vtkMatrix4x4.cxx Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ #include "vtkMatrix4x4.h" #include "vtkMath.h" #include "vtkObjectFactory.h" #include <stdlib.h> #include <math.h> vtkCxxRevisionMacro(vtkMatrix4x4, "1.61"); vtkStandardNewMacro(vtkMatrix4x4); // Useful for viewing a double[16] as a double[4][4] typedef double (*SqMatPtr)[4]; //---------------------------------------------------------------------------- void vtkMatrix4x4::Zero(double Elements[16]) { SqMatPtr elem = (SqMatPtr)Elements; int i,j; for (i = 0; i < 4; i++) { for (j = 0; j < 4; j++) { elem[i][j] = 0.0; } } } //---------------------------------------------------------------------------- void vtkMatrix4x4::Identity(double Elements[16]) { Elements[0] = Elements[5] = Elements[10] = Elements[15] = 1.0; Elements[1] = Elements[2] = Elements[3] = Elements[4] = Elements[6] = Elements[7] = Elements[8] = Elements[9] = Elements[11] = Elements[12] = Elements[13] = Elements[14] = 0.0; } //---------------------------------------------------------------------------- template<class T1, class T2, class T3> void vtkMatrixMultiplyPoint(T1 elem[16], T2 in[4], T3 out[4]) { T3 v1 = in[0]; T3 v2 = in[1]; T3 v3 = in[2]; T3 v4 = in[3]; out[0] = v1*elem[0] + v2*elem[1] + v3*elem[2] + v4*elem[3]; out[1] = v1*elem[4] + v2*elem[5] + v3*elem[6] + v4*elem[7]; out[2] = v1*elem[8] + v2*elem[9] + v3*elem[10] + v4*elem[11]; out[3] = v1*elem[12] + v2*elem[13] + v3*elem[14] + v4*elem[15]; } //---------------------------------------------------------------------------- // Multiply this matrix by a point (in homogeneous coordinates). // and return the result in result. The in[4] and result[4] // arrays must both be allocated but they can be the same array. void vtkMatrix4x4::MultiplyPoint(const double Elements[16], const float in[4], float result[4]) { vtkMatrixMultiplyPoint(Elements,in,result); } //---------------------------------------------------------------------------- void vtkMatrix4x4::MultiplyPoint(const double Elements[16], const double in[4], double result[4]) { vtkMatrixMultiplyPoint(Elements,in,result); } //---------------------------------------------------------------------------- void vtkMatrix4x4::PointMultiply(const double Elements[16], const float in[4], float result[4]) { double newElements[16]; vtkMatrix4x4::Transpose(Elements,newElements); vtkMatrix4x4::MultiplyPoint(newElements,in,result); } //---------------------------------------------------------------------------- void vtkMatrix4x4::PointMultiply(const double Elements[16], const double in[4], double result[4]) { double newElements[16]; vtkMatrix4x4::Transpose(Elements,newElements); vtkMatrix4x4::MultiplyPoint(newElements,in,result); } //---------------------------------------------------------------------------- // Multiplies matrices a and b and stores the result in c. void vtkMatrix4x4::Multiply4x4(const double a[16], const double b[16], double c[16]) { SqMatPtr aMat = (SqMatPtr) a; SqMatPtr bMat = (SqMatPtr) b; SqMatPtr cMat = (SqMatPtr) c; int i, k; double Accum[4][4]; for (i = 0; i < 4; i++) { for (k = 0; k < 4; k++) { Accum[i][k] = aMat[i][0] * bMat[0][k] + aMat[i][1] * bMat[1][k] + aMat[i][2] * bMat[2][k] + aMat[i][3] * bMat[3][k]; } } // Copy to final dest for (i = 0; i < 4; i++) { cMat[i][0] = Accum[i][0]; cMat[i][1] = Accum[i][1]; cMat[i][2] = Accum[i][2]; cMat[i][3] = Accum[i][3]; } } //---------------------------------------------------------------------------- // Matrix Inversion (adapted from Richard Carling in "Graphics Gems," // Academic Press, 1990). void vtkMatrix4x4::Invert(const double inElements[16], double outElements[16]) { SqMatPtr outElem = (SqMatPtr)outElements; // inverse( original_matrix, inverse_matrix ) // calculate the inverse of a 4x4 matrix // // -1 // A = ___1__ adjoint A // det A // int i, j; double det; // calculate the 4x4 determinent // if the determinent is zero, // then the inverse matrix is not unique. det = vtkMatrix4x4::Determinant(inElements); if ( det == 0.0 ) { vtkGenericWarningMacro(<< "Singular matrix, no inverse!" ); return; } // calculate the adjoint matrix vtkMatrix4x4::Adjoint(inElements, outElements ); // scale the adjoint matrix to get the inverse for (i=0; i<4; i++) { for(j=0; j<4; j++) { outElem[i][j] = outElem[i][j] / det; } } } //---------------------------------------------------------------------------- double vtkMatrix4x4::Determinant(const double Elements[16]) { SqMatPtr elem = (SqMatPtr)Elements; double a1, a2, a3, a4, b1, b2, b3, b4, c1, c2, c3, c4, d1, d2, d3, d4; // assign to individual variable names to aid selecting // correct elements a1 = elem[0][0]; b1 = elem[0][1]; c1 = elem[0][2]; d1 = elem[0][3]; a2 = elem[1][0]; b2 = elem[1][1]; c2 = elem[1][2]; d2 = elem[1][3]; a3 = elem[2][0]; b3 = elem[2][1]; c3 = elem[2][2]; d3 = elem[2][3]; a4 = elem[3][0]; b4 = elem[3][1]; c4 = elem[3][2]; d4 = elem[3][3]; return a1 * vtkMath::Determinant3x3( b2, b3, b4, c2, c3, c4, d2, d3, d4) - b1 * vtkMath::Determinant3x3( a2, a3, a4, c2, c3, c4, d2, d3, d4) + c1 * vtkMath::Determinant3x3( a2, a3, a4, b2, b3, b4, d2, d3, d4) - d1 * vtkMath::Determinant3x3( a2, a3, a4, b2, b3, b4, c2, c3, c4); } //---------------------------------------------------------------------------- void vtkMatrix4x4::Adjoint(const double inElements[16], double outElements[16]) { SqMatPtr inElem = (SqMatPtr) inElements; SqMatPtr outElem = (SqMatPtr) outElements; // // adjoint( original_matrix, inverse_matrix ) // // calculate the adjoint of a 4x4 matrix // // Let a denote the minor determinant of matrix A obtained by // ij // // deleting the ith row and jth column from A. // // i+j // Let b = (-1) a // ij ji // // The matrix B = (b ) is the adjoint of A // ij // double a1, a2, a3, a4, b1, b2, b3, b4; double c1, c2, c3, c4, d1, d2, d3, d4; // assign to individual variable names to aid // selecting correct values a1 = inElem[0][0]; b1 = inElem[0][1]; c1 = inElem[0][2]; d1 = inElem[0][3]; a2 = inElem[1][0]; b2 = inElem[1][1]; c2 = inElem[1][2]; d2 = inElem[1][3]; a3 = inElem[2][0]; b3 = inElem[2][1]; c3 = inElem[2][2]; d3 = inElem[2][3]; a4 = inElem[3][0]; b4 = inElem[3][1]; c4 = inElem[3][2]; d4 = inElem[3][3]; // row column labeling reversed since we transpose rows & columns outElem[0][0] = vtkMath::Determinant3x3( b2, b3, b4, c2, c3, c4, d2, d3, d4); outElem[1][0] = - vtkMath::Determinant3x3( a2, a3, a4, c2, c3, c4, d2, d3, d4); outElem[2][0] = vtkMath::Determinant3x3( a2, a3, a4, b2, b3, b4, d2, d3, d4); outElem[3][0] = - vtkMath::Determinant3x3( a2, a3, a4, b2, b3, b4, c2, c3, c4); outElem[0][1] = - vtkMath::Determinant3x3( b1, b3, b4, c1, c3, c4, d1, d3, d4); outElem[1][1] = vtkMath::Determinant3x3( a1, a3, a4, c1, c3, c4, d1, d3, d4); outElem[2][1] = - vtkMath::Determinant3x3( a1, a3, a4, b1, b3, b4, d1, d3, d4); outElem[3][1] = vtkMath::Determinant3x3( a1, a3, a4, b1, b3, b4, c1, c3, c4); outElem[0][2] = vtkMath::Determinant3x3( b1, b2, b4, c1, c2, c4, d1, d2, d4); outElem[1][2] = - vtkMath::Determinant3x3( a1, a2, a4, c1, c2, c4, d1, d2, d4); outElem[2][2] = vtkMath::Determinant3x3( a1, a2, a4, b1, b2, b4, d1, d2, d4); outElem[3][2] = - vtkMath::Determinant3x3( a1, a2, a4, b1, b2, b4, c1, c2, c4); outElem[0][3] = - vtkMath::Determinant3x3( b1, b2, b3, c1, c2, c3, d1, d2, d3); outElem[1][3] = vtkMath::Determinant3x3( a1, a2, a3, c1, c2, c3, d1, d2, d3); outElem[2][3] = - vtkMath::Determinant3x3( a1, a2, a3, b1, b2, b3, d1, d2, d3); outElem[3][3] = vtkMath::Determinant3x3( a1, a2, a3, b1, b2, b3, c1, c2, c3); } //---------------------------------------------------------------------------- void vtkMatrix4x4::DeepCopy(double Elements[16], const double newElements[16]) { for (int i = 0; i < 16; i++) { Elements[i] = newElements[i]; } } //---------------------------------------------------------------------------- // Transpose the matrix and put it into out. void vtkMatrix4x4::Transpose(const double inElements[16], double outElements[16]) { SqMatPtr inElem = (SqMatPtr)inElements; SqMatPtr outElem = (SqMatPtr)outElements; int i, j; double temp; for (i=0; i<4; i++) { for(j=i; j<4; j++) { temp = inElem[i][j]; outElem[i][j] = inElem[j][i]; outElem[j][i] = temp; } } } //---------------------------------------------------------------------------- void vtkMatrix4x4::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os, indent); int i, j; os << indent << "Elements:\n"; for (i = 0; i < 4; i++) { os << indent << indent; for (j = 0; j < 4; j++) { os << this->Element[i][j] << " "; } os << "\n"; } } <commit_msg>BUG: singular matrix should not force a warning<commit_after>/*========================================================================= Program: Visualization Toolkit Module: vtkMatrix4x4.cxx Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ #include "vtkMatrix4x4.h" #include "vtkMath.h" #include "vtkObjectFactory.h" #include <stdlib.h> #include <math.h> vtkCxxRevisionMacro(vtkMatrix4x4, "1.62"); vtkStandardNewMacro(vtkMatrix4x4); // Useful for viewing a double[16] as a double[4][4] typedef double (*SqMatPtr)[4]; //---------------------------------------------------------------------------- void vtkMatrix4x4::Zero(double Elements[16]) { SqMatPtr elem = (SqMatPtr)Elements; int i,j; for (i = 0; i < 4; i++) { for (j = 0; j < 4; j++) { elem[i][j] = 0.0; } } } //---------------------------------------------------------------------------- void vtkMatrix4x4::Identity(double Elements[16]) { Elements[0] = Elements[5] = Elements[10] = Elements[15] = 1.0; Elements[1] = Elements[2] = Elements[3] = Elements[4] = Elements[6] = Elements[7] = Elements[8] = Elements[9] = Elements[11] = Elements[12] = Elements[13] = Elements[14] = 0.0; } //---------------------------------------------------------------------------- template<class T1, class T2, class T3> void vtkMatrixMultiplyPoint(T1 elem[16], T2 in[4], T3 out[4]) { T3 v1 = in[0]; T3 v2 = in[1]; T3 v3 = in[2]; T3 v4 = in[3]; out[0] = v1*elem[0] + v2*elem[1] + v3*elem[2] + v4*elem[3]; out[1] = v1*elem[4] + v2*elem[5] + v3*elem[6] + v4*elem[7]; out[2] = v1*elem[8] + v2*elem[9] + v3*elem[10] + v4*elem[11]; out[3] = v1*elem[12] + v2*elem[13] + v3*elem[14] + v4*elem[15]; } //---------------------------------------------------------------------------- // Multiply this matrix by a point (in homogeneous coordinates). // and return the result in result. The in[4] and result[4] // arrays must both be allocated but they can be the same array. void vtkMatrix4x4::MultiplyPoint(const double Elements[16], const float in[4], float result[4]) { vtkMatrixMultiplyPoint(Elements,in,result); } //---------------------------------------------------------------------------- void vtkMatrix4x4::MultiplyPoint(const double Elements[16], const double in[4], double result[4]) { vtkMatrixMultiplyPoint(Elements,in,result); } //---------------------------------------------------------------------------- void vtkMatrix4x4::PointMultiply(const double Elements[16], const float in[4], float result[4]) { double newElements[16]; vtkMatrix4x4::Transpose(Elements,newElements); vtkMatrix4x4::MultiplyPoint(newElements,in,result); } //---------------------------------------------------------------------------- void vtkMatrix4x4::PointMultiply(const double Elements[16], const double in[4], double result[4]) { double newElements[16]; vtkMatrix4x4::Transpose(Elements,newElements); vtkMatrix4x4::MultiplyPoint(newElements,in,result); } //---------------------------------------------------------------------------- // Multiplies matrices a and b and stores the result in c. void vtkMatrix4x4::Multiply4x4(const double a[16], const double b[16], double c[16]) { SqMatPtr aMat = (SqMatPtr) a; SqMatPtr bMat = (SqMatPtr) b; SqMatPtr cMat = (SqMatPtr) c; int i, k; double Accum[4][4]; for (i = 0; i < 4; i++) { for (k = 0; k < 4; k++) { Accum[i][k] = aMat[i][0] * bMat[0][k] + aMat[i][1] * bMat[1][k] + aMat[i][2] * bMat[2][k] + aMat[i][3] * bMat[3][k]; } } // Copy to final dest for (i = 0; i < 4; i++) { cMat[i][0] = Accum[i][0]; cMat[i][1] = Accum[i][1]; cMat[i][2] = Accum[i][2]; cMat[i][3] = Accum[i][3]; } } //---------------------------------------------------------------------------- // Matrix Inversion (adapted from Richard Carling in "Graphics Gems," // Academic Press, 1990). void vtkMatrix4x4::Invert(const double inElements[16], double outElements[16]) { SqMatPtr outElem = (SqMatPtr)outElements; // inverse( original_matrix, inverse_matrix ) // calculate the inverse of a 4x4 matrix // // -1 // A = ___1__ adjoint A // det A // int i, j; double det; // calculate the 4x4 determinent // if the determinent is zero, // then the inverse matrix is not unique. det = vtkMatrix4x4::Determinant(inElements); if ( det == 0.0 ) { return; } // calculate the adjoint matrix vtkMatrix4x4::Adjoint(inElements, outElements ); // scale the adjoint matrix to get the inverse for (i=0; i<4; i++) { for(j=0; j<4; j++) { outElem[i][j] = outElem[i][j] / det; } } } //---------------------------------------------------------------------------- double vtkMatrix4x4::Determinant(const double Elements[16]) { SqMatPtr elem = (SqMatPtr)Elements; double a1, a2, a3, a4, b1, b2, b3, b4, c1, c2, c3, c4, d1, d2, d3, d4; // assign to individual variable names to aid selecting // correct elements a1 = elem[0][0]; b1 = elem[0][1]; c1 = elem[0][2]; d1 = elem[0][3]; a2 = elem[1][0]; b2 = elem[1][1]; c2 = elem[1][2]; d2 = elem[1][3]; a3 = elem[2][0]; b3 = elem[2][1]; c3 = elem[2][2]; d3 = elem[2][3]; a4 = elem[3][0]; b4 = elem[3][1]; c4 = elem[3][2]; d4 = elem[3][3]; return a1 * vtkMath::Determinant3x3( b2, b3, b4, c2, c3, c4, d2, d3, d4) - b1 * vtkMath::Determinant3x3( a2, a3, a4, c2, c3, c4, d2, d3, d4) + c1 * vtkMath::Determinant3x3( a2, a3, a4, b2, b3, b4, d2, d3, d4) - d1 * vtkMath::Determinant3x3( a2, a3, a4, b2, b3, b4, c2, c3, c4); } //---------------------------------------------------------------------------- void vtkMatrix4x4::Adjoint(const double inElements[16], double outElements[16]) { SqMatPtr inElem = (SqMatPtr) inElements; SqMatPtr outElem = (SqMatPtr) outElements; // // adjoint( original_matrix, inverse_matrix ) // // calculate the adjoint of a 4x4 matrix // // Let a denote the minor determinant of matrix A obtained by // ij // // deleting the ith row and jth column from A. // // i+j // Let b = (-1) a // ij ji // // The matrix B = (b ) is the adjoint of A // ij // double a1, a2, a3, a4, b1, b2, b3, b4; double c1, c2, c3, c4, d1, d2, d3, d4; // assign to individual variable names to aid // selecting correct values a1 = inElem[0][0]; b1 = inElem[0][1]; c1 = inElem[0][2]; d1 = inElem[0][3]; a2 = inElem[1][0]; b2 = inElem[1][1]; c2 = inElem[1][2]; d2 = inElem[1][3]; a3 = inElem[2][0]; b3 = inElem[2][1]; c3 = inElem[2][2]; d3 = inElem[2][3]; a4 = inElem[3][0]; b4 = inElem[3][1]; c4 = inElem[3][2]; d4 = inElem[3][3]; // row column labeling reversed since we transpose rows & columns outElem[0][0] = vtkMath::Determinant3x3( b2, b3, b4, c2, c3, c4, d2, d3, d4); outElem[1][0] = - vtkMath::Determinant3x3( a2, a3, a4, c2, c3, c4, d2, d3, d4); outElem[2][0] = vtkMath::Determinant3x3( a2, a3, a4, b2, b3, b4, d2, d3, d4); outElem[3][0] = - vtkMath::Determinant3x3( a2, a3, a4, b2, b3, b4, c2, c3, c4); outElem[0][1] = - vtkMath::Determinant3x3( b1, b3, b4, c1, c3, c4, d1, d3, d4); outElem[1][1] = vtkMath::Determinant3x3( a1, a3, a4, c1, c3, c4, d1, d3, d4); outElem[2][1] = - vtkMath::Determinant3x3( a1, a3, a4, b1, b3, b4, d1, d3, d4); outElem[3][1] = vtkMath::Determinant3x3( a1, a3, a4, b1, b3, b4, c1, c3, c4); outElem[0][2] = vtkMath::Determinant3x3( b1, b2, b4, c1, c2, c4, d1, d2, d4); outElem[1][2] = - vtkMath::Determinant3x3( a1, a2, a4, c1, c2, c4, d1, d2, d4); outElem[2][2] = vtkMath::Determinant3x3( a1, a2, a4, b1, b2, b4, d1, d2, d4); outElem[3][2] = - vtkMath::Determinant3x3( a1, a2, a4, b1, b2, b4, c1, c2, c4); outElem[0][3] = - vtkMath::Determinant3x3( b1, b2, b3, c1, c2, c3, d1, d2, d3); outElem[1][3] = vtkMath::Determinant3x3( a1, a2, a3, c1, c2, c3, d1, d2, d3); outElem[2][3] = - vtkMath::Determinant3x3( a1, a2, a3, b1, b2, b3, d1, d2, d3); outElem[3][3] = vtkMath::Determinant3x3( a1, a2, a3, b1, b2, b3, c1, c2, c3); } //---------------------------------------------------------------------------- void vtkMatrix4x4::DeepCopy(double Elements[16], const double newElements[16]) { for (int i = 0; i < 16; i++) { Elements[i] = newElements[i]; } } //---------------------------------------------------------------------------- // Transpose the matrix and put it into out. void vtkMatrix4x4::Transpose(const double inElements[16], double outElements[16]) { SqMatPtr inElem = (SqMatPtr)inElements; SqMatPtr outElem = (SqMatPtr)outElements; int i, j; double temp; for (i=0; i<4; i++) { for(j=i; j<4; j++) { temp = inElem[i][j]; outElem[i][j] = inElem[j][i]; outElem[j][i] = temp; } } } //---------------------------------------------------------------------------- void vtkMatrix4x4::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os, indent); int i, j; os << indent << "Elements:\n"; for (i = 0; i < 4; i++) { os << indent << indent; for (j = 0; j < 4; j++) { os << this->Element[i][j] << " "; } os << "\n"; } } <|endoftext|>
<commit_before><commit_msg>Cleaning up code.<commit_after><|endoftext|>
<commit_before>/* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * 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. 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. * * The Original Code is [Open Source Virtual Machine.]. * * The Initial Developer of the Original Code is * Adobe System Incorporated. * Portions created by the Initial Developer are Copyright (C) 2004-2006 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Adobe AS3 Team * [email protected] * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include "MMgc.h" #include "GCDebug.h" #include "GC.h" #include <sys/mman.h> #if !defined(MAP_ANONYMOUS) && defined(MAP_ANON) #define MAP_ANONYMOUS MAP_ANON #endif // !defined(MAP_ANONYMOUS) && defined(MAP_ANON) #if defined(MEMORY_INFO) && defined(AVMPLUS_UNIX) #ifndef _GNU_SOURCE #define _GNU_SOURCE #endif #include <dlfcn.h> #endif // avmplus standalone uses UNIX #ifdef _MAC #define MAP_ANONYMOUS MAP_ANON #endif #ifdef SOLARIS #include <ucontext.h> #include <dlfcn.h> extern "C" caddr_t _getfp(void); typedef caddr_t maddr_ptr; #else typedef void *maddr_ptr; #endif namespace MMgc { #ifndef USE_MMAP void *aligned_malloc(size_t size, size_t align_size, GCMallocFuncPtr m_malloc) { char *ptr, *ptr2, *aligned_ptr; int align_mask = align_size - 1; int alloc_size = size + align_size + sizeof(int); ptr=(char *)m_malloc(alloc_size); if(ptr==NULL) return(NULL); ptr2 = ptr + sizeof(int); aligned_ptr = ptr2 + (align_size - ((size_t)ptr2 & align_mask)); ptr2 = aligned_ptr - sizeof(int); *((int *)ptr2)=(int)(aligned_ptr - ptr); return(aligned_ptr); } void aligned_free(void *ptr, GCFreeFuncPtr m_free) { int *ptr2=(int *)ptr - 1; char *unaligned_ptr = (char*) ptr - *ptr2; m_free(unaligned_ptr); } #endif /* !USE_MMAP */ #ifdef USE_MMAP int GCHeap::vmPageSize() { long v = sysconf(_SC_PAGESIZE); return v; } void* GCHeap::ReserveCodeMemory(void* address, size_t size) { return (char*) mmap((maddr_ptr)address, size, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0); } void GCHeap::ReleaseCodeMemory(void* address, size_t size) { if (munmap((maddr_ptr)address, size) != 0) GCAssert(false); } bool GCHeap::SetGuardPage(void *address) { return false; } #endif /* USE_MMAP */ #ifdef AVMPLUS_JIT_READONLY /** * SetExecuteBit changes the page access protections on a block of pages, * to make JIT-ted code executable or not. * * If executableFlag is true, the memory is made executable and read-only. * * If executableFlag is false, the memory is made non-executable and * read-write. */ void GCHeap::SetExecuteBit(void *address, size_t size, bool executableFlag) { // Should use vmPageSize() or kNativePageSize here. // But this value is hard coded to 4096 if we don't use mmap. int bitmask = sysconf(_SC_PAGESIZE) - 1; // mprotect requires that the addresses be aligned on page boundaries void *endAddress = (void*) ((char*)address + size); void *beginPage = (void*) ((size_t)address & ~bitmask); void *endPage = (void*) (((size_t)endAddress + bitmask) & ~bitmask); size_t sizePaged = (size_t)endPage - (size_t)beginPage; #ifdef DEBUG int retval = #endif mprotect((maddr_ptr)beginPage, sizePaged, executableFlag ? (PROT_READ|PROT_EXEC) : (PROT_READ|PROT_WRITE|PROT_EXEC)); GCAssert(retval == 0); } #endif /* AVMPLUS_JIT_READONLY */ #ifdef USE_MMAP void* GCHeap::CommitCodeMemory(void* address, size_t size) { void* res; if (size == 0) size = GCHeap::kNativePageSize; // default of one page #ifdef AVMPLUS_JIT_READONLY mmap((maddr_ptr)address, size, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_FIXED | MAP_ANONYMOUS, -1, 0); #else mmap((maddr_ptr)address, size, PROT_READ | PROT_WRITE | PROT_EXEC, MAP_PRIVATE | MAP_FIXED | MAP_ANONYMOUS, -1, 0); #endif /* AVMPLUS_JIT_READONLY */ res = address; if (res == address) address = (void*)( (uintptr)address + size ); else address = 0; return address; } void* GCHeap::DecommitCodeMemory(void* address, size_t size) { if (size == 0) size = GCHeap::kNativePageSize; // default of one page // release and re-reserve it ReleaseCodeMemory(address, size); address = ReserveCodeMemory(address, size); return address; } #else int GCHeap::vmPageSize() { return 4096; } void* GCHeap::ReserveCodeMemory(void* address, size_t size) { return aligned_malloc(size, 4096, m_malloc); } void GCHeap::ReleaseCodeMemory(void* address, size_t size) { aligned_free(address, m_free); } bool GCHeap::SetGuardPage(void *address) { return false; } void* GCHeap::CommitCodeMemory(void* address, size_t size) { return address; } void* GCHeap::DecommitCodeMemory(void* address, size_t size) { return address; } #endif /* USE_MMAP */ #ifdef USE_MMAP char* GCHeap::ReserveMemory(char *address, size_t size) { char *addr = (char*)mmap((maddr_ptr)address, size, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0); if (addr == MAP_FAILED) { return NULL; } if(address && address != addr) { // behave like windows and fail if we didn't get the right address ReleaseMemory(addr, size); return NULL; } return addr; } bool GCHeap::CommitMemory(char *address, size_t size) { char *addr = (char*)mmap(address, size, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_FIXED | MAP_ANONYMOUS, -1, 0); GCAssert(addr == address); return addr == address; } bool GCHeap::DecommitMemory(char *address, size_t size) { ReleaseMemory(address, size); // re-reserve it char *addr = (char*)mmap((maddr_ptr)address, size, PROT_NONE, MAP_PRIVATE | MAP_ANONYMOUS | MAP_FIXED, -1, 0); GCAssert(addr == address); return addr == address; } bool GCHeap::CommitMemoryThatMaySpanRegions(char *address, size_t size) { return CommitMemory(address, size); } bool GCHeap::DecommitMemoryThatMaySpanRegions(char *address, size_t size) { return DecommitMemory(address, size); } void GCHeap::ReleaseMemory(char *address, size_t size) { #ifdef DEBUG int result = #endif munmap((maddr_ptr)address, size); GCAssert(result == 0); } #else char* GCHeap::AllocateMemory(size_t size) { return (char *) aligned_malloc(size, 4096, m_malloc); } void GCHeap::ReleaseMemory(char *address) { aligned_free(address, m_free); } #endif #ifdef MEMORY_INFO void GetInfoFromPC(int pc, char *buff, int buffSize) { #ifdef AVMPLUS_UNIX Dl_info dlip; dladdr((void *const)pc, &dlip); sprintf(buff, "0x%08x:%s", pc, dlip.dli_sname); #else sprintf(buff, "0x%x", pc); #endif } #ifdef MMGC_SPARC void GetStackTrace(int *trace, int len, int skip) { // TODO for sparc. GCAssert(false); } #endif #ifdef MMGC_PPC void GetStackTrace(int *trace, int len, int skip) { register int stackp; int pc; asm("mr %0,r1" : "=r" (stackp)); while(skip--) { stackp = *(int*)stackp; } int i=0; // save space for 0 terminator len--; while(i<len && stackp) { pc = *((int*)stackp+2); trace[i++]=pc; stackp = *(int*)stackp; } trace[i] = 0; } #endif #ifdef MMGC_IA32 void GetStackTrace(int *trace, int len, int skip) { void **ebp; #ifdef SOLARIS ebp = (void **)_getfp(); #else asm("mov %%ebp, %0" : "=r" (ebp)); #endif while(skip-- && *ebp) { ebp = (void**)(*ebp); } /* save space for 0 terminator */ len--; int i = 0; while (i < len && *ebp) { /* store the current frame pointer */ trace[i++] = *((int*) ebp + 1); /* get the next frame pointer */ ebp = (void**)(*ebp); } trace[i] = 0; } #endif #ifdef MMGC_ARM void GetStackTrace(int *trace, int len, int skip) {} #endif #endif } <commit_msg>Bug 415326 The mmap option in mprotect is set wrong in GCHeapUnix.cpp. treilly: review+<commit_after>/* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * 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. 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. * * The Original Code is [Open Source Virtual Machine.]. * * The Initial Developer of the Original Code is * Adobe System Incorporated. * Portions created by the Initial Developer are Copyright (C) 2004-2006 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Adobe AS3 Team * [email protected] * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include "MMgc.h" #include "GCDebug.h" #include "GC.h" #include <sys/mman.h> #if !defined(MAP_ANONYMOUS) && defined(MAP_ANON) #define MAP_ANONYMOUS MAP_ANON #endif // !defined(MAP_ANONYMOUS) && defined(MAP_ANON) #if defined(MEMORY_INFO) && defined(AVMPLUS_UNIX) #ifndef _GNU_SOURCE #define _GNU_SOURCE #endif #include <dlfcn.h> #endif // avmplus standalone uses UNIX #ifdef _MAC #define MAP_ANONYMOUS MAP_ANON #endif #ifdef SOLARIS #include <ucontext.h> #include <dlfcn.h> extern "C" caddr_t _getfp(void); typedef caddr_t maddr_ptr; #else typedef void *maddr_ptr; #endif namespace MMgc { #ifndef USE_MMAP void *aligned_malloc(size_t size, size_t align_size, GCMallocFuncPtr m_malloc) { char *ptr, *ptr2, *aligned_ptr; int align_mask = align_size - 1; int alloc_size = size + align_size + sizeof(int); ptr=(char *)m_malloc(alloc_size); if(ptr==NULL) return(NULL); ptr2 = ptr + sizeof(int); aligned_ptr = ptr2 + (align_size - ((size_t)ptr2 & align_mask)); ptr2 = aligned_ptr - sizeof(int); *((int *)ptr2)=(int)(aligned_ptr - ptr); return(aligned_ptr); } void aligned_free(void *ptr, GCFreeFuncPtr m_free) { int *ptr2=(int *)ptr - 1; char *unaligned_ptr = (char*) ptr - *ptr2; m_free(unaligned_ptr); } #endif /* !USE_MMAP */ #ifdef USE_MMAP int GCHeap::vmPageSize() { long v = sysconf(_SC_PAGESIZE); return v; } void* GCHeap::ReserveCodeMemory(void* address, size_t size) { return (char*) mmap((maddr_ptr)address, size, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0); } void GCHeap::ReleaseCodeMemory(void* address, size_t size) { if (munmap((maddr_ptr)address, size) != 0) GCAssert(false); } bool GCHeap::SetGuardPage(void *address) { return false; } #endif /* USE_MMAP */ #ifdef AVMPLUS_JIT_READONLY /** * SetExecuteBit changes the page access protections on a block of pages, * to make JIT-ted code executable or not. * * If executableFlag is true, the memory is made executable and read-only. * * If executableFlag is false, the memory is made non-executable and * read-write. */ void GCHeap::SetExecuteBit(void *address, size_t size, bool executableFlag) { // Should use vmPageSize() or kNativePageSize here. // But this value is hard coded to 4096 if we don't use mmap. int bitmask = sysconf(_SC_PAGESIZE) - 1; // mprotect requires that the addresses be aligned on page boundaries void *endAddress = (void*) ((char*)address + size); void *beginPage = (void*) ((size_t)address & ~bitmask); void *endPage = (void*) (((size_t)endAddress + bitmask) & ~bitmask); size_t sizePaged = (size_t)endPage - (size_t)beginPage; #ifdef DEBUG int retval = #endif mprotect((maddr_ptr)beginPage, sizePaged, executableFlag ? (PROT_READ|PROT_WRITE|PROT_EXEC) : (PROT_READ|PROT_WRITE)); GCAssert(retval == 0); } #endif /* AVMPLUS_JIT_READONLY */ #ifdef USE_MMAP void* GCHeap::CommitCodeMemory(void* address, size_t size) { void* res; if (size == 0) size = GCHeap::kNativePageSize; // default of one page #ifdef AVMPLUS_JIT_READONLY mmap((maddr_ptr)address, size, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_FIXED | MAP_ANONYMOUS, -1, 0); #else mmap((maddr_ptr)address, size, PROT_READ | PROT_WRITE | PROT_EXEC, MAP_PRIVATE | MAP_FIXED | MAP_ANONYMOUS, -1, 0); #endif /* AVMPLUS_JIT_READONLY */ res = address; if (res == address) address = (void*)( (uintptr)address + size ); else address = 0; return address; } void* GCHeap::DecommitCodeMemory(void* address, size_t size) { if (size == 0) size = GCHeap::kNativePageSize; // default of one page // release and re-reserve it ReleaseCodeMemory(address, size); address = ReserveCodeMemory(address, size); return address; } #else int GCHeap::vmPageSize() { return 4096; } void* GCHeap::ReserveCodeMemory(void* address, size_t size) { return aligned_malloc(size, 4096, m_malloc); } void GCHeap::ReleaseCodeMemory(void* address, size_t size) { aligned_free(address, m_free); } bool GCHeap::SetGuardPage(void *address) { return false; } void* GCHeap::CommitCodeMemory(void* address, size_t size) { return address; } void* GCHeap::DecommitCodeMemory(void* address, size_t size) { return address; } #endif /* USE_MMAP */ #ifdef USE_MMAP char* GCHeap::ReserveMemory(char *address, size_t size) { char *addr = (char*)mmap((maddr_ptr)address, size, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0); if (addr == MAP_FAILED) { return NULL; } if(address && address != addr) { // behave like windows and fail if we didn't get the right address ReleaseMemory(addr, size); return NULL; } return addr; } bool GCHeap::CommitMemory(char *address, size_t size) { char *addr = (char*)mmap(address, size, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_FIXED | MAP_ANONYMOUS, -1, 0); GCAssert(addr == address); return addr == address; } bool GCHeap::DecommitMemory(char *address, size_t size) { ReleaseMemory(address, size); // re-reserve it char *addr = (char*)mmap((maddr_ptr)address, size, PROT_NONE, MAP_PRIVATE | MAP_ANONYMOUS | MAP_FIXED, -1, 0); GCAssert(addr == address); return addr == address; } bool GCHeap::CommitMemoryThatMaySpanRegions(char *address, size_t size) { return CommitMemory(address, size); } bool GCHeap::DecommitMemoryThatMaySpanRegions(char *address, size_t size) { return DecommitMemory(address, size); } void GCHeap::ReleaseMemory(char *address, size_t size) { #ifdef DEBUG int result = #endif munmap((maddr_ptr)address, size); GCAssert(result == 0); } #else char* GCHeap::AllocateMemory(size_t size) { return (char *) aligned_malloc(size, 4096, m_malloc); } void GCHeap::ReleaseMemory(char *address) { aligned_free(address, m_free); } #endif #ifdef MEMORY_INFO void GetInfoFromPC(int pc, char *buff, int buffSize) { #ifdef AVMPLUS_UNIX Dl_info dlip; dladdr((void *const)pc, &dlip); sprintf(buff, "0x%08x:%s", pc, dlip.dli_sname); #else sprintf(buff, "0x%x", pc); #endif } #ifdef MMGC_SPARC void GetStackTrace(int *trace, int len, int skip) { // TODO for sparc. GCAssert(false); } #endif #ifdef MMGC_PPC void GetStackTrace(int *trace, int len, int skip) { register int stackp; int pc; asm("mr %0,r1" : "=r" (stackp)); while(skip--) { stackp = *(int*)stackp; } int i=0; // save space for 0 terminator len--; while(i<len && stackp) { pc = *((int*)stackp+2); trace[i++]=pc; stackp = *(int*)stackp; } trace[i] = 0; } #endif #ifdef MMGC_IA32 void GetStackTrace(int *trace, int len, int skip) { void **ebp; #ifdef SOLARIS ebp = (void **)_getfp(); #else asm("mov %%ebp, %0" : "=r" (ebp)); #endif while(skip-- && *ebp) { ebp = (void**)(*ebp); } /* save space for 0 terminator */ len--; int i = 0; while (i < len && *ebp) { /* store the current frame pointer */ trace[i++] = *((int*) ebp + 1); /* get the next frame pointer */ ebp = (void**)(*ebp); } trace[i] = 0; } #endif #ifdef MMGC_ARM void GetStackTrace(int *trace, int len, int skip) {} #endif #endif } <|endoftext|>
<commit_before>/* * Copyright 2014 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. */ #include <algorithm> #include <stdexcept> #include <tightdb/util/assert.hpp> #include <tightdb/util/utf8.hpp> #include <tightdb/util/buffer.hpp> #include "util.hpp" #include "io_realm_internal_Util.h" using namespace std; using namespace tightdb; using namespace tightdb::util; void ThrowException(JNIEnv* env, ExceptionKind exception, std::string classStr, std::string itemStr) { std::string message; jclass jExceptionClass = NULL; TR_ERR((env, "\njni: ThrowingException %d, %s, %s.\n", exception, classStr.c_str(), itemStr.c_str())); switch (exception) { case ClassNotFound: jExceptionClass = env->FindClass("java/lang/ClassNotFoundException"); message = "Class '" + classStr + "' could not be located."; break; case NoSuchField: jExceptionClass = env->FindClass("java/lang/NoSuchFieldException"); message = "Field '" + itemStr + "' could not be located in class io.realm." + classStr; break; case NoSuchMethod: jExceptionClass = env->FindClass("java/lang/NoSuchMethodException"); message = "Method '" + itemStr + "' could not be located in class io.realm." + classStr; break; case IllegalArgument: jExceptionClass = env->FindClass("java/lang/IllegalArgumentException"); message = "Illegal Argument: " + classStr; break; case TableInvalid: jExceptionClass = env->FindClass("java/lang/IllegalStateException"); message = "Illegal State: " + classStr; break; case IOFailed: jExceptionClass = env->FindClass("io/realm/exceptions/RealmIOException"); message = "Failed to open " + classStr + ". " + itemStr; break; case FileNotFound: jExceptionClass = env->FindClass("io/realm/exceptions/RealmIOException"); message = "File not found: " + classStr + "."; break; case FileAccessError: jExceptionClass = env->FindClass("io/realm/exceptions/RealmIOException"); message = "Failed to access: " + classStr + ". " + itemStr; break; case IndexOutOfBounds: jExceptionClass = env->FindClass("java/lang/ArrayIndexOutOfBoundsException"); message = classStr; break; case UnsupportedOperation: jExceptionClass = env->FindClass("java/lang/UnsupportedOperationException"); message = classStr; break; case OutOfMemory: jExceptionClass = env->FindClass("io/realm/internal/OutOfMemoryError"); message = classStr + " " + itemStr; break; case Unspecified: jExceptionClass = env->FindClass("java/lang/RuntimeException"); message = "Unspecified exception. " + classStr; break; case RuntimeError: jExceptionClass = env->FindClass("java/lang/RuntimeException"); message = classStr; break; case RowInvalid: jExceptionClass = env->FindClass("java/lang/IllegalStateException"); message = "Illegal State: " + classStr; break; } if (jExceptionClass != NULL) env->ThrowNew(jExceptionClass, message.c_str()); else { TR_ERR((env, "\nERROR: Couldn't throw exception.\n")); } env->DeleteLocalRef(jExceptionClass); } jclass GetClass(JNIEnv* env, const char* classStr) { jclass localRefClass = env->FindClass(classStr); if (localRefClass == NULL) { ThrowException(env, ClassNotFound, classStr); return NULL; } jclass myClass = reinterpret_cast<jclass>( env->NewGlobalRef(localRefClass) ); env->DeleteLocalRef(localRefClass); return myClass; } void jprint(JNIEnv *env, char *txt) { #if 1 static_cast<void>(env); fprintf(stderr, " -- JNI: %s", txt); fflush(stderr); #else static jclass myClass = GetClass(env, "io/realm/internal/Util"); static jmethodID myMethod = env->GetStaticMethodID(myClass, "javaPrint", "(Ljava/lang/String;)V"); if (myMethod) env->CallStaticVoidMethod(myClass, myMethod, to_jstring(env, txt)); else ThrowException(env, NoSuchMethod, "Util", "javaPrint"); #endif } void jprintf(JNIEnv *env, const char *format, ...) { va_list argptr; char buf[200]; va_start(argptr, format); //vfprintf(stderr, format, argptr); vsnprintf(buf, 200, format, argptr); jprint(env, buf); va_end(argptr); } bool GetBinaryData(JNIEnv* env, jobject jByteBuffer, tightdb::BinaryData& bin) { const char* data = static_cast<char*>(env->GetDirectBufferAddress(jByteBuffer)); if (!data) { ThrowException(env, IllegalArgument, "ByteBuffer is invalid"); return false; } jlong size = env->GetDirectBufferCapacity(jByteBuffer); if (size < 0) { ThrowException(env, IllegalArgument, "Can't get BufferCapacity."); return false; } bin = BinaryData(data, S(size)); return true; } //********************************************************************* // String handling //********************************************************************* namespace { // This assumes that 'jchar' is an integral type with at least 16 // non-sign value bits, that is, an unsigned 16-bit integer, or any // signed or unsigned integer with more than 16 bits. struct JcharTraits { static jchar to_int_type(jchar c) TIGHTDB_NOEXCEPT { return c; } static jchar to_char_type(jchar i) TIGHTDB_NOEXCEPT { return i; } }; struct JStringCharsAccessor { JStringCharsAccessor(JNIEnv* e, jstring s): m_env(e), m_string(s), m_data(e->GetStringChars(s,0)), m_size(get_size(e,s)) {} ~JStringCharsAccessor() { m_env->ReleaseStringChars(m_string, m_data); } const jchar* data() const TIGHTDB_NOEXCEPT { return m_data; } size_t size() const TIGHTDB_NOEXCEPT { return m_size; } private: JNIEnv* const m_env; const jstring m_string; const jchar* const m_data; const size_t m_size; static size_t get_size(JNIEnv* e, jstring s) { size_t size; if (int_cast_with_overflow_detect(e->GetStringLength(s), size)) throw runtime_error("String size overflow"); return size; } }; } // anonymous namespace string string_to_hex(const string& message, StringData& str) { ostringstream ret; const char *s = str.data(); ret << message; for (string::size_type i = 0; i < str.size(); ++i) ret << " 0x" << std::hex << std::setfill('0') << std::setw(2) << (int)s[i]; return ret.str(); } string string_to_hex(const string& message, const jchar *str, size_t size) { ostringstream ret; ret << message; for (size_t i = 0; i < size; ++i) ret << " 0x" << std::hex << std::setfill('0') << std::setw(2) << (int)str[i]; return ret.str(); } jstring to_jstring(JNIEnv* env, StringData str) { // Input is UTF-8 and output is UTF-16. Invalid UTF-8 input is // silently converted to Unicode replacement characters. // We use a small fixed size stack-allocated output buffer to avoid the cost // of dynamic allocation for short input strings. If this buffer turns out // to be too small, we proceed by calulating an estimate for the actual // required output buffer size, and then allocate the buffer dynamically. const size_t stack_buf_size = 48; jchar stack_buf[stack_buf_size]; Buffer<jchar> dyn_buf; const char* in = str.data(); const char* in_end = in + str.size(); jchar* out = stack_buf; jchar* out_begin = out; jchar* out_end = out_begin + stack_buf_size; for (;;) { typedef Utf8x16<jchar, JcharTraits> Xcode; Xcode::to_utf16(in, in_end, out, out_end); bool end_of_input = in == in_end; if (end_of_input) break; bool bad_input = out != out_end; if (bad_input) { // Discard one or more invalid bytes from the input. We shall follow // the stardard way of doing this, namely by first discarding the // leading invalid byte, which must either be a sequence lead byte // (11xxxxxx) or a stray continuation byte (10xxxxxx), and then // discard any additional continuation bytes following leading // invalid byte. for (;;) { ++in; end_of_input = in == in_end; if (end_of_input) break; bool next_byte_is_continuation = unsigned(*in) & 0xC0 == 0x80; if (!next_byte_is_continuation) break; } } size_t used_size = out - out_begin; // What we already have size_t min_capacity = used_size; min_cpacity += 1; // Make space for a replacement character size_t in_2 = in; // Avoid clobbering `in` if (int_add_with_overflow_detect(min_capacity, Xcode::find_utf16_buf_size(in_2, in_end))) throw runtime_error("Buffer size overflow"); bool copy_stack_buf = dyn_buf.size() == 0; size_t used_dyn_buf_size = copy_stack_buf ? 0 : used_size; dyn_buf.reserve(used_dyn_buf_size, min_capacity); out_begin = dyn_buf.data(); out_end = dyn_buf.data() + dyn_buf.size(); out = out_begin + used_size; if (copy_stack_buf) copy(stack_buf, stack_buf_out_end, out_begin); if (bad_input) *out++ = JcharTraits::to_char_type(0xFFFD); // Unicode replacement character } jsize out_size; if (int_cast_with_overflow_detect(out - out_begin, out_size)) throw runtime_error("String size overflow"); return env->NewString(out_begin, out_size); } JStringAccessor::JStringAccessor(JNIEnv* env, jstring str) { // For efficiency, if the incoming UTF-16 string is sufficiently // small, we will choose an UTF-8 output buffer whose size (in // bytes) is simply 4 times the number of 16-bit elements in the // input. This is guaranteed to be enough. However, to avoid // excessive over allocation, this is not done for larger input // strings. JStringCharsAccessor chars(env, str); typedef Utf8x16<jchar, JcharTraits> Xcode; size_t max_project_size = 48; TIGHTDB_ASSERT(max_project_size <= numeric_limits<size_t>::max()/4); size_t buf_size; if (chars.size() <= max_project_size) { buf_size = chars.size() * 4; } else { const jchar* begin = chars.data(); const jchar* end = begin + chars.size(); buf_size = Xcode::find_utf8_buf_size(begin, end); } m_data.reset(new char[buf_size]); // throws { const jchar* in_begin = chars.data(); const jchar* in_end = in_begin + chars.size(); char* out_begin = m_data.get(); char* out_end = m_data.get() + buf_size; if (!Xcode::to_utf8(in_begin, in_end, out_begin, out_end)) { throw runtime_error(string_to_hex("Failure when converting to UTF-8", chars.data(), chars.size())); } TIGHTDB_ASSERT(in_begin == in_end); m_size = out_begin - m_data.get(); } } <commit_msg>Fix for: Lenient UTF-8 -> UTF-16 transcoding (insert replacement characters)<commit_after>/* * Copyright 2014 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. */ #include <algorithm> #include <stdexcept> #include <tightdb/util/assert.hpp> #include <tightdb/util/utf8.hpp> #include <tightdb/util/buffer.hpp> #include "util.hpp" #include "io_realm_internal_Util.h" using namespace std; using namespace tightdb; using namespace tightdb::util; void ThrowException(JNIEnv* env, ExceptionKind exception, std::string classStr, std::string itemStr) { std::string message; jclass jExceptionClass = NULL; TR_ERR((env, "\njni: ThrowingException %d, %s, %s.\n", exception, classStr.c_str(), itemStr.c_str())); switch (exception) { case ClassNotFound: jExceptionClass = env->FindClass("java/lang/ClassNotFoundException"); message = "Class '" + classStr + "' could not be located."; break; case NoSuchField: jExceptionClass = env->FindClass("java/lang/NoSuchFieldException"); message = "Field '" + itemStr + "' could not be located in class io.realm." + classStr; break; case NoSuchMethod: jExceptionClass = env->FindClass("java/lang/NoSuchMethodException"); message = "Method '" + itemStr + "' could not be located in class io.realm." + classStr; break; case IllegalArgument: jExceptionClass = env->FindClass("java/lang/IllegalArgumentException"); message = "Illegal Argument: " + classStr; break; case TableInvalid: jExceptionClass = env->FindClass("java/lang/IllegalStateException"); message = "Illegal State: " + classStr; break; case IOFailed: jExceptionClass = env->FindClass("io/realm/exceptions/RealmIOException"); message = "Failed to open " + classStr + ". " + itemStr; break; case FileNotFound: jExceptionClass = env->FindClass("io/realm/exceptions/RealmIOException"); message = "File not found: " + classStr + "."; break; case FileAccessError: jExceptionClass = env->FindClass("io/realm/exceptions/RealmIOException"); message = "Failed to access: " + classStr + ". " + itemStr; break; case IndexOutOfBounds: jExceptionClass = env->FindClass("java/lang/ArrayIndexOutOfBoundsException"); message = classStr; break; case UnsupportedOperation: jExceptionClass = env->FindClass("java/lang/UnsupportedOperationException"); message = classStr; break; case OutOfMemory: jExceptionClass = env->FindClass("io/realm/internal/OutOfMemoryError"); message = classStr + " " + itemStr; break; case Unspecified: jExceptionClass = env->FindClass("java/lang/RuntimeException"); message = "Unspecified exception. " + classStr; break; case RuntimeError: jExceptionClass = env->FindClass("java/lang/RuntimeException"); message = classStr; break; case RowInvalid: jExceptionClass = env->FindClass("java/lang/IllegalStateException"); message = "Illegal State: " + classStr; break; } if (jExceptionClass != NULL) env->ThrowNew(jExceptionClass, message.c_str()); else { TR_ERR((env, "\nERROR: Couldn't throw exception.\n")); } env->DeleteLocalRef(jExceptionClass); } jclass GetClass(JNIEnv* env, const char* classStr) { jclass localRefClass = env->FindClass(classStr); if (localRefClass == NULL) { ThrowException(env, ClassNotFound, classStr); return NULL; } jclass myClass = reinterpret_cast<jclass>( env->NewGlobalRef(localRefClass) ); env->DeleteLocalRef(localRefClass); return myClass; } void jprint(JNIEnv *env, char *txt) { #if 1 static_cast<void>(env); fprintf(stderr, " -- JNI: %s", txt); fflush(stderr); #else static jclass myClass = GetClass(env, "io/realm/internal/Util"); static jmethodID myMethod = env->GetStaticMethodID(myClass, "javaPrint", "(Ljava/lang/String;)V"); if (myMethod) env->CallStaticVoidMethod(myClass, myMethod, to_jstring(env, txt)); else ThrowException(env, NoSuchMethod, "Util", "javaPrint"); #endif } void jprintf(JNIEnv *env, const char *format, ...) { va_list argptr; char buf[200]; va_start(argptr, format); //vfprintf(stderr, format, argptr); vsnprintf(buf, 200, format, argptr); jprint(env, buf); va_end(argptr); } bool GetBinaryData(JNIEnv* env, jobject jByteBuffer, tightdb::BinaryData& bin) { const char* data = static_cast<char*>(env->GetDirectBufferAddress(jByteBuffer)); if (!data) { ThrowException(env, IllegalArgument, "ByteBuffer is invalid"); return false; } jlong size = env->GetDirectBufferCapacity(jByteBuffer); if (size < 0) { ThrowException(env, IllegalArgument, "Can't get BufferCapacity."); return false; } bin = BinaryData(data, S(size)); return true; } //********************************************************************* // String handling //********************************************************************* namespace { // This assumes that 'jchar' is an integral type with at least 16 // non-sign value bits, that is, an unsigned 16-bit integer, or any // signed or unsigned integer with more than 16 bits. struct JcharTraits { static jchar to_int_type(jchar c) TIGHTDB_NOEXCEPT { return c; } static jchar to_char_type(jchar i) TIGHTDB_NOEXCEPT { return i; } }; struct JStringCharsAccessor { JStringCharsAccessor(JNIEnv* e, jstring s): m_env(e), m_string(s), m_data(e->GetStringChars(s,0)), m_size(get_size(e,s)) {} ~JStringCharsAccessor() { m_env->ReleaseStringChars(m_string, m_data); } const jchar* data() const TIGHTDB_NOEXCEPT { return m_data; } size_t size() const TIGHTDB_NOEXCEPT { return m_size; } private: JNIEnv* const m_env; const jstring m_string; const jchar* const m_data; const size_t m_size; static size_t get_size(JNIEnv* e, jstring s) { size_t size; if (int_cast_with_overflow_detect(e->GetStringLength(s), size)) throw runtime_error("String size overflow"); return size; } }; } // anonymous namespace string string_to_hex(const string& message, StringData& str) { ostringstream ret; const char *s = str.data(); ret << message; for (string::size_type i = 0; i < str.size(); ++i) ret << " 0x" << std::hex << std::setfill('0') << std::setw(2) << (int)s[i]; return ret.str(); } string string_to_hex(const string& message, const jchar *str, size_t size) { ostringstream ret; ret << message; for (size_t i = 0; i < size; ++i) ret << " 0x" << std::hex << std::setfill('0') << std::setw(2) << (int)str[i]; return ret.str(); } jstring to_jstring(JNIEnv* env, StringData str) { // Input is UTF-8 and output is UTF-16. Invalid UTF-8 input is // silently converted to Unicode replacement characters. // We use a small fixed size stack-allocated output buffer to avoid the cost // of dynamic allocation for short input strings. If this buffer turns out // to be too small, we proceed by calulating an estimate for the actual // required output buffer size, and then allocate the buffer dynamically. const size_t stack_buf_size = 48; jchar stack_buf[stack_buf_size]; Buffer<jchar> dyn_buf; const char* in = str.data(); const char* in_end = in + str.size(); jchar* out = stack_buf; jchar* out_begin = out; jchar* out_end = out_begin + stack_buf_size; for (;;) { typedef Utf8x16<jchar, JcharTraits> Xcode; Xcode::to_utf16(in, in_end, out, out_end); bool end_of_input = in == in_end; if (end_of_input) break; bool bad_input = out != out_end; if (bad_input) { // Discard one or more invalid bytes from the input. We shall follow // the stardard way of doing this, namely by first discarding the // leading invalid byte, which must either be a sequence lead byte // (11xxxxxx) or a stray continuation byte (10xxxxxx), and then // discard any additional continuation bytes following leading // invalid byte. for (;;) { ++in; end_of_input = in == in_end; if (end_of_input) break; bool next_byte_is_continuation = unsigned(*in) & 0xC0 == 0x80; if (!next_byte_is_continuation) break; } } size_t used_size = out - out_begin; // What we already have size_t min_capacity = used_size; min_cpacity += 1; // Make space for a replacement character size_t in_2 = in; // Avoid clobbering `in` if (int_add_with_overflow_detect(min_capacity, Xcode::find_utf16_buf_size(in_2, in_end))) throw runtime_error("Buffer size overflow"); bool copy_stack_buf = dyn_buf.size() == 0; size_t used_dyn_buf_size = copy_stack_buf ? 0 : used_size; dyn_buf.reserve(used_dyn_buf_size, min_capacity); if (copy_stack_buf) copy(out_begin, out, dyn_buf.data()); out_begin = dyn_buf.data(); out_end = dyn_buf.data() + dyn_buf.size(); out = out_begin + used_size; if (bad_input) *out++ = JcharTraits::to_char_type(0xFFFD); // Unicode replacement character } jsize out_size; if (int_cast_with_overflow_detect(out - out_begin, out_size)) throw runtime_error("String size overflow"); return env->NewString(out_begin, out_size); } JStringAccessor::JStringAccessor(JNIEnv* env, jstring str) { // For efficiency, if the incoming UTF-16 string is sufficiently // small, we will choose an UTF-8 output buffer whose size (in // bytes) is simply 4 times the number of 16-bit elements in the // input. This is guaranteed to be enough. However, to avoid // excessive over allocation, this is not done for larger input // strings. JStringCharsAccessor chars(env, str); typedef Utf8x16<jchar, JcharTraits> Xcode; size_t max_project_size = 48; TIGHTDB_ASSERT(max_project_size <= numeric_limits<size_t>::max()/4); size_t buf_size; if (chars.size() <= max_project_size) { buf_size = chars.size() * 4; } else { const jchar* begin = chars.data(); const jchar* end = begin + chars.size(); buf_size = Xcode::find_utf8_buf_size(begin, end); } m_data.reset(new char[buf_size]); // throws { const jchar* in_begin = chars.data(); const jchar* in_end = in_begin + chars.size(); char* out_begin = m_data.get(); char* out_end = m_data.get() + buf_size; if (!Xcode::to_utf8(in_begin, in_end, out_begin, out_end)) { throw runtime_error(string_to_hex("Failure when converting to UTF-8", chars.data(), chars.size())); } TIGHTDB_ASSERT(in_begin == in_end); m_size = out_begin - m_data.get(); } } <|endoftext|>
<commit_before><commit_msg>Fix trivial bug introduced in #683<commit_after><|endoftext|>
<commit_before>#include "SDBPShardConnection.h" #include "SDBPClient.h" #include "Application/Common/ClientResponse.h" #include "Application/SDBP/SDBPRequestMessage.h" #include "Application/SDBP/SDBPResponseMessage.h" #define CONN_BUFSIZE 4096 #define CLIENT_MUTEX_GUARD_DECLARE() MutexGuard mutexGuard(client->mutex) #define CLIENT_MUTEX_LOCK() mutexGuard.Lock() #define CLIENT_MUTEX_UNLOCK() mutexGuard.Unlock() using namespace SDBPClient; static bool LessThan(uint64_t a, uint64_t b) { return a < b; } ShardConnection::ShardConnection(Client* client_, uint64_t nodeID_, Endpoint& endpoint_) { client = client_; nodeID = nodeID_; endpoint = endpoint_; autoFlush = false; isBulkSent = false; Connect(); } void ShardConnection::Connect() { // Log_Debug("Connecting to %s", endpoint.ToString()); MessageConnection::Connect(endpoint); } bool ShardConnection::SendRequest(Request* request) { SDBPRequestMessage msg; if (!request->isBulk) { sentRequests.Append(request); request->numTry++; request->requestTime = EventLoop::Now(); } msg.request = request; Write(msg); // if (request->numTry > 1) // Log_Debug("Resending, commandID: %U, conn: %s", request->commandID, endpoint.ToString()); //Log_Debug("Sending conn: %s, writeBuffer = %B", endpoint.ToString(), writeBuffer); // buffer is saturated if (writeBuffer->GetLength() >= MESSAGING_BUFFER_THRESHOLD) return false; return true; } void ShardConnection::SendSubmit(uint64_t /*quorumID*/) { Flush(); } void ShardConnection::Flush() { FlushWriteBuffer(); } uint64_t ShardConnection::GetNodeID() { return nodeID; } Endpoint& ShardConnection::GetEndpoint() { return endpoint; } bool ShardConnection::IsWritePending() { return tcpwrite.active; } void ShardConnection::SetQuorumMembership(uint64_t quorumID) { // SortedList takes care of unique IDs quorums.Add(quorumID, true); } void ShardConnection::ClearQuorumMembership(uint64_t quorumID) { quorums.Remove(quorumID); } void ShardConnection::ClearQuorumMemberships() { quorums.Clear(); } SortedList<uint64_t>& ShardConnection::GetQuorumList() { return quorums; } bool ShardConnection::OnMessage(ReadBuffer& rbuf) { SDBPResponseMessage msg; Request* it; uint64_t quorumID; CLIENT_MUTEX_GUARD_DECLARE(); //Log_Debug("Shard conn: %s, message: %R", endpoint.ToString(), &rbuf); response.Init(); msg.response = &response; if (!msg.Read(rbuf)) return false; // find the request in sent requests by commandID FOREACH (it, sentRequests) { if (it->commandID == response.commandID) { // TODO: what to do when the first in the queue returns NOSERVICE // but the others return OK ?!? // invalidate quorum state on NOSERVICE response if (response.type == CLIENTRESPONSE_NOSERVICE) { quorumID = it->quorumID; InvalidateQuorum(quorumID); return false; } sentRequests.Remove(it); break; } } client->result->AppendRequestResponse(&response); response.Init(); return false; } void ShardConnection::OnWrite() { CLIENT_MUTEX_GUARD_DECLARE(); MessageConnection::OnWrite(); if (client->IsBulkLoading() && !isBulkSent) isBulkSent = true; SendQuorumRequests(); } void ShardConnection::OnConnect() { Log_Trace(); //Log_Debug("Shard connection connected, endpoint: %s", endpoint.ToString()); CLIENT_MUTEX_GUARD_DECLARE(); MessageConnection::OnConnect(); if (client->IsBulkLoading() && !isBulkSent) { SendBulkLoadingRequest(); return; } SendQuorumRequests(); } void ShardConnection::OnClose() { // Log_Debug("Shard connection closing: %s", endpoint.ToString()); Request* it; Request* prev; uint64_t* itQuorum; uint64_t* itNext; CLIENT_MUTEX_GUARD_DECLARE(); isBulkSent = false; // close the socket and try reconnecting MessageConnection::OnClose(); // restart reconnection with timeout EventLoop::Reset(&connectTimeout); // invalidate quorums for (itQuorum = quorums.First(); itQuorum != NULL; itQuorum = itNext) { itNext = quorums.Next(itQuorum); InvalidateQuorum(*itQuorum); } // put back requests that have no response to the client's quorum queue for (it = sentRequests.Last(); it != NULL; it = prev) { prev = sentRequests.Prev(it); sentRequests.Remove(it); client->AddRequestToQuorum(it, false); } } void ShardConnection::InvalidateQuorum(uint64_t quorumID) { Request* it; Request* prev; for (it = sentRequests.Last(); it != NULL; it = prev) { prev = sentRequests.Prev(it); if (it->quorumID == quorumID) { sentRequests.Remove(it); client->AddRequestToQuorum(it, false); } } client->InvalidateQuorum(quorumID, nodeID); } void ShardConnection::SendQuorumRequests() { uint64_t* qit; // notify the client so that it can assign the requests to the connection FOREACH (qit, quorums) client->SendQuorumRequest(this, *qit); } void ShardConnection::SendBulkLoadingRequest() { Request req; req.BulkLoading(0); req.isBulk = true; SendRequest(&req); Flush(); } <commit_msg>Fixed NOSERVICE handling in client.<commit_after>#include "SDBPShardConnection.h" #include "SDBPClient.h" #include "Application/Common/ClientResponse.h" #include "Application/SDBP/SDBPRequestMessage.h" #include "Application/SDBP/SDBPResponseMessage.h" #define CONN_BUFSIZE 4096 #define CLIENT_MUTEX_GUARD_DECLARE() MutexGuard mutexGuard(client->mutex) #define CLIENT_MUTEX_LOCK() mutexGuard.Lock() #define CLIENT_MUTEX_UNLOCK() mutexGuard.Unlock() using namespace SDBPClient; static bool LessThan(uint64_t a, uint64_t b) { return a < b; } ShardConnection::ShardConnection(Client* client_, uint64_t nodeID_, Endpoint& endpoint_) { client = client_; nodeID = nodeID_; endpoint = endpoint_; autoFlush = false; isBulkSent = false; Connect(); } void ShardConnection::Connect() { // Log_Debug("Connecting to %s", endpoint.ToString()); MessageConnection::Connect(endpoint); } bool ShardConnection::SendRequest(Request* request) { SDBPRequestMessage msg; if (!request->isBulk) { sentRequests.Append(request); request->numTry++; request->requestTime = EventLoop::Now(); } msg.request = request; Write(msg); // if (request->numTry > 1) // Log_Debug("Resending, commandID: %U, conn: %s", request->commandID, endpoint.ToString()); //Log_Debug("Sending conn: %s, writeBuffer = %B", endpoint.ToString(), writeBuffer); // buffer is saturated if (writeBuffer->GetLength() >= MESSAGING_BUFFER_THRESHOLD) return false; return true; } void ShardConnection::SendSubmit(uint64_t /*quorumID*/) { Flush(); } void ShardConnection::Flush() { FlushWriteBuffer(); } uint64_t ShardConnection::GetNodeID() { return nodeID; } Endpoint& ShardConnection::GetEndpoint() { return endpoint; } bool ShardConnection::IsWritePending() { return tcpwrite.active; } void ShardConnection::SetQuorumMembership(uint64_t quorumID) { // SortedList takes care of unique IDs quorums.Add(quorumID, true); } void ShardConnection::ClearQuorumMembership(uint64_t quorumID) { quorums.Remove(quorumID); } void ShardConnection::ClearQuorumMemberships() { quorums.Clear(); } SortedList<uint64_t>& ShardConnection::GetQuorumList() { return quorums; } bool ShardConnection::OnMessage(ReadBuffer& rbuf) { SDBPResponseMessage msg; Request* request; CLIENT_MUTEX_GUARD_DECLARE(); //Log_Debug("Shard conn: %s, message: %R", endpoint.ToString(), &rbuf); response.Init(); msg.response = &response; if (!msg.Read(rbuf)) return false; // find the request in sent requests by commandID FOREACH (request, sentRequests) { if (request->commandID == response.commandID) { // put back the request to the quorum queue and // invalidate quorum state on NOSERVICE response if (response.type == CLIENTRESPONSE_NOSERVICE) { sentRequests.Remove(request); client->AddRequestToQuorum(request, false); client->InvalidateQuorum(request->quorumID, nodeID); return false; } sentRequests.Remove(request); break; } } client->result->AppendRequestResponse(&response); response.Init(); return false; } void ShardConnection::OnWrite() { CLIENT_MUTEX_GUARD_DECLARE(); MessageConnection::OnWrite(); if (client->IsBulkLoading() && !isBulkSent) isBulkSent = true; SendQuorumRequests(); } void ShardConnection::OnConnect() { Log_Trace(); //Log_Debug("Shard connection connected, endpoint: %s", endpoint.ToString()); CLIENT_MUTEX_GUARD_DECLARE(); MessageConnection::OnConnect(); if (client->IsBulkLoading() && !isBulkSent) { SendBulkLoadingRequest(); return; } SendQuorumRequests(); } void ShardConnection::OnClose() { // Log_Debug("Shard connection closing: %s", endpoint.ToString()); Request* it; Request* prev; uint64_t* itQuorum; uint64_t* itNext; CLIENT_MUTEX_GUARD_DECLARE(); isBulkSent = false; // close the socket and try reconnecting MessageConnection::OnClose(); // restart reconnection with timeout EventLoop::Reset(&connectTimeout); // invalidate quorums for (itQuorum = quorums.First(); itQuorum != NULL; itQuorum = itNext) { itNext = quorums.Next(itQuorum); InvalidateQuorum(*itQuorum); } // put back requests that have no response to the client's quorum queue for (it = sentRequests.Last(); it != NULL; it = prev) { prev = sentRequests.Prev(it); sentRequests.Remove(it); client->AddRequestToQuorum(it, false); } } void ShardConnection::InvalidateQuorum(uint64_t quorumID) { Request* it; Request* prev; for (it = sentRequests.Last(); it != NULL; it = prev) { prev = sentRequests.Prev(it); if (it->quorumID == quorumID) { sentRequests.Remove(it); client->AddRequestToQuorum(it, false); } } client->InvalidateQuorum(quorumID, nodeID); } void ShardConnection::SendQuorumRequests() { uint64_t* qit; // notify the client so that it can assign the requests to the connection FOREACH (qit, quorums) client->SendQuorumRequest(this, *qit); } void ShardConnection::SendBulkLoadingRequest() { Request req; req.BulkLoading(0); req.isBulk = true; SendRequest(&req); Flush(); } <|endoftext|>
<commit_before>/* Copyright 2017 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include <iostream> #include <vector> #include "tensorflow/contrib/tensorboard/db/schema.h" #include "tensorflow/contrib/tensorboard/db/summary_db_writer.h" #include "tensorflow/core/lib/db/sqlite.h" #include "tensorflow/core/lib/io/record_reader.h" #include "tensorflow/core/platform/init_main.h" #include "tensorflow/core/util/command_line_flags.h" #include "tensorflow/core/util/event.pb.h" namespace tensorflow { namespace { template <typename T> string AddCommas(T n) { static_assert(std::is_integral<T>::value, "is_integral"); string s = strings::StrCat(n); if (s.size() > 3) { int extra = s.size() / 3 - (s.size() % 3 == 0 ? 1 : 0); s.append(extra, 'X'); int c = 0; for (int i = s.size() - 1; i > 0; --i) { s[i] = s[i - extra]; if (++c % 3 == 0) { s[--i] = ','; --extra; } } } return s; } int main(int argc, char* argv[]) { string path; string events; string experiment_name; string run_name; string user_name; std::vector<Flag> flag_list = { Flag("db", &path, "Path of SQLite DB file"), Flag("events", &events, "TensorFlow record proto event log file"), Flag("experiment_name", &experiment_name, "The DB experiment_name value"), Flag("run_name", &run_name, "The DB run_name value"), Flag("user_name", &user_name, "The DB user_name value"), }; string usage = Flags::Usage(argv[0], flag_list); bool parse_result = Flags::Parse(&argc, argv, flag_list); if (!parse_result || path.empty()) { std::cerr << "The loader tool imports tf.Event record files, created by\n" << "SummaryFileWriter, into the sorts of SQLite database files\n" << "created by SummaryDbWriter.\n\n" << "In addition to the flags below, the environment variables\n" << "defined by core/lib/db/sqlite.cc can also be set.\n\n" << usage; return -1; } port::InitMain(argv[0], &argc, &argv); Env* env = Env::Default(); LOG(INFO) << "Opening SQLite file: " << path; Sqlite* db; TF_CHECK_OK(Sqlite::Open( path, SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE | SQLITE_OPEN_NOMUTEX, &db)); core::ScopedUnref unref_db(db); LOG(INFO) << "Initializing TensorBoard schema"; TF_CHECK_OK(SetupTensorboardSqliteDb(db)); LOG(INFO) << "Creating SummaryDbWriter"; SummaryWriterInterface* db_writer; TF_CHECK_OK(CreateSummaryDbWriter(db, experiment_name, run_name, user_name, env, &db_writer)); core::ScopedUnref unref(db_writer); LOG(INFO) << "Loading TF event log: " << events; std::unique_ptr<RandomAccessFile> file; TF_CHECK_OK(env->NewRandomAccessFile(events, &file)); io::RecordReader reader(file.get()); uint64 start = env->NowMicros(); uint64 records = 0; uint64 offset = 0; string record; while (true) { std::unique_ptr<Event> event = std::unique_ptr<Event>(new Event); Status s = reader.ReadRecord(&offset, &record); if (s.code() == error::OUT_OF_RANGE) break; TF_CHECK_OK(s); if (!ParseProtoUnlimited(event.get(), record)) { LOG(FATAL) << "Corrupt tf.Event record" << " offset=" << (offset - record.size()) << " size=" << static_cast<int>(record.size()); } TF_CHECK_OK(db_writer->WriteEvent(std::move(event))); ++records; } uint64 elapsed = env->NowMicros() - start; LOG(INFO) << "Loaded " << AddCommas(offset) << " bytes with " << AddCommas(records) << " records at " << AddCommas(offset / (elapsed / 1000000)) << " bps"; return 0; } } // namespace } // namespace tensorflow int main(int argc, char* argv[]) { return tensorflow::main(argc, argv); } <commit_msg>Fix floating point exception with bps calculation modified: tensorflow/contrib/tensorboard/db/loader.cc<commit_after>/* Copyright 2017 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include <iostream> #include <vector> #include "tensorflow/contrib/tensorboard/db/schema.h" #include "tensorflow/contrib/tensorboard/db/summary_db_writer.h" #include "tensorflow/core/lib/db/sqlite.h" #include "tensorflow/core/lib/io/record_reader.h" #include "tensorflow/core/platform/init_main.h" #include "tensorflow/core/util/command_line_flags.h" #include "tensorflow/core/util/event.pb.h" namespace tensorflow { namespace { template <typename T> string AddCommas(T n) { static_assert(std::is_integral<T>::value, "is_integral"); string s = strings::StrCat(n); if (s.size() > 3) { int extra = s.size() / 3 - (s.size() % 3 == 0 ? 1 : 0); s.append(extra, 'X'); int c = 0; for (int i = s.size() - 1; i > 0; --i) { s[i] = s[i - extra]; if (++c % 3 == 0) { s[--i] = ','; --extra; } } } return s; } int main(int argc, char* argv[]) { string path; string events; string experiment_name; string run_name; string user_name; std::vector<Flag> flag_list = { Flag("db", &path, "Path of SQLite DB file"), Flag("events", &events, "TensorFlow record proto event log file"), Flag("experiment_name", &experiment_name, "The DB experiment_name value"), Flag("run_name", &run_name, "The DB run_name value"), Flag("user_name", &user_name, "The DB user_name value"), }; string usage = Flags::Usage(argv[0], flag_list); bool parse_result = Flags::Parse(&argc, argv, flag_list); if (!parse_result || path.empty()) { std::cerr << "The loader tool imports tf.Event record files, created by\n" << "SummaryFileWriter, into the sorts of SQLite database files\n" << "created by SummaryDbWriter.\n\n" << "In addition to the flags below, the environment variables\n" << "defined by core/lib/db/sqlite.cc can also be set.\n\n" << usage; return -1; } port::InitMain(argv[0], &argc, &argv); Env* env = Env::Default(); LOG(INFO) << "Opening SQLite file: " << path; Sqlite* db; TF_CHECK_OK(Sqlite::Open( path, SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE | SQLITE_OPEN_NOMUTEX, &db)); core::ScopedUnref unref_db(db); LOG(INFO) << "Initializing TensorBoard schema"; TF_CHECK_OK(SetupTensorboardSqliteDb(db)); LOG(INFO) << "Creating SummaryDbWriter"; SummaryWriterInterface* db_writer; TF_CHECK_OK(CreateSummaryDbWriter(db, experiment_name, run_name, user_name, env, &db_writer)); core::ScopedUnref unref(db_writer); LOG(INFO) << "Loading TF event log: " << events; std::unique_ptr<RandomAccessFile> file; TF_CHECK_OK(env->NewRandomAccessFile(events, &file)); io::RecordReader reader(file.get()); uint64 start = env->NowMicros(); uint64 records = 0; uint64 offset = 0; string record; while (true) { std::unique_ptr<Event> event = std::unique_ptr<Event>(new Event); Status s = reader.ReadRecord(&offset, &record); if (s.code() == error::OUT_OF_RANGE) break; TF_CHECK_OK(s); if (!ParseProtoUnlimited(event.get(), record)) { LOG(FATAL) << "Corrupt tf.Event record" << " offset=" << (offset - record.size()) << " size=" << static_cast<int>(record.size()); } TF_CHECK_OK(db_writer->WriteEvent(std::move(event))); ++records; } uint64 elapsed = env->NowMicros() - start; LOG(INFO) << "Loaded " << AddCommas(offset) << " bytes with " << AddCommas(records) << " records"; if (elapsed > 0) { LOG(INFO) << "bps=" << (uint64)(offset / (elapsed / 1000000.0)); } return 0; } } // namespace } // namespace tensorflow int main(int argc, char* argv[]) { return tensorflow::main(argc, argv); } <|endoftext|>
<commit_before>#include "catch.hpp" #include <initializer_list> #include "cxxopts.hpp" class Argv { public: Argv(std::initializer_list<const char*> args) : m_argv(new char*[args.size()]) , m_argc(args.size()) { int i = 0; auto iter = args.begin(); while (iter != args.end()) { auto len = strlen(*iter) + 1; auto ptr = std::unique_ptr<char[]>(new char[len]); strcpy(ptr.get(), *iter); m_args.push_back(std::move(ptr)); m_argv.get()[i] = m_args.back().get(); ++iter; ++i; } } char** argv() const { return m_argv.get(); } int argc() const { return m_argc; } private: std::vector<std::unique_ptr<char[]>> m_args; std::unique_ptr<char*[]> m_argv; int m_argc; }; TEST_CASE("Basic options", "[options]") { cxxopts::Options options("tester", " - test basic options"); options.add_options() ("long", "a long option") ("s,short", "a short option") ("value", "an option with a value", cxxopts::value<std::string>()) ("a,av", "a short option with a value", cxxopts::value<std::string>()) ("6,six", "a short number option") ("p, space", "an option with space between short and long") ; Argv argv({ "tester", "--long", "-s", "--value", "value", "-a", "b", "-6", "-p", "--space", }); char** actual_argv = argv.argv(); auto argc = argv.argc(); auto result = options.parse(argc, actual_argv); CHECK(result.count("long") == 1); CHECK(result.count("s") == 1); CHECK(result.count("value") == 1); CHECK(result.count("a") == 1); CHECK(result["value"].as<std::string>() == "value"); CHECK(result["a"].as<std::string>() == "b"); CHECK(result.count("6") == 1); CHECK(result.count("p") == 2); CHECK(result.count("space") == 2); } TEST_CASE("Short options", "[options]") { cxxopts::Options options("test_short", " - test short options"); options.add_options() ("a", "a short option", cxxopts::value<std::string>()); Argv argv({"test_short", "-a", "value"}); auto actual_argv = argv.argv(); auto argc = argv.argc(); auto result = options.parse(argc, actual_argv); CHECK(result.count("a") == 1); CHECK(result["a"].as<std::string>() == "value"); REQUIRE_THROWS_AS(options.add_options()("", "nothing option"), cxxopts::invalid_option_format_error); } TEST_CASE("No positional", "[positional]") { cxxopts::Options options("test_no_positional", " - test no positional options"); Argv av({"tester", "a", "b", "def"}); char** argv = av.argv(); auto argc = av.argc(); auto result = options.parse(argc, argv); REQUIRE(argc == 4); CHECK(strcmp(argv[1], "a") == 0); } TEST_CASE("All positional", "[positional]") { std::vector<std::string> positional; cxxopts::Options options("test_all_positional", " - test all positional"); options.add_options() ("positional", "Positional parameters", cxxopts::value<std::vector<std::string>>(positional)) ; Argv av({"tester", "a", "b", "c"}); auto argc = av.argc(); auto argv = av.argv(); options.parse_positional("positional"); auto result = options.parse(argc, argv); REQUIRE(argc == 1); REQUIRE(positional.size() == 3); CHECK(positional[0] == "a"); CHECK(positional[1] == "b"); CHECK(positional[2] == "c"); } TEST_CASE("Some positional explicit", "[positional]") { cxxopts::Options options("positional_explicit", " - test positional"); options.add_options() ("input", "Input file", cxxopts::value<std::string>()) ("output", "Output file", cxxopts::value<std::string>()) ("positional", "Positional parameters", cxxopts::value<std::vector<std::string>>()) ; options.parse_positional({"input", "output", "positional"}); Argv av({"tester", "--output", "a", "b", "c", "d"}); char** argv = av.argv(); auto argc = av.argc(); auto result = options.parse(argc, argv); CHECK(argc == 1); CHECK(result.count("output")); CHECK(result["input"].as<std::string>() == "b"); CHECK(result["output"].as<std::string>() == "a"); auto& positional = result["positional"].as<std::vector<std::string>>(); REQUIRE(positional.size() == 2); CHECK(positional[0] == "c"); CHECK(positional[1] == "d"); } TEST_CASE("No positional with extras", "[positional]") { cxxopts::Options options("posargmaster", "shows incorrect handling"); options.add_options() ("dummy", "oh no", cxxopts::value<std::string>()) ; Argv av({"extras", "--", "a", "b", "c", "d"}); char** argv = av.argv(); auto argc = av.argc(); auto old_argv = argv; auto old_argc = argc; options.parse(argc, argv); REQUIRE(argc == old_argc - 1); CHECK(argv[0] == std::string("extras")); CHECK(argv[1] == std::string("a")); } TEST_CASE("Empty with implicit value", "[implicit]") { cxxopts::Options options("empty_implicit", "doesn't handle empty"); options.add_options() ("implicit", "Has implicit", cxxopts::value<std::string>() ->implicit_value("foo")); Argv av({"implicit", "--implicit", ""}); char** argv = av.argv(); auto argc = av.argc(); auto result = options.parse(argc, argv); REQUIRE(result.count("implicit") == 1); REQUIRE(result["implicit"].as<std::string>() == ""); } TEST_CASE("Parse into a reference", "[reference]") { int value = 0; cxxopts::Options options("into_reference", "parses into a reference"); options.add_options() ("ref", "A reference", cxxopts::value(value)); Argv av({"into_reference", "--ref", "42"}); auto argv = av.argv(); auto argc = av.argc(); auto result = options.parse(argc, argv); CHECK(result.count("ref") == 1); CHECK(value == 42); } TEST_CASE("Integers", "[options]") { cxxopts::Options options("parses_integers", "parses integers correctly"); options.add_options() ("positional", "Integers", cxxopts::value<std::vector<int>>()); Argv av({"ints", "--", "5", "6", "-6", "0", "0xab", "0xAf"}); char** argv = av.argv(); auto argc = av.argc(); options.parse_positional("positional"); auto result = options.parse(argc, argv); REQUIRE(result.count("positional") == 6); auto& positional = result["positional"].as<std::vector<int>>(); REQUIRE(positional.size() == 6); CHECK(positional[0] == 5); CHECK(positional[1] == 6); CHECK(positional[2] == -6); CHECK(positional[3] == 0); CHECK(positional[4] == 0xab); CHECK(positional[5] == 0xaf); } TEST_CASE("Unsigned integers", "[options]") { cxxopts::Options options("parses_unsigned", "detects unsigned errors"); options.add_options() ("positional", "Integers", cxxopts::value<std::vector<unsigned int>>()); Argv av({"ints", "--", "-2"}); char** argv = av.argv(); auto argc = av.argc(); options.parse_positional("positional"); CHECK_THROWS_AS(options.parse(argc, argv), cxxopts::argument_incorrect_type); } TEST_CASE("Integer bounds", "[integer]") { cxxopts::Options options("integer_boundaries", "check min/max integer"); options.add_options() ("positional", "Integers", cxxopts::value<std::vector<int8_t>>()); SECTION("No overflow") { Argv av({"ints", "--", "127", "-128", "0x7f", "-0x80", "0x7e"}); auto argv = av.argv(); auto argc = av.argc(); options.parse_positional("positional"); auto result = options.parse(argc, argv); REQUIRE(result.count("positional") == 5); auto& positional = result["positional"].as<std::vector<int8_t>>(); CHECK(positional[0] == 127); CHECK(positional[1] == -128); CHECK(positional[2] == 0x7f); CHECK(positional[3] == -0x80); CHECK(positional[4] == 0x7e); } } TEST_CASE("Overflow on boundary", "[integer]") { using namespace cxxopts::values; int8_t si; uint8_t ui; CHECK_THROWS_AS((integer_parser("128", si)), cxxopts::argument_incorrect_type); CHECK_THROWS_AS((integer_parser("-129", si)), cxxopts::argument_incorrect_type); CHECK_THROWS_AS((integer_parser("256", ui)), cxxopts::argument_incorrect_type); CHECK_THROWS_AS((integer_parser("-0x81", si)), cxxopts::argument_incorrect_type); CHECK_THROWS_AS((integer_parser("0x80", si)), cxxopts::argument_incorrect_type); CHECK_THROWS_AS((integer_parser("0x100", ui)), cxxopts::argument_incorrect_type); } TEST_CASE("Integer overflow", "[options]") { cxxopts::Options options("reject_overflow", "rejects overflowing integers"); options.add_options() ("positional", "Integers", cxxopts::value<std::vector<int8_t>>()); Argv av({"ints", "--", "128"}); auto argv = av.argv(); auto argc = av.argc(); options.parse_positional("positional"); CHECK_THROWS_AS(options.parse(argc, argv), cxxopts::argument_incorrect_type); } TEST_CASE("Floats", "[options]") { cxxopts::Options options("parses_floats", "parses floats correctly"); options.add_options() ("double", "Double precision", cxxopts::value<double>()) ("positional", "Floats", cxxopts::value<std::vector<float>>()); Argv av({"floats", "--double", "0.5", "--", "4", "-4", "1.5e6", "-1.5e6"}); char** argv = av.argv(); auto argc = av.argc(); options.parse_positional("positional"); auto result = options.parse(argc, argv); REQUIRE(result.count("double") == 1); REQUIRE(result.count("positional") == 4); CHECK(result["double"].as<double>() == 0.5); auto& positional = result["positional"].as<std::vector<float>>(); CHECK(positional[0] == 4); CHECK(positional[1] == -4); CHECK(positional[2] == 1.5e6); CHECK(positional[3] == -1.5e6); } <commit_msg>test that fails<commit_after>#include "catch.hpp" #include <initializer_list> #include "cxxopts.hpp" class Argv { public: Argv(std::initializer_list<const char*> args) : m_argv(new char*[args.size()]) , m_argc(args.size()) { int i = 0; auto iter = args.begin(); while (iter != args.end()) { auto len = strlen(*iter) + 1; auto ptr = std::unique_ptr<char[]>(new char[len]); strcpy(ptr.get(), *iter); m_args.push_back(std::move(ptr)); m_argv.get()[i] = m_args.back().get(); ++iter; ++i; } } char** argv() const { return m_argv.get(); } int argc() const { return m_argc; } private: std::vector<std::unique_ptr<char[]>> m_args; std::unique_ptr<char*[]> m_argv; int m_argc; }; TEST_CASE("Basic options", "[options]") { cxxopts::Options options("tester", " - test basic options"); options.add_options() ("long", "a long option") ("s,short", "a short option") ("value", "an option with a value", cxxopts::value<std::string>()) ("a,av", "a short option with a value", cxxopts::value<std::string>()) ("6,six", "a short number option") ("p, space", "an option with space between short and long") ; Argv argv({ "tester", "--long", "-s", "--value", "value", "-a", "b", "-6", "-p", "--space", }); char** actual_argv = argv.argv(); auto argc = argv.argc(); auto result = options.parse(argc, actual_argv); CHECK(result.count("long") == 1); CHECK(result.count("s") == 1); CHECK(result.count("value") == 1); CHECK(result.count("a") == 1); CHECK(result["value"].as<std::string>() == "value"); CHECK(result["a"].as<std::string>() == "b"); CHECK(result.count("6") == 1); CHECK(result.count("p") == 2); CHECK(result.count("space") == 2); } TEST_CASE("Short options", "[options]") { cxxopts::Options options("test_short", " - test short options"); options.add_options() ("a", "a short option", cxxopts::value<std::string>()); Argv argv({"test_short", "-a", "value"}); auto actual_argv = argv.argv(); auto argc = argv.argc(); auto result = options.parse(argc, actual_argv); CHECK(result.count("a") == 1); CHECK(result["a"].as<std::string>() == "value"); REQUIRE_THROWS_AS(options.add_options()("", "nothing option"), cxxopts::invalid_option_format_error); } TEST_CASE("No positional", "[positional]") { cxxopts::Options options("test_no_positional", " - test no positional options"); Argv av({"tester", "a", "b", "def"}); char** argv = av.argv(); auto argc = av.argc(); auto result = options.parse(argc, argv); REQUIRE(argc == 4); CHECK(strcmp(argv[1], "a") == 0); } TEST_CASE("All positional", "[positional]") { std::vector<std::string> positional; cxxopts::Options options("test_all_positional", " - test all positional"); options.add_options() ("positional", "Positional parameters", cxxopts::value<std::vector<std::string>>(positional)) ; Argv av({"tester", "a", "b", "c"}); auto argc = av.argc(); auto argv = av.argv(); options.parse_positional("positional"); auto result = options.parse(argc, argv); REQUIRE(argc == 1); REQUIRE(positional.size() == 3); CHECK(positional[0] == "a"); CHECK(positional[1] == "b"); CHECK(positional[2] == "c"); } TEST_CASE("Some positional explicit", "[positional]") { cxxopts::Options options("positional_explicit", " - test positional"); options.add_options() ("input", "Input file", cxxopts::value<std::string>()) ("output", "Output file", cxxopts::value<std::string>()) ("positional", "Positional parameters", cxxopts::value<std::vector<std::string>>()) ; options.parse_positional({"input", "output", "positional"}); Argv av({"tester", "--output", "a", "b", "c", "d"}); char** argv = av.argv(); auto argc = av.argc(); auto result = options.parse(argc, argv); CHECK(argc == 1); CHECK(result.count("output")); CHECK(result["input"].as<std::string>() == "b"); CHECK(result["output"].as<std::string>() == "a"); auto& positional = result["positional"].as<std::vector<std::string>>(); REQUIRE(positional.size() == 2); CHECK(positional[0] == "c"); CHECK(positional[1] == "d"); } TEST_CASE("No positional with extras", "[positional]") { cxxopts::Options options("posargmaster", "shows incorrect handling"); options.add_options() ("dummy", "oh no", cxxopts::value<std::string>()) ; Argv av({"extras", "--", "a", "b", "c", "d"}); char** argv = av.argv(); auto argc = av.argc(); auto old_argv = argv; auto old_argc = argc; options.parse(argc, argv); REQUIRE(argc == old_argc - 1); CHECK(argv[0] == std::string("extras")); CHECK(argv[1] == std::string("a")); } TEST_CASE("Empty with implicit value", "[implicit]") { cxxopts::Options options("empty_implicit", "doesn't handle empty"); options.add_options() ("implicit", "Has implicit", cxxopts::value<std::string>() ->implicit_value("foo")); Argv av({"implicit", "--implicit", ""}); char** argv = av.argv(); auto argc = av.argc(); auto result = options.parse(argc, argv); REQUIRE(result.count("implicit") == 1); REQUIRE(result["implicit"].as<std::string>() == ""); } TEST_CASE("Default values", "[default]") { cxxopts::Options options("defaults", "has defaults"); options.add_options() ("default", "Has implicit", cxxopts::value<int>() ->default_value("42")); SECTION("Sets defaults") { Argv av({"implicit"}); char** argv = av.argv(); auto argc = av.argc(); auto result = options.parse(argc, argv); CHECK(result.count("default") == 1); CHECK(result["default"].as<int>() == 42); } SECTION("When values provided") { Argv av({"implicit", "default", "5"}); char** argv = av.argv(); auto argc = av.argc(); auto result = options.parse(argc, argv); CHECK(result.count("default") == 1); CHECK(result["default"].as<int>() == 5); } } TEST_CASE("Parse into a reference", "[reference]") { int value = 0; cxxopts::Options options("into_reference", "parses into a reference"); options.add_options() ("ref", "A reference", cxxopts::value(value)); Argv av({"into_reference", "--ref", "42"}); auto argv = av.argv(); auto argc = av.argc(); auto result = options.parse(argc, argv); CHECK(result.count("ref") == 1); CHECK(value == 42); } TEST_CASE("Integers", "[options]") { cxxopts::Options options("parses_integers", "parses integers correctly"); options.add_options() ("positional", "Integers", cxxopts::value<std::vector<int>>()); Argv av({"ints", "--", "5", "6", "-6", "0", "0xab", "0xAf"}); char** argv = av.argv(); auto argc = av.argc(); options.parse_positional("positional"); auto result = options.parse(argc, argv); REQUIRE(result.count("positional") == 6); auto& positional = result["positional"].as<std::vector<int>>(); REQUIRE(positional.size() == 6); CHECK(positional[0] == 5); CHECK(positional[1] == 6); CHECK(positional[2] == -6); CHECK(positional[3] == 0); CHECK(positional[4] == 0xab); CHECK(positional[5] == 0xaf); } TEST_CASE("Unsigned integers", "[options]") { cxxopts::Options options("parses_unsigned", "detects unsigned errors"); options.add_options() ("positional", "Integers", cxxopts::value<std::vector<unsigned int>>()); Argv av({"ints", "--", "-2"}); char** argv = av.argv(); auto argc = av.argc(); options.parse_positional("positional"); CHECK_THROWS_AS(options.parse(argc, argv), cxxopts::argument_incorrect_type); } TEST_CASE("Integer bounds", "[integer]") { cxxopts::Options options("integer_boundaries", "check min/max integer"); options.add_options() ("positional", "Integers", cxxopts::value<std::vector<int8_t>>()); SECTION("No overflow") { Argv av({"ints", "--", "127", "-128", "0x7f", "-0x80", "0x7e"}); auto argv = av.argv(); auto argc = av.argc(); options.parse_positional("positional"); auto result = options.parse(argc, argv); REQUIRE(result.count("positional") == 5); auto& positional = result["positional"].as<std::vector<int8_t>>(); CHECK(positional[0] == 127); CHECK(positional[1] == -128); CHECK(positional[2] == 0x7f); CHECK(positional[3] == -0x80); CHECK(positional[4] == 0x7e); } } TEST_CASE("Overflow on boundary", "[integer]") { using namespace cxxopts::values; int8_t si; uint8_t ui; CHECK_THROWS_AS((integer_parser("128", si)), cxxopts::argument_incorrect_type); CHECK_THROWS_AS((integer_parser("-129", si)), cxxopts::argument_incorrect_type); CHECK_THROWS_AS((integer_parser("256", ui)), cxxopts::argument_incorrect_type); CHECK_THROWS_AS((integer_parser("-0x81", si)), cxxopts::argument_incorrect_type); CHECK_THROWS_AS((integer_parser("0x80", si)), cxxopts::argument_incorrect_type); CHECK_THROWS_AS((integer_parser("0x100", ui)), cxxopts::argument_incorrect_type); } TEST_CASE("Integer overflow", "[options]") { cxxopts::Options options("reject_overflow", "rejects overflowing integers"); options.add_options() ("positional", "Integers", cxxopts::value<std::vector<int8_t>>()); Argv av({"ints", "--", "128"}); auto argv = av.argv(); auto argc = av.argc(); options.parse_positional("positional"); CHECK_THROWS_AS(options.parse(argc, argv), cxxopts::argument_incorrect_type); } TEST_CASE("Floats", "[options]") { cxxopts::Options options("parses_floats", "parses floats correctly"); options.add_options() ("double", "Double precision", cxxopts::value<double>()) ("positional", "Floats", cxxopts::value<std::vector<float>>()); Argv av({"floats", "--double", "0.5", "--", "4", "-4", "1.5e6", "-1.5e6"}); char** argv = av.argv(); auto argc = av.argc(); options.parse_positional("positional"); auto result = options.parse(argc, argv); REQUIRE(result.count("double") == 1); REQUIRE(result.count("positional") == 4); CHECK(result["double"].as<double>() == 0.5); auto& positional = result["positional"].as<std::vector<float>>(); CHECK(positional[0] == 4); CHECK(positional[1] == -4); CHECK(positional[2] == 1.5e6); CHECK(positional[3] == -1.5e6); } <|endoftext|>
<commit_before>/**************************************************************************** ** ** Copyright (C) 2015 WxMaper (http://wxmaper.ru) ** ** This file is part of the PHPQt5. ** ** BEGIN LICENSE: MPL 2.0 ** ** 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/. ** ** END LICENSE ** ****************************************************************************/ #include "phpqt5.h" #include "pqengine_private.h" #include "php_streams.h" zend_object_handlers PHPQt5::pqobject_handlers; php_stream_ops php_stream_qrc_ops = { PHPQt5::php_qrc_write, PHPQt5::php_qrc_read, PHPQt5::php_qrc_close, PHPQt5::php_qrc_flush, "qrc", NULL, NULL, NULL, NULL }; php_stream_wrapper_ops php_stream_qrc_wops = { PHPQt5::qrc_opener, NULL, NULL, NULL, NULL, "qrc wrapper", NULL, NULL, NULL, NULL }; static php_stream_wrapper php_qrc_stream_wrapper = { &php_stream_qrc_wops, NULL, 0 }; php_stream *PHPQt5::qrc_opener(php_stream_wrapper *wrapper, const char *path, const char *mode, int options, zend_string **opened_path, php_stream_context *context) { #ifdef PQDEBUG PQDBG_LVL_START(__FUNCTION__); PQDBGLPUP(path); #endif QString resourcePath = QString(path).mid(6); QByteArray qrc_data; #if defined(PQDEBUG) && defined(PQDETAILEDDEBUG) PQDBGLPUP("open resource"); #endif // QString rFilePath = QString(":/%1/%2").arg(getCorename().constData()).arg(resourcePath); QString rFilePath = QString(":/%1").arg(resourcePath); #if defined(PQDEBUG) && defined(PQDETAILEDDEBUG) PQDBGLPUP(QString("rFilePath: %1").arg(rFilePath)); #endif QFile file(rFilePath); if(file.open(QIODevice::ReadOnly)) { qrc_data = file.readAll(); } else { php_error(E_ERROR, QString("Resource not found: %1%2").arg(path).arg(PHP_EOL).toUtf8().constData()); return nullptr; } QDataStream *s = new QDataStream(qrc_data); php_stream *stream = nullptr; struct qrc_stream_data *data; #if defined(PQDEBUG) && defined(PQDETAILEDDEBUG) PQDBGLPUP("emalloc qrc_stream_data"); #endif data = (qrc_stream_data *) emalloc(sizeof(*data)); data->qrc_file = s; data->stream = stream; #if defined(PQDEBUG) && defined(PQDETAILEDDEBUG) PQDBGLPUP("php_stream_alloc"); #endif stream = php_stream_alloc(&php_stream_qrc_ops, data, NULL, mode); #if defined(PQDEBUG) && defined(PQDETAILEDDEBUG) PQDBGLPUP("done"); #endif PQDBG_LVL_DONE(); return stream; } size_t PHPQt5::php_qrc_write(php_stream *stream, const char *buf, size_t count) { #ifdef PQDEBUG PQDBG_LVL_START(__FUNCTION__); PQDBG_LVL_DONE(); #endif php_error(E_ERROR, QString("Unable to write to resource file!").toUtf8().constData()); return 0; } int PHPQt5::php_qrc_flush(php_stream *stream) { #ifdef PQDEBUG PQDBG_LVL_START(__FUNCTION__); PQDBG_LVL_DONE(); #endif return 0; } int PHPQt5::php_qrc_close(php_stream *stream, int close_handle) { #ifdef PQDEBUG PQDBG_LVL_START(__FUNCTION__); #endif struct qrc_stream_data *self = (struct qrc_stream_data *) stream->abstract; int ret = EOF; #if defined(PQDEBUG) && defined(PQDETAILEDDEBUG) PQDBGLPUP("close device"); #endif self->qrc_file->device()->close(); delete self->qrc_file; #if defined(PQDEBUG) && defined(PQDETAILEDDEBUG) PQDBGLPUP("free stream"); #endif efree(self); #if defined(PQDEBUG) && defined(PQDETAILEDDEBUG) PQDBGLPUP("done"); #endif PQDBG_LVL_DONE(); return ret; } size_t PHPQt5::php_qrc_read(php_stream *stream, char *buf, size_t count) { #ifdef PQDEBUG PQDBG_LVL_START(__FUNCTION__); #endif struct qrc_stream_data *self = (struct qrc_stream_data *) stream->abstract; #if defined(PQDEBUG) && defined(PQDETAILEDDEBUG) PQDBGLPUP("read device"); #endif QDataStream *s = self->qrc_file; size_t read_bytes = s->device()->read(buf, count); stream->eof = 1; #if defined(PQDEBUG) && defined(PQDETAILEDDEBUG) PQDBGLPUP("done"); #endif PQDBG_LVL_DONE(); return read_bytes; } int PHPQt5::zm_startup_phpqt5(INIT_FUNC_ARGS) { #ifdef PQDEBUG PQDBG_LVL_START(__FUNCTION__); #endif qRegisterMetaType<zval>("zval"); qRegisterMetaType<zval*>("zval*"); #if defined(PQDEBUG) && defined(PQDETAILEDDEBUG) PQDBGLPUP("register stream wrapper"); #endif php_register_url_stream_wrapper("qrc", &php_qrc_stream_wrapper); #if defined(PQDEBUG) && defined(PQDETAILEDDEBUG) PQDBGLPUP("register handlers"); #endif memcpy(&pqobject_handlers, zend_get_std_object_handlers(), sizeof(zend_object_handlers)); pqobject_handlers.offset = XtOffsetOf(PQObjectWrapper, zo); pqobject_handlers.free_obj = pqobject_free_storage; pqobject_handlers.call_method = pqobject_call_method; pqobject_handlers.get_method = pqobject_get_method; pqobject_handlers.clone_obj = NULL; // pqobject_handlers.get_property_ptr_ptr = pqobject_get_property_ptr_ptr; // pqobject_handlers.get_properties = pqobject_get_properties; // pqobject_handlers.read_property = pqobject_read_property; // pqobject_handlers.has_property = pqobject_has_property; #if defined(PQDEBUG) && defined(PQDETAILEDDEBUG) PQDBGLPUP("register extensions"); #endif PQEnginePrivate::pq_register_extensions(PQDBG_LVL_C); phpqt5Connections = new PHPQt5Connection(PQDBG_LVL_C); #if defined(PQDEBUG) && defined(PQDETAILEDDEBUG) PQDBGLPUP("done"); #endif PQDBG_LVL_DONE(); return SUCCESS; } <commit_msg>Add error handler function<commit_after>/**************************************************************************** ** ** Copyright (C) 2015 WxMaper (http://wxmaper.ru) ** ** This file is part of the PHPQt5. ** ** BEGIN LICENSE: MPL 2.0 ** ** 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/. ** ** END LICENSE ** ****************************************************************************/ #include "phpqt5.h" #include "pqengine_private.h" #include "php_streams.h" zend_object_handlers PHPQt5::pqobject_handlers; php_stream_ops php_stream_qrc_ops = { PHPQt5::php_qrc_write, PHPQt5::php_qrc_read, PHPQt5::php_qrc_close, PHPQt5::php_qrc_flush, "qrc", NULL, NULL, NULL, NULL }; php_stream_wrapper_ops php_stream_qrc_wops = { PHPQt5::qrc_opener, NULL, NULL, NULL, NULL, "qrc wrapper", NULL, NULL, NULL, NULL }; static php_stream_wrapper php_qrc_stream_wrapper = { &php_stream_qrc_wops, NULL, 0 }; php_stream *PHPQt5::qrc_opener(php_stream_wrapper *wrapper, const char *path, const char *mode, int options, zend_string **opened_path, php_stream_context *context) { #ifdef PQDEBUG PQDBG_LVL_START(__FUNCTION__); PQDBGLPUP(path); #endif QString resourcePath = QString(path).mid(6); QByteArray qrc_data; #if defined(PQDEBUG) && defined(PQDETAILEDDEBUG) PQDBGLPUP("open resource"); #endif // QString rFilePath = QString(":/%1/%2").arg(getCorename().constData()).arg(resourcePath); QString rFilePath = QString(":/%1").arg(resourcePath); #if defined(PQDEBUG) && defined(PQDETAILEDDEBUG) PQDBGLPUP(QString("rFilePath: %1").arg(rFilePath)); #endif QFile file(rFilePath); if(file.open(QIODevice::ReadOnly)) { qrc_data = file.readAll(); } else { php_error(E_ERROR, QString("Resource not found: %1%2").arg(path).arg(PHP_EOL).toUtf8().constData()); return nullptr; } QDataStream *s = new QDataStream(qrc_data); php_stream *stream = nullptr; struct qrc_stream_data *data; #if defined(PQDEBUG) && defined(PQDETAILEDDEBUG) PQDBGLPUP("emalloc qrc_stream_data"); #endif data = (qrc_stream_data *) emalloc(sizeof(*data)); data->qrc_file = s; data->stream = stream; #if defined(PQDEBUG) && defined(PQDETAILEDDEBUG) PQDBGLPUP("php_stream_alloc"); #endif stream = php_stream_alloc(&php_stream_qrc_ops, data, NULL, mode); #if defined(PQDEBUG) && defined(PQDETAILEDDEBUG) PQDBGLPUP("done"); #endif PQDBG_LVL_DONE(); return stream; } size_t PHPQt5::php_qrc_write(php_stream *stream, const char *buf, size_t count) { #ifdef PQDEBUG PQDBG_LVL_START(__FUNCTION__); PQDBG_LVL_DONE(); #endif php_error(E_ERROR, QString("Unable to write to resource file!").toUtf8().constData()); return 0; } int PHPQt5::php_qrc_flush(php_stream *stream) { #ifdef PQDEBUG PQDBG_LVL_START(__FUNCTION__); PQDBG_LVL_DONE(); #endif return 0; } int PHPQt5::php_qrc_close(php_stream *stream, int close_handle) { #ifdef PQDEBUG PQDBG_LVL_START(__FUNCTION__); #endif struct qrc_stream_data *self = (struct qrc_stream_data *) stream->abstract; int ret = EOF; #if defined(PQDEBUG) && defined(PQDETAILEDDEBUG) PQDBGLPUP("close device"); #endif self->qrc_file->device()->close(); delete self->qrc_file; #if defined(PQDEBUG) && defined(PQDETAILEDDEBUG) PQDBGLPUP("free stream"); #endif efree(self); #if defined(PQDEBUG) && defined(PQDETAILEDDEBUG) PQDBGLPUP("done"); #endif PQDBG_LVL_DONE(); return ret; } size_t PHPQt5::php_qrc_read(php_stream *stream, char *buf, size_t count) { #ifdef PQDEBUG PQDBG_LVL_START(__FUNCTION__); #endif struct qrc_stream_data *self = (struct qrc_stream_data *) stream->abstract; #if defined(PQDEBUG) && defined(PQDETAILEDDEBUG) PQDBGLPUP("read device"); #endif QDataStream *s = self->qrc_file; size_t read_bytes = s->device()->read(buf, count); stream->eof = 1; #if defined(PQDEBUG) && defined(PQDETAILEDDEBUG) PQDBGLPUP("done"); #endif PQDBG_LVL_DONE(); return read_bytes; } static void phpqt5_error_handler(int error_num, const char *error_filename, const uint error_lineno, const char *format, va_list args) { QString error_type; switch(error_num) { case E_ERROR: error_type = "Error"; break; case E_WARNING: error_type = "Warning"; break; case E_CORE_ERROR: error_type = "Core Error"; break; case E_CORE_WARNING: error_type = "Core Warning"; break; case E_COMPILE_ERROR: error_type = "Compile Error"; break; case E_COMPILE_WARNING: error_type = "Compile Warning"; break; case E_USER_ERROR: error_type = "User Error"; break; case E_USER_WARNING: error_type = "User Warning"; break; case E_RECOVERABLE_ERROR: error_type = "Recoverable Error"; break; default: return; } pq_pre(QString("<b>%1</b>: %2 in <b>%3</b> on line <b>%4</b>") .arg(error_type) .arg(format) .arg(error_filename) .arg(error_lineno), error_type); } int PHPQt5::zm_startup_phpqt5(INIT_FUNC_ARGS) { #ifdef PQDEBUG PQDBG_LVL_START(__FUNCTION__); #endif zend_error_cb = phpqt5_error_handler; // qRegisterMetaType<zval>("zval"); qRegisterMetaType<zval*>("zval*"); PQDBGLPUP("register stream wrapper"); php_register_url_stream_wrapper("qrc", &php_qrc_stream_wrapper); PQDBGLPUP("register handlers"); memcpy(&pqobject_handlers, zend_get_std_object_handlers(), sizeof(zend_object_handlers)); pqobject_handlers.offset = XtOffsetOf(PQObjectWrapper, zo); pqobject_handlers.free_obj = pqobject_free_storage; pqobject_handlers.call_method = pqobject_call_method; pqobject_handlers.get_method = pqobject_get_method; pqobject_handlers.clone_obj = NULL; // pqobject_handlers.get_property_ptr_ptr = pqobject_get_property_ptr_ptr; // pqobject_handlers.get_properties = pqobject_get_properties; // pqobject_handlers.read_property = pqobject_read_property; // pqobject_handlers.has_property = pqobject_has_property; PQDBGLPUP("register extensions"); PQEnginePrivate::pq_register_extensions(PQDBG_LVL_C); phpqt5Connections = new PHPQt5Connection(PQDBG_LVL_C); PQDBG_LVL_DONE_LPUP(); return SUCCESS; } <|endoftext|>
<commit_before>/* For more information, please see: http://software.sci.utah.edu The MIT License Copyright (c) 2015 Scientific Computing and Imaging Institute, University of Utah. License for the specific language governing rights and limitations under 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 <Core/ConsoleApplication/ConsoleCommands.h> #include <Core/Algorithms/Base/AlgorithmVariableNames.h> #include <Dataflow/Engine/Controller/NetworkEditorController.h> #include <Core/Application/Application.h> #include <Dataflow/Serialization/Network/XMLSerializer.h> #include <Dataflow/Serialization/Network/NetworkDescriptionSerialization.h> #include <Dataflow/Network/Module.h> #include <Core/Logging/ConsoleLogger.h> #include <Core/Python/PythonInterpreter.h> #include <boost/algorithm/string.hpp> using namespace SCIRun::Core; using namespace Commands; using namespace Console; using namespace SCIRun::Dataflow::Networks; using namespace Algorithms; LoadFileCommandConsole::LoadFileCommandConsole() { addParameter(Name("FileNum"), 0); } //TODO: find a better place for this function namespace { void quietModulesIfNotVerbose() { if (!Application::Instance().parameters()->verboseMode()) Module::defaultLogger_.reset(new SCIRun::Core::Logging::NullLogger); } } bool LoadFileCommandConsole::execute() { quietModulesIfNotVerbose(); auto inputFiles = Application::Instance().parameters()->inputFiles(); std::string filename; if (!inputFiles.empty()) filename = inputFiles[0]; else { filename = get(Variables::Filename).toFilename().string(); } /// @todo: real logger std::cout << "Attempting load of " << filename << std::endl; if (!boost::filesystem::exists(filename)) { std::cout << "File does not exist: " << filename << std::endl; return false; } try { auto openedFile = XMLSerializer::load_xml<NetworkFile>(filename); if (openedFile) { Application::Instance().controller()->clear(); Application::Instance().controller()->loadNetwork(openedFile); /// @todo: real logger std::cout << "File load done: " << filename << std::endl; return true; } /// @todo: real logger std::cout << "File load failed: " << filename << std::endl; } catch (...) { /// @todo: real logger std::cout << "File load failed: " << filename << std::endl; } return false; } bool SaveFileCommandConsole::execute() { return !saveImpl(get(Variables::Filename).toFilename().string()).empty(); } bool ExecuteCurrentNetworkCommandConsole::execute() { std::cout << "....Executing network..." << std::endl; Application::Instance().controller()->connectNetworkExecutionFinished([](int code){ std::cout << "Execution finished with code " << code << std::endl; }); Application::Instance().controller()->stopExecutionContextLoopWhenExecutionFinishes(); auto t = Application::Instance().controller()->executeAll(nullptr); std::cout << "....Execute started..." << std::endl; t->join(); std::cout << "....Execute thread stopped...entering interactive mode." << std::endl; InteractiveModeCommandConsole interactive; return interactive.execute(); } QuitAfterExecuteCommandConsole::QuitAfterExecuteCommandConsole() { addParameter(Name("RunningPython"), false); } bool QuitAfterExecuteCommandConsole::execute() { std::cout << "Quit after execute is set." << std::endl; Application::Instance().controller()->connectNetworkExecutionFinished([](int code){ exit(code); }); return true; } QuitCommandConsole::QuitCommandConsole() { addParameter(Name("RunningPython"), false); } bool QuitCommandConsole::execute() { std::cout << "Goodbye!" << std::endl; exit(0); return true; } bool PrintHelpCommand::execute() { std::cout << Application::Instance().commandHelpString() << std::endl; return true; } bool PrintVersionCommand::execute() { std::cout << Application::Instance().version() << std::endl; return true; } bool PrintModulesCommand::execute() { std::cout << "MODULE LIST as of " << Application::Instance().version() << "\n" << Application::Instance().moduleList() << std::endl; return true; } bool InteractiveModeCommandConsole::execute() { #ifdef BUILD_WITH_PYTHON quietModulesIfNotVerbose(); PythonInterpreter::Instance().run_string("import SCIRunPythonAPI; from SCIRunPythonAPI import *"); std::string line; while (true) { std::cout << "scirun5> " << std::flush; std::getline(std::cin, line); if (line == "quit") // TODO: need fix for ^D entry || (!x.empty() && x[0] == '\004')) break; if (std::cin.eof()) break; if (!PythonInterpreter::Instance().run_string(line)) break; } std::cout << "\nGoodbye!" << std::endl; exit(0); #endif return true; } bool RunPythonScriptCommandConsole::execute() { quietModulesIfNotVerbose(); auto script = Application::Instance().parameters()->pythonScriptFile(); if (script) { #ifdef BUILD_WITH_PYTHON std::cout << "RUNNING PYTHON SCRIPT: " << *script << std::endl;; Application::Instance().controller()->clear(); PythonInterpreter::Instance().run_string("import SCIRunPythonAPI; from SCIRunPythonAPI import *"); PythonInterpreter::Instance().run_file(script->string()); //TODO: not sure what else to do here. Probably wait on a condition variable, or just loop forever if (!Application::Instance().parameters()->interactiveMode()) { while (true) { std::cout << "Running Python script." << std::endl; boost::this_thread::sleep(boost::posix_time::milliseconds(1000)); } } std::cout << "Done running Python script." << std::endl; return true; #else std::cout << "Python disabled, cannot run script " << *script << std::endl; return false; #endif } return false; } <commit_msg>Clean up logging.<commit_after>/* For more information, please see: http://software.sci.utah.edu The MIT License Copyright (c) 2015 Scientific Computing and Imaging Institute, University of Utah. License for the specific language governing rights and limitations under 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 <Core/ConsoleApplication/ConsoleCommands.h> #include <Core/Algorithms/Base/AlgorithmVariableNames.h> #include <Dataflow/Engine/Controller/NetworkEditorController.h> #include <Core/Application/Application.h> #include <Dataflow/Serialization/Network/XMLSerializer.h> #include <Dataflow/Serialization/Network/NetworkDescriptionSerialization.h> #include <Dataflow/Network/Module.h> #include <Core/Logging/ConsoleLogger.h> #include <Core/Python/PythonInterpreter.h> #include <boost/algorithm/string.hpp> using namespace SCIRun::Core; using namespace Commands; using namespace Console; using namespace SCIRun::Dataflow::Networks; using namespace Algorithms; LoadFileCommandConsole::LoadFileCommandConsole() { addParameter(Name("FileNum"), 0); } //TODO: find a better place for this function namespace { void quietModulesIfNotVerbose() { if (!Application::Instance().parameters()->verboseMode()) Module::defaultLogger_.reset(new SCIRun::Core::Logging::NullLogger); } } /// @todo: real logger #define LOG_CONSOLE(x) std::cout << "[SCIRun] " << x << std::endl; bool LoadFileCommandConsole::execute() { quietModulesIfNotVerbose(); auto inputFiles = Application::Instance().parameters()->inputFiles(); std::string filename; if (!inputFiles.empty()) filename = inputFiles[0]; else { filename = get(Variables::Filename).toFilename().string(); } LOG_CONSOLE("Attempting load of " << filename); if (!boost::filesystem::exists(filename)) { LOG_CONSOLE("File does not exist: " << filename); return false; } try { auto openedFile = XMLSerializer::load_xml<NetworkFile>(filename); if (openedFile) { Application::Instance().controller()->clear(); Application::Instance().controller()->loadNetwork(openedFile); LOG_CONSOLE("File load done: " << filename); return true; } LOG_CONSOLE("File load failed: " << filename); } catch (...) { LOG_CONSOLE("File load failed: " << filename); } return false; } bool SaveFileCommandConsole::execute() { return !saveImpl(get(Variables::Filename).toFilename().string()).empty(); } bool ExecuteCurrentNetworkCommandConsole::execute() { LOG_CONSOLE("Executing network..."); Application::Instance().controller()->connectNetworkExecutionFinished([](int code){ LOG_CONSOLE("Execution finished with code " << code); }); Application::Instance().controller()->stopExecutionContextLoopWhenExecutionFinishes(); auto t = Application::Instance().controller()->executeAll(nullptr); LOG_CONSOLE("Execution started."); t->join(); LOG_CONSOLE("Execute thread stopped. Entering interactive mode."); InteractiveModeCommandConsole interactive; return interactive.execute(); } QuitAfterExecuteCommandConsole::QuitAfterExecuteCommandConsole() { addParameter(Name("RunningPython"), false); } bool QuitAfterExecuteCommandConsole::execute() { LOG_CONSOLE("Quit after execute is set."); Application::Instance().controller()->connectNetworkExecutionFinished([](int code) { LOG_CONSOLE("Goodbye! Exit code: " << code); exit(code); }); return true; } QuitCommandConsole::QuitCommandConsole() { addParameter(Name("RunningPython"), false); } bool QuitCommandConsole::execute() { LOG_CONSOLE("Goodbye!"); exit(0); return true; } bool PrintHelpCommand::execute() { std::cout << Application::Instance().commandHelpString() << std::endl; return true; } bool PrintVersionCommand::execute() { std::cout << Application::Instance().version() << std::endl; return true; } bool PrintModulesCommand::execute() { std::cout << "MODULE LIST as of " << Application::Instance().version() << "\n" << Application::Instance().moduleList() << std::endl; return true; } bool InteractiveModeCommandConsole::execute() { #ifdef BUILD_WITH_PYTHON quietModulesIfNotVerbose(); PythonInterpreter::Instance().run_string("import SCIRunPythonAPI; from SCIRunPythonAPI import *"); std::string line; while (true) { std::cout << "scirun5> " << std::flush; std::getline(std::cin, line); if (line == "quit") // TODO: need fix for ^D entry || (!x.empty() && x[0] == '\004')) break; if (std::cin.eof()) break; if (!PythonInterpreter::Instance().run_string(line)) break; } std::cout << "\n[SCIRun] Goodbye!" << std::endl; exit(0); #endif return true; } bool RunPythonScriptCommandConsole::execute() { quietModulesIfNotVerbose(); auto script = Application::Instance().parameters()->pythonScriptFile(); if (script) { #ifdef BUILD_WITH_PYTHON LOG_CONSOLE("RUNNING PYTHON SCRIPT: " << *script); Application::Instance().controller()->clear(); PythonInterpreter::Instance().run_string("import SCIRunPythonAPI; from SCIRunPythonAPI import *"); PythonInterpreter::Instance().run_file(script->string()); //TODO: not sure what else to do here. Probably wait on a condition variable, or just loop forever if (!Application::Instance().parameters()->interactiveMode()) { while (true) { LOG_CONSOLE("Running Python script."); boost::this_thread::sleep(boost::posix_time::milliseconds(1000)); } } LOG_CONSOLE("Done running Python script."); return true; #else LOG_CONSOLE("Python disabled, cannot run script " << *script); return false; #endif } return false; } <|endoftext|>
<commit_before>// RUN: %clangxx_asan -fexceptions -O %s -o %t && %run %t // // FIXME: Needs better C++ exception support // XFAIL: win32 // // Test __sanitizer_annotate_contiguous_container. #include <stdlib.h> #include <stdio.h> #include <string.h> #include <assert.h> #include <sanitizer/asan_interface.h> void TestContainer(size_t capacity) { char *beg = new char[capacity]; char *end = beg + capacity; char *mid = beg + capacity; char *old_mid = 0; for (int i = 0; i < 10000; i++) { size_t size = rand() % (capacity + 1); assert(size <= capacity); old_mid = mid; mid = beg + size; __sanitizer_annotate_contiguous_container(beg, end, old_mid, mid); for (size_t idx = 0; idx < size; idx++) assert(!__asan_address_is_poisoned(beg + idx)); for (size_t idx = size; idx < capacity; idx++) assert(__asan_address_is_poisoned(beg + idx)); assert(__sanitizer_verify_contiguous_container(beg, mid, end)); if (mid != beg) assert(!__sanitizer_verify_contiguous_container(beg, mid - 1, end)); if (mid != end) assert(!__sanitizer_verify_contiguous_container(beg, mid + 1, end)); } // Don't forget to unpoison the whole thing before destroing/reallocating. __sanitizer_annotate_contiguous_container(beg, end, mid, end); for (size_t idx = 0; idx < capacity; idx++) assert(!__asan_address_is_poisoned(beg + idx)); delete[] beg; } __attribute__((noinline)) void Throw() { throw 1; } __attribute__((noinline)) void ThrowAndCatch() { try { Throw(); } catch(...) { } } void TestThrow() { char x[32]; __sanitizer_annotate_contiguous_container(x, x + 32, x + 32, x + 14); assert(!__asan_address_is_poisoned(x + 13)); assert(__asan_address_is_poisoned(x + 14)); ThrowAndCatch(); assert(!__asan_address_is_poisoned(x + 13)); // FIXME: invert the assertion below once we fix // https://code.google.com/p/address-sanitizer/issues/detail?id=258 // This assertion works only w/o UAR. if (!__asan_get_current_fake_stack()) assert(!__asan_address_is_poisoned(x + 14)); __sanitizer_annotate_contiguous_container(x, x + 32, x + 14, x + 32); assert(!__asan_address_is_poisoned(x + 13)); assert(!__asan_address_is_poisoned(x + 14)); } int main(int argc, char **argv) { int n = argc == 1 ? 128 : atoi(argv[1]); for (int i = 0; i <= n; i++) TestContainer(i); TestThrow(); } <commit_msg>Remove the XFAIL for the C++ EH test<commit_after>// RUN: %clangxx_asan -fexceptions -O %s -o %t && %run %t // // Test __sanitizer_annotate_contiguous_container. #include <stdlib.h> #include <stdio.h> #include <string.h> #include <assert.h> #include <sanitizer/asan_interface.h> void TestContainer(size_t capacity) { char *beg = new char[capacity]; char *end = beg + capacity; char *mid = beg + capacity; char *old_mid = 0; for (int i = 0; i < 10000; i++) { size_t size = rand() % (capacity + 1); assert(size <= capacity); old_mid = mid; mid = beg + size; __sanitizer_annotate_contiguous_container(beg, end, old_mid, mid); for (size_t idx = 0; idx < size; idx++) assert(!__asan_address_is_poisoned(beg + idx)); for (size_t idx = size; idx < capacity; idx++) assert(__asan_address_is_poisoned(beg + idx)); assert(__sanitizer_verify_contiguous_container(beg, mid, end)); if (mid != beg) assert(!__sanitizer_verify_contiguous_container(beg, mid - 1, end)); if (mid != end) assert(!__sanitizer_verify_contiguous_container(beg, mid + 1, end)); } // Don't forget to unpoison the whole thing before destroing/reallocating. __sanitizer_annotate_contiguous_container(beg, end, mid, end); for (size_t idx = 0; idx < capacity; idx++) assert(!__asan_address_is_poisoned(beg + idx)); delete[] beg; } __attribute__((noinline)) void Throw() { throw 1; } __attribute__((noinline)) void ThrowAndCatch() { try { Throw(); } catch(...) { } } void TestThrow() { char x[32]; __sanitizer_annotate_contiguous_container(x, x + 32, x + 32, x + 14); assert(!__asan_address_is_poisoned(x + 13)); assert(__asan_address_is_poisoned(x + 14)); ThrowAndCatch(); assert(!__asan_address_is_poisoned(x + 13)); // FIXME: invert the assertion below once we fix // https://code.google.com/p/address-sanitizer/issues/detail?id=258 // This assertion works only w/o UAR. if (!__asan_get_current_fake_stack()) assert(!__asan_address_is_poisoned(x + 14)); __sanitizer_annotate_contiguous_container(x, x + 32, x + 14, x + 32); assert(!__asan_address_is_poisoned(x + 13)); assert(!__asan_address_is_poisoned(x + 14)); } int main(int argc, char **argv) { int n = argc == 1 ? 128 : atoi(argv[1]); for (int i = 0; i <= n; i++) TestContainer(i); TestThrow(); } <|endoftext|>
<commit_before>/* * Copyright 2010 MQWeb - Franky Braem * * Licensed under the EUPL, Version 1.1 or – as soon they * will be approved by the European Commission - subsequent * versions of the EUPL (the "Licence"); * You may not use this work except in compliance with the * Licence. * You may obtain a copy of the Licence at: * * http://joinup.ec.europa.eu/software/page/eupl * * Unless required by applicable law or agreed to in * writing, software distributed under the Licence is * distributed on an "AS IS" basis, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. * See the Licence for the specific language governing * permissions and limitations under the Licence. */ #include <sstream> #include <MQ/Web/QueueManagerController.h> #include <MQ/Web/QueueManagerMapper.h> namespace MQ { namespace Web { QueueManagerController::QueueManagerController() : MQController() { } QueueManagerController::~QueueManagerController() { } void QueueManagerController::view() { QueueManagerMapper queueManagerMapper(*commandServer()); Poco::JSON::Object::Ptr dummyFilter = new Poco::JSON::Object(); Poco::JSON::Array::Ptr jsonQueueManagers = queueManagerMapper.inquire(dummyFilter); if ( jsonQueueManagers->size() > 0 ) { set("qmgr", jsonQueueManagers->get(0)); render("home.tpl"); } } } } // Namespace MQ::Web <commit_msg>Check the format and return JSON or HTML<commit_after>/* * Copyright 2010 MQWeb - Franky Braem * * Licensed under the EUPL, Version 1.1 or – as soon they * will be approved by the European Commission - subsequent * versions of the EUPL (the "Licence"); * You may not use this work except in compliance with the * Licence. * You may obtain a copy of the Licence at: * * http://joinup.ec.europa.eu/software/page/eupl * * Unless required by applicable law or agreed to in * writing, software distributed under the Licence is * distributed on an "AS IS" basis, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. * See the Licence for the specific language governing * permissions and limitations under the Licence. */ #include <sstream> #include <MQ/Web/QueueManagerController.h> #include <MQ/Web/QueueManagerMapper.h> namespace MQ { namespace Web { QueueManagerController::QueueManagerController() : MQController() { } QueueManagerController::~QueueManagerController() { } void QueueManagerController::view() { QueueManagerMapper queueManagerMapper(*commandServer()); Poco::JSON::Object::Ptr dummyFilter = new Poco::JSON::Object(); Poco::JSON::Array::Ptr jsonQueueManagers = queueManagerMapper.inquire(dummyFilter); if ( jsonQueueManagers->size() > 0 ) { set("qmgr", jsonQueueManagers->get(0)); if ( format().compare("html") == 0 ) { render("home.tpl"); } else if ( format().compare("json") == 0 ) { data().stringify(response().send()); } } } } } // Namespace MQ::Web <|endoftext|>
<commit_before>#include "Common/HighQueuePch.h" #define BOOST_TEST_NO_MAIN HighQueuePerformanceTest #include <boost/test/unit_test.hpp> #include <HighQueue/Producer.h> #include <HighQueue/Consumer.h> #include <Common/Stopwatch.h> #include <HQPerformance/TestMessage.h> using namespace HighQueue; typedef TestMessage<20> ActualMessage; namespace { volatile std::atomic<uint32_t> threadsReady; volatile bool producerGo = false; void producerFunction(Connection & connection, uint32_t producerNumber, uint64_t messageCount, bool solo) { Producer producer(connection, solo); HighQueue::Message producerMessage; if(!connection.allocate(producerMessage)) { std::cerr << "Failed to allocate message for producer Number " << producerNumber << std::endl; return; } ++threadsReady; while(!producerGo) { std::this_thread::yield(); } for(uint32_t messageNumber = 0; messageNumber < messageCount; ++messageNumber) { auto testMessage = producerMessage.construct<ActualMessage>(producerNumber, messageNumber); producer.publish(producerMessage); } } } #define DISABLE_MultithreadMessagePassingPerformancex #ifdef DISABLE_MultithreadMessagePassingPerformance #pragma message ("DISABLE_MultithreadMessagePassingPerformance") #else // DISABLE_MultithreadMessagePassingPerformance BOOST_AUTO_TEST_CASE(testMultithreadMessagePassingPerformance) { static const size_t entryCount = 100000; static const size_t messageSize = sizeof(ActualMessage); static const uint64_t targetMessageCount = 1000000 * 100; // runs about 5 to 10 seconds in release/optimized build static const size_t producerLimit = 2;//10; // running on 8 core system. Once we go over 7 producers it slows down. That's one thing we want to see. static const size_t consumerLimit = 1; // Just for documentation static const size_t messageCount = entryCount + consumerLimit + producerLimit; static const size_t spinCount = 0; static const size_t yieldCount = ConsumerWaitStrategy::FOREVER; ConsumerWaitStrategy strategy(spinCount, yieldCount); CreationParameters parameters(strategy, entryCount, messageSize, messageCount); Connection connection; connection.createLocal("LocalIv", parameters); Consumer consumer(connection); HighQueue::Message consumerMessage; BOOST_REQUIRE(connection.allocate(consumerMessage)); for(size_t producerCount = 1; producerCount < producerLimit; ++producerCount) { std::cerr << "Test " << producerCount << " producer"; std::vector<std::thread> producerThreads; std::vector<uint64_t> nextMessage; threadsReady = 0; producerGo = false; size_t perProducer = targetMessageCount / producerCount; size_t actualMessageCount = perProducer * producerCount; for(uint32_t nTh = 0; nTh < producerCount; ++nTh) { nextMessage.emplace_back(0u); producerThreads.emplace_back( std::bind(producerFunction, std::ref(connection), nTh, perProducer, producerCount == 1)); } std::this_thread::yield(); while(threadsReady < producerCount) { std::this_thread::yield(); } Stopwatch timer; producerGo = true; for(uint64_t messageNumber = 0; messageNumber < actualMessageCount; ++messageNumber) { consumer.getNext(consumerMessage); auto testMessage = consumerMessage.get<ActualMessage>(); testMessage->touch(); auto & msgNumber = nextMessage[testMessage->producerNumber()]; if(msgNumber != testMessage->messageNumber()) { // the if avoids the performance hit of BOOST_CHECK_EQUAL unless it's needed. BOOST_CHECK_EQUAL(messageNumber, testMessage->messageNumber()); } ++ msgNumber; } auto lapse = timer.nanoseconds(); // sometimes we synchronize thread shut down. producerGo = false; for(size_t nTh = 0; nTh < producerCount; ++nTh) { producerThreads[nTh].join(); } auto messageBytes = sizeof(ActualMessage); auto messageBits = sizeof(ActualMessage) * 8; std::cout << " Passed " << actualMessageCount << ' ' << messageBytes << " byte messages in " << std::setprecision(9) << double(lapse) / double(Stopwatch::nanosecondsPerSecond) << " seconds. " << lapse / actualMessageCount << " nsec./message " << std::setprecision(3) << double(actualMessageCount) / double(lapse) << " GMsg/second " << std::setprecision(3) << double(actualMessageCount * messageBytes) / double(lapse) << " GByte/second " << std::setprecision(3) << double(actualMessageCount * messageBits) / double(lapse) << " GBit/second." << std::endl; } } #endif // DISABLE_MultithreadMessagePassingPerformance <commit_msg>Re-enable multithread test<commit_after>#include "Common/HighQueuePch.h" #define BOOST_TEST_NO_MAIN HighQueuePerformanceTest #include <boost/test/unit_test.hpp> #include <HighQueue/Producer.h> #include <HighQueue/Consumer.h> #include <Common/Stopwatch.h> #include <HQPerformance/TestMessage.h> using namespace HighQueue; typedef TestMessage<20> ActualMessage; namespace { volatile std::atomic<uint32_t> threadsReady; volatile bool producerGo = false; void producerFunction(Connection & connection, uint32_t producerNumber, uint64_t messageCount, bool solo) { Producer producer(connection, solo); HighQueue::Message producerMessage; if(!connection.allocate(producerMessage)) { std::cerr << "Failed to allocate message for producer Number " << producerNumber << std::endl; return; } ++threadsReady; while(!producerGo) { std::this_thread::yield(); } for(uint32_t messageNumber = 0; messageNumber < messageCount; ++messageNumber) { auto testMessage = producerMessage.construct<ActualMessage>(producerNumber, messageNumber); producer.publish(producerMessage); } } } #define DISABLE_MultithreadMessagePassingPerformancex #ifdef DISABLE_MultithreadMessagePassingPerformance #pragma message ("DISABLE_MultithreadMessagePassingPerformance") #else // DISABLE_MultithreadMessagePassingPerformance BOOST_AUTO_TEST_CASE(testMultithreadMessagePassingPerformance) { static const size_t entryCount = 100000; static const size_t messageSize = sizeof(ActualMessage); static const uint64_t targetMessageCount = 1000000 * 100; // runs about 5 to 10 seconds in release/optimized build static const size_t producerLimit = 8; // running on 8 core system. Once we go over 7 producers it slows down. That's one thing we want to see. static const size_t consumerLimit = 1; // Just for documentation static const size_t messageCount = entryCount + consumerLimit + producerLimit; static const size_t spinCount = 0; static const size_t yieldCount = ConsumerWaitStrategy::FOREVER; ConsumerWaitStrategy strategy(spinCount, yieldCount); CreationParameters parameters(strategy, entryCount, messageSize, messageCount); Connection connection; connection.createLocal("LocalIv", parameters); Consumer consumer(connection); HighQueue::Message consumerMessage; BOOST_REQUIRE(connection.allocate(consumerMessage)); for(size_t producerCount = 1; producerCount <= producerLimit; ++producerCount) { std::cerr << "Test " << producerCount << " producer"; std::vector<std::thread> producerThreads; std::vector<uint64_t> nextMessage; threadsReady = 0; producerGo = false; size_t perProducer = targetMessageCount / producerCount; size_t actualMessageCount = perProducer * producerCount; for(uint32_t nTh = 0; nTh < producerCount; ++nTh) { nextMessage.emplace_back(0u); producerThreads.emplace_back( std::bind(producerFunction, std::ref(connection), nTh, perProducer, producerCount == 1)); } std::this_thread::yield(); while(threadsReady < producerCount) { std::this_thread::yield(); } Stopwatch timer; producerGo = true; for(uint64_t messageNumber = 0; messageNumber < actualMessageCount; ++messageNumber) { consumer.getNext(consumerMessage); auto testMessage = consumerMessage.get<ActualMessage>(); testMessage->touch(); auto & msgNumber = nextMessage[testMessage->producerNumber()]; if(msgNumber != testMessage->messageNumber()) { // the if avoids the performance hit of BOOST_CHECK_EQUAL unless it's needed. BOOST_CHECK_EQUAL(messageNumber, testMessage->messageNumber()); } ++ msgNumber; } auto lapse = timer.nanoseconds(); // sometimes we synchronize thread shut down. producerGo = false; for(size_t nTh = 0; nTh < producerCount; ++nTh) { producerThreads[nTh].join(); } auto messageBytes = sizeof(ActualMessage); auto messageBits = sizeof(ActualMessage) * 8; std::cout << " Passed " << actualMessageCount << ' ' << messageBytes << " byte messages in " << std::setprecision(9) << double(lapse) / double(Stopwatch::nanosecondsPerSecond) << " seconds. " << lapse / actualMessageCount << " nsec./message " << std::setprecision(3) << double(actualMessageCount) / double(lapse) << " GMsg/second " << std::setprecision(3) << double(actualMessageCount * messageBytes) / double(lapse) << " GByte/second " << std::setprecision(3) << double(actualMessageCount * messageBits) / double(lapse) << " GBit/second." << std::endl; } } #endif // DISABLE_MultithreadMessagePassingPerformance <|endoftext|>