blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
3
264
content_id
stringlengths
40
40
detected_licenses
listlengths
0
85
license_type
stringclasses
2 values
repo_name
stringlengths
5
140
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
905 values
visit_date
timestamp[us]date
2015-08-09 11:21:18
2023-09-06 10:45:07
revision_date
timestamp[us]date
1997-09-14 05:04:47
2023-09-17 19:19:19
committer_date
timestamp[us]date
1997-09-14 05:04:47
2023-09-06 06:22:19
github_id
int64
3.89k
681M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
22 values
gha_event_created_at
timestamp[us]date
2012-06-07 00:51:45
2023-09-14 21:58:39
gha_created_at
timestamp[us]date
2008-03-27 23:40:48
2023-08-21 23:17:38
gha_language
stringclasses
141 values
src_encoding
stringclasses
34 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
3
10.4M
extension
stringclasses
115 values
content
stringlengths
3
10.4M
authors
listlengths
1
1
author_id
stringlengths
0
158
8969221afbeab49fcd5a5088eb29e2159c166693
6e46cbf7daabffc79ff71b573c50dc30b834ecdf
/src/fault.cc
da6928bb432b647786beb4d79ec47e9281c407fa
[ "BSD-2-Clause" ]
permissive
Kuree/kratos
30355fabd126aa3ae2cb452e0d69038f659699af
8c95d3073db27fd0d2cbe58197d07ec091a028bf
refs/heads/master
2023-02-17T18:13:28.894505
2023-02-17T02:42:08
2023-02-17T02:42:08
190,965,157
53
11
BSD-2-Clause
2021-11-04T06:22:41
2019-06-09T04:47:38
C++
UTF-8
C++
false
false
25,345
cc
#include "fault.hh" #include <chrono> #include <fstream> #include <stack> #include "eval.hh" #include "except.hh" #include "fmt/format.h" #include "graph.hh" #include "stmt.hh" #include "util.hh" using fmt::format; namespace kratos { void SimulationRun::add_simulation_state(const std::map<std::string, int64_t> &values) { // need to parse the inputs and outputs states_.emplace_back(std::make_unique<Simulator>(top_)); auto *state = get_state(states_.size() - 1); for (auto const &[name, value] : values) { // we need to use dot notation to select from the hierarchy // notice these names do not contain the "top" name, e.g. TOP for verilator auto *var = select(name); if (!var) { throw UserException(::format("Unable to parse {0}", name)); } state->set(var, value, false); } } void SimulationRun::mark_wrong_value(const std::string &name) { if (states_.empty()) throw UserException("Simulation run is empty"); auto *v = select(name); auto *v_base = const_cast<Var *>(v->get_var_root_parent()); auto index = states_.size() - 1; wrong_value_[index].emplace(v_base); } void SimulationRun::add_simulation_coverage(const std::unordered_map<Stmt *, uint32_t> &coverage) { // for now we are not interested in stmt counts yet for (auto const &iter : coverage) { coverage_.emplace(iter.first); } } std::pair<Generator *, uint64_t> SimulationRun::select_gen(const std::vector<std::string> &tokens) { Generator *gen = top_; if (tokens[0] != gen->instance_name) return {nullptr, 1}; for (uint64_t index = 1; index < tokens.size(); index++) { auto const &name = tokens[index]; if (!gen->has_child_generator(name)) { return {gen, index}; } else { gen = gen->get_child_generator(name); } } return {gen, tokens.size()}; } Var *SimulationRun::select(const std::string &name) { auto tokens = string::get_tokens(name, "."); auto [gen, index] = select_gen(tokens); if (index >= tokens.size()) return nullptr; if (!gen) return nullptr; auto var_tokens = std::vector<std::string>(tokens.begin() + index, tokens.end()); // get var name, which has to be the first one auto const &var_name = var_tokens[0]; auto *var = gen->get_var(var_name).get(); if (!var) return nullptr; if (var->is_packed() && (var->size().size() > 1 || var->size()[0] > 1)) { throw InternalException("Packed struct not supported yet"); } // get index, if any std::vector<uint32_t> indices; for (uint64_t i = 1; i < var_tokens.size(); i++) { int v; try { v = std::stoi(var_tokens[i]); } catch (std::invalid_argument &) { return nullptr; } if (v < 0) throw UserException(::format("Unable to parse {0}", name)); // slice it var = &(*var)[v]; } return var; } Simulator *SimulationRun::get_state(uint32_t index) { if (index < states_.size()) { return states_[index].get(); } return nullptr; } FaultAnalyzer::FaultAnalyzer(kratos::Generator *generator) : generator_(generator) {} void FaultAnalyzer::add_simulation_run(const std::shared_ptr<SimulationRun> &run) { runs_.emplace_back(run); } template <typename T> T *cast(Stmt *stmt) { auto *r = dynamic_cast<T *>(stmt); if (!r) throw InternalException("Unable to cast stmt type"); return r; } void compute_hit_stmts(Simulator *state, std::unordered_set<Stmt *> &result, Stmt *stmt) { if (stmt->type() == StatementType::If) { auto *if_ = cast<IfStmt>(stmt); auto cond = if_->predicate(); auto val = state->get(cond.get()); if (val && *val) { compute_hit_stmts(state, result, if_->then_body().get()); } else { compute_hit_stmts(state, result, if_->else_body().get()); } } else if (stmt->type() == StatementType::Block) { auto *block = cast<StmtBlock>(stmt); // normal sequential block and combinational block always gets executed // as a result, we're only interested in the conditional statement block, i.e. scoped block if (block->block_type() == StatementBlockType::Scope) result.emplace(stmt); for (auto const &s : *block) { compute_hit_stmts(state, result, s.get()); } } else if (stmt->type() == StatementType::FunctionalCall) { auto *func = cast<FunctionCallStmt>(stmt); if (func->var()->func()->is_dpi() || func->var()->func()->is_builtin()) { // nothing } else { compute_hit_stmts(state, result, func->var()->func()); } } } std::unordered_set<Stmt *> FaultAnalyzer::compute_coverage(uint32_t index) { auto *run = runs_[index].get(); std::unordered_set<Stmt *> result; if (run->has_coverage()) { auto const &cov = run->coverage(); for (auto const &stmt : cov) result.emplace(stmt); } else { auto num_states = run->num_states(); for (uint64_t i = 0; i < num_states; i++) { auto *state = run->get_state(i); // given the state, we need to go through each generators GeneratorGraph g(generator_); auto generators = g.get_sorted_nodes(); for (auto const &gen : generators) { // need to calculate the sequential or combination block auto stmts = gen->get_all_stmts(); for (auto const &stmt : stmts) { compute_hit_stmts(state, result, stmt.get()); } } } } coverage_maps_.emplace(index, result); return result; } std::unordered_set<Stmt *> FaultAnalyzer::compute_fault_stmts_from_coverage() { // compute coverage for each run auto const num_runs_ = num_runs(); for (uint64_t i = 0; i < num_runs_; i++) { if (coverage_maps_.find(i) == coverage_maps_.end()) { compute_coverage(i); } } std::map<Stmt *, uint32_t> correct_stmt_count; std::map<Stmt *, uint32_t> wrong_stmt_count; for (auto const &[run_index, coverage] : coverage_maps_) { auto const &run = runs_[run_index]; bool has_wrong_value = run->has_wrong_value(); for (auto const &stmt : coverage) { if (has_wrong_value) { if (wrong_stmt_count.find(stmt) == wrong_stmt_count.end()) wrong_stmt_count[stmt] = 0; wrong_stmt_count[stmt] += 1; } else { if (correct_stmt_count.find(stmt) == correct_stmt_count.end()) correct_stmt_count[stmt] = 0; correct_stmt_count[stmt] += 1; } } } std::unordered_set<Stmt *> result; // compute the sum for (auto const &iter : wrong_stmt_count) { auto const &stmt = iter.first; if (correct_stmt_count.find(stmt) == correct_stmt_count.end()) result.emplace(stmt); } return result; } class XMLWriter { // code is adapted from // https://gist.github.com/sebclaeys/1227644/3761c33416d71c20efc300e78ea1dc36221185c5 public: XMLWriter(std::ostream &stream, const std::string &header) : stream_(stream) { stream_ << HEADER_; stream_ << header << std::endl; } XMLWriter &open_elt(const std::string &tag) { close_tag(); if (!elt_stack_.empty()) stream_ << std::endl; indent(); stream_ << "<" << tag; elt_stack_.emplace(tag); tag_open_ = true; new_line_ = false; return *this; } XMLWriter &close_elt() { close_tag(); auto elt = elt_stack_.top(); elt_stack_.pop(); if (new_line_) { stream_ << std::endl; indent(); } new_line_ = true; stream_ << "</" << elt << ">"; return *this; } XMLWriter &close_all() { while (!elt_stack_.empty()) close_elt(); return *this; } XMLWriter &attr(const std::string &key, const std::string &value) { stream_ << " " << key << "=\""; write_escape(value); stream_ << "\""; return *this; } template <class T> XMLWriter &attr(const std::string &key, T value) { return attr(key, ::format("{0}", value)); } XMLWriter &content(const std::string &var) { close_tag(); write_escape(var); return *this; } private: std::ostream &stream_; bool tag_open_ = false; bool new_line_ = true; const std::string HEADER_ = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"; const std::string INDENT_ = " "; std::stack<std::string> elt_stack_; inline void close_tag() { if (tag_open_) { stream_ << ">"; tag_open_ = false; } } inline void indent() { for (uint64_t i = 0; i < elt_stack_.size(); i++) { stream_ << INDENT_; } } // not interested in this coverage // LCOV_EXCL_START inline void write_escape(const std::string &str) { // not interested in coverage for this function for (auto const &c : str) switch (c) { case '&': stream_ << "&amp;"; break; case '<': stream_ << "&lt;"; break; case '>': stream_ << "&gt;"; break; case '\'': stream_ << "&apos;"; break; case '"': stream_ << "&quot;"; break; default: stream_ << c; break; } } // LCOV_EXCL_STOP }; class CoverageStatVisitor : public IRVisitor { public: void visit(AssignStmt *stmt) override { auto *parent = stmt->parent(); if (parent->ir_node_kind() == IRNodeKind::StmtKind) { auto *st = reinterpret_cast<Stmt *>(parent); // we are only interested in if (st->type() == StatementType::Block) { auto *st_ = cast<StmtBlock>(st); if (st_->block_type() == StatementBlockType::Scope) { // only add if it has coverage if (!stmt->fn_name_ln.empty()) stmts_.emplace(stmt); } } } } void visit(ScopedStmtBlock *stmt) override { if (!stmt->fn_name_ln.empty()) branches_.emplace(stmt); } [[nodiscard]] const std::unordered_set<IRNode *> &stmts() const { return stmts_; } [[nodiscard]] const std::unordered_set<IRNode *> &branches() const { return branches_; } private: std::unordered_set<IRNode *> stmts_; std::unordered_set<IRNode *> branches_; }; IRNode *has_parent(const std::unordered_set<IRNode *> &parents, IRNode *stmt) { IRNode *node = stmt->parent(); do { if (parents.find(node) != parents.end()) return node; node = node->parent(); } while (node); return nullptr; } // adapted from // https://www.rosettacode.org/wiki/Find_common_directory_path#C.2B.2B std::string longestPath(const std::vector<std::string> &dirs, char separator) { if (dirs.empty()) return ""; auto vsi = dirs.begin(); int max_characters_common = static_cast<int>(vsi->length()); std::string compare_string = *vsi; for (vsi = dirs.begin() + 1; vsi != dirs.end(); vsi++) { std::pair<std::string::const_iterator, std::string::const_iterator> p = std::mismatch(compare_string.begin(), compare_string.end(), vsi->begin()); if ((p.first - compare_string.begin()) < max_characters_common) max_characters_common = p.first - compare_string.begin(); } std::string::size_type found = compare_string.rfind(separator, max_characters_common); return compare_string.substr(0, found); } std::string get_filename_after_root(const std::string &root, const std::string &filename) { auto pos = filename.find(root) + root.size(); auto sep = fs::separator(); while (pos != std::string::npos && filename[pos] == sep) { pos++; } if (pos == std::string::npos) return filename; return filename.substr(pos); } void FaultAnalyzer::output_coverage_xml(const std::string &filename) { std::ofstream stream(filename, std::ofstream::trunc | std::ostream::out); output_coverage_xml(stream); } void FaultAnalyzer::output_coverage_xml(std::ostream &stream) { const std::string header = "<!DOCTYPE coverage SYSTEM " "'http://cobertura.sourceforge.net/xml/coverage-04.dtd'>"; XMLWriter w(stream, header); // need to compute all the stats double line_total; double covered_line; double branch_total; double covered_branch; CoverageStatVisitor visitor; visitor.visit_root(generator_); auto const &total_branches = visitor.branches(); branch_total = static_cast<double>(total_branches.size()); auto const &total_lines = visitor.stmts(); line_total = static_cast<double>(total_lines.size()); // compute the collapsed map std::unordered_map<IRNode *, uint32_t> branch_cover_count; for (auto const &iter : coverage_maps_) { auto const &coverage = iter.second; for (auto const &stmt : coverage) { if (branch_cover_count.find(stmt) == branch_cover_count.end()) branch_cover_count[stmt] = 0; branch_cover_count[stmt] += 1; } } // compute the actual coverage std::unordered_map<IRNode *, uint32_t> line_cover_count; for (auto *stmt : total_lines) { auto *parent = has_parent(total_branches, stmt); if (parent && branch_cover_count.find(parent) != branch_cover_count.end()) { auto count = branch_cover_count.at(parent); line_cover_count.emplace(stmt, count); } } covered_line = static_cast<double>(line_cover_count.size()); covered_branch = static_cast<double>(branch_cover_count.size()); // need to sort all the filename and lines std::map<std::string, std::map<uint32_t, IRNode *>> coverage; for (auto const &stmt : total_lines) { auto const &[fn, ln] = stmt->fn_name_ln.front(); coverage[fn][ln] = stmt; } for (auto const &stmt : total_branches) { auto const &[fn, ln] = stmt->fn_name_ln.front(); coverage[fn][ln] = stmt; } // find the root path // using the longest path std::vector<std::string> filenames; filenames.reserve(coverage.size()); for (auto const &iter : coverage) filenames.emplace_back(iter.first); auto root = longestPath(filenames, fs::separator()); // start to outputting the file coverage files auto now = std::chrono::system_clock::now(); w.open_elt("coverage") .attr("line-rate", line_total > 0 ? covered_line / line_total : 0.0) .attr("branch-rate", branch_total > 0 ? covered_branch / branch_total : 0.0) .attr("lines-covered", static_cast<uint32_t>(covered_line)) .attr("lines-valid", static_cast<uint32_t>(line_total)) .attr("branches-covered", static_cast<uint32_t>(covered_branch)) .attr("branches-valid", static_cast<uint32_t>(branch_total)) .attr("complexity", 0.0) .attr("timestamp", std::chrono::duration_cast<std::chrono::seconds>(now.time_since_epoch()).count()) .attr("version", ::format("kratos 0")); w.open_elt("sources").open_elt("source").content(root).close_elt().close_elt(); // all the source files // packages w.open_elt("packages"); w.open_elt("package"); w.open_elt("classes"); // FIXME: need to split path based to form the packages. for now only one package w.attr("line-rate", 1.0).attr("branch-rate", 1.0).attr("complexity", 1.0); for (auto const &[fn, stmts] : coverage) { // we need to group them by generator name std::map<std::string, std::map<uint32_t, IRNode *>> classes; for (auto const &[ln, stmt] : stmts) { auto *st = dynamic_cast<Stmt *>(stmt); if (!st) throw InternalException("Unable to cast stmt"); auto gen_name = st->generator_parent()->name; classes[gen_name].emplace(ln, stmt); } auto new_fn = get_filename_after_root(root, fn); for (auto const &[class_name, cov] : classes) { w.open_elt("class"); // TODO: add line rate and branch rate w.attr("name", class_name) .attr("filename", new_fn) .attr("line-rate", 1.0) .attr("branch-rate", 1.0) .attr("complexity", 1.0); // blank methods w.open_elt("methods").close_elt(); w.open_elt("lines"); for (auto const &[ln, stmt] : cov) { w.open_elt("line"); // TODO add branch w.attr("number", ln); uint32_t count = 0; if (line_cover_count.find(stmt) != line_cover_count.end()) { count = line_cover_count.at(stmt); } else if (branch_cover_count.find(stmt) != branch_cover_count.end()) { count = branch_cover_count.at(stmt); } w.attr("hits", count); w.attr("branch", "false"); w.close_elt(); } w.close_elt(); // lines w.close_elt(); // class } } w.close_all(); } class CollectScopeStmtVisitor : public IRVisitor { public: void visit(ScopedStmtBlock *stmt) override { add_stmt(stmt); } [[nodiscard]] const std::map<std::pair<std::string, uint32_t>, Stmt *> &stmt_map() const { return stmt_map_; } private: void add_stmt(Stmt *stmt) { auto *gen = stmt->generator_parent(); if (!gen->verilog_fn.empty()) { auto filename = fs::basename(gen->verilog_fn); stmt_map_.emplace(std::make_pair(filename, stmt->verilog_ln), stmt); } } std::map<std::pair<std::string, uint32_t>, Stmt *> stmt_map_; }; std::unordered_map<Stmt *, uint32_t> reverse_map_stmt( Generator *top, const std::set<std::tuple<std::string, uint32_t, uint32_t>> &hit_counts) { CollectScopeStmtVisitor visitor; visitor.visit_root(top); auto const &map = visitor.stmt_map(); std::unordered_map<Stmt *, uint32_t> stmts; for (auto const &[fn, ln, count] : hit_counts) { if (count == 0) continue; auto filename = fs::basename(fn); auto entry = std::make_pair(filename, ln); if (map.find(entry) != map.end()) { stmts.emplace(map.at(entry), count); } } return stmts; } std::unordered_map<Stmt *, uint32_t> parse_verilator_coverage(Generator *top, const std::string &filename) { if (!fs::exists(filename)) throw UserException(::format("{0} does not exist")); std::ifstream file(filename); std::set<std::tuple<std::string, uint32_t, uint32_t>> parse_result; for (std::string line; std::getline(file, line);) { if (line[0] != 'C') continue; // parse the line based on key value pair std::unordered_map<std::string, std::string> data; std::string key; std::string buffer; // a tiny FSM to decode // 0 -> nothing // 1 -> key // 2 -> value uint32_t state = 0; uint64_t index; for (index = 2; index < line.size(); index++) { auto c = line[index]; if (state == 0) { if (c == 1) { // this is key state = 1; } } else if (state == 1) { if (c == 2) { // key ends here key = buffer; buffer = ""; state = 2; } else { buffer += c; } } else { if (c == '\'' || c == 1) { // end of value if (key.empty()) throw InternalException("Failed to parse" + line); data.emplace(key, buffer); key = ""; buffer = ""; if (c == 1) state = 1; if (c == '\'') break; } else { buffer += c; } } } // parse the page type if (data.find("page") == data.end()) throw UserException("Unable to parse " + line); auto page_type = data.at("page"); const std::string line_cov_prefix = "v_line"; if (page_type.substr(0, line_cov_prefix.size()) != line_cov_prefix) continue; if (index >= line.size() - 1) throw UserException("Unable to parse " + line); // need to parse the count std::string count_s = line.substr(index + 1); string::trim(count_s); auto count = static_cast<uint64_t>(std::stol(count_s)); // check on the filename and line number if (data.find("f") == data.end() || data.find("l") == data.end()) throw UserException("Unable to parse" + line); auto const &fn = data.at("f"); auto const ln = static_cast<uint32_t>(std::stoi(data.at("l"))); parse_result.emplace(std::make_tuple(fn, ln, count)); } auto reverse_map = reverse_map_stmt(top, parse_result); return reverse_map; } std::vector<std::string> get_icc_tokens(std::string str) { std::vector<std::string> result; // trim the input and output string::trim(str); std::string buf; for (uint64_t pos = 0; pos < str.size(); pos++) { if (str[pos] == ' ') { if (pos < str.size() - 1) { if (str[pos + 1] == ' ') { // end of token string::trim(buf); if (!buf.empty()) result.emplace_back(buf); buf = ""; continue; } } } buf += str[pos]; // maybe more efficient way to do this? } if (!buf.empty()) result.emplace_back(buf); return result; } std::unordered_map<Stmt *, uint32_t> parse_icc_coverage(Generator *top, const std::string &filename) { std::set<std::tuple<std::string, uint32_t, uint32_t>> parse_result; if (!fs::exists(filename)) throw UserException(::format("{0} does not exist")); std::ifstream file(filename); // state 0: nothing // state 1: searching for block header // state 2: reading block coverage uint32_t state = 0; uint32_t line_count = 0; std::string current_filename; for (std::string line; std::getline(file, line); line_count++) { // scan file by file string::trim(line); if (line[0] == '-') continue; // skip the line section if (state == 0) { const std::string filename_tag = "File name:"; auto pos = line.find(filename_tag); if (pos != std::string::npos) { state = 1; // extract out filename current_filename = line.substr(pos + filename_tag.size()); string::trim(current_filename); } } else if (state == 1) { const std::string count_tag = "Count Block"; auto pos = line.find(count_tag); if (pos != std::string::npos) { state = 2; } } else { if (line.empty()) { // reset everything current_filename = ""; state = 0; continue; } auto tokens = get_icc_tokens(line); if (tokens.size() < 6) throw UserException(::format("Unable to parse line {0} at file {1}:{2}", line, filename, line_count)); auto count_s = tokens[0]; auto line_num = tokens[2]; // only takes the blocks if we are interested // since only the control statements determine what to run // we need to see if any of the branch has taken auto kind = tokens[3]; const static std::unordered_set<std::string> allowed_branch_kind = { "true part of", "false part of", "a case item of"}; if (allowed_branch_kind.find(kind) == allowed_branch_kind.end()) { // skip since it is just a normal code block continue; } auto count = static_cast<uint32_t>(std::stoi(count_s)); auto fn = static_cast<uint32_t>(std::stoi(line_num)); if (current_filename.empty()) throw UserException( ::format("Filename is empty, Unable to parse line {0} at file {1}:{2}", line, filename, line_count)); parse_result.emplace(std::make_tuple(current_filename, fn, count)); } } auto reverse_map = reverse_map_stmt(top, parse_result); return reverse_map; } } // namespace kratos
[ "keyi@stanford.edu" ]
keyi@stanford.edu
44b8d98312a8f22bfb3a7118f02036ecaa4bad40
6b660cb96baa003de9e18e332b048c0f1fa67ab9
/External/SDK/ALK_ThirdPerson_Female_Large_classes.h
4d8226968da33e89f54ec6d8b723aa7c2e9452a3
[]
no_license
zanzo420/zSoT-SDK
1edbff62b3e12695ecf3969537a6d2631a0ff36f
5e581eb0400061f6e5f93b3affd95001f62d4f7c
refs/heads/main
2022-07-30T03:35:51.225374
2021-07-07T01:07:20
2021-07-07T01:07:20
383,634,601
1
0
null
null
null
null
UTF-8
C++
false
false
831
h
#pragma once // Name: SoT, Version: 2.2.0.2 /*!!DEFINE!!*/ /*!!HELPER_DEF!!*/ /*!!HELPER_INC!!*/ #ifdef _MSC_VER #pragma pack(push, 0x01) #endif namespace CG { //--------------------------------------------------------------------------- // Classes //--------------------------------------------------------------------------- // BlueprintGeneratedClass ALK_ThirdPerson_Female_Large.ALK_ThirdPerson_Female_Large_C // 0x0000 (FullSize[0x0028] - InheritedSize[0x0028]) class UALK_ThirdPerson_Female_Large_C : public UAnimationDataStoreId { public: static UClass* StaticClass() { static auto ptr = UObject::FindClass("BlueprintGeneratedClass ALK_ThirdPerson_Female_Large.ALK_ThirdPerson_Female_Large_C"); return ptr; } void AfterRead(); void BeforeDelete(); }; } #ifdef _MSC_VER #pragma pack(pop) #endif
[ "Massimo.linker@gmail.com" ]
Massimo.linker@gmail.com
0390e394fbcdd6e48849c7360607812b2415ab79
1bc6e1d1d884d0c06196d7fc9213b544188735ac
/Importer/main.cpp
aaa266e041d84d44b72371700d808a7b1277efea
[]
no_license
zhorro/openFlashCards
1f58119a151cb1a9f3db8ca25332fe67b6d40e91
16ff255cb24dae48fd319c008a018968d895f028
refs/heads/master
2020-05-03T12:56:36.911847
2013-01-26T13:04:15
2013-01-26T13:04:15
null
0
0
null
null
null
null
UTF-8
C++
false
false
185
cpp
#include <QApplication> #include "importerwindow.h" int main(int argc, char *argv[]) { QApplication a(argc, argv); importerWindow w; w.show(); return a.exec(); }
[ "smaksim@gmail.com" ]
smaksim@gmail.com
bf367d5c821390c1f7350899126d36fe3ca7a166
5450741881fd6f6b58e91fe73d3094bc10344f1d
/tests/codility/NumberSolitaireTests.cpp
b2e6ea8a05d200cadeb08d12e339de79669e2b45
[ "MIT" ]
permissive
antaljanosbenjamin/miscellaneous
32d5cd31f55a04fe463081f810026ace15474f15
ac5d3ecc0faa7443774915db5f7bc274dfd7e827
refs/heads/master
2022-07-18T14:58:44.776502
2022-07-11T19:42:52
2022-07-11T19:42:52
97,752,553
3
0
MIT
2022-07-11T19:42:53
2017-07-19T19:14:41
C++
UTF-8
C++
false
false
322
cpp
#include <catch2/catch.hpp> #include "NumberSolitaire.hpp" TEST_CASE("General") { std::vector<int> A{1, -2, 0, 9, -1, -2}; // NOLINT(readability-magic-numbers) constexpr auto expectedMaxResult = 8; const auto calculatedMaxResult = NumberSolitaire::solution(A); CHECK(calculatedMaxResult == expectedMaxResult); }
[ "antal.janos.benjamin@gmail.com" ]
antal.janos.benjamin@gmail.com
10e6db4c48adac8c342ab39f36c7025716b6eaa7
96f7b90e9de03b71a4ce9a869202c9deabf2775d
/src/hexapodcontrol/src/my_hexapod_controller.cpp
2550c09ac2ee70dde2b195423a41e71de7f33707
[]
no_license
V5Kingsley/hexapod_service_ws
d07d0c3633464123bfe30380ebac51b929088ca6
15670f838e3c2f7567b827118ca3ab3f3010937e
refs/heads/master
2020-03-22T21:04:19.581303
2019-10-30T08:21:41
2019-10-30T08:21:41
140,654,207
1
0
null
null
null
null
UTF-8
C++
false
false
787
cpp
#include <ros/ros.h> #include "gait.h" #include "ik.h" #include "control.h" int main(int argc, char **argv) { ros::init(argc, argv, "my_hexapod_controller"); Control control("hexapod_sm_service", true); ros::AsyncSpinner spinner(3); // Using 3 threads spinner.start(); ros::Rate loop_rate(control.MASTER_LOOP_RATE); ros::Time last_time, current_time; //初始化机器人位姿 while (ros::ok()) { // last_time = ros::Time::now(); control.feedDrives(control.gait.cycle_period_, control.gait.is_travelling_, control.gait.cycle_leg_number_, control.gait.hexapod_stop_flag); loop_rate.sleep(); // current_time = ros::Time::now(); // double d_sec = current_time.toSec() - last_time.toSec(); // ROS_INFO("loop time: %f", d_sec); } return 0; }
[ "928199527@qq.com" ]
928199527@qq.com
bcbbb561c96e1fa5cf79325455d8c2fe655ea035
d862e7e02b7c4a8c4e2ef8713a29bfdde9e58106
/src/sim_aio.cpp
90e6e5aacacf1803567bb6e788be4c5fb0463d76
[]
no_license
GregBowyer/turbovax
84cfb3dc2efe81f809bc57b4bb59189c82ceaf3d
6bfbc3a37440ae9ab7f2d786e5a24a97db7a554d
refs/heads/master
2021-01-15T17:41:02.811469
2016-07-04T02:14:00
2016-07-04T02:14:00
62,477,398
8
1
null
null
null
null
UTF-8
C++
false
false
12,046
cpp
/* * sim_aio.cpp: support for asynchrnonous IO */ #include "sim_defs.h" /****************************************************************************************** * aio_context helper class for async disk and tape IO, * * both disk_context and tape_context derive from aio_context * ******************************************************************************************/ aio_context::aio_context(UNIT* uptr) { dptr = NULL; dbit = 0; this->uptr = uptr; asynch_io = FALSE; io_thread = SMP_THREAD_NULL; io_thread_created = FALSE; io_event = NULL; io_flush_ack = NULL; io_do_flush = FALSE; } aio_context::~aio_context() { asynch_uninit(); } void aio_context::asynch_init(smp_thread_routine_t start_routine, void* arg) { if (io_event == NULL) io_event = smp_simple_semaphore::create(0); else io_event->clear(); if (io_flush_ack == NULL) io_flush_ack = smp_event::create(); if (! io_thread_created) { smp_create_thread(start_routine, arg, &io_thread); io_thread_created = TRUE; } } /* * asynch_uninit will be called either via sim_disk_unload by a VCPU thread holding uptr->lock * (perhaps sometimes console thread holding uptr->lock if manually writing to UQSSP registers) * or by console thread doing detach when all VCPU threads are paused. * In either case mutual exclusion between callers is observed. */ void aio_context::asynch_uninit() { if (io_thread_created) { asynch_io = FALSE; io_event_signal(); smp_wait_thread(io_thread); io_thread_created = FALSE; } asynch_io = FALSE; delete io_event; io_event = NULL; delete io_flush_ack; io_flush_ack = NULL; } void aio_context::thread_loop() { for (;;) { io_event->wait(); volatile t_bool was_asynch_io = asynch_io; volatile t_bool was_flush = io_do_flush; io_do_flush = FALSE; if (has_request()) { /* after seeing operation code set, issue rmb to ensure request paramaters are locally visible on this CPU */ smp_rmb(); perform_request(); } if (was_flush) { perform_flush(); io_flush_ack->set(); } if (! was_asynch_io) break; } } /* * flush() will be normally called either by a VCPU thread holding uptr->lock * or by console thread doing io_flush when all VCPU threads are paused * or by console thread manually writing to UQSSP registers when all VCPU threads are paused * (and also holding uptr->lock, in addition). * In either case mutual exclusion between callers is observed. */ void aio_context::flush() { if (asynch_io) { io_flush_ack->clear(); io_do_flush = TRUE; io_event_signal(); io_flush_ack->wait(); } else { perform_flush(); } } /****************************************************************************************** * AIO event queue * ******************************************************************************************/ /* * Events are posed to AIO event queue by IO processing (IOP) threads on completion of * asynchronous IO request. * * Events are fetched from the queue and processed by primary VCPU's thread, since on VAX * only primrary processor is handling the interrupts (under VMS anyway), therefore it would * be wasteful to spread AIO event handling to other CPUs so they almost immediatelly re-post * device interrupts to the primary processor. It is much more efficient to handle all of * AIO postprocessing within the context of primary processor only. * * Ocassionally requests can be fetched and processed also on the console thread, but * within the context of primary processor as well -- when all VCPUs are suspended and * simulator is entering console mode or executing in the console mode. * * Thus we have multiple producers (IOP threads) but only one consumer (either primary * VCPU thread or console thread, when VCPU threads are paused by the console). * * To reduce overhead and avoid preemption/convoying issues, we implement AIO event * queue as lock-free queue. * * In our particular case (single consumer and multiple producers) we can get by with * CAS or LL/SC instructions. * * If there were multiple consumers, we'd have to use lock-free queue such as described * in Herlihy & Shavit's "The Art of Multiprocessor's Programming" (2008), pp. 230-237 * or Michael & Scott's "Simple, Fast and Practical Non-Blocking and Blocking Concurrent * Queue Algorithms" (1996). These algorithms requuire CAS2 or LL/SC and cannot be * implemented with CAS alone. DCAS abstraction for various platforms is handily * defined in libldfs sources (libldfs.org, file abstraction_dcas.c). * * On host machines where CAS (or LL/SC) instructons are not available, AIO event queue * would have to be implemented as lockable queue, using something like * * AUTO_INIT_LOCK(sim_asynch_queue_lock, SIM_LOCK_CRITICALITY_NONE, 200); * * and * * sim_asynch_queue_lock->lock(); * sim_asynch_queue_lock->unlock(); * * Current implementaton uses CAS. * * There is no ABA problem on inserting side because: * * - UNIT object being inserted is "owned" by inserting IOP thread * - value of head pointer being replaced is confirmed atomically by CAS * - no other field is modified * * There is no ABA problem on removal side because: * * - inserion and removal happens only at the head, so a_next link of * head entry is not modified by IOP thread * - head pointer value cannot cycle ABA except through dequeueing, * by dequeueing is done only by single retrieval thread which is * synchronized to itself * * Interlocked header insertion/retrieval works as LIFO. To maintain fairness * and prevent saturation of the queue by single device, we convert it to FIFO * after the entries had been removed off the interlocked queue. Retrieval side * maintains list private to retrieval thread. After copying all the entries * from the interlocked LIFO list, it puts them on private LIFO list. Double * LIFO ordering creates FIFO. * * Note that current AIO queue code assumes that device handler can use * either sim_async_post_io_event or sim_asynch_activate[_abs], but not both * for the same UNIT. * */ #if !defined(VM_VAX_MP) # error review code: AIO_SIGNAL_CPU sends to primary CPU #endif /* events are put into sim_asynch_queue by IOP threads, retrieved by primary VCPU thread */ static smp_interlocked_addr_val_var sim_asynch_queue = smp_var_init(0); /* "aqueue" is accessed by primary VCPU thread only */ static UNIT* aqueue = NULL; static void init_aio_data() { smp_check_aligned(& sim_asynch_queue); } ON_INIT_INVOKE(init_aio_data); t_bool sim_async_io_queue_isempty() { return smp_interlocked_cas_done_var(& sim_asynch_queue, (t_addr_val) 0, (t_addr_val) 0); } /* Insert new entry at the head, in LIFO order */ #define AIO_INSERT_QUEUE(uptr) \ do \ { \ (uptr)->a_next = (UNIT*) smp_var(sim_asynch_queue); \ } \ while (! smp_interlocked_cas_done_var(& sim_asynch_queue, (t_addr_val) (uptr)->a_next, (t_addr_val) (uptr))) #define AIO_SIGNAL_CPU() \ interrupt_set_int(&cpu_unit_0, IPL_ASYNC_IO, INT_V_ASYNC_IO) void sim_async_post_io_event(UNIT* uptr) { smp_pre_interlocked_wmb(); AIO_INSERT_QUEUE(uptr); AIO_SIGNAL_CPU(); } static t_stat sim_async_activate_thunk(UNIT *uptr, int32 interval) { return sim_activate(uptr, interval); } void sim_asynch_activate(UNIT *uptr, int32 interval) { t_bool signal = FALSE; uptr->lock->lock(); if (uptr->a_activate_call == NULL) { uptr->a_activate_call = sim_async_activate_thunk; uptr->a_sim_interval = interval; AIO_INSERT_QUEUE(uptr); signal = TRUE; } uptr->lock->unlock(); if (signal) AIO_SIGNAL_CPU(); } void sim_asynch_activate_abs(UNIT *uptr, int32 interval) { uptr->lock->lock(); t_bool onqueue = (uptr->a_activate_call != NULL); uptr->a_activate_call = sim_activate_abs; uptr->a_sim_interval = interval; if (! onqueue) AIO_INSERT_QUEUE(uptr); uptr->lock->unlock(); if (! onqueue) AIO_SIGNAL_CPU(); } /* * will normally be invoked at thread priority level VM_CRITICAL, * boosted up by sent interrupt and before interrupt processing * recalculates thread priority down */ void sim_async_process_io_events(RUN_DECL, t_bool* pany, t_bool current_only) { #if !defined(VM_VAX_MP) # error review code: assumes primary CPU context #endif t_bool any = FALSE; for (;;) { UNIT* aq = NULL; UNIT* uptr; /* * Dequeue entries from AIO queue and transfer them to local queue "aq", * reversing order of entries from LIFO to FIFO. */ for (;;) { t_addr_val qe = smp_var(sim_asynch_queue); uptr = (UNIT*) qe; if (uptr == NULL) break; if (smp_interlocked_cas_done_var(& sim_asynch_queue, qe, (t_addr_val) uptr->a_next)) { smp_post_interlocked_rmb(); uptr->a_next = aq; aq = uptr; } } /* * One's first impulse is to process entries directly off "aq", but here is the problem: * a_check_completion can cause device reset, which in turn can call again sim_async_process_io_events, * recursively. This second recursive call should be able to drain events that we just picked off the queue. * * Therefore we put events fetched into "aq" on a static thread-local queue "aqueue" and process * events off this queue, which will be available to recursive invocations of this routine as well. */ if (aqueue == NULL) { aqueue = aq; } else { /* maintain FIFO order */ uptr = aq; while (uptr->a_next) uptr = uptr->a_next; uptr->a_next = aq; } /* Now process events off "aqueue" */ while (aqueue != NULL) { uptr = aqueue; aqueue = uptr->a_next; uptr->a_next = NULL; any = TRUE; uptr->lock->lock(); if (uptr->a_check_completion) (*uptr->a_check_completion)(uptr); if (uptr->a_activate_call) { (*uptr->a_activate_call)(uptr, uptr->a_sim_interval); uptr->a_activate_call = NULL; } uptr->lock->unlock(); } /* anything left? */ if (current_only || sim_async_io_queue_isempty()) break; } if (pany) *pany = any; } /* * Called by console thread when VCPUs are paused to process pending async IO events * and to flush async IO queue. */ void sim_async_process_io_events_for_console() { #if !defined(VM_VAX_MP) # error review code: assumes events are processed in the primary CPU context #endif /* * VAX-specific: do it in the context of primary CPU */ RUN_SCOPE_RSCX; CPU_UNIT* sv_cpu_unit = rscx->cpu_unit; rscx->cpu_unit = cpu_unit = &cpu_unit_0; sim_async_process_io_events(RUN_PASS); rscx->cpu_unit = sv_cpu_unit; }
[ "oboguev@yahoo.com" ]
oboguev@yahoo.com
f9afb094fa979fb34d349f798e109663ce20be71
11348e739dee821e4bdd6ec0e4c6c041a01b0b59
/kk/667.cpp
c2b8db596fa2e7289f63af1bc69e56430f9495c8
[]
no_license
Spartan859/Noip_Code
580b1f022ca4b8bf3e77ff8d57d230340715a98d
8efe9e7cc6f29cd864b9570944932f50115c3089
refs/heads/master
2022-11-18T15:09:19.500944
2020-07-11T13:36:21
2020-07-11T13:36:21
163,517,575
1
0
null
null
null
null
UTF-8
C++
false
false
1,727
cpp
#include<bits/stdc++.h> #define N 1000005 #define ll long long #define mod 100000007 using namespace std; ll segt[N],a[100005],n,m,ans[100005],t,x,y,z,mark[N],cnt=0; void build_tree(ll root,ll st,ll ed){ mark[root]=0; if(st==ed){segt[root]=a[st];return;} ll mid=st+(ed-st)/2; build_tree(root*2+1,st,mid); build_tree(root*2+2,mid+1,ed); segt[root]=max(segt[root*2+1],segt[root*2+2]); } void pushDown(ll root){ if(mark[root] != 0){ mark[root*2+1] += mark[root]; mark[root*2+2] += mark[root]; segt[root*2+1] += mark[root]; segt[root*2+2] += mark[root]; segt[root*2+1]%=mod; segt[root*2+2]%=mod; mark[root] = 0; } } void update(ll root, ll nstart, ll nend, ll ustart, ll uend, ll addVal){ if(ustart > nend || uend < nstart) return ; if(ustart <= nstart && uend >= nend){ mark[root] += addVal; segt[root] += addVal; segt[root]%=mod; return ; } pushDown(root); ll mid = (nstart + nend) / 2; update(root*2+1, nstart, mid, ustart, uend, addVal); update(root*2+2, mid+1, nend, ustart, uend, addVal); segt[root] = max(segt[root*2+1], segt[root*2+2]); segt[root]%=mod; } ll query_tree(ll root,ll nst,ll ned,ll qst,ll qed){ if(qst>ned||qed<nst) return 0; if(qst<=nst&&qed>=ned) return segt[root]; pushDown(root); ll mid=nst+(ned-nst)/2; return max(query_tree(root*2+1,nst,mid,qst,qed),query_tree(root*2+2,mid+1,ned,qst,qed)); } int main(){ scanf("%lld %lld",&n,&m); build_tree(0,1,n); for(ll i=1;i<=m;i++){ scanf("%lld %lld %lld %lld",&t,&x,&y,&z); if(t==1) update(0,1,n,x,y,z); else ans[cnt++]=query_tree(0,1,n,x,x)%mod; } for(ll i=0;i<cnt;i++) printf("%lld\n",ans[i]); return 0; }
[ "36628376+Spartan859@users.noreply.github.com" ]
36628376+Spartan859@users.noreply.github.com
bf949f4467f230340c6c749ada5401c5aca90c2e
49f88ff91aa582e1a9d5ae5a7014f5c07eab7503
/gen/services/resource_coordinator/public/mojom/service_constants.mojom-blink.cc
024b8c61c8ce4f6816e8ffcf63560d97b329a3e6
[]
no_license
AoEiuV020/kiwibrowser-arm64
b6c719b5f35d65906ae08503ec32f6775c9bb048
ae7383776e0978b945e85e54242b4e3f7b930284
refs/heads/main
2023-06-01T21:09:33.928929
2021-06-22T15:56:53
2021-06-22T15:56:53
379,186,747
0
1
null
null
null
null
UTF-8
C++
false
false
1,573
cc
// Copyright 2013 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. #if defined(__clang__) #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wunused-private-field" #elif defined(_MSC_VER) #pragma warning(push) #pragma warning(disable:4056) #pragma warning(disable:4065) #pragma warning(disable:4756) #endif #include "services/resource_coordinator/public/mojom/service_constants.mojom-blink.h" #include <math.h> #include <stdint.h> #include <utility> #include "base/logging.h" #include "base/run_loop.h" #include "mojo/public/cpp/bindings/lib/message_internal.h" #include "mojo/public/cpp/bindings/lib/serialization_util.h" #include "mojo/public/cpp/bindings/lib/unserialized_message_context.h" #include "mojo/public/cpp/bindings/lib/validate_params.h" #include "mojo/public/cpp/bindings/lib/validation_context.h" #include "mojo/public/cpp/bindings/lib/validation_errors.h" #include "mojo/public/interfaces/bindings/interface_control_messages.mojom.h" #include "services/resource_coordinator/public/mojom/service_constants.mojom-shared-message-ids.h" #include "mojo/public/cpp/bindings/lib/wtf_serialization.h" namespace resource_coordinator { namespace mojom { namespace blink { const char kServiceName[] = "resource_coordinator"; } // namespace blink } // namespace mojom } // namespace resource_coordinator namespace mojo { } // namespace mojo #if defined(__clang__) #pragma clang diagnostic pop #elif defined(_MSC_VER) #pragma warning(pop) #endif
[ "aoeiuv020@gmail.com" ]
aoeiuv020@gmail.com
b04bc034b238b9c721e118694a2a44ca4393d9f3
d3b25341d274ce4e1d8144ffa0bea0af583afd4e
/ServiceModule/MLogicServer/config/source/RiseStarCfg.cpp
a2a0ae6759c6e6dbe59f81e45e9809a0dfe839ba
[]
no_license
zwong91/cyaServer
c0a383a44cb0267c8983c9e8426c3e614bda3531
721e91268ac7db86bc606534c78b1eca74a222e5
refs/heads/master
2020-04-26T05:20:22.916718
2017-12-08T03:20:38
2017-12-08T03:20:38
null
0
0
null
null
null
null
WINDOWS-1256
C++
false
false
2,467
cpp
#include "RiseStarCfg.h" #include "ServiceErrorCode.h" #include "ServiceMLogic.h" RiseStarCfg::RiseStarCfg() { } RiseStarCfg::~RiseStarCfg() { } BOOL RiseStarCfg::Load(const char* filename) { Json::Value rootValue; if (!OpenCfgFile(filename, rootValue)) return false; if (!rootValue.isMember("StartUpgrade") || !rootValue["StartUpgrade"].isArray()) return false; int si = rootValue["StartUpgrade"].size(); if (si <= 0) return false; for (int i = 0; i < si; ++i) { SRiseStarCfg starCfg; BYTE star = (BYTE)rootValue["StartUpgrade"][i]["Level"].asUInt(); m_riseStarMap.insert(std::make_pair(star, starCfg)); SRiseStarCfg& starCfgRef = m_riseStarMap[star]; starCfgRef.extraEffect = rootValue["StartUpgrade"][i]["ExtraEffect"].asDouble(); starCfgRef.damagedChance = (BYTE)rootValue["StartUpgrade"][i]["BreakageRate"].asUInt(); starCfgRef.succedChance = (BYTE)rootValue["StartUpgrade"][i]["SuccessRate"].asUInt(); starCfgRef.limitLevel = (BYTE)rootValue["StartUpgrade"][i]["PlayerLevelLimit"].asUInt(); starCfgRef.spend.gold = rootValue["StartUpgrade"][i]["GoldCost"].asUInt(); starCfgRef.spend.stones = (UINT16)rootValue["StartUpgrade"][i]["StarStone"].asUInt(); } return true; } int RiseStarCfg::GetRiseStarSpend(BYTE starLv, SRiseStarSpend& spend) { std::map<BYTE/*ذا¼¶*/, SRiseStarCfg>::iterator it = m_riseStarMap.find(starLv); if (it == m_riseStarMap.end()) return MLS_MAX_STAR_LEVEL; spend = it->second.spend; return MLS_OK; } int RiseStarCfg::GetRiseStarLimitLevel(BYTE starLv, BYTE& limitLevel) { std::map<BYTE/*ذا¼¶*/, SRiseStarCfg>::iterator it = m_riseStarMap.find(starLv); if (it == m_riseStarMap.end()) return MLS_MAX_STAR_LEVEL; limitLevel = it->second.limitLevel; return MLS_OK; } int RiseStarCfg::GetStarTotalSpend(BYTE starLv, SRiseStarSpend& totalSpend) { totalSpend.gold = 0; totalSpend.stones = 0; std::map<BYTE/*ذا¼¶*/, SRiseStarCfg>::iterator it = m_riseStarMap.begin(); for (; it != m_riseStarMap.end(); ++it) { totalSpend.stones = SGSU16Add(totalSpend.stones, it->second.spend.stones); totalSpend.gold = SGSU64Add(totalSpend.gold, it->second.spend.gold); if (starLv == it->first) break; } return MLS_OK; } int RiseStarCfg::GetRiseStarCfg(BYTE starLv, SRiseStarCfg& cfg) { std::map<BYTE/*ذا¼¶*/, SRiseStarCfg>::iterator it = m_riseStarMap.find(starLv); if (it == m_riseStarMap.end()) return MLS_MAX_STAR_LEVEL; cfg = it->second; return MLS_OK; }
[ "haiyhe1991@163.com" ]
haiyhe1991@163.com
1d7e3a60b43c3f036a8aaf99280ba3d427fdac38
f6b62beb41088a762c72486fdb000910dc2c6867
/MODEL/allenatore.cpp
c379108136083b5c4270deffd0dae57e2b78675f
[]
no_license
ffiora/PokemonCards-P2
63bf9487ade266eb9d04030aab8fd5f6c7dfbae3
98a0b63e574dc1affb32002e93b2ebe21f7e0b71
refs/heads/master
2022-04-11T21:13:49.849115
2020-03-30T17:23:30
2020-03-30T17:23:30
251,370,297
0
0
null
null
null
null
UTF-8
C++
false
false
756
cpp
#include "allenatore.h" Allenatore::Allenatore(std::string no, std::string es,std::string nu, std::string ra, std::string se,std::string te, std::string ti):Carta(no,es,nu,ra,se),testo(te),tipo(ti){} std::string Allenatore::getTipo() const { return tipo; } std::string Allenatore::getTesto() const { return testo; } void Allenatore::setTipo(const std::string &value) { tipo = value; } void Allenatore::setTesto(const std::string &value) { testo = value; } Allenatore* Allenatore::clone () const{ return new Allenatore(*this); } nlohmann::json Allenatore::exportToJSON() const{ nlohmann::json j=this->Carta::exportToJSON(); j["supertype"]="Trainer"; j["text"] = {testo}; j["subtype"] = tipo; return j; }
[ "fiorenzafrancesca.fistarollo@studenti.unipd.it" ]
fiorenzafrancesca.fistarollo@studenti.unipd.it
c8f85a65e65c86ae2cc1bc03db276c5a35d00b73
e67f4f4d8073e4bbc8383d909ab22926a58bb4cf
/src/compiler/escape-analysis.cc
45829734c5d93bcffb02d135b542c5ff1bb07a05
[ "BSD-3-Clause", "bzip2-1.0.6", "SunPro" ]
permissive
atcha9035/v8
60c9db15a2049beb29cd1d76ed48e3ac1772aad5
e17f05704ca5afbff58a9b0e70b357ebc7c8ff9d
refs/heads/master
2021-07-12T09:22:54.183419
2017-10-06T12:40:04
2017-10-09T09:36:02
106,272,368
1
0
null
2017-10-09T11:00:39
2017-10-09T11:00:38
null
UTF-8
C++
false
false
28,138
cc
// Copyright 2017 the V8 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. #include "src/compiler/escape-analysis.h" #include "src/bootstrapper.h" #include "src/compiler/linkage.h" #include "src/compiler/node-matchers.h" #include "src/compiler/operator-properties.h" #include "src/compiler/simplified-operator.h" #include "src/zone/zone-list-inl.h" // TODO(mstarzinger): Fix zone-handle-set.h instead! #ifdef DEBUG #define TRACE(...) \ do { \ if (FLAG_trace_turbo_escape) PrintF(__VA_ARGS__); \ } while (false) #else #define TRACE(...) #endif namespace v8 { namespace internal { namespace compiler { template <class T> class Sidetable { public: explicit Sidetable(Zone* zone) : map_(zone) {} T& operator[](const Node* node) { NodeId id = node->id(); if (id >= map_.size()) { map_.resize(id + 1); } return map_[id]; } private: ZoneVector<T> map_; }; template <class T> class SparseSidetable { public: explicit SparseSidetable(Zone* zone, T def_value = T()) : def_value_(std::move(def_value)), map_(zone) {} void Set(const Node* node, T value) { auto iter = map_.find(node->id()); if (iter != map_.end()) { iter->second = std::move(value); } else if (value != def_value_) { map_.insert(iter, std::make_pair(node->id(), std::move(value))); } } const T& Get(const Node* node) const { auto iter = map_.find(node->id()); return iter != map_.end() ? iter->second : def_value_; } private: T def_value_; ZoneUnorderedMap<NodeId, T> map_; }; // Keeps track of the changes to the current node during reduction. // Encapsulates the current state of the IR graph and the reducer state like // side-tables. All access to the IR and the reducer state should happen through // a ReduceScope to ensure that changes and dependencies are tracked and all // necessary node revisitations happen. class ReduceScope { public: typedef EffectGraphReducer::Reduction Reduction; explicit ReduceScope(Node* node, Reduction* reduction) : current_node_(node), reduction_(reduction) {} protected: Node* current_node() const { return current_node_; } Reduction* reduction() { return reduction_; } private: Node* current_node_; Reduction* reduction_; }; // A VariableTracker object keeps track of the values of variables at all points // of the effect chain and introduces new phi nodes when necessary. // Initially and by default, variables are mapped to nullptr, which means that // the variable allocation point does not dominate the current point on the // effect chain. We map variables that represent uninitialized memory to the // Dead node to ensure it is not read. // Unmapped values are impossible by construction, it is indistinguishable if a // PersistentMap does not contain an element or maps it to the default element. class VariableTracker { private: // The state of all variables at one point in the effect chain. class State { typedef PersistentMap<Variable, Node*> Map; public: explicit State(Zone* zone) : map_(zone) {} Node* Get(Variable var) const { CHECK(var != Variable::Invalid()); return map_.Get(var); } void Set(Variable var, Node* node) { CHECK(var != Variable::Invalid()); return map_.Set(var, node); } Map::iterator begin() const { return map_.begin(); } Map::iterator end() const { return map_.end(); } bool operator!=(const State& other) const { return map_ != other.map_; } private: Map map_; }; public: VariableTracker(JSGraph* graph, EffectGraphReducer* reducer, Zone* zone); Variable NewVariable() { return Variable(next_variable_++); } Node* Get(Variable var, Node* effect) { return table_.Get(effect).Get(var); } Zone* zone() { return zone_; } class Scope : public ReduceScope { public: Scope(VariableTracker* tracker, Node* node, Reduction* reduction); ~Scope(); Node* Get(Variable var) { return current_state_.Get(var); } void Set(Variable var, Node* node) { current_state_.Set(var, node); } private: VariableTracker* states_; State current_state_; }; private: State MergeInputs(Node* effect_phi); Zone* zone_; JSGraph* graph_; SparseSidetable<State> table_; ZoneVector<Node*> buffer_; EffectGraphReducer* reducer_; int next_variable_ = 0; DISALLOW_COPY_AND_ASSIGN(VariableTracker); }; // Encapsulates the current state of the escape analysis reducer to preserve // invariants regarding changes and re-visitation. class EscapeAnalysisTracker : public ZoneObject { public: EscapeAnalysisTracker(JSGraph* jsgraph, EffectGraphReducer* reducer, Zone* zone) : virtual_objects_(zone), replacements_(zone), variable_states_(jsgraph, reducer, zone), jsgraph_(jsgraph), zone_(zone) {} class Scope : public VariableTracker::Scope { public: Scope(EffectGraphReducer* reducer, EscapeAnalysisTracker* tracker, Node* node, Reduction* reduction) : VariableTracker::Scope(&tracker->variable_states_, node, reduction), tracker_(tracker), reducer_(reducer) {} const VirtualObject* GetVirtualObject(Node* node) { VirtualObject* vobject = tracker_->virtual_objects_.Get(node); if (vobject) vobject->AddDependency(current_node()); return vobject; } // Create or retrieve a virtual object for the current node. const VirtualObject* InitVirtualObject(int size) { DCHECK_EQ(IrOpcode::kAllocate, current_node()->opcode()); VirtualObject* vobject = tracker_->virtual_objects_.Get(current_node()); if (vobject) { CHECK(vobject->size() == size); } else { vobject = tracker_->NewVirtualObject(size); } if (vobject) vobject->AddDependency(current_node()); vobject_ = vobject; return vobject; } void SetVirtualObject(Node* object) { vobject_ = tracker_->virtual_objects_.Get(object); } void SetEscaped(Node* node) { if (VirtualObject* object = tracker_->virtual_objects_.Get(node)) { if (object->HasEscaped()) return; TRACE("Setting %s#%d to escaped because of use by %s#%d\n", node->op()->mnemonic(), node->id(), current_node()->op()->mnemonic(), current_node()->id()); object->SetEscaped(); object->RevisitDependants(reducer_); } } // The inputs of the current node have to be accessed through the scope to // ensure that they respect the node replacements. Node* ValueInput(int i) { return tracker_->ResolveReplacement( NodeProperties::GetValueInput(current_node(), i)); } Node* ContextInput() { return tracker_->ResolveReplacement( NodeProperties::GetContextInput(current_node())); } void SetReplacement(Node* replacement) { replacement_ = replacement; vobject_ = replacement ? tracker_->virtual_objects_.Get(replacement) : nullptr; TRACE("Set %s#%d as replacement.\n", replacement->op()->mnemonic(), replacement->id()); } void MarkForDeletion() { SetReplacement(tracker_->jsgraph_->Dead()); } ~Scope() { if (replacement_ != tracker_->replacements_[current_node()] || vobject_ != tracker_->virtual_objects_.Get(current_node())) { reduction()->set_value_changed(); } tracker_->replacements_[current_node()] = replacement_; tracker_->virtual_objects_.Set(current_node(), vobject_); } private: EscapeAnalysisTracker* tracker_; EffectGraphReducer* reducer_; VirtualObject* vobject_ = nullptr; Node* replacement_ = nullptr; }; Node* GetReplacementOf(Node* node) { return replacements_[node]; } Node* ResolveReplacement(Node* node) { if (Node* replacement = GetReplacementOf(node)) { // Replacements cannot have replacements. This is important to ensure // re-visitation: If a replacement is replaced, then all nodes accessing // the replacement have to be updated. DCHECK_NULL(GetReplacementOf(replacement)); return replacement; } return node; } private: friend class EscapeAnalysisResult; static const size_t kMaxTrackedObjects = 100; VirtualObject* NewVirtualObject(int size) { if (next_object_id_ >= kMaxTrackedObjects) return nullptr; return new (zone_) VirtualObject(&variable_states_, next_object_id_++, size); } SparseSidetable<VirtualObject*> virtual_objects_; Sidetable<Node*> replacements_; VariableTracker variable_states_; VirtualObject::Id next_object_id_ = 0; JSGraph* const jsgraph_; Zone* const zone_; DISALLOW_COPY_AND_ASSIGN(EscapeAnalysisTracker); }; EffectGraphReducer::EffectGraphReducer( Graph* graph, std::function<void(Node*, Reduction*)> reduce, Zone* zone) : graph_(graph), state_(graph, kNumStates), revisit_(zone), stack_(zone), reduce_(reduce) {} void EffectGraphReducer::ReduceFrom(Node* node) { // Perform DFS and eagerly trigger revisitation as soon as possible. // A stack element {node, i} indicates that input i of node should be visited // next. DCHECK(stack_.empty()); stack_.push({node, 0}); while (!stack_.empty()) { Node* current = stack_.top().node; int& input_index = stack_.top().input_index; if (input_index < current->InputCount()) { Node* input = current->InputAt(input_index); input_index++; switch (state_.Get(input)) { case State::kVisited: // The input is already reduced. break; case State::kOnStack: // The input is on the DFS stack right now, so it will be revisited // later anyway. break; case State::kUnvisited: case State::kRevisit: { state_.Set(input, State::kOnStack); stack_.push({input, 0}); break; } } } else { stack_.pop(); Reduction reduction; reduce_(current, &reduction); for (Edge edge : current->use_edges()) { // Mark uses for revisitation. Node* use = edge.from(); if (NodeProperties::IsEffectEdge(edge)) { if (reduction.effect_changed()) Revisit(use); } else { if (reduction.value_changed()) Revisit(use); } } state_.Set(current, State::kVisited); // Process the revisitation buffer immediately. This improves performance // of escape analysis. Using a stack for {revisit_} reverses the order in // which the revisitation happens. This also seems to improve performance. while (!revisit_.empty()) { Node* revisit = revisit_.top(); if (state_.Get(revisit) == State::kRevisit) { state_.Set(revisit, State::kOnStack); stack_.push({revisit, 0}); } revisit_.pop(); } } } } void EffectGraphReducer::Revisit(Node* node) { if (state_.Get(node) == State::kVisited) { TRACE(" Queueing for revisit: %s#%d\n", node->op()->mnemonic(), node->id()); state_.Set(node, State::kRevisit); revisit_.push(node); } } VariableTracker::VariableTracker(JSGraph* graph, EffectGraphReducer* reducer, Zone* zone) : zone_(zone), graph_(graph), table_(zone, State(zone)), buffer_(zone), reducer_(reducer) {} VariableTracker::Scope::Scope(VariableTracker* states, Node* node, Reduction* reduction) : ReduceScope(node, reduction), states_(states), current_state_(states->zone_) { switch (node->opcode()) { case IrOpcode::kEffectPhi: current_state_ = states_->MergeInputs(node); break; default: int effect_inputs = node->op()->EffectInputCount(); if (effect_inputs == 1) { current_state_ = states_->table_.Get(NodeProperties::GetEffectInput(node, 0)); } else { DCHECK_EQ(0, effect_inputs); } } } VariableTracker::Scope::~Scope() { if (!reduction()->effect_changed() && states_->table_.Get(current_node()) != current_state_) { reduction()->set_effect_changed(); } states_->table_.Set(current_node(), current_state_); } VariableTracker::State VariableTracker::MergeInputs(Node* effect_phi) { // A variable that is mapped to [nullptr] was not assigned a value on every // execution path to the current effect phi. Relying on the invariant that // every variable is initialized (at least with a sentinel like the Dead // node), this means that the variable initialization does not dominate the // current point. So for loop effect phis, we can keep nullptr for a variable // as long as the first input of the loop has nullptr for this variable. For // non-loop effect phis, we can even keep it nullptr as long as any input has // nullptr. DCHECK_EQ(IrOpcode::kEffectPhi, effect_phi->opcode()); int arity = effect_phi->op()->EffectInputCount(); Node* control = NodeProperties::GetControlInput(effect_phi, 0); TRACE("control: %s#%d\n", control->op()->mnemonic(), control->id()); bool is_loop = control->opcode() == IrOpcode::kLoop; buffer_.reserve(arity + 1); State first_input = table_.Get(NodeProperties::GetEffectInput(effect_phi, 0)); State result = first_input; for (std::pair<Variable, Node*> var_value : first_input) { if (Node* value = var_value.second) { Variable var = var_value.first; TRACE("var %i:\n", var.id_); buffer_.clear(); buffer_.push_back(value); bool identical_inputs = true; int num_defined_inputs = 1; TRACE(" input 0: %s#%d\n", value->op()->mnemonic(), value->id()); for (int i = 1; i < arity; ++i) { Node* next_value = table_.Get(NodeProperties::GetEffectInput(effect_phi, i)).Get(var); if (next_value != value) identical_inputs = false; if (next_value != nullptr) { num_defined_inputs++; TRACE(" input %i: %s#%d\n", i, next_value->op()->mnemonic(), next_value->id()); } else { TRACE(" input %i: nullptr\n", i); } buffer_.push_back(next_value); } Node* old_value = table_.Get(effect_phi).Get(var); if (old_value) { TRACE(" old: %s#%d\n", old_value->op()->mnemonic(), old_value->id()); } else { TRACE(" old: nullptr\n"); } // Reuse a previously created phi node if possible. if (old_value && old_value->opcode() == IrOpcode::kPhi && NodeProperties::GetControlInput(old_value, 0) == control) { // Since a phi node can never dominate its control node, // [old_value] cannot originate from the inputs. Thus [old_value] // must have been created by a previous reduction of this [effect_phi]. for (int i = 0; i < arity; ++i) { NodeProperties::ReplaceValueInput( old_value, buffer_[i] ? buffer_[i] : graph_->Dead(), i); // This change cannot affect the rest of the reducer, so there is no // need to trigger additional revisitations. } result.Set(var, old_value); } else { if (num_defined_inputs == 1 && is_loop) { // For loop effect phis, the variable initialization dominates iff it // dominates the first input. DCHECK_EQ(2, arity); DCHECK_EQ(value, buffer_[0]); result.Set(var, value); } else if (num_defined_inputs < arity) { // If the variable is undefined on some input of this non-loop effect // phi, then its initialization does not dominate this point. result.Set(var, nullptr); } else { DCHECK_EQ(num_defined_inputs, arity); // We only create a phi if the values are different. if (identical_inputs) { result.Set(var, value); } else { TRACE("Creating new phi\n"); buffer_.push_back(control); Node* phi = graph_->graph()->NewNode( graph_->common()->Phi(MachineRepresentation::kTagged, arity), arity + 1, &buffer_.front()); // TODO(tebbi): Computing precise types here is tricky, because of // the necessary revisitations. If we really need this, we should // probably do it afterwards. NodeProperties::SetType(phi, Type::Any()); reducer_->AddRoot(phi); result.Set(var, phi); } } } #ifdef DEBUG if (Node* result_node = result.Get(var)) { TRACE(" result: %s#%d\n", result_node->op()->mnemonic(), result_node->id()); } else { TRACE(" result: nullptr\n"); } #endif } } return result; } namespace { int OffsetOfFieldAccess(const Operator* op) { DCHECK(op->opcode() == IrOpcode::kLoadField || op->opcode() == IrOpcode::kStoreField); FieldAccess access = FieldAccessOf(op); return access.offset; } Maybe<int> OffsetOfElementsAccess(const Operator* op, Node* index_node) { DCHECK(op->opcode() == IrOpcode::kLoadElement || op->opcode() == IrOpcode::kStoreElement); Type* index_type = NodeProperties::GetType(index_node); if (!index_type->Is(Type::Number())) return Nothing<int>(); double max = index_type->Max(); double min = index_type->Min(); int index = static_cast<int>(min); if (!(index == min && index == max)) return Nothing<int>(); ElementAccess access = ElementAccessOf(op); DCHECK_GE(ElementSizeLog2Of(access.machine_type.representation()), kPointerSizeLog2); return Just(access.header_size + (index << ElementSizeLog2Of( access.machine_type.representation()))); } Node* LowerCompareMapsWithoutLoad(Node* checked_map, ZoneHandleSet<Map> const& checked_against, JSGraph* jsgraph) { Node* true_node = jsgraph->TrueConstant(); Node* false_node = jsgraph->FalseConstant(); Node* replacement = false_node; for (Handle<Map> map : checked_against) { Node* map_node = jsgraph->HeapConstant(map); // We cannot create a HeapConstant type here as we are off-thread. NodeProperties::SetType(map_node, Type::Internal()); Node* comparison = jsgraph->graph()->NewNode( jsgraph->simplified()->ReferenceEqual(), checked_map, map_node); NodeProperties::SetType(comparison, Type::Boolean()); if (replacement == false_node) { replacement = comparison; } else { replacement = jsgraph->graph()->NewNode( jsgraph->common()->Select(MachineRepresentation::kTaggedPointer), comparison, true_node, replacement); NodeProperties::SetType(replacement, Type::Boolean()); } } return replacement; } void ReduceNode(const Operator* op, EscapeAnalysisTracker::Scope* current, JSGraph* jsgraph) { switch (op->opcode()) { case IrOpcode::kAllocate: { NumberMatcher size(current->ValueInput(0)); if (!size.HasValue()) break; int size_int = static_cast<int>(size.Value()); if (size_int != size.Value()) break; if (const VirtualObject* vobject = current->InitVirtualObject(size_int)) { // Initialize with dead nodes as a sentinel for uninitialized memory. for (Variable field : *vobject) { current->Set(field, jsgraph->Dead()); } } break; } case IrOpcode::kFinishRegion: current->SetVirtualObject(current->ValueInput(0)); break; case IrOpcode::kStoreField: { Node* object = current->ValueInput(0); Node* value = current->ValueInput(1); const VirtualObject* vobject = current->GetVirtualObject(object); Variable var; if (vobject && !vobject->HasEscaped() && vobject->FieldAt(OffsetOfFieldAccess(op)).To(&var)) { current->Set(var, value); current->MarkForDeletion(); } else { current->SetEscaped(object); current->SetEscaped(value); } break; } case IrOpcode::kStoreElement: { Node* object = current->ValueInput(0); Node* index = current->ValueInput(1); Node* value = current->ValueInput(2); const VirtualObject* vobject = current->GetVirtualObject(object); int offset; Variable var; if (vobject && !vobject->HasEscaped() && OffsetOfElementsAccess(op, index).To(&offset) && vobject->FieldAt(offset).To(&var)) { current->Set(var, value); current->MarkForDeletion(); } else { current->SetEscaped(value); current->SetEscaped(object); } break; } case IrOpcode::kLoadField: { Node* object = current->ValueInput(0); const VirtualObject* vobject = current->GetVirtualObject(object); Variable var; if (vobject && !vobject->HasEscaped() && vobject->FieldAt(OffsetOfFieldAccess(op)).To(&var)) { current->SetReplacement(current->Get(var)); } else { // TODO(tebbi): At the moment, we mark objects as escaping if there // is a load from an invalid location to avoid dead nodes. This is a // workaround that should be removed once we can handle dead nodes // everywhere. current->SetEscaped(object); } break; } case IrOpcode::kLoadElement: { Node* object = current->ValueInput(0); Node* index = current->ValueInput(1); const VirtualObject* vobject = current->GetVirtualObject(object); int offset; Variable var; if (vobject && !vobject->HasEscaped() && OffsetOfElementsAccess(op, index).To(&offset) && vobject->FieldAt(offset).To(&var)) { current->SetReplacement(current->Get(var)); } else { current->SetEscaped(object); } break; } case IrOpcode::kTypeGuard: { // The type-guard is re-introduced in the final reducer if the types // don't match. current->SetReplacement(current->ValueInput(0)); break; } case IrOpcode::kReferenceEqual: { Node* left = current->ValueInput(0); Node* right = current->ValueInput(1); const VirtualObject* left_object = current->GetVirtualObject(left); const VirtualObject* right_object = current->GetVirtualObject(right); Node* replacement = nullptr; if (left_object && !left_object->HasEscaped()) { if (right_object && !right_object->HasEscaped() && left_object->id() == right_object->id()) { replacement = jsgraph->TrueConstant(); } else { replacement = jsgraph->FalseConstant(); } } else if (right_object && !right_object->HasEscaped()) { replacement = jsgraph->FalseConstant(); } if (replacement) { // TODO(tebbi) This is a workaround for uninhabited types. If we // replaced a value of uninhabited type with a constant, we would // widen the type of the node. This could produce inconsistent // types (which might confuse representation selection). We get // around this by refusing to constant-fold and escape-analyze // if the type is not inhabited. if (NodeProperties::GetType(left)->IsInhabited() && NodeProperties::GetType(right)->IsInhabited()) { current->SetReplacement(replacement); } else { current->SetEscaped(left); current->SetEscaped(right); } } break; } case IrOpcode::kCheckMaps: { CheckMapsParameters params = CheckMapsParametersOf(op); Node* checked = current->ValueInput(0); const VirtualObject* vobject = current->GetVirtualObject(checked); Variable map_field; if (vobject && !vobject->HasEscaped() && vobject->FieldAt(HeapObject::kMapOffset).To(&map_field)) { if (Node* map = current->Get(map_field)) { Type* const map_type = NodeProperties::GetType(map); if (map_type->IsHeapConstant() && params.maps().contains(ZoneHandleSet<Map>(bit_cast<Handle<Map>>( map_type->AsHeapConstant()->Value())))) { current->MarkForDeletion(); break; } } else { // If the variable has no value, we have not reached the fixed-point // yet. break; } } current->SetEscaped(checked); break; } case IrOpcode::kCompareMaps: { Node* object = current->ValueInput(0); const VirtualObject* vobject = current->GetVirtualObject(object); Variable map_field; if (vobject && !vobject->HasEscaped() && vobject->FieldAt(HeapObject::kMapOffset).To(&map_field)) { if (Node* object_map = current->Get(map_field)) { current->SetReplacement(LowerCompareMapsWithoutLoad( object_map, CompareMapsParametersOf(op), jsgraph)); break; } else { // If the variable has no value, we have not reached the fixed-point // yet. break; } } current->SetEscaped(object); break; } case IrOpcode::kCheckHeapObject: { Node* checked = current->ValueInput(0); switch (checked->opcode()) { case IrOpcode::kAllocate: case IrOpcode::kFinishRegion: case IrOpcode::kHeapConstant: current->SetReplacement(checked); break; default: current->SetEscaped(checked); break; } break; } case IrOpcode::kMapGuard: { Node* object = current->ValueInput(0); const VirtualObject* vobject = current->GetVirtualObject(object); if (vobject && !vobject->HasEscaped()) { current->MarkForDeletion(); } break; } case IrOpcode::kStateValues: case IrOpcode::kFrameState: // These uses are always safe. break; default: { // For unknown nodes, treat all value inputs as escaping. int value_input_count = op->ValueInputCount(); for (int i = 0; i < value_input_count; ++i) { Node* input = current->ValueInput(i); current->SetEscaped(input); } if (OperatorProperties::HasContextInput(op)) { current->SetEscaped(current->ContextInput()); } break; } } } } // namespace void EscapeAnalysis::Reduce(Node* node, Reduction* reduction) { const Operator* op = node->op(); TRACE("Reducing %s#%d\n", op->mnemonic(), node->id()); EscapeAnalysisTracker::Scope current(this, tracker_, node, reduction); ReduceNode(op, &current, jsgraph()); } EscapeAnalysis::EscapeAnalysis(JSGraph* jsgraph, Zone* zone) : EffectGraphReducer( jsgraph->graph(), [this](Node* node, Reduction* reduction) { Reduce(node, reduction); }, zone), tracker_(new (zone) EscapeAnalysisTracker(jsgraph, this, zone)), jsgraph_(jsgraph) {} Node* EscapeAnalysisResult::GetReplacementOf(Node* node) { return tracker_->GetReplacementOf(node); } Node* EscapeAnalysisResult::GetVirtualObjectField(const VirtualObject* vobject, int field, Node* effect) { return tracker_->variable_states_.Get(vobject->FieldAt(field).FromJust(), effect); } const VirtualObject* EscapeAnalysisResult::GetVirtualObject(Node* node) { return tracker_->virtual_objects_.Get(node); } VirtualObject::VirtualObject(VariableTracker* var_states, VirtualObject::Id id, int size) : Dependable(var_states->zone()), id_(id), fields_(var_states->zone()) { DCHECK_EQ(0, size % kPointerSize); TRACE("Creating VirtualObject id:%d size:%d\n", id, size); int num_fields = size / kPointerSize; fields_.reserve(num_fields); for (int i = 0; i < num_fields; ++i) { fields_.push_back(var_states->NewVariable()); } } #undef TRACE } // namespace compiler } // namespace internal } // namespace v8
[ "commit-bot@chromium.org" ]
commit-bot@chromium.org
b710debc06f604d5ba3f1a01ec79cc30884fb172
3d60c921ad82fab20ca3c8e7231bc718dbed4cfc
/FlingEngine/Resources/inc/FlingConfig.h
a4caad8bca489c72ab300722417588b8ce5a30df
[ "MIT" ]
permissive
eddyowen/FlingEngine
96f7d4450caae9b56a9f487c61a4654e1105c84e
12b119b752c90dc344d4beb95bbe42fb693ba97a
refs/heads/master
2023-01-06T12:29:58.014892
2019-12-30T16:16:27
2019-12-30T16:16:27
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,508
h
#pragma once #include "Singleton.hpp" #include "INIReader.h" namespace Fling { /** * Provide simple access to engine configuration options from an INI file * #TODO Parse command line options as well */ class FlingConfig : public Singleton<FlingConfig> { public: virtual void Init() override; virtual void Shutdown() override; /** * Attempt to load a config file (.ini) for the engine * * @param t_File File path to the config file * * @return True if file was read successfully */ bool LoadConfigFile(const std::string& t_File); static std::string GetString(const std::string& t_Section, const std::string& t_Key) { return FlingConfig::Get().GetStringImpl(t_Section, t_Key); } static int GetInt(const std::string& t_Section, const std::string& t_Key, const int t_DefaultVal = -1) { return FlingConfig::Get().GetIntImpl(t_Section, t_Key); } static bool GetBool(const std::string& t_Section, const std::string& t_Key, const bool t_DefaultVal = false) { return FlingConfig::Get().GetBoolImpl(t_Section, t_Key); } static float GetFloat(const std::string& t_Section, const std::string& t_Key, const float t_DefaultVal = 0.0f) { return FlingConfig::Get().GetFloatImpl(t_Section, t_Key); } static double GetDouble(const std::string& t_Section, const std::string& t_Key, const double t_DefaultVal = 0.0) { return FlingConfig::Get().GetDoubleImpl(t_Section, t_Key); } /** * Load in the command line options and store them somewhere that is * globally accessible * * @param argc Argument count * @param argv Command line args * @return Number of options loaded */ UINT32 LoadCommandLineOpts( int argc, char* argv[] ); private: /** Ini config file reader */ static INIReader m_IniReader; std::string GetStringImpl(const std::string& t_Section, const std::string& t_Key) const; int GetIntImpl(const std::string& t_Section, const std::string& t_Key, const int t_DefaultVal = -1) const; bool GetBoolImpl(const std::string& t_Section, const std::string& t_Key, const bool t_DefaultVal = false) const; float GetFloatImpl(const std::string& t_Section, const std::string& t_Key, const float t_DefaultVal = 0.0f) const; double GetDoubleImpl(const std::string& t_Section, const std::string& t_Key, const double t_DefaultVal = 0.0) const; }; } // namespace Fling
[ "benjamin.hoffman.dev@gmail.com" ]
benjamin.hoffman.dev@gmail.com
5dc4ee67a03442280decfcf7b8276a25f1306530
604c5a5dacb8883866e7280fb690d7fe20af24cf
/mainwindow.h
2f29b9ad123bafc2bc4df9dc2ed3623b239e252c
[]
no_license
lkosten/Graphics-algoryihms-lab1
fed706503d92409c87093d44017f3db448147824
cd8a8e7193c4672973742b1df63d4fb93adaa75f
refs/heads/master
2023-03-10T11:35:10.639262
2021-03-02T09:43:16
2021-03-02T09:43:16
343,718,825
0
0
null
null
null
null
UTF-8
C++
false
false
1,670
h
#ifndef MAINWINDOW_H #define MAINWINDOW_H #include <QMainWindow> #include <QValidator> QT_BEGIN_NAMESPACE namespace Ui { class MainWindow; } QT_END_NAMESPACE class MainWindow : public QMainWindow { Q_OBJECT public: MainWindow(QWidget *parent = nullptr); ~MainWindow(); void RGBChanged(); void XYZChanged(); void HSLChanged(); private: Ui::MainWindow *ui; const double eps = 1e-8; bool correct_color; struct RGB { int r; int g; int b; }; struct XYZ { double x; double y; double z; }; struct HSL { double h; double s; double l; }; double FRGB(double x); double FXYZ(double x); std::pair<XYZ, bool> RGBToXYZ(const RGB &rgb); std::pair<HSL, bool> RGBToHSL(const RGB &rgb); std::pair<RGB, bool> XYZToRGB(const XYZ &xyz); std::pair<RGB, bool> HSLToRGB(const HSL &hsl); void SetCorretnessMessage(bool is_correct); void SetRGB(const RGB &rgb); void SetXYZ(const XYZ &xyz); void SetHSL(const HSL &hsl); }; class CustomValiudator : public QDoubleValidator{ QStringList _decimalPoints; public: CustomValiudator() : QDoubleValidator(0, 100, 5) { _decimalPoints.append("."); setNotation(QDoubleValidator::StandardNotation); } State validate(QString &str, int &pos) const{ QString s(str); for(QStringList::ConstIterator point = _decimalPoints.begin(); point != _decimalPoints.end(); ++point){ s.replace(*point, locale().decimalPoint()); } return QDoubleValidator::validate(s, pos); } }; #endif // MAINWINDOW_H
[ "kyarmash@gmail.com" ]
kyarmash@gmail.com
fada9e1c72f48f272b85cab250d536dc30bd4ae3
e27d9e460c374473e692f58013ca692934347ef1
/drafts/quickSpectrogram_2/libraries/liblsl/external/lslboost/spirit/include/karma_bool.hpp
edf8cec2aa5e35ce1256f9c5e52d5898d271d5b5
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
thoughtworksarts/Dual_Brains
84a0edf69d95299021daf4af9311aed5724a2e84
a7a6586b91a280950693b427d8269bd68bf8a7ab
refs/heads/master
2021-09-18T15:50:51.397078
2018-07-16T23:20:18
2018-07-16T23:20:18
119,759,649
3
0
null
2018-07-16T23:14:34
2018-02-01T00:09:16
HTML
UTF-8
C++
false
false
645
hpp
/*============================================================================= Copyright (c) 2001-2011 Joel de Guzman Copyright (c) 2001-2011 Hartmut Kaiser http://spirit.sourceforge.net/ Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at http://www.lslboost.org/LICENSE_1_0.txt) =============================================================================*/ #ifndef BOOST_SPIRIT_INCLUDE_KARMA_BOOL #define BOOST_SPIRIT_INCLUDE_KARMA_BOOL #if defined(_MSC_VER) #pragma once #endif #include <lslboost/spirit/home/karma/numeric/bool.hpp> #endif
[ "gabriel.ibagon@gmail.com" ]
gabriel.ibagon@gmail.com
6f292c18d411e6bcdcd111d14317f21ee9ad6ec0
6b40e9dccf2edc767c44df3acd9b626fcd586b4d
/NT/inetcore/outlookexpress/mailnews/common/iso8601.h
e20f39365c02ca16f717612a1cf6d03ab907765c
[]
no_license
jjzhang166/WinNT5_src_20201004
712894fcf94fb82c49e5cd09d719da00740e0436
b2db264153b80fbb91ef5fc9f57b387e223dbfc2
refs/heads/Win2K3
2023-08-12T01:31:59.670176
2021-10-14T15:14:37
2021-10-14T15:14:37
586,134,273
1
0
null
2023-01-07T03:47:45
2023-01-07T03:47:44
null
UTF-8
C++
false
false
789
h
#ifndef __ISO8601_H #define __ISO8601_H #define ISO8601_ST_YEAR 0x00000001 #define ISO8601_ST_MONTH 0x00000002 #define ISO8601_ST_DAYOFWEEK 0x00000004 #define ISO8601_ST_DAY 0x00000008 #define ISO8601_ST_HOUR 0x00000010 #define ISO8601_ST_MINUTE 0x00000020 #define ISO8601_ST_MILLISEC 0x00000040 class iso8601 { public: static HRESULT toSystemTime(char *pszISODate, SYSTEMTIME *pst, DWORD *pdwFlags, BOOL fLenient = TRUE, BOOL fPartial = TRUE); static HRESULT toFileTime(char *pszISODate, FILETIME *pft, DWORD *pdwFlags, BOOL fLenient = TRUE, BOOL fPartial = TRUE); static HRESULT fromSystemTime(SYSTEMTIME *pst, char *pszISODate); static HRESULT fromFileTime(FILETIME *pft, char *pszISOData); }; #endif
[ "seta7D5@protonmail.com" ]
seta7D5@protonmail.com
0ce7ce3f82ace331c66fb6f411bd7c5ea1bae90e
d86d61437208fde5a7cd7edb599496e5c69b0702
/Plugin~/Src/MeshSync/Utils/msDebug.h
15c73c60a001673b0e5d8e91882ea5276a4d4658
[ "MIT", "GPL-1.0-or-later", "GPL-3.0-only", "Apache-2.0", "GPL-3.0-or-later" ]
permissive
FrogsInSpace/MeshSync
6d67d1902123f5745b41fdba10b4008b77510796
c345cf81ed5d423fa866bb3771f7ac5f74e76b9d
refs/heads/master
2023-04-07T05:12:34.535742
2023-03-16T05:39:11
2023-03-16T05:39:11
149,847,579
0
0
MIT
2018-09-22T05:12:34
2018-09-22T05:12:34
null
UTF-8
C++
false
false
350
h
#pragma once #include "MeshUtils/MeshUtils.h" #ifdef msDebug //#define msDbgEnableProfile #endif namespace ms { #ifdef msDbgEnableProfile #define msProfileScope(Message, ...) mu::ProfileTimer _prof_timer(Message, __VA_ARGS__) #else // msDbgEnableProfile #define msProfileScope(Message, ...) #endif // msDbgEnableProfile } // namespace ms
[ "saint.skr@gmail.com" ]
saint.skr@gmail.com
4e4c34a00f6a6d33f8a662923ef7f48147d32105
7a0d7c572ae3026810d61c057292ce707b6df170
/xxTest/stdafx.cpp
e7c1625ad36b300dff09ceca846673b3ca4d5cae
[]
no_license
riceWithoutIce/xxTea
684c4c2e8849d72e35c4f60bee90c466d32640c4
a18dbfb39ff7f3dae6beb8e69b234fba472e2920
refs/heads/master
2021-01-10T05:07:36.885865
2015-10-16T08:38:07
2015-10-16T08:38:07
43,296,398
0
1
null
null
null
null
GB18030
C++
false
false
259
cpp
// stdafx.cpp : 只包括标准包含文件的源文件 // xxTest.pch 将作为预编译头 // stdafx.obj 将包含预编译类型信息 #include "stdafx.h" // TODO: 在 STDAFX.H 中 // 引用任何所需的附加头文件,而不是在此文件中引用
[ "1433996455@qq.com" ]
1433996455@qq.com
c91ee3129239efb7abb945c19997f8989f140038
dee2ec2a89e1a8b90712acc2c915e1350a01aa3e
/pessoal/revolver.cpp
45da60d007c45739c3ecf8b67768e50ab6b40319
[]
no_license
Ramonlobo633/CGProject
a070764b6bfe5eb827a1ddcac41ac052636dcec3
ce7eb7448d95e6df49a5d100d9dd0e998f2868aa
refs/heads/master
2023-04-08T17:52:23.572427
2021-04-11T06:53:31
2021-04-11T06:53:31
356,069,041
1
0
null
null
null
null
UTF-8
C++
false
false
1,022
cpp
#include "revolver.h" Revolver::Revolver() { model = new Model3DS("../3ds/revolver/Revolver.3ds"); } void Revolver::desenha() { glPushMatrix(); Objeto::desenha(); //GUI::setColor(0.7,0.7,0.7); if (selecionado) { //glEnable(GL_CULL_FACE); GUI::setColor(0.1,0.1,0.1); //GUI::drawBox(-1,-1,-1, 1,1,1, true); } glScalef(6,6,6.2); //ajuste final da escala, podendo ser não-uniforme, independente para cada eixo glRotatef(0,1,0,0); //alinhar o objeto 3ds com os eixos, deixando ele para cima de acordo com o eixo Y glTranslatef(2,0,0); //trazer objeto 3ds para origem glScalef(0.001,0.001,0.001); //apenas para conseguir enxergar o modelo 3ds model->draw(!selecionado); //se estiver selecionado, tem que desenhar o modelo 3ds //não colorido internamente para que a cor de destaque //da seleção tenha efeito glPopMatrix(); }
[ "ramonlobo633@gmail.com" ]
ramonlobo633@gmail.com
fe8301659d3fd01eeeb076060ff948eeb5b4e1ae
ea4274d7f921790c7dd9c7a28dc61692072e61b8
/udp_receiver/receive_copy.h
f7e94947928af57631ac7e3898c760f33177dc1c
[]
no_license
Kelleykuang/GUI-udp
235f4436ca3118be20733ace34194a9a6cfefae1
1c81915a5cf751e72f1b975b391c3c9d8ef57f38
refs/heads/master
2020-06-21T13:36:15.313148
2019-07-18T07:19:29
2019-07-18T07:19:29
197,468,405
0
0
null
null
null
null
UTF-8
C++
false
false
670
h
#ifndef PAINT_H #define PAINT_H #include <QWidget> #include <QList> #include <QChart> #include <QSplineSeries> #include <QScatterSeries> #include <QChartView> #include <QTime> #include <QUdpSocket> #include <QtNetwork> #include "common.h" using namespace QtCharts; class RealTimeCurveQChartWidget : public QObject { Q_OBJECT public: explicit RealTimeCurveQChartWidget(QObject *parent = 0); public slots: void painting(); protected: void timerEvent(QTimerEvent *event) Q_DECL_OVERRIDE; private: int maxSize; int dx; int data; int timerId; //计数器 int times; }; #endif // PAINT_H
[ "kelleykuang@mail.ustc.edu.cn" ]
kelleykuang@mail.ustc.edu.cn
b75f999b3a695ebfad5a6ba66d842db31e950618
b9e1c3de01c323ca5f82863b88d8e4b99e8e449a
/Tests/BT_driver_work_with_bytes_array/BT_driver_work_with_bytes_array.ino
d147e780c1a00f0e9d27873e186d116ad6319e62
[]
no_license
xpanis/DP
0bb9142387952bc2f1a40075ff8ea5bd4398b836
1552794a6dc14a79586565bdbf6d388c4064bb1a
refs/heads/master
2021-05-14T04:54:40.500838
2018-05-11T20:01:03
2018-05-11T20:01:03
116,654,530
0
0
null
null
null
null
UTF-8
C++
false
false
1,169
ino
byte input_msg[102]; input_packet_buffer byte output_msg[98]; - packet_buffer int real_length = 0; bool is_next_zero = false; int myTimeout = 250; // milliseconds for Serial.readString void setup() { Serial.begin(9600); // Default communication rate of the Bluetooth module Serial.setTimeout(myTimeout); for (int i = 0; i < 102; i++) { input_msg[i] = 0; if (i < 98) { output_msg[i] = 0; } } } void loop() { if (Serial.available()) { Serial.readBytes(input_msg, 102); Serial.write(input_msg, 102); if ((input_msg[0] == 255) && (input_msg[1] == 255)) { for (int i = 0; i < 98; i++) { is_next_zero = (input_msg[i + 4] == 0)? true : false; if ((input_msg[i + 2] == 255) && (input_msg[i + 3] == 255) && is_next_zero) { break; } else { output_msg[i] = input_msg[i + 2]; real_length++; } } Serial.write(output_msg, real_length); for (int i = 0; i < 102; i++) { input_msg[i] = 0; } real_length = 0; } } delay(5000); }
[ "panis1994@gmail.com" ]
panis1994@gmail.com
6e69b22021595cb9e2bc52498d4b98002b7b5f63
0ff4e0ce79bb46b097420918e122473a2235b438
/src/util.cpp
42221d49e25be352209ef2599b51a684e22cb083
[ "MIT" ]
permissive
indokathan/instacoin
a053eb6c8673c1dad32e5522b14129e6204cdce3
b8522facd16b356434508a1ff9476f9f70252889
refs/heads/master
2021-09-03T12:16:41.191831
2018-01-09T01:58:10
2018-01-09T01:58:10
116,733,634
0
0
null
null
null
null
UTF-8
C++
false
false
36,653
cpp
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2012 The Bitcoin developers // Copyright (c) 2011-2012 Litecoin Developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "util.h" #include "sync.h" #include "strlcpy.h" #include "version.h" #include "ui_interface.h" #include <boost/algorithm/string/join.hpp> // Work around clang compilation problem in Boost 1.46: // /usr/include/boost/program_options/detail/config_file.hpp:163:17: error: call to function 'to_internal' that is neither visible in the template definition nor found by argument-dependent lookup // See also: http://stackoverflow.com/questions/10020179/compilation-fail-in-boost-librairies-program-options // http://clang.debian.net/status.php?version=3.0&key=CANNOT_FIND_FUNCTION namespace boost { namespace program_options { std::string to_internal(const std::string&); } } #include <boost/program_options/detail/config_file.hpp> #include <boost/program_options/parsers.hpp> #include <boost/filesystem.hpp> #include <boost/filesystem/fstream.hpp> #include <boost/foreach.hpp> #include <boost/thread.hpp> #include <openssl/crypto.h> #include <openssl/rand.h> #include <stdarg.h> #ifdef WIN32 #ifdef _MSC_VER #pragma warning(disable:4786) #pragma warning(disable:4804) #pragma warning(disable:4805) #pragma warning(disable:4717) #endif #ifdef _WIN32_WINNT #undef _WIN32_WINNT #endif #define _WIN32_WINNT 0x0501 #ifdef _WIN32_IE #undef _WIN32_IE #endif #define _WIN32_IE 0x0501 #define WIN32_LEAN_AND_MEAN 1 #ifndef NOMINMAX #define NOMINMAX #endif #include <io.h> /* for _commit */ #include "shlobj.h" #elif defined(__linux__) # include <sys/prctl.h> #endif using namespace std; map<string, string> mapArgs; map<string, vector<string> > mapMultiArgs; bool fDebug = false; bool fDebugNet = false; bool fPrintToConsole = false; bool fPrintToDebugger = false; bool fRequestShutdown = false; bool fShutdown = false; bool fDaemon = false; bool fServer = false; bool fCommandLine = false; string strMiscWarning; bool fTestNet = false; bool fNoListen = false; bool fLogTimestamps = false; CMedianFilter<int64> vTimeOffsets(200,0); bool fReopenDebugLog = false; // Init openssl library multithreading support static CCriticalSection** ppmutexOpenSSL; void locking_callback(int mode, int i, const char* file, int line) { if (mode & CRYPTO_LOCK) { ENTER_CRITICAL_SECTION(*ppmutexOpenSSL[i]); } else { LEAVE_CRITICAL_SECTION(*ppmutexOpenSSL[i]); } } // Init class CInit { public: CInit() { // Init openssl library multithreading support ppmutexOpenSSL = (CCriticalSection**)OPENSSL_malloc(CRYPTO_num_locks() * sizeof(CCriticalSection*)); for (int i = 0; i < CRYPTO_num_locks(); i++) ppmutexOpenSSL[i] = new CCriticalSection(); CRYPTO_set_locking_callback(locking_callback); #ifdef WIN32 // Seed random number generator with screen scrape and other hardware sources RAND_screen(); #endif // Seed random number generator with performance counter RandAddSeed(); } ~CInit() { // Shutdown openssl library multithreading support CRYPTO_set_locking_callback(NULL); for (int i = 0; i < CRYPTO_num_locks(); i++) delete ppmutexOpenSSL[i]; OPENSSL_free(ppmutexOpenSSL); } } instance_of_cinit; void RandAddSeed() { // Seed with CPU performance counter int64 nCounter = GetPerformanceCounter(); RAND_add(&nCounter, sizeof(nCounter), 1.5); memset(&nCounter, 0, sizeof(nCounter)); } void RandAddSeedPerfmon() { RandAddSeed(); // This can take up to 2 seconds, so only do it every 10 minutes static int64 nLastPerfmon; if (GetTime() < nLastPerfmon + 10 * 60) return; nLastPerfmon = GetTime(); #ifdef WIN32 // Don't need this on Linux, OpenSSL automatically uses /dev/urandom // Seed with the entire set of perfmon data unsigned char pdata[250000]; memset(pdata, 0, sizeof(pdata)); unsigned long nSize = sizeof(pdata); long ret = RegQueryValueExA(HKEY_PERFORMANCE_DATA, "Global", NULL, NULL, pdata, &nSize); RegCloseKey(HKEY_PERFORMANCE_DATA); if (ret == ERROR_SUCCESS) { RAND_add(pdata, nSize, nSize/100.0); memset(pdata, 0, nSize); printf("RandAddSeed() %d bytes\n", nSize); } #endif } uint64 GetRand(uint64 nMax) { if (nMax == 0) return 0; // The range of the random source must be a multiple of the modulus // to give every possible output value an equal possibility uint64 nRange = (std::numeric_limits<uint64>::max() / nMax) * nMax; uint64 nRand = 0; do RAND_bytes((unsigned char*)&nRand, sizeof(nRand)); while (nRand >= nRange); return (nRand % nMax); } int GetRandInt(int nMax) { return GetRand(nMax); } uint256 GetRandHash() { uint256 hash; RAND_bytes((unsigned char*)&hash, sizeof(hash)); return hash; } inline int OutputDebugStringF(const char* pszFormat, ...) { int ret = 0; if (fPrintToConsole) { // print to console va_list arg_ptr; va_start(arg_ptr, pszFormat); ret = vprintf(pszFormat, arg_ptr); va_end(arg_ptr); } else { // print to debug.log static FILE* fileout = NULL; if (!fileout) { boost::filesystem::path pathDebug = GetDataDir() / "debug.log"; fileout = fopen(pathDebug.string().c_str(), "a"); if (fileout) setbuf(fileout, NULL); // unbuffered } if (fileout) { static bool fStartedNewLine = true; static boost::mutex mutexDebugLog; boost::mutex::scoped_lock scoped_lock(mutexDebugLog); // reopen the log file, if requested if (fReopenDebugLog) { fReopenDebugLog = false; boost::filesystem::path pathDebug = GetDataDir() / "debug.log"; if (freopen(pathDebug.string().c_str(),"a",fileout) != NULL) setbuf(fileout, NULL); // unbuffered } // Debug print useful for profiling if (fLogTimestamps && fStartedNewLine) fprintf(fileout, "%s ", DateTimeStrFormat("%x %H:%M:%S", GetTime()).c_str()); if (pszFormat[strlen(pszFormat) - 1] == '\n') fStartedNewLine = true; else fStartedNewLine = false; va_list arg_ptr; va_start(arg_ptr, pszFormat); ret = vfprintf(fileout, pszFormat, arg_ptr); va_end(arg_ptr); } } #ifdef WIN32 if (fPrintToDebugger) { static CCriticalSection cs_OutputDebugStringF; // accumulate and output a line at a time { LOCK(cs_OutputDebugStringF); static std::string buffer; va_list arg_ptr; va_start(arg_ptr, pszFormat); buffer += vstrprintf(pszFormat, arg_ptr); va_end(arg_ptr); int line_start = 0, line_end; while((line_end = buffer.find('\n', line_start)) != -1) { OutputDebugStringA(buffer.substr(line_start, line_end - line_start).c_str()); line_start = line_end + 1; } buffer.erase(0, line_start); } } #endif return ret; } string vstrprintf(const std::string &format, va_list ap) { char buffer[50000]; char* p = buffer; int limit = sizeof(buffer); int ret; loop { va_list arg_ptr; va_copy(arg_ptr, ap); ret = _vsnprintf(p, limit, format.c_str(), arg_ptr); va_end(arg_ptr); if (ret >= 0 && ret < limit) break; if (p != buffer) delete[] p; limit *= 2; p = new char[limit]; if (p == NULL) throw std::bad_alloc(); } string str(p, p+ret); if (p != buffer) delete[] p; return str; } string real_strprintf(const std::string &format, int dummy, ...) { va_list arg_ptr; va_start(arg_ptr, dummy); string str = vstrprintf(format, arg_ptr); va_end(arg_ptr); return str; } bool error(const char *format, ...) { va_list arg_ptr; va_start(arg_ptr, format); std::string str = vstrprintf(format, arg_ptr); va_end(arg_ptr); printf("ERROR: %s\n", str.c_str()); return false; } void ParseString(const string& str, char c, vector<string>& v) { if (str.empty()) return; string::size_type i1 = 0; string::size_type i2; loop { i2 = str.find(c, i1); if (i2 == str.npos) { v.push_back(str.substr(i1)); return; } v.push_back(str.substr(i1, i2-i1)); i1 = i2+1; } } string FormatMoney(int64 n, bool fPlus) { // Note: not using straight sprintf here because we do NOT want // localized number formatting. int64 n_abs = (n > 0 ? n : -n); int64 quotient = n_abs/COIN; int64 remainder = n_abs%COIN; string str = strprintf("%"PRI64d".%08"PRI64d, quotient, remainder); // Right-trim excess 0's before the decimal point: int nTrim = 0; for (int i = str.size()-1; (str[i] == '0' && isdigit(str[i-2])); --i) ++nTrim; if (nTrim) str.erase(str.size()-nTrim, nTrim); if (n < 0) str.insert((unsigned int)0, 1, '-'); else if (fPlus && n > 0) str.insert((unsigned int)0, 1, '+'); return str; } bool ParseMoney(const string& str, int64& nRet) { return ParseMoney(str.c_str(), nRet); } bool ParseMoney(const char* pszIn, int64& nRet) { string strWhole; int64 nUnits = 0; const char* p = pszIn; while (isspace(*p)) p++; for (; *p; p++) { if (*p == '.') { p++; int64 nMult = CENT*10; while (isdigit(*p) && (nMult > 0)) { nUnits += nMult * (*p++ - '0'); nMult /= 10; } break; } if (isspace(*p)) break; if (!isdigit(*p)) return false; strWhole.insert(strWhole.end(), *p); } for (; *p; p++) if (!isspace(*p)) return false; if (strWhole.size() > 10) // guard against 63 bit overflow return false; if (nUnits < 0 || nUnits > COIN) return false; int64 nWhole = atoi64(strWhole); int64 nValue = nWhole*COIN + nUnits; nRet = nValue; return true; } static signed char phexdigit[256] = { -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, 0,1,2,3,4,5,6,7,8,9,-1,-1,-1,-1,-1,-1, -1,0xa,0xb,0xc,0xd,0xe,0xf,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,0xa,0xb,0xc,0xd,0xe,0xf,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, }; bool IsHex(const string& str) { BOOST_FOREACH(unsigned char c, str) { if (phexdigit[c] < 0) return false; } return (str.size() > 0) && (str.size()%2 == 0); } vector<unsigned char> ParseHex(const char* psz) { // convert hex dump to vector vector<unsigned char> vch; loop { while (isspace(*psz)) psz++; signed char c = phexdigit[(unsigned char)*psz++]; if (c == (signed char)-1) break; unsigned char n = (c << 4); c = phexdigit[(unsigned char)*psz++]; if (c == (signed char)-1) break; n |= c; vch.push_back(n); } return vch; } vector<unsigned char> ParseHex(const string& str) { return ParseHex(str.c_str()); } static void InterpretNegativeSetting(string name, map<string, string>& mapSettingsRet) { // interpret -nofoo as -foo=0 (and -nofoo=0 as -foo=1) as long as -foo not set if (name.find("-no") == 0) { std::string positive("-"); positive.append(name.begin()+3, name.end()); if (mapSettingsRet.count(positive) == 0) { bool value = !GetBoolArg(name); mapSettingsRet[positive] = (value ? "1" : "0"); } } } void ParseParameters(int argc, const char* const argv[]) { mapArgs.clear(); mapMultiArgs.clear(); for (int i = 1; i < argc; i++) { char psz[10000]; strlcpy(psz, argv[i], sizeof(psz)); char* pszValue = (char*)""; if (strchr(psz, '=')) { pszValue = strchr(psz, '='); *pszValue++ = '\0'; } #ifdef WIN32 _strlwr(psz); if (psz[0] == '/') psz[0] = '-'; #endif if (psz[0] != '-') break; mapArgs[psz] = pszValue; mapMultiArgs[psz].push_back(pszValue); } // New 0.6 features: BOOST_FOREACH(const PAIRTYPE(string,string)& entry, mapArgs) { string name = entry.first; // interpret --foo as -foo (as long as both are not set) if (name.find("--") == 0) { std::string singleDash(name.begin()+1, name.end()); if (mapArgs.count(singleDash) == 0) mapArgs[singleDash] = entry.second; name = singleDash; } // interpret -nofoo as -foo=0 (and -nofoo=0 as -foo=1) as long as -foo not set InterpretNegativeSetting(name, mapArgs); } } std::string GetArg(const std::string& strArg, const std::string& strDefault) { if (mapArgs.count(strArg)) return mapArgs[strArg]; return strDefault; } int64 GetArg(const std::string& strArg, int64 nDefault) { if (mapArgs.count(strArg)) return atoi64(mapArgs[strArg]); return nDefault; } bool GetBoolArg(const std::string& strArg, bool fDefault) { if (mapArgs.count(strArg)) { if (mapArgs[strArg].empty()) return true; return (atoi(mapArgs[strArg]) != 0); } return fDefault; } bool SoftSetArg(const std::string& strArg, const std::string& strValue) { if (mapArgs.count(strArg)) return false; mapArgs[strArg] = strValue; return true; } bool SoftSetBoolArg(const std::string& strArg, bool fValue) { if (fValue) return SoftSetArg(strArg, std::string("1")); else return SoftSetArg(strArg, std::string("0")); } string EncodeBase64(const unsigned char* pch, size_t len) { static const char *pbase64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; string strRet=""; strRet.reserve((len+2)/3*4); int mode=0, left=0; const unsigned char *pchEnd = pch+len; while (pch<pchEnd) { int enc = *(pch++); switch (mode) { case 0: // we have no bits strRet += pbase64[enc >> 2]; left = (enc & 3) << 4; mode = 1; break; case 1: // we have two bits strRet += pbase64[left | (enc >> 4)]; left = (enc & 15) << 2; mode = 2; break; case 2: // we have four bits strRet += pbase64[left | (enc >> 6)]; strRet += pbase64[enc & 63]; mode = 0; break; } } if (mode) { strRet += pbase64[left]; strRet += '='; if (mode == 1) strRet += '='; } return strRet; } string EncodeBase64(const string& str) { return EncodeBase64((const unsigned char*)str.c_str(), str.size()); } vector<unsigned char> DecodeBase64(const char* p, bool* pfInvalid) { static const int decode64_table[256] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 62, -1, -1, -1, 63, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1, -1, -1, -1, -1, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1, -1, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }; if (pfInvalid) *pfInvalid = false; vector<unsigned char> vchRet; vchRet.reserve(strlen(p)*3/4); int mode = 0; int left = 0; while (1) { int dec = decode64_table[(unsigned char)*p]; if (dec == -1) break; p++; switch (mode) { case 0: // we have no bits and get 6 left = dec; mode = 1; break; case 1: // we have 6 bits and keep 4 vchRet.push_back((left<<2) | (dec>>4)); left = dec & 15; mode = 2; break; case 2: // we have 4 bits and get 6, we keep 2 vchRet.push_back((left<<4) | (dec>>2)); left = dec & 3; mode = 3; break; case 3: // we have 2 bits and get 6 vchRet.push_back((left<<6) | dec); mode = 0; break; } } if (pfInvalid) switch (mode) { case 0: // 4n base64 characters processed: ok break; case 1: // 4n+1 base64 character processed: impossible *pfInvalid = true; break; case 2: // 4n+2 base64 characters processed: require '==' if (left || p[0] != '=' || p[1] != '=' || decode64_table[(unsigned char)p[2]] != -1) *pfInvalid = true; break; case 3: // 4n+3 base64 characters processed: require '=' if (left || p[0] != '=' || decode64_table[(unsigned char)p[1]] != -1) *pfInvalid = true; break; } return vchRet; } string DecodeBase64(const string& str) { vector<unsigned char> vchRet = DecodeBase64(str.c_str()); return string((const char*)&vchRet[0], vchRet.size()); } string EncodeBase32(const unsigned char* pch, size_t len) { static const char *pbase32 = "abcdefghijklmnopqrstuvwxyz234567"; string strRet=""; strRet.reserve((len+4)/5*8); int mode=0, left=0; const unsigned char *pchEnd = pch+len; while (pch<pchEnd) { int enc = *(pch++); switch (mode) { case 0: // we have no bits strRet += pbase32[enc >> 3]; left = (enc & 7) << 2; mode = 1; break; case 1: // we have three bits strRet += pbase32[left | (enc >> 6)]; strRet += pbase32[(enc >> 1) & 31]; left = (enc & 1) << 4; mode = 2; break; case 2: // we have one bit strRet += pbase32[left | (enc >> 4)]; left = (enc & 15) << 1; mode = 3; break; case 3: // we have four bits strRet += pbase32[left | (enc >> 7)]; strRet += pbase32[(enc >> 2) & 31]; left = (enc & 3) << 3; mode = 4; break; case 4: // we have two bits strRet += pbase32[left | (enc >> 5)]; strRet += pbase32[enc & 31]; mode = 0; } } static const int nPadding[5] = {0, 6, 4, 3, 1}; if (mode) { strRet += pbase32[left]; for (int n=0; n<nPadding[mode]; n++) strRet += '='; } return strRet; } string EncodeBase32(const string& str) { return EncodeBase32((const unsigned char*)str.c_str(), str.size()); } vector<unsigned char> DecodeBase32(const char* p, bool* pfInvalid) { static const int decode32_table[256] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 26, 27, 28, 29, 30, 31, -1, -1, -1, -1, -1, -1, -1, -1, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }; if (pfInvalid) *pfInvalid = false; vector<unsigned char> vchRet; vchRet.reserve((strlen(p))*5/8); int mode = 0; int left = 0; while (1) { int dec = decode32_table[(unsigned char)*p]; if (dec == -1) break; p++; switch (mode) { case 0: // we have no bits and get 5 left = dec; mode = 1; break; case 1: // we have 5 bits and keep 2 vchRet.push_back((left<<3) | (dec>>2)); left = dec & 3; mode = 2; break; case 2: // we have 2 bits and keep 7 left = left << 5 | dec; mode = 3; break; case 3: // we have 7 bits and keep 4 vchRet.push_back((left<<1) | (dec>>4)); left = dec & 15; mode = 4; break; case 4: // we have 4 bits, and keep 1 vchRet.push_back((left<<4) | (dec>>1)); left = dec & 1; mode = 5; break; case 5: // we have 1 bit, and keep 6 left = left << 5 | dec; mode = 6; break; case 6: // we have 6 bits, and keep 3 vchRet.push_back((left<<2) | (dec>>3)); left = dec & 7; mode = 7; break; case 7: // we have 3 bits, and keep 0 vchRet.push_back((left<<5) | dec); mode = 0; break; } } if (pfInvalid) switch (mode) { case 0: // 8n base32 characters processed: ok break; case 1: // 8n+1 base32 characters processed: impossible case 3: // +3 case 6: // +6 *pfInvalid = true; break; case 2: // 8n+2 base32 characters processed: require '======' if (left || p[0] != '=' || p[1] != '=' || p[2] != '=' || p[3] != '=' || p[4] != '=' || p[5] != '=' || decode32_table[(unsigned char)p[6]] != -1) *pfInvalid = true; break; case 4: // 8n+4 base32 characters processed: require '====' if (left || p[0] != '=' || p[1] != '=' || p[2] != '=' || p[3] != '=' || decode32_table[(unsigned char)p[4]] != -1) *pfInvalid = true; break; case 5: // 8n+5 base32 characters processed: require '===' if (left || p[0] != '=' || p[1] != '=' || p[2] != '=' || decode32_table[(unsigned char)p[3]] != -1) *pfInvalid = true; break; case 7: // 8n+7 base32 characters processed: require '=' if (left || p[0] != '=' || decode32_table[(unsigned char)p[1]] != -1) *pfInvalid = true; break; } return vchRet; } string DecodeBase32(const string& str) { vector<unsigned char> vchRet = DecodeBase32(str.c_str()); return string((const char*)&vchRet[0], vchRet.size()); } bool WildcardMatch(const char* psz, const char* mask) { loop { switch (*mask) { case '\0': return (*psz == '\0'); case '*': return WildcardMatch(psz, mask+1) || (*psz && WildcardMatch(psz+1, mask)); case '?': if (*psz == '\0') return false; break; default: if (*psz != *mask) return false; break; } psz++; mask++; } } bool WildcardMatch(const string& str, const string& mask) { return WildcardMatch(str.c_str(), mask.c_str()); } static std::string FormatException(std::exception* pex, const char* pszThread) { #ifdef WIN32 char pszModule[MAX_PATH] = ""; GetModuleFileNameA(NULL, pszModule, sizeof(pszModule)); #else const char* pszModule = "instacoin"; #endif if (pex) return strprintf( "EXCEPTION: %s \n%s \n%s in %s \n", typeid(*pex).name(), pex->what(), pszModule, pszThread); else return strprintf( "UNKNOWN EXCEPTION \n%s in %s \n", pszModule, pszThread); } void LogException(std::exception* pex, const char* pszThread) { std::string message = FormatException(pex, pszThread); printf("\n%s", message.c_str()); } void PrintException(std::exception* pex, const char* pszThread) { std::string message = FormatException(pex, pszThread); printf("\n\n************************\n%s\n", message.c_str()); fprintf(stderr, "\n\n************************\n%s\n", message.c_str()); strMiscWarning = message; throw; } void PrintExceptionContinue(std::exception* pex, const char* pszThread) { std::string message = FormatException(pex, pszThread); printf("\n\n************************\n%s\n", message.c_str()); fprintf(stderr, "\n\n************************\n%s\n", message.c_str()); strMiscWarning = message; } boost::filesystem::path GetDefaultDataDir() { namespace fs = boost::filesystem; // Windows < Vista: C:\Documents and Settings\Username\Application Data\InstaCoin // Windows >= Vista: C:\Users\Username\AppData\Roaming\InstaCoin // Mac: ~/Library/Application Support/InstaCoin // Unix: ~/.instacoin #ifdef WIN32 // Windows return GetSpecialFolderPath(CSIDL_APPDATA) / "InstaCoin"; #else fs::path pathRet; char* pszHome = getenv("HOME"); if (pszHome == NULL || strlen(pszHome) == 0) pathRet = fs::path("/"); else pathRet = fs::path(pszHome); #ifdef MAC_OSX // Mac pathRet /= "Library/Application Support"; fs::create_directory(pathRet); return pathRet / "InstaCoin"; #else // Unix return pathRet / ".instacoin"; #endif #endif } const boost::filesystem::path &GetDataDir(bool fNetSpecific) { namespace fs = boost::filesystem; static fs::path pathCached[2]; static CCriticalSection csPathCached; static bool cachedPath[2] = {false, false}; fs::path &path = pathCached[fNetSpecific]; // This can be called during exceptions by printf, so we cache the // value so we don't have to do memory allocations after that. if (cachedPath[fNetSpecific]) return path; LOCK(csPathCached); if (mapArgs.count("-datadir")) { path = fs::system_complete(mapArgs["-datadir"]); if (!fs::is_directory(path)) { path = ""; return path; } } else { path = GetDefaultDataDir(); } if (fNetSpecific && GetBoolArg("-testnet", false)) path /= "testnet3"; fs::create_directory(path); cachedPath[fNetSpecific]=true; return path; } boost::filesystem::path GetConfigFile() { boost::filesystem::path pathConfigFile(GetArg("-conf", "instacoin.conf")); if (!pathConfigFile.is_complete()) pathConfigFile = GetDataDir(false) / pathConfigFile; return pathConfigFile; } void ReadConfigFile(map<string, string>& mapSettingsRet, map<string, vector<string> >& mapMultiSettingsRet) { boost::filesystem::ifstream streamConfig(GetConfigFile()); if (!streamConfig.good()) return; // No instacoin.conf file is OK set<string> setOptions; setOptions.insert("*"); for (boost::program_options::detail::config_file_iterator it(streamConfig, setOptions), end; it != end; ++it) { // Don't overwrite existing settings so command line settings override instacoin.conf string strKey = string("-") + it->string_key; if (mapSettingsRet.count(strKey) == 0) { mapSettingsRet[strKey] = it->value[0]; // interpret nofoo=1 as foo=0 (and nofoo=0 as foo=1) as long as foo not set) InterpretNegativeSetting(strKey, mapSettingsRet); } mapMultiSettingsRet[strKey].push_back(it->value[0]); } } boost::filesystem::path GetPidFile() { boost::filesystem::path pathPidFile(GetArg("-pid", "instacoin.pid")); if (!pathPidFile.is_complete()) pathPidFile = GetDataDir() / pathPidFile; return pathPidFile; } void CreatePidFile(const boost::filesystem::path &path, pid_t pid) { FILE* file = fopen(path.string().c_str(), "w"); if (file) { fprintf(file, "%d\n", pid); fclose(file); } } bool RenameOver(boost::filesystem::path src, boost::filesystem::path dest) { #ifdef WIN32 return MoveFileExA(src.string().c_str(), dest.string().c_str(), MOVEFILE_REPLACE_EXISTING); #else int rc = std::rename(src.string().c_str(), dest.string().c_str()); return (rc == 0); #endif /* WIN32 */ } void FileCommit(FILE *fileout) { fflush(fileout); // harmless if redundantly called #ifdef WIN32 _commit(_fileno(fileout)); #else fsync(fileno(fileout)); #endif } int GetFilesize(FILE* file) { int nSavePos = ftell(file); int nFilesize = -1; if (fseek(file, 0, SEEK_END) == 0) nFilesize = ftell(file); fseek(file, nSavePos, SEEK_SET); return nFilesize; } void ShrinkDebugFile() { // Scroll debug.log if it's getting too big boost::filesystem::path pathLog = GetDataDir() / "debug.log"; FILE* file = fopen(pathLog.string().c_str(), "r"); if (file && GetFilesize(file) > 10 * 1000000) { // Restart the file with some of the end char pch[200000]; fseek(file, -sizeof(pch), SEEK_END); int nBytes = fread(pch, 1, sizeof(pch), file); fclose(file); file = fopen(pathLog.string().c_str(), "w"); if (file) { fwrite(pch, 1, nBytes, file); fclose(file); } } } // // "Never go to sea with two chronometers; take one or three." // Our three time sources are: // - System clock // - Median of other nodes clocks // - The user (asking the user to fix the system clock if the first two disagree) // static int64 nMockTime = 0; // For unit testing int64 GetTime() { if (nMockTime) return nMockTime; return time(NULL); } void SetMockTime(int64 nMockTimeIn) { nMockTime = nMockTimeIn; } static int64 nTimeOffset = 0; int64 GetAdjustedTime() { return GetTime() + nTimeOffset; } void AddTimeData(const CNetAddr& ip, int64 nTime) { int64 nOffsetSample = nTime - GetTime(); // Ignore duplicates static set<CNetAddr> setKnown; if (!setKnown.insert(ip).second) return; // Add data vTimeOffsets.input(nOffsetSample); printf("Added time data, samples %d, offset %+"PRI64d" (%+"PRI64d" minutes)\n", vTimeOffsets.size(), nOffsetSample, nOffsetSample/60); if (vTimeOffsets.size() >= 5 && vTimeOffsets.size() % 2 == 1) { int64 nMedian = vTimeOffsets.median(); std::vector<int64> vSorted = vTimeOffsets.sorted(); // Only let other nodes change our time by so much if (abs64(nMedian) < 35 * 60) // changed maximum adjust to 35 mins to avoid letting peers change our time too much in case of an attack. { nTimeOffset = nMedian; } else { nTimeOffset = 0; static bool fDone; if (!fDone) { // If nobody has a time different than ours but within 5 minutes of ours, give a warning bool fMatch = false; BOOST_FOREACH(int64 nOffset, vSorted) if (nOffset != 0 && abs64(nOffset) < 5 * 60) fMatch = true; if (!fMatch) { fDone = true; string strMessage = _("Warning: Please check that your computer's date and time are correct. If your clock is wrong InstaCoin will not work properly."); strMiscWarning = strMessage; printf("*** %s\n", strMessage.c_str()); uiInterface.ThreadSafeMessageBox(strMessage+" ", string("InstaCoin"), CClientUIInterface::OK | CClientUIInterface::ICON_EXCLAMATION); } } } if (fDebug) { BOOST_FOREACH(int64 n, vSorted) printf("%+"PRI64d" ", n); printf("| "); } printf("nTimeOffset = %+"PRI64d" (%+"PRI64d" minutes)\n", nTimeOffset, nTimeOffset/60); } } string FormatVersion(int nVersion) { if (nVersion%100 == 0) return strprintf("%d.%d.%d", nVersion/1000000, (nVersion/10000)%100, (nVersion/100)%100); else return strprintf("%d.%d.%d.%d", nVersion/1000000, (nVersion/10000)%100, (nVersion/100)%100, nVersion%100); } string FormatFullVersion() { return CLIENT_BUILD; } // Format the subversion field according to BIP 14 spec (https://en.bitcoin.it/wiki/BIP_0014) std::string FormatSubVersion(const std::string& name, int nClientVersion, const std::vector<std::string>& comments) { std::ostringstream ss; ss << "/"; ss << name << ":" << FormatVersion(nClientVersion); if (!comments.empty()) ss << "(" << boost::algorithm::join(comments, "; ") << ")"; ss << "/"; return ss.str(); } #ifdef WIN32 boost::filesystem::path GetSpecialFolderPath(int nFolder, bool fCreate) { namespace fs = boost::filesystem; char pszPath[MAX_PATH] = ""; if(SHGetSpecialFolderPathA(NULL, pszPath, nFolder, fCreate)) { return fs::path(pszPath); } printf("SHGetSpecialFolderPathA() failed, could not obtain requested path.\n"); return fs::path(""); } #endif void runCommand(std::string strCommand) { int nErr = ::system(strCommand.c_str()); if (nErr) printf("runCommand error: system(%s) returned %d\n", strCommand.c_str(), nErr); } void RenameThread(const char* name) { #if defined(PR_SET_NAME) // Only the first 15 characters are used (16 - NUL terminator) ::prctl(PR_SET_NAME, name, 0, 0, 0); #elif 0 && (defined(__FreeBSD__) || defined(__OpenBSD__)) // TODO: This is currently disabled because it needs to be verified to work // on FreeBSD or OpenBSD first. When verified the '0 &&' part can be // removed. pthread_set_name_np(pthread_self(), name); #elif defined(MAC_OSX) pthread_setname_np(name); #else // Prevent warnings for unused parameters... (void)name; #endif }
[ "kathan_369@yahoo.com" ]
kathan_369@yahoo.com
35a73cdc341125fd72f1769dcc1b6380449364bc
ce8a4217e20b57b280fe48f9ae865c875c237f8c
/stormancer/stormancer-sources/include/public/stormancer/Utilities/StringUtilities.h
16b3b514b63b711146b3302ed3c099d7c59c5673
[]
no_license
robinhood90/stormancer-sdk-cpp
60060d786ae52817e63aca429f3d20acb7c22d15
10997b58ae0fd89011ab28d6a9b20f7689472486
refs/heads/master
2022-03-10T13:58:31.350124
2019-09-26T09:31:40
2019-09-26T09:31:40
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,174
h
#pragma once #include "stormancer/BuildConfig.h" #include <string> #include <vector> namespace Stormancer { /// Join a vector of strings by using a glue string. /// \param vector The vector of strings to join. /// \param glue A glue string. Default is empty string. std::string stringJoin(const std::vector<std::string>& vector, const std::string& glue = ""); /// Join a vector of strings by using a glue string. /// \param vector The vector of strings to join. /// \param glue A glue string. Default is empty string. std::wstring stringJoin(const std::vector<std::wstring>& vector, const std::wstring& glue = L""); /// Split a string to a vector of strings by using a separator string. /// \param str The string to split. /// \param separator the separator to detect in the string. std::vector<std::string> stringSplit(const std::string& str, const std::string& separator); /// Split a string to a vector of strings by using a separator string. /// \param str The string to split. /// \param separator the separator to detect in the string. std::vector<std::string> stringSplit(const std::string& str, const char separator); /// Split a string to a vector of strings by using a separator string. /// \param str The string to split. /// \param separator the separator to detect in the string. std::vector<std::wstring> stringSplit(const std::wstring& str, const std::wstring& separator); /// Split a string to a vector of strings by using a separator string. /// \param str The string to split. /// \param separator the separator to detect in the string. std::vector<std::wstring> stringSplit(const std::wstring& str, const wchar_t separator); /// Trim a specific character from the start and the end of a string. /// \param str The string to trim. /// \param ch the character to remove from the string. Default is space. std::string stringTrim(const std::string& str, char ch = ' '); /// Trim a specific character from the start and the end of a string. /// \param str The string to trim. /// \param ch the character to remove from the string. Default is space. std::wstring stringTrim(const std::wstring& str, wchar_t ch = ' '); }
[ "hal9000@stormancer.com" ]
hal9000@stormancer.com
5172bc044a23739a3fa840084b042f3a7894023d
2a0d3b7b60adb5a76f0494fc329aee528bb58d97
/Almond/src/Almond/ImGui/ImGuiLayer.h
9b0d597f88a7c958b76d8410e1f86705f70ff621
[ "Apache-2.0" ]
permissive
joshrudesill/Almond
029b2023e185afe0fa453018e425dea1d1f803c8
aab1e74eb5f85b9e06d5159ff3d429b728f7ac5e
refs/heads/main
2023-02-22T00:13:37.654985
2021-01-27T19:52:14
2021-01-27T19:52:14
318,249,021
0
0
null
null
null
null
UTF-8
C++
false
false
465
h
#pragma once #include "Almond/Layer.h" #include "Almond/Events/KeyEvent.h" #include "Almond/Events/MouseEvent.h" #include "Almond/Events/ApplicationEvent.h" namespace Almond { class ALMOND_API ImGuiLayer : public Layer { public: ImGuiLayer(); ~ImGuiLayer(); virtual void onAttach() override; virtual void onDetach() override; virtual void onImGuiRender(float fr) override; void begin(); void end(); private: float m_Time = 0.0f; }; }
[ "joshrudesill@gmail.com" ]
joshrudesill@gmail.com
7223f363a97d274d2c17ee3605bfc5e187ae2678
88ae8695987ada722184307301e221e1ba3cc2fa
/third_party/skia/src/shaders/SkColorFilterShader.cpp
eee266cc12d0b311578e4ac08e84113daedbf341
[ "Apache-2.0", "LGPL-2.0-or-later", "MIT", "GPL-1.0-or-later", "BSD-3-Clause" ]
permissive
iridium-browser/iridium-browser
71d9c5ff76e014e6900b825f67389ab0ccd01329
5ee297f53dc7f8e70183031cff62f37b0f19d25f
refs/heads/master
2023-08-03T16:44:16.844552
2023-07-20T15:17:00
2023-07-23T16:09:30
220,016,632
341
40
BSD-3-Clause
2021-08-13T13:54:45
2019-11-06T14:32:31
null
UTF-8
C++
false
false
4,979
cpp
/* * Copyright 2013 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "include/core/SkShader.h" #include "include/core/SkString.h" #include "src/base/SkArenaAlloc.h" #include "src/core/SkColorFilterBase.h" #include "src/core/SkRasterPipeline.h" #include "src/core/SkReadBuffer.h" #include "src/core/SkVM.h" #include "src/core/SkWriteBuffer.h" #include "src/shaders/SkColorFilterShader.h" #if defined(SK_GANESH) #include "src/gpu/ganesh/GrFPArgs.h" #include "src/gpu/ganesh/GrFragmentProcessor.h" #endif #if defined(SK_GRAPHITE) #include "src/gpu/graphite/KeyHelpers.h" #include "src/gpu/graphite/PaintParamsKey.h" #endif SkColorFilterShader::SkColorFilterShader(sk_sp<SkShader> shader, float alpha, sk_sp<SkColorFilter> filter) : fShader(std::move(shader)) , fFilter(as_CFB_sp(std::move(filter))) , fAlpha (alpha) { SkASSERT(fShader); SkASSERT(fFilter); } sk_sp<SkFlattenable> SkColorFilterShader::CreateProc(SkReadBuffer& buffer) { auto shader = buffer.readShader(); auto filter = buffer.readColorFilter(); if (!shader || !filter) { return nullptr; } return sk_make_sp<SkColorFilterShader>(shader, 1.0f, filter); } bool SkColorFilterShader::isOpaque() const { return fShader->isOpaque() && fAlpha == 1.0f && as_CFB(fFilter)->isAlphaUnchanged(); } void SkColorFilterShader::flatten(SkWriteBuffer& buffer) const { buffer.writeFlattenable(fShader.get()); SkASSERT(fAlpha == 1.0f); // Not exposed in public API SkShader::makeWithColorFilter(). buffer.writeFlattenable(fFilter.get()); } bool SkColorFilterShader::appendStages(const SkStageRec& rec, const MatrixRec& mRec) const { if (!as_SB(fShader)->appendStages(rec, mRec)) { return false; } if (fAlpha != 1.0f) { rec.fPipeline->append(SkRasterPipelineOp::scale_1_float, rec.fAlloc->make<float>(fAlpha)); } if (!fFilter->appendStages(rec, fShader->isOpaque())) { return false; } return true; } #if defined(SK_ENABLE_SKVM) skvm::Color SkColorFilterShader::program(skvm::Builder* p, skvm::Coord device, skvm::Coord local, skvm::Color paint, const MatrixRec& mRec, const SkColorInfo& dst, skvm::Uniforms* uniforms, SkArenaAlloc* alloc) const { // Run the shader. skvm::Color c = as_SB(fShader)->program(p, device, local, paint, mRec, dst, uniforms, alloc); if (!c) { return {}; } // Scale that by alpha. if (fAlpha != 1.0f) { skvm::F32 A = p->uniformF(uniforms->pushF(fAlpha)); c.r *= A; c.g *= A; c.b *= A; c.a *= A; } // Finally run that through the color filter. return fFilter->program(p,c, dst, uniforms,alloc); } #endif #if defined(SK_GANESH) ///////////////////////////////////////////////////////////////////// std::unique_ptr<GrFragmentProcessor> SkColorFilterShader::asFragmentProcessor(const GrFPArgs& args, const MatrixRec& mRec) const { auto shaderFP = as_SB(fShader)->asFragmentProcessor(args, mRec); if (!shaderFP) { return nullptr; } // TODO I guess, but it shouldn't come up as used today. SkASSERT(fAlpha == 1.0f); auto [success, fp] = fFilter->asFragmentProcessor(std::move(shaderFP), args.fContext, *args.fDstColorInfo, args.fSurfaceProps); // If the filter FP could not be created, we still want to return the shader FP, so checking // success can be omitted here. return std::move(fp); } #endif /////////////////////////////////////////////////////////////////////////////////////////////////// #if defined(SK_GRAPHITE) void SkColorFilterShader::addToKey(const skgpu::graphite::KeyContext& keyContext, skgpu::graphite::PaintParamsKeyBuilder* builder, skgpu::graphite::PipelineDataGatherer* gatherer) const { using namespace skgpu::graphite; ColorFilterShaderBlock::BeginBlock(keyContext, builder, gatherer); as_SB(fShader)->addToKey(keyContext, builder, gatherer); as_CFB(fFilter)->addToKey(keyContext, builder, gatherer); builder->endBlock(); } #endif // SK_ENABLE_SKSL /////////////////////////////////////////////////////////////////////////////////////////////////// sk_sp<SkShader> SkShader::makeWithColorFilter(sk_sp<SkColorFilter> filter) const { SkShader* base = const_cast<SkShader*>(this); if (!filter) { return sk_ref_sp(base); } return sk_make_sp<SkColorFilterShader>(sk_ref_sp(base), 1.0f, std::move(filter)); }
[ "jengelh@inai.de" ]
jengelh@inai.de
042912ee62fa085d65cc579609866b59ab47f79a
91a882547e393d4c4946a6c2c99186b5f72122dd
/Source/XPSP1/NT/windows/advcore/ctf/uim/compart.cpp
c8833ca785cbeaa4234151c562f2eba3ae0e7064
[]
no_license
IAmAnubhavSaini/cryptoAlgorithm-nt5src
94f9b46f101b983954ac6e453d0cf8d02aa76fc7
d9e1cdeec650b9d6d3ce63f9f0abe50dabfaf9e2
refs/heads/master
2023-09-02T10:14:14.795579
2021-11-20T13:47:06
2021-11-20T13:47:06
null
0
0
null
null
null
null
UTF-8
C++
false
false
22,396
cpp
// // compart.cpp // #include "private.h" #include "globals.h" #include "regsvr.h" #include "compart.h" #include "helpers.h" #include "thdutil.h" #include "tim.h" #include "cicmutex.h" #include "timlist.h" #include "cregkey.h" /* e575186e-71a8-4ef4-90da-14ed705e7df2 */ extern const IID IID_PRIV_CCOMPARTMENTMGR = { 0xe575186e, 0x71a8, 0x4ef4, {0x90, 0xda, 0x14, 0xed, 0x70, 0x5e, 0x7d, 0xf2} }; /* 8b05c1ad-adf0-4a78-a3e2-d38cae3e28be */ extern const IID IID_PRIV_CGLOBALCOMPARTMENT = { 0x8b05c1ad, 0xadf0, 0x4a78, {0xa3, 0xe2, 0xd3, 0x8c, 0xae, 0x3e, 0x28, 0xbe} }; DBG_ID_INSTANCE(CCompartment); DBG_ID_INSTANCE(CCompartmentMgr); DBG_ID_INSTANCE(CEnumCompartment); DBG_ID_INSTANCE(CGlobalCompartment); extern CCicMutex g_mutexCompart; //+--------------------------------------------------------------------------- // // EnsureGlobalCompartment // //---------------------------------------------------------------------------- BOOL EnsureGlobalCompartment(SYSTHREAD *psfn) { if (psfn->_pGlobalCompMgr) return TRUE; psfn->_pGlobalCompMgr = new CGlobalCompartmentMgr(g_gaApp); if (psfn->_pGlobalCompMgr) { if (g_gcomplist.Init(psfn)) return TRUE; delete psfn->_pGlobalCompMgr; psfn->_pGlobalCompMgr = NULL; } return FALSE; } //+--------------------------------------------------------------------------- // // GetCompartmentDWORD // //---------------------------------------------------------------------------- HRESULT MyGetCompartmentDWORD(CCompartmentMgr *pCompMgr, REFGUID rguid, DWORD *pdw) { HRESULT hr; ITfCompartment *pComp; VARIANT var; if (!pCompMgr) return E_FAIL; *pdw = 0; if (SUCCEEDED(hr = pCompMgr->GetCompartment(rguid, &pComp))) { hr = pComp->GetValue(&var); if (hr == S_OK) { Assert(var.vt == VT_I4); *pdw = var.lVal; // no need to VariantClear because VT_I4 } pComp->Release(); } return hr; } //+--------------------------------------------------------------------------- // // SetCompartmentDWORD // //---------------------------------------------------------------------------- HRESULT MySetCompartmentDWORD(TfClientId tid, CCompartmentMgr *pCompMgr, REFGUID rguid, DWORD dw) { HRESULT hr; ITfCompartment *pComp; VARIANT var; if (!pCompMgr) return E_FAIL; if (SUCCEEDED(hr = pCompMgr->GetCompartment(rguid, &pComp))) { var.vt = VT_I4; var.lVal = dw; hr = pComp->SetValue(tid, &var); pComp->Release(); } return hr; } //+--------------------------------------------------------------------------- // // ToggleCompartmentDWORD // // Toggle DWORD value between 0 and 1. // //---------------------------------------------------------------------------- HRESULT MyToggleCompartmentDWORD(TfClientId tid, CCompartmentMgr *pCompMgr, REFGUID rguid, DWORD *pdwOld) { ITfCompartment *pComp; VARIANT var; DWORD dw = 0; HRESULT hr = E_FAIL; if (!pCompMgr) return E_FAIL; if (pCompMgr->GetCompartment(rguid, &pComp) == S_OK) { if (SUCCEEDED(pComp->GetValue(&var))) { if (var.vt == VT_EMPTY) { // compartment is uninitialized var.vt = VT_I4; var.lVal = 0; } else { Assert(var.vt == VT_I4); } var.lVal = (var.lVal == 0) ? 1 : 0; // no need to VariantClear because VT_I4 if ((hr = pComp->SetValue(tid, &var)) == S_OK) { dw = var.lVal; } } pComp->Release(); } if (pdwOld) *pdwOld = dw; return hr; } ////////////////////////////////////////////////////////////////////////////// // // CCompartmentMgr // ////////////////////////////////////////////////////////////////////////////// //+--------------------------------------------------------------------------- // // ctor // //---------------------------------------------------------------------------- CCompartmentMgr::CCompartmentMgr(TfClientId tidOwner, COMPTYPE cType) { Dbg_MemSetThisNameIDCounter(TEXT("CCompartmentMgr"), PERF_COMPARTMGR_COUNTER); _tidOwner = tidOwner; _cType = cType; } //+--------------------------------------------------------------------------- // // dtor // //---------------------------------------------------------------------------- CCompartmentMgr::~CCompartmentMgr() { CleanUp(); } //+--------------------------------------------------------------------------- // // CleanUp // //---------------------------------------------------------------------------- void CCompartmentMgr::CleanUp() { int nCnt = _rgCompartment.Count(); int i; for (i = 0; i < nCnt; i++) { CCompartmentBase *pComp = _rgCompartment.Get(i); pComp->Invalid(); pComp->Release(); } _rgCompartment.Clear(); } //+--------------------------------------------------------------------------- // // GetCompartment // //---------------------------------------------------------------------------- STDAPI CCompartmentMgr::GetCompartment(REFGUID rguid, ITfCompartment **ppcomp) { CCompartmentBase *pComp; if (!ppcomp) return E_INVALIDARG; *ppcomp = NULL; pComp = _Get(rguid); if (!pComp) return E_OUTOFMEMORY; *ppcomp = pComp; pComp->AddRef(); return S_OK; } //+--------------------------------------------------------------------------- // // ClearCompartment // //---------------------------------------------------------------------------- STDAPI CCompartmentMgr::ClearCompartment(TfClientId tid, REFGUID rguid) { TfGuidAtom guidatom; CCompartmentBase *pComp; int iInsert; HRESULT hr; if (FAILED(hr = MyRegisterGUID(rguid, &guidatom))) return hr; pComp = _Find(guidatom, &iInsert); if (!pComp) return CONNECT_E_NOCONNECTION; if (pComp->_GetAccess() & CA_ONLYOWNERSET) { if (_tidOwner != tid) return E_UNEXPECTED; } _rgCompartment.Remove(iInsert, 1); pComp->Invalid(); pComp->Release(); return S_OK; } //+--------------------------------------------------------------------------- // // EnumCompartment // //---------------------------------------------------------------------------- STDAPI CCompartmentMgr::EnumCompartments(IEnumGUID **ppEnum) { CEnumCompartment *pEnum; if (!ppEnum) return E_INVALIDARG; pEnum = new CEnumCompartment(); if (!pEnum) return E_OUTOFMEMORY; if (pEnum->_Init(&_rgCompartment)) *ppEnum = pEnum; else SafeReleaseClear(pEnum); return pEnum ? S_OK : E_FAIL; } //+--------------------------------------------------------------------------- // // _Find // //---------------------------------------------------------------------------- CCompartmentBase *CCompartmentMgr::_Find(TfGuidAtom guidatom, int *piOut) { CCompartmentBase *pComp; CCompartmentBase *pCompMatch; int iMin; int iMax; int iMid; pCompMatch = NULL; iMid = -1; iMin = 0; iMax = _rgCompartment.Count(); while (iMin < iMax) { iMid = (iMin + iMax) / 2; pComp = _rgCompartment.Get(iMid); Assert(pComp != NULL); if (guidatom < pComp->GetGuidAtom()) { iMax = iMid; } else if (guidatom > pComp->GetGuidAtom()) { iMin = iMid + 1; } else // guidatom == pComp->GetGuidAtom(). { pCompMatch = pComp; break; } } if (!pCompMatch) { if (iMid >= 0) { CCompartmentBase *pCompTmp = _rgCompartment.Get(iMid); if (pCompTmp->GetGuidAtom() < guidatom) { iMid++; } } } if (piOut) *piOut = iMid; return pCompMatch; } //+--------------------------------------------------------------------------- // // _Get // //---------------------------------------------------------------------------- CCompartmentBase *CCompartmentMgr::_Get(REFGUID rguid) { CCompartmentBase *pComp; int iInsert; TfGuidAtom guidatom; if (FAILED(MyRegisterGUID(rguid, &guidatom))) return NULL; pComp = _Find(guidatom, &iInsert); if (!pComp) { TfPropertyType proptype = TF_PT_NONE; // // system predefined compartments does not allow any other type. // if ((IsEqualGUID(rguid, GUID_COMPARTMENT_KEYBOARD_DISABLED)) || (IsEqualGUID(rguid, GUID_COMPARTMENT_HANDWRITING_OPENCLOSE)) || (IsEqualGUID(rguid, GUID_COMPARTMENT_SPEECH_OPENCLOSE))) { proptype = TF_PT_DWORD; } if (_cType == COMPTYPE_GLOBAL) pComp = new CGlobalCompartment(this, rguid, guidatom, proptype); else pComp = new CCompartment(this, guidatom, proptype); if (pComp) { if (iInsert < 0) iInsert = 0; if (_rgCompartment.Insert(iInsert, 1)) { _rgCompartment.Set(iInsert, pComp); } else { delete pComp; pComp = NULL; } } } return pComp; } //+--------------------------------------------------------------------------- // // NotifyGlobalCompartmentChange // //---------------------------------------------------------------------------- void CCompartmentMgr::NotifyGlobalCompartmentChange(DWORD dwId) { Assert(_cType == COMPTYPE_GLOBAL); int nCnt = _rgCompartment.Count(); for (int i = 0; i < nCnt; i++) { CCompartmentBase *pComp = _rgCompartment.Get(i); if (dwId == pComp->GetId()) { pComp->MakeNotify(); break; } } } ////////////////////////////////////////////////////////////////////////////// // // CGlobalCompartmenMgr // ////////////////////////////////////////////////////////////////////////////// STDAPI CGlobalCompartmentMgr::QueryInterface(REFIID riid, void **ppvObj) { *ppvObj = NULL; if (IsEqualIID(riid, IID_IUnknown) || IsEqualIID(riid, IID_ITfCompartmentMgr)) { *ppvObj = SAFECAST(this, ITfCompartmentMgr *); } if (*ppvObj) { return S_OK; } return E_NOINTERFACE; } ULONG CGlobalCompartmentMgr::AddRef(void) { _cRef++; return _cRef; } ULONG CGlobalCompartmentMgr::Release(void) { _cRef--; if (_cRef <= 0) { // // Calller may call Release() more than AddRef().. // We should not call TIM::Release() at this time. // Assert(0) return 0; } return _cRef; } ////////////////////////////////////////////////////////////////////////////// // // CEnumCompartment // ////////////////////////////////////////////////////////////////////////////// //+--------------------------------------------------------------------------- // // ctor // //---------------------------------------------------------------------------- CEnumCompartment::CEnumCompartment() { Dbg_MemSetThisNameIDCounter(TEXT("CEnumCompartment"), PERF_ENUMCOMPART_COUNTER); } //+--------------------------------------------------------------------------- // // Init // //---------------------------------------------------------------------------- BOOL CEnumCompartment::_Init(CPtrArray<CCompartmentBase> *prgComp) { int nCnt = prgComp->Count(); int i; BOOL fRet = FALSE; CicEnterCriticalSection(g_cs); _pga = SGA_Init(nCnt, NULL); if (_pga == NULL) goto Exit; for (i = 0; i < nCnt; i++) { CCompartmentBase *pComp = prgComp->Get(i); if (FAILED((MyGetGUID(pComp->GetGuidAtom(), &_pga->rgGuid[i])))) goto Exit; } fRet = TRUE; Exit: CicLeaveCriticalSection(g_cs); return fRet; } ////////////////////////////////////////////////////////////////////////////// // // CCompartmentBase // ////////////////////////////////////////////////////////////////////////////// const COMPARTMENTACCESS CCompartmentBase::_c_ca[] = { {&GUID_COMPARTMENT_KEYBOARD_DISABLED, CA_ONLYOWNERSET}, {NULL, 0} }; CCompartmentBase::CCompartmentBase(CCompartmentMgr *pCompMgr, TfGuidAtom guidatom, TfPropertyType proptype) { Assert(!_fInvalid); _guidatom = guidatom; _proptype = proptype; _pCompMgr = pCompMgr; int n = 0; while (_c_ca[n].pguid) { if (MyIsEqualTfGuidAtom(guidatom, *_c_ca[n].pguid)) { _dwAccess = _c_ca[n].dwAccess; } n++; } } ////////////////////////////////////////////////////////////////////////////// // // CCompartment // ////////////////////////////////////////////////////////////////////////////// //+--------------------------------------------------------------------------- // // ctor // //---------------------------------------------------------------------------- CCompartment::CCompartment(CCompartmentMgr *pCompMgr, TfGuidAtom guidatom, TfPropertyType proptype) :CCompartmentBase(pCompMgr, guidatom, proptype) { Dbg_MemSetThisNameIDCounter(TEXT("CCompartment"), PERF_COMPART_COUNTER); } //+--------------------------------------------------------------------------- // // dtor // //---------------------------------------------------------------------------- CCompartment::~CCompartment() { if (_prop.type == TF_PT_UNKNOWN) { // // #489905 // // we can not call sink anymore after DLL_PROCESS_DETACH. // if (!DllShutdownInProgress()) _prop.punk->Release(); } else if (_prop.type == TF_PT_BSTR) SysFreeString(_prop.bstr); } //+--------------------------------------------------------------------------- // // Advise // //---------------------------------------------------------------------------- HRESULT CCompartment::AdviseSink(REFIID riid, IUnknown *punk, DWORD *pdwCookie) { const IID *rgiid; rgiid = &IID_ITfCompartmentEventSink; return GenericAdviseSink(riid, punk, &rgiid, &_rgCompartmentSink, 1, pdwCookie); } //+--------------------------------------------------------------------------- // // Unadvise // //---------------------------------------------------------------------------- HRESULT CCompartment::UnadviseSink(DWORD dwCookie) { return GenericUnadviseSink(&_rgCompartmentSink, 1, dwCookie); } //+--------------------------------------------------------------------------- // // GetValue // //---------------------------------------------------------------------------- HRESULT CCompartment::GetValue(VARIANT *pvarValue) { HRESULT hr; if (_fInvalid) { Assert(0); return E_UNEXPECTED; } if (pvarValue == NULL) return E_INVALIDARG; QuickVariantInit(pvarValue); hr = TfPropToVariant(pvarValue, &_prop, ADDREF); if (hr != S_OK) return hr; return (pvarValue->vt == VT_EMPTY) ? S_FALSE : S_OK; } //+--------------------------------------------------------------------------- // // SetValue // //---------------------------------------------------------------------------- HRESULT CCompartment::SetValue(TfClientId tid, const VARIANT *pvarValue) { HRESULT hr; if (_fInvalid) { Assert(0); return E_UNEXPECTED; } if (_fInSet) return E_UNEXPECTED; if (pvarValue == NULL) return E_INVALIDARG; if (!IsValidCiceroVarType(pvarValue->vt)) return E_INVALIDARG; if (pvarValue->vt == VT_EMPTY) return E_INVALIDARG; if (_GetAccess() & CA_ONLYOWNERSET) { if (_GetMgr()->_GetTIPOwner() != tid) return E_UNEXPECTED; } hr = VariantToTfProp(&_prop, pvarValue, ADDREF, FALSE); if (hr != S_OK) return hr; int i; int nCnt = _rgCompartmentSink.Count(); if (nCnt) { GUID guid; if (FAILED(MyGetGUID(_guidatom, &guid))) { return E_FAIL; Assert(0); } _fInSet = TRUE; for (i = 0; i < nCnt; i++) { ((ITfCompartmentEventSink *)_rgCompartmentSink.GetPtr(i)->pSink)->OnChange(guid); } _fInSet = FALSE; } return S_OK; } ////////////////////////////////////////////////////////////////////////////// // // CGlobalCompartment // ////////////////////////////////////////////////////////////////////////////// //+--------------------------------------------------------------------------- // // ctor // //---------------------------------------------------------------------------- CGlobalCompartment::CGlobalCompartment(CCompartmentMgr *pCompMgr, REFGUID rguid, TfGuidAtom guidatom, TfPropertyType proptype) :CCompartmentBase(pCompMgr, guidatom, proptype) { Dbg_MemSetThisNameIDCounter(TEXT("CGlobalCompartment"), PERF_GLOBCOMPART_COUNTER); _dwId = (DWORD)(-1); _guidCompart = rguid; } //+--------------------------------------------------------------------------- // // dtor // //---------------------------------------------------------------------------- CGlobalCompartment::~CGlobalCompartment() { } //+--------------------------------------------------------------------------- // // Advise // //---------------------------------------------------------------------------- HRESULT CGlobalCompartment::AdviseSink(REFIID riid, IUnknown *punk, DWORD *pdwCookie) { const IID *rgiid; if (_dwId == (DWORD)(-1)) { _dwId = g_gcomplist.GetId(_guidCompart); if (_dwId == (DWORD)(-1)) { TFPROPERTY prop; memset(&prop, 0, sizeof(prop)); _dwId = g_gcomplist.SetProperty(_guidCompart, &prop); if (_dwId == (DWORD)(-1)) return E_FAIL; } } rgiid = &IID_ITfCompartmentEventSink; return GenericAdviseSink(riid, punk, &rgiid, &_rgCompartmentSink, 1, pdwCookie); } //+--------------------------------------------------------------------------- // // Unadvise // //---------------------------------------------------------------------------- HRESULT CGlobalCompartment::UnadviseSink(DWORD dwCookie) { return GenericUnadviseSink(&_rgCompartmentSink, 1, dwCookie); } //+--------------------------------------------------------------------------- // // GetValue // //---------------------------------------------------------------------------- HRESULT CGlobalCompartment::GetValue(VARIANT *pvarValue) { HRESULT hr; TFPROPERTY prop; if (_fInvalid) { Assert(0); return E_UNEXPECTED; } if (pvarValue == NULL) return E_INVALIDARG; QuickVariantInit(pvarValue); if (_dwId == (DWORD)(-1)) { _dwId = g_gcomplist.GetId(_guidCompart); } memset(&prop, 0, sizeof(TFPROPERTY)); if (_dwId != (DWORD)(-1)) g_gcomplist.GetProperty(_guidCompart, &prop); Assert(prop.type != TF_PT_UNKNOWN); hr = TfPropToVariant(pvarValue, &prop, ADDREF); if (hr != S_OK) return hr; return (pvarValue->vt == VT_EMPTY) ? S_FALSE : S_OK; } //+--------------------------------------------------------------------------- // // SetValue // //---------------------------------------------------------------------------- HRESULT CGlobalCompartment::SetValue(TfClientId tid, const VARIANT *pvarValue) { HRESULT hr; TFPROPERTY prop; if (_fInvalid) { Assert(0); return E_UNEXPECTED; } if (_fInSet) return E_UNEXPECTED; if (pvarValue == NULL) return E_INVALIDARG; if (!IsValidCiceroVarType(pvarValue->vt)) return E_INVALIDARG; if (_GetAccess() & CA_ONLYOWNERSET) { if (_GetMgr()->_GetTIPOwner() != tid) return E_UNEXPECTED; } if (pvarValue->vt == VT_UNKNOWN) { Assert(0); return E_INVALIDARG; } hr = VariantToTfProp(&prop, pvarValue, NO_ADDREF, FALSE); if (hr != S_OK) return hr; _dwId = g_gcomplist.SetProperty(_guidCompart, &prop); if (_dwId == (DWORD)(-1)) return E_FAIL; hr = (prop.type != TF_PT_NONE) ? S_OK : E_FAIL; if (SUCCEEDED(hr)) { // // make a notify to the sinks of the current thread. // if (!MakeNotify()) return E_FAIL; PostTimListMessage(TLF_GCOMPACTIVE, 0, g_msgPrivate, TFPRIV_GLOBALCOMPARTMENTSYNC, _dwId); } return hr; } //+--------------------------------------------------------------------------- // // EnumThreadProc // //---------------------------------------------------------------------------- BOOL CGlobalCompartment::EnumThreadProc(DWORD dwThreadId, DWORD dwProcessId, void *pv) { if (dwThreadId != GetCurrentThreadId()) { CGlobalCompartment *_this = (CGlobalCompartment *)pv; PostThreadMessage(dwThreadId, g_msgPrivate, TFPRIV_GLOBALCOMPARTMENTSYNC, _this->_dwId); } return FALSE; } //+--------------------------------------------------------------------------- // // MakeNotify // //---------------------------------------------------------------------------- BOOL CGlobalCompartment::MakeNotify() { int i; int nCnt = _rgCompartmentSink.Count(); if (nCnt) { GUID guid; if (FAILED(MyGetGUID(_guidatom, &guid))) { Assert(0); return FALSE; } _fInSet = TRUE; for (i = 0; i < nCnt; i++) { ((ITfCompartmentEventSink *)_rgCompartmentSink.GetPtr(i)->pSink)->OnChange(guid); } _fInSet = FALSE; } return TRUE; }
[ "support@cryptoalgo.cf" ]
support@cryptoalgo.cf
0649e394fd77f57bbdd921c30e73af6dcb38169c
d014365963430c485a51fc6de20e6ce3d50655b5
/HackerRank/Algorithms/Implementation/ACMICPCTeam.cpp
5d9701ff8174124385798906421b4ca1a99dddac
[]
no_license
archie94/Codes
ed7d07bc69bd64513d964649b1389711e04fbed5
fa605a2832697e8021d060eec9645c615a8ebf0e
refs/heads/master
2021-01-17T02:17:28.329661
2018-04-21T12:09:49
2018-04-21T12:09:49
45,904,046
2
1
null
null
null
null
UTF-8
C++
false
false
561
cpp
#include <iostream> #include <cstdio> #include <algorithm> #include <cmath> using namespace std; int main() { int n,m; cin>>n>>m; string s[n]; getchar(); for(int i=0;i<n;i++) { cin>>s[i]; } int maxTopic=0; int maxTeam=0; for(int i=0;i<n-1;i++) { for(int j=i+1;j<n;j++){ int topic=0; for(int k=0;k<m;k++) { if(s[i][k]=='1' || s[j][k]=='1') { topic++; } } if(topic>maxTopic) { maxTeam=1; maxTopic=topic; }else if(topic==maxTopic) { maxTeam++; } } } cout<<maxTopic<<endl<<maxTeam<<endl; return 0; }
[ "arkaprava94@gmail.com" ]
arkaprava94@gmail.com
0769f862f3af75d19b91b7012a2434da8fe5df72
73c8a3179b944b63b2a798542896e4cdf0937b6e
/Notebook/src/Mathematics - Euler Phi Funciton.cpp
5b7bf75d3b0a0b03d98af9098a5d51e589731259
[ "Apache-2.0" ]
permissive
aajjbb/contest-files
c151f1ab9b562ca91d2f8f4070cb0aac126a188d
71de602a798b598b0365c570dd5db539fecf5b8c
refs/heads/master
2023-07-23T19:34:12.565296
2023-07-16T00:57:55
2023-07-16T00:57:59
52,963,297
2
4
null
2017-08-03T20:12:19
2016-03-02T13:05:25
C++
UTF-8
C++
false
false
1,315
cpp
//Memoizing #include <iostream> #include <limits.h> #include <cstdlib> #include <cmath> using namespace std; const int N1 = 50001, N2 = 5133; bool isPrime[N1]; int prime[N2], nPrime, totient[N1]; void sieveAndTotient() { // reset for (int i = 0; i < N1; ++i) totient[i] = i; isPrime[0] = isPrime[1] = false; for (int i = 3; i < N1; i += 2) isPrime[i] = true; for (int i = 4; i < N1; i += 2) isPrime[i] = false; nPrime = 0; // 2 // update for 2 prime[nPrime++] = 2; for (int j = 2; j < N1; j += 2) { isPrime[j] = false; // totient for 2 totient[j] -= totient[j] / 2; } isPrime[2] = true; // odds for (int i = 3; i < N1; i += 2) if (isPrime[i]) { // update for i prime[nPrime++] = i; if (i < INT_MAX) for (int j = i; j < N1; j += i) { isPrime[j] = false; // totient for i totient[j] -= totient[j] / i; } isPrime[i] = true; } } //Direct int fi(int n) { int result = n; for (int i = 2; i * i <= n; i++) { if (n % i == 0) { result -= result / i; } while (n % i == 0) { n /= i; } } if (n > 1) { result -= result / n; } return result; }
[ "jefersonlsiq@gmail.com" ]
jefersonlsiq@gmail.com
3a9d4c48e71c10c762aaff9a7b7a5594ab72203b
77d9f19eafffd4be11cda6391229ccb84bf4faf2
/src/aligned.cpp
c12646ea9f043e4513a5d7527a86563a01c10ad4
[ "MIT" ]
permissive
rivas-lab/multisnpnet-Cox
bb2d42d1bfd5e87546512ea9b7b2c182485770e0
2f4e978e4b51838efe45bf5a0e33f22ffe4b63a9
refs/heads/master
2023-02-27T09:55:42.211805
2020-10-12T18:05:05
2020-10-12T18:05:05
261,369,357
2
0
null
null
null
null
UTF-8
C++
false
false
13,776
cpp
#define EIGEN_USE_MKL_ALL #include <Rcpp.h> #include <omp.h> #include <vector> #include <iostream> #include <sys/time.h> #include <cmath> #include "mrcox_types.h" // [[Rcpp::depends(RcppEigen)]] // void rev_cumsum_assign(const MatrixXd &src, MatrixXd &dest) { const int K = src.cols(); const int N = src.rows(); for(int k = 0; k < K; ++k){ double current = 0; for (int i = 0; i < N; ++i){ current += src(N-1-i, k); dest(N-1-i, k) = current; } } } class MCox_aligned { const int N; //Number of observations const int K; //Number of responses const int p; //Number of predictors MapMatd X; MapMatd status; MapMati rankmin; MapMati rankmax; std::vector<PermMat> orders; //Permutation matrices such that P_i * X sort X in increasing event time order // Store intermediate results MatrixXd eta; MatrixXd exp_eta; MatrixXd risk_denom; MatrixXd outer_accumu; MatrixXd residual; double get_residual(const MapMatd &v, bool get_val=false){ //std::cout << "first product\n"; eta.noalias() = X*v; //std::cout << "first product done\n"; // Get them in the right order #pragma omp parallel for for(int k = 0; k < K; ++k){ eta.col(k) = orders[k] * eta.col(k); } exp_eta.noalias() = eta.array().exp().matrix(); #pragma omp parallel for for(int k = 0; k < K; ++k){ // reverse cumsum to get risk_denom double current = 0; for (int i = 0; i < N; ++i){ current += exp_eta(N-1-i, k); risk_denom(N-1-i, k) = current; } // adjust ties // This won't have aliasing problem for(int i = 0; i < N; ++i){ risk_denom(i, k) = risk_denom(rankmin(i, k), k); } } // get outer accumu outer_accumu.noalias() = (status.array()/risk_denom.array()).matrix(); #pragma omp parallel for for(int k = 0; k < K; ++k){ double current = 0; for(int i = 0; i < N; ++i){ current += outer_accumu(i, k); outer_accumu(i, k) = current; } // Adjust ties, this also won't have alias for(int i = 0; i < N; ++i){ outer_accumu(i, k) = outer_accumu(rankmax(i, k), k); } } residual.noalias() = (outer_accumu.array() * exp_eta.array() - status.array()).matrix(); // Get the order back #pragma omp parallel for for(int k = 0; k<K; ++k){ residual.col(k) = orders[k].transpose() * residual.col(k); } double cox_val = 0; if(get_val){ cox_val = ((risk_denom.array().log() - eta.array()) * status.array()).sum(); } return cox_val; } public: MCox_aligned(int N, int K, int p, const double *X, const double *status, const int *rankmin, const int *rankmax, const Rcpp::List order_list) : N(N), K(K), p(p), X(X, N, p), status(status, N, K), rankmin(rankmin, N, K), rankmax(rankmax, N, K), eta(N, K), exp_eta(N, K), risk_denom(N, K), outer_accumu(N, K), residual(N, K) { for (int k = 0; k < K; ++k){ orders.emplace_back(Rcpp::as<VectorXi>(order_list[k])); } } double get_gradient(const double *vptr, MatrixXd & grad, bool get_val=false){ MapMatd v(vptr, p, K); double cox_val = get_residual(v, get_val); //std::cout << "second product\n"; //grad.noalias() = (residual.transpose() * X).transpose(); grad.noalias() = X.transpose() * residual; //std::cout << "second product done\n"; return cox_val; } double get_value_only(const double *vptr){ MapMatd v(vptr, p, K); eta.noalias() = X*v; // Get them in the right order #pragma omp parallel for for(int k = 0; k < K; ++k){ eta.col(k) = orders[k] * eta.col(k); } exp_eta.noalias() = eta.array().exp().matrix(); #pragma omp parallel for for(int k = 0; k < K; ++k){ // reverse cumsum to get risk_denom double current = 0; for (int i = 0; i < N; ++i){ current += exp_eta(N-1-i, k); risk_denom(N-1-i, k) = current; } // adjust ties // This won't have aliasing problem for(int i = 0; i < N; ++i){ risk_denom(i, k) = risk_denom(rankmin(i, k), k); } } double cox_val = ((risk_denom.array().log() - eta.array()) * status.array()).sum(); return cox_val; } MatrixXd Rget_residual(const double *vptr){ MapMatd v(vptr, p, K); get_residual(v); return residual; } }; void grad_step_l1(Eigen::Map<Eigen::MatrixXd> & B, const MatrixXd & grad, const MatrixXd &v, const double step_size, double lambda_1, const VectorXd & penalty_factor) { B.noalias() = v - step_size*grad; B = ((B.cwiseAbs().colwise() - lambda_1*step_size*penalty_factor).array().max(0) * B.array().sign()).matrix(); } void get_row_norm(const MatrixXd &Bfull, const double step_size, double lambda_2, const VectorXd & penalty_factor, VectorXd & B_row_norm) { B_row_norm.noalias() = Bfull.rowwise().norm().cwiseMax(lambda_2*step_size*penalty_factor); } void prox_l2(Eigen::Map<Eigen::MatrixXd> & B, const double step_size, double lambda_2, const VectorXd & penalty_factor, const VectorXd & B_row_norm) { B = ((B_row_norm.array() - lambda_2*step_size*penalty_factor.array())/(B_row_norm.array())).matrix().asDiagonal() * B; } void update_parameters(MatrixXd & B, const MatrixXd & grad, const MatrixXd &v, const double step_size, double lambda_1, double lambda_2, const VectorXd & penalty_factor, VectorXd & B_row_norm) { int K = grad.cols(); B.noalias() = v - step_size*grad; // Apply proximal operator here: //Soft-thresholding B = ((B.cwiseAbs().colwise() - lambda_1*step_size*penalty_factor).array().max(0) * B.array().sign()).matrix(); // Group soft-thresholding // should be called the pmax of B_row_norm and lambda_2*step_size B_row_norm.noalias() = B.rowwise().norm().cwiseMax(lambda_2*step_size*penalty_factor); B = ((B_row_norm.array() - lambda_2*step_size*penalty_factor.array())/(B_row_norm.array())).matrix().asDiagonal() * B; } // [[Rcpp::export]] Rcpp::List fit_aligned(Rcpp::NumericMatrix X, Rcpp::NumericMatrix status, Rcpp::IntegerMatrix rankmin, Rcpp::IntegerMatrix rankmax, Rcpp::List order_list, Rcpp::NumericMatrix B0, Rcpp::NumericVector lambda_1_all, Rcpp::NumericVector lambda_2_all, VectorXd pfac, double step_size = 1.0, int niter=2000, double linesearch_beta = 1.1, double eps=1e-5 // convergence criteria ) { int N = X.rows(); int p = X.cols(); int K = status.cols(); int K0 = B0.cols(); // B has K >= K0 columns, the extra columns will be used for group proximal operator MapMatd Bmap(&B0(0,0), p, K0); MapMatd vmap(&B0(0,0), p, K); MCox_aligned prob(N, K, p, &X(0,0), &status(0,0), &rankmin(0,0), &rankmax(0,0), order_list); MatrixXd Bfull(Bmap); // has dimension p by K0 Eigen::Map<Eigen::MatrixXd> B(Bfull.data(), p, K); MatrixXd prev_B(vmap); MatrixXd v(vmap); MatrixXd grad(p,K); MatrixXd grad_ls(p,K); VectorXd B_row_norm(p); const int nlambda = lambda_1_all.size(); double step_size_intial = step_size; double weight_old, weight_new; double rhs_ls; struct timeval start, end; Rcpp::List result(nlambda); Rcpp::List residual_result(nlambda); for (int lam_ind = 0; lam_ind < nlambda; ++lam_ind){ gettimeofday(&start, NULL); double lambda_1 = lambda_1_all[lam_ind]; double lambda_2 = lambda_2_all[lam_ind]; double step_size = step_size_intial; weight_old = 1.0; bool stop; // stop line search double value_change; if(lam_ind > 0){ v.noalias() = B; } for (int i = 0; i< niter; i++){ Rcpp::checkUserInterrupt(); prev_B.noalias() = B; double cox_val = prob.get_gradient(v.data(), grad, true); while (true){ grad_step_l1(B, grad, v, step_size, lambda_1, pfac); get_row_norm(Bfull, step_size, lambda_2, pfac, B_row_norm); prox_l2(B, step_size, lambda_2, pfac, B_row_norm); //update_parameters(B, grad, v, step_size, lambda_1, lambda_2, pfac, B_row_norm); double cox_val_next = prob.get_value_only(B.data()); if(!std::isfinite(cox_val_next)){ stop = (step_size < 1e-9); } else { rhs_ls = cox_val + (grad.array() * (B - v).array()).sum() + (B-v).squaredNorm()/(2*step_size); stop = (cox_val_next <= rhs_ls); } if (stop){ value_change = abs(cox_val_next - cox_val)/fmax(1.0, abs(cox_val)); break; } step_size /= linesearch_beta; } if(value_change < 5e-7){ std::cout << "convergence based on value change reached in " << i <<" iterations\n"; std::cout << "current step size is " << step_size << std::endl; gettimeofday(&end, NULL); double delta = ((end.tv_sec - start.tv_sec) * 1000000u + end.tv_usec - start.tv_usec) / 1.e6; std::cout << "elapsed time is " << delta << " seconds" << std::endl; Rcpp::checkUserInterrupt(); break; } // Nesterov weight weight_new = 0.5*(1+sqrt(1+4*weight_old*weight_old)); v.noalias() = B + ((weight_old - 1)/weight_new) * (B - prev_B); weight_old = weight_new; if (i != 0 && i % 100 == 0){ std::cout << "reached " << i << " iterations\n"; gettimeofday(&end, NULL); double delta = ((end.tv_sec - start.tv_sec) * 1000000u + end.tv_usec - start.tv_usec) / 1.e6; std::cout << "elapsed time is " << delta << " seconds" << std::endl; std::cout << "current step size is " << step_size << std::endl; Rcpp::checkUserInterrupt(); } } result[lam_ind] = Bfull; residual_result[lam_ind] = prob.Rget_residual(B.data()); std::cout << "Solution for the " << lam_ind+1 << "th lambda pair is obtained\n"; } return Rcpp::List::create(Rcpp::Named("result") = result, Rcpp::Named("residual") = residual_result); } //' @export // [[Rcpp::export]] VectorXd compute_dual_norm(MatrixXd grad, double alpha, double tol) { int p = grad.rows(); VectorXd upperbound((grad.cwiseAbs().rowwise().maxCoeff()).cwiseMin(grad.rowwise().norm()/alpha)); VectorXd dual_norm(p); #pragma omp parallel for schedule(dynamic, 1) for (int i = 0; i < p; ++i){ double lower = 0.0; double upper = upperbound[i]; if (upper <= tol){ dual_norm[i] = 0.0; } else { int num_iter = (int)ceil(log2(upper/tol)); for (int j = 0; j < num_iter; ++j){ double bound = (lower + upper)/2; bool less = ((grad.row(i).array().abs() - bound).max(0).matrix().norm()) <= alpha * bound; if (less){ upper = bound; } else { lower = bound; } } dual_norm[i] = (lower + upper)/2; } } return dual_norm; } //' @export // [[Rcpp::export]] MatrixXd compute_residual(Rcpp::NumericMatrix X, Rcpp::NumericMatrix status, Rcpp::IntegerMatrix rankmin, Rcpp::IntegerMatrix rankmax, Rcpp::List order_list, MatrixXd v) { int N = X.rows(); int p = X.cols(); int K = status.cols(); MCox_aligned prob(N, K, p, &X(0,0), &status(0,0), &rankmin(0,0), &rankmax(0,0), order_list); return prob.Rget_residual(v.data()); }
[ "ruilinli@stanford.edu" ]
ruilinli@stanford.edu
4abf615a03f29ac61bcab7f8f3b2063fb126407d
813d1a7e1b931431e05a9d6a3ae3120bb735667d
/src/main_node.cpp
a9dc4cc6eeed1a1a7d79b56fd97a76702845d5df
[]
no_license
rohanpsingh/train_hourglass
eb144b5fd8c41d3229ed349595825ad06719f38d
a46d9a47ff1f1448b2b91b5e577be42a022462ed
refs/heads/master
2020-03-22T21:22:28.528902
2018-12-14T04:09:40
2018-12-14T04:09:40
140,681,165
0
0
null
null
null
null
UTF-8
C++
false
false
1,162
cpp
#include "common_headers.h" #include "ros_utils.h" #include "lua_utils.h" #include <message_filters/subscriber.h> #include <message_filters/synchronizer.h> #include <message_filters/sync_policies/approximate_time.h> int main (int argc, char** argv){ ros::init(argc, argv, "train"); ros::NodeHandle nh("~"); setRosParameters(nh); initializeLua(); setLuaParameters(); message_filters::Subscriber<sensor_msgs::Image> img_sub(nh, "input_image", 1); message_filters::Subscriber<darknet_ros_msgs::BoundingBoxes> box_sub(nh, "input_bbox", 1); message_filters::Subscriber<object_keypoint_msgs::ObjectKeyPointArray> kpa_sub(nh, "input_kpts", 1); typedef message_filters::sync_policies::ApproximateTime<sensor_msgs::Image, darknet_ros_msgs::BoundingBoxes, object_keypoint_msgs::ObjectKeyPointArray> SyncPolicy; message_filters::Synchronizer<SyncPolicy> sync(SyncPolicy(100), img_sub, box_sub, kpa_sub); sync.registerCallback(boost::bind(&msgCallback, _1, _2, _3)); ros::spin(); return 0; }
[ "rohan565singh@gmail.com" ]
rohan565singh@gmail.com
4784ae14f5184886f48a37b815edb4d12479fc54
6b2a8dd202fdce77c971c412717e305e1caaac51
/solutions_5639104758808576_1/C++/courage/1.cpp
33c0b5e3d49cecdb9046feb450088e2f97648706
[]
no_license
alexandraback/datacollection
0bc67a9ace00abbc843f4912562f3a064992e0e9
076a7bc7693f3abf07bfdbdac838cb4ef65ccfcf
refs/heads/master
2021-01-24T18:27:24.417992
2017-05-23T09:23:38
2017-05-23T09:23:38
84,313,442
2
4
null
null
null
null
UTF-8
C++
false
false
384
cpp
#include <cstdio> int t,n,m,ans,x; char s[1010]; int main(){ freopen("1.in","r",stdin); freopen("1.out","w",stdout); scanf("%d",&t); for (int T = 1;T <= t;++T){ scanf("%d",&m); n = 0; ans = 0; scanf("%s",s); for (int i = 0;i <= m;++i){ if (n < i){ ans += i - n; n = i; } n += s[i] - '0'; } printf("Case #%d: %d\n",T,ans); } }
[ "eewestman@gmail.com" ]
eewestman@gmail.com
bebdcb3cd3010961c929429118788f2b36c99316
d4f8c7d8e5f4021117a5c64045a3ddc72d9ec55a
/Common/material.h
511d5cde36946a3a5b26e891c4a08e55215f40bc
[]
no_license
anlingbbq/LearnRayTracing
86dc0747a1b1afa1f0c91d030dafe647322a4ff2
9bb4bec69cc6440325eac5a174634d844e144840
refs/heads/master
2023-04-30T03:56:03.188253
2021-05-17T09:38:38
2021-05-17T09:38:38
297,340,343
0
0
null
null
null
null
UTF-8
C++
false
false
3,063
h
#ifndef MATERIALH #define MATERIALH struct hit_record; #include "ray.h" #include "hitable.h" #include "helper.h" float schlick(float cosine, float ref_idx) { float r0 = (1 - ref_idx) / (1 + ref_idx); r0 = r0 * r0; return r0 + (1 - r0) * pow((1 - cosine), 5); } bool refract(const vec3& v, const vec3& n, float ni_over_nt, vec3& refracted) { vec3 uv = unit_vector(v); float dt = dot(uv, n); float discriminant = 1.0f - ni_over_nt * ni_over_nt * (1.0f - dt * dt); if (discriminant > 0) { refracted = ni_over_nt * (uv - n * dt) - n * sqrt(discriminant); return true; } else return false; } vec3 reflect(const vec3& v, const vec3& n) { return v - 2 * dot(v, n) * n; } vec3 random_in_unit_sphere() { vec3 p; do { p = 2.0 * vec3(drand48(), drand48(), drand48()) - vec3(1, 1, 1); } while (p.squared_length() >= 1.0); return p; } class material { public: virtual bool scatter(const ray& r_in, const hit_record& rec, vec3& attenuation, ray& scattered) const = 0; }; class lambertian : public material { public: lambertian(const vec3& v) : albedo(v) {} virtual bool scatter(const ray& r_in, const hit_record& rec, vec3& attenuation, ray& scattered) const { vec3 target = rec.p + rec.normal + random_in_unit_sphere(); scattered = ray(rec.p, target - rec.p); attenuation = albedo; return true; } vec3 albedo; }; class metal : public material { public: metal(const vec3& v) : albedo(v), fuzz(0) {} metal(const vec3& v, float f) : albedo(v) { if (f < 1) fuzz = f; else fuzz = 1; } virtual bool scatter(const ray& r_in, const hit_record& rec, vec3& attenuation, ray& scattered) const { vec3 reflected = reflect(unit_vector(r_in.direction()), rec.normal); scattered = ray(rec.p, reflected + fuzz * random_in_unit_sphere()); attenuation = albedo; return (dot(scattered.direction(), rec.normal) > 0); } vec3 albedo; float fuzz; }; class dielectric : public material { public: dielectric(float ri) : ref_idx(ri) {} virtual bool scatter(const ray& r_in, const hit_record& rec, vec3& attenuation, ray& scattered) const { vec3 outward_normal; vec3 reflected = reflect(r_in.direction(), rec.normal); float ni_over_nt; attenuation = vec3(1.0, 1.0, 1.0); vec3 refracted; float reflect_prob; float cosine; if (dot(r_in.direction(), rec.normal) > 0) { outward_normal = -rec.normal; ni_over_nt = ref_idx; // cosine = ref_idx * dot(r_in.direction(), rec.normal) / r_in.direction().length(); cosine = dot(r_in.direction(), rec.normal) / r_in.direction().length(); cosine = sqrt(1 - ref_idx * ref_idx * (1 - cosine * cosine)); } else { outward_normal = rec.normal; ni_over_nt = 1.0f / ref_idx; cosine = -dot(r_in.direction(), rec.normal) / r_in.direction().length(); } if (refract(r_in.direction(), outward_normal, ni_over_nt, refracted)) reflect_prob = schlick(cosine, ref_idx); else reflect_prob = 1.0; if (drand48() < reflect_prob) scattered = ray(rec.p, reflected); else scattered = ray(rec.p, refracted); return true; } float ref_idx; }; #endif
[ "lijie1992no1@163.com" ]
lijie1992no1@163.com
7ef50810f11b95142f4f0e5d4aab88281497b72c
80315f1bba85314018587f46ee309a00638d14d4
/ServerModel/LogicModel/RoomManager.cpp
d063228e5c0d8543ebbf273e5372ff62fcb1faf7
[]
no_license
pope88/Servers
e54ae276ca4979bccd4043e823f0c7e56a444075
332960c5878a733fd6daf77c15a856d7570c8b5b
refs/heads/master
2021-01-10T22:05:07.995636
2013-12-18T11:59:52
2013-12-18T11:59:52
null
0
0
null
null
null
null
UTF-8
C++
false
false
44
cpp
#include "Config.h" #include "RoomManager.h"
[ "pope@fanersai.com" ]
pope@fanersai.com
86dabcdec48bc680ce572639d7d55ea122c7d770
c6fa53212eb03017f9e72fad36dbf705b27cc797
/CondFormats/HcalObjects/interface/HcalDcsValues.h
92e7a451de5df6c08ce5c04bb3cf846363fefc2c
[]
no_license
gem-sw/cmssw
a31fc4ef2233b2157e1e7cbe9a0d9e6c2795b608
5893ef29c12b2718b3c1385e821170f91afb5446
refs/heads/CMSSW_6_2_X_SLHC
2022-04-29T04:43:51.786496
2015-12-16T16:09:31
2015-12-16T16:09:31
12,892,177
2
4
null
2018-11-22T13:40:31
2013-09-17T10:10:26
C++
UTF-8
C++
false
false
2,015
h
// -*- C++ -*- #ifndef HcalDcsValues_h #define HcalDcsValues_h #include <iostream> //#include <set> #include <vector> #include "CondFormats/HcalObjects/interface/HcalDcsValue.h" #include "DataFormats/HcalDetId/interface/HcalDetId.h" #include "DataFormats/HcalDetId/interface/HcalDcsDetId.h" #include "DataFormats/HcalDetId/interface/HcalSubdetector.h" /* \class: HcalDcsValues \author: Jacob Anderson A container class for holding the dcs values from the database. The values are organized by subdetector, and sorted by HcalDcsDetId. There is also checking functionality to be able to see that the values are witin their set bounds. */ class HcalDcsValues { public: typedef std::vector<HcalDcsValue> DcsSet; //The subdetectors of interest to the Hcal run certification enum DcsSubDet{ HcalHB = 1, HcalHE = 2, HcalHO0 = 3, HcalHO12 = 4, HcalHF = 5 }; HcalDcsValues(); virtual ~HcalDcsValues(); // add a new value to the appropriate list bool addValue(HcalDcsValue const& newVal); void sortAll(); // check if a given id has any entries in a list bool exists(HcalDcsDetId const& fid); // get a list of values that are for the give id DcsSet getValues(HcalDcsDetId const& fid); DcsSet const & getAllSubdetValues(DcsSubDet subd) const; std::string myname() const { return (std::string)"HcalDcsValues"; } //Check the values of a subdetector. If LS is -1 then for the whole run //otherwise for the given LS. bool DcsValuesOK(DcsSubDet subd, int LS = -1); //bool DcsValuesOK(HcalDetID dataId, DcsMap, int LS = -1) const; protected: bool foundDcsId(DcsSet const& valList, HcalDcsDetId const& fid) const; bool subDetOk(DcsSet const& valList, int LS) const; bool sortList(DcsSet& valList) const; private: DcsSet mHBValues; mutable bool mHBsorted; DcsSet mHEValues; mutable bool mHEsorted; DcsSet mHO0Values; mutable bool mHO0sorted; DcsSet mHO12Values; mutable bool mHO12sorted; DcsSet mHFValues; mutable bool mHFsorted; }; #endif
[ "sha1-056215a7deed826ca8e627b453e96d110263ed4b@cern.ch" ]
sha1-056215a7deed826ca8e627b453e96d110263ed4b@cern.ch
ceba60fde640843dc90f27f40e9d1270c9cc4b7e
b2f2c4942f535285a28cfaa2127abc4a33a54c4a
/syzygy/agent/asan/block_impl.h
b15bb0b9d1e761804506e067043356efead854c2
[ "Apache-2.0" ]
permissive
pombreda/syzygy
4f71e27e54182e26ee3f6605be62d60210bb5820
7bac6936c0c28872bfabc10a1108e0157ff65d4a
refs/heads/master
2021-01-25T07:08:04.019036
2015-03-12T18:29:28
2015-03-12T18:29:28
32,210,396
1
1
null
null
null
null
UTF-8
C++
false
false
1,871
h
// Copyright 2014 Google Inc. 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. // // Internal implementation details for block.h. Not meant to be included // directly. #ifndef SYZYGY_AGENT_ASAN_BLOCK_IMPL_H_ #define SYZYGY_AGENT_ASAN_BLOCK_IMPL_H_ namespace agent { namespace asan { // Forward declaration. struct BlockInfo; // A structure describing the layout of a block. This is largely implementation // detail, but exposed for unittesting. As far as the user is concerned this is // an opaque blob. struct BlockLayout { // The alignment of the entire block. size_t block_alignment; // The size of the entire block (the rest of the fields summed). size_t block_size; // Left redzone. size_t header_size; size_t header_padding_size; // Body. size_t body_size; // Right redzone. size_t trailer_padding_size; size_t trailer_size; }; // Identifies whole pages that are spanned by the redzones and body of the // given block. Directly sets the various *_pages* fields in @p block_info. // @param block_info The block information to be inspected and modified. // @note This is exposed as a convience function, but it is not meant to be // directly called by the user. void BlockIdentifyWholePages(BlockInfo* block_info); } // namespace asan } // namespace agent #endif // SYZYGY_AGENT_ASAN_BLOCK_IMPL_H_
[ "chrisha@chromium.org" ]
chrisha@chromium.org
57b8c6381e06f5f9feb63ecf513c5990431572e1
ac0b9c85542e6d1ef59c5e9df4618ddf22223ae0
/kratos/applications/ParticleMechanicsApplication/custom_python/particle_mechanics_python_application.cpp
1ad1ae49f32b1657cda79ce03cc7400d53afeb66
[]
no_license
UPC-EnricBonet/trunk
30cb6fbd717c1e78d95ec66bc0f6df1a041b2b72
1cecfe201c8c9a1b87b2d87faf8e505b7b1f772d
refs/heads/master
2021-06-04T05:10:06.060945
2016-07-15T15:29:00
2016-07-15T15:29:00
33,677,051
3
0
null
null
null
null
UTF-8
C++
false
false
6,948
cpp
/* ============================================================================== KratosParticleMechanicsApplication A library based on: Kratos A General Purpose Software for Multi-Physics Finite Element Analysis Version 1.0 (Released on march 05, 2007). Copyright 2007 Pooyan Dadvand, Riccardo Rossi, Janosch Stascheit, Felix Nagel pooyan@cimne.upc.edu rrossi@cimne.upc.edu janosch.stascheit@rub.de nagel@sd.rub.de - CIMNE (International Center for Numerical Methods in Engineering), Gran Capita' s/n, 08034 Barcelona, Spain - Ruhr-University Bochum, Institute for Structural Mechanics, Germany 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 condition: Distribution of this code for any commercial purpose is permissible ONLY BY DIRECT ARRANGEMENT WITH THE COPYRIGHT OWNERS. 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. ============================================================================== */ // // Project Name: Kratos // Last modified by: $Author: ilaria $ // Date: $Date: July 2015$ // Revision: $Revision: 1.3 $ // // // System includes #if defined(KRATOS_PYTHON) // External includes #include <boost/python.hpp> // Project includes #include "includes/define.h" #include "custom_python/add_custom_strategies_to_python.h" #include "custom_python/add_custom_utilities_to_python.h" #include "custom_elements/updated_lagrangian.hpp" //#include "custom_elements/updated_lagrangian_quadrilateral.hpp" //#include "custom_elements/total_lagrangian.hpp" #include "geometries/triangle_3d_3.h" #include "geometries/triangle_2d_3.h" //#include "geometries/quadrilateral_2d_4.h" #include "geometries/tetrahedra_3d_4.h" #include "particle_mechanics_application.h" namespace Kratos { namespace Python { using namespace boost::python; Element::Pointer CreateUpdatedLagragian2D3N() { UpdatedLagrangian::Pointer NewElement( new UpdatedLagrangian( 0, Element::GeometryType::Pointer( new Triangle2D3 <Node<3> >( Element::GeometryType::PointsArrayType( 3, Node<3>() ) ) ) )); return NewElement; } Element::Pointer CreateUpdatedLagragian3D4N() { UpdatedLagrangian::Pointer NewElement( new UpdatedLagrangian( 0, Element::GeometryType::Pointer( new Tetrahedra3D4 <Node<3> >( Element::GeometryType::PointsArrayType( 4, Node<3>() ) ) ) )); return NewElement; } //Element::Pointer CreateUpdatedLagragian2D4N() //{ //UpdatedLagrangianQuad::Pointer NewElement( //new UpdatedLagrangianQuad( 0, Element::GeometryType::Pointer( new Quadrilateral2D4 <Node<3> >( Element::GeometryType::PointsArrayType( 4, Node<3>() ) ) ) )); //return NewElement; //} //Element::Pointer CreateTotalLagragian2D3N() //{ //TotalLagrangian::Pointer NewElement( //new TotalLagrangian( 0, Element::GeometryType::Pointer( new Triangle2D3 <Node<3> >( Element::GeometryType::PointsArrayType( 3, Node<3>() ) ) ) )); //return NewElement; //} //Element::Pointer CreateTotalLagragian3D4N() //{ //TotalLagrangian::Pointer NewElement( //new TotalLagrangian( 0, Element::GeometryType::Pointer( new Tetrahedra3D4 <Node<3> >( Element::GeometryType::PointsArrayType( 4, Node<3>() ) ) ) )); //return NewElement; //} BOOST_PYTHON_MODULE(KratosParticleMechanicsApplication) { class_<KratosParticleMechanicsApplication, KratosParticleMechanicsApplication::Pointer, bases<KratosApplication>, boost::noncopyable >("KratosParticleMechanicsApplication") ; AddCustomStrategiesToPython(); AddCustomUtilitiesToPython(); def("CreateUpdatedLagragian2D3N", &CreateUpdatedLagragian2D3N); def("CreateUpdatedLagragian3D4N", &CreateUpdatedLagragian3D4N); //def("CreateUpdatedLagragian2D4N", &CreateUpdatedLagragian2D4N); //def("CreateTotalLagragian2D3N", &CreateTotalLagragian2D3N); //def("CreateTotalLagragian3D4N", &CreateTotalLagragian3D4N); //registering variables in python KRATOS_REGISTER_IN_PYTHON_3D_VARIABLE_WITH_COMPONENTS( GAUSS_COORD ) KRATOS_REGISTER_IN_PYTHON_VARIABLE(COUNTER); KRATOS_REGISTER_IN_PYTHON_VARIABLE(MP_NUMBER); KRATOS_REGISTER_IN_PYTHON_VARIABLE(MP_BOOL); KRATOS_REGISTER_IN_PYTHON_VARIABLE(WEIGHT); KRATOS_REGISTER_IN_PYTHON_VARIABLE(MP_MASS); KRATOS_REGISTER_IN_PYTHON_VARIABLE(MP_DENSITY); KRATOS_REGISTER_IN_PYTHON_VARIABLE(MP_VOLUME); KRATOS_REGISTER_IN_PYTHON_VARIABLE(MP_KINETIC_ENERGY); KRATOS_REGISTER_IN_PYTHON_VARIABLE(MP_STRAIN_ENERGY); KRATOS_REGISTER_IN_PYTHON_VARIABLE(MP_TOTAL_ENERGY); //KRATOS_REGISTER_IN_PYTHON_VARIABLE(NODAL_MASS); KRATOS_REGISTER_IN_PYTHON_3D_VARIABLE_WITH_COMPONENTS(AUX_VELOCITY); KRATOS_REGISTER_IN_PYTHON_3D_VARIABLE_WITH_COMPONENTS(AUX_ACCELERATION); KRATOS_REGISTER_IN_PYTHON_VARIABLE(MP_DISPLACEMENT); KRATOS_REGISTER_IN_PYTHON_VARIABLE(MP_VELOCITY); KRATOS_REGISTER_IN_PYTHON_VARIABLE(MP_ACCELERATION); KRATOS_REGISTER_IN_PYTHON_VARIABLE(AUX_MP_VELOCITY); KRATOS_REGISTER_IN_PYTHON_VARIABLE(AUX_MP_ACCELERATION); KRATOS_REGISTER_IN_PYTHON_VARIABLE(MP_VOLUME_ACCELERATION); KRATOS_REGISTER_IN_PYTHON_VARIABLE(NODAL_INTERNAL_FORCE); KRATOS_REGISTER_IN_PYTHON_VARIABLE(DISPLACEMENT_AUX); KRATOS_REGISTER_IN_PYTHON_VARIABLE(MP_CAUCHY_STRESS_VECTOR); KRATOS_REGISTER_IN_PYTHON_VARIABLE(MP_ALMANSI_STRAIN_VECTOR); KRATOS_REGISTER_IN_PYTHON_VARIABLE(PREVIOUS_MP_CAUCHY_STRESS_VECTOR); KRATOS_REGISTER_IN_PYTHON_VARIABLE(PREVIOUS_MP_ALMANSI_STRAIN_VECTOR); KRATOS_REGISTER_IN_PYTHON_VARIABLE(MP_CONSTITUTIVE_MATRIX); KRATOS_REGISTER_IN_PYTHON_VARIABLE(NODAL_MOMENTUM); KRATOS_REGISTER_IN_PYTHON_VARIABLE(NODAL_INERTIA); //KRATOS_REGISTER_IN_PYTHON_VARIABLE(NODAL_AREA); //KRATOS_REGISTER_IN_PYTHON_VARIABLE( CONSTITUTIVE_LAW_POINTER ) //KRATOS_REGISTER_IN_PYTHON_VARIABLE( RAYLEIGH_ALPHA ) //KRATOS_REGISTER_IN_PYTHON_VARIABLE( RAYLEIGH_BETA ) //KRATOS_REGISTER_IN_PYTHON_VARIABLE( EXTERNAL_FORCES_VECTOR ) //KRATOS_REGISTER_IN_PYTHON_VARIABLE( INTERNAL_FORCES_VECTOR ) } } // namespace Python. } // namespace Kratos. #endif // KRATOS_PYTHON defined
[ "enriquebonetgil@hotmail.com" ]
enriquebonetgil@hotmail.com
1bfe8e427e1099b7b50ed23b051e3963061c4383
595f30484be107111b8dfa3c3d2f6726efd4cfc5
/tree.cpp
6f4f00c1da48ee9aa34c2e1770483b27fd1608a1
[ "MIT" ]
permissive
Alvazz/CarvingCat
c91560ea23eb5089916a24e09c1fd3adc63d2993
42ebdae03084ece64315c098802dd7f1c64a81df
refs/heads/main
2023-01-14T14:33:15.433378
2020-11-28T07:03:28
2020-11-28T07:03:28
null
0
0
null
null
null
null
UTF-8
C++
false
false
5,024
cpp
#include <iostream> #include <string> #include <queue> #include<stack> using namespace std; struct tree_node{ struct tree_node *left; struct tree_node *right; struct tree_node *parent; int val; }; void level_order_traversal(struct tree_node *root) { struct tree_node *node; queue<struct tree_node*> q; int i = 1; q.push(root); while(!q.empty()){ node = q.front(); q.pop(); node->val = i; cout << node->val << " "; if(node->left != NULL) q.push(node->left); if(node->right != NULL) q.push(node->right); i++; } cout << endl; } void pre_order_traversal(struct tree_node *root) { if(root != NULL){ cout << root->val << " "; pre_order_traversal(root->left); pre_order_traversal(root->right); } } void preorder_iterative(struct tree_node *root) { stack<struct tree_node*> stk; struct tree_node *current; stk.push(root); while(!stk.empty()){ current = stk.top(); stk.pop(); cout << current->val << " "; if(current->right != NULL) stk.push(current->right); if(current->left != NULL) stk.push(current->left); } } void in_order_traversal(struct tree_node *root) { if(root != NULL){ in_order_traversal(root->left); cout << root->val << " "; in_order_traversal(root->right); } } void inorder_iterative(struct tree_node *root) { struct tree_node *current; stack<struct tree_node*> stk; current = root; while(!stk.empty() || current != NULL){ while(current != NULL){ stk.push(current); current = current->left; } current = stk.top(); stk.pop(); cout << current->val << " "; current = current->right; } } void post_order_traversal(struct tree_node *root) { if(root != NULL){ post_order_traversal(root->left); post_order_traversal(root->right); cout << root->val << " "; } } void postorder_iterative(struct tree_node *root) { stack<struct tree_node*> stk; struct tree_node *current; stk.push(root); while(!stk.empty()){ current = stk.top(); if(current->right == NULL && current->left == NULL){ cout << current->val << " "; stk.pop(); } if(current->right != NULL) stk.push(current->right); if(current->left != NULL) stk.push(current->left); current->right = NULL; current->left = NULL; } } int max_depth(struct tree_node *root) { int maximum_depth; int left_depth; int right_depth; if(root == NULL) return 0; if(root->left == NULL && root->right == NULL) return 1; if(root->left != NULL) left_depth = max_depth(root->left); if(root->right != NULL) right_depth = max_depth(root->right); maximum_depth = max(left_depth, right_depth); return maximum_depth+1; } int min_depth(struct tree_node *root) { int minimum_depth; int left_depth; int right_depth; if(root == NULL) return 0; if(root->left == NULL && root->right == NULL) return 1; if(root->left != NULL) left_depth = min_depth(root->left); if(root->right != NULL) right_depth = min_depth(root->right); minimum_depth = min(left_depth, right_depth); return minimum_depth+1; } int main() { struct tree_node *a = new tree_node; struct tree_node *b = new tree_node; struct tree_node *c = new tree_node; struct tree_node *d = new tree_node; struct tree_node *e = new tree_node; struct tree_node *f = new tree_node; struct tree_node *g = new tree_node; struct tree_node *h = new tree_node; struct tree_node *i = new tree_node; struct tree_node *j = new tree_node; a->left = b; a->right = c; b->left = d; b->right = e; d->left = NULL; d->right = NULL; e->left = g; e->right = h; c->left = f; c->right = NULL; f->left = NULL; f->right = i; g->left = NULL; g->right = NULL; h->left = NULL; h->right = NULL; i->left = NULL; i->right = NULL; level_order_traversal(a); cout << "max_depth = " << max_depth(a) << endl; cout << "min_depth = " << min_depth(a) << endl; cout << "pre_order_traversal" << endl; pre_order_traversal(a); cout << endl; cout << "preorder_iterative" << endl; preorder_iterative(a); cout << endl; cout << "in_order_traversal" << endl; in_order_traversal(a); cout << endl; cout << "inorder_iterative" << endl; inorder_iterative(a); cout << endl; cout << "post_order_traversal" << endl; post_order_traversal(a); cout << endl; cout << "postorder_iterative" << endl; postorder_iterative(a); cout << endl; return 0; }
[ "s880367@gmail.com" ]
s880367@gmail.com
18c5d5bf0bc6d94b3e8397bf19d42f568a8769c9
0bef9637ea35797a1e23f72cb3900be59b5a790f
/HardwareSensor/ASSFaceEither.cpp
a2262d60eaccf603992244e553124e7969195c12
[]
no_license
Agile2018/HardwareSensor
72635739cb2c8c2a32474ebcb1bc2b06bcae2910
8503fb4c828601b2fcd838580c88128e60279a76
refs/heads/master
2020-05-18T14:27:42.833469
2019-05-13T18:34:36
2019-05-13T18:34:36
184,472,348
0
0
null
null
null
null
UTF-8
C++
false
false
384
cpp
#include "ASSFaceEither.h" void ASSFaceEither::Clear() { _code = 0; _label = ""; } int ASSFaceEither::GetCode() { return _code; } string ASSFaceEither::GetLabel() { return _label; } void ASSFaceEither::SetCode(int code) { _code = code; } void ASSFaceEither::SetLabel(string label) { _label = label; } ASSFaceEither::ASSFaceEither() { } ASSFaceEither::~ASSFaceEither() { }
[ "david.arturo.silva@gmail.com" ]
david.arturo.silva@gmail.com
875a94ff856cb2ea6f2e72fa11d7151641c6a646
c9ea4b7d00be3092b91bf157026117bf2c7a77d7
/比赛/校内/NOIP模拟试题/201811080800(40)[NOILinux]/ck.cpp
d9589879bdcb5bf4b363b857e2f0db8bfba5a952
[]
no_license
Jerry-Terrasse/Programming
dc39db2259c028d45c58304e8f29b2116eef4bfd
a59a23259d34a14e38a7d4c8c4d6c2b87a91574c
refs/heads/master
2020-04-12T08:31:48.429416
2019-04-20T00:32:55
2019-04-20T00:32:55
162,387,499
3
0
null
null
null
null
UTF-8
C++
false
false
514
cpp
#include<iostream> #include<ctime> #include<cstdilb> #include<cstdio> using namespace std; int main() { int t=0; for(;;++t) { cout<<t<<':'<<endl; system("./da >c.in"); system("./1 <c.in >c.1"); system("./2 <c.in >c.2"); system("./bf <c.in >c.bf"); system("./c_set <c.in >c.set"); if(system("diff c.1 c.2")||system("diff c.2 c.bf")||system("diff c.bf c.set")) { system("pause"); system("pause"); } else { cout<<"AC"<<endl; } } return 0; }
[ "3305049949@qq.com" ]
3305049949@qq.com
92d7363157bc290bb8c12c6dc97aee0ac44331df
b7ec1f746d70f37379b684a9b39da011c2bf7572
/R2DebugMod/teleport.cpp
d25383221c757708ebe5603601ed36f7269de2f6
[]
no_license
kellsnc/R2DebugMod
0105dea4be32988219a88aec9b9fddc829f43327
4f3c3992f48a98403309160388ab93e63abc733f
refs/heads/master
2023-03-30T15:04:52.705344
2021-03-31T22:01:35
2021-03-31T22:01:35
352,388,425
0
0
null
null
null
null
UTF-8
C++
false
false
2,178
cpp
#include "pch.h" Trampoline* PreDrawLanguageText_t = nullptr; #define CopyPosButton 0x43 #define PastePosButton 0x56 static bool EnableTeleport = true; static bool ShowCopyNotPaste = false; static int TeleportTimer = 0; static Vector3 SavedPosition = {}; void __cdecl PreDrawLanguageText_r(int context) { TARGET_DYNAMIC(PreDrawLanguageText)(context); Text2D text = {}; Vector3* pos = GetPlayerPosition(); std::string string = "Position: " + std::to_string(pos->x) + ", " + std::to_string(pos->z) + ", " + std::to_string(pos->y); text.text = string.c_str(); text.positionX = 10; text.positionY = 10; text.size = 5; text.alphaByte = 255; _DrawText(0x5004D4, &text); if (SavedPosition.length() != 0) { if (TeleportTimer > 0) { string = ShowCopyNotPaste == true ? "Position saved!" : "Teleported!"; } else { string = "Saved position: " + std::to_string(SavedPosition.x) + ", " + std::to_string(SavedPosition.z) + ", " + std::to_string(SavedPosition.y); } text.text = string.c_str(); text.positionY = 30; text.size = 3; text.alphaByte = TeleportTimer > 0 ? TeleportTimer : 255; _DrawText(0x5004D4, &text); } } void Teleport_OnFrame() { if (EnableTeleport && TeleportTimer <= 0) { if (GetAsyncKeyState(CopyPosButton) & KEY_PRESSED) { SavedPosition = *GetPlayerPosition(); ShowCopyNotPaste = true; TeleportTimer = 255; } else if (GetAsyncKeyState(PastePosButton) & KEY_PRESSED) { if (SavedPosition.length() != 0) { SetPlayerPosition(&SavedPosition); ShowCopyNotPaste = false; TeleportTimer = 255; } } } if (TeleportTimer > 0) { TeleportTimer -= 10; } } void Teleport_Init(const IniFile* config) { EnableTeleport = config->getBool("", "EnableTeleport", EnableTeleport); if (config->getBool("", "ShowPosition", false)) { PreDrawLanguageText_t = new Trampoline((int)PreDrawLanguageText, (int)PreDrawLanguageText + 0x5, PreDrawLanguageText_r); } }
[ "kellspam@outlook.fr" ]
kellspam@outlook.fr
65adf1b91f3597974991120fd11151d526e95d12
05627ea25c2b369cc438fc161d4d711627bbd9ed
/toj 353_AC.cpp
fbc63526cb2fa8e238ebbad6528f7d581e7edc00
[]
no_license
SCJ1210/OJ_code
0ada81a1d4791e0b7d12ee8d786acead18c18b3c
13b2d49ad6433ce2114cc08f48d22edaea4d2a0b
refs/heads/master
2021-01-13T05:33:59.625979
2017-03-01T12:53:55
2017-03-01T12:53:55
79,987,439
0
0
null
null
null
null
UTF-8
C++
false
false
621
cpp
//By SCJ #include<bits/stdc++.h> using namespace std; #define endl '\n' int dp[5005][5005]; char x[5005],y[5005]; int main() { int A,B,C; scanf("%d%d%d",&A,&B,&C); x[0]=y[0]=' '; scanf("%s%s",x+1,y+1); int n=strlen(x)-1,m=strlen(y)-1; for(int i=1;i<=n;++i) dp[i][0]=dp[i-1][0]+B; for(int i=1;i<=m;++i) dp[0][i]=dp[0][i-1]+A; for(int i=1;i<=n;++i) { for(int j=1;j<=m;++j) { int tp=min(abs(x[i]-y[j]),26-abs(x[i]-y[i]))*C; //tp=min(tp,A+B); dp[i][j]=min({dp[i-1][j]+B,dp[i][j-1]+A,dp[i-1][j-1]+tp}); } } printf("%d\n",dp[n][m]); } /* 4 2 3 DOMEN DOMAIN 1 1 1 DOMEN ABDOMEN 3 2 1 DOMEN DOORS */
[ "stu41235njrmpru8@gmail.com" ]
stu41235njrmpru8@gmail.com
137829cccfb76112fecbaef861ff065f3cb54b9e
c45ed46065d8b78dac0dd7df1c95b944f34d1033
/TC-SRM-581-div1-250/613.cpp
08601d01bc08c28039addca268e53bf56967973e
[]
no_license
yzq986/cntt2016-hw1
ed65a6b7ad3dfe86a4ff01df05b8fc4b7329685e
12e799467888a0b3c99ae117cce84e8842d92337
refs/heads/master
2021-01-17T11:27:32.270012
2017-01-26T03:23:22
2017-01-26T03:23:22
84,036,200
0
0
null
2017-03-06T06:04:12
2017-03-06T06:04:12
null
UTF-8
C++
false
false
3,711
cpp
// BEGIN CUT HERE // END CUT HERE #line 5 "SurveillanceSystem.cpp" #include <cstdlib> #include <cctype> #include <cstring> #include <cstdio> #include <cmath> #include <algorithm> #include <vector> #include <string> #include <iostream> #include <sstream> #include <map> #include <set> #include <queue> #include <stack> #include <fstream> #include <numeric> #include <iomanip> #include <bitset> #include <list> #include <stdexcept> #include <functional> #include <utility> #include <ctime> using namespace std; int js[210],sum[210][210],bo[210],ls[210]; class SurveillanceSystem { public: string getContainerInfo(string st, vector <int> rep, int l) { for (int i=0;i<rep.size();i++) js[rep[i]]++; for (int i=0;i<st.length();i++) for (int j=i;j<st.length();j++) if (i==j) sum[i][j]=(st[i]=='X');else sum[i][j]=(st[j]=='X')+sum[i][j-1]; for (int i=0;i<=l;i++) if (js[i]) { int p=0; memset(ls,0,sizeof(ls)); for (int j=0;j<=st.length()-l;j++) if (sum[j][j+l-1]==i) {p++;for (int k=j;k<j+l;k++) ls[k]++;} //for (int j=0;j<st.length();j++) cout<<ls[j]<<' '; //cout<<endl<<endl; for (int j=0;j<st.length();j++) { if (ls[j]>=p-js[i]+1) bo[j]=max(bo[j],2); else if (ls[j]) bo[j]=max(bo[j],1); } } string s; for (int i=0;i<st.length();i++) if (bo[i]==2) s=s+"+";else if (bo[i]==0) s=s+"-";else s=s+"?"; return s; } // BEGIN CUT HERE public: void run_test(int Case) { if ((Case == -1) || (Case == 0)) test_case_0(); if ((Case == -1) || (Case == 1)) test_case_1(); if ((Case == -1) || (Case == 2)) test_case_2(); if ((Case == -1) || (Case == 3)) test_case_3(); if ((Case == -1) || (Case == 4)) test_case_4(); } private: template <typename T> string print_array(const vector<T> &V) { ostringstream os; os << "{ "; for (typename vector<T>::const_iterator iter = V.begin(); iter != V.end(); ++iter) os << '\"' << *iter << "\","; os << " }"; return os.str(); } void verify_case(int Case, const string &Expected, const string &Received) { cerr << "Test Case #" << Case << "..."; if (Expected == Received) cerr << "PASSED" << endl; else { cerr << "FAILED" << endl; cerr << "\tExpected: \"" << Expected << '\"' << endl; cerr << "\tReceived: \"" << Received << '\"' << endl; } } void test_case_0() { string Arg0 = "-X--XX"; int Arr1[] = {1, 2}; vector <int> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); int Arg2 = 3; string Arg3 = "??++++"; verify_case(0, Arg3, getContainerInfo(Arg0, Arg1, Arg2)); } void test_case_1() { string Arg0 = "-XXXXX-"; int Arr1[] = {2}; vector <int> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); int Arg2 = 3; string Arg3 = "???-???"; verify_case(1, Arg3, getContainerInfo(Arg0, Arg1, Arg2)); } void test_case_2() { string Arg0 = "------X-XX-"; int Arr1[] = {3, 0, 2, 0}; vector <int> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); int Arg2 = 5; string Arg3 = "++++++++++?"; verify_case(2, Arg3, getContainerInfo(Arg0, Arg1, Arg2)); } void test_case_3() { string Arg0 = "-XXXXX---X--"; int Arr1[] = {2, 1, 0, 1}; vector <int> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); int Arg2 = 3; string Arg3 = "???-??++++??"; verify_case(3, Arg3, getContainerInfo(Arg0, Arg1, Arg2)); } void test_case_4() { string Arg0 = "-XX--X-XX-X-X--X---XX-X---XXXX-----X"; int Arr1[] = {3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3}; vector <int> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); int Arg2 = 7; string Arg3 = "???++++?++++++++++++++++++++??????--"; verify_case(4, Arg3, getContainerInfo(Arg0, Arg1, Arg2)); } // END CUT HERE }; // BEGIN CUT HERE int main() { SurveillanceSystem ___test; ___test.run_test(1); return 0; } // END CUT HERE
[ "lyx13958187360@126.com" ]
lyx13958187360@126.com
d4c134e5d3e43cae65637d8a9e37cdc719c9bb89
27d5670a7739a866c3ad97a71c0fc9334f6875f2
/Blindmode/CPP/Targets/MapLib/Windows/src/WinBitmap.cpp
739aa17f6e1bfe9dd4fef78a142d43e84e240604
[ "BSD-3-Clause" ]
permissive
ravustaja/Wayfinder-S60-Navigator
ef506c418b8c2e6498ece6dcae67e583fb8a4a95
14d1b729b2cea52f726874687e78f17492949585
refs/heads/master
2021-01-16T20:53:37.630909
2010-06-28T09:51:10
2010-06-28T09:51:10
null
0
0
null
null
null
null
UTF-8
C++
false
false
12,429
cpp
/* Copyright (c) 1999 - 2010, Vodafone Group Services Ltd 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 Vodafone Group Services Ltd nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "WinBitmap.h" #include <cstring> #include <cstdio> #include "BitBuffer.h" /* the global logging file */ #include <fstream> extern ofstream gLogFile; #include <cstdio> #include <cstring> namespace isab { /* private constructor */ WinBitmap::WinBitmap() : m_bmp(NULL), m_mask(NULL), m_oldBmp(NULL), m_dc(NULL), m_width(0), m_height(0), m_isMasked(false) { } int WinBitmap::readColorMapData( const TGAHEADER& tgaHeader, const byte* colorData ) { if ( tgaHeader.colorMapType == 0 ) { // No colormap information available. return 0; } uint16 colorMapLength = tgaHeader.colorMapSpec[2] + (tgaHeader.colorMapSpec[3] << 8); uint8 colorMapEntrySize = tgaHeader.colorMapSpec[4]; // The length of the buffer is not necessarily correct, however // it doesn't matter. We won't read too long. BitBuffer cmBuf( (byte*) colorData, colorMapLength * 4 ); PIXEL pixel; m_colorMap.reserve( colorMapLength ); for( int i = 0; i < colorMapLength; ++i ) { switch (colorMapEntrySize) { case 8: default: { // Gray scale. pixel.red=cmBuf.readNextBAByte(); pixel.green=pixel.red; pixel.blue=pixel.red; break; } // XXX: Does not handle case 15 or 16. case 24: case 32: { // 8 bits each of blue, green and red. pixel.blue=cmBuf.readNextBAByte(); pixel.green=cmBuf.readNextBAByte(); pixel.red=cmBuf.readNextBAByte(); break; } } // Add pixel to color map. m_colorMap.push_back( pixel ); } // Return the offset. return cmBuf.getCurrentOffset(); } /* second-phase constrcutor */ bool WinBitmap::construct(const byte* dataBuf, uint32 nbrBytes) { /* get the current DC format */ m_dc = CreateCompatibleDC(NULL); if(m_dc == NULL) { return(false); } /** TGA Implementation **/ #if 1 register int32 row, col; register int32 index; int32 red, green, blue, alpha; int32 bitDepth; HDC maskDC = NULL; HBITMAP oldMaskBmp = NULL; /* get the BMP file information */ TGAHEADER tgaHeader; ::memcpy(&tgaHeader, dataBuf, sizeof(TGAHEADER)); /* get the location of the color data */ int offset = sizeof(TGAHEADER) + tgaHeader.numCharsID; const byte* colorData = reinterpret_cast<const byte*>(&dataBuf[offset]); bool useColorMap = false; if ( tgaHeader.colorMapType == 1 ) { // Use color map. useColorMap = true; // Read the color map data. int offsetToColorData = readColorMapData( tgaHeader, colorData ); // Add the offset to colorData so that the colorData actually // points to the color data instead of to the color map. colorData += offsetToColorData; } // colorData should now point at the color data! /* set the dimensions */ m_width = tgaHeader.imageWidth; m_height = tgaHeader.imageHeight; /* get the bit-depth of the image */ bitDepth = tgaHeader.bitsPerPixel; /* create the bitmap using the given info */ m_bmp = CreateBitmap(m_width, m_height, 1, GetDeviceCaps(m_dc, BITSPIXEL), NULL); if(m_bmp == NULL) { /* cannot create bitmap */ return(false); } /* select the bitmap into the DC */ m_oldBmp = (HBITMAP)SelectObject(m_dc, m_bmp); /* create the same sized monocrome mask if required */ if(bitDepth == 32) { m_mask = CreateBitmap(m_width, m_height, 1, 1, NULL); /* check for errors */ if(m_mask == NULL) { return(false); } /* create DC, and select the mask into it */ maskDC = CreateCompatibleDC(NULL); /* check for errors */ if(maskDC == NULL) { return(false); } /* select our monochrome mask into it */ oldMaskBmp = (HBITMAP)SelectObject(maskDC, m_mask); } /* Bottom-up TGAs are expected .. read and create */ index = 0; for(row = m_height-1; row >= 0; --row) { for(col = 0; col < m_width; ++col) { /* 32-bit TGAs need different processing from 24-bit */ if(bitDepth == 32) { if ( useColorMap ) { int colorMapIdx = colorData[ index++ ]; PIXEL p = m_colorMap[ colorMapIdx ]; blue = p.blue; green = p.green; red = p.red; alpha = 255; } else { // No color map. /* read the color value in components */ blue = colorData[index++]; green = colorData[index++]; red = colorData[index++]; alpha = colorData[index++]; } /* write the color pixel */ SetPixelV(m_dc, col, row, RGB(red,green,blue)); /* check the alpha component */ if(alpha > 127) { /* solid pixel */ SetPixelV(maskDC, col, row, RGB(255,255,255)); } else { /* transparent pixel */ SetPixelV(maskDC, col, row, RGB(0,0,0)); } } /* expecting 24-bit RGB Image */ else { if ( useColorMap ) { int colorMapIdx = colorData[ index++ ]; PIXEL p = m_colorMap[ colorMapIdx ]; blue = p.blue; green = p.green; red = p.red; } else { // No color map. /* read the color value in components */ blue = colorData[index++]; green = colorData[index++]; red = colorData[index++]; } /* write the color pixel */ SetPixelV(m_dc, col, row, RGB(red,green,blue)); } } } /* release the mask DC if used */ if(bitDepth == 32) { SelectObject(maskDC, oldMaskBmp); DeleteDC(maskDC); } if(bitDepth == 32) { /* set our masked flag */ m_isMasked = true; } else { m_isMasked = false; } /* success */ return(true); #endif /** BMP Implementation **/ #if 0 register int32 row, col; register int32 index; int32 red, green, blue, alpha; HDC maskDC = NULL; HBITMAP oldMaskBmp = NULL; /* get the BMP file information */ BITMAPFILEHEADER bmHeader; BITMAPINFOHEADER bmInfo; ::memcpy(&bmHeader, dataBuf, sizeof(BITMAPFILEHEADER)); ::memcpy(&bmInfo, &dataBuf[sizeof(BITMAPFILEHEADER)], sizeof(BITMAPINFOHEADER)); /* get the location of the color data */ const byte* colorData = reinterpret_cast<const byte*>(&dataBuf[bmHeader.bfOffBits]); /* set the dimensions */ m_width = bmInfo.biWidth; m_height = bmInfo.biHeight; /* create the bitmap using the given info */ m_bmp = CreateBitmap(m_width, m_height, 1, GetDeviceCaps(m_dc, BITSPIXEL), NULL); if(m_bmp == NULL) { /* cannot create bitmap */ return(false); } /* select the bitmap into the DC */ m_oldBmp = (HBITMAP)SelectObject(m_dc, m_bmp); /* create the same sized monocrome mask if required */ if(bmInfo.biBitCount == 32) { m_mask = CreateBitmap(m_width, m_height, 1, 1, NULL); /* check for errors */ if(m_mask == NULL) { return(false); } /* create DC, and select the mask into it */ maskDC = CreateCompatibleDC(NULL); /* check for errors */ if(maskDC == NULL) { return(false); } /* select our monochrome mask into it */ oldMaskBmp = (HBITMAP)SelectObject(maskDC, m_mask); } /* Bottom-up BMP's are expected .. read and create */ index = 0; for(row = m_height-1; row >= 0; --row) { for(col = 0; col < m_width; ++col) { /* 32-bit BMP's need different processing from 24-bit */ if(bmInfo.biBitCount == 32) { /* read the color value in components */ alpha = colorData[index++]; blue = colorData[index++]; green = colorData[index++]; red = colorData[index++]; /* write the color pixel */ SetPixelV(m_dc, col, row, RGB(red,green,blue)); /* check the alpha component */ if(alpha > 127) { /* solid pixel */ SetPixelV(maskDC, col, row, RGB(255,255,255)); } else { /* transparent pixel */ SetPixelV(maskDC, col, row, RGB(0,0,0)); } } /* expecting 24-bit RGB Image */ else { /* read the color value in components */ blue = colorData[index++]; green = colorData[index++]; red = colorData[index++]; /* write the color pixel */ SetPixelV(m_dc, col, row, RGB(red,green,blue)); } } } /* release the mask DC if used */ if(bmInfo.biBitCount == 32) { SelectObject(maskDC, oldMaskBmp); DeleteDC(maskDC); } if(bmInfo.biBitCount == 32) { /* set our masked flag */ m_isMasked = true; } else { m_isMasked = false; } /* success */ return(true); #endif /* TESTING Implemntation */ #if 0 /* try to create the bitmap -- TESTING */ m_bmp = CreateBitmap(7, 7, 1, GetDeviceCaps(m_dc, BITSPIXEL), NULL); if(m_bmp == NULL) { /* delete the DC */ DeleteDC(m_dc); return(false); } /* select the bitmap into the DC */ m_oldBmp = (HBITMAP)SelectObject(m_dc, m_bmp); /* set the dimensions */ m_width = 7; m_height = 7; /* TEST - clear the bitmap */ HBRUSH clrBrush = CreateSolidBrush( RGB(200,20,20) ); RECT bmpRect; SetRect(&bmpRect, 0, 0, m_width, m_height); FillRect(m_dc, &bmpRect, clrBrush); DeleteObject(clrBrush); /* success */ return(true); #endif } /* allocator */ WinBitmap* WinBitmap::allocate(const byte* dataBuf, uint32 nbrBytes) { /* create the new object */ WinBitmap* newObj = new WinBitmap(); if(newObj == NULL) { return(NULL); } /* do second-phase construction */ if(!newObj->construct(dataBuf, nbrBytes)) { /* delete the allocated object */ delete newObj; return(NULL); } /* return the newly allocated object */ return(newObj); } /* destructor */ WinBitmap::~WinBitmap() { /* delete the mask bitmap */ if(m_mask) { DeleteObject(m_mask); } if(m_bmp) { /* restore the original bitmap */ SelectObject(m_dc, m_oldBmp); /* delete the DC */ DeleteDC(m_dc); /* delete our bitmap */ DeleteObject(m_bmp); } if(m_dc) { /* delete the DC */ DeleteDC(m_dc); } } };
[ "hlars@sema-ovpn-morpheus.itinerary.com" ]
hlars@sema-ovpn-morpheus.itinerary.com
ae6fa38befc614d4c56774fa6146660f363e5f1c
93ea6c91d410abd7e8e08aaa9ed833bbd0d55064
/common/libmix/videoencoder/VideoEncoderBase.cpp
f8d2a618c450c424e4d39ee0e037ebc65277a9e9
[]
no_license
tank0412/android_hardware_intel-1
4c7a0f02b6b878d2e48d12d6b0f20cc184676f51
0c96fe72615b7ca1b3b09e16923d84ce1476b1ad
refs/heads/master
2021-01-22T00:10:19.567866
2016-03-06T17:10:34
2016-03-06T17:10:34
53,292,711
0
1
null
2016-03-07T03:23:09
2016-03-07T03:23:09
null
UTF-8
C++
false
false
65,052
cpp
/* * Copyright (c) 2009-2011 Intel Corporation. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <string.h> #include "VideoEncoderLog.h" #include "VideoEncoderBase.h" #include "IntelMetadataBuffer.h" #include <va/va_tpi.h> #include <va/va_android.h> VideoEncoderBase::VideoEncoderBase() :mInitialized(true) ,mStarted(false) ,mVADisplay(NULL) ,mVAContext(VA_INVALID_ID) ,mVAConfig(VA_INVALID_ID) ,mVAEntrypoint(VAEntrypointEncSlice) ,mNewHeader(false) ,mRenderMaxSliceSize(false) ,mRenderQP (false) ,mRenderAIR(false) ,mRenderCIR(false) ,mRenderFrameRate(false) ,mRenderBitRate(false) ,mRenderHrd(false) ,mRenderMultiTemporal(false) ,mForceKFrame(false) ,mSeqParamBuf(0) ,mPicParamBuf(0) ,mSliceParamBuf(0) ,mAutoRefSurfaces(NULL) ,mRefSurface(VA_INVALID_SURFACE) ,mRecSurface(VA_INVALID_SURFACE) ,mFrameNum(0) ,mCodedBufSize(0) ,mAutoReference(false) ,mAutoReferenceSurfaceNum(4) ,mEncPackedHeaders(VA_ATTRIB_NOT_SUPPORTED) ,mSliceSizeOverflow(false) ,mCurOutputTask(NULL) ,mOutCodedBuffer(0) ,mOutCodedBufferPtr(NULL) ,mCurSegment(NULL) ,mOffsetInSeg(0) ,mTotalSize(0) ,mTotalSizeCopied(0) ,mFrameSkipped(false) ,mSupportedSurfaceMemType(0) ,mVASurfaceMappingAction(0) #ifdef INTEL_VIDEO_XPROC_SHARING ,mSessionFlag(0) #endif { VAStatus vaStatus = VA_STATUS_SUCCESS; // here the display can be any value, use following one // just for consistence purpose, so don't define it unsigned int display = 0x18C34078; int majorVersion = -1; int minorVersion = -1; setDefaultParams(); LOG_V("vaGetDisplay \n"); mVADisplay = vaGetDisplay(&display); if (mVADisplay == NULL) { LOG_E("vaGetDisplay failed."); } vaStatus = vaInitialize(mVADisplay, &majorVersion, &minorVersion); LOG_V("vaInitialize \n"); if (vaStatus != VA_STATUS_SUCCESS) { LOG_E( "Failed vaInitialize, vaStatus = %d\n", vaStatus); mInitialized = false; } } VideoEncoderBase::~VideoEncoderBase() { VAStatus vaStatus = VA_STATUS_SUCCESS; stop(); vaStatus = vaTerminate(mVADisplay); LOG_V( "vaTerminate\n"); if (vaStatus != VA_STATUS_SUCCESS) { LOG_W( "Failed vaTerminate, vaStatus = %d\n", vaStatus); } else { mVADisplay = NULL; } #ifdef INTEL_VIDEO_XPROC_SHARING IntelMetadataBuffer::ClearContext(mSessionFlag, false); #endif } Encode_Status VideoEncoderBase::start() { Encode_Status ret = ENCODE_SUCCESS; VAStatus vaStatus = VA_STATUS_SUCCESS; if (!mInitialized) { LOGE("Encoder Initialize fail can not start"); return ENCODE_DRIVER_FAIL; } if (mStarted) { LOG_V("Encoder has been started\n"); return ENCODE_ALREADY_INIT; } if (mComParams.rawFormat != RAW_FORMAT_NV12) #ifdef IMG_GFX mVASurfaceMappingAction |= MAP_ACTION_COLORCONVERT; #else return ENCODE_NOT_SUPPORTED; #endif if (mComParams.resolution.width > 2048 || mComParams.resolution.height > 2048){ LOGE("Unsupported resolution width %d, height %d\n", mComParams.resolution.width, mComParams.resolution.height); return ENCODE_NOT_SUPPORTED; } queryAutoReferenceConfig(mComParams.profile); VAConfigAttrib vaAttrib_tmp[6],vaAttrib[VAConfigAttribTypeMax]; int vaAttribNumber = 0; vaAttrib_tmp[0].type = VAConfigAttribRTFormat; vaAttrib_tmp[1].type = VAConfigAttribRateControl; vaAttrib_tmp[2].type = VAConfigAttribEncAutoReference; vaAttrib_tmp[3].type = VAConfigAttribEncPackedHeaders; vaAttrib_tmp[4].type = VAConfigAttribEncMaxRefFrames; vaAttrib_tmp[5].type = VAConfigAttribEncRateControlExt; vaStatus = vaGetConfigAttributes(mVADisplay, mComParams.profile, VAEntrypointEncSlice, &vaAttrib_tmp[0], 6); CHECK_VA_STATUS_RETURN("vaGetConfigAttributes"); if((vaAttrib_tmp[0].value & VA_RT_FORMAT_YUV420) != 0) { vaAttrib[vaAttribNumber].type = VAConfigAttribRTFormat; vaAttrib[vaAttribNumber].value = VA_RT_FORMAT_YUV420; vaAttribNumber++; } vaAttrib[vaAttribNumber].type = VAConfigAttribRateControl; vaAttrib[vaAttribNumber].value = mComParams.rcMode; vaAttribNumber++; vaAttrib[vaAttribNumber].type = VAConfigAttribEncAutoReference; vaAttrib[vaAttribNumber].value = mAutoReference ? 1 : VA_ATTRIB_NOT_SUPPORTED; vaAttribNumber++; if(vaAttrib_tmp[3].value != VA_ATTRIB_NOT_SUPPORTED) { vaAttrib[vaAttribNumber].type = VAConfigAttribEncPackedHeaders; vaAttrib[vaAttribNumber].value = vaAttrib[3].value; vaAttribNumber++; mEncPackedHeaders = vaAttrib[3].value; } if(vaAttrib_tmp[4].value != VA_ATTRIB_NOT_SUPPORTED) { vaAttrib[vaAttribNumber].type = VAConfigAttribEncMaxRefFrames; vaAttrib[vaAttribNumber].value = vaAttrib[4].value; vaAttribNumber++; mEncMaxRefFrames = vaAttrib[4].value; } if(vaAttrib_tmp[5].value != VA_ATTRIB_NOT_SUPPORTED) { vaAttrib[vaAttribNumber].type = VAConfigAttribEncRateControlExt; vaAttrib[vaAttribNumber].value = mComParams.numberOfLayer; vaAttribNumber++; } LOG_V( "======VA Configuration======\n"); LOG_V( "profile = %d\n", mComParams.profile); LOG_V( "mVAEntrypoint = %d\n", mVAEntrypoint); LOG_V( "vaAttrib[0].type = %d\n", vaAttrib[0].type); LOG_V( "vaAttrib[1].type = %d\n", vaAttrib[1].type); LOG_V( "vaAttrib[2].type = %d\n", vaAttrib[2].type); LOG_V( "vaAttrib[0].value (Format) = %d\n", vaAttrib[0].value); LOG_V( "vaAttrib[1].value (RC mode) = %d\n", vaAttrib[1].value); LOG_V( "vaAttrib[2].value (AutoReference) = %d\n", vaAttrib[2].value); LOG_V( "vaAttribNumber is %d\n", vaAttribNumber); LOG_V( "mComParams.numberOfLayer is %d\n", mComParams.numberOfLayer); LOG_V( "vaCreateConfig\n"); vaStatus = vaCreateConfig( mVADisplay, mComParams.profile, mVAEntrypoint, &vaAttrib[0], 2, &(mVAConfig)); // &vaAttrib[0], 3, &(mVAConfig)); //uncomment this after psb_video supports CHECK_VA_STATUS_RETURN("vaCreateConfig"); querySupportedSurfaceMemTypes(); if (mComParams.rcMode == VA_RC_VCM) { // Following three features are only enabled in VCM mode mRenderMaxSliceSize = true; mRenderAIR = true; mRenderBitRate = true; } LOG_V( "======VA Create Surfaces for Rec/Ref frames ======\n"); uint32_t stride_aligned, height_aligned; if(mAutoReference == false){ stride_aligned = (mComParams.resolution.width + 15) & ~15; height_aligned = (mComParams.resolution.height + 15) & ~15; }else{ // this alignment is used for AVC. For vp8 encode, driver will handle the alignment if(mComParams.profile == VAProfileVP8Version0_3) { stride_aligned = mComParams.resolution.width; height_aligned = mComParams.resolution.height; mVASurfaceMappingAction |= MAP_ACTION_COPY; } else { stride_aligned = (mComParams.resolution.width + 63) & ~63; //on Merr, stride must be 64 aligned. height_aligned = (mComParams.resolution.height + 31) & ~31; mVASurfaceMappingAction |= MAP_ACTION_ALIGN64; } } if(mAutoReference == false){ mRefSurface = CreateNewVASurface(mVADisplay, stride_aligned, height_aligned); mRecSurface = CreateNewVASurface(mVADisplay, stride_aligned, height_aligned); }else { mAutoRefSurfaces = new VASurfaceID [mAutoReferenceSurfaceNum]; for(uint32_t i = 0; i < mAutoReferenceSurfaceNum; i ++) mAutoRefSurfaces[i] = CreateNewVASurface(mVADisplay, stride_aligned, height_aligned); } CHECK_VA_STATUS_RETURN("vaCreateSurfaces"); //Prepare all Surfaces to be added into Context uint32_t contextSurfaceCnt; if(mAutoReference == false ) contextSurfaceCnt = 2 + mSrcSurfaceMapList.size(); else contextSurfaceCnt = mAutoReferenceSurfaceNum + mSrcSurfaceMapList.size(); VASurfaceID *contextSurfaces = new VASurfaceID[contextSurfaceCnt]; int32_t index = -1; android::List<VASurfaceMap *>::iterator map_node; for(map_node = mSrcSurfaceMapList.begin(); map_node != mSrcSurfaceMapList.end(); map_node++) { contextSurfaces[++index] = (*map_node)->getVASurface(); (*map_node)->setTracked(); } if(mAutoReference == false){ contextSurfaces[++index] = mRefSurface; contextSurfaces[++index] = mRecSurface; } else { for (uint32_t i=0; i < mAutoReferenceSurfaceNum; i++) contextSurfaces[++index] = mAutoRefSurfaces[i]; } //Initialize and save the VA context ID LOG_V( "vaCreateContext\n"); vaStatus = vaCreateContext(mVADisplay, mVAConfig, #ifdef IMG_GFX mComParams.resolution.width, mComParams.resolution.height, #else stride_aligned, height_aligned, #endif VA_PROGRESSIVE, contextSurfaces, contextSurfaceCnt, &(mVAContext)); CHECK_VA_STATUS_RETURN("vaCreateContext"); delete [] contextSurfaces; LOG_I("Success to create libva context width %d, height %d\n", mComParams.resolution.width, mComParams.resolution.height); uint32_t maxSize = 0; ret = getMaxOutSize(&maxSize); CHECK_ENCODE_STATUS_RETURN("getMaxOutSize"); // Create CodedBuffer for output VABufferID VACodedBuffer; for(uint32_t i = 0; i <mComParams.codedBufNum; i++) { vaStatus = vaCreateBuffer(mVADisplay, mVAContext, VAEncCodedBufferType, mCodedBufSize, 1, NULL, &VACodedBuffer); CHECK_VA_STATUS_RETURN("vaCreateBuffer::VAEncCodedBufferType"); mVACodedBufferList.push_back(VACodedBuffer); } if (ret == ENCODE_SUCCESS) mStarted = true; LOG_V( "end\n"); return ret; } Encode_Status VideoEncoderBase::encode(VideoEncRawBuffer *inBuffer, uint32_t timeout) { Encode_Status ret = ENCODE_SUCCESS; VAStatus vaStatus = VA_STATUS_SUCCESS; if (!mStarted) { LOG_E("Encoder has not initialized yet\n"); return ENCODE_NOT_INIT; } CHECK_NULL_RETURN_IFFAIL(inBuffer); //======Prepare all resources encoder needed=====. //Prepare encode vaSurface VASurfaceID sid = VA_INVALID_SURFACE; ret = manageSrcSurface(inBuffer, &sid); CHECK_ENCODE_STATUS_RETURN("manageSrcSurface"); //Prepare CodedBuffer mCodedBuffer_Lock.lock(); if(mVACodedBufferList.empty()){ if(timeout == FUNC_BLOCK) mCodedBuffer_Cond.wait(mCodedBuffer_Lock); else if (timeout > 0) { if(NO_ERROR != mEncodeTask_Cond.waitRelative(mCodedBuffer_Lock, 1000000*timeout)){ mCodedBuffer_Lock.unlock(); LOG_E("Time out wait for Coded buffer.\n"); return ENCODE_DEVICE_BUSY; } } else {//Nonblock mCodedBuffer_Lock.unlock(); LOG_E("Coded buffer is not ready now.\n"); return ENCODE_DEVICE_BUSY; } } if(mVACodedBufferList.empty()){ mCodedBuffer_Lock.unlock(); return ENCODE_DEVICE_BUSY; } VABufferID coded_buf = (VABufferID) *(mVACodedBufferList.begin()); mVACodedBufferList.erase(mVACodedBufferList.begin()); mCodedBuffer_Lock.unlock(); LOG_V("CodedBuffer ID 0x%08x\n", coded_buf); //All resources are ready, start to assemble EncodeTask EncodeTask* task = new EncodeTask(); task->completed = false; task->enc_surface = sid; task->coded_buffer = coded_buf; task->timestamp = inBuffer->timeStamp; task->priv = inBuffer->priv; //Setup frame info, like flag ( SYNCFRAME), frame number, type etc task->type = inBuffer->type; task->flag = inBuffer->flag; PrepareFrameInfo(task); if(mAutoReference == false){ //Setup ref /rec frames //TODO: B frame support, temporary use same logic switch (inBuffer->type) { case FTYPE_UNKNOWN: case FTYPE_IDR: case FTYPE_I: case FTYPE_P: { if(!mFrameSkipped) { VASurfaceID tmpSurface = mRecSurface; mRecSurface = mRefSurface; mRefSurface = tmpSurface; } task->ref_surface = mRefSurface; task->rec_surface = mRecSurface; break; } case FTYPE_B: default: LOG_V("Something wrong, B frame may not be supported in this mode\n"); ret = ENCODE_NOT_SUPPORTED; goto CLEAN_UP; } }else { task->ref_surface = VA_INVALID_SURFACE; task->rec_surface = VA_INVALID_SURFACE; } //======Start Encoding, add task to list====== LOG_V("Start Encoding vaSurface=0x%08x\n", task->enc_surface); vaStatus = vaBeginPicture(mVADisplay, mVAContext, task->enc_surface); CHECK_VA_STATUS_GOTO_CLEANUP("vaBeginPicture"); ret = sendEncodeCommand(task); CHECK_ENCODE_STATUS_CLEANUP("sendEncodeCommand"); vaStatus = vaEndPicture(mVADisplay, mVAContext); CHECK_VA_STATUS_GOTO_CLEANUP("vaEndPicture"); LOG_V("Add Task %p into Encode Task list\n", task); mEncodeTask_Lock.lock(); mEncodeTaskList.push_back(task); mEncodeTask_Cond.signal(); mEncodeTask_Lock.unlock(); mFrameNum ++; LOG_V("encode return Success\n"); return ENCODE_SUCCESS; CLEAN_UP: delete task; mCodedBuffer_Lock.lock(); mVACodedBufferList.push_back(coded_buf); //push to CodedBuffer pool again since it is not used mCodedBuffer_Cond.signal(); mCodedBuffer_Lock.unlock(); LOG_V("encode return error=%x\n", ret); return ret; } /* 1. Firstly check if one task is outputting data, if yes, continue outputting, if not try to get one from list. 2. Due to block/non-block/block with timeout 3 modes, if task is not completed, then sync surface, if yes, start output data 3. Use variable curoutputtask to record task which is getOutput() working on to avoid push again when get failure on non-block/block with timeout modes. 4. if complete all output data, curoutputtask should be set NULL */ Encode_Status VideoEncoderBase::getOutput(VideoEncOutputBuffer *outBuffer, uint32_t timeout) { Encode_Status ret = ENCODE_SUCCESS; VAStatus vaStatus = VA_STATUS_SUCCESS; bool useLocalBuffer = false; CHECK_NULL_RETURN_IFFAIL(outBuffer); if (mCurOutputTask == NULL) { mEncodeTask_Lock.lock(); if(mEncodeTaskList.empty()) { LOG_V("getOutput CurrentTask is NULL\n"); if(timeout == FUNC_BLOCK) { LOG_V("waiting for task....\n"); mEncodeTask_Cond.wait(mEncodeTask_Lock); } else if (timeout > 0) { LOG_V("waiting for task in %i ms....\n", timeout); if(NO_ERROR != mEncodeTask_Cond.waitRelative(mEncodeTask_Lock, 1000000*timeout)) { mEncodeTask_Lock.unlock(); LOG_E("Time out wait for encode task.\n"); return ENCODE_NO_REQUEST_DATA; } } else {//Nonblock mEncodeTask_Lock.unlock(); return ENCODE_NO_REQUEST_DATA; } } if(mEncodeTaskList.empty()){ mEncodeTask_Lock.unlock(); return ENCODE_DATA_NOT_READY; } mCurOutputTask = *(mEncodeTaskList.begin()); mEncodeTaskList.erase(mEncodeTaskList.begin()); mEncodeTask_Lock.unlock(); } //sync/query/wait task if not completed if (mCurOutputTask->completed == false) { VASurfaceStatus vaSurfaceStatus; if (timeout == FUNC_BLOCK) { //block mode, direct sync surface to output data mOutCodedBuffer = mCurOutputTask->coded_buffer; // Check frame skip // Need encoding to be completed before calling query surface below to // get the right skip frame flag for current frame // It is a requirement of video driver // vaSyncSurface syncs the wrong frame when rendering the same surface multiple times, // so use vaMapbuffer instead LOG_V ("block mode, vaMapBuffer ID = 0x%08x\n", mOutCodedBuffer); if (mOutCodedBufferPtr == NULL) { vaStatus = vaMapBuffer (mVADisplay, mOutCodedBuffer, (void **)&mOutCodedBufferPtr); CHECK_VA_STATUS_GOTO_CLEANUP("vaMapBuffer"); CHECK_NULL_RETURN_IFFAIL(mOutCodedBufferPtr); } vaStatus = vaQuerySurfaceStatus(mVADisplay, mCurOutputTask->enc_surface, &vaSurfaceStatus); CHECK_VA_STATUS_RETURN("vaQuerySurfaceStatus"); mFrameSkipped = vaSurfaceStatus & VASurfaceSkipped; mCurOutputTask->completed = true; } else { //For both block with timeout and non-block mode, query surface, if ready, output data LOG_V ("non-block mode, vaQuerySurfaceStatus ID = 0x%08x\n", mCurOutputTask->enc_surface); vaStatus = vaQuerySurfaceStatus(mVADisplay, mCurOutputTask->enc_surface, &vaSurfaceStatus); if (vaSurfaceStatus & VASurfaceReady) { mOutCodedBuffer = mCurOutputTask->coded_buffer; mFrameSkipped = vaSurfaceStatus & VASurfaceSkipped; mCurOutputTask->completed = true; //if need to call SyncSurface again ? } else {//not encode complet yet, but keep all context and return directly return ENCODE_DATA_NOT_READY; } } } //start to output data ret = prepareForOutput(outBuffer, &useLocalBuffer); CHECK_ENCODE_STATUS_CLEANUP("prepareForOutput"); //copy all flags to outBuffer outBuffer->offset = 0; outBuffer->flag = mCurOutputTask->flag; outBuffer->type = mCurOutputTask->type; outBuffer->timeStamp = mCurOutputTask->timestamp; outBuffer->priv = mCurOutputTask->priv; if (outBuffer->format == OUTPUT_EVERYTHING || outBuffer->format == OUTPUT_FRAME_DATA) { ret = outputAllData(outBuffer); CHECK_ENCODE_STATUS_CLEANUP("outputAllData"); }else { ret = getExtFormatOutput(outBuffer); CHECK_ENCODE_STATUS_CLEANUP("getExtFormatOutput"); } LOG_V("out size for this getOutput call = %d\n", outBuffer->dataSize); ret = cleanupForOutput(); CHECK_ENCODE_STATUS_CLEANUP("cleanupForOutput"); LOG_V("getOutput return Success, Frame skip is %d\n", mFrameSkipped); return ENCODE_SUCCESS; CLEAN_UP: if (outBuffer->data && (useLocalBuffer == true)) { delete[] outBuffer->data; outBuffer->data = NULL; useLocalBuffer = false; } if (mOutCodedBufferPtr != NULL) { vaStatus = vaUnmapBuffer(mVADisplay, mOutCodedBuffer); mOutCodedBufferPtr = NULL; mCurSegment = NULL; } delete mCurOutputTask; mCurOutputTask = NULL; mCodedBuffer_Lock.lock(); mVACodedBufferList.push_back(mOutCodedBuffer); mCodedBuffer_Cond.signal(); mCodedBuffer_Lock.unlock(); LOG_V("getOutput return error=%x\n", ret); return ret; } void VideoEncoderBase::flush() { LOG_V( "Begin\n"); // reset the properities mFrameNum = 0; LOG_V( "end\n"); } Encode_Status VideoEncoderBase::stop() { VAStatus vaStatus = VA_STATUS_SUCCESS; Encode_Status ret = ENCODE_SUCCESS; LOG_V( "Begin\n"); // It is possible that above pointers have been allocated // before we set mStarted to true if (!mStarted) { LOG_V("Encoder has been stopped\n"); return ENCODE_SUCCESS; } if (mAutoRefSurfaces) { delete[] mAutoRefSurfaces; mAutoRefSurfaces = NULL; } mCodedBuffer_Lock.lock(); mVACodedBufferList.clear(); mCodedBuffer_Lock.unlock(); mCodedBuffer_Cond.broadcast(); //Delete all uncompleted tasks mEncodeTask_Lock.lock(); while(! mEncodeTaskList.empty()) { delete *mEncodeTaskList.begin(); mEncodeTaskList.erase(mEncodeTaskList.begin()); } mEncodeTask_Lock.unlock(); mEncodeTask_Cond.broadcast(); //Release Src Surface Buffer Map, destroy surface manually since it is not added into context LOG_V( "Rlease Src Surface Map\n"); while(! mSrcSurfaceMapList.empty()) { delete (*mSrcSurfaceMapList.begin()); mSrcSurfaceMapList.erase(mSrcSurfaceMapList.begin()); } LOG_V( "vaDestroyContext\n"); if (mVAContext != VA_INVALID_ID) { vaStatus = vaDestroyContext(mVADisplay, mVAContext); CHECK_VA_STATUS_GOTO_CLEANUP("vaDestroyContext"); } LOG_V( "vaDestroyConfig\n"); if (mVAConfig != VA_INVALID_ID) { vaStatus = vaDestroyConfig(mVADisplay, mVAConfig); CHECK_VA_STATUS_GOTO_CLEANUP("vaDestroyConfig"); } CLEAN_UP: mStarted = false; mSliceSizeOverflow = false; mCurOutputTask= NULL; mOutCodedBuffer = 0; mCurSegment = NULL; mOffsetInSeg =0; mTotalSize = 0; mTotalSizeCopied = 0; mFrameSkipped = false; mSupportedSurfaceMemType = 0; LOG_V( "end\n"); return ret; } Encode_Status VideoEncoderBase::prepareForOutput( VideoEncOutputBuffer *outBuffer, bool *useLocalBuffer) { VAStatus vaStatus = VA_STATUS_SUCCESS; VACodedBufferSegment *vaCodedSeg = NULL; uint32_t status = 0; LOG_V( "begin\n"); // Won't check parameters here as the caller already checked them // mCurSegment is NULL means it is first time to be here after finishing encoding a frame if (mCurSegment == NULL) { if (mOutCodedBufferPtr == NULL) { vaStatus = vaMapBuffer (mVADisplay, mOutCodedBuffer, (void **)&mOutCodedBufferPtr); CHECK_VA_STATUS_RETURN("vaMapBuffer"); CHECK_NULL_RETURN_IFFAIL(mOutCodedBufferPtr); } LOG_V("Coded Buffer ID been mapped = 0x%08x\n", mOutCodedBuffer); mTotalSize = 0; mOffsetInSeg = 0; mTotalSizeCopied = 0; vaCodedSeg = (VACodedBufferSegment *)mOutCodedBufferPtr; mCurSegment = (VACodedBufferSegment *)mOutCodedBufferPtr; while (1) { mTotalSize += vaCodedSeg->size; status = vaCodedSeg->status; #ifndef IMG_GFX uint8_t *pTemp; uint32_t ii; pTemp = (uint8_t*)vaCodedSeg->buf; for(ii = 0; ii < 16;){ if (*(pTemp + ii) == 0xFF) ii++; else break; } if (ii > 0) { mOffsetInSeg = ii; } #endif if (!mSliceSizeOverflow) { mSliceSizeOverflow = status & VA_CODED_BUF_STATUS_SLICE_OVERFLOW_MASK; } if (vaCodedSeg->next == NULL) break; vaCodedSeg = (VACodedBufferSegment *)vaCodedSeg->next; } } // We will support two buffer allocation mode, // one is application allocates the buffer and passes to encode, // the other is encode allocate memory //means app doesn't allocate the buffer, so _encode will allocate it. if (outBuffer->data == NULL) { *useLocalBuffer = true; outBuffer->data = new uint8_t[mTotalSize - mTotalSizeCopied + 100]; if (outBuffer->data == NULL) { LOG_E( "outBuffer->data == NULL\n"); return ENCODE_NO_MEMORY; } outBuffer->bufferSize = mTotalSize + 100; outBuffer->dataSize = 0; } // Clear all flag for every call outBuffer->flag = 0; if (mSliceSizeOverflow) outBuffer->flag |= ENCODE_BUFFERFLAG_SLICEOVERFOLOW; if (!mCurSegment) return ENCODE_FAIL; if (mCurSegment->size < mOffsetInSeg) { LOG_E("mCurSegment->size < mOffsetInSeg\n"); return ENCODE_FAIL; } // Make sure we have data in current segment if (mCurSegment->size == mOffsetInSeg) { if (mCurSegment->next != NULL) { mCurSegment = (VACodedBufferSegment *)mCurSegment->next; mOffsetInSeg = 0; } else { LOG_V("No more data available\n"); outBuffer->flag |= ENCODE_BUFFERFLAG_DATAINVALID; outBuffer->dataSize = 0; mCurSegment = NULL; return ENCODE_NO_REQUEST_DATA; } } LOG_V( "end\n"); return ENCODE_SUCCESS; } Encode_Status VideoEncoderBase::cleanupForOutput() { VAStatus vaStatus = VA_STATUS_SUCCESS; //mCurSegment is NULL means all data has been copied out if (mCurSegment == NULL && mOutCodedBufferPtr) { vaStatus = vaUnmapBuffer(mVADisplay, mOutCodedBuffer); CHECK_VA_STATUS_RETURN("vaUnmapBuffer"); mOutCodedBufferPtr = NULL; mTotalSize = 0; mOffsetInSeg = 0; mTotalSizeCopied = 0; delete mCurOutputTask; mCurOutputTask = NULL; mCodedBuffer_Lock.lock(); mVACodedBufferList.push_back(mOutCodedBuffer); mCodedBuffer_Cond.signal(); mCodedBuffer_Lock.unlock(); LOG_V("All data has been outputted, return CodedBuffer 0x%08x to pool\n", mOutCodedBuffer); } return ENCODE_SUCCESS; } Encode_Status VideoEncoderBase::queryProfileLevelConfig(VADisplay dpy, VAProfile profile) { VAStatus vaStatus = VA_STATUS_SUCCESS; VAEntrypoint entryPtr[8]; int i, entryPtrNum; if(profile == VAProfileH264Main) //need to be fixed return ENCODE_NOT_SUPPORTED; vaStatus = vaQueryConfigEntrypoints(dpy, profile, entryPtr, &entryPtrNum); CHECK_VA_STATUS_RETURN("vaQueryConfigEntrypoints"); for(i=0; i<entryPtrNum; i++){ if(entryPtr[i] == VAEntrypointEncSlice) return ENCODE_SUCCESS; } return ENCODE_NOT_SUPPORTED; } Encode_Status VideoEncoderBase::queryAutoReferenceConfig(VAProfile profile) { VAStatus vaStatus = VA_STATUS_SUCCESS; VAConfigAttrib attrib_list; attrib_list.type = VAConfigAttribEncAutoReference; attrib_list.value = VA_ATTRIB_NOT_SUPPORTED; vaStatus = vaGetConfigAttributes(mVADisplay, profile, VAEntrypointEncSlice, &attrib_list, 1); if(attrib_list.value == VA_ATTRIB_NOT_SUPPORTED ) mAutoReference = false; else mAutoReference = true; return ENCODE_SUCCESS; } Encode_Status VideoEncoderBase::querySupportedSurfaceMemTypes() { VAStatus vaStatus = VA_STATUS_SUCCESS; unsigned int num = 0; VASurfaceAttrib* attribs = NULL; //get attribs number vaStatus = vaQuerySurfaceAttributes(mVADisplay, mVAConfig, attribs, &num); CHECK_VA_STATUS_RETURN("vaGetSurfaceAttributes"); if (num == 0) return ENCODE_SUCCESS; attribs = new VASurfaceAttrib[num]; vaStatus = vaQuerySurfaceAttributes(mVADisplay, mVAConfig, attribs, &num); CHECK_VA_STATUS_RETURN("vaGetSurfaceAttributes"); for(uint32_t i = 0; i < num; i ++) { if (attribs[i].type == VASurfaceAttribMemoryType) { mSupportedSurfaceMemType = attribs[i].value.value.i; break; } else continue; } delete attribs; return ENCODE_SUCCESS; } Encode_Status VideoEncoderBase::outputAllData(VideoEncOutputBuffer *outBuffer) { // Data size been copied for every single call uint32_t sizeCopiedHere = 0; uint32_t sizeToBeCopied = 0; CHECK_NULL_RETURN_IFFAIL(outBuffer->data); while (1) { LOG_V("mCurSegment->size = %d, mOffsetInSeg = %d\n", mCurSegment->size, mOffsetInSeg); LOG_V("outBuffer->bufferSize = %d, sizeCopiedHere = %d, mTotalSizeCopied = %d\n", outBuffer->bufferSize, sizeCopiedHere, mTotalSizeCopied); if (mCurSegment->size < mOffsetInSeg || outBuffer->bufferSize < sizeCopiedHere) { LOG_E("mCurSegment->size < mOffsetInSeg || outBuffer->bufferSize < sizeCopiedHere\n"); return ENCODE_FAIL; } if ((mCurSegment->size - mOffsetInSeg) <= outBuffer->bufferSize - sizeCopiedHere) { sizeToBeCopied = mCurSegment->size - mOffsetInSeg; memcpy(outBuffer->data + sizeCopiedHere, (uint8_t *)mCurSegment->buf + mOffsetInSeg, sizeToBeCopied); sizeCopiedHere += sizeToBeCopied; mTotalSizeCopied += sizeToBeCopied; mOffsetInSeg = 0; } else { sizeToBeCopied = outBuffer->bufferSize - sizeCopiedHere; memcpy(outBuffer->data + sizeCopiedHere, (uint8_t *)mCurSegment->buf + mOffsetInSeg, outBuffer->bufferSize - sizeCopiedHere); mTotalSizeCopied += sizeToBeCopied; mOffsetInSeg += sizeToBeCopied; outBuffer->dataSize = outBuffer->bufferSize; outBuffer->remainingSize = mTotalSize - mTotalSizeCopied; outBuffer->flag |= ENCODE_BUFFERFLAG_PARTIALFRAME; return ENCODE_BUFFER_TOO_SMALL; } if (mCurSegment->next == NULL) { outBuffer->dataSize = sizeCopiedHere; outBuffer->remainingSize = 0; outBuffer->flag |= ENCODE_BUFFERFLAG_ENDOFFRAME; mCurSegment = NULL; return ENCODE_SUCCESS; } mCurSegment = (VACodedBufferSegment *)mCurSegment->next; mOffsetInSeg = 0; } } void VideoEncoderBase::setDefaultParams() { // Set default value for input parameters mComParams.profile = VAProfileH264Baseline; mComParams.level = 41; mComParams.rawFormat = RAW_FORMAT_NV12; mComParams.frameRate.frameRateNum = 30; mComParams.frameRate.frameRateDenom = 1; mComParams.resolution.width = 0; mComParams.resolution.height = 0; mComParams.intraPeriod = 30; mComParams.rcMode = RATE_CONTROL_NONE; mComParams.rcParams.initQP = 15; mComParams.rcParams.minQP = 0; mComParams.rcParams.maxQP = 0; mComParams.rcParams.I_minQP = 0; mComParams.rcParams.I_maxQP = 0; mComParams.rcParams.bitRate = 640000; mComParams.rcParams.targetPercentage= 0; mComParams.rcParams.windowSize = 0; mComParams.rcParams.disableFrameSkip = 0; mComParams.rcParams.disableBitsStuffing = 1; mComParams.rcParams.enableIntraFrameQPControl = 0; mComParams.rcParams.temporalFrameRate = 0; mComParams.rcParams.temporalID = 0; mComParams.cyclicFrameInterval = 30; mComParams.refreshType = VIDEO_ENC_NONIR; mComParams.airParams.airMBs = 0; mComParams.airParams.airThreshold = 0; mComParams.airParams.airAuto = 1; mComParams.disableDeblocking = 2; mComParams.syncEncMode = false; mComParams.codedBufNum = 2; mComParams.numberOfLayer = 1; mComParams.nPeriodicity = 0; memset(mComParams.nLayerID,0,32*sizeof(uint32_t)); mHrdParam.bufferSize = 0; mHrdParam.initBufferFullness = 0; mStoreMetaDataInBuffers.isEnabled = false; } Encode_Status VideoEncoderBase::setParameters( VideoParamConfigSet *videoEncParams) { Encode_Status ret = ENCODE_SUCCESS; CHECK_NULL_RETURN_IFFAIL(videoEncParams); LOG_V("Config type = %x\n", (int)videoEncParams->type); if (mStarted) { LOG_E("Encoder has been initialized, should use setConfig to change configurations\n"); return ENCODE_ALREADY_INIT; } switch (videoEncParams->type) { case VideoParamsTypeCommon: { VideoParamsCommon *paramsCommon = reinterpret_cast <VideoParamsCommon *> (videoEncParams); if (paramsCommon->size != sizeof (VideoParamsCommon)) { return ENCODE_INVALID_PARAMS; } if(paramsCommon->codedBufNum < 2) paramsCommon->codedBufNum =2; mComParams = *paramsCommon; break; } case VideoParamsTypeUpSteamBuffer: { VideoParamsUpstreamBuffer *upStreamBuffer = reinterpret_cast <VideoParamsUpstreamBuffer *> (videoEncParams); if (upStreamBuffer->size != sizeof (VideoParamsUpstreamBuffer)) { return ENCODE_INVALID_PARAMS; } ret = setUpstreamBuffer(upStreamBuffer); break; } case VideoParamsTypeUsrptrBuffer: { // usrptr only can be get // this case should not happen break; } case VideoParamsTypeHRD: { VideoParamsHRD *hrd = reinterpret_cast <VideoParamsHRD *> (videoEncParams); if (hrd->size != sizeof (VideoParamsHRD)) { return ENCODE_INVALID_PARAMS; } mHrdParam.bufferSize = hrd->bufferSize; mHrdParam.initBufferFullness = hrd->initBufferFullness; mRenderHrd = true; break; } case VideoParamsTypeStoreMetaDataInBuffers: { VideoParamsStoreMetaDataInBuffers *metadata = reinterpret_cast <VideoParamsStoreMetaDataInBuffers *> (videoEncParams); if (metadata->size != sizeof (VideoParamsStoreMetaDataInBuffers)) { return ENCODE_INVALID_PARAMS; } mStoreMetaDataInBuffers.isEnabled = metadata->isEnabled; break; } case VideoParamsTypeTemporalLayer:{ VideoParamsTemporalLayer *temporallayer = reinterpret_cast <VideoParamsTemporalLayer *> (videoEncParams); if (temporallayer->size != sizeof(VideoParamsTemporalLayer)) { return ENCODE_INVALID_PARAMS; } mComParams.numberOfLayer = temporallayer->numberOfLayer; mComParams.nPeriodicity = temporallayer->nPeriodicity; for(uint32_t i=0;i<temporallayer->nPeriodicity;i++) mComParams.nLayerID[i] = temporallayer->nLayerID[i]; mRenderMultiTemporal = true; break; } case VideoParamsTypeAVC: case VideoParamsTypeH263: case VideoParamsTypeMP4: case VideoParamsTypeVC1: case VideoParamsTypeVP8: { ret = derivedSetParams(videoEncParams); break; } default: { LOG_E ("Wrong ParamType here\n"); return ENCODE_INVALID_PARAMS; } } return ret; } Encode_Status VideoEncoderBase::getParameters( VideoParamConfigSet *videoEncParams) { Encode_Status ret = ENCODE_SUCCESS; CHECK_NULL_RETURN_IFFAIL(videoEncParams); LOG_V("Config type = %d\n", (int)videoEncParams->type); switch (videoEncParams->type) { case VideoParamsTypeCommon: { VideoParamsCommon *paramsCommon = reinterpret_cast <VideoParamsCommon *> (videoEncParams); if (paramsCommon->size != sizeof (VideoParamsCommon)) { return ENCODE_INVALID_PARAMS; } *paramsCommon = mComParams; break; } case VideoParamsTypeUpSteamBuffer: { // Get upstream buffer could happen // but not meaningful a lot break; } case VideoParamsTypeUsrptrBuffer: { VideoParamsUsrptrBuffer *usrptrBuffer = reinterpret_cast <VideoParamsUsrptrBuffer *> (videoEncParams); if (usrptrBuffer->size != sizeof (VideoParamsUsrptrBuffer)) { return ENCODE_INVALID_PARAMS; } ret = getNewUsrptrFromSurface( usrptrBuffer->width, usrptrBuffer->height, usrptrBuffer->format, usrptrBuffer->expectedSize, &(usrptrBuffer->actualSize), &(usrptrBuffer->stride), &(usrptrBuffer->usrPtr)); break; } case VideoParamsTypeHRD: { VideoParamsHRD *hrd = reinterpret_cast <VideoParamsHRD *> (videoEncParams); if (hrd->size != sizeof (VideoParamsHRD)) { return ENCODE_INVALID_PARAMS; } hrd->bufferSize = mHrdParam.bufferSize; hrd->initBufferFullness = mHrdParam.initBufferFullness; break; } case VideoParamsTypeStoreMetaDataInBuffers: { VideoParamsStoreMetaDataInBuffers *metadata = reinterpret_cast <VideoParamsStoreMetaDataInBuffers *> (videoEncParams); if (metadata->size != sizeof (VideoParamsStoreMetaDataInBuffers)) { return ENCODE_INVALID_PARAMS; } metadata->isEnabled = mStoreMetaDataInBuffers.isEnabled; break; } case VideoParamsTypeProfileLevel: { VideoParamsProfileLevel *profilelevel = reinterpret_cast <VideoParamsProfileLevel *> (videoEncParams); if (profilelevel->size != sizeof (VideoParamsProfileLevel)) { return ENCODE_INVALID_PARAMS; } profilelevel->level = 0; if(queryProfileLevelConfig(mVADisplay, profilelevel->profile) == ENCODE_SUCCESS){ profilelevel->isSupported = true; if(profilelevel->profile == VAProfileH264High) profilelevel->level = 42; else if(profilelevel->profile == VAProfileH264Main) profilelevel->level = 42; else if(profilelevel->profile == VAProfileH264Baseline) profilelevel->level = 41; else{ profilelevel->level = 0; profilelevel->isSupported = false; } } } case VideoParamsTypeTemporalLayer:{ VideoParamsTemporalLayer *temporallayer = reinterpret_cast <VideoParamsTemporalLayer *> (videoEncParams); if(temporallayer->size != sizeof(VideoParamsTemporalLayer)) { return ENCODE_INVALID_PARAMS; } temporallayer->numberOfLayer = mComParams.numberOfLayer; break; } case VideoParamsTypeAVC: case VideoParamsTypeH263: case VideoParamsTypeMP4: case VideoParamsTypeVC1: case VideoParamsTypeVP8: { derivedGetParams(videoEncParams); break; } default: { LOG_E ("Wrong ParamType here\n"); break; } } return ENCODE_SUCCESS; } Encode_Status VideoEncoderBase::setConfig(VideoParamConfigSet *videoEncConfig) { Encode_Status ret = ENCODE_SUCCESS; CHECK_NULL_RETURN_IFFAIL(videoEncConfig); LOG_V("Config type = %d\n", (int)videoEncConfig->type); // workaround #if 0 if (!mStarted) { LOG_E("Encoder has not initialized yet, can't call setConfig\n"); return ENCODE_NOT_INIT; } #endif switch (videoEncConfig->type) { case VideoConfigTypeFrameRate: { VideoConfigFrameRate *configFrameRate = reinterpret_cast <VideoConfigFrameRate *> (videoEncConfig); if (configFrameRate->size != sizeof (VideoConfigFrameRate)) { return ENCODE_INVALID_PARAMS; } mComParams.frameRate = configFrameRate->frameRate; mRenderFrameRate = true; break; } case VideoConfigTypeBitRate: { VideoConfigBitRate *configBitRate = reinterpret_cast <VideoConfigBitRate *> (videoEncConfig); if (configBitRate->size != sizeof (VideoConfigBitRate)) { return ENCODE_INVALID_PARAMS; } if(mComParams.numberOfLayer == 1) { mComParams.rcParams = configBitRate->rcParams; mRenderBitRate = true; } else { mTemporalLayerBitrateFramerate[configBitRate->rcParams.temporalID].nLayerID = configBitRate->rcParams.temporalID; mTemporalLayerBitrateFramerate[configBitRate->rcParams.temporalID].bitRate = configBitRate->rcParams.bitRate; mTemporalLayerBitrateFramerate[configBitRate->rcParams.temporalID].frameRate = configBitRate->rcParams.temporalFrameRate; } break; } case VideoConfigTypeResolution: { // Not Implemented break; } case VideoConfigTypeIntraRefreshType: { VideoConfigIntraRefreshType *configIntraRefreshType = reinterpret_cast <VideoConfigIntraRefreshType *> (videoEncConfig); if (configIntraRefreshType->size != sizeof (VideoConfigIntraRefreshType)) { return ENCODE_INVALID_PARAMS; } mComParams.refreshType = configIntraRefreshType->refreshType; break; } case VideoConfigTypeCyclicFrameInterval: { VideoConfigCyclicFrameInterval *configCyclicFrameInterval = reinterpret_cast <VideoConfigCyclicFrameInterval *> (videoEncConfig); if (configCyclicFrameInterval->size != sizeof (VideoConfigCyclicFrameInterval)) { return ENCODE_INVALID_PARAMS; } mComParams.cyclicFrameInterval = configCyclicFrameInterval->cyclicFrameInterval; break; } case VideoConfigTypeAIR: { VideoConfigAIR *configAIR = reinterpret_cast <VideoConfigAIR *> (videoEncConfig); if (configAIR->size != sizeof (VideoConfigAIR)) { return ENCODE_INVALID_PARAMS; } mComParams.airParams = configAIR->airParams; mRenderAIR = true; break; } case VideoConfigTypeCIR: { VideoConfigCIR *configCIR = reinterpret_cast <VideoConfigCIR *> (videoEncConfig); if (configCIR->size != sizeof (VideoConfigCIR)) { return ENCODE_INVALID_PARAMS; } mComParams.cirParams = configCIR->cirParams; mRenderCIR = true; break; } case VideoConfigTypeAVCIntraPeriod: case VideoConfigTypeNALSize: case VideoConfigTypeIDRRequest: case VideoConfigTypeSliceNum: case VideoConfigTypeVP8: case VideoConfigTypeVP8ReferenceFrame: case VideoConfigTypeVP8MaxFrameSizeRatio:{ ret = derivedSetConfig(videoEncConfig); break; } default: { LOG_E ("Wrong Config Type here\n"); break; } } return ret; } Encode_Status VideoEncoderBase::getConfig(VideoParamConfigSet *videoEncConfig) { Encode_Status ret = ENCODE_SUCCESS; CHECK_NULL_RETURN_IFFAIL(videoEncConfig); LOG_V("Config type = %d\n", (int)videoEncConfig->type); switch (videoEncConfig->type) { case VideoConfigTypeFrameRate: { VideoConfigFrameRate *configFrameRate = reinterpret_cast <VideoConfigFrameRate *> (videoEncConfig); if (configFrameRate->size != sizeof (VideoConfigFrameRate)) { return ENCODE_INVALID_PARAMS; } configFrameRate->frameRate = mComParams.frameRate; break; } case VideoConfigTypeBitRate: { VideoConfigBitRate *configBitRate = reinterpret_cast <VideoConfigBitRate *> (videoEncConfig); if (configBitRate->size != sizeof (VideoConfigBitRate)) { return ENCODE_INVALID_PARAMS; } configBitRate->rcParams = mComParams.rcParams; break; } case VideoConfigTypeResolution: { // Not Implemented break; } case VideoConfigTypeIntraRefreshType: { VideoConfigIntraRefreshType *configIntraRefreshType = reinterpret_cast <VideoConfigIntraRefreshType *> (videoEncConfig); if (configIntraRefreshType->size != sizeof (VideoConfigIntraRefreshType)) { return ENCODE_INVALID_PARAMS; } configIntraRefreshType->refreshType = mComParams.refreshType; break; } case VideoConfigTypeCyclicFrameInterval: { VideoConfigCyclicFrameInterval *configCyclicFrameInterval = reinterpret_cast <VideoConfigCyclicFrameInterval *> (videoEncConfig); if (configCyclicFrameInterval->size != sizeof (VideoConfigCyclicFrameInterval)) { return ENCODE_INVALID_PARAMS; } configCyclicFrameInterval->cyclicFrameInterval = mComParams.cyclicFrameInterval; break; } case VideoConfigTypeAIR: { VideoConfigAIR *configAIR = reinterpret_cast <VideoConfigAIR *> (videoEncConfig); if (configAIR->size != sizeof (VideoConfigAIR)) { return ENCODE_INVALID_PARAMS; } configAIR->airParams = mComParams.airParams; break; } case VideoConfigTypeCIR: { VideoConfigCIR *configCIR = reinterpret_cast <VideoConfigCIR *> (videoEncConfig); if (configCIR->size != sizeof (VideoConfigCIR)) { return ENCODE_INVALID_PARAMS; } configCIR->cirParams = mComParams.cirParams; break; } case VideoConfigTypeAVCIntraPeriod: case VideoConfigTypeNALSize: case VideoConfigTypeIDRRequest: case VideoConfigTypeSliceNum: case VideoConfigTypeVP8: { ret = derivedGetConfig(videoEncConfig); break; } default: { LOG_E ("Wrong ParamType here\n"); break; } } return ret; } void VideoEncoderBase:: PrepareFrameInfo (EncodeTask* task) { if (mNewHeader) mFrameNum = 0; LOG_V( "mFrameNum = %d ", mFrameNum); updateFrameInfo(task) ; } Encode_Status VideoEncoderBase:: updateFrameInfo (EncodeTask* task) { task->type = FTYPE_P; // determine the picture type if (mFrameNum == 0) task->type = FTYPE_I; if (mComParams.intraPeriod != 0 && ((mFrameNum % mComParams.intraPeriod) == 0)) task->type = FTYPE_I; if (task->type == FTYPE_I) task->flag |= ENCODE_BUFFERFLAG_SYNCFRAME; return ENCODE_SUCCESS; } Encode_Status VideoEncoderBase::getMaxOutSize (uint32_t *maxSize) { uint32_t size = mComParams.resolution.width * mComParams.resolution.height; if (maxSize == NULL) { LOG_E("maxSize == NULL\n"); return ENCODE_NULL_PTR; } LOG_V( "Begin\n"); if (mCodedBufSize > 0) { *maxSize = mCodedBufSize; LOG_V ("Already calculate the max encoded size, get the value directly"); return ENCODE_SUCCESS; } // here, VP8 is different from AVC/H263 if(mComParams.profile == VAProfileVP8Version0_3) // for VP8 encode { // According to VIED suggestions, in CBR mode, coded buffer should be the size of 3 bytes per luma pixel // in CBR_HRD mode, coded buffer size should be 5 * rc_buf_sz * rc_target_bitrate; // now we just hardcode mCodedBufSize as 2M to walk round coded buffer size issue; /* if(mComParams.rcMode == VA_RC_CBR) // CBR_HRD mode mCodedBufSize = 5 * mComParams.rcParams.bitRate * 6000; else // CBR mode mCodedBufSize = 3 * mComParams.resolution.width * mComParams.resolution.height; */ mCodedBufSize = (2 * 1024 * 1024 + 31) & (~31); } else // for AVC/H263/MPEG4 encode { // base on the rate control mode to calculate the defaule encoded buffer size if (mComParams.rcMode == VA_RC_NONE) { mCodedBufSize = (size * 400) / (16 * 16); // set to value according to QP } else { mCodedBufSize = mComParams.rcParams.bitRate / 4; } mCodedBufSize = max (mCodedBufSize , (size * 400) / (16 * 16)); // in case got a very large user input bit rate value mCodedBufSize = min(mCodedBufSize, (size * 1.5 * 8)); mCodedBufSize = (mCodedBufSize + 15) &(~15); } *maxSize = mCodedBufSize; return ENCODE_SUCCESS; } Encode_Status VideoEncoderBase::getNewUsrptrFromSurface( uint32_t width, uint32_t height, uint32_t format, uint32_t expectedSize, uint32_t *outsize, uint32_t *stride, uint8_t **usrptr) { Encode_Status ret = ENCODE_FAIL; VAStatus vaStatus = VA_STATUS_SUCCESS; VASurfaceID surface = VA_INVALID_SURFACE; VAImage image; uint32_t index = 0; LOG_V( "Begin\n"); // If encode session has been configured, we can not request surface creation anymore if (mStarted) { LOG_E( "Already Initialized, can not request VA surface anymore\n"); return ENCODE_WRONG_STATE; } if (width<=0 || height<=0 ||outsize == NULL ||stride == NULL || usrptr == NULL) { LOG_E("width<=0 || height<=0 || outsize == NULL || stride == NULL ||usrptr == NULL\n"); return ENCODE_NULL_PTR; } // Current only NV12 is supported in VA API // Through format we can get known the number of planes if (format != STRING_TO_FOURCC("NV12")) { LOG_W ("Format is not supported\n"); return ENCODE_NOT_SUPPORTED; } surface = CreateNewVASurface(mVADisplay, width, height); if (surface == VA_INVALID_SURFACE) return ENCODE_DRIVER_FAIL; vaStatus = vaDeriveImage(mVADisplay, surface, &image); CHECK_VA_STATUS_RETURN("vaDeriveImage"); LOG_V( "vaDeriveImage Done\n"); vaStatus = vaMapBuffer(mVADisplay, image.buf, (void **) usrptr); CHECK_VA_STATUS_RETURN("vaMapBuffer"); // make sure the physical page been allocated for (index = 0; index < image.data_size; index = index + 4096) { unsigned char tmp = *(*usrptr + index); if (tmp == 0) *(*usrptr + index) = 0; } *outsize = image.data_size; *stride = image.pitches[0]; LOG_V( "surface = 0x%08x\n",(uint32_t)surface); LOG_V("image->pitches[0] = %d\n", image.pitches[0]); LOG_V("image->pitches[1] = %d\n", image.pitches[1]); LOG_V("image->offsets[0] = %d\n", image.offsets[0]); LOG_V("image->offsets[1] = %d\n", image.offsets[1]); LOG_V("image->num_planes = %d\n", image.num_planes); LOG_V("image->width = %d\n", image.width); LOG_V("image->height = %d\n", image.height); LOG_V("data_size = %d\n", image.data_size); LOG_V("usrptr = 0x%p\n", *usrptr); vaStatus = vaUnmapBuffer(mVADisplay, image.buf); CHECK_VA_STATUS_RETURN("vaUnmapBuffer"); vaStatus = vaDestroyImage(mVADisplay, image.image_id); CHECK_VA_STATUS_RETURN("vaDestroyImage"); if (*outsize < expectedSize) { LOG_E ("Allocated buffer size is small than the expected size, destroy the surface"); LOG_I ("Allocated size is %d, expected size is %d\n", *outsize, expectedSize); vaStatus = vaDestroySurfaces(mVADisplay, &surface, 1); CHECK_VA_STATUS_RETURN("vaDestroySurfaces"); return ENCODE_FAIL; } VASurfaceMap *map = new VASurfaceMap(mVADisplay, mSupportedSurfaceMemType); if (map == NULL) { LOG_E( "new VASurfaceMap failed\n"); return ENCODE_NO_MEMORY; } map->setVASurface(surface); //special case, vasuface is set, so nothing do in doMapping // map->setType(MetadataBufferTypeEncoder); map->setValue((intptr_t)*usrptr); ValueInfo vinfo; memset(&vinfo, 0, sizeof(ValueInfo)); vinfo.mode = (MemMode)MEM_MODE_USRPTR; vinfo.handle = 0; vinfo.size = 0; vinfo.width = width; vinfo.height = height; vinfo.lumaStride = width; vinfo.chromStride = width; vinfo.format = VA_FOURCC_NV12; vinfo.s3dformat = 0xffffffff; map->setValueInfo(vinfo); map->doMapping(); mSrcSurfaceMapList.push_back(map); ret = ENCODE_SUCCESS; return ret; } Encode_Status VideoEncoderBase::setUpstreamBuffer(VideoParamsUpstreamBuffer *upStreamBuffer) { Encode_Status status = ENCODE_SUCCESS; CHECK_NULL_RETURN_IFFAIL(upStreamBuffer); if (upStreamBuffer->bufCnt == 0) { LOG_E("bufCnt == 0\n"); return ENCODE_FAIL; } for(unsigned int i=0; i < upStreamBuffer->bufCnt; i++) { if (findSurfaceMapByValue(upStreamBuffer->bufList[i]) != NULL) //already mapped continue; //wrap upstream buffer into vaSurface VASurfaceMap *map = new VASurfaceMap(mVADisplay, mSupportedSurfaceMemType); // map->setType(MetadataBufferTypeUser); map->setValue(upStreamBuffer->bufList[i]); ValueInfo vinfo; memset(&vinfo, 0, sizeof(ValueInfo)); vinfo.mode = (MemMode)upStreamBuffer->bufferMode; vinfo.handle = (intptr_t)upStreamBuffer->display; vinfo.size = 0; if (upStreamBuffer->bufAttrib) { vinfo.width = upStreamBuffer->bufAttrib->realWidth; vinfo.height = upStreamBuffer->bufAttrib->realHeight; vinfo.lumaStride = upStreamBuffer->bufAttrib->lumaStride; vinfo.chromStride = upStreamBuffer->bufAttrib->chromStride; vinfo.format = upStreamBuffer->bufAttrib->format; } vinfo.s3dformat = 0xFFFFFFFF; map->setValueInfo(vinfo); status = map->doMapping(); if (status == ENCODE_SUCCESS) mSrcSurfaceMapList.push_back(map); else delete map; } return status; } Encode_Status VideoEncoderBase::manageSrcSurface(VideoEncRawBuffer *inBuffer, VASurfaceID *sid) { Encode_Status ret = ENCODE_SUCCESS; IntelMetadataBufferType type; intptr_t value; ValueInfo vinfo; ValueInfo *pvinfo = &vinfo; intptr_t *extravalues = NULL; unsigned int extravalues_count = 0; IntelMetadataBuffer imb; VASurfaceMap *map = NULL; memset(&vinfo, 0, sizeof(ValueInfo)); if (mStoreMetaDataInBuffers.isEnabled) { //metadatabuffer mode LOG_V("in metadata mode, data=%p, size=%d\n", inBuffer->data, inBuffer->size); if (imb.UnSerialize(inBuffer->data, inBuffer->size) != IMB_SUCCESS) { //fail to parse buffer return ENCODE_NO_REQUEST_DATA; } imb.GetType(type); imb.GetValue(value); } else { //raw mode LOG_I("in raw mode, data=%p, size=%d\n", inBuffer->data, inBuffer->size); if (! inBuffer->data || inBuffer->size == 0) { return ENCODE_NULL_PTR; } type = IntelMetadataBufferTypeUser; value = (intptr_t)inBuffer->data; } #ifdef INTEL_VIDEO_XPROC_SHARING uint32_t sflag = mSessionFlag; imb.GetSessionFlag(mSessionFlag); if (mSessionFlag != sflag) { //new sharing session, flush buffer sharing cache IntelMetadataBuffer::ClearContext(sflag, false); //flush surfacemap cache LOG_V( "Flush Src Surface Map\n"); while(! mSrcSurfaceMapList.empty()) { delete (*mSrcSurfaceMapList.begin()); mSrcSurfaceMapList.erase(mSrcSurfaceMapList.begin()); } } #endif //find if mapped map = (VASurfaceMap*) findSurfaceMapByValue(value); if (map) { //has mapped, get surfaceID directly and do all necessary actions LOG_V("direct find surface %d from value %i\n", map->getVASurface(), value); *sid = map->getVASurface(); map->doMapping(); return ret; } //if no found from list, then try to map value with parameters LOG_V("not find surface from cache with value %i, start mapping if enough information\n", value); if (mStoreMetaDataInBuffers.isEnabled) { //if type is IntelMetadataBufferTypeGrallocSource, use default parameters since no ValueInfo if (type == IntelMetadataBufferTypeGrallocSource) { vinfo.mode = MEM_MODE_GFXHANDLE; vinfo.handle = 0; vinfo.size = 0; vinfo.width = mComParams.resolution.width; vinfo.height = mComParams.resolution.height; vinfo.lumaStride = mComParams.resolution.width; vinfo.chromStride = mComParams.resolution.width; vinfo.format = VA_FOURCC_NV12; vinfo.s3dformat = 0xFFFFFFFF; } else { //get all info mapping needs imb.GetValueInfo(pvinfo); imb.GetExtraValues(extravalues, extravalues_count); } } else { //raw mode vinfo.mode = MEM_MODE_MALLOC; vinfo.handle = 0; vinfo.size = inBuffer->size; vinfo.width = mComParams.resolution.width; vinfo.height = mComParams.resolution.height; vinfo.lumaStride = mComParams.resolution.width; vinfo.chromStride = mComParams.resolution.width; vinfo.format = VA_FOURCC_NV12; vinfo.s3dformat = 0xFFFFFFFF; } /* Start mapping, if pvinfo is not NULL, then have enough info to map; * if extravalues is not NULL, then need to do more times mapping */ if (pvinfo){ //map according info, and add to surfacemap list map = new VASurfaceMap(mVADisplay, mSupportedSurfaceMemType); map->setValue(value); map->setValueInfo(*pvinfo); map->setAction(mVASurfaceMappingAction); ret = map->doMapping(); if (ret == ENCODE_SUCCESS) { LOG_V("surface mapping success, map value %i into surface %d\n", value, map->getVASurface()); mSrcSurfaceMapList.push_back(map); } else { delete map; LOG_E("surface mapping failed, wrong info or meet serious error\n"); return ret; } *sid = map->getVASurface(); } else { //can't map due to no info LOG_E("surface mapping failed, missing information\n"); return ENCODE_NO_REQUEST_DATA; } if (extravalues) { //map more using same ValueInfo for(unsigned int i=0; i<extravalues_count; i++) { map = new VASurfaceMap(mVADisplay, mSupportedSurfaceMemType); map->setValue(extravalues[i]); map->setValueInfo(vinfo); ret = map->doMapping(); if (ret == ENCODE_SUCCESS) { LOG_V("surface mapping extravalue success, map value %i into surface %d\n", extravalues[i], map->getVASurface()); mSrcSurfaceMapList.push_back(map); } else { delete map; map = NULL; LOG_E( "surface mapping extravalue failed, extravalue is %i\n", extravalues[i]); } } } return ret; } Encode_Status VideoEncoderBase::renderDynamicBitrate(EncodeTask* task) { VAStatus vaStatus = VA_STATUS_SUCCESS; LOG_V( "Begin\n\n"); // disable bits stuffing and skip frame apply to all rate control mode VAEncMiscParameterBuffer *miscEncParamBuf; VAEncMiscParameterRateControl *bitrateControlParam; VABufferID miscParamBufferID; vaStatus = vaCreateBuffer(mVADisplay, mVAContext, VAEncMiscParameterBufferType, sizeof (VAEncMiscParameterBuffer) + sizeof (VAEncMiscParameterRateControl), 1, NULL, &miscParamBufferID); CHECK_VA_STATUS_RETURN("vaCreateBuffer"); vaStatus = vaMapBuffer(mVADisplay, miscParamBufferID, (void **)&miscEncParamBuf); CHECK_VA_STATUS_RETURN("vaMapBuffer"); miscEncParamBuf->type = VAEncMiscParameterTypeRateControl; bitrateControlParam = (VAEncMiscParameterRateControl *)miscEncParamBuf->data; bitrateControlParam->bits_per_second = mComParams.rcParams.bitRate; bitrateControlParam->initial_qp = mComParams.rcParams.initQP; if(mComParams.rcParams.enableIntraFrameQPControl && (task->type == FTYPE_IDR || task->type == FTYPE_I)) { bitrateControlParam->min_qp = mComParams.rcParams.I_minQP; bitrateControlParam->max_qp = mComParams.rcParams.I_maxQP; mRenderBitRate = true; LOG_I("apply I min/max qp for IDR or I frame\n"); } else { bitrateControlParam->min_qp = mComParams.rcParams.minQP; bitrateControlParam->max_qp = mComParams.rcParams.maxQP; mRenderBitRate = false; LOG_I("revert to original min/max qp after IDR or I frame\n"); } bitrateControlParam->target_percentage = mComParams.rcParams.targetPercentage; bitrateControlParam->window_size = mComParams.rcParams.windowSize; bitrateControlParam->rc_flags.bits.disable_frame_skip = mComParams.rcParams.disableFrameSkip; bitrateControlParam->rc_flags.bits.disable_bit_stuffing = mComParams.rcParams.disableBitsStuffing; bitrateControlParam->basic_unit_size = 0; LOG_I("bits_per_second = %d\n", bitrateControlParam->bits_per_second); LOG_I("initial_qp = %d\n", bitrateControlParam->initial_qp); LOG_I("min_qp = %d\n", bitrateControlParam->min_qp); LOG_I("max_qp = %d\n", bitrateControlParam->max_qp); LOG_I("target_percentage = %d\n", bitrateControlParam->target_percentage); LOG_I("window_size = %d\n", bitrateControlParam->window_size); LOG_I("disable_frame_skip = %d\n", bitrateControlParam->rc_flags.bits.disable_frame_skip); LOG_I("disable_bit_stuffing = %d\n", bitrateControlParam->rc_flags.bits.disable_bit_stuffing); vaStatus = vaUnmapBuffer(mVADisplay, miscParamBufferID); CHECK_VA_STATUS_RETURN("vaUnmapBuffer"); vaStatus = vaRenderPicture(mVADisplay, mVAContext, &miscParamBufferID, 1); CHECK_VA_STATUS_RETURN("vaRenderPicture"); return ENCODE_SUCCESS; } Encode_Status VideoEncoderBase::renderDynamicFrameRate() { VAStatus vaStatus = VA_STATUS_SUCCESS; if (mComParams.rcMode != RATE_CONTROL_VCM) { LOG_W("Not in VCM mode, but call SendDynamicFramerate\n"); return ENCODE_SUCCESS; } VAEncMiscParameterBuffer *miscEncParamBuf; VAEncMiscParameterFrameRate *frameRateParam; VABufferID miscParamBufferID; vaStatus = vaCreateBuffer(mVADisplay, mVAContext, VAEncMiscParameterBufferType, sizeof(miscEncParamBuf) + sizeof(VAEncMiscParameterFrameRate), 1, NULL, &miscParamBufferID); CHECK_VA_STATUS_RETURN("vaCreateBuffer"); vaStatus = vaMapBuffer(mVADisplay, miscParamBufferID, (void **)&miscEncParamBuf); CHECK_VA_STATUS_RETURN("vaMapBuffer"); miscEncParamBuf->type = VAEncMiscParameterTypeFrameRate; frameRateParam = (VAEncMiscParameterFrameRate *)miscEncParamBuf->data; frameRateParam->framerate = (unsigned int) (mComParams.frameRate.frameRateNum + mComParams.frameRate.frameRateDenom/2) / mComParams.frameRate.frameRateDenom; vaStatus = vaUnmapBuffer(mVADisplay, miscParamBufferID); CHECK_VA_STATUS_RETURN("vaUnmapBuffer"); vaStatus = vaRenderPicture(mVADisplay, mVAContext, &miscParamBufferID, 1); CHECK_VA_STATUS_RETURN("vaRenderPicture"); LOG_I( "frame rate = %d\n", frameRateParam->framerate); return ENCODE_SUCCESS; } Encode_Status VideoEncoderBase::renderHrd() { VAStatus vaStatus = VA_STATUS_SUCCESS; VAEncMiscParameterBuffer *miscEncParamBuf; VAEncMiscParameterHRD *hrdParam; VABufferID miscParamBufferID; vaStatus = vaCreateBuffer(mVADisplay, mVAContext, VAEncMiscParameterBufferType, sizeof(miscEncParamBuf) + sizeof(VAEncMiscParameterHRD), 1, NULL, &miscParamBufferID); CHECK_VA_STATUS_RETURN("vaCreateBuffer"); vaStatus = vaMapBuffer(mVADisplay, miscParamBufferID, (void **)&miscEncParamBuf); CHECK_VA_STATUS_RETURN("vaMapBuffer"); miscEncParamBuf->type = VAEncMiscParameterTypeHRD; hrdParam = (VAEncMiscParameterHRD *)miscEncParamBuf->data; hrdParam->buffer_size = mHrdParam.bufferSize; hrdParam->initial_buffer_fullness = mHrdParam.initBufferFullness; vaStatus = vaUnmapBuffer(mVADisplay, miscParamBufferID); CHECK_VA_STATUS_RETURN("vaUnmapBuffer"); vaStatus = vaRenderPicture(mVADisplay, mVAContext, &miscParamBufferID, 1); CHECK_VA_STATUS_RETURN("vaRenderPicture"); return ENCODE_SUCCESS; } VASurfaceMap *VideoEncoderBase::findSurfaceMapByValue(intptr_t value) { android::List<VASurfaceMap *>::iterator node; for(node = mSrcSurfaceMapList.begin(); node != mSrcSurfaceMapList.end(); node++) { if ((*node)->getValue() == value) return *node; else continue; } return NULL; }
[ "douglas@gadeco.com.br" ]
douglas@gadeco.com.br
4950da42173bf5f962b52b7c31b0538531decdf8
30871a624da21421ee839ad49a0b6f65f74b80bf
/Lectures Codes/Code (6)/Code/crypto.cpp
d364f8f2ce64ff064a97a7715f62350227d78ba5
[]
no_license
bakurits/Programming-Abstractions
7b15dbe543951e74d543389cb0c37efd4ef07cb2
680a87b3f029fe004355512be70ba822d1cd5ca9
refs/heads/master
2021-01-19T19:14:26.673149
2017-07-19T18:21:16
2017-07-19T18:21:16
88,407,754
0
1
null
null
null
null
UTF-8
C++
false
false
749
cpp
#include <map> #include <string> #include <iostream> #include <fstream> #include <cstring> #include "foreach.h" using namespace std; /* Crypto system for completely unsafe login. */ struct Crypto { map<string, string> users; Crypto() { ifstream input("plaintext-passwords.txt"); string username, password; while (getline(input, username) && getline(input, password)) { users[username] = password; } } static Crypto& instance() { static Crypto theInstance; return theInstance; } bool login(string& username, string& password) { if (!users.count(username)) return false; return users[username] == password; } }; bool login(string& username, string& password) { return Crypto::instance().login(username, password); }
[ "bakuricucxashvili@gmail.com" ]
bakuricucxashvili@gmail.com
4c942431d86ea9f64ce5f4ac6e5cc9fe9ce44dc9
01013d41da9fa455f7e6bd0f41622a59b121d6ab
/QBaekJoon_1216_돌게임/ConsoleApplication1_Test/ConsoleApplication1_Test.cpp
558d8c9714a83f69df47ea38d343952da22cdabe
[]
no_license
sanghoon23/Algorithm
e0a166d85ee3bc05bc34c867736610c70f667d40
61094fcd82035b1575372a4b1b90e3c03cfa2cc7
refs/heads/master
2023-06-03T03:05:48.116288
2021-06-23T07:02:42
2021-06-23T07:02:42
231,328,217
0
0
null
null
null
null
UTF-8
C++
false
false
827
cpp
#include "pch.h" #include <iostream> using namespace std; int N = 0; int main() { cin >> N; if (N % 2 == 0) cout << "CY"; else cout << "SK"; return 0; } /////////////////////////////////////////////////////////////////////////////////////////////////// //@이상한 짓 //#include <iostream> //#include <vector> //#include <string> //using namespace std; //int N = 0; //int main() //{ // vector<string> Temp1; // Temp1.push_back("Start"); // for (int i = 1; i <= 999; ++i) // { // if (i == 1) { Temp1.push_back("SK"); continue; } // if (i % 3 == 1 && i != 1) Temp1.push_back("SK"); // else Temp1.push_back("CY"); // } // // vector<string> Temp2; // Temp2.push_back("Start"); // for (int i = 1; i <= 999; ++i) // { // if (i % 2 == 0) Temp2.push_back("CY"); // else Temp2.push_back("SK"); // } // // return 0; //}
[ "sanghoon23@naver.com" ]
sanghoon23@naver.com
d12f628a9a249cbc5d2d8e4d8c6035a1db33a628
1942a0d16bd48962e72aa21fad8d034fa9521a6c
/aws-cpp-sdk-ssm/include/aws/ssm/model/DescribeEffectiveInstanceAssociationsRequest.h
d01548bc4f860ff19fc9d09f48ff8794c479278c
[ "Apache-2.0", "JSON", "MIT" ]
permissive
yecol/aws-sdk-cpp
1aff09a21cfe618e272c2c06d358cfa0fb07cecf
0b1ea31e593d23b5db49ee39d0a11e5b98ab991e
refs/heads/master
2021-01-20T02:53:53.557861
2018-02-11T11:14:58
2018-02-11T11:14:58
83,822,910
0
1
null
2017-03-03T17:17:00
2017-03-03T17:17:00
null
UTF-8
C++
false
false
5,367
h
/* * Copyright 2010-2016 Amazon.com, Inc. or its affiliates. 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. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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 #include <aws/ssm/SSM_EXPORTS.h> #include <aws/ssm/SSMRequest.h> #include <aws/core/utils/memory/stl/AWSString.h> namespace Aws { namespace SSM { namespace Model { /** */ class AWS_SSM_API DescribeEffectiveInstanceAssociationsRequest : public SSMRequest { public: DescribeEffectiveInstanceAssociationsRequest(); Aws::String SerializePayload() const override; Aws::Http::HeaderValueCollection GetRequestSpecificHeaders() const override; /** * <p>The instance ID for which you want to view all associations.</p> */ inline const Aws::String& GetInstanceId() const{ return m_instanceId; } /** * <p>The instance ID for which you want to view all associations.</p> */ inline void SetInstanceId(const Aws::String& value) { m_instanceIdHasBeenSet = true; m_instanceId = value; } /** * <p>The instance ID for which you want to view all associations.</p> */ inline void SetInstanceId(Aws::String&& value) { m_instanceIdHasBeenSet = true; m_instanceId = value; } /** * <p>The instance ID for which you want to view all associations.</p> */ inline void SetInstanceId(const char* value) { m_instanceIdHasBeenSet = true; m_instanceId.assign(value); } /** * <p>The instance ID for which you want to view all associations.</p> */ inline DescribeEffectiveInstanceAssociationsRequest& WithInstanceId(const Aws::String& value) { SetInstanceId(value); return *this;} /** * <p>The instance ID for which you want to view all associations.</p> */ inline DescribeEffectiveInstanceAssociationsRequest& WithInstanceId(Aws::String&& value) { SetInstanceId(value); return *this;} /** * <p>The instance ID for which you want to view all associations.</p> */ inline DescribeEffectiveInstanceAssociationsRequest& WithInstanceId(const char* value) { SetInstanceId(value); return *this;} /** * <p>The maximum number of items to return for this call. The call also returns a * token that you can specify in a subsequent call to get the next set of * results.</p> */ inline int GetMaxResults() const{ return m_maxResults; } /** * <p>The maximum number of items to return for this call. The call also returns a * token that you can specify in a subsequent call to get the next set of * results.</p> */ inline void SetMaxResults(int value) { m_maxResultsHasBeenSet = true; m_maxResults = value; } /** * <p>The maximum number of items to return for this call. The call also returns a * token that you can specify in a subsequent call to get the next set of * results.</p> */ inline DescribeEffectiveInstanceAssociationsRequest& WithMaxResults(int value) { SetMaxResults(value); return *this;} /** * <p>The token for the next set of items to return. (You received this token from * a previous call.)</p> */ inline const Aws::String& GetNextToken() const{ return m_nextToken; } /** * <p>The token for the next set of items to return. (You received this token from * a previous call.)</p> */ inline void SetNextToken(const Aws::String& value) { m_nextTokenHasBeenSet = true; m_nextToken = value; } /** * <p>The token for the next set of items to return. (You received this token from * a previous call.)</p> */ inline void SetNextToken(Aws::String&& value) { m_nextTokenHasBeenSet = true; m_nextToken = value; } /** * <p>The token for the next set of items to return. (You received this token from * a previous call.)</p> */ inline void SetNextToken(const char* value) { m_nextTokenHasBeenSet = true; m_nextToken.assign(value); } /** * <p>The token for the next set of items to return. (You received this token from * a previous call.)</p> */ inline DescribeEffectiveInstanceAssociationsRequest& WithNextToken(const Aws::String& value) { SetNextToken(value); return *this;} /** * <p>The token for the next set of items to return. (You received this token from * a previous call.)</p> */ inline DescribeEffectiveInstanceAssociationsRequest& WithNextToken(Aws::String&& value) { SetNextToken(value); return *this;} /** * <p>The token for the next set of items to return. (You received this token from * a previous call.)</p> */ inline DescribeEffectiveInstanceAssociationsRequest& WithNextToken(const char* value) { SetNextToken(value); return *this;} private: Aws::String m_instanceId; bool m_instanceIdHasBeenSet; int m_maxResults; bool m_maxResultsHasBeenSet; Aws::String m_nextToken; bool m_nextTokenHasBeenSet; }; } // namespace Model } // namespace SSM } // namespace Aws
[ "henso@amazon.com" ]
henso@amazon.com
d70ad5698dd021b4636a0ed9d8885e254ec963fa
5f4b7850caed77bf1d2ca8d5125dc21099b79209
/Chapter 5-C++ and STL/& 5.5.cpp
5d81d90c87aad48f5850b86af282480a0030e25b
[]
no_license
Inuyashaaaaa/IntroductionToAlgorithmicContests
92720cffae226b6951aa389a14fcaacb94b3c275
55c69843f42162ed3b8f661c20f451c1174bfff1
refs/heads/master
2020-06-20T00:24:10.893652
2020-03-14T06:32:12
2020-03-14T06:32:12
196,926,192
2
0
null
null
null
null
UTF-8
C++
false
false
1,257
cpp
#include<set> #include<map> #include<stack> #include<vector> #include<algorithm> #include<iostream> #include<string> #include<iterator> #define ALL(x) x.begin(),x.end() #define INS(x) inserter(x,x.begin()) using namespace std; typedef set<int> Set; map<Set,int> IDcache; vector<Set> Setcache; int ID (Set x) { if (IDcache.count(x)) return IDcache[x]; Setcache.push_back(x); return IDcache[x] = Setcache.size() - 1; } int main() { stack<int> s; int T; cin >> T; int n; while(T--){ cin >> n; for(int i = 0; i < n; i++){ string op; cin >> op; if(op[0] == 'P') s.push(ID(Set())); else if(op[0] == 'D') s.push(s.top()); else { Set x1 = Setcache[s.top()]; s.pop(); Set x2 = Setcache[s.top()]; s.pop(); Set x; if(op[0] == 'U') set_union (ALL(x1), ALL(x2), INS(x)); if(op[0] == 'I') set_intersection (ALL(x1), ALL(x2), INS(x)); if(op[0] == 'A') { x = x2; x.insert(ID(x1));} s.push(ID(x)); } cout << Setcache[s.top()].size() << endl; } cout << "***" << endl; } //system("pause"); return 0; }
[ "1486835097@qq.com" ]
1486835097@qq.com
1ba67f969b16c6d99c7e60a80eb038a892ead66f
651806424e6d31f80ffe61bac3de28ded42c7fba
/raytracer/include/scene/sceneobject.hpp
560ae56984e8c950a62df89508eb1b9338aafbfe
[]
no_license
FrederikBoehm/map_raytracer
2fcb9f636b3316750213ea2ad7b97d8632cd716c
de95f560314563b29f5adb4ab35ec63295fe0631
refs/heads/master
2023-06-23T14:51:14.086191
2021-07-23T07:42:28
2021-07-23T07:42:28
373,054,060
0
0
null
null
null
null
UTF-8
C++
false
false
2,500
hpp
#ifndef SCENEOBJECT_HPP #define SCENEOBJECT_HPP #include "shapes/shape.hpp" #include "shapes/plane.hpp" #include "shapes/sphere.hpp" #include "material/material.hpp" #include "surface_interaction.hpp" #include <memory> namespace rt { class CHostSceneobject; class CDeviceSceneobject { friend class CSceneobjectConnection; public: D_CALLABLE SSurfaceInteraction intersect(const Ray& ray); private: CShape* m_shape; CMaterial m_material; //CDeviceSceneobject() {} }; class CSceneobjectConnection { public: CSceneobjectConnection(CHostSceneobject* hostSceneobject); CSceneobjectConnection(const CSceneobjectConnection&& connection); void allocateDeviceMemory(); void setDeviceSceneobject(CDeviceSceneobject* destination); void copyToDevice(); void freeDeviceMemory(); private: CHostSceneobject* m_hostSceneobject = nullptr; CDeviceSceneobject* m_deviceSceneobject = nullptr; CShape* m_deviceShape = nullptr; }; class CHostSceneobject { friend class CSceneobjectConnection; public: CHostSceneobject(EShape shape, const glm::vec3& worldPos, float radius, const glm::vec3& normal, const glm::vec3& le); CHostSceneobject(EShape shape, const glm::vec3& worldPos, float radius, const glm::vec3& normal, const glm::vec3& diffuseReflection, const glm::vec3& specularReflection, float shininess); CHostSceneobject::CHostSceneobject(CHostSceneobject&& sceneobject); void allocateDeviceMemory(); void setDeviceSceneobject(CDeviceSceneobject* destination); void copyToDevice(); void freeDeviceMemory(); private: std::shared_ptr<CShape> m_shape; CMaterial m_material; CSceneobjectConnection m_hostDeviceConnection; static std::shared_ptr<CShape> getShape(EShape shape, const glm::vec3& worldPos, float radius, const glm::vec3& normal); }; inline void CHostSceneobject::allocateDeviceMemory() { m_hostDeviceConnection.allocateDeviceMemory(); } inline void CHostSceneobject::setDeviceSceneobject(CDeviceSceneobject* destination) { m_hostDeviceConnection.setDeviceSceneobject(destination); } inline void CHostSceneobject::copyToDevice() { m_hostDeviceConnection.copyToDevice(); } inline void CSceneobjectConnection::setDeviceSceneobject(CDeviceSceneobject* destination) { m_deviceSceneobject = destination; } inline void CHostSceneobject::freeDeviceMemory() { m_hostDeviceConnection.freeDeviceMemory(); } } #endif // !SCENEOBJECT_HPP
[ "frederik.boehm@fau.de" ]
frederik.boehm@fau.de
f8558dc5325a7c740acfa85c5011b1c21e777db5
c280d5e1c4448f2206cf4c429d2ff6b34edeb0f5
/include/http/net/Cert.hpp
24d5db610314b52d89ec6a41e891b7e4dcec6bb8
[ "MIT" ]
permissive
y11en/cpphttp
830145e05523ff2b90617904a3890d4ac8d3a8d5
adfc148716bc65aff29e881d1872c9dea6fc6af9
refs/heads/master
2020-04-01T19:25:54.026156
2017-01-28T20:02:13
2017-01-28T20:02:13
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,649
hpp
#pragma once #include <algorithm> #include <memory> #include <string> namespace http { struct OpenSslPrivateCertData; /**A single private key and certificate used to authenticate a TLS server or client.*/ class PrivateCert { public: #if defined(_WIN32) && !defined(HTTP_USE_OPENSSL) /**PCCERT_CONTEXT*/ typedef const void *Native; #else typedef std::shared_ptr<OpenSslPrivateCertData> Native; #endif PrivateCert() : native(nullptr) {} explicit PrivateCert(Native native) : native(native) { } PrivateCert(const PrivateCert &cp) : native(dup(cp.native)) { } PrivateCert(PrivateCert &&mv); ~PrivateCert(); PrivateCert& operator = (const PrivateCert &cp) { if (native) free(native); if (cp.native) native = dup(cp.native); return *this; } PrivateCert& operator = (PrivateCert &&mv) { std::swap(native, mv.native); return *this; } explicit operator bool()const { return native != nullptr; } Native get()const { return native; } private: Native native; static void free(Native native); static Native dup(Native native); }; /**Load a certificate with private key from a PKCS#12 archive.*/ PrivateCert load_pfx_cert(const std::string &file, const std::string &password); /**Load a certificate with private key from a pair of pem files. * NOT COMPLETE */ PrivateCert load_pem_priv_cert(const std::string &crt_file, const std::string &key_file); }
[ "wnewbery@hotmail.co.uk" ]
wnewbery@hotmail.co.uk
dfb9b65d7b0a6f6f87e6e548b2d761f5fb7917c6
a7c6423c34179d1b198d193fc94ad96472f0372a
/엔터프라이즈/1주/ComponentDevelopment/교재소스/Chapter12/DynamicCollection/Client/stdafx.cpp
bbd5903addea3f796bcdec90db6a79c291791d84
[]
no_license
jung-ki-hun/project_S
1e197b43986c00170b7d2ca48a55c3fb133ddc4b
aec7d0fda3d48a15515f25eca43d0e76e6678f25
refs/heads/master
2023-03-29T13:07:11.965927
2021-04-03T15:27:20
2021-04-03T15:27:20
353,912,210
0
0
null
null
null
null
UTF-8
C++
false
false
274
cpp
// stdafx.cpp : source file that includes just the standard includes // Client.pch will be the pre-compiled header // stdafx.obj will contain the pre-compiled type information #include "stdafx.h" #if (_ATL_VER < 0x0700) #include <atlimpl.cpp> #endif //(_ATL_VER < 0x0700)
[ "khkh0130@gmail.com" ]
khkh0130@gmail.com
64ef952d1ba67b5d1df5b537b3977042f2584081
59dc938d387e0fbd1970391f27d26a4adc0423a6
/Engine/Source/Core/Filmic/HdrRgbFilm.cpp
fb9657fdd1e01277898211cbbaf333c0ec21290d
[ "MIT" ]
permissive
VovoWang/Photon-v2
35d06bcc279a887c1e4a301744fa97cb77210216
82687ba650e98a2bfb73d897f673aa9a856245af
refs/heads/master
2021-04-26T22:19:04.520190
2018-03-06T11:44:13
2018-03-06T11:44:13
124,069,900
0
0
null
2018-03-06T11:40:25
2018-03-06T11:40:25
null
UTF-8
C++
false
false
6,936
cpp
#include "Core/Filmic/HdrRgbFilm.h" #include "Math/TVector3.h" #include "Frame/TFrame.h" #include "FileIO/InputPacket.h" #include "Core/Filmic/SampleFilter.h" #include "Math/Function/TConstant2D.h" #include "Math/Function/TGaussian2D.h" #include "Core/Filmic/SampleFilterFactory.h" #include <cstddef> #include <iostream> #include <algorithm> #include <cmath> namespace ph { HdrRgbFilm::HdrRgbFilm(const int64 actualWidthPx, const int64 actualHeightPx, const std::shared_ptr<SampleFilter>& filter) : HdrRgbFilm(actualWidthPx, actualHeightPx, TAABB2D<int64>(TVector2<int64>(0, 0), TVector2<int64>(actualWidthPx, actualHeightPx)), filter) { } HdrRgbFilm::HdrRgbFilm(const int64 actualWidthPx, const int64 actualHeightPx, const TAABB2D<int64>& effectiveWindowPx, const std::shared_ptr<SampleFilter>& filter) : Film(actualWidthPx, actualHeightPx, effectiveWindowPx, filter), m_pixelRadianceSensors(effectiveWindowPx.calcArea(), RadianceSensor()) { } HdrRgbFilm::~HdrRgbFilm() = default; void HdrRgbFilm::addSample(const float64 xPx, const float64 yPx, const SpectralStrength& radiance) { const TVector2<float64> samplePosPx(xPx, yPx); // compute filter bounds TVector2<float64> filterMin(samplePosPx.sub(m_filter->getHalfSizePx())); TVector2<float64> filterMax(samplePosPx.add(m_filter->getHalfSizePx())); // reduce to effective bounds filterMin = filterMin.max(TVector2<float64>(m_effectiveWindowPx.minVertex)); filterMax = filterMax.min(TVector2<float64>(m_effectiveWindowPx.maxVertex)); // compute pixel index bounds (exclusive on x1y1) TVector2<int64> x0y0(filterMin.sub(0.5).ceil()); TVector2<int64> x1y1(filterMax.sub(0.5).floor()); x1y1.x += 1; x1y1.y += 1; for(int64 y = x0y0.y; y < x1y1.y; y++) { for(int64 x = x0y0.x; x < x1y1.x; x++) { // TODO: factor out the -0.5 part const float64 filterX = x - (xPx - 0.5); const float64 filterY = y - (yPx - 0.5); const std::size_t fx = x - m_effectiveWindowPx.minVertex.x; const std::size_t fy = y - m_effectiveWindowPx.minVertex.y; const std::size_t index = fy * static_cast<std::size_t>(m_effectiveResPx.x) + fx; const float64 weight = m_filter->evaluate(filterX, filterY); const Vector3R& rgb = radiance.genLinearSrgb();// FIXME: check color space m_pixelRadianceSensors[index].accuR += rgb.x * weight; m_pixelRadianceSensors[index].accuG += rgb.y * weight; m_pixelRadianceSensors[index].accuB += rgb.z * weight; m_pixelRadianceSensors[index].accuWeight += weight; } } } std::unique_ptr<Film> HdrRgbFilm::genChild(const TAABB2D<int64>& effectiveWindowPx) { auto childFilm = std::make_unique<HdrRgbFilm>(m_actualResPx.x, m_actualResPx.y, effectiveWindowPx, m_filter); HdrRgbFilm* parent = this; HdrRgbFilm* child = childFilm.get(); childFilm->m_merger = [=]() -> void { parent->mergeWith(*child); }; return std::move(childFilm); } void HdrRgbFilm::developRegion(HdrRgbFrame& out_frame, const TAABB2D<int64>& regionPx) const { if(out_frame.widthPx() != m_actualResPx.x || out_frame.heightPx() != m_actualResPx.y) { std::cerr << "warning: at HdrRgbFilm::develop(), " << "input frame dimension mismatch" << std::endl; return; } TAABB2D<int64> frameIndexBound(m_effectiveWindowPx); frameIndexBound.intersectWith(regionPx); frameIndexBound.maxVertex.subLocal(1); float64 sensorR, sensorG, sensorB; float64 reciWeight; std::size_t fx, fy, filmIndex; for(int64 y = 0; y < m_actualResPx.y; y++) { for(int64 x = 0; x < m_actualResPx.x; x++) { if(!frameIndexBound.isIntersectingArea({x, y})) { continue; } fx = x - m_effectiveWindowPx.minVertex.x; fy = y - m_effectiveWindowPx.minVertex.y; filmIndex = fy * static_cast<std::size_t>(m_effectiveResPx.x) + fx; const float64 sensorWeight = m_pixelRadianceSensors[filmIndex].accuWeight; // prevent division by zero reciWeight = sensorWeight == 0.0 ? 0.0 : 1.0 / sensorWeight; sensorR = m_pixelRadianceSensors[filmIndex].accuR * reciWeight; sensorG = m_pixelRadianceSensors[filmIndex].accuG * reciWeight; sensorB = m_pixelRadianceSensors[filmIndex].accuB * reciWeight; const Vector3R pixel(TVector3<float64>(sensorR, sensorG, sensorB)); // TODO: prevent negative pixel out_frame.setPixel(static_cast<uint32>(x), static_cast<uint32>(y), HdrRgbFrame::Pixel({pixel.x, pixel.y, pixel.z})); } } } void HdrRgbFilm::clear() { std::fill(m_pixelRadianceSensors.begin(), m_pixelRadianceSensors.end(), RadianceSensor()); } void HdrRgbFilm::mergeWith(const HdrRgbFilm& other) { const std::size_t numSensors = other.m_pixelRadianceSensors.size(); for(std::size_t i = 0; i < numSensors; i++) { m_pixelRadianceSensors[i].accuR += other.m_pixelRadianceSensors[i].accuR; m_pixelRadianceSensors[i].accuG += other.m_pixelRadianceSensors[i].accuG; m_pixelRadianceSensors[i].accuB += other.m_pixelRadianceSensors[i].accuB; m_pixelRadianceSensors[i].accuWeight += other.m_pixelRadianceSensors[i].accuWeight; } } // command interface SdlTypeInfo HdrRgbFilm::ciTypeInfo() { return SdlTypeInfo(ETypeCategory::REF_FILM, "hdr-rgb"); } void HdrRgbFilm::ciRegister(CommandRegister& cmdRegister) { SdlLoader loader; loader.setFunc<HdrRgbFilm>(ciLoad); cmdRegister.setLoader(loader); } std::unique_ptr<HdrRgbFilm> HdrRgbFilm::ciLoad(const InputPacket& packet) { const integer filmWidth = packet.getInteger("width", 0, DataTreatment::REQUIRED()); const integer filmHeight = packet.getInteger("height", 0, DataTreatment::REQUIRED()); const std::string filterName = packet.getString("filter-name", "box"); const integer rectX = packet.getInteger("rect-x", 0); const integer rectY = packet.getInteger("rect-y", 0); const integer rectW = packet.getInteger("rect-w", filmWidth); const integer rectH = packet.getInteger("rect-h", filmHeight); std::shared_ptr<SampleFilter> sampleFilter; if(filterName == "box") { sampleFilter = std::make_shared<SampleFilter>(SampleFilterFactory::createBoxFilter()); } else if(filterName == "gaussian") { sampleFilter = std::make_shared<SampleFilter>(SampleFilterFactory::createGaussianFilter()); } else if(filterName == "mn") { sampleFilter = std::make_shared<SampleFilter>(SampleFilterFactory::createMNFilter()); } else { std::cerr << "warning: at HdrRgbFilm::ciLoad(), " << "unknown filter name specified: " << filterName << std::endl; } const TAABB2D<int64> effectWindowPx({rectX, rectY}, {rectX + rectW, rectY + rectH}); return std::make_unique<HdrRgbFilm>(filmWidth, filmHeight, effectWindowPx, sampleFilter); } }// end namespace
[ "b01502051@ntu.edu.tw" ]
b01502051@ntu.edu.tw
3eebae5c24d2b47631dde31ff67f47363a096ffe
4beed964b545272ffecaedd561e6296878336752
/.vscode/tree planting.cpp
4b8c87240a93d3d6dcc96678dd7f66e85536ab35
[]
no_license
papicheng/offer-boom
dddf946efb39c17337252886f0a1c7f6dc791119
de440090a4d694ac4de8ebb0abeb56494ffe86d3
refs/heads/master
2022-12-03T18:41:27.737606
2020-08-19T12:27:48
2020-08-19T12:27:48
288,728,075
0
0
null
null
null
null
GB18030
C++
false
false
2,211
cpp
/*功能: 种树问题: 输入的第一行为一个数字,表示土地的长度; 输入的第二行为一个由0和1组成并以空格分割的数列,表示该土地上目前的种植情况。 输入 5 1 0 0 0 0 输出 2 */ #include<bits/stdc++.h> using namespace std; /* 每一次循环一次结束,x就是代表如果当前位置种花(置1)的话,当前位置和之前所 有位置能种花的最大个数,y就是代表如果当前位置不种花(置0)的话,当前位置和 之前所有位置能种花的最大个数 */ /*方法一 import java.util.*; public class Main{ static int N = 100010; static int[] a = new int[N]; public static void main(String[] args){ Scanner cin = new Scanner(System.in); int n = cin.nextInt(); for (int i = 1; i <= n; i ++){ a[i] = cin.nextInt(); } int cnt = 0; for (int i = 1; i <= n;){ if (a[i] == 0){ if (a[i - 1] == 0 && a[i + 1] == 0) cnt ++; i += 2; }else{ i += 2; } } System.out.print(cnt); } } */ ////方法一有问题 int method1(int n, vector<int>& B){ vector<int> A(B); A.push_back(0); A.push_back(0); int count = 0; for(int i = 1; i <= n; i += 2){ if(A[i] == 0 && A[i - 1] == 0 && A[i + 1] == 0){ ++count; } } return count; } int method2(int n, vector<int>& A){ int x = 0, y = 0; for( int i = 0; i < n; ++i){ int temp_x, temp_y; if(A[i] == 1){ temp_x = y; temp_y = -1; } else{ temp_x = y + 1; temp_y = max(x, y); } x = temp_x; y = temp_y; } return max(x, y); } int main() { int n; // cin>> n; n = 8; vector<int> A; for(int i = 0;i < n; ++i){ int t = 0; // cin>>t; A.push_back(t); } A[0] = 1; A[6] = 1; //输入结束///////////////////////////////////////////// int res; res = method1(n, A); cout<<res<<endl; res = method2(n, A); cout<< res<<endl; return 0; }
[ "2275316862@qq.com" ]
2275316862@qq.com
6b7f0eb8314ab453fc3af2695e91c4dcfc9e2ed1
445afeae8a60e77bba1329eb983609e862c2c32d
/Core/HttpHeader.h
be24c882407ee34cb06ff2db0cb64c88088ca3cc
[ "MIT" ]
permissive
staring/Remote_Access_Library
39a5e3d1c6a1e8c61aa4a45085cb432b3365b2fe
8fb1c7494b89e76fa5a438a84b01e21ae24ccff8
refs/heads/master
2021-01-19T11:32:45.214576
2017-02-04T17:11:23
2017-02-04T17:11:23
null
0
0
null
null
null
null
UTF-8
C++
false
false
847
h
#pragma once #include <unordered_map> #include <string> #include <istream> namespace SL { namespace Remote_Access_Library { namespace Network { const auto HTTP_METHOD = "Method"; const auto HTTP_PATH = "Path"; const auto HTTP_VERSION = "Http_Version"; const auto HTTP_STATUSCODE = "Http_StatusCode"; const auto HTTP_CONTENTLENGTH = "Content-Length"; const auto HTTP_CONTENTTYPE = "Content-Type"; const auto HTTP_CACHECONTROL = "Cache-Control"; const auto HTTP_LASTMODIFIED = "Last-Modified"; const auto HTTP_SECWEBSOCKETKEY = "Sec-WebSocket-Key"; const auto HTTP_SECWEBSOCKETACCEPT = "Sec-WebSocket-Accept"; const auto HTTP_ENDLINE = "\r\n"; const auto HTTP_KEYVALUEDELIM = ": "; std::unordered_map<std::string, std::string> Parse(std::string defaultheaderversion, std::istream& stream); } } }
[ "smasherprog@gmail.com" ]
smasherprog@gmail.com
445ec521815f30a15ff5cc92d148e845a434e6de
13c0a6bf91796c1a53044d78395a95599c0924c3
/Test-2-AnalogInput/Test-2-AnalogInput.ino
eb92e504997175a37332ae00129061ef94ee7e24
[]
no_license
kennyviperhk/Moto
df139c81eeb51d5da8928987fff1400c8c3361f2
412da6f8a5686278836c196ad6579aa41a57b9cc
refs/heads/master
2020-11-30T15:36:08.145911
2020-09-24T08:57:51
2020-09-24T08:57:51
230,432,326
0
0
null
null
null
null
UTF-8
C++
false
false
2,325
ino
/* Analog Input Demonstrates analog input by reading an analog sensor on analog pin 0 and turning on and off a light emitting diode(LED) connected to digital pin 13. The amount of time the LED will be on and off depends on the value obtained by analogRead(). The circuit: Potentiometer attached to analog input 0 center pin of the potentiometer to the analog pin one side pin (either one) to ground the other side pin to +5V LED anode (long leg) attached to digital output 13 LED cathode (short leg) attached to ground Note: because most Arduinos have a built-in LED attached to pin 13 on the board, the LED is optional. Created by David Cuartielles modified 30 Aug 2011 By Tom Igoe This example code is in the public domain. http://arduino.cc/en/Tutorial/AnalogInput */ int brake1Range[2] = {513, 507}; int throttle1Range[2] = {190, 860}; int brake1Pin = A0; // select the input pin for the potentiometer int throttle1Pin = A1; // select the input pin for the potentiometer int ledPin = 13; // select the pin for the LED int brake1Val = 0; // variable to store the value coming from the sensor int throttle1Val = 0; // variable to store the value coming from the sensor int b1Val = 0; // variable to store the value coming from the sensor int t1Val = 0; // variable to store the value coming from the sensor void setup() { // declare the ledPin as an OUTPUT: pinMode(ledPin, OUTPUT); Serial.begin(115200); } void loop() { // read the value from the sensor: brake1Val = analogRead(brake1Pin); throttle1Val = analogRead(throttle1Pin); b1Val = map(brake1Val, brake1Range[0], brake1Range[1], 0, 255); if (brake1Val > brake1Range[0]) { b1Val = 0; } else if (brake1Val <= brake1Range[1]) { b1Val = 255; } if (throttle1Val > throttle1Range[0]) { if (throttle1Val > throttle1Range[1]) { throttle1Val = throttle1Range[1]; } t1Val = map(throttle1Val, throttle1Range[0], throttle1Range[1], 0, 255); } else if (throttle1Val <= throttle1Range[0]) { t1Val = 0; } Serial.print( "A0: "); Serial.print( brake1Val); Serial.print( " A1: "); Serial.print( throttle1Val); Serial.print( " A0: "); Serial.print( b1Val); Serial.print( " A1: "); Serial.println( t1Val); }
[ "kennyviperhk@gmail.com" ]
kennyviperhk@gmail.com
4f2126d993c56925cdd51de808a7dd074920e71b
da1aa824deb8d7d7416151601e662629765780f0
/Seg3D/src/Core/Algorithms/Fields/ScaleFieldMeshAndData.h
831cceedaebe447af413a2792972a67aa5de9967
[ "MIT" ]
permissive
viscenter/educe
69b5402782a4455af6d4009cb69f0d9a47042095
2dca76e7def3e0620896f155af64f6ba84163d77
refs/heads/master
2021-01-02T22:44:36.560170
2009-06-12T15:16:15
2009-06-12T15:16:15
5,413,435
1
0
null
null
null
null
UTF-8
C++
false
false
3,999
h
/* For more information, please see: http://software.sci.utah.edu The MIT License Copyright (c) 2004 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. */ #ifndef CORE_ALGORITHMS_FIELDS_SCALEFIELD_H #define CORE_ALGORITHMS_FIELDS_SCALEFIELD_H 1 #include <Core/Algorithms/Util/DynamicAlgo.h> #include <Core/Geometry/BBox.h> #include <sci_hash_map.h> //! for Windows support #include <Core/Algorithms/Fields/share.h> namespace SCIRunAlgo { using namespace SCIRun; class SCISHARE ScaleFieldMeshAndDataAlgo : public DynamicAlgoBase { public: virtual bool ScaleFieldMeshAndData(ProgressReporter *pr, FieldHandle input, FieldHandle& output,double datascale,double meshscale, bool scale_from_center); }; template <class FIELD> class ScaleFieldMeshAndDataAlgoT : public ScaleFieldMeshAndDataAlgo { public: virtual bool ScaleFieldMeshAndData(ProgressReporter *pr, FieldHandle input, FieldHandle& output,double datascale,double meshscale, bool scale_from_center); }; template <class FIELD> bool ScaleFieldMeshAndDataAlgoT<FIELD>::ScaleFieldMeshAndData(ProgressReporter *pr, FieldHandle input, FieldHandle& output,double datascale,double meshscale, bool scale_from_center) { FIELD *ifield = dynamic_cast<FIELD *>(input.get_rep()); if (ifield == 0) { pr->error("ScaleFieldMeshAndData: Could not obtain input field"); return (false); } output = input->clone(); FIELD *ofield = dynamic_cast<FIELD *>(output.get_rep()); if (ofield == 0) { pr->error("ScaleFieldMeshAndData: Could not copy input field"); return (false); } BBox box = input->mesh()->get_bounding_box(); Vector center = 0.5*(box.min()+box.max()); // scale mesh, only when needed if (scale_from_center || (meshscale != 1.0)) { ofield->mesh_detach(); Transform tf; tf.load_identity(); if (scale_from_center) tf.pre_translate(-center); tf.pre_scale(Vector(meshscale,meshscale,meshscale)); if (scale_from_center) tf.pre_translate(center); ofield->mesh()->transform(tf); } typename FIELD::mesh_handle_type omesh = ofield->get_typed_mesh(); // scale data if (ofield->basis_order() == 0) { typename FIELD::mesh_type::Elem::iterator it, it_end; typename FIELD::value_type val; val = 0; omesh->begin(it); omesh->end(it_end); while (it != it_end) { ifield->value(val,*it); val = val*datascale; ofield->set_value(val,*(it)); ++it; } } else if (ofield->basis_order() == 1) { typename FIELD::mesh_type::Node::iterator it, it_end; typename FIELD::value_type val; val = 0; omesh->begin(it); omesh->end(it_end); while (it != it_end) { ifield->value(val,*it); val = val*datascale; ofield->set_value(val,*(it)); ++it; } } output->copy_properties(input.get_rep()); return (true); } } // end namespace SCIRunAlgo #endif
[ "ryan.baumann@gmail.com" ]
ryan.baumann@gmail.com
165e204af11e0dd6b7af5f198e9fd1d32660b955
b8cf45084f9d045389a0945aff344d2b12ec2d11
/Android/testlac/app/src/main/cpp/lac.h
82ae9cf4e1edb799f48d88893c738b2a708bae81
[ "Apache-2.0" ]
permissive
Siuuuu7/lac
954c2bf544f32499842e6919db167036148deba4
e667d7ad3fb63f01455ce8e9f24a6af12407eea2
refs/heads/master
2023-02-09T19:15:15.448299
2021-01-05T05:14:46
2021-01-05T05:14:46
326,892,477
0
0
Apache-2.0
2021-01-05T05:14:47
2021-01-05T05:07:45
null
UTF-8
C++
false
false
2,733
h
/* Copyright (c) 2020 Baidu, Inc. 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. */ #ifndef BAIDU_LAC_LAC_H #define BAIDU_LAC_LAC_H #include <unordered_map> #include <memory> #include <string> #include <vector> #include "paddle_api.h" /* 编码设置 */ enum CODE_TYPE { CODE_GB18030 = 0, CODE_UTF8 = 1, }; /* 模型输出的结构 */ struct OutputItem { std::string word; // 分词结果 std::string tag; // 单词类型 }; #endif #ifndef LAC_CLASS #define LAC_CLASS class LAC { private: CODE_TYPE _codetype; /* 中间变量 */ std::vector<std::string> _seq_words; std::vector<std::vector<std::string>> _seq_words_batch; std::vector<std::vector<uint64_t>> _lod; std::vector<std::string> _labels; std::vector<OutputItem> _results; std::vector<std::vector<OutputItem>> _results_batch; /* 数据转换词典 */ std::shared_ptr<std::unordered_map<int64_t, std::string>> _id2label_dict; std::shared_ptr<std::unordered_map<std::string, std::string>> _q2b_dict; std::shared_ptr<std::unordered_map<std::string, int64_t>> _word2id_dict; int64_t _oov_id; /* paddle数据结构*/ std::shared_ptr<paddle::lite_api::PaddlePredictor> _predictor; // std::unique_ptr<paddle::lite_api::Tensor> _input_tensor; // std::unique_ptr<const paddle::lite_api::Tensor> _output_tensor; // private: /* 将字符串输入转为Tensor */ int feed_data(const std::vector<std::string> &querys); /* 将模型标签结果转换为模型输出格式 */ int parse_targets( const std::vector<std::string> &tag_ids, const std::vector<std::string> &words, std::vector<OutputItem> &result); public: /* 初始化:装载模型和词典 */ explicit LAC(std::string model_dict_path, int threads = 1, CODE_TYPE type = CODE_UTF8); /* 更新为单个字典文件, 去除protobuf依赖删除 */ // explicit LAC(std::string model_dict_path, int threads = 1, CODE_TYPE type = CODE_UTF8); /* 调用程序 */ std::vector<OutputItem> lexer(const std::string &query); // 单个query std::vector<std::vector<OutputItem>> lexer(const std::vector<std::string> &query); // batch }; #endif
[ "huangdingbang@baidu.com" ]
huangdingbang@baidu.com
3e1126b75177cb960bbe5c39f2a78049ff1105fc
807fd3f1d55cd1a9f253cb63da4db2d259d8b7cf
/main/node/Subscriber.h
06b4f9f8783e03b7aa747779fd0cc098df3569cb
[ "UCAR" ]
permissive
WardF/hycast
f329b42b55a97a0f9159d17e08e6d34f4bb730f8
6dbea3ef56d4cbd1861a04a9b931da3dd3664733
refs/heads/master
2022-12-23T14:05:26.718210
2020-09-28T20:20:58
2020-09-28T20:20:58
299,418,890
0
0
NOASSERTION
2020-09-28T20:03:29
2020-09-28T20:03:29
null
UTF-8
C++
false
false
1,593
h
/** * Subscriber node. * * Copyright 2020 University Corporation for Atmospheric Research. All Rights * reserved. See file "COPYING" in the top-level source-directory for usage * restrictions. * * File: Subscriber.h * Created on: Jan 13, 2020 * Author: Steven R. Emmerson */ #ifndef MAIN_RECEIVER_RECEIVER_H_ #define MAIN_RECEIVER_RECEIVER_H_ #include <main/inet/PortPool.h> #include <main/inet/SockAddr.h> #include "McastProto.h" #include "P2pMgr.h" #include "Repository.h" #include "ServerPool.h" #include <memory> namespace hycast { class Subscriber { class Impl; std::shared_ptr<Impl> pImpl; Subscriber(Impl* const impl); public: /** * Constructs. * * @param[in] srcMcastInfo Information on source-specific multicast * @param[in,out] p2pInfo Information on peer-to-peer network * @param[in,out] p2pSrvrPool Pool of potential peer-servers * @param[in,out] repo Data-product repository */ Subscriber( const SrcMcastAddrs& srcMcastInfo, P2pInfo& p2pInfo, ServerPool& p2pSrvrPool, SubRepo& repo); /** * Executes this instance. Doesn't return until either `halt()` is called * or an exception is thrown. * * @see `halt()` */ void operator()() const; /** * Halts execution of this instance. Causes `operator()()` to return. * * @see `operator()()` */ void halt() const; }; } // namespace #endif /* MAIN_RECEIVER_RECEIVER_H_ */
[ "emmerson@ucar.edu" ]
emmerson@ucar.edu
08ee90f18c7a1a1f996bfc4590838d8ddece3211
93c1a594f554cef47453982015bf80b7c730c4cc
/Project_Beom/Project_Beom/PlayerTopDiagonalStandToDownState.h
233accdf9d1f7541aabb44483c4579a49839886f
[]
no_license
Beom-portfolio/MetalSlug
d0f77db0cc0dda37ad18b5424808c44dba26492e
1fb7f99b73e1f727eb1eeafd859c22996928698e
refs/heads/master
2021-05-22T15:15:32.080061
2020-08-08T13:25:42
2020-08-08T13:25:42
252,969,918
0
1
null
null
null
null
UTF-8
C++
false
false
435
h
#pragma once #include "State.h" class PlayerTopDiagonalStandToDownState : public State { public: PlayerTopDiagonalStandToDownState(); virtual ~PlayerTopDiagonalStandToDownState(); public: virtual void Enter(GameObject* object); virtual State* HandleInput(GameObject* object, KeyManager* input); virtual void Update(GameObject* object, const float& TimeDelta); private: DIRECTION m_originDir = DIR_END; int m_count = 0; };
[ "sb921204@naver.com" ]
sb921204@naver.com
64298cd062c3895afbd7b9b0329da64df002c93e
d41d7fdad2d6f1f54bb74adc205cc5106f6789ad
/cpp_td5/Menu.cpp
f155b279526d6dc11b1d05e03a5691bcd2f16fa6
[]
no_license
kevinushaka/cpp
add664aadfdfe43e3f1e1b46ce9fa77a4d7e98ae
13d55dd48be094be22a6fa6cbeba801d4ea96210
refs/heads/master
2023-01-20T02:55:14.863177
2020-11-23T16:15:46
2020-11-23T16:15:46
293,530,968
0
0
null
null
null
null
UTF-8
C++
false
false
974
cpp
#include "Menu.h" #include <iostream> Menu::Menu(const std::string& title):title(title){} void Menu::activate(){ int choice=-1; int end=this->items.size(); while(choice!=end){ std::cout<<this->title<<std::endl; for (unsigned i=0; i<this->items.size(); i++){ std::cout<<" "<<i<<"- "<<this->items[i]->title<<std::endl; } std::cout<<" "<<end<<"- "<<"quit"<<std::endl; std::cout<<"Votre choix ?"<<std::endl; std::cin>>choice; if(choice<end && choice >=0){ this->items.at(choice)->execute(); }else if( end==choice){ return; }else{ std::cout<<"Le menu séléctionné n'extiste pas. Réessayez."<<std::endl; } } } void Menu::addItem(const MenuItem& in) { this->items.push_back(in.clone()); } Menu::~Menu(){ for (unsigned i=0; i<this->items.size(); i++){ delete this->items[i]; } }
[ "kkubwawe@gmail.com" ]
kkubwawe@gmail.com
130e2b47fe7a273c42093eb657ce8d7342958ecb
919cf843e476f371d9d29141253cdfe55b58a760
/test/zsummer_server/Client.h
1bb5e729a87cff42b4d4a34b941781dc65264917
[ "MIT" ]
permissive
Respublica/zsummer
45ceca5d596cd7dff911d9c76bd2eb2c670a9287
be61a16738ac6ae10768936d04135ac8a4803343
refs/heads/master
2021-01-16T19:25:10.807920
2013-06-09T16:20:29
2013-06-09T16:20:29
null
0
0
null
null
null
null
GB18030
C++
false
false
2,473
h
/* * ZSUMMER License * ----------- * * ZSUMMER is licensed under the terms of the MIT license reproduced below. * This means that ZSUMMER is free software and can be used for both academic * and commercial purposes at absolutely no cost. * * * =============================================================================== * * Copyright (C) 2010-2013 YaweiZhang <yawei_zhang@foxmail.com>. * * 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. * * =============================================================================== * * (end of COPYRIGHT) */ //! zsummer的测试服务模块(对应zsummer底层网络封装的上层设计测试服务) 可视为服务端架构中的 gateway服务/agent服务/前端服务, 特点是高并发高吞吐量 //! Socket Client头文件 #ifndef ZSUMMER_CLIENT_H_ #define ZSUMMER_CLIENT_H_ #include "header.h" //! 前向声明 class CIOServer; //! 上层Socekt Client的二次封装 class CClient :public ITcpSocketCallback { public: CClient(); ~CClient(); void InitSocket(CIOServer *ios, ITcpSocket *s); virtual bool OnRecv(); virtual bool OnConnect(bool bConnected); virtual bool OnSend(); virtual bool OnClose(); CIOServer * m_ios; ITcpSocket * m_socket; //! 每个消息包分两次分别读取头部和包体 unsigned char m_type; //! 读包 Packet m_recving; //! 写包队列 std::queue<Packet *> m_sendque; //! 当前写包 Packet m_sending; }; #endif
[ "yawei_zhang@foxmail.com" ]
yawei_zhang@foxmail.com
5a461f18d15105929bdecc0007c6cf05f9bb4f21
260a986070c2092c2befabf491d6a89b43b8c781
/won/networking/messages/EventDisconnect.hxx
3d4a5309de1edc3c82f758c473ec895aff0a4a41
[]
no_license
razodactyl/darkreign2
7801e5c7e655f63c6789a0a8ed3fef9e5e276605
b6dc795190c05d39baa41e883ddf4aabcf12f968
refs/heads/master
2023-03-26T11:45:41.086911
2020-07-10T22:43:26
2020-07-10T22:43:26
256,714,317
11
2
null
2020-04-20T06:10:20
2020-04-18T09:27:10
C++
UTF-8
C++
false
false
228
hxx
#pragma once #include <enet/enetpp.hxx> #include <Networking/SendableEventMessage.hxx> class EventDisconnect { public: UniqueClassId_Declare(EventDisconnect); ENetPeer* peer; EventDisconnect(ENetPeer* peer); };
[ "razodactyl@gmail.com" ]
razodactyl@gmail.com
fbeb5370992da75f98b4b7378ca4f0c2815f125d
d9a0b2779c9bb41d8ad467107184fcf2035ae688
/Dev/Common/MedusaCore/Core/Proto/Client/EnvironmentTag.pb.cc
14ccf5815ce9c6a47918419f5f8068a1a2a261d7
[]
no_license
alkaidlong/PaperDemo
7061f6803f2c95b6984fdc3420f73d09ce3c194c
a3c355f2734f368381b8122b4fda5f26dd4197b1
refs/heads/master
2021-01-10T14:26:59.883117
2016-04-08T07:45:06
2016-04-08T07:45:06
55,754,744
0
0
null
null
null
null
UTF-8
C++
false
true
16,627
cc
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: EnvironmentTag.proto #define INTERNAL_SUPPRESS_PROTOBUF_FIELD_DEPRECATION #include "EnvironmentTag.pb.h" #include <algorithm> #include <google/protobuf/stubs/common.h> #include <google/protobuf/stubs/once.h> #include <google/protobuf/io/coded_stream.h> #include <google/protobuf/wire_format_lite_inl.h> #include <google/protobuf/descriptor.h> #include <google/protobuf/generated_message_reflection.h> #include <google/protobuf/reflection_ops.h> #include <google/protobuf/wire_format.h> // @@protoc_insertion_point(includes) namespace Medusa { namespace CoreProto { namespace { const ::google::protobuf::Descriptor* EnvironmentTag_descriptor_ = NULL; const ::google::protobuf::internal::GeneratedMessageReflection* EnvironmentTag_reflection_ = NULL; const ::google::protobuf::EnumDescriptor* EnvironmentTag_Versions_descriptor_ = NULL; const ::google::protobuf::EnumDescriptor* EnvironmentTag_Devices_descriptor_ = NULL; const ::google::protobuf::EnumDescriptor* EnvironmentTag_Languages_descriptor_ = NULL; } // namespace void protobuf_AssignDesc_EnvironmentTag_2eproto() { protobuf_AddDesc_EnvironmentTag_2eproto(); const ::google::protobuf::FileDescriptor* file = ::google::protobuf::DescriptorPool::generated_pool()->FindFileByName( "EnvironmentTag.proto"); GOOGLE_CHECK(file != NULL); EnvironmentTag_descriptor_ = file->message_type(0); static const int EnvironmentTag_offsets_[3] = { GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(EnvironmentTag, version_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(EnvironmentTag, device_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(EnvironmentTag, language_), }; EnvironmentTag_reflection_ = new ::google::protobuf::internal::GeneratedMessageReflection( EnvironmentTag_descriptor_, EnvironmentTag::default_instance_, EnvironmentTag_offsets_, GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(EnvironmentTag, _has_bits_[0]), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(EnvironmentTag, _unknown_fields_), -1, ::google::protobuf::DescriptorPool::generated_pool(), ::google::protobuf::MessageFactory::generated_factory(), sizeof(EnvironmentTag)); EnvironmentTag_Versions_descriptor_ = EnvironmentTag_descriptor_->enum_type(0); EnvironmentTag_Devices_descriptor_ = EnvironmentTag_descriptor_->enum_type(1); EnvironmentTag_Languages_descriptor_ = EnvironmentTag_descriptor_->enum_type(2); } namespace { GOOGLE_PROTOBUF_DECLARE_ONCE(protobuf_AssignDescriptors_once_); inline void protobuf_AssignDescriptorsOnce() { ::google::protobuf::GoogleOnceInit(&protobuf_AssignDescriptors_once_, &protobuf_AssignDesc_EnvironmentTag_2eproto); } void protobuf_RegisterTypes(const ::std::string&) { protobuf_AssignDescriptorsOnce(); ::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage( EnvironmentTag_descriptor_, &EnvironmentTag::default_instance()); } } // namespace void protobuf_ShutdownFile_EnvironmentTag_2eproto() { delete EnvironmentTag::default_instance_; delete EnvironmentTag_reflection_; } void protobuf_AddDesc_EnvironmentTag_2eproto() { static bool already_here = false; if (already_here) return; already_here = true; GOOGLE_PROTOBUF_VERIFY_VERSION; ::Medusa::CoreProto::protobuf_AddDesc_Geometry_2eproto(); ::google::protobuf::DescriptorPool::InternalAddGeneratedFile( "\n\024EnvironmentTag.proto\022\020Medusa.CoreProto" "\032\016Geometry.proto\"\276\002\n\016EnvironmentTag\022:\n\007V" "ersion\030\001 \002(\0162).Medusa.CoreProto.Environm" "entTag.Versions\0228\n\006Device\030\002 \002(\0162(.Medusa" ".CoreProto.EnvironmentTag.Devices\022<\n\010Lan" "guage\030\003 \002(\0162*.Medusa.CoreProto.Environme" "ntTag.Languages\"\036\n\010Versions\022\010\n\004main\020\001\022\010\n" "\004free\020\002\"7\n\007Devices\022\006\n\002sd\020\001\022\006\n\002hd\020\002\022\007\n\003hd" "5\020\004\022\010\n\004ipad\020\010\022\t\n\005ipad3\020\020\"\037\n\tLanguages\022\010\n" "\004enus\020\001\022\010\n\004zhcn\020\002", 377); ::google::protobuf::MessageFactory::InternalRegisterGeneratedFile( "EnvironmentTag.proto", &protobuf_RegisterTypes); EnvironmentTag::default_instance_ = new EnvironmentTag(); EnvironmentTag::default_instance_->InitAsDefaultInstance(); ::google::protobuf::internal::OnShutdown(&protobuf_ShutdownFile_EnvironmentTag_2eproto); } // Force AddDescriptors() to be called at static initialization time. struct StaticDescriptorInitializer_EnvironmentTag_2eproto { StaticDescriptorInitializer_EnvironmentTag_2eproto() { protobuf_AddDesc_EnvironmentTag_2eproto(); } } static_descriptor_initializer_EnvironmentTag_2eproto_; // =================================================================== const ::google::protobuf::EnumDescriptor* EnvironmentTag_Versions_descriptor() { protobuf_AssignDescriptorsOnce(); return EnvironmentTag_Versions_descriptor_; } bool EnvironmentTag_Versions_IsValid(int value) { switch(value) { case 1: case 2: return true; default: return false; } } #ifndef _MSC_VER const EnvironmentTag_Versions EnvironmentTag::main; const EnvironmentTag_Versions EnvironmentTag::free; const EnvironmentTag_Versions EnvironmentTag::Versions_MIN; const EnvironmentTag_Versions EnvironmentTag::Versions_MAX; const int EnvironmentTag::Versions_ARRAYSIZE; #endif // _MSC_VER const ::google::protobuf::EnumDescriptor* EnvironmentTag_Devices_descriptor() { protobuf_AssignDescriptorsOnce(); return EnvironmentTag_Devices_descriptor_; } bool EnvironmentTag_Devices_IsValid(int value) { switch(value) { case 1: case 2: case 4: case 8: case 16: return true; default: return false; } } #ifndef _MSC_VER const EnvironmentTag_Devices EnvironmentTag::sd; const EnvironmentTag_Devices EnvironmentTag::hd; const EnvironmentTag_Devices EnvironmentTag::hd5; const EnvironmentTag_Devices EnvironmentTag::ipad; const EnvironmentTag_Devices EnvironmentTag::ipad3; const EnvironmentTag_Devices EnvironmentTag::Devices_MIN; const EnvironmentTag_Devices EnvironmentTag::Devices_MAX; const int EnvironmentTag::Devices_ARRAYSIZE; #endif // _MSC_VER const ::google::protobuf::EnumDescriptor* EnvironmentTag_Languages_descriptor() { protobuf_AssignDescriptorsOnce(); return EnvironmentTag_Languages_descriptor_; } bool EnvironmentTag_Languages_IsValid(int value) { switch(value) { case 1: case 2: return true; default: return false; } } #ifndef _MSC_VER const EnvironmentTag_Languages EnvironmentTag::enus; const EnvironmentTag_Languages EnvironmentTag::zhcn; const EnvironmentTag_Languages EnvironmentTag::Languages_MIN; const EnvironmentTag_Languages EnvironmentTag::Languages_MAX; const int EnvironmentTag::Languages_ARRAYSIZE; #endif // _MSC_VER #ifndef _MSC_VER const int EnvironmentTag::kVersionFieldNumber; const int EnvironmentTag::kDeviceFieldNumber; const int EnvironmentTag::kLanguageFieldNumber; #endif // !_MSC_VER EnvironmentTag::EnvironmentTag() : ::google::protobuf::Message() { SharedCtor(); } void EnvironmentTag::InitAsDefaultInstance() { } EnvironmentTag::EnvironmentTag(const EnvironmentTag& from) : ::google::protobuf::Message() { SharedCtor(); MergeFrom(from); } void EnvironmentTag::SharedCtor() { _cached_size_ = 0; version_ = 1; device_ = 1; language_ = 1; ::memset(_has_bits_, 0, sizeof(_has_bits_)); } EnvironmentTag::~EnvironmentTag() { SharedDtor(); } void EnvironmentTag::SharedDtor() { if (this != default_instance_) { } } void EnvironmentTag::SetCachedSize(int size) const { GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); _cached_size_ = size; GOOGLE_SAFE_CONCURRENT_WRITES_END(); } const ::google::protobuf::Descriptor* EnvironmentTag::descriptor() { protobuf_AssignDescriptorsOnce(); return EnvironmentTag_descriptor_; } const EnvironmentTag& EnvironmentTag::default_instance() { if (default_instance_ == NULL) protobuf_AddDesc_EnvironmentTag_2eproto(); return *default_instance_; } EnvironmentTag* EnvironmentTag::default_instance_ = NULL; EnvironmentTag* EnvironmentTag::New() const { return new EnvironmentTag; } void EnvironmentTag::Clear() { if (_has_bits_[0 / 32] & (0xffu << (0 % 32))) { version_ = 1; device_ = 1; language_ = 1; } ::memset(_has_bits_, 0, sizeof(_has_bits_)); mutable_unknown_fields()->Clear(); } bool EnvironmentTag::MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input) { #define DO_(EXPRESSION) if (!(EXPRESSION)) return false ::google::protobuf::uint32 tag; while ((tag = input->ReadTag()) != 0) { switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { // required .Medusa.CoreProto.EnvironmentTag.Versions Version = 1; case 1: { if (::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == ::google::protobuf::internal::WireFormatLite::WIRETYPE_VARINT) { int value; DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< int, ::google::protobuf::internal::WireFormatLite::TYPE_ENUM>( input, &value))); if (::Medusa::CoreProto::EnvironmentTag_Versions_IsValid(value)) { set_version(static_cast< ::Medusa::CoreProto::EnvironmentTag_Versions >(value)); } else { mutable_unknown_fields()->AddVarint(1, value); } } else { goto handle_uninterpreted; } if (input->ExpectTag(16)) goto parse_Device; break; } // required .Medusa.CoreProto.EnvironmentTag.Devices Device = 2; case 2: { if (::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == ::google::protobuf::internal::WireFormatLite::WIRETYPE_VARINT) { parse_Device: int value; DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< int, ::google::protobuf::internal::WireFormatLite::TYPE_ENUM>( input, &value))); if (::Medusa::CoreProto::EnvironmentTag_Devices_IsValid(value)) { set_device(static_cast< ::Medusa::CoreProto::EnvironmentTag_Devices >(value)); } else { mutable_unknown_fields()->AddVarint(2, value); } } else { goto handle_uninterpreted; } if (input->ExpectTag(24)) goto parse_Language; break; } // required .Medusa.CoreProto.EnvironmentTag.Languages Language = 3; case 3: { if (::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == ::google::protobuf::internal::WireFormatLite::WIRETYPE_VARINT) { parse_Language: int value; DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< int, ::google::protobuf::internal::WireFormatLite::TYPE_ENUM>( input, &value))); if (::Medusa::CoreProto::EnvironmentTag_Languages_IsValid(value)) { set_language(static_cast< ::Medusa::CoreProto::EnvironmentTag_Languages >(value)); } else { mutable_unknown_fields()->AddVarint(3, value); } } else { goto handle_uninterpreted; } if (input->ExpectAtEnd()) return true; break; } default: { handle_uninterpreted: if (::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == ::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) { return true; } DO_(::google::protobuf::internal::WireFormat::SkipField( input, tag, mutable_unknown_fields())); break; } } } return true; #undef DO_ } void EnvironmentTag::SerializeWithCachedSizes( ::google::protobuf::io::CodedOutputStream* output) const { // required .Medusa.CoreProto.EnvironmentTag.Versions Version = 1; if (has_version()) { ::google::protobuf::internal::WireFormatLite::WriteEnum( 1, this->version(), output); } // required .Medusa.CoreProto.EnvironmentTag.Devices Device = 2; if (has_device()) { ::google::protobuf::internal::WireFormatLite::WriteEnum( 2, this->device(), output); } // required .Medusa.CoreProto.EnvironmentTag.Languages Language = 3; if (has_language()) { ::google::protobuf::internal::WireFormatLite::WriteEnum( 3, this->language(), output); } if (!unknown_fields().empty()) { ::google::protobuf::internal::WireFormat::SerializeUnknownFields( unknown_fields(), output); } } ::google::protobuf::uint8* EnvironmentTag::SerializeWithCachedSizesToArray( ::google::protobuf::uint8* target) const { // required .Medusa.CoreProto.EnvironmentTag.Versions Version = 1; if (has_version()) { target = ::google::protobuf::internal::WireFormatLite::WriteEnumToArray( 1, this->version(), target); } // required .Medusa.CoreProto.EnvironmentTag.Devices Device = 2; if (has_device()) { target = ::google::protobuf::internal::WireFormatLite::WriteEnumToArray( 2, this->device(), target); } // required .Medusa.CoreProto.EnvironmentTag.Languages Language = 3; if (has_language()) { target = ::google::protobuf::internal::WireFormatLite::WriteEnumToArray( 3, this->language(), target); } if (!unknown_fields().empty()) { target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray( unknown_fields(), target); } return target; } int EnvironmentTag::ByteSize() const { int total_size = 0; if (_has_bits_[0 / 32] & (0xffu << (0 % 32))) { // required .Medusa.CoreProto.EnvironmentTag.Versions Version = 1; if (has_version()) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::EnumSize(this->version()); } // required .Medusa.CoreProto.EnvironmentTag.Devices Device = 2; if (has_device()) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::EnumSize(this->device()); } // required .Medusa.CoreProto.EnvironmentTag.Languages Language = 3; if (has_language()) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::EnumSize(this->language()); } } if (!unknown_fields().empty()) { total_size += ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize( unknown_fields()); } GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); _cached_size_ = total_size; GOOGLE_SAFE_CONCURRENT_WRITES_END(); return total_size; } void EnvironmentTag::MergeFrom(const ::google::protobuf::Message& from) { GOOGLE_CHECK_NE(&from, this); const EnvironmentTag* source = ::google::protobuf::internal::dynamic_cast_if_available<const EnvironmentTag*>( &from); if (source == NULL) { ::google::protobuf::internal::ReflectionOps::Merge(from, this); } else { MergeFrom(*source); } } void EnvironmentTag::MergeFrom(const EnvironmentTag& from) { GOOGLE_CHECK_NE(&from, this); if (from._has_bits_[0 / 32] & (0xffu << (0 % 32))) { if (from.has_version()) { set_version(from.version()); } if (from.has_device()) { set_device(from.device()); } if (from.has_language()) { set_language(from.language()); } } mutable_unknown_fields()->MergeFrom(from.unknown_fields()); } void EnvironmentTag::CopyFrom(const ::google::protobuf::Message& from) { if (&from == this) return; Clear(); MergeFrom(from); } void EnvironmentTag::CopyFrom(const EnvironmentTag& from) { if (&from == this) return; Clear(); MergeFrom(from); } bool EnvironmentTag::IsInitialized() const { if ((_has_bits_[0] & 0x00000007) != 0x00000007) return false; return true; } void EnvironmentTag::Swap(EnvironmentTag* other) { if (other != this) { std::swap(version_, other->version_); std::swap(device_, other->device_); std::swap(language_, other->language_); std::swap(_has_bits_[0], other->_has_bits_[0]); _unknown_fields_.Swap(&other->_unknown_fields_); std::swap(_cached_size_, other->_cached_size_); } } ::google::protobuf::Metadata EnvironmentTag::GetMetadata() const { protobuf_AssignDescriptorsOnce(); ::google::protobuf::Metadata metadata; metadata.descriptor = EnvironmentTag_descriptor_; metadata.reflection = EnvironmentTag_reflection_; return metadata; } // @@protoc_insertion_point(namespace_scope) } // namespace CoreProto } // namespace Medusa // @@protoc_insertion_point(global_scope)
[ "alkaidlong@outlook.com" ]
alkaidlong@outlook.com
3ce02a2b990f4abc06d091a0b7a3494b48cb8e0c
ab6f0485c5f1fdaea79598a0e41266cfa3b9c918
/Bullseye2016/src/Commands/MoveWheelsOutCommand.h
9937daed7430837fe7019a29d288b3c18468448e
[]
no_license
Bullseye4984/2016
33c698dc054b5352da81f8a21271cfbbf0174c69
3f4b588452b6d9cffb7eb1045d590ea4d5190623
refs/heads/master
2021-01-14T09:36:46.918356
2016-03-07T01:02:32
2016-03-07T01:02:32
47,716,720
0
0
null
null
null
null
UTF-8
C++
false
false
1,139
h
// RobotBuilder Version: 2.0 // // This file was generated by RobotBuilder. It contains sections of // code that are automatically generated and assigned by robotbuilder. // These sections will be updated in the future when you export to // C++ from RobotBuilder. Do not put any code or make any change in // the blocks indicating autogenerated code or it will be lost on an // update. Deleting the comments indicating the section will prevent // it from being updated in the future. #ifndef MoveWheelsOutCommand_H #define MoveWheelsOutCommand_H #include "Commands/Subsystem.h" #include "../Robot.h" /** * * * @author ExampleAuthor */ class MoveWheelsOutCommand: public Command { public: // BEGIN AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=CONSTRUCTOR MoveWheelsOutCommand(); // END AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=CONSTRUCTOR virtual void Initialize(); virtual void Execute(); virtual bool IsFinished(); virtual void End(); virtual void Interrupted(); private: // BEGIN AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=VARIABLES // END AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=VARIABLES }; #endif
[ "nathan@vaniman.com" ]
nathan@vaniman.com
4eb549b0b4785750fb5e7d4a710332af51e3f4c5
d41bd699ca9ba23a656dfb6b673a2a5a377abccb
/App/ARKitRoomModeling/Libraries/libil2cpp/include/codegen/il2cpp-codegen-il2cpp.h
9642413b5955444acd3750c9b1529a1acbe625f0
[]
no_license
adityas/ARKit-RoomModeling
1135e045fb4e0f7645d05df44889355f5da31ba6
4d73853813396b3afd3b7eab25837bf06534efa6
refs/heads/master
2021-08-24T07:44:14.156922
2017-12-08T17:52:57
2017-12-08T17:52:57
113,513,210
3
1
null
null
null
null
UTF-8
C++
false
false
33,796
h
#pragma once #include "il2cpp-codegen-common.h" #include "utils/Il2CppHStringReference.h" #include "utils/RegisterRuntimeInitializeAndCleanup.h" #include "metadata/GenericMethod.h" #include "vm/Array.h" #include "vm/Assembly.h" #include "vm/Atomic.h" #include "vm/CCW.h" #include "vm/Class.h" #include "vm/COM.h" #include "vm/Domain.h" #include "vm/Exception.h" #include "vm/InternalCalls.h" #include "vm/LastError.h" #include "vm/MarshalAlloc.h" #include "vm/MetadataCache.h" #include "vm/Method.h" #include "vm/Object.h" #include "vm/Profiler.h" #include "vm/RCW.h" #include "vm/Reflection.h" #include "vm/Runtime.h" #include "vm/String.h" #include "vm/Thread.h" #include "vm/ThreadPool.h" #include "vm/Type.h" #include "vm/WindowsRuntime.h" #include "vm/ThreadPoolMs.h" #ifdef _MSC_VER #define IL2CPP_DISABLE_OPTIMIZATIONS __pragma(optimize("", off)) #define IL2CPP_ENABLE_OPTIMIZATIONS __pragma(optimize("", on)) #else #define IL2CPP_DISABLE_OPTIMIZATIONS #define IL2CPP_ENABLE_OPTIMIZATIONS #endif struct ProfilerMethodSentry { ProfilerMethodSentry(const RuntimeMethod* method) #if IL2CPP_ENABLE_PROFILER : m_method(method) #endif { #if IL2CPP_ENABLE_PROFILER il2cpp::vm::Profiler::MethodEnter(m_method); #endif } ~ProfilerMethodSentry() { #if IL2CPP_ENABLE_PROFILER il2cpp::vm::Profiler::MethodExit(m_method); #endif } private: const RuntimeMethod* m_method; }; struct StackTraceSentry { StackTraceSentry(const RuntimeMethod* method) : m_method(method) { Il2CppStackFrameInfo frame_info; frame_info.method = method; #if IL2CPP_DEBUGGER_ENABLED frame_info.id = -1; frame_info.il_offset = 0; frame_info.type = FRAME_TYPE_MANAGED; #endif il2cpp::vm::StackTrace::PushFrame(frame_info); } #if IL2CPP_DEBUGGER_ENABLED StackTraceSentry(const RuntimeMethod* method, void* this_ptr, void **params, int32_t params_count, void **locals, int32_t locals_count) : m_method(method) { Il2CppStackFrameInfo frame_info; frame_info.id = -1; frame_info.this_ptr = this_ptr; frame_info.method = method; frame_info.il_offset = 0; frame_info.type = FRAME_TYPE_MANAGED; frame_info.params = params; frame_info.params_count = params_count; frame_info.locals = locals; frame_info.locals_count = locals_count; il2cpp::vm::StackTrace::PushFrame(frame_info); } #endif ~StackTraceSentry() { il2cpp::vm::StackTrace::PopFrame(); } private: const RuntimeMethod* m_method; }; template<typename T> struct Il2CppFakeBox : RuntimeObject { T m_Value; Il2CppFakeBox(RuntimeClass* boxedType, T* value) { klass = boxedType; monitor = NULL; m_Value = *value; } }; // TODO: This file should contain all the functions and type declarations needed for the generated code. // Hopefully, we stop including everything in the generated code and know exactly what dependencies we have. // Note that all parameter and return types should match the generated types not the runtime types. inline void il2cpp_codegen_register(const Il2CppCodeRegistration* const codeRegistration, const Il2CppMetadataRegistration* const metadataRegistration, const Il2CppCodeGenOptions* const codeGenOptions) { il2cpp::vm::MetadataCache::Register(codeRegistration, metadataRegistration, codeGenOptions); } #include "GeneratedCodeGen.h" // type registration inline void* il2cpp_codegen_get_thread_static_data(RuntimeClass* klass) { return il2cpp::vm::Thread::GetThreadStaticData(klass->thread_static_fields_offset); } inline Il2CppCodeGenString* il2cpp_codegen_string_new_wrapper(const char* str) { return (Il2CppCodeGenString*)il2cpp::vm::String::NewWrapper(str); } inline Il2CppCodeGenString* il2cpp_codegen_string_new_utf16(const il2cpp::utils::StringView<Il2CppChar>& str) { return (Il2CppCodeGenString*)il2cpp::vm::String::NewUtf16(str.Str(), static_cast<int32_t>(str.Length())); } inline Il2CppCodeGenType* il2cpp_codegen_type_get_object(const RuntimeType* type) { return (Il2CppCodeGenType*)il2cpp::vm::Reflection::GetTypeObject(type); } inline NORETURN void il2cpp_codegen_raise_exception(Il2CppCodeGenException *ex) { il2cpp::vm::Exception::Raise((RuntimeException*)ex); } inline void il2cpp_codegen_raise_execution_engine_exception_if_method_is_not_found(const RuntimeMethod* method) { il2cpp::vm::Runtime::RaiseExecutionEngineExceptionIfMethodIsNotFound(method); } inline void il2cpp_codegen_raise_execution_engine_exception(const RuntimeMethod* method) { il2cpp::vm::Runtime::AlwaysRaiseExecutionEngineException(method); } inline void il2cpp_codegen_raise_out_of_memory_exception() { il2cpp::vm::Exception::RaiseOutOfMemoryException(); } inline Il2CppCodeGenException* il2cpp_codegen_get_argument_exception(const char* param, const char* msg) { return (Il2CppCodeGenException*)il2cpp::vm::Exception::GetArgumentException(param, msg); } inline Il2CppCodeGenException* il2cpp_codegen_get_argument_null_exception(const char* param) { return (Il2CppCodeGenException*)il2cpp::vm::Exception::GetArgumentNullException(param); } inline Il2CppCodeGenException* il2cpp_codegen_get_overflow_exception() { return (Il2CppCodeGenException*)il2cpp::vm::Exception::GetOverflowException("Arithmetic operation resulted in an overflow."); } inline Il2CppCodeGenException* il2cpp_codegen_get_not_supported_exception(const char* msg) { return (Il2CppCodeGenException*)il2cpp::vm::Exception::GetNotSupportedException(msg); } inline Il2CppCodeGenException* il2cpp_codegen_get_array_type_mismatch_exception() { return (Il2CppCodeGenException*)il2cpp::vm::Exception::GetArrayTypeMismatchException(); } inline Il2CppCodeGenException* il2cpp_codegen_get_invalid_cast_exception(const char* msg) { return (Il2CppCodeGenException*)il2cpp::vm::Exception::GetInvalidCastException(msg); } inline Il2CppCodeGenException* il2cpp_codegen_get_invalid_operation_exception(const char* msg) { return (Il2CppCodeGenException*)il2cpp::vm::Exception::GetInvalidOperationException(msg); } inline Il2CppCodeGenException* il2cpp_codegen_get_marshal_directive_exception(const char* msg) { return (Il2CppCodeGenException*)il2cpp::vm::Exception::GetMarshalDirectiveException(msg); } inline Il2CppCodeGenException* il2cpp_codegen_get_missing_method_exception(const char* msg) { return (Il2CppCodeGenException*)il2cpp::vm::Exception::GetMissingMethodException(msg); } inline Il2CppCodeGenException* il2cpp_codegen_get_maximum_nested_generics_exception() { return (Il2CppCodeGenException*)il2cpp::vm::Exception::GetMaxmimumNestedGenericsException(); } inline RuntimeClass* il2cpp_codegen_object_class(RuntimeObject* obj) { return obj->klass; } // OpCode.IsInst inline RuntimeObject* IsInst(RuntimeObject *obj, RuntimeClass* targetType) { return il2cpp::vm::Object::IsInst(obj, targetType); } inline RuntimeObject* IsInstSealed(RuntimeObject *obj, RuntimeClass* targetType) { #if IL2CPP_DEBUG IL2CPP_ASSERT((targetType->flags & TYPE_ATTRIBUTE_SEALED) != 0); IL2CPP_ASSERT((targetType->flags & TYPE_ATTRIBUTE_INTERFACE) == 0); #endif if (!obj) return NULL; // optimized version to compare sealed classes return (obj->klass == targetType ? obj : NULL); } inline RuntimeObject* IsInstClass(RuntimeObject *obj, RuntimeClass* targetType) { #if IL2CPP_DEBUG IL2CPP_ASSERT((targetType->flags & TYPE_ATTRIBUTE_INTERFACE) == 0); #endif if (!obj) return NULL; // optimized version to compare classes return il2cpp::vm::Class::HasParentUnsafe(obj->klass, targetType) ? obj : NULL; } // OpCode.Castclass NORETURN inline void RaiseInvalidCastException(RuntimeObject* obj, RuntimeClass* targetType) { std::string exceptionMessage = il2cpp::utils::Exception::FormatInvalidCastException(obj->klass->element_class, targetType); RuntimeException* exception = il2cpp::vm::Exception::GetInvalidCastException(exceptionMessage.c_str()); il2cpp::vm::Exception::Raise(exception); } inline RuntimeObject* Castclass(RuntimeObject *obj, RuntimeClass* targetType) { if (!obj) return NULL; RuntimeObject* result = il2cpp::vm::Object::IsInst(obj, targetType); if (result) return result; RaiseInvalidCastException(obj, targetType); return NULL; } inline RuntimeObject* CastclassSealed(RuntimeObject *obj, RuntimeClass* targetType) { if (!obj) return NULL; RuntimeObject* result = IsInstSealed(obj, targetType); if (result) return result; RaiseInvalidCastException(obj, targetType); return NULL; } inline RuntimeObject* CastclassClass(RuntimeObject *obj, RuntimeClass* targetType) { if (!obj) return NULL; RuntimeObject* result = IsInstClass(obj, targetType); if (result) return result; RaiseInvalidCastException(obj, targetType); return NULL; } inline void NullCheck(void* this_ptr) { if (this_ptr != NULL) return; il2cpp::vm::Exception::RaiseNullReferenceException(); il2cpp_codegen_no_return(); } // OpCode.Box inline RuntimeObject* Box(RuntimeClass* type, void* data) { return il2cpp::vm::Object::Box(type, data); } // OpCode.UnBox inline void* UnBox(RuntimeObject* obj) { NullCheck(obj); return il2cpp::vm::Object::Unbox(obj); } inline void* UnBox(RuntimeObject* obj, RuntimeClass* expectedBoxedClass) { NullCheck(obj); if (obj->klass->element_class == expectedBoxedClass->element_class) return il2cpp::vm::Object::Unbox(obj); RaiseInvalidCastException(obj, expectedBoxedClass); il2cpp_codegen_no_return(); } inline void UnBoxNullable(RuntimeObject* obj, RuntimeClass* expectedBoxedClass, void* storage) { // We only need to do type checks if obj is not null // Unboxing null nullable is perfectly valid and returns an instance that has no value if (obj != NULL) { if (obj->klass->element_class != expectedBoxedClass->element_class) RaiseInvalidCastException(obj, expectedBoxedClass); } il2cpp::vm::Object::UnboxNullable(obj, expectedBoxedClass, storage); } inline uint32_t il2cpp_codegen_sizeof(RuntimeClass* klass) { if (!klass->valuetype) { return sizeof(void*); } return il2cpp::vm::Class::GetInstanceSize(klass) - sizeof(RuntimeObject); } FORCE_INLINE const VirtualInvokeData& il2cpp_codegen_get_virtual_invoke_data(Il2CppMethodSlot slot, const RuntimeObject* obj) { Assert(slot != 65535 && "il2cpp_codegen_get_virtual_invoke_data got called on a non-virtual method"); return obj->klass->vtable[slot]; } FORCE_INLINE const VirtualInvokeData& il2cpp_codegen_get_interface_invoke_data(Il2CppMethodSlot slot, const RuntimeObject* obj, const RuntimeClass* declaringInterface) { Assert(slot != 65535 && "il2cpp_codegen_get_interface_invoke_data got called on a non-virtual method"); return il2cpp::vm::Class::GetInterfaceInvokeDataFromVTable(obj, declaringInterface, slot); } FORCE_INLINE const RuntimeMethod* il2cpp_codegen_get_generic_virtual_method(const RuntimeMethod* method, const RuntimeObject* obj) { uint16_t slot = method->slot; const RuntimeMethod* methodDefinition = obj->klass->vtable[slot].method; return il2cpp::vm::Runtime::GetGenericVirtualMethod(methodDefinition, method); } FORCE_INLINE void il2cpp_codegen_get_generic_virtual_invoke_data(const RuntimeMethod* method, const RuntimeObject* obj, VirtualInvokeData* invokeData) { const RuntimeMethod* targetRuntimeMethod = il2cpp_codegen_get_generic_virtual_method(method, obj); #if IL2CPP_DEBUG IL2CPP_ASSERT(targetRuntimeMethod); #endif invokeData->methodPtr = targetRuntimeMethod->methodPointer; invokeData->method = targetRuntimeMethod; } FORCE_INLINE const RuntimeMethod* il2cpp_codegen_get_generic_interface_method(const RuntimeMethod* method, const RuntimeObject* obj) { const RuntimeMethod* methodDefinition = il2cpp::vm::Class::GetInterfaceInvokeDataFromVTable(obj, method->declaring_type, method->slot).method; return il2cpp::vm::Runtime::GetGenericVirtualMethod(methodDefinition, method); } FORCE_INLINE void il2cpp_codegen_get_generic_interface_invoke_data(const RuntimeMethod* method, const RuntimeObject* obj, VirtualInvokeData* invokeData) { const RuntimeMethod* targetRuntimeMethod = il2cpp_codegen_get_generic_interface_method(method, obj); #if IL2CPP_DEBUG IL2CPP_ASSERT(targetRuntimeMethod); #endif invokeData->methodPtr = targetRuntimeMethod->methodPointer; invokeData->method = targetRuntimeMethod; } #include "GeneratedVirtualInvokers.h" #include "GeneratedInterfaceInvokers.h" #include "GeneratedGenericVirtualInvokers.h" #include "GeneratedGenericInterfaceInvokers.h" // OpCode.Ldtoken inline Il2CppCodeGenRuntimeTypeHandle LoadTypeToken(const RuntimeType* ptr) { Il2CppCodeGenRuntimeTypeHandle handle; handle.set_value_0(reinterpret_cast<intptr_t>(ptr)); return handle; } inline Il2CppCodeGenRuntimeFieldHandle LoadFieldToken(void* ptr) { Il2CppCodeGenRuntimeFieldHandle handle; handle.set_value_0(reinterpret_cast<intptr_t>(ptr)); return handle; } inline Il2CppCodeGenRuntimeArgumentHandle LoadArgList() { Il2CppCodeGenRuntimeArgumentHandle handle; handle.set_args_0(0); IL2CPP_ASSERT(false && "__arglist usage not supported."); return handle; } inline Il2CppCodeGenRuntimeMethodHandle LoadMethodToken(const RuntimeMethod* ptr) { Il2CppCodeGenRuntimeMethodHandle handle; handle.set_value_0(reinterpret_cast<intptr_t>(ptr)); return handle; } inline RuntimeClass* InitializedTypeInfo(RuntimeClass* klass) { il2cpp::vm::Class::Init(klass); return klass; } inline RuntimeClass* il2cpp_codegen_class_from_type(const RuntimeType *type) { return InitializedTypeInfo(il2cpp::vm::Class::FromIl2CppType(type)); } inline void* InterlockedExchangeImplRef(void** location, void* value) { return il2cpp::icalls::mscorlib::System::Threading::Interlocked::ExchangePointer(location, value); } template<typename T> inline T InterlockedCompareExchangeImpl(T* location, T value, T comparand) { return (T)il2cpp::icalls::mscorlib::System::Threading::Interlocked::CompareExchange_T((void**)location, value, comparand); } template<typename T> inline T InterlockedExchangeImpl(T* location, T value) { return (T)InterlockedExchangeImplRef((void**)location, value); } inline void il2cpp_codegen_memory_barrier() { il2cpp::vm::Thread::MemoryBarrier(); } inline void ArrayGetGenericValueImpl(RuntimeArray* thisPtr, int32_t pos, void* value) { memcpy(value, ((uint8_t*)thisPtr) + sizeof(RuntimeArray) + pos * thisPtr->klass->element_size, thisPtr->klass->element_size); } inline void ArraySetGenericValueImpl(RuntimeArray * thisPtr, int32_t pos, void* value) { memcpy(((uint8_t*)thisPtr) + sizeof(RuntimeArray) + pos * thisPtr->klass->element_size, value, thisPtr->klass->element_size); } inline RuntimeArray* SZArrayNew(RuntimeClass* arrayType, uint32_t length) { il2cpp::vm::Class::Init(arrayType); return il2cpp::vm::Array::NewSpecific(arrayType, length); } inline RuntimeArray* GenArrayNew(RuntimeClass* arrayType, il2cpp_array_size_t* dimensions) { return il2cpp::vm::Array::NewFull(arrayType, dimensions, NULL); } // Performance optimization as detailed here: http://blogs.msdn.com/b/clrcodegeneration/archive/2009/08/13/array-bounds-check-elimination-in-the-clr.aspx // Since array size is a signed int32_t, a single unsigned check can be performed to determine if index is less than array size. // Negative indices will map to a unsigned number greater than or equal to 2^31 which is larger than allowed for a valid array. #define IL2CPP_ARRAY_BOUNDS_CHECK(index, length) \ do { \ if (((uint32_t)(index)) >= ((uint32_t)length)) il2cpp::vm::Exception::Raise (il2cpp::vm::Exception::GetIndexOutOfRangeException()); \ } while (0) inline bool il2cpp_codegen_class_is_assignable_from(RuntimeClass *klass, RuntimeClass *oklass) { return il2cpp::vm::Class::IsAssignableFrom(klass, oklass); } inline RuntimeObject* il2cpp_codegen_object_new(RuntimeClass *klass) { return il2cpp::vm::Object::New(klass); } inline Il2CppMethodPointer il2cpp_codegen_resolve_icall(const char* name) { Il2CppMethodPointer method = il2cpp::vm::InternalCalls::Resolve(name); if (!method) { il2cpp::vm::Exception::Raise(il2cpp::vm::Exception::GetMissingMethodException(name)); } return method; } template<typename FunctionPointerType, size_t dynamicLibraryLength, size_t entryPointLength> inline FunctionPointerType il2cpp_codegen_resolve_pinvoke(const Il2CppNativeChar(&nativeDynamicLibrary)[dynamicLibraryLength], const char(&entryPoint)[entryPointLength], Il2CppCallConvention callingConvention, Il2CppCharSet charSet, int parameterSize, bool isNoMangle) { const PInvokeArguments pinvokeArgs = { il2cpp::utils::StringView<Il2CppNativeChar>(nativeDynamicLibrary), il2cpp::utils::StringView<char>(entryPoint), callingConvention, charSet, parameterSize, isNoMangle }; return reinterpret_cast<FunctionPointerType>(il2cpp::vm::PlatformInvoke::Resolve(pinvokeArgs)); } template<typename T> inline T* il2cpp_codegen_marshal_allocate_array(size_t length) { return static_cast<T*>(il2cpp::vm::MarshalAlloc::Allocate((il2cpp_array_size_t)(sizeof(T) * length))); } inline char* il2cpp_codegen_marshal_string(Il2CppCodeGenString* string) { return il2cpp::vm::PlatformInvoke::MarshalCSharpStringToCppString((RuntimeString*)string); } inline void il2cpp_codegen_marshal_string_fixed(Il2CppCodeGenString* string, char* buffer, int numberOfCharacters) { return il2cpp::vm::PlatformInvoke::MarshalCSharpStringToCppStringFixed((RuntimeString*)string, buffer, numberOfCharacters); } inline Il2CppChar* il2cpp_codegen_marshal_wstring(Il2CppCodeGenString* string) { return il2cpp::vm::PlatformInvoke::MarshalCSharpStringToCppWString((RuntimeString*)string); } inline void il2cpp_codegen_marshal_wstring_fixed(Il2CppCodeGenString* string, Il2CppChar* buffer, int numberOfCharacters) { return il2cpp::vm::PlatformInvoke::MarshalCSharpStringToCppWStringFixed((RuntimeString*)string, buffer, numberOfCharacters); } inline Il2CppChar* il2cpp_codegen_marshal_bstring(Il2CppCodeGenString* string) { return il2cpp::vm::PlatformInvoke::MarshalCSharpStringToCppBString((RuntimeString*)string); } inline Il2CppCodeGenString* il2cpp_codegen_marshal_string_result(const char* value) { return (Il2CppCodeGenString*)il2cpp::vm::PlatformInvoke::MarshalCppStringToCSharpStringResult(value); } inline Il2CppCodeGenString* il2cpp_codegen_marshal_wstring_result(const Il2CppChar* value) { return (Il2CppCodeGenString*)il2cpp::vm::PlatformInvoke::MarshalCppWStringToCSharpStringResult(value); } inline Il2CppCodeGenString* il2cpp_codegen_marshal_bstring_result(const Il2CppChar* value) { return (Il2CppCodeGenString*)il2cpp::vm::PlatformInvoke::MarshalCppBStringToCSharpStringResult(value); } inline void il2cpp_codegen_marshal_free_bstring(Il2CppChar* value) { il2cpp::vm::PlatformInvoke::MarshalFreeBString(value); } inline char* il2cpp_codegen_marshal_string_builder(Il2CppCodeGenStringBuilder* stringBuilder) { return il2cpp::vm::PlatformInvoke::MarshalStringBuilder((RuntimeStringBuilder*)stringBuilder); } inline Il2CppChar* il2cpp_codegen_marshal_wstring_builder(Il2CppCodeGenStringBuilder* stringBuilder) { return il2cpp::vm::PlatformInvoke::MarshalWStringBuilder((RuntimeStringBuilder*)stringBuilder); } inline void il2cpp_codegen_marshal_string_builder_result(Il2CppCodeGenStringBuilder* stringBuilder, char* buffer) { il2cpp::vm::PlatformInvoke::MarshalStringBuilderResult((RuntimeStringBuilder*)stringBuilder, buffer); } inline void il2cpp_codegen_marshal_wstring_builder_result(Il2CppCodeGenStringBuilder* stringBuilder, Il2CppChar* buffer) { il2cpp::vm::PlatformInvoke::MarshalWStringBuilderResult((RuntimeStringBuilder*)stringBuilder, buffer); } inline Il2CppHString il2cpp_codegen_create_hstring(Il2CppCodeGenString* str) { return il2cpp::vm::WindowsRuntime::CreateHString(reinterpret_cast<RuntimeString*>(str)); } inline Il2CppCodeGenString* il2cpp_codegen_marshal_hstring_result(Il2CppHString hstring) { return reinterpret_cast<Il2CppCodeGenString*>(il2cpp::vm::WindowsRuntime::HStringToManagedString(hstring)); } inline void il2cpp_codegen_marshal_free_hstring(Il2CppHString hstring) { il2cpp::vm::WindowsRuntime::DeleteHString(hstring); } inline void il2cpp_codegen_marshal_free(void* ptr) { il2cpp::vm::PlatformInvoke::MarshalFree(ptr); } inline Il2CppMethodPointer il2cpp_codegen_marshal_delegate(Il2CppCodeGenMulticastDelegate* d) { return (Il2CppMethodPointer)il2cpp::vm::PlatformInvoke::MarshalDelegate((RuntimeDelegate*)d); } template<typename T> inline T* il2cpp_codegen_marshal_function_ptr_to_delegate(Il2CppMethodPointer functionPtr, RuntimeClass* delegateType) { return (T*)il2cpp::vm::PlatformInvoke::MarshalFunctionPointerToDelegate(reinterpret_cast<void*>(functionPtr), delegateType); } inline void il2cpp_codegen_marshal_store_last_error() { il2cpp::vm::LastError::StoreLastError(); } class il2cpp_native_wrapper_vm_thread_attacher { public: il2cpp_native_wrapper_vm_thread_attacher() : _threadWasAttached(false) { if (il2cpp::vm::Thread::Current() == NULL) { il2cpp::vm::Thread::Attach(il2cpp::vm::Domain::GetRoot()); _threadWasAttached = true; } } ~il2cpp_native_wrapper_vm_thread_attacher() { if (_threadWasAttached) il2cpp::vm::Thread::Detach(il2cpp::vm::Thread::Current()); } private: bool _threadWasAttached; }; #if _DEBUG inline void il2cpp_codegen_check_marshalling_allocations() { if (il2cpp::vm::MarshalAlloc::HasUnfreedAllocations()) il2cpp::vm::Exception::Raise(il2cpp::vm::Exception::GetInvalidOperationException("Error in marshaling allocation. Some memory has been leaked.")); } inline void il2cpp_codegen_clear_all_tracked_marshalling_allocations() { il2cpp::vm::MarshalAlloc::ClearAllTrackedAllocations(); } #endif inline void DivideByZeroCheck(int64_t denominator) { if (denominator != 0) return; il2cpp::vm::Exception::RaiseDivideByZeroException(); il2cpp_codegen_no_return(); } inline void Initobj(RuntimeClass* type, void* data) { if (type->valuetype) memset(data, 0, type->instance_size - sizeof(RuntimeObject)); else *static_cast<RuntimeObject**>(data) = NULL; } inline bool MethodIsStatic(const RuntimeMethod* method) { return !il2cpp::vm::Method::IsInstance(method); } inline bool MethodHasParameters(const RuntimeMethod* method) { return il2cpp::vm::Method::GetParamCount(method) != 0; } #define IL2CPP_RUNTIME_CLASS_INIT(klass) do { if((klass)->has_cctor && !(klass)->cctor_finished) il2cpp::vm::Runtime::ClassInit ((klass)); } while (0) // generic sharing #define IL2CPP_RGCTX_DATA(rgctxVar, index) (InitializedTypeInfo(rgctxVar[index].klass)) #define IL2CPP_RGCTX_SIZEOF(rgctxVar, index) (il2cpp_codegen_sizeof(IL2CPP_RGCTX_DATA(rgctxVar, index))) #define IL2CPP_RGCTX_TYPE(rgctxVar, index) (rgctxVar[index].type) #define IL2CPP_RGCTX_METHOD_INFO(rgctxVar, index) (rgctxVar[index].method) #define IL2CPP_RGCTX_FIELD_INFO(klass, index) ((klass)->fields+index) inline void ArrayElementTypeCheck(RuntimeArray* array, void* value) { if (value != NULL && il2cpp::vm::Object::IsInst((RuntimeObject*)value, array->klass->element_class) == NULL) il2cpp_codegen_raise_exception(il2cpp_codegen_get_array_type_mismatch_exception()); } inline const RuntimeMethod* GetVirtualMethodInfo(RuntimeObject* pThis, Il2CppMethodSlot slot) { if (!pThis) il2cpp::vm::Exception::RaiseNullReferenceException(); return pThis->klass->vtable[slot].method; } inline const RuntimeMethod* GetInterfaceMethodInfo(RuntimeObject* pThis, Il2CppMethodSlot slot, RuntimeClass* declaringInterface) { if (!pThis) il2cpp::vm::Exception::RaiseNullReferenceException(); return il2cpp::vm::Class::GetInterfaceInvokeDataFromVTable(pThis, declaringInterface, slot).method; } inline void il2cpp_codegen_initialize_method(uint32_t index) { il2cpp::vm::MetadataCache::InitializeMethodMetadata(index); } inline bool il2cpp_codegen_type_implements_virtual_method(RuntimeClass* type, const RuntimeMethod* method) { IL2CPP_ASSERT(il2cpp::vm::Class::IsValuetype(type)); return method->declaring_type == type; } inline Il2CppCodeGenMethodBase* il2cpp_codegen_get_method_object(const RuntimeMethod* method) { if (method->is_inflated) method = il2cpp::vm::MetadataCache::GetGenericMethodDefinition(method); return (Il2CppCodeGenMethodBase*)il2cpp::vm::Reflection::GetMethodObject(method, method->declaring_type); } inline Il2CppCodeGenType* il2cpp_codegen_get_type(Il2CppMethodPointer getTypeFunction, Il2CppCodeGenString* typeName, const char* assemblyName) { typedef Il2CppCodeGenType* (*getTypeFuncType)(RuntimeObject*, Il2CppCodeGenString*, const RuntimeMethod*); RuntimeString* assemblyQualifiedTypeName = il2cpp::vm::Type::AppendAssemblyNameIfNecessary((RuntimeString*)typeName, assemblyName); // Try to find the type using a hint about about calling assembly. If it is not found, fall back to calling GetType without the hint. Il2CppCodeGenType* type = ((getTypeFuncType)getTypeFunction)(NULL, (Il2CppCodeGenString*)assemblyQualifiedTypeName, NULL); if (type == NULL) return ((getTypeFuncType)getTypeFunction)(NULL, typeName, NULL); return type; } inline Il2CppCodeGenType* il2cpp_codegen_get_type(Il2CppMethodPointer getTypeFunction, Il2CppCodeGenString* typeName, bool throwOnError, const char* assemblyName) { typedef Il2CppCodeGenType* (*getTypeFuncType)(RuntimeObject*, Il2CppCodeGenString*, bool, const RuntimeMethod*); RuntimeString* assemblyQualifiedTypeName = il2cpp::vm::Type::AppendAssemblyNameIfNecessary((RuntimeString*)typeName, assemblyName); // Try to find the type using a hint about about calling assembly. If it is not found, fall back to calling GetType without the hint. Il2CppCodeGenType* type = ((getTypeFuncType)getTypeFunction)(NULL, (Il2CppCodeGenString*)assemblyQualifiedTypeName, throwOnError, NULL); if (type == NULL) return ((getTypeFuncType)getTypeFunction)(NULL, typeName, throwOnError, NULL); return type; } inline Il2CppCodeGenType* il2cpp_codegen_get_type(Il2CppMethodPointer getTypeFunction, Il2CppCodeGenString* typeName, bool throwOnError, bool ignoreCase, const char* assemblyName) { typedef Il2CppCodeGenType* (*getTypeFuncType)(RuntimeObject*, Il2CppCodeGenString*, bool, bool, const RuntimeMethod*); RuntimeString* assemblyQualifiedTypeName = il2cpp::vm::Type::AppendAssemblyNameIfNecessary((RuntimeString*)typeName, assemblyName); // Try to find the type using a hint about about calling assembly. If it is not found, fall back to calling GetType without the hint. Il2CppCodeGenType* type = ((getTypeFuncType)getTypeFunction)(NULL, (Il2CppCodeGenString*)assemblyQualifiedTypeName, throwOnError, ignoreCase, NULL); if (type == NULL) return ((getTypeFuncType)getTypeFunction)(NULL, typeName, throwOnError, ignoreCase, NULL); return type; } inline Il2CppCodeGenAssembly* il2cpp_codegen_get_executing_assembly(const RuntimeMethod* method) { return (Il2CppCodeGenAssembly*)il2cpp::vm::Reflection::GetAssemblyObject(il2cpp::vm::MetadataCache::GetAssemblyFromIndex(method->declaring_type->image->assemblyIndex)); } // Atomic inline void* il2cpp_codegen_atomic_compare_exchange_pointer(void* volatile* dest, void* exchange, void* comparand) { return il2cpp::vm::Atomic::CompareExchangePointer(dest, exchange, comparand); } template<typename T> inline T* il2cpp_codegen_atomic_compare_exchange_pointer(T* volatile* dest, T* newValue, T* oldValue) { return il2cpp::vm::Atomic::CompareExchangePointer(dest, newValue, oldValue); } // COM inline void il2cpp_codegen_com_marshal_variant(RuntimeObject* obj, Il2CppVariant* variant) { il2cpp::vm::COM::MarshalVariant(obj, variant); } inline RuntimeObject* il2cpp_codegen_com_marshal_variant_result(const Il2CppVariant* variant) { return il2cpp::vm::COM::MarshalVariantResult(variant); } inline void il2cpp_codegen_com_destroy_variant(Il2CppVariant* variant) { il2cpp::vm::COM::DestroyVariant(variant); } inline Il2CppSafeArray* il2cpp_codegen_com_marshal_safe_array(Il2CppChar type, RuntimeArray* managedArray) { return il2cpp::vm::COM::MarshalSafeArray(type, managedArray); } inline RuntimeArray* il2cpp_codegen_com_marshal_safe_array_result(Il2CppChar variantType, RuntimeClass* type, Il2CppSafeArray* safeArray) { return il2cpp::vm::COM::MarshalSafeArrayResult(variantType, type, safeArray); } inline Il2CppSafeArray* il2cpp_codegen_com_marshal_safe_array_bstring(RuntimeArray* managedArray) { return il2cpp::vm::COM::MarshalSafeArrayBString(managedArray); } inline RuntimeArray* il2cpp_codegen_com_marshal_safe_array_bstring_result(RuntimeClass* type, Il2CppSafeArray* safeArray) { return il2cpp::vm::COM::MarshalSafeArrayBStringResult(type, safeArray); } inline void il2cpp_codegen_com_destroy_safe_array(Il2CppSafeArray* safeArray) { il2cpp::vm::COM::DestroySafeArray(safeArray); } inline void il2cpp_codegen_com_create_instance(const Il2CppGuid& clsid, Il2CppIUnknown** identity) { il2cpp::vm::COM::CreateInstance(clsid, identity); } inline void il2cpp_codegen_com_register_rcw(Il2CppComObject* rcw) { il2cpp::vm::RCW::Register(rcw); } template<typename T> inline T* il2cpp_codegen_com_get_or_create_rcw_from_iunknown(Il2CppIUnknown* unknown, RuntimeClass* fallbackClass) { return static_cast<T*>(il2cpp::vm::RCW::GetOrCreateFromIUnknown(unknown, fallbackClass)); } template<typename T> inline T* il2cpp_codegen_com_get_or_create_rcw_from_iinspectable(Il2CppIInspectable* unknown, RuntimeClass* fallbackClass) { return static_cast<T*>(il2cpp::vm::RCW::GetOrCreateFromIInspectable(unknown, fallbackClass)); } template<typename T> inline T* il2cpp_codegen_com_get_or_create_rcw_for_sealed_class(Il2CppIUnknown* unknown, RuntimeClass* objectClass) { return static_cast<T*>(il2cpp::vm::RCW::GetOrCreateForSealedClass(unknown, objectClass)); } inline void il2cpp_codegen_il2cpp_com_object_cleanup(Il2CppComObject* rcw) { il2cpp::vm::RCW::Cleanup(rcw); } template<typename InterfaceType> inline InterfaceType* il2cpp_codegen_com_get_or_create_ccw(RuntimeObject* obj) { return static_cast<InterfaceType*>(il2cpp::vm::CCW::GetOrCreate(obj, InterfaceType::IID)); } inline intptr_t il2cpp_codegen_com_get_iunknown_for_object(RuntimeObject* obj) { return reinterpret_cast<intptr_t>(il2cpp::vm::CCW::GetOrCreate(obj, Il2CppIUnknown::IID)); } inline void il2cpp_codegen_com_raise_exception_if_failed(il2cpp_hresult_t hr, bool defaultToCOMException) { il2cpp::vm::Exception::RaiseIfFailed(hr, defaultToCOMException); } inline RuntimeException* il2cpp_codegen_com_get_exception(il2cpp_hresult_t hr, bool defaultToCOMException) { return il2cpp::vm::Exception::Get(hr, defaultToCOMException); } inline RuntimeException* il2cpp_codegen_com_get_exception_for_invalid_iproperty_cast(RuntimeObject* value, const char* a, const char* b) { return il2cpp::vm::CCW::GetIPropertyValueInvalidCast(value, a, b); } inline void il2cpp_codegen_store_exception_info(RuntimeException* ex, Il2CppCodeGenString* exceptionString) { il2cpp::vm::Exception::StoreExceptionInfo(ex, reinterpret_cast<RuntimeString*>(exceptionString)); } inline Il2CppIActivationFactory* il2cpp_codegen_windows_runtime_get_activation_factory(const il2cpp::utils::StringView<Il2CppNativeChar>& runtimeClassName) { return il2cpp::vm::WindowsRuntime::GetActivationFactory(runtimeClassName); } // delegate inline Il2CppAsyncResult* il2cpp_codegen_delegate_begin_invoke(RuntimeDelegate* delegate, void** params, RuntimeDelegate* asyncCallback, RuntimeObject* state) { #if NET_4_0 return il2cpp::vm::ThreadPoolMs::DelegateBeginInvoke(delegate, params, asyncCallback, state); #else return il2cpp::vm::ThreadPool::Queue(delegate, params, asyncCallback, state); #endif } inline RuntimeObject* il2cpp_codegen_delegate_end_invoke(Il2CppAsyncResult* asyncResult, void **out_args) { #if NET_4_0 return il2cpp::vm::ThreadPoolMs::DelegateEndInvoke(asyncResult, out_args); #else return il2cpp::vm::ThreadPool::Wait(asyncResult, out_args); #endif } inline const Il2CppGenericInst* il2cpp_codegen_get_generic_class_inst(RuntimeClass* genericClass) { IL2CPP_ASSERT(genericClass->generic_class); return genericClass->generic_class->context.class_inst; } inline RuntimeClass* il2cpp_codegen_inflate_generic_class(RuntimeClass* genericClassDefinition, const Il2CppGenericInst* genericInst) { return il2cpp::vm::Class::GetInflatedGenericInstanceClass(genericClassDefinition, genericInst); } inline void* il2cpp_codegen_static_fields_for(RuntimeClass* klass) { return klass->static_fields; } inline Il2CppMethodPointer il2cpp_codegen_get_method_pointer(const RuntimeMethod* method) { return method->methodPointer; } inline const RuntimeType* il2cpp_codegen_method_return_type(const RuntimeMethod* method) { return method->return_type; } inline bool il2cpp_codegen_is_import_or_windows_runtime(const RuntimeObject *object) { return object->klass->is_import_or_windows_runtime; } inline std::string il2cpp_codegen_format_exception(const RuntimeException* ex) { return il2cpp::utils::Exception::FormatException(ex); }
[ "aditya.pyro@gmail.com" ]
aditya.pyro@gmail.com
805e15ba8f931f74c86d91e7f546f92ab752c4ab
ff4871f13f3f83ad22c55b1478abb42cb0a216f0
/Operational-Sudoku/Operational-Sudoku/Operational-Sudoku.cpp
c9fd941590412f0e25da26eab827e88852ecaa1d
[]
no_license
Astro-gram/Programs
81ab645c6ebbb0b08498352bd478fa1850f86a1b
f7e17cf4cf59d9208c54bda642d188e928f6f5db
refs/heads/master
2023-06-16T20:20:20.178925
2021-07-18T01:51:00
2021-07-18T01:51:00
355,695,172
0
0
null
null
null
null
UTF-8
C++
false
false
8,722
cpp
#include <iostream> #include <string> #include <cstdlib> #include <vector> using namespace std; //Random number (1-9) -> (rand() % 9) + 1 void printBoard(int board[9][9]); void printBoardClean(int board[9][9]); void fillBoard(int board[9][9], int form[9][9][2], int values[9]); void createBlanks(int pool[9][9]); int main() { //FORM 1: int cords[9][9][2]; cords[0][0][0] = 0; cords[0][0][1] = 0; cords[0][1][0] = 2; cords[0][1][1] = 4; cords[0][2][0] = 1; cords[0][2][1] = 8; cords[0][3][0] = 5; cords[0][3][1] = 2; cords[0][4][0] = 3; cords[0][4][1] = 5; cords[0][5][0] = 4; cords[0][5][1] = 7; cords[0][6][0] = 6; cords[0][6][1] = 1; cords[0][7][0] = 8; cords[0][7][1] = 3; cords[0][8][0] = 7; cords[0][8][1] = 6; cords[1][0][0] = 0; cords[1][0][1] = 1; cords[1][1][0] = 1; cords[1][1][1] = 4; cords[1][2][0] = 2; cords[1][2][1] = 8; cords[1][3][0] = 4; cords[1][3][1] = 2; cords[1][4][0] = 5; cords[1][4][1] = 5; cords[1][5][0] = 3; cords[1][5][1] = 6; cords[1][6][0] = 8; cords[1][6][1] = 0; cords[1][7][0] = 6; cords[1][7][1] = 3; cords[1][8][0] = 7; cords[1][8][1] = 7; cords[2][0][0] = 0; cords[2][0][1] = 2; cords[2][1][0] = 1; cords[2][1][1] = 5; cords[2][2][0] = 2; cords[2][2][1] = 6; cords[2][3][0] = 4; cords[2][3][1] = 1; cords[2][4][0] = 5; cords[2][4][1] = 4; cords[2][5][0] = 3; cords[2][5][1] = 7; cords[2][6][0] = 6; cords[2][6][1] = 0; cords[2][7][0] = 7; cords[2][7][1] = 3; cords[2][8][0] = 8; cords[2][8][1] = 8; cords[3][0][0] = 1; cords[3][0][1] = 0; cords[3][1][0] = 2; cords[3][1][1] = 5; cords[3][2][0] = 0; cords[3][2][1] = 7; cords[3][3][0] = 3; cords[3][3][1] = 1; cords[3][4][0] = 5; cords[3][4][1] = 3; cords[3][5][0] = 4; cords[3][5][1] = 8; cords[3][6][0] = 8; cords[3][6][1] = 2; cords[3][7][0] = 7; cords[3][7][1] = 4; cords[3][8][0] = 6; cords[3][8][1] = 6; cords[4][0][0] = 1; cords[4][0][1] = 1; cords[4][1][0] = 2; cords[4][1][1] = 3; cords[4][2][0] = 0; cords[4][2][1] = 8; cords[4][3][0] = 5; cords[4][3][1] = 0; cords[4][4][0] = 3; cords[4][4][1] = 4; cords[4][5][0] = 4; cords[4][5][1] = 6; cords[4][6][0] = 6; cords[4][6][1] = 2; cords[4][7][0] = 7; cords[4][7][1] = 5; cords[4][8][0] = 8; cords[4][8][1] = 7; cords[5][0][0] = 1; cords[5][0][1] = 2; cords[5][1][0] = 0; cords[5][1][1] = 4; cords[5][2][0] = 2; cords[5][2][1] = 7; cords[5][3][0] = 3; cords[5][3][1] = 0; cords[5][4][0] = 4; cords[5][4][1] = 3; cords[5][5][0] = 5; cords[5][5][1] = 8; cords[5][6][0] = 7; cords[5][6][1] = 1; cords[5][7][0] = 6; cords[5][7][1] = 5; cords[5][8][0] = 8; cords[5][8][1] = 6; cords[6][0][0] = 2; cords[6][0][1] = 0; cords[6][1][0] = 1; cords[6][1][1] = 3; cords[6][2][0] = 0; cords[6][2][1] = 6; cords[6][3][0] = 3; cords[6][3][1] = 2; cords[6][4][0] = 4; cords[6][4][1] = 5; cords[6][5][0] = 5; cords[6][5][1] = 7; cords[6][6][0] = 8; cords[6][6][1] = 1; cords[6][7][0] = 6; cords[6][7][1] = 4; cords[6][8][0] = 7; cords[6][8][1] = 8; cords[7][0][0] = 2; cords[7][0][1] = 1; cords[7][1][0] = 0; cords[7][1][1] = 5; cords[7][2][0] = 1; cords[7][2][1] = 7; cords[7][3][0] = 4; cords[7][3][1] = 0; cords[7][4][0] = 3; cords[7][4][1] = 3; cords[7][5][0] = 5; cords[7][5][1] = 6; cords[7][6][0] = 7; cords[7][6][1] = 2; cords[7][7][0] = 8; cords[7][7][1] = 4; cords[7][8][0] = 6; cords[7][8][1] = 8; cords[8][0][0] = 2; cords[8][0][1] = 2; cords[8][1][0] = 0; cords[8][1][1] = 3; cords[8][2][0] = 1; cords[8][2][1] = 6; cords[8][3][0] = 5; cords[8][3][1] = 1; cords[8][4][0] = 4; cords[8][4][1] = 4; cords[8][5][0] = 3; cords[8][5][1] = 8; cords[8][6][0] = 7; cords[8][6][1] = 0; cords[8][7][0] = 8; cords[8][7][1] = 5; cords[8][8][0] = 6; cords[8][8][1] = 7; //CODE STARTS HERE srand(time(0)); cout << " -- SUDUKO GAME v1 --\n\n\n"; //Sets all items to 0 int board[9][9]; for (int i = 0; i < 9; i++) { for (int j = 0; j < 9; j++) { board[i][j] = 0; } } int values[9]; vector<int> valPool = { 1, 2, 3, 4, 5, 6, 7, 8, 9 }; for (int i = 0; i < 9; i++) { int randNum = (rand() % valPool.size()); values[i] = valPool[randNum]; valPool.erase(valPool.begin() + randNum); } fillBoard(board, cords, values); printBoard(board); cout << endl; system("pause"); } //FUNCTIONS: void fillBoard(int board[9][9], int form[9][9][2], int values[9]) { for (int i = 0; i < 9; i++) { for (int j = 0; j < 9; j++) { int x = form[i][j][0]; int y = form[i][j][1]; board[x][y] = values[i]; } } } void printBoard(int board[9][9]) { for (int i = 0; i < 9; i++) { for (int j = 0; j < 9; j++) { cout << " " << board[i][j]; if (j == 2 || j == 5) { cout << " |"; } } if (i == 2 || i == 5) cout << "\n ---------------------"; cout << "\n"; } } void createBlanks() { rand() % 9; int orginalBoard; //orginalBoard = board; } void printBoardClean(int board[9][9]) { for (int i = 0; i < 9; i++) { for (int j = 0; j < 9; j++) { cout << board[i][j]; } cout << endl; } } /* for (int i = 0; i < 9; i++) { for (int j = 0; j < 3; j++) { for (int z = 0; z < 3; z++) { cout << " " << (rand() % 9) + 1; } if (j != 2) cout << " |"; } if (i == 2 || i == 5) cout << "\n ---------------------"; cout << "\n"; } cout << "* * * | * * * | * * *\n"; cout << "* * * | * * * | * * *\n"; cout << "* * * | * * * | * * *\n"; cout << "---------------------\n"; cout << "* * * | * * * | * * *\n"; cout << "* * * | * * * | * * *\n"; cout << "* * * | * * * | * * *\n"; cout << "---------------------\n"; cout << "* * * | * * * | * * *\n"; cout << "* * * | * * * | * * *\n"; cout << "* * * | * * * | * * *\n\n"; for (int i = 0; i < 9; i++) { cout << "* * * | * * * | * * *\n"; cout << "-----------------------\n"; } for (int miniBoxRow = 0; miniBoxRow < 3; miniBoxRow++) { for (int miniBoxCol = 0; miniBoxCol < 3; miniBoxCol++) { for (int indBoxRow = 0; indBoxRow < 3; indBoxRow++) { for (int indBoxCol = 0; indBoxCol < 3; indBoxCol++) { printBoardClean(board); cout << "\n\n\n\n"; bool unqNum = false; int randNum; int x = miniBoxRow * 3 + indBoxRow; int y = miniBoxCol * 3 + indBoxCol; while (!unqNum) { randNum = (rand() % 9) + 1; if (randNum == board[x][0] || randNum == board[x][1] || randNum == board[x][2] || randNum == board[x][3] || randNum == board[x][4] || randNum == board[x][5] || randNum == board[x][6] || randNum == board[x][7] || randNum == board[x][8]) continue; if (randNum == board[0][y] || randNum == board[1][y] || randNum == board[2][y] || randNum == board[3][y] || randNum == board[4][y] || randNum == board[5][y] || randNum == board[6][y] || randNum == board[7][y] || randNum == board[8][y]) continue; if (randNum == board[miniBoxRow * 3][miniBoxCol * 3] || randNum == board[miniBoxRow * 3][miniBoxCol * 3 + 1] || randNum == board[miniBoxRow * 3][miniBoxCol * 3 + 2] || randNum == board[miniBoxRow * 3 + 1][miniBoxCol * 3] || randNum == board[miniBoxRow * 3 + 1][miniBoxCol * 3 + 1] || randNum == board[miniBoxRow * 3 + 1][miniBoxCol * 3 + 2] || randNum == board[miniBoxRow * 3 + 2][miniBoxCol * 3] || randNum == board[miniBoxRow * 3 + 2][miniBoxCol * 3 + 1] || randNum == board[miniBoxRow * 3 + 2][miniBoxCol * 3 + 2]) continue; unqNum = true; cout << "test" << endl; } board[x][y] = randNum; } } } int genNum(int board[9][9], int x, int y) { if (x > 8 || x < 0 || y > 8 || y < 0) { return -1; } bool unqNum = false; int miniBoxX = x / 3; int miniBoxY = y / 3; int randNum; while (!unqNum) { randNum = (rand() % 9) + 1; if (randNum == board[x][0] || randNum == board[x][1] || randNum == board[x][2] || randNum == board[x][3] || randNum == board[x][4] || randNum == board[x][5] || randNum == board[x][6] || randNum == board[x][7] || randNum == board[x][8]) continue; if (randNum == board[0][y] || randNum == board[1][y] || randNum == board[2][y] || randNum == board[3][y] || randNum == board[4][y] || randNum == board[5][y] || randNum == board[6][y] || randNum == board[7][y] || randNum == board[8][y]) continue; if (randNum == board[miniBoxX * 3][miniBoxY * 3] || randNum == board[miniBoxX * 3][miniBoxY * 3 + 1] || randNum == board[miniBoxX * 3][miniBoxY * 3 + 2] || randNum == board[miniBoxX * 3 + 1][miniBoxY * 3] || randNum == board[miniBoxX * 3 + 1][miniBoxY * 3 + 1] || randNum == board[miniBoxX * 3 + 1][miniBoxY * 3 + 2] || randNum == board[miniBoxX * 3 + 2][miniBoxY * 3] || randNum == board[miniBoxX * 3 + 2][miniBoxY * 3 + 1] || randNum == board[miniBoxX * 3 + 2][miniBoxY * 3 + 2]) continue; unqNum = true; } return randNum; } }*/
[ "benwebs03@gmail.com" ]
benwebs03@gmail.com
1e41c722e8a6db8989c04d829660891744d14110
9a00bb7fd56cdf83d8717dc595a4e09968faad91
/Composite/Composite.h
af87288420aaf3842ca2da398a837922ca3f0dfe
[]
no_license
duxingheiying/DesignPatterns
541cdac713348bd7f086e8a2acf0399d93b4dc9c
d01ea00e2e966125cea84b1820168e0089074efe
refs/heads/master
2022-01-11T20:55:11.584436
2019-06-17T13:42:37
2019-06-17T13:42:37
188,552,215
1
0
null
null
null
null
UTF-8
C++
false
false
405
h
#ifndef _COMPOSITE_H_ #define _COMPOSITE_H_ #include "Component.h" #include <vector> using namespace std; using namespace std; class Composite : public Component { public: Composite(); ~Composite(); public: void Operation(); void Add(Component * com); void Remove(Component * com); Component * GetChild(int index); protected: private: vector<Component*>comVec; }; #endif // !_COMPOSITE_H_
[ "guweicao@sina.com" ]
guweicao@sina.com
579811ff167ce0eaf0ff7319a64855d205ba9177
aa9c6b23ad708439c2553b2982bef9436c2c99b4
/Source/Tokens/Operators/TOXor.cpp
ae134ed88e03f445880943494ab81b6daf2d5b21
[]
no_license
Y-Less/yavascript
a07ba883380a81c86de2ed14416605b572284d30
4911c182d6b09fd46e67a61d6f080c4a97d0ca3f
refs/heads/master
2021-01-19T07:43:26.120864
2013-06-01T20:07:42
2013-06-01T20:07:42
10,427,721
8
2
null
null
null
null
UTF-8
C++
false
false
1,403
cpp
// ========================================================================= // The contents of this file are subject to the Mozilla Public License // Version 1.1 (the "License"); you may not use this file except in // compliance with the License. You may obtain a copy of the License at // http://www.mozilla.org/MPL/ // // Software distributed under the License is distributed on an "AS IS" // basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the // License for the specific language governing rights and limitations // under the License. // // The Original Code is the yavascript development system - TOXor.cpp. // // The Initial Developer of the Original Code is Alex "Y_Less" Cole. // ========================================================================= #include "TOXor.h" std::ostream & TOXor:: Debug(std::ostream & s) const { // Function to do the addition s << "$Y._xor("; // Parameters GetChild(0).Debug(s); s << ", "; GetChild(1).Debug(s); // End s << ')'; return s; }
[ "alex@y-less.com" ]
alex@y-less.com
df54303a6674e7e0e667db120d925f969c1420f2
b7f3edb5b7c62174bed808079c3b21fb9ea51d52
/chrome/browser/ui/views/frame/browser_non_client_frame_view_factory_chromeos.cc
7243749b7f67f9bd5d38b77fa4d64d97c2c1a872
[ "BSD-3-Clause" ]
permissive
otcshare/chromium-src
26a7372773b53b236784c51677c566dc0ad839e4
64bee65c921db7e78e25d08f1e98da2668b57be5
refs/heads/webml
2023-03-21T03:20:15.377034
2020-11-16T01:40:14
2020-11-16T01:40:14
209,262,645
18
21
BSD-3-Clause
2023-03-23T06:20:07
2019-09-18T08:52:07
null
UTF-8
C++
false
false
562
cc
// Copyright 2017 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/ui/views/frame/browser_non_client_frame_view_ash.h" namespace chrome { std::unique_ptr<BrowserNonClientFrameView> CreateBrowserNonClientFrameView( BrowserFrame* frame, BrowserView* browser_view) { auto frame_view = std::make_unique<BrowserNonClientFrameViewAsh>(frame, browser_view); frame_view->Init(); return frame_view; } } // namespace chrome
[ "commit-bot@chromium.org" ]
commit-bot@chromium.org
b652bf70ceb234d664d25d0cc53487025f81b6c4
2d91b79ab5e8a23cc1c08495d9013174581a5705
/modules/tnm067lab1/processors/imagemappingcpu.cpp
dac0f96336046d2bcc25804c2a10bf05c807c0cd
[]
no_license
jacobmolin/TNM067-SciVis
e005142b81871c6fa869378884fd34552f2fc392
5d4827313ae4f7b660df84f589421898e919e6f4
refs/heads/master
2023-08-22T13:59:39.063269
2021-10-16T17:09:15
2021-10-16T17:09:15
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,340
cpp
#include <modules/tnm067lab1/processors/imagemappingcpu.h> #include <modules/tnm067lab1/utils/scalartocolormapping.h> #include <inviwo/core/common/inviwoapplication.h> #include <inviwo/core/datastructures/image/layerramprecision.h> #include <inviwo/core/util/indexmapper.h> #include <inviwo/core/util/imageramutils.h> namespace inviwo { // The Class Identifier has to be globally unique. Use a reverse DNS naming scheme const ProcessorInfo ImageMappingCPU::processorInfo_{ "org.inviwo.ImageMappingCPU", // Class identifier "Image Mapping CPU", // Display name "TNM067", // Category CodeState::Stable, // Code state Tags::CPU, // Tags }; const ProcessorInfo ImageMappingCPU::getProcessorInfo() const { return processorInfo_; } ImageMappingCPU::ImageMappingCPU() : Processor() , inport_("inport", true) , outport_("outport", false) , numColors_("numColors", "Number of colors", 2, 1, 10) , colors_({FloatVec4Property{"color1", "Color 1", vec4(0, 0, 0, 1), vec4(0, 0, 0, 1), vec4(1)}, FloatVec4Property{"color2", "Color 2", vec4(1), vec4(0, 0, 0, 1), vec4(1)}, FloatVec4Property{"color3", "Color 3", vec4(1), vec4(0, 0, 0, 1), vec4(1)}, FloatVec4Property{"color4", "Color 4", vec4(1), vec4(0, 0, 0, 1), vec4(1)}, FloatVec4Property{"color5", "Color 5", vec4(1), vec4(0, 0, 0, 1), vec4(1)}, FloatVec4Property{"color6", "Color 6", vec4(1), vec4(0, 0, 0, 1), vec4(1)}, FloatVec4Property{"color7", "Color 7", vec4(1), vec4(0, 0, 0, 1), vec4(1)}, FloatVec4Property{"color8", "Color 8", vec4(1), vec4(0, 0, 0, 1), vec4(1)}, FloatVec4Property{"color9", "Color 9", vec4(1), vec4(0, 0, 0, 1), vec4(1)}, FloatVec4Property{"color10", "Color 10", vec4(1), vec4(0, 0, 0, 1), vec4(1)}}) { addPort(inport_); addPort(outport_); addProperty(numColors_); for (auto& c : colors_) { c.setSemantics(PropertySemantics::Color); c.setCurrentStateAsDefault(); addProperty(c); } auto colorVisibility = [&]() { for (size_t i = 0; i < 10; i++) { colors_[i].setVisible(i < numColors_); } }; numColors_.onChange(colorVisibility); colorVisibility(); } void ImageMappingCPU::process() { auto inImg = inport_.getData(); auto img = std::make_shared<Image>(inImg->getDimensions(), DataVec4UInt8::get()); auto outRep = static_cast<LayerRAMPrecision<glm::u8vec4>*>( img->getColorLayer()->getEditableRepresentation<LayerRAM>()); glm::u8vec4* outPixels = outRep->getDataTyped(); util::IndexMapper2D index(inImg->getDimensions()); ScalarToColorMapping map; for (size_t i = 0; i < numColors_.get(); i++) { map.addBaseColors(colors_[i].get()); } inImg->getColorLayer()->getRepresentation<LayerRAM>()->dispatch<void>([&](const auto inRep) { auto inPixels = inRep->getDataTyped(); util::forEachPixelParallel(*inRep, [&](size2_t pos) { auto i = index(pos); float inPixelVal = util::glm_convert_normalized<float>(inPixels[i]); outPixels[i] = map.sample(inPixelVal) * 255.f; }); }); outport_.setData(img); } } // namespace inviwo
[ "jacob.molle.molin@gmail.com" ]
jacob.molle.molin@gmail.com
9ce4e8a7e0ac3b147859076d046307654b4a90d6
f7c673d103a0a7261246dbdde75490f8eed918ab
/source/GameCore/net/SimulatorSettings.h
9c6c09d4216942cb62d41bfd54806d458c228606
[]
no_license
phisn/PixelJumper2
2c69faf83c09136b81befd7a930c19ea0ab521f6
842878cb3e44113cc2753abe889de62921242266
refs/heads/master
2022-11-14T04:44:00.690120
2020-07-06T09:38:38
2020-07-06T09:38:38
277,490,158
0
0
null
2020-07-06T09:38:42
2020-07-06T08:48:52
C++
UTF-8
C++
false
false
90
h
#pragma once namespace Game { struct SimulatorSettings { int maxClients = 128; }; }
[ "phisn@outlook.de" ]
phisn@outlook.de
ddac0628c153628042ad33efaa867e6c3f7335ad
3da8a7affbf570aa8187c7259a7429c07182e373
/unity/Communicator/include/Animal.h
22a5c9386f5ecf5f244ae7c6975b31d6f00e3f3b
[ "MIT" ]
permissive
hagenmek/motion-lab
085c44b50afb71302333fafde6c167b0d0897bf4
f5fbf84aa727626936480f2a486b1dd2a5a13794
refs/heads/master
2023-06-17T09:29:15.684816
2020-09-04T12:14:48
2020-09-04T12:14:48
null
0
0
null
null
null
null
UTF-8
C++
false
false
208
h
#include <string> #include "animallib_Export.h" using namespace std; class Animal { private: string name; public: animallib_EXPORT Animal(string); virtual animallib_EXPORT void print_name(); };
[ "Sondre.Tordal@macgregor.com" ]
Sondre.Tordal@macgregor.com
c876402d3920e77a9c3f9aab5204d21e7286d18d
48654211a8dff5c16cc57ad8cc9d2c495eb83383
/surfaceWater/runCases/RANS_2D/MeshSelection4/5mmX0.5mm/0/nut
c41e18e9688346a754dab9922665fb49890e3377
[ "MIT" ]
permissive
edsaac/bioclogging
6be54e5490ee6b7bed4eb2e89c078148e95e59ef
bd4be9c9bb0adcc094ce4ef45f6066ffde1b825f
refs/heads/master
2023-07-05T02:52:06.077922
2021-08-26T17:10:36
2021-08-26T17:10:36
299,431,688
0
0
MIT
2020-12-30T23:42:03
2020-09-28T21:06:21
C++
UTF-8
C++
false
false
1,132
/*--------------------------------*- C++ -*----------------------------------*\ ========= | \\ / F ield | OpenFOAM: The Open Source CFD Toolbox \\ / O peration | Website: https://openfoam.org \\ / A nd | Version: 7 \\/ M anipulation | \*---------------------------------------------------------------------------*/ FoamFile { version 2.0; format ascii; class volScalarField; location "0"; object nut; } // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // dimensions [0 2 -1 0 0 0 0]; internalField uniform 0; boundaryField { front { type empty; } back { type empty; } right { type cyclicAMI; } left { type cyclicAMI; } top { type calculated; value uniform 0; } bottom { type nutkWallFunction; value uniform 0; } } // ************************************************************************* //
[ "esaavedrac@u.northwestern.edu" ]
esaavedrac@u.northwestern.edu
5d9524ea8105f76ac777522fed904c54729d2c45
102be9b531fc0cad28bb1f938f1858292c0397f4
/src/wcs/esp8266/FB_TCP_Client.cpp
44951a47e682ad0c96144b7627747ad8e13ca6a5
[ "LicenseRef-scancode-other-permissive", "MIT" ]
permissive
sanchirganzorig/Firebase-ESP-Client
76b98a580d9bdfb7383a5eefdbc2037ab63863dc
3076fc6abb70986645ebb9a0c83eac60d3319986
refs/heads/main
2023-09-04T15:01:59.062093
2021-11-23T14:55:50
2021-11-23T14:55:50
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,521
cpp
/** * Firebase TCP Client v1.1.16 * * Created November 23, 2021 * * The MIT License (MIT) * Copyright (c) 2021 K. Suwatchai (Mobizt) * * * Permission is hereby granted, free of charge, to any person returning a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of * the Software, and to permit persons to whom the Software is furnished to do so, * subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifndef FB_TCP_Client_CPP #define FB_TCP_Client_CPP #ifdef ESP8266 #include "FB_TCP_Client.h" FB_TCP_Client::FB_TCP_Client() { } FB_TCP_Client::~FB_TCP_Client() { release(); MBSTRING().swap(_host); MBSTRING().swap(_CAFile); } bool FB_TCP_Client::begin(const char *host, uint16_t port) { if (strcmp(_host.c_str(), host) != 0) mflnChecked = false; _host = host; _port = port; //probe for fragmentation support at the specified size if (!mflnChecked) { fragmentable = _wcs->probeMaxFragmentLength(_host.c_str(), _port, chunkSize); if (fragmentable) { _bsslRxSize = chunkSize; _bsslTxSize = chunkSize; _wcs->setBufferSizes(_bsslRxSize, _bsslTxSize); } mflnChecked = true; } if (!fragmentable) _wcs->setBufferSizes(_bsslRxSize, _bsslTxSize); return true; } bool FB_TCP_Client::connected() { if (_wcs) return (_wcs->connected()); return false; } int FB_TCP_Client::send(const char *data, size_t len) { if (!connect()) return FIREBASE_ERROR_TCP_ERROR_CONNECTION_REFUSED; if (len == 0) len = strlen(data); if (len == 0) return 0; if (_wcs->write((const uint8_t *)data, len) != len) return FIREBASE_ERROR_TCP_ERROR_SEND_PAYLOAD_FAILED; return 0; } WiFiClient *FB_TCP_Client::stream(void) { if (connected()) return _wcs.get(); return nullptr; } bool FB_TCP_Client::connect(void) { if (connected()) { while (_wcs->available() > 0) _wcs->read(); return true; } _wcs->setTimeout(timeout); if (!_wcs->connect(_host.c_str(), _port)) return false; return connected(); } void FB_TCP_Client::release() { if (_wcs) { _wcs->stop(); _wcs.reset(nullptr); _wcs.release(); } if (x509) delete x509; } void FB_TCP_Client::setCACert(const char *caCert) { release(); _wcs = std::unique_ptr<FB_ESP_SSL_CLIENT>(new FB_ESP_SSL_CLIENT()); _wcs->setBufferSizes(_bsslRxSize, _bsslTxSize); if (caCert) { x509 = new X509List(caCert); _wcs->setTrustAnchors(x509); _certType = 1; } else { _wcs->setInsecure(); _certType = 0; } _wcs->setNoDelay(true); } void FB_TCP_Client::setCACertFile(const char *caCertFile, uint8_t storageType, struct fb_esp_sd_config_info_t sd_config) { _sdPin = sd_config.ss; _wcs->setBufferSizes(_bsslRxSize, _bsslTxSize); if (_clockReady && strlen(caCertFile) > 0) { fs::File f; if (storageType == 1) { #if defined FLASH_FS FLASH_FS.begin(); if (FLASH_FS.exists(caCertFile)) f = FLASH_FS.open(caCertFile, "r"); #endif } else if (storageType == 2) { #if defined SD_FS SD_FS.begin(_sdPin); if (SD_FS.exists(caCertFile)) f = SD_FS.open(caCertFile, FILE_READ); #endif } if (f) { size_t len = f.size(); uint8_t *der = new uint8_t[len]; if (f.available()) f.read(der, len); f.close(); _wcs->setTrustAnchors(new X509List(der, len)); delete[] der; } _certType = 2; } _wcs->setNoDelay(true); } #endif /* ESP8266 */ #endif /* FB_TCP_Client_CPP */
[ "k_suwatchai@hotmail.com" ]
k_suwatchai@hotmail.com
57f4cc087d560341095bdce8868a0e605d9a56fa
00f1cfc73ba05f72373fbdfd303f6f34dd3a533e
/JLJlang.m/PublicInterfaces/activemq/connector/openwire/commands/Response.h
749ebdaf1e32aff5690429ace81f9a594a056595
[]
no_license
weltermann17/just-like-java
07c7f6164d636688f9d09cdc8421e51d84fdb25f
6517f1c1015e0b17a023b1b475fcc2f3eed9bade
refs/heads/master
2020-06-06T08:32:13.367694
2014-07-01T21:19:06
2014-07-01T21:19:06
21,002,059
4
0
null
null
null
null
UTF-8
C++
false
false
3,356
h
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef _ACTIVEMQ_CONNECTOR_OPENWIRE_COMMANDS_RESPONSE_H_ #define _ACTIVEMQ_CONNECTOR_OPENWIRE_COMMANDS_RESPONSE_H_ // Turn off warning message for ignored exception specification #ifdef _MSC_VER #pragma warning( disable : 4290 ) #endif #include <activemq/util/Config.h> #include <activemq/connector/openwire/commands/BaseCommand.h> #include <vector> #include <string> namespace activemq{ namespace connector{ namespace openwire{ namespace commands{ /* * * Command and marshaling code for OpenWire format for Response * * * NOTE!: This file is autogenerated - do not modify! * if you need to make a change, please see the Java Classes * in the activemq-openwire-generator module * */ class AMQCPP_API Response : public BaseCommand<transport::Response> { protected: int correlationId; public: const static unsigned char ID_RESPONSE = 30; public: Response(); virtual ~Response(); /** * Get the unique identifier that this object and its own * Marshaller share. * @returns new DataStructure type copy. */ virtual unsigned char getDataStructureType() const; /** * Clone this object and return a new instance that the * caller now owns, this will be an exact copy of this one * @returns new copy of this object. */ virtual Response* cloneDataStructure() const; /** * Copy the contents of the passed object into this object's * members, overwriting any existing data. * @param src - Source Object */ virtual void copyDataStructure( const DataStructure* src ); /** * Returns a string containing the information for this DataStructure * such as its type and value of its elements. * @return formatted string useful for debugging. */ virtual std::string toString() const; /** * Compares the DataStructure passed in to this one, and returns if * they are equivalent. Equivalent here means that they are of the * same type, and that each element of the objects are the same. * @returns true if DataStructure's are Equal. */ virtual bool equals( const DataStructure* value ) const; virtual int getCorrelationId() const; virtual void setCorrelationId( int correlationId ); }; }}}} #endif /*_ACTIVEMQ_CONNECTOR_OPENWIRE_COMMANDS_RESPONSE_H_*/
[ "weltermann17@yahoo.com" ]
weltermann17@yahoo.com
36a4d74baa13fbc232ccbd43e32c615464e95ffc
12f441018818dc2dcb1a8a89bccd946d87e0ac9e
/cppwinrt/winrt/impl/Windows.UI.Composition.Core.1.h
bd49ce20c9819ddaf8085761888434dc9a8de04a
[ "MIT" ]
permissive
dlech/bleak-winrt
cc7dd76fca9453b7415d65a428e22b2cbfe36209
a6c1f3fd073a7b5678304ea6bc08b9b067544320
refs/heads/main
2022-09-12T00:15:01.497572
2022-09-09T22:57:53
2022-09-09T22:57:53
391,440,675
10
1
null
null
null
null
UTF-8
C++
false
false
707
h
// WARNING: Please don't edit this file. It was generated by C++/WinRT v2.0.220608.4 #pragma once #ifndef WINRT_Windows_UI_Composition_Core_1_H #define WINRT_Windows_UI_Composition_Core_1_H #include "winrt/impl/Windows.UI.Composition.Core.0.h" WINRT_EXPORT namespace winrt::Windows::UI::Composition::Core { struct __declspec(empty_bases) ICompositorController : winrt::Windows::Foundation::IInspectable, impl::consume_t<ICompositorController> { ICompositorController(std::nullptr_t = nullptr) noexcept {} ICompositorController(void* ptr, take_ownership_from_abi_t) noexcept : winrt::Windows::Foundation::IInspectable(ptr, take_ownership_from_abi) {} }; } #endif
[ "david@lechnology.com" ]
david@lechnology.com
0c2a0a263036f99f3b13631c0fe5a08f4659c35e
6c673ef312169d6c1ed8377334f30a5d44b5b5c7
/Object-Oriented-Programming-CPP-2016-/hw4/_mainTester.cpp
0bb7ce127492bf6e2d7ea86e4c9a5ae88b1a9fe7
[]
no_license
BurakAkten/GTUCourses
f9cb8bc309f69e9a341093179578b5eaa86ccf2b
f33ae4ab9d979d8c4e7959e144a49852e265134a
refs/heads/master
2021-05-18T13:31:21.913411
2020-03-30T09:49:52
2020-03-30T09:49:52
251,263,626
0
0
null
null
null
null
UTF-8
C++
false
false
2,368
cpp
/* * File:CPUProgram.cpp *Author:Burak AKTEN * * *Created on November 12 in 2016 * * */ #include "requiredIncs.h" int main(int argc, char** argv){ //////////////////////////////////////////////////////////////////////// //command line parameters const char* filename = argv[1]; int option = atoi(argv[2]); //////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////// //Testing class CPUProgram //op [] CPUProgram myCPUProgram(option); myCPUProgram.ReadFile(filename); cout << "***********************************************"<<endl; cout << myCPUProgram[0] << endl; cout << myCPUProgram[myCPUProgram.size() - 1] << endl; cout << "***********************************************"<<endl; //op + cout << ((myCPUProgram + "MOV R1, #45")[myCPUProgram.size() - 1]) << endl; cout << "***********************************************"<<endl; //op += myCPUProgram += "MOV R2, #50"; cout << myCPUProgram[myCPUProgram.size() - 1] << endl; cout << "***********************************************"<<endl; //op + << CPUProgram myOtherCPUProgram(option); myOtherCPUProgram.ReadFile(filename); cout << (myCPUProgram + myOtherCPUProgram) << endl; cout << "***********************************************"<<endl; //op COMP -- cout << (myCPUProgram == myOtherCPUProgram ? "DONE" : "FAIL") << endl; cout << (myCPUProgram <= myOtherCPUProgram ? "DONE" : "FAIL") << endl; cout << (myCPUProgram > myOtherCPUProgram ? "FAIL" : "DONE") << endl; --myOtherCPUProgram; cout << (myCPUProgram != myOtherCPUProgram ? "DONE" : "FAIL") << endl; cout << (myCPUProgram >= myOtherCPUProgram ? "DONE" : "FAIL") << endl; cout << (myCPUProgram < myOtherCPUProgram ? "FAIL" : "DONE") << endl; cout << "***********************************************"<<endl; //op () cout << myCPUProgram(5,10) << endl; cout << "***********************************************"<<endl; //error check myCPUProgram += ""; cout << myCPUProgram[myCPUProgram.size() - 1] << endl; cout << myCPUProgram[myCPUProgram.size()] << endl; cout << "***********************************************"<<endl; ////////////////////////////////////////////////////////////////////////// return 0; }
[ "burak@mondayhero.io" ]
burak@mondayhero.io
ced51d4aa211fe59d86fdc02b2dfdb598b8a8750
998b4f90dc55be48e40f52c2ed7edc4a067ff234
/Reference/ProgrammingI-DYS/C in Taiwan/big number multiplication.cpp
728dffd03a0b0c6cce986c7da11f5bda9824823c
[]
no_license
SYJINTW/ProgrammingII
4fa039e5c788186ddceaef63ec1c6ab7803fdfff
1d74d48136128d50e7492a182130f09d229d41ea
refs/heads/master
2023-02-19T20:00:13.198117
2021-01-20T19:16:43
2021-01-20T19:16:43
303,156,203
1
1
null
null
null
null
WINDOWS-1252
C++
false
false
1,260
cpp
#include <stdio.h> #define BIGINT_WIDTH 4 #define BIGINT_BASE 10000 #define DIGIT_NUM 16 #define NUM_SIZE (DIGIT_NUM/BIGINT_WIDTH) #define ANS_SIZE (NUM_SIZE*2) int main() { int num[NUM_SIZE] = {0}; // store input number (under base 10000) int ans[ANS_SIZE] = {0}; // store answer (under base 10000) char input[DIGIT_NUM]; // store input nunber (under base 10) // input : input 16-digit number to a char array (under base 10) for(int i = 0; i < DIGIT_NUM; i++) scanf("%c", &input[i]); // convert from base 10 to base 10000 for(int d = 0; d < DIGIT_NUM; d++) { int num_idx = (DIGIT_NUM-d-1)/BIGINT_WIDTH; num[num_idx] *= 10; num[num_idx] += input[d]-'0'; } // TODO: multiplication for(int up = 0; up < NUM_SIZE; up++) for(int down = 0; down < NUM_SIZE; down++) ans[up+down] += num[down]*num[up]; // TODO: deal with carry (³B²z¶i¦ì) for(int d = 0; d < ANS_SIZE-1; d++) { ans[d+1]+=ans[d]/10000; ans[d]%=10000; } // print answer printf("%4d", ans[ANS_SIZE-1]); for(int d = ANS_SIZE-2; d >= 0; d--) printf("%04d", ans[d]); printf("\n"); return 0; }
[ "yuanjiun911@outlook.com" ]
yuanjiun911@outlook.com
0d35afbd24fcfd799d2cffd8ef2c39bd645054a1
99d63a0b94026c9b2fd5f809b57d5ab870f6e189
/cli/main.cc
71d8cc732380bfd8fa1b9af4fef50f7eb8c4bf54
[]
no_license
caoimhechaos/libdoozer
c3fcc2b01ecb72143156dbbd53fd585a86d85918
c89c966c8c795917d8284b1f3564e2bdf4d8e957
refs/heads/master
2022-02-21T08:59:18.404304
2013-07-04T23:27:01
2013-07-04T23:28:08
6,252,838
0
0
null
null
null
null
UTF-8
C++
false
false
3,269
cc
/*- * Copyright (c) 2012 Caoimhe Chaos <caoimhechaos@protonmail.com>, * Ancient Solutions. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * THIS SOFTWARE IS PROVIDED BY ANCIENT SOLUTIONS 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 * FOUNDATION OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <QtCore/QString> #include <vector> #include "doozer.h" #include <iostream> #include <stdlib.h> #include "cli/cli.h" doozer::Conn* conn; void usage() { std::cerr << "Each command takes zero or more options and zero or " << "more arguments." << std::endl << "In addition, there are some global options that can be " << "used with any command." << std::endl << "The exit status is 0 on success, 1 for a rev mismatch, " << "and 2 otherwise." << std::endl; exit(1); } int main(int argc, char** argv) { conn = new doozer::Conn(); if (!conn->IsValid()) { doozer::Error* err = conn->GetError(); std::cerr << err->ToString() << std::endl; return 1; } if (!strcmp(argv[1], "add") && argc >= 3) { QString path(argv[2]); add(path); } else if (!strcmp(argv[1], "del") && argc >= 4) { QString path(argv[2]); QString revstr(argv[3]); uint64_t rev = revstr.toLongLong(); del(path, rev); } else if (!strcmp(argv[1], "get") && argc >= 3) { QString path(argv[2]); get(path); } else if (!strcmp(argv[1], "nop")) { nop(); } else if (!strcmp(argv[1], "rev") && argc >= 3) { QString path(argv[2]); rev(path); } else if (!strcmp(argv[1], "set") && argc >= 5) { QString path(argv[2]); QString revstr(argv[3]); QByteArray data(argv[4]); uint64_t rev = revstr.toLongLong(); set(path, rev, data); } else if (!strcmp(argv[1], "stat") && argc >= 3) { QString path(argv[2]); stat(path); } else if (!strcmp(argv[1], "touch") && argc >= 3) { QString path(argv[2]); touch(path); } else if (!strcmp(argv[1], "wait") && argc >= 3) { QString glob(argv[2]); wait(glob); } else if (!strcmp(argv[1], "watch") && argc >= 3) { QString glob(argv[2]); watch(glob); } else usage(); return 0; }
[ "caoimhechaos@protonmail.com" ]
caoimhechaos@protonmail.com
dbd087d75a0ad65302385134479ec8d6e28228cf
cd765439448e35703189a6a833c46a1484a85069
/CustomEngine/Src/SceneManager.h
7607ca396dcc4e819d644dc269aed4a81dc72f25
[]
no_license
AchiraSophathammarungsee/CustomEngine
25bcb02e552f380b27970ceaaa032f478b24af72
18641fbd41a895de7d06b3e46c6ca98542aa070e
refs/heads/master
2023-06-19T21:55:38.758417
2021-07-08T07:25:52
2021-07-08T07:25:52
384,027,117
0
0
null
null
null
null
UTF-8
C++
false
false
430
h
#ifndef SCENEMANAGER_H #define SCENEMANAGER_H #include "Scene.h" class SceneManager { public: static void Init(Scene* newscene); static void Update(); static void Exit(); // Reload current scene static void RefreshScene(); // Load new scene static void LoadScene(Scene* nextscene); static Scene* GetCurrentScene(); private: SceneManager() {}; ~SceneManager() {}; static Scene* CurrentScene; }; #endif
[ "achira@bitegginc.com" ]
achira@bitegginc.com
5b8f925822f51274d771adffab219140f860bf8e
fdbfbcf4d6a0ef6f3c1b600e7b8037eed0f03f9e
/common/drake_marker.h
3658d7a7823ac60f49b6e7dae42638d41810080a
[ "BSD-3-Clause" ]
permissive
RobotLocomotion/drake
4529c397f8424145623dd70665531b5e246749a0
3905758e8e99b0f2332461b1cb630907245e0572
refs/heads/master
2023-08-30T21:45:12.782437
2023-08-30T15:59:07
2023-08-30T15:59:07
16,256,144
2,904
1,270
NOASSERTION
2023-09-14T20:51:30
2014-01-26T16:11:05
C++
UTF-8
C++
false
false
405
h
#pragma once /// @file /// This is an internal (not installed) header. Do not use this outside of /// `find_resource.cc`. namespace drake { namespace internal { // Provides a concrete object to ensure that this marker library is linked. // This returns a simple magic constant to ensure the library was loaded // correctly. int drake_marker_lib_check(); } // namespace internal } // namespace drake
[ "eric.cousineau@tri.global" ]
eric.cousineau@tri.global
f531b9e9a69e2fbd0db9bd01a053152bee302252
bdd6da968f2935d69df5b7e13340f5a30995c73b
/kinectEx/src/testApp.h
7f29a746b3b87aaee947728053ca1f6da42770bf
[]
no_license
astomusic/HCI_OpenFramwork
c17e13d5e9b07daf00b96f9b25db83febc96c601
3277a445d7489a1ab3ec4adf2357c106bd36e621
refs/heads/master
2021-01-01T20:01:27.184755
2014-08-29T11:40:22
2014-08-29T11:40:22
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,219
h
#ifndef _TEST_APP #define _TEST_APP #include "ofxOpenNI.h" #include "ofMain.h" #include "Ball.h" #include "DetectingEffect.h" #include <tr1/array> #define MAX_DEVICES 1 #define MAX_NUMBER_OF_HAND 2 class testApp : public ofBaseApp{ public: void setup(); void update(); void draw(); void exit(); void keyPressed (int key); void keyReleased(int key); void mouseMoved(int x, int y ); void mouseDragged(int x, int y, int button); void mousePressed(int x, int y, int button); void mouseReleased(int x, int y, int button); void windowResized(int w, int h); private: void handEvent(ofxOpenNIHandEvent & event); ofxOpenNI openNIDevice; ofTrueTypeFont verdana; std::tr1::array<DetectingEffect*, MAX_NUMBER_OF_HAND> detectingEffectList; unsigned int detectingEffectIdx; vector<Ball*> balls; vector<Ball*> myhands; int numHands; int numBalls; float spring; float gravity; float friction; float width; float height; void checkCollision(); void checkCollisionWithHand(void); void checkCollisionWithBar(); void checkCollisionMeetHand(void); int countRed(); int countGreen(); }; #endif
[ "astomusic@naver.com" ]
astomusic@naver.com
47e148f90acb9f1d5164edfc5cb44167564fa2e5
c732eff57131f1b67b6bb2d6bb8258e455846792
/OpenCVTest/src/main.cpp
23032073d02ace23496d277462da9df4722f1572
[]
no_license
szhao/szhao-masters_project
bff458b22d9c83d078d9d50b2586a83e36798b98
ccbcdf182c9332b74decbd1b26d3ccf508325133
refs/heads/master
2020-06-04T01:47:33.931378
2011-12-18T22:30:11
2011-12-18T22:30:11
null
0
0
null
null
null
null
UTF-8
C++
false
false
15,484
cpp
/* * main.cpp * * Created on: Aug 17, 2011 * Author: root */ // The short example shows how to use new-style image classes declared in cxcore.hpp. // There is also a very similar matrix class (CvMatrix) - a wrapper for CvMat using namespace std; // OpenCV libraries #include <cv.h> #include <highgui.h> #include <cvaux.h> #include <cxcore.h> using namespace cv; #include <sstream> #include <iostream> #include <fstream> #include <stdio.h> #include <string.h> // OpenKinect libraries #include <libfreenect.h> #include <libfreenect_cv.h> #include <libfreenect_sync.h> #include <vector> #include <cmath> #include <pthread.h> #include <sys/stat.h> #include <sys/types.h> #include <dirent.h> // Some definitions for OpenKinect #define FREENECT_FRAME_W 640 #define FREENECT_FRAME_H 480 #define FREENECT_FRAME_PIX (FREENECT_FRAME_H*FREENECT_FRAME_W) //width*height pixels in the image #define FREENECT_VIDEO_RGB_SIZE (FREENECT_FRAME_PIX*3) //3 bytes per pixel #define FREENECT_DEPTH_11BIT_SIZE (FREENECT_FRAME_PIX*sizeof(uint16_t)) #define CVX_RED CV_RGB(0xff,0x00,0x00) #define CVX_GREEN CV_RGB(0x00,0xff,0x00) #define CVX_BLUE CV_RGB(0x00,0x00,0xff) #define CONTOUR_MATCH_THRESHOLD 2.5 // functions to bridge OpenCV and OpenKinect IplImage *freenect_sync_get_depth_cv(int index){ static IplImage *image = 0; static char *data = 0; if (!image) image = cvCreateImageHeader(cvSize(640,480), 16, 1); unsigned int timestamp; if (freenect_sync_get_depth((void**)&data, &timestamp, index, FREENECT_DEPTH_11BIT)) return NULL; cvSetData(image, data, 640*2); return image; } IplImage *freenect_sync_get_rgb_cv(int index){ static IplImage *image = 0; static char *data = 0; if (!image) image = cvCreateImageHeader(cvSize(640,480), 8, 3); unsigned int timestamp; if (freenect_sync_get_video((void**)&data, &timestamp, index, FREENECT_VIDEO_RGB)) return NULL; cvSetData(image, data, 640*3); return image; } //Builds a colored 8-bit 3 channel image based on depth image IplImage *GlViewColor(IplImage *depth){ static IplImage *image = 0; if (!image) image = cvCreateImage(cvSize(640,480), 8, 3); unsigned char *depth_mid = (unsigned char*)(image->imageData); int i; for (i = 0; i < 640*480; i++) { int lb = ((short *)depth->imageData)[i] % 256; int ub = ((short *)depth->imageData)[i] / 256; switch (ub) { case 0: depth_mid[3*i+2] = 255; depth_mid[3*i+1] = 255-lb; depth_mid[3*i+0] = 255-lb; break; case 1: depth_mid[3*i+2] = 255; depth_mid[3*i+1] = lb; depth_mid[3*i+0] = 0; break; case 2: depth_mid[3*i+2] = 255-lb; depth_mid[3*i+1] = 255; depth_mid[3*i+0] = 0; break; case 3: depth_mid[3*i+2] = 0; depth_mid[3*i+1] = 255; depth_mid[3*i+0] = lb; break; case 4: depth_mid[3*i+2] = 0; depth_mid[3*i+1] = 255-lb; depth_mid[3*i+0] = 255; break; case 5: depth_mid[3*i+2] = 0; depth_mid[3*i+1] = 0; depth_mid[3*i+0] = 255-lb; break; default: depth_mid[3*i+2] = 0; depth_mid[3*i+1] = 0; depth_mid[3*i+0] = 0; break; } } return image; } string convertInt(int number) { if (number == 0) return "0"; string temp=""; string returnvalue=""; while (number>0) { temp+=number%10+48; number/=10; } for (int i=0;i<temp.length();i++) returnvalue+=temp[temp.length()-i-1]; return returnvalue; } // Save the contours on disk. Current implementation is via xml files on file system. future goal is to implement database abstraction void SaveContour(CvSeq* contour[], string objname){ //code to check that the object name is valid i.e. only alpha numeric characters // okay, let's save it, but only the exterior contour, not all the holes ifstream infile; ofstream outfile; string line; string fobjname = ""; string num = ""; infile.open ("./objects/index", ios::in); outfile.open ("./objects/index", ios::app); int highest = 0; while ( getline(infile,line)){ istringstream liness( line ); getline( liness, fobjname, ',' ); getline( liness, num, ',' ); if (fobjname == objname) { int i = atoi(num.c_str()); if (i > highest) highest = i; } } infile.close(); outfile << objname << "," << convertInt(highest+1) <<"\n"; outfile.close(); cout << "Creating database entry for Object " << objname << endl; string objname1="./objects/"+objname+"-"+convertInt(highest+1)+"_1.xml"; string objname2="./objects/"+objname+"-"+convertInt(highest+1)+"_2.xml"; string objname3="./objects/"+objname+"-"+convertInt(highest+1)+"_3.xml"; cvSave(objname1.c_str(), contour[0]); cvSave(objname2.c_str(), contour[0]); cvSave(objname3.c_str(), contour[2]); } // returns the saved contour with the best fit. If this is below the threshold, then null is returned. string FindBestFitContour(CvSeq* seq[]){ CvSeq* topcontour = NULL; string line; string fobjname = ""; string bestobjname = ""; string num = ""; ifstream infile; CvSeq *dbcontour[3]; double diff = 0; double min_diff = CONTOUR_MATCH_THRESHOLD; dbcontour[0] = 0; dbcontour[1] = 0; dbcontour[2] = 0; CvContourTree *treedb1 = NULL; CvContourTree *treecurr1 = NULL; CvContourTree *treedb2 = NULL; CvContourTree *treecurr2 = NULL; CvContourTree *treedb3 = NULL; CvContourTree *treecurr3 = NULL; CvMemStorage *storagedb1 = NULL; CvMemStorage *storagecurr1 = NULL; CvMemStorage *storagedb2 = NULL; CvMemStorage *storagecurr2 = NULL; CvMemStorage *storagedb3 = NULL; CvMemStorage *storagecurr3 = NULL; storagedb1 = cvCreateMemStorage(0); storagedb2 = cvCreateMemStorage(0); storagedb3 = cvCreateMemStorage(0); storagecurr1 = cvCreateMemStorage(0); storagecurr2 = cvCreateMemStorage(0); storagecurr3 = cvCreateMemStorage(0); infile.open ("./objects/index", ios::in); while (getline(infile,line)){ diff = 0; istringstream liness( line ); getline( liness, fobjname, ',' ); getline( liness, num, ',' ); string c1 = "./objects/"+fobjname+"-"+num+"_1.xml"; string c2 = "./objects/"+fobjname+"-"+num+"_2.xml";; string c3 = "./objects/"+fobjname+"-"+num+"_3.xml";; char c1_c[c1.size()]; char c2_c[c2.size()]; char c3_c[c3.size()]; // Let's start loading these files for comparison. First we have to do a little conversion to char[]. for (int a=0;a<=c1.size();a++){ c1_c[a]=c1[a]; } for (int b=0;b<=c1.size();b++){ c2_c[b]=c2[b]; } for (int c=0;c<=c1.size();c++){ c3_c[c]=c3[c]; } // Next we use the cvLoad to load up the contour array and begin computing scores and cre // let's create the contour trees for each of these, and then compalre them // find the maximum over the threshold and try to ID based on a likely object // Okay, let's add up a similarity score on each image. if there is only a few coordinates, // don't bother calculating anything for the level. dbcontour[0] = (CvSeq*) cvLoad(c1_c, storagedb1, 0, 0); if (seq[0]->total < 5 || dbcontour[0]->total < 5 || dbcontour[0] == NULL) { cout << "useless data in currcontour[0]\n"; diff += 1; } else { treedb1 = cvCreateContourTree(dbcontour[0], storagedb1, 0); treecurr1 = cvCreateContourTree(seq[0], storagecurr1, 0); diff += cvMatchContourTrees(treedb1, treecurr1, CV_CONTOUR_TREES_MATCH_I1, CONTOUR_MATCH_THRESHOLD); } dbcontour[1] = (CvSeq*) cvLoad(c2_c, storagedb2, 0, 0); if (seq[1]->total < 5 || dbcontour[1]->total < 5 || dbcontour[1] == NULL) { cout << "useless data in currcontour[1]\n"; diff += 1; } else { treedb2 = cvCreateContourTree(dbcontour[1], storagedb2, 0); treecurr2 = cvCreateContourTree(seq[1], storagecurr2, 0); diff += cvMatchContourTrees(treedb2, treecurr2, CV_CONTOUR_TREES_MATCH_I1, CONTOUR_MATCH_THRESHOLD); } dbcontour[2] = (CvSeq*) cvLoad(c3_c, storagedb3, 0, 0); if (seq[2]->total < 5 || dbcontour[2]->total < 5 || dbcontour[2] == NULL) { cout << "useless data in currcontour[2]\n"; diff += 1; } else { treedb3 = cvCreateContourTree(dbcontour[2], storagedb3, 0); treecurr3 = cvCreateContourTree(seq[2], storagecurr3, 0); diff += cvMatchContourTrees(treedb3, treecurr3, CV_CONTOUR_TREES_MATCH_I1, CONTOUR_MATCH_THRESHOLD); } cout << "Computing score for object " << fobjname << "-" << num << ": " << diff << endl; // okay, this is the most likely match. if (diff < min_diff) { min_diff = diff; bestobjname = fobjname; } } cvClearMemStorage(storagedb1); cvClearMemStorage(storagedb2); cvClearMemStorage(storagedb3); cvClearMemStorage(storagecurr1); cvClearMemStorage(storagecurr2); cvClearMemStorage(storagecurr3); // is the match better than the threshold? if (min_diff > CONTOUR_MATCH_THRESHOLD) cout << "The closest matching object is " << bestobjname << " with a score of " << min_diff << endl; return bestobjname; } // take an image and store identity as contours at various depths by click of space bar int main(int argc, char **argv) { // declare variables IplImage *image = freenect_sync_get_rgb_cv(0); IplImage *depth = freenect_sync_get_depth_cv(0); IplImage *gray_depth = NULL; IplImage *depth1 = NULL; IplImage *depth2 = NULL; IplImage *depth3 = NULL; cvNamedWindow("RGB"); cvNamedWindow("Depth"); cvNamedWindow("Depth1"); cvNamedWindow("Depth2"); cvNamedWindow("Depth3"); CvSeq *currcontour[3]; currcontour[0] = 0; currcontour[1] = 0; currcontour[2] = 0; CvSeq *lastcontour[3]; lastcontour[0] = 0; lastcontour[1] = 0; lastcontour[2] = 0; CvMemStorage *storage1 = NULL; CvMemStorage *storage2 = NULL; CvMemStorage *storage3 = NULL; string objname = ""; string delreply = ""; string isitreply = ""; storage1 = cvCreateMemStorage(0); storage2 = cvCreateMemStorage(0); storage3 = cvCreateMemStorage(0); // initialize gray_depth once so we don't have to keep doing it later in the loop depth = GlViewColor(depth); gray_depth = cvCreateImage(cvGetSize(depth), depth->depth, 1); depth1 = cvCreateImage(cvGetSize(depth), depth->depth, 1); depth2 = cvCreateImage(cvGetSize(depth), depth->depth, 1); depth3 = cvCreateImage(cvGetSize(depth), depth->depth, 1); // if the folder for objects is not created, go ahead and create it struct stat st; if(stat("/tmp",&st) != 0){ if(mkdir("./objects",0777)==-1)//creating a directory { cout << "Error while creating objects directory\n"; exit(1); } } //loop to display video while (1) { //error checking and set up work if (!image) { printf("Error: Kinect not connected?\n"); return -1; } image = freenect_sync_get_rgb_cv(0); cvCvtColor(image, image, CV_RGB2BGR); depth = freenect_sync_get_depth_cv(0); if (!depth) { printf("Error: Kinect not connected?\n"); return -1; } // start working on images and derivative images depth = GlViewColor(depth); cvZero(depth1); cvZero(depth2); cvZero(depth3); //alright, let's gray it out for diagnostics purposes cvCvtColor(depth,gray_depth,CV_BGR2GRAY); cvThreshold (gray_depth, gray_depth, 180, 256, CV_THRESH_TOZERO); // Take 3 contours at different depths. This is roughly 33 inches from the Kinect cvThreshold (gray_depth, depth1, 180, 256, CV_THRESH_TRUNC); cvThreshold (gray_depth, depth2, 190, 256, CV_THRESH_TRUNC); cvThreshold (gray_depth, depth3, 200, 256, CV_THRESH_TRUNC); //Let's find the contours cvFindContours(depth1, storage1, &currcontour[0], sizeof(CvContour), CV_RETR_TREE, CV_CHAIN_APPROX_SIMPLE); cvFindContours(depth2, storage2, &currcontour[1], sizeof(CvContour), CV_RETR_TREE, CV_CHAIN_APPROX_SIMPLE); cvFindContours(depth3, storage3, &currcontour[2], sizeof(CvContour), CV_RETR_TREE, CV_CHAIN_APPROX_SIMPLE); cvZero(depth1); cvZero(depth2); cvZero(depth3); // go ahead and get the largest contour for each, which represents the outline for (currcontour[0]; currcontour[0] != NULL; currcontour[0] = currcontour[0]->h_next){ lastcontour[0] = currcontour[0]; } currcontour[0] = lastcontour[0]; for (currcontour[1]; currcontour[1] != NULL; currcontour[1] = currcontour[1]->h_next){ lastcontour[1] = currcontour[1]; } currcontour[1] = lastcontour[1]; for (currcontour[2]; currcontour[2] != NULL; currcontour[2] = currcontour[2]->h_next){ lastcontour[2] = currcontour[2]; } currcontour[2] = lastcontour[2]; // approximate polygons! currcontour[0] = cvApproxPoly(currcontour[0], sizeof(CvContour), storage1, CV_POLY_APPROX_DP, 5, 0); currcontour[1] = cvApproxPoly(currcontour[1], sizeof(CvContour), storage2, CV_POLY_APPROX_DP, 5, 0); currcontour[2] = cvApproxPoly(currcontour[2], sizeof(CvContour), storage3, CV_POLY_APPROX_DP, 5, 0); //let's draw these cvDrawContours(depth1, currcontour[0], cvScalarAll(255), cvScalarAll(255), 0); cvDrawContours(depth2, currcontour[1], cvScalarAll(255), cvScalarAll(255), 0); cvDrawContours(depth3, currcontour[2], cvScalarAll(255), cvScalarAll(255), 0); cvShowImage("RGB", image); cvShowImage("Depth", gray_depth); cvShowImage("Depth1", depth1); cvShowImage("Depth2", depth2); cvShowImage("Depth3", depth3); char key = cvWaitKey(10); // esc is pressed - exit the program if (key == 27) { cvReleaseImage(&depth1); cvReleaseImage(&depth2); cvReleaseImage(&depth3); cvReleaseImage(&image); cvReleaseImage(&depth); cvReleaseImage(&gray_depth); cvDestroyWindow("RGB"); cvDestroyWindow("Depth"); cvDestroyWindow("Depth1"); cvDestroyWindow("Depth2"); cvDestroyWindow("Depth3"); cvClearMemStorage(storage1); cvClearMemStorage(storage2); cvClearMemStorage(storage3); break; // space bar is pressed - try to recognize the object // If it is an unrecognized object (new object), save its identity } else if (key == 32) { // try to find that object in the database objname = FindBestFitContour(currcontour); // was there a return for objname? if (objname == ""){ cout << "I have no idea what this is. What is this object?" << endl; getline(cin, objname); SaveContour(currcontour, objname); } else { isitreply= ""; while (isitreply != "y" && isitreply != "n"){ cout << "Is it a " << objname <<"? (y/n) \n"; getline(cin, isitreply); // if confirmed, then we're set! If not, let's ask what it actually is and save it if (isitreply == "y") { cout << "woohoo!\n"; } else if (isitreply == "n"){ cout << "Okay, what is it?" << endl; getline(cin, objname); SaveContour(currcontour, objname); } } } // if the delete key is pressed, we'll delete all the saved contour objects } else if (key == 100) { delreply= ""; while (delreply != "y" && delreply != "n"){ cout << "Are you sure you want to delete the Object database? (y/n) \n"; getline(cin, delreply); // if confirmed, delete everything in the directory and create anew if (delreply == "y") { system("rm -r ./objects"); cout << "Objects database has been reset!\n"; if(mkdir("./objects",0777)==-1)//creating a directory { cout << "Error while creating objects directory\n"; exit(1); } } else if (delreply == "n") continue; } } } return 0; }
[ "root@ubuntu" ]
root@ubuntu
73ac7d2a74b6a89217eed97ad42b6333e3996cb3
d9eabbade9e830728d3eb0da32f74be1024f2964
/CFA10060_GUI_Lib.cpp
2e484ea35262430f6d096ada058be34d86ea93ce
[ "Unlicense" ]
permissive
crystalfontz/CFA-10060_Arduino_GUI_Library
d8c509f9aa6e746bbf06a886420c39ccacb1fef3
187ae7ec3db88719f63fbe1fc5e739fac0d94206
refs/heads/master
2016-09-06T21:47:03.785491
2015-09-02T19:00:52
2015-09-02T19:00:52
41,821,681
0
0
null
null
null
null
UTF-8
C++
false
false
10,107
cpp
/********************************************************* Crystalfontz CFA-10060 Arduino Simple GUI Library This library requires that the CFA10060_Lib is installed. Crystalfontz: http://www.crystalfontz.com Library Source: https://github.com/crystalfontz/CFA-10060_Arduino_GUI_Library Distributed under the "Unlicense" software license. See: http://unlicense.org/ **********************************************************/ #include <CFA10060_Lib.h> #include "CFA10060_GUI_Lib.h" /////////////////////////////////////////////////////////////////////////////////////////////////// //See CFA10060_GUI_Lib.h for library settings. /////////////////////////////////////////////////////////////////////////////////////////////////// CFA10060_GUI::CFA10060_GUI(CFA10060 &CFA10060_Lib) { //class initialization display = &CFA10060_Lib; formItemCount = 0; } /////////////////////////////////////////////////////////////////////////////////////////////////// void CFA10060_GUI::newForm(void) { //start a new form formItemCount = 0; } uint8_t CFA10060_GUI::addButton(itemType type, int8_t startX, uint8_t startY, uint8_t width, uint8_t height, CFA10060::Color_t bgColor, CFA10060::Color_t borderColor, CFA10060::Color_t textColor, const char *text) { //add a button to the form if ((type != typeButtonYesNoOkCancel) && (type != typeButtonToggle)) //not a button, return false return 0; if (formItemCount > CFA10060_GUI_MAX_FORM_ITEMS - 1) //already at max inputs, return false return 0; //save the button data formItem[formItemCount].type = type; formItem[formItemCount].x = startX; formItem[formItemCount].y = startY; formItem[formItemCount].w = width; formItem[formItemCount].h = height; formItem[formItemCount].bgColor = bgColor; formItem[formItemCount].borderColor = borderColor; formItem[formItemCount].textColor = textColor; formItem[formItemCount].text = text; formItem[formItemCount].state = stateNone; formItem[formItemCount].value = 0; if (formItem[formItemCount].type == typeButtonToggle) formItem[formItemCount].state = stateToggledOff; //pre-calcs formItem[formItemCount].asx = formItem[formItemCount].x; formItem[formItemCount].asy = formItem[formItemCount].y; formItem[formItemCount].aex = formItem[formItemCount].x + formItem[formItemCount].w; formItem[formItemCount].aey = formItem[formItemCount].y + formItem[formItemCount].h; //done ok formItemCount++; return 1; } uint8_t CFA10060_GUI::addSpinBox( int8_t startX, uint8_t startY, uint8_t width, uint8_t height, CFA10060::Color_t bgColor, CFA10060::Color_t borderColor, CFA10060::Color_t textColor, short startValue, short minValue, short maxValue) { //add a number selection scroll box if (formItemCount > CFA10060_GUI_MAX_FORM_ITEMS - 1) //already at max inputs, return false return 0; //save item data formItem[formItemCount].type = typeSpinBox; formItem[formItemCount].x = startX; formItem[formItemCount].y = startY; formItem[formItemCount].w = width; formItem[formItemCount].h = height; formItem[formItemCount].bgColor = bgColor; formItem[formItemCount].borderColor = borderColor; formItem[formItemCount].textColor = textColor; formItem[formItemCount].min = minValue; formItem[formItemCount].max = maxValue; formItem[formItemCount].state = stateNone; formItem[formItemCount].value = startValue; //pre-calcs formItem[formItemCount].asx = formItem[formItemCount].x + 2; formItem[formItemCount].asy = formItem[formItemCount].y + 2; formItem[formItemCount].aex = formItem[formItemCount].x + formItem[formItemCount].h; formItem[formItemCount].aey = formItem[formItemCount].y + formItem[formItemCount].h - 2; formItem[formItemCount].bsx = formItem[formItemCount].x + formItem[formItemCount].w - formItem[formItemCount].h; formItem[formItemCount].bsy = formItem[formItemCount].y + 2; formItem[formItemCount].bex = formItem[formItemCount].x + formItem[formItemCount].w - 2; formItem[formItemCount].bey = formItem[formItemCount].y + formItem[formItemCount].h - 2; //done ok formItemCount++; return 1; } CFA10060_GUI::itemState CFA10060_GUI::getState(uint8_t item) { //return item state return formItem[item].state; } int CFA10060_GUI::getValue(uint8_t item) { //return item value return formItem[item].value; } void CFA10060_GUI::runForm(void) { //run the form uint8_t cx, cy; CFA10060::Pads_t pads; uint8_t i; uint8_t exit; //draw the form renderForm(); //display the cursor display->cmdLCDCursor(CFA10060::cursorArrowNormal); exit = 0; while(!exit) { //get cursor location display->cmdLCDCursor(cx, cy, pads); //check button/pad state if (pads == CFA10060::Enter) { //enter tapped, check form item bounds for (i = 0; i < formItemCount; i++) { if ((formItem[i].type == typeButtonYesNoOkCancel) || (formItem[i].type == typeButtonToggle)) { //is a button or toggle button if ((formItem[i].asx < cx) && (formItem[i].aex > cx) && (formItem[i].asy < cy) && (formItem[i].aey > cy)) { //in bounds, this button was tapped if (formItem[i].type == typeButtonYesNoOkCancel) { //yes/no/ok/cancel style button, save state and exit form formItem[i].state = stateClicked; formItem[i].value = 1; exit = 1; break; } if (formItem[i].type == typeButtonToggle) { //toggle button, change state and redraw button if (formItem[i].state == stateToggledOn) { formItem[i].state = stateToggledOff; formItem[i].value = 0; } else { formItem[i].state = stateToggledOn; formItem[i].value = 1; } //redraw renderButton(i); } } } if (formItem[i].type == typeSpinBox) { //is a num scroll box if ((formItem[i].asx < cx) && (formItem[i].aex > cx) && (formItem[i].asy < cy) && (formItem[i].aey > cy)) { //in bounds, the -ve button was tapped formItem[i].value--; if (formItem[i].value < formItem[i].min) formItem[i].value = formItem[i].min; //redraw renderSpinBox(i); //change state formItem[i].state = stateClicked; } if ((formItem[i].bsx < cx) && (formItem[i].bex > cx) && (formItem[i].bsy < cy) && (formItem[i].bey > cy)) { //in bounds, the +ve button was tapped formItem[i].value++; if (formItem[i].value > formItem[i].max) formItem[i].value = formItem[i].max; //redraw renderSpinBox(i); //change state formItem[i].state = stateClicked; } } } } //small delay delay(100); } //finished, a button has been pressed //turn off the cursor display->cmdLCDCursor(CFA10060::cursorOff); } uint8_t CFA10060_GUI::renderForm(void) { //render the described form uint8_t i; //render form items for (i = 0; i < formItemCount; i++) switch (formItem[i].type) { case typeButtonYesNoOkCancel: case typeButtonToggle: renderButton(i); break; case typeSpinBox: renderSpinBox(i); break; default: break; } } /////////////////////////////////////////////////////////////////////////////////////////////////// uint8_t CFA10060_GUI::renderButton(uint8_t b) { //render the button uint8_t x, y; uint8_t cr; x = formItem[b].x; y = formItem[b].y; //button box display->cmdSetColor(formItem[b].borderColor, formItem[b].bgColor); display->cmdDrawRoundedRectangle( x, y, formItem[b].aex, formItem[b].aey, 6, CFA10060::drawOutlineAndFilled); //selected/checked circle if (formItem[b].type == typeButtonToggle) { //circle radius if ((formItem[b].w) < (formItem[b].h)) cr = formItem[b].w - 4; else cr = formItem[b].h - 4; cr = cr / 2; //draw circle if (formItem[b].state == stateToggledOn) display->cmdSetColor(formItem[b].borderColor, formItem[b].textColor); else display->cmdSetColor(formItem[b].borderColor, formItem[b].bgColor); display->cmdDrawCircle(x + cr + 2, y + cr + 2, cr, CFA10060::drawOutlineAndFilled); //move text over x += cr + 4; } //text center x += (formItem[b].w - (strlen(formItem[b].text) * 8)) / 2; y += (formItem[b].h - 8) / 2; //draw text display->cmdSetColor( formItem[b].textColor.R, formItem[b].textColor.G, formItem[b].textColor.B, 0, 0, 0); display->cmdDrawText(x,y, (char*)formItem[b].text, CFA10060::font8x8, CFA10060::bgTransparent); } uint8_t CFA10060_GUI::renderSpinBox(uint8_t b) { //render the number scroll box char text[6]; //outside box display->cmdSetColor(formItem[b].borderColor, formItem[b].bgColor); display->cmdDrawRoundedRectangle( formItem[b].x, formItem[b].y, formItem[b].x + formItem[b].w, formItem[b].y + formItem[b].h, 6, CFA10060::drawOutlineAndFilled); //button - display->cmdSetColor(formItem[b].textColor, formItem[b].bgColor); display->cmdDrawRoundedRectangle( formItem[b].asx, formItem[b].asy, formItem[b].aex, formItem[b].aey, 3, CFA10060::drawOutlineAndFilled); display->cmdDrawText( formItem[b].asx + (formItem[b].h / 2) - 3, formItem[b].asy + (formItem[b].h / 2) - 6, "-", CFA10060::font8x8, CFA10060::bgTransparent); //button + display->cmdDrawRoundedRectangle( formItem[b].bsx, formItem[b].bsy, formItem[b].bex, formItem[b].bey, 3, CFA10060::drawOutlineAndFilled); display->cmdDrawText( formItem[b].bsx + (formItem[b].h / 2) - 3, formItem[b].bsy + (formItem[b].h / 2) - 6, "+", CFA10060::font8x8, CFA10060::bgTransparent); //number value itoa(formItem[b].value, text, 10); display->cmdSetColor(formItem[b].textColor, formItem[b].bgColor); display->cmdDrawText( formItem[b].x + ((formItem[b].w - strlen(text) * 8) / 2) + 2, formItem[b].y + (formItem[b].h / 2) - 4, text, CFA10060::font8x8, CFA10060::bgTransparent); }
[ "mwp@mwp.id.au" ]
mwp@mwp.id.au
524b09018873cbeb578aad2d15162dc0ae17e797
bdfafb9f2f66f150eba77ecee1b3793b169fbdf7
/ProjectTwo/P2pc/queue.h
91c80bbe5eb6d280bdad637ee714975676dddbc5
[]
no_license
DeWubs/csci21
1b26151b0191a05e047d75a8763d7195707065d4
be8547bc9e7c4f3a5f46a76a8829f5cfdd131ccd
refs/heads/master
2021-09-14T16:18:40.311156
2018-05-16T02:26:31
2018-05-16T02:26:31
118,704,993
0
0
null
null
null
null
UTF-8
C++
false
false
3,445
h
/* queue.h Robert Prouty april 10th 2018 header for a queue */ #include <string> #include <iostream> #include <cstdlib> #include <sstream> #include "node.h" using namespace std; #ifndef QUEUE_H #define QUEUE_H template<typename Type> class Queue{ private: Node <Type>* head_; Node <Type>* tail_; public: /* constructor and destructors for queue */ Queue(){ head_ = NULL; tail_ = NULL; } ~Queue(){ if (head_ != NULL) { clear(); } } /*pushes a value onto the back of the queue @param value */ void push(Type data){ Node<Type>* temp_ptr = new Node<Type>; if (head_ == NULL){ temp_ptr->set_contents(data); head_ = temp_ptr; tail_ = temp_ptr; } else{ temp_ptr->set_contents(data); tail_->set_next_node(temp_ptr); tail_ = temp_ptr; } } /*pops a value off the front queue*/ void pop(){ if (head_ != NULL){ Node<Type>* temp_ptr = head_; if (head_ == tail_){ head_ = NULL; tail_ = NULL; delete temp_ptr; } else{ head_ = temp_ptr->getNextNode(); delete temp_ptr; } } } /*will return a value at a location in the queue @param int index @param return Type*/ Type at(int index){ Node<Type>* temp_ptr = head_; for (int i = 0; i < index; i++){ temp_ptr = temp_ptr->getNextNode(); } return temp_ptr->contents(); } /*will clear the whole queue and reset the head and tail */ void clear(){ Node<Type>* temp_ptr = head_; while (temp_ptr != tail_){ Node<Type>* suc_node = temp_ptr->getNextNode(); delete temp_ptr; temp_ptr = suc_node; } delete temp_ptr; tail_ = NULL; head_ = NULL; } /* * Returns number of items in queue * @return int */ int size(){ int temp_size = 1; Node<Type>* temp_ptr = head_; if (head_ != tail_){ while(temp_ptr != tail_){ temp_size++; temp_ptr = temp_ptr->getNextNode(); } } if (head_ == NULL){ temp_size = 0; } return temp_size; } /* * will return all of the values int he queue front to back * @return string */ string print(){ string output; Node<Type>* temp_ptr = head_; for (int i = 0; i < this->size(); i++) { output += temp_ptr->contents(); output += " "; temp_ptr = temp_ptr->getNextNode(); } output = output.substr(0, output.size() - 1); return output; } }; #endif
[ "rprouty001@student.butte.edu" ]
rprouty001@student.butte.edu
da6b83d1cca14b9b67a5aae3f20414faf528da58
c5bdea6c8688a838527bf48e3b2692186a00daae
/SceneBasedGraphics/VerticalLayout.h
2303a9768245d95a1e77f686e9f492b06e1b939b
[]
no_license
JakeI/GraphicsEngine
546818073008d69914048d7a1d7b93bad02de295
da49943eb3dcae93e307a5226043ef2067018e60
refs/heads/master
2021-01-17T17:11:37.707062
2017-06-19T20:47:34
2017-06-19T20:47:34
68,299,593
0
0
null
null
null
null
UTF-8
C++
false
false
191
h
#pragma once #include "WeightedLayout.h" class VerticalLayout : public WeightedLayout { public: VerticalLayout(); ~VerticalLayout(); void resize(int x, int y, int w, int h) override; };
[ "j.illerhaus@live.de" ]
j.illerhaus@live.de
6d7a623df96ffd6e10296dd80daf9f26fe9cfdde
662e72371dfa5c103aa18afafa5a32df846fdee3
/d3d8/IDirect3D8.cpp
cf4a59e337b236afbe7fcae4e4431f713c17cedc
[ "Zlib" ]
permissive
elishacloud/BloodRayne-2-Patch
345462d67ce744eed8c331490c33b7c35314d527
577f28394934e52776d38236f76dac866db6bdf7
refs/heads/master
2023-03-08T08:35:12.654206
2021-02-25T18:30:13
2021-02-25T18:30:13
111,978,645
17
3
null
null
null
null
UTF-8
C++
false
false
10,370
cpp
/** * Copyright (C) 2020 Elisha Riedlinger * * This software is provided 'as-is', without any express or implied warranty. In no event will the * authors be held liable for any damages arising from the use of this software. * Permission is granted to anyone to use this software for any purpose, including commercial * applications, and to alter it and redistribute it freely, subject to the following restrictions: * * 1. The origin of this software must not be misrepresented; you must not claim that you wrote the * original software. If you use this software in a product, an acknowledgment in the product * documentation would be appreciated but is not required. * 2. Altered source versions must be plainly marked as such, and must not be misrepresented as * being the original software. * 3. This notice may not be removed or altered from any source distribution. */ #include "d3d8.h" HWND DeviceWindow = nullptr; LONG BufferWidth = 0, BufferHeight = 0; HRESULT m_IDirect3D8::QueryInterface(REFIID riid, LPVOID *ppvObj) { Logging::LogDebug() << __FUNCTION__; if ((riid == IID_IDirect3D8 || riid == IID_IUnknown) && ppvObj) { AddRef(); *ppvObj = this; return S_OK; } return ProxyInterface->QueryInterface(riid, ppvObj); } ULONG m_IDirect3D8::AddRef() { Logging::LogDebug() << __FUNCTION__; return ProxyInterface->AddRef(); } ULONG m_IDirect3D8::Release() { Logging::LogDebug() << __FUNCTION__; ULONG count = ProxyInterface->Release(); if (count == 0) { delete this; } return count; } HRESULT m_IDirect3D8::EnumAdapterModes(THIS_ UINT Adapter, UINT Mode, D3DDISPLAYMODE* pMode) { Logging::LogDebug() << __FUNCTION__; return ProxyInterface->EnumAdapterModes(Adapter, Mode, pMode); } UINT m_IDirect3D8::GetAdapterCount() { Logging::LogDebug() << __FUNCTION__; return ProxyInterface->GetAdapterCount(); } HRESULT m_IDirect3D8::GetAdapterDisplayMode(UINT Adapter, D3DDISPLAYMODE *pMode) { Logging::LogDebug() << __FUNCTION__; return ProxyInterface->GetAdapterDisplayMode(Adapter, pMode); } HRESULT m_IDirect3D8::GetAdapterIdentifier(UINT Adapter, DWORD Flags, D3DADAPTER_IDENTIFIER8 *pIdentifier) { Logging::LogDebug() << __FUNCTION__; return ProxyInterface->GetAdapterIdentifier(Adapter, Flags, pIdentifier); } UINT m_IDirect3D8::GetAdapterModeCount(THIS_ UINT Adapter) { Logging::LogDebug() << __FUNCTION__; return ProxyInterface->GetAdapterModeCount(Adapter); } HMONITOR m_IDirect3D8::GetAdapterMonitor(UINT Adapter) { Logging::LogDebug() << __FUNCTION__; return ProxyInterface->GetAdapterMonitor(Adapter); } HRESULT m_IDirect3D8::GetDeviceCaps(UINT Adapter, D3DDEVTYPE DeviceType, D3DCAPS8 *pCaps) { Logging::LogDebug() << __FUNCTION__; return ProxyInterface->GetDeviceCaps(Adapter, DeviceType, pCaps); } HRESULT m_IDirect3D8::RegisterSoftwareDevice(void *pInitializeFunction) { Logging::LogDebug() << __FUNCTION__; return ProxyInterface->RegisterSoftwareDevice(pInitializeFunction); } HRESULT m_IDirect3D8::CheckDepthStencilMatch(UINT Adapter, D3DDEVTYPE DeviceType, D3DFORMAT AdapterFormat, D3DFORMAT RenderTargetFormat, D3DFORMAT DepthStencilFormat) { Logging::LogDebug() << __FUNCTION__; return ProxyInterface->CheckDepthStencilMatch(Adapter, DeviceType, AdapterFormat, RenderTargetFormat, DepthStencilFormat); } HRESULT m_IDirect3D8::CheckDeviceFormat(UINT Adapter, D3DDEVTYPE DeviceType, D3DFORMAT AdapterFormat, DWORD Usage, D3DRESOURCETYPE RType, D3DFORMAT CheckFormat) { Logging::LogDebug() << __FUNCTION__; return ProxyInterface->CheckDeviceFormat(Adapter, DeviceType, AdapterFormat, Usage, RType, CheckFormat); } HRESULT m_IDirect3D8::CheckDeviceMultiSampleType(THIS_ UINT Adapter, D3DDEVTYPE DeviceType, D3DFORMAT SurfaceFormat, BOOL Windowed, D3DMULTISAMPLE_TYPE MultiSampleType) { Logging::LogDebug() << __FUNCTION__; if (FullscreenWndMode) { Windowed = true; } return ProxyInterface->CheckDeviceMultiSampleType(Adapter, DeviceType, SurfaceFormat, Windowed, MultiSampleType); } HRESULT m_IDirect3D8::CheckDeviceType(UINT Adapter, D3DDEVTYPE CheckType, D3DFORMAT DisplayFormat, D3DFORMAT BackBufferFormat, BOOL Windowed) { Logging::LogDebug() << __FUNCTION__; if (FullscreenWndMode) { Windowed = true; } return ProxyInterface->CheckDeviceType(Adapter, CheckType, DisplayFormat, BackBufferFormat, Windowed); } DWORD GetBitCount(D3DFORMAT Format) { switch (Format) { case D3DFMT_UNKNOWN: break; case D3DFMT_R3G3B2: case D3DFMT_A8: case D3DFMT_P8: case D3DFMT_L8: case D3DFMT_A4L4: return 8; case D3DFMT_R5G6B5: case D3DFMT_X1R5G5B5: case D3DFMT_A1R5G5B5: case D3DFMT_A4R4G4B4: case D3DFMT_A8R3G3B2: case D3DFMT_X4R4G4B4: case D3DFMT_A8P8: case D3DFMT_A8L8: case D3DFMT_V8U8: case D3DFMT_L6V5U5: case D3DFMT_D16_LOCKABLE: case D3DFMT_D15S1: case D3DFMT_D16: case D3DFMT_UYVY: case D3DFMT_YUY2: return 16; case D3DFMT_R8G8B8: return 24; case D3DFMT_A8R8G8B8: case D3DFMT_X8R8G8B8: case D3DFMT_A2B10G10R10: case D3DFMT_G16R16: case D3DFMT_X8L8V8U8: case D3DFMT_Q8W8V8U8: case D3DFMT_V16U16: case D3DFMT_A2W10V10U10: case D3DFMT_D32: case D3DFMT_D24S8: case D3DFMT_D24X8: case D3DFMT_D24X4S4: return 32; case D3DFMT_DXT1: case D3DFMT_DXT2: case D3DFMT_DXT3: case D3DFMT_DXT4: break; } LOG_LIMIT(100, __FUNCTION__ << " Display format not Implemented: " << Format); return 0; } HRESULT m_IDirect3D8::CreateDevice(UINT Adapter, D3DDEVTYPE DeviceType, HWND hFocusWindow, DWORD BehaviorFlags, D3DPRESENT_PARAMETERS *pPresentationParameters, IDirect3DDevice8 **ppReturnedDeviceInterface) { Logging::LogDebug() << __FUNCTION__; // Get device information static bool RunOnce = true; if (RunOnce) { RunOnce = false; D3DADAPTER_IDENTIFIER8 dai; if (SUCCEEDED(ProxyInterface->GetAdapterIdentifier(Adapter, 0, &dai))) { Logging::Log() << "|---------- VIDEO CARD ----------"; Logging::Log() << "| " __FUNCTION__ << " Using video card: " << dai.Description << " (" << Logging::hex(dai.VendorId) << ")"; Logging::Log() << "|--------------------------------"; } } // Update presentation parameters UpdatePresentParameter(pPresentationParameters, &hFocusWindow, true); // Set game window to forground SetForegroundWindow(DeviceWindow); HRESULT hr = ProxyInterface->CreateDevice(Adapter, DeviceType, hFocusWindow, BehaviorFlags, pPresentationParameters, ppReturnedDeviceInterface); if (SUCCEEDED(hr) && ppReturnedDeviceInterface) { *ppReturnedDeviceInterface = new m_IDirect3DDevice8(*ppReturnedDeviceInterface, this); } else { Logging::Log() << __FUNCTION__ << " Failed to CreateDevice!"; } return hr; } // Set Presentation Parameters void UpdatePresentParameter(D3DPRESENT_PARAMETERS* pPresentationParameters, HWND *hFocusWindow, bool SetWindow) { if (!pPresentationParameters) { return; } BufferWidth = (pPresentationParameters->BackBufferWidth) ? pPresentationParameters->BackBufferWidth : BufferWidth; BufferHeight = (pPresentationParameters->BackBufferHeight) ? pPresentationParameters->BackBufferHeight : BufferHeight; DeviceWindow = (pPresentationParameters->hDeviceWindow) ? pPresentationParameters->hDeviceWindow : (hFocusWindow && *hFocusWindow) ? *hFocusWindow : DeviceWindow; // Check if window is minimized and restore it if (IsWindow(DeviceWindow) && IsIconic(DeviceWindow)) { ShowWindow(DeviceWindow, SW_RESTORE); } // Set window size if window mode is enabled if (FullscreenWndMode && IsWindow(DeviceWindow)) { pPresentationParameters->Windowed = true; pPresentationParameters->FullScreen_RefreshRateInHz = 0; if (pPresentationParameters->SwapEffect) { pPresentationParameters->FullScreen_PresentationInterval = D3DPRESENT_INTERVAL_DEFAULT; } if (SetWindow) { if (!BufferWidth || !BufferHeight) { RECT tempRect; GetClientRect(DeviceWindow, &tempRect); BufferWidth = tempRect.right; BufferHeight = tempRect.bottom; } if (FullscreenWndMode) { DEVMODE newSettings; ZeroMemory(&newSettings, sizeof(newSettings)); if (EnumDisplaySettings(nullptr, ENUM_CURRENT_SETTINGS, &newSettings) != 0) { newSettings.dmPelsWidth = BufferWidth; newSettings.dmPelsHeight = BufferHeight; newSettings.dmFields = DM_PELSWIDTH | DM_PELSHEIGHT; ChangeDisplaySettings(&newSettings, CDS_FULLSCREEN); } } AdjustWindow(DeviceWindow, BufferWidth, BufferHeight); } } } void GetDesktopRes(LONG &screenWidth, LONG &screenHeight) { HMONITOR monitor = MonitorFromWindow(GetDesktopWindow(), MONITOR_DEFAULTTONEAREST); MONITORINFO info = {}; info.cbSize = sizeof(MONITORINFO); GetMonitorInfo(monitor, &info); screenWidth = info.rcMonitor.right - info.rcMonitor.left; screenHeight = info.rcMonitor.bottom - info.rcMonitor.top; } // Adjusting the window position for WindowMode void AdjustWindow(HWND MainhWnd, LONG displayWidth, LONG displayHeight) { if (!MainhWnd || !displayWidth || !displayHeight) { Logging::Log() << __FUNCTION__ << " Error: could not set window size, nullptr."; return; } // Get screen width and height LONG screenWidth = 0, screenHeight = 0; GetDesktopRes(screenWidth, screenHeight); // Set window active and focus SetActiveWindow(MainhWnd); SetFocus(MainhWnd); // Get window border LONG lStyle = GetWindowLong(MainhWnd, GWL_STYLE) | WS_VISIBLE; if (screenHeight > displayHeight + 32) { lStyle |= WS_OVERLAPPEDWINDOW; } else { lStyle &= ~WS_OVERLAPPEDWINDOW; } // Set window border SetWindowLong(MainhWnd, GWL_STYLE, lStyle); SetWindowPos(MainhWnd, nullptr, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER | SWP_FRAMECHANGED); // Set window size SetWindowPos(MainhWnd, nullptr, 0, 0, displayWidth, displayHeight, SWP_NOMOVE | SWP_NOZORDER); // Adjust for window decoration to ensure client area matches display size RECT tempRect; GetClientRect(MainhWnd, &tempRect); LONG newDisplayWidth = (displayWidth - tempRect.right) + displayWidth; LONG newDisplayHeight = (displayHeight - tempRect.bottom) + displayHeight; // Move window to center and adjust size LONG xLoc = 0; LONG yLoc = 0; if (screenWidth >= newDisplayWidth && screenHeight >= newDisplayHeight) { xLoc = (screenWidth - newDisplayWidth) / 2; yLoc = (screenHeight - newDisplayHeight) / 2; } SetWindowPos(MainhWnd, nullptr, xLoc, yLoc, newDisplayWidth, newDisplayHeight, SWP_NOZORDER); }
[ "elisha@novicemail.com" ]
elisha@novicemail.com
a6121b36b94cd48efcb9bfb27595dead3765df14
234faa2e309d8e90cc47a44eb740a71c3c7ae08b
/include/poly.h
b96fae30af7159d15dee7316a5895e4b63298e5b
[]
no_license
qinjunli1107/Opengl_Mantra
9472b019bc915839d11ab566da4645b5d31f0ec1
7f60f0b2abde068cb1f6c2fe7d634104b4e33179
refs/heads/master
2021-01-13T09:41:37.765483
2011-10-18T20:24:24
2011-10-18T20:24:24
null
0
0
null
null
null
null
UTF-8
C++
false
false
8,680
h
/* * poly.h * * Opengl - utilities relating to polygons that use indexed vertices, employs namespace DR * * Created on: Jun 15, 2010 * Author: drogers */ #ifndef UTIL_H_ #define UTIL_H_ #include <iostream> #include <string> #include <vector> #include "mygl.h" #include "dr_util.h" #include "vec.h" // a namespace for things that might easily clash // may extend this namespace DR { using std::ostream; using std::string; using std::vector; // bidirectional graph edge struct IndexedEdge { GLint u; GLint v; IndexedEdge() {} IndexedEdge(const IndexedEdge& other) { u = other.u; v = other.v; } GLint other_end(GLint vert) { return vert == u ? v : u; } bool operator==(const IndexedEdge& other) const { return (other.u == u && other.v == v) || (other.u == v && other.v == u); } bool operator!=(const IndexedEdge& other) const { return !(*this == other); } string to_string(); bool contains(GLint vert) { return (vert == u || vert == v); } }; // Polygon -- primitive (either quad or triangle) // assumes access to an array somewhere of vec3 vertices and normals // that it indexes class Polygon { friend ostream& operator<<(ostream&, const Polygon&); public: Polygon(); // vertices and normals are the arrays the GLint indices index Polygon(GLint size, vec3 *vertices, vec3 *normals); Polygon(const Polygon& p); virtual ~Polygon(); // assignment makes a deep copy of everything // but actual_verts and actual_norms point to same storage const Polygon& operator=(const Polygon& other); // at this point == compares verts and norms by index // not by actual vertex or normal contents bool operator==(const Polygon& other) const; bool operator!=(const Polygon& other) const { return !(*this == other); } GLint size; GLint *verts; GLint *norms; vec3 facetnorm; // polygons have edges, of course only if you need them .. IndexedEdge *edges; // what the center is depends on the polygon // in the case of irregular quads and triangle, // it's the centroid vec3 center; /** * Length of longest side. Good for various geometric approximations. * Reset whenever resizing. * Called automatically by set_edges, which is called by the winding functions. */ void set_max_side_length(); GLfloat max_side_length; /** * need to call this after vertices are set or modified * base class prints message to stderr */ virtual void set_center() { std::cerr << "Polygon base class set_center() called" << std::endl; } // call after vertices are set or changed, edges follow order of vertices // and connect last back to first void set_edges(); // sets the facet norm, by default uses order of first 3 verts // applying cross product: (v0, v1) X (v1, v2) // supply vertices[3] and above will be used with param vertices[] void set_facetnorm(GLint *vertices=NULL); // ensures that polygon has right handed winding based on the normal // if no normal is passed in, uses first vertex normal ( actual_norms[norms[0]] ) void set_winding_from_normal(GLfloat *normal=NULL); void reverse_winding(); bool contains(GLint vert); bool contains(const IndexedEdge& edge); /** * Note: depends on DR::FLOAT_TOLERANCE */ bool contains(const vec3 actual_vert); // virtual void get_actual_verts(GLfloat **out); // return string representation, if show_edges is true, adds edges virtual string to_string(bool show_edges=false) const; /** * Get a copy of the polys vertices as Vecs to play with. */ void get_actual_verts(vector<Vec>& out) const ; /** * render facet normal using a colored line drawn from the center of the poly * assumes center has been set * param: scale - scale factor multiplied by length of a side to create line length */ void draw_facetnorm(const GLfloat *color, GLfloat scale=2) const; // same as above but for each norm, at the vertex void draw_normals(GLfloat *color, GLfloat scale=2); // set this polygon's pointer to the array holding its vertex normals void set_normals_storage(vec3 *normals_storage) { actual_norms = normals_storage; } virtual void render(GLfloat *color=NULL, bool use_fnorm=true); /** * Disables gl_lighting * wire: draw wireframe * line_sz: if wire, line size [1] */ virtual void render_no_lighting(const GLfloat *color, bool wire=false, GLfloat line_sz=1) const; /** * Returns true if ray intersects this poly. * If found, intersecting point will be put in out. * The ray is defined by a Vec, ray0, and a direction vector, ray_dir * The plane is defined by a Vec, plane0, and its normal, plane_norm * Base class prints error and returns false; */ virtual bool ray_intersect(Vec& out, Vec ray0, Vec ray_dir) const { std::cerr << "Polygon base class ray_intersect() called" << std::endl; return false; } /** * Returns true if a line segment joining points pt1 and pt2 * penetrates this polygon by at least delta (ie 1 point should not * be in the polygon's plane. * If true, intersection point will be in intersection */ bool line_penetrates(const Vec& pt1, const Vec& pt2, GLfloat delta, Vec& intersection) const; /** * RELIES ON FACETNORM BEING SET * Returns true if point is above the plane of this polygon, * with the facetnorm being considered up. */ bool is_above_poly(const Vec& point) const; /** * Init precomputed stuff for ray intersection. * Called by set_edges, so shouldn't have to worry. */ virtual void init_precomputed() { std::cerr << "Polygon base class init_precomputed() called" << std::endl; } /** * precomputed info used in testing if points are in a triangle * quad will use 2 of these */ struct TrianglePrecompute{ GLfloat d; Vec u_beta; Vec u_gamma; }; TrianglePrecompute precomputed; protected: // references to vertex and normal storage vec3 *actual_verts; vec3 *actual_norms; // virtual void render(); }; class Triangle: public Polygon { public: Triangle(vec3 *vertices, vec3 *normals) : Polygon(3, vertices, normals) {} Triangle(const Triangle& t): Polygon(t) {} void set_center(); /** * Returns true if ray intersects this poly. * If found, intersecting point will be put in out. * The ray is defined by a Vec, ray0, and a direction vector, ray_dir */ bool ray_intersect(Vec& out, Vec ray0, Vec ray_dir) const; void init_precomputed(); // return string representation, if show_edges is true, adds edges // prefixes output with "Triangle: " string to_string(bool show_edges=false) const; private: Triangle() {} }; class Quad: public Polygon { public: Quad(vec3 *vertices, vec3 *normals) : Polygon(4, vertices, normals) {} Quad(const Quad& q): Polygon(q) {} void set_center(); /** * Returns true if ray intersects this poly. * If found, intersecting point will be put in out. * The ray is defined by a Vec, ray0, and a direction vector, ray_dir */ bool ray_intersect(Vec& out, Vec ray0, Vec ray_dir) const; void init_precomputed(); // data for a second triangle test for intersections TrianglePrecompute precomputed2; // return string representation, if show_edges is true, adds edges // prefixes output with "Quad: " string to_string(bool show_edges=false) const; private: Quad() {} }; /** * Comparison operator for poly pointers, compares by index verts and facetnorm */ struct PolygonCompare: std::binary_function<const Polygon *, const Polygon *, bool> { bool operator()(const Polygon *lhs, const Polygon *rhs) const; }; // print out vector of polys with indices of vector // set a limit for printing if desired, -1 -> no limit // print_p: print the pointer as well void print_polys(const std::vector<Polygon*>& polys, int limit=-1, bool print_p=false); //*** note these implementations could be done somehow with stl, // but since I'm using pointers, and I don't want to compare pointers // it's a thing // puts the intersection of v1 and v2 in intersect // clears intersect before and removes duplicates from intersect after void intersection(const vector<Polygon*>& v1, const vector<Polygon*>& v2, vector<Polygon*>& intersect); // puts elements of the set difference of v1 and v2 in out void difference(const vector<Polygon*>& v1, const vector<Polygon*>& v2, vector<Polygon*>& out); // removes duplicates from v void uniq(vector<Polygon*>& v); // returns true if v contains p (not pointer, actual poly) bool contains(const vector<Polygon*>& v, const Polygon& p); // todo ** fix this - unnecessary after better acquainted with stl // add all to the back of another vector template<class T> void add_all(const vector<T>& from, vector<T>& to) { copy(from.begin(), from.end(), back_inserter(to)); } } // ** end namespace DR ** #endif /* UTIL_H_ */
[ "dave@drogers.us" ]
dave@drogers.us
ecbc58a11f9533468cf2b16edbaad25b2e3957f1
3149e2e17725eaf95b25e67274e0c7356d2bea0d
/src/noui.cpp
6553553b7191bacf90c489229125b54d60027440
[ "MIT" ]
permissive
Samsufi/GAL
89642a83dba1f4b1c78b14efd471a7d0bf0b9348
d64c4faac60d073d3e86c87ceedf3058dfade6cc
refs/heads/master
2020-03-18T18:06:00.291246
2018-05-27T18:56:08
2018-05-27T18:56:08
135,071,466
0
0
null
null
null
null
UTF-8
C++
false
false
1,587
cpp
// Copyright (c) 2010 Satoshi Nakamoto // Copyright (c) 2009-2014 The Bitcoin developers // Copyright (c) 2014-2015 The Dash developers // Copyright (c) 2015-2017 The GALR developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "noui.h" #include "ui_interface.h" #include "util.h" #include <cstdio> #include <stdint.h> #include <string> static bool noui_ThreadSafeMessageBox(const std::string& message, const std::string& caption, unsigned int style) { bool fSecure = style & CClientUIInterface::SECURE; style &= ~CClientUIInterface::SECURE; std::string strCaption; // Check for usage of predefined caption switch (style) { case CClientUIInterface::MSG_ERROR: strCaption += _("Error"); break; case CClientUIInterface::MSG_WARNING: strCaption += _("Warning"); break; case CClientUIInterface::MSG_INFORMATION: strCaption += _("Information"); break; default: strCaption += caption; // Use supplied caption (can be empty) } if (!fSecure) LogPrintf("%s: %s\n", strCaption, message); fprintf(stderr, "%s: %s\n", strCaption.c_str(), message.c_str()); return false; } static void noui_InitMessage(const std::string& message) { LogPrintf("init message: %s\n", message); } void noui_connect() { // Connect galrd signal handlers uiInterface.ThreadSafeMessageBox.connect(noui_ThreadSafeMessageBox); uiInterface.InitMessage.connect(noui_InitMessage); }
[ "samuel.ly99@gmail.com" ]
samuel.ly99@gmail.com
32f1037b573f41c5aec6203c5210b98f63def59c
2fd82e3038e56451db63128463e70229b3fc84aa
/src/camera.cpp
3ba7c3f692c39a3f417a615866720a7b2662ba54
[]
no_license
RebeccaJohnson926/ray-tracer
7a85ff9f1bd1e2959c3fb49596c46b3d98c916e8
da2aab48b32ea782940948c29780b2a9d19d8e8f
refs/heads/master
2020-08-23T05:37:19.682867
2016-11-12T02:05:32
2016-11-12T02:05:32
73,525,246
0
0
null
null
null
null
UTF-8
C++
false
false
4,024
cpp
// // Rebecca Johnson // CSCE 412 Computer Graphics // Wolff // 5 May 2016 // // File name: camera.cpp // #include "camera.h" #include <glm/glm.hpp> /// <summary> /// Constructs a new Camera object with the given film and field of view. /// The Camera is given a default position and orientation. /// The default position is (0,0,0), looking in the negative z direction, /// with the y-axis defining "up" for the Camera. /// </summary> /// <param name="filmWidth">The width of the film in pixels.</param> /// <param name="filmHeight">The height of the film in pixels.</param> /// <param name="fovy">The vertical field-of-view angle in radians.</param> Camera::Camera( unsigned int filmWidth, unsigned int filmHeight, float fovy ) : film(filmWidth, filmHeight), fovy(fovy), location(0,0,0) { n = glm::vec3( 0, 0, 1 ); u = glm::normalize( glm::cross( glm::vec3( 0, 1, 0 ), n ) ); v = glm::normalize( glm::cross( n, u ) ); } /// <summary> /// Orient this Camera based on the given information. This will update the /// position and axes of this camera such that it is positioned at loc, /// oriented to look towards the point at, and rotated so that up is the /// approximate upward direction for someone looking through the Camera. /// </summary> /// <param name="loc">The location of the Camera in world coordinates.</param> /// <param name="at">The point toward which the Camera is pointed (in world coordinates).</param> /// <param name="up">A vector that gives the approximate upward direction for /// the Camera in world coordinates.</param> void Camera::orient( const glm::vec3 & loc, const glm::vec3 & at, const glm::vec3 & up ) { location = loc; n = glm::normalize( loc - at ); u = glm::normalize( glm::cross( up, n ) ); v = glm::normalize( glm::cross( n,u ) ); } /// <returns>A pointer to this Camera's Film.</returns> Film * Camera::getFilm(){ return & film; } /// <summary> /// Returns a Ray object with its origin at the camera's position and a /// direction that points through the center of the pixel at (x, y) on the /// image plane. The Ray's direction is computed as if the image plane is /// located a distance of 1.0 from the position of the camera on the Camera's /// negative n-axis (i.e. at -1.0 on the n-axis). The image plane is oriented /// perpendicular to the Camera's n axis. /// /// The Ray is defined with its start at Ray.epsilon, /// and its end at the maximum value for a float (default values). /// /// x and y are pixel-based coordinates. For example, the pixel at the lower /// left corner of the image plane is located at pixel-coordinate (0,0). /// The corrsponding Ray should go through the center of that pixel, but is /// defined in world coordinates. The pixel at the upper-right of the image plane /// is given as (w-1, h-1) in pixel coordinats where w is the width of the /// Film and h is the height of the Film. /// </summary> /// <param name="x">The x coordinate on the image plane (pixel-based).</param> /// <param name="y">The y coordinate on the image plane (pixel-based).</param> /// <returns>A Ray object with origin at this Camera's position and direction /// through the center of the pixel on the image plane at (x, y). </returns> Ray Camera::getRay( int x, int y ) const{ float w = film.getWidth(); float h = film.getHeight(); //find height and width of the film plane float b = 2 * glm::tan( fovy/2 ); float a = b * ( w / h ); //width and height of single pixel float sX = a/w; //pixel width float sY = b/h; //pixel height //find origin and direction of ray that goes through center of pixel r=O+dt glm::vec3 orgn = location-n; glm::vec3 p = (location-n) + ( ((1/2) + x)*sX - (a/2)) * u + ( ((1/2) +y) * sY - (b/2) ) * v; glm::vec3 d = (p-location)/(glm::length(p-location)); Ray r( orgn, d ); return r; } /// <returns>The position of this camera.</returns> glm::vec3 Camera::getLocation(){ return location; }
[ "Rebecca@Rebeccas-MacBook-Pro-2.local" ]
Rebecca@Rebeccas-MacBook-Pro-2.local
5b1938ddd5ccfd92c113b7a21e703d36d0159f57
cae7b697a28f376b371304685ee00f0c46f89e70
/MiamiFallOut/ScoreManager.hh
38bdb90459512a18f6eeda218d0a567f941df0c3
[]
no_license
aurelienCastellarnau/MiamiFallOut
2e6e2dab47fa34ac51e1e622465479e62a4c2369
acd97202720b9e66fd2c9deab27d1b80c802374f
refs/heads/master
2020-03-31T00:28:26.618247
2018-11-08T20:58:20
2018-11-08T20:58:20
151,741,036
0
2
null
2018-11-08T21:46:41
2018-10-05T15:25:05
C++
UTF-8
C++
false
false
986
hh
#pragma once #include "stdafx.h" #include "AbstractEntity.hh" #include "IShapeManager.hh" #include "ShapeEntity.hh" #include "IObserver.hh" #include "Player.hh" class ScoreManager: public IObserver, public IShapeManager { public: ScoreManager(); ScoreManager(sf::RenderWindow*); std::list<ShapeEntity*> GetEntities() const; Player* GetPlayer() const; void AddEntity(ShapeEntity* const entity); void RemoveEntity(ShapeEntity* const entity); void Update(); // IShapeManager implementation void SetWindow(sf::RenderWindow*) override; sf::RenderWindow* GetWindow() const override; bool GetEndCondition() const; void SetEndCondition(bool end_condition); int GetScore() const; void SetScore(int score); int GetHit() const; void SetHit(int hit); // IObserver implementation virtual void Notify(IObservable* observable) override; ~ScoreManager(); private: std::list<ShapeEntity*> _entities; sf::RenderWindow* _window; bool _end_condition; int _score; int _hit; };
[ "castelllarnau.a@gmail.com" ]
castelllarnau.a@gmail.com
c7554220070f71bbf86a94eb5a83afe82ac8e0f5
55fcee0d560da7436262d2b755913120ad086bfb
/src/test/scriptnum_tests.cpp
f67c16cad3b7cf5bda9a1249e0741ffdc2b92775
[ "MIT" ]
permissive
Truckman83/DAS
a164bc93b52c0099d63d17db52331e70018fac16
387b744193452abddd074b4dd5e78005747a7428
refs/heads/master
2021-07-10T09:30:58.057974
2017-10-02T22:45:34
2017-10-02T22:45:34
105,590,268
5
3
null
null
null
null
UTF-8
C++
false
false
7,456
cpp
// Copyright (c) 2012-2015 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "scriptnum10.h" #include "script/script.h" #include "test/test_das.h" #include <boost/test/unit_test.hpp> #include <limits.h> #include <stdint.h> BOOST_FIXTURE_TEST_SUITE(scriptnum_tests, BasicTestingSetup) static const int64_t values[] = \ { 0, 1, CHAR_MIN, CHAR_MAX, UCHAR_MAX, SHRT_MIN, USHRT_MAX, INT_MIN, INT_MAX, UINT_MAX, LONG_MIN, LONG_MAX }; static const int64_t offsets[] = { 1, 0x79, 0x80, 0x81, 0xFF, 0x7FFF, 0x8000, 0xFFFF, 0x10000}; static bool verify(const CScriptNum10& bignum, const CScriptNum& scriptnum) { return bignum.getvch() == scriptnum.getvch() && bignum.getint() == scriptnum.getint(); } static void CheckCreateVch(const int64_t& num) { CScriptNum10 bignum(num); CScriptNum scriptnum(num); BOOST_CHECK(verify(bignum, scriptnum)); std::vector<unsigned char> vch = bignum.getvch(); CScriptNum10 bignum2(bignum.getvch(), false); vch = scriptnum.getvch(); CScriptNum scriptnum2(scriptnum.getvch(), false); BOOST_CHECK(verify(bignum2, scriptnum2)); CScriptNum10 bignum3(scriptnum2.getvch(), false); CScriptNum scriptnum3(bignum2.getvch(), false); BOOST_CHECK(verify(bignum3, scriptnum3)); } static void CheckCreateInt(const int64_t& num) { CScriptNum10 bignum(num); CScriptNum scriptnum(num); BOOST_CHECK(verify(bignum, scriptnum)); BOOST_CHECK(verify(CScriptNum10(bignum.getint()), CScriptNum(scriptnum.getint()))); BOOST_CHECK(verify(CScriptNum10(scriptnum.getint()), CScriptNum(bignum.getint()))); BOOST_CHECK(verify(CScriptNum10(CScriptNum10(scriptnum.getint()).getint()), CScriptNum(CScriptNum(bignum.getint()).getint()))); } static void CheckAdd(const int64_t& num1, const int64_t& num2) { const CScriptNum10 bignum1(num1); const CScriptNum10 bignum2(num2); const CScriptNum scriptnum1(num1); const CScriptNum scriptnum2(num2); CScriptNum10 bignum3(num1); CScriptNum10 bignum4(num1); CScriptNum scriptnum3(num1); CScriptNum scriptnum4(num1); // int64_t overflow is undefined. bool invalid = (((num2 > 0) && (num1 > (std::numeric_limits<int64_t>::max() - num2))) || ((num2 < 0) && (num1 < (std::numeric_limits<int64_t>::min() - num2)))); if (!invalid) { BOOST_CHECK(verify(bignum1 + bignum2, scriptnum1 + scriptnum2)); BOOST_CHECK(verify(bignum1 + bignum2, scriptnum1 + num2)); BOOST_CHECK(verify(bignum1 + bignum2, scriptnum2 + num1)); } } static void CheckNegate(const int64_t& num) { const CScriptNum10 bignum(num); const CScriptNum scriptnum(num); // -INT64_MIN is undefined if (num != std::numeric_limits<int64_t>::min()) BOOST_CHECK(verify(-bignum, -scriptnum)); } static void CheckSubtract(const int64_t& num1, const int64_t& num2) { const CScriptNum10 bignum1(num1); const CScriptNum10 bignum2(num2); const CScriptNum scriptnum1(num1); const CScriptNum scriptnum2(num2); bool invalid = false; // int64_t overflow is undefined. invalid = ((num2 > 0 && num1 < std::numeric_limits<int64_t>::min() + num2) || (num2 < 0 && num1 > std::numeric_limits<int64_t>::max() + num2)); if (!invalid) { BOOST_CHECK(verify(bignum1 - bignum2, scriptnum1 - scriptnum2)); BOOST_CHECK(verify(bignum1 - bignum2, scriptnum1 - num2)); } invalid = ((num1 > 0 && num2 < std::numeric_limits<int64_t>::min() + num1) || (num1 < 0 && num2 > std::numeric_limits<int64_t>::max() + num1)); if (!invalid) { BOOST_CHECK(verify(bignum2 - bignum1, scriptnum2 - scriptnum1)); BOOST_CHECK(verify(bignum2 - bignum1, scriptnum2 - num1)); } } static void CheckCompare(const int64_t& num1, const int64_t& num2) { const CScriptNum10 bignum1(num1); const CScriptNum10 bignum2(num2); const CScriptNum scriptnum1(num1); const CScriptNum scriptnum2(num2); BOOST_CHECK((bignum1 == bignum1) == (scriptnum1 == scriptnum1)); BOOST_CHECK((bignum1 != bignum1) == (scriptnum1 != scriptnum1)); BOOST_CHECK((bignum1 < bignum1) == (scriptnum1 < scriptnum1)); BOOST_CHECK((bignum1 > bignum1) == (scriptnum1 > scriptnum1)); BOOST_CHECK((bignum1 >= bignum1) == (scriptnum1 >= scriptnum1)); BOOST_CHECK((bignum1 <= bignum1) == (scriptnum1 <= scriptnum1)); BOOST_CHECK((bignum1 == bignum1) == (scriptnum1 == num1)); BOOST_CHECK((bignum1 != bignum1) == (scriptnum1 != num1)); BOOST_CHECK((bignum1 < bignum1) == (scriptnum1 < num1)); BOOST_CHECK((bignum1 > bignum1) == (scriptnum1 > num1)); BOOST_CHECK((bignum1 >= bignum1) == (scriptnum1 >= num1)); BOOST_CHECK((bignum1 <= bignum1) == (scriptnum1 <= num1)); BOOST_CHECK((bignum1 == bignum2) == (scriptnum1 == scriptnum2)); BOOST_CHECK((bignum1 != bignum2) == (scriptnum1 != scriptnum2)); BOOST_CHECK((bignum1 < bignum2) == (scriptnum1 < scriptnum2)); BOOST_CHECK((bignum1 > bignum2) == (scriptnum1 > scriptnum2)); BOOST_CHECK((bignum1 >= bignum2) == (scriptnum1 >= scriptnum2)); BOOST_CHECK((bignum1 <= bignum2) == (scriptnum1 <= scriptnum2)); BOOST_CHECK((bignum1 == bignum2) == (scriptnum1 == num2)); BOOST_CHECK((bignum1 != bignum2) == (scriptnum1 != num2)); BOOST_CHECK((bignum1 < bignum2) == (scriptnum1 < num2)); BOOST_CHECK((bignum1 > bignum2) == (scriptnum1 > num2)); BOOST_CHECK((bignum1 >= bignum2) == (scriptnum1 >= num2)); BOOST_CHECK((bignum1 <= bignum2) == (scriptnum1 <= num2)); } static void RunCreate(const int64_t& num) { CheckCreateInt(num); CScriptNum scriptnum(num); if (scriptnum.getvch().size() <= CScriptNum::nDefaultMaxNumSize) CheckCreateVch(num); else { BOOST_CHECK_THROW (CheckCreateVch(num), scriptnum10_error); } } static void RunOperators(const int64_t& num1, const int64_t& num2) { CheckAdd(num1, num2); CheckSubtract(num1, num2); CheckNegate(num1); CheckCompare(num1, num2); } BOOST_AUTO_TEST_CASE(creation) { for(size_t i = 0; i < sizeof(values) / sizeof(values[0]); ++i) { for(size_t j = 0; j < sizeof(offsets) / sizeof(offsets[0]); ++j) { RunCreate(values[i]); RunCreate(values[i] + offsets[j]); RunCreate(values[i] - offsets[j]); } } } BOOST_AUTO_TEST_CASE(operators) { for(size_t i = 0; i < sizeof(values) / sizeof(values[0]); ++i) { for(size_t j = 0; j < sizeof(offsets) / sizeof(offsets[0]); ++j) { RunOperators(values[i], values[i]); RunOperators(values[i], -values[i]); RunOperators(values[i], values[j]); RunOperators(values[i], -values[j]); RunOperators(values[i] + values[j], values[j]); RunOperators(values[i] + values[j], -values[j]); RunOperators(values[i] - values[j], values[j]); RunOperators(values[i] - values[j], -values[j]); RunOperators(values[i] + values[j], values[i] + values[j]); RunOperators(values[i] + values[j], values[i] - values[j]); RunOperators(values[i] - values[j], values[i] + values[j]); RunOperators(values[i] - values[j], values[i] - values[j]); } } } BOOST_AUTO_TEST_SUITE_END()
[ "ethscryptdev@gmail.com" ]
ethscryptdev@gmail.com
60a8b81b1f87323103354fc48b0fcc0b08c79e01
bf1eb722747705d84671970891253200a2a0b657
/gameclock/SuddenDeathTimeControlUi.h
6945595d666a1e0f7bcd5346c3c8f593ad4c2301
[]
no_license
asiviero/Arduino
4d4f834f0832c9c4b533127ec9883cb44f1cfbbe
5f05dbdf576a8201abc48e310b78035309f6ebcf
refs/heads/master
2020-12-25T16:25:38.443327
2012-07-29T23:37:25
2012-07-29T23:37:25
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,322
h
#ifndef __SuddenDeathTimeControlUi_h__ #define __SuddenDeathTimeControlUi_h__ #include <avr/pgmspace.h> #include <stdlib.h> #include "TimeControlUi.h" #include "SuddenDeathTimeControl.h" const prog_char suddenDeathName[] PROGMEM = "Sudden Death"; const prog_char suddenDeathOption1[] PROGMEM = " 30 sec"; const prog_char suddenDeathOption2[] PROGMEM = " 1 min"; const prog_char suddenDeathOption3[] PROGMEM = " 5 min"; const prog_char suddenDeathOption4[] PROGMEM = " 10 min"; const prog_char suddenDeathOption5[] PROGMEM = " 20 min"; const prog_char suddenDeathOption6[] PROGMEM = " 30 min"; const prog_char suddenDeathOption7[] PROGMEM = " 1 hour"; const prog_char *suddenDeathOptions[] PROGMEM = { suddenDeathOption1, suddenDeathOption2, suddenDeathOption3, suddenDeathOption4, suddenDeathOption5, suddenDeathOption6, suddenDeathOption7 }; class SuddenDeathTimeControlUi : public TimeControlUi { public: virtual const prog_char *getName() { return suddenDeathName; } virtual int16_t getNumberOfOptions() { return 7; } virtual const prog_char *getOption(int16_t option) { switch( option ) { case 0: return suddenDeathOptions[ option ]; case 1: return suddenDeathOptions[ option ]; case 2: return suddenDeathOptions[ option ]; case 3: return suddenDeathOptions[ option ]; case 4: return suddenDeathOptions[ option ]; case 5: return suddenDeathOptions[ option ]; case 6: return suddenDeathOptions[ option ]; } return suddenDeathOptions[ 0 ]; } virtual TimeControl *create(int16_t option) { uint32_t time = 0; switch( option ) { case 0: time = 1000L * 30L; break; case 1: time = 1000L * 60L * 1L; break; case 2: time = 1000L * 60L * 5L; break; case 3: time = 1000L * 60L * 10L; break; case 4: time = 1000L * 60L * 20L; break; case 5: time = 1000L * 60L * 30L; break; case 6: time = 1000L * 60L * 60L * 1L; break; } return new SuddenDeathTimeControl( time ); } }; #endif
[ "matias.g.rodriguez@gmail.com" ]
matias.g.rodriguez@gmail.com
24297104c2e7d8b20c32f6f226f513a64bbbeadf
1c18ead26dbc4d2391f2a2a2a219a5dbf5255dc8
/src/rpcmasternode-budget.cpp
82f7b19fc7e4c8a0685ae5ebc3c889e264275497
[ "MIT" ]
permissive
ZzerLo/Triskelpremium
8792b41caa68567852de85a30965a43848e5f0ea
76aa4230f6361d9078dc1be58cf97f4e90ec83b2
refs/heads/master
2020-03-31T03:11:13.433374
2018-10-06T06:57:29
2018-10-06T06:57:29
null
0
0
null
null
null
null
UTF-8
C++
false
false
45,493
cpp
// Copyright (c) 2014-2015 The Dash Developers // Copyright (c) 2015-2017 The PIVX developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "activemasternode.h" #include "db.h" #include "init.h" #include "main.h" #include "masternode-budget.h" #include "masternode-payments.h" #include "masternodeconfig.h" #include "masternodeman.h" #include "masternode-helpers.h" #include "rpcserver.h" #include "utilmoneystr.h" #include <univalue.h> #include <fstream> using namespace std; void budgetToJSON(CBudgetProposal* pbudgetProposal, UniValue& bObj) { CTxDestination address1; ExtractDestination(pbudgetProposal->GetPayee(), address1); CBitcoinAddress address2(address1); bObj.push_back(Pair("Name", pbudgetProposal->GetName())); bObj.push_back(Pair("URL", pbudgetProposal->GetURL())); bObj.push_back(Pair("Hash", pbudgetProposal->GetHash().ToString())); bObj.push_back(Pair("FeeHash", pbudgetProposal->nFeeTXHash.ToString())); bObj.push_back(Pair("BlockStart", (int64_t)pbudgetProposal->GetBlockStart())); bObj.push_back(Pair("BlockEnd", (int64_t)pbudgetProposal->GetBlockEnd())); bObj.push_back(Pair("TotalPaymentCount", (int64_t)pbudgetProposal->GetTotalPaymentCount())); bObj.push_back(Pair("RemainingPaymentCount", (int64_t)pbudgetProposal->GetRemainingPaymentCount())); bObj.push_back(Pair("PaymentAddress", address2.ToString())); bObj.push_back(Pair("Ratio", pbudgetProposal->GetRatio())); bObj.push_back(Pair("Yeas", (int64_t)pbudgetProposal->GetYeas())); bObj.push_back(Pair("Nays", (int64_t)pbudgetProposal->GetNays())); bObj.push_back(Pair("Abstains", (int64_t)pbudgetProposal->GetAbstains())); bObj.push_back(Pair("TotalPayment", ValueFromAmount(pbudgetProposal->GetAmount() * pbudgetProposal->GetTotalPaymentCount()))); bObj.push_back(Pair("MonthlyPayment", ValueFromAmount(pbudgetProposal->GetAmount()))); bObj.push_back(Pair("IsEstablished", pbudgetProposal->IsEstablished())); std::string strError = ""; bObj.push_back(Pair("IsValid", pbudgetProposal->IsValid(strError))); bObj.push_back(Pair("IsValidReason", strError.c_str())); bObj.push_back(Pair("fValid", pbudgetProposal->fValid)); } // This command is retained for backwards compatibility, but is deprecated. // Future removal of this command is planned to keep things clean. UniValue mnbudget(const UniValue& params, bool fHelp) { string strCommand; if (params.size() >= 1) strCommand = params[0].get_str(); if (fHelp || (strCommand != "vote-alias" && strCommand != "vote-many" && strCommand != "prepare" && strCommand != "submit" && strCommand != "vote" && strCommand != "getvotes" && strCommand != "getinfo" && strCommand != "show" && strCommand != "projection" && strCommand != "check" && strCommand != "nextblock")) throw runtime_error( "mnbudget \"command\"... ( \"passphrase\" )\n" "\nVote or show current budgets\n" "This command is deprecated, please see individual command documentation for future reference\n\n" "\nAvailable commands:\n" " prepare - Prepare proposal for network by signing and creating tx\n" " submit - Submit proposal for network\n" " vote-many - Vote on a Triskelpremium initiative\n" " vote-alias - Vote on a Triskelpremium initiative\n" " vote - Vote on a Triskelpremium initiative/budget\n" " getvotes - Show current masternode budgets\n" " getinfo - Show current masternode budgets\n" " show - Show all budgets\n" " projection - Show the projection of which proposals will be paid the next cycle\n" " check - Scan proposals and remove invalid\n" " nextblock - Get next superblock for budget system\n"); if (strCommand == "nextblock") { UniValue newParams(UniValue::VARR); // forward params but skip command for (unsigned int i = 1; i < params.size(); i++) { newParams.push_back(params[i]); } return getnextsuperblock(newParams, fHelp); } if (strCommand == "prepare") { UniValue newParams(UniValue::VARR); // forward params but skip command for (unsigned int i = 1; i < params.size(); i++) { newParams.push_back(params[i]); } return preparebudget(newParams, fHelp); } if (strCommand == "submit") { UniValue newParams(UniValue::VARR); // forward params but skip command for (unsigned int i = 1; i < params.size(); i++) { newParams.push_back(params[i]); } return submitbudget(newParams, fHelp); } if (strCommand == "vote" || strCommand == "vote-many" || strCommand == "vote-alias") { if (strCommand == "vote-alias") throw runtime_error( "vote-alias is not supported with this command\n" "Please use mnbudgetvote instead.\n" ); return mnbudgetvote(params, fHelp); } if (strCommand == "projection") { UniValue newParams(UniValue::VARR); // forward params but skip command for (unsigned int i = 1; i < params.size(); i++) { newParams.push_back(params[i]); } return getbudgetprojection(newParams, fHelp); } if (strCommand == "show" || strCommand == "getinfo") { UniValue newParams(UniValue::VARR); // forward params but skip command for (unsigned int i = 1; i < params.size(); i++) { newParams.push_back(params[i]); } return getbudgetinfo(newParams, fHelp); } if (strCommand == "getvotes") { UniValue newParams(UniValue::VARR); // forward params but skip command for (unsigned int i = 1; i < params.size(); i++) { newParams.push_back(params[i]); } return getbudgetvotes(newParams, fHelp); } if (strCommand == "check") { UniValue newParams(UniValue::VARR); // forward params but skip command for (unsigned int i = 1; i < params.size(); i++) { newParams.push_back(params[i]); } return checkbudgets(newParams, fHelp); } return NullUniValue; } UniValue preparebudget(const UniValue& params, bool fHelp) { int nBlockMin = 0; CBlockIndex* pindexPrev = chainActive.Tip(); if (fHelp || params.size() != 6) throw runtime_error( "preparebudget \"proposal-name\" \"url\" payment-count block-start \"tkp-address\" monthly-payment\n" "\nPrepare proposal for network by signing and creating tx\n" "\nArguments:\n" "1. \"proposal-name\": (string, required) Desired proposal name (20 character limit)\n" "2. \"url\": (string, required) URL of proposal details (64 character limit)\n" "3. payment-count: (numeric, required) Total number of monthly payments\n" "4. block-start: (numeric, required) Starting super block height\n" "5. \"tkp-address\": (string, required) TKP address to send payments to\n" "6. monthly-payment: (numeric, required) Monthly payment amount\n" "\nResult:\n" "\"xxxx\" (string) proposal fee hash (if successful) or error message (if failed)\n" "\nExamples:\n" + HelpExampleCli("preparebudget", "\"test-proposal\" \"https://savebitcoin.io/t/test-proposal\" 2 820800 \"D9oc6C3dttUbv8zd7zGNq1qKBGf4ZQ1XEE\" 500") + HelpExampleRpc("preparebudget", "\"test-proposal\" \"https://savebitcoin.io/t/test-proposal\" 2 820800 \"D9oc6C3dttUbv8zd7zGNq1qKBGf4ZQ1XEE\" 500")); if (pwalletMain->IsLocked()) throw JSONRPCError(RPC_WALLET_UNLOCK_NEEDED, "Error: Please enter the wallet passphrase with walletpassphrase first."); std::string strProposalName = SanitizeString(params[0].get_str()); if (strProposalName.size() > 20) throw runtime_error("Invalid proposal name, limit of 20 characters."); std::string strURL = SanitizeString(params[1].get_str()); if (strURL.size() > 64) throw runtime_error("Invalid url, limit of 64 characters."); int nPaymentCount = params[2].get_int(); if (nPaymentCount < 1) throw runtime_error("Invalid payment count, must be more than zero."); // Start must be in the next budget cycle if (pindexPrev != NULL) nBlockMin = pindexPrev->nHeight - pindexPrev->nHeight % GetBudgetPaymentCycleBlocks() + GetBudgetPaymentCycleBlocks(); int nBlockStart = params[3].get_int(); if (nBlockStart % GetBudgetPaymentCycleBlocks() != 0) { int nNext = pindexPrev->nHeight - pindexPrev->nHeight % GetBudgetPaymentCycleBlocks() + GetBudgetPaymentCycleBlocks(); throw runtime_error(strprintf("Invalid block start - must be a budget cycle block. Next valid block: %d", nNext)); } int nBlockEnd = nBlockStart + GetBudgetPaymentCycleBlocks() * nPaymentCount; // End must be AFTER current cycle if (nBlockStart < nBlockMin) throw runtime_error("Invalid block start, must be more than current height."); if (nBlockEnd < pindexPrev->nHeight) throw runtime_error("Invalid ending block, starting block + (payment_cycle*payments) must be more than current height."); CBitcoinAddress address(params[4].get_str()); if (!address.IsValid()) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid TKP address"); // Parse TKP address CScript scriptPubKey = GetScriptForDestination(address.Get()); CAmount nAmount = AmountFromValue(params[5]); //************************************************************************* // create transaction 15 minutes into the future, to allow for confirmation time CBudgetProposalBroadcast budgetProposalBroadcast(strProposalName, strURL, nPaymentCount, scriptPubKey, nAmount, nBlockStart, 0); std::string strError = ""; if (!budgetProposalBroadcast.IsValid(strError, false)) throw runtime_error("Proposal is not valid - " + budgetProposalBroadcast.GetHash().ToString() + " - " + strError); bool useIX = false; //true; // if (params.size() > 7) { // if(params[7].get_str() != "false" && params[7].get_str() != "true") // return "Invalid use_ix, must be true or false"; // useIX = params[7].get_str() == "true" ? true : false; // } CWalletTx wtx; if (!pwalletMain->GetBudgetSystemCollateralTX(wtx, budgetProposalBroadcast.GetHash(), useIX)) { throw runtime_error("Error making collateral transaction for proposal. Please check your wallet balance."); } // make our change address CReserveKey reservekey(pwalletMain); //send the tx to the network pwalletMain->CommitTransaction(wtx, reservekey, useIX ? "ix" : "tx"); return wtx.GetHash().ToString(); } UniValue submitbudget(const UniValue& params, bool fHelp) { int nBlockMin = 0; CBlockIndex* pindexPrev = chainActive.Tip(); if (fHelp || params.size() != 7) throw runtime_error( "submitbudget \"proposal-name\" \"url\" payment-count block-start \"tkp-address\" monthly-payment \"fee-tx\"\n" "\nSubmit proposal to the network\n" "\nArguments:\n" "1. \"proposal-name\": (string, required) Desired proposal name (20 character limit)\n" "2. \"url\": (string, required) URL of proposal details (64 character limit)\n" "3. payment-count: (numeric, required) Total number of monthly payments\n" "4. block-start: (numeric, required) Starting super block height\n" "5. \"tkp-address\": (string, required) TKP address to send payments to\n" "6. monthly-payment: (numeric, required) Monthly payment amount\n" "7. \"fee-tx\": (string, required) Transaction hash from preparebudget command\n" "\nResult:\n" "\"xxxx\" (string) proposal hash (if successful) or error message (if failed)\n" "\nExamples:\n" + HelpExampleCli("submitbudget", "\"test-proposal\" \"https://savebitcoin.io/t/test-proposal\" 2 820800 \"D9oc6C3dttUbv8zd7zGNq1qKBGf4ZQ1XEE\" 500") + HelpExampleRpc("submitbudget", "\"test-proposal\" \"https://savebitcoin.io/t/test-proposal\" 2 820800 \"D9oc6C3dttUbv8zd7zGNq1qKBGf4ZQ1XEE\" 500")); // Check these inputs the same way we check the vote commands: // ********************************************************** std::string strProposalName = SanitizeString(params[0].get_str()); if (strProposalName.size() > 20) throw runtime_error("Invalid proposal name, limit of 20 characters."); std::string strURL = SanitizeString(params[1].get_str()); if (strURL.size() > 64) throw runtime_error("Invalid url, limit of 64 characters."); int nPaymentCount = params[2].get_int(); if (nPaymentCount < 1) throw runtime_error("Invalid payment count, must be more than zero."); // Start must be in the next budget cycle if (pindexPrev != NULL) nBlockMin = pindexPrev->nHeight - pindexPrev->nHeight % GetBudgetPaymentCycleBlocks() + GetBudgetPaymentCycleBlocks(); int nBlockStart = params[3].get_int(); if (nBlockStart % GetBudgetPaymentCycleBlocks() != 0) { int nNext = pindexPrev->nHeight - pindexPrev->nHeight % GetBudgetPaymentCycleBlocks() + GetBudgetPaymentCycleBlocks(); throw runtime_error(strprintf("Invalid block start - must be a budget cycle block. Next valid block: %d", nNext)); } int nBlockEnd = nBlockStart + (GetBudgetPaymentCycleBlocks() * nPaymentCount); // End must be AFTER current cycle if (nBlockStart < nBlockMin) throw runtime_error("Invalid block start, must be more than current height."); if (nBlockEnd < pindexPrev->nHeight) throw runtime_error("Invalid ending block, starting block + (payment_cycle*payments) must be more than current height."); CBitcoinAddress address(params[4].get_str()); if (!address.IsValid()) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid TKP address"); // Parse TKP address CScript scriptPubKey = GetScriptForDestination(address.Get()); CAmount nAmount = AmountFromValue(params[5]); uint256 hash = ParseHashV(params[6], "parameter 1"); //create the proposal incase we're the first to make it CBudgetProposalBroadcast budgetProposalBroadcast(strProposalName, strURL, nPaymentCount, scriptPubKey, nAmount, nBlockStart, hash); std::string strError = ""; int nConf = 0; if (!IsBudgetCollateralValid(hash, budgetProposalBroadcast.GetHash(), strError, budgetProposalBroadcast.nTime, nConf)) { throw runtime_error("Proposal FeeTX is not valid - " + hash.ToString() + " - " + strError); } if (!masternodeSync.IsBlockchainSynced()) { throw runtime_error("Must wait for client to sync with masternode network. Try again in a minute or so."); } // if(!budgetProposalBroadcast.IsValid(strError)){ // return "Proposal is not valid - " + budgetProposalBroadcast.GetHash().ToString() + " - " + strError; // } budget.mapSeenMasternodeBudgetProposals.insert(make_pair(budgetProposalBroadcast.GetHash(), budgetProposalBroadcast)); budgetProposalBroadcast.Relay(); if(budget.AddProposal(budgetProposalBroadcast)) { return budgetProposalBroadcast.GetHash().ToString(); } throw runtime_error("Invalid proposal, see debug.log for details."); } UniValue mnbudgetvote(const UniValue& params, bool fHelp) { std::string strCommand; if (params.size() >= 1) { strCommand = params[0].get_str(); // Backwards compatibility with legacy `mnbudget` command if (strCommand == "vote") strCommand = "local"; if (strCommand == "vote-many") strCommand = "many"; if (strCommand == "vote-alias") strCommand = "alias"; } if (fHelp || (params.size() == 3 && (strCommand != "local" && strCommand != "many")) || (params.size() == 4 && strCommand != "alias") || params.size() > 4 || params.size() < 3) throw runtime_error( "mnbudgetvote \"local|many|alias\" \"votehash\" \"yes|no\" ( \"alias\" )\n" "\nVote on a budget proposal\n" "\nArguments:\n" "1. \"mode\" (string, required) The voting mode. 'local' for voting directly from a masternode, 'many' for voting with a MN controller and casting the same vote for each MN, 'alias' for voting with a MN controller and casting a vote for a single MN\n" "2. \"votehash\" (string, required) The vote hash for the proposal\n" "3. \"votecast\" (string, required) Your vote. 'yes' to vote for the proposal, 'no' to vote against\n" "4. \"alias\" (string, required for 'alias' mode) The MN alias to cast a vote for.\n" "\nResult:\n" "{\n" " \"overall\": \"xxxx\", (string) The overall status message for the vote cast\n" " \"detail\": [\n" " {\n" " \"node\": \"xxxx\", (string) 'local' or the MN alias\n" " \"result\": \"xxxx\", (string) Either 'Success' or 'Failed'\n" " \"error\": \"xxxx\", (string) Error message, if vote failed\n" " }\n" " ,...\n" " ]\n" "}\n" "\nExamples:\n" + HelpExampleCli("mnbudgetvote", "\"local\" \"ed2f83cedee59a91406f5f47ec4d60bf5a7f9ee6293913c82976bd2d3a658041\" \"yes\"") + HelpExampleRpc("mnbudgetvote", "\"local\" \"ed2f83cedee59a91406f5f47ec4d60bf5a7f9ee6293913c82976bd2d3a658041\" \"yes\"")); uint256 hash = ParseHashV(params[1], "parameter 1"); std::string strVote = params[2].get_str(); if (strVote != "yes" && strVote != "no") return "You can only vote 'yes' or 'no'"; int nVote = VOTE_ABSTAIN; if (strVote == "yes") nVote = VOTE_YES; if (strVote == "no") nVote = VOTE_NO; int success = 0; int failed = 0; UniValue resultsObj(UniValue::VARR); if (strCommand == "local") { CPubKey pubKeyMasternode; CKey keyMasternode; std::string errorMessage; UniValue statusObj(UniValue::VOBJ); while (true) { if (!masternodeSigner.SetKey(strMasterNodePrivKey, errorMessage, keyMasternode, pubKeyMasternode)) { failed++; statusObj.push_back(Pair("node", "local")); statusObj.push_back(Pair("result", "failed")); statusObj.push_back(Pair("error", "Masternode signing error, could not set key correctly: " + errorMessage)); resultsObj.push_back(statusObj); break; } CMasternode* pmn = mnodeman.Find(activeMasternode.vin); if (pmn == NULL) { failed++; statusObj.push_back(Pair("node", "local")); statusObj.push_back(Pair("result", "failed")); statusObj.push_back(Pair("error", "Failure to find masternode in list : " + activeMasternode.vin.ToString())); resultsObj.push_back(statusObj); break; } CBudgetVote vote(activeMasternode.vin, hash, nVote); if (!vote.Sign(keyMasternode, pubKeyMasternode)) { failed++; statusObj.push_back(Pair("node", "local")); statusObj.push_back(Pair("result", "failed")); statusObj.push_back(Pair("error", "Failure to sign.")); resultsObj.push_back(statusObj); break; } std::string strError = ""; if (budget.UpdateProposal(vote, NULL, strError)) { success++; budget.mapSeenMasternodeBudgetVotes.insert(make_pair(vote.GetHash(), vote)); vote.Relay(); statusObj.push_back(Pair("node", "local")); statusObj.push_back(Pair("result", "success")); statusObj.push_back(Pair("error", "")); } else { failed++; statusObj.push_back(Pair("node", "local")); statusObj.push_back(Pair("result", "failed")); statusObj.push_back(Pair("error", "Error voting : " + strError)); } resultsObj.push_back(statusObj); break; } UniValue returnObj(UniValue::VOBJ); returnObj.push_back(Pair("overall", strprintf("Voted successfully %d time(s) and failed %d time(s).", success, failed))); returnObj.push_back(Pair("detail", resultsObj)); return returnObj; } if (strCommand == "many") { BOOST_FOREACH (CMasternodeConfig::CMasternodeEntry mne, masternodeConfig.getEntries()) { std::string errorMessage; std::vector<unsigned char> vchMasterNodeSignature; std::string strMasterNodeSignMessage; CPubKey pubKeyCollateralAddress; CKey keyCollateralAddress; CPubKey pubKeyMasternode; CKey keyMasternode; UniValue statusObj(UniValue::VOBJ); if (!masternodeSigner.SetKey(mne.getPrivKey(), errorMessage, keyMasternode, pubKeyMasternode)) { failed++; statusObj.push_back(Pair("node", mne.getAlias())); statusObj.push_back(Pair("result", "failed")); statusObj.push_back(Pair("error", "Masternode signing error, could not set key correctly: " + errorMessage)); resultsObj.push_back(statusObj); continue; } CMasternode* pmn = mnodeman.Find(pubKeyMasternode); if (pmn == NULL) { failed++; statusObj.push_back(Pair("node", mne.getAlias())); statusObj.push_back(Pair("result", "failed")); statusObj.push_back(Pair("error", "Can't find masternode by pubkey")); resultsObj.push_back(statusObj); continue; } CBudgetVote vote(pmn->vin, hash, nVote); if (!vote.Sign(keyMasternode, pubKeyMasternode)) { failed++; statusObj.push_back(Pair("node", mne.getAlias())); statusObj.push_back(Pair("result", "failed")); statusObj.push_back(Pair("error", "Failure to sign.")); resultsObj.push_back(statusObj); continue; } std::string strError = ""; if (budget.UpdateProposal(vote, NULL, strError)) { budget.mapSeenMasternodeBudgetVotes.insert(make_pair(vote.GetHash(), vote)); vote.Relay(); success++; statusObj.push_back(Pair("node", mne.getAlias())); statusObj.push_back(Pair("result", "success")); statusObj.push_back(Pair("error", "")); } else { failed++; statusObj.push_back(Pair("node", mne.getAlias())); statusObj.push_back(Pair("result", "failed")); statusObj.push_back(Pair("error", strError.c_str())); } resultsObj.push_back(statusObj); } UniValue returnObj(UniValue::VOBJ); returnObj.push_back(Pair("overall", strprintf("Voted successfully %d time(s) and failed %d time(s).", success, failed))); returnObj.push_back(Pair("detail", resultsObj)); return returnObj; } if (strCommand == "alias") { std::string strAlias = params[3].get_str(); std::vector<CMasternodeConfig::CMasternodeEntry> mnEntries; mnEntries = masternodeConfig.getEntries(); BOOST_FOREACH(CMasternodeConfig::CMasternodeEntry mne, masternodeConfig.getEntries()) { if( strAlias != mne.getAlias()) continue; std::string errorMessage; std::vector<unsigned char> vchMasterNodeSignature; std::string strMasterNodeSignMessage; CPubKey pubKeyCollateralAddress; CKey keyCollateralAddress; CPubKey pubKeyMasternode; CKey keyMasternode; UniValue statusObj(UniValue::VOBJ); if(!masternodeSigner.SetKey(mne.getPrivKey(), errorMessage, keyMasternode, pubKeyMasternode)){ failed++; statusObj.push_back(Pair("node", mne.getAlias())); statusObj.push_back(Pair("result", "failed")); statusObj.push_back(Pair("error", "Masternode signing error, could not set key correctly: " + errorMessage)); resultsObj.push_back(statusObj); continue; } CMasternode* pmn = mnodeman.Find(pubKeyMasternode); if(pmn == NULL) { failed++; statusObj.push_back(Pair("node", mne.getAlias())); statusObj.push_back(Pair("result", "failed")); statusObj.push_back(Pair("error", "Can't find masternode by pubkey")); resultsObj.push_back(statusObj); continue; } CBudgetVote vote(pmn->vin, hash, nVote); if(!vote.Sign(keyMasternode, pubKeyMasternode)){ failed++; statusObj.push_back(Pair("node", mne.getAlias())); statusObj.push_back(Pair("result", "failed")); statusObj.push_back(Pair("error", "Failure to sign.")); resultsObj.push_back(statusObj); continue; } std::string strError = ""; if(budget.UpdateProposal(vote, NULL, strError)) { budget.mapSeenMasternodeBudgetVotes.insert(make_pair(vote.GetHash(), vote)); vote.Relay(); success++; statusObj.push_back(Pair("node", mne.getAlias())); statusObj.push_back(Pair("result", "success")); statusObj.push_back(Pair("error", "")); } else { failed++; statusObj.push_back(Pair("node", mne.getAlias())); statusObj.push_back(Pair("result", "failed")); statusObj.push_back(Pair("error", strError.c_str())); } resultsObj.push_back(statusObj); } UniValue returnObj(UniValue::VOBJ); returnObj.push_back(Pair("overall", strprintf("Voted successfully %d time(s) and failed %d time(s).", success, failed))); returnObj.push_back(Pair("detail", resultsObj)); return returnObj; } return NullUniValue; } UniValue getbudgetvotes(const UniValue& params, bool fHelp) { if (params.size() != 1) throw runtime_error( "getbudgetvotes \"proposal-name\"\n" "\nPrint vote information for a budget proposal\n" "\nArguments:\n" "1. \"proposal-name\": (string, required) Name of the proposal\n" "\nResult:\n" "[\n" " {\n" " \"mnId\": \"xxxx\", (string) Hash of the masternode's collateral transaction\n" " \"nHash\": \"xxxx\", (string) Hash of the vote\n" " \"Vote\": \"YES|NO\", (string) Vote cast ('YES' or 'NO')\n" " \"nTime\": xxxx, (numeric) Time in seconds since epoch the vote was cast\n" " \"fValid\": true|false, (boolean) 'true' if the vote is valid, 'false' otherwise\n" " }\n" " ,...\n" "]\n" "\nExamples:\n" + HelpExampleCli("getbudgetvotes", "\"test-proposal\"") + HelpExampleRpc("getbudgetvotes", "\"test-proposal\"")); std::string strProposalName = SanitizeString(params[0].get_str()); UniValue ret(UniValue::VARR); CBudgetProposal* pbudgetProposal = budget.FindProposal(strProposalName); if (pbudgetProposal == NULL) throw runtime_error("Unknown proposal name"); std::map<uint256, CBudgetVote>::iterator it = pbudgetProposal->mapVotes.begin(); while (it != pbudgetProposal->mapVotes.end()) { UniValue bObj(UniValue::VOBJ); bObj.push_back(Pair("mnId", (*it).second.vin.prevout.hash.ToString())); bObj.push_back(Pair("nHash", (*it).first.ToString().c_str())); bObj.push_back(Pair("Vote", (*it).second.GetVoteString())); bObj.push_back(Pair("nTime", (int64_t)(*it).second.nTime)); bObj.push_back(Pair("fValid", (*it).second.fValid)); ret.push_back(bObj); it++; } return ret; } UniValue getnextsuperblock(const UniValue& params, bool fHelp) { if (fHelp || params.size() != 0) throw runtime_error( "getnextsuperblock\n" "\nPrint the next super block height\n" "\nResult:\n" "n (numeric) Block height of the next super block\n" "\nExamples:\n" + HelpExampleCli("getnextsuperblock", "") + HelpExampleRpc("getnextsuperblock", "")); CBlockIndex* pindexPrev = chainActive.Tip(); if (!pindexPrev) return "unknown"; int nNext = pindexPrev->nHeight - pindexPrev->nHeight % GetBudgetPaymentCycleBlocks() + GetBudgetPaymentCycleBlocks(); return nNext; } UniValue getbudgetprojection(const UniValue& params, bool fHelp) { if (fHelp || params.size() != 0) throw runtime_error( "getbudgetprojection\n" "\nShow the projection of which proposals will be paid the next cycle\n" "\nResult:\n" "[\n" " {\n" " \"Name\": \"xxxx\", (string) Proposal Name\n" " \"URL\": \"xxxx\", (string) Proposal URL\n" " \"Hash\": \"xxxx\", (string) Proposal vote hash\n" " \"FeeHash\": \"xxxx\", (string) Proposal fee hash\n" " \"BlockStart\": n, (numeric) Proposal starting block\n" " \"BlockEnd\": n, (numeric) Proposal ending block\n" " \"TotalPaymentCount\": n, (numeric) Number of payments\n" " \"RemainingPaymentCount\": n, (numeric) Number of remaining payments\n" " \"PaymentAddress\": \"xxxx\", (string) TKP address of payment\n" " \"Ratio\": x.xxx, (numeric) Ratio of yeas vs nays\n" " \"Yeas\": n, (numeric) Number of yea votes\n" " \"Nays\": n, (numeric) Number of nay votes\n" " \"Abstains\": n, (numeric) Number of abstains\n" " \"TotalPayment\": xxx.xxx, (numeric) Total payment amount\n" " \"MonthlyPayment\": xxx.xxx, (numeric) Monthly payment amount\n" " \"IsEstablished\": true|false, (boolean) Established (true) or (false)\n" " \"IsValid\": true|false, (boolean) Valid (true) or Invalid (false)\n" " \"IsValidReason\": \"xxxx\", (string) Error message, if any\n" " \"fValid\": true|false, (boolean) Valid (true) or Invalid (false)\n" " \"Alloted\": xxx.xxx, (numeric) Amount alloted in current period\n" " \"TotalBudgetAlloted\": xxx.xxx (numeric) Total alloted\n" " }\n" " ,...\n" "]\n" "\nExamples:\n" + HelpExampleCli("getbudgetprojection", "") + HelpExampleRpc("getbudgetprojection", "")); UniValue ret(UniValue::VARR); UniValue resultObj(UniValue::VOBJ); CAmount nTotalAllotted = 0; std::vector<CBudgetProposal*> winningProps = budget.GetBudget(); BOOST_FOREACH (CBudgetProposal* pbudgetProposal, winningProps) { nTotalAllotted += pbudgetProposal->GetAllotted(); CTxDestination address1; ExtractDestination(pbudgetProposal->GetPayee(), address1); CBitcoinAddress address2(address1); UniValue bObj(UniValue::VOBJ); budgetToJSON(pbudgetProposal, bObj); bObj.push_back(Pair("Alloted", ValueFromAmount(pbudgetProposal->GetAllotted()))); bObj.push_back(Pair("TotalBudgetAlloted", ValueFromAmount(nTotalAllotted))); ret.push_back(bObj); } return ret; } UniValue getbudgetinfo(const UniValue& params, bool fHelp) { if (fHelp || params.size() > 1) throw runtime_error( "getbudgetinfo ( \"proposal\" )\n" "\nShow current masternode budgets\n" "\nArguments:\n" "1. \"proposal\" (string, optional) Proposal name\n" "\nResult:\n" "[\n" " {\n" " \"Name\": \"xxxx\", (string) Proposal Name\n" " \"URL\": \"xxxx\", (string) Proposal URL\n" " \"Hash\": \"xxxx\", (string) Proposal vote hash\n" " \"FeeHash\": \"xxxx\", (string) Proposal fee hash\n" " \"BlockStart\": n, (numeric) Proposal starting block\n" " \"BlockEnd\": n, (numeric) Proposal ending block\n" " \"TotalPaymentCount\": n, (numeric) Number of payments\n" " \"RemainingPaymentCount\": n, (numeric) Number of remaining payments\n" " \"PaymentAddress\": \"xxxx\", (string) TKP address of payment\n" " \"Ratio\": x.xxx, (numeric) Ratio of yeas vs nays\n" " \"Yeas\": n, (numeric) Number of yea votes\n" " \"Nays\": n, (numeric) Number of nay votes\n" " \"Abstains\": n, (numeric) Number of abstains\n" " \"TotalPayment\": xxx.xxx, (numeric) Total payment amount\n" " \"MonthlyPayment\": xxx.xxx, (numeric) Monthly payment amount\n" " \"IsEstablished\": true|false, (boolean) Established (true) or (false)\n" " \"IsValid\": true|false, (boolean) Valid (true) or Invalid (false)\n" " \"IsValidReason\": \"xxxx\", (string) Error message, if any\n" " \"fValid\": true|false, (boolean) Valid (true) or Invalid (false)\n" " }\n" " ,...\n" "]\n" "\nExamples:\n" + HelpExampleCli("getbudgetprojection", "") + HelpExampleRpc("getbudgetprojection", "")); UniValue ret(UniValue::VARR); std::string strShow = "valid"; if (params.size() == 1) { std::string strProposalName = SanitizeString(params[0].get_str()); CBudgetProposal* pbudgetProposal = budget.FindProposal(strProposalName); if (pbudgetProposal == NULL) throw runtime_error("Unknown proposal name"); UniValue bObj(UniValue::VOBJ); budgetToJSON(pbudgetProposal, bObj); ret.push_back(bObj); return ret; } std::vector<CBudgetProposal*> winningProps = budget.GetAllProposals(); BOOST_FOREACH (CBudgetProposal* pbudgetProposal, winningProps) { if (strShow == "valid" && !pbudgetProposal->fValid) continue; UniValue bObj(UniValue::VOBJ); budgetToJSON(pbudgetProposal, bObj); ret.push_back(bObj); } return ret; } UniValue mnbudgetrawvote(const UniValue& params, bool fHelp) { if (fHelp || params.size() != 6) throw runtime_error( "mnbudgetrawvote \"masternode-tx-hash\" masternode-tx-index \"proposal-hash\" yes|no time \"vote-sig\"\n" "\nCompile and relay a proposal vote with provided external signature instead of signing vote internally\n" "\nArguments:\n" "1. \"masternode-tx-hash\" (string, required) Transaction hash for the masternode\n" "2. masternode-tx-index (numeric, required) Output index for the masternode\n" "3. \"proposal-hash\" (string, required) Proposal vote hash\n" "4. yes|no (boolean, required) Vote to cast\n" "5. time (numeric, required) Time since epoch in seconds\n" "6. \"vote-sig\" (string, required) External signature\n" "\nResult:\n" "\"status\" (string) Vote status or error message\n" "\nExamples:\n" + HelpExampleCli("mnbudgetrawvote", "") + HelpExampleRpc("mnbudgetrawvote", "")); uint256 hashMnTx = ParseHashV(params[0], "mn tx hash"); int nMnTxIndex = params[1].get_int(); CTxIn vin = CTxIn(hashMnTx, nMnTxIndex); uint256 hashProposal = ParseHashV(params[2], "Proposal hash"); std::string strVote = params[3].get_str(); if (strVote != "yes" && strVote != "no") return "You can only vote 'yes' or 'no'"; int nVote = VOTE_ABSTAIN; if (strVote == "yes") nVote = VOTE_YES; if (strVote == "no") nVote = VOTE_NO; int64_t nTime = params[4].get_int64(); std::string strSig = params[5].get_str(); bool fInvalid = false; vector<unsigned char> vchSig = DecodeBase64(strSig.c_str(), &fInvalid); if (fInvalid) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Malformed base64 encoding"); CMasternode* pmn = mnodeman.Find(vin); if (pmn == NULL) { return "Failure to find masternode in list : " + vin.ToString(); } CBudgetVote vote(vin, hashProposal, nVote); vote.nTime = nTime; vote.vchSig = vchSig; if (!vote.SignatureValid(true)) { return "Failure to verify signature."; } std::string strError = ""; if (budget.UpdateProposal(vote, NULL, strError)) { budget.mapSeenMasternodeBudgetVotes.insert(make_pair(vote.GetHash(), vote)); vote.Relay(); return "Voted successfully"; } else { return "Error voting : " + strError; } } UniValue mnfinalbudget(const UniValue& params, bool fHelp) { string strCommand; if (params.size() >= 1) strCommand = params[0].get_str(); if (fHelp || (strCommand != "suggest" && strCommand != "vote-many" && strCommand != "vote" && strCommand != "show" && strCommand != "getvotes")) throw runtime_error( "mnfinalbudget \"command\"... ( \"passphrase\" )\n" "Vote or show current budgets\n" "\nAvailable commands:\n" " vote-many - Vote on a finalized budget\n" " vote - Vote on a finalized budget\n" " show - Show existing finalized budgets\n" " getvotes - Get vote information for each finalized budget\n"); if (strCommand == "vote-many") { if (params.size() != 2) throw runtime_error("Correct usage is 'mnfinalbudget vote-many BUDGET_HASH'"); std::string strHash = params[1].get_str(); uint256 hash(strHash); int success = 0; int failed = 0; UniValue resultsObj(UniValue::VOBJ); BOOST_FOREACH (CMasternodeConfig::CMasternodeEntry mne, masternodeConfig.getEntries()) { std::string errorMessage; std::vector<unsigned char> vchMasterNodeSignature; std::string strMasterNodeSignMessage; CPubKey pubKeyCollateralAddress; CKey keyCollateralAddress; CPubKey pubKeyMasternode; CKey keyMasternode; UniValue statusObj(UniValue::VOBJ); if (!masternodeSigner.SetKey(mne.getPrivKey(), errorMessage, keyMasternode, pubKeyMasternode)) { failed++; statusObj.push_back(Pair("result", "failed")); statusObj.push_back(Pair("errorMessage", "Masternode signing error, could not set key correctly: " + errorMessage)); resultsObj.push_back(Pair(mne.getAlias(), statusObj)); continue; } CMasternode* pmn = mnodeman.Find(pubKeyMasternode); if (pmn == NULL) { failed++; statusObj.push_back(Pair("result", "failed")); statusObj.push_back(Pair("errorMessage", "Can't find masternode by pubkey")); resultsObj.push_back(Pair(mne.getAlias(), statusObj)); continue; } CFinalizedBudgetVote vote(pmn->vin, hash); if (!vote.Sign(keyMasternode, pubKeyMasternode)) { failed++; statusObj.push_back(Pair("result", "failed")); statusObj.push_back(Pair("errorMessage", "Failure to sign.")); resultsObj.push_back(Pair(mne.getAlias(), statusObj)); continue; } std::string strError = ""; if (budget.UpdateFinalizedBudget(vote, NULL, strError)) { budget.mapSeenFinalizedBudgetVotes.insert(make_pair(vote.GetHash(), vote)); vote.Relay(); success++; statusObj.push_back(Pair("result", "success")); } else { failed++; statusObj.push_back(Pair("result", strError.c_str())); } resultsObj.push_back(Pair(mne.getAlias(), statusObj)); } UniValue returnObj(UniValue::VOBJ); returnObj.push_back(Pair("overall", strprintf("Voted successfully %d time(s) and failed %d time(s).", success, failed))); returnObj.push_back(Pair("detail", resultsObj)); return returnObj; } if (strCommand == "vote") { if (params.size() != 2) throw runtime_error("Correct usage is 'mnfinalbudget vote BUDGET_HASH'"); std::string strHash = params[1].get_str(); uint256 hash(strHash); CPubKey pubKeyMasternode; CKey keyMasternode; std::string errorMessage; if (!masternodeSigner.SetKey(strMasterNodePrivKey, errorMessage, keyMasternode, pubKeyMasternode)) return "Error upon calling SetKey"; CMasternode* pmn = mnodeman.Find(activeMasternode.vin); if (pmn == NULL) { return "Failure to find masternode in list : " + activeMasternode.vin.ToString(); } CFinalizedBudgetVote vote(activeMasternode.vin, hash); if (!vote.Sign(keyMasternode, pubKeyMasternode)) { return "Failure to sign."; } std::string strError = ""; if (budget.UpdateFinalizedBudget(vote, NULL, strError)) { budget.mapSeenFinalizedBudgetVotes.insert(make_pair(vote.GetHash(), vote)); vote.Relay(); return "success"; } else { return "Error voting : " + strError; } } if (strCommand == "show") { UniValue resultObj(UniValue::VOBJ); std::vector<CFinalizedBudget*> winningFbs = budget.GetFinalizedBudgets(); BOOST_FOREACH (CFinalizedBudget* finalizedBudget, winningFbs) { UniValue bObj(UniValue::VOBJ); bObj.push_back(Pair("FeeTX", finalizedBudget->nFeeTXHash.ToString())); bObj.push_back(Pair("Hash", finalizedBudget->GetHash().ToString())); bObj.push_back(Pair("BlockStart", (int64_t)finalizedBudget->GetBlockStart())); bObj.push_back(Pair("BlockEnd", (int64_t)finalizedBudget->GetBlockEnd())); bObj.push_back(Pair("Proposals", finalizedBudget->GetProposals())); bObj.push_back(Pair("VoteCount", (int64_t)finalizedBudget->GetVoteCount())); bObj.push_back(Pair("Status", finalizedBudget->GetStatus())); std::string strError = ""; bObj.push_back(Pair("IsValid", finalizedBudget->IsValid(strError))); bObj.push_back(Pair("IsValidReason", strError.c_str())); resultObj.push_back(Pair(finalizedBudget->GetName(), bObj)); } return resultObj; } if (strCommand == "getvotes") { if (params.size() != 2) throw runtime_error("Correct usage is 'mnbudget getvotes budget-hash'"); std::string strHash = params[1].get_str(); uint256 hash(strHash); UniValue obj(UniValue::VOBJ); CFinalizedBudget* pfinalBudget = budget.FindFinalizedBudget(hash); if (pfinalBudget == NULL) return "Unknown budget hash"; std::map<uint256, CFinalizedBudgetVote>::iterator it = pfinalBudget->mapVotes.begin(); while (it != pfinalBudget->mapVotes.end()) { UniValue bObj(UniValue::VOBJ); bObj.push_back(Pair("nHash", (*it).first.ToString().c_str())); bObj.push_back(Pair("nTime", (int64_t)(*it).second.nTime)); bObj.push_back(Pair("fValid", (*it).second.fValid)); obj.push_back(Pair((*it).second.vin.prevout.ToStringShort(), bObj)); it++; } return obj; } return NullUniValue; } UniValue checkbudgets(const UniValue& params, bool fHelp) { if (fHelp || params.size() != 0) throw runtime_error( "checkbudgets\n" "\nInitiates a buddget check cycle manually\n" "\nExamples:\n" + HelpExampleCli("checkbudgets", "") + HelpExampleRpc("checkbudgets", "")); budget.CheckAndRemove(); return NullUniValue; }
[ "falcon@gmail.com" ]
falcon@gmail.com
d072e91650ee0c3d72a87ed63826fc484325ec78
0cd8bbc974b822c46b64712d3be53e9808a5c246
/10327.cpp
16ba1f24a93e15e1c9dadd8c230c76c6bfe39d50
[]
no_license
limon2009/ACM-UVA-Online-Judge-solution
b78e8f709c88e5db6fdac83a7bd5ec71f7ab00b0
0f86718d3c609e654a3c16a29e0f91620ac40cd1
refs/heads/master
2021-08-11T04:58:42.829356
2017-11-13T06:14:09
2017-11-13T06:14:09
110,505,263
1
3
null
null
null
null
UTF-8
C++
false
false
334
cpp
#include<stdio.h> int a[1010]; main () { int i,j,k,n,s; while(scanf("%d",&n) == 1) { for(i = 0; i<n; i++) scanf("%d",&a[i]); s = 0; for(i = 0; i<n-1; i++){ for(j = i+1; j<n; j++){ if(a[i]>a[j]) { s++; } } } printf("Minimum exchange operations : %d\n",s); s = 0; } return 0; }
[ "md.moniruzzaman@bjitgroup.com" ]
md.moniruzzaman@bjitgroup.com
88b1068ae4782529dd877d607a63e9b079022d85
9ecd0e78eb37bd88c55669ad9f35a35874802592
/CPP/git_console/git_console/TestTools.cpp
d16c905dd2036d40eb4ca8291cd981d02d3c1296
[]
no_license
chengyuhaohfs/GitHub
8df34ff2344588321c57bd712617519720a07d98
0cec9283068941d0e4b2cf924a7b1cc4e7f5dd04
refs/heads/master
2020-03-10T18:32:39.984313
2019-01-03T22:27:25
2019-01-03T22:27:25
129,528,168
0
0
null
null
null
null
GB18030
C++
false
false
3,932
cpp
#include "StdAfx.h" #include "TestTools.h" using std::cout; using std::endl; CTestTools::CTestTools(void) { } CTestTools::~CTestTools(void) { } CString CTestTools::GetCurDir() { CString csModuleFile = ""; DWORD dwRes = GetModuleFileName(AfxGetStaticModuleState()->m_hCurrentInstanceHandle, csModuleFile.GetBuffer(MAX_PATH), MAX_PATH); csModuleFile.ReleaseBuffer(); if (dwRes == 0) { cout << "Get current Module file failed!\n"; return csModuleFile; } return csModuleFile.Mid(0, csModuleFile.ReverseFind('\\') + 1); } void CTestTools::GetFileContent(CString csFile, CString &csContent) { { WIN32_FIND_DATA wData; ZeroMemory(&wData, sizeof(wData)); HANDLE hFile = FindFirstFile(csFile, &wData); if (INVALID_HANDLE_VALUE == hFile) { std::cout << "Can't find file " << csFile << std::endl; CloseHandle(hFile); return; } } CFile cfile; if (cfile.Open(csFile, CFile::modeRead)) { UINT fileSize = (UINT)cfile.GetLength(); char *chBuffer = new char[fileSize + 1]; ZeroMemory(chBuffer, fileSize + 1); UINT uiLen = cfile.Read(chBuffer, fileSize); if (uiLen == 0) { std::cout << "Read nothing from file " << csFile << std::endl; delete[] chBuffer; cfile.Close(); return; } csContent.Format("%s", chBuffer); delete[] chBuffer; cfile.Close(); } else { std::cout << "Can't open file " << csFile << std::endl; return; } } BOOL CTestTools::PickStringWithRegex(CString cstrRev, CStringArray &ca_finds, std::string strRegex) { std::string strRev = cstrRev.GetBuffer(cstrRev.GetLength()); cstrRev.ReleaseBuffer(); std::regex partten(strRegex); std::smatch match_value; bool bMatched = std::regex_search(strRev, match_value, partten); if (bMatched) { std::string strFind = match_value[0]; for (auto iter = match_value.begin(); iter != match_value.end(); iter++) { ca_finds.Add(iter->str().c_str()); } } else { return FALSE; } return TRUE; } void CTestTools::SplitCommentToLine(CString cstrRev, CStringArray &ca_lines) { int iStart = 0; for (int index = 0; index < cstrRev.GetLength(); index++) { if (cstrRev.GetAt(index) == '\n' || cstrRev.GetAt(index) == '\r') { while (cstrRev.GetAt(index) == '\n' || cstrRev.GetAt(index) == '\r') { index++; } CString cstr = cstrRev.Mid(iStart, index - iStart); iStart = index; ca_lines.Add(cstr); } } } void CTestTools::GroupByRegex(CStringArray &ca_lines, std::vector<std::string> parttens) { std::string strCurGroup = ""; std::string strCurRegex = ""; std::map<std::string, std::vector<std::string>> map_finds; for (int index = 0; index < ca_lines.GetSize(); index++) { CString cstr = ca_lines.GetAt(index); if (0 == cstr.Trim().GetLength()) { continue; } std::string str = cstr.GetBuffer(cstr.GetLength()); cstr.ReleaseBuffer(); // for (auto iter = parttens.begin(); iter != parttens.end(); iter++) // { // std::regex partten(*iter); // std::match_results<std::string::const_iterator> match_values; // if (std::regex_search(str, match_values, partten)) // { // strCurRegex = *iter; // // 如果匹配到则进入循环,直到遇到下一个匹配 // // } // } // 当匹配到第一个正则时写入,到遇到下一个时停止 { std::regex partten(parttens[0]); std::match_results<std::string::const_iterator> match_values; if ( std::regex_search(str, match_values, partten) ) { strCurGroup = str; continue; } if (strCurGroup.length() != 0 && 0 != str.length()) { map_finds[strCurGroup].push_back(str); } } // if (0 != str.length() && 0 != strCurRegex.length()) // { // map_finds[strCurRegex].push_back(str); // } } for (auto iter = map_finds.begin(); iter != map_finds.end(); iter++) { cout << iter->first << ":\n"; for (auto subiter = iter->second.begin(); subiter != iter->second.end(); subiter++) { cout << *subiter << endl; } } }
[ "chengyu1184789@163.com" ]
chengyu1184789@163.com
0369df7d9bdf16544bcaa89e9cf0a52eee4f5be0
1a8fd946c9226226edfe445c65f401e60c244b63
/cxx_linux_proc_info/main.cpp
9b0f2b4cf7a5c0cd916ad5ef75dae5a2da752b47
[ "MIT" ]
permissive
tobiashienzsch/examples
9500a7349764de81c1fd3e9d8d062f35537ab7cf
654b5dc1c76242b6829e24ec0aa454df61919bc7
refs/heads/master
2023-07-21T14:23:17.049413
2023-07-20T03:41:41
2023-07-20T03:41:41
254,099,949
0
0
null
null
null
null
UTF-8
C++
false
false
1,557
cpp
// #include <stdio.h> // #include <stdlib.h> // int main(int, char **) { // FILE *cpuinfo = fopen(, "rb"); // char *arg = 0; // size_t size = 0; // while (getdelim(&arg, &size, 0, cpuinfo) != -1) { // puts(arg); // } // free(arg); // fclose(cpuinfo); // return 0; // } #include <algorithm> #include <fstream> #include <iostream> #include <string> #include <unordered_map> /** * @brief Remove all leading spaces on the given string in place. */ auto LeftTrim(std::string &s) -> void { s.erase(s.begin(), std::find_if(s.begin(), s.end(), [](int ch) { return std::isspace(ch) == 0; })); } auto RightTrim(std::string &s) -> void { s.erase(std::find_if(s.rbegin(), s.rend(), [](int ch) { return std::isspace(ch) == 0; }) .base(), s.end()); } int main() { std::string line; std::ifstream myfile("/proc/cpuinfo"); if (!myfile.is_open()) { std::cout << "Unable to open file"; } std::unordered_map<std::string, std::string> map{}; while (getline(myfile, line)) { auto found = std::find(std::begin(line), std::end(line), ':'); if (found != std::end(line)) { auto key = std::string(std::begin(line), found); auto value = std::string(++found, line.end()); LeftTrim(key); RightTrim(key); LeftTrim(value); RightTrim(value); map.insert(std::make_pair(key, value)); } } myfile.close(); for (auto const &item : map) { std::cout << item.first << ": " << item.second << '\n'; } return 0; }
[ "post@tobias-hienzsch.de" ]
post@tobias-hienzsch.de
b1e9d9f0c549024beb17f43ed2e28bf9cda17a90
1162ee428955c2d130628bfd21aa6df8634cf5e6
/MFCBrowser/stdafx.cpp
72e0145127248d23329b377ec461edc685717ad5
[]
no_license
Charlie178268/MFCBrowser
ebc3379a8ba8939d218f21438bc54d80589e24db
d8d3c5b704a09aba4a581369a679ab60390f78fd
refs/heads/master
2021-01-22T03:18:16.724896
2017-05-25T05:37:44
2017-05-25T05:37:44
92,368,602
0
0
null
null
null
null
GB18030
C++
false
false
165
cpp
// stdafx.cpp : 只包括标准包含文件的源文件 // MFCBrowser.pch 将作为预编译头 // stdafx.obj 将包含预编译类型信息 #include "stdafx.h"
[ "1248603165@qq.com" ]
1248603165@qq.com
48be160567af38a9aa7d17e28b766fc06f105812
aab7eafab5efae62cb06c3a2b6c26fe08eea0137
/sweight_normdata/sweighting/NOFCME_2016_35TCK/src/fitAndSplotJpsiKDataForTraining.cpp
7301e63bbf95f279b3966437efa607774683dcd1
[]
no_license
Sally27/B23MuNu_backup
397737f58722d40e2a1007649d508834c1acf501
bad208492559f5820ed8c1899320136406b78037
refs/heads/master
2020-04-09T18:12:43.308589
2018-12-09T14:16:25
2018-12-09T14:16:25
160,504,958
0
1
null
null
null
null
UTF-8
C++
false
false
76,385
cpp
#include "fitAndSplotJpsiKDataForTraining.hpp" #include "RooRealVar.h" #include "RooDataSet.h" #include "RooWorkspace.h" #include "TFile.h" #include "RooPlot.h" #include "RooArgSet.h" #include "TCanvas.h" #include "TTree.h" #include "RooExponential.h" #include "RooAddPdf.h" #include "RooMinuit.h" #include "RooCBShape.h" #include "RooDataHist.h" #include "RooStats/SPlot.h" #include "TTreeFormula.h" #include "RooGaussian.h" #include "MyCB.hpp" #include "RooIpatia2.hpp" #include "TLegend.h" #include "TLine.h" void FitAndSplotJpsiKDataForTraining::makeSWeightedTree(string extracut, string label, string tuplename) { TFile fw(workspaceFileName.c_str()); RooWorkspace* workspaceFit = (RooWorkspace*)fw.Get("workspaceFit"); if(!workspaceFit) { cerr<<"ERROR: in function FitAndSplotJpsiKDataForTraining::makeSWeightedTree, no workspace found in file "<<workspaceFileName<<endl; return; } RooDataSet* data = (RooDataSet*)workspaceFit->data("data"); RooAbsPdf* model_total = workspaceFit->pdf("model"); RooRealVar* sig = workspaceFit->var("sig"); RooRealVar* bkg = workspaceFit->var("bkg"); RooRealVar* bkg2 = workspaceFit->var("bkg2"); if(!data || !model_total || !sig || !bkg || !bkg2) { cerr<<"ERROR: in function FitAndSplotJpsiKDataForTraining::makeSWeightedTree, error downloading stuff from workspace"<<endl; return; } TFile f( (datadir+"/"+tuplename).c_str()); TTree* t = (TTree*)f.Get(treename.c_str()); if(!t) { cerr<<"ERROR: in function FitAndSplotJpsiKDataForTraining::makeSWeightedTree, no tree "<<treename<<" found in "<<datadir<<"/"<<tuplename<<endl; return; } RooStats::SPlot wdata("wData", "wData", *data, model_total, RooArgList(*sig, *bkg, *bkg2)); double Bplus_MM; t->SetBranchAddress("Bplus_MM", &Bplus_MM); string nameNewFile("../Sweights/Data_WS_sweights_2012.root"); TFile f2(nameNewFile.c_str(), "RECREATE"); TTree* t2 = t->CloneTree(0); double sig_sw; double bkg_sw; double bkg2_sw; double event_sw; t2->Branch("sig_sw", &sig_sw, "sig_sw/D"); t2->Branch("bkg_sw", &bkg_sw, "bkg_sw/D"); t2->Branch("bkg2_sw", &bkg2_sw, "bkg2_sw/D"); t2->Branch("event_sw", &event_sw, "event_sw/D"); int j(0); if(data->sumEntries() == t->GetEntries(("Bplus_MM>"+d2s(Bplus_MM_min)+" && Bplus_MM <"+d2s(Bplus_MM_max)).c_str() ) ) { cout<<"Putting the sweights in the tree... Filling "<<data->sumEntries()<<" entries"<<endl; } else { cerr<<"ERROR: in function FitAndSplotJpsiKDataForTraining::makeSWeightedTree, mismatch in the number of entries"<<endl; cerr<<"data: "<<data->sumEntries()<<" entries. tuple: "<<t->GetEntries(("Bplus_MM>"+d2s(Bplus_MM_min)+" && Bplus_MM <"+d2s(Bplus_MM_max)).c_str())<<" entries."<<endl; } int nEntries(t->GetEntries()); if(extracut == "") extracut = "1"; TTreeFormula ttf( "ttf", extracut.c_str(), t); for(int i(0); i<nEntries; ++i) { t->GetEntry(i); if(i % (nEntries/10) == 0) cout<<100*i/nEntries<<"\% "<<flush; if(Bplus_MM > Bplus_MM_min && Bplus_MM < Bplus_MM_max) { sig_sw = wdata.GetSWeight(j,"sig"); bkg_sw = wdata.GetSWeight(j,"bkg"); bkg2_sw = wdata.GetSWeight(j,"bkg2"); event_sw= sig_sw+bkg_sw+bkg2_sw; if(ttf.EvalInstance()) t2->Fill(); ++j; } } t2->Write("", TObject::kOverwrite); f2.Close(); fw.Close(); f.Close(); } void FitAndSplotJpsiKDataForTraining::GetYields(string dataset,string tag) { cout<<"Plotting result of the fit"<<endl; TFile fw(workspaceFileName.c_str()); RooWorkspace* workspaceFit = (RooWorkspace*)fw.Get("workspaceFit"); if(!workspaceFit) { cerr<<"ERROR: in function FitAndSplotJpsiKDataForTraining::plot, no workspace found in file "<<workspaceFileName<<endl; return; } RooRealVar* Bplus_MM = workspaceFit->var("Bplus_MM"); RooDataSet* data = (RooDataSet*)workspaceFit->data("data"); RooAbsPdf* model_total = workspaceFit->pdf("model"); RooRealVar* num_sig = workspaceFit->var("sig"); RooRealVar* num_misid = workspaceFit->var("bkg"); RooRealVar* num_exp = workspaceFit->var("bkg2"); if(!data || !Bplus_MM || !model_total) { cerr<<"ERROR: in function FitAndSplotJpsiKDataForTraining::plot, error downloading stuff from workspace"<<endl; cout<<Bplus_MM<<" "<<data<<" "<<model_total<<endl; return; } if(!data || !num_exp || !num_sig || !num_misid) { cerr<<"ERROR: in function FitAndSplotB23MuNuDataForTraining::plot, error downloading stuff from workspace"<<endl; // cout<<Bplus_Corrected_Mass<<" "<<data<<" "<<endl; return; } string tags=dataset; ofstream out; out.open(("../FOM/FOM_"+dataset+"_"+tag+".txt").c_str()); out<<"\\begin{table}[h]"<<endl; out<<"\\begin{center}"<<endl; out<<"\\begin{tabular}{| l | l | l | l |}"<<endl; out<<"\\hline"<<endl; out<<"Sample & cut & 3fb$^{-1}$ \\\\ "<<endl; out<<"B^{+} \\rightarrow J/#psi K^{+} & "<<tags<<" & "<< num_sig->getVal() <<"\\pm"<<num_sig->getError() <<" \\\\ "<<endl; out<<"B^{+} \\rightarrow J/#psi #pi^{+} & "<<tags<<" & "<< num_misid->getVal() <<"\\pm"<<num_misid->getError() <<" \\\\ " <<endl; out<<"Combinatorial & "<<tags<<" & "<< num_exp->getVal() <<"\\pm"<<num_exp->getError() <<" \\\\ "<<endl; out<<"\\hline"<<endl; out<<"\\end{tabular}"<<endl; out<<"\\end{center}"<<endl; out<<"\\caption{STATISTICS.txt}"<<endl; out<<"\\end{table}"<<endl; TFile *fillinfo = new TFile(("../FitResults/FitControl_"+dataset+"_"+tag+".root").c_str(),"RECREATE"); TTree *fillinfotree = new TTree(("FitControl_"+dataset).c_str(),("FitControl_"+dataset).c_str()); FillEffInfo(fillinfotree, "JpsikEv",double(num_sig->getVal()),false); FillEffInfo(fillinfotree, "NumNormObs_Err",double(num_sig->getError()),true); FillEffInfo(fillinfotree, "NumNormObs",double(num_sig->getVal()),true); fillinfo->cd(); fillinfotree->Write("",TObject::kOverwrite); delete fillinfotree; delete fillinfo; } void FitAndSplotJpsiKDataForTraining::plotprettyhypathia3(string dataset) { cout<<"Plotting result of the fit"<<endl; TFile fw(workspaceFileName.c_str()); RooWorkspace* workspaceFit = (RooWorkspace*)fw.Get("workspaceFit"); if(!workspaceFit) { cerr<<"ERROR: in function FitAndSplotJpsiKDataForTraining::plot, no workspace found in file "<<workspaceFileName<<endl; return; } RooRealVar* Bplus_MM = workspaceFit->var("Bplus_MM"); RooDataSet* data = (RooDataSet*)workspaceFit->data("data"); RooAbsPdf* model_total = workspaceFit->pdf("model"); if(!data || !Bplus_MM || !model_total) { cerr<<"ERROR: in function FitAndSplotJpsiKDataForTraining::plot, error downloading stuff from workspace"<<endl; cout<<Bplus_MM<<" "<<data<<" "<<model_total<<endl; return; } RooPlot* frame = Bplus_MM->frame(); data->plotOn(frame); model_total->plotOn(frame, RooFit::LineColor(kRed) ); savePullPlot(*frame, plotdir+"pullPlot.root"); TFile fpull((plotdir+"pullPlot.root").c_str()); TCanvas* cpull = (TCanvas*)fpull.Get("pullplot"); // model_total->paramOn(frame); model_total->plotOn(frame, RooFit::LineColor(kGreen), RooFit::Components("expo"), RooFit::Name("combinatorial")); model_total->plotOn(frame, RooFit::LineColor(kBlue), RooFit::Components("cb1"), RooFit::Name("signal")); model_total->plotOn(frame, RooFit::LineColor(kMagenta), RooFit::Components("piblah"), RooFit::Name("pimumu")); TLegend *leg = new TLegend(0.7,0.7,0.9,0.9); leg->AddEntry(frame->findObject("combinatorial"),"Combinatorial","l"); leg->AddEntry(frame->findObject("signal"),"B^{+} #rightarrow J/#psi K^{+}","l"); leg->AddEntry(frame->findObject("pimumu"),"B^{+} #rightarrow J/#psi #pi^{+}","l"); TCanvas canv("canv", "canv", 600, 600); frame->GetXaxis()->SetTitle("m(J/#psi K^{+})"); frame->SetMinimum(0.1); frame->Draw(); leg->Draw("same"); TCanvas canvTot("canvTot", "canvTot", 600, 600); canvTot.Divide(1,2); canvTot.cd(1); gPad->SetPad(0.005, 0.205, 0.995, 0.995); canv.DrawClonePad(); canvTot.cd(2); gPad->SetPad(0.005, 0.005, 0.995, 0.2); cpull->DrawClonePad(); canvTot.Print((plotdir+"HypatiaplotJpsiKFitPretty"+dataset+".pdf").c_str()); canvTot.Print((plotdir+"HypatiaplotJpsiKFitPretty"+dataset+".root").c_str()); canv.SetLogy(); canvTot.cd(1); canv.DrawClonePad(); canvTot.Print((plotdir+"HypatiaplotJpsiKFitLogyPretty"+dataset+".pdf").c_str()); canvTot.Print((plotdir+"HypatiaplotJpsiKFitLogyPretty"+dataset+".root").c_str()); fw.Close(); fpull.Close(); } void FitAndSplotJpsiKDataForTraining::plotprettyhypathia(string dataset) { cout<<"Plotting result of the fit"<<endl; TFile fw(workspaceFileName.c_str()); RooWorkspace* workspaceFit = (RooWorkspace*)fw.Get("workspaceFit"); if(!workspaceFit) { cerr<<"ERROR: in function FitAndSplotJpsiKDataForTraining::plot, no workspace found in file "<<workspaceFileName<<endl; return; } RooRealVar* Bplus_MM = workspaceFit->var("Bplus_MM"); RooDataSet* data = (RooDataSet*)workspaceFit->data("data"); RooAbsPdf* model_total = workspaceFit->pdf("model"); if(!data || !Bplus_MM || !model_total) { cerr<<"ERROR: in function FitAndSplotJpsiKDataForTraining::plot, error downloading stuff from workspace"<<endl; cout<<Bplus_MM<<" "<<data<<" "<<model_total<<endl; return; } RooPlot* frame = Bplus_MM->frame(); data->plotOn(frame); model_total->plotOn(frame, RooFit::LineColor(kRed) ); savePullPlot(*frame, plotdir+"pullPlot.root"); TFile fpull((plotdir+"pullPlot.root").c_str()); TCanvas* cpull = (TCanvas*)fpull.Get("pullplot"); // model_total->paramOn(frame); model_total->plotOn(frame, RooFit::LineColor(kGreen), RooFit::Components("expo"), RooFit::Name("combinatorial")); model_total->plotOn(frame, RooFit::LineColor(kBlue), RooFit::Components("cb1"), RooFit::Name("signal")); TLegend *leg = new TLegend(0.7,0.7,0.9,0.9); leg->AddEntry(frame->findObject("combinatorial"),"Combinatorial","l"); leg->AddEntry(frame->findObject("signal"),"B^{+} -> J/#psi K^{+}","l"); TCanvas canv("canv", "canv", 600, 600); frame->GetXaxis()->SetTitle("m(J/#psi K^{+})"); frame->Draw(); leg->Draw("same"); TCanvas canvTot("canvTot", "canvTot", 600, 600); canvTot.Divide(1,2); canvTot.cd(1); gPad->SetPad(0.005, 0.205, 0.995, 0.995); canv.DrawClonePad(); canvTot.cd(2); gPad->SetPad(0.005, 0.005, 0.995, 0.2); cpull->DrawClonePad(); canvTot.Print((plotdir+"HypatiaplotJpsiKFitPretty"+dataset+".pdf").c_str()); canvTot.Print((plotdir+"HypatiaplotJpsiKFitPretty"+dataset+".root").c_str()); canv.SetLogy(); canvTot.cd(1); canv.DrawClonePad(); canvTot.Print((plotdir+"HypatiaplotJpsiKFitLogyPretty"+dataset+".pdf").c_str()); canvTot.Print((plotdir+"HypatiaplotJpsiKFitLogyPretty"+dataset+".root").c_str()); fw.Close(); fpull.Close(); } void FitAndSplotJpsiKDataForTraining::plotpretty() { cout<<"Plotting result of the fit"<<endl; TFile fw(workspaceFileName.c_str()); RooWorkspace* workspaceFit = (RooWorkspace*)fw.Get("workspaceFit"); if(!workspaceFit) { cerr<<"ERROR: in function FitAndSplotJpsiKDataForTraining::plot, no workspace found in file "<<workspaceFileName<<endl; return; } RooRealVar* Bplus_MM = workspaceFit->var("Bplus_MM"); RooDataSet* data = (RooDataSet*)workspaceFit->data("data"); RooAbsPdf* model_total = workspaceFit->pdf("model"); if(!data || !Bplus_MM || !model_total) { cerr<<"ERROR: in function FitAndSplotJpsiKDataForTraining::plot, error downloading stuff from workspace"<<endl; cout<<Bplus_MM<<" "<<data<<" "<<model_total<<endl; return; } RooPlot* frame = Bplus_MM->frame(); data->plotOn(frame); model_total->plotOn(frame, RooFit::LineColor(kRed) ); savePullPlot(*frame, plotdir+"pullPlot.root"); TFile fpull((plotdir+"pullPlot.root").c_str()); TCanvas* cpull = (TCanvas*)fpull.Get("pullplot"); // model_total->paramOn(frame); model_total->plotOn(frame, RooFit::LineColor(kGreen), RooFit::Components("expo"), RooFit::Name("combinatorial")); model_total->plotOn(frame, RooFit::LineColor(kBlue), RooFit::Components("cb1"), RooFit::Name("signal")); TLegend *leg = new TLegend(0.7,0.7,0.9,0.9); leg->AddEntry(frame->findObject("combinatorial"),"Combinatorial","l"); leg->AddEntry(frame->findObject("signal"),"B^{+} -> J/#psi K^{+}","l"); TCanvas canv("canv", "canv", 600, 600); frame->GetXaxis()->SetTitle("m(J/#psi K^{+})"); frame->Draw(); leg->Draw("same"); TCanvas canvTot("canvTot", "canvTot", 600, 600); canvTot.Divide(1,2); canvTot.cd(1); gPad->SetPad(0.005, 0.205, 0.995, 0.995); canv.DrawClonePad(); canvTot.cd(2); gPad->SetPad(0.005, 0.005, 0.995, 0.2); cpull->DrawClonePad(); canvTot.Print((plotdir+"plotJpsiKFitPretty.pdf").c_str()); canvTot.Print((plotdir+"plotJpsiKFitPretty.root").c_str()); canv.SetLogy(); canvTot.cd(1); canv.DrawClonePad(); canvTot.Print((plotdir+"plotJpsiKFitLogyPretty.pdf").c_str()); canvTot.Print((plotdir+"plotJpsiKFitLogyPretty.root").c_str()); fw.Close(); fpull.Close(); } vector<double> FitAndSplotJpsiKDataForTraining::pimumufitweight(bool binnedFit, string type, string pimumufilename, string weightname, bool weighted) { cout<<"Start Signal Component fit"<<endl; RooRealVar Bplus_Corrected_Mass("Bplus_MM","Bplus_MM",Bplus_MM_min,Bplus_MM_max); RooRealVar Bplus_corMassERR("Bplus_corMassERR","Bplus_corMassERR",0,600); RooRealVar weightnamevar(weightname.c_str(),weightname.c_str(), 0.0 ,1.0); TFile* f = new TFile((pimumufilename+type+".root").c_str()); TTree* t = (TTree*)f->Get("DecayTree"); t->SetBranchStatus("*", 0); t->SetBranchStatus("Bplus_MM", 1); RooDataSet dr("dr","dr", RooArgSet(Bplus_Corrected_Mass), Import(*t)); if (weighted==true) { RooDataSet dr("dr","dr", RooArgSet(Bplus_Corrected_Mass,weightnamevar), Import(*t), WeightVar(weightname.c_str())); } dr.Print(); RooRealVar cbmeanrar(("picbmeanrar_"+type).c_str(),("cbmeanrar"+type).c_str(), 5331.0, 5320.8, 5340.0); RooRealVar cbsigmarar(("picbsigmarar_"+type).c_str(),("cbsigmarar"+type).c_str(),8.6,0.1,60);//,0.1,50) ; RooRealVar cbsignalrar(("picbsignalrar_"+type).c_str(),("cbsignalrar"+type).c_str(),5.0,0.0,10.0) ; RooRealVar nral(("pinral_"+type).c_str(),"",1.0,0.1,3.0); RooRealVar alpharal(("pialpharal_"+type).c_str(),"",1.0,0.1,5.0); RooRealVar nrar(("pinrar_"+type).c_str(),"",1.0,0.1,5.0); RooRealVar alpharar(("pialpharar_"+type).c_str(),"",1.0,0.1,10.0); MyCB blah(("piblah_"+type).c_str(), ("piblah"+type).c_str(), Bplus_Corrected_Mass, cbmeanrar, cbsigmarar, nral , alpharal, nrar, alpharar); RooPlot* frame8 = Bplus_Corrected_Mass.frame(Title("Unbinned fit with double ccrystal ball function")) ; dr.plotOn(frame8); // blah.fitTo(dr); Bplus_Corrected_Mass.setBins(100); RooDataHist* bdata; if(binnedFit) bdata = dr.binnedClone("binned", "binned") ; //fit the stuff RooAbsReal* nll; if(binnedFit) nll = blah.createNLL(*bdata, RooFit::NumCPU(8) ) ; if(!binnedFit) nll = blah.createNLL(dr, RooFit::NumCPU(8) ) ; RooMinuit m(*nll); m.migrad(); m.hesse(); m.minos(); blah.plotOn(frame8,DataError(RooAbsData::SumW2)); RooPlot* frameun = Bplus_Corrected_Mass.frame(Title("Unbinned fit with double ccrystal ball function")) ; dr.plotOn(frameun); blah.plotOn(frameun,DataError(RooAbsData::SumW2)); blah.paramOn(frameun); vector<double> myresults; cout<<"MBplus_Corrected_Mass fitted values:"<<endl; cout<<cbmeanrar.getVal()<<endl; cout<<cbsigmarar.getVal()<<endl; cout<<cbsignalrar.getVal()<<endl; cout<<nral.getVal()<<endl; cout<<alpharal.getVal()<<endl; cout<<nrar.getVal()<<endl; cout<<alpharar.getVal()<<endl; myresults.push_back(cbmeanrar.getVal()); myresults.push_back(cbsigmarar.getVal()); myresults.push_back(nral.getVal()); myresults.push_back(alpharal.getVal()); myresults.push_back(nrar.getVal()); myresults.push_back(alpharar.getVal()); //cbmeanrar.setConstant(); //cbsigmarar.setConstant(); cbsignalrar.setConstant(); nral.setConstant(); alpharal.setConstant(); nrar.setConstant(); alpharar.setConstant(); //C a l c u l a t e chi squared // cout<<"Chi squared: "<< frame8->chiSquare() <<endl; RooHist* hresid = frame8->residHist(); RooHist* hpull = frame8->pullHist(); RooPlot* frame9 = Bplus_Corrected_Mass.frame(Title("Residual Distribution")); frame9->addPlotable(hresid,"P"); RooPlot* frame10 = Bplus_Corrected_Mass.frame(Title("Pull Distribution")) ; frame10->addPlotable(hpull,"P"); TCanvas* canv4 = new TCanvas("mBplus_Corrected_Massattempt5","mBplus_Corrected_Massattempt5",800,800) ; canv4->Divide(2,2) ; canv4->cd(1) ; gPad->SetLeftMargin(0.15) ; frame8->GetYaxis()->SetTitleOffset(1.4) ; frame8->Draw() ; canv4->cd(2) ; gPad->SetLeftMargin(0.15) ; frame9->GetYaxis()->SetTitleOffset(1.4) ; frame9->Draw() ; canv4->cd(3) ; gPad->SetLeftMargin(0.15) ; frame10->GetYaxis()->SetTitleOffset(1.4) ; frame10->Draw() ; canv4->cd(4) ; gPad->SetLeftMargin(0.15) ; frameun->GetYaxis()->SetTitleOffset(1.4) ; frameun->Draw() ; canv4->SaveAs((plotdir+"mcpimumu_NOTMAIN_WEIGHT_"+type+".pdf").c_str()); TCanvas* canvlog = new TCanvas("pimumu","pimumu",600,600) ; frameun->Draw(); TCanvas canvTot("canvTot", "canvTot", 600, 600); canvTot.Divide(1,2); canvTot.cd(1); gPad->SetPad(0.005, 0.205, 0.995, 0.995); canvlog->DrawClonePad(); delete canvlog; savePullPlot(*frameun, plotdir+"pullPlot_pi.root"); TFile fpull((plotdir+"pullPlot_pi.root").c_str()); TCanvas* cpull = (TCanvas*)fpull.Get("pullplot"); canvTot.cd(2); gPad->SetPad(0.005, 0.005, 0.995, 0.2); gPad->SetLeftMargin(0.15) ; cpull->DrawClonePad(); canvTot.Print((plotdir+"mcpimumu_NOTMAIN_WEIGHT_moreinfo_"+type+".pdf").c_str()); canvTot.Print((plotdir+"mcpimumu_NOTMAIN_WEIGHT_moreinfo_"+type+".root").c_str()); TCanvas* canvnew = new TCanvas("signalplot","mBplus_Corrected_Massnew",800,800) ; gPad->SetLeftMargin(0.15) ; frame8->GetYaxis()->SetTitleOffset(1.4) ; frame8->Draw() ; TFile *fm = new TFile((plotdir+"plotpimumuWEIGHT_"+type+".root").c_str(),"RECREATE"); canvnew->Write(); fm->Close(); delete fm; delete canvnew; RooWorkspace *w8 = new RooWorkspace("w","workspace"); // string namews8="pimumu"; TFile wrkspc8((plotdir+"myworkspaceWEIGHT_"+namews8+"_"+type+".root").c_str(),"RECREATE"); w8->import(Bplus_Corrected_Mass); // w8->import(weightnamevar); w8->import(dr); w8->import(blah); cout<<"Signal workspace"<<endl; w8->Print(); w8->Write(); wrkspc8.Write(); delete canv4; return(myresults); } vector<double> FitAndSplotJpsiKDataForTraining::pimumufitnoweight(string type, string pimumufilename) { cout<<"Start Signal Component fit"<<endl; RooRealVar Bplus_Corrected_Mass("Bplus_MM","Bplus_MM",5150,5450); // RooRealVar Bplus_corMassERR("Bplus_corMassERR","Bplus_corMassERR",0,600); // RooRealVar weightnamevar(weightname.c_str(),weightname.c_str(), 0.0 ,1.0); TFile* f = new TFile((pimumufilename+type+".root").c_str()); TTree* t = (TTree*)f->Get("DecayTree"); RooDataSet dr("dr","dr", RooArgSet(Bplus_Corrected_Mass), Import(*t)); dr.Print(); RooRealVar cbmeanrar(("picbmeanrar_"+type).c_str(),("cbmeanrar"+type).c_str(), 5283.0, 5200.8, 5350.0); RooRealVar cbsigmarar(("picbsigmarar_"+type).c_str(),("cbsigmarar"+type).c_str(),8.6,0.1,60);//,0.1,50) ; RooRealVar cbsignalrar(("picbsignalrar_"+type).c_str(),("cbsignalrar"+type).c_str(),5.0,0.0,10.0) ; RooRealVar nral(("pinral_"+type).c_str(),"",1.0,0.1,3.0); RooRealVar alpharal(("pialpharal_"+type).c_str(),"",1.0,0.1,5.0); RooRealVar nrar(("pinrar_"+type).c_str(),"",1.0,0.1,5.0); RooRealVar alpharar(("pialpharar_"+type).c_str(),"",1.0,0.1,10.0); MyCB blah(("piblah_"+type).c_str(), ("piblah"+type).c_str(), Bplus_Corrected_Mass, cbmeanrar, cbsigmarar, nral , alpharal, nrar, alpharar); RooPlot* frame8 = Bplus_Corrected_Mass.frame(Title("Unbinned fit with double ccrystal ball function")) ; dr.plotOn(frame8); blah.fitTo(dr); blah.plotOn(frame8,DataError(RooAbsData::SumW2)); RooPlot* frameun = Bplus_Corrected_Mass.frame(Title("Unbinned fit with double ccrystal ball function")) ; dr.plotOn(frameun); blah.plotOn(frameun,DataError(RooAbsData::SumW2)); blah.paramOn(frameun); vector<double> myresults; cout<<"MBplus_Corrected_Mass fitted values:"<<endl; cout<<cbmeanrar.getVal()<<endl; cout<<cbsigmarar.getVal()<<endl; cout<<cbsignalrar.getVal()<<endl; cout<<nral.getVal()<<endl; cout<<alpharal.getVal()<<endl; cout<<nrar.getVal()<<endl; cout<<alpharar.getVal()<<endl; myresults.push_back(cbmeanrar.getVal()); myresults.push_back(cbsigmarar.getVal()); myresults.push_back(nral.getVal()); myresults.push_back(alpharal.getVal()); myresults.push_back(nrar.getVal()); myresults.push_back(alpharar.getVal()); cbmeanrar.setConstant(); //cbsigmarar.setConstant(); cbsignalrar.setConstant(); nral.setConstant(); alpharal.setConstant(); nrar.setConstant(); alpharar.setConstant(); //C a l c u l a t e chi squared // cout<<"Chi squared: "<< frame8->chiSquare() <<endl; RooHist* hresid = frame8->residHist(); RooHist* hpull = frame8->pullHist(); RooPlot* frame9 = Bplus_Corrected_Mass.frame(Title("Residual Distribution")); frame9->addPlotable(hresid,"P"); RooPlot* frame10 = Bplus_Corrected_Mass.frame(Title("Pull Distribution")) ; frame10->addPlotable(hpull,"P"); TCanvas* canv4 = new TCanvas("mBplus_Corrected_Massattempt5","mBplus_Corrected_Massattempt5",800,800) ; canv4->Divide(2,2) ; canv4->cd(1) ; gPad->SetLeftMargin(0.15) ; frame8->GetYaxis()->SetTitleOffset(1.4) ; frame8->Draw() ; canv4->cd(2) ; gPad->SetLeftMargin(0.15) ; frame9->GetYaxis()->SetTitleOffset(1.4) ; frame9->Draw() ; canv4->cd(3) ; gPad->SetLeftMargin(0.15) ; frame10->GetYaxis()->SetTitleOffset(1.4) ; frame10->Draw() ; canv4->cd(4) ; gPad->SetLeftMargin(0.15) ; frameun->GetYaxis()->SetTitleOffset(1.4) ; frameun->Draw() ; canv4->SaveAs((plotdir+"mcpimumu_NOTMAIN_NOWEIGHT_"+type+".pdf").c_str()); TCanvas* canvnew = new TCanvas("signalplot","mBplus_Corrected_Massnew",800,800) ; gPad->SetLeftMargin(0.15) ; frame8->GetYaxis()->SetTitleOffset(1.4) ; frame8->Draw() ; TFile *fm = new TFile((plotdir+"plotpimumuNOWEIGHT_"+type+".root").c_str(),"RECREATE"); canvnew->Write(); fm->Close(); delete fm; delete canvnew; RooWorkspace *w8 = new RooWorkspace("w","workspace"); // string namews8="pimumu"; TFile wrkspc8((plotdir+"myworkspaceNOWEIGHT_"+namews8+"_"+type+".root").c_str(),"RECREATE"); w8->import(Bplus_Corrected_Mass); // w8->import(weightnamevar); w8->import(dr); w8->import(blah); cout<<"Signal workspace"<<endl; w8->Print(); w8->Write(); wrkspc8.Write(); delete canv4; return(myresults); } vector<double> FitAndSplotJpsiKDataForTraining::sigfitnoweight(string type, string mcfilename) { cout<<"Start Signal Component fit"<<endl; RooRealVar Bplus_Corrected_Mass("Bplus_MM","Bplus_MM",5150,5450); // RooRealVar Bplus_corMassERR("Bplus_corMassERR","Bplus_corMassERR",0,600); // RooRealVar weightnamevar(weightname.c_str(),weightname.c_str(), 0.0 ,1.0); TFile* f = new TFile((mcfilename+type+".root").c_str()); TTree* t = (TTree*)f->Get("DecayTree"); RooDataSet dr("dr","dr", RooArgSet(Bplus_Corrected_Mass), Import(*t)); dr.Print(); RooRealVar cbmeanrar(("cbmeanrar_"+type).c_str(),("cbmeanrar"+type).c_str(), 5283.0, 5280.8, 5290.0); RooRealVar cbsigmarar(("cbsigmarar_"+type).c_str(),("cbsigmarar"+type).c_str(),8.6,0.1,20);//,0.1,50) ; RooRealVar cbsignalrar(("cbsignalrar_"+type).c_str(),("cbsignalrar"+type).c_str(),5.0,0.0,10.0) ; RooRealVar nral(("nral_"+type).c_str(),"",1.0,0.1,3.0); RooRealVar alpharal(("alpharal_"+type).c_str(),"",1.0,0.1,5.0); RooRealVar nrar(("nrar_"+type).c_str(),"",1.0,0.1,5.0); RooRealVar alpharar(("alpharar_"+type).c_str(),"",1.0,0.1,5.0); MyCB blah(("blah_"+type).c_str(), ("blah"+type).c_str(), Bplus_Corrected_Mass, cbmeanrar, cbsigmarar, nral , alpharal, nrar, alpharar); RooPlot* frame8 = Bplus_Corrected_Mass.frame(Title("Unbinned fit with double ccrystal ball function")) ; dr.plotOn(frame8); blah.fitTo(dr); blah.plotOn(frame8,DataError(RooAbsData::SumW2)); RooPlot* frameun = Bplus_Corrected_Mass.frame(Title("Unbinned fit with double ccrystal ball function")) ; dr.plotOn(frameun); blah.plotOn(frameun,DataError(RooAbsData::SumW2)); blah.paramOn(frameun); vector<double> myresults; cout<<"MBplus_Corrected_Mass fitted values:"<<endl; cout<<cbmeanrar.getVal()<<endl; cout<<cbsigmarar.getVal()<<endl; cout<<cbsignalrar.getVal()<<endl; cout<<nral.getVal()<<endl; cout<<alpharal.getVal()<<endl; cout<<nrar.getVal()<<endl; cout<<alpharar.getVal()<<endl; myresults.push_back(cbmeanrar.getVal()); myresults.push_back(cbsigmarar.getVal()); myresults.push_back(nral.getVal()); myresults.push_back(alpharal.getVal()); myresults.push_back(nrar.getVal()); myresults.push_back(alpharar.getVal()); cbmeanrar.setConstant(); cbsigmarar.setConstant(); cbsignalrar.setConstant(); nral.setConstant(); alpharal.setConstant(); nrar.setConstant(); alpharar.setConstant(); //C a l c u l a t e chi squared // cout<<"Chi squared: "<< frame8->chiSquare() <<endl; RooHist* hresid = frame8->residHist(); RooHist* hpull = frame8->pullHist(); RooPlot* frame9 = Bplus_Corrected_Mass.frame(Title("Residual Distribution")); frame9->addPlotable(hresid,"P"); RooPlot* frame10 = Bplus_Corrected_Mass.frame(Title("Pull Distribution")) ; frame10->addPlotable(hpull,"P"); TCanvas* canv4 = new TCanvas("mBplus_Corrected_Massattempt5","mBplus_Corrected_Massattempt5",800,800) ; canv4->Divide(2,2) ; canv4->cd(1) ; gPad->SetLeftMargin(0.15) ; frame8->GetYaxis()->SetTitleOffset(1.4) ; frame8->Draw() ; canv4->cd(2) ; gPad->SetLeftMargin(0.15) ; frame9->GetYaxis()->SetTitleOffset(1.4) ; frame9->Draw() ; canv4->cd(3) ; gPad->SetLeftMargin(0.15) ; frame10->GetYaxis()->SetTitleOffset(1.4) ; frame10->Draw() ; canv4->cd(4) ; gPad->SetLeftMargin(0.15) ; frameun->GetYaxis()->SetTitleOffset(1.4) ; frameun->Draw() ; canv4->SaveAs((plotdir+"mcsigfit_NOTMAIN_NOWEIGHT_"+type+".pdf").c_str()); TCanvas* canvnew = new TCanvas("signalplot","mBplus_Corrected_Massnew",800,800) ; gPad->SetLeftMargin(0.15) ; frame8->GetYaxis()->SetTitleOffset(1.4) ; frame8->Draw() ; TFile *fm = new TFile((plotdir+"plotsigNOWEIGHT_"+type+".root").c_str(),"RECREATE"); canvnew->Write(); fm->Close(); delete fm; delete canvnew; RooWorkspace *w8 = new RooWorkspace("w","workspace"); // string namews8="signal"; TFile wrkspc8((plotdir+"myworkspaceNOWEIGHT_"+namews8+"_"+type+".root").c_str(),"RECREATE"); w8->import(Bplus_Corrected_Mass); // w8->import(weightnamevar); w8->import(dr); w8->import(blah); cout<<"Signal workspace"<<endl; w8->Print(); w8->Write(); wrkspc8.Write(); delete canv4; return(myresults); } void FitAndSplotJpsiKDataForTraining::plot() { cout<<"Plotting result of the fit"<<endl; TFile fw(workspaceFileName.c_str()); RooWorkspace* workspaceFit = (RooWorkspace*)fw.Get("workspaceFit"); if(!workspaceFit) { cerr<<"ERROR: in function FitAndSplotJpsiKDataForTraining::plot, no workspace found in file "<<workspaceFileName<<endl; return; } RooRealVar* Bplus_MM = workspaceFit->var("Bplus_MM"); RooDataSet* data = (RooDataSet*)workspaceFit->data("data"); RooAbsPdf* model_total = workspaceFit->pdf("model"); if(!data || !Bplus_MM || !model_total) { cerr<<"ERROR: in function FitAndSplotJpsiKDataForTraining::plot, error downloading stuff from workspace"<<endl; cout<<Bplus_MM<<" "<<data<<" "<<model_total<<endl; return; } RooPlot* frame = Bplus_MM->frame(); data->plotOn(frame); model_total->plotOn(frame, RooFit::LineColor(kRed) ); savePullPlot(*frame, plotdir+"pullPlot.root"); TFile fpull((plotdir+"pullPlot.root").c_str()); TCanvas* cpull = (TCanvas*)fpull.Get("pullplot"); model_total->paramOn(frame); model_total->plotOn(frame, RooFit::LineColor(kGreen), RooFit::Components("expo")); model_total->plotOn(frame, RooFit::LineColor(kBlue), RooFit::Components("cb1")); TCanvas canv("canv", "canv", 600, 600); frame->Draw(); TCanvas canvTot("canvTot", "canvTot", 600, 600); canvTot.Divide(1,2); canvTot.cd(1); gPad->SetPad(0.005, 0.205, 0.995, 0.995); canv.DrawClonePad(); canvTot.cd(2); gPad->SetPad(0.005, 0.005, 0.995, 0.2); cpull->DrawClonePad(); canvTot.Print((plotdir+"plotJpsiKFit.pdf").c_str()); canvTot.Print((plotdir+"plotJpsiKFit.root").c_str()); canv.SetLogy(); canvTot.cd(1); canv.DrawClonePad(); canvTot.Print((plotdir+"plotJpsiKFitLogy.pdf").c_str()); canvTot.Print((plotdir+"plotJpsiKFitLogy.root").c_str()); fw.Close(); fpull.Close(); } vector<double> FitAndSplotJpsiKDataForTraining::sigfithypathia(bool binnedFit,string weightname, string type, string mcfilename, string dataset, bool weighted) { cout<<"Start Signal Component fit"<<endl; RooRealVar Bplus_Corrected_Mass("Bplus_MM","Bplus_MM",Bplus_MM_min,Bplus_MM_max); // RooRealVar Bplus_corMassERR("Bplus_corMassERR","Bplus_corMassERR",0,600); RooRealVar weightnamevar(weightname.c_str(),weightname.c_str(), 0.0 ,1.0); TFile* f = new TFile((mcfilename+type+".root").c_str()); TTree* t = (TTree*)f->Get("DecayTree"); t->SetBranchStatus("*", 0); t->SetBranchStatus("Bplus_MM", 1); RooDataSet dr("dr","dr", RooArgSet(Bplus_Corrected_Mass), Import(*t)); // if (weighted==true) // { // RooDataSet dr("dr","dr", RooArgSet(Bplus_Corrected_Mass), Import(*t)); // } if (weighted==true) { RooDataSet dr("dr","dr", RooArgSet(Bplus_Corrected_Mass,weightnamevar), Import(*t), WeightVar(weightname.c_str())); } // RooDataSet dr("dr","dr", RooArgSet(Bplus_Corrected_Mass,weightnamevar), Import(*t), WeightVar(weightname.c_str())); dr.Print(); // mean_ ( "mean","mean coeff",this, mean ), // sigma_( "sigma","sigma coeff",this, sigma ), // lambda_( "lambda","lambda coeff",this, lambda ), // zeta_( "zeta","zeta coeff",this, zeta ), // beta_( "beta","beta coeff",this, beta ), // a_ ( "a","a coeff",this, a), // n_ ( "n","n coeff",this, n), // RooAbsReal& _x, // RooAbsReal& _l, // RooAbsReal& _zeta, // RooAbsReal& _fb, // RooAbsReal& _sigma, // RooAbsReal& _mu, // RooAbsReal& _a, // RooAbsReal& _n, // RooAbsReal& _a2, // RooAbsReal& _n2 // RooRealVar l(("l_"+type).c_str(),"l",-4.0, -6.0, 6.0); // RooRealVar zeta(("zeta_"+type).c_str(),"l",0.002, 0.0001, 0.1); // RooRealVar fb(("fb_"+type).c_str(),"l",-0.1,0.1); // RooRealVar sigma(("sigma_"+type).c_str(),"l",9.81);//,8.0,10.0);//,0.1,50) ; // RooRealVar mean(("mean_"+type).c_str(),"l", 5280.0); // RooRealVar a1coeff(("a1coeff_"+type).c_str(),"l",2.75, 2.5, 3.0); // RooRealVar n1coeff(("n1coeff_"+type).c_str(),"l",1.27,10.0); // RooRealVar a2coeff(("a2coeff_"+type).c_str(),"a2co",2.44, 0.1,10.0); // RooRealVar n2coeff(("n2coeff_"+type).c_str(),"l",3.35,10.0); // RooRealVar l(("l_"+type).c_str(),"l",-4.0, -6.0, -0.1); // RooRealVar zeta(("zeta_"+type).c_str(),"l",1.0e-5, 1.0e-8, 5.0); // RooRealVar fb(("fb_"+type).c_str(),"l",-0.001,-0.1,-0.00001); // RooRealVar sigma(("sigma_"+type).c_str(),"l",9.81);//,8.0,10.0);//,0.1,50) ; // RooRealVar mean(("mean_"+type).c_str(),"l", 5280.0); // RooRealVar a1coeff(("a1coeff_"+type).c_str(),"l",2.75, 1.0, 3.0); // RooRealVar n1coeff(("n1coeff_"+type).c_str(),"l",0.1,10.0); // RooRealVar a2coeff(("a2coeff_"+type).c_str(),"a2co",3.17, 0.1,4.0); // RooRealVar n2coeff(("n2coeff_"+type).c_str(),"l",2.35,0.1,4.0); RooRealVar l(("l_"+type).c_str(),"l",-4.0, -6.0, -2.0); RooRealVar zeta(("zeta_"+type).c_str(),"l",1.0e-5, 1.0e-8, 1.0); RooRealVar fb(("fb_"+type).c_str(),"l",-0.001,-0.1,-0.00001); RooRealVar sigma(("sigma_"+type).c_str(),"l",9.81);//,8.0,10.0);//,0.1,50) ; RooRealVar mean(("mean_"+type).c_str(),"l", 5280.0); RooRealVar a1coeff(("a1coeff_"+type).c_str(),"l",2.15, 2.0, 3.0); RooRealVar n1coeff(("n1coeff_"+type).c_str(),"l",0.1,10.0); RooRealVar a2coeff(("a2coeff_"+type).c_str(),"a2co",3.17, 0.1,4.0); RooRealVar n2coeff(("n2coeff_"+type).c_str(),"l",2.35,0.1,4.0); //gROOT->ProcessLine(".L $URANIAROOT/src/RooIpatia2.cxx+"); //RooRealVar alpharar(("alpharar_"+type).c_str(),"",1.0,0.1,5.0); RooIpatia2 blah(("blah_"+type).c_str(), ("blah"+type).c_str(), Bplus_Corrected_Mass, l, zeta, fb , sigma, mean, a1coeff, n1coeff, a2coeff, n2coeff); double value(0); value = blah.analyticalIntegral(1,"Bplus_MM"); cout<<"value: "<< value<<endl; // double plu(0.8); double plu(0.2); vector<double> lop; lop.push_back(plu); //return(lop); RooPlot* frame8 = Bplus_Corrected_Mass.frame(Title("Unbinned fit with double 2sided hypathia function")) ; dr.plotOn(frame8); // blah.paramOn(frame8); // // blah.fitTo(dr);//,RooFit::Minos(1), RooFit::Offset(kTRUE)); //bin the data to be fast (for testing) // Bplus_Corrected_Mass.setBins(100); RooDataHist* bdata; if(binnedFit) bdata = dr.binnedClone("binned", "binned") ; //fit the stuff RooAbsReal* nll; if(binnedFit) nll = blah.createNLL(*bdata, RooFit::NumCPU(8) ) ; if(!binnedFit) nll = blah.createNLL(dr, RooFit::NumCPU(8) ) ; RooMinuit m(*nll); m.migrad(); m.hesse(); m.minos(); blah.plotOn(frame8,DataError(RooAbsData::SumW2)); blah.paramOn(frame8); RooPlot* frameun = Bplus_Corrected_Mass.frame(Title("Unbinned fit with double 2sided hypathia function")) ; dr.plotOn(frameun); blah.plotOn(frameun,DataError(RooAbsData::SumW2)); blah.paramOn(frameun); vector<double> myresults; myresults.push_back(l.getVal()); myresults.push_back(zeta.getVal()); myresults.push_back(fb.getVal()); myresults.push_back(sigma.getVal()); myresults.push_back(mean.getVal()); myresults.push_back(a1coeff.getVal()); myresults.push_back(n1coeff.getVal()); myresults.push_back(a2coeff.getVal()); myresults.push_back(n2coeff.getVal()); mean.setConstant(); sigma.setConstant(); l.setConstant(); zeta.setConstant(); fb.setConstant(); a1coeff.setConstant(); n1coeff.setConstant(); a2coeff.setConstant(); n2coeff.setConstant(); // alpharar.setConstant(); //C a l c u l a t e chi squared // cout<<"Chi squared: "<< frame8->chiSquare() <<endl; RooHist* hresid = frame8->residHist(); RooHist* hpull = frame8->pullHist(); RooPlot* frame9 = Bplus_Corrected_Mass.frame(Title("Residual Distribution")); frame9->addPlotable(hresid,"P"); RooPlot* frame10 = Bplus_Corrected_Mass.frame(Title("Pull Distribution")) ; frame10->addPlotable(hpull,"P"); TCanvas* canv4 = new TCanvas("mBplus_Corrected_Massattempt5","mBplus_Corrected_Massattempt5",800,800) ; canv4->Divide(2,2) ; canv4->cd(1) ; gPad->SetLeftMargin(0.15) ; frame8->GetYaxis()->SetTitleOffset(1.4) ; frame8->Draw() ; canv4->cd(2) ; gPad->SetLeftMargin(0.15) ; frame9->GetYaxis()->SetTitleOffset(1.4) ; frame9->Draw() ; canv4->cd(3) ; gPad->SetLeftMargin(0.15) ; frame10->GetYaxis()->SetTitleOffset(1.4) ; frame10->Draw() ; canv4->cd(4) ; gPad->SetLeftMargin(0.15) ; frameun->GetYaxis()->SetTitleOffset(1.4) ; frameun->Draw() ; canv4->SaveAs((plotdir+"mcsigfit_HYP_NOTMAIN_"+type+dataset+".pdf").c_str()); TCanvas* canvlog = new TCanvas("new","log",800,800) ; canvlog->SetLogy() ; frame8->Draw() ;// gPad->SetLeftMargin(0.15) ; frame8->GetYaxis()->SetTitleOffset(1.4) ; frame8->Draw() ; canvlog->SaveAs((plotdir+"mcsigfit_HYP_NOTMAIN_LOGY_"+type+dataset+".pdf").c_str()); // delete canvlog; //new stuff// TCanvas canvTot("canvTot", "canvTot", 600, 600); canvTot.Divide(1,2); canvTot.cd(1); gPad->SetPad(0.005, 0.205, 0.995, 0.995); canvlog->DrawClonePad(); delete canvlog; savePullPlot(*frame8, plotdir+"pullPlot_spec.root"); TFile fpull((plotdir+"pullPlot_spec.root").c_str()); TCanvas* cpull = (TCanvas*)fpull.Get("pullplot"); canvTot.cd(2); gPad->SetPad(0.005, 0.005, 0.995, 0.2); gPad->SetLeftMargin(0.15) ; cpull->DrawClonePad(); canvTot.Print((plotdir+"mcsigfit_HYP_NOTMAIN_LOGY_moreinfo_"+type+dataset+".pdf").c_str()); canvTot.Print((plotdir+"mcsigfit_HYP_NOTMAIN_LOGY_moreinfo_"+type+dataset+".root").c_str()); TCanvas* canvnew = new TCanvas("signalplot","mBplus_Corrected_Massnew",800,800) ; gPad->SetLeftMargin(0.15) ; frame8->GetYaxis()->SetTitleOffset(1.4) ; frame8->Draw() ; TFile *fm = new TFile((plotdir+"plotsig_"+type+dataset+".root").c_str(),"RECREATE"); canvnew->Write(); fm->Close(); delete fm; delete canvnew; RooWorkspace *w8 = new RooWorkspace("w","workspace"); // string namews8="signal"; TFile wrkspc8((plotdir+"myworkspace_"+namews8+"_"+type+".root").c_str(),"RECREATE"); w8->import(Bplus_Corrected_Mass); w8->import(weightnamevar); w8->import(dr); w8->import(blah); cout<<"Signal workspace"<<endl; w8->Print(); w8->Write(); wrkspc8.Write(); delete canv4; return(myresults); } vector<double> FitAndSplotJpsiKDataForTraining::sigfit(string weightname, string type,string mcfilename) { cout<<"Start Signal Component fit"<<endl; RooRealVar Bplus_Corrected_Mass("Bplus_MM","Bplus_MM",5150,5450); // RooRealVar Bplus_corMassERR("Bplus_corMassERR","Bplus_corMassERR",0,600); RooRealVar weightnamevar(weightname.c_str(),weightname.c_str(), 0.0 ,1.0); TFile* f = new TFile((mcfilename+type+".root").c_str()); TTree* t = (TTree*)f->Get("DecayTree"); RooDataSet dr("dr","dr", RooArgSet(Bplus_Corrected_Mass,weightnamevar), Import(*t), WeightVar(weightname.c_str())); dr.Print(); RooRealVar cbmeanrar(("cbmeanrar_"+type).c_str(),("cbmeanrar"+type).c_str(), 5283.0, 5280.8, 5290.0); RooRealVar cbsigmarar(("cbsigmarar_"+type).c_str(),("cbsigmarar"+type).c_str(),8.6,0.1,20);//,0.1,50) ; RooRealVar cbsignalrar(("cbsignalrar_"+type).c_str(),("cbsignalrar"+type).c_str(),5.0,0.0,10.0) ; RooRealVar nral(("nral_"+type).c_str(),"",1.0,0.1,3.0); RooRealVar alpharal(("alpharal_"+type).c_str(),"",1.0,0.1,5.0); RooRealVar nrar(("nrar_"+type).c_str(),"",1.0,0.1,5.0); RooRealVar alpharar(("alpharar_"+type).c_str(),"",1.0,0.1,5.0); MyCB blah(("blah_"+type).c_str(), ("blah"+type).c_str(), Bplus_Corrected_Mass, cbmeanrar, cbsigmarar, nral , alpharal, nrar, alpharar); RooPlot* frame8 = Bplus_Corrected_Mass.frame(Title("Unbinned fit with double ccrystal ball function")) ; dr.plotOn(frame8); blah.fitTo(dr); blah.plotOn(frame8,DataError(RooAbsData::SumW2)); RooPlot* frameun = Bplus_Corrected_Mass.frame(Title("Unbinned fit with double ccrystal ball function")) ; dr.plotOn(frameun); blah.plotOn(frameun,DataError(RooAbsData::SumW2)); blah.paramOn(frameun); vector<double> myresults; cout<<"MBplus_Corrected_Mass fitted values:"<<endl; cout<<cbmeanrar.getVal()<<endl; cout<<cbsigmarar.getVal()<<endl; cout<<cbsignalrar.getVal()<<endl; cout<<nral.getVal()<<endl; cout<<alpharal.getVal()<<endl; cout<<nrar.getVal()<<endl; cout<<alpharar.getVal()<<endl; myresults.push_back(cbmeanrar.getVal()); myresults.push_back(cbsigmarar.getVal()); myresults.push_back(nral.getVal()); myresults.push_back(alpharal.getVal()); myresults.push_back(nrar.getVal()); myresults.push_back(alpharar.getVal()); cbmeanrar.setConstant(); cbsigmarar.setConstant(); cbsignalrar.setConstant(); nral.setConstant(); alpharal.setConstant(); nrar.setConstant(); alpharar.setConstant(); //C a l c u l a t e chi squared // cout<<"Chi squared: "<< frame8->chiSquare() <<endl; RooHist* hresid = frame8->residHist(); RooHist* hpull = frame8->pullHist(); RooPlot* frame9 = Bplus_Corrected_Mass.frame(Title("Residual Distribution")); frame9->addPlotable(hresid,"P"); RooPlot* frame10 = Bplus_Corrected_Mass.frame(Title("Pull Distribution")) ; frame10->addPlotable(hpull,"P"); TCanvas* canv4 = new TCanvas("mBplus_Corrected_Massattempt5","mBplus_Corrected_Massattempt5",800,800) ; canv4->Divide(2,2) ; canv4->cd(1) ; gPad->SetLeftMargin(0.15) ; frame8->GetYaxis()->SetTitleOffset(1.4) ; frame8->Draw() ; canv4->cd(2) ; gPad->SetLeftMargin(0.15) ; frame9->GetYaxis()->SetTitleOffset(1.4) ; frame9->Draw() ; canv4->cd(3) ; gPad->SetLeftMargin(0.15) ; frame10->GetYaxis()->SetTitleOffset(1.4) ; frame10->Draw() ; canv4->cd(4) ; gPad->SetLeftMargin(0.15) ; frameun->GetYaxis()->SetTitleOffset(1.4) ; frameun->Draw() ; canv4->SaveAs((plotdir+"mcsigfit_NOTMAIN_"+type+".pdf").c_str()); TCanvas* canvlog = new TCanvas("new","log",800,800) ; canvlog->SetLogy() ; gPad->SetLeftMargin(0.15) ; frame8->GetYaxis()->SetTitleOffset(1.4) ; frame8->Draw() ; canvlog->SaveAs((plotdir+"mcsigfit_NOTMAIN_LOGY_"+type+".pdf").c_str()); delete canvlog; TCanvas* canvnew = new TCanvas("signalplot","mBplus_Corrected_Massnew",800,800) ; gPad->SetLeftMargin(0.15) ; frame8->GetYaxis()->SetTitleOffset(1.4) ; frame8->Draw() ; TFile *fm = new TFile((plotdir+"plotsig_"+type+".root").c_str(),"RECREATE"); canvnew->Write(); fm->Close(); delete fm; delete canvnew; RooWorkspace *w8 = new RooWorkspace("w","workspace"); // string namews8="signal"; TFile wrkspc8((plotdir+"myworkspace_"+namews8+"_"+type+".root").c_str(),"RECREATE"); w8->import(Bplus_Corrected_Mass); w8->import(weightnamevar); w8->import(dr); w8->import(blah); cout<<"Signal workspace"<<endl; w8->Print(); w8->Write(); wrkspc8.Write(); delete canv4; return(myresults); } void FitAndSplotJpsiKDataForTraining::fitJpsiKDataHypathia3(bool binnedFit, string type, string dataset) { cout<<"fitting with hyp function"<<endl; //Get the dataset TFile* f_low = new TFile((plotdir+"myworkspace_signal_"+type+".root").c_str()); RooWorkspace* ws_low = (RooWorkspace*)f_low->Get("w"); RooRealVar* l = ws_low->var(("l_"+type).c_str()); RooRealVar* zeta = ws_low->var(("zeta_"+type).c_str()); RooRealVar* fb = ws_low->var(("fb_"+type).c_str()); RooRealVar sigma(("sigma_"+type).c_str(),"l",9.81,8.0,20.0);//,8.0,10.0);//,0.1,50) ; RooRealVar mean(("mean_"+type).c_str(),"l", 5280.0,5278.0,5285.0); RooRealVar* a1coeff= ws_low->var(("a1coeff_"+type).c_str()); RooRealVar* n1coeff= ws_low->var(("n1coeff_"+type).c_str()); RooRealVar* a2coeff= ws_low->var(("a2coeff_"+type).c_str()); RooRealVar* n2coeff= ws_low->var(("n2coeff_"+type).c_str()); TFile* f_pi = new TFile((plotdir+"myworkspaceWEIGHT_pimumu_"+type+".root").c_str()); RooWorkspace* ws_pi = (RooWorkspace*)f_pi->Get("w"); RooRealVar* cbmeanrar=ws_pi->var(("picbmeanrar_"+type).c_str()); RooRealVar* cbsigmarar=ws_pi->var(("picbsigmarar_"+type).c_str());//,0.1,50) ; RooRealVar* cbsignalrar=ws_pi->var(("picbsignalrar_"+type).c_str()) ; RooRealVar* nral=ws_pi->var(("pinral_"+type).c_str()); RooRealVar* alpharal=ws_pi->var(("pialpharal_"+type).c_str()); RooRealVar* nrar=ws_pi->var(("pinrar_"+type).c_str()); RooRealVar* alpharar=ws_pi->var(("pialpharar_"+type).c_str()); // MyCB blah("piblah", "piblah", *Bplus_MM, *cbmeanrar, *cbsigmarar, *nral , *alpharal, nrar, *alpharar); if(!ws_low || !f_low || !l || !fb || !a1coeff || !n1coeff || !n2coeff || !a2coeff) { cerr<<"ERROR: in function FitAndSplotJpsiKDataForTraining, error downloading stuff from workspace"<<endl; return; } // RooIpatia2 cb1("cb1", "cb1", *Bplus_MM, *l, zeta, *fb , sigma, mean, *a1coeff, *n1coeff, *a2coeff, *n2coeff); f_low->Close(); delete f_low; TFile fw(workspaceFileName.c_str(), "UPDATE"); RooWorkspace* workspaceData = (RooWorkspace*)fw.Get("workspaceData"); if(!workspaceData) { cerr<<"ERROR: in function fitJpsiKData, no workspace found in file "<<workspaceFileName<<endl; return; } RooRealVar* Bplus_MM = workspaceData->var("Bplus_MM"); RooDataSet* data = (RooDataSet*)workspaceData->data("data"); if(!data || !Bplus_MM) { cerr<<"ERROR: in function FitAndSplotJpsiKDataForTraining, error downloading stuff from workspace"<<endl; return; } MyCB blah("piblah", "piblah", *Bplus_MM, *cbmeanrar, *cbsigmarar, *nral , *alpharal, *nrar, *alpharar); RooIpatia2 cb1("cb1", "cb1", *Bplus_MM, *l, *zeta, *fb , sigma, mean, *a1coeff, *n1coeff, *a2coeff, *n2coeff); //prepare the fit function RooRealVar lambda("lambda","lambda",-0.1, 0.1); RooRealVar meanB("meanB","meanB", 5280., 5290.); // RooRealVar l(("l_"+type).c_str(),"l",-3.39,-6,-2); // RooRealVar zeta(("zeta_"+type).c_str(),"l",1.0e-2,1e-8,1e-4); // RooRealVar fb(("fb_"+type).c_str(),"l",-0.00241, -1.0,1.0); // RooRealVar sigma(("sigma_"+type).c_str(),"l",9.81,8.0,20.0);//,8.0,10.0);//,0.1,50) ; // RooRealVar mean(("mean_"+type).c_str(),"l", 5280.0, 5275.0, 5285.0); // RooRealVar a1coeff(("a1coeff_"+type).c_str(),"l",2.5,0.1,5.0); // RooRealVar n1coeff(("n1coeff_"+type).c_str(),"l",1.8,0.1,10.0); // RooRealVar a2coeff(("a2coeff_"+type).c_str(),"a2co",2.0, 0.1,5.0); // RooRealVar n2coeff(("n2coeff_"+type).c_str(),"l",1.18,0.1,10.0); // RooIpatia2 cb1("cb1", "cb1", *Bplus_MM, l, zeta, fb , sigma, mean, a1coeff, n1coeff, a2coeff, n2coeff); // RooRealVar cbmeanrar("cbmeanrar","cbmeanrar", 5283., 5280., 5290.); // RooRealVar cbsigmarar("cbsigmarar","cbsigmarar",16.,1.,20.);//,0.1,50) ; // RooRealVar cbsignalrar("cbsignalrar","cbsignalrar",10,0.0,1000000) ; // RooRealVar nral("nral","",1.0,0.1,5.0); // RooRealVar alpharal("alpharal","",1.0,0.1,20.0); // RooRealVar nrar("nrar","",1.0,0.1,5.0); // RooRealVar alpharar("alpharar","",1.0,0.1,20.0); // MyCB cb1("cb1", "cb1", *Bplus_MM, cbmeanrar, cbsigmarar, nral , alpharal, nrar, alpharar); // RooGaussian cb1("cb1", "cb1", *Bplus_MM, meanB, sigma); // RooCBShape cb1("cb1", "cb1", *Bplus_MM, meanB, sigma, alpha, n); // RooCBShape cb2("cb2", "cb2", *Bplus_MM, meanB, sigma1, alpha, n); //-----C0mbinatorial------------// RooExponential expo("expo", "exponential PDF", *Bplus_MM, lambda); // RooRealVar vc1("vc1", "vc1",0.75, 0.15,0.9); RooRealVar sig("sig","sig",4000000 ,1000,17000000); RooRealVar bkg("bkg","bkg",1000000, 2 ,10000000) ; RooRealVar bkg2("bkg2","bkg2",1000000, 2 ,10000000) ; // RooAddPdf sigCB_B0("sigCB0","sigCB0",RooArgList( cb1, cb2),RooArgList( vc1)) ; RooAddPdf model_total("model","model", RooArgList( cb1, expo, blah) ,RooArgList(sig, bkg, bkg2)); //bin the data to be fast (for testing) Bplus_MM->setBins(100); RooDataHist* bdata; if(binnedFit) bdata = new RooDataHist("data_tau", "data_tau", RooArgSet( *Bplus_MM), *data) ; //fit the stuff RooAbsReal* nll; if(binnedFit) nll = model_total.createNLL(*bdata, RooFit::NumCPU(8) ) ; if(!binnedFit) nll = model_total.createNLL(*data, RooFit::NumCPU(8) ) ; RooMinuit m(*nll); m.migrad(); m.hesse(); m.minos(); //plot RooPlot* frame = Bplus_MM->frame(); model_total.paramOn(frame); data->plotOn(frame); model_total.plotOn(frame, RooFit::LineColor(kRed) ); model_total.plotOn(frame, RooFit::LineColor(kGreen), RooFit::Components("expo")); model_total.plotOn(frame, RooFit::LineColor(kBlue), RooFit::Components("cb1")); model_total.plotOn(frame, RooFit::LineColor(kMagenta), RooFit::Components("piblah")); TCanvas canv("canv", "canv", 600, 600); frame->Draw(); canv.Print((plotdir+"HypathiaplotJpsiK"+dataset+".pdf").c_str()); canv.Print((plotdir+"HypathiaplotJpsiK"+dataset+".root").c_str()); //save the fit function // workspace->import(lambda, true); // workspace->import(meanB, true); // workspace->import(sigma, true ); // workspace->import(sigma1, true); // workspace->import(n, true); // workspace->import(alpha, true); // //workspace->import(cb1); // //workspace->import(cb2); // //workspace->import(expo); // workspace->import(vc1, true); // workspace->import(sig, true); // workspace->import(bkg, true); //workspace->import(sigCB_B0); RooWorkspace workspaceFit("workspaceFit", "workspaceFit"); workspaceFit.import(*data); workspaceFit.import(model_total); //workspaceFit.writeToFile(workspaceFileName.c_str()); workspaceFit.Write("", TObject::kOverwrite); cout<<"Workspace for fit has been saved:"<<endl; workspaceFit.Print(); fw.Close(); } void FitAndSplotJpsiKDataForTraining::fitJpsiKDataHypathia2(bool binnedFit, string type, string dataset) { cout<<"fitting with hyp function"<<endl; //Get the dataset TFile* f_low = new TFile((plotdir+"myworkspace_signal_"+type+".root").c_str()); RooWorkspace* ws_low = (RooWorkspace*)f_low->Get("w"); RooRealVar* l = ws_low->var(("l_"+type).c_str()); RooRealVar* zeta = ws_low->var(("zeta_"+type).c_str()); RooRealVar* fb = ws_low->var(("fb_"+type).c_str()); RooRealVar sigma(("sigma_"+type).c_str(),"l",9.81,8.0,20.0);//,8.0,10.0);//,0.1,50) ; RooRealVar mean(("mean_"+type).c_str(),"l", 5280.0,5278.0,5285.0); RooRealVar* a1coeff= ws_low->var(("a1coeff_"+type).c_str()); RooRealVar* n1coeff= ws_low->var(("n1coeff_"+type).c_str()); RooRealVar* a2coeff= ws_low->var(("a2coeff_"+type).c_str()); RooRealVar* n2coeff= ws_low->var(("n2coeff_"+type).c_str()); if(!ws_low || !f_low || !l || !fb || !a1coeff || !n1coeff || !n2coeff || !a2coeff) { cerr<<"ERROR: in function FitAndSplotJpsiKDataForTraining, error downloading stuff from workspace"<<endl; return; } // RooIpatia2 cb1("cb1", "cb1", *Bplus_MM, *l, zeta, *fb , sigma, mean, *a1coeff, *n1coeff, *a2coeff, *n2coeff); f_low->Close(); delete f_low; TFile fw(workspaceFileName.c_str(), "UPDATE"); RooWorkspace* workspaceData = (RooWorkspace*)fw.Get("workspaceData"); if(!workspaceData) { cerr<<"ERROR: in function fitJpsiKData, no workspace found in file "<<workspaceFileName<<endl; return; } RooRealVar* Bplus_MM = workspaceData->var("Bplus_MM"); RooDataSet* data = (RooDataSet*)workspaceData->data("data"); if(!data || !Bplus_MM) { cerr<<"ERROR: in function FitAndSplotJpsiKDataForTraining, error downloading stuff from workspace"<<endl; return; } RooIpatia2 cb1("cb1", "cb1", *Bplus_MM, *l, *zeta, *fb , sigma, mean, *a1coeff, *n1coeff, *a2coeff, *n2coeff); //prepare the fit function RooRealVar lambda("lambda","lambda",-2.39906e-03,-0.1, 0.1); RooRealVar meanB("meanB","meanB", 5280., 5290.); // RooRealVar l(("l_"+type).c_str(),"l",-3.39,-6,-2); // RooRealVar zeta(("zeta_"+type).c_str(),"l",1.0e-2,1e-8,1e-4); // RooRealVar fb(("fb_"+type).c_str(),"l",-0.00241, -1.0,1.0); // RooRealVar sigma(("sigma_"+type).c_str(),"l",9.81,8.0,20.0);//,8.0,10.0);//,0.1,50) ; // RooRealVar mean(("mean_"+type).c_str(),"l", 5280.0, 5275.0, 5285.0); // RooRealVar a1coeff(("a1coeff_"+type).c_str(),"l",2.5,0.1,5.0); // RooRealVar n1coeff(("n1coeff_"+type).c_str(),"l",1.8,0.1,10.0); // RooRealVar a2coeff(("a2coeff_"+type).c_str(),"a2co",2.0, 0.1,5.0); // RooRealVar n2coeff(("n2coeff_"+type).c_str(),"l",1.18,0.1,10.0); // RooIpatia2 cb1("cb1", "cb1", *Bplus_MM, l, zeta, fb , sigma, mean, a1coeff, n1coeff, a2coeff, n2coeff); // RooRealVar cbmeanrar("cbmeanrar","cbmeanrar", 5283., 5280., 5290.); // RooRealVar cbsigmarar("cbsigmarar","cbsigmarar",16.,1.,20.);//,0.1,50) ; // RooRealVar cbsignalrar("cbsignalrar","cbsignalrar",10,0.0,1000000) ; // RooRealVar nral("nral","",1.0,0.1,5.0); // RooRealVar alpharal("alpharal","",1.0,0.1,20.0); // RooRealVar nrar("nrar","",1.0,0.1,5.0); // RooRealVar alpharar("alpharar","",1.0,0.1,20.0); // MyCB cb1("cb1", "cb1", *Bplus_MM, cbmeanrar, cbsigmarar, nral , alpharal, nrar, alpharar); // RooGaussian cb1("cb1", "cb1", *Bplus_MM, meanB, sigma); // RooCBShape cb1("cb1", "cb1", *Bplus_MM, meanB, sigma, alpha, n); // RooCBShape cb2("cb2", "cb2", *Bplus_MM, meanB, sigma1, alpha, n); //-----C0mbinatorial------------// RooExponential expo("expo", "exponential PDF", *Bplus_MM, lambda); // RooRealVar vc1("vc1", "vc1",0.75, 0.15,0.9); RooRealVar sig("sig","sig",120000 ,1000,200000); RooRealVar bkg("bkg","bkg",100, 2 ,5000) ; //RooRealVar bkg2("bkg2","bkg2",100, 2 ,5000) ; // RooAddPdf sigCB_B0("sigCB0","sigCB0",RooArgList( cb1, cb2),RooArgList( vc1)) ; RooAddPdf model_total("model","model", RooArgList( cb1, expo) ,RooArgList(sig, bkg)); //bin the data to be fast (for testing) Bplus_MM->setBins(100); RooDataHist* bdata; if(binnedFit) bdata = new RooDataHist("data_tau", "data_tau", RooArgSet( *Bplus_MM), *data) ; //fit the stuff RooAbsReal* nll; if(binnedFit) nll = model_total.createNLL(*bdata, RooFit::NumCPU(8) ) ; if(!binnedFit) nll = model_total.createNLL(*data, RooFit::NumCPU(8) ) ; RooMinuit m(*nll); m.minos(); m.hesse(); m.migrad(); //plot RooPlot* frame = Bplus_MM->frame(); model_total.paramOn(frame); data->plotOn(frame); model_total.plotOn(frame, RooFit::LineColor(kRed) ); model_total.plotOn(frame, RooFit::LineColor(kGreen), RooFit::Components("expo")); model_total.plotOn(frame, RooFit::LineColor(kBlue), RooFit::Components("cb1")); model_total.plotOn(frame, RooFit::LineColor(kMagenta), RooFit::Components("piblah")); TCanvas canv("canv", "canv", 600, 600); frame->Draw(); canv.Print((plotdir+"HypathiaplotJpsiK"+dataset+".pdf").c_str()); canv.Print((plotdir+"HypathiaplotJpsiK"+dataset+".root").c_str()); //save the fit function // workspace->import(lambda, true); // workspace->import(meanB, true); // workspace->import(sigma, true ); // workspace->import(sigma1, true); // workspace->import(n, true); // workspace->import(alpha, true); // //workspace->import(cb1); // //workspace->import(cb2); // //workspace->import(expo); // workspace->import(vc1, true); // workspace->import(sig, true); // workspace->import(bkg, true); //workspace->import(sigCB_B0); RooWorkspace workspaceFit("workspaceFit", "workspaceFit"); workspaceFit.import(*data); workspaceFit.import(model_total); //workspaceFit.writeToFile(workspaceFileName.c_str()); workspaceFit.Write("", TObject::kOverwrite); cout<<"Workspace for fit has been saved:"<<endl; workspaceFit.Print(); fw.Close(); } void FitAndSplotJpsiKDataForTraining::fitJpsiKDataHypathia(bool binnedFit, string type) { cout<<"fitting"<<endl; //Get the dataset TFile fw(workspaceFileName.c_str(), "UPDATE"); RooWorkspace* workspaceData = (RooWorkspace*)fw.Get("workspaceData"); if(!workspaceData) { cerr<<"ERROR: in function fitJpsiKData, no workspace found in file "<<workspaceFileName<<endl; return; } RooRealVar* Bplus_MM = workspaceData->var("Bplus_MM"); RooDataSet* data = (RooDataSet*)workspaceData->data("data"); if(!data || !Bplus_MM) { cerr<<"ERROR: in function FitAndSplotJpsiKDataForTraining, error downloading stuff from workspace"<<endl; return; } TFile* f_low = new TFile((plotdir+"myworkspace_signal_"+type+".root").c_str()); RooWorkspace* ws_low = (RooWorkspace*)f_low->Get("w"); RooAbsPdf* pdf_sig_low = ws_low->pdf(("blah_"+type).c_str()); RooRealVar* l = ws_low->var(("l_"+type).c_str()); RooRealVar* zeta = ws_low->var(("l_"+type).c_str()); RooRealVar* fb = ws_low->var(("fb_"+type).c_str()); RooRealVar sigma(("sigma_"+type).c_str(),"l",9.81,8.0,20.0);//,8.0,10.0);//,0.1,50) ; RooRealVar mean(("mean_"+type).c_str(),"l", 5280.0); RooRealVar* a1coeff= ws_low->var(("a1coeff_"+type).c_str()); RooRealVar* n1coeff= ws_low->var(("n1coeff_"+type).c_str()); RooRealVar* a2coeff= ws_low->var(("a2coeff_"+type).c_str()); RooRealVar* n2coeff= ws_low->var(("n2coeff_"+type).c_str()); // if(!ws_low || !f_low || !pdf_sig_low || !l || !zeta || !fb || !a1coeff || !n1coeff || !n2coeff || !a2coeff) // { // cerr<<"ERROR: in function FitAndSplotJpsiKDataForTraining, error downloading stuff from workspace"<<endl; // return; // } RooIpatia2 cb1("cb1", "cb1", *Bplus_MM, *l, *zeta, *fb , sigma, mean, *a1coeff, *n1coeff, *a2coeff, *n2coeff); //prepare the fit function RooRealVar lambda("lambda","lambda",-2.39906e-03,-0.1, 0.1); RooRealVar meanB("meanB","meanB", 5280., 5290.); // RooRealVar l(("l_"+type).c_str(),"l",-3.39); // RooRealVar zeta(("zeta_"+type).c_str(),"l",0.000006269,1e-8,1e-4); // RooRealVar fb(("fb_"+type).c_str(),"l",-0.00241); // RooRealVar sigma(("sigma_"+type).c_str(),"l",9.81,8.0,20.0);//,8.0,10.0);//,0.1,50) ; // RooRealVar mean(("mean_"+type).c_str(),"l", 5280.0, 5275.0, 5285.0); // RooRealVar a1coeff(("a1coeff_"+type).c_str(),"l",2.73); // RooRealVar n1coeff(("n1coeff_"+type).c_str(),"l",1.8); // RooRealVar a2coeff(("a2coeff_"+type).c_str(),"a2co",3.23); // RooRealVar n2coeff(("n2coeff_"+type).c_str(),"l",1.18); // RooIpatia2 cb1("cb1", "cb1", *Bplus_MM, l, zeta, fb , sigma, mean, a1coeff, n1coeff, a2coeff, n2coeff); // RooRealVar cbmeanrar("cbmeanrar","cbmeanrar", 5283., 5280., 5290.); // RooRealVar cbsigmarar("cbsigmarar","cbsigmarar",16.,1.,20.);//,0.1,50) ; // RooRealVar cbsignalrar("cbsignalrar","cbsignalrar",10,0.0,1000000) ; // RooRealVar nral("nral","",1.0,0.1,5.0); // RooRealVar alpharal("alpharal","",1.0,0.1,20.0); // RooRealVar nrar("nrar","",1.0,0.1,5.0); // RooRealVar alpharar("alpharar","",1.0,0.1,20.0); // MyCB cb1("cb1", "cb1", *Bplus_MM, cbmeanrar, cbsigmarar, nral , alpharal, nrar, alpharar); // RooGaussian cb1("cb1", "cb1", *Bplus_MM, meanB, sigma); // RooCBShape cb1("cb1", "cb1", *Bplus_MM, meanB, sigma, alpha, n); // RooCBShape cb2("cb2", "cb2", *Bplus_MM, meanB, sigma1, alpha, n); //-----C0mbinatorial------------// RooExponential expo("expo", "exponential PDF", *Bplus_MM, lambda); // RooRealVar vc1("vc1", "vc1",0.75, 0.15,0.9); RooRealVar sig("sig","sig",120000 ,100000,140000); RooRealVar bkg("bkg","bkg",100, 2 ,5000) ; // RooAddPdf sigCB_B0("sigCB0","sigCB0",RooArgList( cb1, cb2),RooArgList( vc1)) ; RooAddPdf model_total("model","model", RooArgList( cb1, expo) ,RooArgList(sig, bkg)); //bin the data to be fast (for testing) Bplus_MM->setBins(100); RooDataHist* bdata; if(binnedFit) bdata = new RooDataHist("data_tau", "data_tau", RooArgSet( *Bplus_MM), *data) ; //fit the stuff RooAbsReal* nll; if(binnedFit) nll = model_total.createNLL(*bdata, RooFit::NumCPU(8) ) ; if(!binnedFit) nll = model_total.createNLL(*data, RooFit::NumCPU(8) ) ; RooMinuit m(*nll); m.minos(); m.hesse(); m.migrad(); //plot RooPlot* frame = Bplus_MM->frame(); data->plotOn(frame); model_total.plotOn(frame, RooFit::LineColor(kRed) ); model_total.plotOn(frame, RooFit::LineColor(kGreen), RooFit::Components("expo")); model_total.plotOn(frame, RooFit::LineColor(kBlue), RooFit::Components("cb1")); TCanvas canv("canv", "canv", 600, 600); frame->Draw(); canv.Print((plotdir+"HypathiaplotJpsiK.pdf").c_str()); canv.Print((plotdir+"HypathiaplotJpsiK.root").c_str()); //save the fit function // workspace->import(lambda, true); // workspace->import(meanB, true); // workspace->import(sigma, true ); // workspace->import(sigma1, true); // workspace->import(n, true); // workspace->import(alpha, true); // //workspace->import(cb1); // //workspace->import(cb2); // //workspace->import(expo); // workspace->import(vc1, true); // workspace->import(sig, true); // workspace->import(bkg, true); //workspace->import(sigCB_B0); RooWorkspace workspaceFit("workspaceFit", "workspaceFit"); workspaceFit.import(*data); workspaceFit.import(model_total); //workspaceFit.writeToFile(workspaceFileName.c_str()); workspaceFit.Write("", TObject::kOverwrite); cout<<"Workspace for fit has been saved:"<<endl; workspaceFit.Print(); fw.Close(); } void FitAndSplotJpsiKDataForTraining::fitJpsiKData3(bool binnedFit) { cout<<"fitting"<<endl; //Get the dataset TFile fw(workspaceFileName.c_str(), "UPDATE"); RooWorkspace* workspaceData = (RooWorkspace*)fw.Get("workspaceData"); if(!workspaceData) { cerr<<"ERROR: in function fitJpsiKData, no workspace found in file "<<workspaceFileName<<endl; return; } RooRealVar* Bplus_MM = workspaceData->var("Bplus_MM"); RooDataSet* data = (RooDataSet*)workspaceData->data("data"); if(!data || !Bplus_MM) { cerr<<"ERROR: in function FitAndSplotJpsiKDataForTraining, error downloading stuff from workspace"<<endl; return; } //prepare the fit function RooRealVar lambda("lambda","lambda",-2.39906e-05,-0.000001, -0.0001); RooRealVar meanB("meanB","meanB", 5283., 5280., 5290.); RooRealVar sigma("sigma", "sigma",16. ,13., 20.); RooRealVar sigma1("sigma1", "sigma1",28. ,22., 50.); // RooRealVar n("n", "n",20. ,1., 80.); // RooRealVar alpha("alpha", "alpha",1.5 ,1., 2.8); RooGaussian cb1("cb1", "cb1", *Bplus_MM, meanB, sigma); // RooCBShape cb1("cb1", "cb1", *Bplus_MM, meanB, sigma, alpha, n); // RooCBShape cb2("cb2", "cb2", *Bplus_MM, meanB, sigma1, alpha, n); RooExponential expo("expo", "exponential PDF", *Bplus_MM, lambda); // RooRealVar vc1("vc1", "vc1",0.75, 0.15,0.9); RooRealVar sig("sig","sig",110000 ,100000,150000); RooRealVar bkg("bkg","bkg",10000, 2 ,40000) ; // RooAddPdf sigCB_B0("sigCB0","sigCB0",RooArgList( cb1, cb2),RooArgList( vc1)) ; RooAddPdf model_total("model","model", RooArgList( cb1, expo) ,RooArgList(sig, bkg)); //bin the data to be fast (for testing) Bplus_MM->setBins(100); RooDataHist* bdata; if(binnedFit) bdata = new RooDataHist("data_tau", "data_tau", RooArgSet( *Bplus_MM), *data) ; //fit the stuff RooAbsReal* nll; if(binnedFit) nll = model_total.createNLL(*bdata, RooFit::NumCPU(8) ) ; if(!binnedFit) nll = model_total.createNLL(*data, RooFit::NumCPU(8) ) ; RooMinuit m(*nll); m.minos(); m.hesse(); m.migrad(); //plot RooPlot* frame = Bplus_MM->frame(); data->plotOn(frame); model_total.plotOn(frame, RooFit::LineColor(kRed) ); model_total.plotOn(frame, RooFit::LineColor(kGreen), RooFit::Components("expo")); model_total.plotOn(frame, RooFit::LineColor(kBlue), RooFit::Components("cb1")); TCanvas canv("canv", "canv", 600, 600); frame->Draw(); canv.Print((plotdir+"plotJpsiK.pdf").c_str()); canv.Print((plotdir+"plotJpsiK.root").c_str()); //save the fit function // workspace->import(lambda, true); // workspace->import(meanB, true); // workspace->import(sigma, true ); // workspace->import(sigma1, true); // workspace->import(n, true); // workspace->import(alpha, true); // //workspace->import(cb1); // //workspace->import(cb2); // //workspace->import(expo); // workspace->import(vc1, true); // workspace->import(sig, true); // workspace->import(bkg, true); //workspace->import(sigCB_B0); RooWorkspace workspaceFit("workspaceFit", "workspaceFit"); workspaceFit.import(*data); workspaceFit.import(model_total); //workspaceFit.writeToFile(workspaceFileName.c_str()); workspaceFit.Write("", TObject::kOverwrite); cout<<"Workspace for fit has been saved:"<<endl; workspaceFit.Print(); fw.Close(); } void FitAndSplotJpsiKDataForTraining::fitJpsiKData2(bool binnedFit) { cout<<"fitting"<<endl; //Get the dataset TFile fw(workspaceFileName.c_str(), "UPDATE"); RooWorkspace* workspaceData = (RooWorkspace*)fw.Get("workspaceData"); if(!workspaceData) { cerr<<"ERROR: in function fitJpsiKData, no workspace found in file "<<workspaceFileName<<endl; return; } RooRealVar* Bplus_MM = workspaceData->var("Bplus_MM"); RooDataSet* data = (RooDataSet*)workspaceData->data("data"); if(!data || !Bplus_MM) { cerr<<"ERROR: in function FitAndSplotJpsiKDataForTraining, error downloading stuff from workspace"<<endl; return; } //prepare the fit function RooRealVar lambda("lambda","lambda",-2.39906e-03,-0.1, 0.1); RooRealVar meanB("meanB","meanB", 5283., 5280., 5290.); RooRealVar sigma("sigma", "sigma",16. ,13., 20.); RooRealVar sigma1("sigma1", "sigma1",28. ,22., 50.); RooRealVar n("n", "n",20. ,1., 80.); RooRealVar alpha("alpha", "alpha",1.5 ,1., 2.8); RooCBShape cb1("cb1", "cb1", *Bplus_MM, meanB, sigma, alpha, n); // RooCBShape cb2("cb2", "cb2", *Bplus_MM, meanB, sigma1, alpha, n); RooExponential expo("expo", "exponential PDF", *Bplus_MM, lambda); // RooRealVar vc1("vc1", "vc1",0.75, 0.15,0.9); RooRealVar sig("sig","sig",110000 ,100000,150000); RooRealVar bkg("bkg","bkg",10000, 2 ,40000) ; // RooAddPdf sigCB_B0("sigCB0","sigCB0",RooArgList( cb1, cb2),RooArgList( vc1)) ; RooAddPdf model_total("model","model", RooArgList( cb1, expo) ,RooArgList(sig, bkg)); //bin the data to be fast (for testing) Bplus_MM->setBins(100); RooDataHist* bdata; if(binnedFit) bdata = new RooDataHist("data_tau", "data_tau", RooArgSet( *Bplus_MM), *data) ; //fit the stuff RooAbsReal* nll; if(binnedFit) nll = model_total.createNLL(*bdata, RooFit::NumCPU(8) ) ; if(!binnedFit) nll = model_total.createNLL(*data, RooFit::NumCPU(8) ) ; RooMinuit m(*nll); m.minos(); m.hesse(); m.migrad(); //plot RooPlot* frame = Bplus_MM->frame(); data->plotOn(frame); model_total.plotOn(frame, RooFit::LineColor(kRed) ); model_total.plotOn(frame, RooFit::LineColor(kGreen), RooFit::Components("expo")); model_total.plotOn(frame, RooFit::LineColor(kBlue), RooFit::Components("cb1")); TCanvas canv("canv", "canv", 600, 600); frame->Draw(); canv.Print((plotdir+"plotJpsiK.pdf").c_str()); canv.Print((plotdir+"plotJpsiK.root").c_str()); //save the fit function // workspace->import(lambda, true); // workspace->import(meanB, true); // workspace->import(sigma, true ); // workspace->import(sigma1, true); // workspace->import(n, true); // workspace->import(alpha, true); // //workspace->import(cb1); // //workspace->import(cb2); // //workspace->import(expo); // workspace->import(vc1, true); // workspace->import(sig, true); // workspace->import(bkg, true); //workspace->import(sigCB_B0); RooWorkspace workspaceFit("workspaceFit", "workspaceFit"); workspaceFit.import(*data); workspaceFit.import(model_total); //workspaceFit.writeToFile(workspaceFileName.c_str()); workspaceFit.Write("", TObject::kOverwrite); cout<<"Workspace for fit has been saved:"<<endl; workspaceFit.Print(); fw.Close(); } void FitAndSplotJpsiKDataForTraining::fitJpsiKData4(bool binnedFit) { cout<<"fitting"<<endl; //Get the dataset TFile fw(workspaceFileName.c_str(), "UPDATE"); RooWorkspace* workspaceData = (RooWorkspace*)fw.Get("workspaceData"); if(!workspaceData) { cerr<<"ERROR: in function fitJpsiKData, no workspace found in file "<<workspaceFileName<<endl; return; } RooRealVar* Bplus_MM = workspaceData->var("Bplus_MM"); RooDataSet* data = (RooDataSet*)workspaceData->data("data"); if(!data || !Bplus_MM) { cerr<<"ERROR: in function FitAndSplotJpsiKDataForTraining, error downloading stuff from workspace"<<endl; return; } //prepare the fit function RooRealVar lambda("lambda","lambda",-2.39906e-03,-0.1, 0.1); RooRealVar meanB("meanB","meanB", 5283., 5280., 5290.); RooRealVar cbmeanrar("cbmeanrar","cbmeanrar", 5283., 5280., 5290.); RooRealVar cbsigmarar("cbsigmarar","cbsigmarar",16.,1.,20.);//,0.1,50) ; RooRealVar cbsignalrar("cbsignalrar","cbsignalrar",10,0.0,1000000) ; RooRealVar nral("nral","",1.0,0.1,5.0); RooRealVar alpharal("alpharal","",1.0,0.1,20.0); RooRealVar nrar("nrar","",1.0,0.1,5.0); RooRealVar alpharar("alpharar","",1.0,0.1,20.0); MyCB cb1("cb1", "cb1", *Bplus_MM, cbmeanrar, cbsigmarar, nral , alpharal, nrar, alpharar); // RooGaussian cb1("cb1", "cb1", *Bplus_MM, meanB, sigma); // RooCBShape cb1("cb1", "cb1", *Bplus_MM, meanB, sigma, alpha, n); // RooCBShape cb2("cb2", "cb2", *Bplus_MM, meanB, sigma1, alpha, n); //-----C0mbinatorial------------// RooExponential expo("expo", "exponential PDF", *Bplus_MM, lambda); // RooRealVar vc1("vc1", "vc1",0.75, 0.15,0.9); RooRealVar sig("sig","sig",120000 ,50000,170000); RooRealVar bkg("bkg","bkg",10000, 2 ,40000) ; // RooAddPdf sigCB_B0("sigCB0","sigCB0",RooArgList( cb1, cb2),RooArgList( vc1)) ; RooAddPdf model_total("model","model", RooArgList( cb1, expo) ,RooArgList(sig, bkg)); //bin the data to be fast (for testing) Bplus_MM->setBins(100); RooDataHist* bdata; if(binnedFit) bdata = new RooDataHist("data_tau", "data_tau", RooArgSet( *Bplus_MM), *data) ; //fit the stuff RooAbsReal* nll; if(binnedFit) nll = model_total.createNLL(*bdata, RooFit::NumCPU(8) ) ; if(!binnedFit) nll = model_total.createNLL(*data, RooFit::NumCPU(8) ) ; RooMinuit m(*nll); m.minos(); m.hesse(); m.migrad(); //plot RooPlot* frame = Bplus_MM->frame(); data->plotOn(frame); model_total.plotOn(frame, RooFit::LineColor(kRed) ); model_total.plotOn(frame, RooFit::LineColor(kGreen), RooFit::Components("expo")); model_total.plotOn(frame, RooFit::LineColor(kBlue), RooFit::Components("cb1")); TCanvas canv("canv", "canv", 600, 600); frame->Draw(); canv.Print((plotdir+"plotJpsiK.pdf").c_str()); canv.Print((plotdir+"plotJpsiK.root").c_str()); //save the fit function // workspace->import(lambda, true); // workspace->import(meanB, true); // workspace->import(sigma, true ); // workspace->import(sigma1, true); // workspace->import(n, true); // workspace->import(alpha, true); // //workspace->import(cb1); // //workspace->import(cb2); // //workspace->import(expo); // workspace->import(vc1, true); // workspace->import(sig, true); // workspace->import(bkg, true); //workspace->import(sigCB_B0); RooWorkspace workspaceFit("workspaceFit", "workspaceFit"); workspaceFit.import(*data); workspaceFit.import(model_total); //workspaceFit.writeToFile(workspaceFileName.c_str()); workspaceFit.Write("", TObject::kOverwrite); cout<<"Workspace for fit has been saved:"<<endl; workspaceFit.Print(); fw.Close(); } void FitAndSplotJpsiKDataForTraining::fitJpsiKData(bool binnedFit) { cout<<"fitting"<<endl; //Get the dataset TFile fw(workspaceFileName.c_str(), "UPDATE"); RooWorkspace* workspaceData = (RooWorkspace*)fw.Get("workspaceData"); if(!workspaceData) { cerr<<"ERROR: in function fitJpsiKData, no workspace found in file "<<workspaceFileName<<endl; return; } RooRealVar* Bplus_MM = workspaceData->var("Bplus_MM"); RooDataSet* data = (RooDataSet*)workspaceData->data("data"); if(!data || !Bplus_MM) { cerr<<"ERROR: in function FitAndSplotJpsiKDataForTraining, error downloading stuff from workspace"<<endl; return; } //prepare the fit function RooRealVar lambda("lambda","lambda",-2.39906e-03,-0.1, 0.1); RooRealVar meanB("meanB","meanB", 5283., 5280., 5290.); RooRealVar sigma("sigma", "sigma",16. ,13., 20.); RooRealVar sigma1("sigma1", "sigma1",28. ,22., 50.); RooRealVar n("n", "n",20. ,1., 50.); RooRealVar alpha("alpha", "alpha",1.5 ,1., 2.8); RooCBShape cb1("cb1", "cb1", *Bplus_MM, meanB, sigma, alpha, n); RooCBShape cb2("cb2", "cb2", *Bplus_MM, meanB, sigma1, alpha, n); RooExponential expo("expo", "exponential PDF", *Bplus_MM, lambda); RooRealVar vc1("vc1", "vc1",0.75, 0.15,0.9); RooRealVar sig("sig","sig",1.20933e+06 ,5.e+05,1.e+07); RooRealVar bkg("bkg","bkg",1.64134e+05, 5.e+04 ,1.e+06) ; RooAddPdf sigCB_B0("sigCB0","sigCB0",RooArgList( cb1, cb2),RooArgList( vc1)) ; RooAddPdf model_total("model","model", RooArgList( sigCB_B0, expo) ,RooArgList(sig, bkg)); //bin the data to be fast (for testing) Bplus_MM->setBins(500); RooDataHist* bdata; if(binnedFit) bdata = new RooDataHist("data_tau", "data_tau", RooArgSet( *Bplus_MM), *data) ; //fit the stuff RooAbsReal* nll; if(binnedFit) nll = model_total.createNLL(*bdata, RooFit::NumCPU(8) ) ; if(!binnedFit) nll = model_total.createNLL(*data, RooFit::NumCPU(8) ) ; RooMinuit m(*nll); m.minos(); m.hesse(); m.migrad(); //plot RooPlot* frame = Bplus_MM->frame(); data->plotOn(frame); model_total.plotOn(frame, RooFit::LineColor(kRed) ); model_total.plotOn(frame, RooFit::LineColor(kGreen), RooFit::Components("expo")); model_total.plotOn(frame, RooFit::LineColor(kBlue), RooFit::Components("sigCB0")); TCanvas canv("canv", "canv", 600, 600); frame->Draw(); canv.Print((plotdir+"plotJpsiK.pdf").c_str()); canv.Print((plotdir+"plotJpsiK.root").c_str()); //save the fit function // workspace->import(lambda, true); // workspace->import(meanB, true); // workspace->import(sigma, true ); // workspace->import(sigma1, true); // workspace->import(n, true); // workspace->import(alpha, true); // //workspace->import(cb1); // //workspace->import(cb2); // //workspace->import(expo); // workspace->import(vc1, true); // workspace->import(sig, true); // workspace->import(bkg, true); //workspace->import(sigCB_B0); RooWorkspace workspaceFit("workspaceFit", "workspaceFit"); workspaceFit.import(*data); workspaceFit.import(model_total); //workspaceFit.writeToFile(workspaceFileName.c_str()); workspaceFit.Write("", TObject::kOverwrite); cout<<"Workspace for fit has been saved:"<<endl; workspaceFit.Print(); fw.Close(); } void FitAndSplotJpsiKDataForTraining::prepareWorkspace(string tuplename) { cout<<" Going to prepare data workspace "<<endl; TFile f( (tuplename).c_str()); TTree* t = (TTree*)f.Get(treename.c_str()); if(!t) { cerr<<"ERROR: in function prepareWorkspace, no tree "<<treename<<" found in "<<"/"<<tuplename<<endl; return; } t->SetBranchStatus("*", 0); t->SetBranchStatus("Bplus_MM", 1); t->SetBranchStatus("HLT1TCK", 1); RooRealVar Bplus_MM("Bplus_MM", "Bplus_MM",Bplus_MM_min,Bplus_MM_max); RooRealVar HLT1TCK("HLT1TCK", "HLT1TCK",0,1e9); RooArgSet vars(Bplus_MM,HLT1TCK); cout<<"Cut applied: "<<"Bplus_MM>"+d2s(Bplus_MM_min)+" && Bplus_MM <"+d2s(Bplus_MM_max)<<endl; cout<<"Cut applied: "<<"HLT1TCK==288888335 "<<endl; RooDataSet data("data", "data", vars, Import(*t), Cut( ("HLT1TCK==288888335 && Bplus_MM>"+d2s(Bplus_MM_min)+" && Bplus_MM <"+d2s(Bplus_MM_max)).c_str() ) ); RooWorkspace workspaceData("workspaceData", "workspaceData"); workspaceData.import(Bplus_MM); workspaceData.import(data); //workspaceData.writeToFile(workspaceFileName.c_str()); TFile fws(workspaceFileName.c_str(), "RECREATE"); workspaceData.Write("",TObject::kOverwrite ); cout<<"Workspace containing data ready:"<<endl; workspaceData.Print(); f.Close(); fws.Close(); }
[ "ss4314@ss4314-laptop.hep.ph.ic.ac.uk" ]
ss4314@ss4314-laptop.hep.ph.ic.ac.uk
c7190be97b72f29e4a6dce74889b3375c368a767
785df77400157c058a934069298568e47950e40b
/TnbMesh/TnbLib/Aft/Entities/Boundary/Edge/Surface/G/Aft2d_gSegmentEdgeIO.cxx
e8a42aee1651c17ead6fb5dced642f8caa86cf27
[]
no_license
amir5200fx/Tonb
cb108de09bf59c5c7e139435e0be008a888d99d5
ed679923dc4b2e69b12ffe621fc5a6c8e3652465
refs/heads/master
2023-08-31T08:59:00.366903
2023-08-31T07:42:24
2023-08-31T07:42:24
230,028,961
9
3
null
2023-07-20T16:53:31
2019-12-25T02:29:32
C++
UTF-8
C++
false
false
419
cxx
#include <Aft2d_gSegmentEdge.hxx> #include <Aft2d_gPlnCurveSurface.hxx> #include <Aft2d_ElementSurface.hxx> template<> TNB_SAVE_IMPLEMENTATION(tnbLib::Mesh_BndEdgeGeomAdaptorBase<tnbLib::Aft2d_gPlnCurveSurface>) { ar & theCurve_; } template<> TNB_LOAD_IMPLEMENTATION(tnbLib::Mesh_BndEdgeGeomAdaptorBase<tnbLib::Aft2d_gPlnCurveSurface>) { ar & theCurve_; } BOOST_CLASS_EXPORT_IMPLEMENT(tnbLib::Aft2d_gSegmentEdge);
[ "aasoleimani86@gmail.com" ]
aasoleimani86@gmail.com
951f318f49aa7972afcd8b68cf015a43f593d3db
18795f2721c4572e7d375d316686326dc70cf51e
/mtmlib/ssmType.hpp
fb4439a27309a4bfb74e06630152d07ca8ea9fa7
[]
no_license
tamago2013/tamago2013
1401f9a1e3ea270c2beb71f93f09b8eb1c6e46fd
d60e82ab3e4847d32fbdd087dafd282ddbacffc4
refs/heads/master
2020-04-16T11:19:28.653025
2013-11-16T16:47:10
2013-11-16T16:47:10
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,735
hpp
/* SSM Type SSMの名前ここで定義しておく 2012/10/11 MTM */ #ifndef MTM_SSM_TYPE #define MTM_SSM_TYPE #include"ssm-laser.hpp" //Line_GL============================================================= //MTM Line_Data(自作判定された線分の始点・終点データ(GL座標系)) #define SNAME_MTM_LINE "Line_Data" #define SID_MTM_LINE 2 #define SID_MTM_GRAND_EDGE 5 //直線データ型の定義 typedef struct{ int numpoints; int points_on_the_line[100]; //その直線上に乗った点の数 double start_x[100]; //その直線の始点x座標 double start_y[100]; //その直線の始点y座標 double finish_x[100]; //その直線の終点x座標 double finish_y[100]; //その直線の終点y座標 }MTM_Line; //Pinfo(YSD)========================================================== #define SNAME_YSD_PINFO "Pinfo" #define SID_YSD_PINFO 1 typedef struct{ int route; int waypoint; }YSD_Pinfo; //MapChangerの流すMap番号=============================================== #define SNAME_MTM_MINFO "Minfo" #define SID_MTM_MINFO_LINE 0 #define SID_MTM_MINFO_EDGE 1 #define MTM_MINFO_CHAR_SIZE 300 typedef struct{ char mapname[MTM_MINFO_CHAR_SIZE]; //マップのフルパス(最大200文字) int mapnum; //マップ番号 }MTM_Minfo; //Adjusterが流すそれぞれのアジャスト情報====================================== #define SNAME_MTM_ADJUST "MTM_Adjust" #define SID_MTM_ADJUST_LINE 1 #define SID_MTM_ADJUST_GRAND_EDGE 2 typedef struct{ double x; double y; double theta; bool valid; //有効かどうか(アジャスト失敗時はこれをtrueに) }MTM_Adjust; //YSDのGrandEdgeDetectorの情報========================================== #define SNAME_YSD_GRAND_EDGE SSM_NAME_SOKUIKI_3D_FS_EDGE #define SID_YSD_GRAND_EDGE 1 /* 構造体はSSM_SOKUIKI_3D */ /* //GrandEdgeGetterが流す蓄積されたEdge情報================================= //YSD_GRAND_EDGEがあるのでおそらくデバッグ用 #define SNAME_MTM_GRAND_EDGE "Heaped_Grand_Edge" #define SID_MTM_GRAND_EDGE 2 #define MTM_GRAND_EDGE_SIZE 500 typedef struct{ int numpoints; float edge_x_gl[MTM_GRAND_EDGE_SIZE]; float edge_y_gl[MTM_GRAND_EDGE_SIZE]; }MTM_GrandEdge; //GrandEdgeGetterが流す蓄積されたEdge情報================================= //YSD_GRAND_EDGEがあるのでおそらくデバッグ用 #define SNAME_MTM_GRAND_EDGE_LINE "Heaped_Grand_Edge_Line" #define SID_MTM_GRAND_EDGE_LINE 2 typedef struct{ int numpoints; double start_x[100]; //その直線の始点x座標 double start_y[100]; //その直線の始点y座標 double finish_x[100]; //その直線の終点x座標 double finish_y[100]; //その直線の終点y座標 }MTM_GrandEdgeLine; */ #endif
[ "a-matsumoto@roboken.esys.tsukuba.ac.jp" ]
a-matsumoto@roboken.esys.tsukuba.ac.jp