text
stringlengths
54
60.6k
<commit_before>// Copyright 2019 Google LLC // // 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 <fcntl.h> #include <linux/filter.h> #include <sys/resource.h> #include <syscall.h> #include <cstddef> #include <cstdint> #include <cstdio> #include <cstdlib> #include <memory> #include <string> #include <utility> #include <vector> #include <glog/logging.h> #include "sandboxed_api/util/flag.h" #include "absl/memory/memory.h" #include "sandboxed_api/sandbox2/comms.h" #include "sandboxed_api/sandbox2/executor.h" #include "sandboxed_api/sandbox2/limits.h" #include "sandboxed_api/sandbox2/policy.h" #include "sandboxed_api/sandbox2/policybuilder.h" #include "sandboxed_api/sandbox2/result.h" #include "sandboxed_api/sandbox2/sandbox2.h" #include "sandboxed_api/sandbox2/util/bpf_helper.h" #include "sandboxed_api/util/runfiles.h" using std::string; ABSL_FLAG(string, input, "", "Input file"); ABSL_FLAG(string, output, "", "Output file"); ABSL_FLAG(bool, decompress, false, "Decompress instead of compress."); namespace { std::unique_ptr<sandbox2::Policy> GetPolicy() { return sandbox2::PolicyBuilder() // Allow read on STDIN. .AddPolicyOnSyscall(__NR_read, {ARG_32(0), JEQ32(0, ALLOW)}) // Allow write on STDOUT / STDERR. .AddPolicyOnSyscall(__NR_write, {ARG_32(0), JEQ32(1, ALLOW), JEQ32(2, ALLOW)}) .AllowSyscall(__NR_fstat) .AllowStaticStartup() .AllowSystemMalloc() .AllowExit() .BlockSyscallWithErrno(__NR_access, ENOENT) .BuildOrDie(); } } // namespace int main(int argc, char** argv) { gflags::ParseCommandLineFlags(&argc, &argv, true); google::InitGoogleLogging(argv[0]); if (absl::GetFlag(FLAGS_input).empty()) { LOG(ERROR) << "Parameter --input required."; return 1; } if (absl::GetFlag(FLAGS_output).empty()) { LOG(ERROR) << "Parameter --output required."; return 1; } // Note: In your own code, use sapi::GetDataDependencyFilePath() instead. const std::string path = sapi::internal::GetSapiDataDependencyFilePath( "sandbox2/examples/zlib/zpipe"); std::vector<std::string> args = {path}; if (absl::GetFlag(FLAGS_decompress)) { args.push_back("-d"); } std::vector<std::string> envs = {}; auto executor = absl::make_unique<sandbox2::Executor>(path, args, envs); executor // Kill sandboxed processes with a signal (SIGXFSZ) if it writes more than // these many bytes to the file-system. ->limits() ->set_rlimit_fsize(1ULL << 30) // 1GiB .set_rlimit_cpu(60) // The CPU time limit in seconds. .set_walltime_limit(absl::Seconds(5)); // Create input + output FD. int fd_in = open(absl::GetFlag(FLAGS_input).c_str(), O_RDONLY); int fd_out = open(absl::GetFlag(FLAGS_output).c_str(), O_WRONLY | O_CREAT | O_TRUNC, 0644); CHECK_GE(fd_in, 0); CHECK_GE(fd_out, 0); executor->ipc()->MapFd(fd_in, STDIN_FILENO); executor->ipc()->MapFd(fd_out, STDOUT_FILENO); auto policy = GetPolicy(); sandbox2::Sandbox2 s2(std::move(executor), std::move(policy)); // Let the sandboxee run. auto result = s2.Run(); close(fd_in); close(fd_out); if (result.final_status() != sandbox2::Result::OK) { LOG(ERROR) << "Sandbox error: " << result.ToString(); return 2; // e.g. sandbox violation, signal (sigsegv) } auto code = result.reason_code(); if (code) { LOG(ERROR) << "Sandboxee exited with non-zero: " << code; return 3; // e.g. normal child error } LOG(INFO) << "Sandboxee finished: " << result.ToString(); return EXIT_SUCCESS; } <commit_msg>Enable AArch64 syscalls in examples<commit_after>// Copyright 2019 Google LLC // // 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 <fcntl.h> #include <linux/filter.h> #include <sys/resource.h> #include <syscall.h> #include <cstddef> #include <cstdint> #include <cstdio> #include <cstdlib> #include <memory> #include <string> #include <utility> #include <vector> #include <glog/logging.h> #include "sandboxed_api/util/flag.h" #include "absl/memory/memory.h" #include "sandboxed_api/sandbox2/comms.h" #include "sandboxed_api/sandbox2/executor.h" #include "sandboxed_api/sandbox2/limits.h" #include "sandboxed_api/sandbox2/policy.h" #include "sandboxed_api/sandbox2/policybuilder.h" #include "sandboxed_api/sandbox2/result.h" #include "sandboxed_api/sandbox2/sandbox2.h" #include "sandboxed_api/sandbox2/util/bpf_helper.h" #include "sandboxed_api/util/runfiles.h" using std::string; ABSL_FLAG(string, input, "", "Input file"); ABSL_FLAG(string, output, "", "Output file"); ABSL_FLAG(bool, decompress, false, "Decompress instead of compress."); namespace { std::unique_ptr<sandbox2::Policy> GetPolicy() { return sandbox2::PolicyBuilder() // Allow read on STDIN. .AddPolicyOnSyscall(__NR_read, {ARG_32(0), JEQ32(0, ALLOW)}) // Allow write on STDOUT / STDERR. .AddPolicyOnSyscall(__NR_write, {ARG_32(0), JEQ32(1, ALLOW), JEQ32(2, ALLOW)}) .AllowSyscall(__NR_fstat) .AllowStaticStartup() .AllowSystemMalloc() .AllowExit() #ifdef __NR_access .BlockSyscallWithErrno(__NR_access, ENOENT) #endif #ifdef __NR_faccessat .BlockSyscallWithErrno(__NR_faccessat, ENOENT) #endif .BuildOrDie(); } } // namespace int main(int argc, char** argv) { gflags::ParseCommandLineFlags(&argc, &argv, true); google::InitGoogleLogging(argv[0]); if (absl::GetFlag(FLAGS_input).empty()) { LOG(ERROR) << "Parameter --input required."; return 1; } if (absl::GetFlag(FLAGS_output).empty()) { LOG(ERROR) << "Parameter --output required."; return 1; } // Note: In your own code, use sapi::GetDataDependencyFilePath() instead. const std::string path = sapi::internal::GetSapiDataDependencyFilePath( "sandbox2/examples/zlib/zpipe"); std::vector<std::string> args = {path}; if (absl::GetFlag(FLAGS_decompress)) { args.push_back("-d"); } std::vector<std::string> envs = {}; auto executor = absl::make_unique<sandbox2::Executor>(path, args, envs); executor // Kill sandboxed processes with a signal (SIGXFSZ) if it writes more than // these many bytes to the file-system. ->limits() ->set_rlimit_fsize(1ULL << 30) // 1GiB .set_rlimit_cpu(60) // The CPU time limit in seconds. .set_walltime_limit(absl::Seconds(5)); // Create input + output FD. int fd_in = open(absl::GetFlag(FLAGS_input).c_str(), O_RDONLY); int fd_out = open(absl::GetFlag(FLAGS_output).c_str(), O_WRONLY | O_CREAT | O_TRUNC, 0644); CHECK_GE(fd_in, 0); CHECK_GE(fd_out, 0); executor->ipc()->MapFd(fd_in, STDIN_FILENO); executor->ipc()->MapFd(fd_out, STDOUT_FILENO); auto policy = GetPolicy(); sandbox2::Sandbox2 s2(std::move(executor), std::move(policy)); // Let the sandboxee run. auto result = s2.Run(); close(fd_in); close(fd_out); if (result.final_status() != sandbox2::Result::OK) { LOG(ERROR) << "Sandbox error: " << result.ToString(); return 2; // e.g. sandbox violation, signal (sigsegv) } auto code = result.reason_code(); if (code) { LOG(ERROR) << "Sandboxee exited with non-zero: " << code; return 3; // e.g. normal child error } LOG(INFO) << "Sandboxee finished: " << result.ToString(); return EXIT_SUCCESS; } <|endoftext|>
<commit_before>/*************************************************************************** * io/benchmark_configured_disks.cpp * * Part of the STXXL. See http://stxxl.sourceforge.net * * Copyright (C) 2009 Johannes Singler <singler@ira.uka.de> * * Distributed under the Boost Software License, Version 1.0. * (See accompanying file LICENSE_1_0.txt or copy at * http://www.boost.org/LICENSE_1_0.txt) **************************************************************************/ /* example gnuplot command for the output of this program: (x-axis: offset in GiB, y-axis: bandwidth in MiB/s) plot \ "disk.log" using ($2/1024):($7) w l title "read", \ "disk.log" using ($2/1024):($4) w l title "write" */ #include <iomanip> #include <vector> #include <stxxl/io> #include <stxxl/mng> #ifndef BOOST_MSVC #include <unistd.h> #endif using stxxl::request_ptr; using stxxl::file; using stxxl::timestamp; #ifdef BLOCK_ALIGN #undef BLOCK_ALIGN #endif #define BLOCK_ALIGN 4096 #define POLL_DELAY 1000 #define CHECK_AFTER_READ 0 #define MB (1024 * 1024) #define GB (1024 * 1024 * 1024) void usage(const char * argv0) { std::cout << "Usage: " << argv0 << " length step [r|w]" << std::endl; std::cout << " 'length' is given in GiB, 'step' size in MiB" << std::endl; std::cout << " length == 0 implies till end of space (please ignore the write error)" << std::endl; exit(-1); } int main(int argc, char * argv[]) { if (argc < 3) usage(argv[0]); stxxl::int64 offset = 0; stxxl::int64 length = stxxl::int64(GB) * stxxl::int64(atoi(argv[1])); stxxl::int64 step_size = stxxl::int64(MB) * stxxl::int64(atoi(argv[2])); stxxl::int64 endpos = offset + length; bool do_read = true, do_write = true; if (argc == 4 && (strcmp("r", argv[3]) == 0 || strcmp("R", argv[3]) == 0)) do_write = false; if (argc == 4 && (strcmp("w", argv[3]) == 0 || strcmp("W", argv[3]) == 0)) do_read = false; const unsigned raw_block_size = 8 * MB; const unsigned block_size = raw_block_size / sizeof(int); typedef stxxl::typed_block<raw_block_size, unsigned> block_type; typedef stxxl::BID<raw_block_size> BID_type; unsigned num_blocks_per_step = STXXL_DIVRU(step_size, raw_block_size); step_size = num_blocks_per_step * raw_block_size; block_type* buffer = new block_type[num_blocks_per_step]; request_ptr * reqs = new request_ptr[num_blocks_per_step]; std::vector<BID_type> blocks; double totaltimeread = 0, totaltimewrite = 0; stxxl::int64 totalsizeread = 0, totalsizewrite = 0; std::cout << "# Step size: " << step_size << " bytes (" << num_blocks_per_step << " blocks of " << raw_block_size << " bytes)" << std::endl; //touch data, so it is actually allcoated for (unsigned j = 0; j < num_blocks_per_step; ++j) for (unsigned i = 0; i < block_size; ++i) buffer[j][i] = j * block_size + i; try { STXXL_DEFAULT_ALLOC_STRATEGY alloc; while (offset < endpos) { const stxxl::int64 current_step_size = std::min<stxxl::int64>(step_size, endpos - offset); #if CHECK_AFTER_READ const stxxl::int64 current_step_size_int = current_step_size / sizeof(int); #endif const unsigned current_num_blocks_per_step = STXXL_DIVRU(current_step_size, raw_block_size); std::cout << "Offset " << std::setw(7) << offset / MB << " MiB: " << std::fixed; stxxl::unsigned_type num_total_blocks = blocks.size(); blocks.resize(num_total_blocks + current_num_blocks_per_step); stxxl::block_manager::get_instance()->new_blocks(alloc, blocks.begin() + num_total_blocks, blocks.end()); double begin = timestamp(), end, elapsed; if (do_write) { for (unsigned j = 0; j < current_num_blocks_per_step; j++) reqs[j] = buffer[j].write(blocks[num_total_blocks + j]); wait_all(reqs, current_num_blocks_per_step); end = timestamp(); elapsed = end - begin; totalsizewrite += current_step_size; totaltimewrite += elapsed; } else elapsed = 0.0; std::cout << std::setw(7) << std::setprecision(3) << (double(current_step_size) / MB / elapsed) << " MiB/s write, "; begin = timestamp(); if (do_read) { for (unsigned j = 0; j < current_num_blocks_per_step; j++) reqs[j] = buffer[j].read(blocks[num_total_blocks + j]); wait_all(reqs, current_num_blocks_per_step); end = timestamp(); elapsed = end - begin; totalsizeread += current_step_size; totaltimeread += elapsed; } else elapsed = 0.0; std::cout << std::setw(7) << std::setprecision(3) << (double(current_step_size) / MB / elapsed) << " MiB/s read" << std::endl; #if CHECK_AFTER_READ for (unsigned j = 0; j < current_num_blocks_per_step; j++) { for (unsigned i = 0; i < block_size; i++) { if (buffer[j][i] != j * block_size + i) { int ibuf = i / current_step_size_int; int pos = i % current_step_size_int; std::cout << "Error on disk " << ibuf << " position " << std::hex << std::setw(8) << offset + pos * sizeof(int) << " got: " << std::hex << std::setw(8) << buffer[j][i] << " wanted: " << std::hex << std::setw(8) << (j * block_size + i) << std::dec << std::endl; i = (ibuf + 1) * current_step_size_int; // jump to next } } } #endif offset += current_step_size; } } catch (const std::exception & ex) { std::cout << std::endl; STXXL_ERRMSG(ex.what()); } std::cout << "=============================================================================================" << std::endl; std::cout << "# Average over " << std::setw(7) << totalsizewrite / MB << " MiB: "; std::cout << std::setw(7) << std::setprecision(3) << (double(totalsizewrite) / MB / totaltimewrite) << " MiB/s write, "; std::cout << std::setw(7) << std::setprecision(3) << (double(totalsizeread) / MB / totaltimeread) << " MiB/s read" << std::endl; delete[] reqs; delete[] buffer; return 0; } <commit_msg>Nicer output.<commit_after>/*************************************************************************** * io/benchmark_configured_disks.cpp * * Part of the STXXL. See http://stxxl.sourceforge.net * * Copyright (C) 2009 Johannes Singler <singler@ira.uka.de> * * Distributed under the Boost Software License, Version 1.0. * (See accompanying file LICENSE_1_0.txt or copy at * http://www.boost.org/LICENSE_1_0.txt) **************************************************************************/ /* example gnuplot command for the output of this program: (x-axis: offset in GiB, y-axis: bandwidth in MiB/s) plot \ "disk.log" using ($2/1024):($7) w l title "read", \ "disk.log" using ($2/1024):($4) w l title "write" */ #include <iomanip> #include <vector> #include <stxxl/io> #include <stxxl/mng> #ifndef BOOST_MSVC #include <unistd.h> #endif using stxxl::request_ptr; using stxxl::file; using stxxl::timestamp; #ifdef BLOCK_ALIGN #undef BLOCK_ALIGN #endif #define BLOCK_ALIGN 4096 #define POLL_DELAY 1000 #define CHECK_AFTER_READ 0 #define MB (1024 * 1024) #define GB (1024 * 1024 * 1024) void usage(const char * argv0) { std::cout << "Usage: " << argv0 << " length step [r|w]" << std::endl; std::cout << " 'length' is given in GiB, 'step' size in MiB" << std::endl; std::cout << " length == 0 implies till end of space (please ignore the write error)" << std::endl; exit(-1); } int main(int argc, char * argv[]) { if (argc < 3) usage(argv[0]); stxxl::int64 offset = 0; stxxl::int64 length = stxxl::int64(GB) * stxxl::int64(atoi(argv[1])); stxxl::int64 step_size = stxxl::int64(MB) * stxxl::int64(atoi(argv[2])); stxxl::int64 endpos = offset + length; bool do_read = true, do_write = true; if (argc == 4 && (strcmp("r", argv[3]) == 0 || strcmp("R", argv[3]) == 0)) do_write = false; if (argc == 4 && (strcmp("w", argv[3]) == 0 || strcmp("W", argv[3]) == 0)) do_read = false; const unsigned raw_block_size = 8 * MB; const unsigned block_size = raw_block_size / sizeof(int); typedef stxxl::typed_block<raw_block_size, unsigned> block_type; typedef stxxl::BID<raw_block_size> BID_type; unsigned num_blocks_per_step = STXXL_DIVRU(step_size, raw_block_size); step_size = num_blocks_per_step * raw_block_size; block_type* buffer = new block_type[num_blocks_per_step]; request_ptr * reqs = new request_ptr[num_blocks_per_step]; std::vector<BID_type> blocks; double totaltimeread = 0, totaltimewrite = 0; stxxl::int64 totalsizeread = 0, totalsizewrite = 0; std::cout << "# Step size: " << stxxl::add_IEC_binary_multiplier(step_size, "B") << " (" << num_blocks_per_step << " blocks of " << stxxl::add_IEC_binary_multiplier(raw_block_size, "B") << ")" << std::endl; //touch data, so it is actually allcoated for (unsigned j = 0; j < num_blocks_per_step; ++j) for (unsigned i = 0; i < block_size; ++i) buffer[j][i] = j * block_size + i; try { STXXL_DEFAULT_ALLOC_STRATEGY alloc; while (offset < endpos) { const stxxl::int64 current_step_size = std::min<stxxl::int64>(step_size, endpos - offset); #if CHECK_AFTER_READ const stxxl::int64 current_step_size_int = current_step_size / sizeof(int); #endif const unsigned current_num_blocks_per_step = STXXL_DIVRU(current_step_size, raw_block_size); std::cout << "Offset " << std::setw(7) << offset / MB << " MiB: " << std::fixed; stxxl::unsigned_type num_total_blocks = blocks.size(); blocks.resize(num_total_blocks + current_num_blocks_per_step); stxxl::block_manager::get_instance()->new_blocks(alloc, blocks.begin() + num_total_blocks, blocks.end()); double begin = timestamp(), end, elapsed; if (do_write) { for (unsigned j = 0; j < current_num_blocks_per_step; j++) reqs[j] = buffer[j].write(blocks[num_total_blocks + j]); wait_all(reqs, current_num_blocks_per_step); end = timestamp(); elapsed = end - begin; totalsizewrite += current_step_size; totaltimewrite += elapsed; } else elapsed = 0.0; std::cout << std::setw(5) << std::setprecision(1) << (double(current_step_size) / MB / elapsed) << " MiB/s write, "; begin = timestamp(); if (do_read) { for (unsigned j = 0; j < current_num_blocks_per_step; j++) reqs[j] = buffer[j].read(blocks[num_total_blocks + j]); wait_all(reqs, current_num_blocks_per_step); end = timestamp(); elapsed = end - begin; totalsizeread += current_step_size; totaltimeread += elapsed; } else elapsed = 0.0; std::cout << std::setw(5) << std::setprecision(1) << (double(current_step_size) / MB / elapsed) << " MiB/s read" << std::endl; #if CHECK_AFTER_READ for (unsigned j = 0; j < current_num_blocks_per_step; j++) { for (unsigned i = 0; i < block_size; i++) { if (buffer[j][i] != j * block_size + i) { int ibuf = i / current_step_size_int; int pos = i % current_step_size_int; std::cout << "Error on disk " << ibuf << " position " << std::hex << std::setw(8) << offset + pos * sizeof(int) << " got: " << std::hex << std::setw(8) << buffer[j][i] << " wanted: " << std::hex << std::setw(8) << (j * block_size + i) << std::dec << std::endl; i = (ibuf + 1) * current_step_size_int; // jump to next } } } #endif offset += current_step_size; } } catch (const std::exception & ex) { std::cout << std::endl; STXXL_ERRMSG(ex.what()); } std::cout << "=============================================================================================" << std::endl; std::cout << "# Average over " << std::setw(7) << totalsizewrite / MB << " MiB: "; std::cout << std::setw(5) << std::setprecision(1) << (double(totalsizewrite) / MB / totaltimewrite) << " MiB/s write, "; std::cout << std::setw(5) << std::setprecision(1) << (double(totalsizeread) / MB / totaltimeread) << " MiB/s read" << std::endl; delete[] reqs; delete[] buffer; return 0; } <|endoftext|>
<commit_before>/* * Spatial Computation - Manifestation of Spatial computing. * Copyright © 2014 Pranav Kant * * This code is available to you under Apache License Version 2.0, January * 2014. You can grab a copy of license from the same repository from where you * fetched this code. */ #ifndef SPATIAL_DATAFLOW_HPP #define SPATIAL_DATAFLOW_HPP #include "llvm/Pass.h" #include "llvm/PassManager.h" #include "llvm/IR/Module.h" #include "llvm/IR/Instruction.h" #include "llvm/IR/Instructions.h" #include "llvm/Support/InstIterator.h" #include "llvm/Support/raw_ostream.h" #include <vector> using namespace llvm; template<typename T> class DFG{ T p; public: DFG(T t) : p(t) { } std::string getFunctionName(){ return p->getName(); } T operator*() {return p;} }; template<> struct DOTGraphTraits<DFG<Function*> > : public DefaultDOTGraphTraits{ explicit DOTGraphTraits(bool isSimple=false) : DefaultDOTGraphTraits(isSimple){} static std::string getGraphName(DFG<Function*> F){ return "DFG for function \'" + F.getFunctionName() + "\'"; } static std::string getNodeLabel(Value *v, const DFG<Function*> &F){ Instruction *instr = dyn_cast<Instruction>(v); std::string str; raw_string_ostream rso(str); instr->print(rso); return str; } }; template<> struct GraphTraits<DFG<Function*> > { typedef Value NodeType; typedef Value::use_iterator ChildIteratorType; static NodeType *getEntryNode(Value *G){ return G; } static inline ChildIteratorType child_begin(NodeType *N){ Instruction *instr = dyn_cast<Instruction>(N); return N->use_begin(); } static inline ChildIteratorType child_end(NodeType *N){ return N->use_end(); } typedef inst_iterator nodes_iterator; static nodes_iterator nodes_begin(DFG<Function*> F){ return inst_begin(*F); } static nodes_iterator nodes_end(DFG<Function*> F){ return inst_end(*F); } }; /* class DFGWriter : public GraphWriter<DFG<Function*> > { raw_ostream &O; public: DFGWriter(raw_ostream &o, const DFG<Function*> &F, bool SN); void writeHeader(const std::string &Title); void writeGraph(const std::string &Title=""); }; raw_ostream &WriteDFG(raw_ostream &O, const DFG<Function*> &G, bool shortNames = false, const Twine &Title = ""); */ #endif <commit_msg>silenced compiler warnings<commit_after>/* * Spatial Computation - Manifestation of Spatial computing. * Copyright © 2014 Pranav Kant * * This code is available to you under Apache License Version 2.0, January * 2014. You can grab a copy of license from the same repository from where you * fetched this code. */ #ifndef SPATIAL_DATAFLOW_HPP #define SPATIAL_DATAFLOW_HPP #include "llvm/Pass.h" #include "llvm/PassManager.h" #include "llvm/IR/Module.h" #include "llvm/IR/Instruction.h" #include "llvm/IR/Instructions.h" #include "llvm/Support/InstIterator.h" #include "llvm/Support/raw_ostream.h" #include <vector> using namespace llvm; template<typename T> class DFG{ T p; public: DFG(T t) : p(t) { } std::string getFunctionName(){ return p->getName(); } T operator*() {return p;} }; namespace llvm { template<> struct DOTGraphTraits<DFG<Function*> > : public DefaultDOTGraphTraits{ explicit DOTGraphTraits(bool isSimple=false) : DefaultDOTGraphTraits(isSimple){} static std::string getGraphName(DFG<Function*> F){ return "DFG for function \'" + F.getFunctionName() + "\'"; } static std::string getNodeLabel(Value *v, const DFG<Function*> &F){ Instruction *instr = dyn_cast<Instruction>(v); std::string str; raw_string_ostream rso(str); instr->print(rso); return str; } }; template<> struct GraphTraits<DFG<Function*> > { typedef Value NodeType; typedef Value::use_iterator ChildIteratorType; static NodeType *getEntryNode(Value *G){ return G; } static inline ChildIteratorType child_begin(NodeType *N){ Instruction *instr = dyn_cast<Instruction>(N); return N->use_begin(); } static inline ChildIteratorType child_end(NodeType *N){ return N->use_end(); } typedef inst_iterator nodes_iterator; static nodes_iterator nodes_begin(DFG<Function*> F){ return inst_begin(*F); } static nodes_iterator nodes_end(DFG<Function*> F){ return inst_end(*F); } }; } #endif <|endoftext|>
<commit_before>// ======================================================================== // // Copyright 2009-2020 Intel Corporation // // // // Licensed under the Apache License, Version 2.0 (the "License"); // // you may not use this file except in compliance with the License. // // You may obtain a copy of the License at // // // // http://www.apache.org/licenses/LICENSE-2.0 // // // // Unless required by applicable law or agreed to in writing, software // // distributed under the License is distributed on an "AS IS" BASIS, // // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // // limitations under the License. // // ======================================================================== // #include "../../../external/catch.hpp" #include "../../../../kernels/geometry/sphere_intersector.h" #include "../../../../common/simd/sse.cpp" using namespace embree; namespace __sphere_unit_tests_internal { struct fakeEpilog { fakeEpilog (Ray& ray) : ray_(ray) {} bool operator ()(const vbool<4> & , const sse2::SphereIntersectorHitM<4>& hit) const { ray_.id = -1; for (auto i=0; i<4; ++i) { if (hit.vt[i] > 1.e-5f && hit.vt[i] < ray_.tfar) { ray_.tfar = hit.vt[i]; ray_.id = i; } } return ray_.id != -1; } Ray& ray_; }; } TEST_CASE ("Overlapping spheres with filtering - Issue 676 fix-intersection-epilog-handling", "[spheres]") { sse2::CurvePrecalculations1 pre; vbool<4> valid {true, true, false, false}; Vec3fa org (14.8001127f, -9.01768494f, 3.47012758f); Vec3fa dir (-0.989340246f, -0.0190101117f, -0.144376263f); Ray ray (org, dir); Vec4vf<4> v0; v0.x = vfloat<4>{ 9.66870880f, 10.0441875f, 0.f, 0.f}; v0.y = vfloat<4>{-16.3965702f, -9.69345284f, 0.f, 0.f}; v0.z = vfloat<4>{ 3.93995930f, 3.94893074f, 0.f, 0.f}; v0.w = vfloat<4>{9.f, 9.f, 0.f, 0.f}; __sphere_unit_tests_internal::fakeEpilog epilog (ray); sse2::SphereIntersector1<4>::intersect (valid, ray, pre, v0, epilog); int id = ray.id; REQUIRE (id == 0); REQUIRE (ray.tfar == Approx (10.2983)); } <commit_msg>just some formatting<commit_after>// ======================================================================== // // Copyright 2009-2020 Intel Corporation // // // // Licensed under the Apache License, Version 2.0 (the "License"); // // you may not use this file except in compliance with the License. // // You may obtain a copy of the License at // // // // http://www.apache.org/licenses/LICENSE-2.0 // // // // Unless required by applicable law or agreed to in writing, software // // distributed under the License is distributed on an "AS IS" BASIS, // // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // // limitations under the License. // // ======================================================================== // #include "../../../external/catch.hpp" #include "../../../../kernels/geometry/sphere_intersector.h" #include "../../../../common/simd/sse.cpp" using namespace embree; namespace __sphere_unit_tests_internal { struct fakeEpilog { fakeEpilog (Ray& ray) : ray_(ray) {} bool operator ()(const vbool<4> & , const sse2::SphereIntersectorHitM<4>& hit) const { ray_.id = -1; for (auto i=0; i<4; ++i) { if (hit.vt[i] > 1.e-5f && hit.vt[i] < ray_.tfar) { ray_.tfar = hit.vt[i]; ray_.id = i; } } return ray_.id != -1; } Ray& ray_; }; } TEST_CASE ("Overlapping spheres with filtering - Issue 676 fix-intersection-epilog-handling", "[spheres]") { sse2::CurvePrecalculations1 pre; vbool<4> valid {true, true, false, false}; Vec3fa org (14.8001127f, -9.01768494f, 3.47012758f); Vec3fa dir (-0.989340246f, -0.0190101117f, -0.144376263f); Ray ray (org, dir); Vec4vf<4> v0; v0.x = vfloat<4>{ 9.66870880f, 10.0441875f, 0.f, 0.f}; v0.y = vfloat<4>{-16.3965702f, -9.69345284f, 0.f, 0.f}; v0.z = vfloat<4>{ 3.93995930f, 3.94893074f, 0.f, 0.f}; v0.w = vfloat<4>{9.f, 9.f, 0.f, 0.f}; __sphere_unit_tests_internal::fakeEpilog epilog (ray); sse2::SphereIntersector1<4>::intersect (valid, ray, pre, v0, epilog); int id = ray.id; REQUIRE (id == 0); REQUIRE (ray.tfar == Approx (10.2983)); } <|endoftext|>
<commit_before>#include <stdexcept> #include <sstream> #include <fstream> #include "db-redis.h" #include "types.h" #include "util.h" #define DB_REDIS_HMGET_NUMFIELDS 30 #define REPLY_TYPE_ERR(reply, desc) do { \ throw std::runtime_error(std::string("Unexpected type for " desc ": ") \ + replyTypeStr((reply)->type)); \ } while(0) static inline int64_t stoi64(const std::string &s) { std::stringstream tmp(s); int64_t t; tmp >> t; return t; } static inline std::string i64tos(int64_t i) { std::ostringstream os; os << i; return os.str(); } DBRedis::DBRedis(const std::string &mapdir) { std::ifstream ifs((mapdir + "/world.mt").c_str()); if(!ifs.good()) throw std::runtime_error("Failed to read world.mt"); std::string tmp; tmp = read_setting("redis_address", ifs); ifs.seekg(0); hash = read_setting("redis_hash", ifs); ifs.seekg(0); const char *addr = tmp.c_str(); int port = stoi64(read_setting_default("redis_port", ifs, "6379")); ctx = tmp.find('/') != std::string::npos ? redisConnectUnix(addr) : redisConnect(addr, port); if(!ctx) { throw std::runtime_error("Cannot allocate redis context"); } else if(ctx->err) { std::string err = std::string("Connection error: ") + ctx->errstr; redisFree(ctx); throw std::runtime_error(err); } /* Redis is just a key-value store, so the only optimization we can do * is to cache the block positions that exist in the db. */ loadPosCache(); } DBRedis::~DBRedis() { redisFree(ctx); } std::vector<BlockPos> DBRedis::getBlockPos(BlockPos min, BlockPos max) { std::vector<BlockPos> res; for (const auto &it : posCache) { if (it.first < min.z || it.first >= max.z) continue; for (auto pos2 : it.second) { if (pos2.first < min.x || pos2.first >= max.x) continue; if (pos2.second < min.y || pos2.second >= max.y) continue; res.emplace_back(pos2.first, pos2.second, it.first); } } return res; } const char *DBRedis::replyTypeStr(int type) { switch(type) { case REDIS_REPLY_STATUS: return "REDIS_REPLY_STATUS"; case REDIS_REPLY_ERROR: return "REDIS_REPLY_ERROR"; case REDIS_REPLY_INTEGER: return "REDIS_REPLY_INTEGER"; case REDIS_REPLY_NIL: return "REDIS_REPLY_NIL"; case REDIS_REPLY_STRING: return "REDIS_REPLY_STRING"; case REDIS_REPLY_ARRAY: return "REDIS_REPLY_ARRAY"; default: return "unknown"; } } void DBRedis::loadPosCache() { redisReply *reply; reply = (redisReply*) redisCommand(ctx, "HKEYS %s", hash.c_str()); if(!reply) throw std::runtime_error("Redis command HKEYS failed"); if(reply->type != REDIS_REPLY_ARRAY) REPLY_TYPE_ERR(reply, "HKEYS reply"); for(size_t i = 0; i < reply->elements; i++) { if(reply->element[i]->type != REDIS_REPLY_STRING) REPLY_TYPE_ERR(reply->element[i], "HKEYS subreply"); BlockPos pos = decodeBlockPos(stoi64(reply->element[i]->str)); posCache[pos.z].emplace_back(pos.x, pos.y); } freeReplyObject(reply); } void DBRedis::HMGET(const std::vector<BlockPos> &positions, std::function<void(std::size_t, ustring)> result) { const char *argv[DB_REDIS_HMGET_NUMFIELDS + 2]; argv[0] = "HMGET"; argv[1] = hash.c_str(); std::vector<BlockPos>::const_iterator position = positions.begin(); std::size_t remaining = positions.size(); while (remaining > 0) { const std::size_t batch_size = (remaining > DB_REDIS_HMGET_NUMFIELDS) ? DB_REDIS_HMGET_NUMFIELDS : remaining; redisReply *reply; { // storage to preserve validity of .c_str() std::string keys[batch_size]; for (std::size_t i = 0; i < batch_size; ++i) { keys[i] = i64tos(encodeBlockPos(*position++)); argv[i+2] = keys[i].c_str(); } reply = (redisReply*) redisCommandArgv(ctx, batch_size + 2, argv, NULL); } if(!reply) throw std::runtime_error("Redis command HMGET failed"); if (reply->type != REDIS_REPLY_ARRAY) REPLY_TYPE_ERR(reply, "HMGET reply"); if (reply->elements != batch_size) { freeReplyObject(reply); throw std::runtime_error("HMGET wrong number of elements"); } for (std::size_t i = 0; i < reply->elements; ++i) { redisReply *subreply = reply->element[i]; if (subreply->type == REDIS_REPLY_NIL) continue; else if (subreply->type != REDIS_REPLY_STRING) REPLY_TYPE_ERR(subreply, "HMGET subreply"); if (subreply->len == 0) throw std::runtime_error("HMGET empty string"); result(i, ustring((const unsigned char *) subreply->str, subreply->len)); } freeReplyObject(reply); remaining -= batch_size; } } void DBRedis::getBlocksOnXZ(BlockList &blocks, int16_t x, int16_t z, int16_t min_y, int16_t max_y) { auto it = posCache.find(z); if (it == posCache.cend()) return; std::vector<BlockPos> positions; for (auto pos2 : it->second) { if (pos2.first == x && pos2.second >= min_y && pos2.second < max_y) positions.emplace_back(x, pos2.second, z); } getBlocksByPos(blocks, positions); } void DBRedis::getBlocksByPos(BlockList &blocks, const std::vector<BlockPos> &positions) { auto result = [&] (std::size_t i, ustring data) { blocks.emplace_back(positions[i], std::move(data)); }; HMGET(positions, result); } <commit_msg>Fix another bug in the Redis backend<commit_after>#include <stdexcept> #include <sstream> #include <fstream> #include "db-redis.h" #include "types.h" #include "util.h" #define DB_REDIS_HMGET_NUMFIELDS 30 #define REPLY_TYPE_ERR(reply, desc) do { \ throw std::runtime_error(std::string("Unexpected type for " desc ": ") \ + replyTypeStr((reply)->type)); \ } while(0) static inline int64_t stoi64(const std::string &s) { std::stringstream tmp(s); int64_t t; tmp >> t; return t; } static inline std::string i64tos(int64_t i) { std::ostringstream os; os << i; return os.str(); } DBRedis::DBRedis(const std::string &mapdir) { std::ifstream ifs((mapdir + "/world.mt").c_str()); if(!ifs.good()) throw std::runtime_error("Failed to read world.mt"); std::string tmp; tmp = read_setting("redis_address", ifs); ifs.seekg(0); hash = read_setting("redis_hash", ifs); ifs.seekg(0); const char *addr = tmp.c_str(); int port = stoi64(read_setting_default("redis_port", ifs, "6379")); ctx = tmp.find('/') != std::string::npos ? redisConnectUnix(addr) : redisConnect(addr, port); if(!ctx) { throw std::runtime_error("Cannot allocate redis context"); } else if(ctx->err) { std::string err = std::string("Connection error: ") + ctx->errstr; redisFree(ctx); throw std::runtime_error(err); } /* Redis is just a key-value store, so the only optimization we can do * is to cache the block positions that exist in the db. */ loadPosCache(); } DBRedis::~DBRedis() { redisFree(ctx); } std::vector<BlockPos> DBRedis::getBlockPos(BlockPos min, BlockPos max) { std::vector<BlockPos> res; for (const auto &it : posCache) { if (it.first < min.z || it.first >= max.z) continue; for (auto pos2 : it.second) { if (pos2.first < min.x || pos2.first >= max.x) continue; if (pos2.second < min.y || pos2.second >= max.y) continue; res.emplace_back(pos2.first, pos2.second, it.first); } } return res; } const char *DBRedis::replyTypeStr(int type) { switch(type) { case REDIS_REPLY_STATUS: return "REDIS_REPLY_STATUS"; case REDIS_REPLY_ERROR: return "REDIS_REPLY_ERROR"; case REDIS_REPLY_INTEGER: return "REDIS_REPLY_INTEGER"; case REDIS_REPLY_NIL: return "REDIS_REPLY_NIL"; case REDIS_REPLY_STRING: return "REDIS_REPLY_STRING"; case REDIS_REPLY_ARRAY: return "REDIS_REPLY_ARRAY"; default: return "unknown"; } } void DBRedis::loadPosCache() { redisReply *reply; reply = (redisReply*) redisCommand(ctx, "HKEYS %s", hash.c_str()); if(!reply) throw std::runtime_error("Redis command HKEYS failed"); if(reply->type != REDIS_REPLY_ARRAY) REPLY_TYPE_ERR(reply, "HKEYS reply"); for(size_t i = 0; i < reply->elements; i++) { if(reply->element[i]->type != REDIS_REPLY_STRING) REPLY_TYPE_ERR(reply->element[i], "HKEYS subreply"); BlockPos pos = decodeBlockPos(stoi64(reply->element[i]->str)); posCache[pos.z].emplace_back(pos.x, pos.y); } freeReplyObject(reply); } void DBRedis::HMGET(const std::vector<BlockPos> &positions, std::function<void(std::size_t, ustring)> result) { const char *argv[DB_REDIS_HMGET_NUMFIELDS + 2]; argv[0] = "HMGET"; argv[1] = hash.c_str(); std::vector<BlockPos>::const_iterator position = positions.begin(); std::size_t remaining = positions.size(); std::size_t abs_i = 0; while (remaining > 0) { const std::size_t batch_size = (remaining > DB_REDIS_HMGET_NUMFIELDS) ? DB_REDIS_HMGET_NUMFIELDS : remaining; redisReply *reply; { // storage to preserve validity of .c_str() std::string keys[batch_size]; for (std::size_t i = 0; i < batch_size; ++i) { keys[i] = i64tos(encodeBlockPos(*position++)); argv[i+2] = keys[i].c_str(); } reply = (redisReply*) redisCommandArgv(ctx, batch_size + 2, argv, NULL); } if(!reply) throw std::runtime_error("Redis command HMGET failed"); if (reply->type != REDIS_REPLY_ARRAY) REPLY_TYPE_ERR(reply, "HMGET reply"); if (reply->elements != batch_size) { freeReplyObject(reply); throw std::runtime_error("HMGET wrong number of elements"); } for (std::size_t i = 0; i < reply->elements; ++i) { redisReply *subreply = reply->element[i]; if (subreply->type == REDIS_REPLY_NIL) continue; else if (subreply->type != REDIS_REPLY_STRING) REPLY_TYPE_ERR(subreply, "HMGET subreply"); if (subreply->len == 0) throw std::runtime_error("HMGET empty string"); result(abs_i + i, ustring((const unsigned char *) subreply->str, subreply->len)); } freeReplyObject(reply); abs_i += reply->elements; remaining -= batch_size; } } void DBRedis::getBlocksOnXZ(BlockList &blocks, int16_t x, int16_t z, int16_t min_y, int16_t max_y) { auto it = posCache.find(z); if (it == posCache.cend()) return; std::vector<BlockPos> positions; for (auto pos2 : it->second) { if (pos2.first == x && pos2.second >= min_y && pos2.second < max_y) positions.emplace_back(x, pos2.second, z); } getBlocksByPos(blocks, positions); } void DBRedis::getBlocksByPos(BlockList &blocks, const std::vector<BlockPos> &positions) { auto result = [&] (std::size_t i, ustring data) { blocks.emplace_back(positions[i], std::move(data)); }; HMGET(positions, result); } <|endoftext|>
<commit_before>//-------------------------------------------------------------------------------- // This file is a portion of the Hieroglyph 3 Rendering Engine. It is distributed // under the MIT License, available in the root of this distribution and // at the following URL: // // http://www.opensource.org/licenses/mit-license.php // // Copyright (c) 2003-2010 Jason Zink //-------------------------------------------------------------------------------- //-------------------------------------------------------------------------------- #include "PCH.h" #include "SpriteFontDX11.h" //-------------------------------------------------------------------------------- using namespace Glyph3; using namespace Gdiplus; //-------------------------------------------------------------------------------- SpriteFontDX11::SpriteFontDX11() : m_fSize(0), m_uTexHeight(0), m_fSpaceWidth(0), m_fCharHeight(0) { } //-------------------------------------------------------------------------------- SpriteFontDX11::~SpriteFontDX11() { } //-------------------------------------------------------------------------------- bool SpriteFontDX11::Initialize(LPCWSTR fontName, float fontSize, UINT fontStyle, bool antiAliased ) { m_fSize = fontSize; TextRenderingHint hint = antiAliased ? TextRenderingHintAntiAliasGridFit : TextRenderingHintSystemDefault; // Init GDI+ ULONG_PTR token = NULL; GdiplusStartupInput startupInput (NULL, TRUE, TRUE); GdiplusStartupOutput startupOutput; GdiPlusCall( GdiplusStartup( &token, &startupInput, &startupOutput ) ); // Create the font Gdiplus::Font font( fontName, fontSize, fontStyle, UnitPixel, NULL ); // Check for error during construction GdiPlusCall( font.GetLastStatus() ); // Create a temporary Bitmap and Graphics for figuring out the rough size required // for drawing all of the characters int size = static_cast<int>( fontSize * NumChars * 2 ) + 1; Bitmap sizeBitmap( size, size, PixelFormat32bppARGB ); GdiPlusCall( sizeBitmap.GetLastStatus() ); Graphics sizeGraphics( &sizeBitmap ); GdiPlusCall( sizeGraphics.GetLastStatus() ); GdiPlusCall( sizeGraphics.SetTextRenderingHint( hint ) ); m_fCharHeight = font.GetHeight(&sizeGraphics) * 1.5f; WCHAR allChars[NumChars + 1]; for( WCHAR i = 0; i < NumChars; ++i ) allChars[i] = i + StartChar; allChars[NumChars] = 0; RectF sizeRect; GdiPlusCall( sizeGraphics.MeasureString( allChars, NumChars, &font, PointF( 0, 0 ), &sizeRect ) ); int numRows = static_cast<int>( sizeRect.Width / TexWidth ) + 1; int texHeight = static_cast<int>( numRows * m_fCharHeight ) + 1; // Create a temporary Bitmap and Graphics for drawing the characters one by one int tempSize = static_cast<int>( fontSize * 2 ); Bitmap drawBitmap( tempSize, tempSize, PixelFormat32bppARGB ); GdiPlusCall( drawBitmap.GetLastStatus()); Graphics drawGraphics( &drawBitmap ); GdiPlusCall( drawGraphics.GetLastStatus() ); GdiPlusCall( drawGraphics.SetTextRenderingHint( hint ) ); // Create a temporary Bitmap + Graphics for creating a full character set Bitmap textBitmap ( TexWidth, texHeight, PixelFormat32bppARGB ); GdiPlusCall( textBitmap.GetLastStatus() ); Graphics textGraphics ( &textBitmap ); GdiPlusCall( textGraphics.GetLastStatus() ); GdiPlusCall( textGraphics.Clear( Color( 0, 255, 255, 255 ) ) ); GdiPlusCall( textGraphics.SetCompositingMode( CompositingModeSourceCopy ) ); // Solid brush for text rendering SolidBrush brush ( Color( 255, 255, 255, 255 ) ); GdiPlusCall( brush.GetLastStatus() ); // Draw all of the characters, and copy them to the full character set WCHAR charString [2]; charString[1] = 0; int currentX = 0; int currentY = 0; for(UINT64 i = 0; i < NumChars; ++i) { charString[0] = static_cast<WCHAR>(i + StartChar); // Draw the character GdiPlusCall( drawGraphics.Clear( Color( 0, 255, 255, 255 ) ) ); GdiPlusCall( drawGraphics.DrawString( charString, 1, &font, PointF( 0, 0 ), &brush ) ); // Figure out the amount of blank space before the character int minX = 0; for( int x = 0; x < tempSize; ++x ) { for( int y = 0; y < tempSize; ++y ) { Color color; GdiPlusCall( drawBitmap.GetPixel( x, y, &color ) ); if( color.GetAlpha() > 0 ) { minX = x; x = tempSize; break; } } } // Figure out the amount of blank space after the character int maxX = tempSize - 1; for( int x = tempSize - 1; x >= 0; --x ) { for( int y = 0; y < tempSize; ++y ) { Color color; GdiPlusCall( drawBitmap.GetPixel( x, y, &color ) ); if( color.GetAlpha() > 0 ) { maxX = x; x = -1; break; } } } int charWidth = maxX - minX + 1; // Figure out if we need to move to the next row if ( currentX + charWidth >= TexWidth ) { currentX = 0; currentY += static_cast<int>( m_fCharHeight ) + 1; } // Fill out the structure describing the character position m_CharDescs[i].X = static_cast<float>( currentX ); m_CharDescs[i].Y = static_cast<float>( currentY ); m_CharDescs[i].Width = static_cast<float>( charWidth ); m_CharDescs[i].Height = static_cast<float>( m_fCharHeight ); // Copy the character over int height = static_cast<int>( m_fCharHeight + 1 ); GdiPlusCall(textGraphics.DrawImage( &drawBitmap, currentX, currentY, minX, 0, charWidth, height, UnitPixel ) ); currentX += charWidth + 1; } // Figure out the width of a space character charString[0] = ' '; charString[1] = 0; GdiPlusCall(drawGraphics.MeasureString( charString, 1, &font, PointF( 0, 0 ), &sizeRect ) ); m_fSpaceWidth = sizeRect.Width; // Lock the bitmap for direct memory access BitmapData bmData; GdiPlusCall(textBitmap.LockBits( &Rect( 0, 0, TexWidth, texHeight ), ImageLockModeRead, PixelFormat32bppARGB, &bmData ) ); // Create a D3D texture, initalized with the bitmap data D3D11_TEXTURE2D_DESC texDesc; texDesc.Width = TexWidth; texDesc.Height = texHeight; texDesc.MipLevels = 1; texDesc.ArraySize = 1; texDesc.Format = DXGI_FORMAT_B8G8R8A8_UNORM; texDesc.SampleDesc.Count = 1; texDesc.SampleDesc.Quality = 0; texDesc.Usage = D3D11_USAGE_IMMUTABLE; texDesc.BindFlags = D3D11_BIND_SHADER_RESOURCE; texDesc.CPUAccessFlags = 0; texDesc.MiscFlags = 0; Texture2dConfigDX11 config; config.SetDefaults(); config.SetArraySize( 1 ); config.SetBindFlags( D3D11_BIND_SHADER_RESOURCE ); config.SetCPUAccessFlags( 0 ); config.SetFormat( DXGI_FORMAT_B8G8R8A8_UNORM ); config.SetWidth( TexWidth ); config.SetHeight( texHeight ); config.SetMipLevels( 1 ); config.SetMiscFlags( 0 ); DXGI_SAMPLE_DESC sampleDesc; sampleDesc.Count = 1; sampleDesc.Quality = 0; config.SetSampleDesc( sampleDesc ); config.SetUsage( D3D11_USAGE_IMMUTABLE ); D3D11_SUBRESOURCE_DATA data; data.pSysMem = bmData.Scan0; data.SysMemPitch = TexWidth * 4; data.SysMemSlicePitch = 0; // Get the renderer RendererDX11* renderer = RendererDX11::Get(); // Create the texture m_pTexture = renderer->CreateTexture2D( &config, &data ); // Unlock the bitmap GdiPlusCall( textBitmap.UnlockBits( &bmData ) ); return true; } //-------------------------------------------------------------------------------- int SpriteFontDX11::SRViewResource() const { return m_iSRView; } //-------------------------------------------------------------------------------- const SpriteFontDX11::CharDesc* SpriteFontDX11::CharDescriptors() const { return m_CharDescs; } //-------------------------------------------------------------------------------- const SpriteFontDX11::CharDesc& SpriteFontDX11::GetCharDescriptor(WCHAR character) const { _ASSERT(character >= StartChar && character <= EndChar); return m_CharDescs[character - StartChar]; } //-------------------------------------------------------------------------------- float SpriteFontDX11::Size() const { return m_fSize; } //-------------------------------------------------------------------------------- UINT SpriteFontDX11::TextureWidth() const { return TexWidth; } //-------------------------------------------------------------------------------- UINT SpriteFontDX11::TextureHeight() const { return m_uTexHeight; } //-------------------------------------------------------------------------------- float SpriteFontDX11::SpaceWidth() const { return m_fSpaceWidth; } //-------------------------------------------------------------------------------- float SpriteFontDX11::CharHeight() const { return m_fCharHeight; } //-------------------------------------------------------------------------------- ResourcePtr SpriteFontDX11::TextureResource() const { return m_pTexture; } //--------------------------------------------------------------------------------<commit_msg>- Fixed non-antialiased font generation<commit_after>//-------------------------------------------------------------------------------- // This file is a portion of the Hieroglyph 3 Rendering Engine. It is distributed // under the MIT License, available in the root of this distribution and // at the following URL: // // http://www.opensource.org/licenses/mit-license.php // // Copyright (c) 2003-2010 Jason Zink //-------------------------------------------------------------------------------- //-------------------------------------------------------------------------------- #include "PCH.h" #include "SpriteFontDX11.h" //-------------------------------------------------------------------------------- using namespace Glyph3; using namespace Gdiplus; //-------------------------------------------------------------------------------- SpriteFontDX11::SpriteFontDX11() : m_fSize(0), m_uTexHeight(0), m_fSpaceWidth(0), m_fCharHeight(0) { } //-------------------------------------------------------------------------------- SpriteFontDX11::~SpriteFontDX11() { } //-------------------------------------------------------------------------------- bool SpriteFontDX11::Initialize(LPCWSTR fontName, float fontSize, UINT fontStyle, bool antiAliased ) { m_fSize = fontSize; TextRenderingHint hint = antiAliased ? TextRenderingHintAntiAliasGridFit : TextRenderingHintSingleBitPerPixelGridFit; // Init GDI+ ULONG_PTR token = NULL; GdiplusStartupInput startupInput (NULL, TRUE, TRUE); GdiplusStartupOutput startupOutput; GdiPlusCall( GdiplusStartup( &token, &startupInput, &startupOutput ) ); // Create the font Gdiplus::Font font( fontName, fontSize, fontStyle, UnitPixel, NULL ); // Check for error during construction GdiPlusCall( font.GetLastStatus() ); // Create a temporary Bitmap and Graphics for figuring out the rough size required // for drawing all of the characters int size = static_cast<int>( fontSize * NumChars * 2 ) + 1; Bitmap sizeBitmap( size, size, PixelFormat32bppARGB ); GdiPlusCall( sizeBitmap.GetLastStatus() ); Graphics sizeGraphics( &sizeBitmap ); GdiPlusCall( sizeGraphics.GetLastStatus() ); GdiPlusCall( sizeGraphics.SetTextRenderingHint( hint ) ); m_fCharHeight = font.GetHeight(&sizeGraphics) * 1.5f; WCHAR allChars[NumChars + 1]; for( WCHAR i = 0; i < NumChars; ++i ) allChars[i] = i + StartChar; allChars[NumChars] = 0; RectF sizeRect; GdiPlusCall( sizeGraphics.MeasureString( allChars, NumChars, &font, PointF( 0, 0 ), &sizeRect ) ); int numRows = static_cast<int>( sizeRect.Width / TexWidth ) + 1; int texHeight = static_cast<int>( numRows * m_fCharHeight ) + 1; // Create a temporary Bitmap and Graphics for drawing the characters one by one int tempSize = static_cast<int>( fontSize * 2 ); Bitmap drawBitmap( tempSize, tempSize, PixelFormat32bppARGB ); GdiPlusCall( drawBitmap.GetLastStatus()); Graphics drawGraphics( &drawBitmap ); GdiPlusCall( drawGraphics.GetLastStatus() ); GdiPlusCall( drawGraphics.SetTextRenderingHint( hint ) ); // Create a temporary Bitmap + Graphics for creating a full character set Bitmap textBitmap ( TexWidth, texHeight, PixelFormat32bppARGB ); GdiPlusCall( textBitmap.GetLastStatus() ); Graphics textGraphics ( &textBitmap ); GdiPlusCall( textGraphics.GetLastStatus() ); GdiPlusCall( textGraphics.Clear( Color( 0, 255, 255, 255 ) ) ); GdiPlusCall( textGraphics.SetCompositingMode( CompositingModeSourceCopy ) ); // Solid brush for text rendering SolidBrush brush ( Color( 255, 255, 255, 255 ) ); GdiPlusCall( brush.GetLastStatus() ); // Draw all of the characters, and copy them to the full character set WCHAR charString [2]; charString[1] = 0; int currentX = 0; int currentY = 0; for(UINT64 i = 0; i < NumChars; ++i) { charString[0] = static_cast<WCHAR>(i + StartChar); // Draw the character GdiPlusCall( drawGraphics.Clear( Color( 0, 255, 255, 255 ) ) ); GdiPlusCall( drawGraphics.DrawString( charString, 1, &font, PointF( 0, 0 ), &brush ) ); // Figure out the amount of blank space before the character int minX = 0; for( int x = 0; x < tempSize; ++x ) { for( int y = 0; y < tempSize; ++y ) { Color color; GdiPlusCall( drawBitmap.GetPixel( x, y, &color ) ); if( color.GetAlpha() > 0 ) { minX = x; x = tempSize; break; } } } // Figure out the amount of blank space after the character int maxX = tempSize - 1; for( int x = tempSize - 1; x >= 0; --x ) { for( int y = 0; y < tempSize; ++y ) { Color color; GdiPlusCall( drawBitmap.GetPixel( x, y, &color ) ); if( color.GetAlpha() > 0 ) { maxX = x; x = -1; break; } } } int charWidth = maxX - minX + 1; // Figure out if we need to move to the next row if ( currentX + charWidth >= TexWidth ) { currentX = 0; currentY += static_cast<int>( m_fCharHeight ) + 1; } // Fill out the structure describing the character position m_CharDescs[i].X = static_cast<float>( currentX ); m_CharDescs[i].Y = static_cast<float>( currentY ); m_CharDescs[i].Width = static_cast<float>( charWidth ); m_CharDescs[i].Height = static_cast<float>( m_fCharHeight ); // Copy the character over int height = static_cast<int>( m_fCharHeight + 1 ); GdiPlusCall(textGraphics.DrawImage( &drawBitmap, currentX, currentY, minX, 0, charWidth, height, UnitPixel ) ); currentX += charWidth + 1; } // Figure out the width of a space character charString[0] = ' '; charString[1] = 0; GdiPlusCall(drawGraphics.MeasureString( charString, 1, &font, PointF( 0, 0 ), &sizeRect ) ); m_fSpaceWidth = sizeRect.Width; // Lock the bitmap for direct memory access BitmapData bmData; GdiPlusCall(textBitmap.LockBits( &Rect( 0, 0, TexWidth, texHeight ), ImageLockModeRead, PixelFormat32bppARGB, &bmData ) ); // Create a D3D texture, initalized with the bitmap data D3D11_TEXTURE2D_DESC texDesc; texDesc.Width = TexWidth; texDesc.Height = texHeight; texDesc.MipLevels = 1; texDesc.ArraySize = 1; texDesc.Format = DXGI_FORMAT_B8G8R8A8_UNORM; texDesc.SampleDesc.Count = 1; texDesc.SampleDesc.Quality = 0; texDesc.Usage = D3D11_USAGE_IMMUTABLE; texDesc.BindFlags = D3D11_BIND_SHADER_RESOURCE; texDesc.CPUAccessFlags = 0; texDesc.MiscFlags = 0; Texture2dConfigDX11 config; config.SetDefaults(); config.SetArraySize( 1 ); config.SetBindFlags( D3D11_BIND_SHADER_RESOURCE ); config.SetCPUAccessFlags( 0 ); config.SetFormat( DXGI_FORMAT_B8G8R8A8_UNORM ); config.SetWidth( TexWidth ); config.SetHeight( texHeight ); config.SetMipLevels( 1 ); config.SetMiscFlags( 0 ); DXGI_SAMPLE_DESC sampleDesc; sampleDesc.Count = 1; sampleDesc.Quality = 0; config.SetSampleDesc( sampleDesc ); config.SetUsage( D3D11_USAGE_IMMUTABLE ); D3D11_SUBRESOURCE_DATA data; data.pSysMem = bmData.Scan0; data.SysMemPitch = TexWidth * 4; data.SysMemSlicePitch = 0; // Get the renderer RendererDX11* renderer = RendererDX11::Get(); // Create the texture m_pTexture = renderer->CreateTexture2D( &config, &data ); // Unlock the bitmap GdiPlusCall( textBitmap.UnlockBits( &bmData ) ); return true; } //-------------------------------------------------------------------------------- int SpriteFontDX11::SRViewResource() const { return m_iSRView; } //-------------------------------------------------------------------------------- const SpriteFontDX11::CharDesc* SpriteFontDX11::CharDescriptors() const { return m_CharDescs; } //-------------------------------------------------------------------------------- const SpriteFontDX11::CharDesc& SpriteFontDX11::GetCharDescriptor(WCHAR character) const { _ASSERT(character >= StartChar && character <= EndChar); return m_CharDescs[character - StartChar]; } //-------------------------------------------------------------------------------- float SpriteFontDX11::Size() const { return m_fSize; } //-------------------------------------------------------------------------------- UINT SpriteFontDX11::TextureWidth() const { return TexWidth; } //-------------------------------------------------------------------------------- UINT SpriteFontDX11::TextureHeight() const { return m_uTexHeight; } //-------------------------------------------------------------------------------- float SpriteFontDX11::SpaceWidth() const { return m_fSpaceWidth; } //-------------------------------------------------------------------------------- float SpriteFontDX11::CharHeight() const { return m_fCharHeight; } //-------------------------------------------------------------------------------- ResourcePtr SpriteFontDX11::TextureResource() const { return m_pTexture; } //--------------------------------------------------------------------------------<|endoftext|>
<commit_before>//////////////////////////////////////////////////////////////////////////////// // // File: ProcessExtractSurf.cpp // // For more information, please see: http://www.nektar.info/ // // The MIT License // // Copyright (c) 2006 Division of Applied Mathematics, Brown University (USA), // Department of Aeronautics, Imperial College London (UK), and Scientific // Computing and Imaging Institute, University of Utah (USA). // // 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. // // Description: Extract one or more surfaces from mesh. // //////////////////////////////////////////////////////////////////////////////// #include "MeshElements.h" #include "ProcessScalar.h" #include <SpatialDomains/MeshGraph.h> #include <LocalRegions/QuadExp.h> #include <LibUtilities/Interpreter/AnalyticExpressionEvaluator.hpp> #include <LibUtilities/Foundations/ManagerAccess.h> #include <vector> using namespace std; namespace Nektar { namespace Utilities { ModuleKey ProcessScalar::className = GetModuleFactory().RegisterCreatorFunction( ModuleKey(eProcessModule, "scalar"), ProcessScalar::create, "Impose a scalar function z=f(x,y) on a surface."); ProcessScalar::ProcessScalar(MeshSharedPtr m) : ProcessModule(m) { m_config["surf"] = ConfigOption(false, "-1", "Tag identifying surface/composite to process."); m_config["nq"] = ConfigOption(false, "-1", "Number of quadrature points to generate."); m_config["scalar"] = ConfigOption(false, "", "Expression to evaluate."); } ProcessScalar::~ProcessScalar() { } void ProcessScalar::Process() { int i, j, k; string surf = m_config["surf"].as<string>(); // Obtain vector of surface IDs from string. vector<unsigned int> surfs; ParseUtils::GenerateSeqVector(surf.c_str(), surfs); sort(surfs.begin(), surfs.end()); // If we're running in verbose mode print out a list of surfaces. if (m_mesh->m_verbose) { cout << "ProcessScalar: extracting surface" << (surfs.size() > 1 ? "s" : "") << " " << surf << endl; } const int nq = m_config["nq"].as<int>(); const int nTot = nq*nq; string expr = m_config["scalar"].as<string>(); LibUtilities::AnalyticExpressionEvaluator rEval; int rExprId = rEval.DefineFunction("x y z", expr); // Make a copy of all existing elements of one dimension lower. vector<ElementSharedPtr> el = m_mesh->m_element[m_mesh->m_expDim-1]; // Iterate over list of surface elements. for (i = 0; i < el.size(); ++i) { // Work out whether this lies on our surface of interest. vector<int> inter, tags = el[i]->GetTagList(); sort(tags.begin(), tags.end()); set_intersection(surfs.begin(), surfs.end(), tags .begin(), tags .end(), back_inserter(inter)); // It doesn't continue to next element. if (inter.size() != 1) { continue; } // Grab face link. FaceSharedPtr f = el[i]->GetFaceLink(); #if 0 LibUtilities::BasisKey C0( LibUtilities::eModified_A, nq, LibUtilities::PointsKey( nq, LibUtilities::eGaussLobattoLegendre)); LocalRegions::QuadExpSharedPtr quad = MemoryManager<LocalRegions::QuadExp>::AllocateSharedPtr( C0, C0, boost::dynamic_pointer_cast<SpatialDomains::QuadGeom>(f->GetGeom(m_mesh->m_spaceDim))); // Get coordinates of face Array<OneD, NekDouble> xc(nTot), yc(nTot), zc(nTot); quad->GetCoords(xc, yc, zc); #endif const int edge[4][2] = {{0,1}, {nq-1, nq}, {nq*nq-1, -1}, {nq*(nq-1), -nq}}; // Update vertices for (j = 0; j < 4; ++j) { NodeSharedPtr n = f->m_vertexList[j]; n->m_z = rEval.Evaluate(rExprId, n->m_x, n->m_y, 0.0, 0.0); } // Put curvature into edges for (j = 0; j < f->m_edgeList.size(); ++j) { NodeSharedPtr n1 = f->m_edgeList[j]->m_n1; NodeSharedPtr n2 = f->m_edgeList[j]->m_n2; Node disp = *n2-*n1; f->m_edgeList[j]->m_edgeNodes.clear(); for (k = 1; k < nq-1; ++k) { Node n = *n1 + disp * k / (nq-1.0); n.m_z = rEval.Evaluate(rExprId, n.m_x, n.m_y, 0.0, 0.0); f->m_edgeList[j]->m_edgeNodes.push_back( NodeSharedPtr(new Node(n))); } } } } } } <commit_msg>Slight change for the xml creation<commit_after>//////////////////////////////////////////////////////////////////////////////// // // File: ProcessExtractSurf.cpp // // For more information, please see: http://www.nektar.info/ // // The MIT License // // Copyright (c) 2006 Division of Applied Mathematics, Brown University (USA), // Department of Aeronautics, Imperial College London (UK), and Scientific // Computing and Imaging Institute, University of Utah (USA). // // 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. // // Description: Extract one or more surfaces from mesh. // //////////////////////////////////////////////////////////////////////////////// #include "MeshElements.h" #include "ProcessScalar.h" #include <SpatialDomains/MeshGraph.h> #include <LocalRegions/QuadExp.h> #include <LibUtilities/Interpreter/AnalyticExpressionEvaluator.hpp> #include <LibUtilities/Foundations/ManagerAccess.h> #include <vector> using namespace std; namespace Nektar { namespace Utilities { ModuleKey ProcessScalar::className = GetModuleFactory().RegisterCreatorFunction( ModuleKey(eProcessModule, "scalar"), ProcessScalar::create, "Impose a scalar function z=f(x,y) on a surface."); ProcessScalar::ProcessScalar(MeshSharedPtr m) : ProcessModule(m) { m_config["surf"] = ConfigOption(false, "-1", "Tag identifying surface/composite to process."); m_config["nq"] = ConfigOption(false, "-1", "Number of quadrature points to generate."); m_config["scalar"] = ConfigOption(false, "", "Expression to evaluate."); } ProcessScalar::~ProcessScalar() { } void ProcessScalar::Process() { int i, j, k; string surf = m_config["surf"].as<string>(); // Obtain vector of surface IDs from string. vector<unsigned int> surfs; ParseUtils::GenerateSeqVector(surf.c_str(), surfs); sort(surfs.begin(), surfs.end()); // If we're running in verbose mode print out a list of surfaces. if (m_mesh->m_verbose) { cout << "ProcessScalar: extracting surface" << (surfs.size() > 1 ? "s" : "") << " " << surf << endl; } const int nq = m_config["nq"].as<int>(); const int nTot = nq*nq; string expr = m_config["scalar"].as<string>(); LibUtilities::AnalyticExpressionEvaluator rEval; int rExprId = rEval.DefineFunction("x y z", expr); // Make a copy of all existing elements of one dimension lower. vector<ElementSharedPtr> el = m_mesh->m_element[m_mesh->m_expDim-1]; // Iterate over list of surface elements. for (i = 0; i < el.size(); ++i) { // Work out whether this lies on our surface of interest. vector<int> inter, tags = el[i]->GetTagList(); sort(tags.begin(), tags.end()); set_intersection(surfs.begin(), surfs.end(), tags .begin(), tags .end(), back_inserter(inter)); // It doesn't continue to next element. if (inter.size() != 1) { continue; } // Grab face link. FaceSharedPtr f = el[i]->GetFaceLink(); #if 0 LibUtilities::BasisKey C0( LibUtilities::eModified_A, nq, LibUtilities::PointsKey( nq, LibUtilities::eGaussLobattoLegendre)); LocalRegions::QuadExpSharedPtr quad = MemoryManager<LocalRegions::QuadExp>::AllocateSharedPtr( C0, C0, boost::dynamic_pointer_cast<SpatialDomains::QuadGeom>(f->GetGeom(m_mesh->m_spaceDim))); // Get coordinates of face Array<OneD, NekDouble> xc(nTot), yc(nTot), zc(nTot); quad->GetCoords(xc, yc, zc); #endif const int edge[4][2] = {{0,1}, {nq-1, nq}, {nq*nq-1, -1}, {nq*(nq-1), -nq}}; // Update vertices for (j = 0; j < 4; ++j) { NodeSharedPtr n = f->m_vertexList[j]; n->m_z = rEval.Evaluate(rExprId, n->m_x, n->m_y, 0.0, 0.0); if (n->m_z < 1e-32) { n->m_z = 0; } } // Put curvature into edges for (j = 0; j < f->m_edgeList.size(); ++j) { NodeSharedPtr n1 = f->m_edgeList[j]->m_n1; NodeSharedPtr n2 = f->m_edgeList[j]->m_n2; Node disp = *n2-*n1; f->m_edgeList[j]->m_edgeNodes.clear(); for (k = 1; k < nq-1; ++k) { Node n = *n1 + disp * k / (nq-1.0); n.m_z = rEval.Evaluate(rExprId, n.m_x, n.m_y, 0.0, 0.0); if (n.m_z < 1e-32) { n.m_z = 0; } f->m_edgeList[j]->m_edgeNodes.push_back( NodeSharedPtr(new Node(n))); } } } } } } <|endoftext|>
<commit_before>// Copyright (c) 2013-2019 The Syscoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <validation.h> #include <services/asset.h> #include <services/assetconsensus.h> #include <consensus/validation.h> #include <dbwrapper.h> #include <rpc/util.h> #include <univalue.h> std::string stringFromSyscoinTx(const int &nVersion) { switch (nVersion) { case SYSCOIN_TX_VERSION_ASSET_ACTIVATE: return "assetactivate"; case SYSCOIN_TX_VERSION_ASSET_UPDATE: return "assetupdate"; case SYSCOIN_TX_VERSION_ASSET_SEND: return "assetsend"; case SYSCOIN_TX_VERSION_ALLOCATION_SEND: return "assetallocationsend"; case SYSCOIN_TX_VERSION_ALLOCATION_BURN_TO_ETHEREUM: return "assetallocationburntoethereum"; case SYSCOIN_TX_VERSION_ALLOCATION_BURN_TO_SYSCOIN: return "assetallocationburntosyscoin"; case SYSCOIN_TX_VERSION_SYSCOIN_BURN_TO_ALLOCATION: return "syscoinburntoassetallocation"; case SYSCOIN_TX_VERSION_ALLOCATION_MINT: return "assetallocationmint"; default: return "<unknown assetallocation op>"; } } std::vector<unsigned char> vchFromString(const std::string &str) { unsigned char *strbeg = (unsigned char*)str.c_str(); return std::vector<unsigned char>(strbeg, strbeg + str.size()); } std::string stringFromVch(const std::vector<unsigned char> &vch) { std::string res; std::vector<unsigned char>::const_iterator vi = vch.begin(); while (vi != vch.end()) { res += (char)(*vi); vi++; } return res; } bool CAsset::UnserializeFromData(const std::vector<unsigned char> &vchData) { try { CDataStream dsAsset(vchData, SER_NETWORK, PROTOCOL_VERSION); Unserialize(dsAsset); } catch (std::exception &e) { SetNull(); return false; } return true; } bool CAsset::UnserializeFromTx(const CTransaction &tx) { std::vector<unsigned char> vchData; int nOut; if (!GetSyscoinData(tx, vchData, nOut)) { SetNull(); return false; } if(!UnserializeFromData(vchData)) { SetNull(); return false; } return true; } uint32_t GenerateSyscoinGuid(const COutPoint& outPoint) { arith_uint256 txidArith = UintToArith256(outPoint.hash); txidArith += outPoint.n; return txidArith.GetLow32(); } void CAsset::SerializeData( std::vector<unsigned char> &vchData) { CDataStream dsAsset(SER_NETWORK, PROTOCOL_VERSION); Serialize(dsAsset); vchData = std::vector<unsigned char>(dsAsset.begin(), dsAsset.end()); } bool GetAsset(const uint32_t &nAsset, CAsset& txPos) { if (!passetdb || !passetdb->ReadAsset(nAsset, txPos)) return false; return true; } bool CheckTxInputsAssets(const CTransaction &tx, TxValidationState &state, const uint32_t &nAsset, std::unordered_map<uint32_t, std::pair<bool, CAmount> > &mapAssetIn, const std::unordered_map<uint32_t, std::pair<bool, CAmount> > &mapAssetOut) { if (mapAssetOut.empty()) { return state.Invalid(TxValidationResult::TX_CONSENSUS, "bad-txns-asset-outputs-empty"); } std::unordered_map<uint32_t, std::pair<bool, CAmount> >::const_iterator itOut; const bool &isNoInput = IsSyscoinWithNoInputTx(tx.nVersion); if(isNoInput) { itOut = mapAssetOut.find(nAsset); if (itOut == mapAssetOut.end()) { return state.Invalid(TxValidationResult::TX_CONSENSUS, "bad-txns-asset-output-first-asset-not-found"); } } // case 1: asset send without zero val input, covered by this check // case 2: asset send with zero val of another asset, covered by mapAssetIn != mapAssetOut // case 3: asset send with multiple zero val input/output, covered by GetAssetValueOut() for output and CheckTxInputs() for input // case 4: asset send sending assets without inputs of those assets, covered by this check + mapAssetIn != mapAssetOut if (tx.nVersion == SYSCOIN_TX_VERSION_ASSET_SEND) { if (mapAssetIn.empty()) { return state.Invalid(TxValidationResult::TX_CONSENSUS, "bad-txns-assetsend-inputs-empty"); } auto itIn = mapAssetIn.find(nAsset); if (itIn == mapAssetIn.end()) { return state.Invalid(TxValidationResult::TX_CONSENSUS, "bad-txns-assetsend-input-first-asset-not-found"); } // check that the first input asset and first output asset match // note that we only care about first asset because below we will end up enforcing in == out for the rest if (itIn->first != itOut->first) { return state.Invalid(TxValidationResult::TX_CONSENSUS, "bad-txns-assetsend-guid-mismatch"); } // check that the first input asset has zero val input spent if (!itIn->second.first) { return state.Invalid(TxValidationResult::TX_CONSENSUS, "bad-txns-assetsend-missing-zero-val-input"); } // check that the first output asset has zero val output if (!itOut->second.first) { return state.Invalid(TxValidationResult::TX_CONSENSUS, "bad-txns-assetsend-missing-zero-val-output"); } } // asset send also falls into this so for the first out we need to check for asset send seperately above if (isNoInput) { // add first asset out to in so it matches, the rest should be the same // the first one is verified by checksyscoininputs() later on (part of asset send is also) // emplace will add if it doesn't exist or update it below auto it = mapAssetIn.emplace(nAsset, std::make_pair(itOut->second.first, itOut->second.second)); if (!it.second) { it.first->second = std::make_pair(itOut->second.first, itOut->second.second); } } // this will check that all assets with inputs match amounts being sent on outputs // it will also ensure that inputs and outputs per asset are equal with respects to zero-val inputs/outputs (asset ownership utxos) if (mapAssetIn != mapAssetOut) { return state.Invalid(TxValidationResult::TX_CONSENSUS, "bad-txns-assetsend-io-mismatch"); } return true; } CAuxFeeDetails::CAuxFeeDetails(const UniValue& value, const uint8_t &nPrecision){ if(!value.isObject()) { SetNull(); return; } const UniValue& arrObj = find_value(value.get_obj(), "fee_struct"); if(!arrObj.isArray()) { SetNull(); return; } const UniValue& arr = arrObj.get_array(); for (size_t i = 0; i < arr.size(); ++i) { const UniValue& auxFeeObj = arr[i]; if(!auxFeeObj.isArray()) { SetNull(); return; } const UniValue& auxFeeArr = auxFeeObj.get_array(); if(auxFeeArr.size() != 2 || (!auxFeeArr[0].isNum() && !auxFeeArr[0].isStr()) || !auxFeeArr[1].isStr()) { SetNull(); return; } double fPct; if(ParseDouble(auxFeeArr[1].get_str(), &fPct) && fPct <= 65.535){ const uint16_t& nPercent = (uint16_t)(fPct*100000); vecAuxFees.push_back(CAuxFee(AssetAmountFromValue(auxFeeArr[0], nPrecision), nPercent)); } else { SetNull(); return; } } } UniValue CAuxFeeDetails::ToJson() const { UniValue value(UniValue::VOBJ); UniValue feeStruct(UniValue::VARR); for(const auto& auxfee: vecAuxFees) { UniValue auxfeeArr(UniValue::VARR); auxfeeArr.push_back(auxfee.nBound); auxfeeArr.push_back(auxfee.nPercent); feeStruct.push_back(auxfeeArr); } value.pushKV("fee_struct", feeStruct); return value; } CNotaryDetails::CNotaryDetails(const UniValue& value){ if(!value.isObject()) { SetNull(); return; } const UniValue& endpointObj = find_value(value.get_obj(), "endpoint"); if(!endpointObj.isStr()) { SetNull(); return; } strEndPoint = EncodeBase64(endpointObj.get_str()); const UniValue& isObj = find_value(value.get_obj(), "instant_transfers"); if(!isObj.isBool()) { SetNull(); return; } bEnableInstantTransfers = isObj.get_bool()? 1: 0; const UniValue& hdObj = find_value(value.get_obj(), "hd_required"); if(!hdObj.isBool()) { SetNull(); return; } bRequireHD = hdObj.get_bool()? 1: 0; } UniValue CNotaryDetails::ToJson() const { UniValue value(UniValue::VOBJ); value.pushKV("endpoint", DecodeBase64(strEndPoint)); value.pushKV("instant_transfers", bEnableInstantTransfers); value.pushKV("hd_required", bRequireHD); return value; }<commit_msg>fix pct<commit_after>// Copyright (c) 2013-2019 The Syscoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <validation.h> #include <services/asset.h> #include <services/assetconsensus.h> #include <consensus/validation.h> #include <dbwrapper.h> #include <rpc/util.h> #include <univalue.h> std::string stringFromSyscoinTx(const int &nVersion) { switch (nVersion) { case SYSCOIN_TX_VERSION_ASSET_ACTIVATE: return "assetactivate"; case SYSCOIN_TX_VERSION_ASSET_UPDATE: return "assetupdate"; case SYSCOIN_TX_VERSION_ASSET_SEND: return "assetsend"; case SYSCOIN_TX_VERSION_ALLOCATION_SEND: return "assetallocationsend"; case SYSCOIN_TX_VERSION_ALLOCATION_BURN_TO_ETHEREUM: return "assetallocationburntoethereum"; case SYSCOIN_TX_VERSION_ALLOCATION_BURN_TO_SYSCOIN: return "assetallocationburntosyscoin"; case SYSCOIN_TX_VERSION_SYSCOIN_BURN_TO_ALLOCATION: return "syscoinburntoassetallocation"; case SYSCOIN_TX_VERSION_ALLOCATION_MINT: return "assetallocationmint"; default: return "<unknown assetallocation op>"; } } std::vector<unsigned char> vchFromString(const std::string &str) { unsigned char *strbeg = (unsigned char*)str.c_str(); return std::vector<unsigned char>(strbeg, strbeg + str.size()); } std::string stringFromVch(const std::vector<unsigned char> &vch) { std::string res; std::vector<unsigned char>::const_iterator vi = vch.begin(); while (vi != vch.end()) { res += (char)(*vi); vi++; } return res; } bool CAsset::UnserializeFromData(const std::vector<unsigned char> &vchData) { try { CDataStream dsAsset(vchData, SER_NETWORK, PROTOCOL_VERSION); Unserialize(dsAsset); } catch (std::exception &e) { SetNull(); return false; } return true; } bool CAsset::UnserializeFromTx(const CTransaction &tx) { std::vector<unsigned char> vchData; int nOut; if (!GetSyscoinData(tx, vchData, nOut)) { SetNull(); return false; } if(!UnserializeFromData(vchData)) { SetNull(); return false; } return true; } uint32_t GenerateSyscoinGuid(const COutPoint& outPoint) { arith_uint256 txidArith = UintToArith256(outPoint.hash); txidArith += outPoint.n; return txidArith.GetLow32(); } void CAsset::SerializeData( std::vector<unsigned char> &vchData) { CDataStream dsAsset(SER_NETWORK, PROTOCOL_VERSION); Serialize(dsAsset); vchData = std::vector<unsigned char>(dsAsset.begin(), dsAsset.end()); } bool GetAsset(const uint32_t &nAsset, CAsset& txPos) { if (!passetdb || !passetdb->ReadAsset(nAsset, txPos)) return false; return true; } bool CheckTxInputsAssets(const CTransaction &tx, TxValidationState &state, const uint32_t &nAsset, std::unordered_map<uint32_t, std::pair<bool, CAmount> > &mapAssetIn, const std::unordered_map<uint32_t, std::pair<bool, CAmount> > &mapAssetOut) { if (mapAssetOut.empty()) { return state.Invalid(TxValidationResult::TX_CONSENSUS, "bad-txns-asset-outputs-empty"); } std::unordered_map<uint32_t, std::pair<bool, CAmount> >::const_iterator itOut; const bool &isNoInput = IsSyscoinWithNoInputTx(tx.nVersion); if(isNoInput) { itOut = mapAssetOut.find(nAsset); if (itOut == mapAssetOut.end()) { return state.Invalid(TxValidationResult::TX_CONSENSUS, "bad-txns-asset-output-first-asset-not-found"); } } // case 1: asset send without zero val input, covered by this check // case 2: asset send with zero val of another asset, covered by mapAssetIn != mapAssetOut // case 3: asset send with multiple zero val input/output, covered by GetAssetValueOut() for output and CheckTxInputs() for input // case 4: asset send sending assets without inputs of those assets, covered by this check + mapAssetIn != mapAssetOut if (tx.nVersion == SYSCOIN_TX_VERSION_ASSET_SEND) { if (mapAssetIn.empty()) { return state.Invalid(TxValidationResult::TX_CONSENSUS, "bad-txns-assetsend-inputs-empty"); } auto itIn = mapAssetIn.find(nAsset); if (itIn == mapAssetIn.end()) { return state.Invalid(TxValidationResult::TX_CONSENSUS, "bad-txns-assetsend-input-first-asset-not-found"); } // check that the first input asset and first output asset match // note that we only care about first asset because below we will end up enforcing in == out for the rest if (itIn->first != itOut->first) { return state.Invalid(TxValidationResult::TX_CONSENSUS, "bad-txns-assetsend-guid-mismatch"); } // check that the first input asset has zero val input spent if (!itIn->second.first) { return state.Invalid(TxValidationResult::TX_CONSENSUS, "bad-txns-assetsend-missing-zero-val-input"); } // check that the first output asset has zero val output if (!itOut->second.first) { return state.Invalid(TxValidationResult::TX_CONSENSUS, "bad-txns-assetsend-missing-zero-val-output"); } } // asset send also falls into this so for the first out we need to check for asset send seperately above if (isNoInput) { // add first asset out to in so it matches, the rest should be the same // the first one is verified by checksyscoininputs() later on (part of asset send is also) // emplace will add if it doesn't exist or update it below auto it = mapAssetIn.emplace(nAsset, std::make_pair(itOut->second.first, itOut->second.second)); if (!it.second) { it.first->second = std::make_pair(itOut->second.first, itOut->second.second); } } // this will check that all assets with inputs match amounts being sent on outputs // it will also ensure that inputs and outputs per asset are equal with respects to zero-val inputs/outputs (asset ownership utxos) if (mapAssetIn != mapAssetOut) { return state.Invalid(TxValidationResult::TX_CONSENSUS, "bad-txns-assetsend-io-mismatch"); } return true; } CAuxFeeDetails::CAuxFeeDetails(const UniValue& value, const uint8_t &nPrecision){ if(!value.isObject()) { SetNull(); return; } const UniValue& arrObj = find_value(value.get_obj(), "fee_struct"); if(!arrObj.isArray()) { SetNull(); return; } const UniValue& arr = arrObj.get_array(); for (size_t i = 0; i < arr.size(); ++i) { const UniValue& auxFeeObj = arr[i]; if(!auxFeeObj.isArray()) { SetNull(); return; } const UniValue& auxFeeArr = auxFeeObj.get_array(); if(auxFeeArr.size() != 2 || (!auxFeeArr[0].isNum() && !auxFeeArr[0].isStr()) || !auxFeeArr[1].isStr()) { SetNull(); return; } double fPct; if(ParseDouble(auxFeeArr[1].get_str(), &fPct) && fPct <= 65.535){ const uint16_t& nPercent = (uint16_t)(fPct*1000); vecAuxFees.push_back(CAuxFee(AssetAmountFromValue(auxFeeArr[0], nPrecision), nPercent)); } else { SetNull(); return; } } } UniValue CAuxFeeDetails::ToJson() const { UniValue value(UniValue::VOBJ); UniValue feeStruct(UniValue::VARR); for(const auto& auxfee: vecAuxFees) { UniValue auxfeeArr(UniValue::VARR); auxfeeArr.push_back(auxfee.nBound); auxfeeArr.push_back(auxfee.nPercent); feeStruct.push_back(auxfeeArr); } value.pushKV("fee_struct", feeStruct); return value; } CNotaryDetails::CNotaryDetails(const UniValue& value){ if(!value.isObject()) { SetNull(); return; } const UniValue& endpointObj = find_value(value.get_obj(), "endpoint"); if(!endpointObj.isStr()) { SetNull(); return; } strEndPoint = EncodeBase64(endpointObj.get_str()); const UniValue& isObj = find_value(value.get_obj(), "instant_transfers"); if(!isObj.isBool()) { SetNull(); return; } bEnableInstantTransfers = isObj.get_bool()? 1: 0; const UniValue& hdObj = find_value(value.get_obj(), "hd_required"); if(!hdObj.isBool()) { SetNull(); return; } bRequireHD = hdObj.get_bool()? 1: 0; } UniValue CNotaryDetails::ToJson() const { UniValue value(UniValue::VOBJ); value.pushKV("endpoint", DecodeBase64(strEndPoint)); value.pushKV("instant_transfers", bEnableInstantTransfers); value.pushKV("hd_required", bRequireHD); return value; }<|endoftext|>
<commit_before><commit_msg>fix WAE mbError unused<commit_after><|endoftext|>
<commit_before>/******************************************************************************* * benchmarks/data/file_read_write.cpp * * Part of Project Thrill. * * Copyright (C) 2015 Tobias Sturm <mail@tobiassturm.de> * * This file has no license. Only Chuck Norris can compile it. ******************************************************************************/ #include <thrill/api/context.hpp> #include <thrill/common/cmdline_parser.hpp> #include <thrill/common/logger.hpp> #include <thrill/common/stats_timer.hpp> #include <iostream> #include <random> #include <string> #include <tuple> #include "data_generators.hpp" using namespace thrill; // NOLINT using common::StatsTimer; //! Writes and reads random elements from a file. //! Elements are genreated before the timer startet //! Number of elements depends on the number of bytes. //! one RESULT line will be printed for each iteration //! All iterations use the same generated data. //! Variable-length elements range between 1 and 100 bytes template <typename Type> void ConductExperiment(uint64_t bytes, unsigned iterations, api::Context& ctx, const std::string& type_as_string) { for (unsigned i = 0; i < iterations; i++) { auto file = ctx.GetFile(); auto writer = file.GetWriter(); auto data = Generator<Type>(bytes); std::cout << "writing " << bytes << " bytes" << std::endl; StatsTimer<true> write_timer(true); while (data.HasNext()) { writer(data.Next()); } writer.Close(); write_timer.Stop(); std::cout << "reading " << bytes << " bytes" << std::endl; auto reader = file.GetConsumeReader(); StatsTimer<true> read_timer(true); while (reader.HasNext()) reader.Next<Type>(); read_timer.Stop(); std::cout << "RESULT" << " datatype=" << type_as_string << " size=" << bytes << " write_time=" << write_timer.Microseconds() << " read_time=" << read_timer.Microseconds() << std::endl; } } int main(int argc, const char** argv) { common::NameThisThread("benchmark"); common::CmdlineParser clp; clp.SetDescription("thrill::data benchmark for disk I/O"); clp.SetAuthor("Tobias Sturm <mail@tobiassturm.de>"); unsigned iterations = 1; uint64_t bytes; std::string type; clp.AddBytes('b', "bytes", bytes, "number of bytes to process"); clp.AddUInt('n', "iterations", iterations, "Iterations (default: 1)"); clp.AddParamString("type", type, "data type (size_t, string, pair, triple)"); if (!clp.Process(argc, argv)) return -1; using pair = std::tuple<std::string, size_t>; using triple = std::tuple<std::string, size_t, std::string>; if (type == "size_t") api::RunLocalSameThread(std::bind(ConductExperiment<size_t>, bytes, iterations, std::placeholders::_1, type)); else if (type == "string") api::RunLocalSameThread(std::bind(ConductExperiment<std::string>, bytes, iterations, std::placeholders::_1, type)); else if (type == "pair") api::RunLocalSameThread(std::bind(ConductExperiment<pair>, bytes, iterations, std::placeholders::_1, type)); else if (type == "triple") api::RunLocalSameThread(std::bind(ConductExperiment<triple>, bytes, iterations, std::placeholders::_1, type)); else abort(); } /******************************************************************************/ <commit_msg>add non-consume option to file_read_write benchmark<commit_after>/******************************************************************************* * benchmarks/data/file_read_write.cpp * * Part of Project Thrill. * * Copyright (C) 2015 Tobias Sturm <mail@tobiassturm.de> * * This file has no license. Only Chuck Norris can compile it. ******************************************************************************/ #include <thrill/api/context.hpp> #include <thrill/common/cmdline_parser.hpp> #include <thrill/common/logger.hpp> #include <thrill/common/stats_timer.hpp> #include <iostream> #include <random> #include <string> #include <tuple> #include "data_generators.hpp" using namespace thrill; // NOLINT using common::StatsTimer; //! Writes and reads random elements from a file. //! Elements are genreated before the timer startet //! Number of elements depends on the number of bytes. //! one RESULT line will be printed for each iteration //! All iterations use the same generated data. //! Variable-length elements range between 1 and 100 bytes template <typename Type> void ConductExperiment(uint64_t bytes, unsigned iterations, api::Context& ctx, const std::string& type_as_string, const std::string& reader_type) { if (reader_type != "consume" && reader_type != "non-consume") abort(); for (unsigned i = 0; i < iterations; i++) { auto file = ctx.GetFile(); auto writer = file.GetWriter(); auto data = Generator<Type>(bytes); std::cout << "writing " << bytes << " bytes" << std::endl; StatsTimer<true> write_timer(true); while (data.HasNext()) { writer(data.Next()); } writer.Close(); write_timer.Stop(); std::cout << "reading " << bytes << " bytes" << std::endl; bool consume = reader_type == "consume"; StatsTimer<true> read_timer(true); auto reader = file.GetReader(consume); while (reader.HasNext()) reader.Next<Type>(); read_timer.Stop(); std::cout << "RESULT" << " datatype=" << type_as_string << " size=" << bytes << " reader=" << reader_type << " write_time=" << write_timer.Microseconds() << " read_time=" << read_timer.Microseconds() << std::endl; } } int main(int argc, const char** argv) { common::NameThisThread("benchmark"); common::CmdlineParser clp; clp.SetDescription("thrill::data benchmark for disk I/O"); clp.SetAuthor("Tobias Sturm <mail@tobiassturm.de>"); unsigned iterations = 1; uint64_t bytes = 1024; std::string type; std::string reader_type; clp.AddBytes('b', "bytes", bytes, "number of bytes to process (default 1024)"); clp.AddUInt('n', "iterations", iterations, "Iterations (default: 1)"); clp.AddParamString("type", type, "data type (size_t, string, pair, triple)"); clp.AddParamString("reader", reader_type, "reader type (consume, non-consume)"); if (!clp.Process(argc, argv)) return -1; using pair = std::tuple<std::string, size_t>; using triple = std::tuple<std::string, size_t, std::string>; if (type == "size_t") api::RunLocalSameThread(std::bind(ConductExperiment<size_t>, bytes, iterations, std::placeholders::_1, type, reader_type)); else if (type == "string") api::RunLocalSameThread(std::bind(ConductExperiment<std::string>, bytes, iterations, std::placeholders::_1, type, reader_type)); else if (type == "pair") api::RunLocalSameThread(std::bind(ConductExperiment<pair>, bytes, iterations, std::placeholders::_1, type, reader_type)); else if (type == "triple") api::RunLocalSameThread(std::bind(ConductExperiment<triple>, bytes, iterations, std::placeholders::_1, type, reader_type)); else abort(); } /******************************************************************************/ <|endoftext|>
<commit_before>/* * Copyright (c) 2003-2006 The Regents of The University of Michigan * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer; * redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution; * neither the name of the copyright holders nor the names of 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. * * Authors: Nathan Binkert */ #include <errno.h> #include <fcntl.h> #include <unistd.h> #include <fstream> #include <string> #include "arch/kernel_stats.hh" #include "arch/vtophys.hh" #include "base/debug.hh" #include "cpu/base.hh" #include "cpu/thread_context.hh" #include "cpu/quiesce_event.hh" #include "params/BaseCPU.hh" #include "sim/pseudo_inst.hh" #include "sim/serialize.hh" #include "sim/sim_events.hh" #include "sim/sim_exit.hh" #include "sim/stat_control.hh" #include "sim/stats.hh" #include "sim/system.hh" #if FULL_SYSTEM #include "sim/vptr.hh" #endif using namespace std; using namespace Stats; using namespace TheISA; namespace PseudoInst { #if FULL_SYSTEM void arm(ThreadContext *tc) { if (tc->getKernelStats()) tc->getKernelStats()->arm(); } void quiesce(ThreadContext *tc) { if (!tc->getCpuPtr()->params()->do_quiesce) return; DPRINTF(Quiesce, "%s: quiesce()\n", tc->getCpuPtr()->name()); tc->suspend(); if (tc->getKernelStats()) tc->getKernelStats()->quiesce(); } void quiesceNs(ThreadContext *tc, uint64_t ns) { if (!tc->getCpuPtr()->params()->do_quiesce || ns == 0) return; EndQuiesceEvent *quiesceEvent = tc->getQuiesceEvent(); Tick resume = curTick + Clock::Int::ns * ns; mainEventQueue.reschedule(quiesceEvent, resume, true); DPRINTF(Quiesce, "%s: quiesceNs(%d) until %d\n", tc->getCpuPtr()->name(), ns, resume); tc->suspend(); if (tc->getKernelStats()) tc->getKernelStats()->quiesce(); } void quiesceCycles(ThreadContext *tc, uint64_t cycles) { if (!tc->getCpuPtr()->params()->do_quiesce || cycles == 0) return; EndQuiesceEvent *quiesceEvent = tc->getQuiesceEvent(); Tick resume = curTick + tc->getCpuPtr()->ticks(cycles); mainEventQueue.reschedule(quiesceEvent, resume, true); DPRINTF(Quiesce, "%s: quiesceCycles(%d) until %d\n", tc->getCpuPtr()->name(), cycles, resume); tc->suspend(); if (tc->getKernelStats()) tc->getKernelStats()->quiesce(); } uint64_t quiesceTime(ThreadContext *tc) { return (tc->readLastActivate() - tc->readLastSuspend()) / Clock::Int::ns; } #endif uint64_t rpns(ThreadContext *tc) { return curTick / Clock::Int::ns; } void wakeCPU(ThreadContext *tc, uint64_t cpuid) { System *sys = tc->getSystemPtr(); ThreadContext *other_tc = sys->threadContexts[cpuid]; if (other_tc->status() == ThreadContext::Suspended) other_tc->activate(); } void m5exit(ThreadContext *tc, Tick delay) { Tick when = curTick + delay * Clock::Int::ns; Event *event = new SimLoopExitEvent("m5_exit instruction encountered", 0); mainEventQueue.schedule(event, when); } #if FULL_SYSTEM void loadsymbol(ThreadContext *tc) { const string &filename = tc->getCpuPtr()->system->params()->symbolfile; if (filename.empty()) { return; } std::string buffer; ifstream file(filename.c_str()); if (!file) fatal("file error: Can't open symbol table file %s\n", filename); while (!file.eof()) { getline(file, buffer); if (buffer.empty()) continue; int idx = buffer.find(' '); if (idx == string::npos) continue; string address = "0x" + buffer.substr(0, idx); eat_white(address); if (address.empty()) continue; // Skip over letter and space string symbol = buffer.substr(idx + 3); eat_white(symbol); if (symbol.empty()) continue; Addr addr; if (!to_number(address, addr)) continue; if (!tc->getSystemPtr()->kernelSymtab->insert(addr, symbol)) continue; DPRINTF(Loader, "Loaded symbol: %s @ %#llx\n", symbol, addr); } file.close(); } void addsymbol(ThreadContext *tc, Addr addr, Addr symbolAddr) { char symb[100]; CopyStringOut(tc, symb, symbolAddr, 100); std::string symbol(symb); DPRINTF(Loader, "Loaded symbol: %s @ %#llx\n", symbol, addr); tc->getSystemPtr()->kernelSymtab->insert(addr,symbol); debugSymbolTable->insert(addr,symbol); } #endif void resetstats(ThreadContext *tc, Tick delay, Tick period) { if (!tc->getCpuPtr()->params()->do_statistics_insts) return; Tick when = curTick + delay * Clock::Int::ns; Tick repeat = period * Clock::Int::ns; Stats::StatEvent(false, true, when, repeat); } void dumpstats(ThreadContext *tc, Tick delay, Tick period) { if (!tc->getCpuPtr()->params()->do_statistics_insts) return; Tick when = curTick + delay * Clock::Int::ns; Tick repeat = period * Clock::Int::ns; Stats::StatEvent(true, false, when, repeat); } void dumpresetstats(ThreadContext *tc, Tick delay, Tick period) { if (!tc->getCpuPtr()->params()->do_statistics_insts) return; Tick when = curTick + delay * Clock::Int::ns; Tick repeat = period * Clock::Int::ns; Stats::StatEvent(true, true, when, repeat); } void m5checkpoint(ThreadContext *tc, Tick delay, Tick period) { if (!tc->getCpuPtr()->params()->do_checkpoint_insts) return; Tick when = curTick + delay * Clock::Int::ns; Tick repeat = period * Clock::Int::ns; Event *event = new SimLoopExitEvent("checkpoint", 0, repeat); mainEventQueue.schedule(event, when); } #if FULL_SYSTEM uint64_t readfile(ThreadContext *tc, Addr vaddr, uint64_t len, uint64_t offset) { const string &file = tc->getSystemPtr()->params()->readfile; if (file.empty()) { return ULL(0); } uint64_t result = 0; int fd = ::open(file.c_str(), O_RDONLY, 0); if (fd < 0) panic("could not open file %s\n", file); if (::lseek(fd, offset, SEEK_SET) < 0) panic("could not seek: %s", strerror(errno)); char *buf = new char[len]; char *p = buf; while (len > 0) { int bytes = ::read(fd, p, len); if (bytes <= 0) break; p += bytes; result += bytes; len -= bytes; } close(fd); CopyIn(tc, vaddr, buf, result); delete [] buf; return result; } #endif void debugbreak(ThreadContext *tc) { debug_break(); } void switchcpu(ThreadContext *tc) { exitSimLoop("switchcpu"); } /* namespace PseudoInst */ } <commit_msg>pseudo: only include kernel stats if FULL_SYSTEM.<commit_after>/* * Copyright (c) 2003-2006 The Regents of The University of Michigan * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer; * redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution; * neither the name of the copyright holders nor the names of 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. * * Authors: Nathan Binkert */ #include <errno.h> #include <fcntl.h> #include <unistd.h> #include <fstream> #include <string> #include "config/full_system.hh" #include "arch/vtophys.hh" #include "base/debug.hh" #include "cpu/base.hh" #include "cpu/thread_context.hh" #include "cpu/quiesce_event.hh" #include "params/BaseCPU.hh" #include "sim/pseudo_inst.hh" #include "sim/serialize.hh" #include "sim/sim_events.hh" #include "sim/sim_exit.hh" #include "sim/stat_control.hh" #include "sim/stats.hh" #include "sim/system.hh" #if FULL_SYSTEM #include "arch/kernel_stats.hh" #include "sim/vptr.hh" #endif using namespace std; using namespace Stats; using namespace TheISA; namespace PseudoInst { #if FULL_SYSTEM void arm(ThreadContext *tc) { if (tc->getKernelStats()) tc->getKernelStats()->arm(); } void quiesce(ThreadContext *tc) { if (!tc->getCpuPtr()->params()->do_quiesce) return; DPRINTF(Quiesce, "%s: quiesce()\n", tc->getCpuPtr()->name()); tc->suspend(); if (tc->getKernelStats()) tc->getKernelStats()->quiesce(); } void quiesceNs(ThreadContext *tc, uint64_t ns) { if (!tc->getCpuPtr()->params()->do_quiesce || ns == 0) return; EndQuiesceEvent *quiesceEvent = tc->getQuiesceEvent(); Tick resume = curTick + Clock::Int::ns * ns; mainEventQueue.reschedule(quiesceEvent, resume, true); DPRINTF(Quiesce, "%s: quiesceNs(%d) until %d\n", tc->getCpuPtr()->name(), ns, resume); tc->suspend(); if (tc->getKernelStats()) tc->getKernelStats()->quiesce(); } void quiesceCycles(ThreadContext *tc, uint64_t cycles) { if (!tc->getCpuPtr()->params()->do_quiesce || cycles == 0) return; EndQuiesceEvent *quiesceEvent = tc->getQuiesceEvent(); Tick resume = curTick + tc->getCpuPtr()->ticks(cycles); mainEventQueue.reschedule(quiesceEvent, resume, true); DPRINTF(Quiesce, "%s: quiesceCycles(%d) until %d\n", tc->getCpuPtr()->name(), cycles, resume); tc->suspend(); if (tc->getKernelStats()) tc->getKernelStats()->quiesce(); } uint64_t quiesceTime(ThreadContext *tc) { return (tc->readLastActivate() - tc->readLastSuspend()) / Clock::Int::ns; } #endif uint64_t rpns(ThreadContext *tc) { return curTick / Clock::Int::ns; } void wakeCPU(ThreadContext *tc, uint64_t cpuid) { System *sys = tc->getSystemPtr(); ThreadContext *other_tc = sys->threadContexts[cpuid]; if (other_tc->status() == ThreadContext::Suspended) other_tc->activate(); } void m5exit(ThreadContext *tc, Tick delay) { Tick when = curTick + delay * Clock::Int::ns; Event *event = new SimLoopExitEvent("m5_exit instruction encountered", 0); mainEventQueue.schedule(event, when); } #if FULL_SYSTEM void loadsymbol(ThreadContext *tc) { const string &filename = tc->getCpuPtr()->system->params()->symbolfile; if (filename.empty()) { return; } std::string buffer; ifstream file(filename.c_str()); if (!file) fatal("file error: Can't open symbol table file %s\n", filename); while (!file.eof()) { getline(file, buffer); if (buffer.empty()) continue; int idx = buffer.find(' '); if (idx == string::npos) continue; string address = "0x" + buffer.substr(0, idx); eat_white(address); if (address.empty()) continue; // Skip over letter and space string symbol = buffer.substr(idx + 3); eat_white(symbol); if (symbol.empty()) continue; Addr addr; if (!to_number(address, addr)) continue; if (!tc->getSystemPtr()->kernelSymtab->insert(addr, symbol)) continue; DPRINTF(Loader, "Loaded symbol: %s @ %#llx\n", symbol, addr); } file.close(); } void addsymbol(ThreadContext *tc, Addr addr, Addr symbolAddr) { char symb[100]; CopyStringOut(tc, symb, symbolAddr, 100); std::string symbol(symb); DPRINTF(Loader, "Loaded symbol: %s @ %#llx\n", symbol, addr); tc->getSystemPtr()->kernelSymtab->insert(addr,symbol); debugSymbolTable->insert(addr,symbol); } #endif void resetstats(ThreadContext *tc, Tick delay, Tick period) { if (!tc->getCpuPtr()->params()->do_statistics_insts) return; Tick when = curTick + delay * Clock::Int::ns; Tick repeat = period * Clock::Int::ns; Stats::StatEvent(false, true, when, repeat); } void dumpstats(ThreadContext *tc, Tick delay, Tick period) { if (!tc->getCpuPtr()->params()->do_statistics_insts) return; Tick when = curTick + delay * Clock::Int::ns; Tick repeat = period * Clock::Int::ns; Stats::StatEvent(true, false, when, repeat); } void dumpresetstats(ThreadContext *tc, Tick delay, Tick period) { if (!tc->getCpuPtr()->params()->do_statistics_insts) return; Tick when = curTick + delay * Clock::Int::ns; Tick repeat = period * Clock::Int::ns; Stats::StatEvent(true, true, when, repeat); } void m5checkpoint(ThreadContext *tc, Tick delay, Tick period) { if (!tc->getCpuPtr()->params()->do_checkpoint_insts) return; Tick when = curTick + delay * Clock::Int::ns; Tick repeat = period * Clock::Int::ns; Event *event = new SimLoopExitEvent("checkpoint", 0, repeat); mainEventQueue.schedule(event, when); } #if FULL_SYSTEM uint64_t readfile(ThreadContext *tc, Addr vaddr, uint64_t len, uint64_t offset) { const string &file = tc->getSystemPtr()->params()->readfile; if (file.empty()) { return ULL(0); } uint64_t result = 0; int fd = ::open(file.c_str(), O_RDONLY, 0); if (fd < 0) panic("could not open file %s\n", file); if (::lseek(fd, offset, SEEK_SET) < 0) panic("could not seek: %s", strerror(errno)); char *buf = new char[len]; char *p = buf; while (len > 0) { int bytes = ::read(fd, p, len); if (bytes <= 0) break; p += bytes; result += bytes; len -= bytes; } close(fd); CopyIn(tc, vaddr, buf, result); delete [] buf; return result; } #endif void debugbreak(ThreadContext *tc) { debug_break(); } void switchcpu(ThreadContext *tc) { exitSimLoop("switchcpu"); } /* namespace PseudoInst */ } <|endoftext|>
<commit_before>/* * Copyright (c) 2003-2006 The Regents of The University of Michigan * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer; * redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution; * neither the name of the copyright holders nor the names of 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. * * Authors: Nathan Binkert */ class ThreadContext; //We need the "Tick" and "Addr" data types from here #include "base/types.hh" namespace PseudoInst { /** * @todo these externs are only here for a hack in fullCPU::takeOver... */ extern bool doStatisticsInsts; extern bool doCheckpointInsts; extern bool doQuiesce; #if FULL_SYSTEM void arm(ThreadContext *tc); void quiesce(ThreadContext *tc); void quiesceSkip(ThreadContext *tc); void quiesceNs(ThreadContext *tc, uint64_t ns); void quiesceCycles(ThreadContext *tc, uint64_t cycles); uint64_t quiesceTime(ThreadContext *tc); uint64_t readfile(ThreadContext *tc, Addr vaddr, uint64_t len, uint64_t offset); void loadsymbol(ThreadContext *xc); void addsymbol(ThreadContext *tc, Addr addr, Addr symbolAddr); #endif uint64_t rpns(ThreadContext *tc); void wakeCPU(ThreadContext *tc, uint64_t cpuid); void m5exit(ThreadContext *tc, Tick delay); void resetstats(ThreadContext *tc, Tick delay, Tick period); void dumpstats(ThreadContext *tc, Tick delay, Tick period); void dumpresetstats(ThreadContext *tc, Tick delay, Tick period); void m5checkpoint(ThreadContext *tc, Tick delay, Tick period); void debugbreak(ThreadContext *tc); void switchcpu(ThreadContext *tc); void workbegin(ThreadContext *tc, uint64_t workid, uint64_t threadid); void workend(ThreadContext *tc, uint64_t workid, uint64_t threadid); } // namespace PseudoInst <commit_msg>PseudoInst: Add compiler guards to pseudo_inst.hh.<commit_after>/* * Copyright (c) 2003-2006 The Regents of The University of Michigan * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer; * redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution; * neither the name of the copyright holders nor the names of 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. * * Authors: Nathan Binkert */ #ifndef __SIM_PSEUDO_INST_HH__ #define __SIM_PSEUDO_INST_HH__ class ThreadContext; //We need the "Tick" and "Addr" data types from here #include "base/types.hh" namespace PseudoInst { /** * @todo these externs are only here for a hack in fullCPU::takeOver... */ extern bool doStatisticsInsts; extern bool doCheckpointInsts; extern bool doQuiesce; #if FULL_SYSTEM void arm(ThreadContext *tc); void quiesce(ThreadContext *tc); void quiesceSkip(ThreadContext *tc); void quiesceNs(ThreadContext *tc, uint64_t ns); void quiesceCycles(ThreadContext *tc, uint64_t cycles); uint64_t quiesceTime(ThreadContext *tc); uint64_t readfile(ThreadContext *tc, Addr vaddr, uint64_t len, uint64_t offset); void loadsymbol(ThreadContext *xc); void addsymbol(ThreadContext *tc, Addr addr, Addr symbolAddr); #endif uint64_t rpns(ThreadContext *tc); void wakeCPU(ThreadContext *tc, uint64_t cpuid); void m5exit(ThreadContext *tc, Tick delay); void resetstats(ThreadContext *tc, Tick delay, Tick period); void dumpstats(ThreadContext *tc, Tick delay, Tick period); void dumpresetstats(ThreadContext *tc, Tick delay, Tick period); void m5checkpoint(ThreadContext *tc, Tick delay, Tick period); void debugbreak(ThreadContext *tc); void switchcpu(ThreadContext *tc); void workbegin(ThreadContext *tc, uint64_t workid, uint64_t threadid); void workend(ThreadContext *tc, uint64_t workid, uint64_t threadid); } // namespace PseudoInst #endif // __SIM_PSEUDO_INST_HH__ <|endoftext|>
<commit_before>// Copyright (c) 2014-2015, The Monero Project // // 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. // // Parts of this file are originally copyright (c) 2012-2013 The Cryptonote developers #include <boost/uuid/uuid.hpp> #include <boost/uuid/random_generator.hpp> #include <unordered_map> #include "include_base_utils.h" using namespace epee; #include "wallet/wallet2.h" using namespace cryptonote; namespace { uint64_t const TEST_FEE = 5000000000; // 5 * 10^9 uint64_t const TEST_DUST_THRESHOLD = 5000000000; // 5 * 10^9 } std::string generate_random_wallet_name() { std::stringstream ss; ss << boost::uuids::random_generator()(); return ss.str(); } inline uint64_t random(const uint64_t max_value) { return (uint64_t(rand()) ^ (uint64_t(rand())<<16) ^ (uint64_t(rand())<<32) ^ (uint64_t(rand())<<48)) % max_value; } bool do_send_money(tools::wallet2& w1, tools::wallet2& w2, size_t mix_in_factor, uint64_t amount_to_transfer, transaction& tx, size_t parts=1) { CHECK_AND_ASSERT_MES(parts > 0, false, "parts must be > 0"); std::vector<cryptonote::tx_destination_entry> dsts; dsts.reserve(parts); uint64_t amount_used = 0; uint64_t max_part = amount_to_transfer / parts; for (size_t i = 0; i < parts; ++i) { cryptonote::tx_destination_entry de; de.addr = w2.get_account().get_keys().m_account_address; if (i < parts - 1) de.amount = random(max_part); else de.amount = amount_to_transfer - amount_used; amount_used += de.amount; //std::cout << "PARTS (" << amount_to_transfer << ") " << amount_used << " " << de.amount << std::endl; dsts.push_back(de); } try { tools::wallet2::pending_tx ptx; w1.transfer(dsts, mix_in_factor, 0, TEST_FEE, std::vector<uint8_t>(), tools::detail::null_split_strategy, tools::tx_dust_policy(TEST_DUST_THRESHOLD), tx, ptx); w1.commit_tx(ptx); return true; } catch (const std::exception&) { return false; } } uint64_t get_money_in_first_transfers(const tools::wallet2::transfer_container& incoming_transfers, size_t n_transfers) { uint64_t summ = 0; size_t count = 0; BOOST_FOREACH(const tools::wallet2::transfer_details& td, incoming_transfers) { summ += td.m_tx.vout[td.m_internal_output_index].amount; if(++count >= n_transfers) return summ; } return summ; } #define FIRST_N_TRANSFERS 10*10 bool transactions_flow_test(std::string& working_folder, std::string path_source_wallet, std::string path_target_wallet, std::string& daemon_addr_a, std::string& daemon_addr_b, uint64_t amount_to_transfer, size_t mix_in_factor, size_t transactions_count, size_t transactions_per_second) { LOG_PRINT_L0("-----------------------STARTING TRANSACTIONS FLOW TEST-----------------------"); tools::wallet2 w1, w2; if(path_source_wallet.empty()) path_source_wallet = generate_random_wallet_name(); if(path_target_wallet.empty()) path_target_wallet = generate_random_wallet_name(); try { w1.generate(working_folder + "/" + path_source_wallet, ""); w2.generate(working_folder + "/" + path_target_wallet, ""); } catch (const std::exception& e) { LOG_ERROR("failed to generate wallet: " << e.what()); return false; } w1.init(daemon_addr_a); size_t blocks_fetched = 0; bool received_money; bool ok; if(!w1.refresh(blocks_fetched, received_money, ok)) { LOG_ERROR( "failed to refresh source wallet from " << daemon_addr_a ); return false; } w2.init(daemon_addr_b); LOG_PRINT_GREEN("Using wallets: " << ENDL << "Source: " << w1.get_account().get_public_address_str(false) << ENDL << "Path: " << working_folder + "/" + path_source_wallet << ENDL << "Target: " << w2.get_account().get_public_address_str(false) << ENDL << "Path: " << working_folder + "/" + path_target_wallet, LOG_LEVEL_1); //lets do some money epee::net_utils::http::http_simple_client http_client; COMMAND_RPC_STOP_MINING::request daemon1_req = AUTO_VAL_INIT(daemon1_req); COMMAND_RPC_STOP_MINING::response daemon1_rsp = AUTO_VAL_INIT(daemon1_rsp); bool r = net_utils::invoke_http_json_remote_command2(daemon_addr_a + "/stop_mine", daemon1_req, daemon1_rsp, http_client, 10000); CHECK_AND_ASSERT_MES(r, false, "failed to stop mining"); COMMAND_RPC_START_MINING::request daemon_req = AUTO_VAL_INIT(daemon_req); COMMAND_RPC_START_MINING::response daemon_rsp = AUTO_VAL_INIT(daemon_rsp); daemon_req.miner_address = w1.get_account().get_public_address_str(false); daemon_req.threads_count = 9; r = net_utils::invoke_http_json_remote_command2(daemon_addr_a + "/start_mining", daemon_req, daemon_rsp, http_client, 10000); CHECK_AND_ASSERT_MES(r, false, "failed to get getrandom_outs"); CHECK_AND_ASSERT_MES(daemon_rsp.status == CORE_RPC_STATUS_OK, false, "failed to getrandom_outs.bin"); //wait for money, until balance will have enough money w1.refresh(blocks_fetched, received_money, ok); while(w1.unlocked_balance() < amount_to_transfer) { misc_utils::sleep_no_w(1000); w1.refresh(blocks_fetched, received_money, ok); } //lets make a lot of small outs to ourselves //since it is not possible to start from transaction that bigger than 20Kb, we gonna make transactions //with 500 outs (about 18kb), and we have to wait appropriate count blocks, mined for test wallet while(true) { tools::wallet2::transfer_container incoming_transfers; w1.get_transfers(incoming_transfers); if(incoming_transfers.size() > FIRST_N_TRANSFERS && get_money_in_first_transfers(incoming_transfers, FIRST_N_TRANSFERS) < w1.unlocked_balance() ) { //lets go! size_t count = 0; BOOST_FOREACH(tools::wallet2::transfer_details& td, incoming_transfers) { cryptonote::transaction tx_s; bool r = do_send_money(w1, w1, 0, td.m_tx.vout[td.m_internal_output_index].amount - TEST_FEE, tx_s, 50); CHECK_AND_ASSERT_MES(r, false, "Failed to send starter tx " << get_transaction_hash(tx_s)); LOG_PRINT_GREEN("Starter transaction sent " << get_transaction_hash(tx_s), LOG_LEVEL_0); if(++count >= FIRST_N_TRANSFERS) break; } break; }else { misc_utils::sleep_no_w(1000); w1.refresh(blocks_fetched, received_money, ok); } } //do actual transfer uint64_t transfered_money = 0; uint64_t transfer_size = amount_to_transfer/transactions_count; size_t i = 0; struct tx_test_entry { transaction tx; size_t m_received_count; uint64_t amount_transfered; }; crypto::key_image lst_sent_ki = AUTO_VAL_INIT(lst_sent_ki); std::unordered_map<crypto::hash, tx_test_entry> txs; for(i = 0; i != transactions_count; i++) { uint64_t amount_to_tx = (amount_to_transfer - transfered_money) > transfer_size ? transfer_size: (amount_to_transfer - transfered_money); while(w1.unlocked_balance() < amount_to_tx + TEST_FEE) { misc_utils::sleep_no_w(1000); LOG_PRINT_L0("not enough money, waiting for cashback or mining"); w1.refresh(blocks_fetched, received_money, ok); } transaction tx; /*size_t n_attempts = 0; while (!do_send_money(w1, w2, mix_in_factor, amount_to_tx, tx)) { n_attempts++; std::cout << "failed to transfer money, refresh and try again (attempts=" << n_attempts << ")" << std::endl; w1.refresh(); }*/ if(!do_send_money(w1, w2, mix_in_factor, amount_to_tx, tx)) { LOG_PRINT_L0("failed to transfer money, tx: " << get_transaction_hash(tx) << ", refresh and try again" ); w1.refresh(blocks_fetched, received_money, ok); if(!do_send_money(w1, w2, mix_in_factor, amount_to_tx, tx)) { LOG_PRINT_L0( "failed to transfer money, second chance. tx: " << get_transaction_hash(tx) << ", exit" ); LOCAL_ASSERT(false); return false; } } lst_sent_ki = boost::get<txin_to_key>(tx.vin[0]).k_image; transfered_money += amount_to_tx; LOG_PRINT_L0("transferred " << amount_to_tx << ", i=" << i ); tx_test_entry& ent = txs[get_transaction_hash(tx)] = boost::value_initialized<tx_test_entry>(); ent.amount_transfered = amount_to_tx; ent.tx = tx; //if(i % transactions_per_second) // misc_utils::sleep_no_w(1000); } LOG_PRINT_L0( "waiting some new blocks..."); misc_utils::sleep_no_w(DIFFICULTY_BLOCKS_ESTIMATE_TIMESPAN*20*1000);//wait two blocks before sync on another wallet on another daemon LOG_PRINT_L0( "refreshing..."); bool recvd_money = false; while(w2.refresh(blocks_fetched, recvd_money, ok) && ( (blocks_fetched && recvd_money) || !blocks_fetched ) ) { misc_utils::sleep_no_w(DIFFICULTY_BLOCKS_ESTIMATE_TIMESPAN*1000);//wait two blocks before sync on another wallet on another daemon } uint64_t money_2 = w2.balance(); if(money_2 == transfered_money) { LOG_PRINT_GREEN("-----------------------FINISHING TRANSACTIONS FLOW TEST OK-----------------------", LOG_LEVEL_0); LOG_PRINT_GREEN("transferred " << print_money(transfered_money) << " via " << i << " transactions" , LOG_LEVEL_0); return true; }else { tools::wallet2::transfer_container tc; w2.get_transfers(tc); BOOST_FOREACH(tools::wallet2::transfer_details& td, tc) { auto it = txs.find(get_transaction_hash(td.m_tx)); CHECK_AND_ASSERT_MES(it != txs.end(), false, "transaction not found in local cache"); it->second.m_received_count += 1; } BOOST_FOREACH(auto& tx_pair, txs) { if(tx_pair.second.m_received_count != 1) { LOG_PRINT_RED_L0("Transaction lost: " << get_transaction_hash(tx_pair.second.tx)); } } LOG_PRINT_RED_L0("-----------------------FINISHING TRANSACTIONS FLOW TEST FAILED-----------------------" ); LOG_PRINT_RED_L0("income " << print_money(money_2) << " via " << i << " transactions, expected money = " << print_money(transfered_money) ); LOCAL_ASSERT(false); return false; } return true; } <commit_msg>tests: fix build error with CLANG<commit_after>// Copyright (c) 2014-2015, The Monero Project // // 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. // // Parts of this file are originally copyright (c) 2012-2013 The Cryptonote developers #include <boost/uuid/uuid.hpp> #include <boost/uuid/random_generator.hpp> #include <unordered_map> #include "include_base_utils.h" using namespace epee; #include "wallet/wallet2.h" using namespace cryptonote; namespace { uint64_t const TEST_FEE = 5000000000; // 5 * 10^9 uint64_t const TEST_DUST_THRESHOLD = 5000000000; // 5 * 10^9 } std::string generate_random_wallet_name() { std::stringstream ss; ss << boost::uuids::random_generator()(); return ss.str(); } inline uint64_t random(const uint64_t max_value) { return (uint64_t(rand()) ^ (uint64_t(rand())<<16) ^ (uint64_t(rand())<<32) ^ (uint64_t(rand())<<48)) % max_value; } bool do_send_money(tools::wallet2& w1, tools::wallet2& w2, size_t mix_in_factor, uint64_t amount_to_transfer, transaction& tx, size_t parts=1) { CHECK_AND_ASSERT_MES(parts > 0, false, "parts must be > 0"); std::vector<cryptonote::tx_destination_entry> dsts; dsts.reserve(parts); uint64_t amount_used = 0; uint64_t max_part = amount_to_transfer / parts; for (size_t i = 0; i < parts; ++i) { cryptonote::tx_destination_entry de; de.addr = w2.get_account().get_keys().m_account_address; if (i < parts - 1) de.amount = random(max_part); else de.amount = amount_to_transfer - amount_used; amount_used += de.amount; //std::cout << "PARTS (" << amount_to_transfer << ") " << amount_used << " " << de.amount << std::endl; dsts.push_back(de); } try { tools::wallet2::pending_tx ptx; w1.transfer(dsts, mix_in_factor, 0, TEST_FEE, std::vector<uint8_t>(), tools::detail::null_split_strategy, tools::tx_dust_policy(TEST_DUST_THRESHOLD), tx, ptx); w1.commit_tx(ptx); return true; } catch (const std::exception&) { return false; } } uint64_t get_money_in_first_transfers(const tools::wallet2::transfer_container& incoming_transfers, size_t n_transfers) { uint64_t summ = 0; size_t count = 0; BOOST_FOREACH(const tools::wallet2::transfer_details& td, incoming_transfers) { summ += td.m_tx.vout[td.m_internal_output_index].amount; if(++count >= n_transfers) return summ; } return summ; } #define FIRST_N_TRANSFERS 10*10 bool transactions_flow_test(std::string& working_folder, std::string path_source_wallet, std::string path_target_wallet, std::string& daemon_addr_a, std::string& daemon_addr_b, uint64_t amount_to_transfer, size_t mix_in_factor, size_t transactions_count, size_t transactions_per_second) { LOG_PRINT_L0("-----------------------STARTING TRANSACTIONS FLOW TEST-----------------------"); tools::wallet2 w1, w2; if(path_source_wallet.empty()) path_source_wallet = generate_random_wallet_name(); if(path_target_wallet.empty()) path_target_wallet = generate_random_wallet_name(); try { w1.generate(working_folder + "/" + path_source_wallet, ""); w2.generate(working_folder + "/" + path_target_wallet, ""); } catch (const std::exception& e) { LOG_ERROR("failed to generate wallet: " << e.what()); return false; } w1.init(daemon_addr_a); uint64_t blocks_fetched = 0; bool received_money; bool ok; if(!w1.refresh(blocks_fetched, received_money, ok)) { LOG_ERROR( "failed to refresh source wallet from " << daemon_addr_a ); return false; } w2.init(daemon_addr_b); LOG_PRINT_GREEN("Using wallets: " << ENDL << "Source: " << w1.get_account().get_public_address_str(false) << ENDL << "Path: " << working_folder + "/" + path_source_wallet << ENDL << "Target: " << w2.get_account().get_public_address_str(false) << ENDL << "Path: " << working_folder + "/" + path_target_wallet, LOG_LEVEL_1); //lets do some money epee::net_utils::http::http_simple_client http_client; COMMAND_RPC_STOP_MINING::request daemon1_req = AUTO_VAL_INIT(daemon1_req); COMMAND_RPC_STOP_MINING::response daemon1_rsp = AUTO_VAL_INIT(daemon1_rsp); bool r = net_utils::invoke_http_json_remote_command2(daemon_addr_a + "/stop_mine", daemon1_req, daemon1_rsp, http_client, 10000); CHECK_AND_ASSERT_MES(r, false, "failed to stop mining"); COMMAND_RPC_START_MINING::request daemon_req = AUTO_VAL_INIT(daemon_req); COMMAND_RPC_START_MINING::response daemon_rsp = AUTO_VAL_INIT(daemon_rsp); daemon_req.miner_address = w1.get_account().get_public_address_str(false); daemon_req.threads_count = 9; r = net_utils::invoke_http_json_remote_command2(daemon_addr_a + "/start_mining", daemon_req, daemon_rsp, http_client, 10000); CHECK_AND_ASSERT_MES(r, false, "failed to get getrandom_outs"); CHECK_AND_ASSERT_MES(daemon_rsp.status == CORE_RPC_STATUS_OK, false, "failed to getrandom_outs.bin"); //wait for money, until balance will have enough money w1.refresh(blocks_fetched, received_money, ok); while(w1.unlocked_balance() < amount_to_transfer) { misc_utils::sleep_no_w(1000); w1.refresh(blocks_fetched, received_money, ok); } //lets make a lot of small outs to ourselves //since it is not possible to start from transaction that bigger than 20Kb, we gonna make transactions //with 500 outs (about 18kb), and we have to wait appropriate count blocks, mined for test wallet while(true) { tools::wallet2::transfer_container incoming_transfers; w1.get_transfers(incoming_transfers); if(incoming_transfers.size() > FIRST_N_TRANSFERS && get_money_in_first_transfers(incoming_transfers, FIRST_N_TRANSFERS) < w1.unlocked_balance() ) { //lets go! size_t count = 0; BOOST_FOREACH(tools::wallet2::transfer_details& td, incoming_transfers) { cryptonote::transaction tx_s; bool r = do_send_money(w1, w1, 0, td.m_tx.vout[td.m_internal_output_index].amount - TEST_FEE, tx_s, 50); CHECK_AND_ASSERT_MES(r, false, "Failed to send starter tx " << get_transaction_hash(tx_s)); LOG_PRINT_GREEN("Starter transaction sent " << get_transaction_hash(tx_s), LOG_LEVEL_0); if(++count >= FIRST_N_TRANSFERS) break; } break; }else { misc_utils::sleep_no_w(1000); w1.refresh(blocks_fetched, received_money, ok); } } //do actual transfer uint64_t transfered_money = 0; uint64_t transfer_size = amount_to_transfer/transactions_count; size_t i = 0; struct tx_test_entry { transaction tx; size_t m_received_count; uint64_t amount_transfered; }; crypto::key_image lst_sent_ki = AUTO_VAL_INIT(lst_sent_ki); std::unordered_map<crypto::hash, tx_test_entry> txs; for(i = 0; i != transactions_count; i++) { uint64_t amount_to_tx = (amount_to_transfer - transfered_money) > transfer_size ? transfer_size: (amount_to_transfer - transfered_money); while(w1.unlocked_balance() < amount_to_tx + TEST_FEE) { misc_utils::sleep_no_w(1000); LOG_PRINT_L0("not enough money, waiting for cashback or mining"); w1.refresh(blocks_fetched, received_money, ok); } transaction tx; /*size_t n_attempts = 0; while (!do_send_money(w1, w2, mix_in_factor, amount_to_tx, tx)) { n_attempts++; std::cout << "failed to transfer money, refresh and try again (attempts=" << n_attempts << ")" << std::endl; w1.refresh(); }*/ if(!do_send_money(w1, w2, mix_in_factor, amount_to_tx, tx)) { LOG_PRINT_L0("failed to transfer money, tx: " << get_transaction_hash(tx) << ", refresh and try again" ); w1.refresh(blocks_fetched, received_money, ok); if(!do_send_money(w1, w2, mix_in_factor, amount_to_tx, tx)) { LOG_PRINT_L0( "failed to transfer money, second chance. tx: " << get_transaction_hash(tx) << ", exit" ); LOCAL_ASSERT(false); return false; } } lst_sent_ki = boost::get<txin_to_key>(tx.vin[0]).k_image; transfered_money += amount_to_tx; LOG_PRINT_L0("transferred " << amount_to_tx << ", i=" << i ); tx_test_entry& ent = txs[get_transaction_hash(tx)] = boost::value_initialized<tx_test_entry>(); ent.amount_transfered = amount_to_tx; ent.tx = tx; //if(i % transactions_per_second) // misc_utils::sleep_no_w(1000); } LOG_PRINT_L0( "waiting some new blocks..."); misc_utils::sleep_no_w(DIFFICULTY_BLOCKS_ESTIMATE_TIMESPAN*20*1000);//wait two blocks before sync on another wallet on another daemon LOG_PRINT_L0( "refreshing..."); bool recvd_money = false; while(w2.refresh(blocks_fetched, recvd_money, ok) && ( (blocks_fetched && recvd_money) || !blocks_fetched ) ) { misc_utils::sleep_no_w(DIFFICULTY_BLOCKS_ESTIMATE_TIMESPAN*1000);//wait two blocks before sync on another wallet on another daemon } uint64_t money_2 = w2.balance(); if(money_2 == transfered_money) { LOG_PRINT_GREEN("-----------------------FINISHING TRANSACTIONS FLOW TEST OK-----------------------", LOG_LEVEL_0); LOG_PRINT_GREEN("transferred " << print_money(transfered_money) << " via " << i << " transactions" , LOG_LEVEL_0); return true; }else { tools::wallet2::transfer_container tc; w2.get_transfers(tc); BOOST_FOREACH(tools::wallet2::transfer_details& td, tc) { auto it = txs.find(get_transaction_hash(td.m_tx)); CHECK_AND_ASSERT_MES(it != txs.end(), false, "transaction not found in local cache"); it->second.m_received_count += 1; } BOOST_FOREACH(auto& tx_pair, txs) { if(tx_pair.second.m_received_count != 1) { LOG_PRINT_RED_L0("Transaction lost: " << get_transaction_hash(tx_pair.second.tx)); } } LOG_PRINT_RED_L0("-----------------------FINISHING TRANSACTIONS FLOW TEST FAILED-----------------------" ); LOG_PRINT_RED_L0("income " << print_money(money_2) << " via " << i << " transactions, expected money = " << print_money(transfered_money) ); LOCAL_ASSERT(false); return false; } return true; } <|endoftext|>
<commit_before>/*! @file @copyright Edouard Alligand and Joel Falcou 2015-2017 (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt) */ #ifndef BOOST_BRIGAND_ALGORITHMS_ANY_HPP #define BOOST_BRIGAND_ALGORITHMS_ANY_HPP #include <brigand/types/bool.hpp> #include <brigand/algorithms/detail/non_null.hpp> #include <brigand/algorithms/none.hpp> namespace brigand { namespace detail { template< typename Sequence, typename Predicate > struct any_impl : bool_<!none<Sequence,Predicate>::value> {}; } // Is a predicate true for at least one type ? template<typename Sequence, typename Predicate = detail::non_null> using any = typename detail::any_impl<Sequence,Predicate>::type; } #endif <commit_msg>Delete any.hpp<commit_after><|endoftext|>
<commit_before>/* * Copyright 2015-present Facebook, 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 <thrift/lib/cpp2/server/proxygen/ProxygenThriftServer.h> #include <fcntl.h> #include <signal.h> #include <iostream> #include <random> #include <folly/Conv.h> #include <folly/Memory.h> #include <folly/ScopeGuard.h> #include <folly/SocketAddress.h> #include <folly/io/async/AsyncServerSocket.h> #include <folly/portability/Sockets.h> #include <glog/logging.h> #include <proxygen/httpserver/ResponseBuilder.h> #include <thrift/lib/cpp/concurrency/PosixThreadFactory.h> #include <thrift/lib/cpp/concurrency/Thread.h> #include <thrift/lib/cpp/concurrency/ThreadManager.h> #include <thrift/lib/cpp/server/TServerObserver.h> #include <thrift/lib/cpp2/GeneratedCodeHelper.h> #include <thrift/lib/cpp2/protocol/Serializer.h> #include <thrift/lib/cpp2/server/Cpp2Connection.h> namespace apache { namespace thrift { using apache::thrift::concurrency::Runnable; using folly::SocketAddress; using proxygen::HTTPMessage; using proxygen::HTTPServer; using proxygen::HTTPServerOptions; using proxygen::ProxygenError; using proxygen::RequestHandlerChain; using proxygen::ResponseBuilder; using proxygen::ResponseHandler; using proxygen::UpgradeProtocol; void ProxygenThriftServer::ThriftRequestHandler::onRequest( std::unique_ptr<HTTPMessage> msg) noexcept { msg_ = std::move(msg); header_->setSequenceNumber(msg_->getSeqNo()); apache::thrift::THeader::StringToStringMap thriftHeaders; msg_->getHeaders().forEach( [&](const std::string& key, const std::string& val) { thriftHeaders[key] = val; }); header_->setReadHeaders(std::move(thriftHeaders)); } void ProxygenThriftServer::ThriftRequestHandler::onBody( std::unique_ptr<folly::IOBuf> body) noexcept { if (body_) { body_->prependChain(std::move(body)); } else { body_ = std::move(body); // This is a good time to detect the protocol, since if the header isn't // there we can sniff the body. auto& headers = msg_->getHeaders(); auto proto = headers.getSingleOrEmpty( proxygen::HTTPHeaderCode::HTTP_HEADER_X_THRIFT_PROTOCOL); if (proto == "binary") { header_->setProtocolId(protocol::T_BINARY_PROTOCOL); } else if (proto == "compact") { header_->setProtocolId(protocol::T_COMPACT_PROTOCOL); } else if (proto == "json") { header_->setProtocolId(protocol::T_JSON_PROTOCOL); } else if (proto == "simplejson") { header_->setProtocolId(protocol::T_SIMPLE_JSON_PROTOCOL); } else { if (body_->length() == 0) { LOG(ERROR) << "Do not have a magic byte to sniff for the protocol"; return; } auto protByte = body_->data()[0]; switch (protByte) { case 0x80: header_->setProtocolId(protocol::T_BINARY_PROTOCOL); break; case 0x82: header_->setProtocolId(protocol::T_COMPACT_PROTOCOL); break; default: LOG(ERROR) << "Unable to determine protocol from magic byte " << (int)protByte; } } } } void ProxygenThriftServer::ThriftRequestHandler::onEOM() noexcept { folly::RequestContextScopeGuard rctxScopeGuard; connCtx_ = std::make_shared<apache::thrift::Cpp2ConnContext>( &msg_->getClientAddress(), nullptr, nullptr, nullptr, nullptr); buf_ = body_->clone(); // for apache::thrift::ResponseChannelRequest // Set up timeouts std::chrono::milliseconds queueTimeout; std::chrono::milliseconds taskTimeout; bool differentTimeouts = worker_->server_->getTaskExpireTimeForRequest( *header_, queueTimeout, taskTimeout); if (differentTimeouts) { if (queueTimeout > std::chrono::milliseconds(0)) { timer_->scheduleTimeout(&queueTimeout_, queueTimeout); } } if (taskTimeout > std::chrono::milliseconds(0)) { timer_->scheduleTimeout(&taskTimeout_, taskTimeout); } worker_->server_->incActiveRequests(); reqCtx_ = std::make_shared<apache::thrift::Cpp2RequestContext>( connCtx_.get(), header_.get()); request_ = new ProxygenRequest(this, header_, connCtx_, reqCtx_); auto req = std::unique_ptr<apache::thrift::ResponseChannelRequest>(request_); auto protoId = static_cast<apache::thrift::protocol::PROTOCOL_TYPES>( header_->getProtocolId()); if (!apache::thrift::detail::ap::deserializeMessageBegin( protoId, req, body_.get(), reqCtx_.get(), worker_->evb_)) { return; } worker_->getProcessor()->process( std::move(req), std::move(body_), protoId, reqCtx_.get(), worker_->evb_, threadManager_); } void ProxygenThriftServer::ThriftRequestHandler::onUpgrade( UpgradeProtocol /*protocol*/) noexcept { LOG(WARNING) << "ProxygenThriftServer does not support upgrade requests"; } void ProxygenThriftServer::ThriftRequestHandler::requestComplete() noexcept { if (cb_) { cb_->messageSent(); } delete this; } void ProxygenThriftServer::ThriftRequestHandler::onError( ProxygenError err) noexcept { LOG(ERROR) << "Proxygen error=" << err; // TODO(ckwalsh) Expose proxygen errors as a counter somewhere delete this; } void ProxygenThriftServer::ThriftRequestHandler::sendReply( std::unique_ptr<folly::IOBuf>&& buf, // && from ResponseChannel.h apache::thrift::MessageChannel::SendCallback* cb, folly::Optional<uint32_t>) { queueTimeout_.cancelTimeout(); taskTimeout_.cancelTimeout(); if (request_) { request_->clearHandler(); request_ = nullptr; } worker_->server_->decActiveRequests(); auto response = ResponseBuilder(downstream_); response.status(200, "OK"); for (auto itr : header_->releaseWriteHeaders()) { response.header(itr.first, itr.second); } response.header( proxygen::HTTPHeaderCode::HTTP_HEADER_CONTENT_TYPE, "application/x-thrift"); switch (header_->getProtocolId()) { case protocol::T_BINARY_PROTOCOL: response.header( proxygen::HTTPHeaderCode::HTTP_HEADER_X_THRIFT_PROTOCOL, "binary"); break; case protocol::T_COMPACT_PROTOCOL: response.header( proxygen::HTTPHeaderCode::HTTP_HEADER_X_THRIFT_PROTOCOL, "compact"); break; case protocol::T_JSON_PROTOCOL: response.header( proxygen::HTTPHeaderCode::HTTP_HEADER_X_THRIFT_PROTOCOL, "json"); break; case protocol::T_SIMPLE_JSON_PROTOCOL: response.header( proxygen::HTTPHeaderCode::HTTP_HEADER_X_THRIFT_PROTOCOL, "simplejson"); break; default: // Do nothing break; } auto& headers = msg_->getHeaders(); if (headers.exists(THeader::QUERY_LOAD_HEADER)) { auto& loadHeader = headers.getSingleOrEmpty(THeader::QUERY_LOAD_HEADER); auto load = worker_->server_->getLoad(loadHeader); response.header(THeader::QUERY_LOAD_HEADER, folly::to<std::string>(load)); } response.body(std::move(buf)).sendWithEOM(); if (cb) { cb->sendQueued(); cb_ = cb; } } void ProxygenThriftServer::ThriftRequestHandler::sendErrorWrapped( folly::exception_wrapper ew, std::string exCode, apache::thrift::MessageChannel::MessageChannel::SendCallback* cb) { // Other types are unimplemented. DCHECK(ew.is_compatible_with<apache::thrift::TApplicationException>()); header_->setHeader("ex", exCode); ew.with_exception<apache::thrift::TApplicationException>( [&](apache::thrift::TApplicationException& tae) { std::unique_ptr<folly::IOBuf> exbuf; auto proto = header_->getProtocolId(); try { exbuf = serializeError(proto, tae, getBuf()); } catch (const apache::thrift::protocol::TProtocolException& pe) { LOG(ERROR) << "serializeError failed. type=" << pe.getType() << " what()=" << pe.what(); if (request_) { request_->clearHandler(); request_ = nullptr; } worker_->server_->decActiveRequests(); ResponseBuilder(downstream_) .status(500, "Internal Server Error") .closeConnection() .sendWithEOM(); return; } sendReply(std::move(exbuf), cb); }); } void ProxygenThriftServer::ThriftRequestHandler::TaskTimeout:: timeoutExpired() noexcept { if (hard_ || !request_->reqCtx_->getStartedProcessing()) { request_->sendErrorWrapped( folly::make_exception_wrapper<TApplicationException>( TApplicationException::TApplicationExceptionType::TIMEOUT, "Task expired"), kTaskExpiredErrorCode); request_->cancel(); VLOG(1) << "ERROR: Task expired on channel: " << request_->msg_->getClientAddress().describe(); auto observer = request_->worker_->server_->getObserver(); if (observer) { observer->taskTimeout(); } } } bool ProxygenThriftServer::isOverloaded( const transport::THeader::StringToStringMap* headers, const std::string* method) const { if (UNLIKELY(isOverloaded_ && isOverloaded_(headers, method))) { return true; } LOG(WARNING) << "isOverloaded is not implemented"; return false; } uint64_t ProxygenThriftServer::getNumDroppedConnections() const { uint64_t droppedConns = 0; if (server_) { for (auto socket : server_->getSockets()) { auto serverSock = dynamic_cast<const folly::AsyncServerSocket*>(socket); if (serverSock) { droppedConns += serverSock->getNumDroppedConnections(); } } } return droppedConns; } void ProxygenThriftServer::serve() { if (!observer_ && apache::thrift::server::observerFactory_) { observer_ = apache::thrift::server::observerFactory_->getObserver(); } auto nPoolThreads = getNumCPUWorkerThreads(); auto nWorkers = getNumIOWorkerThreads(); if (!threadManager_) { int numThreads = nPoolThreads > 0 ? nPoolThreads : nWorkers; std::shared_ptr<apache::thrift::concurrency::ThreadManager> threadManager( PriorityThreadManager::newPriorityThreadManager( numThreads, true /*stats*/)); threadManager->enableCodel(getEnableCodel()); auto poolThreadName = getCPUWorkerThreadName(); if (!poolThreadName.empty()) { threadManager->setNamePrefix(poolThreadName); } threadManager->start(); setThreadManager(threadManager); } threadManager_->setExpireCallback([&](std::shared_ptr<Runnable> r) { EventTask* task = dynamic_cast<EventTask*>(r.get()); if (task) { task->expired(); } }); threadManager_->setCodelCallback([&](std::shared_ptr<Runnable> /*r*/) { auto observer = getObserver(); if (observer) { observer->queueTimeout(); } }); std::vector<HTTPServer::IPConfig> IPs; if (port_ != -1) { IPs.emplace_back(SocketAddress("::", port_, true), httpProtocol_); } else { IPs.emplace_back(address_, httpProtocol_); } HTTPServerOptions options; options.threads = static_cast<size_t>(nWorkers); options.idleTimeout = getIdleTimeout(); options.initialReceiveWindow = initialReceiveWindow_; options.shutdownOn = {SIGINT, SIGTERM}; options.handlerFactories = RequestHandlerChain().addThen<ThriftRequestHandlerFactory>(this).build(); configMutable_ = false; server_ = std::make_unique<HTTPServer>(std::move(options)); server_->bind(IPs); server_->setSessionInfoCallback(this); server_->start([&]() { // Notify handler of the preServe event if (this->eventHandler_ != nullptr) { auto addrs = this->server_->addresses(); if (!addrs.empty()) { this->eventHandler_->preServe(&addrs[0].address); } } }); // Server stopped for some reason server_.reset(); } void ProxygenThriftServer::stop() { server_->stop(); } void ProxygenThriftServer::stopListening() { server_->stop(); } } // namespace thrift } // namespace apache <commit_msg>In Proxygen Thrift Server, clear out request in onError()<commit_after>/* * Copyright 2015-present Facebook, 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 <thrift/lib/cpp2/server/proxygen/ProxygenThriftServer.h> #include <fcntl.h> #include <signal.h> #include <iostream> #include <random> #include <folly/Conv.h> #include <folly/Memory.h> #include <folly/ScopeGuard.h> #include <folly/SocketAddress.h> #include <folly/io/async/AsyncServerSocket.h> #include <folly/portability/Sockets.h> #include <glog/logging.h> #include <proxygen/httpserver/ResponseBuilder.h> #include <thrift/lib/cpp/concurrency/PosixThreadFactory.h> #include <thrift/lib/cpp/concurrency/Thread.h> #include <thrift/lib/cpp/concurrency/ThreadManager.h> #include <thrift/lib/cpp/server/TServerObserver.h> #include <thrift/lib/cpp2/GeneratedCodeHelper.h> #include <thrift/lib/cpp2/protocol/Serializer.h> #include <thrift/lib/cpp2/server/Cpp2Connection.h> namespace apache { namespace thrift { using apache::thrift::concurrency::Runnable; using folly::SocketAddress; using proxygen::HTTPMessage; using proxygen::HTTPServer; using proxygen::HTTPServerOptions; using proxygen::ProxygenError; using proxygen::RequestHandlerChain; using proxygen::ResponseBuilder; using proxygen::ResponseHandler; using proxygen::UpgradeProtocol; void ProxygenThriftServer::ThriftRequestHandler::onRequest( std::unique_ptr<HTTPMessage> msg) noexcept { msg_ = std::move(msg); header_->setSequenceNumber(msg_->getSeqNo()); apache::thrift::THeader::StringToStringMap thriftHeaders; msg_->getHeaders().forEach( [&](const std::string& key, const std::string& val) { thriftHeaders[key] = val; }); header_->setReadHeaders(std::move(thriftHeaders)); } void ProxygenThriftServer::ThriftRequestHandler::onBody( std::unique_ptr<folly::IOBuf> body) noexcept { if (body_) { body_->prependChain(std::move(body)); } else { body_ = std::move(body); // This is a good time to detect the protocol, since if the header isn't // there we can sniff the body. auto& headers = msg_->getHeaders(); auto proto = headers.getSingleOrEmpty( proxygen::HTTPHeaderCode::HTTP_HEADER_X_THRIFT_PROTOCOL); if (proto == "binary") { header_->setProtocolId(protocol::T_BINARY_PROTOCOL); } else if (proto == "compact") { header_->setProtocolId(protocol::T_COMPACT_PROTOCOL); } else if (proto == "json") { header_->setProtocolId(protocol::T_JSON_PROTOCOL); } else if (proto == "simplejson") { header_->setProtocolId(protocol::T_SIMPLE_JSON_PROTOCOL); } else { if (body_->length() == 0) { LOG(ERROR) << "Do not have a magic byte to sniff for the protocol"; return; } auto protByte = body_->data()[0]; switch (protByte) { case 0x80: header_->setProtocolId(protocol::T_BINARY_PROTOCOL); break; case 0x82: header_->setProtocolId(protocol::T_COMPACT_PROTOCOL); break; default: LOG(ERROR) << "Unable to determine protocol from magic byte " << (int)protByte; } } } } void ProxygenThriftServer::ThriftRequestHandler::onEOM() noexcept { folly::RequestContextScopeGuard rctxScopeGuard; connCtx_ = std::make_shared<apache::thrift::Cpp2ConnContext>( &msg_->getClientAddress(), nullptr, nullptr, nullptr, nullptr); buf_ = body_->clone(); // for apache::thrift::ResponseChannelRequest // Set up timeouts std::chrono::milliseconds queueTimeout; std::chrono::milliseconds taskTimeout; bool differentTimeouts = worker_->server_->getTaskExpireTimeForRequest( *header_, queueTimeout, taskTimeout); if (differentTimeouts) { if (queueTimeout > std::chrono::milliseconds(0)) { timer_->scheduleTimeout(&queueTimeout_, queueTimeout); } } if (taskTimeout > std::chrono::milliseconds(0)) { timer_->scheduleTimeout(&taskTimeout_, taskTimeout); } worker_->server_->incActiveRequests(); reqCtx_ = std::make_shared<apache::thrift::Cpp2RequestContext>( connCtx_.get(), header_.get()); request_ = new ProxygenRequest(this, header_, connCtx_, reqCtx_); auto req = std::unique_ptr<apache::thrift::ResponseChannelRequest>(request_); auto protoId = static_cast<apache::thrift::protocol::PROTOCOL_TYPES>( header_->getProtocolId()); if (!apache::thrift::detail::ap::deserializeMessageBegin( protoId, req, body_.get(), reqCtx_.get(), worker_->evb_)) { return; } worker_->getProcessor()->process( std::move(req), std::move(body_), protoId, reqCtx_.get(), worker_->evb_, threadManager_); } void ProxygenThriftServer::ThriftRequestHandler::onUpgrade( UpgradeProtocol /*protocol*/) noexcept { LOG(WARNING) << "ProxygenThriftServer does not support upgrade requests"; } void ProxygenThriftServer::ThriftRequestHandler::requestComplete() noexcept { if (cb_) { cb_->messageSent(); } delete this; } void ProxygenThriftServer::ThriftRequestHandler::onError( ProxygenError err) noexcept { LOG(ERROR) << "Proxygen error=" << err; if (request_) { request_->clearHandler(); request_ = nullptr; } // TODO(ckwalsh) Expose proxygen errors as a counter somewhere delete this; } void ProxygenThriftServer::ThriftRequestHandler::sendReply( std::unique_ptr<folly::IOBuf>&& buf, // && from ResponseChannel.h apache::thrift::MessageChannel::SendCallback* cb, folly::Optional<uint32_t>) { queueTimeout_.cancelTimeout(); taskTimeout_.cancelTimeout(); if (request_) { request_->clearHandler(); request_ = nullptr; } worker_->server_->decActiveRequests(); auto response = ResponseBuilder(downstream_); response.status(200, "OK"); for (auto itr : header_->releaseWriteHeaders()) { response.header(itr.first, itr.second); } response.header( proxygen::HTTPHeaderCode::HTTP_HEADER_CONTENT_TYPE, "application/x-thrift"); switch (header_->getProtocolId()) { case protocol::T_BINARY_PROTOCOL: response.header( proxygen::HTTPHeaderCode::HTTP_HEADER_X_THRIFT_PROTOCOL, "binary"); break; case protocol::T_COMPACT_PROTOCOL: response.header( proxygen::HTTPHeaderCode::HTTP_HEADER_X_THRIFT_PROTOCOL, "compact"); break; case protocol::T_JSON_PROTOCOL: response.header( proxygen::HTTPHeaderCode::HTTP_HEADER_X_THRIFT_PROTOCOL, "json"); break; case protocol::T_SIMPLE_JSON_PROTOCOL: response.header( proxygen::HTTPHeaderCode::HTTP_HEADER_X_THRIFT_PROTOCOL, "simplejson"); break; default: // Do nothing break; } auto& headers = msg_->getHeaders(); if (headers.exists(THeader::QUERY_LOAD_HEADER)) { auto& loadHeader = headers.getSingleOrEmpty(THeader::QUERY_LOAD_HEADER); auto load = worker_->server_->getLoad(loadHeader); response.header(THeader::QUERY_LOAD_HEADER, folly::to<std::string>(load)); } response.body(std::move(buf)).sendWithEOM(); if (cb) { cb->sendQueued(); cb_ = cb; } } void ProxygenThriftServer::ThriftRequestHandler::sendErrorWrapped( folly::exception_wrapper ew, std::string exCode, apache::thrift::MessageChannel::MessageChannel::SendCallback* cb) { // Other types are unimplemented. DCHECK(ew.is_compatible_with<apache::thrift::TApplicationException>()); header_->setHeader("ex", exCode); ew.with_exception<apache::thrift::TApplicationException>( [&](apache::thrift::TApplicationException& tae) { std::unique_ptr<folly::IOBuf> exbuf; auto proto = header_->getProtocolId(); try { exbuf = serializeError(proto, tae, getBuf()); } catch (const apache::thrift::protocol::TProtocolException& pe) { LOG(ERROR) << "serializeError failed. type=" << pe.getType() << " what()=" << pe.what(); if (request_) { request_->clearHandler(); request_ = nullptr; } worker_->server_->decActiveRequests(); ResponseBuilder(downstream_) .status(500, "Internal Server Error") .closeConnection() .sendWithEOM(); return; } sendReply(std::move(exbuf), cb); }); } void ProxygenThriftServer::ThriftRequestHandler::TaskTimeout:: timeoutExpired() noexcept { if (hard_ || !request_->reqCtx_->getStartedProcessing()) { request_->sendErrorWrapped( folly::make_exception_wrapper<TApplicationException>( TApplicationException::TApplicationExceptionType::TIMEOUT, "Task expired"), kTaskExpiredErrorCode); request_->cancel(); VLOG(1) << "ERROR: Task expired on channel: " << request_->msg_->getClientAddress().describe(); auto observer = request_->worker_->server_->getObserver(); if (observer) { observer->taskTimeout(); } } } bool ProxygenThriftServer::isOverloaded( const transport::THeader::StringToStringMap* headers, const std::string* method) const { if (UNLIKELY(isOverloaded_ && isOverloaded_(headers, method))) { return true; } LOG(WARNING) << "isOverloaded is not implemented"; return false; } uint64_t ProxygenThriftServer::getNumDroppedConnections() const { uint64_t droppedConns = 0; if (server_) { for (auto socket : server_->getSockets()) { auto serverSock = dynamic_cast<const folly::AsyncServerSocket*>(socket); if (serverSock) { droppedConns += serverSock->getNumDroppedConnections(); } } } return droppedConns; } void ProxygenThriftServer::serve() { if (!observer_ && apache::thrift::server::observerFactory_) { observer_ = apache::thrift::server::observerFactory_->getObserver(); } auto nPoolThreads = getNumCPUWorkerThreads(); auto nWorkers = getNumIOWorkerThreads(); if (!threadManager_) { int numThreads = nPoolThreads > 0 ? nPoolThreads : nWorkers; std::shared_ptr<apache::thrift::concurrency::ThreadManager> threadManager( PriorityThreadManager::newPriorityThreadManager( numThreads, true /*stats*/)); threadManager->enableCodel(getEnableCodel()); auto poolThreadName = getCPUWorkerThreadName(); if (!poolThreadName.empty()) { threadManager->setNamePrefix(poolThreadName); } threadManager->start(); setThreadManager(threadManager); } threadManager_->setExpireCallback([&](std::shared_ptr<Runnable> r) { EventTask* task = dynamic_cast<EventTask*>(r.get()); if (task) { task->expired(); } }); threadManager_->setCodelCallback([&](std::shared_ptr<Runnable> /*r*/) { auto observer = getObserver(); if (observer) { observer->queueTimeout(); } }); std::vector<HTTPServer::IPConfig> IPs; if (port_ != -1) { IPs.emplace_back(SocketAddress("::", port_, true), httpProtocol_); } else { IPs.emplace_back(address_, httpProtocol_); } HTTPServerOptions options; options.threads = static_cast<size_t>(nWorkers); options.idleTimeout = getIdleTimeout(); options.initialReceiveWindow = initialReceiveWindow_; options.shutdownOn = {SIGINT, SIGTERM}; options.handlerFactories = RequestHandlerChain().addThen<ThriftRequestHandlerFactory>(this).build(); configMutable_ = false; server_ = std::make_unique<HTTPServer>(std::move(options)); server_->bind(IPs); server_->setSessionInfoCallback(this); server_->start([&]() { // Notify handler of the preServe event if (this->eventHandler_ != nullptr) { auto addrs = this->server_->addresses(); if (!addrs.empty()) { this->eventHandler_->preServe(&addrs[0].address); } } }); // Server stopped for some reason server_.reset(); } void ProxygenThriftServer::stop() { server_->stop(); } void ProxygenThriftServer::stopListening() { server_->stop(); } } // namespace thrift } // namespace apache <|endoftext|>
<commit_before><commit_msg>Reordered tests for `AnyValue` into canonical datatype order.<commit_after><|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: LNoException.cxx,v $ * * $Revision: 1.3 $ * * last change: $Author: rt $ $Date: 2005-09-08 05:45: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 _CONNECTIVITY_EVOAB_LTABLE_HXX_ #include "LTable.hxx" #endif #ifndef _CONNECTIVITY_EVOAB_LCONNECTION_HXX_ #include "LConnection.hxx" #endif using namespace connectivity; using namespace connectivity::evoab; //------------------------------------------------------------------ xub_StrLen OEvoabString::GetTokenCount( sal_Unicode cTok, sal_Unicode cStrDel ) const { if ( !Len() ) return 0; xub_StrLen nTokCount = 1; BOOL bStart = TRUE; // Stehen wir auf dem ersten Zeichen im Token? BOOL bInString = FALSE; // Befinden wir uns INNERHALB eines (cStrDel delimited) String? // Suche bis Stringende nach dem ersten nicht uebereinstimmenden Zeichen for( xub_StrLen i = 0; i < Len(); i++ ) { if (bStart) { bStart = FALSE; // Erstes Zeichen ein String-Delimiter? if ((*this).GetChar(i) == cStrDel) { bInString = TRUE; // dann sind wir jetzt INNERHALB des Strings! continue; // dieses Zeichen ueberlesen! } } if (bInString) { // Wenn jetzt das String-Delimiter-Zeichen auftritt ... if ( (*this).GetChar(i) == cStrDel ) { if ((i+1 < Len()) && ((*this).GetChar(i+1) == cStrDel)) { // Verdoppeltes String-Delimiter-Zeichen: i++; // kein String-Ende, naechstes Zeichen ueberlesen. } else { // String-Ende bInString = FALSE; } } } else { // Stimmt das Tokenzeichen ueberein, dann erhoehe TokCount if ( (*this).GetChar(i) == cTok ) { nTokCount++; bStart = TRUE; } } } //OSL_TRACE("OEvoabString::nTokCount = %d\n", ((OUtoCStr(::rtl::OUString(nTokCount))) ? (OUtoCStr(::rtl::OUString(nTokCount))):("NULL")) ); return nTokCount; } //------------------------------------------------------------------ void OEvoabString::GetTokenSpecial( String& _rStr,xub_StrLen& nStartPos, sal_Unicode cTok, sal_Unicode cStrDel ) const { _rStr.Erase(); xub_StrLen nLen = Len(); if ( nLen ) { BOOL bInString = (nStartPos < nLen) && ((*this).GetChar(nStartPos) == cStrDel); // Befinden wir uns INNERHALB eines (cStrDel delimited) String? // Erstes Zeichen ein String-Delimiter? if (bInString ) ++nStartPos; // dieses Zeichen ueberlesen! // Suche bis Stringende nach dem ersten nicht uebereinstimmenden Zeichen for( xub_StrLen i = nStartPos; i < nLen; ++i ) { if (bInString) { // Wenn jetzt das String-Delimiter-Zeichen auftritt ... if ( (*this).GetChar(i) == cStrDel ) { if ((i+1 < nLen) && ((*this).GetChar(i+1) == cStrDel)) { // Verdoppeltes String-Delimiter-Zeichen: ++i; // kein String-Ende, naechstes Zeichen ueberlesen. _rStr += (*this).GetChar(i); // Zeichen gehoert zum Resultat-String } else { // String-Ende bInString = FALSE; } } else { _rStr += (*this).GetChar(i); // Zeichen gehoert zum Resultat-String } } else { // Stimmt das Tokenzeichen ueberein, dann erhoehe nTok if ( (*this).GetChar(i) == cTok ) { // Vorzeitiger Abbruch der Schleife moeglich, denn // wir haben, was wir wollten. nStartPos = i+1; break; } else { _rStr += (*this).GetChar(i); // Zeichen gehoert zum Resultat-String } } } } } // ----------------------------------------------------------------------------- void OEvoabTable::refreshIndexes() { } // ----------------------------------------------------------------------------- sal_Bool OEvoabTable::checkHeaderLine() { if (m_nFilePos == 0 && ((OEvoabConnection*)m_pConnection)->isHeaderLine()) { BOOL bRead2; do { bRead2 = m_pFileStream->ReadByteStringLine(m_aCurrentLine,m_pConnection->getTextEncoding()); } while(bRead2 && !m_aCurrentLine.Len()); m_nFilePos = m_pFileStream->Tell(); if (m_pFileStream->IsEof()) return sal_False; } return sal_True; } //------------------------------------------------------------------ sal_Bool OEvoabTable::seekRow(IResultSetHelper::Movement eCursorPosition, sal_Int32 nOffset, sal_Int32& nCurPos) { //OSL_TRACE("OEvoabTable::(before SeekRow)m_aCurrentLine = %d\n", ((OUtoCStr(::rtl::OUString(m_aCurrentLine))) ? (OUtoCStr(::rtl::OUString(m_aCurrentLine))):("NULL")) ); if ( !m_pFileStream ) return sal_False; OEvoabConnection* pConnection = (OEvoabConnection*)m_pConnection; // ---------------------------------------------------------- // Positionierung vorbereiten: //OSL_TRACE("OEvoabTable::(before SeekRow,m_pFileStriam Exist)m_aCurrentLine = %d\n", ((OUtoCStr(::rtl::OUString(m_aCurrentLine))) ? (OUtoCStr(::rtl::OUString(m_aCurrentLine))):("NULL")) ); sal_uInt32 nTempPos = m_nFilePos; m_nFilePos = nCurPos; switch(eCursorPosition) { case IResultSetHelper::FIRST: m_nFilePos = 0; m_nRowPos = 1; // run through case IResultSetHelper::NEXT: if(eCursorPosition != IResultSetHelper::FIRST) ++m_nRowPos; m_pFileStream->Seek(m_nFilePos); if (m_pFileStream->IsEof() || !checkHeaderLine()) { m_nMaxRowCount = m_nRowPos; return sal_False; } m_aRowToFilePos.insert(::std::map<sal_Int32,sal_Int32>::value_type(m_nRowPos,m_nFilePos)); m_pFileStream->ReadByteStringLine(m_aCurrentLine,pConnection->getTextEncoding()); if (m_pFileStream->IsEof()) { m_nMaxRowCount = m_nRowPos; return sal_False; } nCurPos = m_pFileStream->Tell(); break; case IResultSetHelper::PRIOR: --m_nRowPos; if(m_nRowPos > 0) { m_nFilePos = m_aRowToFilePos.find(m_nRowPos)->second; m_pFileStream->Seek(m_nFilePos); if (m_pFileStream->IsEof() || !checkHeaderLine()) return sal_False; m_pFileStream->ReadByteStringLine(m_aCurrentLine,pConnection->getTextEncoding()); if (m_pFileStream->IsEof()) return sal_False; nCurPos = m_pFileStream->Tell(); } else m_nRowPos = 0; break; break; case IResultSetHelper::LAST: if(m_nMaxRowCount) { m_nFilePos = m_aRowToFilePos.rbegin()->second; m_nRowPos = m_aRowToFilePos.rbegin()->first; m_pFileStream->Seek(m_nFilePos); if (m_pFileStream->IsEof() || !checkHeaderLine()) return sal_False; m_pFileStream->ReadByteStringLine(m_aCurrentLine,pConnection->getTextEncoding()); if (m_pFileStream->IsEof()) return sal_False; nCurPos = m_pFileStream->Tell(); } else { while(seekRow(IResultSetHelper::NEXT,1,nCurPos)) ; // run through after last row // now I know all seekRow(IResultSetHelper::PRIOR,1,nCurPos); } break; case IResultSetHelper::RELATIVE: if(nOffset > 0) { for(sal_Int32 i = 0;i<nOffset;++i) seekRow(IResultSetHelper::NEXT,1,nCurPos); } else if(nOffset < 0) { for(sal_Int32 i = nOffset;i;++i) seekRow(IResultSetHelper::PRIOR,1,nCurPos); } break; case IResultSetHelper::ABSOLUTE: { if(nOffset < 0) nOffset = m_nRowPos + nOffset; ::std::map<sal_Int32,sal_Int32>::const_iterator aIter = m_aRowToFilePos.find(nOffset); if(aIter != m_aRowToFilePos.end()) { m_nFilePos = aIter->second; m_pFileStream->Seek(m_nFilePos); if (m_pFileStream->IsEof() || !checkHeaderLine()) return sal_False; m_pFileStream->ReadByteStringLine(m_aCurrentLine,pConnection->getTextEncoding()); if (m_pFileStream->IsEof()) return sal_False; nCurPos = m_pFileStream->Tell(); } else if(m_nMaxRowCount && nOffset > m_nMaxRowCount) // offset is outside the table { m_nRowPos = m_nMaxRowCount; return sal_False; } else { aIter = m_aRowToFilePos.upper_bound(nOffset); if(aIter == m_aRowToFilePos.end()) { m_nRowPos = m_aRowToFilePos.rbegin()->first; nCurPos = m_nFilePos = m_aRowToFilePos.rbegin()->second; while(m_nRowPos != nOffset) seekRow(IResultSetHelper::NEXT,1,nCurPos); } else { --aIter; m_nRowPos = aIter->first; m_nFilePos = aIter->second; m_pFileStream->Seek(m_nFilePos); if (m_pFileStream->IsEof() || !checkHeaderLine()) return sal_False; m_pFileStream->ReadByteStringLine(m_aCurrentLine,pConnection->getTextEncoding()); if (m_pFileStream->IsEof()) return sal_False; nCurPos = m_pFileStream->Tell(); } } } break; case IResultSetHelper::BOOKMARK: m_pFileStream->Seek(nOffset); if (m_pFileStream->IsEof()) return sal_False; m_nFilePos = m_pFileStream->Tell(); // Byte-Position in der Datei merken (am ZeilenANFANG) m_pFileStream->ReadByteStringLine(m_aCurrentLine,pConnection->getTextEncoding()); if (m_pFileStream->IsEof()) return sal_False; nCurPos = m_pFileStream->Tell(); break; } //OSL_TRACE("OEvoabTable::(after SeekRow)m_aCurrentLine = %d\n", ((OUtoCStr(::rtl::OUString(m_aCurrentLine))) ? (OUtoCStr(::rtl::OUString(m_aCurrentLine))):("NULL")) ); return sal_True; } // ----------------------------------------------------------------------------- <commit_msg>INTEGRATION: CWS warnings01 (1.3.30); FILE MERGED 2005/11/07 14:43:24 fs 1.3.30.1: #i57457# warning-free code<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: LNoException.cxx,v $ * * $Revision: 1.4 $ * * last change: $Author: hr $ $Date: 2006-06-20 01:23:21 $ * * 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 _CONNECTIVITY_EVOAB_LTABLE_HXX_ #include "LTable.hxx" #endif #ifndef _CONNECTIVITY_EVOAB_LCONNECTION_HXX_ #include "LConnection.hxx" #endif using namespace connectivity; using namespace connectivity::evoab; //------------------------------------------------------------------ xub_StrLen OEvoabString::GetTokenCount( sal_Unicode cTok, sal_Unicode cStrDel ) const { if ( !Len() ) return 0; xub_StrLen nTokCount = 1; BOOL bStart = TRUE; // Stehen wir auf dem ersten Zeichen im Token? BOOL bInString = FALSE; // Befinden wir uns INNERHALB eines (cStrDel delimited) String? // Suche bis Stringende nach dem ersten nicht uebereinstimmenden Zeichen for( xub_StrLen i = 0; i < Len(); i++ ) { if (bStart) { bStart = FALSE; // Erstes Zeichen ein String-Delimiter? if ((*this).GetChar(i) == cStrDel) { bInString = TRUE; // dann sind wir jetzt INNERHALB des Strings! continue; // dieses Zeichen ueberlesen! } } if (bInString) { // Wenn jetzt das String-Delimiter-Zeichen auftritt ... if ( (*this).GetChar(i) == cStrDel ) { if ((i+1 < Len()) && ((*this).GetChar(i+1) == cStrDel)) { // Verdoppeltes String-Delimiter-Zeichen: i++; // kein String-Ende, naechstes Zeichen ueberlesen. } else { // String-Ende bInString = FALSE; } } } else { // Stimmt das Tokenzeichen ueberein, dann erhoehe TokCount if ( (*this).GetChar(i) == cTok ) { nTokCount++; bStart = TRUE; } } } //OSL_TRACE("OEvoabString::nTokCount = %d\n", ((OUtoCStr(::rtl::OUString(nTokCount))) ? (OUtoCStr(::rtl::OUString(nTokCount))):("NULL")) ); return nTokCount; } //------------------------------------------------------------------ void OEvoabString::GetTokenSpecial( String& _rStr,xub_StrLen& nStartPos, sal_Unicode cTok, sal_Unicode cStrDel ) const { _rStr.Erase(); xub_StrLen nLen = Len(); if ( nLen ) { BOOL bInString = (nStartPos < nLen) && ((*this).GetChar(nStartPos) == cStrDel); // Befinden wir uns INNERHALB eines (cStrDel delimited) String? // Erstes Zeichen ein String-Delimiter? if (bInString ) ++nStartPos; // dieses Zeichen ueberlesen! // Suche bis Stringende nach dem ersten nicht uebereinstimmenden Zeichen for( xub_StrLen i = nStartPos; i < nLen; ++i ) { if (bInString) { // Wenn jetzt das String-Delimiter-Zeichen auftritt ... if ( (*this).GetChar(i) == cStrDel ) { if ((i+1 < nLen) && ((*this).GetChar(i+1) == cStrDel)) { // Verdoppeltes String-Delimiter-Zeichen: ++i; // kein String-Ende, naechstes Zeichen ueberlesen. _rStr += (*this).GetChar(i); // Zeichen gehoert zum Resultat-String } else { // String-Ende bInString = FALSE; } } else { _rStr += (*this).GetChar(i); // Zeichen gehoert zum Resultat-String } } else { // Stimmt das Tokenzeichen ueberein, dann erhoehe nTok if ( (*this).GetChar(i) == cTok ) { // Vorzeitiger Abbruch der Schleife moeglich, denn // wir haben, was wir wollten. nStartPos = i+1; break; } else { _rStr += (*this).GetChar(i); // Zeichen gehoert zum Resultat-String } } } } } // ----------------------------------------------------------------------------- void OEvoabTable::refreshIndexes() { } // ----------------------------------------------------------------------------- sal_Bool OEvoabTable::checkHeaderLine() { if (m_nFilePos == 0 && ((OEvoabConnection*)m_pConnection)->isHeaderLine()) { BOOL bRead2; do { bRead2 = m_pFileStream->ReadByteStringLine(m_aCurrentLine,m_pConnection->getTextEncoding()); } while(bRead2 && !m_aCurrentLine.Len()); m_nFilePos = m_pFileStream->Tell(); if (m_pFileStream->IsEof()) return sal_False; } return sal_True; } //------------------------------------------------------------------ sal_Bool OEvoabTable::seekRow(IResultSetHelper::Movement eCursorPosition, sal_Int32 nOffset, sal_Int32& nCurPos) { //OSL_TRACE("OEvoabTable::(before SeekRow)m_aCurrentLine = %d\n", ((OUtoCStr(::rtl::OUString(m_aCurrentLine))) ? (OUtoCStr(::rtl::OUString(m_aCurrentLine))):("NULL")) ); if ( !m_pFileStream ) return sal_False; OEvoabConnection* pConnection = (OEvoabConnection*)m_pConnection; // ---------------------------------------------------------- // Positionierung vorbereiten: //OSL_TRACE("OEvoabTable::(before SeekRow,m_pFileStriam Exist)m_aCurrentLine = %d\n", ((OUtoCStr(::rtl::OUString(m_aCurrentLine))) ? (OUtoCStr(::rtl::OUString(m_aCurrentLine))):("NULL")) ); m_nFilePos = nCurPos; switch(eCursorPosition) { case IResultSetHelper::FIRST: m_nFilePos = 0; m_nRowPos = 1; // run through case IResultSetHelper::NEXT: if(eCursorPosition != IResultSetHelper::FIRST) ++m_nRowPos; m_pFileStream->Seek(m_nFilePos); if (m_pFileStream->IsEof() || !checkHeaderLine()) { m_nMaxRowCount = m_nRowPos; return sal_False; } m_aRowToFilePos.insert(::std::map<sal_Int32,sal_Int32>::value_type(m_nRowPos,m_nFilePos)); m_pFileStream->ReadByteStringLine(m_aCurrentLine,pConnection->getTextEncoding()); if (m_pFileStream->IsEof()) { m_nMaxRowCount = m_nRowPos; return sal_False; } nCurPos = m_pFileStream->Tell(); break; case IResultSetHelper::PRIOR: --m_nRowPos; if(m_nRowPos > 0) { m_nFilePos = m_aRowToFilePos.find(m_nRowPos)->second; m_pFileStream->Seek(m_nFilePos); if (m_pFileStream->IsEof() || !checkHeaderLine()) return sal_False; m_pFileStream->ReadByteStringLine(m_aCurrentLine,pConnection->getTextEncoding()); if (m_pFileStream->IsEof()) return sal_False; nCurPos = m_pFileStream->Tell(); } else m_nRowPos = 0; break; break; case IResultSetHelper::LAST: if(m_nMaxRowCount) { m_nFilePos = m_aRowToFilePos.rbegin()->second; m_nRowPos = m_aRowToFilePos.rbegin()->first; m_pFileStream->Seek(m_nFilePos); if (m_pFileStream->IsEof() || !checkHeaderLine()) return sal_False; m_pFileStream->ReadByteStringLine(m_aCurrentLine,pConnection->getTextEncoding()); if (m_pFileStream->IsEof()) return sal_False; nCurPos = m_pFileStream->Tell(); } else { while(seekRow(IResultSetHelper::NEXT,1,nCurPos)) ; // run through after last row // now I know all seekRow(IResultSetHelper::PRIOR,1,nCurPos); } break; case IResultSetHelper::RELATIVE: if(nOffset > 0) { for(sal_Int32 i = 0;i<nOffset;++i) seekRow(IResultSetHelper::NEXT,1,nCurPos); } else if(nOffset < 0) { for(sal_Int32 i = nOffset;i;++i) seekRow(IResultSetHelper::PRIOR,1,nCurPos); } break; case IResultSetHelper::ABSOLUTE: { if(nOffset < 0) nOffset = m_nRowPos + nOffset; ::std::map<sal_Int32,sal_Int32>::const_iterator aIter = m_aRowToFilePos.find(nOffset); if(aIter != m_aRowToFilePos.end()) { m_nFilePos = aIter->second; m_pFileStream->Seek(m_nFilePos); if (m_pFileStream->IsEof() || !checkHeaderLine()) return sal_False; m_pFileStream->ReadByteStringLine(m_aCurrentLine,pConnection->getTextEncoding()); if (m_pFileStream->IsEof()) return sal_False; nCurPos = m_pFileStream->Tell(); } else if(m_nMaxRowCount && nOffset > m_nMaxRowCount) // offset is outside the table { m_nRowPos = m_nMaxRowCount; return sal_False; } else { aIter = m_aRowToFilePos.upper_bound(nOffset); if(aIter == m_aRowToFilePos.end()) { m_nRowPos = m_aRowToFilePos.rbegin()->first; nCurPos = m_nFilePos = m_aRowToFilePos.rbegin()->second; while(m_nRowPos != nOffset) seekRow(IResultSetHelper::NEXT,1,nCurPos); } else { --aIter; m_nRowPos = aIter->first; m_nFilePos = aIter->second; m_pFileStream->Seek(m_nFilePos); if (m_pFileStream->IsEof() || !checkHeaderLine()) return sal_False; m_pFileStream->ReadByteStringLine(m_aCurrentLine,pConnection->getTextEncoding()); if (m_pFileStream->IsEof()) return sal_False; nCurPos = m_pFileStream->Tell(); } } } break; case IResultSetHelper::BOOKMARK: m_pFileStream->Seek(nOffset); if (m_pFileStream->IsEof()) return sal_False; m_nFilePos = m_pFileStream->Tell(); // Byte-Position in der Datei merken (am ZeilenANFANG) m_pFileStream->ReadByteStringLine(m_aCurrentLine,pConnection->getTextEncoding()); if (m_pFileStream->IsEof()) return sal_False; nCurPos = m_pFileStream->Tell(); break; } //OSL_TRACE("OEvoabTable::(after SeekRow)m_aCurrentLine = %d\n", ((OUtoCStr(::rtl::OUString(m_aCurrentLine))) ? (OUtoCStr(::rtl::OUString(m_aCurrentLine))):("NULL")) ); return sal_True; } // ----------------------------------------------------------------------------- <|endoftext|>
<commit_before>// // Copyright (c) 2015 CNRS // Copyright (c) 2015 Wandercraft, 86 rue de Paris 91400 Orsay, France. // // This file is part of Pinocchio // Pinocchio is free software: you can redistribute it // and/or modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation, either version // 3 of the License, or (at your option) any later version. // // Pinocchio 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 Lesser Public License for more details. You should have // received a copy of the GNU Lesser General Public License along with // Pinocchio If not, see // <http://www.gnu.org/licenses/>. #ifndef __se3_motion_hpp__ #define __se3_motion_hpp__ #include <Eigen/Core> #include <Eigen/Geometry> #include "pinocchio/spatial/fwd.hpp" #include "pinocchio/spatial/force.hpp" namespace se3 { template< class Derived> class MotionBase { protected: typedef Derived Derived_t; SPATIAL_TYPEDEF_TEMPLATE(Derived_t); public: Derived_t & derived() { return *static_cast<Derived_t*>(this); } const Derived_t& derived() const { return *static_cast<const Derived_t*>(this); } const Angular_t & angular() const { return static_cast<const Derived_t*>(this)->angular_impl(); } const Linear_t & linear() const { return static_cast<const Derived_t*>(this)->linear_impl(); } Angular_t & angular() { return static_cast<Derived_t*>(this)->angular_impl(); } Linear_t & linear() { return static_cast<Derived_t*>(this)->linear_impl(); } void angular(const Angular_t & R) { static_cast< Derived_t*>(this)->angular_impl(R); } void linear(const Linear_t & R) { static_cast< Derived_t*>(this)->linear_impl(R); } Vector6 toVector() const { return derived().toVector_impl(); } operator Vector6 () const { return toVector(); } ActionMatrix_t toActionMatrix() const { return derived().toActionMatrix_impl(); } operator Matrix6 () const { return toActionMatrix(); } Derived_t operator-() const { return derived().__minus__(); } Derived_t operator+(const Derived_t & v2) const { return derived().__plus__(v2); } Derived_t operator-(const Derived_t & v2) const { return derived().__minus__(v2); } Derived_t& operator+=(const Derived_t & v2) { return derived().__pequ__(v2); } Derived_t se3Action(const SE3 & m) const { return derived().se3Action_impl(m); } /// bv = aXb.actInv(av) Derived_t se3ActionInverse(const SE3 & m) const { return derived().se3ActionInverse_impl(m); } void disp(std::ostream & os) const { derived().disp_impl(os); } friend std::ostream & operator << (std::ostream & os, const MotionBase<Derived_t> & mv) { mv.disp(os); return os; } }; // class MotionBase template<typename T, int U> struct traits< MotionTpl<T, U> > { typedef T Scalar_t; typedef Eigen::Matrix<T,3,1,U> Vector3; typedef Eigen::Matrix<T,4,1,U> Vector4; typedef Eigen::Matrix<T,6,1,U> Vector6; typedef Eigen::Matrix<T,3,3,U> Matrix3; typedef Eigen::Matrix<T,4,4,U> Matrix4; typedef Eigen::Matrix<T,6,6,U> Matrix6; typedef Matrix6 ActionMatrix_t; typedef Vector3 Angular_t; typedef Vector3 Linear_t; typedef Eigen::Quaternion<T,U> Quaternion_t; typedef SE3Tpl<T,U> SE3; typedef ForceTpl<T,U> Force; typedef MotionTpl<T,U> Motion; typedef Symmetric3Tpl<T,U> Symmetric3; enum { LINEAR = 0, ANGULAR = 3 }; }; // traits MotionTpl template<typename _Scalar, int _Options> class MotionTpl : public MotionBase< MotionTpl< _Scalar, _Options > > { public: SPATIAL_TYPEDEF_TEMPLATE(MotionTpl); public: // Constructors MotionTpl() : m_w(), m_v() {} template<typename v1,typename v2> MotionTpl(const Eigen::MatrixBase<v1> & v, const Eigen::MatrixBase<v2> & w) : m_w(w), m_v(v) {} template<typename v6> explicit MotionTpl(const Eigen::MatrixBase<v6> & v) : m_w(v.template segment<3>(ANGULAR)) , m_v(v.template segment<3>(LINEAR)) { EIGEN_STATIC_ASSERT_VECTOR_ONLY(v6); assert( v.size() == 6 ); } template<typename S2,int O2> explicit MotionTpl(const MotionTpl<S2,O2> & clone) : m_w(clone.angular()),m_v(clone.linear()) {} // initializers static MotionTpl Zero() { return MotionTpl(Vector3::Zero(), Vector3::Zero()); } static MotionTpl Random() { return MotionTpl(Vector3::Random(),Vector3::Random()); } MotionTpl & setZero () { m_v.setZero (); m_w.setZero (); return *this; } MotionTpl & setRandom () { m_v.setRandom (); m_w.setRandom (); return *this; } Vector6 toVector_impl() const { Vector6 v; v.template segment<3>(ANGULAR) = m_w; v.template segment<3>(LINEAR) = m_v; return v; } ActionMatrix_t toActionMatrix_impl () const { ActionMatrix_t X; X.block <3,3> (ANGULAR, ANGULAR) = X.block <3,3> (LINEAR, LINEAR) = skew (m_w); X.block <3,3> (LINEAR, ANGULAR) = skew (m_v); X.block <3,3> (ANGULAR, LINEAR).setZero (); return X; } // Getters const Vector3 & angular_impl() const { return m_w; } const Vector3 & linear_impl() const { return m_v; } Vector3 & angular_impl() { return m_w; } Vector3 & linear_impl() { return m_v; } void angular_impl(const Vector3 & w) { m_w=w; } void linear_impl(const Vector3 & v) { m_v=v; } // Arithmetic operators template<typename S2, int O2> MotionTpl & operator= (const MotionTpl<S2,O2> & other) { m_w = other.angular (); m_v = other.linear (); return *this; } template<typename V6> MotionTpl & operator=(const Eigen::MatrixBase<V6> & v) { EIGEN_STATIC_ASSERT_VECTOR_ONLY(V6); assert(v.size() == 6); m_w = v.template segment<3>(ANGULAR); m_v = v.template segment<3>(LINEAR); return *this; } MotionTpl __minus__() const { return MotionTpl(-m_v, -m_w); } MotionTpl __plus__(const MotionTpl & v2) const { return MotionTpl(m_v+v2.m_v,m_w+v2.m_w); } MotionTpl __minus__(const MotionTpl & v2) const { return MotionTpl(m_v-v2.m_v,m_w-v2.m_w); } MotionTpl& __pequ__(const MotionTpl & v2) { m_v+=v2.m_v; m_w+=v2.m_w; return *this; } // MotionTpl operator*(Scalar a) const // { // return MotionTpl(m_w*a, m_v*a); // } // friend MotionTpl operator*(Scalar a, const MotionTpl & mv) // { // return MotionTpl(mv.w()*a, mv.v()*a); // } MotionTpl cross(const MotionTpl& v2) const { return MotionTpl( m_v.cross(v2.m_w)+m_w.cross(v2.m_v), m_w.cross(v2.m_w) ); } Force cross(const Force& phi) const { return Force( m_w.cross(phi.linear()), m_w.cross(phi.angular())+m_v.cross(phi.linear()) ); } MotionTpl se3Action_impl(const SE3 & m) const { Vector3 Rw (static_cast<Vector3>(m.rotation() * angular_impl())); return MotionTpl( m.rotation()*linear_impl() + m.translation().cross(Rw), Rw); } /// bv = aXb.actInv(av) MotionTpl se3ActionInverse_impl(const SE3 & m) const { return MotionTpl( m.rotation().transpose()*(linear_impl()-m.translation().cross(angular_impl())), m.rotation().transpose()*angular_impl()); } void disp_impl(std::ostream & os) const { os << " v = " << linear_impl().transpose () << std::endl << " w = " << angular_impl().transpose () << std::endl; } /** \brief Compute the classical acceleration of point according to the spatial velocity and spatial acceleration of the frame centered on this point */ static inline Vector3 computeLinearClassicalAcceleration (const MotionTpl & spatial_velocity, const MotionTpl & spatial_acceleration) { return spatial_acceleration.linear () + spatial_velocity.angular ().cross (spatial_velocity.linear ()); } /** \brief Compute the spatial motion quantity of the parallel frame translated by translation_vector */ MotionTpl translate (const Vector3 & translation_vector) const { return MotionTpl (m_v + m_w.cross (translation_vector), m_w); } private: Vector3 m_w; Vector3 m_v; }; // class MotionTpl template<typename S,int O> MotionTpl<S,O> operator^( const MotionTpl<S,O> &m1, const MotionTpl<S,O> &m2 ) { return m1.cross(m2); } template<typename S,int O> ForceTpl<S,O> operator^( const MotionTpl<S,O> &m, const ForceTpl<S,O> &f ) { return m.cross(f); } typedef MotionTpl<double> Motion; /////////////// BiasZero /////////////// struct BiasZero; template<> struct traits< BiasZero > { typedef double Scalar_t; typedef Eigen::Matrix<double,3,1,0> Vector3; typedef Eigen::Matrix<double,4,1,0> Vector4; typedef Eigen::Matrix<double,6,1,0> Vector6; typedef Eigen::Matrix<double,3,3,0> Matrix3; typedef Eigen::Matrix<double,4,4,0> Matrix4; typedef Eigen::Matrix<double,6,6,0> Matrix6; typedef Matrix6 ActionMatrix_t; typedef Vector3 Angular_t; typedef Vector3 Linear_t; typedef Eigen::Quaternion<double,0> Quaternion_t; typedef SE3Tpl<double,0> SE3; typedef ForceTpl<double,0> Force; typedef MotionTpl<double,0> Motion; typedef Symmetric3Tpl<double,0> Symmetric3; enum { LINEAR = 0, ANGULAR = 3 }; }; // traits BiasZero struct BiasZero : public MotionBase< BiasZero > { SPATIAL_TYPEDEF_NO_TEMPLATE(BiasZero); operator Motion () const { return Motion::Zero(); } }; // struct BiasZero inline const Motion & operator+( const Motion& v, const BiasZero&) { return v; } inline const Motion & operator+ ( const BiasZero&,const Motion& v) { return v; } } // namespace se3 #endif // ifndef __se3_motion_hpp__ <commit_msg>[C++] Set motion data to protected<commit_after>// // Copyright (c) 2015 CNRS // Copyright (c) 2015 Wandercraft, 86 rue de Paris 91400 Orsay, France. // // This file is part of Pinocchio // Pinocchio is free software: you can redistribute it // and/or modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation, either version // 3 of the License, or (at your option) any later version. // // Pinocchio 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 Lesser Public License for more details. You should have // received a copy of the GNU Lesser General Public License along with // Pinocchio If not, see // <http://www.gnu.org/licenses/>. #ifndef __se3_motion_hpp__ #define __se3_motion_hpp__ #include <Eigen/Core> #include <Eigen/Geometry> #include "pinocchio/spatial/fwd.hpp" #include "pinocchio/spatial/force.hpp" namespace se3 { template< class Derived> class MotionBase { protected: typedef Derived Derived_t; SPATIAL_TYPEDEF_TEMPLATE(Derived_t); public: Derived_t & derived() { return *static_cast<Derived_t*>(this); } const Derived_t& derived() const { return *static_cast<const Derived_t*>(this); } const Angular_t & angular() const { return static_cast<const Derived_t*>(this)->angular_impl(); } const Linear_t & linear() const { return static_cast<const Derived_t*>(this)->linear_impl(); } Angular_t & angular() { return static_cast<Derived_t*>(this)->angular_impl(); } Linear_t & linear() { return static_cast<Derived_t*>(this)->linear_impl(); } void angular(const Angular_t & R) { static_cast< Derived_t*>(this)->angular_impl(R); } void linear(const Linear_t & R) { static_cast< Derived_t*>(this)->linear_impl(R); } Vector6 toVector() const { return derived().toVector_impl(); } operator Vector6 () const { return toVector(); } ActionMatrix_t toActionMatrix() const { return derived().toActionMatrix_impl(); } operator Matrix6 () const { return toActionMatrix(); } Derived_t operator-() const { return derived().__minus__(); } Derived_t operator+(const Derived_t & v2) const { return derived().__plus__(v2); } Derived_t operator-(const Derived_t & v2) const { return derived().__minus__(v2); } Derived_t& operator+=(const Derived_t & v2) { return derived().__pequ__(v2); } Derived_t se3Action(const SE3 & m) const { return derived().se3Action_impl(m); } /// bv = aXb.actInv(av) Derived_t se3ActionInverse(const SE3 & m) const { return derived().se3ActionInverse_impl(m); } void disp(std::ostream & os) const { derived().disp_impl(os); } friend std::ostream & operator << (std::ostream & os, const MotionBase<Derived_t> & mv) { mv.disp(os); return os; } }; // class MotionBase template<typename T, int U> struct traits< MotionTpl<T, U> > { typedef T Scalar_t; typedef Eigen::Matrix<T,3,1,U> Vector3; typedef Eigen::Matrix<T,4,1,U> Vector4; typedef Eigen::Matrix<T,6,1,U> Vector6; typedef Eigen::Matrix<T,3,3,U> Matrix3; typedef Eigen::Matrix<T,4,4,U> Matrix4; typedef Eigen::Matrix<T,6,6,U> Matrix6; typedef Matrix6 ActionMatrix_t; typedef Vector3 Angular_t; typedef Vector3 Linear_t; typedef Eigen::Quaternion<T,U> Quaternion_t; typedef SE3Tpl<T,U> SE3; typedef ForceTpl<T,U> Force; typedef MotionTpl<T,U> Motion; typedef Symmetric3Tpl<T,U> Symmetric3; enum { LINEAR = 0, ANGULAR = 3 }; }; // traits MotionTpl template<typename _Scalar, int _Options> class MotionTpl : public MotionBase< MotionTpl< _Scalar, _Options > > { public: SPATIAL_TYPEDEF_TEMPLATE(MotionTpl); public: // Constructors MotionTpl() : m_w(), m_v() {} template<typename v1,typename v2> MotionTpl(const Eigen::MatrixBase<v1> & v, const Eigen::MatrixBase<v2> & w) : m_w(w), m_v(v) {} template<typename v6> explicit MotionTpl(const Eigen::MatrixBase<v6> & v) : m_w(v.template segment<3>(ANGULAR)) , m_v(v.template segment<3>(LINEAR)) { EIGEN_STATIC_ASSERT_VECTOR_ONLY(v6); assert( v.size() == 6 ); } template<typename S2,int O2> explicit MotionTpl(const MotionTpl<S2,O2> & clone) : m_w(clone.angular()),m_v(clone.linear()) {} // initializers static MotionTpl Zero() { return MotionTpl(Vector3::Zero(), Vector3::Zero()); } static MotionTpl Random() { return MotionTpl(Vector3::Random(),Vector3::Random()); } MotionTpl & setZero () { m_v.setZero (); m_w.setZero (); return *this; } MotionTpl & setRandom () { m_v.setRandom (); m_w.setRandom (); return *this; } Vector6 toVector_impl() const { Vector6 v; v.template segment<3>(ANGULAR) = m_w; v.template segment<3>(LINEAR) = m_v; return v; } ActionMatrix_t toActionMatrix_impl () const { ActionMatrix_t X; X.block <3,3> (ANGULAR, ANGULAR) = X.block <3,3> (LINEAR, LINEAR) = skew (m_w); X.block <3,3> (LINEAR, ANGULAR) = skew (m_v); X.block <3,3> (ANGULAR, LINEAR).setZero (); return X; } // Getters const Vector3 & angular_impl() const { return m_w; } const Vector3 & linear_impl() const { return m_v; } Vector3 & angular_impl() { return m_w; } Vector3 & linear_impl() { return m_v; } void angular_impl(const Vector3 & w) { m_w=w; } void linear_impl(const Vector3 & v) { m_v=v; } // Arithmetic operators template<typename S2, int O2> MotionTpl & operator= (const MotionTpl<S2,O2> & other) { m_w = other.angular (); m_v = other.linear (); return *this; } template<typename V6> MotionTpl & operator=(const Eigen::MatrixBase<V6> & v) { EIGEN_STATIC_ASSERT_VECTOR_ONLY(V6); assert(v.size() == 6); m_w = v.template segment<3>(ANGULAR); m_v = v.template segment<3>(LINEAR); return *this; } MotionTpl __minus__() const { return MotionTpl(-m_v, -m_w); } MotionTpl __plus__(const MotionTpl & v2) const { return MotionTpl(m_v+v2.m_v,m_w+v2.m_w); } MotionTpl __minus__(const MotionTpl & v2) const { return MotionTpl(m_v-v2.m_v,m_w-v2.m_w); } MotionTpl& __pequ__(const MotionTpl & v2) { m_v+=v2.m_v; m_w+=v2.m_w; return *this; } // MotionTpl operator*(Scalar a) const // { // return MotionTpl(m_w*a, m_v*a); // } // friend MotionTpl operator*(Scalar a, const MotionTpl & mv) // { // return MotionTpl(mv.w()*a, mv.v()*a); // } MotionTpl cross(const MotionTpl& v2) const { return MotionTpl( m_v.cross(v2.m_w)+m_w.cross(v2.m_v), m_w.cross(v2.m_w) ); } Force cross(const Force& phi) const { return Force( m_w.cross(phi.linear()), m_w.cross(phi.angular())+m_v.cross(phi.linear()) ); } MotionTpl se3Action_impl(const SE3 & m) const { Vector3 Rw (static_cast<Vector3>(m.rotation() * angular_impl())); return MotionTpl( m.rotation()*linear_impl() + m.translation().cross(Rw), Rw); } /// bv = aXb.actInv(av) MotionTpl se3ActionInverse_impl(const SE3 & m) const { return MotionTpl( m.rotation().transpose()*(linear_impl()-m.translation().cross(angular_impl())), m.rotation().transpose()*angular_impl()); } void disp_impl(std::ostream & os) const { os << " v = " << linear_impl().transpose () << std::endl << " w = " << angular_impl().transpose () << std::endl; } /** \brief Compute the classical acceleration of point according to the spatial velocity and spatial acceleration of the frame centered on this point */ static inline Vector3 computeLinearClassicalAcceleration (const MotionTpl & spatial_velocity, const MotionTpl & spatial_acceleration) { return spatial_acceleration.linear () + spatial_velocity.angular ().cross (spatial_velocity.linear ()); } /** \brief Compute the spatial motion quantity of the parallel frame translated by translation_vector */ MotionTpl translate (const Vector3 & translation_vector) const { return MotionTpl (m_v + m_w.cross (translation_vector), m_w); } protected: Vector3 m_w; Vector3 m_v; }; // class MotionTpl template<typename S,int O> MotionTpl<S,O> operator^( const MotionTpl<S,O> &m1, const MotionTpl<S,O> &m2 ) { return m1.cross(m2); } template<typename S,int O> ForceTpl<S,O> operator^( const MotionTpl<S,O> &m, const ForceTpl<S,O> &f ) { return m.cross(f); } typedef MotionTpl<double> Motion; /////////////// BiasZero /////////////// struct BiasZero; template<> struct traits< BiasZero > { typedef double Scalar_t; typedef Eigen::Matrix<double,3,1,0> Vector3; typedef Eigen::Matrix<double,4,1,0> Vector4; typedef Eigen::Matrix<double,6,1,0> Vector6; typedef Eigen::Matrix<double,3,3,0> Matrix3; typedef Eigen::Matrix<double,4,4,0> Matrix4; typedef Eigen::Matrix<double,6,6,0> Matrix6; typedef Matrix6 ActionMatrix_t; typedef Vector3 Angular_t; typedef Vector3 Linear_t; typedef Eigen::Quaternion<double,0> Quaternion_t; typedef SE3Tpl<double,0> SE3; typedef ForceTpl<double,0> Force; typedef MotionTpl<double,0> Motion; typedef Symmetric3Tpl<double,0> Symmetric3; enum { LINEAR = 0, ANGULAR = 3 }; }; // traits BiasZero struct BiasZero : public MotionBase< BiasZero > { SPATIAL_TYPEDEF_NO_TEMPLATE(BiasZero); operator Motion () const { return Motion::Zero(); } }; // struct BiasZero inline const Motion & operator+( const Motion& v, const BiasZero&) { return v; } inline const Motion & operator+ ( const BiasZero&,const Motion& v) { return v; } } // namespace se3 #endif // ifndef __se3_motion_hpp__ <|endoftext|>
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* * This file is part of the LibreOffice project. * * 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/. * * This file incorporates work covered by the following license notice: * * 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 . */ #include "Connection.hxx" #include "Driver.hxx" #include "ResultSet.hxx" #include "Statement.hxx" #include "Util.hxx" #include <comphelper/sequence.hxx> #include <osl/diagnose.h> #include <osl/thread.h> #include <rtl/ustrbuf.hxx> #include <com/sun/star/lang/DisposedException.hpp> #include <com/sun/star/sdbc/ResultSetConcurrency.hpp> #include <com/sun/star/sdbc/ResultSetType.hpp> #include <com/sun/star/sdbc/FetchDirection.hpp> using namespace connectivity::firebird; using namespace com::sun::star; using namespace com::sun::star::uno; using namespace com::sun::star::lang; using namespace com::sun::star::beans; using namespace com::sun::star::sdbc; using namespace com::sun::star::sdbcx; using namespace com::sun::star::container; using namespace com::sun::star::io; using namespace com::sun::star::util; using namespace ::comphelper; using namespace ::osl; using namespace ::rtl; using namespace ::std; // ---- XBatchExecution - UNSUPPORTED ---------------------------------------- void SAL_CALL OStatement::addBatch(const OUString& sql) throw(SQLException, RuntimeException) { (void) sql; } void SAL_CALL OStatement::clearBatch() throw(SQLException, RuntimeException) { } Sequence< sal_Int32 > SAL_CALL OStatement::executeBatch() throw(SQLException, RuntimeException) { return Sequence< sal_Int32 >(); } IMPLEMENT_SERVICE_INFO(OStatement,"com.sun.star.sdbcx.OStatement","com.sun.star.sdbc.Statement"); void SAL_CALL OStatement::acquire() throw() { OStatementCommonBase::acquire(); } void SAL_CALL OStatement::release() throw() { OStatementCommonBase::release(); } void OStatement::disposeResultSet() { MutexGuard aGuard(m_pConnection->getMutex()); checkDisposed(OStatementCommonBase_Base::rBHelper.bDisposed); OStatementCommonBase::disposeResultSet(); if (m_pSqlda) { freeSQLVAR(m_pSqlda); free(m_pSqlda); m_pSqlda = 0; } } // ---- XStatement ----------------------------------------------------------- sal_Int32 SAL_CALL OStatement::executeUpdate(const OUString& sql) throw(SQLException, RuntimeException) { MutexGuard aGuard(m_pConnection->getMutex()); checkDisposed(OStatementCommonBase_Base::rBHelper.bDisposed); int aErr = isc_dsql_execute_immediate(m_statusVector, &m_pConnection->getDBHandle(), &m_pConnection->getTransaction(), 0, OUStringToOString(sql, RTL_TEXTENCODING_UTF8).getStr(), FIREBIRD_SQL_DIALECT, NULL); if (aErr) SAL_WARN("connectivity.firebird", "isc_dsql_execute_immediate failed" ); evaluateStatusVector(m_statusVector, sql, *this); // TODO: get number of changed rows with SELECT ROW_COUNT (use executeQuery) // return getUpdateCount(); return 0; } uno::Reference< XResultSet > SAL_CALL OStatement::executeQuery(const OUString& sql) throw(SQLException, RuntimeException) { MutexGuard aGuard(m_pConnection->getMutex()); checkDisposed(OStatementCommonBase_Base::rBHelper.bDisposed); ISC_STATUS aErr = 0; disposeResultSet(); prepareAndDescribeStatement(sql, m_pSqlda); aErr = isc_dsql_execute(m_statusVector, &m_pConnection->getTransaction(), &m_aStatementHandle, 1, NULL); if (aErr) SAL_WARN("connectivity.firebird", "isc_dsql_execute failed"); m_xResultSet = new OResultSet(m_pConnection, uno::Reference< XInterface >(*this), m_aStatementHandle, m_pSqlda); // TODO: deal with cleanup evaluateStatusVector(m_statusVector, sql, *this); if (isDDLStatement(m_aStatementHandle)) m_pConnection->commit(); return m_xResultSet; } sal_Bool SAL_CALL OStatement::execute(const OUString& sql) throw(SQLException, RuntimeException) { uno::Reference< XResultSet > xResults = executeQuery(sql); return xResults.is(); // TODO: what if we have multiple results? } uno::Reference< XConnection > SAL_CALL OStatement::getConnection() throw(SQLException, RuntimeException) { MutexGuard aGuard(m_pConnection->getMutex()); checkDisposed(OStatementCommonBase_Base::rBHelper.bDisposed); return (uno::Reference< XConnection >)m_pConnection; } Any SAL_CALL OStatement::queryInterface( const Type & rType ) throw(RuntimeException) { Any aRet = OStatement_Base::queryInterface(rType); if(!aRet.hasValue()) aRet = ::cppu::queryInterface(rType,static_cast< XBatchExecution*> (this)); if(!aRet.hasValue()) aRet = OStatementCommonBase::queryInterface(rType); return aRet; } uno::Sequence< Type > SAL_CALL OStatement::getTypes() throw(RuntimeException) { return concatSequences(OStatement_Base::getTypes(), OStatementCommonBase::getTypes()); } void SAL_CALL OStatement::close() throw(SQLException, RuntimeException) { OStatementCommonBase::close(); } void SAL_CALL OStatement::disposing() { disposeResultSet(); close(); } /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <commit_msg>Add some debug output. (firebird-sdbc)<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* * This file is part of the LibreOffice project. * * 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/. * * This file incorporates work covered by the following license notice: * * 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 . */ #include "Connection.hxx" #include "Driver.hxx" #include "ResultSet.hxx" #include "Statement.hxx" #include "Util.hxx" #include <comphelper/sequence.hxx> #include <osl/diagnose.h> #include <osl/thread.h> #include <rtl/ustrbuf.hxx> #include <com/sun/star/lang/DisposedException.hpp> #include <com/sun/star/sdbc/ResultSetConcurrency.hpp> #include <com/sun/star/sdbc/ResultSetType.hpp> #include <com/sun/star/sdbc/FetchDirection.hpp> using namespace connectivity::firebird; using namespace com::sun::star; using namespace com::sun::star::uno; using namespace com::sun::star::lang; using namespace com::sun::star::beans; using namespace com::sun::star::sdbc; using namespace com::sun::star::sdbcx; using namespace com::sun::star::container; using namespace com::sun::star::io; using namespace com::sun::star::util; using namespace ::comphelper; using namespace ::osl; using namespace ::rtl; using namespace ::std; // ---- XBatchExecution - UNSUPPORTED ---------------------------------------- void SAL_CALL OStatement::addBatch(const OUString& sql) throw(SQLException, RuntimeException) { (void) sql; } void SAL_CALL OStatement::clearBatch() throw(SQLException, RuntimeException) { } Sequence< sal_Int32 > SAL_CALL OStatement::executeBatch() throw(SQLException, RuntimeException) { return Sequence< sal_Int32 >(); } IMPLEMENT_SERVICE_INFO(OStatement,"com.sun.star.sdbcx.OStatement","com.sun.star.sdbc.Statement"); void SAL_CALL OStatement::acquire() throw() { OStatementCommonBase::acquire(); } void SAL_CALL OStatement::release() throw() { OStatementCommonBase::release(); } void OStatement::disposeResultSet() { MutexGuard aGuard(m_pConnection->getMutex()); checkDisposed(OStatementCommonBase_Base::rBHelper.bDisposed); OStatementCommonBase::disposeResultSet(); if (m_pSqlda) { freeSQLVAR(m_pSqlda); free(m_pSqlda); m_pSqlda = 0; } } // ---- XStatement ----------------------------------------------------------- sal_Int32 SAL_CALL OStatement::executeUpdate(const OUString& sql) throw(SQLException, RuntimeException) { MutexGuard aGuard(m_pConnection->getMutex()); checkDisposed(OStatementCommonBase_Base::rBHelper.bDisposed); SAL_INFO("connectivity.firebird", "executeUpdate(" << sql << ")"); int aErr = isc_dsql_execute_immediate(m_statusVector, &m_pConnection->getDBHandle(), &m_pConnection->getTransaction(), 0, OUStringToOString(sql, RTL_TEXTENCODING_UTF8).getStr(), FIREBIRD_SQL_DIALECT, NULL); if (aErr) SAL_WARN("connectivity.firebird", "isc_dsql_execute_immediate failed" ); evaluateStatusVector(m_statusVector, sql, *this); // TODO: get number of changed rows with SELECT ROW_COUNT (use executeQuery) // return getUpdateCount(); return 0; } uno::Reference< XResultSet > SAL_CALL OStatement::executeQuery(const OUString& sql) throw(SQLException, RuntimeException) { MutexGuard aGuard(m_pConnection->getMutex()); checkDisposed(OStatementCommonBase_Base::rBHelper.bDisposed); SAL_INFO("connectivity.firebird", "executeQuery(" << sql << ")"); ISC_STATUS aErr = 0; disposeResultSet(); prepareAndDescribeStatement(sql, m_pSqlda); aErr = isc_dsql_execute(m_statusVector, &m_pConnection->getTransaction(), &m_aStatementHandle, 1, NULL); if (aErr) SAL_WARN("connectivity.firebird", "isc_dsql_execute failed"); m_xResultSet = new OResultSet(m_pConnection, uno::Reference< XInterface >(*this), m_aStatementHandle, m_pSqlda); // TODO: deal with cleanup evaluateStatusVector(m_statusVector, sql, *this); if (isDDLStatement(m_aStatementHandle)) m_pConnection->commit(); return m_xResultSet; } sal_Bool SAL_CALL OStatement::execute(const OUString& sql) throw(SQLException, RuntimeException) { uno::Reference< XResultSet > xResults = executeQuery(sql); return xResults.is(); // TODO: what if we have multiple results? } uno::Reference< XConnection > SAL_CALL OStatement::getConnection() throw(SQLException, RuntimeException) { MutexGuard aGuard(m_pConnection->getMutex()); checkDisposed(OStatementCommonBase_Base::rBHelper.bDisposed); return (uno::Reference< XConnection >)m_pConnection; } Any SAL_CALL OStatement::queryInterface( const Type & rType ) throw(RuntimeException) { Any aRet = OStatement_Base::queryInterface(rType); if(!aRet.hasValue()) aRet = ::cppu::queryInterface(rType,static_cast< XBatchExecution*> (this)); if(!aRet.hasValue()) aRet = OStatementCommonBase::queryInterface(rType); return aRet; } uno::Sequence< Type > SAL_CALL OStatement::getTypes() throw(RuntimeException) { return concatSequences(OStatement_Base::getTypes(), OStatementCommonBase::getTypes()); } void SAL_CALL OStatement::close() throw(SQLException, RuntimeException) { OStatementCommonBase::close(); } void SAL_CALL OStatement::disposing() { disposeResultSet(); close(); } /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <|endoftext|>
<commit_before>// Jubatus: Online machine learning framework for distributed environment // Copyright (C) 2011,2012 Preferred Infrastructure and Nippon Telegraph and Telephone Corporation. // // 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA #include "server_helper.hpp" #include <signal.h> #include <string> #include "../common/cht.hpp" #include "../common/membership.hpp" #include "../common/util.hpp" namespace jubatus { namespace server { namespace framework { using std::string; using std::ostringstream; namespace { string make_logfile_name(const server_argv& a) { std::ostringstream logfile; if (a.logdir != "") { logfile << a.logdir << '/'; logfile << a.program_name << '.'; logfile << a.eth << '_' << a.port; logfile << ".zklog."; logfile << getpid(); } return logfile.str(); } } // namespace server_helper_impl::server_helper_impl(const server_argv& a) { common::util::prepare_signal_handling(); if (a.daemon) { ::signal(SIGHUP, SIG_IGN); LOG(INFO) << "set daemon mode (SIGHUP is now ignored)"; } #ifdef HAVE_ZOOKEEPER_H if (!a.is_standalone()) { zk_.reset(common::create_lock_service("zk", a.z, a.zookeeper_timeout, make_logfile_name(a))); register_lock_service(zk_); } #endif } server_helper_impl::~server_helper_impl() { zk_config_lock_.reset(); zk_.reset(); #ifdef HAVE_ZOOKEEPER_H close_lock_service(); #endif } void server_helper_impl::prepare_for_start(const server_argv& a, bool use_cht) { #ifdef HAVE_ZOOKEEPER_H if (!a.is_standalone()) { common::prepare_jubatus(*zk_, a.type, a.name); if (a.join) { // join to the existing cluster with -j option LOG(INFO) << "joining to the cluseter " << a.name; LOG(ERROR) << "join is not supported yet :("; } } #endif } void term_if_deleted(string path) { LOG(INFO) << "My actor [" << path << "] was deleted, preparing for finish"; kill(getpid(), SIGINT); } void server_helper_impl::prepare_for_run(const server_argv& a, bool use_cht) { #ifdef HAVE_ZOOKEEPER_H if (!a.is_standalone()) { if (use_cht) { common::cht::setup_cht_dir(*zk_, a.type, a.name); common::cht ht(zk_, a.type, a.name); ht.register_node(a.eth, a.port); } register_actor(*zk_, a.type, a.name, a.eth, a.port); // if regestered actor was deleted, this server should finish watch_delete_actor(*zk_, a.type, a.name, a.eth, a.port, term_if_deleted); LOG(INFO) << "registered group membership"; } #endif } void server_helper_impl::get_config_lock(const server_argv& a, int retry) { #ifdef HAVE_ZOOKEEPER_H if (!a.is_standalone()) { string lock_path; common::build_config_lock_path(lock_path, a.type, a.name); zk_config_lock_ = jubatus::util::lang::shared_ptr<common::try_lockable>( new common::lock_service_mutex(*zk_, lock_path)); while (!zk_config_lock_->try_rlock()) { if (retry == 0) { throw JUBATUS_EXCEPTION( core::common::exception::runtime_error( "any user is writing config?")); } retry--; sleep(1); } } #endif } } // namespace framework } // namespace server } // namespace jubatus <commit_msg>Show warning if log output is tty in daemon mode<commit_after>// Jubatus: Online machine learning framework for distributed environment // Copyright (C) 2011,2012 Preferred Infrastructure and Nippon Telegraph and Telephone Corporation. // // 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA #include "server_helper.hpp" #include <unistd.h> #include <signal.h> #include <string> #include "../common/cht.hpp" #include "../common/membership.hpp" #include "../common/util.hpp" namespace jubatus { namespace server { namespace framework { using std::string; using std::ostringstream; namespace { string make_logfile_name(const server_argv& a) { std::ostringstream logfile; if (a.logdir != "") { logfile << a.logdir << '/'; logfile << a.program_name << '.'; logfile << a.eth << '_' << a.port; logfile << ".zklog."; logfile << getpid(); } return logfile.str(); } } // namespace server_helper_impl::server_helper_impl(const server_argv& a) { common::util::prepare_signal_handling(); if (a.daemon) { if (a.logdir == "" && ::isatty(::fileno(stderr))) { LOG(WARNING) << "output tty in daemon mode"; } if (::signal(SIGHUP, SIG_IGN) == SIG_ERR) { LOG(FATAL) << "Failed to ignore SIGHUP"; } LOG(INFO) << "set daemon mode (SIGHUP is now ignored)"; } #ifdef HAVE_ZOOKEEPER_H if (!a.is_standalone()) { zk_.reset(common::create_lock_service("zk", a.z, a.zookeeper_timeout, make_logfile_name(a))); register_lock_service(zk_); } #endif } server_helper_impl::~server_helper_impl() { zk_config_lock_.reset(); zk_.reset(); #ifdef HAVE_ZOOKEEPER_H close_lock_service(); #endif } void server_helper_impl::prepare_for_start(const server_argv& a, bool use_cht) { #ifdef HAVE_ZOOKEEPER_H if (!a.is_standalone()) { common::prepare_jubatus(*zk_, a.type, a.name); if (a.join) { // join to the existing cluster with -j option LOG(INFO) << "joining to the cluseter " << a.name; LOG(ERROR) << "join is not supported yet :("; } } #endif } void term_if_deleted(string path) { LOG(INFO) << "My actor [" << path << "] was deleted, preparing for finish"; kill(getpid(), SIGINT); } void server_helper_impl::prepare_for_run(const server_argv& a, bool use_cht) { #ifdef HAVE_ZOOKEEPER_H if (!a.is_standalone()) { if (use_cht) { common::cht::setup_cht_dir(*zk_, a.type, a.name); common::cht ht(zk_, a.type, a.name); ht.register_node(a.eth, a.port); } register_actor(*zk_, a.type, a.name, a.eth, a.port); // if regestered actor was deleted, this server should finish watch_delete_actor(*zk_, a.type, a.name, a.eth, a.port, term_if_deleted); LOG(INFO) << "registered group membership"; } #endif } void server_helper_impl::get_config_lock(const server_argv& a, int retry) { #ifdef HAVE_ZOOKEEPER_H if (!a.is_standalone()) { string lock_path; common::build_config_lock_path(lock_path, a.type, a.name); zk_config_lock_ = jubatus::util::lang::shared_ptr<common::try_lockable>( new common::lock_service_mutex(*zk_, lock_path)); while (!zk_config_lock_->try_rlock()) { if (retry == 0) { throw JUBATUS_EXCEPTION( core::common::exception::runtime_error( "any user is writing config?")); } retry--; sleep(1); } } #endif } } // namespace framework } // namespace server } // namespace jubatus <|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; version 3 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. */ #include "sqlhighlighter.h" #include "config.h" QVector<SqlHighlighter::HighlightRule> SqlHighlighter::highlightingRules; QStringList SqlHighlighter::basicSqlKeywords; QRegExp SqlHighlighter::beginBlockMarkers[2]; QTextCharFormat SqlHighlighter::blockFormats[2]; QRegExp SqlHighlighter::endBlockMarkers[2]; QStringList SqlHighlighter::sqlFunctions; QStringList SqlHighlighter::sqlTypes; /* * Blockstates : * 0 : nothing special * 1 : string * 2 : comment */ SqlHighlighter::SqlHighlighter( QTextEdit *parent ) : QSyntaxHighlighter( parent ) { QMap<QString,QColor> colors = Config::shColor; QMap<QString,QTextCharFormat> formats = Config::shFormat; HighlightRule rule; // basic SQL syntax foreach( const QString &pattern, basicSqlKeywords ) { rule.format = formats["sql_basics"]; rule.format.setForeground( colors["sql_basics"] ); rule.pattern = QRegExp( "\\b" + pattern.toLower() + "\\b" ); highlightingRules.append( rule ); rule.pattern = QRegExp( "\\b" + pattern.toUpper() + "\\b" ); highlightingRules.append( rule ); } // SQL functions foreach( const QString &pattern, sqlFunctions ) { rule.format = formats["sql_functions"]; rule.format.setForeground( colors["sql_functions"] ); rule.pattern = QRegExp( "\\b" + pattern.toLower() + "\\b" ); highlightingRules.append( rule ); rule.pattern = QRegExp( "\\b" + pattern.toUpper() + "\\b" ); highlightingRules.append( rule ); } // SQL types foreach( const QString &pattern, sqlTypes ) { rule.format = formats["sql_types"]; rule.format.setForeground( colors["sql_types"] ); rule.pattern = QRegExp( "\\b" + pattern.toLower() + "\\b" ); highlightingRules.append( rule ); rule.pattern = QRegExp( "\\b" + pattern.toUpper() + "\\b" ); highlightingRules.append( rule ); } // numbers rule.format = formats["numbers"]; rule.format.setForeground( colors["numbers"] ); rule.pattern = QRegExp( "\\b\\d+\\.?\\d*\\b" ); highlightingRules << rule; /* * Blocks */ blockFormats[0] = formats["strings"]; blockFormats[0].setForeground( colors["strings"] ); blockFormats[1] = formats["comments"]; blockFormats[1].setForeground( colors["comments"] ); beginBlockMarkers[0] = QRegExp( "(\"|'|`)" ); beginBlockMarkers[1] = QRegExp( "--" ); endBlockMarkers[0] = QRegExp( "(\"|'|`)" ); endBlockMarkers[1] = QRegExp( "\n" ); } void SqlHighlighter::highlightBlock( const QString &block ) { if( block.isEmpty() || block.isNull() ) return; // keywords foreach( const HighlightRule &rule, highlightingRules ) { QRegExp expression( rule.pattern ); int index = expression.indexIn( block ); while( index >= 0 ) { int length = expression.matchedLength(); setFormat( index, length, rule.format ); index = expression.indexIn( block, index + length ); } } // context foreach( const HighlightRule &rule, contextRules ) { QRegExp expression( rule.pattern ); int index = expression.indexIn( block ); while( index >= 0 ) { int length = expression.matchedLength(); setFormat( index, length, rule.format ); index = expression.indexIn( block, index + length ); } } /* * Handling blocks (comments, strings, etc.) */ setCurrentBlockState(0); int startIndex = 0; /* * Each block category (comments, strings, etc.) will be analysed. */ for( int s = 0; s < 2; s++ ) { if( previousBlockState() != s + 1 ) startIndex = block.indexOf( beginBlockMarkers[s] ); // if startIndex < 0, it means all blocks have been proceeded while( startIndex >= 0 ) { // strings have a special case :) if( s == 0 ) endBlockMarkers[0] = QRegExp( block.at( startIndex ) ); int endIndex = block.indexOf( endBlockMarkers[s], startIndex + 1); int length; // does the block end anywhere ? if( endIndex == -1 ) { setCurrentBlockState( s + 1 ); length = block.length() - startIndex; } else { length = endIndex - startIndex + beginBlockMarkers[s].matchedLength(); } // applying syntax format setFormat( startIndex, length, blockFormats[s] ); startIndex = block.indexOf( beginBlockMarkers[s], startIndex + length ); } } } void SqlHighlighter::reloadColors() { } void SqlHighlighter::reloadContext(QStringList tables, QMultiMap<QString, QString>fields) { contextRules.clear(); HighlightRule r; foreach( QString t, tables ) { r.pattern = QRegExp( "\\b" + t + "\\b" ); r.format = Config::shFormat["ctxt_table"]; r.format.setForeground( Config::shColor["ctxt_table"] ); r.format.setUnderlineStyle(QTextCharFormat::SingleUnderline); contextRules << r; } QStringList l = fields.values(); #if QT_VERSION >= 0x040500 l.removeDuplicates(); #endif foreach( QString f, l ) { r.pattern = QRegExp( "\\b" + f + "\\b" ); r.format = Config::shFormat["ctxt_field"]; r.format.setForeground( Config::shColor["ctxt_field"] ); contextRules << r; } rehighlight(); } void SqlHighlighter::reloadKeywords() { basicSqlKeywords.clear(); sqlFunctions.clear(); sqlTypes.clear(); QStringList files; QString prefix; #if defined( Q_WS_X11 ) prefix = QString( PREFIX ).append( "/share/dbmaster/sqlsyntax/" ); #endif #if defined(Q_WS_WIN) prefix = "share/sqlsyntax/"; #endif files << "sql_basics" << "sql_functions" << "sql_types"; for( int i=0; i<files.size(); i++ ) { QFile file( files[i].prepend( prefix ) ); if( !file.open( QIODevice::ReadOnly | QIODevice::Text ) ) { qDebug() << "Cannot open " << file.fileName(); return; } while( !file.atEnd() ) { QString line = file.readLine(); if( line.isEmpty() ) continue; line.remove( "\n" ); switch( i ) { case 0: basicSqlKeywords << line; break; case 1: sqlFunctions << line; break; case 2: sqlTypes << line; } } file.close(); } reloadColors(); } QStringList SqlHighlighter::sqlFunctionList() { return sqlFunctions; } QStringList SqlHighlighter::sqlKeywordList() { return basicSqlKeywords; } QStringList SqlHighlighter::sqlTypeList() { return sqlTypes; } <commit_msg>#988 [Windows] Aucune syntaxe SQL<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; version 3 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. */ #include "sqlhighlighter.h" #include "config.h" QVector<SqlHighlighter::HighlightRule> SqlHighlighter::highlightingRules; QStringList SqlHighlighter::basicSqlKeywords; QRegExp SqlHighlighter::beginBlockMarkers[2]; QTextCharFormat SqlHighlighter::blockFormats[2]; QRegExp SqlHighlighter::endBlockMarkers[2]; QStringList SqlHighlighter::sqlFunctions; QStringList SqlHighlighter::sqlTypes; /* * Blockstates : * 0 : nothing special * 1 : string * 2 : comment */ SqlHighlighter::SqlHighlighter( QTextEdit *parent ) : QSyntaxHighlighter( parent ) { QMap<QString,QColor> colors = Config::shColor; QMap<QString,QTextCharFormat> formats = Config::shFormat; HighlightRule rule; // basic SQL syntax foreach( const QString &pattern, basicSqlKeywords ) { rule.format = formats["sql_basics"]; rule.format.setForeground( colors["sql_basics"] ); rule.pattern = QRegExp( "\\b" + pattern.toLower() + "\\b" ); highlightingRules.append( rule ); rule.pattern = QRegExp( "\\b" + pattern.toUpper() + "\\b" ); highlightingRules.append( rule ); } // SQL functions foreach( const QString &pattern, sqlFunctions ) { rule.format = formats["sql_functions"]; rule.format.setForeground( colors["sql_functions"] ); rule.pattern = QRegExp( "\\b" + pattern.toLower() + "\\b" ); highlightingRules.append( rule ); rule.pattern = QRegExp( "\\b" + pattern.toUpper() + "\\b" ); highlightingRules.append( rule ); } // SQL types foreach( const QString &pattern, sqlTypes ) { rule.format = formats["sql_types"]; rule.format.setForeground( colors["sql_types"] ); rule.pattern = QRegExp( "\\b" + pattern.toLower() + "\\b" ); highlightingRules.append( rule ); rule.pattern = QRegExp( "\\b" + pattern.toUpper() + "\\b" ); highlightingRules.append( rule ); } // numbers rule.format = formats["numbers"]; rule.format.setForeground( colors["numbers"] ); rule.pattern = QRegExp( "\\b\\d+\\.?\\d*\\b" ); highlightingRules << rule; /* * Blocks */ blockFormats[0] = formats["strings"]; blockFormats[0].setForeground( colors["strings"] ); blockFormats[1] = formats["comments"]; blockFormats[1].setForeground( colors["comments"] ); beginBlockMarkers[0] = QRegExp( "(\"|'|`)" ); beginBlockMarkers[1] = QRegExp( "--" ); endBlockMarkers[0] = QRegExp( "(\"|'|`)" ); endBlockMarkers[1] = QRegExp( "\n" ); } void SqlHighlighter::highlightBlock( const QString &block ) { if( block.isEmpty() || block.isNull() ) return; // keywords foreach( const HighlightRule &rule, highlightingRules ) { QRegExp expression( rule.pattern ); int index = expression.indexIn( block ); while( index >= 0 ) { int length = expression.matchedLength(); setFormat( index, length, rule.format ); index = expression.indexIn( block, index + length ); } } // context foreach( const HighlightRule &rule, contextRules ) { QRegExp expression( rule.pattern ); int index = expression.indexIn( block ); while( index >= 0 ) { int length = expression.matchedLength(); setFormat( index, length, rule.format ); index = expression.indexIn( block, index + length ); } } /* * Handling blocks (comments, strings, etc.) */ setCurrentBlockState(0); int startIndex = 0; /* * Each block category (comments, strings, etc.) will be analysed. */ for( int s = 0; s < 2; s++ ) { if( previousBlockState() != s + 1 ) startIndex = block.indexOf( beginBlockMarkers[s] ); // if startIndex < 0, it means all blocks have been proceeded while( startIndex >= 0 ) { // strings have a special case :) if( s == 0 ) endBlockMarkers[0] = QRegExp( block.at( startIndex ) ); int endIndex = block.indexOf( endBlockMarkers[s], startIndex + 1); int length; // does the block end anywhere ? if( endIndex == -1 ) { setCurrentBlockState( s + 1 ); length = block.length() - startIndex; } else { length = endIndex - startIndex + beginBlockMarkers[s].matchedLength(); } // applying syntax format setFormat( startIndex, length, blockFormats[s] ); startIndex = block.indexOf( beginBlockMarkers[s], startIndex + length ); } } } void SqlHighlighter::reloadColors() { } void SqlHighlighter::reloadContext(QStringList tables, QMultiMap<QString, QString>fields) { contextRules.clear(); HighlightRule r; foreach( QString t, tables ) { r.pattern = QRegExp( "\\b" + t + "\\b" ); r.format = Config::shFormat["ctxt_table"]; r.format.setForeground( Config::shColor["ctxt_table"] ); r.format.setUnderlineStyle(QTextCharFormat::SingleUnderline); contextRules << r; } QStringList l = fields.values(); #if QT_VERSION >= 0x040500 l.removeDuplicates(); #endif foreach( QString f, l ) { r.pattern = QRegExp( "\\b" + f + "\\b" ); r.format = Config::shFormat["ctxt_field"]; r.format.setForeground( Config::shColor["ctxt_field"] ); contextRules << r; } rehighlight(); } void SqlHighlighter::reloadKeywords() { basicSqlKeywords.clear(); sqlFunctions.clear(); sqlTypes.clear(); QStringList files; QString prefix; #if defined( Q_WS_X11 ) prefix = QString( PREFIX ).append( "/share/dbmaster/sqlsyntax/" ); #endif #if defined(Q_WS_WIN) prefix = QString(PREFIX).append("\\share\\sqlsyntax\\"); #endif files << "sql_basics" << "sql_functions" << "sql_types"; for( int i=0; i<files.size(); i++ ) { QFile file( files[i].prepend( prefix ) ); if( !file.open( QIODevice::ReadOnly | QIODevice::Text ) ) { qDebug() << "Cannot open " << file.fileName(); return; } while( !file.atEnd() ) { QString line = file.readLine(); if( line.isEmpty() ) continue; line.remove( "\n" ); switch( i ) { case 0: basicSqlKeywords << line; break; case 1: sqlFunctions << line; break; case 2: sqlTypes << line; } } file.close(); } reloadColors(); } QStringList SqlHighlighter::sqlFunctionList() { return sqlFunctions; } QStringList SqlHighlighter::sqlKeywordList() { return basicSqlKeywords; } QStringList SqlHighlighter::sqlTypeList() { return sqlTypes; } <|endoftext|>
<commit_before>/* * Copyright (c) 2007 MIPS Technologies, 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 the copyright holders 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. * * Authors: Korey Sewell * */ #include "config/the_isa.hh" #include "cpu/inorder/resources/fetch_seq_unit.hh" #include "cpu/inorder/resource_pool.hh" using namespace std; using namespace TheISA; using namespace ThePipeline; FetchSeqUnit::FetchSeqUnit(std::string res_name, int res_id, int res_width, int res_latency, InOrderCPU *_cpu, ThePipeline::Params *params) : Resource(res_name, res_id, res_width, res_latency, _cpu), instSize(sizeof(MachInst)) { for (ThreadID tid = 0; tid < ThePipeline::MaxThreads; tid++) { delaySlotInfo[tid].numInsts = 0; delaySlotInfo[tid].targetReady = false; pcValid[tid] = false; pcBlockStage[tid] = 0; squashSeqNum[tid] = (InstSeqNum)-1; lastSquashCycle[tid] = 0; } } FetchSeqUnit::~FetchSeqUnit() { delete [] resourceEvent; } void FetchSeqUnit::init() { resourceEvent = new FetchSeqEvent[width]; initSlots(); } void FetchSeqUnit::execute(int slot_num) { // After this is working, change this to a reinterpret cast // for performance considerations ResourceRequest* fs_req = reqMap[slot_num]; DynInstPtr inst = fs_req->inst; ThreadID tid = inst->readTid(); int stage_num = fs_req->getStageNum(); int seq_num = inst->seqNum; fs_req->fault = NoFault; switch (fs_req->cmd) { case AssignNextPC: { if (pcValid[tid]) { if (delaySlotInfo[tid].targetReady && delaySlotInfo[tid].numInsts == 0) { // Set PC to target PC[tid] = delaySlotInfo[tid].targetAddr; //next_PC nextPC[tid] = PC[tid] + instSize; //next_NPC nextNPC[tid] = PC[tid] + (2 * instSize); delaySlotInfo[tid].targetReady = false; DPRINTF(InOrderFetchSeq, "[tid:%i]: Setting PC to delay slot target\n",tid); } inst->setPC(PC[tid]); inst->setNextPC(PC[tid] + instSize); inst->setNextNPC(PC[tid] + (instSize * 2)); #if ISA_HAS_DELAY_SLOT inst->setPredTarg(inst->readNextNPC()); #else inst->setPredTarg(inst->readNextPC()); #endif inst->setMemAddr(PC[tid]); inst->setSeqNum(cpu->getAndIncrementInstSeq(tid)); DPRINTF(InOrderFetchSeq, "[tid:%i]: Assigning [sn:%i] to PC %08p, NPC %08p, NNPC %08p\n", tid, inst->seqNum, inst->readPC(), inst->readNextPC(), inst->readNextNPC()); if (delaySlotInfo[tid].numInsts > 0) { --delaySlotInfo[tid].numInsts; // It's OK to set PC to target of branch if (delaySlotInfo[tid].numInsts == 0) { delaySlotInfo[tid].targetReady = true; } DPRINTF(InOrderFetchSeq, "[tid:%i]: %i delay slot inst(s) left to" " process.\n", tid, delaySlotInfo[tid].numInsts); } PC[tid] = nextPC[tid]; nextPC[tid] = nextNPC[tid]; nextNPC[tid] += instSize; fs_req->done(); } else { DPRINTF(InOrderStall, "STALL: [tid:%i]: NPC not valid\n", tid); fs_req->setCompleted(false); } } break; case UpdateTargetPC: { if (inst->isControl()) { // If it's a return, then we must wait for resolved address. if (inst->isReturn() && !inst->predTaken()) { cpu->pipelineStage[stage_num]->toPrevStages->stageBlock[stage_num][tid] = true; pcValid[tid] = false; pcBlockStage[tid] = stage_num; } else if (inst->isCondDelaySlot() && !inst->predTaken()) { // Not-Taken AND Conditional Control DPRINTF(InOrderFetchSeq, "[tid:%i]: [sn:%i]: [PC:%08p] Predicted Not-Taken Cond. " "Delay inst. Skipping delay slot and Updating PC to %08p\n", tid, inst->seqNum, inst->readPC(), inst->readPredTarg()); DPRINTF(InOrderFetchSeq, "[tid:%i] Setting up squash to start from stage %i, after [sn:%i].\n", tid, stage_num, seq_num); inst->bdelaySeqNum = seq_num; inst->squashingStage = stage_num; squashAfterInst(inst, stage_num, tid); } else if (!inst->isCondDelaySlot() && !inst->predTaken()) { // Not-Taken Control DPRINTF(InOrderFetchSeq, "[tid:%i]: [sn:%i]: Predicted Not-Taken Control " "inst. updating PC to %08p\n", tid, inst->seqNum, inst->readNextPC()); #if ISA_HAS_DELAY_SLOT ++delaySlotInfo[tid].numInsts; delaySlotInfo[tid].targetReady = false; delaySlotInfo[tid].targetAddr = inst->readNextNPC(); #else assert(delaySlotInfo[tid].numInsts == 0); #endif } else if (inst->predTaken()) { // Taken Control #if ISA_HAS_DELAY_SLOT ++delaySlotInfo[tid].numInsts; delaySlotInfo[tid].targetReady = false; delaySlotInfo[tid].targetAddr = inst->readPredTarg(); DPRINTF(InOrderFetchSeq, "[tid:%i]: [sn:%i] Updating delay slot target " "to PC %08p\n", tid, inst->seqNum, inst->readPredTarg()); inst->bdelaySeqNum = seq_num + 1; #else inst->bdelaySeqNum = seq_num; assert(delaySlotInfo[tid].numInsts == 0); #endif inst->squashingStage = stage_num; DPRINTF(InOrderFetchSeq, "[tid:%i] Setting up squash to start from stage %i, after [sn:%i].\n", tid, stage_num, inst->bdelaySeqNum); // Do Squashing squashAfterInst(inst, stage_num, tid); } } else { DPRINTF(InOrderFetchSeq, "[tid:%i]: [sn:%i]: Ignoring branch target update " "since then is not a control instruction.\n", tid, inst->seqNum); } fs_req->done(); } break; default: fatal("Unrecognized command to %s", resName); } } inline void FetchSeqUnit::squashAfterInst(DynInstPtr inst, int stage_num, ThreadID tid) { // Squash In Pipeline Stage cpu->pipelineStage[stage_num]->squashDueToBranch(inst, tid); // Squash inside current resource, so if there needs to be fetching on same cycle // the fetch information will be correct. // squash(inst, stage_num, inst->bdelaySeqNum, tid); // Schedule Squash Through-out Resource Pool cpu->resPool->scheduleEvent((InOrderCPU::CPUEventType)ResourcePool::SquashAll, inst, 0); } void FetchSeqUnit::squash(DynInstPtr inst, int squash_stage, InstSeqNum squash_seq_num, ThreadID tid) { DPRINTF(InOrderFetchSeq, "[tid:%i]: Updating due to squash from stage %i.\n", tid, squash_stage); InstSeqNum done_seq_num = inst->bdelaySeqNum; Addr new_PC = inst->readPredTarg(); if (squashSeqNum[tid] <= done_seq_num && lastSquashCycle[tid] == curTick) { DPRINTF(InOrderFetchSeq, "[tid:%i]: Ignoring squash from stage %i, since" "there is an outstanding squash that is older.\n", tid, squash_stage); } else { squashSeqNum[tid] = done_seq_num; lastSquashCycle[tid] = curTick; // If The very next instruction number is the done seq. num, // then we haven't seen the delay slot yet ... if it isn't // the last done_seq_num then this is the delay slot inst. if (cpu->nextInstSeqNum(tid) != done_seq_num && !inst->procDelaySlotOnMispred) { delaySlotInfo[tid].numInsts = 0; delaySlotInfo[tid].targetReady = false; // Reset PC PC[tid] = new_PC; nextPC[tid] = new_PC + instSize; nextNPC[tid] = new_PC + (2 * instSize); DPRINTF(InOrderFetchSeq, "[tid:%i]: Setting PC to %08p.\n", tid, PC[tid]); } else { #if !ISA_HAS_DELAY_SLOT assert(0); #endif delaySlotInfo[tid].numInsts = 1; delaySlotInfo[tid].targetReady = false; delaySlotInfo[tid].targetAddr = (inst->procDelaySlotOnMispred) ? inst->branchTarget() : new_PC; // Reset PC to Delay Slot Instruction if (inst->procDelaySlotOnMispred) { PC[tid] = new_PC; nextPC[tid] = new_PC + instSize; nextNPC[tid] = new_PC + (2 * instSize); } } // Unblock Any Stages Waiting for this information to be updated ... if (!pcValid[tid]) { cpu->pipelineStage[pcBlockStage[tid]]->toPrevStages->stageUnblock[pcBlockStage[tid]][tid] = true; } pcValid[tid] = true; } Resource::squash(inst, squash_stage, squash_seq_num, tid); } FetchSeqUnit::FetchSeqEvent::FetchSeqEvent() : ResourceEvent() { } void FetchSeqUnit::FetchSeqEvent::process() { FetchSeqUnit* fs_res = dynamic_cast<FetchSeqUnit*>(resource); assert(fs_res); for (int i=0; i < MaxThreads; i++) { fs_res->PC[i] = fs_res->cpu->readPC(i); fs_res->nextPC[i] = fs_res->cpu->readNextPC(i); fs_res->nextNPC[i] = fs_res->cpu->readNextNPC(i); DPRINTF(InOrderFetchSeq, "[tid:%i]: Setting PC:%08p NPC:%08p NNPC:%08p.\n", fs_res->PC[i], fs_res->nextPC[i], fs_res->nextNPC[i]); fs_res->pcValid[i] = true; } //cpu->fetchPriorityList.push_back(tid); } void FetchSeqUnit::activateThread(ThreadID tid) { pcValid[tid] = true; PC[tid] = cpu->readPC(tid); nextPC[tid] = cpu->readNextPC(tid); nextNPC[tid] = cpu->readNextNPC(tid); cpu->fetchPriorityList.push_back(tid); DPRINTF(InOrderFetchSeq, "[tid:%i]: Reading PC:%08p NPC:%08p NNPC:%08p.\n", tid, PC[tid], nextPC[tid], nextNPC[tid]); } void FetchSeqUnit::deactivateThread(ThreadID tid) { delaySlotInfo[tid].numInsts = 0; delaySlotInfo[tid].targetReady = false; pcValid[tid] = false; pcBlockStage[tid] = 0; squashSeqNum[tid] = (InstSeqNum)-1; lastSquashCycle[tid] = 0; list<ThreadID>::iterator thread_it = find(cpu->fetchPriorityList.begin(), cpu->fetchPriorityList.end(), tid); if (thread_it != cpu->fetchPriorityList.end()) cpu->fetchPriorityList.erase(thread_it); } void FetchSeqUnit::suspendThread(ThreadID tid) { deactivateThread(tid); } void FetchSeqUnit::updateAfterContextSwitch(DynInstPtr inst, ThreadID tid) { pcValid[tid] = true; if (cpu->thread[tid]->lastGradIsBranch) { /** This function assumes that the instruction causing the context * switch was right after the branch. Thus, if it's not, then * we are updating incorrectly here */ assert(cpu->thread[tid]->lastBranchNextPC == inst->readPC()); PC[tid] = cpu->thread[tid]->lastBranchNextNPC; nextPC[tid] = PC[tid] + instSize; nextNPC[tid] = nextPC[tid] + instSize; } else { PC[tid] = inst->readNextPC(); nextPC[tid] = inst->readNextNPC(); nextNPC[tid] = inst->readNextNPC() + instSize; } DPRINTF(InOrderFetchSeq, "[tid:%i]: Updating PCs due to Context Switch." "Assigning PC:%08p NPC:%08p NNPC:%08p.\n", tid, PC[tid], nextPC[tid], nextNPC[tid]); } <commit_msg>inorder: squash from memory stall this applies to multithreading models which would like to squash a thread on memory stall<commit_after>/* * Copyright (c) 2007 MIPS Technologies, 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 the copyright holders 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. * * Authors: Korey Sewell * */ #include "config/the_isa.hh" #include "cpu/inorder/resources/fetch_seq_unit.hh" #include "cpu/inorder/resource_pool.hh" using namespace std; using namespace TheISA; using namespace ThePipeline; FetchSeqUnit::FetchSeqUnit(std::string res_name, int res_id, int res_width, int res_latency, InOrderCPU *_cpu, ThePipeline::Params *params) : Resource(res_name, res_id, res_width, res_latency, _cpu), instSize(sizeof(MachInst)) { for (ThreadID tid = 0; tid < ThePipeline::MaxThreads; tid++) { delaySlotInfo[tid].numInsts = 0; delaySlotInfo[tid].targetReady = false; pcValid[tid] = false; pcBlockStage[tid] = 0; squashSeqNum[tid] = (InstSeqNum)-1; lastSquashCycle[tid] = 0; } } FetchSeqUnit::~FetchSeqUnit() { delete [] resourceEvent; } void FetchSeqUnit::init() { resourceEvent = new FetchSeqEvent[width]; initSlots(); } void FetchSeqUnit::execute(int slot_num) { // After this is working, change this to a reinterpret cast // for performance considerations ResourceRequest* fs_req = reqMap[slot_num]; DynInstPtr inst = fs_req->inst; ThreadID tid = inst->readTid(); int stage_num = fs_req->getStageNum(); int seq_num = inst->seqNum; fs_req->fault = NoFault; switch (fs_req->cmd) { case AssignNextPC: { if (pcValid[tid]) { if (delaySlotInfo[tid].targetReady && delaySlotInfo[tid].numInsts == 0) { // Set PC to target PC[tid] = delaySlotInfo[tid].targetAddr; //next_PC nextPC[tid] = PC[tid] + instSize; //next_NPC nextNPC[tid] = PC[tid] + (2 * instSize); delaySlotInfo[tid].targetReady = false; DPRINTF(InOrderFetchSeq, "[tid:%i]: Setting PC to delay slot target\n",tid); } inst->setPC(PC[tid]); inst->setNextPC(PC[tid] + instSize); inst->setNextNPC(PC[tid] + (instSize * 2)); #if ISA_HAS_DELAY_SLOT inst->setPredTarg(inst->readNextNPC()); #else inst->setPredTarg(inst->readNextPC()); #endif inst->setMemAddr(PC[tid]); inst->setSeqNum(cpu->getAndIncrementInstSeq(tid)); DPRINTF(InOrderFetchSeq, "[tid:%i]: Assigning [sn:%i] to PC %08p, NPC %08p, NNPC %08p\n", tid, inst->seqNum, inst->readPC(), inst->readNextPC(), inst->readNextNPC()); if (delaySlotInfo[tid].numInsts > 0) { --delaySlotInfo[tid].numInsts; // It's OK to set PC to target of branch if (delaySlotInfo[tid].numInsts == 0) { delaySlotInfo[tid].targetReady = true; } DPRINTF(InOrderFetchSeq, "[tid:%i]: %i delay slot inst(s) left to" " process.\n", tid, delaySlotInfo[tid].numInsts); } PC[tid] = nextPC[tid]; nextPC[tid] = nextNPC[tid]; nextNPC[tid] += instSize; fs_req->done(); } else { DPRINTF(InOrderStall, "STALL: [tid:%i]: NPC not valid\n", tid); fs_req->setCompleted(false); } } break; case UpdateTargetPC: { if (inst->isControl()) { // If it's a return, then we must wait for resolved address. if (inst->isReturn() && !inst->predTaken()) { cpu->pipelineStage[stage_num]->toPrevStages->stageBlock[stage_num][tid] = true; pcValid[tid] = false; pcBlockStage[tid] = stage_num; } else if (inst->isCondDelaySlot() && !inst->predTaken()) { // Not-Taken AND Conditional Control DPRINTF(InOrderFetchSeq, "[tid:%i]: [sn:%i]: [PC:%08p] Predicted Not-Taken Cond. " "Delay inst. Skipping delay slot and Updating PC to %08p\n", tid, inst->seqNum, inst->readPC(), inst->readPredTarg()); DPRINTF(InOrderFetchSeq, "[tid:%i] Setting up squash to start from stage %i, after [sn:%i].\n", tid, stage_num, seq_num); inst->bdelaySeqNum = seq_num; inst->squashingStage = stage_num; squashAfterInst(inst, stage_num, tid); } else if (!inst->isCondDelaySlot() && !inst->predTaken()) { // Not-Taken Control DPRINTF(InOrderFetchSeq, "[tid:%i]: [sn:%i]: Predicted Not-Taken Control " "inst. updating PC to %08p\n", tid, inst->seqNum, inst->readNextPC()); #if ISA_HAS_DELAY_SLOT ++delaySlotInfo[tid].numInsts; delaySlotInfo[tid].targetReady = false; delaySlotInfo[tid].targetAddr = inst->readNextNPC(); #else assert(delaySlotInfo[tid].numInsts == 0); #endif } else if (inst->predTaken()) { // Taken Control #if ISA_HAS_DELAY_SLOT ++delaySlotInfo[tid].numInsts; delaySlotInfo[tid].targetReady = false; delaySlotInfo[tid].targetAddr = inst->readPredTarg(); DPRINTF(InOrderFetchSeq, "[tid:%i]: [sn:%i] Updating delay slot target " "to PC %08p\n", tid, inst->seqNum, inst->readPredTarg()); inst->bdelaySeqNum = seq_num + 1; #else inst->bdelaySeqNum = seq_num; assert(delaySlotInfo[tid].numInsts == 0); #endif inst->squashingStage = stage_num; DPRINTF(InOrderFetchSeq, "[tid:%i] Setting up squash to start from stage %i, after [sn:%i].\n", tid, stage_num, inst->bdelaySeqNum); // Do Squashing squashAfterInst(inst, stage_num, tid); } } else { DPRINTF(InOrderFetchSeq, "[tid:%i]: [sn:%i]: Ignoring branch target update " "since then is not a control instruction.\n", tid, inst->seqNum); } fs_req->done(); } break; default: fatal("Unrecognized command to %s", resName); } } inline void FetchSeqUnit::squashAfterInst(DynInstPtr inst, int stage_num, ThreadID tid) { // Squash In Pipeline Stage cpu->pipelineStage[stage_num]->squashDueToBranch(inst, tid); // Squash inside current resource, so if there needs to be fetching on same cycle // the fetch information will be correct. // squash(inst, stage_num, inst->bdelaySeqNum, tid); // Schedule Squash Through-out Resource Pool cpu->resPool->scheduleEvent((InOrderCPU::CPUEventType)ResourcePool::SquashAll, inst, 0); } void FetchSeqUnit::squash(DynInstPtr inst, int squash_stage, InstSeqNum squash_seq_num, ThreadID tid) { DPRINTF(InOrderFetchSeq, "[tid:%i]: Updating due to squash from stage %i.\n", tid, squash_stage); InstSeqNum done_seq_num = inst->bdelaySeqNum; // Handles the case where we are squashing because of something that is // not a branch...like a memory stall Addr new_PC = (inst->isControl()) ? inst->readPredTarg() : inst->readPC() + instSize; if (squashSeqNum[tid] <= done_seq_num && lastSquashCycle[tid] == curTick) { DPRINTF(InOrderFetchSeq, "[tid:%i]: Ignoring squash from stage %i, since" "there is an outstanding squash that is older.\n", tid, squash_stage); } else { squashSeqNum[tid] = done_seq_num; lastSquashCycle[tid] = curTick; // If The very next instruction number is the done seq. num, // then we haven't seen the delay slot yet ... if it isn't // the last done_seq_num then this is the delay slot inst. if (cpu->nextInstSeqNum(tid) != done_seq_num && !inst->procDelaySlotOnMispred) { delaySlotInfo[tid].numInsts = 0; delaySlotInfo[tid].targetReady = false; // Reset PC PC[tid] = new_PC; nextPC[tid] = new_PC + instSize; nextNPC[tid] = new_PC + (2 * instSize); DPRINTF(InOrderFetchSeq, "[tid:%i]: Setting PC to %08p.\n", tid, PC[tid]); } else { #if !ISA_HAS_DELAY_SLOT assert(0); #endif delaySlotInfo[tid].numInsts = 1; delaySlotInfo[tid].targetReady = false; delaySlotInfo[tid].targetAddr = (inst->procDelaySlotOnMispred) ? inst->branchTarget() : new_PC; // Reset PC to Delay Slot Instruction if (inst->procDelaySlotOnMispred) { PC[tid] = new_PC; nextPC[tid] = new_PC + instSize; nextNPC[tid] = new_PC + (2 * instSize); } } // Unblock Any Stages Waiting for this information to be updated ... if (!pcValid[tid]) { cpu->pipelineStage[pcBlockStage[tid]]->toPrevStages->stageUnblock[pcBlockStage[tid]][tid] = true; } pcValid[tid] = true; } Resource::squash(inst, squash_stage, squash_seq_num, tid); } FetchSeqUnit::FetchSeqEvent::FetchSeqEvent() : ResourceEvent() { } void FetchSeqUnit::FetchSeqEvent::process() { FetchSeqUnit* fs_res = dynamic_cast<FetchSeqUnit*>(resource); assert(fs_res); for (int i=0; i < MaxThreads; i++) { fs_res->PC[i] = fs_res->cpu->readPC(i); fs_res->nextPC[i] = fs_res->cpu->readNextPC(i); fs_res->nextNPC[i] = fs_res->cpu->readNextNPC(i); DPRINTF(InOrderFetchSeq, "[tid:%i]: Setting PC:%08p NPC:%08p NNPC:%08p.\n", fs_res->PC[i], fs_res->nextPC[i], fs_res->nextNPC[i]); fs_res->pcValid[i] = true; } //cpu->fetchPriorityList.push_back(tid); } void FetchSeqUnit::activateThread(ThreadID tid) { pcValid[tid] = true; PC[tid] = cpu->readPC(tid); nextPC[tid] = cpu->readNextPC(tid); nextNPC[tid] = cpu->readNextNPC(tid); cpu->fetchPriorityList.push_back(tid); DPRINTF(InOrderFetchSeq, "[tid:%i]: Reading PC:%08p NPC:%08p NNPC:%08p.\n", tid, PC[tid], nextPC[tid], nextNPC[tid]); } void FetchSeqUnit::deactivateThread(ThreadID tid) { delaySlotInfo[tid].numInsts = 0; delaySlotInfo[tid].targetReady = false; pcValid[tid] = false; pcBlockStage[tid] = 0; squashSeqNum[tid] = (InstSeqNum)-1; lastSquashCycle[tid] = 0; list<ThreadID>::iterator thread_it = find(cpu->fetchPriorityList.begin(), cpu->fetchPriorityList.end(), tid); if (thread_it != cpu->fetchPriorityList.end()) cpu->fetchPriorityList.erase(thread_it); } void FetchSeqUnit::suspendThread(ThreadID tid) { deactivateThread(tid); } void FetchSeqUnit::updateAfterContextSwitch(DynInstPtr inst, ThreadID tid) { pcValid[tid] = true; if (cpu->thread[tid]->lastGradIsBranch) { /** This function assumes that the instruction causing the context * switch was right after the branch. Thus, if it's not, then * we are updating incorrectly here */ assert(cpu->thread[tid]->lastBranchNextPC == inst->readPC()); PC[tid] = cpu->thread[tid]->lastBranchNextNPC; nextPC[tid] = PC[tid] + instSize; nextNPC[tid] = nextPC[tid] + instSize; } else { PC[tid] = inst->readNextPC(); nextPC[tid] = inst->readNextNPC(); nextNPC[tid] = inst->readNextNPC() + instSize; } DPRINTF(InOrderFetchSeq, "[tid:%i]: Updating PCs due to Context Switch." "Assigning PC:%08p NPC:%08p NNPC:%08p.\n", tid, PC[tid], nextPC[tid], nextNPC[tid]); } <|endoftext|>
<commit_before>/** * Policies * (C) 2004-2006 Jack Lloyd * * Released under the terms of the Botan license */ #include <botan/tls_policy.h> #include <botan/tls_exceptn.h> namespace Botan { /** * Return allowed ciphersuites */ std::vector<u16bit> TLS_Policy::ciphersuites() const { return suite_list(allow_static_rsa(), allow_edh_rsa(), allow_edh_dsa()); } /** * Return allowed ciphersuites */ std::vector<u16bit> TLS_Policy::suite_list(bool use_rsa, bool use_edh_rsa, bool use_edh_dsa) const { std::vector<u16bit> suites; if(use_edh_dsa) { suites.push_back(DHE_DSS_AES256_SHA); suites.push_back(DHE_DSS_AES128_SHA); suites.push_back(DHE_DSS_3DES_SHA); } if(use_edh_rsa) { suites.push_back(DHE_RSA_AES256_SHA); suites.push_back(DHE_RSA_AES128_SHA); suites.push_back(DHE_RSA_3DES_SHA); } if(use_rsa) { suites.push_back(RSA_AES256_SHA); suites.push_back(RSA_AES128_SHA); suites.push_back(RSA_3DES_SHA); suites.push_back(RSA_RC4_SHA); suites.push_back(RSA_RC4_MD5); } if(suites.size() == 0) throw TLS_Exception(INTERNAL_ERROR, "TLS_Policy error: All ciphersuites disabled"); return suites; } /** * Return allowed compression algorithms */ std::vector<byte> TLS_Policy::compression() const { std::vector<byte> algs; algs.push_back(NO_COMPRESSION); return algs; } /** * Choose which ciphersuite to use */ u16bit TLS_Policy::choose_suite(const std::vector<u16bit>& c_suites, bool have_rsa, bool have_dsa) const { bool use_static_rsa = allow_static_rsa() && have_rsa; bool use_edh_rsa = allow_edh_rsa() && have_rsa; bool use_edh_dsa = allow_edh_dsa() && have_dsa; std::vector<u16bit> s_suites = suite_list(use_static_rsa, use_edh_rsa, use_edh_dsa); for(u32bit j = 0; j != s_suites.size(); j++) for(u32bit k = 0; k != c_suites.size(); k++) if(s_suites[j] == c_suites[k]) return s_suites[j]; return 0; } /** * Choose which compression algorithm to use */ byte TLS_Policy::choose_compression(const std::vector<byte>& c_comp) const { std::vector<byte> s_comp = compression(); for(u32bit j = 0; j != s_comp.size(); j++) for(u32bit k = 0; k != c_comp.size(); k++) if(s_comp[j] == c_comp[k]) return s_comp[j]; return NO_COMPRESSION; } /** * Return the group to use for empheral DH */ DL_Group TLS_Policy::dh_group() const { return DL_Group("IETF-1024"); } /** * Default certificate check */ bool TLS_Policy::check_cert(const std::vector<X509_Certificate>&, const std::string&) const { return true; } } <commit_msg>Naming scheme for DL groups has changed<commit_after>/** * Policies * (C) 2004-2006 Jack Lloyd * * Released under the terms of the Botan license */ #include <botan/tls_policy.h> #include <botan/tls_exceptn.h> namespace Botan { /** * Return allowed ciphersuites */ std::vector<u16bit> TLS_Policy::ciphersuites() const { return suite_list(allow_static_rsa(), allow_edh_rsa(), allow_edh_dsa()); } /** * Return allowed ciphersuites */ std::vector<u16bit> TLS_Policy::suite_list(bool use_rsa, bool use_edh_rsa, bool use_edh_dsa) const { std::vector<u16bit> suites; if(use_edh_dsa) { suites.push_back(DHE_DSS_AES256_SHA); suites.push_back(DHE_DSS_AES128_SHA); suites.push_back(DHE_DSS_3DES_SHA); } if(use_edh_rsa) { suites.push_back(DHE_RSA_AES256_SHA); suites.push_back(DHE_RSA_AES128_SHA); suites.push_back(DHE_RSA_3DES_SHA); } if(use_rsa) { suites.push_back(RSA_AES256_SHA); suites.push_back(RSA_AES128_SHA); suites.push_back(RSA_3DES_SHA); suites.push_back(RSA_RC4_SHA); suites.push_back(RSA_RC4_MD5); } if(suites.size() == 0) throw TLS_Exception(INTERNAL_ERROR, "TLS_Policy error: All ciphersuites disabled"); return suites; } /** * Return allowed compression algorithms */ std::vector<byte> TLS_Policy::compression() const { std::vector<byte> algs; algs.push_back(NO_COMPRESSION); return algs; } /** * Choose which ciphersuite to use */ u16bit TLS_Policy::choose_suite(const std::vector<u16bit>& c_suites, bool have_rsa, bool have_dsa) const { bool use_static_rsa = allow_static_rsa() && have_rsa; bool use_edh_rsa = allow_edh_rsa() && have_rsa; bool use_edh_dsa = allow_edh_dsa() && have_dsa; std::vector<u16bit> s_suites = suite_list(use_static_rsa, use_edh_rsa, use_edh_dsa); for(u32bit j = 0; j != s_suites.size(); j++) for(u32bit k = 0; k != c_suites.size(); k++) if(s_suites[j] == c_suites[k]) return s_suites[j]; return 0; } /** * Choose which compression algorithm to use */ byte TLS_Policy::choose_compression(const std::vector<byte>& c_comp) const { std::vector<byte> s_comp = compression(); for(u32bit j = 0; j != s_comp.size(); j++) for(u32bit k = 0; k != c_comp.size(); k++) if(s_comp[j] == c_comp[k]) return s_comp[j]; return NO_COMPRESSION; } /** * Return the group to use for empheral DH */ DL_Group TLS_Policy::dh_group() const { return DL_Group("modp/ietf/1024"); } /** * Default certificate check */ bool TLS_Policy::check_cert(const std::vector<X509_Certificate>&, const std::string&) const { return true; } } <|endoftext|>
<commit_before>#include "juuhcode.hpp" const auto static comparison = [](const Node *first, const Node *second) { return first->frequency > second->frequency; }; // initialize with the given string JuuhCode::JuuhCode(const std::string &s) : stringToEncode(s) { std::cout << "Calculating frequencies..." << std::endl; calculateFrequencies(); std::cout << "Creating a tree..." << std::endl; createTree(); std::cout << "Generating Huffman code..." << std::endl; generateHuffmanCode(root, ""); std::cout << "Generating the encoded string..." << std::endl; generateEncodedString(); std::cout << std::endl; } // calculate character (byte) frequencies void JuuhCode::calculateFrequencies() { for (const auto c : stringToEncode) { ++(frequencies[static_cast<uint8_t>(c)]); } } // create the initial leaves and internal leaves void JuuhCode::createTree() { std::priority_queue<Node *, std::vector<Node *>, decltype(comparison)> tree( comparison); // loop through bytes ("characters") and push them into the queue uint8_t i = 0; do { const auto frequency = frequencies[i]; if (frequency == 0) { continue; } auto node = new Node(frequency, i); tree.push(node); } while (i++ != UINT8_MAX); // create internal nodes while (tree.size() > 1) { auto rightChild = tree.top(); tree.pop(); auto leftChild = tree.top(); tree.pop(); auto parent = new Node(leftChild, rightChild); tree.push(parent); } root = tree.top(); } // recursively generate huffman coding void JuuhCode::generateHuffmanCode(const Node *node, const std::string &code) { // assign a code if (!node->left && !node->right) { codes[node->character] = code; return; } generateHuffmanCode(node->left, code + "0"); generateHuffmanCode(node->right, code + "1"); } // print the codes void JuuhCode::printCodes() const { for (const auto &pair : codes) { auto character = pair.first; auto code = pair.second; std::cout << "'" << character << "': " << code << std::endl; } } void JuuhCode::generateEncodedString() { std::string encoded = ""; for (const char &c : stringToEncode) { encoded.append(codes.at(static_cast<uint8_t>(c))); } encodedString = encoded; } // print the encoded string void JuuhCode::printEncodedString() const { std::cout << encodedString << std::endl; } void JuuhCode::printStats() const { const size_t originalBytes = stringToEncode.length(); const size_t encodedBytes = encodedString.length() / 8; const double percentage = (static_cast<double>(encodedBytes) / static_cast<double>(originalBytes)) * 100; std::cout << "Original size:\t" << originalBytes << " bytes" << std::endl; std::cout << "Encoded size:\t" << encodedBytes << " bytes (" << percentage << "% of original)" << std::endl; } <commit_msg>refactor<commit_after>#include "juuhcode.hpp" const auto static comparison = [](const Node *first, const Node *second) { return first->frequency > second->frequency; }; // initialize with the given string JuuhCode::JuuhCode(const std::string &s) : stringToEncode(s) { std::cout << "Calculating frequencies..." << std::endl; calculateFrequencies(); std::cout << "Creating a tree..." << std::endl; createTree(); std::cout << "Generating Huffman code..." << std::endl; generateHuffmanCode(root, ""); std::cout << "Generating the encoded string..." << std::endl; generateEncodedString(); std::cout << std::endl; } // calculate character (byte) frequencies void JuuhCode::calculateFrequencies() { for (const auto &c : stringToEncode) { ++(frequencies[static_cast<uint8_t>(c)]); } } // create the initial leaves and internal leaves void JuuhCode::createTree() { std::priority_queue<Node *, std::vector<Node *>, decltype(comparison)> tree( comparison); // loop through bytes ("characters") and push them into the queue uint8_t i = 0; do { const auto frequency = frequencies[i]; if (frequency == 0) { continue; } auto node = new Node(frequency, i); tree.push(node); } while (i++ != UINT8_MAX); // create internal nodes while (tree.size() > 1) { auto rightChild = tree.top(); tree.pop(); auto leftChild = tree.top(); tree.pop(); auto parent = new Node(leftChild, rightChild); tree.push(parent); } root = tree.top(); } // recursively generate huffman coding void JuuhCode::generateHuffmanCode(const Node *node, const std::string &code) { // assign a code if (!node->left && !node->right) { codes[node->character] = code; return; } generateHuffmanCode(node->left, code + "0"); generateHuffmanCode(node->right, code + "1"); } // print the codes void JuuhCode::printCodes() const { for (const auto &pair : codes) { auto character = pair.first; auto code = pair.second; std::cout << "'" << character << "': " << code << std::endl; } } void JuuhCode::generateEncodedString() { std::string encoded = ""; for (const char &c : stringToEncode) { encoded.append(codes.at(static_cast<uint8_t>(c))); } encodedString = encoded; } // print the encoded string void JuuhCode::printEncodedString() const { std::cout << encodedString << std::endl; } void JuuhCode::printStats() const { const size_t originalBytes = stringToEncode.length(); const size_t encodedBytes = encodedString.length() / 8; const double percentage = (static_cast<double>(encodedBytes) / static_cast<double>(originalBytes)) * 100; std::cout << "Original size:\t" << originalBytes << " bytes" << std::endl; std::cout << "Encoded size:\t" << encodedBytes << " bytes (" << percentage << "% of original)" << std::endl; } <|endoftext|>
<commit_before>#include <vector> #include <string> #include <fstream> #include "boost/program_options.hpp" #include "boost/algorithm/string.hpp" #include "boost/lexical_cast.hpp" #include "vtrc-client-base/vtrc-client.h" #include "vtrc-common/vtrc-pool-pair.h" #include "vtrc-common/vtrc-exception.h" #include "remote-fs-iface.h" #include "vtrc-condition-variable.h" #include "vtrc-mutex.h" #include "vtrc-bind.h" #include "vtrc-ref.h" namespace po = boost::program_options; using namespace vtrc; void get_options( po::options_description& desc ) { desc.add_options( ) ("help,?", "help message") ("server,s", po::value<std::string>( ), "server name; <tcp address>:<port> or <pipe/file name>") ("path,p", po::value<std::string>( ), "Init remote path for client") ("pwd,w", "Show current remote path") ("info,i", po::value<std::string>( ), "Show info about remote path") ("list,l", "list remote directory") ("tree,t", "show remote directory as tree") ("pull,g", po::value<std::string>( ), "Download remote file") ("push,u", po::value<std::string>( ), "Upload local file") ("block-size,b", po::value<unsigned>( ), "Block size for pull and push" "; 1-44000") ; } void connect_to( client::vtrc_client_sptr client, std::string const &name ) { std::vector<std::string> params; std::string::const_reverse_iterator b(name.rbegin( )); std::string::const_reverse_iterator e(name.rend( )); for( ; b!=e ;++b ) { if( *b == ':' ) { std::string::const_reverse_iterator bb(b); ++bb; params.push_back( std::string( name.begin( ), bb.base( )) ); params.push_back( std::string( b.base( ), name.end( ))); break; } } if( params.empty( ) ) { params.push_back( name ); } if( params.size( ) == 1 ) { /// local name client->connect( params[0] ); } else if( params.size( ) == 2 ) { /// tcp client->connect( params[0], params[1]); } } void on_client_ready( vtrc::condition_variable &cond ) { std::cout << "Connection is ready...\n"; cond.notify_all( ); } std::string leaf_of( const std::string &path ) { std::string::const_reverse_iterator b(path.rbegin( )); std::string::const_reverse_iterator e(path.rend( )); for( ; b!=e ;++b ) { if( *b == '/' || *b == '\\' ) { return std::string( b.base( ), path.end( ) ); } } return path; } void list_dir( vtrc::shared_ptr<interfaces::remote_fs> &impl ) { vtrc::shared_ptr<interfaces::remote_fs_iterator> i(impl->begin_iterator( )); std::string lstring( 2, ' ' ); for( ; !i->end( ); i->next( )) { bool is_dir( i->info( ).is_directory_ ); std::cout << lstring << ( i->info( ).is_empty_ ? " " : "+" ); std::cout << ( is_dir ? "[" : " " ) << leaf_of(i->info( ).path_) << ( is_dir ? "]" : " " ) << "\n"; } } void push_file( client::vtrc_client_sptr client, const std::string &local_path, size_t block_size ) { std::string name = leaf_of( local_path ); vtrc::shared_ptr<interfaces::remote_file> rem_f ( interfaces::create_remote_file( client, name, "wb" ) ); std::cout << "Open remote file success.\n" << "Starting...\n" << "Block size = " << block_size << std::endl; std::ifstream f; f.open(local_path.c_str( ), std::ofstream::in ); std::string block(block_size, 0); size_t total = 0; size_t r = f.readsome( &block[0], block_size ); while( r ) { size_t shift = 0; while ( r ) { size_t w = rem_f->write( block.c_str( ) + shift, r ); total += w; shift += w; r -= w; std::cout << "Post " << total << " bytes\r"; } r = f.readsome( &block[0], block_size ); } std::cout << "\nUpload complete\n"; } void pull_file( client::vtrc_client_sptr client, vtrc::shared_ptr<interfaces::remote_fs> &impl, const std::string &remote_path, size_t block_size ) { size_t remote_size = -1; try { remote_size = impl->file_size( remote_path ); std::cout << "Remote file size is: " << remote_size << "\n"; } catch( const vtrc::common::exception &ex ) { std::cout << "Remote file size is unknown: " << remote_path << " '" << ex.what( ) << "; " << ex.additional( ) << "'" << "\n"; } std::string name = leaf_of( remote_path ); vtrc::shared_ptr<interfaces::remote_file> rem_f ( interfaces::create_remote_file( client, remote_path, "rb" ) ); std::cout << "Open remote file success.\n" << "Starting...\n" << "Block size = " << block_size << std::endl; std::ofstream f; f.open(name.c_str( ), std::ofstream::out ); std::string block; size_t total = 0; while( rem_f->read( block, block_size ) ) { total += block.size( ); std::cout << "Got " << total << " bytes\r"; f.write( block.c_str( ), block.size( ) ); } std::cout << "\nDownload complete\n"; } void tree_dir( vtrc::shared_ptr<interfaces::remote_fs> &impl, const std::string &path, int level = 0 ) { vtrc::shared_ptr<interfaces::remote_fs_iterator> i (impl->begin_iterator( path )); std::string lstring( level * 2, ' ' ); for( ; !i->end( ); i->next( )) { bool is_dir( i->info( ).is_directory_ ); std::cout << lstring << ( i->info( ).is_empty_ ? " " : "+" ); if( is_dir ) { std::cout << "[" << leaf_of(i->info( ).path_) << "]\n"; try { tree_dir( impl, i->info( ).path_, level + 1 ); } catch( ... ) { std::cout << lstring << " <iteration failed>\n"; } } else if( i->info( ).is_symlink_ ) { std::cout << "<!" << leaf_of(i->info( ).path_) << ">\n"; } else { std::cout << " " << leaf_of(i->info( ).path_) << "\n"; } } } void tree_dir( vtrc::shared_ptr<interfaces::remote_fs> &impl ) { tree_dir( impl, "", 0 ); } int start( const po::variables_map &params ) { if( params.count( "server" ) == 0 ) { throw std::runtime_error("Server is not defined;\n" "Use --help for details"); } /// will use onle one thread for io. /// because we don't have callbacks or events from server-side common::pool_pair pp( 1 ); client::vtrc_client_sptr client = client::vtrc_client::create( pp ); /// connect slot to 'on_ready' std::cout << "Creating client ... " ; vtrc::condition_variable ready_cond; client->get_on_ready( ).connect( vtrc::bind( on_client_ready, vtrc::ref( ready_cond ) ) ); std::cout << "success\n"; std::string path; connect_to( client, params["server"].as<std::string>( ) ); std::cout << "Connected to " << params["server"].as<std::string>( ) << "\n"; vtrc::mutex ready_mutex; vtrc::unique_lock<vtrc::mutex> ready_lock(ready_mutex); ready_cond.wait( ready_lock, vtrc::bind( &client::vtrc_client::ready, client ) ); if( params.count( "path" ) ) { path = params["path"].as<std::string>( ); } std::cout << "Path is: '" << path << "'\nCreating interface..."; vtrc::shared_ptr<interfaces::remote_fs> impl (interfaces::create_remote_fs(client, path)); std::cout << "Success; id is '" << impl->get_handle( ) << "'\n"; std::cout << "Path " << ( impl->exists( ) ? "exists" : "not exists" ) << "\n"; if( params.count( "pwd" ) ) { std::cout << "PWD: " << impl->pwd( ) << "\n"; } if( params.count( "info" ) ) { std::string pi(params["info"].as<std::string>( )); std::cout << "Trying get info about '" << pi << "'..."; interfaces::fs_info inf = impl->info( pi ); std::cout << "success.\nInfo:\n"; std::cout << "\texists:\t\t" << (inf.is_exist_ ? "true" : "false") << "\n"; std::cout << "\tdirectory:\t" << (inf.is_directory_ ? "true" : "false") << "\n"; std::cout << "\tempty:\t\t" << (inf.is_empty_ ? "true" : "false") << "\n"; std::cout << "\tregular:\t" << (inf.is_regular_ ? "true" : "false") << "\n"; } if( params.count( "list" ) ) { std::cout << "List dir:\n"; list_dir( impl ); } if( params.count( "tree" ) ) { std::cout << "Tree dir:\n"; tree_dir( impl ); } size_t bs = params.count( "block-size" ) ? params["block-size"].as<unsigned>( ) : 4096; if( params.count( "pull" ) ) { std::string path = params["pull"].as<std::string>( ); std::cout << "pull file '" << path << "'\n"; pull_file( client, impl, path, bs ); } if( params.count( "push" ) ) { std::string path = params["push"].as<std::string>( ); std::cout << "push file '" << path << "'\n"; push_file( client, path, bs ); } impl.reset( ); // close fs instance pp.stop_all( ); pp.join_all( ); return 0; } <commit_msg>examples<commit_after>#include <vector> #include <string> #include <fstream> #include "boost/program_options.hpp" #include "boost/algorithm/string.hpp" #include "boost/lexical_cast.hpp" #include "vtrc-client-base/vtrc-client.h" #include "vtrc-common/vtrc-pool-pair.h" #include "vtrc-common/vtrc-exception.h" #include "remote-fs-iface.h" #include "vtrc-condition-variable.h" #include "vtrc-mutex.h" #include "vtrc-bind.h" #include "vtrc-ref.h" namespace po = boost::program_options; using namespace vtrc; void get_options( po::options_description& desc ) { desc.add_options( ) ("help,?", "help message") ("server,s", po::value<std::string>( ), "server name; <tcp address>:<port> or <pipe/file name>") ("path,p", po::value<std::string>( ), "Init remote path for client") ("pwd,w", "Show current remote path") ("info,i", po::value<std::string>( ), "Show info about remote path") ("list,l", "list remote directory") ("tree,t", "show remote directory as tree") ("pull,g", po::value<std::string>( ), "Download remote file") ("push,u", po::value<std::string>( ), "Upload local file") ("block-size,b", po::value<unsigned>( ), "Block size for pull and push" "; 1-44000") ; } void connect_to( client::vtrc_client_sptr client, std::string const &name ) { std::vector<std::string> params; std::string::const_reverse_iterator b(name.rbegin( )); std::string::const_reverse_iterator e(name.rend( )); for( ; b!=e ;++b ) { if( *b == ':' ) { std::string::const_reverse_iterator bb(b); ++bb; params.push_back( std::string( name.begin( ), bb.base( )) ); params.push_back( std::string( b.base( ), name.end( ))); break; } } if( params.empty( ) ) { params.push_back( name ); } if( params.size( ) == 1 ) { /// local name client->connect( params[0] ); } else if( params.size( ) == 2 ) { /// tcp client->connect( params[0], params[1]); } } void on_client_ready( vtrc::condition_variable &cond ) { std::cout << "Connection is ready...\n"; cond.notify_all( ); } std::string leaf_of( const std::string &path ) { std::string::const_reverse_iterator b(path.rbegin( )); std::string::const_reverse_iterator e(path.rend( )); for( ; b!=e ;++b ) { if( *b == '/' || *b == '\\' ) { return std::string( b.base( ), path.end( ) ); } } return path; } void list_dir( vtrc::shared_ptr<interfaces::remote_fs> &impl ) { vtrc::shared_ptr<interfaces::remote_fs_iterator> i(impl->begin_iterator( )); std::string lstring( 2, ' ' ); for( ; !i->end( ); i->next( )) { bool is_dir( i->info( ).is_directory_ ); std::cout << lstring << ( i->info( ).is_empty_ ? " " : "+" ); std::cout << ( is_dir ? "[" : " " ) << leaf_of(i->info( ).path_) << ( is_dir ? "]" : " " ) << "\n"; } } namespace rfs_examples { /// rfs-push-file.cpp void push_file( client::vtrc_client_sptr client, const std::string &local_path, size_t block_size ); /// rfs-pull-file.cpp void pull_file( client::vtrc_client_sptr client, vtrc::shared_ptr<interfaces::remote_fs> &impl, const std::string &remote_path, size_t block_size ); } void tree_dir( vtrc::shared_ptr<interfaces::remote_fs> &impl, const std::string &path, int level = 0 ) { vtrc::shared_ptr<interfaces::remote_fs_iterator> i (impl->begin_iterator( path )); std::string lstring( level * 2, ' ' ); for( ; !i->end( ); i->next( )) { bool is_dir( i->info( ).is_directory_ ); std::cout << lstring << ( i->info( ).is_empty_ ? " " : "+" ); if( is_dir ) { std::cout << "[" << leaf_of(i->info( ).path_) << "]\n"; try { tree_dir( impl, i->info( ).path_, level + 1 ); } catch( ... ) { std::cout << lstring << " <iteration failed>\n"; } } else if( i->info( ).is_symlink_ ) { std::cout << "<!" << leaf_of(i->info( ).path_) << ">\n"; } else { std::cout << " " << leaf_of(i->info( ).path_) << "\n"; } } } void tree_dir( vtrc::shared_ptr<interfaces::remote_fs> &impl ) { tree_dir( impl, "", 0 ); } int start( const po::variables_map &params ) { if( params.count( "server" ) == 0 ) { throw std::runtime_error("Server is not defined;\n" "Use --help for details"); } /// will use onle one thread for io. /// because we don't have callbacks or events from server-side common::pool_pair pp( 1 ); client::vtrc_client_sptr client = client::vtrc_client::create( pp ); /// connect slot to 'on_ready' std::cout << "Creating client ... " ; vtrc::condition_variable ready_cond; client->get_on_ready( ).connect( vtrc::bind( on_client_ready, vtrc::ref( ready_cond ) ) ); std::cout << "success\n"; std::string path; connect_to( client, params["server"].as<std::string>( ) ); std::cout << "Connected to " << params["server"].as<std::string>( ) << "\n"; vtrc::mutex ready_mutex; vtrc::unique_lock<vtrc::mutex> ready_lock(ready_mutex); ready_cond.wait( ready_lock, vtrc::bind( &client::vtrc_client::ready, client ) ); if( params.count( "path" ) ) { path = params["path"].as<std::string>( ); } std::cout << "Path is: '" << path << "'\nCreating interface..."; vtrc::shared_ptr<interfaces::remote_fs> impl (interfaces::create_remote_fs(client, path)); std::cout << "Success; id is '" << impl->get_handle( ) << "'\n"; std::cout << "Path " << ( impl->exists( ) ? "exists" : "not exists" ) << "\n"; if( params.count( "pwd" ) ) { std::cout << "PWD: " << impl->pwd( ) << "\n"; } if( params.count( "info" ) ) { std::string pi(params["info"].as<std::string>( )); std::cout << "Trying get info about '" << pi << "'..."; interfaces::fs_info inf = impl->info( pi ); std::cout << "success.\nInfo:\n"; std::cout << "\texists:\t\t" << (inf.is_exist_ ? "true" : "false") << "\n"; std::cout << "\tdirectory:\t" << (inf.is_directory_ ? "true" : "false") << "\n"; std::cout << "\tempty:\t\t" << (inf.is_empty_ ? "true" : "false") << "\n"; std::cout << "\tregular:\t" << (inf.is_regular_ ? "true" : "false") << "\n"; } if( params.count( "list" ) ) { std::cout << "List dir:\n"; list_dir( impl ); } if( params.count( "tree" ) ) { std::cout << "Tree dir:\n"; tree_dir( impl ); } size_t bs = params.count( "block-size" ) ? params["block-size"].as<unsigned>( ) : 4096; if( params.count( "pull" ) ) { std::string path = params["pull"].as<std::string>( ); std::cout << "pull file '" << path << "'\n"; rfs_examples::pull_file( client, impl, path, bs ); } if( params.count( "push" ) ) { std::string path = params["push"].as<std::string>( ); std::cout << "push file '" << path << "'\n"; rfs_examples::push_file( client, path, bs ); } impl.reset( ); // close fs instance pp.stop_all( ); pp.join_all( ); return 0; } <|endoftext|>
<commit_before>#include <iostream> #include "utility.hpp" // Inludes common necessary includes for development using depthai library #include "depthai/depthai.hpp" int main() { // Create pipeline dai::Pipeline pipeline; // Define sources and outputs auto camRgb = pipeline.create<dai::node::ColorCamera>(); auto imageManip = pipeline.create<dai::node::ImageManip>(); auto imageManip2 = pipeline.create<dai::node::ImageManip>(); auto camOut = pipeline.create<dai::node::XLinkOut>(); auto manipOut = pipeline.create<dai::node::XLinkOut>(); auto manipOut2 = pipeline.create<dai::node::XLinkOut>(); auto manip2In = pipeline.create<dai::node::XLinkIn>(); camOut->setStreamName("preview"); manipOut->setStreamName("manip"); manipOut2->setStreamName("manip2"); manip2In->setStreamName("manip2In"); // Properties camRgb->setPreviewSize(304, 304); camRgb->setResolution(dai::ColorCameraProperties::SensorResolution::THE_1080_P); camRgb->setInterleaved(false); camRgb->setColorOrder(dai::ColorCameraProperties::ColorOrder::BGR); // Create a center crop image manipulation imageManip->initialConfig.setCenterCrop(0.7f); imageManip->initialConfig.setResizeThumbnail(300, 400); // Second image manipulator - Create a off center crop imageManip2->initialConfig.setCropRect(0.1, 0.1, 0.3, 0.3); imageManip2->setWaitForConfigInput(true); // Linking camRgb->preview.link(camOut->input); camRgb->preview.link(imageManip->inputImage); imageManip->out.link(manipOut->input); imageManip->out.link(imageManip2->inputImage); imageManip2->out.link(manipOut2->input); manip2In->out.link(imageManip2->inputConfig); // Connect to device and start pipeline dai::Device device(pipeline); // Create input & output queues auto previewQueue = device.getOutputQueue("preview", 8, false); auto manipQueue = device.getOutputQueue("manip", 8, false); auto manipQueue2 = device.getOutputQueue("manip2", 8, false); auto manip2InQueue = device.getInputQueue("manip2In"); // keep processing data int frameCounter = 0; float xmin = 0.1f; float xmax = 0.3f; while(true) { xmin += 0.003f; xmax += 0.003f; if(xmax >= 1.0f) { xmin = 0.0f; xmax = 0.2f; } dai::ImageManipConfig cfg; cfg.setCropRect(xmin, 0.1f, xmax, 0.3f); manip2InQueue->send(cfg); // Gets both image frames auto preview = previewQueue->get<dai::ImgFrame>(); auto manip = manipQueue->get<dai::ImgFrame>(); auto manip2 = manipQueue2->get<dai::ImgFrame>(); auto matPreview = toMat(preview->getData(), preview->getWidth(), preview->getHeight(), 3, 1); auto matManip = toMat(manip->getData(), manip->getWidth(), manip->getHeight(), 3, 1); auto matManip2 = toMat(manip2->getData(), manip2->getWidth(), manip2->getHeight(), 3, 1); // Display both cv::imshow("preview", matPreview); cv::imshow("manip", matManip); cv::imshow("manip2", matManip2); int key = cv::waitKey(1); if(key == 'q') { return 0; } frameCounter++; } return 0; } <commit_msg>Restarting docs building<commit_after>#include <iostream> #include "utility.hpp" // Inludes common necessary includes for development using depthai library #include "depthai/depthai.hpp" int main() { // Create pipeline dai::Pipeline pipeline; // Define sources and outputs auto camRgb = pipeline.create<dai::node::ColorCamera>(); auto imageManip = pipeline.create<dai::node::ImageManip>(); auto imageManip2 = pipeline.create<dai::node::ImageManip>(); auto camOut = pipeline.create<dai::node::XLinkOut>(); auto manipOut = pipeline.create<dai::node::XLinkOut>(); auto manipOut2 = pipeline.create<dai::node::XLinkOut>(); auto manip2In = pipeline.create<dai::node::XLinkIn>(); camOut->setStreamName("preview"); manipOut->setStreamName("manip"); manipOut2->setStreamName("manip2"); manip2In->setStreamName("manip2In"); // Properties camRgb->setPreviewSize(304, 304); camRgb->setResolution(dai::ColorCameraProperties::SensorResolution::THE_1080_P); camRgb->setInterleaved(false); camRgb->setColorOrder(dai::ColorCameraProperties::ColorOrder::BGR); // Create a center crop image manipulation imageManip->initialConfig.setCenterCrop(0.7f); imageManip->initialConfig.setResizeThumbnail(300, 400); // Second image manipulator - Create a off center crop imageManip2->initialConfig.setCropRect(0.1, 0.1, 0.3, 0.3); imageManip2->setWaitForConfigInput(true); // Linking camRgb->preview.link(camOut->input); camRgb->preview.link(imageManip->inputImage); imageManip->out.link(manipOut->input); imageManip->out.link(imageManip2->inputImage); imageManip2->out.link(manipOut2->input); manip2In->out.link(imageManip2->inputConfig); // Connect to device and start pipeline dai::Device device(pipeline); // Create input & output queues auto previewQueue = device.getOutputQueue("preview", 8, false); auto manipQueue = device.getOutputQueue("manip", 8, false); auto manipQueue2 = device.getOutputQueue("manip2", 8, false); auto manip2InQueue = device.getInputQueue("manip2In"); // keep processing data int frameCounter = 0; float xmin = 0.1f; float xmax = 0.3f; while(true) { xmin += 0.003f; xmax += 0.003f; if(xmax >= 1.0f) { xmin = 0.0f; xmax = 0.2f; } dai::ImageManipConfig cfg; cfg.setCropRect(xmin, 0.1f, xmax, 0.3f); manip2InQueue->send(cfg); // Gets both image frames auto preview = previewQueue->get<dai::ImgFrame>(); auto manip = manipQueue->get<dai::ImgFrame>(); auto manip2 = manipQueue2->get<dai::ImgFrame>(); auto matPreview = toMat(preview->getData(), preview->getWidth(), preview->getHeight(), 3, 1); auto matManip = toMat(manip->getData(), manip->getWidth(), manip->getHeight(), 3, 1); auto matManip2 = toMat(manip2->getData(), manip2->getWidth(), manip2->getHeight(), 3, 1); // Display both cv::imshow("preview", matPreview); cv::imshow("manip", matManip); cv::imshow("manip2", matManip2); int key = cv::waitKey(1); if(key == 'q') { return 0; } frameCounter++; } return 0; }<|endoftext|>
<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/file_select_helper.h" #include <string> #include "base/bind.h" #include "base/file_util.h" #include "base/platform_file.h" #include "base/string_split.h" #include "base/string_util.h" #include "base/utf_string_conversions.h" #include "chrome/browser/platform_util.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/ui/browser.h" #include "chrome/browser/ui/browser_list.h" #include "content/public/browser/notification_details.h" #include "content/public/browser/notification_source.h" #include "content/public/browser/notification_types.h" #include "content/public/browser/render_view_host.h" #include "content/public/browser/render_widget_host_view.h" #include "content/public/common/file_chooser_params.h" #include "content/public/common/selected_file_info.h" #include "grit/generated_resources.h" #include "net/base/mime_util.h" #include "ui/base/l10n/l10n_util.h" using content::BrowserThread; using content::RenderViewHost; using content::RenderWidgetHost; using content::WebContents; namespace { // There is only one file-selection happening at any given time, // so we allocate an enumeration ID for that purpose. All IDs from // the renderer must start at 0 and increase. const int kFileSelectEnumerationId = -1; void NotifyRenderViewHost(RenderViewHost* render_view_host, const std::vector<content::SelectedFileInfo>& files, SelectFileDialog::Type dialog_type) { const int kReadFilePermissions = base::PLATFORM_FILE_OPEN | base::PLATFORM_FILE_READ | base::PLATFORM_FILE_EXCLUSIVE_READ | base::PLATFORM_FILE_ASYNC; const int kWriteFilePermissions = base::PLATFORM_FILE_CREATE | base::PLATFORM_FILE_CREATE_ALWAYS | base::PLATFORM_FILE_OPEN | base::PLATFORM_FILE_OPEN_ALWAYS | base::PLATFORM_FILE_OPEN_TRUNCATED | base::PLATFORM_FILE_WRITE | base::PLATFORM_FILE_WRITE_ATTRIBUTES | base::PLATFORM_FILE_ASYNC; int permissions = kReadFilePermissions; if (dialog_type == SelectFileDialog::SELECT_SAVEAS_FILE) permissions = kWriteFilePermissions; render_view_host->FilesSelectedInChooser(files, permissions); } // Converts a list of FilePaths to a list of SelectedFileInfo, with the // display name field left empty. std::vector<content::SelectedFileInfo> ConvertToSelectedFileInfoList( std::vector<FilePath> paths) { std::vector<content::SelectedFileInfo> selected_files; for (size_t i = 0; i < paths.size(); ++i) { selected_files.push_back( content::SelectedFileInfo(paths[i], FilePath::StringType())); } return selected_files; } } // namespace struct FileSelectHelper::ActiveDirectoryEnumeration { ActiveDirectoryEnumeration() : rvh_(NULL) {} scoped_ptr<DirectoryListerDispatchDelegate> delegate_; scoped_ptr<net::DirectoryLister> lister_; RenderViewHost* rvh_; std::vector<FilePath> results_; }; FileSelectHelper::FileSelectHelper(Profile* profile) : profile_(profile), render_view_host_(NULL), web_contents_(NULL), select_file_dialog_(), select_file_types_(), dialog_type_(SelectFileDialog::SELECT_OPEN_FILE) { } FileSelectHelper::~FileSelectHelper() { // There may be pending file dialogs, we need to tell them that we've gone // away so they don't try and call back to us. if (select_file_dialog_.get()) select_file_dialog_->ListenerDestroyed(); // Stop any pending directory enumeration, prevent a callback, and free // allocated memory. std::map<int, ActiveDirectoryEnumeration*>::iterator iter; for (iter = directory_enumerations_.begin(); iter != directory_enumerations_.end(); ++iter) { iter->second->lister_.reset(); delete iter->second; } } void FileSelectHelper::FileSelected(const FilePath& path, int index, void* params) { FileSelectedWithExtraInfo( content::SelectedFileInfo(path, FilePath::StringType()), index, params); } void FileSelectHelper::FileSelectedWithExtraInfo( const content::SelectedFileInfo& file, int index, void* params) { if (!render_view_host_) return; const FilePath& path = file.path; profile_->set_last_selected_directory(path.DirName()); if (dialog_type_ == SelectFileDialog::SELECT_FOLDER) { StartNewEnumeration(path, kFileSelectEnumerationId, render_view_host_); return; } std::vector<content::SelectedFileInfo> files; files.push_back(file); NotifyRenderViewHost(render_view_host_, files, dialog_type_); // No members should be accessed from here on. RunFileChooserEnd(); } void FileSelectHelper::MultiFilesSelected(const std::vector<FilePath>& files, void* params) { std::vector<content::SelectedFileInfo> selected_files = ConvertToSelectedFileInfoList(files); MultiFilesSelectedWithExtraInfo(selected_files, params); } void FileSelectHelper::MultiFilesSelectedWithExtraInfo( const std::vector<content::SelectedFileInfo>& files, void* params) { if (!files.empty()) profile_->set_last_selected_directory(files[0].path.DirName()); if (!render_view_host_) return; NotifyRenderViewHost(render_view_host_, files, dialog_type_); // No members should be accessed from here on. RunFileChooserEnd(); } void FileSelectHelper::FileSelectionCanceled(void* params) { if (!render_view_host_) return; // If the user cancels choosing a file to upload we pass back an // empty vector. NotifyRenderViewHost( render_view_host_, std::vector<content::SelectedFileInfo>(), dialog_type_); // No members should be accessed from here on. RunFileChooserEnd(); } void FileSelectHelper::StartNewEnumeration(const FilePath& path, int request_id, RenderViewHost* render_view_host) { scoped_ptr<ActiveDirectoryEnumeration> entry(new ActiveDirectoryEnumeration); entry->rvh_ = render_view_host; entry->delegate_.reset(new DirectoryListerDispatchDelegate(this, request_id)); entry->lister_.reset(new net::DirectoryLister(path, true, net::DirectoryLister::NO_SORT, entry->delegate_.get())); if (!entry->lister_->Start()) { if (request_id == kFileSelectEnumerationId) FileSelectionCanceled(NULL); else render_view_host->DirectoryEnumerationFinished(request_id, entry->results_); } else { directory_enumerations_[request_id] = entry.release(); } } void FileSelectHelper::OnListFile( int id, const net::DirectoryLister::DirectoryListerData& data) { ActiveDirectoryEnumeration* entry = directory_enumerations_[id]; // Directory upload returns directories via a "." file, so that // empty directories are included. This util call just checks // the flags in the structure; there's no file I/O going on. if (file_util::FileEnumerator::IsDirectory(data.info)) entry->results_.push_back(data.path.Append(FILE_PATH_LITERAL("."))); else entry->results_.push_back(data.path); } void FileSelectHelper::OnListDone(int id, int error) { // This entry needs to be cleaned up when this function is done. scoped_ptr<ActiveDirectoryEnumeration> entry(directory_enumerations_[id]); directory_enumerations_.erase(id); if (!entry->rvh_) return; if (error) { FileSelectionCanceled(NULL); return; } std::vector<content::SelectedFileInfo> selected_files = ConvertToSelectedFileInfoList(entry->results_); if (id == kFileSelectEnumerationId) NotifyRenderViewHost(entry->rvh_, selected_files, dialog_type_); else entry->rvh_->DirectoryEnumerationFinished(id, entry->results_); EnumerateDirectoryEnd(); } SelectFileDialog::FileTypeInfo* FileSelectHelper::GetFileTypesFromAcceptType( const std::vector<string16>& accept_types) { if (accept_types.empty()) return NULL; // Create FileTypeInfo and pre-allocate for the first extension list. scoped_ptr<SelectFileDialog::FileTypeInfo> file_type( new SelectFileDialog::FileTypeInfo()); file_type->include_all_files = true; file_type->extensions.resize(1); std::vector<FilePath::StringType>* extensions = &file_type->extensions.back(); // Find the correspondinge extensions. int valid_type_count = 0; int description_id = 0; for (size_t i = 0; i < accept_types.size(); ++i) { std::string ascii_mime_type = UTF16ToASCII(accept_types[i]); // WebKit normalizes MIME types. See HTMLInputElement::acceptMIMETypes(). DCHECK(StringToLowerASCII(ascii_mime_type) == ascii_mime_type) << "A MIME type contains uppercase letter: " << ascii_mime_type; DCHECK(TrimWhitespaceASCII(ascii_mime_type, TRIM_ALL, &ascii_mime_type) == TRIM_NONE) << "A MIME type contains whitespace: '" << ascii_mime_type << "'"; size_t old_extension_size = extensions->size(); if (ascii_mime_type == "image/*") { description_id = IDS_IMAGE_FILES; net::GetImageExtensions(extensions); } else if (ascii_mime_type == "audio/*") { description_id = IDS_AUDIO_FILES; net::GetAudioExtensions(extensions); } else if (ascii_mime_type == "video/*") { description_id = IDS_VIDEO_FILES; net::GetVideoExtensions(extensions); } else { net::GetExtensionsForMimeType(ascii_mime_type, extensions); } if (extensions->size() > old_extension_size) valid_type_count++; } // If no valid extension is added, bail out. if (valid_type_count == 0) return NULL; // Use a generic description "Custom Files" if either of the following is // true: // 1) There're multiple types specified, like "audio/*,video/*" // 2) There're multiple extensions for a MIME type without parameter, like // "ehtml,shtml,htm,html" for "text/html". On Windows, the select file // dialog uses the first extension in the list to form the description, // like "EHTML Files". This is not what we want. if (valid_type_count > 1 || (valid_type_count == 1 && description_id == 0 && extensions->size() > 1)) description_id = IDS_CUSTOM_FILES; if (description_id) { file_type->extension_description_overrides.push_back( l10n_util::GetStringUTF16(description_id)); } return file_type.release(); } void FileSelectHelper::RunFileChooser( RenderViewHost* render_view_host, content::WebContents* web_contents, const content::FileChooserParams& params) { DCHECK(!render_view_host_); DCHECK(!web_contents_); render_view_host_ = render_view_host; web_contents_ = web_contents; notification_registrar_.RemoveAll(); notification_registrar_.Add( this, content::NOTIFICATION_RENDER_WIDGET_HOST_DESTROYED, content::Source<RenderWidgetHost>(render_view_host_)); notification_registrar_.Add( this, content::NOTIFICATION_WEB_CONTENTS_DESTROYED, content::Source<WebContents>(web_contents_)); BrowserThread::PostTask( BrowserThread::FILE, FROM_HERE, base::Bind(&FileSelectHelper::RunFileChooserOnFileThread, this, params)); // Because this class returns notifications to the RenderViewHost, it is // difficult for callers to know how long to keep a reference to this // instance. We AddRef() here to keep the instance alive after we return // to the caller, until the last callback is received from the file dialog. // At that point, we must call RunFileChooserEnd(). AddRef(); } void FileSelectHelper::RunFileChooserOnFileThread( const content::FileChooserParams& params) { select_file_types_.reset( GetFileTypesFromAcceptType(params.accept_types)); BrowserThread::PostTask( BrowserThread::UI, FROM_HERE, base::Bind(&FileSelectHelper::RunFileChooserOnUIThread, this, params)); } void FileSelectHelper::RunFileChooserOnUIThread( const content::FileChooserParams& params) { if (!render_view_host_ || !web_contents_) { // If the renderer was destroyed before we started, just cancel the // operation. RunFileChooserEnd(); return; } if (!select_file_dialog_.get()) select_file_dialog_ = SelectFileDialog::Create(this); switch (params.mode) { case content::FileChooserParams::Open: dialog_type_ = SelectFileDialog::SELECT_OPEN_FILE; break; case content::FileChooserParams::OpenMultiple: dialog_type_ = SelectFileDialog::SELECT_OPEN_MULTI_FILE; break; case content::FileChooserParams::OpenFolder: dialog_type_ = SelectFileDialog::SELECT_FOLDER; break; case content::FileChooserParams::Save: dialog_type_ = SelectFileDialog::SELECT_SAVEAS_FILE; break; default: dialog_type_ = SelectFileDialog::SELECT_OPEN_FILE; // Prevent warning. NOTREACHED(); } FilePath default_file_name = params.default_file_name; if (default_file_name.empty()) default_file_name = profile_->last_selected_directory(); gfx::NativeWindow owning_window = platform_util::GetTopLevel(render_view_host_->GetView()->GetNativeView()); select_file_dialog_->SelectFile( dialog_type_, params.title, default_file_name, select_file_types_.get(), select_file_types_.get() ? 1 : 0, // 1-based index. FILE_PATH_LITERAL(""), web_contents_, owning_window, NULL); select_file_types_.reset(); } // This method is called when we receive the last callback from the file // chooser dialog. Perform any cleanup and release the reference we added // in RunFileChooser(). void FileSelectHelper::RunFileChooserEnd() { render_view_host_ = NULL; web_contents_ = NULL; Release(); } void FileSelectHelper::EnumerateDirectory(int request_id, RenderViewHost* render_view_host, const FilePath& path) { DCHECK_NE(kFileSelectEnumerationId, request_id); // Because this class returns notifications to the RenderViewHost, it is // difficult for callers to know how long to keep a reference to this // instance. We AddRef() here to keep the instance alive after we return // to the caller, until the last callback is received from the enumeration // code. At that point, we must call EnumerateDirectoryEnd(). AddRef(); StartNewEnumeration(path, request_id, render_view_host); } // This method is called when we receive the last callback from the enumeration // code. Perform any cleanup and release the reference we added in // EnumerateDirectory(). void FileSelectHelper::EnumerateDirectoryEnd() { Release(); } void FileSelectHelper::Observe(int type, const content::NotificationSource& source, const content::NotificationDetails& details) { switch (type) { case content::NOTIFICATION_RENDER_WIDGET_HOST_DESTROYED: { DCHECK(content::Source<RenderWidgetHost>(source).ptr() == render_view_host_); render_view_host_ = NULL; break; } case content::NOTIFICATION_WEB_CONTENTS_DESTROYED: { DCHECK(content::Source<WebContents>(source).ptr() == web_contents_); web_contents_ = NULL; break; } default: NOTREACHED(); } } <commit_msg>[Coverity] Change pass-by-val to pass-by-ref<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/file_select_helper.h" #include <string> #include "base/bind.h" #include "base/file_util.h" #include "base/platform_file.h" #include "base/string_split.h" #include "base/string_util.h" #include "base/utf_string_conversions.h" #include "chrome/browser/platform_util.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/ui/browser.h" #include "chrome/browser/ui/browser_list.h" #include "content/public/browser/notification_details.h" #include "content/public/browser/notification_source.h" #include "content/public/browser/notification_types.h" #include "content/public/browser/render_view_host.h" #include "content/public/browser/render_widget_host_view.h" #include "content/public/common/file_chooser_params.h" #include "content/public/common/selected_file_info.h" #include "grit/generated_resources.h" #include "net/base/mime_util.h" #include "ui/base/l10n/l10n_util.h" using content::BrowserThread; using content::RenderViewHost; using content::RenderWidgetHost; using content::WebContents; namespace { // There is only one file-selection happening at any given time, // so we allocate an enumeration ID for that purpose. All IDs from // the renderer must start at 0 and increase. const int kFileSelectEnumerationId = -1; void NotifyRenderViewHost(RenderViewHost* render_view_host, const std::vector<content::SelectedFileInfo>& files, SelectFileDialog::Type dialog_type) { const int kReadFilePermissions = base::PLATFORM_FILE_OPEN | base::PLATFORM_FILE_READ | base::PLATFORM_FILE_EXCLUSIVE_READ | base::PLATFORM_FILE_ASYNC; const int kWriteFilePermissions = base::PLATFORM_FILE_CREATE | base::PLATFORM_FILE_CREATE_ALWAYS | base::PLATFORM_FILE_OPEN | base::PLATFORM_FILE_OPEN_ALWAYS | base::PLATFORM_FILE_OPEN_TRUNCATED | base::PLATFORM_FILE_WRITE | base::PLATFORM_FILE_WRITE_ATTRIBUTES | base::PLATFORM_FILE_ASYNC; int permissions = kReadFilePermissions; if (dialog_type == SelectFileDialog::SELECT_SAVEAS_FILE) permissions = kWriteFilePermissions; render_view_host->FilesSelectedInChooser(files, permissions); } // Converts a list of FilePaths to a list of SelectedFileInfo, with the // display name field left empty. std::vector<content::SelectedFileInfo> ConvertToSelectedFileInfoList( const std::vector<FilePath>& paths) { std::vector<content::SelectedFileInfo> selected_files; for (size_t i = 0; i < paths.size(); ++i) { selected_files.push_back( content::SelectedFileInfo(paths[i], FilePath::StringType())); } return selected_files; } } // namespace struct FileSelectHelper::ActiveDirectoryEnumeration { ActiveDirectoryEnumeration() : rvh_(NULL) {} scoped_ptr<DirectoryListerDispatchDelegate> delegate_; scoped_ptr<net::DirectoryLister> lister_; RenderViewHost* rvh_; std::vector<FilePath> results_; }; FileSelectHelper::FileSelectHelper(Profile* profile) : profile_(profile), render_view_host_(NULL), web_contents_(NULL), select_file_dialog_(), select_file_types_(), dialog_type_(SelectFileDialog::SELECT_OPEN_FILE) { } FileSelectHelper::~FileSelectHelper() { // There may be pending file dialogs, we need to tell them that we've gone // away so they don't try and call back to us. if (select_file_dialog_.get()) select_file_dialog_->ListenerDestroyed(); // Stop any pending directory enumeration, prevent a callback, and free // allocated memory. std::map<int, ActiveDirectoryEnumeration*>::iterator iter; for (iter = directory_enumerations_.begin(); iter != directory_enumerations_.end(); ++iter) { iter->second->lister_.reset(); delete iter->second; } } void FileSelectHelper::FileSelected(const FilePath& path, int index, void* params) { FileSelectedWithExtraInfo( content::SelectedFileInfo(path, FilePath::StringType()), index, params); } void FileSelectHelper::FileSelectedWithExtraInfo( const content::SelectedFileInfo& file, int index, void* params) { if (!render_view_host_) return; const FilePath& path = file.path; profile_->set_last_selected_directory(path.DirName()); if (dialog_type_ == SelectFileDialog::SELECT_FOLDER) { StartNewEnumeration(path, kFileSelectEnumerationId, render_view_host_); return; } std::vector<content::SelectedFileInfo> files; files.push_back(file); NotifyRenderViewHost(render_view_host_, files, dialog_type_); // No members should be accessed from here on. RunFileChooserEnd(); } void FileSelectHelper::MultiFilesSelected(const std::vector<FilePath>& files, void* params) { std::vector<content::SelectedFileInfo> selected_files = ConvertToSelectedFileInfoList(files); MultiFilesSelectedWithExtraInfo(selected_files, params); } void FileSelectHelper::MultiFilesSelectedWithExtraInfo( const std::vector<content::SelectedFileInfo>& files, void* params) { if (!files.empty()) profile_->set_last_selected_directory(files[0].path.DirName()); if (!render_view_host_) return; NotifyRenderViewHost(render_view_host_, files, dialog_type_); // No members should be accessed from here on. RunFileChooserEnd(); } void FileSelectHelper::FileSelectionCanceled(void* params) { if (!render_view_host_) return; // If the user cancels choosing a file to upload we pass back an // empty vector. NotifyRenderViewHost( render_view_host_, std::vector<content::SelectedFileInfo>(), dialog_type_); // No members should be accessed from here on. RunFileChooserEnd(); } void FileSelectHelper::StartNewEnumeration(const FilePath& path, int request_id, RenderViewHost* render_view_host) { scoped_ptr<ActiveDirectoryEnumeration> entry(new ActiveDirectoryEnumeration); entry->rvh_ = render_view_host; entry->delegate_.reset(new DirectoryListerDispatchDelegate(this, request_id)); entry->lister_.reset(new net::DirectoryLister(path, true, net::DirectoryLister::NO_SORT, entry->delegate_.get())); if (!entry->lister_->Start()) { if (request_id == kFileSelectEnumerationId) FileSelectionCanceled(NULL); else render_view_host->DirectoryEnumerationFinished(request_id, entry->results_); } else { directory_enumerations_[request_id] = entry.release(); } } void FileSelectHelper::OnListFile( int id, const net::DirectoryLister::DirectoryListerData& data) { ActiveDirectoryEnumeration* entry = directory_enumerations_[id]; // Directory upload returns directories via a "." file, so that // empty directories are included. This util call just checks // the flags in the structure; there's no file I/O going on. if (file_util::FileEnumerator::IsDirectory(data.info)) entry->results_.push_back(data.path.Append(FILE_PATH_LITERAL("."))); else entry->results_.push_back(data.path); } void FileSelectHelper::OnListDone(int id, int error) { // This entry needs to be cleaned up when this function is done. scoped_ptr<ActiveDirectoryEnumeration> entry(directory_enumerations_[id]); directory_enumerations_.erase(id); if (!entry->rvh_) return; if (error) { FileSelectionCanceled(NULL); return; } std::vector<content::SelectedFileInfo> selected_files = ConvertToSelectedFileInfoList(entry->results_); if (id == kFileSelectEnumerationId) NotifyRenderViewHost(entry->rvh_, selected_files, dialog_type_); else entry->rvh_->DirectoryEnumerationFinished(id, entry->results_); EnumerateDirectoryEnd(); } SelectFileDialog::FileTypeInfo* FileSelectHelper::GetFileTypesFromAcceptType( const std::vector<string16>& accept_types) { if (accept_types.empty()) return NULL; // Create FileTypeInfo and pre-allocate for the first extension list. scoped_ptr<SelectFileDialog::FileTypeInfo> file_type( new SelectFileDialog::FileTypeInfo()); file_type->include_all_files = true; file_type->extensions.resize(1); std::vector<FilePath::StringType>* extensions = &file_type->extensions.back(); // Find the correspondinge extensions. int valid_type_count = 0; int description_id = 0; for (size_t i = 0; i < accept_types.size(); ++i) { std::string ascii_mime_type = UTF16ToASCII(accept_types[i]); // WebKit normalizes MIME types. See HTMLInputElement::acceptMIMETypes(). DCHECK(StringToLowerASCII(ascii_mime_type) == ascii_mime_type) << "A MIME type contains uppercase letter: " << ascii_mime_type; DCHECK(TrimWhitespaceASCII(ascii_mime_type, TRIM_ALL, &ascii_mime_type) == TRIM_NONE) << "A MIME type contains whitespace: '" << ascii_mime_type << "'"; size_t old_extension_size = extensions->size(); if (ascii_mime_type == "image/*") { description_id = IDS_IMAGE_FILES; net::GetImageExtensions(extensions); } else if (ascii_mime_type == "audio/*") { description_id = IDS_AUDIO_FILES; net::GetAudioExtensions(extensions); } else if (ascii_mime_type == "video/*") { description_id = IDS_VIDEO_FILES; net::GetVideoExtensions(extensions); } else { net::GetExtensionsForMimeType(ascii_mime_type, extensions); } if (extensions->size() > old_extension_size) valid_type_count++; } // If no valid extension is added, bail out. if (valid_type_count == 0) return NULL; // Use a generic description "Custom Files" if either of the following is // true: // 1) There're multiple types specified, like "audio/*,video/*" // 2) There're multiple extensions for a MIME type without parameter, like // "ehtml,shtml,htm,html" for "text/html". On Windows, the select file // dialog uses the first extension in the list to form the description, // like "EHTML Files". This is not what we want. if (valid_type_count > 1 || (valid_type_count == 1 && description_id == 0 && extensions->size() > 1)) description_id = IDS_CUSTOM_FILES; if (description_id) { file_type->extension_description_overrides.push_back( l10n_util::GetStringUTF16(description_id)); } return file_type.release(); } void FileSelectHelper::RunFileChooser( RenderViewHost* render_view_host, content::WebContents* web_contents, const content::FileChooserParams& params) { DCHECK(!render_view_host_); DCHECK(!web_contents_); render_view_host_ = render_view_host; web_contents_ = web_contents; notification_registrar_.RemoveAll(); notification_registrar_.Add( this, content::NOTIFICATION_RENDER_WIDGET_HOST_DESTROYED, content::Source<RenderWidgetHost>(render_view_host_)); notification_registrar_.Add( this, content::NOTIFICATION_WEB_CONTENTS_DESTROYED, content::Source<WebContents>(web_contents_)); BrowserThread::PostTask( BrowserThread::FILE, FROM_HERE, base::Bind(&FileSelectHelper::RunFileChooserOnFileThread, this, params)); // Because this class returns notifications to the RenderViewHost, it is // difficult for callers to know how long to keep a reference to this // instance. We AddRef() here to keep the instance alive after we return // to the caller, until the last callback is received from the file dialog. // At that point, we must call RunFileChooserEnd(). AddRef(); } void FileSelectHelper::RunFileChooserOnFileThread( const content::FileChooserParams& params) { select_file_types_.reset( GetFileTypesFromAcceptType(params.accept_types)); BrowserThread::PostTask( BrowserThread::UI, FROM_HERE, base::Bind(&FileSelectHelper::RunFileChooserOnUIThread, this, params)); } void FileSelectHelper::RunFileChooserOnUIThread( const content::FileChooserParams& params) { if (!render_view_host_ || !web_contents_) { // If the renderer was destroyed before we started, just cancel the // operation. RunFileChooserEnd(); return; } if (!select_file_dialog_.get()) select_file_dialog_ = SelectFileDialog::Create(this); switch (params.mode) { case content::FileChooserParams::Open: dialog_type_ = SelectFileDialog::SELECT_OPEN_FILE; break; case content::FileChooserParams::OpenMultiple: dialog_type_ = SelectFileDialog::SELECT_OPEN_MULTI_FILE; break; case content::FileChooserParams::OpenFolder: dialog_type_ = SelectFileDialog::SELECT_FOLDER; break; case content::FileChooserParams::Save: dialog_type_ = SelectFileDialog::SELECT_SAVEAS_FILE; break; default: dialog_type_ = SelectFileDialog::SELECT_OPEN_FILE; // Prevent warning. NOTREACHED(); } FilePath default_file_name = params.default_file_name; if (default_file_name.empty()) default_file_name = profile_->last_selected_directory(); gfx::NativeWindow owning_window = platform_util::GetTopLevel(render_view_host_->GetView()->GetNativeView()); select_file_dialog_->SelectFile( dialog_type_, params.title, default_file_name, select_file_types_.get(), select_file_types_.get() ? 1 : 0, // 1-based index. FILE_PATH_LITERAL(""), web_contents_, owning_window, NULL); select_file_types_.reset(); } // This method is called when we receive the last callback from the file // chooser dialog. Perform any cleanup and release the reference we added // in RunFileChooser(). void FileSelectHelper::RunFileChooserEnd() { render_view_host_ = NULL; web_contents_ = NULL; Release(); } void FileSelectHelper::EnumerateDirectory(int request_id, RenderViewHost* render_view_host, const FilePath& path) { DCHECK_NE(kFileSelectEnumerationId, request_id); // Because this class returns notifications to the RenderViewHost, it is // difficult for callers to know how long to keep a reference to this // instance. We AddRef() here to keep the instance alive after we return // to the caller, until the last callback is received from the enumeration // code. At that point, we must call EnumerateDirectoryEnd(). AddRef(); StartNewEnumeration(path, request_id, render_view_host); } // This method is called when we receive the last callback from the enumeration // code. Perform any cleanup and release the reference we added in // EnumerateDirectory(). void FileSelectHelper::EnumerateDirectoryEnd() { Release(); } void FileSelectHelper::Observe(int type, const content::NotificationSource& source, const content::NotificationDetails& details) { switch (type) { case content::NOTIFICATION_RENDER_WIDGET_HOST_DESTROYED: { DCHECK(content::Source<RenderWidgetHost>(source).ptr() == render_view_host_); render_view_host_ = NULL; break; } case content::NOTIFICATION_WEB_CONTENTS_DESTROYED: { DCHECK(content::Source<WebContents>(source).ptr() == web_contents_); web_contents_ = NULL; break; } default: NOTREACHED(); } } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: infotips.cxx,v $ * * $Revision: 1.2 $ * * last change: $Author: hr $ $Date: 2004-04-07 11:13:37 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef GLOBAL_HXX_INCLUDED #include "internal/global.hxx" #endif #ifndef INFOTIPS_HXX_INCLUDED #include "internal/infotips.hxx" #endif #ifndef SHLXTHDL_HXX_INCLUDED #include "internal/shlxthdl.hxx" #endif #ifndef METAINFO_HXX_INCLUDED #include "internal/metainfo.hxx" #endif #ifndef UTILITIES_HXX_INCLUDED #include "internal/utilities.hxx" #endif #ifndef REGISTRY_HXX_INCLUDED #include "internal/registry.hxx" #endif #ifndef FILEEXTENSIONS_HXX_INCLUDED #include "internal/fileextensions.hxx" #endif #ifndef CONFIG_HXX_INCLUDED #include "internal/config.hxx" #endif #include "internal/resource.h" #include <stdio.h> #include <stdlib.h> #define MAX_STRING 80 #define KB 1024.0 const std::wstring WSPACE = std::wstring(SPACE); //----------------------------- // //----------------------------- CInfoTip::CInfoTip(long RefCnt) : m_RefCnt(RefCnt) { ZeroMemory(m_szFileName, sizeof(m_szFileName)); InterlockedIncrement(&g_DllRefCnt); } //----------------------------- // //----------------------------- CInfoTip::~CInfoTip() { InterlockedDecrement(&g_DllRefCnt); } //----------------------------- // IUnknown methods //----------------------------- HRESULT STDMETHODCALLTYPE CInfoTip::QueryInterface(REFIID riid, void __RPC_FAR *__RPC_FAR *ppvObject) { *ppvObject = 0; IUnknown* pUnk = 0; if (IID_IUnknown == riid || IID_IQueryInfo == riid) { pUnk = static_cast<IQueryInfo*>(this); pUnk->AddRef(); *ppvObject = pUnk; return S_OK; } else if (IID_IPersistFile == riid) { pUnk = static_cast<IPersistFile*>(this); pUnk->AddRef(); *ppvObject = pUnk; return S_OK; } return E_NOINTERFACE; } //---------------------------- // //---------------------------- ULONG STDMETHODCALLTYPE CInfoTip::AddRef(void) { return InterlockedIncrement(&m_RefCnt); } //---------------------------- // //---------------------------- ULONG STDMETHODCALLTYPE CInfoTip::Release( void) { long refcnt = InterlockedDecrement(&m_RefCnt); if (0 == m_RefCnt) delete this; return refcnt; } //********************helper functions for GetInfoTip functions********************** /** get file type infomation from registry. */ std::wstring getFileTypeInfo(const std::string& file_extension) { char extKeyValue[MAX_STRING]; char typeKeyValue[MAX_STRING]; ::std::string sDot("."); if (QueryRegistryKey(HKEY_CLASSES_ROOT, (sDot.append(file_extension)).c_str(), extKeyValue, MAX_STRING)) if (QueryRegistryKey( HKEY_CLASSES_ROOT, extKeyValue, typeKeyValue, MAX_STRING)) return StringToWString(typeKeyValue); return EMPTY_STRING; } /** get file size. */ DWORD getSizeOfFile( char* FileName ) { HANDLE hFile = CreateFile(StringToWString(FileName).c_str(), // open file GENERIC_READ, // open for reading FILE_SHARE_READ|FILE_SHARE_WRITE|FILE_SHARE_DELETE, // share for all operations NULL, // no security OPEN_EXISTING, // existing file only FILE_ATTRIBUTE_NORMAL, // normal file NULL); // no attr. template if (hFile != INVALID_HANDLE_VALUE) { DWORD dwSize = GetFileSize( HANDLE(hFile), NULL ); CloseHandle( HANDLE(hFile) ); return dwSize; } return INVALID_FILE_SIZE; } /** format file size in to be more readable. */ std::wstring formatSizeOfFile( DWORD dwSize ) { char *buffer; int decimal, sign; double dFileSize = (double)dwSize/(double)KB; buffer = _fcvt( dFileSize, 1, &decimal, &sign ); ::std::wstring wsTemp = StringToWString( buffer ); int pos=decimal % 3; ::std::wstring wsBuffer = wsTemp.substr( 0,pos); if ( decimal ) for (;decimal - pos > 2;pos += 3) { if (pos) wsBuffer.append(StringToWString(",")); wsBuffer.append( wsTemp.substr( pos, 3) ); } else wsBuffer.append(StringToWString("0")); wsBuffer.append(StringToWString(".")); wsBuffer.append(wsTemp.substr( decimal, wsTemp.size()-decimal )); wsBuffer.append(StringToWString("KB")); return wsBuffer; } /** get file size infomation. */ std::wstring getFileSizeInfo(char* FileName) { DWORD dwSize=getSizeOfFile(FileName); if (dwSize != INVALID_FILE_SIZE) return formatSizeOfFile( dwSize ); return EMPTY_STRING; } //---------------------------- // IQueryInfo methods //---------------------------- HRESULT STDMETHODCALLTYPE CInfoTip::GetInfoTip(DWORD dwFlags, wchar_t** ppwszTip) { std::wstring msg; const std::wstring CONST_SPACE(SPACE); //display File Type, no matter other info is loaded successfully or not. std::wstring tmpTypeStr = getFileTypeInfo( get_file_name_extension(m_szFileName) ); if ( tmpTypeStr != EMPTY_STRING ) { msg += GetResString(IDS_TYPE_COLON) + CONST_SPACE; msg += tmpTypeStr; } try { COpenOfficeMetaInformation meta_info_accessor(m_szFileName); //display document title; if ( meta_info_accessor.getTagData( META_INFO_TITLE ).length() > 0) { msg += L"\n"; msg += GetResString(IDS_TITLE_COLON) + CONST_SPACE; msg += meta_info_accessor.getTagData( META_INFO_TITLE ); } else { msg += L"\n"; msg += GetResString(IDS_TITLE_COLON) + CONST_SPACE; msg += m_FileNameOnly; } //display document author; if ( meta_info_accessor.getTagData( META_INFO_AUTHOR ).length() > 0) { msg += L"\n"; msg += GetResString( IDS_AUTHOR_COLON ) + CONST_SPACE; msg += meta_info_accessor.getTagData( META_INFO_AUTHOR ); } //display document subject; if ( meta_info_accessor.getTagData( META_INFO_SUBJECT ).length() > 0) { msg += L"\n"; msg += GetResString(IDS_SUBJECT_COLON) + CONST_SPACE; msg += meta_info_accessor.getTagData( META_INFO_SUBJECT ); } //display document description; if ( meta_info_accessor.getTagData( META_INFO_DESCRIPTION ).length() > 0) { msg += L"\n"; msg += GetResString( IDS_COMMENTS_COLON ) + CONST_SPACE; msg += meta_info_accessor.getTagData( META_INFO_DESCRIPTION ); } //display midified time formated into locale representation. ::std::wstring wsDateTime = meta_info_accessor.getTagData( META_INFO_MODIFIED ); if ( wsDateTime.length() == 19 ) { msg += L"\n"; msg += GetResString( IDS_MODIFIED_COLON ) + CONST_SPACE; //fill in the SYSTEMTIME structure; std::string asDateTime = WStringToString( wsDateTime ); SYSTEMTIME DateTime; DateTime.wYear = ( unsigned short )strtol( asDateTime.substr( 0, 4 ).c_str(), NULL, 10 ); DateTime.wMonth = ( unsigned short )strtol( asDateTime.substr( 5, 2 ).c_str(), NULL, 10 ); DateTime.wDayOfWeek = 0; DateTime.wDay = ( unsigned short )strtol( asDateTime.substr( 8, 2 ).c_str(), NULL, 10 ); DateTime.wHour = ( unsigned short )strtol( asDateTime.substr( 11,2 ).c_str(), NULL, 10 ); DateTime.wMinute = ( unsigned short )strtol( asDateTime.substr( 14,2 ).c_str(), NULL, 10 ); DateTime.wSecond = ( unsigned short )strtol( asDateTime.substr( 17,2 ).c_str(), NULL, 10 ); DateTime.wMilliseconds = 0; //get Date info from structure WCHAR DateBuffer[ MAX_STRING ]; int DateSize = GetDateFormatW( LOCALE_SYSTEM_DEFAULT, 0, &DateTime, NULL, DateBuffer, MAX_STRING ); if ( DateSize ) wsDateTime.assign(DateBuffer); else wsDateTime = StringToWString( asDateTime ); //get Time info from structure WCHAR TimeBuffer[ MAX_STRING ]; int TimeSize = GetTimeFormatW( LOCALE_SYSTEM_DEFAULT, 0, &DateTime, NULL, TimeBuffer, MAX_STRING ); if ( TimeSize ) { wsDateTime.append(SPACE); wsDateTime.append(TimeBuffer); } else wsDateTime = StringToWString( asDateTime ); msg += wsDateTime; } else if ( wsDateTime.length() > 0) { msg += L"\n"; msg += GetResString( IDS_MODIFIED_COLON ) + CONST_SPACE; msg += wsDateTime; } } catch (const std::exception&) { //return E_FAIL; } //display file size, no matter other infomation is loaded successfully or not. std::wstring tmpSizeStr = getFileSizeInfo( m_szFileName ); if ( tmpSizeStr != EMPTY_STRING ) { msg += L"\n"; msg += GetResString( IDS_SIZE_COLON ) + CONST_SPACE; msg += tmpSizeStr; } //finalize and assignthe string. LPMALLOC lpMalloc; HRESULT hr = SHGetMalloc(&lpMalloc); if (SUCCEEDED(hr)) { size_t len = sizeof(wchar_t) * msg.length() + sizeof(wchar_t); wchar_t* pMem = reinterpret_cast<wchar_t*>(lpMalloc->Alloc(len)); ZeroMemory(pMem, len); msg.copy(pMem,msg.length()); *ppwszTip = pMem; lpMalloc->Release(); return S_OK; } return E_FAIL; } //---------------------------- // //---------------------------- HRESULT STDMETHODCALLTYPE CInfoTip::GetInfoFlags(DWORD *pdwFlags) { return E_NOTIMPL; } //---------------------------- // IPersist methods //---------------------------- HRESULT STDMETHODCALLTYPE CInfoTip::GetClassID(CLSID* pClassID) { pClassID = const_cast<CLSID*>(&CLSID_INFOTIP_HANDLER); return S_OK; } //---------------------------- // IPersistFile methods //---------------------------- HRESULT STDMETHODCALLTYPE CInfoTip::Load(LPCOLESTR pszFileName, DWORD dwMode) { std::wstring fname = pszFileName; // there must be a '\' and there must even be an // extension, else we would not have been called std::wstring::iterator begin = fname.begin() + fname.find_last_of(L"\\") + 1; std::wstring::iterator end = fname.end(); m_FileNameOnly = std::wstring(begin, end); std::string fnameA = WStringToString(fname); // #115531# // ZeroMemory because strncpy doesn't '\0'-terminates the destination // string; reserve the last place in the buffer for the final '\0' // that's why '(sizeof(m_szFileName) - 1)' ZeroMemory(m_szFileName, sizeof(m_szFileName)); strncpy(m_szFileName, fnameA.c_str(), (sizeof(m_szFileName) - 1)); return S_OK; } //---------------------------- // //---------------------------- HRESULT STDMETHODCALLTYPE CInfoTip::IsDirty(void) { return E_NOTIMPL; } //---------------------------- // //---------------------------- HRESULT STDMETHODCALLTYPE CInfoTip::Save(LPCOLESTR pszFileName, BOOL fRemember) { return E_NOTIMPL; } //---------------------------- // //---------------------------- HRESULT STDMETHODCALLTYPE CInfoTip::SaveCompleted(LPCOLESTR pszFileName) { return E_NOTIMPL; } //---------------------------- // //---------------------------- HRESULT STDMETHODCALLTYPE CInfoTip::GetCurFile(LPOLESTR __RPC_FAR *ppszFileName) { return E_NOTIMPL; } <commit_msg>INTEGRATION: CWS desktintgr02 (1.2.8); FILE MERGED 2004/08/18 06:41:51 deuce 1.2.8.4: Issue number: i32660, i32927, i32268 Submitted by: Gorden Lin {Gorden.Lin@Sun.com} Reviewed by: Tino Rachui {Tino.Rachui@Sun.com} 2004/08/05 08:45:28 deuce 1.2.8.3: Issue number: i21110 Submitted by: Gorden Lin {Gorden.Lin@Sun.com} Reviewed by: Tino Rachui {Tino.Rachui@Sun.com} 2004/08/02 03:22:05 deuce 1.2.8.2: Issue number: i21110 Submitted by: Gorden Lin {Gorden.Lin@Sun.com} Reviewed by: Tino Rachui {Tino.Rachui@Sun.com} 2004/07/29 09:14:07 deuce 1.2.8.1: Issue number: 21110 Submitted by: Gorden Lin {gorden.lin@sun.com} Reviewed by: Tino Rachui {tino.rachui@sun.com}<commit_after>/************************************************************************* * * $RCSfile: infotips.cxx,v $ * * $Revision: 1.3 $ * * last change: $Author: hr $ $Date: 2004-09-08 14:32:12 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef GLOBAL_HXX_INCLUDED #include "internal/global.hxx" #endif #ifndef INFOTIPS_HXX_INCLUDED #include "internal/infotips.hxx" #endif #ifndef SHLXTHDL_HXX_INCLUDED #include "internal/shlxthdl.hxx" #endif #ifndef METAINFOREADER_HXX_INCLUDED #include "internal/metainforeader.hxx" #endif #ifndef CONTENTREADER_HXX_INCLUDED #include "internal/contentreader.hxx" #endif #ifndef UTILITIES_HXX_INCLUDED #include "internal/utilities.hxx" #endif #ifndef REGISTRY_HXX_INCLUDED #include "internal/registry.hxx" #endif #ifndef FILEEXTENSIONS_HXX_INCLUDED #include "internal/fileextensions.hxx" #endif #ifndef ISO8601_CONVERTER_HXX_INCLUDED #include "internal/iso8601_converter.hxx" #endif #ifndef CONFIG_HXX_INCLUDED #include "internal/config.hxx" #endif #include "internal/resource.h" #include <stdio.h> #include <utility> #include <stdlib.h> #define MAX_STRING 80 #define KB 1024.0 const std::wstring WSPACE = std::wstring(SPACE); //----------------------------- // //----------------------------- CInfoTip::CInfoTip(long RefCnt) : m_RefCnt(RefCnt) { ZeroMemory(m_szFileName, sizeof(m_szFileName)); InterlockedIncrement(&g_DllRefCnt); } //----------------------------- // //----------------------------- CInfoTip::~CInfoTip() { InterlockedDecrement(&g_DllRefCnt); } //----------------------------- // IUnknown methods //----------------------------- HRESULT STDMETHODCALLTYPE CInfoTip::QueryInterface(REFIID riid, void __RPC_FAR *__RPC_FAR *ppvObject) { *ppvObject = 0; IUnknown* pUnk = 0; if (IID_IUnknown == riid || IID_IQueryInfo == riid) { pUnk = static_cast<IQueryInfo*>(this); pUnk->AddRef(); *ppvObject = pUnk; return S_OK; } else if (IID_IPersistFile == riid) { pUnk = static_cast<IPersistFile*>(this); pUnk->AddRef(); *ppvObject = pUnk; return S_OK; } return E_NOINTERFACE; } //---------------------------- // //---------------------------- ULONG STDMETHODCALLTYPE CInfoTip::AddRef(void) { return InterlockedIncrement(&m_RefCnt); } //---------------------------- // //---------------------------- ULONG STDMETHODCALLTYPE CInfoTip::Release( void) { long refcnt = InterlockedDecrement(&m_RefCnt); if (0 == m_RefCnt) delete this; return refcnt; } //********************helper functions for GetInfoTip functions********************** /** get file type infomation from registry. */ std::wstring getFileTypeInfo(const std::string& file_extension) { char extKeyValue[MAX_STRING]; char typeKeyValue[MAX_STRING]; ::std::string sDot("."); if (QueryRegistryKey(HKEY_CLASSES_ROOT, (sDot.append(file_extension)).c_str(), "", extKeyValue, MAX_STRING)) if (QueryRegistryKey( HKEY_CLASSES_ROOT, extKeyValue, "",typeKeyValue, MAX_STRING)) return StringToWString(typeKeyValue); return EMPTY_STRING; } /** get file size. */ DWORD getSizeOfFile( char* FileName ) { HANDLE hFile = CreateFile(StringToWString(FileName).c_str(), // open file GENERIC_READ, // open for reading FILE_SHARE_READ|FILE_SHARE_WRITE|FILE_SHARE_DELETE, // share for all operations NULL, // no security OPEN_EXISTING, // existing file only FILE_ATTRIBUTE_NORMAL, // normal file NULL); // no attr. template if (hFile != INVALID_HANDLE_VALUE) { DWORD dwSize = GetFileSize( HANDLE(hFile), NULL ); CloseHandle( HANDLE(hFile) ); return dwSize; } return INVALID_FILE_SIZE; } /** format file size in to be more readable. */ std::wstring formatSizeOfFile( DWORD dwSize ) { char *buffer; int decimal, sign; double dFileSize = (double)dwSize/(double)KB; buffer = _fcvt( dFileSize, 1, &decimal, &sign ); ::std::wstring wsTemp = StringToWString( buffer ); int pos=decimal % 3; ::std::wstring wsBuffer = wsTemp.substr( 0,pos); if ( decimal ) for (;decimal - pos > 2;pos += 3) { if (pos) wsBuffer.append(StringToWString(",")); wsBuffer.append( wsTemp.substr( pos, 3) ); } else wsBuffer.append(StringToWString("0")); wsBuffer.append(StringToWString(".")); wsBuffer.append(wsTemp.substr( decimal, wsTemp.size()-decimal )); wsBuffer.append(StringToWString("KB")); return wsBuffer; } /** get file size infomation. */ std::wstring getFileSizeInfo(char* FileName) { DWORD dwSize=getSizeOfFile(FileName); if (dwSize != INVALID_FILE_SIZE) return formatSizeOfFile( dwSize ); return EMPTY_STRING; } //---------------------------- // IQueryInfo methods //---------------------------- HRESULT STDMETHODCALLTYPE CInfoTip::GetInfoTip(DWORD /*dwFlags*/, wchar_t** ppwszTip) { std::wstring msg; const std::wstring CONST_SPACE(SPACE); //display File Type, no matter other info is loaded successfully or not. std::wstring tmpTypeStr = getFileTypeInfo( get_file_name_extension(m_szFileName) ); if ( tmpTypeStr != EMPTY_STRING ) { msg += GetResString(IDS_TYPE_COLON) + CONST_SPACE; msg += tmpTypeStr; } try { CMetaInfoReader meta_info_accessor(m_szFileName); //display document title; if ( meta_info_accessor.getTagData( META_INFO_TITLE ).length() > 0) { if ( msg != EMPTY_STRING ) msg += L"\n"; msg += GetResString(IDS_TITLE_COLON) + CONST_SPACE; msg += meta_info_accessor.getTagData( META_INFO_TITLE ); } else { if ( msg != EMPTY_STRING ) msg += L"\n"; msg += GetResString(IDS_TITLE_COLON) + CONST_SPACE; msg += m_FileNameOnly; } //display document author; if ( meta_info_accessor.getTagData( META_INFO_AUTHOR ).length() > 0) { if ( msg != EMPTY_STRING ) msg += L"\n"; msg += GetResString( IDS_AUTHOR_COLON ) + CONST_SPACE; msg += meta_info_accessor.getTagData( META_INFO_AUTHOR ); } //display document subject; if ( meta_info_accessor.getTagData( META_INFO_SUBJECT ).length() > 0) { if ( msg != EMPTY_STRING ) msg += L"\n"; msg += GetResString(IDS_SUBJECT_COLON) + CONST_SPACE; msg += meta_info_accessor.getTagData( META_INFO_SUBJECT ); } //display document description; if ( meta_info_accessor.getTagData( META_INFO_DESCRIPTION ).length() > 0) { if ( msg != EMPTY_STRING ) msg += L"\n"; msg += GetResString( IDS_COMMENTS_COLON ) + CONST_SPACE; msg += meta_info_accessor.getTagData( META_INFO_DESCRIPTION ); } //display midified time formated into locale representation. if ( iso8601_date_to_local_date(meta_info_accessor.getTagData(META_INFO_MODIFIED )).length() > 0) { if ( msg != EMPTY_STRING ) msg += L"\n"; msg += GetResString( IDS_MODIFIED_COLON ) + CONST_SPACE; msg += iso8601_date_to_local_date(meta_info_accessor.getTagData(META_INFO_MODIFIED )); } } catch (const std::exception&) { //return E_FAIL; } //display file size, no matter other infomation is loaded successfully or not. std::wstring tmpSizeStr = getFileSizeInfo( m_szFileName ); if ( tmpSizeStr != EMPTY_STRING ) { msg += L"\n"; msg += GetResString( IDS_SIZE_COLON ) + CONST_SPACE; msg += tmpSizeStr; } //finalize and assignthe string. LPMALLOC lpMalloc; HRESULT hr = SHGetMalloc(&lpMalloc); if (SUCCEEDED(hr)) { size_t len = sizeof(wchar_t) * msg.length() + sizeof(wchar_t); wchar_t* pMem = reinterpret_cast<wchar_t*>(lpMalloc->Alloc(len)); ZeroMemory(pMem, len); msg.copy(pMem,msg.length()); *ppwszTip = pMem; lpMalloc->Release(); return S_OK; } return E_FAIL; } //---------------------------- // //---------------------------- HRESULT STDMETHODCALLTYPE CInfoTip::GetInfoFlags(DWORD * /*pdwFlags*/ ) { return E_NOTIMPL; } //---------------------------- // IPersist methods //---------------------------- HRESULT STDMETHODCALLTYPE CInfoTip::GetClassID(CLSID* pClassID) { pClassID = const_cast<CLSID*>(&CLSID_INFOTIP_HANDLER); return S_OK; } //---------------------------- // IPersistFile methods //---------------------------- HRESULT STDMETHODCALLTYPE CInfoTip::Load(LPCOLESTR pszFileName, DWORD /*dwMode*/) { std::wstring fname = pszFileName; // there must be a '\' and there must even be an // extension, else we would not have been called std::wstring::iterator begin = fname.begin() + fname.find_last_of(L"\\") + 1; std::wstring::iterator end = fname.end(); m_FileNameOnly = std::wstring(begin, end); std::string fnameA = WStringToString(fname); // #115531# // ZeroMemory because strncpy doesn't '\0'-terminates the destination // string; reserve the last place in the buffer for the final '\0' // that's why '(sizeof(m_szFileName) - 1)' ZeroMemory(m_szFileName, sizeof(m_szFileName)); strncpy(m_szFileName, fnameA.c_str(), (sizeof(m_szFileName) - 1)); return S_OK; } //---------------------------- // //---------------------------- HRESULT STDMETHODCALLTYPE CInfoTip::IsDirty(void) { return E_NOTIMPL; } //---------------------------- // //---------------------------- HRESULT STDMETHODCALLTYPE CInfoTip::Save(LPCOLESTR /*pszFileName*/, BOOL /*fRemember*/) { return E_NOTIMPL; } //---------------------------- // //---------------------------- HRESULT STDMETHODCALLTYPE CInfoTip::SaveCompleted(LPCOLESTR /*pszFileName*/) { return E_NOTIMPL; } //---------------------------- // //---------------------------- HRESULT STDMETHODCALLTYPE CInfoTip::GetCurFile(LPOLESTR __RPC_FAR * /*ppszFileName*/) { return E_NOTIMPL; } <|endoftext|>
<commit_before>/****************************************************************************** * Copyright 2018 The Apollo 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. *****************************************************************************/ /** * @file **/ #include "modules/planning/scenarios/side_pass/side_pass_stage.h" #include <algorithm> #include <vector> #include "modules/common/configs/vehicle_config_helper.h" #include "modules/common/proto/pnc_point.pb.h" #include "modules/planning/common/frame.h" #include "modules/planning/common/planning_gflags.h" #include "modules/planning/common/speed_profile_generator.h" namespace apollo { namespace planning { namespace scenario { namespace side_pass { using apollo::common::TrajectoryPoint; using apollo::common::math::Vec2d; using apollo::common::VehicleConfigHelper; constexpr double kExtraMarginforStopOnWaitPointStage = 3.0; /* * @brief: * STAGE: SidePassBackup */ Stage::StageStatus SidePassBackup::Process( const TrajectoryPoint& planning_start_point, Frame* frame) { // check the status of side pass scenario const SLBoundary& adc_sl_boundary = frame->reference_line_info().front().AdcSlBoundary(); const PathDecision& path_decision = frame->reference_line_info().front().path_decision(); bool has_blocking_obstacle = false; for (const auto* obstacle : path_decision.obstacles().Items()) { if (obstacle->IsVirtual() || !obstacle->IsStatic()) { continue; } CHECK(obstacle->IsStatic()); if (obstacle->speed() > GetContext()->scenario_config_.block_obstacle_min_speed()) { continue; } if (obstacle->PerceptionSLBoundary().start_s() <= adc_sl_boundary.end_s()) { // such vehicles are behind the ego car. continue; } if (obstacle->PerceptionSLBoundary().start_s() > adc_sl_boundary.end_s() + GetContext()->scenario_config_.max_front_obstacle_distance()) { // vehicles are far away continue; } // check driving_width const auto& reference_line = frame->reference_line_info().front().reference_line(); const double driving_width = reference_line.GetDrivingWidth(obstacle->PerceptionSLBoundary()); const double adc_width = VehicleConfigHelper::GetConfig().vehicle_param().width(); if (driving_width - adc_width - FLAGS_static_decision_nudge_l_buffer > GetContext()->scenario_config_.min_l_nudge_buffer()) { continue; } has_blocking_obstacle = true; break; } GetContext()->backup_stage_cycle_num_ += 1; if (!has_blocking_obstacle || GetContext()->backup_stage_cycle_num_ > GetContext()->scenario_config_.max_backup_stage_cycle_num()) { GetContext()->backup_stage_cycle_num_ = 0; next_stage_ = ScenarioConfig::NO_STAGE; return Stage::FINISHED; } // do path planning bool plan_ok = ExecuteTaskOnReferenceLine(planning_start_point, frame); if (!plan_ok) { AERROR << "Stage " << Name() << " error: " << "planning on reference line failed."; return Stage::ERROR; } return Stage::RUNNING; } /* * @brief: * STAGE: SidePassApproachObstacle */ Stage::StageStatus SidePassApproachObstacle::Process( const TrajectoryPoint& planning_start_point, Frame* frame) { // check the status of side pass scenario const SLBoundary& adc_sl_boundary = frame->reference_line_info().front().AdcSlBoundary(); const PathDecision& path_decision = frame->reference_line_info().front().path_decision(); bool has_blocking_obstacle = false; for (const auto* obstacle : path_decision.obstacles().Items()) { if (obstacle->IsVirtual() || !obstacle->IsStatic()) { continue; } CHECK(obstacle->IsStatic()); if (obstacle->speed() > GetContext()->scenario_config_.block_obstacle_min_speed()) { continue; } if (obstacle->PerceptionSLBoundary().start_s() <= adc_sl_boundary.end_s()) { // such vehicles are behind the ego car. continue; } if (obstacle->PerceptionSLBoundary().start_s() > adc_sl_boundary.end_s() + GetContext()->scenario_config_.max_front_obstacle_distance()) { // vehicles are far away continue; } // check driving_width const auto& reference_line = frame->reference_line_info().front().reference_line(); const double driving_width = reference_line.GetDrivingWidth(obstacle->PerceptionSLBoundary()); const double adc_width = VehicleConfigHelper::GetConfig().vehicle_param().width(); if (driving_width - adc_width - FLAGS_static_decision_nudge_l_buffer > GetContext()->scenario_config_.min_l_nudge_buffer()) { continue; } has_blocking_obstacle = true; break; } if (!has_blocking_obstacle) { next_stage_ = ScenarioConfig::NO_STAGE; return Stage::FINISHED; } // do path planning bool plan_ok = ExecuteTaskOnReferenceLine(planning_start_point, frame); if (!plan_ok) { AERROR << "Stage " << Name() << " error: " << "planning on reference line failed."; return Stage::ERROR; } const ReferenceLineInfo& reference_line_info = frame->reference_line_info().front(); double adc_velocity = frame->vehicle_state().linear_velocity(); double adc_front_edge_s = reference_line_info.AdcSlBoundary().end_s(); double front_obstacle_distance = 1000; for (const auto* obstacle : path_decision.obstacles().Items()) { if (obstacle->IsVirtual()) { continue; } bool is_on_road = reference_line_info.reference_line().HasOverlap( obstacle->PerceptionBoundingBox()); if (!is_on_road) { continue; } const auto& obstacle_sl = obstacle->PerceptionSLBoundary(); if (obstacle_sl.end_s() <= reference_line_info.AdcSlBoundary().start_s()) { continue; } double distance = obstacle_sl.start_s() - adc_front_edge_s; if (distance < front_obstacle_distance) { front_obstacle_distance = distance; } } if ((front_obstacle_distance) < 0) { AERROR << "Stage " << Name() << " error: " << "front obstacle has wrong position."; return Stage::ERROR; } double max_stop_velocity = GetContext()->scenario_config_.approach_obstacle_max_stop_speed(); double min_stop_obstacle_distance = GetContext()->scenario_config_.approach_obstacle_min_stop_distance(); if (adc_velocity < max_stop_velocity && front_obstacle_distance > min_stop_obstacle_distance) { next_stage_ = ScenarioConfig::SIDE_PASS_GENERATE_PATH; return Stage::FINISHED; } return Stage::RUNNING; } /* * @brief: * STAGE: SidePassGeneratePath */ Stage::StageStatus SidePassGeneratePath::Process( const TrajectoryPoint& planning_start_point, Frame* frame) { if (!ExecuteTaskOnReferenceLine(planning_start_point, frame)) { AERROR << "Fail to plan on reference_line."; GetContext()->backup_stage_cycle_num_ = 0; next_stage_ = ScenarioConfig::SIDE_PASS_BACKUP; return Stage::FINISHED; } GetContext()->path_data_ = frame->reference_line_info().front().path_data(); if (frame->reference_line_info().front().trajectory().NumOfPoints() > 0) { next_stage_ = ScenarioConfig::SIDE_PASS_STOP_ON_WAITPOINT; return Stage::FINISHED; } return Stage::RUNNING; } /* * @brief: * STAGE: SidePassDetectSafety */ Stage::StageStatus SidePassDetectSafety::Process( const TrajectoryPoint& planning_start_point, Frame* frame) { const auto& reference_line_info = frame->reference_line_info().front(); bool update_success = GetContext()->path_data_.UpdateFrenetFramePath( &reference_line_info.reference_line()); if (!update_success) { AERROR << "Fail to update path_data."; return Stage::ERROR; } const auto adc_frenet_frame_point_ = reference_line_info.reference_line().GetFrenetPoint( frame->PlanningStartPoint().path_point()); bool trim_success = GetContext()->path_data_.LeftTrimWithRefS(adc_frenet_frame_point_); if (!trim_success) { AERROR << "Fail to trim path_data. adc_frenet_frame_point: " << adc_frenet_frame_point_.ShortDebugString(); return Stage::ERROR; } auto& rfl_info = frame->mutable_reference_line_info()->front(); *(rfl_info.mutable_path_data()) = GetContext()->path_data_; const auto& path_points = rfl_info.path_data().discretized_path(); auto* debug_path = rfl_info.mutable_debug()->mutable_planning_data()->add_path(); debug_path->set_name("DpPolyPathOptimizer"); debug_path->mutable_path_point()->CopyFrom( {path_points.begin(), path_points.end()}); if (!ExecuteTaskOnReferenceLine(planning_start_point, frame)) { return Stage::ERROR; } bool is_safe = true; double adc_front_edge_s = reference_line_info.AdcSlBoundary().end_s(); const PathDecision& path_decision = frame->reference_line_info().front().path_decision(); for (const auto* obstacle : path_decision.obstacles().Items()) { // TODO(All): check according to neighbor lane. if (obstacle->IsVirtual() && obstacle->Id().substr(0, 3) == "SP_" && obstacle->PerceptionSLBoundary().start_s() >= adc_front_edge_s) { is_safe = false; break; } } if (is_safe) { GetContext()->pass_obstacle_stuck_cycle_num_ = 0; next_stage_ = ScenarioConfig::SIDE_PASS_PASS_OBSTACLE; return Stage::FINISHED; } return Stage::RUNNING; } /* * @brief: * STAGE: SidePassPassObstacle */ Stage::StageStatus SidePassPassObstacle::Process( const TrajectoryPoint& planning_start_point, Frame* frame) { const auto& reference_line_info = frame->reference_line_info().front(); bool update_success = GetContext()->path_data_.UpdateFrenetFramePath( &reference_line_info.reference_line()); if (!update_success) { AERROR << "Fail to update path_data."; return Stage::ERROR; } ADEBUG << "Processing SidePassPassObstacle."; const auto adc_frenet_frame_point_ = reference_line_info.reference_line().GetFrenetPoint( frame->PlanningStartPoint().path_point()); bool trim_success = GetContext()->path_data_.LeftTrimWithRefS(adc_frenet_frame_point_); if (!trim_success) { AERROR << "Fail to trim path_data. adc_frenet_frame_point: " << adc_frenet_frame_point_.ShortDebugString(); return Stage::ERROR; } auto& rfl_info = frame->mutable_reference_line_info()->front(); *(rfl_info.mutable_path_data()) = GetContext()->path_data_; const auto& path_points = rfl_info.path_data().discretized_path(); auto* debug_path = rfl_info.mutable_debug()->mutable_planning_data()->add_path(); // TODO(All): // Have to use DpPolyPathOptimizer to show in dreamview. Need change to // correct name. debug_path->set_name("DpPolyPathOptimizer"); debug_path->mutable_path_point()->CopyFrom( {path_points.begin(), path_points.end()}); bool plan_ok = ExecuteTaskOnReferenceLine(planning_start_point, frame); if (!plan_ok) { AERROR << "Fail to plan on reference line."; return Stage::ERROR; } const SLBoundary& adc_sl_boundary = reference_line_info.AdcSlBoundary(); const auto& end_point = reference_line_info.path_data().discretized_path().back(); Vec2d last_xy_point(end_point.x(), end_point.y()); // get s of last point on path common::SLPoint sl_point; if (!reference_line_info.reference_line().XYToSL(last_xy_point, &sl_point)) { AERROR << "Fail to transfer cartesian point to frenet point."; return Stage::ERROR; } double distance_to_path_end = sl_point.s() - GetContext()->scenario_config_.side_pass_exit_distance(); double adc_velocity = frame->vehicle_state().linear_velocity(); double max_velocity_for_stop = GetContext()->scenario_config_.approach_obstacle_max_stop_speed(); if (adc_velocity < max_velocity_for_stop) { GetContext()->pass_obstacle_stuck_cycle_num_ += 1; } else { GetContext()->pass_obstacle_stuck_cycle_num_ = 0; } if (adc_sl_boundary.end_s() > distance_to_path_end || GetContext()->pass_obstacle_stuck_cycle_num_ > 60) { next_stage_ = ScenarioConfig::NO_STAGE; return Stage::FINISHED; } return Stage::RUNNING; } } // namespace side_pass } // namespace scenario } // namespace planning } // namespace apollo <commit_msg>planning: updated side pass approach blocking obstacle stage.<commit_after>/****************************************************************************** * Copyright 2018 The Apollo 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. *****************************************************************************/ /** * @file **/ #include "modules/planning/scenarios/side_pass/side_pass_stage.h" #include <algorithm> #include <vector> #include <string> #include "modules/common/configs/vehicle_config_helper.h" #include "modules/common/proto/pnc_point.pb.h" #include "modules/planning/common/frame.h" #include "modules/planning/common/planning_gflags.h" #include "modules/planning/common/speed_profile_generator.h" namespace apollo { namespace planning { namespace scenario { namespace side_pass { using apollo::common::TrajectoryPoint; using apollo::common::math::Vec2d; using apollo::common::VehicleConfigHelper; constexpr double kExtraMarginforStopOnWaitPointStage = 3.0; /* * @brief: * STAGE: SidePassBackup */ Stage::StageStatus SidePassBackup::Process( const TrajectoryPoint& planning_start_point, Frame* frame) { // check the status of side pass scenario const SLBoundary& adc_sl_boundary = frame->reference_line_info().front().AdcSlBoundary(); const PathDecision& path_decision = frame->reference_line_info().front().path_decision(); bool has_blocking_obstacle = false; for (const auto* obstacle : path_decision.obstacles().Items()) { if (obstacle->IsVirtual() || !obstacle->IsStatic()) { continue; } CHECK(obstacle->IsStatic()); if (obstacle->speed() > GetContext()->scenario_config_.block_obstacle_min_speed()) { continue; } if (obstacle->PerceptionSLBoundary().start_s() <= adc_sl_boundary.end_s()) { // such vehicles are behind the ego car. continue; } if (obstacle->PerceptionSLBoundary().start_s() > adc_sl_boundary.end_s() + GetContext()->scenario_config_.max_front_obstacle_distance()) { // vehicles are far away continue; } // check driving_width const auto& reference_line = frame->reference_line_info().front().reference_line(); const double driving_width = reference_line.GetDrivingWidth(obstacle->PerceptionSLBoundary()); const double adc_width = VehicleConfigHelper::GetConfig().vehicle_param().width(); if (driving_width - adc_width - FLAGS_static_decision_nudge_l_buffer > GetContext()->scenario_config_.min_l_nudge_buffer()) { continue; } has_blocking_obstacle = true; break; } GetContext()->backup_stage_cycle_num_ += 1; if (!has_blocking_obstacle || GetContext()->backup_stage_cycle_num_ > GetContext()->scenario_config_.max_backup_stage_cycle_num()) { GetContext()->backup_stage_cycle_num_ = 0; next_stage_ = ScenarioConfig::NO_STAGE; return Stage::FINISHED; } // do path planning bool plan_ok = ExecuteTaskOnReferenceLine(planning_start_point, frame); if (!plan_ok) { AERROR << "Stage " << Name() << " error: " << "planning on reference line failed."; return Stage::ERROR; } return Stage::RUNNING; } /* * @brief: * STAGE: SidePassApproachObstacle */ Stage::StageStatus SidePassApproachObstacle::Process( const TrajectoryPoint& planning_start_point, Frame* frame) { std::string blocking_obstacle_id = GetContext()->front_blocking_obstacle_id_; const auto front_blocking_obstacle = frame->Find(blocking_obstacle_id); double obstacle_start_s = front_blocking_obstacle->PerceptionSLBoundary().start_s(); const SLBoundary& adc_sl_boundary = frame->reference_line_info().front().AdcSlBoundary(); if ((adc_sl_boundary.end_s() - obstacle_start_s) < GetContext()->scenario_config_.min_front_obstacle_distance()) { next_stage_ = ScenarioConfig::NO_STAGE; return Stage::FINISHED; } double kBlockingObstacleDistance = 2.0; std::string virtual_obstacle_id = blocking_obstacle_id + "_virtual_stop"; for (auto& reference_line_info : *frame->mutable_reference_line_info()) { auto* obstacle = frame->CreateStopObstacle( &reference_line_info, virtual_obstacle_id, obstacle_start_s - kBlockingObstacleDistance); if (!obstacle) { AERROR << "Failed to create virtual stop obstacle[" << virtual_obstacle_id << "]"; next_stage_ = ScenarioConfig::NO_STAGE; return Stage::FINISHED; } break; } // check the status of side pass scenario const PathDecision& path_decision = frame->reference_line_info().front().path_decision(); bool has_blocking_obstacle = false; for (const auto* obstacle : path_decision.obstacles().Items()) { if (obstacle->IsVirtual() || !obstacle->IsStatic()) { continue; } CHECK(obstacle->IsStatic()); if (obstacle->speed() > GetContext()->scenario_config_.block_obstacle_min_speed()) { continue; } if (obstacle->PerceptionSLBoundary().start_s() <= adc_sl_boundary.end_s()) { // such vehicles are behind the ego car. continue; } if (obstacle->PerceptionSLBoundary().start_s() > adc_sl_boundary.end_s() + GetContext()->scenario_config_.max_front_obstacle_distance()) { // vehicles are far away continue; } // check driving_width const auto& reference_line = frame->reference_line_info().front().reference_line(); const double driving_width = reference_line.GetDrivingWidth(obstacle->PerceptionSLBoundary()); const double adc_width = VehicleConfigHelper::GetConfig().vehicle_param().width(); if (driving_width - adc_width - FLAGS_static_decision_nudge_l_buffer > GetContext()->scenario_config_.min_l_nudge_buffer()) { continue; } has_blocking_obstacle = true; break; } if (!has_blocking_obstacle) { next_stage_ = ScenarioConfig::NO_STAGE; return Stage::FINISHED; } // do path planning bool plan_ok = ExecuteTaskOnReferenceLine(planning_start_point, frame); if (!plan_ok) { AERROR << "Stage " << Name() << " error: " << "planning on reference line failed."; return Stage::ERROR; } const ReferenceLineInfo& reference_line_info = frame->reference_line_info().front(); double adc_velocity = frame->vehicle_state().linear_velocity(); double adc_front_edge_s = reference_line_info.AdcSlBoundary().end_s(); double front_obstacle_distance = 1000; for (const auto* obstacle : path_decision.obstacles().Items()) { if (obstacle->IsVirtual()) { continue; } bool is_on_road = reference_line_info.reference_line().HasOverlap( obstacle->PerceptionBoundingBox()); if (!is_on_road) { continue; } const auto& obstacle_sl = obstacle->PerceptionSLBoundary(); if (obstacle_sl.end_s() <= reference_line_info.AdcSlBoundary().start_s()) { continue; } double distance = obstacle_sl.start_s() - adc_front_edge_s; if (distance < front_obstacle_distance) { front_obstacle_distance = distance; } } if ((front_obstacle_distance) < 0) { AERROR << "Stage " << Name() << " error: " << "front obstacle has wrong position."; return Stage::ERROR; } double max_stop_velocity = GetContext()->scenario_config_.approach_obstacle_max_stop_speed(); double min_stop_obstacle_distance = GetContext()->scenario_config_.approach_obstacle_min_stop_distance(); if (adc_velocity < max_stop_velocity && front_obstacle_distance > min_stop_obstacle_distance) { next_stage_ = ScenarioConfig::SIDE_PASS_GENERATE_PATH; return Stage::FINISHED; } return Stage::RUNNING; } /* * @brief: * STAGE: SidePassGeneratePath */ Stage::StageStatus SidePassGeneratePath::Process( const TrajectoryPoint& planning_start_point, Frame* frame) { if (!ExecuteTaskOnReferenceLine(planning_start_point, frame)) { AERROR << "Fail to plan on reference_line."; GetContext()->backup_stage_cycle_num_ = 0; next_stage_ = ScenarioConfig::SIDE_PASS_BACKUP; return Stage::FINISHED; } GetContext()->path_data_ = frame->reference_line_info().front().path_data(); if (frame->reference_line_info().front().trajectory().NumOfPoints() > 0) { next_stage_ = ScenarioConfig::SIDE_PASS_STOP_ON_WAITPOINT; return Stage::FINISHED; } return Stage::RUNNING; } /* * @brief: * STAGE: SidePassDetectSafety */ Stage::StageStatus SidePassDetectSafety::Process( const TrajectoryPoint& planning_start_point, Frame* frame) { const auto& reference_line_info = frame->reference_line_info().front(); bool update_success = GetContext()->path_data_.UpdateFrenetFramePath( &reference_line_info.reference_line()); if (!update_success) { AERROR << "Fail to update path_data."; return Stage::ERROR; } const auto adc_frenet_frame_point_ = reference_line_info.reference_line().GetFrenetPoint( frame->PlanningStartPoint().path_point()); bool trim_success = GetContext()->path_data_.LeftTrimWithRefS(adc_frenet_frame_point_); if (!trim_success) { AERROR << "Fail to trim path_data. adc_frenet_frame_point: " << adc_frenet_frame_point_.ShortDebugString(); return Stage::ERROR; } auto& rfl_info = frame->mutable_reference_line_info()->front(); *(rfl_info.mutable_path_data()) = GetContext()->path_data_; const auto& path_points = rfl_info.path_data().discretized_path(); auto* debug_path = rfl_info.mutable_debug()->mutable_planning_data()->add_path(); debug_path->set_name("DpPolyPathOptimizer"); debug_path->mutable_path_point()->CopyFrom( {path_points.begin(), path_points.end()}); if (!ExecuteTaskOnReferenceLine(planning_start_point, frame)) { return Stage::ERROR; } bool is_safe = true; double adc_front_edge_s = reference_line_info.AdcSlBoundary().end_s(); const PathDecision& path_decision = frame->reference_line_info().front().path_decision(); for (const auto* obstacle : path_decision.obstacles().Items()) { // TODO(All): check according to neighbor lane. if (obstacle->IsVirtual() && obstacle->Id().substr(0, 3) == "SP_" && obstacle->PerceptionSLBoundary().start_s() >= adc_front_edge_s) { is_safe = false; break; } } if (is_safe) { GetContext()->pass_obstacle_stuck_cycle_num_ = 0; next_stage_ = ScenarioConfig::SIDE_PASS_PASS_OBSTACLE; return Stage::FINISHED; } return Stage::RUNNING; } /* * @brief: * STAGE: SidePassPassObstacle */ Stage::StageStatus SidePassPassObstacle::Process( const TrajectoryPoint& planning_start_point, Frame* frame) { const auto& reference_line_info = frame->reference_line_info().front(); bool update_success = GetContext()->path_data_.UpdateFrenetFramePath( &reference_line_info.reference_line()); if (!update_success) { AERROR << "Fail to update path_data."; return Stage::ERROR; } ADEBUG << "Processing SidePassPassObstacle."; const auto adc_frenet_frame_point_ = reference_line_info.reference_line().GetFrenetPoint( frame->PlanningStartPoint().path_point()); bool trim_success = GetContext()->path_data_.LeftTrimWithRefS(adc_frenet_frame_point_); if (!trim_success) { AERROR << "Fail to trim path_data. adc_frenet_frame_point: " << adc_frenet_frame_point_.ShortDebugString(); return Stage::ERROR; } auto& rfl_info = frame->mutable_reference_line_info()->front(); *(rfl_info.mutable_path_data()) = GetContext()->path_data_; const auto& path_points = rfl_info.path_data().discretized_path(); auto* debug_path = rfl_info.mutable_debug()->mutable_planning_data()->add_path(); // TODO(All): // Have to use DpPolyPathOptimizer to show in dreamview. Need change to // correct name. debug_path->set_name("DpPolyPathOptimizer"); debug_path->mutable_path_point()->CopyFrom( {path_points.begin(), path_points.end()}); bool plan_ok = ExecuteTaskOnReferenceLine(planning_start_point, frame); if (!plan_ok) { AERROR << "Fail to plan on reference line."; return Stage::ERROR; } const SLBoundary& adc_sl_boundary = reference_line_info.AdcSlBoundary(); const auto& end_point = reference_line_info.path_data().discretized_path().back(); Vec2d last_xy_point(end_point.x(), end_point.y()); // get s of last point on path common::SLPoint sl_point; if (!reference_line_info.reference_line().XYToSL(last_xy_point, &sl_point)) { AERROR << "Fail to transfer cartesian point to frenet point."; return Stage::ERROR; } double distance_to_path_end = sl_point.s() - GetContext()->scenario_config_.side_pass_exit_distance(); double adc_velocity = frame->vehicle_state().linear_velocity(); double max_velocity_for_stop = GetContext()->scenario_config_.approach_obstacle_max_stop_speed(); if (adc_velocity < max_velocity_for_stop) { GetContext()->pass_obstacle_stuck_cycle_num_ += 1; } else { GetContext()->pass_obstacle_stuck_cycle_num_ = 0; } if (adc_sl_boundary.end_s() > distance_to_path_end || GetContext()->pass_obstacle_stuck_cycle_num_ > 60) { next_stage_ = ScenarioConfig::NO_STAGE; return Stage::FINISHED; } return Stage::RUNNING; } } // namespace side_pass } // namespace scenario } // namespace planning } // namespace apollo <|endoftext|>
<commit_before>#include "pch.h" #include "ReactVideoViewManager.h" #include "NativeModules.h" #include "ReactVideoView.h" namespace winrt::ReactNativeVideoCPP::implementation { ReactVideoViewManager::ReactVideoViewManager() {} // IViewManager hstring ReactVideoViewManager::Name() noexcept { return L"RCTVideo"; } FrameworkElement ReactVideoViewManager::CreateView() noexcept { auto reactVideoView = winrt::ReactNativeVideoCPP::ReactVideoView(m_reactContext); return reactVideoView; } // IViewManagerWithReactContext IReactContext ReactVideoViewManager::ReactContext() noexcept { return m_reactContext; } void ReactVideoViewManager::ReactContext(IReactContext reactContext) noexcept { m_reactContext = reactContext; } // IViewManagerWithExportedViewConstants winrt::Microsoft::ReactNative::ConstantProviderDelegate ReactVideoViewManager::ExportedViewConstants() noexcept { return [](winrt::Microsoft::ReactNative::IJSValueWriter const &constantWriter) { WriteProperty(constantWriter, L"ScaleNone", to_hstring(std::to_string((int)Stretch::None))); WriteProperty(constantWriter, L"ScaleToFill", to_hstring(std::to_string((int)Stretch::UniformToFill))); WriteProperty(constantWriter, L"ScaleAspectFit", to_hstring(std::to_string((int)Stretch::Uniform))); WriteProperty(constantWriter, L"ScaleAspectFill", to_hstring(std::to_string((int)Stretch::Fill))); }; } // IViewManagerWithNativeProperties IMapView<hstring, ViewManagerPropertyType> ReactVideoViewManager::NativeProps() noexcept { auto nativeProps = winrt::single_threaded_map<hstring, ViewManagerPropertyType>(); nativeProps.Insert(L"src", ViewManagerPropertyType::Map); nativeProps.Insert(L"resizeMode", ViewManagerPropertyType::String); nativeProps.Insert(L"repeat", ViewManagerPropertyType::Boolean); nativeProps.Insert(L"paused", ViewManagerPropertyType::Boolean); nativeProps.Insert(L"muted", ViewManagerPropertyType::Boolean); nativeProps.Insert(L"volume", ViewManagerPropertyType::Number); nativeProps.Insert(L"seek", ViewManagerPropertyType::Number); nativeProps.Insert(L"controls", ViewManagerPropertyType::Boolean); nativeProps.Insert(L"fullscreen", ViewManagerPropertyType::Boolean); nativeProps.Insert(L"progressUpdateInterval", ViewManagerPropertyType::Number); return nativeProps.GetView(); } void ReactVideoViewManager::UpdateProperties( FrameworkElement const &view, IJSValueReader const &propertyMapReader) noexcept { if (auto reactVideoView = view.try_as<winrt::ReactNativeVideoCPP::ReactVideoView>()) { const JSValueObject &propertyMap = JSValue::ReadObjectFrom(propertyMapReader); for (auto const &pair : propertyMap) { auto const &propertyName = pair.first; auto const &propertyValue = pair.second; if (!propertyValue.IsNull()) { if (propertyName == "src") { auto const &srcMap = propertyValue.Object(); auto const &uri = srcMap.at("uri"); reactVideoView.Set_UriString(to_hstring(uri.String())); } else if (propertyName == "resizeMode") { reactVideoView.Stretch(static_cast<Stretch>(std::stoul(propertyValue.String()))); } else if (propertyName == "repeat") { reactVideoView.Set_IsLoopingEnabled(propertyValue.Boolean()); } else if (propertyName == "paused") { m_paused = propertyValue.Boolean(); reactVideoView.Set_Paused(m_paused); } else if (propertyName == "muted") { reactVideoView.Set_Muted(propertyValue.Boolean()); } else if (propertyName == "volume") { reactVideoView.Set_Volume(propertyValue.Double()); } else if (propertyName == "seek") { reactVideoView.Set_Position(propertyValue.Double()); } else if (propertyName == "controls") { reactVideoView.Set_Controls(propertyValue.Boolean()); } else if (propertyName == "fullscreen") { reactVideoView.Set_FullScreen(propertyValue.Boolean()); } else if (propertyName == "progressUpdateInterval") { reactVideoView.Set_ProgressUpdateInterval(propertyValue.Int64()); } } } reactVideoView.Set_AutoPlay(!m_paused); // auto play on pause false or not set. } } // IViewManagerWithExportedEventTypeConstants ConstantProviderDelegate ReactVideoViewManager::ExportedCustomBubblingEventTypeConstants() noexcept { return nullptr; } ConstantProviderDelegate ReactVideoViewManager::ExportedCustomDirectEventTypeConstants() noexcept { return [](winrt::Microsoft::ReactNative::IJSValueWriter const &constantWriter) { WriteCustomDirectEventTypeConstant(constantWriter, "Load"); WriteCustomDirectEventTypeConstant(constantWriter, "End"); WriteCustomDirectEventTypeConstant(constantWriter, "Seek"); WriteCustomDirectEventTypeConstant(constantWriter, "Progress"); }; } } // namespace winrt::ReactNativeVideoCPP::implementation <commit_msg>Renaming Boolean etc to AsBoolean (#2119)<commit_after>#include "pch.h" #include "ReactVideoViewManager.h" #include "NativeModules.h" #include "ReactVideoView.h" namespace winrt::ReactNativeVideoCPP::implementation { ReactVideoViewManager::ReactVideoViewManager() {} // IViewManager hstring ReactVideoViewManager::Name() noexcept { return L"RCTVideo"; } FrameworkElement ReactVideoViewManager::CreateView() noexcept { auto reactVideoView = winrt::ReactNativeVideoCPP::ReactVideoView(m_reactContext); return reactVideoView; } // IViewManagerWithReactContext IReactContext ReactVideoViewManager::ReactContext() noexcept { return m_reactContext; } void ReactVideoViewManager::ReactContext(IReactContext reactContext) noexcept { m_reactContext = reactContext; } // IViewManagerWithExportedViewConstants winrt::Microsoft::ReactNative::ConstantProviderDelegate ReactVideoViewManager::ExportedViewConstants() noexcept { return [](winrt::Microsoft::ReactNative::IJSValueWriter const &constantWriter) { WriteProperty(constantWriter, L"ScaleNone", to_hstring(std::to_string((int)Stretch::None))); WriteProperty(constantWriter, L"ScaleToFill", to_hstring(std::to_string((int)Stretch::UniformToFill))); WriteProperty(constantWriter, L"ScaleAspectFit", to_hstring(std::to_string((int)Stretch::Uniform))); WriteProperty(constantWriter, L"ScaleAspectFill", to_hstring(std::to_string((int)Stretch::Fill))); }; } // IViewManagerWithNativeProperties IMapView<hstring, ViewManagerPropertyType> ReactVideoViewManager::NativeProps() noexcept { auto nativeProps = winrt::single_threaded_map<hstring, ViewManagerPropertyType>(); nativeProps.Insert(L"src", ViewManagerPropertyType::Map); nativeProps.Insert(L"resizeMode", ViewManagerPropertyType::String); nativeProps.Insert(L"repeat", ViewManagerPropertyType::Boolean); nativeProps.Insert(L"paused", ViewManagerPropertyType::Boolean); nativeProps.Insert(L"muted", ViewManagerPropertyType::Boolean); nativeProps.Insert(L"volume", ViewManagerPropertyType::Number); nativeProps.Insert(L"seek", ViewManagerPropertyType::Number); nativeProps.Insert(L"controls", ViewManagerPropertyType::Boolean); nativeProps.Insert(L"fullscreen", ViewManagerPropertyType::Boolean); nativeProps.Insert(L"progressUpdateInterval", ViewManagerPropertyType::Number); return nativeProps.GetView(); } void ReactVideoViewManager::UpdateProperties( FrameworkElement const &view, IJSValueReader const &propertyMapReader) noexcept { if (auto reactVideoView = view.try_as<winrt::ReactNativeVideoCPP::ReactVideoView>()) { const JSValueObject &propertyMap = JSValue::ReadObjectFrom(propertyMapReader); for (auto const &pair : propertyMap) { auto const &propertyName = pair.first; auto const &propertyValue = pair.second; if (!propertyValue.IsNull()) { if (propertyName == "src") { auto const &srcMap = propertyValue.AsObject(); auto const &uri = srcMap.at("uri"); reactVideoView.Set_UriString(to_hstring(uri.AsString())); } else if (propertyName == "resizeMode") { reactVideoView.Stretch(static_cast<Stretch>(std::stoul(propertyValue.AsString()))); } else if (propertyName == "repeat") { reactVideoView.Set_IsLoopingEnabled(propertyValue.AsBoolean()); } else if (propertyName == "paused") { m_paused = propertyValue.AsBoolean(); reactVideoView.Set_Paused(m_paused); } else if (propertyName == "muted") { reactVideoView.Set_Muted(propertyValue.AsBoolean()); } else if (propertyName == "volume") { reactVideoView.Set_Volume(propertyValue.AsDouble()); } else if (propertyName == "seek") { reactVideoView.Set_Position(propertyValue.AsDouble()); } else if (propertyName == "controls") { reactVideoView.Set_Controls(propertyValue.AsBoolean()); } else if (propertyName == "fullscreen") { reactVideoView.Set_FullScreen(propertyValue.AsBoolean()); } else if (propertyName == "progressUpdateInterval") { reactVideoView.Set_ProgressUpdateInterval(propertyValue.AsInt64()); } } } reactVideoView.Set_AutoPlay(!m_paused); // auto play on pause false or not set. } } // IViewManagerWithExportedEventTypeConstants ConstantProviderDelegate ReactVideoViewManager::ExportedCustomBubblingEventTypeConstants() noexcept { return nullptr; } ConstantProviderDelegate ReactVideoViewManager::ExportedCustomDirectEventTypeConstants() noexcept { return [](winrt::Microsoft::ReactNative::IJSValueWriter const &constantWriter) { WriteCustomDirectEventTypeConstant(constantWriter, "Load"); WriteCustomDirectEventTypeConstant(constantWriter, "End"); WriteCustomDirectEventTypeConstant(constantWriter, "Seek"); WriteCustomDirectEventTypeConstant(constantWriter, "Progress"); }; } } // namespace winrt::ReactNativeVideoCPP::implementation <|endoftext|>
<commit_before>//============================================================================= // ■ kernel.cpp //----------------------------------------------------------------------------- // 这个文件是干什么的?www //============================================================================= //--------------------------------------------------------------------------- // ● 主程序 //--------------------------------------------------------------------------- void initialize_main() { Terminal::width = 80; Terminal::height = 25; Terminal::write_char((struct pos) {4, 4}, '%', (struct Terminal::char_color) { .fg = Terminal::AQUA, .bg = Terminal::NAVY, }); Graphics::width = 320; Graphics::height = 200; Graphics::fill_rect(16, 16, Graphics::width - 16 * 2, Graphics::height - 16 * 2, Graphics::GREEN); Graphics::draw_text((struct pos) {32, 32}, "Frogimine", Graphics::LIME); Graphics::set_pixel((struct pos) {64, 64}, Graphics::YELLOW); Graphics::draw_text((struct pos) {32, 0}, "Proudly booted by", Graphics::FUCHSIA); Graphics::draw_text((struct pos) {32, 12}, MultibootInfo::boot_loader_name, Graphics::FUCHSIA); char buf[15]; FMString::long2charbuf(buf, 233); Graphics::draw_text((struct pos) {32, 24}, buf, Graphics::WHITE); return; } //--------------------------------------------------------------------------- // ● 内核主程序 //--------------------------------------------------------------------------- extern "C" void kernel_main(type_address multiboot_info_address) { MultibootInfo::initialize(multiboot_info_address); GDT::initialize(); IDT::initialize(); Interrupt::initialize(); ASM::sti(); initialize_main(); Interrupt::initialize_stage2(); } <commit_msg>创建中断处理函数,第四部分<commit_after>//============================================================================= // ■ kernel.cpp //----------------------------------------------------------------------------- // 这个文件是干什么的?www //============================================================================= //--------------------------------------------------------------------------- // ● 主程序 //--------------------------------------------------------------------------- void initialize_main() { Terminal::width = 80; Terminal::height = 25; Terminal::write_char((struct pos) {4, 4}, '%', (struct Terminal::char_color) { .fg = Terminal::AQUA, .bg = Terminal::NAVY, }); Graphics::width = 320; Graphics::height = 200; Graphics::fill_rect(16, 16, Graphics::width - 16 * 2, Graphics::height - 16 * 2, Graphics::GREEN); Graphics::draw_text((struct pos) {32, 32}, "Frogimine", Graphics::LIME); Graphics::set_pixel((struct pos) {64, 64}, Graphics::YELLOW); Graphics::draw_text((struct pos) {32, 0}, "Proudly booted by", Graphics::FUCHSIA); Graphics::draw_text((struct pos) {32, 12}, MultibootInfo::boot_loader_name, Graphics::FUCHSIA); char buf[15]; FMString::long2charbuf(buf, 233); Graphics::draw_text((struct pos) {32, 24}, buf, Graphics::WHITE); return; } //--------------------------------------------------------------------------- // ● 内核主程序 //--------------------------------------------------------------------------- extern "C" void kernel_main(type_address multiboot_info_address) { MultibootInfo::initialize(multiboot_info_address); GDT::initialize(); IDT::initialize(); Interrupt::initialize(); ASM::sti(); initialize_main(); Interrupt::initialize_stage2(); for (;;) ASM::hlt(); } <|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 <pal.h> #include <pal_assert.h> #include <unistd.h> #include <fcntl.h> #include <sys/socket.h> #include <sys/un.h> #include <sys/stat.h> #include "diagnosticsipc.h" #include "processdescriptor.h" IpcStream::DiagnosticsIpc::DiagnosticsIpc(const int serverSocket, sockaddr_un *const pServerAddress) : _serverSocket(serverSocket), _pServerAddress(new sockaddr_un), _isClosed(false) { _ASSERTE(_pServerAddress != nullptr); _ASSERTE(_serverSocket != -1); _ASSERTE(pServerAddress != nullptr); if (_pServerAddress == nullptr || pServerAddress == nullptr) return; memcpy(_pServerAddress, pServerAddress, sizeof(sockaddr_un)); } IpcStream::DiagnosticsIpc::~DiagnosticsIpc() { Close(); delete _pServerAddress; } IpcStream::DiagnosticsIpc *IpcStream::DiagnosticsIpc::Create(const char *const pIpcName, ErrorCallback callback) { #ifdef __APPLE__ mode_t prev_mask = umask(~(S_IRUSR | S_IWUSR)); // This will set the default permission bit to 600 #endif // __APPLE__ const int serverSocket = ::socket(AF_UNIX, SOCK_STREAM, 0); if (serverSocket == -1) { if (callback != nullptr) callback(strerror(errno), errno); #ifdef __APPLE__ umask(prev_mask); #endif // __APPLE__ _ASSERTE(!"Failed to create diagnostics IPC socket."); return nullptr; } sockaddr_un serverAddress{}; serverAddress.sun_family = AF_UNIX; const ProcessDescriptor pd = ProcessDescriptor::FromCurrentProcess(); PAL_GetTransportName( sizeof(serverAddress.sun_path), serverAddress.sun_path, pIpcName, pd.m_Pid, pd.m_ApplicationGroupId, "socket"); #ifndef __APPLE__ if (fchmod(serverSocket, S_IRUSR | S_IWUSR) == -1) { if (callback != nullptr) callback(strerror(errno), errno); _ASSERTE(!"Failed to set permissions on diagnostics IPC socket."); return nullptr; } #endif // __APPLE__ const int fSuccessBind = ::bind(serverSocket, (sockaddr *)&serverAddress, sizeof(serverAddress)); if (fSuccessBind == -1) { if (callback != nullptr) callback(strerror(errno), errno); _ASSERTE(fSuccessBind != -1); const int fSuccessClose = ::close(serverSocket); _ASSERTE(fSuccessClose != -1); #ifdef __APPLE__ umask(prev_mask); #endif // __APPLE__ return nullptr; } const int fSuccessfulListen = ::listen(serverSocket, /* backlog */ 255); if (fSuccessfulListen == -1) { if (callback != nullptr) callback(strerror(errno), errno); _ASSERTE(fSuccessfulListen != -1); const int fSuccessUnlink = ::unlink(serverAddress.sun_path); _ASSERTE(fSuccessUnlink != -1); const int fSuccessClose = ::close(serverSocket); _ASSERTE(fSuccessClose != -1); #ifdef __APPLE__ umask(prev_mask); #endif // __APPLE__ return nullptr; } #ifdef __APPLE__ umask(prev_mask); #endif // __APPLE__ return new IpcStream::DiagnosticsIpc(serverSocket, &serverAddress); } IpcStream *IpcStream::DiagnosticsIpc::Accept(ErrorCallback callback) const { sockaddr_un from; socklen_t fromlen = sizeof(from); const int clientSocket = ::accept(_serverSocket, (sockaddr *)&from, &fromlen); if (clientSocket == -1) { if (callback != nullptr) callback(strerror(errno), errno); return nullptr; } return new IpcStream(clientSocket); } void IpcStream::DiagnosticsIpc::Close(ErrorCallback callback) { if (_isClosed) return; _isClosed = true; if (_serverSocket != -1) { if (::close(_serverSocket) == -1) { if (callback != nullptr) callback(strerror(errno), errno); _ASSERTE(!"Failed to close unix domain socket."); } Unlink(callback); } } //! This helps remove the socket from the filesystem when the runtime exits. //! From: http://man7.org/linux/man-pages/man7/unix.7.html#NOTES //! Binding to a socket with a filename creates a socket in the //! filesystem that must be deleted by the caller when it is no longer //! needed (using unlink(2)). The usual UNIX close-behind semantics //! apply; the socket can be unlinked at any time and will be finally //! removed from the filesystem when the last reference to it is closed. void IpcStream::DiagnosticsIpc::Unlink(ErrorCallback callback) { const int fSuccessUnlink = ::unlink(_pServerAddress->sun_path); if (fSuccessUnlink == -1) { if (callback != nullptr) callback(strerror(errno), errno); _ASSERTE(!"Failed to unlink server address."); } } IpcStream::~IpcStream() { if (_clientSocket != -1) { Flush(); const int fSuccessClose = ::close(_clientSocket); _ASSERTE(fSuccessClose != -1); } } bool IpcStream::Read(void *lpBuffer, const uint32_t nBytesToRead, uint32_t &nBytesRead) const { _ASSERTE(lpBuffer != nullptr); const ssize_t ssize = ::recv(_clientSocket, lpBuffer, nBytesToRead, 0); const bool fSuccess = ssize != -1; if (!fSuccess) { // TODO: Add error handling. } nBytesRead = static_cast<uint32_t>(ssize); return fSuccess; } bool IpcStream::Write(const void *lpBuffer, const uint32_t nBytesToWrite, uint32_t &nBytesWritten) const { _ASSERTE(lpBuffer != nullptr); const ssize_t ssize = ::send(_clientSocket, lpBuffer, nBytesToWrite, 0); const bool fSuccess = ssize != -1; if (!fSuccess) { // TODO: Add error handling. } nBytesWritten = static_cast<uint32_t>(ssize); return fSuccess; } bool IpcStream::Flush() const { // fsync - http://man7.org/linux/man-pages/man2/fsync.2.html ??? return true; } <commit_msg>Delete man page quote (#26779)<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 <pal.h> #include <pal_assert.h> #include <unistd.h> #include <fcntl.h> #include <sys/socket.h> #include <sys/un.h> #include <sys/stat.h> #include "diagnosticsipc.h" #include "processdescriptor.h" IpcStream::DiagnosticsIpc::DiagnosticsIpc(const int serverSocket, sockaddr_un *const pServerAddress) : _serverSocket(serverSocket), _pServerAddress(new sockaddr_un), _isClosed(false) { _ASSERTE(_pServerAddress != nullptr); _ASSERTE(_serverSocket != -1); _ASSERTE(pServerAddress != nullptr); if (_pServerAddress == nullptr || pServerAddress == nullptr) return; memcpy(_pServerAddress, pServerAddress, sizeof(sockaddr_un)); } IpcStream::DiagnosticsIpc::~DiagnosticsIpc() { Close(); delete _pServerAddress; } IpcStream::DiagnosticsIpc *IpcStream::DiagnosticsIpc::Create(const char *const pIpcName, ErrorCallback callback) { #ifdef __APPLE__ mode_t prev_mask = umask(~(S_IRUSR | S_IWUSR)); // This will set the default permission bit to 600 #endif // __APPLE__ const int serverSocket = ::socket(AF_UNIX, SOCK_STREAM, 0); if (serverSocket == -1) { if (callback != nullptr) callback(strerror(errno), errno); #ifdef __APPLE__ umask(prev_mask); #endif // __APPLE__ _ASSERTE(!"Failed to create diagnostics IPC socket."); return nullptr; } sockaddr_un serverAddress{}; serverAddress.sun_family = AF_UNIX; const ProcessDescriptor pd = ProcessDescriptor::FromCurrentProcess(); PAL_GetTransportName( sizeof(serverAddress.sun_path), serverAddress.sun_path, pIpcName, pd.m_Pid, pd.m_ApplicationGroupId, "socket"); #ifndef __APPLE__ if (fchmod(serverSocket, S_IRUSR | S_IWUSR) == -1) { if (callback != nullptr) callback(strerror(errno), errno); _ASSERTE(!"Failed to set permissions on diagnostics IPC socket."); return nullptr; } #endif // __APPLE__ const int fSuccessBind = ::bind(serverSocket, (sockaddr *)&serverAddress, sizeof(serverAddress)); if (fSuccessBind == -1) { if (callback != nullptr) callback(strerror(errno), errno); _ASSERTE(fSuccessBind != -1); const int fSuccessClose = ::close(serverSocket); _ASSERTE(fSuccessClose != -1); #ifdef __APPLE__ umask(prev_mask); #endif // __APPLE__ return nullptr; } const int fSuccessfulListen = ::listen(serverSocket, /* backlog */ 255); if (fSuccessfulListen == -1) { if (callback != nullptr) callback(strerror(errno), errno); _ASSERTE(fSuccessfulListen != -1); const int fSuccessUnlink = ::unlink(serverAddress.sun_path); _ASSERTE(fSuccessUnlink != -1); const int fSuccessClose = ::close(serverSocket); _ASSERTE(fSuccessClose != -1); #ifdef __APPLE__ umask(prev_mask); #endif // __APPLE__ return nullptr; } #ifdef __APPLE__ umask(prev_mask); #endif // __APPLE__ return new IpcStream::DiagnosticsIpc(serverSocket, &serverAddress); } IpcStream *IpcStream::DiagnosticsIpc::Accept(ErrorCallback callback) const { sockaddr_un from; socklen_t fromlen = sizeof(from); const int clientSocket = ::accept(_serverSocket, (sockaddr *)&from, &fromlen); if (clientSocket == -1) { if (callback != nullptr) callback(strerror(errno), errno); return nullptr; } return new IpcStream(clientSocket); } void IpcStream::DiagnosticsIpc::Close(ErrorCallback callback) { if (_isClosed) return; _isClosed = true; if (_serverSocket != -1) { if (::close(_serverSocket) == -1) { if (callback != nullptr) callback(strerror(errno), errno); _ASSERTE(!"Failed to close unix domain socket."); } Unlink(callback); } } // This helps remove the socket from the filesystem when the runtime exits. // See: http://man7.org/linux/man-pages/man7/unix.7.html#NOTES void IpcStream::DiagnosticsIpc::Unlink(ErrorCallback callback) { const int fSuccessUnlink = ::unlink(_pServerAddress->sun_path); if (fSuccessUnlink == -1) { if (callback != nullptr) callback(strerror(errno), errno); _ASSERTE(!"Failed to unlink server address."); } } IpcStream::~IpcStream() { if (_clientSocket != -1) { Flush(); const int fSuccessClose = ::close(_clientSocket); _ASSERTE(fSuccessClose != -1); } } bool IpcStream::Read(void *lpBuffer, const uint32_t nBytesToRead, uint32_t &nBytesRead) const { _ASSERTE(lpBuffer != nullptr); const ssize_t ssize = ::recv(_clientSocket, lpBuffer, nBytesToRead, 0); const bool fSuccess = ssize != -1; if (!fSuccess) { // TODO: Add error handling. } nBytesRead = static_cast<uint32_t>(ssize); return fSuccess; } bool IpcStream::Write(const void *lpBuffer, const uint32_t nBytesToWrite, uint32_t &nBytesWritten) const { _ASSERTE(lpBuffer != nullptr); const ssize_t ssize = ::send(_clientSocket, lpBuffer, nBytesToWrite, 0); const bool fSuccess = ssize != -1; if (!fSuccess) { // TODO: Add error handling. } nBytesWritten = static_cast<uint32_t>(ssize); return fSuccess; } bool IpcStream::Flush() const { // fsync - http://man7.org/linux/man-pages/man2/fsync.2.html ??? return true; } <|endoftext|>
<commit_before>/// /// @file pi_deleglise_rivat2.cpp /// @brief Implementation of the Lagarias-Miller-Odlyzko prime counting /// algorithm with the improvements of Deleglise and Rivat. /// In this implementation the easy leaves have been split up /// into clustered easy leaves and sparse easy leaves. /// This implementation is based on the paper: Tomás Oliveira e /// Silva, Computing pi(x): the combinatorial method, Revista do /// DETUA, vol. 4, no. 6, March 2006, pp. 759-768. /// /// Copyright (C) 2014 Kim Walisch, <kim.walisch@gmail.com> /// /// This file is distributed under the BSD License. See the COPYING /// file in the top level directory. /// #include <primecount-internal.hpp> #include <primesieve.hpp> #include <BitSieve.hpp> #include <pmath.hpp> #include <PhiTiny.hpp> #include <tos_counters.hpp> #include <stdint.h> #include <algorithm> #include <vector> using namespace std; using namespace primecount; namespace { /// Cross-off the multiples of prime in the sieve array. /// For each element that is unmarked the first time update /// the special counters tree data structure. /// template <typename T1, typename T2> void cross_off(int64_t prime, int64_t low, int64_t high, int64_t& next_multiple, T1& sieve, T2& counters) { int64_t segment_size = sieve.size(); int64_t k = next_multiple; for (; k < high; k += prime * 2) { if (sieve[k - low]) { sieve.unset(k - low); cnt_update(counters, k - low, segment_size); } } next_multiple = k; } /// Calculate the contribution of the special leaves. /// @see ../docs/computing-special-leaves.md /// @pre y > 0 && c > 1 /// int64_t S2(int64_t x, int64_t y, int64_t z, int64_t pi_y, int64_t c, vector<int32_t>& primes, vector<int32_t>& lpf, vector<int32_t>& mu) { int64_t limit = z + 1; int64_t segment_size = next_power_of_2(isqrt(limit)); int64_t pi_sqrty = pi_bsearch(primes, isqrt(y)); int64_t S2_result = 0; BitSieve sieve(segment_size); vector<int32_t> counters(segment_size); vector<int32_t> pi = make_pi(y); vector<int64_t> next(primes.begin(), primes.end()); vector<int64_t> phi(primes.size(), 0); // Segmented sieve of Eratosthenes for (int64_t low = 1; low < limit; low += segment_size) { // Current segment = interval [low, high[ int64_t high = min(low + segment_size, limit); int64_t b = 2; sieve.memset(low); // phi(y, b) nodes with b <= c do not contribute to S2, so we // simply sieve out the multiples of the first c primes for (; b <= c; b++) { int64_t k = next[b]; for (int64_t prime = primes[b]; k < high; k += prime * 2) sieve.unset(k - low); next[b] = k; } // Initialize special tree data structure from sieve cnt_finit(sieve, counters, segment_size); // For c + 1 <= b <= pi_sqrty // Find all special leaves: n = primes[b] * m, with mu[m] != 0 and primes[b] < lpf[m] // which satisfy: low <= (x / n) < high for (; b <= pi_sqrty; b++) { int64_t prime = primes[b]; int64_t min_m = max(x / (prime * high), y / prime); int64_t max_m = min(x / (prime * low), y); if (prime >= max_m) goto next_segment; for (int64_t m = max_m; m > min_m; m--) { if (mu[m] != 0 && prime < lpf[m]) { int64_t n = prime * m; int64_t count = cnt_query(counters, (x / n) - low); int64_t phi_xn = phi[b] + count; S2_result -= mu[m] * phi_xn; } } phi[b] += cnt_query(counters, (high - 1) - low); cross_off(prime, low, high, next[b], sieve, counters); } // For pi_sqrty <= b < pi_y // Find all special leaves: n = primes[b] * primes[l] // which satisfy: low <= (x / n) < high for (; b < pi_y; b++) { int64_t prime = primes[b]; int64_t l = pi[min(x / (prime * low), y)]; if (prime >= primes[l]) goto next_segment; int64_t min_hard_leaf = max(x / (prime * high), y / prime); min_hard_leaf = in_between(prime, min_hard_leaf, y); int64_t min_trivial_leaf = min(x / (prime * prime), y); int64_t min_clustered_easy_leaf = min(isqrt(x / prime), y); int64_t min_sparse_easy_leaf = min(z / prime, y); min_trivial_leaf = max(min_hard_leaf, min_trivial_leaf); min_clustered_easy_leaf = max(min_hard_leaf, min_clustered_easy_leaf); min_sparse_easy_leaf = max(min_hard_leaf, min_sparse_easy_leaf); // Find all trivial leaves which satisfy: // phi(x / (primes[b] * primes[l]), b - 1) = 1 if (primes[l] > min_trivial_leaf) { int64_t l_min = pi[min_trivial_leaf]; S2_result += l - l_min; l = l_min; } // Find all clustered easy leaves which satisfy: // x / n <= y such that phi(x / n, b - 1) = pi[x / n] - b + 2 // And phi(x / n, b - 1) == phi(x / m, b - 1) while (primes[l] > min_clustered_easy_leaf) { int64_t n = prime * primes[l]; int64_t xn = x / n; assert(xn < isquare(primes[b])); int64_t phi_xn = pi[xn] - b + 2; int64_t m = prime * primes[b + phi_xn - 1]; int64_t xm = max(x / m, min_clustered_easy_leaf); int64_t l2 = pi[xm]; S2_result += phi_xn * (l - l2); l = l2; } // Find all sparse easy leaves which satisfy: // x / n <= y such that phi(x / n, b - 1) = pi[x / n] - b + 2 for (; primes[l] > min_sparse_easy_leaf; l--) { int64_t n = prime * primes[l]; int64_t xn = x / n; assert(xn < isquare(primes[b])); S2_result += pi[xn] - b + 2; } // Find all hard leaves which satisfy: // low <= (x / n) < high for (; primes[l] > min_hard_leaf; l--) { int64_t n = prime * primes[l]; int64_t xn = x / n; int64_t count = cnt_query(counters, xn - low); int64_t phi_xn = phi[b] + count; S2_result += phi_xn; } phi[b] += cnt_query(counters, (high - 1) - low); cross_off(prime, low, high, next[b], sieve, counters); } next_segment:; } return S2_result; } } // namespace namespace primecount { /// Calculate the number of primes below x using the /// Deleglise-Rivat algorithm. /// Run time: O(x^(2/3) / (log x)^2) operations, O(x^(1/3) * log x) space. /// int64_t pi_deleglise_rivat2(int64_t x) { if (x < 2) return 0; // alpha is a tuning factor double d = (double) x; double alpha = in_between(1, log(d) - 3 * log(log(d)), iroot<6>(x)); int64_t y = (int64_t) (alpha * iroot<3>(x)); int64_t z = x / y; vector<int32_t> mu = make_moebius(y); vector<int32_t> lpf = make_least_prime_factor(y); vector<int32_t> primes; primes.push_back(0); primesieve::generate_primes(y, &primes); int64_t pi_y = primes.size() - 1; int64_t c = min<int64_t>(PhiTiny::MAX_A, pi_y); int64_t s1 = S1(x, y, c, primes, lpf , mu); int64_t s2 = S2(x, y, z, pi_y, c, primes, lpf , mu); int64_t p2 = P2(x, y, 1); int64_t phi = s1 + s2; int64_t sum = phi + pi_y - 1 - p2; return sum; } } // namespace primecount <commit_msg>Use primecount::generate_primes()<commit_after>/// /// @file pi_deleglise_rivat2.cpp /// @brief Implementation of the Lagarias-Miller-Odlyzko prime counting /// algorithm with the improvements of Deleglise and Rivat. /// In this implementation the easy leaves have been split up /// into clustered easy leaves and sparse easy leaves. /// This implementation is based on the paper: Tomás Oliveira e /// Silva, Computing pi(x): the combinatorial method, Revista do /// DETUA, vol. 4, no. 6, March 2006, pp. 759-768. /// /// Copyright (C) 2014 Kim Walisch, <kim.walisch@gmail.com> /// /// This file is distributed under the BSD License. See the COPYING /// file in the top level directory. /// #include <primecount-internal.hpp> #include <BitSieve.hpp> #include <pmath.hpp> #include <PhiTiny.hpp> #include <tos_counters.hpp> #include <stdint.h> #include <algorithm> #include <vector> using namespace std; using namespace primecount; namespace { /// Cross-off the multiples of prime in the sieve array. /// For each element that is unmarked the first time update /// the special counters tree data structure. /// template <typename T1, typename T2> void cross_off(int64_t prime, int64_t low, int64_t high, int64_t& next_multiple, T1& sieve, T2& counters) { int64_t segment_size = sieve.size(); int64_t k = next_multiple; for (; k < high; k += prime * 2) { if (sieve[k - low]) { sieve.unset(k - low); cnt_update(counters, k - low, segment_size); } } next_multiple = k; } /// Calculate the contribution of the special leaves. /// @see ../docs/computing-special-leaves.md /// @pre y > 0 && c > 1 /// int64_t S2(int64_t x, int64_t y, int64_t z, int64_t pi_y, int64_t c, vector<int32_t>& primes, vector<int32_t>& lpf, vector<int32_t>& mu) { int64_t limit = z + 1; int64_t segment_size = next_power_of_2(isqrt(limit)); int64_t pi_sqrty = pi_bsearch(primes, isqrt(y)); int64_t S2_result = 0; BitSieve sieve(segment_size); vector<int32_t> counters(segment_size); vector<int32_t> pi = make_pi(y); vector<int64_t> next(primes.begin(), primes.end()); vector<int64_t> phi(primes.size(), 0); // Segmented sieve of Eratosthenes for (int64_t low = 1; low < limit; low += segment_size) { // Current segment = interval [low, high[ int64_t high = min(low + segment_size, limit); int64_t b = 2; sieve.memset(low); // phi(y, b) nodes with b <= c do not contribute to S2, so we // simply sieve out the multiples of the first c primes for (; b <= c; b++) { int64_t k = next[b]; for (int64_t prime = primes[b]; k < high; k += prime * 2) sieve.unset(k - low); next[b] = k; } // Initialize special tree data structure from sieve cnt_finit(sieve, counters, segment_size); // For c + 1 <= b <= pi_sqrty // Find all special leaves: n = primes[b] * m, with mu[m] != 0 and primes[b] < lpf[m] // which satisfy: low <= (x / n) < high for (; b <= pi_sqrty; b++) { int64_t prime = primes[b]; int64_t min_m = max(x / (prime * high), y / prime); int64_t max_m = min(x / (prime * low), y); if (prime >= max_m) goto next_segment; for (int64_t m = max_m; m > min_m; m--) { if (mu[m] != 0 && prime < lpf[m]) { int64_t n = prime * m; int64_t count = cnt_query(counters, (x / n) - low); int64_t phi_xn = phi[b] + count; S2_result -= mu[m] * phi_xn; } } phi[b] += cnt_query(counters, (high - 1) - low); cross_off(prime, low, high, next[b], sieve, counters); } // For pi_sqrty <= b < pi_y // Find all special leaves: n = primes[b] * primes[l] // which satisfy: low <= (x / n) < high for (; b < pi_y; b++) { int64_t prime = primes[b]; int64_t l = pi[min(x / (prime * low), y)]; if (prime >= primes[l]) goto next_segment; int64_t min_hard_leaf = max(x / (prime * high), y / prime); min_hard_leaf = in_between(prime, min_hard_leaf, y); int64_t min_trivial_leaf = min(x / (prime * prime), y); int64_t min_clustered_easy_leaf = min(isqrt(x / prime), y); int64_t min_sparse_easy_leaf = min(z / prime, y); min_trivial_leaf = max(min_hard_leaf, min_trivial_leaf); min_clustered_easy_leaf = max(min_hard_leaf, min_clustered_easy_leaf); min_sparse_easy_leaf = max(min_hard_leaf, min_sparse_easy_leaf); // Find all trivial leaves which satisfy: // phi(x / (primes[b] * primes[l]), b - 1) = 1 if (primes[l] > min_trivial_leaf) { int64_t l_min = pi[min_trivial_leaf]; S2_result += l - l_min; l = l_min; } // Find all clustered easy leaves which satisfy: // x / n <= y such that phi(x / n, b - 1) = pi[x / n] - b + 2 // And phi(x / n, b - 1) == phi(x / m, b - 1) while (primes[l] > min_clustered_easy_leaf) { int64_t n = prime * primes[l]; int64_t xn = x / n; assert(xn < isquare(primes[b])); int64_t phi_xn = pi[xn] - b + 2; int64_t m = prime * primes[b + phi_xn - 1]; int64_t xm = max(x / m, min_clustered_easy_leaf); int64_t l2 = pi[xm]; S2_result += phi_xn * (l - l2); l = l2; } // Find all sparse easy leaves which satisfy: // x / n <= y such that phi(x / n, b - 1) = pi[x / n] - b + 2 for (; primes[l] > min_sparse_easy_leaf; l--) { int64_t n = prime * primes[l]; int64_t xn = x / n; assert(xn < isquare(primes[b])); S2_result += pi[xn] - b + 2; } // Find all hard leaves which satisfy: // low <= (x / n) < high for (; primes[l] > min_hard_leaf; l--) { int64_t n = prime * primes[l]; int64_t xn = x / n; int64_t count = cnt_query(counters, xn - low); int64_t phi_xn = phi[b] + count; S2_result += phi_xn; } phi[b] += cnt_query(counters, (high - 1) - low); cross_off(prime, low, high, next[b], sieve, counters); } next_segment:; } return S2_result; } } // namespace namespace primecount { /// Calculate the number of primes below x using the /// Deleglise-Rivat algorithm. /// Run time: O(x^(2/3) / (log x)^2) operations, O(x^(1/3) * log x) space. /// int64_t pi_deleglise_rivat2(int64_t x) { if (x < 2) return 0; // alpha is a tuning factor double d = (double) x; double alpha = in_between(1, log(d) - 3 * log(log(d)), iroot<6>(x)); int64_t y = (int64_t) (alpha * iroot<3>(x)); int64_t z = x / y; vector<int32_t> mu = make_moebius(y); vector<int32_t> lpf = make_least_prime_factor(y); vector<int32_t> primes = generate_primes(y); int64_t pi_y = primes.size() - 1; int64_t c = min<int64_t>(PhiTiny::MAX_A, pi_y); int64_t s1 = S1(x, y, c, primes, lpf , mu); int64_t s2 = S2(x, y, z, pi_y, c, primes, lpf , mu); int64_t p2 = P2(x, y, 1); int64_t phi = s1 + s2; int64_t sum = phi + pi_y - 1 - p2; return sum; } } // namespace primecount <|endoftext|>
<commit_before><commit_msg>Corrigindo identação<commit_after><|endoftext|>
<commit_before> // // This source file is part of appleseed. // Visit http://appleseedhq.net/ for additional information and resources. // // This software is released under the MIT license. // // Copyright (c) 2010-2012 Francois Beaune, Jupiter Jazz Limited // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // // Interface header. #include "thinlenscamera.h" // appleseed.renderer headers. #include "renderer/global/globallogger.h" #include "renderer/global/globaltypes.h" #include "renderer/kernel/intersection/intersector.h" #include "renderer/kernel/shading/shadingpoint.h" #include "renderer/kernel/shading/shadingray.h" #include "renderer/kernel/texturing/texturecache.h" #include "renderer/kernel/texturing/texturestore.h" #include "renderer/modeling/camera/camera.h" #include "renderer/modeling/project/project.h" #include "renderer/utility/paramarray.h" #include "renderer/utility/transformsequence.h" // appleseed.foundation headers. #include "foundation/math/matrix.h" #include "foundation/math/sampling.h" #include "foundation/math/scalar.h" #include "foundation/math/transform.h" #include "foundation/math/vector.h" #include "foundation/platform/compiler.h" #include "foundation/platform/types.h" #include "foundation/utility/containers/dictionary.h" #include "foundation/utility/containers/specializedarrays.h" #include "foundation/utility/autoreleaseptr.h" #include "foundation/utility/string.h" // Standard headers. #include <cassert> #include <cstddef> #include <limits> #include <vector> using namespace foundation; using namespace std; namespace renderer { namespace { // // A thin lens camera that supports active autofocus. // // References: // // http://en.wikipedia.org/wiki/Thin_lens // http://en.wikipedia.org/wiki/Focal_length // http://en.wikipedia.org/wiki/F-number // http://en.wikipedia.org/wiki/Autofocus // http://en.wikipedia.org/wiki/Diaphragm_(optics) // const char* Model = "thinlens_camera"; class ThinLensCamera : public Camera { public: ThinLensCamera( const char* name, const ParamArray& params) : Camera(name, params) { m_film_dimensions = get_film_dimensions(); m_focal_length = get_focal_length(); m_f_stop = extract_f_stop(); extract_focal_distance( m_autofocus_enabled, m_autofocus_target, m_focal_distance); extract_diaphragm_blade_count(); extract_diaphragm_tilt_angle(); // Precompute some values. m_lens_radius = 0.5 * m_focal_length / m_f_stop; m_rcp_film_width = 1.0 / m_film_dimensions[0]; m_rcp_film_height = 1.0 / m_film_dimensions[1]; // Build the diaphragm polygon. if (m_diaphragm_blade_count > 0) { m_diaphragm_vertices.resize(m_diaphragm_blade_count); build_regular_polygon( m_diaphragm_blade_count, m_diaphragm_tilt_angle, &m_diaphragm_vertices.front()); } } virtual void release() override { delete this; } virtual const char* get_model() const override { return Model; } virtual void on_frame_begin(const Project& project) override { Camera::on_frame_begin(project); // Perform autofocus, if enabled. if (m_autofocus_enabled) { TextureStore texture_store(*project.get_scene()); TextureCache texture_cache(texture_store); Intersector intersector(project.get_trace_context(), texture_cache, false); m_focal_distance = get_autofocus_focal_distance(intersector); } // Precompute some values. const double t = m_focal_distance / m_focal_length; m_kx = m_film_dimensions[0] * t; m_ky = m_film_dimensions[1] * t; } virtual void generate_ray( SamplingContext& sampling_context, const Vector2d& point, ShadingRay& ray) const override { // Initialize the ray. initialize_ray(sampling_context, ray); // Sample the surface of the lens. Vector2d lens_point; if (m_diaphragm_blade_count == 0) { sampling_context.split_in_place(2, 1); const Vector2d s = sampling_context.next_vector2<2>(); lens_point = m_lens_radius * sample_disk_uniform(s); } else { sampling_context.split_in_place(3, 1); const Vector3d s = sampling_context.next_vector2<3>(); lens_point = m_lens_radius * sample_regular_polygon_uniform( s, m_diaphragm_vertices.size(), &m_diaphragm_vertices.front()); } // Retrieve the camera transformation. Transformd transform; if (m_transform_sequence.size() > 1) { sampling_context.split_in_place(1, 1); const double time = sampling_context.next_double2(); transform = m_transform_sequence.evaluate(time); } else transform = m_transform_sequence.evaluate(0.0); // Set the ray origin. const Transformd::MatrixType& mat = transform.get_local_to_parent(); ray.m_org.x = mat[ 0] * lens_point.x + mat[ 1] * lens_point.y + mat[ 3]; ray.m_org.y = mat[ 4] * lens_point.x + mat[ 5] * lens_point.y + mat[ 7]; ray.m_org.z = mat[ 8] * lens_point.x + mat[ 9] * lens_point.y + mat[11]; const double w = mat[12] * lens_point.x + mat[13] * lens_point.y + mat[15]; assert(w != 0.0); if (w != 1.0) ray.m_org /= w; // Compute the location of the focus point. const Vector3d focus_point( (point.x - 0.5) * m_kx, (0.5 - point.y) * m_ky, -m_focal_distance); // Set the ray direction. ray.m_dir = focus_point; ray.m_dir.x -= lens_point.x; ray.m_dir.y -= lens_point.y; ray.m_dir = transform.vector_to_parent(ray.m_dir); } virtual Vector2d project(const Vector3d& point) const override { const double k = -m_focal_length / point.z; const double x = 0.5 + (point.x * k * m_rcp_film_width); const double y = 0.5 - (point.y * k * m_rcp_film_height); return Vector2d(x, y); } private: // Parameters. Vector2d m_film_dimensions; // film dimensions, in meters double m_focal_length; // focal length, in meters double m_f_stop; // f-stop bool m_autofocus_enabled; // is autofocus enabled? Vector2d m_autofocus_target; // autofocus target on film plane in NDC double m_focal_distance; // focal distance, in meters size_t m_diaphragm_blade_count; // number of blades of the diaphragm, 0 for round aperture double m_diaphragm_tilt_angle; // tilt angle of the diaphragm in radians // Precomputed values. double m_lens_radius; // radius of the lens, in meters, in local space double m_rcp_film_width; // film width reciprocal double m_rcp_film_height; // film height reciprocal double m_kx, m_ky; vector<Vector2d> m_diaphragm_vertices; void extract_diaphragm_blade_count() { const int blade_count = m_params.get_optional<int>("diaphragm_blades", 0); if (blade_count == 0 || blade_count >= 3) m_diaphragm_blade_count = static_cast<size_t>(blade_count); else { m_diaphragm_blade_count = 0; RENDERER_LOG_ERROR( "while defining camera \"%s\": invalid value \"%d\" for parameter \"%s\", " "using default value \"" FMT_SIZE_T "\".", get_name(), blade_count, "diaphragm_blades", m_diaphragm_blade_count); } } void extract_diaphragm_tilt_angle() { m_diaphragm_tilt_angle = deg_to_rad(m_params.get_optional<double>("diaphragm_tilt_angle", 0.0)); } double get_autofocus_focal_distance(const Intersector& intersector) const { // Create a ray. The autofocus considers the scene in the middle of the shutter interval. ShadingRay ray; ray.m_tmin = 0.0; ray.m_tmax = numeric_limits<double>::max(); ray.m_time = 0.5 * (get_shutter_open_time() + get_shutter_close_time()); ray.m_flags = ~0; // Set the ray origin. const Transformd transform = m_transform_sequence.evaluate(0.0); const Transformd::MatrixType& mat = transform.get_local_to_parent(); ray.m_org.x = mat[ 3]; ray.m_org.y = mat[ 7]; ray.m_org.z = mat[11]; const double w = mat[15]; assert(w != 0.0); if (w != 1.0) ray.m_org /= w; // Transform the film point from NDC to camera space. const Vector3d target( (m_autofocus_target[0] - 0.5) * m_film_dimensions[0], (0.5 - m_autofocus_target[1]) * m_film_dimensions[1], -m_focal_length); // Set the ray direction. ray.m_dir = transform.vector_to_parent(target); // Trace the ray. ShadingPoint shading_point; intersector.trace(ray, shading_point); if (shading_point.hit()) { // Hit: compute the focal distance. const Vector3d v = shading_point.get_point() - ray.m_org; const Vector3d camera_direction = transform.vector_to_parent(Vector3d(0.0, 0.0, -1.0)); const double af_focal_distance = dot(v, camera_direction); RENDERER_LOG_INFO( "camera \"%s\": autofocus sets focal distance to %f %s (using camera position at time=0.0).", get_name(), af_focal_distance, plural(af_focal_distance, "meter").c_str()); return af_focal_distance; } else { // No hit: focus at infinity. RENDERER_LOG_INFO( "camera \"%s\": autofocus sets focal distance to infinity (using camera position at time=0.0).", get_name()); return 1.0e38; } } }; } // // ThinLensCameraFactory class implementation. // const char* ThinLensCameraFactory::get_model() const { return Model; } const char* ThinLensCameraFactory::get_human_readable_model() const { return "Thin Lens Camera"; } DictionaryArray ThinLensCameraFactory::get_widget_definitions() const { DictionaryArray definitions = CameraFactory::get_widget_definitions(); definitions.push_back( Dictionary() .insert("name", "f_stop") .insert("label", "F-number") .insert("widget", "text_box") .insert("use", "required") .insert("default", "8.0")); definitions.push_back( Dictionary() .insert("name", "focal_distance") .insert("label", "Focal Distance") .insert("widget", "text_box") .insert("use", "required") .insert("default", "1.0")); definitions.push_back( Dictionary() .insert("name", "autofocus_target") .insert("label", "Autofocus Target") .insert("widget", "text_box") .insert("use", "required")); definitions.push_back( Dictionary() .insert("name", "diaphragm_blades") .insert("label", "Diaphragm Blades") .insert("widget", "text_box") .insert("use", "required") .insert("default", "0")); definitions.push_back( Dictionary() .insert("name", "diaphragm_tilt_angle") .insert("label", "Diaphragm Tilt Angle") .insert("widget", "text_box") .insert("use", "required") .insert("default", "0.0")); return definitions; } auto_release_ptr<Camera> ThinLensCameraFactory::create( const char* name, const ParamArray& params) const { return auto_release_ptr<Camera>(new ThinLensCamera(name, params)); } } // namespace renderer <commit_msg>bug fix: use the time value stored in the ray for camera transform interpolation instead of sampling again the shutter interval.<commit_after> // // This source file is part of appleseed. // Visit http://appleseedhq.net/ for additional information and resources. // // This software is released under the MIT license. // // Copyright (c) 2010-2012 Francois Beaune, Jupiter Jazz Limited // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // // Interface header. #include "thinlenscamera.h" // appleseed.renderer headers. #include "renderer/global/globallogger.h" #include "renderer/global/globaltypes.h" #include "renderer/kernel/intersection/intersector.h" #include "renderer/kernel/shading/shadingpoint.h" #include "renderer/kernel/shading/shadingray.h" #include "renderer/kernel/texturing/texturecache.h" #include "renderer/kernel/texturing/texturestore.h" #include "renderer/modeling/camera/camera.h" #include "renderer/modeling/project/project.h" #include "renderer/utility/paramarray.h" #include "renderer/utility/transformsequence.h" // appleseed.foundation headers. #include "foundation/math/matrix.h" #include "foundation/math/sampling.h" #include "foundation/math/scalar.h" #include "foundation/math/transform.h" #include "foundation/math/vector.h" #include "foundation/platform/compiler.h" #include "foundation/platform/types.h" #include "foundation/utility/containers/dictionary.h" #include "foundation/utility/containers/specializedarrays.h" #include "foundation/utility/autoreleaseptr.h" #include "foundation/utility/string.h" // Standard headers. #include <cassert> #include <cstddef> #include <limits> #include <vector> using namespace foundation; using namespace std; namespace renderer { namespace { // // A thin lens camera that supports active autofocus. // // References: // // http://en.wikipedia.org/wiki/Thin_lens // http://en.wikipedia.org/wiki/Focal_length // http://en.wikipedia.org/wiki/F-number // http://en.wikipedia.org/wiki/Autofocus // http://en.wikipedia.org/wiki/Diaphragm_(optics) // const char* Model = "thinlens_camera"; class ThinLensCamera : public Camera { public: ThinLensCamera( const char* name, const ParamArray& params) : Camera(name, params) { m_film_dimensions = get_film_dimensions(); m_focal_length = get_focal_length(); m_f_stop = extract_f_stop(); extract_focal_distance( m_autofocus_enabled, m_autofocus_target, m_focal_distance); extract_diaphragm_blade_count(); extract_diaphragm_tilt_angle(); // Precompute some values. m_lens_radius = 0.5 * m_focal_length / m_f_stop; m_rcp_film_width = 1.0 / m_film_dimensions[0]; m_rcp_film_height = 1.0 / m_film_dimensions[1]; // Build the diaphragm polygon. if (m_diaphragm_blade_count > 0) { m_diaphragm_vertices.resize(m_diaphragm_blade_count); build_regular_polygon( m_diaphragm_blade_count, m_diaphragm_tilt_angle, &m_diaphragm_vertices.front()); } } virtual void release() override { delete this; } virtual const char* get_model() const override { return Model; } virtual void on_frame_begin(const Project& project) override { Camera::on_frame_begin(project); // Perform autofocus, if enabled. if (m_autofocus_enabled) { TextureStore texture_store(*project.get_scene()); TextureCache texture_cache(texture_store); Intersector intersector(project.get_trace_context(), texture_cache, false); m_focal_distance = get_autofocus_focal_distance(intersector); } // Precompute some values. const double t = m_focal_distance / m_focal_length; m_kx = m_film_dimensions[0] * t; m_ky = m_film_dimensions[1] * t; } virtual void generate_ray( SamplingContext& sampling_context, const Vector2d& point, ShadingRay& ray) const override { // Initialize the ray. initialize_ray(sampling_context, ray); // Sample the surface of the lens. Vector2d lens_point; if (m_diaphragm_blade_count == 0) { sampling_context.split_in_place(2, 1); const Vector2d s = sampling_context.next_vector2<2>(); lens_point = m_lens_radius * sample_disk_uniform(s); } else { sampling_context.split_in_place(3, 1); const Vector3d s = sampling_context.next_vector2<3>(); lens_point = m_lens_radius * sample_regular_polygon_uniform( s, m_diaphragm_vertices.size(), &m_diaphragm_vertices.front()); } // Retrieve the camera transformation. const Transformd transform = m_transform_sequence.size() > 1 ? m_transform_sequence.evaluate(ray.m_time) : m_transform_sequence.evaluate(0.0); // Set the ray origin. const Transformd::MatrixType& mat = transform.get_local_to_parent(); ray.m_org.x = mat[ 0] * lens_point.x + mat[ 1] * lens_point.y + mat[ 3]; ray.m_org.y = mat[ 4] * lens_point.x + mat[ 5] * lens_point.y + mat[ 7]; ray.m_org.z = mat[ 8] * lens_point.x + mat[ 9] * lens_point.y + mat[11]; const double w = mat[12] * lens_point.x + mat[13] * lens_point.y + mat[15]; assert(w != 0.0); if (w != 1.0) ray.m_org /= w; // Compute the location of the focus point. const Vector3d focus_point( (point.x - 0.5) * m_kx, (0.5 - point.y) * m_ky, -m_focal_distance); // Set the ray direction. ray.m_dir = focus_point; ray.m_dir.x -= lens_point.x; ray.m_dir.y -= lens_point.y; ray.m_dir = transform.vector_to_parent(ray.m_dir); } virtual Vector2d project(const Vector3d& point) const override { const double k = -m_focal_length / point.z; const double x = 0.5 + (point.x * k * m_rcp_film_width); const double y = 0.5 - (point.y * k * m_rcp_film_height); return Vector2d(x, y); } private: // Parameters. Vector2d m_film_dimensions; // film dimensions, in meters double m_focal_length; // focal length, in meters double m_f_stop; // f-stop bool m_autofocus_enabled; // is autofocus enabled? Vector2d m_autofocus_target; // autofocus target on film plane in NDC double m_focal_distance; // focal distance, in meters size_t m_diaphragm_blade_count; // number of blades of the diaphragm, 0 for round aperture double m_diaphragm_tilt_angle; // tilt angle of the diaphragm in radians // Precomputed values. double m_lens_radius; // radius of the lens, in meters, in local space double m_rcp_film_width; // film width reciprocal double m_rcp_film_height; // film height reciprocal double m_kx, m_ky; vector<Vector2d> m_diaphragm_vertices; void extract_diaphragm_blade_count() { const int blade_count = m_params.get_optional<int>("diaphragm_blades", 0); if (blade_count == 0 || blade_count >= 3) m_diaphragm_blade_count = static_cast<size_t>(blade_count); else { m_diaphragm_blade_count = 0; RENDERER_LOG_ERROR( "while defining camera \"%s\": invalid value \"%d\" for parameter \"%s\", " "using default value \"" FMT_SIZE_T "\".", get_name(), blade_count, "diaphragm_blades", m_diaphragm_blade_count); } } void extract_diaphragm_tilt_angle() { m_diaphragm_tilt_angle = deg_to_rad(m_params.get_optional<double>("diaphragm_tilt_angle", 0.0)); } double get_autofocus_focal_distance(const Intersector& intersector) const { // Create a ray. The autofocus considers the scene in the middle of the shutter interval. ShadingRay ray; ray.m_tmin = 0.0; ray.m_tmax = numeric_limits<double>::max(); ray.m_time = 0.5 * (get_shutter_open_time() + get_shutter_close_time()); ray.m_flags = ~0; // Set the ray origin. const Transformd transform = m_transform_sequence.evaluate(0.0); const Transformd::MatrixType& mat = transform.get_local_to_parent(); ray.m_org.x = mat[ 3]; ray.m_org.y = mat[ 7]; ray.m_org.z = mat[11]; const double w = mat[15]; assert(w != 0.0); if (w != 1.0) ray.m_org /= w; // Transform the film point from NDC to camera space. const Vector3d target( (m_autofocus_target[0] - 0.5) * m_film_dimensions[0], (0.5 - m_autofocus_target[1]) * m_film_dimensions[1], -m_focal_length); // Set the ray direction. ray.m_dir = transform.vector_to_parent(target); // Trace the ray. ShadingPoint shading_point; intersector.trace(ray, shading_point); if (shading_point.hit()) { // Hit: compute the focal distance. const Vector3d v = shading_point.get_point() - ray.m_org; const Vector3d camera_direction = transform.vector_to_parent(Vector3d(0.0, 0.0, -1.0)); const double af_focal_distance = dot(v, camera_direction); RENDERER_LOG_INFO( "camera \"%s\": autofocus sets focal distance to %f %s (using camera position at time=0.0).", get_name(), af_focal_distance, plural(af_focal_distance, "meter").c_str()); return af_focal_distance; } else { // No hit: focus at infinity. RENDERER_LOG_INFO( "camera \"%s\": autofocus sets focal distance to infinity (using camera position at time=0.0).", get_name()); return 1.0e38; } } }; } // // ThinLensCameraFactory class implementation. // const char* ThinLensCameraFactory::get_model() const { return Model; } const char* ThinLensCameraFactory::get_human_readable_model() const { return "Thin Lens Camera"; } DictionaryArray ThinLensCameraFactory::get_widget_definitions() const { DictionaryArray definitions = CameraFactory::get_widget_definitions(); definitions.push_back( Dictionary() .insert("name", "f_stop") .insert("label", "F-number") .insert("widget", "text_box") .insert("use", "required") .insert("default", "8.0")); definitions.push_back( Dictionary() .insert("name", "focal_distance") .insert("label", "Focal Distance") .insert("widget", "text_box") .insert("use", "required") .insert("default", "1.0")); definitions.push_back( Dictionary() .insert("name", "autofocus_target") .insert("label", "Autofocus Target") .insert("widget", "text_box") .insert("use", "required")); definitions.push_back( Dictionary() .insert("name", "diaphragm_blades") .insert("label", "Diaphragm Blades") .insert("widget", "text_box") .insert("use", "required") .insert("default", "0")); definitions.push_back( Dictionary() .insert("name", "diaphragm_tilt_angle") .insert("label", "Diaphragm Tilt Angle") .insert("widget", "text_box") .insert("use", "required") .insert("default", "0.0")); return definitions; } auto_release_ptr<Camera> ThinLensCameraFactory::create( const char* name, const ParamArray& params) const { return auto_release_ptr<Camera>(new ThinLensCamera(name, params)); } } // namespace renderer <|endoftext|>
<commit_before>/**************************************************************************** ** ** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). ** Contact: Qt Software Information (qt-info@nokia.com) ** ** This file is part of the Qt Assistant of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** 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 either Technology Preview License Agreement or the ** Beta Release License Agreement. ** ** 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.0, 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. ** ** If you are unsure which license is appropriate for your use, please ** contact the sales department at qt-sales@nokia.com. ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "contentwindow.h" #include "centralwidget.h" #include <QtGui/QLayout> #include <QtGui/QFocusEvent> #include <QtGui/QMenu> #include <QtHelp/QHelpEngine> #include <QtHelp/QHelpContentWidget> QT_BEGIN_NAMESPACE ContentWindow::ContentWindow(QHelpEngine *helpEngine) : m_helpEngine(helpEngine) , m_contentWidget(0) , m_expandDepth(-2) { m_contentWidget = m_helpEngine->contentWidget(); m_contentWidget->viewport()->installEventFilter(this); m_contentWidget->setContextMenuPolicy(Qt::CustomContextMenu); QVBoxLayout *layout = new QVBoxLayout(this); layout->setMargin(4); layout->addWidget(m_contentWidget); connect(m_contentWidget, SIGNAL(customContextMenuRequested(QPoint)), this, SLOT(showContextMenu(QPoint))); connect(m_contentWidget, SIGNAL(linkActivated(QUrl)), this, SIGNAL(linkActivated(QUrl))); QHelpContentModel *contentModel = qobject_cast<QHelpContentModel*>(m_contentWidget->model()); connect(contentModel, SIGNAL(contentsCreated()), this, SLOT(expandTOC())); } ContentWindow::~ContentWindow() { } bool ContentWindow::syncToContent(const QUrl& url) { QModelIndex idx = m_contentWidget->indexOf(url); if (!idx.isValid()) return false; m_contentWidget->setCurrentIndex(idx); return true; } void ContentWindow::expandTOC() { if (m_expandDepth > -2) { expandToDepth(m_expandDepth); m_expandDepth = -2; } } void ContentWindow::expandToDepth(int depth) { m_expandDepth = depth; if (depth == -1) m_contentWidget->expandAll(); else m_contentWidget->expandToDepth(depth); } void ContentWindow::focusInEvent(QFocusEvent *e) { if (e->reason() != Qt::MouseFocusReason) m_contentWidget->setFocus(); } void ContentWindow::keyPressEvent(QKeyEvent *e) { if (e->key() == Qt::Key_Escape) emit escapePressed(); } bool ContentWindow::eventFilter(QObject *o, QEvent *e) { if (m_contentWidget && o == m_contentWidget->viewport() && e->type() == QEvent::MouseButtonRelease) { QMouseEvent *me = static_cast<QMouseEvent*>(e); if (m_contentWidget->indexAt(me->pos()).isValid() && me->button() == Qt::LeftButton) { itemClicked(m_contentWidget->currentIndex()); } else if (m_contentWidget->indexAt(me->pos()).isValid() && me->button() == Qt::MidButton) { QHelpContentModel *contentModel = qobject_cast<QHelpContentModel*>(m_contentWidget->model()); QHelpContentItem *itm = contentModel->contentItemAt(m_contentWidget->currentIndex()); CentralWidget::instance()->setSourceInNewTab(itm->url()); } } return QWidget::eventFilter(o, e); } void ContentWindow::showContextMenu(const QPoint &pos) { if (!m_contentWidget->indexAt(pos).isValid()) return; QMenu menu; QAction *curTab = menu.addAction(tr("Open Link")); QAction *newTab = menu.addAction(tr("Open Link in New Tab")); menu.move(m_contentWidget->mapToGlobal(pos)); QHelpContentModel *contentModel = qobject_cast<QHelpContentModel*>(m_contentWidget->model()); QHelpContentItem *itm = contentModel->contentItemAt(m_contentWidget->currentIndex()); QAction *action = menu.exec(); if (curTab == action) emit linkActivated(itm->url()); else if (newTab == action) CentralWidget::instance()->setSourceInNewTab(itm->url()); } void ContentWindow::itemClicked(const QModelIndex &index) { if (!index.isValid()) return; QHelpContentModel *contentModel = qobject_cast<QHelpContentModel*>(m_contentWidget->model()); QHelpContentItem *itm = contentModel->contentItemAt(index); if (itm) emit linkActivated(itm->url()); } QT_END_NAMESPACE <commit_msg>don't invoke the current item without selection<commit_after>/**************************************************************************** ** ** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). ** Contact: Qt Software Information (qt-info@nokia.com) ** ** This file is part of the Qt Assistant of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** 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 either Technology Preview License Agreement or the ** Beta Release License Agreement. ** ** 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.0, 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. ** ** If you are unsure which license is appropriate for your use, please ** contact the sales department at qt-sales@nokia.com. ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "contentwindow.h" #include "centralwidget.h" #include <QtGui/QLayout> #include <QtGui/QFocusEvent> #include <QtGui/QMenu> #include <QtHelp/QHelpEngine> #include <QtHelp/QHelpContentWidget> QT_BEGIN_NAMESPACE ContentWindow::ContentWindow(QHelpEngine *helpEngine) : m_helpEngine(helpEngine) , m_contentWidget(0) , m_expandDepth(-2) { m_contentWidget = m_helpEngine->contentWidget(); m_contentWidget->viewport()->installEventFilter(this); m_contentWidget->setContextMenuPolicy(Qt::CustomContextMenu); QVBoxLayout *layout = new QVBoxLayout(this); layout->setMargin(4); layout->addWidget(m_contentWidget); connect(m_contentWidget, SIGNAL(customContextMenuRequested(QPoint)), this, SLOT(showContextMenu(QPoint))); connect(m_contentWidget, SIGNAL(linkActivated(QUrl)), this, SIGNAL(linkActivated(QUrl))); QHelpContentModel *contentModel = qobject_cast<QHelpContentModel*>(m_contentWidget->model()); connect(contentModel, SIGNAL(contentsCreated()), this, SLOT(expandTOC())); } ContentWindow::~ContentWindow() { } bool ContentWindow::syncToContent(const QUrl& url) { QModelIndex idx = m_contentWidget->indexOf(url); if (!idx.isValid()) return false; m_contentWidget->setCurrentIndex(idx); return true; } void ContentWindow::expandTOC() { if (m_expandDepth > -2) { expandToDepth(m_expandDepth); m_expandDepth = -2; } } void ContentWindow::expandToDepth(int depth) { m_expandDepth = depth; if (depth == -1) m_contentWidget->expandAll(); else m_contentWidget->expandToDepth(depth); } void ContentWindow::focusInEvent(QFocusEvent *e) { if (e->reason() != Qt::MouseFocusReason) m_contentWidget->setFocus(); } void ContentWindow::keyPressEvent(QKeyEvent *e) { if (e->key() == Qt::Key_Escape) emit escapePressed(); } bool ContentWindow::eventFilter(QObject *o, QEvent *e) { if (m_contentWidget && o == m_contentWidget->viewport() && e->type() == QEvent::MouseButtonRelease) { QMouseEvent *me = static_cast<QMouseEvent*>(e); QModelIndex index = m_contentWidget->indexAt(me->pos()); QItemSelectionModel *sm = m_contentWidget->selectionModel(); if (index.isValid() && (sm && sm->isSelected(index))) { if (me->button() == Qt::LeftButton) { itemClicked(index); } else if (me->button() == Qt::MidButton) { QHelpContentModel *contentModel = qobject_cast<QHelpContentModel*>(m_contentWidget->model()); if (contentModel) { QHelpContentItem *itm = contentModel->contentItemAt(index); if (itm) CentralWidget::instance()->setSourceInNewTab(itm->url()); } } } } return QWidget::eventFilter(o, e); } void ContentWindow::showContextMenu(const QPoint &pos) { if (!m_contentWidget->indexAt(pos).isValid()) return; QMenu menu; QAction *curTab = menu.addAction(tr("Open Link")); QAction *newTab = menu.addAction(tr("Open Link in New Tab")); menu.move(m_contentWidget->mapToGlobal(pos)); QHelpContentModel *contentModel = qobject_cast<QHelpContentModel*>(m_contentWidget->model()); QHelpContentItem *itm = contentModel->contentItemAt(m_contentWidget->currentIndex()); QAction *action = menu.exec(); if (curTab == action) emit linkActivated(itm->url()); else if (newTab == action) CentralWidget::instance()->setSourceInNewTab(itm->url()); } void ContentWindow::itemClicked(const QModelIndex &index) { QHelpContentModel *contentModel = qobject_cast<QHelpContentModel*>(m_contentWidget->model()); if (contentModel) { QHelpContentItem *itm = contentModel->contentItemAt(index); if (itm) emit linkActivated(itm->url()); } } QT_END_NAMESPACE <|endoftext|>
<commit_before>// caffe.hpp is the header file that you need to include in your code. It wraps // all the internal caffe header files into one for simpler inclusion. #ifndef CAFFE_CAFFE_HPP_ #define CAFFE_CAFFE_HPP_ #include "caffe/blob.hpp" #include "caffe/common.hpp" #include "caffe/filler.hpp" #include "caffe/layer.hpp" #include "caffe/net.hpp" #include "caffe/proto/caffe.pb.h" #include "caffe/solver.hpp" #include "caffe/util/benchmark.hpp" #include "caffe/util/io.hpp" #include "caffe/vision_layers.hpp" #endif // CAFFE_CAFFE_HPP_ <commit_msg>add factory header to caffe hpp<commit_after>// caffe.hpp is the header file that you need to include in your code. It wraps // all the internal caffe header files into one for simpler inclusion. #ifndef CAFFE_CAFFE_HPP_ #define CAFFE_CAFFE_HPP_ #include "caffe/blob.hpp" #include "caffe/common.hpp" #include "caffe/filler.hpp" #include "caffe/layer.hpp" #include "caffe/layer_factory.hpp" #include "caffe/net.hpp" #include "caffe/proto/caffe.pb.h" #include "caffe/solver.hpp" #include "caffe/util/benchmark.hpp" #include "caffe/util/io.hpp" #include "caffe/vision_layers.hpp" #endif // CAFFE_CAFFE_HPP_ <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: ColumnControl.hxx,v $ * * $Revision: 1.2 $ * * last change: $Author: kz $ $Date: 2004-05-19 13:56:48 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the License); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an AS IS basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef DBAUI_COLUMNCONTROL_HXX #define DBAUI_COLUMNCONTROL_HXX #ifndef _TOOLKIT_CONTROLS_UNOCONTROL_HXX_ #include <toolkit/controls/unocontrol.hxx> #endif #ifndef _DBASHARED_APITOOLS_HXX_ #include "apitools.hxx" #endif namespace dbaui { class OColumnControl : public UnoControl { ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory> m_xORB; public: OColumnControl(const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory>& _rxFactory); // UnoControl virtual ::rtl::OUString GetComponentServiceName(); // XServiceInfo DECLARE_SERVICE_INFO_STATIC(); // ::com::sun::star::awt::XControl virtual void SAL_CALL createPeer(const ::com::sun::star::uno::Reference< ::com::sun::star::awt::XToolkit >& _rToolkit, const ::com::sun::star::uno::Reference< ::com::sun::star::awt::XWindowPeer >& Parent) throw(::com::sun::star::uno::RuntimeException); }; //......................................................................... } // namespace dbaui //......................................................................... #endif // DBAUI_COLUMNCONTROL_HXX <commit_msg>INTEGRATION: CWS ooo19126 (1.2.232); FILE MERGED 2005/09/05 17:35:55 rt 1.2.232.1: #i54170# Change license header: remove SISSL<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: ColumnControl.hxx,v $ * * $Revision: 1.3 $ * * last change: $Author: rt $ $Date: 2005-09-08 16:46:36 $ * * 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 DBAUI_COLUMNCONTROL_HXX #define DBAUI_COLUMNCONTROL_HXX #ifndef _TOOLKIT_CONTROLS_UNOCONTROL_HXX_ #include <toolkit/controls/unocontrol.hxx> #endif #ifndef _DBASHARED_APITOOLS_HXX_ #include "apitools.hxx" #endif namespace dbaui { class OColumnControl : public UnoControl { ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory> m_xORB; public: OColumnControl(const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory>& _rxFactory); // UnoControl virtual ::rtl::OUString GetComponentServiceName(); // XServiceInfo DECLARE_SERVICE_INFO_STATIC(); // ::com::sun::star::awt::XControl virtual void SAL_CALL createPeer(const ::com::sun::star::uno::Reference< ::com::sun::star::awt::XToolkit >& _rToolkit, const ::com::sun::star::uno::Reference< ::com::sun::star::awt::XWindowPeer >& Parent) throw(::com::sun::star::uno::RuntimeException); }; //......................................................................... } // namespace dbaui //......................................................................... #endif // DBAUI_COLUMNCONTROL_HXX <|endoftext|>
<commit_before>#include <map> #include <memory> #include <string> #include <vector> #include <fstream> #include <iostream> #include <JsonDefs.h> #include <JsonSchema.h> #include <JsonErrors.h> #include <JsonResolver.h> // Resolver and typedef for jsvor. namespace jsvor = JsonSchemaValidator; class SimpleResolver : public jsvor::JsonResolver { public: explicit SimpleResolver() : schemas_() { } virtual jsvor::JsonSchemaPtr Resolve(const std::string& ref) const { auto it = schemas_.find(ref); return it != schemas_.end() ? it->second : jsvor::JsonSchemaPtr(); } void AddSchema(const std::string& schema_path, const jsvor::JsonSchemaPtr& schema) { schemas_.insert({schema_path, schema}); } private: std::map<std::string, jsvor::JsonSchemaPtr> schemas_; }; typedef std::vector<jsvor::JsonSchemaPtr> JsonSchemas; typedef std::shared_ptr<SimpleResolver> SimpleResolverPtr; // Show error and help. template <typename Value> void Show(std::ostream& os, const Value& value) { os << value; } template <typename Value, typename... Values> void Show(std::ostream& os, const Value& value, const Values&... values) { Show(os, value); Show(os, values...); } void Usage() { Show(std::cout, "Usage: Validator [SCHEMA]... MAIN_SCHEMA JSON"); std::cout << std::endl; exit(EXIT_SUCCESS); } template <typename... Args> void ShowError(const Args&... args) { Show(std::cerr, args...); std::cerr << std::endl; exit(EXIT_FAILURE); } // Load files and schemas. std::string LoadFileContent(const std::string& file_path) { std::ifstream file(file_path.c_str()); if (not file.is_open()) { ShowError("Cannot open file ", file_path); } return std::string((std::istreambuf_iterator<char>(file)), std::istreambuf_iterator<char>()); } std::string GetFileName(const std::string& file_path) { std::string::size_type last_slash = file_path.find_last_of("/\\"); if (last_slash != std::string::npos) { return file_path.substr(last_slash + 1); } return file_path; } jsvor::JsonSchemaPtr LoadSchema(const std::string& schema_path, const SimpleResolverPtr& resolver) { const std::string content = LoadFileContent(schema_path); try { auto schema = std::make_shared<jsvor::JsonSchema>(content, resolver); resolver->AddSchema(GetFileName(schema_path), schema); return schema; } catch (const jsvor::Error& ex) { ShowError("Could not load schema from ", schema_path, ": ", ex.what()); } return jsvor::JsonSchemaPtr(); } int main(int argc, char * argv[]) { // Parse arguments. if (argc < 3) { Usage(); } std::vector<std::string> schema_paths; for (int arg_index = 1; arg_index < argc - 2; ++arg_index) { schema_paths.push_back(std::string(argv[arg_index])); } std::string main_schema_path = argv[argc - 2]; std::string json_path = argv[argc - 1]; // Load schemas. auto resolver = std::make_shared<SimpleResolver>(); for (const auto& schema_path: schema_paths) { LoadSchema(schema_path, resolver); } auto main_schema = LoadSchema(main_schema_path, resolver); // Load and validate file. auto json = LoadFileContent(json_path); try { main_schema->Validate(json); } catch (const jsvor::IncorrectDocument& error) { ShowError("Incorrect json document: ", error.what()); } exit(EXIT_SUCCESS); } <commit_msg>Fix formatting according with code style<commit_after>#include <map> #include <memory> #include <string> #include <vector> #include <fstream> #include <iostream> #include <JsonDefs.h> #include <JsonSchema.h> #include <JsonErrors.h> #include <JsonResolver.h> // Resolver and typedef for jsvor. namespace jsvor = JsonSchemaValidator; class SimpleResolver : public jsvor::JsonResolver { public: explicit SimpleResolver() : schemas_() { } virtual jsvor::JsonSchemaPtr Resolve(const std::string &ref) const { auto it = schemas_.find(ref); return it != schemas_.end() ? it->second : jsvor::JsonSchemaPtr(); } void AddSchema(const std::string &schema_path, const jsvor::JsonSchemaPtr &schema) { schemas_.insert({schema_path, schema}); } private: std::map<std::string, jsvor::JsonSchemaPtr> schemas_; }; typedef std::vector<jsvor::JsonSchemaPtr> JsonSchemas; typedef std::shared_ptr<SimpleResolver> SimpleResolverPtr; // Show error and help. template <typename Value> void Show(std::ostream &os, const Value& value) { os << value; } template <typename Value, typename... Values> void Show(std::ostream &os, const Value &value, const Values&... values) { Show(os, value); Show(os, values...); } void Usage() { Show(std::cout, "Usage: Validator [SCHEMA]... MAIN_SCHEMA JSON"); std::cout << std::endl; exit(EXIT_SUCCESS); } template <typename... Args> void ShowError(const Args&... args) { Show(std::cerr, args...); std::cerr << std::endl; exit(EXIT_FAILURE); } // Load files and schemas. std::string LoadFileContent(const std::string &file_path) { std::ifstream file(file_path.c_str()); if (not file.is_open()) { ShowError("Cannot open file ", file_path); } return std::string((std::istreambuf_iterator<char>(file)), std::istreambuf_iterator<char>()); } std::string GetFileName(const std::string &file_path) { std::string::size_type last_slash = file_path.find_last_of("/\\"); if (last_slash != std::string::npos) { return file_path.substr(last_slash + 1); } return file_path; } jsvor::JsonSchemaPtr LoadSchema(const std::string &schema_path, const SimpleResolverPtr &resolver) { const std::string content = LoadFileContent(schema_path); try { auto schema = std::make_shared<jsvor::JsonSchema>(content, resolver); resolver->AddSchema(GetFileName(schema_path), schema); return schema; } catch (const jsvor::Error &ex) { ShowError("Could not load schema from ", schema_path, ": ", ex.what()); } return jsvor::JsonSchemaPtr(); } int main(int argc, char *argv[]) { // Parse arguments. if (argc < 3) { Usage(); } std::vector<std::string> schema_paths; for (int arg_index = 1; arg_index < argc - 2; ++arg_index) { schema_paths.push_back(std::string(argv[arg_index])); } std::string main_schema_path = argv[argc - 2]; std::string json_path = argv[argc - 1]; // Load schemas. auto resolver = std::make_shared<SimpleResolver>(); for (const auto& schema_path: schema_paths) { LoadSchema(schema_path, resolver); } auto main_schema = LoadSchema(main_schema_path, resolver); // Load and validate file. auto json = LoadFileContent(json_path); try { main_schema->Validate(json); } catch (const jsvor::IncorrectDocument &error) { ShowError("Incorrect json document: ", error.what()); } exit(EXIT_SUCCESS); } <|endoftext|>
<commit_before>#include <Windows.h> #include "SepehrNotes.h" void jingleBells(); void xmasSong(); void pinkPanther(); SepehrNoteEngine song(150); int main() { printf("Sepehr Mohammadi Presents...\n"); printf("Playing a loop of \"Pink Panther\""); while (true) { //jingleBells(); //xmasSong(); pinkPanther(); } } void jingleBells() { Beep(song.Note("G", 4), song.NoteValue(1 / 4.0)); Beep(song.Note("E", 4), song.NoteValue(1 / 4.0)); Beep(song.Note("E", 4), song.NoteValue(1 / 2.0)); Beep(song.Note("E", 4), song.NoteValue(1 / 4.0)); Beep(song.Note("E", 4), song.NoteValue(1 / 4.0)); Beep(song.Note("E", 4), song.NoteValue(1 / 2.0)); Beep(song.Note("E", 4), song.NoteValue(1 / 4.0)); Beep(song.Note("G", 4), song.NoteValue(1 / 4.0)); Beep(song.Note("C", 4), song.NoteValue(1 / 4.0)); Beep(song.Note("D", 4), song.NoteValue(1 / 4.0)); Beep(song.Note("E", 4), song.NoteValue(1)); Beep(song.Note("F", 4), song.NoteValue(1 / 4.0)); Beep(song.Note("F", 4), song.NoteValue(1 / 4.0)); Beep(song.Note("F", 4), song.NoteValue(1 / 4.0)); Beep(song.Note("F", 4), song.NoteValue(1 / 4.0)); Beep(song.Note("F", 4), song.NoteValue(1 / 4.0)); Beep(song.Note("E", 4), song.NoteValue(1 / 4.0)); Beep(song.Note("E", 4), song.NoteValue(1 / 4.0)); Beep(song.Note("E", 4), song.NoteValue(1 / 4.0)); Beep(song.Note("E", 4), song.NoteValue(1 / 4.0)); Beep(song.Note("D", 4), song.NoteValue(1 / 4.0)); Beep(song.Note("D", 4), song.NoteValue(1 / 4.0)); Beep(song.Note("E", 4), song.NoteValue(1 / 4.0)); Beep(song.Note("D", 4), song.NoteValue(1 / 2.0)); Beep(song.Note("G", 4), song.NoteValue(1 / 2.0)); } void xmasSong() { Beep(song.Note("G", 3), song.NoteValue(1 / 4.0)); Beep(song.Note("C", 4), song.NoteValue(1 / 4.0)); Beep(song.Note("C", 4), song.NoteValue(1 / 8.0)); Beep(song.Note("D", 4), song.NoteValue(1 / 8.0)); Beep(song.Note("C", 4), song.NoteValue(1 / 8.0)); Beep(song.Note("B", 3), song.NoteValue(1 / 8.0)); Beep(song.Note("A", 3), song.NoteValue(1 / 4.0)); Beep(song.Note("A", 3), song.NoteValue(1 / 4.0)); Beep(song.Note("A", 3), song.NoteValue(1 / 4.0)); Beep(song.Note("D", 4), song.NoteValue(1 / 4.0)); Beep(song.Note("D", 4), song.NoteValue(1 / 8.0)); Beep(song.Note("E", 4), song.NoteValue(1 / 8.0)); Beep(song.Note("D", 4), song.NoteValue(1 / 8.0)); Beep(song.Note("C", 4), song.NoteValue(1 / 8.0)); Beep(song.Note("B", 3), song.NoteValue(1 / 4.0)); Beep(song.Note("G", 3), song.NoteValue(1 / 4.0)); Beep(song.Note("G", 3), song.NoteValue(1 / 4.0)); Beep(song.Note("E", 4), song.NoteValue(1 / 4.0)); Beep(song.Note("E", 4), song.NoteValue(1 / 8.0)); Beep(song.Note("F", 4), song.NoteValue(1 / 8.0)); Beep(song.Note("E", 4), song.NoteValue(1 / 8.0)); Beep(song.Note("D", 4), song.NoteValue(1 / 8.0)); Beep(song.Note("C", 4), song.NoteValue(1 / 4.0)); Beep(song.Note("A", 3), song.NoteValue(1 / 4.0)); Beep(song.Note("G", 3), song.NoteValue(1 / 8.0)); Beep(song.Note("G", 3), song.NoteValue(1 / 8.0)); Beep(song.Note("A", 3), song.NoteValue(1 / 4.0)); Beep(song.Note("D", 4), song.NoteValue(1 / 4.0)); Beep(song.Note("B", 3), song.NoteValue(1 / 4.0)); Beep(song.Note("C", 4), song.NoteValue(1 / 2.0)); } void pinkPanther() { for (int octave = 4; octave < 6; octave++) { Beep(song.Note("D#", octave), song.NoteValue(1 / 16.0)); Beep(song.Note("E",octave), song.NoteValue(1 / 4.0, 0)); Sleep(song.NoteValue(1 / 8.0, 1)); Beep(song.Note("F#", octave), song.NoteValue(1 / 16.0)); Beep(song.Note("G", octave), song.NoteValue(1 / 4.0, 0)); Sleep(song.NoteValue(1 / 8.0, 1)); Beep(song.Note("D#", octave), song.NoteValue(1 / 16.0)); Beep(song.Note("E", octave), song.NoteValue(1 / 8.0, 1)); Beep(song.Note("F#", octave), song.NoteValue(1 / 16.0)); Beep(song.Note("G",octave), song.NoteValue(1 / 8.0, 1)); Beep(song.Note("C", octave+1), song.NoteValue(1 / 16.0)); Beep(song.Note("B", octave), song.NoteValue(1 / 8.0, 1)); Beep(song.Note("E", octave), song.NoteValue(1 / 16.0)); Beep(song.Note("G", octave), song.NoteValue(1 / 8.0, 1)); Beep(song.Note("B", octave), song.NoteValue(1 / 16.0)); Beep(song.Note("Bb", octave), song.NoteValue(1 / 2.0 + 1 / 12.0)); Beep(song.Note("A", octave), song.NoteValue(1 / 12.0)); Beep(song.Note("G", octave), song.NoteValue(1 / 12.0)); Beep(song.Note("E", octave), song.NoteValue(1 / 12.0)); Beep(song.Note("D", octave), song.NoteValue(1 / 12.0)); Beep(song.Note("E", octave), song.NoteValue(1 / 12.0 + 1 / 2.0)); Sleep(song.NoteValue(1 / 4.0)); Sleep(song.NoteValue(1 / 8.0, 1)); } } <commit_msg>Added O Holy Night<commit_after>#include <Windows.h> #include "SepehrNotes.h" void jingleBells(); void xmasSong(); void pinkPanther(); void oholynight(); SepehrNoteEngine song(100); int main() { printf("Sepehr Mohammadi Presents...\n"); printf("Playing a loop of \"O Holy Night\""); while (true) { //jingleBells(); //xmasSong(); //pinkPanther(); oholynight(); } } void jingleBells() { Beep(song.Note("G", 4), song.NoteValue(1 / 4.0)); Beep(song.Note("E", 4), song.NoteValue(1 / 4.0)); Beep(song.Note("E", 4), song.NoteValue(1 / 2.0)); Beep(song.Note("E", 4), song.NoteValue(1 / 4.0)); Beep(song.Note("E", 4), song.NoteValue(1 / 4.0)); Beep(song.Note("E", 4), song.NoteValue(1 / 2.0)); Beep(song.Note("E", 4), song.NoteValue(1 / 4.0)); Beep(song.Note("G", 4), song.NoteValue(1 / 4.0)); Beep(song.Note("C", 4), song.NoteValue(1 / 4.0)); Beep(song.Note("D", 4), song.NoteValue(1 / 4.0)); Beep(song.Note("E", 4), song.NoteValue(1)); Beep(song.Note("F", 4), song.NoteValue(1 / 4.0)); Beep(song.Note("F", 4), song.NoteValue(1 / 4.0)); Beep(song.Note("F", 4), song.NoteValue(1 / 4.0)); Beep(song.Note("F", 4), song.NoteValue(1 / 4.0)); Beep(song.Note("F", 4), song.NoteValue(1 / 4.0)); Beep(song.Note("E", 4), song.NoteValue(1 / 4.0)); Beep(song.Note("E", 4), song.NoteValue(1 / 4.0)); Beep(song.Note("E", 4), song.NoteValue(1 / 4.0)); Beep(song.Note("E", 4), song.NoteValue(1 / 4.0)); Beep(song.Note("D", 4), song.NoteValue(1 / 4.0)); Beep(song.Note("D", 4), song.NoteValue(1 / 4.0)); Beep(song.Note("E", 4), song.NoteValue(1 / 4.0)); Beep(song.Note("D", 4), song.NoteValue(1 / 2.0)); Beep(song.Note("G", 4), song.NoteValue(1 / 2.0)); } void xmasSong() { Beep(song.Note("G", 3), song.NoteValue(1 / 4.0)); Beep(song.Note("C", 4), song.NoteValue(1 / 4.0)); Beep(song.Note("C", 4), song.NoteValue(1 / 8.0)); Beep(song.Note("D", 4), song.NoteValue(1 / 8.0)); Beep(song.Note("C", 4), song.NoteValue(1 / 8.0)); Beep(song.Note("B", 3), song.NoteValue(1 / 8.0)); Beep(song.Note("A", 3), song.NoteValue(1 / 4.0)); Beep(song.Note("A", 3), song.NoteValue(1 / 4.0)); Beep(song.Note("A", 3), song.NoteValue(1 / 4.0)); Beep(song.Note("D", 4), song.NoteValue(1 / 4.0)); Beep(song.Note("D", 4), song.NoteValue(1 / 8.0)); Beep(song.Note("E", 4), song.NoteValue(1 / 8.0)); Beep(song.Note("D", 4), song.NoteValue(1 / 8.0)); Beep(song.Note("C", 4), song.NoteValue(1 / 8.0)); Beep(song.Note("B", 3), song.NoteValue(1 / 4.0)); Beep(song.Note("G", 3), song.NoteValue(1 / 4.0)); Beep(song.Note("G", 3), song.NoteValue(1 / 4.0)); Beep(song.Note("E", 4), song.NoteValue(1 / 4.0)); Beep(song.Note("E", 4), song.NoteValue(1 / 8.0)); Beep(song.Note("F", 4), song.NoteValue(1 / 8.0)); Beep(song.Note("E", 4), song.NoteValue(1 / 8.0)); Beep(song.Note("D", 4), song.NoteValue(1 / 8.0)); Beep(song.Note("C", 4), song.NoteValue(1 / 4.0)); Beep(song.Note("A", 3), song.NoteValue(1 / 4.0)); Beep(song.Note("G", 3), song.NoteValue(1 / 8.0)); Beep(song.Note("G", 3), song.NoteValue(1 / 8.0)); Beep(song.Note("A", 3), song.NoteValue(1 / 4.0)); Beep(song.Note("D", 4), song.NoteValue(1 / 4.0)); Beep(song.Note("B", 3), song.NoteValue(1 / 4.0)); Beep(song.Note("C", 4), song.NoteValue(1 / 2.0)); } void pinkPanther() { for (int octave = 4; octave < 6; octave++) { Beep(song.Note("D#", octave), song.NoteValue(1 / 16.0)); Beep(song.Note("E",octave), song.NoteValue(1 / 4.0, 0)); Sleep(song.NoteValue(1 / 8.0, 1)); Beep(song.Note("F#", octave), song.NoteValue(1 / 16.0)); Beep(song.Note("G", octave), song.NoteValue(1 / 4.0, 0)); Sleep(song.NoteValue(1 / 8.0, 1)); Beep(song.Note("D#", octave), song.NoteValue(1 / 16.0)); Beep(song.Note("E", octave), song.NoteValue(1 / 8.0, 1)); Beep(song.Note("F#", octave), song.NoteValue(1 / 16.0)); Beep(song.Note("G",octave), song.NoteValue(1 / 8.0, 1)); Beep(song.Note("C", octave+1), song.NoteValue(1 / 16.0)); Beep(song.Note("B", octave), song.NoteValue(1 / 8.0, 1)); Beep(song.Note("E", octave), song.NoteValue(1 / 16.0)); Beep(song.Note("G", octave), song.NoteValue(1 / 8.0, 1)); Beep(song.Note("B", octave), song.NoteValue(1 / 16.0)); Beep(song.Note("Bb", octave), song.NoteValue(1 / 2.0 + 1 / 12.0)); Beep(song.Note("A", octave), song.NoteValue(1 / 12.0)); Beep(song.Note("G", octave), song.NoteValue(1 / 12.0)); Beep(song.Note("E", octave), song.NoteValue(1 / 12.0)); Beep(song.Note("D", octave), song.NoteValue(1 / 12.0)); Beep(song.Note("E", octave), song.NoteValue(1 / 12.0 + 1 / 2.0)); Sleep(song.NoteValue(1 / 4.0)); Sleep(song.NoteValue(1 / 8.0, 1)); } } void oholynight() { Beep(song.Note("E", 4), song.NoteValue(1 / 4.0,1)); Beep(song.Note("E", 4), song.NoteValue(1 / 4.0)); Beep(song.Note("E", 4), song.NoteValue(1 / 8.0)); Beep(song.Note("G", 4), song.NoteValue(1 / 2.0)); Sleep(song.NoteValue(1 /8.0)); Beep(song.Note("G", 4), song.NoteValue(1 /8.0)); Beep(song.Note("A", 4), song.NoteValue(1 / 4.0)); Beep(song.Note("A", 4), song.NoteValue(1 / 8.0)); Beep(song.Note("F", 4), song.NoteValue(1 / 4.0)); Beep(song.Note("A", 4), song.NoteValue(1 / 8.0)); Beep(song.Note("C", 5), song.NoteValue(1 / 2.0,1)); Beep(song.Note("G", 4), song.NoteValue(1 / 4.0)); Beep(song.Note("G", 4), song.NoteValue(1 / 8.0)); Beep(song.Note("E", 4), song.NoteValue(1 / 4.0)); Beep(song.Note("D", 4), song.NoteValue(1 / 8.0)); Beep(song.Note("C", 4), song.NoteValue(1 / 4.0,1)); Beep(song.Note("E", 4), song.NoteValue(1 / 4.0)); Beep(song.Note("E", 4), song.NoteValue(1 / 8.0)); Beep(song.Note("G", 4), song.NoteValue(1 / 4.0,1)); Beep(song.Note("F", 4), song.NoteValue(1 / 4.0)); Beep(song.Note("F", 4), song.NoteValue(1 / 8.0)); Beep(song.Note("C", 4), song.NoteValue(1 / 2.0+1/2.0,1)); Sleep(song.NoteValue(1 / 2.0, 1)); } <|endoftext|>
<commit_before>#include <regex> #include <string> #include "loader.h" #include "hdd.h" Loader::Loader(std::ifstream ifs, HDD * hdd) { DLOG("Parsing program file."); std::string line; std::regex header_regex("// [A-z]+ ([A-Fa-f0-9]+) ([A-Fa-f0-9]+) ([[A-Fa-f0-9]+)"); std::smatch header_match; std::regex end_regex("// END"); for ( std::getline(ifs, line); ifs.eof(); std::getline(ifs, line) ) { if ( std::regex_match(line, header_match, header_regex) ) { File file; std::vector<WORD> program; if (header_match.size() == 4) { file.id = std::stoul(header_match[1].str(), 0, 16); file.programSize = std::stoul(header_match[2].str(), 0, 16); file.priority = std::stoul(header_match[3].str(), 0, 16); DLOG("job id: %u, job size (word): %lu, job priority: %u", file.id, file.programSize, file.priority ); /* Temporarily cache opcodes, since we don't know size of file yet */ for (size_t i = 0; i < file.programSize; i++) { std::getline(ifs, line); program.push_back((WORD)stoul(line)); } /* Match against data header */ if ( std::regex_match(line, header_match, header_regex) ) { if (header_match.size() == 4) { file.inputBufferSize = std::stoul(header_match[1].str(), 0, 16); file.outputBufferSize = std::stoul(header_match[2].str(), 0, 16); file.tempBufferSize = std::stoul(header_match[3].str(), 0, 16); DLOG("input buffer: %lu, output buffer size: %lu, temp buffer size: %lu", file.inputBufferSize, file.outputBufferSize, file.tempBufferSize ); size_t dataSize = file.inputBufferSize + file.outputBufferSize + file.tempBufferSize; /* We can now allocate a file */ File * pFile = (File *)hdd->newFile(sizeof(File) + (file.programSize + dataSize) * sizeof(WORD)); /* copy file header */ memcpy(pFile, &file, sizeof(File)); /* copy program opcodes */ memcpy(pFile + sizeof(File), program.data(), program.size() * sizeof(WORD)); WORD * currentWord = (WORD *)pFile + sizeof(File) + (program.size() * sizeof(WORD)); /* parse and copy data */ for (size_t i = 0; i < (dataSize); i++) { std::getline(ifs, line); *currentWord = (WORD)stoul(line); } } else { /* Corrupted data header, let's abort */ continue; } } else { /* This should never happen, abort this program and move on */ continue; } } else { /* end of this program block */ if ( std::regex_match(line, end_regex) ) continue; for ( size_t i = 0; i < header_match.size(); i++ ) DLOG("[ERROR] while parsing header with match %lu and chunk %s", i + 1, header_match[i].str().c_str()); } } else { DLOG("[ERROR] while parsing program header, searching to // END and retrying."); } } DLOG("Finished parsing program file."); } <commit_msg>failure to namespace memcpy was failing on travis<commit_after>#include <regex> #include <string> #include <cstring> #include "loader.h" #include "hdd.h" Loader::Loader(std::ifstream ifs, HDD * hdd) { DLOG("Parsing program file."); std::string line; std::regex header_regex("// [A-z]+ ([A-Fa-f0-9]+) ([A-Fa-f0-9]+) ([[A-Fa-f0-9]+)"); std::smatch header_match; std::regex end_regex("// END"); for ( std::getline(ifs, line); ifs.eof(); std::getline(ifs, line) ) { if ( std::regex_match(line, header_match, header_regex) ) { File file; std::vector<WORD> program; if (header_match.size() == 4) { file.id = std::stoul(header_match[1].str(), 0, 16); file.programSize = std::stoul(header_match[2].str(), 0, 16); file.priority = std::stoul(header_match[3].str(), 0, 16); DLOG("job id: %u, job size (word): %lu, job priority: %u", file.id, file.programSize, file.priority ); /* Temporarily cache opcodes, since we don't know size of file yet */ for (size_t i = 0; i < file.programSize; i++) { std::getline(ifs, line); program.push_back((WORD)stoul(line)); } /* Match against data header */ if ( std::regex_match(line, header_match, header_regex) ) { if (header_match.size() == 4) { file.inputBufferSize = std::stoul(header_match[1].str(), 0, 16); file.outputBufferSize = std::stoul(header_match[2].str(), 0, 16); file.tempBufferSize = std::stoul(header_match[3].str(), 0, 16); DLOG("input buffer: %lu, output buffer size: %lu, temp buffer size: %lu", file.inputBufferSize, file.outputBufferSize, file.tempBufferSize ); size_t dataSize = file.inputBufferSize + file.outputBufferSize + file.tempBufferSize; /* We can now allocate a file */ File * pFile = (File *)hdd->newFile(sizeof(File) + (file.programSize + dataSize) * sizeof(WORD)); /* copy file header */ std::memcpy(pFile, &file, sizeof(File)); /* copy program opcodes */ std::memcpy(pFile + sizeof(File), program.data(), program.size() * sizeof(WORD)); WORD * currentWord = (WORD *)pFile + sizeof(File) + (program.size() * sizeof(WORD)); /* parse and copy data */ for (size_t i = 0; i < (dataSize); i++) { std::getline(ifs, line); *currentWord = (WORD)stoul(line); } } else { /* Corrupted data header, let's abort */ continue; } } else { /* This should never happen, abort this program and move on */ continue; } } else { /* end of this program block */ if ( std::regex_match(line, end_regex) ) continue; for ( size_t i = 0; i < header_match.size(); i++ ) DLOG("[ERROR] while parsing header with match %lu and chunk %s", i + 1, header_match[i].str().c_str()); } } else { DLOG("[ERROR] while parsing program header, searching to // END and retrying."); } } DLOG("Finished parsing program file."); } <|endoftext|>
<commit_before><commit_msg>Adapt style to standard library<commit_after><|endoftext|>
<commit_before>/* COPYRIGHT (c) 2014 Umut Acar, Arthur Chargueraud, and Michael * Rainey * All rights reserved. * * \file sort.hpp * \brief Sorting algorithms * */ #include "array.hpp" #ifndef _MINICOURSE_SORT_H_ #define _MINICOURSE_SORT_H_ /***********************************************************************/ long nlogn(long n) { return pasl::data::estimator::annotation::nlgn(n); } /*---------------------------------------------------------------------*/ /* Sequential sort */ void in_place_sort(array_ref xs, long lo, long hi) { if (hi-lo > 0) std::sort(&xs[lo], &xs[hi-1]+1); } void in_place_sort(array_ref xs) { in_place_sort(xs, 0l, xs.size()); } array seqsort(const_array_ref xs) { array tmp = copy(xs); in_place_sort(tmp); return tmp; } array seqsort(const_array_ref xs, long lo, long hi) { array tmp = slice(xs, lo, hi); in_place_sort(tmp); return tmp; } /*---------------------------------------------------------------------*/ /* Parallel quicksort */ controller_type quicksort_contr("quicksort"); array quicksort(const_array_ref xs) { long n = xs.size(); array result = { }; auto seq = [&] { result = seqsort(xs); }; par::cstmt(quicksort_contr, [&] { return nlogn(n); }, [&] { if (n < 2) { seq(); } else { long m = n/2; value_type p = xs[m]; array less = filter([&] (value_type x) { return x < p; }, xs); array equal = filter([&] (value_type x) { return x == p; }, xs); array greater = filter([&] (value_type x) { return x > p; }, xs); array left = { }; array right = { }; par::fork2([&] { left = quicksort(less); }, [&] { right = quicksort(greater); }); result = concat(left, equal, right); } }, seq); return result; } /*---------------------------------------------------------------------*/ /* Parallel mergesort */ void merge_seq(const_array_ref xs, const_array_ref ys, array_ref tmp, long lo_xs, long hi_xs, long lo_ys, long hi_ys, long lo_tmp) { long i = lo_xs; long j = lo_ys; long z = lo_tmp; // merge two halves until one is empty while (i < hi_xs and j < hi_ys) tmp[z++] = (xs[i] < ys[j]) ? xs[i++] : ys[j++]; // copy remaining items prim::copy(&xs[0], &tmp[0], i, hi_xs, z); prim::copy(&ys[0], &tmp[0], j, hi_ys, z); } void merge_seq(array_ref xs, array_ref tmp, long lo, long mid, long hi) { merge_seq(xs, xs, tmp, lo, mid, mid, hi, lo); // copy back to source array prim::copy(&tmp[0], &xs[0], lo, hi, lo); } long lower_bound(const_array_ref xs, long lo, long hi, value_type val) { const value_type* first_xs = &xs[0]; return std::lower_bound(first_xs+lo, first_xs+hi, val)-first_xs; } controller_type merge_contr("merge"); void merge_par(const_array_ref xs, const_array_ref ys, array_ref tmp, long lo_xs, long hi_xs, long lo_ys, long hi_ys, long lo_tmp) { long n1 = hi_xs-lo_xs; long n2 = hi_ys-lo_ys; auto seq = [&] { merge_seq(xs, ys, tmp, lo_xs, hi_xs, lo_ys, hi_ys, lo_tmp); }; par::cstmt(merge_contr, [&] { return n1+n2; }, [&] { if (n1 < n2) { // to ensure that the first subarray being sorted is the larger or the two merge_par(ys, xs, tmp, lo_ys, hi_ys, lo_xs, hi_xs, lo_tmp); } else if (n1 == 1) { if (n2 == 0) { // xs singleton; ys empty tmp[lo_tmp] = xs[lo_xs]; } else { // both singletons tmp[lo_tmp+0] = std::min(xs[lo_xs], ys[lo_ys]); tmp[lo_tmp+1] = std::max(xs[lo_xs], ys[lo_ys]); } } else { // select pivot positions long mid_xs = (lo_xs+hi_xs)/2; long mid_ys = lower_bound(ys, lo_ys, hi_ys, xs[mid_xs]); // number of items to be treated by the first parallel call long k = (mid_xs-lo_xs) + (mid_ys-lo_ys); par::fork2([&] { merge_par(xs, ys, tmp, lo_xs, mid_xs, lo_ys, mid_ys, lo_tmp); }, [&] { merge_par(xs, ys, tmp, mid_xs, hi_xs, mid_ys, hi_ys, lo_tmp+k); }); } }, seq); } void merge_par(array_ref xs, array_ref tmp, long lo, long mid, long hi) { merge_par(xs, xs, tmp, lo, mid, mid, hi, lo); // copy back to source array prim::pcopy(&tmp[0], &xs[0], lo, hi, lo); } array merge(const_array_ref xs, const_array_ref ys) { long n = xs.size(); long m = ys.size(); array tmp = array(n + m); merge_par(xs, ys, tmp, 0l, n, 0l, m, 0l); return tmp; } controller_type mergesort_contr("mergesort"); void mergesort_rec(array_ref xs, array_ref tmp, long lo, long hi) { long n = hi - lo; auto seq = [&] { in_place_sort(xs, lo, hi); }; par::cstmt(mergesort_contr, [&] { return nlogn(n); }, [&] { if (n <= 2) { seq(); return; } long mid = (lo + hi) / 2; par::fork2([&] { mergesort_rec(xs, tmp, lo, mid); }, [&] { mergesort_rec(xs, tmp, mid, hi); }); merge_par(xs, tmp, lo, mid, hi); }, seq); } array mergesort(const_array_ref xs) { long n = xs.size(); array result = copy(xs); array tmp = array(n); mergesort_rec(result, tmp, 0l, n); return result; } /***********************************************************************/ #endif /*! _MINICOURSE_SORT_H_ */ <commit_msg>Trying std::merge<commit_after>/* COPYRIGHT (c) 2014 Umut Acar, Arthur Chargueraud, and Michael * Rainey * All rights reserved. * * \file sort.hpp * \brief Sorting algorithms * */ #include "array.hpp" #ifndef _MINICOURSE_SORT_H_ #define _MINICOURSE_SORT_H_ /***********************************************************************/ long nlogn(long n) { return pasl::data::estimator::annotation::nlgn(n); } /*---------------------------------------------------------------------*/ /* Sequential sort */ void in_place_sort(array_ref xs, long lo, long hi) { if (hi-lo > 0) std::sort(&xs[lo], &xs[hi-1]+1); } void in_place_sort(array_ref xs) { in_place_sort(xs, 0l, xs.size()); } array seqsort(const_array_ref xs) { array tmp = copy(xs); in_place_sort(tmp); return tmp; } array seqsort(const_array_ref xs, long lo, long hi) { array tmp = slice(xs, lo, hi); in_place_sort(tmp); return tmp; } /*---------------------------------------------------------------------*/ /* Parallel quicksort */ controller_type quicksort_contr("quicksort"); array quicksort(const_array_ref xs) { long n = xs.size(); array result = { }; auto seq = [&] { result = seqsort(xs); }; par::cstmt(quicksort_contr, [&] { return nlogn(n); }, [&] { if (n < 2) { seq(); } else { long m = n/2; value_type p = xs[m]; array less = filter([&] (value_type x) { return x < p; }, xs); array equal = filter([&] (value_type x) { return x == p; }, xs); array greater = filter([&] (value_type x) { return x > p; }, xs); array left = { }; array right = { }; par::fork2([&] { left = quicksort(less); }, [&] { right = quicksort(greater); }); result = concat(left, equal, right); } }, seq); return result; } /*---------------------------------------------------------------------*/ /* Sequential merge */ void merge_seq(const_array_ref xs, const_array_ref ys, array_ref tmp, long lo_xs, long hi_xs, long lo_ys, long hi_ys, long lo_tmp) { std::merge(&xs[lo_xs], &xs[hi_xs-1]+1, &ys[lo_ys], &ys[hi_ys-1]+1, &tmp[lo_tmp]); } void merge_seq(array_ref xs, array_ref tmp, long lo, long mid, long hi) { merge_seq(xs, xs, tmp, lo, mid, mid, hi, lo); // copy back to source array prim::copy(&tmp[0], &xs[0], lo, hi, lo); } /*---------------------------------------------------------------------*/ /* Parallel merge */ long lower_bound(const_array_ref xs, long lo, long hi, value_type val) { const value_type* first_xs = &xs[0]; return std::lower_bound(first_xs+lo, first_xs+hi, val)-first_xs; } controller_type merge_contr("merge"); void merge_par(const_array_ref xs, const_array_ref ys, array_ref tmp, long lo_xs, long hi_xs, long lo_ys, long hi_ys, long lo_tmp) { long n1 = hi_xs-lo_xs; long n2 = hi_ys-lo_ys; auto seq = [&] { merge_seq(xs, ys, tmp, lo_xs, hi_xs, lo_ys, hi_ys, lo_tmp); }; par::cstmt(merge_contr, [&] { return n1+n2; }, [&] { if (n1 < n2) { // to ensure that the first subarray being sorted is the larger or the two merge_par(ys, xs, tmp, lo_ys, hi_ys, lo_xs, hi_xs, lo_tmp); } else if (n1 == 1) { if (n2 == 0) { // xs singleton; ys empty tmp[lo_tmp] = xs[lo_xs]; } else { // both singletons tmp[lo_tmp+0] = std::min(xs[lo_xs], ys[lo_ys]); tmp[lo_tmp+1] = std::max(xs[lo_xs], ys[lo_ys]); } } else { // select pivot positions long mid_xs = (lo_xs+hi_xs)/2; long mid_ys = lower_bound(ys, lo_ys, hi_ys, xs[mid_xs]); // number of items to be treated by the first parallel call long k = (mid_xs-lo_xs) + (mid_ys-lo_ys); par::fork2([&] { merge_par(xs, ys, tmp, lo_xs, mid_xs, lo_ys, mid_ys, lo_tmp); }, [&] { merge_par(xs, ys, tmp, mid_xs, hi_xs, mid_ys, hi_ys, lo_tmp+k); }); } }, seq); } void merge_par(array_ref xs, array_ref tmp, long lo, long mid, long hi) { merge_par(xs, xs, tmp, lo, mid, mid, hi, lo); // copy back to source array prim::pcopy(&tmp[0], &xs[0], lo, hi, lo); } array merge(const_array_ref xs, const_array_ref ys) { long n = xs.size(); long m = ys.size(); array tmp = array(n + m); merge_par(xs, ys, tmp, 0l, n, 0l, m, 0l); return tmp; } /*---------------------------------------------------------------------*/ /* Parallel mergesort */ controller_type mergesort_contr("mergesort"); void mergesort_rec(array_ref xs, array_ref tmp, long lo, long hi) { long n = hi - lo; auto seq = [&] { in_place_sort(xs, lo, hi); }; par::cstmt(mergesort_contr, [&] { return nlogn(n); }, [&] { if (n <= 2) { seq(); return; } long mid = (lo + hi) / 2; par::fork2([&] { mergesort_rec(xs, tmp, lo, mid); }, [&] { mergesort_rec(xs, tmp, mid, hi); }); merge_par(xs, tmp, lo, mid, hi); }, seq); } array mergesort(const_array_ref xs) { long n = xs.size(); array result = copy(xs); array tmp = array(n); mergesort_rec(result, tmp, 0l, n); return result; } /***********************************************************************/ #endif /*! _MINICOURSE_SORT_H_ */ <|endoftext|>
<commit_before><commit_msg>fixup base64<commit_after><|endoftext|>
<commit_before>/* Copyright (c) 2009-2011, 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 <boost/filesystem/fstream.hpp> #include <boost/property_tree/ptree.hpp> #include <boost/property_tree/xml_parser.hpp> #include "logview.hh" #include "markup.hh" #include "project.hh" /** Pages related to logs. Primary Author(s): Sebastien Mirolo <smirolo@fortylines.com> */ pathVariable indexFile("indexFile", "index file with projects dependencies information"); void logAddSessionVars( boost::program_options::options_description& all, boost::program_options::options_description& visible ) { using namespace boost::program_options; options_description localOptions("log"); localOptions.add(indexFile.option()); all.add(localOptions); visible.add(localOptions); } void logviewFetch( session& s, const boost::filesystem::path& pathname ) { using namespace RAPIDXML; using namespace boost::filesystem; /* remove the '/log' command tag and add the project dependency info (dws.xml). */ boost::filesystem::path indexFileName = indexFile.value(s); /* Each log contains the results gathered on a build server. We prefer to present one build results per column but need to write s.out() one table row at a time so we create the table entirely in memory before we display it. If we were to present build results per row, we would still need to preprocess the log files once but only to determine the column headers. */ static const boost::regex logPat("([^-]+)-.*\\.log"); /* build as column headers */ typedef std::set<path> colHeadersType; colHeadersType colHeaders; /* (project,(build,[status,exitCode])) */ typedef std::map<path,std::pair<std::string,int> > colType; typedef std::map<std::string,colType> tableType; tableType table; /* Populate the project names based on the projects specified in the index file. */ xml_document<> *doc = s.loadxml(indexFileName); if ( doc ) { /* Error loading the document, don't bother */ xml_node<> *root = doc->first_node(); if( root != NULL ) { for( xml_node<> *project = root->first_node("project"); project != NULL; project = project->next_sibling("project") ) { xml_attribute<> *name = project->first_attribute("name"); if( name != NULL ) { path repcontrol((srcTop.value(s) / path(name->value())) / ".git"); if( boost::filesystem::exists(repcontrol) ) { table[name->value()] = colType(); } } } } path dirname(is_directory(pathname) ? pathname : siteTop.value(s) / "log"); std::string logBase; for( directory_iterator entry = directory_iterator(dirname); entry != directory_iterator(); ++entry ) { boost::smatch m; path filename(*entry); filename = filename.filename(); if( boost::regex_search(filename.string(),m,logPat) ) { xml_document<> *doc = s.loadxml(*entry); if ( doc ) { /* If there was an error loading the XML file, don't bother. */ logBase = m.str(1); colHeaders.insert(filename); xml_node<> *root = doc->first_node(); if( root != NULL ) { for( xml_node<> *project = root->first_node("section"); project != NULL; project = project->next_sibling("section") ) { xml_attribute<> *name = project->first_attribute("id"); if( name != NULL ) { xml_node<> *status = project->first_node("status"); if( status != NULL ) { int exitCode = 0; xml_attribute<> *exitAttr = status->first_attribute("error"); if( exitAttr ) { exitCode = atoi(exitAttr->value()); } table[name->value()][filename] = std::make_pair(status->value(),exitCode); } } } } } } } } s.out() << html::p() << "This build view page shows the stability " "of all projects at a glance. Each column represents a build log " "obtained by running the following command on a local machine:" << html::p::end; s.out() << html::pre() << html::a().href("/resources/dws") << "dws" << html::a::end << " build " << s.asAbsUrl(s.asUrl(indexFileName),"") << html::pre::end; s.out() << html::p() << "dws, the inter-project dependency tool " "generates a build log file with XML markups as part of building " "projects. That build log is then stamped with the local machine " "hostname and time before being uploaded onto the remote machine. " "This page presents all build logs currently available on the remote " "machine." << html::p::end; /* Display the table column headers. */ if( colHeaders.empty() ) { s.out() << html::pre() << "There are no logs available" << html::pre::end; } else { s.out() << html::table(); s.out() << html::tr(); s.out() << html::th() << html::th::end; for( colHeadersType::const_iterator col = colHeaders.begin(); col != colHeaders.end(); ++col ) { s.out() << html::th() << html::a().href((boost::filesystem::path("/log") / *col).string()) << *col << html::a::end << html::th::end; } s.out() << html::tr::end; /* Display one project per row, one build result per column. */ for( tableType::const_iterator row = table.begin(); row != table.end(); ++row ) { s.out() << html::tr(); s.out() << html::th() << projhref(s,row->first) << html::th::end; for( colHeadersType::const_iterator col = colHeaders.begin(); col != colHeaders.end(); ++col ) { colType::const_iterator value = row->second.find(*col); if( value != row->second.end() ) { if( value->second.second ) { s.out() << html::td().classref("positiveErrorCode"); } else { s.out() << html::td(); } s.out() << value->second.first; } else { s.out() << html::td(); } s.out() << html::td::end; } s.out() << html::tr::end; } s.out() << html::table::end; } /* footer */ s.out() << html::p() << "Each cell contains the time it took to make " "a specific project. If make exited with an error code before " "the completion of the last target, it is marked " << html::span().classref("positiveErrorCode") << "&nbsp;as such&nbsp;" << html::span::end << "." << html::p::end; s.out() << emptyParaHack; } void regressionsFetch( session& s, const boost::filesystem::path& pathname ) { using namespace RAPIDXML; using namespace boost::filesystem; boost::filesystem::path regressname = siteTop.value(s) / boost::filesystem::path("log/tests") / (document.value(s).pathname.parent_path().filename().string() + std::string("-test/regression.log")); if( !boost::filesystem::exists(regressname) ) { s.out() << html::p() << "There are no regression logs available for the unit tests." << html::p::end; return; } xml_document<> *doc = s.loadxml(regressname); xml_node<> *root = doc->first_node(); if( root != NULL ) { std::set<std::string> headers; for( xml_node<> *testcase = root->first_node("testcase"); testcase != NULL; testcase = testcase->next_sibling("testcase") ) { xml_attribute<> *name = testcase->first_attribute("name"); assert( name != NULL ); headers.insert(name->value()); } typedef std::map<std::string,size_t> colMap; colMap colmap; size_t col = 0; s.out() << html::p(); s.out() << html::table() << std::endl; s.out() << html::tr(); s.out() << html::th() << html::th::end; for( std::set<std::string>::const_iterator header = headers.begin(); header != headers.end(); ++header ) { s.out() << html::th() << *header << html::th::end; colmap.insert(std::make_pair(*header,col++)); } s.out() << html::tr::end; std::string current; xml_node<>* cols[colmap.size()]; for( xml_node<> *test = root->first_node("testcase"); test != NULL; test = test->next_sibling("testcase") ) { xml_attribute<> *name = test->first_attribute("classname"); if( name->value() != current ) { if( !current.empty() ) { s.out() << html::tr() << html::td() << current << html::td::end; for( xml_node<> **c = cols; c != &cols[colmap.size()]; ++c ) { s.out() << html::td(); if( *c != NULL ) { xml_node<> *error = (*c)->first_node("error"); if( error ) { xml_attribute<> *type = error->first_attribute("type"); s.out() << type->value(); } else { s.out() << "pass"; } } s.out() << html::td::end; } s.out() << html::tr::end; } current = name->value(); memset(cols,0,sizeof(cols)); } name = test->first_attribute("name"); if( name != NULL ) { colMap::const_iterator found = colmap.find(name->value()); if( found != colmap.end() ) { cols[found->second] = test; } } } if( !current.empty() ) { s.out() << html::tr() << html::td() << current << html::td::end; for( xml_node<> **c = cols; c != &cols[colmap.size()]; ++c ) { s.out() << html::td(); if( *c != NULL ) { xml_node<> *error = (*c)->first_node("error"); if( error ) { xml_attribute<> *type = error->first_attribute("type"); s.out() << type->value(); } else { s.out() << "pass"; } } s.out() << html::td::end; } s.out() << html::tr::end; } #if 0 /* display the actual ouput as an expandable row. */ s.out() << html::tr(); memset(cols,0,sizeof(cols)); for( xml_node<> **c = cols; c != &cols[colmap.size() + 1]; ++c ) { assert( *c == NULL ); } for( xml_node<> *output = test->first_node("output"); output != NULL; output = output->next_sibling("output") ) { xml_attribute<> *name = output->first_attribute("name"); if( name != NULL ) { colMap::const_iterator found = colmap.find(name->value()); xml_node<> *data = output; if( output->first_node() != NULL ) { data = output->first_node(); } if( found != colmap.end() ) { cols[found->second] = data; } else { cols[0] = data; } } } for( xml_node<> **c = cols; c != &cols[colmap.size() + 1]; ++c ) { s.out() << html::td() << html::pre(); if( *c != NULL ) s.out() << (*c)->value(); s.out() << html::pre::end << html::td::end; } s.out() << html::tr::end; #endif s.out() << html::table::end << html::p::end; } } <commit_msg>can deal with a lot less formatting of log output (support plain text)<commit_after>/* Copyright (c) 2009-2012, 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 <boost/filesystem/fstream.hpp> #include <boost/property_tree/ptree.hpp> #include <boost/property_tree/xml_parser.hpp> #include "logview.hh" #include "markup.hh" #include "project.hh" /** Pages related to logs. Primary Author(s): Sebastien Mirolo <smirolo@fortylines.com> */ pathVariable indexFile("indexFile", "index file with projects dependencies information"); void logAddSessionVars( boost::program_options::options_description& all, boost::program_options::options_description& visible ) { using namespace boost::program_options; options_description localOptions("log"); localOptions.add(indexFile.option()); all.add(localOptions); visible.add(localOptions); } void logviewFetch( session& s, const boost::filesystem::path& pathname ) { using namespace RAPIDXML; using namespace boost::filesystem; /* remove the '/log' command tag and add the project dependency info (dws.xml). */ boost::filesystem::path indexFileName = indexFile.value(s); /* Each log contains the results gathered on a build server. We prefer to present one build results per column but need to write s.out() one table row at a time so we create the table entirely in memory before we display it. If we were to present build results per row, we would still need to preprocess the log files once but only to determine the column headers. */ static const boost::regex logPat("([^-]+)-.*\\.log"); /* build as column headers */ typedef std::set<path> colHeadersType; colHeadersType colHeaders; /* (project,(build,[status,exitCode])) */ typedef std::map<path,std::pair<std::string,int> > colType; typedef std::map<std::string,colType> tableType; tableType table; /* Populate the project names based on the projects specified in the index file. */ xml_document<> *doc = s.loadxml(indexFileName); if ( doc ) { /* Error loading the document, don't bother */ xml_node<> *root = doc->first_node(); if( root != NULL ) { for( xml_node<> *project = root->first_node("project"); project != NULL; project = project->next_sibling("project") ) { xml_attribute<> *name = project->first_attribute("name"); if( name != NULL ) { path repcontrol((srcTop.value(s) / path(name->value()))); if( boost::filesystem::exists(repcontrol) ) { table[name->value()] = colType(); } } } } path dirname(is_directory(pathname) ? pathname : siteTop.value(s) / "log"); std::string logBase; for( directory_iterator entry = directory_iterator(dirname); entry != directory_iterator(); ++entry ) { boost::smatch m; path fullpath = entry->path(); path filename = fullpath.filename(); if( boost::regex_search(filename.string(),m,logPat) ) { boost::filesystem::ifstream input; s.openfile(input, *entry); colHeaders.insert(filename); std::string name; while( !input.eof() ) { std::string line; getline(input, line); if( boost::regex_match(line, m, boost::regex("######## (\\S+)")) ) { name = m.str(1); } else if( boost::regex_match(line, m, boost::regex("\\S+: completed in (.*)")) ) { std::string status = m.str(1); if( table.find(name) != table.end() ) { table[name][filename] = std::make_pair(status, 0); } } else if( boost::regex_match(line, m, boost::regex("\\S+: error \\((\\d+)\\) after (.*)")) ) { std::string status = m.str(2); int exitCode = atoi(m.str(1).c_str()); if( table.find(name) != table.end() ) { table[name][filename] = std::make_pair(status, exitCode); } } } } } } s.out() << html::p() << "This build view page shows the stability " "of all projects at a glance. Each column represents a build log " "obtained by running the following command on a local machine:" << html::p::end; s.out() << html::pre() << html::a().href("/resources/dws") << "dws" << html::a::end << " build " << s.asAbsUrl(s.asUrl(indexFileName),"") << html::pre::end; s.out() << html::p() << "dws, the inter-project dependency tool " "generates a build log file with XML markups as part of building " "projects. That build log is then stamped with the local machine " "hostname and time before being uploaded onto the remote machine. " "This page presents all build logs currently available on the remote " "machine." << html::p::end; /* Display the table column headers. */ if( colHeaders.empty() ) { s.out() << html::pre() << "There are no logs available" << html::pre::end; } else { s.out() << html::table(); s.out() << html::tr(); s.out() << html::th() << html::th::end; for( colHeadersType::const_iterator col = colHeaders.begin(); col != colHeaders.end(); ++col ) { s.out() << html::th() << html::a().href((boost::filesystem::path("/log") / *col).string()) << *col << html::a::end << html::th::end; } s.out() << html::tr::end; /* Display one project per row, one build result per column. */ for( tableType::const_iterator row = table.begin(); row != table.end(); ++row ) { s.out() << html::tr(); s.out() << html::th() << projhref(s,row->first) << html::th::end; for( colHeadersType::const_iterator col = colHeaders.begin(); col != colHeaders.end(); ++col ) { colType::const_iterator value = row->second.find(*col); if( value != row->second.end() ) { if( value->second.second ) { s.out() << html::td().classref("positiveErrorCode"); } else { s.out() << html::td(); } s.out() << value->second.first; } else { s.out() << html::td(); } s.out() << html::td::end; } s.out() << html::tr::end; } s.out() << html::table::end; } /* footer */ s.out() << html::p() << "Each cell contains the time it took to make " "a specific project. If make exited with an error code before " "the completion of the last target, it is marked " << html::span().classref("positiveErrorCode") << "&nbsp;as such&nbsp;" << html::span::end << "." << html::p::end; s.out() << emptyParaHack; } void regressionsFetch( session& s, const boost::filesystem::path& pathname ) { using namespace RAPIDXML; using namespace boost::filesystem; boost::filesystem::path regressname = siteTop.value(s) / boost::filesystem::path("log/tests") / (document.value(s).pathname.parent_path().filename().string() + std::string("-test/regression.log")); if( !boost::filesystem::exists(regressname) ) { s.out() << html::p() << "There are no regression logs available for the unit tests." << html::p::end; return; } xml_document<> *doc = s.loadxml(regressname); xml_node<> *root = doc->first_node(); if( root != NULL ) { std::set<std::string> headers; for( xml_node<> *testcase = root->first_node("testcase"); testcase != NULL; testcase = testcase->next_sibling("testcase") ) { xml_attribute<> *name = testcase->first_attribute("name"); assert( name != NULL ); headers.insert(name->value()); } typedef std::map<std::string,size_t> colMap; colMap colmap; size_t col = 0; s.out() << html::p(); s.out() << html::table() << std::endl; s.out() << html::tr(); s.out() << html::th() << html::th::end; for( std::set<std::string>::const_iterator header = headers.begin(); header != headers.end(); ++header ) { s.out() << html::th() << *header << html::th::end; colmap.insert(std::make_pair(*header,col++)); } s.out() << html::tr::end; std::string current; xml_node<>* cols[colmap.size()]; for( xml_node<> *test = root->first_node("testcase"); test != NULL; test = test->next_sibling("testcase") ) { xml_attribute<> *name = test->first_attribute("classname"); if( name->value() != current ) { if( !current.empty() ) { s.out() << html::tr() << html::td() << current << html::td::end; for( xml_node<> **c = cols; c != &cols[colmap.size()]; ++c ) { s.out() << html::td(); if( *c != NULL ) { xml_node<> *error = (*c)->first_node("error"); if( error ) { xml_attribute<> *type = error->first_attribute("type"); s.out() << type->value(); } else { s.out() << "pass"; } } s.out() << html::td::end; } s.out() << html::tr::end; } current = name->value(); memset(cols,0,sizeof(cols)); } name = test->first_attribute("name"); if( name != NULL ) { colMap::const_iterator found = colmap.find(name->value()); if( found != colmap.end() ) { cols[found->second] = test; } } } if( !current.empty() ) { s.out() << html::tr() << html::td() << current << html::td::end; for( xml_node<> **c = cols; c != &cols[colmap.size()]; ++c ) { s.out() << html::td(); if( *c != NULL ) { xml_node<> *error = (*c)->first_node("error"); if( error ) { xml_attribute<> *type = error->first_attribute("type"); s.out() << type->value(); } else { s.out() << "pass"; } } s.out() << html::td::end; } s.out() << html::tr::end; } #if 0 /* display the actual ouput as an expandable row. */ s.out() << html::tr(); memset(cols,0,sizeof(cols)); for( xml_node<> **c = cols; c != &cols[colmap.size() + 1]; ++c ) { assert( *c == NULL ); } for( xml_node<> *output = test->first_node("output"); output != NULL; output = output->next_sibling("output") ) { xml_attribute<> *name = output->first_attribute("name"); if( name != NULL ) { colMap::const_iterator found = colmap.find(name->value()); xml_node<> *data = output; if( output->first_node() != NULL ) { data = output->first_node(); } if( found != colmap.end() ) { cols[found->second] = data; } else { cols[0] = data; } } } for( xml_node<> **c = cols; c != &cols[colmap.size() + 1]; ++c ) { s.out() << html::td() << html::pre(); if( *c != NULL ) s.out() << (*c)->value(); s.out() << html::pre::end << html::td::end; } s.out() << html::tr::end; #endif s.out() << html::table::end << html::p::end; } } <|endoftext|>
<commit_before>#include "libcassandra/connection_manager.h" #include "libcassandra/cassandra_client.h" using org::apache::cassandra::CassandraClient; namespace libcassandra { CassandraConnectionManager::CassandraConnectionManager() : port_(0), pool_size_(0), last_connect_(0) {} CassandraConnectionManager::~CassandraConnectionManager() { clear(); } time_t CassandraConnectionManager::createTimeStamp() const { struct timeval tv; gettimeofday(&tv, NULL); return tv.tv_sec * 1000000 + tv.tv_usec; } void CassandraConnectionManager::init( const std::string& host, int port, size_t pool_size) { host_ = host; port_ = port; pool_size_ = pool_size; reconnect(); } void CassandraConnectionManager::clear() { std::list<MyCassandraClient *>::iterator it = clients_.begin(); for (; it != clients_.end(); ++it) { delete *it; } clients_.clear(); } bool CassandraConnectionManager::reconnect() { time_t new_timestamp = createTimeStamp(); boost::unique_lock<boost::mutex> lock(mutex_); if (new_timestamp - last_connect_ < 10000000) return false; last_connect_ = new_timestamp; clear(); for (size_t i = 0; i < pool_size_; ++i) { clients_.push_back(new MyCassandraClient(host_, port_)); clients_.back()->open(); } return true; } MyCassandraClient * CassandraConnectionManager::borrowClient() { MyCassandraClient* client = NULL; boost::unique_lock<boost::mutex> lock(mutex_); while (clients_.empty()) { cond_.wait(lock); } client = clients_.front(); clients_.pop_front(); return client; } void CassandraConnectionManager::releaseClient(MyCassandraClient * client) { boost::unique_lock<boost::mutex> lock(mutex_); clients_.push_back(client); cond_.notify_one(); } } <commit_msg>fix CassandraConnectionManager::init()<commit_after>#include "libcassandra/connection_manager.h" #include "libcassandra/cassandra_client.h" using org::apache::cassandra::CassandraClient; namespace libcassandra { CassandraConnectionManager::CassandraConnectionManager() : port_(0), pool_size_(0), last_connect_(0) {} CassandraConnectionManager::~CassandraConnectionManager() { clear(); } time_t CassandraConnectionManager::createTimeStamp() const { struct timeval tv; gettimeofday(&tv, NULL); return tv.tv_sec * 1000000 + tv.tv_usec; } void CassandraConnectionManager::init( const std::string& host, int port, size_t pool_size) { host_ = host; port_ = port; pool_size_ = pool_size; last_connect_ = 0; reconnect(); } void CassandraConnectionManager::clear() { std::list<MyCassandraClient *>::iterator it = clients_.begin(); for (; it != clients_.end(); ++it) { delete *it; } clients_.clear(); } bool CassandraConnectionManager::reconnect() { time_t new_timestamp = createTimeStamp(); boost::unique_lock<boost::mutex> lock(mutex_); if (new_timestamp - last_connect_ < 10000000) return false; last_connect_ = new_timestamp; clear(); for (size_t i = 0; i < pool_size_; ++i) { clients_.push_back(new MyCassandraClient(host_, port_)); clients_.back()->open(); } return true; } MyCassandraClient * CassandraConnectionManager::borrowClient() { MyCassandraClient* client = NULL; boost::unique_lock<boost::mutex> lock(mutex_); while (clients_.empty()) { cond_.wait(lock); } client = clients_.front(); clients_.pop_front(); return client; } void CassandraConnectionManager::releaseClient(MyCassandraClient * client) { boost::unique_lock<boost::mutex> lock(mutex_); clients_.push_back(client); cond_.notify_one(); } } <|endoftext|>
<commit_before>/* * Copyright (c) 2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ #include <folly/Memory.h> #include <folly/DynamicConverter.h> #include <gtest/gtest.h> #include <gmock/gmock.h> #include <vector> #include <wangle/client/ssl/SSLSessionPersistentCache.h> #include <wangle/client/persistence/test/TestUtil.h> #include <wangle/client/ssl/test/TestUtil.h> using namespace testing; using namespace std::chrono; using namespace wangle; namespace wangle { class MockTimeUtil : public SSLSessionPersistentCache::TimeUtil { public: void advance(std::chrono::milliseconds ms) { t_ += ms; } std::chrono::time_point<std::chrono::system_clock> now() const override { return t_; } private: std::chrono::time_point<std::chrono::system_clock> t_; }; class SSLSessionPersistentCacheTest : public Test { public: SSLSessionPersistentCacheTest(): filename_(getPersistentCacheFilename()) {} void SetUp() override { for (auto& it : getSessions()) { sessions_.emplace_back(it.first, it.second); } sessionWithTicket_ = getSessionWithTicket(); sessions_.emplace_back(sessionWithTicket_.first, sessionWithTicket_.second); // Create the cache fresh for each test mockTimeUtil_ = new MockTimeUtil(); cache_.reset(new SSLSessionPersistentCache(filename_, 50, std::chrono::seconds(150))); cache_->setTimeUtil( std::unique_ptr<SSLSessionPersistentCache::TimeUtil>(mockTimeUtil_)); } void TearDown() override { for (const auto& it : sessions_) { SSL_SESSION_free(it.first); } sessions_.clear(); cache_.reset(); EXPECT_TRUE(unlink(filename_.c_str()) != -1); } protected: void verifyEntryInCache(const std::string& hostname, std::pair<SSL_SESSION*, size_t> session, bool inCache = true) { auto s = cache_->getSSLSession(hostname); if (inCache) { ASSERT_TRUE(s != nullptr); ASSERT_TRUE( isSameSession( session, std::make_pair(s.get(), session.second))); } else { ASSERT_FALSE(s); } } protected: std::string filename_; MockTimeUtil *mockTimeUtil_; std::unique_ptr<SSLSessionPersistentCache> cache_; std::vector<std::pair<SSL_SESSION*, size_t>> sessions_; std::pair<SSL_SESSION*, size_t> sessionWithTicket_; }; TEST_F(SSLSessionPersistentCacheTest, Basic) { for (size_t i = 0; i < sessions_.size(); ++i) { std::string hostname("host" + std::to_string(i)); // The session data does not exist before set. ASSERT_EQ(i, cache_->size()); ASSERT_FALSE(cache_->getSSLSession(hostname)); cache_->setSSLSession(hostname, createPersistentTestSession(sessions_[i])); // The session data should exist before set. ASSERT_EQ(i + 1, cache_->size()); verifyEntryInCache(hostname, sessions_[i]); } // The previously inserted sessions shouldn't have changed. Then remove them // one by one and verify they are not in cache after the removal. for (size_t i = 0; i < sessions_.size(); ++i) { std::string hostname("host" + std::to_string(i)); verifyEntryInCache(hostname, sessions_[i]); cache_->removeSSLSession(hostname); verifyEntryInCache(hostname, sessions_[i], false); } } TEST_F(SSLSessionPersistentCacheTest, BadSession) { std::string badHost = "bad"; // Insert bad session to an empty cache. cache_->setSSLSession(badHost, SSLSessionPtr(nullptr)); ASSERT_FALSE(cache_->getSSLSession(badHost)); ASSERT_EQ(0, cache_->size()); cache_->setSSLSession("host0", createPersistentTestSession(sessions_[0])); cache_->setSSLSession("host1", createPersistentTestSession(sessions_[1])); // Insert bad session to non-empty cache cache_->setSSLSession(badHost, SSLSessionPtr(nullptr)); ASSERT_FALSE(cache_->getSSLSession(badHost)); ASSERT_EQ(2, cache_->size()); verifyEntryInCache("host0", sessions_[0]); verifyEntryInCache("host1", sessions_[1]); } TEST_F(SSLSessionPersistentCacheTest, Overwrite) { cache_->setSSLSession("host0", createPersistentTestSession(sessions_[0])); cache_->setSSLSession("host1", createPersistentTestSession(sessions_[1])); { // Overwrite host1 with a nullptr, the cache shouldn't have changed. cache_->setSSLSession("host1", SSLSessionPtr(nullptr)); verifyEntryInCache("host0", sessions_[0]); verifyEntryInCache("host1", sessions_[1]); } { // Valid overwrite. cache_->setSSLSession("host1", createPersistentTestSession(sessions_[3])); verifyEntryInCache("host0", sessions_[0]); verifyEntryInCache("host1", sessions_[3]); } } TEST_F(SSLSessionPersistentCacheTest, SessionTicketTimeout) { std::string myhost("host3"); cache_->setSSLSession( myhost, createPersistentTestSession(sessionWithTicket_)); cache_->enableTicketLifetimeExpiration(true); // First verify element is successfully added to the cache auto s = cache_->getSSLSession(myhost); ASSERT_TRUE(s != nullptr); ASSERT_TRUE(s->tlsext_ticklen > 0); verifyEntryInCache(myhost, sessions_[3]); // Verify that if element is added to cache within // tlsext_tick_lifetime_hint seconds ago, we can retrieve it // advance current time by slightly less than tlsext_tick_lifetime_hint // Ticket should still be in cache long lifetime_seconds = s->tlsext_tick_lifetime_hint; mockTimeUtil_->advance( duration_cast<milliseconds>(seconds(lifetime_seconds - 10))); verifyEntryInCache(myhost, sessions_[3]); // advance current time to >= tlsext_tick_lifetime_hint // Ticket should not be in cache mockTimeUtil_->advance(duration_cast<milliseconds>(seconds(15))); ASSERT_FALSE(cache_->getSSLSession(myhost)); } } <commit_msg>Switch from std::to_string to folly::to<commit_after>/* * Copyright (c) 2016, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ #include <folly/Format.h> #include <folly/DynamicConverter.h> #include <folly/Memory.h> #include <gmock/gmock.h> #include <gtest/gtest.h> #include <vector> #include <wangle/client/ssl/SSLSessionPersistentCache.h> #include <wangle/client/persistence/test/TestUtil.h> #include <wangle/client/ssl/test/TestUtil.h> using namespace testing; using namespace std::chrono; using namespace wangle; namespace wangle { class MockTimeUtil : public SSLSessionPersistentCache::TimeUtil { public: void advance(std::chrono::milliseconds ms) { t_ += ms; } std::chrono::time_point<std::chrono::system_clock> now() const override { return t_; } private: std::chrono::time_point<std::chrono::system_clock> t_; }; class SSLSessionPersistentCacheTest : public Test { public: SSLSessionPersistentCacheTest(): filename_(getPersistentCacheFilename()) {} void SetUp() override { for (auto& it : getSessions()) { sessions_.emplace_back(it.first, it.second); } sessionWithTicket_ = getSessionWithTicket(); sessions_.emplace_back(sessionWithTicket_.first, sessionWithTicket_.second); // Create the cache fresh for each test mockTimeUtil_ = new MockTimeUtil(); cache_.reset(new SSLSessionPersistentCache(filename_, 50, std::chrono::seconds(150))); cache_->setTimeUtil( std::unique_ptr<SSLSessionPersistentCache::TimeUtil>(mockTimeUtil_)); } void TearDown() override { for (const auto& it : sessions_) { SSL_SESSION_free(it.first); } sessions_.clear(); cache_.reset(); EXPECT_TRUE(unlink(filename_.c_str()) != -1); } protected: void verifyEntryInCache(const std::string& hostname, std::pair<SSL_SESSION*, size_t> session, bool inCache = true) { auto s = cache_->getSSLSession(hostname); if (inCache) { ASSERT_TRUE(s != nullptr); ASSERT_TRUE( isSameSession( session, std::make_pair(s.get(), session.second))); } else { ASSERT_FALSE(s); } } protected: std::string filename_; MockTimeUtil *mockTimeUtil_; std::unique_ptr<SSLSessionPersistentCache> cache_; std::vector<std::pair<SSL_SESSION*, size_t>> sessions_; std::pair<SSL_SESSION*, size_t> sessionWithTicket_; }; TEST_F(SSLSessionPersistentCacheTest, Basic) { for (size_t i = 0; i < sessions_.size(); ++i) { auto hostname = folly::sformat("host{}", i); // The session data does not exist before set. ASSERT_EQ(i, cache_->size()); ASSERT_FALSE(cache_->getSSLSession(hostname)); cache_->setSSLSession(hostname, createPersistentTestSession(sessions_[i])); // The session data should exist before set. ASSERT_EQ(i + 1, cache_->size()); verifyEntryInCache(hostname, sessions_[i]); } // The previously inserted sessions shouldn't have changed. Then remove them // one by one and verify they are not in cache after the removal. for (size_t i = 0; i < sessions_.size(); ++i) { auto hostname = folly::sformat("host{}", i); verifyEntryInCache(hostname, sessions_[i]); cache_->removeSSLSession(hostname); verifyEntryInCache(hostname, sessions_[i], false); } } TEST_F(SSLSessionPersistentCacheTest, BadSession) { std::string badHost = "bad"; // Insert bad session to an empty cache. cache_->setSSLSession(badHost, SSLSessionPtr(nullptr)); ASSERT_FALSE(cache_->getSSLSession(badHost)); ASSERT_EQ(0, cache_->size()); cache_->setSSLSession("host0", createPersistentTestSession(sessions_[0])); cache_->setSSLSession("host1", createPersistentTestSession(sessions_[1])); // Insert bad session to non-empty cache cache_->setSSLSession(badHost, SSLSessionPtr(nullptr)); ASSERT_FALSE(cache_->getSSLSession(badHost)); ASSERT_EQ(2, cache_->size()); verifyEntryInCache("host0", sessions_[0]); verifyEntryInCache("host1", sessions_[1]); } TEST_F(SSLSessionPersistentCacheTest, Overwrite) { cache_->setSSLSession("host0", createPersistentTestSession(sessions_[0])); cache_->setSSLSession("host1", createPersistentTestSession(sessions_[1])); { // Overwrite host1 with a nullptr, the cache shouldn't have changed. cache_->setSSLSession("host1", SSLSessionPtr(nullptr)); verifyEntryInCache("host0", sessions_[0]); verifyEntryInCache("host1", sessions_[1]); } { // Valid overwrite. cache_->setSSLSession("host1", createPersistentTestSession(sessions_[3])); verifyEntryInCache("host0", sessions_[0]); verifyEntryInCache("host1", sessions_[3]); } } TEST_F(SSLSessionPersistentCacheTest, SessionTicketTimeout) { std::string myhost("host3"); cache_->setSSLSession( myhost, createPersistentTestSession(sessionWithTicket_)); cache_->enableTicketLifetimeExpiration(true); // First verify element is successfully added to the cache auto s = cache_->getSSLSession(myhost); ASSERT_TRUE(s != nullptr); ASSERT_TRUE(s->tlsext_ticklen > 0); verifyEntryInCache(myhost, sessions_[3]); // Verify that if element is added to cache within // tlsext_tick_lifetime_hint seconds ago, we can retrieve it // advance current time by slightly less than tlsext_tick_lifetime_hint // Ticket should still be in cache long lifetime_seconds = s->tlsext_tick_lifetime_hint; mockTimeUtil_->advance( duration_cast<milliseconds>(seconds(lifetime_seconds - 10))); verifyEntryInCache(myhost, sessions_[3]); // advance current time to >= tlsext_tick_lifetime_hint // Ticket should not be in cache mockTimeUtil_->advance(duration_cast<milliseconds>(seconds(15))); ASSERT_FALSE(cache_->getSSLSession(myhost)); } } <|endoftext|>
<commit_before>#include "fileinputstream.h" #include "stringterminatedsubstream.h" #include "xmlindexwriter.h" #include <iostream> using namespace Strigi; using namespace std; string readHeader(InputStream* f) { StringTerminatedSubStream header(f, "\r\n\r\n"); string h; const char* d; int32_t nread = header.read(d, 1000, 0); while (nread > 0) { h.append(d, nread); nread = header.read(d, 1000, 0); } return h; } /** * Start parsing a file. The stream must be positioned at the start of the file * header. **/ bool parseFile(StreamAnalyzer& sa, XmlIndexManager& manager, FileInputStream& f, const string& delim) { string header = readHeader(&f); string filename; const char* start = header.c_str(); start = strstr(start, "filename="); if (start) { start += 9; const char* end = 0; char c = *start; if (c == '\'' || c == '"') { start += 1; end = strchr(start, c); } if (end) { filename.assign(start, end-start); } else { filename.assign(start); } } // analyzer the stream StringTerminatedSubStream stream(&f, delim); if (filename.size()) { AnalysisResult result(filename, time(0), *manager.indexWriter(), sa); sa.analyze(result, &stream); } // read the rest of the stream const char* d; int32_t nread = stream.read(d, 1000, 0); while (nread > 0) { nread = stream.read(d, 1000, 0); } // check if this is the last file nread = f.read(d, 2, 2); return nread == 2 && *d == '\r' && d[1] == '\n'; } int main() { const TagMapping mapping(0); cout << "Content-Type:text/xml;charset=UTF-8\r\n\r\n" "<?xml version='1.0' encoding='UTF-8'?>\n<" << mapping.map("metadata") << ">\n"; // read from stdin FileInputStream f(stdin, ""); // read the first line const char* d; const int32_t maxlength = 1024; int32_t nread = f.read(d, maxlength, maxlength); f.reset(0); if (nread < 1) { cout << " <error>input too small</error>\n</" << mapping.map("metadata") << "\n" << flush; return 0; } // get out the delimiter const char* end = d + nread; const char* p = d; while (p < end-1 && *p != '\r') p++; if (*p != '\r' || p[1] != '\n') { cout << " <error>no delimiter line</error></" << mapping.map("metadata") << ">\n" << flush; return 0; } string delim(d, p-d); // skip the delimiter + '\r\n' f.reset(delim.length() + 2); // parse all files XmlIndexManager manager(cout, mapping); AnalyzerConfiguration ac; StreamAnalyzer sa(ac); sa.setIndexWriter(*manager.indexWriter()); while (parseFile(sa, manager, f, delim)); cout << "</" << mapping.map("metadata") << ">\n" << flush; return 0; } <commit_msg>add missing character<commit_after>#include "fileinputstream.h" #include "stringterminatedsubstream.h" #include "xmlindexwriter.h" #include <iostream> using namespace Strigi; using namespace std; string readHeader(InputStream* f) { StringTerminatedSubStream header(f, "\r\n\r\n"); string h; const char* d; int32_t nread = header.read(d, 1000, 0); while (nread > 0) { h.append(d, nread); nread = header.read(d, 1000, 0); } return h; } /** * Start parsing a file. The stream must be positioned at the start of the file * header. **/ bool parseFile(StreamAnalyzer& sa, XmlIndexManager& manager, FileInputStream& f, const string& delim) { string header = readHeader(&f); string filename; const char* start = header.c_str(); start = strstr(start, "filename="); if (start) { start += 9; const char* end = 0; char c = *start; if (c == '\'' || c == '"') { start += 1; end = strchr(start, c); } if (end) { filename.assign(start, end-start); } else { filename.assign(start); } } // analyzer the stream StringTerminatedSubStream stream(&f, delim); if (filename.size()) { AnalysisResult result(filename, time(0), *manager.indexWriter(), sa); sa.analyze(result, &stream); } // read the rest of the stream const char* d; int32_t nread = stream.read(d, 1000, 0); while (nread > 0) { nread = stream.read(d, 1000, 0); } // check if this is the last file nread = f.read(d, 2, 2); return nread == 2 && *d == '\r' && d[1] == '\n'; } int main() { const TagMapping mapping(0); cout << "Content-Type:text/xml;charset=UTF-8\r\n\r\n" "<?xml version='1.0' encoding='UTF-8'?>\n<" << mapping.map("metadata") << ">\n"; // read from stdin FileInputStream f(stdin, ""); // read the first line const char* d; const int32_t maxlength = 1024; int32_t nread = f.read(d, maxlength, maxlength); f.reset(0); if (nread < 1) { cout << " <error>input too small</error>\n</" << mapping.map("metadata") << ">\n" << flush; return 0; } // get out the delimiter const char* end = d + nread; const char* p = d; while (p < end-1 && *p != '\r') p++; if (*p != '\r' || p[1] != '\n') { cout << " <error>no delimiter line</error></" << mapping.map("metadata") << ">\n" << flush; return 0; } string delim(d, p-d); // skip the delimiter + '\r\n' f.reset(delim.length() + 2); // parse all files XmlIndexManager manager(cout, mapping); AnalyzerConfiguration ac; StreamAnalyzer sa(ac); sa.setIndexWriter(*manager.indexWriter()); while (parseFile(sa, manager, f, delim)); cout << "</" << mapping.map("metadata") << ">\n" << flush; return 0; } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: SharedConnection.cxx,v $ * * $Revision: 1.4 $ * * last change: $Author: rt $ $Date: 2005-09-08 10:29:59 $ * * 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 DBA_CORE_SHARED_CONNECTION_HXX #include "SharedConnection.hxx" #endif #ifndef _TOOLS_DEBUG_HXX #include <tools/debug.hxx> #endif namespace dbaccess { using namespace ::com::sun::star::uno; using namespace ::com::sun::star::lang; using namespace ::com::sun::star::sdbc; using namespace ::com::sun::star::container; // using namespace ::com::sun::star::reflection; using namespace connectivity; DBG_NAME(OSharedConnection) OSharedConnection::OSharedConnection(Reference< XAggregation >& _rxProxyConnection) : OSharedConnection_BASE(m_aMutex) { DBG_CTOR(OSharedConnection,NULL); setDelegation(_rxProxyConnection,m_refCount); } // ----------------------------------------------------------------------------- OSharedConnection::~OSharedConnection() { DBG_DTOR(OSharedConnection,NULL); } // ----------------------------------------------------------------------------- void SAL_CALL OSharedConnection::disposing(void) { OSharedConnection_BASE::disposing(); OConnectionWrapper::disposing(); } // ----------------------------------------------------------------------------- Reference< XStatement > SAL_CALL OSharedConnection::createStatement( ) throw(SQLException, RuntimeException) { ::osl::MutexGuard aGuard( m_aMutex ); checkDisposed(rBHelper.bDisposed); return m_xConnection->createStatement(); } // -------------------------------------------------------------------------------- Reference< XPreparedStatement > SAL_CALL OSharedConnection::prepareStatement( const ::rtl::OUString& sql ) throw(SQLException, RuntimeException) { ::osl::MutexGuard aGuard( m_aMutex ); checkDisposed(rBHelper.bDisposed); return m_xConnection->prepareStatement(sql); } // -------------------------------------------------------------------------------- Reference< XPreparedStatement > SAL_CALL OSharedConnection::prepareCall( const ::rtl::OUString& sql ) throw(SQLException, RuntimeException) { ::osl::MutexGuard aGuard( m_aMutex ); checkDisposed(rBHelper.bDisposed); return m_xConnection->prepareCall(sql); } // -------------------------------------------------------------------------------- ::rtl::OUString SAL_CALL OSharedConnection::nativeSQL( const ::rtl::OUString& sql ) throw(SQLException, RuntimeException) { ::osl::MutexGuard aGuard( m_aMutex ); checkDisposed(rBHelper.bDisposed); return m_xConnection->nativeSQL(sql); } // -------------------------------------------------------------------------------- sal_Bool SAL_CALL OSharedConnection::getAutoCommit( ) throw(SQLException, RuntimeException) { ::osl::MutexGuard aGuard( m_aMutex ); checkDisposed(rBHelper.bDisposed); return m_xConnection->getAutoCommit(); } // -------------------------------------------------------------------------------- void SAL_CALL OSharedConnection::commit( ) throw(SQLException, RuntimeException) { ::osl::MutexGuard aGuard( m_aMutex ); checkDisposed(rBHelper.bDisposed); m_xConnection->commit(); } // -------------------------------------------------------------------------------- void SAL_CALL OSharedConnection::rollback( ) throw(SQLException, RuntimeException) { ::osl::MutexGuard aGuard( m_aMutex ); checkDisposed(rBHelper.bDisposed); m_xConnection->rollback(); } // -------------------------------------------------------------------------------- sal_Bool SAL_CALL OSharedConnection::isClosed( ) throw(SQLException, RuntimeException) { ::osl::MutexGuard aGuard( m_aMutex ); return m_xConnection->isClosed(); } // -------------------------------------------------------------------------------- Reference< XDatabaseMetaData > SAL_CALL OSharedConnection::getMetaData( ) throw(SQLException, RuntimeException) { ::osl::MutexGuard aGuard( m_aMutex ); checkDisposed(rBHelper.bDisposed); return m_xConnection->getMetaData(); } // -------------------------------------------------------------------------------- sal_Bool SAL_CALL OSharedConnection::isReadOnly( ) throw(SQLException, RuntimeException) { ::osl::MutexGuard aGuard( m_aMutex ); checkDisposed(rBHelper.bDisposed); return m_xConnection->isReadOnly(); } // -------------------------------------------------------------------------------- ::rtl::OUString SAL_CALL OSharedConnection::getCatalog( ) throw(SQLException, RuntimeException) { ::osl::MutexGuard aGuard( m_aMutex ); checkDisposed(rBHelper.bDisposed); return m_xConnection->getCatalog(); } // -------------------------------------------------------------------------------- sal_Int32 SAL_CALL OSharedConnection::getTransactionIsolation( ) throw(SQLException, RuntimeException) { ::osl::MutexGuard aGuard( m_aMutex ); checkDisposed(rBHelper.bDisposed); return m_xConnection->getTransactionIsolation(); } // -------------------------------------------------------------------------------- Reference< ::com::sun::star::container::XNameAccess > SAL_CALL OSharedConnection::getTypeMap( ) throw(SQLException, RuntimeException) { ::osl::MutexGuard aGuard( m_aMutex ); checkDisposed(rBHelper.bDisposed); return m_xConnection->getTypeMap(); } // ----------------------------------------------------------------------------- //........................................................................ } // namespace dbaccess //........................................................................ <commit_msg>INTEGRATION: CWS pchfix02 (1.4.184); FILE MERGED 2006/09/01 17:24:08 kaib 1.4.184.1: #i68856# Added header markers and pch files<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: SharedConnection.cxx,v $ * * $Revision: 1.5 $ * * last change: $Author: obo $ $Date: 2006-09-17 06:38:04 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_dbaccess.hxx" #ifndef DBA_CORE_SHARED_CONNECTION_HXX #include "SharedConnection.hxx" #endif #ifndef _TOOLS_DEBUG_HXX #include <tools/debug.hxx> #endif namespace dbaccess { using namespace ::com::sun::star::uno; using namespace ::com::sun::star::lang; using namespace ::com::sun::star::sdbc; using namespace ::com::sun::star::container; // using namespace ::com::sun::star::reflection; using namespace connectivity; DBG_NAME(OSharedConnection) OSharedConnection::OSharedConnection(Reference< XAggregation >& _rxProxyConnection) : OSharedConnection_BASE(m_aMutex) { DBG_CTOR(OSharedConnection,NULL); setDelegation(_rxProxyConnection,m_refCount); } // ----------------------------------------------------------------------------- OSharedConnection::~OSharedConnection() { DBG_DTOR(OSharedConnection,NULL); } // ----------------------------------------------------------------------------- void SAL_CALL OSharedConnection::disposing(void) { OSharedConnection_BASE::disposing(); OConnectionWrapper::disposing(); } // ----------------------------------------------------------------------------- Reference< XStatement > SAL_CALL OSharedConnection::createStatement( ) throw(SQLException, RuntimeException) { ::osl::MutexGuard aGuard( m_aMutex ); checkDisposed(rBHelper.bDisposed); return m_xConnection->createStatement(); } // -------------------------------------------------------------------------------- Reference< XPreparedStatement > SAL_CALL OSharedConnection::prepareStatement( const ::rtl::OUString& sql ) throw(SQLException, RuntimeException) { ::osl::MutexGuard aGuard( m_aMutex ); checkDisposed(rBHelper.bDisposed); return m_xConnection->prepareStatement(sql); } // -------------------------------------------------------------------------------- Reference< XPreparedStatement > SAL_CALL OSharedConnection::prepareCall( const ::rtl::OUString& sql ) throw(SQLException, RuntimeException) { ::osl::MutexGuard aGuard( m_aMutex ); checkDisposed(rBHelper.bDisposed); return m_xConnection->prepareCall(sql); } // -------------------------------------------------------------------------------- ::rtl::OUString SAL_CALL OSharedConnection::nativeSQL( const ::rtl::OUString& sql ) throw(SQLException, RuntimeException) { ::osl::MutexGuard aGuard( m_aMutex ); checkDisposed(rBHelper.bDisposed); return m_xConnection->nativeSQL(sql); } // -------------------------------------------------------------------------------- sal_Bool SAL_CALL OSharedConnection::getAutoCommit( ) throw(SQLException, RuntimeException) { ::osl::MutexGuard aGuard( m_aMutex ); checkDisposed(rBHelper.bDisposed); return m_xConnection->getAutoCommit(); } // -------------------------------------------------------------------------------- void SAL_CALL OSharedConnection::commit( ) throw(SQLException, RuntimeException) { ::osl::MutexGuard aGuard( m_aMutex ); checkDisposed(rBHelper.bDisposed); m_xConnection->commit(); } // -------------------------------------------------------------------------------- void SAL_CALL OSharedConnection::rollback( ) throw(SQLException, RuntimeException) { ::osl::MutexGuard aGuard( m_aMutex ); checkDisposed(rBHelper.bDisposed); m_xConnection->rollback(); } // -------------------------------------------------------------------------------- sal_Bool SAL_CALL OSharedConnection::isClosed( ) throw(SQLException, RuntimeException) { ::osl::MutexGuard aGuard( m_aMutex ); return m_xConnection->isClosed(); } // -------------------------------------------------------------------------------- Reference< XDatabaseMetaData > SAL_CALL OSharedConnection::getMetaData( ) throw(SQLException, RuntimeException) { ::osl::MutexGuard aGuard( m_aMutex ); checkDisposed(rBHelper.bDisposed); return m_xConnection->getMetaData(); } // -------------------------------------------------------------------------------- sal_Bool SAL_CALL OSharedConnection::isReadOnly( ) throw(SQLException, RuntimeException) { ::osl::MutexGuard aGuard( m_aMutex ); checkDisposed(rBHelper.bDisposed); return m_xConnection->isReadOnly(); } // -------------------------------------------------------------------------------- ::rtl::OUString SAL_CALL OSharedConnection::getCatalog( ) throw(SQLException, RuntimeException) { ::osl::MutexGuard aGuard( m_aMutex ); checkDisposed(rBHelper.bDisposed); return m_xConnection->getCatalog(); } // -------------------------------------------------------------------------------- sal_Int32 SAL_CALL OSharedConnection::getTransactionIsolation( ) throw(SQLException, RuntimeException) { ::osl::MutexGuard aGuard( m_aMutex ); checkDisposed(rBHelper.bDisposed); return m_xConnection->getTransactionIsolation(); } // -------------------------------------------------------------------------------- Reference< ::com::sun::star::container::XNameAccess > SAL_CALL OSharedConnection::getTypeMap( ) throw(SQLException, RuntimeException) { ::osl::MutexGuard aGuard( m_aMutex ); checkDisposed(rBHelper.bDisposed); return m_xConnection->getTypeMap(); } // ----------------------------------------------------------------------------- //........................................................................ } // namespace dbaccess //........................................................................ <|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. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ // File : SolveInverseProblemWithTSVD.cc // Author : Jaume Coll-Font, Moritz Dannhauer, Ayla Khan, Dan White // Date : September 06th, 2017 (last update) #include <Core/Datatypes/String.h> #include <Core/Datatypes/Scalar.h> #include <Modules/Legacy/Inverse/SolveInverseProblemWithTikhonovTSVD.h> #include <Core/Algorithms/Base/AlgorithmBase.h> #include <Core/Algorithms/Legacy/Inverse/SolveInverseProblemWithTikhonovTSVD_impl.h> // #include <Core/Datatypes/MatrixTypeConversions.h> #include <Core/Algorithms/Legacy/Inverse/TikhonovAlgoAbstractBase.h> #include <Core/Datatypes/DenseColumnMatrix.h> #include <Core/Datatypes/Legacy/Field/Field.h> using namespace SCIRun; using namespace SCIRun::Core::Datatypes; using namespace SCIRun::Modules; using namespace SCIRun::Modules::Inverse; using namespace SCIRun::Dataflow::Networks; using namespace SCIRun::Core::Algorithms; using namespace SCIRun::Core::Algorithms::Inverse; // Module definitions. Sets the info into the staticInfo_ MODULE_INFO_DEF(SolveInverseProblemWithTikhonovTSVD, Inverse, SCIRun) // Constructor neeeds to have empty inputs and the parent's constructor has staticInfo_ as an input (adapted to thsi module in MODULE_INFO_DEF macro) // Constructor needs to initialize all input/output ports SolveInverseProblemWithTikhonovTSVD::SolveInverseProblemWithTikhonovTSVD() : Module(staticInfo_) { //inputs INITIALIZE_PORT(ForwardMatrix); INITIALIZE_PORT(WeightingInSourceSpace); INITIALIZE_PORT(MeasuredPotentials); INITIALIZE_PORT(WeightingInSensorSpace); INITIALIZE_PORT(matrixU); INITIALIZE_PORT(singularValues); INITIALIZE_PORT(matrixV); // outputs INITIALIZE_PORT(InverseSolution); INITIALIZE_PORT(RegularizationParameter); INITIALIZE_PORT(RegInverse); } void SolveInverseProblemWithTikhonovTSVD::setStateDefaults() { auto state = get_state(); state->setValue(Parameters::LambdaMin,1); state->setValue(Parameters::LambdaMax,100); state->setValue(Parameters::LambdaNum,100); state->setValue(Parameters::LambdaResolution,1); setStateStringFromAlgo(Parameters::TikhonovImplementation); setStateStringFromAlgoOption(Parameters::RegularizationMethod); setStateDoubleFromAlgo(Parameters::LambdaFromDirectEntry); //setStateDoubleFromAlgo(Parameters::LambdaMin); //setStateDoubleFromAlgo(Parameters::LambdaMax); //setStateIntFromAlgo(Parameters::LambdaNum); //setStateDoubleFromAlgo(Parameters::LambdaResolution); setStateDoubleFromAlgo(Parameters::LambdaSliderValue); setStateIntFromAlgo(Parameters::LambdaCorner); setStateStringFromAlgo(Parameters::LCurveText); } // execute function void SolveInverseProblemWithTikhonovTSVD::execute() { // load required inputs auto forward_matrix_h = getRequiredInput(ForwardMatrix); auto hMatrixMeasDat = getRequiredInput(MeasuredPotentials); // load regularization optional inputs auto hMatrixRegMat = getOptionalInput(WeightingInSourceSpace); auto hMatrixNoiseCov = getOptionalInput(WeightingInSensorSpace); // load SVD optional inputs auto hMatrixU = getOptionalInput(matrixU); auto hSingularValues = getOptionalInput(singularValues); auto hMatrixV = getOptionalInput(matrixV); if (needToExecute()) { // Obtain rank of forward matrix int rank; if ( hSingularValues ) { rank = (*hSingularValues)->nrows(); } else{ Eigen::FullPivLU<SCIRun::Core::Datatypes::DenseMatrix::EigenBase> lu_decomp(*forward_matrix_h); rank = lu_decomp.rank(); } //std::cout << "Computed rank: " << rank << std::endl; // set parameters auto state = get_state(); state->setValue( Parameters::TikhonovImplementation, std::string("TikhonovTSVD") ); setAlgoStringFromState(Parameters::TikhonovImplementation); setAlgoOptionFromState(Parameters::RegularizationMethod); setAlgoDoubleFromState(Parameters::LambdaFromDirectEntry); int LambdaMin= std::max(static_cast <int> (state->getValue(Parameters::LambdaMin).toDouble()),1); int LambdaMax= std::min(static_cast <int> (state->getValue(Parameters::LambdaMax).toDouble()),rank); if (LambdaMax<LambdaMin) { int tmp = LambdaMax; LambdaMax=LambdaMin; LambdaMin=LambdaMax; } int LambdaNum= LambdaMax - LambdaMin+1; state->setValue(Parameters::LambdaNum, LambdaNum); state->setValue(Parameters::LambdaMin, static_cast <double> (LambdaMin)); state->setValue(Parameters::LambdaMax, static_cast <double> (LambdaMax)); setAlgoDoubleFromState(Parameters::LambdaMin); setAlgoDoubleFromState(Parameters::LambdaMax); setAlgoIntFromState(Parameters::LambdaNum); setAlgoDoubleFromState(Parameters::LambdaSliderValue); setAlgoIntFromState(Parameters::LambdaCorner); setAlgoStringFromState(Parameters::LCurveText); // run auto output = algo().run( withInputData( (ForwardMatrix, forward_matrix_h) (MeasuredPotentials,hMatrixMeasDat) (MeasuredPotentials,hMatrixMeasDat) (WeightingInSourceSpace,optionalAlgoInput(hMatrixRegMat)) (WeightingInSensorSpace,optionalAlgoInput(hMatrixNoiseCov)) (matrixU,optionalAlgoInput(hMatrixU))(singularValues,optionalAlgoInput(hSingularValues)) (matrixV,optionalAlgoInput(hMatrixV))) ); // update L-curve /* NO EXISTE SolveInverseProblemWithTikhonovTSVD_impl::Input::lcurveGuiUpdate update = boost::bind(&SolveInverseProblemWithTikhonov::update_lcurve_gui, this, _1, _2, _3); */ // set outputs sendOutputFromAlgorithm(InverseSolution,output); sendOutputFromAlgorithm(RegularizationParameter,output); sendOutputFromAlgorithm(RegInverse,output); } } <commit_msg> a small bug<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. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ // File : SolveInverseProblemWithTSVD.cc // Author : Jaume Coll-Font, Moritz Dannhauer, Ayla Khan, Dan White // Date : September 06th, 2017 (last update) #include <Core/Datatypes/String.h> #include <Core/Datatypes/Scalar.h> #include <Modules/Legacy/Inverse/SolveInverseProblemWithTikhonovTSVD.h> #include <Core/Algorithms/Base/AlgorithmBase.h> #include <Core/Algorithms/Legacy/Inverse/SolveInverseProblemWithTikhonovTSVD_impl.h> // #include <Core/Datatypes/MatrixTypeConversions.h> #include <Core/Algorithms/Legacy/Inverse/TikhonovAlgoAbstractBase.h> #include <Core/Datatypes/DenseColumnMatrix.h> #include <Core/Datatypes/Legacy/Field/Field.h> using namespace SCIRun; using namespace SCIRun::Core::Datatypes; using namespace SCIRun::Modules; using namespace SCIRun::Modules::Inverse; using namespace SCIRun::Dataflow::Networks; using namespace SCIRun::Core::Algorithms; using namespace SCIRun::Core::Algorithms::Inverse; // Module definitions. Sets the info into the staticInfo_ MODULE_INFO_DEF(SolveInverseProblemWithTikhonovTSVD, Inverse, SCIRun) // Constructor neeeds to have empty inputs and the parent's constructor has staticInfo_ as an input (adapted to thsi module in MODULE_INFO_DEF macro) // Constructor needs to initialize all input/output ports SolveInverseProblemWithTikhonovTSVD::SolveInverseProblemWithTikhonovTSVD() : Module(staticInfo_) { //inputs INITIALIZE_PORT(ForwardMatrix); INITIALIZE_PORT(WeightingInSourceSpace); INITIALIZE_PORT(MeasuredPotentials); INITIALIZE_PORT(WeightingInSensorSpace); INITIALIZE_PORT(matrixU); INITIALIZE_PORT(singularValues); INITIALIZE_PORT(matrixV); // outputs INITIALIZE_PORT(InverseSolution); INITIALIZE_PORT(RegularizationParameter); INITIALIZE_PORT(RegInverse); } void SolveInverseProblemWithTikhonovTSVD::setStateDefaults() { auto state = get_state(); state->setValue(Parameters::LambdaMin,1); state->setValue(Parameters::LambdaMax,100); state->setValue(Parameters::LambdaNum,100); state->setValue(Parameters::LambdaResolution,1); setStateStringFromAlgo(Parameters::TikhonovImplementation); setStateStringFromAlgoOption(Parameters::RegularizationMethod); setStateDoubleFromAlgo(Parameters::LambdaFromDirectEntry); //setStateDoubleFromAlgo(Parameters::LambdaMin); //setStateDoubleFromAlgo(Parameters::LambdaMax); //setStateIntFromAlgo(Parameters::LambdaNum); //setStateDoubleFromAlgo(Parameters::LambdaResolution); setStateDoubleFromAlgo(Parameters::LambdaSliderValue); setStateIntFromAlgo(Parameters::LambdaCorner); setStateStringFromAlgo(Parameters::LCurveText); } // execute function void SolveInverseProblemWithTikhonovTSVD::execute() { // load required inputs auto forward_matrix_h = getRequiredInput(ForwardMatrix); auto hMatrixMeasDat = getRequiredInput(MeasuredPotentials); // load regularization optional inputs auto hMatrixRegMat = getOptionalInput(WeightingInSourceSpace); auto hMatrixNoiseCov = getOptionalInput(WeightingInSensorSpace); // load SVD optional inputs auto hMatrixU = getOptionalInput(matrixU); auto hSingularValues = getOptionalInput(singularValues); auto hMatrixV = getOptionalInput(matrixV); if (needToExecute()) { // Obtain rank of forward matrix int rank; if ( hSingularValues ) { rank = (*hSingularValues)->nrows(); } else{ Eigen::FullPivLU<SCIRun::Core::Datatypes::DenseMatrix::EigenBase> lu_decomp(*forward_matrix_h); rank = lu_decomp.rank(); } //std::cout << "Computed rank: " << rank << std::endl; // set parameters auto state = get_state(); state->setValue( Parameters::TikhonovImplementation, std::string("TikhonovTSVD") ); setAlgoStringFromState(Parameters::TikhonovImplementation); setAlgoOptionFromState(Parameters::RegularizationMethod); setAlgoDoubleFromState(Parameters::LambdaFromDirectEntry); int LambdaMin= std::max(static_cast <int> (state->getValue(Parameters::LambdaMin).toDouble()),1); int LambdaMax= std::min(static_cast <int> (state->getValue(Parameters::LambdaMax).toDouble()),rank); if (LambdaMax<LambdaMin) { int tmp = LambdaMax; LambdaMax=LambdaMin; LambdaMin=tmp; } int LambdaNum= LambdaMax - LambdaMin+1; state->setValue(Parameters::LambdaNum, LambdaNum); state->setValue(Parameters::LambdaMin, static_cast <double> (LambdaMin)); state->setValue(Parameters::LambdaMax, static_cast <double> (LambdaMax)); setAlgoDoubleFromState(Parameters::LambdaMin); setAlgoDoubleFromState(Parameters::LambdaMax); setAlgoIntFromState(Parameters::LambdaNum); setAlgoDoubleFromState(Parameters::LambdaSliderValue); setAlgoIntFromState(Parameters::LambdaCorner); setAlgoStringFromState(Parameters::LCurveText); // run auto output = algo().run( withInputData( (ForwardMatrix, forward_matrix_h) (MeasuredPotentials,hMatrixMeasDat) (MeasuredPotentials,hMatrixMeasDat) (WeightingInSourceSpace,optionalAlgoInput(hMatrixRegMat)) (WeightingInSensorSpace,optionalAlgoInput(hMatrixNoiseCov)) (matrixU,optionalAlgoInput(hMatrixU))(singularValues,optionalAlgoInput(hSingularValues)) (matrixV,optionalAlgoInput(hMatrixV))) ); // update L-curve /* NO EXISTE SolveInverseProblemWithTikhonovTSVD_impl::Input::lcurveGuiUpdate update = boost::bind(&SolveInverseProblemWithTikhonov::update_lcurve_gui, this, _1, _2, _3); */ // set outputs sendOutputFromAlgorithm(InverseSolution,output); sendOutputFromAlgorithm(RegularizationParameter,output); sendOutputFromAlgorithm(RegInverse,output); } } <|endoftext|>
<commit_before>#include "product_price_trend.h" #include <common/Utilities.h> #include <log-manager/PriceHistory.h> #include <document-manager/DocumentManager.h> #include <am/range/AmIterator.h> #include <libcassandra/util_functions.h> #include <boost/date_time/posix_time/posix_time.hpp> #include <boost/filesystem.hpp> #include <algorithm> using namespace std; using namespace libcassandra; using izenelib::util::UString; namespace sf1r { ProductPriceTrend::ProductPriceTrend( const boost::shared_ptr<DocumentManager>& document_manager, const CassandraStorageConfig& cassandraConfig, const string& collection_name, const string& data_dir, const vector<string>& group_prop_vec, const vector<uint32_t>& time_int_vec) : document_manager_(document_manager) , cassandraConfig_(cassandraConfig) , collection_name_(collection_name) , data_dir_(data_dir) , group_prop_vec_(group_prop_vec) , time_int_vec_(time_int_vec) , enable_tpc_(!group_prop_vec_.empty() && !time_int_vec_.empty()) { } ProductPriceTrend::~ProductPriceTrend() { for (TPCStorage::iterator it = tpc_storage_.begin(); it != tpc_storage_.end(); ++it) { for (uint32_t i = 0; i < time_int_vec_.size(); i++) delete it->second[i]; } } bool ProductPriceTrend::Init() { if (!cassandraConfig_.enable) return false; price_history_.reset(new PriceHistory(cassandraConfig_.keyspace)); price_history_->createColumnFamily(); if (!price_history_->is_enabled) return false; for (vector<string>::const_iterator it = group_prop_vec_.begin(); it != group_prop_vec_.end(); ++it) { vector<TPCBTree *>& prop_tpc = tpc_storage_[*it]; for (uint32_t i = 0; i < time_int_vec_.size(); i++) { string db_path = data_dir_ + "/" + *it + "." + boost::lexical_cast<string>(time_int_vec_[i]) + ".tpc"; prop_tpc.push_back(new TPCBTree(db_path)); if (!prop_tpc.back()->open()) { boost::filesystem::remove_all(db_path); prop_tpc.back()->open(); } } } price_history_buffer_.reserve(10000); return true; } bool ProductPriceTrend::Insert( const string& docid, const ProductPrice& price, time_t timestamp) { price_history_buffer_.push_back(PriceHistoryRow(docid)); price_history_buffer_.back().insert(timestamp, price); if (IsBufferFull_()) { return Flush(); } return true; } bool ProductPriceTrend::Update( const string& docid, const ProductPrice& price, time_t timestamp, map<string, string>& group_prop_map) { price_history_buffer_.push_back(PriceHistoryRow(docid)); price_history_buffer_.back().insert(timestamp, price); if (enable_tpc_ && !group_prop_map.empty() && price.value.first > 0) { PropItemType& prop_item = prop_map_[docid]; prop_item.first = price.value.first; prop_item.second.swap(group_prop_map); } if (IsBufferFull_()) { return Flush(); } return true; } bool ProductPriceTrend::IsBufferFull_() { return price_history_buffer_.size() >= 10000; } bool ProductPriceTrend::Flush() { bool ret = true; time_t now = Utilities::createTimeStamp(); if (!prop_map_.empty()) { for (uint32_t i = 0; i < time_int_vec_.size(); i++) { if (!UpdateTPC_(i, now)) ret = false; } prop_map_.clear(); } if (!price_history_->updateMultiRow(price_history_buffer_)) ret = false; price_history_buffer_.clear(); return ret; } bool ProductPriceTrend::CronJob() { if (!enable_tpc_) return true; //TODO return true; } bool ProductPriceTrend::UpdateTPC_(uint32_t time_int, time_t timestamp) { vector<string> key_list; Utilities::getKeyList(key_list, prop_map_); if (timestamp == -1) timestamp = Utilities::createTimeStamp(); timestamp -= 86400000000LL * time_int_vec_[time_int]; vector<PriceHistoryRow> row_list; if (!price_history_->getMultiSlice(row_list, key_list, serializeLong(timestamp), "", 1)) return false; map<string, map<string, TPCQueue> > tpc_cache; for (uint32_t i = 0; i < row_list.size(); i++) { const PropItemType& prop_item = prop_map_.find(row_list[i].getDocId())->second; const pair<time_t, ProductPrice>& price_record = *(row_list[i].getPriceHistory().begin()); const ProductPriceType& old_price = price_record.second.value.first; float price_cut = old_price == 0 ? 0 : 1 - prop_item.first / old_price; for (map<string, string>::const_iterator it = prop_item.second.begin(); it != prop_item.second.end(); ++it) { TPCQueue& tpc_queue = tpc_cache[it->first][it->second]; if (tpc_queue.empty()) { tpc_queue.reserve(1000); tpc_storage_[it->first][time_int]->get(it->second, tpc_queue); } if (tpc_queue.size() < 1000) { tpc_queue.push_back(make_pair(price_cut, row_list[i].getDocId())); push_heap(tpc_queue.begin(), tpc_queue.end(), rel_ops::operator> <TPCQueue::value_type>); } else if (price_cut > tpc_queue[0].first) { pop_heap(tpc_queue.begin(), tpc_queue.end(), rel_ops::operator> <TPCQueue::value_type>); tpc_queue.back().first = price_cut; tpc_queue.back().second = row_list[i].getDocId(); push_heap(tpc_queue.begin(), tpc_queue.end(), rel_ops::operator> <TPCQueue::value_type>); } } } for (map<string, map<string, TPCQueue> >::const_iterator it = tpc_cache.begin(); it != tpc_cache.end(); ++it) { TPCBTree* tpc_btree = tpc_storage_[it->first][time_int]; for (map<string, TPCQueue>::const_iterator mit = it->second.begin(); mit != it->second.end(); ++mit) { tpc_btree->update(mit->first, mit->second); } tpc_btree->flush(); } return true; } bool ProductPriceTrend::GetMultiPriceHistory( PriceHistoryList& history_list, const vector<string>& docid_list, time_t from_tt, time_t to_tt, string& error_msg) { string from_str(from_tt == -1 ? "" : serializeLong(from_tt)); string to_str(to_tt == -1 ? "" : serializeLong(to_tt)); vector<PriceHistoryRow> row_list; if (!price_history_->getMultiSlice(row_list, docid_list, from_str, to_str)) { error_msg = "Failed retrieving price histories from Cassandra"; return false; } history_list.reserve(history_list.size() + row_list.size()); for (vector<PriceHistoryRow>::const_iterator it = row_list.begin(); it != row_list.end(); ++it) { const PriceHistory::PriceHistoryType& price_history = it->getPriceHistory(); PriceHistoryItem history_item; history_item.reserve(price_history.size()); for (PriceHistory::PriceHistoryType::const_iterator hit = price_history.begin(); hit != price_history.end(); ++hit) { history_item.push_back(make_pair(string(), hit->second.value)); history_item.back().first = boost::posix_time::to_iso_string( boost::posix_time::from_time_t(hit->first / 1000000 - timezone) + boost::posix_time::microseconds(hit->first % 1000000)); } history_list.push_back(make_pair(it->getDocId(), PriceHistoryItem())); history_list.back().second.swap(history_item); } if (history_list.empty()) { error_msg = "Have not got any valid docid"; return false; } return true; } bool ProductPriceTrend::GetMultiPriceRange( PriceRangeList& range_list, const vector<string>& docid_list, time_t from_tt, time_t to_tt, string& error_msg) { string from_str(from_tt == -1 ? "" : serializeLong(from_tt)); string to_str(to_tt == -1 ? "" : serializeLong(to_tt)); vector<PriceHistoryRow> row_list; if (!price_history_->getMultiSlice(row_list, docid_list, from_str, to_str)) { error_msg = "Failed retrieving price histories from Cassandra"; return false; } range_list.reserve(range_list.size() + row_list.size()); for (vector<PriceHistoryRow>::const_iterator it = row_list.begin(); it != row_list.end(); ++it) { const PriceHistory::PriceHistoryType& price_history = it->getPriceHistory(); ProductPrice range_item; for (PriceHistory::PriceHistoryType::const_iterator hit = price_history.begin(); hit != price_history.end(); ++hit) { range_item += hit->second; } range_list.push_back(make_pair(it->getDocId(), range_item.value)); } if (range_list.empty()) { error_msg = "Have not got any valid docid"; return false; } return true; } bool ProductPriceTrend::GetTopPriceCutList( TPCQueue& tpc_queue, const string& prop_name, const string& prop_value, uint32_t days, uint32_t count, string& error_msg) { if (!enable_tpc_) { error_msg = "Top price-cut list is not enabled for this collection."; return false; } TPCStorage::const_iterator tpc_it = tpc_storage_.find(prop_name); if (tpc_it == tpc_storage_.end()) { error_msg = "Don't find data for this property name: " + prop_name; return false; } uint32_t time_int = 0; while (days > time_int_vec_[time_int++] && time_int < time_int_vec_.size() - 1); if (!tpc_it->second[time_int]->get(prop_value, tpc_queue)) { error_msg = "Don't find price-cut record for this property value: " + prop_value; return false; } sort_heap(tpc_queue.begin(), tpc_queue.end(), rel_ops::operator><TPCQueue::value_type>); if (tpc_queue.size() > count) tpc_queue.resize(count); return true; } bool ProductPriceTrend::MigratePriceHistory( const string& new_keyspace, const string& old_prefix, const string& new_prefix, string& error_msg) { if (new_keyspace == cassandraConfig_.keyspace) return true; vector<string> docid_list; docid_list.reserve(4000); boost::shared_ptr<PriceHistory> new_price_history(new PriceHistory(new_keyspace)); new_price_history->createColumnFamily(); for (uint32_t i = 1; i <= document_manager_->getMaxDocId(); i++) { Document doc; document_manager_->getDocument(i, doc); Document::property_const_iterator kit = doc.findProperty("DOCID"); if (kit == doc.propertyEnd()) continue; const UString& key = kit->second.get<UString>(); docid_list.push_back(string()); key.convertString(docid_list.back(), UString::UTF_8); if (!old_prefix.empty()) { docid_list.back() = old_prefix + "_" + docid_list.back(); } if (docid_list.size() == 4000) { vector<PriceHistoryRow> row_list; if (!price_history_->getMultiSlice(row_list, docid_list)) { error_msg = "Can't get price history from Cassandra."; return false; } if (!old_prefix.empty()) { std::size_t len = old_prefix.length() + 1; if (!new_prefix.empty()) { for (vector<PriceHistoryRow>::iterator it = row_list.begin(); it != row_list.end(); ++it) { it->setDocId(new_prefix + "_" + it->getDocId().substr(len)); } } else { for (vector<PriceHistoryRow>::iterator it = row_list.begin(); it != row_list.end(); ++it) { it->setDocId(it->getDocId().substr(len)); } } } else if (!new_prefix.empty()) { for (vector<PriceHistoryRow>::iterator it = row_list.begin(); it != row_list.end(); ++it) { it->setDocId(new_prefix + "_" + it->getDocId()); } } if (!new_price_history->updateMultiRow(row_list)) { error_msg = "Can't update price history to Cassandra."; return false; } docid_list.clear(); } } if (!docid_list.empty()) { vector<PriceHistoryRow> row_list; if (!price_history_->getMultiSlice(row_list, docid_list)) { error_msg = "Can't get price history from Cassandra."; return false; } if (!old_prefix.empty()) { std::size_t len = old_prefix.length() + 1; if (!new_prefix.empty()) { for (vector<PriceHistoryRow>::iterator it = row_list.begin(); it != row_list.end(); ++it) { it->setDocId(new_prefix + "_" + it->getDocId().substr(len)); } } else { for (vector<PriceHistoryRow>::iterator it = row_list.begin(); it != row_list.end(); ++it) { it->setDocId(it->getDocId().substr(len)); } } } else if (!new_prefix.empty()) { for (vector<PriceHistoryRow>::iterator it = row_list.begin(); it != row_list.end(); ++it) { it->setDocId(new_prefix + "_" + it->getDocId()); } } if (!new_price_history->updateMultiRow(row_list)) { error_msg = "Can't update price history to Cassandra."; return false; } } return true; } } <commit_msg>add console output<commit_after>#include "product_price_trend.h" #include <common/Utilities.h> #include <log-manager/PriceHistory.h> #include <document-manager/DocumentManager.h> #include <am/range/AmIterator.h> #include <libcassandra/util_functions.h> #include <boost/date_time/posix_time/posix_time.hpp> #include <boost/filesystem.hpp> #include <algorithm> using namespace std; using namespace libcassandra; using izenelib::util::UString; namespace sf1r { ProductPriceTrend::ProductPriceTrend( const boost::shared_ptr<DocumentManager>& document_manager, const CassandraStorageConfig& cassandraConfig, const string& collection_name, const string& data_dir, const vector<string>& group_prop_vec, const vector<uint32_t>& time_int_vec) : document_manager_(document_manager) , cassandraConfig_(cassandraConfig) , collection_name_(collection_name) , data_dir_(data_dir) , group_prop_vec_(group_prop_vec) , time_int_vec_(time_int_vec) , enable_tpc_(!group_prop_vec_.empty() && !time_int_vec_.empty()) { } ProductPriceTrend::~ProductPriceTrend() { for (TPCStorage::iterator it = tpc_storage_.begin(); it != tpc_storage_.end(); ++it) { for (uint32_t i = 0; i < time_int_vec_.size(); i++) delete it->second[i]; } } bool ProductPriceTrend::Init() { if (!cassandraConfig_.enable) return false; price_history_.reset(new PriceHistory(cassandraConfig_.keyspace)); price_history_->createColumnFamily(); if (!price_history_->is_enabled) return false; for (vector<string>::const_iterator it = group_prop_vec_.begin(); it != group_prop_vec_.end(); ++it) { vector<TPCBTree *>& prop_tpc = tpc_storage_[*it]; for (uint32_t i = 0; i < time_int_vec_.size(); i++) { string db_path = data_dir_ + "/" + *it + "." + boost::lexical_cast<string>(time_int_vec_[i]) + ".tpc"; prop_tpc.push_back(new TPCBTree(db_path)); if (!prop_tpc.back()->open()) { boost::filesystem::remove_all(db_path); prop_tpc.back()->open(); } } } price_history_buffer_.reserve(10000); return true; } bool ProductPriceTrend::Insert( const string& docid, const ProductPrice& price, time_t timestamp) { price_history_buffer_.push_back(PriceHistoryRow(docid)); price_history_buffer_.back().insert(timestamp, price); if (IsBufferFull_()) { return Flush(); } return true; } bool ProductPriceTrend::Update( const string& docid, const ProductPrice& price, time_t timestamp, map<string, string>& group_prop_map) { price_history_buffer_.push_back(PriceHistoryRow(docid)); price_history_buffer_.back().insert(timestamp, price); if (enable_tpc_ && !group_prop_map.empty() && price.value.first > 0) { PropItemType& prop_item = prop_map_[docid]; prop_item.first = price.value.first; prop_item.second.swap(group_prop_map); } if (IsBufferFull_()) { return Flush(); } return true; } bool ProductPriceTrend::IsBufferFull_() { return price_history_buffer_.size() >= 10000; } bool ProductPriceTrend::Flush() { bool ret = true; time_t now = Utilities::createTimeStamp(); if (!prop_map_.empty()) { for (uint32_t i = 0; i < time_int_vec_.size(); i++) { if (!UpdateTPC_(i, now)) ret = false; } prop_map_.clear(); } if (!price_history_->updateMultiRow(price_history_buffer_)) ret = false; price_history_buffer_.clear(); return ret; } bool ProductPriceTrend::CronJob() { if (!enable_tpc_) return true; //TODO return true; } bool ProductPriceTrend::UpdateTPC_(uint32_t time_int, time_t timestamp) { vector<string> key_list; Utilities::getKeyList(key_list, prop_map_); if (timestamp == -1) timestamp = Utilities::createTimeStamp(); timestamp -= 86400000000LL * time_int_vec_[time_int]; vector<PriceHistoryRow> row_list; if (!price_history_->getMultiSlice(row_list, key_list, serializeLong(timestamp), "", 1)) return false; map<string, map<string, TPCQueue> > tpc_cache; for (uint32_t i = 0; i < row_list.size(); i++) { const PropItemType& prop_item = prop_map_.find(row_list[i].getDocId())->second; const pair<time_t, ProductPrice>& price_record = *(row_list[i].getPriceHistory().begin()); const ProductPriceType& old_price = price_record.second.value.first; float price_cut = old_price == 0 ? 0 : 1 - prop_item.first / old_price; for (map<string, string>::const_iterator it = prop_item.second.begin(); it != prop_item.second.end(); ++it) { TPCQueue& tpc_queue = tpc_cache[it->first][it->second]; if (tpc_queue.empty()) { tpc_queue.reserve(1000); tpc_storage_[it->first][time_int]->get(it->second, tpc_queue); } if (tpc_queue.size() < 1000) { tpc_queue.push_back(make_pair(price_cut, row_list[i].getDocId())); push_heap(tpc_queue.begin(), tpc_queue.end(), rel_ops::operator> <TPCQueue::value_type>); } else if (price_cut > tpc_queue[0].first) { pop_heap(tpc_queue.begin(), tpc_queue.end(), rel_ops::operator> <TPCQueue::value_type>); tpc_queue.back().first = price_cut; tpc_queue.back().second = row_list[i].getDocId(); push_heap(tpc_queue.begin(), tpc_queue.end(), rel_ops::operator> <TPCQueue::value_type>); } } } for (map<string, map<string, TPCQueue> >::const_iterator it = tpc_cache.begin(); it != tpc_cache.end(); ++it) { TPCBTree* tpc_btree = tpc_storage_[it->first][time_int]; for (map<string, TPCQueue>::const_iterator mit = it->second.begin(); mit != it->second.end(); ++mit) { tpc_btree->update(mit->first, mit->second); } tpc_btree->flush(); } return true; } bool ProductPriceTrend::GetMultiPriceHistory( PriceHistoryList& history_list, const vector<string>& docid_list, time_t from_tt, time_t to_tt, string& error_msg) { string from_str(from_tt == -1 ? "" : serializeLong(from_tt)); string to_str(to_tt == -1 ? "" : serializeLong(to_tt)); vector<PriceHistoryRow> row_list; if (!price_history_->getMultiSlice(row_list, docid_list, from_str, to_str)) { error_msg = "Failed retrieving price histories from Cassandra"; return false; } history_list.reserve(history_list.size() + row_list.size()); for (vector<PriceHistoryRow>::const_iterator it = row_list.begin(); it != row_list.end(); ++it) { const PriceHistory::PriceHistoryType& price_history = it->getPriceHistory(); PriceHistoryItem history_item; history_item.reserve(price_history.size()); for (PriceHistory::PriceHistoryType::const_iterator hit = price_history.begin(); hit != price_history.end(); ++hit) { history_item.push_back(make_pair(string(), hit->second.value)); history_item.back().first = boost::posix_time::to_iso_string( boost::posix_time::from_time_t(hit->first / 1000000 - timezone) + boost::posix_time::microseconds(hit->first % 1000000)); } history_list.push_back(make_pair(it->getDocId(), PriceHistoryItem())); history_list.back().second.swap(history_item); } if (history_list.empty()) { error_msg = "Have not got any valid docid"; return false; } return true; } bool ProductPriceTrend::GetMultiPriceRange( PriceRangeList& range_list, const vector<string>& docid_list, time_t from_tt, time_t to_tt, string& error_msg) { string from_str(from_tt == -1 ? "" : serializeLong(from_tt)); string to_str(to_tt == -1 ? "" : serializeLong(to_tt)); vector<PriceHistoryRow> row_list; if (!price_history_->getMultiSlice(row_list, docid_list, from_str, to_str)) { error_msg = "Failed retrieving price histories from Cassandra"; return false; } range_list.reserve(range_list.size() + row_list.size()); for (vector<PriceHistoryRow>::const_iterator it = row_list.begin(); it != row_list.end(); ++it) { const PriceHistory::PriceHistoryType& price_history = it->getPriceHistory(); ProductPrice range_item; for (PriceHistory::PriceHistoryType::const_iterator hit = price_history.begin(); hit != price_history.end(); ++hit) { range_item += hit->second; } range_list.push_back(make_pair(it->getDocId(), range_item.value)); } if (range_list.empty()) { error_msg = "Have not got any valid docid"; return false; } return true; } bool ProductPriceTrend::GetTopPriceCutList( TPCQueue& tpc_queue, const string& prop_name, const string& prop_value, uint32_t days, uint32_t count, string& error_msg) { if (!enable_tpc_) { error_msg = "Top price-cut list is not enabled for this collection."; return false; } TPCStorage::const_iterator tpc_it = tpc_storage_.find(prop_name); if (tpc_it == tpc_storage_.end()) { error_msg = "Don't find data for this property name: " + prop_name; return false; } uint32_t time_int = 0; while (days > time_int_vec_[time_int++] && time_int < time_int_vec_.size() - 1); if (!tpc_it->second[time_int]->get(prop_value, tpc_queue)) { error_msg = "Don't find price-cut record for this property value: " + prop_value; return false; } sort_heap(tpc_queue.begin(), tpc_queue.end(), rel_ops::operator><TPCQueue::value_type>); if (tpc_queue.size() > count) tpc_queue.resize(count); return true; } bool ProductPriceTrend::MigratePriceHistory( const string& new_keyspace, const string& old_prefix, const string& new_prefix, string& error_msg) { if (new_keyspace == cassandraConfig_.keyspace) return true; vector<string> docid_list; docid_list.reserve(4000); boost::shared_ptr<PriceHistory> new_price_history(new PriceHistory(new_keyspace)); new_price_history->createColumnFamily(); uint32_t count = 0; for (uint32_t i = 1; i <= document_manager_->getMaxDocId(); i++) { Document doc; document_manager_->getDocument(i, doc); Document::property_const_iterator kit = doc.findProperty("DOCID"); if (kit == doc.propertyEnd()) continue; const UString& key = kit->second.get<UString>(); docid_list.push_back(string()); key.convertString(docid_list.back(), UString::UTF_8); if (!old_prefix.empty()) { docid_list.back() = old_prefix + "_" + docid_list.back(); } if (docid_list.size() == 4000) { vector<PriceHistoryRow> row_list; if (!price_history_->getMultiSlice(row_list, docid_list)) { error_msg = "Can't get price history from Cassandra."; return false; } if (!old_prefix.empty()) { std::size_t len = old_prefix.length() + 1; if (!new_prefix.empty()) { for (vector<PriceHistoryRow>::iterator it = row_list.begin(); it != row_list.end(); ++it) { it->setDocId(new_prefix + "_" + it->getDocId().substr(len)); } } else { for (vector<PriceHistoryRow>::iterator it = row_list.begin(); it != row_list.end(); ++it) { it->setDocId(it->getDocId().substr(len)); } } } else if (!new_prefix.empty()) { for (vector<PriceHistoryRow>::iterator it = row_list.begin(); it != row_list.end(); ++it) { it->setDocId(new_prefix + "_" + it->getDocId()); } } if (!new_price_history->updateMultiRow(row_list)) { error_msg = "Can't update price history to Cassandra."; return false; } docid_list.clear(); } if (++count % 100000 == 0) { LOG(INFO) << "Migrating price history: " << count; } } if (!docid_list.empty()) { vector<PriceHistoryRow> row_list; if (!price_history_->getMultiSlice(row_list, docid_list)) { error_msg = "Can't get price history from Cassandra."; return false; } if (!old_prefix.empty()) { std::size_t len = old_prefix.length() + 1; if (!new_prefix.empty()) { for (vector<PriceHistoryRow>::iterator it = row_list.begin(); it != row_list.end(); ++it) { it->setDocId(new_prefix + "_" + it->getDocId().substr(len)); } } else { for (vector<PriceHistoryRow>::iterator it = row_list.begin(); it != row_list.end(); ++it) { it->setDocId(it->getDocId().substr(len)); } } } else if (!new_prefix.empty()) { for (vector<PriceHistoryRow>::iterator it = row_list.begin(); it != row_list.end(); ++it) { it->setDocId(new_prefix + "_" + it->getDocId()); } } if (!new_price_history->updateMultiRow(row_list)) { error_msg = "Can't update price history to Cassandra."; return false; } } return true; } } <|endoftext|>
<commit_before>/* - Designer will publish: http://docs.ros.org/indigo/api/trajectory_msgs/html/msg/JointTrajectory.html - Designer will receive: (with root link as 0,0,0) http://docs.ros.org/indigo/api/sensor_msgs/html/msg/JointState.html */ #include <cstdlib> #include <string> #include <ros/ros.h> #include <lcm/lcm-cpp.hpp> #include "lcmtypes/drc/robot_plan_t.hpp" #include "lcmtypes/drc/plan_control_t.hpp" #include "lcmtypes/drc/affordance_collection_t.hpp" #include "lcmtypes/drc/robot_state_t.hpp" #include <trajectory_msgs/JointTrajectory.h> #include <ipab_msgs/PlannerRequest.h> #include <std_srvs/Empty.h> #include <std_msgs/String.h> #include "lcmtypes/ipab/exotica_planner_request_t.hpp" using namespace std; class LCM2ROS { public: LCM2ROS(boost::shared_ptr<lcm::LCM> &lcm_, ros::NodeHandle &nh_); ~LCM2ROS() { } private: boost::shared_ptr<lcm::LCM> lcm_; ros::NodeHandle nh_; ros::Publisher planner_request_pub_; ros::Publisher ik_request_pub_; void plannerRequestHandler(const lcm::ReceiveBuffer* rbuf, const std::string &channel, const ipab::exotica_planner_request_t* msg); void ikRequestHandler(const lcm::ReceiveBuffer* rbuf, const std::string &channel, const ipab::exotica_planner_request_t* msg); }; LCM2ROS::LCM2ROS(boost::shared_ptr<lcm::LCM> &lcm_, ros::NodeHandle &nh_) : lcm_(lcm_), nh_(nh_) { lcm_->subscribe("PLANNER_REQUEST", &LCM2ROS::plannerRequestHandler, this); planner_request_pub_ = nh_.advertise<ipab_msgs::PlannerRequest>("/exotica/planner_request", 10); lcm_->subscribe("IK_REQUEST", &LCM2ROS::ikRequestHandler, this); ik_request_pub_ = nh_.advertise<ipab_msgs::PlannerRequest>("/exotica/ik_request", 10); } void translatePlannerRequest(const ipab::exotica_planner_request_t* msg, ipab_msgs::PlannerRequest& m) { m.header.stamp = ros::Time().fromSec(msg->utime * 1E-6); m.poses = msg->poses; m.constraints = msg->constraints; m.affordances = msg->affordances; m.seed_pose = msg->seed_pose; m.nominal_pose = msg->nominal_pose; m.end_pose = msg->end_pose; m.joint_names = msg->joint_names; m.options = msg->options; } void LCM2ROS::plannerRequestHandler(const lcm::ReceiveBuffer* rbuf, const std::string &channel, const ipab::exotica_planner_request_t* msg) { ROS_ERROR("LCM2ROS got PLANNER_REQUEST"); ipab_msgs::PlannerRequest m; translatePlannerRequest(msg, m); planner_request_pub_.publish(m); } void LCM2ROS::ikRequestHandler(const lcm::ReceiveBuffer* rbuf, const std::string &channel, const ipab::exotica_planner_request_t* msg) { ROS_ERROR("LCM2ROS got IK_REQUEST"); ipab_msgs::PlannerRequest m; translatePlannerRequest(msg, m); ik_request_pub_.publish(m); } int main(int argc, char** argv) { ros::init(argc, argv, "lcm2ros", ros::init_options::NoSigintHandler); boost::shared_ptr<lcm::LCM> lcm(new lcm::LCM); if (!lcm->good()) { std::cerr << "ERROR: lcm is not good()" << std::endl; } ros::NodeHandle nh; LCM2ROS handlerObject(lcm, nh); cout << "\nlcm2ros translator ready\n"; ROS_ERROR("LCM2ROS Translator Ready"); while (0 == lcm->handle()) ; return 0; } <commit_msg>lcm2ros_exotica.cpp: roslint compatible<commit_after>// Copyright 2015 Vladimir Ivan /* - Designer will publish: http://docs.ros.org/indigo/api/trajectory_msgs/html/msg/JointTrajectory.html - Designer will receive: (with root link as 0,0,0) http://docs.ros.org/indigo/api/sensor_msgs/html/msg/JointState.html */ #include <cstdlib> #include <string> #include <ros/ros.h> #include <lcm/lcm-cpp.hpp> #include "lcmtypes/drc/robot_plan_t.hpp" #include "lcmtypes/drc/plan_control_t.hpp" #include "lcmtypes/drc/affordance_collection_t.hpp" #include "lcmtypes/drc/robot_state_t.hpp" #include <trajectory_msgs/JointTrajectory.h> #include <ipab_msgs/PlannerRequest.h> #include <std_srvs/Empty.h> #include <std_msgs/String.h> #include "lcmtypes/ipab/exotica_planner_request_t.hpp" class LCM2ROS { public: LCM2ROS(boost::shared_ptr<lcm::LCM> &lcm_, ros::NodeHandle &nh_); ~LCM2ROS() { } private: boost::shared_ptr<lcm::LCM> lcm_; ros::NodeHandle nh_; ros::Publisher planner_request_pub_; ros::Publisher ik_request_pub_; void plannerRequestHandler(const lcm::ReceiveBuffer* rbuf, const std::string &channel, const ipab::exotica_planner_request_t* msg); void ikRequestHandler(const lcm::ReceiveBuffer* rbuf, const std::string &channel, const ipab::exotica_planner_request_t* msg); }; LCM2ROS::LCM2ROS(boost::shared_ptr<lcm::LCM> &lcm_, ros::NodeHandle &nh_) { lcm_->subscribe("PLANNER_REQUEST", &LCM2ROS::plannerRequestHandler, this); planner_request_pub_ = nh_.advertise<ipab_msgs::PlannerRequest>("/exotica/planner_request", 10); lcm_->subscribe("IK_REQUEST", &LCM2ROS::ikRequestHandler, this); ik_request_pub_ = nh_.advertise<ipab_msgs::PlannerRequest>("/exotica/ik_request", 10); } void translatePlannerRequest(const ipab::exotica_planner_request_t* msg, ipab_msgs::PlannerRequest& m) { m.header.stamp = ros::Time().fromSec(msg->utime * 1E-6); m.poses = msg->poses; m.constraints = msg->constraints; m.affordances = msg->affordances; m.seed_pose = msg->seed_pose; m.nominal_pose = msg->nominal_pose; m.end_pose = msg->end_pose; m.joint_names = msg->joint_names; m.options = msg->options; } void LCM2ROS::plannerRequestHandler(const lcm::ReceiveBuffer* rbuf, const std::string &channel, const ipab::exotica_planner_request_t* msg) { ROS_ERROR("LCM2ROS got PLANNER_REQUEST"); ipab_msgs::PlannerRequest m; translatePlannerRequest(msg, m); planner_request_pub_.publish(m); } void LCM2ROS::ikRequestHandler(const lcm::ReceiveBuffer* rbuf, const std::string &channel, const ipab::exotica_planner_request_t* msg) { ROS_ERROR("LCM2ROS got IK_REQUEST"); ipab_msgs::PlannerRequest m; translatePlannerRequest(msg, m); ik_request_pub_.publish(m); } int main(int argc, char** argv) { ros::init(argc, argv, "lcm2ros", ros::init_options::NoSigintHandler); boost::shared_ptr<lcm::LCM> lcm(new lcm::LCM); if (!lcm->good()) { std::cerr << "ERROR: lcm is not good()" << std::endl; } ros::NodeHandle nh; LCM2ROS handlerObject(lcm, nh); ROS_INFO_STREAM("lcm2ros translator ready"); ROS_ERROR_STREAM("LCM2ROS Translator Ready"); while (0 == lcm->handle()) { } return 0; } <|endoftext|>
<commit_before><commit_msg>updted BIDMat_RAND.cpp<commit_after><|endoftext|>
<commit_before> // pcl_voxel_grid cloud1234.pcd cloud1234_down.pcd -leaf 0.01,0.01,0.01 #include <stdio.h> #include <iostream> #include <fstream> #include <string> #include <boost/shared_ptr.hpp> #include <boost/tokenizer.hpp> #include <boost/foreach.hpp> #include <lcm/lcm-cpp.hpp> #include "lcmtypes/drc_lcmtypes.hpp" #include "lcmtypes/bot_core.hpp" #include <Eigen/Dense> #include <Eigen/StdVector> #include <ConciseArgs> #include <pcl/filters/passthrough.h> #include <rgbd_simulation/rgbd_primitives.hpp> // to create basic meshes #include <pointcloud_tools/pointcloud_vis.hpp> #include <pointcloud_tools/filter_planes.hpp> using namespace Eigen; using namespace std; using namespace boost; class StatePub { public: StatePub(boost::shared_ptr<lcm::LCM> &lcm_, string pcd_filename_a, string pcd_filename_b); ~StatePub() {} boost::shared_ptr<lcm::LCM> lcm_; private: pcl::PolygonMesh::Ptr prim_mesh_ ; rgbd_primitives* prim_; pointcloud_vis* pc_vis_; pcl::PointCloud<pcl::PointXYZRGB>::Ptr readPCD(std::string filename); void boxFilter(pcl::PointCloud<pcl::PointXYZRGB>::Ptr cloud); void moveCloud(); Isometry3dTime null_poseT_; }; StatePub::StatePub(boost::shared_ptr<lcm::LCM> &lcm_, std::string pcd_filename_a, string pcd_filename_b): lcm_(lcm_), null_poseT_(0, Eigen::Isometry3d::Identity()){ pc_vis_ = new pointcloud_vis(lcm_->getUnderlyingLCM()); // obj: id name type reset // pts: id name type reset objcoll usergb rgb float colors_b[] ={1.0,0.0,1.0}; std::vector<float> colors_v; colors_v.assign(colors_b,colors_b+4*sizeof(float)); pc_vis_->obj_cfg_list.push_back( obj_cfg(349995,"Vehicle Tracker - Null",5,1) ); // 7 = full | 2 wireframe pc_vis_->obj_cfg_list.push_back( obj_cfg(1000,"Pose - Null",5,0) ); pc_vis_->ptcld_cfg_list.push_back( ptcld_cfg(1001,"Cloud - A" ,1,1, 1000,1, {0,0,1})); pc_vis_->ptcld_cfg_list.push_back( ptcld_cfg(1002,"Cloud - B" ,1,1, 1000,1, {1,0,0})); pc_vis_->ptcld_cfg_list.push_back( ptcld_cfg(1010,"Cloud - Filtered" ,1,1, 1000,1, {1,0,1})); pcl::PointCloud<pcl::PointXYZRGB>::Ptr cloud_a (new pcl::PointCloud<pcl::PointXYZRGB> ()); cloud_a = readPCD(pcd_filename_a); pcl::PointCloud<pcl::PointXYZRGB>::Ptr cloud_b (new pcl::PointCloud<pcl::PointXYZRGB> ()); cloud_b = readPCD(pcd_filename_b); pc_vis_->pose_to_lcm_from_list(1000, null_poseT_); pc_vis_->ptcld_to_lcm_from_list(1001, *cloud_a, null_poseT_.utime, null_poseT_.utime); pc_vis_->ptcld_to_lcm_from_list(1002, *cloud_b, null_poseT_.utime, null_poseT_.utime); *cloud_a += *cloud_b; boxFilter(cloud_a); //moveCloud(); pc_vis_->ptcld_to_lcm_from_list(1010, *cloud_a, null_poseT_.utime, null_poseT_.utime); pcl::io::savePCDFileASCII ("filtered_pcd.pcd", *cloud_a); } void StatePub::boxFilter(pcl::PointCloud<pcl::PointXYZRGB>::Ptr cloud){ pcl::PassThrough<pcl::PointXYZRGB> pass; pass.setInputCloud (cloud); pass.setFilterFieldName ("x"); pass.setFilterLimits (-1.5, 1.5); //pass.setFilterLimitsNegative (true); pass.filter (*cloud); pass.setInputCloud (cloud); pass.setFilterFieldName ("y"); pass.setFilterLimits (-1.5, 1.5); //pass.setFilterLimitsNegative (true); pass.filter (*cloud); // pass.setInputCloud (cloud); // pass.setFilterFieldName ("z"); // pass.setFilterLimits (1.035, 3.5); //pass.setFilterLimitsNegative (true); // pass.filter (*cloud); } void StatePub::moveCloud(){ /* Eigen::Isometry3f local_to_lidar; Eigen::Quaternionf quat = euler_to_quat_f( yaw*M_PI/180.0 ,0,0); //Eigen::Quaternionf quat = Eigen::Quaternionf(1,0,0,0); local_to_lidar.setIdentity(); // local_to_lidar.translation() << 1.2575, 1.3, 1.16; local_to_lidar.translation() << x,y,z;//0,0,-0.63; local_to_lidar.rotate(quat); pc_vis_->obj_cfg_list.push_back( obj_cfg(1005,"[BoxFilter] Pose to removed",5,0) ); Isometry3dTime local_to_lidarT = Isometry3dTime(0, local_to_lidar.cast<double>() ); pc_vis_->pose_to_lcm_from_list(1005, local_to_lidarT); Eigen::Isometry3f local_to_lidar_i = local_to_lidar.inverse(); Eigen::Quaternionf quat_i = Eigen::Quaternionf ( local_to_lidar_i.rotation() ); pcl::transformPointCloud (*_cloud, *_cloud, local_to_lidar_i.translation(), quat_i); // !! modifies lidar_cloud */ } pcl::PointCloud<pcl::PointXYZRGB>::Ptr StatePub::readPCD(std::string filename){ pcl::PointCloud<pcl::PointXYZRGB>::Ptr cloud (new pcl::PointCloud<pcl::PointXYZRGB> ()); if (pcl::io::loadPCDFile<pcl::PointXYZRGB> ( filename, *cloud) == -1){ // load the file cout << "couldnt read " << filename << "\n"; exit(-1); } cout << "read a cloud with " << cloud->points.size() << " points\n"; return cloud; } int main (int argc, char ** argv){ ConciseArgs parser(argc, argv, "lidar-passthrough"); string pcd_filename_a = "/home/mfallon/drc/software/perception/trackers/data/car_simulator/vehicle_200000000.pcd"; string pcd_filename_b = "/home/mfallon/drc/software/perception/trackers/data/car_simulator/chassis.txt"; parser.add(pcd_filename_a, "a", "pcd_filename_a", "pcd_filename_a"); parser.add(pcd_filename_b, "b", "pcd_filename_b", "pcd_filename_b"); parser.parse(); boost::shared_ptr<lcm::LCM> lcm(new lcm::LCM); if(!lcm->good()) return 1; StatePub app(lcm, pcd_filename_a, pcd_filename_b); cout << "StatePub ready"<< endl; // while(0 == lcm->handle()); return 0; } <commit_msg><commit_after>// 1. use drc-get-lidar-depth-image to create 4 point clouds: // - 4 views from 2.5m away, front back, left right // 2. merge them with this tool, one by one: // drc-car-clouds -a a.pcd -b b.pcd -----> ab.pcd clipped // 3. downsample with voxel grid: // pcl_voxel_grid cloud1234.pcd cloud1234_down.pcd -leaf 0.02,0.02,0.02 #include <stdio.h> #include <iostream> #include <fstream> #include <string> #include <boost/shared_ptr.hpp> #include <boost/tokenizer.hpp> #include <boost/foreach.hpp> #include <lcm/lcm-cpp.hpp> #include "lcmtypes/drc_lcmtypes.hpp" #include "lcmtypes/bot_core.hpp" #include <Eigen/Dense> #include <Eigen/StdVector> #include <ConciseArgs> #include <pcl/filters/passthrough.h> #include <rgbd_simulation/rgbd_primitives.hpp> // to create basic meshes #include <pointcloud_tools/pointcloud_vis.hpp> #include <pointcloud_tools/filter_planes.hpp> using namespace Eigen; using namespace std; using namespace boost; class StatePub { public: StatePub(boost::shared_ptr<lcm::LCM> &lcm_, string pcd_filename_a, string pcd_filename_b); ~StatePub() {} boost::shared_ptr<lcm::LCM> lcm_; private: pcl::PolygonMesh::Ptr prim_mesh_ ; rgbd_primitives* prim_; pointcloud_vis* pc_vis_; pcl::PointCloud<pcl::PointXYZRGB>::Ptr readPCD(std::string filename); void boxFilter(pcl::PointCloud<pcl::PointXYZRGB>::Ptr cloud); void moveCloud(); Isometry3dTime null_poseT_; }; StatePub::StatePub(boost::shared_ptr<lcm::LCM> &lcm_, std::string pcd_filename_a, string pcd_filename_b): lcm_(lcm_), null_poseT_(0, Eigen::Isometry3d::Identity()){ pc_vis_ = new pointcloud_vis(lcm_->getUnderlyingLCM()); // obj: id name type reset // pts: id name type reset objcoll usergb rgb float colors_b[] ={1.0,0.0,1.0}; std::vector<float> colors_v; colors_v.assign(colors_b,colors_b+4*sizeof(float)); pc_vis_->obj_cfg_list.push_back( obj_cfg(349995,"Vehicle Tracker - Null",5,1) ); // 7 = full | 2 wireframe pc_vis_->obj_cfg_list.push_back( obj_cfg(1000,"Pose - Null",5,0) ); pc_vis_->ptcld_cfg_list.push_back( ptcld_cfg(1001,"Cloud - A" ,1,1, 1000,1, {0,0,1})); pc_vis_->ptcld_cfg_list.push_back( ptcld_cfg(1002,"Cloud - B" ,1,1, 1000,1, {1,0,0})); pc_vis_->ptcld_cfg_list.push_back( ptcld_cfg(1010,"Cloud - Filtered" ,1,1, 1000,1, {1,0,1})); pcl::PointCloud<pcl::PointXYZRGB>::Ptr cloud_a (new pcl::PointCloud<pcl::PointXYZRGB> ()); cloud_a = readPCD(pcd_filename_a); pcl::PointCloud<pcl::PointXYZRGB>::Ptr cloud_b (new pcl::PointCloud<pcl::PointXYZRGB> ()); cloud_b = readPCD(pcd_filename_b); pc_vis_->pose_to_lcm_from_list(1000, null_poseT_); pc_vis_->ptcld_to_lcm_from_list(1001, *cloud_a, null_poseT_.utime, null_poseT_.utime); pc_vis_->ptcld_to_lcm_from_list(1002, *cloud_b, null_poseT_.utime, null_poseT_.utime); *cloud_a += *cloud_b; boxFilter(cloud_a); //moveCloud(); pc_vis_->ptcld_to_lcm_from_list(1010, *cloud_a, null_poseT_.utime, null_poseT_.utime); pcl::io::savePCDFileASCII ("filtered_pcd.pcd", *cloud_a); } void StatePub::boxFilter(pcl::PointCloud<pcl::PointXYZRGB>::Ptr cloud){ pcl::PassThrough<pcl::PointXYZRGB> pass; pass.setInputCloud (cloud); pass.setFilterFieldName ("x"); pass.setFilterLimits (-1.5, 1.5); //pass.setFilterLimitsNegative (true); pass.filter (*cloud); pass.setInputCloud (cloud); pass.setFilterFieldName ("y"); pass.setFilterLimits (-1.5, 1.5); //pass.setFilterLimitsNegative (true); pass.filter (*cloud); // pass.setInputCloud (cloud); // pass.setFilterFieldName ("z"); // pass.setFilterLimits (1.035, 3.5); //pass.setFilterLimitsNegative (true); // pass.filter (*cloud); } void StatePub::moveCloud(){ /* Eigen::Isometry3f local_to_lidar; Eigen::Quaternionf quat = euler_to_quat_f( yaw*M_PI/180.0 ,0,0); //Eigen::Quaternionf quat = Eigen::Quaternionf(1,0,0,0); local_to_lidar.setIdentity(); // local_to_lidar.translation() << 1.2575, 1.3, 1.16; local_to_lidar.translation() << x,y,z;//0,0,-0.63; local_to_lidar.rotate(quat); pc_vis_->obj_cfg_list.push_back( obj_cfg(1005,"[BoxFilter] Pose to removed",5,0) ); Isometry3dTime local_to_lidarT = Isometry3dTime(0, local_to_lidar.cast<double>() ); pc_vis_->pose_to_lcm_from_list(1005, local_to_lidarT); Eigen::Isometry3f local_to_lidar_i = local_to_lidar.inverse(); Eigen::Quaternionf quat_i = Eigen::Quaternionf ( local_to_lidar_i.rotation() ); pcl::transformPointCloud (*_cloud, *_cloud, local_to_lidar_i.translation(), quat_i); // !! modifies lidar_cloud */ } pcl::PointCloud<pcl::PointXYZRGB>::Ptr StatePub::readPCD(std::string filename){ pcl::PointCloud<pcl::PointXYZRGB>::Ptr cloud (new pcl::PointCloud<pcl::PointXYZRGB> ()); if (pcl::io::loadPCDFile<pcl::PointXYZRGB> ( filename, *cloud) == -1){ // load the file cout << "couldnt read " << filename << "\n"; exit(-1); } cout << "read a cloud with " << cloud->points.size() << " points\n"; return cloud; } int main (int argc, char ** argv){ ConciseArgs parser(argc, argv, "lidar-passthrough"); string pcd_filename_a = "/home/mfallon/drc/software/perception/trackers/data/car_simulator/vehicle_200000000.pcd"; string pcd_filename_b = "/home/mfallon/drc/software/perception/trackers/data/car_simulator/chassis.txt"; parser.add(pcd_filename_a, "a", "pcd_filename_a", "pcd_filename_a"); parser.add(pcd_filename_b, "b", "pcd_filename_b", "pcd_filename_b"); parser.parse(); boost::shared_ptr<lcm::LCM> lcm(new lcm::LCM); if(!lcm->good()) return 1; StatePub app(lcm, pcd_filename_a, pcd_filename_b); cout << "StatePub ready"<< endl; // while(0 == lcm->handle()); return 0; } <|endoftext|>
<commit_before>#include <bits/stdc++.h> #define dd(x) cout << #x << ": " << x << endl; #define optimize_ios ios_base::sync_with_stdio(0);cin.tie(0); #define MAXN 1000002 #define MOD 21092013 #define INF -1 using namespace std; typedef stack<bool> stackbl; typedef stack<int> stacki; string S, T; stackbl Tree; stacki MovsLater; bool direction; int DP[MAXN]; int lastOccurrence[3]; inline int getIdx(char c) { return c == 'L' ? 0 : (c == 'R' ? 1 : 2); } inline char toChar(bool idx) { return idx ? 'R' : 'L'; } inline bool isMovDown(char c) { return c == 'L' or c == 'R'; } bool dontHaveMovUp() { int i, n = T.size(); bool res = true; for (i = 0; i < n; ++i) { if (!isMovDown(T[i])) { res = false; } else { direction = getIdx(T[i]); if (! res) { return res; break; } } } return res; } inline int modMult(int a, int b) { return ((a % MOD) * (b % MOD)) % MOD; } inline int modPositive(int n) { return ((n % MOD) + MOD) % MOD; } inline int modSub(int a, int b) { return ((a % MOD) - (b % MOD)) % MOD; } inline int modSum(int a, int b) { return ((a % MOD) + (b % MOD)) % MOD; } int countDistinctSubsequences() { int i, n, charIdx; n = T.size(), DP[0] = 1; for (i = 1; i <= n; ++i) { DP[i] = modMult(2, DP[i - 1]); charIdx = getIdx(T[i - 1]); if (lastOccurrence[charIdx] > 0) { DP[i] = modPositive(modSub(DP[i], DP[lastOccurrence[charIdx] - 1])); } lastOccurrence[charIdx] = i; } return DP[n]; } void getTree() { int i, n = S.size(); for (i = 0; i < n; ++i) { if (isMovDown(S[i])) { Tree.push(getIdx(S[i]) ^ 1); } else if (! Tree.empty()) { Tree.pop(); } } } void findMovsLater() { int i, n = T.size(), movs = 0; for (i = n - 1; i >= 0; --i) { if (isMovDown(T[i])) { ++movs; } else { MovsLater.push(movs); } } MovsLater.push(movs); } int countDistinctNodes() { int movs, res = 0, i = 0, parentDirection; while ((! MovsLater.empty()) and (! Tree.empty())) { movs = MovsLater.top(); MovsLater.pop(); if (i == 0) { res = modSum(res, modSum(movs, 1)); } else { parentDirection = Tree.top(); Tree.pop(); if (parentDirection == direction) { res = modSum(res, movs); } res = modSum(res, 1); } ++i; } return res; } int main() { optimize_ios cin >> S >> T; getTree(); if (dontHaveMovUp()) { cout << countDistinctSubsequences() << '\n'; } else { findMovsLater(); cout << countDistinctNodes() << '\n'; } return 0; } <commit_msg>omegaUp - TeamSkynet-Training-01 - Árbol Binario de Turing - Subtask 4 of 5<commit_after>#include <bits/stdc++.h> #define dd(x) cout << #x << ": " << x << endl; #define optimize_ios ios_base::sync_with_stdio(0);cin.tie(0); #define MAXN 1000002 #define MOD 21092013 #define PB push_back #define MP make_pair #define NODE first.first #define PARENT first.second #define LEFT second.first #define RIGHT second.second #define ALL(x) x.begin(), x.end() #define INF -1 #define L 0 #define R 1 using namespace std; typedef stack<bool> stackbl; typedef stack<int> stacki; typedef vector<bool> vectorbl; string S, T; stackbl ParentDirections; vectorbl ChildrenDirections; stacki MovsLater; bool direction; int DP[MAXN]; int lastOccurrence[3]; inline int getIdx(char c) { return c == 'L' ? 0 : (c == 'R' ? 1 : 2); } inline char toChar(bool idx) { return idx ? 'R' : 'L'; } inline bool isMovDown(char c) { return c == 'L' or c == 'R'; } bool dontHaveMovUp() { int i, n = T.size(); bool res = true; for (i = 0; i < n; ++i) { if (!isMovDown(T[i])) { res = false; } else { direction = getIdx(T[i]); if (! res) { return res; break; } } } return res; } inline int modMult(int a, int b) { return ((a % MOD) * (b % MOD)) % MOD; } inline int modPositive(int n) { return ((n % MOD) + MOD) % MOD; } inline int modSub(int a, int b) { return ((a % MOD) - (b % MOD)) % MOD; } inline int modSum(int a, int b) { return ((a % MOD) + (b % MOD)) % MOD; } int countDistinctSubsequences() { int i, n, charIdx; n = T.size(), DP[0] = 1; for (i = 1; i <= n; ++i) { DP[i] = modMult(2, DP[i - 1]); charIdx = getIdx(T[i - 1]); if (lastOccurrence[charIdx] > 0) { DP[i] = modPositive(modSub(DP[i], DP[lastOccurrence[charIdx] - 1])); } lastOccurrence[charIdx] = i; } return DP[n]; } void getFinalDirections() { int i, n = S.size(); for (i = 0; i < n; ++i) { if (isMovDown(S[i])) { ParentDirections.push(getIdx(S[i]) ^ 1); } else if (! ParentDirections.empty()) { ParentDirections.pop(); } } stackbl tmp(ParentDirections); while (!tmp.empty()) { ChildrenDirections.PB(tmp.top() ^ 1); tmp.pop(); } reverse(ALL(ChildrenDirections)); } void findMovsLater() { int i, n = T.size(), movs = 0; for (i = n - 1; i >= 0; --i) { if (isMovDown(T[i])) { ++movs; } else { MovsLater.push(movs); } } MovsLater.push(movs); } int countDistinctNodes() { int movs, res = 0, i = 0, parentDirection; while ((! MovsLater.empty()) and (! ParentDirections.empty())) { movs = MovsLater.top(); MovsLater.pop(); if (i == 0) { res = modSum(res, modSum(movs, 1)); } else { parentDirection = ParentDirections.top(); ParentDirections.pop(); if (parentDirection == direction) { res = modSum(res, movs); } res = modSum(res, 1); } ++i; } return res; } typedef pair<int, int> Pair; typedef pair<Pair, Pair> Tern; vector<Tern> BT; vector<string> Subsequences; set<int> ans; int createNode(int val) { int idx = BT.size(); BT.PB(MP(MP(val, idx), MP(INF, INF))); return idx; } int generateTree(int node, int level) { if (level >= ChildrenDirections.size()) { return node; } bool direction = ChildrenDirections[level]; if (direction == L) { int leftIdx = createNode(level + 1); BT[leftIdx].PARENT = node; BT[node].LEFT = leftIdx; return generateTree(leftIdx, level + 1); } else { int rightIdx = createNode(level + 1); BT[rightIdx].PARENT = node; BT[node].RIGHT = rightIdx; return generateTree(rightIdx, level + 1); } } void printTree() { int i, n = BT.size(); cout << "Tree: " << endl; for (i = 0; i < n; ++i) cout << setw(2) << BT[i].NODE << " "; cout << endl; for (i = 0; i < n; ++i) cout << setw(2) << BT[i].PARENT << " "; cout << endl; for (i = 0; i < n; ++i) cout << setw(2) << BT[i].LEFT << " "; cout << endl; for (i = 0; i < n; ++i) cout << setw(2) << BT[i].RIGHT << " "; cout << endl; } void generateAllSubsequences() { int i, j, n = T.size(), iter = 0; string s; set<string> heap; //cout << "All Subs: " << endl; for (i = 0; i < (1 << n); ++i) { s = ""; for (j = 0; j < n; ++j) { if ((i & (1 << j)) > 0) { s += T[j]; } } heap.insert(s); //cout << ">" << s << endl; } //cout << endl; for (set<string>::iterator it = heap.begin(); it != heap.end(); ++it) { Subsequences.PB((*it)); } } void travel(int node, int subsequenceIdx, int level) { if (node != INF) { ans.insert(node); } if (level >= Subsequences[subsequenceIdx].size()) { return; } char c = Subsequences[subsequenceIdx][level]; //cout << c << " "; if (c == 'U') { travel(BT[node].PARENT, subsequenceIdx, level + 1); } else if (c == 'L') { if (BT[node].LEFT == INF) { int leftIdx = createNode(BT.size()); BT[leftIdx].PARENT = node; BT[node].LEFT = leftIdx; } travel(BT[node].LEFT, subsequenceIdx, level + 1); } else { if (BT[node].RIGHT == INF) { int rightIdx = createNode(BT.size()); BT[rightIdx].PARENT = node; BT[node].RIGHT = rightIdx; } travel(BT[node].RIGHT, subsequenceIdx, level + 1); } } void findDistinctNodes(int currentNode) { int i, n = Subsequences.size(); for (i = 0; i < n; ++i) { //cout << ">"; travel(currentNode, i, 0); //cout << endl; } } int main() { optimize_ios cin >> S >> T; getFinalDirections(); if (T.size() <= 20) { int root = createNode(0); int currentNode = generateTree(root, 0); //dd(currentNode); //printTree(); generateAllSubsequences(); findDistinctNodes(currentNode); /*printTree(); cout << "Different Nodes: " << endl; for (set<int>::iterator it = ans.begin(); it != ans.end(); ++it) { cout << (*it) << " "; } cout << endl;*/ cout << ans.size() << '\n'; } else if (dontHaveMovUp()) { cout << countDistinctSubsequences() << '\n'; } else { findMovsLater(); cout << countDistinctNodes() << '\n'; } return 0; } <|endoftext|>
<commit_before>/* dtkDistributedMapper.cpp --- * * Author: Thibaud Kloczko * Created: 2013 Thu Feb 7 10:55:57 (+0100) */ /* Commentary: * */ /* Change log: * */ #include "dtkDistributedMapper.h" #include <QtCore> // ///////////////////////////////////////////////////////////////// // dtkDistributedMapperPrivate interface // ///////////////////////////////////////////////////////////////// class dtkDistributedMapperPrivate { public: dtkDistributedMapperPrivate(void) {;} ~dtkDistributedMapperPrivate(void) {;} public: void setMapping(const qlonglong& id_number, const qlonglong& pu_number); void initMap(const qlonglong& map_size, const qlonglong& pu_size); void setMap(const qlonglong& local_map_size, const qlonglong& pu_id); public: qlonglong localToGlobal(const qlonglong& local_id, const qlonglong& pu_id) const; qlonglong globalToLocal(const qlonglong& global_id) const; qlonglong count(const qlonglong& pu_id) const; qlonglong owner(const qlonglong& global_id) const; QVector<qlonglong> readers(const qlonglong& global_id) const; public: qlonglong id_count; qlonglong pu_count; qlonglong step; QVector<qlonglong> map; }; // ///////////////////////////////////////////////////////////////// // dtkDistributedMapperPrivate implementation // ///////////////////////////////////////////////////////////////// void dtkDistributedMapperPrivate::setMapping(const qlonglong& id_number, const qlonglong& pu_number) { this->id_count = id_number; this->pu_count = pu_number; this->map.reserve(this->pu_count + 1); if (this->pu_count == 1) { this->map << 0; this->step = this->id_count; } else if (this->id_count < this->pu_count ) { qDebug() << "Number of ids less than process count: NOT YET IMPLEMENTED"; return; } else if (this->id_count < this->pu_count * 2) { for (qlonglong i = 0; i < this->id_count - this->pu_count; ++i) this->map << i * 2; qlonglong start = (this->id_count - this->pu_count) *2; for (qlonglong i = this->id_count - this->pu_count; i < this->pu_count; ++i) this->map << start++; this->step = 0; } else { this->step = qRound(this->id_count / (1. * this->pu_count)); for (qlonglong i = 0; i < this->pu_count - 1; ++i) { this->map << i * this->step; } this->map << (this->map.at(this->pu_count - 2) + this->step); } this->map << this->id_count; } void dtkDistributedMapperPrivate::initMap(const qlonglong& map_size, const qlonglong& pu_size) { this->id_count = map_size; this->pu_count = pu_size; this->map.resize(this->pu_count + 1); this->map[this->pu_count] = map_size; this->step = 0; } void dtkDistributedMapperPrivate::setMap(const qlonglong& offset, const qlonglong& pu_id) { this->map[pu_id] = offset; } qlonglong dtkDistributedMapperPrivate::localToGlobal(const qlonglong& local_id, const qlonglong& pu_id) const { return ( local_id + this->map.at(pu_id) ); } qlonglong dtkDistributedMapperPrivate::globalToLocal(const qlonglong& global_id) const { qlonglong pu_id = this->owner(global_id); return ( global_id - this->map.at(pu_id) ); } qlonglong dtkDistributedMapperPrivate::count(const qlonglong& pu_id) const { return ( this->map.at(pu_id + 1) - this->map.at(pu_id) ); // if ( pu_id != (this->pu_count - 1) ) // return ( this->map.at(pu_id + 1) - this->map.at(pu_id) ); // else // return ( this->id_count - this->map.at(pu_id) ); } qlonglong dtkDistributedMapperPrivate::owner(const qlonglong& global_id) const { if (this->step > 0) { return qMin((qlonglong)(global_id / this->step), this->pu_count-1); } else { qlonglong current_id = this->map[this->map.count() - 2]; qlonglong pid = this->pu_count-1; while (global_id < current_id) { current_id = this->map.at(--pid); } return pid; } } // ///////////////////////////////////////////////////////////////// // dtkDistributedMapper implementation // ///////////////////////////////////////////////////////////////// dtkDistributedMapper::dtkDistributedMapper(void) : QObject(), d(new dtkDistributedMapperPrivate) { } dtkDistributedMapper::~dtkDistributedMapper(void) { delete d; } void dtkDistributedMapper::setMapping(const qlonglong& id_count, const qlonglong& pu_count) { d->setMapping(id_count, pu_count); } void dtkDistributedMapper::initMap(const qlonglong& map_size, const qlonglong& pu_size) { d->initMap(map_size, pu_size); } void dtkDistributedMapper::setMap(const qlonglong& offset, const qlonglong& pu_id) { d->setMap(offset, pu_id); } qlonglong dtkDistributedMapper::localToGlobal(const qlonglong& local_id, const qlonglong& pu_id) const { return d->localToGlobal(local_id, pu_id); } qlonglong dtkDistributedMapper::globalToLocal(const qlonglong& global_id) const { return d->globalToLocal(global_id); } qlonglong dtkDistributedMapper::count(const qlonglong& pu_id) const { return d->count(pu_id); } qlonglong dtkDistributedMapper::startIndex(const qlonglong& pu_id) const { return d->map[pu_id]; } qlonglong dtkDistributedMapper::lastIndex(const qlonglong& pu_id) const { return d->map[pu_id + 1] - 1; } qlonglong dtkDistributedMapper::owner(const qlonglong& global_id) const { return d->owner(global_id); } <commit_msg>fix mapper<commit_after>/* dtkDistributedMapper.cpp --- * * Author: Thibaud Kloczko * Created: 2013 Thu Feb 7 10:55:57 (+0100) */ /* Commentary: * */ /* Change log: * */ #include "dtkDistributedMapper.h" #include <QtCore> // ///////////////////////////////////////////////////////////////// // dtkDistributedMapperPrivate interface // ///////////////////////////////////////////////////////////////// class dtkDistributedMapperPrivate { public: dtkDistributedMapperPrivate(void) {;} ~dtkDistributedMapperPrivate(void) {;} public: void setMapping(const qlonglong& id_number, const qlonglong& pu_number); void initMap(const qlonglong& map_size, const qlonglong& pu_size); void setMap(const qlonglong& local_map_size, const qlonglong& pu_id); public: qlonglong localToGlobal(const qlonglong& local_id, const qlonglong& pu_id) const; qlonglong globalToLocal(const qlonglong& global_id) const; qlonglong count(const qlonglong& pu_id) const; qlonglong owner(const qlonglong& global_id) const; QVector<qlonglong> readers(const qlonglong& global_id) const; public: qlonglong id_count; qlonglong pu_count; qlonglong step; QVector<qlonglong> map; }; // ///////////////////////////////////////////////////////////////// // dtkDistributedMapperPrivate implementation // ///////////////////////////////////////////////////////////////// void dtkDistributedMapperPrivate::setMapping(const qlonglong& id_number, const qlonglong& pu_number) { this->id_count = id_number; this->pu_count = pu_number; this->map.reserve(this->pu_count + 1); this->map.clear(); if (this->pu_count == 1) { this->map << 0; this->step = this->id_count; } else if (this->id_count < this->pu_count ) { qDebug() << "Number of ids less than process count: NOT YET IMPLEMENTED"; return; } else if (this->id_count < this->pu_count * 2) { for (qlonglong i = 0; i < this->id_count - this->pu_count; ++i) this->map << i * 2; qlonglong start = (this->id_count - this->pu_count) *2; for (qlonglong i = this->id_count - this->pu_count; i < this->pu_count; ++i) this->map << start++; this->step = 0; } else { this->step = qRound(this->id_count / (1. * this->pu_count)); qlonglong last = qMin(this->id_count / this->step, this->pu_count -1); for (qlonglong i = 0; i < last; ++i) this->map << i * this->step; qlonglong start = (last - 1) * this->step; for (qlonglong i = last; i < this->pu_count; ++i) { start += this->step -1; this->map << qMin(start, this->id_count -1); } this->step = 0; } this->map << this->id_count; } void dtkDistributedMapperPrivate::initMap(const qlonglong& map_size, const qlonglong& pu_size) { this->id_count = map_size; this->pu_count = pu_size; this->map.resize(this->pu_count + 1); this->map[this->pu_count] = map_size; this->step = 0; } void dtkDistributedMapperPrivate::setMap(const qlonglong& offset, const qlonglong& pu_id) { this->map[pu_id] = offset; } qlonglong dtkDistributedMapperPrivate::localToGlobal(const qlonglong& local_id, const qlonglong& pu_id) const { return ( local_id + this->map.at(pu_id) ); } qlonglong dtkDistributedMapperPrivate::globalToLocal(const qlonglong& global_id) const { qlonglong pu_id = this->owner(global_id); return ( global_id - this->map.at(pu_id) ); } qlonglong dtkDistributedMapperPrivate::count(const qlonglong& pu_id) const { return ( this->map.at(pu_id + 1) - this->map.at(pu_id) ); // if ( pu_id != (this->pu_count - 1) ) // return ( this->map.at(pu_id + 1) - this->map.at(pu_id) ); // else // return ( this->id_count - this->map.at(pu_id) ); } qlonglong dtkDistributedMapperPrivate::owner(const qlonglong& global_id) const { if (this->step > 0) { return qMin((qlonglong)(global_id / this->step), this->pu_count-1); } else { qlonglong current_id = this->map[this->map.count() - 2]; qlonglong pid = this->pu_count-1; while (global_id < current_id) { current_id = this->map.at(--pid); } return pid; } } // ///////////////////////////////////////////////////////////////// // dtkDistributedMapper implementation // ///////////////////////////////////////////////////////////////// dtkDistributedMapper::dtkDistributedMapper(void) : QObject(), d(new dtkDistributedMapperPrivate) { } dtkDistributedMapper::~dtkDistributedMapper(void) { delete d; } void dtkDistributedMapper::setMapping(const qlonglong& id_count, const qlonglong& pu_count) { d->setMapping(id_count, pu_count); } void dtkDistributedMapper::initMap(const qlonglong& map_size, const qlonglong& pu_size) { d->initMap(map_size, pu_size); } void dtkDistributedMapper::setMap(const qlonglong& offset, const qlonglong& pu_id) { d->setMap(offset, pu_id); } qlonglong dtkDistributedMapper::localToGlobal(const qlonglong& local_id, const qlonglong& pu_id) const { return d->localToGlobal(local_id, pu_id); } qlonglong dtkDistributedMapper::globalToLocal(const qlonglong& global_id) const { return d->globalToLocal(global_id); } qlonglong dtkDistributedMapper::count(const qlonglong& pu_id) const { return d->count(pu_id); } qlonglong dtkDistributedMapper::startIndex(const qlonglong& pu_id) const { return d->map[pu_id]; } qlonglong dtkDistributedMapper::lastIndex(const qlonglong& pu_id) const { return d->map[pu_id + 1] - 1; } qlonglong dtkDistributedMapper::owner(const qlonglong& global_id) const { return d->owner(global_id); } <|endoftext|>
<commit_before>// // PROJECT: Aspia // FILE: ui/address_book/open_address_book_dialog.cc // LICENSE: Mozilla Public License Version 2.0 // PROGRAMMERS: Dmitry Chapyshev (dmitry@aspia.ru) // #include "ui/address_book/open_address_book_dialog.h" #include "base/strings/unicode.h" #include "crypto/secure_memory.h" namespace aspia { const std::wstring& OpenAddressBookDialog::GetPassword() const { return password_.string(); } LRESULT OpenAddressBookDialog::OnInitDialog( UINT /* message */, WPARAM /* wparam */, LPARAM /* lparam */, BOOL& /* handled */) { GetDlgItem(IDC_PASSWORD_EDIT).SetFocus(); return TRUE; } LRESULT OpenAddressBookDialog::OnClose( UINT /* message */, WPARAM /* wparam */, LPARAM /* lparam */, BOOL& /* handled */) { EndDialog(IDCANCEL); return 0; } LRESULT OpenAddressBookDialog::OnOkButton( WORD /* notify_code */, WORD /* control_id */, HWND /* control */, BOOL& /* handled */) { SecureArray<WCHAR, 256> buffer; GetDlgItemTextW(IDC_PASSWORD_EDIT, buffer.get(), static_cast<int>(buffer.count())); password_.mutable_string().assign(buffer.get()); EndDialog(IDOK); return 0; } LRESULT OpenAddressBookDialog::OnCancelButton( WORD /* notify_code */, WORD /* control_id */, HWND /* control */, BOOL& /* handled */) { EndDialog(IDCANCEL); return 0; } } // namespace aspia <commit_msg>- Using GetWindowString.<commit_after>// // PROJECT: Aspia // FILE: ui/address_book/open_address_book_dialog.cc // LICENSE: Mozilla Public License Version 2.0 // PROGRAMMERS: Dmitry Chapyshev (dmitry@aspia.ru) // #include "ui/address_book/open_address_book_dialog.h" #include "base/strings/unicode.h" #include "crypto/secure_memory.h" #include "ui/ui_util.h" namespace aspia { const std::wstring& OpenAddressBookDialog::GetPassword() const { return password_.string(); } LRESULT OpenAddressBookDialog::OnInitDialog( UINT /* message */, WPARAM /* wparam */, LPARAM /* lparam */, BOOL& /* handled */) { GetDlgItem(IDC_PASSWORD_EDIT).SetFocus(); return TRUE; } LRESULT OpenAddressBookDialog::OnClose( UINT /* message */, WPARAM /* wparam */, LPARAM /* lparam */, BOOL& /* handled */) { EndDialog(IDCANCEL); return 0; } LRESULT OpenAddressBookDialog::OnOkButton( WORD /* notify_code */, WORD /* control_id */, HWND /* control */, BOOL& /* handled */) { password_ = GetWindowString(GetDlgItem(IDC_PASSWORD_EDIT)); EndDialog(IDOK); return 0; } LRESULT OpenAddressBookDialog::OnCancelButton( WORD /* notify_code */, WORD /* control_id */, HWND /* control */, BOOL& /* handled */) { EndDialog(IDCANCEL); return 0; } } // namespace aspia <|endoftext|>
<commit_before>/* * opencog/learning/moses/representation/representation.cc * * Copyright (C) 2002-2008 Novamente LLC * All Rights Reserved * * Written by Moshe Looks * Predrag Janicic * * 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 <boost/thread.hpp> #include <boost/range/algorithm/find_if.hpp> #include <opencog/util/lazy_random_selector.h> #include <opencog/comboreduct/reduct/reduct.h> #include <opencog/comboreduct/reduct/meta_rules.h> #include <opencog/comboreduct/reduct/logical_rules.h> #include <opencog/comboreduct/reduct/general_rules.h> #include "../moses/using.h" #include "representation.h" #include "build_knobs.h" namespace opencog { namespace moses { // Stepsize should be roughly the standard-deviation of the expected // distribution of the contin variables. // // XXX TODO: One might think that varying the stepsize, i.e. shrinking // it, as the optimizers tune into a specific value, would be a good // thing (so that the optimizer could tune to a more precise value). // Unfortunately, a simple experiment in tuning (see below, surrounded // by "#if 0") didn't work; it didn't find better answers, and it // lengthened running time. static contin_t stepsize = 1.0; // Expansion factor should be 1 or greater; it should never be less // than one. Optimal values are probably 1.5 to 2.0. static contin_t expansion = 2.0; // By default, contin knobs will have 5 "pseudo-bits" of binary // precision. Roughly speaking, they can hold 2^5 = 32 different // values, or just a little better than one decimal place of precision. static int depth = 5; void set_stepsize(double new_ss) { stepsize = new_ss; } void set_expansion(double new_ex) { expansion = new_ex; } void set_depth(int new_depth) { depth = new_depth; } representation::representation(const reduct::rule& simplify_candidate, const reduct::rule& simplify_knob_building, const combo_tree& exemplar_, const type_tree& tt, const operator_set& ignore_ops, const combo_tree_ns_set* perceptions, const combo_tree_ns_set* actions) : _exemplar(exemplar_), _simplify_candidate(&simplify_candidate), _simplify_knob_building(&simplify_knob_building) { logger().debug() << "Building representation from exemplar: " << _exemplar; // Build the knobs. build_knobs(_exemplar, tt, *this, ignore_ops, perceptions, actions, stepsize, expansion, depth); logger().debug() << "After knob building: " << _exemplar; #if 0 // Attempt to adjust the contin spec step size to a value that is // "most likely to be useful" for exploring the neighborhood of an // exemplar. Basically, we try to guess what step size we were last // at when we modified this contin; we do this by lopping off // factors of two until we've matched the previous pecision. // This way, when exploring in a deme, we explore values near the // old value, with appropriate step sizes. // // Unfortunately, experiments seem to discredit this idea: it often // slows down the search, and rarely/never seems to provide better // answers. Leaving this commented out for now. contin_map new_cmap; foreach (contin_v& v, contin) { field_set::contin_spec cspec = v.first; contin_t remain = fabs(cspec.mean); remain -= floor(remain + 0.01f); contin_t new_step = remain; if (remain < 0.01f) new_step = stepsize; else remain -= new_step; while (0.01f < remain) { new_step *= 0.5f; if (new_step < remain + 0.01f) remain -= new_step; } cspec.step_size = new_step; new_cmap.insert(make_pair(cspec, v.second)); } contin = new_cmap; #endif // Convert the knobs into a field set. std::multiset<field_set::spec> tmp; foreach (const disc_v& v, disc) tmp.insert(v.first); foreach (const contin_v& v, contin) tmp.insert(v.first); _fields = field_set(tmp.begin(), tmp.end()); // build mapping from combo tree iterator to knobs and idx for (pre_it it = _exemplar.begin(); it != _exemplar.end(); ++it) { // find disc knobs disc_map_cit d_cit = boost::find_if(disc, [&it](const disc_v& v) { return v.second->get_loc() == it; }); if (d_cit != disc.end()) { it_disc_knob[it] = d_cit; it_disc_idx[it] = _fields.begin_disc_raw_idx() + distance(disc.cbegin(), d_cit); } else { // find contin knobs contin_map_cit c_cit = boost::find_if(contin, [&it](const contin_v& v) { return v.second.get_loc() == it; }); if (c_cit != contin.end()) { it_contin_knob[it] = c_cit; it_contin_idx[it] = distance(contin.cbegin(), c_cit); } } } if (logger().isDebugEnabled()) { std::stringstream ss; ostream_prototype(ss << "Created prototype: "); logger().debug(ss.str()); } #ifdef EXEMPLAR_INST_IS_UNDEAD set_exemplar_inst(); { std::stringstream ss; ss << "Exemplar instance: " << _fields.stream(_exemplar_inst); logger().debug(ss.str()); } #endif // EXEMPLAR_INST_IS_UNDEAD } /// Turn the knobs on the representation, so thaat the knob settings match /// the instance supplied as the argument. void representation::transform(const instance& inst) { // XXX TODO need to add support for "term algebra" knobs contin_map_it ckb = contin.begin(); for (field_set::const_contin_iterator ci = _fields.begin_contin(inst); ci != _fields.end_contin(inst); ++ci, ++ckb) { ckb->second.turn(*ci); //_exemplar.validate(); } // cout << _fields.stream(inst) << endl; disc_map_it dkb = disc.begin(); for (field_set::const_disc_iterator di = _fields.begin_disc(inst); di != _fields.end_disc(inst); ++di, ++dkb) { dkb->second->turn(*di); //_exemplar.validate(); } for (field_set::const_bit_iterator bi = _fields.begin_bit(inst); bi != _fields.end_bit(inst); ++bi, ++dkb) { dkb->second->turn(*bi); } //cout << _exemplar << endl; // std::cout << "New exemplar (after build): " << _exemplar << std::endl; } combo_tree representation::get_clean_exemplar(bool reduce, bool knob_building) const { // Make a copy -- expensive! but necessary. combo_tree tr = exemplar(); clean_combo_tree(tr, reduce, knob_building); return tr; } void representation::clean_combo_tree(combo_tree &tr, bool reduce, bool knob_building) const { using namespace reduct; // Remove null vertices. clean_reduce(tr); if (reduce) { //reduce if (logger().isFineEnabled()) { logger().fine() << "Reduce (knob=" << knob_building << ") candidate: " << tr; } if (knob_building) (*get_simplify_knob_building())(tr); else (*get_simplify_candidate())(tr); } } /// Create a combo tree that corresponds to the instance inst. /// /// This is done by twiddling the knobs on the representation so that /// it matches the supplied inst, copying the rep to an equivalent, /// but knob-less combo tree, and returning that. Optionally, if the /// 'reduce' flag is set, then the tree is reduced. /// /// Warning: use get_candidate instead which is both more efficient /// and scales better on multi-proc (as it is locker free) combo_tree representation::get_candidate_lock(const instance& inst, bool reduce) { // In order to make this method thread-safe, a copy of the exemplar // must be made under the lock, after the transform step. // Unfortunately, copying the exemplar is expensive, but seemingly // unavoidable: the knob mapper only works for the member _exemplar. // Thus we cannot have "const combo_tree &tr = exemplar();" boost::mutex::scoped_lock lock(tranform_mutex); transform(inst); combo_tree tr = exemplar(); // make copy before unlocking. lock.unlock(); clean_combo_tree(tr, reduce); return tr; } // Same function as get_candidate_lock but doesn't use lock and does not // modify _exemplar, instead it build the combo tree from scratch combo_tree representation::get_candidate(const instance& inst, bool reduce) const { combo_tree candidate; get_candidate_rec(inst, _exemplar.begin(), candidate.end(), candidate); // this can probably be simplified, it doesn't need to remove // null_vertices anymore clean_combo_tree(candidate, reduce); return candidate; } // Append *src (turned according inst) as child of parent_dst and, in // case it's not null_vertex, repeat recursively using that appended // child as new parent_dst. If candidate is empty (parent_dst is // invalid) then copy *src (turned according to inst) as root of // candidate void representation::get_candidate_rec(const instance& inst, combo_tree::iterator src, combo_tree::iterator parent_dst, combo_tree& candidate) const { typedef combo_tree::iterator pre_it; typedef combo_tree::sibling_iterator sib_it; // recursive call on the children of src to parent_dst auto recursive_call = [&inst, &candidate, this](pre_it new_parent_dst, pre_it src) { for(sib_it src_child = src.begin(); src_child != src.end(); ++src_child) get_candidate_rec(inst, src_child, new_parent_dst, candidate); }; // append v to parent_dst's children. If candidate is empty then // set it as head. Return the iterator pointing to the new content. auto append_child = [&candidate](pre_it parent_dst, const vertex& v) { return candidate.empty()? candidate.set_head(v) : candidate.append_child(parent_dst, v); }; // find the knob associated to src (if any) disc_map_cit dcit = find_disc_knob(src); if (dcit == disc.end()) { contin_map_cit ccit = find_contin_knob(src); if (ccit == contin.end()) // no knob found recursive_call(append_child(parent_dst, *src), src); else { // contin knob found contin_t c = _fields.get_contin(inst, it_contin_idx.find(src)->second); ccit->second.append_to(candidate, parent_dst, c); } } else { // disc knob found int d = _fields.get_raw(inst, it_disc_idx.find(src)->second); pre_it new_src = dcit->second->append_to(candidate, parent_dst, d); if (_exemplar.is_valid(new_src)) recursive_call(parent_dst, new_src); } } #ifdef EXEMPLAR_INST_IS_UNDEAD // XXX This is dead code, no one uses it, and looking at the below, it // looks inconsistent to me. I'm going to leave it here for a while, but // it should be removed by 2013 or 2014 if not sooner... // XXX why are we clearing this, instead of setting it back to the // _exemplar_inst ??? XXX is this broken?? // // XXX Note that the clear_exemplar() methods on the knobs are probably // not needed either!? void representation::clear_exemplar() { foreach(disc_v& v, disc) v.second->clear_exemplar(); foreach(contin_v& v, contin) v.second.clear_exemplar(); } // What is this doing ? seems to be clearing things out, why do we need this? // XXX that, and contin seems to be handled inconsistently with disc... // I mean, shouldn't we be setting the exemplar_inst fields so that // they match the exmplar? Do we even need the exemplar_inst for anything? void representation::set_exemplar_inst() { OC_ASSERT(_exemplar_inst.empty(), "Should be called only once," " therefore _exemplar_inst should be empty"); _exemplar_inst.resize(_fields.packed_width()); // @todo: term algebras // bit for(field_set::bit_iterator it = _fields.begin_bit(_exemplar_inst); it != _fields.end_bit(_exemplar_inst); ++it) *it = false; // disc for(field_set::disc_iterator it = _fields.begin_disc(_exemplar_inst); it != _fields.end_disc(_exemplar_inst); ++it) *it = 0; // contin contin_map_cit c_cit = contin.begin(); for(field_set::contin_iterator it = _fields.begin_contin(_exemplar_inst); it != _fields.end_contin(_exemplar_inst); ++it, ++c_cit) { // this should actually set the contin knob to Stop ... // because the mean of the associated contin field is // equal to the initial contin value *it = get_contin(*c_cit->second.get_loc()); } } #endif // EXEMPLAR_INST_IS_UNDEAD } // ~namespace moses } // ~namespace opencog <commit_msg>some minor logging improvement representation::clean_combo_tree<commit_after>/* * opencog/learning/moses/representation/representation.cc * * Copyright (C) 2002-2008 Novamente LLC * All Rights Reserved * * Written by Moshe Looks * Predrag Janicic * * 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 <boost/thread.hpp> #include <boost/range/algorithm/find_if.hpp> #include <opencog/util/lazy_random_selector.h> #include <opencog/comboreduct/reduct/reduct.h> #include <opencog/comboreduct/reduct/meta_rules.h> #include <opencog/comboreduct/reduct/logical_rules.h> #include <opencog/comboreduct/reduct/general_rules.h> #include "../moses/using.h" #include "representation.h" #include "build_knobs.h" namespace opencog { namespace moses { // Stepsize should be roughly the standard-deviation of the expected // distribution of the contin variables. // // XXX TODO: One might think that varying the stepsize, i.e. shrinking // it, as the optimizers tune into a specific value, would be a good // thing (so that the optimizer could tune to a more precise value). // Unfortunately, a simple experiment in tuning (see below, surrounded // by "#if 0") didn't work; it didn't find better answers, and it // lengthened running time. static contin_t stepsize = 1.0; // Expansion factor should be 1 or greater; it should never be less // than one. Optimal values are probably 1.5 to 2.0. static contin_t expansion = 2.0; // By default, contin knobs will have 5 "pseudo-bits" of binary // precision. Roughly speaking, they can hold 2^5 = 32 different // values, or just a little better than one decimal place of precision. static int depth = 5; void set_stepsize(double new_ss) { stepsize = new_ss; } void set_expansion(double new_ex) { expansion = new_ex; } void set_depth(int new_depth) { depth = new_depth; } representation::representation(const reduct::rule& simplify_candidate, const reduct::rule& simplify_knob_building, const combo_tree& exemplar_, const type_tree& tt, const operator_set& ignore_ops, const combo_tree_ns_set* perceptions, const combo_tree_ns_set* actions) : _exemplar(exemplar_), _simplify_candidate(&simplify_candidate), _simplify_knob_building(&simplify_knob_building) { logger().debug() << "Building representation from exemplar: " << _exemplar; // Build the knobs. build_knobs(_exemplar, tt, *this, ignore_ops, perceptions, actions, stepsize, expansion, depth); logger().debug() << "After knob building: " << _exemplar; #if 0 // Attempt to adjust the contin spec step size to a value that is // "most likely to be useful" for exploring the neighborhood of an // exemplar. Basically, we try to guess what step size we were last // at when we modified this contin; we do this by lopping off // factors of two until we've matched the previous pecision. // This way, when exploring in a deme, we explore values near the // old value, with appropriate step sizes. // // Unfortunately, experiments seem to discredit this idea: it often // slows down the search, and rarely/never seems to provide better // answers. Leaving this commented out for now. contin_map new_cmap; foreach (contin_v& v, contin) { field_set::contin_spec cspec = v.first; contin_t remain = fabs(cspec.mean); remain -= floor(remain + 0.01f); contin_t new_step = remain; if (remain < 0.01f) new_step = stepsize; else remain -= new_step; while (0.01f < remain) { new_step *= 0.5f; if (new_step < remain + 0.01f) remain -= new_step; } cspec.step_size = new_step; new_cmap.insert(make_pair(cspec, v.second)); } contin = new_cmap; #endif // Convert the knobs into a field set. std::multiset<field_set::spec> tmp; foreach (const disc_v& v, disc) tmp.insert(v.first); foreach (const contin_v& v, contin) tmp.insert(v.first); _fields = field_set(tmp.begin(), tmp.end()); // build mapping from combo tree iterator to knobs and idx for (pre_it it = _exemplar.begin(); it != _exemplar.end(); ++it) { // find disc knobs disc_map_cit d_cit = boost::find_if(disc, [&it](const disc_v& v) { return v.second->get_loc() == it; }); if (d_cit != disc.end()) { it_disc_knob[it] = d_cit; it_disc_idx[it] = _fields.begin_disc_raw_idx() + distance(disc.cbegin(), d_cit); } else { // find contin knobs contin_map_cit c_cit = boost::find_if(contin, [&it](const contin_v& v) { return v.second.get_loc() == it; }); if (c_cit != contin.end()) { it_contin_knob[it] = c_cit; it_contin_idx[it] = distance(contin.cbegin(), c_cit); } } } if (logger().isDebugEnabled()) { std::stringstream ss; ostream_prototype(ss << "Created prototype: "); logger().debug(ss.str()); } #ifdef EXEMPLAR_INST_IS_UNDEAD set_exemplar_inst(); { std::stringstream ss; ss << "Exemplar instance: " << _fields.stream(_exemplar_inst); logger().debug(ss.str()); } #endif // EXEMPLAR_INST_IS_UNDEAD } /// Turn the knobs on the representation, so thaat the knob settings match /// the instance supplied as the argument. void representation::transform(const instance& inst) { // XXX TODO need to add support for "term algebra" knobs contin_map_it ckb = contin.begin(); for (field_set::const_contin_iterator ci = _fields.begin_contin(inst); ci != _fields.end_contin(inst); ++ci, ++ckb) { ckb->second.turn(*ci); //_exemplar.validate(); } // cout << _fields.stream(inst) << endl; disc_map_it dkb = disc.begin(); for (field_set::const_disc_iterator di = _fields.begin_disc(inst); di != _fields.end_disc(inst); ++di, ++dkb) { dkb->second->turn(*di); //_exemplar.validate(); } for (field_set::const_bit_iterator bi = _fields.begin_bit(inst); bi != _fields.end_bit(inst); ++bi, ++dkb) { dkb->second->turn(*bi); } //cout << _exemplar << endl; // std::cout << "New exemplar (after build): " << _exemplar << std::endl; } combo_tree representation::get_clean_exemplar(bool reduce, bool knob_building) const { // Make a copy -- expensive! but necessary. combo_tree tr = exemplar(); clean_combo_tree(tr, reduce, knob_building); return tr; } void representation::clean_combo_tree(combo_tree &tr, bool reduce, bool knob_building) const { using namespace reduct; // Remove null vertices. clean_reduce(tr); if (reduce) { //reduce if (logger().isFineEnabled()) { logger().fine() << "Reduce " << (knob_building? "(knob_building)" : "") << " candidate: " << tr; } if (knob_building) (*get_simplify_knob_building())(tr); else (*get_simplify_candidate())(tr); if (logger().isFineEnabled()) { logger().fine() << "Reduced candidate:" << tr; } } } /// Create a combo tree that corresponds to the instance inst. /// /// This is done by twiddling the knobs on the representation so that /// it matches the supplied inst, copying the rep to an equivalent, /// but knob-less combo tree, and returning that. Optionally, if the /// 'reduce' flag is set, then the tree is reduced. /// /// Warning: use get_candidate instead which is both more efficient /// and scales better on multi-proc (as it is locker free) combo_tree representation::get_candidate_lock(const instance& inst, bool reduce) { // In order to make this method thread-safe, a copy of the exemplar // must be made under the lock, after the transform step. // Unfortunately, copying the exemplar is expensive, but seemingly // unavoidable: the knob mapper only works for the member _exemplar. // Thus we cannot have "const combo_tree &tr = exemplar();" boost::mutex::scoped_lock lock(tranform_mutex); transform(inst); combo_tree tr = exemplar(); // make copy before unlocking. lock.unlock(); clean_combo_tree(tr, reduce); return tr; } // Same function as get_candidate_lock but doesn't use lock and does not // modify _exemplar, instead it build the combo tree from scratch combo_tree representation::get_candidate(const instance& inst, bool reduce) const { combo_tree candidate; get_candidate_rec(inst, _exemplar.begin(), candidate.end(), candidate); // this can probably be simplified, it doesn't need to remove // null_vertices anymore clean_combo_tree(candidate, reduce); return candidate; } // Append *src (turned according inst) as child of parent_dst and, in // case it's not null_vertex, repeat recursively using that appended // child as new parent_dst. If candidate is empty (parent_dst is // invalid) then copy *src (turned according to inst) as root of // candidate void representation::get_candidate_rec(const instance& inst, combo_tree::iterator src, combo_tree::iterator parent_dst, combo_tree& candidate) const { typedef combo_tree::iterator pre_it; typedef combo_tree::sibling_iterator sib_it; // recursive call on the children of src to parent_dst auto recursive_call = [&inst, &candidate, this](pre_it new_parent_dst, pre_it src) { for(sib_it src_child = src.begin(); src_child != src.end(); ++src_child) get_candidate_rec(inst, src_child, new_parent_dst, candidate); }; // append v to parent_dst's children. If candidate is empty then // set it as head. Return the iterator pointing to the new content. auto append_child = [&candidate](pre_it parent_dst, const vertex& v) { return candidate.empty()? candidate.set_head(v) : candidate.append_child(parent_dst, v); }; // find the knob associated to src (if any) disc_map_cit dcit = find_disc_knob(src); if (dcit == disc.end()) { contin_map_cit ccit = find_contin_knob(src); if (ccit == contin.end()) // no knob found recursive_call(append_child(parent_dst, *src), src); else { // contin knob found contin_t c = _fields.get_contin(inst, it_contin_idx.find(src)->second); ccit->second.append_to(candidate, parent_dst, c); } } else { // disc knob found int d = _fields.get_raw(inst, it_disc_idx.find(src)->second); pre_it new_src = dcit->second->append_to(candidate, parent_dst, d); if (_exemplar.is_valid(new_src)) recursive_call(parent_dst, new_src); } } #ifdef EXEMPLAR_INST_IS_UNDEAD // XXX This is dead code, no one uses it, and looking at the below, it // looks inconsistent to me. I'm going to leave it here for a while, but // it should be removed by 2013 or 2014 if not sooner... // XXX why are we clearing this, instead of setting it back to the // _exemplar_inst ??? XXX is this broken?? // // XXX Note that the clear_exemplar() methods on the knobs are probably // not needed either!? void representation::clear_exemplar() { foreach(disc_v& v, disc) v.second->clear_exemplar(); foreach(contin_v& v, contin) v.second.clear_exemplar(); } // What is this doing ? seems to be clearing things out, why do we need this? // XXX that, and contin seems to be handled inconsistently with disc... // I mean, shouldn't we be setting the exemplar_inst fields so that // they match the exmplar? Do we even need the exemplar_inst for anything? void representation::set_exemplar_inst() { OC_ASSERT(_exemplar_inst.empty(), "Should be called only once," " therefore _exemplar_inst should be empty"); _exemplar_inst.resize(_fields.packed_width()); // @todo: term algebras // bit for(field_set::bit_iterator it = _fields.begin_bit(_exemplar_inst); it != _fields.end_bit(_exemplar_inst); ++it) *it = false; // disc for(field_set::disc_iterator it = _fields.begin_disc(_exemplar_inst); it != _fields.end_disc(_exemplar_inst); ++it) *it = 0; // contin contin_map_cit c_cit = contin.begin(); for(field_set::contin_iterator it = _fields.begin_contin(_exemplar_inst); it != _fields.end_contin(_exemplar_inst); ++it, ++c_cit) { // this should actually set the contin knob to Stop ... // because the mean of the associated contin field is // equal to the initial contin value *it = get_contin(*c_cit->second.get_loc()); } } #endif // EXEMPLAR_INST_IS_UNDEAD } // ~namespace moses } // ~namespace opencog <|endoftext|>
<commit_before>#include "musicplayedlistpopwidget.h" #include "musicfunctionuiobject.h" #include "musicsongslistplayedtablewidget.h" #include "musicsettingmanager.h" #include "musictinyuiobject.h" #include "musicuiobject.h" #include "musicapplication.h" #include "musicplayedlist.h" #include <QLabel> #include <QBoxLayout> #include <QPushButton> #include <QToolButton> #include <QScrollArea> #define MAX_SIZE 3 MusicPlayedListPopWidget *MusicPlayedListPopWidget::m_instance = nullptr; MusicPlayedListPopWidget::MusicPlayedListPopWidget(QWidget *parent) : MusicToolMenuWidget(parent) { m_instance = this; m_playlist = nullptr; setToolTip(tr("playedList")); setStyleSheet(MusicUIObject::MKGBtnPlayedList); disconnect(this, SIGNAL(clicked()), this, SLOT(popupMenu())); connect(this, SIGNAL(clicked()), SLOT(popupMenu())); initWidget(); } MusicPlayedListPopWidget::~MusicPlayedListPopWidget() { delete m_playedListWidget; qDeleteAll(m_labels); } QString MusicPlayedListPopWidget::getClassName() { return staticMetaObject.className(); } MusicPlayedListPopWidget *MusicPlayedListPopWidget::instance() { return m_instance; } void MusicPlayedListPopWidget::setPlaylist(MusicPlayedlist *playlist) { delete m_playlist; m_playlist = playlist; } MusicPlayedlist *MusicPlayedListPopWidget::playlist() const { return m_playlist; } void MusicPlayedListPopWidget::clear() { m_songLists.clear(); m_playedListWidget->clearAllItems(); setPlayListCount(0); } void MusicPlayedListPopWidget::resetToolIndex(const PairList &indexs) { MusicPlayedItems *items = m_playlist->mediaList(); for(int s=0; s<items->count(); ++s) { for(int i=0; i<indexs.count(); ++i) { const std::pair<int, int> &index = indexs[i]; if(items->at(s).m_toolIndex == index.first) { (*items)[s].m_toolIndex = index.second; break; } } } } void MusicPlayedListPopWidget::remove(int index) { if(index < 0 || index >= m_songLists.count()) { return; } m_playlist->removeMedia(index); m_songLists.removeAt(index); m_playedListWidget->removeRow(index); m_playedListWidget->setPlayRowIndex(-1); updateSongsFileName(); } void MusicPlayedListPopWidget::remove(int toolIndex, const QString &path) { int index = -1; do { index = m_playlist->removeMedia(toolIndex, path); if(index != -1) { m_songLists.removeAt(index); m_playedListWidget->removeRow(index); } }while(index != -1); m_playedListWidget->setPlayRowIndex(-1); updateSongsFileName(); } void MusicPlayedListPopWidget::remove(int toolIndex, const MusicSong &song) { remove(toolIndex, song.getMusicPath()); } void MusicPlayedListPopWidget::append(int toolIndex, const MusicSong &song) { m_playlist->appendMedia(toolIndex, song.getMusicPath()); m_songLists << song; updateSongsFileName(); } void MusicPlayedListPopWidget::append(const MusicSongs &song) { clear(); m_songLists = song; updateSongsFileName(); } void MusicPlayedListPopWidget::insert(int toolIndex, const MusicSong &song) { insert(toolIndex, m_playedListWidget->getPlayRowIndex() + 1, song); } void MusicPlayedListPopWidget::insert(int toolIndex, int index, const MusicSong &song) { if(index < 0 || index > m_songLists.count()) { return; } (index != m_songLists.count()) ? m_songLists.insert(index, song) : m_songLists.append(song); m_playlist->insertLaterMedia(toolIndex, song.getMusicPath()); int row = m_playedListWidget->getPlayRowIndex(); m_playedListWidget->clearAllItems(); updateSongsFileName(); m_playedListWidget->setPlayRowIndex(row); m_playedListWidget->selectPlayedRow(); foreach(const MusicPlayedItem &item, m_playlist->laterListConst()) { m_playedListWidget->setPlayLaterState(item.m_toolIndex); } } void MusicPlayedListPopWidget::setCurrentIndex() { int index = m_playlist->currentIndex(); m_playedListWidget->selectRow(index); } void MusicPlayedListPopWidget::setCurrentIndex(int toolIndex, const MusicSong &song) { m_playlist->setCurrentIndex(toolIndex, song.getMusicPath()); setCurrentIndex(); } void MusicPlayedListPopWidget::resizeWindow() { // int h = M_SETTING_PTR->value(MusicSettingManager::WidgetSize).toSize().height(); // m_containWidget->setFixedSize(300, 500 + h - WINDOW_HEIGHT_MIN); } void MusicPlayedListPopWidget::popupMenu() { QPoint pos = mapToGlobal(QPoint(0, 0)); pos.setY(pos.y() - m_containWidget->height() - 10); pos.setX(pos.x() - (m_containWidget->width() - width() - 3)); m_playedListWidget->selectPlayedRow(); m_menu->exec(pos); } void MusicPlayedListPopWidget::setDeleteItemAt(int index) { m_playedListWidget->clearPlayLaterState(); m_playlist->removeMedia(index); int id = m_playedListWidget->getPlayRowIndex(); m_playedListWidget->setPlayRowIndex(-1); if(id == index) { MusicApplication *w = MusicApplication::instance(); if(w->isPlaying()) { w->musicPlayNext(); } else { m_playlist->setCurrentIndex(); } if(m_playlist->isEmpty()) { setPlayEmpty(); } } else { m_playedListWidget->selectRow(id); } setPlayListCount(m_songLists.count()); } void MusicPlayedListPopWidget::setDeleteItemAll() { if(m_songLists.isEmpty()) { return; } int count = m_playedListWidget->rowCount(); for(int i=0; i<count; ++i) { m_playedListWidget->removeRow(0); } setPlayEmpty(); } void MusicPlayedListPopWidget::cellDoubleClicked(int row, int) { m_playlist->laterListClear(); m_playedListWidget->clearPlayLaterState(); MusicApplication::instance()->musicPlayedIndex(row); } void MusicPlayedListPopWidget::initWidget() { QHBoxLayout *layout = new QHBoxLayout(this); layout->setContentsMargins(0, 0, 0, 0); layout->setSpacing(2); layout->addStretch(2); for(int i=0; i<MAX_SIZE; ++i) { QLabel *label = new QLabel(this); label->setFixedWidth(9); label->setPixmap(QPixmap(":/tiny/lb_number0")); layout->addWidget(label); m_labels << label; } layout->addStretch(1); setLayout(layout); m_containWidget->setFixedSize(320, 400); QVBoxLayout *containLayout = new QVBoxLayout(m_containWidget); containLayout->setContentsMargins(0, 0, 0, 0); containLayout->setSpacing(0); containLayout->addWidget( createContainerWidget() ); m_scrollArea = new QScrollArea(this); m_scrollArea->setWidgetResizable(true); m_scrollArea->setFrameShape(QFrame::NoFrame); m_scrollArea->setFrameShadow(QFrame::Plain); m_scrollArea->setAlignment(Qt::AlignLeft); QString alphaStr = MusicUIObject::MBackgroundStyle17; QWidget *view = m_scrollArea->viewport(); view->setObjectName("viewport"); view->setStyleSheet(QString("#viewport{%1}").arg(alphaStr)); m_scrollArea->setStyleSheet(MusicUIObject::MScrollBarStyle01); m_playedListWidget = new MusicSongsListPlayedTableWidget(this); m_playedListWidget->setSongsFileName(&m_songLists); connect(m_playedListWidget, SIGNAL(setDeleteItemAt(int)), SLOT(setDeleteItemAt(int))); connect(m_playedListWidget, SIGNAL(cellDoubleClicked(int,int)), SLOT(cellDoubleClicked(int,int))); QWidget *playedListContainer = new QWidget(m_scrollArea); QVBoxLayout *playedListLayout = new QVBoxLayout(playedListContainer); playedListLayout->setContentsMargins(0, 0, 0, 0); playedListLayout->setSpacing(0); playedListLayout->addWidget(m_playedListWidget); playedListContainer->setLayout(playedListLayout); m_scrollArea->setWidget(playedListContainer); m_playedListWidget->setMovedScrollBar(m_scrollArea->verticalScrollBar()); containLayout->addWidget(m_scrollArea); m_containWidget->setLayout(containLayout); } QWidget *MusicPlayedListPopWidget::createContainerWidget() { QWidget *topWidget = new QWidget(this); topWidget->setFixedHeight(35); topWidget->setStyleSheet(MusicUIObject::MBackgroundStyle20); QHBoxLayout *topWidgetLayout = new QHBoxLayout(topWidget); topWidgetLayout->setSpacing(15); QLabel *label = new QLabel(tr("playedList"), topWidget); label->setStyleSheet(MusicUIObject::MColorStyle11 + MusicUIObject::MFontStyle01 + MusicUIObject::MFontStyle03); QPushButton *shareButton = new QPushButton(this); shareButton->setFixedSize(16, 16); shareButton->setToolTip(tr("shareList")); shareButton->setCursor(QCursor(Qt::PointingHandCursor)); shareButton->setStyleSheet(MusicUIObject::MKGTinyBtnShare); QPushButton *deleteButton = new QPushButton(this); deleteButton->setFixedSize(16, 16); deleteButton->setToolTip(tr("clearList")); deleteButton->setCursor(QCursor(Qt::PointingHandCursor)); deleteButton->setStyleSheet(MusicUIObject::MKGTinyBtnDelete); connect(deleteButton, SIGNAL(clicked()), SLOT(setDeleteItemAll())); #ifdef Q_OS_UNIX shareButton->setFocusPolicy(Qt::NoFocus); deleteButton->setFocusPolicy(Qt::NoFocus); #endif QToolButton *closeButton = new QToolButton(this); closeButton->setFixedSize(16, 16); closeButton->setToolTip(tr("closeList")); closeButton->setCursor(QCursor(Qt::PointingHandCursor)); closeButton->setStyleSheet(MusicUIObject::MKGTinyBtnClose); connect(closeButton, SIGNAL(clicked()), m_menu, SLOT(close())); topWidgetLayout->addWidget(label); topWidgetLayout->addStretch(1); topWidgetLayout->addWidget(shareButton); topWidgetLayout->addWidget(deleteButton); topWidgetLayout->addWidget(closeButton); topWidget->setLayout(topWidgetLayout); return topWidget; } void MusicPlayedListPopWidget::updateSongsFileName() { setPlayListCount(m_songLists.count()); m_playedListWidget->updateSongsFileName(m_songLists); } void MusicPlayedListPopWidget::setPlayListCount(int count) { if(count >= 1000) { for(int i=MAX_SIZE-1; i>=0; --i) { m_labels[i]->setPixmap(QPixmap(QString(":/tiny/lb_number%1").arg(9))); } } else { for(int i=MAX_SIZE-1; i>=0; --i) { m_labels[i]->setPixmap(QPixmap(QString(":/tiny/lb_number%1").arg(count%10))); count = count/10; } } } void MusicPlayedListPopWidget::setPlayEmpty() { m_playedListWidget->setPlayRowIndex(-1); m_songLists.clear(); setPlayListCount(0); MusicApplication::instance()->musicPlayIndex(-1); } <commit_msg>Fix played row delete error[632589]<commit_after>#include "musicplayedlistpopwidget.h" #include "musicfunctionuiobject.h" #include "musicsongslistplayedtablewidget.h" #include "musicsettingmanager.h" #include "musictinyuiobject.h" #include "musicuiobject.h" #include "musicapplication.h" #include "musicplayedlist.h" #include <QLabel> #include <QBoxLayout> #include <QPushButton> #include <QToolButton> #include <QScrollArea> #define MAX_SIZE 3 MusicPlayedListPopWidget *MusicPlayedListPopWidget::m_instance = nullptr; MusicPlayedListPopWidget::MusicPlayedListPopWidget(QWidget *parent) : MusicToolMenuWidget(parent) { m_instance = this; m_playlist = nullptr; setToolTip(tr("playedList")); setStyleSheet(MusicUIObject::MKGBtnPlayedList); disconnect(this, SIGNAL(clicked()), this, SLOT(popupMenu())); connect(this, SIGNAL(clicked()), SLOT(popupMenu())); initWidget(); } MusicPlayedListPopWidget::~MusicPlayedListPopWidget() { delete m_playedListWidget; qDeleteAll(m_labels); } QString MusicPlayedListPopWidget::getClassName() { return staticMetaObject.className(); } MusicPlayedListPopWidget *MusicPlayedListPopWidget::instance() { return m_instance; } void MusicPlayedListPopWidget::setPlaylist(MusicPlayedlist *playlist) { delete m_playlist; m_playlist = playlist; } MusicPlayedlist *MusicPlayedListPopWidget::playlist() const { return m_playlist; } void MusicPlayedListPopWidget::clear() { m_songLists.clear(); m_playedListWidget->clearAllItems(); setPlayListCount(0); } void MusicPlayedListPopWidget::resetToolIndex(const PairList &indexs) { MusicPlayedItems *items = m_playlist->mediaList(); for(int s=0; s<items->count(); ++s) { for(int i=0; i<indexs.count(); ++i) { const std::pair<int, int> &index = indexs[i]; if(items->at(s).m_toolIndex == index.first) { (*items)[s].m_toolIndex = index.second; break; } } } } void MusicPlayedListPopWidget::remove(int index) { if(index < 0 || index >= m_songLists.count()) { return; } m_playlist->removeMedia(index); m_songLists.removeAt(index); m_playedListWidget->replacePlayWidgetRow(); m_playedListWidget->removeRow(index); m_playedListWidget->setPlayRowIndex(-1); updateSongsFileName(); } void MusicPlayedListPopWidget::remove(int toolIndex, const QString &path) { int index = -1; m_playedListWidget->replacePlayWidgetRow(); do { index = m_playlist->removeMedia(toolIndex, path); if(index != -1) { m_songLists.removeAt(index); m_playedListWidget->removeRow(index); } }while(index != -1); m_playedListWidget->setPlayRowIndex(-1); updateSongsFileName(); } void MusicPlayedListPopWidget::remove(int toolIndex, const MusicSong &song) { remove(toolIndex, song.getMusicPath()); } void MusicPlayedListPopWidget::append(int toolIndex, const MusicSong &song) { m_playlist->appendMedia(toolIndex, song.getMusicPath()); m_songLists << song; updateSongsFileName(); } void MusicPlayedListPopWidget::append(const MusicSongs &song) { clear(); m_songLists = song; updateSongsFileName(); } void MusicPlayedListPopWidget::insert(int toolIndex, const MusicSong &song) { insert(toolIndex, m_playedListWidget->getPlayRowIndex() + 1, song); } void MusicPlayedListPopWidget::insert(int toolIndex, int index, const MusicSong &song) { if(index < 0 || index > m_songLists.count()) { return; } (index != m_songLists.count()) ? m_songLists.insert(index, song) : m_songLists.append(song); m_playlist->insertLaterMedia(toolIndex, song.getMusicPath()); int row = m_playedListWidget->getPlayRowIndex(); m_playedListWidget->clearAllItems(); updateSongsFileName(); m_playedListWidget->setPlayRowIndex(row); m_playedListWidget->selectPlayedRow(); foreach(const MusicPlayedItem &item, m_playlist->laterListConst()) { m_playedListWidget->setPlayLaterState(item.m_toolIndex); } } void MusicPlayedListPopWidget::setCurrentIndex() { int index = m_playlist->currentIndex(); m_playedListWidget->selectRow(index); } void MusicPlayedListPopWidget::setCurrentIndex(int toolIndex, const MusicSong &song) { m_playlist->setCurrentIndex(toolIndex, song.getMusicPath()); setCurrentIndex(); } void MusicPlayedListPopWidget::resizeWindow() { // int h = M_SETTING_PTR->value(MusicSettingManager::WidgetSize).toSize().height(); // m_containWidget->setFixedSize(300, 500 + h - WINDOW_HEIGHT_MIN); } void MusicPlayedListPopWidget::popupMenu() { QPoint pos = mapToGlobal(QPoint(0, 0)); pos.setY(pos.y() - m_containWidget->height() - 10); pos.setX(pos.x() - (m_containWidget->width() - width() - 3)); m_playedListWidget->selectPlayedRow(); m_menu->exec(pos); } void MusicPlayedListPopWidget::setDeleteItemAt(int index) { m_playedListWidget->clearPlayLaterState(); m_playlist->removeMedia(index); int id = m_playedListWidget->getPlayRowIndex(); m_playedListWidget->setPlayRowIndex(-1); if(id == index) { MusicApplication *w = MusicApplication::instance(); if(w->isPlaying()) { w->musicPlayNext(); } else { m_playlist->setCurrentIndex(); } if(m_playlist->isEmpty()) { setPlayEmpty(); } } else { m_playedListWidget->selectRow(id); } setPlayListCount(m_songLists.count()); } void MusicPlayedListPopWidget::setDeleteItemAll() { if(m_songLists.isEmpty()) { return; } m_playedListWidget->replacePlayWidgetRow(); int count = m_playedListWidget->rowCount(); for(int i=0; i<count; ++i) { m_playedListWidget->removeRow(0); } setPlayEmpty(); } void MusicPlayedListPopWidget::cellDoubleClicked(int row, int) { m_playlist->laterListClear(); m_playedListWidget->clearPlayLaterState(); MusicApplication::instance()->musicPlayedIndex(row); } void MusicPlayedListPopWidget::initWidget() { QHBoxLayout *layout = new QHBoxLayout(this); layout->setContentsMargins(0, 0, 0, 0); layout->setSpacing(2); layout->addStretch(2); for(int i=0; i<MAX_SIZE; ++i) { QLabel *label = new QLabel(this); label->setFixedWidth(9); label->setPixmap(QPixmap(":/tiny/lb_number0")); layout->addWidget(label); m_labels << label; } layout->addStretch(1); setLayout(layout); m_containWidget->setFixedSize(320, 400); QVBoxLayout *containLayout = new QVBoxLayout(m_containWidget); containLayout->setContentsMargins(0, 0, 0, 0); containLayout->setSpacing(0); containLayout->addWidget( createContainerWidget() ); m_scrollArea = new QScrollArea(this); m_scrollArea->setWidgetResizable(true); m_scrollArea->setFrameShape(QFrame::NoFrame); m_scrollArea->setFrameShadow(QFrame::Plain); m_scrollArea->setAlignment(Qt::AlignLeft); QString alphaStr = MusicUIObject::MBackgroundStyle17; QWidget *view = m_scrollArea->viewport(); view->setObjectName("viewport"); view->setStyleSheet(QString("#viewport{%1}").arg(alphaStr)); m_scrollArea->setStyleSheet(MusicUIObject::MScrollBarStyle01); m_playedListWidget = new MusicSongsListPlayedTableWidget(this); m_playedListWidget->setSongsFileName(&m_songLists); connect(m_playedListWidget, SIGNAL(setDeleteItemAt(int)), SLOT(setDeleteItemAt(int))); connect(m_playedListWidget, SIGNAL(cellDoubleClicked(int,int)), SLOT(cellDoubleClicked(int,int))); QWidget *playedListContainer = new QWidget(m_scrollArea); QVBoxLayout *playedListLayout = new QVBoxLayout(playedListContainer); playedListLayout->setContentsMargins(0, 0, 0, 0); playedListLayout->setSpacing(0); playedListLayout->addWidget(m_playedListWidget); playedListContainer->setLayout(playedListLayout); m_scrollArea->setWidget(playedListContainer); m_playedListWidget->setMovedScrollBar(m_scrollArea->verticalScrollBar()); containLayout->addWidget(m_scrollArea); m_containWidget->setLayout(containLayout); } QWidget *MusicPlayedListPopWidget::createContainerWidget() { QWidget *topWidget = new QWidget(this); topWidget->setFixedHeight(35); topWidget->setStyleSheet(MusicUIObject::MBackgroundStyle20); QHBoxLayout *topWidgetLayout = new QHBoxLayout(topWidget); topWidgetLayout->setSpacing(15); QLabel *label = new QLabel(tr("playedList"), topWidget); label->setStyleSheet(MusicUIObject::MColorStyle11 + MusicUIObject::MFontStyle01 + MusicUIObject::MFontStyle03); QPushButton *shareButton = new QPushButton(this); shareButton->setFixedSize(16, 16); shareButton->setToolTip(tr("shareList")); shareButton->setCursor(QCursor(Qt::PointingHandCursor)); shareButton->setStyleSheet(MusicUIObject::MKGTinyBtnShare); QPushButton *deleteButton = new QPushButton(this); deleteButton->setFixedSize(16, 16); deleteButton->setToolTip(tr("clearList")); deleteButton->setCursor(QCursor(Qt::PointingHandCursor)); deleteButton->setStyleSheet(MusicUIObject::MKGTinyBtnDelete); connect(deleteButton, SIGNAL(clicked()), SLOT(setDeleteItemAll())); #ifdef Q_OS_UNIX shareButton->setFocusPolicy(Qt::NoFocus); deleteButton->setFocusPolicy(Qt::NoFocus); #endif QToolButton *closeButton = new QToolButton(this); closeButton->setFixedSize(16, 16); closeButton->setToolTip(tr("closeList")); closeButton->setCursor(QCursor(Qt::PointingHandCursor)); closeButton->setStyleSheet(MusicUIObject::MKGTinyBtnClose); connect(closeButton, SIGNAL(clicked()), m_menu, SLOT(close())); topWidgetLayout->addWidget(label); topWidgetLayout->addStretch(1); topWidgetLayout->addWidget(shareButton); topWidgetLayout->addWidget(deleteButton); topWidgetLayout->addWidget(closeButton); topWidget->setLayout(topWidgetLayout); return topWidget; } void MusicPlayedListPopWidget::updateSongsFileName() { setPlayListCount(m_songLists.count()); m_playedListWidget->updateSongsFileName(m_songLists); } void MusicPlayedListPopWidget::setPlayListCount(int count) { if(count >= 1000) { for(int i=MAX_SIZE-1; i>=0; --i) { m_labels[i]->setPixmap(QPixmap(QString(":/tiny/lb_number%1").arg(9))); } } else { for(int i=MAX_SIZE-1; i>=0; --i) { m_labels[i]->setPixmap(QPixmap(QString(":/tiny/lb_number%1").arg(count%10))); count = count/10; } } } void MusicPlayedListPopWidget::setPlayEmpty() { m_playedListWidget->setPlayRowIndex(-1); m_songLists.clear(); setPlayListCount(0); MusicApplication::instance()->musicPlayIndex(-1); } <|endoftext|>
<commit_before>/* This file is part of the ORK library. Full copyright and license terms can be found in the LICENSE.txt file. */ #pragma once #ifndef ORK_ORK_HPP #error This header can only be included from ork/common.hpp! #endif #include"ork/detail/text.hpp" #include"ork/detail/exception.hpp" namespace ork { #define ORK_WARN_(MSG) ORK_CAT3(ORK_FLOC, ORK(": Warning: "), ORK(MSG)) #if defined _MSC_VER #define ORK_VSWARNING(MSG) message(ORK_WARN_(MSG)) #else #define ORK_VSWARNING(MSG) #endif //Make the code execute as one statement; used because it could be more exotic(per-platform) in the future. #define ORK_STMT(CODE) {CODE} //do{CODE}while(false); #if defined _MSC_VER #define ORK_INLINE __forceinline #elif defined __GNUC__ #define ORK_INLINE __attribute__((always_inline)) inline #else #error "Compiler not supported" #endif #if defined __GNUC__ || _MSC_VER > 1800 #define ORK_NO_EXCEPT noexcept #else #define ORK_NO_EXCEPT//throw() #endif #define ORK_UNREACHABLE ORK_THROW(ORK("Unreachable")); /*** Begin Looping section. Macros to simplify basic loops. This may seem like overkill,but the loop headers are easier to type, less error prone,and consistently optimized. ***/ #define LOOP_(LIMIT,INDEX)for(size_t INDEX=0;INDEX!=LIMIT;++INDEX) #define LOOPI(LIMIT)LOOP_(LIMIT,i) #define LOOPJ(LIMIT)LOOP_(LIMIT,j) #define LOOPK(LIMIT)LOOP_(LIMIT,k) #define LOOPL(LIMIT)LOOP_(LIMIT,l) #define LOOPR(LIMIT,INDEX)for(size_t INDEX=LIMIT;INDEX--!=0;/*Do Nothing*/) #define LOOPRI(LIMIT)LOOPR(LIMIT,i) #define LOOPRJ(LIMIT)LOOPR(LIMIT,j) #define LOOPRK(LIMIT)LOOPR(LIMIT,k) #define LOOPRL(LIMIT)LOOPR(LIMIT,l) /*Loops over vectors, the limit variable must be obviously constant for the compiler to vectorize anything.*/ #define LOOPV(SERIES,INDEX)for(size_t INDEX=0,limit##INDEX=SERIES.size();INDEX!=limit##INDEX;++INDEX) #define LOOPVI(SERIES)LOOPV(SERIES,i) #define LOOPVJ(SERIES)LOOPV(SERIES,j) #define LOOPVK(SERIES)LOOPV(SERIES,k) #define LOOPVL(SERIES)LOOPV(SERIES,l) #define ORK_EMPTY_ /*Empty*/ /* Copy and move semantics */ #define ORK_COPY_(TYPE)\ TYPE(const TYPE&)=default;\ TYPE&operator=(const TYPE&)=default; #if defined __GNUC__ || _MSC_VER > 1700//VS 2013 or later #define ORK_NO_COPY_(TYPE)\ TYPE(const TYPE&)=delete;\ TYPE&operator=(const TYPE&)=delete; #define ORK_NO_MOVE_(TYPE)\ TYPE(TYPE&&)=delete;\ TYPE&operator=(TYPE&&)=delete; #define ORK_MOVE_(TYPE)\ TYPE(TYPE&&)=default;\ TYPE&operator=(TYPE&&)=default; #else #define ORK_NO_COPY_(TYPE)\ private:\ TYPE(const TYPE&);\ TYPE&operator=(const TYPE&); #define ORK_NO_MOVE_(TYPE) ORK_EMPTY_ #define ORK_MOVE_(TYPE) ORK_EMPTY_ #endif #define ORK_NON_COPYABLE(TYPE) ORK_NO_COPY_(TYPE) ORK_NO_MOVE_(TYPE) #if defined __GNUC__ || _MSC_VER > 1700//VS 2013 or later #define ORK_MOVE_ONLY(TYPE) ORK_NO_COPY_(TYPE) ORK_MOVE_(TYPE) #define ORK_MOVEABLE(TYPE) ORK_COPY_(TYPE) ORK_MOVE_(TYPE) #endif /* The macros below provide more control over construction, including insertion of code in both the constructor and assignment operator. These macros also support VS 2012. */ //Construction #define ORK_CMOVE_(M) M(std::move(rhs.M)) #define ORK_CMOVE_1_(M1) ORK_CMOVE_(M1) #define ORK_CMOVE_2_(M1,M2) ORK_CMOVE_1_(M1), ORK_CMOVE_(M2) #define ORK_CMOVE_3_(M1,M2,M3) ORK_CMOVE_2_(M1,M2), ORK_CMOVE_(M3) #define ORK_CMOVE_4_(M1,M2,M3,M4) ORK_CMOVE_3_(M1,M2,M3), ORK_CMOVE_(M4) #define ORK_CMOVE_5_(M1,M2,M3,M4,M5) ORK_CMOVE_4_(M1,M2,M3,M4), ORK_CMOVE_(M5) //Assignment #define ORK_AMOVE_(M) M=std::move(rhs.M); #define ORK_AMOVE_1_(M1) ORK_AMOVE_(M1) #define ORK_AMOVE_2_(M1,M2) ORK_AMOVE_1_(M1) ORK_AMOVE_(M2) #define ORK_AMOVE_3_(M1,M2,M3) ORK_AMOVE_2_(M1,M2) ORK_AMOVE_(M3) #define ORK_AMOVE_4_(M1,M2,M3,M4) ORK_AMOVE_3_(M1,M2,M3) ORK_AMOVE_(M4) #define ORK_AMOVE_5_(M1,M2,M3,M4,M5) ORK_AMOVE_4_(M1,M2,M3,M4) ORK_AMOVE_(M5) /* This constructor somewhat surreptitiously inserts noexcept but a throwing move constructor is pointless anyway */ #define ORK_MOVE_CONSTRUCT_(TYPE,CODE)\ public:\ TYPE(TYPE&&rhs)ORK_NO_EXCEPT:CODE{ /*Constructor body here*/ #define ORK_MOVE_ASSIGN_(TYPE,CODE)\ }\ public:\ TYPE&operator=(TYPE&&rhs)ORK_NO_EXCEPT{\ if(this!=&rhs){\ CODE /*Assignment body here*/ #define ORK_MOVE_END_\ }\ return *this;\ } /* These macros wrap up functionality. The first inserts the same code in the constuctor and assigment operator. The second inserts no code. */ #define ORK_MOVE_CON1_(TYPE,M1) ORK_MOVE_CONSTRUCT_(TYPE,ORK_CMOVE_1_(M1)) #define ORK_MOVE_CON2_(TYPE,M1,M2) ORK_MOVE_CONSTRUCT_(TYPE,ORK_CMOVE_2_(M1,M2)) #define ORK_MOVE_CON3_(TYPE,M1,M2,M3) ORK_MOVE_CONSTRUCT_(TYPE,ORK_CMOVE_3_(M1,M2,M3)) #define ORK_MOVE_CON4_(TYPE,M1,M2,M3,M4) ORK_MOVE_CONSTRUCT_(TYPE,ORK_CMOVE_4_(M1,M2,M3,M4)) #define ORK_MOVE_CON5_(TYPE,M1,M2,M3,M4,M5) ORK_MOVE_CONSTRUCT_(TYPE,ORK_CMOVE_5_(M1,M2,M3,M4,M5)) #define ORK_MOVE_OP1_(TYPE,M1) ORK_MOVE_ASSIGN_(TYPE,ORK_AMOVE_1_(M1)) #define ORK_MOVE_OP2_(TYPE,M1,M2) ORK_MOVE_ASSIGN_(TYPE,ORK_AMOVE_2_(M1,M2)) #define ORK_MOVE_OP3_(TYPE,M1,M2,M3) ORK_MOVE_ASSIGN_(TYPE,ORK_AMOVE_3_(M1,M2,M3)) #define ORK_MOVE_OP4_(TYPE,M1,M2,M3,M4) ORK_MOVE_ASSIGN_(TYPE,ORK_AMOVE_4_(M1,M2,M3,M4)) #define ORK_MOVE_OP5_(TYPE,M1,M2,M3,M4,M5) ORK_MOVE_ASSIGN_(TYPE,ORK_AMOVE_5_(M1,M2,M3,M4,M5)) #define ORK_MOVE_1_(TYPE,M1,CODE) ORK_MOVE_CON1_(TYPE,M1) CODE ORK_MOVE_OP1_(TYPE,M1) CODE ORK_MOVE_END_ #define ORK_MOVE_2_(TYPE,M1,M2,CODE) ORK_MOVE_CON2_(TYPE,M1,M2) CODE ORK_MOVE_OP2_(TYPE,M1,M2) CODE ORK_MOVE_END_ #define ORK_MOVE_3_(TYPE,M1,M2,M3,CODE) ORK_MOVE_CON3_(TYPE,M1,M2,M3) CODE ORK_MOVE_OP3_(TYPE,M1,M2,M3) CODE ORK_MOVE_END_ #define ORK_MOVE_4_(TYPE,M1,M2,M3,M4,CODE) ORK_MOVE_CON4_(TYPE,M1,M2,M3,M4) CODE ORK_MOVE_OP4_(TYPE,M1,M2,M3,M4) CODE ORK_MOVE_END_ #define ORK_MOVE_5_(TYPE,M1,M2,M3,M4,M5,CODE) ORK_MOVE_CON5_(TYPE,M1,M2,M3,M4,M5) CODE ORK_MOVE_OP5_(TYPE,M1,M2,M3,M4,M5) CODE ORK_MOVE_END_ #define ORK_MOVEABLE_1(TYPE,M1) ORK_COPY_(TYPE) ORK_MOVE_1_(TYPE,M1,ORK_EMPTY_) #define ORK_MOVEABLE_2(TYPE,M1,M2) ORK_COPY_(TYPE) ORK_MOVE_2_(TYPE,M1,M2,ORK_EMPTY_) #define ORK_MOVEABLE_3(TYPE,M1,M2,M3) ORK_COPY_(TYPE) ORK_MOVE_3_(TYPE,M1,M2,M3,ORK_EMPTY_) #define ORK_MOVEABLE_4(TYPE,M1,M2,M3,M4) ORK_COPY_(TYPE) ORK_MOVE_4_(TYPE,M1,M2,M3,M4,ORK_EMPTY_) #define ORK_MOVEABLE_5(TYPE,M1,M2,M3,M4,M5) ORK_COPY_(TYPE) ORK_MOVE_5_(TYPE,M1,M2,M3,M4,M5,ORK_EMPTY_) #define ORK_MOVE_ONLY_1(TYPE,M1) ORK_NO_COPY_(TYPE) ORK_MOVE_1_(TYPE,M1,ORK_EMPTY_) #define ORK_MOVE_ONLY_2(TYPE,M1,M2) ORK_NO_COPY_(TYPE) ORK_MOVE_2_(TYPE,M1,M2,ORK_EMPTY_) #define ORK_MOVE_ONLY_3(TYPE,M1,M2,M3) ORK_NO_COPY_(TYPE) ORK_MOVE_3_(TYPE,M1,M2,M3,ORK_EMPTY_) #define ORK_MOVE_ONLY_4(TYPE,M1,M2,M3,M4) ORK_NO_COPY_(TYPE) ORK_MOVE_4_(TYPE,M1,M2,M3,M4,ORK_EMPTY_) #define ORK_MOVE_ONLY_5(TYPE,M1,M2,M3,M4,M5) ORK_NO_COPY_(TYPE) ORK_MOVE_5_(TYPE,M1,M2,M3,M4,M5,ORK_EMPTY_) }//namespace ork <commit_msg>Added a constexpr macro<commit_after>/* This file is part of the ORK library. Full copyright and license terms can be found in the LICENSE.txt file. */ #pragma once #ifndef ORK_ORK_HPP #error This header can only be included from ork/common.hpp! #endif #include"ork/detail/text.hpp" #include"ork/detail/exception.hpp" namespace ork { #define ORK_WARN_(MSG) ORK_CAT3(ORK_FLOC, ORK(": Warning: "), ORK(MSG)) #if defined _MSC_VER #define ORK_VSWARNING(MSG) message(ORK_WARN_(MSG)) #else #define ORK_VSWARNING(MSG) #endif //Make the code execute as one statement; used because it could be more exotic(per-platform) in the future. #define ORK_STMT(CODE) {CODE} //do{CODE}while(false); #if defined _MSC_VER #define ORK_INLINE __forceinline #elif defined __GNUC__ #define ORK_INLINE __attribute__((always_inline)) inline #else #error "Compiler not supported" #endif #if defined __GNUC__ || _MSC_VER > 1800 #define ORK_NO_EXCEPT noexcept #define ORK_CONSTEXPR constexpr #else #define ORK_NO_EXCEPT//throw() #define ORK_CONSTEXPR #endif #define ORK_UNREACHABLE ORK_THROW(ORK("Unreachable")); /*** Begin Looping section. Macros to simplify basic loops. This may seem like overkill,but the loop headers are easier to type, less error prone,and consistently optimized. ***/ #define LOOP_(LIMIT,INDEX)for(size_t INDEX=0;INDEX!=LIMIT;++INDEX) #define LOOPI(LIMIT)LOOP_(LIMIT,i) #define LOOPJ(LIMIT)LOOP_(LIMIT,j) #define LOOPK(LIMIT)LOOP_(LIMIT,k) #define LOOPL(LIMIT)LOOP_(LIMIT,l) #define LOOPR(LIMIT,INDEX)for(size_t INDEX=LIMIT;INDEX--!=0;/*Do Nothing*/) #define LOOPRI(LIMIT)LOOPR(LIMIT,i) #define LOOPRJ(LIMIT)LOOPR(LIMIT,j) #define LOOPRK(LIMIT)LOOPR(LIMIT,k) #define LOOPRL(LIMIT)LOOPR(LIMIT,l) /*Loops over vectors, the limit variable must be obviously constant for the compiler to vectorize anything.*/ #define LOOPV(SERIES,INDEX)for(size_t INDEX=0,limit##INDEX=SERIES.size();INDEX!=limit##INDEX;++INDEX) #define LOOPVI(SERIES)LOOPV(SERIES,i) #define LOOPVJ(SERIES)LOOPV(SERIES,j) #define LOOPVK(SERIES)LOOPV(SERIES,k) #define LOOPVL(SERIES)LOOPV(SERIES,l) #define ORK_EMPTY_ /*Empty*/ /* Copy and move semantics */ #define ORK_COPY_(TYPE)\ TYPE(const TYPE&)=default;\ TYPE&operator=(const TYPE&)=default; #if defined __GNUC__ || _MSC_VER > 1700//VS 2013 or later #define ORK_NO_COPY_(TYPE)\ TYPE(const TYPE&)=delete;\ TYPE&operator=(const TYPE&)=delete; #define ORK_NO_MOVE_(TYPE)\ TYPE(TYPE&&)=delete;\ TYPE&operator=(TYPE&&)=delete; #define ORK_MOVE_(TYPE)\ TYPE(TYPE&&)=default;\ TYPE&operator=(TYPE&&)=default; #else #define ORK_NO_COPY_(TYPE)\ private:\ TYPE(const TYPE&);\ TYPE&operator=(const TYPE&); #define ORK_NO_MOVE_(TYPE) ORK_EMPTY_ #define ORK_MOVE_(TYPE) ORK_EMPTY_ #endif #define ORK_NON_COPYABLE(TYPE) ORK_NO_COPY_(TYPE) ORK_NO_MOVE_(TYPE) #if defined __GNUC__ || _MSC_VER > 1700//VS 2013 or later #define ORK_MOVE_ONLY(TYPE) ORK_NO_COPY_(TYPE) ORK_MOVE_(TYPE) #define ORK_MOVEABLE(TYPE) ORK_COPY_(TYPE) ORK_MOVE_(TYPE) #endif /* The macros below provide more control over construction, including insertion of code in both the constructor and assignment operator. These macros also support VS 2012. */ //Construction #define ORK_CMOVE_(M) M(std::move(rhs.M)) #define ORK_CMOVE_1_(M1) ORK_CMOVE_(M1) #define ORK_CMOVE_2_(M1,M2) ORK_CMOVE_1_(M1), ORK_CMOVE_(M2) #define ORK_CMOVE_3_(M1,M2,M3) ORK_CMOVE_2_(M1,M2), ORK_CMOVE_(M3) #define ORK_CMOVE_4_(M1,M2,M3,M4) ORK_CMOVE_3_(M1,M2,M3), ORK_CMOVE_(M4) #define ORK_CMOVE_5_(M1,M2,M3,M4,M5) ORK_CMOVE_4_(M1,M2,M3,M4), ORK_CMOVE_(M5) //Assignment #define ORK_AMOVE_(M) M=std::move(rhs.M); #define ORK_AMOVE_1_(M1) ORK_AMOVE_(M1) #define ORK_AMOVE_2_(M1,M2) ORK_AMOVE_1_(M1) ORK_AMOVE_(M2) #define ORK_AMOVE_3_(M1,M2,M3) ORK_AMOVE_2_(M1,M2) ORK_AMOVE_(M3) #define ORK_AMOVE_4_(M1,M2,M3,M4) ORK_AMOVE_3_(M1,M2,M3) ORK_AMOVE_(M4) #define ORK_AMOVE_5_(M1,M2,M3,M4,M5) ORK_AMOVE_4_(M1,M2,M3,M4) ORK_AMOVE_(M5) /* This constructor somewhat surreptitiously inserts noexcept but a throwing move constructor is pointless anyway */ #define ORK_MOVE_CONSTRUCT_(TYPE,CODE)\ public:\ TYPE(TYPE&&rhs)ORK_NO_EXCEPT:CODE{ /*Constructor body here*/ #define ORK_MOVE_ASSIGN_(TYPE,CODE)\ }\ public:\ TYPE&operator=(TYPE&&rhs)ORK_NO_EXCEPT{\ if(this!=&rhs){\ CODE /*Assignment body here*/ #define ORK_MOVE_END_\ }\ return *this;\ } /* These macros wrap up functionality. The first inserts the same code in the constuctor and assigment operator. The second inserts no code. */ #define ORK_MOVE_CON1_(TYPE,M1) ORK_MOVE_CONSTRUCT_(TYPE,ORK_CMOVE_1_(M1)) #define ORK_MOVE_CON2_(TYPE,M1,M2) ORK_MOVE_CONSTRUCT_(TYPE,ORK_CMOVE_2_(M1,M2)) #define ORK_MOVE_CON3_(TYPE,M1,M2,M3) ORK_MOVE_CONSTRUCT_(TYPE,ORK_CMOVE_3_(M1,M2,M3)) #define ORK_MOVE_CON4_(TYPE,M1,M2,M3,M4) ORK_MOVE_CONSTRUCT_(TYPE,ORK_CMOVE_4_(M1,M2,M3,M4)) #define ORK_MOVE_CON5_(TYPE,M1,M2,M3,M4,M5) ORK_MOVE_CONSTRUCT_(TYPE,ORK_CMOVE_5_(M1,M2,M3,M4,M5)) #define ORK_MOVE_OP1_(TYPE,M1) ORK_MOVE_ASSIGN_(TYPE,ORK_AMOVE_1_(M1)) #define ORK_MOVE_OP2_(TYPE,M1,M2) ORK_MOVE_ASSIGN_(TYPE,ORK_AMOVE_2_(M1,M2)) #define ORK_MOVE_OP3_(TYPE,M1,M2,M3) ORK_MOVE_ASSIGN_(TYPE,ORK_AMOVE_3_(M1,M2,M3)) #define ORK_MOVE_OP4_(TYPE,M1,M2,M3,M4) ORK_MOVE_ASSIGN_(TYPE,ORK_AMOVE_4_(M1,M2,M3,M4)) #define ORK_MOVE_OP5_(TYPE,M1,M2,M3,M4,M5) ORK_MOVE_ASSIGN_(TYPE,ORK_AMOVE_5_(M1,M2,M3,M4,M5)) #define ORK_MOVE_1_(TYPE,M1,CODE) ORK_MOVE_CON1_(TYPE,M1) CODE ORK_MOVE_OP1_(TYPE,M1) CODE ORK_MOVE_END_ #define ORK_MOVE_2_(TYPE,M1,M2,CODE) ORK_MOVE_CON2_(TYPE,M1,M2) CODE ORK_MOVE_OP2_(TYPE,M1,M2) CODE ORK_MOVE_END_ #define ORK_MOVE_3_(TYPE,M1,M2,M3,CODE) ORK_MOVE_CON3_(TYPE,M1,M2,M3) CODE ORK_MOVE_OP3_(TYPE,M1,M2,M3) CODE ORK_MOVE_END_ #define ORK_MOVE_4_(TYPE,M1,M2,M3,M4,CODE) ORK_MOVE_CON4_(TYPE,M1,M2,M3,M4) CODE ORK_MOVE_OP4_(TYPE,M1,M2,M3,M4) CODE ORK_MOVE_END_ #define ORK_MOVE_5_(TYPE,M1,M2,M3,M4,M5,CODE) ORK_MOVE_CON5_(TYPE,M1,M2,M3,M4,M5) CODE ORK_MOVE_OP5_(TYPE,M1,M2,M3,M4,M5) CODE ORK_MOVE_END_ #define ORK_MOVEABLE_1(TYPE,M1) ORK_COPY_(TYPE) ORK_MOVE_1_(TYPE,M1,ORK_EMPTY_) #define ORK_MOVEABLE_2(TYPE,M1,M2) ORK_COPY_(TYPE) ORK_MOVE_2_(TYPE,M1,M2,ORK_EMPTY_) #define ORK_MOVEABLE_3(TYPE,M1,M2,M3) ORK_COPY_(TYPE) ORK_MOVE_3_(TYPE,M1,M2,M3,ORK_EMPTY_) #define ORK_MOVEABLE_4(TYPE,M1,M2,M3,M4) ORK_COPY_(TYPE) ORK_MOVE_4_(TYPE,M1,M2,M3,M4,ORK_EMPTY_) #define ORK_MOVEABLE_5(TYPE,M1,M2,M3,M4,M5) ORK_COPY_(TYPE) ORK_MOVE_5_(TYPE,M1,M2,M3,M4,M5,ORK_EMPTY_) #define ORK_MOVE_ONLY_1(TYPE,M1) ORK_NO_COPY_(TYPE) ORK_MOVE_1_(TYPE,M1,ORK_EMPTY_) #define ORK_MOVE_ONLY_2(TYPE,M1,M2) ORK_NO_COPY_(TYPE) ORK_MOVE_2_(TYPE,M1,M2,ORK_EMPTY_) #define ORK_MOVE_ONLY_3(TYPE,M1,M2,M3) ORK_NO_COPY_(TYPE) ORK_MOVE_3_(TYPE,M1,M2,M3,ORK_EMPTY_) #define ORK_MOVE_ONLY_4(TYPE,M1,M2,M3,M4) ORK_NO_COPY_(TYPE) ORK_MOVE_4_(TYPE,M1,M2,M3,M4,ORK_EMPTY_) #define ORK_MOVE_ONLY_5(TYPE,M1,M2,M3,M4,M5) ORK_NO_COPY_(TYPE) ORK_MOVE_5_(TYPE,M1,M2,M3,M4,M5,ORK_EMPTY_) }//namespace ork <|endoftext|>
<commit_before>// This file is a part of the IncludeOS unikernel - www.includeos.org // // Copyright 2015 Oslo and Akershus University College of Applied Sciences // and Alfred Bratterud // // 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. #pragma once #ifndef FS_DISK_HPP #define FS_DISK_HPP #include "common.hpp" #include <fs/filesystem.hpp> #include <fs/dirent.hpp> #include <hw/block_device.hpp> #include <deque> #include <vector> #include <functional> namespace fs { /** * Class to initialize file systems on block devices / partitions **/ class Disk { public: class Err_not_mounted : public std::runtime_error { using runtime_error::runtime_error; }; struct Partition; using on_parts_func = delegate<void(fs::error_t, std::vector<Partition>&)>; using on_init_func = delegate<void(fs::error_t, File_system&)>; using lba_t = uint32_t; enum partition_t { MBR = 0, //< Master Boot Record (0) VBR1, //> extended partitions (1-4) VBR2, VBR3, VBR4, }; struct Partition { explicit Partition(const uint8_t fl, const uint8_t Id, const uint32_t LBA, const uint32_t sz) noexcept : flags {fl}, id {Id}, lba_begin {LBA}, sectors {sz} {} uint8_t flags; uint8_t id; uint32_t lba_begin; uint32_t sectors; // true if the partition has boot code / is bootable bool is_boot() const noexcept { return flags & 0x1; } // human-readable name of partition id std::string name() const; // logical block address of beginning of partition uint32_t lba() const { return lba_begin; } }; //< struct Partition //************** disk functions **************// // construct a disk with a given block-device explicit Disk(hw::Block_device&); // returns the device the disk is using hw::Block_device& dev() noexcept { return device; } // Returns true if the disk has no sectors bool empty() const noexcept { return device.size() == 0; } // Initializes file system on the first partition detected (MBR -> VBR1-4 -> ext) // NOTE: Always detects and instantiates a FAT filesystem void init_fs(on_init_func func); // Initialize file system on specified partition // NOTE: Always detects and instantiates a FAT filesystem void init_fs(partition_t part, on_init_func func); // mount custom filesystem on MBR or VBRn template <class T, class... Args> void init_fs(Args&&... args, partition_t part, on_init_func func) { // construct custom filesystem filesys.reset(new T(args...)); internal_init(part, func); } std::string name() { return device.device_name(); } auto device_id() { return device.id(); } // Creates a vector of the partitions on disk (see: on_parts_func) // Note: No file system needs to be initialized beforehand void partitions(on_parts_func func); // returns true if a filesystem is initialized bool fs_ready() const noexcept { return (bool) filesys; } // Returns a reference to a mounted filesystem // If no filesystem is mounted, the results are undefined File_system& fs() noexcept { return *filesys; } private: void internal_init(partition_t part, on_init_func func); hw::Block_device& device; std::unique_ptr<File_system> filesys; }; //< class Disk using Disk_ptr = std::shared_ptr<Disk>; } //< namespace fs #endif //< FS_DISK_HPP <commit_msg>fs: Disk now throws if accessing uninitialized fs<commit_after>// This file is a part of the IncludeOS unikernel - www.includeos.org // // Copyright 2015 Oslo and Akershus University College of Applied Sciences // and Alfred Bratterud // // 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. #pragma once #ifndef FS_DISK_HPP #define FS_DISK_HPP #include "common.hpp" #include <fs/filesystem.hpp> #include <fs/dirent.hpp> #include <hw/block_device.hpp> #include <common> #include <deque> #include <vector> #include <functional> namespace fs { /** * Class to initialize file systems on block devices / partitions **/ class Disk { public: class Err_not_mounted : public std::runtime_error { using runtime_error::runtime_error; }; struct Partition; using on_parts_func = delegate<void(fs::error_t, std::vector<Partition>&)>; using on_init_func = delegate<void(fs::error_t, File_system&)>; using lba_t = uint32_t; enum partition_t { MBR = 0, //< Master Boot Record (0) VBR1, //> extended partitions (1-4) VBR2, VBR3, VBR4, }; struct Partition { explicit Partition(const uint8_t fl, const uint8_t Id, const uint32_t LBA, const uint32_t sz) noexcept : flags {fl}, id {Id}, lba_begin {LBA}, sectors {sz} {} uint8_t flags; uint8_t id; uint32_t lba_begin; uint32_t sectors; // true if the partition has boot code / is bootable bool is_boot() const noexcept { return flags & 0x1; } // human-readable name of partition id std::string name() const; // logical block address of beginning of partition uint32_t lba() const { return lba_begin; } }; //< struct Partition //************** disk functions **************// // construct a disk with a given block-device explicit Disk(hw::Block_device&); // returns the device the disk is using hw::Block_device& dev() noexcept { return device; } // Returns true if the disk has no sectors bool empty() const noexcept { return device.size() == 0; } // Initializes file system on the first partition detected (MBR -> VBR1-4 -> ext) // NOTE: Always detects and instantiates a FAT filesystem void init_fs(on_init_func func); // Initialize file system on specified partition // NOTE: Always detects and instantiates a FAT filesystem void init_fs(partition_t part, on_init_func func); // mount custom filesystem on MBR or VBRn template <class T, class... Args> void init_fs(Args&&... args, partition_t part, on_init_func func) { // construct custom filesystem filesys.reset(new T(args...)); internal_init(part, func); } std::string name() { return device.device_name(); } auto device_id() { return device.id(); } // Creates a vector of the partitions on disk (see: on_parts_func) // Note: No file system needs to be initialized beforehand void partitions(on_parts_func func); // returns true if a filesystem is initialized bool fs_ready() const noexcept { return (bool) filesys; } // Returns a reference to a mounted filesystem // If no filesystem is mounted, the results are undefined File_system& fs() noexcept { if(UNLIKELY(not fs_ready())) { throw Err_not_mounted{"Filesystem not ready - make sure to init_fs before accessing"}; } return *filesys; } private: void internal_init(partition_t part, on_init_func func); hw::Block_device& device; std::unique_ptr<File_system> filesys; }; //< class Disk using Disk_ptr = std::shared_ptr<Disk>; } //< namespace fs #endif //< FS_DISK_HPP <|endoftext|>
<commit_before>/* * Copyright (c) 2016 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #include "webrtc/modules/congestion_controller/probe_controller.h" #include <algorithm> #include <initializer_list> #include "webrtc/base/logging.h" #include "webrtc/system_wrappers/include/metrics.h" namespace webrtc { namespace { // Number of deltas between probes per cluster. On the very first cluster, // we will need kProbeDeltasPerCluster + 1 probes, but on a cluster following // another, we need kProbeDeltasPerCluster probes. constexpr int kProbeDeltasPerCluster = 5; // Maximum waiting time from the time of initiating probing to getting // the measured results back. constexpr int64_t kMaxWaitingTimeForProbingResultMs = 1000; // Value of |min_bitrate_to_probe_further_bps_| that indicates // further probing is disabled. constexpr int kExponentialProbingDisabled = 0; // Default probing bitrate limit. Applied only when the application didn't // specify max bitrate. constexpr int kDefaultMaxProbingBitrateBps = 100000000; // This is a limit on how often probing can be done when there is a BW // drop detected in ALR. constexpr int64_t kAlrProbingIntervalMinMs = 5000; // Interval between probes when ALR periodic probing is enabled. constexpr int64_t kAlrPeriodicProbingIntervalMs = 5000; // Minimum probe bitrate percentage to probe further for repeated probes. constexpr int kRepeatedProbeMinPercentage = 125; } // namespace ProbeController::ProbeController(PacedSender* pacer, Clock* clock) : pacer_(pacer), clock_(clock), network_state_(kNetworkUp), state_(State::kInit), min_bitrate_to_probe_further_bps_(kExponentialProbingDisabled), time_last_probing_initiated_ms_(0), estimated_bitrate_bps_(0), start_bitrate_bps_(0), max_bitrate_bps_(0), last_alr_probing_time_(clock_->TimeInMilliseconds()), enable_periodic_alr_probing_(false) {} void ProbeController::SetBitrates(int min_bitrate_bps, int start_bitrate_bps, int max_bitrate_bps) { rtc::CritScope cs(&critsect_); if (start_bitrate_bps > 0) { start_bitrate_bps_ = start_bitrate_bps; } else if (start_bitrate_bps_ == 0) { start_bitrate_bps_ = min_bitrate_bps; } int old_max_bitrate_bps = max_bitrate_bps_; max_bitrate_bps_ = max_bitrate_bps; switch (state_) { case State::kInit: if (network_state_ == kNetworkUp) InitiateExponentialProbing(); break; case State::kWaitingForProbingResult: break; case State::kProbingComplete: // Initiate probing when |max_bitrate_| was increased mid-call. if (estimated_bitrate_bps_ != 0 && estimated_bitrate_bps_ < old_max_bitrate_bps && max_bitrate_bps_ > old_max_bitrate_bps) { InitiateProbing(clock_->TimeInMilliseconds(), {max_bitrate_bps}, kExponentialProbingDisabled); } break; } } void ProbeController::OnNetworkStateChanged(NetworkState network_state) { rtc::CritScope cs(&critsect_); network_state_ = network_state; if (network_state_ == kNetworkUp && state_ == State::kInit) InitiateExponentialProbing(); } void ProbeController::InitiateExponentialProbing() { RTC_DCHECK(network_state_ == kNetworkUp); RTC_DCHECK(state_ == State::kInit); RTC_DCHECK_GT(start_bitrate_bps_, 0); // When probing at 1.8 Mbps ( 6x 300), this represents a threshold of // 1.2 Mbps to continue probing. InitiateProbing(clock_->TimeInMilliseconds(), {3 * start_bitrate_bps_, 6 * start_bitrate_bps_}, 4 * start_bitrate_bps_); } void ProbeController::SetEstimatedBitrate(int bitrate_bps) { rtc::CritScope cs(&critsect_); int64_t now_ms = clock_->TimeInMilliseconds(); if (state_ == State::kWaitingForProbingResult) { if ((now_ms - time_last_probing_initiated_ms_) > kMaxWaitingTimeForProbingResultMs) { LOG(LS_INFO) << "kWaitingForProbingResult: timeout"; state_ = State::kProbingComplete; min_bitrate_to_probe_further_bps_ = kExponentialProbingDisabled; } else { // Continue probing if probing results indicate channel has greater // capacity. LOG(LS_INFO) << "Measured bitrate: " << bitrate_bps << " Minimum to probe further: " << min_bitrate_to_probe_further_bps_; if (min_bitrate_to_probe_further_bps_ != kExponentialProbingDisabled && bitrate_bps > min_bitrate_to_probe_further_bps_) { // Double the probing bitrate and expect a minimum of 25% gain to // continue probing. InitiateProbing(now_ms, {2 * bitrate_bps}, bitrate_bps * kRepeatedProbeMinPercentage / 100); } else { // Stop exponential probing. state_ = State::kProbingComplete; min_bitrate_to_probe_further_bps_ = kExponentialProbingDisabled; } } } // Detect a drop in estimated BW when operating in ALR and not already // probing. The current response is to initiate a single probe session at the // previous bitrate and immediately use the reported bitrate as the new // bitrate. // // If the probe session fails, the assumption is that this drop was a // real one from a competing flow or something else on the network and // it ramps up from bitrate_bps. if (state_ == State::kProbingComplete && pacer_->GetApplicationLimitedRegionStartTime() && bitrate_bps < estimated_bitrate_bps_ / 2 && (now_ms - last_alr_probing_time_) > kAlrProbingIntervalMinMs) { LOG(LS_INFO) << "Detected big BW drop in ALR, start probe."; // Track how often we probe in response to BW drop in ALR. RTC_HISTOGRAM_COUNTS_10000("WebRTC.BWE.AlrProbingIntervalInS", (now_ms - last_alr_probing_time_) / 1000); InitiateProbing(now_ms, {estimated_bitrate_bps_}, kExponentialProbingDisabled); last_alr_probing_time_ = now_ms; // TODO(isheriff): May want to track when we did ALR probing in order // to reset |last_alr_probing_time_| if we validate that it was a // drop due to exogenous event. } estimated_bitrate_bps_ = bitrate_bps; } void ProbeController::EnablePeriodicAlrProbing(bool enable) { rtc::CritScope cs(&critsect_); enable_periodic_alr_probing_ = enable; } void ProbeController::Process() { rtc::CritScope cs(&critsect_); if (state_ != State::kProbingComplete || !enable_periodic_alr_probing_) return; // Probe bandwidth periodically when in ALR state. rtc::Optional<int64_t> alr_start_time = pacer_->GetApplicationLimitedRegionStartTime(); if (alr_start_time) { int64_t now_ms = clock_->TimeInMilliseconds(); int64_t next_probe_time_ms = std::max(*alr_start_time, time_last_probing_initiated_ms_) + kAlrPeriodicProbingIntervalMs; if (now_ms >= next_probe_time_ms) { InitiateProbing( now_ms, {estimated_bitrate_bps_ * 2}, estimated_bitrate_bps_ * kRepeatedProbeMinPercentage / 100); } } } void ProbeController::InitiateProbing( int64_t now_ms, std::initializer_list<int> bitrates_to_probe, int min_bitrate_to_probe_further_bps) { bool first_cluster = true; for (int bitrate : bitrates_to_probe) { int max_probe_bitrate_bps = max_bitrate_bps_ > 0 ? max_bitrate_bps_ : kDefaultMaxProbingBitrateBps; bitrate = std::min(bitrate, max_probe_bitrate_bps); if (first_cluster) { pacer_->CreateProbeCluster(bitrate, kProbeDeltasPerCluster + 1); first_cluster = false; } else { pacer_->CreateProbeCluster(bitrate, kProbeDeltasPerCluster); } } min_bitrate_to_probe_further_bps_ = min_bitrate_to_probe_further_bps; time_last_probing_initiated_ms_ = now_ms; if (min_bitrate_to_probe_further_bps == kExponentialProbingDisabled) state_ = State::kProbingComplete; else state_ = State::kWaitingForProbingResult; } } // namespace webrtc <commit_msg>Reduce ProbeController::kDefaultMaxProbingBitrateBps to 10 mbps.<commit_after>/* * Copyright (c) 2016 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #include "webrtc/modules/congestion_controller/probe_controller.h" #include <algorithm> #include <initializer_list> #include "webrtc/base/logging.h" #include "webrtc/system_wrappers/include/metrics.h" namespace webrtc { namespace { // Number of deltas between probes per cluster. On the very first cluster, // we will need kProbeDeltasPerCluster + 1 probes, but on a cluster following // another, we need kProbeDeltasPerCluster probes. constexpr int kProbeDeltasPerCluster = 5; // Maximum waiting time from the time of initiating probing to getting // the measured results back. constexpr int64_t kMaxWaitingTimeForProbingResultMs = 1000; // Value of |min_bitrate_to_probe_further_bps_| that indicates // further probing is disabled. constexpr int kExponentialProbingDisabled = 0; // Default probing bitrate limit. Applied only when the application didn't // specify max bitrate. constexpr int kDefaultMaxProbingBitrateBps = 5000000; // This is a limit on how often probing can be done when there is a BW // drop detected in ALR. constexpr int64_t kAlrProbingIntervalMinMs = 5000; // Interval between probes when ALR periodic probing is enabled. constexpr int64_t kAlrPeriodicProbingIntervalMs = 5000; // Minimum probe bitrate percentage to probe further for repeated probes. constexpr int kRepeatedProbeMinPercentage = 125; } // namespace ProbeController::ProbeController(PacedSender* pacer, Clock* clock) : pacer_(pacer), clock_(clock), network_state_(kNetworkUp), state_(State::kInit), min_bitrate_to_probe_further_bps_(kExponentialProbingDisabled), time_last_probing_initiated_ms_(0), estimated_bitrate_bps_(0), start_bitrate_bps_(0), max_bitrate_bps_(0), last_alr_probing_time_(clock_->TimeInMilliseconds()), enable_periodic_alr_probing_(false) {} void ProbeController::SetBitrates(int min_bitrate_bps, int start_bitrate_bps, int max_bitrate_bps) { rtc::CritScope cs(&critsect_); if (start_bitrate_bps > 0) { start_bitrate_bps_ = start_bitrate_bps; } else if (start_bitrate_bps_ == 0) { start_bitrate_bps_ = min_bitrate_bps; } int old_max_bitrate_bps = max_bitrate_bps_; max_bitrate_bps_ = max_bitrate_bps; switch (state_) { case State::kInit: if (network_state_ == kNetworkUp) InitiateExponentialProbing(); break; case State::kWaitingForProbingResult: break; case State::kProbingComplete: // Initiate probing when |max_bitrate_| was increased mid-call. if (estimated_bitrate_bps_ != 0 && estimated_bitrate_bps_ < old_max_bitrate_bps && max_bitrate_bps_ > old_max_bitrate_bps) { InitiateProbing(clock_->TimeInMilliseconds(), {max_bitrate_bps}, kExponentialProbingDisabled); } break; } } void ProbeController::OnNetworkStateChanged(NetworkState network_state) { rtc::CritScope cs(&critsect_); network_state_ = network_state; if (network_state_ == kNetworkUp && state_ == State::kInit) InitiateExponentialProbing(); } void ProbeController::InitiateExponentialProbing() { RTC_DCHECK(network_state_ == kNetworkUp); RTC_DCHECK(state_ == State::kInit); RTC_DCHECK_GT(start_bitrate_bps_, 0); // When probing at 1.8 Mbps ( 6x 300), this represents a threshold of // 1.2 Mbps to continue probing. InitiateProbing(clock_->TimeInMilliseconds(), {3 * start_bitrate_bps_, 6 * start_bitrate_bps_}, 4 * start_bitrate_bps_); } void ProbeController::SetEstimatedBitrate(int bitrate_bps) { rtc::CritScope cs(&critsect_); int64_t now_ms = clock_->TimeInMilliseconds(); if (state_ == State::kWaitingForProbingResult) { if ((now_ms - time_last_probing_initiated_ms_) > kMaxWaitingTimeForProbingResultMs) { LOG(LS_INFO) << "kWaitingForProbingResult: timeout"; state_ = State::kProbingComplete; min_bitrate_to_probe_further_bps_ = kExponentialProbingDisabled; } else { // Continue probing if probing results indicate channel has greater // capacity. LOG(LS_INFO) << "Measured bitrate: " << bitrate_bps << " Minimum to probe further: " << min_bitrate_to_probe_further_bps_; if (min_bitrate_to_probe_further_bps_ != kExponentialProbingDisabled && bitrate_bps > min_bitrate_to_probe_further_bps_) { // Double the probing bitrate and expect a minimum of 25% gain to // continue probing. InitiateProbing(now_ms, {2 * bitrate_bps}, bitrate_bps * kRepeatedProbeMinPercentage / 100); } else { // Stop exponential probing. state_ = State::kProbingComplete; min_bitrate_to_probe_further_bps_ = kExponentialProbingDisabled; } } } // Detect a drop in estimated BW when operating in ALR and not already // probing. The current response is to initiate a single probe session at the // previous bitrate and immediately use the reported bitrate as the new // bitrate. // // If the probe session fails, the assumption is that this drop was a // real one from a competing flow or something else on the network and // it ramps up from bitrate_bps. if (state_ == State::kProbingComplete && pacer_->GetApplicationLimitedRegionStartTime() && bitrate_bps < estimated_bitrate_bps_ / 2 && (now_ms - last_alr_probing_time_) > kAlrProbingIntervalMinMs) { LOG(LS_INFO) << "Detected big BW drop in ALR, start probe."; // Track how often we probe in response to BW drop in ALR. RTC_HISTOGRAM_COUNTS_10000("WebRTC.BWE.AlrProbingIntervalInS", (now_ms - last_alr_probing_time_) / 1000); InitiateProbing(now_ms, {estimated_bitrate_bps_}, kExponentialProbingDisabled); last_alr_probing_time_ = now_ms; // TODO(isheriff): May want to track when we did ALR probing in order // to reset |last_alr_probing_time_| if we validate that it was a // drop due to exogenous event. } estimated_bitrate_bps_ = bitrate_bps; } void ProbeController::EnablePeriodicAlrProbing(bool enable) { rtc::CritScope cs(&critsect_); enable_periodic_alr_probing_ = enable; } void ProbeController::Process() { rtc::CritScope cs(&critsect_); if (state_ != State::kProbingComplete || !enable_periodic_alr_probing_) return; // Probe bandwidth periodically when in ALR state. rtc::Optional<int64_t> alr_start_time = pacer_->GetApplicationLimitedRegionStartTime(); if (alr_start_time) { int64_t now_ms = clock_->TimeInMilliseconds(); int64_t next_probe_time_ms = std::max(*alr_start_time, time_last_probing_initiated_ms_) + kAlrPeriodicProbingIntervalMs; if (now_ms >= next_probe_time_ms) { InitiateProbing( now_ms, {estimated_bitrate_bps_ * 2}, estimated_bitrate_bps_ * kRepeatedProbeMinPercentage / 100); } } } void ProbeController::InitiateProbing( int64_t now_ms, std::initializer_list<int> bitrates_to_probe, int min_bitrate_to_probe_further_bps) { bool first_cluster = true; for (int bitrate : bitrates_to_probe) { int max_probe_bitrate_bps = max_bitrate_bps_ > 0 ? max_bitrate_bps_ : kDefaultMaxProbingBitrateBps; bitrate = std::min(bitrate, max_probe_bitrate_bps); if (first_cluster) { pacer_->CreateProbeCluster(bitrate, kProbeDeltasPerCluster + 1); first_cluster = false; } else { pacer_->CreateProbeCluster(bitrate, kProbeDeltasPerCluster); } } min_bitrate_to_probe_further_bps_ = min_bitrate_to_probe_further_bps; time_last_probing_initiated_ms_ = now_ms; if (min_bitrate_to_probe_further_bps == kExponentialProbingDisabled) state_ = State::kProbingComplete; else state_ = State::kWaitingForProbingResult; } } // namespace webrtc <|endoftext|>
<commit_before>//===-- AsmPrinterDwarf.cpp - AsmPrinter Dwarf Support --------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements the Dwarf emissions parts of AsmPrinter. // //===----------------------------------------------------------------------===// #define DEBUG_TYPE "asm-printer" #include "llvm/CodeGen/AsmPrinter.h" #include "llvm/CodeGen/MachineLocation.h" #include "llvm/MC/MCAsmInfo.h" #include "llvm/MC/MCSection.h" #include "llvm/MC/MCStreamer.h" #include "llvm/MC/MCSymbol.h" #include "llvm/Target/TargetData.h" #include "llvm/Target/TargetFrameLowering.h" #include "llvm/Target/TargetLoweringObjectFile.h" #include "llvm/Target/TargetMachine.h" #include "llvm/Target/TargetRegisterInfo.h" #include "llvm/ADT/Twine.h" #include "llvm/Support/Dwarf.h" using namespace llvm; //===----------------------------------------------------------------------===// // Dwarf Emission Helper Routines //===----------------------------------------------------------------------===// /// EmitSLEB128 - emit the specified signed leb128 value. void AsmPrinter::EmitSLEB128(int Value, const char *Desc) const { if (isVerbose() && Desc) OutStreamer.AddComment(Desc); if (MAI->hasLEB128()) { OutStreamer.EmitSLEB128IntValue(Value); return; } // If we don't have .sleb128, emit as .bytes. int Sign = Value >> (8 * sizeof(Value) - 1); bool IsMore; do { unsigned char Byte = static_cast<unsigned char>(Value & 0x7f); Value >>= 7; IsMore = Value != Sign || ((Byte ^ Sign) & 0x40) != 0; if (IsMore) Byte |= 0x80; OutStreamer.EmitIntValue(Byte, 1, /*addrspace*/0); } while (IsMore); } /// EmitULEB128 - emit the specified signed leb128 value. void AsmPrinter::EmitULEB128(unsigned Value, const char *Desc, unsigned PadTo) const { if (isVerbose() && Desc) OutStreamer.AddComment(Desc); // FIXME: Should we add a PadTo option to the streamer? if (MAI->hasLEB128() && PadTo == 0) { OutStreamer.EmitULEB128IntValue(Value); return; } // If we don't have .uleb128 or we want to emit padding, emit as .bytes. do { unsigned char Byte = static_cast<unsigned char>(Value & 0x7f); Value >>= 7; if (Value || PadTo != 0) Byte |= 0x80; OutStreamer.EmitIntValue(Byte, 1, /*addrspace*/0); } while (Value); if (PadTo) { if (PadTo > 1) OutStreamer.EmitFill(PadTo - 1, 0x80/*fillval*/, 0/*addrspace*/); OutStreamer.EmitFill(1, 0/*fillval*/, 0/*addrspace*/); } } /// EmitCFAByte - Emit a .byte 42 directive for a DW_CFA_xxx value. void AsmPrinter::EmitCFAByte(unsigned Val) const { if (isVerbose()) { if (Val >= dwarf::DW_CFA_offset && Val < dwarf::DW_CFA_offset+64) OutStreamer.AddComment("DW_CFA_offset + Reg (" + Twine(Val-dwarf::DW_CFA_offset) + ")"); else OutStreamer.AddComment(dwarf::CallFrameString(Val)); } OutStreamer.EmitIntValue(Val, 1, 0/*addrspace*/); } static const char *DecodeDWARFEncoding(unsigned Encoding) { switch (Encoding) { case dwarf::DW_EH_PE_absptr: return "absptr"; case dwarf::DW_EH_PE_omit: return "omit"; case dwarf::DW_EH_PE_pcrel: return "pcrel"; case dwarf::DW_EH_PE_udata4: return "udata4"; case dwarf::DW_EH_PE_udata8: return "udata8"; case dwarf::DW_EH_PE_sdata4: return "sdata4"; case dwarf::DW_EH_PE_sdata8: return "sdata8"; case dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_udata4: return "pcrel udata4"; case dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4: return "pcrel sdata4"; case dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_udata8: return "pcrel udata8"; case dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata8: return "pcrel sdata8"; case dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |dwarf::DW_EH_PE_udata4: return "indirect pcrel udata4"; case dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |dwarf::DW_EH_PE_sdata4: return "indirect pcrel sdata4"; case dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |dwarf::DW_EH_PE_udata8: return "indirect pcrel udata8"; case dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |dwarf::DW_EH_PE_sdata8: return "indirect pcrel sdata8"; } return "<unknown encoding>"; } /// EmitEncodingByte - Emit a .byte 42 directive that corresponds to an /// encoding. If verbose assembly output is enabled, we output comments /// describing the encoding. Desc is an optional string saying what the /// encoding is specifying (e.g. "LSDA"). void AsmPrinter::EmitEncodingByte(unsigned Val, const char *Desc) const { if (isVerbose()) { if (Desc != 0) OutStreamer.AddComment(Twine(Desc)+" Encoding = " + Twine(DecodeDWARFEncoding(Val))); else OutStreamer.AddComment(Twine("Encoding = ") + DecodeDWARFEncoding(Val)); } OutStreamer.EmitIntValue(Val, 1, 0/*addrspace*/); } /// GetSizeOfEncodedValue - Return the size of the encoding in bytes. unsigned AsmPrinter::GetSizeOfEncodedValue(unsigned Encoding) const { if (Encoding == dwarf::DW_EH_PE_omit) return 0; switch (Encoding & 0x07) { default: assert(0 && "Invalid encoded value."); case dwarf::DW_EH_PE_absptr: return TM.getTargetData()->getPointerSize(); case dwarf::DW_EH_PE_udata2: return 2; case dwarf::DW_EH_PE_udata4: return 4; case dwarf::DW_EH_PE_udata8: return 8; } } void AsmPrinter::EmitReference(const MCSymbol *Sym, unsigned Encoding) const { const TargetLoweringObjectFile &TLOF = getObjFileLowering(); const MCExpr *Exp = TLOF.getExprForDwarfReference(Sym, Mang, MMI, Encoding, OutStreamer); OutStreamer.EmitAbsValue(Exp, GetSizeOfEncodedValue(Encoding)); } void AsmPrinter::EmitReference(const GlobalValue *GV, unsigned Encoding)const{ const TargetLoweringObjectFile &TLOF = getObjFileLowering(); const MCExpr *Exp = TLOF.getExprForDwarfGlobalReference(GV, Mang, MMI, Encoding, OutStreamer); OutStreamer.EmitValue(Exp, GetSizeOfEncodedValue(Encoding), /*addrspace*/0); } /// EmitSectionOffset - Emit the 4-byte offset of Label from the start of its /// section. This can be done with a special directive if the target supports /// it (e.g. cygwin) or by emitting it as an offset from a label at the start /// of the section. /// /// SectionLabel is a temporary label emitted at the start of the section that /// Label lives in. void AsmPrinter::EmitSectionOffset(const MCSymbol *Label, const MCSymbol *SectionLabel) const { // On COFF targets, we have to emit the special .secrel32 directive. if (const char *SecOffDir = MAI->getDwarfSectionOffsetDirective()) { OutStreamer.EmitCOFFSecRel32(Label); return; } // Get the section that we're referring to, based on SectionLabel. const MCSection &Section = SectionLabel->getSection(); // If Label has already been emitted, verify that it is in the same section as // section label for sanity. assert((!Label->isInSection() || &Label->getSection() == &Section) && "Section offset using wrong section base for label"); // If the section in question will end up with an address of 0 anyway, we can // just emit an absolute reference to save a relocation. if (Section.isBaseAddressKnownZero()) { OutStreamer.EmitSymbolValue(Label, 4, 0/*AddrSpace*/); return; } // Otherwise, emit it as a label difference from the start of the section. EmitLabelDifference(Label, SectionLabel, 4); } //===----------------------------------------------------------------------===// // Dwarf Lowering Routines //===----------------------------------------------------------------------===// /// EmitFrameMoves - Emit frame instructions to describe the layout of the /// frame. void AsmPrinter::EmitFrameMoves(const std::vector<MachineMove> &Moves, MCSymbol *BaseLabel, bool isEH) const { const TargetRegisterInfo *RI = TM.getRegisterInfo(); int stackGrowth = TM.getTargetData()->getPointerSize(); if (TM.getFrameLowering()->getStackGrowthDirection() != TargetFrameLowering::StackGrowsUp) stackGrowth *= -1; for (unsigned i = 0, N = Moves.size(); i < N; ++i) { const MachineMove &Move = Moves[i]; MCSymbol *Label = Move.getLabel(); // Throw out move if the label is invalid. if (Label && !Label->isDefined()) continue; // Not emitted, in dead code. const MachineLocation &Dst = Move.getDestination(); const MachineLocation &Src = Move.getSource(); // Advance row if new location. if (BaseLabel && Label) { MCSymbol *ThisSym = Label; if (ThisSym != BaseLabel) { EmitCFAByte(dwarf::DW_CFA_advance_loc4); EmitLabelDifference(ThisSym, BaseLabel, 4); BaseLabel = ThisSym; } } // If advancing cfa. if (Dst.isReg() && Dst.getReg() == MachineLocation::VirtualFP) { assert(!Src.isReg() && "Machine move not supported yet."); if (Src.getReg() == MachineLocation::VirtualFP) { EmitCFAByte(dwarf::DW_CFA_def_cfa_offset); } else { EmitCFAByte(dwarf::DW_CFA_def_cfa); EmitULEB128(RI->getDwarfRegNum(Src.getReg(), isEH), "Register"); } EmitULEB128(-Src.getOffset(), "Offset"); continue; } if (Src.isReg() && Src.getReg() == MachineLocation::VirtualFP) { assert(Dst.isReg() && "Machine move not supported yet."); EmitCFAByte(dwarf::DW_CFA_def_cfa_register); EmitULEB128(RI->getDwarfRegNum(Dst.getReg(), isEH), "Register"); continue; } unsigned Reg = RI->getDwarfRegNum(Src.getReg(), isEH); int Offset = Dst.getOffset() / stackGrowth; if (Offset < 0) { EmitCFAByte(dwarf::DW_CFA_offset_extended_sf); EmitULEB128(Reg, "Reg"); EmitSLEB128(Offset, "Offset"); } else if (Reg < 64) { EmitCFAByte(dwarf::DW_CFA_offset + Reg); EmitULEB128(Offset, "Offset"); } else { EmitCFAByte(dwarf::DW_CFA_offset_extended); EmitULEB128(Reg, "Reg"); EmitULEB128(Offset, "Offset"); } } } /// EmitFrameMoves - Emit frame instructions to describe the layout of the /// frame. void AsmPrinter::EmitCFIFrameMoves(const std::vector<MachineMove> &Moves) const { const TargetRegisterInfo *RI = TM.getRegisterInfo(); int stackGrowth = TM.getTargetData()->getPointerSize(); if (TM.getFrameLowering()->getStackGrowthDirection() != TargetFrameLowering::StackGrowsUp) stackGrowth *= -1; for (unsigned i = 0, N = Moves.size(); i < N; ++i) { const MachineMove &Move = Moves[i]; MCSymbol *Label = Move.getLabel(); // Throw out move if the label is invalid. if (Label && !Label->isDefined()) continue; // Not emitted, in dead code. const MachineLocation &Dst = Move.getDestination(); const MachineLocation &Src = Move.getSource(); // If advancing cfa. if (Dst.isReg() && Dst.getReg() == MachineLocation::VirtualFP) { assert(!Src.isReg() && "Machine move not supported yet."); if (Src.getReg() == MachineLocation::VirtualFP) { OutStreamer.EmitCFIDefCfaOffset(-Src.getOffset()); } else { assert("Machine move not supported yet"); // Reg + Offset } } else if (Src.isReg() && Src.getReg() == MachineLocation::VirtualFP) { assert(Dst.isReg() && "Machine move not supported yet."); OutStreamer.EmitCFIDefCfaRegister(RI->getDwarfRegNum(Dst.getReg(), true)); } else { assert(!Dst.isReg() && "Machine move not supported yet."); OutStreamer.EmitCFIOffset(RI->getDwarfRegNum(Src.getReg(), true), Dst.getOffset()); } } } <commit_msg>Remove dead variable.<commit_after>//===-- AsmPrinterDwarf.cpp - AsmPrinter Dwarf Support --------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements the Dwarf emissions parts of AsmPrinter. // //===----------------------------------------------------------------------===// #define DEBUG_TYPE "asm-printer" #include "llvm/CodeGen/AsmPrinter.h" #include "llvm/CodeGen/MachineLocation.h" #include "llvm/MC/MCAsmInfo.h" #include "llvm/MC/MCSection.h" #include "llvm/MC/MCStreamer.h" #include "llvm/MC/MCSymbol.h" #include "llvm/Target/TargetData.h" #include "llvm/Target/TargetFrameLowering.h" #include "llvm/Target/TargetLoweringObjectFile.h" #include "llvm/Target/TargetMachine.h" #include "llvm/Target/TargetRegisterInfo.h" #include "llvm/ADT/Twine.h" #include "llvm/Support/Dwarf.h" using namespace llvm; //===----------------------------------------------------------------------===// // Dwarf Emission Helper Routines //===----------------------------------------------------------------------===// /// EmitSLEB128 - emit the specified signed leb128 value. void AsmPrinter::EmitSLEB128(int Value, const char *Desc) const { if (isVerbose() && Desc) OutStreamer.AddComment(Desc); if (MAI->hasLEB128()) { OutStreamer.EmitSLEB128IntValue(Value); return; } // If we don't have .sleb128, emit as .bytes. int Sign = Value >> (8 * sizeof(Value) - 1); bool IsMore; do { unsigned char Byte = static_cast<unsigned char>(Value & 0x7f); Value >>= 7; IsMore = Value != Sign || ((Byte ^ Sign) & 0x40) != 0; if (IsMore) Byte |= 0x80; OutStreamer.EmitIntValue(Byte, 1, /*addrspace*/0); } while (IsMore); } /// EmitULEB128 - emit the specified signed leb128 value. void AsmPrinter::EmitULEB128(unsigned Value, const char *Desc, unsigned PadTo) const { if (isVerbose() && Desc) OutStreamer.AddComment(Desc); // FIXME: Should we add a PadTo option to the streamer? if (MAI->hasLEB128() && PadTo == 0) { OutStreamer.EmitULEB128IntValue(Value); return; } // If we don't have .uleb128 or we want to emit padding, emit as .bytes. do { unsigned char Byte = static_cast<unsigned char>(Value & 0x7f); Value >>= 7; if (Value || PadTo != 0) Byte |= 0x80; OutStreamer.EmitIntValue(Byte, 1, /*addrspace*/0); } while (Value); if (PadTo) { if (PadTo > 1) OutStreamer.EmitFill(PadTo - 1, 0x80/*fillval*/, 0/*addrspace*/); OutStreamer.EmitFill(1, 0/*fillval*/, 0/*addrspace*/); } } /// EmitCFAByte - Emit a .byte 42 directive for a DW_CFA_xxx value. void AsmPrinter::EmitCFAByte(unsigned Val) const { if (isVerbose()) { if (Val >= dwarf::DW_CFA_offset && Val < dwarf::DW_CFA_offset+64) OutStreamer.AddComment("DW_CFA_offset + Reg (" + Twine(Val-dwarf::DW_CFA_offset) + ")"); else OutStreamer.AddComment(dwarf::CallFrameString(Val)); } OutStreamer.EmitIntValue(Val, 1, 0/*addrspace*/); } static const char *DecodeDWARFEncoding(unsigned Encoding) { switch (Encoding) { case dwarf::DW_EH_PE_absptr: return "absptr"; case dwarf::DW_EH_PE_omit: return "omit"; case dwarf::DW_EH_PE_pcrel: return "pcrel"; case dwarf::DW_EH_PE_udata4: return "udata4"; case dwarf::DW_EH_PE_udata8: return "udata8"; case dwarf::DW_EH_PE_sdata4: return "sdata4"; case dwarf::DW_EH_PE_sdata8: return "sdata8"; case dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_udata4: return "pcrel udata4"; case dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4: return "pcrel sdata4"; case dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_udata8: return "pcrel udata8"; case dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata8: return "pcrel sdata8"; case dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |dwarf::DW_EH_PE_udata4: return "indirect pcrel udata4"; case dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |dwarf::DW_EH_PE_sdata4: return "indirect pcrel sdata4"; case dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |dwarf::DW_EH_PE_udata8: return "indirect pcrel udata8"; case dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |dwarf::DW_EH_PE_sdata8: return "indirect pcrel sdata8"; } return "<unknown encoding>"; } /// EmitEncodingByte - Emit a .byte 42 directive that corresponds to an /// encoding. If verbose assembly output is enabled, we output comments /// describing the encoding. Desc is an optional string saying what the /// encoding is specifying (e.g. "LSDA"). void AsmPrinter::EmitEncodingByte(unsigned Val, const char *Desc) const { if (isVerbose()) { if (Desc != 0) OutStreamer.AddComment(Twine(Desc)+" Encoding = " + Twine(DecodeDWARFEncoding(Val))); else OutStreamer.AddComment(Twine("Encoding = ") + DecodeDWARFEncoding(Val)); } OutStreamer.EmitIntValue(Val, 1, 0/*addrspace*/); } /// GetSizeOfEncodedValue - Return the size of the encoding in bytes. unsigned AsmPrinter::GetSizeOfEncodedValue(unsigned Encoding) const { if (Encoding == dwarf::DW_EH_PE_omit) return 0; switch (Encoding & 0x07) { default: assert(0 && "Invalid encoded value."); case dwarf::DW_EH_PE_absptr: return TM.getTargetData()->getPointerSize(); case dwarf::DW_EH_PE_udata2: return 2; case dwarf::DW_EH_PE_udata4: return 4; case dwarf::DW_EH_PE_udata8: return 8; } } void AsmPrinter::EmitReference(const MCSymbol *Sym, unsigned Encoding) const { const TargetLoweringObjectFile &TLOF = getObjFileLowering(); const MCExpr *Exp = TLOF.getExprForDwarfReference(Sym, Mang, MMI, Encoding, OutStreamer); OutStreamer.EmitAbsValue(Exp, GetSizeOfEncodedValue(Encoding)); } void AsmPrinter::EmitReference(const GlobalValue *GV, unsigned Encoding)const{ const TargetLoweringObjectFile &TLOF = getObjFileLowering(); const MCExpr *Exp = TLOF.getExprForDwarfGlobalReference(GV, Mang, MMI, Encoding, OutStreamer); OutStreamer.EmitValue(Exp, GetSizeOfEncodedValue(Encoding), /*addrspace*/0); } /// EmitSectionOffset - Emit the 4-byte offset of Label from the start of its /// section. This can be done with a special directive if the target supports /// it (e.g. cygwin) or by emitting it as an offset from a label at the start /// of the section. /// /// SectionLabel is a temporary label emitted at the start of the section that /// Label lives in. void AsmPrinter::EmitSectionOffset(const MCSymbol *Label, const MCSymbol *SectionLabel) const { // On COFF targets, we have to emit the special .secrel32 directive. if (MAI->getDwarfSectionOffsetDirective()) { OutStreamer.EmitCOFFSecRel32(Label); return; } // Get the section that we're referring to, based on SectionLabel. const MCSection &Section = SectionLabel->getSection(); // If Label has already been emitted, verify that it is in the same section as // section label for sanity. assert((!Label->isInSection() || &Label->getSection() == &Section) && "Section offset using wrong section base for label"); // If the section in question will end up with an address of 0 anyway, we can // just emit an absolute reference to save a relocation. if (Section.isBaseAddressKnownZero()) { OutStreamer.EmitSymbolValue(Label, 4, 0/*AddrSpace*/); return; } // Otherwise, emit it as a label difference from the start of the section. EmitLabelDifference(Label, SectionLabel, 4); } //===----------------------------------------------------------------------===// // Dwarf Lowering Routines //===----------------------------------------------------------------------===// /// EmitFrameMoves - Emit frame instructions to describe the layout of the /// frame. void AsmPrinter::EmitFrameMoves(const std::vector<MachineMove> &Moves, MCSymbol *BaseLabel, bool isEH) const { const TargetRegisterInfo *RI = TM.getRegisterInfo(); int stackGrowth = TM.getTargetData()->getPointerSize(); if (TM.getFrameLowering()->getStackGrowthDirection() != TargetFrameLowering::StackGrowsUp) stackGrowth *= -1; for (unsigned i = 0, N = Moves.size(); i < N; ++i) { const MachineMove &Move = Moves[i]; MCSymbol *Label = Move.getLabel(); // Throw out move if the label is invalid. if (Label && !Label->isDefined()) continue; // Not emitted, in dead code. const MachineLocation &Dst = Move.getDestination(); const MachineLocation &Src = Move.getSource(); // Advance row if new location. if (BaseLabel && Label) { MCSymbol *ThisSym = Label; if (ThisSym != BaseLabel) { EmitCFAByte(dwarf::DW_CFA_advance_loc4); EmitLabelDifference(ThisSym, BaseLabel, 4); BaseLabel = ThisSym; } } // If advancing cfa. if (Dst.isReg() && Dst.getReg() == MachineLocation::VirtualFP) { assert(!Src.isReg() && "Machine move not supported yet."); if (Src.getReg() == MachineLocation::VirtualFP) { EmitCFAByte(dwarf::DW_CFA_def_cfa_offset); } else { EmitCFAByte(dwarf::DW_CFA_def_cfa); EmitULEB128(RI->getDwarfRegNum(Src.getReg(), isEH), "Register"); } EmitULEB128(-Src.getOffset(), "Offset"); continue; } if (Src.isReg() && Src.getReg() == MachineLocation::VirtualFP) { assert(Dst.isReg() && "Machine move not supported yet."); EmitCFAByte(dwarf::DW_CFA_def_cfa_register); EmitULEB128(RI->getDwarfRegNum(Dst.getReg(), isEH), "Register"); continue; } unsigned Reg = RI->getDwarfRegNum(Src.getReg(), isEH); int Offset = Dst.getOffset() / stackGrowth; if (Offset < 0) { EmitCFAByte(dwarf::DW_CFA_offset_extended_sf); EmitULEB128(Reg, "Reg"); EmitSLEB128(Offset, "Offset"); } else if (Reg < 64) { EmitCFAByte(dwarf::DW_CFA_offset + Reg); EmitULEB128(Offset, "Offset"); } else { EmitCFAByte(dwarf::DW_CFA_offset_extended); EmitULEB128(Reg, "Reg"); EmitULEB128(Offset, "Offset"); } } } /// EmitFrameMoves - Emit frame instructions to describe the layout of the /// frame. void AsmPrinter::EmitCFIFrameMoves(const std::vector<MachineMove> &Moves) const { const TargetRegisterInfo *RI = TM.getRegisterInfo(); int stackGrowth = TM.getTargetData()->getPointerSize(); if (TM.getFrameLowering()->getStackGrowthDirection() != TargetFrameLowering::StackGrowsUp) stackGrowth *= -1; for (unsigned i = 0, N = Moves.size(); i < N; ++i) { const MachineMove &Move = Moves[i]; MCSymbol *Label = Move.getLabel(); // Throw out move if the label is invalid. if (Label && !Label->isDefined()) continue; // Not emitted, in dead code. const MachineLocation &Dst = Move.getDestination(); const MachineLocation &Src = Move.getSource(); // If advancing cfa. if (Dst.isReg() && Dst.getReg() == MachineLocation::VirtualFP) { assert(!Src.isReg() && "Machine move not supported yet."); if (Src.getReg() == MachineLocation::VirtualFP) { OutStreamer.EmitCFIDefCfaOffset(-Src.getOffset()); } else { assert("Machine move not supported yet"); // Reg + Offset } } else if (Src.isReg() && Src.getReg() == MachineLocation::VirtualFP) { assert(Dst.isReg() && "Machine move not supported yet."); OutStreamer.EmitCFIDefCfaRegister(RI->getDwarfRegNum(Dst.getReg(), true)); } else { assert(!Dst.isReg() && "Machine move not supported yet."); OutStreamer.EmitCFIOffset(RI->getDwarfRegNum(Src.getReg(), true), Dst.getOffset()); } } } <|endoftext|>
<commit_before>//=-- llvm/CodeGen/DwarfAccelTable.cpp - Dwarf Accelerator Tables -*- C++ -*-=// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file contains support for writing dwarf accelerator tables. // //===----------------------------------------------------------------------===// #include "DwarfAccelTable.h" #include "DwarfDebug.h" #include "DIE.h" #include "llvm/ADT/Twine.h" #include "llvm/CodeGen/AsmPrinter.h" #include "llvm/MC/MCExpr.h" #include "llvm/MC/MCStreamer.h" #include "llvm/MC/MCSymbol.h" #include "llvm/Support/Debug.h" using namespace llvm; const char *DwarfAccelTable::Atom::AtomTypeString(enum AtomType AT) { switch (AT) { case eAtomTypeNULL: return "eAtomTypeNULL"; case eAtomTypeDIEOffset: return "eAtomTypeDIEOffset"; case eAtomTypeCUOffset: return "eAtomTypeCUOffset"; case eAtomTypeTag: return "eAtomTypeTag"; case eAtomTypeNameFlags: return "eAtomTypeNameFlags"; case eAtomTypeTypeFlags: return "eAtomTypeTypeFlags"; } llvm_unreachable("invalid AtomType!"); } // The general case would need to have a less hard coded size for the // length of the HeaderData, however, if we're constructing based on a // single Atom then we know it will always be: 4 + 4 + 2 + 2. DwarfAccelTable::DwarfAccelTable(DwarfAccelTable::Atom atom) : Header(12), HeaderData(atom) { } // The length of the header data is always going to be 4 + 4 + 4*NumAtoms. DwarfAccelTable::DwarfAccelTable(std::vector<DwarfAccelTable::Atom> &atomList) : Header(8 + (atomList.size() * 4)), HeaderData(atomList) { } DwarfAccelTable::~DwarfAccelTable() { for (size_t i = 0, e = Data.size(); i < e; ++i) delete Data[i]; for (StringMap<DataArray>::iterator EI = Entries.begin(), EE = Entries.end(); EI != EE; ++EI) for (DataArray::iterator DI = EI->second.begin(), DE = EI->second.end(); DI != DE; ++DI) delete (*DI); } void DwarfAccelTable::AddName(StringRef Name, DIE* die, char Flags) { // If the string is in the list already then add this die to the list // otherwise add a new one. DataArray &DIEs = Entries[Name]; DIEs.push_back(new HashDataContents(die, Flags)); } void DwarfAccelTable::ComputeBucketCount(void) { // First get the number of unique hashes. std::vector<uint32_t> uniques; uniques.resize(Data.size()); for (size_t i = 0, e = Data.size(); i < e; ++i) uniques[i] = Data[i]->HashValue; std::stable_sort(uniques.begin(), uniques.end()); std::vector<uint32_t>::iterator p = std::unique(uniques.begin(), uniques.end()); uint32_t num = std::distance(uniques.begin(), p); // Then compute the bucket size, minimum of 1 bucket. if (num > 1024) Header.bucket_count = num/4; if (num > 16) Header.bucket_count = num/2; else Header.bucket_count = num > 0 ? num : 1; Header.hashes_count = num; } namespace { // DIESorter - comparison predicate that sorts DIEs by their offset. struct DIESorter { bool operator()(const struct DwarfAccelTable::HashDataContents *A, const struct DwarfAccelTable::HashDataContents *B) const { return A->Die->getOffset() < B->Die->getOffset(); } }; } void DwarfAccelTable::FinalizeTable(AsmPrinter *Asm, const char *Prefix) { // Create the individual hash data outputs. for (StringMap<DataArray>::iterator EI = Entries.begin(), EE = Entries.end(); EI != EE; ++EI) { struct HashData *Entry = new HashData((*EI).getKeyData()); // Unique the entries. std::stable_sort(EI->second.begin(), EI->second.end(), DIESorter()); EI->second.erase(std::unique(EI->second.begin(), EI->second.end()), EI->second.end()); for (DataArray::const_iterator DI = EI->second.begin(), DE = EI->second.end(); DI != DE; ++DI) Entry->addData((*DI)); Data.push_back(Entry); } // Figure out how many buckets we need, then compute the bucket // contents and the final ordering. We'll emit the hashes and offsets // by doing a walk during the emission phase. We add temporary // symbols to the data so that we can reference them during the offset // later, we'll emit them when we emit the data. ComputeBucketCount(); // Compute bucket contents and final ordering. Buckets.resize(Header.bucket_count); for (size_t i = 0, e = Data.size(); i < e; ++i) { uint32_t bucket = Data[i]->HashValue % Header.bucket_count; Buckets[bucket].push_back(Data[i]); Data[i]->Sym = Asm->GetTempSymbol(Prefix, i); } } // Emits the header for the table via the AsmPrinter. void DwarfAccelTable::EmitHeader(AsmPrinter *Asm) { Asm->OutStreamer.AddComment("Header Magic"); Asm->EmitInt32(Header.magic); Asm->OutStreamer.AddComment("Header Version"); Asm->EmitInt16(Header.version); Asm->OutStreamer.AddComment("Header Hash Function"); Asm->EmitInt16(Header.hash_function); Asm->OutStreamer.AddComment("Header Bucket Count"); Asm->EmitInt32(Header.bucket_count); Asm->OutStreamer.AddComment("Header Hash Count"); Asm->EmitInt32(Header.hashes_count); Asm->OutStreamer.AddComment("Header Data Length"); Asm->EmitInt32(Header.header_data_len); Asm->OutStreamer.AddComment("HeaderData Die Offset Base"); Asm->EmitInt32(HeaderData.die_offset_base); Asm->OutStreamer.AddComment("HeaderData Atom Count"); Asm->EmitInt32(HeaderData.Atoms.size()); for (size_t i = 0; i < HeaderData.Atoms.size(); i++) { Atom A = HeaderData.Atoms[i]; Asm->OutStreamer.AddComment(Atom::AtomTypeString(A.type)); Asm->EmitInt16(A.type); Asm->OutStreamer.AddComment(dwarf::FormEncodingString(A.form)); Asm->EmitInt16(A.form); } } // Walk through and emit the buckets for the table. This will look // like a list of numbers of how many elements are in each bucket. void DwarfAccelTable::EmitBuckets(AsmPrinter *Asm) { unsigned index = 0; for (size_t i = 0, e = Buckets.size(); i < e; ++i) { Asm->OutStreamer.AddComment("Bucket " + Twine(i)); if (Buckets[i].size() != 0) Asm->EmitInt32(index); else Asm->EmitInt32(UINT32_MAX); index += Buckets[i].size(); } } // Walk through the buckets and emit the individual hashes for each // bucket. void DwarfAccelTable::EmitHashes(AsmPrinter *Asm) { for (size_t i = 0, e = Buckets.size(); i < e; ++i) { for (HashList::const_iterator HI = Buckets[i].begin(), HE = Buckets[i].end(); HI != HE; ++HI) { Asm->OutStreamer.AddComment("Hash in Bucket " + Twine(i)); Asm->EmitInt32((*HI)->HashValue); } } } // Walk through the buckets and emit the individual offsets for each // element in each bucket. This is done via a symbol subtraction from the // beginning of the section. The non-section symbol will be output later // when we emit the actual data. void DwarfAccelTable::EmitOffsets(AsmPrinter *Asm, MCSymbol *SecBegin) { for (size_t i = 0, e = Buckets.size(); i < e; ++i) { for (HashList::const_iterator HI = Buckets[i].begin(), HE = Buckets[i].end(); HI != HE; ++HI) { Asm->OutStreamer.AddComment("Offset in Bucket " + Twine(i)); MCContext &Context = Asm->OutStreamer.getContext(); const MCExpr *Sub = MCBinaryExpr::CreateSub(MCSymbolRefExpr::Create((*HI)->Sym, Context), MCSymbolRefExpr::Create(SecBegin, Context), Context); Asm->OutStreamer.EmitValue(Sub, sizeof(uint32_t), 0); } } } // Walk through the buckets and emit the full data for each element in // the bucket. For the string case emit the dies and the various offsets. // Terminate each HashData bucket with 0. void DwarfAccelTable::EmitData(AsmPrinter *Asm, DwarfDebug *D) { uint64_t PrevHash = UINT64_MAX; for (size_t i = 0, e = Buckets.size(); i < e; ++i) { for (HashList::const_iterator HI = Buckets[i].begin(), HE = Buckets[i].end(); HI != HE; ++HI) { // Remember to emit the label for our offset. Asm->OutStreamer.EmitLabel((*HI)->Sym); Asm->OutStreamer.AddComment((*HI)->Str); Asm->EmitSectionOffset(D->getStringPoolEntry((*HI)->Str), D->getStringPool()); Asm->OutStreamer.AddComment("Num DIEs"); Asm->EmitInt32((*HI)->Data.size()); for (std::vector<struct HashDataContents*>::const_iterator DI = (*HI)->Data.begin(), DE = (*HI)->Data.end(); DI != DE; ++DI) { // Emit the DIE offset Asm->EmitInt32((*DI)->Die->getOffset()); // If we have multiple Atoms emit that info too. // FIXME: A bit of a hack, we either emit only one atom or all info. if (HeaderData.Atoms.size() > 1) { Asm->EmitInt16((*DI)->Die->getTag()); Asm->EmitInt8((*DI)->Flags); } } // Emit a 0 to terminate the data unless we have a hash collision. if (PrevHash != (*HI)->HashValue) Asm->EmitInt32(0); PrevHash = (*HI)->HashValue; } } } // Emit the entire data structure to the output file. void DwarfAccelTable::Emit(AsmPrinter *Asm, MCSymbol *SecBegin, DwarfDebug *D) { // Emit the header. EmitHeader(Asm); // Emit the buckets. EmitBuckets(Asm); // Emit the hashes. EmitHashes(Asm); // Emit the offsets. EmitOffsets(Asm, SecBegin); // Emit the hash data. EmitData(Asm, D); } #ifndef NDEBUG void DwarfAccelTable::print(raw_ostream &O) { Header.print(O); HeaderData.print(O); O << "Entries: \n"; for (StringMap<DataArray>::const_iterator EI = Entries.begin(), EE = Entries.end(); EI != EE; ++EI) { O << "Name: " << EI->getKeyData() << "\n"; for (DataArray::const_iterator DI = EI->second.begin(), DE = EI->second.end(); DI != DE; ++DI) (*DI)->print(O); } O << "Buckets and Hashes: \n"; for (size_t i = 0, e = Buckets.size(); i < e; ++i) for (HashList::const_iterator HI = Buckets[i].begin(), HE = Buckets[i].end(); HI != HE; ++HI) (*HI)->print(O); O << "Data: \n"; for (std::vector<HashData*>::const_iterator DI = Data.begin(), DE = Data.end(); DI != DE; ++DI) (*DI)->print(O); } #endif <commit_msg>No need to do an expensive stable sort for a bunch of integers.<commit_after>//=-- llvm/CodeGen/DwarfAccelTable.cpp - Dwarf Accelerator Tables -*- C++ -*-=// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file contains support for writing dwarf accelerator tables. // //===----------------------------------------------------------------------===// #include "DwarfAccelTable.h" #include "DwarfDebug.h" #include "DIE.h" #include "llvm/ADT/Twine.h" #include "llvm/ADT/STLExtras.h" #include "llvm/CodeGen/AsmPrinter.h" #include "llvm/MC/MCExpr.h" #include "llvm/MC/MCStreamer.h" #include "llvm/MC/MCSymbol.h" #include "llvm/Support/Debug.h" using namespace llvm; const char *DwarfAccelTable::Atom::AtomTypeString(enum AtomType AT) { switch (AT) { case eAtomTypeNULL: return "eAtomTypeNULL"; case eAtomTypeDIEOffset: return "eAtomTypeDIEOffset"; case eAtomTypeCUOffset: return "eAtomTypeCUOffset"; case eAtomTypeTag: return "eAtomTypeTag"; case eAtomTypeNameFlags: return "eAtomTypeNameFlags"; case eAtomTypeTypeFlags: return "eAtomTypeTypeFlags"; } llvm_unreachable("invalid AtomType!"); } // The general case would need to have a less hard coded size for the // length of the HeaderData, however, if we're constructing based on a // single Atom then we know it will always be: 4 + 4 + 2 + 2. DwarfAccelTable::DwarfAccelTable(DwarfAccelTable::Atom atom) : Header(12), HeaderData(atom) { } // The length of the header data is always going to be 4 + 4 + 4*NumAtoms. DwarfAccelTable::DwarfAccelTable(std::vector<DwarfAccelTable::Atom> &atomList) : Header(8 + (atomList.size() * 4)), HeaderData(atomList) { } DwarfAccelTable::~DwarfAccelTable() { for (size_t i = 0, e = Data.size(); i < e; ++i) delete Data[i]; for (StringMap<DataArray>::iterator EI = Entries.begin(), EE = Entries.end(); EI != EE; ++EI) for (DataArray::iterator DI = EI->second.begin(), DE = EI->second.end(); DI != DE; ++DI) delete (*DI); } void DwarfAccelTable::AddName(StringRef Name, DIE* die, char Flags) { // If the string is in the list already then add this die to the list // otherwise add a new one. DataArray &DIEs = Entries[Name]; DIEs.push_back(new HashDataContents(die, Flags)); } void DwarfAccelTable::ComputeBucketCount(void) { // First get the number of unique hashes. std::vector<uint32_t> uniques(Data.size()); for (size_t i = 0, e = Data.size(); i < e; ++i) uniques[i] = Data[i]->HashValue; array_pod_sort(uniques.begin(), uniques.end()); std::vector<uint32_t>::iterator p = std::unique(uniques.begin(), uniques.end()); uint32_t num = std::distance(uniques.begin(), p); // Then compute the bucket size, minimum of 1 bucket. if (num > 1024) Header.bucket_count = num/4; if (num > 16) Header.bucket_count = num/2; else Header.bucket_count = num > 0 ? num : 1; Header.hashes_count = num; } namespace { // DIESorter - comparison predicate that sorts DIEs by their offset. struct DIESorter { bool operator()(const struct DwarfAccelTable::HashDataContents *A, const struct DwarfAccelTable::HashDataContents *B) const { return A->Die->getOffset() < B->Die->getOffset(); } }; } void DwarfAccelTable::FinalizeTable(AsmPrinter *Asm, const char *Prefix) { // Create the individual hash data outputs. for (StringMap<DataArray>::iterator EI = Entries.begin(), EE = Entries.end(); EI != EE; ++EI) { struct HashData *Entry = new HashData((*EI).getKeyData()); // Unique the entries. std::stable_sort(EI->second.begin(), EI->second.end(), DIESorter()); EI->second.erase(std::unique(EI->second.begin(), EI->second.end()), EI->second.end()); for (DataArray::const_iterator DI = EI->second.begin(), DE = EI->second.end(); DI != DE; ++DI) Entry->addData((*DI)); Data.push_back(Entry); } // Figure out how many buckets we need, then compute the bucket // contents and the final ordering. We'll emit the hashes and offsets // by doing a walk during the emission phase. We add temporary // symbols to the data so that we can reference them during the offset // later, we'll emit them when we emit the data. ComputeBucketCount(); // Compute bucket contents and final ordering. Buckets.resize(Header.bucket_count); for (size_t i = 0, e = Data.size(); i < e; ++i) { uint32_t bucket = Data[i]->HashValue % Header.bucket_count; Buckets[bucket].push_back(Data[i]); Data[i]->Sym = Asm->GetTempSymbol(Prefix, i); } } // Emits the header for the table via the AsmPrinter. void DwarfAccelTable::EmitHeader(AsmPrinter *Asm) { Asm->OutStreamer.AddComment("Header Magic"); Asm->EmitInt32(Header.magic); Asm->OutStreamer.AddComment("Header Version"); Asm->EmitInt16(Header.version); Asm->OutStreamer.AddComment("Header Hash Function"); Asm->EmitInt16(Header.hash_function); Asm->OutStreamer.AddComment("Header Bucket Count"); Asm->EmitInt32(Header.bucket_count); Asm->OutStreamer.AddComment("Header Hash Count"); Asm->EmitInt32(Header.hashes_count); Asm->OutStreamer.AddComment("Header Data Length"); Asm->EmitInt32(Header.header_data_len); Asm->OutStreamer.AddComment("HeaderData Die Offset Base"); Asm->EmitInt32(HeaderData.die_offset_base); Asm->OutStreamer.AddComment("HeaderData Atom Count"); Asm->EmitInt32(HeaderData.Atoms.size()); for (size_t i = 0; i < HeaderData.Atoms.size(); i++) { Atom A = HeaderData.Atoms[i]; Asm->OutStreamer.AddComment(Atom::AtomTypeString(A.type)); Asm->EmitInt16(A.type); Asm->OutStreamer.AddComment(dwarf::FormEncodingString(A.form)); Asm->EmitInt16(A.form); } } // Walk through and emit the buckets for the table. This will look // like a list of numbers of how many elements are in each bucket. void DwarfAccelTable::EmitBuckets(AsmPrinter *Asm) { unsigned index = 0; for (size_t i = 0, e = Buckets.size(); i < e; ++i) { Asm->OutStreamer.AddComment("Bucket " + Twine(i)); if (Buckets[i].size() != 0) Asm->EmitInt32(index); else Asm->EmitInt32(UINT32_MAX); index += Buckets[i].size(); } } // Walk through the buckets and emit the individual hashes for each // bucket. void DwarfAccelTable::EmitHashes(AsmPrinter *Asm) { for (size_t i = 0, e = Buckets.size(); i < e; ++i) { for (HashList::const_iterator HI = Buckets[i].begin(), HE = Buckets[i].end(); HI != HE; ++HI) { Asm->OutStreamer.AddComment("Hash in Bucket " + Twine(i)); Asm->EmitInt32((*HI)->HashValue); } } } // Walk through the buckets and emit the individual offsets for each // element in each bucket. This is done via a symbol subtraction from the // beginning of the section. The non-section symbol will be output later // when we emit the actual data. void DwarfAccelTable::EmitOffsets(AsmPrinter *Asm, MCSymbol *SecBegin) { for (size_t i = 0, e = Buckets.size(); i < e; ++i) { for (HashList::const_iterator HI = Buckets[i].begin(), HE = Buckets[i].end(); HI != HE; ++HI) { Asm->OutStreamer.AddComment("Offset in Bucket " + Twine(i)); MCContext &Context = Asm->OutStreamer.getContext(); const MCExpr *Sub = MCBinaryExpr::CreateSub(MCSymbolRefExpr::Create((*HI)->Sym, Context), MCSymbolRefExpr::Create(SecBegin, Context), Context); Asm->OutStreamer.EmitValue(Sub, sizeof(uint32_t), 0); } } } // Walk through the buckets and emit the full data for each element in // the bucket. For the string case emit the dies and the various offsets. // Terminate each HashData bucket with 0. void DwarfAccelTable::EmitData(AsmPrinter *Asm, DwarfDebug *D) { uint64_t PrevHash = UINT64_MAX; for (size_t i = 0, e = Buckets.size(); i < e; ++i) { for (HashList::const_iterator HI = Buckets[i].begin(), HE = Buckets[i].end(); HI != HE; ++HI) { // Remember to emit the label for our offset. Asm->OutStreamer.EmitLabel((*HI)->Sym); Asm->OutStreamer.AddComment((*HI)->Str); Asm->EmitSectionOffset(D->getStringPoolEntry((*HI)->Str), D->getStringPool()); Asm->OutStreamer.AddComment("Num DIEs"); Asm->EmitInt32((*HI)->Data.size()); for (std::vector<struct HashDataContents*>::const_iterator DI = (*HI)->Data.begin(), DE = (*HI)->Data.end(); DI != DE; ++DI) { // Emit the DIE offset Asm->EmitInt32((*DI)->Die->getOffset()); // If we have multiple Atoms emit that info too. // FIXME: A bit of a hack, we either emit only one atom or all info. if (HeaderData.Atoms.size() > 1) { Asm->EmitInt16((*DI)->Die->getTag()); Asm->EmitInt8((*DI)->Flags); } } // Emit a 0 to terminate the data unless we have a hash collision. if (PrevHash != (*HI)->HashValue) Asm->EmitInt32(0); PrevHash = (*HI)->HashValue; } } } // Emit the entire data structure to the output file. void DwarfAccelTable::Emit(AsmPrinter *Asm, MCSymbol *SecBegin, DwarfDebug *D) { // Emit the header. EmitHeader(Asm); // Emit the buckets. EmitBuckets(Asm); // Emit the hashes. EmitHashes(Asm); // Emit the offsets. EmitOffsets(Asm, SecBegin); // Emit the hash data. EmitData(Asm, D); } #ifndef NDEBUG void DwarfAccelTable::print(raw_ostream &O) { Header.print(O); HeaderData.print(O); O << "Entries: \n"; for (StringMap<DataArray>::const_iterator EI = Entries.begin(), EE = Entries.end(); EI != EE; ++EI) { O << "Name: " << EI->getKeyData() << "\n"; for (DataArray::const_iterator DI = EI->second.begin(), DE = EI->second.end(); DI != DE; ++DI) (*DI)->print(O); } O << "Buckets and Hashes: \n"; for (size_t i = 0, e = Buckets.size(); i < e; ++i) for (HashList::const_iterator HI = Buckets[i].begin(), HE = Buckets[i].end(); HI != HE; ++HI) (*HI)->print(O); O << "Data: \n"; for (std::vector<HashData*>::const_iterator DI = Data.begin(), DE = Data.end(); DI != DE; ++DI) (*DI)->print(O); } #endif <|endoftext|>
<commit_before>#include "HeaderAndFooter.h" TBTK::DocumentationExamples::HeaderAndFooter headerAndFooter("BlockDiagonalizer"); //! [BlockDiagonalizer] #include "TBTK/Model.h" #include "TBTK/PropertyExtractor/BlockDiagonalizer.h" #include "TBTK/Range.h" #include "TBTK/Smooth.h" #include "TBTK/Solver/BlockDiagonalizer.h" #include "TBTK/Streams.h" #include "TBTK/Visualization/MatPlotLib/Plotter.h" #include <complex> #include <cmath> using namespace std; using namespace TBTK; using namespace Visualization::MatPlotLib; int main(){ const int NUM_K_POINTS = 10000; double a = 1; Model model; Range K(0, 2*M_PI, NUM_K_POINTS); for(int k = 0; k < NUM_K_POINTS; k++) model << HoppingAmplitude(cos(K[k]*a), {k, 0}, {k, 1}) + HC; model.setChemicalPotential(-0.5); model.setTemperature(300); model.construct(); Solver::BlockDiagonalizer solver; solver.setModel(model); solver.run(); const double LOWER_BOUND = -5; const double UPPER_BOUND = 5; const int RESOLUTION = 200; PropertyExtractor::BlockDiagonalizer propertyExtractor(solver); propertyExtractor.setEnergyWindow( LOWER_BOUND, UPPER_BOUND, RESOLUTION ); Plotter plotter; const double SMOOTHING_SIGMA = 0.01; const unsigned int SMOOTHING_WINDOW = 51; Property::DOS dos = propertyExtractor.calculateDOS(); dos = Smooth::gaussian(dos, SMOOTHING_SIGMA, SMOOTHING_WINDOW); Streams::out << dos << "\n"; plotter.plot(dos); plotter.save("figures/DOS.png"); Property::Density density = propertyExtractor.calculateDensity({ //All k-points, summing over the second subindex. {_a_, IDX_SUM_ALL} }); Streams::out << density << "\n"; plotter.clear(); plotter.plot({_a_, IDX_SUM_ALL}, density); plotter.setLabelX("k"); plotter.save("figures/Density.png"); } //! [BlockDiagonalizer] <commit_msg>Updated example for PropertyExtractor::BlockDiagonalizer with scaled axes.<commit_after>#include "HeaderAndFooter.h" TBTK::DocumentationExamples::HeaderAndFooter headerAndFooter("BlockDiagonalizer"); //! [BlockDiagonalizer] #include "TBTK/Model.h" #include "TBTK/PropertyExtractor/BlockDiagonalizer.h" #include "TBTK/Range.h" #include "TBTK/Smooth.h" #include "TBTK/Solver/BlockDiagonalizer.h" #include "TBTK/Streams.h" #include "TBTK/Visualization/MatPlotLib/Plotter.h" #include <complex> #include <cmath> using namespace std; using namespace TBTK; using namespace Visualization::MatPlotLib; int main(){ const int NUM_K_POINTS = 10000; double a = 1; Model model; Range K(0, 2*M_PI, NUM_K_POINTS); for(int k = 0; k < NUM_K_POINTS; k++) model << HoppingAmplitude(cos(K[k]*a), {k, 0}, {k, 1}) + HC; model.setChemicalPotential(-0.5); model.setTemperature(300); model.construct(); Solver::BlockDiagonalizer solver; solver.setModel(model); solver.run(); const double LOWER_BOUND = -5; const double UPPER_BOUND = 5; const int RESOLUTION = 200; PropertyExtractor::BlockDiagonalizer propertyExtractor(solver); propertyExtractor.setEnergyWindow( LOWER_BOUND, UPPER_BOUND, RESOLUTION ); Plotter plotter; const double SMOOTHING_SIGMA = 0.01; const unsigned int SMOOTHING_WINDOW = 51; Property::DOS dos = propertyExtractor.calculateDOS(); dos = Smooth::gaussian(dos, SMOOTHING_SIGMA, SMOOTHING_WINDOW); Streams::out << dos << "\n"; plotter.plot(dos); plotter.save("figures/DOS.png"); Property::Density density = propertyExtractor.calculateDensity({ //All k-points, summing over the second subindex. {_a_, IDX_SUM_ALL} }); Streams::out << density << "\n"; plotter.clear(); plotter.setAxes({{0, {0, 2*M_PI}}}); plotter.plot({_a_, IDX_SUM_ALL}, density); plotter.setLabelX("k"); plotter.save("figures/Density.png"); } //! [BlockDiagonalizer] <|endoftext|>
<commit_before>/* * PresynapticPerspectiveStochasticDelivery.cpp * * Created on: Aug 24, 2017 * Author: Pete Schultz */ #include "PresynapticPerspectiveStochasticDelivery.hpp" // Note: there is a lot of code duplication between PresynapticPerspectiveConvolveDelivery // and PresynapticPerspectiveStochasticDelivery. namespace PV { PresynapticPerspectiveStochasticDelivery::PresynapticPerspectiveStochasticDelivery( char const *name, PVParams *params, Communicator const *comm) { initialize(name, params, comm); } PresynapticPerspectiveStochasticDelivery::PresynapticPerspectiveStochasticDelivery() {} PresynapticPerspectiveStochasticDelivery::~PresynapticPerspectiveStochasticDelivery() { delete mRandState; } void PresynapticPerspectiveStochasticDelivery::initialize( char const *name, PVParams *params, Communicator const *comm) { BaseObject::initialize(name, params, comm); } void PresynapticPerspectiveStochasticDelivery::setObjectType() { mObjectType = "PresynapticPerspectiveStochasticDelivery"; } int PresynapticPerspectiveStochasticDelivery::ioParamsFillGroup(enum ParamsIOFlag ioFlag) { int status = HyPerDelivery::ioParamsFillGroup(ioFlag); return status; } void PresynapticPerspectiveStochasticDelivery::ioParam_receiveGpu(enum ParamsIOFlag ioFlag) { mReceiveGpu = false; // If it's true, we should be using a different class. } Response::Status PresynapticPerspectiveStochasticDelivery::communicateInitInfo( std::shared_ptr<CommunicateInitInfoMessage const> message) { auto status = HyPerDelivery::communicateInitInfo(message); if (!Response::completed(status)) { return status; } // HyPerDelivery::communicateInitInfo() postpones until mWeightsPair communicates. pvAssert(mWeightsPair and mWeightsPair->getInitInfoCommunicatedFlag()); mWeightsPair->needPre(); return Response::SUCCESS; } Response::Status PresynapticPerspectiveStochasticDelivery::allocateDataStructures() { auto status = HyPerDelivery::allocateDataStructures(); if (!Response::completed(status)) { return status; } allocateRandState(); #ifdef PV_USE_OPENMP_THREADS allocateThreadGSyn(); #endif // PV_USE_OPENMP_THREADS return Response::SUCCESS; } void PresynapticPerspectiveStochasticDelivery::allocateRandState() { mRandState = new Random(mPreData->getLayerLoc(), true /*need RNGs in the extended buffer*/); } void PresynapticPerspectiveStochasticDelivery::deliver(float *destBuffer) { // Check if we need to update based on connection's channel if (getChannelCode() == CHANNEL_NOUPDATE) { return; } float *postChannel = destBuffer; pvAssert(postChannel); PVLayerLoc const *preLoc = mPreData->getLayerLoc(); PVLayerLoc const *postLoc = mPostGSyn->getLayerLoc(); Weights *weights = mWeightsPair->getPreWeights(); int const nxPreExtended = preLoc->nx + preLoc->halo.rt + preLoc->halo.rt; int const nyPreExtended = preLoc->ny + preLoc->halo.dn + preLoc->halo.up; int const numPreExtended = nxPreExtended * nyPreExtended * preLoc->nf; int const numPostRestricted = postLoc->nx * postLoc->ny * postLoc->nf; int nbatch = preLoc->nbatch; pvAssert(nbatch == postLoc->nbatch); const int sy = postLoc->nx * postLoc->nf; // stride in restricted layer const int syw = weights->getGeometry()->getPatchStrideY(); // stride in patch bool const preLayerIsSparse = mPreData->getSparseLayer(); int numAxonalArbors = mArborList->getNumAxonalArbors(); for (int arbor = 0; arbor < numAxonalArbors; arbor++) { int delay = mArborList->getDelay(arbor); PVLayerCube activityCube = mPreData->getPublisher()->createCube(delay); for (int b = 0; b < nbatch; b++) { size_t batchOffset = b * numPreExtended; float const *activityBatch = activityCube.data + batchOffset; float *gSynPatchHeadBatch = postChannel + b * numPostRestricted; SparseList<float>::Entry const *activeIndicesBatch = nullptr; int numNeurons; if (preLayerIsSparse) { activeIndicesBatch = (SparseList<float>::Entry *)activityCube.activeIndices + batchOffset; numNeurons = activityCube.numActive[b]; } else { numNeurons = activityCube.numItems / activityCube.loc.nbatch; } #ifdef PV_USE_OPENMP_THREADS clearThreadGSyn(); #endif std::size_t const *gSynPatchStart = weights->getGeometry()->getGSynPatchStart().data(); if (!preLayerIsSparse) { for (int y = 0; y < weights->getPatchSizeY(); y++) { #ifdef PV_USE_OPENMP_THREADS #pragma omp parallel for schedule(guided) #endif for (int idx = 0; idx < numNeurons; idx++) { int kPreExt = idx; // Weight Patch const *patch = &weights->getPatch(kPreExt); if (y >= patch->ny) { continue; } // Activity float a = activityBatch[kPreExt]; if (a == 0.0f) { continue; } a *= mDeltaTimeFactor; float *gSynPatchHead = setWorkingGSynBuffer(gSynPatchHeadBatch); float *postPatchStart = &gSynPatchHead[gSynPatchStart[kPreExt]]; const int nk = patch->nx * weights->getPatchSizeF(); float const *weightDataHead = weights->getDataFromPatchIndex(arbor, kPreExt); float const *weightDataStart = &weightDataHead[patch->offset]; taus_uint4 *rng = mRandState->getRNG(kPreExt); long along = (long)((double)a * cl_random_max()); float *v = postPatchStart + y * sy; float const *weightValues = weightDataStart + y * syw; for (int k = 0; k < nk; k++) { *rng = cl_random_get(*rng); v[k] += (rng->s0 < along) * weightValues[k]; } } } } else { // Sparse, use the stored activity / index pairs int const nyp = weights->getPatchSizeY(); for (int y = 0; y < nyp; y++) { #ifdef PV_USE_OPENMP_THREADS #pragma omp parallel for schedule(guided) #endif for (int idx = 0; idx < numNeurons; idx++) { int kPreExt = activeIndicesBatch[idx].index; // Weight Patch const *patch = &weights->getPatch(kPreExt); if (y >= patch->ny) { continue; } // Activity float a = activeIndicesBatch[idx].value; if (a == 0.0f) { continue; } a *= mDeltaTimeFactor; float *gSynPatchHead = setWorkingGSynBuffer(gSynPatchHeadBatch); float *postPatchStart = &gSynPatchHead[gSynPatchStart[kPreExt]]; const int nk = patch->nx * weights->getPatchSizeF(); float const *weightDataHead = weights->getDataFromPatchIndex(arbor, kPreExt); float const *weightDataStart = &weightDataHead[patch->offset]; taus_uint4 *rng = mRandState->getRNG(kPreExt); long along = (long)((double)a * cl_random_max()); float *v = postPatchStart + y * sy; float const *weightValues = weightDataStart + y * syw; for (int k = 0; k < nk; k++) { *rng = cl_random_get(*rng); v[k] += (rng->s0 < along) * weightValues[k]; } } } } accumulateThreadGSyn(gSynPatchHeadBatch); } } } void PresynapticPerspectiveStochasticDelivery::deliverUnitInput(float *recvBuffer) { PVLayerLoc const *preLoc = mPreData->getLayerLoc(); PVLayerLoc const *postLoc = mPostGSyn->getLayerLoc(); Weights *weights = mWeightsPair->getPreWeights(); int const numPostRestricted = postLoc->nx * postLoc->ny * postLoc->nf; int nbatch = postLoc->nbatch; const int sy = postLoc->nx * postLoc->nf; // stride in restricted layer const int syw = weights->getGeometry()->getPatchStrideY(); // stride in patch int const numAxonalArbors = mArborList->getNumAxonalArbors(); for (int arbor = 0; arbor < numAxonalArbors; arbor++) { int delay = mArborList->getDelay(arbor); PVLayerCube activityCube = mPreData->getPublisher()->createCube(delay); for (int b = 0; b < nbatch; b++) { float *recvBatch = recvBuffer + b * numPostRestricted; int numNeurons = activityCube.numItems / activityCube.loc.nbatch; #ifdef PV_USE_OPENMP_THREADS clearThreadGSyn(); #endif std::size_t const *gSynPatchStart = weights->getGeometry()->getGSynPatchStart().data(); for (int y = 0; y < weights->getPatchSizeY(); y++) { #ifdef PV_USE_OPENMP_THREADS #pragma omp parallel for schedule(guided) #endif for (int idx = 0; idx < numNeurons; idx++) { int kPreExt = idx; // Weight Patch const *patch = &weights->getPatch(kPreExt); if (y >= patch->ny) { continue; } // Activity float a = mDeltaTimeFactor; float *recvPatchHead = setWorkingGSynBuffer(recvBatch); float *postPatchStart = &recvPatchHead[gSynPatchStart[kPreExt]]; const int nk = patch->nx * weights->getPatchSizeF(); float const *weightDataHead = weights->getDataFromPatchIndex(arbor, kPreExt); float const *weightDataStart = &weightDataHead[patch->offset]; taus_uint4 *rng = mRandState->getRNG(kPreExt); long along = (long)cl_random_max(); float *v = postPatchStart + y * sy; float const *weightValues = weightDataStart + y * syw; for (int k = 0; k < nk; k++) { *rng = cl_random_get(*rng); v[k] += (rng->s0 < along) * weightValues[k]; } } } #ifdef PV_USE_OPENMP_THREADS accumulateThreadGSyn(recvBatch); #endif // PV_USE_OPENMP_THREADS } } } } // end namespace PV <commit_msg>Bugfix to StochasticDelivery::deliverUnitInput()<commit_after>/* * PresynapticPerspectiveStochasticDelivery.cpp * * Created on: Aug 24, 2017 * Author: Pete Schultz */ #include "PresynapticPerspectiveStochasticDelivery.hpp" #include <cmath> // Note: there is a lot of code duplication between PresynapticPerspectiveConvolveDelivery // and PresynapticPerspectiveStochasticDelivery. namespace PV { PresynapticPerspectiveStochasticDelivery::PresynapticPerspectiveStochasticDelivery( char const *name, PVParams *params, Communicator const *comm) { initialize(name, params, comm); } PresynapticPerspectiveStochasticDelivery::PresynapticPerspectiveStochasticDelivery() {} PresynapticPerspectiveStochasticDelivery::~PresynapticPerspectiveStochasticDelivery() { delete mRandState; } void PresynapticPerspectiveStochasticDelivery::initialize( char const *name, PVParams *params, Communicator const *comm) { BaseObject::initialize(name, params, comm); } void PresynapticPerspectiveStochasticDelivery::setObjectType() { mObjectType = "PresynapticPerspectiveStochasticDelivery"; } int PresynapticPerspectiveStochasticDelivery::ioParamsFillGroup(enum ParamsIOFlag ioFlag) { int status = HyPerDelivery::ioParamsFillGroup(ioFlag); return status; } void PresynapticPerspectiveStochasticDelivery::ioParam_receiveGpu(enum ParamsIOFlag ioFlag) { mReceiveGpu = false; // If it's true, we should be using a different class. } Response::Status PresynapticPerspectiveStochasticDelivery::communicateInitInfo( std::shared_ptr<CommunicateInitInfoMessage const> message) { auto status = HyPerDelivery::communicateInitInfo(message); if (!Response::completed(status)) { return status; } // HyPerDelivery::communicateInitInfo() postpones until mWeightsPair communicates. pvAssert(mWeightsPair and mWeightsPair->getInitInfoCommunicatedFlag()); mWeightsPair->needPre(); return Response::SUCCESS; } Response::Status PresynapticPerspectiveStochasticDelivery::allocateDataStructures() { auto status = HyPerDelivery::allocateDataStructures(); if (!Response::completed(status)) { return status; } allocateRandState(); #ifdef PV_USE_OPENMP_THREADS allocateThreadGSyn(); #endif // PV_USE_OPENMP_THREADS return Response::SUCCESS; } void PresynapticPerspectiveStochasticDelivery::allocateRandState() { mRandState = new Random(mPreData->getLayerLoc(), true /*need RNGs in the extended buffer*/); } void PresynapticPerspectiveStochasticDelivery::deliver(float *destBuffer) { // Check if we need to update based on connection's channel if (getChannelCode() == CHANNEL_NOUPDATE) { return; } float *postChannel = destBuffer; pvAssert(postChannel); PVLayerLoc const *preLoc = mPreData->getLayerLoc(); PVLayerLoc const *postLoc = mPostGSyn->getLayerLoc(); Weights *weights = mWeightsPair->getPreWeights(); int const nxPreExtended = preLoc->nx + preLoc->halo.rt + preLoc->halo.rt; int const nyPreExtended = preLoc->ny + preLoc->halo.dn + preLoc->halo.up; int const numPreExtended = nxPreExtended * nyPreExtended * preLoc->nf; int const numPostRestricted = postLoc->nx * postLoc->ny * postLoc->nf; int nbatch = preLoc->nbatch; pvAssert(nbatch == postLoc->nbatch); const int sy = postLoc->nx * postLoc->nf; // stride in restricted layer const int syw = weights->getGeometry()->getPatchStrideY(); // stride in patch bool const preLayerIsSparse = mPreData->getSparseLayer(); int numAxonalArbors = mArborList->getNumAxonalArbors(); for (int arbor = 0; arbor < numAxonalArbors; arbor++) { int delay = mArborList->getDelay(arbor); PVLayerCube activityCube = mPreData->getPublisher()->createCube(delay); for (int b = 0; b < nbatch; b++) { size_t batchOffset = b * numPreExtended; float const *activityBatch = activityCube.data + batchOffset; float *gSynPatchHeadBatch = postChannel + b * numPostRestricted; SparseList<float>::Entry const *activeIndicesBatch = nullptr; int numNeurons; if (preLayerIsSparse) { activeIndicesBatch = (SparseList<float>::Entry *)activityCube.activeIndices + batchOffset; numNeurons = activityCube.numActive[b]; } else { numNeurons = activityCube.numItems / activityCube.loc.nbatch; } #ifdef PV_USE_OPENMP_THREADS clearThreadGSyn(); #endif std::size_t const *gSynPatchStart = weights->getGeometry()->getGSynPatchStart().data(); if (!preLayerIsSparse) { for (int y = 0; y < weights->getPatchSizeY(); y++) { #ifdef PV_USE_OPENMP_THREADS #pragma omp parallel for schedule(guided) #endif for (int idx = 0; idx < numNeurons; idx++) { int kPreExt = idx; // Weight Patch const *patch = &weights->getPatch(kPreExt); if (y >= patch->ny) { continue; } // Activity float a = activityBatch[kPreExt]; if (a == 0.0f) { continue; } a *= mDeltaTimeFactor; float *gSynPatchHead = setWorkingGSynBuffer(gSynPatchHeadBatch); float *postPatchStart = &gSynPatchHead[gSynPatchStart[kPreExt]]; const int nk = patch->nx * weights->getPatchSizeF(); float const *weightDataHead = weights->getDataFromPatchIndex(arbor, kPreExt); float const *weightDataStart = &weightDataHead[patch->offset]; taus_uint4 *rng = mRandState->getRNG(kPreExt); long along = (long)((double)a * cl_random_max()); float *v = postPatchStart + y * sy; float const *weightValues = weightDataStart + y * syw; for (int k = 0; k < nk; k++) { *rng = cl_random_get(*rng); v[k] += (rng->s0 < along) * weightValues[k]; } } } } else { // Sparse, use the stored activity / index pairs int const nyp = weights->getPatchSizeY(); for (int y = 0; y < nyp; y++) { #ifdef PV_USE_OPENMP_THREADS #pragma omp parallel for schedule(guided) #endif for (int idx = 0; idx < numNeurons; idx++) { int kPreExt = activeIndicesBatch[idx].index; // Weight Patch const *patch = &weights->getPatch(kPreExt); if (y >= patch->ny) { continue; } // Activity float a = activeIndicesBatch[idx].value; if (a == 0.0f) { continue; } a *= mDeltaTimeFactor; float *gSynPatchHead = setWorkingGSynBuffer(gSynPatchHeadBatch); float *postPatchStart = &gSynPatchHead[gSynPatchStart[kPreExt]]; const int nk = patch->nx * weights->getPatchSizeF(); float const *weightDataHead = weights->getDataFromPatchIndex(arbor, kPreExt); float const *weightDataStart = &weightDataHead[patch->offset]; taus_uint4 *rng = mRandState->getRNG(kPreExt); long along = (long)((double)a * cl_random_max()); float *v = postPatchStart + y * sy; float const *weightValues = weightDataStart + y * syw; for (int k = 0; k < nk; k++) { *rng = cl_random_get(*rng); v[k] += (rng->s0 < along) * weightValues[k]; } } } } accumulateThreadGSyn(gSynPatchHeadBatch); } } } void PresynapticPerspectiveStochasticDelivery::deliverUnitInput(float *recvBuffer) { PVLayerLoc const *preLoc = mPreData->getLayerLoc(); PVLayerLoc const *postLoc = mPostGSyn->getLayerLoc(); Weights *weights = mWeightsPair->getPreWeights(); int const numPostRestricted = postLoc->nx * postLoc->ny * postLoc->nf; int nbatch = postLoc->nbatch; const int sy = postLoc->nx * postLoc->nf; // stride in restricted layer const int syw = weights->getGeometry()->getPatchStrideY(); // stride in patch int const numAxonalArbors = mArborList->getNumAxonalArbors(); for (int arbor = 0; arbor < numAxonalArbors; arbor++) { int delay = mArborList->getDelay(arbor); PVLayerCube activityCube = mPreData->getPublisher()->createCube(delay); for (int b = 0; b < nbatch; b++) { float *recvBatch = recvBuffer + b * numPostRestricted; int numNeurons = activityCube.numItems / activityCube.loc.nbatch; #ifdef PV_USE_OPENMP_THREADS clearThreadGSyn(); #endif std::size_t const *gSynPatchStart = weights->getGeometry()->getGSynPatchStart().data(); for (int y = 0; y < weights->getPatchSizeY(); y++) { #ifdef PV_USE_OPENMP_THREADS #pragma omp parallel for schedule(guided) #endif for (int idx = 0; idx < numNeurons; idx++) { int kPreExt = idx; // Weight Patch const *patch = &weights->getPatch(kPreExt); if (y >= patch->ny) { continue; } // Activity float a = mDeltaTimeFactor; float *recvPatchHead = setWorkingGSynBuffer(recvBatch); float *postPatchStart = &recvPatchHead[gSynPatchStart[kPreExt]]; const int nk = patch->nx * weights->getPatchSizeF(); float const *weightDataHead = weights->getDataFromPatchIndex(arbor, kPreExt); float const *weightDataStart = &weightDataHead[patch->offset]; taus_uint4 *rng = mRandState->getRNG(kPreExt); long along = (long)std::floor((double)a * cl_random_max()); float *v = postPatchStart + y * sy; float const *weightValues = weightDataStart + y * syw; for (int k = 0; k < nk; k++) { *rng = cl_random_get(*rng); v[k] += (rng->s0 < along) * weightValues[k]; } } } #ifdef PV_USE_OPENMP_THREADS accumulateThreadGSyn(recvBatch); #endif // PV_USE_OPENMP_THREADS } } } } // end namespace PV <|endoftext|>
<commit_before>// ============================================================================= // PROJECT CHRONO - http://projectchrono.org // // Copyright (c) 2014 projectchrono.org // All right reserved. // // Use of this source code is governed by a BSD-style license that can be found // in the LICENSE file at the top level of the distribution and at // http://projectchrono.org/license-chrono.txt. // // ============================================================================= // Authors: Justin Madsen // ============================================================================= // // model a single track chain system, as part of a tracked vehicle. Uses JSON input files // // ============================================================================= #include <cstdio> #include "subsys/trackSystem/TrackSystem.h" namespace chrono { // ----------------------------------------------------------------------------- // Static variables // idler, right side const ChVector<> TrackSystem::m_idlerPos(-2.1904, -0.1443, 0.2447); // relative to local csys const ChQuaternion<> TrackSystem::m_idlerRot(QUNIT); // drive gear, right side const ChVector<> TrackSystem::m_gearPos(1.7741, -0.0099, 0.2447); // relative to local csys const ChQuaternion<> TrackSystem::m_gearRot(QUNIT); // Support rollers const int TrackSystem::m_numRollers = 0; const double TrackSystem::m_roller_mass = 100.0; const ChVector<> TrackSystem::m_roller_inertia(19.82, 19.82, 26.06); // rotates about z-axis initially const double TrackSystem::m_roller_radius = 0.2; // Unused on M113 const double TrackSystem::m_roller_width = 0.2; // Unused on M113 // suspension const int TrackSystem::m_numSuspensions = 5; TrackSystem::TrackSystem(const std::string& name, int track_idx) : m_track_idx(track_idx), m_name(name) { // FILE* fp = fopen(filename.c_str(), "r"); // char readBuffer[65536]; // fclose(fp); Create(track_idx); } // Create: 1) load/set the subsystem data, resize vectors 2) BuildSubsystems() // TODO: replace hard-coded junk with JSON input files for each subsystem void TrackSystem::Create(int track_idx) { /* // read idler info assert(d.HasMember("Idler")); m_idlerMass = d["Idler"]["Mass"].GetDouble(); m_idlerPos = loadVector(d["Idler"]["Location"]); m_idlerInertia = loadVector(d["Idler"]["Inertia"]); m_idlerRadius = d["Spindle"]["Radius"].GetDouble(); m_idlerWidth = d["Spindle"]["Width"].GetDouble(); m_idler_K = d["Idler"]["SpringK"].GetDouble(); m_idler_C = d["Idler"]["SpringC"].GetDouble(); // Read Drive Gear data assert(d.HasMember("Drive Gear")); assert(d["Drive Gear"].IsObject()); m_gearMass = d["Drive Gear"]["Mass"].GetDouble(); m_gearPos = loadVector(d["Drive Gear"]["Location"]); m_gearInertia = loadVector(d["Drive Gear"]["Inertia"]); m_gearRadius = d["Drive Gear"]["Radius"].GetDouble(); m_gearWidth = d["Drive Gear"]["Width"].GetDouble(); // Read Support Roller info assert(d.HasMember("Support Roller")); assert(d["Support Roller"].IsObject()); m_rollerMass = d["Support Roller"]["Mass"].GetDouble(); m_rollerInertia = loadVector(d["Support Roller"]["Inertia"]); m_rollerRadius = d["Support Roller"]["Radius"].GetDouble(); m_rollerWidth = d["Support Roller"]["Width"].GetDouble(); assert(d["Support Roller"]["Location"].IsArray()); m_NumRollers = d["Support Roller"]["Location"].Size(); */ // no support rollers, for this model m_supportRollers.resize(m_numRollers); m_supportRollers_rev.resize(m_numRollers); /* m_rollerLocs.resize(m_NumRollers); for(int i = 0; i < m_NumRollers; i++ ) { m_rollerLocs[i] = loadVector(d["Support Roller"]["Location"][i]); } // Read Suspension data assert(d.HasMember("Suspension")); assert(d["Suspension"].IsObject()); assert(d["Suspension"]["Location"].IsArray() ); m_suspensionFilename = d["Suspension"]["Input File"].GetString(); m_NumSuspensions = d["Suspension"]["Location"].Size(); m_suspensions.resize(m_numSuspensions); m_suspensionLocs.resize(m_numSuspensions); for(int j = 0; j < m_numSuspensions; j++) { // m_suspensionLocs[j] = loadVector(d["Suspension"]["Locaiton"][j]); } */ m_suspensions.resize(m_numSuspensions); m_suspensionLocs.resize(m_numSuspensions); // hard-code positions relative to trackSystem csys. Start w/ one nearest sprocket m_suspensionLocs[0] = ChVector<>(1.3336, 0, 0); m_suspensionLocs[1] = ChVector<>(0.6668, 0, 0); // trackSystem c-sys aligned with middle suspension subsystem arm/chassis revolute constraint position m_suspensionLocs[2] = ChVector<>(0,0,0); m_suspensionLocs[3] = ChVector<>(-0.6682, 0, 0); m_suspensionLocs[4] = ChVector<>(-1.3368, 0, 0); /* // Read Track Chain data assert(d.HasMember("Track Chain")); assert(d["Track Chain"].IsObject()); m_trackChainFilename = d["Track Chain"]["Input File"].GetString() */ // create the various subsystems, from the hardcoded static variables in each subsystem class BuildSubsystems(); } void TrackSystem::BuildSubsystems() { // build one of each of the following subsystems. VisualizationType and CollisionType defaults are PRIMITIVES m_driveGear = ChSharedPtr<DriveGear>(new DriveGear("drive gear "+std::to_string(m_track_idx), VisualizationType::PRIMITIVES, CollisionType::PRIMITIVES) ); m_idler = ChSharedPtr<IdlerSimple>(new IdlerSimple("idler "+std::to_string(m_track_idx), VisualizationType::PRIMITIVES, CollisionType::PRIMITIVES) ); m_chain = ChSharedPtr<TrackChain>(new TrackChain("chain "+std::to_string(m_track_idx), VisualizationType::PRIMITIVES, CollisionType::PRIMITIVES) ); // CollisionType::COMPOUNDPRIMITIVES) ); // build suspension/road wheel subsystems for(int i = 0; i < m_numSuspensions; i++) { m_suspensions[i] = ChSharedPtr<TorsionArmSuspension>(new TorsionArmSuspension("suspension "+std::to_string(i) +", chain "+std::to_string(m_track_idx), VisualizationType::PRIMITIVES, CollisionType::PRIMITIVES) ); } // build support rollers manually (if any) for(int j = 0; j < m_numRollers; j++) { m_supportRollers[j] = ChSharedPtr<ChBody>(new ChBody); m_supportRollers[j]->SetNameString("support roller"+std::to_string(j)+", chain "+std::to_string(m_track_idx) ); m_supportRollers[j]->SetMass(m_roller_mass); m_supportRollers[j]->SetInertiaXX(m_roller_inertia); } } void TrackSystem::Initialize(ChSharedPtr<ChBodyAuxRef> chassis, const ChVector<>& local_pos) { m_local_pos = local_pos; m_gearPosRel = m_gearPos; m_idlerPosRel = m_idlerPos; // if we're on the left side of the vehicle, switch lateral z-axis on all relative positions if(m_local_pos.z < 0) { m_gearPosRel.z *= -1; m_idlerPosRel.z *= -1; } // Create list of the center location of the rolling elements and their clearance. // Clearance is a sphere shaped envelope at each center location, where it can // be guaranteed that the track chain geometry will not penetrate the sphere. std::vector<ChVector<>> rolling_elem_locs; // w.r.t. chassis ref. frame std::vector<double> clearance; // 1 per rolling elem // initialize 1 of each of the following subsystems. // will use the chassis ref frame to do the transforms, since the TrackSystem // local ref. frame has same rot (just difference in position) m_driveGear->Initialize(chassis, ChCoordsys<>(m_local_pos + Get_gearPosRel(), QUNIT) ); // drive sprocket is First added to the lists passed into TrackChain Init() rolling_elem_locs.push_back(m_local_pos + Get_gearPosRel() ); clearance.push_back(m_driveGear->GetRadius() ); // initialize the torsion arm suspension subsystems for(int s_idx = 0; s_idx < m_suspensionLocs.size(); s_idx++) { m_suspensions[s_idx]->Initialize(chassis, ChCoordsys<>(m_local_pos + m_suspensionLocs[s_idx], QUNIT) ); // add to the lists passed into the track chain, find location of each wheel center w.r.t. chassis coords. rolling_elem_locs.push_back(m_local_pos + m_suspensionLocs[s_idx] + m_suspensions[s_idx]->GetWheelPosRel() ); clearance.push_back(m_suspensions[s_idx]->GetWheelRadius() ); } // initialize the support rollers. // NOTE: None for the M113 for(int r_idx = 0; r_idx < m_rollerLocs.size(); r_idx++) { initialize_roller(m_supportRollers[r_idx], chassis, m_local_pos + m_rollerLocs[r_idx], QUNIT, r_idx); // add to the points passed into the track chain rolling_elem_locs.push_back( m_local_pos + m_rollerLocs[r_idx] ); clearance.push_back(m_roller_radius); } // last control point: the idler body m_idler->Initialize(chassis, ChCoordsys<>(m_local_pos + Get_idlerPosRel(), QUNIT) ); // add to the lists passed into the track chain Init() rolling_elem_locs.push_back(m_local_pos + Get_idlerPosRel() ); clearance.push_back(m_idler->GetRadius() ); // After all rolling elements have been initialized, now able to setup the TrackChain. // Assumed that start_pos is between idler and gear control points, e.g., on the top // of the track chain. ChVector<> start_pos = (rolling_elem_locs.front() + rolling_elem_locs.back())/2.0; start_pos.y += (clearance.front() + clearance.back() )/2.0; // Assumption: start_pos should lie close to where the actual track chain would // pass between the idler and driveGears. // MUST be on the top part of the chain so the chain wrap rotation direction can be assumed. // rolling_elem_locs, start_pos w.r.t. chassis c-sys m_chain->Initialize(chassis, rolling_elem_locs, clearance, start_pos ); } // initialize a roller at the specified location and orientation, w.r.t. TrackSystem c-sys void TrackSystem::initialize_roller(ChSharedPtr<ChBody> body, ChSharedPtr<ChBodyAuxRef> chassis, const ChVector<>& loc, const ChQuaternion<>& rot, int idx) { // express loc and rot in the global c-sys ChFrame<> frame_to_abs(loc, rot); body->SetPos(loc); body->SetRot(rot); // transform point to absolute frame and initialize // add the revolute joint at the location and w/ orientation specified // Add a visual asset // Add a collision shape body->SetCollide(true); body->GetCollisionModel()->ClearModel(); // set collision family, gear is a rolling element like the wheels body->GetCollisionModel()->SetFamily((int)CollisionFam::WHEELS); // don't collide with other rolling elements or ground body->GetCollisionModel()->SetFamilyMaskNoCollisionWithFamily((int)CollisionFam::GROUND); body->GetCollisionModel()->BuildModel(); } ChVector<> TrackSystem::Get_idler_spring_react() { ChVector<> outVect = m_idler->m_shock->Get_react_force(); return outVect; } } // end namespace chrono <commit_msg>use new initialize function defs<commit_after>// ============================================================================= // PROJECT CHRONO - http://projectchrono.org // // Copyright (c) 2014 projectchrono.org // All right reserved. // // Use of this source code is governed by a BSD-style license that can be found // in the LICENSE file at the top level of the distribution and at // http://projectchrono.org/license-chrono.txt. // // ============================================================================= // Authors: Justin Madsen // ============================================================================= // // model a single track chain system, as part of a tracked vehicle. Uses JSON input files // // ============================================================================= #include <cstdio> #include "subsys/trackSystem/TrackSystem.h" namespace chrono { // ----------------------------------------------------------------------------- // Static variables // idler, right side const ChVector<> TrackSystem::m_idlerPos(-2.1904, -0.1443, 0.2447); // relative to local csys const ChQuaternion<> TrackSystem::m_idlerRot(QUNIT); // drive gear, right side const ChVector<> TrackSystem::m_gearPos(1.7741, -0.0099, 0.2447); // relative to local csys const ChQuaternion<> TrackSystem::m_gearRot(QUNIT); // Support rollers const int TrackSystem::m_numRollers = 0; const double TrackSystem::m_roller_mass = 100.0; const ChVector<> TrackSystem::m_roller_inertia(19.82, 19.82, 26.06); // rotates about z-axis initially const double TrackSystem::m_roller_radius = 0.2; // Unused on M113 const double TrackSystem::m_roller_width = 0.2; // Unused on M113 // suspension const int TrackSystem::m_numSuspensions = 5; TrackSystem::TrackSystem(const std::string& name, int track_idx) : m_track_idx(track_idx), m_name(name) { // FILE* fp = fopen(filename.c_str(), "r"); // char readBuffer[65536]; // fclose(fp); Create(track_idx); } // Create: 1) load/set the subsystem data, resize vectors 2) BuildSubsystems() // TODO: replace hard-coded junk with JSON input files for each subsystem void TrackSystem::Create(int track_idx) { /* // read idler info assert(d.HasMember("Idler")); m_idlerMass = d["Idler"]["Mass"].GetDouble(); m_idlerPos = loadVector(d["Idler"]["Location"]); m_idlerInertia = loadVector(d["Idler"]["Inertia"]); m_idlerRadius = d["Spindle"]["Radius"].GetDouble(); m_idlerWidth = d["Spindle"]["Width"].GetDouble(); m_idler_K = d["Idler"]["SpringK"].GetDouble(); m_idler_C = d["Idler"]["SpringC"].GetDouble(); // Read Drive Gear data assert(d.HasMember("Drive Gear")); assert(d["Drive Gear"].IsObject()); m_gearMass = d["Drive Gear"]["Mass"].GetDouble(); m_gearPos = loadVector(d["Drive Gear"]["Location"]); m_gearInertia = loadVector(d["Drive Gear"]["Inertia"]); m_gearRadius = d["Drive Gear"]["Radius"].GetDouble(); m_gearWidth = d["Drive Gear"]["Width"].GetDouble(); // Read Support Roller info assert(d.HasMember("Support Roller")); assert(d["Support Roller"].IsObject()); m_rollerMass = d["Support Roller"]["Mass"].GetDouble(); m_rollerInertia = loadVector(d["Support Roller"]["Inertia"]); m_rollerRadius = d["Support Roller"]["Radius"].GetDouble(); m_rollerWidth = d["Support Roller"]["Width"].GetDouble(); assert(d["Support Roller"]["Location"].IsArray()); m_NumRollers = d["Support Roller"]["Location"].Size(); */ // no support rollers, for this model m_supportRollers.resize(m_numRollers); m_supportRollers_rev.resize(m_numRollers); /* m_rollerLocs.resize(m_NumRollers); for(int i = 0; i < m_NumRollers; i++ ) { m_rollerLocs[i] = loadVector(d["Support Roller"]["Location"][i]); } // Read Suspension data assert(d.HasMember("Suspension")); assert(d["Suspension"].IsObject()); assert(d["Suspension"]["Location"].IsArray() ); m_suspensionFilename = d["Suspension"]["Input File"].GetString(); m_NumSuspensions = d["Suspension"]["Location"].Size(); m_suspensions.resize(m_numSuspensions); m_suspensionLocs.resize(m_numSuspensions); for(int j = 0; j < m_numSuspensions; j++) { // m_suspensionLocs[j] = loadVector(d["Suspension"]["Locaiton"][j]); } */ m_suspensions.resize(m_numSuspensions); m_suspensionLocs.resize(m_numSuspensions); // hard-code positions relative to trackSystem csys. Start w/ one nearest sprocket m_suspensionLocs[0] = ChVector<>(1.3336, 0, 0); m_suspensionLocs[1] = ChVector<>(0.6668, 0, 0); // trackSystem c-sys aligned with middle suspension subsystem arm/chassis revolute constraint position m_suspensionLocs[2] = ChVector<>(0,0,0); m_suspensionLocs[3] = ChVector<>(-0.6682, 0, 0); m_suspensionLocs[4] = ChVector<>(-1.3368, 0, 0); /* // Read Track Chain data assert(d.HasMember("Track Chain")); assert(d["Track Chain"].IsObject()); m_trackChainFilename = d["Track Chain"]["Input File"].GetString() */ // create the various subsystems, from the hardcoded static variables in each subsystem class BuildSubsystems(); } void TrackSystem::BuildSubsystems() { // build one of each of the following subsystems. VisualizationType and CollisionType defaults are PRIMITIVES m_driveGear = ChSharedPtr<DriveGear>(new DriveGear("drive gear "+std::to_string(m_track_idx), VisualizationType::PRIMITIVES, CollisionType::PRIMITIVES) ); m_idler = ChSharedPtr<IdlerSimple>(new IdlerSimple("idler "+std::to_string(m_track_idx), VisualizationType::PRIMITIVES, CollisionType::PRIMITIVES) ); m_chain = ChSharedPtr<TrackChain>(new TrackChain("chain "+std::to_string(m_track_idx), VisualizationType::PRIMITIVES, CollisionType::PRIMITIVES) ); // CollisionType::COMPOUNDPRIMITIVES) ); // build suspension/road wheel subsystems for(int i = 0; i < m_numSuspensions; i++) { m_suspensions[i] = ChSharedPtr<TorsionArmSuspension>(new TorsionArmSuspension("suspension "+std::to_string(i) +", chain "+std::to_string(m_track_idx), VisualizationType::PRIMITIVES, CollisionType::PRIMITIVES) ); } // build support rollers manually (if any) for(int j = 0; j < m_numRollers; j++) { m_supportRollers[j] = ChSharedPtr<ChBody>(new ChBody); m_supportRollers[j]->SetNameString("support roller"+std::to_string(j)+", chain "+std::to_string(m_track_idx) ); m_supportRollers[j]->SetMass(m_roller_mass); m_supportRollers[j]->SetInertiaXX(m_roller_inertia); } } void TrackSystem::Initialize(ChSharedPtr<ChBodyAuxRef> chassis, const ChVector<>& local_pos) { m_local_pos = local_pos; m_gearPosRel = m_gearPos; m_idlerPosRel = m_idlerPos; // if we're on the left side of the vehicle, switch lateral z-axis on all relative positions if(m_local_pos.z < 0) { m_gearPosRel.z *= -1; m_idlerPosRel.z *= -1; } // Create list of the center location of the rolling elements and their clearance. // Clearance is a sphere shaped envelope at each center location, where it can // be guaranteed that the track chain geometry will not penetrate the sphere. std::vector<ChVector<>> rolling_elem_locs; // w.r.t. chassis ref. frame std::vector<double> clearance; // 1 per rolling elem // initialize 1 of each of the following subsystems. // will use the chassis ref frame to do the transforms, since the TrackSystem // local ref. frame has same rot (just difference in position) m_driveGear->Initialize(chassis, chassis->GetFrame_REF_to_abs(), ChCoordsys<>(m_local_pos + Get_gearPosRel(), QUNIT) ); // drive sprocket is First added to the lists passed into TrackChain Init() rolling_elem_locs.push_back(m_local_pos + Get_gearPosRel() ); clearance.push_back(m_driveGear->GetRadius() ); // initialize the torsion arm suspension subsystems for(int s_idx = 0; s_idx < m_suspensionLocs.size(); s_idx++) { m_suspensions[s_idx]->Initialize(chassis, chassis->GetFrame_REF_to_abs(), ChCoordsys<>(m_local_pos + m_suspensionLocs[s_idx], QUNIT) ); // add to the lists passed into the track chain, find location of each wheel center w.r.t. chassis coords. rolling_elem_locs.push_back(m_local_pos + m_suspensionLocs[s_idx] + m_suspensions[s_idx]->GetWheelPosRel() ); clearance.push_back(m_suspensions[s_idx]->GetWheelRadius() ); } // initialize the support rollers. // NOTE: None for the M113 for(int r_idx = 0; r_idx < m_rollerLocs.size(); r_idx++) { initialize_roller(m_supportRollers[r_idx], chassis, m_local_pos + m_rollerLocs[r_idx], QUNIT, r_idx); // add to the points passed into the track chain rolling_elem_locs.push_back( m_local_pos + m_rollerLocs[r_idx] ); clearance.push_back(m_roller_radius); } // last control point: the idler body m_idler->Initialize(chassis, chassis->GetFrame_REF_to_abs(), ChCoordsys<>(m_local_pos + Get_idlerPosRel(), QUNIT) ); // add to the lists passed into the track chain Init() rolling_elem_locs.push_back(m_local_pos + Get_idlerPosRel() ); clearance.push_back(m_idler->GetRadius() ); // After all rolling elements have been initialized, now able to setup the TrackChain. // Assumed that start_pos is between idler and gear control points, e.g., on the top // of the track chain. ChVector<> start_pos = (rolling_elem_locs.front() + rolling_elem_locs.back())/2.0; start_pos.y += (clearance.front() + clearance.back() )/2.0; // Assumption: start_pos should lie close to where the actual track chain would // pass between the idler and driveGears. // MUST be on the top part of the chain so the chain wrap rotation direction can be assumed. // rolling_elem_locs, start_pos w.r.t. chassis c-sys m_chain->Initialize(chassis, chassis->GetFrame_REF_to_abs(), rolling_elem_locs, clearance, start_pos ); } // initialize a roller at the specified location and orientation, w.r.t. TrackSystem c-sys void TrackSystem::initialize_roller(ChSharedPtr<ChBody> body, ChSharedPtr<ChBodyAuxRef> chassis, const ChVector<>& loc, const ChQuaternion<>& rot, int idx) { // express loc and rot in the global c-sys ChFrame<> frame_to_abs(loc, rot); body->SetPos(loc); body->SetRot(rot); // transform point to absolute frame and initialize // add the revolute joint at the location and w/ orientation specified // Add a visual asset // Add a collision shape body->SetCollide(true); body->GetCollisionModel()->ClearModel(); // set collision family, gear is a rolling element like the wheels body->GetCollisionModel()->SetFamily((int)CollisionFam::WHEELS); // don't collide with other rolling elements or ground body->GetCollisionModel()->SetFamilyMaskNoCollisionWithFamily((int)CollisionFam::GROUND); body->GetCollisionModel()->BuildModel(); } ChVector<> TrackSystem::Get_idler_spring_react() { ChVector<> outVect = m_idler->m_shock->Get_react_force(); return outVect; } } // end namespace chrono <|endoftext|>
<commit_before>#include "screen.hpp" void Screen::init(Uint16 pWidth, Uint16 pHeight, Uint8 pBpp, Uint8 pMode, Uint8 pSubMode) { setProperties(pWidth, pHeight, pBpp); mode = pMode; subMode = pSubMode; string windowTitleStr = "Project Z"; string footerLeftStr = "idx.CodeLab 2014"; string footerRightStr = ""; if (mode == MODE_EDITOR) { windowTitleStr = windowTitleStr + " - Editor"; footerRightStr = "0/0"; } #ifdef DEBUG cout << "Set SDL" << endl; #endif SDL_Init(SDL_INIT_EVERYTHING); SDL_EnableUNICODE(SDL_ENABLE); #ifdef DEBUG cout << "Set Screen" << endl; #endif resize(pWidth, pHeight, true); SDL_WM_SetCaption(windowTitleStr.c_str(), NULL); footerLeftText.initTTF(); footerLeftText.set(footerLeftStr); footerRightText.set(footerRightStr); list.set(surface); if (mode == MODE_EDITOR) { list.init(LIST_MODE_EDITOR_TERRAIN); } else if (mode == MODE_GAME) { list.init(LIST_MODE_GAME_BUILDINGS); } if (mode == MODE_EDITOR) { input.set(surface); input.init("Set resource value"); } } void Screen::setSubMode(Uint8 pSubMode) { subMode = pSubMode; } void Screen::initMap(Map *pMap) { map.init(pMap, (mode == MODE_EDITOR) ? true : false); map.set(surface); updateFooterRightText(); } void Screen::updateFooterRightText() { if (mode == MODE_EDITOR) { footerRightText.set(map.getSizeString()); } } void Screen::resize(Uint16 s_width, Uint16 s_height, bool isInit) { width = s_width; height = s_height; // SDL_HWSURFACE | SDL_DOUBLEBUF | SDL_RESIZABLE surface = SDL_SetVideoMode( width, height, bpp, SDL_SWSURFACE | SDL_RESIZABLE ); list.setProperties(width, height, bpp); if (isInit == false && mode == MODE_EDITOR) { list.resize(false); input.resize(); } } void Screen::update() { SDL_FillRect( surface, &surface->clip_rect, SDL_MapRGB(surface->format, 0, 0, 0) ); if (subMode == SUB_MODE_EDITOR_MAP || subMode == SUB_MODE_GAME_MAP || subMode == SUB_MODE_EDITOR_MAP_INPUT) { map.show(); map.showGrid(); map.showFieldSelection(); } else if (subMode == SUB_MODE_EDITOR_LIST || subMode == SUB_MODE_GAME_LIST) { list.show(); } if (subMode == SUB_MODE_EDITOR_MAP_INPUT) { input.show(); } apply(0, height - footerLeftText.getHeight(), footerLeftText.get()); if (mode == MODE_EDITOR) { apply( width - footerRightText.getWidth(), height - footerRightText.getHeight(), footerRightText.get() ); } SDL_Flip(surface); } void Screen::quit() { if (mode == MODE_EDITOR) { input.unset(); } map.unset(); list.unset(); footerLeftText.unset(); footerRightText.unset(); footerLeftText.quitTTF(); #ifdef DEBUG cout << "Unset SDL" << endl; #endif SDL_EnableUNICODE(SDL_DISABLE); SDL_Quit(); } <commit_msg>correction list resize<commit_after>#include "screen.hpp" void Screen::init(Uint16 pWidth, Uint16 pHeight, Uint8 pBpp, Uint8 pMode, Uint8 pSubMode) { setProperties(pWidth, pHeight, pBpp); mode = pMode; subMode = pSubMode; string windowTitleStr = "Project Z"; string footerLeftStr = "idx.CodeLab 2014"; string footerRightStr = ""; if (mode == MODE_EDITOR) { windowTitleStr = windowTitleStr + " - Editor"; footerRightStr = "0/0"; } #ifdef DEBUG cout << "Set SDL" << endl; #endif SDL_Init(SDL_INIT_EVERYTHING); SDL_EnableUNICODE(SDL_ENABLE); #ifdef DEBUG cout << "Set Screen" << endl; #endif resize(pWidth, pHeight, true); SDL_WM_SetCaption(windowTitleStr.c_str(), NULL); footerLeftText.initTTF(); footerLeftText.set(footerLeftStr); footerRightText.set(footerRightStr); list.set(surface); if (mode == MODE_EDITOR) { list.init(LIST_MODE_EDITOR_TERRAIN); } else if (mode == MODE_GAME) { list.init(LIST_MODE_GAME_BUILDINGS); } if (mode == MODE_EDITOR) { input.set(surface); input.init("Set resource value"); } } void Screen::setSubMode(Uint8 pSubMode) { subMode = pSubMode; } void Screen::initMap(Map *pMap) { map.init(pMap, (mode == MODE_EDITOR) ? true : false); map.set(surface); updateFooterRightText(); } void Screen::updateFooterRightText() { if (mode == MODE_EDITOR) { footerRightText.set(map.getSizeString()); } } void Screen::resize(Uint16 s_width, Uint16 s_height, bool isInit) { width = s_width; height = s_height; // SDL_HWSURFACE | SDL_DOUBLEBUF | SDL_RESIZABLE surface = SDL_SetVideoMode( width, height, bpp, SDL_SWSURFACE | SDL_RESIZABLE ); list.setProperties(width, height, bpp); if (isInit == false) { list.resize(false); if (mode == MODE_EDITOR) { input.resize(); } } } void Screen::update() { SDL_FillRect( surface, &surface->clip_rect, SDL_MapRGB(surface->format, 0, 0, 0) ); if (subMode != SUB_MODE_GAME_MENU) { map.show(); map.showGrid(); map.showFieldSelection(); } if (subMode == SUB_MODE_EDITOR_LIST || subMode == SUB_MODE_GAME_LIST) { list.show(); } if (subMode == SUB_MODE_EDITOR_MAP_INPUT) { input.show(); } apply(0, height - footerLeftText.getHeight(), footerLeftText.get()); if (mode == MODE_EDITOR) { apply( width - footerRightText.getWidth(), height - footerRightText.getHeight(), footerRightText.get() ); } SDL_Flip(surface); } void Screen::quit() { if (mode == MODE_EDITOR) { input.unset(); } map.unset(); list.unset(); footerLeftText.unset(); footerRightText.unset(); footerLeftText.quitTTF(); #ifdef DEBUG cout << "Unset SDL" << endl; #endif SDL_EnableUNICODE(SDL_DISABLE); SDL_Quit(); } <|endoftext|>
<commit_before>/* * Copyright (c) 2015 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 <dali/internal/render/renderers/render-geometry.h> #include <dali/internal/common/buffer-index.h> #include <dali/internal/render/gl-resources/context.h> #include <dali/internal/render/gl-resources/gpu-buffer.h> #include <dali/internal/render/renderers/render-property-buffer.h> #include <dali/internal/render/shaders/program.h> namespace Dali { namespace Internal { namespace SceneGraph { RenderGeometry::RenderGeometry( GeometryType type, bool requiresDepthTest ) : mIndexBuffer(0), mGeometryType( type ), mRequiresDepthTest(requiresDepthTest ), mHasBeenUpdated(false), mAttributesChanged(true) { } RenderGeometry::~RenderGeometry() { } void RenderGeometry::GlContextCreated( Context& context ) { } void RenderGeometry::GlContextDestroyed() { } void RenderGeometry::AddPropertyBuffer( Render::PropertyBuffer* propertyBuffer, bool isIndexBuffer ) { if( isIndexBuffer ) { mIndexBuffer = propertyBuffer; } else { mVertexBuffers.PushBack( propertyBuffer ); mAttributesChanged = true; } } void RenderGeometry::RemovePropertyBuffer( const Render::PropertyBuffer* propertyBuffer ) { if( propertyBuffer == mIndexBuffer ) { mIndexBuffer = 0; } else { size_t bufferCount = mVertexBuffers.Size(); for( size_t i(0); i<bufferCount; ++i ) { if( propertyBuffer == mVertexBuffers[i] ) { //This will delete the gpu buffer associated to the RenderPropertyBuffer if there is one mVertexBuffers.Remove( mVertexBuffers.Begin()+i); mAttributesChanged = true; break; } } } } void RenderGeometry::GetAttributeLocationFromProgram( Vector<GLint>& attributeLocation, Program& program, BufferIndex bufferIndex ) const { attributeLocation.Clear(); for( size_t i(0); i< mVertexBuffers.Size(); ++i ) { unsigned int attributeCount = mVertexBuffers[i]->GetAttributeCount(); for( unsigned int j = 0; j < attributeCount; ++j ) { const std::string& attributeName = mVertexBuffers[i]->GetAttributeName( j ); unsigned int index = program.RegisterCustomAttribute( attributeName ); GLint location = program.GetCustomAttributeLocation( index ); if( -1 == location ) { DALI_LOG_WARNING( "Attribute not found in the shader: %s\n", attributeName.c_str() ); } attributeLocation.PushBack( location ); } } } void RenderGeometry::OnRenderFinished() { mHasBeenUpdated = false; mAttributesChanged = false; } void RenderGeometry::UploadAndDraw( Context& context, BufferIndex bufferIndex, Vector<GLint>& attributeLocation ) { if( !mHasBeenUpdated ) { // Update buffers if( mIndexBuffer ) { if(!mIndexBuffer->Update( context, true ) ) { //Index buffer is not ready ( Size, data or format has not been specified yet ) return; } } for( unsigned int i = 0; i < mVertexBuffers.Count(); ++i ) { if( !mVertexBuffers[i]->Update( context, false ) ) { //Vertex buffer is not ready ( Size, data or format has not been specified yet ) return; } } mHasBeenUpdated = true; } //Bind buffers to attribute locations unsigned int base = 0; for( unsigned int i = 0; i < mVertexBuffers.Count(); ++i ) { mVertexBuffers[i]->BindBuffer( GpuBuffer::ARRAY_BUFFER ); base += mVertexBuffers[i]->EnableVertexAttributes( context, attributeLocation, base ); } if( mIndexBuffer ) { mIndexBuffer->BindBuffer( GpuBuffer::ELEMENT_ARRAY_BUFFER ); } //Bind index buffer unsigned int numIndices(0u); if( mIndexBuffer ) { numIndices = mIndexBuffer->GetDataSize() / mIndexBuffer->GetElementSize(); } //Draw call switch(mGeometryType) { case Dali::Geometry::TRIANGLES: { if( numIndices ) { context.DrawElements(GL_TRIANGLES, numIndices, GL_UNSIGNED_SHORT, 0); } else { unsigned int numVertices = mVertexBuffers[0]->GetElementCount(); context.DrawArrays( GL_TRIANGLES, 0, numVertices ); } break; } case Dali::Geometry::LINES: { if( numIndices ) { context.DrawElements(GL_LINES, numIndices, GL_UNSIGNED_SHORT, 0); } else { unsigned int numVertices = mVertexBuffers[0]->GetElementCount(); context.DrawArrays( GL_LINES, 0, numVertices ); } break; } case Dali::Geometry::POINTS: { unsigned int numVertices = mVertexBuffers[0]->GetElementCount(); context.DrawArrays(GL_POINTS, 0, numVertices ); break; } case Dali::Geometry::TRIANGLE_STRIP: { if( numIndices ) { context.DrawElements(GL_TRIANGLE_STRIP, numIndices, GL_UNSIGNED_SHORT, 0); } else { unsigned int numVertices = mVertexBuffers[0]->GetElementCount(); context.DrawArrays(GL_TRIANGLE_STRIP, 0, numVertices ); } break; } case Dali::Geometry::TRIANGLE_FAN: { if( numIndices ) { context.DrawElements(GL_TRIANGLE_FAN, numIndices, GL_UNSIGNED_SHORT, 0); } else { unsigned int numVertices = mVertexBuffers[0]->GetElementCount(); context.DrawArrays(GL_TRIANGLE_FAN, 0, numVertices ); } break; } default: { DALI_ASSERT_ALWAYS( 0 && "Geometry type not supported (yet)" ); break; } } //Disable atrributes for( unsigned int i = 0; i < attributeLocation.Count(); ++i ) { if( attributeLocation[i] != -1 ) { context.DisableVertexAttributeArray( attributeLocation[i] ); } } } } // namespace SceneGraph } // namespace Internal } // namespace Dali <commit_msg>Added previously ommited types of geometry: LINE_STRIP, LINE_LOOP in the 'switch' statement of UploadAndDraw()<commit_after>/* * Copyright (c) 2015 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 <dali/internal/render/renderers/render-geometry.h> #include <dali/internal/common/buffer-index.h> #include <dali/internal/render/gl-resources/context.h> #include <dali/internal/render/gl-resources/gpu-buffer.h> #include <dali/internal/render/renderers/render-property-buffer.h> #include <dali/internal/render/shaders/program.h> namespace Dali { namespace Internal { namespace SceneGraph { RenderGeometry::RenderGeometry( GeometryType type, bool requiresDepthTest ) : mIndexBuffer(0), mGeometryType( type ), mRequiresDepthTest(requiresDepthTest ), mHasBeenUpdated(false), mAttributesChanged(true) { } RenderGeometry::~RenderGeometry() { } void RenderGeometry::GlContextCreated( Context& context ) { } void RenderGeometry::GlContextDestroyed() { } void RenderGeometry::AddPropertyBuffer( Render::PropertyBuffer* propertyBuffer, bool isIndexBuffer ) { if( isIndexBuffer ) { mIndexBuffer = propertyBuffer; } else { mVertexBuffers.PushBack( propertyBuffer ); mAttributesChanged = true; } } void RenderGeometry::RemovePropertyBuffer( const Render::PropertyBuffer* propertyBuffer ) { if( propertyBuffer == mIndexBuffer ) { mIndexBuffer = 0; } else { size_t bufferCount = mVertexBuffers.Size(); for( size_t i(0); i<bufferCount; ++i ) { if( propertyBuffer == mVertexBuffers[i] ) { //This will delete the gpu buffer associated to the RenderPropertyBuffer if there is one mVertexBuffers.Remove( mVertexBuffers.Begin()+i); mAttributesChanged = true; break; } } } } void RenderGeometry::GetAttributeLocationFromProgram( Vector<GLint>& attributeLocation, Program& program, BufferIndex bufferIndex ) const { attributeLocation.Clear(); for( size_t i(0); i< mVertexBuffers.Size(); ++i ) { unsigned int attributeCount = mVertexBuffers[i]->GetAttributeCount(); for( unsigned int j = 0; j < attributeCount; ++j ) { const std::string& attributeName = mVertexBuffers[i]->GetAttributeName( j ); unsigned int index = program.RegisterCustomAttribute( attributeName ); GLint location = program.GetCustomAttributeLocation( index ); if( -1 == location ) { DALI_LOG_WARNING( "Attribute not found in the shader: %s\n", attributeName.c_str() ); } attributeLocation.PushBack( location ); } } } void RenderGeometry::OnRenderFinished() { mHasBeenUpdated = false; mAttributesChanged = false; } void RenderGeometry::UploadAndDraw( Context& context, BufferIndex bufferIndex, Vector<GLint>& attributeLocation ) { if( !mHasBeenUpdated ) { // Update buffers if( mIndexBuffer ) { if(!mIndexBuffer->Update( context, true ) ) { //Index buffer is not ready ( Size, data or format has not been specified yet ) return; } } for( unsigned int i = 0; i < mVertexBuffers.Count(); ++i ) { if( !mVertexBuffers[i]->Update( context, false ) ) { //Vertex buffer is not ready ( Size, data or format has not been specified yet ) return; } } mHasBeenUpdated = true; } //Bind buffers to attribute locations unsigned int base = 0; for( unsigned int i = 0; i < mVertexBuffers.Count(); ++i ) { mVertexBuffers[i]->BindBuffer( GpuBuffer::ARRAY_BUFFER ); base += mVertexBuffers[i]->EnableVertexAttributes( context, attributeLocation, base ); } if( mIndexBuffer ) { mIndexBuffer->BindBuffer( GpuBuffer::ELEMENT_ARRAY_BUFFER ); } //Bind index buffer unsigned int numIndices(0u); if( mIndexBuffer ) { numIndices = mIndexBuffer->GetDataSize() / mIndexBuffer->GetElementSize(); } //Draw call switch(mGeometryType) { case Dali::Geometry::TRIANGLES: { if( numIndices ) { context.DrawElements(GL_TRIANGLES, numIndices, GL_UNSIGNED_SHORT, 0); } else { unsigned int numVertices = mVertexBuffers[0]->GetElementCount(); context.DrawArrays( GL_TRIANGLES, 0, numVertices ); } break; } case Dali::Geometry::LINES: { if( numIndices ) { context.DrawElements(GL_LINES, numIndices, GL_UNSIGNED_SHORT, 0); } else { unsigned int numVertices = mVertexBuffers[0]->GetElementCount(); context.DrawArrays( GL_LINES, 0, numVertices ); } break; } case Dali::Geometry::POINTS: { unsigned int numVertices = mVertexBuffers[0]->GetElementCount(); context.DrawArrays(GL_POINTS, 0, numVertices ); break; } case Dali::Geometry::TRIANGLE_STRIP: { if( numIndices ) { context.DrawElements(GL_TRIANGLE_STRIP, numIndices, GL_UNSIGNED_SHORT, 0); } else { unsigned int numVertices = mVertexBuffers[0]->GetElementCount(); context.DrawArrays(GL_TRIANGLE_STRIP, 0, numVertices ); } break; } case Dali::Geometry::TRIANGLE_FAN: { if( numIndices ) { context.DrawElements(GL_TRIANGLE_FAN, numIndices, GL_UNSIGNED_SHORT, 0); } else { unsigned int numVertices = mVertexBuffers[0]->GetElementCount(); context.DrawArrays(GL_TRIANGLE_FAN, 0, numVertices ); } break; } case Dali::Geometry::LINE_LOOP: { if( numIndices ) { context.DrawElements(GL_LINE_LOOP, numIndices, GL_UNSIGNED_SHORT, 0); } else { unsigned int numVertices = mVertexBuffers[0]->GetElementCount(); context.DrawArrays(GL_LINE_LOOP, 0, numVertices ); } break; } case Dali::Geometry::LINE_STRIP: { if( numIndices ) { context.DrawElements(GL_LINE_STRIP, numIndices, GL_UNSIGNED_SHORT, 0); } else { unsigned int numVertices = mVertexBuffers[0]->GetElementCount(); context.DrawArrays(GL_LINE_STRIP, 0, numVertices ); } break; } default: { DALI_ASSERT_ALWAYS( 0 && "Geometry type not supported (yet)" ); break; } } //Disable atrributes for( unsigned int i = 0; i < attributeLocation.Count(); ++i ) { if( attributeLocation[i] != -1 ) { context.DisableVertexAttributeArray( attributeLocation[i] ); } } } } // namespace SceneGraph } // namespace Internal } // namespace Dali <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: fmtextcontrolfeature.cxx,v $ * * $Revision: 1.3 $ * * last change: $Author: rt $ $Date: 2005-09-08 22:57:54 $ * * 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 SVX_SOURCE_INC_FMTEXTCONTROLFEATURE_HXX #include "fmtextcontrolfeature.hxx" #endif /** === begin UNO includes === **/ /** === end UNO includes === **/ //........................................................................ namespace svx { //........................................................................ using namespace ::com::sun::star::uno; using namespace ::com::sun::star::frame; using namespace ::com::sun::star::lang; using namespace ::com::sun::star::beans; using namespace ::com::sun::star::util; //==================================================================== //= FmTextControlFeature //==================================================================== //-------------------------------------------------------------------- FmTextControlFeature::FmTextControlFeature( const Reference< XDispatch >& _rxDispatcher, const URL& _rFeatureURL, SfxSlotId _nSlotId, ISlotInvalidator* _pInvalidator ) :m_xDispatcher ( _rxDispatcher ) ,m_aFeatureURL ( _rFeatureURL ) ,m_nSlotId ( _nSlotId ) ,m_pInvalidator ( _pInvalidator ) ,m_bFeatureEnabled( false ) { OSL_ENSURE( _rxDispatcher.is(), "FmTextControlFeature::FmTextControlFeature: invalid dispatcher!" ); OSL_ENSURE( m_nSlotId, "FmTextControlFeature::FmTextControlFeature: invalid slot id!" ); OSL_ENSURE( m_pInvalidator, "FmTextControlFeature::FmTextControlFeature: invalid invalidator!" ); osl_incrementInterlockedCount( &m_refCount ); try { m_xDispatcher->addStatusListener( this, m_aFeatureURL ); } catch( const Exception& ) { OSL_ENSURE( sal_False, "FmTextControlFeature::FmTextControlFeature: caught an exception!" ); } osl_decrementInterlockedCount( &m_refCount ); } //-------------------------------------------------------------------- FmTextControlFeature::~FmTextControlFeature( ) { } //-------------------------------------------------------------------- void FmTextControlFeature::dispatch() const SAL_THROW(()) { dispatch( Sequence< PropertyValue >( ) ); } //-------------------------------------------------------------------- void FmTextControlFeature::dispatch( const Sequence< PropertyValue >& _rArgs ) const SAL_THROW(()) { try { if ( m_xDispatcher.is() ) m_xDispatcher->dispatch( m_aFeatureURL, _rArgs ); } catch( const Exception& ) { OSL_ENSURE( sal_False, "FmTextControlFeature::dispatch: caught an exception!" ); } } //-------------------------------------------------------------------- void SAL_CALL FmTextControlFeature::statusChanged( const FeatureStateEvent& _rState ) throw (RuntimeException) { m_aFeatureState = _rState.State; m_bFeatureEnabled = _rState.IsEnabled; if ( m_pInvalidator ) m_pInvalidator->Invalidate( m_nSlotId ); } //-------------------------------------------------------------------- void SAL_CALL FmTextControlFeature::disposing( const EventObject& Source ) throw (RuntimeException) { // nothing to do } //-------------------------------------------------------------------- void FmTextControlFeature::dispose() SAL_THROW(()) { try { m_xDispatcher->removeStatusListener( this, m_aFeatureURL ); m_xDispatcher.clear(); } catch( const Exception& ) { OSL_ENSURE( sal_False, "FmTextControlFeature::dispose: caught an exception!" ); } } //........................................................................ } // namespace svx //........................................................................ <commit_msg>INTEGRATION: CWS warnings01 (1.3.222); FILE MERGED 2006/02/15 13:28:11 fs 1.3.222.1: #i55991# warning-free code<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: fmtextcontrolfeature.cxx,v $ * * $Revision: 1.4 $ * * last change: $Author: hr $ $Date: 2006-06-19 15:58:24 $ * * 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 SVX_SOURCE_INC_FMTEXTCONTROLFEATURE_HXX #include "fmtextcontrolfeature.hxx" #endif /** === begin UNO includes === **/ /** === end UNO includes === **/ //........................................................................ namespace svx { //........................................................................ using namespace ::com::sun::star::uno; using namespace ::com::sun::star::frame; using namespace ::com::sun::star::lang; using namespace ::com::sun::star::beans; using namespace ::com::sun::star::util; //==================================================================== //= FmTextControlFeature //==================================================================== //-------------------------------------------------------------------- FmTextControlFeature::FmTextControlFeature( const Reference< XDispatch >& _rxDispatcher, const URL& _rFeatureURL, SfxSlotId _nSlotId, ISlotInvalidator* _pInvalidator ) :m_xDispatcher ( _rxDispatcher ) ,m_aFeatureURL ( _rFeatureURL ) ,m_nSlotId ( _nSlotId ) ,m_pInvalidator ( _pInvalidator ) ,m_bFeatureEnabled( false ) { OSL_ENSURE( _rxDispatcher.is(), "FmTextControlFeature::FmTextControlFeature: invalid dispatcher!" ); OSL_ENSURE( m_nSlotId, "FmTextControlFeature::FmTextControlFeature: invalid slot id!" ); OSL_ENSURE( m_pInvalidator, "FmTextControlFeature::FmTextControlFeature: invalid invalidator!" ); osl_incrementInterlockedCount( &m_refCount ); try { m_xDispatcher->addStatusListener( this, m_aFeatureURL ); } catch( const Exception& ) { OSL_ENSURE( sal_False, "FmTextControlFeature::FmTextControlFeature: caught an exception!" ); } osl_decrementInterlockedCount( &m_refCount ); } //-------------------------------------------------------------------- FmTextControlFeature::~FmTextControlFeature( ) { } //-------------------------------------------------------------------- void FmTextControlFeature::dispatch() const SAL_THROW(()) { dispatch( Sequence< PropertyValue >( ) ); } //-------------------------------------------------------------------- void FmTextControlFeature::dispatch( const Sequence< PropertyValue >& _rArgs ) const SAL_THROW(()) { try { if ( m_xDispatcher.is() ) m_xDispatcher->dispatch( m_aFeatureURL, _rArgs ); } catch( const Exception& ) { OSL_ENSURE( sal_False, "FmTextControlFeature::dispatch: caught an exception!" ); } } //-------------------------------------------------------------------- void SAL_CALL FmTextControlFeature::statusChanged( const FeatureStateEvent& _rState ) throw (RuntimeException) { m_aFeatureState = _rState.State; m_bFeatureEnabled = _rState.IsEnabled; if ( m_pInvalidator ) m_pInvalidator->Invalidate( m_nSlotId ); } //-------------------------------------------------------------------- void SAL_CALL FmTextControlFeature::disposing( const EventObject& /*Source*/ ) throw (RuntimeException) { // nothing to do } //-------------------------------------------------------------------- void FmTextControlFeature::dispose() SAL_THROW(()) { try { m_xDispatcher->removeStatusListener( this, m_aFeatureURL ); m_xDispatcher.clear(); } catch( const Exception& ) { OSL_ENSURE( sal_False, "FmTextControlFeature::dispose: caught an exception!" ); } } //........................................................................ } // namespace svx //........................................................................ <|endoftext|>
<commit_before> #include <iostream> #include "storage/Devices/PartitionImpl.h" #include "storage/Devices/DiskImpl.h" #include "storage/Devicegraph.h" #include "storage/SystemInfo/SystemInfo.h" #include "storage/Utils/SystemCmd.h" #include "storage/Utils/StorageDefines.h" #include "storage/Utils/StorageTmpl.h" namespace storage { using namespace std; const char* DeviceTraits<Partition>::classname = "Partition"; Partition::Impl::Impl(const string& name, const Region& region, PartitionType type) : BlkDevice::Impl(name, region.to_kb(region.get_length())), region(region), type(type), id(ID_LINUX), boot(false) { } Partition::Impl::Impl(const xmlNode* node) : BlkDevice::Impl(node), region(), type(PRIMARY), id(ID_LINUX), boot(false) { string tmp; getChildValue(node, "region", region); if (getChildValue(node, "type", tmp)) type = toValueWithFallback(tmp, PRIMARY); getChildValue(node, "id", id); getChildValue(node, "boot", boot); } void Partition::Impl::probe(SystemInfo& systeminfo) { BlkDevice::Impl::probe(systeminfo); const Devicegraph* g = get_devicegraph(); Devicegraph::Impl::vertex_descriptor v1 = g->get_impl().parent(get_vertex()); Devicegraph::Impl::vertex_descriptor v2 = g->get_impl().parent(v1); string pp_name = dynamic_cast<const BlkDevice*>(g->get_impl()[v2])->get_name(); const Parted& parted = systeminfo.getParted(pp_name); Parted::Entry entry; if (!parted.getEntry(get_number(), entry)) throw; id = entry.id; boot = entry.boot; } void Partition::Impl::save(xmlNode* node) const { BlkDevice::Impl::save(node); setChildValue(node, "region", region); setChildValue(node, "type", toString(type)); setChildValueIf(node, "id", id, id != 0); setChildValueIf(node, "boot", boot, boot); } unsigned int Partition::Impl::get_number() const { string::size_type pos = get_name().find_last_not_of("0123456789"); return atoi(get_name().substr(pos + 1).c_str()); } void Partition::Impl::set_size_k(unsigned long long size_k) { BlkDevice::Impl::set_size_k(size_k); const PartitionTable* partitiontable = get_partition_table(); const Disk* disk = partitiontable->get_disk(); region.set_length(get_size_k() * 1024 / disk->get_impl().get_geometry().cylinderSize()); } void Partition::Impl::set_region(const Region& region) { Impl::region = region; const PartitionTable* partitiontable = get_partition_table(); const Disk* disk = partitiontable->get_disk(); const Geometry& geometry = disk->get_impl().get_geometry(); if (region.get_block_size() != geometry.cylinderSize()) ST_THROW(DifferentBlockSizes(region.get_block_size(), geometry.cylinderSize())); set_size_k(region.get_length() * disk->get_impl().get_geometry().cylinderSize() / 1024); } const PartitionTable* Partition::Impl::get_partition_table() const { Devicegraph::Impl::vertex_descriptor v = get_devicegraph()->get_impl().parent(get_vertex()); return to_partition_table(get_devicegraph()->get_impl()[v]); } void Partition::Impl::add_create_actions(Actiongraph::Impl& actiongraph) const { vector<Action::Base*> actions; actions.push_back(new Action::Create(get_sid())); actions.push_back(new Action::SetPartitionId(get_sid())); actiongraph.add_chain(actions); } void Partition::Impl::add_modify_actions(Actiongraph::Impl& actiongraph, const Device* lhs_base) const { const Impl& lhs = dynamic_cast<const Impl&>(lhs_base->get_impl()); if (get_type() != lhs.get_type()) { throw runtime_error("cannot change partition type"); } if (get_region().get_start() != lhs.get_region().get_start()) { throw runtime_error("cannot move partition"); } if (get_id() != lhs.get_id()) { Action::Base* action = new Action::SetPartitionId(get_sid()); actiongraph.add_vertex(action); } } void Partition::Impl::add_delete_actions(Actiongraph::Impl& actiongraph) const { vector<Action::Base*> actions; actions.push_back(new Action::Delete(get_sid())); actiongraph.add_chain(actions); } bool Partition::Impl::equal(const Device::Impl& rhs_base) const { const Impl& rhs = dynamic_cast<const Impl&>(rhs_base); if (!BlkDevice::Impl::equal(rhs)) return false; return region == rhs.region && type == rhs.type && id == rhs.id && boot == rhs.boot; } void Partition::Impl::log_diff(std::ostream& log, const Device::Impl& rhs_base) const { const Impl& rhs = dynamic_cast<const Impl&>(rhs_base); BlkDevice::Impl::log_diff(log, rhs); storage::log_diff(log, "region", region, rhs.region); storage::log_diff_enum(log, "type", type, rhs.type); storage::log_diff_hex(log, "id", id, rhs.id); storage::log_diff(log, "boot", boot, rhs.boot); } void Partition::Impl::print(std::ostream& out) const { BlkDevice::Impl::print(out); out << " region:" << get_region(); } void Partition::Impl::process_udev_ids(vector<string>& udev_ids) const { const Devicegraph* g = get_devicegraph(); Devicegraph::Impl::vertex_descriptor v1 = g->get_impl().parent(get_vertex()); Devicegraph::Impl::vertex_descriptor v2 = g->get_impl().parent(v1); const Disk* disk = dynamic_cast<const Disk*>(g->get_impl()[v2]); disk->get_impl().process_udev_ids(udev_ids); } bool Partition::Impl::cmp_lt_number(const Partition* lhs, const Partition* rhs) { return lhs->get_number() < rhs->get_number(); } Text Partition::Impl::do_create_text(bool doing) const { return sformat(_("Create partition %1$s (%2$s)"), get_name().c_str(), get_size_string().c_str()); } void Partition::Impl::do_create() const { const PartitionTable* partitiontable = get_partition_table(); const Disk* disk = partitiontable->get_disk(); string cmd_line = PARTEDBIN " -s " + quote(disk->get_name()) + " unit cyl mkpart " + toString(get_type()) + " "; if (get_type() != EXTENDED) { // TODO look at id cmd_line += "ext2 "; } cmd_line += to_string(get_region().get_start()) + " " + to_string(get_region().get_end()); cout << cmd_line << endl; SystemCmd cmd(cmd_line); if (cmd.retcode() != 0) ST_THROW(Exception("create partition failed")); } Text Partition::Impl::do_set_id_text(bool doing) const { string tmp = id_to_string(get_id()); if (tmp.empty()) return sformat(_("Set id of partition %1$s to 0x%2$02X"), get_name().c_str(), get_id()); else return sformat(_("Set id of partition %1$s to %2$s (0x%3$02X)"), get_name().c_str(), tmp.c_str(), get_id()); } void Partition::Impl::do_set_id() const { const PartitionTable* partitiontable = get_partition_table(); const Disk* disk = partitiontable->get_disk(); string cmd_line = PARTEDBIN " -s " + quote(disk->get_name()) + " set " + to_string(get_number()) + " type " + to_string(get_id()); cout << cmd_line << endl; SystemCmd cmd(cmd_line); if (cmd.retcode() != 0) ST_THROW(Exception("set partition id failed")); } Text Partition::Impl::do_delete_text(bool doing) const { return sformat(_("Delete partition %1$s (%2$s)"), get_name().c_str(), get_size_string().c_str()); } void Partition::Impl::do_delete() const { const PartitionTable* partitiontable = get_partition_table(); const Disk* disk = partitiontable->get_disk(); string cmd_line = PARTEDBIN " -s " + disk->get_name() + " rm " + to_string(get_number()); cout << cmd_line << endl; SystemCmd cmd(cmd_line); if (cmd.retcode() != 0) ST_THROW(Exception("delete partition failed")); } namespace Action { Text SetPartitionId::text(const Actiongraph::Impl& actiongraph, bool doing) const { const Partition* partition = to_partition(device_rhs(actiongraph)); return partition->get_impl().do_set_id_text(doing); } void SetPartitionId::commit(const Actiongraph::Impl& actiongraph) const { const Partition* partition = to_partition(device_rhs(actiongraph)); partition->get_impl().do_set_id(); } } string id_to_string(unsigned int id) { switch (id) { case ID_SWAP: return "Linux Swap"; case ID_LINUX: return "Linux"; case ID_LVM: return "Linux LVM"; case ID_RAID: return "Linux RAID"; } return ""; } } <commit_msg>- call parted with filesystem type depending on partition id<commit_after> #include <iostream> #include "storage/Devices/PartitionImpl.h" #include "storage/Devices/DiskImpl.h" #include "storage/Devicegraph.h" #include "storage/SystemInfo/SystemInfo.h" #include "storage/Utils/SystemCmd.h" #include "storage/Utils/StorageDefines.h" #include "storage/Utils/StorageTmpl.h" namespace storage { using namespace std; const char* DeviceTraits<Partition>::classname = "Partition"; Partition::Impl::Impl(const string& name, const Region& region, PartitionType type) : BlkDevice::Impl(name, region.to_kb(region.get_length())), region(region), type(type), id(ID_LINUX), boot(false) { } Partition::Impl::Impl(const xmlNode* node) : BlkDevice::Impl(node), region(), type(PRIMARY), id(ID_LINUX), boot(false) { string tmp; getChildValue(node, "region", region); if (getChildValue(node, "type", tmp)) type = toValueWithFallback(tmp, PRIMARY); getChildValue(node, "id", id); getChildValue(node, "boot", boot); } void Partition::Impl::probe(SystemInfo& systeminfo) { BlkDevice::Impl::probe(systeminfo); const Devicegraph* g = get_devicegraph(); Devicegraph::Impl::vertex_descriptor v1 = g->get_impl().parent(get_vertex()); Devicegraph::Impl::vertex_descriptor v2 = g->get_impl().parent(v1); string pp_name = dynamic_cast<const BlkDevice*>(g->get_impl()[v2])->get_name(); const Parted& parted = systeminfo.getParted(pp_name); Parted::Entry entry; if (!parted.getEntry(get_number(), entry)) throw; id = entry.id; boot = entry.boot; } void Partition::Impl::save(xmlNode* node) const { BlkDevice::Impl::save(node); setChildValue(node, "region", region); setChildValue(node, "type", toString(type)); setChildValueIf(node, "id", id, id != 0); setChildValueIf(node, "boot", boot, boot); } unsigned int Partition::Impl::get_number() const { string::size_type pos = get_name().find_last_not_of("0123456789"); return atoi(get_name().substr(pos + 1).c_str()); } void Partition::Impl::set_size_k(unsigned long long size_k) { BlkDevice::Impl::set_size_k(size_k); const PartitionTable* partitiontable = get_partition_table(); const Disk* disk = partitiontable->get_disk(); region.set_length(get_size_k() * 1024 / disk->get_impl().get_geometry().cylinderSize()); } void Partition::Impl::set_region(const Region& region) { Impl::region = region; const PartitionTable* partitiontable = get_partition_table(); const Disk* disk = partitiontable->get_disk(); const Geometry& geometry = disk->get_impl().get_geometry(); if (region.get_block_size() != geometry.cylinderSize()) ST_THROW(DifferentBlockSizes(region.get_block_size(), geometry.cylinderSize())); set_size_k(region.get_length() * disk->get_impl().get_geometry().cylinderSize() / 1024); } const PartitionTable* Partition::Impl::get_partition_table() const { Devicegraph::Impl::vertex_descriptor v = get_devicegraph()->get_impl().parent(get_vertex()); return to_partition_table(get_devicegraph()->get_impl()[v]); } void Partition::Impl::add_create_actions(Actiongraph::Impl& actiongraph) const { vector<Action::Base*> actions; actions.push_back(new Action::Create(get_sid())); actions.push_back(new Action::SetPartitionId(get_sid())); actiongraph.add_chain(actions); } void Partition::Impl::add_modify_actions(Actiongraph::Impl& actiongraph, const Device* lhs_base) const { const Impl& lhs = dynamic_cast<const Impl&>(lhs_base->get_impl()); if (get_type() != lhs.get_type()) { throw runtime_error("cannot change partition type"); } if (get_region().get_start() != lhs.get_region().get_start()) { throw runtime_error("cannot move partition"); } if (get_id() != lhs.get_id()) { Action::Base* action = new Action::SetPartitionId(get_sid()); actiongraph.add_vertex(action); } } void Partition::Impl::add_delete_actions(Actiongraph::Impl& actiongraph) const { vector<Action::Base*> actions; actions.push_back(new Action::Delete(get_sid())); actiongraph.add_chain(actions); } bool Partition::Impl::equal(const Device::Impl& rhs_base) const { const Impl& rhs = dynamic_cast<const Impl&>(rhs_base); if (!BlkDevice::Impl::equal(rhs)) return false; return region == rhs.region && type == rhs.type && id == rhs.id && boot == rhs.boot; } void Partition::Impl::log_diff(std::ostream& log, const Device::Impl& rhs_base) const { const Impl& rhs = dynamic_cast<const Impl&>(rhs_base); BlkDevice::Impl::log_diff(log, rhs); storage::log_diff(log, "region", region, rhs.region); storage::log_diff_enum(log, "type", type, rhs.type); storage::log_diff_hex(log, "id", id, rhs.id); storage::log_diff(log, "boot", boot, rhs.boot); } void Partition::Impl::print(std::ostream& out) const { BlkDevice::Impl::print(out); out << " region:" << get_region(); } void Partition::Impl::process_udev_ids(vector<string>& udev_ids) const { const Devicegraph* g = get_devicegraph(); Devicegraph::Impl::vertex_descriptor v1 = g->get_impl().parent(get_vertex()); Devicegraph::Impl::vertex_descriptor v2 = g->get_impl().parent(v1); const Disk* disk = dynamic_cast<const Disk*>(g->get_impl()[v2]); disk->get_impl().process_udev_ids(udev_ids); } bool Partition::Impl::cmp_lt_number(const Partition* lhs, const Partition* rhs) { return lhs->get_number() < rhs->get_number(); } Text Partition::Impl::do_create_text(bool doing) const { return sformat(_("Create partition %1$s (%2$s)"), get_name().c_str(), get_size_string().c_str()); } void Partition::Impl::do_create() const { const PartitionTable* partitiontable = get_partition_table(); const Disk* disk = partitiontable->get_disk(); string cmd_line = PARTEDBIN " -s " + quote(disk->get_name()) + " unit cyl mkpart " + toString(get_type()) + " "; if (get_type() != EXTENDED) { switch (get_id()) { case ID_SWAP: cmd_line += "linux-swap "; break; case ID_GPT_BOOT: case ID_DOS16: case ID_DOS32: cmd_line += "fat32 "; break; case ID_APPLE_HFS: cmd_line += "hfs "; break; default: cmd_line += "ext2 "; break; } } cmd_line += to_string(get_region().get_start()) + " " + to_string(get_region().get_end()); cout << cmd_line << endl; SystemCmd cmd(cmd_line); if (cmd.retcode() != 0) ST_THROW(Exception("create partition failed")); } Text Partition::Impl::do_set_id_text(bool doing) const { string tmp = id_to_string(get_id()); if (tmp.empty()) return sformat(_("Set id of partition %1$s to 0x%2$02X"), get_name().c_str(), get_id()); else return sformat(_("Set id of partition %1$s to %2$s (0x%3$02X)"), get_name().c_str(), tmp.c_str(), get_id()); } void Partition::Impl::do_set_id() const { const PartitionTable* partitiontable = get_partition_table(); const Disk* disk = partitiontable->get_disk(); string cmd_line = PARTEDBIN " -s " + quote(disk->get_name()) + " set " + to_string(get_number()) + " type " + to_string(get_id()); cout << cmd_line << endl; SystemCmd cmd(cmd_line); if (cmd.retcode() != 0) ST_THROW(Exception("set partition id failed")); } Text Partition::Impl::do_delete_text(bool doing) const { return sformat(_("Delete partition %1$s (%2$s)"), get_name().c_str(), get_size_string().c_str()); } void Partition::Impl::do_delete() const { const PartitionTable* partitiontable = get_partition_table(); const Disk* disk = partitiontable->get_disk(); string cmd_line = PARTEDBIN " -s " + disk->get_name() + " rm " + to_string(get_number()); cout << cmd_line << endl; SystemCmd cmd(cmd_line); if (cmd.retcode() != 0) ST_THROW(Exception("delete partition failed")); } namespace Action { Text SetPartitionId::text(const Actiongraph::Impl& actiongraph, bool doing) const { const Partition* partition = to_partition(device_rhs(actiongraph)); return partition->get_impl().do_set_id_text(doing); } void SetPartitionId::commit(const Actiongraph::Impl& actiongraph) const { const Partition* partition = to_partition(device_rhs(actiongraph)); partition->get_impl().do_set_id(); } } string id_to_string(unsigned int id) { switch (id) { case ID_SWAP: return "Linux Swap"; case ID_LINUX: return "Linux"; case ID_LVM: return "Linux LVM"; case ID_RAID: return "Linux RAID"; } return ""; } } <|endoftext|>
<commit_before>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/chips/p9/procedures/hwp/pm/p9_pm_occ_control.H $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2015,2019 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* Licensed under the Apache License, Version 2.0 (the "License"); */ /* you may not use this file except in compliance with the License. */ /* You may obtain a copy of the License at */ /* */ /* http://www.apache.org/licenses/LICENSE-2.0 */ /* */ /* Unless required by applicable law or agreed to in writing, software */ /* distributed under the License is distributed on an "AS IS" BASIS, */ /* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */ /* implied. See the License for the specific language governing */ /* permissions and limitations under the License. */ /* */ /* IBM_PROLOG_END_TAG */ /// /// @file p9_pm_occ_control.H /// @brief Reset and halt control of the OCC PPC405 /// // *HWP HWP Owner: Greg Still <stillgs @us.ibm.com> // *HWP FW Owner: Sangeetha T S <sangeet2@in.ibm.com> // *HWP Team: PM // *HWP Level: 2 // *HWP Consumed by: FSP:HS /// /// @verbatim /// High-level procedure flow: /// - process parameters passed to procedure /// - If (i_ppc405_boot_ctrl != PPC405_BOOT_NULL) /// Initialize boot vector registers in SRAM (SRBV0,1,2,3) /// - Initialize SRBV0,1,2 with all 0's (illegal instructions) /// - Initialize SRBV0 per passed parameter (i_ppc405_boot_ctrl) /// - If (i_ppc405_boot_ctrl = PPC405_BOOT_SRAM) /// Initialize to Branch Absolute 0xFFF80010 /// - If (i_ppc405_boot_ctrl = PPC405_BOOT_MEM) /// Initialize to Branch Absolute 0x00000010 /// - If (i_ppc405_boot_ctrl = PPC405_BOOT_OLD) /// initialize to Branch Relative -16 /// - Write PPC405 reset/halt bits based on i_ppc405_reset_ctrl (OCR, OJCFG) /// - if PPC405_RESET_NULL , do nothing /// - if PPC405_RESET_OFF , write reset bit to 0 (PPC405 not reset) /// - if PPC405_RESET_ON , write reset bit to 1 (PPC405 reset) /// - if PPC405_HALT_OFF , write halt bit to 0 (PPC405 not halted) /// - if PPC405_HALT_ON , write halt bit to 1 (PPC405 halted) /// - if PPC405_RESET_SEQUENCE , Perform the safe halt->reset sequence /// - if PPC405_START , Start the PPC405 /// /// Procedure Prereq: /// - System clocks are running /// @endverbatim #ifndef _P9_OCC_CONTROL_H_ #define _P9_OCC_CONTROL_H_ // ----------------------------------------------------------------------------- // Includes // ----------------------------------------------------------------------------- #include <fapi2.H> #include <p9_pm.H> #include <p9_misc_scom_addresses.H> #include <p9_perv_scom_addresses.H> // ----------------------------------------------------------------------------- // ENUMS // ----------------------------------------------------------------------------- namespace p9occ_ctrl { enum PPC_CONTROL { PPC405_RESET_NULL, ///< Do nothing PPC405_RESET_OFF, ///< Deassert the PPC405 reset PPC405_RESET_ON, ///< Assert the PPC405 reset PPC405_HALT_OFF, ///< Deassert the PPC405 halt PPC405_HALT_ON, ///< Assert the PPC405 halt PPC405_RESET_SEQUENCE, ///< Perform the safe halt->reset sequence PPC405_START ///< Perform start sequence }; enum PPC_BOOT_CONTROL { PPC405_BOOT_NULL, ///< Do nothing PPC405_BOOT_SRAM, ///< Boot from OCC SRAM PPC405_BOOT_MEM, ///< Boot from memory PPC405_BOOT_OLD ///< Deprecated }; } // function pointer typedef definition for HWP call support typedef fapi2::ReturnCode (*p9_pm_occ_control_FP_t) (const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>&, const p9occ_ctrl::PPC_CONTROL, const p9occ_ctrl::PPC_BOOT_CONTROL); extern "C" { // ----------------------------------------------------------------------------- // Function prototype // ----------------------------------------------------------------------------- /// @brief Control the operation of the OCC PPC405 /// @param [in] i_target Chip Target /// @param [in] i_ppc405_reset_ctrl Actionto be taken on PPC405 /// @param [in] i_ppc405_boot_ctrl Location of boot instruction /// /// @return FAPI_RC_SUCCESS on success or error return code fapi2::ReturnCode p9_pm_occ_control( const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target, const p9occ_ctrl::PPC_CONTROL i_ppc405_reset_ctrl, const p9occ_ctrl::PPC_BOOT_CONTROL i_ppc405_boot_ctrl); } // extern "C" #endif // _P9_OCC_CONTROL_H_ <commit_msg>p9_pm_occ_control Fix OCC memory boot launching<commit_after>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/chips/p9/procedures/hwp/pm/p9_pm_occ_control.H $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2015,2019 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* Licensed under the Apache License, Version 2.0 (the "License"); */ /* you may not use this file except in compliance with the License. */ /* You may obtain a copy of the License at */ /* */ /* http://www.apache.org/licenses/LICENSE-2.0 */ /* */ /* Unless required by applicable law or agreed to in writing, software */ /* distributed under the License is distributed on an "AS IS" BASIS, */ /* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */ /* implied. See the License for the specific language governing */ /* permissions and limitations under the License. */ /* */ /* IBM_PROLOG_END_TAG */ /// /// @file p9_pm_occ_control.H /// @brief Reset and halt control of the OCC PPC405 /// // *HWP HWP Owner: Greg Still <stillgs @us.ibm.com> // *HWP FW Owner: Sangeetha T S <sangeet2@in.ibm.com> // *HWP Team: PM // *HWP Level: 2 // *HWP Consumed by: FSP:HS /// /// @verbatim /// High-level procedure flow: /// - process parameters passed to procedure /// - If (i_ppc405_boot_ctrl != PPC405_BOOT_NULL) /// Initialize boot vector registers in SRAM (SRBV0,1,2,3) /// - Initialize SRBV0,1,2 with all 0's (illegal instructions) /// - Initialize SRBV0 per passed parameter (i_ppc405_boot_ctrl) /// - If (i_ppc405_boot_ctrl = PPC405_BOOT_SRAM) /// Initialize to Branch Absolute 0xFFF80010 /// - Else If (i_ppc405_boot_ctrl = PPC405_BOOT_OLD) /// initialize to Branch Relative -16 /// - Else (i_ppc405_boot_ctrl = PPC405_BOOT_MEM || NULL) /// Load branch formation code into OCC SRAM at 0xFFF40000 /// to branch to 0x80000010 (HOMER + 0x40) /// Initialize to Branch Absolute 0xFFF40000 /// - Write PPC405 reset/halt bits based on i_ppc405_reset_ctrl (OCR, OJCFG) /// - if PPC405_RESET_NULL , do nothing /// - if PPC405_RESET_OFF , write reset bit to 0 (PPC405 not reset) /// - if PPC405_RESET_ON , write reset bit to 1 (PPC405 reset) /// - if PPC405_HALT_OFF , write halt bit to 0 (PPC405 not halted) /// - if PPC405_HALT_ON , write halt bit to 1 (PPC405 halted) /// - if PPC405_RESET_SEQUENCE , Perform the safe halt->reset sequence /// - if PPC405_START , Start the PPC405 /// /// Procedure Prereq: /// - System clocks are running /// @endverbatim #ifndef _P9_OCC_CONTROL_H_ #define _P9_OCC_CONTROL_H_ // ----------------------------------------------------------------------------- // Includes // ----------------------------------------------------------------------------- #include <fapi2.H> #include <p9_pm.H> #include <p9_misc_scom_addresses.H> #include <p9_perv_scom_addresses.H> // ----------------------------------------------------------------------------- // ENUMS // ----------------------------------------------------------------------------- namespace p9occ_ctrl { enum PPC_CONTROL { PPC405_RESET_NULL, ///< Do nothing PPC405_RESET_OFF, ///< Deassert the PPC405 reset PPC405_RESET_ON, ///< Assert the PPC405 reset PPC405_HALT_OFF, ///< Deassert the PPC405 halt PPC405_HALT_ON, ///< Assert the PPC405 halt PPC405_RESET_SEQUENCE, ///< Perform the safe halt->reset sequence PPC405_START ///< Perform start sequence }; enum PPC_BOOT_CONTROL { PPC405_BOOT_NULL, ///< Do nothing PPC405_BOOT_SRAM, ///< Boot from OCC SRAM PPC405_BOOT_MEM, ///< Boot from memory PPC405_BOOT_OLD ///< Deprecated }; } // function pointer typedef definition for HWP call support typedef fapi2::ReturnCode (*p9_pm_occ_control_FP_t) (const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>&, const p9occ_ctrl::PPC_CONTROL, const p9occ_ctrl::PPC_BOOT_CONTROL); extern "C" { // ----------------------------------------------------------------------------- // Function prototype // ----------------------------------------------------------------------------- /// @brief Control the operation of the OCC PPC405 /// @param [in] i_target Chip Target /// @param [in] i_ppc405_reset_ctrl Actionto be taken on PPC405 /// @param [in] i_ppc405_boot_ctrl Location of boot instruction /// /// @return FAPI_RC_SUCCESS on success or error return code fapi2::ReturnCode p9_pm_occ_control( const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target, const p9occ_ctrl::PPC_CONTROL i_ppc405_reset_ctrl, const p9occ_ctrl::PPC_BOOT_CONTROL i_ppc405_boot_ctrl); } // extern "C" #endif // _P9_OCC_CONTROL_H_ <|endoftext|>
<commit_before>/* * Copyright (c) 2018 SUSE LLC * * All Rights Reserved. * * This program is free software; you can redistribute it and/or modify it * under the terms of version 2 of the GNU General Public License as published * by the Free Software Foundation. * * 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, contact Novell, Inc. * * To contact Novell about this file by physical or electronic mail, you may * find current contact information at www.novell.com. */ #include "storage/Utils/StorageDefines.h" #include "storage/Utils/SystemCmd.h" #include "storage/Devices/BlkDeviceImpl.h" #include "storage/Filesystems/ExfatImpl.h" #include "storage/FreeInfo.h" #include "storage/UsedFeatures.h" namespace storage { using namespace std; const char* DeviceTraits<Exfat>::classname = "Exfat"; Exfat::Impl::Impl(const xmlNode* node) : BlkFilesystem::Impl(node) { } string Exfat::Impl::get_pretty_classname() const { // TRANSLATORS: name of object return _("EXFAT").translated; } ContentInfo Exfat::Impl::detect_content_info_on_disk() const { EnsureMounted ensure_mounted(get_filesystem()); ContentInfo content_info; content_info.is_windows = detect_is_windows(ensure_mounted.get_any_mount_point()); return content_info; } uint64_t Exfat::Impl::used_features() const { return UF_EXFAT | BlkFilesystem::Impl::used_features(); } void Exfat::Impl::do_create() { const BlkDevice* blk_device = get_blk_device(); string cmd_line = MKFS_EXFAT_BIN " " + get_mkfs_options() + " " + quote(blk_device->get_name()); wait_for_devices(); SystemCmd cmd(cmd_line, SystemCmd::DoThrow); probe_uuid(); } void Exfat::Impl::do_set_label() const { const BlkDevice* blk_device = get_blk_device(); string cmd_line = EXFAT_LABEL_BIN " " + quote(blk_device->get_name()) + " " + quote(get_label()); SystemCmd cmd(cmd_line, SystemCmd::DoThrow); } } <commit_msg>- changed pretty name<commit_after>/* * Copyright (c) 2018 SUSE LLC * * All Rights Reserved. * * This program is free software; you can redistribute it and/or modify it * under the terms of version 2 of the GNU General Public License as published * by the Free Software Foundation. * * 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, contact Novell, Inc. * * To contact Novell about this file by physical or electronic mail, you may * find current contact information at www.novell.com. */ #include "storage/Utils/StorageDefines.h" #include "storage/Utils/SystemCmd.h" #include "storage/Devices/BlkDeviceImpl.h" #include "storage/Filesystems/ExfatImpl.h" #include "storage/FreeInfo.h" #include "storage/UsedFeatures.h" namespace storage { using namespace std; const char* DeviceTraits<Exfat>::classname = "Exfat"; Exfat::Impl::Impl(const xmlNode* node) : BlkFilesystem::Impl(node) { } string Exfat::Impl::get_pretty_classname() const { // TRANSLATORS: name of a filesystem object in the storage devicegraph return _("exFAT").translated; } ContentInfo Exfat::Impl::detect_content_info_on_disk() const { EnsureMounted ensure_mounted(get_filesystem()); ContentInfo content_info; content_info.is_windows = detect_is_windows(ensure_mounted.get_any_mount_point()); return content_info; } uint64_t Exfat::Impl::used_features() const { return UF_EXFAT | BlkFilesystem::Impl::used_features(); } void Exfat::Impl::do_create() { const BlkDevice* blk_device = get_blk_device(); string cmd_line = MKFS_EXFAT_BIN " " + get_mkfs_options() + " " + quote(blk_device->get_name()); wait_for_devices(); SystemCmd cmd(cmd_line, SystemCmd::DoThrow); probe_uuid(); } void Exfat::Impl::do_set_label() const { const BlkDevice* blk_device = get_blk_device(); string cmd_line = EXFAT_LABEL_BIN " " + quote(blk_device->get_name()) + " " + quote(get_label()); SystemCmd cmd(cmd_line, SystemCmd::DoThrow); } } <|endoftext|>
<commit_before>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/chips/p9/procedures/hwp/pm/p9_quad_power_off.C $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2015,2019 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* Licensed under the Apache License, Version 2.0 (the "License"); */ /* you may not use this file except in compliance with the License. */ /* You may obtain a copy of the License at */ /* */ /* http://www.apache.org/licenses/LICENSE-2.0 */ /* */ /* Unless required by applicable law or agreed to in writing, software */ /* distributed under the License is distributed on an "AS IS" BASIS, */ /* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */ /* implied. See the License for the specific language governing */ /* permissions and limitations under the License. */ /* */ /* IBM_PROLOG_END_TAG */ /// /// @file p9_quad_power_off.C /// @brief Power off the EQ including the functional cores associatated with it. /// //---------------------------------------------------------------------------- // *HWP HWP Owner : Greg Still <stillgs@us.ibm.com> // *HWP FW Owner : Sumit Kumar <sumit_kumar@in.ibm.com> // *HWP Team : PM // *HWP Level : 2 // *HWP Consumed by : OCC:CME:FSP //---------------------------------------------------------------------------- // // @verbatim // High-level procedure flow: // - For each good EC associated with the targeted EQ, power it off. // - Power off the EQ. // @endverbatim // //------------------------------------------------------------------------------ // ---------------------------------------------------------------------- // Includes // ---------------------------------------------------------------------- #include <p9_quad_power_off.H> // ---------------------------------------------------------------------- // Function definitions // ---------------------------------------------------------------------- // Procedure p9_quad_power_off entry point, comments in header fapi2::ReturnCode p9_quad_power_off( const fapi2::Target<fapi2::TARGET_TYPE_EQ>& i_target) { fapi2::ReturnCode rc = fapi2::FAPI2_RC_SUCCESS; uint8_t l_unit_pos = 0; FAPI_INF("p9_quad_power_off: Entering..."); // Get chiplet position FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_CHIP_UNIT_POS, i_target, l_unit_pos)); FAPI_INF("Quad power off chiplet no.%d", l_unit_pos); // Call the procedure p9_pm_pfet_control_eq(i_target, PM_PFET_TYPE_C::BOTH, PM_PFET_TYPE_C::OFF); FAPI_INF("p9_quad_power_off: ...Exiting"); fapi_try_exit: return fapi2::current_err; } <commit_msg>p9_quad_power_off.C fix for chip unit pos<commit_after>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/chips/p9/procedures/hwp/pm/p9_quad_power_off.C $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2015,2019 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* Licensed under the Apache License, Version 2.0 (the "License"); */ /* you may not use this file except in compliance with the License. */ /* You may obtain a copy of the License at */ /* */ /* http://www.apache.org/licenses/LICENSE-2.0 */ /* */ /* Unless required by applicable law or agreed to in writing, software */ /* distributed under the License is distributed on an "AS IS" BASIS, */ /* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */ /* implied. See the License for the specific language governing */ /* permissions and limitations under the License. */ /* */ /* IBM_PROLOG_END_TAG */ /// /// @file p9_quad_power_off.C /// @brief Power off the EQ including the functional cores associatated with it. /// //---------------------------------------------------------------------------- // *HWP HWP Owner : Greg Still <stillgs@us.ibm.com> // *HWP FW Owner : Sumit Kumar <sumit_kumar@in.ibm.com> // *HWP Team : PM // *HWP Level : 2 // *HWP Consumed by : OCC:CME:FSP //---------------------------------------------------------------------------- // // @verbatim // High-level procedure flow: // - For each good EC associated with the targeted EQ, power it off. // - Power off the EQ. // @endverbatim // //------------------------------------------------------------------------------ // ---------------------------------------------------------------------- // Includes // ---------------------------------------------------------------------- #include <p9_quad_power_off.H> // ---------------------------------------------------------------------- // Function definitions // ---------------------------------------------------------------------- // Procedure p9_quad_power_off entry point, comments in header fapi2::ReturnCode p9_quad_power_off( const fapi2::Target<fapi2::TARGET_TYPE_EQ>& i_target) { fapi2::ReturnCode rc = fapi2::FAPI2_RC_SUCCESS; uint32_t l_unit_pos = 0; FAPI_INF("p9_quad_power_off: Entering..."); // Get chiplet position l_unit_pos = i_target.getChipletNumber(); FAPI_INF("Quad power off chiplet no.%d", l_unit_pos); // Call the procedure FAPI_EXEC_HWP(rc, p9_pm_pfet_control_eq, i_target, PM_PFET_TYPE_C::BOTH,PM_PFET_TYPE_C::OFF); FAPI_TRY(rc); fapi_try_exit: FAPI_INF("p9_quad_power_off: ...Exiting"); return fapi2::current_err; } <|endoftext|>
<commit_before>#include "extended.h" #include <core/db.h> #include <core/path.h> #include <text/text.h> #include <misc/repl.h> ExtendedTrack::ExtendedTrack(int tid){ id = 0; if(tid<=0) return; DB::Result r = DB::query( "SELECT tracks.title, tracks.user_id, users.name, tracks.visible, tracks.date," " tracks.notes, tracks.airable, tracks.license, array_to_string(tracks.tags, ',') FROM tracks, users " "WHERE tracks.id = " + number(tid) + " AND tracks.user_id = users.id"); if(!r.empty()){ id = tid; title = r[0][0]; artist = User(number(r[0][1]), r[0][2]); visible = r[0][3] == "t"; date = r[0][4]; // Ext notes = r[0][5]; airable = r[0][6] == "t"; license = r[0][7]; // Tags std::string tstr = r[0][8]; std::string buf; for(std::string::const_iterator i=tstr.begin(); i!=tstr.end(); i++){ if(*i == ','){ if(!buf.empty()){ tags.push_back(buf); buf.clear(); } } else buf += *i; } if(!buf.empty()) tags.push_back(buf); // last tag } } void ExtendedTrack::fill(Dict *d) const{ Track::fill(d); d->SetValueAndShowSection("NOTES", notes, "HAS_NOTES"); d->SetValueAndShowSection("LICENSE", license, "HAS_LICENSE"); d->ShowSection(airable ? "IS_AIRABLE" : "NOT_AIRABLE"); // Tags if(!tags.empty()){ d->ShowSection("HAS_TAGS"); for(std::vector<std::string>::const_iterator i=tags.begin(); i!=tags.end(); i++) d->SetValueAndShowSection("TAG", *i, "TAG"); } // License d->SetValue("LICENSE", license); d->ShowSection(license == "Copyright" ? "COPYRIGHT" : "OTHER_LICENSE"); } // Hits Repl hitsd; void initHitsd(){ if(!hitsd){ std::string path = eqbeatsDir() + "/hitsd.sock"; hitsd = Repl(path.c_str()); } } int ExtendedTrack::getHits(){ initHitsd(); return number(hitsd.exec("get " + number(id))); } int ExtendedTrack::hit(){ initHitsd(); return number(hitsd.exec("increment " + number(id))); } <commit_msg>hits: redis backend<commit_after>#include "extended.h" #include <core/db.h> #include <core/path.h> #include <text/text.h> #include <misc/repl.h> #include <hiredis/hiredis.h> ExtendedTrack::ExtendedTrack(int tid){ id = 0; if(tid<=0) return; DB::Result r = DB::query( "SELECT tracks.title, tracks.user_id, users.name, tracks.visible, tracks.date," " tracks.notes, tracks.airable, tracks.license, array_to_string(tracks.tags, ',') FROM tracks, users " "WHERE tracks.id = " + number(tid) + " AND tracks.user_id = users.id"); if(!r.empty()){ id = tid; title = r[0][0]; artist = User(number(r[0][1]), r[0][2]); visible = r[0][3] == "t"; date = r[0][4]; // Ext notes = r[0][5]; airable = r[0][6] == "t"; license = r[0][7]; // Tags std::string tstr = r[0][8]; std::string buf; for(std::string::const_iterator i=tstr.begin(); i!=tstr.end(); i++){ if(*i == ','){ if(!buf.empty()){ tags.push_back(buf); buf.clear(); } } else buf += *i; } if(!buf.empty()) tags.push_back(buf); // last tag } } void ExtendedTrack::fill(Dict *d) const{ Track::fill(d); d->SetValueAndShowSection("NOTES", notes, "HAS_NOTES"); d->SetValueAndShowSection("LICENSE", license, "HAS_LICENSE"); d->ShowSection(airable ? "IS_AIRABLE" : "NOT_AIRABLE"); // Tags if(!tags.empty()){ d->ShowSection("HAS_TAGS"); for(std::vector<std::string>::const_iterator i=tags.begin(); i!=tags.end(); i++) d->SetValueAndShowSection("TAG", *i, "TAG"); } // License d->SetValue("LICENSE", license); d->ShowSection(license == "Copyright" ? "COPYRIGHT" : "OTHER_LICENSE"); } // Hits int runRedis(const char *format, int id){ redisReply *reply = (redisReply*) redisCommand(DB::redis(), format, id); if(!reply) return 0; int hits = 0; if(reply->type == REDIS_REPLY_INTEGER) hits = reply->integer; else if(reply->type == REDIS_REPLY_STRING) hits = number((std::string) reply->str); freeReplyObject(reply); return hits; } int ExtendedTrack::getHits(){ return runRedis("GET hits:%d", id); } int ExtendedTrack::hit(){ return runRedis("INCR hits:%d", id); } <|endoftext|>
<commit_before>/* * Copyright (c) 2002-2005 The Regents of The University of Michigan * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer; * redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution; * neither the name of the copyright holders nor the names of 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. * * Authors: Ron Dreslinski * Ali Saidi */ /** * @file * Declaration of a bus object. */ #ifndef __MEM_BUS_HH__ #define __MEM_BUS_HH__ #include <string> #include <list> #include <inttypes.h> #include "base/range.hh" #include "mem/mem_object.hh" #include "mem/packet.hh" #include "mem/port.hh" #include "mem/request.hh" #include "sim/eventq.hh" class Bus : public MemObject { /** a globally unique id for this bus. */ int busId; /** the clock speed for the bus */ int clock; /** the width of the bus in bytes */ int width; /** the next tick at which the bus will be idle */ Tick tickNextIdle; static const int defaultId = -1; struct DevMap { int portId; Range<Addr> range; }; std::vector<DevMap> portList; AddrRangeList defaultRange; std::vector<DevMap> portSnoopList; /** Function called by the port when the bus is recieving a Timing transaction.*/ bool recvTiming(Packet *pkt); /** Function called by the port when the bus is recieving a Atomic transaction.*/ Tick recvAtomic(Packet *pkt); /** Function called by the port when the bus is recieving a Functional transaction.*/ void recvFunctional(Packet *pkt); /** Timing function called by port when it is once again able to process * requests. */ void recvRetry(int id); /** Function called by the port when the bus is recieving a status change.*/ void recvStatusChange(Port::Status status, int id); /** Find which port connected to this bus (if any) should be given a packet * with this address. * @param addr Address to find port for. * @param id Id of the port this packet was received from (to prevent * loops) * @return pointer to port that the packet should be sent out of. */ Port *findPort(Addr addr, int id); /** Find all ports with a matching snoop range, except src port. Keep in mind * that the ranges shouldn't overlap or you will get a double snoop to the same * interface.and the cache will assert out. * @param addr Address to find snoop prts for. * @param id Id of the src port of the request to avoid calling snoop on src * @return vector of IDs to snoop on */ std::vector<int> findSnoopPorts(Addr addr, int id); /** Snoop all relevant ports atomicly. */ Tick atomicSnoop(Packet *pkt); /** Snoop all relevant ports functionally. */ void functionalSnoop(Packet *pkt); /** Call snoop on caches, be sure to set SNOOP_COMMIT bit if you want * the snoop to happen * @return True if succeds. */ bool timingSnoop(Packet *pkt); /** Process address range request. * @param resp addresses that we can respond to * @param snoop addresses that we would like to snoop * @param id ide of the busport that made the request. */ void addressRanges(AddrRangeList &resp, AddrRangeList &snoop, int id); /** Occupy the bus with transmitting the packet pkt */ void occupyBus(PacketPtr pkt); /** Declaration of the buses port type, one will be instantiated for each of the interfaces connecting to the bus. */ class BusPort : public Port { bool _onRetryList; /** A pointer to the bus to which this port belongs. */ Bus *bus; /** A id to keep track of the intercafe ID this port is connected to. */ int id; public: /** Constructor for the BusPort.*/ BusPort(const std::string &_name, Bus *_bus, int _id) : Port(_name), _onRetryList(false), bus(_bus), id(_id) { } bool onRetryList() { return _onRetryList; } void onRetryList(bool newVal) { _onRetryList = newVal; } protected: /** When reciving a timing request from the peer port (at id), pass it to the bus. */ virtual bool recvTiming(Packet *pkt) { pkt->setSrc(id); return bus->recvTiming(pkt); } /** When reciving a Atomic requestfrom the peer port (at id), pass it to the bus. */ virtual Tick recvAtomic(Packet *pkt) { pkt->setSrc(id); return bus->recvAtomic(pkt); } /** When reciving a Functional requestfrom the peer port (at id), pass it to the bus. */ virtual void recvFunctional(Packet *pkt) { pkt->setSrc(id); bus->recvFunctional(pkt); } /** When reciving a status changefrom the peer port (at id), pass it to the bus. */ virtual void recvStatusChange(Status status) { bus->recvStatusChange(status, id); } /** When reciving a retry from the peer port (at id), pass it to the bus. */ virtual void recvRetry() { bus->recvRetry(id); } // This should return all the 'owned' addresses that are // downstream from this bus, yes? That is, the union of all // the 'owned' address ranges of all the other interfaces on // this bus... virtual void getDeviceAddressRanges(AddrRangeList &resp, AddrRangeList &snoop) { bus->addressRanges(resp, snoop, id); } // Hack to make translating port work without changes virtual int deviceBlockSize() { return 32; } }; class BusFreeEvent : public Event { Bus * bus; public: BusFreeEvent(Bus * _bus); void process(); const char *description(); }; BusFreeEvent busIdle; bool inRetry; /** An array of pointers to the peer port interfaces connected to this bus.*/ std::vector<BusPort*> interfaces; /** An array of pointers to ports that retry should be called on because the * original send failed for whatever reason.*/ std::list<BusPort*> retryList; void addToRetryList(BusPort * port) { if (!inRetry) { // The device wasn't retrying a packet, or wasn't at an appropriate // time. assert(!port->onRetryList()); port->onRetryList(true); retryList.push_back(port); } else { if (port->onRetryList()) { // The device was retrying a packet. It didn't work, so we'll leave // it at the head of the retry list. assert(port == retryList.front()); inRetry = false; } else { retryList.push_back(port); } } } /** Port that handles requests that don't match any of the interfaces.*/ Port *defaultPort; public: /** A function used to return the port associated with this bus object. */ virtual Port *getPort(const std::string &if_name, int idx = -1); virtual void init(); Bus(const std::string &n, int bus_id, int _clock, int _width) : MemObject(n), busId(bus_id), clock(_clock), width(_width), tickNextIdle(0), busIdle(this), inRetry(false), defaultPort(NULL) { //Both the width and clock period must be positive if (width <= 0) fatal("Bus width must be positive\n"); if (clock <= 0) fatal("Bus clock period must be positive\n"); } }; #endif //__MEM_BUS_HH__ <commit_msg>Forgot to mark myself as on the retry list<commit_after>/* * Copyright (c) 2002-2005 The Regents of The University of Michigan * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer; * redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution; * neither the name of the copyright holders nor the names of 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. * * Authors: Ron Dreslinski * Ali Saidi */ /** * @file * Declaration of a bus object. */ #ifndef __MEM_BUS_HH__ #define __MEM_BUS_HH__ #include <string> #include <list> #include <inttypes.h> #include "base/range.hh" #include "mem/mem_object.hh" #include "mem/packet.hh" #include "mem/port.hh" #include "mem/request.hh" #include "sim/eventq.hh" class Bus : public MemObject { /** a globally unique id for this bus. */ int busId; /** the clock speed for the bus */ int clock; /** the width of the bus in bytes */ int width; /** the next tick at which the bus will be idle */ Tick tickNextIdle; static const int defaultId = -1; struct DevMap { int portId; Range<Addr> range; }; std::vector<DevMap> portList; AddrRangeList defaultRange; std::vector<DevMap> portSnoopList; /** Function called by the port when the bus is recieving a Timing transaction.*/ bool recvTiming(Packet *pkt); /** Function called by the port when the bus is recieving a Atomic transaction.*/ Tick recvAtomic(Packet *pkt); /** Function called by the port when the bus is recieving a Functional transaction.*/ void recvFunctional(Packet *pkt); /** Timing function called by port when it is once again able to process * requests. */ void recvRetry(int id); /** Function called by the port when the bus is recieving a status change.*/ void recvStatusChange(Port::Status status, int id); /** Find which port connected to this bus (if any) should be given a packet * with this address. * @param addr Address to find port for. * @param id Id of the port this packet was received from (to prevent * loops) * @return pointer to port that the packet should be sent out of. */ Port *findPort(Addr addr, int id); /** Find all ports with a matching snoop range, except src port. Keep in mind * that the ranges shouldn't overlap or you will get a double snoop to the same * interface.and the cache will assert out. * @param addr Address to find snoop prts for. * @param id Id of the src port of the request to avoid calling snoop on src * @return vector of IDs to snoop on */ std::vector<int> findSnoopPorts(Addr addr, int id); /** Snoop all relevant ports atomicly. */ Tick atomicSnoop(Packet *pkt); /** Snoop all relevant ports functionally. */ void functionalSnoop(Packet *pkt); /** Call snoop on caches, be sure to set SNOOP_COMMIT bit if you want * the snoop to happen * @return True if succeds. */ bool timingSnoop(Packet *pkt); /** Process address range request. * @param resp addresses that we can respond to * @param snoop addresses that we would like to snoop * @param id ide of the busport that made the request. */ void addressRanges(AddrRangeList &resp, AddrRangeList &snoop, int id); /** Occupy the bus with transmitting the packet pkt */ void occupyBus(PacketPtr pkt); /** Declaration of the buses port type, one will be instantiated for each of the interfaces connecting to the bus. */ class BusPort : public Port { bool _onRetryList; /** A pointer to the bus to which this port belongs. */ Bus *bus; /** A id to keep track of the intercafe ID this port is connected to. */ int id; public: /** Constructor for the BusPort.*/ BusPort(const std::string &_name, Bus *_bus, int _id) : Port(_name), _onRetryList(false), bus(_bus), id(_id) { } bool onRetryList() { return _onRetryList; } void onRetryList(bool newVal) { _onRetryList = newVal; } protected: /** When reciving a timing request from the peer port (at id), pass it to the bus. */ virtual bool recvTiming(Packet *pkt) { pkt->setSrc(id); return bus->recvTiming(pkt); } /** When reciving a Atomic requestfrom the peer port (at id), pass it to the bus. */ virtual Tick recvAtomic(Packet *pkt) { pkt->setSrc(id); return bus->recvAtomic(pkt); } /** When reciving a Functional requestfrom the peer port (at id), pass it to the bus. */ virtual void recvFunctional(Packet *pkt) { pkt->setSrc(id); bus->recvFunctional(pkt); } /** When reciving a status changefrom the peer port (at id), pass it to the bus. */ virtual void recvStatusChange(Status status) { bus->recvStatusChange(status, id); } /** When reciving a retry from the peer port (at id), pass it to the bus. */ virtual void recvRetry() { bus->recvRetry(id); } // This should return all the 'owned' addresses that are // downstream from this bus, yes? That is, the union of all // the 'owned' address ranges of all the other interfaces on // this bus... virtual void getDeviceAddressRanges(AddrRangeList &resp, AddrRangeList &snoop) { bus->addressRanges(resp, snoop, id); } // Hack to make translating port work without changes virtual int deviceBlockSize() { return 32; } }; class BusFreeEvent : public Event { Bus * bus; public: BusFreeEvent(Bus * _bus); void process(); const char *description(); }; BusFreeEvent busIdle; bool inRetry; /** An array of pointers to the peer port interfaces connected to this bus.*/ std::vector<BusPort*> interfaces; /** An array of pointers to ports that retry should be called on because the * original send failed for whatever reason.*/ std::list<BusPort*> retryList; void addToRetryList(BusPort * port) { if (!inRetry) { // The device wasn't retrying a packet, or wasn't at an appropriate // time. assert(!port->onRetryList()); port->onRetryList(true); retryList.push_back(port); } else { if (port->onRetryList()) { // The device was retrying a packet. It didn't work, so we'll leave // it at the head of the retry list. assert(port == retryList.front()); inRetry = false; } else { port->onRetryList(true); retryList.push_back(port); } } } /** Port that handles requests that don't match any of the interfaces.*/ Port *defaultPort; public: /** A function used to return the port associated with this bus object. */ virtual Port *getPort(const std::string &if_name, int idx = -1); virtual void init(); Bus(const std::string &n, int bus_id, int _clock, int _width) : MemObject(n), busId(bus_id), clock(_clock), width(_width), tickNextIdle(0), busIdle(this), inRetry(false), defaultPort(NULL) { //Both the width and clock period must be positive if (width <= 0) fatal("Bus width must be positive\n"); if (clock <= 0) fatal("Bus clock period must be positive\n"); } }; #endif //__MEM_BUS_HH__ <|endoftext|>
<commit_before>#include "include/moduler.hpp" #include "include/imoduleexport.hpp" #include <loader/include/loader.hpp> #include <logger/include/logger.hpp> #include <sstream> namespace moduler { static Moduler *modulerInstance{ nullptr }; class ModulerPrivate { public: loader::Loader *loaderInstance{ nullptr }; ModulerPrivate() : loaderInstance{ loader::createLoader() } {} ~ModulerPrivate() { loader::destroyLoader(); } }; Moduler::Moduler() { m_private = new ModulerPrivate; } Moduler::~Moduler() { delete m_private; } using CreateModuleFunc = bool (*)(); using GetModuleFunc = moduler::IModule * (*)(); using DeleteModuleFunc = bool(*)(); IModule *Moduler::loadModule(const char * fileName) { LOG_DEBUG_STR("Going to open " << fileName); auto *moduleData(m_private->loaderInstance->loadModule(fileName)); if (moduleData) { LOG_DEBUG("Object file loaded"); auto createModuleFunc = static_cast<CreateModuleFunc>(m_private->loaderInstance->loadMethod(fileName, CREATE_MODULE_FUNC_NAME_STR)); auto getModuleFunc = static_cast<GetModuleFunc>(m_private->loaderInstance->loadMethod(fileName, GET_MODULE_FUNC_NAME_STR)); auto deleteModuleFunc = static_cast<DeleteModuleFunc>(m_private->loaderInstance->loadMethod(fileName, DELETE_MODULE_FUNC_NAME_STR)); if (createModuleFunc && getModuleFunc && deleteModuleFunc) { LOG_INFO_STR("Module from " << fileName << " has correct interface definition"); LOG_INFO("Initializing module..."); createModuleFunc(); IModule *loadedModule = getModuleFunc(); auto *moduleInfo = loadedModule->moduleInformation(); LOG_INFO("Module info:"); LOG_INFO_STR("Name: " << moduleInfo->name); LOG_INFO_STR("Version: " << moduleInfo->version << "." << moduleInfo->subVersion << "." << moduleInfo->patch); LOG_INFO("Seems module has correct implementation"); return loadedModule; } else { LOG_WARNING("Cannot read method createModule()"); } } return nullptr; } Moduler *createModuler () { if (!modulerInstance) { LOG_DEBUG("Creating moduler..."); modulerInstance = new Moduler; LOG_DEBUG("Moduler created"); } else { LOG_DEBUG("Moduler already reated"); } return modulerInstance; } void destroyModuler() { if (modulerInstance) { LOG_DEBUG("Destroying moduler..."); delete modulerInstance; modulerInstance = nullptr; LOG_DEBUG("Moduler destroyed"); } } } <commit_msg>Store the loaded module<commit_after>#include "include/moduler.hpp" #include "include/imoduleexport.hpp" #include <loader/include/loader.hpp> #include <logger/include/logger.hpp> #include <sstream> #include <map> namespace moduler { static Moduler *modulerInstance{ nullptr }; struct ModuleData { using CreateModuleFunc = bool(*)(); using GetModuleFunc = moduler::IModule * (*)(); using DeleteModuleFunc = bool(*)(); ModuleInformation *moduleInformation{ nullptr }; CreateModuleFunc createModuleFunc{ nullptr }; GetModuleFunc getModuleFunc{ nullptr }; DeleteModuleFunc deleteModuleFunc{ nullptr }; std::string fileName; }; class ModulerPrivate { public: loader::Loader *loaderInstance{ nullptr }; std::map<std::string, ModuleData> modules; ModulerPrivate() : loaderInstance{ loader::createLoader() } {} ~ModulerPrivate() { loader::destroyLoader(); } }; Moduler::Moduler() { m_private = new ModulerPrivate; } Moduler::~Moduler() { delete m_private; } IModule *Moduler::loadModule(const char * fileName) { LOG_DEBUG_STR("Going to open " << fileName); auto *moduleObject(m_private->loaderInstance->loadModule(fileName)); if (moduleObject) { LOG_DEBUG("Object file loaded"); auto createModuleFunc = static_cast<ModuleData::CreateModuleFunc>(m_private->loaderInstance->loadMethod(fileName, CREATE_MODULE_FUNC_NAME_STR)); auto getModuleFunc = static_cast<ModuleData::GetModuleFunc>(m_private->loaderInstance->loadMethod(fileName, GET_MODULE_FUNC_NAME_STR)); auto deleteModuleFunc = static_cast<ModuleData::DeleteModuleFunc>(m_private->loaderInstance->loadMethod(fileName, DELETE_MODULE_FUNC_NAME_STR)); if (createModuleFunc && getModuleFunc && deleteModuleFunc) { LOG_INFO_STR("Module from " << fileName << " has correct interface definition"); LOG_INFO("Initializing module..."); createModuleFunc(); IModule *loadedModule = getModuleFunc(); auto *moduleInfo = loadedModule->moduleInformation(); LOG_INFO("Module info:"); LOG_INFO_STR("Name: " << moduleInfo->name); LOG_INFO_STR("Version: " << moduleInfo->version << "." << moduleInfo->subVersion << "." << moduleInfo->patch); LOG_INFO("Seems module has correct implementation"); ModuleData moduleData; moduleData.moduleInformation = loadedModule->moduleInformation(); moduleData.createModuleFunc = createModuleFunc; moduleData.getModuleFunc = getModuleFunc; moduleData.deleteModuleFunc = deleteModuleFunc; m_private->modules[fileName] = moduleData; return loadedModule; } else { LOG_WARNING("Cannot read method createModule()"); } } return nullptr; } Moduler *createModuler () { if (!modulerInstance) { LOG_DEBUG("Creating moduler..."); modulerInstance = new Moduler; LOG_DEBUG("Moduler created"); } else { LOG_DEBUG("Moduler already reated"); } return modulerInstance; } void destroyModuler() { if (modulerInstance) { LOG_DEBUG("Destroying moduler..."); delete modulerInstance; modulerInstance = nullptr; LOG_DEBUG("Moduler destroyed"); } } } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: mediator.hxx,v $ * * $Revision: 1.5 $ * * last change: $Author: obo $ $Date: 2004-03-17 10:14:48 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef _MEDIATOR_HXX #define _MEDIATOR_HXX #include <string.h> #include <stdarg.h> #ifndef _STRING_HXX #include <tools/string.hxx> #endif #ifndef _LIST_HXX #include <tools/list.hxx> #endif #ifndef _LINK_HXX #include <tools/link.hxx> #endif #ifndef _VOS_PIPE_HXX_ #include <vos/pipe.hxx> #endif #ifndef _VOS_MUTEX_HXX_ #include <vos/mutex.hxx> #endif #ifndef _VOS_CONDITN_HXX_ #include <vos/conditn.hxx> #endif #ifndef _VOS_THREAD_HXX_ #include <vos/thread.hxx> #endif #if OSL_DEBUG_LEVEL > 1 #include <stdio.h> #endif struct MediatorMessage { ULONG m_nID; ULONG m_nBytes; char* m_pBytes; char* m_pRun; MediatorMessage() : m_nID( 0 ), m_nBytes( 0 ), m_pBytes( NULL ), m_pRun( NULL ) {} MediatorMessage( ULONG nID, ULONG nBytes, char* pBytes ) : m_nID( nID ),m_nBytes( nBytes ), m_pRun( NULL ) { m_pBytes = new char[ m_nBytes ]; memcpy( m_pBytes, pBytes, (size_t)m_nBytes ); } ~MediatorMessage() { if( m_pBytes ) delete [] m_pBytes; } void Set( ULONG nBytes, char* pBytes ) { if( m_pBytes ) delete [] m_pBytes; m_nBytes = nBytes; m_pBytes = new char[ m_nBytes ]; memcpy( m_pBytes, pBytes, (size_t)m_nBytes ); } ULONG ExtractULONG(); char* GetString(); UINT32 GetUINT32(); void* GetBytes( ULONG& ); void* GetBytes() { ULONG nBytes; return GetBytes( nBytes ); } void Rewind() { m_pRun = NULL; } }; DECLARE_LIST( MediatorMessageList, MediatorMessage* ); class MediatorListener; class Mediator { friend class MediatorListener; protected: int m_nSocket; MediatorMessageList m_aMessageQueue; NAMESPACE_VOS(OMutex) m_aQueueMutex; NAMESPACE_VOS(OMutex) m_aSendMutex; // only one thread can send a message at any given time NAMESPACE_VOS(OCondition) m_aNewMessageCdtn; MediatorListener* m_pListener; // thread to fill the queue ULONG m_nCurrentID; // will be constantly increased with each message sent bool m_bValid; Link m_aConnectionLostHdl; Link m_aNewMessageHdl; public: Mediator( int nSocket ); ~Mediator(); // mark mediator as invalid. No more messages will be processed, // SendMessage, WaitForMessage, TransactMessage will return immediatly // with error void invalidate() { m_bValid = false; } ULONG SendMessage( ULONG nBytes, const char* pBytes, ULONG nMessageID = 0 ); ULONG SendMessage( const ByteString& rMessage, ULONG nMessageID = 0 ) { return SendMessage( rMessage.Len(), rMessage.GetBuffer(), nMessageID ); } BOOL WaitForMessage( ULONG nTimeOut = 5000 ); // timeout in ms // TRUE: Message came in // FALSE: timed out // if timeout is set, WaitForMessage will wait even if there are messages // in the queue virtual MediatorMessage* WaitForAnswer( ULONG nMessageID ); // wait for an answer message ( ID >= 1 << 24 ) // the message will be removed from the queue and returned MediatorMessage* TransactMessage( ULONG nBytes, char* pBytes ); // sends a message and waits for an answer MediatorMessage* GetNextMessage( BOOL bWait = FALSE ); Link SetConnectionLostHdl( const Link& rLink ) { Link aRet = m_aConnectionLostHdl; m_aConnectionLostHdl = rLink; return aRet; } Link SetNewMessageHdl( const Link& rLink ) { Link aRet = m_aNewMessageHdl; m_aNewMessageHdl = rLink; return aRet; } }; class MediatorListener : public NAMESPACE_VOS( OThread ) { friend class Mediator; private: Mediator* m_pMediator; ::vos::OMutex m_aMutex; MediatorListener( Mediator* ); ~MediatorListener(); virtual void run(); virtual void onTerminated(); }; inline void medDebug( int condition, const char* pFormat, ... ) { #if OSL_DEBUG_LEVEL > 1 if( condition ) { va_list ap; va_start( ap, pFormat ); vfprintf( stderr, pFormat, ap ); va_end( ap ); } #endif } #endif // _MEDIATOR_HXX <commit_msg>INTEGRATION: CWS ooo19126 (1.5.308); FILE MERGED 2005/09/05 12:59:48 rt 1.5.308.1: #i54170# Change license header: remove SISSL<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: mediator.hxx,v $ * * $Revision: 1.6 $ * * last change: $Author: rt $ $Date: 2005-09-08 19:54:22 $ * * 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 _MEDIATOR_HXX #define _MEDIATOR_HXX #include <string.h> #include <stdarg.h> #ifndef _STRING_HXX #include <tools/string.hxx> #endif #ifndef _LIST_HXX #include <tools/list.hxx> #endif #ifndef _LINK_HXX #include <tools/link.hxx> #endif #ifndef _VOS_PIPE_HXX_ #include <vos/pipe.hxx> #endif #ifndef _VOS_MUTEX_HXX_ #include <vos/mutex.hxx> #endif #ifndef _VOS_CONDITN_HXX_ #include <vos/conditn.hxx> #endif #ifndef _VOS_THREAD_HXX_ #include <vos/thread.hxx> #endif #if OSL_DEBUG_LEVEL > 1 #include <stdio.h> #endif struct MediatorMessage { ULONG m_nID; ULONG m_nBytes; char* m_pBytes; char* m_pRun; MediatorMessage() : m_nID( 0 ), m_nBytes( 0 ), m_pBytes( NULL ), m_pRun( NULL ) {} MediatorMessage( ULONG nID, ULONG nBytes, char* pBytes ) : m_nID( nID ),m_nBytes( nBytes ), m_pRun( NULL ) { m_pBytes = new char[ m_nBytes ]; memcpy( m_pBytes, pBytes, (size_t)m_nBytes ); } ~MediatorMessage() { if( m_pBytes ) delete [] m_pBytes; } void Set( ULONG nBytes, char* pBytes ) { if( m_pBytes ) delete [] m_pBytes; m_nBytes = nBytes; m_pBytes = new char[ m_nBytes ]; memcpy( m_pBytes, pBytes, (size_t)m_nBytes ); } ULONG ExtractULONG(); char* GetString(); UINT32 GetUINT32(); void* GetBytes( ULONG& ); void* GetBytes() { ULONG nBytes; return GetBytes( nBytes ); } void Rewind() { m_pRun = NULL; } }; DECLARE_LIST( MediatorMessageList, MediatorMessage* ); class MediatorListener; class Mediator { friend class MediatorListener; protected: int m_nSocket; MediatorMessageList m_aMessageQueue; NAMESPACE_VOS(OMutex) m_aQueueMutex; NAMESPACE_VOS(OMutex) m_aSendMutex; // only one thread can send a message at any given time NAMESPACE_VOS(OCondition) m_aNewMessageCdtn; MediatorListener* m_pListener; // thread to fill the queue ULONG m_nCurrentID; // will be constantly increased with each message sent bool m_bValid; Link m_aConnectionLostHdl; Link m_aNewMessageHdl; public: Mediator( int nSocket ); ~Mediator(); // mark mediator as invalid. No more messages will be processed, // SendMessage, WaitForMessage, TransactMessage will return immediatly // with error void invalidate() { m_bValid = false; } ULONG SendMessage( ULONG nBytes, const char* pBytes, ULONG nMessageID = 0 ); ULONG SendMessage( const ByteString& rMessage, ULONG nMessageID = 0 ) { return SendMessage( rMessage.Len(), rMessage.GetBuffer(), nMessageID ); } BOOL WaitForMessage( ULONG nTimeOut = 5000 ); // timeout in ms // TRUE: Message came in // FALSE: timed out // if timeout is set, WaitForMessage will wait even if there are messages // in the queue virtual MediatorMessage* WaitForAnswer( ULONG nMessageID ); // wait for an answer message ( ID >= 1 << 24 ) // the message will be removed from the queue and returned MediatorMessage* TransactMessage( ULONG nBytes, char* pBytes ); // sends a message and waits for an answer MediatorMessage* GetNextMessage( BOOL bWait = FALSE ); Link SetConnectionLostHdl( const Link& rLink ) { Link aRet = m_aConnectionLostHdl; m_aConnectionLostHdl = rLink; return aRet; } Link SetNewMessageHdl( const Link& rLink ) { Link aRet = m_aNewMessageHdl; m_aNewMessageHdl = rLink; return aRet; } }; class MediatorListener : public NAMESPACE_VOS( OThread ) { friend class Mediator; private: Mediator* m_pMediator; ::vos::OMutex m_aMutex; MediatorListener( Mediator* ); ~MediatorListener(); virtual void run(); virtual void onTerminated(); }; inline void medDebug( int condition, const char* pFormat, ... ) { #if OSL_DEBUG_LEVEL > 1 if( condition ) { va_list ap; va_start( ap, pFormat ); vfprintf( stderr, pFormat, ap ); va_end( ap ); } #endif } #endif // _MEDIATOR_HXX <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: objectinspectormodel.cxx,v $ * * $Revision: 1.5 $ * * last change: $Author: kz $ $Date: 2007-05-10 10:49:12 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_extensions.hxx" #ifndef EXTENSIONS_PROPCTRLR_MODULEPRC_HXX #include "modulepcr.hxx" #endif #ifndef _EXTENSIONS_PROPCTRLR_PCRCOMMON_HXX_ #include "pcrcommon.hxx" #endif #ifndef INSPECTORMODELBASE_HXX #include "inspectormodelbase.hxx" #endif /** === begin UNO includes === **/ #ifndef _COM_SUN_STAR_UCB_ALREADYINITIALIZEDEXCEPTION_HPP_ #include <com/sun/star/ucb/AlreadyInitializedException.hpp> #endif #ifndef _COM_SUN_STAR_LANG_ILLEGALARGUMENTEXCEPTION_HPP_ #include <com/sun/star/lang/IllegalArgumentException.hpp> #endif /** === end UNO includes === **/ #include <cppuhelper/implbase3.hxx> #include <comphelper/broadcasthelper.hxx> #include <comphelper/uno3.hxx> //........................................................................ namespace pcr { //........................................................................ /** === begin UNO using === **/ using ::com::sun::star::inspection::XObjectInspectorModel; using ::com::sun::star::lang::XInitialization; using ::com::sun::star::lang::XServiceInfo; using ::com::sun::star::uno::Reference; using ::com::sun::star::uno::XComponentContext; using ::com::sun::star::uno::RuntimeException; using ::com::sun::star::uno::Sequence; using ::com::sun::star::uno::Any; using ::com::sun::star::inspection::PropertyCategoryDescriptor; using ::com::sun::star::uno::Exception; using ::com::sun::star::uno::XInterface; using ::com::sun::star::lang::IllegalArgumentException; using ::com::sun::star::ucb::AlreadyInitializedException; using ::com::sun::star::beans::XPropertySetInfo; using ::com::sun::star::uno::makeAny; /** === end UNO using === **/ //==================================================================== //= ObjectInspectorModel //==================================================================== class ObjectInspectorModel : public ImplInspectorModel { private: Sequence< Any > m_aFactories; public: ObjectInspectorModel( const Reference< XComponentContext >& _rxContext ); // XObjectInspectorModel virtual Sequence< Any > SAL_CALL getHandlerFactories() throw (RuntimeException); virtual Sequence< PropertyCategoryDescriptor > SAL_CALL describeCategories( ) throw (RuntimeException); virtual ::sal_Int32 SAL_CALL getPropertyOrderIndex( const ::rtl::OUString& PropertyName ) throw (RuntimeException); // XInitialization virtual void SAL_CALL initialize( const Sequence< Any >& aArguments ) throw (Exception, RuntimeException); // XServiceInfo virtual ::rtl::OUString SAL_CALL getImplementationName( ) throw (RuntimeException); virtual Sequence< ::rtl::OUString > SAL_CALL getSupportedServiceNames( ) throw (RuntimeException); // XServiceInfo - static versions static ::rtl::OUString getImplementationName_static( ) throw(RuntimeException); static Sequence< ::rtl::OUString > getSupportedServiceNames_static( ) throw(RuntimeException); static Reference< XInterface > SAL_CALL Create(const Reference< XComponentContext >&); protected: void createDefault(); void createWithHandlerFactories( const Sequence< Any >& _rFactories ); void createWithHandlerFactoriesAndHelpSection( const Sequence< Any >& _rFactories, sal_Int32 _nMinHelpTextLines, sal_Int32 _nMaxHelpTextLines ); private: /** checks a given condition to be <TRUE/>, and throws an IllegalArgumentException if not */ void impl_verifyArgument_throw( bool _bCondition, sal_Int16 _nArgumentPosition ); }; //==================================================================== //= ObjectInspectorModel //==================================================================== ObjectInspectorModel::ObjectInspectorModel( const Reference< XComponentContext >& _rxContext ) :ImplInspectorModel( _rxContext ) { } //-------------------------------------------------------------------- Sequence< Any > SAL_CALL ObjectInspectorModel::getHandlerFactories() throw (RuntimeException) { return m_aFactories; } //-------------------------------------------------------------------- Sequence< PropertyCategoryDescriptor > SAL_CALL ObjectInspectorModel::describeCategories( ) throw (RuntimeException) { // no category info provided by this default implementation return Sequence< PropertyCategoryDescriptor >( ); } //-------------------------------------------------------------------- ::sal_Int32 SAL_CALL ObjectInspectorModel::getPropertyOrderIndex( const ::rtl::OUString& /*PropertyName*/ ) throw (RuntimeException) { // no ordering provided by this default implementation return 0; } //-------------------------------------------------------------------- void SAL_CALL ObjectInspectorModel::initialize( const Sequence< Any >& _arguments ) throw (Exception, RuntimeException) { ::osl::MutexGuard aGuard( m_aMutex ); if ( m_aFactories.getLength() ) throw AlreadyInitializedException(); StlSyntaxSequence< Any > arguments( _arguments ); if ( arguments.empty() ) { // constructor: "createDefault()" createDefault(); return; } Sequence< Any > factories; impl_verifyArgument_throw( arguments[0] >>= factories, 1 ); if ( arguments.size() == 1 ) { // constructor: "createWithHandlerFactories( any[] )" createWithHandlerFactories( factories ); return; } sal_Int32 nMinHelpTextLines( 0 ), nMaxHelpTextLines( 0 ); if ( arguments.size() == 3 ) { // constructor: "createWithHandlerFactoriesAndHelpSection( any[], long, long )" impl_verifyArgument_throw( arguments[1] >>= nMinHelpTextLines, 2 ); impl_verifyArgument_throw( arguments[2] >>= nMaxHelpTextLines, 3 ); createWithHandlerFactoriesAndHelpSection( factories, nMinHelpTextLines, nMaxHelpTextLines ); return; } impl_verifyArgument_throw( false, 2 ); } //-------------------------------------------------------------------- ::rtl::OUString SAL_CALL ObjectInspectorModel::getImplementationName( ) throw (RuntimeException) { return getImplementationName_static(); } //-------------------------------------------------------------------- Sequence< ::rtl::OUString > SAL_CALL ObjectInspectorModel::getSupportedServiceNames( ) throw (RuntimeException) { return getSupportedServiceNames_static(); } //-------------------------------------------------------------------- ::rtl::OUString ObjectInspectorModel::getImplementationName_static( ) throw(RuntimeException) { return ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "org.openoffice.comp.extensions.ObjectInspectorModel" ) ); } //-------------------------------------------------------------------- Sequence< ::rtl::OUString > ObjectInspectorModel::getSupportedServiceNames_static( ) throw(RuntimeException) { ::rtl::OUString sService( RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.inspection.ObjectInspectorModel" ) ); return Sequence< ::rtl::OUString >( &sService, 1 ); } //-------------------------------------------------------------------- Reference< XInterface > SAL_CALL ObjectInspectorModel::Create(const Reference< XComponentContext >& _rxContext ) { return *( new ObjectInspectorModel( _rxContext ) ); } //-------------------------------------------------------------------- void ObjectInspectorModel::createDefault() { m_aFactories.realloc( 1 ); m_aFactories[0] <<= ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.inspection.GenericPropertyHandler" ) ); } //-------------------------------------------------------------------- void ObjectInspectorModel::createWithHandlerFactories( const Sequence< Any >& _rFactories ) { impl_verifyArgument_throw( _rFactories.getLength() > 0, 1 ); m_aFactories = _rFactories; } //-------------------------------------------------------------------- void ObjectInspectorModel::createWithHandlerFactoriesAndHelpSection( const Sequence< Any >& _rFactories, sal_Int32 _nMinHelpTextLines, sal_Int32 _nMaxHelpTextLines ) { impl_verifyArgument_throw( _rFactories.getLength() > 0, 1 ); impl_verifyArgument_throw( _nMinHelpTextLines >= 1, 2 ); impl_verifyArgument_throw( _nMaxHelpTextLines >= 1, 3 ); impl_verifyArgument_throw( _nMinHelpTextLines <= _nMaxHelpTextLines, 2 ); m_aFactories = _rFactories; enableHelpSectionProperties( _nMinHelpTextLines, _nMaxHelpTextLines ); } //-------------------------------------------------------------------- void ObjectInspectorModel::impl_verifyArgument_throw( bool _bCondition, sal_Int16 _nArgumentPosition ) { if ( !_bCondition ) throw IllegalArgumentException( ::rtl::OUString(), *this, _nArgumentPosition ); } //........................................................................ } // namespace pcr //........................................................................ //------------------------------------------------------------------------ extern "C" void SAL_CALL createRegistryInfo_ObjectInspectorModel() { ::pcr::OAutoRegistration< ::pcr::ObjectInspectorModel > aObjectInspectorModelRegistration; } <commit_msg>INTEGRATION: CWS changefileheader (1.5.164); FILE MERGED 2008/04/01 12:29:50 thb 1.5.164.2: #i85898# Stripping all external header guards 2008/03/31 12:31:51 rt 1.5.164.1: #i87441# Change license header to LPGL v3.<commit_after>/************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2008 by Sun Microsystems, Inc. * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: objectinspectormodel.cxx,v $ * $Revision: 1.6 $ * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_extensions.hxx" #include "modulepcr.hxx" #include "pcrcommon.hxx" #include "inspectormodelbase.hxx" /** === begin UNO includes === **/ #include <com/sun/star/ucb/AlreadyInitializedException.hpp> #include <com/sun/star/lang/IllegalArgumentException.hpp> /** === end UNO includes === **/ #include <cppuhelper/implbase3.hxx> #include <comphelper/broadcasthelper.hxx> #include <comphelper/uno3.hxx> //........................................................................ namespace pcr { //........................................................................ /** === begin UNO using === **/ using ::com::sun::star::inspection::XObjectInspectorModel; using ::com::sun::star::lang::XInitialization; using ::com::sun::star::lang::XServiceInfo; using ::com::sun::star::uno::Reference; using ::com::sun::star::uno::XComponentContext; using ::com::sun::star::uno::RuntimeException; using ::com::sun::star::uno::Sequence; using ::com::sun::star::uno::Any; using ::com::sun::star::inspection::PropertyCategoryDescriptor; using ::com::sun::star::uno::Exception; using ::com::sun::star::uno::XInterface; using ::com::sun::star::lang::IllegalArgumentException; using ::com::sun::star::ucb::AlreadyInitializedException; using ::com::sun::star::beans::XPropertySetInfo; using ::com::sun::star::uno::makeAny; /** === end UNO using === **/ //==================================================================== //= ObjectInspectorModel //==================================================================== class ObjectInspectorModel : public ImplInspectorModel { private: Sequence< Any > m_aFactories; public: ObjectInspectorModel( const Reference< XComponentContext >& _rxContext ); // XObjectInspectorModel virtual Sequence< Any > SAL_CALL getHandlerFactories() throw (RuntimeException); virtual Sequence< PropertyCategoryDescriptor > SAL_CALL describeCategories( ) throw (RuntimeException); virtual ::sal_Int32 SAL_CALL getPropertyOrderIndex( const ::rtl::OUString& PropertyName ) throw (RuntimeException); // XInitialization virtual void SAL_CALL initialize( const Sequence< Any >& aArguments ) throw (Exception, RuntimeException); // XServiceInfo virtual ::rtl::OUString SAL_CALL getImplementationName( ) throw (RuntimeException); virtual Sequence< ::rtl::OUString > SAL_CALL getSupportedServiceNames( ) throw (RuntimeException); // XServiceInfo - static versions static ::rtl::OUString getImplementationName_static( ) throw(RuntimeException); static Sequence< ::rtl::OUString > getSupportedServiceNames_static( ) throw(RuntimeException); static Reference< XInterface > SAL_CALL Create(const Reference< XComponentContext >&); protected: void createDefault(); void createWithHandlerFactories( const Sequence< Any >& _rFactories ); void createWithHandlerFactoriesAndHelpSection( const Sequence< Any >& _rFactories, sal_Int32 _nMinHelpTextLines, sal_Int32 _nMaxHelpTextLines ); private: /** checks a given condition to be <TRUE/>, and throws an IllegalArgumentException if not */ void impl_verifyArgument_throw( bool _bCondition, sal_Int16 _nArgumentPosition ); }; //==================================================================== //= ObjectInspectorModel //==================================================================== ObjectInspectorModel::ObjectInspectorModel( const Reference< XComponentContext >& _rxContext ) :ImplInspectorModel( _rxContext ) { } //-------------------------------------------------------------------- Sequence< Any > SAL_CALL ObjectInspectorModel::getHandlerFactories() throw (RuntimeException) { return m_aFactories; } //-------------------------------------------------------------------- Sequence< PropertyCategoryDescriptor > SAL_CALL ObjectInspectorModel::describeCategories( ) throw (RuntimeException) { // no category info provided by this default implementation return Sequence< PropertyCategoryDescriptor >( ); } //-------------------------------------------------------------------- ::sal_Int32 SAL_CALL ObjectInspectorModel::getPropertyOrderIndex( const ::rtl::OUString& /*PropertyName*/ ) throw (RuntimeException) { // no ordering provided by this default implementation return 0; } //-------------------------------------------------------------------- void SAL_CALL ObjectInspectorModel::initialize( const Sequence< Any >& _arguments ) throw (Exception, RuntimeException) { ::osl::MutexGuard aGuard( m_aMutex ); if ( m_aFactories.getLength() ) throw AlreadyInitializedException(); StlSyntaxSequence< Any > arguments( _arguments ); if ( arguments.empty() ) { // constructor: "createDefault()" createDefault(); return; } Sequence< Any > factories; impl_verifyArgument_throw( arguments[0] >>= factories, 1 ); if ( arguments.size() == 1 ) { // constructor: "createWithHandlerFactories( any[] )" createWithHandlerFactories( factories ); return; } sal_Int32 nMinHelpTextLines( 0 ), nMaxHelpTextLines( 0 ); if ( arguments.size() == 3 ) { // constructor: "createWithHandlerFactoriesAndHelpSection( any[], long, long )" impl_verifyArgument_throw( arguments[1] >>= nMinHelpTextLines, 2 ); impl_verifyArgument_throw( arguments[2] >>= nMaxHelpTextLines, 3 ); createWithHandlerFactoriesAndHelpSection( factories, nMinHelpTextLines, nMaxHelpTextLines ); return; } impl_verifyArgument_throw( false, 2 ); } //-------------------------------------------------------------------- ::rtl::OUString SAL_CALL ObjectInspectorModel::getImplementationName( ) throw (RuntimeException) { return getImplementationName_static(); } //-------------------------------------------------------------------- Sequence< ::rtl::OUString > SAL_CALL ObjectInspectorModel::getSupportedServiceNames( ) throw (RuntimeException) { return getSupportedServiceNames_static(); } //-------------------------------------------------------------------- ::rtl::OUString ObjectInspectorModel::getImplementationName_static( ) throw(RuntimeException) { return ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "org.openoffice.comp.extensions.ObjectInspectorModel" ) ); } //-------------------------------------------------------------------- Sequence< ::rtl::OUString > ObjectInspectorModel::getSupportedServiceNames_static( ) throw(RuntimeException) { ::rtl::OUString sService( RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.inspection.ObjectInspectorModel" ) ); return Sequence< ::rtl::OUString >( &sService, 1 ); } //-------------------------------------------------------------------- Reference< XInterface > SAL_CALL ObjectInspectorModel::Create(const Reference< XComponentContext >& _rxContext ) { return *( new ObjectInspectorModel( _rxContext ) ); } //-------------------------------------------------------------------- void ObjectInspectorModel::createDefault() { m_aFactories.realloc( 1 ); m_aFactories[0] <<= ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.inspection.GenericPropertyHandler" ) ); } //-------------------------------------------------------------------- void ObjectInspectorModel::createWithHandlerFactories( const Sequence< Any >& _rFactories ) { impl_verifyArgument_throw( _rFactories.getLength() > 0, 1 ); m_aFactories = _rFactories; } //-------------------------------------------------------------------- void ObjectInspectorModel::createWithHandlerFactoriesAndHelpSection( const Sequence< Any >& _rFactories, sal_Int32 _nMinHelpTextLines, sal_Int32 _nMaxHelpTextLines ) { impl_verifyArgument_throw( _rFactories.getLength() > 0, 1 ); impl_verifyArgument_throw( _nMinHelpTextLines >= 1, 2 ); impl_verifyArgument_throw( _nMaxHelpTextLines >= 1, 3 ); impl_verifyArgument_throw( _nMinHelpTextLines <= _nMaxHelpTextLines, 2 ); m_aFactories = _rFactories; enableHelpSectionProperties( _nMinHelpTextLines, _nMaxHelpTextLines ); } //-------------------------------------------------------------------- void ObjectInspectorModel::impl_verifyArgument_throw( bool _bCondition, sal_Int16 _nArgumentPosition ) { if ( !_bCondition ) throw IllegalArgumentException( ::rtl::OUString(), *this, _nArgumentPosition ); } //........................................................................ } // namespace pcr //........................................................................ //------------------------------------------------------------------------ extern "C" void SAL_CALL createRegistryInfo_ObjectInspectorModel() { ::pcr::OAutoRegistration< ::pcr::ObjectInspectorModel > aObjectInspectorModelRegistration; } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: updatecheckconfig.hxx,v $ * * $Revision: 1.5 $ * * last change: $Author: hr $ $Date: 2007-07-31 15:57:22 $ * * 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 _CPPUHELPER_IMPLBASE3_HXX_ #include <cppuhelper/implbase3.hxx> #endif #ifndef _COM_SUN_STAR_BEANS_NAMEDVALUE_HPP_ #include <com/sun/star/beans/NamedValue.hpp> #endif #ifndef _COM_SUN_STAR_CONTAINER_XNAMECONTAINER_HPP_ #include <com/sun/star/container/XNameContainer.hpp> #endif #ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_ #include <com/sun/star/lang/XServiceInfo.hpp> #endif #ifndef _COM_SUN_STAR_UNO_XCOMPONENTCONTEXT_HPP_ #include <com/sun/star/uno/XComponentContext.hpp> #endif #ifndef _COM_SUN_STAR_UTIL_XCHANGESBATCH_HPP_ #include <com/sun/star/util/XChangesBatch.hpp> #endif #ifndef _RTL_REF_HXX_ #include <rtl/ref.hxx> #endif #include "updatecheckconfiglistener.hxx" #include "updateinfo.hxx" /* Interface to acess configuration data read-only */ struct IByNameAccess { virtual ::com::sun::star::uno::Any getValue(const sal_Char * pName) = 0; }; /* This helper class provides by name access to a sequence of named values */ class NamedValueByNameAccess : public IByNameAccess { const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::NamedValue >& m_rValues; public: NamedValueByNameAccess( const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::NamedValue >& rValues) : m_rValues(rValues) {} ; virtual ~NamedValueByNameAccess(); virtual ::com::sun::star::uno::Any getValue(const sal_Char * pName); }; /* This class encapsulates the configuration item actually used for storing the state * the update check is actually in. */ class UpdateCheckROModel { public: UpdateCheckROModel(IByNameAccess& aNameAccess) : m_aNameAccess(aNameAccess) {}; bool isAutoCheckEnabled() const; bool isAutoDownloadEnabled() const; bool isDownloadPaused() const; rtl::OUString getLocalFileName() const; sal_Int64 getDownloadSize() const; rtl::OUString getUpdateEntryVersion() const; void getUpdateEntry(UpdateInfo& rInfo) const; private: rtl::OUString getStringValue(const sal_Char *) const; IByNameAccess& m_aNameAccess; }; /* This class implements the non published UNO service com.sun.star.setup.UpdateCheckConfig, * which primary use is to be able to track changes done in the Toos -> Options page of this * component, as this is not supported by the OOo configuration for extendable groups. */ class UpdateCheckConfig : public ::cppu::WeakImplHelper3< ::com::sun::star::container::XNameReplace, ::com::sun::star::util::XChangesBatch, ::com::sun::star::lang::XServiceInfo > { UpdateCheckConfig(const ::com::sun::star::uno::Reference< ::com::sun::star::container::XNameContainer >& xContainer, const ::rtl::Reference< UpdateCheckConfigListener >& rListener ); virtual ~UpdateCheckConfig(); public: static ::com::sun::star::uno::Sequence< rtl::OUString > getServiceNames(); static rtl::OUString getImplName(); static ::rtl::Reference< UpdateCheckConfig > get( const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XComponentContext >& xContext, const ::rtl::Reference< UpdateCheckConfigListener >& rListener = ::rtl::Reference< UpdateCheckConfigListener >()); // Should really implement ROModel .. bool isAutoCheckEnabled() const; bool isAutoDownloadEnabled() const; rtl::OUString getUpdateEntryVersion() const; /* Updates the timestamp of last check, but does not commit the change * as either clearUpdateFound() or setUpdateFound() are expected to get * called next. */ void updateLastChecked(); /* Returns the date of the last successful check in seconds since 1970 */ sal_Int64 getLastChecked() const; /* Returns configured check interval in seconds */ sal_Int64 getCheckInterval() const; /* Reset values of previously remembered update */ void clearUpdateFound(); /* Stores the specified data of an available update */ void storeUpdateFound(const UpdateInfo& rInfo, const rtl::OUString& aCurrentBuild); // Returns the local file name of a started download rtl::OUString getLocalFileName() const; // Returns the local file name of a started download rtl::OUString getDownloadDestination() const; // stores the local file name of a just started download void storeLocalFileName(const rtl::OUString& rFileName, sal_Int64 nFileSize); // Removes the local file name of a download void clearLocalFileName(); // Stores the bool value for manually paused downloads void storeDownloadPaused(bool paused); // Returns the directory that acts as the user's desktop static rtl::OUString getDesktopDirectory(); // Returns a directory accessible for all users static rtl::OUString getAllUsersDirectory(); // XElementAccess virtual ::com::sun::star::uno::Type SAL_CALL getElementType( ) throw (::com::sun::star::uno::RuntimeException); virtual sal_Bool SAL_CALL hasElements( ) throw (::com::sun::star::uno::RuntimeException); // XNameAccess virtual ::com::sun::star::uno::Any SAL_CALL getByName( const ::rtl::OUString& aName ) throw (::com::sun::star::container::NoSuchElementException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getElementNames( ) throw (::com::sun::star::uno::RuntimeException); virtual ::sal_Bool SAL_CALL hasByName( const ::rtl::OUString& aName ) throw (::com::sun::star::uno::RuntimeException); // XNameReplace virtual void SAL_CALL replaceByName( const ::rtl::OUString& aName, const ::com::sun::star::uno::Any& aElement ) throw (::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::container::NoSuchElementException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException); // XChangesBatch virtual void SAL_CALL commitChanges( ) throw (::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException); virtual ::sal_Bool SAL_CALL hasPendingChanges( ) throw (::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::uno::Sequence< ::com::sun::star::util::ElementChange > SAL_CALL getPendingChanges( ) throw (::com::sun::star::uno::RuntimeException); // XServiceInfo virtual rtl::OUString SAL_CALL getImplementationName() throw (::com::sun::star::uno::RuntimeException); virtual sal_Bool SAL_CALL supportsService(rtl::OUString const & serviceName) throw (::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::uno::Sequence< rtl::OUString > SAL_CALL getSupportedServiceNames() throw (::com::sun::star::uno::RuntimeException); private: const ::com::sun::star::uno::Reference< ::com::sun::star::container::XNameContainer > m_xContainer; const ::rtl::Reference< UpdateCheckConfigListener > m_rListener; }; //------------------------------------------------------------------------------ template <typename T> T getValue( const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::NamedValue >& rNamedValues, const sal_Char * pszName ) throw (::com::sun::star::uno::RuntimeException) { for( sal_Int32 n=0; n < rNamedValues.getLength(); n++ ) { // Unfortunatly gcc-3.3 does not like Any.get<T>(); if( rNamedValues[n].Name.equalsAscii( pszName ) ) { T value; if( ! (rNamedValues[n].Value >>= value) ) throw ::com::sun::star::uno::RuntimeException( ::rtl::OUString( cppu_Any_extraction_failure_msg( &rNamedValues[n].Value, ::cppu::getTypeFavourUnsigned(&value).getTypeLibType() ), SAL_NO_ACQUIRE ), ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >() ); return value; } } return T(); } <commit_msg>INTEGRATION: CWS updchk10 (1.5.2); FILE MERGED 2007/10/23 10:54:05 dv 1.5.2.1: #i82851# Support automatic checking for extension updates<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: updatecheckconfig.hxx,v $ * * $Revision: 1.6 $ * * last change: $Author: ihi $ $Date: 2007-11-19 16:48:41 $ * * 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 _CPPUHELPER_IMPLBASE3_HXX_ #include <cppuhelper/implbase3.hxx> #endif #ifndef _COM_SUN_STAR_BEANS_NAMEDVALUE_HPP_ #include <com/sun/star/beans/NamedValue.hpp> #endif #ifndef _COM_SUN_STAR_CONTAINER_XNAMECONTAINER_HPP_ #include <com/sun/star/container/XNameContainer.hpp> #endif #ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_ #include <com/sun/star/lang/XServiceInfo.hpp> #endif #ifndef _COM_SUN_STAR_UNO_XCOMPONENTCONTEXT_HPP_ #include <com/sun/star/uno/XComponentContext.hpp> #endif #ifndef _COM_SUN_STAR_UTIL_XCHANGESBATCH_HPP_ #include <com/sun/star/util/XChangesBatch.hpp> #endif #ifndef _RTL_REF_HXX_ #include <rtl/ref.hxx> #endif #include "updatecheckconfiglistener.hxx" #include "updateinfo.hxx" /* Interface to acess configuration data read-only */ struct IByNameAccess { virtual ::com::sun::star::uno::Any getValue(const sal_Char * pName) = 0; }; /* This helper class provides by name access to a sequence of named values */ class NamedValueByNameAccess : public IByNameAccess { const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::NamedValue >& m_rValues; public: NamedValueByNameAccess( const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::NamedValue >& rValues) : m_rValues(rValues) {} ; virtual ~NamedValueByNameAccess(); virtual ::com::sun::star::uno::Any getValue(const sal_Char * pName); }; /* This class encapsulates the configuration item actually used for storing the state * the update check is actually in. */ class UpdateCheckROModel { public: UpdateCheckROModel(IByNameAccess& aNameAccess) : m_aNameAccess(aNameAccess) {}; bool isAutoCheckEnabled() const; bool isAutoDownloadEnabled() const; bool isDownloadPaused() const; rtl::OUString getLocalFileName() const; sal_Int64 getDownloadSize() const; rtl::OUString getUpdateEntryVersion() const; void getUpdateEntry(UpdateInfo& rInfo) const; private: rtl::OUString getStringValue(const sal_Char *) const; IByNameAccess& m_aNameAccess; }; /* This class implements the non published UNO service com.sun.star.setup.UpdateCheckConfig, * which primary use is to be able to track changes done in the Toos -> Options page of this * component, as this is not supported by the OOo configuration for extendable groups. */ class UpdateCheckConfig : public ::cppu::WeakImplHelper3< ::com::sun::star::container::XNameReplace, ::com::sun::star::util::XChangesBatch, ::com::sun::star::lang::XServiceInfo > { UpdateCheckConfig(const ::com::sun::star::uno::Reference< ::com::sun::star::container::XNameContainer >& xContainer, const ::rtl::Reference< UpdateCheckConfigListener >& rListener ); virtual ~UpdateCheckConfig(); public: static ::com::sun::star::uno::Sequence< rtl::OUString > getServiceNames(); static rtl::OUString getImplName(); static ::rtl::Reference< UpdateCheckConfig > get( const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XComponentContext >& xContext, const ::rtl::Reference< UpdateCheckConfigListener >& rListener = ::rtl::Reference< UpdateCheckConfigListener >()); // Should really implement ROModel .. bool isAutoCheckEnabled() const; bool isAutoDownloadEnabled() const; rtl::OUString getUpdateEntryVersion() const; /* Updates the timestamp of last check, but does not commit the change * as either clearUpdateFound() or setUpdateFound() are expected to get * called next. */ void updateLastChecked(); /* Returns the date of the last successful check in seconds since 1970 */ sal_Int64 getLastChecked() const; /* Returns configured check interval in seconds */ sal_Int64 getCheckInterval() const; /* Reset values of previously remembered update */ void clearUpdateFound(); /* Stores the specified data of an available update */ void storeUpdateFound(const UpdateInfo& rInfo, const rtl::OUString& aCurrentBuild); // Returns the local file name of a started download rtl::OUString getLocalFileName() const; // Returns the local file name of a started download rtl::OUString getDownloadDestination() const; // stores the local file name of a just started download void storeLocalFileName(const rtl::OUString& rFileName, sal_Int64 nFileSize); // Removes the local file name of a download void clearLocalFileName(); // Stores the bool value for manually paused downloads void storeDownloadPaused(bool paused); // Returns the directory that acts as the user's desktop static rtl::OUString getDesktopDirectory(); // Returns a directory accessible for all users static rtl::OUString getAllUsersDirectory(); // store and retrieve information about extensions void storeExtensionVersion( const rtl::OUString& rExtensionName, const rtl::OUString& rVersion ); bool checkExtensionVersion( const rtl::OUString& rExtensionName, const rtl::OUString& rVersion ); // XElementAccess virtual ::com::sun::star::uno::Type SAL_CALL getElementType( ) throw (::com::sun::star::uno::RuntimeException); virtual sal_Bool SAL_CALL hasElements( ) throw (::com::sun::star::uno::RuntimeException); // XNameAccess virtual ::com::sun::star::uno::Any SAL_CALL getByName( const ::rtl::OUString& aName ) throw (::com::sun::star::container::NoSuchElementException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getElementNames( ) throw (::com::sun::star::uno::RuntimeException); virtual ::sal_Bool SAL_CALL hasByName( const ::rtl::OUString& aName ) throw (::com::sun::star::uno::RuntimeException); // XNameReplace virtual void SAL_CALL replaceByName( const ::rtl::OUString& aName, const ::com::sun::star::uno::Any& aElement ) throw (::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::container::NoSuchElementException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException); // XChangesBatch virtual void SAL_CALL commitChanges( ) throw (::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException); virtual ::sal_Bool SAL_CALL hasPendingChanges( ) throw (::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::uno::Sequence< ::com::sun::star::util::ElementChange > SAL_CALL getPendingChanges( ) throw (::com::sun::star::uno::RuntimeException); // XServiceInfo virtual rtl::OUString SAL_CALL getImplementationName() throw (::com::sun::star::uno::RuntimeException); virtual sal_Bool SAL_CALL supportsService(rtl::OUString const & serviceName) throw (::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::uno::Sequence< rtl::OUString > SAL_CALL getSupportedServiceNames() throw (::com::sun::star::uno::RuntimeException); private: static rtl::OUString getSubVersion( const rtl::OUString& rVersion, sal_Int32 *nIndex ); static bool isVersionGreater( const rtl::OUString& rVersion1, const rtl::OUString& rVersion2 ); const ::com::sun::star::uno::Reference< ::com::sun::star::container::XNameContainer > m_xContainer; const ::rtl::Reference< UpdateCheckConfigListener > m_rListener; }; //------------------------------------------------------------------------------ template <typename T> T getValue( const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::NamedValue >& rNamedValues, const sal_Char * pszName ) throw (::com::sun::star::uno::RuntimeException) { for( sal_Int32 n=0; n < rNamedValues.getLength(); n++ ) { // Unfortunatly gcc-3.3 does not like Any.get<T>(); if( rNamedValues[n].Name.equalsAscii( pszName ) ) { T value; if( ! (rNamedValues[n].Value >>= value) ) throw ::com::sun::star::uno::RuntimeException( ::rtl::OUString( cppu_Any_extraction_failure_msg( &rNamedValues[n].Value, ::cppu::getTypeFavourUnsigned(&value).getTypeLibType() ), SAL_NO_ACQUIRE ), ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >() ); return value; } } return T(); } <|endoftext|>
<commit_before>#include <boost/test/unit_test.hpp> #include "SoftXMT.hpp" #include "GlobalTaskJoiner.hpp" #include "ForkJoin.hpp" #include "AsyncParallelFor.hpp" #include "Delegate.hpp" #include "PerformanceTools.hpp" BOOST_AUTO_TEST_SUITE( AsyncParallelFor_Global_tests ); #define MAX_NODES 8 #define SIZE 10000 int64_t done[SIZE*MAX_NODES] = {0}; int64_t count2 = 0; int64_t global_count = 0; int64_t local_count = 0; void loop_body(int64_t start, int64_t num ) { /*BOOST_MESSAGE( "execute [" << start << "," << start+num << ") with thread " << CURRENT_THREAD->id );*/ BOOST_CHECK( num <= FLAGS_async_par_for_threshold ); for (int i=start; i<start+num; i++) { int64_t marked = SoftXMT_delegate_fetch_and_add_word( make_global( &done[i], 0 ), 1 ); BOOST_CHECK( marked == 0 ); SoftXMT_delegate_fetch_and_add_word( make_global( &global_count, 0 ), 1 ); local_count++; } } struct parallel_func : public ForkJoinIteration { void operator()(int64_t nid) const { int64_t start = nid * SIZE; int64_t iters = SIZE; global_joiner.reset(); async_parallel_for<&loop_body, &joinerSpawn<&loop_body> > ( start, iters ); global_joiner.wait(); } }; // don't care what type goes into the GlobalAddress typedef int64_t dummy_t; void loop_body2(int64_t start, int64_t num, GlobalAddress<dummy_t> shared_arg_packed) { /*BOOST_MESSAGE( "execute [" << start << "," << start+num << ") with thread " << CURRENT_THREAD->id );*/ BOOST_CHECK( num <= FLAGS_async_par_for_threshold ); int64_t origin = reinterpret_cast<int64_t>(shared_arg_packed.pointer()); for (int i=start; i<start+num; i++) { SoftXMT_delegate_fetch_and_add_word( make_global( &count2, origin ), 1 ); SoftXMT_delegate_fetch_and_add_word( make_global( &global_count, 0 ), 1 ); local_count++; } } LOOP_FUNCTION(check_count2, nid) { BOOST_CHECK( count2 == SIZE ); } struct parallel_func2 : public ForkJoinIteration { void operator()(int64_t nid) const { local_count = 0; int64_t start = nid * SIZE; int64_t iters = SIZE; // pack an argument into the global address (hack). // This is useful if we need just the node() from the global address and want to use the other // bits for something else. int64_t shared_arg = SoftXMT_mynode(); GlobalAddress<dummy_t> shared_arg_packed = make_global( reinterpret_cast<dummy_t*>(shared_arg) ); global_joiner.reset(); async_parallel_for<dummy_t,&loop_body2, &joinerSpawn_hack<dummy_t,&loop_body2> >(start,iters,shared_arg_packed); global_joiner.wait(); } }; LOOP_FUNCTION(func_enable_google_profiler, nid) { SoftXMT_start_profiling(); } void profile_start() { #ifdef GOOGLE_PROFILER func_enable_google_profiler g; fork_join_custom(&g); #endif } LOOP_FUNCTION(func_disable_google_profiler, nid) { SoftXMT_stop_profiling(); } void profile_stop() { #ifdef GOOGLE_PROFILER func_disable_google_profiler g; fork_join_custom(&g); #endif } void user_main( void * args ) { BOOST_CHECK( SoftXMT_nodes() <= MAX_NODES ); int64_t total_iters = SoftXMT_nodes() * SIZE; BOOST_MESSAGE( total_iters << " iterations over " << SoftXMT_nodes() << " nodes" ); BOOST_MESSAGE( "Test default" ); { parallel_func f; SoftXMT_reset_stats_all_nodes(); profile_start(); fork_join_custom(&f); profile_stop(); for (int i=0; i<total_iters; i++) { BOOST_CHECK( done[i] == 1 ); } BOOST_CHECK( global_count == total_iters ); // print out individual participations for (Node n=0; n<SoftXMT_nodes(); n++) { int64_t n_count = SoftXMT_delegate_read_word( make_global( &local_count, n ) ); BOOST_MESSAGE( n << " did " << n_count << " iterations" ); } } BOOST_MESSAGE( "Test with shared arg" ); { // with shared arg global_count = 0; parallel_func2 f; profile_start(); fork_join_custom(&f); profile_stop(); // check all iterations happened BOOST_CHECK( global_count == total_iters ); // check all shared args used properly check_count2 ff; fork_join_custom(&ff); // print out individual participations for (Node n=0; n<SoftXMT_nodes(); n++) { int64_t n_count = SoftXMT_delegate_read_word( make_global( &local_count, n ) ); BOOST_MESSAGE( n << " did " << n_count << " iterations" ); } } BOOST_MESSAGE( "user main is exiting" ); SoftXMT_dump_stats_all_nodes(); } BOOST_AUTO_TEST_CASE( test1 ) { SoftXMT_init( &(boost::unit_test::framework::master_test_suite().argc), &(boost::unit_test::framework::master_test_suite().argv) ); SoftXMT_activate(); DVLOG(1) << "Spawning user main Thread...."; SoftXMT_run_user_main( &user_main, (void*)NULL ); VLOG(5) << "run_user_main returned"; CHECK( SoftXMT_done() ); SoftXMT_finish( 0 ); } BOOST_AUTO_TEST_SUITE_END(); <commit_msg>Remove unneccessary '&'s before template params in AsyncParallelFor test.<commit_after>#include <boost/test/unit_test.hpp> #include "SoftXMT.hpp" #include "GlobalTaskJoiner.hpp" #include "ForkJoin.hpp" #include "AsyncParallelFor.hpp" #include "Delegate.hpp" #include "PerformanceTools.hpp" BOOST_AUTO_TEST_SUITE( AsyncParallelFor_Global_tests ); #define MAX_NODES 8 #define SIZE 10000 int64_t done[SIZE*MAX_NODES] = {0}; int64_t count2 = 0; int64_t global_count = 0; int64_t local_count = 0; void loop_body(int64_t start, int64_t num ) { /*BOOST_MESSAGE( "execute [" << start << "," << start+num << ") with thread " << CURRENT_THREAD->id );*/ BOOST_CHECK( num <= FLAGS_async_par_for_threshold ); for (int i=start; i<start+num; i++) { int64_t marked = SoftXMT_delegate_fetch_and_add_word( make_global( &done[i], 0 ), 1 ); BOOST_CHECK( marked == 0 ); SoftXMT_delegate_fetch_and_add_word( make_global( &global_count, 0 ), 1 ); local_count++; } } struct parallel_func : public ForkJoinIteration { void operator()(int64_t nid) const { int64_t start = nid * SIZE; int64_t iters = SIZE; global_joiner.reset(); async_parallel_for<loop_body, joinerSpawn<loop_body> > ( start, iters ); global_joiner.wait(); } }; // don't care what type goes into the GlobalAddress typedef int64_t dummy_t; void loop_body2(int64_t start, int64_t num, GlobalAddress<dummy_t> shared_arg_packed) { /*BOOST_MESSAGE( "execute [" << start << "," << start+num << ") with thread " << CURRENT_THREAD->id );*/ BOOST_CHECK( num <= FLAGS_async_par_for_threshold ); int64_t origin = reinterpret_cast<int64_t>(shared_arg_packed.pointer()); for (int i=start; i<start+num; i++) { SoftXMT_delegate_fetch_and_add_word( make_global( &count2, origin ), 1 ); SoftXMT_delegate_fetch_and_add_word( make_global( &global_count, 0 ), 1 ); local_count++; } } LOOP_FUNCTION(check_count2, nid) { BOOST_CHECK( count2 == SIZE ); } struct parallel_func2 : public ForkJoinIteration { void operator()(int64_t nid) const { local_count = 0; int64_t start = nid * SIZE; int64_t iters = SIZE; // pack an argument into the global address (hack). // This is useful if we need just the node() from the global address and want to use the other // bits for something else. int64_t shared_arg = SoftXMT_mynode(); GlobalAddress<dummy_t> shared_arg_packed = make_global( reinterpret_cast<dummy_t*>(shared_arg) ); global_joiner.reset(); async_parallel_for<dummy_t,loop_body2,joinerSpawn_hack<dummy_t,loop_body2> >(start,iters,shared_arg_packed); global_joiner.wait(); } }; LOOP_FUNCTION(func_enable_google_profiler, nid) { SoftXMT_start_profiling(); } void profile_start() { #ifdef GOOGLE_PROFILER func_enable_google_profiler g; fork_join_custom(&g); #endif } LOOP_FUNCTION(func_disable_google_profiler, nid) { SoftXMT_stop_profiling(); } void profile_stop() { #ifdef GOOGLE_PROFILER func_disable_google_profiler g; fork_join_custom(&g); #endif } void user_main( void * args ) { BOOST_CHECK( SoftXMT_nodes() <= MAX_NODES ); int64_t total_iters = SoftXMT_nodes() * SIZE; BOOST_MESSAGE( total_iters << " iterations over " << SoftXMT_nodes() << " nodes" ); BOOST_MESSAGE( "Test default" ); { parallel_func f; SoftXMT_reset_stats_all_nodes(); profile_start(); fork_join_custom(&f); profile_stop(); for (int i=0; i<total_iters; i++) { BOOST_CHECK( done[i] == 1 ); } BOOST_CHECK( global_count == total_iters ); // print out individual participations for (Node n=0; n<SoftXMT_nodes(); n++) { int64_t n_count = SoftXMT_delegate_read_word( make_global( &local_count, n ) ); BOOST_MESSAGE( n << " did " << n_count << " iterations" ); } } BOOST_MESSAGE( "Test with shared arg" ); { // with shared arg global_count = 0; parallel_func2 f; profile_start(); fork_join_custom(&f); profile_stop(); // check all iterations happened BOOST_CHECK( global_count == total_iters ); // check all shared args used properly check_count2 ff; fork_join_custom(&ff); // print out individual participations for (Node n=0; n<SoftXMT_nodes(); n++) { int64_t n_count = SoftXMT_delegate_read_word( make_global( &local_count, n ) ); BOOST_MESSAGE( n << " did " << n_count << " iterations" ); } } BOOST_MESSAGE( "user main is exiting" ); SoftXMT_dump_stats_all_nodes(); } BOOST_AUTO_TEST_CASE( test1 ) { SoftXMT_init( &(boost::unit_test::framework::master_test_suite().argc), &(boost::unit_test::framework::master_test_suite().argv) ); SoftXMT_activate(); DVLOG(1) << "Spawning user main Thread...."; SoftXMT_run_user_main( &user_main, (void*)NULL ); VLOG(5) << "run_user_main returned"; CHECK( SoftXMT_done() ); SoftXMT_finish( 0 ); } BOOST_AUTO_TEST_SUITE_END(); <|endoftext|>
<commit_before>//===-- SystemZRegisterInfo.cpp - SystemZ register information ------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "SystemZInstrInfo.h" #include "SystemZRegisterInfo.h" #include "SystemZSubtarget.h" #include "llvm/CodeGen/MachineInstrBuilder.h" #include "llvm/CodeGen/MachineRegisterInfo.h" #include "llvm/Target/TargetFrameLowering.h" using namespace llvm; #define GET_REGINFO_TARGET_DESC #include "SystemZGenRegisterInfo.inc" SystemZRegisterInfo::SystemZRegisterInfo() : SystemZGenRegisterInfo(SystemZ::R14D) {} const MCPhysReg * SystemZRegisterInfo::getCalleeSavedRegs(const MachineFunction *MF) const { return CSR_SystemZ_SaveList; } const uint32_t * SystemZRegisterInfo::getCallPreservedMask(const MachineFunction &MF, CallingConv::ID CC) const { return CSR_SystemZ_RegMask; } BitVector SystemZRegisterInfo::getReservedRegs(const MachineFunction &MF) const { BitVector Reserved(getNumRegs()); const SystemZFrameLowering *TFI = getFrameLowering(MF); if (TFI->hasFP(MF)) { // R11D is the frame pointer. Reserve all aliases. Reserved.set(SystemZ::R11D); Reserved.set(SystemZ::R11L); Reserved.set(SystemZ::R11H); Reserved.set(SystemZ::R10Q); } // R15D is the stack pointer. Reserve all aliases. Reserved.set(SystemZ::R15D); Reserved.set(SystemZ::R15L); Reserved.set(SystemZ::R15H); Reserved.set(SystemZ::R14Q); return Reserved; } void SystemZRegisterInfo::eliminateFrameIndex(MachineBasicBlock::iterator MI, int SPAdj, unsigned FIOperandNum, RegScavenger *RS) const { assert(SPAdj == 0 && "Outgoing arguments should be part of the frame"); MachineBasicBlock &MBB = *MI->getParent(); MachineFunction &MF = *MBB.getParent(); auto *TII = static_cast<const SystemZInstrInfo *>(MF.getSubtarget().getInstrInfo()); const SystemZFrameLowering *TFI = getFrameLowering(MF); DebugLoc DL = MI->getDebugLoc(); // Decompose the frame index into a base and offset. int FrameIndex = MI->getOperand(FIOperandNum).getIndex(); unsigned BasePtr; int64_t Offset = (TFI->getFrameIndexReference(MF, FrameIndex, BasePtr) + MI->getOperand(FIOperandNum + 1).getImm()); // Special handling of dbg_value instructions. if (MI->isDebugValue()) { MI->getOperand(FIOperandNum).ChangeToRegister(BasePtr, /*isDef*/ false); MI->getOperand(FIOperandNum + 1).ChangeToImmediate(Offset); return; } // See if the offset is in range, or if an equivalent instruction that // accepts the offset exists. unsigned Opcode = MI->getOpcode(); unsigned OpcodeForOffset = TII->getOpcodeForOffset(Opcode, Offset); if (OpcodeForOffset) MI->getOperand(FIOperandNum).ChangeToRegister(BasePtr, false); else { // Create an anchor point that is in range. Start at 0xffff so that // can use LLILH to load the immediate. int64_t OldOffset = Offset; int64_t Mask = 0xffff; do { Offset = OldOffset & Mask; OpcodeForOffset = TII->getOpcodeForOffset(Opcode, Offset); Mask >>= 1; assert(Mask && "One offset must be OK"); } while (!OpcodeForOffset); unsigned ScratchReg = MF.getRegInfo().createVirtualRegister(&SystemZ::ADDR64BitRegClass); int64_t HighOffset = OldOffset - Offset; if (MI->getDesc().TSFlags & SystemZII::HasIndex && MI->getOperand(FIOperandNum + 2).getReg() == 0) { // Load the offset into the scratch register and use it as an index. // The scratch register then dies here. TII->loadImmediate(MBB, MI, ScratchReg, HighOffset); MI->getOperand(FIOperandNum).ChangeToRegister(BasePtr, false); MI->getOperand(FIOperandNum + 2).ChangeToRegister(ScratchReg, false, false, true); } else { // Load the anchor address into a scratch register. unsigned LAOpcode = TII->getOpcodeForOffset(SystemZ::LA, HighOffset); if (LAOpcode) BuildMI(MBB, MI, DL, TII->get(LAOpcode),ScratchReg) .addReg(BasePtr).addImm(HighOffset).addReg(0); else { // Load the high offset into the scratch register and use it as // an index. TII->loadImmediate(MBB, MI, ScratchReg, HighOffset); BuildMI(MBB, MI, DL, TII->get(SystemZ::AGR),ScratchReg) .addReg(ScratchReg, RegState::Kill).addReg(BasePtr); } // Use the scratch register as the base. It then dies here. MI->getOperand(FIOperandNum).ChangeToRegister(ScratchReg, false, false, true); } } MI->setDesc(TII->get(OpcodeForOffset)); MI->getOperand(FIOperandNum + 1).ChangeToImmediate(Offset); } unsigned SystemZRegisterInfo::getFrameRegister(const MachineFunction &MF) const { const SystemZFrameLowering *TFI = getFrameLowering(MF); return TFI->hasFP(MF) ? SystemZ::R11D : SystemZ::R15D; } <commit_msg>[SystemZ] Use LDE32 instead of LE, when Offset is small.<commit_after>//===-- SystemZRegisterInfo.cpp - SystemZ register information ------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "SystemZInstrInfo.h" #include "SystemZRegisterInfo.h" #include "SystemZSubtarget.h" #include "llvm/CodeGen/MachineInstrBuilder.h" #include "llvm/CodeGen/MachineRegisterInfo.h" #include "llvm/Target/TargetFrameLowering.h" using namespace llvm; #define GET_REGINFO_TARGET_DESC #include "SystemZGenRegisterInfo.inc" SystemZRegisterInfo::SystemZRegisterInfo() : SystemZGenRegisterInfo(SystemZ::R14D) {} const MCPhysReg * SystemZRegisterInfo::getCalleeSavedRegs(const MachineFunction *MF) const { return CSR_SystemZ_SaveList; } const uint32_t * SystemZRegisterInfo::getCallPreservedMask(const MachineFunction &MF, CallingConv::ID CC) const { return CSR_SystemZ_RegMask; } BitVector SystemZRegisterInfo::getReservedRegs(const MachineFunction &MF) const { BitVector Reserved(getNumRegs()); const SystemZFrameLowering *TFI = getFrameLowering(MF); if (TFI->hasFP(MF)) { // R11D is the frame pointer. Reserve all aliases. Reserved.set(SystemZ::R11D); Reserved.set(SystemZ::R11L); Reserved.set(SystemZ::R11H); Reserved.set(SystemZ::R10Q); } // R15D is the stack pointer. Reserve all aliases. Reserved.set(SystemZ::R15D); Reserved.set(SystemZ::R15L); Reserved.set(SystemZ::R15H); Reserved.set(SystemZ::R14Q); return Reserved; } void SystemZRegisterInfo::eliminateFrameIndex(MachineBasicBlock::iterator MI, int SPAdj, unsigned FIOperandNum, RegScavenger *RS) const { assert(SPAdj == 0 && "Outgoing arguments should be part of the frame"); MachineBasicBlock &MBB = *MI->getParent(); MachineFunction &MF = *MBB.getParent(); auto *TII = static_cast<const SystemZInstrInfo *>(MF.getSubtarget().getInstrInfo()); const SystemZFrameLowering *TFI = getFrameLowering(MF); DebugLoc DL = MI->getDebugLoc(); // Decompose the frame index into a base and offset. int FrameIndex = MI->getOperand(FIOperandNum).getIndex(); unsigned BasePtr; int64_t Offset = (TFI->getFrameIndexReference(MF, FrameIndex, BasePtr) + MI->getOperand(FIOperandNum + 1).getImm()); // Special handling of dbg_value instructions. if (MI->isDebugValue()) { MI->getOperand(FIOperandNum).ChangeToRegister(BasePtr, /*isDef*/ false); MI->getOperand(FIOperandNum + 1).ChangeToImmediate(Offset); return; } // See if the offset is in range, or if an equivalent instruction that // accepts the offset exists. unsigned Opcode = MI->getOpcode(); unsigned OpcodeForOffset = TII->getOpcodeForOffset(Opcode, Offset); if (OpcodeForOffset) { if (OpcodeForOffset == SystemZ::LE && MF.getSubtarget<SystemZSubtarget>().hasVector()) { // If LE is ok for offset, use LDE instead on z13. OpcodeForOffset = SystemZ::LDE32; } MI->getOperand(FIOperandNum).ChangeToRegister(BasePtr, false); } else { // Create an anchor point that is in range. Start at 0xffff so that // can use LLILH to load the immediate. int64_t OldOffset = Offset; int64_t Mask = 0xffff; do { Offset = OldOffset & Mask; OpcodeForOffset = TII->getOpcodeForOffset(Opcode, Offset); Mask >>= 1; assert(Mask && "One offset must be OK"); } while (!OpcodeForOffset); unsigned ScratchReg = MF.getRegInfo().createVirtualRegister(&SystemZ::ADDR64BitRegClass); int64_t HighOffset = OldOffset - Offset; if (MI->getDesc().TSFlags & SystemZII::HasIndex && MI->getOperand(FIOperandNum + 2).getReg() == 0) { // Load the offset into the scratch register and use it as an index. // The scratch register then dies here. TII->loadImmediate(MBB, MI, ScratchReg, HighOffset); MI->getOperand(FIOperandNum).ChangeToRegister(BasePtr, false); MI->getOperand(FIOperandNum + 2).ChangeToRegister(ScratchReg, false, false, true); } else { // Load the anchor address into a scratch register. unsigned LAOpcode = TII->getOpcodeForOffset(SystemZ::LA, HighOffset); if (LAOpcode) BuildMI(MBB, MI, DL, TII->get(LAOpcode),ScratchReg) .addReg(BasePtr).addImm(HighOffset).addReg(0); else { // Load the high offset into the scratch register and use it as // an index. TII->loadImmediate(MBB, MI, ScratchReg, HighOffset); BuildMI(MBB, MI, DL, TII->get(SystemZ::AGR),ScratchReg) .addReg(ScratchReg, RegState::Kill).addReg(BasePtr); } // Use the scratch register as the base. It then dies here. MI->getOperand(FIOperandNum).ChangeToRegister(ScratchReg, false, false, true); } } MI->setDesc(TII->get(OpcodeForOffset)); MI->getOperand(FIOperandNum + 1).ChangeToImmediate(Offset); } unsigned SystemZRegisterInfo::getFrameRegister(const MachineFunction &MF) const { const SystemZFrameLowering *TFI = getFrameLowering(MF); return TFI->hasFP(MF) ? SystemZ::R11D : SystemZ::R15D; } <|endoftext|>
<commit_before>/* * Copyright(C) 2014, ChenYang, Jupiter-org. * * _______ * /\ \ __ __ * \ /-\ \-/ /\ \ /\ \ * \ \ \ __ __ _____\/_/ _\_\ \__ ____ ____ * \ \ \/\ \ \ \/\ __/\/\`\/\___ __\/`__'\/\ __\ * \ \ \ \ \ \ \ \ \_\ \ \ \/___/\ \_/\ __/ \ \_/ * /_\ \ \ \ \ \--\ \ \ \_'/\ \_\ \ \_\\ \____\ \_\ * \__\_\/_/\/____/_/\ \ \ \/_/ \/_/ \/____/\/_/ * \ \_\ * \/_/ * @file: jupiter_sprite_manage.cpp * @author: ChenYang :) * @date: 2014/11/25 10:47 * @brief: Once you created lots of sprites, how to manage them? Aye, * you get it, use what this file provided for you. * Enjoy yourself! :-) */ #include "jupiter_sprite_manage.h" JupiterSpriteManage::JupiterSpriteManage() { } JupiterSpriteManage::~JupiterSpriteManage() { release(); } bool JupiterSpriteManage::addSprite(JupiterSprite * pSprite, int nZorder) { if (pSprite != NULL) { pSprite->setZOrder(nZorder); if (!jupiSprites.empty()) { vector<JupiterSprite *>::iterator curSprite; for (curSprite = jupiSprites.begin(); curSprite != jupiSprites.end(); curSprite++) if (nZorder < (*curSprite)->getZOrder()) { jupiSprites.insert(curSprite, pSprite); return true; } } jupiSprites.push_back(pSprite); return true; } return false; } void JupiterSpriteManage::release(bool bdelSprite) { if (!jupiSprites.empty()) { if(bdelSprite) { vector<JupiterSprite *>::iterator curSprite; for (curSprite = jupiSprites.begin(); curSprite != jupiSprites.end(); curSprite++) delete *curSprite; // delete sprite object } jupiSprites.clear(); // delete pointer of container vector<JupiterSprite *>(jupiSprites).swap(jupiSprites); // compress container } } void JupiterSpriteManage::delSprite(JupiterSprite* pSprite, bool bdelSprite, bool bCompress) { if (!jupiSprites.empty()) { vector<JupiterSprite*>::iterator curSprite; for (curSprite = jupiSprites.begin(); curSprite != jupiSprites.end(); curSprite++) if((*curSprite)->getID() == pSprite->getID()) { if(bdelSprite) delete pSprite; jupiSprites.erase(curSprite); break; } if(bCompress) vector<JupiterSprite *>(jupiSprites).swap(jupiSprites); } } bool JupiterSpriteManage::findSprite(JupiterSprite* pSprite) { if (!jupiSprites.empty()) { vector<JupiterSprite*>::iterator curSprite; for (curSprite = jupiSprites.begin(); curSprite != jupiSprites.end(); curSprite++) if((*curSprite)->getID() == pSprite->getID()) return true; } return false; } void JupiterSpriteManage::setSpriteVisible(JupiterSprite* pSprite, bool bVisible) { pSprite->setVisible(bVisible); } void JupiterSpriteManage::draw(HDC hDC) { if (!jupiSprites.empty()) { vector<JupiterSprite *>::iterator curSprite; for (curSprite = jupiSprites.begin(); curSprite != jupiSprites.end(); curSprite++) { (*curSprite)->drawSprite(hDC); } } } ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /*þZ˳*/ void JupiterSpriteManage::setZOrder(JupiterSprite * pSprite,int nZorder) { delSprite(pSprite); //ɾ addSprite(pSprite,nZorder); //Ӿ }<commit_msg>display error<commit_after>/* * Copyright(C) 2014, ChenYang, Jupiter-org. * * _______ * /\ \ __ __ * \ /-\ \-/ /\ \ /\ \ * \ \ \ __ __ _____\/_/ _\_\ \__ ____ ____ * \ \ \/\ \ \ \/\ __/\/\`\/\___ __\/`__'\/\ __\ * \ \ \ \ \ \ \ \ \_\ \ \ \/___/\ \_/\ __/ \ \_/ * /_\ \ \ \ \ \--\ \ \ \_'/\ \_\ \ \_\\ \____\ \_\ * \__\_\/_/\/____/_/\ \ \ \/_/ \/_/ \/____/\/_/ * \ \_\ * \/_/ * @file: jupiter_sprite_manage.cpp * @author: ChenYang :) * @date: 2014/11/25 10:47 * @brief: Once you created lots of sprites, how to manage them? Aye, * you get it, use what this file provided for you. * Enjoy yourself! :-) */ #include "jupiter_sprite_manage.h" JupiterSpriteManage::JupiterSpriteManage() { } JupiterSpriteManage::~JupiterSpriteManage() { release(); } bool JupiterSpriteManage::addSprite(JupiterSprite * pSprite, int nZorder) { if (pSprite != NULL) { pSprite->setZOrder(nZorder); if (!jupiSprites.empty()) { vector<JupiterSprite *>::iterator curSprite; for (curSprite = jupiSprites.begin(); curSprite != jupiSprites.end(); curSprite++) if (nZorder < (*curSprite)->getZOrder()) { jupiSprites.insert(curSprite, pSprite); return true; } } jupiSprites.push_back(pSprite); return true; } return false; } void JupiterSpriteManage::release(bool bdelSprite) { if (!jupiSprites.empty()) { if(bdelSprite) { vector<JupiterSprite *>::iterator curSprite; for (curSprite = jupiSprites.begin(); curSprite != jupiSprites.end(); curSprite++) delete *curSprite; // delete sprite object } jupiSprites.clear(); // delete pointer of container vector<JupiterSprite *>(jupiSprites).swap(jupiSprites); // compress container } } void JupiterSpriteManage::delSprite(JupiterSprite* pSprite, bool bdelSprite, bool bCompress) { if (!jupiSprites.empty()) { vector<JupiterSprite*>::iterator curSprite; for (curSprite = jupiSprites.begin(); curSprite != jupiSprites.end(); curSprite++) if((*curSprite)->getID() == pSprite->getID()) { if(bdelSprite) delete pSprite; jupiSprites.erase(curSprite); break; } if(bCompress) vector<JupiterSprite *>(jupiSprites).swap(jupiSprites); } } bool JupiterSpriteManage::findSprite(JupiterSprite* pSprite) { if (!jupiSprites.empty()) { vector<JupiterSprite*>::iterator curSprite; for (curSprite = jupiSprites.begin(); curSprite != jupiSprites.end(); curSprite++) if((*curSprite)->getID() == pSprite->getID()) return true; } return false; } void JupiterSpriteManage::setSpriteVisible(JupiterSprite* pSprite, bool bVisible) { pSprite->setVisible(bVisible); } void JupiterSpriteManage::draw(HDC hDC) { if (!jupiSprites.empty()) { vector<JupiterSprite *>::iterator curSprite; for (curSprite = jupiSprites.begin(); curSprite != jupiSprites.end(); curSprite++) { (*curSprite)->drawSprite(hDC); } } } void JupiterSpriteManage::setZOrder(JupiterSprite* pSprite,int nZorder) { delSprite(pSprite); addSprite(pSprite,nZorder); } <|endoftext|>
<commit_before>#include <iostream> #include <fstream> #include <vector> #include <array> #include <tuple> #include <memory> #include <string> using std::tuple; using std::make_tuple; using std::vector; using std::array; using std::string; using std::shared_ptr; #include <cereal/archives/json.hpp> #include <cereal/types/vector.hpp> #include <cereal/types/array.hpp> #include <opencv2/opencv.hpp> #include "opencv2/xfeatures2d.hpp" #include "camera_models.h" struct DataSetPair { DataSetPair(string left, string right) { image_left = cv::imread(left); image_right = cv::imread(right); if (image_left.data == NULL || image_right.data == NULL) { std::cerr << "ERROR: cannot load DataSetPair images\n"; } } cv::Mat image_left; cv::Mat image_right; }; // Returns the list of indexes that sort the match array by distance vector<size_t> argsort(vector<cv::DMatch> matches) { // Extend the vector with indexes vector< tuple<size_t, cv::DMatch> > indexed_matches; size_t n = 0; for (n = 0; n < matches.size(); ++n) { indexed_matches.push_back(make_tuple(n, matches[n])); } // Sort by distance std::sort(indexed_matches.begin(), indexed_matches.end(), [](const tuple<size_t, cv::DMatch>& a, const tuple<size_t, cv::DMatch>& b) { return std::get<1>(a).distance < std::get<1>(b).distance; }); // Extract the index vector<size_t> indexes(matches.size()); for (size_t i = 0; i < matches.size(); i++) { indexes[i] = std::get<0>(indexed_matches[i]); } return indexes; } template<typename T> vector<T> reorder(const vector<T>& input, vector<size_t> indexes) { vector<T> output(input.size()); for (size_t i = 0; i < input.size(); i++) { output[i] = input[indexes[i]]; } return output; } void write_matches_image(string path, cv::Mat image1, cv::Mat image2, vector<cv::KeyPoint> keypoint1, vector<cv::KeyPoint> keypoint2, vector<cv::DMatch> matches, size_t nb_of_features) { // Maximum wrap if (nb_of_features > matches.size()) { nb_of_features = matches.size(); } // Keep nb_of_features elements vector<cv::DMatch> good_matches(matches.begin(), matches.begin() + nb_of_features); // Draw cv::Mat img; cv::drawMatches(image1, keypoint1, image2, keypoint2, good_matches, img, cv::Scalar::all(-1), cv::Scalar::all(-1), vector<char>(), cv::DrawMatchesFlags::NOT_DRAW_SINGLE_POINTS); cv::imwrite(path, img); } // TODO add support for computing any feature on a zoom out input // see results for features 5% outlier level in report // // Represents image features of a dataset (keypoints and matches) // As well as pairwise relationship (relative image positions, existence of overlap) struct ImageFeatures { ImageFeatures(const DataSetPair& ds, const size_t maximum_number_of_matches) : data_set(ds) { cv::Ptr<cv::xfeatures2d::SURF> surf = cv::xfeatures2d::SURF::create(); cv::Ptr<cv::xfeatures2d::SIFT> sift = cv::xfeatures2d::SIFT::create(); cv::Ptr<cv::FeatureDetector> detector = sift; cv::Ptr<cv::DescriptorExtractor> descriptor = sift; // Detect and compute descriptors detector->detect(data_set.image_left, keypoint1); detector->detect(data_set.image_right, keypoint2); descriptor->compute(data_set.image_left, keypoint1, descriptor1); descriptor->compute(data_set.image_right, keypoint2, descriptor2); if (descriptor1.empty() || descriptor2.empty()) { std::cerr << "Empty descriptor!" << std::endl; } // FLANN needs type of descriptor to be CV_32F if (descriptor1.type()!= CV_32F) { descriptor1.convertTo(descriptor1, CV_32F); } if (descriptor2.type()!= CV_32F) { descriptor2.convertTo(descriptor2, CV_32F); } // Match using FLANN cv::FlannBasedMatcher matcher; matcher.match(descriptor1, descriptor2, matches); // Sort matches by distance // Note that keypoints don't need to be reordered because the index // of a match's keypoint is stored in match.queryIdx and match.trainIdx // (i.e. is not given implicitly by the order of the keypoint vector) vector<size_t> order = argsort(matches); matches = reorder(matches, order); write_matches_image("matches.jpg", data_set.image_left, data_set.image_right, keypoint1, keypoint2, matches, maximum_number_of_matches); // Store into simple ordered by distance vector of observations for (size_t i = 0; i < matches.size() && i < maximum_number_of_matches; i++) { // query is kp1, train is kp2 (see declaration of matcher.match observations.push_back(array<double, 4>{ keypoint1[matches[i].queryIdx].pt.x, keypoint1[matches[i].queryIdx].pt.y, keypoint2[matches[i].trainIdx].pt.x, keypoint2[matches[i].trainIdx].pt.y }); } } vector<cv::KeyPoint> keypoint1; vector<cv::KeyPoint> keypoint2; cv::Mat descriptor1; cv::Mat descriptor2; vector<cv::DMatch> matches; vector< array<double, 4> > observations; const DataSetPair& data_set; }; // struct Model0 : public Model { struct Model0 { Model0(const ImageFeatures& f, array<const double, 3> internal, array<double, 6> left_cam, array<double, 6> right_cam) : features(f), internal(internal) { // Initialize from parent model // (for now hard coded left-right images) // Initialize cameras side by side cameras.push_back(left_cam); cameras.push_back(right_cam); terrain.resize(features.observations.size()); // For each observation for (size_t i = 0; i < features.observations.size(); i++) { // Down project to z=0 to initialize terrain double dx_left, dy_left; double dx_right, dy_right; double elevation = 0.0; image_to_world(internal.data(), cameras[0].data(), &features.observations[i][0], &elevation, &dx_left, &dy_left); image_to_world(internal.data(), cameras[1].data(), &features.observations[i][2], &elevation, &dx_right, &dy_right); // Take average of both projections terrain[i] = {(dx_left + dx_right)/2.0, (dy_left + dy_right)/2.0}; } } template <class Archive> void serialize(Archive& ar) { ar(cereal::make_nvp("cameras", cameras), cereal::make_nvp("terrain", terrain)); } const ImageFeatures& features; // 3 dof internals: {f, ppx, ppy} array<const double, 3> internal; // Parameters vector< array<double, 6> > cameras; // 6 dof cameras vector< array<double, 2> > terrain; // 2 dof ground points on flat terrain }; template <int N> void print_array(array<double, N> arr) { for (size_t i = 0; i < N; i++) { std::cout << arr[i] << " "; } } int main(int argc, char* argv[]) { google::InitGoogleLogging(argv[0]); if (argc < 3) { std::cerr << "Usage: ./model0 data_dir results_dir" << std::endl; return -1; } string data = std::string(argv[1]); string results_dir = std::string(argv[2]) + "/features_analysis"; // Test problem for model0 // This problem definition code could be moved to a 'project file' or equivalent // Load images // defines filenames, pairwise order std::cout << "Loading images..." << std::endl; DataSetPair data_set(data + "/alinta-stockpile/DSC_5522.JPG", data + "/alinta-stockpile/DSC_5521.JPG"); // Match features and obtain observations std::cout << "Matching features..." << std::endl; ImageFeatures features(data_set, 10); // Create model std::cout << "Setting up model..." << std::endl; Model0 model(features, {48.3355e-3, 0.0093e-3, -0.0276e-3}, {0, 0, 269, 0, 0, 0}, {0, 0, 269, 0, 0, 0}); const double pixel_size = 0.0085e-3; // Setup solver std::cout << "Solving..." << std::endl; ceres::Problem problem; for (size_t i = 0; i < model.features.observations.size(); i++) { // Residual for left cam ceres::CostFunction* cost_function_left = Model0ReprojectionError::create(model.internal, pixel_size*model.features.observations[i][0], pixel_size*model.features.observations[i][1]); problem.AddResidualBlock(cost_function_left, NULL, model.cameras[0].data(), model.terrain[i].data() ); // Residual for right cam ceres::CostFunction* cost_function_right = Model0ReprojectionError::create(model.internal, pixel_size*model.features.observations[i][2], pixel_size*model.features.observations[i][3]); problem.AddResidualBlock(cost_function_right, NULL, model.cameras[1].data(), model.terrain[i].data() ); } problem.SetParameterBlockConstant(model.cameras[0].data()); ceres::Solver::Options options; options.linear_solver_type = ceres::DENSE_SCHUR; options.minimizer_progress_to_stdout = true; options.max_linear_solver_iterations = 3; options.max_num_iterations = 30; options.num_threads = 1; ceres::Solver::Summary summary; ceres::Solve(options, &problem, &summary); std::cout << summary.FullReport() << "\n"; std::cout << "==================" << std::endl; print_array<6>(model.cameras[0]); std::cout << std::endl; print_array<6>(model.cameras[1]); std::cout << std::endl; // Serialize model with cereal std::ofstream ofs("model0.json"); cereal::JSONOutputArchive output(ofs); output(model); } <commit_msg>serialize more and specialize std::array<double, N><commit_after>#include <iostream> #include <fstream> #include <vector> #include <array> #include <tuple> #include <memory> #include <string> using std::tuple; using std::make_tuple; using std::vector; using std::array; using std::string; using std::shared_ptr; #include <cereal/archives/json.hpp> #include <cereal/types/vector.hpp> #include <cereal/types/array.hpp> #include <opencv2/opencv.hpp> #include "opencv2/xfeatures2d.hpp" #include "camera_models.h" struct DataSetPair { DataSetPair(string l, string r) : left(l), right(r) { } void load(string data_root) { image_left = cv::imread(data_root + "/" + left); image_right = cv::imread(data_root + "/" + right); if (image_left.data == NULL || image_right.data == NULL) { std::cerr << "ERROR: cannot load DataSetPair images\n"; } } template <class Archive> void serialize(Archive& ar) { ar(CEREAL_NVP(left), CEREAL_NVP(right)); } const std::string left; const std::string right; // TODO load images on demand // or manually, ex: if (!isloaded) data_set.load() before computing features cv::Mat image_left; cv::Mat image_right; }; // Returns the list of indexes that sort the match array by distance vector<size_t> argsort(vector<cv::DMatch> matches) { // Extend the vector with indexes vector< tuple<size_t, cv::DMatch> > indexed_matches; size_t n = 0; for (n = 0; n < matches.size(); ++n) { indexed_matches.push_back(make_tuple(n, matches[n])); } // Sort by distance std::sort(indexed_matches.begin(), indexed_matches.end(), [](const tuple<size_t, cv::DMatch>& a, const tuple<size_t, cv::DMatch>& b) { return std::get<1>(a).distance < std::get<1>(b).distance; }); // Extract the index vector<size_t> indexes(matches.size()); for (size_t i = 0; i < matches.size(); i++) { indexes[i] = std::get<0>(indexed_matches[i]); } return indexes; } template<typename T> vector<T> reorder(const vector<T>& input, vector<size_t> indexes) { vector<T> output(input.size()); for (size_t i = 0; i < input.size(); i++) { output[i] = input[indexes[i]]; } return output; } void write_matches_image(string path, cv::Mat image1, cv::Mat image2, vector<cv::KeyPoint> keypoint1, vector<cv::KeyPoint> keypoint2, vector<cv::DMatch> matches, size_t nb_of_features) { // Maximum wrap if (nb_of_features > matches.size()) { nb_of_features = matches.size(); } // Keep nb_of_features elements vector<cv::DMatch> good_matches(matches.begin(), matches.begin() + nb_of_features); // Draw cv::Mat img; cv::drawMatches(image1, keypoint1, image2, keypoint2, good_matches, img, cv::Scalar::all(-1), cv::Scalar::all(-1), vector<char>(), cv::DrawMatchesFlags::NOT_DRAW_SINGLE_POINTS); cv::imwrite(path, img); } // TODO add support for computing any feature on a zoom out input // see results for features 5% outlier level in report // // Represents image features of a dataset (keypoints and matches) // As well as pairwise relationship (relative image positions, existence of overlap) struct ImageFeatures { ImageFeatures(const DataSetPair& ds, const size_t maximum_number_of_matches) : data_set(ds) { cv::Ptr<cv::xfeatures2d::SURF> surf = cv::xfeatures2d::SURF::create(); cv::Ptr<cv::xfeatures2d::SIFT> sift = cv::xfeatures2d::SIFT::create(); cv::Ptr<cv::FeatureDetector> detector = sift; cv::Ptr<cv::DescriptorExtractor> descriptor = sift; // Detect and compute descriptors detector->detect(data_set.image_left, keypoint1); detector->detect(data_set.image_right, keypoint2); descriptor->compute(data_set.image_left, keypoint1, descriptor1); descriptor->compute(data_set.image_right, keypoint2, descriptor2); if (descriptor1.empty() || descriptor2.empty()) { std::cerr << "Empty descriptor!" << std::endl; } // FLANN needs type of descriptor to be CV_32F if (descriptor1.type()!= CV_32F) { descriptor1.convertTo(descriptor1, CV_32F); } if (descriptor2.type()!= CV_32F) { descriptor2.convertTo(descriptor2, CV_32F); } // Match using FLANN cv::FlannBasedMatcher matcher; matcher.match(descriptor1, descriptor2, matches); // Sort matches by distance // Note that keypoints don't need to be reordered because the index // of a match's keypoint is stored in match.queryIdx and match.trainIdx // (i.e. is not given implicitly by the order of the keypoint vector) vector<size_t> order = argsort(matches); matches = reorder(matches, order); write_matches_image("matches.jpg", data_set.image_left, data_set.image_right, keypoint1, keypoint2, matches, maximum_number_of_matches); // Store into simple ordered by distance vector of observations for (size_t i = 0; i < matches.size() && i < maximum_number_of_matches; i++) { // query is kp1, train is kp2 (see declaration of matcher.match observations.push_back(array<double, 4>{ keypoint1[matches[i].queryIdx].pt.x, keypoint1[matches[i].queryIdx].pt.y, keypoint2[matches[i].trainIdx].pt.x, keypoint2[matches[i].trainIdx].pt.y }); } } template <class Archive> void serialize(Archive& ar) { ar(cereal::make_nvp("observations", observations)); } vector<cv::KeyPoint> keypoint1; vector<cv::KeyPoint> keypoint2; cv::Mat descriptor1; cv::Mat descriptor2; vector<cv::DMatch> matches; vector< array<double, 4> > observations; const DataSetPair& data_set; }; // struct Model0 : public Model { struct Model0 { Model0(const ImageFeatures& f, array<const double, 3> internal, array<double, 6> left_cam, array<double, 6> right_cam) : features(f), internal(internal) { // Initialize from parent model // (for now hard coded left-right images) // Initialize cameras side by side cameras.push_back(left_cam); cameras.push_back(right_cam); terrain.resize(features.observations.size()); // For each observation for (size_t i = 0; i < features.observations.size(); i++) { // Down project to z=0 to initialize terrain double dx_left, dy_left; double dx_right, dy_right; double elevation = 0.0; image_to_world(internal.data(), cameras[0].data(), &features.observations[i][0], &elevation, &dx_left, &dy_left); image_to_world(internal.data(), cameras[1].data(), &features.observations[i][2], &elevation, &dx_right, &dy_right); // Take average of both projections terrain[i] = {(dx_left + dx_right)/2.0, (dy_left + dy_right)/2.0}; } } template <class Archive> void serialize(Archive& ar) { ar(cereal::make_nvp("cameras", cameras), cereal::make_nvp("terrain", terrain)); } const ImageFeatures& features; // 3 dof internals: {f, ppx, ppy} array<const double, 3> internal; // Parameters vector< array<double, 6> > cameras; // 6 dof cameras vector< array<double, 2> > terrain; // 2 dof ground points on flat terrain }; // Overload std::array for JSON to use [] namespace cereal { template <std::size_t N> void save(cereal::JSONOutputArchive& archive, std::array<double, N> const& list) { archive(cereal::make_size_tag(static_cast<cereal::size_type>(list.size()))); for (auto && v : list) { archive(v); } } } int main(int argc, char* argv[]) { google::InitGoogleLogging(argv[0]); if (argc < 3) { std::cerr << "Usage: ./model0 data_dir results_dir" << std::endl; return -1; } string data_root = std::string(argv[1]); string results_dir = std::string(argv[2]) + "/features_analysis"; // Test problem for model0 // This problem definition code could be moved to a 'project file' or equivalent // Load images // defines filenames, pairwise order std::cout << "Loading images..." << std::endl; DataSetPair data_set("alinta-stockpile/DSC_5522.JPG", "alinta-stockpile/DSC_5521.JPG"); data_set.load(data_root); // Match features and obtain observations std::cout << "Matching features..." << std::endl; ImageFeatures features(data_set, 10); // Create model std::cout << "Setting up model..." << std::endl; Model0 model(features, {48.3355e-3, 0.0093e-3, -0.0276e-3}, {0, 0, 269, 0, 0, 0}, {0, 0, 269, 0, 0, 0}); const double pixel_size = 0.0085e-3; // Setup solver std::cout << "Solving..." << std::endl; ceres::Problem problem; for (size_t i = 0; i < model.features.observations.size(); i++) { // Residual for left cam ceres::CostFunction* cost_function_left = Model0ReprojectionError::create(model.internal, pixel_size*model.features.observations[i][0], pixel_size*model.features.observations[i][1]); problem.AddResidualBlock(cost_function_left, NULL, model.cameras[0].data(), model.terrain[i].data() ); // Residual for right cam ceres::CostFunction* cost_function_right = Model0ReprojectionError::create(model.internal, pixel_size*model.features.observations[i][2], pixel_size*model.features.observations[i][3]); problem.AddResidualBlock(cost_function_right, NULL, model.cameras[1].data(), model.terrain[i].data() ); } problem.SetParameterBlockConstant(model.cameras[0].data()); ceres::Solver::Options options; options.linear_solver_type = ceres::DENSE_SCHUR; options.minimizer_progress_to_stdout = true; options.max_linear_solver_iterations = 3; options.max_num_iterations = 30; options.num_threads = 1; ceres::Solver::Summary summary; ceres::Solve(options, &problem, &summary); std::cout << summary.FullReport() << "\n"; std::cout << "==================" << std::endl; cereal::JSONOutputArchive sum(std::cout); sum(model.cameras[0]); sum(model.cameras[1]); // Serialize model with cereal std::ofstream ofs("model0.json"); cereal::JSONOutputArchive output(ofs); output( cereal::make_nvp("data", data_set), cereal::make_nvp("features", features), cereal::make_nvp("model", model) ); } <|endoftext|>
<commit_before>// [[Rcpp::depends(RcppArmadillo)]] #include <RcppArmadillo.h> #include <Rmath.h> #include <vector> #include <cassert> #include "vmat.h" #include "gmat.h" #include "DataPairs.h" #include "quadrule.h" #include "pn.h" #include "functions.h" using namespace Rcpp; using namespace arma; using namespace std; const double twopi = 2*datum::pi; ///////////////////////////////////////////////////////////////////////////////////////////////// /* Full loglikelihood */ double loglikfull(unsigned row, DataPairs &data, const gmat &sigmaMarg, const gmat &sigmaJoint, const gmat &sigmaCond, vmat sigmaU, vec u, bool full=1){ data.pi_gen(row, u); // Estimation of pi based on u irowvec causes = data.causes_get(row); // Failure causes for pair in question double res = 0; // Initialising output (loglik contribution) if ((causes(0) > 0) & (causes(1) > 0)){ /* Both individuals experience failure */ res = logdF2(row, causes, data, sigmaJoint, u); } else if((causes(0) <= 0) & (causes(1) <= 0)){ /* Neither individual experience failure */ if ((causes(0) < 0) & (causes(1) < 0)){ // Full follow-up for both individuals for (unsigned i=1; i<=2; i++){ // Over individuals double lik = 1; for (unsigned j=1; j<=data.ncauses; j++){ // Over failure causes double prob = F1(row, j, i, data); lik -= prob; } res += log(lik); } } else if (((causes(0) < 0) & (causes(1) == 0)) | ((causes(0) == 0) & (causes(1) < 0))){ // Full follow-up for only one individual for (unsigned i=1; i<=2; i++){ // Over individuals double lik = 1; for (unsigned j=1; j<=data.ncauses; j++){ // Over failure causes if (causes(i-1) < 0){ double prob = F1(row, j, i, data); lik -= prob; } else { double prob = F1(row, j, i, data, sigmaMarg, u); lik -= prob; } } res += log(lik); } } else { // Full follow-up for neither individual double lik = 1; // Marginal probabilities for (unsigned i=1; i<=2; i++){ // Over individuals for (unsigned j=1; j<=data.ncauses; j++){ // Over failure causes double prob = F1(row, j, i, data, sigmaMarg, u); lik -= prob; // Subtracting } } // Bivariate probabilities for (unsigned k=1; k<=data.ncauses; k++){ // Over failure causes for (unsigned l=1; l<=data.ncauses; l++){ irowvec vcauses(2); vcauses(0) = k; vcauses(1) = l; double prob = F2(row, vcauses, data, sigmaJoint, u); lik += prob; // Adding } } res = log(lik); } } else { /* One individual experiences failure the other does not */ for (unsigned i=1; i<=2; i++){ // Over individuals unsigned cause = causes(i-1); if (cause > 0){ // Marginal probability of failure res += logdF1(row, cause, i, data, sigmaMarg, u); } else { // Marginal probability of no failure unsigned cond_cause; if (i==1){ cond_cause = causes(1); } else { cond_cause = causes(0); } for (unsigned j=1; j<=data.ncauses; j++){ // Over failure causes double lik = 1; if (cause < 0){ // Unconditional double prob = F1(row, j, i, data); lik -= prob; } else { // Conditional double prob = F1(row, j, i, cond_cause, data, sigmaCond, u); lik -= prob; } res += log(lik); } } } } /* Contribution from u */ if (full){ vmat sig = sigmaU; // Variance-covariance matrix of u double inner = as_scalar(u*sig.inv*u.t()); // PDF of u double logpdfu = log(pow(twopi,-(data.ncauses/2))) + sig.loginvsqdet - 0.5*inner; // Adding to the loglik res += logpdfu; } /* Return */ return(res); } ///////////////////////////////////////////////////////////////////////////////////////////////// /* Score function of full loglikelihood */ rowvec Dloglikfull(unsigned row, DataPairs &data, const gmat &sigmaMarg, const gmat &sigmaJoint, const gmat &sigmaCond, vmat sigmaU, vec u, bool full=1){ /* Estimation of pi, dpidu and dlogpidu */ data.pi_gen(row, u); data.dpidu_gen(row, u); data.dlogpidu_gen(row, u); irowvec causes = data.causes_get(row); // Failure causes for pair in question rowvec res = zeros<rowvec>(data.ncauses); // Initialising output (score contribution) if ((causes(0) > 0) & (causes(1) > 0)){ /* Both individuals experience failure */ res = dlogdF2du(row, causes, data, sigmaJoint, u); } else if((causes(0) <= 0) & (causes(1) <= 0)){ /* Neither individual experience failure */ if ((causes(0) < 0) & (causes(1) < 0)){ // Full follow-up for both individuals for (unsigned i=1; i<=2; i++){ // Over individuals double lik = 1; rowvec likdu = zeros<rowvec>(data.ncauses); for (unsigned j=1; j<=data.ncauses; j++){ // Over failure causes double prob = F1(row, j, i, data); rowvec probdu = dF1du(row, j, i, data); lik -= prob; likdu -= probdu; } res += (1/lik)*likdu; } } else if (((causes(0) < 0) & (causes(1) == 0)) | ((causes(0) == 0) & (causes(1) < 0))){ // Full follow-up for only one individual for (unsigned i=1; i<=2; i++){ // Over individuals double lik = 1; rowvec likdu = zeros<rowvec>(data.ncauses); for (unsigned j=1; j<=data.ncauses; j++){ // Over failure causes if (causes(i-1) < 0){ double prob = F1(row, j, i, data); rowvec probdu = dF1du(row, j, i, data); lik -= prob; likdu -= probdu; } else { double prob = F1(row, j, i, data, sigmaMarg, u); rowvec probdu = dF1du(row, j, i, data, sigmaMarg, u); lik -= prob; likdu -= probdu; } } res += (1/lik)*likdu; } } else { // Full follow-up for neither individual double lik = 1; rowvec likdu = zeros<rowvec>(data.ncauses); // Marginal probabilities for (unsigned i=1; i<=2; i++){ // Over individuals for (unsigned j=1; j<=data.ncauses; j++){ // Over failure causes double prob = F1(row, j, i, data, sigmaMarg, u); rowvec probdu = dF1du(row, j, i, data, sigmaMarg, u); lik -= prob; // Subtracting likdu -= probdu; } } // Bivariate probabilities for (unsigned k=1; k<=data.ncauses; k++){ // Over failure causes for (unsigned l=1; l<=data.ncauses; l++){ irowvec vcauses(2); vcauses(0) = k; vcauses(1) = l; double prob = F2(row, vcauses, data, sigmaJoint, u); rowvec probdu = dF2du(row, vcauses, data, sigmaJoint, u); lik += prob; // Adding likdu += probdu; } } res = (1/lik)*likdu; } } else { /* One individual experiences failure the other does not */ for (unsigned i=1; i<=2; i++){ // Over individuals unsigned cause = causes(i-1); if (cause > 0){ // Marginal probability of failure res += dlogdF1du(row, cause, i, data, sigmaMarg, u); } else { // Marginal probability of no failure unsigned cond_cause; if (i==1){ cond_cause = causes(1); } else { cond_cause = causes(0); } for (unsigned j=1; j<=data.ncauses; j++){ // Over failure causes double lik = 1; rowvec likdu = zeros<rowvec>(data.ncauses); if (cause < 0){ // Uncondtional double prob = F1(row, j, i, data); rowvec probdu = dF1du(row, j, i, data); lik -= prob; likdu -= probdu; } else { // Conditional double prob = F1(row, j, i, cond_cause, data, sigmaCond, u); rowvec probdu = dF1du(row, j, i, cond_cause, data, sigmaCond, u); lik -= prob; likdu -= probdu; } res += (1/lik)*likdu; } } } } /* Contribution from u */ if (full){ vmat sig = sigmaU; // Variance-covariance matrix etc. of u // Adding to the score res += -u.t()*sig.inv; }; return(res); } ///////////////////////////////////////////////////////////////////////////// // FOR TESTING double loglikout(unsigned row, mat sigma, vec u, int ncauses, imat causes, mat alpha, mat dalpha, mat beta, mat gamma){ // Initialising gmats of sigma (Joint, Cond) gmat sigmaJoint = gmat(ncauses, ncauses); gmat sigmaCond = gmat(ncauses, ncauses); gmat sigmaMarg = gmat(ncauses, 1); // Vectors for extracting rows and columns from sigma uvec rcJ(2); /* for joint */ uvec rc1(1); /* for conditional */ uvec rc2(ncauses+1); /* for conditional */ uvec rcu(ncauses); for (int h=0; h<ncauses; h++){ rcu(h) = ncauses + h; }; // Calculating and setting sigmaJoint for (int h=0; h<ncauses; h++){ for (int i=0; i<ncauses; i++){ rcJ(0)=h; rcJ(1)=ncauses+i; vmat x = vmat(sigma, rcJ, rcu); sigmaJoint.set(h,i,x); }; }; // Extracting marginal from sigmaJoint and setting sigmaMarg for (int h=0; h<ncauses; h++){ vmat Marg = vmat(1); sigmaMarg.set(h,0,x); }; // Calculating and setting sigmaCond for (int h=0; h<ncauses; h++){ for (int i=0; i<ncauses; i++){ rc1(1) = h; rc2(0) = i; for (int j=0; j<ncauses; j++){ rc2(j+1) = rcu(j); }; vmat x = vmat(sigma, rc1, rc2); sigmaCond.set(h,i,x); }; }; // vmat of the us mat matU = sigma.submat(rcu,rcu); vmat sigmaU = vmat(matU); // Generating DataPairs DataPairs data = DataPairs(ncauses, causes, alpha, dalpha, beta, gamma); // Estimating likelihood contribution double loglik = loglikfull(unsigned row, data, sigmaMarg, sigmaJoint, sigmaCond, sigmaU, u, bool full=1); // Return return loglik; }; //rowvec Dloglikout(unsigned row, mat sigma, mat data, vec u){ // Generating gmats of sigma (Marg, Joint, MargCond, sigU) // Generating DataPairs // Estimating score contribution // rowvec score = Dloglikfull(unsigned row, DataPairs data, gmat sigmaJoint, gmat sigmaMargCond, vmat sigmaU, vec u, bool full=1); // Return // return score; //}; <commit_msg>testing<commit_after>// [[Rcpp::depends(RcppArmadillo)]] #include <RcppArmadillo.h> #include <Rmath.h> #include <vector> #include <cassert> #include "vmat.h" #include "gmat.h" #include "DataPairs.h" #include "quadrule.h" #include "pn.h" #include "functions.h" using namespace Rcpp; using namespace arma; using namespace std; const double twopi = 2*datum::pi; ///////////////////////////////////////////////////////////////////////////////////////////////// /* Full loglikelihood */ double loglikfull(unsigned row, DataPairs &data, const gmat &sigmaMarg, const gmat &sigmaJoint, const gmat &sigmaCond, vmat sigmaU, vec u, bool full=1){ data.pi_gen(row, u); // Estimation of pi based on u irowvec causes = data.causes_get(row); // Failure causes for pair in question double res = 0; // Initialising output (loglik contribution) if ((causes(0) > 0) & (causes(1) > 0)){ /* Both individuals experience failure */ res = logdF2(row, causes, data, sigmaJoint, u); } else if((causes(0) <= 0) & (causes(1) <= 0)){ /* Neither individual experience failure */ if ((causes(0) < 0) & (causes(1) < 0)){ // Full follow-up for both individuals for (unsigned i=1; i<=2; i++){ // Over individuals double lik = 1; for (unsigned j=1; j<=data.ncauses; j++){ // Over failure causes double prob = F1(row, j, i, data); lik -= prob; } res += log(lik); } } else if (((causes(0) < 0) & (causes(1) == 0)) | ((causes(0) == 0) & (causes(1) < 0))){ // Full follow-up for only one individual for (unsigned i=1; i<=2; i++){ // Over individuals double lik = 1; for (unsigned j=1; j<=data.ncauses; j++){ // Over failure causes if (causes(i-1) < 0){ double prob = F1(row, j, i, data); lik -= prob; } else { double prob = F1(row, j, i, data, sigmaMarg, u); lik -= prob; } } res += log(lik); } } else { // Full follow-up for neither individual double lik = 1; // Marginal probabilities for (unsigned i=1; i<=2; i++){ // Over individuals for (unsigned j=1; j<=data.ncauses; j++){ // Over failure causes double prob = F1(row, j, i, data, sigmaMarg, u); lik -= prob; // Subtracting } } // Bivariate probabilities for (unsigned k=1; k<=data.ncauses; k++){ // Over failure causes for (unsigned l=1; l<=data.ncauses; l++){ irowvec vcauses(2); vcauses(0) = k; vcauses(1) = l; double prob = F2(row, vcauses, data, sigmaJoint, u); lik += prob; // Adding } } res = log(lik); } } else { /* One individual experiences failure the other does not */ for (unsigned i=1; i<=2; i++){ // Over individuals unsigned cause = causes(i-1); if (cause > 0){ // Marginal probability of failure res += logdF1(row, cause, i, data, sigmaMarg, u); } else { // Marginal probability of no failure unsigned cond_cause; if (i==1){ cond_cause = causes(1); } else { cond_cause = causes(0); } for (unsigned j=1; j<=data.ncauses; j++){ // Over failure causes double lik = 1; if (cause < 0){ // Unconditional double prob = F1(row, j, i, data); lik -= prob; } else { // Conditional double prob = F1(row, j, i, cond_cause, data, sigmaCond, u); lik -= prob; } res += log(lik); } } } } /* Contribution from u */ if (full){ vmat sig = sigmaU; // Variance-covariance matrix of u double inner = as_scalar(u*sig.inv*u.t()); // PDF of u double logpdfu = log(pow(twopi,-(data.ncauses/2))) + sig.loginvsqdet - 0.5*inner; // Adding to the loglik res += logpdfu; } /* Return */ return(res); } ///////////////////////////////////////////////////////////////////////////////////////////////// /* Score function of full loglikelihood */ rowvec Dloglikfull(unsigned row, DataPairs &data, const gmat &sigmaMarg, const gmat &sigmaJoint, const gmat &sigmaCond, vmat sigmaU, vec u, bool full=1){ /* Estimation of pi, dpidu and dlogpidu */ data.pi_gen(row, u); data.dpidu_gen(row, u); data.dlogpidu_gen(row, u); irowvec causes = data.causes_get(row); // Failure causes for pair in question rowvec res = zeros<rowvec>(data.ncauses); // Initialising output (score contribution) if ((causes(0) > 0) & (causes(1) > 0)){ /* Both individuals experience failure */ res = dlogdF2du(row, causes, data, sigmaJoint, u); } else if((causes(0) <= 0) & (causes(1) <= 0)){ /* Neither individual experience failure */ if ((causes(0) < 0) & (causes(1) < 0)){ // Full follow-up for both individuals for (unsigned i=1; i<=2; i++){ // Over individuals double lik = 1; rowvec likdu = zeros<rowvec>(data.ncauses); for (unsigned j=1; j<=data.ncauses; j++){ // Over failure causes double prob = F1(row, j, i, data); rowvec probdu = dF1du(row, j, i, data); lik -= prob; likdu -= probdu; } res += (1/lik)*likdu; } } else if (((causes(0) < 0) & (causes(1) == 0)) | ((causes(0) == 0) & (causes(1) < 0))){ // Full follow-up for only one individual for (unsigned i=1; i<=2; i++){ // Over individuals double lik = 1; rowvec likdu = zeros<rowvec>(data.ncauses); for (unsigned j=1; j<=data.ncauses; j++){ // Over failure causes if (causes(i-1) < 0){ double prob = F1(row, j, i, data); rowvec probdu = dF1du(row, j, i, data); lik -= prob; likdu -= probdu; } else { double prob = F1(row, j, i, data, sigmaMarg, u); rowvec probdu = dF1du(row, j, i, data, sigmaMarg, u); lik -= prob; likdu -= probdu; } } res += (1/lik)*likdu; } } else { // Full follow-up for neither individual double lik = 1; rowvec likdu = zeros<rowvec>(data.ncauses); // Marginal probabilities for (unsigned i=1; i<=2; i++){ // Over individuals for (unsigned j=1; j<=data.ncauses; j++){ // Over failure causes double prob = F1(row, j, i, data, sigmaMarg, u); rowvec probdu = dF1du(row, j, i, data, sigmaMarg, u); lik -= prob; // Subtracting likdu -= probdu; } } // Bivariate probabilities for (unsigned k=1; k<=data.ncauses; k++){ // Over failure causes for (unsigned l=1; l<=data.ncauses; l++){ irowvec vcauses(2); vcauses(0) = k; vcauses(1) = l; double prob = F2(row, vcauses, data, sigmaJoint, u); rowvec probdu = dF2du(row, vcauses, data, sigmaJoint, u); lik += prob; // Adding likdu += probdu; } } res = (1/lik)*likdu; } } else { /* One individual experiences failure the other does not */ for (unsigned i=1; i<=2; i++){ // Over individuals unsigned cause = causes(i-1); if (cause > 0){ // Marginal probability of failure res += dlogdF1du(row, cause, i, data, sigmaMarg, u); } else { // Marginal probability of no failure unsigned cond_cause; if (i==1){ cond_cause = causes(1); } else { cond_cause = causes(0); } for (unsigned j=1; j<=data.ncauses; j++){ // Over failure causes double lik = 1; rowvec likdu = zeros<rowvec>(data.ncauses); if (cause < 0){ // Uncondtional double prob = F1(row, j, i, data); rowvec probdu = dF1du(row, j, i, data); lik -= prob; likdu -= probdu; } else { // Conditional double prob = F1(row, j, i, cond_cause, data, sigmaCond, u); rowvec probdu = dF1du(row, j, i, cond_cause, data, sigmaCond, u); lik -= prob; likdu -= probdu; } res += (1/lik)*likdu; } } } } /* Contribution from u */ if (full){ vmat sig = sigmaU; // Variance-covariance matrix etc. of u // Adding to the score res += -u.t()*sig.inv; }; return(res); } ///////////////////////////////////////////////////////////////////////////// // FOR TESTING double loglikout(mat sigma, vec u, int ncauses, imat causes, mat alpha, mat dalpha, mat beta, mat gamma){ // Initialising gmats of sigma (Joint, Cond) gmat sigmaJoint = gmat(ncauses, ncauses); gmat sigmaCond = gmat(ncauses, ncauses); gmat sigmaMarg = gmat(ncauses, 1); // Vectors for extracting rows and columns from sigma uvec rcJ(2); /* for joint */ uvec rc1(1); /* for conditional */ uvec rc2(ncauses+1); /* for conditional */ uvec rcu(ncauses); for (int h=0; h<ncauses; h++){ rcu(h) = ncauses + h; }; // Calculating and setting sigmaJoint for (int h=0; h<ncauses; h++){ for (int i=0; i<ncauses; i++){ rcJ(0)=h; rcJ(1)=ncauses+i; vmat x = vmat(sigma, rcJ, rcu); sigmaJoint.set(h,i,x); }; }; // Calculating and setting sigmaMarg for (int h=0; h<ncauses; h++){ rc1(0) = h; vmat x = vmat(sigma, rc1, rcu); sigmaMarg.set(h,1,x); }; // Calculating and setting sigmaCond for (int h=0; h<ncauses; h++){ for (int i=0; i<ncauses; i++){ rc1(0) = h; rc2(0) = i; for (int j=0; j<ncauses; j++){ rc2(j+1) = rcu(j); }; vmat x = vmat(sigma, rc1, rc2); sigmaCond.set(h,i,x); }; }; // vmat of the us mat matU = sigma.submat(rcu,rcu); vmat sigmaU = vmat(matU); // Generating DataPairs DataPairs data = DataPairs(ncauses, causes, alpha, dalpha, beta, gamma); unsigned row = 1; // Estimating likelihood contribution double loglik = loglikfull(row, data, sigmaMarg, sigmaJoint, sigmaCond, sigmaU, u, full=1); // Return return loglik; }; //rowvec Dloglikout(unsigned row, mat sigma, mat data, vec u){ // Generating gmats of sigma (Marg, Joint, MargCond, sigU) // Generating DataPairs // Estimating score contribution // rowvec score = Dloglikfull(unsigned row, DataPairs data, gmat sigmaJoint, gmat sigmaMargCond, vmat sigmaU, vec u, bool full=1); // Return // return score; //}; <|endoftext|>
<commit_before>#include <opencv2/highgui/highgui.hpp> #include <opencv2/imgproc/imgproc.hpp> #include <stdlib.h> #include <iostream> #include <string> #include <sstream> std::string const intToString(int n){ std::stringstream ss; ss << n; return ss.str(); } void const drawObject(cv::Point const &center, cv::Mat &frame, bool showCoords = false){ cv::Scalar color(0, 255, 0); cv::circle(frame, center, 15, color, 2); if(showCoords){ std::string coords = "x" + intToString(center.x) + " y" + intToString(center.y); cv::putText(frame, coords, cv::Point(center.x + 20, center.y), 1, 1, color, 1); } } void const intro(){ using namespace std; cout << "ECS: Quit" << endl; cout << "SPACEBAR: toggle tracking" << endl; cout << "c: toggle coords" << endl; } int main(){ using namespace cv; intro(); VideoCapture cap(0); if(!cap.isOpened()){ std::cerr << "could not open webcam!" << std::endl; return EXIT_FAILURE; } Mat imgOrginal; bool tracking = false, showCoords = false; while(true){ if(!cap.read(imgOrginal)){ std::cerr << "could not read frame from video stream!" << std::endl; return EXIT_FAILURE; } if(tracking){ //tracking action } imshow("Orginal", imgOrginal); int keyCode = waitKey(30); switch(keyCode){ case 27: //ESC return EXIT_SUCCESS; break; case 32: //SPACEBAR tracking = !tracking; break; case 99: // c key showCoords = !showCoords; break; default: if(keyCode >= 0){ std::cout << "keyCode: " << keyCode << std::endl; } break; } } return EXIT_SUCCESS; } <commit_msg>WIP - get absdiff img<commit_after>#include <opencv2/highgui/highgui.hpp> #include <opencv2/imgproc/imgproc.hpp> #include <stdlib.h> #include <iostream> #include <string> #include <sstream> std::string const intToString(int n){ std::stringstream ss; ss << n; return ss.str(); } void const drawObject(cv::Point const &center, cv::Mat &frame, bool showCoords = false){ cv::Scalar color(0, 255, 0); cv::circle(frame, center, 15, color, 2); if(showCoords){ std::string coords = "x" + intToString(center.x) + " y" + intToString(center.y); cv::putText(frame, coords, cv::Point(center.x + 20, center.y), 1, 1, color, 1); } } void const intro(){ using namespace std; cout << "ECS: Quit" << endl; cout << "SPACEBAR: toggle tracking" << endl; cout << "c: toggle coords" << endl; } int main(){ using namespace cv; intro(); VideoCapture cap(0); if(!cap.isOpened()){ std::cerr << "could not open webcam!" << std::endl; return EXIT_FAILURE; } Mat imgOrginal, imgOrginal2, imgGray1, imgGray2, imgDiff; bool tracking = false, showCoords = false; while(true){ if(!cap.read(imgOrginal)){ std::cerr << "could not read frame from video stream!" << std::endl; return EXIT_FAILURE; } cvtColor(imgOrginal, imgGray1, COLOR_BGR2GRAY); cap.read(imgOrginal2); cvtColor(imgOrginal2, imgGray2, COLOR_BGR2GRAY); absdiff(imgGray1, imgGray2, imgDiff); if(tracking){ //tracking action } imshow("Orginal", imgDiff); int keyCode = waitKey(30); switch(keyCode){ case 27: //ESC return EXIT_SUCCESS; break; case 32: //SPACEBAR tracking = !tracking; break; case 99: // c key showCoords = !showCoords; break; default: if(keyCode >= 0){ std::cout << "keyCode: " << keyCode << std::endl; } break; } } return EXIT_SUCCESS; } <|endoftext|>
<commit_before>#ifndef _CUI_TBXFORM_HXX #define _CUI_TBXFORM_HXX #ifndef _SFXTBXCTRL_HXX //autogen #include <sfx2/tbxctrl.hxx> #endif #ifndef _SV_FIELD_HXX //autogen #include <vcl/field.hxx> #endif #ifndef _SV_DIALOG_HXX //autogen #include <vcl/dialog.hxx> #endif #ifndef _SV_BUTTON_HXX //autogen #include <vcl/button.hxx> #endif //======================================================================== class FmInputRecordNoDialog : public ModalDialog { public: FixedText m_aLabel; NumericField m_aRecordNo; OKButton m_aOk; CancelButton m_aCancel; public: FmInputRecordNoDialog(Window * pParent); void SetValue(double dNew) { m_aRecordNo.SetValue(dNew); } long GetValue() const { return m_aRecordNo.GetValue(); } }; #endif <commit_msg>INTEGRATION: CWS warnings01 (1.4.634); FILE MERGED 2006/05/04 14:46:51 os 1.4.634.1: warnings removed<commit_after>#ifndef _CUI_TBXFORM_HXX #define _CUI_TBXFORM_HXX #ifndef _SFXTBXCTRL_HXX //autogen #include <sfx2/tbxctrl.hxx> #endif #ifndef _SV_FIELD_HXX //autogen #include <vcl/field.hxx> #endif #ifndef _SV_DIALOG_HXX //autogen #include <vcl/dialog.hxx> #endif #ifndef _SV_BUTTON_HXX //autogen #include <vcl/button.hxx> #endif //======================================================================== class FmInputRecordNoDialog : public ModalDialog { public: FixedText m_aLabel; NumericField m_aRecordNo; OKButton m_aOk; CancelButton m_aCancel; public: FmInputRecordNoDialog(Window * pParent); void SetValue(long dNew) { m_aRecordNo.SetValue(dNew); } long GetValue() const { return m_aRecordNo.GetValue(); } }; #endif <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: outl_pch.hxx,v $ * * $Revision: 1.3 $ * * last change: $Author: kz $ $Date: 2007-05-10 14:55:45 $ * * 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 * ************************************************************************/ #include <svtools/intitem.hxx> #include <editeng.hxx> #include <editview.hxx> #include <editdata.hxx> #include <eerdll.hxx> #include <lrspitem.hxx> #include <fhgtitem.hxx> <commit_msg>INTEGRATION: CWS vgbugs07 (1.3.32); FILE MERGED 2007/06/04 13:27:14 vg 1.3.32.1: #i76605# Remove -I .../inc/module hack introduced by hedaburemove01<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: outl_pch.hxx,v $ * * $Revision: 1.4 $ * * last change: $Author: hr $ $Date: 2007-06-27 18:40:44 $ * * 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 * ************************************************************************/ #include <svtools/intitem.hxx> #include <svx/editeng.hxx> #include <svx/editview.hxx> #include <svx/editdata.hxx> #include <eerdll.hxx> #include <svx/lrspitem.hxx> #include <svx/fhgtitem.hxx> <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: outleeng.cxx,v $ * * $Revision: 1.11 $ * * last change: $Author: kz $ $Date: 2005-10-05 13:25:22 $ * * 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 * ************************************************************************/ #include <outl_pch.hxx> #pragma hdrstop #define _OUTLINER_CXX #include <outliner.hxx> #include <outleeng.hxx> #include <paralist.hxx> #include <outliner.hrc> #ifndef _SFXITEMSET_HXX //autogen #include <svtools/itemset.hxx> #endif #ifndef _EEITEM_HXX //autogen #include <eeitem.hxx> #endif OutlinerEditEng::OutlinerEditEng( Outliner* pEngOwner, SfxItemPool* pPool ) : EditEngine( pPool ) { pOwner = pEngOwner; } OutlinerEditEng::~OutlinerEditEng() { } void OutlinerEditEng::PaintingFirstLine( USHORT nPara, const Point& rStartPos, long nBaseLineY, const Point& rOrigin, short nOrientation, OutputDevice* pOutDev ) { pOwner->PaintBullet( nPara, rStartPos, rOrigin, nOrientation, pOutDev ); } Rectangle OutlinerEditEng::GetBulletArea( USHORT nPara ) { Rectangle aBulletArea = Rectangle( Point(), Point() ); if ( nPara < pOwner->pParaList->GetParagraphCount() ) { if ( pOwner->ImplHasBullet( nPara ) ) aBulletArea = pOwner->ImpCalcBulletArea( nPara, FALSE, FALSE ); } return aBulletArea; } void OutlinerEditEng::ParagraphInserted( USHORT nNewParagraph ) { pOwner->ParagraphInserted( nNewParagraph ); EditEngine::ParagraphInserted( nNewParagraph ); } void OutlinerEditEng::ParagraphDeleted( USHORT nDeletedParagraph ) { pOwner->ParagraphDeleted( nDeletedParagraph ); EditEngine::ParagraphDeleted( nDeletedParagraph ); } void OutlinerEditEng::StyleSheetChanged( SfxStyleSheet* pStyle ) { pOwner->StyleSheetChanged( pStyle ); } void OutlinerEditEng::ParaAttribsChanged( USHORT nPara ) { pOwner->ParaAttribsChanged( nPara ); } void OutlinerEditEng::ParagraphHeightChanged( USHORT nPara ) { pOwner->ParagraphHeightChanged( nPara ); EditEngine::ParagraphHeightChanged( nPara ); } BOOL OutlinerEditEng::SpellNextDocument() { return pOwner->SpellNextDocument(); } BOOL OutlinerEditEng::ConvertNextDocument() { return pOwner->ConvertNextDocument(); } XubString OutlinerEditEng::GetUndoComment( USHORT nUndoId ) const { #ifndef SVX_LIGHT switch( nUndoId ) { case OLUNDO_DEPTH: return XubString( EditResId( RID_OUTLUNDO_DEPTH )); case OLUNDO_EXPAND: return XubString( EditResId( RID_OUTLUNDO_EXPAND )); case OLUNDO_COLLAPSE: return XubString( EditResId( RID_OUTLUNDO_COLLAPSE )); case OLUNDO_ATTR: return XubString( EditResId( RID_OUTLUNDO_ATTR )); case OLUNDO_INSERT: return XubString( EditResId( RID_OUTLUNDO_INSERT )); default: return EditEngine::GetUndoComment( nUndoId ); } #else // SVX_LIGHT XubString aString; return aString; #endif } // #101498# void OutlinerEditEng::DrawingText( const Point& rStartPos, const XubString& rText, USHORT nTextStart, USHORT nTextLen, const sal_Int32* pDXArray, const SvxFont& rFont, USHORT nPara, USHORT nIndex, BYTE nRightToLeft) { if ( nIndex == 0 ) { // Dann das Bullet 'malen', dort wird bStrippingPortions ausgewertet // und Outliner::DrawingText gerufen // DrawingText liefert die BaseLine, DrawBullet braucht Top(). Point aCorrectedPos( rStartPos ); aCorrectedPos.Y() = GetDocPosTopLeft( nPara ).Y(); aCorrectedPos.Y() += GetFirstLineOffset( nPara ); pOwner->PaintBullet( nPara, aCorrectedPos, Point(), 0, GetRefDevice() ); } // #101498# pOwner->DrawingText(rStartPos,rText,nTextStart,nTextLen,pDXArray,rFont,nPara,nIndex,nRightToLeft); } void OutlinerEditEng::FieldClicked( const SvxFieldItem& rField, USHORT nPara, USHORT nPos ) { EditEngine::FieldClicked( rField, nPara, nPos ); // Falls URL pOwner->FieldClicked( rField, nPara, nPos ); } void OutlinerEditEng::FieldSelected( const SvxFieldItem& rField, USHORT nPara, USHORT nPos ) { pOwner->FieldSelected( rField, nPara, nPos ); } XubString OutlinerEditEng::CalcFieldValue( const SvxFieldItem& rField, USHORT nPara, USHORT nPos, Color*& rpTxtColor, Color*& rpFldColor ) { return pOwner->CalcFieldValue( rField, nPara, nPos, rpTxtColor, rpFldColor ); } <commit_msg>INTEGRATION: CWS warnings01 (1.11.180); FILE MERGED 2006/04/20 14:49:59 cl 1.11.180.1: warning free code changes<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: outleeng.cxx,v $ * * $Revision: 1.12 $ * * last change: $Author: hr $ $Date: 2006-06-19 16:22:37 $ * * 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 * ************************************************************************/ #include <outl_pch.hxx> #define _OUTLINER_CXX #include <outliner.hxx> #include <outleeng.hxx> #include <paralist.hxx> #include <outliner.hrc> #ifndef _SFXITEMSET_HXX //autogen #include <svtools/itemset.hxx> #endif #ifndef _EEITEM_HXX //autogen #include <eeitem.hxx> #endif OutlinerEditEng::OutlinerEditEng( Outliner* pEngOwner, SfxItemPool* pPool ) : EditEngine( pPool ) { pOwner = pEngOwner; } OutlinerEditEng::~OutlinerEditEng() { } void OutlinerEditEng::PaintingFirstLine( USHORT nPara, const Point& rStartPos, long nBaseLineY, const Point& rOrigin, short nOrientation, OutputDevice* pOutDev ) { pOwner->PaintBullet( nPara, rStartPos, rOrigin, nOrientation, pOutDev ); } Rectangle OutlinerEditEng::GetBulletArea( USHORT nPara ) { Rectangle aBulletArea = Rectangle( Point(), Point() ); if ( nPara < pOwner->pParaList->GetParagraphCount() ) { if ( pOwner->ImplHasBullet( nPara ) ) aBulletArea = pOwner->ImpCalcBulletArea( nPara, FALSE, FALSE ); } return aBulletArea; } void OutlinerEditEng::ParagraphInserted( USHORT nNewParagraph ) { pOwner->ParagraphInserted( nNewParagraph ); EditEngine::ParagraphInserted( nNewParagraph ); } void OutlinerEditEng::ParagraphDeleted( USHORT nDeletedParagraph ) { pOwner->ParagraphDeleted( nDeletedParagraph ); EditEngine::ParagraphDeleted( nDeletedParagraph ); } void OutlinerEditEng::StyleSheetChanged( SfxStyleSheet* pStyle ) { pOwner->StyleSheetChanged( pStyle ); } void OutlinerEditEng::ParaAttribsChanged( USHORT nPara ) { pOwner->ParaAttribsChanged( nPara ); } void OutlinerEditEng::ParagraphHeightChanged( USHORT nPara ) { pOwner->ParagraphHeightChanged( nPara ); EditEngine::ParagraphHeightChanged( nPara ); } BOOL OutlinerEditEng::SpellNextDocument() { return pOwner->SpellNextDocument(); } BOOL OutlinerEditEng::ConvertNextDocument() { return pOwner->ConvertNextDocument(); } XubString OutlinerEditEng::GetUndoComment( USHORT nUndoId ) const { #ifndef SVX_LIGHT switch( nUndoId ) { case OLUNDO_DEPTH: return XubString( EditResId( RID_OUTLUNDO_DEPTH )); case OLUNDO_EXPAND: return XubString( EditResId( RID_OUTLUNDO_EXPAND )); case OLUNDO_COLLAPSE: return XubString( EditResId( RID_OUTLUNDO_COLLAPSE )); case OLUNDO_ATTR: return XubString( EditResId( RID_OUTLUNDO_ATTR )); case OLUNDO_INSERT: return XubString( EditResId( RID_OUTLUNDO_INSERT )); default: return EditEngine::GetUndoComment( nUndoId ); } #else // SVX_LIGHT XubString aString; return aString; #endif } // #101498# void OutlinerEditEng::DrawingText( const Point& rStartPos, const XubString& rText, USHORT nTextStart, USHORT nTextLen, const sal_Int32* pDXArray, const SvxFont& rFont, USHORT nPara, USHORT nIndex, BYTE nRightToLeft) { if ( nIndex == 0 ) { // Dann das Bullet 'malen', dort wird bStrippingPortions ausgewertet // und Outliner::DrawingText gerufen // DrawingText liefert die BaseLine, DrawBullet braucht Top(). Point aCorrectedPos( rStartPos ); aCorrectedPos.Y() = GetDocPosTopLeft( nPara ).Y(); aCorrectedPos.Y() += GetFirstLineOffset( nPara ); pOwner->PaintBullet( nPara, aCorrectedPos, Point(), 0, GetRefDevice() ); } // #101498# pOwner->DrawingText(rStartPos,rText,nTextStart,nTextLen,pDXArray,rFont,nPara,nIndex,nRightToLeft); } void OutlinerEditEng::FieldClicked( const SvxFieldItem& rField, USHORT nPara, USHORT nPos ) { EditEngine::FieldClicked( rField, nPara, nPos ); // Falls URL pOwner->FieldClicked( rField, nPara, nPos ); } void OutlinerEditEng::FieldSelected( const SvxFieldItem& rField, USHORT nPara, USHORT nPos ) { pOwner->FieldSelected( rField, nPara, nPos ); } XubString OutlinerEditEng::CalcFieldValue( const SvxFieldItem& rField, USHORT nPara, USHORT nPos, Color*& rpTxtColor, Color*& rpFldColor ) { return pOwner->CalcFieldValue( rField, nPara, nPos, rpTxtColor, rpFldColor ); } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: paralist.cxx,v $ * * $Revision: 1.7 $ * * last change: $Author: obo $ $Date: 2006-10-12 13:03:24 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_svx.hxx" #include <paralist.hxx> #include <outliner.hxx> // nur wegen Paragraph, muss geaendert werden! #include <numdef.hxx> DBG_NAME(Paragraph) Paragraph::Paragraph( USHORT nDDepth ) : aBulSize( -1, -1) { DBG_CTOR( Paragraph, 0 ); DBG_ASSERT( ( nDDepth < SVX_MAX_NUM ) || ( nDDepth == 0xFFFF ), "Paragraph-CTOR: nDepth invalid!" ); nDepth = nDDepth; nFlags = 0; bVisible = TRUE; } Paragraph::Paragraph( const Paragraph& rPara ) : aBulText( rPara.aBulText ) , aBulSize( rPara.aBulSize ) { DBG_CTOR( Paragraph, 0 ); nDepth = rPara.nDepth; nFlags = rPara.nFlags; bVisible = rPara.bVisible; } Paragraph::~Paragraph() { DBG_DTOR( Paragraph, 0 ); } void ParagraphList::Clear( BOOL bDestroyParagraphs ) { if ( bDestroyParagraphs ) { for ( ULONG n = GetParagraphCount(); n; ) { Paragraph* pPara = GetParagraph( --n ); delete pPara; } } List::Clear(); } void ParagraphList::MoveParagraphs( ULONG nStart, ULONG nDest, ULONG _nCount ) { if ( ( nDest < nStart ) || ( nDest >= ( nStart + _nCount ) ) ) { ULONG n; ParagraphList aParas; for ( n = 0; n < _nCount; n++ ) { Paragraph* pPara = GetParagraph( nStart ); aParas.Insert( pPara, LIST_APPEND ); Remove( nStart ); } if ( nDest > nStart ) nDest -= _nCount; for ( n = 0; n < _nCount; n++ ) { Paragraph* pPara = aParas.GetParagraph( n ); Insert( pPara, nDest++ ); } } else DBG_ERROR( "MoveParagraphs: Invalid Parameters" ); } Paragraph* ParagraphList::NextVisible( Paragraph* pPara ) const { ULONG n = GetAbsPos( pPara ); Paragraph* p = GetParagraph( ++n ); while ( p && !p->IsVisible() ) p = GetParagraph( ++n ); return p; } Paragraph* ParagraphList::PrevVisible( Paragraph* pPara ) const { ULONG n = GetAbsPos( pPara ); Paragraph* p = n ? GetParagraph( --n ) : NULL; while ( p && !p->IsVisible() ) p = n ? GetParagraph( --n ) : NULL; return p; } Paragraph* ParagraphList::LastVisible() const { ULONG n = GetParagraphCount(); Paragraph* p = n ? GetParagraph( --n ) : NULL; while ( p && !p->IsVisible() ) p = n ? GetParagraph( --n ) : NULL; return p; } BOOL ParagraphList::HasChilds( Paragraph* pParagraph ) const { ULONG n = GetAbsPos( pParagraph ); Paragraph* pNext = GetParagraph( ++n ); return ( pNext && ( pNext->GetDepth() > pParagraph->GetDepth() ) ) ? TRUE : FALSE; } BOOL ParagraphList::HasHiddenChilds( Paragraph* pParagraph ) const { ULONG n = GetAbsPos( pParagraph ); Paragraph* pNext = GetParagraph( ++n ); return ( pNext && ( pNext->GetDepth() > pParagraph->GetDepth() ) && !pNext->IsVisible() ) ? TRUE : FALSE; } BOOL ParagraphList::HasVisibleChilds( Paragraph* pParagraph ) const { ULONG n = GetAbsPos( pParagraph ); Paragraph* pNext = GetParagraph( ++n ); return ( pNext && ( pNext->GetDepth() > pParagraph->GetDepth() ) && pNext->IsVisible() ) ? TRUE : FALSE; } ULONG ParagraphList::GetChildCount( Paragraph* pParent ) const { ULONG nChildCount = 0; ULONG n = GetAbsPos( pParent ); Paragraph* pPara = GetParagraph( ++n ); while ( pPara && ( pPara->GetDepth() > pParent->GetDepth() ) ) { nChildCount++; pPara = GetParagraph( ++n ); } return nChildCount; } Paragraph* ParagraphList::GetParent( Paragraph* pParagraph, USHORT& rRelPos ) const { rRelPos = 0; ULONG n = GetAbsPos( pParagraph ); Paragraph* pPrev = GetParagraph( --n ); while ( pPrev && ( pPrev->GetDepth() >= pParagraph->GetDepth() ) ) { if ( pPrev->GetDepth() == pParagraph->GetDepth() ) rRelPos++; pPrev = GetParagraph( --n ); } return pPrev; } void ParagraphList::Expand( Paragraph* pParent ) { ULONG nChildCount = GetChildCount( pParent ); ULONG nPos = GetAbsPos( pParent ); for ( ULONG n = 1; n <= nChildCount; n++ ) { Paragraph* pPara = GetParagraph( nPos+n ); if ( !( pPara->IsVisible() ) ) { pPara->bVisible = TRUE; aVisibleStateChangedHdl.Call( pPara ); } } } void ParagraphList::Collapse( Paragraph* pParent ) { ULONG nChildCount = GetChildCount( pParent ); ULONG nPos = GetAbsPos( pParent ); for ( ULONG n = 1; n <= nChildCount; n++ ) { Paragraph* pPara = GetParagraph( nPos+n ); if ( pPara->IsVisible() ) { pPara->bVisible = FALSE; aVisibleStateChangedHdl.Call( pPara ); } } } ULONG ParagraphList::GetVisPos( Paragraph* pPara ) { ULONG nVisPos = 0; ULONG nPos = GetAbsPos( pPara ); for ( ULONG n = 0; n < nPos; n++ ) { Paragraph* _pPara = GetParagraph( n ); if ( _pPara->IsVisible() ) nVisPos++; } return nVisPos; } <commit_msg>INTEGRATION: CWS vgbugs07 (1.7.320); FILE MERGED 2007/06/04 13:27:14 vg 1.7.320.1: #i76605# Remove -I .../inc/module hack introduced by hedaburemove01<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: paralist.cxx,v $ * * $Revision: 1.8 $ * * last change: $Author: hr $ $Date: 2007-06-27 18:42:51 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_svx.hxx" #include <paralist.hxx> #include <svx/outliner.hxx> // nur wegen Paragraph, muss geaendert werden! #include <svx/numdef.hxx> DBG_NAME(Paragraph) Paragraph::Paragraph( USHORT nDDepth ) : aBulSize( -1, -1) { DBG_CTOR( Paragraph, 0 ); DBG_ASSERT( ( nDDepth < SVX_MAX_NUM ) || ( nDDepth == 0xFFFF ), "Paragraph-CTOR: nDepth invalid!" ); nDepth = nDDepth; nFlags = 0; bVisible = TRUE; } Paragraph::Paragraph( const Paragraph& rPara ) : aBulText( rPara.aBulText ) , aBulSize( rPara.aBulSize ) { DBG_CTOR( Paragraph, 0 ); nDepth = rPara.nDepth; nFlags = rPara.nFlags; bVisible = rPara.bVisible; } Paragraph::~Paragraph() { DBG_DTOR( Paragraph, 0 ); } void ParagraphList::Clear( BOOL bDestroyParagraphs ) { if ( bDestroyParagraphs ) { for ( ULONG n = GetParagraphCount(); n; ) { Paragraph* pPara = GetParagraph( --n ); delete pPara; } } List::Clear(); } void ParagraphList::MoveParagraphs( ULONG nStart, ULONG nDest, ULONG _nCount ) { if ( ( nDest < nStart ) || ( nDest >= ( nStart + _nCount ) ) ) { ULONG n; ParagraphList aParas; for ( n = 0; n < _nCount; n++ ) { Paragraph* pPara = GetParagraph( nStart ); aParas.Insert( pPara, LIST_APPEND ); Remove( nStart ); } if ( nDest > nStart ) nDest -= _nCount; for ( n = 0; n < _nCount; n++ ) { Paragraph* pPara = aParas.GetParagraph( n ); Insert( pPara, nDest++ ); } } else DBG_ERROR( "MoveParagraphs: Invalid Parameters" ); } Paragraph* ParagraphList::NextVisible( Paragraph* pPara ) const { ULONG n = GetAbsPos( pPara ); Paragraph* p = GetParagraph( ++n ); while ( p && !p->IsVisible() ) p = GetParagraph( ++n ); return p; } Paragraph* ParagraphList::PrevVisible( Paragraph* pPara ) const { ULONG n = GetAbsPos( pPara ); Paragraph* p = n ? GetParagraph( --n ) : NULL; while ( p && !p->IsVisible() ) p = n ? GetParagraph( --n ) : NULL; return p; } Paragraph* ParagraphList::LastVisible() const { ULONG n = GetParagraphCount(); Paragraph* p = n ? GetParagraph( --n ) : NULL; while ( p && !p->IsVisible() ) p = n ? GetParagraph( --n ) : NULL; return p; } BOOL ParagraphList::HasChilds( Paragraph* pParagraph ) const { ULONG n = GetAbsPos( pParagraph ); Paragraph* pNext = GetParagraph( ++n ); return ( pNext && ( pNext->GetDepth() > pParagraph->GetDepth() ) ) ? TRUE : FALSE; } BOOL ParagraphList::HasHiddenChilds( Paragraph* pParagraph ) const { ULONG n = GetAbsPos( pParagraph ); Paragraph* pNext = GetParagraph( ++n ); return ( pNext && ( pNext->GetDepth() > pParagraph->GetDepth() ) && !pNext->IsVisible() ) ? TRUE : FALSE; } BOOL ParagraphList::HasVisibleChilds( Paragraph* pParagraph ) const { ULONG n = GetAbsPos( pParagraph ); Paragraph* pNext = GetParagraph( ++n ); return ( pNext && ( pNext->GetDepth() > pParagraph->GetDepth() ) && pNext->IsVisible() ) ? TRUE : FALSE; } ULONG ParagraphList::GetChildCount( Paragraph* pParent ) const { ULONG nChildCount = 0; ULONG n = GetAbsPos( pParent ); Paragraph* pPara = GetParagraph( ++n ); while ( pPara && ( pPara->GetDepth() > pParent->GetDepth() ) ) { nChildCount++; pPara = GetParagraph( ++n ); } return nChildCount; } Paragraph* ParagraphList::GetParent( Paragraph* pParagraph, USHORT& rRelPos ) const { rRelPos = 0; ULONG n = GetAbsPos( pParagraph ); Paragraph* pPrev = GetParagraph( --n ); while ( pPrev && ( pPrev->GetDepth() >= pParagraph->GetDepth() ) ) { if ( pPrev->GetDepth() == pParagraph->GetDepth() ) rRelPos++; pPrev = GetParagraph( --n ); } return pPrev; } void ParagraphList::Expand( Paragraph* pParent ) { ULONG nChildCount = GetChildCount( pParent ); ULONG nPos = GetAbsPos( pParent ); for ( ULONG n = 1; n <= nChildCount; n++ ) { Paragraph* pPara = GetParagraph( nPos+n ); if ( !( pPara->IsVisible() ) ) { pPara->bVisible = TRUE; aVisibleStateChangedHdl.Call( pPara ); } } } void ParagraphList::Collapse( Paragraph* pParent ) { ULONG nChildCount = GetChildCount( pParent ); ULONG nPos = GetAbsPos( pParent ); for ( ULONG n = 1; n <= nChildCount; n++ ) { Paragraph* pPara = GetParagraph( nPos+n ); if ( pPara->IsVisible() ) { pPara->bVisible = FALSE; aVisibleStateChangedHdl.Call( pPara ); } } } ULONG ParagraphList::GetVisPos( Paragraph* pPara ) { ULONG nVisPos = 0; ULONG nPos = GetAbsPos( pPara ); for ( ULONG n = 0; n < nPos; n++ ) { Paragraph* _pPara = GetParagraph( n ); if ( _pPara->IsVisible() ) nVisPos++; } return nVisPos; } <|endoftext|>
<commit_before><commit_msg>Apply Style: Fix the styles preview on Windows.<commit_after><|endoftext|>
<commit_before><commit_msg>Make small UI tweaks to SvxColorWindow_Impl<commit_after><|endoftext|>
<commit_before><commit_msg>Fix color update for selection with multiple colors<commit_after><|endoftext|>
<commit_before>#include <tulip/BoundingBox.h> #include <tulip/Coord.h> #include <tulip/BooleanProperty.h> #include "ZoomAndPanAnimation.h" #include "GlRect2D.h" #include "GlScene.h" #include "GlLayer.h" #include "TimeMeasurer.h" #include "RectangleZoomInteractor.h" static ZoomAndPanAnimation *zoomAndPanAnimation = NULL; static const unsigned int baseAnimDuration = 1000; static bool animating = false; static double animDuration = 0; static TimeMeasurer tm; static const unsigned int delay = 40; static void animate(void *value) { AnimateParams *animParams = reinterpret_cast<AnimateParams*>(value); double t = tm.getElapsedTime() / animDuration; if (t < 1.0) { zoomAndPanAnimation->zoomAndPanAnimationStep(t); animParams->scene->setBackupBackBuffer(false); animParams->scene->requestDraw(); timerFunc(delay, animate, animParams); } else { zoomAndPanAnimation->zoomAndPanAnimationStep(1.0); animParams->scene->setBackupBackBuffer(true); animParams->scene->requestDraw(); delete zoomAndPanAnimation; zoomAndPanAnimation = NULL; animating = false; } } RectangleZoomInteractor::RectangleZoomInteractor(GlScene *glScene) : _firstX(-1), _firstY(-1), _curX(-1), _curY(-1), _dragStarted(false) { setScene(glScene); _animParams.scene = glScene; } bool RectangleZoomInteractor::mouseCallback(const MouseButton &button, const MouseButtonState &state, int x, int y, const int & /*modifiers*/) { if (!_glScene) return false; Camera *camera = _glScene->getMainLayer()->getCamera(); tlp::Vec4i viewport = camera->getViewport(); if (x < viewport[0] || x > viewport[2] || y < viewport[1] || y > viewport[3] || animating) return false; _mouseButton = button; if (button == LEFT_BUTTON) { if (state == DOWN) { _firstX = _curX = x; _firstY = _curY = y; _dragStarted = true; return true; } else if (state == UP && _dragStarted) { _dragStarted = false; tlp::Coord bbMin = camera->screenTo3DWorld(tlp::Coord(viewport[2] - _firstX, _firstY)); tlp::Coord bbMax = camera->screenTo3DWorld(tlp::Coord(viewport[2] - _curX, _curY)); tlp::BoundingBox bb; bb.expand(bbMin); bb.expand(bbMax); zoomAndPanAnimation = new ZoomAndPanAnimation(camera, bb, baseAnimDuration); if (zoomAndPanAnimation->canDoZoomAndPan()) { animDuration = zoomAndPanAnimation->getAnimationDuration(); animating = true; _animParams.scene = _glScene; tm.reset(); timerFunc(delay, animate, &_animParams); } else { delete zoomAndPanAnimation; zoomAndPanAnimation = NULL; } _firstX = _curX = -1; _firstY = _curY = -1; _glScene->requestDraw(); return true; } } return false; } bool RectangleZoomInteractor::mouseMoveCallback(int x, int y, const int & /*modifiers*/) { if (!_glScene) return false; tlp::Vec4i viewport = _glScene->getMainLayer()->getCamera()->getViewport(); if (x < viewport[0] || x > viewport[2] || y < viewport[1] || y > viewport[3] || animating) return false; if (_mouseButton == LEFT_BUTTON && _dragStarted) { _curX = x; _curY = y; _glScene->requestDraw(); return true; } return false; } bool RectangleZoomInteractor::keyboardCallback(const std::string &keyStr, const int & /*modifiers*/) { if (!_glScene || animating) return false; if (keyStr == "c") { Camera *camera = _glScene->getMainLayer()->getCamera(); zoomAndPanAnimation = new ZoomAndPanAnimation(camera, camera->getSceneBoundingBox(), baseAnimDuration); animDuration = zoomAndPanAnimation->getAnimationDuration(); animating = true; _animParams.scene = _glScene; tm.reset(); timerFunc(delay, animate, &_animParams); return true; } return false; } void RectangleZoomInteractor::draw() { if (!_glScene || _firstX != -1) { Camera *camera = _glScene->getMainLayer()->getCamera(); Camera camera2d(false); tlp::Vec4i viewport = camera->getViewport(); camera2d.setViewport(viewport); camera2d.initGl(); tlp::Vec2f bl(std::min(_firstX, _curX), std::min(viewport[3] - _firstY, viewport[3] - _curY)); tlp::Vec2f tr(std::max(_firstX, _curX), std::max(viewport[3] - _firstY, viewport[3] - _curY)); GlRect2D rect(bl, tr, 0, tlp::Color(0,0,255,100), tlp::Color::Black); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); rect.draw(camera2d); glDisable(GL_BLEND); } } <commit_msg>animate zoom and pan till the view is centered on double click<commit_after>#include <tulip/BoundingBox.h> #include <tulip/Coord.h> #include <tulip/BooleanProperty.h> #include "ZoomAndPanAnimation.h" #include "GlRect2D.h" #include "GlScene.h" #include "GlLayer.h" #include "TimeMeasurer.h" #include "RectangleZoomInteractor.h" static ZoomAndPanAnimation *zoomAndPanAnimation = NULL; static const unsigned int baseAnimDuration = 1000; static bool animating = false; static double animDuration = 0; static TimeMeasurer tm; static const unsigned int delay = 40; static void animate(void *value) { AnimateParams *animParams = reinterpret_cast<AnimateParams*>(value); double t = tm.getElapsedTime() / animDuration; if (t < 1.0) { zoomAndPanAnimation->zoomAndPanAnimationStep(t); animParams->scene->setBackupBackBuffer(false); animParams->scene->requestDraw(); timerFunc(delay, animate, animParams); } else { zoomAndPanAnimation->zoomAndPanAnimationStep(1.0); animParams->scene->setBackupBackBuffer(true); animParams->scene->requestDraw(); delete zoomAndPanAnimation; zoomAndPanAnimation = NULL; animating = false; } } RectangleZoomInteractor::RectangleZoomInteractor(GlScene *glScene) : _firstX(-1), _firstY(-1), _curX(-1), _curY(-1), _dragStarted(false) { setScene(glScene); _animParams.scene = glScene; } bool RectangleZoomInteractor::mouseCallback(const MouseButton &button, const MouseButtonState &state, int x, int y, const int & /*modifiers*/) { if (!_glScene || animating) return false; Camera *camera = _glScene->getMainLayer()->getCamera(); tlp::Vec4i viewport = camera->getViewport(); if (x < viewport[0] || x > viewport[2] || y < viewport[1] || y > viewport[3] || animating) return false; _mouseButton = button; if (button == LEFT_BUTTON) { if (state == DOWN) { _firstX = _curX = x; _firstY = _curY = y; // double click if (tm.getElapsedTime() < 150) { keyboardCallback("c", 0); } else { _dragStarted = true; } tm.reset(); return true; } else if (state == UP && _dragStarted) { _dragStarted = false; tlp::Coord bbMin = camera->screenTo3DWorld(tlp::Coord(viewport[2] - _firstX, _firstY)); tlp::Coord bbMax = camera->screenTo3DWorld(tlp::Coord(viewport[2] - _curX, _curY)); tlp::BoundingBox bb; bb.expand(bbMin); bb.expand(bbMax); zoomAndPanAnimation = new ZoomAndPanAnimation(camera, bb, baseAnimDuration); if (zoomAndPanAnimation->canDoZoomAndPan()) { animDuration = zoomAndPanAnimation->getAnimationDuration(); animating = true; _animParams.scene = _glScene; tm.reset(); timerFunc(delay, animate, &_animParams); } else { delete zoomAndPanAnimation; zoomAndPanAnimation = NULL; } _firstX = _curX = -1; _firstY = _curY = -1; _glScene->requestDraw(); return true; } } return false; } bool RectangleZoomInteractor::mouseMoveCallback(int x, int y, const int & /*modifiers*/) { if (!_glScene || animating) return false; tlp::Vec4i viewport = _glScene->getMainLayer()->getCamera()->getViewport(); if (x < viewport[0] || x > viewport[2] || y < viewport[1] || y > viewport[3] || animating) return false; if (_mouseButton == LEFT_BUTTON && _dragStarted) { _curX = x; _curY = y; _glScene->requestDraw(); return true; } return false; } bool RectangleZoomInteractor::keyboardCallback(const std::string &keyStr, const int & /*modifiers*/) { if (!_glScene || animating) return false; if (keyStr == "c") { Camera *camera = _glScene->getMainLayer()->getCamera(); zoomAndPanAnimation = new ZoomAndPanAnimation(camera, camera->getSceneBoundingBox(), baseAnimDuration); animDuration = zoomAndPanAnimation->getAnimationDuration(); animating = true; _animParams.scene = _glScene; tm.reset(); timerFunc(delay, animate, &_animParams); return true; } return false; } void RectangleZoomInteractor::draw() { if (!_glScene || _firstX != -1) { Camera *camera = _glScene->getMainLayer()->getCamera(); Camera camera2d(false); tlp::Vec4i viewport = camera->getViewport(); camera2d.setViewport(viewport); camera2d.initGl(); tlp::Vec2f bl(std::min(_firstX, _curX), std::min(viewport[3] - _firstY, viewport[3] - _curY)); tlp::Vec2f tr(std::max(_firstX, _curX), std::max(viewport[3] - _firstY, viewport[3] - _curY)); GlRect2D rect(bl, tr, 0, tlp::Color(0,0,255,100), tlp::Color::Black); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); rect.draw(camera2d); glDisable(GL_BLEND); } } <|endoftext|>
<commit_before>#ifndef VG_PACKER_HPP_INCLUDED #define VG_PACKER_HPP_INCLUDED #include <iostream> #include <map> #include <chrono> #include <ctime> #include "omp.h" #include "xg.hpp" #include "alignment.hpp" #include "path.hpp" #include "position.hpp" #include "json2pb.h" #include "graph.hpp" #include "gcsa/internal.h" #include "xg_position.hpp" #include "utility.hpp" namespace vg { using namespace sdsl; class Packer { public: Packer(void); Packer(xg::XG* xidx, size_t bin_size = 0); ~Packer(void); xg::XG* xgidx; void merge_from_files(const vector<string>& file_names); void merge_from_dynamic(vector<Packer*>& packers); void load_from_file(const string& file_name); void save_to_file(const string& file_name); void load(istream& in); size_t serialize(std::ostream& out, sdsl::structure_tree_node* s = NULL, std::string name = ""); void make_compact(void); void make_dynamic(void); void add(const Alignment& aln, bool record_edits = true); size_t graph_length(void) const; size_t position_in_basis(const Position& pos) const; string pos_key(size_t i) const; string edit_value(const Edit& edit, bool revcomp) const; vector<Edit> edits_at_position(size_t i) const; size_t coverage_at_position(size_t i) const; void collect_coverage(const Packer& c); ostream& as_table(ostream& out, bool show_edits, vector<vg::id_t> node_ids); ostream& show_structure(ostream& out); // debugging void write_edits(vector<ofstream*>& out) const; // for merge void write_edits(ostream& out, size_t bin) const; // for merge size_t get_bin_size(void) const; size_t get_n_bins(void) const; bool is_dynamic(void); size_t coverage_size(void); private: void ensure_edit_tmpfiles_open(void); void close_edit_tmpfiles(void); void remove_edit_tmpfiles(void); bool is_compacted = false; // dynamic model gcsa::CounterArray coverage_dynamic; vector<string> edit_tmpfile_names; vector<ofstream*> tmpfstreams; // which bin should we use size_t bin_for_position(size_t i) const; size_t n_bins = 1; size_t bin_size = 0; size_t edit_length = 0; size_t edit_count = 0; dac_vector<> coverage_civ; // graph coverage (compacted coverage_dynamic) // vector<csa_sada<enc_vector<>, 32, 32, sa_order_sa_sampling<>, isa_sampling<>, succinct_byte_alphabet<> > > edit_csas; // make separators that are somewhat unusual, as we escape these char delim1 = '\xff'; char delim2 = '\xfe'; // double the delimiter in the string string escape_delim(const string& s, char d) const; string escape_delims(const string& s) const; // take each double delimiter back to a single string unescape_delim(const string& s, char d) const; string unescape_delims(const string& s) const; }; // for making a combined matrix output and maybe doing other fun operations class Packers : public vector<Packer> { void load(const vector<string>& file_names); ostream& as_table(ostream& out); }; } #endif <commit_msg>Add edge coverage vector<commit_after>#ifndef VG_PACKER_HPP_INCLUDED #define VG_PACKER_HPP_INCLUDED #include <iostream> #include <map> #include <chrono> #include <ctime> #include "omp.h" #include "xg.hpp" #include "alignment.hpp" #include "path.hpp" #include "position.hpp" #include "json2pb.h" #include "graph.hpp" #include "gcsa/internal.h" #include "xg_position.hpp" #include "utility.hpp" namespace vg { using namespace sdsl; class Packer { public: Packer(void); Packer(xg::XG* xidx, size_t bin_size = 0); ~Packer(void); xg::XG* xgidx; void merge_from_files(const vector<string>& file_names); void merge_from_dynamic(vector<Packer*>& packers); void load_from_file(const string& file_name); void save_to_file(const string& file_name); void load(istream& in); size_t serialize(std::ostream& out, sdsl::structure_tree_node* s = NULL, std::string name = ""); void make_compact(void); void make_dynamic(void); void add(const Alignment& aln, bool record_edits = true); size_t graph_length(void) const; size_t position_in_basis(const Position& pos) const; string pos_key(size_t i) const; string edit_value(const Edit& edit, bool revcomp) const; vector<Edit> edits_at_position(size_t i) const; size_t coverage_at_position(size_t i) const; void collect_coverage(const Packer& c); ostream& as_table(ostream& out, bool show_edits, vector<vg::id_t> node_ids); ostream& show_structure(ostream& out); // debugging void write_edits(vector<ofstream*>& out) const; // for merge void write_edits(ostream& out, size_t bin) const; // for merge size_t get_bin_size(void) const; size_t get_n_bins(void) const; bool is_dynamic(void); size_t coverage_size(void); private: void ensure_edit_tmpfiles_open(void); void close_edit_tmpfiles(void); void remove_edit_tmpfiles(void); bool is_compacted = false; // dynamic model gcsa::CounterArray coverage_dynamic; gcsa::CounterArray edge_coverage_dynamic; vector<string> edit_tmpfile_names; vector<ofstream*> tmpfstreams; // which bin should we use size_t bin_for_position(size_t i) const; size_t n_bins = 1; size_t bin_size = 0; size_t edit_length = 0; size_t edit_count = 0; dac_vector<> coverage_civ; // graph coverage (compacted coverage_dynamic) // vector<csa_sada<enc_vector<>, 32, 32, sa_order_sa_sampling<>, isa_sampling<>, succinct_byte_alphabet<> > > edit_csas; // make separators that are somewhat unusual, as we escape these char delim1 = '\xff'; char delim2 = '\xfe'; // double the delimiter in the string string escape_delim(const string& s, char d) const; string escape_delims(const string& s) const; // take each double delimiter back to a single string unescape_delim(const string& s, char d) const; string unescape_delims(const string& s) const; }; // for making a combined matrix output and maybe doing other fun operations class Packers : public vector<Packer> { void load(const vector<string>& file_names); ostream& as_table(ostream& out); }; } #endif <|endoftext|>
<commit_before>/* -*- c++ -*- identitymanager.h KMail, the KDE mail client. Copyright (c) 2002 the KMail authors. See file AUTHORS for details This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License, version 2.0, as published by the Free Software Foundation. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, US */ // config keys: static const char * configKeyDefaultIdentity = "Default Identity"; #include "identitymanager.h" #include "kmidentity.h" // for IdentityList::{export,import}Data #ifndef KMAIL_TESTING #include "kmkernel.h" #endif #include <kemailsettings.h> // for IdentityEntry::fromControlCenter() #include <kapplication.h> #include <klocale.h> #include <kconfig.h> #include <kdebug.h> #include <qregexp.h> #include <qtl.h> #include <pwd.h> // for struct pw; #include <unistd.h> // for getuid #include <assert.h> IdentityManager::IdentityManager( QObject * parent, const char * name ) : ConfigManager( parent, name ) { readConfig(); mShadowIdentities = mIdentities; // we need at least a default identity: if ( mIdentities.isEmpty() ) { kdDebug( 5006 ) << "IdentityManager: No identity found. Creating default." << endl; createDefaultIdentity(); commit(); } } IdentityManager::~IdentityManager() { kdWarning( hasPendingChanges(), 5006 ) << "IdentityManager: There were uncommited changes!" << endl; } void IdentityManager::commit() { if ( !hasPendingChanges() ) return; mIdentities = mShadowIdentities; writeConfig(); emit changed(); } void IdentityManager::rollback() { mShadowIdentities = mIdentities; } bool IdentityManager::hasPendingChanges() const { return mIdentities != mShadowIdentities; } QStringList IdentityManager::identities() const { QStringList result; for ( ConstIterator it = mIdentities.begin() ; it != mIdentities.end() ; ++it ) result << (*it).identityName(); return result; } QStringList IdentityManager::shadowIdentities() const { QStringList result; for ( ConstIterator it = mShadowIdentities.begin() ; it != mShadowIdentities.end() ; ++it ) result << (*it).identityName(); return result; } // hmm, anyone can explain why I need to explicitely instantate qHeapSort? //template void qHeapSort( QValueList<KMIdentity> & ); void IdentityManager::sort() { qHeapSort( mShadowIdentities ); } void IdentityManager::writeConfig() const { QStringList identities = groupList(); KConfig * config = kapp->config(); for ( QStringList::Iterator group = identities.begin() ; group != identities.end() ; ++group ) config->deleteGroup( *group ); int i = 0; for ( ConstIterator it = mIdentities.begin() ; it != mIdentities.end() ; ++it, ++i ) { KConfigGroup cg( config, QString::fromLatin1("Identity #%1").arg(i) ); (*it).writeConfig( &cg ); if ( (*it).isDefault() ) { // remember which one is default: KConfigGroup general( config, "General" ); general.writeEntry( configKeyDefaultIdentity, (*it).identityName() ); } } #ifndef KMAIL_TESTING kernel->slotRequestConfigSync(); #else config->sync(); #endif } void IdentityManager::readConfig() { mIdentities.clear(); QStringList identities = groupList(); if ( identities.isEmpty() ) return; // nothing to be done... KConfigGroup general( kapp->config(), "General" ); QString defaultIdentity = general.readEntry( configKeyDefaultIdentity ); bool haveDefault = false; for ( QStringList::Iterator group = identities.begin() ; group != identities.end() ; ++group ) { KConfigGroup config( kapp->config(), *group ); mIdentities << KMIdentity(); mIdentities.last().readConfig( &config ); if ( !haveDefault && mIdentities.last().identityName() == defaultIdentity ) { haveDefault = true; mIdentities.last().setIsDefault( true ); } } if ( !haveDefault ) { kdWarning( 5006 ) << "IdentityManager: There was no default identity. Marking first one as default." << endl; mIdentities.first().setIsDefault( true ); } qHeapSort( mIdentities ); } QStringList IdentityManager::groupList() const { return kapp->config()->groupList().grep( QRegExp("^Identity #\\d+$") ); } IdentityManager::ConstIterator IdentityManager::begin() const { return mIdentities.begin(); } IdentityManager::ConstIterator IdentityManager::end() const { return mIdentities.end(); } IdentityManager::Iterator IdentityManager::begin() { return mShadowIdentities.begin(); } IdentityManager::Iterator IdentityManager::end() { return mShadowIdentities.end(); } const KMIdentity & IdentityManager::identityForName( const QString & name ) const { for ( ConstIterator it = begin() ; it != end() ; ++it ) if ( (*it).identityName() == name ) return (*it); return KMIdentity::null; } const KMIdentity & IdentityManager::identityForNameOrDefault( const QString & name ) const { const KMIdentity & ident = identityForName( name ); if ( ident.isNull() ) return defaultIdentity(); else return ident; } const KMIdentity & IdentityManager::identityForAddress( const QString & addressList ) const { for ( ConstIterator it = begin() ; it != end() ; ++it ) if ( addressList.find( (*it).emailAddr(), 0, false ) != -1 ) return (*it); return KMIdentity::null; } KMIdentity & IdentityManager::identityForName( const QString & name ) { for ( Iterator it = begin() ; it != end() ; ++it ) if ( (*it).identityName() == name ) return (*it); kdWarning( 5006 ) << "IdentityManager::identityForName() used as newFromScratch() replacement!" << "\n name == \"" << name << "\"" << endl; return newFromScratch( name ); } const KMIdentity & IdentityManager::defaultIdentity() const { for ( ConstIterator it = begin() ; it != end() ; ++it ) if ( (*it).isDefault() ) return (*it); (mIdentities.isEmpty() ? kdFatal( 5006 ) : kdWarning( 5006 ) ) << "IdentityManager: No default identity found!" << endl; return *begin(); } bool IdentityManager::setAsDefault( const QString & name ) { // First, check if the identity actually exists: QStringList names = shadowIdentities(); if ( names.find( name ) == names.end() ) return false; // Then, change the default as requested: for ( Iterator it = begin() ; it != end() ; ++it ) (*it).setIsDefault( (*it).identityName() == name ); // and re-sort: sort(); return true; } bool IdentityManager::removeIdentity( const QString & name ) { for ( Iterator it = begin() ; it != end() ; ++it ) if ( (*it).identityName() == name ) { bool removedWasDefault = (*it).isDefault(); mShadowIdentities.remove( it ); if ( removedWasDefault ) mShadowIdentities.first().setIsDefault( true ); return true; } return false; } KMIdentity & IdentityManager::newFromScratch( const QString & name ) { return newFromExisting( KMIdentity( name ) ); } KMIdentity & IdentityManager::newFromControlCenter( const QString & name ) { KEMailSettings es; es.setProfile( es.defaultProfileName() ); return newFromExisting( KMIdentity( name, es.getSetting( KEMailSettings::RealName ), es.getSetting( KEMailSettings::EmailAddress ), es.getSetting( KEMailSettings::Organization ), es.getSetting( KEMailSettings::ReplyToAddress ) ) ); } KMIdentity & IdentityManager::newFromExisting( const KMIdentity & other, const QString & name ) { mShadowIdentities << other; KMIdentity & result = mShadowIdentities.last(); result.setIsDefault( false ); // we don't want two default identities! if ( !name.isNull() ) result.setIdentityName( name ); return result; } void IdentityManager::createDefaultIdentity() { struct passwd * pw = getpwuid( getuid() ); QString fullName, emailAddr; if ( pw ) { // extract possible full name from /etc/passwd fullName = QString::fromLocal8Bit( pw->pw_gecos ); int i = fullName.find(','); if ( i > 0 ) fullName.truncate( i ); // extract login name from /etc/passwd and get hostname to form an // educated guess about the possible email address: char str[256]; if ( !gethostname( str, 255 ) ) // str need not be NUL-terminated if it has full length: str[255] = 0; else str[0] = 0; emailAddr = QString::fromLatin1("%1@%2") .arg( QString::fromLocal8Bit( pw->pw_name ) ) .arg( QString::fromLatin1( *str ? str : "localhost" ) ); } mShadowIdentities << KMIdentity( i18n("Default"), fullName, emailAddr ); mShadowIdentities.last().setIsDefault( true ); } #include "identitymanager.moc" <commit_msg>comment typo<commit_after>/* -*- c++ -*- identitymanager.cpp KMail, the KDE mail client. Copyright (c) 2002 the KMail authors. See file AUTHORS for details This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License, version 2.0, as published by the Free Software Foundation. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, US */ // config keys: static const char * configKeyDefaultIdentity = "Default Identity"; #include "identitymanager.h" #include "kmidentity.h" // for IdentityList::{export,import}Data #ifndef KMAIL_TESTING #include "kmkernel.h" #endif #include <kemailsettings.h> // for IdentityEntry::fromControlCenter() #include <kapplication.h> #include <klocale.h> #include <kconfig.h> #include <kdebug.h> #include <qregexp.h> #include <qtl.h> #include <pwd.h> // for struct pw; #include <unistd.h> // for getuid #include <assert.h> IdentityManager::IdentityManager( QObject * parent, const char * name ) : ConfigManager( parent, name ) { readConfig(); mShadowIdentities = mIdentities; // we need at least a default identity: if ( mIdentities.isEmpty() ) { kdDebug( 5006 ) << "IdentityManager: No identity found. Creating default." << endl; createDefaultIdentity(); commit(); } } IdentityManager::~IdentityManager() { kdWarning( hasPendingChanges(), 5006 ) << "IdentityManager: There were uncommited changes!" << endl; } void IdentityManager::commit() { if ( !hasPendingChanges() ) return; mIdentities = mShadowIdentities; writeConfig(); emit changed(); } void IdentityManager::rollback() { mShadowIdentities = mIdentities; } bool IdentityManager::hasPendingChanges() const { return mIdentities != mShadowIdentities; } QStringList IdentityManager::identities() const { QStringList result; for ( ConstIterator it = mIdentities.begin() ; it != mIdentities.end() ; ++it ) result << (*it).identityName(); return result; } QStringList IdentityManager::shadowIdentities() const { QStringList result; for ( ConstIterator it = mShadowIdentities.begin() ; it != mShadowIdentities.end() ; ++it ) result << (*it).identityName(); return result; } // hmm, anyone can explain why I need to explicitely instantate qHeapSort? //template void qHeapSort( QValueList<KMIdentity> & ); void IdentityManager::sort() { qHeapSort( mShadowIdentities ); } void IdentityManager::writeConfig() const { QStringList identities = groupList(); KConfig * config = kapp->config(); for ( QStringList::Iterator group = identities.begin() ; group != identities.end() ; ++group ) config->deleteGroup( *group ); int i = 0; for ( ConstIterator it = mIdentities.begin() ; it != mIdentities.end() ; ++it, ++i ) { KConfigGroup cg( config, QString::fromLatin1("Identity #%1").arg(i) ); (*it).writeConfig( &cg ); if ( (*it).isDefault() ) { // remember which one is default: KConfigGroup general( config, "General" ); general.writeEntry( configKeyDefaultIdentity, (*it).identityName() ); } } #ifndef KMAIL_TESTING kernel->slotRequestConfigSync(); #else config->sync(); #endif } void IdentityManager::readConfig() { mIdentities.clear(); QStringList identities = groupList(); if ( identities.isEmpty() ) return; // nothing to be done... KConfigGroup general( kapp->config(), "General" ); QString defaultIdentity = general.readEntry( configKeyDefaultIdentity ); bool haveDefault = false; for ( QStringList::Iterator group = identities.begin() ; group != identities.end() ; ++group ) { KConfigGroup config( kapp->config(), *group ); mIdentities << KMIdentity(); mIdentities.last().readConfig( &config ); if ( !haveDefault && mIdentities.last().identityName() == defaultIdentity ) { haveDefault = true; mIdentities.last().setIsDefault( true ); } } if ( !haveDefault ) { kdWarning( 5006 ) << "IdentityManager: There was no default identity. Marking first one as default." << endl; mIdentities.first().setIsDefault( true ); } qHeapSort( mIdentities ); } QStringList IdentityManager::groupList() const { return kapp->config()->groupList().grep( QRegExp("^Identity #\\d+$") ); } IdentityManager::ConstIterator IdentityManager::begin() const { return mIdentities.begin(); } IdentityManager::ConstIterator IdentityManager::end() const { return mIdentities.end(); } IdentityManager::Iterator IdentityManager::begin() { return mShadowIdentities.begin(); } IdentityManager::Iterator IdentityManager::end() { return mShadowIdentities.end(); } const KMIdentity & IdentityManager::identityForName( const QString & name ) const { for ( ConstIterator it = begin() ; it != end() ; ++it ) if ( (*it).identityName() == name ) return (*it); return KMIdentity::null; } const KMIdentity & IdentityManager::identityForNameOrDefault( const QString & name ) const { const KMIdentity & ident = identityForName( name ); if ( ident.isNull() ) return defaultIdentity(); else return ident; } const KMIdentity & IdentityManager::identityForAddress( const QString & addressList ) const { for ( ConstIterator it = begin() ; it != end() ; ++it ) if ( addressList.find( (*it).emailAddr(), 0, false ) != -1 ) return (*it); return KMIdentity::null; } KMIdentity & IdentityManager::identityForName( const QString & name ) { for ( Iterator it = begin() ; it != end() ; ++it ) if ( (*it).identityName() == name ) return (*it); kdWarning( 5006 ) << "IdentityManager::identityForName() used as newFromScratch() replacement!" << "\n name == \"" << name << "\"" << endl; return newFromScratch( name ); } const KMIdentity & IdentityManager::defaultIdentity() const { for ( ConstIterator it = begin() ; it != end() ; ++it ) if ( (*it).isDefault() ) return (*it); (mIdentities.isEmpty() ? kdFatal( 5006 ) : kdWarning( 5006 ) ) << "IdentityManager: No default identity found!" << endl; return *begin(); } bool IdentityManager::setAsDefault( const QString & name ) { // First, check if the identity actually exists: QStringList names = shadowIdentities(); if ( names.find( name ) == names.end() ) return false; // Then, change the default as requested: for ( Iterator it = begin() ; it != end() ; ++it ) (*it).setIsDefault( (*it).identityName() == name ); // and re-sort: sort(); return true; } bool IdentityManager::removeIdentity( const QString & name ) { for ( Iterator it = begin() ; it != end() ; ++it ) if ( (*it).identityName() == name ) { bool removedWasDefault = (*it).isDefault(); mShadowIdentities.remove( it ); if ( removedWasDefault ) mShadowIdentities.first().setIsDefault( true ); return true; } return false; } KMIdentity & IdentityManager::newFromScratch( const QString & name ) { return newFromExisting( KMIdentity( name ) ); } KMIdentity & IdentityManager::newFromControlCenter( const QString & name ) { KEMailSettings es; es.setProfile( es.defaultProfileName() ); return newFromExisting( KMIdentity( name, es.getSetting( KEMailSettings::RealName ), es.getSetting( KEMailSettings::EmailAddress ), es.getSetting( KEMailSettings::Organization ), es.getSetting( KEMailSettings::ReplyToAddress ) ) ); } KMIdentity & IdentityManager::newFromExisting( const KMIdentity & other, const QString & name ) { mShadowIdentities << other; KMIdentity & result = mShadowIdentities.last(); result.setIsDefault( false ); // we don't want two default identities! if ( !name.isNull() ) result.setIdentityName( name ); return result; } void IdentityManager::createDefaultIdentity() { struct passwd * pw = getpwuid( getuid() ); QString fullName, emailAddr; if ( pw ) { // extract possible full name from /etc/passwd fullName = QString::fromLocal8Bit( pw->pw_gecos ); int i = fullName.find(','); if ( i > 0 ) fullName.truncate( i ); // extract login name from /etc/passwd and get hostname to form an // educated guess about the possible email address: char str[256]; if ( !gethostname( str, 255 ) ) // str need not be NUL-terminated if it has full length: str[255] = 0; else str[0] = 0; emailAddr = QString::fromLatin1("%1@%2") .arg( QString::fromLocal8Bit( pw->pw_name ) ) .arg( QString::fromLatin1( *str ? str : "localhost" ) ); } mShadowIdentities << KMIdentity( i18n("Default"), fullName, emailAddr ); mShadowIdentities.last().setIsDefault( true ); } #include "identitymanager.moc" <|endoftext|>
<commit_before>#pragma once #include <memory> #include <mpi.h> #include <Eigen/Dense> #include <Eigen/Sparse> #include <SmurffCpp/Utils/Distribution.h> #include <SmurffCpp/Priors/MacauPrior.hpp> #include <SmurffCpp/Utils/linop.h> #include <SmurffCpp/Model.h> namespace smurff { //why not use init method ? // Prior with side information template<class FType> class MPIMacauPrior : public MacauPrior<FType> { public: int world_rank; int world_size; private: int* rhs_for_rank = NULL; double* rec = NULL; int* sendcounts = NULL; int* displs = NULL; Eigen::MatrixXd Ft_y; public: MPIMacauPrior(std::shared_ptr<BaseSession> session, int mode) : MacauPrior<FType>(session, mode) { MPI_Comm_size(MPI_COMM_WORLD, &world_size); MPI_Comm_rank(MPI_COMM_WORLD, &world_rank); } virtual ~MPIMacauPrior() {} void init() override { MacauPrior<FType>::init(); rhs_for_rank = new int[world_size]; split_work_mpi(this->num_latent(), world_size, rhs_for_rank); sendcounts = new int[world_size]; displs = new int[world_size]; int sum = 0; for (int n = 0; n < world_size; n++) { sendcounts[n] = rhs_for_rank[n] * this->Features->cols(); displs[n] = sum; sum += sendcounts[n]; } rec = new double[sendcounts[world_rank]]; } //TODO: missing implementation std::ostream &info(std::ostream &os, std::string indent) override { if (world_rank == 0) { MacauPrior<FType>::info(os, indent); os << indent << " MPI version with " << world_size << " ranks\n"; } return os; } void sample_beta() override { const int num_latent = this->beta.rows(); const int num_feat = this->beta.cols(); if (world_rank == 0) { this->compute_Ft_y_omp(this->Ft_y); this->Ft_y.transposeInPlace(); } MPI_Bcast(& this->lambda_beta, 1, MPI_DOUBLE, 0, MPI_COMM_WORLD); MPI_Bcast(& this->tol, 1, MPI_DOUBLE, 0, MPI_COMM_WORLD); // sending Ft_y MPI_Scatterv(this->Ft_y.data(), sendcounts, displs, MPI_DOUBLE, rec, sendcounts[world_rank], MPI_DOUBLE, 0, MPI_COMM_WORLD); int nrhs = rhs_for_rank[world_rank]; Eigen::MatrixXd RHS(nrhs, num_feat), result(nrhs, num_feat); #pragma omp parallel for schedule(static) for (int f = 0; f < num_feat; f++) { for (int d = 0; d < nrhs; d++) { RHS(d, f) = rec[f + d * num_feat]; } } // solving smurff::linop::solve_blockcg(result, *this->Features, this->lambda_beta, RHS, this->tol, 32, 8); result.transposeInPlace(); MPI_Gatherv(result.data(), nrhs*num_feat, MPI_DOUBLE, this->Ft_y.data(), sendcounts, displs, MPI_DOUBLE, 0, MPI_COMM_WORLD); if (world_rank == 0) { //this->beta = Ft_y.transpose(); #pragma omp parallel for schedule(static) for (int f = 0; f < num_feat; f++) { for (int d = 0; d < num_latent; d++) { this->beta(d, f) = this->Ft_y(f, d); } } } } bool run_slave() override { sample_beta(); return true; } int rhs() const { return rhs_for_rank[world_rank]; } void split_work_mpi(int num_latent, int num_nodes, int* work) { double avg_work = num_latent / (double) num_nodes; int work_unit; if (2 <= avg_work) work_unit = 2; else work_unit = 1; int min_work = work_unit * (int)floor(avg_work / work_unit); int work_left = num_latent; for (int i = 0; i < num_nodes; i++) { work[i] = min_work; work_left -= min_work; } int i = 0; while (work_left > 0) { int take = std::min(work_left, work_unit); work[i] += take; work_left -= take; i = (i + 1) % num_nodes; } } }; } <commit_msg>rename lambda_beta to beta_precision according to #3 in MPIMacauPrior<commit_after>#pragma once #include <memory> #include <mpi.h> #include <Eigen/Dense> #include <Eigen/Sparse> #include <SmurffCpp/Utils/Distribution.h> #include <SmurffCpp/Priors/MacauPrior.hpp> #include <SmurffCpp/Utils/linop.h> #include <SmurffCpp/Model.h> namespace smurff { //why not use init method ? // Prior with side information template<class FType> class MPIMacauPrior : public MacauPrior<FType> { public: int world_rank; int world_size; private: int* rhs_for_rank = NULL; double* rec = NULL; int* sendcounts = NULL; int* displs = NULL; Eigen::MatrixXd Ft_y; public: MPIMacauPrior(std::shared_ptr<BaseSession> session, int mode) : MacauPrior<FType>(session, mode) { MPI_Comm_size(MPI_COMM_WORLD, &world_size); MPI_Comm_rank(MPI_COMM_WORLD, &world_rank); } virtual ~MPIMacauPrior() {} void init() override { MacauPrior<FType>::init(); rhs_for_rank = new int[world_size]; split_work_mpi(this->num_latent(), world_size, rhs_for_rank); sendcounts = new int[world_size]; displs = new int[world_size]; int sum = 0; for (int n = 0; n < world_size; n++) { sendcounts[n] = rhs_for_rank[n] * this->Features->cols(); displs[n] = sum; sum += sendcounts[n]; } rec = new double[sendcounts[world_rank]]; } //TODO: missing implementation std::ostream &info(std::ostream &os, std::string indent) override { if (world_rank == 0) { MacauPrior<FType>::info(os, indent); os << indent << " MPI version with " << world_size << " ranks\n"; } return os; } void sample_beta() override { const int num_latent = this->beta.rows(); const int num_feat = this->beta.cols(); if (world_rank == 0) { this->compute_Ft_y_omp(this->Ft_y); this->Ft_y.transposeInPlace(); } MPI_Bcast(& this->beta_precision, 1, MPI_DOUBLE, 0, MPI_COMM_WORLD); MPI_Bcast(& this->tol, 1, MPI_DOUBLE, 0, MPI_COMM_WORLD); // sending Ft_y MPI_Scatterv(this->Ft_y.data(), sendcounts, displs, MPI_DOUBLE, rec, sendcounts[world_rank], MPI_DOUBLE, 0, MPI_COMM_WORLD); int nrhs = rhs_for_rank[world_rank]; Eigen::MatrixXd RHS(nrhs, num_feat), result(nrhs, num_feat); #pragma omp parallel for schedule(static) for (int f = 0; f < num_feat; f++) { for (int d = 0; d < nrhs; d++) { RHS(d, f) = rec[f + d * num_feat]; } } // solving smurff::linop::solve_blockcg(result, *this->Features, this->beta_precision, RHS, this->tol, 32, 8); result.transposeInPlace(); MPI_Gatherv(result.data(), nrhs*num_feat, MPI_DOUBLE, this->Ft_y.data(), sendcounts, displs, MPI_DOUBLE, 0, MPI_COMM_WORLD); if (world_rank == 0) { //this->beta = Ft_y.transpose(); #pragma omp parallel for schedule(static) for (int f = 0; f < num_feat; f++) { for (int d = 0; d < num_latent; d++) { this->beta(d, f) = this->Ft_y(f, d); } } } } bool run_slave() override { sample_beta(); return true; } int rhs() const { return rhs_for_rank[world_rank]; } void split_work_mpi(int num_latent, int num_nodes, int* work) { double avg_work = num_latent / (double) num_nodes; int work_unit; if (2 <= avg_work) work_unit = 2; else work_unit = 1; int min_work = work_unit * (int)floor(avg_work / work_unit); int work_left = num_latent; for (int i = 0; i < num_nodes; i++) { work[i] = min_work; work_left -= min_work; } int i = 0; while (work_left > 0) { int take = std::min(work_left, work_unit); work[i] += take; work_left -= take; i = (i + 1) % num_nodes; } } }; } <|endoftext|>
<commit_before>/* CSVInputDataItem.C * * Copyright (C) 2009 Marcel Schumann * * This file is part of QuEasy -- A Toolbox for Automated QSAR Model * Construction and Validation. * QuEasy is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or (at * your option) any later version. * * QuEasy is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see <http://www.gnu.org/licenses/>. */ #include <CSVInputDataItem.h> #include <mainWindow.h> #include <BALL/QSAR/exception.h> #include <BALL/VIEW/KERNEL/iconLoader.h> #include <exception.h> #include <inputDataDialog.h> #include <QtGui/QDialog> #include <QtGui/QDrag> #include <QtCore/QMimeData> #include <QtGui/QApplication> #include <QtGui/QMessageBox> using namespace BALL::QSAR; namespace BALL { namespace VIEW { CSVInputDataItem::CSVInputDataItem(QString filename, DataItemView* view): InputDataItem(filename, view) { setPixmap(findPixmap("csv_icon")); QStringList list = filename_.split("/"); setName(list[list.size()-1]); append_ = 0; data_ = new QSARData(); } CSVInputDataItem::CSVInputDataItem(QSARData* data, DataItemView* view) { view_ = view; append_ = true; setPixmap(findPixmap("csv_icon")); data_ = data; } CSVInputDataItem::~CSVInputDataItem() { if (view_ && view_->name == "view") { //if the item was connected to others, delete it from its respective pipeline if (!removeDisconnectedItem()) { removeFromPipeline(); } } } CSVInputDataItem::CSVInputDataItem(CSVInputDataItem& item): InputDataItem(filename_, center_data_, center_y_ ,item.view_) { no_y_ = item. no_y_; x_labels_ = item.x_labels_; y_labels_ = item.y_labels_; append_ = item.append_; } void CSVInputDataItem::setSeperator(string sep) { if(sep=="tabulator") {sep_=" ";} else sep_=sep; } bool CSVInputDataItem::execute() { if(done_) return 0; // do nothing twice... if(append_) appendData(); else readData(); return 1; } void CSVInputDataItem::readData() { if(done_) return; // do nothing twice... string st = filename_.toStdString(); data_->readCSVFile(st.c_str(), no_y_, x_labels_, y_labels_, sep_.c_str(), 0, nonnumeric_class_names_); if (center_data_) { data_->centerData(center_y_); } done_ = 1; } void CSVInputDataItem::appendData() { if(done_) return; // do nothing twice.. string st = filename_.toStdString(); data_->readCSVFile(st.c_str(), no_y_, x_labels_, y_labels_, sep_.c_str(), 1, nonnumeric_class_names_); if (center_data_) { data_->centerData(center_y_); } done_ = 1; } void CSVInputDataItem::setXLabelFlag(bool x) { x_labels_ = x; } void CSVInputDataItem::setYLabelFlag(bool y) { y_labels_ = y; } void CSVInputDataItem::setNumOfActivities(int num) { no_y_ = num; } bool CSVInputDataItem::checkForDiscreteY() { if(checked_for_discrete_y_) return discrete_y_; try { if(done_) // if data has already been read, check within data-structure { discrete_y_=data_->checkforDiscreteY(); } else // if data has not been read, check within file { //discrete_y_=data_->checkforDiscreteY(filename_.toStdString().c_str(), activity_values_); return true; } } catch(BALL::Exception::GeneralException e) { // e.g. input file has not been found QMessageBox::critical(view_,e.getName(),e.getMessage()); return 0; } checked_for_discrete_y_ = 1; return discrete_y_; } void CSVInputDataItem::contextMenuEvent(QGraphicsSceneContextMenuEvent* /*event*/) { InputDataDialog inputDataDialog(this); inputDataDialog.exec(); } void CSVInputDataItem::addToPipeline() { view_->data_scene->main_window->csv_input_pipeline_.insert(this); view_->data_scene->main_window->all_items_pipeline_.insert(this); } void CSVInputDataItem::removeFromPipeline() { view_->data_scene->main_window->csv_input_pipeline_.erase(this); view_->data_scene->main_window->all_items_pipeline_.erase(this); } void CSVInputDataItem::replaceItem(InputDataItem* old_item) { transferEdges(old_item); // steal the old item's edges // put the new item into the the pipeline at the same position CSVInputDataItem* old_csv = dynamic_cast<CSVInputDataItem*>(old_item); SDFInputDataItem* old_sdf = dynamic_cast<SDFInputDataItem*>(old_item); if(old_csv) { Pipeline<CSVInputDataItem*>::iterator csv_it=view_->data_scene->main_window->csv_input_pipeline_.find(old_csv); if(csv_it!=view_->data_scene->main_window->csv_input_pipeline_.end()) { view_->data_scene->main_window->csv_input_pipeline_.insert(csv_it,this); view_->data_scene->main_window->csv_input_pipeline_.erase(csv_it); } else view_->data_scene->main_window->csv_input_pipeline_.insert(this); } else if(old_sdf) { // delete all features that were read from CSV-files appended to the old SDF-item for(list<CSVInputDataItem*>::iterator csv_it=old_sdf->getConnectedCSVItems()->begin(); csv_it!=old_sdf->getConnectedCSVItems()->end(); csv_it++) { delete *csv_it; } view_->data_scene->main_window->csv_input_pipeline_.insert(this); } else view_->data_scene->main_window->csv_input_pipeline_.insert(this); Pipeline<DataItem*>::iterator it = view_->data_scene->main_window->all_items_pipeline_.find(old_item); if(it!=view_->data_scene->main_window->all_items_pipeline_.end()) { view_->data_scene->main_window->all_items_pipeline_.insert(it,this); } else { view_->data_scene->main_window->all_items_pipeline_.insert(this); } // kill the old item delete old_item; // finially, make sure that the entire pipeline created by use of this input is reset change(); } } } <commit_msg>Clarified licence<commit_after>#include <CSVInputDataItem.h> #include <mainWindow.h> #include <BALL/QSAR/exception.h> #include <BALL/VIEW/KERNEL/iconLoader.h> #include <exception.h> #include <inputDataDialog.h> #include <QtGui/QDialog> #include <QtGui/QDrag> #include <QtCore/QMimeData> #include <QtGui/QApplication> #include <QtGui/QMessageBox> using namespace BALL::QSAR; namespace BALL { namespace VIEW { CSVInputDataItem::CSVInputDataItem(QString filename, DataItemView* view): InputDataItem(filename, view) { setPixmap(findPixmap("csv_icon")); QStringList list = filename_.split("/"); setName(list[list.size()-1]); append_ = 0; data_ = new QSARData(); } CSVInputDataItem::CSVInputDataItem(QSARData* data, DataItemView* view) { view_ = view; append_ = true; setPixmap(findPixmap("csv_icon")); data_ = data; } CSVInputDataItem::~CSVInputDataItem() { if (view_ && view_->name == "view") { //if the item was connected to others, delete it from its respective pipeline if (!removeDisconnectedItem()) { removeFromPipeline(); } } } CSVInputDataItem::CSVInputDataItem(CSVInputDataItem& item): InputDataItem(filename_, center_data_, center_y_ ,item.view_) { no_y_ = item. no_y_; x_labels_ = item.x_labels_; y_labels_ = item.y_labels_; append_ = item.append_; } void CSVInputDataItem::setSeperator(string sep) { if(sep=="tabulator") {sep_=" ";} else sep_=sep; } bool CSVInputDataItem::execute() { if(done_) return 0; // do nothing twice... if(append_) appendData(); else readData(); return 1; } void CSVInputDataItem::readData() { if(done_) return; // do nothing twice... string st = filename_.toStdString(); data_->readCSVFile(st.c_str(), no_y_, x_labels_, y_labels_, sep_.c_str(), 0, nonnumeric_class_names_); if (center_data_) { data_->centerData(center_y_); } done_ = 1; } void CSVInputDataItem::appendData() { if(done_) return; // do nothing twice.. string st = filename_.toStdString(); data_->readCSVFile(st.c_str(), no_y_, x_labels_, y_labels_, sep_.c_str(), 1, nonnumeric_class_names_); if (center_data_) { data_->centerData(center_y_); } done_ = 1; } void CSVInputDataItem::setXLabelFlag(bool x) { x_labels_ = x; } void CSVInputDataItem::setYLabelFlag(bool y) { y_labels_ = y; } void CSVInputDataItem::setNumOfActivities(int num) { no_y_ = num; } bool CSVInputDataItem::checkForDiscreteY() { if(checked_for_discrete_y_) return discrete_y_; try { if(done_) // if data has already been read, check within data-structure { discrete_y_=data_->checkforDiscreteY(); } else // if data has not been read, check within file { //discrete_y_=data_->checkforDiscreteY(filename_.toStdString().c_str(), activity_values_); return true; } } catch(BALL::Exception::GeneralException e) { // e.g. input file has not been found QMessageBox::critical(view_,e.getName(),e.getMessage()); return 0; } checked_for_discrete_y_ = 1; return discrete_y_; } void CSVInputDataItem::contextMenuEvent(QGraphicsSceneContextMenuEvent* /*event*/) { InputDataDialog inputDataDialog(this); inputDataDialog.exec(); } void CSVInputDataItem::addToPipeline() { view_->data_scene->main_window->csv_input_pipeline_.insert(this); view_->data_scene->main_window->all_items_pipeline_.insert(this); } void CSVInputDataItem::removeFromPipeline() { view_->data_scene->main_window->csv_input_pipeline_.erase(this); view_->data_scene->main_window->all_items_pipeline_.erase(this); } void CSVInputDataItem::replaceItem(InputDataItem* old_item) { transferEdges(old_item); // steal the old item's edges // put the new item into the the pipeline at the same position CSVInputDataItem* old_csv = dynamic_cast<CSVInputDataItem*>(old_item); SDFInputDataItem* old_sdf = dynamic_cast<SDFInputDataItem*>(old_item); if(old_csv) { Pipeline<CSVInputDataItem*>::iterator csv_it=view_->data_scene->main_window->csv_input_pipeline_.find(old_csv); if(csv_it!=view_->data_scene->main_window->csv_input_pipeline_.end()) { view_->data_scene->main_window->csv_input_pipeline_.insert(csv_it,this); view_->data_scene->main_window->csv_input_pipeline_.erase(csv_it); } else view_->data_scene->main_window->csv_input_pipeline_.insert(this); } else if(old_sdf) { // delete all features that were read from CSV-files appended to the old SDF-item for(list<CSVInputDataItem*>::iterator csv_it=old_sdf->getConnectedCSVItems()->begin(); csv_it!=old_sdf->getConnectedCSVItems()->end(); csv_it++) { delete *csv_it; } view_->data_scene->main_window->csv_input_pipeline_.insert(this); } else view_->data_scene->main_window->csv_input_pipeline_.insert(this); Pipeline<DataItem*>::iterator it = view_->data_scene->main_window->all_items_pipeline_.find(old_item); if(it!=view_->data_scene->main_window->all_items_pipeline_.end()) { view_->data_scene->main_window->all_items_pipeline_.insert(it,this); } else { view_->data_scene->main_window->all_items_pipeline_.insert(this); } // kill the old item delete old_item; // finially, make sure that the entire pipeline created by use of this input is reset change(); } } } <|endoftext|>
<commit_before>/* BEGIN_COMMON_COPYRIGHT_HEADER * (c)LGPL2+ * * Razor - a lightweight, Qt based, desktop toolset * http://razor-qt.org * * Copyright: 2010-2011 Razor team * Authors: * Alexander Sokoloff <sokoloff.a@gmail.com> * * This program or library is free software; you can redistribute it * and/or modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * You should have received a copy of the GNU Lesser General * Public License along with this library; if not, write to the * Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301 USA * * END_COMMON_COPYRIGHT_HEADER */ #include "xdgdirs.h" #include <stdlib.h> #include <QDir> #include <QStringBuilder> // for the % operator #include <QDebug> static const QString userDirectoryString[8] = { "Desktop", "Download", "Templates", "Publicshare", "Documents", "Music", "Pictures", "Videos" }; // Helper functions prototypes void fixBashShortcuts(QString &s); void removeEndigSlash(QString &s); QString xdgSingleDir(const QString &envVar, const QString &def, bool createDir); QStringList xdgDirList(const QString &envVar, const QString &postfix); /************************************************ Helper func. ************************************************/ void fixBashShortcuts(QString &s) { if (s.startsWith('~')) s = QString(getenv("HOME")) + (s).mid(1); } void removeEndingSlash(QString &s) { // We don't check for empty strings. Caller must check it. // Remove the ending slash, except for root dirs. if (s.length() > 1 && s.endsWith(QLatin1Char('/'))) s.chop(1); } /************************************************ Helper func. ************************************************/ QString xdgSingleDir(const QString &envVar, const QString &def, bool createDir) { #if QT_VERSION < QT_VERSION_CHECK(5,0,0) QString s(getenv(envVar.toAscii())); #else QString s(getenv(envVar.toLatin1())); #endif if (!s.isEmpty()) fixBashShortcuts(s); else s = QString("%1/%2").arg(getenv("HOME"), def); QDir d(s); if (createDir && !d.exists()) { if (!d.mkpath(".")) qWarning() << QString("Can't create %1 directory.").arg(d.absolutePath()); } return d.absolutePath(); } /************************************************ Helper func. ************************************************/ QStringList xdgDirList(const QString &envVar, const QString &postfix) { #if QT_VERSION < QT_VERSION_CHECK(5,0,0) QStringList dirs = QString(getenv(envVar.toAscii())).split(':', QString::SkipEmptyParts); #else QStringList dirs = QString(getenv(envVar.toLatin1())).split(':', QString::SkipEmptyParts); #endif QMutableStringListIterator i(dirs); while(i.hasNext()) { i.next(); QString s = i.value(); if (s.isEmpty()) { i.remove(); } else { fixBashShortcuts(s); removeEndingSlash(s); i.setValue(s % postfix); } } return dirs; } /************************************************ ************************************************/ QString XdgDirs::userDir(XdgDirs::UserDirectory dir) { // possible values for UserDirectory if (dir < 0 || dir > 7) return QString(); QString folderName = userDirectoryString[dir]; QString fallback; if (getenv("HOME") == NULL) return QString("/tmp"); else if (dir == XdgDirs::Desktop) fallback = QString("%1/%2").arg(getenv("HOME")).arg("Desktop"); else fallback = QString(getenv("HOME")); QString configDir(configHome()); QFile configFile(configDir + "/user-dirs.dirs"); if (!configFile.exists()) return fallback; if (!configFile.open(QIODevice::ReadOnly | QIODevice::Text)) return fallback; QString userDirVar("XDG_" + folderName.toUpper() + "_DIR"); QTextStream in(&configFile); QString line; while (!in.atEnd()) { line = in.readLine(); if (line.contains(userDirVar)) { configFile.close(); // get path between quotes line = line.section('"', 1, 1); line.replace("$HOME", "~"); fixBashShortcuts(line); return line; } } configFile.close(); return fallback; } /************************************************ ************************************************/ bool XdgDirs::setUserDir(XdgDirs::UserDirectory dir, const QString& value, bool createDir) { // possible values for UserDirectory if (dir < 0 || dir > 7) return false; if (!(value.startsWith("$HOME") || value.startsWith("~/") || value.startsWith(QString(getenv("HOME"))))) return false; QString folderName = userDirectoryString[dir]; QString configDir(configHome()); QFile configFile(configDir + "/user-dirs.dirs"); // create the file if doesn't exist and opens it if (!configFile.open(QIODevice::ReadWrite | QIODevice::Text)) return false; QTextStream stream(&configFile); QVector<QString> lines; QString line; bool foundVar = false; while (!stream.atEnd()) { line = stream.readLine(); if (line.indexOf("XDG_" + folderName.toUpper() + "_DIR") == 0) { foundVar = true; QString path = line.section('"', 1, 1); line.replace(path, value); lines.append(line); } else if (line.indexOf("XDG_") == 0) { lines.append(line); } } stream.reset(); configFile.resize(0); if (!foundVar) stream << QString("XDG_%1_DIR=\"%2\"\n").arg(folderName.toUpper()).arg(value); for (QVector<QString>::iterator i = lines.begin(); i != lines.end(); ++i) stream << *i << "\n"; configFile.close(); if (createDir) { QString path = QString(value).replace("$HOME", "~"); fixBashShortcuts(path); QDir().mkpath(path); } return true; } /************************************************ ************************************************/ QString XdgDirs::dataHome(bool createDir) { return xdgSingleDir("XDG_DATA_HOME", ".local/share", createDir); } /************************************************ ************************************************/ QString XdgDirs::configHome(bool createDir) { return xdgSingleDir("XDG_CONFIG_HOME", ".config", createDir); } /************************************************ ************************************************/ QStringList XdgDirs::dataDirs(const QString &postfix) { QStringList dirs = xdgDirList("XDG_DATA_DIRS", postfix); if (dirs.isEmpty()) { dirs << QLatin1String("/usr/local/share") % postfix; dirs << QLatin1String("/usr/share") % postfix; } return dirs; } /************************************************ ************************************************/ QStringList XdgDirs::configDirs(const QString &postfix) { QStringList dirs = xdgDirList("XDG_CONFIG_DIRS", postfix); if (dirs.isEmpty()) { dirs << QLatin1String("/etc/xdg") % postfix; } return dirs; } /************************************************ ************************************************/ QString XdgDirs::cacheHome(bool createDir) { return xdgSingleDir("XDG_CACHE_HOME", ".cache", createDir); } /************************************************ ************************************************/ QString XdgDirs::runtimeDir() { QString result(getenv("XDG_RUNTIME_DIR")); fixBashShortcuts(result); return result; } /************************************************ ************************************************/ QString XdgDirs::autostartHome(bool createDir) { QDir dir(QString("%1/autostart").arg(configHome(createDir))); if (createDir && !dir.exists()) { if (!dir.mkpath(".")) qWarning() << QString("Can't create %1 directory.").arg(dir.absolutePath()); } return dir.absolutePath(); } /************************************************ ************************************************/ QStringList XdgDirs::autostartDirs(const QString &postfix) { QStringList dirs; foreach(QString dir, configDirs()) dirs << QString("%1/autostart").arg(dir) + postfix; return dirs; } <commit_msg>Make sure returned directories don't have an trailing '/'<commit_after>/* BEGIN_COMMON_COPYRIGHT_HEADER * (c)LGPL2+ * * Razor - a lightweight, Qt based, desktop toolset * http://razor-qt.org * * Copyright: 2010-2011 Razor team * Authors: * Alexander Sokoloff <sokoloff.a@gmail.com> * * This program or library is free software; you can redistribute it * and/or modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * You should have received a copy of the GNU Lesser General * Public License along with this library; if not, write to the * Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301 USA * * END_COMMON_COPYRIGHT_HEADER */ #include "xdgdirs.h" #include <stdlib.h> #include <QDir> #include <QStringBuilder> // for the % operator #include <QDebug> static const QString userDirectoryString[8] = { "Desktop", "Download", "Templates", "Publicshare", "Documents", "Music", "Pictures", "Videos" }; // Helper functions prototypes void fixBashShortcuts(QString &s); void removeEndigSlash(QString &s); QString xdgSingleDir(const QString &envVar, const QString &def, bool createDir); QStringList xdgDirList(const QString &envVar, const QString &postfix); /************************************************ Helper func. ************************************************/ void fixBashShortcuts(QString &s) { if (s.startsWith('~')) s = QString(getenv("HOME")) + (s).mid(1); } void removeEndingSlash(QString &s) { // We don't check for empty strings. Caller must check it. // Remove the ending slash, except for root dirs. if (s.length() > 1 && s.endsWith(QLatin1Char('/'))) s.chop(1); } /************************************************ Helper func. ************************************************/ QString xdgSingleDir(const QString &envVar, const QString &def, bool createDir) { #if QT_VERSION < QT_VERSION_CHECK(5,0,0) QString s(getenv(envVar.toAscii())); #else QString s(getenv(envVar.toLatin1())); #endif if (!s.isEmpty()) fixBashShortcuts(s); else s = QString("%1/%2").arg(getenv("HOME"), def); QDir d(s); if (createDir && !d.exists()) { if (!d.mkpath(".")) qWarning() << QString("Can't create %1 directory.").arg(d.absolutePath()); } QString r = d.absolutePath(); removeEndingSlash(r); return r; } /************************************************ Helper func. ************************************************/ QStringList xdgDirList(const QString &envVar, const QString &postfix) { #if QT_VERSION < QT_VERSION_CHECK(5,0,0) QStringList dirs = QString(getenv(envVar.toAscii())).split(':', QString::SkipEmptyParts); #else QStringList dirs = QString(getenv(envVar.toLatin1())).split(':', QString::SkipEmptyParts); #endif QMutableStringListIterator i(dirs); while(i.hasNext()) { i.next(); QString s = i.value(); if (s.isEmpty()) { i.remove(); } else { fixBashShortcuts(s); removeEndingSlash(s); i.setValue(s % postfix); } } return dirs; } /************************************************ ************************************************/ QString XdgDirs::userDir(XdgDirs::UserDirectory dir) { // possible values for UserDirectory if (dir < 0 || dir > 7) return QString(); QString folderName = userDirectoryString[dir]; QString fallback; if (getenv("HOME") == NULL) return QString("/tmp"); else if (dir == XdgDirs::Desktop) fallback = QString("%1/%2").arg(getenv("HOME")).arg("Desktop"); else fallback = QString(getenv("HOME")); QString configDir(configHome()); QFile configFile(configDir + "/user-dirs.dirs"); if (!configFile.exists()) return fallback; if (!configFile.open(QIODevice::ReadOnly | QIODevice::Text)) return fallback; QString userDirVar("XDG_" + folderName.toUpper() + "_DIR"); QTextStream in(&configFile); QString line; while (!in.atEnd()) { line = in.readLine(); if (line.contains(userDirVar)) { configFile.close(); // get path between quotes line = line.section('"', 1, 1); line.replace("$HOME", "~"); fixBashShortcuts(line); return line; } } configFile.close(); return fallback; } /************************************************ ************************************************/ bool XdgDirs::setUserDir(XdgDirs::UserDirectory dir, const QString& value, bool createDir) { // possible values for UserDirectory if (dir < 0 || dir > 7) return false; if (!(value.startsWith("$HOME") || value.startsWith("~/") || value.startsWith(QString(getenv("HOME"))))) return false; QString folderName = userDirectoryString[dir]; QString configDir(configHome()); QFile configFile(configDir + "/user-dirs.dirs"); // create the file if doesn't exist and opens it if (!configFile.open(QIODevice::ReadWrite | QIODevice::Text)) return false; QTextStream stream(&configFile); QVector<QString> lines; QString line; bool foundVar = false; while (!stream.atEnd()) { line = stream.readLine(); if (line.indexOf("XDG_" + folderName.toUpper() + "_DIR") == 0) { foundVar = true; QString path = line.section('"', 1, 1); line.replace(path, value); lines.append(line); } else if (line.indexOf("XDG_") == 0) { lines.append(line); } } stream.reset(); configFile.resize(0); if (!foundVar) stream << QString("XDG_%1_DIR=\"%2\"\n").arg(folderName.toUpper()).arg(value); for (QVector<QString>::iterator i = lines.begin(); i != lines.end(); ++i) stream << *i << "\n"; configFile.close(); if (createDir) { QString path = QString(value).replace("$HOME", "~"); fixBashShortcuts(path); QDir().mkpath(path); } return true; } /************************************************ ************************************************/ QString XdgDirs::dataHome(bool createDir) { return xdgSingleDir("XDG_DATA_HOME", ".local/share", createDir); } /************************************************ ************************************************/ QString XdgDirs::configHome(bool createDir) { return xdgSingleDir("XDG_CONFIG_HOME", ".config", createDir); } /************************************************ ************************************************/ QStringList XdgDirs::dataDirs(const QString &postfix) { QStringList dirs = xdgDirList("XDG_DATA_DIRS", postfix); if (dirs.isEmpty()) { dirs << QLatin1String("/usr/local/share") % postfix; dirs << QLatin1String("/usr/share") % postfix; } return dirs; } /************************************************ ************************************************/ QStringList XdgDirs::configDirs(const QString &postfix) { QStringList dirs = xdgDirList("XDG_CONFIG_DIRS", postfix); if (dirs.isEmpty()) { dirs << QLatin1String("/etc/xdg") % postfix; } return dirs; } /************************************************ ************************************************/ QString XdgDirs::cacheHome(bool createDir) { return xdgSingleDir("XDG_CACHE_HOME", ".cache", createDir); } /************************************************ ************************************************/ QString XdgDirs::runtimeDir() { QString result(getenv("XDG_RUNTIME_DIR")); fixBashShortcuts(result); return result; } /************************************************ ************************************************/ QString XdgDirs::autostartHome(bool createDir) { QDir dir(QString("%1/autostart").arg(configHome(createDir))); if (createDir && !dir.exists()) { if (!dir.mkpath(".")) qWarning() << QString("Can't create %1 directory.").arg(dir.absolutePath()); } return dir.absolutePath(); } /************************************************ ************************************************/ QStringList XdgDirs::autostartDirs(const QString &postfix) { QStringList dirs; foreach(QString dir, configDirs()) dirs << QString("%1/autostart").arg(dir) + postfix; return dirs; } <|endoftext|>
<commit_before>/* Copyright 2014-2015 Juhani Numminen * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef PONG_PADDLE_HPP #define PONG_PADDLE_HPP #include <SFML/Graphics/RectangleShape.hpp> class Ball; class Paddle { public: static constexpr auto width = 20.f; static constexpr auto height = 100.f; static constexpr auto speed = 20.f; static constexpr auto slowSpeed = 5.f; Paddle(float x0 = 0.f, float y0 = 0.f, const sf::Color& color = sf::Color::White); float right() const { return x + width; } float bottom() const { return y + height; } sf::RectangleShape& getRectangleShape(); float x; float y; int points; private: sf::RectangleShape rectangleShape; }; bool intersects(const Paddle& paddle, const Ball& ball); #endif // PONG_PADDLE_HPP <commit_msg>Make the CPU paddle a bit faster<commit_after>/* Copyright 2014-2015 Juhani Numminen * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef PONG_PADDLE_HPP #define PONG_PADDLE_HPP #include <SFML/Graphics/RectangleShape.hpp> class Ball; class Paddle { public: static constexpr auto width = 20.f; static constexpr auto height = 100.f; static constexpr auto speed = 20.f; static constexpr auto slowSpeed = 8.f; Paddle(float x0 = 0.f, float y0 = 0.f, const sf::Color& color = sf::Color::White); float right() const { return x + width; } float bottom() const { return y + height; } sf::RectangleShape& getRectangleShape(); float x; float y; int points; private: sf::RectangleShape rectangleShape; }; bool intersects(const Paddle& paddle, const Ball& ball); #endif // PONG_PADDLE_HPP <|endoftext|>