hexsha
stringlengths
40
40
size
int64
7
1.05M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
269
max_stars_repo_name
stringlengths
5
108
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
269
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
9
max_issues_count
int64
1
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
269
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
9
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
7
1.05M
avg_line_length
float64
1.21
330k
max_line_length
int64
6
990k
alphanum_fraction
float64
0.01
0.99
author_id
stringlengths
2
40
c62ba82f26507c4449211900d7af3342ea19710f
854
cpp
C++
lab3/lab6/lab6/main.cpp
AlexBlack559/stllabs
8dd7bcf154c87631e125874dffa9d5189d1c14f9
[ "MIT" ]
null
null
null
lab3/lab6/lab6/main.cpp
AlexBlack559/stllabs
8dd7bcf154c87631e125874dffa9d5189d1c14f9
[ "MIT" ]
null
null
null
lab3/lab6/lab6/main.cpp
AlexBlack559/stllabs
8dd7bcf154c87631e125874dffa9d5189d1c14f9
[ "MIT" ]
null
null
null
// // main.cpp // lab6 // // Created by Alexander Chernyi on 29/09/2017. // Copyright © 2017 Alexander Chernyi. All rights reserved. // #include <iostream> #include <fstream> #include <streambuf> #include <vector> #include <set> using namespace std; struct Point { int x,y; }; struct Shape { int vetex_num; vector<Point> vertexes; }; void task1() { ifstream file; file.open("File.txt"); if (!file) { cerr << "Error reading file" << endl; return; } set<string> words; copy(istream_iterator<string>(file), istream_iterator<string>(), inserter(words, words.begin())); copy(words.begin(), words.end(), ostream_iterator<string>(cout, " ")); cout << endl; } void task2() { } int main(int argc, const char * argv[]) { task1(); task2(); return 0; }
16.113208
101
0.591335
AlexBlack559
c62c55c7b1eb1fc5972b151f4e333698db251c05
1,133
cc
C++
UVa Online Judge/v110/11003.cc
mjenrungrot/algorithm
e0e8174eb133ba20931c2c7f5c67732e4cb2b703
[ "MIT" ]
1
2021-12-08T08:58:43.000Z
2021-12-08T08:58:43.000Z
UVa Online Judge/v110/11003.cc
mjenrungrot/algorithm
e0e8174eb133ba20931c2c7f5c67732e4cb2b703
[ "MIT" ]
null
null
null
UVa Online Judge/v110/11003.cc
mjenrungrot/algorithm
e0e8174eb133ba20931c2c7f5c67732e4cb2b703
[ "MIT" ]
null
null
null
/*============================================================================= # Author: Teerapat Jenrungrot - https://github.com/mjenrungrot/ # FileName: 11003.cc # Description: UVa Online Judge - 11003 =============================================================================*/ #include <bits/stdc++.h> using namespace std; typedef pair<int, int> ii; const int MAXLIMIT = 6005; int main() { ios::sync_with_stdio(false); cin.tie(0); int N; while (cin >> N) { if (N == 0) break; vector<ii> A(N); for (int i = 0; i < N; i++) { int weight, load; cin >> weight >> load; A[i] = ii(weight, load); } vector<int> dp(MAXLIMIT, -1); dp[0] = 0; int ans = 0; for (int i = N - 1; i >= 0; i--) { for (int j = A[i].second - 1; j >= 0; j--) { if (dp[j] == -1) continue; dp[j + A[i].first] = max(dp[j + A[i].first], dp[j] + 1); ans = max(ans, dp[j + A[i].first]); } } cout << ans << endl; } return 0; }
26.97619
79
0.375993
mjenrungrot
c632a0e5946095aca67f1f114964edc6bfc45080
14,720
cpp
C++
src/2ls/summary_checker_base.cpp
viktormalik/2ls
d35ccf73c34d48e6fbf9a25049cd9c77bc2cb02a
[ "BSD-4-Clause" ]
null
null
null
src/2ls/summary_checker_base.cpp
viktormalik/2ls
d35ccf73c34d48e6fbf9a25049cd9c77bc2cb02a
[ "BSD-4-Clause" ]
3
2017-09-15T14:43:44.000Z
2017-11-24T09:12:41.000Z
src/2ls/summary_checker_base.cpp
viktormalik/2ls
d35ccf73c34d48e6fbf9a25049cd9c77bc2cb02a
[ "BSD-4-Clause" ]
2
2017-09-18T09:41:22.000Z
2018-01-29T18:12:33.000Z
/*******************************************************************\ Module: Summary Checker Base Author: Peter Schrammel \*******************************************************************/ /// \file /// Summary Checker Base #include <iostream> #include <util/options.h> #include <util/i2string.h> #include <util/simplify_expr.h> #include <langapi/language_util.h> #include <util/prefix.h> #include <goto-programs/write_goto_binary.h> #include <solvers/sat/satcheck.h> #include <solvers/flattening/bv_pointers.h> #include <solvers/prop/literal_expr.h> #include <ssa/local_ssa.h> #include <ssa/simplify_ssa.h> #include <ssa/ssa_build_goto_trace.h> #include <domains/ssa_analyzer.h> #include <ssa/ssa_unwinder.h> #include <solver/summarizer_fw.h> #include <solver/summarizer_fw_term.h> #include <solver/summarizer_bw.h> #include <solver/summarizer_bw_term.h> #ifdef SHOW_CALLING_CONTEXTS #include <solver/summarizer_fw_contexts.h> #endif #include "show.h" #include "instrument_goto.h" #include "summary_checker_base.h" void summary_checker_baset::SSA_functions( const goto_modelt &goto_model, const namespacet &ns) { // compute SSA for all the functions forall_goto_functions(f_it, goto_model.goto_functions) { if(!f_it->second.body_available()) continue; if(has_prefix(id2string(f_it->first), TEMPLATE_DECL)) continue; status() << "Computing SSA of " << f_it->first << messaget::eom; ssa_db.create(f_it->first, f_it->second, ns); local_SSAt &SSA=ssa_db.get(f_it->first); // simplify, if requested if(simplify) { status() << "Simplifying" << messaget::eom; ::simplify(SSA, ns); } SSA.output(debug()); debug() << eom; } // properties initialize_property_map(goto_model.goto_functions); } void summary_checker_baset::summarize( const goto_modelt &goto_model, bool forward, bool termination) { summarizer_baset *summarizer=NULL; #ifdef SHOW_CALLING_CONTEXTS if(options.get_bool_option("show-calling-contexts")) summarizer=new summarizer_fw_contextst( options, summary_db, ssa_db, ssa_unwinder, ssa_inliner); else // NOLINT(*) #endif { if(forward && !termination) summarizer=new summarizer_fwt( options, summary_db, ssa_db, ssa_unwinder, ssa_inliner); if(forward && termination) summarizer=new summarizer_fw_termt( options, summary_db, ssa_db, ssa_unwinder, ssa_inliner); if(!forward && !termination) summarizer=new summarizer_bwt( options, summary_db, ssa_db, ssa_unwinder, ssa_inliner); if(!forward && termination) summarizer=new summarizer_bw_termt( options, summary_db, ssa_db, ssa_unwinder, ssa_inliner); } assert(summarizer!=NULL); summarizer->set_message_handler(get_message_handler()); if(!options.get_bool_option("context-sensitive") && options.get_bool_option("all-functions")) summarizer->summarize(); else summarizer->summarize(goto_model.goto_functions.entry_point()); // statistics solver_instances+=summarizer->get_number_of_solver_instances(); solver_calls+=summarizer->get_number_of_solver_calls(); summaries_used+=summarizer->get_number_of_summaries_used(); termargs_computed+=summarizer->get_number_of_termargs_computed(); delete summarizer; } summary_checker_baset::resultt summary_checker_baset::check_properties() { // analyze all the functions for(ssa_dbt::functionst::const_iterator f_it=ssa_db.functions().begin(); f_it!=ssa_db.functions().end(); f_it++) { status() << "Checking properties of " << f_it->first << messaget::eom; #if 0 // for debugging show_ssa_symbols(*f_it->second, std::cerr); #endif check_properties(f_it); if(options.get_bool_option("show-invariants")) { if(!summary_db.exists(f_it->first)) continue; show_invariants(*(f_it->second), summary_db.get(f_it->first), result()); result() << eom; } } summary_checker_baset::resultt result=property_checkert::PASS; for(property_mapt::const_iterator p_it=property_map.begin(); p_it!=property_map.end(); p_it++) { if(p_it->second.result==FAIL) return property_checkert::FAIL; if(p_it->second.result==UNKNOWN) result=property_checkert::UNKNOWN; } return result; } void summary_checker_baset::check_properties( const ssa_dbt::functionst::const_iterator f_it) { unwindable_local_SSAt &SSA=*f_it->second; bool all_properties=options.get_bool_option("all-properties"); SSA.output_verbose(debug()); debug() << eom; // incremental version // solver incremental_solvert &solver=ssa_db.get_solver(f_it->first); solver.set_message_handler(get_message_handler()); // give SSA to solver solver << SSA; SSA.mark_nodes(); solver.new_context(); exprt enabling_expr=SSA.get_enabling_exprs(); solver << enabling_expr; // invariant, calling contexts if(summary_db.exists(f_it->first)) { solver << summary_db.get(f_it->first).fw_invariant; solver << summary_db.get(f_it->first).fw_precondition; if(options.get_bool_option("heap") && summary_db.get(f_it->first).aux_precondition.is_not_nil()) { solver << summary_db.get(f_it->first).aux_precondition; } } // callee summaries solver << ssa_inliner.get_summaries(SSA); // freeze loop head selects exprt::operandst loophead_selects= get_loophead_selects(f_it->first, SSA, *solver.solver); // check whether loops have been fully unwound exprt::operandst loop_continues= get_loop_continues(f_it->first, SSA, *solver.solver); bool fully_unwound= is_fully_unwound(loop_continues, loophead_selects, solver); status() << "Loops " << (fully_unwound ? "" : "not ") << "fully unwound" << eom; cover_goals_extt cover_goals( SSA, solver, loophead_selects, property_map, !fully_unwound && options.get_bool_option("spurious-check"), all_properties, options.get_bool_option("trace") || options.get_option("graphml-witness")!="" || options.get_option("json-cex")!=""); #if 0 debug() << "(C) " << from_expr(SSA.ns, "", enabling_expr) << eom; #endif const goto_programt &goto_program=SSA.goto_function.body; for(goto_programt::instructionst::const_iterator i_it=goto_program.instructions.begin(); i_it!=goto_program.instructions.end(); i_it++) { if(!i_it->is_assert()) continue; const source_locationt &location=i_it->source_location; irep_idt property_id=location.get_property_id(); if(i_it->guard.is_true()) { property_map[property_id].result=PASS; continue; } // do not recheck properties that have already been decided if(property_map[property_id].result!=UNKNOWN) continue; // TODO: some properties do not show up in initialize_property_map if(property_id=="") continue; std::list<local_SSAt::nodest::const_iterator> assertion_nodes; SSA.find_nodes(i_it, assertion_nodes); unsigned property_counter=0; for(std::list<local_SSAt::nodest::const_iterator>::const_iterator n_it=assertion_nodes.begin(); n_it!=assertion_nodes.end(); n_it++) { for(local_SSAt::nodet::assertionst::const_iterator a_it=(*n_it)->assertions.begin(); a_it!=(*n_it)->assertions.end(); a_it++, property_counter++) { exprt property=*a_it; if(simplify) property=::simplify_expr(property, SSA.ns); #if 0 std::cout << "property: " << from_expr(SSA.ns, "", property) << std::endl; #endif property_map[property_id].location=i_it; cover_goals.goal_map[property_id].conjuncts.push_back(property); } } } for(cover_goals_extt::goal_mapt::const_iterator it=cover_goals.goal_map.begin(); it!=cover_goals.goal_map.end(); it++) { // Our goal is to falsify a property. // The following is TRUE if the conjunction is empty. literalt p=!solver.convert(conjunction(it->second.conjuncts)); cover_goals.add(p); } status() << "Running " << solver.solver->decision_procedure_text() << eom; cover_goals(); // set all non-covered goals to PASS except if we do not try // to cover all goals and we have found a FAIL if(all_properties || cover_goals.number_covered()==0) { std::list<cover_goals_extt::cover_goalt>::const_iterator g_it= cover_goals.goals.begin(); for(cover_goals_extt::goal_mapt::const_iterator it=cover_goals.goal_map.begin(); it!=cover_goals.goal_map.end(); it++, g_it++) { if(!g_it->covered) property_map[it->first].result=PASS; } } solver.pop_context(); debug() << "** " << cover_goals.number_covered() << " of " << cover_goals.size() << " failed (" << cover_goals.iterations() << " iterations)" << eom; } void summary_checker_baset::report_statistics() { for(ssa_dbt::functionst::const_iterator f_it=ssa_db.functions().begin(); f_it!=ssa_db.functions().end(); f_it++) { incremental_solvert &solver=ssa_db.get_solver(f_it->first); unsigned calls=solver.get_number_of_solver_calls(); if(calls>0) solver_instances++; solver_calls+=calls; } statistics() << "** statistics: " << eom; statistics() << " number of solver instances: " << solver_instances << eom; statistics() << " number of solver calls: " << solver_calls << eom; statistics() << " number of summaries used: " << summaries_used << eom; statistics() << " number of termination arguments computed: " << termargs_computed << eom; statistics() << eom; } void summary_checker_baset::do_show_vcc( const local_SSAt &SSA, const goto_programt::const_targett i_it, const local_SSAt::nodet::assertionst::const_iterator &a_it) { std::cout << i_it->source_location << "\n"; std::cout << i_it->source_location.get_comment() << "\n"; std::list<exprt> ssa_constraints; ssa_constraints << SSA; unsigned i=1; for(std::list<exprt>::const_iterator c_it=ssa_constraints.begin(); c_it!=ssa_constraints.end(); c_it++, i++) std::cout << "{-" << i << "} " << from_expr(SSA.ns, "", *c_it) << "\n"; std::cout << "|--------------------------\n"; std::cout << "{1} " << from_expr(SSA.ns, "", *a_it) << "\n"; std::cout << "\n"; } /// returns the select guards at the loop heads in order to check whether a /// countermodel is spurious exprt::operandst summary_checker_baset::get_loophead_selects( const irep_idt &function_name, const local_SSAt &SSA, prop_convt &solver) { // TODO: this should be provided by unwindable_local_SSA exprt::operandst loophead_selects; for(local_SSAt::nodest::const_iterator n_it=SSA.nodes.begin(); n_it!=SSA.nodes.end(); n_it++) { if(n_it->loophead==SSA.nodes.end()) continue; symbol_exprt lsguard= SSA.name(SSA.guard_symbol(), local_SSAt::LOOP_SELECT, n_it->location); ssa_unwinder.get(function_name).unwinder_rename(lsguard, *n_it, true); loophead_selects.push_back(not_exprt(lsguard)); solver.set_frozen(solver.convert(lsguard)); } literalt loophead_selects_literal= solver.convert(conjunction(loophead_selects)); if(!loophead_selects_literal.is_constant()) solver.set_frozen(loophead_selects_literal); #if 0 std::cout << "loophead_selects: " << from_expr(SSA.ns, "", conjunction(loophead_selects)) << std::endl; #endif return loophead_selects; } /// returns the loop continuation guards at the end of the loops in order to /// check whether we can unroll further exprt::operandst summary_checker_baset::get_loop_continues( const irep_idt &function_name, const local_SSAt &SSA, prop_convt &solver) { // TODO: this should be provided by unwindable_local_SSA exprt::operandst loop_continues; ssa_unwinder.get(function_name).loop_continuation_conditions(loop_continues); if(loop_continues.size()==0) { // TODO: this should actually be done transparently by the unwinder for(local_SSAt::nodest::const_iterator n_it=SSA.nodes.begin(); n_it!=SSA.nodes.end(); n_it++) { if(n_it->loophead==SSA.nodes.end()) continue; symbol_exprt guard=SSA.guard_symbol(n_it->location); symbol_exprt cond=SSA.cond_symbol(n_it->location); loop_continues.push_back(and_exprt(guard, cond)); } } #if 0 std::cout << "loophead_continues: " << from_expr(SSA.ns, "", disjunction(loop_continues)) << std::endl; #endif return loop_continues; } /// checks whether the loops have been fully unwound bool summary_checker_baset::is_fully_unwound( const exprt::operandst &loop_continues, const exprt::operandst &loophead_selects, incremental_solvert &solver) { solver.new_context(); solver << and_exprt(conjunction(loophead_selects), disjunction(loop_continues)); solver_calls++; // statistics switch(solver()) { case decision_proceduret::D_SATISFIABLE: solver.pop_context(); return false; break; case decision_proceduret::D_UNSATISFIABLE: solver.pop_context(); solver << conjunction(loophead_selects); return true; break; case decision_proceduret::D_ERROR: default: throw "error from decision procedure"; } } /// checks whether a countermodel is spurious bool summary_checker_baset::is_spurious( const exprt::operandst &loophead_selects, incremental_solvert &solver) { // check loop head choices in model bool invariants_involved=false; for(exprt::operandst::const_iterator l_it=loophead_selects.begin(); l_it!=loophead_selects.end(); l_it++) { if(solver.get(l_it->op0()).is_true()) { invariants_involved=true; break; } } if(!invariants_involved) return false; // force avoiding paths going through invariants solver << conjunction(loophead_selects); solver_calls++; // statistics switch(solver()) { case decision_proceduret::D_SATISFIABLE: return false; break; case decision_proceduret::D_UNSATISFIABLE: return true; break; case decision_proceduret::D_ERROR: default: throw "error from decision procedure"; } } /// instruments the code with the inferred information and outputs it to a goto- /// binary void summary_checker_baset::instrument_and_output(goto_modelt &goto_model) { instrument_gotot instrument_goto(options, ssa_db, summary_db); instrument_goto(goto_model); std::string filename=options.get_option("instrument-output"); status() << "Writing instrumented goto-binary " << filename << eom; write_goto_binary( filename, goto_model.symbol_table, goto_model.goto_functions, get_message_handler()); }
28.862745
80
0.68587
viktormalik
c6343e197bf845ef1682bf5f1721539496c8f16a
5,260
cc
C++
chrome/browser/policy/device_token_fetcher_unittest.cc
SlimKatLegacy/android_external_chromium
bc611cda58cc18d0dbaa8a7aee05eb3c0742e573
[ "BSD-3-Clause" ]
2
2017-02-20T14:25:04.000Z
2019-12-13T13:58:28.000Z
chrome/browser/policy/device_token_fetcher_unittest.cc
SlimKatLegacy/android_external_chromium
bc611cda58cc18d0dbaa8a7aee05eb3c0742e573
[ "BSD-3-Clause" ]
2
2017-07-25T09:37:22.000Z
2017-08-04T07:18:56.000Z
chrome/browser/policy/device_token_fetcher_unittest.cc
SlimKatLegacy/android_external_chromium
bc611cda58cc18d0dbaa8a7aee05eb3c0742e573
[ "BSD-3-Clause" ]
2
2017-08-09T09:03:23.000Z
2020-05-26T09:14:49.000Z
// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/policy/device_token_fetcher.h" #include "base/file_util.h" #include "base/memory/scoped_temp_dir.h" #include "base/message_loop.h" #include "chrome/browser/net/gaia/token_service.h" #include "chrome/browser/policy/device_management_service.h" #include "chrome/browser/policy/mock_device_management_backend.h" #include "chrome/browser/policy/mock_device_management_service.h" #include "chrome/browser/policy/policy_notifier.h" #include "chrome/browser/policy/proto/device_management_backend.pb.h" #include "chrome/browser/policy/user_policy_cache.h" #include "chrome/common/net/gaia/gaia_constants.h" #include "chrome/test/testing_profile.h" #include "content/browser/browser_thread.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" namespace policy { const char kTestToken[] = "device_token_fetcher_test_auth_token"; using testing::_; using testing::Mock; class MockTokenAvailableObserver : public DeviceTokenFetcher::Observer { public: MockTokenAvailableObserver() {} virtual ~MockTokenAvailableObserver() {} MOCK_METHOD0(OnDeviceTokenAvailable, void()); private: DISALLOW_COPY_AND_ASSIGN(MockTokenAvailableObserver); }; class DeviceTokenFetcherTest : public testing::Test { protected: DeviceTokenFetcherTest() : ui_thread_(BrowserThread::UI, &loop_), file_thread_(BrowserThread::FILE, &loop_) { EXPECT_TRUE(temp_user_data_dir_.CreateUniqueTempDir()); } virtual void SetUp() { cache_.reset(new UserPolicyCache( temp_user_data_dir_.path().AppendASCII("DeviceTokenFetcherTest"))); service_.set_backend(&backend_); } virtual void TearDown() { loop_.RunAllPending(); } MessageLoop loop_; MockDeviceManagementBackend backend_; MockDeviceManagementService service_; scoped_ptr<CloudPolicyCacheBase> cache_; PolicyNotifier notifier_; ScopedTempDir temp_user_data_dir_; private: BrowserThread ui_thread_; BrowserThread file_thread_; }; TEST_F(DeviceTokenFetcherTest, FetchToken) { testing::InSequence s; EXPECT_CALL(backend_, ProcessRegisterRequest(_, _, _, _)).WillOnce( MockDeviceManagementBackendSucceedRegister()); DeviceTokenFetcher fetcher(&service_, cache_.get(), &notifier_); MockTokenAvailableObserver observer; EXPECT_CALL(observer, OnDeviceTokenAvailable()); fetcher.AddObserver(&observer); EXPECT_EQ("", fetcher.GetDeviceToken()); fetcher.FetchToken("fake_auth_token", "fake_device_id", em::DeviceRegisterRequest::USER, "fake_machine_id", "fake_machine_model"); loop_.RunAllPending(); Mock::VerifyAndClearExpectations(&observer); std::string token = fetcher.GetDeviceToken(); EXPECT_NE("", token); // Calling FetchToken() again should result in a new token being fetched. EXPECT_CALL(backend_, ProcessRegisterRequest(_, _, _, _)).WillOnce( MockDeviceManagementBackendSucceedRegister()); EXPECT_CALL(observer, OnDeviceTokenAvailable()); fetcher.FetchToken("fake_auth_token", "fake_device_id", em::DeviceRegisterRequest::USER, "fake_machine_id", "fake_machine_model"); loop_.RunAllPending(); Mock::VerifyAndClearExpectations(&observer); std::string token2 = fetcher.GetDeviceToken(); EXPECT_NE("", token2); EXPECT_NE(token, token2); fetcher.RemoveObserver(&observer); } TEST_F(DeviceTokenFetcherTest, RetryOnError) { testing::InSequence s; EXPECT_CALL(backend_, ProcessRegisterRequest(_, _, _, _)).WillOnce( MockDeviceManagementBackendFailRegister( DeviceManagementBackend::kErrorRequestFailed)).WillOnce( MockDeviceManagementBackendSucceedRegister()); DeviceTokenFetcher fetcher(&service_, cache_.get(), &notifier_, 0, 0, 0); MockTokenAvailableObserver observer; EXPECT_CALL(observer, OnDeviceTokenAvailable()); fetcher.AddObserver(&observer); fetcher.FetchToken("fake_auth_token", "fake_device_id", em::DeviceRegisterRequest::USER, "fake_machine_id", "fake_machine_model"); loop_.RunAllPending(); Mock::VerifyAndClearExpectations(&observer); EXPECT_NE("", fetcher.GetDeviceToken()); fetcher.RemoveObserver(&observer); } TEST_F(DeviceTokenFetcherTest, UnmanagedDevice) { EXPECT_CALL(backend_, ProcessRegisterRequest(_, _, _, _)).WillOnce( MockDeviceManagementBackendFailRegister( DeviceManagementBackend::kErrorServiceManagementNotSupported)); EXPECT_FALSE(cache_->is_unmanaged()); DeviceTokenFetcher fetcher(&service_, cache_.get(), &notifier_); MockTokenAvailableObserver observer; EXPECT_CALL(observer, OnDeviceTokenAvailable()).Times(0); fetcher.AddObserver(&observer); fetcher.FetchToken("fake_auth_token", "fake_device_id", em::DeviceRegisterRequest::USER, "fake_machine_id", "fake_machine_model"); loop_.RunAllPending(); Mock::VerifyAndClearExpectations(&observer); EXPECT_EQ("", fetcher.GetDeviceToken()); EXPECT_TRUE(cache_->is_unmanaged()); fetcher.RemoveObserver(&observer); } } // namespace policy
37.042254
75
0.752281
SlimKatLegacy
c634b533805e345840f1a76fbdcf6a21e52977b2
2,745
hpp
C++
aessparse.hpp
pibara/AESsparsepp
12c51fd93ea344e6a65715026fe5baa6c18c34ed
[ "BSD-3-Clause" ]
1
2019-04-30T05:40:55.000Z
2019-04-30T05:40:55.000Z
aessparse.hpp
pibara/AESsparsepp
12c51fd93ea344e6a65715026fe5baa6c18c34ed
[ "BSD-3-Clause" ]
null
null
null
aessparse.hpp
pibara/AESsparsepp
12c51fd93ea344e6a65715026fe5baa6c18c34ed
[ "BSD-3-Clause" ]
null
null
null
#ifndef _AESSPARSE_HPP #define _AESSPARSE_HPP namespace aessparse { //Interface for any type of sparse file implementation. struct abstract_sparse_file { //Low level read and write. virtual ssize_t read(void *buf, size_t count, off_t offset) = 0; virtual ssize_t write(const void *buf, size_t count, off_t offset) = 0; //Navigation functions within hole/data fragments. virtual off_t lseek_data(off_t offset) = 0; virtual off_t lseek_hole(off_t offset) = 0; //Query the size of the file. virtual off_t getsize() = 0; }; //Non owning open file rw opened loopback implementation for sparse file. struct loopback_sparse_file: public abstract_sparse_file { loopback_sparse_file(int file); ssize_t read(void *buf, size_t count, off_t offset); ssize_t write(const void *buf, size_t count, off_t offset); off_t lseek_data(off_t offset); off_t lseek_hole(off_t offset); off_t getsize(); private: int mFile; }; //Interface for aes sparse file. struct abstract_aes_sparse_file { //low level read and write functions. virtual ssize_t read(void *buf, size_t count, off_t offset) = 0; virtual ssize_t write(const void *buf, size_t count, off_t offset) = 0; //Don't really know a good interface for communicating padding size yet, this is a place holder for something suitable. virtual ssize_t getpadlen() = 0; }; struct aes_sparse_file; //movable pimpl wrapper. struct aes_sparse_file: public abstract_aes_sparse_file { //creation function is frind so it can invoke constructor. friend aes_sparse_file create_aes_sparse_file(abstract_sparse_file const &, CryptoPP::SecByteBlock); //Move constuctor, needed by creator function invocation. aes_sparse_file(aes_sparse_file&& other); aes_sparse_file& operator=(aes_sparse_file&& other); //No coppy allowed aes_sparse_file(aes_sparse_file& other) = delete; aes_sparse_file& operator=(aes_sparse_file& other) = delete; //destructor will destroy 'owned' pImpl if needed. ~aes_sparse_file(); ssize_t read(void *buf, size_t count, off_t offset); ssize_t write(const void *buf, size_t count, off_t offset); virtual ssize_t getpadlen(); private: //Private constructor to be used by friend creation function aes_sparse_file(abstract_sparse_file *impl); //Pointer to implementation. abstract_aes_sparse_file *pImpl; }; //Function for creating a aes sparse file using a sparse file and a file encryption key. aes_sparse_file create_aes_sparse_file(abstract_sparse_file const &, CryptoPP::SecByteBlock); } #endif
45.75
125
0.704918
pibara
c637589e05691bfe79809edbeceb26fcd88d3765
1,972
cpp
C++
Other/CampusChapter1/GAMENUM.cpp
vinaysomawat/CodeChef-Solutions
9a0666a4f1badd593cd075f3beb05377e3c6657a
[ "MIT" ]
1
2020-04-12T01:39:10.000Z
2020-04-12T01:39:10.000Z
Other/CampusChapter1/GAMENUM.cpp
vinaysomawat/CodeChef-Solutions
9a0666a4f1badd593cd075f3beb05377e3c6657a
[ "MIT" ]
null
null
null
Other/CampusChapter1/GAMENUM.cpp
vinaysomawat/CodeChef-Solutions
9a0666a4f1badd593cd075f3beb05377e3c6657a
[ "MIT" ]
null
null
null
/* Contest: CodeChef March 2020 Cook-Off challange Problem link:https://www.codechef.com/CHPTRS01/problems/GAMENUM GitHub Solution Repository: https://github.com/vinaysomawat/CodeChef-Solutions Author: Vinay Somawat Author's Webpage: http://vinaysomawat.github.io/ Author's mail: vinaysomawat@hotmail.com */ #include<bits/stdc++.h> #define ll long long int using namespace std; #define IOS ios::sync_with_stdio(0); cin.tie(0); cout.tie(0); #ifdef LOCAL #define trace(...) __f(#__VA_ARGS__, __VA_ARGS__) template <typename Arg1> void __f(const char* name, Arg1&& arg1){ cerr << name << ": " << arg1 << endl; } template <typename Arg1, typename... Args> void __f(const char* names, Arg1&& arg1, Args&&... args){ const char* comma = strchr(names + 1, ','); cerr.write(names, comma - names) << ": " << arg1 << " |"; __f(comma + 1, args...); } #else #define trace(...) 42 #endif ll n; void fill(ll a, string &aa){ int i = n - 1; while(a){ if (a&1){ aa[i] = '1'; } a = a >> 1; i--; } } void solve() { ll a, b; cin >> a >> b; n = floor(log2(max(a, b))) + 1; string aa(n, '0'), bb(n, '0'); fill(a, aa); fill(b, bb); trace(aa, bb); ll mx = a ^ b; trace(mx); int rotations = 0; int ansrt = 0; for (int i = 1; i <= 65; i++){ rotate(bb.rbegin(), bb.rbegin()+1, bb.rend()); ll x = bitset<64>(bb).to_ullong(); if (x == b) break; rotations++; if ((x ^ a) > mx){ ansrt = rotations; mx = x ^ a; } } cout << ansrt << ' ' << mx << endl; } int main(){ IOS; #ifdef LOCAL #endif int t; cin >> t; while(t--){ solve(); } #ifdef LOCAL cerr << "Time elapsed: " << 1.0 * clock() / CLOCKS_PER_SEC << " s.\n"; #endif return 0; }
21.204301
82
0.501014
vinaysomawat
c637af69d097f5019a95a19120f626dc1e8250aa
663
hpp
C++
extras/CAEN/include/CAENFlashException.hpp
flagarde/YAODAQ
851df4aa32b8695c4706bb3ec9f353f4461c9cad
[ "MIT" ]
null
null
null
extras/CAEN/include/CAENFlashException.hpp
flagarde/YAODAQ
851df4aa32b8695c4706bb3ec9f353f4461c9cad
[ "MIT" ]
11
2021-05-14T19:50:27.000Z
2022-03-31T07:19:41.000Z
extras/CAEN/include/CAENFlashException.hpp
flagarde/YAODAQ
851df4aa32b8695c4706bb3ec9f353f4461c9cad
[ "MIT" ]
5
2021-05-11T13:30:30.000Z
2021-05-26T19:57:22.000Z
#pragma once #include "Exception.hpp" namespace CAEN { enum FLASH_API_ERROR_CODES : int_least32_t { SUCCESS = 0, ACCESS_FAILED = -1, PARAMETER_NOT_ALLOWED = -2, FILE_OPEN_ERROR = -3, MALLOC_ERROR = -4, UNINITIALIZED = -5, NOT_IMPLEMENTED = -6, UNSUPPORTED_FLASH_DEVICE = -7 }; class CAENFlashException: public yaodaq::Exception { public: CAENFlashException(const int_least32_t& code, const source_location& location = source_location::current()); private: CAENFlashException() = delete; const char* errorStrings(const int_least32_t& code); }; } // namespace CAEN
22.1
110
0.656109
flagarde
c6390e9603cc1dc1a6049e71dfc2921decdf829d
1,193
hpp
C++
peer/src/base/RpcId.hpp
MisterTea/we-go-all
a58948db466d419ea6b12e0bac61c383d1c49a83
[ "Apache-2.0" ]
2
2018-10-08T22:08:55.000Z
2019-02-06T17:44:24.000Z
peer/src/base/RpcId.hpp
MisterTea/we-go-all
a58948db466d419ea6b12e0bac61c383d1c49a83
[ "Apache-2.0" ]
null
null
null
peer/src/base/RpcId.hpp
MisterTea/we-go-all
a58948db466d419ea6b12e0bac61c383d1c49a83
[ "Apache-2.0" ]
null
null
null
#ifndef __RPC_ID_H__ #define __RPC_ID_H__ #include "Headers.hpp" namespace wga { class RpcId { public: RpcId() : barrier(0), id(0) {} RpcId(int64_t _barrier, uint64_t _id) : barrier(_barrier), id(_id) {} bool operator==(const RpcId& other) const { return barrier == other.barrier && id == other.id; } bool operator!=(const RpcId& other) const { return !(*this == other); } bool operator<(const RpcId& other) const { return barrier < other.barrier || (barrier == other.barrier && id < other.id); } string str() const { return to_string(barrier) + "/" + to_string(id); } bool empty() { return barrier == 0 && id == 0; } int64_t barrier; uint64_t id; }; } // namespace wga namespace std { template <> struct hash<wga::RpcId> { public: // hash functor: hash uuid to size_t value by pseudorandomizing transform size_t operator()(const wga::RpcId& rpcId) const { if (sizeof(size_t) > 4) { return size_t(rpcId.barrier ^ rpcId.id); } else { uint64_t hash64 = rpcId.barrier ^ rpcId.id; return size_t(uint32_t(hash64 >> 32) ^ uint32_t(hash64)); } } }; } // namespace std #define SESSION_KEY_RPCID RpcId(0, 1) #endif
25.934783
75
0.643755
MisterTea
c639773af75377d6274e825e3cbaafc1df93caeb
662
cpp
C++
luogu/codes/P1226.cpp
Tony031218/OI
562f5f45d0448f4eab77643b99b825405a123d92
[ "MIT" ]
1
2021-02-22T03:39:24.000Z
2021-02-22T03:39:24.000Z
luogu/codes/P1226.cpp
Tony031218/OI
562f5f45d0448f4eab77643b99b825405a123d92
[ "MIT" ]
null
null
null
luogu/codes/P1226.cpp
Tony031218/OI
562f5f45d0448f4eab77643b99b825405a123d92
[ "MIT" ]
null
null
null
/************************************************************* * > File Name : P1226.cpp * > Author : Tony * > Created Time : 2019/05/07 15:29:41 **************************************************************/ #include <bits/stdc++.h> using namespace std; typedef long long LL; LL b, p, k; LL pow_mod(LL a, LL p, LL n) { if (p == 0 && n == 1) return 0; if (p == 0) return 1; LL ans = pow_mod(a, p / 2, n); ans = ans * ans % n; if (p % 2 == 1) ans = ans * a % n; return ans; } int main() { scanf("%lld %lld %lld", &b, &p, &k); printf("%lld^%lld mod %lld=%lld", b, p, k, pow_mod(b, p, k)); return 0; }
26.48
65
0.39426
Tony031218
c63a3fcc62e822c9df1a52f796b4cdf04490ed5b
289
cpp
C++
Backup/testappBackup.cpp
erzu12/Minerva-Engine
8e280946d561d31a0e09fe9d576dfca1412cd9e3
[ "Apache-2.0" ]
null
null
null
Backup/testappBackup.cpp
erzu12/Minerva-Engine
8e280946d561d31a0e09fe9d576dfca1412cd9e3
[ "Apache-2.0" ]
null
null
null
Backup/testappBackup.cpp
erzu12/Minerva-Engine
8e280946d561d31a0e09fe9d576dfca1412cd9e3
[ "Apache-2.0" ]
null
null
null
#include "minerva.h" #include <iostream> class Testapp : public Core { public: Testapp() { } ~Testapp() { } Log log; void Update(UpdateEvent* updateEvent) override { } // void Start(StartEvent* startEvent) override // { // } }; Core* GameInit(){ return new Testapp(); }
10.321429
47
0.633218
erzu12
c63b2e19b704532e353fd351a3ea4ee464e5c16d
14,753
hpp
C++
src/game.hpp
assasinwar9/Barony
c67c01de1168db1c5a2edad98b23cfff9f999187
[ "FTL", "Zlib", "MIT" ]
373
2016-06-28T06:56:46.000Z
2022-03-23T02:32:54.000Z
src/game.hpp
assasinwar9/Barony
c67c01de1168db1c5a2edad98b23cfff9f999187
[ "FTL", "Zlib", "MIT" ]
361
2016-07-06T19:09:25.000Z
2022-03-26T14:14:19.000Z
src/game.hpp
addictgamer/Barony
c67c01de1168db1c5a2edad98b23cfff9f999187
[ "FTL", "Zlib", "MIT" ]
129
2016-06-29T09:02:49.000Z
2022-01-23T09:56:06.000Z
/*------------------------------------------------------------------------------- BARONY File: game.hpp Desc: header file for the game Copyright 2013-2016 (c) Turning Wheel LLC, all rights reserved. See LICENSE for details. -------------------------------------------------------------------------------*/ #pragma once #include <vector> #include <random> #include <chrono> #ifdef STEAMWORKS #include <steam/steam_api.h> #include "steam.hpp" #endif // REMEMBER TO CHANGE THIS WITH EVERY NEW OFFICIAL VERSION!!! #define VERSION "v3.3.7" #define GAME_CODE //#define MAX_FPS_LIMIT 60 //TODO: Make this configurable. class Entity; #define DEBUG 1 #define ENTITY_PACKET_LENGTH 46 #define NET_PACKET_SIZE 512 // impulses (bound keystrokes, mousestrokes, and joystick/game controller strokes) //TODO: Player-by-player basis. extern Uint32 impulses[NUMIMPULSES]; extern Uint32 joyimpulses[NUM_JOY_IMPULSES]; //Joystick/gamepad only impulses. extern int reversemouse; extern real_t mousespeed; void handleEvents(void); void startMessages(); // net packet send typedef struct packetsend_t { UDPsocket sock; int channel; UDPpacket* packet; int num; int tries; int hostnum; } packetsend_t; extern list_t safePacketsSent; extern std::unordered_map<int, Uint32> safePacketsReceivedMap[MAXPLAYERS]; extern bool receivedclientnum; extern Uint32 clientplayer; extern Sint32 numplayers; extern Sint32 clientnum; extern bool intro; extern int introstage; extern bool gamePaused; extern bool fadeout, fadefinished; extern int fadealpha; extern Entity* client_selected[MAXPLAYERS]; extern bool inrange[MAXPLAYERS]; extern bool deleteallbuttons; extern Sint32 client_classes[MAXPLAYERS]; extern Uint32 client_keepalive[MAXPLAYERS]; extern Uint16 portnumber; extern list_t messages; extern list_t command_history; extern node_t* chosen_command; extern bool command; extern bool noclip, godmode, buddhamode; extern bool everybodyfriendly; extern bool combat, combattoggle; extern bool assailant[MAXPLAYERS]; extern bool oassailant[MAXPLAYERS]; extern int assailantTimer[MAXPLAYERS]; static const int COMBAT_MUSIC_COOLDOWN = 200; // 200 ticks of combat music before it fades away. extern list_t removedEntities; extern list_t entitiesToDelete[MAXPLAYERS]; extern char maptoload[256], configtoload[256]; extern bool loadingmap, loadingconfig; extern int startfloor; extern bool skipintro; extern Uint32 uniqueGameKey; // definitions extern bool showfps; extern real_t t, ot, frameval[AVERAGEFRAMES]; extern Uint32 cycles, pingtime; extern Uint32 timesync; extern real_t fps; static const int NUMCLASSES = 21; #define NUMRACES 13 #define NUMPLAYABLERACES 9 extern char address[64]; extern bool loadnextlevel; extern int skipLevelsOnLoad; extern bool loadingSameLevelAsCurrent; extern std::string loadCustomNextMap; extern Uint32 forceMapSeed; extern int currentlevel; extern bool secretlevel; extern bool darkmap; extern int shaking, bobbing; extern int musvolume; extern SDL_Surface* title_bmp; extern SDL_Surface* titleDefault_bmp; extern SDL_Surface* logo_bmp; extern SDL_Surface* cursor_bmp; extern SDL_Surface* cross_bmp; extern SDL_Surface* selected_cursor_bmp; extern SDL_Surface* controllerglyphs1_bmp; extern SDL_Surface* skillIcons_bmp; enum PlayerClasses : int { CLASS_BARBARIAN, CLASS_WARRIOR, CLASS_HEALER, CLASS_ROGUE, CLASS_WANDERER, CLASS_CLERIC, CLASS_MERCHANT, CLASS_WIZARD, CLASS_ARCANIST, CLASS_JOKER, CLASS_SEXTON, CLASS_NINJA, CLASS_MONK, CLASS_CONJURER, CLASS_ACCURSED, CLASS_MESMER, CLASS_BREWER, CLASS_MACHINIST, CLASS_PUNISHER, CLASS_SHAMAN, CLASS_HUNTER }; static const int CLASS_SHAMAN_NUM_STARTING_SPELLS = 15; enum PlayerRaces : int { RACE_HUMAN, RACE_SKELETON, RACE_VAMPIRE, RACE_SUCCUBUS, RACE_GOATMAN, RACE_AUTOMATON, RACE_INCUBUS, RACE_GOBLIN, RACE_INSECTOID, RACE_RAT, RACE_TROLL, RACE_SPIDER, RACE_IMP }; enum ESteamLeaderboardTitles : int { LEADERBOARD_NONE, LEADERBOARD_NORMAL_TIME, LEADERBOARD_NORMAL_SCORE, LEADERBOARD_MULTIPLAYER_TIME, LEADERBOARD_MULTIPLAYER_SCORE, LEADERBOARD_HELL_TIME, LEADERBOARD_HELL_SCORE, LEADERBOARD_HARDCORE_TIME, LEADERBOARD_HARDCORE_SCORE, LEADERBOARD_CLASSIC_TIME, LEADERBOARD_CLASSIC_SCORE, LEADERBOARD_CLASSIC_HARDCORE_TIME, LEADERBOARD_CLASSIC_HARDCORE_SCORE, LEADERBOARD_MULTIPLAYER_CLASSIC_TIME, LEADERBOARD_MULTIPLAYER_CLASSIC_SCORE, LEADERBOARD_MULTIPLAYER_HELL_TIME, LEADERBOARD_MULTIPLAYER_HELL_SCORE, LEADERBOARD_DLC_NORMAL_TIME, LEADERBOARD_DLC_NORMAL_SCORE, LEADERBOARD_DLC_MULTIPLAYER_TIME, LEADERBOARD_DLC_MULTIPLAYER_SCORE, LEADERBOARD_DLC_HELL_TIME, LEADERBOARD_DLC_HELL_SCORE, LEADERBOARD_DLC_HARDCORE_TIME, LEADERBOARD_DLC_HARDCORE_SCORE, LEADERBOARD_DLC_CLASSIC_TIME, LEADERBOARD_DLC_CLASSIC_SCORE, LEADERBOARD_DLC_CLASSIC_HARDCORE_TIME, LEADERBOARD_DLC_CLASSIC_HARDCORE_SCORE, LEADERBOARD_DLC_MULTIPLAYER_CLASSIC_TIME, LEADERBOARD_DLC_MULTIPLAYER_CLASSIC_SCORE, LEADERBOARD_DLC_MULTIPLAYER_HELL_TIME, LEADERBOARD_DLC_MULTIPLAYER_HELL_SCORE }; bool achievementUnlocked(const char* achName); void steamAchievement(const char* achName); void steamUnsetAchievement(const char* achName); void steamAchievementClient(int player, const char* achName); void steamAchievementEntity(Entity* my, const char* achName); // give steam achievement to an entity, and check for valid player info. void steamStatisticUpdate(int statisticNum, ESteamStatTypes type, int value); void steamStatisticUpdateClient(int player, int statisticNum, ESteamStatTypes type, int value); void steamIndicateStatisticProgress(int statisticNum, ESteamStatTypes type); void freePlayerEquipment(int x); void pauseGame(int mode, int ignoreplayer); int initGame(); void deinitGame(); Uint32 timerCallback(Uint32 interval, void* param); void handleButtons(void); void gameLogic(void); // behavior function prototypes: void actAnimator(Entity* my); void actRotate(Entity* my); void actLiquid(Entity* my); void actEmpty(Entity* my); void actFurniture(Entity* my); void actMCaxe(Entity* my); void actDoorFrame(Entity* my); void actDeathCam(Entity* my); void actPlayerLimb(Entity* my); void actTorch(Entity* my); void actCrystalShard(Entity* my); void actDoor(Entity* my); void actHudWeapon(Entity* my); void actHudArm(Entity* my); void actHudShield(Entity* my); void actHudAdditional(Entity* my); void actHudArrowModel(Entity* my); void actItem(Entity* my); void actGoldBag(Entity* my); void actGib(Entity* my); Entity* spawnGib(Entity* parentent, int customGibSprite = -1); Entity* spawnGibClient(Sint16 x, Sint16 y, Sint16 z, Sint16 sprite); void serverSpawnGibForClient(Entity* gib); void actLadder(Entity* my); void actLadderUp(Entity* my); void actPortal(Entity* my); void actWinningPortal(Entity* my); void actFlame(Entity* my); void actCampfire(Entity* my); Entity* spawnFlame(Entity* parentent, Sint32 sprite); void actMagic(Entity* my); Entity* castMagic(Entity* parentent); void actSprite(Entity* my); void actSpriteNametag(Entity* my); void actSpriteWorldTooltip(Entity* my); void actSleepZ(Entity* my); Entity* spawnBang(Sint16 x, Sint16 y, Sint16 z); Entity* spawnExplosion(Sint16 x, Sint16 y, Sint16 z); Entity* spawnExplosionFromSprite(Uint16 sprite, Sint16 x, Sint16 y, Sint16 z); Entity* spawnSleepZ(Sint16 x, Sint16 y, Sint16 z); Entity* spawnFloatingSpriteMisc(int sprite, Sint16 x, Sint16 y, Sint16 z); void actArrow(Entity* my); void actBoulder(Entity* my); void actBoulderTrap(Entity* my); void actBoulderTrapEast(Entity* my); void actBoulderTrapWest(Entity* my); void actBoulderTrapSouth(Entity* my); void actBoulderTrapNorth(Entity* my); void actHeadstone(Entity* my); void actThrown(Entity* my); void actBeartrap(Entity* my); void actBeartrapLaunched(Entity* my); void actBomb(Entity* my); void actDecoyBox(Entity* my); void actDecoyBoxCrank(Entity* my); void actSpearTrap(Entity* my); void actWallBuster(Entity* my); void actWallBuilder(Entity* my); void actPowerCrystalBase(Entity* my); void actPowerCrystal(Entity* my); void actPowerCrystalParticleIdle(Entity* my); void actPedestalBase(Entity* my); void actPedestalOrb(Entity* my); void actMidGamePortal(Entity* my); void actCustomPortal(Entity* my); void actTeleporter(Entity* my); void actMagicTrapCeiling(Entity* my); void actExpansionEndGamePortal(Entity* my); void actSoundSource(Entity* my); void actLightSource(Entity* my); void actSignalTimer(Entity* my); void startMessages(); bool frameRateLimit(Uint32 maxFrameRate, bool resetAccumulator = true); extern Uint32 networkTickrate; extern bool gameloopFreezeEntities; extern Uint32 serverSchedulePlayerHealthUpdate; #define TOUCHRANGE 32 #define STRIKERANGE 24 #define XPSHARERANGE 256 // function prototypes for charclass.c: void initClass(int player); void initShapeshiftHotbar(int player); void deinitShapeshiftHotbar(int player); bool playerUnlockedShamanSpell(int player, Item* item); extern char last_ip[64]; extern char last_port[64]; //TODO: Maybe increase with level or something? //TODO: Pause health regen during combat? #define HEAL_TIME 600 //10 seconds. //Original time: 3600 (1 minute) #define MAGIC_REGEN_TIME 300 // 5 seconds #define DEFAULT_HP 30 #define DEFAULT_MP 30 #define HP_MOD 5 #define MP_MOD 5 #define SPRITE_FLAME 13 #define SPRITE_CRYSTALFLAME 96 #define MAXCHARGE 30 // charging up weapons static const int BASE_MELEE_DAMAGE = 8; static const int BASE_RANGED_DAMAGE = 7; static const int BASE_THROWN_DAMAGE = 6; static const int BASE_PLAYER_UNARMED_DAMAGE = 8; extern bool spawn_blood; extern bool capture_mouse; //Useful for debugging when the game refuses to release the mouse when it's crashed. #define LEVELSFILE "maps/levels.txt" #define SECRETLEVELSFILE "maps/secretlevels.txt" #define LENGTH_OF_LEVEL_REGION 5 #define TICKS_PER_SECOND 50 static const Uint8 TICKS_TO_PROCESS_FIRE = 30; // The amount of ticks needed until the 'BURNING' Status Effect is processed (char_fire % TICKS_TO_PROCESS_FIRE == 0) static const int EFFECT_WITHDRAWAL_BASE_TIME = TICKS_PER_SECOND * 60 * 8; // 8 minutes base withdrawal time. static const std::string PLAYERNAMES_MALE_FILE = "playernames-male.txt"; static const std::string PLAYERNAMES_FEMALE_FILE = "playernames-female.txt"; extern std::vector<std::string> randomPlayerNamesMale; extern std::vector<std::string> randomPlayerNamesFemale; extern bool enabledDLCPack1; extern bool enabledDLCPack2; extern std::vector<std::string> physFSFilesInDirectory; void loadRandomNames(); void mapLevel(int player); void mapFoodOnLevel(int player); class TileEntityListHandler { private: static const int kMaxMapDimension = 256; public: list_t gridEntities[kMaxMapDimension][kMaxMapDimension]; void clearTile(int x, int y); void emptyGridEntities(); list_t* getTileList(int x, int y); node_t* addEntity(Entity& entity); node_t* updateEntity(Entity& entity); std::vector<list_t*> getEntitiesWithinRadius(int u, int v, int radius); std::vector<list_t*> getEntitiesWithinRadiusAroundEntity(Entity* entity, int radius); TileEntityListHandler() { for ( int i = 0; i < kMaxMapDimension; ++i ) { for ( int j = 0; j < kMaxMapDimension; ++j ) { gridEntities[i][j].first = nullptr; gridEntities[i][j].last = nullptr; } } }; ~TileEntityListHandler() { for ( int i = 0; i < kMaxMapDimension; ++i ) { for ( int j = 0; j < kMaxMapDimension; ++j ) { clearTile(i, j); } } }; }; extern TileEntityListHandler TileEntityList; extern float framerateAccumulatedTime; class DebugStatsClass { public: std::chrono::high_resolution_clock::time_point t1StartLoop; std::chrono::high_resolution_clock::time_point t2PostEvents; std::chrono::high_resolution_clock::time_point t21PostHandleMessages; std::chrono::high_resolution_clock::time_point t3SteamCallbacks; std::chrono::high_resolution_clock::time_point t4Music; std::chrono::high_resolution_clock::time_point t5MainDraw; std::chrono::high_resolution_clock::time_point t6Messages; std::chrono::high_resolution_clock::time_point t7Inputs; std::chrono::high_resolution_clock::time_point t8Status; std::chrono::high_resolution_clock::time_point t9GUI; std::chrono::high_resolution_clock::time_point t10FrameLimiter; std::chrono::high_resolution_clock::time_point t11End; std::chrono::high_resolution_clock::time_point eventsT1; std::chrono::high_resolution_clock::time_point eventsT2; std::chrono::high_resolution_clock::time_point eventsT3; std::chrono::high_resolution_clock::time_point eventsT4; std::chrono::high_resolution_clock::time_point eventsT5; std::chrono::high_resolution_clock::time_point eventsT6; std::chrono::high_resolution_clock::time_point messagesT1; std::chrono::high_resolution_clock::time_point t1Stored; std::chrono::high_resolution_clock::time_point t2Stored; std::chrono::high_resolution_clock::time_point t21Stored; std::chrono::high_resolution_clock::time_point t3Stored; std::chrono::high_resolution_clock::time_point t4Stored; std::chrono::high_resolution_clock::time_point t5Stored; std::chrono::high_resolution_clock::time_point t6Stored; std::chrono::high_resolution_clock::time_point t7Stored; std::chrono::high_resolution_clock::time_point t8Stored; std::chrono::high_resolution_clock::time_point t9Stored; std::chrono::high_resolution_clock::time_point t10Stored; std::chrono::high_resolution_clock::time_point t11Stored; std::chrono::high_resolution_clock::time_point eventsT1stored; std::chrono::high_resolution_clock::time_point eventsT2stored; std::chrono::high_resolution_clock::time_point eventsT3stored; std::chrono::high_resolution_clock::time_point eventsT4stored; std::chrono::high_resolution_clock::time_point eventsT5stored; std::chrono::high_resolution_clock::time_point eventsT6stored; std::chrono::high_resolution_clock::time_point messagesT1stored; std::chrono::high_resolution_clock::time_point messagesT2WhileLoop; bool handlePacketStartLoop = false; std::unordered_map<unsigned long, std::pair<std::string, int>> networkPackets; std::unordered_map<int, int> entityUpdatePackets; bool displayStats = false; char debugOutput[1024]; char debugEventOutput[1024]; DebugStatsClass() {}; void inline storeOldTimePoints() { t1Stored = t1StartLoop; t2Stored = t2PostEvents; t21Stored = t21PostHandleMessages; t3Stored = t3SteamCallbacks; t4Stored = t4Music; t5Stored = t5MainDraw; t6Stored = t6Messages; t7Stored = t7Inputs; t8Stored = t8Status; t9Stored = t9GUI; t10Stored = t10FrameLimiter; t11Stored = t11End; eventsT1stored = eventsT1; eventsT2stored = eventsT2; eventsT3stored = eventsT3; eventsT4stored = eventsT4; eventsT5stored = eventsT5; eventsT6stored = eventsT6; messagesT1stored = messagesT1; }; void storeStats(); void storeEventStats(); }; extern DebugStatsClass DebugStats;
30.607884
164
0.793601
assasinwar9
c63b3390ffb324c52fedcfe538c9dc06eceb630b
21,772
cpp
C++
src/evolve_eas_multi_objective.cpp
mihaioltean/evolve-algorithms
16c86b21effc137483040838162a18579bf76fc2
[ "MIT" ]
1
2021-09-29T13:07:47.000Z
2021-09-29T13:07:47.000Z
src/evolve_eas_multi_objective.cpp
mihaioltean/evolve-algorithms
16c86b21effc137483040838162a18579bf76fc2
[ "MIT" ]
null
null
null
src/evolve_eas_multi_objective.cpp
mihaioltean/evolve-algorithms
16c86b21effc137483040838162a18579bf76fc2
[ "MIT" ]
null
null
null
//--------------------------------------------------------------------------- // Evolving Evolutionary Algorithms for MultiObjective problems // Copyright (C) 2016, Mihai Oltean (mihai.oltean@gmail.com) // Version 2016.12.26.1 // Compiled with Microsoft Visual C++ 2013 // Just create a console application and set this file as the main file of the project // MIT License // New versions of this program will be available at: https://github.com/mihaioltean/evolve-algorithms // Please reports any sugestions and/or bugs to mihai.oltean@gmail.com #include <stdio.h> #include <stdlib.h> #include <math.h> #include <string.h> #include <float.h> #include "lista_voidp.h" #define NUM_MICRO_EA_OPERATORS 4 #define MICRO_EA_RANDOM_INIT 0 #define MICRO_EA_DOMINATOR_SELECTION 1 #define MICRO_EA_CROSSOVER 2 #define MICRO_EA_MUTATION 3 //--------------------------------------------------------------------------- struct t_code3{// three address code int op; // operators are the MICRO EA OPERATORS int adr1, adr2; // pointers to arguments }; //--------------------------------------------------------------------------- struct t_meta_gp_chromosome{ t_code3 *prg; // the program - a string of genes double fitness; // the fitness (or the error) }; //--------------------------------------------------------------------------- struct t_meta_gp_parameters{ int code_length; // number of instructions in a chromosome int num_generations; int pop_size; // population size double mutation_probability, crossover_probability; }; //--------------------------------------------------------------------------- struct t_micro_ea_parameters{ double mutation_probability; int num_runs; int num_bits_per_dimension; int initial_pop_size; }; //--------------------------------------------------------------------------- void allocate_meta_chromosome(t_meta_gp_chromosome &c, t_meta_gp_parameters &params) { c.prg = new t_code3[params.code_length]; } //--------------------------------------------------------------------------- void delete_meta_chromosome(t_meta_gp_chromosome &c) { if (c.prg) { delete[] c.prg; c.prg = NULL; } } //--------------------------------------------------------------------------- void copy_individual(t_meta_gp_chromosome& dest, const t_meta_gp_chromosome& source, t_meta_gp_parameters &params) { for (int i = 0; i < params.code_length; i++) dest.prg[i] = source.prg[i]; dest.fitness = source.fitness; } //--------------------------------------------------------------------------- void generate_random_meta_chromosome(t_meta_gp_chromosome &a, t_meta_gp_parameters &meta_gp_params, int micro_ea_pop_size) // randomly initializes the individuals { for (int i = 0; i < micro_ea_pop_size; i++) { a.prg[i].op = MICRO_EA_RANDOM_INIT; // generate a random solution a.prg[i].adr1 = -1; a.prg[i].adr2 = -1; } // for all other genes we put either an operator, variable or constant for (int i = micro_ea_pop_size; i < meta_gp_params.code_length; i++) { a.prg[i].op = 1 + rand() % (NUM_MICRO_EA_OPERATORS - 1); a.prg[i].adr1 = rand() % i; a.prg[i].adr2 = rand() % i; } } //--------------------------------------------------------------------------- void mutate_meta_chromosome(t_meta_gp_chromosome &a_chromosome, t_meta_gp_parameters& params, int micro_ea_pop_size) // mutate the individual { // mutate each symbol with the given probability // no mutation for the first micro_ea_pop_size genes because they are only used for initialization of the micro ea population // other genes for (int i = micro_ea_pop_size; i < params.code_length; i++) { double p = rand() / (double)RAND_MAX; // mutate the operator if (p < params.mutation_probability) { // we mutate it, but we have to decide what we put here p = rand() / (double)RAND_MAX; a_chromosome.prg[i].op = 1 + rand() % (NUM_MICRO_EA_OPERATORS - 1); } p = rand() / (double)RAND_MAX; // mutate the first address (adr1) if (p < params.mutation_probability) a_chromosome.prg[i].adr1 = rand() % i; p = rand() / (double)RAND_MAX; // mutate the second address (adr2) if (p < params.mutation_probability) a_chromosome.prg[i].adr2 = rand() % i; } } //--------------------------------------------------------------------------- void one_cut_point_crossover(const t_meta_gp_chromosome &parent1, const t_meta_gp_chromosome &parent2, t_meta_gp_parameters &params, t_meta_gp_chromosome &offspring1, t_meta_gp_chromosome &offspring2) { int cutting_pct = rand() % params.code_length; for (int i = 0; i < cutting_pct; i++) { offspring1.prg[i] = parent1.prg[i]; offspring2.prg[i] = parent2.prg[i]; } for (int i = cutting_pct; i < params.code_length; i++) { offspring1.prg[i] = parent2.prg[i]; offspring2.prg[i] = parent1.prg[i]; } } //--------------------------------------------------------------------------- void uniform_crossover(const t_meta_gp_chromosome &parent1, const t_meta_gp_chromosome &parent2, t_meta_gp_parameters &params, t_meta_gp_chromosome &offspring1, t_meta_gp_chromosome &offspring2) { for (int i = 0; i < params.code_length; i++) if (rand() % 2) { offspring1.prg[i] = parent1.prg[i]; offspring2.prg[i] = parent2.prg[i]; } else { offspring1.prg[i] = parent2.prg[i]; offspring2.prg[i] = parent1.prg[i]; } } //--------------------------------------------------------------------------- int sort_function(const void *a, const void *b) {// comparator for quick sort if (((t_meta_gp_chromosome *)a)->fitness < ((t_meta_gp_chromosome *)b)->fitness) return 1; else if (((t_meta_gp_chromosome *)a)->fitness > ((t_meta_gp_chromosome *)b)->fitness) return -1; else return 0; } //--------------------------------------------------------------------------- void print_meta_chromosome(t_meta_gp_chromosome& an_individual, int code_length) { printf("The chromosome is:\n"); for (int i = 0; i < code_length; i++) switch (an_individual.prg[i].op) { case MICRO_EA_RANDOM_INIT: printf("%d: MICRO_EA_RANDOM_INIT\n", i); break; case MICRO_EA_DOMINATOR_SELECTION: printf("%d: MICRO_EA_DOMINATOR_SELECTION(%d, %d)\n", i, an_individual.prg[i].adr1, an_individual.prg[i].adr2); break; case MICRO_EA_CROSSOVER: printf("%d: MICRO_EA_CROSSOVER(%d, %d)\n", i, an_individual.prg[i].adr1, an_individual.prg[i].adr2); break; case MICRO_EA_MUTATION: printf("%d: MICRO_EA_MUTATION(%d)\n", i, an_individual.prg[i].adr1); break; } printf("Fitness = %lf\n", an_individual.fitness); } //--------------------------------------------------------------------------- int tournament_selection(t_meta_gp_chromosome *pop, int pop_size, int tournament_size) // Size is the size of the tournament { int r, p; p = rand() % pop_size; for (int i = 1; i < tournament_size; i++) { r = rand() % pop_size; p = pop[r].fitness < pop[p].fitness ? r : p; } return p; } //--------------------------------------------------------------------------- // function to be optimized //--------------------------------------------------------------------------- //ZDT1 //--------------------------------------------------------------------------- double f1(double *p, int num_dimensions) { return p[0]; } //--------------------------------------------------------------------------- double f2(double* p, int num_dimensions) { // test function T1 double sum = 0; for (int i = 1; i < num_dimensions; i++) sum += p[i]; double g = 1 + (9 * sum) / (double)(num_dimensions - 1); double h = 1 - sqrt(f1(p, num_dimensions) / g); return g * h; } //--------------------------------------------------------------------------- double binary_to_real(char* b_string, int num_bits_per_dimension, double min_x, double max_x) { // transform a binary string of num_bits_per_dimension size into a real number in [min_x ... max_x] interval double x_real = 0; for (int j = 0; j < num_bits_per_dimension; j++) x_real = x_real * 2 + (int)b_string[j]; // now I have them in interval [0 ... 2 ^ num_bits_per_dimension - 1] x_real /= ((1 << num_bits_per_dimension) - 1); // now I have them in [0 ... 1] interval x_real *= (max_x - min_x); // now I have them in [0 ... max_x - min_x] interval x_real += min_x; // now I have them in [min_x ... max_x] interval return x_real; } //-------------------------------------------------------------------- bool dominates(double* p1, double* p2) // returns true if p1 dominates p2 { for (int i = 0; i < 2; i++) if (p2[i] < p1[i]) return false; for (int i = 0; i < 2; i++) if (p1[i] < p2[i]) return true; return false; } //--------------------------------------------------------------------------- void sort_list(TLista &nondominated) { bool sorted = false; while (!sorted) { sorted = true; for (node_double_linked * node_p = nondominated.head; node_p->next; node_p = node_p->next) { double *p = (double*)nondominated.GetCurrentInfo(node_p); double *p_next = (double*)nondominated.GetCurrentInfo(node_p->next); if (p[0] > p_next[0]) { void *tmp_inf = node_p->inf; node_p->inf = node_p->next->inf; node_p->next->inf = tmp_inf; sorted = false; } } } } //--------------------------------------------------------------------------- double compute_hypervolume(TLista &nondominated, double *reference) { sort_list(nondominated); double hyper_volume = 0; for (node_double_linked * node_p = nondominated.head; node_p->next; node_p = node_p->next) { double *p = (double*)nondominated.GetCurrentInfo(node_p); double *p_next = (double*)nondominated.GetCurrentInfo(node_p->next); hyper_volume += (p_next[0] - p[0]) * (reference[1] - p[1]); } double *p = (double*)nondominated.GetTailInfo(); hyper_volume += (reference[0] - p[0]) * (reference[1] - p[1]); return hyper_volume; } //--------------------------------------------------------------------------- double make_one_run(t_meta_gp_chromosome &an_individual, int code_length, t_micro_ea_parameters &micro_params, int num_dimensions, double min_x, double max_x, double **micro_fitness, char **micro_values, double *x, FILE *f) { for (int i = 0; i < code_length; i++) { switch (an_individual.prg[i].op) { case MICRO_EA_RANDOM_INIT: // Initialization for (int j = 0; j < num_dimensions; j++) for (int k = 0; k < micro_params.num_bits_per_dimension; k++) micro_values[i][j * micro_params.num_bits_per_dimension + k] = rand() % 2; // random values // compute fitness of that micro chromosome // transform to base 10 for (int j = 0; j < num_dimensions; j++) x[j] = binary_to_real(micro_values[i] + j * micro_params.num_bits_per_dimension, micro_params.num_bits_per_dimension, min_x, max_x); micro_fitness[i][0] = f1(x, num_dimensions);// apply f - compute fitness of micro micro_fitness[i][1] = f2(x, num_dimensions);// apply f - compute fitness of micro break; case MICRO_EA_DOMINATOR_SELECTION: // Selection (binary tournament) if (dominates(micro_fitness[an_individual.prg[i].adr1], micro_fitness[an_individual.prg[i].adr2])) { memcpy(micro_values[i], micro_values[an_individual.prg[i].adr1], micro_params.num_bits_per_dimension * num_dimensions); micro_fitness[i][0] = micro_fitness[an_individual.prg[i].adr1][0]; micro_fitness[i][1] = micro_fitness[an_individual.prg[i].adr1][1]; } else { // p2 dominates or are nondominated memcpy(micro_values[i], micro_values[an_individual.prg[i].adr2], micro_params.num_bits_per_dimension * num_dimensions); micro_fitness[i][0] = micro_fitness[an_individual.prg[i].adr2][0]; micro_fitness[i][1] = micro_fitness[an_individual.prg[i].adr2][1]; } break; case MICRO_EA_CROSSOVER: // Mutation with a fixed mutation probability for (int j = 0; j < num_dimensions; j++) for (int k = 0; k < micro_params.num_bits_per_dimension; k++) { int p = rand() % 2; if (p) micro_values[i][j * micro_params.num_bits_per_dimension + k] = micro_values[an_individual.prg[i].adr1][j * micro_params.num_bits_per_dimension + k]; else micro_values[i][j * micro_params.num_bits_per_dimension + k] = micro_values[an_individual.prg[i].adr2][j * micro_params.num_bits_per_dimension + k]; } // compute fitness of that micro chromosome // transform to base 10 for (int j = 0; j < num_dimensions; j++) x[j] = binary_to_real(micro_values[i] + j * micro_params.num_bits_per_dimension, micro_params.num_bits_per_dimension, min_x, max_x); micro_fitness[i][0] = f1(x, num_dimensions);// apply f - compute fitness of micro micro_fitness[i][1] = f2(x, num_dimensions);// apply f - compute fitness of micro break; case MICRO_EA_MUTATION: // Mutation with a fixed mutation probability for (int j = 0; j < num_dimensions; j++) for (int k = 0; k < micro_params.num_bits_per_dimension; k++) { double p = rand() / (double)RAND_MAX; if (p < micro_params.mutation_probability) micro_values[i][j * micro_params.num_bits_per_dimension + k] = 1 - micro_values[an_individual.prg[i].adr1][j * micro_params.num_bits_per_dimension + k]; else micro_values[i][j * micro_params.num_bits_per_dimension + k] = micro_values[an_individual.prg[i].adr1][j * micro_params.num_bits_per_dimension + k]; } // compute fitness of that micro chromosome // transform to base 10 for (int j = 0; j < num_dimensions; j++) x[j] = binary_to_real(micro_values[i] + j * micro_params.num_bits_per_dimension, micro_params.num_bits_per_dimension, min_x, max_x); micro_fitness[i][0] = f1(x, num_dimensions);// apply f - compute fitness of micro micro_fitness[i][1] = f2(x, num_dimensions);// apply f - compute fitness of micro break; } } // create a list with nondominated TLista nondominated; nondominated.Add(micro_fitness[0]); for (int i = 1; i < code_length; i++) { node_double_linked * node_p = nondominated.head; bool dominated = false; while (node_p) { double *p = (double*)nondominated.GetCurrentInfo(node_p); if (dominates(p, micro_fitness[i])) { dominated = true; break; } else if (dominates(micro_fitness[i], p)) node_p = nondominated.DeleteCurrent(node_p); else// move to the next one node_p = node_p->next; } if (!dominated) nondominated.Add(micro_fitness[i]); } // compute the distance to front double reference[2] = { 11, 11 }; double hyper_volume = compute_hypervolume(nondominated, reference); if (f) { fprintf(f, "%lf\n", hyper_volume); fprintf(f, "%d\n", nondominated.count); for (node_double_linked* node_p = nondominated.head; node_p; node_p = node_p->next) { double *p = (double*)nondominated.GetCurrentInfo(node_p); fprintf(f, "%lf %lf ", p[0], p[1]); } fprintf(f, "\n"); } return hyper_volume; } //--------------------------------------------------------------------------- void compute_fitness(t_meta_gp_chromosome &an_individual, int code_length, t_micro_ea_parameters &micro_params, int num_dimensions, double min_x, double max_x, double **micro_fitness, char **micro_values, double *x, FILE *f) { double average_hypervolume = 0; // average fitness over all runs // evaluate code for (int r = 0; r < micro_params.num_runs; r++) {// micro ea is run on multi runs srand(r); double hyper_volume = make_one_run(an_individual, code_length, micro_params, num_dimensions, min_x, max_x, micro_fitness, micro_values, x, f); // add to average average_hypervolume += hyper_volume; } average_hypervolume /= (double)micro_params.num_runs; an_individual.fitness = average_hypervolume; } //--------------------------------------------------------------------------- void start_steady_state_mep(t_meta_gp_parameters &meta_gp_params, t_micro_ea_parameters &micro_params, int num_dimensions, double min_x, double max_x, FILE *f_out) // Steady-State { // a steady state approach: // we work with 1 population // newly created individuals will replace the worst existing ones (only if they are better). // allocate memory t_meta_gp_chromosome *population; population = new t_meta_gp_chromosome[meta_gp_params.pop_size]; for (int i = 0; i < meta_gp_params.pop_size; i++) allocate_meta_chromosome(population[i], meta_gp_params); t_meta_gp_chromosome offspring1, offspring2; allocate_meta_chromosome(offspring1, meta_gp_params); allocate_meta_chromosome(offspring2, meta_gp_params); double *x = new double[num_dimensions]; // buffer for storing real values double **micro_fitness = new double*[meta_gp_params.code_length]; // fitness for each micro EA chromosome for (int i = 0; i < meta_gp_params.code_length; i++) micro_fitness[i] = new double[2]; // allocate some memory char **micro_values; micro_values = new char*[meta_gp_params.code_length]; for (int i = 0; i < meta_gp_params.code_length; i++) micro_values[i] = new char[num_dimensions * micro_params.num_bits_per_dimension]; // initialize for (int i = 0; i < meta_gp_params.pop_size; i++) { generate_random_meta_chromosome(population[i], meta_gp_params, micro_params.initial_pop_size); compute_fitness(population[i], meta_gp_params.code_length, micro_params, num_dimensions, min_x, max_x, micro_fitness, micro_values, x, NULL); } // sort ascendingly by fitness qsort((void *)population, meta_gp_params.pop_size, sizeof(population[0]), sort_function); printf("generation %d, best fitness = %lf\n", 0, population[0].fitness); // print the front of the best fprintf(f_out, "%d\n", 0); srand(0); make_one_run(population[0], meta_gp_params.code_length, micro_params, num_dimensions, min_x, max_x, micro_fitness, micro_values, x, f_out); for (int g = 1; g < meta_gp_params.num_generations; g++) {// for each generation for (int k = 0; k < meta_gp_params.pop_size; k += 2) { // choose the parents using binary tournament int r1 = tournament_selection(population, meta_gp_params.pop_size, 2); int r2 = tournament_selection(population, meta_gp_params.pop_size, 2); // crossover double p = rand() / double(RAND_MAX); if (p < meta_gp_params.crossover_probability) one_cut_point_crossover(population[r1], population[r2], meta_gp_params, offspring1, offspring2); else {// no crossover so the offspring are a copy of the parents copy_individual(offspring1, population[r1], meta_gp_params); copy_individual(offspring2, population[r2], meta_gp_params); } // mutate the result and compute fitness mutate_meta_chromosome(offspring1, meta_gp_params, micro_params.initial_pop_size); compute_fitness(offspring1, meta_gp_params.code_length, micro_params, num_dimensions, min_x, max_x, micro_fitness, micro_values, x, NULL); // mutate the other offspring and compute fitness mutate_meta_chromosome(offspring2, meta_gp_params, micro_params.initial_pop_size); compute_fitness(offspring2, meta_gp_params.code_length, micro_params, num_dimensions, min_x, max_x, micro_fitness, micro_values, x, NULL); // replace the worst in the population if (offspring1.fitness > population[meta_gp_params.pop_size - 1].fitness) { copy_individual(population[meta_gp_params.pop_size - 1], offspring1, meta_gp_params); qsort((void *)population, meta_gp_params.pop_size, sizeof(population[0]), sort_function); } if (offspring2.fitness > population[meta_gp_params.pop_size - 1].fitness) { copy_individual(population[meta_gp_params.pop_size - 1], offspring2, meta_gp_params); qsort((void *)population, meta_gp_params.pop_size, sizeof(population[0]), sort_function); } } // print the front of the best fprintf(f_out, "%d\n", g); srand(0); make_one_run(population[0], meta_gp_params.code_length, micro_params, num_dimensions, min_x, max_x, micro_fitness, micro_values, x, f_out); printf("generation %d, best fitness = %lf\n", g, population[0].fitness); } // print best chromosome print_meta_chromosome(population[0], meta_gp_params.code_length); // free memory delete_meta_chromosome(offspring1); delete_meta_chromosome(offspring2); for (int i = 0; i < meta_gp_params.pop_size; i++) delete_meta_chromosome(population[i]); delete[] population; for (int i = 0; i < meta_gp_params.code_length; i++) delete[] micro_values[i]; delete[] micro_values; for (int i = 0; i < meta_gp_params.code_length; i++) delete[] micro_fitness[i]; delete[] micro_fitness; delete[] x; } //-------------------------------------------------------------------- bool read_reference_points(char *file_name, TLista &reference_points) { FILE * f = fopen(file_name, "r"); if (!f) return false; char c; for (int i = 0; i < 100; i++) { double *p = new double[2]; fscanf(f, "%lf%c%lf", &p[0], &c, &p[1]); reference_points.Add(p); } fclose(f); return true; } //-------------------------------------------------------------------- int main(void) { t_meta_gp_parameters meta_gp_params; meta_gp_params.pop_size = 10; // the number of individuals in population (must be an even number!) meta_gp_params.code_length = 10000; meta_gp_params.num_generations = 100; // the number of generations meta_gp_params.mutation_probability = 0.01; // mutation probability meta_gp_params.crossover_probability = 0.9; // crossover probability t_micro_ea_parameters micro_ea_params; micro_ea_params.mutation_probability = 0.01; micro_ea_params.num_bits_per_dimension = 30; micro_ea_params.num_runs = 30; micro_ea_params.initial_pop_size = 100; FILE *f_out = fopen("c:\\temp\\zdt1_front.txt", "w"); printf("evolution started...\n"); srand(0); start_steady_state_mep(meta_gp_params, micro_ea_params, 30, 0, 1, f_out); fclose(f_out); printf("Press enter ..."); getchar(); return 0; } //--------------------------------------------------------------------
39.158273
224
0.638894
mihaioltean
c63e90a89646c8cb2b4c62a1d55fee5b927f722d
112
cpp
C++
algorithms/default.cpp
kosmaz/HackerRank
1107804c8213d169070a5529de26b97eb190e06c
[ "MIT" ]
1
2015-03-21T20:08:28.000Z
2015-03-21T20:08:28.000Z
algorithms/default.cpp
kosmaz/HackerRank
1107804c8213d169070a5529de26b97eb190e06c
[ "MIT" ]
null
null
null
algorithms/default.cpp
kosmaz/HackerRank
1107804c8213d169070a5529de26b97eb190e06c
[ "MIT" ]
null
null
null
#include <iostream> using namespace std; void Run() { return; } int main() { Run(); return 0; }
8.615385
21
0.553571
kosmaz
c646a6d6df3c7f49f5cef31870b401f9ef22413c
1,479
cpp
C++
Dynamic Programming/Longest Increasing Subsequence/LargestDivisibleSubset368.cpp
devangi2000/Data-Structures-Algorithms-Handbook
ce0f00de89af5da7f986e65089402dc6908a09b5
[ "MIT" ]
38
2021-10-14T09:36:53.000Z
2022-01-27T02:36:19.000Z
Dynamic Programming/Longest Increasing Subsequence/LargestDivisibleSubset368.cpp
devangi2000/Data-Structures-Algorithms-Handbook
ce0f00de89af5da7f986e65089402dc6908a09b5
[ "MIT" ]
null
null
null
Dynamic Programming/Longest Increasing Subsequence/LargestDivisibleSubset368.cpp
devangi2000/Data-Structures-Algorithms-Handbook
ce0f00de89af5da7f986e65089402dc6908a09b5
[ "MIT" ]
4
2021-12-06T15:47:12.000Z
2022-02-04T04:25:00.000Z
// Given a set of distinct positive integers nums, return the largest subset answer such that every pair // (answer[i], answer[j]) of elements in this subset satisfies: // answer[i] % answer[j] == 0, or // answer[j] % answer[i] == 0 // If there are multiple solutions, return any of them. // Example 1: // Input: nums = [1,2,3] // Output: [1,2] // Explanation: [1,3] is also accepted. // Example 2: // Input: nums = [1,2,4,8] // Output: [1,2,4,8] // Constraints: // 1 <= nums.length <= 1000 // 1 <= nums[i] <= 2 * 109 // All the integers in nums are unique. class Solution { public: vector<int> largestDivisibleSubset(vector<int>& nums) { int n = nums.size(), maxlen = 0, maxind = -1; if(n == 1) return nums; vector<int> dp(n), pre(n); sort(nums.begin(), nums.end()); for(int i = 0; i < n; i++){ dp[i] = 1; pre[i] = -1; for(int j = i-1; j >= 0; j--){ if(nums[i] % nums[j] == 0){ if(dp[i] < 1 + dp[j]){ dp[i] = 1 + dp[j]; pre[i] = j; } } } if(dp[i] > maxlen){ maxlen = dp[i]; maxind = i; } } vector<int> res; while(maxind != -1){ res.push_back(nums[maxind]); maxind = pre[maxind]; } return res; } };
29
106
0.443543
devangi2000
c647e1588ab85979651918406ec9a2d73a6df0ab
225
cpp
C++
coin2xml.cpp
milasudril/coin
3e2d4778560894a36dfec9fc6cc245faae7301ae
[ "BSD-2-Clause-FreeBSD" ]
null
null
null
coin2xml.cpp
milasudril/coin
3e2d4778560894a36dfec9fc6cc245faae7301ae
[ "BSD-2-Clause-FreeBSD" ]
3
2018-01-21T08:39:47.000Z
2018-01-21T08:42:18.000Z
coin2xml.cpp
milasudril/coin
3e2d4778560894a36dfec9fc6cc245faae7301ae
[ "BSD-2-Clause-FreeBSD" ]
null
null
null
//@ {"targets":[{"name":"coin2xml","type":"application"}]} #include "input.hpp" #include "writerxml.hpp" #include "lexercoin.hpp" int main() { read(stdin, CoIN::LexerCoIN{}, CoIN::WriterXML<FILE*>(stdout)); return 0; }
18.75
64
0.648889
milasudril
c6495482a87babd49bb27f4964c179ea7f9aa3b1
1,856
cpp
C++
src/app/app_cmd_parser.cpp
yyh12345685/libnbf
64f6fa1b37b88f673ead8577291b10a30cac4040
[ "Apache-2.0" ]
null
null
null
src/app/app_cmd_parser.cpp
yyh12345685/libnbf
64f6fa1b37b88f673ead8577291b10a30cac4040
[ "Apache-2.0" ]
null
null
null
src/app/app_cmd_parser.cpp
yyh12345685/libnbf
64f6fa1b37b88f673ead8577291b10a30cac4040
[ "Apache-2.0" ]
1
2021-10-13T01:35:07.000Z
2021-10-13T01:35:07.000Z
#include <string.h> #include <iostream> #include "app/app_cmd_parser.h" #ifndef __APP_VERSION__ #define __APP_VERSION__ "(date: 22:25:00 2019/12/15 +0800)" #endif namespace bdf{ static void UsageInner(const char *exe, bool help){ std::cerr << "Copyright 2019 by yyh," << " Basic Net Framework Model" << std::endl; std::cerr << "libbdf: " << __APP_VERSION__ << std::endl; if (help) { std::cerr << "Usage: " << " --c/-c config_file --l/-l log_file [--d/-d:daemon]" << std::endl; } } int AppCmdParser::Usage(int argc, char* argv[]){ if (argc == 2){ if (0 == strcasecmp(argv[1], "-h") || 0 == strcasecmp(argv[1], "--help")){ UsageInner(argv[0], true); help_mode_ = true; return 1; } else if (0 == strcasecmp(argv[1], "-v") || 0 == strcasecmp(argv[1], "--version")){ UsageInner(argv[0], false); return 1; } } if (argc < 3){ UsageInner(argv[0], true); return 2; } return 0; } int AppCmdParser::ParseArgv(int argc, char* argv[]){ for (int i = 1; i < argc; ++i){ if (0 == strcmp(argv[i], "-c")|| 0 == strcmp(argv[i], "--config")){ if (++i < argc) application_config_ = argv[i]; continue; } if (0 == strcmp(argv[i], "-d")|| 0 == strcmp(argv[i], "--daemon")){ daemon_mode_ = true; continue; } if (0 == strcmp(argv[i], "-l") || 0 == strcmp(argv[i], "--log")) { if (++i < argc) logger_config_ = argv[i]; continue; } std::cerr << "unexpected argv: " << argv[i] << std::endl; } if (application_config_.empty()){ std::cerr<<"configure file is not available" << std::endl; return 1; } return 0; } int AppCmdParser::ParseCmd(int argc, char* argv[]) { if ( 0 != Usage(argc,argv)){ return -1; } if (0!= ParseArgv(argc, argv)){ return -2; } return 0; } }
22.91358
76
0.543642
yyh12345685
c64dcbaa41d8d220adf73936fdb62bddb9b6f7e0
1,425
cpp
C++
app/src/SingleRunHandler.cpp
elchtzeasar/balcony-watering-system
2fb20dc8bdf79cff4b7ba93cb362489562b62732
[ "MIT" ]
null
null
null
app/src/SingleRunHandler.cpp
elchtzeasar/balcony-watering-system
2fb20dc8bdf79cff4b7ba93cb362489562b62732
[ "MIT" ]
null
null
null
app/src/SingleRunHandler.cpp
elchtzeasar/balcony-watering-system
2fb20dc8bdf79cff4b7ba93cb362489562b62732
[ "MIT" ]
null
null
null
#include "SingleRunHandler.h" #include "IArduino.h" #include "HWFactory.h" #include "LogicFactory.h" #include "WateringLogic.h" #include <string> #include <iostream> namespace balcony_watering_system { namespace app { using ::balcony_watering_system::hardware::HWFactory; using ::balcony_watering_system::logic::LogicFactory; using ::balcony_watering_system::logic::WateringLogic; SingleRunHandler::SingleRunHandler(const LogicFactory& logicFactory, const HWFactory& hwFactory) : wateringLogic(logicFactory.getWateringLogic()), arduino(hwFactory.getArduino()), logger("app.single-run") { } SingleRunHandler::~SingleRunHandler() { } bool SingleRunHandler::exec() { const auto state = wateringLogic.getState(); bool keepRunning; switch (state) { case WateringLogic::State::NOT_WATERING: keepRunning = false; LOG_INFO(logger, "state=" << state << " => shutting down"); break; case WateringLogic::State::IDLE: case WateringLogic::State::WATERING: keepRunning = true; LOG_INFO(logger, "state=" << state << " => waiting"); break; default: keepRunning = true; LOG_FATAL(logger, "unknown state=" << int(state) << " => shutting down"); break; } if (!keepRunning && arduino.isShutdownEnabled()) { arduino.shutdown(); system("shutdown -h now"); exit(0); } return keepRunning; } } /* namespace app */ } /* namespace balcony_watering_system */
24.152542
98
0.701754
elchtzeasar
c64f8c1cd88021908e2eb9b8bb0695bfe3f5cd3b
2,572
cc
C++
tests/unit/features/StreamingDenseFeatures_unittest.cc
srgnuclear/shogun
33c04f77a642416376521b0cd1eed29b3256ac13
[ "Ruby", "MIT" ]
1
2015-11-05T18:31:14.000Z
2015-11-05T18:31:14.000Z
tests/unit/features/StreamingDenseFeatures_unittest.cc
waderly/shogun
9288b6fa38e001d63c32188f7f847dadea66e2ae
[ "Ruby", "MIT" ]
null
null
null
tests/unit/features/StreamingDenseFeatures_unittest.cc
waderly/shogun
9288b6fa38e001d63c32188f7f847dadea66e2ae
[ "Ruby", "MIT" ]
null
null
null
/* * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * Written (W) 2013 Viktor Gal */ #include <shogun/features/streaming/StreamingDenseFeatures.h> #include <shogun/io/CSVFile.h> #include <shogun/io/streaming/StreamingAsciiFile.h> #include <unistd.h> #include <gtest/gtest.h> using namespace shogun; TEST(StreamingDenseFeaturesTest, example_reading_from_file) { index_t n=20; index_t dim=2; std::string tmp_name = "/tmp/StreamingDenseFeatures_reading.XXXXXX"; char* fname = mktemp(const_cast<char*>(tmp_name.c_str())); SGMatrix<float64_t> data(dim,n); for (index_t i=0; i<dim*n; ++i) data.matrix[i] = sg_rand->std_normal_distrib(); CDenseFeatures<float64_t>* orig_feats=new CDenseFeatures<float64_t>(data); CCSVFile* saved_features = new CCSVFile(fname, 'w'); orig_feats->save(saved_features); saved_features->close(); SG_UNREF(saved_features); CStreamingAsciiFile* input = new CStreamingAsciiFile(fname); input->set_delimiter(','); CStreamingDenseFeatures<float64_t>* feats = new CStreamingDenseFeatures<float64_t>(input, false, 5); index_t i = 0; feats->start_parser(); while (feats->get_next_example()) { SGVector<float64_t> example = feats->get_vector(); SGVector<float64_t> expected = orig_feats->get_feature_vector(i); ASSERT_EQ(dim, example.vlen); for (index_t j = 0; j < dim; j++) EXPECT_NEAR(expected.vector[j], example.vector[j], 1E-5); feats->release_example(); i++; } feats->end_parser(); SG_UNREF(orig_feats); SG_UNREF(feats); int delete_success = unlink(fname); ASSERT_EQ(0, delete_success); } TEST(StreamingDenseFeaturesTest, example_reading_from_features) { index_t n=20; index_t dim=2; SGMatrix<float64_t> data(dim,n); for (index_t i=0; i<dim*n; ++i) data.matrix[i] = sg_rand->std_normal_distrib(); CDenseFeatures<float64_t>* orig_feats=new CDenseFeatures<float64_t>(data); CStreamingDenseFeatures<float64_t>* feats = new CStreamingDenseFeatures<float64_t>(orig_feats); index_t i = 0; feats->start_parser(); while (feats->get_next_example()) { SGVector<float64_t> example = feats->get_vector(); SGVector<float64_t> expected = orig_feats->get_feature_vector(i); ASSERT_EQ(dim, example.vlen); for (index_t j = 0; j < dim; j++) EXPECT_DOUBLE_EQ(expected.vector[j], example.vector[j]); feats->release_example(); i++; } feats->end_parser(); SG_UNREF(feats); }
27.073684
96
0.734837
srgnuclear
c65132082e64302e29b178bd5c1a5db607bae6a9
991
cpp
C++
DataStructures/Trie/Contacts/contacts.cpp
suzyz/HackerRank
e97f76c4b39aa448e43e30b479d9718b8b88b2d2
[ "MIT" ]
null
null
null
DataStructures/Trie/Contacts/contacts.cpp
suzyz/HackerRank
e97f76c4b39aa448e43e30b479d9718b8b88b2d2
[ "MIT" ]
null
null
null
DataStructures/Trie/Contacts/contacts.cpp
suzyz/HackerRank
e97f76c4b39aa448e43e30b479d9718b8b88b2d2
[ "MIT" ]
null
null
null
#include <iostream> #include <cstring> #include <algorithm> using namespace std; class Trie { public: int count; Trie *p[26]; Trie() { count = 0; memset(p,0,sizeof(p)); } ~Trie(); void add(string name); int find(string prefix); }; void Trie::add(string name) { Trie *ch = this; for (int i = 0; i < name.length(); ++i) { if (ch->p[name[i]] == NULL) ch->p[name[i]] = new Trie; ch = ch->p[name[i]]; ++ ch->count; } } int Trie::find(string prefix) { Trie *ch = this; for (int i = 0; i < prefix.length(); ++i) { if (ch->p[prefix[i]] == NULL) return 0; ch = ch->p[prefix[i]]; } if (ch == NULL) return 0; return ch->count; } int main() { int n; Trie *trie = new Trie; cin>>n; for (int i = 0; i < n; ++i) { string operation,name; cin>>operation>>name; for (int j = 0; j < name.length(); ++j) name[j] -= 'a'; if (operation=="add") trie->add(name); else { int ans = trie->find(name); cout<<ans<<endl; } } return 0; }
13.391892
42
0.543895
suzyz
c652265353ccd4981683a608c6fa1215ce18c62f
1,661
cpp
C++
src/io/io_file.cpp
le1ca/silica-irc
c81117e0416eb4446e2eddf9e810087159fd05cc
[ "MIT" ]
null
null
null
src/io/io_file.cpp
le1ca/silica-irc
c81117e0416eb4446e2eddf9e810087159fd05cc
[ "MIT" ]
null
null
null
src/io/io_file.cpp
le1ca/silica-irc
c81117e0416eb4446e2eddf9e810087159fd05cc
[ "MIT" ]
null
null
null
#include <silica/common/error.h> #include <silica/io/io_file.h> #include <fcntl.h> #include <unistd.h> namespace silica { namespace io { const std::unordered_map<std::string, int> io_file::flag_map = {{"r", O_RDONLY}, {"r+", O_RDWR}, {"w", O_WRONLY | O_CREAT | O_TRUNC}, {"w+", O_RDWR | O_CREAT | O_TRUNC}, {"a", O_WRONLY | O_CREAT | O_APPEND}, {"a+", O_RDWR | O_CREAT | O_APPEND}}; int io_file::decode_flags(const std::string& flags) { const std::unordered_map<std::string, int>::const_iterator it(flag_map.find(flags)); if (it == flag_map.end()) { make_error("socket_wrapper_file: invalid file flags '" << flags << "'"); } return it->second; } io_file::io_file(std::string const& filename, std::string const& flags) { if ((m_fd = open(filename.c_str(), decode_flags(flags))) < 0) { make_error("open()"); } } bool io_file::valid() { return true; } size_t io_file::avail() const { ssize_t orig; ssize_t result; if ((orig = lseek(m_fd, 0, SEEK_CUR)) == -1) { make_error_errno("lseek(): ", errno); } if ((result = lseek(m_fd, 0, SEEK_END)) == -1) { make_error_errno("lseek(): ", errno); } if (lseek(m_fd, orig, SEEK_SET) == -1) { make_error_errno("lseek(): ", errno); } return result - orig; } } // namespace io } // namespace silica
33.897959
101
0.493679
le1ca
c65447f8c5916a9cc3c384b5f68039ec7392a483
1,715
cpp
C++
merge_sort/main.cpp
215559085/AlogrithmAndDatastructrue
00b24b150fea29d2339d6a1797768174e955fc05
[ "MIT" ]
null
null
null
merge_sort/main.cpp
215559085/AlogrithmAndDatastructrue
00b24b150fea29d2339d6a1797768174e955fc05
[ "MIT" ]
null
null
null
merge_sort/main.cpp
215559085/AlogrithmAndDatastructrue
00b24b150fea29d2339d6a1797768174e955fc05
[ "MIT" ]
null
null
null
#include <iostream> #include <vector> using namespace std; vector<int> merge_twins(vector<vector<int>>* twin_group){ auto* tg = twin_group; int i = 1; do{ vector<int> result; vector<int> Vs1 = (*tg)[i-1]; vector<int> Vs2 = (*tg)[i]; for(int a=0,b=0;a<Vs1.size()||b<Vs2.size();){ if(a>=Vs1.size()){ result.push_back(Vs2[b]);++b; } else if(b>=Vs2.size()){ result.push_back(Vs1[a]);++a; } else{ if(Vs1[a] > Vs2[b]){ result.push_back(Vs1[a]);++a;} else{result.push_back(Vs2[b]);++b;} } } tg->push_back(result); i+=2; }while(i < tg->size()); delete(tg); return tg->back(); } vector<int> merge_sort(vector<int>& Vs,int start,int end){ auto* twin_group = new vector<vector<int>>; for(int i = start+1;i<end;){ vector<int> twin = * new vector<int>; if(Vs[i] > Vs[i-1]){ twin.push_back(Vs[i]); twin.push_back(Vs[i-1]); } else{ twin.push_back(Vs[i-1]); twin.push_back(Vs[i]); } twin_group->push_back(twin); if(end-i == 1){ vector<int> alone = * new vector<int>; alone.push_back(Vs[end]); twin_group->push_back(alone); } i+=2; } return merge_twins(twin_group); } int main() { vector<int> Vs={8,5,4,6,8,8,5,4,6,32,1,8,9,6,7,5,1,5,8,6,6,4,5,621,77,54,8,5,1,7,5,46,8,13,5,4,68,6,5,13,4,15}; cout << "Hello, World!" << endl; vector<int> res = merge_sort(Vs,0,Vs.size()-1); for(auto i : res){ cout<<i<<" "; } cout<<endl; return 0; }
29.568966
115
0.486297
215559085
c65532dcda327cba6f96cf98e6047f99002a1dcb
118
cpp
C++
project646/src/component146/cpp/lib1.cpp
gradle/perf-native-large
af00fd258fbe9c7d274f386e46847fe12062cc71
[ "Apache-2.0" ]
2
2016-11-23T17:25:24.000Z
2016-11-23T17:25:27.000Z
project646/src/component146/cpp/lib1.cpp
gradle/perf-native-large
af00fd258fbe9c7d274f386e46847fe12062cc71
[ "Apache-2.0" ]
15
2016-09-15T03:19:32.000Z
2016-09-17T09:15:32.000Z
project646/src/component146/cpp/lib1.cpp
gradle/perf-native-large
af00fd258fbe9c7d274f386e46847fe12062cc71
[ "Apache-2.0" ]
2
2019-11-09T16:26:55.000Z
2021-01-13T10:51:09.000Z
#include <stdio.h> #include <component146/lib1.h> int component146_1 () { printf("Hello world!\n"); return 0; }
13.111111
30
0.661017
gradle
c65655ea0fc5628ef66eb4ebe9c8ab24b4d58a30
482
cpp
C++
src/RE/NetImmerse/NiRefObject/NiObject/NiColorData.cpp
thallada/CommonLibSSE
b092c699c3ccd1af6d58d05f677f2977ec054cfe
[ "MIT" ]
1
2021-08-30T20:33:43.000Z
2021-08-30T20:33:43.000Z
src/RE/NetImmerse/NiRefObject/NiObject/NiColorData.cpp
thallada/CommonLibSSE
b092c699c3ccd1af6d58d05f677f2977ec054cfe
[ "MIT" ]
null
null
null
src/RE/NetImmerse/NiRefObject/NiObject/NiColorData.cpp
thallada/CommonLibSSE
b092c699c3ccd1af6d58d05f677f2977ec054cfe
[ "MIT" ]
1
2020-10-08T02:48:33.000Z
2020-10-08T02:48:33.000Z
#include "RE/NetImmerse/NiRefObject/NiObject/NiColorData.h" namespace RE { NiColorData::NiColorData() : numKeys(0), pad14(0), keys(nullptr), type(KeyType::kNoInterp), keySize(0), pad25(0), pad26(0) {} std::uint32_t NiColorData::GetNumKeys() const { return numKeys; } NiColorKey* NiColorData::GetAnim(std::uint32_t& a_numKeys, KeyType& a_type, std::uint8_t& a_size) const { a_numKeys = numKeys; a_type = type; a_size = keySize; return keys; } }
15.548387
104
0.682573
thallada
c6567048e511e42f403afd7a4dd35ed2a879183f
7,055
cpp
C++
src/pgen/dusty_soundwave.cpp
PinghuiHuang/athena-pp-dustfluids
fce21992cc107aa553e83dd76b8d03ae90e990c7
[ "BSD-3-Clause" ]
2
2020-07-02T09:48:49.000Z
2020-08-25T02:37:21.000Z
src/pgen/dusty_soundwave.cpp
PinghuiHuang/athena-pp-dustfluids
fce21992cc107aa553e83dd76b8d03ae90e990c7
[ "BSD-3-Clause" ]
null
null
null
src/pgen/dusty_soundwave.cpp
PinghuiHuang/athena-pp-dustfluids
fce21992cc107aa553e83dd76b8d03ae90e990c7
[ "BSD-3-Clause" ]
1
2021-11-12T13:39:48.000Z
2021-11-12T13:39:48.000Z
//======================================================================================== // Athena++ astrophysical MHD code // Copyright(C) 2014 James M. Stone <jmstone@princeton.edu> and other code contributors // Licensed under the 3-clause BSD License, see LICENSE file for details //======================================================================================== //! \file default_pgen.cpp // \brief Provides default (empty) versions of all functions in problem generator files // This means user does not have to implement these functions if they are not needed. // // The attribute "weak" is used to ensure the loader selects the user-defined version of // functions rather than the default version given here. // // The attribute "alias" may be used with the "weak" functions (in non-defining // declarations) in order to have them refer to common no-operation function definition in // the same translation unit. Target function must be specified by mangled name unless C // linkage is specified. // // This functionality is not in either the C nor the C++ standard. These GNU extensions // are largely supported by LLVM, Intel, IBM, but may affect portability for some // architecutres and compilers. In such cases, simply define all 6 of the below class // functions in every pgen/*.cpp file (without any function attributes). // C headers // C++ headers #include <algorithm> // min, max #include <cmath> // sqrt() #include <cstdio> // fopen(), fprintf(), freopen() #include <iostream> // endl #include <sstream> // stringstream #include <stdexcept> // runtime_error #include <string> // c_str() // Athena++ headers #include "../athena.hpp" #include "../athena_arrays.hpp" #include "../coordinates/coordinates.hpp" #include "../eos/eos.hpp" #include "../field/field.hpp" #include "../globals.hpp" #include "../hydro/hydro.hpp" #include "../mesh/mesh.hpp" #include "../parameter_input.hpp" #include "../reconstruct/reconstruction.hpp" #include "../dustfluids/dustfluids.hpp" #ifdef MPI_PARALLEL #include <mpi.h> #endif #if NON_BAROTROPIC_EOS #error "This problem generator requires isothermal equation of state!" #endif // problem parameters which are useful to make global to this file namespace { // Parameters which define initial solution -- made global so that they can be shared // with functions A1,2,3 which compute vector potentials Real rhog0, p0, u0, v0, w0, bx0, by0, bz0, dby, dbz; Real delta_rho_gas_real, delta_rho_gas_imag; Real delta_vel_gas_real, delta_vel_gas_imag; Real user_dt; Real amp, lambda, k_par; // amplitude, Wavelength, 2*PI/wavelength Real gam, gm1, iso_cs, vflow; Real initial_D2G[NDUSTFLUIDS]; Real delta_rho_dust_real[NDUSTFLUIDS]; Real delta_rho_dust_imag[NDUSTFLUIDS]; Real delta_vel_dust_real[NDUSTFLUIDS]; Real delta_vel_dust_imag[NDUSTFLUIDS]; Real MyTimeStep(MeshBlock *pmb); } // namespace // 3x members of Mesh class: namespace { Real MyTimeStep(MeshBlock *pmb) { Real min_user_dt = user_dt; return min_user_dt; } } //======================================================================================== //! \fn void Mesh::InitUserMeshData(ParameterInput *pin) // \brief Function to initialize problem-specific data in Mesh class. Can also be used // to initialize variables which are global to (and therefore can be passed to) other // functions in this file. Called in Mesh constructor. //======================================================================================== void Mesh::InitUserMeshData(ParameterInput *pin) { // read global parameters rhog0 = pin->GetOrAddReal("problem", "rhog0", 1.0); user_dt = pin->GetOrAddReal("time", "user_dt", 1.375e-2); amp = pin->GetReal("problem", "amp"); vflow = pin->GetOrAddReal("problem", "vflow", 0.0); iso_cs = pin->GetReal("hydro", "iso_sound_speed"); delta_rho_gas_real = pin->GetReal("problem", "delta_rho_gas_real"); delta_rho_gas_imag = pin->GetReal("problem", "delta_rho_gas_imag"); delta_vel_gas_real = pin->GetReal("problem", "delta_vel_gas_real"); delta_vel_gas_imag = pin->GetReal("problem", "delta_vel_gas_imag"); if (NDUSTFLUIDS > 0) { for (int n=0; n<NDUSTFLUIDS; ++n) { delta_rho_dust_real[n] = pin->GetReal("dust", "delta_rho_d_" + std::to_string(n+1) + "_real"); delta_rho_dust_imag[n] = pin->GetReal("dust", "delta_rho_d_" + std::to_string(n+1) + "_imag"); delta_vel_dust_real[n] = pin->GetReal("dust", "delta_vel_d_" + std::to_string(n+1) + "_real"); delta_vel_dust_imag[n] = pin->GetReal("dust", "delta_vel_d_" + std::to_string(n+1) + "_imag"); initial_D2G[n] = pin->GetReal("dust", "Initial_D2G_" + std::to_string(n+1)); } } if (NON_BAROTROPIC_EOS) { gam = pin->GetReal("hydro", "gamma"); gm1 = (gam - 1.0); } Real x1size = mesh_size.x1max - mesh_size.x1min; Real x2size = mesh_size.x2max - mesh_size.x2min; Real x3size = mesh_size.x3max - mesh_size.x3min; Real x1 = x1size; Real x2 = 0.0; Real x3 = 0.0; lambda = x1; k_par = 2.0*(PI)/lambda; u0 = vflow; v0 = 0.0; w0 = 0.0; p0 = SQR(iso_cs)*rhog0; if (user_dt > 0.0) EnrollUserTimeStepFunction(MyTimeStep); return; } void MeshBlock::ProblemGenerator(ParameterInput *pin) { Real inv_gm1 = 1./gm1; for (int k=ks; k<=ke; k++) { for (int j=js; j<=je; j++) { for (int i=is; i<=ie; i++) { Real x = pcoord->x1v(i); Real sn = std::sin(k_par*x); Real cn = std::cos(k_par*x); Real &gas_den = phydro->u(IDN, k, j, i); Real &gas_m1 = phydro->u(IM1, k, j, i); Real &gas_m2 = phydro->u(IM2, k, j, i); Real &gas_m3 = phydro->u(IM3, k, j, i); Real delta_rho = amp*rhog0*(cn*delta_rho_gas_real - sn*delta_rho_gas_imag); Real delta_vel = amp*iso_cs*(cn*delta_vel_gas_real - sn*delta_vel_gas_imag); gas_den = rhog0 + delta_rho; gas_m1 = rhog0*(u0 + delta_vel); gas_m2 = 0.0; gas_m3 = 0.0; if (NDUSTFLUIDS >0) { for (int n=0; n<NDUSTFLUIDS; ++n) { int dust_id = n; int rho_id = 4*dust_id; int v1_id = rho_id + 1; int v2_id = rho_id + 2; int v3_id = rho_id + 3; Real &dust_den = pdustfluids->df_cons(rho_id, k, j, i); Real &dust_m1 = pdustfluids->df_cons(v1_id, k, j, i); Real &dust_m2 = pdustfluids->df_cons(v2_id, k, j, i); Real &dust_m3 = pdustfluids->df_cons(v3_id, k, j, i); Real rhod0 = initial_D2G[dust_id] * rhog0; Real delta_dust_rho = rhog0*amp*(cn*delta_rho_dust_real[n] - sn*delta_rho_dust_imag[n]); Real delta_dust_vel = amp*iso_cs*(cn*delta_vel_dust_real[n] - sn*delta_vel_dust_imag[n]); dust_den = rhod0 + delta_dust_rho; dust_m1 = rhod0*(vflow + delta_dust_vel); dust_m2 = 0.0; dust_m3 = 0.0; } } } } } return; }
36.937173
101
0.617576
PinghuiHuang
c65d17798602b9ca5256d8dfa64085cebf993067
28,893
cpp
C++
UnrealMvvmTests/Source/UnrealMvvmTests/Private/ListenManager.spec.cpp
druhasu/UnrealMvvm
3ab5a2e98a36583c74c72c0a76c1669f37ff1820
[ "MIT" ]
5
2021-11-28T17:09:25.000Z
2022-03-14T08:55:03.000Z
UnrealMvvmTests/Source/UnrealMvvmTests/Private/ListenManager.spec.cpp
druhasu/UnrealMvvm
3ab5a2e98a36583c74c72c0a76c1669f37ff1820
[ "MIT" ]
null
null
null
UnrealMvvmTests/Source/UnrealMvvmTests/Private/ListenManager.spec.cpp
druhasu/UnrealMvvm
3ab5a2e98a36583c74c72c0a76c1669f37ff1820
[ "MIT" ]
2
2021-12-23T14:10:28.000Z
2022-03-27T15:34:10.000Z
// Copyright Andrei Sudarikov. All Rights Reserved. #include "Misc/AutomationTest.h" #include "Mvvm/ListenManager.h" #include "TestListener.h" BEGIN_DEFINE_SPEC(ListenManagerSpec, "UnrealMvvm.ListenManager", EAutomationTestFlags::ClientContext | EAutomationTestFlags::EditorContext | EAutomationTestFlags::ServerContext | EAutomationTestFlags::EngineFilter) END_DEFINE_SPEC(ListenManagerSpec) class FEventHolder { public: DECLARE_EVENT(FEventHolder, FTestEvent); mutable FTestEvent EventField; FTestEvent& EventMethod() { return EventField; } FTestEvent& EventMethodConst() const { return EventField; } DECLARE_MULTICAST_DELEGATE(FTestDelegate); mutable FTestDelegate DelegateField; FTestDelegate& DelegateMethod() { return DelegateField; } FTestDelegate& DelegateMethodConst() const { return DelegateField; } mutable FTestDynamicDelegate DynamicDelegateField; FTestDynamicDelegate& DynamicDelegateMethod() { return DynamicDelegateField; } FTestDynamicDelegate& DynamicDelegateMethodConst() const { return DynamicDelegateField; } }; class FSecondBase { int32 Dummy; }; class FMultiInheritedEventHolder : public FEventHolder, public FSecondBase { public: FTestEvent EventFieldDerived; FTestEvent& EventMethodDerived() { return EventFieldDerived; } FTestDynamicDelegate DynamicDelegateFieldDerived; FTestDynamicDelegate& DynamicDelegateMethodDerived() { return DynamicDelegateFieldDerived; } }; bool StaticInvoked = false; void StaticCallback() { StaticInvoked = true; } void ListenManagerSpec::Define() { Describe("Simple Delegate", [this]() { Describe("WithStatic", [this]() { It("Should Listen To Simple Event Field With Static", [this]() { FEventHolder Holder; FListenManager Manager; StaticInvoked = false; Manager.Listen(&Holder, &FEventHolder::EventField).WithStatic(&StaticCallback); Holder.EventField.Broadcast(); TestTrue("Listener not added", Holder.EventField.IsBound()); TestTrue("Listener not invoked", StaticInvoked); }); It("Should Listen To Simple Delegate Field With Static", [this]() { FEventHolder Holder; FListenManager Manager; StaticInvoked = false; Manager.Listen(&Holder, &FEventHolder::DelegateField).WithStatic(&StaticCallback); Holder.DelegateField.Broadcast(); TestTrue("Listener not added", Holder.DelegateField.IsBound()); TestTrue("Listener not invoked", StaticInvoked); }); It("Should Listen To Simple Event Method With Static", [this]() { FEventHolder Holder; FListenManager Manager; StaticInvoked = false; Manager.Listen(&Holder, &FEventHolder::EventMethod).WithStatic(&StaticCallback); Holder.EventField.Broadcast(); TestTrue("Listener not added", Holder.EventField.IsBound()); TestTrue("Listener not invoked", StaticInvoked); }); It("Should Listen To Simple Delegate Method With Static", [this]() { FEventHolder Holder; FListenManager Manager; StaticInvoked = false; Manager.Listen(&Holder, &FEventHolder::DelegateMethod).WithStatic(&StaticCallback); Holder.DelegateField.Broadcast(); TestTrue("Listener not added", Holder.DelegateField.IsBound()); TestTrue("Listener not invoked", StaticInvoked); }); It("Should Listen To Simple Event Const Method With Static", [this]() { FEventHolder Holder; FListenManager Manager; StaticInvoked = false; Manager.Listen(&Holder, &FEventHolder::EventMethodConst).WithStatic(&StaticCallback); Holder.EventField.Broadcast(); TestTrue("Listener not added", Holder.EventField.IsBound()); TestTrue("Listener not invoked", StaticInvoked); }); It("Should Listen To Simple Delegate Const Method With Static", [this]() { FEventHolder Holder; FListenManager Manager; StaticInvoked = false; Manager.Listen(&Holder, &FEventHolder::DelegateMethodConst).WithStatic(&StaticCallback); Holder.DelegateField.Broadcast(); TestTrue("Listener not added", Holder.DelegateField.IsBound()); TestTrue("Listener not invoked", StaticInvoked); }); It("Should Unsubscribe From Simple Event With Static", [this]() { FEventHolder Holder; FListenManager Manager; Manager.Listen(&Holder, &FEventHolder::EventField).WithStatic(&StaticCallback); TestTrue("Listener not added", Holder.EventField.IsBound()); Manager.UnsubscribeAll(); TestFalse("Listener not removed", Holder.EventField.IsBound()); }); It("Should Unsubscribe From Simple Delegate With Static", [this]() { FEventHolder Holder; FListenManager Manager; Manager.Listen(&Holder, &FEventHolder::DelegateField).WithStatic(&StaticCallback); TestTrue("Listener not added", Holder.DelegateField.IsBound()); Manager.UnsubscribeAll(); TestFalse("Listener not removed", Holder.DelegateField.IsBound()); }); }); Describe("WithLambda", [this]() { It("Should Listen To Simple Event Field With Lambda", [this]() { FEventHolder Holder; FListenManager Manager; bool Invoked = false; Manager.Listen(&Holder, &FEventHolder::EventField).WithLambda([&Invoked]() { Invoked = true; }); Holder.EventField.Broadcast(); TestTrue("Listener not added", Holder.EventField.IsBound()); TestTrue("Listener not invoked", Invoked); }); It("Should Listen To Simple Delegate Field With Lambda", [this]() { FEventHolder Holder; FListenManager Manager; bool Invoked = false; Manager.Listen(&Holder, &FEventHolder::DelegateField).WithLambda([&Invoked]() { Invoked = true; }); Holder.DelegateField.Broadcast(); TestTrue("Listener not added", Holder.DelegateField.IsBound()); TestTrue("Listener not invoked", Invoked); }); It("Should Listen To Simple Event Method With Lambda", [this]() { FEventHolder Holder; FListenManager Manager; bool Invoked = false; Manager.Listen(&Holder, &FEventHolder::EventMethod).WithLambda([&Invoked]() { Invoked = true; }); Holder.EventField.Broadcast(); TestTrue("Listener not added", Holder.EventField.IsBound()); TestTrue("Listener not invoked", Invoked); }); It("Should Listen To Simple Delegate Method With Lambda", [this]() { FEventHolder Holder; FListenManager Manager; bool Invoked = false; Manager.Listen(&Holder, &FEventHolder::DelegateMethod).WithLambda([&Invoked]() { Invoked = true; }); Holder.DelegateField.Broadcast(); TestTrue("Listener not added", Holder.DelegateField.IsBound()); TestTrue("Listener not invoked", Invoked); }); It("Should Listen To Simple Event Const Method With Lambda", [this]() { FEventHolder Holder; FListenManager Manager; bool Invoked = false; Manager.Listen(&Holder, &FEventHolder::EventMethodConst).WithLambda([&Invoked]() { Invoked = true; }); Holder.EventField.Broadcast(); TestTrue("Listener not added", Holder.EventField.IsBound()); TestTrue("Listener not invoked", Invoked); }); It("Should Listen To Simple Delegate Const Method With Lambda", [this]() { FEventHolder Holder; FListenManager Manager; bool Invoked = false; Manager.Listen(&Holder, &FEventHolder::DelegateMethodConst).WithLambda([&Invoked]() { Invoked = true; }); Holder.DelegateField.Broadcast(); TestTrue("Listener not added", Holder.DelegateField.IsBound()); TestTrue("Listener not invoked", Invoked); }); It("Should Unsubscribe From Simple Event With Lambda", [this]() { FEventHolder Holder; FListenManager Manager; Manager.Listen(&Holder, &FEventHolder::EventField).WithLambda([]() {}); TestTrue("Listener not added", Holder.EventField.IsBound()); Manager.UnsubscribeAll(); TestFalse("Listener not removed", Holder.EventField.IsBound()); }); It("Should Unsubscribe From Simple Delegate With Lambda", [this]() { FEventHolder Holder; FListenManager Manager; Manager.Listen(&Holder, &FEventHolder::DelegateField).WithLambda([]() {}); TestTrue("Listener not added", Holder.DelegateField.IsBound()); Manager.UnsubscribeAll(); TestFalse("Listener not removed", Holder.DelegateField.IsBound()); }); }); Describe("WithWeakLambda", [this]() { It("Should Listen To Simple Event Field With Lambda", [this]() { FEventHolder Holder; FListenManager Manager; bool Invoked = false; UTestListener* Listener = NewObject<UTestListener>(); Manager.Listen(&Holder, &FEventHolder::EventField).WithWeakLambda(Listener, [&Invoked]() { Invoked = true; }); Holder.EventField.Broadcast(); TestTrue("Listener not added", Holder.EventField.IsBound()); TestTrue("Listener not invoked", Invoked); }); It("Should Listen To Simple Delegate Field With WeakLambda", [this]() { FEventHolder Holder; FListenManager Manager; bool Invoked = false; UTestListener* Listener = NewObject<UTestListener>(); Manager.Listen(&Holder, &FEventHolder::DelegateField).WithWeakLambda(Listener, [&Invoked]() { Invoked = true; }); Holder.DelegateField.Broadcast(); TestTrue("Listener not added", Holder.DelegateField.IsBound()); TestTrue("Listener not invoked", Invoked); }); It("Should Listen To Simple Event Method With WeakLambda", [this]() { FEventHolder Holder; FListenManager Manager; bool Invoked = false; UTestListener* Listener = NewObject<UTestListener>(); Manager.Listen(&Holder, &FEventHolder::EventMethod).WithWeakLambda(Listener, [&Invoked]() { Invoked = true; }); Holder.EventField.Broadcast(); TestTrue("Listener not added", Holder.EventField.IsBound()); TestTrue("Listener not invoked", Invoked); }); It("Should Listen To Simple Delegate Method With WeakLambda", [this]() { FEventHolder Holder; FListenManager Manager; bool Invoked = false; UTestListener* Listener = NewObject<UTestListener>(); Manager.Listen(&Holder, &FEventHolder::DelegateMethod).WithWeakLambda(Listener, [&Invoked]() { Invoked = true; }); Holder.DelegateField.Broadcast(); TestTrue("Listener not added", Holder.DelegateField.IsBound()); TestTrue("Listener not invoked", Invoked); }); It("Should Listen To Simple Event Const Method With WeakLambda", [this]() { FEventHolder Holder; FListenManager Manager; bool Invoked = false; UTestListener* Listener = NewObject<UTestListener>(); Manager.Listen(&Holder, &FEventHolder::EventMethodConst).WithWeakLambda(Listener, [&Invoked]() { Invoked = true; }); Holder.EventField.Broadcast(); TestTrue("Listener not added", Holder.EventField.IsBound()); TestTrue("Listener not invoked", Invoked); }); It("Should Listen To Simple Delegate Const Method With WeakLambda", [this]() { FEventHolder Holder; FListenManager Manager; bool Invoked = false; UTestListener* Listener = NewObject<UTestListener>(); Manager.Listen(&Holder, &FEventHolder::DelegateMethodConst).WithWeakLambda(Listener, [&Invoked]() { Invoked = true; }); Holder.DelegateField.Broadcast(); TestTrue("Listener not added", Holder.DelegateField.IsBound()); TestTrue("Listener not invoked", Invoked); }); It("Should Unsubscribe From Simple Event With WeakLambda", [this]() { FEventHolder Holder; FListenManager Manager; UTestListener* Listener = NewObject<UTestListener>(); Manager.Listen(&Holder, &FEventHolder::EventField).WithWeakLambda(Listener, []() {}); TestTrue("Listener not added", Holder.EventField.IsBound()); Manager.UnsubscribeAll(); TestFalse("Listener not removed", Holder.EventField.IsBound()); }); It("Should Unsubscribe From Simple Delegate With WeakLambda", [this]() { FEventHolder Holder; FListenManager Manager; UTestListener* Listener = NewObject<UTestListener>(); Manager.Listen(&Holder, &FEventHolder::DelegateField).WithWeakLambda(Listener, []() {}); TestTrue("Listener not added", Holder.DelegateField.IsBound()); Manager.UnsubscribeAll(); TestFalse("Listener not removed", Holder.DelegateField.IsBound()); }); }); Describe("WithSP", [this]() { It("Should Listen To Simple Event Field With SharedPtr", [this]() { FEventHolder Holder; FListenManager Manager; TSharedPtr<FTestListener> Listener = MakeShared<FTestListener>(); Manager.Listen(&Holder, &FEventHolder::EventField).WithSP(Listener.Get(), &FTestListener::SimpleCallback); Holder.EventField.Broadcast(); TestTrue("Listener not added", Holder.EventField.IsBound()); TestTrue("Listener not invoked", Listener->Invoked); }); It("Should Listen To Simple Delegate Field With SharedPtr", [this]() { FEventHolder Holder; FListenManager Manager; TSharedPtr<FTestListener> Listener = MakeShared<FTestListener>(); Manager.Listen(&Holder, &FEventHolder::DelegateField).WithSP(Listener.Get(), &FTestListener::SimpleCallback); Holder.DelegateField.Broadcast(); TestTrue("Listener not added", Holder.DelegateField.IsBound()); TestTrue("Listener not invoked", Listener->Invoked); }); It("Should Listen To Simple Event Method With SharedPtr", [this]() { FEventHolder Holder; FListenManager Manager; TSharedPtr<FTestListener> Listener = MakeShared<FTestListener>(); Manager.Listen(&Holder, &FEventHolder::EventMethod).WithSP(Listener.Get(), &FTestListener::SimpleCallback); Holder.EventField.Broadcast(); TestTrue("Listener not added", Holder.EventField.IsBound()); TestTrue("Listener not invoked", Listener->Invoked); }); It("Should Listen To Simple Delegate Method With SharedPtr", [this]() { FEventHolder Holder; FListenManager Manager; TSharedPtr<FTestListener> Listener = MakeShared<FTestListener>(); Manager.Listen(&Holder, &FEventHolder::DelegateMethod).WithSP(Listener.Get(), &FTestListener::SimpleCallback); Holder.DelegateField.Broadcast(); TestTrue("Listener not added", Holder.DelegateField.IsBound()); TestTrue("Listener not invoked", Listener->Invoked); }); It("Should Listen To Simple Event Const Method With SharedPtr", [this]() { FEventHolder Holder; FListenManager Manager; TSharedPtr<FTestListener> Listener = MakeShared<FTestListener>(); Manager.Listen(&Holder, &FEventHolder::EventMethodConst).WithSP(Listener.Get(), &FTestListener::SimpleCallback); Holder.EventField.Broadcast(); TestTrue("Listener not added", Holder.EventField.IsBound()); TestTrue("Listener not invoked", Listener->Invoked); }); It("Should Listen To Simple Delegate Const Method With SharedPtr", [this]() { FEventHolder Holder; FListenManager Manager; TSharedPtr<FTestListener> Listener = MakeShared<FTestListener>(); Manager.Listen(&Holder, &FEventHolder::DelegateMethodConst).WithSP(Listener.Get(), &FTestListener::SimpleCallback); Holder.DelegateField.Broadcast(); TestTrue("Listener not added", Holder.DelegateField.IsBound()); TestTrue("Listener not invoked", Listener->Invoked); }); It("Should Unsubscribe From Simple Event With SharedPtr", [this]() { FEventHolder Holder; FListenManager Manager; TSharedPtr<FTestListener> Listener = MakeShared<FTestListener>(); Manager.Listen(&Holder, &FEventHolder::EventField).WithSP(Listener.Get(), &FTestListener::SimpleCallback); TestTrue("Listener not added", Holder.EventField.IsBound()); Manager.UnsubscribeAll(); TestFalse("Listener not removed", Holder.EventField.IsBound()); }); It("Should Unsubscribe From Simple Delegate With SharedPtr", [this]() { FEventHolder Holder; FListenManager Manager; TSharedPtr<FTestListener> Listener = MakeShared<FTestListener>(); Manager.Listen(&Holder, &FEventHolder::DelegateField).WithSP(Listener.Get(), &FTestListener::SimpleCallback); TestTrue("Listener not added", Holder.DelegateField.IsBound()); Manager.UnsubscribeAll(); TestFalse("Listener not removed", Holder.DelegateField.IsBound()); }); }); Describe("WithUObject", [this]() { It("Should Listen To Simple Event Field With UObject", [this]() { FEventHolder Holder; FListenManager Manager; UTestListener* Listener = NewObject<UTestListener>(); Manager.Listen(&Holder, &FEventHolder::EventField).WithUObject(Listener, &UTestListener::SimpleCallback); Holder.EventField.Broadcast(); TestTrue("Listener not added", Holder.EventField.IsBound()); TestTrue("Listener not invoked", Listener->Invoked); }); It("Should Listen To Simple Delegate Field With UObject", [this]() { FEventHolder Holder; FListenManager Manager; UTestListener* Listener = NewObject<UTestListener>(); Manager.Listen(&Holder, &FEventHolder::DelegateField).WithUObject(Listener, &UTestListener::SimpleCallback); Holder.DelegateField.Broadcast(); TestTrue("Listener not added", Holder.DelegateField.IsBound()); TestTrue("Listener not invoked", Listener->Invoked); }); It("Should Listen To Simple Event Method With UObject", [this]() { FEventHolder Holder; FListenManager Manager; UTestListener* Listener = NewObject<UTestListener>(); Manager.Listen(&Holder, &FEventHolder::EventMethod).WithUObject(Listener, &UTestListener::SimpleCallback); Holder.EventField.Broadcast(); TestTrue("Listener not added", Holder.EventField.IsBound()); TestTrue("Listener not invoked", Listener->Invoked); }); It("Should Listen To Simple Delegate Method With UObject", [this]() { FEventHolder Holder; FListenManager Manager; UTestListener* Listener = NewObject<UTestListener>(); Manager.Listen(&Holder, &FEventHolder::DelegateMethod).WithUObject(Listener, &UTestListener::SimpleCallback); Holder.DelegateField.Broadcast(); TestTrue("Listener not added", Holder.DelegateField.IsBound()); TestTrue("Listener not invoked", Listener->Invoked); }); It("Should Listen To Simple Event Const Method With UObject", [this]() { FEventHolder Holder; FListenManager Manager; UTestListener* Listener = NewObject<UTestListener>(); Manager.Listen(&Holder, &FEventHolder::EventMethodConst).WithUObject(Listener, &UTestListener::SimpleCallback); Holder.EventField.Broadcast(); TestTrue("Listener not added", Holder.EventField.IsBound()); TestTrue("Listener not invoked", Listener->Invoked); }); It("Should Listen To Simple Delegate Const Method With UObject", [this]() { FEventHolder Holder; FListenManager Manager; UTestListener* Listener = NewObject<UTestListener>(); Manager.Listen(&Holder, &FEventHolder::DelegateMethodConst).WithUObject(Listener, &UTestListener::SimpleCallback); Holder.DelegateField.Broadcast(); TestTrue("Listener not added", Holder.DelegateField.IsBound()); TestTrue("Listener not invoked", Listener->Invoked); }); It("Should Unsubscribe From Simple Event With UObject", [this]() { FEventHolder Holder; FListenManager Manager; UTestListener* Listener = NewObject<UTestListener>(); Manager.Listen(&Holder, &FEventHolder::EventField).WithUObject(Listener, &UTestListener::SimpleCallback); TestTrue("Listener not added", Holder.EventField.IsBound()); Manager.UnsubscribeAll(); TestFalse("Listener not removed", Holder.EventField.IsBound()); }); It("Should Unsubscribe From Simple Delegate With UObject", [this]() { FEventHolder Holder; FListenManager Manager; UTestListener* Listener = NewObject<UTestListener>(); Manager.Listen(&Holder, &FEventHolder::DelegateField).WithUObject(Listener, &UTestListener::SimpleCallback); TestTrue("Listener not added", Holder.DelegateField.IsBound()); Manager.UnsubscribeAll(); TestFalse("Listener not removed", Holder.DelegateField.IsBound()); }); }); It("Should Compile Unsubscriber From Event Of Class With Several Bases", [this]() { FMultiInheritedEventHolder Holder; FListenManager Manager; bool Invoked = false; Manager.Listen(&Holder, &FMultiInheritedEventHolder::EventFieldDerived).WithLambda([&Invoked]() { Invoked = true; }); Manager.Listen(&Holder, &FMultiInheritedEventHolder::EventMethodDerived).WithLambda([&Invoked]() { Invoked = true; }); Holder.EventField.Broadcast(); Manager.UnsubscribeAll(); }); }); Describe("Dynamic Delegate", [this]() { Describe("WithDynamic", [this]() { It("Should Listen To Dynamic Delegate Field With UFunction", [this]() { FEventHolder Holder; FListenManager Manager; UTestListener* Listener = NewObject<UTestListener>(); Manager.Listen(&Holder, &FEventHolder::DynamicDelegateField).WithDynamic(Listener, &UTestListener::DynamicCallback); Holder.DynamicDelegateField.Broadcast(); TestTrue("Listener not added", Holder.DynamicDelegateField.IsBound()); TestTrue("Listener not invoked", Listener->Invoked); }); It("Should Listen To Dynamic Delegate Method With UFunction", [this]() { FEventHolder Holder; FListenManager Manager; UTestListener* Listener = NewObject<UTestListener>(); Manager.Listen(&Holder, &FEventHolder::DynamicDelegateMethod).WithDynamic(Listener, &UTestListener::DynamicCallback); Holder.DynamicDelegateField.Broadcast(); TestTrue("Listener not added", Holder.DynamicDelegateField.IsBound()); TestTrue("Listener not invoked", Listener->Invoked); }); It("Should Listen To Dynamic Delegate Const Method With UFunction", [this]() { FEventHolder Holder; FListenManager Manager; UTestListener* Listener = NewObject<UTestListener>(); Manager.Listen(&Holder, &FEventHolder::DynamicDelegateMethodConst).WithDynamic(Listener, &UTestListener::DynamicCallback); Holder.DynamicDelegateField.Broadcast(); TestTrue("Listener not added", Holder.DynamicDelegateField.IsBound()); TestTrue("Listener not invoked", Listener->Invoked); }); It("Should Unsubscribe From Dynamic Delegate With UFunction", [this]() { FEventHolder Holder; FListenManager Manager; UTestListener* Listener = NewObject<UTestListener>(); Manager.Listen(&Holder, &FEventHolder::DynamicDelegateField).WithDynamic(Listener, &UTestListener::DynamicCallback); TestTrue("Listener not added", Holder.DynamicDelegateField.IsBound()); Manager.UnsubscribeAll(); TestFalse("Listener not removed", Holder.DynamicDelegateField.IsBound()); }); }); It("Should Compile Unsubscriber From Event Of Class With Several Bases", [this]() { FListenManager Manager; UTestListener* Listener = NewObject<UTestListener>(); { FMultiInheritedEventHolder Holder; Manager.Listen(&Holder, &FMultiInheritedEventHolder::DynamicDelegateFieldDerived).WithDynamic(Listener, &UTestListener::DynamicCallback); Holder.DynamicDelegateField.Broadcast(); Manager.UnsubscribeAll(); } { FMultiInheritedEventHolder Holder; Manager.Listen(&Holder, &FMultiInheritedEventHolder::DynamicDelegateMethodDerived).WithDynamic(Listener, &UTestListener::DynamicCallback); Holder.DynamicDelegateField.Broadcast(); Manager.UnsubscribeAll(); } }); }); It("Should Remove All Subscriptions From Destructor", [this]() { FEventHolder Holder; { FListenManager Manager; Manager.Listen(&Holder, &FEventHolder::DelegateField).WithLambda([]() {}); TestTrue("Listener not added", Holder.DelegateField.IsBound()); } TestFalse("Listener not removed", Holder.DelegateField.IsBound()); }); }
41.692641
214
0.582736
druhasu
c6607ed75baf7e2ae95be4b8afdba08de2d70c57
5,159
cpp
C++
src/editable_graph.cpp
jlwitthuhn/cycles-shader-editor
0d6771801402ca7ecff006f399be90b1beea2884
[ "MIT" ]
11
2018-04-05T06:52:17.000Z
2021-12-14T07:02:52.000Z
src/editable_graph.cpp
jlwitthuhn/cycles-shader-editor
0d6771801402ca7ecff006f399be90b1beea2884
[ "MIT" ]
2
2018-01-18T04:30:58.000Z
2020-07-25T09:49:23.000Z
src/editable_graph.cpp
jlwitthuhn/cycles-shader-editor
0d6771801402ca7ecff006f399be90b1beea2884
[ "MIT" ]
4
2018-04-02T13:36:40.000Z
2021-08-21T21:23:23.000Z
#include "editable_graph.h" #include "node_outputs.h" #include "sockets.h" #include "util_vector.h" cse::EditableGraph::EditableGraph(const ShaderGraphType type) { reset(type); } void cse::EditableGraph::add_node(std::shared_ptr<EditableNode>& node, const Float2 world_pos) { if (node.use_count() == 0) { return; } node->world_pos = world_pos; nodes.push_front(node); should_push_undo_state = true; } void cse::EditableGraph::add_connection(const std::weak_ptr<NodeSocket> socket_begin, const std::weak_ptr<NodeSocket> socket_end) { EditableNode* source_node = nullptr; if (const auto socket_begin_ptr = socket_begin.lock()) { if (socket_begin_ptr->io_type != SocketIOType::OUTPUT) { return; } source_node = socket_begin_ptr->parent; } else { // pointer is invalid return; } if (const auto socket_end_ptr = socket_end.lock()) { if (socket_end_ptr->io_type != SocketIOType::INPUT) { return; } if (socket_end_ptr->parent == source_node) { // Do not allow a node to connect to itself return; } } else { // pointer is invalid return; } // Remove any existing connection with this endpoint remove_connection_with_end(socket_end); should_push_undo_state = true; NodeConnection new_connection(socket_begin, socket_end); connections.push_back(new_connection); } cse::NodeConnection cse::EditableGraph::remove_connection_with_end(const std::weak_ptr<NodeSocket> socket_end) { const NodeConnection default_result = NodeConnection(std::weak_ptr<NodeSocket>(), std::weak_ptr<NodeSocket>()); if (socket_end.expired()) { return default_result; } std::list<NodeConnection>::iterator iter; for (iter = connections.begin(); iter != connections.end(); iter++) { if (iter->end_socket.lock() == socket_end.lock()) { should_push_undo_state = true; NodeConnection result = *iter; connections.erase(iter); return result; } } return default_result; } void cse::EditableGraph::remove_node_set(const cse::WeakNodeSet& weak_nodes_to_remove) { // Create a set of shared_ptrs from the weak_ptrs SharedNodeSet shared_nodes_to_remove; for (auto weak_node : weak_nodes_to_remove) { shared_nodes_to_remove.insert(weak_node.lock()); } // Remove all nodes in the set auto node_iter = nodes.begin(); while (node_iter != nodes.end()) { auto this_node = *node_iter; if (this_node->can_be_deleted() && shared_nodes_to_remove.count(this_node) == 1) { node_iter = nodes.erase(node_iter); should_push_undo_state = true; } else { node_iter++; } } remove_invalid_connections(); } bool cse::EditableGraph::is_node_under_point(const Float2 world_pos) const { for (const auto this_node : nodes) { if (this_node->contains_point(world_pos)) { return true; } } return false; } std::weak_ptr<cse::EditableNode> cse::EditableGraph::get_node_under_point(const Float2 world_pos) const { for (const auto this_node : nodes) { if (this_node->contains_point(world_pos)) { return this_node; } } return std::weak_ptr<EditableNode>(); } std::weak_ptr<cse::NodeSocket> cse::EditableGraph::get_socket_under_point(const Float2 world_pos) const { for (const auto this_node : nodes) { auto maybe_result = this_node->get_socket_label_under_point(world_pos); if (maybe_result.expired() == false) { return maybe_result; } } return std::weak_ptr<NodeSocket>(); } std::weak_ptr<cse::NodeSocket> cse::EditableGraph::get_connector_under_point(const Float2 world_pos, const SocketIOType io_type) const { for (const auto this_node : nodes) { auto maybe_result = this_node->get_socket_connector_under_point(world_pos); if (auto maybe_result_ptr = maybe_result.lock()) { if (maybe_result_ptr->io_type == io_type) { return maybe_result; } } } return std::weak_ptr<NodeSocket>(); } void cse::EditableGraph::raise_node(const std::weak_ptr<cse::EditableNode> weak_node) { if (weak_node.expired()) { return; } const std::shared_ptr<EditableNode> node_to_raise = weak_node.lock(); // Exit early if this is already the top node if (nodes.front() == node_to_raise) { return; } for (auto iter = nodes.begin(); iter != nodes.end(); iter++) { const std::shared_ptr<EditableNode> this_node = *iter; if (this_node == node_to_raise) { nodes.erase(iter); nodes.push_front(this_node); return; } } } bool cse::EditableGraph::needs_undo_push() { bool result = false; for (const auto this_node : nodes) { if (this_node->changed) { result = true; this_node->changed = false; } } if (should_push_undo_state) { result = true; should_push_undo_state = false; } return result; } void cse::EditableGraph::reset(const ShaderGraphType type) { connections.clear(); nodes.clear(); switch (type) { case ShaderGraphType::EMPTY: // Do nothing break; case ShaderGraphType::MATERIAL: { nodes.push_back(std::make_shared<MaterialOutputNode>(Float2(0.0f, 0.0f))); } } } void cse::EditableGraph::remove_invalid_connections() { std::list<NodeConnection>::iterator iter = connections.begin(); while (iter != connections.end()) { if (iter->is_valid()) { iter++; } else { iter = connections.erase(iter); } } }
24.684211
134
0.718356
jlwitthuhn
c660c618ee8ef913577bbbda3f560db160ae2d42
1,188
cpp
C++
Source/Core/Geometry/HittableList.cpp
T-rvw/RayTracingRender
941782dc070b27db381976650aa6bddd8e6f45a1
[ "MIT" ]
null
null
null
Source/Core/Geometry/HittableList.cpp
T-rvw/RayTracingRender
941782dc070b27db381976650aa6bddd8e6f45a1
[ "MIT" ]
null
null
null
Source/Core/Geometry/HittableList.cpp
T-rvw/RayTracingRender
941782dc070b27db381976650aa6bddd8e6f45a1
[ "MIT" ]
null
null
null
#include "HittableList.h" std::optional<HitRecord> HittableList::hit(const Ray& ray, double minT, double maxT) const { bool hitAnything = false; double closestT = maxT; std::optional<HitRecord> finalResult = std::nullopt; for (const auto& pHittableObject : m_vecHittableObjects) { std::optional<HitRecord> tempResult = pHittableObject->hit(ray, minT, closestT); if (tempResult.has_value()) { hitAnything = true; closestT = tempResult.value().rayT(); finalResult = tempResult.value(); } } return finalResult; } std::optional<AABB> HittableList::boundingBox(double t0, double t1) const { std::optional<AABB> optOutputBox; for (const auto& pHittableObject : m_vecHittableObjects) { std::optional<AABB> optBox = pHittableObject->boundingBox(t0, t1); if (!optBox.has_value()) { break; } if (!optOutputBox.has_value()) { optOutputBox = std::move(optBox); } else { optOutputBox = AABB::merge(optOutputBox.value(), optBox.value()); } } return optOutputBox; }
26.4
90
0.598485
T-rvw
c661be2d8619ef8cca0232b790ae6157d71518b7
1,725
hpp
C++
HttpServer/include/Http/HttpStatusCode.hpp
WoozChucky/cpp-webserver-eventdriven
5ea96b299f7f948e45a7591b4aa46b3e6e895373
[ "MIT" ]
1
2021-04-13T18:36:38.000Z
2021-04-13T18:36:38.000Z
HttpServer/include/Http/HttpStatusCode.hpp
WoozChucky/cpp-webserver-eventdriven
5ea96b299f7f948e45a7591b4aa46b3e6e895373
[ "MIT" ]
1
2022-03-02T00:24:24.000Z
2022-03-02T00:24:24.000Z
HttpServer/include/Http/HttpStatusCode.hpp
WoozChucky/cpp-webserver-eventdriven
5ea96b299f7f948e45a7591b4aa46b3e6e895373
[ "MIT" ]
null
null
null
// // Created by Nuno Levezinho Silva on 17/09/2019. // #ifndef HTTPSTATUSCODE_HPP #define HTTPSTATUSCODE_HPP #include <Abstractions/Types.hpp> enum HttpStatusCode : U16 { /* 1xx Status Codes */ CONTINUE = 100, SWITCHING_PROTOCOLS = 101, EARLY_HINTS = 103, /* 2xx Status Codes */ OK = 200, CREATED = 201, ACCEPTED = 202, NON_AUTHORITATIVE_INFORMATION = 203, NO_CONTENT = 204, RESET_CONTENT = 205, PARTIAL_CONTENT = 206, /* 3xx Status Codes */ MULTIPLE_CHOICES = 300, MOVED_PERMANENTLY = 301, FOUND = 302, SEE_OTHER = 303, NOT_MODIFIED = 304, TEMPORARY_REDIRECT = 307, PERMANENT_REDIRECT = 308, /* 4xx Status Codes */ BAD_REQUEST = 400, UNAUTHORIZED = 401, PAYMENT_REQUIRED = 402, FORBIDDEN = 403, NOT_FOUND = 404, METHOD_NOT_ALLOWED = 405, NOT_ACCEPTABLE = 406, PROXY_AUTHENTICATION_REQUIRED = 407, REQUEST_TIMEOUT = 408, CONFLICT = 409, GONE = 410, LENGTH_REQUIRED = 411, PRECONDITION_FAILED = 412, PAYLOAD_TOO_LARGE = 413, URI_TOO_LONG = 414, UNSUPPORTED_MEDIA_TYPE = 415, RANGE_NOT_SATISFIABLE = 416, EXPECTATION_FAILED = 417, IM_A_TEAMPOT = 418, UNPROCESSABLE_ENTITY = 422, TOO_EARLY = 425, UPGRADE_REQUIRED = 426, PRECONDITION_REQUIRED = 428, TOO_MANY_REQUESTS = 429, REQUEST_HEADER_FIELDS_TOO_LARGE = 431, UNAVAILABLE_FOR_LEGAL_REASONS = 451, /* 5xx Status Codes */ INTERNAL_SERVER_ERROR = 500, NOT_IMPLEMENTED = 501, BAD_GATEWAY = 502, SERVICE_UNAVAILABLE = 503, GATEWAY_TIMEOUT = 504, HTTP_VERSION_NOT_SUPPORTED = 505, NETWORK_AUTHENTICATION_REQUIRED = 511 }; #endif //HTTPSTATUSCODE_HPP
23.310811
49
0.669565
WoozChucky
c6620ab873aefa1315e7443326b824fab893e6ac
949
cpp
C++
Dice_throw.cpp
shivamkrs89/DYNAMIC-PROGRAMMING
7284918d61107ed9ac8092349b5289c69e628e2d
[ "MIT" ]
2
2021-05-27T14:56:52.000Z
2021-05-27T15:08:02.000Z
Dice_throw.cpp
shivamkrs89/DYNAMIC-PROGRAMMING
7284918d61107ed9ac8092349b5289c69e628e2d
[ "MIT" ]
null
null
null
Dice_throw.cpp
shivamkrs89/DYNAMIC-PROGRAMMING
7284918d61107ed9ac8092349b5289c69e628e2d
[ "MIT" ]
null
null
null
Given integers n, faces, and total, return the number of ways it is possible to throw n dice with faces faces each to get total. Mod the result by 10 ** 9 + 7. Constraints 1 ≤ n, faces, total ≤ 100 Example 1 Input n = 2 faces = 6 total = 7 Output 6 Explanation There are 6 ways to make 7 with 2 6-sided dice: 1 and 6 6 and 1 2 and 5 5 and 2 3 and 4 4 and 3 //code //better expalination refer to https://www.geeksforgeeks.org/dice-throw-dp-30/ int solve(int n, int faces, int total) { int md=1e9+7; long long count=0; long long int dp[n+1][total+1]; memset(dp,0,sizeof(dp)); int i,j; for(i=1;i<=total;i++) { if(i<=faces) dp[1][i]=1; } for(i=2;i<=n;i++) { for(j=1;j<=total;j++) { dp[i][j]=(dp[i-1][j-1]+dp[i][j-1])%md;//fiing a face j-1 to 1 and getting possiblities. if(j>=faces+1) dp[i][j]-=dp[i-1][j-faces-1]; } } return dp[n][total]%md;
15.306452
128
0.582719
shivamkrs89
c66346c8c4231e22097018ff169b19d3c7c200de
1,314
cpp
C++
src/common/utils/timer.cpp
VNOpenAI/daisykit
8c313c3ce067e0cc6e2880543a791a778a3f4bfa
[ "Apache-2.0" ]
13
2021-09-06T04:15:45.000Z
2021-09-30T04:03:36.000Z
src/common/utils/timer.cpp
Daisykit-AI/daisykit
1342e2849e45f11cd05df7c2d990b4e4679c4e7e
[ "Apache-2.0" ]
7
2021-09-17T17:43:11.000Z
2021-09-28T12:38:11.000Z
src/common/utils/timer.cpp
Daisykit-AI/daisykit
1342e2849e45f11cd05df7c2d990b4e4679c4e7e
[ "Apache-2.0" ]
5
2021-09-12T03:26:28.000Z
2021-10-09T07:39:15.000Z
// Copyright 2021 The DaisyKit Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "daisykit/common/utils/timer.h" #include <chrono> #include <ctime> namespace daisykit { namespace utils { // Get current time point. TimePoint Timer::Now() { return std::chrono::high_resolution_clock::now(); } // Get time eslapsed from `start` to `end` time points. double Timer::CalcTimeElapsedMs(TimePoint start, TimePoint end) { double elapsed_time_ms = std::chrono::duration<double, std::milli>(end - start).count(); return elapsed_time_ms; } // Get time eslapsed from `start` to now. double Timer::CalcTimeElapsedMs(TimePoint start) { auto now = Now(); return CalcTimeElapsedMs(start, now); } } // namespace utils } // namespace daisykit
32.04878
77
0.709285
VNOpenAI
c664f6a8ac1667c36a3a4c5bc1fb915baf952536
949
cpp
C++
arm/src/dynamixel_hand_control.cpp
AvatarQuest/AVA-ros
3e945d859155f559761f47040b1431e0e9ee8da1
[ "MIT" ]
null
null
null
arm/src/dynamixel_hand_control.cpp
AvatarQuest/AVA-ros
3e945d859155f559761f47040b1431e0e9ee8da1
[ "MIT" ]
null
null
null
arm/src/dynamixel_hand_control.cpp
AvatarQuest/AVA-ros
3e945d859155f559761f47040b1431e0e9ee8da1
[ "MIT" ]
null
null
null
#include "ros/ros.h" #include <geometry_msgs/Vector3.h> #define AXIS y double states[5]; void pinkyCB(const geometry_msgs::Vector3::ConstPtr& msg) { } void ringCB(const geometry_msgs::Vector3::ConstPtr& msg) { } void indexCB(const geometry_msgs::Vector3::ConstPtr& msg) { } void middleCB(const geometry_msgs::Vector3::ConstPtr& msg) { } void thumbCB(const geometry_msgs::Vector3::ConstPtr& msg) { } int main(int argc, char** argv) { ros::init(argc, argv, "dynamixel_hand"); ros::NodeHandle nh; ros::Subscriber pinky_sub = nh.subscribe("pinky", 1, pinkyCB); ros::Subscriber ring_sub = nh.subscribe("ring", 1, ringCB); ros::Subscriber index_sub = nh.subscribe("index", 1,indexCB); ros::Subscriber middle_sub = nh.subscribe("middle", 1, middleCB); ros::Subscriber thumb_sub = nh.subscribe("thumb", 1, thumbCB); ROS_INFO("%s", "starting node 'dynamixel_hand_control'"); ros::spin(); return 0; }
23.146341
69
0.689146
AvatarQuest
c6655ba5c3b1ea97fca8c409457b22d999f41bdb
7,068
hh
C++
core/bootstrap/srpc.hh
HXLLL/rlibv2
a9165e5863dae9c54e0fe80e682f75ec31d858c6
[ "Apache-2.0" ]
17
2020-06-27T01:01:25.000Z
2022-02-26T00:20:20.000Z
core/bootstrap/srpc.hh
HXLLL/rlibv2
a9165e5863dae9c54e0fe80e682f75ec31d858c6
[ "Apache-2.0" ]
null
null
null
core/bootstrap/srpc.hh
HXLLL/rlibv2
a9165e5863dae9c54e0fe80e682f75ec31d858c6
[ "Apache-2.0" ]
6
2020-07-08T02:18:09.000Z
2022-02-16T01:36:13.000Z
#pragma once #include <mutex> // lock #include <utility> // std::pair #include "./channel.hh" #include "./multi_msg.hh" #include "./proto.hh" namespace rdmaio { namespace bootstrap { using namespace proto; enum CallStatus : u8 { Ok = 0, Nop, WrongReply, NotMatch, FatalErr, }; struct __attribute__((packed)) SRpcHeader { rpc_id_t id; u64 checksum; }; struct __attribute__((packed)) SReplyHeader { u8 callstatus; u64 checksum; // if dummy is euqal to 1, // then we will omit the checksum check at client // because it is a heartbeat reply message u8 dummy = 0; }; /*! A simple RPC used for establish connection for RDMA. */ class SRpc { public: static const u64 invalid_checksum = 0; private: Arc<SendChannel> channel; u64 checksum = invalid_checksum + 1; public: using MMsg = MultiMsg<kMaxMsgSz>; explicit SRpc(const std::string &addr) : channel(SendChannel::create(addr).value()) {} /*! Send an RPC with id "id", using a specificed parameter. */ Result<std::string> call(const rpc_id_t &id, const ByteBuffer &parameter) { auto mmsg_o = MMsg::create_exact(sizeof(rpc_id_t) + parameter.size()); if (mmsg_o) { auto &mmsg = mmsg_o.value(); RDMA_ASSERT(mmsg.append(::rdmaio::Marshal::dump<SRpcHeader>( {.id = id, .checksum = checksum}))); RDMA_ASSERT(mmsg.append(parameter)); return channel->send(*mmsg.buf); } else { return ::rdmaio::Err( std::string("Msg too large!, only kMaxMsgSz supported")); } } /*! Recv a reply from the server ysing the timeout specified. \Note: this call must follow from a "call" */ Result<ByteBuffer> receive_reply(const double &timeout_usec = 1000000, bool heartbeat = false) { retry: auto res = channel->recv(timeout_usec); if (res == IOCode::Ok) { // further we decode the header for check try { auto decoded_reply = MultiMsg<kMaxMsgSz>::create_from(res.desc).value(); auto header = ::rdmaio::Marshal::dedump<SReplyHeader>( decoded_reply.query_one(0).value()) .value(); // first we handle heartbeat reply if (header.dummy) { if (!heartbeat) goto retry; // ignore the heartbeat reply return ::rdmaio::Ok(ByteBuffer("")); } // then we handle normal reply if (header.checksum == checksum) { checksum += 1; switch (header.callstatus) { case CallStatus::Ok: return ::rdmaio::Ok(decoded_reply.query_one(1).value()); case CallStatus::Nop: return ::rdmaio::Err(ByteBuffer("Not ready")); default: return ::rdmaio::Err(ByteBuffer("unknown error")); } } else return ::rdmaio::Err(ByteBuffer("Fatal checksum error")); } catch (std::exception &e) { return ::rdmaio::Err(ByteBuffer("decode reply error")); } } else { // the receive has error, just return return res; } } }; class SRpcHandler; class RPCFactory { friend class SRpcHandler; /*! A simple RPC function: handle(const ByteBuffer &req) -> ByteBuffer */ using req_handler_f = std::function<ByteBuffer(const ByteBuffer &req)>; std::map<rpc_id_t, req_handler_f> registered_handlers; std::mutex lock; RPCFactory() { // register a default heartbeat handler register_handler(RCtrlBinderIdType::HeartBeat, &RPCFactory::heartbeat_handler); }; public: bool register_handler(rpc_id_t id, req_handler_f val) { std::lock_guard<std::mutex> guard(lock); if (registered_handlers.find(id) == registered_handlers.end()) { registered_handlers.insert(std::make_pair(id, val)); return true; } return false; } ByteBuffer call_one(rpc_id_t id, const ByteBuffer &parameter) { auto fn = registered_handlers.find(id)->second; return fn(parameter); } private: static ByteBuffer heartbeat_handler(const ByteBuffer &b) { return ByteBuffer("1"); // a null reply is ok } }; class SRpcHandler { Arc<RecvChannel> channel; RPCFactory factory; public: explicit SRpcHandler(const usize &port, const std::string &h = "localhost") : channel(RecvChannel::create(port, h).value()) {} bool register_handler(rpc_id_t id, RPCFactory::req_handler_f val) { return factory.register_handler(id, val); } /*! Run a event loop to call received RPC calls \ret: number of PRCs served */ usize run_one_event_loop() { usize count = 0; for (channel->start(1000000); channel->has_msg(); channel->next(), count += 1) { auto &msg = channel->cur(); u64 checksum = SRpc::invalid_checksum; try { MultiMsg<kMaxMsgSz> segmeneted_msg; SRpcHeader header; try { // create from move the cur_msg to a MuiltiMsg segmeneted_msg = MultiMsg<kMaxMsgSz>::create_from(msg).value(); // query the RPC call id header = ::rdmaio::Marshal::dedump<SRpcHeader>( segmeneted_msg.query_one(0).value()) .value(); checksum = header.checksum; } catch (std::exception &e) { // some error happens, which is fatal because we cannot decode the // checksum MultiMsg<kMaxMsgSz> coded_reply = MultiMsg<kMaxMsgSz>::create_exact(sizeof(SReplyHeader)).value(); coded_reply.append(::rdmaio::Marshal::dump<SReplyHeader>( {.callstatus = CallStatus::FatalErr, .checksum = checksum, .dummy = 0})); channel->reply_cur(*coded_reply.buf); continue; } // really handles the request rpc_id_t id = header.id; ByteBuffer parameter = segmeneted_msg.query_one(1).value(); // call the RPC ByteBuffer reply = factory.call_one(id, parameter); MultiMsg<kMaxMsgSz> coded_reply = MultiMsg<kMaxMsgSz>::create_exact(sizeof(SReplyHeader) + reply.size()) .value(); coded_reply.append(::rdmaio::Marshal::dump<SReplyHeader>( {.callstatus = CallStatus::Ok, .checksum = checksum, .dummy = (id == RCtrlBinderIdType::HeartBeat) ? static_cast<u8>(1) : static_cast<u8>(0)})); coded_reply.append(reply); // send the reply to the client channel->reply_cur(*coded_reply.buf); } catch (std::exception &e) { MultiMsg<kMaxMsgSz> coded_reply = MultiMsg<kMaxMsgSz>::create_exact(sizeof(SReplyHeader)).value(); // some error happens coded_reply.append(::rdmaio::Marshal::dump<SReplyHeader>( {.callstatus = CallStatus::Nop, .checksum = checksum})); channel->reply_cur(*coded_reply.buf); } } return count; } }; } // namespace bootstrap } // namespace rdmaio
27.826772
84
0.604697
HXLLL
c668d4df23c87822213e9a3314680eff69713ff9
361
cpp
C++
data_structure/test/union_find.test.cpp
cormoran/LibAlgorithm
9eec05a36343c891be5fee475678a283081c68d3
[ "MIT" ]
1
2020-03-28T23:46:14.000Z
2020-03-28T23:46:14.000Z
data_structure/test/union_find.test.cpp
cormoran/LibAlgorithm
9eec05a36343c891be5fee475678a283081c68d3
[ "MIT" ]
null
null
null
data_structure/test/union_find.test.cpp
cormoran/LibAlgorithm
9eec05a36343c891be5fee475678a283081c68d3
[ "MIT" ]
null
null
null
#define PROBLEM "https://judge.yosupo.jp/problem/unionfind" #include "../union_find.hpp" int main() { int N, Q; cin >> N >> Q; UnionFind uf(N); while (Q--) { int t, u, v; cin >> t >> u >> v; if (t == 0) uf.unite(u, v); else cout << (uf.query(u, v) ? 1 : 0) << endl; } return 0; }
20.055556
59
0.434903
cormoran
c66d7bd2cd24a9b86b2c0a2054db11807b7ad3e3
420
cpp
C++
ContainerWithMostWater/ContainerWithMostWater.cpp
yergen/leetcode
7b6dac49ac44e0bf43a4ecb4795ea8cfe6afa4ab
[ "MIT" ]
null
null
null
ContainerWithMostWater/ContainerWithMostWater.cpp
yergen/leetcode
7b6dac49ac44e0bf43a4ecb4795ea8cfe6afa4ab
[ "MIT" ]
null
null
null
ContainerWithMostWater/ContainerWithMostWater.cpp
yergen/leetcode
7b6dac49ac44e0bf43a4ecb4795ea8cfe6afa4ab
[ "MIT" ]
null
null
null
#include<vector> #include<iostream> #include<algorithm> using namespace::std; class Solution { public: int maxArea(vector<int>& height) { int m = 0, n = height.size(); for (int i = 0; i < n; ++i) for (int j = i + 1; j < n;++j) { m = max(min(height[i], height[j])*(j - i),m); } return m; } }; int main() { vector<int> h{1,8,6,2,5,4,8,3,7}; Solution sol; cout << sol.maxArea(h) << endl; return 0; }
16.153846
48
0.566667
yergen
c66d9feab8bf43eb3a8d932bc2b5b85b71c95fab
816
cpp
C++
2out/NamedTest.cpp
DBrutski/2out
28aecd80496250641672638c9ab2cfdc9e5df36d
[ "MIT" ]
null
null
null
2out/NamedTest.cpp
DBrutski/2out
28aecd80496250641672638c9ab2cfdc9e5df36d
[ "MIT" ]
null
null
null
2out/NamedTest.cpp
DBrutski/2out
28aecd80496250641672638c9ab2cfdc9e5df36d
[ "MIT" ]
null
null
null
// Copyright (c) 2017-2020 Andrey Valyaev <dron.valyaev@gmail.com> // // This software may be modified and distributed under the terms // of the MIT license. See the LICENSE file for details. #include "NamedTest.h" #include "NamedResult.h" #include "SuiteTest.h" using namespace std; using namespace oout; NamedTest::NamedTest(const string &name, const shared_ptr<const Test> &test) : name(name), test(test) { } NamedTest::NamedTest(const string &name, const shared_ptr<const NamedTest> &test) : NamedTest(name, make_shared<const SuiteTest>(test)) { } NamedTest::NamedTest(const string &name, const list<shared_ptr<const Test>> &tests) : NamedTest(name, make_shared<const SuiteTest>(tests)) { } unique_ptr<const Result> NamedTest::result() const { return make_unique<NamedResult>(name, test->result()); }
25.5
83
0.746324
DBrutski
c66df8b390747c9ce12f0ade5066bbbada49eedb
762
cpp
C++
UVa/AC/A_Change_in_Thermal_Unit-11984.cpp
AHJenin/acm-type-problems
e2a6d58fe8872ceaed822f5ee8911bfc173c6192
[ "MIT" ]
4
2018-05-17T08:37:53.000Z
2018-06-08T18:47:21.000Z
UVa/AC/A_Change_in_Thermal_Unit-11984.cpp
arafat-hasan/acm-type-problems
e2a6d58fe8872ceaed822f5ee8911bfc173c6192
[ "MIT" ]
null
null
null
UVa/AC/A_Change_in_Thermal_Unit-11984.cpp
arafat-hasan/acm-type-problems
e2a6d58fe8872ceaed822f5ee8911bfc173c6192
[ "MIT" ]
null
null
null
/************************************************************** * FILE NAME: A_Change_in_Thermal_Unit-11984.cpp * * PURPOSE: Solve of Uva problem. * * @author: Md. Arafat Hasan Jenin * EMAIL: OpenDoor.Arafat@gmail.com * * DEVELOPMENT HISTORY: * Date Change Version Description * -------------------------------------------------------------------- * 21 Nov 16 New 1.0 Completed,Accepted ***************************************************************/ #include <stdio.h> int main() { int testcase, j = 0; double c, f; scanf("%i", &testcase); while (j < testcase && scanf("%lf %lf", &c, &f) == 2) { j++; printf("Case %i: %.2lf\n", j, c + f/1.8); } return 0; }
27.214286
70
0.392388
AHJenin
c66e985c0711996f7104556c5b523c0e1ef16624
2,244
cc
C++
chrome/browser/download/download_resource_throttle.cc
iplo/Chain
8bc8943d66285d5258fffc41bed7c840516c4422
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
231
2015-01-08T09:04:44.000Z
2021-12-30T03:03:10.000Z
chrome/browser/download/download_resource_throttle.cc
j4ckfrost/android_external_chromium_org
a1a3dad8b08d1fcf6b6b36c267158ed63217c780
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
1
2017-02-14T21:55:58.000Z
2017-02-14T21:55:58.000Z
chrome/browser/download/download_resource_throttle.cc
j4ckfrost/android_external_chromium_org
a1a3dad8b08d1fcf6b6b36c267158ed63217c780
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
268
2015-01-21T05:53:28.000Z
2022-03-25T22:09:01.000Z
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/download/download_resource_throttle.h" #include "base/bind.h" #include "chrome/browser/download/download_stats.h" #include "content/public/browser/resource_controller.h" DownloadResourceThrottle::DownloadResourceThrottle( DownloadRequestLimiter* limiter, int render_process_id, int render_view_id, int request_id, const std::string& request_method) : querying_limiter_(true), request_allowed_(false), request_deferred_(false) { limiter->CanDownloadOnIOThread( render_process_id, render_view_id, request_id, request_method, base::Bind(&DownloadResourceThrottle::ContinueDownload, AsWeakPtr())); } DownloadResourceThrottle::~DownloadResourceThrottle() { } void DownloadResourceThrottle::WillStartRequest(bool* defer) { WillDownload(defer); } void DownloadResourceThrottle::WillRedirectRequest(const GURL& new_url, bool* defer) { WillDownload(defer); } void DownloadResourceThrottle::WillProcessResponse(bool* defer) { WillDownload(defer); } const char* DownloadResourceThrottle::GetNameForLogging() const { return "DownloadResourceThrottle"; } void DownloadResourceThrottle::WillDownload(bool* defer) { DCHECK(!request_deferred_); // Defer the download until we have the DownloadRequestLimiter result. if (querying_limiter_) { request_deferred_ = true; *defer = true; return; } if (!request_allowed_) controller()->Cancel(); } void DownloadResourceThrottle::ContinueDownload(bool allow) { querying_limiter_ = false; request_allowed_ = allow; if (allow) { // Presumes all downloads initiated by navigation use this throttle and // nothing else does. RecordDownloadSource(DOWNLOAD_INITIATED_BY_NAVIGATION); } else { RecordDownloadCount(CHROME_DOWNLOAD_COUNT_BLOCKED_BY_THROTTLING); } if (request_deferred_) { request_deferred_ = false; if (allow) { controller()->Resume(); } else { controller()->Cancel(); } } }
26.714286
75
0.717023
iplo
c670d9031f90bb661f04de19db1931e8af596364
4,039
cxx
C++
test/mpi/cxx/io/fileerrx.cxx
OpenCMISS-Dependencies/mpich2
cc5f4d3fd0f8c9f2774d10deaebdced77985d839
[ "Unlicense" ]
7
2015-12-31T03:15:50.000Z
2020-08-15T00:54:47.000Z
test/mpi/cxx/io/fileerrx.cxx
grondo/mvapich2-cce
ec084d8e07db1cf2ac1352ee4c604ae7dbae55cb
[ "Intel", "mpich2", "Unlicense" ]
3
2015-12-30T22:28:15.000Z
2017-05-16T19:17:42.000Z
test/mpi/cxx/io/fileerrx.cxx
grondo/mvapich2-cce
ec084d8e07db1cf2ac1352ee4c604ae7dbae55cb
[ "Intel", "mpich2", "Unlicense" ]
3
2015-12-29T22:14:56.000Z
2019-06-13T07:23:35.000Z
/* -*- Mode: C++; c-basic-offset:4 ; -*- */ /* * * (C) 2003 by Argonne National Laboratory. * See COPYRIGHT in top-level directory. */ #include "mpi.h" #include "mpitestconf.h" #ifdef HAVE_IOSTREAM // Not all C++ compilers have iostream instead of iostream.h #include <iostream> #ifdef HAVE_NAMESPACE_STD // Those that do often need the std namespace; otherwise, a bare "cout" // is likely to fail to compile using namespace std; #endif #else #include <iostream.h> #endif #ifdef HAVE_STRING_H #include <string.h> #endif #include "mpitestcxx.h" static int codesSeen[3], callcount; void myerrhanfunc( MPI::File &fh, int *errcode, ... ); int main( int argc, char **argv ) { int errs = 0; MPI::File fh; MPI::Intracomm comm; MPI::Errhandler myerrhan, qerr; char filename[50]; char *errstring; int code[2], newerrclass, eclass, rlen; MTest_Init( ); errstring = new char [MPI::MAX_ERROR_STRING]; callcount = 0; // Setup some new codes and classes newerrclass = MPI::Add_error_class(); code[0] = MPI::Add_error_code( newerrclass ); code[1] = MPI::Add_error_code( newerrclass ); MPI::Add_error_string( newerrclass, "New Class" ); MPI::Add_error_string( code[0], "First new code" ); MPI::Add_error_string( code[1], "Second new code" ); myerrhan = MPI::File::Create_errhandler( myerrhanfunc ); // Create a new communicator so that we can leave the default errors-abort // on COMM_WORLD. Use this comm for file_open, just to leave a little // more separation from comm_world comm = MPI::COMM_WORLD.Dup(); fh = MPI::File::Open( comm, "testfile.txt", MPI::MODE_RDWR | MPI::MODE_CREATE, MPI::INFO_NULL ); fh.Set_errhandler( myerrhan ); qerr = fh.Get_errhandler(); if (qerr != myerrhan) { errs++; cout << " Did not get expected error handler\n"; } qerr.Free(); // We can free our error handler now myerrhan.Free(); fh.Call_errhandler( newerrclass ); fh.Call_errhandler( code[0] ); fh.Call_errhandler( code[1] ); if (callcount != 3) { errs++; cout << " Expected 3 calls to error handler, found " << callcount << "\n"; } else { if (codesSeen[0] != newerrclass) { errs++; cout << "Expected class " << newerrclass << " got " << codesSeen[0] << "\n"; } if (codesSeen[1] != code[0]) { errs++; cout << "(1)Expected code " << code[0] << " got " << codesSeen[1] << "\n"; } if (codesSeen[2] != code[1]) { errs++; cout << "(2)Expected code " << code[1] << " got " << codesSeen[2] << "\n"; } } fh.Close(); comm.Free(); MPI::File::Delete( "testfile.txt", MPI::INFO_NULL ); // Check error strings while we're here... MPI::Get_error_string( newerrclass, errstring, rlen ); if (strcmp(errstring,"New Class") != 0) { errs++; cout << " Wrong string for error class: " << errstring << "\n"; } eclass = MPI::Get_error_class( code[0] ); if (eclass != newerrclass) { errs++; cout << " Class for new code is not correct\n"; } MPI::Get_error_string( code[0], errstring, rlen ); if (strcmp( errstring, "First new code") != 0) { errs++; cout << " Wrong string for error code: " << errstring << "\n"; } eclass = MPI::Get_error_class( code[1] ); if (eclass != newerrclass) { errs++; cout << " Class for new code is not correct\n"; } MPI::Get_error_string( code[1], errstring, rlen ); if (strcmp( errstring, "Second new code") != 0) { errs++; cout << " Wrong string for error code: " << errstring << "\n"; } delete [] errstring; MTest_Finalize( errs ); MPI::Finalize(); return 0; } void myerrhanfunc( MPI::File &fh, int *errcode, ... ) { char *errstring; int rlen; errstring = new char [MPI::MAX_ERROR_STRING]; callcount++; // Remember the code we've seen if (callcount < 4) { codesSeen[callcount-1] = *errcode; } MPI::Get_error_string( *errcode, errstring, rlen ); delete [] errstring; }
25.726115
78
0.607824
OpenCMISS-Dependencies
c67107e8ef019307c8a122f6a5d37eeaebb06ac6
2,006
cpp
C++
components/xtl/tests/xtl/types/type_info.cpp
untgames/funner
c91614cda55fd00f5631d2bd11c4ab91f53573a3
[ "MIT" ]
7
2016-03-30T17:00:39.000Z
2017-03-27T16:04:04.000Z
components/xtl/tests/xtl/types/type_info.cpp
untgames/Funner
c91614cda55fd00f5631d2bd11c4ab91f53573a3
[ "MIT" ]
4
2017-11-21T11:25:49.000Z
2018-09-20T17:59:27.000Z
components/xtl/tests/xtl/types/type_info.cpp
untgames/Funner
c91614cda55fd00f5631d2bd11c4ab91f53573a3
[ "MIT" ]
4
2016-11-29T15:18:40.000Z
2017-03-27T16:04:08.000Z
#include <cstdio> #include <xtl/type_info.h> using namespace xtl; struct A { virtual ~A () {} }; void dump1 (const xtl::type_info& t) { #define DUMP_FIELD(X) if (t.X ()) printf (" %s\n", #X); DUMP_FIELD (is_void); DUMP_FIELD (is_integral); DUMP_FIELD (is_floating_point); DUMP_FIELD (is_array); DUMP_FIELD (is_pointer); DUMP_FIELD (is_reference); DUMP_FIELD (is_member_object_pointer); DUMP_FIELD (is_member_function_pointer); DUMP_FIELD (is_enum); DUMP_FIELD (is_union); DUMP_FIELD (is_class); DUMP_FIELD (is_function); DUMP_FIELD (is_arithmetic); DUMP_FIELD (is_fundamental); DUMP_FIELD (is_object); DUMP_FIELD (is_scalar); DUMP_FIELD (is_compound); DUMP_FIELD (is_member_pointer); DUMP_FIELD (is_const); DUMP_FIELD (is_volatile); DUMP_FIELD (is_pod); DUMP_FIELD (is_empty); DUMP_FIELD (is_polymorphic); DUMP_FIELD (is_abstract); DUMP_FIELD (has_trivial_constructor); DUMP_FIELD (has_trivial_copy); DUMP_FIELD (has_trivial_assign); // DUMP_FIELD (has_trivial_destructor); // DUMP_FIELD (has_nothrow_constructor); // DUMP_FIELD (has_nothrow_copy); // DUMP_FIELD (has_nothrow_assign); // DUMP_FIELD (has_virtual_destructor); DUMP_FIELD (is_signed); DUMP_FIELD (is_unsigned); // printf (" alignment_of: %u\n", t.alignment_of ()); printf (" rank: %u\n", t.rank ()); #undef DUMP_FIELD } void dump (const char* name, const xtl::type_info& t) { printf ("type '%s'\n", name); dump1 (t); printf ("type remove_const('%s')\n", name); dump1 (t.remove_const ()); printf ("type 'remove_const(remove_reference('%s'))\n", name); dump1 (t.remove_const ().remove_reference ()); } int main () { printf ("Results of type_info_test:\n"); // const xtl::type_info& int_type = get_type<int> (); // dump ("int", int_type); const xtl::type_info& a_type = get_type<const A&> (); dump ("A", a_type); return 0; }
23.6
65
0.654536
untgames
c674dc404555c0f67ff09b2220a690bef2624a2d
26,770
cxx
C++
Source/igstkLandmark3DRegistration.cxx
ipa/IGSTK
d31f77b04aa72469e18e8a989ed8316bad39ed7a
[ "BSD-3-Clause" ]
5
2016-02-12T18:55:20.000Z
2022-02-05T09:23:07.000Z
Source/igstkLandmark3DRegistration.cxx
ipa/IGSTK
d31f77b04aa72469e18e8a989ed8316bad39ed7a
[ "BSD-3-Clause" ]
1
2018-01-26T10:39:31.000Z
2018-01-26T10:39:31.000Z
Source/igstkLandmark3DRegistration.cxx
ipa/IGSTK
d31f77b04aa72469e18e8a989ed8316bad39ed7a
[ "BSD-3-Clause" ]
4
2017-09-24T01:19:32.000Z
2021-06-20T18:02:42.000Z
/*========================================================================= Program: Image Guided Surgery Software Toolkit Module: igstkLandmark3DRegistration.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) ISC Insight Software Consortium. All rights reserved. See IGSTKCopyright.txt or http://www.igstk.org/copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #if defined(_MSC_VER) #pragma warning( disable : 4786 ) #endif #include "igstkLandmark3DRegistration.h" #include "igstkEvents.h" #include "igstkCoordinateSystemTransformToResult.h" #include "itkNumericTraits.h" #include "itkMatrix.h" #include "itkSymmetricEigenAnalysis.h" #include "vnl/vnl_math.h" namespace igstk { /** Constructor */ Landmark3DRegistration::Landmark3DRegistration() : m_StateMachine( this ) { // Set the state descriptors igstkAddStateMacro( Idle ); igstkAddStateMacro( ImageLandmark1Added ); igstkAddStateMacro( TrackerLandmark1Added ); igstkAddStateMacro( ImageLandmark2Added ); igstkAddStateMacro( TrackerLandmark2Added ); igstkAddStateMacro( ImageLandmark3Added ); igstkAddStateMacro( TrackerLandmark3Added ); igstkAddStateMacro( AttemptingToComputeTransform ); igstkAddStateMacro( TransformComputed ); // Set the input descriptors igstkAddInputMacro( ImageLandmark ); igstkAddInputMacro( TrackerLandmark ); igstkAddInputMacro( ComputeTransform ); igstkAddInputMacro( GetTransformFromTrackerToImage ); igstkAddInputMacro( GetTransformFromImageToTracker ); igstkAddInputMacro( GetRMSError ); igstkAddInputMacro( ResetRegistration ); igstkAddInputMacro( TransformComputationSuccess ); igstkAddInputMacro( TransformComputationFailure ); // Add transition for landmark point adding igstkAddTransitionMacro(Idle, ImageLandmark, ImageLandmark1Added, AddImageLandmarkPoint); igstkAddTransitionMacro(ImageLandmark1Added, TrackerLandmark, TrackerLandmark1Added, AddTrackerLandmarkPoint); igstkAddTransitionMacro(ImageLandmark1Added, ImageLandmark, ImageLandmark1Added, ReportInvalidRequest); igstkAddTransitionMacro(TrackerLandmark1Added, ImageLandmark, ImageLandmark2Added, AddImageLandmarkPoint); igstkAddTransitionMacro(TrackerLandmark1Added, TrackerLandmark, TrackerLandmark1Added, ReportInvalidRequest); igstkAddTransitionMacro(ImageLandmark2Added, TrackerLandmark, TrackerLandmark2Added, AddTrackerLandmarkPoint); igstkAddTransitionMacro(ImageLandmark2Added, ImageLandmark, ImageLandmark2Added, ReportInvalidRequest); igstkAddTransitionMacro(TrackerLandmark2Added, ImageLandmark, ImageLandmark3Added, AddImageLandmarkPoint); igstkAddTransitionMacro(TrackerLandmark2Added, TrackerLandmark, TrackerLandmark2Added, ReportInvalidRequest); igstkAddTransitionMacro(ImageLandmark3Added, TrackerLandmark, TrackerLandmark3Added, AddTrackerLandmarkPoint); igstkAddTransitionMacro(ImageLandmark3Added, ImageLandmark, ImageLandmark3Added, ReportInvalidRequest); igstkAddTransitionMacro(TrackerLandmark3Added, ImageLandmark, ImageLandmark3Added, AddImageLandmarkPoint); igstkAddTransitionMacro(TrackerLandmark3Added, TrackerLandmark, TrackerLandmark3Added, ReportInvalidRequest); igstkAddTransitionMacro( TrackerLandmark3Added, ComputeTransform, AttemptingToComputeTransform, ComputeTransform ); igstkAddTransitionMacro( AttemptingToComputeTransform, TransformComputationSuccess, TransformComputed, ReportSuccessInTransformComputation ); igstkAddTransitionMacro( AttemptingToComputeTransform, TransformComputationFailure, TrackerLandmark3Added, ReportFailureInTransformComputation ); igstkAddTransitionMacro( TransformComputed, GetTransformFromTrackerToImage, TransformComputed, GetTransformFromTrackerToImage ); igstkAddTransitionMacro( TransformComputed, GetTransformFromImageToTracker, TransformComputed, GetTransformFromImageToTracker ); igstkAddTransitionMacro( TransformComputed, GetRMSError, TransformComputed, GetRMSError ); // Add transitions for all invalid requests igstkAddTransitionMacro( Idle, ComputeTransform, Idle, ReportInvalidRequest ); igstkAddTransitionMacro( ImageLandmark1Added, ComputeTransform, ImageLandmark1Added, ReportInvalidRequest ); igstkAddTransitionMacro( ImageLandmark2Added, ComputeTransform, ImageLandmark2Added, ReportInvalidRequest); igstkAddTransitionMacro( ImageLandmark3Added, ComputeTransform, ImageLandmark3Added, ReportInvalidRequest); igstkAddTransitionMacro( TrackerLandmark1Added, ComputeTransform, TrackerLandmark1Added, ReportInvalidRequest); igstkAddTransitionMacro( TrackerLandmark2Added, ComputeTransform, TrackerLandmark2Added, ReportInvalidRequest); igstkAddTransitionMacro( Idle, GetTransformFromTrackerToImage, Idle, ReportInvalidRequest ); igstkAddTransitionMacro( Idle, GetTransformFromImageToTracker, Idle, ReportInvalidRequest ); igstkAddTransitionMacro( ImageLandmark1Added, GetTransformFromTrackerToImage, ImageLandmark1Added, ReportInvalidRequest ); igstkAddTransitionMacro( ImageLandmark1Added, GetTransformFromImageToTracker, ImageLandmark1Added, ReportInvalidRequest ); igstkAddTransitionMacro( ImageLandmark2Added, GetTransformFromTrackerToImage, ImageLandmark2Added, ReportInvalidRequest); igstkAddTransitionMacro( ImageLandmark2Added, GetTransformFromImageToTracker, ImageLandmark2Added, ReportInvalidRequest); igstkAddTransitionMacro( ImageLandmark3Added, GetTransformFromTrackerToImage, ImageLandmark3Added, ReportInvalidRequest); igstkAddTransitionMacro( ImageLandmark3Added, GetTransformFromImageToTracker, ImageLandmark3Added, ReportInvalidRequest); igstkAddTransitionMacro( TrackerLandmark1Added, GetTransformFromTrackerToImage, TrackerLandmark1Added, ReportInvalidRequest); igstkAddTransitionMacro( TrackerLandmark1Added, GetTransformFromImageToTracker, TrackerLandmark1Added, ReportInvalidRequest); igstkAddTransitionMacro( TrackerLandmark2Added, GetTransformFromTrackerToImage, TrackerLandmark2Added, ReportInvalidRequest); igstkAddTransitionMacro( TrackerLandmark2Added, GetTransformFromImageToTracker, TrackerLandmark2Added, ReportInvalidRequest); igstkAddTransitionMacro( TrackerLandmark3Added, GetTransformFromTrackerToImage, TrackerLandmark3Added, ReportInvalidRequest); igstkAddTransitionMacro( TrackerLandmark3Added, GetTransformFromImageToTracker, TrackerLandmark3Added, ReportInvalidRequest); igstkAddTransitionMacro( Idle, GetRMSError, Idle, ReportInvalidRequest ); igstkAddTransitionMacro( ImageLandmark1Added, GetRMSError, ImageLandmark1Added, ReportInvalidRequest ); igstkAddTransitionMacro( ImageLandmark2Added, GetRMSError, ImageLandmark2Added, ReportInvalidRequest); igstkAddTransitionMacro( ImageLandmark3Added, GetRMSError, ImageLandmark3Added, ReportInvalidRequest); igstkAddTransitionMacro( TrackerLandmark1Added, GetRMSError, TrackerLandmark1Added, ReportInvalidRequest); igstkAddTransitionMacro( TrackerLandmark2Added, GetRMSError, TrackerLandmark2Added, ReportInvalidRequest); igstkAddTransitionMacro( TrackerLandmark3Added, GetRMSError, TrackerLandmark3Added, ReportInvalidRequest); igstkAddTransitionMacro( TransformComputed, ImageLandmark, TransformComputed, ReportInvalidRequest); igstkAddTransitionMacro( TransformComputed, TrackerLandmark, TransformComputed, ReportInvalidRequest); //Add transitions for registration reset state input igstkAddTransitionMacro( TransformComputed, ResetRegistration, Idle, ResetRegistration); igstkAddTransitionMacro( ImageLandmark1Added, ResetRegistration, Idle, ResetRegistration); igstkAddTransitionMacro( ImageLandmark2Added, ResetRegistration, Idle, ResetRegistration); igstkAddTransitionMacro( ImageLandmark3Added, ResetRegistration, Idle, ResetRegistration); igstkAddTransitionMacro( TrackerLandmark1Added, ResetRegistration, Idle, ResetRegistration); igstkAddTransitionMacro( TrackerLandmark2Added, ResetRegistration, Idle, ResetRegistration); igstkAddTransitionMacro( TrackerLandmark3Added, ResetRegistration, Idle, ResetRegistration); igstkAddTransitionMacro( AttemptingToComputeTransform, ResetRegistration, Idle, ResetRegistration); // Select the initial state of the state machine igstkSetInitialStateMacro( Idle ); // Finish the programming and get ready to run m_StateMachine.SetReadyToRun(); m_Transform = TransformType::New(); m_TransformInitializer = TransformInitializerType::New(); // Initialize the RMS error m_RMSError = 0.0; // Initialize collinearity tolerance m_CollinearityTolerance = 0.0001; // Initialize the coordinate systems of the Tracker and the Image // This should later be replaced with the actual coordinate systems // of the Tracker and Image points that are received. m_TrackerCoordinateSystem = CoordinateSystem::New(); m_ImageCoordinateSystem = CoordinateSystem::New(); } /** Destructor */ Landmark3DRegistration::~Landmark3DRegistration() { } /* The "AddImageLandmark" method adds landmark points to the image * landmark point container */ void Landmark3DRegistration::AddImageLandmarkPointProcessing() { igstkLogMacro( DEBUG, "igstk::Landmark3DRegistration::" "AddImageLandmarkPointProcessing called...\n"); m_ImageLandmarks.push_back(m_ImageLandmarkPoint); } /* The "AddTrackerLandmark" method adds landmark points to the * tracker landmark point container */ void Landmark3DRegistration::AddTrackerLandmarkPointProcessing() { igstkLogMacro( DEBUG, "igstk::Landmark3DRegistration::" "AddTrackerLandmarkPointProcessing called...\n"); m_TrackerLandmarks.push_back(m_TrackerLandmarkPoint); } /* The "ResetRegsitration" method empties the landmark point containers to start the process again */ void Landmark3DRegistration::ResetRegistrationProcessing() { igstkLogMacro( DEBUG, "igstk::Landmark3DRegistration::" "ResetRegistrationProcessing called...\n"); //Empty the image and tracker landmark containers while( m_ImageLandmarks.size() > 0 ) { m_ImageLandmarks.pop_back(); } while( m_TrackerLandmarks.size() > 0 ) { m_TrackerLandmarks.pop_back(); } //Reset the transform TransformType::ParametersType parameters ( m_Transform->GetNumberOfParameters() ); parameters[0] = 0.0; parameters[1] = 0.0; parameters[2] = 1.0; parameters[3] = 0.0; parameters[4] = 0.0; parameters[5] = 0.0; m_Transform->SetParameters( parameters ); } /* The "CheckCollinearity" method checks whether the landmark points * are collinear or not */ bool Landmark3DRegistration::CheckCollinearity() { typedef itk::Matrix<double,3,3> MatrixType; typedef itk::Vector<double,3> VectorType; MatrixType covarianceMatrix; PointsContainerConstIterator pointItr; VectorType landmarkVector; VectorType landmarkCentered; VectorType landmarkCentroid; landmarkVector.Fill(0.0); pointItr = m_ImageLandmarks.begin(); while( pointItr != m_ImageLandmarks.end() ) { landmarkVector[0] += (*pointItr)[0]; landmarkVector[1] += (*pointItr)[1]; landmarkVector[2] += (*pointItr)[2]; ++pointItr; } for(unsigned int ic=0; ic<3; ic++) { landmarkCentroid[ic] = landmarkVector[ic] / this->m_ImageLandmarks.size(); } pointItr = m_ImageLandmarks.begin(); while( pointItr != m_ImageLandmarks.end() ) { for(unsigned int i=0; i<3; i++) { landmarkCentered[i] = (*pointItr)[i] - landmarkCentroid[i]; } for(unsigned int i=0; i<3; i++) { for(unsigned int j=0; j<3; j++) { covarianceMatrix[i][j] += landmarkCentered[i] * landmarkCentered[j]; } } ++pointItr; } MatrixType eigenVectors; VectorType eigenValues; typedef itk::SymmetricEigenAnalysis< MatrixType, VectorType, MatrixType > SymmetricEigenAnalysisType; SymmetricEigenAnalysisType symmetricEigenSystem(3); symmetricEigenSystem.SetOrderEigenMagnitudes( true ); symmetricEigenSystem.ComputeEigenValuesAndVectors ( covarianceMatrix, eigenValues, eigenVectors ); double ratio; ratio = ( vnl_math_sqr ( eigenValues[0]) + vnl_math_sqr ( eigenValues[1]))/ ( vnl_math_sqr ( eigenValues[2])); if ( ratio > m_CollinearityTolerance ) { return false; } else { return true; } } /* The "ComputeTransform" method calculates the rigid body transformation parameters */ void Landmark3DRegistration:: ComputeTransformProcessing() { igstkLogMacro( DEBUG, "igstk::Landmark3DRegistration::" "ComputeTransformProcessing called...\n"); m_TransformInitializer->SetFixedLandmarks(m_TrackerLandmarks); m_TransformInitializer->SetMovingLandmarks(m_ImageLandmarks); m_TransformInitializer->SetTransform( m_Transform ); bool failure = false; // check for collinearity failure = CheckCollinearity(); if ( ! failure ) { try { m_TransformInitializer->InitializeTransform(); } catch ( itk::ExceptionObject & excp ) { igstkLogMacro( DEBUG, "igstk::Landmark3DRegistration::" "Transform computation exception" << excp.GetDescription()); failure = true; } } if( failure ) { igstkLogMacro( DEBUG, "ComputationFailureInput getting pushed" ); igstkPushInputMacro( TransformComputationFailure ); } else { //Compute RMS error it the transform computation is successful this->ComputeRMSError(); igstkLogMacro( DEBUG, "ComputationSuccessInput getting pushed" ); igstkPushInputMacro( TransformComputationSuccess ); } this->m_StateMachine.ProcessInputs(); } /** The "ComputeRMSError" method computes the RMS error of the registration */ void Landmark3DRegistration::ComputeRMSError() { igstkLogMacro( DEBUG, "igstk::Landmark3DRegistration::" "ComputeRMSError called..\n"); //Check if the transformation parameters were evaluated correctly PointsContainerConstIterator mitr = m_TrackerLandmarks.begin(); PointsContainerConstIterator fitr = m_ImageLandmarks.begin(); TransformType::OutputVectorType errortr; TransformType::OutputVectorType::RealValueType sum; sum = itk::NumericTraits< TransformType::OutputVectorType::RealValueType > ::ZeroValue(); int counter = itk::NumericTraits< int >::ZeroValue(); while( mitr != m_TrackerLandmarks.end() ) { errortr = *fitr - m_Transform->TransformPoint( *mitr ); sum = sum + errortr.GetSquaredNorm(); ++mitr; ++fitr; counter++; } m_RMSError = sqrt( sum / counter ); } /** The "GetTransformFromTrackerToImage()" method throws and event * containing the transform from tracker to image. */ void Landmark3DRegistration::GetTransformFromTrackerToImageProcessing() { igstkLogMacro( DEBUG, "igstk::Landmark3DRegistration::\ GetTransformFromTrackerToImageProcessing called...\n" ); igstk::Transform transform; const igstk::Transform::ErrorType error = m_RMSError; const igstk::Transform::TimePeriodType timePeriod = itk::NumericTraits<double>::max(); typedef TransformType::TranslationType TranslationType; typedef TransformType::VersorType VersorType; VersorType versor = m_Transform->GetVersor(); TranslationType translation = m_Transform->GetOffset(); transform.SetTranslationAndRotation( translation, versor, error, timePeriod ); CoordinateSystemTransformToResult transformCarrier; transformCarrier.Initialize( transform, m_TrackerCoordinateSystem, m_ImageCoordinateSystem ); CoordinateSystemTransformToEvent transformEvent; transformEvent.Set( transformCarrier ); this->InvokeEvent( transformEvent ); } /** The "GetTransformFromImageToTrackerProcessing()" method throws and event * containing the transform from image to tracker */ void Landmark3DRegistration::GetTransformFromImageToTrackerProcessing() { igstkLogMacro( DEBUG, "igstk::Landmark3DRegistration::" "GetTransformFromImageToTrackerProcessing called...\n" ); igstk::Transform transform; const igstk::Transform::ErrorType error = m_RMSError; const igstk::Transform::TimePeriodType timePeriod = itk::NumericTraits<double>::max(); typedef TransformType::TranslationType TranslationType; typedef TransformType::VersorType VersorType; VersorType versor = m_Transform->GetVersor(); TranslationType translation = m_Transform->GetOffset(); transform.SetTranslationAndRotation( translation, versor, error, timePeriod ); CoordinateSystemTransformToResult transformCarrier; transformCarrier.Initialize( transform.GetInverse(), m_ImageCoordinateSystem, m_TrackerCoordinateSystem ); CoordinateSystemTransformToEvent transformEvent; transformEvent.Set( transformCarrier ); this->InvokeEvent( transformEvent ); } /** The "GetRMSError()" method throws and event containing the RMS error */ void Landmark3DRegistration::GetRMSErrorProcessing() { igstkLogMacro( DEBUG, "igstk::Landmark3DRegistration::\ GetRMSErrorProcessing called...\n" ); DoubleTypeEvent event; EventHelperType::DoubleType error; error = m_RMSError; event.Set( error ); this->InvokeEvent( event ); } /* The ReportInvalidRequest function reports invalid requests */ void Landmark3DRegistration::ReportInvalidRequestProcessing() { igstkLogMacro( DEBUG, "igstk::Landmark3DRegistration::" "ReportInvalidRequestProcessing called...\n"); this->InvokeEvent(InvalidRequestErrorEvent()); } /* The ReportSuccessInTransformComputation function reports success in transform calculation */ void Landmark3DRegistration::ReportSuccessInTransformComputationProcessing() { igstkLogMacro( DEBUG, "igstk::Landmark3DRegistration::" "ReportSuccessInTransformComputationProcessing called...\n"); this->InvokeEvent( TransformComputationSuccessEvent() ); } /* The ReportFailureInTransformComputationProcessing function reports failure in transform calculation */ void Landmark3DRegistration::ReportFailureInTransformComputationProcessing() { igstkLogMacro( DEBUG, "igstk::Landmark3DRegistration::" "ReportFailureInTransformComputationProcessing called...\n"); this->InvokeEvent( TransformComputationFailureEvent() ); } void Landmark3DRegistration::RequestAddImageLandmarkPoint( const LandmarkImagePointType & pt) { igstkLogMacro( DEBUG, "igstk::Landmark3DRegistration::" "RequestAddImageLandmarkPoint called...\n"); this->m_ImageLandmarkPoint = pt; igstkPushInputMacro( ImageLandmark ); this->m_StateMachine.ProcessInputs(); } void Landmark3DRegistration::RequestAddTrackerLandmarkPoint( const LandmarkImagePointType & pt) { igstkLogMacro( DEBUG, "igstk::Landmark3DRegistration::" "RequestAddTrackerLandmarkPoint called...\n"); this->m_TrackerLandmarkPoint = pt; igstkPushInputMacro( TrackerLandmark ); this->m_StateMachine.ProcessInputs(); } void Landmark3DRegistration::RequestResetRegistration() { igstkLogMacro( DEBUG, "igstk::Landmark3DRegistration::" "RequestResetRegistration called...\n"); igstkPushInputMacro( ResetRegistration ); this->m_StateMachine.ProcessInputs(); } void Landmark3DRegistration::RequestSetCollinearityTolerance( const double & tolerance) { igstkLogMacro( DEBUG, "igstk::Landmark3DRegistration::" "RequestSetCollinearityTolerance called...\n"); this->m_CollinearityTolerance = tolerance; this->m_StateMachine.ProcessInputs(); } void Landmark3DRegistration::RequestComputeTransform() { igstkLogMacro( DEBUG, "igstk::Landmark3DRegistration::" "RequestComputeTransform called...\n"); igstkPushInputMacro( ComputeTransform ); this->m_StateMachine.ProcessInputs(); } void Landmark3DRegistration::RequestGetTransformFromTrackerToImage() { igstkLogMacro( DEBUG, "igstk::Landmark3DRegistration::RequestGetTransformFromTrackerToImage" " called...\n" ); igstkPushInputMacro( GetTransformFromTrackerToImage ); this->m_StateMachine.ProcessInputs(); } void Landmark3DRegistration::RequestGetTransformFromImageToTracker() { igstkLogMacro( DEBUG, "igstk::Landmark3DRegistration::RequestGetTransformFromImageToTracker" " called...\n" ); igstkPushInputMacro( GetTransformFromImageToTracker ); this->m_StateMachine.ProcessInputs(); } void Landmark3DRegistration::RequestGetRMSError() { igstkLogMacro( DEBUG, "igstk::Landmark3DRegistration::RequestGetRMSError called...\n" ); igstkPushInputMacro( GetRMSError ); this->m_StateMachine.ProcessInputs(); } /** Print Self function */ void Landmark3DRegistration::PrintSelf( std::ostream& os, itk::Indent indent ) const { Superclass::PrintSelf(os, indent); os << indent << "Tracker Landmarks: " << std::endl; PointsContainerConstIterator fitr = m_TrackerLandmarks.begin(); while( fitr != m_TrackerLandmarks.end() ) { os << indent << *fitr << std::endl; ++fitr; } os << indent << "Image Landmarks: " << std::endl; PointsContainerConstIterator mitr = m_ImageLandmarks.begin(); while( mitr != m_ImageLandmarks.end() ) { os << indent << *mitr << std::endl; ++mitr; } } } // end namespace igstk
33.29602
80
0.617333
ipa
c679657a86fa3389305f5f1ea740f415f78da72e
2,436
cpp
C++
dev/Basic/shared/database/DB_Config.cpp
gusugusu1018/simmobility-prod
d30a5ba353673f8fd35f4868c26994a0206a40b6
[ "MIT" ]
50
2018-12-21T08:21:38.000Z
2022-01-24T09:47:59.000Z
dev/Basic/shared/database/DB_Config.cpp
gusugusu1018/simmobility-prod
d30a5ba353673f8fd35f4868c26994a0206a40b6
[ "MIT" ]
2
2018-12-19T13:42:47.000Z
2019-05-13T04:11:45.000Z
dev/Basic/shared/database/DB_Config.cpp
gusugusu1018/simmobility-prod
d30a5ba353673f8fd35f4868c26994a0206a40b6
[ "MIT" ]
27
2018-11-28T07:30:34.000Z
2022-02-05T02:22:26.000Z
/* * Copyright Singapore-MIT Alliance for Research and Technology * * File: DatabaseConfig.cpp * Author: Pedro Gandola <pedrogandola@smart.mit.edu> * * Created on October 11, 2013, 11:26 AM */ #include "DB_Config.hpp" #include "entities/profile/ProfileBuilder.hpp" using namespace sim_mob; using namespace sim_mob::db; using std::string; namespace { const string SECTION = "database"; const string PROP_HOST = "host"; const string PROP_PASS = "password"; const string PROP_USER = "username"; const string PROP_DB = "dbname"; const string PROP_PORT = "port"; } DB_Config::DB_Config(const string& file) : PropertyLoader(file, "database"), port(0), host(""), password(""), username(""), databaseName("") { } DB_Config::DB_Config(const DB_Config& orig) : PropertyLoader(orig) { host = orig.host; port = orig.port; username = orig.username; password = orig.password; databaseName = orig.databaseName; } DB_Config::DB_Config(std::string& host, std::string& port, std::string& dbname, std::string& username, std::string& password) : PropertyLoader(), port(std::atoi(port.c_str())), host(host), databaseName(dbname), username(username), password(password) { } DB_Config::~DB_Config() { } const string& DB_Config::getDatabaseName() const { return databaseName; } const string& DB_Config::getPassword() const { return password; } const string& DB_Config::getUsername() const { return username; } const string& DB_Config::getHost() const { return host; } unsigned int DB_Config::getPort() const { return port; } void DB_Config::setDatabaseName(const string& databaseName) { this->databaseName = databaseName; } void DB_Config::setPassword(const string& password) { this->password = password; } void DB_Config::setUsername(const string& username) { this->username = username; } void DB_Config::setPort(unsigned int port) { this->port = port; } void DB_Config::setHost(const string& host) { this->host = host; } void DB_Config::loadImpl(const boost::property_tree::ptree& tree) { host = tree.get<string>(toProp(getSection(), PROP_HOST)); this->port = tree.get<unsigned int>(toProp(getSection(), PROP_PORT)); this->username = tree.get<string>(toProp(getSection(), PROP_USER)); this->password = tree.get<string>(toProp(getSection(), PROP_PASS)); this->databaseName = tree.get<string>(toProp(getSection(), PROP_DB)); }
22.555556
129
0.700328
gusugusu1018
c67a69c925222045dc8c9466a3d985194826c68d
8,394
cpp
C++
racermate/cpp_tester_save/trainer.cpp
SRAM/RacerMateDLL
a980e43919ae6c749561071cc135d5af221eb6c2
[ "MIT" ]
3
2020-10-08T21:30:28.000Z
2021-04-27T00:24:00.000Z
racermate/cpp_tester_save/trainer.cpp
SRAM/RacerMateDLL
a980e43919ae6c749561071cc135d5af221eb6c2
[ "MIT" ]
null
null
null
racermate/cpp_tester_save/trainer.cpp
SRAM/RacerMateDLL
a980e43919ae6c749561071cc135d5af221eb6c2
[ "MIT" ]
null
null
null
#include <stdlib.h> #include <assert.h> #include <glib_defines.h> #include <fatalerror.h> #include <dll_globals.h> #include <errors.h> #include "trainer.h" int Trainer::Chainrings[MAX_FRONT_GEARS] = { 28, 39, 56, 0, 0 }; // up to 5 front gears int Trainer::cogset[MAX_REAR_GEARS] = { 11, 12, 13, 14, 15, 16, 17, 19, 21, 23, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; // up to 20 rear gears /**************************************************************************** ****************************************************************************/ Trainer::Trainer(void) { what = DEVICE_NOT_SCANNED; ix = "zzz"; iport = -1; memset(portname, 0, sizeof(portname)); memset(keystr, 0, sizeof(keystr)); comtype = BAD_INPUT_TYPE; fw = 0; cal = 0; keys = 0x40; watts = 0.0f; rpm = 0.0f; hr = 0.0f; mph = 0.0f; slope = 0; // %grade * 100 fix = 0; // index of velotron front gear (0-2) rix = 0; // index of velotron rear gear (0-9) maxfix = -1; // highest non-zero index for front gear maxrix = -1; // highest non-zero index for rear gear bars = NULL; average_bars = NULL; bike_kgs = (float)(TOKGS*20.0f); // weight of bike in kgs wheeldiameter = 700.0f; // in mm, 27.0 inches ActualChainring = 62; // physical number of teeth on velotron front gear Actualcog = 14; // physical number of teeth on velotron rear gear person_kgs = (float)(TOKGS*150.0f); drag_factor = 100; manwatts = 100; // integer calmode = false; memset(gteststring, 0, sizeof(gteststring)); broadcast_port = -1; listen_port = -1; wind = 0.0f; // float, kph draft_wind = 0.0f; // float, kph /* iwind_kph = 0; idraft_wind_kph = 0; iwind_mph = 0; idraft_wind_mph = 0; wind_kph = 0.0f; draft_wind_kph = 0.0f; wind_mph = 0.0f; draft_wind_mph = 0.0f; */ bp = 0; return; } // constructor /**************************************************************************** ****************************************************************************/ int Trainer::init(const char * _ix, int _broadcast_port, int _listen_port) { ix = _ix; broadcast_port = _broadcast_port; listen_port = _listen_port; const char *cptr; int status; bool b; //iport = ix + 1; iport = 1; #ifdef WIN32 sprintf(portname, "COM%d", iport); #elif defined __MACH__ #else #endif if (iport>=CLIENT_SERIAL_PORT_BASE && iport <= CLIENT_SERIAL_PORT_BASE+16) { // trainer is server comtype = TRAINER_IS_SERVER; // trainer is a server } else if (iport>=SERVER_SERIAL_PORT_BASE && iport <= SERVER_SERIAL_PORT_BASE+16) { // trainer is client comtype = TRAINER_IS_CLIENT; // trainer is client } else if (iport >= UDP_SERVER_SERIAL_PORT_BASE && iport <= UDP_SERVER_SERIAL_PORT_BASE + 16) { // trainer is UDP client comtype = TRAINER_IS_CLIENT; // trainer is client } else { comtype = WIN_RS232; } if (comtype==TRAINER_IS_CLIENT) { // trainer is a client int debug_level = 2; status = set_network_parameters( broadcast_port, // 9071 listen_port, // 9099 false, // ip_discover true, // udp flag ix, debug_level ); assert(status==ALL_OK); } bp = 17; what = GetRacerMateDeviceID(ix); if (what == DEVICE_COMPUTRAINER) { printf("found computrainer on port %s\r\n", portname); } else if (what == DEVICE_VELOTRON) { printf("found velotron on port %s\n", portname); } else if (what == DEVICE_EXISTS) { sprintf(gteststring, "don't see trainer on port %s\r\n", portname); throw(fatalError(__FILE__, __LINE__, gteststring)); } else { sprintf(gteststring, "no trainer on port %s", portname); throw(fatalError(__FILE__, __LINE__, gteststring)); } if (what==DEVICE_COMPUTRAINER || what==DEVICE_VELOTRON) { fw = GetFirmWareVersion(ix); if (comtype==TRAINER_IS_CLIENT) { // trainer is a client assert(fw==4543); } else { assert(fw==4095); } if (FAILED(fw)) { cptr = get_errstr(fw); sprintf(gteststring, "%s", cptr); throw(fatalError(__FILE__, __LINE__, gteststring)); } if (what==DEVICE_VELOTRON) { if (fw != 190) { sprintf(gteststring, "unknown firmware version ( %d )", fw); throw(fatalError(__FILE__, __LINE__, gteststring)); } } printf("firmware = %d\r\n", fw); } b = GetIsCalibrated(ix, fw); // false printf("calibrated = %s\r\n", b?"true":"false"); if (what==DEVICE_COMPUTRAINER || what==DEVICE_VELOTRON) { cal = GetCalibration(ix); // 200 printf("cal = %d\r\n", cal); status = set_ftp(ix, fw, 1.0f); if (status!=DEVICE_NOT_RUNNING) { cptr = get_errstr(status); throw(fatalError(__FILE__, __LINE__, cptr)); } printf("ftp set\r\n"); if (what==DEVICE_VELOTRON) { maxfix = -1; for(int i=0; i<MAX_FRONT_GEARS; i++) { if (Chainrings[i]==0) { break; } maxfix++; } maxrix = -1; for(int i=0; i<MAX_REAR_GEARS; i++) { if (cogset[i]==0) { break; } maxrix++; } bp = 1; fix = maxfix; // whatever you want the default gears to be rix = 0; // whatever you want the default gears to be status = SetVelotronParameters( ix, fw, maxfix+1, maxrix+1, Chainrings, cogset, wheeldiameter, // mm ActualChainring, Actualcog, bike_kgs, //person_kgs, fix, // 2, start off in gear 56/11 rix // 9, start off in gear 56/11 ); // <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< if (status!=ALL_OK) { cptr = get_errstr(status); throw(fatalError(__FILE__, __LINE__, cptr)); } printf("velotron parameters set\r\n"); status = setGear(ix, fw, fix, rix); // go in to starting gear if (status!=ALL_OK) { cptr = get_errstr(status); throw(fatalError(__FILE__, __LINE__, cptr)); } } // if (what==DEVICE_VELOTRON) { } // if (what==DEVICE_COMPUTRAINER || what==DEVICE_VELOTRON) { status = startTrainer(ix); // start trainer <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< if (status!=ALL_OK && status != DEVICE_ALREADY_RUNNING) { cptr = get_errstr(status); racermate_close(); throw(fatalError(__FILE__, __LINE__, cptr)); } if (what==DEVICE_COMPUTRAINER) { printf("computrainer started\r\n"); } else { printf("velotron started\r\n"); } if (what==DEVICE_COMPUTRAINER || what==DEVICE_VELOTRON) { status = resetTrainer(ix, fw, cal); // resets ds, decoder, etc if (status!=ALL_OK) { cptr = get_errstr(status); throw(fatalError(__FILE__, __LINE__, cptr)); } printf("trainer reset\r\n"); } status = ResetAverages(ix, fw); if (status!=ALL_OK) { cptr = get_errstr(status); throw(fatalError(__FILE__, __LINE__, cptr)); } printf("averages reset\r\n"); slope = 100; // set slope to 1% status = SetSlope(ix, fw, cal, bike_kgs, person_kgs, drag_factor, slope/100.0f); // sets windload mode if (status!=ALL_OK) { cptr = get_errstr(status); throw(fatalError(__FILE__, __LINE__, cptr)); } printf("wind load mode set\r\n"); status = setPause(ix, true); if (status!=ALL_OK) { cptr = get_errstr(status); throw(fatalError(__FILE__, __LINE__, cptr)); } printf("paused\r\n"); Sleep(500); status = setPause(ix, false); if (status!=ALL_OK) { cptr = get_errstr(status); throw(fatalError(__FILE__, __LINE__, cptr)); } printf("unpaused\r\n"); float wind_mph = 10.0f; // in mph status = set_wind(ix, fw, (float)(TOKPH*wind_mph)); if (status!=ALL_OK) { cptr = get_errstr(status); throw(fatalError(__FILE__, __LINE__, cptr)); } status = SetHRBeepBounds(ix, fw, 39, 139, true); if (status!=ALL_OK) { cptr = get_errstr(status); throw(fatalError(__FILE__, __LINE__, cptr)); } keys = GetHandleBarButtons(ix, fw); // keys should be accumulated keys pressed since last call if (keys==BAD_FIRMWARE_VERSION) { cptr = get_errstr(keys); throw(fatalError(__FILE__, __LINE__, cptr)); } return 0; }
26.479495
137
0.566476
SRAM
c690da46c5286e03571a740c0c5831a7dd3d8697
11,222
cpp
C++
src/uml/src_gen/uml/impl/TypeImpl.cpp
MichaelBranz/MDE4CPP
5b918850a37e9cee54f6c3b92f381b0458451724
[ "MIT" ]
null
null
null
src/uml/src_gen/uml/impl/TypeImpl.cpp
MichaelBranz/MDE4CPP
5b918850a37e9cee54f6c3b92f381b0458451724
[ "MIT" ]
1
2019-03-01T00:54:13.000Z
2019-03-04T02:15:50.000Z
src/uml/src_gen/uml/impl/TypeImpl.cpp
vallesch/MDE4CPP
7f8a01dd6642820913b2214d255bef2ea76be309
[ "MIT" ]
null
null
null
#include "uml/impl/TypeImpl.hpp" #ifdef NDEBUG #define DEBUG_MESSAGE(a) /**/ #else #define DEBUG_MESSAGE(a) a #endif #ifdef ACTIVITY_DEBUG_ON #define ACT_DEBUG(a) a #else #define ACT_DEBUG(a) /**/ #endif //#include "util/ProfileCallCount.hpp" #include <cassert> #include <iostream> #include <sstream> #include "abstractDataTypes/Bag.hpp" #include "abstractDataTypes/Subset.hpp" #include "abstractDataTypes/SubsetUnion.hpp" #include "abstractDataTypes/Union.hpp" #include "abstractDataTypes/SubsetUnion.hpp" #include "ecore/EAnnotation.hpp" #include "ecore/EClass.hpp" #include "uml/impl/UmlPackageImpl.hpp" //Forward declaration includes #include "persistence/interfaces/XLoadHandler.hpp" // used for Persistence #include "persistence/interfaces/XSaveHandler.hpp" // used for Persistence #include "uml/UmlFactory.hpp" #include "uml/UmlPackage.hpp" #include <exception> // used in Persistence #include "uml/Association.hpp" #include "uml/Comment.hpp" #include "uml/Dependency.hpp" #include "ecore/EAnnotation.hpp" #include "uml/Element.hpp" #include "uml/Namespace.hpp" #include "uml/Package.hpp" #include "uml/PackageableElement.hpp" #include "uml/StringExpression.hpp" #include "uml/TemplateParameter.hpp" #include "uml/Type.hpp" #include "ecore/EcorePackage.hpp" #include "ecore/EcoreFactory.hpp" #include "uml/UmlPackage.hpp" #include "uml/UmlFactory.hpp" #include "ecore/EAttribute.hpp" #include "ecore/EStructuralFeature.hpp" using namespace uml; //********************************* // Constructor / Destructor //********************************* TypeImpl::TypeImpl() { //********************************* // Attribute Members //********************************* //********************************* // Reference Members //********************************* //References //Init references } TypeImpl::~TypeImpl() { #ifdef SHOW_DELETION std::cout << "-------------------------------------------------------------------------------------------------\r\ndelete Type "<< this << "\r\n------------------------------------------------------------------------ " << std::endl; #endif } //Additional constructor for the containments back reference TypeImpl::TypeImpl(std::weak_ptr<uml::Namespace > par_namespace) :TypeImpl() { m_namespace = par_namespace; m_owner = par_namespace; } //Additional constructor for the containments back reference TypeImpl::TypeImpl(std::weak_ptr<uml::Element > par_owner) :TypeImpl() { m_owner = par_owner; } //Additional constructor for the containments back reference TypeImpl::TypeImpl(std::weak_ptr<uml::Package > par_Package, const int reference_id) :TypeImpl() { switch(reference_id) { case UmlPackage::PACKAGEABLEELEMENT_EREFERENCE_OWNINGPACKAGE: m_owningPackage = par_Package; m_namespace = par_Package; return; case UmlPackage::TYPE_EREFERENCE_PACKAGE: m_package = par_Package; m_namespace = par_Package; return; default: std::cerr << __PRETTY_FUNCTION__ <<" Reference not found in class with the given ID" << std::endl; } } //Additional constructor for the containments back reference TypeImpl::TypeImpl(std::weak_ptr<uml::TemplateParameter > par_owningTemplateParameter) :TypeImpl() { m_owningTemplateParameter = par_owningTemplateParameter; m_owner = par_owningTemplateParameter; } //Additional constructor for the containments back reference TypeImpl::TypeImpl(const TypeImpl & obj):TypeImpl() { //create copy of all Attributes #ifdef SHOW_COPIES std::cout << "+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\r\ncopy Type "<< this << "\r\n+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ " << std::endl; #endif m_name = obj.getName(); m_qualifiedName = obj.getQualifiedName(); m_visibility = obj.getVisibility(); //copy references with no containment (soft copy) std::shared_ptr<Bag<uml::Dependency>> _clientDependency = obj.getClientDependency(); m_clientDependency.reset(new Bag<uml::Dependency>(*(obj.getClientDependency().get()))); m_namespace = obj.getNamespace(); m_owner = obj.getOwner(); m_owningPackage = obj.getOwningPackage(); m_owningTemplateParameter = obj.getOwningTemplateParameter(); m_package = obj.getPackage(); m_templateParameter = obj.getTemplateParameter(); //Clone references with containment (deep copy) std::shared_ptr<Bag<ecore::EAnnotation>> _eAnnotationsList = obj.getEAnnotations(); for(std::shared_ptr<ecore::EAnnotation> _eAnnotations : *_eAnnotationsList) { this->getEAnnotations()->add(std::shared_ptr<ecore::EAnnotation>(std::dynamic_pointer_cast<ecore::EAnnotation>(_eAnnotations->copy()))); } #ifdef SHOW_SUBSET_UNION std::cout << "Copying the Subset: " << "m_eAnnotations" << std::endl; #endif if(obj.getNameExpression()!=nullptr) { m_nameExpression = std::dynamic_pointer_cast<uml::StringExpression>(obj.getNameExpression()->copy()); } #ifdef SHOW_SUBSET_UNION std::cout << "Copying the Subset: " << "m_nameExpression" << std::endl; #endif std::shared_ptr<Bag<uml::Comment>> _ownedCommentList = obj.getOwnedComment(); for(std::shared_ptr<uml::Comment> _ownedComment : *_ownedCommentList) { this->getOwnedComment()->add(std::shared_ptr<uml::Comment>(std::dynamic_pointer_cast<uml::Comment>(_ownedComment->copy()))); } #ifdef SHOW_SUBSET_UNION std::cout << "Copying the Subset: " << "m_ownedComment" << std::endl; #endif } std::shared_ptr<ecore::EObject> TypeImpl::copy() const { std::shared_ptr<TypeImpl> element(new TypeImpl(*this)); element->setThisTypePtr(element); return element; } std::shared_ptr<ecore::EClass> TypeImpl::eStaticClass() const { return UmlPackageImpl::eInstance()->getType_EClass(); } //********************************* // Attribute Setter Getter //********************************* //********************************* // Operations //********************************* bool TypeImpl::conformsTo(std::shared_ptr<uml::Type> other) { std::cout << __PRETTY_FUNCTION__ << std::endl; throw "UnsupportedOperationException"; } std::shared_ptr<uml::Association> TypeImpl::createAssociation(bool end1IsNavigable,AggregationKind end1Aggregation,std::string end1Name,int end1Lower,int end1Upper,std::shared_ptr<uml::Type> end1Type,bool end2IsNavigable,AggregationKind end2Aggregation,std::string end2Name,int end2Lower,int end2Upper) { std::cout << __PRETTY_FUNCTION__ << std::endl; throw "UnsupportedOperationException"; } std::shared_ptr<Bag<uml::Association> > TypeImpl::getAssociations() { std::cout << __PRETTY_FUNCTION__ << std::endl; throw "UnsupportedOperationException"; } //********************************* // References //********************************* std::weak_ptr<uml::Package > TypeImpl::getPackage() const { return m_package; } void TypeImpl::setPackage(std::shared_ptr<uml::Package> _package) { m_package = _package; } //********************************* // Union Getter //********************************* std::weak_ptr<uml::Namespace > TypeImpl::getNamespace() const { return m_namespace; } std::shared_ptr<Union<uml::Element>> TypeImpl::getOwnedElement() const { return m_ownedElement; } std::weak_ptr<uml::Element > TypeImpl::getOwner() const { return m_owner; } std::shared_ptr<Type> TypeImpl::getThisTypePtr() const { return m_thisTypePtr.lock(); } void TypeImpl::setThisTypePtr(std::weak_ptr<Type> thisTypePtr) { m_thisTypePtr = thisTypePtr; setThisPackageableElementPtr(thisTypePtr); } std::shared_ptr<ecore::EObject> TypeImpl::eContainer() const { if(auto wp = m_namespace.lock()) { return wp; } if(auto wp = m_owner.lock()) { return wp; } if(auto wp = m_owningPackage.lock()) { return wp; } if(auto wp = m_package.lock()) { return wp; } if(auto wp = m_owningTemplateParameter.lock()) { return wp; } return nullptr; } //********************************* // Structural Feature Getter/Setter //********************************* Any TypeImpl::eGet(int featureID, bool resolve, bool coreType) const { switch(featureID) { case UmlPackage::TYPE_EREFERENCE_PACKAGE: return eAny(getPackage()); //2613 } return PackageableElementImpl::eGet(featureID, resolve, coreType); } bool TypeImpl::internalEIsSet(int featureID) const { switch(featureID) { case UmlPackage::TYPE_EREFERENCE_PACKAGE: return getPackage().lock() != nullptr; //2613 } return PackageableElementImpl::internalEIsSet(featureID); } bool TypeImpl::eSet(int featureID, Any newValue) { switch(featureID) { case UmlPackage::TYPE_EREFERENCE_PACKAGE: { // BOOST CAST std::shared_ptr<uml::Package> _package = newValue->get<std::shared_ptr<uml::Package>>(); setPackage(_package); //2613 return true; } } return PackageableElementImpl::eSet(featureID, newValue); } //********************************* // Persistence Functions //********************************* void TypeImpl::load(std::shared_ptr<persistence::interfaces::XLoadHandler> loadHandler) { std::map<std::string, std::string> attr_list = loadHandler->getAttributeList(); loadAttributes(loadHandler, attr_list); // // Create new objects (from references (containment == true)) // // get UmlFactory std::shared_ptr<uml::UmlFactory> modelFactory = uml::UmlFactory::eInstance(); int numNodes = loadHandler->getNumOfChildNodes(); for(int ii = 0; ii < numNodes; ii++) { loadNode(loadHandler->getNextNodeName(), loadHandler, modelFactory); } } void TypeImpl::loadAttributes(std::shared_ptr<persistence::interfaces::XLoadHandler> loadHandler, std::map<std::string, std::string> attr_list) { PackageableElementImpl::loadAttributes(loadHandler, attr_list); } void TypeImpl::loadNode(std::string nodeName, std::shared_ptr<persistence::interfaces::XLoadHandler> loadHandler, std::shared_ptr<uml::UmlFactory> modelFactory) { PackageableElementImpl::loadNode(nodeName, loadHandler, modelFactory); } void TypeImpl::resolveReferences(const int featureID, std::list<std::shared_ptr<ecore::EObject> > references) { switch(featureID) { case UmlPackage::TYPE_EREFERENCE_PACKAGE: { if (references.size() == 1) { // Cast object to correct type std::shared_ptr<uml::Package> _package = std::dynamic_pointer_cast<uml::Package>( references.front() ); setPackage(_package); } return; } } PackageableElementImpl::resolveReferences(featureID, references); } void TypeImpl::save(std::shared_ptr<persistence::interfaces::XSaveHandler> saveHandler) const { saveContent(saveHandler); PackageableElementImpl::saveContent(saveHandler); NamedElementImpl::saveContent(saveHandler); ParameterableElementImpl::saveContent(saveHandler); ElementImpl::saveContent(saveHandler); ecore::EModelElementImpl::saveContent(saveHandler); ObjectImpl::saveContent(saveHandler); ecore::EObjectImpl::saveContent(saveHandler); } void TypeImpl::saveContent(std::shared_ptr<persistence::interfaces::XSaveHandler> saveHandler) const { try { std::shared_ptr<uml::UmlPackage> package = uml::UmlPackage::eInstance(); } catch (std::exception& e) { std::cout << "| ERROR | " << e.what() << std::endl; } }
25.105145
303
0.671894
MichaelBranz
c691771b3d95c6170f28ab814ecfc5b04c35fbad
4,732
cpp
C++
terrain_generator/src/gen/Document.cpp
marek-cel/fightersfs-tools
e692a8af7e44cfae6e35ecfa916d3ffdc46a9eb3
[ "CC0-1.0" ]
null
null
null
terrain_generator/src/gen/Document.cpp
marek-cel/fightersfs-tools
e692a8af7e44cfae6e35ecfa916d3ffdc46a9eb3
[ "CC0-1.0" ]
null
null
null
terrain_generator/src/gen/Document.cpp
marek-cel/fightersfs-tools
e692a8af7e44cfae6e35ecfa916d3ffdc46a9eb3
[ "CC0-1.0" ]
1
2021-02-22T21:22:33.000Z
2021-02-22T21:22:33.000Z
/****************************************************************************//* * Copyright (C) 2020 Marek M. Cel * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom * the Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS * IN THE SOFTWARE. ******************************************************************************/ #include <osgDB/WriteFile> #include <osgUtil/Optimizer> #include <QFileInfo> #include <QTextStream> #include <gen/Document.h> //////////////////////////////////////////////////////////////////////////////// Document::Document() : m_terrain ( 0 ) { newEmpty(); } //////////////////////////////////////////////////////////////////////////////// Document::Document( QString fileName ) : m_terrain ( 0 ) { readFile( fileName ); } //////////////////////////////////////////////////////////////////////////////// Document::~Document() { if ( m_terrain ) delete m_terrain; m_terrain = 0; } //////////////////////////////////////////////////////////////////////////////// void Document::newEmpty() { if ( m_terrain ) delete m_terrain; m_terrain = 0; m_terrain = new Terrain(); } //////////////////////////////////////////////////////////////////////////////// bool Document::exportAs( QString fileName ) { osgUtil::Optimizer optimizer; int options = osgUtil::Optimizer::FLATTEN_STATIC_TRANSFORMS | osgUtil::Optimizer::REMOVE_REDUNDANT_NODES | osgUtil::Optimizer::REMOVE_LOADED_PROXY_NODES | osgUtil::Optimizer::COMBINE_ADJACENT_LODS | osgUtil::Optimizer::SHARE_DUPLICATE_STATE | osgUtil::Optimizer::MERGE_GEOMETRY | osgUtil::Optimizer::MAKE_FAST_GEOMETRY | osgUtil::Optimizer::CHECK_GEOMETRY | osgUtil::Optimizer::OPTIMIZE_TEXTURE_SETTINGS | osgUtil::Optimizer::STATIC_OBJECT_DETECTION; optimizer.optimize( m_terrain->getRoot(), options ); osgDB::writeNodeFile( *( m_terrain->getRoot() ), fileName.toStdString() ); return true; } //////////////////////////////////////////////////////////////////////////////// bool Document::generateElevation( QString fileName ) { return m_terrain->generateElevation( fileName ); } //////////////////////////////////////////////////////////////////////////////// bool Document::readFile( QString fileName ) { newEmpty(); QFile devFile( fileName ); if ( devFile.open( QFile::ReadOnly | QFile::Text ) ) { QDomDocument doc; doc.setContent( &devFile, false ); QDomElement rootNode = doc.documentElement(); if ( rootNode.tagName() == "terrain" ) { if ( m_terrain ) delete m_terrain; m_terrain = 0; m_terrain = new Terrain( &rootNode ); return true; } devFile.close(); } return false; } //////////////////////////////////////////////////////////////////////////////// bool Document::saveFile( QString fileName ) { QString fileTemp = fileName; if ( QFileInfo( fileTemp ).suffix() != QString( "xml" ) ) { fileTemp += ".xml"; } QFile devFile( fileTemp ); if ( devFile.open( QFile::WriteOnly | QFile::Truncate | QFile::Text ) ) { QTextStream out; out.setDevice( &devFile ); out.setCodec("UTF-8"); out << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"; QDomDocument doc( "terrain" ); doc.setContent( &devFile, false ); QDomElement dataNode = doc.createElement( "terrain" ); doc.appendChild( dataNode ); m_terrain->save( &doc, &dataNode ); out << doc.toString(); devFile.close(); return true; } return false; }
28.506024
80
0.531488
marek-cel
c691d6ee70928d2af3c4fda40cc2abc5dbe0c2bd
402
cpp
C++
Codebreaker/problems/prefixsums/prefixsums.cpp
object-oriented-human/competitive
9e761020e887d8980a39a64eeaeaa39af0ecd777
[ "MIT" ]
2
2021-07-27T10:46:47.000Z
2021-07-27T10:47:57.000Z
Codebreaker/problems/prefixsums/prefixsums.cpp
foooop/competitive
9e761020e887d8980a39a64eeaeaa39af0ecd777
[ "MIT" ]
null
null
null
Codebreaker/problems/prefixsums/prefixsums.cpp
foooop/competitive
9e761020e887d8980a39a64eeaeaa39af0ecd777
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; int main() { ios::sync_with_stdio(false); cin.tie(0); cout.tie(0); int n, q, l, r; cin >> n >> q; long long arr[n], pre[n+1]; pre[0] = 0; for (int i = 0; i < n; i++) { cin >> arr[i]; pre[i+1] = pre[i] + arr[i]; } while (q--) { cin >> l >> r; cout << pre[r] - pre[l-1] << "\n"; } }
18.272727
42
0.41791
object-oriented-human
c694695e87e0bdedb9160fde71e98921f56e853f
1,917
hpp
C++
src_code/AdvancedQt/timelog1/richtextlineedit.hpp
yanrong/book_demo
20cd13f3c3507a11e826ebbf22bd1c7bcb36e06f
[ "Apache-2.0" ]
null
null
null
src_code/AdvancedQt/timelog1/richtextlineedit.hpp
yanrong/book_demo
20cd13f3c3507a11e826ebbf22bd1c7bcb36e06f
[ "Apache-2.0" ]
null
null
null
src_code/AdvancedQt/timelog1/richtextlineedit.hpp
yanrong/book_demo
20cd13f3c3507a11e826ebbf22bd1c7bcb36e06f
[ "Apache-2.0" ]
null
null
null
#ifndef RICHTEXTLINEEDIT_HPP #define RICHTEXTLINEEDIT_HPP /* Copyright (c) 2009-10 Qtrac Ltd. All rights reserved. This program or module is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. It is provided for educational purposes and is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. */ #include <QTextEdit> class QAction; class QKeyEvent; class RichTextLineEdit : public QTextEdit { Q_OBJECT public: explicit RichTextLineEdit(QWidget *parent=0); QString toSimpleHtml() const; QSize sizeHint() const; QSize minimumSizeHint() const; public slots: void toggleItalic() { setFontItalic(!fontItalic()); } void toggleBold() { setFontWeight(fontWeight() > QFont::Normal ? QFont::Normal : QFont::Bold); } signals: void returnPressed(); protected: void keyPressEvent(QKeyEvent *event); private slots: void customContextMenuRequested(const QPoint &pos); void applyTextEffect(); void applyColor(QAction *action); private: enum Style {Bold, Italic, StrikeOut, NoSuperOrSubscript, Subscript, Superscript}; void createShortcuts(); void createActions(); QAction *createAction(const QString &text, const QVariant &data); QMenu *createColorMenu(); void updateContextMenuActions(); QAction *boldAction; QAction *italicAction; QAction *strikeOutAction; QAction *noSubOrSuperScriptAction; QAction *superScriptAction; QAction *subScriptAction; QAction *colorAction; }; #endif // RICHTEXTLINEEDIT_HPP
27
72
0.718832
yanrong
c696f7511726ba3926ab439ccffe30451927f2ee
265
cpp
C++
codeforce1/68A. Irrational problem.cpp
khaled-farouk/My_problem_solving_solutions
46ed6481fc9b424d0714bc717cd0ba050a6638ef
[ "MIT" ]
null
null
null
codeforce1/68A. Irrational problem.cpp
khaled-farouk/My_problem_solving_solutions
46ed6481fc9b424d0714bc717cd0ba050a6638ef
[ "MIT" ]
null
null
null
codeforce1/68A. Irrational problem.cpp
khaled-farouk/My_problem_solving_solutions
46ed6481fc9b424d0714bc717cd0ba050a6638ef
[ "MIT" ]
null
null
null
#include <stdio.h> using namespace std; int main() { int p1, p2, p3, p4, a, b, res = 0; scanf("%d %d %d %d %d %d", &p1, &p2, &p3, &p4, &a, &b); for(int i = a; i <= b; ++i) if(i == (((i % p1) % p2) % p3) % p4) ++res; printf("%d\n", res); return 0; }
17.666667
56
0.449057
khaled-farouk
c6978ccc95c5107ae3b593a395d45c7448526eca
7,899
cpp
C++
Examples/Tutorial1.cpp
haskellstudio/belle_old
a5ce86954b61dbacde1d1bf24472d95246be45e5
[ "BSD-2-Clause" ]
null
null
null
Examples/Tutorial1.cpp
haskellstudio/belle_old
a5ce86954b61dbacde1d1bf24472d95246be45e5
[ "BSD-2-Clause" ]
null
null
null
Examples/Tutorial1.cpp
haskellstudio/belle_old
a5ce86954b61dbacde1d1bf24472d95246be45e5
[ "BSD-2-Clause" ]
null
null
null
/* ============================================================================== Copyright 2007-2013 William Andrew Burnson. 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 WILLIAM ANDREW BURNSON ''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 WILLIAM ANDREW BURNSON OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ------------------------------------------------------------------------------ This file is part of Belle, Bonne, Sage -- The 'Beautiful, Good, Wise' C++ Vector-Graphics Library for Music Notation ============================================================================== */ //------------------------------------------------------------------------------ /* Tutorial 1: Drawing simple graphics manually in Belle This tutorial explains the graphics abstraction used by Belle, Bonne, Sage. It assumes familiarity with prim as seen in Tutorial 0. On Mac/Linux you can build and run from the terminal using: Scripts/MakeAndRun Tutorial1 For more information related to building, see the README. */ //------------------------------------------------------------------------------ //Include Belle, Bonne, Sage and compile it in this .cpp file. #define BELLE_COMPILE_INLINE #include "Belle.h" //These were discussed in Tutorial 0. using namespace prim; using namespace prim::planar; /*The core belle namespace. It contains classes relevant to drawing such as Affine, Canvas, Color, Font, Painter, Path, Portfolio, Shapes, Text.*/ using namespace belle; //Belle has output painters which are rendering targets such as PDF and JUCE. using namespace belle::painters; //------------------------------------------------------------------------------ /*In Belle there are three fundamental abstract data types for graphics: Portfolio, Canvas, and Painter. The Portfolio contains a list of Canvases and can be thought of as a document with multiple pages. The user of the library must at least subclass Canvas, and implement the Paint virtual method. If the user needs the Portfolio to store any information relevant to the whole document to be accessed during the Paint, then the Portfolio should also be subclassed. The Painter is a device-independent vector graphics object and could represent file or screen-based output. This example will show how to subclass both Portfolio and Canvas and how to use the PDF and SVG painters. */ //Subclass Score from belle::Portfolio struct Score : public Portfolio { //An array of rectangles to paint. Array<Rectangle> RectanglesToPaint; /*Subclass Page from belle::Canvas. Note that Page is a class inside a class, so it is really a Score::Page; however, it is not necessary to do it this way. It just logically groups the Page class with the Score to which it pertains.*/ struct Page : public Canvas { //This method gets called once per canvas. void Paint(Painter& Painter, Portfolio& Portfolio) { /*Since we need access to the Score (as opposed to base class Portfolio) in order to draw the rectangles, we can forward the paint call to a custom paint method which uses a Score& instead of a Portfolio&.*/ Paint(Painter, dynamic_cast<Score&>(Portfolio)); } //Custom paint method with score. void Paint(Painter& Painter, Score& Score) { //Print which page is being painted. c >> "Painting page: " << Painter.GetPageNumber(); //Paint each rectangle in the rectangle array. for(count i = 0; i < Score.RectanglesToPaint.n(); i++) { /*Create an empty path. A path is a vector graphics object containing a list of core instructions: move-to (start new path), line-to, cubic-to (Bezier curve), and close-path. Generally, multiple subpaths are interpreted by the rendering targets according to the zero-winding rule.*/ Path p; /*Add the rectangle shape to the path. The Shapes class contains several primitive building methods.*/ Shapes::AddRectangle(p, Score.RectanglesToPaint[i]); //Alternate green fill with blue stroke. if(i % 2 == 0) Painter.SetFill(Colors::green); else Painter.SetStroke(Colors::blue, 0.01); //Draw the path, separating the fills and strokes by page. if(i % 2 == Painter.GetPageNumber()) Painter.Draw(p); } } }; }; //This program creates a couple of pages with some rectangles using Belle. int main() { //Step 1: Create a score, add some pages, and give it some information. //Instantiate a score. Score MyScore; //Add a portrait page to the score. MyScore.Canvases.Add() = new Score::Page; MyScore.Canvases.z()->Dimensions = Paper::Portrait(Paper::Letter); //Add a landscape page to the score. MyScore.Canvases.Add() = new Score::Page; MyScore.Canvases.z()->Dimensions = Paper::Landscape(Paper::Letter); /*Add some rectangles for the score to paint. Note this is just a custom member that was created to demonstrate how to pass information to the painter. There is nothing intrinsic to the Score about painting rectangles.*/ const number GeometricConstant = 1.2; for(number i = 0.01; i < 8.0; i *= GeometricConstant) MyScore.RectanglesToPaint.Add() = Rectangle(Vector(i, i), Vector(i, i) * GeometricConstant); //Step 2a: Draw the score to PDF. /*Set the PDF-specific properties, for example, the output filename. If no filename is set, then the contents of the PDF file end up in PDF::Properties::Output.*/ PDF::Properties PDFSpecificProperties; PDFSpecificProperties.Filename = "Tutorial1.pdf"; /*Write the score to PDF. Note how in Belle, the Canvas Paint() method is never called directly. Instead a portfolio creates a render target which then calls back the paint method on each canvas. This is an extension of the device-independent graphics paradigm.*/ MyScore.Create<PDF>(PDFSpecificProperties); //Print the name of the output file. c >> "Wrote PDF to '" << PDFSpecificProperties.Filename << "'."; /*Step 2b: Here is the same thing except using the SVG renderer. Since SVG is an image format, the result will be a sequence of files.*/ /*Set the SVG-specific properties, for example, the output filename prefix. If no filename is set, then the contents of the SVG file end up in the SVG::Properties::Output array.*/ SVG::Properties SVGSpecificProperties; SVGSpecificProperties.FilenameStem = "Tutorial1-"; //Write the score to SVG. MyScore.Create<SVG>(SVGSpecificProperties); //Note the name of the output file to console window. c >> "Wrote SVGs to '" << SVGSpecificProperties.FilenameStem << "*.svg'."; //Finish the console output. c.Finish(); return 0; }
39.298507
80
0.677681
haskellstudio
57927aac4a22c9f89ac86a3479e6d473a5015e39
998
cpp
C++
Hacker Rank/Equal_Stacks.cpp
aryabharat/ONLINE_CODING
3f3318c5e660d9b30c14618db8068816ba902d0f
[ "Apache-2.0" ]
1
2019-03-17T09:30:08.000Z
2019-03-17T09:30:08.000Z
Hacker Rank/Equal_Stacks.cpp
aryabharat/ONLINE_CODING
3f3318c5e660d9b30c14618db8068816ba902d0f
[ "Apache-2.0" ]
null
null
null
Hacker Rank/Equal_Stacks.cpp
aryabharat/ONLINE_CODING
3f3318c5e660d9b30c14618db8068816ba902d0f
[ "Apache-2.0" ]
null
null
null
#include <bits/stdc++.h> using namespace std; int main() { int n1,n2,n3; cin >> n1 >> n2 >> n3; vector <int> a (n1); vector <int> b (n2); vector <int> c (n3); int s1=0,s2=0,s3=0; for(int i=0;i<n1;i++) { cin >> a[i]; s1+=a[i]; } for(int i=0;i<n2;i++) { cin >> b[i]; s2+=b[i]; } for(int i=0;i<n3;i++) { cin >> c[i]; s3+=c[i]; } bool ans = false; if(s1 == s2 && s2 == s3) { cout << s2 << "\n"; ans = true; } int i=0,j=0,k=0; while(!ans) { if((s1 == s2 && s2 == s3) || (s1 == 0 && s2 == 0 && s3 ==0)) { ans = true; cout << s1 <<"\n"; continue; } if(s1 > s2) { s1-=a[i]; i++; } else if(s2>s3) { s2-=b[j]; j++; } else { s3-=c[k]; k++; } } }
16.633333
68
0.298597
aryabharat
5792f109530c70a22aa33a23ff491e5c56d6fcc2
718
cpp
C++
src/regularizers/regularizer_l1_l2.cpp
Seraphid/eddl
f627585a05edb91aaf991b898163cbe8cca66caf
[ "MIT" ]
null
null
null
src/regularizers/regularizer_l1_l2.cpp
Seraphid/eddl
f627585a05edb91aaf991b898163cbe8cca66caf
[ "MIT" ]
null
null
null
src/regularizers/regularizer_l1_l2.cpp
Seraphid/eddl
f627585a05edb91aaf991b898163cbe8cca66caf
[ "MIT" ]
null
null
null
/* * EDDL Library - European Distributed Deep Learning Library. * Version: 0.3 * copyright (c) 2019, Universidad Politécnica de Valencia (UPV), PRHLT Research Centre * Date: October 2019 * Author: PRHLT Research Centre, UPV, (rparedes@prhlt.upv.es), (jon@prhlt.upv.es) * All rights reserved */ #include <stdio.h> #include <stdlib.h> #include <iostream> #include "regularizer.h" using namespace std; RL1L2::RL1L2(float l1, float l2) : Regularizer("l1_l2") { this->l1 = l1; this->l2 = l2; } void RL1L2::apply(Tensor* T) { Tensor *S = T->clone(); Tensor *A = T->clone(); S->sign_(); Tensor::add(1.0f, T, -this->l1, S, T, 0); Tensor::add(1.0f, T, -this->l2, A, T, 0); delete A; delete S; }
19.405405
86
0.643454
Seraphid
57953b4740e7cbf56e605f36e0e47547f20abe2e
1,935
cpp
C++
Ds18b20.cpp
konkers/mcp
4b926e886cb812177b3755f915bf53e866675c5d
[ "Apache-2.0" ]
null
null
null
Ds18b20.cpp
konkers/mcp
4b926e886cb812177b3755f915bf53e866675c5d
[ "Apache-2.0" ]
null
null
null
Ds18b20.cpp
konkers/mcp
4b926e886cb812177b3755f915bf53e866675c5d
[ "Apache-2.0" ]
null
null
null
// Copyright 2013 Erik Gilling <konkers@konkers.net> // // 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 Licene. #include "Ds18b20.hpp" #define DS18B20_CMD_CONVERT_T 0x44 #define DS18B20_CMD_WRITE_SCRATCHPAD 0x4e #define DS18B20_CMD_READ_SCRATCHPAD 0xbe #define DS18B20_CMD_COPY_SCRATCHPAD 0x48 #define DS18B20_CMD_RECAL_E2 0xb8 #define DS18B20_CMD_READ_PS 0xb4 Ds18b20::Ds18b20(Dongle *dongle, Dongle::Addr addr, std::string name, float cal0, float cal100) : dongle(dongle), addr(addr), name(name) { offset = -cal0; scale = 100.0 / (cal100 - cal0); } Ds18b20::Ds18b20(Dongle *dongle, Dongle::Addr addr) : dongle(dongle), addr(addr), offset(0.0), scale(1.0) { name = addr.getName(); } void Ds18b20::startConversion(void) { dongle->reset(); dongle->matchRom(addr); dongle->writeByte(DS18B20_CMD_CONVERT_T); } void Ds18b20::startAllConversion(void) { dongle->reset(); dongle->skipRom(); dongle->writeByte(DS18B20_CMD_CONVERT_T); } bool Ds18b20::isConversionDone(void) { return dongle->read() == 1; } void Ds18b20::updateTemp(void) { unsigned val; float newTemp; dongle->reset(); dongle->matchRom(addr); dongle->writeByte(DS18B20_CMD_READ_SCRATCHPAD); val = dongle->readByte(); val |= dongle->readByte() << 8; newTemp = (val >> 4) + (val & 0xf) * (1.0/16.0); newTemp -= offset; newTemp *= scale; temp = newTemp; }
26.875
97
0.694057
konkers
579540c2c6fd2d4491af00e69b2522bb4d774fd9
4,426
cpp
C++
hal/src/main/native/sim/Notifier.cpp
nathanmutin/allwpilib
3ff2c45e4559df7d6a28bac905ad92d0640c95ac
[ "BSD-3-Clause" ]
5
2019-03-16T21:59:49.000Z
2019-05-03T21:31:57.000Z
hal/src/main/native/sim/Notifier.cpp
nathanmutin/allwpilib
3ff2c45e4559df7d6a28bac905ad92d0640c95ac
[ "BSD-3-Clause" ]
1
2019-06-11T20:32:07.000Z
2019-06-13T02:35:34.000Z
hal/src/main/native/sim/Notifier.cpp
nathanmutin/allwpilib
3ff2c45e4559df7d6a28bac905ad92d0640c95ac
[ "BSD-3-Clause" ]
5
2019-03-29T00:38:20.000Z
2019-10-18T21:42:15.000Z
/*----------------------------------------------------------------------------*/ /* Copyright (c) 2016-2019 FIRST. All Rights Reserved. */ /* Open Source Software - may be modified and shared by FRC teams. The code */ /* must be accompanied by the FIRST BSD license file in the root directory of */ /* the project. */ /*----------------------------------------------------------------------------*/ #include "hal/Notifier.h" #include <chrono> #include <wpi/condition_variable.h> #include <wpi/mutex.h> #include <wpi/timestamp.h> #include "HALInitializer.h" #include "hal/HAL.h" #include "hal/cpp/fpga_clock.h" #include "hal/handles/UnlimitedHandleResource.h" namespace { struct Notifier { uint64_t waitTime; bool updatedAlarm = false; bool active = true; bool running = false; wpi::mutex mutex; wpi::condition_variable cond; }; } // namespace using namespace hal; class NotifierHandleContainer : public UnlimitedHandleResource<HAL_NotifierHandle, Notifier, HAL_HandleEnum::Notifier> { public: ~NotifierHandleContainer() { ForEach([](HAL_NotifierHandle handle, Notifier* notifier) { { std::scoped_lock lock(notifier->mutex); notifier->active = false; notifier->running = false; } notifier->cond.notify_all(); // wake up any waiting threads }); } }; static NotifierHandleContainer* notifierHandles; namespace hal { namespace init { void InitializeNotifier() { static NotifierHandleContainer nH; notifierHandles = &nH; } } // namespace init } // namespace hal extern "C" { HAL_NotifierHandle HAL_InitializeNotifier(int32_t* status) { hal::init::CheckInit(); std::shared_ptr<Notifier> notifier = std::make_shared<Notifier>(); HAL_NotifierHandle handle = notifierHandles->Allocate(notifier); if (handle == HAL_kInvalidHandle) { *status = HAL_HANDLE_ERROR; return HAL_kInvalidHandle; } return handle; } void HAL_StopNotifier(HAL_NotifierHandle notifierHandle, int32_t* status) { auto notifier = notifierHandles->Get(notifierHandle); if (!notifier) return; { std::scoped_lock lock(notifier->mutex); notifier->active = false; notifier->running = false; } notifier->cond.notify_all(); } void HAL_CleanNotifier(HAL_NotifierHandle notifierHandle, int32_t* status) { auto notifier = notifierHandles->Free(notifierHandle); if (!notifier) return; // Just in case HAL_StopNotifier() wasn't called... { std::scoped_lock lock(notifier->mutex); notifier->active = false; notifier->running = false; } notifier->cond.notify_all(); } void HAL_UpdateNotifierAlarm(HAL_NotifierHandle notifierHandle, uint64_t triggerTime, int32_t* status) { auto notifier = notifierHandles->Get(notifierHandle); if (!notifier) return; { std::scoped_lock lock(notifier->mutex); notifier->waitTime = triggerTime; notifier->running = true; notifier->updatedAlarm = true; } // We wake up any waiters to change how long they're sleeping for notifier->cond.notify_all(); } void HAL_CancelNotifierAlarm(HAL_NotifierHandle notifierHandle, int32_t* status) { auto notifier = notifierHandles->Get(notifierHandle); if (!notifier) return; { std::scoped_lock lock(notifier->mutex); notifier->running = false; } } uint64_t HAL_WaitForNotifierAlarm(HAL_NotifierHandle notifierHandle, int32_t* status) { auto notifier = notifierHandles->Get(notifierHandle); if (!notifier) return 0; std::unique_lock lock(notifier->mutex); while (notifier->active) { double waitTime; if (!notifier->running) { waitTime = (HAL_GetFPGATime(status) * 1e-6) + 1000.0; // If not running, wait 1000 seconds } else { waitTime = notifier->waitTime * 1e-6; } // Don't wait twice notifier->updatedAlarm = false; auto timeoutTime = hal::fpga_clock::epoch() + std::chrono::duration<double>(waitTime); notifier->cond.wait_until(lock, timeoutTime); if (notifier->updatedAlarm) { notifier->updatedAlarm = false; continue; } if (!notifier->running) continue; if (!notifier->active) break; notifier->running = false; return HAL_GetFPGATime(status); } return 0; } } // extern "C"
27.6625
80
0.641889
nathanmutin
579588c078078f70999774e00fd4cab4ecd210d1
2,055
hpp
C++
Tests/Tests.hpp
bbercovici/RigidBodyKinematics
110d30cc20251081a4558f6851bdfd5abc0fdd82
[ "MIT" ]
null
null
null
Tests/Tests.hpp
bbercovici/RigidBodyKinematics
110d30cc20251081a4558f6851bdfd5abc0fdd82
[ "MIT" ]
null
null
null
Tests/Tests.hpp
bbercovici/RigidBodyKinematics
110d30cc20251081a4558f6851bdfd5abc0fdd82
[ "MIT" ]
null
null
null
// MIT License // Copyright (c) 2018 Benjamin Bercovici // 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. namespace Tests{ void test_euler321_to_mrp(); void test_dXattitudedt() ; void test_domegadt() ; void test_dmrpdt(); void test_shadow_mrp() ; void test_mrp_to_quat(); void test_euler321d_to_dcm(); void test_euler313d_to_dcm(); void test_euler313d_to_mrp(); void test_euler321d_to_mrp(); void test_mrp_to_dcm(); void test_dcm_to_mrp(); void test_euler313_to_mrp(); void test_euler313_to_dcm(); void test_longitude_latitude_to_dcm(); void test_tilde(); void test_M1(); void test_M2(); void test_M3(); void test_dcm_to_euler321(); void test_dcm_to_euler313(); void test_mrp_to_euler313(); void test_mrp_to_euler321(); void test_dcm_to_euler321d(); void test_dcm_to_euler313d(); void test_mrp_to_euler313d(); void test_mrp_to_euler321d(); void test_dcm_to_quat() ; void test_dcm_to_prv() ; void test_prv_to_dcm(); void test_prv_to_mrp(); void test_Bmat(); void test_partial_mrp_dot_partial_mrp(); }
35.431034
81
0.771776
bbercovici
579a8f2bcac59e5a1b4c8cd04e1db176cfddd175
5,233
cpp
C++
src/thread.cpp
corehacker/ch-cpp-utils
4b03045fbecc867f7c6b088eabd8aa4cc30f1170
[ "MIT" ]
5
2017-11-05T11:41:42.000Z
2020-09-03T07:49:12.000Z
src/thread.cpp
corehacker/ch-cpp-utils
4b03045fbecc867f7c6b088eabd8aa4cc30f1170
[ "MIT" ]
1
2017-11-14T02:50:16.000Z
2017-11-14T02:50:16.000Z
src/thread.cpp
corehacker/ch-cpp-utils
4b03045fbecc867f7c6b088eabd8aa4cc30f1170
[ "MIT" ]
null
null
null
/******************************************************************************* * * BSD 2-Clause License * * Copyright (c) 2017, Sandeep Prakash * 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. * * 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. ******************************************************************************/ /******************************************************************************* * Copyright (c) 2017, Sandeep Prakash <123sandy@gmail.com> * * \file thread.cpp * * \author Sandeep Prakash * * \date Apr 1, 2017 * * \brief * ******************************************************************************/ #include <iostream> #include <glog/logging.h> #include "ch-cpp-utils/thread.hpp" using namespace std; namespace ChCppUtils { void * Thread::threadFunc (void *this_) { Thread *t = (Thread *) this_; t->run (); LOG(INFO) << "Exiting thread routine" <<std::endl; return NULL; } void Thread::run () { if (true == mBase) { mEventBase = event_base_new(); LOG(INFO) << "Creating event base: " << mEventBase; } else { mEventBase = NULL; LOG(INFO) << "Not creating event base: " << mEventBase; } if(mInitCbk) { mInitCbk(mInitCbkThis); } mSemaphore.notify(); LOG(INFO) << "Notified start."; while (true) { ThreadJobBase *job = mGetJob (mGetJobThis); if(job->isExit()) { LOG(INFO) << "Exit Job Command"; SAFE_DELETE(job); break; } runJob (job); } if(mDeInitCbk) { mDeInitCbk(mDeInitCbkThis); } if(mEventBase) { event_base_free(mEventBase); mEventBase = NULL; } LOG(INFO) << "Exited thread."; mThread->detach(); LOG(INFO) << "Detached thread."; mSemaphore.notify(); LOG(INFO) << "Notified exit."; } void Thread::runJob (ThreadJobBase *job) { if (job->routine) { job->routine (job->arg, mEventBase); } SAFE_DELETE(job); } thread::id Thread::getId() { return mThread->get_id(); } void Thread::join() { if (mThread->joinable()) { LOG(INFO) << "Joining thread: 0x" << std::hex << getId() << std::dec ; mThread->join(); } } struct event_base *Thread::getEventBase() { return mEventBase; } Thread::Thread (ThreadGetJob getJob, void *this_) { LOG(INFO) << "Creating thread"; mGetJob = getJob; mGetJobThis = this_; mBase = false; mEventBase = NULL; mInitCbk = nullptr; mInitCbkThis = nullptr; mThread = nullptr; mDeInitCbk = nullptr; mDeInitCbkThis = nullptr; } Thread::Thread (ThreadGetJob getJob, void *this_, bool base) { LOG(INFO) << "*****Thread"; mGetJob = getJob; mGetJobThis = this_; mBase = base; mEventBase = NULL; mInitCbk = nullptr; mInitCbkThis = nullptr; mThread = nullptr; mDeInitCbk = nullptr; mDeInitCbkThis = nullptr; } Thread::Thread (ThreadGetJob getJob, void *this_, bool base, ThreadInitCbk initCbk, void *initCbkThis, ThreadDeInitCbk deinitCbk, void *deinitCbkThis) { LOG(INFO) << "*****Thread"; mGetJob = getJob; mGetJobThis = this_; mBase = base; mEventBase = NULL; mInitCbk = initCbk; mInitCbkThis = initCbkThis; mDeInitCbk = deinitCbk; mDeInitCbkThis = deinitCbkThis; mThread = nullptr; } void Thread::start() { mThread = new std::thread(Thread::threadFunc, this); LOG(INFO) << "Waiting for thread to start: 0x" << std::hex << getId() << std::dec ; mSemaphore.wait(); LOG(INFO) << "Thread start complete: 0x" << std::hex << getId() << std::dec ; } Thread::~Thread () { LOG(INFO) << "*****~Thread"; thread::id id = getId(); LOG(INFO) << "Waiting for thread to exit: 0x" << std::hex << id << std::dec ; mSemaphore.wait(); LOG(INFO) << "Thread exited: 0x" << std::hex << id << std::dec; SAFE_DELETE(mThread); } }
26.974227
85
0.590101
corehacker
579cf96ef36d30823a70b491cc0015e6813be116
7,562
cpp
C++
src/gpu/GrTextureParamsAdjuster.cpp
Perspex/skia
e25fe5a294e9cee8f23207eef63fad6cffa9ced4
[ "Apache-2.0" ]
2
2019-07-19T17:40:28.000Z
2020-05-09T11:58:41.000Z
src/gpu/GrTextureParamsAdjuster.cpp
AvaloniaUI/skia
e25fe5a294e9cee8f23207eef63fad6cffa9ced4
[ "Apache-2.0" ]
null
null
null
src/gpu/GrTextureParamsAdjuster.cpp
AvaloniaUI/skia
e25fe5a294e9cee8f23207eef63fad6cffa9ced4
[ "Apache-2.0" ]
null
null
null
/* * Copyright 2015 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "GrTextureParamsAdjuster.h" #include "GrCaps.h" #include "GrContext.h" #include "GrDrawContext.h" #include "GrGpu.h" #include "GrGpuResourcePriv.h" #include "GrResourceKey.h" #include "GrTexture.h" #include "GrTextureParams.h" #include "GrTextureProvider.h" #include "SkCanvas.h" #include "SkGr.h" #include "SkGrPriv.h" #include "effects/GrTextureDomain.h" typedef GrTextureProducer::CopyParams CopyParams; ////////////////////////////////////////////////////////////////////////////// static GrTexture* copy_on_gpu(GrTexture* inputTexture, const SkIRect* subset, const CopyParams& copyParams) { SkASSERT(!subset || !subset->isEmpty()); GrContext* context = inputTexture->getContext(); SkASSERT(context); const GrCaps* caps = context->caps(); // Either it's a cache miss or the original wasn't cached to begin with. GrSurfaceDesc rtDesc = inputTexture->desc(); rtDesc.fFlags = rtDesc.fFlags | kRenderTarget_GrSurfaceFlag; rtDesc.fWidth = copyParams.fWidth; rtDesc.fHeight = copyParams.fHeight; rtDesc.fConfig = GrMakePixelConfigUncompressed(rtDesc.fConfig); // If the config isn't renderable try converting to either A8 or an 32 bit config. Otherwise, // fail. if (!caps->isConfigRenderable(rtDesc.fConfig, false)) { if (GrPixelConfigIsAlphaOnly(rtDesc.fConfig)) { if (caps->isConfigRenderable(kAlpha_8_GrPixelConfig, false)) { rtDesc.fConfig = kAlpha_8_GrPixelConfig; } else if (caps->isConfigRenderable(kSkia8888_GrPixelConfig, false)) { rtDesc.fConfig = kSkia8888_GrPixelConfig; } else { return nullptr; } } else if (kRGB_GrColorComponentFlags == (kRGB_GrColorComponentFlags & GrPixelConfigComponentMask(rtDesc.fConfig))) { if (caps->isConfigRenderable(kSkia8888_GrPixelConfig, false)) { rtDesc.fConfig = kSkia8888_GrPixelConfig; } else { return nullptr; } } else { return nullptr; } } SkAutoTUnref<GrTexture> copy(context->textureProvider()->createTexture(rtDesc, true)); if (!copy) { return nullptr; } // TODO: If no scaling is being performed then use copySurface. GrPaint paint; SkScalar sx; SkScalar sy; if (subset) { sx = 1.f / inputTexture->width(); sy = 1.f / inputTexture->height(); } if (copyParams.fFilter != GrTextureParams::kNone_FilterMode && subset && (subset->width() != copyParams.fWidth || subset->height() != copyParams.fHeight)) { SkRect domain; domain.fLeft = (subset->fLeft + 0.5f) * sx; domain.fTop = (subset->fTop + 0.5f)* sy; domain.fRight = (subset->fRight - 0.5f) * sx; domain.fBottom = (subset->fBottom - 0.5f) * sy; // This would cause us to read values from outside the subset. Surely, the caller knows // better! SkASSERT(copyParams.fFilter != GrTextureParams::kMipMap_FilterMode); paint.addColorFragmentProcessor( GrTextureDomainEffect::Create(inputTexture, SkMatrix::I(), domain, GrTextureDomain::kClamp_Mode, copyParams.fFilter))->unref(); } else { GrTextureParams params(SkShader::kClamp_TileMode, copyParams.fFilter); paint.addColorTextureProcessor(inputTexture, SkMatrix::I(), params); } SkRect localRect; if (subset) { localRect = SkRect::Make(*subset); localRect.fLeft *= sx; localRect.fTop *= sy; localRect.fRight *= sx; localRect.fBottom *= sy; } else { localRect = SkRect::MakeWH(1.f, 1.f); } SkAutoTUnref<GrDrawContext> drawContext(context->drawContext(copy->asRenderTarget())); if (!drawContext) { return nullptr; } SkRect dstRect = SkRect::MakeWH(SkIntToScalar(rtDesc.fWidth), SkIntToScalar(rtDesc.fHeight)); drawContext->fillRectToRect(GrClip::WideOpen(), paint, SkMatrix::I(), dstRect, localRect); return copy.detach(); } GrTextureAdjuster::GrTextureAdjuster(GrTexture* original, const SkIRect& contentArea) : fOriginal(original) { if (contentArea.fLeft > 0 || contentArea.fTop > 0 || contentArea.fRight < original->width() || contentArea.fBottom < original->height()) { fContentArea.set(contentArea); } } GrTexture* GrTextureAdjuster::refTextureSafeForParams(const GrTextureParams& params, SkIPoint* outOffset) { GrTexture* texture = this->originalTexture(); GrContext* context = texture->getContext(); CopyParams copyParams; const SkIRect* contentArea = this->contentArea(); if (contentArea && GrTextureParams::kMipMap_FilterMode == params.filterMode()) { // If we generate a MIP chain for texture it will read pixel values from outside the content // area. copyParams.fWidth = contentArea->width(); copyParams.fHeight = contentArea->height(); copyParams.fFilter = GrTextureParams::kBilerp_FilterMode; } else if (!context->getGpu()->makeCopyForTextureParams(texture->width(), texture->height(), params, &copyParams)) { if (outOffset) { if (contentArea) { outOffset->set(contentArea->fLeft, contentArea->fRight); } else { outOffset->set(0, 0); } } return SkRef(texture); } GrUniqueKey key; this->makeCopyKey(copyParams, &key); if (key.isValid()) { GrTexture* result = context->textureProvider()->findAndRefTextureByUniqueKey(key); if (result) { return result; } } GrTexture* result = copy_on_gpu(texture, contentArea, copyParams); if (result) { if (key.isValid()) { result->resourcePriv().setUniqueKey(key); this->didCacheCopy(key); } if (outOffset) { outOffset->set(0, 0); } } return result; } ////////////////////////////////////////////////////////////////////////////// GrTexture* GrTextureMaker::refTextureForParams(GrContext* ctx, const GrTextureParams& params) { CopyParams copyParams; if (!ctx->getGpu()->makeCopyForTextureParams(this->width(), this->height(), params, &copyParams)) { return this->refOriginalTexture(ctx); } GrUniqueKey copyKey; this->makeCopyKey(copyParams, &copyKey); if (copyKey.isValid()) { GrTexture* result = ctx->textureProvider()->findAndRefTextureByUniqueKey(copyKey); if (result) { return result; } } GrTexture* result = this->generateTextureForParams(ctx, copyParams); if (!result) { return nullptr; } if (copyKey.isValid()) { ctx->textureProvider()->assignUniqueKeyToTexture(copyKey, result); this->didCacheCopy(copyKey); } return result; } GrTexture* GrTextureMaker::generateTextureForParams(GrContext* ctx, const CopyParams& copyParams) { SkAutoTUnref<GrTexture> original(this->refOriginalTexture(ctx)); if (!original) { return nullptr; } return copy_on_gpu(original, nullptr, copyParams); }
36.009524
100
0.609627
Perspex
579e193ddcadad859910cb1a513699ace70c2912
4,623
cpp
C++
Kamek/src/music.cpp
RedStoneMatt/SuperLuigiLandWii
8b98f3b16a1e5d99681ac382d5e603248a1c53db
[ "MIT" ]
4
2021-01-18T18:14:18.000Z
2022-02-20T13:08:28.000Z
Kamek/src/music.cpp
RedStoneMatt/SuperLuigiLandWii
8b98f3b16a1e5d99681ac382d5e603248a1c53db
[ "MIT" ]
null
null
null
Kamek/src/music.cpp
RedStoneMatt/SuperLuigiLandWii
8b98f3b16a1e5d99681ac382d5e603248a1c53db
[ "MIT" ]
null
null
null
#include <game.h> #include <sfx.h> #include "music.h" bool isTrailerMode; struct HijackedStream { //const char *original; //const char *originalFast; u32 stringOffset; u32 stringOffsetFast; u32 infoOffset; u8 originalID; int streamID; }; struct Hijacker { HijackedStream stream[2]; u8 currentStream; u8 currentCustomTheme; }; const char* SongNameList [] = { "HEADLONG_HOLD", "BOSS_TOWER", "MENU", "WAYSIDE_UW", "CHALLENGE", "WINDY_RUIN_UG", "GOOMBA_GROTTO", "CLIFFSIDE", "BOSS_ROY", "GOOMBA_GRO_UG", "WINDY_RUINS1", "LAVA_LAIR", "SHFTNG_SWMPLN", "ICE_FLOE_FERR", "JAPAN", "PUMPKIN", "EERIE_EXCURS", "BOSS_WENDY", "BOWSER", "BONUS", "AMBUSH", "BRIDGE_DRUMS", "SNOW2", "BOSS_MORTON", "SUNNY_ASCENT", "AUTUMN", "WYSIDE_WALLOW", "LWLGHT_LBRNTH", "GHASTLY_GLADE", "JUNGLE_SWING", "BOSS_IGGY", "BOSS_LARRY", "ROCKSLIDE_RUN", "FINAL_KAMEK", "SINGALONG", "FACTORY", "BOSS_LUDWIG", "CHNLNK_CHMBER", "YOSHIHOUSE", "PRLOUS_PSSAGE", "BOMB_BASEMENT", "WINDY_RUINS2", "BOSS_LEMMY", "MINIGAME", "BONUS_AREA", "CHALLENGE", "TERMINA_TOWER", "", "", "", "", "", "", "", "", "", "BOSS_CASTLE", "BOSS_AIRSHIP", NULL }; // Offsets are from the start of the INFO block, not the start of the brsar. // INFO begins at 0x212C0, so that has to be subtracted from absolute offsets // within the brsar. #define _I(offs) ((offs)-0x212C0) Hijacker Hijackers[2] = { { { {/*"athletic_lr.n.32.brstm", "athletic_fast_lr.n.32.brstm",*/ _I(0x4A8F8), _I(0x4A938), _I(0x476C4), 4, STRM_BGM_ATHLETIC}, {/*"BGM_SIRO.32.brstm", "BGM_SIRO_fast.32.brstm",*/ _I(0x4B2E8), _I(0x4B320), _I(0x48164), 10, STRM_BGM_SHIRO} }, 0, 0 }, { { {/*"STRM_BGM_CHIJOU.brstm", "STRM_BGM_CHIJOU_FAST.brstm",*/ _I(0x4A83C), _I(0x4A8B4), 0, 1, STRM_BGM_CHIJOU}, {/*"STRM_BGM_CHIKA.brstm", "STRM_BGM_CHIKA_FAST.brstm",*/ _I(0x4A878), _I(0x4A780), 0, 2, STRM_BGM_CHIKA}, }, 0, 0 } }; extern void *SoundRelatedClass; inline char *BrsarInfoOffset(u32 offset) { return (char*)(*(u32*)(((u32)SoundRelatedClass) + 0x5CC)) + offset; } void FixFilesize(u32 streamNameOffset); u8 hijackMusicWithSongName(const char *songName, int themeID, bool hasFast, int channelCount, int trackCount, int *wantRealStreamID) { Hijacker *hj = &Hijackers[channelCount==4?1:0]; if(isTrailerMode) { songName = "NOMUSICFORU"; } // do we already have this theme in this slot? // if so, don't switch streams // if we do, NSMBW will think it's a different song, and restart it ... // but if it's just an area transition where both areas are using the same // song, we don't want that if ((themeID >= 0) && hj->currentCustomTheme == themeID) return hj->stream[hj->currentStream].originalID; // which one do we use this time...? int toUse = (hj->currentStream + 1) & 1; hj->currentStream = toUse; hj->currentCustomTheme = themeID; // write the stream's info HijackedStream *stream = &hj->stream[hj->currentStream]; if (stream->infoOffset) { u16 *thing = (u16*)(BrsarInfoOffset(stream->infoOffset) + 4); OSReport("Modifying stream info, at offset %x which is at pointer %x\n", stream->infoOffset, thing); OSReport("It currently has: channel count %d, track bitfield 0x%x\n", thing[0], thing[1]); thing[0] = channelCount; thing[1] = (1 << trackCount) - 1; OSReport("It has been set to: channel count %d, track bitfield 0x%x\n", thing[0], thing[1]); } sprintf(BrsarInfoOffset(stream->stringOffset), "new/%s.er", songName); sprintf(BrsarInfoOffset(stream->stringOffsetFast), hasFast?"new/%s_F.er":"new/%s.er", songName); // update filesizes FixFilesize(stream->stringOffset); FixFilesize(stream->stringOffsetFast); // done! if (wantRealStreamID) *wantRealStreamID = stream->streamID; return stream->originalID; } //oh for fuck's sake #include "fileload.h" void FixFilesize(u32 streamNameOffset) { char *streamName = BrsarInfoOffset(streamNameOffset); char nameWithSound[80]; snprintf(nameWithSound, 79, "/Sound/%s", streamName); s32 entryNum; DVDHandle info; if ((entryNum = DVDConvertPathToEntrynum(nameWithSound)) >= 0) { if (DVDFastOpen(entryNum, &info)) { u32 *lengthPtr = (u32*)(streamName - 0x1C); *lengthPtr = info.length; } } else OSReport("What, I couldn't find \"%s\" :(\n", nameWithSound); } extern "C" u8 after_course_getMusicForZone(u8 realThemeID) { if (realThemeID < 100) return realThemeID; bool usesDrums = (realThemeID >= 200); // OSReport("isTrailerMode = %d\n", isTrailerMode); return hijackMusicWithSongName(SongNameList[realThemeID-100], realThemeID, true, usesDrums?4:2, usesDrums?2:1, 0); }
23
134
0.687432
RedStoneMatt
579e4a7fae56346e0653227db8f680a97f5542d6
9,186
cpp
C++
src/demos/irrlicht/demo_IRR_fourbar.cpp
lucasw/chrono
e79d8c761c718ecb4c796725cff37026f357da8c
[ "BSD-3-Clause" ]
null
null
null
src/demos/irrlicht/demo_IRR_fourbar.cpp
lucasw/chrono
e79d8c761c718ecb4c796725cff37026f357da8c
[ "BSD-3-Clause" ]
null
null
null
src/demos/irrlicht/demo_IRR_fourbar.cpp
lucasw/chrono
e79d8c761c718ecb4c796725cff37026f357da8c
[ "BSD-3-Clause" ]
null
null
null
// ============================================================================= // PROJECT CHRONO - http://projectchrono.org // // Copyright (c) 2014 projectchrono.org // All rights reserved. // // Use of this source code is governed by a BSD-style license that can be found // in the LICENSE file at the top level of the distribution and at // http://projectchrono.org/license-chrono.txt. // // ============================================================================= // Authors: Alessandro Tasora // ============================================================================= // // Demo code about // - using IRRLICHT as a realtime 3D viewer of a four-bar mechanism // - using the IRRLICHT graphical user interface (GUI) to handle user-input // via mouse. // // ============================================================================= #include "chrono/physics/ChLinkMotorRotationSpeed.h" #include "chrono/physics/ChSystemNSC.h" #include "chrono_irrlicht/ChVisualSystemIrrlicht.h" // Use the namespaces of Chrono using namespace chrono; using namespace chrono::irrlicht; // Use the main namespaces of Irrlicht using namespace irr; using namespace irr::core; using namespace irr::scene; using namespace irr::video; using namespace irr::io; using namespace irr::gui; // Some static data (this is a simple application, we can do this ;) just to allow easy GUI manipulation IGUIStaticText* text_motorspeed = 0; // The MyEventReceiver class will be used to manage input // from the GUI graphical user interface (the interface will // be created with the basic -yet flexible- platform // independent toolset of Irrlicht). class MyEventReceiver : public IEventReceiver { public: MyEventReceiver(ChSystemNSC* system, IrrlichtDevice* device, std::shared_ptr<ChLinkMotorRotationSpeed> motor) { // store pointer to physical system & other stuff so we can tweak them by user keyboard msystem = system; mdevice = device; mmotor = motor; } bool OnEvent(const SEvent& event) { // check if user moved the sliders with mouse.. if (event.EventType == EET_GUI_EVENT) { s32 id = event.GUIEvent.Caller->getID(); switch (event.GUIEvent.EventType) { case EGET_SCROLL_BAR_CHANGED: if (id == 101) // id of 'motor speed' slider.. { s32 pos = ((IGUIScrollBar*)event.GUIEvent.Caller)->getPos(); double newspeed = 10 * (double)pos / 100.0; // set the speed into motor object if (auto mfun = std::dynamic_pointer_cast<ChFunction_Const>(mmotor->GetSpeedFunction())) mfun->Set_yconst(newspeed); // show speed as formatted text in interface screen char message[50]; sprintf(message, "Motor speed: %g [rad/s]", newspeed); text_motorspeed->setText(core::stringw(message).c_str()); } break; default: break; } } return false; } private: ChSystemNSC* msystem; IrrlichtDevice* mdevice; std::shared_ptr<ChLinkMotorRotationSpeed> mmotor; }; int main(int argc, char* argv[]) { GetLog() << "Copyright (c) 2017 projectchrono.org\nChrono version: " << CHRONO_VERSION << "\n\n"; // 1- Create a Chrono physical system ChSystemNSC sys; // 2- Create the rigid bodies of the four-bar mechanical system // (a flywheel, a rod, a rocker, a truss), maybe setting // position/mass/inertias of their center of mass (COG) etc. // ..the truss auto my_body_A = chrono_types::make_shared<ChBody>(); sys.AddBody(my_body_A); my_body_A->SetBodyFixed(true); // truss does not move! // ..the flywheel auto my_body_B = chrono_types::make_shared<ChBody>(); sys.AddBody(my_body_B); my_body_B->SetPos(ChVector<>(0, 0, 0)); // position of COG of flywheel // ..the rod auto my_body_C = chrono_types::make_shared<ChBody>(); sys.AddBody(my_body_C); my_body_C->SetPos(ChVector<>(4, 0, 0)); // position of COG of rod // ..the rocker auto my_body_D = chrono_types::make_shared<ChBody>(); sys.AddBody(my_body_D); my_body_D->SetPos(ChVector<>(8, -4, 0)); // position of COG of rod // 3- Create constraints: the mechanical joints between the // rigid bodies. Doesn't matter if some constraints are redundant. // .. a motor between flywheel and truss auto my_link_AB = chrono_types::make_shared<ChLinkMotorRotationSpeed>(); my_link_AB->Initialize(my_body_A, my_body_B, ChFrame<>(ChVector<>(0, 0, 0))); sys.AddLink(my_link_AB); auto my_speed_function = chrono_types::make_shared<ChFunction_Const>(CH_C_PI); // speed w=3.145 rad/sec my_link_AB->SetSpeedFunction(my_speed_function); // .. a revolute joint between flywheel and rod auto my_link_BC = chrono_types::make_shared<ChLinkLockRevolute>(); my_link_BC->Initialize(my_body_B, my_body_C, ChCoordsys<>(ChVector<>(2, 0, 0))); sys.AddLink(my_link_BC); // .. a revolute joint between rod and rocker auto my_link_CD = chrono_types::make_shared<ChLinkLockRevolute>(); my_link_CD->Initialize(my_body_C, my_body_D, ChCoordsys<>(ChVector<>(8, 0, 0))); sys.AddLink(my_link_CD); // .. a revolute joint between rocker and truss auto my_link_DA = chrono_types::make_shared<ChLinkLockRevolute>(); my_link_DA->Initialize(my_body_D, my_body_A, ChCoordsys<>(ChVector<>(8, -8, 0))); sys.AddLink(my_link_DA); // Create the Irrlicht visualization system auto vis = chrono_types::make_shared<ChVisualSystemIrrlicht>(); sys.SetVisualSystem(vis); vis->SetWindowSize(800, 600); vis->SetWindowTitle("Four-bar mechanism"); vis->Initialize(); vis->AddLogo(); vis->AddSkyBox(); vis->AddCamera(ChVector<>(0, 0, -8)); vis->AddTypicalLights(); // ..add a GUI text and GUI slider to control motor of mechanism via mouse text_motorspeed = vis->GetGUIEnvironment()->addStaticText(L"Motor speed:", rect<s32>(300, 85, 400, 100), false); IGUIScrollBar* scrollbar = vis->GetGUIEnvironment()->addScrollBar(true, rect<s32>(300, 105, 450, 120), 0, 101); scrollbar->setMax(100); // ..Finally create the custom event receiver MyEventReceiver receiver(&sys, vis->GetDevice(), my_link_AB); vis->AddUserEventReceiver(&receiver); // // Configure the solver with non-default settings // // By default, the solver uses the EULER_IMPLICIT_LINEARIZED stepper, that is very fast, // but may allow some geometric error in constraints (because it is based on constraint // stabilization). Alternatively, the timestepper EULER_IMPLICIT_PROJECTED is slower, // but it is based on constraint projection, so gaps in constraints are less noticeable // (hence avoids the 'spongy' behaviour of the default stepper, which operates only // on speed-impulse level and keeps constraints'closed' by a continuous stabilization). sys.SetTimestepperType(ChTimestepper::Type::EULER_IMPLICIT_LINEARIZED); // // Simulation loop // // use this array of points to store trajectory of a rod-point std::vector<chrono::ChVector<> > mtrajectory; while (vis->Run()) { vis->BeginScene(); vis->DrawAll(); // .. draw a grid tools::drawGrid(vis.get(), 0.5, 0.5); // .. draw a circle representing flywheel tools::drawCircle(vis.get(), 2.1, ChCoordsys<>(ChVector<>(0, 0, 0), QUNIT)); // .. draw a small circle representing joint BC tools::drawCircle(vis.get(), 0.06, ChCoordsys<>(my_link_BC->GetMarker1()->GetAbsCoord().pos, QUNIT)); // .. draw a small circle representing joint CD tools::drawCircle(vis.get(), 0.06, ChCoordsys<>(my_link_CD->GetMarker1()->GetAbsCoord().pos, QUNIT)); // .. draw a small circle representing joint DA tools::drawCircle(vis.get(), 0.06, ChCoordsys<>(my_link_DA->GetMarker1()->GetAbsCoord().pos, QUNIT)); // .. draw the rod (from joint BC to joint CD) tools::drawSegment(vis.get(), my_link_BC->GetMarker1()->GetAbsCoord().pos, my_link_CD->GetMarker1()->GetAbsCoord().pos, ChColor(0, 1, 0)); // .. draw the rocker (from joint CD to joint DA) tools::drawSegment(vis.get(), my_link_CD->GetMarker1()->GetAbsCoord().pos, my_link_DA->GetMarker1()->GetAbsCoord().pos, ChColor(1, 0, 0)); // .. draw the trajectory of the rod-point tools::drawPolyline(vis.get(), mtrajectory, ChColor(0, 0.5f, 0)); // We need to add another point to the array of 3d points describing the trajectory to be drawn.. mtrajectory.push_back(my_body_C->Point_Body2World(ChVector<>(1, 1, 0))); // keep only last 150 points.. if (mtrajectory.size() > 150) mtrajectory.erase(mtrajectory.begin()); // Perform time integration sys.DoStepDynamics(0.001); vis->EndScene(); } return 0; }
41.565611
116
0.629872
lucasw
57a02641dfeb01d4e5ac47a70fc678e18e36edd8
5,565
hpp
C++
sprite.hpp
mika314/brekout
5ef4a08a84d250c5de340e593c1770ab92a4e8a9
[ "MIT" ]
null
null
null
sprite.hpp
mika314/brekout
5ef4a08a84d250c5de340e593c1770ab92a4e8a9
[ "MIT" ]
null
null
null
sprite.hpp
mika314/brekout
5ef4a08a84d250c5de340e593c1770ab92a4e8a9
[ "MIT" ]
null
null
null
#pragma once #include <sdlpp/sdlpp.hpp> #define LOAD_SPRITE(name) loadSprite(sprite_##name##_bmp, sprite_##name##_bmp_len) auto loadSprite(unsigned char *, unsigned) -> SDL_Surface *; // clang-format off extern unsigned char sprite_title_screen_bmp[]; extern unsigned sprite_title_screen_bmp_len; extern unsigned char sprite_font_bmp[]; extern unsigned sprite_font_bmp_len; extern unsigned char sprite_play_button_bmp[]; extern unsigned sprite_play_button_bmp_len; extern unsigned char sprite_play_button_down_bmp[]; extern unsigned sprite_play_button_down_bmp_len; extern unsigned char sprite_crash_bmp[]; extern unsigned sprite_crash_bmp_len; extern unsigned char sprite_check_online_bmp[]; extern unsigned sprite_check_online_bmp_len; extern unsigned char sprite_check_online_down_bmp[]; extern unsigned sprite_check_online_down_bmp_len; extern unsigned char sprite_close_bmp[]; extern unsigned sprite_close_bmp_len; extern unsigned char sprite_close_down_bmp[]; extern unsigned sprite_close_down_bmp_len; extern unsigned char sprite_loading_00_bmp[]; extern unsigned sprite_loading_00_bmp_len; extern unsigned char sprite_loading_01_bmp[]; extern unsigned sprite_loading_01_bmp_len; extern unsigned char sprite_loading_02_bmp[]; extern unsigned sprite_loading_02_bmp_len; extern unsigned char sprite_loading_03_bmp[]; extern unsigned sprite_loading_03_bmp_len; extern unsigned char sprite_loading_04_bmp[]; extern unsigned sprite_loading_04_bmp_len; extern unsigned char sprite_loading_05_bmp[]; extern unsigned sprite_loading_05_bmp_len; extern unsigned char sprite_loading_06_bmp[]; extern unsigned sprite_loading_06_bmp_len; extern unsigned char sprite_loading_07_bmp[]; extern unsigned sprite_loading_07_bmp_len; extern unsigned char sprite_loading_08_bmp[]; extern unsigned sprite_loading_08_bmp_len; extern unsigned char sprite_loading_09_bmp[]; extern unsigned sprite_loading_09_bmp_len; extern unsigned char sprite_loading_10_bmp[]; extern unsigned sprite_loading_10_bmp_len; extern unsigned char sprite_loading_11_bmp[]; extern unsigned sprite_loading_11_bmp_len; extern unsigned char sprite_loading_12_bmp[]; extern unsigned sprite_loading_12_bmp_len; extern unsigned char sprite_loading_13_bmp[]; extern unsigned sprite_loading_13_bmp_len; extern unsigned char sprite_loading_14_bmp[]; extern unsigned sprite_loading_14_bmp_len; extern unsigned char sprite_loading_15_bmp[]; extern unsigned sprite_loading_15_bmp_len; extern unsigned char sprite_loading_16_bmp[]; extern unsigned sprite_loading_16_bmp_len; extern unsigned char sprite_loading_17_bmp[]; extern unsigned sprite_loading_17_bmp_len; extern unsigned char sprite_issue_fixed_bmp[]; extern unsigned sprite_issue_fixed_bmp_len; extern unsigned char sprite_issue_fixed_2_bmp[]; extern unsigned sprite_issue_fixed_2_bmp_len; extern unsigned char sprite_issue_fixed_3_bmp[]; extern unsigned sprite_issue_fixed_3_bmp_len; extern unsigned char sprite_issue_fixed_4_bmp[]; extern unsigned sprite_issue_fixed_4_bmp_len; extern unsigned char sprite_boot_screen_bmp[]; extern unsigned sprite_boot_screen_bmp_len; extern unsigned char sprite_ver_b_bmp[]; extern unsigned sprite_ver_b_bmp_len; extern unsigned char sprite_ver_r_bmp[]; extern unsigned sprite_ver_r_bmp_len; extern unsigned char sprite_ver_2_bmp[]; extern unsigned sprite_ver_2_bmp_len; extern unsigned char sprite_ver_3_bmp[]; extern unsigned sprite_ver_3_bmp_len; extern unsigned char sprite_game_field_bmp[]; extern unsigned sprite_game_field_bmp_len; extern unsigned char sprite_snake_01_bmp[]; extern unsigned sprite_snake_01_bmp_len; extern unsigned char sprite_snake_02_bmp[]; extern unsigned sprite_snake_02_bmp_len; extern unsigned char sprite_snake_03_bmp[]; extern unsigned sprite_snake_03_bmp_len; extern unsigned char sprite_snake_04_bmp[]; extern unsigned sprite_snake_04_bmp_len; extern unsigned char sprite_snake_05_bmp[]; extern unsigned sprite_snake_05_bmp_len; extern unsigned char sprite_snake_06_bmp[]; extern unsigned sprite_snake_06_bmp_len; extern unsigned char sprite_snake_07_bmp[]; extern unsigned sprite_snake_07_bmp_len; extern unsigned char sprite_snake_08_bmp[]; extern unsigned sprite_snake_08_bmp_len; extern unsigned char sprite_snake_09_bmp[]; extern unsigned sprite_snake_09_bmp_len; extern unsigned char sprite_snake_10_bmp[]; extern unsigned sprite_snake_10_bmp_len; extern unsigned char sprite_snake_11_bmp[]; extern unsigned sprite_snake_11_bmp_len; extern unsigned char sprite_snake_12_bmp[]; extern unsigned sprite_snake_12_bmp_len; extern unsigned char sprite_snake_13_bmp[]; extern unsigned sprite_snake_13_bmp_len; extern unsigned char sprite_snake_14_bmp[]; extern unsigned sprite_snake_14_bmp_len; extern unsigned char sprite_fruit_bmp[]; extern unsigned sprite_fruit_bmp_len; extern unsigned char sprite_snekout_bmp[]; extern unsigned sprite_snekout_bmp_len; extern unsigned char sprite_update_bmp[]; extern unsigned sprite_update_bmp_len; extern unsigned char sprite_update_down_bmp[]; extern unsigned sprite_update_down_bmp_len; extern unsigned char sprite_restart_bmp[]; extern unsigned sprite_restart_bmp_len; extern unsigned char sprite_restart_down_bmp[]; extern unsigned sprite_restart_down_bmp_len; extern unsigned char sprite_last_crash_bmp[]; extern unsigned sprite_last_crash_bmp_len;
44.52
82
0.82372
mika314
57a458bbb8d961b2c92c33c797a509351c88222e
865
hpp
C++
src/Net.hpp
edelkas/pfdb
f492767cb1fce18e737cdd6beeca23293a6acab4
[ "MIT" ]
null
null
null
src/Net.hpp
edelkas/pfdb
f492767cb1fce18e737cdd6beeca23293a6acab4
[ "MIT" ]
null
null
null
src/Net.hpp
edelkas/pfdb
f492767cb1fce18e737cdd6beeca23293a6acab4
[ "MIT" ]
null
null
null
#pragma once #include "Downloader.hpp" #include "Parser.hpp" enum Website { NONE, IMDB, FILMAFFINITY }; enum UrlType { MOVIE, SEARCH }; /** * Class for downloading and parsing movies and movies searches. * * Each supported website is implemented as a namespace. It is extensible. * This class is a singleton, only one instance can be created. */ class Net { private: Downloader downloader; Parser parser; public: Net(); ~Net(); static Website Host(const std::string& url); /** * Download HTML file using libCURL and parse it using MyHTML */ void Parse(const std::string& url); void Parse(Website web, const std::string& id); /** * Singleton: Remove possibility of duplicating object. */ Net(const Net&) = delete; // Remove copy constructor Net& operator=(const Net&) = delete; // Remove asignment operator };
22.763158
74
0.684393
edelkas
57a56c63473220c2da0c8dbe4d200fbadf9efd18
3,049
cpp
C++
SoundManager.cpp
thuxtable/thomas-was-late-tutorial
e9d333a62a903d5d951917b35b84268ceb1831df
[ "MIT" ]
null
null
null
SoundManager.cpp
thuxtable/thomas-was-late-tutorial
e9d333a62a903d5d951917b35b84268ceb1831df
[ "MIT" ]
null
null
null
SoundManager.cpp
thuxtable/thomas-was-late-tutorial
e9d333a62a903d5d951917b35b84268ceb1831df
[ "MIT" ]
null
null
null
#include "stdafx.h" #include "SoundManager.h" #include <SFML/Audio.hpp> using namespace sf; SoundManager::SoundManager() { //Load the sound in the buffers m_FireBuffer.loadFromFile("sound/fire1.wav"); m_FallInFireBuffer.loadFromFile("sound/fallinfire.wav"); m_FallInWaterBuffer.loadFromFile("sound/fallinwater.wav"); m_JumpBuffer.loadFromFile("sound/jump.wav"); m_ReachGoalBuffer.loadFromFile("sound/reachgoal.wav"); //Associate the sounds with the buffers m_Fire1Sound.setBuffer(m_FireBuffer); m_Fire2Sound.setBuffer(m_FireBuffer); m_Fire3Sound.setBuffer(m_FireBuffer); m_FallInFireSound.setBuffer(m_FallInFireBuffer); m_FallInWaterSound.setBuffer(m_FallInWaterBuffer); m_JumpSound.setBuffer(m_JumpBuffer); m_ReachGoalSound.setBuffer(m_ReachGoalBuffer); //When the player is 150 pixels away, the sound is full volume float minDistance = 150; //The sound reduces steadily as the player moves further away float attentuation = 15; //Set all attentuation levels m_Fire1Sound.setAttenuation(attentuation); m_Fire2Sound.setAttenuation(attentuation); m_Fire3Sound.setAttenuation(attentuation); //Set all min distance levels m_Fire1Sound.setMinDistance(minDistance); m_Fire2Sound.setMinDistance(minDistance); m_Fire3Sound.setMinDistance(minDistance); //Loop fire sounds when played m_Fire1Sound.setLoop(true); m_Fire2Sound.setLoop(true); m_Fire3Sound.setLoop(true); } void SoundManager::playFire(Vector2f emitterLocation, Vector2f listenerLocation) { //Where is Thomas, the listener Listener::setPosition(listenerLocation.x, listenerLocation.y, 0.0f); switch (m_NextSound) { case 1: //Locate/move the source of the sound m_Fire1Sound.setPosition(emitterLocation.x, emitterLocation.y, 0.0f); if (m_Fire1Sound.getStatus() == Sound::Status::Stopped) { //Play the sound, if it's not already playing m_Fire1Sound.play(); } break; case 2: m_Fire2Sound.setPosition(emitterLocation.x, emitterLocation.y, 0.0f); if (m_Fire1Sound.getStatus() == Sound::Status::Stopped) { //Play the sound, if it's not already playing m_Fire2Sound.play(); } break; case 3: m_Fire3Sound.setPosition(emitterLocation.x, emitterLocation.y, 0.0f); if (m_Fire1Sound.getStatus() == Sound::Status::Stopped) { //Play the sound, if it's not already playing m_Fire3Sound.play(); } break; } //End switch //Increment to the next fire sound m_NextSound++; //Go back to 1 when third has started if (m_NextSound > 3) { m_NextSound = 1; } } void SoundManager::playFallInFire(){ m_FallInFireSound.setRelativeToListener(true); m_FallInFireSound.play(); } void SoundManager::playFallInWater(){ m_FallInWaterSound.setRelativeToListener(true); m_FallInWaterSound.play(); } void SoundManager::playJump(){ m_JumpSound.setRelativeToListener(true); m_JumpSound.play(); } void SoundManager::playReachGoal() { m_ReachGoalSound.setRelativeToListener(true); m_ReachGoalSound.play(); }
27.718182
83
0.740899
thuxtable
57a586a31db0ed73304515c6257bcb4fd49a856f
809
hpp
C++
Runtime/GuiSys/CHudBossEnergyInterface.hpp
henriquegemignani/urde
78185e682e16c3e1b41294d92f2841357272acb2
[ "MIT" ]
1
2020-06-09T07:49:34.000Z
2020-06-09T07:49:34.000Z
Runtime/GuiSys/CHudBossEnergyInterface.hpp
henriquegemignani/urde
78185e682e16c3e1b41294d92f2841357272acb2
[ "MIT" ]
6
2020-06-09T07:49:45.000Z
2021-04-06T22:19:57.000Z
Runtime/GuiSys/CHudBossEnergyInterface.hpp
henriquegemignani/urde
78185e682e16c3e1b41294d92f2841357272acb2
[ "MIT" ]
null
null
null
#pragma once #include "Runtime/RetroTypes.hpp" #include <zeus/CVector3f.hpp> namespace urde { class CAuiEnergyBarT01; class CGuiFrame; class CGuiTextPane; class CGuiWidget; class CHudBossEnergyInterface { float x0_alpha = 0.f; float x4_fader = 0.f; float x8_curEnergy = 0.f; float xc_maxEnergy = 0.f; bool x10_24_visible : 1 = false; CGuiWidget* x14_basewidget_bossenergystuff; CAuiEnergyBarT01* x18_energybart01_bossbar; CGuiTextPane* x1c_textpane_boss; public: explicit CHudBossEnergyInterface(CGuiFrame& selHud); void Update(float dt); void SetAlpha(float a) { x0_alpha = a; } void SetBossParams(bool visible, std::u16string_view name, float curEnergy, float maxEnergy); static std::pair<zeus::CVector3f, zeus::CVector3f> BossEnergyCoordFunc(float t); }; } // namespace urde
26.096774
95
0.765142
henriquegemignani
57a5b85097776bebb42f508452cdfc7592037f12
541
cpp
C++
Codeforces/118A String Task.cpp
sreejonK19/online-judge-solutions
da65d635cc488c8f305e48b49727ad62649f5671
[ "MIT" ]
null
null
null
Codeforces/118A String Task.cpp
sreejonK19/online-judge-solutions
da65d635cc488c8f305e48b49727ad62649f5671
[ "MIT" ]
null
null
null
Codeforces/118A String Task.cpp
sreejonK19/online-judge-solutions
da65d635cc488c8f305e48b49727ad62649f5671
[ "MIT" ]
2
2018-11-06T19:37:56.000Z
2018-11-09T19:05:46.000Z
#include <bits/stdc++.h> using namespace std; char str[102]; int main( int argc, char ** argv ) { scanf( "%s", str ); int len = strlen( str ); for( int i = 0 ; i < len ; i++ ) { if( str[i] >= 'A' && str[i] <='Z' ) { str[i] = 'a' + (str[i] - 'A'); } } for( int i = 0 ; i < len ; i++ ) { if( str[i] != 'a' && str[i] != 'o' && str[i] != 'y' && str[i] != 'e' && str[i] != 'u' && str[i] != 'i' ) { printf( ".%c", str[i] ); } } printf( "\n" ); return 0; }
23.521739
114
0.358595
sreejonK19
57a9741f2146f092d4dbdc5156e43dd5eb8acbee
729
cpp
C++
uva/562.cpp
dk00/old-stuff
e1184684c85fe9bbd1ceba58b94d4da84c67784e
[ "Unlicense" ]
null
null
null
uva/562.cpp
dk00/old-stuff
e1184684c85fe9bbd1ceba58b94d4da84c67784e
[ "Unlicense" ]
null
null
null
uva/562.cpp
dk00/old-stuff
e1184684c85fe9bbd1ceba58b94d4da84c67784e
[ "Unlicense" ]
null
null
null
#include<stdio.h> #include<malloc.h> #include<math.h> main(){ int sum,min,*s1=(int *)malloc(sizeof(int)*50001),i,m, *tmp,k[100],*s2=(int *)malloc(sizeof(int)*50001),j,n; scanf("%d",&n); for(;n>0;n--){ scanf("%d",&m); for(sum=(i=0);i<m;i++){ scanf("%d",&k[i]); sum+=k[i]; s1[i]=(s2[i]=0); } for(min=sum;i<=sum;i++) s1[i]=(s2[i]=0); for(i=0,s1[0]=1;i<m;i++){ for(j=0;j+k[i]<=sum;j++){ s2[j]=(s1[j] || s2[j]); s2[j+k[i]]=s1[j]; } for(;j<=sum;j++) s2[j]=(s1[j] || s2[j]); tmp=s1;s1=s2;s2=tmp; } for(i=0;i<=sum;i++){ if(s1[i] && abs(sum-i*2)<min)min=abs(sum-i*2); } printf("%d\n",min); } }
22.78125
54
0.418381
dk00
57abe71a368dd98e118131317ce49f209b66e373
13,130
cpp
C++
src/qt/src/3rdparty/webkit/Source/WebCore/platform/graphics/cg/GraphicsContext3DCG.cpp
ant0ine/phantomjs
8114d44a28134b765ab26b7e13ce31594fa81253
[ "BSD-3-Clause" ]
46
2015-01-08T14:32:34.000Z
2022-02-05T16:48:26.000Z
src/qt/src/3rdparty/webkit/Source/WebCore/platform/graphics/cg/GraphicsContext3DCG.cpp
ant0ine/phantomjs
8114d44a28134b765ab26b7e13ce31594fa81253
[ "BSD-3-Clause" ]
7
2015-01-20T14:28:12.000Z
2017-01-18T17:21:44.000Z
src/qt/src/3rdparty/webkit/Source/WebCore/platform/graphics/cg/GraphicsContext3DCG.cpp
ant0ine/phantomjs
8114d44a28134b765ab26b7e13ce31594fa81253
[ "BSD-3-Clause" ]
14
2015-10-27T06:17:48.000Z
2020-03-03T06:15:50.000Z
/* * Copyright (C) 2010 Apple Inc. All rights reserved. * Copyright (C) 2010 Google Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 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 APPLE COMPUTER, INC. ``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 APPLE COMPUTER, INC. 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 "config.h" #if ENABLE(WEBGL) #include "GraphicsContext3D.h" #include "BitmapImage.h" #include "GraphicsContextCG.h" #include "Image.h" #include <CoreGraphics/CGBitmapContext.h> #include <CoreGraphics/CGContext.h> #include <CoreGraphics/CGDataProvider.h> #include <CoreGraphics/CGImage.h> #include <wtf/RetainPtr.h> namespace WebCore { enum SourceDataFormatBase { SourceFormatBaseR = 0, SourceFormatBaseA, SourceFormatBaseRA, SourceFormatBaseAR, SourceFormatBaseRGB, SourceFormatBaseRGBA, SourceFormatBaseARGB, SourceFormatBaseNumFormats }; enum AlphaFormat { AlphaFormatNone = 0, AlphaFormatFirst, AlphaFormatLast, AlphaFormatNumFormats }; // This returns SourceFormatNumFormats if the combination of input parameters is unsupported. static GraphicsContext3D::SourceDataFormat getSourceDataFormat(unsigned int componentsPerPixel, AlphaFormat alphaFormat, bool is16BitFormat, bool bigEndian) { const static SourceDataFormatBase formatTableBase[4][AlphaFormatNumFormats] = { // componentsPerPixel x AlphaFormat // AlphaFormatNone AlphaFormatFirst AlphaFormatLast { SourceFormatBaseR, SourceFormatBaseA, SourceFormatBaseA }, // 1 componentsPerPixel { SourceFormatBaseNumFormats, SourceFormatBaseAR, SourceFormatBaseRA }, // 2 componentsPerPixel { SourceFormatBaseRGB, SourceFormatBaseNumFormats, SourceFormatBaseNumFormats }, // 3 componentsPerPixel { SourceFormatBaseNumFormats, SourceFormatBaseARGB, SourceFormatBaseRGBA } // 4 componentsPerPixel }; const static GraphicsContext3D::SourceDataFormat formatTable[SourceFormatBaseNumFormats][4] = { // SourceDataFormatBase x bitsPerComponent x endian // 8bits, little endian 8bits, big endian 16bits, little endian 16bits, big endian { GraphicsContext3D::SourceFormatR8, GraphicsContext3D::SourceFormatR8, GraphicsContext3D::SourceFormatR16Little, GraphicsContext3D::SourceFormatR16Big }, { GraphicsContext3D::SourceFormatA8, GraphicsContext3D::SourceFormatA8, GraphicsContext3D::SourceFormatA16Little, GraphicsContext3D::SourceFormatA16Big }, { GraphicsContext3D::SourceFormatAR8, GraphicsContext3D::SourceFormatRA8, GraphicsContext3D::SourceFormatRA16Little, GraphicsContext3D::SourceFormatRA16Big }, { GraphicsContext3D::SourceFormatRA8, GraphicsContext3D::SourceFormatAR8, GraphicsContext3D::SourceFormatAR16Little, GraphicsContext3D::SourceFormatAR16Big }, { GraphicsContext3D::SourceFormatBGR8, GraphicsContext3D::SourceFormatRGB8, GraphicsContext3D::SourceFormatRGB16Little, GraphicsContext3D::SourceFormatRGB16Big }, { GraphicsContext3D::SourceFormatABGR8, GraphicsContext3D::SourceFormatRGBA8, GraphicsContext3D::SourceFormatRGBA16Little, GraphicsContext3D::SourceFormatRGBA16Big }, { GraphicsContext3D::SourceFormatBGRA8, GraphicsContext3D::SourceFormatARGB8, GraphicsContext3D::SourceFormatARGB16Little, GraphicsContext3D::SourceFormatARGB16Big } }; ASSERT(componentsPerPixel <= 4 && componentsPerPixel > 0); SourceDataFormatBase formatBase = formatTableBase[componentsPerPixel - 1][alphaFormat]; if (formatBase == SourceFormatBaseNumFormats) return GraphicsContext3D::SourceFormatNumFormats; return formatTable[formatBase][(is16BitFormat ? 2 : 0) + (bigEndian ? 1 : 0)]; } bool GraphicsContext3D::getImageData(Image* image, GC3Denum format, GC3Denum type, bool premultiplyAlpha, bool ignoreGammaAndColorProfile, Vector<uint8_t>& outputVector) { if (!image) return false; CGImageRef cgImage; RetainPtr<CGImageRef> decodedImage; bool hasAlpha = image->isBitmapImage() ? static_cast<BitmapImage*>(image)->frameHasAlphaAtIndex(0) : true; if ((ignoreGammaAndColorProfile || (hasAlpha && !premultiplyAlpha)) && image->data()) { ImageSource decoder(ImageSource::AlphaNotPremultiplied, ignoreGammaAndColorProfile ? ImageSource::GammaAndColorProfileIgnored : ImageSource::GammaAndColorProfileApplied); decoder.setData(image->data(), true); if (!decoder.frameCount()) return false; decodedImage.adoptCF(decoder.createFrameAtIndex(0)); cgImage = decodedImage.get(); } else cgImage = image->nativeImageForCurrentFrame(); if (!cgImage) return false; size_t width = CGImageGetWidth(cgImage); size_t height = CGImageGetHeight(cgImage); if (!width || !height) return false; // See whether the image is using an indexed color space, and if // so, re-render it into an RGB color space. The image re-packing // code requires color data, not color table indices, for the // image data. CGColorSpaceRef colorSpace = CGImageGetColorSpace(cgImage); CGColorSpaceModel model = CGColorSpaceGetModel(colorSpace); if (model == kCGColorSpaceModelIndexed) { RetainPtr<CGContextRef> bitmapContext; // FIXME: we should probably manually convert the image by indexing into // the color table, which would allow us to avoid premultiplying the // alpha channel. Creation of a bitmap context with an alpha channel // doesn't seem to work unless it's premultiplied. bitmapContext.adoptCF(CGBitmapContextCreate(0, width, height, 8, width * 4, deviceRGBColorSpaceRef(), kCGImageAlphaPremultipliedFirst | kCGBitmapByteOrder32Host)); if (!bitmapContext) return false; CGContextSetBlendMode(bitmapContext.get(), kCGBlendModeCopy); CGContextSetInterpolationQuality(bitmapContext.get(), kCGInterpolationNone); CGContextDrawImage(bitmapContext.get(), CGRectMake(0, 0, width, height), cgImage); // Now discard the original CG image and replace it with a copy from the bitmap context. decodedImage.adoptCF(CGBitmapContextCreateImage(bitmapContext.get())); cgImage = decodedImage.get(); } size_t bitsPerComponent = CGImageGetBitsPerComponent(cgImage); size_t bitsPerPixel = CGImageGetBitsPerPixel(cgImage); if (bitsPerComponent != 8 && bitsPerComponent != 16) return false; if (bitsPerPixel % bitsPerComponent) return false; size_t componentsPerPixel = bitsPerPixel / bitsPerComponent; CGBitmapInfo bitInfo = CGImageGetBitmapInfo(cgImage); bool bigEndianSource = false; // These could technically be combined into one large switch // statement, but we prefer not to so that we fail fast if we // encounter an unexpected image configuration. if (bitsPerComponent == 16) { switch (bitInfo & kCGBitmapByteOrderMask) { case kCGBitmapByteOrder16Big: bigEndianSource = true; break; case kCGBitmapByteOrder16Little: bigEndianSource = false; break; case kCGBitmapByteOrderDefault: // This is a bug in earlier version of cg where the default endian // is little whereas the decoded 16-bit png image data is actually // Big. Later version (10.6.4) no longer returns ByteOrderDefault. bigEndianSource = true; break; default: return false; } } else { switch (bitInfo & kCGBitmapByteOrderMask) { case kCGBitmapByteOrder32Big: bigEndianSource = true; break; case kCGBitmapByteOrder32Little: bigEndianSource = false; break; case kCGBitmapByteOrderDefault: // It appears that the default byte order is actually big // endian even on little endian architectures. bigEndianSource = true; break; default: return false; } } AlphaOp neededAlphaOp = AlphaDoNothing; AlphaFormat alphaFormat = AlphaFormatNone; switch (CGImageGetAlphaInfo(cgImage)) { case kCGImageAlphaPremultipliedFirst: if (!premultiplyAlpha) neededAlphaOp = AlphaDoUnmultiply; alphaFormat = AlphaFormatFirst; break; case kCGImageAlphaFirst: // This path is only accessible for MacOS earlier than 10.6.4. if (premultiplyAlpha) neededAlphaOp = AlphaDoPremultiply; alphaFormat = AlphaFormatFirst; break; case kCGImageAlphaNoneSkipFirst: // This path is only accessible for MacOS earlier than 10.6.4. alphaFormat = AlphaFormatFirst; break; case kCGImageAlphaPremultipliedLast: if (!premultiplyAlpha) neededAlphaOp = AlphaDoUnmultiply; alphaFormat = AlphaFormatLast; break; case kCGImageAlphaLast: if (premultiplyAlpha) neededAlphaOp = AlphaDoPremultiply; alphaFormat = AlphaFormatLast; break; case kCGImageAlphaNoneSkipLast: alphaFormat = AlphaFormatLast; break; case kCGImageAlphaNone: alphaFormat = AlphaFormatNone; break; default: return false; } SourceDataFormat srcDataFormat = getSourceDataFormat(componentsPerPixel, alphaFormat, bitsPerComponent == 16, bigEndianSource); if (srcDataFormat == SourceFormatNumFormats) return false; RetainPtr<CFDataRef> pixelData; pixelData.adoptCF(CGDataProviderCopyData(CGImageGetDataProvider(cgImage))); if (!pixelData) return false; const UInt8* rgba = CFDataGetBytePtr(pixelData.get()); outputVector.resize(width * height * 4); unsigned int srcUnpackAlignment = 0; size_t bytesPerRow = CGImageGetBytesPerRow(cgImage); unsigned int padding = bytesPerRow - bitsPerPixel / 8 * width; if (padding) { srcUnpackAlignment = padding + 1; while (bytesPerRow % srcUnpackAlignment) ++srcUnpackAlignment; } bool rt = packPixels(rgba, srcDataFormat, width, height, srcUnpackAlignment, format, type, neededAlphaOp, outputVector.data()); return rt; } void GraphicsContext3D::paintToCanvas(const unsigned char* imagePixels, int imageWidth, int imageHeight, int canvasWidth, int canvasHeight, CGContextRef context) { if (!imagePixels || imageWidth <= 0 || imageHeight <= 0 || canvasWidth <= 0 || canvasHeight <= 0 || !context) return; int rowBytes = imageWidth * 4; RetainPtr<CGDataProviderRef> dataProvider(AdoptCF, CGDataProviderCreateWithData(0, imagePixels, rowBytes * imageHeight, 0)); RetainPtr<CGImageRef> cgImage(AdoptCF, CGImageCreate(imageWidth, imageHeight, 8, 32, rowBytes, deviceRGBColorSpaceRef(), kCGImageAlphaPremultipliedFirst | kCGBitmapByteOrder32Host, dataProvider.get(), 0, false, kCGRenderingIntentDefault)); // CSS styling may cause the canvas's content to be resized on // the page. Go back to the Canvas to figure out the correct // width and height to draw. CGRect rect = CGRectMake(0, 0, canvasWidth, canvasHeight); // We want to completely overwrite the previous frame's // rendering results. CGContextSaveGState(context); CGContextSetBlendMode(context, kCGBlendModeCopy); CGContextSetInterpolationQuality(context, kCGInterpolationNone); CGContextDrawImage(context, rect, cgImage.get()); CGContextRestoreGState(context); } } // namespace WebCore #endif // ENABLE(WEBGL)
46.725979
184
0.695506
ant0ine
57ac3fb47e1ebac7f43a3a91551508cf2387b2b8
8,114
hpp
C++
adaptors/fftw/mpi.hpp
correaa/b-multi
1e961f877662aa7a26933834f9064d2ec8b00b4a
[ "Intel" ]
null
null
null
adaptors/fftw/mpi.hpp
correaa/b-multi
1e961f877662aa7a26933834f9064d2ec8b00b4a
[ "Intel" ]
11
2020-05-09T20:57:21.000Z
2020-06-10T00:00:17.000Z
adaptors/fftw/mpi.hpp
correaa/b-multi
1e961f877662aa7a26933834f9064d2ec8b00b4a
[ "Intel" ]
null
null
null
#if COMPILATION// -*-indent-tabs-mode:t;c-basic-offset:4;tab-width:4;-*- ln -sf $0 $0.cpp;mpicxx -g -I$HOME/prj/alf $0.cpp -o $0x -lfftw3 -lfftw3_mpi&&time mpirun -n 4 $0x&&rm $0x $0.cpp;exit #ln -sf $0 $0.cpp;mpicxx -g -I$HOME/prj/alf $0.cpp -o $0x -lfftw3 -lfftw3_mpi&&time mpirun -n 4 valgrind --leak-check=full --track-origins=yes --show-leak-kinds=all --suppressions=$HOME/prj/alf/boost/mpi3/test/communicator_main.cpp.openmpi.supp --error-exitcode=1 $0x&&rm $0x $0.cpp;exit #endif // © Alfredo A. Correa 2020 // apt-get install libfftw3-mpi-dev // compile with: mpicc simple_mpi_example.c -Wl,-rpath=/usr/local/lib -lfftw3_mpi -lfftw3 -o simple_mpi_example */ #include "../../array.hpp" #include "../../config/NODISCARD.hpp" #include<boost/mpi3/communicator.hpp> #include<boost/mpi3/environment.hpp> #include "../fftw.hpp" #include <fftw3-mpi.h> namespace boost{ namespace multi{ namespace fftw{ template<typename T> struct allocator : std::allocator<T>{ template <typename U> struct rebind{using other = fftw::allocator<U>;}; NODISCARD("to avoid memory leak") T* allocate(std::size_t n){ return static_cast<T*>(fftw_malloc(sizeof(T)*n));} void deallocate(T* data, std::size_t){fftw_free(data);} }; namespace mpi{ struct environment{ environment(){fftw_mpi_init();} ~environment(){fftw_mpi_cleanup();} }; template<class T, multi::dimensionality_type D, class Alloc = fftw::allocator<T>> struct array; namespace bmpi3 = boost::mpi3; template<class T, class Alloc> struct array<T, multi::dimensionality_type{2}, Alloc>{ using element_type = T; mutable bmpi3::communicator comm_; Alloc alloc_; typename std::allocator_traits<Alloc>::size_type local_count_; array_ptr<T, 2, typename std::allocator_traits<Alloc>::pointer> local_ptr_; ptrdiff_t n0_; static std::pair<typename std::allocator_traits<Alloc>::size_type, multi::extensions_type_<2>> local_2d(multi::extensions_type_<2> ext, boost::mpi3::communicator const& comm){ ptrdiff_t local_n0, local_0_start; auto count = fftw_mpi_local_size_2d(std::get<0>(ext).size(), std::get<1>(ext).size(), comm.get(), &local_n0, &local_0_start); assert( count >= local_n0*std::get<1>(ext).size() ); return {count, {{local_0_start, local_0_start + local_n0}, std::get<1>(ext)}}; } static auto local_count_2d(multi::extensions_type_<2> ext, boost::mpi3::communicator const& comm){ return local_2d(ext, comm).first; } static auto local_extension_2d(multi::extensions_type_<2> ext, boost::mpi3::communicator const& comm){ return local_2d(ext, comm).second; } array(multi::extensions_type_<2> ext, bmpi3::communicator comm = mpi3::environment::self(), Alloc alloc = {}) : comm_{std::move(comm)}, alloc_{alloc}, local_count_{local_count_2d(ext, comm_)}, local_ptr_ {alloc_.allocate(local_count_), local_extension_2d(ext, comm_)}, n0_{multi::layout_t<2>(ext).size()} { if(not std::is_trivially_default_constructible<element_type>{}) adl_alloc_uninitialized_default_construct_n(alloc_, local_ptr_->base(), local_ptr_->num_elements()); } bmpi3::communicator& comm() const&{return comm_;} array(array const& other) : comm_ {other.comm_}, alloc_ {other.alloc_}, local_count_{other.local_count_}, local_ptr_ {alloc_.allocate(local_count_), local_extension_2d(other.extensions(), comm_)}, n0_{multi::layout_t<2>(other.extensions()).size()} { local_cutout() = other.local_cutout(); } array(array&& other) : comm_ {std::move(other.comm_)}, alloc_ {std::move(other.alloc_)}, local_count_{std::exchange(other.local_count_, 0)}, local_ptr_ {std::exchange(other.local_ptr_, nullptr)}, n0_{multi::layout_t<2>(other.extensions()).size()} {} explicit array(multi::array<T, 2> const& other, bmpi3::communicator comm = mpi3::environment::self(), Alloc alloc = {}) : array(other.extensions(), comm, alloc) { local_cutout() = other.stenciled(std::get<0>(local_cutout().extensions()), std::get<1>(local_cutout().extensions())); } bool empty() const{return extensions().num_elements();} array_ref <T, 2> local_cutout() &{return *local_ptr_;} array_cref<T, 2> local_cutout() const&{return *local_ptr_;} ptrdiff_t local_count() const&{return local_count_;} multi::extensions_type_<2> extensions() const&{return {n0_, std::get<1>(local_cutout().extensions())};} ptrdiff_t num_elements() const&{return multi::layout_t<2>(extensions()).num_elements();} operator multi::array<T, 2>() const&{ static_assert( std::is_trivially_copy_assignable<T>{}, "!" ); multi::array<T, 2> ret(extensions(), alloc_); comm_.all_gatherv_n(local_cutout().data_elements(), local_cutout().num_elements(), ret.data_elements()); return ret; } array& operator=(multi::array<T, 2> const& other) &{ if(other.extensions() == extensions()) local_cutout() = other.stenciled(std::get<0>(local_cutout().extensions()), std::get<1>(local_cutout().extensions())); else{ array tmp{other}; std::swap(*this, tmp); } return *this; } bool operator==(multi::array<T, 2> const& other) const&{ if(other.extensions() != extensions()) return false; return comm_&=(local_cutout() == other.stenciled(std::get<0>(local_cutout().extensions()), std::get<1>(local_cutout().extensions()))); } friend bool operator==(multi::array<T, 2> const& other, array const& self){ return self.operator==(other); } bool operator==(array<T, 2> const& other) const&{assert(comm_==other.comm_); return comm_&=(local_cutout() == other.local_cutout()); } array& operator=(array const& other)&{ if(other.extensions() == this->extensions() and other.comm_ == other.comm_) local_cutout() = other.local_cutout(); else assert(0); return *this; } ~array() noexcept{alloc_.deallocate(local_cutout().data_elements(), local_count_);} }; array<std::complex<double>, 2>& dft(array<std::complex<double>, 2> const& A, array<std::complex<double>, 2>& B, fftw::sign s){ assert( A.extensions() == B.extensions() ); assert( A.comm() == B.comm() ); fftw_plan p = fftw_mpi_plan_dft_2d( std::get<0>(A.extensions()).size(), std::get<1>(A.extensions()).size(), (fftw_complex *)A.local_cutout().data_elements(), (fftw_complex *)B.local_cutout().data_elements(), A.comm().get(), s, FFTW_ESTIMATE ); fftw_execute(p); fftw_destroy_plan(p); return B; } array<std::complex<double>, 2>& dft_forward(array<std::complex<double>, 2> const& A, array<std::complex<double>, 2>& B){ return dft(A, B, fftw::forward); } array<std::complex<double>, 2> dft_forward(array<std::complex<double>,2> const& A){ array<std::complex<double>, 2> ret(A.extensions()); dft_forward(A, ret); return ret; } }}}} #if not __INCLUDE_LEVEL__ #include<boost/mpi3/main.hpp> #include<boost/mpi3/environment.hpp> #include<boost/mpi3/ostream.hpp> #include "../fftw.hpp" namespace mpi3 = boost::mpi3; namespace multi = boost::multi; int mpi3::main(int, char*[], mpi3::communicator world){ multi::fftw::mpi::environment fenv; multi::fftw::mpi::array<std::complex<double>, 2> A({41, 321}, world); mpi3::ostream os{world}; os<< "global sizes" << std::get<0>(A.extensions()) <<'x'<< std::get<1>(A.extensions()) <<' '<< A.num_elements() <<std::endl; os<< A.local_cutout().extension() <<'x'<< std::get<1>(A.local_cutout().extensions()) <<"\t#="<< A.local_cutout().num_elements() <<" allocated "<< A.local_count() <<std::endl; { auto x = A.local_cutout().extensions(); for(auto i : std::get<0>(x)) for(auto j : std::get<1>(x)) A.local_cutout()[i][j] = std::complex<double>(i + j, i + 2*j + 1)/std::abs(std::complex<double>(i + j, i + 2*j + 1)); } multi::array<std::complex<double>, 2> A2 = A; assert( A2 == A ); using multi::fftw::dft_forward; dft_forward(A , A ); dft_forward(A2, A2); { auto x = A.local_cutout().extensions(); for(auto i : std::get<0>(x)) for(auto j : std::get<1>(x)) if(not( std::abs(A.local_cutout()[i][j] - A2[i][j]) < 1e-12 )){ std::cout << A.local_cutout()[i][j] - A2[i][j] <<' '<< std::abs(A.local_cutout()[i][j] - A2[i][j]) << std::endl; } } return 0; } #endif
39.009615
287
0.678087
correaa
57ac65275f24017930aaba052830defa1b3b4019
14,297
cpp
C++
src/runtime/base/memory/smart_allocator.cpp
burhan/hiphop-php
6e02d7072a02fbaad1856878c2515e35f7e529f0
[ "PHP-3.01", "Zend-2.0" ]
null
null
null
src/runtime/base/memory/smart_allocator.cpp
burhan/hiphop-php
6e02d7072a02fbaad1856878c2515e35f7e529f0
[ "PHP-3.01", "Zend-2.0" ]
null
null
null
src/runtime/base/memory/smart_allocator.cpp
burhan/hiphop-php
6e02d7072a02fbaad1856878c2515e35f7e529f0
[ "PHP-3.01", "Zend-2.0" ]
null
null
null
/* +----------------------------------------------------------------------+ | HipHop for PHP | +----------------------------------------------------------------------+ | Copyright (c) 2010- Facebook, Inc. (http://www.facebook.com) | +----------------------------------------------------------------------+ | This source file is subject to version 3.01 of the PHP license, | | that is bundled with this package in the file LICENSE, and is | | available through the world-wide-web at the following url: | | http://www.php.net/license/3_01.txt | | If you did not receive a copy of the PHP license and are unable to | | obtain it through the world-wide-web, please send a note to | | license@php.net so we can mail you a copy immediately. | +----------------------------------------------------------------------+ */ #include <runtime/base/memory/smart_allocator.h> #include <runtime/base/memory/memory_manager.h> #include <runtime/base/resource_data.h> #include <runtime/base/server/server_stats.h> #include <runtime/base/runtime_option.h> #include <util/logger.h> /* * Enabling these will prevent us from allocating out of the free list * and cause deallocated objects to be filled with garbage. This is * intended for detecting data that is freed too eagerly. */ #if defined(SMART_ALLOCATOR_DEBUG_FREE) && !defined(DETECT_DOUBLE_FREE) # define DETECT_DOUBLE_FREE #endif namespace HPHP { /////////////////////////////////////////////////////////////////////////////// // initializer std::set<AllocatorThreadLocalInit>& GetAllocatorInitList() { static std::set<AllocatorThreadLocalInit> allocatorInitList; return allocatorInitList; } void InitAllocatorThreadLocal() { for (std::set<AllocatorThreadLocalInit>::iterator it = GetAllocatorInitList().begin(); it != GetAllocatorInitList().end(); it++) { (*it)(); } } /////////////////////////////////////////////////////////////////////////////// // helpers static int calculate_item_count(int itemSize) { int itemCount = SLAB_SIZE / itemSize; if (itemCount == 0) { itemCount = 1; } else if (itemCount > MAX_OBJECT_COUNT_PER_SLAB) { itemCount = MAX_OBJECT_COUNT_PER_SLAB; } return itemCount; } static int findIndex(const vector<char *> &blocks, const BlockIndexMap &blockIndex, int64 p, int colMax) { // First try int64 hit = p / colMax; BlockIndexMap::const_iterator it = blockIndex.find(hit); if (it != blockIndex.end()) { int idx = it->second; if ((int64)blocks[idx] <= p) { return idx; } } // Second try, and it must be correct hit--; ASSERT(blockIndex.find(hit) != blockIndex.end() && (int64)blocks[blockIndex.find(hit)->second] <= p); return blockIndex.find(hit)->second; } /////////////////////////////////////////////////////////////////////////////// // constructor and destructor SmartAllocatorImpl::SmartAllocatorImpl(int nameEnum, int itemCount, int itemSize, int flag) : m_itemSize(itemSizeRoundup(itemSize)) , m_row(0) , m_nameEnum(Name(nameEnum)) , m_itemCount(itemCount) , m_flag(flag) , m_allocatedBlocks(0) , m_multiplier(1) , m_maxMultiplier(1) , m_targetMultiplier(1) { // automatically pick a good per slab item count if (m_itemCount <= 0) { m_itemCount = SLAB_SIZE / m_itemSize; switch (nameEnum) { case GlobalVariables: m_itemCount = 1; break; case RefData: case Variant: case SharedMap: m_itemCount = 128; // rarely used items belong to this group m_maxMultiplier = SLAB_SIZE / (m_itemSize * m_itemCount); ASSERT(m_maxMultiplier >= 1); break; case ObjectData: m_itemCount = calculate_item_count(m_itemSize); m_maxMultiplier = SLAB_SIZE / (m_itemSize * m_itemCount); ASSERT(m_maxMultiplier >= 1); break; case Bucket: m_itemCount *= 4; // we need lots of Buckets break; default: break; } } ASSERT(itemCount); ASSERT(itemSize); m_colMax = m_itemSize * m_itemCount; char *p = (char *)malloc(m_colMax); m_next = p; m_limit = p + m_colMax; m_blocks.push_back(p); m_blockIndex[((int64)p) / m_colMax] = 0; // Cancel out jemalloc's accounting for this slab. MemoryUsageStats* stats = &MemoryManager::TheMemoryManager()->getStats(); JEMALLOC_STATS_ADJUST(stats, m_colMax); stats->alloc += m_colMax; if (stats->alloc > stats->peakAlloc) { stats->peakAlloc = stats->alloc; } if (nameEnum < 0) { m_name = "(unknown)"; } else { static const char *TypeNames[] = { #define SMART_ALLOCATOR_ENTRY(x) #x, #include "runtime/base/memory/smart_allocator.inc_gen" #undef SMART_ALLOCATOR_ENTRY }; ASSERT(nameEnum < (int)(sizeof(TypeNames)/sizeof(TypeNames[0]))); m_name = TypeNames[nameEnum]; } MemoryManager::TheMemoryManager()->add(this); } SmartAllocatorImpl::~SmartAllocatorImpl() { unsigned int size = m_blocks.size(); for (unsigned int i = 0; i < size; i += m_multiplier) { free(m_blocks[i]); } } /////////////////////////////////////////////////////////////////////////////// // alloc/dealloc helpers HOT_FUNC void *SmartAllocatorImpl::alloc(size_t nbytes) { ASSERT(nbytes == size_t(m_itemSize)); ASSERT(m_next && m_next <= m_limit); // Just update the usage, while the peakUsage is maintained by // FrameInjection. MemoryUsageStats* stats = &MemoryManager::TheMemoryManager()->getStats(); int64 usage = (stats->usage += nbytes); if (hhvm && UNLIKELY(usage > stats->maxBytes)) { // It's possible that this simplified check will trip later than // it should in a perfect world but it's cheaper than a full call // to refreshStats on every alloc(). MemoryManager::TheMemoryManager()->refreshStatsHelper(); } #ifndef SMART_ALLOCATOR_DEBUG_FREE void* freelist_value = m_freelist.maybePop(); if (LIKELY(freelist_value != NULL)) return freelist_value; #endif char* p = m_next; if (LIKELY(p + nbytes <= m_limit)) { m_next = p + nbytes; return p; } // Slow path return allocHelper(); } void *SmartAllocatorImpl::allocHelper() { ASSERT(m_next == m_limit); if (m_allocatedBlocks == 0) { // used up the last batch ASSERT(m_blocks.size() % m_multiplier == 0); size_t size = m_colMax * m_multiplier; char *p = (char *)malloc(size); m_blocks.push_back(p); m_blockIndex[((int64)p) / m_colMax] = m_blocks.size() - 1; // Cancel out jemalloc's accounting for this slab. MemoryUsageStats* stats = &MemoryManager::TheMemoryManager()->getStats(); JEMALLOC_STATS_ADJUST(stats, size); m_allocatedBlocks = m_multiplier - 1; stats->alloc += size; if (stats->alloc > stats->peakAlloc) { stats->peakAlloc = stats->alloc; } } else { // still have some blocks left from the last batch char *p = m_blocks.back() + m_colMax; m_blocks.push_back(p); m_blockIndex[((int64)p) / m_colMax] = m_blocks.size() - 1; m_allocatedBlocks--; } m_row++; ASSERT(m_row == (int)m_blocks.size() - 1); char *p = m_blocks[m_row]; m_next = p + m_itemSize; m_limit = p + m_colMax; return p; } bool SmartAllocatorImpl::assertValidHelper(void *obj) const { if (obj) { #ifdef DETECT_DOUBLE_FREE GarbageList *fl = const_cast<GarbageList *>(&m_freelist); for (GarbageList::iterator it = fl->begin(); it != fl->end(); ++it) { void *p = *it; if (p == obj) return false; } #endif // Check obj is indeed from a slab. int idx = findIndex(m_blocks, m_blockIndex, (int64)obj, m_colMax); char *block = m_blocks[idx]; return obj >= block && obj < block + m_colMax && (((char*)obj - block) % m_itemSize) == 0; } return false; } bool SmartAllocatorImpl::isFromThisAllocator(void* p) const { for (size_t i = 0; i < m_blocks.size(); ++i) { if (p >= m_blocks[i] && p < m_blocks[i] + m_colMax) { return true; } } return false; } /////////////////////////////////////////////////////////////////////////////// // SmartAllocatorManager methods HOT_FUNC void SmartAllocatorImpl::rollbackObjects() { // sweep dangling objects if (m_flag & NeedSweep) { FreeMap freeMap; prepareFreeMap(freeMap); int max = m_colMax; int bitIndex = 0; for (unsigned int i = 0; i < m_blocks.size(); i++) { char *start = (char *)m_blocks[i]; if (i == m_blocks.size() - 1) max = m_next - start; for (char *obj = start; obj < start + max; obj += m_itemSize, bitIndex++) { if (!freeMap.test(bitIndex)) { sweep(obj); } } } } m_freelist.clear(); // update the target multiplier m_targetMultiplier += m_blocks.size(); m_targetMultiplier >>= 1; int newMultiplier = m_multiplier; // adjust the multiplier, but not too fast if (m_multiplier < m_targetMultiplier) { newMultiplier <<= 1; if (newMultiplier > m_maxMultiplier) newMultiplier = m_maxMultiplier; } else if ((m_multiplier >> 1) >= m_targetMultiplier && m_multiplier >= 2) { newMultiplier >>= 1; } m_blockIndex.clear(); ASSERT(m_freelist.empty()); for (unsigned int i = m_multiplier; i < m_blocks.size(); i += m_multiplier) { free(m_blocks[i]); } m_blocks.resize(1); if (m_multiplier != newMultiplier) { // don't use realloc because we don't want to pay for its memcpy. free(m_blocks[0]); m_blocks[0] = (char*) malloc(m_colMax * newMultiplier); } m_blockIndex[((int64)m_blocks[0]) / m_colMax] = 0; m_multiplier = newMultiplier; // reset for new allocations m_allocatedBlocks = m_multiplier - 1; m_row = 0; m_next = m_blocks[0]; m_limit = m_next + m_colMax; } void SmartAllocatorImpl::checkMemory(bool detailed) { int col = m_next - m_blocks[m_row]; int allocated = m_itemCount * m_row + (col / m_itemSize); int freed = m_freelist.size(); printf("%16s (%6d bytes %6d x %3d): %s %8d alloc %8d free\n", m_name, m_itemSize, m_itemCount, (m_row + 1), freed != allocated ? "bad" : "ok ", allocated, freed); if (detailed) { std::set<void *> freelist; int index = 0; #define MAX_REPORT 10 int count = MAX_REPORT; for (GarbageList::iterator it = m_freelist.begin(); it != m_freelist.end(); ++it) { void *p = *it; if (freelist.find(p) != freelist.end()) { if (--count == -1) { printf("stopped reporting more than %d double-freed items\n", MAX_REPORT); } else if (count > 0) { printf("Double-freed Item %d:\n", ++index); dump(p); } } else { freelist.insert(p); } } index = 0; count = MAX_REPORT; for (int i = 0; i <= m_row; i++) { int jmax = m_colMax; if (i == m_row) jmax = m_next - m_blocks[i]; for (int j = 0; j < jmax; j += m_itemSize) { void *p = m_blocks[i] + j; if (freelist.find(p) == freelist.end()) { if (--count == -1) { printf("stopped reporting more than %d leaked items\n", MAX_REPORT); } else if (count > 0) { printf("Leaked Item at {%d:%d} %d:\n", i, j/m_itemSize, ++index); dump(p); } } else { freelist.erase(p); } } } count = MAX_REPORT; for (std::set<void *>::const_iterator iter = freelist.begin(); iter != freelist.end(); ++iter) { if (--count == -1) { printf("stopped reporting more than %d invalid items\n", MAX_REPORT); } else if (count > 0) { void *p = *iter; printf("Invalid Item %p:\n", p); } } } } HOT_FUNC void SmartAllocatorImpl::prepareFreeMap(FreeMap& freeMap) const { ASSERT(freeMap.empty()); freeMap.resize(m_blocks.size() * m_itemCount); for (GarbageList::iterator it = m_freelist.begin(); it != m_freelist.end(); ++it) { int64 freed = (int64)(*it); int idx = findIndex(m_blocks, m_blockIndex, freed, m_colMax); // no double free! ASSERT(!freeMap.test(idx * m_itemCount + (freed - (int64)m_blocks[idx]) / m_itemSize)); freeMap.set(idx * m_itemCount + (freed - (int64)m_blocks[idx]) / m_itemSize); } } /////////////////////////////////////////////////////////////////////////////// static bool is_object_alive(char* caddr) { return *reinterpret_cast<int*>(caddr + FAST_REFCOUNT_OFFSET) != RefCountTombstoneValue; } static bool UNUSED is_iterable_type(SmartAllocatorImpl::Name type) { return type == SmartAllocatorImpl::Variant || type == SmartAllocatorImpl::RefData || type == SmartAllocatorImpl::ObjectData || type == SmartAllocatorImpl::StringData || type == SmartAllocatorImpl::HphpArray || type == SmartAllocatorImpl::VectorArray || type == SmartAllocatorImpl::ZendArray; } SmartAllocatorImpl::Iterator::Iterator(const SmartAllocatorImpl* sa) : m_sa(*sa) , m_row(0) , m_col(-m_sa.m_itemSize) { ASSERT(hhvm); ASSERT(is_iterable_type(sa->getAllocatorType())); next(); } void* SmartAllocatorImpl::Iterator::current() const { return m_row == -1 ? 0 : m_sa.m_blocks[m_row] + m_col; } void SmartAllocatorImpl::Iterator::next() { do { m_col += m_sa.m_itemSize; if (m_col >= m_sa.m_colMax) { ASSERT(m_col == m_sa.m_colMax); if (++m_row >= m_sa.m_row) { m_row = -1; return; } m_col = 0; } int col = m_sa.m_next - m_sa.m_blocks[m_sa.m_row]; if (m_row == m_sa.m_row && m_col >= col) { m_row = -1; return; } } while (!is_object_alive(static_cast<char*>(current()))); } /////////////////////////////////////////////////////////////////////////////// // ObjectAllocator classes ObjectAllocatorBase::ObjectAllocatorBase(int itemSize) : SmartAllocatorImpl(SmartAllocatorImpl::ObjectData, -1, itemSize, SmartAllocatorImpl::NoCallbacks) { } void ObjectAllocatorBase::sweep(void *p) { // do nothing } void ObjectAllocatorBase::dump(void *p) { printf("%p", p); } /////////////////////////////////////////////////////////////////////////////// }
30.945887
79
0.585927
burhan
57adea372917bbbcf7eae81f58b06a7d8bd1f7ac
1,038
hpp
C++
engine/Engine.hpp
InfiniBrains/mobagen
262fa833195cd1b32f82ee4d825b0a39e7ebe4cb
[ "WTFPL" ]
32
2017-12-29T16:44:35.000Z
2021-08-06T23:10:28.000Z
engine/Engine.hpp
InfiniBrains/mobagen
262fa833195cd1b32f82ee4d825b0a39e7ebe4cb
[ "WTFPL" ]
66
2017-12-29T16:37:35.000Z
2019-04-19T23:57:20.000Z
engine/Engine.hpp
InfiniBrains/mobagen
262fa833195cd1b32f82ee4d825b0a39e7ebe4cb
[ "WTFPL" ]
7
2017-12-29T16:49:53.000Z
2021-08-06T23:10:35.000Z
#pragma once #include <chrono> #include "GLManager.hpp" #include "Window.hpp" #include "GLEWManager.hpp" #include "PhysicsManager.hpp" #include "Game.hpp" #include "Input.hpp" namespace mobagen { class Engine { public: Engine(Game *game, char *windowTitle, glm::vec2 windowSize); ~Engine(void); #ifdef EMSCRIPTEN static void loop(void); #endif void tick(void); void start(void); Window *getWindow(void) const; GLManager *getGLManager(void) const; PhysicsManager *getPhysicsManager(void) const; std::chrono::microseconds getDeltaTime(void) const; private: std::unique_ptr<Window> m_window; std::unique_ptr<GLEWManager> m_glewManager; std::unique_ptr<GLManager> m_glManager; std::unique_ptr<PhysicsManager> m_physicsManager; std::chrono::high_resolution_clock::time_point m_time, m_lastTime; std::chrono::microseconds m_deltaTime; //std::chrono::high_resolution_clock::time_point m_physicsTimeSimulated; Game *game; bool quit, m_fireRay; }; }
19.961538
76
0.714836
InfiniBrains
57aeafc36db70ae263debb875f1aab33a499d4d9
7,683
cpp
C++
src/ppu.cpp
ceanrim/CarmiNES
f0f20b95dba916893b4c4eb41f4b15e4fd075df1
[ "BSD-2-Clause" ]
2
2018-02-15T07:40:35.000Z
2018-09-22T21:17:33.000Z
src/ppu.cpp
ceanrim/CarmiNES
f0f20b95dba916893b4c4eb41f4b15e4fd075df1
[ "BSD-2-Clause" ]
null
null
null
src/ppu.cpp
ceanrim/CarmiNES
f0f20b95dba916893b4c4eb41f4b15e4fd075df1
[ "BSD-2-Clause" ]
null
null
null
/* ======================================================================== File: Date: Revision: Creator: Carmine Foggia ======================================================================== */ /*TODO: *Simulate PPU registers completely and properly *Emulate read/write buffering *Emulate sprites *Emulate scanline timing *PAL */ #include <windows.h> #include "main.h" #include "nesclass.h" #include "ppu.h" PPUClass::PPUClass() :LastEmulatedCycle(0), Scanline(261), Dot(0), VRAMAddr(0), PPUADDRWriteTick(0) { memset(OAM, 0, 256); Register2002 = 0; } void PPUClass::Init(unsigned short Mapper) { switch(Mapper) { case 0: { CHRROM = NES.ROMFile + 16 + NES.RAM.PRGROMSize; PatternTables[0] = CHRROM; PatternTables[1] = CHRROM + 4096; if(Mirroring & 8) //Four screen VRAM/No mirroring { Nametables[0] = Nametable0; Nametables[1] = Nametable1; Nametables[2] = Nametable2; Nametables[3] = Nametable3; } else if(Mirroring == 0) //Horizontal mirroring { Nametables[0] = Nametables[1] = Nametable0; Nametables[2] = Nametables[3] = Nametable2; } else if(Mirroring == 1) //Vertical mirroring { Nametables[0] = Nametables[2] = Nametable0; Nametables[1] = Nametables[3] = Nametable1; } break; } } memset(Nametable0, 0, 1024); memset(Nametable1, 0, 1024); memset(Nametable2, 0, 1024); memset(Nametable3, 0, 1024); //memset(BackgroundPalettes, 0, 16); //FOR DEBUG: BackgroundPalettes[0][0] = 0x0F; BackgroundPalettes[0][1] = 0x16; BackgroundPalettes[0][2] = 0x30; BackgroundPalettes[0][3] = 0x37; memset(BackgroundPalettes[1], 0, 12); memset(SpritePalettes, 0, 16); } //TODO: The PPU processes pixels 8 by 8, implement this void PPUClass::Run(unsigned long long CycleToGet) //Only NTSC for now { bool RollingOver = false; if(LastEmulatedCycle > CycleToGet) //Let's avoid infinite loops because of //cycle rollover { RollingOver = true; CycleToGet += NTSC_CYCLE_COUNT; } /*if((LastEmulatedCycle < NTSC_VBLANK_CYCLE) && (CycleToGet >= NTSC_VBLANK_CYCLE)) { Register2002 |= 0b10000000; NES.NMI = true; } if((LastEmulatedCycle < NTSC_VBLANK_UNSET_CYCLE) && (CycleToGet >= NTSC_VBLANK_UNSET_CYCLE)) { Register2002 &= 0b01111111; }*/ while(LastEmulatedCycle < CycleToGet) { LastEmulatedCycle += 5; if(Scanline == 261) //Pre-render scanline { if(Dot == 0) { Register2002 &= 0b01111111; Dot++; } else if(Dot < (338 + (NES.FrameCount & 1)?0:1)) { Dot++; } else { Dot = -1; Scanline = 0; } } else if(Scanline <= 239) { if(Dot == -1) { Dot++; } else if(Dot <= 255) { unsigned char BackgroundTile = Nametables[NametableBase][((Scanline >> 3) << 5) + Dot >> 3]; unsigned char Palette = Nametables[NametableBase] [960 + ((Scanline >> 5) << 3) + (Dot >> 5)]; if(Scanline & 16) { if(Dot & 16) { Palette >>= 6; } else { Palette >>= 4; Palette &= 3; } } else { if(Dot & 16) { Palette >>= 2; Palette &= 3; } else { Palette &= 3; } } unsigned char Color = 0; Color = (PatternTables[PatternTableBase] [(BackgroundTile << 4) + (Scanline & 7)] & (1 << (7 - (Dot & 7)))) >> (7 - (Dot & 7)); Color |= ((PatternTables[PatternTableBase] [(BackgroundTile << 4) + (Scanline & 7) + 8] & (1 << (7 - (Dot & 7)))) >> (7 - (Dot & 7)) << 1); NES.RenderBuffer.Memory[(Scanline << 8) + Dot] = NES.Debugger.ColorRGBTable [NES.PPU.BackgroundPalettes[Palette][Color]]; Dot++; } else if(Dot < 339) { Dot++; } else { Scanline++; Dot = -1; } } else if(Scanline == 240) { if(Dot < 339) { Dot++; } else { Scanline++; Dot = -1; } } else if(Scanline == 241) { if(Dot == 0) { Register2002 |= 0b10000000; if(NES.NMIEnabled) { NES.NMI = true; } Dot++; } else if(Dot < 339) { Dot++; } else { Scanline++; Dot = -1; } } else if(Scanline < 261) { if(Dot < 339) { Dot++; } else { Scanline++; Dot = -1; } } } if(RollingOver) { LastEmulatedCycle -= NTSC_CYCLE_COUNT; } } void PPUClass::Write(unsigned char valueToWrite) //TODO: Buffering { if(VRAMAddr < 0x1FFF) { PatternTables[(VRAMAddr & 0x1000) >> 12][VRAMAddr & 0x0FFF] = valueToWrite; } else if((VRAMAddr >= 0x2000) && (VRAMAddr < 0x3F00)) { Nametables[(VRAMAddr & 0x0C00) >> 14][VRAMAddr & 0x03FF] = valueToWrite; } else if(VRAMAddr >= 0x3F00) { if(VRAMAddr & 3) { if(VRAMAddr & 16) //Sprite palettes { SpritePalettes[(VRAMAddr & 12) >> 2][VRAMAddr & 3] = valueToWrite; } else { BackgroundPalettes[(VRAMAddr & 12) >> 2][VRAMAddr & 3] = valueToWrite; } } else { BackgroundPalettes[0][0] = valueToWrite; BackgroundPalettes[1][0] = valueToWrite; BackgroundPalettes[2][0] = valueToWrite; BackgroundPalettes[3][0] = valueToWrite; SpritePalettes[0][0] = valueToWrite; SpritePalettes[1][0] = valueToWrite; SpritePalettes[2][0] = valueToWrite; SpritePalettes[3][0] = valueToWrite; } } else { char ErrorMessage[] = "Tried to write value $00 at $0000 in PPU."; UchartoHex(valueToWrite, ErrorMessage + 22, false); UshorttoHex(VRAMAddr, ErrorMessage + 29, false); MessageBox(0, ErrorMessage, "Error", IDOK); } VRAMAddr += PPUADDRIncrement; }
28.246324
86
0.411948
ceanrim
57aedb8e4e426e87a08dd158627d2962880dc56f
14,662
cpp
C++
Eudora71/EuShlExt/ShellHookImpl.cpp
dusong7/eudora-win
850a6619e6b0d5abc770bca8eb5f3b9001b7ccd2
[ "BSD-3-Clause-Clear" ]
10
2018-05-23T10:43:48.000Z
2021-12-02T17:59:48.000Z
Eudora71/EuShlExt/ShellHookImpl.cpp
ivanagui2/hermesmail-code
34387722d5364163c71b577fc508b567de56c5f6
[ "BSD-3-Clause-Clear" ]
1
2019-03-19T03:56:36.000Z
2021-05-26T18:36:03.000Z
Eudora71/EuShlExt/ShellHookImpl.cpp
ivanagui2/hermesmail-code
34387722d5364163c71b577fc508b567de56c5f6
[ "BSD-3-Clause-Clear" ]
11
2018-05-23T10:43:53.000Z
2021-12-27T15:42:58.000Z
#include "windows.h" #include <stdio.h> #include "ShellHookImpl.h" #include "tchar.h" #include "time.h" #include "resource.h" extern unsigned int g_cRefThisDll; extern DWORD TlsIndex; extern HANDLE g_hModule; // The Shell Factory Class CShellExtClassFactory::CShellExtClassFactory() { //DumpLogInformation("CShellExtClassFactory::CShellExtClassFactory()\n"); m_cRef = 0L; g_cRefThisDll++; } CShellExtClassFactory::~CShellExtClassFactory() { g_cRefThisDll--; } STDMETHODIMP CShellExtClassFactory::QueryInterface(REFIID riid, LPVOID FAR *ppv) { THREADINFO *pti; THREADINFO ti; pti = &ti; pti = (THREADINFO *)TlsGetValue(TlsIndex); DumpLogInformation("In ShellExtClassFactory::QueryInterface()"); *ppv = NULL; if (IsEqualIID(riid, IID_IUnknown) || IsEqualIID(riid, IID_IClassFactory)) { *ppv = (LPCLASSFACTORY)this; AddRef(); return NOERROR; } return E_NOINTERFACE; } STDMETHODIMP_(ULONG) CShellExtClassFactory::AddRef() { THREADINFO *pti; THREADINFO ti; pti = &ti; pti = (THREADINFO *)TlsGetValue(TlsIndex); return ++m_cRef; } STDMETHODIMP_(ULONG) CShellExtClassFactory::Release() { THREADINFO *pti; THREADINFO ti; pti = &ti; pti = (THREADINFO *)TlsGetValue(TlsIndex); if (--m_cRef) return m_cRef; delete this; return 0L; } STDMETHODIMP CShellExtClassFactory::CreateInstance(LPUNKNOWN pUnkOuter, REFIID riid, LPVOID *ppvObj) { THREADINFO *pti; THREADINFO ti; pti = &ti; pti = (THREADINFO *)TlsGetValue(TlsIndex); DumpLogInformation("In ShellExtClassFactory::CreateInstance()"); *ppvObj = NULL; // Shell extensions typically don't support aggregation (inheritance) if (pUnkOuter) return CLASS_E_NOAGGREGATION; LPCSHELLEXT pShellExt = NULL; if (pShellExt == NULL) { try { //Create the CShellExt object pShellExt = new CShellExt(); } catch (...) { // Something's gone wrong. Write it to the log. DumpLogInformation("In ShellExtClassFactory::CreateInstance: Unable to create ShellExt Object"); pShellExt=NULL; } } if (NULL == pShellExt) return E_OUTOFMEMORY; return pShellExt->QueryInterface(riid, ppvObj); } STDMETHODIMP CShellExtClassFactory::LockServer(BOOL fLock) { THREADINFO *pti; THREADINFO ti; pti = &ti; pti = (THREADINFO *)TlsGetValue(TlsIndex); //return NOERROR; return S_OK; } CShellExt::CShellExt() { //DumpLogInformation("CShellExt::CShellExt()\n"); m_cRef = 0L; m_pDataObj = NULL; m_pLMRegData = NULL; m_nPathCount = 0; g_cRefThisDll++; } CShellExt::~CShellExt() { //DumpLogInformation("CShellExt::~CShellExt()\n"); if (m_pDataObj) m_pDataObj->Release(); if (m_pLMRegData) delete [] m_pLMRegData; g_cRefThisDll--; } STDMETHODIMP CShellExt::QueryInterface(REFIID riid, LPVOID FAR *ppv) { THREADINFO *pti; THREADINFO ti; pti = &ti; pti = (THREADINFO *)TlsGetValue(TlsIndex); *ppv = NULL; if (IsEqualIID(riid, IID_IUnknown) || IsEqualIID(riid, IID_IPersistFile)) { DumpLogInformation("In ShellExt::QueryInterface() --> IID_IPersistFile"); *ppv = (LPPERSISTFILE)this; } else if (IsEqualIID(riid, IID_IShellExecuteHook)) { DumpLogInformation("In ShellExt::QueryInterface() --> IID_IShellExecuteHook"); *ppv = (IShellExecuteHook *)this; LoadConfiguration(); } if (*ppv) { AddRef(); return NOERROR; } DumpLogInformation("In ShellExt::QueryInterface() --> Unsupported Interface!"); return E_NOINTERFACE; } STDMETHODIMP_(ULONG) CShellExt::AddRef() { THREADINFO *pti; THREADINFO ti; pti = &ti; pti = (THREADINFO *)TlsGetValue(TlsIndex); DumpLogInformation("In ShellExt::AddRef()"); return ++m_cRef; } STDMETHODIMP_(ULONG) CShellExt::Release() { DumpLogInformation("In ShellExt::Release()"); if (--m_cRef) return m_cRef; delete this; return 0L; } INT_PTR CALLBACK WarnDlgProc( HWND hwndDlg, // handle to dialog box UINT uMsg, // message WPARAM wParam, // first message parameter LPARAM lParam // second message parameter ) { if (uMsg == WM_INITDIALOG) { // Buffer used for loading the string from the string table TCHAR szBuff[1024]; // This buffer will contain the final text so formed. TCHAR szFinalTextBuff[1024 /* size of szBuff*/ + _MAX_PATH + _MAX_FNAME + _MAX_EXT + sizeof(TCHAR)]; HWND hWndControl = GetDlgItem(hwndDlg, IDC_ALERT_TEXT); // Load the string fro the string table. LoadString((HINSTANCE) g_hModule, IDS_WARN_STRING, szBuff, sizeof(szBuff)); sprintf(szFinalTextBuff,szBuff, lParam); if (hWndControl) SetWindowText(hWndControl, szFinalTextBuff); } else if (uMsg == WM_COMMAND) { if (HIWORD(wParam) == BN_CLICKED) { // Destroy the Dialog. EndDialog(hwndDlg, LOWORD(wParam) ); } } return FALSE; } STDMETHODIMP CShellExt::Execute( LPSHELLEXECUTEINFO pei) { THREADINFO *pti; THREADINFO ti; pti = &ti; pti = (THREADINFO *)TlsGetValue(TlsIndex); TCHAR szData[1024] = {0}; TCHAR szValueName[1024] = {0}; DWORD dwDataBufSize=1024; BOOL bAlreadyWarned = FALSE; DWORD dwKeyDataType = 0; HKEY hKey = NULL; DWORD dwValue = 0; TCHAR szShortPathName1[_MAX_PATH + _MAX_FNAME + _MAX_EXT + SIZEOF_NULL_TERMINATOR] = {0}; TCHAR szShortPathName2[_MAX_PATH + _MAX_FNAME + _MAX_EXT + SIZEOF_NULL_TERMINATOR] = {0}; static int sBufLength = _MAX_PATH + _MAX_FNAME + _MAX_EXT; try { for (int i = 0; i < m_nPathCount; i++) { bAlreadyWarned = FALSE; // Convert to Short Path Name. Also if for some reason the entry in registry has an empty path, then make sure we skip it. // Any path that is registered as a path to be "protected" by Shell Extension CANNOT BE EMPTY if ( GetShortPathName((LPTSTR)pei->lpFile, szShortPathName1, sBufLength) && GetShortPathName(m_pLMRegData[i].szPath, szShortPathName2, sBufLength) && (_tcslen(szShortPathName2) > 0) ) { if( (m_pLMRegData) && _tcsstr( _tcslwr(szShortPathName1),_tcslwr(szShortPathName2) ) ) { if (IsExecutable(pei->lpFile,i+1)) { // Check if already warned by Application that is launching (e.g Eudora). If so, then do not warn again // It's the application's (the one that is launching/executing this file) duty to set the value of AlreadyWarned'N' to the // appropriate value. if ( RegOpenKeyEx(HKEY_CURRENT_USER, LM_REG_APP_KEY,0, KEY_READ | KEY_WRITE, &hKey) == ERROR_SUCCESS) { sprintf(szValueName,LM_REG_ALREADYWARNED_KEY,i+1); if (RegQueryValueEx(hKey, szValueName, NULL, &dwKeyDataType, (LPBYTE)szData, &(dwDataBufSize = sizeof(szData))) == ERROR_SUCCESS) { bAlreadyWarned = *((DWORD*)szData); //Reset the "AlreadyWarned#n" sprintf(szValueName,LM_REG_ALREADYWARNED_KEY,i+1); dwValue = 0; RegSetValueEx(hKey, szValueName, 0, REG_DWORD, (const PBYTE) &dwValue, sizeof(DWORD)); } RegCloseKey(hKey); } if (!bAlreadyWarned) { if ( (pei) && ( (long) pei->hInstApp < 32) ) pei->hInstApp = (HINSTANCE) 32; // This makes sure that Shell does not generate any error message box. if (IDCANCEL == ::DialogBoxParam( (HINSTANCE) g_hModule, MAKEINTRESOURCE(IDD_YES_NO), NULL, (DLGPROC ) &WarnDlgProc, LPARAM(pei->lpFile))) return S_OK; // Let Shell know that we handled it. else return S_FALSE; // Let Shell Handle it. We are done. } } } } else if (_tcslen(szShortPathName2) <= 0) DumpLogInformation("The Path, Path#%d is empty",i + 1); } } catch(...) { // Something's gone wrong here ..write to the log. DumpLogInformation("Exception when trying to determine if Executable, Path : %s",(LPTSTR)pei->lpFile); } return S_FALSE; } STDMETHODIMP_(VOID) CShellExt::LoadConfiguration() { THREADINFO *pti; THREADINFO ti; pti = &ti; pti = (THREADINFO *)TlsGetValue(TlsIndex); // This is the function that loads the configuration from the registry TCHAR szData[1024] = {0}; TCHAR szValueName[1024] = {0}; DWORD dwDataBufSize=1024; DWORD dwKeyDataType = 0; HKEY hKey = NULL; // All the entries are under HKCU\Qualcomm\Eudora\LauchManager if ( RegOpenKeyEx(HKEY_CURRENT_USER, LM_REG_APP_KEY,0, KEY_READ, &hKey) == ERROR_SUCCESS) { if (RegQueryValueEx(hKey, LM_REG_PATHCOUNT_KEY, NULL, &dwKeyDataType,(LPBYTE) szData, &(dwDataBufSize = sizeof(szData))) == ERROR_SUCCESS) { if (dwKeyDataType == REG_DWORD) { m_nPathCount = *((DWORD*)szData); DumpLogInformation("Loading Configuration Info : PathCount %d",m_nPathCount); } else // Write to the log that somehow the value is corrupted { DumpLogInformation("Error Loading Configuration Info : PathCount %d ...resetting to zero",*((DWORD*)szData)); m_nPathCount = 0; } // Also write to the log if the Path Count is negative if (m_nPathCount < 0) { DumpLogInformation("Error PathCount value is negative : %d ...resetting to zero",*((DWORD*)szData)); m_nPathCount = 0; } // Delete the memory allocated (if any) if(m_pLMRegData) delete [] m_pLMRegData; // Allocate memory here so that we could fill the data. m_pLMRegData = new LM_REG_DATA[m_nPathCount]; for (int i = 0; i < m_nPathCount; i++) { // Allocate memory sprintf(szValueName,LM_REG_PATH_KEY,i+1); if (RegQueryValueEx(hKey, szValueName, NULL, &dwKeyDataType, (LPBYTE)szData, &(dwDataBufSize = sizeof(szData))) == ERROR_SUCCESS) { _tcsncpy(m_pLMRegData[i].szPath,(LPCTSTR)szData,_MAX_PATH > 1024 ? _MAX_PATH : 1024); } } } RegCloseKey(hKey); } return; } // This function determines if the FileName so passed is one amongst the malicious file-types that could possibly contain // viruses, worms etc when opened/executed. The list which specifies the malicious extensions is provided in the registry. STDMETHODIMP_(BOOL) CShellExt::IsExecutable(LPCTSTR Filename, int nPathOffset) { THREADINFO *pti; THREADINFO ti; pti = &ti; pti = (THREADINFO *)TlsGetValue(TlsIndex); TCHAR szData[1024] = {0}; TCHAR szValueName[1024] = {0}; DWORD dwDataBufSize=1024; DWORD dwKeyDataType = 0; HKEY hKey = NULL; TCHAR szWarnExtensions[1024] = {0}; TCHAR szDoNotWarnExtensions[1024] = {0}; BOOL bFound = FALSE; if (!Filename) return FALSE; LPSTR lpLastPeriod = _tcsrchr(Filename, '.'); if (lpLastPeriod) { // We found the file's extension if ( RegOpenKeyEx(HKEY_CURRENT_USER, LM_REG_APP_KEY,0, KEY_READ, &hKey) == ERROR_SUCCESS) { // Get the WarnExtensions value for the specified Path Index sprintf(szValueName,LM_REG_WARN_KEY,nPathOffset); if (RegQueryValueEx(hKey, szValueName, NULL, &dwKeyDataType, (LPBYTE)szData, &(dwDataBufSize = sizeof(szData))) == ERROR_SUCCESS) { _tcscpy(szWarnExtensions,(LPCTSTR)szData); } // Get the DoNotWarnExtensions value for the specified Path Index sprintf(szValueName,LM_REG_DONOTWARN_KEY,nPathOffset); if (RegQueryValueEx(hKey, szValueName, NULL, &dwKeyDataType, (LPBYTE)szData, &(dwDataBufSize = sizeof(szData))) == ERROR_SUCCESS) { _tcscpy(szDoNotWarnExtensions,(LPCTSTR)szData); } RegCloseKey(hKey); } if ( szWarnExtensions[_tcslen(szWarnExtensions) - 1] != '|') _tcscat(szWarnExtensions,"|"); // This helps us while parsing TCHAR seps[] = "|"; // token's that will be used for parsing. TCHAR *token; token = _tcstok( szWarnExtensions, seps ); while( token != NULL ) { // While there are tokens if (!_tcsnicmp(token,lpLastPeriod + 1,_tcslen(token)) ) { // Found an extension in the WarnExtensions List bFound = TRUE; break; } // Get next token token = _tcstok( NULL, seps ); } if (bFound) { token = _tcstok( szDoNotWarnExtensions, seps ); while( token != NULL ) { // While there are tokens if (!_tcsnicmp(token,lpLastPeriod + 1,_tcslen(token)) ) { // Found an extension in the DoNotWarnExtensions List ..hence set the bFound to FALSE. bFound = FALSE; break; } // Get next token token = _tcstok( NULL, seps ); } } } return bFound; } // This function will dump the logging information in a file when required. void DumpLogInformation(const TCHAR *szFormat ... ) { TCHAR szTempBuffer[4096] = {0}; // Sufficient enough to store the string to display TCHAR szBuffer[3968] = {0}; TCHAR szDate[128], szTime[128]; va_list argptr; // try/catch block so that if somehow the code misbehaves, we do not crash the Shell. try { // Today's date _strdate(szDate); // Current time _strtime(szTime); // Format the passed arguments va_start( argptr, szFormat ); wvsprintf( szBuffer, szFormat, argptr ); va_end( argptr ); #ifdef _DEBUG // Wrapped this in #ifdef because OutputDebugString dumps the information in release mode also sprintf(szTempBuffer,"EuShlExt : %s, %s - %s\n", szDate, szTime, szBuffer); OutputDebugString(szTempBuffer); #endif TCHAR szData[1024]; DWORD dwDataBufSize=1024; DWORD dwKeyDataType; HKEY hKey = NULL; DWORD dwEnableLogging = FALSE; TCHAR szLogFilePath[_MAX_PATH + _MAX_FNAME + _MAX_EXT]; if ( RegOpenKeyEx(HKEY_CURRENT_USER, LM_REG_APP_KEY, 0, KEY_READ | KEY_WRITE, &hKey) == ERROR_SUCCESS) { dwKeyDataType = REG_DWORD; if (RegQueryValueEx(hKey, LM_REG_ENABLELOGGING_KEY, NULL, &dwKeyDataType,(LPBYTE) szData, &(dwDataBufSize = sizeof(szData))) == ERROR_SUCCESS) { if (dwKeyDataType == REG_DWORD) dwEnableLogging = *((DWORD*)szData); else dwEnableLogging = FALSE; // If logging enabled & a valid DLLPath is found if ( (dwEnableLogging) && (RegQueryValueEx(hKey, LM_REG_DLLPATH_KEY, NULL, &dwKeyDataType,(LPBYTE) szData, &(dwDataBufSize = sizeof(szData))) == ERROR_SUCCESS) ) { if (szData) { TCHAR *pChar = _tcsrchr((LPTSTR)szData,'\\'); if (pChar) { *pChar = '\0'; _tcscpy(szLogFilePath, szData); _tcscat(szLogFilePath, "\\EuShlExt.log"); FILE* fLogFile = NULL; fLogFile = fopen(szLogFilePath,"a"); if (fLogFile) { sprintf(szTempBuffer,"%s, %s - %s\n", szDate, szTime, szBuffer); fprintf(fLogFile, szTempBuffer); fclose(fLogFile); } } } } } } } catch(...) { // Do nothing, makes sure any misbehaviour does not crash the shell } }
25.49913
145
0.666417
dusong7
57afb922aa05a8271d69066a46ac26b34dcdad8f
947
hpp
C++
include/xvega/grammar/config/error_band_config.hpp
domoritz/xvega
3754dee3e7e38e79282ba267cd86c3885807a4cd
[ "BSD-3-Clause" ]
34
2020-08-14T14:32:51.000Z
2022-02-16T23:20:02.000Z
include/xvega/grammar/config/error_band_config.hpp
domoritz/xvega
3754dee3e7e38e79282ba267cd86c3885807a4cd
[ "BSD-3-Clause" ]
19
2020-08-20T20:04:39.000Z
2022-02-28T14:34:37.000Z
include/xvega/grammar/config/error_band_config.hpp
domoritz/xvega
3754dee3e7e38e79282ba267cd86c3885807a4cd
[ "BSD-3-Clause" ]
7
2020-08-14T14:18:17.000Z
2022-02-01T10:59:24.000Z
// Copyright (c) 2020, QuantStack and XVega Contributors // // Distributed under the terms of the BSD 3-Clause License. // // The full license is in the file LICENSE, distributed with this software. #ifndef XVEGA_ERROR_BAND_CONFIG_HPP #define XVEGA_ERROR_BAND_CONFIG_HPP #include "./mark_config.hpp" namespace xv { using bool_mark_config_type = xtl::variant<mark_config, bool>; struct error_band_config : public xp::xobserved<error_band_config> { XPROPERTY(xtl::xoptional<bool_mark_config_type>, error_band_config, band); XPROPERTY(xtl::xoptional<bool_mark_config_type>, error_band_config, borders); XPROPERTY(xtl::xoptional<std::string>, error_band_config, extent); XPROPERTY(xtl::xoptional<std::string>, error_band_config, interpolate); XPROPERTY(xtl::xoptional<double>, error_band_config, tension); }; XVEGA_API void to_json(nl::json& j, const error_band_config& data); } #endif
33.821429
85
0.7434
domoritz
57b2e3f8c0c66b13c2c56059e8b73489931844a4
903
cpp
C++
0013_Roman_to_Integer/solution.cpp
Heliovic/LeetCode_Solutions
73d5a7aaffe62da9a9cd8a80288b260085fda08f
[ "MIT" ]
2
2019-02-18T15:32:57.000Z
2019-03-18T12:55:35.000Z
0013_Roman_to_Integer/solution.cpp
Heliovic/LeetCode_Solutions
73d5a7aaffe62da9a9cd8a80288b260085fda08f
[ "MIT" ]
null
null
null
0013_Roman_to_Integer/solution.cpp
Heliovic/LeetCode_Solutions
73d5a7aaffe62da9a9cd8a80288b260085fda08f
[ "MIT" ]
null
null
null
class Solution { public: map<char, int> mp; int romanToInt(string s) { mp['I'] = 1; mp['V'] = 5; mp['X'] = 10; mp['L'] = 50; mp['C'] = 100; mp['D'] = 500; mp['M'] = 1000; int ans = 0; for (int i = 0; i < s.size(); i++) { if (i != s.size() - 1) { string str = ""; str += s[i]; str += s[i + 1]; if (str == "IV") {ans += 4; i++; continue;} if (str == "IX") {ans += 9; i++; continue;} if (str == "XL") {ans += 40; i++; continue;} if (str == "XC") {ans += 90; i++; continue;} if (str == "CD") {ans += 400; i++; continue;} if (str == "CM") {ans += 900; i++; continue;} } ans += mp[s[i]]; } return ans; } };
27.363636
61
0.311185
Heliovic
57b2e8d7bc408c63121f64cac74df2a28044a127
683
cpp
C++
copyfile/main.cpp
mario21ic/cpp-demos
286968591a586c2332b9fa915f330b1a0b1219ee
[ "MIT" ]
null
null
null
copyfile/main.cpp
mario21ic/cpp-demos
286968591a586c2332b9fa915f330b1a0b1219ee
[ "MIT" ]
null
null
null
copyfile/main.cpp
mario21ic/cpp-demos
286968591a586c2332b9fa915f330b1a0b1219ee
[ "MIT" ]
null
null
null
#include<iostream> #include<ncurses.h> #include<fstream> #include<stdio.h> #include<stdlib.h> void main() { clrscr(); ifstream fs; ofstream ft; char ch, fname1[20], fname2[20]; cout<<"Enter source file name with extension (like files.txt) : "; gets(fname1); fs.open(fname1); if(!fs) { cout<<"Error in opening source file..!!"; getch(); exit(1); } cout<<"Enter target file name with extension (like filet.txt) : "; gets(fname2); ft.open(fname2); if(!ft) { cout<<"Error in opening target file..!!"; fs.close(); getch(); exit(2); } while(fs.eof()==0) { fs>>ch; ft<<ch; } cout<<"File copied successfully..!!"; fs.close(); ft.close(); getch(); }
16.261905
67
0.617862
mario21ic
57b451a9b4fd704c703280407af46606c21b24e8
894
cpp
C++
tests/simple_pputil.cpp
crapp/pputil
d38edd744f3f998dd4957e659641cab2fa5c6a40
[ "MIT" ]
null
null
null
tests/simple_pputil.cpp
crapp/pputil
d38edd744f3f998dd4957e659641cab2fa5c6a40
[ "MIT" ]
null
null
null
tests/simple_pputil.cpp
crapp/pputil
d38edd744f3f998dd4957e659641cab2fa5c6a40
[ "MIT" ]
null
null
null
#include <iostream> #include "pputil.hpp" #include "simple_pputil.hpp" namespace ut = pputil; StreamOp::StreamOp(){}; StreamOp::StreamOp(std::string s) : mystring(std::move(s)){}; StreamOp::~StreamOp(){}; void StreamOp::setMyString(std::string mystring) { this->mystring = std::move(mystring); } std::string StreamOp::getMyString() const { return this->mystring; } int main(ATTR_UNUSED int argc, ATTR_UNUSED char *argv[]) { // concatenate some simple strings std::string cons = ut::stringify("Foo", "Bar", "Baz"); // prints FooBarBaz std::cout << cons << std::endl; // concatenate with objects implementing stream operator StreamOp so("OperatorToString"); std::cout << cons + " AND " + ut::op_to_string(so) << std::endl; // create toml usable strings std::cout << ut::toml_stringify("GENERAL", "FOO", "BAR", "BAZ") << std::endl; return 0; }
25.542857
81
0.657718
crapp
57b5d5e9433f6463eccbfc6bb319306cc083cfff
8,478
cpp
C++
src/robot_model.cpp
mayataka/invariant-ekf
775d9ab5ac7599fe2fd983b8a907c241c7d3a8e0
[ "BSD-3-Clause" ]
1
2022-03-28T12:38:09.000Z
2022-03-28T12:38:09.000Z
src/robot_model.cpp
mayataka/inekf
775d9ab5ac7599fe2fd983b8a907c241c7d3a8e0
[ "BSD-3-Clause" ]
null
null
null
src/robot_model.cpp
mayataka/inekf
775d9ab5ac7599fe2fd983b8a907c241c7d3a8e0
[ "BSD-3-Clause" ]
null
null
null
#include "inekf/robot_model.hpp" namespace inekf { pinocchio::Model RobotModel::buildFloatingBaseModel( const std::string& path_to_urdf) { pinocchio::Model pin_model; pinocchio::urdf::buildModel(path_to_urdf, pinocchio::JointModelFreeFlyer(), pin_model); return pin_model; } RobotModel::RobotModel(const std::string& path_to_urdf, const int imu_frame, const std::vector<int>& contact_frames) : RobotModel(buildFloatingBaseModel(path_to_urdf), imu_frame, contact_frames) { } RobotModel::RobotModel(const std::string& path_to_urdf, const std::string& imu_frame, const std::vector<std::string>& contact_frames) : RobotModel(buildFloatingBaseModel(path_to_urdf), imu_frame, contact_frames) { } RobotModel::RobotModel(const pinocchio::Model& pin_model, const int imu_frame, const std::vector<int>& contact_frames) : contact_frames_(contact_frames), imu_frame_(imu_frame), model_(pin_model), data_(), q_(), v_(), a_(), tau_(), jac_6d_() { data_ = pinocchio::Data(model_); q_ = Eigen::VectorXd(model_.nq); v_ = Eigen::VectorXd(model_.nv); a_ = Eigen::VectorXd(model_.nv); tau_ = Eigen::VectorXd(model_.nv); for (int i=0; i<contact_frames.size(); ++i) { jac_6d_.push_back(Eigen::MatrixXd::Zero(6, model_.nv)); } } RobotModel::RobotModel(const pinocchio::Model& pin_model, const std::string& imu_frame, const std::vector<std::string>& contact_frames) : contact_frames_(), imu_frame_(), model_(pin_model), data_(), q_(), v_(), a_(), tau_(), jac_6d_() { data_ = pinocchio::Data(model_); q_ = Eigen::VectorXd(model_.nq); v_ = Eigen::VectorXd(model_.nv); a_ = Eigen::VectorXd(model_.nv); tau_ = Eigen::VectorXd(model_.nv); for (int i=0; i<contact_frames.size(); ++i) { jac_6d_.push_back(Eigen::MatrixXd::Zero(6, model_.nv)); } try { if (!model_.existFrame(imu_frame)) { throw std::invalid_argument( "Invalid argument: frame " + imu_frame + " does not exit!"); } } catch(const std::exception& e) { std::cerr << e.what() << '\n'; std::exit(EXIT_FAILURE); } imu_frame_ = model_.getFrameId(imu_frame); contact_frames_.clear(); for (const auto& e : contact_frames) { try { if (!model_.existFrame(e)) { throw std::invalid_argument( "Invalid argument: frame " + e + " does not exit!"); } } catch(const std::exception& e) { std::cerr << e.what() << '\n'; std::exit(EXIT_FAILURE); } contact_frames_.push_back(model_.getFrameId(e)); } } RobotModel::RobotModel() : contact_frames_(), imu_frame_(), model_(), data_(), q_(), v_(), a_(), tau_(), jac_6d_() { } void RobotModel::updateLegKinematics(const Eigen::VectorXd& qJ, const pinocchio::ReferenceFrame rf) { updateKinematics(Eigen::Vector3d::Zero(), Eigen::Quaterniond::Identity().coeffs(), qJ, rf); } void RobotModel::updateLegKinematics(const Eigen::VectorXd& qJ, const Eigen::VectorXd& dqJ, const pinocchio::ReferenceFrame rf) { updateKinematics(Eigen::Vector3d::Zero(), Eigen::Quaterniond::Identity().coeffs(), Eigen::Vector3d::Zero(), Eigen::Vector3d::Zero(), qJ, dqJ, rf); } void RobotModel::updateKinematics(const Eigen::Vector3d& base_pos, const Eigen::Vector4d& base_quat, const Eigen::VectorXd& qJ, const pinocchio::ReferenceFrame rf) { q_.template head<3>() = base_pos; q_.template segment<4>(3) = base_quat; q_.tail(model_.nq-7) = qJ; pinocchio::normalize(model_, q_); pinocchio::forwardKinematics(model_, data_, q_); pinocchio::updateFramePlacements(model_, data_); pinocchio::computeJointJacobians(model_, data_, q_); for (int i=0; i<contact_frames_.size(); ++i) { pinocchio::getFrameJacobian(model_, data_, contact_frames_[i], rf, jac_6d_[i]); } } void RobotModel::updateKinematics(const Eigen::Vector3d& base_pos, const Eigen::Vector4d& base_quat, const Eigen::Vector3d& base_linear_vel, const Eigen::Vector3d& base_angular_vel, const Eigen::VectorXd& qJ, const Eigen::VectorXd& dqJ, const pinocchio::ReferenceFrame rf) { q_.template head<3>() = base_pos; q_.template segment<4>(3) = base_quat; v_.template head<3>() = base_linear_vel; v_.template segment<3>(3) = base_angular_vel; q_.tail(model_.nq-7) = qJ; v_.tail(model_.nv-6) = dqJ; pinocchio::normalize(model_, q_); pinocchio::forwardKinematics(model_, data_, q_, v_); pinocchio::updateFramePlacements(model_, data_); pinocchio::computeJointJacobians(model_, data_, q_); for (int i=0; i<contact_frames_.size(); ++i) { pinocchio::getFrameJacobian(model_, data_, contact_frames_[i], rf, jac_6d_[i]); } } void RobotModel::updateLegDynamics(const Eigen::VectorXd& qJ, const Eigen::VectorXd& dqJ) { updateDynamics(Eigen::Vector3d::Zero(), Eigen::Quaterniond::Identity().coeffs(), Eigen::Vector3d::Zero(), Eigen::Vector3d::Zero(), Eigen::Vector3d::Zero(), Eigen::Vector3d::Zero(), qJ, dqJ, Eigen::VectorXd::Zero(nJ())); } void RobotModel::updateDynamics(const Eigen::Vector3d& base_pos, const Eigen::Vector4d& base_quat, const Eigen::Vector3d& base_linear_vel, const Eigen::Vector3d& base_angular_vel, const Eigen::Vector3d& base_linear_acc, const Eigen::Vector3d& base_angular_acc, const Eigen::VectorXd& qJ, const Eigen::VectorXd& dqJ, const Eigen::VectorXd& ddqJ) { q_.template head<3>() = base_pos; q_.template segment<4>(3) = base_quat; v_.template head<3>() = base_linear_vel; v_.template segment<3>(3) = base_angular_vel; a_.template head<3>() = base_linear_acc; a_.template segment<3>(3) = base_angular_acc; q_.tail(model_.nq-7) = qJ; v_.tail(model_.nv-6) = dqJ; a_.tail(model_.nv-6) = ddqJ; tau_ = pinocchio::rnea(model_, data_, q_, v_, a_); } const Eigen::Vector3d& RobotModel::getBasePosition() const { return data_.oMf[imu_frame_].translation(); } const Eigen::Matrix3d& RobotModel::getBaseRotation() const { return data_.oMf[imu_frame_].rotation(); } const Eigen::Vector3d& RobotModel::getContactPosition(const int contact_id) const { assert(contact_id >= 0); assert(contact_id < contact_frames_.size()); return data_.oMf[contact_frames_[contact_id]].translation(); } const Eigen::Matrix3d& RobotModel::getContactRotation(const int contact_id) const { assert(contact_id >= 0); assert(contact_id < contact_frames_.size()); return data_.oMf[contact_frames_[contact_id]].rotation(); } const Eigen::Block<const Eigen::MatrixXd> RobotModel::getContactJacobian(const int contact_id) const { assert(contact_id >= 0); assert(contact_id < contact_frames_.size()); return jac_6d_[contact_id].topRows(3); } const Eigen::Block<const Eigen::MatrixXd> RobotModel::getJointContactJacobian(const int contact_id) const { assert(contact_id >= 0); assert(contact_id < contact_frames_.size()); return jac_6d_[contact_id].topRightCorner(3, nJ()); } const Eigen::VectorXd& RobotModel::getInverseDynamics() const { return tau_; } const Eigen::VectorBlock<const Eigen::VectorXd> RobotModel::getJointInverseDynamics() const { return tau_.tail(nJ()); } const std::vector<int>& RobotModel::getContactFrames() const { return contact_frames_; } int RobotModel::nq() const { return model_.nq; } int RobotModel::nv() const { return model_.nv; } int RobotModel::nJ() const { return model_.nv-6; } int RobotModel::numContacts() const { return contact_frames_.size(); } } // namespace inekf
31.054945
107
0.612173
mayataka
57b686bb8b3c6b1fc326542951589ea72a6010b5
2,799
cpp
C++
Service/gpiopin.cpp
elnappo/Baulicht
9ff14938d01b228135eb7092891e31494176782e
[ "MIT" ]
null
null
null
Service/gpiopin.cpp
elnappo/Baulicht
9ff14938d01b228135eb7092891e31494176782e
[ "MIT" ]
1
2015-04-07T22:46:18.000Z
2015-04-08T07:27:55.000Z
Service/gpiopin.cpp
elnappo/Baulicht
9ff14938d01b228135eb7092891e31494176782e
[ "MIT" ]
null
null
null
#include "gpiopin.h" #include <QFile> #include <QDebug> namespace { static const QString exportPath = "/sys/class/gpio/export"; static const QString pinPath = "/sys/class/gpio/gpio%1"; static const QString valuePath = "/sys/class/gpio/gpio%1/value"; static const QString directionPath = "/sys/class/gpio/gpio%1/direction"; } class GPIOPin::Private { public: // Properties int pin; QString errorString; // Functions bool tryExport(); }; bool GPIOPin::Private::tryExport() { errorString.clear(); QString path = pinPath.arg(pin); if (QFile::exists(path)) return true; QFile file(path); if (file.open(QIODevice::WriteOnly)) { file.write(QString::number(pin).toLatin1()); return true; } else { errorString = file.errorString(); } return false; } GPIOPin::GPIOPin(int pin) : d(new Private) { d->pin = pin; } GPIOPin::~GPIOPin() { delete d; } GPIOPin::Direction GPIOPin::direction() const { d->tryExport(); d->errorString.clear(); QString path = directionPath.arg(d->pin); QFile file(path); if (file.open(QIODevice::ReadOnly)) { QByteArray direction = file.readAll().trimmed(); if (direction == "in") return In; else if (direction == "out") return Out; } else { d->errorString = file.errorString(); } return Unknown; } void GPIOPin::setDirection(const Direction &direction) { d->tryExport(); d->errorString.clear(); QString path = directionPath.arg(d->pin); QFile file(path); if (file.open(QIODevice::WriteOnly)) { switch(direction) { case In: file.write("in"); break; case Out: file.write("out"); break; default: break; } } else { qDebug() << "Failed to set direction on pin:" << file.errorString(); d->errorString = file.errorString(); } } QByteArray GPIOPin::value() const { d->tryExport(); d->errorString.clear(); QString path = valuePath.arg(d->pin); QFile file(path); if (file.open(QIODevice::ReadOnly)) { return file.readAll(); } else { d->errorString = file.errorString(); } return QByteArray(); } void GPIOPin::setValue(const QByteArray &value) { d->tryExport(); d->errorString.clear(); QString path = valuePath.arg(d->pin); QFile file(path); if (file.open(QIODevice::WriteOnly)) { file.write(value); } else { qDebug() << "Failed to set value on pin:" << file.errorString(); d->errorString = file.errorString(); } } int GPIOPin::pin() const { return d->pin; } QString GPIOPin::errorString() const { return d->errorString; }
19.851064
76
0.586995
elnappo
57bdf8636eacaf95435fb2340cc319a7ba07f6d5
4,727
cpp
C++
WebKit2-7534.57.7/WebKit2-7534.57.7/Platform/qt/SharedMemorySymbian.cpp
mlcldh/appleWebKit2
39cc42a4710c9319c8da269621844493ab2ccdd6
[ "MIT" ]
1
2021-05-27T07:29:31.000Z
2021-05-27T07:29:31.000Z
WebKit2-7534.57.7/WebKit2-7534.57.7/Platform/qt/SharedMemorySymbian.cpp
mlcldh/appleWebKit2
39cc42a4710c9319c8da269621844493ab2ccdd6
[ "MIT" ]
null
null
null
WebKit2-7534.57.7/WebKit2-7534.57.7/Platform/qt/SharedMemorySymbian.cpp
mlcldh/appleWebKit2
39cc42a4710c9319c8da269621844493ab2ccdd6
[ "MIT" ]
null
null
null
/* Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "config.h" #if PLATFORM(QT) && OS(SYMBIAN) #include "SharedMemory.h" #include "ArgumentDecoder.h" #include "ArgumentEncoder.h" #include <e32math.h> #include <qdebug.h> #include <qglobal.h> #include <sys/param.h> namespace WebKit { SharedMemory::Handle::Handle() : m_chunkID(0) , m_size(0) { } SharedMemory::Handle::~Handle() { } bool SharedMemory::Handle::isNull() const { return !m_chunkID; } void SharedMemory::Handle::encode(CoreIPC::ArgumentEncoder* encoder) const { ASSERT(!isNull()); encoder->encodeUInt32(m_size); // name of the global chunk (masquerading as uint32_t for ease of serialization) encoder->encodeUInt32(m_chunkID); } bool SharedMemory::Handle::decode(CoreIPC::ArgumentDecoder* decoder, Handle& handle) { size_t size; if (!decoder->decodeUInt32(size)) return false; uint32_t chunkID; if (!decoder->decodeUInt32(chunkID)) return false; handle.m_size = size; handle.m_chunkID = chunkID; return true; } // FIXME: To be removed as part of Bug 55877 CoreIPC::Attachment SharedMemory::Handle::releaseToAttachment() const { return CoreIPC::Attachment(-1, 0); } // FIXME: To be removed as part of Bug 55877 void SharedMemory::Handle::adoptFromAttachment(int, size_t) { } PassRefPtr<SharedMemory> SharedMemory::create(size_t size) { // On Symbian, global chunks (shared memory segments) have system-unique names, so we pick a random // number from the kernel's random pool and use it as a string. // Using an integer simplifies serialization of the name in Handle::encode() uint32_t random = Math::Random(); TBuf<KMaxKernelName> chunkName; chunkName.Format(_L("%d"), random); RChunk chunk; TInt error = chunk.CreateGlobal(chunkName, size, size); if (error) { qCritical() << "Failed to create WK2 shared memory of size " << size << " with error " << error; return 0; } RefPtr<SharedMemory> sharedMemory(adoptRef(new SharedMemory)); sharedMemory->m_handle = chunk.Handle(); sharedMemory->m_size = chunk.Size(); sharedMemory->m_data = static_cast<void*>(chunk.Base()); return sharedMemory.release(); } PassRefPtr<SharedMemory> SharedMemory::create(const Handle& handle, Protection protection) { if (handle.isNull()) return 0; // Convert number to string, and open the global chunk TBuf<KMaxKernelName> chunkName; chunkName.Format(_L("%d"), handle.m_chunkID); RChunk chunk; // NOTE: Symbian OS doesn't support read-only global chunks. TInt error = chunk.OpenGlobal(chunkName, false); if (error) { qCritical() << "Failed to create WK2 shared memory from handle " << error; return 0; } chunk.Adjust(chunk.MaxSize()); RefPtr<SharedMemory> sharedMemory(adoptRef(new SharedMemory)); sharedMemory->m_handle = chunk.Handle(); sharedMemory->m_size = chunk.Size(); sharedMemory->m_data = static_cast<void*>(chunk.Base()); return sharedMemory.release(); } SharedMemory::~SharedMemory() { // FIXME: We don't Close() the chunk here, causing leaks of the shared memory segment // If we do, the chunk is closed the decommitted prematurely before the other process // has a chance to OpenGlobal() it. } bool SharedMemory::createHandle(Handle& handle, Protection protection) { ASSERT_ARG(handle, handle.isNull()); RChunk chunk; if (chunk.SetReturnedHandle(m_handle)) return false; // Convert the name (string form) to a uint32_t. TName globalChunkName = chunk.Name(); TLex lexer(globalChunkName); TUint32 nameAsInt = 0; if (lexer.Val(nameAsInt, EDecimal)) return false; handle.m_chunkID = nameAsInt; handle.m_size = m_size; return true; } unsigned SharedMemory::systemPageSize() { return PAGE_SIZE; } } // namespace WebKit #endif
28.305389
104
0.697271
mlcldh
57be0c35fcf710e6e160fa71ecdaa7a3a5a7475d
10,400
cc
C++
source/tracking/pyG4VSteppingVerbose.cc
yu22mal/geant4_pybind
ff7efc322fe53f39c7ae7ed140861052a92479fd
[ "Unlicense" ]
6
2021-08-08T08:40:13.000Z
2022-03-23T03:05:15.000Z
source/tracking/pyG4VSteppingVerbose.cc
yu22mal/geant4_pybind
ff7efc322fe53f39c7ae7ed140861052a92479fd
[ "Unlicense" ]
3
2021-12-01T14:38:06.000Z
2022-02-10T11:28:28.000Z
source/tracking/pyG4VSteppingVerbose.cc
yu22mal/geant4_pybind
ff7efc322fe53f39c7ae7ed140861052a92479fd
[ "Unlicense" ]
3
2021-07-16T13:57:34.000Z
2022-02-07T11:17:19.000Z
#include <pybind11/pybind11.h> #include <pybind11/stl.h> #include <G4VSteppingVerbose.hh> #include <G4SteppingVerbose.hh> #include <G4SteppingManager.hh> #include <G4Navigator.hh> #include <G4VPhysicalVolume.hh> #include <G4VSensitiveDetector.hh> #include <G4ProcessVector.hh> #include <G4SteppingManager.hh> #include <G4Track.hh> #include <G4UserSteppingAction.hh> #include <G4StepPoint.hh> #include <G4VParticleChange.hh> #include "typecast.hh" #include "opaques.hh" namespace py = pybind11; class PublicG4VSteppingVerbose : public G4VSteppingVerbose { public: using G4VSteppingVerbose::fManager; using G4VSteppingVerbose::fUserSteppingAction; using G4VSteppingVerbose::CorrectedStep; using G4VSteppingVerbose::FirstStep; using G4VSteppingVerbose::fStepStatus; using G4VSteppingVerbose::GeometricalStep; using G4VSteppingVerbose::PhysicalStep; using G4VSteppingVerbose::PreStepPointIsGeom; using G4VSteppingVerbose::Mass; using G4VSteppingVerbose::TempInitVelocity; using G4VSteppingVerbose::TempVelocity; using G4VSteppingVerbose::sumEnergyChange; using G4VSteppingVerbose::fParticleChange; using G4VSteppingVerbose::fPostStepPoint; using G4VSteppingVerbose::fPreStepPoint; using G4VSteppingVerbose::fSecondary; using G4VSteppingVerbose::fStep; using G4VSteppingVerbose::fTrack; using G4VSteppingVerbose::fCurrentProcess; using G4VSteppingVerbose::fCurrentVolume; using G4VSteppingVerbose::fSensitive; using G4VSteppingVerbose::fAlongStepDoItVector; using G4VSteppingVerbose::fAtRestDoItVector; using G4VSteppingVerbose::fPostStepDoItVector; using G4VSteppingVerbose::fAlongStepGetPhysIntVector; using G4VSteppingVerbose::fAtRestGetPhysIntVector; using G4VSteppingVerbose::fPostStepGetPhysIntVector; using G4VSteppingVerbose::MAXofAlongStepLoops; using G4VSteppingVerbose::MAXofAtRestLoops; using G4VSteppingVerbose::MAXofPostStepLoops; using G4VSteppingVerbose::currentMinimumStep; using G4VSteppingVerbose::numberOfInteractionLengthLeft; using G4VSteppingVerbose::fAlongStepDoItProcTriggered; using G4VSteppingVerbose::fAtRestDoItProcTriggered; using G4VSteppingVerbose::fPostStepDoItProcTriggered; using G4VSteppingVerbose::fN2ndariesAlongStepDoIt; using G4VSteppingVerbose::fN2ndariesAtRestDoIt; using G4VSteppingVerbose::fN2ndariesPostStepDoIt; using G4VSteppingVerbose::fNavigator; using G4VSteppingVerbose::verboseLevel; using G4VSteppingVerbose::fSelectedAlongStepDoItVector; using G4VSteppingVerbose::fSelectedAtRestDoItVector; using G4VSteppingVerbose::fSelectedPostStepDoItVector; using G4VSteppingVerbose::fPreviousStepSize; using G4VSteppingVerbose::fTouchableHandle; using G4VSteppingVerbose::StepControlFlag; using G4VSteppingVerbose::fCondition; using G4VSteppingVerbose::fGPILSelection; using G4VSteppingVerbose::physIntLength; }; class PyG4VSteppingVerbose : public G4VSteppingVerbose, public py::trampoline_self_life_support { public: using G4VSteppingVerbose::G4VSteppingVerbose; void NewStep() override { PYBIND11_OVERRIDE(void, G4VSteppingVerbose, NewStep, ); } void AtRestDoItInvoked() override { PYBIND11_OVERRIDE(void, G4VSteppingVerbose, AtRestDoItInvoked, ); } void AlongStepDoItAllDone() override { PYBIND11_OVERRIDE(void, G4VSteppingVerbose, AlongStepDoItAllDone, ); } void PostStepDoItAllDone() override { PYBIND11_OVERRIDE(void, G4VSteppingVerbose, PostStepDoItAllDone, ); } void AlongStepDoItOneByOne() override { PYBIND11_OVERRIDE(void, G4VSteppingVerbose, AlongStepDoItOneByOne, ); } void PostStepDoItOneByOne() override { PYBIND11_OVERRIDE(void, G4VSteppingVerbose, PostStepDoItOneByOne, ); } void StepInfo() override { PYBIND11_OVERRIDE(void, G4VSteppingVerbose, StepInfo, ); } void TrackingStarted() override { PYBIND11_OVERRIDE(void, G4VSteppingVerbose, TrackingStarted, ); } void DPSLStarted() override { PYBIND11_OVERRIDE(void, G4VSteppingVerbose, DPSLStarted, ); } void DPSLUserLimit() override { PYBIND11_OVERRIDE(void, G4VSteppingVerbose, DPSLUserLimit, ); } void DPSLPostStep() override { PYBIND11_OVERRIDE(void, G4VSteppingVerbose, DPSLPostStep, ); } void DPSLAlongStep() override { PYBIND11_OVERRIDE(void, G4VSteppingVerbose, DPSLAlongStep, ); } void VerboseTrack() override { PYBIND11_OVERRIDE(void, G4VSteppingVerbose, VerboseTrack, ); } void VerboseParticleChange() override { PYBIND11_OVERRIDE(void, G4VSteppingVerbose, VerboseParticleChange, ); } }; void export_G4VSteppingVerbose(py::module &m) { py::class_<G4VSteppingVerbose, PyG4VSteppingVerbose>(m, "G4VSteppingVerbose") .def_static("SetInstance", [](py::disown_ptr<G4VSteppingVerbose> instance) { G4VSteppingVerbose::SetInstance(instance); }) .def_static("GetInstance", &G4VSteppingVerbose::GetInstance, py::return_value_policy::reference) .def_static("GetSilent", &G4VSteppingVerbose::GetSilent) .def_static("SetSilent", &G4VSteppingVerbose::SetSilent) .def_static("SetSilentStepInfo", &G4VSteppingVerbose::SetSilentStepInfo) .def("NewStep", &G4VSteppingVerbose::NewStep) .def("CopyState", &G4VSteppingVerbose::CopyState) .def("SetManager", &G4VSteppingVerbose::SetManager) .def("AtRestDoItInvoked", &G4VSteppingVerbose::AtRestDoItInvoked) .def("AlongStepDoItAllDone", &G4VSteppingVerbose::AlongStepDoItAllDone) .def("PostStepDoItAllDone", &G4VSteppingVerbose::PostStepDoItAllDone) .def("AlongStepDoItOneByOne", &G4VSteppingVerbose::AlongStepDoItOneByOne) .def("StepInfo", &G4VSteppingVerbose::StepInfo) .def("TrackingStarted", &G4VSteppingVerbose::TrackingStarted) .def("DPSLStarted", &G4VSteppingVerbose::DPSLStarted) .def("DPSLUserLimit", &G4VSteppingVerbose::DPSLUserLimit) .def("DPSLPostStep", &G4VSteppingVerbose::DPSLPostStep) .def("DPSLAlongStep", &G4VSteppingVerbose::DPSLAlongStep) .def("VerboseTrack", &G4VSteppingVerbose::VerboseTrack) .def("VerboseParticleChange", &G4VSteppingVerbose::VerboseParticleChange) .def_readwrite("fManager", &PublicG4VSteppingVerbose::fManager) .def_readwrite("fUserSteppingAction", &PublicG4VSteppingVerbose::fUserSteppingAction) .def_readwrite("PhysicalStep", &PublicG4VSteppingVerbose::PhysicalStep) .def_readwrite("GeometricalStep", &PublicG4VSteppingVerbose::GeometricalStep) .def_readwrite("CorrectedStep", &PublicG4VSteppingVerbose::CorrectedStep) .def_readwrite("PreStepPointIsGeom", &PublicG4VSteppingVerbose::PreStepPointIsGeom) .def_readwrite("FirstStep", &PublicG4VSteppingVerbose::FirstStep) .def_readwrite("fStepStatus", &PublicG4VSteppingVerbose::fStepStatus) .def_readwrite("TempInitVelocity", &PublicG4VSteppingVerbose::TempInitVelocity) .def_readwrite("TempVelocity", &PublicG4VSteppingVerbose::TempVelocity) .def_readwrite("Mass", &PublicG4VSteppingVerbose::Mass) .def_readwrite("sumEnergyChange", &PublicG4VSteppingVerbose::sumEnergyChange) .def_readwrite("fParticleChange", &PublicG4VSteppingVerbose::fParticleChange) .def_readwrite("fTrack", &PublicG4VSteppingVerbose::fTrack) .def_readwrite("fSecondary", &PublicG4VSteppingVerbose::fSecondary) .def_readwrite("fStep", &PublicG4VSteppingVerbose::fStep) .def_readwrite("fPreStepPoint", &PublicG4VSteppingVerbose::fPreStepPoint) .def_readwrite("fPostStepPoint", &PublicG4VSteppingVerbose::fPostStepPoint) .def_readwrite("fCurrentVolume", &PublicG4VSteppingVerbose::fCurrentVolume) .def_readwrite("fSensitive", &PublicG4VSteppingVerbose::fSensitive) .def_readwrite("fCurrentProcess", &PublicG4VSteppingVerbose::fCurrentProcess) .def_readwrite("fAtRestDoItVector", &PublicG4VSteppingVerbose::fAtRestDoItVector) .def_readwrite("fAlongStepDoItVector", &PublicG4VSteppingVerbose::fAlongStepDoItVector) .def_readwrite("fPostStepDoItVector", &PublicG4VSteppingVerbose::fPostStepDoItVector) .def_readwrite("fAtRestGetPhysIntVector", &PublicG4VSteppingVerbose::fAtRestGetPhysIntVector) .def_readwrite("fAlongStepGetPhysIntVector", &PublicG4VSteppingVerbose::fAlongStepGetPhysIntVector) .def_readwrite("fPostStepGetPhysIntVector", &PublicG4VSteppingVerbose::fPostStepGetPhysIntVector) .def_readwrite("MAXofAtRestLoops", &PublicG4VSteppingVerbose::MAXofAtRestLoops) .def_readwrite("MAXofAlongStepLoops", &PublicG4VSteppingVerbose::MAXofAlongStepLoops) .def_readwrite("MAXofPostStepLoops", &PublicG4VSteppingVerbose::MAXofPostStepLoops) .def_readwrite("currentMinimumStep", &PublicG4VSteppingVerbose::currentMinimumStep) .def_readwrite("numberOfInteractionLengthLeft", &PublicG4VSteppingVerbose::numberOfInteractionLengthLeft) .def_readwrite("fAtRestDoItProcTriggered", &PublicG4VSteppingVerbose::fAtRestDoItProcTriggered) .def_readwrite("fAlongStepDoItProcTriggered", &PublicG4VSteppingVerbose::fAlongStepDoItProcTriggered) .def_readwrite("fPostStepDoItProcTriggered", &PublicG4VSteppingVerbose::fPostStepDoItProcTriggered) .def_readwrite("fN2ndariesAtRestDoIt", &PublicG4VSteppingVerbose::fN2ndariesAtRestDoIt) .def_readwrite("fN2ndariesAlongStepDoIt", &PublicG4VSteppingVerbose::fN2ndariesAlongStepDoIt) .def_readwrite("fN2ndariesPostStepDoIt", &PublicG4VSteppingVerbose::fN2ndariesPostStepDoIt) .def_readwrite("fNavigator", &PublicG4VSteppingVerbose::fNavigator) .def_readwrite("verboseLevel", &PublicG4VSteppingVerbose::verboseLevel) .def_readwrite("fSelectedAtRestDoItVector", &PublicG4VSteppingVerbose::fSelectedAtRestDoItVector) .def_readwrite("fSelectedAlongStepDoItVector", &PublicG4VSteppingVerbose::fSelectedAlongStepDoItVector) .def_readwrite("fSelectedPostStepDoItVector", &PublicG4VSteppingVerbose::fSelectedPostStepDoItVector) .def_readwrite("fPreviousStepSize", &PublicG4VSteppingVerbose::fPreviousStepSize) .def_readwrite("fTouchableHandle", &PublicG4VSteppingVerbose::fTouchableHandle) .def_readwrite("StepControlFlag", &PublicG4VSteppingVerbose::StepControlFlag) .def_readwrite("physIntLength", &PublicG4VSteppingVerbose::physIntLength) .def_readwrite("fCondition", &PublicG4VSteppingVerbose::fCondition) .def_readwrite("fGPILSelection", &PublicG4VSteppingVerbose::fGPILSelection); }
47.058824
114
0.793846
yu22mal
57befa71c36d17f4002708b73496a2f71d0dedbf
109
cc
C++
live/score.cc
netromdk/patching
e08dd1655c1c3464c54e633423f231780853afe9
[ "MIT" ]
2
2016-10-18T02:19:30.000Z
2019-09-12T02:40:37.000Z
live/score.cc
netromdk/patching
e08dd1655c1c3464c54e633423f231780853afe9
[ "MIT" ]
null
null
null
live/score.cc
netromdk/patching
e08dd1655c1c3464c54e633423f231780853afe9
[ "MIT" ]
null
null
null
#include <iostream> int main() { int score = 1; std::cout << "score = " << score << "\n"; return 0; }
13.625
43
0.513761
netromdk
57c2d05e086d53b3dd0832a7a37a3583a84af4f6
10,687
hpp
C++
include/strf/to_string.hpp
robhz786/strf
72163cb10f5cc725788bbce74ce16e4024489734
[ "BSL-1.0" ]
49
2019-12-16T10:39:22.000Z
2022-03-28T02:32:47.000Z
include/strf/to_string.hpp
ckerr/strf
72163cb10f5cc725788bbce74ce16e4024489734
[ "BSL-1.0" ]
36
2019-12-13T00:31:22.000Z
2022-03-13T18:22:14.000Z
include/strf/to_string.hpp
ckerr/strf
72163cb10f5cc725788bbce74ce16e4024489734
[ "BSL-1.0" ]
3
2019-12-07T20:05:51.000Z
2021-11-30T02:45:35.000Z
#ifndef STRF_DETAIL_OUTPUT_TYPES_STD_STRING_HPP #define STRF_DETAIL_OUTPUT_TYPES_STD_STRING_HPP // Copyright (C) (See commit logs on github.com/robhz786/strf) // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #include <strf/destination.hpp> #include <strf.hpp> #include <string> namespace strf { template < typename CharT , typename Traits = std::char_traits<CharT> , typename Allocator = std::allocator<CharT> > class basic_string_appender final: public strf::destination<CharT> { using string_type_ = std::basic_string<CharT, Traits, Allocator>; public: basic_string_appender(string_type_& str) : strf::destination<CharT>(buf_, buf_size_) , str_(str) { } basic_string_appender( string_type_& str , std::size_t size ) : strf::destination<CharT>(buf_, buf_size_) , str_(str) { str_.reserve(size); } basic_string_appender(const basic_string_appender&) = delete; basic_string_appender(basic_string_appender&&) = delete; void recycle() override { auto * p = this->buffer_ptr(); this->set_buffer_ptr(buf_); STRF_IF_LIKELY (this->good()) { this->set_good(false); str_.append(buf_, p); this->set_good(true); } } void finish() { auto * p = this->buffer_ptr(); STRF_IF_LIKELY (this->good()) { this->set_good(false); str_.append(buf_, p); } } private: void do_write(const CharT* str, std::size_t str_len) override { auto * p = this->buffer_ptr(); this->set_buffer_ptr(buf_); STRF_IF_LIKELY (this->good()) { this->set_good(false); str_.append(buf_, p); str_.append(str, str_len); this->set_good(true); } } string_type_& str_; static constexpr std::size_t buf_size_ = strf::min_space_after_recycle<CharT>(); CharT buf_[buf_size_]; }; template < typename CharT , typename Traits = std::char_traits<CharT> , typename Allocator = std::allocator<CharT> > class basic_string_maker final: public strf::destination<CharT> { using string_type_ = std::basic_string<CharT, Traits, Allocator>; public: basic_string_maker() : strf::destination<CharT>(buf_, buf_size_) { } basic_string_maker(strf::tag<void>) : basic_string_maker() { } basic_string_maker(const basic_string_maker&) = delete; basic_string_maker(basic_string_maker&&) = delete; ~basic_string_maker() { if (string_initialized_) { string_ptr()->~string_type_(); } } void recycle() override; string_type_ finish() { STRF_IF_LIKELY (this->good()) { this->set_good(false); std::size_t count = this->buffer_ptr() - buf_; STRF_IF_LIKELY ( ! string_initialized_) { return {buf_, count}; } string_ptr() -> append(buf_, count); return std::move(*string_ptr()); } return {}; } private: void do_write(const CharT* str, std::size_t str_len) override; bool string_initialized_ = false; string_type_* string_ptr() { void* ptr = &string_obj_space_; return reinterpret_cast<string_type_*>(ptr); } static constexpr std::size_t buf_size_ = strf::min_space_after_recycle<CharT>(); CharT buf_[buf_size_]; using string_storage_type_ = typename std::aligned_storage < sizeof(string_type_), alignof(string_type_) > :: type; string_storage_type_ string_obj_space_; }; template < typename CharT, typename Traits, typename Allocator > void basic_string_maker<CharT, Traits, Allocator>::recycle() { std::size_t count = this->buffer_ptr() - buf_; this->set_buffer_ptr(buf_); STRF_IF_LIKELY (this->good()) { this->set_good(false); // in case the following code throws if ( ! string_initialized_) { new (string_ptr()) string_type_{buf_, count}; string_initialized_ = true; } else { string_ptr() -> append(buf_, count); } this->set_good(true); } } template < typename CharT, typename Traits, typename Allocator > void basic_string_maker<CharT, Traits, Allocator>::do_write(const CharT* str, std::size_t str_len) { STRF_IF_LIKELY (this->good()) { std::size_t buf_count = this->buffer_ptr() - buf_; this->set_buffer_ptr(buf_); this->set_good(false); // in case the following code throws if ( ! string_initialized_) { new (string_ptr()) string_type_(); string_ptr()->reserve((buf_count + str_len) << 1); string_ptr()->append(buf_, buf_count); string_ptr()->append(str, str_len); string_initialized_ = true; } else { string_ptr()->append(buf_, buf_count); string_ptr()->append(str, str_len); } this->set_good(true); } } template < typename CharT , typename Traits = std::char_traits<CharT> , typename Allocator = std::allocator<CharT> > class basic_sized_string_maker final : public strf::destination<CharT> { public: explicit basic_sized_string_maker(std::size_t count) : strf::destination<CharT>(nullptr, nullptr) , str_(count ? count : 1, (CharT)0) { this->set_buffer_ptr(&*str_.begin()); this->set_buffer_end(&*str_.begin() + (count ? count : 1)); } basic_sized_string_maker(const basic_sized_string_maker&) = delete; basic_sized_string_maker(basic_sized_string_maker&&) = delete; void recycle() override { std::size_t original_size = this->buffer_ptr() - str_.data(); constexpr std::size_t min_buff_size = strf::min_space_after_recycle<CharT>(); auto append_size = strf::detail::max<std::size_t>(original_size, min_buff_size); str_.append(append_size, (CharT)0); this->set_buffer_ptr(&*str_.begin() + original_size); this->set_buffer_end(&*str_.begin() + original_size + append_size); } std::basic_string<CharT, Traits, Allocator> finish() { str_.resize(this->buffer_ptr() - str_.data()); return std::move(str_); } private: std::basic_string<CharT, Traits, Allocator> str_; }; using string_appender = basic_string_appender<char>; using u16string_appender = basic_string_appender<char16_t>; using u32string_appender = basic_string_appender<char32_t>; using wstring_appender = basic_string_appender<wchar_t>; using string_maker = basic_string_maker<char>; using u16string_maker = basic_string_maker<char16_t>; using u32string_maker = basic_string_maker<char32_t>; using wstring_maker = basic_string_maker<wchar_t>; using sized_string_maker = basic_sized_string_maker<char>; using sized_u16string_maker = basic_sized_string_maker<char16_t>; using sized_u32string_maker = basic_sized_string_maker<char32_t>; using sized_wstring_maker = basic_sized_string_maker<wchar_t>; #if defined(__cpp_char8_t) using u8string_appender = basic_string_appender<char8_t>; using u8string_maker = basic_string_maker<char8_t>; using pre_sized_u8string_maker = basic_sized_string_maker<char8_t>; #endif namespace detail { template <typename CharT, typename Traits, typename Allocator> class basic_string_appender_creator { public: using char_type = CharT; using destination_type = strf::basic_string_appender<CharT, Traits, Allocator>; using sized_destination_type = destination_type; using finish_type = void; basic_string_appender_creator ( std::basic_string<CharT, Traits, Allocator>& str ) : str_(str) { } basic_string_appender_creator(const basic_string_appender_creator&) = default; std::basic_string<CharT, Traits, Allocator>& create() const noexcept { return str_; } std::basic_string<CharT, Traits, Allocator>& create(std::size_t size) const noexcept { str_.reserve(str_.size() + size); return str_; } private: std::basic_string<CharT, Traits, Allocator>& str_; }; template < typename CharT , typename Traits = std::char_traits<CharT> , typename Allocator = std::allocator<CharT> > class basic_string_maker_creator { public: using char_type = CharT; using finish_type = std::basic_string<CharT, Traits, Allocator>; using destination_type = strf::basic_string_maker<CharT, Traits, Allocator>; using sized_destination_type = strf::basic_sized_string_maker<CharT, Traits, Allocator>; strf::tag<void> create() const noexcept { return strf::tag<void>{}; } std::size_t create(std::size_t size) const noexcept { return size; } }; } template <typename CharT, typename Traits, typename Allocator> inline auto append(std::basic_string<CharT, Traits, Allocator>& str) -> strf::destination_no_reserve < strf::detail::basic_string_appender_creator<CharT, Traits, Allocator> > { return strf::destination_no_reserve < strf::detail::basic_string_appender_creator<CharT, Traits, Allocator> > { str }; } template <typename CharT, typename Traits, typename Allocator> inline auto assign(std::basic_string<CharT, Traits, Allocator>& str) -> strf::destination_no_reserve < strf::detail::basic_string_appender_creator<CharT, Traits, Allocator> > { str.clear(); return append(str); } #if defined(STRF_HAS_VARIABLE_TEMPLATES) template< typename CharT , typename Traits = std::char_traits<CharT> , typename Allocator = std::allocator<CharT> > constexpr strf::destination_no_reserve < strf::detail::basic_string_maker_creator<CharT, Traits, Allocator> > to_basic_string{}; #endif // defined(STRF_HAS_VARIABLE_TEMPLATES) #if defined(__cpp_char8_t) constexpr strf::destination_no_reserve < strf::detail::basic_string_maker_creator<char8_t> > to_u8string{}; #endif constexpr strf::destination_no_reserve < strf::detail::basic_string_maker_creator<char> > to_string{}; constexpr strf::destination_no_reserve < strf::detail::basic_string_maker_creator<char16_t> > to_u16string{}; constexpr strf::destination_no_reserve < strf::detail::basic_string_maker_creator<char32_t> > to_u32string{}; constexpr strf::destination_no_reserve < strf::detail::basic_string_maker_creator<wchar_t> > to_wstring{}; } // namespace strf #endif // STRF_DETAIL_OUTPUT_TYPES_STD_STRING_HPP
29.199454
98
0.669879
robhz786
57c5b18d422e0297b27d64813751f64fefa63d02
456
cpp
C++
sc-virt/src/lib/Transforms/ScVirt/OpcodeGenerator.cpp
tum-i4/dta-vs-osc
b39f4d4eb6ffea501025fc3e07622251c2118fe0
[ "MIT" ]
15
2021-12-08T09:53:35.000Z
2022-03-07T10:13:37.000Z
sc-virt/src/lib/Transforms/ScVirt/OpcodeGenerator.cpp
tum-i4/dta-vs-osc
b39f4d4eb6ffea501025fc3e07622251c2118fe0
[ "MIT" ]
null
null
null
sc-virt/src/lib/Transforms/ScVirt/OpcodeGenerator.cpp
tum-i4/dta-vs-osc
b39f4d4eb6ffea501025fc3e07622251c2118fe0
[ "MIT" ]
1
2021-12-13T22:45:20.000Z
2021-12-13T22:45:20.000Z
#include "llvm/Transforms/ScVirt/OpcodeGenerator.hpp" #include "llvm/Support/Debug.h" #include "llvm/Support/raw_ostream.h" #define DEBUG_TYPE "OpcodeGenerator" using namespace llvm; uint16_t OpcodeGenerator::generate() { auto Res = Distr(Generator); while(UsedList.find(Res) != UsedList.end()) { Res = Distr(Generator); } UsedList.emplace(Res); return Res; } void OpcodeGenerator::release(const uint16_t Val) { UsedList.erase(Val); }
20.727273
53
0.730263
tum-i4
57c5cd5b95fad6a645cf3533d90300ba97a02577
3,941
cpp
C++
UVa 1342 - That Nice Euler Circuit/sample/1342 - That Nice Euler Circuit.cpp
tadvi/uva
0ac0cbdf593879b4fb02a3efc09adbb031cb47d5
[ "MIT" ]
1
2020-11-24T03:17:21.000Z
2020-11-24T03:17:21.000Z
UVa 1342 - That Nice Euler Circuit/sample/1342 - That Nice Euler Circuit.cpp
tadvi/uva
0ac0cbdf593879b4fb02a3efc09adbb031cb47d5
[ "MIT" ]
null
null
null
UVa 1342 - That Nice Euler Circuit/sample/1342 - That Nice Euler Circuit.cpp
tadvi/uva
0ac0cbdf593879b4fb02a3efc09adbb031cb47d5
[ "MIT" ]
1
2021-04-11T16:22:31.000Z
2021-04-11T16:22:31.000Z
// Euler characteristic, V - E + F = 2 #include <stdio.h> #include <math.h> #include <algorithm> #include <set> #include <map> #include <assert.h> #include <vector> #include <string.h> using namespace std; #define eps 1e-8 struct Pt { double x, y; Pt(double a = 0, double b = 0): x(a), y(b) {} Pt operator-(const Pt &a) const { return Pt(x - a.x, y - a.y); } Pt operator+(const Pt &a) const { return Pt(x + a.x, y + a.y); } Pt operator*(const double a) const { return Pt(x * a, y * a); } bool operator==(const Pt &a) const { return fabs(x - a.x) < eps && fabs(y - a.y) < eps; } bool operator!=(const Pt &a) const { return !(a == *this); } bool operator<(const Pt &a) const { if (fabs(x - a.x) > eps) return x < a.x; if (fabs(y - a.y) > eps) return y < a.y; return false; } double length() { return hypot(x, y); } void read() { scanf("%lf %lf", &x, &y); } }; const double pi = acos(-1); int cmpZero(double v) { if (fabs(v) > eps) return v > 0 ? 1 : -1; return 0; } double dot(Pt a, Pt b) { return a.x * b.x + a.y * b.y; } double cross(Pt o, Pt a, Pt b) { return (a.x-o.x)*(b.y-o.y)-(a.y-o.y)*(b.x-o.x); } double cross2(Pt a, Pt b) { return a.x * b.y - a.y * b.x; } int between(Pt a, Pt b, Pt c) { return dot(c - a, b - a) >= -eps && dot(c - b, a - b) >= -eps; } int onSeg(Pt a, Pt b, Pt c) { return between(a, b, c) && fabs(cross(a, b, c)) < eps; } struct Seg { Pt s, e; int label; Seg(Pt a = Pt(), Pt b = Pt(), int l=0): s(a), e(b), label(l) { } bool operator!=(const Seg &other) const { return !((s == other.s && e == other.e) || (e == other.s && s == other.e)); } }; int intersection(Pt as, Pt at, Pt bs, Pt bt) { if (cmpZero(cross(as, at, bs) * cross(as, at, bt)) < 0 && cmpZero(cross(bs, bt, as) * cross(bs, bt, at)) < 0) return 1; return 0; } Pt getIntersect(Seg a, Seg b) { Pt u = a.s - b.s; double t = cross2(b.e - b.s, u)/cross2(a.e - a.s, b.e - b.s); return a.s + (a.e - a.s) * t; } double getAngle(Pt va, Pt vb) { // segment, not vector return acos(dot(va, vb) / va.length() / vb.length()); } Pt rotateRadian(Pt a, double radian) { double x, y; x = a.x * cos(radian) - a.y * sin(radian); y = a.x * sin(radian) + a.y * cos(radian); return Pt(x, y); } int inPolygon(vector<Pt> &p, Pt q) { int i, j, cnt = 0; int n = p.size(); for(i = 0, j = n-1; i < n; j = i++) { if(onSeg(p[i], p[j], q)) return 1; if(p[i].y > q.y != p[j].y > q.y && q.x < (p[j].x-p[i].x)*(q.y-p[i].y)/(p[j].y-p[i].y) + p[i].x) cnt++; } return cnt&1; } double polygonArea(vector<Pt> &p) { double area = 0; int n = p.size(); for(int i = 0; i < n;i++) area += p[i].x * p[(i+1)%n].y - p[i].y * p[(i+1)%n].x; return fabs(area) /2; } Pt projectLine(Pt as, Pt ae, Pt p) { double a, b, c, v; a = as.y - ae.y, b = ae.x - as.x; c = - (a * as.x + b * as.y); v = a * p.x + b * p.y + c; return Pt(p.x - v*a / (a*a+b*b), p.y - v*b/ (a*a+b*b)); } // maybe collinear !!!!!!!! int main() { const int MAXN = 305; int n, cases = 0; Pt D[MAXN]; while (scanf("%d", &n) == 1 && n) { int V = 0, E = 0; vector<Pt> SV; for (int i = 0; i < n; i++) D[i].read(), SV.push_back(D[i]); for (int i = 0; i+1 < n; i++) { for (int j = i+1; j+1 < n; j++) { if (intersection(D[i], D[i+1], D[j], D[j+1])) { Pt p = getIntersect(Seg(D[i], D[i+1]), Seg(D[j], D[j+1])); SV.push_back(p); } } } sort(SV.begin(), SV.end()); SV.resize(unique(SV.begin(), SV.end()) - SV.begin()); V = SV.size(), E = n - 1; for (int i = 0; i < SV.size(); i++) { for (int j = 0; j+1 < n; j++) { if (onSeg(D[j], D[j+1], SV[i]) && SV[i] != D[j] && SV[i] != D[j+1]) E++; } } // printf("%d %d\n", E, V); int ret = E - V + 2; // V - E + F = 2, F = E - V + 2 printf("Case %d: There are %d pieces.\n", ++cases, ret); } return 0; } /* 7 1 1 1 5 2 1 2 5 5 1 3 5 1 1 0 */
24.177914
77
0.4915
tadvi
57c658905af1af182a86b61a8114805c9749fd27
4,836
cc
C++
net/instaweb/rewriter/mobilize_menu_render_filter_test.cc
crowell/modpagespeed_tmp
d2c063875d819c46c2d88a5ddb70578cae2a5909
[ "Apache-2.0" ]
null
null
null
net/instaweb/rewriter/mobilize_menu_render_filter_test.cc
crowell/modpagespeed_tmp
d2c063875d819c46c2d88a5ddb70578cae2a5909
[ "Apache-2.0" ]
null
null
null
net/instaweb/rewriter/mobilize_menu_render_filter_test.cc
crowell/modpagespeed_tmp
d2c063875d819c46c2d88a5ddb70578cae2a5909
[ "Apache-2.0" ]
null
null
null
/* * Copyright 2015 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // Author: morlovich@google.com (Maksim Orlovich) #include "net/instaweb/rewriter/public/mobilize_menu_render_filter.h" #include "base/logging.h" #include "net/instaweb/rewriter/public/rewrite_driver.h" #include "net/instaweb/rewriter/public/rewrite_options.h" #include "net/instaweb/rewriter/public/rewrite_test_base.h" #include "net/instaweb/rewriter/public/server_context.h" #include "net/instaweb/rewriter/public/test_rewrite_driver_factory.h" #include "pagespeed/kernel/base/gtest.h" #include "pagespeed/kernel/base/scoped_ptr.h" #include "pagespeed/kernel/base/string_util.h" #include "pagespeed/kernel/http/content_type.h" #include "pagespeed/opt/http/mock_property_page.h" #include "pagespeed/opt/http/property_cache.h" #include "pagespeed/opt/http/request_context.h" namespace net_instaweb { namespace { const char kPageUrl[] = "http://test.com/page.html"; // Much simplified version of kActualMenu1 the same in MobilizeMenuFilterTest const char kContent[] = "<nav data-mobile-role=navigational>" "<ul>" " <li><a href='/submenu1'>Submenu1</a>" " <ul>" " <li><a href='/a'>A</a></li>" " <li><a href='/b'>B</a><li>" " <li><a href='/c'>C</a></li>" " </ul>" " </li>" " <li><a href='/submenu2'>Submenu2</a>" " <ul>" " <li><a href='/d'>D</a></li>" " <li><a href='/e'>E</a></li>" " <li><a href='/f'>F</a></li>" " </ul>" " </li>" "</ul>" "</nav>"; class MobilizeMenuRenderFilterTest : public RewriteTestBase { protected: MobilizeMenuRenderFilterTest() : pcache_(NULL), page_(NULL) {} virtual void SetUp() { RewriteTestBase::SetUp(); filter_.reset(new MobilizeMenuRenderFilter(rewrite_driver())); options()->ClearSignatureForTesting(); options()->set_mob_always(true); server_context()->ComputeSignature(options()); rewrite_driver()->AppendOwnedPreRenderFilter(filter_.release()); SetResponseWithDefaultHeaders(kPageUrl, kContentTypeHtml, kContent, 100); pcache_ = rewrite_driver()->server_context()->page_property_cache(); const PropertyCache::Cohort* dom_cohort = SetupCohort(pcache_, RewriteDriver::kDomCohort); server_context()->set_dom_cohort(dom_cohort); ClearDriverAndSetUpPCache(); } void ClearDriverAndSetUpPCache() { rewrite_driver()->Clear(); rewrite_driver()->set_request_context( RequestContext::NewTestRequestContext(factory()->thread_system())); page_ = NewMockPage(kPageUrl); rewrite_driver()->set_property_page(page_); pcache_->Read(page_); } virtual bool AddHtmlTags() const { return false; } scoped_ptr<MobilizeMenuRenderFilter> filter_; PropertyCache* pcache_; PropertyPage* page_; }; TEST_F(MobilizeMenuRenderFilterTest, BasicOperation) { const char kMenu[] = "<!--Computed menu:entries {\n" " name: \"Submenu1\"\n" " submenu {\n" " entries {\n" " name: \"A\"\n" " url: \"/a\"\n" " }\n" " entries {\n" " name: \"B\"\n" " url: \"/b\"\n" " }\n" " entries {\n" " name: \"C\"\n" " url: \"/c\"\n" " }\n" " entries {\n" " name: \"Submenu1\"\n" " url: \"/submenu1\"\n" " }\n" " }\n" "}\n" "entries {\n" " name: \"Submenu2\"\n" " submenu {\n" " entries {\n" " name: \"D\"\n" " url: \"/d\"\n" " }\n entries {\n" " name: \"E\"\n" " url: \"/e\"\n" " }\n" " entries {\n" " name: \"F\"\n" " url: \"/f\"\n" " }\n" " entries {\n" " name: \"Submenu2\"\n" " url: \"/submenu2\"\n" " }\n" " }\n" "}\n" "-->"; // computes. ValidateExpected("page", kContent, StrCat(kContent, kMenu)); // Does the same thing from pcache. SetFetchResponse404(kPageUrl); ValidateExpected("page", kContent, StrCat(kContent, kMenu)); } TEST_F(MobilizeMenuRenderFilterTest, HandleFailure) { // Note that Done(false) makes computation fail, 404 doesn't. SetFetchFailOnUnexpected(false); ValidateExpected("not_page", kContent, StrCat(kContent, "<!--No computed menu-->")); } } // namespace } // namespace net_instaweb
30.037267
77
0.622622
crowell
57c966f2fc476239a6d8772ac677792003b36486
735
cpp
C++
src/reference.cpp
cscheid/guitar
b6ae866f3724822e151d6e9ecedfabcf13860c48
[ "Apache-2.0" ]
2
2015-01-08T00:08:48.000Z
2018-10-24T22:15:27.000Z
src/reference.cpp
cscheid/guitar
b6ae866f3724822e151d6e9ecedfabcf13860c48
[ "Apache-2.0" ]
null
null
null
src/reference.cpp
cscheid/guitar
b6ae866f3724822e151d6e9ecedfabcf13860c48
[ "Apache-2.0" ]
1
2018-10-24T22:15:28.000Z
2018-10-24T22:15:28.000Z
#include "reference.h" #include "entry_points.h" using namespace Rcpp; GitReference::GitReference(git_reference *_ref) { ref = boost::shared_ptr<git_reference>(_ref, git_reference_free); } bool GitReference::has_log() { return git_reference_has_log(ref.get()); } SEXP GitReference::peel(unsigned int otype) { BEGIN_RCPP git_object *result; int err = git_reference_peel(&result, ref.get(), (git_otype) otype); if (err) throw Rcpp::exception("git_reference_peel failed"); return object_to_sexp(result); END_RCPP } RCPP_MODULE(guitar_reference) { class_<GitReference>("Reference") .method("has_log", &GitReference::has_log) .method("peel", &GitReference::peel) ; }
22.272727
72
0.693878
cscheid
57cc9065e37403ba79e00f4dcf601fd1a4920adc
681
cpp
C++
MainFolder/Compass_debug/calibrate_com.cpp
chrismolli/quad101
687e219d41bc247c61e4c7776ce8f0ada2e29551
[ "MIT" ]
1
2018-02-06T02:11:47.000Z
2018-02-06T02:11:47.000Z
MainFolder/Compass_debug/calibrate_com.cpp
chrismolli/quad101
687e219d41bc247c61e4c7776ce8f0ada2e29551
[ "MIT" ]
4
2016-06-21T22:00:09.000Z
2016-10-25T17:38:03.000Z
MainFolder/Compass_debug/calibrate_com.cpp
chrismolli/quad101
687e219d41bc247c61e4c7776ce8f0ada2e29551
[ "MIT" ]
3
2017-04-27T20:19:16.000Z
2021-01-17T23:46:34.000Z
/* Debuging script for tilt compensated compass */ #include "Arduino.h" #include "Timer.h" #include "../lib/Sensors/IMU/imu.h" #define SAMPLE_RATE_X 10 Timer t; IMU imu; void data(){ imu.update(SAMPLE_RATE_X); } void serial(){ //imu.debug(); //imu.com.sendSerial(); Serial.print(imu.rot[0]); Serial.print(","); Serial.print(imu.rot[1]); Serial.print(","); Serial.print(imu.rot[2]); Serial.println(";"); } //Mainroutines void setup(){ Serial.begin(230400); while(!Serial); imu.begin(); imu.com.calibrate(); t.every(SAMPLE_RATE_X,data); t.every(10*SAMPLE_RATE_X,serial); } void loop(){ //t.update(); //if(Serial.available()) Serial.end(); }
15.477273
44
0.646109
chrismolli
57cd0a87c1529f73fb77b5fbaf9ecd99b3d829e3
3,232
cpp
C++
applications/plugins/Compliant/misc/FailNode.cpp
sofa-framework/issofa
94855f488465bc3ed41223cbde987581dfca5389
[ "OML" ]
null
null
null
applications/plugins/Compliant/misc/FailNode.cpp
sofa-framework/issofa
94855f488465bc3ed41223cbde987581dfca5389
[ "OML" ]
null
null
null
applications/plugins/Compliant/misc/FailNode.cpp
sofa-framework/issofa
94855f488465bc3ed41223cbde987581dfca5389
[ "OML" ]
null
null
null
#include "FailNode.h" namespace sofa { namespace simulation { using namespace core::objectmodel; void FailNode::doExecuteVisitor(simulation::Visitor* /*action*/, bool /*precomputedOrder*/) { fail(); } void FailNode::fail() { throw std::logic_error("not implemented"); } void* FailNode::getObject(const sofa::core::objectmodel::BaseClass* /*class_info*/, const sofa::core::objectmodel::TagSet& /*tags*/, SearchDirection /*dir*/ ) const { fail(); return 0; } Node* FailNode::findCommonParent( simulation::Node* /*node2*/ ) {fail(); return 0; } void* FailNode::getObject(const sofa::core::objectmodel::BaseClass* /*class_info*/, const std::string& /*path*/) const { fail(); return 0; } void FailNode::getObjects(const sofa::core::objectmodel::BaseClass* /*class_info*/, GetObjectsCallBack& /*container*/, const sofa::core::objectmodel::TagSet& /*tags*/, SearchDirection /*dir*/ ) const { fail(); } Node::SPtr FailNode::createChild(const std::string& /*nodeName*/) { fail(); return 0;} FailNode::Parents FailNode::getParents() const { fail(); FailNode::Parents oNull; return oNull; } FailNode::Children FailNode::getChildren() const { fail(); FailNode::Parents oNull; return oNull; } /// returns number of parents size_t FailNode::getNbParents() const { fail(); return 0;} /// return the first parent (returns NULL if no parent) BaseNode* FailNode::getFirstParent() const { fail(); return NULL; } /// Add a child node void FailNode::addChild(BaseNode::SPtr /*node*/){ fail(); } /// Remove a child node void FailNode::removeChild(BaseNode::SPtr /*node*/){ fail(); } /// Move a node from another node void FailNode::moveChild(BaseNode::SPtr /*node*/){ fail(); } /// Add a generic object bool FailNode::addObject(BaseObject::SPtr /*obj*/){ fail(); return 0; } /// Remove a generic object bool FailNode::removeObject(BaseObject::SPtr /*obj*/){ fail(); return 0; } /// Move an object from a node to another node void FailNode::moveObject(BaseObject::SPtr /*obj*/){ fail(); } /// Test if the given node is a parent of this node. bool FailNode::hasParent(const BaseNode* /*node*/) const{ fail(); return 0; } /// Test if the given node is an ancestor of this node. /// An ancestor is a parent or (recursively) the parent of an ancestor. bool FailNode::hasAncestor(const BaseNode * /*node*/) const{ fail(); return 0; } bool FailNode::hasAncestor(const BaseContext * /*context*/) const{ fail(); return 0; } /// Remove the current node from the graph: depending on the type of Node, it can have one or several parents. void FailNode::detachFromGraph(){ fail(); } /// Get this node context BaseContext* FailNode::getContext(){ fail(); return 0; } /// Get this node context const BaseContext* FailNode::getContext() const{ fail(); return 0; } /// Return the full path name of this node std::string FailNode::getPathName() const {fail(); return 0; } /// Return the path from this node to the root node std::string FailNode::getRootPath() const {fail(); return 0; } void* FailNode::findLinkDestClass(const BaseClass* /*destType*/, const std::string& /*path*/, const BaseLink* /*link*/){ fail(); return 0;} } }
33.319588
139
0.678527
sofa-framework
57ce35b77d04cbea2b6b75b272998f6a8a49f8e9
1,895
cpp
C++
Includes/font.cpp
dracc/NevolutionX
a1a9495282cc5516ff17521cd57dc46dfa52b85d
[ "MIT" ]
72
2019-03-28T19:23:52.000Z
2022-03-12T05:58:19.000Z
Includes/font.cpp
dracc/NevolutionX
a1a9495282cc5516ff17521cd57dc46dfa52b85d
[ "MIT" ]
94
2019-04-30T06:59:43.000Z
2022-02-20T23:06:25.000Z
Includes/font.cpp
dracc/NevolutionX
a1a9495282cc5516ff17521cd57dc46dfa52b85d
[ "MIT" ]
26
2019-04-27T14:11:11.000Z
2022-03-27T03:18:47.000Z
#include "font.h" #include <cassert> #include "3rdparty/SDL_FontCache/SDL_FontCache.h" #include "infoLog.h" Font::Font(Renderer& renderer, const char* path) : renderer(renderer) { fcFont = FC_CreateFont(); assert(fcFont); bool load_success = FC_LoadFont(fcFont, renderer.getRenderer(), path, 20, FC_MakeColor(250, 250, 250, 255), TTF_STYLE_NORMAL); assert(load_success); } Font::~Font() { FC_FreeFont(fcFont); } std::pair<float, float> Font::draw(const std::string& str, std::pair<float, float> coordinates) { FC_Draw(fcFont, renderer.getRenderer(), std::get<0>(coordinates), std::get<1>(coordinates), "%s", str.c_str()); FC_Rect rect = FC_GetBounds(fcFont, std::get<0>(coordinates), std::get<1>(coordinates), FC_ALIGN_LEFT, FC_MakeScale(1.0f, 1.0f), "%s", str.c_str()); return std::pair<float, float>(rect.w, rect.h); } std::pair<float, float> Font::drawColumn(const std::string& str, std::pair<float, float> coordinates, float maxWidth) { FC_Rect rect = FC_DrawColumn(fcFont, renderer.getRenderer(), std::get<0>(coordinates), std::get<1>(coordinates), static_cast<Uint16>(maxWidth), "%s", str.c_str()); return std::pair<float, float>{ rect.w, rect.h }; } float Font::getFontHeight() const { return FC_GetLineHeight(fcFont); } float Font::getColumnHeight(const std::string& str, float maxWidth) const { return FC_GetColumnHeight(fcFont, static_cast<Uint16>(maxWidth), "%s", str.c_str()); } float Font::getTextHeight(const std::string& str) const { return FC_GetHeight(fcFont, "%s", str.c_str()); } float Font::getTextWidth(const std::string& str) const { return FC_GetWidth(fcFont, "%s", str.c_str()); }
36.442308
90
0.614248
dracc
57ce4fb7cb3d20c09ecb466270ed13f31ea84b47
6,046
cpp
C++
src/HPMeshGen2/main.cpp
DanielZint/hpmeshgen
cdfb9163ed92523fcf41a127c8173097e935c0a3
[ "MIT" ]
2
2022-02-09T08:51:16.000Z
2022-02-09T08:51:27.000Z
src/HPMeshGen2/main.cpp
DanielZint/hpmeshgen
cdfb9163ed92523fcf41a127c8173097e935c0a3
[ "MIT" ]
null
null
null
src/HPMeshGen2/main.cpp
DanielZint/hpmeshgen
cdfb9163ed92523fcf41a127c8173097e935c0a3
[ "MIT" ]
null
null
null
#include <experimental/filesystem> // glog #include <glog/logging.h> #include "Config.h" #include "BsgGenerator.h" // Mesh Function #include "MeshFunctions.h" #include "Simplificator.h" #include "DMO/Solver.h" #include "GridEvaluation/eval.h" #include "baseDirectory.h" #include "Simplify.h" #include "ScalarField/ScalarField.h" #include "Stopwatch/Stopwatch.h" namespace fs = std::experimental::filesystem; void generateBsg( const Config& config ) { BsgGenerator bsgGenerator( config ); if ( config.reductionOutput() ) bsgGenerator.simplificator().simplificationOutput( config.outputFolder() ); bsgGenerator.generate(); //MeshFunctions::printMesh( config.outputFolder() / "fragmentMesh.off", bsgGenerator.fragmentMesh() ); //MeshFunctions::printMesh( config.outputFolder() / "fragmentMeshRefined.off", bsgGenerator.bsg().quadMesh ); //MeshFunctions::printMesh( config.outputFolder() / "fragmentMeshRefinedTri.off", bsgGenerator.bsg().triMesh ); if( config.convexHullDecimation() ) { bsgGenerator.adaptElementsToContour(); } BlockStructuredGrid& bsg = bsgGenerator.bsg(); LOG( INFO ) << "# quads after refinement: " << bsg.quadMesh.n_faces() << std::endl; if ( config.sizegridOutput() ) { bsgGenerator.inputMesh().sizeField().toVTK( config.outputFolder() / "sizegrid.vtk", false ); bsgGenerator.inputMesh().depthField().toVTK( config.outputFolder() / "depthgrid.vtk", false ); } if ( config.blockMeshOutput() ) { MeshFunctions::printMesh( config.outputFolder() / "simplifiedMesh.off", bsgGenerator.simplifiedMesh() ); MeshFunctions::printMesh( config.outputFolder() / "fragmentMesh.off", bsgGenerator.fragmentMesh() ); MeshFunctions::printMesh( config.outputFolder() / "fragmentMeshRefined.off", bsgGenerator.bsg().quadMesh ); } //bsgGenerator.optimizeBsg(); // evaluation MeshFunctions::printMesh( config.outputFolder() / "fineMeshFinal.off", bsg.triMesh ); MeshFunctions::displayQuality( bsg.triMesh, 10 ); // apply depth to BSG //bsgGenerator.inputMesh().applyDepth( bsg.triMesh ); //bsgGenerator.inputMesh().applyDepth( bsg.quadMesh ); /////////////////////// // write bsg to file // // rescale mesh //MeshFunctions::rescaleMesh(*bsg.fineMesh, 1000, 1000, 1000); //bsg.patch_segmentation(nBlocks); //bsg.write_bsg(config.outputFolder(), "BSG_east_b" + std::to_string(nBlocks) + "_f" + std::to_string(bsg.n_patches())); //bsg.write_bsg( config.outputFolder(), "BSG_east_b" + std::to_string(nBlocks) + "_f" + std::to_string(bsg.n_patches()) + "_scaled"); //if (config.meshFile().extension() == ".14") { // bsg.exportMeshAdcirc( config.outputFolder(), config.meshFile().stem().string() + "_" + std::to_string(config.nRefinementSteps()) + ".14"); //} std::string bsgName = std::string( "BSG_" ) + config.meshFile().stem().string() + "_b" + std::to_string( config.nBlocks() ) + "_f" + std::to_string( bsg.nFragments() ); if( config.convexHullDecimation() ) { bsgName += "_m"; } fs::path bsgFolder = config.outputFolder() / bsgName; fs::create_directories( bsgFolder ); if( !config.convexHullDecimation() ) { const auto& sf = bsgGenerator.inputMesh().sizeField(); DMO::UniformGrid grid_d; grid_d.n = { (int)sf.Nx(), (int)sf.Ny() }; grid_d.h = { sf.hx(), sf.hy() }; grid_d.aabbMin = { sf.aabb().xMin, sf.aabb().yMin }; grid_d.aabbMax = { sf.aabb().xMax, sf.aabb().yMax }; thrust::host_vector<float> sgVals; sgVals.resize( grid_d.n.x * grid_d.n.y ); for( int i = 0; i < grid_d.n.x * grid_d.n.y; ++i ) { sgVals[i] = sf( i ); } thrust::device_vector<float> sgVals_d = sgVals; grid_d.vals = sgVals_d.data().get(); DMO::Metrics::MeanRatioTriangle metricMeanRatio; DMO::Metrics::DensityTriangle metricDensity( grid_d ); DMO::Metrics::DensityWithMeanRatioTriangle metricInner( metricMeanRatio, metricDensity ); DMO::DmoMesh dmoMeshInner = DMO::DmoMesh::create<DMO::Set::Inner>( bsg.triMesh ); DMO::Solver dmo( bsg.triMesh, &metricInner, &dmoMeshInner ); dmo.solve( 100 ); DMO::Solver( bsg.triMesh, &metricMeanRatio, &dmoMeshInner ).solve( 1 ); bsg.copy_positions_tri2quad(); } // evaluation MeshFunctions::printMesh( bsgFolder / ( bsgName + "_" + std::to_string( bsg.nGridNodes() ) + ".off" ), bsg.triMesh ); MeshFunctions::printMeshCartesian( bsgFolder / ( bsgName + "_" + std::to_string( bsg.nGridNodes() ) + "_cart.off" ), bsg.triMesh, bsgGenerator.inputMesh() ); MeshFunctions::displayQuality( bsg.triMesh, 10 ); // apply depth to BSG bsgGenerator.inputMesh().applyDepth( bsg.triMesh ); bsgGenerator.inputMesh().applyDepth( bsg.quadMesh ); GridEvaluation::eval( bsg.triMesh, bsgGenerator.inputMesh(), bsgFolder / ( bsgName + "_" + std::to_string( bsg.nGridNodes() ) + ".vtk" ) ); MeshFunctions::printMesh( bsgFolder / "triBlocks.off", bsgGenerator.simplifiedMesh() ); MeshFunctions::printMeshCartesian( bsgFolder / "triBlocks_cart.off", bsgGenerator.simplifiedMesh(), bsgGenerator.inputMesh() ); bsg.patch_segmentation( config.nBlocks() ); bsg.write_bsg( bsgFolder, bsgName, config.convexHullDecimation() ); // only write BSG and fort files if input is a fort.14 file if( config.meshFile().extension() == ".14" ) { bsg.exportMeshAdcirc( bsgFolder, config.meshFile().stem().string() + "_" + std::to_string( bsg.nGridNodes() ) + ".14", bsgGenerator.inputMesh() ); } //bsg.print_svg( config.outputFolder().string() + "bsgPrint.svg" ); } int main( int argc, char* argv[] ) { google::InitGoogleLogging( argv[0] ); //FLAGS_timestamp_in_logfile_name = false; FLAGS_logtostderr = true; FLAGS_colorlogtostderr = true; fs::current_path( BASE_DIRECTORY ); // load config file const Config config( "HPMeshGenParameter.txt" ); // set logging flags //FLAGS_logtostderr = false; //FLAGS_alsologtostderr = true; //FLAGS_log_dir = config.outputFolder().string(); // print config to log config.log(); // do it! Stopwatch sw; sw.start(); generateBsg( config ); sw.stop(); LOG( WARNING ) << "Runtime: " << sw.runtimeStr<Stopwatch::Milliseconds>(); LOG( INFO ) << "HPMeshGen2 finished"; }
36.421687
169
0.700298
DanielZint
57ce95504d7b142d41b21bd26ed2768dde5ff27c
712
hpp
C++
jobin/atomic.hpp
Marcos30004347/jobin
40eec7bf9579002426320253eae6eaaea6b50d10
[ "Apache-2.0" ]
2
2020-09-30T05:12:09.000Z
2020-10-12T23:40:32.000Z
jobin/atomic.hpp
Marcos30004347/Jobin
40eec7bf9579002426320253eae6eaaea6b50d10
[ "Apache-2.0" ]
null
null
null
jobin/atomic.hpp
Marcos30004347/Jobin
40eec7bf9579002426320253eae6eaaea6b50d10
[ "Apache-2.0" ]
null
null
null
#ifndef JOBIN_ATOMIC_H #define JOBIN_ATOMIC_H #include <atomic> template <typename T> class atomic { private: std::atomic<T> _atomic; public: atomic(T initial): _atomic(initial) {} atomic() {} ~atomic() {} bool compare_exchange_strong(T current_value, T new_value){ return _atomic.compare_exchange_strong(current_value, new_value); } bool compare_exchange_weak(T current_value, T new_value) { return _atomic.compare_exchange_weak(current_value, new_value); } T exchange(T value) { return _atomic.exchange(value); } T load() { return _atomic.load(); } void store(T value) { _atomic.store(value); } }; #endif
17.8
73
0.65309
Marcos30004347
57d3b4319e93ba09b78646b0772987f75a42c873
15,969
cc
C++
chrome/browser/download/download_request_manager.cc
bluebellzhy/chromium
008c4fef2676506869a0404239da31e83fd6ccc7
[ "BSD-3-Clause" ]
1
2016-05-08T15:35:17.000Z
2016-05-08T15:35:17.000Z
chrome/browser/download/download_request_manager.cc
bluebellzhy/chromium
008c4fef2676506869a0404239da31e83fd6ccc7
[ "BSD-3-Clause" ]
null
null
null
chrome/browser/download/download_request_manager.cc
bluebellzhy/chromium
008c4fef2676506869a0404239da31e83fd6ccc7
[ "BSD-3-Clause" ]
null
null
null
// Copyright (c) 2006-2008 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/download/download_request_manager.h" #include "base/message_loop.h" #include "base/thread.h" #include "chrome/browser/navigation_controller.h" #include "chrome/browser/navigation_entry.h" #include "chrome/browser/constrained_window.h" #include "chrome/browser/tab_contents.h" #include "chrome/browser/tab_contents_delegate.h" #include "chrome/browser/tab_util.h" #include "chrome/common/l10n_util.h" #include "chrome/common/notification_registrar.h" #include "chrome/common/notification_service.h" #include "chrome/views/dialog_delegate.h" #include "chrome/views/message_box_view.h" #include "generated_resources.h" namespace { // DialogDelegateImpl ---------------------------------------------------------- // DialogDelegateImpl is the DialogDelegate implementation used to prompt the // the user as to whether they want to allow multiple downloads. // DialogDelegateImpl delegates the allow/cancel methods to the // TabDownloadState. // // TabDownloadState does not directly implement DialogDelegate, rather it is // split into DialogDelegateImpl as TabDownloadState may be deleted before // the dialog. class DialogDelegateImpl : public views::DialogDelegate { public: DialogDelegateImpl(TabContents* tab, DownloadRequestManager::TabDownloadState* host); void set_host(DownloadRequestManager::TabDownloadState* host) { host_ = host; } // Closes the prompt. void CloseWindow(); private: // DialogDelegate methods; virtual bool Cancel(); virtual bool Accept(); virtual views::View* GetContentsView() { return message_view_; } virtual std::wstring GetDialogButtonLabel(DialogButton button) const; virtual int GetDefaultDialogButton() const { return DIALOGBUTTON_CANCEL; } virtual void WindowClosing(); // The TabDownloadState we're displaying the dialog for. May be null. DownloadRequestManager::TabDownloadState* host_; MessageBoxView* message_view_; ConstrainedWindow* window_; DISALLOW_COPY_AND_ASSIGN(DialogDelegateImpl); }; } // namespace // TabDownloadState ------------------------------------------------------------ // TabDownloadState maintains the download state for a particular tab. // TabDownloadState installs observers to update the download status // appropriately. Additionally TabDownloadState prompts the user as necessary. // TabDownloadState deletes itself (by invoking DownloadRequestManager::Remove) // as necessary. class DownloadRequestManager::TabDownloadState : public NotificationObserver { public: // Creates a new TabDownloadState. |controller| is the controller the // TabDownloadState tracks the state of and is the host for any dialogs that // are displayed. |originating_controller| is used to determine the host of // the initial download. If |originating_controller| is null, |controller| is // used. |originating_controller| is typically null, but differs from // |controller| in the case of a constrained popup requesting the download. TabDownloadState(DownloadRequestManager* host, NavigationController* controller, NavigationController* originating_controller); ~TabDownloadState(); // Status of the download. void set_download_status(DownloadRequestManager::DownloadStatus status) { status_ = status; } DownloadRequestManager::DownloadStatus download_status() const { return status_; } // Invoked when a user gesture occurs (mouse click, enter or space). This // may result in invoking Remove on DownloadRequestManager. void OnUserGesture(); // Asks the user if they really want to allow the download. // See description above CanDownloadOnIOThread for details on lifetime of // callback. void PromptUserForDownload(TabContents* tab, DownloadRequestManager::Callback* callback); // Are we showing a prompt to the user? bool is_showing_prompt() const { return (dialog_delegate_ != NULL); } // NavigationController we're tracking. NavigationController* controller() const { return controller_; } // Invoked from DialogDelegateImpl. Notifies the delegates and changes the // status appropriately. void Cancel(); void Accept(); private: // NotificationObserver method. void Observe(NotificationType type, const NotificationSource& source, const NotificationDetails& details); // Notifies the callbacks as to whether the download is allowed or not. // Updates status_ appropriately. void NotifyCallbacks(bool allow); DownloadRequestManager* host_; NavigationController* controller_; // Host of the first page the download started on. This may be empty. std::string initial_page_host_; DownloadRequestManager::DownloadStatus status_; // Callbacks we need to notify. This is only non-empty if we're showing a // dialog. // See description above CanDownloadOnIOThread for details on lifetime of // callbacks. std::vector<DownloadRequestManager::Callback*> callbacks_; // Used to remove observers installed on NavigationController. NotificationRegistrar registrar_; // Handles showing the dialog to the user, may be null. DialogDelegateImpl* dialog_delegate_; DISALLOW_COPY_AND_ASSIGN(TabDownloadState); }; DownloadRequestManager::TabDownloadState::TabDownloadState( DownloadRequestManager* host, NavigationController* controller, NavigationController* originating_controller) : host_(host), controller_(controller), status_(DownloadRequestManager::ALLOW_ONE_DOWNLOAD), dialog_delegate_(NULL) { Source<NavigationController> notification_source(controller); registrar_.Add(this, NOTIFY_NAV_ENTRY_COMMITTED, notification_source); registrar_.Add(this, NOTIFY_TAB_CLOSED, notification_source); NavigationEntry* active_entry = originating_controller ? originating_controller->GetActiveEntry() : controller->GetActiveEntry(); if (active_entry) initial_page_host_ = active_entry->url().host(); } DownloadRequestManager::TabDownloadState::~TabDownloadState() { // We should only be destroyed after the callbacks have been notified. DCHECK(callbacks_.empty()); // And we should have closed the message box. DCHECK(!dialog_delegate_); } void DownloadRequestManager::TabDownloadState::OnUserGesture() { if (is_showing_prompt()) { // Don't change the state if the user clicks on the page some where. return; } if (status_ != DownloadRequestManager::ALLOW_ALL_DOWNLOADS && status_ != DownloadRequestManager::DOWNLOADS_NOT_ALLOWED) { // Revert to default status. host_->Remove(this); // WARNING: We've been deleted. return; } } void DownloadRequestManager::TabDownloadState::PromptUserForDownload( TabContents* tab, DownloadRequestManager::Callback* callback) { callbacks_.push_back(callback); if (is_showing_prompt()) return; // Already showing prompt. if (DownloadRequestManager::delegate_) NotifyCallbacks(DownloadRequestManager::delegate_->ShouldAllowDownload()); else dialog_delegate_ = new DialogDelegateImpl(tab, this); } void DownloadRequestManager::TabDownloadState::Cancel() { NotifyCallbacks(false); } void DownloadRequestManager::TabDownloadState::Accept() { NotifyCallbacks(true); } void DownloadRequestManager::TabDownloadState::Observe( NotificationType type, const NotificationSource& source, const NotificationDetails& details) { if ((type != NOTIFY_NAV_ENTRY_COMMITTED && type != NOTIFY_TAB_CLOSED) || Source<NavigationController>(source).ptr() != controller_) { NOTREACHED(); return; } switch(type) { case NOTIFY_NAV_ENTRY_COMMITTED: { if (is_showing_prompt()) { // We're prompting the user and they navigated away. Close the popup and // cancel the downloads. dialog_delegate_->CloseWindow(); // After switch we'll notify callbacks and get deleted. } else if (status_ == DownloadRequestManager::ALLOW_ALL_DOWNLOADS || status_ == DownloadRequestManager::DOWNLOADS_NOT_ALLOWED) { // User has either allowed all downloads or canceled all downloads. Only // reset the download state if the user is navigating to a different // host (or host is empty). NavigationController::LoadCommittedDetails* load_details = Details<NavigationController::LoadCommittedDetails>(details).ptr(); NavigationEntry* entry = load_details->entry; if (load_details->is_auto || !entry || (!initial_page_host_.empty() && !entry->url().host().empty() && entry->url().host() == initial_page_host_)) { return; } } // else case: we're not prompting user and user hasn't allowed or // disallowed downloads, break so that we get deleted after switch. break; } case NOTIFY_TAB_CLOSED: // Tab closed, no need to handle closing the dialog as it's owned by the // TabContents, break so that we get deleted after switch. break; default: NOTREACHED(); } NotifyCallbacks(false); host_->Remove(this); } void DownloadRequestManager::TabDownloadState::NotifyCallbacks(bool allow) { if (dialog_delegate_) { // Reset the delegate so we don't get notified again. dialog_delegate_->set_host(NULL); dialog_delegate_ = NULL; } status_ = allow ? DownloadRequestManager::ALLOW_ALL_DOWNLOADS : DownloadRequestManager::DOWNLOADS_NOT_ALLOWED; std::vector<DownloadRequestManager::Callback*> callbacks; callbacks.swap(callbacks_); for (size_t i = 0; i < callbacks.size(); ++i) host_->ScheduleNotification(callbacks[i], allow); } namespace { // DialogDelegateImpl ---------------------------------------------------------- DialogDelegateImpl::DialogDelegateImpl( TabContents* tab, DownloadRequestManager::TabDownloadState* host) : host_(host) { message_view_ = new MessageBoxView( MessageBoxView::kIsConfirmMessageBox, l10n_util::GetString(IDS_MULTI_DOWNLOAD_WARNING), std::wstring()); window_ = tab->CreateConstrainedDialog(this, message_view_); } void DialogDelegateImpl::CloseWindow() { window_->CloseConstrainedWindow(); } bool DialogDelegateImpl::Cancel() { if (host_) host_->Cancel(); return true; } bool DialogDelegateImpl::Accept() { if (host_) host_->Accept(); return true; } std::wstring DialogDelegateImpl::GetDialogButtonLabel( DialogButton button) const { if (button == DIALOGBUTTON_OK) return l10n_util::GetString(IDS_MULTI_DOWNLOAD_WARNING_ALLOW); if (button == DIALOGBUTTON_CANCEL) return l10n_util::GetString(IDS_MULTI_DOWNLOAD_WARNING_DENY); return std::wstring(); } void DialogDelegateImpl::WindowClosing() { DCHECK(!host_); delete this; } } // namespace // DownloadRequestManager ------------------------------------------------------ DownloadRequestManager::DownloadRequestManager(MessageLoop* io_loop, MessageLoop* ui_loop) : io_loop_(io_loop), ui_loop_(ui_loop) { } DownloadRequestManager::~DownloadRequestManager() { // All the tabs should have closed before us, which sends notification and // removes from state_map_. As such, there should be no pending callbacks. DCHECK(state_map_.empty()); } DownloadRequestManager::DownloadStatus DownloadRequestManager::GetDownloadStatus(TabContents* tab) { TabDownloadState* state = GetDownloadState(tab->controller(), NULL, false); return state ? state->download_status() : ALLOW_ONE_DOWNLOAD; } void DownloadRequestManager::CanDownloadOnIOThread(int render_process_host_id, int render_view_id, Callback* callback) { // This is invoked on the IO thread. Schedule the task to run on the UI // thread so that we can query UI state. DCHECK(!io_loop_ || io_loop_ == MessageLoop::current()); ui_loop_->PostTask(FROM_HERE, NewRunnableMethod(this, &DownloadRequestManager::CanDownload, render_process_host_id, render_view_id, callback)); } void DownloadRequestManager::OnUserGesture(TabContents* tab) { NavigationController* controller = tab->controller(); if (!controller) { NOTREACHED(); return; } TabDownloadState* state = GetDownloadState(controller, NULL, false); if (!state) return; state->OnUserGesture(); } // static void DownloadRequestManager::SetTestingDelegate(TestingDelegate* delegate) { delegate_ = delegate; } DownloadRequestManager::TabDownloadState* DownloadRequestManager:: GetDownloadState(NavigationController* controller, NavigationController* originating_controller, bool create) { DCHECK(controller); StateMap::iterator i = state_map_.find(controller); if (i != state_map_.end()) return i->second; if (!create) return NULL; TabDownloadState* state = new TabDownloadState(this, controller, originating_controller); state_map_[controller] = state; return state; } void DownloadRequestManager::CanDownload(int render_process_host_id, int render_view_id, Callback* callback) { DCHECK(!ui_loop_ || MessageLoop::current() == ui_loop_); TabContents* originating_tab = tab_util::GetTabContentsByID(render_process_host_id, render_view_id); if (!originating_tab) { // The tab was closed, don't allow the download. ScheduleNotification(callback, false); return; } CanDownloadImpl(originating_tab, callback); } void DownloadRequestManager::CanDownloadImpl( TabContents* originating_tab, Callback* callback) { TabContents* effective_tab = originating_tab; if (effective_tab->delegate() && effective_tab->delegate()->GetConstrainingContents(effective_tab)) { // The tab requesting the download is a constrained popup that is not // shown, treat the request as if it came from the parent. effective_tab = effective_tab->delegate()->GetConstrainingContents(effective_tab); } NavigationController* controller = effective_tab->controller(); DCHECK(controller); TabDownloadState* state = GetDownloadState( controller, originating_tab->controller(), true); switch (state->download_status()) { case ALLOW_ALL_DOWNLOADS: ScheduleNotification(callback, true); break; case ALLOW_ONE_DOWNLOAD: state->set_download_status(PROMPT_BEFORE_DOWNLOAD); ScheduleNotification(callback, true); break; case DOWNLOADS_NOT_ALLOWED: ScheduleNotification(callback, false); break; case PROMPT_BEFORE_DOWNLOAD: state->PromptUserForDownload(effective_tab, callback); break; default: NOTREACHED(); } } void DownloadRequestManager::ScheduleNotification(Callback* callback, bool allow) { if (io_loop_) { io_loop_->PostTask(FROM_HERE, NewRunnableMethod(this, &DownloadRequestManager::NotifyCallback, callback, allow)); } else { NotifyCallback(callback, allow); } } void DownloadRequestManager::NotifyCallback(Callback* callback, bool allow) { // We better be on the IO thread now. DCHECK(!io_loop_ || MessageLoop::current() == io_loop_); if (allow) callback->ContinueDownload(); else callback->CancelDownload(); } void DownloadRequestManager::Remove(TabDownloadState* state) { DCHECK(state_map_.find(state->controller()) != state_map_.end()); state_map_.erase(state->controller()); delete state; } // static DownloadRequestManager::TestingDelegate* DownloadRequestManager::delegate_ = NULL;
33.26875
80
0.710439
bluebellzhy
57d3f68de943e8499169642d2af602d257560edb
2,589
cpp
C++
source/aoc/src/aoc2018/d08/solver.cpp
daduraro/aoc
9029de9d6e703fa1b20a466c1286b74ce9a7b23c
[ "BSD-2-Clause" ]
1
2019-12-06T11:29:14.000Z
2019-12-06T11:29:14.000Z
source/aoc/src/aoc2018/d08/solver.cpp
daduraro/aoc
9029de9d6e703fa1b20a466c1286b74ce9a7b23c
[ "BSD-2-Clause" ]
null
null
null
source/aoc/src/aoc2018/d08/solver.cpp
daduraro/aoc
9029de9d6e703fa1b20a466c1286b74ce9a7b23c
[ "BSD-2-Clause" ]
null
null
null
#include "aoc/solver.h" #include <memory> #include <iostream> #include <string> #include <vector> #include <array> #include <algorithm> #include <numeric> #include <iterator> #include <limits> #include <type_traits> #include <cassert> #include <ddr/data/tree.h> namespace { using namespace aoc; constexpr std::size_t YEAR = 2018; constexpr std::size_t DAY = 8; using node_t = ddr::data::node_t<std::vector<std::intmax_t>>; using input_t = node_t; input_t parse_input(std::istream& is) { input_t root; auto read_tree = [&is](node_t& node) -> void { auto impl = [&is](const auto& self, node_t& node) -> void { std::size_t num_children, num_data; if (!(is >> num_children >> num_data)) throw parse_exception{}; node.children.resize(num_children); for (node_t& child : node.children) self(self, child); std::copy_n(std::istream_iterator<std::intmax_t>(is), num_data, std::back_inserter(*node)); if (is.fail()) throw parse_exception{}; }; impl(impl, node); }; read_tree(root); return root; } std::size_t resultA(const input_t& in) noexcept { std::vector<const node_t*> nodes; nodes.push_back(&in); std::intmax_t accum = 0; while (!nodes.empty()) { const node_t& node = *nodes.back(); nodes.pop_back(); accum += std::reduce(node->begin(), node->end()); for (const node_t& child : node.children) nodes.push_back(&child); } return std::size_t(accum); } std::size_t resultB(const node_t& in) noexcept { if (in.children.empty()) { auto sum = std::reduce(in->begin(), in->end()); return std::size_t(sum); } else { std::vector<std::optional<std::size_t>> cached_values; cached_values.resize(in.children.size()); std::size_t accum = 0; for (auto child : *in) { if (child == 0 || std::size_t(child) > in.children.size()) continue; // invalid child auto& value = cached_values[child-1]; if (!value) value = resultB(in.children[child - 1]); accum += *value; } return accum; } } } namespace aoc { template<> auto create_solver<YEAR, DAY>() noexcept -> std::unique_ptr<solver_interface> { return create_solver<YEAR, DAY>(parse_input, resultA, resultB); } }
30.458824
107
0.555041
daduraro
57d47d9749c836f8aa60d9357a9d746672aa9e99
11,710
cpp
C++
src/kerberos/Kerberos.cpp
wollars/kerberos-machinery
95c648133a7229b94b78af74283b3a8a1574922b
[ "Unlicense" ]
1
2018-06-12T21:48:53.000Z
2018-06-12T21:48:53.000Z
src/kerberos/Kerberos.cpp
wollars/kerberos-machinery
95c648133a7229b94b78af74283b3a8a1574922b
[ "Unlicense" ]
null
null
null
src/kerberos/Kerberos.cpp
wollars/kerberos-machinery
95c648133a7229b94b78af74283b3a8a1574922b
[ "Unlicense" ]
null
null
null
#include "Kerberos.h" namespace kerberos { void Kerberos::bootstrap(StringMap & parameters) { // -------------------------------- // Set parameters from command-line setParameters(parameters); // --------------------- // Initialize kerberos std::string configuration = (helper::getValueByKey(parameters, "config")) ?: CONFIGURATION_PATH; configure(configuration); // ------------------ // Open the io thread startIOThread(); // ------------------------------------------ // Guard is a filewatcher, that looks if the // configuration has been changed. On change // guard will re-configure all instances. std::string directory = configuration.substr(0, configuration.rfind('/')); std::string file = configuration.substr(configuration.rfind('/')+1); guard = new FW::Guard(); guard->listenTo(directory, file); guard->onChange(&Kerberos::reconfigure); guard->start(); // -------------------------- // This should be forever... while(true) { // ------------------- // Initialize data JSON data; data.SetObject(); // ------------------------------------ // Guard look if the configuration has // been changed... guard->look(); // -------------------------------------------- // If machinery is NOT allowed to do detection // continue iteration if(!machinery->allowed(m_images)) { BINFO << "Machinery on hold, conditions failed."; continue; } // -------------------- // Clean image to save Image cleanImage = *m_images[m_images.size()-1]; // -------------- // Processing.. if(machinery->detect(m_images, data)) { // --------------------------- // If something is detected... pthread_mutex_lock(&m_ioLock); Detection detection(toJSON(data), cleanImage); m_detections.push_back(detection); pthread_mutex_unlock(&m_ioLock); } // ------------- // Shift images m_images = capture->shiftImage(); } } std::string Kerberos::toJSON(JSON & data) { JSON::AllocatorType& allocator = data.GetAllocator(); JSONValue timestamp; timestamp.SetString(kerberos::helper::getTimestamp().c_str(), allocator); data.AddMember("timestamp", timestamp, allocator); std::string micro = kerberos::helper::getMicroseconds(); micro = kerberos::helper::to_string((int)micro.length()) + "-" + micro; JSONValue microseconds; microseconds.SetString(micro.c_str(), allocator); data.AddMember("microseconds", microseconds, allocator); data.AddMember("token", rand()%1000, allocator); rapidjson::StringBuffer buffer; rapidjson::Writer<rapidjson::StringBuffer> writer(buffer); data.Accept(writer); return buffer.GetString(); } void Kerberos::configure(const std::string & configuration) { // --------------------------- // Get settings from XML file LINFO << "Reading configuration file: " << configuration; StringMap settings = kerberos::helper::getSettingsFromXML(configuration); // ------------------------------- // Override config with parameters StringMap parameters = getParameters(); StringMap::iterator begin = parameters.begin(); StringMap::iterator end = parameters.end(); for(begin; begin != end; begin++) { settings[begin->first] = begin->second; } LINFO << helper::printStringMap("Final configuration:", settings); // ------------------------------------------- // Check if we need to disable verbose logging easyloggingpp::Logger * logger = easyloggingpp::Loggers::getLogger("business"); easyloggingpp::Configurations & config = logger->configurations(); if(settings.at("logging") == "false") { LINFO << "Logging is set to info"; config.set(easyloggingpp::Level::Info, easyloggingpp::ConfigurationType::Enabled, "false"); } else { LINFO << "Logging is set to verbose"; config.set(easyloggingpp::Level::Info, easyloggingpp::ConfigurationType::Enabled, "true"); } logger->reconfigure(); // ----------------- // Configure cloud configureCloud(settings); // ------------------ // Configure capture configureCapture(settings); // -------------------- // Initialize machinery if(machinery != 0) delete machinery; machinery = new Machinery(); machinery->setCapture(capture); machinery->setup(settings); // ------------------- // Take first images for(ImageVector::iterator it = m_images.begin(); it != m_images.end(); it++) { delete *it; } m_images.clear(); m_images = capture->takeImages(3); machinery->initialize(m_images); } // ---------------------------------- // Configure capture device + stream void Kerberos::configureCapture(StringMap & settings) { // ----------------------- // Stop stream and capture if(stream != 0) { LINFO << "Stopping streaming"; stopStreamThread(); delete stream; stream = 0; } if(capture != 0) { LINFO << "Stopping capture device"; if(capture->isOpened()) { machinery->disableCapture(); capture->stopGrabThread(); capture->close(); } delete capture; capture = 0; } // --------------------------- // Initialize capture device LINFO << "Starting capture device: " + settings.at("capture"); capture = Factory<Capture>::getInstance()->create(settings.at("capture")); capture->setup(settings); capture->startGrabThread(); // ------------------ // Initialize stream stream = new Stream(); stream->configureStream(settings); startStreamThread(); } // ---------------------------------- // Configure cloud device + thread void Kerberos::configureCloud(StringMap & settings) { // --------------------------- // Initialize cloud service if(cloud != 0) { LINFO << "Stopping cloud service"; cloud->stopUploadThread(); cloud->stopPollThread(); delete cloud; } LINFO << "Starting cloud service: " + settings.at("cloud"); cloud = Factory<Cloud>::getInstance()->create(settings.at("cloud")); cloud->setup(settings); } // -------------------------------------------- // Function ran in a thread, which continuously // stream MJPEG's. void * streamContinuously(void * self) { Kerberos * kerberos = (Kerberos *) self; while(kerberos->stream->isOpened()) { try { kerberos->stream->connect(); if(kerberos->capture->isOpened()) { Image image = kerberos->capture->retrieve(); if(kerberos->capture->m_angle != 0) { image.rotate(kerberos->capture->m_angle); } kerberos->stream->write(image); } usleep(kerberos->stream->wait * 1000 * 1000); // sleep x microsec. } catch(cv::Exception & ex){} } } void Kerberos::startStreamThread() { // ------------------------------------------------ // Start a new thread that streams MJPEG's continuously. if(stream != 0) { //if stream object just exists try to open configured stream port stream->open(); } pthread_create(&m_streamThread, NULL, streamContinuously, this); } void Kerberos::stopStreamThread() { // ---------------------------------- // Cancel the existing stream thread, pthread_cancel(m_streamThread); pthread_join(m_streamThread, NULL); } // ------------------------------------------- // Function ran in a thread, which continuously // checks if some detections occurred and // execute the IO devices if so. void * checkDetectionsContinuously(void * self) { Kerberos * kerberos = (Kerberos *) self; int previousCount = 0; int currentCount = 0; int timesEqual = 0; while(true) { try { previousCount = currentCount; currentCount = kerberos->m_detections.size(); if(previousCount == currentCount) { timesEqual++; } else if(timesEqual > 0) { timesEqual--; } // If no new detections are found, we will run the IO devices (or max 30 images in memory) if((currentCount > 0 && timesEqual > 4) || currentCount >= 30) { BINFO << "Executing IO devices for " + helper::to_string(currentCount) + " detection(s)"; for (int i = 0; i < currentCount; i++) { Detection detection = kerberos->m_detections[0]; JSON data; data.Parse(detection.t.c_str()); pthread_mutex_lock(&kerberos->m_ioLock); if(kerberos->machinery->save(detection.k, data)) { kerberos->m_detections.erase(kerberos->m_detections.begin()); } else { LERROR << "IO: can't execute"; } pthread_mutex_unlock(&kerberos->m_ioLock); usleep(500*1000); } timesEqual = 0; } usleep(500*1000); } catch(cv::Exception & ex) { pthread_mutex_unlock(&kerberos->m_ioLock); } } } void Kerberos::startIOThread() { // ------------------------------------------------ // Start a new thread that cheks for detections pthread_create(&m_ioThread, NULL, checkDetectionsContinuously, this); } void Kerberos::stopIOThread() { // ---------------------------------- // Cancel the existing io thread, pthread_cancel(m_ioThread); pthread_join(m_ioThread, NULL); } }
30.336788
110
0.453288
wollars
57d851ae0017539de24973dbefb1403309175015
3,234
hh
C++
surfaces/CenteredSphere.hh
celeritas-project/orange-port
9aa2d36984a24a02ed6d14688a889d4266f7b1af
[ "Apache-2.0", "MIT" ]
null
null
null
surfaces/CenteredSphere.hh
celeritas-project/orange-port
9aa2d36984a24a02ed6d14688a889d4266f7b1af
[ "Apache-2.0", "MIT" ]
null
null
null
surfaces/CenteredSphere.hh
celeritas-project/orange-port
9aa2d36984a24a02ed6d14688a889d4266f7b1af
[ "Apache-2.0", "MIT" ]
null
null
null
//---------------------------------*-C++-*-----------------------------------// /*! * \file surfaces/CenteredSphere.hh * \brief CenteredCenteredSphere class declaration * \note Copyright (c) 2020 Oak Ridge National Laboratory, UT-Battelle, LLC. */ //---------------------------------------------------------------------------// #pragma once #include "Definitions.hh" namespace celeritas { class Sphere; //---------------------------------------------------------------------------// /*! * CenteredSphere at an arbitrary spatial point. */ class CenteredSphere { public: //// ATTRIBUTES //// //! Get the surface type of this surface. static constexpr SurfaceType surface_type() { return SurfaceType::so; } //! Number of values associated with data(), and pointer construction static constexpr size_type size() { return 1; } //! Number of possible intersections static constexpr size_type num_intersections() { return 2; } // Whether the given sphere is at the origin static bool can_simplify(const Sphere& sq); public: //// CONSTRUCTION //// // Construct with radius explicit CenteredSphere(real_type radius); // Inline construction from flattened coefficients (copying data) explicit inline CenteredSphere(const real_type* coeff); // Construct from a degenerate SQ explicit CenteredSphere(const Sphere& sq); //! Access the data for this object, for inlining into a surface const real_type* data() const { return &radius_sq_; } //! Access the type-deleted surface data GenericSurfaceRef view() const { return GenericSurfaceRef::from_surface(*this); } //// TRANSFORMATION //// // Return a new sphere translated by some vector Sphere translated(const Transform& t) const; //! Return a sphere transformed by a rotate/translate Sphere transformed(const Transform& t) const; // Clip a bounding box to a shape with this sense void clip(Sense sense, BoundingBox& bbox) const; //// CALCULATION //// // Determine the sense of the position relative to this surface (init) inline SignedSense calc_sense(const Real3& x) const; // Determine distance to intersection inline void calc_intersections(const Real3& pos, const Real3& dir, bool on_surface, real_type* dist_iter) const; // Calculate outward normal at a position inline Real3 calc_normal(const Real3& pos) const; //// ACCESSORS //// //! Get the square of the radius real_type radius_sq() const { return radius_sq_; } private: //// DATA //// // Square of the radius real_type radius_sq_; }; // Print to a stream std::ostream& operator<<(std::ostream&, const CenteredSphere&); //---------------------------------------------------------------------------// } // namespace celeritas //---------------------------------------------------------------------------// // INLINE DEFINITIONS //---------------------------------------------------------------------------// #include "CenteredSphere.i.hh" //---------------------------------------------------------------------------//
31.096154
85
0.552876
celeritas-project
57dcecfb55e531f906d765c095cf588fe4d9794e
9,684
cpp
C++
Libraries/Utility/JSON.cpp
xycsoscyx/gekengine
cb9c933c6646169c0af9c7e49be444ff6f97835d
[ "MIT" ]
1
2019-04-22T00:10:49.000Z
2019-04-22T00:10:49.000Z
Libraries/Utility/JSON.cpp
xycsoscyx/gekengine
cb9c933c6646169c0af9c7e49be444ff6f97835d
[ "MIT" ]
null
null
null
Libraries/Utility/JSON.cpp
xycsoscyx/gekengine
cb9c933c6646169c0af9c7e49be444ff6f97835d
[ "MIT" ]
2
2017-10-16T15:40:55.000Z
2019-04-22T00:10:50.000Z
#include <jsoncons/json.hpp> #include "GEK/Utility/JSON.hpp" #include "GEK/Utility/FileSystem.hpp" #include "GEK/Utility/Context.hpp" namespace Gek { const JSON::Array JSON::EmptyArray = JSON::Array(); const JSON::Object JSON::EmptyObject = JSON::Object(); const JSON JSON::Empty = JSON(); JSON GetFromJSON(jsoncons::json const &object) { if (object.empty() || object.is_null()) { return JSON::Empty; } JSON value; switch (object.kind()) { case jsoncons::value_kind::short_string_value: case jsoncons::value_kind::long_string_value: case jsoncons::value_kind::byte_string_value: value = object.as_string(); break; case jsoncons::value_kind::bool_value: value = object.as<bool>(); break; case jsoncons::value_kind::double_value: value = object.as<float>(); break; case jsoncons::value_kind::int64_value: value = object.as<int64_t>(); break; case jsoncons::value_kind::uint64_value: value = object.as<uint64_t>(); break; case jsoncons::value_kind::array_value: value = JSON::Array(object.size()); for (size_t index = 0; index < object.size(); ++index) { value[index] = GetFromJSON(object[index]); } break; case jsoncons::value_kind::object_value: value = JSON::Object(); for (auto &pair : object.object_range()) { value[pair.key()] = GetFromJSON(pair.value()); } break; }; return value; } void JSON::load(FileSystem::Path const &filePath) { if (filePath.isFile()) { std::string object(FileSystem::Load(filePath, String::Empty)); std::istringstream dataStream(object); jsoncons::json_decoder<jsoncons::json> decoder; jsoncons::json_reader reader(dataStream, decoder); std::error_code errorCode; reader.read(errorCode); if (errorCode) { LockedWrite{ std::cerr } << errorCode.message() << " at line " << reader.line() << ", and column " << reader.column() << ", in " << filePath.getString(); } else { *this = GetFromJSON(decoder.get_result()); } } } void JSON::save(FileSystem::Path const &filePath) { FileSystem::Save(filePath, getString()); } std::string escapeJsonString(const std::string& input) { std::ostringstream ss; for (auto iter = input.cbegin(); iter != input.cend(); iter++) { //C++98/03: //for (std::string::const_iterator iter = input.begin(); iter != input.end(); iter++) { switch (*iter) { case '\\': ss << "\\\\"; break; case '"': ss << "\\\""; break; case '/': ss << "\\/"; break; case '\b': ss << "\\b"; break; case '\f': ss << "\\f"; break; case '\n': ss << "\\n"; break; case '\r': ss << "\\r"; break; case '\t': ss << "\\t"; break; default: ss << *iter; break; }; } return ss.str(); } std::string JSON::getString(void) const { return visit( [](std::string const &visitedData) { return String::Format("\"{}\"", escapeJsonString(visitedData)); }, [](JSON::Array const &visitedData) { std::stringstream stream; stream << "[ "; bool writtenPrevious = false; for (auto &index : visitedData) { if (writtenPrevious) { stream << ", "; } stream << index.getString(); writtenPrevious = true; } stream << (std::empty(visitedData) ? "]" : " ]"); return stream.str(); }, [](JSON::Object const &visitedData) { std::stringstream stream; stream << "{ "; bool writtenPrevious = false; for (auto &index : visitedData) { if (writtenPrevious) { stream << ", "; } stream << "\"" << index.first << "\": "; stream << index.second.getString(); writtenPrevious = true; } stream << (std::empty(visitedData) ? "}" : " }"); return stream.str(); }, [](auto && visitedData) { return String::Format("{}", visitedData); }); } JSON const &JSON::getIndex(size_t index) const { if (auto value = std::get_if<Array>(&data)) { return value->at(index); } else { return Empty; } } JSON const &JSON::getMember(std::string_view name) const { if (auto value = std::get_if<Object>(&data)) { auto search = value->find(name.data()); if (search == std::end(*value)) { return Empty; } else { return search->second; } } else { return Empty; } } JSON &JSON::operator [] (size_t index) { if (!isType<Array>()) { data = EmptyArray; } return std::get<Array>(data)[index]; } JSON &JSON::operator [] (std::string_view name) { if (!isType<Object>()) { data = EmptyObject; } return std::get<Object>(data)[name.data()]; } Math::Float2 JSON::evaluate(ShuntingYard &shuntingYard, Math::Float2 const &defaultValue) const { auto data = asType(EmptyArray); switch (data.size()) { case 1: return Math::Float2(data[0].evaluate(shuntingYard, 0.0f)); default: return Math::Float2( data[0].evaluate(shuntingYard, defaultValue.x), data[1].evaluate(shuntingYard, defaultValue.y)); }; } Math::Float3 JSON::evaluate(ShuntingYard &shuntingYard, Math::Float3 const &defaultValue) const { auto data = asType(EmptyArray); switch (data.size()) { case 1: return Math::Float3(data[0].evaluate(shuntingYard, 0.0f)); case 3: return Math::Float3( data[0].evaluate(shuntingYard, defaultValue.x), data[1].evaluate(shuntingYard, defaultValue.y), data[2].evaluate(shuntingYard, defaultValue.z)); default: return defaultValue; }; } Math::Float4 JSON::evaluate(ShuntingYard &shuntingYard, Math::Float4 const &defaultValue) const { auto data = asType(EmptyArray); switch (data.size()) { case 1: return Math::Float4(data[0].evaluate(shuntingYard, 0.0f)); case 3: return Math::Float4( data[0].evaluate(shuntingYard, defaultValue.x), data[1].evaluate(shuntingYard, defaultValue.y), data[2].evaluate(shuntingYard, defaultValue.z), defaultValue.w); case 4: return Math::Float4( data[0].evaluate(shuntingYard, defaultValue.x), data[1].evaluate(shuntingYard, defaultValue.y), data[2].evaluate(shuntingYard, defaultValue.z), data[3].evaluate(shuntingYard, defaultValue.w)); default: return defaultValue; }; } Math::Quaternion JSON::evaluate(ShuntingYard &shuntingYard, Math::Quaternion const &defaultValue) const { auto data = asType(EmptyArray); switch (data.size()) { case 3: if (true) { float pitch = data[0].evaluate(shuntingYard, Math::Infinity); float yaw = data[1].evaluate(shuntingYard, Math::Infinity); float roll = data[2].evaluate(shuntingYard, Math::Infinity); if (pitch != Math::Infinity && yaw != Math::Infinity && roll != Math::Infinity) { return Math::Quaternion::MakeEulerRotation(pitch, yaw, roll); } return defaultValue; } case 4: return Math::Quaternion( data[0].evaluate(shuntingYard, defaultValue.x), data[1].evaluate(shuntingYard, defaultValue.y), data[2].evaluate(shuntingYard, defaultValue.z), data[3].evaluate(shuntingYard, defaultValue.w)); default: return defaultValue; }; } std::string JSON::evaluate(ShuntingYard &shuntingYard, std::string const &defaultValue) const { return visit( [](std::string const &visitedData) { return visitedData; }, [defaultValue](Object const &visitedData) { return defaultValue; }, [defaultValue](Array const &visitedData) { return defaultValue; }, [defaultValue](auto const &visitedData) { return String::Format("{}", GetValueOrDefault(visitedData, defaultValue)); }); } }; // namespace Gek
28.821429
169
0.491119
xycsoscyx
57dd7f66c393b3c9ac123b4cee2754bd124fdcb4
1,895
cpp
C++
runtime/libs/tflite/src/RandomInputInitializer.cpp
chogba6/ONE
3d35259f89ee3109cfd35ab6f38c231904487f3b
[ "Apache-2.0" ]
255
2020-05-22T07:45:29.000Z
2022-03-29T23:58:22.000Z
runtime/libs/tflite/src/RandomInputInitializer.cpp
chogba6/ONE
3d35259f89ee3109cfd35ab6f38c231904487f3b
[ "Apache-2.0" ]
5,102
2020-05-22T07:48:33.000Z
2022-03-31T23:43:39.000Z
runtime/libs/tflite/src/RandomInputInitializer.cpp
chogba6/ONE
3d35259f89ee3109cfd35ab6f38c231904487f3b
[ "Apache-2.0" ]
120
2020-05-22T07:51:08.000Z
2022-02-16T19:08:05.000Z
/* * Copyright (c) 2021 Samsung Electronics Co., Ltd. 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 "tflite/RandomInputInitializer.h" #include "tflite/TensorView.h" #include <misc/tensor/IndexIterator.h> namespace nnfw { namespace tflite { void RandomInputInitializer::run(::tflite::Interpreter &interp) { for (const auto &tensor_idx : interp.inputs()) { TfLiteTensor *tensor = interp.tensor(tensor_idx); switch (tensor->type) { case kTfLiteFloat32: setValue<float>(interp, tensor_idx); break; case kTfLiteInt32: setValue<int32_t>(interp, tensor_idx); break; case kTfLiteUInt8: setValue<uint8_t>(interp, tensor_idx); break; case kTfLiteBool: setValue<bool>(interp, tensor_idx); break; case kTfLiteInt8: setValue<int8_t>(interp, tensor_idx); break; default: throw std::runtime_error{"Not supported input type"}; } } } template <typename T> void RandomInputInitializer::setValue(::tflite::Interpreter &interp, int tensor_idx) { auto tensor_view = nnfw::tflite::TensorView<T>::make(interp, tensor_idx); nnfw::misc::tensor::iterate(tensor_view.shape()) << [&](const nnfw::misc::tensor::Index &ind) { tensor_view.at(ind) = _randgen.generate<T>(); }; } } // namespace tflite } // namespace nnfw
28.712121
99
0.687071
chogba6
57e07c8bb6d9a6242cd4d2c8d2a11f9aed8cbe87
2,730
cpp
C++
week5/code/btree_tree_print.cpp
hj02/Vor2015
675641f12773229e242c6e0bde290bdd537bf830
[ "MIT" ]
null
null
null
week5/code/btree_tree_print.cpp
hj02/Vor2015
675641f12773229e242c6e0bde290bdd537bf830
[ "MIT" ]
null
null
null
week5/code/btree_tree_print.cpp
hj02/Vor2015
675641f12773229e242c6e0bde290bdd537bf830
[ "MIT" ]
null
null
null
#include <iostream> #include <cstdio> using namespace std; struct TreeNode { int data; TreeNode* left; TreeNode* right; bool is_leaf(); }; bool TreeNode::is_leaf() { return (left == NULL && right == NULL); } typedef TreeNode* NodePtr; NodePtr parse_tree() { char c; cin >> c; // Read ( cin >> c; // Read next character // If the next character is ), this is the empty tree if(c == ')') { return NULL; } // Return the "borrowed" character to the input stream cin.putback(c); int node_data; cin >> node_data; NodePtr node = new TreeNode; node->data = node_data; node->left = parse_tree(); node->right = parse_tree(); cin >> c; // Consume the trailing ) return node; } void print_infix(NodePtr tree) { if(tree == NULL) { return; } print_infix(tree->left); cout << tree->data << " "; print_infix(tree->right); } void print_postfix(NodePtr tree) { if(tree == NULL) { return; } print_infix(tree->left); print_infix(tree->right); cout << tree->data << " "; } void print_prefix(NodePtr tree) { if(tree == NULL) { return; } cout << tree->data << " "; print_infix(tree->left); print_infix(tree->right); } const int INDENT_SIZE = 3; void indent(int level) { for(int i = 0; i != level * INDENT_SIZE; i++) { cout << " "; } } void print_tree(NodePtr tree, int level = 0) { indent(level); if(tree == NULL) { cout << "()" << endl; return; } cout << "(" << tree->data << endl; print_tree(tree->left, level + 1); print_tree(tree->right, level + 1); indent(level); cout << ")" << endl; } // Prints the end symbol of a lisp-style representation of a tree. If the tree // is not a rightmost child, the end symbol is a newline character. Otherwise, // there is no end symbol (i.e., it is the empty string). void tree_end(bool right) { if(!right) { cout << endl; } } // Print tree lisp-style void print_tree_lisp(NodePtr tree, int level = 0, bool right = false) { indent(level); if(tree == NULL) { cout << "()"; tree_end(right); return; } // Print leaves as numbers inside brackets, but not // with two empty children. cout << "(" << tree->data; if(tree->is_leaf()) { cout << ")"; tree_end(right); } else { cout << endl; print_tree_lisp(tree->left, level + 1, false); print_tree_lisp(tree->right, level + 1, true); cout << ")"; tree_end(right); } } int main() { NodePtr tree = parse_tree(); print_tree_lisp(tree); cout << endl; return 0; }
18.571429
78
0.558974
hj02
57e25bcc359aa95ba9adf31c0df0fca12ef8f594
8,760
cc
C++
src/vw/GPU/TexAlloc.cc
tkeemon/visionworkbench
df59fcb31191e1fc4fecfe1901963da1614a52b1
[ "NASA-1.3" ]
1
2020-06-02T04:06:43.000Z
2020-06-02T04:06:43.000Z
src/vw/GPU/TexAlloc.cc
tkeemon/visionworkbench
df59fcb31191e1fc4fecfe1901963da1614a52b1
[ "NASA-1.3" ]
null
null
null
src/vw/GPU/TexAlloc.cc
tkeemon/visionworkbench
df59fcb31191e1fc4fecfe1901963da1614a52b1
[ "NASA-1.3" ]
null
null
null
// __BEGIN_LICENSE__ // Copyright (C) 2006-2010 United States Government as represented by // the Administrator of the National Aeronautics and Space Administration. // All Rights Reserved. // __END_LICENSE__ #include <vw/GPU/TexAlloc.h> namespace vw { namespace GPU { //############################################################ // TexAlloc: Class Variables //############################################################ bool TexAlloc::isInit = false; list<TexObj*> TexAlloc::texRecycleList; int TexAlloc::allocatedCount = 0; int TexAlloc::allocatedSize = 0; bool TexAlloc::recylingEnabled = false; std::map<pair<Tex_Format, Tex_Type>, pair<Tex_Format, Tex_Type> > TexAlloc::textureSubstitutesMap; //############################################################# // TexAlloc: Class Functions //############################################################# static char buffer[512]; TexObj* TexAlloc::alloc(int w, int h, Tex_Format format, Tex_Type type) { // check for init if(!isInit) initialize_texalloc(); // Attribute Substition Tex_Format realFormat = format; Tex_Type realType = type; get_texture_substitution(format, type, realFormat, realType); // Try to find it in recycling if enabled... TexObj* texObj = NULL; if(recylingEnabled) { TexObj* bestTex = NULL; TexObj* cTex; std::list<TexObj*>::iterator iter; for(iter = texRecycleList.begin(); iter != texRecycleList.end(); iter++) { cTex = *iter; if(cTex->format() == realFormat && cTex->type() == realType && cTex->width() == w && cTex->height() == h) bestTex = cTex; } if(bestTex) { texRecycleList.remove(bestTex); texObj = bestTex; if(gpu_log_enabled()) { sprintf(buffer, "+++ Creating Texture: { %s, %s, (%i x %i) } - RECYCLED from (%i x %i) (Total Allocated: %.2fMB)\n", TexFormatToString(format), TexTypeToString(type), w, h, bestTex->width(), bestTex->height(), allocatedSize/1000000.0); gpu_log(buffer); } } } // if necessary, create new TexObj if(!texObj) { texObj = new TexObj(w, h, realFormat, realType); allocatedCount++; allocatedSize += texObj->MemorySize(); if(gpu_log_enabled()) { if(format != realFormat || type != realType) sprintf(buffer, "+++ Creating Texture: { %s, %s, (%i x %i) } - NEW, Substituting {%s, %s } (Total Allocated: %.2fMB)\n", TexFormatToString(format), TexTypeToString(type), w, h, TexFormatToString(realFormat), TexTypeToString(realType), allocatedSize/1000000.0); else sprintf(buffer, "+++ Creating Texture: { %s, %s, (%i x %i) } - NEW (Total of %.3fMB)\n", TexFormatToString(format), TexTypeToString(type), w, h, allocatedSize/1000000.0); gpu_log(buffer); } } // return return texObj; } void TexAlloc::release(TexObj* texObj) { if(recylingEnabled) { texRecycleList.push_back(texObj); if(gpu_log_enabled()) { sprintf(buffer, "--- Recycling Texture: { %s, %s, (%i x %i) } (Total Allocated %.2fMB)\n", TexFormatToString(texObj->format()), TexTypeToString(texObj->type()), texObj->width(), texObj->height(), allocatedSize/1000000.0); gpu_log(buffer); } } else { allocatedCount--; allocatedSize -= texObj->MemorySize(); if(gpu_log_enabled()) { sprintf(buffer, "--- Deleting Texture: { %s, %s, (%i x %i) } (Total Allocated %.2fMB)\n", TexFormatToString(texObj->format()), TexTypeToString(texObj->type()), texObj->width(), texObj->height(), allocatedSize/1000000.0); gpu_log(buffer); } delete texObj; } } void TexAlloc::clear_recycled() { std::list<TexObj*>::iterator iter; for(iter = texRecycleList.begin(); iter != texRecycleList.end(); iter++) { TexObj* texObj = *iter; allocatedCount--; allocatedSize -= texObj->MemorySize(); if(gpu_log_enabled()) { sprintf(buffer, "--- Deleting Texture: { %s, %s, (%i x %i) } (Total Allocated %.2fMB)\n", TexFormatToString(texObj->format()), TexTypeToString(texObj->type()), texObj->width(), texObj->height(), allocatedSize/1000000.0); gpu_log(buffer); } delete *iter; } texRecycleList.clear(); } void TexAlloc::generate_texture_substitutions(bool verbose) { textureSubstitutesMap.clear(); char buffer1[256]; char buffer2[256]; bool chart[3][3]; static Tex_Format textureFormats[] = { GPU_RED, GPU_RGB, GPU_RGBA }; static Tex_Type textureTypes[] = { GPU_UINT8, GPU_FLOAT16, GPU_FLOAT32 }; for(int i_format=0; i_format < 3; i_format++) { Tex_Format format = textureFormats[i_format]; if(format == GPU_RED) sprintf(buffer1, "GPU_RED"); else if(format == GPU_RGB) sprintf(buffer1, "GPU_RGB"); else if(format == GPU_RGBA) sprintf(buffer1, "GPU_RGBA"); for(int i_type=0; i_type < 3; i_type++) { bool failed = false; Tex_Type type = textureTypes[i_type]; if(type == GPU_UINT8) sprintf(buffer2, "GPU_UINT8"); else if(type == GPU_FLOAT16) sprintf(buffer2, "GPU_FLOAT16"); else if(type == GPU_FLOAT32) sprintf(buffer2, "GPU_FLOAT32"); if(verbose) printf("Checking Texture Support for: format = %s, type = %s\n", buffer1, buffer2); auto_ptr<TexObj> texRef(new TexObj(100, 100, format, type)); if(!texRef->width()) { failed = true; if(verbose) printf(" *** Failed on create.\n"); } if(!failed) { glCheckFramebufferStatusEXT(GL_FRAMEBUFFER_EXT); glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, g_framebuffer); glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, texRef->target(), texRef->name(), 0); glDrawBuffer(GL_COLOR_ATTACHMENT0_EXT); glReadBuffer(GL_COLOR_ATTACHMENT0_EXT); if(!CheckFramebuffer(false)) { failed = true; if(verbose) printf(" *** Failed on bind to framebuffer.\n"); } } chart[i_format][i_type] = !failed; } } for(int i_format=0; i_format < 3; i_format++) { for(int i_type=0; i_type < 3; i_type++) { bool found = false; Tex_Format inFormat = textureFormats[i_format]; Tex_Type inType = textureTypes[i_type]; Tex_Format outFormat; Tex_Type outType; for(int j_format=i_format; j_format < 3 && !found; j_format++) { for(int j_type=i_type; j_type < 3; j_type++) { if(chart[j_format][j_type]) { found = true; outFormat = textureFormats[j_format]; outType = textureTypes[j_type]; textureSubstitutesMap[pair<Tex_Format, Tex_Type>(inFormat, inType)] = pair<Tex_Format, Tex_Type>(outFormat, outType); if(verbose) { printf("[%s, %s] implemented as: ", TexFormatToString(inFormat), TexTypeToString(inType)); printf("[%s, %s]\n", TexFormatToString(outFormat), TexTypeToString(outType)); } break; } } } if(verbose && !found) { Tex_Format format = inFormat; if(format == GPU_RED) sprintf(buffer1, "GPU_RED"); else if(format == GPU_RGB) sprintf(buffer1, "GPU_RGB"); else if(format == GPU_RGBA) sprintf(buffer1, "GPU_RGBA"); Tex_Type type = inType; if(type == GPU_UINT8) sprintf(buffer2, "GPU_UINT8"); else if(type == GPU_FLOAT16) sprintf(buffer2, "GPU_FLOAT16"); else if(type == GPU_FLOAT32) sprintf(buffer2, "GPU_FLOAT32"); printf("[%s, %s] NOT IMPLEMENTED!\n", buffer1, buffer2); } } } } bool TexAlloc::get_texture_substitution(Tex_Format inFormat, Tex_Type inType, Tex_Format& outFormat, Tex_Type& outType) { map<pair<Tex_Format, Tex_Type>, pair<Tex_Format, Tex_Type> >::iterator iter; iter = textureSubstitutesMap.find(pair<Tex_Format, Tex_Type>(inFormat, inType)); if(iter != textureSubstitutesMap.end()) { outFormat = (*iter).second.first; outType = (*iter).second.second; return true; } else return false; } //############################################################### // TexAlloc: Class Functions - Private //############################################################### void TexAlloc::initialize_texalloc() { generate_texture_substitutions(); isInit = true; } } } // namespaces GPU, vw
39.459459
157
0.575571
tkeemon
57e2fcceba37ff5cc50f347e505114f0dc1297b5
1,162
hpp
C++
include/mettle/driver/subprocess_test_runner.hpp
JohnGalbraith/mettle
38b70fe1dc0f30e98b768a37108196328182b5f4
[ "BSD-3-Clause" ]
1
2019-06-07T08:03:33.000Z
2019-06-07T08:03:33.000Z
include/mettle/driver/subprocess_test_runner.hpp
JohnGalbraith/mettle
38b70fe1dc0f30e98b768a37108196328182b5f4
[ "BSD-3-Clause" ]
null
null
null
include/mettle/driver/subprocess_test_runner.hpp
JohnGalbraith/mettle
38b70fe1dc0f30e98b768a37108196328182b5f4
[ "BSD-3-Clause" ]
2
2018-07-02T19:28:43.000Z
2019-06-07T08:03:35.000Z
#ifndef INC_METTLE_DRIVER_SUBPROCESS_TEST_RUNNER_HPP #define INC_METTLE_DRIVER_SUBPROCESS_TEST_RUNNER_HPP #include <chrono> #include <optional> #ifdef _WIN32 # include <wtypes.h> #endif #include <mettle/suite/compiled_suite.hpp> #include <mettle/driver/log/core.hpp> #include <mettle/driver/detail/export.hpp> namespace mettle { class METTLE_PUBLIC subprocess_test_runner { public: using timeout_t = std::optional<std::chrono::milliseconds>; subprocess_test_runner(timeout_t timeout = {}) : timeout_(timeout) {} template<class Rep, class Period> subprocess_test_runner(std::chrono::duration<Rep, Period> timeout) : timeout_(timeout) {} test_result operator ()(const test_info &test, log::test_output &output) const; private: timeout_t timeout_; }; #ifndef _WIN32 using fd_type = int; int make_fd_private(int fd); #else using fd_type = HANDLE; METTLE_PUBLIC int make_fd_private(HANDLE handle); METTLE_PUBLIC const test_info * find_test(const suites_list &suites, test_uid id); METTLE_PUBLIC bool run_single_test(const test_info &test, HANDLE log_pipe); #endif } // namespace mettle #endif
21.924528
77
0.74957
JohnGalbraith
57e36318440c12465fa8f81ec416b3634c165154
659
cc
C++
Q_06.cc
koichi-murakami/c-pre
75bd902172d89af50e86a50d8a8dbfcbfb913635
[ "BSD-2-Clause" ]
1
2019-04-02T21:57:48.000Z
2019-04-02T21:57:48.000Z
Q_06.cc
koichi-murakami/cpp_pre
75bd902172d89af50e86a50d8a8dbfcbfb913635
[ "BSD-2-Clause" ]
null
null
null
Q_06.cc
koichi-murakami/cpp_pre
75bd902172d89af50e86a50d8a8dbfcbfb913635
[ "BSD-2-Clause" ]
null
null
null
#include <iostream> using namespace std; class Ellipse { public: Ellipse( ) = default; Ellipse( double x, double y ){ a = x; b = y; } ~Ellipse( ) = default; double area(){ return pi*a*b; } string shapeName(){ return "Ellipse"; } private: double a, b; const double pi = 3.14159265; }; int main() { auto el = Ellipse( 3.0, 4.0 ); string name1 = el.shapeName(); double space1= el.area(); auto ptr = new Ellipse( 5.0, 6.0 ); string name2 = ptr->shapeName(); double space2= ptr->area(); cout << name1 << " : " << space1 << endl; cout << name2 << " : " << space2 << endl; }
22.724138
50
0.53566
koichi-murakami
57e52371c2c80a644b438e9a3ec7e4e5e84aff29
2,950
cpp
C++
src/abpos.cpp
barrystyle/xpchain-v2
6ef26771300d1db0398b0d51b74db9119307708b
[ "MIT" ]
null
null
null
src/abpos.cpp
barrystyle/xpchain-v2
6ef26771300d1db0398b0d51b74db9119307708b
[ "MIT" ]
null
null
null
src/abpos.cpp
barrystyle/xpchain-v2
6ef26771300d1db0398b0d51b74db9119307708b
[ "MIT" ]
null
null
null
// Copyright (c) 2019-2020 barrystyle/xpchain team // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <amount.h> #include <chainparams.h> #include <util.h> #include <validation.h> //! return if we're in mainnet or not bool isMainnet() { return Params().NetworkIDString() == "main"; } //! return age of a given input int GetLastHeight(uint256 txHash) { uint256 hashBlock; CTransactionRef stakeInput; const Consensus::Params& consensusParams = Params().GetConsensus(); if (!GetTransaction(txHash, stakeInput, consensusParams, hashBlock)) return 0; if (hashBlock == uint256()) return 0; return mapBlockIndex[hashBlock]->nHeight; } //! return which year 'phase' we are currently in with abpos void GetPoSPhase(int nHeight, int& nPhase, int& nBlocks) { nPhase = 0, nBlocks = 0; const int nYearBlocks = isMainnet() ? 525600 : 1024; const int nStartHeight = isMainnet() ? Params().GetConsensus().abposHeight : 128; if (nHeight - nStartHeight <= 0) return; //! subtract recursively to determine year int nPhaseStep = nHeight - nStartHeight; while (nPhaseStep > nYearBlocks) { nPhase++; nPhaseStep -= nYearBlocks; } nBlocks = nPhaseStep; } //! return interest rate per input in given PoS phase int GetPoSInterest(int nHeight, int nCoinAge) { int nPhase = 0, nBlocks = 0; std::vector<unsigned int> stakeParameters; //! retrieve appropriate params GetPoSPhase(nHeight, nPhase, nBlocks); switch (nPhase) { case 0: return 0; case 1: stakeParameters = { 60, 240, 2920 }; //! 0.6% - 2.4%, 2920 = 0.1% case 2: stakeParameters = { 50, 200, 3504 }; //! 0.5% - 2.0%, 3504 = 0.1% case 3: stakeParameters = { 40, 160, 4380 }; //! 0.4% - 1.6%, 4380 = 0.1% case 4: stakeParameters = { 30, 120, 5840 }; //! 0.3% - 1.2%, 5840 = 0.1% case 5: stakeParameters = { 15, 60, 11580 }; //! 0.15% - 0.60%, 11580 = 0.1% default: return 0; } //! recursively calculate interest window int nBaseInterest = stakeParameters.at(0); int nTempCalc = nBlocks - nCoinAge; if (nTempCalc < 0) nTempCalc = 0; while (nTempCalc > 0) { nBaseInterest++; nTempCalc -= stakeParameters.at(2); } assert(nBaseInterest < stakeParameters.at(1)); return nBaseInterest; } //! calculate the stake reward, given an input coin amount and its age CAmount GetStakeReward(CAmount coinAmount, int nCoinAge) { //! we do not calculate on sub-decimal amounts CAmount calculatedAmount = round(coinAmount * COIN) / COIN; if (calculatedAmount < 1) return 0; const int nHeight = chainActive.Height(); const int nInterestRate = GetPoSInterest(nHeight, nCoinAge); CAmount nReward = (coinAmount * nInterestRate) / 10000; return nReward; }
30.412371
85
0.649153
barrystyle
57e89dd379394574585b82b36dc6d3096913ef18
155
cc
C++
Emscripten/file_io/file_io.cc
stephenfire/Book-DISO-WebAssembly
35054b59caa4284680d7dd73bf2637de5631caa7
[ "MIT" ]
57
2018-02-14T02:12:00.000Z
2022-03-04T09:12:26.000Z
Emscripten/file_io/file_io.cc
stephenfire/Book-DISO-WebAssembly
35054b59caa4284680d7dd73bf2637de5631caa7
[ "MIT" ]
15
2018-08-23T12:37:53.000Z
2021-05-09T10:22:27.000Z
Emscripten/file_io/file_io.cc
stephenfire/Book-DISO-WebAssembly
35054b59caa4284680d7dd73bf2637de5631caa7
[ "MIT" ]
15
2019-01-27T09:35:19.000Z
2022-02-03T13:56:03.000Z
#include <iostream> using namespace std; int main(int argc, char **argv) { char _t; cin >> _t; cout << _t << endl; cerr << _t << endl; return 0; }
14.090909
33
0.593548
stephenfire