blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
2
247
content_id
stringlengths
40
40
detected_licenses
listlengths
0
57
license_type
stringclasses
2 values
repo_name
stringlengths
4
111
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringlengths
4
58
visit_date
timestamp[ns]date
2015-07-25 18:16:41
2023-09-06 10:45:08
revision_date
timestamp[ns]date
1970-01-14 14:03:36
2023-09-06 06:22:19
committer_date
timestamp[ns]date
1970-01-14 14:03:36
2023-09-06 06:22:19
github_id
int64
3.89k
689M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
25 values
gha_event_created_at
timestamp[ns]date
2012-06-07 00:51:45
2023-09-14 21:58:52
gha_created_at
timestamp[ns]date
2008-03-27 23:40:48
2023-08-24 19:49:39
gha_language
stringclasses
159 values
src_encoding
stringclasses
34 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
7
10.5M
extension
stringclasses
111 values
filename
stringlengths
1
195
text
stringlengths
7
10.5M
76ad0ebf28f9ed0af1e16a25e9f10302e6d8277a
15ae3c07d969f1e75bc2af9555cf3e952be9bfff
/analysis/pragma_before/pragma_554.hpp
503daf25082180027bae8495876c557727ca076e
[]
no_license
marroko/generators
d2d1855d9183cbc32f9cd67bdae8232aba2d1131
9e80511155444f42f11f25063c0176cb3b6f0a66
refs/heads/master
2023-02-01T16:55:03.955738
2020-12-12T14:11:17
2020-12-12T14:11:17
316,802,086
0
0
null
null
null
null
UTF-8
C++
false
false
140
hpp
pragma_554.hpp
#ifndef TWIGXLYVUJQ_VJLCVYJQSEX_FXUYEGLBW_HPP #define TWIGXLYVUJQ_VJLCVYJQSEX_FXUYEGLBW_HPP #endif // TWIGXLYVUJQ_VJLCVYJQSEX_FXUYEGLBW_HPP
4363d46c2a835b97cc7ecc1ec74ca0ed209c66e6
dd3cf7414ede3f652971e6be71407122d4326974
/ADS/bit.cpp
86560e83b102b3f43ac6a01e49d69a93591d1f76
[]
no_license
AmanKathait15/Data-Structure-and-Algorithm
a3c82f086e8a376c9bfd1e0d87a538337322ebe6
d2c04d37ef7492bf2b4e24b5b7a2756043030899
refs/heads/master
2023-02-01T17:54:06.438376
2020-11-29T13:47:35
2020-11-29T13:47:35
null
0
0
null
null
null
null
UTF-8
C++
false
false
742
cpp
bit.cpp
#include<bits/stdc++.h> using namespace std; #define num int num query(num bit[],num i,num res) { for(; i>0; i = i & (i-1)) res+= bit[i]; return res; } void update(num bit[],num i,num val,num n) { for(; i<=n; i+= i & (-i)) bit[i] += val; } void display(num a[],num n) { for(num i=0; i<=n; i++) { printf("%d ",a[i]); } printf("\n"); } int main() { num n,q; cin>>n>>q; num a[n],bit[n+1]; memset(bit,0,sizeof(bit)); for(num i=0; i<n; i++) { cin>>a[i]; update(bit,i+1,a[i],n); //built bit simultaneously } while(q--) { display(bit,n); num c,i,val; cin>>c>>i; if(c) cout<<query(bit,i,0)<<"\n"; else { cin>>val; update(bit,i,(val-a[i-1]),n); a[i-1]=val; display(a,n-1); } } return 0; }
8c91ce3e7a18ec8d2f456dccc1f2eaf49927482c
affec18a9b771fba9cc089e3d587983276d3d261
/A/1064.cpp
7ce783f2fd197b902cc7aec75bd367c56330289a
[]
no_license
sh4062/PAT
62a6400ad9ba2d1e23b1075916640a27a2c4a21f
e8a907c660b62bb45ceba10c30fe35c3546aed1e
refs/heads/master
2020-04-23T09:28:25.958675
2019-04-03T10:21:00
2019-04-03T10:21:00
171,069,408
0
0
null
null
null
null
UTF-8
C++
false
false
609
cpp
1064.cpp
#include <bits/stdc++.h> using namespace std; int N; vector<int> in; void inorder(int r) { if (r > N) return; inorder(2 * r); in.push_back(r); inorder(2 * r + 1); } int main() { cin >> N; vector<int> v; v.push_back(-1); in.push_back(-1); for (int i = 0; i < N; i++) { int t; cin >> t; v.push_back(t); } sort(v.begin(), v.end()); inorder(1); vector<int> v2(N + 1, 0); for (int i = 1; i <= N; i++) { v2[in[i]] = v[i]; } for (int i = 1; i < N; i++) cout << v2[i] << " "; cout << v2[N]; }
d51d7d1c4f6ddae945fcfb050158715f9c536800
8f50c262f89d3dc4f15f2f67eb76e686b8f808f5
/MuonSpectrometer/MuonGMdbObjects/src/DblQ00Alin.cxx
c4361ead96779045e2f62686db1ed283a040a0b6
[ "Apache-2.0" ]
permissive
strigazi/athena
2d099e6aab4a94ab8b636ae681736da4e13ac5c9
354f92551294f7be678aebcd7b9d67d2c4448176
refs/heads/master
2022-12-09T02:05:30.632208
2020-09-03T14:03:18
2020-09-03T14:03:18
292,587,480
0
1
null
null
null
null
UTF-8
C++
false
false
3,794
cxx
DblQ00Alin.cxx
/* Copyright (C) 2002-2020 CERN for the benefit of the ATLAS collaboration */ /*************************************************************************** DB data - Muon Station components ----------------------------------------- ***************************************************************************/ #include "MuonGMdbObjects/DblQ00Alin.h" #include "RDBAccessSvc/IRDBRecordset.h" #include "AmdcDb/AmdcDb.h" #include "AmdcDb/AmdcDbRecord.h" #include <iostream> #include <stdio.h> namespace MuonGM { DblQ00Alin::DblQ00Alin(std::unique_ptr<IRDBQuery>&& alin) : m_nObj(0) { if(alin) { alin->execute(); m_nObj = alin->size(); m_d = new ALIN[m_nObj]; if (m_nObj == 0) std::cerr<<"NO Alin banks in the MuonDD Database"<<std::endl; // field indexes unsigned fieldVers(1); unsigned fieldDx(2); unsigned fieldDy(3); unsigned fieldI(4); unsigned fieldWidth_xs(5); unsigned fieldWidth_xl(6); unsigned fieldLength_y(7); unsigned fieldExcent(8); unsigned fieldDead1(9); unsigned fieldJtyp(10); unsigned fieldIndx(11); unsigned fieldIcut(12); int i=0; while(alin->next()) { m_d[i].version = alin->data<int>(fieldVers); m_d[i].dx = alin->data<float>(fieldDx); m_d[i].dy = alin->data<float>(fieldDy); m_d[i].i = alin->data<int>(fieldI); m_d[i].width_xs = alin->data<float>(fieldWidth_xs); m_d[i].width_xl = alin->data<float>(fieldWidth_xl); m_d[i].length_y = alin->data<float>(fieldLength_y); m_d[i].excent = alin->data<float>(fieldExcent); m_d[i].dead1 = alin->data<float>(fieldDead1); m_d[i].jtyp = alin->data<int>(fieldJtyp); m_d[i].indx = alin->data<int>(fieldIndx); m_d[i].icut = alin->data<int>(fieldIcut); i++; } alin->finalize(); } else { m_d = new ALIN[0]; std::cerr<<"NO Alin banks in the MuonDD Database"<<std::endl; } } DblQ00Alin::DblQ00Alin(AmdcDb* alin) : m_nObj(0) { IRDBRecordset_ptr pIRDBRecordset = alin->getRecordsetPtr(std::string(getObjName()),"Amdc"); std::vector<IRDBRecord*>::const_iterator it = pIRDBRecordset->begin(); m_nObj = pIRDBRecordset->size(); m_d = new ALIN[m_nObj]; if (m_nObj == 0) std::cerr<<"NO Alin banks in the AmdcDbRecord"<<std::endl; const AmdcDbRecord* pAmdcDbRecord = dynamic_cast<const AmdcDbRecord*>((*it)); if (pAmdcDbRecord == 0){ std::cerr << "No way to cast in AmdcDbRecord for " << getObjName() << std::endl; return; } std::vector< std::string> VariableList = pAmdcDbRecord->getVariableList(); int ItemTot = VariableList.size() ; for(int Item=0 ; Item<ItemTot ; Item++){ std::string DbVar = VariableList[Item]; } int i = -1; it = pIRDBRecordset->begin(); for( ; it<pIRDBRecordset->end(); it++){ pAmdcDbRecord = dynamic_cast<const AmdcDbRecord*>((*it)); if(pAmdcDbRecord == 0){ std::cerr << "No way to cast in AmdcDbRecord for " << getObjName() << std::endl; return; } i = i + 1; m_d[i].version = (*it)->getInt("VERS"); m_d[i].dx = (*it)->getFloat("DX"); m_d[i].dy = (*it)->getFloat("DY"); m_d[i].i = (*it)->getInt("I"); m_d[i].width_xs = (*it)->getFloat("WIDTH_XS"); m_d[i].width_xl = (*it)->getFloat("WIDTH_XL"); m_d[i].length_y = (*it)->getFloat("LENGTH_Y"); m_d[i].excent = (*it)->getFloat("EXCENT"); m_d[i].dead1 = (*it)->getFloat("DEAD1"); m_d[i].jtyp = (*it)->getInt("JTYP"); m_d[i].indx = (*it)->getInt("INDX"); m_d[i].icut = (*it)->getInt("ICUT"); } } DblQ00Alin::~DblQ00Alin() { delete [] m_d; } } // end of namespace MuonGM
c79ce5c119f12feec1a3e1938ca9157384fae340
d77775087bcc0c0ea68bf02550486b7c807a95f1
/ObjExpCore/ProcessInfo.cpp
401ae9073729b89f171d774e09d2c5f795d6f94a
[ "MIT" ]
permissive
zodiacon/SystemExplorer
7dcbd08e95a1f64c81b9fc7faadc2866b271dd73
f5d51f63581807dbd2a8957bc4bc9dae4aa001cc
refs/heads/master
2023-06-21T20:03:41.393103
2023-06-10T20:44:16
2023-06-10T20:44:16
204,397,104
593
113
MIT
2021-08-28T09:48:59
2019-08-26T04:41:32
C
UTF-8
C++
false
false
780
cpp
ProcessInfo.cpp
#include "pch.h" #include "ProcessInfo.h" using namespace WinSys; ProcessInfo::ProcessInfo() { } const std::vector<std::shared_ptr<ThreadInfo>>& ProcessInfo::GetThreads() const { return _threads; } const std::wstring& WinSys::ProcessInfo::GetUserName() const { if (!_userName.empty()) return _userName; if (UserSid) { WCHAR name[64], domain[64]; DWORD lname = _countof(name), ldomain = _countof(domain); SID_NAME_USE use; if (::LookupAccountSid(nullptr, (PSID)UserSid, name, &lname, domain, &ldomain, &use)) _userName = domain + std::wstring(L"\\") + name; } return _userName; } void ProcessInfo::AddThread(std::shared_ptr<ThreadInfo> thread) { _threads.push_back(thread); } void ProcessInfo::ClearThreads() { _threads.clear(); _threads.reserve(16); }
23f4c79485a35008a4e092bf46e367323c188d9e
7f85be85e41a07dd9e4587f589ed1f95885027c5
/exec/analyze_pfc.cc
45bd2cd53b48ff2c15294dfc8e6f7d2388dd3852
[]
no_license
thomas-davenport-op/MODAnalyzer-PC
e1210855ef066c32b954445c6ba445b78b30c72e
8da41e51d668812dc5db933822c4506d89e0017a
refs/heads/master
2020-05-17T10:22:24.753524
2020-04-21T13:13:30
2020-04-21T13:13:30
183,653,165
0
0
null
null
null
null
UTF-8
C++
false
false
6,901
cc
analyze_pfc.cc
#include <iostream> #include <unordered_map> #include <sstream> #include <fstream> #include <vector> #include <string> #include <stdexcept> #include <iterator> #include <iomanip> #include <limits> #include <chrono> #include <boost/unordered_map.hpp> #include <boost/unordered_map.hpp> #include <boost/filesystem.hpp> #include "fastjet/ClusterSequence.hh" #include "fastjet/contrib/SoftDrop.hh" #include "../interface/Event.h" #include "../interface/Property.h" using namespace std; using namespace fastjet; using namespace contrib; using namespace boost::filesystem; void analyze_pfc(MOD::Event & event_being_read, ofstream & output_file, int & event_serial_number); void get_all_files_to_process(std::vector<string> & all_files, vector<boost::filesystem::path> input_paths); double angularity_lambda(PseudoJet jet, float k, float beta); int main(int argc, char * argv[]) { auto start = std::chrono::steady_clock::now(); ofstream output_file(argv[1], ios::out | ios::app); if (argc < 3) { std::cerr << "You need to give at least two arguments: output path and one or more input directories." << endl; return 0; } vector<path> input_paths; for (int i=2; i < argc; i++) { input_paths.push_back(argv[i]); } cout << endl << endl << "Starting count_events with the following given arguments: " << endl << endl; cout << "Output File : " << argv[1] << endl; cout << "Input Paths (" << input_paths.size() << ") : "; for (unsigned i=0; i < input_paths.size(); i++) { if (i > 0) cout << " " << input_paths[i] << endl; else cout << input_paths[i] << endl; } // Recursively collect all filenames to process. vector<string> all_filenames; get_all_files_to_process(all_filenames, input_paths); // Sort the list. std::sort(all_filenames.begin(), all_filenames.end()); cout << endl << endl << "Starting counting event on " << all_filenames.size() << " files." << endl << endl; int file_counter = 0; int event_counter = 0; // Loop through all those files and count events. for (unsigned i = 0; i < all_filenames.size(); i++) { ifstream file_to_process(all_filenames[i]); file_counter++; if ((file_counter % 100) == 0) cout << "Processing file number " << file_counter << " / " << all_filenames.size() << endl; MOD::Event event_being_read; int event_serial_number = 1; while( event_being_read.read_event(file_to_process) ) { if( (event_counter % 10000) == 0 ) cout << "Processed " << (event_counter - 1) << " events so far." << endl; // Write out version info in the output file for the "syncing plots" thing to work (as it needs to figure out which directory to put things into). if (event_serial_number == 1) output_file << "%" << " Version " << event_being_read.version() << endl; analyze_pfc(event_being_read, output_file, event_serial_number); event_being_read = MOD::Event(); event_serial_number++; event_counter++; } event_being_read = MOD::Event(); event_serial_number++; // } } auto finish = std::chrono::steady_clock::now(); double elapsed_seconds = std::chrono::duration_cast<std::chrono::duration<double> >(finish - start).count(); cout << "Finished processing " << (event_counter - 1) << " events in " << elapsed_seconds << " seconds!" << endl; return 0; } void get_all_files_to_process(std::vector<string> & all_files, vector<boost::filesystem::path> input_paths) { for (unsigned i = 0; i < input_paths.size(); i++) { boost::filesystem::path input_path = input_paths[i]; directory_iterator end_itr; for (directory_iterator itr(input_path); itr != end_itr; ++itr) { if (is_regular_file(itr->path())) { string current_file = itr->path().string(); if (current_file.substr( current_file.length() - 3, current_file.length()) == "mod") { all_files.push_back(current_file); } } else { // cout << itr->path().string() << endl; get_all_files_to_process(all_files, { itr->path() }); } } } } void analyze_pfc(MOD::Event & event_being_read, ofstream & output_file, int & event_serial_number) { JetDefinition jet_def_cambridge(cambridge_algorithm, fastjet::JetDefinition::max_allowable_R); PseudoJet hardest_jet = event_being_read.hardest_jet(); if ( ! (hardest_jet.E() > 0.0)) { return; } double jec; if ((event_being_read.data_source() == 0) || (event_being_read.data_source() == 3)) { // EXPERIMENT or PRISTINE jec = event_being_read.get_hardest_jet_jec(); } else { jec = 1.0; } vector<PseudoJet> hardest_jet_pfcs = hardest_jet.constituents(); for (unsigned i = 0; i < hardest_jet_pfcs.size(); i++) { vector<MOD::Property> properties; properties.push_back(MOD::Property("# Entry", " Entry")); properties.push_back(MOD::Property("event_number", event_being_read.event_number())); properties.push_back(MOD::Property("prescale", event_being_read.weight())); properties.push_back(MOD::Property("hardest_pT", jec * hardest_jet.pt())); properties.push_back(MOD::Property("jet_eta", hardest_jet.eta())); properties.push_back(MOD::Property("pfc_pT", hardest_jet_pfcs[i].pt())); properties.push_back(MOD::Property("pfc_eta", hardest_jet_pfcs[i].eta())); properties.push_back(MOD::Property("pfc_pdgId", hardest_jet_pfcs[i].user_info<MOD::InfoPFC>().pdgId())); // Now that we've calculated all observables, write them out. string name; int padding = 40; if (event_serial_number == 1) { for (unsigned p = 0; p < properties.size(); p++) { if (p > 0) output_file << setw(padding); output_file << properties[p].name(); } output_file << endl; } for (unsigned q = 0; q < properties.size(); q++) { if (q > 0) output_file << setw(padding); output_file << properties[q]; } output_file << endl; } } double angularity_lambda(PseudoJet jet, float k, float beta) { double lambda = 0.0; double R = 0.5; // Jet Radius. double total_pT = 0.0; for (unsigned j = 0; j < jet.constituents().size(); j++) { total_pT += jet.constituents()[j].pt(); } for (unsigned i = 0; i < jet.constituents().size(); i++) { PseudoJet constituent = jet.constituents()[i]; double z_i = constituent.pt() / total_pT; double delta_R = constituent.delta_R(jet); double theta_i = delta_R / R; lambda += pow(z_i, k) * pow(theta_i, beta); } return lambda; }
f65479beecd91581e106bc44e73d7e17fdc4d1ae
fd911fe124408f4f6e300b084b6f1d30f5da30ba
/libs/base/include/mrpt/utils/CTicTac.h
665b933a22ae8c5a118277c76ea678524ad099ad
[ "BSD-3-Clause" ]
permissive
tg1716/SLAM
5710024e34f83687c6524cfb947479951d67941e
b8583fb98a4241d87ae08ac78b0420c154f5e1a5
refs/heads/master
2021-01-02T09:11:41.110755
2017-07-30T16:04:31
2017-07-30T16:04:31
99,160,224
5
2
null
2017-08-02T21:13:21
2017-08-02T20:57:07
null
UTF-8
C++
false
false
1,550
h
CTicTac.h
/* +------------------------------------------------------------------------+ | Mobile Robot Programming Toolkit (MRPT) | | http://www.mrpt.org/ | | | | Copyright (c) 2005-2017, Individual contributors, see AUTHORS file | | See: http://www.mrpt.org/Authors - All rights reserved. | | Released under BSD License. See details in http://www.mrpt.org/License | +------------------------------------------------------------------------+ */ #ifndef CTICTAC_H #define CTICTAC_H #include <mrpt/base/link_pragmas.h> #include <type_traits> namespace mrpt { namespace utils { /** This class implements a high-performance stopwatch. * Typical resolution is about 1e-6 seconds. * \note The class is named after the Spanish equivalent of "Tic-Toc" ;-) * \ingroup mrpt_base_grp */ class BASE_IMPEXP CTicTac { public: /** Default constructor. Implicitly calls Tic() */ CTicTac(); CTicTac(const CTicTac&) = delete; CTicTac& operator=(const CTicTac&) = delete; /** Starts the stopwatch. \sa Tac */ void Tic(); /** Stops the stopwatch. \return Returns the ellapsed time in seconds. \sa * Tic */ double Tac(); private: unsigned char largeInts[64]; }; // End of class def. static_assert( !std::is_copy_constructible<CTicTac>::value && !std::is_copy_assignable<CTicTac>::value, "Copy Check"); } // End of namespace } // End of namespace #endif
5ecc2981b944ed21b31e3144894e05de28c2cc42
4e6ee280d0635e9b747e19cf61447c67a2609e77
/Engine/Command.h
1cf059489640dc18f3526d67a8e2179df04c94c5
[]
no_license
NicolasCAZIN/TRN
89442af85c1b15795e752c4c77911fb853e508cc
b236d94b2b9e200398f5d56f752c53bc8fbc1fb8
refs/heads/master
2021-01-02T09:36:07.057149
2019-06-11T11:55:41
2019-06-11T11:55:41
99,256,071
0
0
null
null
null
null
UTF-8
C++
false
false
388
h
Command.h
#pragma once #include "engine_global.h" namespace TRN { namespace Engine { class ENGINE_EXPORT Executor { protected : class Handle; std::unique_ptr<Handle> handle; public: Executor(); ~Executor(); public : void post(const std::function<void(void)> &functor); public: public : void join(); static std::shared_ptr<Executor> create(); }; }; };
da38dd9d9bf2d254311aaceed73bbb1ade280196
52531543ffc69b4ddb83332d7596d9bec6dea63b
/src/Chapter15/queuetp.h
d6c5636f4944ee3c8b5bc3fce864a3575e307b2d
[]
no_license
linxiaoyi0724/Cpp_CourseUbuntu
6daf5913eada48c8b57c9047939a59fc25affe53
a4894898ac1a5a231cabc430a6f33c565cd219df
refs/heads/master
2021-07-13T08:15:31.999533
2020-09-07T06:00:40
2020-09-07T06:00:40
195,845,505
0
0
null
null
null
null
UTF-8
C++
false
false
1,345
h
queuetp.h
#ifndef QUEUETP_H_ #define QUEUETP_H_ template<typename T> class QueueTp { private: enum { Q_SIZE = 10 }; class Node { public: T item; Node* next; Node(const T& i):item(i),next(0){} }; Node* front; Node* rear; int items; const int qsize; QueueTp(const QueueTp& q):qsize(0){} //QueueTp& operator=(const QueueTp& q) { return *this; } public: QueueTp(int qs = Q_SIZE); ~QueueTp(); bool IsEmpty()const { return items == 0; } bool IsFull()const { return items == qsize; } int QueueCount()const { return items; } bool EnQueue(const T &item); bool DeQueue(T &item); }; template <typename T> QueueTp<T>::QueueTp(int qs):qsize(qs) { front = rear = 0; items = 0; } template <typename T> QueueTp<T>::~QueueTp() { Node* temp; while (front != 0) { temp = front; front = front->next; delete temp; } } template<typename T> bool QueueTp<T>::EnQueue(const T &item) { if (IsFull()) { return false; } Node *add = new Node(item); if (add == NULL) { return false; } items++; if (front == 0) { front = add; } else { rear->next = add; } rear = add; return true; } template <typename T> bool QueueTp<T>::DeQueue(T &item) { if (front == 0) return false; item = front->item; items--; Node* temp = front; front = front->next; delete temp; if (items == 0) rear = 0; return true; } #endif
f9efbf42a29ce668fbe39db537730d09c873e887
f954d4becae0ef07d253dec5ebe9eb7238919f4d
/editor/cn/[剑指 Offer 05]替换空格.cpp
a316aaa034729eae4a1dbe9be52e2c43923da69c
[]
no_license
iznilul/leetcode-
ec2c4f3d6ea487daa0791810c45971abeca87952
c4ee1510701601e6d0851e68753ba0768099cbfb
refs/heads/main
2023-03-30T14:46:19.387944
2021-04-09T05:02:21
2021-04-09T05:02:21
315,317,344
0
0
null
null
null
null
UTF-8
C++
false
false
956
cpp
[剑指 Offer 05]替换空格.cpp
//请实现一个函数,把字符串 s 中的每个空格替换成"%20"。 // // // // 示例 1: // // 输入:s = "We are happy." //输出:"We%20are%20happy." // // // // 限制: // // 0 <= s 的长度 <= 10000 // 👍 66 👎 0 //leetcode submit region begin(Prohibit modification and deletion) class Solution { public: string replaceSpace(string s) { int length = s.length(); int count=0; for(int i=0;i<length;i++){ if(s[i]==' ') count++; } s.resize(length + count * 2); int length1=s.length(); for(int i=length-1,j=length1-1;i>=0;i--,j--){ if(s[i]!=' ') s[j] = s[i]; else{ s[j] = '0'; s[j - 1] = '2'; s[j - 2] = '%'; j-=2; } } return s; } }; //leetcode submit region end(Prohibit modification and deletion)
7986f4c8fe2aba05786af64f355686f27bd98be3
4efddc6f368533090c68bd806d6327154cfa57a0
/day7/intcode.hpp
eb073b15bf9223f1cf5ba67b8493e42dcdfdffcd
[]
no_license
Shensd/AdventOfCode2019
e6edcfae513b4fdda9ab58bdd6ed44778726d666
3712f9e23229b001edf4d7d80cb9c834ee649262
refs/heads/master
2022-12-10T01:38:51.353812
2019-12-17T02:22:25
2019-12-17T02:22:25
225,270,494
0
0
null
2022-11-22T04:54:12
2019-12-02T02:44:41
C++
UTF-8
C++
false
false
3,139
hpp
intcode.hpp
#ifndef INTCODE_HPP #define INTCODE_HPP #include <iostream> #include <fstream> #include <vector> #include <sstream> #include <algorithm> namespace intcode { /** * Contains information about a given instruction */ class Instruction { public: // max argument amount is 3 bool flags[3]; unsigned int opcode; Instruction(unsigned int opcode, bool flags[3]) : opcode(opcode) { std::copy(flags, flags+3, Instruction::flags); } std::string to_string(void) { char buffer[32]; sprintf(buffer, "OPCODE : %u, FLAGS : %d%d%d", opcode, flags[0], flags[1], flags[2]); return buffer; } }; /** * Used to control input to program in the form of a universal int stream */ class IntStream { public: std::vector<int> contents; IntStream(std::vector<int> contents) : contents(contents) {} int get(void) { int last = contents.back(); contents.pop_back(); return last; } void push(int value) { contents.push_back(value); } int size(void) { return contents.size(); } }; enum { PROGRAM_FINISH, PROGRAM_BEGIN, OUT_OF_INSTRUCTIONS, INPUT_EMPTY, UNKNOWN_OPCODE }; /** * Used for resuming execution from a given previous state */ class RunState { public: unsigned int opcode_position; std::vector<int> output; unsigned int interrupt_reason; RunState(unsigned int opcode_position, std::vector<int> output, unsigned int interrupt_reason) : opcode_position(opcode_position), output(output), interrupt_reason(interrupt_reason) {} RunState() : opcode_position(0), output({}), interrupt_reason(PROGRAM_BEGIN) {} }; Instruction parse_instruction(int instruction); std::vector<int> get_opcodes_from_file(std::string file_location); typedef int (*opcodefnptr)(int, std::vector<int>&, IntStream&, std::vector<int>&); /* BEGIN INSTRUCTION FUNCTIONS */ int instr_add(int offset, std::vector<int>& tape, IntStream& input, std::vector<int>& output); int instr_multi(int offset, std::vector<int>& tape, IntStream& input, std::vector<int>& output); int instr_input(int offset, std::vector<int>& tape, IntStream& input, std::vector<int>& output); int instr_output(int offset, std::vector<int>& tape, IntStream& input, std::vector<int>& output); int instr_jump_true(int offset, std::vector<int>& tape, IntStream& input, std::vector<int>& output); int instr_jump_false(int offset, std::vector<int>& tape, IntStream& input, std::vector<int>& output); int instr_less_than(int offset, std::vector<int>& tape, IntStream& input, std::vector<int>& output); int instr_equals(int offset, std::vector<int>& tape, IntStream& input, std::vector<int>& output); /* END INSTRUCTION FUNCTIONS */ RunState run_program(std::vector<int>& opcodes, std::vector<int> input, RunState state = RunState()); } #endif // !INTCODE_HPP
46e9e3fb74c7df4068d1c380b22bcd769748ac40
04f15913aca8a702efe47962bf82b60eedad73d9
/World/LibZ/MapParameters.h
49e277e0b09b858cc9d5c849287b61b3dc34d91a
[]
no_license
DevilCCCP/Code
eae9b7f5a2fede346deefe603a817027a87ef753
9cc1a06e5010bb585876056a727abad48bca3915
refs/heads/master
2021-10-07T17:04:27.728918
2021-09-28T06:49:50
2021-09-28T06:49:50
166,522,458
0
1
null
null
null
null
UTF-8
C++
false
false
1,521
h
MapParameters.h
#pragma once #include <Lib/Include/Common.h> DefineClassS(MapParameters); class MapParameters { PROPERTY_GET (int, GlobeRadius) PROPERTY_GET (int, GlobeSector) PROPERTY_GET (int, WorldSector) PROPERTY_GET (int, GroundPercent) PROPERTY_GET (int, GlobePlateCount) PROPERTY_GET (int, WorldPlateCount) ; public: void setGlobeRadius(int value); void setGlobeSector(int value); void setWorldSector(int value); void setGroundPercent(int value); void setGlobePlateCount(int value); void setWorldPlateCount(int value); public: static int MinimumGlobeRadius() { return 30; } static int MaximumGlobeRadius() { return 300; } static int DefaultGlobeRadius() { return 100; } static int MinimumGlobeSector() { return 30; } static int MaximumGlobeSector() { return 360; } static int DefaultGlobeSector() { return 120; } static int MinimumWorldSector() { return 30; } static int MaximumWorldSector() { return 360; } static int DefaultWorldSector() { return 120; } static int MinimumGroundPercent() { return 10; } static int MaximumGroundPercent() { return 80; } static int DefaultGroundPercent() { return 30; } static int MinimumGlobePlateCount() { return 1; } static int MaximumGlobePlateCount() { return 9; } static int DefaultGlobePlateCount() { return 3; } static int MinimumWorldPlateCount() { return 1; } static int MaximumWorldPlateCount() { return 9; } static int DefaultWorldPlateCount() { return 3; } public: MapParameters(); };
709b1ced0dbee7ae7830ee42d8633130a1ce06e3
c9cd834598d05d75668b6774bb46b592ed37c0d6
/source/main.cpp
4f97cab1a9005a7f2299834c4d6f4729c42dc678
[]
no_license
pmcalabrese/web-bluetooth-mbed
e994b89bdb86ef5b1e104a21bd3e8ae8d8dc503a
a8c6929c6d00e2f7c307aee657b5350eca58b959
refs/heads/master
2021-01-23T00:44:30.157433
2018-02-16T11:13:32
2018-02-16T11:13:32
92,835,668
0
0
null
null
null
null
UTF-8
C++
false
false
4,897
cpp
main.cpp
/* mbed Microcontroller Library * Copyright (c) 2006-2013 ARM Limited * * 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 <events/mbed_events.h> #include <mbed.h> #include "ble/BLE.h" #include "LEDService.h" #include "ButtonService.h" DigitalOut alivenessLED(LED1, 0); DigitalOut actuatedLED(LED2, 0); DigitalOut pLED(LED3, 0); InterruptIn button1(BUTTON1); const static char DEVICE_NAME[] = "LED"; static const uint16_t uuid16_list[] = {LEDService::LED_SERVICE_UUID, ButtonService::BUTTON_SERVICE_UUID}; static EventQueue eventQueue( /* event count */ 10 * /* event size */ 32 ); enum { RELEASED = 0, PRESSED, IDLE }; static uint8_t buttonState = IDLE; static ButtonService *buttonServicePtr; static LEDService *ledServicePtr; // I think there must be a static here void disconnectionCallback(const Gap::DisconnectionCallbackParams_t *params) { (void) params; BLE::Instance().gap().startAdvertising(); } void blinkCallback(void) { alivenessLED = !alivenessLED; /* Do blinky on LED1 to indicate system aliveness. */ } /** * This callback allows the LEDService to receive updates to the ledState Characteristic. * * @param[in] params * Information about the characterisitc being updated. */ void onDataWrittenCallback(const GattWriteCallbackParams *params) { if ((params->handle == ledServicePtr->getValueHandle()) && (params->len == 1)) { actuatedLED = *(params->data); } } /** * This function is called when the ble initialization process has failled */ void onBleInitError(BLE &ble, ble_error_t error) { /* Initialization error handling should go here */ } /** * Callback triggered when the ble initialization process has finished */ void bleInitComplete(BLE::InitializationCompleteCallbackContext *params) { BLE& ble = params->ble; ble_error_t error = params->error; if (error != BLE_ERROR_NONE) { /* In case of error, forward the error handling to onBleInitError */ onBleInitError(ble, error); return; } /* Ensure that it is the default instance of BLE */ if(ble.getInstanceID() != BLE::DEFAULT_INSTANCE) { return; } ble.gap().onDisconnection(disconnectionCallback); ble.gattServer().onDataWritten(onDataWrittenCallback); bool initialValueForLEDCharacteristic = false; ledServicePtr = new LEDService(ble, initialValueForLEDCharacteristic); /* Setup primary service */ bool initialValueForBUTTONCharacteristic = false; buttonServicePtr = new ButtonService(ble, initialValueForBUTTONCharacteristic /* initial value for button pressed */); /* setup advertising */ ble.gap().accumulateAdvertisingPayload(GapAdvertisingData::BREDR_NOT_SUPPORTED | GapAdvertisingData::LE_GENERAL_DISCOVERABLE); ble.gap().accumulateAdvertisingPayload(GapAdvertisingData::COMPLETE_LIST_16BIT_SERVICE_IDS, (uint8_t *)uuid16_list, sizeof(uuid16_list)); ble.gap().accumulateAdvertisingPayload(GapAdvertisingData::COMPLETE_LOCAL_NAME, (uint8_t *)DEVICE_NAME, sizeof(DEVICE_NAME)); ble.gap().setAdvertisingType(GapAdvertisingParams::ADV_CONNECTABLE_UNDIRECTED); ble.gap().setAdvertisingInterval(1000); /* 1000ms. */ ble.gap().startAdvertising(); } void scheduleBleEventsProcessing(BLE::OnEventsToProcessCallbackContext* context) { BLE &ble = BLE::Instance(); eventQueue.call(Callback<void()>(&ble, &BLE::processEvents)); } void buttonPressedCallback(void) { /* Note that the buttonPressedCallback() executes in interrupt context, so it is safer to access * BLE device API from the main thread. */ buttonState = PRESSED; buttonServicePtr->updateButtonState(buttonState); pLED = true; } void buttonReleasedCallback(void) { /* Note that the buttonReleasedCallback() executes in interrupt context, so it is safer to access * BLE device API from the main thread. */ buttonState = RELEASED; buttonServicePtr->updateButtonState(buttonState); pLED = false; } int main() { int id = eventQueue.call_every(100, blinkCallback); button1.fall(buttonPressedCallback); button1.rise(buttonReleasedCallback); BLE &ble = BLE::Instance(); ble.onEventsToProcess(scheduleBleEventsProcessing); ble.init(bleInitComplete); eventQueue.dispatch_forever(); while (ble.hasInitialized() == false) { /* spin loop */ } return 0; }
3ce9820df60f6f562f88c5e97ae32b4453408c80
830bef33457d814d0168e5a9557987a049c0083c
/src/docker/v2/HTTPRequest.h
4c2ad53486e79de8666bd7467de9cc31681075dc
[]
no_license
przemkovv/sphinx-cpp
c005f1f11904c72c3f1561319c9fb867bde5ebdd
5950f1e331fd968303b8d8756758c57686c92cfb
refs/heads/master
2020-05-21T19:09:32.066325
2016-11-24T02:46:28
2016-11-24T02:46:28
62,318,132
0
0
null
null
null
null
UTF-8
C++
false
false
652
h
HTTPRequest.h
#pragma once #include "HTTPCommon.h" #include "HTTPHeaders.h" #include <fmt/format.h> #include <map> #include <string> namespace Sphinx { namespace Docker { namespace v2 { class HTTPRequest { HTTPMethod method_; std::string uri_; HTTPHeaders headers_; std::string data_; void addDefaultHeaders(); public: HTTPRequest() : HTTPRequest(HTTPMethod::GET, "/") {} HTTPRequest(HTTPMethod method, const std::string &uri, const std::string &data = "", const HTTPHeaders &additional_headers = {}); std::string to_string() const; }; } // namespace v2 } // namespace Docker } // namespace Sphinx
36831e42c1cb8497bede654b2d33398d18f63d54
d91a183cd3f4c4909c5603825568c47e97de559a
/C++/Fibonacci.cpp
7a3c99f5f043063d0c7e0c2fb19fe057e66b8145
[]
no_license
Eliale/CandCplusplus
b4c5236c80e06f17dacbe2ee307be8abbeda0356
4a578cdd7eb6e3220d2caef6e2b22c49e4620e3d
refs/heads/master
2021-01-01T04:26:30.026096
2016-05-10T04:10:45
2016-05-10T04:10:45
58,429,000
0
0
null
null
null
null
UTF-8
C++
false
false
324
cpp
Fibonacci.cpp
#include <iostream> #include<conio.h> using namespace std; int f(int o){ int s,a=0,b=1,c=1; while(c<=o){ s=a+b; a=b; b=s; c++; } return s; } int main(){ int s,o; cout<<"Posicion: ";cin>>o; s=f(o); cout<<"La serie va en :"<<s<<endl; cout<<" Presione una tecla para salir"; getch(); }
45df26106f2eaf8086be75eff545f187fb8575d7
acb84fb8d54724fac008a75711f926126e9a7dcd
/codeforces/705/D[ Ant Man ].cpp
021fa7710dd57afd58a4e879f37bf6e9b47d46b1
[]
no_license
zrt/algorithm
ceb48825094642d9704c98a7817aa60c2f3ccdeb
dd56a1ba86270060791deb91532ab12f5028c7c2
refs/heads/master
2020-05-04T23:44:25.347482
2019-04-04T19:48:58
2019-04-04T19:48:58
179,553,878
1
0
null
null
null
null
UTF-8
C++
false
false
2,712
cpp
D[ Ant Man ].cpp
#include<cstdio> #include<cstring> #include<algorithm> #include<cmath> using namespace std; typedef long long LL; #define int long long int n,s,e; int x[5005],a[5005],b[5005],c[5005],d[5005]; LL dp[5005][5005]; LL inf; signed main(){ scanf("%I64d%I64d%I64d",&n,&s,&e); for(int i=1;i<=n;i++) scanf("%I64d",&x[i]); for(int i=1;i<=n;i++) scanf("%I64d",&a[i]); for(int i=1;i<=n;i++) scanf("%I64d",&b[i]); for(int i=1;i<=n;i++) scanf("%I64d",&c[i]); for(int i=1;i<=n;i++) scanf("%I64d",&d[i]); if(s>e){ s=n-s+1; e=n-e+1; reverse(x+1,x+n+1); reverse(a+1,a+n+1); reverse(b+1,b+n+1); reverse(c+1,c+n+1); reverse(d+1,d+n+1); for(int i=1;i<=n;i++) swap(a[i],b[i]); for(int i=1;i<=n;i++) swap(c[i],d[i]); } //s left e right //dp[][] memset(dp,0x3f,sizeof dp); dp[1][0]=0; inf=dp[0][0]; for(int i=1;i<=n;i++){ for(int j=0;j<=n;j++){ if(j==0&&i!=1) continue; if(dp[i][j]!=inf){ if(i==s){ /* i==s 1 ->| 2 |-> 3 |<- 4 <-| */ //2 dp[i+1][j+1]=min(dp[i+1][j+1],dp[i][j]+d[i]+(j+1)*abs(x[i+1]-x[i])); //4 if(j>=2) dp[i+1][j-1]=min(dp[i+1][j-1],dp[i][j]+c[i]+(j-1)*abs(x[i+1]-x[i])); }else if(i==e){ /* i==e 1 ->| 2 |-> 3 |<- 4 <-| */ //1 if(j>=2 || e == n) dp[i+1][j-1]=min(dp[i+1][j-1],dp[i][j]+a[i]+(j-1)*abs(x[i+1]-x[i])); //3 dp[i+1][j+1]=min(dp[i+1][j+1],dp[i][j]+b[i]+(j+1)*abs(x[i+1]-x[i])); }else{ //i!=s i!=e /* 1 > 2 v 3 < 4 ^ */ //1 if(j>=3) dp[i+1][j-2]=min(dp[i+1][j-2],dp[i][j]+a[i]+c[i]+(j-2)*(abs(x[i+1]-x[i]))); if(j==2&&(i==n)) dp[i+1][j-2]=min(dp[i+1][j-2],dp[i][j]+a[i]+c[i]); //2 if(j>0) dp[i+1][j]=min(dp[i+1][j],dp[i][j]+a[i]+d[i]+j*abs(x[i+1]-x[i])); //4 if(j>1) dp[i+1][j]=min(dp[i+1][j],dp[i][j]+b[i]+c[i]+j*abs(x[i+1]-x[i])); //3 dp[i+1][j+2]=min(dp[i+1][j+2],dp[i][j]+d[i]+b[i]+(j+2)*abs(x[i+1]-x[i])); } } } } printf("%I64d\n",dp[n+1][0]); return 0; }
4af4aad0a0b5d51535f2d3a898f289868dec2274
bd95293502da63e754234efebab66569f127f9e6
/Tree/Easy/538. Convert BST to Greater Tree.cpp
1c45653557cfa314bbb10aee6fc51c6cbb2686dc
[]
no_license
TCODeva/Algorithms
2444cfe5a1158303ffa1c6e37eee14c3b9a924de
41183e9849df676d04177b2f4659143392ccd06f
refs/heads/master
2021-06-17T15:37:39.812306
2019-08-23T02:22:53
2019-08-23T02:22:53
138,134,788
0
0
null
null
null
null
UTF-8
C++
false
false
1,742
cpp
538. Convert BST to Greater Tree.cpp
/* LeetCode 538. Convert BST to Greater Tree * Given a Binary Search Tree (BST), convert it to a Greater Tree such that every key of the original BST is changed to the original key plus sum of all keys greater than the original key in BST. * * Example: * * Input: The root of a Binary Search Tree like this: * 5 * / \ * 2 13 * * Output: The root of a Greater Tree like this: * 18 * / \ * 20 13 */ /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ //reverse in-order traversal: class Solution { public: TreeNode* convertBST(TreeNode* root) { if (root) { convertBST(root->right); sum += root->val; root->val = sum; convertBST(root->left); } return root; } private: int sum = 0; }; //Stack: class Solution { public: TreeNode* convertBST(TreeNode* root) { int sum = 0; TreeNode* node = root; stack<TreeNode*> stack; while (!stack.empty() || node) { /* push all nodes up to (and including) this subtree's maximum on * the stack. */ while (node) { stack.push(node); node = node->right; } node = stack.top(); stack.pop(); sum += node->val; node->val = sum; /* all nodes with values between the current and its parent lie in * the left subtree. */ node = node->left; } return root; } };
7b290685ae4cd46ad1c1c64a4291129c7f55cb57
385cfbb27ee3bcc219ec2ac60fa22c2aa92ed8a0
/ThirdParty/fbxsdk/2009.3/include/fbxfilesdk/kfbxmodules/kfbxplugin.h
d21ba031e99e46cc73d19232afbb382c6c6e403f
[ "LicenseRef-scancode-unknown-license-reference", "MIT" ]
permissive
palestar/medusa
edbddf368979be774e99f74124b9c3bc7bebb2a8
7f8dc717425b5cac2315e304982993354f7cb27e
refs/heads/develop
2023-05-09T19:12:42.957288
2023-05-05T12:43:35
2023-05-05T12:43:35
59,434,337
35
18
MIT
2018-01-21T01:34:01
2016-05-22T21:05:17
C++
UTF-8
C++
false
false
8,272
h
kfbxplugin.h
#ifndef FBXFILESDK_KFBXMODULES_KFBXPLUGIN_H #define FBXFILESDK_KFBXMODULES_KFBXPLUGIN_H /************************************************************************************** Copyright (C) 2001 - 2006 Autodesk, Inc. and/or its licensors. All Rights Reserved. The coded instructions, statements, computer programs, and/or related material (collectively the "Data") in these files contain unpublished information proprietary to Autodesk, Inc. and/or its licensors, which is protected by Canada and United States of America federal copyright law and by international treaties. The Data may not be disclosed or distributed to third parties, in whole or in part, without the prior written consent of Autodesk, Inc. ("Autodesk"). THE DATA IS PROVIDED "AS IS" AND WITHOUT WARRANTY. ALL WARRANTIES ARE EXPRESSLY EXCLUDED AND DISCLAIMED. AUTODESK MAKES NO WARRANTY OF ANY KIND WITH RESPECT TO THE DATA, EXPRESS, IMPLIED OR ARISING BY CUSTOM OR TRADE USAGE, AND DISCLAIMS ANY IMPLIED WARRANTIES OF TITLE, NON-INFRINGEMENT, MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE OR USE. WITHOUT LIMITING THE FOREGOING, AUTODESK DOES NOT WARRANT THAT THE OPERATION OF THE DATA WILL BE UNINTERRUPTED OR ERROR FREE. IN NO EVENT SHALL AUTODESK, ITS AFFILIATES, PARENT COMPANIES, LICENSORS OR SUPPLIERS ("AUTODESK GROUP") BE LIABLE FOR ANY LOSSES, DAMAGES OR EXPENSES OF ANY KIND (INCLUDING WITHOUT LIMITATION PUNITIVE OR MULTIPLE DAMAGES OR OTHER SPECIAL, DIRECT, INDIRECT, EXEMPLARY, INCIDENTAL, LOSS OF PROFITS, REVENUE OR DATA, COST OF COVER OR CONSEQUENTIAL LOSSES OR DAMAGES OF ANY KIND), HOWEVER CAUSED, AND REGARDLESS OF THE THEORY OF LIABILITY, WHETHER DERIVED FROM CONTRACT, TORT (INCLUDING, BUT NOT LIMITED TO, NEGLIGENCE), OR OTHERWISE, ARISING OUT OF OR RELATING TO THE DATA OR ITS USE OR ANY OTHER PERFORMANCE, WHETHER OR NOT AUTODESK HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH LOSS OR DAMAGE. **************************************************************************************/ #include <fbxfilesdk/components/kbaselib/kaydaradef_h.h> // FBX includes #include <fbxfilesdk/kfbxplugins/kfbxobject.h> #include <fbxfilesdk/components/kbaselib/klib/kstring.h> #include <fbxfilesdk/components/kbaselib/klib/kintrusivelist.h> #include <fbxfilesdk/kfbxevents/kfbxemitter.h> #include <fbxfilesdk/kfbxevents/kfbxlistener.h> // FBX begin namespace #include <fbxfilesdk/fbxfilesdk_nsbegin.h> // Forward declaration class KFbxSdkManager; ///////////////////////////////////////////////////////////////////////////////////////// // TODO: todonamespace // Every FBX module should have a namespace but for consistency, // you have, for this version of fbx, to use the fbx object without namespace //namespace kfbxmodules //{ // Forward declaration class KFbxLoadingStrategy; class KFbxPluginContainer; #define KFBXPLUGIN_DECLARE(Plugin)\ public:\ static Plugin* Create( const KFbxPluginDefinition& pDefinition );\ void Destroy(); #define KFBXPLUGIN_IMPLEMENT(Plugin)\ Plugin* Plugin::Create( const KFbxPluginDefinition& pDefinition )\ {\ return new Plugin( pDefinition );\ }\ void Plugin::Destroy()\ {\ delete this;\ } /** \class KFbxPluginDefinition * * \brief Plug-in defines itself by filling this structure * */ struct KFBX_DLL KFbxPluginDefinition { KFbxPluginDefinition():mName("Unknown Name"),mVersion("Unknown Version"){} KString mName; KString mVersion; }; /** \class KFbxPluginData * * \brief Data used to communicate information between an application and a plug-in * */ struct KFBX_DLL KFbxPluginData { KFbxPluginData():mQueryEmitter(0),mSDKManager(0),mPluginContainer(0){} explicit KFbxPluginData(const KFbxPluginData& r):mQueryEmitter(r.mQueryEmitter),mSDKManager(r.mSDKManager),mPluginContainer(r.mPluginContainer){} KFbxSdkManager* mSDKManager; // (Optional) SDK manager to which the plug-in can register custom types KFbxPluginContainer* mPluginContainer; // (Optional) Container which will have the ownership of the plug-in kfbxevents::KFbxEmitter* mQueryEmitter; // (Optional) The plug-in can listen to this query emitter }; /** \class KFbxPlugin * * \brief Abstract class used to implement plug-ins. * */ class KFBX_DLL KFbxPlugin : public kfbxevents::KFbxListener { KFBX_LISTNODE(KFbxPlugin,1); public: /** *\name Public interface */ //@{ /** const accessor to the plug-in definition. Plug-in definition contains basic information on the plug-in like its name or version. * \return The definition for the current plug-in */ inline const KFbxPluginDefinition& GetDefinition()const; virtual void Destroy() = 0; inline KFbxObject& GetPluginSettings() { return *(mPluginSettings.Get()); } inline const KFbxObject& GetPluginSettings() const { return *(mPluginSettings.Get()); } //@} protected: /** Constructor * Use the Create() and Destroy() methods declared and implemented in the * KFBXPLUGIN_DECLARE and KFBXPLUGIN_IMPLEMENT macros to construct and destroy * KFbxPlugin objects. * \param pDefinition */ explicit KFbxPlugin(const KFbxPluginDefinition& pDefinition); /** Accessor to the plug-in data. * \return The data for the current plug-in */ inline KFbxPluginData& GetData(); /** const accessor to the plug-in data. * \return The const data for the current plug-in */ inline const KFbxPluginData& GetData()const; private: bool mInitialized; KFbxPluginData mData; KFbxPluginDefinition mDefinition; public: /** *\name User implementation */ //@{ /** Method called after plug-in construction. At that moment, plug-in data have been properly * initialized. This is where the user implementation do their initialization routines */ virtual bool SpecificInitialize() = 0; /** Method called before plug-in destruction. * This is where the user implementation do their uninitialization routines */ virtual bool SpecificTerminate() = 0; //@} virtual bool NeedReadWrite(){ return false; } virtual void WriteBegin(KFbxScene& pScene){} virtual void WriteSettings(KFbxObject& pSettings){} virtual void WriteEnd(KFbxScene& pScene){} virtual void ReadBegin(KFbxScene& pScene){} virtual void ReadSettings(KFbxObject& pSettings){} virtual void ReadEnd(KFbxScene& pScene){} /** *\name Event registration */ //@{ template <typename EventType,typename ListernerType> inline KFbxEventHandler* Bind(void (ListernerType::*pFunc)(const EventType*)) { return KFbxListener::Bind<EventType,ListernerType>(*(GetData().mQueryEmitter), pFunc ); } private: /////////////////////////////////////////////////////////////////////////////// // // WARNING! // // Anything beyond these lines may not be documented accurately and is // subject to change without notice. // /////////////////////////////////////////////////////////////////////////////// #ifndef DOXYGEN_SHOULD_SKIP_THIS friend class KFbxLoadingStrategy; bool Initialize(const KFbxPluginData& pData); bool Terminate(); KFBXObjectScopedPtr<KFbxObject> mPluginSettings; #endif }; ///////////////////////////////////////////////////////////////////////////////////////////// inline const KFbxPluginDefinition& KFbxPlugin::GetDefinition()const{ return mDefinition; } ///////////////////////////////////////////////////////////////////////////////////////////// inline KFbxPluginData& KFbxPlugin::GetData(){ return mData; } ///////////////////////////////////////////////////////////////////////////////////////////// inline const KFbxPluginData& KFbxPlugin::GetData()const{ return mData; } //} // FBX end namespace #include <fbxfilesdk/fbxfilesdk_nsend.h> #endif // FBXFILESDK_KFBXMODULES_KFBXPLUGIN_H
d4965f49f8f77fc55381cbdd52632cffcc3b127c
e8bd2e42949f26afc319d6573ce84dcc1703ba5d
/src/Buff.cpp
c1a7cd0b50218d9513e9e70016745a77b91a7c17
[]
no_license
mxmanseven/YoYoDaq
c1c47df879b6b79878b9567e724e09f9f5042c14
fc4d33de9c771e1682da1f42a3a38ba6c29ac905
refs/heads/master
2023-04-19T04:42:13.868578
2021-04-30T23:00:35
2021-04-30T23:00:35
253,975,193
0
0
null
null
null
null
UTF-8
C++
false
false
2,568
cpp
Buff.cpp
#include "Buff.h" String SampleToString(Sample sample) { return String(sample.mills) + "\t" + String(sample.sample) + "\r\n"; } Buff::Buff() { aHead = 0; aTail = 0; aIsFull = false; bHead = 0; bTail = 0; bIsFull = false; } int Buff::Push(Sample value, bool& isFull) { lastSample = value; int result = 0; if (!aIsFull && aHead < buffSize) { aBuff[aHead++] = value; if(aHead == buffSize) { aIsFull = true; isFull = true; aHead = 0; aTail = 0; } } else if (!bIsFull && bHead < buffSize) { bBuff[bHead++] = value; if(bHead == buffSize) { bIsFull = true; isFull = true; bHead = 0; bTail = 0; } } else { isFull = true; result = -1; } return result; } Sample Buff::GetNext(bool& isMore) { isMore = false; Sample value; if (aIsFull) { value = aBuff[aTail++]; if (aTail == buffSize) { aIsFull = false; aHead = 0; aTail = 0; } else { isMore = true; } } else if (bIsFull) { value = bBuff[bTail++]; if (bTail == buffSize) { bIsFull = false; bHead = 0; bTail = 0; } else { isMore = true; } } return value; } void Buff::ZeroOut() { Sample value; value.mills = 0; value.sample = 0; lastSample = value; aHead = 0; aTail = 0; aIsFull = false; bHead = 0; bTail = 0; bIsFull = false; // maybe i don not need to zero out the array if the pointers (ahead, atail...) // are zerowed. // for (int i = 0; i < buffSize; i++) { // aBuff[i] = // } } // set loop count to many times buff size to exercise // moving between buffers. // Should print out numbers 1 to loop count. void Buff::Test() { Buff buff; Serial.println("Buff Test"); for(int i = 0; i < 100; i++) { Sample sample; sample.mills = i; sample.sample = -1 * i; bool isFull = false; buff.Push(sample, isFull); if (isFull) { bool isMore = true; while (isMore) { sample = buff.GetNext(isMore); Serial.println(String(sample.mills)); } } } }
6fbfc34fc4cdecceb0e5628d5ad16aa709171bc8
651c85f8d1b2fe0d19caccfa1446bc0bc8766a93
/src/app_thread.cpp
b9ed0901af87650e13c2e555c88ddaa2837271cc
[]
no_license
AlexMax/lyirc
7a4bba18beeacabbd26a9f9890558a26074b5d8c
68da2d1406523e6717b4ee87ab504e86223b20fb
refs/heads/master
2021-05-07T06:26:19.042447
2017-11-23T03:41:01
2017-11-23T03:41:01
111,758,665
0
0
null
null
null
null
UTF-8
C++
false
false
517
cpp
app_thread.cpp
#include "app_thread.h" #include <asio.hpp> AppThread::ExitCode AppThread::Entry() { asio::io_service service; // Resolve an IRC server asio::ip::tcp::resolver resolver(service); asio::ip::tcp::resolver::query query("irc.zandronum.com", "6667"); resolver.async_resolve(query, [](auto error, auto it) { // Connect to the IRC server asio::ip::tcp::socket socket(service); asio::async_connect(socket, it, [auto error, auto it]() { }); }); return 0; }
911972af03a968f3f0abc46de3872769a70869be
8b4de051ad8c265d36433f795fb98b388495e9d4
/Stratum/StSerialization/JsonSpaceItem2dSerializer.cpp
c82ecfcd9d8113999638e5a4c07d6dc16b37ad12
[]
no_license
RamizJ/Stratum
138494d1915873b606ebf1f50bdb34715f64f12b
e392ba9455efe8d1624d2a14a9a89038113433c1
refs/heads/master
2022-12-10T05:21:13.967757
2020-08-21T20:57:37
2020-08-21T20:57:37
289,362,616
1
0
null
null
null
null
UTF-8
C++
false
false
2,192
cpp
JsonSpaceItem2dSerializer.cpp
#include "JsonSpaceItem2dSerializer.h" #include <SpaceItem.h> using namespace StData; namespace StSerialization { JsonSpaceItem2dSerializer::JsonSpaceItem2dSerializer() : JsonSpaceItemSerializer() {} QJsonObject JsonSpaceItem2dSerializer::serialize(SpaceItem2d* spaceItem2d) { QJsonObject result = JsonSpaceItemSerializer::serialize(spaceItem2d); QPointF origin = spaceItem2d->origin(); QSizeF size = spaceItem2d->size(); result[KEY_SPACEITEM2D_ORIGIN] = pointToString(origin); result[KEY_SPACEITEM2D_SIZE] = sizeToString(size); result[KEY_SPACEITEM2D_ANGLE] = spaceItem2d->angle(); return result; } void JsonSpaceItem2dSerializer::deserialize(const QJsonObject& itemData, SpaceItem2d* spaceItem2d) { if(spaceItem2d == nullptr || itemData.isEmpty()) return; JsonSpaceItemSerializer::deserialize(itemData, spaceItem2d); QString originData = itemData.value(KEY_SPACEITEM2D_ORIGIN).toString(); QString sizeData = itemData.value(KEY_SPACEITEM2D_SIZE).toString(); QList<QString> coords = originData.split(';', QString::SkipEmptyParts); double x = coords.at(0).toDouble(); double y = coords.at(1).toDouble(); QList<QString> sizeParams = sizeData.split(';', QString::SkipEmptyParts); double w = sizeParams.at(0).toDouble(); double h = sizeParams.at(1).toDouble(); spaceItem2d->setOrigin(QPointF(x, y)); spaceItem2d->setSize(QSizeF(w, h)); } QString JsonSpaceItem2dSerializer::pointToString(const QPointF& p) { return QString("%1;%2").arg(p.x()).arg(p.y()); } QString JsonSpaceItem2dSerializer::sizeToString(const QSizeF& s) { return QString("%1;%2").arg(s.width()).arg(s.height()); } QPointF JsonSpaceItem2dSerializer::pointFromString(const QString& str) { QList<QString> xy = str.split(';', QString::SkipEmptyParts); if(xy.length() == 2) return QPointF(xy.at(0).toDouble(), xy.at(1).toDouble()); return QPointF(); } QSizeF JsonSpaceItem2dSerializer::sizeFromString(const QString& str) { QList<QString> wh = str.split(';', QString::SkipEmptyParts); if(wh.length() == 2) return QSizeF(wh.at(0).toDouble(), wh.at(1).toDouble()); return QSizeF(); } }
3d1ad0be00ed7bcead12eec4687a1db15cdaabb0
7e48d392300fbc123396c6a517dfe8ed1ea7179f
/RodentVR/Intermediate/Build/Win64/RodentVR/Inc/Engine/CurveLinearColorAtlas.gen.cpp
2ac0e9a5bad4e5d9ad035a076fc54068eac157ec
[]
no_license
WestRyanK/Rodent-VR
f4920071b716df6a006b15c132bc72d3b0cba002
2033946f197a07b8c851b9a5075f0cb276033af6
refs/heads/master
2021-06-14T18:33:22.141793
2020-10-27T03:25:33
2020-10-27T03:25:33
154,956,842
1
1
null
2018-11-29T09:56:21
2018-10-27T11:23:11
C++
UTF-8
C++
false
false
13,742
cpp
CurveLinearColorAtlas.gen.cpp
// Copyright Epic Games, Inc. All Rights Reserved. /*=========================================================================== Generated code exported from UnrealHeaderTool. DO NOT modify this manually! Edit the corresponding .h files instead! ===========================================================================*/ #include "UObject/GeneratedCppIncludes.h" #include "Engine/Classes/Curves/CurveLinearColorAtlas.h" #ifdef _MSC_VER #pragma warning (push) #pragma warning (disable : 4883) #endif PRAGMA_DISABLE_DEPRECATION_WARNINGS void EmptyLinkFunctionForGeneratedCodeCurveLinearColorAtlas() {} // Cross Module References ENGINE_API UClass* Z_Construct_UClass_UCurveLinearColorAtlas_NoRegister(); ENGINE_API UClass* Z_Construct_UClass_UCurveLinearColorAtlas(); ENGINE_API UClass* Z_Construct_UClass_UTexture2D(); UPackage* Z_Construct_UPackage__Script_Engine(); ENGINE_API UClass* Z_Construct_UClass_UCurveLinearColor_NoRegister(); // End Cross Module References DEFINE_FUNCTION(UCurveLinearColorAtlas::execGetCurvePosition) { P_GET_OBJECT(UCurveLinearColor,Z_Param_InCurve); P_GET_PROPERTY_REF(FFloatProperty,Z_Param_Out_Position); P_FINISH; P_NATIVE_BEGIN; *(bool*)Z_Param__Result=P_THIS->GetCurvePosition(Z_Param_InCurve,Z_Param_Out_Position); P_NATIVE_END; } void UCurveLinearColorAtlas::StaticRegisterNativesUCurveLinearColorAtlas() { UClass* Class = UCurveLinearColorAtlas::StaticClass(); static const FNameNativePtrPair Funcs[] = { { "GetCurvePosition", &UCurveLinearColorAtlas::execGetCurvePosition }, }; FNativeFunctionRegistrar::RegisterFunctions(Class, Funcs, UE_ARRAY_COUNT(Funcs)); } struct Z_Construct_UFunction_UCurveLinearColorAtlas_GetCurvePosition_Statics { struct CurveLinearColorAtlas_eventGetCurvePosition_Parms { UCurveLinearColor* InCurve; float Position; bool ReturnValue; }; static void NewProp_ReturnValue_SetBit(void* Obj); static const UE4CodeGen_Private::FBoolPropertyParams NewProp_ReturnValue; static const UE4CodeGen_Private::FFloatPropertyParams NewProp_Position; static const UE4CodeGen_Private::FObjectPropertyParams NewProp_InCurve; static const UE4CodeGen_Private::FPropertyParamsBase* const PropPointers[]; #if WITH_METADATA static const UE4CodeGen_Private::FMetaDataPairParam Function_MetaDataParams[]; #endif static const UE4CodeGen_Private::FFunctionParams FuncParams; }; void Z_Construct_UFunction_UCurveLinearColorAtlas_GetCurvePosition_Statics::NewProp_ReturnValue_SetBit(void* Obj) { ((CurveLinearColorAtlas_eventGetCurvePosition_Parms*)Obj)->ReturnValue = 1; } const UE4CodeGen_Private::FBoolPropertyParams Z_Construct_UFunction_UCurveLinearColorAtlas_GetCurvePosition_Statics::NewProp_ReturnValue = { "ReturnValue", nullptr, (EPropertyFlags)0x0010000000000580, UE4CodeGen_Private::EPropertyGenFlags::Bool | UE4CodeGen_Private::EPropertyGenFlags::NativeBool, RF_Public|RF_Transient|RF_MarkAsNative, 1, sizeof(bool), sizeof(CurveLinearColorAtlas_eventGetCurvePosition_Parms), &Z_Construct_UFunction_UCurveLinearColorAtlas_GetCurvePosition_Statics::NewProp_ReturnValue_SetBit, METADATA_PARAMS(nullptr, 0) }; const UE4CodeGen_Private::FFloatPropertyParams Z_Construct_UFunction_UCurveLinearColorAtlas_GetCurvePosition_Statics::NewProp_Position = { "Position", nullptr, (EPropertyFlags)0x0010000000000180, UE4CodeGen_Private::EPropertyGenFlags::Float, RF_Public|RF_Transient|RF_MarkAsNative, 1, STRUCT_OFFSET(CurveLinearColorAtlas_eventGetCurvePosition_Parms, Position), METADATA_PARAMS(nullptr, 0) }; const UE4CodeGen_Private::FObjectPropertyParams Z_Construct_UFunction_UCurveLinearColorAtlas_GetCurvePosition_Statics::NewProp_InCurve = { "InCurve", nullptr, (EPropertyFlags)0x0010000000000080, UE4CodeGen_Private::EPropertyGenFlags::Object, RF_Public|RF_Transient|RF_MarkAsNative, 1, STRUCT_OFFSET(CurveLinearColorAtlas_eventGetCurvePosition_Parms, InCurve), Z_Construct_UClass_UCurveLinearColor_NoRegister, METADATA_PARAMS(nullptr, 0) }; const UE4CodeGen_Private::FPropertyParamsBase* const Z_Construct_UFunction_UCurveLinearColorAtlas_GetCurvePosition_Statics::PropPointers[] = { (const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UFunction_UCurveLinearColorAtlas_GetCurvePosition_Statics::NewProp_ReturnValue, (const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UFunction_UCurveLinearColorAtlas_GetCurvePosition_Statics::NewProp_Position, (const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UFunction_UCurveLinearColorAtlas_GetCurvePosition_Statics::NewProp_InCurve, }; #if WITH_METADATA const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UFunction_UCurveLinearColorAtlas_GetCurvePosition_Statics::Function_MetaDataParams[] = { { "Category", "Math|Curves" }, { "ModuleRelativePath", "Classes/Curves/CurveLinearColorAtlas.h" }, }; #endif const UE4CodeGen_Private::FFunctionParams Z_Construct_UFunction_UCurveLinearColorAtlas_GetCurvePosition_Statics::FuncParams = { (UObject*(*)())Z_Construct_UClass_UCurveLinearColorAtlas, nullptr, "GetCurvePosition", nullptr, nullptr, sizeof(CurveLinearColorAtlas_eventGetCurvePosition_Parms), Z_Construct_UFunction_UCurveLinearColorAtlas_GetCurvePosition_Statics::PropPointers, UE_ARRAY_COUNT(Z_Construct_UFunction_UCurveLinearColorAtlas_GetCurvePosition_Statics::PropPointers), RF_Public|RF_Transient|RF_MarkAsNative, (EFunctionFlags)0x04420401, 0, 0, METADATA_PARAMS(Z_Construct_UFunction_UCurveLinearColorAtlas_GetCurvePosition_Statics::Function_MetaDataParams, UE_ARRAY_COUNT(Z_Construct_UFunction_UCurveLinearColorAtlas_GetCurvePosition_Statics::Function_MetaDataParams)) }; UFunction* Z_Construct_UFunction_UCurveLinearColorAtlas_GetCurvePosition() { static UFunction* ReturnFunction = nullptr; if (!ReturnFunction) { UE4CodeGen_Private::ConstructUFunction(ReturnFunction, Z_Construct_UFunction_UCurveLinearColorAtlas_GetCurvePosition_Statics::FuncParams); } return ReturnFunction; } UClass* Z_Construct_UClass_UCurveLinearColorAtlas_NoRegister() { return UCurveLinearColorAtlas::StaticClass(); } struct Z_Construct_UClass_UCurveLinearColorAtlas_Statics { static UObject* (*const DependentSingletons[])(); static const FClassFunctionLinkInfo FuncInfo[]; #if WITH_METADATA static const UE4CodeGen_Private::FMetaDataPairParam Class_MetaDataParams[]; #endif #if WITH_METADATA static const UE4CodeGen_Private::FMetaDataPairParam NewProp_GradientCurves_MetaData[]; #endif static const UE4CodeGen_Private::FArrayPropertyParams NewProp_GradientCurves; static const UE4CodeGen_Private::FObjectPropertyParams NewProp_GradientCurves_Inner; #if WITH_METADATA static const UE4CodeGen_Private::FMetaDataPairParam NewProp_TextureSize_MetaData[]; #endif static const UE4CodeGen_Private::FUInt32PropertyParams NewProp_TextureSize; #if WITH_EDITORONLY_DATA #if WITH_METADATA static const UE4CodeGen_Private::FMetaDataPairParam NewProp_bIsDirty_MetaData[]; #endif static void NewProp_bIsDirty_SetBit(void* Obj); static const UE4CodeGen_Private::FBoolPropertyParams NewProp_bIsDirty; #endif // WITH_EDITORONLY_DATA static const UE4CodeGen_Private::FPropertyParamsBase* const PropPointers[]; #if WITH_EDITORONLY_DATA #endif // WITH_EDITORONLY_DATA static const FCppClassTypeInfoStatic StaticCppClassTypeInfo; static const UE4CodeGen_Private::FClassParams ClassParams; }; UObject* (*const Z_Construct_UClass_UCurveLinearColorAtlas_Statics::DependentSingletons[])() = { (UObject* (*)())Z_Construct_UClass_UTexture2D, (UObject* (*)())Z_Construct_UPackage__Script_Engine, }; const FClassFunctionLinkInfo Z_Construct_UClass_UCurveLinearColorAtlas_Statics::FuncInfo[] = { { &Z_Construct_UFunction_UCurveLinearColorAtlas_GetCurvePosition, "GetCurvePosition" }, // 631513191 }; #if WITH_METADATA const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UClass_UCurveLinearColorAtlas_Statics::Class_MetaDataParams[] = { { "Comment", "/**\n* Manages gradient LUT textures for registered actors and assigns them to the corresponding materials on the actor\n*/" }, { "HideCategories", "Object" }, { "IncludePath", "Curves/CurveLinearColorAtlas.h" }, { "ModuleRelativePath", "Classes/Curves/CurveLinearColorAtlas.h" }, { "ToolTip", "Manages gradient LUT textures for registered actors and assigns them to the corresponding materials on the actor" }, }; #endif #if WITH_METADATA const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UClass_UCurveLinearColorAtlas_Statics::NewProp_GradientCurves_MetaData[] = { { "Category", "Curves" }, { "Comment", "// Size of the lookup textures\n" }, { "ModuleRelativePath", "Classes/Curves/CurveLinearColorAtlas.h" }, { "ToolTip", "Size of the lookup textures" }, }; #endif const UE4CodeGen_Private::FArrayPropertyParams Z_Construct_UClass_UCurveLinearColorAtlas_Statics::NewProp_GradientCurves = { "GradientCurves", nullptr, (EPropertyFlags)0x0010000000000001, UE4CodeGen_Private::EPropertyGenFlags::Array, RF_Public|RF_Transient|RF_MarkAsNative, 1, STRUCT_OFFSET(UCurveLinearColorAtlas, GradientCurves), EArrayPropertyFlags::None, METADATA_PARAMS(Z_Construct_UClass_UCurveLinearColorAtlas_Statics::NewProp_GradientCurves_MetaData, UE_ARRAY_COUNT(Z_Construct_UClass_UCurveLinearColorAtlas_Statics::NewProp_GradientCurves_MetaData)) }; const UE4CodeGen_Private::FObjectPropertyParams Z_Construct_UClass_UCurveLinearColorAtlas_Statics::NewProp_GradientCurves_Inner = { "GradientCurves", nullptr, (EPropertyFlags)0x0000000000000000, UE4CodeGen_Private::EPropertyGenFlags::Object, RF_Public|RF_Transient|RF_MarkAsNative, 1, 0, Z_Construct_UClass_UCurveLinearColor_NoRegister, METADATA_PARAMS(nullptr, 0) }; #if WITH_METADATA const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UClass_UCurveLinearColorAtlas_Statics::NewProp_TextureSize_MetaData[] = { { "Category", "Curves" }, { "ModuleRelativePath", "Classes/Curves/CurveLinearColorAtlas.h" }, }; #endif const UE4CodeGen_Private::FUInt32PropertyParams Z_Construct_UClass_UCurveLinearColorAtlas_Statics::NewProp_TextureSize = { "TextureSize", nullptr, (EPropertyFlags)0x0010000000000001, UE4CodeGen_Private::EPropertyGenFlags::UInt32, RF_Public|RF_Transient|RF_MarkAsNative, 1, STRUCT_OFFSET(UCurveLinearColorAtlas, TextureSize), METADATA_PARAMS(Z_Construct_UClass_UCurveLinearColorAtlas_Statics::NewProp_TextureSize_MetaData, UE_ARRAY_COUNT(Z_Construct_UClass_UCurveLinearColorAtlas_Statics::NewProp_TextureSize_MetaData)) }; #if WITH_EDITORONLY_DATA #if WITH_METADATA const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UClass_UCurveLinearColorAtlas_Statics::NewProp_bIsDirty_MetaData[] = { { "ModuleRelativePath", "Classes/Curves/CurveLinearColorAtlas.h" }, }; #endif void Z_Construct_UClass_UCurveLinearColorAtlas_Statics::NewProp_bIsDirty_SetBit(void* Obj) { ((UCurveLinearColorAtlas*)Obj)->bIsDirty = 1; } const UE4CodeGen_Private::FBoolPropertyParams Z_Construct_UClass_UCurveLinearColorAtlas_Statics::NewProp_bIsDirty = { "bIsDirty", nullptr, (EPropertyFlags)0x0010000800000000, UE4CodeGen_Private::EPropertyGenFlags::Bool , RF_Public|RF_Transient|RF_MarkAsNative, 1, sizeof(uint8), sizeof(UCurveLinearColorAtlas), &Z_Construct_UClass_UCurveLinearColorAtlas_Statics::NewProp_bIsDirty_SetBit, METADATA_PARAMS(Z_Construct_UClass_UCurveLinearColorAtlas_Statics::NewProp_bIsDirty_MetaData, UE_ARRAY_COUNT(Z_Construct_UClass_UCurveLinearColorAtlas_Statics::NewProp_bIsDirty_MetaData)) }; #endif // WITH_EDITORONLY_DATA const UE4CodeGen_Private::FPropertyParamsBase* const Z_Construct_UClass_UCurveLinearColorAtlas_Statics::PropPointers[] = { (const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UClass_UCurveLinearColorAtlas_Statics::NewProp_GradientCurves, (const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UClass_UCurveLinearColorAtlas_Statics::NewProp_GradientCurves_Inner, (const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UClass_UCurveLinearColorAtlas_Statics::NewProp_TextureSize, #if WITH_EDITORONLY_DATA (const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UClass_UCurveLinearColorAtlas_Statics::NewProp_bIsDirty, #endif // WITH_EDITORONLY_DATA }; const FCppClassTypeInfoStatic Z_Construct_UClass_UCurveLinearColorAtlas_Statics::StaticCppClassTypeInfo = { TCppClassTypeTraits<UCurveLinearColorAtlas>::IsAbstract, }; const UE4CodeGen_Private::FClassParams Z_Construct_UClass_UCurveLinearColorAtlas_Statics::ClassParams = { &UCurveLinearColorAtlas::StaticClass, nullptr, &StaticCppClassTypeInfo, DependentSingletons, FuncInfo, Z_Construct_UClass_UCurveLinearColorAtlas_Statics::PropPointers, nullptr, UE_ARRAY_COUNT(DependentSingletons), UE_ARRAY_COUNT(FuncInfo), UE_ARRAY_COUNT(Z_Construct_UClass_UCurveLinearColorAtlas_Statics::PropPointers), 0, 0x009000A0u, METADATA_PARAMS(Z_Construct_UClass_UCurveLinearColorAtlas_Statics::Class_MetaDataParams, UE_ARRAY_COUNT(Z_Construct_UClass_UCurveLinearColorAtlas_Statics::Class_MetaDataParams)) }; UClass* Z_Construct_UClass_UCurveLinearColorAtlas() { static UClass* OuterClass = nullptr; if (!OuterClass) { UE4CodeGen_Private::ConstructUClass(OuterClass, Z_Construct_UClass_UCurveLinearColorAtlas_Statics::ClassParams); } return OuterClass; } IMPLEMENT_CLASS(UCurveLinearColorAtlas, 2561278045); template<> ENGINE_API UClass* StaticClass<UCurveLinearColorAtlas>() { return UCurveLinearColorAtlas::StaticClass(); } static FCompiledInDefer Z_CompiledInDefer_UClass_UCurveLinearColorAtlas(Z_Construct_UClass_UCurveLinearColorAtlas, &UCurveLinearColorAtlas::StaticClass, TEXT("/Script/Engine"), TEXT("UCurveLinearColorAtlas"), false, nullptr, nullptr, nullptr); DEFINE_VTABLE_PTR_HELPER_CTOR(UCurveLinearColorAtlas); PRAGMA_ENABLE_DEPRECATION_WARNINGS #ifdef _MSC_VER #pragma warning (pop) #endif
dbcdc83d19d3cf942c0ae7e66dc9a4fd5bcbd1be
f84a306a523cce262c5e6a8347046dc9c71cd9bb
/com/mainwindow.h
b07bfca1a26ad15ed356055c173b68c4cb8afc79
[]
no_license
zhangjingbo123/Qt_Uart
bd9ffd80402ed6348495834447194f8913808760
60b3b158d09db8943851ef8c9aa29731f0440ef3
refs/heads/master
2023-02-24T22:53:08.301836
2021-01-31T03:32:54
2021-01-31T03:32:54
334,559,246
0
0
null
null
null
null
UTF-8
C++
false
false
1,346
h
mainwindow.h
#ifndef MAINWINDOW_H #define MAINWINDOW_H #include <QMainWindow> #include <QTimer> //定时器相关库 #include <QMovie> #include <QSerialPort> //提供访问串口的功能 #include <QSerialPortInfo> //提供系统中存在的串口的信息 #include <advanced.h> #include "database.h" namespace Ui { class MainWindow; } class MainWindow : public QMainWindow { Q_OBJECT public: explicit MainWindow(QWidget *parent = 0); ~MainWindow(); void WindowInit(); void Serial_start(); public slots: void Check_Serial_Dynamic(); void Update_Com_Serial(QStringList); void on_OpenCom_clicked(); void on_ClearRX_clicked(); void on_clearsend_clicked(); void on_senddata_clicked(); void on_AdvancedOpen_clicked(); void Upate_ComPara(ComPara_t); void Update_ComSum(QString); void ChangeBD(); void DecideToAddTime(int); void DecideToChange16(int); private: Ui::MainWindow *ui; QStringList oldPortStringList; QSerialPort serial; int AddTimeFlag; int ToChange16; QTimer *TimeSerial = new QTimer; QMovie *movie = new QMovie("I:/com/gif/dance.gif"); Advanced *advanced; void serialPort_readyRead(); struct ComPara_t OldComPara; DataBase database; signals: void onNewSerialPort(QStringList); }; #endif // MAINWINDOW_H
309767d10331ca6be8722f7b7ac346ebfb72ef56
6b550d3d0b182bcddda1f0a175d6b6cd07b60fb3
/logdevice/server/admincommands/InfoGossip.h
617014a8e22336180614c2f8681195cc3b03dc20
[ "BSD-3-Clause" ]
permissive
Rachelmorrell/LogDevice
5bd04f7ab0bdf9cc6e5b2da4a4b51210cdc9a4c8
3a8d800033fada47d878b64533afdf41dc79e057
refs/heads/master
2021-06-24T09:10:20.240011
2020-04-21T14:10:52
2020-04-21T14:13:09
157,563,026
1
0
NOASSERTION
2020-04-21T19:20:55
2018-11-14T14:43:33
C++
UTF-8
C++
false
false
4,812
h
InfoGossip.h
/** * Copyright (c) 2017-present, Facebook, Inc. and its affiliates. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. */ #pragma once #include <folly/json.h> #include "logdevice/common/NodeID.h" #include "logdevice/server/FailureDetector.h" #include "logdevice/server/admincommands/AdminCommand.h" namespace facebook { namespace logdevice { namespace commands { class InfoGossip : public AdminCommand { using AdminCommand::AdminCommand; private: node_index_t node_idx_{-1}; bool json_{false}; public: void getOptions(boost::program_options::options_description& opts) override { opts.add_options()( "node-idx", boost::program_options::value<node_index_t>(&node_idx_)); opts.add_options()("json", boost::program_options::bool_switch(&json_)); } void getPositionalOptions( boost::program_options::positional_options_description& opts) override { opts.add("node-idx", 1); } std::string getUsage() override { return "info gossip [--json] [node idx]"; } void run() override { if (json_) { printJson(); } else { printPretty(); } } void printJson() { auto serialized = folly::json::serialize( composeJson(), folly::json::serialization_opts()); out_.printf("%s", serialized.c_str()); out_.printf("\r\n"); } folly::dynamic composeJson() { folly::dynamic obj = folly::dynamic::object; auto detector = server_->getServerProcessor()->failure_detector_.get(); if (detector == nullptr) { obj["error"] = "Failure detector not used."; return obj; } const auto& nodes_configuration = server_->getProcessor()->getNodesConfiguration(); node_index_t lo = 0; node_index_t hi = nodes_configuration->getMaxNodeIndex(); if (node_idx_ != node_index_t(-1)) { if (node_idx_ > hi) { obj["error"] = folly::sformat( "Node index expected to be in the [0, %u] range", hi); return obj; } lo = hi = node_idx_; } auto cs = server_->getProcessor()->cluster_state_.get(); auto& states = obj["states"] = folly::dynamic::array; for (node_index_t idx = lo; idx <= hi; ++idx) { if (!nodes_configuration->isNodeInServiceDiscoveryConfig(idx)) { continue; } folly::dynamic row = folly::dynamic::object; row["node_id"] = folly::sformat("N{}", idx); row["status"] = cs->isNodeAlive(idx) ? "ALIVE" : "DEAD"; row["detector"] = detector->getStateJson(idx); row["boycott_status"] = cs->isNodeBoycotted(idx) ? "BOYCOTTED" : "-"; row["health_status"] = toString(cs->getNodeStatus(idx)).c_str(); states.push_back(row); } if (node_idx_ == node_index_t(-1)) { // print domain isolation status in case "info gossip" is issued // without index obj["domain_isolation"] = detector->getDomainIsolationString().c_str(); // print current ISOLATION value obj["isolated"] = detector->isIsolated() ? "true" : "false"; obj["stable_state"] = detector->isStableState() ? "true" : "false"; } return obj; } void printPretty() { auto detector = server_->getServerProcessor()->failure_detector_.get(); if (detector == nullptr) { out_.printf("Failure detector not used.\r\n"); return; } const auto& nodes_configuration = server_->getProcessor()->getNodesConfiguration(); node_index_t lo = 0; node_index_t hi = nodes_configuration->getMaxNodeIndex(); if (node_idx_ != node_index_t(-1)) { if (node_idx_ > hi) { out_.printf("Node index expected to be in the [0, %u] range\r\n", hi); return; } lo = hi = node_idx_; } auto cs = server_->getProcessor()->cluster_state_.get(); for (node_index_t idx = lo; idx <= hi; ++idx) { if (!nodes_configuration->isNodeInServiceDiscoveryConfig(idx)) { continue; } out_.printf("GOSSIP N%u %s %s %s %s\r\n", idx, cs->isNodeAlive(idx) ? "ALIVE" : "DEAD", detector->getStateString(idx).c_str(), cs->isNodeBoycotted(idx) ? "BOYCOTTED" : "-", toString(cs->getNodeStatus(idx)).c_str()); } if (node_idx_ == node_index_t(-1)) { // print domain isolation status in case "info gossip" is issued // without index out_.printf("%s", detector->getDomainIsolationString().c_str()); // print current ISOLATION value out_.printf("ISOLATED %s\r\n", detector->isIsolated() ? "true" : "false"); out_.printf( "STABLE_STATE %s\r\n", detector->isStableState() ? "true" : "false"); } } }; }}} // namespace facebook::logdevice::commands
56fd5317ffc87912c66b36a58849591ba9d5e25a
d328d1aea80afd6599020542a97d5291dd40405d
/include/Core/Bindings/obe/Audio/Exceptions/Exceptions.hpp
3b765608a6d1c1125e52988a6d9f34801afabafe
[ "MIT", "BSD-2-Clause", "Zlib" ]
permissive
PierrickLP/ObEngine
69a73cca18f66c724744d8303eaf0020574a88c3
337ad3c62e66e9cf71876c277692216edfe58493
refs/heads/master
2022-12-24T09:55:40.074207
2020-10-07T15:03:34
2020-10-07T15:03:34
106,604,958
1
0
MIT
2019-10-02T16:04:53
2017-10-11T20:19:50
C++
UTF-8
C++
false
false
171
hpp
Exceptions.hpp
#pragma once namespace sol { class state_view; }; namespace obe::Audio::Exceptions::Bindings { void LoadClassAudioFileNotFound(sol::state_view state); };
5e0b43532bdb6b3fce2b304acaf096c8f08431cc
3be55f50f2fafe702f862d194cf6399db42d6e5e
/Program 3/Tree.cpp
ab40ccf42bbc9c9db6dccdc9da02676dd861f6bd
[]
no_license
xcaracal/CS14
46cb5857543ff25c08d3d08343eb24ce53caf2d6
502c23218e5597a2dafac3049873864107c6d466
refs/heads/master
2021-03-13T18:54:45.598276
2020-04-08T06:28:49
2020-04-08T06:28:49
246,701,919
0
1
null
null
null
null
UTF-8
C++
false
false
21,590
cpp
Tree.cpp
// // Created by hoang on 2/23/2020. // #include <string> #include <iostream> #include "Tree.h" //public: Tree::Tree() { root = nullptr; } Tree::~Tree() { destruct(root); } void Tree::insert(const string& data) { if (root == nullptr) { root = new Node(data); return; } if (search(data)) { return; } Node* curr = root; while (true) { //if no children if (curr->left == nullptr && curr->middle == nullptr && curr->right == nullptr) { //if node only has one item fix. if (curr->large.empty()) { if (data > curr->small) { curr->large = data; } else { curr->large = curr->small; curr->small = data; } //full node } else { split(curr, data, nullptr, nullptr); } return; } //has children else { if (data < curr->small) { curr = curr->left; //if 3 node } else if (!(curr->large.empty())) { if (data < curr->large) { curr = curr->middle; } else if (data > curr->large) { curr = curr->right; } } //2 node else if (data > curr->large) { curr = curr->right; } } } } void Tree::preOrder() const { preOrder(root); cout << endl; } void Tree::inOrder() const { inOrder(root); cout << endl; } void Tree::postOrder() const { postOrder(root); cout << endl; } void Tree::remove(const string& key) { //not found if (!search(key)) { return; } Node* curr = search(root, key); Node* swap = curr; //find the successor to find the inorder sucessor and if theres nothing else then its itself. Move from node if (curr->middle != nullptr && curr->small == key) { //fins successor from middle and if not go right; swap = curr->middle; } else if (curr->right != nullptr) { swap = curr->right; } //move to find the inorder successor while (swap->left != nullptr || swap->middle != nullptr || swap->right != nullptr) { //keep moving left to find successor swap = swap->left; } if (curr->small == key) { //changes the keys curr->small = swap->small; //if it only holds one item, fix it if (swap->large.empty()) { swap->small.clear(); fix(swap, nullptr); } else { //if node has two nodes just delete the large one after swaping them swap->small = swap->large; swap->large.clear(); } } else //change the large one { if (curr != swap) { curr->large = swap->small; if (swap->large.empty()) { swap->small.clear(); fix(swap, nullptr); } else { swap->small = swap->large; swap->large.clear(); } } else { swap->large.clear(); } } } void Tree::fix(Node* curr, Node* child) // basically rebalance { if (curr == root) { if (curr->left != nullptr || curr->right != nullptr) { root = child; child->parent = nullptr; } else { root = nullptr; } delete curr; return; } //no 3 node sibs if (curr->parent->left->large.empty() && curr->parent->right->large.empty()) { //if its the left child if (curr->parent->left == curr) { curr = curr->parent; curr->left->small = curr->small; if (curr->large.empty()) { curr->left->large = curr->right->small; curr->small.clear(); if (child != nullptr) { curr->left->left = child; child->parent = curr->left; curr->left->middle = curr->right->left; curr->left->middle->parent = curr->left; curr->left->right = curr->right->right; curr->left->right->parent = curr->left; } delete curr->right; curr->right = nullptr; fix(curr, curr->left); } else { curr->left->large = curr->middle->small; curr->small = curr->large; curr->large.clear(); if (child != nullptr) { curr->left->left = child; child->parent = curr->left; curr->left->middle = curr->middle->left; curr->left->middle->parent = curr->left; curr->left->right = curr->middle->right; curr->left->right->parent = curr->left; } delete curr->middle; curr->middle = nullptr; } } //if parent right child else if (curr->parent->right == curr) { curr = curr->parent; if (curr->large.empty()) { curr->left->large = curr->small; curr->small.clear(); delete curr->right; curr->right = nullptr; if (child != nullptr) { curr->left->middle = curr->left->right; curr->left->middle->parent = curr->left; curr->left->right = child; child->parent = curr->left; } fix(curr, curr->left); } else { curr->right->large = curr->large; curr->large.clear(); curr->right->small = curr->middle->small; if (child != nullptr) { curr->right->right = child; child->parent = curr->right; curr->right->middle = curr->middle->right; curr->right->middle->parent = curr->right; curr->right->left = curr->middle->left; curr->right->left->parent = curr->right; } delete curr->middle; curr->middle = nullptr; } } // its the middle child; else { curr = curr->parent; curr->left->large = curr->small; curr->small = curr->large; curr->large.clear(); if (child != nullptr) { curr->left->middle = curr->left->right; curr->left->middle->parent = curr->left; curr->left->right = child; child->parent = curr->left; } delete curr->middle; curr->middle = nullptr; } } //the node has a 3 node sib then we want to redistribute else { //if node parent left child if (curr->parent->left == curr) { curr = curr->parent; curr->left->small = curr->small; if (curr->large.empty()) { curr->small = curr->right->small; curr->right->small = curr->right->large; curr->right->large.clear(); if (child != nullptr) { curr->left->left = child; child->parent = curr->left; curr->left->right = curr->right->left; curr->left->right->parent = curr->left; curr->right->left = curr->right->middle; curr->right->left->parent = curr->right; curr->right->middle = nullptr; } } else { curr->small = curr->middle->small; if (curr->middle->large.empty()) { curr->middle->small = curr->large; curr->large = curr->right->small; curr->right->small = curr->right->large; curr->right->large.clear(); if (child != nullptr) { curr->left->left = child; child->parent = curr->left; curr->left->right = curr->middle->left; curr->left->right->parent = curr->left; curr->middle->left = curr->middle->right; curr->middle->left->parent = curr->middle; curr->middle->right = curr->right->left; curr->middle->right->parent = curr->middle; curr->right->left = curr->right->middle; curr->right->left->parent = curr->right; curr->right->middle = nullptr; } } else { curr->middle->small = curr->middle->large; curr->middle->large.clear(); if (child != nullptr) { curr->left->left = child; child->parent = curr->left; curr->left->right = curr->middle->left; curr->left->right->parent = curr->left; curr->middle->left = curr->middle->right; curr->middle->left->parent = curr->middle; curr->middle->right = curr->right->left; curr->middle->right->parent = curr->middle; curr->right->left = curr->right->middle; curr->right->left->parent = curr->right; curr->right->middle = nullptr; } } } } //if node os parent right else if (curr->parent->right == curr) { curr = curr->parent; if (curr->large.empty()) { curr->right->small = curr->small; curr->small = curr->left->large; curr->left->large.clear(); if (child != nullptr) { curr->right->right = child; child->parent = curr->right; curr->right->left = curr->left->right; curr->right->left->parent = curr->right; curr->left->right = curr->left->middle; curr->left->right->parent = curr->left; curr->left->middle = nullptr; } } else { curr->right->small = curr->large; if (curr->middle->large.empty()) { curr->large = curr->middle->small; curr->middle->small = curr->small; curr->small = curr->left->large; curr->left->large.clear(); if (child != nullptr) { curr->right->right = child; child->parent = curr->right; curr->right->left = curr->middle->right; curr->right->left->parent = curr->right; curr->middle->right = curr->middle->left; curr->middle->right->parent = curr->middle; curr->middle->left = curr->left->right; curr->middle->left->parent = curr->middle; curr->left->right = curr->left->middle; curr->left->right->parent = curr->left; curr->left->middle = nullptr; } } else { curr->large = curr->middle->large; curr->middle->large.clear(); if (child != nullptr) { curr->right->right = child; child->parent = curr->right; curr->right->left = curr->middle->right; curr->right->left->parent = curr->right; curr->middle->right = curr->middle->middle; curr->middle->right->parent = curr->middle; curr->middle->middle = nullptr; } } } } //else node is parent's middle child else { curr = curr->parent; if (curr->right->large.empty()) { curr->middle->small = curr->small; curr->small = curr->left->large; curr->left->large.clear(); if (child != nullptr) { curr->middle->right = child; child->parent = curr->middle; curr->middle->left = curr->left->right; curr->middle->left->parent = curr->middle; curr->left->right = curr->left->middle; curr->left->right->parent = curr->left; curr->left->middle = nullptr; } } else { curr->middle->small = curr->large; curr->large = curr->right->small; curr->right->small = curr->right->large; curr->right->large.clear(); if (child != nullptr) { curr->middle->left = child; child->parent = curr->middle; curr->middle->right = curr->right->left; curr->middle->right->parent = curr->middle; curr->right->left = curr->right->middle; curr->right->left->parent = curr->right; curr->right->middle = nullptr; } } } } } bool Tree::search(const string& key) const { //return a node if true, false otherwise return search(root, key); } //private: void Tree::destruct(Node* node) const { if (node) { if (node->large.empty())//2 Node { destruct(node->left); destruct(node->right); delete node; } else//3 Node { destruct(node->left); destruct(node->middle); destruct(node->right); delete node; } } } void Tree::preOrder(Node* node) const { if (node != nullptr) { //node only has one item inside if (node->large.empty()) { cout << node->small << ", "; preOrder(node->left); preOrder(node->right); } else { cout << node->small << ", "; preOrder(node->left); cout << node->large << ", "; preOrder(node->middle); preOrder(node->right); } } } void Tree::inOrder(Node* node) const { if (node) { if (node->large.empty()) { inOrder(node->left); cout << node->small << ", "; inOrder(node->right); } else { inOrder(node->left); cout << node->small << ", "; inOrder(node->middle); cout << node->large << ", "; inOrder(node->right); } } } void Tree::postOrder(Node* node)const { if (node) { if (node->large.empty()) { postOrder(node->left); postOrder(node->right); cout << node->small << ", "; } else { postOrder(node->left); postOrder(node->middle); cout << node->small << ", "; postOrder(node->right); cout << node->large << ", "; } } } Node* Tree::search(Node* node, const string& key) const { if (node) { //it equals if (key == node->small) { return node; } //go left no matter what if (key < node->small) { return search(node->left, key); //checks is two node } else if (node->large.empty()) { return search(node->right, key); //means its a 3 node } else { if (key == node->large) { return node; } else if (key < node->large) { return search(node->middle, key); } else { return search(node->right, key); } } } //not found return nullptr; } void Tree::split(Node* curr, const string& key, Node* leftChild, Node* rightChild) { string midValue; Node* leftNode; Node* rightNode; //find small, middle, and large value //key is mid if (key > curr->small&& key < curr->large) { midValue = key; leftNode = new Node(curr->small); rightNode = new Node(curr->large); //small is mid } else if (key < curr->small) { midValue = curr->small; leftNode = new Node(key); rightNode = new Node(curr->large); //large is mid } else { midValue = curr->large; leftNode = new Node(curr->small); rightNode = new Node(key); } //put mid in parent or create a new parent //if root if (curr->parent == nullptr) { root = new Node(midValue); root->left = leftNode; leftNode->parent = root; root->right = rightNode; rightNode->parent = root; //if parent is not a full node with 3 children } else if (curr->parent->large.empty()) { //you can move the data into parent if (midValue > curr->parent->small) { curr->parent->large = midValue; //if inserting into parent with one and data is less than small } else { curr->parent->large = curr->parent->small; curr->parent->small = midValue; } //rotate left if (leftNode->small < curr->parent->small) { curr->parent->left = leftNode; curr->parent->middle = rightNode; //rotate right } else { curr->parent->middle = leftNode; curr->parent->right = rightNode; } //set parents leftNode->parent = curr->parent; rightNode->parent = curr->parent; } else { //if parent is full split(curr->parent, midValue, leftNode, rightNode); } //if curr was not leaf, connect the values if (curr->left != nullptr || curr->middle != nullptr || curr->right != nullptr) { if (leftChild->small < leftNode->small) { leftNode->left = leftChild; leftChild->parent = leftNode; leftNode->right = rightChild; rightChild->parent = leftNode; //the top part is for the extra data from the other nodes that had to be split rightNode->left = curr->middle; rightNode->left->parent = rightNode; rightNode->right = curr->right; rightNode->right->parent = rightNode; } else if (rightChild->small > rightNode->small) { leftNode->left = curr->left; leftNode->left->parent = leftNode; leftNode->right = curr->middle; leftNode->right->parent = leftNode; //bottom parts are extra data rightNode->left = leftChild; leftChild->parent = rightNode; rightNode->right = rightChild; rightChild->parent = rightNode; } else { leftNode->left = curr->left; leftNode->left->parent = leftNode; leftNode->right = leftChild; leftChild->parent = leftNode; rightNode->left = rightChild; rightChild->parent = rightNode; rightNode->right = curr->right; rightNode->right->parent = rightNode; } } delete curr; }
dae7c523f81db36ec53cf9294752e2cd212225ea
a0e5492c89cc242548ef4ecbb66cb2d276e16d8c
/raytracing/camera.h
5d4fe1aca6411bdc5f4f22a2e6212b3b816d632d
[]
no_license
john27328/raytracing
7c1e581211eda2b85b154fd81ec07ebffefc9526
37575255b5ebd804ffdd2540fc181b7b3453eaeb
refs/heads/master
2020-08-27T07:51:14.489465
2019-11-07T08:28:47
2019-11-07T08:28:47
217,289,593
0
0
null
null
null
null
UTF-8
C++
false
false
373
h
camera.h
#ifndef CAMERA_H #define CAMERA_H #include "vector.h" #include "screen.h" #include "edge.h" template <typename T, int N> class Camera: public Edge<T, N> { public: Camera(Vector<T> p0, Vector<T> direction, ScreenSPtr &screen); private: Vector<T> _p0; Vector<T> _direction; T _fullAbgle; ScreenSPtr _screen; }; #endif // CAMERA_H
8f32bb241f8a5b8e15a6b6d41bfe5e00eea1047d
cf0bf9a7ea2eeb77ef732562f71741b31f53185f
/Exercicios/bissexto.cpp
1609ea97e77e1307d59f856cc5ccccb68a003e60
[]
no_license
MarcosF19/Linguagem-C-plus-plus
ee95c5bf0d0eac9fa394fb4103ac2e3812119df7
bef69bf4315a79eb571bd599822674e76abed8d9
refs/heads/main
2023-05-23T13:53:08.152803
2021-06-18T00:07:20
2021-06-18T00:07:20
349,216,318
0
1
null
null
null
null
UTF-8
C++
false
false
754
cpp
bissexto.cpp
#include <iostream> #include <cstdlib> #include <math.h> #include <string> using namespace std; int ano, tecla, MR; string status = ""; int main() { setlocale(LC_ALL, "Portuguese"); Menu: cout << "\n1 Executar..."; cout << "\n2 Finalizar..."; cout << "\n3 Item "; cin >> tecla; switch (tecla) { case 1: cout << "Digite um ano: "; cin >> ano; MR = ano % 4; if (MR == 0) { status = "Ano bissexto"; } else if (MR != 0) { status = "Não é um ano bissexto"; } cout << status << endl; break; case 2: cout << "Finalizando"; exit(0); break; } goto Menu; return 0; }
48e6bf0cba0855b4103a4312529a4fddc5cb0a8c
3a7186b7b54e4434d2cadaa9593ead85817961c2
/functionBeforeMain.cpp
ca7bc1dda208f18c2d8633195a54c74046b07636
[]
no_license
kumar0908/Object-Oriented-Programming-using-C-
9f5b19e46acced5e48a46692db4aaf2aefb6c36e
ccde7a975eb6003ca287f552ddbf599eb997c107
refs/heads/main
2023-02-04T09:52:48.816851
2020-12-29T09:27:55
2020-12-29T09:27:55
321,666,988
0
0
null
null
null
null
UTF-8
C++
false
false
323
cpp
functionBeforeMain.cpp
#include<iostream> int function() { std::cout<<"We are calling it before main!!"<<std::endl; return 5; } class Base{ public: static int variable; }; int Base::variable = function(); // function will get called int main() { std::cout<<"Inside main!!!"<<std::endl; // it will get printed at the end. return 0; }
ac4d78a14649594bafc3a1c7fda9e3d455c51b0d
a3a98a214adf107f593ad40622178e9934a2fde0
/src/bovil/algorithms/machine_learning/Regression.h
67d6858523c41b14515a4541a8b88e373d48e759
[]
no_license
Bardo91/BOVIL
3af0217d758e7aa68608319dd912ec0ddbbaf677
968d618d403a080f68d99cacfee7d9a8da452b1a
refs/heads/master
2019-07-13T04:31:05.478486
2016-02-17T00:33:32
2016-02-17T00:33:32
16,981,627
0
0
null
null
null
null
UTF-8
C++
false
false
3,046
h
Regression.h
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // BOViL: Bardo Open Vision Libraries // /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // #ifndef _BOVIL_ALGORITHMS_MACHINELEARNING_REGRESSION_H_ #define _BOVIL_ALGORITHMS_MACHINELEARNING_REGRESSION_H_ #include <array> #include <Eigen/Eigen> #include <vector> #include "Polynomial.h" namespace BOViL { namespace algorithms{ /// Base tamplate of Regression algorithms (i.e. LinealRegression, PolinomialRegression, Logistic Regression, /// etc.). Now cost function is always square function. Regression takes as template arguments: /// \tparam InputSize_ number of variables + 1. (ex. a0 + a1*x1 + a2*x2 --> InputSize_ = 3) template<unsigned Nvars_, unsigned Nmonomials_> class Regression{ public: // Public interface /// Redefinition for simplyfied understanding typedef std::function<Eigen::Matrix<double, Nmonomials_, 1>(const Eigen::Matrix<double, 1, Nvars_> &)> Hypothesis; /// Build a regression with the given hypothesys. /// \param _hypothesis Polinomial equation that defines the hypothesis /// \param _transformation Additional transformation (g(x)) that can be applied to hypothesis, for example: sigmoid to use regression as logistic regression. Default g(x) = x; Regression(const Polynomial<Nvars_, Nmonomials_> &_hypothesis, const std::function<double(double)> &_transformation = [](double _x) {return _x;}); /// \brief Traing network with given dataset. /// \tparam TrainSize_ size of training set /// \param _x inputs of datasets. /// \param _y desired results for given inputs. /// \param _alpha gradient coefficient /// \param _lambda regularization parameter /// \param _maxIter maximum number of iteration allowed /// \param _tol min difference required between steps in cost function template <unsigned TrainSize_> void train(const Eigen::Matrix<double, TrainSize_, Nvars_> &_x, const Eigen::Matrix<double, TrainSize_, 1> &_y, double _alpha, double _lambda, unsigned _maxIter = 150, double _tol = 0.00001); /// \brief Prediction of Regression. /// \param Input values. double evaluate(const Eigen::Matrix<double, 1, Nvars_> &_x) const; Polynomial<Nvars_, Nmonomials_> hypothesis() const; private: template <unsigned TrainSize_> Eigen::Matrix<double, TrainSize_, Nmonomials_> adaptSet(const Eigen::Matrix<double, TrainSize_,Nvars_> &_x) const; Eigen::Matrix<double, Nmonomials_,1> gradient(const Eigen::Matrix<double, 1, Nmonomials_> &_x, double _y) const; // For debugging purposes. double cost(const Eigen::Matrix<double, 1, Nmonomials_> &_x, double _y) const; private: // Private members Polynomial<Nvars_, Nmonomials_> mHypothesis; std::function<double(double)> mTransformation; }; } // namespace algorithms } // namespace BOViL #include "Regression.inl" #endif _BOVIL_ALGORITHMS_MACHINELEARNING_REGRESSION_H_
493bd5171cc68e9b4a60fb0dfc8f83643dfbf452
0b08351f1ec3c84a5a21b0cecb5d00afdb0ff798
/listas/exercicio 7/include/Jogador.h
a761214294a4700a47e9b10bdb28a4261757189a
[]
no_license
linguagemprogramacao/exercicios
a0170b61280c199dbf276362dcc8d0243076e21a
dd8c350ed312afeeece5d0c9e01f7e77f267ea0f
refs/heads/master
2020-03-28T13:22:43.377793
2019-02-22T20:00:45
2019-02-22T20:00:45
148,389,933
1
0
null
null
null
null
UTF-8
C++
false
false
435
h
Jogador.h
#ifndef JOGADOR_H #define JOGADOR_H #include "Cartela.h" #include <string> #include <iostream> using namespace std; class Jogador { private: string nome; Cartela cartelas[5]; int qntCartelas = 0; public: int getQntCartelas(); Jogador(); Jogador(string nome, int qntCartelas); bool verificarCartela(); void marcarCartela(int valor); friend ostream& operator<< (ostream &o, Jogador const Jogador); }; #endif
7b4bce0e787f96557347cef9c75ed806bfb9e83c
742d18f098742b1808f4dc7807c563369f1cef5c
/C++/BehaviorTree/Variable.h
65be74266d60c91cfc6eae84e4a4f21acfba313f
[]
no_license
zh880517/BehaviorTree
fc577b91c32f8c484b05b80239c7e9e293aad40c
e2aa92ea82684d047256822fd8aefe4ab3b35175
refs/heads/master
2020-04-17T16:44:03.370452
2019-01-29T11:28:04
2019-01-29T11:28:04
166,752,950
0
0
null
null
null
null
UTF-8
C++
false
false
282
h
Variable.h
#pragma once class IVariable { public: IVariable() = default; }; template<class T> class TVariable : public IVariable { public: TVariable() = default; ~TVariable() = default; TVariable(TVariable&) = delete; TVariable &operator=(const TVariable &) = delete; T Value = {}; };
1971e3d74e129f4b44a3218393a989d8c232c2de
cd8c7913735a1e66ef3522aa8be9c28ae065f41a
/CanNotOpenLvlException.cpp
48a96752eb77c81d1ba70dd14606aa3fc853b4f9
[]
no_license
epikur90/towerdef
b4c61f593418101c8c5944c90e5e0417422d5bca
3d2d7c8e6868ae7927b86a093987c1bf2fa74a59
refs/heads/master
2020-04-05T23:20:33.269623
2014-06-11T06:09:08
2014-06-11T06:09:08
null
0
0
null
null
null
null
UTF-8
C++
false
false
526
cpp
CanNotOpenLvlException.cpp
//------------------------------------------------------------------------------ /// Filename: CanNotOpenLvlException.cpp /// Description: TODO /// Authors: Tutors /// Group: 00 Tutor all /// Latest Change: 15.04.2011 //------------------------------------------------------------------------------ #include "CanNotOpenLvlException.h" CanNotOpenLvlException::CanNotOpenLvlException() throw() : CorruptionException("Error: Level file cannot be opened!",3) { } CanNotOpenLvlException::~CanNotOpenLvlException() throw() { }
98fd94e1d6cb935898288981bf08c533354ad672
b5148313edb5d1de3ef8287812ed578d5b85d220
/nodeMcu/nodeMcu.ino
241fd2d3cf9acfa1fbe0dc9b39858efedb59bd4c
[]
no_license
Aakashko/Rover
5a4d7449c5aa9c801b86e7968b3226a1c46f0fa9
d48054ec9c775998e6bb1f9cd5a80a3977832ec3
refs/heads/master
2021-02-18T10:58:41.566425
2020-02-17T13:40:34
2020-02-17T13:40:34
245,188,537
1
0
null
2020-03-05T14:44:24
2020-03-05T14:44:23
null
UTF-8
C++
false
false
2,138
ino
nodeMcu.ino
/* This sketch demonstrates how to set up a simple HTTP-like server. The server will set a GPIO pin depending on the request http://server_ip/gpio/0 will set the GPIO2 low, http://server_ip/gpio/1 will set the GPIO2 high server_ip is the IP address of the ESP8266 module, will be printed to Serial when the module is connected. */ #include <ESP8266WiFi.h> #ifndef STASSID #define STASSID "realme" #define STAPSK "iwilltypeforyou" #endif const char* ssid = STASSID; const char* password = STAPSK; // Create an instance of the server // specify the port to listen on as an argument WiFiServer server(80); void setup() { Serial.begin(115200); delay(1000); pinMode(5, OUTPUT); pinMode(4, OUTPUT); pinMode(0, OUTPUT); pinMode(2, OUTPUT); Serial.print(F("Connecting to ")); Serial.println(ssid); WiFi.mode(WIFI_STA); WiFi.begin(ssid, password); while (WiFi.status() != WL_CONNECTED) { delay(500); Serial.print(F(".")); } Serial.println(); Serial.println(F("WiFi connected")); // Start the server server.begin(); Serial.println(F("Server started")); // Print the IP address Serial.println(WiFi.localIP()); } void loop() { // Check if a client has connected WiFiClient client = server.available(); if (!client) { return; } Serial.println(F("new client")); while(client) { String m = client.readStringUntil('.'); if(m.length()!=0) { Serial.println("move: "); Serial.println(m); if(m=="w") { digitalWrite(5, 1); digitalWrite(4, 0); digitalWrite(0, 1); digitalWrite(2, 0); } else if(m=="s") { digitalWrite(5, 0); digitalWrite(4, 1); digitalWrite(0, 0); digitalWrite(2, 1); } else if(m=="d") { digitalWrite(5, 1); digitalWrite(4, 0); digitalWrite(0, 0); digitalWrite(2, 0); } else if(m=="a") { digitalWrite(5, 0); digitalWrite(4, 1); digitalWrite(0, 0); digitalWrite(2, 0); } delay(1000); } } }
5a3abaea5859d26c63986216eb63d83d61df68d0
59eafae3bc4d13b9844c47d2e12aaa2b04fb6da0
/yukicoder/1308.cpp
522fc3f5c923ac98aba60243dff716a055ab08cb
[]
no_license
pes-magic/procon
004d7cd877e1cb56fea8d4b8b6cc8ba564a93a29
7afd1564b9228144d53920cc8e6a91012144b530
refs/heads/master
2023-08-31T17:29:06.829263
2023-08-25T12:32:27
2023-08-25T12:32:27
228,394,327
3
0
null
2023-08-24T11:48:04
2019-12-16T13:33:20
Jupyter Notebook
UTF-8
C++
false
false
1,987
cpp
1308.cpp
#include <iostream> #include <vector> #include <queue> using namespace std; int main(){ int N, Q; long long C; while(cin >> N >> Q >> C){ vector<vector<pair<int, long long>>> g(N); for(int i=0;i<N-1;i++){ int u, v, l; cin >> u >> v >> l; g[u-1].emplace_back(v-1, l); g[v-1].emplace_back(u-1, l); } vector<int> x(Q); for(auto& t : x){ cin >> t; --t; } long long res = 0; vector<int> seq(1, x[0]); vector<long long> cost(1, -C); for(int i=0;i+1<Q;i++){ vector<long long> dist(N, -1); vector<int> prev(N, -1); dist[x[i+1]] = 0; queue<int> qu; qu.push(x[i+1]); while(!qu.empty()){ int p = qu.front(); qu.pop(); for(auto& nd : g[p]){ if(dist[nd.first] != -1) continue; dist[nd.first] = dist[p] + nd.second; prev[nd.first] = p; qu.push(nd.first); } } long long whole = dist[x[i]]; res += whole; int cur = x[i]; while(true){ int next = prev[cur]; if(next == -1) break; seq.push_back(next); cost.push_back(whole-dist[next]-C); cur = next; } } vector<vector<int>> posList(N); for(int i=0;i<seq.size();i++){ posList[seq[i]].push_back(i); } vector<int> next(seq.size(), -1); for(auto& v : posList){ for(int i=0;i+1<v.size();i++) next[v[i]] = v[i+1]; } vector<long long> dp(seq.size(), 0); for(int i=0;i+1<seq.size();i++){ if(next[i] != -1) dp[next[i]] = max(dp[next[i]], dp[i] + cost[next[i]]); dp[i+1] = max(dp[i+1], dp[i]); } cout << res - dp.back() << endl; } }
7eb36464a053349e0a90615913a5fb97a274de71
5550fdaf7a228386ee07b9fd686259a68944ba90
/PAT/advanced/A1009.cpp
a80baf0ab5a574bdc5ca167949888cd73ced014c
[ "MIT" ]
permissive
sptuan/LeetCode-Practice
bdc2e0189e010f7de18fe322aef089d7989d5fcf
68e1ca329190264fdeeef1a2a1d4c2a56caa27f6
refs/heads/master
2023-02-25T02:03:11.030407
2021-01-31T06:29:37
2021-01-31T06:29:37
153,608,566
0
0
null
null
null
null
UTF-8
C++
false
false
1,195
cpp
A1009.cpp
#include <iostream> #include <stdio.h> #include <math.h> using namespace std; int main(int argc, char** argv) { int K1,K2; int i,j; double ans[2020]; for(i=0;i<2020;i++){ ans[i] = 0; } cin>>K1; double a1[1010]; for(i=0;i<1010;i++){ a1[i] = 0; } for(i = 0; i < K1; i++){ int N; double a; cin>>N>>a; a1[N] = a; } cin>>K2; double a2[1010]; for(i=0;i<1010;i++){ a2[i] = 0; } for(i = 0; i < K2; i++){ int N; double a; cin>>N>>a; a2[N] = a; } int temp=0; for(i=0; i <1010; i++){ for(j=0; j<1010;j++){ if((a1[i]>0.01) || (a1[i]<-0.01)){ if((a2[j]>0.01) || (a2[j]<-0.01)){ ans[i+j]+=a1[i]*a2[j]; } } } } for(i = 0; i < 2020; i++){ if((ans[i]>0.01) || (ans[i]<-0.01)){ temp++; } } cout<<temp; for(i = 2019; i >= 0; i--){ if((ans[i]>0.01) || (ans[i]<-0.01)){ printf(" %d %.1f",i,ans[i]); } } /* int temp=0; for(i = 0; i < 1010; i++){ ans[i] = a1[i] + a2[i]; if((ans[i]>0.01) || (ans[i]<-0.01)){ temp++; } } cout<<temp; for(i = 1009; i >= 0; i--){ if((ans[i]>0.01) || (ans[i]<-0.01)){ printf(" %d %.1f",i,ans[i]); } } */ return 0; }
ea49466624ee0f66d78a95ebb93200bacf00c0ba
772f27c0c7e3f2df230736d3259c1a831994a887
/src/mdp/learning/reinforcementLearning/reinforcedLearning.cpp
bc32598a8446d4c837f5cfeebf1aa43bd1bce6c6
[ "BSD-3-Clause" ]
permissive
Jacques-Florence/schedSim
04008b2da3495a4f213d9e89fb03a85ccc8e16c1
cd5f356ec1d177963d401b69996a19a68646d7af
refs/heads/master
2021-05-07T17:48:43.879031
2017-11-27T01:02:08
2017-11-27T01:02:08
108,736,406
1
0
null
null
null
null
UTF-8
C++
false
false
9,521
cpp
reinforcedLearning.cpp
/** * Copyright 2017 Jacques Florence * All rights reserved. * See License.txt file * */ #include "reinforcedLearning.h" #include <cassert> #include <cmath> #include <iomanip> #include <iostream> #include <fstream> #include <memory> #include <stdexcept> #include <vector> #include <utils/randomGenerator.h> #include <utils/stringUtils.h> #include <mdp/mdpConfiguration.h> #include <mdp/context.h> #include <mdp/actionSpace.h> #include <mdp/policy.h> #include <mdp/stateSpace.h> #include "rlBackupAlgo/qLearning.h" #include "rlBackupAlgo/sarsaLambda.h" #include "rlBackupAlgo/delayedQLearning.h" #include "rlBackupAlgo/naiveQLambda.h" #include "rlBackupAlgo/watkinsQLambda.h" #include "actionSelection/actionSelectionStrategy.h" #include "actionSelection/epsilonGreedy.h" #include "actionSelection/gibbsActionSelection.h" #include "actionValuesFunction/tabularActionValues.h" using namespace Mdp; ReinforcedLearning::ReinforcedLearning(std::shared_ptr<Context> c) : LearningStrategy(c) , S(c->stateSpace->size()) , A(c->actionSpace->size()) , actionValuesRecord(ActionValuesRecord(c->conf, S, A)) , rewardRecord(c->conf, "rewardRecord") { assert(context != nullptr); assert(context->conf != nullptr); } ReinforcedLearning::~ReinforcedLearning() { if (backupAlgo != nullptr) delete backupAlgo; } /*TODO: what to do with initializeModel vs constructor? * initializeModel is a public function. Why? Where is it called?*/ void ReinforcedLearning::initializeModel() { previousState = context->stateSpace->getState(); std::cerr << "initial state is: " << previousState <<"\n"; initializePolicy(); assert(context != nullptr); assert(context->conf != nullptr); backupAlgo = getBackupAlgorithm(); backupAlgo->init(); actionValuesRecord.init(); /*FIXME: REDUNDANT*/ initializePolicy(); initializeActionSelectionStrategy(); printStateSpace(); } void ReinforcedLearning::printStateSpace() { #ifdef PRINT size_t S = context->stateSpace->size(); for (size_t s = 0; s < S; s++) { std::vector<size_t> *vect = context->stateSpace->factorize(s); for (size_t i = 0; i < vect->size(); i++) { std::cerr << (*vect)[i] << " "; } std::cerr << "\n"; } #endif } void ReinforcedLearning::initializeActionSelectionStrategy() { std::string str = context->conf->getStringValue("reinforcementLearning", "actionSelectionStrategy"); if (!str.compare("epsilonGreedy")) { double epsilon = context->conf->getRlEpsilonFromFile(); double epsilonDecaySpeed = context->conf->getDoubleValue( "reinforcementLearning", "epsilonDecaySpeed"); long long unsigned int epsilonTimeout = context->conf->getUnsignedLongLongIntValue( "reinforcementLearning", "epsilonTimeOut"); actionSelectionStrategy = new EpsilonGreedy(epsilon, epsilonDecaySpeed, epsilonTimeout); } else if (!str.compare("greedy")) { actionSelectionStrategy = new EpsilonGreedy(0.0, 0.0, 0); } else if (!str.compare("Gibbs")) { double temperature = context->conf->getDoubleValue("reinforcementLearning", "GibbsTemperature"); double tempDecaySpeed = context->conf->getDoubleValue("reinforcementLearning", "GibbsTempDecaySpeed"); double tempStepSize = context->conf->getDoubleValue("reinforcementLearning", "GibbsTempStepSize"); actionSelectionStrategy = new GibbsActionSelection(temperature, tempDecaySpeed, tempStepSize); } else { throw std::invalid_argument("invalid value for actionSelectionStrategy"); } } void ReinforcedLearning::initializePolicy() { std::string initStr = context->conf->getStringValue("reinforcementLearning", "initialPolicy"); if (!initStr.compare("uniform")) { context->policy->initializeUniformly(); } else if (!initStr.compare("fromFile")) { /*TODO: path is hardcoded*/ context->policy->initializeFromFile("configuration/initialPolicy"); } else { throw std::invalid_argument("initial policy not defined"); } } RlBackupAlgorithm *ReinforcedLearning::getBackupAlgorithm() { std::string str = context->conf->getStringValue("reinforcementLearning", "algo"); if (!str.compare(QLearning::configKey)) { actionValues = new TabularActionValues(context); return new QLearning(context, dynamic_cast<TabularActionValues*>(actionValues)); } if (!str.compare(SarsaLambda::configKey)) { actionValues = new TabularActionValues(context); return new SarsaLambda(context, dynamic_cast<TabularActionValues*>(actionValues)); } if (!str.compare(DelayedQLearning::configKey)) { actionValues = new TabularActionValues(context); return new DelayedQLearning(context, dynamic_cast<TabularActionValues*>(actionValues)); } if (!str.compare(WatkinsQLambda::configKey)) { actionValues = new TabularActionValues(context); return new WatkinsQLambda(context, dynamic_cast<TabularActionValues*>(actionValues)); } if (!str.compare(NaiveQLambda::configKey)) { actionValues = new TabularActionValues(context); return new NaiveQLambda(context, dynamic_cast<TabularActionValues*>(actionValues)); } throw std::runtime_error("Reinforcement Learning algorithm lookup failed"); } void ReinforcedLearning::updateModel() { /*We use Q-learning*/ previousAction = context->actionSpace->getLastAction(); state_t newState = context->stateSpace->getState(); double reward = context->stateSpace->getReward(); if (reward == -HUGE_VAL) reward = -1.0e100; static double discountFactor = context->conf->getDoubleValue("mdp", "discountFactor"); updateLongTermReward(reward, discountFactor); //updateActualDiscountedReward(reward); backupAlgo->notifyUpdateNeeded(); backupAlgo->updateActionValues(previousState, newState, previousAction, reward); actionValuesRecord.recordActionValues(actionValues, previousState, previousAction); updatePolicy(previousState); previousState = newState; } void ReinforcedLearning::updateLongTermReward(double reward, double discountFactor) { longTermReward *= discountFactor; longTermReward += reward; } void ReinforcedLearning::updateActualDiscountedReward(double reward) { static long long int counter = 0; actualDiscountedReward *= discountFactor; actualDiscountedReward += reward; rewardRecord.add(counter++, actualDiscountedReward); } void ReinforcedLearning::updatePolicy(state_t state) { static const bool updatePolicy = context->conf->getBoolValue("reinforcementLearning", "updatePolicy", true); if (!updatePolicy) { return; } epsilonGreedyPolicyUpdate(state); //FIXME: remove epsilongreedy from the name } void ReinforcedLearning::epsilonGreedyPolicyUpdate(state_t state) { action_t bestAction = getBestAction(state); std::vector<double> av = actionValues->getValues(state); //bestAction = getBestActionFromInitialPolicy(state); std::vector<double> policy = actionSelectionStrategy->generatePolicy(av, bestAction); context->policy->update(state, policy); } action_t ReinforcedLearning::getBestActionFromInitialPolicy(state_t s) { size_t S = context->stateSpace->size(); size_t A = context->actionSpace->size(); static std::vector<std::vector<double>> init(S, std::vector<double>(A)); static bool valid = false; static std::vector<action_t> bestAction(S); if (!valid) { valid = true; std::string filename = "configuration/initialPolicy"; std::fstream stream; stream.open(filename); if (!stream.is_open()) throw std::runtime_error("cannot open file"); std::string line; std::vector<std::vector<double>> pol; size_t a = 0; while(std::getline(stream, line)) { std::vector<std::string> elements = Utils::StringUtils::split(line, ' '); std::vector<double> row; /*TODO: this can be rewritten more elegantly*/ for (size_t i = 0; i < elements.size(); i++) { row.push_back(std::stod(elements[i])); } init[a++] = row; } double bestValue; for (size_t s = 0; s < S; s++) { bestAction[s] = 0; bestValue = init[s][0]; for (size_t a = 1; a < A; a++) { if (init[s][a] > bestValue) { bestValue = init[s][a]; bestAction[s] = a; } } } } return bestAction[s]; } action_t ReinforcedLearning::getBestAction(state_t state) { return backupAlgo->getBestAction(state); } void ReinforcedLearning::end() { actionValuesRecord.end(); #ifdef PRINT /*Action values are Q-learning's equivalent to mdp policy table*/ printActionValuesToFile("./"); #endif rewardRecord.printToFile("reports"); #ifdef PRINT std::cerr << "the long-term reward is " << longTermReward <<"\n"; #endif } void ReinforcedLearning::printActionValuesToFile(std::string folder) { std::ofstream file; std::ofstream normalized; file.open(folder + "/rlfile.txt", std::ios_base::app); normalized.open(folder + "/rlfilenormalized.txt", std::ios_base::app); for (unsigned int i = 0; i < S; i++) { bool allEqual = true; unsigned int maxIndex = 0; double maxValue = actionValues->getValue(i, 0); for (size_t j = 1; j < A; j++) { if (actionValues->getValue(i, j) > maxValue) { maxValue = actionValues->getValue(i, j); maxIndex = j; } double eps = 0.0000001; //TODO: what value should this be? Maybe make it relative to the abs value of actionValues[i][j] if (actionValues->getValue(i, j) < actionValues->getValue(i, j-1) - eps || actionValues->getValue(i, j) > actionValues->getValue(i, j-1) + eps) allEqual = false; } for (unsigned int j = 0; j < A; j++) { file << actionValues->getValue(i, j)<<" "; normalized << ((allEqual == true) ? 1 : ((j == maxIndex) ? 1 : 0) ) <<" "; } file << "\n"; normalized << "\n"; } file.close(); normalized.close(); }
8a59948e84fe6209ad14446b451806fb0d312c42
14dacc389911c4aba0bb42b3f01df75dbba2ad38
/ch19/stack-assignment.cpp
468479ac7fdf491b6d75c657e8c093e669b8082d
[]
no_license
RaymondSHANG/cpp_from_control_to_objects_8e
9fe5142c6a7890743ffdc4a22f7ae4f8bb588c60
ba537974d5d7b7012ae659368f1887f739e50c3b
refs/heads/master
2023-04-17T06:20:55.635444
2021-04-16T01:22:13
2021-04-16T01:22:13
null
0
0
null
null
null
null
UTF-8
C++
false
false
11,029
cpp
stack-assignment.cpp
/*Write a function that takes a string parameter and determines whether the string contains matching grouping symbols. Grouping symbols are parenthesis ( ) , brackets [] and curly braces { }. For example, the string {a(b+ac)d[xy]g} and kab*cd contain matching grouping symbols. However, the strings ac)cd(e(k, xy{za(dx)k, and {a(b+ac}d) do not contain matching grouping symbols. (Note: open and closed grouping symbols have to match both in number and in the order they occur in the string). Your function must use a stack data structure to determine whether the string parameter satisfies the condition described above. You may define your own stack class or use the STL stack class. Write a driver program (i.e. a function main()) to test your function. Deliverables: 1. a copy of your function and the test driver program source codes in a text file (e.g. a .cpp file) 2. screen shots of your test driver program runs showing it meets the problem's specifications.*/ #include <iostream> #include <stack> #include "dynstack.hpp" #include <cassert> #include <initializer_list> // #include <ranges> // :*( MinGW using namespace std; bool MATCHING_DEBUG = true; // Function definitions template <typename T> bool list_contains(T& test, std::initializer_list<T> items) { for (auto& item : items) { if (test == item) return true; } return false; } char paired_symbol(char& test) { /* Return the matching symmetric grouping symbol Grouping symbols are (), [], {}. This function will return the symmetric grouping symbol */ if (test == '(') { return ')'; } else if (test == ')') { return '('; } else if (test == '[') { return ']'; } else if (test == ']') { return '['; } else if (test == '{') { return '}'; } else if (test == '}') { return '{'; } throw std::logic_error("Function argument must be one of {'(', '[', '{', '}', ']', ')'}"); } bool matching_group(string str) { /*Return true if the string str contains matching grouping symbols Grouping symbols include (), [], {} The symbols must match in order and number that occur in the string Rigorous specification: 1. Grouping symbols include (), {}, [] 2. Grouping symbols CAN envelope other grouping symbols - ([{}]) is valid 3. Groups cannot overlap. ([{})]} is invalid 4. The grouping can contain any number of other characters between opening and closing 5. Groups MUST be paired. Grouping symbols that do not have a pair will NOT pass the test Example: (abc{defg} fails the test 6. Non-symmetric groups are valid. Example {[]()} inputs ------ str : (string) string of any characters outputs ------ boolean if the above conditions are satisfied */ // Debugging if (MATCHING_DEBUG) { std::cout << "Beginning " << __func__ << " with arguments: " << str << endl; } DynamicStack<char> stak; std::initializer_list<char> group_symbols = {'(', '[', '{', '}', ']', ')'}; // Iterate through the string and insert matching elements onto a stack for (std::string::reverse_iterator rit = str.rbegin(); rit!=str.rend(); ++rit) { char character = *rit; if (list_contains(character, group_symbols)) { stak.push(character); } } /* Negative test (Automatic failure) */ // A stack with an odd number of elements automatically fails (Non-paired group) if ((stak.get_length() % 2) != 0) { if (MATCHING_DEBUG) { std::cout << "Fail: string has an odd number of grouping symbols (non-paired group)" << "\n\n"; } return false; } /* Positive test (Automatic pass) */ // An empty stack automatically passes (no grouping symbols) if (stak.is_empty()) { if (MATCHING_DEBUG) { std::cout << "Pass: string has no grouping symbols (text only)" << "\n\n"; } return true; } /* Positive test (Conditional pass) Example stack contents: {'(', '{', '}', '[', ']', ')'} */ while (!stak.is_empty()) { // 1. Pop an element auto element = stak.pop(); // '(' // {'{', '}', '[', ']', ')'} if (list_contains(element, {')', ']', '}'})) { // Because of the structure of this loop and the stack // It is a negative condition to encounter a closing // grouping symbol at the beginning of test phase if (MATCHING_DEBUG) { std::cout << "Fail: string has backwards facing grouping symbol (unpaired)" << "\n\n"; } return false; } if (paired_symbol(element) == stak.peek_back()) { // 2. See if the back element matches // Remove the back matching element stak.pop_back(); // {'{', '}', '[', ']'} } else if (paired_symbol(element) == stak.peek_front()) { // 3. Test if the next element matches otherwise // Remove the next matching element stak.pop(); } else { // 4. else fail if (MATCHING_DEBUG) { std::cout << "Fail: grouping symbols are unpaired or overlapping (unpaired/overlapping)" << "\n\n"; } return false; } } // We made it :) if (MATCHING_DEBUG) { std::cout << "Pass: all requirements met" << "\n\n"; } return true; } void test_dynamic_stack() { std::cout << "Beginning " << __func__ << endl; { /* Test initialization, push, pop, push back, pop back operations */ std::cout << "Initializing stack {1,2,3,4,5}" << endl; // Initialization DynamicStack<int> dstack{1,2,3,4,5}; std::cout << dstack; // Push std::cout << "Pushing item to top: " << endl; dstack.push(10); std::cout << dstack; // Pop auto res = dstack.pop(); std::cout << "Popping item from top: " << endl; std::cout << dstack; assert (res == 10); res = dstack.pop(); std::cout << "Popping item from top: " << endl; std::cout << dstack; assert (res == 5); // Push back std::cout << "Pushing item to back: " << endl; dstack.push_back(6); std::cout << dstack; std::cout << "Pushing item to back: " << endl; dstack.push_back(7); std::cout << dstack; // Pop back std::cout << "Popping item from back: " << endl; res = dstack.pop_back(); std::cout << dstack; assert (res == 7); std::cout << "Popping item from back: " << endl; res = dstack.pop_back(); std::cout << dstack; assert (res == 6); }; // End block { /**/ // Peek DynamicStack<int> dstack{1,2,3,4,5}; assert(dstack.peek_front() == 5); assert(dstack.peek_back() == 1); // Perform some operations to make sure front and back pointers are preserved // Push operations dstack.push(6); assert(dstack.peek_front() == 6); assert(dstack.peek_back() == 1); dstack.push_back(0); assert(dstack.peek_front() == 6); assert(dstack.peek_back() == 0); // Pop operations dstack.pop(); // 6 assert(dstack.peek_front() == 5); assert(dstack.peek_back() == 0); dstack.pop_back(); // 0 assert(dstack.peek_front() == 5); assert(dstack.peek_back() == 1); }; // End block { /**/ // Length DynamicStack<int> dstack{1,2,3,4,5}; assert(dstack.get_length() == 5); // Perform some operations to make sure front and back pointers are preserved // Push operations dstack.push(6); assert(dstack.get_length() == 6); dstack.push_back(0); assert(dstack.get_length() == 7); // Pop operations dstack.pop(); // 6 assert(dstack.get_length() == 6); dstack.pop_back(); // 0 assert(dstack.get_length() == 5); }; // End block { /* Test length with non-initialized instance */ // Non-initialized DynamicStack<int> dstack; assert(dstack.get_length() == 0); dstack.push(0); assert(dstack.get_length() == 1); dstack.push(1); assert(dstack.get_length() == 2); dstack.push(2); assert(dstack.get_length() == 3); dstack.push_back(-1); assert(dstack.get_length() == 4); dstack.push_back(-2); assert(dstack.get_length() == 5); dstack.push_back(-3); assert(dstack.get_length() == 6); dstack.pop(); assert(dstack.get_length() == 5); dstack.pop(); assert(dstack.get_length() == 4); dstack.pop(); assert(dstack.get_length() == 3); dstack.pop(); assert(dstack.get_length() == 2); dstack.pop(); assert(dstack.get_length() == 1); dstack.pop(); assert(dstack.get_length() == 0); }; // End block std::cout << "Success - Passed " << __func__ << "\n\n"; } void test_matching_group() { std::cout << "Beginning " << __func__ << endl; /* ############## ## Positive ## ############## */ // Positive - simple symmetric string test = "(a)"; auto res = matching_group(test); assert(res == true); // Positive - text only test = "Non-Matching-Group"; res = matching_group(test); assert(res == true); // Positive - two layers symmetric test = "(~{some-test}11)"; res = matching_group(test); assert(res == true); // Positive - three layers symmetric test = "*4378kk$#&*&^(9~{som{e-tes}t}191)"; res = matching_group(test); assert(res == true); // Positive - Non symmetric test = "{a(b+ac)d[xy]g}"; res = matching_group(test); assert(res == true); /* ############## ## Negative ## ############## */ // Negative - Unpaired test = "a)a(a"; res = matching_group(test); assert(res == false); // Negative - Unpaired w/ partial matching test = "[a)a(a]"; res = matching_group(test); assert(res == false); // Negative - Unpaired, ungrouped, odd number test = "ac)cd(e(k"; res = matching_group(test); assert(res == false); // Negative - Unpaired, ungrouped, even number test = "ac)cd(e(k("; res = matching_group(test); assert(res == false); // Negative - Unpaired symbols (odd number) test = "xy{za(dx)k"; res = matching_group(test); assert(res == false); // Negative - Overlapping test = "{a(b+ac}d)"; res = matching_group(test); assert(res == false); // Negative - Overlapping test = "{x(x+x{x)x}x[xx]x}"; res = matching_group(test); assert(res == false); std::cout << "Success - Passed " << __func__ << "\n\n"; } int main () { // Test pop, push, pop_back, push_back, initialization, and other operations // test_dynamic_stack(); // Comment out for demonstration of grouping phase // Test matching_group test_matching_group(); try { // Do something } catch (const std::logic_error& e) { // Print something } return 0; }
65c7d33b1c7c3602dca060a897046dee098d8d81
d839ef7211c25a5a447ddaafeade13677512fc48
/301-400/395_Longest_Substring_with_At_Least_K_Repeating_Characters.h
6a72dccaf378a07d89c68dd27256d91b04ef5cb2
[]
no_license
RiceReallyGood/LeetCode_Revise
3d1a5546df7abd234d3db652e1e4720812497d14
db9133f40a579850abc94f74d0d7c10af1193c70
refs/heads/master
2023-03-01T03:59:31.700854
2021-02-10T13:12:29
2021-02-10T13:12:29
318,096,813
0
0
null
null
null
null
UTF-8
C++
false
false
1,516
h
395_Longest_Substring_with_At_Least_K_Repeating_Characters.h
#include <string> #include <unordered_map> #include <vector> using namespace std; class Solution { public: int longestSubstring(string s, int k) { int maxlen = 0; for(int i = 0; i < s.length(); i++){ int count[26] = {0}; for(int j = i; j < s.length(); j++){ if(++count[s[j] - 'a'] < k) continue; int flag = true; for(int c = 0; c < 26; c++){ if(count[c] == 0) continue; if(count[c] < k){ flag = false; break; } } if(flag) maxlen = max(maxlen, j - i + 1); } } return maxlen; } }; class Solution { public: int longestSubstring(string s, int k) { if(s.size() == 0 || s.size() < k) return 0; unordered_map<char,int> char_Num; for(char p : s) char_Num[p]++; vector<int> index;//切割点 for(int i = 0; i < s.size(); i++){ if(char_Num[s[i]] < k) index.push_back(i); } if(index.empty()) return s.size(); int left = 0, len = 0, ans = 0; index.push_back(s.size());//来计算最后一段字符串的长度 for(int i = 0; i < index.size(); i++){ len = index[i] - left; if(len >= k && len > ans) ans = max(ans,longestSubstring(s.substr(left, len), k)); left = index[i] + 1; } return ans; } };
cb84a04349a5d1398df62ae33205bedc5406c3de
a5f717f4cab2664a4df521d5357f243a60a33452
/random/random.cpp
9a5c1d7abc60878508c17925723114ebcb76c913
[]
no_license
dinulichess/fire
9120438bd2a89b20051f229ea24f0b9d33e77f00
590a2b6d293f9fb44a6f2ea01047d215213f24a9
refs/heads/main
2023-04-21T06:47:45.323034
2021-04-27T22:16:53
2021-04-27T22:16:53
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,011
cpp
random.cpp
#include <random> #include "../position.h" #include "../movepick.h" #include "../pragma.h" #include "../util/util.h" // use uniform_real_distribution to generate all possible value and avoid statistical bias void random(position& pos) { int num_moves = 0; // find & count legal moves for (const auto& m : legal_move_list(pos)) num_moves++; // seed the generator std::random_device rd; // use standard mersenne_twister_engine std::mt19937 gen(rd()); // calculate a uniform distribution between 1 and num_moves + 1 std::uniform_real_distribution<> distribution (1, num_moves + 1); // generate a random number using the distribution from above const int r = static_cast<int>(distribution(gen)); // find the move num_moves = 0; for (const auto& m : legal_move_list(pos)) { num_moves++; if (num_moves == r) { // play and output the move pos.play_move(m, pos.give_check(m)); acout() << "bestmove " << util::move_to_string(m, pos) << std::endl; } } }
e4f87be2bba475442ca310242a636147e5bba284
b28cb3b39f60d0a5e34f796d5b2199bc9ff8efd2
/Vectores_Guia_13/Vectores4.cpp
f65c4af22327160ed81a152b6fe77892a8924d6c
[]
no_license
otto-krause/Ascencios_Alexis_Guia_13
96aee8868be30540bb6d6b475ffb0415928f81b0
c74f1deca0e115127603795e91bd59e651fa05f8
refs/heads/main
2023-02-07T08:54:54.319174
2020-12-11T17:16:05
2020-12-11T17:16:05
314,381,312
0
0
null
null
null
null
UTF-8
C++
false
false
328
cpp
Vectores4.cpp
#include <stdio.h> #include <stdlib.h> int main() { int a,promgen,alumnos[30]; int i=1; for (a=0;a<30;a++) { printf("Ingrese las notas del %d alumno ", i); scanf("%d",&alumnos[a]); i++; promgen=promgen+alumnos[a]; } promgen=promgen/30; printf("\n El promedio es %d",promgen); return 0; }
bce0ca7134ce7a9fcb831626fc49996bd11c5d28
95b9d429360f115c3c4f85412ad524aaa0ecef91
/Homework/Assignment2/Sem_V3/Variable.h
1dce5ec602c35752e6ce807369df407e7a8b4e21
[]
no_license
adaviloper/COSC3360
a5a793ad07e06f4f6f880fd3d70d439fd4de784b
7aa5984725310487773c93e2de1b29a542b22900
refs/heads/master
2021-09-01T12:21:20.492968
2017-12-27T00:33:15
2017-12-27T00:33:15
null
0
0
null
null
null
null
UTF-8
C++
false
false
236
h
Variable.h
// // Created by hackeysack09 on 11/5/2016. // #ifndef SEM_V3_VARIABLE_H #define SEM_V3_VARIABLE_H #endif //SEM_V3_VARIABLE_H #include <string> #include <iostream> using namespace std; struct Variable { int value; string name; };
bbdbd05c9d1989f7a1879c38d8dbf2bc7b848b5b
78ce6ae9db3a8fa0ef765b011916e314287d891c
/lander.cpp
5950363fc48512dbc101e72a756b529a1d6416af
[]
no_license
lucicd/moonLander
488a473776d860627b6b03877cbfc54ebad64e72
7b649e2b428576bacee7238a3b4f07b0296007c3
refs/heads/master
2020-05-29T13:13:28.005811
2019-06-07T08:10:52
2019-06-07T08:10:52
189,152,771
0
0
null
null
null
null
UTF-8
C++
false
false
2,264
cpp
lander.cpp
/*********************************************************************** * Implementation File: * LANDER : A class representing a lunar lander * Author: * Drazen Lucic * Summary: * Everything we need to know about a lunar lander including * the location, velocity, fuel level, and status (landed, alive). * Also includes methods to draw the lander and apply the thrust. ************************************************************************/ #include "lander.h" #include "uiDraw.h" #include "game.h" #include <iostream> // Returns true if the thrusters can be activaed bool Lander::canThrust() const { return isAlive() && !isLanded(); } // Returns true while the lander is alive bool Lander::isAlive() const { return m_ground->isAboveGround(m_point); } // Returns true when the lander lands on the platform. bool Lander::isLanded() const { Game * game = static_cast<Game *>(Interface::p); return game->justLanded(); } // Applies gravity on the lander effectively pulling it down void Lander::applyGravity(float gravity) { m_velocity.setDy(m_velocity.getDy() - gravity); } // Activates lander's left thruster, which pushes the lander to the right. void Lander::applyThrustLeft() { if (!canThrust()) return; if (m_fuel < SIDE_THRUST_FUEL) return; m_velocity.setDx(m_velocity.getDx() + SIDE_THRUST_AMOUNT); m_fuel -= SIDE_THRUST_FUEL; } // Activates lander's right thruster, which pushes the lander to the left. void Lander::applyThrustRight() { if (!canThrust()) return; if (m_fuel < SIDE_THRUST_FUEL) return; m_velocity.setDx(m_velocity.getDx() - SIDE_THRUST_AMOUNT); m_fuel -= SIDE_THRUST_FUEL; } // Activates lander's bottom thruster, which slows lander's descent. void Lander::applyThrustBottom() { if (!canThrust()) return; if (m_fuel < UPWARD_THRUST_FUEL) return; m_velocity.setDy(m_velocity.getDy() + UPWARD_THRUST_AMOUNT); m_fuel -= UPWARD_THRUST_FUEL; } // Advances the lander to a new position. void Lander::advance() { // m_point.setX(150); // m_point.setY(150); m_point.setX(m_point.getX() + m_velocity.getDx()); m_point.setY(m_point.getY() + m_velocity.getDy()); } // Draws the lander on the screen. void Lander::draw() const { drawLander(getPoint()); }
724a7893bebc6c901d9d14073ed91d2f629d6487
8758abed02380e64a6e5c49b8cb6d133455a384d
/search-step.cpp
1f99a817de22a5ecd4e8329ecfa8403b964590ed
[ "MIT" ]
permissive
st34-satoshi/quixo-cpp
c413e8b943aac0f6beff596e08d3133a16e8c3bb
9d71c506bea91d8a12253d527958ac0c04d0327e
refs/heads/master
2023-08-03T18:03:27.849305
2021-09-17T16:24:53
2021-09-17T16:24:53
229,896,760
0
0
null
null
null
null
UTF-8
C++
false
false
8,727
cpp
search-step.cpp
/** * after computing all states value, compute the step to win. * the winner tries to win in minimum steps. * the loser tries to lose in max steps. * */ #include "state.cpp" const int DEFAULT_STEP = 200; // TODO: select the good number void init(){ createCombinations(); initState(); initMovingMasks(); initEncoding(); } inline bool isWin(vector<bool> *values, ll index){ return (!values->at(index*2ll) && values->at(index*2ll + 1ll)); } inline bool isLoss(vector<bool> *values, ll index){ return values->at(index*2ll) && values->at(index*2ll + 1ll); } inline bool isWinOrDraw(vector<bool> *values, ll index){ return values->at(index*2ll) && !(values->at(index*2ll + 1ll)); } inline bool isDefault(vector<bool> *values, ll index){ return !(values->at(index*2ll)) && !(values->at(index*2ll + 1ll)); } inline bool isDraw(vector<bool> *values, ll index){ // default or winOrDraw return !(values->at(index*2ll + 1ll)); } void updateStepsFromNext(vector<int> *steps, vector<bool> *values, int oNumber, int xNumber){ // if next state is loss, this state step --> min(this step, next step+1) // if next state is win, this state step --> if this step is Default, nextS+1, else max(thisS, nextS) // read next states from the file vector<bool> nextStatesValue(getCombination(combinationSize, xNumber)*getCombination(combinationSize-xNumber, oNumber+1) * 2); // next states values of values readStatesValue(&nextStatesValue, xNumber, oNumber+1); // read next states step from file vector<int> nextStatesStep(getCombination(combinationSize, xNumber)*getCombination(combinationSize-xNumber, oNumber+1)); // next states values of values readStatesStep(&nextStatesStep, xNumber, oNumber+1); for (ull i=0ll;i<nextStatesStep.size();i++){ if(isLoss(&nextStatesValue, i)){ ll stateNumber = generateState(i, xNumber, oNumber+1); StateArray sa = createPreviousStates(stateNumber, /*fromEmpty*/true); ll stateI; for(int j=0;j<sa.count;j++){ stateI = generateIndexNumber(sa.states[j], oNumber, xNumber); steps->at(stateI) = min(steps->at(stateI), nextStatesStep[i]+1); } }else if(isWin(&nextStatesValue, i)){ ll stateNumber = generateState(i, xNumber, oNumber+1); StateArray sa = createPreviousStates(stateNumber, /*fromEmpty*/true); ll stateN, stateI; for(int j=0;j<sa.count;j++){ stateN = sa.states[j]; stateI = generateIndexNumber(stateN, oNumber, xNumber); if(isLoss(values, stateI)){ if(steps->at(stateI) == DEFAULT_STEP){ steps->at(stateI) = nextStatesStep[i]+1; }else{ steps->at(stateI) = max(steps->at(stateI), nextStatesStep[i]+1); } } } } } } void updateStepFromEndStates(vector<int> *statesStep, int oNumber, int xNumber, vector<bool> *reverseStatesValue, vector<int> *reverseStatesStep){ // find the states which end of the game in reverseStates, update the states step to 0 for (ull i=0ll;i<reverseStatesValue->size()/2ll;i++){ if (isDraw(reverseStatesValue, i)){ continue; // not the end of the game } ll stateNumber = generateState(i, xNumber, oNumber); int win = isWin(stateNumber); // win:1, lose:-1, draw:0 if (win != 0){ // update this state step to 0 reverseStatesStep->at(i) = 0; } } } bool updateStatesStep(vector<bool> *statesValue, vector<int> *statesStep, vector<int> *statesStepTmp, vector<bool> *reverseStatesValue, vector<int> *reverseStatsStep, int oNumber, int xNumber, int presentStep){ // if the max next states step == present step -1, then update the state step bool continueSearching = false; for (ull i=0ll;i<statesStep->size();i++){ if (isDraw(statesValue, i)){ continue; // not loss } if(statesStep->at(i) < presentStep){ continue; // this state step already decided! } continueSearching = true; // check all next states step if (isWin(statesValue, i)){ if(statesStepTmp->at(i) == presentStep){ statesStep->at(i) = presentStep; continue; } // at least one next loss state step is present step-1, update StateArray sa = createNextStates(generateState(i, oNumber, xNumber), false); for(int j=0;j<sa.count;j++){ ll nextStateI = generateIndexNumber(sa.states[j], xNumber, oNumber); if(isLoss(reverseStatesValue, nextStateI) && reverseStatsStep->at(nextStateI) == presentStep-1){ statesStep->at(i) = presentStep; break; } } }else if(isLoss(statesValue, i)){ // if next max step == present step -1, update int nextMaxStep = 0; if(statesStepTmp->at(i) != DEFAULT_STEP){ nextMaxStep = statesStepTmp->at(i) - 1; } StateArray sa = createNextStates(generateState(i, oNumber, xNumber), false); for(int j=0;j<sa.count;j++){ ll nextStateI = generateIndexNumber(sa.states[j], xNumber, oNumber); nextMaxStep = max(nextMaxStep, reverseStatsStep->at(nextStateI)); } if(nextMaxStep == presentStep-1){ statesStep->at(i) = presentStep; } } } return continueSearching; } void computeStatesStep(int oNumber, int xNumber){ // we need to compute reverse states at the same time. // read the value from file vector<bool> values(combinations[combinationSize][oNumber] * combinations[(combinationSize-oNumber)][xNumber] * 2); vector<bool> valuesReverse(combinations[combinationSize][xNumber] * combinations[(combinationSize-xNumber)][oNumber] * 2); readStatesValue(&values, oNumber, xNumber); readStatesValue(&valuesReverse, xNumber, oNumber); // initialize steps vector<int> statesSteps(combinations[combinationSize][oNumber] * combinations[(combinationSize-oNumber)][xNumber], DEFAULT_STEP); vector<int> reverseStatesSteps(combinations[combinationSize][xNumber] * combinations[(combinationSize-xNumber)][oNumber], DEFAULT_STEP); vector<int> statesStepsTmp(combinations[combinationSize][oNumber] * combinations[(combinationSize-oNumber)][xNumber], DEFAULT_STEP); vector<int> reverseStatesStepsTmp(combinations[combinationSize][xNumber] * combinations[(combinationSize-xNumber)][oNumber], DEFAULT_STEP); updateStepsFromNext(&statesStepsTmp, &values, oNumber, xNumber); updateStepsFromNext(&reverseStatesStepsTmp, &valuesReverse, xNumber, oNumber); updateStepFromEndStates(&statesSteps, oNumber, xNumber, &valuesReverse, &reverseStatesSteps); updateStepFromEndStates(&reverseStatesSteps, xNumber, oNumber, &values, &statesSteps); // compute steps until no update int i = 1; for(;i<=DEFAULT_STEP;i++){ if(i==DEFAULT_STEP){ cout << "ERROR: reached default step!" << endl; exit(0); } bool continueSearching = false; // // check all states // if(oNumber==xNumber){ // continueSearching = updateStatesStep(&values, &statesSteps, &statesSteps, oNumber, xNumber, i); // }else{ continueSearching = updateStatesStep(&values, &statesSteps, &statesStepsTmp, &valuesReverse, &reverseStatesSteps, oNumber, xNumber, i); continueSearching = updateStatesStep(&valuesReverse, &reverseStatesSteps, &reverseStatesStepsTmp, &values, &statesSteps, xNumber, oNumber, i) || continueSearching; // } if (!continueSearching){ break; } } cout << "loop count " << i << endl; // save resutl to strage writeStatesSteps(&statesSteps, oNumber, xNumber); writeStatesSteps(&reverseStatesSteps, xNumber, oNumber); } void computeAllStatesStep(){ // compute from end(o+x=combinationSize) for(int total=combinationSize; total>=0;total--){ cout << "total = " << total << endl; for(int oNumber=0;oNumber<=total/2;oNumber++){ cout << "o number = " << oNumber << endl; int xNumber = total - oNumber; computeStatesStep(oNumber, xNumber); } } } int main(){ clock_t start = clock(); init(); computeAllStatesStep(); clock_t end = clock(); cout << "end : " << (double)(end - start)/ CLOCKS_PER_SEC << " sec" << endl; return 0; }
5a9c627ab50020fdb6b1be336d32c2f38cd31322
0810b81ad0b59c59de1cd50c279ecf7d79c24ecb
/src/file/file.cpp
722fecd6acbdb226b53c8ab0827f5c3ece3d243d
[]
no_license
fwindolf/cuda-image
be11fe59e6e476f46a3f3ec0167dafb1a5cae0d8
c3cc2d1b815e45c56edbd7af8d42dc38fe42957f
refs/heads/master
2020-05-19T01:31:40.252967
2020-01-05T15:57:45
2020-01-05T15:57:45
184,758,389
2
1
null
2019-06-19T14:08:15
2019-05-03T13:17:41
C++
UTF-8
C++
false
false
3,624
cpp
file.cpp
#include "cuimage/file/file.h" #define TINYEXR_IMPLEMENTATION #include "tinyexr.h" #include <iostream> using namespace cuimage; cv::Mat File::_readExr(const std::string& fileName) { EXRVersion exr_version; std::vector<float> image; int ret = ParseEXRVersionFromFile(&exr_version, fileName.c_str()); if (ret != 0) { std::cerr << "Invalid EXR file: " << fileName << std::endl; return cv::Mat(); } if (exr_version.multipart) { // must be multipart flag is true. std::cerr << "Invalid EXR file, " << fileName << " is multipart" << std::endl; return cv::Mat(); } // 2. Read EXR header EXRHeader exr_header; InitEXRHeader(&exr_header); const char* err = nullptr; ParseEXRHeaderFromFile(&exr_header, &exr_version, fileName.c_str(), &err); if (err) { std::cerr << "Parse EXR failed for file " << fileName << ", err: " << err << std::endl; FreeEXRErrorMessage(err); // free's buffer for an error message return cv::Mat(); } EXRImage exr_image; InitEXRImage(&exr_image); LoadEXRImageFromFile(&exr_image, &exr_header, fileName.c_str(), &err); if (err) { std::cerr << "Loading EXR failed for file " << fileName << ", err: " << err << std::endl; FreeEXRHeader(&exr_header); FreeEXRErrorMessage(err); // free's buffer for an error message return cv::Mat(); } // 3. Access image data // Copy image to vector if (!exr_header.tiled && exr_image.images) { if (exr_image.num_channels == 1) { // Row format (R, R, R, R, ... ) image.resize(exr_image.width * exr_image.height); float val; for (int i = 0; i < image.size(); i++) { val = reinterpret_cast<float**>(exr_image.images)[0][i]; if (val < 0 || val > 1e12) val = 0; // Add to array image.at(i) = val; } } else if (exr_image.num_channels == 3) { // Scanline format (RGBA, RGBA, ...) image.resize(exr_image.width * exr_image.height * 3); float val, val_r = 0, val_g = 0, val_b = 0; for (int i = 0; i < exr_image.width * exr_image.height; i++) { for (int c = 0; c < 3; c++) { std::string c_name = exr_header.channels[c].name; val = reinterpret_cast<float**>(exr_image.images)[c][i]; if (val < 0 || val > 1e12) val = 0; if (c_name == "R") val_r = val; else if (c_name == "G") val_g = val; else if (c_name == "B") val_b = val; } // Add to array image.at(3 * i + 0) = val_r; image.at(3 * i + 1) = val_g; image.at(3 * i + 2) = val_b; } } } else if (exr_header.tiled && exr_image.tiles) { // tiled format (R, R, ..., G, G ..., ...) std::cerr << "EXR in unsupported tiled format" << std::endl; return cv::Mat(); } else { std::cerr << "EXR file " << fileName << " has not/invalid content" << std::endl; return cv::Mat(); } return cv::Mat(exr_image.height, exr_image.width, CV_32FC(exr_image.num_channels), image.data()); }
5b24ed906d0df4e70234bfde8694606408e15a6e
0d1398465317a035399215f7bd67f7257da983ff
/SNAP/Logic/LevelSet/SNAPAdvectionFieldImageFilter.h
cbe55348fa9f21d146c3a8e6ef20f5eb9d0de17d
[]
no_license
mxgbs/ITKApps
9d0ef50fa3bfde2a4980e10dc9a11717b2158be6
568518371f0822abebfca763ebee2ba3ff97251d
refs/heads/master
2021-01-18T04:37:28.750169
2014-10-28T13:17:05
2014-10-28T13:17:05
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,028
h
SNAPAdvectionFieldImageFilter.h
/*========================================================================= Program: Insight Segmentation & Registration Toolkit Module: SNAPAdvectionFieldImageFilter.h Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) 2003 Insight Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/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. =========================================================================*/ #ifndef __SNAPAdvectionFieldImageFilter_h_ #define __SNAPAdvectionFieldImageFilter_h_ #include "itkCovariantVector.h" #include "itkImage.h" #include "itkImageToImageFilter.h" /** * \class SNAPAdvectionFieldImageFilter * \brief A filter used to compute the advection field in the SNAP level set * equation. */ template <class TInputImage, class TOutputValueType=float> class SNAPAdvectionFieldImageFilter: public itk::ImageToImageFilter< TInputImage, itk::Image< itk::CovariantVector<TOutputValueType, TInputImage::ImageDimension>, TInputImage::ImageDimension> > { public: /** Input image types */ typedef TInputImage InputImageType; typedef itk::SmartPointer<InputImageType> InputImagePointer; /** Standard class typedefs. */ typedef SNAPAdvectionFieldImageFilter Self; typedef itk::SmartPointer<Self> Pointer; typedef itk::SmartPointer<const Self> ConstPointer; /** Image dimension. */ itkStaticConstMacro(ImageDimension, unsigned int, TInputImage::ImageDimension); /** Output image types */ typedef itk::CovariantVector< TOutputValueType, itkGetStaticConstMacro(ImageDimension)> VectorType; typedef itk::Image< VectorType, itkGetStaticConstMacro(ImageDimension)> OutputImageType; typedef itk::SmartPointer<OutputImageType> OutputImagePointer; typedef itk::ImageToImageFilter<InputImageType,OutputImageType> Superclass; /** Method for creation through the object factory. */ itkNewMacro(Self); /** Set the power of g() by which the gradient is scaled */ itkSetMacro(Exponent,unsigned int); /** Get the power of g() by which the gradient is scaled */ itkGetMacro(Exponent,unsigned int); protected: SNAPAdvectionFieldImageFilter(); virtual ~SNAPAdvectionFieldImageFilter() {}; void PrintSelf(std::ostream& os, itk::Indent indent) const; /** Generate Data */ void GenerateData( void ); private: /** The g-scaling exponent */ unsigned int m_Exponent; }; #ifndef ITK_MANUAL_INSTANTIATION #include "SNAPAdvectionFieldImageFilter.txx" #endif #endif // __SNAPAdvectionFieldImageFilter_h_
6393f107ac0eef6964fd89f23808f86fe8490929
2d468433f1ecd2f0650bef8a5ee3b16460692097
/src/lib/utils/plugin_manager.hpp
e1ce2bfc59f22ca8080eaa37273eb3f11bacb4f0
[ "MIT" ]
permissive
hyrise-mp/hyrise
6819d45fa68f167a9d32c3351e83b1dc33ee9537
cefb5fb70dfc0a6e43f35d7dd098d7ac703d4602
refs/heads/master
2020-05-26T22:18:15.914031
2019-06-04T12:10:34
2019-06-04T12:10:34
188,396,488
2
0
MIT
2019-06-04T12:10:36
2019-05-24T09:46:14
C++
UTF-8
C++
false
false
1,579
hpp
plugin_manager.hpp
#pragma once #include <filesystem> #include <unordered_map> #include "types.hpp" #include "utils/abstract_plugin.hpp" #include "utils/singleton.hpp" #include "utils/string_utils.hpp" namespace opossum { using PluginHandle = void*; using PluginName = std::string; struct PluginHandleWrapper { PluginHandle handle; AbstractPlugin* plugin; }; class PluginManager : public Singleton<PluginManager> { friend class PluginManagerTest; friend class SingletonTest; public: void load_plugin(const std::filesystem::path& path); void unload_plugin(const PluginName& name); ~PluginManager(); // Deletes the entire PluginManager and creates a new one, used especially in tests. // This can lead to a lot of issues if there are still running tasks / threads that // want to access a resource. You should be very sure that this is what you want. // Have a look at base_test.hpp to see the correct order of resetting things. static void reset(); protected: friend class Singleton; PluginManager() {} const PluginManager& operator=(const PluginManager&) = delete; PluginManager& operator=(PluginManager&&) = default; std::unordered_map<PluginName, PluginHandleWrapper> _plugins; // This method is called during destruction and stops and unloads all currently loaded plugions. void _clean_up(); bool _is_duplicate(AbstractPlugin* plugin) const; const std::unordered_map<PluginName, PluginHandleWrapper>::iterator _unload_erase_plugin( const std::unordered_map<PluginName, PluginHandleWrapper>::iterator it); }; } // namespace opossum
b148a3862333d040618aa155f57aa18ef8ae4eb9
96ebe9f4ccba7c9fdd7acdecaa8216787598a93c
/EyerVideoWand/EyerWand/EyerWandVideoResource.cpp
db3e7f9f213e2ca696813f43de4fb8493ed12150
[]
no_license
yinhuiyao11/EyerVideoWand
51552599311cb57bae498bd27f7b6afcb1de597b
6c9b177f5dd8afc46ead980ff4a648531df6ae59
refs/heads/master
2023-01-02T23:46:21.247705
2020-04-09T13:12:56
2020-04-09T13:12:56
238,478,033
0
0
null
2020-11-05T03:08:31
2020-02-05T15:06:10
C++
UTF-8
C++
false
false
2,251
cpp
EyerWandVideoResource.cpp
#include "EyerWand.hpp" namespace Eyer { EyerWandVideoResource::EyerWandVideoResource() { } EyerWandVideoResource::~EyerWandVideoResource() { for(int i=0;i<decoderLineList.getLength();i++){ EyerVideoDecoderLine * decoderLine = nullptr; decoderLineList.find(i, decoderLine); if(decoderLine != nullptr){ delete decoderLine; } } decoderLineList.clear(); } int EyerWandVideoResource::GetVideoFrame(EyerAVFrame & avFrame, double ts) { // EyerLog("Deocde Line: %d\n", decoderLineList.getLength()); EyerVideoDecoderLine * decoderLine = nullptr; for(int i=0;i<decoderLineList.getLength();i++) { EyerVideoDecoderLine * dl = nullptr; decoderLineList.find(i, dl); if(ts >= dl->GetStartTime()){ decoderLine = dl; } } if(decoderLine == nullptr){ decoderLine = new EyerVideoDecoderLine(resPath, ts); decoderLineList.insertBack(decoderLine); } decoderLine->GetFrame(avFrame, ts); return 0; } int EyerWandVideoResource::GetVideoDuration(double & duration) { int finalRet = 0; Eyer::EyerAVReader reader(resPath); int videoStreamIndex = -1; int streamCount = 0; EyerAVStream avStream; int ret = reader.Open(); if(ret){ finalRet = -1; goto END; } streamCount = reader.GetStreamCount(); for(int i=0;i<streamCount;i++){ EyerAVStream stream; ret = reader.GetStream(stream, i); if(ret){ continue; } if(stream.GetStreamType() == EyerAVStreamType::STREAM_TYPE_VIDEO){ videoStreamIndex = i; } } if(videoStreamIndex < 0){ finalRet = -1; goto END; } ret = reader.GetStream(avStream, videoStreamIndex); if(ret){ finalRet = -1; goto END; } finalRet = 0; duration = avStream.GetDuration(); END: ret = reader.Close(); return finalRet; } }
d51acd093d964281bc01f2479d7cc39593894adc
675b48fea07692e7e4f709660af33261ba212711
/代码1/IOCPserver/IOCPserver/TcpSrv.h
427e76970ddafafc1be09beaa9eb3e3b579e4e83
[]
no_license
six-beauty/six_beauty
b939f41d64a85c9de23540c9231c1247cb546181
756c832f8c74412705eac3f9ededdf46e83e2fad
refs/heads/master
2021-01-21T02:28:10.832079
2015-08-27T05:59:26
2015-08-27T05:59:26
25,392,927
0
1
null
null
null
null
GB18030
C++
false
false
4,497
h
TcpSrv.h
#ifndef _TCPSRV_H #define _TCPSRV_H #include "StdAfx.h" #include<vector> #include<list> #include <winsock2.h> #include <MSWSock.h> #pragma comment(lib,"ws2_32.lib") #define SOCK_BUF_SIZE 8192 #define SERVERPORT 65001 using namespace std; typedef enum _operation_type { ACCEPT_TYPE, SEND_TYPE, RECV_TYPE, NULL_TYPE }OPERATION_TYPE; //定义完成端口中的单I/O数据结构体,每一个I/O操作对应一个_per_io_data typedef struct _per_io_data { OVERLAPPED s_overlapped; //系统用异步IO信息结构体 SOCKET s_socket; //本次I/O操作所使用的socket WSABUF s_databuf; //存储数据缓冲区,用来给重叠操作传递参数 char s_buffer[SOCK_BUF_SIZE];//对应WSABUF里的缓冲区 OPERATION_TYPE s_optype; //网络操作类型 //初始化 _per_io_data() { memset(&s_overlapped,0,sizeof(OVERLAPPED)); memset(&s_buffer,0,SOCK_BUF_SIZE); s_socket=INVALID_SOCKET; s_databuf.len=0; s_databuf.buf=s_buffer; s_optype=NULL_TYPE; } ~_per_io_data() { if(s_socket!=INVALID_SOCKET) { closesocket(s_socket); s_socket=INVALID_SOCKET; } } void ResetBuffer() { memset(&s_buffer,0,SOCK_BUF_SIZE); } }per_io_data,*p_per_io_data; //定义单句柄数据结构体,每个“句柄”对应一个socket,每个socket可以对应多个I/O操作 typedef struct _per_socket_data { SOCKET s_socket; //对应客户端的套接字 SOCKADDR_IN s_clientaddr; //对应客户端的地址 vector<p_per_io_data> s_vtiodata; //socket的I/O操作的数据结构体 //对于listensocket即本地socket,存放的是acceptIO操作 //对于clientsocket(客户端),存放recv和send的IO操作 _per_socket_data() { s_socket=INVALID_SOCKET; memset(&s_clientaddr,0,sizeof(s_clientaddr)); } ~_per_socket_data() { if(s_socket!=INVALID_SOCKET) { //循环删除客户端 for(vector<p_per_io_data>::iterator iter=s_vtiodata.begin();iter!=s_vtiodata.end();iter++) { delete *iter; iter=s_vtiodata.erase(iter); } //关闭socket closesocket(s_socket); } for(vector<p_per_io_data>::iterator iter=s_vtiodata.begin();iter!=s_vtiodata.end();) { delete *iter; //第一次解应用取得单I/O结构体地址,第二次取得结构体 iter=s_vtiodata.erase(iter); } }//~_per_socket_data; p_per_io_data add_new_iodata() { p_per_io_data newiodata=new per_io_data; s_vtiodata.push_back(newiodata); return newiodata; } void dele_iodata(p_per_io_data deledata) { for(vector<p_per_io_data>::iterator iter=s_vtiodata.begin();iter!=s_vtiodata.end();iter++) { if(*iter==deledata) { delete *iter; iter=s_vtiodata.erase(iter); } } } }per_socket_data,*p_per_socket_data; class TcpSrv { private: CRITICAL_SECTION m_cslock; //临界锁 HANDLE m_EndEvent; //结束事件 HANDLE m_completionport; //完成端口句柄 vector<per_socket_data*> lstclntdata; //客户端的socket链表,方便释放内存 int m_nThreads; //工作线程的个数 HANDLE *m_workthhdle; //工作线程句柄 per_socket_data* m_socketdata; //监听socketdata LPFN_ACCEPTEX m_lpAcceptEx; //acceptex函数的指针 LPFN_GETACCEPTEXSOCKADDRS m_lpGetAcceptExSockAddrs; //GetAcceptSockAddrs函数的指针 struct sockaddr_in m_localsockaddr; //本地地址 TcpSrv* m_this; //类的所有者 public: //构造函数 TcpSrv(): m_completionport(INVALID_HANDLE_VALUE), m_workthhdle(NULL), m_nThreads(0), lstclntdata(NULL), m_lpAcceptEx(NULL), m_lpGetAcceptExSockAddrs(NULL) { } //析构函数 //程序开始准备,加载动态库,创建完成端口,创建线程池 bool setout(); //初始化监听socket bool initlistensocket(); //启动程序 void startup() { setout(); initlistensocket(); } //关闭服务器 void closeIocp(); //投递异步accept请求 bool postaccept(p_per_io_data persockdata); //投递异步recv请求 bool postrecv(per_io_data* perIodata); //工作者线程 static DWORD WINAPI WorkThread(LPVOID lParam); //workthread线程accept处理函数 bool _doAccept(per_socket_data* psockdata,per_io_data* piodata); //workthread线程recv处理函数 bool _doRecv(per_socket_data* psockdata,per_io_data* piodata); //workthread线程send处理函数 // bool _doSend(per_socket_data* psockdata,per_io_data* piodata); //释放其中一个客户端的资源 void endconnect(per_socket_data* ppsocketdata); }; #endif
e43fb0573ece3ecfa38426e2b9c9f7dbb9959983
b9c61af231c6dd0278e72c36abab2ddda50a4389
/test_static.cpp
a8ec4a795238690e097c0af09186c950817cfbf7
[ "BSD-3-Clause", "BSD-2-Clause", "NCSA" ]
permissive
ContinuumIO/ispc
21e0a10d96a9e131c9947c60eec97624b657863a
f3089df0866ce8e699a6436e51f3c5534be01d7d
refs/heads/master
2023-03-23T00:32:22.671060
2012-02-07T19:11:40
2012-02-07T19:13:32
3,381,232
4
3
null
null
null
null
UTF-8
C++
false
false
5,074
cpp
test_static.cpp
/* Copyright (c) 2010-2011, Intel Corporation All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of Intel Corporation nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #if defined(_WIN32) || defined(_WIN64) #define ISPC_IS_WINDOWS #elif defined(__linux__) #define ISPC_IS_LINUX #elif defined(__APPLE__) #define ISPC_IS_APPLE #endif #ifdef ISPC_IS_WINDOWS #include <windows.h> #endif // ISPC_IS_WINDOWS #include <assert.h> #include <string.h> #include <stdio.h> #include <stdint.h> #ifdef ISPC_IS_LINUX #include <malloc.h> #endif extern "C" { extern int width(); extern void f_v(float *result); extern void f_f(float *result, float *a); extern void f_fu(float *result, float *a, float b); extern void f_fi(float *result, float *a, int *b); extern void f_du(float *result, double *a, double b); extern void f_duf(float *result, double *a, float b); extern void f_di(float *result, double *a, int *b); extern void result(float *val); void ISPCLaunch(void **handlePtr, void *f, void *d, int); void ISPCSync(void *handle); void *ISPCAlloc(void **handlePtr, int64_t size, int32_t alignment); } void ISPCLaunch(void **handle, void *f, void *d, int count) { *handle = (void *)0xdeadbeef; typedef void (*TaskFuncType)(void *, int, int, int, int); TaskFuncType func = (TaskFuncType)f; for (int i = 0; i < count; ++i) func(d, 0, 1, i, count); } void ISPCSync(void *) { } void *ISPCAlloc(void **handle, int64_t size, int32_t alignment) { *handle = (void *)0xdeadbeef; // and now, we leak... #ifdef ISPC_IS_WINDOWS return _aligned_malloc(size, alignment); #endif #ifdef ISPC_IS_LINUX return memalign(alignment, size); #endif #ifdef ISPC_IS_APPLE void *mem = malloc(size + (alignment-1) + sizeof(void*)); char *amem = ((char*)mem) + sizeof(void*); amem = amem + uint32_t(alignment - (reinterpret_cast<uint64_t>(amem) & (alignment - 1))); ((void**)amem)[-1] = mem; return amem; #endif } int main(int argc, char *argv[]) { int w = width(); assert(w <= 16); float returned_result[16]; for (int i = 0; i < 16; ++i) returned_result[i] = -1e20; float vfloat[16] = { 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16}; double vdouble[16] = { 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16}; int vint[16] = { 2,4,6,8,10,12,14,16,18,20,22,24,26,28,30,32 }; int vint2[16] = { 5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20}; float b = 5.; #if (TEST_SIG == 0) f_v(returned_result); #elif (TEST_SIG == 1) f_f(returned_result, vfloat); #elif (TEST_SIG == 2) f_fu(returned_result, vfloat, b); #elif (TEST_SIG == 3) f_fi(returned_result, vfloat, vint); #elif (TEST_SIG == 4) f_du(returned_result, vdouble, 5.); #elif (TEST_SIG == 5) f_duf(returned_result, vdouble, 5.f); #elif (TEST_SIG == 6) f_di(returned_result, vdouble, vint2); #else #error "Unknown or unset TEST_SIG value" #endif float expected_result[16]; memset(expected_result, 0, 16*sizeof(float)); result(expected_result); int errors = 0; for (int i = 0; i < w; ++i) { if (returned_result[i] != expected_result[i]) { #ifdef EXPECT_FAILURE // bingo, failed return 1; #else printf("%s: value %d disagrees: returned %f [%a], expected %f [%a]\n", argv[0], i, returned_result[i], returned_result[i], expected_result[i], expected_result[i]); ++errors; #endif // EXPECT_FAILURE } } #ifdef EXPECT_FAILURE // Don't expect to get here return 0; #else return errors > 0; #endif }
054d02c40a0ce00cadeee53f8eff6c457373f68d
4a86cf652383946f94ebae58b6c61781dc7ab2d8
/LeetCode/234回文链表.cpp
2bdb3e86cb9e3bde833ede2cd1d6573bc2e6debe
[]
no_license
liuyoude/My-Road-to-Algorithm
1149144b04938af246c29269e7c8a5c7d3b8eb04
b9016484c78b6d1558ca58072f44b45b014937db
refs/heads/main
2023-03-14T23:25:28.782635
2021-03-15T12:40:19
2021-03-15T12:40:19
315,302,263
0
0
null
null
null
null
GB18030
C++
false
false
2,160
cpp
234回文链表.cpp
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode() : val(0), next(nullptr) {} * ListNode(int x) : val(x), next(nullptr) {} * ListNode(int x, ListNode *next) : val(x), next(next) {} * }; */ /* 解法1:利用递归得到链表的逆序遍历 */ class Solution { public: ListNode* left; bool isPalindrome(ListNode* head) { left = head; return traverse(head); } bool traverse(ListNode* right){ if(right == nullptr) return true; bool res = traverse(right->next); // 逆序遍历链表,right从右向左,left从左向右 res = res && (left->val == right->val); left = left->next; return res; } }; /** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode() : val(0), next(nullptr) {} * ListNode(int x) : val(x), next(nullptr) {} * ListNode(int x, ListNode *next) : val(x), next(next) {} * }; */ /* 解法2: 快慢链表找中点,反转中点后半段链表 */ class Solution { public: bool isPalindrome(ListNode* head) { // 利用快慢指针找中点 ListNode *slow, *fast; slow = head; fast = head; while(fast != nullptr && fast->next != nullptr){ slow = slow->next; fast = fast->next->next; } //链表长为奇数时slow还需指向next if(fast != nullptr) slow = slow->next; // 反转slow后面的链表 ListNode* left = head; ListNode* right = reverse(slow); // 从终端对比原指针和翻转指针 while(right != nullptr){ if(left->val != right->val) return false; left = left->next; right = right->next; } return true; } ListNode* reverse(ListNode* head){ ListNode *pre, *cur; pre = nullptr; cur = head; while(cur != nullptr){ ListNode* next = cur->next; cur->next = pre; pre = cur; cur = next; } return pre; } };
c4367da610f5f572be809be5cb666c7a024b2ab6
775cde13c2acbfbd6a8857ebe3ea3c1399aecee2
/src/programmers/Balloon.cpp
432ba409e3c52f384d551714c525022031be3e8a
[]
no_license
goaldae/Algorithm
1e7d4328443e2ddc42015355a68e2bb167328c7f
2ac8cb0336012cceff9c8e747b967da7194df7fa
refs/heads/master
2023-04-20T07:13:54.214390
2023-04-06T10:47:02
2023-04-06T10:47:02
167,889,230
0
0
null
2019-03-24T05:35:23
2019-01-28T02:55:13
Java
UTF-8
C++
false
false
1,146
cpp
Balloon.cpp
#include <iostream> #include <string> #include <vector> #include <algorithm> using namespace std; bool cmp(pair<int, int> a, pair<int, int> b){ return a.second<b.second; } int solution(vector<int> a) { int answer = 0; if (a.size()<=2) return a.size(); //개수가 2이하면 다 살릴수있음 answer = 2; //숫자가 3개 이상이면 최소한 2개는 살림 pair<int, int> temp; vector<pair<int, int> > list; for(int i = 0; i<a.size(); i++){ temp.first = i; temp.second = a[i]; list.push_back(temp); } sort(list.begin(), list.end(), cmp); int l, r; if(list[0].first<list[1].first){ l = list[0].first; r = list[1].first; }else{ l = list[1].first; r = list[0].first; } //제일 작은 숫자 인덱스 l //두번째 작은 숫자 인덱스 r for(int i = 2; i<list.size(); i++){ int m = list[i].first; if(m<l){ //m<l<r 살림 answer++; l = m; }else if(m>r){ //m<l<r 살림 answer++; r = m; } } return answer; }
31e7a682eb65f40186e7cddce5f09c9007258d93
e07c972e474ade8bd95444df97342a47e7dcca25
/volt_gfx/include/volt/gfx/global_events/GFXEvents.hpp
e5d56604747c5477b01b53c254932f503b9b786e
[]
no_license
SirHall/volt_gfx
bbc1f82a538ac5767a586d88c681aaf65defb3cb
7d6827894cfe09feeb17caea1ab2e5668ae0b1da
refs/heads/master
2022-06-27T02:37:46.458293
2022-05-15T21:09:14
2022-05-15T21:09:14
217,846,126
0
0
null
null
null
null
UTF-8
C++
false
false
1,187
hpp
GFXEvents.hpp
#pragma once #ifndef VOLT_GFX_GLOBAL_EVENTS_GFXEVENTS_HPP #define VOLT_GFX_GLOBAL_EVENTS_GFXEVENTS_HPP #include "volt/gfx/global_events/GFXEventChar.hpp" #include "volt/gfx/global_events/GFXEventCursorEnter.hpp" #include "volt/gfx/global_events/GFXEventCursorPos.hpp" #include "volt/gfx/global_events/GFXEventDrop.hpp" #include "volt/gfx/global_events/GFXEventError.hpp" #include "volt/gfx/global_events/GFXEventFramebufferSize.hpp" #include "volt/gfx/global_events/GFXEventJoystick.hpp" #include "volt/gfx/global_events/GFXEventKey.hpp" #include "volt/gfx/global_events/GFXEventMonitor.hpp" #include "volt/gfx/global_events/GFXEventMouseButton.hpp" #include "volt/gfx/global_events/GFXEventScroll.hpp" #include "volt/gfx/global_events/GFXEventWindowClose.hpp" #include "volt/gfx/global_events/GFXEventWindowContentScale.hpp" #include "volt/gfx/global_events/GFXEventWindowFocus.hpp" #include "volt/gfx/global_events/GFXEventWindowIconify.hpp" #include "volt/gfx/global_events/GFXEventWindowMaximize.hpp" #include "volt/gfx/global_events/GFXEventWindowPos.hpp" #include "volt/gfx/global_events/GFXEventWindowRefresh.hpp" #include "volt/gfx/global_events/GFXEventWindowSize.hpp" #endif
b783059550b1f0a9751827f45827b7d0046ca02f
e3815d7ba7825e4e2e6bc81068d623c1cba53a40
/src/util/Async.hh
9b9f3e5578d1e39656fdb4a2bf43fbdc4f982126
[ "Apache-2.0" ]
permissive
couchbaselabs/BLIP-Cpp
22e4873a708b6b8b85c3b5d75d49b590d30d068a
a614b936d2e2561e430b3c9a22ba23c1d272722b
refs/heads/master
2023-09-06T05:13:27.721744
2022-03-09T03:53:51
2022-03-09T03:53:51
81,492,638
17
5
Apache-2.0
2020-03-03T02:46:29
2017-02-09T20:38:09
C++
UTF-8
C++
false
false
13,109
hh
Async.hh
// // Async.hh // // Copyright © 2018 Couchbase. 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. // #pragma once #include "RefCounted.hh" #include <cassert> #include <functional> namespace litecore { namespace actor { class Actor; /* Async<T> represents a result of type T that may not be available yet. This concept is also referred to as a "future". You can create one by first creating an AsyncProvider<T>, which is also known as a "promise", then calling its `asyncValue` method: Async<int> getIntFromServer() { Retained<AsyncProvider<int>> intProvider = Async<int>::provider(); sendServerRequestFor(intProvider); return intProvider->asyncValue(); } You can simplify this somewhat: Async<int> getIntFromServer() { auto intProvider = Async<int>::provider(); // `auto` is your friend sendServerRequestFor(intProvider); return intProvider; // implicit conversion to Async } The AsyncProvider reference has to be stored somewhere until the result is available. Then you call its setResult() method: int result = valueReceivedFromServer(); intProvider.setResult(result); Async<T> has a `ready` method that tells whether the result is available, and a `result` method that returns the result (or aborts if it's not available.) However, it does not provide any way to block and wait for the result. That's intentional: we don't want blocking! Instead, the way you work with async results is within an _asynchronous function_. ASYNCHRONOUS FUNCTIONS An asynchronous function is a function that can resolve Async values in a way that appears synchronous, but without actually blocking. It always returns an Async result (or void), since if the Async value it's resolving isn't available, the function itself has to return without (yet) providing a result. Here's what one looks like: Async<T> anAsyncFunction() { BEGIN_ASYNC_RETURNING(T) ... return t; END_ASYNC() } If the function doesn't return a result, it looks like this: void aVoidAsyncFunction() { BEGIN_ASYNC() ... END_ASYNC() } In between BEGIN and END you can "unwrap" Async values, such as those returned by other asynchronous functions, by calling asyncCall(). The first parameter is the variable to assign the result to, and the second is the expression returning the async result: asyncCall(int n, someOtherAsyncFunction()); `asyncCall` is a macro that hides some very weird control flow. What happens is that, if the Async value isn't yet available, `asyncCall` causes the enclosing function to return. (Obviously it returns an unavailable Async value.) It also registers as an observer of the value, so when its result does become available, the enclosing function _resumes_ right where it left off, assigns the result to the variable, and continues. ASYNC CALLS AND VARIABLE SCOPE `asyncCall()` places some odd restrictions on your code. Most importantly, a variable declared between the BEGIN/END cannot have a scope that extends across an `asyncCall`: int foo = ....; asyncCall(int n, someOtherAsyncFunction()); // ERROR: Cannot jump from switch... This is because the macro expansion of `asyncCall()` includes a `switch` label, and it's not possible to jump to that label (when resuming the async flow of control) skipping the variable declaration. If you want to use a variable across `asyncCall` scopes, you must declare it _before_ the BEGIN_ASYNC -- its scope then includes the entire async function: int foo; BEGIN_ASYNC_RETURNING(T) ... foo = ....; asyncCall(int n, someOtherAsyncFunction()); // OK! foo += n; Or if the variable isn't used after the next `asyncCall`, just use braces to limit its scope: { int foo = ....; } asyncCall(int n, someOtherAsyncFunction()); // OK! THREADING By default, an async method resumes immediately when the Async value it's waiting for becomes available. That means when the provider's `setResult` method is called, or when the async method returning that value finally returns a result. This is reasonable in single- threaded code. `asyncCall` is aware of Actors, however. So if an async Actor method waits, it will be resumed on that Actor's execution context. This ensures that the Actor's code runs single-threaded, as expected. */ #define BEGIN_ASYNC_RETURNING(T) \ return _asyncBody<T>([=](AsyncState &_async_state_) mutable -> T { \ switch (_async_state_.continueAt()) { \ default: #define BEGIN_ASYNC() \ _asyncBody<void>([=](AsyncState &_async_state_) mutable -> void { \ switch (_async_state_.continueAt()) { \ default: #define asyncCall(VAR, CALL) \ if (_async_state_._asyncCall(CALL, __LINE__)) return {}; \ case __LINE__: \ VAR = _async_state_.asyncResult<decltype(CALL)::ResultType>(); _async_state_.reset(); #define END_ASYNC() \ } \ }); class AsyncBase; class AsyncContext; template <class T> class Async; template <class T> class AsyncProvider; /** The state data passed to the lambda of an async function. */ class AsyncState { public: uint32_t continueAt() const {return _continueAt;} bool _asyncCall(const AsyncBase &a, int lineNo); template <class T> T&& asyncResult() { return ((AsyncProvider<T>*)_calling.get())->extractResult(); } void reset() {_calling = nullptr;} protected: fleece::Retained<AsyncContext> _calling; // What I'm blocked awaiting uint32_t _continueAt {0}; // label/line# to continue lambda at }; // Maintains the context/state of an async operation and its observer. // Abstract base class of AsyncProvider<T>. class AsyncContext : public fleece::RefCounted, protected AsyncState { public: bool ready() const {return _ready;} void setObserver(AsyncContext *p); void wakeUp(AsyncContext *async); protected: AsyncContext(Actor *actor); ~AsyncContext(); void start(); void _wait(); void _gotResult(); virtual void next() =0; bool _ready {false}; // True when result is ready fleece::Retained<AsyncContext> _observer; // Dependent context waiting on me Actor *_actor; // Owning actor, if any fleece::Retained<Actor> _waitingActor; // Actor that's waiting, if any fleece::Retained<AsyncContext> _waitingSelf; // Keeps `this` from being freed #if DEBUG public: static std::atomic_int gInstanceCount; #endif template <class T> friend class Async; friend class Actor; }; /** An asynchronously-provided result, seen from the producer side. */ template <class T> class AsyncProvider : public AsyncContext { public: template <class LAMBDA> explicit AsyncProvider(Actor *actor, const LAMBDA body) :AsyncContext(actor) ,_body(body) { } static fleece::Retained<AsyncProvider> create() { return new AsyncProvider; } Async<T> asyncValue() { return Async<T>(this); } void setResult(const T &result) { _result = result; _gotResult(); } const T& result() const { assert(_ready); return _result; } T&& extractResult() { assert(_ready); return std::move(_result); } private: AsyncProvider() :AsyncContext(nullptr) { } void next() override { _result = _body(*this); if (_calling) _wait(); else _gotResult(); } std::function<T(AsyncState&)> _body; // The async function body T _result {}; // My result }; // Specialization of AsyncProvider for use in functions with no return value (void). template <> class AsyncProvider<void> : public AsyncContext { public: template <class LAMBDA> explicit AsyncProvider(Actor *actor, const LAMBDA &body) :AsyncContext(actor) ,_body(body) { } static fleece::Retained<AsyncProvider> create() { return new AsyncProvider; } private: AsyncProvider() :AsyncContext(nullptr) { } void next() override { _body(*this); if (_calling) _wait(); else _gotResult(); } std::function<void(AsyncState&)> _body; // The async function body }; // base class of Async<T> class AsyncBase { public: explicit AsyncBase(const fleece::Retained<AsyncContext> &context) :_context(context) { } bool ready() const {return _context->ready();} protected: fleece::Retained<AsyncContext> _context; // The AsyncProvider that owns my value friend class AsyncState; }; /** An asynchronously-provided result, seen from the client side. */ template <class T> class Async : public AsyncBase { public: using ResultType = T; Async(AsyncProvider<T> *provider) :AsyncBase(provider) { } Async(const fleece::Retained<AsyncProvider<T>> &provider) :AsyncBase(provider) { } template <class LAMBDA> Async(Actor *actor, const LAMBDA& bodyFn) :Async( new AsyncProvider<T>(actor, bodyFn) ) { _context->start(); } /** Returns a new AsyncProvider<T>. */ static fleece::Retained<AsyncProvider<T>> provider() { return AsyncProvider<T>::create(); } const T& result() const {return ((AsyncProvider<T>*)_context.get())->result();} /** Invokes the callback when this Async's result becomes ready, or immediately if it's ready now. */ template <class LAMBDA> void wait(LAMBDA callback) { if (ready()) callback(result()); else (void) new AsyncWaiter(_context, callback); } // Internal class used by wait(), above class AsyncWaiter : public AsyncContext { public: template <class LAMBDA> AsyncWaiter(AsyncContext *context, LAMBDA callback) :AsyncContext(nullptr) ,_callback(callback) { _waitingSelf = this; _calling = context; _wait(); } protected: void next() override { _callback(asyncResult<T>()); _waitingSelf = nullptr; } private: std::function<void(T)> _callback; }; }; // Specialization of Async<> for functions with no result template <> class Async<void> : public AsyncBase { public: Async(AsyncProvider<void> *provider) :AsyncBase(provider) { } Async(const fleece::Retained<AsyncProvider<void>> &provider) :AsyncBase(provider) { } static fleece::Retained<AsyncProvider<void>> provider() { return AsyncProvider<void>::create(); } template <class LAMBDA> Async(Actor *actor, const LAMBDA& bodyFn) :Async( new AsyncProvider<void>(actor, bodyFn) ) { _context->start(); } }; /** Body of an async function: Creates an AsyncProvider from the lambda given, then returns an Async that refers to that provider. */ template <class T, class LAMBDA> Async<T> _asyncBody(const LAMBDA &bodyFn) { return Async<T>(nullptr, bodyFn); } } }
3bbc178c51cabd05a68c0cab649c810f7e5437d1
b69a21b62bcdab75ab24264b3354a1947acf5e6f
/client/clickedlineedit.cpp
69a0152d6f9ba3bf66faea85c8beb83272dd815c
[ "CC-BY-4.0", "MIT" ]
permissive
aernesto/moodbox_aka_risovaska
97ee1127e1ed7a2ddcc85079cab15c70b575d05f
5943452e4c7fc9e3c828f62f565cd2da9a040e92
refs/heads/master
2021-01-01T17:17:39.638815
2012-02-28T15:31:55
2012-02-28T15:31:55
null
0
0
null
null
null
null
UTF-8
C++
false
false
308
cpp
clickedlineedit.cpp
#include "clickedlineedit.h" namespace MoodBox { ClickedLineEdit::ClickedLineEdit(QWidget *parent) : QLineEdit(parent) { } ClickedLineEdit::~ClickedLineEdit() { } void ClickedLineEdit::mousePressEvent(QMouseEvent * event) { QLineEdit::mousePressEvent(event); selectAll(); } }
ec65e6488abc1983f171cb89add63c103e048ca7
80c585608b7bb36ef5653aec866819e0eb919cfa
/src/MobileTest/src/TestScopedLock.cpp
bd1b2808e6a6fbff2d47768180a78349e20e2ac6
[]
no_license
ARLM-Attic/peoples-note
109bb9539c612054d6ff2a4db3bdce84bad189c4
1e7354c66a9e2b6ccb8b9ee9c31314bfa4af482d
refs/heads/master
2020-12-30T16:14:51.727240
2013-07-07T09:56:03
2013-07-07T09:56:03
90,967,267
0
0
null
null
null
null
UTF-8
C++
false
false
757
cpp
TestScopedLock.cpp
#include "stdafx.h" #include "ScopedLock.h" #include "Test.h" struct Context { int marker; CRITICAL_SECTION section; }; DWORD WINAPI ScopedLockThread(void * param) { Context * context(reinterpret_cast<Context*>(param)); ScopedLock lock(context->section); context->marker = 1; return 0; } AUTO_TEST_CASE(TestScopedLock) { Context context; context.marker = 0; ::InitializeCriticalSection(&context.section); HANDLE otherThread(::CreateThread(NULL, 0, &ScopedLockThread, &context, CREATE_SUSPENDED, NULL)); { ScopedLock lock(context.section); ::ResumeThread(otherThread); ::Sleep(10); TEST_CHECK_EQUAL(context.marker, 0); } ::Sleep(10); TEST_CHECK_EQUAL(context.marker, 1); }
e6314d80fcde98b8308e218efce711852ec1f272
46d056a4f9f2b0c0c642bc9f78a43e77ed46fb43
/trail.cpp
b1a5fd052c845425e885c9c78aa421e4920b4089
[]
no_license
jiselectric/leet-code-solutions
036c30b6383312dd08031461ff8cd78340744b23
8936f9e37c57f065581daffe5af584d6320cbe35
refs/heads/master
2021-06-22T00:16:32.167519
2021-01-21T09:23:57
2021-01-21T09:23:57
177,428,908
0
0
null
null
null
null
UTF-8
C++
false
false
326
cpp
trail.cpp
#include <iostream> #include <math.h> using namespace std; int N; int fives = 5; int division = 1; int answer = 0; int main() { cin >> N; while(division > 0) { division = floor(N / fives); answer = answer + division; fives = fives * 5; } cout << answer; return answer; }
58d7b694e0721cf18531e2f2d8fd7a773e0d7809
769b013ceceb3080af71d58a0e36c5ea846e3e95
/payStub/main.cpp
2066fef9d2e34eb504f98a64a85568ec0ccde793
[]
no_license
gstrauch2/paystub
bede5abe6fb9e260403ae8929e2d1d7cb9f5866e
9a1c1d1695c3fad956fab3c2d3b149446100ab41
refs/heads/master
2021-04-29T18:34:52.618587
2018-02-16T00:53:06
2018-02-16T00:53:06
121,695,494
0
0
null
null
null
null
UTF-8
C++
false
false
1,481
cpp
main.cpp
/* George Strauch * formatted paystub * formats a monthly paystub * feb-14-2018 * */ #include <iostream> #include <iomanip> using namespace std; int main() { string strName = "George Strauch"; double dblGross = 20000.00; double dblFedTax = 0.0; // 15% double dblStateTax = 0.0; // 0% double dblssTax = 0.0; // 5.75% double dblMedTax = 0.0; // 2.75% double dblPension = 0.0; // 5% double dblHealth = 0.0; // 5% double dblNet = 0.0; dblFedTax = (dblGross/100)*15; dblStateTax = (dblGross/100)*0; dblssTax = (dblGross/100)*5.75; dblMedTax = (dblGross/100)*2.75; dblPension = (dblGross/100)*5; dblHealth = 75; dblNet = dblGross - dblFedTax - dblStateTax - dblssTax - dblMedTax - dblPension - dblHealth; cout << fixed; cout << setprecision(2); cout << left << strName << endl; cout << setw(30) << "dblGross pay" << setfill('.') << "$" << dblGross << endl; cout << setw(30) <<"Federal tax" << setfill('.') << "$" << dblFedTax << endl; cout << setw(30) << "State tax" << setfill('.') << "$" << dblStateTax << endl; cout << setw(30) << "Social security tax" << setfill('.') << "$" << dblssTax << endl; cout << setw(30) << "Pension plan" << setfill('.') << "$" << dblPension << endl; cout << setw(30) << "Health insurance" << setfill('.') << "$" << dblHealth << endl; cout << setw(30) << "Net pay" << setfill('.') << "$" << dblNet << endl; return 0; }
9c5f67cfdda8d44624834156864273138ec78798
1ec8fb145d9e0f228740ac78a3acd277ee2e0d2e
/1385D.cpp
8146fdb0da2041f0b993c8996b1fb47f03e8c48b
[]
no_license
Sadik1603075/code_forces
853aa8f827c3137c76fd4f43bba03b80544ba88f
a27e809eca383f702c48e29d9795d06d35e9b41b
refs/heads/master
2022-11-29T05:47:03.885339
2020-08-09T06:47:26
2020-08-09T06:47:26
286,182,808
0
0
null
null
null
null
UTF-8
C++
false
false
652
cpp
1385D.cpp
#include<bits/stdc++.h> using namespace std; #define ll long long ll arr[200003]; int main() { ll t,i,n,k,j; cin>>t; while(t--) { cin>>n; for(i=1;i<=n;i++) { scanf("%lld",&arr[i]); } k = arr[n]; for(i=n-1;i>=1;i--) { if(arr[i]>=k) k= arr[i]; else break; } k = arr[i]; for(i=i-1;i>=1;i--) { if(arr[i]<=k) k = arr[i]; else break; } if(i<0) i=0; cout<<i<<endl; } return 0; }
294c2b911a1f2110bf5be046f344471de380fb27
3ca6791f25d370ebfab30466e506f6d05d9ee16b
/src/RendererNotification.hpp
c711370d032a0cd0d348966fd8d1593846ff590c
[]
no_license
pderkowski/game
2269ea31cf5455a97da99ef2f08676226f9007f2
995078057934b2f820d5d86a4b67a10b720efcda
refs/heads/master
2021-05-27T18:11:23.040923
2014-09-13T15:57:27
2014-09-13T15:57:27
null
0
0
null
null
null
null
UTF-8
C++
false
false
255
hpp
RendererNotification.hpp
/* Copyright 2014 <Piotr Derkowski> */ #ifndef RENDERERNOTIFICATION_HPP_ #define RENDERERNOTIFICATION_HPP_ #include "SFML/Graphics/Rect.hpp" struct RendererNotification { sf::FloatRect displayedRectangle; }; #endif // RENDERERNOTIFICATION_HPP_
e0576d059b382d78c51f38645f65fca836d7b5c5
6f9b4790db69ddabaf36c00b057222541463a14c
/Breakout/BoxCollider.cpp
5a800abdc5c473bf19a4b48d3ac5390a1954c119
[]
no_license
Glynn-Taylor/Breakout
079e5e293f248fa049f4abb3e3c5955947a6f918
c933af1246098c2eaad4179016efaf2834e906b1
refs/heads/master
2021-01-18T21:37:32.979938
2017-04-02T21:41:52
2017-04-02T21:41:52
87,017,949
0
0
null
null
null
null
UTF-8
C++
false
false
1,993
cpp
BoxCollider.cpp
#ifndef BOX_COLLIDER #define BOX_COLLIDER #include "Collider.hpp" #include "BoxCollider.hpp" #include "GameObject.hpp" #include <cstdio> //A rectangular collider that can resolve collisions with other rectangular colliders. //Constructor BoxCollider::BoxCollider(const float width, const float height, const float length,GameObject& obj) : Collider(obj){ w=width; h=height; } //Generic method first called to determine collider types and resolve specific collider method CollisionInfo BoxCollider::CollidesWith(Collider const& other) const{ //Tell other collider to run it's BoxCollider collision function return other.CollidesWith(*this); } //Specific 'has collided with another box collider' function CollisionInfo BoxCollider::CollidesWith(BoxCollider const& other) const{ CollisionInfo collision; //implement AABB //(Ax,Ay) (Bx,By) // |------| |------| // | | | | // | | | | // |------| |------| // (AX,AY) (BX,BY) collision.collision=false; //Use a seperating axis test float xDiff = other.Collider::gameObject.x - Collider::gameObject.x; float pX = (other.Collider::w/2.0f + Collider::w/2.0f) - (xDiff < 0 ? -xDiff : xDiff); //If there is no x difference then we have collided if(pX<=0) return collision; float yDiff = other.Collider::gameObject.y - Collider::gameObject.y; float pY = (other.Collider::h/2.0f + Collider::h/2.0f) - (yDiff < 0 ? -yDiff : yDiff); //If there is no y difference then we have collided if(pY<=0) return collision; //Flag for notifying about collision collision.collision=true; //Get the hit normal //Resolve for smaller xdifference if(pX<pY){ float sx = xDiff < 0 ? -1 : 1; collision.side = xDiff < 0 ? XMINUS : XPLUS; collision.dx=pX*sx; collision.dy=0; //Resolve for smaller ydifference }else{ float sy = yDiff < 0 ? -1 : 1; collision.side = yDiff < 0 ? YMINUS : YPLUS; collision.dy = pY*sy; collision.dx=0; } //Return the result of the test return collision; } #endif
d2cacc3582a1f384036335cadb74d8c980b08f8c
ab06aa4ac12a8290b1246078f28ab540ceb9e660
/s09e03_cpp/codigo.cpp
ef17dccc4f912155e863d99f3959e1059cd88389
[]
no_license
flavio-barros/fup-2020.2-turma6
add631538a60bce723099e0a1b18c8aafa7d2806
382c18444afe8e9727ba7d1e2543c5e3701c3fdb
refs/heads/master
2023-03-08T11:36:27.382103
2021-02-23T18:37:33
2021-02-23T18:37:33
317,796,778
2
0
null
null
null
null
UTF-8
C++
false
false
515
cpp
codigo.cpp
#include <cstdio> // #include <stdbool.h> #include <iostream> using namespace std; string juntar(string one, string two){ return one + two; } int main(){ int x = 0; float f = 0.0f; int vet[5] = {5, 4, 3, 2, 1}; bool value = true; (void) value;//ele nao dar warning de nao utilizada (void) vet; cin >> x >> f; cout << "o x eh " << x << "\n"; printf("%03d %06.2f\n", x, f); string nome; cin >> nome; nome += " eh lindao"; nome == "David"; std::sort() }
2f9c1449fbd38cb5af5fda302e88d6d51421c609
73266ea6be2de149a4700798b221bd4c79525604
/CPP Modules/00/ex01/Phonebook.hpp
73d9e0673f25c662e9d0b7e76bb76be8f790636f
[]
no_license
Caceresenzo/42
de90b0262b573d4056102ad04ed0f6fbef169858
df1e14c019994202da0abbe221455f1a6ee291e4
refs/heads/master
2023-08-15T06:14:08.625075
2023-08-13T17:19:00
2023-08-13T17:19:00
220,007,175
92
36
null
null
null
null
UTF-8
C++
false
false
1,356
hpp
Phonebook.hpp
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* Phonebook.hpp :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: ecaceres <marvin@42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/12/04 11:52:55 by ecaceres #+# #+# */ /* Updated: 2019/12/04 11:52:59 by ecaceres ### ########.fr */ /* */ /* ************************************************************************** */ #ifndef PHONEBOOK_HPP # define PHONEBOOK_HPP # define ERR_PHONEBOOK_FULL "The Phonebook is full." # define ERR_SEARCH_INVALID_INDEX_INPUT "Invalid input." # define ERR_SEARCH_OUT_OF_BOUNDS "Input out of bounds." # define MAX_CONTACT 8 # define ASK "?> " # define ASK_CONTACT_INFO " ?> " # define ASK_INDEX "Index ?> " # define DISPLAY_CONTACT_INFO ": " # define CMD_ADD "ADD" # define CMD_SEARCH "SEARCH" # define CMD_EXIT "EXIT" #endif /* PHONEBOOK_HPP_ */
57111357c3aac05259cbe9c1ecfc7fcd14b7e09d
192fd8f3017356222af0b86682b64435a8e69e90
/lab7/GroupedShapes/Picture.h
158c8514208548d44679e749b1f989d50e553049
[]
no_license
Tandyru/ood-labs
d5ecfe9a0169e8607f3cad8b4bea54a88c1b9ff8
7c9fc19599eb37014d997e5a9a0dd5439acaf4e6
refs/heads/master
2021-07-15T18:21:25.802606
2019-02-07T18:24:49
2019-02-07T18:24:49
147,715,235
0
0
null
null
null
null
UTF-8
C++
false
false
113
h
Picture.h
#pragma once #include "../GroupedShapesLib/Picture.h" #include <memory> std::unique_ptr<CPicture> GetPicture();
4309cbdff8841e937f42faf4a3ea3762585c0a7e
1dff02275f30fe1b0c5b4f15ddd8954cae917c1b
/ugene/src/plugins/biostruct3d_view/src/BioStruct3DViewPlugin.cpp
0da77c95b19926656bbba33cf9611230c8a5458b
[ "MIT" ]
permissive
iganna/lspec
eaba0a5de9cf467370934c6235314bb2165a0cdb
c75cba3e4fa9a46abeecbf31b5d467827cf4fec0
refs/heads/master
2021-05-05T09:03:18.420097
2018-06-13T22:59:08
2018-06-13T22:59:08
118,641,727
0
0
null
null
null
null
UTF-8
C++
false
false
6,522
cpp
BioStruct3DViewPlugin.cpp
/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2012 UniPro <ugene@unipro.ru> * http://ugene.unipro.ru * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "BioStruct3DViewPlugin.h" #include "BioStruct3DSplitter.h" #include "BioStruct3DGLWidget.h" #include <U2Core/GObject.h> #include <U2Core/BaseDocumentFormats.h> #include <U2Core/DocumentModel.h> #include <U2Core/GObjectTypes.h> #include <U2Core/DNASequenceObject.h> #include <U2Core/BioStruct3DObject.h> #include <U2Gui/MainWindow.h> #include <U2Core/DocumentSelection.h> #include <U2View/AnnotatedDNAView.h> #include <U2View/ADVSequenceObjectContext.h> #include <U2View/ADVConstants.h> #include <U2View/ADVSingleSequenceWidget.h> #include <U2Gui/GUIUtils.h> #include <U2Core/LoadRemoteDocumentTask.h> #include <QtGui/QMessageBox> #include <QtGui/QMenu> namespace U2 { /*! * \mainpage BioStruct3D Viewer Plugin Documentation * * \section viewer Introduction * * BioStruct3D Viewer is a macromolecular viewing / editing tool. * It is activated whenever UGENE loads document that contains BioStruct3DObject. * * * \subsection main Main Classes * * plugin classes: * - BioStruct3DGLWidget : Widget for rendering 3d representations of macromolecular structure. * - BioStruct3DSplitter : Multiple glWidgets layout and manipulation * - GLFrame : Class for manipulating the 3d viewpoint * * plugin interfaces: * - BioStruct3DGLRenderer : General interface for structure 3d graphical styles * - BioStruct3DColorScheme : Interface for coloring atoms, bonds, etc. * * */ extern "C" Q_DECL_EXPORT Plugin* U2_PLUGIN_INIT_FUNC() { if (AppContext::getMainWindow()) { BioStruct3DViewPlugin* plug = new BioStruct3DViewPlugin(); return plug; } return NULL; } BioStruct3DViewPlugin::BioStruct3DViewPlugin() : Plugin(tr("3D Structure Viewer"), tr("Visualizes 3D structures of biological molecules.")) { // Init plugin view context viewContext = new BioStruct3DViewContext(this); viewContext->init(); } BioStruct3DViewPlugin::~BioStruct3DViewPlugin() { } BioStruct3DViewContext::BioStruct3DViewContext(QObject* p) : GObjectViewWindowContext(p, ANNOTATED_DNA_VIEW_FACTORY_ID) { } void BioStruct3DViewContext::initViewContext(GObjectView* v) { AnnotatedDNAView* av = qobject_cast<AnnotatedDNAView*>(v); U2SequenceObject* dna=av->getSequenceInFocus()->getSequenceObject(); Document* doc = dna->getDocument(); QList<GObject*> biostructObjs = doc->findGObjectByType(GObjectTypes::BIOSTRUCTURE_3D); if (biostructObjs.isEmpty()) { return; } QList<ADVSequenceWidget*> seqWidgets = av->getSequenceWidgets(); foreach(ADVSequenceWidget* w, seqWidgets) { ADVSingleSequenceWidget* aw = qobject_cast<ADVSingleSequenceWidget*>(w); if (aw!=NULL) { aw->setDetViewCollapsed(true); aw->setOverviewCollapsed(true); } } foreach(GObject* obj, biostructObjs) { v->addObject(obj); } } bool BioStruct3DViewContext::canHandle(GObjectView* v, GObject* o) { Q_UNUSED(v); bool res = qobject_cast<BioStruct3DObject*>(o) != NULL; return res; } void BioStruct3DViewContext::onObjectAdded(GObjectView* view, GObject* obj) { //todo: add sequence & all objects associated with sequence to the view? BioStruct3DObject* obj3d = qobject_cast<BioStruct3DObject*>(obj); if (obj3d == NULL || view == NULL) { return; } AnnotatedDNAView* av = qobject_cast<AnnotatedDNAView*>(view); BioStruct3DSplitter* splitter = NULL; if (splitterMap.contains(view)) { splitter = splitterMap.value(view); } else { splitter = new BioStruct3DSplitter(getClose3DViewAction(view), av); } av->insertWidgetIntoSplitter(splitter); splitter->addObject(obj3d); splitterMap.insert(view,splitter); } void BioStruct3DViewContext::onObjectRemoved(GObjectView* v, GObject* obj) { BioStruct3DObject* obj3d = qobject_cast<BioStruct3DObject*>(obj); if (obj3d == NULL) { return; } BioStruct3DSplitter* splitter = splitterMap.value(v); bool close = splitter->removeObject(obj3d); if (close) { splitter->close(); //unregister3DView(v,splitter); } } void BioStruct3DViewContext::unregister3DView(GObjectView* view, BioStruct3DSplitter* splitter) { assert(splitter->getChildWidgets().isEmpty()); splitter->close(); AnnotatedDNAView* av = qobject_cast<AnnotatedDNAView*>(view); av->unregisterSplitWidget(splitter); splitterMap.remove(view); splitter->deleteLater(); } QAction* BioStruct3DViewContext::getClose3DViewAction(GObjectView* view) { QList<QObject*> resources = viewResources.value(view); foreach(QObject* r, resources) { GObjectViewAction* a= qobject_cast<GObjectViewAction*>(r); if (a!=NULL) { return a; } } QAction* a = new GObjectViewAction(this, view, tr("Close 3D Structure Viewer")); connect(a, SIGNAL(triggered()), SLOT(sl_close3DView())); resources.append(a); return a; } void BioStruct3DViewContext::sl_close3DView() { GObjectViewAction* action = qobject_cast<GObjectViewAction*>(sender()); GObjectView* ov = action->getObjectView(); QList<GObject*> objects = ov->getObjects(); foreach(GObject* obj, objects) { if (obj->getGObjectType() == GObjectTypes::BIOSTRUCTURE_3D) { ov->removeObject(obj); } } } void BioStruct3DViewContext::sl_windowClosing(MWMDIWindow* w) { GObjectViewWindow *gvw = qobject_cast<GObjectViewWindow*>(w); if (gvw) { GObjectView *view = gvw->getObjectView(); // safe to remove: splitter will be deleted with ADV splitterMap.remove(view); } GObjectViewWindowContext::sl_windowClosing(w); } }//namespace
e47479e7cfa28f0dcc35193b06942878394535e3
1a4ca41081ec7889152912c66606747e5b03b822
/Algorithms/SymbolicToCompare/SymbolicCode/gen3_Jc_dot.cc
ff51814d3e1d05093b4b35e6a30445efc53eebe5
[]
no_license
yonchien/RobotDynamicsAndControl
57df50e51f44c2124bca67141650b5c40f910843
4dc61cea42dabe570808b76ea20c43c4a21b7287
refs/heads/main
2023-07-24T09:34:29.364118
2021-05-04T12:27:36
2021-05-04T12:27:50
null
0
0
null
null
null
null
UTF-8
C++
false
false
6,474
cc
gen3_Jc_dot.cc
/* * Automatically Generated from Mathematica. * Fri 30 Apr 2021 09:00:25 GMT-04:00 */ #ifdef MATLAB_MEX_FILE #include <stdexcept> #include <cmath> #include<math.h> /** * Copied from Wolfram Mathematica C Definitions file mdefs.hpp * Changed marcos to inline functions (Eric Cousineau) */ inline double Power(double x, double y) { return pow(x, y); } inline double Sqrt(double x) { return sqrt(x); } inline double Abs(double x) { return fabs(x); } inline double Exp(double x) { return exp(x); } inline double Log(double x) { return log(x); } inline double Sin(double x) { return sin(x); } inline double Cos(double x) { return cos(x); } inline double Tan(double x) { return tan(x); } inline double ArcSin(double x) { return asin(x); } inline double ArcCos(double x) { return acos(x); } inline double ArcTan(double x) { return atan(x); } /* update ArcTan function to use atan2 instead. */ inline double ArcTan(double x, double y) { return atan2(y,x); } inline double Sinh(double x) { return sinh(x); } inline double Cosh(double x) { return cosh(x); } inline double Tanh(double x) { return tanh(x); } const double E = 2.71828182845904523536029; const double Pi = 3.14159265358979323846264; const double Degree = 0.01745329251994329576924; inline double Sec(double x) { return 1/cos(x); } inline double Csc(double x) { return 1/sin(x); } #endif /* * Sub functions */ static void output1(double *p_output1,const double *var1,const double *var2) { double t1096; double t1170; double t1172; double t1207; double t1100; double t1176; double t1180; double t1225; double t1226; double t1227; double t1231; double t1232; double t1239; double t1241; double t1243; double t1244; double t1246; double t1245; double t1249; double t1251; double t1253; double t1257; double t1258; double t1315; double t1318; double t1319; double t1342; double t1343; double t1350; double t1278; double t1292; double t1293; double t1263; double t1265; double t1268; double t1273; double t1297; double t1299; double t1332; double t1334; double t1335; double t1321; double t1323; double t1327; double t1330; double t1336; double t1338; double t1351; double t1362; double t1370; t1096 = Cos(var1[0]); t1170 = Sin(var1[0]); t1172 = -0.01*t1170; t1207 = 0.01*t1096; t1100 = -0.05*t1096; t1176 = t1100 + t1172; t1180 = var2[0]*t1176; t1225 = -0.05*t1170; t1226 = t1207 + t1225; t1227 = var2[0]*t1226; t1231 = 0.05*t1096; t1232 = t1231 + t1172; t1239 = var2[0]*t1232; t1241 = 0.05*t1170; t1243 = t1207 + t1241; t1244 = var2[0]*t1243; t1246 = Sin(var1[1]); t1245 = Cos(var1[2]); t1249 = t1096*t1245*t1246; t1251 = Cos(var1[1]); t1253 = Sin(var1[2]); t1257 = t1096*t1251*t1253; t1258 = t1249 + t1257; t1315 = t1245*t1170*t1246; t1318 = t1251*t1170*t1253; t1319 = t1315 + t1318; t1342 = t1245*t1246; t1343 = t1251*t1253; t1350 = t1342 + t1343; t1278 = t1251*t1245*t1170; t1292 = -1.*t1170*t1246*t1253; t1293 = t1278 + t1292; t1263 = 0.25*t1096*t1246; t1265 = 0.25*t1258; t1268 = t1263 + t1265; t1273 = 0.25*t1251*t1170; t1297 = 0.25*t1293; t1299 = t1273 + t1297; t1332 = -1.*t1096*t1251*t1245; t1334 = t1096*t1246*t1253; t1335 = t1332 + t1334; t1321 = 0.25*t1170*t1246; t1323 = 0.25*t1319; t1327 = t1321 + t1323; t1330 = -0.25*t1096*t1251; t1336 = 0.25*t1335; t1338 = t1330 + t1336; t1351 = 0.25*var2[2]*t1350; t1362 = 0.25*var2[2]*t1293; t1370 = 0.25*var2[2]*t1335; p_output1[0]=0; p_output1[1]=t1180; p_output1[2]=t1227; p_output1[3]=0; p_output1[4]=0; p_output1[5]=0; p_output1[6]=0; p_output1[7]=0; p_output1[8]=0; p_output1[9]=0; p_output1[10]=t1239; p_output1[11]=t1244; p_output1[12]=0; p_output1[13]=0; p_output1[14]=0; p_output1[15]=0; p_output1[16]=0; p_output1[17]=0; p_output1[18]=0; p_output1[19]=t1180; p_output1[20]=t1227; p_output1[21]=0; p_output1[22]=0; p_output1[23]=0; p_output1[24]=0; p_output1[25]=0; p_output1[26]=0; p_output1[27]=0; p_output1[28]=t1239; p_output1[29]=t1244; p_output1[30]=0; p_output1[31]=0; p_output1[32]=0; p_output1[33]=0; p_output1[34]=0; p_output1[35]=0; p_output1[36]=0; p_output1[37]=t1299*var2[0] + t1268*var2[1] + 0.25*t1258*var2[2]; p_output1[38]=t1338*var2[0] + t1327*var2[1] + 0.25*t1319*var2[2]; p_output1[39]=t1351 + (0.25*t1246 + 0.25*t1350)*var2[1]; p_output1[40]=t1362 + t1268*var2[0] + t1299*var2[1]; p_output1[41]=t1370 + t1327*var2[0] + t1338*var2[1]; p_output1[42]=t1351 + 0.25*t1350*var2[1]; p_output1[43]=t1362 + 0.25*t1258*var2[0] + 0.25*t1293*var2[1]; p_output1[44]=t1370 + 0.25*t1319*var2[0] + 0.25*t1335*var2[1]; } #ifdef MATLAB_MEX_FILE #include "mex.h" /* * Main function */ void mexFunction( int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[] ) { size_t mrows, ncols; double *var1,*var2; double *p_output1; /* Check for proper number of arguments. */ if( nrhs != 2) { mexErrMsgIdAndTxt("MATLAB:MShaped:invalidNumInputs", "Two input(s) required (var1,var2)."); } else if( nlhs > 1) { mexErrMsgIdAndTxt("MATLAB:MShaped:maxlhs", "Too many output arguments."); } /* The input must be a noncomplex double vector or scaler. */ mrows = mxGetM(prhs[0]); ncols = mxGetN(prhs[0]); if( !mxIsDouble(prhs[0]) || mxIsComplex(prhs[0]) || ( !(mrows == 1 && ncols == 3) && !(mrows == 3 && ncols == 1))) { mexErrMsgIdAndTxt( "MATLAB:MShaped:inputNotRealVector", "var1 is wrong."); } mrows = mxGetM(prhs[1]); ncols = mxGetN(prhs[1]); if( !mxIsDouble(prhs[1]) || mxIsComplex(prhs[1]) || ( !(mrows == 1 && ncols == 3) && !(mrows == 3 && ncols == 1))) { mexErrMsgIdAndTxt( "MATLAB:MShaped:inputNotRealVector", "var2 is wrong."); } /* Assign pointers to each input. */ var1 = mxGetPr(prhs[0]); var2 = mxGetPr(prhs[1]); /* Create matrices for return arguments. */ plhs[0] = mxCreateDoubleMatrix((mwSize) 3, (mwSize) 15, mxREAL); p_output1 = mxGetPr(plhs[0]); /* Call the calculation subroutine. */ output1(p_output1,var1,var2); } #else // MATLAB_MEX_FILE #include "gen3_Jc_dot.hh" namespace SymExpression { void gen3_Jc_dot_raw(double *p_output1, const double *var1,const double *var2) { // Call Subroutines output1(p_output1, var1, var2); } } #endif // MATLAB_MEX_FILE
0bda8dade7f9aadb734fb96c3652c36b1657e9f6
d619fae80686082f47146413d9ef86fb2c1e322b
/Src/Modules/Perception/BallPerceptors/CNSBallPerceptor/BallPerceptor2017.h
1bf07c4038379cbca8b0ed32f96b72c7f96dd91c
[]
no_license
Handsome-Computer-Organization/walkingEngine
ab7d4382a76d2eeb11858bab8dd063abe47c1be3
9fa39c9a75d7a7ea8b3b9f2526ddd2ce346b8ac5
refs/heads/master
2021-06-18T14:41:45.470558
2017-05-11T06:19:47
2017-05-11T06:35:10
null
0
0
null
null
null
null
UTF-8
C++
false
false
10,170
h
BallPerceptor2017.h
/** * @file BallPerceptor.cpp * This file declares a module that provides a ball percept of the new oficial Robocup SPL ball. * @author Gabriel Azocar * @author Pablo Cano * UChile Robotics Team * * Partially based on B-Human's ball perceptor of the coderelease 2014 * whose authors are: * @author Colin Graf * @author marcel * @author Florian Maaß * @author Thomas Röfer */ #pragma once #define IS_FULL_SIZE true #include "Tools/Module/Module.h" #include "Tools/Math/Transformation.h" #include "Representations/Configuration/FieldDimensions.h" #include "Representations/Modeling/RobotPose.h" #include "Representations/Perception/ImagePreprocessing/ECImage.h" #include "Representations/Perception/ImagePreprocessing/BodyContour.h" #include "Representations/Perception/ImagePreprocessing/CameraMatrix.h" #include "Representations/Perception/ImagePreprocessing/ImageCoordinateSystem.h" #include "Representations/Perception/ImagePreprocessing/FieldColor.h" #include "Representations/Perception/BallPercepts/BallPercept.h" #include "Representations/Perception/BallPercepts/BallPercept2017.h" #include "Representations/Perception/BallPercepts/BallSpots.h" //#include "Representations/Perception/PlayersPercept.h" //#include "Representations/Perception/FieldBoundary.h" //#include "Representations/Modeling/BallModel.h" //#include "Representations/Modeling/Odometer.h" //#include "Representations/Perception/BallSpots.h" //#include "Representations/Perception/LinePercept.h" #include "Tools/Streams/AutoStreamable.h" #include "Tools/Debugging/DebugImages.h" #include <math.h> #include <limits.h> #include <iostream> //#include "Dependence/ImageToolbox.h" #include <chrono> MODULE(BallPerceptor2017, { , REQUIRES(FieldDimensions), REQUIRES(ECImage), REQUIRES(BodyContour), REQUIRES(CameraMatrix), REQUIRES(ImageCoordinateSystem), REQUIRES(CameraInfo), REQUIRES(FieldColor), REQUIRES(BallSpots), REQUIRES(BallPercept2017), // REQUIRES(RobotPose), // REQUIRES(Odometer), // REQUIRES(TJArkVision), // REQUIRES(LinePercept), // REQUIRES(BlackAndWhiteBallPercept), // REQUIRES(BallSpots), // REQUIRES(PlayersPercept), USES(RobotPose), PROVIDES(BallPercept), DEFINES_PARAMETERS( {, (float)(0.4f) pointsRotation, (float)(2) scanTolerance, (float)(1.8) upRadiusTolerance, (float)(0.6f) downRadiusTolerance, (int)(6) searchEdgePointsTolerance, (float)(0.2f) minNumOfTransitions, (float)(0.2f) greenThrld, (int)(20) gradient, (float)(1.8f) regionSizeTolerance, (int)(11) minValidEdges, (float)(1.f) radiusGap, (float)(2.f) areaFactor, }), }); /** * The class scales the input and output data if full size images * are avalable. */ class BallPerceptorScaler2017 : public BallPerceptor2017Base { private: protected: CameraInfo theCameraInfo; BallSpots theBallSpots; ImageCoordinateSystem theImageCoordinateSystem; /** * The only access to image pixels. * @param y The y coordinate of the pixel in the range defined in theCameraInfo. * @param y The y coordinate of the pixel in the range defined in theCameraInfo. * @param The pixel as a temporary object. Do not use yCbCrPadding of that pixel. */ const Image::Pixel getPixel(int y, int x) const { // if(theCameraInfo.camera == CameraInfo::upper && IS_FULL_SIZE) // return theImage.getFullSizePixel(y, x); // else // return theImage[y][x]; } /** * Update the copies of input representations that contain data * that might have to be scaled up. * Must be called in each cycle before any computations are performed. */ void scaleInput(); /** * Scale down the output if required. * @param ballPercept The ball percept the fields of which might be scaled. */ void scaleOutput(BallPercept& ball) const; /** * Scale down a single value if required. * This is only supposed to be used in debug drawings. * @param value The value that might be scaled. * @return The scaled value. */ template<typename T> T scale(T value) const { if(theCameraInfo.camera == CameraInfo::upper && IS_FULL_SIZE) return value / (T) 2; else return value; } }; class BallPerceptor2017 : public BallPerceptorScaler2017 { public: //Constructor BallPerceptor2017(); static const int NUM_STAR_SCANLINES = 16; static const int NUM_STAR_SCANLINE_CANDIDATES = 2 * NUM_STAR_SCANLINES; const float maxBallRadius = 120; private: class BallPoint { public: Vector2i step; Vector2i start; Vector2i point; Vector2f pointf; bool atBorder; bool isValid; BallPoint() : atBorder(false), isValid(false) {} }; struct Region { bool horizontal; Vector2i init; Vector2i end; int index; bool areIntersected(Region& other) { if(horizontal == other.horizontal) { if(horizontal){ return std::abs(init.y() - other.init.y()) < 3 && init.x() <= other.end.x() && end.x() >= other.init.x(); } else{ return std::abs(init.x() - other.init.x()) < 3 && init.y() <= other.end.y() && end.y() >= other.init.y(); } } else{ if(horizontal){ return (other.init.x() >= init.x() && other.init.x() < end.x()) && (init.y() >= other.init.y() && init.y() <= other.end.y()); } else{ return (init.x() >= other.init.x() && init.x() < other.end.x()) && (other.init.y() >= init.y() && other.init.y() <= end.y()); } } } }; struct Ball { int x, y, radius, q; bool found; }; struct candidateBall { Ball ball; float disError; float score; }; struct circle { float x, y, r, q; }; struct Pentagon { Pentagon() : width(INT_MAX,0), heigth(INT_MAX,0), points(0){} void addRegion(Region& region) { center += region.init + region.end; points += 2; width.x() = region.init.x() < width.x() ? region.init.x() : width.x(); width.y() = region.end.x() > width.y() ? region.end.x() : width.y(); heigth.x() = region.init.y() < heigth.x() ? region.init.y() : heigth.x(); heigth.y() = region.end.y() > heigth.y() ? region.end.y() : heigth.y(); } void isPentagon(float maxArea, float radius) { float totalHeigh = float(heigth.y() - heigth.x()); float totalWidth = float(width.y() - width.x()); if(totalHeigh > 2*radius/3 || totalWidth > 2*radius/3 || totalHeigh < 2 || totalWidth < 2) { valid = false; return; } float factor = totalHeigh/totalWidth; if(factor < 0.5f || factor > 2.f) { valid = false; return; } area = totalWidth*totalHeigh; valid = area < maxArea; } void setCenter() { center = center / points; } Vector2i center; Vector2i width; Vector2i heigth; int points; float area; bool valid; }; //Update Functions void update(BallPercept& ballPercept); //Verification Functions void searchBallFromBallSpots(BallPercept2017& ballPercept); bool analyzeBallSpot(const BallSpot ballSpot, BallPercept2017& ballPercept); bool calculateBallOnField(BallPercept& ballPercept) const; bool checkBallOnField(BallPercept2017 ball) const; //Cascade Functions bool checkBallSpot(const BallSpot& ballSpot); bool checkRegionSizes(const BallSpot& ballSpot); bool searchEdgePoints(const BallSpot& ballSpot,const ColorRGBA& color); bool isBallFromPoints(); bool checkNewRadius(); bool checkBallNear(BallPercept2017& ballPercept); bool isRobotNear(); bool searchValidEdges(); bool checkGreenInside(); bool checkPentagons(); //Pentagon Functions void scanLine(Vector2i step, Vector2i origin, Vector2i end); void mergeRegions(); void changeIndex(int from, int to); int createPentagons(); int validatePentagons(); //Debug Functions void drawBall(const Vector2f& pos) const; bool drawError(BallSpot ballSpot, std::string message); bool showRegionSizes(const BallSpot& ballSpot); Ball fitBall(const Vector2f& center, const float searchR, Vector2f& ballColor); // circle ransacCircle(point_2d points[NUM_STAR_SCANLINE_CANDIDATES], // float maxDistEdge); circle getCircle(float x1, float y1, float x2,float y2, float x3, float y3); // float searchEdges(const Image& img, point_2d pos, // point_2d points[NUM_STAR_SCANLINES * 2], // Vector2f& ballColor,float searchR); Ball newBall(float x, float y, float radius, bool found, float q); // float guessDiameter(point_2d points[NUM_STAR_SCANLINES]); circle newCircle(float x, float y, float r,float q); bool classifyBalls2(Ball & b); // bool possibleGreen(const Image::Pixel& p) const; // // bool possibleGrayScale(const Image::Pixel& p) const; // // bool isWhite(const Image::Pixel* p) const; // // ColorTable::Colors determineColor(const Image::Pixel& p) const; float tansig(float per,float ref); int myThreshold1(int centerX, int centerY, int radius); void save_bw(Vector2f c, float radius); void countAround(const Vector2i& center, float radius, int& greenCount, int& nonWhiteCount, int& avgGreenY) const; void countAtRadius(const Vector2i& center, float radius, int& greenCount, int& nonWhiteCount, int& avgGreenY) const; bool checkInnerGreen(Vector2i center, float r) const; bool classifyBalls3(BallPerceptor2017::Ball & b); // Internal Variables double imageHeigth, imageWidth, approxRadius; float radius; int validBallPoints; bool ballValidity; Vector2f center, pentagonsCenter; BallPoint ballPoints[16]; std::vector<Region> regions; std::vector<Pentagon> pentagons; std::vector<BallPercept2017> balls; std::vector<candidateBall> possibleBalls; int greenAround; };
311bba9c79bb52e25428f099aacee0746c2f6a4c
6b2a8dd202fdce77c971c412717e305e1caaac51
/solutions_2453486_1/C++/Junkbot/tic.cpp
dd10a984de93abb0c8d949c58f66da84fbff377e
[]
no_license
alexandraback/datacollection
0bc67a9ace00abbc843f4912562f3a064992e0e9
076a7bc7693f3abf07bfdbdac838cb4ef65ccfcf
refs/heads/master
2021-01-24T18:27:24.417992
2017-05-23T09:23:38
2017-05-23T09:23:38
84,313,442
2
4
null
null
null
null
UTF-8
C++
false
false
1,819
cpp
tic.cpp
#include <cstdio> const int MAX_N = 5; int T; int N = 4; char board[MAX_N][MAX_N]; bool check(char target) { // go down for(int j=0;j<N;j++) { bool win = true; for(int i=0;i<N;i++) { if(board[i][j] != target && board[i][j] != 'T') { win = false; break; } } if(win) { return true; } } // go right for(int i=0;i<N;i++) { bool win = true; for(int j=0;j<N;j++) { if(board[i][j] != target && board[i][j] != 'T') { win = false; break; } } if(win) { return true; } } // diagonals bool win = true; for(int i=0;i<N;i++) { if(board[i][i] != target && board[i][i] != 'T') { win = false; break; } } if(win) { return true; } win = true; for(int i=0;i<N;i++) { if(board[i][N-i-1] != target && board[i][N-i-1] != 'T') { win = false; break; } } if(win) { return true; } return false; } bool isFull(void) { for(int i=0;i<N;i++) { for(int j=0;j<N;j++) { if(board[i][j] == '.') { return false; } } } return true; } int main() { scanf("%d",&T); for(int z=1;z<=T;z++) { printf("Case #%d: ", z); for(int i=0;i<N;i++) { scanf(" %s ",board[i]); } if(check('X')) { printf("X won\n"); } else if(check('O')) { printf("O won\n"); } else if(isFull()) { printf("Draw\n"); } else { printf("Game has not completed\n"); } } return 0; }
7c4309de9dd0ed0f52d60cb9ded7b25888447247
c1e10ac7a355a39067954918d62dc5f28df3f8f8
/tutorial/ruud_van_der_pass_openmp/04_omp_methods/11_omp_get_wtick.cpp
fb06621093cd9b0502243bebaf19f110f52e6087
[]
no_license
grayasm/git-main
be46c568c3b9edcfe9d583bac8aba1302932b0d1
88ef1393b241383a75ade3e8677238536fe95afa
refs/heads/master
2023-08-05T03:49:36.674748
2023-08-03T14:57:55
2023-08-03T14:57:55
32,255,990
12
5
null
null
null
null
UTF-8
C++
false
false
831
cpp
11_omp_get_wtick.cpp
/* double omp_get_wtick(void); Gets the timer precision, i.e., the number of seconds between two successive clock ticks. */ #include <stdio.h> #include <omp.h> #ifdef WIN32 #include <windows.h> #define sleep(a) Sleep(a*1000) #else //linux #include <unistd.h> #endif //WIN32 int main(int argc, char** argv) { double start = omp_get_wtime (); sleep (1); double end = omp_get_wtime (); double wtick = omp_get_wtick (); printf ("start = %.16g\n" "end = %.16g\n" "diff = %.16g\n", start, end, end - start); printf ("wtick = %.16g\n" "1/wtick = %.16g\n", wtick, 1.0/wtick); return 0; } /* $> ./10_omp_get_wtime start = 31352.738506449 end = 31353.738726453 diff = 1.000220003999857 wtick = 1e-09 1/wtick = 999999999.9999999 */
3acb6fbc70a210cc96a6aa65c084920015ba8f9f
4134a01c4befc9cfa56d42ee81147f861ddf3565
/zoompangraphicsview.h
3a333a06d452a784ebd656834d29200cc6b2abbf
[]
no_license
grefab/msa
b1119aa80c926083630a5aa6c41387fd93d83e6e
cf9793e8cdccb9d7e19ea14a147279cddcf07de3
refs/heads/master
2021-01-10T18:31:17.122238
2014-07-31T03:40:31
2014-07-31T03:40:31
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,224
h
zoompangraphicsview.h
#ifndef ZOOMPANGRAPHICSVIEW_H #define ZOOMPANGRAPHICSVIEW_H #include <QGraphicsView> class ZoomPanGraphicsView : public QGraphicsView { Q_OBJECT public: explicit ZoomPanGraphicsView(QWidget *parent = 0); signals: void loadFileRequest(QString filename); void enlargeCircle(); void shrinkCircle(); void addCircle(QPointF point); void removeCircle(QPointF point); void showCircle(); void hideCircle(); void circlePosChanged(QPointF point); protected: void keyPressEvent(QKeyEvent* event); void keyReleaseEvent(QKeyEvent* event); void wheelEvent(QWheelEvent* event); void mousePressEvent(QMouseEvent* event); void mouseMoveEvent(QMouseEvent* event); void mouseReleaseEvent(QMouseEvent* event); void dragEnterEvent(QDragEnterEvent *event); void dragMoveEvent(QDragMoveEvent *event); void dragLeaveEvent(QDragLeaveEvent * event); void dropEvent(QDropEvent *event); private: enum class MouseMode { Move, Interact }; private: void updateMouseMode(Qt::KeyboardModifiers modifiers); void updateCursor(); QPoint lastMousePos_; MouseMode mouseMode_ = MouseMode::Move; }; #endif // ZOOMPANGRAPHICSVIEW_H
37869fc99b546a92e43f9a424c21b894e90cbee6
ec728f4ddc541bba92ed1ca3cd7b091fe6f4d582
/binarySearch.cpp
a206950ca1beb7bd71bba439adf788ecf5acd78e
[]
no_license
Ash-jo121/coding-blocks
8488e2f1d42916626d4f3ad3eb0d9139e2e23dc4
ad3c6600fba2dd1f54a798bbbf6499ed75a07ad7
refs/heads/master
2023-01-30T12:43:40.633663
2020-12-01T13:21:40
2020-12-01T13:21:40
262,059,033
0
0
null
null
null
null
UTF-8
C++
false
false
749
cpp
binarySearch.cpp
#include<bits/stdc++.h> #define int long long #define MOD 1000000007 #define N 1000001 #define vi vector<int> #define pb push_back using namespace std; int binarySearch(int a[], int n, int key) { int s = 0; int e = n - 1; while (s <= e) { int mid = (s + e) / 2; if (a[mid] == key) { return mid; } else if (a[mid] > key) { e = mid - 1; } else { s = mid + 1; } } return -1; } int32_t main() { ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); #ifndef ONLINE_JUDGE freopen("input.txt", "r", stdin); freopen("output.txt", "w", stdout); #endif int n; cin >> n; int a[n] = {0}; for (int i = 0; i < n; i++) { cin >> a[i]; } int key; cin >> key; int index = binarySearch(a, n, key); return 0; }
d059a9a7af962ce77ae95d0636b7c18c312dc5d8
010279e2ba272d09e9d2c4e903722e5faba2cf7a
/catboost/cuda/cuda_lib/fwd.h
9e05b9f5c8a9ab0433a4abdf01147b66ba01fe46
[ "Apache-2.0" ]
permissive
catboost/catboost
854c1a1f439a96f1ae6b48e16644be20aa04dba2
f5042e35b945aded77b23470ead62d7eacefde92
refs/heads/master
2023-09-01T12:14:14.174108
2023-09-01T10:01:01
2023-09-01T10:22:12
97,556,265
8,012
1,425
Apache-2.0
2023-09-11T03:32:32
2017-07-18T05:29:04
Python
UTF-8
C++
false
false
461
h
fwd.h
#pragma once #include <util/generic/fwd.h> namespace NCudaLib { enum class EPtrType : int { CudaDevice, CudaHost, // pinned cuda memory Host // CPU, non-pinned }; } namespace NCudaLib { template <class T, class TMapping, EPtrType Type = EPtrType::CudaDevice> class TCudaBuffer; template <class T> class TDistributedObject; class TMirrorMapping; class TSingleMapping; class TStripeMapping; }
2fc9da68826f48d90e52af3605be86628a6deca5
0f09b036d90e5a85da1856516893422c476bce46
/Samples/DirectXA4/RenderMesh.cpp
24bcb9610b74268466353467cfc414e3f675b66a
[ "LicenseRef-scancode-unknown-license-reference", "MIT" ]
permissive
longde123/simdrast
034aac5aca5b13c7ad332ba865f9f6bc036a992e
9f2cbdd039fb3c7779adcc8a320d492e5db69e92
refs/heads/master
2016-09-05T09:09:57.641242
2015-05-17T11:03:08
2015-05-17T11:03:08
35,762,669
5
3
null
null
null
null
UTF-8
C++
false
false
3,816
cpp
RenderMesh.cpp
// // RenderMesh.cpp // DirectXA4 // // Created by Rasmus Barringer on 2013-06-07. // Copyright (c) 2013 Rasmus Barringer. All rights reserved. // #include "RenderMesh.h" RenderMesh::RenderMesh(fx::Mesh* mesh) : mesh(mesh) { for (size_t i = 0; i < mesh->textures.size(); ++i) textures.push_back(new Texture(mesh->textures[i])); for (size_t i = 0; i < mesh->drawCalls.size(); ++i) { const fx::Mesh::DrawCall& source = mesh->drawCalls[i]; DrawCall* drawCall = new DrawCall(); drawCall->texture = mesh->drawCalls[i].texture; D3D11_BUFFER_DESC bd = { 0 }; bd.Usage = D3D11_USAGE_DEFAULT; bd.ByteWidth = sizeof(fx::Mesh::VertexAttributes) * source.vertexCount; bd.BindFlags = D3D11_BIND_VERTEX_BUFFER; bd.CPUAccessFlags = 0; D3D11_SUBRESOURCE_DATA initData = { 0 }; initData.pSysMem = &source.attributes[0]; DX_THROW_ON_FAIL(DxContext::getDevice()->CreateBuffer(&bd, &initData, &drawCall->vertexBuffer)); bd.Usage = D3D11_USAGE_DEFAULT; bd.ByteWidth = sizeof(unsigned) * source.indexCount; bd.BindFlags = D3D11_BIND_INDEX_BUFFER; bd.CPUAccessFlags = 0; initData.pSysMem = source.indices; DX_THROW_ON_FAIL(DxContext::getDevice()->CreateBuffer(&bd, &initData, &drawCall->indexBuffer)); drawCall->indexCount = source.indexCount; drawCalls.push_back(drawCall); } } const D3D11_INPUT_ELEMENT_DESC* RenderMesh::layout() const { static const D3D11_INPUT_ELEMENT_DESC layout[] = { { "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0 }, { "NORMAL", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 12, D3D11_INPUT_PER_VERTEX_DATA, 0 }, { "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, 24, D3D11_INPUT_PER_VERTEX_DATA, 0 }, { 0 }, }; return layout; } void RenderMesh::renderOpaque() { for (size_t i = 0; i < mesh->sortedDrawCalls.size(); ++i) { unsigned idx = (unsigned)(mesh->sortedDrawCalls[i] - &mesh->drawCalls[0]); DrawCall& drawCall = *drawCalls[idx]; if (drawCall.texture != fx::Mesh::noTexture) { if (mesh->textures[drawCall.texture]->hasAlpha()) continue; textures[drawCall.texture]->bind(0); } else { ID3D11ShaderResourceView* views[] = { 0 }; DxContext::getContext()->PSSetShaderResources(0, 1, views); } UINT stride = sizeof(fx::Mesh::VertexAttributes); UINT offset = 0; ID3D11Buffer* buffers[] = { drawCall.vertexBuffer, }; DxContext::getContext()->IASetVertexBuffers(0, 1, buffers, &stride, &offset); DxContext::getContext()->IASetIndexBuffer(drawCall.indexBuffer, DXGI_FORMAT_R32_UINT, 0); DxContext::getContext()->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST); DxContext::getContext()->DrawIndexed(drawCall.indexCount, 0, 0); } } void RenderMesh::renderTransparent() { for (size_t i = 0; i < mesh->sortedDrawCalls.size(); ++i) { unsigned idx = (unsigned)(mesh->sortedDrawCalls[i] - &mesh->drawCalls[0]); DrawCall& drawCall = *drawCalls[idx]; if (drawCall.texture == fx::Mesh::noTexture) continue; if (!mesh->textures[drawCall.texture]->hasAlpha()) continue; textures[drawCall.texture]->bind(0); UINT stride = sizeof(fx::Mesh::VertexAttributes); UINT offset = 0; ID3D11Buffer* buffers[] = { drawCall.vertexBuffer, }; DxContext::getContext()->IASetVertexBuffers(0, 1, buffers, &stride, &offset); DxContext::getContext()->IASetIndexBuffer(drawCall.indexBuffer, DXGI_FORMAT_R32_UINT, 0); DxContext::getContext()->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST); DxContext::getContext()->DrawIndexed(drawCall.indexCount, 0, 0); } } RenderMesh::~RenderMesh() { for (size_t i = 0; i < textures.size(); ++i) delete textures[i]; for (size_t i = 0; i < drawCalls.size(); ++i) delete drawCalls[i]; }
62addd4d87ac31709e6f5681147e96e627a28555
4dedede14d78cc6e54c443e3f065f7d7a706f943
/src/gui/glrand.h
d059ce41e0632ef17305ae1f687abba233084d38
[]
no_license
se4u/manifold
2bf01787a5c76cfee7f8c7512126e9dde8d0aa33
dd32a9a0354eb9c90649c23cbed38e2afcc178f8
refs/heads/master
2020-04-12T07:06:59.869705
2017-04-22T02:18:09
2017-04-22T02:18:09
null
0
0
null
null
null
null
UTF-8
C++
false
false
28,407
h
glrand.h
/* * @Author: kmrocki@us.ibm.com * @Date: 2017-03-20 10:09:39 * @Last Modified by: kmrocki@us.ibm.com * @Last Modified time: 2017-03-31 14:17:10 */ #ifndef __GLPLOT_H__ #define __GLPLOT_H__ #include <nanogui/window.h> #include <nanogui/layout.h> #include <nanogui/glcanvas.h> #include <nanogui/label.h> #include <nanogui/entypo.h> #include <nanogui/toolbutton.h> #include <nanogui/slider.h> #include <gui/gldata.h> // nvgCreateImageA #include <gl/tex.h> #define POINT_SHADER_NAME "datapoint_shader" #define POINT_FRAG_FILE "./src/glsl/datapoint.f.glsl" #define POINT_VERT_FILE "./src/glsl/datapoint.v.glsl" #define POINT_TEX_SHADER_NAME "datapoint_tex_shader" #define POINT_TEX_FRAG_FILE "./src/glsl/tex_point.f.glsl" #define POINT_TEX_GEOM_FILE "./src/glsl/tex_point.g.glsl" #define POINT_TEX_VERT_FILE "./src/glsl/tex_point.v.glsl" #define CAM_SHADER_NAME "cam_shader" #define CAM_FRAG_FILE "./src/glsl/cam.f.glsl" #define CAM_GEOM_FILE "./src/glsl/cam.g.glsl" #define CAM_VERT_FILE "./src/glsl/cam.v.glsl" #define RAY_SHADER_NAME "ray_shader" #define RAY_FRAG_FILE "./src/glsl/ray.f.glsl" #define RAY_GEOM_FILE "./src/glsl/ray.g.glsl" #define RAY_VERT_FILE "./src/glsl/ray.v.glsl" #define BOX_SHADER_NAME "box_shader" #define BOX_FRAG_FILE "./src/glsl/surf_box.f.glsl" #define BOX_GEOM_FILE "./src/glsl/surf_box.g.glsl" // #define BOX_GEOM_FILE "./src/glsl/boxgrid.g.glsl" #define BOX_VERT_FILE "./src/glsl/surf_box.v.glsl" class Plot : public nanogui::GLCanvas { public: Plot ( Widget *parent, std::string _caption, const Eigen::Vector2i &w_size, int i, PlotData *plot_data, bool transparent = false, bool _keyboard_enabled = false, bool _mouse_enabled = false, bool _show_rays = false, GLFWwindow *w = nullptr, NVGcontext *nvg = nullptr, float _fovy = 67.0f, const Eigen::Vector3f _camera = Eigen::Vector3f(0.0f, 0.0f, 5.0f), const Eigen::Vector3f _rotation = Eigen::Vector3f(0.0f, 0.0f, 0.0f), const Eigen::Vector3f _box_size = Eigen::Vector3f(1.0f, 1.0f, 1.0f) , bool _ortho = false, int record_intvl = 0, const std::string r_prefix = "") : nanogui::GLCanvas ( parent, transparent ) { GLCanvas::setSize (w_size); glfw_window = w; keyboard_enabled = _keyboard_enabled; mousemotion_enabled = _mouse_enabled; show_rays = _show_rays; vg = nvg; data = nullptr; setBackgroundColor ( nanogui::Color ( 64, 64, 64, 64 ) ); setDrawBorder ( true ); setVisible ( true ); forward = Eigen::Vector3f (0.0f, 0.0f, -1.0f); raydir = forward; right = Eigen::Vector3f ( 1.0f, 0.0f, 0.0f); up = Eigen::Vector3f (0.0f, 1.0f, 0.0f); index = i; caption = _caption; bind_data(plot_data); translation.setZero(); total_translation.setZero(); total_rotation.setZero(); init_camera(_fovy, _camera, _rotation, _ortho); box_size = _box_size; init_shaders(); record_interval = record_intvl; record_prefix = r_prefix; tic = glfwGetTime(); m_arcball.setSize ( w_size ); model_scale = Eigen::Vector3f(1, 1, 1); tools = new nanogui::Widget(this); tools->setLayout(new nanogui::GroupLayout(0, 0, 0, 0)); nanogui::Widget *arrows = new nanogui::Widget(tools); arrows->setLayout(new nanogui::GridLayout(nanogui::Orientation::Horizontal, 4, nanogui::Alignment::Middle, 2, 2)); nanogui::Button *b; Eigen::Vector2i bsize = Eigen::Vector2i(20, 20); nanogui::Color bcolor = nanogui::Color(192, 128, 0, 25); nanogui::Color ccolor = nanogui::Color(64, 128, 32, 25); b = arrows->add<nanogui::Button>("", ENTYPO_ICON_TRIANGLE_LEFT); b->setFixedSize(bsize); b->setBackgroundColor(bcolor); b->setCallback([&] { translation[0] -= cam_speed; }); b->setTooltip("left"); b = arrows->add<nanogui::Button>("", ENTYPO_ICON_TRIANGLE_DOWN); b->setFixedSize(bsize); b->setBackgroundColor(bcolor); b->setCallback([&] { translation[1] -= cam_speed; }); b->setTooltip("down"); b = arrows->add<nanogui::Button>("", ENTYPO_ICON_TRIANGLE_UP); b->setFixedSize(bsize); b->setBackgroundColor(bcolor); b->setCallback([&] { translation[1] += cam_speed; }); b->setTooltip("up"); b = arrows->add<nanogui::Button>("", ENTYPO_ICON_TRIANGLE_RIGHT); b->setFixedSize(bsize); b->setBackgroundColor(bcolor); b->setCallback([&] { translation[0] += cam_speed; }); b->setTooltip("right"); nanogui::Widget *views = new nanogui::Widget(tools); views->setLayout(new nanogui::GridLayout(nanogui::Orientation::Horizontal, 4, nanogui::Alignment::Middle, 2, 2)); b = views->add<nanogui::Button>("", ENTYPO_ICON_PLUS); b->setFlags(nanogui::Button::RadioButton); b->setFixedSize(bsize); b->setBackgroundColor(ccolor); b->setPushed(coord_type == 0); b->setCallback([&]() { std::cout << "Coords 0: " << std::endl; coord_type = 0;}); b = views->add<nanogui::Button>("", ENTYPO_ICON_CD); b->setFlags(nanogui::Button::RadioButton); b->setFixedSize(bsize); b->setPushed(coord_type == 1); b->setBackgroundColor(ccolor); b->setCallback([&]() { std::cout << "Coords 1: " << std::endl; coord_type = 1;}); b = views->add<nanogui::Button>("", ENTYPO_ICON_GLOBE); b->setFlags(nanogui::Button::RadioButton); b->setFixedSize(bsize); b->setPushed(coord_type == 2); b->setBackgroundColor(ccolor); b->setCallback([&]() { std::cout << "Coords 2: " << std::endl; coord_type = 2;}); b = views->add<nanogui::Button>("", ENTYPO_ICON_SWEDEN); b->setFlags(nanogui::Button::ToggleButton); b->setFixedSize(bsize); b->setBackgroundColor(ccolor); b->setPushed(show_box); b->setChangeCallback([&](bool state) { std::cout << "Grid off/on " << std::endl; show_box = state; }); nanogui::Widget *shader_tools = new nanogui::Widget(tools); shader_tools->setLayout(new nanogui::GridLayout(nanogui::Orientation::Horizontal, 4, nanogui::Alignment::Middle, 2, 2)); b = shader_tools->add<nanogui::Button>("", ENTYPO_ICON_MONITOR); b->setFlags(nanogui::Button::ToggleButton); b->setFixedSize(bsize); b->setPushed(use_textures); b->setChangeCallback([&](bool state) { std::cout << "Textures: " << state << std::endl; use_textures = state;}); b = shader_tools->add<nanogui::Button>("", ENTYPO_ICON_HAIR_CROSS); b->setFlags(nanogui::Button::ToggleButton); b->setFixedSize(bsize); b->setPushed(show_rays); b->setChangeCallback([&](bool state) { std::cout << "Show Rays: " << state << std::endl; show_rays = state;}); b = shader_tools->add<nanogui::Button>("", ENTYPO_ICON_KEYBOARD); b->setFlags(nanogui::Button::ToggleButton); b->setFixedSize(bsize); b->setPushed(keyboard_enabled); b->setChangeCallback([&](bool state) { std::cout << "Textures: " << state << std::endl; keyboard_enabled = state;}); b = shader_tools->add<nanogui::Button>("", ENTYPO_ICON_MOUSE); b->setFlags(nanogui::Button::ToggleButton); b->setFixedSize(bsize); b->setPushed(mousemotion_enabled); b->setChangeCallback([&](bool state) { std::cout << "Mouse: " << state << std::endl; mousemotion_enabled = state;}); nanogui::Widget *sliders = new nanogui::Widget(tools); sliders->setLayout(new nanogui::GridLayout(nanogui::Orientation::Horizontal, 2, nanogui::Alignment::Middle, 0, 0)); new nanogui::Label(sliders, "FOV", "sans-bold", 7); nanogui::Slider *slider = new nanogui::Slider(sliders); slider->setValue(0.5f); slider->setFixedWidth(80); slider->setCallback([&](float value) { fovy = (value * 170.0f); std::cout << "fovy: " << fovy << std::endl; }); new nanogui::Label(sliders, "CAM", "sans-bold", 7); slider = new nanogui::Slider(sliders); slider->setValue(cam_speed); slider->setFixedWidth(80); slider->setCallback([&](float value) { cam_speed = value; std::cout << "cam speed: " << cam_speed << std::endl; cam_angular_speed = (cam_speed / 1000.0f ) * 360.0f / M_PI; }); new nanogui::Label(sliders, "MAG", "sans-bold", 7); slider = new nanogui::Slider(sliders); slider->setValue(0.5f); slider->setFixedWidth(80); slider->setCallback([&](float value) { float s = powf(10, ((value - 0.5f) * 4.0f)); model_scale = Eigen::Vector3f(s, s, s); std::cout << "scale: " << model_scale << std::endl; }); new nanogui::Label(sliders, "SZ", "sans-bold", 7); slider = new nanogui::Slider(sliders); slider->setValue(0.2f); slider->setFixedWidth(80); slider->setCallback([&](float value) { float s = value * 10.0f; pt_size = s; std::cout << "pt size: " << pt_size << std::endl; }); new nanogui::Label(sliders, "A", "sans-bold", 7); slider = new nanogui::Slider(sliders); slider->setValue(0.7f); slider->setFixedWidth(80); slider->setCallback([&](float value) { alpha = value; std::cout << "alpha: " << alpha << std::endl; }); tools->setPosition({w_size[0] - 91, 0}); } void init_shaders() { m_pointShader = new nanogui::GLShader(); m_pointShader->initFromFiles ( POINT_SHADER_NAME, POINT_VERT_FILE, POINT_FRAG_FILE ); m_pointTexShader = new nanogui::GLShader(); m_pointTexShader->initFromFiles ( POINT_TEX_SHADER_NAME, POINT_TEX_VERT_FILE, POINT_TEX_FRAG_FILE, POINT_TEX_GEOM_FILE ); m_cubeShader = new nanogui::GLShader(); m_cubeShader->initFromFiles ( BOX_SHADER_NAME, BOX_VERT_FILE, BOX_FRAG_FILE, BOX_GEOM_FILE ); size_t tex_size = 64; Eigen::Matrix<unsigned char, Eigen::Dynamic, Eigen::Dynamic> rgba_image = Eigen::Matrix<unsigned char, Eigen::Dynamic, Eigen::Dynamic>::Ones(tex_size, tex_size * 4) * 16; // textures.emplace_back ( std::pair<int, std::string> ( nvgCreateImageA ( vg, 512, 512, NVG_IMAGE_GENERATE_MIPMAPS, ( unsigned char * ) rgba_image.data() ), "" ) ); textures.emplace_back ( std::pair<int, std::string> ( nvgCreateImageRGBA ( vg, tex_size, tex_size, NVG_IMAGE_NEAREST, ( unsigned char * ) rgba_image.data() ), "" ) ); m_camShader = new nanogui::GLShader(); m_camShader->initFromFiles ( CAM_SHADER_NAME, CAM_VERT_FILE, CAM_FRAG_FILE, CAM_GEOM_FILE ); m_rayShader = new nanogui::GLShader(); m_rayShader->initFromFiles ( RAY_SHADER_NAME, RAY_VERT_FILE, RAY_FRAG_FILE, RAY_GEOM_FILE ); } void init_camera(float _fovy, const Eigen::Vector3f _camera, const Eigen::Vector3f _rotation, bool _ortho = false) { ortho = _ortho; camera = _camera; rotation = _rotation; fovy = _fovy; q.setIdentity(); q = rotate(rotation, forward, up, right) * q; near = 0.1f; far = 200.0f; cam_speed = 0.2f; cam_angular_speed = (cam_speed / 1000.0f) * 360.0f / M_PI; } void update_projection() { float fH; float fW; if (ortho) { fH = 11.0f; fW = 11.0f; near = 0.0f; far = fH + fW; proj = nanogui::ortho(-fW, fW, -fH, fH, near, far); } else { fH = std::tan(fovy / 360.0f * M_PI) * near; fW = fH * (float) mSize.x() / (float) mSize.y(); proj = nanogui::frustum(-fW, fW, -fH, fH, near, far); } } void update_view() { // have to update cam position based on m_arcball state somehow q = rotate(rotation, forward, up, right) * q; R = quat_to_mat(q); forward = (R * (-1.0f * Eigen::Vector4f::UnitZ())).block(0, 0, 3, 1); right = (R * (Eigen::Vector4f::UnitX())).block(0, 0, 3, 1); up = (R * (Eigen::Vector4f::UnitY())).block(0, 0, 3, 1); camera += forward * (-translation[2]); camera += up * translation[1]; camera += right * translation[0]; total_rotation += rotation; total_translation += translation; rotation.setZero(); translation.setZero(); T = translate({camera[0], camera[1], camera[2]}); view = R.inverse() * T.inverse(); } void update_model() { model.setIdentity(); data_model = nanogui::scale(model_scale) * model; //nanogui::scale(model_scale); box_model = model; //nanogui::scale(model_scale); data_model = translate({ -box_size[0] / 2, -box_size[1] / 2, -box_size[2] / 2}) * data_model; } void bind_data(PlotData* d) { data = d; } void unbind_data() { data = nullptr; } void refresh_data() { /* Upload points to GPU */ if (data) { // if (index == 0) { m_pointShader->bind(); m_pointShader->uploadAttrib("position", data->p_vertices); m_pointShader->uploadAttrib("color", data->p_colors); m_pointTexShader->bind(); m_pointTexShader->uploadAttrib("position", data->p_vertices); m_pointTexShader->uploadAttrib("color", data->p_colors); m_pointTexShader->uploadAttrib("texcoords", data->p_texcoords); // } m_cubeShader->bind(); m_cubeShader->uploadIndices ( data->c_indices ); m_cubeShader->uploadAttrib("position", data->c_vertices); m_cubeShader->uploadAttrib("color", data->c_colors); local_data_checksum = data->checksum; } else { /* printf("data is null... not refreshing\n") */; } } void refresh_camera_positions() { // update cam position data->e_vertices.col (2 * index) = camera - forward; data->e_vertices.col (2 * index + 1) = camera; //update rays data->r_vertices.col (2 * index) = camera; data->r_vertices.col (2 * index + 1) = camera + 50 * raydir; m_camShader->bind(); m_camShader->uploadAttrib("position", data->e_vertices); m_camShader->uploadAttrib("color", data->e_colors); m_rayShader->bind(); m_rayShader->uploadAttrib("position", data->r_vertices); m_rayShader->uploadAttrib("color", data->e_colors); } bool mouseButtonEvent(const Eigen::Vector2i &p, int button, bool down, int modifiers) override { if (!GLCanvas::mouseButtonEvent(p, button, down, modifiers)) { if (button == GLFW_MOUSE_BUTTON_1) m_arcball.button(p, down); } return true; } bool mouseMotionEvent ( const Eigen::Vector2i &p, const Eigen::Vector2i &rel, int button, int modifiers ) override { if (!GLCanvas::mouseMotionEvent(p, rel, button, modifiers)) { if (mousemotion_enabled) { /* takes mouse position on screen and return ray in world coords */ Eigen::Vector3f relative_pos = Eigen::Vector3f ( 2.0f * ( float ) ( p[0] - mPos[0] ) / ( float ) mSize[0] - 1.0f, ( float ) ( -2.0f * ( p[1] - mPos[1] ) ) / ( float ) mSize[0] + 1.0f, 1.0f ); mouse_last_x = relative_pos[0]; mouse_last_y = relative_pos[1]; update_mouse_overlay(); m_arcball.motion(p); // std::cout << m_arcball.matrix() << std::endl; } } return true; } void update_mouse_overlay() { // ray casting Eigen::Vector3f ray_nds ( mouse_last_x, mouse_last_y, 1.0f ); Eigen::Vector4f ray_clip ( mouse_last_x, mouse_last_y, -1.0f, 1.0f ); Eigen::Vector4f ray_eye = proj.inverse() * ray_clip; ray_eye[2] = -1.0f; ray_eye[3] = 0.0f; Eigen::Vector3f world = ( view.inverse() * ray_eye ).head<3>(); // std::cout << "world: " << std::endl << world << std::endl; Eigen::Vector3f world_normalized = world.normalized(); // std::cout << "normalized: " << std::endl << world_normalized << std::endl; raydir = world_normalized; } void process_keyboard() { if (glfw_window && keyboard_enabled) { float rate = (( glfwGetKey ( glfw_window, GLFW_KEY_LEFT_SHIFT ) ) == GLFW_PRESS) ? 5.0 : 1.0f; if ( glfwGetKey ( glfw_window, 'A' ) == GLFW_PRESS ) translation[0] -= cam_speed * rate; if ( glfwGetKey ( glfw_window, 'D' ) == GLFW_PRESS ) translation[0] += cam_speed * rate; if ( glfwGetKey ( glfw_window, 'E' ) == GLFW_PRESS ) translation[1] -= cam_speed * rate; if ( glfwGetKey ( glfw_window, 'Q' ) == GLFW_PRESS ) translation[1] += cam_speed * rate; if ( glfwGetKey ( glfw_window, 'W' ) == GLFW_PRESS ) translation[2] -= cam_speed * rate; if ( glfwGetKey ( glfw_window, 'S' ) == GLFW_PRESS ) translation[2] += cam_speed * rate; if ( glfwGetKey ( glfw_window, 'Z' ) == GLFW_PRESS ) rotation[0] -= cam_angular_speed * rate; if ( glfwGetKey ( glfw_window, 'C' ) == GLFW_PRESS ) rotation[0] += cam_angular_speed * rate; if ( glfwGetKey ( glfw_window, GLFW_KEY_RIGHT ) == GLFW_PRESS ) rotation[1] -= cam_angular_speed * rate; if ( glfwGetKey ( glfw_window, GLFW_KEY_LEFT ) == GLFW_PRESS ) rotation[1] += cam_angular_speed * rate; if ( glfwGetKey ( glfw_window, GLFW_KEY_DOWN ) == GLFW_PRESS ) rotation[2] -= cam_angular_speed * rate; if ( glfwGetKey ( glfw_window, GLFW_KEY_UP ) == GLFW_PRESS ) rotation[2] += cam_angular_speed * rate; } } void update_mvp() { // update model, view, projection update_model(); update_view(); update_projection(); mvp = proj * view * model; data_mvp = proj * view * data_model; box_mvp = proj * view * box_model; } void update_frame_count() { frame_time = glfwGetTime() - tic; num_frames++; tic = glfwGetTime(); } void drawGL() override { update_frame_count(); process_keyboard(); /* Upload points to GPU */ bool record = false; if (data->checksum != local_data_checksum) { refresh_data(); record = true; } refresh_camera_positions(); update_mvp(); /* Render */ glDisable ( GL_DEPTH_TEST ); //glBlendFunc ( GL_ONE, GL_ONE ); glBlendFunc ( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA ); glEnable ( GL_BLEND ); if (show_box) { m_cubeShader->bind(); m_cubeShader->setUniform("mvp", box_mvp); m_cubeShader->setUniform("model", box_model); m_cubeShader->setUniform("view", view); m_cubeShader->setUniform("proj", proj); m_cubeShader->drawIndexed ( GL_LINES, 0, data->c_indices.cols() ); } m_camShader->bind(); m_camShader->setUniform("mvp", mvp); m_camShader->drawArray(GL_LINES, 0, data->e_vertices.cols()); if (show_rays) { m_rayShader->bind(); m_rayShader->setUniform("mvp", mvp); m_rayShader->drawArray(GL_LINES, 0, data->r_vertices.cols()); } if (!use_textures) { glEnable ( GL_PROGRAM_POINT_SIZE ); m_pointShader->bind(); m_pointShader->setUniform("mvp", data_mvp); m_pointShader->setUniform ( "coord_type", coord_type ); m_pointShader->setUniform ( "pt_size", pt_size ); m_pointShader->setUniform ( "alpha", alpha ); // m_pointShader->setUniform ( "radius_intersect", radius_intersect ); m_pointShader->drawArray(GL_POINTS, 0, data->p_vertices.cols()); glDisable ( GL_PROGRAM_POINT_SIZE ); glDisable ( GL_BLEND ); glEnable ( GL_DEPTH_TEST ); } else { m_pointTexShader->bind(); // glActiveTexture ( GL_TEXTURE0 ); // glBindTexture ( GL_TEXTURE_2D, ( std::vector<std::pair<int, std::string>> ( data->textures ) [0] ).first ); // float textures_per_dim = ceil ( sqrtf ( train_data.size() ) ); //star glBindTexture ( GL_TEXTURE_2D, ( std::vector<std::pair<int, std::string>> ( data->textures ) [1] ).first ); float textures_per_dim = 1; m_pointTexShader->setUniform ( "image", 0 ); m_pointTexShader->setUniform ( "view", view ); m_pointTexShader->setUniform ( "proj", proj ); m_pointTexShader->setUniform ( "selected", selected ); m_pointTexShader->setUniform ( "model", data_model ); m_pointTexShader->setUniform ( "coord_type", coord_type ); float quad_size = 0.005f; float radius = sqrtf ( 2 * quad_size ); float tex_w = 1.0f / (float)textures_per_dim; m_pointTexShader->setUniform ( "radius", radius ); m_pointTexShader->setUniform ( "tex_w", tex_w ); glPointSize ( 1 ); glEnable ( GL_DEPTH_TEST ); glEnable ( GL_BLEND ); glBlendFunc ( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA ); m_pointTexShader->drawArray ( GL_POINTS, 0, data->p_vertices.cols() ); glDisable ( GL_BLEND ); glDisable ( GL_DEPTH_TEST ); } // additional stuff, directly in nanovg if (vg) { nvgSave(vg); // border nvgBeginPath(vg); nvgStrokeWidth(vg, 1); nvgRoundedRect(vg, mPos.x() + 0.5f, mPos.y() + 0.5f, mSize.x() - 1, mSize.y() - 1, 0); nvgStrokeColor(vg, nanogui::Color(1.0f, 1.0f, 1.0f, 0.1f)); nvgStroke(vg); // caption, bottom-left if (!caption.empty()) { nvgFontFace(vg, "sans"); nvgFontSize(vg, 9); nvgFontBlur(vg, 0.3f); nvgFillColor(vg, nanogui::Color(1.0f, 1.0f, 1.0f, 0.5f)); // nvgText(vg, mPos.x() + 3, mPos.y() + size().y() - 3, string_format ( "T [%.1f, %.1f, %.1f], R [%.1f, %.1f, %.1f], C [%.1f, %.1f, %.1f], F [%.1f, %.1f, %.1f], U [%.1f, %.1f, %.1f]", total_translation[0], total_translation[1], total_translation[2], total_rotation[0], total_rotation[1], total_rotation[2], camera[0], camera[1], camera[2], forward[0], forward[1], forward[2], up[0], up[1], up[2] ).c_str(), nullptr); nvgText(vg, mPos.x() + 37, mPos.y() + size().y() - 3, string_format ( "[%s]", caption.c_str()).c_str(), nullptr); } // cam info, bottom-left if (!ortho) nvgText(vg, mPos.x() + 3, mPos.y() + size().y() - 3, string_format ( "FOV: %.1f", fovy).c_str(), nullptr); else nvgText(vg, mPos.x() + 3, mPos.y() + size().y() - 3, string_format ( "ORTHO" ).c_str(), nullptr); nvgText(vg, mPos.x() + 95, mPos.y() + size().y() - 3, string_format ( "mouse at [%.3f, %.3f]", mouse_last_x, mouse_last_y ).c_str(), nullptr); // bottom-right label nvgFontFace(vg, "sans"); nvgFontSize(vg, 9); nvgFontBlur(vg, 0.3f); nvgFillColor(vg, nanogui::Color(1.0f, 1.0f, 1.0f, 0.5f)); nvgText(vg, mPos.x() + size().x() - 28, mPos.y() + size().y() - 3, string_format ( "%.1f fps", 1.0f / frame_time ).c_str(), nullptr); // top-right label // tools // nvgFontFace(vg, "sans"); // nvgFontSize(vg, 9); // nvgFontBlur(vg, 0.3f); // nvgFillColor(vg, nanogui::Color(1.0f, 1.0f, 1.0f, 0.5f)); // top-left label nvgFontFace(vg, "sans"); nvgFontSize(vg, 9); nvgFontBlur(vg, 0.3f); nvgFillColor(vg, nanogui::Color(1.0f, 1.0f, 1.0f, 0.5f)); nvgText(vg, mPos.x() + 2, mPos.y() + 7, string_format ( "%d", num_frames ).c_str(), nullptr); // draw cameras' coords for (int i = 0; i < data->e_vertices.cols(); i += 2) { // skip self if (i / 2 == index) continue; nvgFontSize(vg, 6); Eigen::Vector3f coords3f = data->e_vertices.col(i + 1); Eigen::Vector3f screen_coords = nanogui::project(coords3f, model * view, proj, size()); screen_coords[1] = size().y() - screen_coords[1]; // background nvgBeginPath(vg); nvgRoundedRect(vg, mPos.x() + screen_coords[0] + 1, mPos.y() + screen_coords[1], 16, 16, 4); nvgFillColor(vg, nanogui::Color(0.5f, 0.5f, 0.5f, 0.5f)); nvgFill(vg); Eigen::Vector3f color = data->e_colors.col(i); nvgFillColor(vg, nanogui::Color(color[0], color[1], color[2], 0.5f)); nvgText(vg, mPos.x() + screen_coords[0] + 5, mPos.y() + screen_coords[1] + 5, string_format ( "%1.1f", coords3f[0]).c_str(), nullptr); nvgText(vg, mPos.x() + screen_coords[0] + 5, mPos.y() + screen_coords[1] + 10, string_format ( "%1.1f", coords3f[1]).c_str(), nullptr); nvgText(vg, mPos.x() + screen_coords[0] + 5, mPos.y() + screen_coords[1] + 15, string_format ( "%1.1f", coords3f[2]).c_str(), nullptr); } nvgRestore(vg); } else { /* printf("cam %d: nanovg context == nullptr \n", index); */ } // save sreen if (record_interval > 0) { // if (num_frames % record_interval == 0) { if (record) { std::string fname = string_format ( "snapshots/screens/%s_%08d.png", record_prefix.c_str(), num_frames); saveScreenShot(false, fname.c_str()); } } } void saveScreenShot(int premult, const char* name) { Eigen::Vector2i fbSize; Eigen::Vector2i wsize; if (glfw_window) { glfwGetFramebufferSize ( glfw_window, &fbSize[0], &fbSize[1] ); glfwGetWindowSize ( glfw_window, &wsize[0], &wsize[1] ); float pixel_ratio = (float)fbSize[0] / wsize[0]; int x = mPos.x() * pixel_ratio; int y = fbSize[1] - size().y() * pixel_ratio - 5; int w = size().x() * pixel_ratio; int h = size().y() * pixel_ratio - 5; screenshot(x, y, w, h, premult, name); } } virtual bool resizeEvent ( const Eigen::Vector2i &size ) { m_arcball.setSize ( size ); tools->setPosition({size[0] - 91, 0}); return true; } // virtual bool mouseButtonEvent ( const Eigen::Vector2i &p, int button, bool down, int modifiers ) { // // if ( !SurfPlot::mouseButtonEvent ( p, button, down, modifiers ) ) { // if ( button == GLFW_MOUSE_BUTTON_1 ) // m_arcball.button ( p, down ); // // } // return false; // } /* check if a ray and a sphere intersect. if not hit, returns false. it rejects intersections behind the ray caster's origin, and sets intersection_distance to the closest intersection */ // bool ray_sphere ( // Eigen::Vector3f ray_origin_wor, // Eigen::Vector3f ray_direction_wor, // Eigen::Vector3f sphere_centre_wor, // float sphere_radius, // float* intersection_distance // ) { // // work out components of quadratic // Eigen::Vector3f dist_to_sphere = ray_origin_wor - sphere_centre_wor; // float b = ray_direction_wor.dot(dist_to_sphere); // float c = dist_to_sphere.dot(dist_to_sphere) - // sphere_radius * sphere_radius; // float b_squared_minus_c = b * b - c; // // check for "imaginary" answer. == ray completely misses sphere // if (b_squared_minus_c < 0.0f) { // return false; // } // // check for ray hitting twice (in and out of the sphere) // if (b_squared_minus_c > 0.0f) { // // get the 2 intersection distances along ray // float t_a = -b + sqrt (b_squared_minus_c); // float t_b = -b - sqrt (b_squared_minus_c); // *intersection_distance = t_b; // // if behind viewer, throw one or both away // if (t_a < 0.0) { // if (t_b < 0.0) { // return false; // } // } else if (t_b < 0.0) { // *intersection_distance = t_a; // } // return true; // } // // check for ray hitting once (skimming the surface) // if (0.0f == b_squared_minus_c) { // // if behind viewer, throw away // float t = -b + sqrt (b_squared_minus_c); // if (t < 0.0f) { // return false; // } // *intersection_distance = t; // return true; // } // // note: could also check if ray origin is inside sphere radius // return false; // } // bool mouseButtonEvent ( const Eigen::Vector2i &p, int button, bool down, int modifiers ) override { // if ( button == GLFW_MOUSE_BUTTON_1 && down ) { // int closest_sphere_clicked = -1; // float closest_intersection = 0.0f; // for (int i = 0; i < data->p_vertices.cols(); i++) { // float t_dist = 0.0f; // if (ray_sphere ( // camera, raydir, data->p_vertices.col(i), 0.1f, &t_dist // )) { // // if more than one sphere is in path of ray, only use the closest one // if (-1 == closest_sphere_clicked || t_dist < closest_intersection) { // closest_sphere_clicked = i; // closest_intersection = t_dist; // } // } // } // endfor // if (closest_sphere_clicked > -1) { // int idx = closest_sphere_clicked; // printf ("sphere %i was clicked\n", idx); // selected = Eigen::Vector3f(0, 0, 0); // selected << data->p_vertices.col(idx)[0], data->p_vertices.col(idx)[1], data->p_vertices.col(idx)[2]; // } // } // return true; // } ~Plot() { /* free resources */ delete m_pointShader; delete m_pointTexShader; delete m_cubeShader; delete m_camShader; delete m_rayShader; } //data PlotData *data; nanogui::Widget *tools; Eigen::Vector3f selected; std::vector<std::pair<int, std::string>> textures; size_t local_data_checksum = 0; size_t record_interval = 0; std::string record_prefix = ""; bool keyboard_enabled = false; bool mousemotion_enabled = true; bool show_box = true; // for intercepting keyboard events GLFWwindow *glfw_window = nullptr; NVGcontext *vg = nullptr; // shaders nanogui::GLShader *m_pointShader = nullptr; nanogui::GLShader *m_pointTexShader = nullptr; nanogui::GLShader *m_cubeShader = nullptr; nanogui::GLShader *m_camShader = nullptr; nanogui::GLShader *m_rayShader = nullptr; nanogui::GLShader *master_pointShader = nullptr; nanogui::GLShader *master_pointTexShader = nullptr; nanogui::GLShader *master_cubeShader = nullptr; nanogui::GLShader *master_camShader = nullptr; nanogui::GLShader *master_rayShader = nullptr; //model, view, projection... Eigen::Vector3f translation, rotation, camera, forward, right, up, data_translation, box_size, total_translation, total_rotation, model_scale; Eigen::Matrix4f view, proj, model, data_model, box_model, mvp, data_mvp, box_mvp; Eigen::Matrix4f T, R; Eigen::Quaternionf q; Eigen::Vector3f raydir; nanogui::Arcball m_arcball; bool ortho = false; bool use_textures = false; bool show_rays = true; int coord_type = 0; float pt_size = 2.0f; float alpha = 0.7f; float near, far, fovy; float cam_speed, cam_angular_speed; std::string caption = ""; int index = 0; float frame_time, tic; size_t num_frames = 0; float mouse_last_x = -1, mouse_last_y = - 1; }; #endif
c6a0258dd46efe9c4ae167bad85bc002d1f4c558
b1f7a2309825dbe6d5953f6582d7f442d1d40422
/lc-cn/求众数2.cpp
67967874bcbbba99fb9d27cde849b2ff12621367
[]
no_license
helloMickey/Algorithm
cbb8aea2a4279b2d76002592a658c54475977ff0
d0923a9e14e288def11b0a8191097b5fd7a85f46
refs/heads/master
2023-07-03T00:58:05.754471
2021-08-09T14:42:49
2021-08-09T14:42:49
201,753,017
1
0
null
null
null
null
UTF-8
C++
false
false
2,205
cpp
求众数2.cpp
// https://leetcode-cn.com/problems/majority-element-ii/ /* 给定一个大小为 n 的整数数组,找出其中所有出现超过 ⌊ n/3 ⌋ 次的元素。 【笔记】摩尔投票法。 该算法用于1/2情况,它说:“在任何数组中,出现次数大于该数组长度一半的值只能有一个。” 那么,改进一下用于1/3。可以着么说:“在任何数组中,出现次数大于该数组长度1/3的值最多只有两个。” 于是,需要定义两个变量。空间复杂度为O(1)。 */ class Solution { public: vector<int> majorityElement(vector<int>& nums) { // can1和can2具有相同的起点 int c1 = 0, c2 = 0, can1 = nums[0], can2 = nums[0]; for (int num : nums) { // 投票过程,优先为can1投票 if (can1 == num) { c1++; continue; } // 其次为can2投票 if (can2 == num) { c2++; continue; } // can1和can2的投票必须分开,这里是当can1的票数归零时,重新投票 if (c1 == 0 && num != can2) { can1 = num; c1++; continue; } // can2归零,注意不能和can1相等 if (c2 == 0 && num != can1) { can2 = num; c2++; continue; } // 没有与can1和can2相等的,那么同时减一票 c1--; c2--; } // 再计数 -- 两次遍历也满足O(N), 如果题目中标明一定存在两个超过 1/3 的数,后面的步骤可以不需要,直接返回 can1,can2。 c1 = 0; c2 = 0; for (int num : nums) { if (can1 == num) c1++; if (can2 == num) c2++; } vector<int> res; if (c1 > nums.size() / 3) res.emplace_back(can1); // 注意由于一开始起点相同。所以需要排除 can1 == can2的情况 if (can1 != can2 && c2 > nums.size() / 3) res.emplace_back(can2); return res; } };
7156f92cd64dfbcc6d4af8204c381b31f8581d78
2517065805d99cd36b5ca26d74b6691f868ad591
/src/Ramp.cpp
032c1c941b26cb64acce840e6a3bd9681b442a49
[]
no_license
jsm174/vpxpp
ff8cf176ac1cf82aa81f5d2d68af9e93e62eed73
b34eafbd58d65e8cdc8a6894a561c8d199b8fae2
refs/heads/main
2023-08-28T02:55:14.055079
2021-10-08T21:22:56
2021-10-08T21:22:56
398,131,825
1
0
null
2021-09-23T01:50:05
2021-08-20T02:27:21
C++
UTF-8
C++
false
false
17,822
cpp
Ramp.cpp
#include "Ramp.h" #include "DragPoint.h" #include "RegUtil.h" #include "Inlines.h" const ItemTypeEnum Ramp::ItemType = eItemRamp; const int Ramp::TypeNameID = 145; const int Ramp::ToolID = 146; const int Ramp::CursorID = 150; const unsigned Ramp::AllowedViews = 1; Ramp* Ramp::COMCreate() { /*CComObject<Ramp>* obj = 0; if ((((HRESULT)(CComObject<Ramp>::CreateInstance(&obj))) < 0)) { //MessageBoxA(0, "Failed to create COM object.", "Visual Pinball", // 0x00000030L); } obj->AddRef(); return obj;*/ return new Ramp(); } IEditable* Ramp::COMCreateEditable() { return static_cast<IEditable*>(COMCreate()); } IEditable* Ramp::COMCreateAndInit(PinTable* ptable, float x, float y) { Ramp* obj = Ramp::COMCreate(); obj->Init(ptable, x, y, true); return obj; } Ramp::Ramp() { // TODO: m_menuid = IDR_SURFACEMENU; m_d.m_collidable = true; m_d.m_visible = true; m_dynamicVertexBuffer = NULL; m_dynamicIndexBuffer = NULL; m_dynamicVertexBuffer2 = NULL; m_dynamicVertexBufferRegenerate = true; m_d.m_depthBias = 0.0f; m_d.m_wireDiameter = 6.0f; m_d.m_wireDistanceX = 38.0f; m_d.m_wireDistanceY = 88.0f; // TODO: m_propPosition = NULL; // TODO: m_propPhysics = NULL; m_d.m_hitEvent = false; m_d.m_overwritePhysics = true; m_rgheightInit = NULL; } Ramp::~Ramp() { } bool Ramp::IsTransparent() const { return m_ptable->GetMaterial(m_d.m_szMaterial)->m_bOpacityActive; } HRESULT Ramp::Init(PinTable* ptable, float x, float y, bool fromMouseClick) { RegUtil* pRegUtil = RegUtil::SharedInstance(); m_ptable = ptable; SetDefaults(fromMouseClick); m_d.m_visible = true; float length = 0.5f * pRegUtil->LoadValueFloatWithDefault("DefaultProps\\Ramp", "Length", 400.0f); // CComObject<DragPoint> *pdp; // CComObject<DragPoint>::CreateInstance(&pdp); // if (pdp) // { // pdp->AddRef(); // pdp->Init(this, x, y + length, 0.f, true); // pdp->m_calcHeight = m_d.m_heightbottom; // m_vdpoint.push_back(pdp); // } // CComObject<DragPoint>::CreateInstance(&pdp); // if (pdp) // { // pdp->AddRef(); // pdp->Init(this, x, y - length, 0.f, true); // pdp->m_calcHeight = m_d.m_heighttop; // m_vdpoint.push_back(pdp); // } InitVBA(true, 0, NULL); return S_OK; } HRESULT Ramp::InitVBA(bool fNew, int id, wchar_t* const wzName) { wchar_t wzUniqueName[128]; if (fNew && !wzName) { GetPTable()->GetUniqueName(eItemRamp, wzUniqueName, 128); wcsncpy(m_wzName, wzUniqueName, MAXNAMEBUFFER); } InitScript(); return ((HRESULT)0L); } HRESULT Ramp::InitLoad(POLE::Stream* pStream, PinTable* pTable, int* pId, int version) { SetDefaults(false); m_ptable = pTable; BiffReader biffReader(pStream, this, pId, version); biffReader.Load(); return S_OK; } HRESULT Ramp::InitPostLoad() { return S_OK; } void Ramp::SetDefaults(bool fromMouseClick) { RegUtil* pRegUtil = RegUtil::SharedInstance(); static const char strKeyName[] = "DefaultProps\\Ramp"; m_d.m_heightbottom = fromMouseClick ? pRegUtil->LoadValueFloatWithDefault(strKeyName, "HeightBottom", 0.0f) : 0.0f; m_d.m_heighttop = fromMouseClick ? pRegUtil->LoadValueFloatWithDefault(strKeyName, "HeightTop", 50.0f) : 50.0f; m_d.m_widthbottom = fromMouseClick ? pRegUtil->LoadValueFloatWithDefault(strKeyName, "WidthBottom", 75.0f) : 75.0f; m_d.m_widthtop = fromMouseClick ? pRegUtil->LoadValueFloatWithDefault(strKeyName, "WidthTop", 60.0f) : 60.0f; m_d.m_type = fromMouseClick ? (RampType)pRegUtil->LoadValueIntWithDefault(strKeyName, "RampType", RampTypeFlat) : RampTypeFlat; m_d.m_tdr.m_TimerEnabled = fromMouseClick ? pRegUtil->LoadValueBoolWithDefault(strKeyName, "TimerEnabled", false) : false; m_d.m_tdr.m_TimerInterval = fromMouseClick ? pRegUtil->LoadValueIntWithDefault(strKeyName, "TimerInterval", 100) : 100; HRESULT hr = pRegUtil->LoadValue(strKeyName, "Image", m_d.m_szImage); if ((hr != S_OK) || !fromMouseClick) { m_d.m_szImage.clear(); } m_d.m_imagealignment = fromMouseClick ? (RampImageAlignment)pRegUtil->LoadValueIntWithDefault(strKeyName, "ImageMode", ImageModeWorld) : ImageModeWorld; m_d.m_imageWalls = fromMouseClick ? pRegUtil->LoadValueBoolWithDefault(strKeyName, "ImageWalls", true) : true; m_d.m_leftwallheight = fromMouseClick ? pRegUtil->LoadValueFloatWithDefault(strKeyName, "LeftWallHeight", 62.0f) : 62.0f; m_d.m_rightwallheight = fromMouseClick ? pRegUtil->LoadValueFloatWithDefault(strKeyName, "RightWallHeight", 62.0f) : 62.0f; m_d.m_leftwallheightvisible = fromMouseClick ? pRegUtil->LoadValueFloatWithDefault(strKeyName, "LeftWallHeightVisible", 30.0f) : 30.0f; m_d.m_rightwallheightvisible = fromMouseClick ? pRegUtil->LoadValueFloatWithDefault(strKeyName, "RightWallHeightVisible", 30.0f) : 30.0f; m_d.m_threshold = fromMouseClick ? pRegUtil->LoadValueFloatWithDefault(strKeyName, "HitThreshold", 2.0f) : 2.0f; SetDefaultPhysics(fromMouseClick); m_d.m_visible = fromMouseClick ? pRegUtil->LoadValueBoolWithDefault(strKeyName, "Visible", true) : true; m_d.m_collidable = fromMouseClick ? pRegUtil->LoadValueBoolWithDefault(strKeyName, "Collidable", true) : true; m_d.m_reflectionEnabled = fromMouseClick ? pRegUtil->LoadValueBoolWithDefault(strKeyName, "ReflectionEnabled", true) : true; m_d.m_wireDiameter = fromMouseClick ? pRegUtil->LoadValueFloatWithDefault(strKeyName, "WireDiameter", 8.0f) : 8.0f; m_d.m_wireDistanceX = fromMouseClick ? pRegUtil->LoadValueFloatWithDefault(strKeyName, "WireDistanceX", 38.0f) : 38.0f; m_d.m_wireDistanceY = fromMouseClick ? pRegUtil->LoadValueFloatWithDefault(strKeyName, "WireDistanceY", 88.0f) : 88.0f; } void Ramp::SetDefaultPhysics(bool fromMouseClick) { RegUtil* pRegUtil = RegUtil::SharedInstance(); static const char strKeyName[] = "DefaultProps\\Ramp"; m_d.m_elasticity = fromMouseClick ? pRegUtil->LoadValueFloatWithDefault(strKeyName, "Elasticity", 0.3f) : 0.3f; m_d.m_friction = fromMouseClick ? pRegUtil->LoadValueFloatWithDefault(strKeyName, "Friction", 0.3f) : 0.3f; m_d.m_scatter = fromMouseClick ? pRegUtil->LoadValueFloatWithDefault(strKeyName, "Scatter", 0) : 0; } bool Ramp::LoadToken(const int id, BiffReader* const pBiffReader) { switch (id) { case FID(PIID): pBiffReader->GetInt((int*)pBiffReader->m_pData); break; case FID(HTBT): pBiffReader->GetFloat(m_d.m_heightbottom); break; case FID(HTTP): pBiffReader->GetFloat(m_d.m_heighttop); break; case FID(WDBT): pBiffReader->GetFloat(m_d.m_widthbottom); break; case FID(WDTP): pBiffReader->GetFloat(m_d.m_widthtop); break; case FID(MATR): pBiffReader->GetString(m_d.m_szMaterial); break; case FID(TMON): pBiffReader->GetBool(m_d.m_tdr.m_TimerEnabled); break; case FID(TMIN): pBiffReader->GetInt(m_d.m_tdr.m_TimerInterval); break; case FID(TYPE): pBiffReader->GetInt(&m_d.m_type); break; case FID(IMAG): pBiffReader->GetString(m_d.m_szImage); break; case FID(ALGN): pBiffReader->GetInt(&m_d.m_imagealignment); break; case FID(IMGW): pBiffReader->GetBool(m_d.m_imageWalls); break; case FID(NAME): pBiffReader->GetWideString(m_wzName, sizeof(m_wzName) / sizeof(wchar_t)); break; case FID(WLHL): pBiffReader->GetFloat(m_d.m_leftwallheight); break; case FID(WLHR): pBiffReader->GetFloat(m_d.m_rightwallheight); break; case FID(WVHL): pBiffReader->GetFloat(m_d.m_leftwallheightvisible); break; case FID(WVHR): pBiffReader->GetFloat(m_d.m_rightwallheightvisible); break; case FID(HTEV): pBiffReader->GetBool(m_d.m_hitEvent); break; case FID(THRS): pBiffReader->GetFloat(m_d.m_threshold); break; case FID(ELAS): pBiffReader->GetFloat(m_d.m_elasticity); break; case FID(RFCT): pBiffReader->GetFloat(m_d.m_friction); break; case FID(RSCT): pBiffReader->GetFloat(m_d.m_scatter); break; case FID(CLDR): pBiffReader->GetBool(m_d.m_collidable); break; case FID(RVIS): pBiffReader->GetBool(m_d.m_visible); break; case FID(REEN): pBiffReader->GetBool(m_d.m_reflectionEnabled); break; case FID(RADB): pBiffReader->GetFloat(m_d.m_depthBias); break; case FID(RADI): pBiffReader->GetFloat(m_d.m_wireDiameter); break; case FID(RADX): pBiffReader->GetFloat(m_d.m_wireDistanceX); break; case FID(RADY): pBiffReader->GetFloat(m_d.m_wireDistanceY); break; case FID(MAPH): pBiffReader->GetString(m_d.m_szPhysicsMaterial); break; case FID(OVPH): pBiffReader->GetBool(m_d.m_overwritePhysics); break; default: { LoadPointToken(id, pBiffReader, pBiffReader->m_version); ISelect::LoadToken(id, pBiffReader); break; } } return true; } PinTable* Ramp::GetPTable() { return m_ptable; } const PinTable* Ramp::GetPTable() const { return m_ptable; } IEditable* Ramp::GetIEditable() { return static_cast<IEditable*>(this); } const IEditable* Ramp::GetIEditable() const { return static_cast<const IEditable*>(this); } ISelect* Ramp::GetISelect() { return static_cast<ISelect*>(this); } const ISelect* Ramp::GetISelect() const { return static_cast<const ISelect*>(this); } IHitable* Ramp::GetIHitable() { return static_cast<IHitable*>(this); } const IHitable* Ramp::GetIHitable() const { return static_cast<const IHitable*>(this); } ItemTypeEnum Ramp::GetItemType() const { return eItemRamp; } void Ramp::WriteRegDefaults() { RegUtil* pRegUtil = RegUtil::SharedInstance(); static const char strKeyName[] = "DefaultProps\\Ramp"; pRegUtil->SaveValueFloat(strKeyName, "HeightBottom", m_d.m_heightbottom); pRegUtil->SaveValueFloat(strKeyName, "HeightTop", m_d.m_heighttop); pRegUtil->SaveValueFloat(strKeyName, "WidthBottom", m_d.m_widthbottom); pRegUtil->SaveValueFloat(strKeyName, "WidthTop", m_d.m_widthtop); pRegUtil->SaveValueInt(strKeyName, "RampType", m_d.m_type); pRegUtil->SaveValueBool(strKeyName, "TimerEnabled", m_d.m_tdr.m_TimerEnabled); pRegUtil->SaveValueInt(strKeyName, "TimerInterval", m_d.m_tdr.m_TimerInterval); pRegUtil->SaveValue(strKeyName, "Image", m_d.m_szImage); pRegUtil->SaveValueInt(strKeyName, "ImageMode", m_d.m_imagealignment); pRegUtil->SaveValueBool(strKeyName, "ImageWalls", m_d.m_imageWalls); pRegUtil->SaveValueFloat(strKeyName, "LeftWallHeight", m_d.m_leftwallheight); pRegUtil->SaveValueFloat(strKeyName, "RightWallHeight", m_d.m_rightwallheight); pRegUtil->SaveValueFloat(strKeyName, "LeftWallHeightVisible", m_d.m_leftwallheightvisible); pRegUtil->SaveValueFloat(strKeyName, "RightWallHeightVisible", m_d.m_rightwallheightvisible); pRegUtil->SaveValueBool(strKeyName, "HitEvent", m_d.m_hitEvent); pRegUtil->SaveValueFloat(strKeyName, "HitThreshold", m_d.m_threshold); pRegUtil->SaveValueFloat(strKeyName, "Elasticity", m_d.m_elasticity); pRegUtil->SaveValueFloat(strKeyName, "Friction", m_d.m_friction); pRegUtil->SaveValueFloat(strKeyName, "Scatter", m_d.m_scatter); pRegUtil->SaveValueBool(strKeyName, "Collidable", m_d.m_collidable); pRegUtil->SaveValueBool(strKeyName, "Visible", m_d.m_visible); pRegUtil->SaveValueBool(strKeyName, "ReflectionEnabled", m_d.m_reflectionEnabled); pRegUtil->SaveValueFloat(strKeyName, "WireDiameter", m_d.m_wireDiameter); pRegUtil->SaveValueFloat(strKeyName, "WireDistanceX", m_d.m_wireDistanceX); pRegUtil->SaveValueFloat(strKeyName, "WireDistanceY", m_d.m_wireDistanceY); } void Ramp::GetHitShapes(std::vector<HitObject*>& pvho) { } void Ramp::GetHitShapesDebug(std::vector<HitObject*>& pvho) { } void Ramp::RenderStatic() { } void Ramp::RenderDynamic() { } void Ramp::RenderSetup() { } ItemTypeEnum Ramp::HitableGetItemType() const { return eItemRamp; } IScriptable* Ramp::GetScriptable() { return (IScriptable*)this; } wchar_t* Ramp::get_Name() { return m_wzName; } void Ramp::GetBoundingVertices(std::vector<Vertex3Ds>& pvvertex3D) { float* rgheight1; int cvertex; const Vertex2D* const rgvLocal = GetRampVertex(cvertex, &rgheight1, NULL, NULL, NULL, HIT_SHAPE_DETAIL_LEVEL, true); Vertex3Ds bbox_min(FLT_MAX, FLT_MAX, FLT_MAX); Vertex3Ds bbox_max(-FLT_MAX, -FLT_MAX, -FLT_MAX); for (int i = 0; i < cvertex; i++) { { const Vertex3Ds pv(rgvLocal[i].x, rgvLocal[i].y, rgheight1[i] + (float)(2.0 * PHYS_SKIN)); // leave room for ball //!! use ballsize bbox_min.x = min(bbox_min.x, pv.x); bbox_min.y = min(bbox_min.y, pv.y); bbox_min.z = min(bbox_min.z, pv.z); bbox_max.x = max(bbox_max.x, pv.x); bbox_max.y = max(bbox_max.y, pv.y); bbox_max.z = max(bbox_max.z, pv.z); } const Vertex3Ds pv(rgvLocal[cvertex * 2 - i - 1].x, rgvLocal[cvertex * 2 - i - 1].y, rgheight1[i] + (float)(2.0 * PHYS_SKIN)); // leave room for ball //!! use ballsize bbox_min.x = min(bbox_min.x, pv.x); bbox_min.y = min(bbox_min.y, pv.y); bbox_min.z = min(bbox_min.z, pv.z); bbox_max.x = max(bbox_max.x, pv.x); bbox_max.y = max(bbox_max.y, pv.y); bbox_max.z = max(bbox_max.z, pv.z); } delete[] rgvLocal; delete[] rgheight1; for (int i = 0; i < 8; i++) { const Vertex3Ds pv( (i & 1) ? bbox_min.x : bbox_max.x, (i & 2) ? bbox_min.y : bbox_max.y, (i & 4) ? bbox_min.z : bbox_max.z); pvvertex3D.push_back(pv); } } void Ramp::AssignHeightToControlPoint(const RenderVertex3D& v, const float height) { for (size_t i = 0; i < m_vdpoint.size(); i++) { if (m_vdpoint[i]->m_v.x == v.x && m_vdpoint[i]->m_v.y == v.y) { m_vdpoint[i]->m_calcHeight = height; } } } // // license:GPLv3+ // Ported at: VisualPinball.Engine/VPT/Ramp/RampMeshGenerator.cs // Vertex2D* Ramp::GetRampVertex(int& pcvertex, float** const ppheight, bool** const ppfCross, float** const ppratio, Vertex2D** const pMiddlePoints, const float _accuracy, const bool inc_width) { std::vector<RenderVertex3D> vvertex; GetCentralCurve(vvertex, _accuracy); const int cvertex = (int)vvertex.size(); pcvertex = cvertex; Vertex2D* const rgvLocal = new Vertex2D[cvertex * 2]; if (ppheight) { *ppheight = new float[cvertex]; } if (ppfCross) { *ppfCross = new bool[cvertex]; } if (ppratio) { *ppratio = new float[cvertex]; } if (pMiddlePoints) { *pMiddlePoints = new Vertex2D[cvertex]; } float totallength = 0; const float bottomHeight = m_d.m_heightbottom + m_ptable->m_tableheight; const float topHeight = m_d.m_heighttop + m_ptable->m_tableheight; for (int i = 0; i < (cvertex - 1); i++) { const RenderVertex3D& v1 = vvertex[i]; const RenderVertex3D& v2 = vvertex[i + 1]; const float dx = v1.x - v2.x; const float dy = v1.y - v2.y; const float length = sqrtf(dx * dx + dy * dy); totallength += length; } float currentlength = 0; for (int i = 0; i < cvertex; i++) { const RenderVertex3D& vprev = vvertex[(i > 0) ? i - 1 : i]; const RenderVertex3D& vnext = vvertex[(i < (cvertex - 1)) ? i + 1 : i]; const RenderVertex3D& vmiddle = vvertex[i]; if (ppfCross) { (*ppfCross)[i] = vmiddle.controlPoint; } Vertex2D vnormal; { Vertex2D v1normal(vprev.y - vmiddle.y, vmiddle.x - vprev.x); Vertex2D v2normal(vmiddle.y - vnext.y, vnext.x - vmiddle.x); if (i == (cvertex - 1)) { v1normal.Normalize(); vnormal = v1normal; } else if (i == 0) { v2normal.Normalize(); vnormal = v2normal; } else { v1normal.Normalize(); v2normal.Normalize(); if (fabsf(v1normal.x - v2normal.x) < 0.0001f && fabsf(v1normal.y - v2normal.y) < 0.0001f) { vnormal = v1normal; } else { const float A = vprev.y - vmiddle.y; const float B = vmiddle.x - vprev.x; const float C = A * (v1normal.x - vprev.x) + B * (v1normal.y - vprev.y); const float D = vnext.y - vmiddle.y; const float E = vmiddle.x - vnext.x; const float F = D * (v2normal.x - vnext.x) + E * (v2normal.y - vnext.y); const float det = A * E - B * D; const float inv_det = (det != 0.0f) ? 1.0f / det : 0.0f; const float intersectx = (B * F - E * C) * inv_det; const float intersecty = (C * D - A * F) * inv_det; vnormal.x = vmiddle.x - intersectx; vnormal.y = vmiddle.y - intersecty; } } } { const float dx = vprev.x - vmiddle.x; const float dy = vprev.y - vmiddle.y; const float length = sqrtf(dx * dx + dy * dy); currentlength += length; } const float percentage = currentlength / totallength; float widthcur = percentage * (m_d.m_widthtop - m_d.m_widthbottom) + m_d.m_widthbottom; if (ppheight) { (*ppheight)[i] = vmiddle.z + percentage * (topHeight - bottomHeight) + bottomHeight; } AssignHeightToControlPoint(vvertex[i], vmiddle.z + percentage * (topHeight - bottomHeight) + bottomHeight); if (ppratio) { (*ppratio)[i] = 1.0f - percentage; } if (isHabitrail() && m_d.m_type != RampType1Wire) { widthcur = m_d.m_wireDistanceX; if (inc_width) { widthcur += 20.0f; } } else if (m_d.m_type == RampType1Wire) { widthcur = m_d.m_wireDiameter; } if (pMiddlePoints) { (*pMiddlePoints)[i] = Vertex2D(vmiddle.x, vmiddle.y) + vnormal; } rgvLocal[i] = Vertex2D(vmiddle.x, vmiddle.y) + (widthcur * 0.5f) * vnormal; rgvLocal[cvertex * 2 - i - 1] = Vertex2D(vmiddle.x, vmiddle.y) - (widthcur * 0.5f) * vnormal; } return rgvLocal; } template <typename T> void Ramp::GetCentralCurve(std::vector<T>& vv, const float _accuracy) const { float accuracy; if (_accuracy != -1.f) { accuracy = _accuracy; } else { const Material* const mat = m_ptable->GetMaterial(m_d.m_szMaterial); if (!mat->m_bOpacityActive) { accuracy = 10.f; } else { accuracy = (float)m_ptable->GetDetailLevel(); } } accuracy = 4.0f * powf(10.0f, (10.0f - accuracy) * (float)(1.0 / 1.5)); IHaveDragPoints::GetRgVertex(vv, false, accuracy); } // // license:GPLv3+ // Ported at: VisualPinball.Engine/VPT/Ramp/RampHitGenerator.cs // bool Ramp::isHabitrail() const { return m_d.m_type == RampType4Wire || m_d.m_type == RampType1Wire || m_d.m_type == RampType2Wire || m_d.m_type == RampType3WireLeft || m_d.m_type == RampType3WireRight; } // // end of license:GPLv3+, back to 'old MAME'-like //
eadc7b7c78d4b546a68a2a4b3f39d4f7a5440691
618a14dd17be3c4eb3b0757e8e272d6d979d898e
/PaintShooting/GamePadXInput.cpp
1453ed0be3268b8b5a1efa00c98cb52dd4385064
[]
no_license
koutcha/PaintShooting
562c30e14ee4edc64923345b9f2e5c64b8b33075
95910929043e8d73107a92ada6e49cf605490566
refs/heads/master
2020-04-16T22:10:46.766583
2019-01-16T02:07:45
2019-01-16T02:07:45
165,956,384
0
0
null
null
null
null
UTF-8
C++
false
false
2,654
cpp
GamePadXInput.cpp
#include "GamePadXInput.h" GamePadXInput::GamePadXInput() { updateState(); } GamePadXInput::~GamePadXInput() { } void GamePadXInput::updateState() { DWORD dwResult; for (DWORD i = 0; i < MAX_PAD_NUMBER; i++) { // Simply get the state of the controller from XInput. dwResult = XInputGetState(i, &padData[i].state); if (dwResult == ERROR_SUCCESS) { padData[i].hasConnection = true; XINPUT_STATE& state = padData[i].state; if ((state.Gamepad.sThumbLX < XINPUT_GAMEPAD_LEFT_THUMB_DEADZONE && state.Gamepad.sThumbLX > -XINPUT_GAMEPAD_LEFT_THUMB_DEADZONE) && (state.Gamepad.sThumbLY < XINPUT_GAMEPAD_LEFT_THUMB_DEADZONE && state.Gamepad.sThumbLY > -XINPUT_GAMEPAD_LEFT_THUMB_DEADZONE)) { state.Gamepad.sThumbLX = 0; state.Gamepad.sThumbLY = 0; } if ((state.Gamepad.sThumbRX < XINPUT_GAMEPAD_RIGHT_THUMB_DEADZONE && state.Gamepad.sThumbRX > -XINPUT_GAMEPAD_RIGHT_THUMB_DEADZONE) && (state.Gamepad.sThumbRY < XINPUT_GAMEPAD_RIGHT_THUMB_DEADZONE && state.Gamepad.sThumbRY > -XINPUT_GAMEPAD_RIGHT_THUMB_DEADZONE)) { state.Gamepad.sThumbRX = 0; state.Gamepad.sThumbRY = 0; } } else { padData[i].hasConnection = false;; } } } bool GamePadXInput::checkConnection(int padID) const { if (padID<0 || padID>=MAX_PAD_NUMBER) { return false; } return padData[padID].hasConnection; } bool GamePadXInput::getButtonOn(int padID, unsigned short xInputButtonCode) const { if (padID < 0 || padID >= MAX_PAD_NUMBER) { return false; } if (padData[padID].hasConnection) { WORD buttons = padData[padID].state.Gamepad.wButtons; return buttons & xInputButtonCode; } else { return false; } } short GamePadXInput::getLY(int padID) const { if (checkConnection(padID)) { return padData[padID].state.Gamepad.sThumbLY; } else { return 0; } } short GamePadXInput::getLX(int padID) const { if (checkConnection(padID)) { return padData[padID].state.Gamepad.sThumbLX; } else { return 0; } } short GamePadXInput::getRY(int padID) const { if (checkConnection(padID)) { return padData[padID].state.Gamepad.sThumbRY; } else { return 0; } } short GamePadXInput::getRX(int padID) const { if (checkConnection(padID)) { return padData[padID].state.Gamepad.sThumbRX; } else { return 0; } } unsigned char GamePadXInput::getRT(int padID) const { if (checkConnection(padID)) { return padData[padID].state.Gamepad.bRightTrigger; } else { return 0; } } unsigned char GamePadXInput::getLT(int padID) const { if (checkConnection(padID)) { return padData[padID].state.Gamepad.bLeftTrigger; } else { return 0; } }
f06a12570e196fd82d5cd18ec2f030df1f39622d
4e35423872fe989ccb1f876486b451326d89ba9a
/third_party/splinelibpy/third_party/SplineLib/Tests/ParameterSpaces/b_spline_basis_function_test.cpp
f3aac6d06e5b94555b2a051b26aebd75171e7935
[ "MIT" ]
permissive
j042/gustav-alpha
54efba1c60f2aed674285580c28f5ae0d4d500ec
f738dcd66fb70df376b8a954a75a9024155a5c7a
refs/heads/main
2023-07-21T01:25:08.725352
2021-08-31T09:26:10
2021-08-31T09:26:10
null
0
0
null
null
null
null
UTF-8
C++
false
false
5,727
cpp
b_spline_basis_function_test.cpp
/* Copyright (c) 2018–2021 SplineLib 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 <gtest/gtest.h> #include "Sources/ParameterSpaces/b_spline_basis_function.hpp" #include "Sources/Utilities/error_handling.hpp" #include "Tests/ParameterSpaces/knot_vector_mock.hpp" namespace splinelib::tests::parameter_spaces::b_spline_basis_function { using sources::parameter_spaces::BSplineBasisFunction; // Test basis functions N_{2,0} and N_{0,2} from NURBS book Exa. 2.1. TEST(BSplineBasisFunctionSuite, IsEqualAndOperatorEqual) { using KnotVector = testing::StrictMock<AKnotVectorMock>; constexpr Degree const kDegree0{}, kDegree2{2}; constexpr KnotSpan const kKnotSpan0{}, kKnotSpan1{1}, kKnotSpan2{2}; constexpr sources::parameter_spaces::Tolerance const kTolerance{1.2 * sources::parameter_spaces::kEpsilon}; KnotVector knot_vector, knot_vector_perturbed; knot_vector.NurbsBookExa2_1(); knot_vector_perturbed.NurbsBookExa2_1Perturbed(); BSplineBasisFunction const *basis_function_2_0{}, *basis_function_0_2{}; ASSERT_NO_THROW(basis_function_2_0 = BSplineBasisFunction::CreateDynamic(knot_vector, kKnotSpan2, kDegree0)); ASSERT_NO_THROW(basis_function_0_2 = BSplineBasisFunction::CreateDynamic(knot_vector, kKnotSpan0, kDegree2)); BSplineBasisFunction *basis_function_2_0_equal{}; ASSERT_NO_THROW(basis_function_2_0_equal = BSplineBasisFunction::CreateDynamic(knot_vector, kKnotSpan2, kDegree0)); EXPECT_TRUE(IsEqual(*basis_function_2_0_equal, *basis_function_2_0)); EXPECT_TRUE(*basis_function_2_0_equal == *basis_function_2_0); BSplineBasisFunction *basis_function_2_0_knot_vector{}; ASSERT_NO_THROW(basis_function_2_0_knot_vector = BSplineBasisFunction::CreateDynamic(knot_vector_perturbed, kKnotSpan2, kDegree0)); EXPECT_FALSE(IsEqual(*basis_function_2_0_knot_vector, *basis_function_2_0)); EXPECT_FALSE(*basis_function_2_0_knot_vector == *basis_function_2_0); EXPECT_FALSE(IsEqual(*basis_function_2_0_knot_vector, *basis_function_2_0, kTolerance)); ASSERT_NO_THROW(basis_function_2_0_knot_vector = BSplineBasisFunction::CreateDynamic(knot_vector_perturbed, kKnotSpan2, kDegree0, kTolerance)); EXPECT_TRUE(IsEqual(*basis_function_2_0_knot_vector, *basis_function_2_0, kTolerance)); BSplineBasisFunction *basis_function_2_0_knot_span{}; ASSERT_NO_THROW(basis_function_2_0_knot_span = BSplineBasisFunction::CreateDynamic(knot_vector, kKnotSpan1, kDegree0)); EXPECT_FALSE(IsEqual(*basis_function_2_0_knot_span, *basis_function_2_0)); EXPECT_FALSE(*basis_function_2_0_knot_span == *basis_function_2_0); BSplineBasisFunction *basis_function_0_2_equal{}; ASSERT_NO_THROW(basis_function_0_2_equal = BSplineBasisFunction::CreateDynamic(knot_vector, kKnotSpan0, kDegree2)); EXPECT_TRUE(IsEqual(*basis_function_0_2_equal, *basis_function_0_2)); EXPECT_TRUE(*basis_function_0_2_equal == *basis_function_0_2); BSplineBasisFunction *basis_function_0_2_knot_vector{}; ASSERT_NO_THROW(basis_function_0_2_knot_vector = BSplineBasisFunction::CreateDynamic(knot_vector_perturbed, kKnotSpan0, kDegree2)); EXPECT_FALSE(IsEqual(*basis_function_0_2_knot_vector, *basis_function_0_2)); EXPECT_FALSE(*basis_function_0_2_knot_vector == *basis_function_0_2); EXPECT_FALSE(IsEqual(*basis_function_0_2_knot_vector, *basis_function_0_2, kTolerance)); ASSERT_NO_THROW(basis_function_0_2_knot_vector = BSplineBasisFunction::CreateDynamic(knot_vector_perturbed, kKnotSpan0, kDegree2, kTolerance)); EXPECT_TRUE(IsEqual(*basis_function_0_2_knot_vector, *basis_function_0_2, kTolerance)); BSplineBasisFunction *basis_function_0_2_knot_span{}; ASSERT_NO_THROW(basis_function_0_2_knot_span = BSplineBasisFunction::CreateDynamic(knot_vector, kKnotSpan1, kDegree2)); // N_{1,2} == N_{0,2} is true for BSplineBasisFunctions corresponding to {0.0, 0.0, 0.0, 1.0, 1.0, 1.0}. EXPECT_TRUE(IsEqual(*basis_function_0_2_knot_span, *basis_function_0_2)); EXPECT_TRUE(*basis_function_0_2_knot_span == *basis_function_0_2); BSplineBasisFunction *basis_function_0_2_degree{}; ASSERT_NO_THROW(basis_function_0_2_degree = BSplineBasisFunction::CreateDynamic(knot_vector, kKnotSpan0, Degree{1})); EXPECT_FALSE(IsEqual(*basis_function_0_2_degree, *basis_function_0_2)); EXPECT_FALSE(*basis_function_0_2_degree == *basis_function_0_2); } } // namespace splinelib::tests::parameter_spaces::b_spline_basis_function
94128cf6abd4eec82e29374873b8e0705e6ec7cd
7a12fbf4a4c5e6017dac3eeb829f7272848ba672
/WhoAmI_source/src/Physics.cpp
63f76ae6c6a83219ff2c0b6360a0a7bc32c30a30
[]
no_license
CH-Kwon/Who_Am_I
5336f00996b683453828792f8f294cc10fb4bb12
c21f01b502de36724e3965658575d25ce4740463
refs/heads/master
2023-04-11T17:05:46.088709
2021-05-04T08:01:19
2021-05-04T08:01:19
364,178,338
0
0
null
null
null
null
UTF-8
C++
false
false
6,228
cpp
Physics.cpp
/** \file Physics.cpp \author jungdae.chur \par email: wmdhwmdh@gmail.com \par course: GAM200 \date 12/13/2017 \brief All content (c) 2017 DigiPen (USA) Corporation, all rights reserved. */ #include "Physics.h" //include RigidBody, Transform, BoxCollision and so on... #include "Headers_Components.h" //for debugging #include "DebugUtil.h" #include "PhysicsLogic.h" #include <cassert> #include <iostream> //using glm::vec3/glm::mat44 instead of before Vector3/Matrix44 class #include "Object.h" #include <glm/glm.hpp> #include <glm/vec3.hpp> // #include "Input.h" #include "PlayerController.h" #include "PlayerLogic.h" #include "Transform.hpp" // #ifdef _WIN32 #include "../../WhoAmI/Include/PlayerLogic.h" #else //apple #include "PlayerLogic.h" #endif namespace FindersEngine { class Pair { public: Pair(RigidBody* lhs, RigidBody* rhs) : m_lhs(lhs), m_rhs(rhs) { } RigidBody* m_lhs; RigidBody* m_rhs; private: }; Physics* PHYSICS = nullptr; Physics::Physics() { assert(PHYSICS == nullptr && "PHYSICS system is already existing!"); PHYSICS = this; m_collision = new Collision(); } Physics::~Physics() { delete m_collision; m_collision = 0; } void Physics::Init() { } void Physics::Update(float deltaTime) { PHYSICS_LOGIC->SeperateByRoom(); ExplicitEuler(deltaTime); AbleToCollide(); } void Physics::push_back_RigidBody(RigidBody* rigidbody) { PHYSICS->m_vecprb.push_back(rigidbody); } void Physics::ExplicitEuler(float deltaTime) { Transform* pTr = nullptr; //current frame position, next frame position glm::vec3 curfp; for (std::vector<RigidBody*>::iterator iter = m_vecprb.begin(); iter != m_vecprb.end(); ++iter) { //Explicit Euler method //f(t + dt) = f(t) + f'(t)dt //next frame's position = current frame's posotion + (vector * dt) pTr = dynamic_cast<Transform*>((*iter)->GetOwner()->GetComponent(CT_TRANSFORM)); curfp = pTr->getPosition(); //p' = p + vt pTr->setPosition(curfp + (*iter)->pm_vel * deltaTime); if ((*iter)->GetOwner()->GetObjType() == OT_BULLET) { (*iter)->pm_vel = (*iter)->pm_vel * 0.97f + ((*iter)->pm_force * (*iter)->pm_invMass) * deltaTime; } else (*iter)->pm_vel = (*iter)->pm_vel * 0.8f + ((*iter)->pm_force * (*iter)->pm_invMass) * deltaTime; //v' = v + at = v + F/m * at (*iter)->pm_force = glm::vec3(0.f); //Set Zero } } void Physics::AbleToCollide() { //k; number of objects //Big O Notation(n^2 / 2) //(*i) = RigidBody* //i = RigidBody** for (std::vector<RigidBody*>::iterator i = m_vecprb.begin(); i != m_vecprb.end(); ++i) { for (std::vector<RigidBody*>::iterator j = i + 1; j != m_vecprb.end(); ++j) { ShapeType i_shape = (*i)->m_pTransform->GetOwner()->GetShapeType(); ShapeType j_shape = (*j)->m_pTransform->GetOwner()->GetShapeType(); if (i_shape == ST_CIRCLE && j_shape == ST_CIRCLE) { if (m_collision->CircleCircleCollisionCheck((*i)->GetOwner(), (*j)->GetOwner())) { m_rigidbody->ResolveIntersection((*i), (*j)); m_rigidbody->CollisionResponseGeneral((*i), (*j)); } } else if (i_shape == ST_CIRCLE && j_shape == ST_RECTANGLE) { if (m_collision->CircleRectCollisionCheck((*i)->GetOwner(), (*j)->GetOwner())) { if ((*j)->GetOwner()->GetObjType() == OT_HDOOR || (*j)->GetOwner()->GetObjType() == OT_VDOOR) { m_rigidbody->CollisionResponseWithDoor((*i), (*j)); if ((*i)->GetOwner()->GetObjType() == OT_PLAYER) m_rigidbody->GenerateActionHint(); } else if ((*j)->GetOwner()->GetObjType() == OT_FDOOR) { m_rigidbody->CollisionResponseWithFinal((*i)); if ((*i)->GetOwner()->GetObjType() == OT_PLAYER) { m_rigidbody->GenerateActionHint(); } } else m_rigidbody->CollisionResponseWithWall((*i), (*j)); } m_rigidbody->RemoveActionHint(); } else if (j_shape == ST_CIRCLE && i_shape == ST_RECTANGLE) { if (m_collision->CircleRectCollisionCheck((*i)->GetOwner(), (*j)->GetOwner())) { if ((*i)->GetOwner()->GetObjType() == OT_HDOOR || (*i)->GetOwner()->GetObjType() == OT_VDOOR) { m_rigidbody->CollisionResponseWithDoor((*i), (*j)); if ((*j)->GetOwner()->GetObjType() == OT_PLAYER) m_rigidbody->GenerateActionHint(); } else if ((*i)->GetOwner()->GetObjType() == OT_FDOOR) { m_rigidbody->CollisionResponseWithFinal((*j)); if ((*j)->GetOwner()->GetObjType() == OT_PLAYER) m_rigidbody->GenerateActionHint(); } else m_rigidbody->CollisionResponseWithWall((*j), (*i)); } m_rigidbody->RemoveActionHint(); } //put the pair into the container m_vecpair.push_back(Pair(*i, *j)); } } } };
16e7423086cf710fb0254d1edf4ce960264ab297
2e0a6fd5767ee4551d370f682910702be9095d73
/SlicerModules/SpatialObjectsModule/Widgets/qSlicerSpatialObjectsGlyphWidget.cxx
30139523b25e245a2e094a984bb56d52ce90db59
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
LucasGandel/TubeTK
ee0ce6a378aab732a3ee051ecd2ea36332d4943a
50682d4d8b30b0392575685e11e16a1086790bc8
refs/heads/master
2021-01-18T09:29:06.802793
2016-01-30T04:11:39
2016-01-30T04:11:39
40,605,754
1
1
null
2015-08-12T14:39:59
2015-08-12T14:39:59
null
UTF-8
C++
false
false
9,690
cxx
qSlicerSpatialObjectsGlyphWidget.cxx
/*========================================================================= Library: TubeTK Copyright 2010 Kitware Inc. 28 Corporate Drive, Clifton Park, NY, 12065, USA. 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. =========================================================================*/ // qMRML includes #include "qSlicerSpatialObjectsGlyphWidget.h" #include "ui_qSlicerSpatialObjectsGlyphWidget.h" // MRML includes #include <vtkMRMLSpatialObjectsDisplayNode.h> #include <vtkMRMLSpatialObjectsDisplayPropertiesNode.h> //------------------------------------------------------------------------------ class qSlicerSpatialObjectsGlyphWidgetPrivate : public Ui_qSlicerSpatialObjectsGlyphWidget { Q_DECLARE_PUBLIC(qSlicerSpatialObjectsGlyphWidget); protected: qSlicerSpatialObjectsGlyphWidget* const q_ptr; public: qSlicerSpatialObjectsGlyphWidgetPrivate( qSlicerSpatialObjectsGlyphWidget& object); void init(); bool centeredOrigin(double* origin) const; vtkMRMLSpatialObjectsDisplayNode* SpatialObjectsDisplayNode; vtkMRMLSpatialObjectsDisplayPropertiesNode* SpatialObjectsDisplayPropertiesNode; }; //------------------------------------------------------------------------------ qSlicerSpatialObjectsGlyphWidgetPrivate:: qSlicerSpatialObjectsGlyphWidgetPrivate( qSlicerSpatialObjectsGlyphWidget& object) : q_ptr(&object) { this->SpatialObjectsDisplayNode = 0; this->SpatialObjectsDisplayPropertiesNode = 0; } //------------------------------------------------------------------------------ void qSlicerSpatialObjectsGlyphWidgetPrivate::init() { Q_Q(qSlicerSpatialObjectsGlyphWidget); this->setupUi(q); QObject::connect(this->GlyphTypeSelector, SIGNAL(currentIndexChanged(int)), q, SLOT(setGlyphType(int))); QObject::connect(this->ScaleFactorSlider, SIGNAL(valueChanged(double)), q, SLOT(setGlyphScaleFactor(double))); QObject::connect(this->SpacingSlider, SIGNAL(valueChanged(double)), q, SLOT(setGlyphSpacing(double))); QObject::connect(this->GlyphSidesSlider, SIGNAL(valueChanged(double)), q, SLOT(setTubeGlyphNumberOfSides(double))); QObject::connect(this->GlyphRadiusSlider, SIGNAL(valueChanged(double)), q, SLOT(setTubeGlyphRadius(double))); } //------------------------------------------------------------------------------ qSlicerSpatialObjectsGlyphWidget:: qSlicerSpatialObjectsGlyphWidget(QWidget *_parent) : Superclass(_parent) , d_ptr(new qSlicerSpatialObjectsGlyphWidgetPrivate(*this)) { Q_D(qSlicerSpatialObjectsGlyphWidget); d->init(); } //------------------------------------------------------------------------------ qSlicerSpatialObjectsGlyphWidget::~qSlicerSpatialObjectsGlyphWidget() {} //------------------------------------------------------------------------------ vtkMRMLSpatialObjectsDisplayNode* qSlicerSpatialObjectsGlyphWidget:: spatialObjectsDisplayNode() const { Q_D(const qSlicerSpatialObjectsGlyphWidget); return d->SpatialObjectsDisplayNode; } //------------------------------------------------------------------------------ vtkMRMLSpatialObjectsDisplayPropertiesNode* qSlicerSpatialObjectsGlyphWidget:: spatialObjectsDisplayPropertiesNode() const { Q_D(const qSlicerSpatialObjectsGlyphWidget); return d->SpatialObjectsDisplayNode ? d->SpatialObjectsDisplayNode->GetSpatialObjectsDisplayPropertiesNode() : 0; } //------------------------------------------------------------------------------ void qSlicerSpatialObjectsGlyphWidget:: setSpatialObjectsDisplayNode(vtkMRMLNode* node) { this->setSpatialObjectsDisplayNode( vtkMRMLSpatialObjectsDisplayNode::SafeDownCast(node)); } //------------------------------------------------------------------------------ void qSlicerSpatialObjectsGlyphWidget:: setSpatialObjectsDisplayNode( vtkMRMLSpatialObjectsDisplayNode* SpatialObjectsDisplayNode) { Q_D(qSlicerSpatialObjectsGlyphWidget); vtkMRMLSpatialObjectsDisplayNode *oldDisplayNode = d->SpatialObjectsDisplayNode; d->SpatialObjectsDisplayNode = SpatialObjectsDisplayNode; qvtkReconnect(oldDisplayNode, d->SpatialObjectsDisplayNode, vtkCommand::ModifiedEvent, this, SLOT(updateWidgetFromMRMLDisplayNode())); this->updateWidgetFromMRMLDisplayNode(); } //------------------------------------------------------------------------------ void qSlicerSpatialObjectsGlyphWidget:: setSpatialObjectsDisplayPropertiesNode(vtkMRMLNode* node) { this->setSpatialObjectsDisplayPropertiesNode (vtkMRMLSpatialObjectsDisplayPropertiesNode::SafeDownCast(node)); } //------------------------------------------------------------------------------ void qSlicerSpatialObjectsGlyphWidget:: setSpatialObjectsDisplayPropertiesNode( vtkMRMLSpatialObjectsDisplayPropertiesNode* node) { Q_D(qSlicerSpatialObjectsGlyphWidget); d->SpatialObjectsDisplayPropertiesNode = node; // Selection of the Glyph type d->GlyphTypeSelector->blockSignals(true); d->GlyphTypeSelector->clear(); int i = d->SpatialObjectsDisplayPropertiesNode->GetFirstGlyphGeometry(); for(; i <= d->SpatialObjectsDisplayPropertiesNode->GetLastGlyphGeometry(); ++i) { std::cout << "Glyph" << i << ": " << d->SpatialObjectsDisplayPropertiesNode->GetGlyphGeometryAsString(i) << std::endl; d->GlyphTypeSelector->addItem( d->SpatialObjectsDisplayPropertiesNode->GetGlyphGeometryAsString(i), i); } d->GlyphTypeSelector->blockSignals(false); } //------------------------------------------------------------------------------ void qSlicerSpatialObjectsGlyphWidget::setGlyphType(int type) { Q_D(qSlicerSpatialObjectsGlyphWidget); if(!d->SpatialObjectsDisplayPropertiesNode) { return; } d->SpatialObjectsDisplayPropertiesNode->SetGlyphGeometry(type); QWidget* widget = d->GlyphSubPropertiesWidget->findChild<QWidget*>( d->SpatialObjectsDisplayPropertiesNode->GetGlyphGeometryAsString()); if(widget) { d->GlyphSubPropertiesWidget->setCurrentWidget(widget); d->GlyphSubPropertiesWidget->setEnabled(true); } else { d->GlyphSubPropertiesWidget->setEnabled(false); } } //------------------------------------------------------------------------------ void qSlicerSpatialObjectsGlyphWidget::setGlyphScaleFactor(double scale) { Q_D(qSlicerSpatialObjectsGlyphWidget); if(!d->SpatialObjectsDisplayPropertiesNode) { return; } d->SpatialObjectsDisplayPropertiesNode->SetGlyphScaleFactor(scale); } //------------------------------------------------------------------------------ void qSlicerSpatialObjectsGlyphWidget::setGlyphSpacing(double spacing) { Q_D(qSlicerSpatialObjectsGlyphWidget); if(!d->SpatialObjectsDisplayPropertiesNode) { return; } d->SpatialObjectsDisplayPropertiesNode->SetLineGlyphResolution( static_cast<int>(spacing)); } //------------------------------------------------------------------------------ void qSlicerSpatialObjectsGlyphWidget::setTubeGlyphNumberOfSides(double sides) { Q_D(qSlicerSpatialObjectsGlyphWidget); if(!d->SpatialObjectsDisplayPropertiesNode) { return; } d->SpatialObjectsDisplayPropertiesNode->SetTubeGlyphNumberOfSides( static_cast<int>(sides)); } //------------------------------------------------------------------------------ void qSlicerSpatialObjectsGlyphWidget::setTubeGlyphRadius(double radius) { Q_D(qSlicerSpatialObjectsGlyphWidget); if(!d->SpatialObjectsDisplayPropertiesNode) { return; } d->SpatialObjectsDisplayPropertiesNode->SetTubeGlyphRadius(radius); } //------------------------------------------------------------------------------ void qSlicerSpatialObjectsGlyphWidget::updateWidgetFromMRMLDisplayNode() { Q_D(qSlicerSpatialObjectsGlyphWidget); if(!d->SpatialObjectsDisplayNode) { return; } if(d->SpatialObjectsDisplayPropertiesNode != d->SpatialObjectsDisplayNode->GetSpatialObjectsDisplayPropertiesNode()) { this->setSpatialObjectsDisplayPropertiesNode( d->SpatialObjectsDisplayNode->GetSpatialObjectsDisplayPropertiesNode()); } this->updateWidgetFromMRMLDisplayPropertiesNode(); } //------------------------------------------------------------------------------ void qSlicerSpatialObjectsGlyphWidget:: updateWidgetFromMRMLDisplayPropertiesNode() { Q_D(qSlicerSpatialObjectsGlyphWidget); if(!d->SpatialObjectsDisplayNode || !d->SpatialObjectsDisplayPropertiesNode) { return; } d->GlyphTypeSelector->setCurrentIndex( d->SpatialObjectsDisplayPropertiesNode->GetGlyphGeometry()); d->ScaleFactorSlider->setValue( d->SpatialObjectsDisplayPropertiesNode->GetGlyphScaleFactor()); d->SpacingSlider->setValue( d->SpatialObjectsDisplayPropertiesNode->GetLineGlyphResolution()); d->GlyphSidesSlider->setValue( d->SpatialObjectsDisplayPropertiesNode->GetTubeGlyphNumberOfSides()); d->GlyphRadiusSlider->setValue( d->SpatialObjectsDisplayPropertiesNode->GetTubeGlyphRadius()); }
411b8a767dec1d6c27b867247a169a5666bf2192
f2574b2f053b6faa4b6d4fc75bef389e83132c33
/ntl/stlx/cstd/wctype.h
75af8985b58f03401831b3f2733595ea46c4a3db
[ "Zlib", "LicenseRef-scancode-stlport-4.5" ]
permissive
icestudent/ontl
a0a391b06b55ef45f496021614cf0b9df318e7a6
6ed48916bbc8323776c710f393c853ee94cb97de
refs/heads/master
2022-05-15T21:45:29.063446
2022-05-04T03:51:02
2022-05-04T11:18:20
15,104,848
46
13
null
2022-05-04T11:18:20
2013-12-11T10:45:04
C++
UTF-8
C++
false
false
310
h
wctype.h
#pragma once #include "../cwctype.hxx" using std::iswalnum; using std::iswalpha; using std::iswblank; using std::iswcntrl; using std::iswdigit; using std::iswgraph; using std::iswlower; using std::iswprint; using std::iswpunct; using std::iswspace; using std::iswupper; using std::iswxdigit;
a12d75c2893ed24fc1a86426cbaba97a556fdaf9
080941f107281f93618c30a7aa8bec9e8e2d8587
/src/conditioners/kmzcleanup_core.cpp
f3f7520b0e3e092b2fb16a3daaa21c653a48c167
[ "MIT" ]
permissive
scoopr/COLLADA_Refinery
6d40ee1497b9f33818ec1e71677c3d0a0bf8ced4
3a5ad1a81e0359f9025953e38e425bc10b5bf6c5
refs/heads/master
2021-01-22T01:55:14.642769
2009-03-10T21:31:04
2009-03-10T21:31:04
194,828
2
0
null
null
null
null
UTF-8
C++
false
false
30,161
cpp
kmzcleanup_core.cpp
/* The MIT License Copyright 2006 Sony Computer Entertainment Inc. 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 "kmzcleanup.h" #include "dom/domConstants.h" //#define PRINTF if (verbose) printf template<class T> int Kmzcleanup::processprimitive(T primitive, int verbose) { int input_count = (int)primitive->getInput_array().getCount(); printf("input count in primitive is %d\n", input_count); int input_set; for (int i = 0; i < input_count; i++) { xsNMTOKEN semantic = primitive->getInput_array()[i]->getSemantic(); if (strcmp(semantic, "TEXCOORD") == 0) { input_set = (int)primitive->getInput_array()[i]->getSet(); return input_set; } //if } // for return 0; } bool Kmzcleanup::checkbindneeded(DAE* input, daeString material, int verbose) { unsigned int index = 0; domCOLLADA *root = (domCOLLADA*)input->getDatabase()->getDocument(index)->getDomRoot(); daeElementRefArray elementArray; for ( unsigned int j = 0; j < root->getLibrary_materials_array().getCount(); j++ ) { domLibrary_materials *lm = root->getLibrary_materials_array()[j]; for ( unsigned int k = 0; k < lm->getMaterial_array().getCount(); k++ ) { elementArray.append( lm->getMaterial_array()[k] ); } } for ( unsigned int j = 0; j < elementArray.getCount(); j++ ) { daeString id = elementArray[j]->getID(); if ( (id != NULL) && (strcmp(material, id) == 0)) { domMaterial *thisMaterial = (domMaterial *)(daeElement *)elementArray[j]; thisMaterial->getInstance_effect()->getUrl().resolveElement(); daeElement *thisElement = thisMaterial->getInstance_effect()->getUrl().getElement(); domEffect *thisEffect = (domEffect *)thisElement; //int count = (int)thisEffect->getProfile_common()->getNewparam_array().getCount(); //int count = (int)thisEffect->getNewparam_array().getCount(); int count = (int)thisEffect->getContents().getCount(); for (int i = 0; i < count; i++) { domProfile_COMMON *profile = daeSafeCast< domProfile_COMMON >( thisEffect->getContents()[i] ); if (profile != NULL) { if (profile->getTechnique()) { domProfile_COMMON::domTechnique::domPhong * phong = profile->getTechnique()->getPhong(); if (phong == NULL) continue; domCommon_color_or_texture_type_complexType::domTexture *thisTexture = phong->getDiffuse()->getTexture(); if (thisTexture != NULL) return true; else continue; } } } } } return false; } bool Kmzcleanup::init() { addBoolOption( "verbose", "verbose", "verbose print out", true ); return true; } int Kmzcleanup::execute() { int error = 0; bool effect_change = false; map <string, int> strmap; map <string, int>::iterator si; bool verbose; getBoolOption( "verbose", verbose ); unsigned int assetCount = _dae->getDatabase()->getElementCount(NULL, COLLADA_TYPE_ASSET, getInput(0).c_str()); //cerr<<"There are "<<assetCount<<" assets in this file\n"; domAsset * thisAsset; for(unsigned int i=0; i<assetCount; i++) { // Get the next asset error = _dae->getDatabase()->getElement((daeElement**)&thisAsset,i, NULL, COLLADA_TYPE_ASSET, getInput(0).c_str()); if(error != DAE_OK) continue; domAsset::domCreated *pCreated = thisAsset->getCreated(); if (pCreated == 0) { // need to add created domAsset::domCreated *newCreated; newCreated = (domAsset::domCreated *)thisAsset->createAndPlace(COLLADA_TYPE_CREATED); newCreated->setValue("2005-11-14T02:16:38Z"); } domAsset::domModified *pModified = thisAsset->getModified(); if (pModified == 0) { // need to add modified domAsset::domModified *newModified; newModified = (domAsset::domModified *)thisAsset->createAndPlace(COLLADA_TYPE_MODIFIED); newModified->setValue("2005-11-15T11:36:38Z"); } domAsset::domContributor_Array & contributors = thisAsset->getContributor_array(); for (unsigned int i=0; i< contributors.getCount(); i++) { domAsset::domContributorRef contrib = contributors[i]; domAsset::domContributor::domAuthoring_toolRef ref = contrib->getAuthoring_tool(); if (ref) { printf("authoring tool is %s\n", ref->getValue()); if ( strstr(ref->getValue(), "KMZ fix") != NULL) { // check for "TEXTCOORD" and fix it unsigned int geometryInstanceCount = _dae->getDatabase()->getElementCount(NULL, "instance_geometry", getInput(0).c_str()); //printf("there are %d instance_geometry\n", geometryInstanceCount); for (unsigned int currentGeometryInstance = 0; currentGeometryInstance < geometryInstanceCount; currentGeometryInstance++) { domInstance_geometry *thisGeometryInstance; error = _dae->getDatabase()->getElement((daeElement**)&thisGeometryInstance,currentGeometryInstance, NULL, "instance_geometry", getInput(0).c_str()); if (error != DAE_OK) { return(-1); } domBind_materialRef bindMaterial = thisGeometryInstance->getBind_material(); if (bindMaterial != NULL) { domInstance_material_Array &instanceMaterialArray = bindMaterial->getTechnique_common()->getInstance_material_array(); int materialArrayCount = (int)instanceMaterialArray.getCount(); for (int i = 0; i < materialArrayCount; i++) { domInstance_material::domBind_vertex_input_Array &bindInputArray = instanceMaterialArray[i]->getBind_vertex_input_array(); int bindInputArrayCount = (int)bindInputArray.getCount(); for (int j = 0; j < bindInputArrayCount; j++) { xsNCName inputSemantic = bindInputArray[j]->getInput_semantic(); if (strcmp(inputSemantic, "TEXTCOORD") == 0) bindInputArray[j]->setInput_semantic("TEXCOORD"); } // for } // for } // if } // for } // if KMZ fix if ( 1 /*(strstr(ref->getValue(), "SketchUp") != NULL) || (strstr(ref->getValue(), "Google") != NULL) || (strstr(ref->getValue(), "PhotoModeler") != NULL)*/ ) { printf("start kmz cleaning...\n"); // change /library_effects/effect/profile_COMMON/technique/phong/diffuse/texture@texcoord="1" to texture@texcoord="UVSET0" unsigned int phongCount = _dae->getDatabase()->getElementCount(NULL, COLLADA_TYPE_PHONG, getInput(0).c_str()); //cerr<<"There are "<<phongCount<<" phongs in this file\n"; domProfile_COMMON::domTechnique::domPhong * thisPhong; domCommon_color_or_texture_type_complexType::domTexture * thisTexture; for (unsigned int i = 0; i < phongCount; i++) { //Get the next phong error = _dae->getDatabase()->getElement((daeElement**)&thisPhong, i, NULL, COLLADA_TYPE_PHONG, getInput(0).c_str()); if (error != DAE_OK) continue; domCommon_color_or_texture_type * thisDiffuse; thisDiffuse = thisPhong->getDiffuse(); if (thisDiffuse != NULL) { thisTexture = thisDiffuse->getTexture(); if (thisTexture != NULL) { xsNCName attribute = thisTexture->getTexcoord(); //cerr<<"texture coordinate : "<<attribute<<"\n"; if (strcmp(attribute, "1") == 0) { //cerr<<"set texture coordinate\n"; thisTexture->setTexcoord("UVSET0"); } xsNCName texture = thisTexture->getTexture(); char *texture_1; if (texture) { if (texture[0] >= '0' && texture[0] <= '9') { texture_1 = new char[strlen(texture) + 1 + 1]; sprintf(texture_1, "a%s", texture); } else { texture_1 = new char[strlen(texture) + 1]; strcpy(texture_1, texture); } //printf("texture image is %s\n", texture); daeElement *parent = thisPhong->getParentElement(); domProfile_COMMON::domTechnique *thisTechnique = (domProfile_COMMON::domTechnique *)parent; //domCommon_newparam_type * thisNewParam = (domCommon_newparam_type *)thisTechnique->createAndPlace("newparam"); daeElement *parent2 = thisTechnique->getParentElement(); domProfile_COMMON *thisProfile = (domProfile_COMMON *)parent2; int newparam_count = (int)thisProfile->getNewparam_array().getCount(); if (newparam_count == 0 ) { domCommon_newparam_type * thisNewParam = (domCommon_newparam_type *)thisProfile->createAndPlace("newparam"); char *surface_id = new char[strlen(texture_1) + 1 + 8]; sprintf(surface_id, "%s-surface", texture_1); //printf("surface id is %s\n", surface_id); thisNewParam->setSid(surface_id); domFx_surface_common * thisSurface = (domFx_surface_common *)thisNewParam->createAndPlace("surface"); thisSurface->setType(FX_SURFACE_TYPE_ENUM_2D); domFx_surface_init_from_common * thisInitFrom = (domFx_surface_init_from_common *)thisSurface->createAndPlace("init_from"); thisInitFrom->setValue(texture_1); domCommon_newparam_type * thisNewParam2 = (domCommon_newparam_type *)thisProfile->createAndPlace("newparam"); char *sampler_id = new char[strlen(texture_1) + 1 + 8]; sprintf(sampler_id, "%s-sampler", texture_1); //printf("sampler id is %s\n", sampler_id); thisNewParam2->setSid(sampler_id); domFx_sampler2D_common * thisSampler2D = (domFx_sampler2D_common *)thisNewParam2->createAndPlace("sampler2D"); domFx_sampler2D_common::domSource * thisSource = (domFx_sampler2D_common::domSource *)thisSampler2D->createAndPlace("source"); //printf("before source set id\n"); thisSource->setValue(surface_id); //printf("after source set id\n"); thisTexture->setTexture(sampler_id); delete [] surface_id; delete [] sampler_id; } } } //if }//if } //for // remove library_geometries/geometry/mesh/triangles@material="BackColor" // remove library_geometries/geometry/mesh/lines@material="EdgeColor" unsigned int geometryElementCount = _dae->getDatabase()->getElementCount(NULL, "geometry", getInput(0).c_str()); // Iterate over all the geometry assets for(unsigned int currentGeometry = 0; currentGeometry < geometryElementCount; currentGeometry++) { // Get the next geometry element domGeometry *thisGeometry; error = _dae->getDatabase()->getElement((daeElement**)&thisGeometry,currentGeometry, NULL, "geometry", getInput(0).c_str()); if (error != DAE_OK) { return(-1); } // Get the geometry element's mesh domMesh *thisMesh = thisGeometry->getMesh(); if (thisMesh==NULL) continue; // if there are no mesh in this geometry, skip to next one // Loop over all the triangle assets in this mesh int trianglesAssetCount = (int) thisMesh->getTriangles_array().getCount(); //printf("there are %d triangles\n", trianglesAssetCount); for(int currentTriangles = 0; currentTriangles < trianglesAssetCount; currentTriangles++) { domTriangles *thisTriangles = thisMesh->getTriangles_array().get(currentTriangles); if (thisTriangles != NULL) { xsNCName triMaterial = thisTriangles->getMaterial(); if (triMaterial) { if (strcmp(triMaterial, "BackColor") == 0) { //printf("remove the triangle with backcolor\n"); thisMesh->removeChildElement(thisTriangles); currentTriangles--; trianglesAssetCount--; } // if } } // if } // for /*int linesCount = (int) thisMesh->getLines_array().getCount(); printf("there are %d lines\n", linesCount); for (int currentLines = 0; currentLines < linesCount; currentLines++) { domLines *thisLines = thisMesh->getLines_array().get(currentLines); if (thisLines != NULL) { xsNCName lineMaterial= thisLines->getMaterial(); if (strcmp(lineMaterial, "EdgeColor") == 0) { printf("remove the line with edgecolor\n"); thisMesh->removeChildElement(thisLines); currentLines--; linesCount--; } // if } // if } // for*/ } // for // change the id/name of images/materials/effects if they start with a numerical number int imageElementCount = (int)(_dae->getDatabase()->getElementCount(NULL, "image", getInput(0).c_str())); for(int currentImg = 0; currentImg < imageElementCount; currentImg++) { domImage *thisImage; error = _dae->getDatabase()->getElement((daeElement**)&thisImage,currentImg, NULL, "image", getInput(0).c_str()); xsID image_id = thisImage->getId(); if (image_id) { if (image_id[0] >= '0' && image_id[0] <= '9') { char *image_id_1 = new char[strlen(image_id) + 1 + 1]; sprintf(image_id_1, "a%s", image_id); thisImage->setId(image_id_1); delete [] image_id_1; } } xsNCName image_name = thisImage->getName(); if (image_name) { if (image_name[0] >= '0' && image_name[0] <= '9') { char *image_name_1 = new char[strlen(image_name) + 1 + 1]; sprintf(image_name_1, "a%s", image_name); thisImage->setName(image_name_1); delete [] image_name_1; } } } int materialElementCount = (int)(_dae->getDatabase()->getElementCount(NULL, "material", getInput(0).c_str())); for(int currentMat = 0; currentMat < materialElementCount; currentMat++) { domMaterial *thisMaterial; error = _dae->getDatabase()->getElement((daeElement**)&thisMaterial,currentMat, NULL, "material", getInput(0).c_str()); xsID material_id = thisMaterial->getId(); if (material_id) { if (material_id[0] >= '0' && material_id[0] <= '9') { char *material_id_1 = new char[strlen(material_id) + 1 + 1]; sprintf(material_id_1, "a%s", material_id); thisMaterial->setId(material_id_1); delete [] material_id_1; } } xsNCName material_name = thisMaterial->getName(); if (material_name) { if (material_name[0] >= '0' && material_name[0] <= '9') { char *material_name_1 = new char[strlen(material_name) + 1 + 1]; sprintf(material_name_1, "a%s", material_name); thisMaterial->setName(material_name_1); delete [] material_name_1; } } domInstance_effectRef instance_ref = thisMaterial->getInstance_effect(); daeString uri = instance_ref->getUrl().getURI(); printf("uri is %s\n", uri); daeString id = instance_ref->getUrl().getID(); printf("uri id is %s\n", id); if (id[0] >= '0' && id[0] <= '9') { char *uri_1 = new char[strlen(id) + 1 + 1]; sprintf(uri_1, "#a%s", id); daeURI thisUri((DAE&)*_dae, (daeString)uri_1, false); instance_ref->setUrl(thisUri); } } int effectElementCount = (int)(_dae->getDatabase()->getElementCount(NULL, "effect", getInput(0).c_str())); for(int currentEffect = 0; currentEffect < effectElementCount; currentEffect++) { domEffect *thisEffect; error = _dae->getDatabase()->getElement((daeElement**)&thisEffect,currentEffect, NULL, "effect", getInput(0).c_str()); xsID effect_id = thisEffect->getId(); if (effect_id) { if (effect_id[0] >= '0' && effect_id[0] <= '9') { effect_change = true; char *effect_id_1 = new char[strlen(effect_id) + 1 + 1]; sprintf(effect_id_1, "a%s", effect_id); thisEffect->setId(effect_id_1); delete [] effect_id_1; } } xsNCName effect_name = thisEffect->getName(); if (effect_name) { if (effect_name[0] >= '0' && effect_name[0] <= '9') { char *effect_name_1 = new char[strlen(effect_name) + 1 + 1]; sprintf(effect_name_1, "a%s", effect_name); thisEffect->setName(effect_name_1); delete [] effect_name_1; } } } // add bind_material unsigned int geometryInstanceCount = _dae->getDatabase()->getElementCount(NULL, "instance_geometry", getInput(0).c_str()); //printf("there are %d instance_geometry\n", geometryInstanceCount); for (unsigned int currentGeometryInstance = 0; currentGeometryInstance < geometryInstanceCount; currentGeometryInstance++) { domInstance_geometry *thisGeometryInstance; error = _dae->getDatabase()->getElement((daeElement**)&thisGeometryInstance,currentGeometryInstance, NULL, "instance_geometry", getInput(0).c_str()); if (error != DAE_OK) { return(-1); } daeElementRef thisElement = thisGeometryInstance->getUrl().getElement(); domGeometry *thisGeometry = (domGeometry *)(daeElement*)thisElement; //printf("get the geometry\n"); // Get the geometry element's mesh domMesh *thisMesh = thisGeometry->getMesh(); //printf("get the mesh\n"); if (thisMesh==NULL) continue; // if there are no mesh in this geometry, skip to next one // Loop over all the polygon assets in this mesh int polygonsAssetCount = (int) thisMesh->getPolygons_array().getCount(); //printf("there are %d polygons\n", polygonsAssetCount); for(int currentPolygons = 0; currentPolygons < polygonsAssetCount; currentPolygons++) { domPolygons *thisPolygons = thisMesh->getPolygons_array().get(currentPolygons); if (thisPolygons) { xsNCName polygonMaterial = thisPolygons->getMaterial(); if (polygonMaterial) { if (polygonMaterial[0] >= '0' && polygonMaterial[0] <= '9') { char *polygonMaterial_1 = new char[strlen(polygonMaterial) + 1 + 1]; sprintf(polygonMaterial_1, "a%s", polygonMaterial); thisPolygons->setMaterial(polygonMaterial_1); int set = processprimitive(thisPolygons, verbose); strmap.insert(pair<string, int>(polygonMaterial_1, set)); delete [] polygonMaterial_1; } else { int set = processprimitive(thisPolygons, verbose); strmap.insert(pair<string, int>(polygonMaterial, set)); } } } } // Loop over all the polylist assets in this mesh int polylistsAssetCount = (int) thisMesh->getPolylist_array().getCount(); //printf("there are %d polylists\n", polylistsAssetCount); for(int currentPolylists = 0; currentPolylists < polylistsAssetCount; currentPolylists++) { domPolylist *thisPolylists = thisMesh->getPolylist_array().get(currentPolylists); if (thisPolylists) { xsNCName polylistMaterial = thisPolylists->getMaterial(); if (polylistMaterial) { if (polylistMaterial[0] >= '0' && polylistMaterial[0] <= '9') { char *polylistMaterial_1 = new char[strlen(polylistMaterial) + 1 + 1]; sprintf(polylistMaterial_1, "a%s", polylistMaterial); thisPolylists->setMaterial(polylistMaterial_1); int set = processprimitive(thisPolylists, verbose); strmap.insert(pair<string, int>(polylistMaterial_1, set)); delete [] polylistMaterial_1; } else { int set = processprimitive(thisPolylists, verbose); strmap.insert(pair<string, int>(polylistMaterial, set)); } } } } // Loop over all the triangle assets in this mesh int trianglesAssetCount = (int) thisMesh->getTriangles_array().getCount(); //printf("there are %d triangles\n", trianglesAssetCount); for(int currentTriangles = 0; currentTriangles < trianglesAssetCount; currentTriangles++) { domTriangles *thisTriangles = thisMesh->getTriangles_array().get(currentTriangles); if (thisTriangles) { xsNCName triangleMaterial = thisTriangles->getMaterial(); if (triangleMaterial) { if (triangleMaterial[0] >= '0' && triangleMaterial[0] <= '9') { char *triangleMaterial_1 = new char[strlen(triangleMaterial) + 1 + 1]; sprintf(triangleMaterial_1, "a%s", triangleMaterial); thisTriangles->setMaterial(triangleMaterial_1); int set = processprimitive(thisTriangles, verbose); strmap.insert(pair<string, int>(triangleMaterial_1, set)); delete [] triangleMaterial_1; } else { int set = processprimitive(thisTriangles, verbose); strmap.insert(pair<string, int>(triangleMaterial, set)); } } } } // Loop over all the tristrips assets in this mesh int tristripsAssetCount = (int) thisMesh->getTristrips_array().getCount(); //printf("there are %d tristrips\n", tristripsAssetCount); for(int currentTristrips = 0; currentTristrips < tristripsAssetCount; currentTristrips++) { domTristrips *thisTristrips = thisMesh->getTristrips_array().get(currentTristrips); if (thisTristrips) { xsNCName tristripMaterial = thisTristrips->getMaterial(); if (tristripMaterial) { if (tristripMaterial[0] >= '0' && tristripMaterial[0] <= '9') { char *tristripMaterial_1 = new char[strlen(tristripMaterial) + 1 + 1]; sprintf(tristripMaterial_1, "a%s", tristripMaterial); thisTristrips->setMaterial(tristripMaterial_1); int set = processprimitive(thisTristrips, verbose); strmap.insert(pair<string, int>(tristripMaterial_1, set)); delete [] tristripMaterial_1; } else { int set = processprimitive(thisTristrips, verbose); strmap.insert(pair<string, int>(tristripMaterial, set)); } } } } // Loop over all the trifans assets in this mesh int trifansAssetCount = (int) thisMesh->getTrifans_array().getCount(); //printf("there are %d trifans\n", trifansAssetCount); for(int currentTrifans = 0; currentTrifans < trifansAssetCount; currentTrifans++) { domTrifans *thisTrifans = thisMesh->getTrifans_array().get(currentTrifans); if (thisTrifans) { xsNCName trifanMaterial = thisTrifans->getMaterial(); if (trifanMaterial) { if (trifanMaterial[0] >= '0' && trifanMaterial[0] <= '9') { char *trifanMaterial_1 = new char[strlen(trifanMaterial) + 1 + 1]; sprintf(trifanMaterial_1, "a%s", trifanMaterial); thisTrifans->setMaterial(trifanMaterial_1); int set = processprimitive(thisTrifans, verbose); strmap.insert(pair<string, int>(trifanMaterial_1, set)); delete [] trifanMaterial_1; } else { int set = processprimitive(thisTrifans, verbose); strmap.insert(pair<string, int>(trifanMaterial, set)); } } } } // Loop over all the lines assets in this mesh int linesAssetCount = (int) thisMesh->getLines_array().getCount(); //printf("there are %d lines\n", linesAssetCount); for(int currentLines = 0; currentLines < linesAssetCount; currentLines++) { domLines *thisLines = thisMesh->getLines_array().get(currentLines); if (thisLines) { xsNCName lineMaterial = thisLines->getMaterial(); if (lineMaterial) { if (lineMaterial[0] >= '0' && lineMaterial[0] <= '9') { char *lineMaterial_1 = new char[strlen(lineMaterial) + 1 + 1]; sprintf(lineMaterial_1, "a%s", lineMaterial); thisLines->setMaterial(lineMaterial_1); int set = processprimitive(thisLines, verbose); strmap.insert(pair<string, int>(lineMaterial_1, set)); delete [] lineMaterial_1; } else { int set = processprimitive(thisLines, verbose); strmap.insert(pair<string, int>(lineMaterial, set)); } } } } // Loop over all the linestrips assets in this mesh int linestripsAssetCount = (int) thisMesh->getLinestrips_array().getCount(); //printf("there are %d linestrips\n", linestripsAssetCount); for(int currentLinestrips = 0; currentLinestrips < linestripsAssetCount; currentLinestrips++) { domLinestrips *thisLinestrips = thisMesh->getLinestrips_array().get(currentLinestrips); if (thisLinestrips) { xsNCName linestripMaterial = thisLinestrips->getMaterial(); if (linestripMaterial) { if (linestripMaterial[0] >= '0' && linestripMaterial[0] <= '9') { char *linestripMaterial_1 = new char[strlen(linestripMaterial) + 1 + 1]; sprintf(linestripMaterial_1, "a%s", linestripMaterial); thisLinestrips->setMaterial(linestripMaterial_1); int set = processprimitive(thisLinestrips, verbose); strmap.insert(pair<string, int>(linestripMaterial_1, set)); delete [] linestripMaterial_1; } else { int set = processprimitive(thisLinestrips, verbose); strmap.insert(pair<string, int>(linestripMaterial, set)); } } } } /*for (si=strmap.begin(); si!=strmap.end(); si++) { cout << (*si).first << " "; cout << endl; }*/ domBind_materialRef bindMaterial = thisGeometryInstance->getBind_material(); if (bindMaterial == NULL) { if (strmap.size() != 0) { domBind_material *thisBindMaterial = (domBind_material *)thisGeometryInstance->createAndPlace("bind_material"); domSource::domTechnique_common *thisTechniqueCommon = (domSource::domTechnique_common *)thisBindMaterial->createAndPlace("technique_common"); for (si=strmap.begin(); si!=strmap.end();si++) { domInstance_material * thisInstanceMaterial = (domInstance_material *)thisTechniqueCommon->createAndPlace("instance_material"); string targetValue("#"); targetValue += (*si).first.c_str(); //printf("symbol value is %s\n", (*si).c_str()); //printf("target value is %s\n", targetValue.c_str()); thisInstanceMaterial->setSymbol((*si).first.c_str()); daeURI thisUri((DAE&)*(daeString)targetValue.c_str(), false); thisInstanceMaterial->setTarget(thisUri); //check if it needs <bind_vertex_input> //printf("material name is %s\n", (*si).first.c_str()); if (effect_change == true) { //printf("bind vertex is needed\n"); domInstance_material::domBind_vertex_input * thisBindVertexInput = (domInstance_material::domBind_vertex_input *)thisInstanceMaterial->createAndPlace("bind_vertex_input"); thisBindVertexInput->setSemantic("UVSET0"); thisBindVertexInput->setInput_semantic("TEXCOORD"); thisBindVertexInput->setInput_set((*si).second); } else if (checkbindneeded(_dae, (*si).first.c_str(), verbose) == true) { //printf("bind vertex is needed\n"); domInstance_material::domBind_vertex_input * thisBindVertexInput = (domInstance_material::domBind_vertex_input *)thisInstanceMaterial->createAndPlace("bind_vertex_input"); thisBindVertexInput->setSemantic("UVSET0"); thisBindVertexInput->setInput_semantic("TEXCOORD"); thisBindVertexInput->setInput_set((*si).second); } else { printf("bind vertex is not needed\n"); } } strmap.clear(); } } else { domInstance_material_Array &instanceMaterialArray = bindMaterial->getTechnique_common()->getInstance_material_array(); int materialArrayCount = (int)instanceMaterialArray.getCount(); printf("material array count is %d\n", materialArrayCount); for (int i = 0; i < materialArrayCount; i++) { domInstance_material::domBind_Array &bindArray = instanceMaterialArray[i]->getBind_array(); int bindArrayCount = (int)bindArray.getCount(); printf("bind array count is %d\n", bindArrayCount); if (bindArrayCount != 0) { xsNCName symbol = instanceMaterialArray[i]->getSymbol(); for (int j = 0; j < bindArrayCount; j++) { instanceMaterialArray[i]->removeChildElement(bindArray[j]); } domInstance_material::domBind_vertex_input * thisBindVertexInput = (domInstance_material::domBind_vertex_input *)instanceMaterialArray[i]->createAndPlace("bind_vertex_input"); thisBindVertexInput->setSemantic("UVSET0"); thisBindVertexInput->setInput_semantic("TEXCOORD"); for (si = strmap.begin(); si != strmap.end(); si++) { if (strcmp(symbol, (*si).first.c_str()) == 0) { thisBindVertexInput->setInput_set((*si).second); } } } } } // else } //ref->setValue("KMZ fix"); unsigned int index = 0; daeDocument * thisDocument = (daeDocument *)_dae->getDatabase()->getDocument(index); domCOLLADA *thisCollada = (domCOLLADA *)thisDocument->getDomRoot(); thisCollada->setAttribute("version", "1.4.1"); break; } } } } // for return 0; } Conditioner::Register< KmzcleanupProxy > kmzcleanupProxy;
b8fe6611b60524ce0b207b59d81ea2ed68c21cdf
4c6f379972a5aba051681f90a6727c4b9c3c5fff
/src/ProxyClient/ProxyClient.cpp
f41c83d7917bc05250660e1a79c740f9e0dd928f
[]
no_license
metahashorg/metagate
8aa6db7c9ad99b3ce9735c00123783030a59c2a3
ae03640e64a0db148b4f937626a1a8ae9a0137e0
refs/heads/master
2022-02-24T21:13:22.343544
2022-02-02T11:03:20
2022-02-02T11:03:20
134,271,725
37
17
null
2019-04-15T13:02:41
2018-05-21T13:17:51
C++
UTF-8
C++
false
false
6,126
cpp
ProxyClient.cpp
#include "ProxyClient.h" #include "ProxyClientMessage.h" #include "MetaGate/MetaGate.h" #include "qt_utilites/SlotWrapper.h" #include "qt_utilites/QRegister.h" #include "qt_utilites/ManagerWrapperImpl.h" #include "utilites/machine_uid.h" #include "Paths.h" #include <QSettings> SET_LOG_NAMESPACE("PXC"); namespace proxy_client { ProxyClient::ProxyClient(metagate::MetaGate &metagate, QObject *parent) : TimerClass(20s, parent) , proxyClient(new localconnection::LocalClient(getLocalServerPath(), this)) , mhProxyActive(false) { hardwareId = QString::fromStdString(::getMachineUid()); Q_CONNECT(proxyClient, &localconnection::LocalClient::callbackCall, this, &ProxyClient::callbackCall); Q_CONNECT(this, &ProxyClient::getStatus, this, &ProxyClient::onGetStatus); Q_CONNECT(this, &ProxyClient::getEnabledSetting, this, &ProxyClient::onGetEnabledSetting); Q_CONNECT(this, &ProxyClient::setProxyConfigAndRestart, this, &ProxyClient::onSetProxyConfigAndRestart); Q_CONNECT(this, &ProxyClient::getMHProxyStatus, this, &ProxyClient::onGetMHProxyStatus); Q_CONNECT(&metagate, &metagate::MetaGate::forgingActiveChanged, this, &ProxyClient::onForgingActiveChanged); Q_REG(ProxyClient::GetStatusCallback, "ProxyClient::GetStatusCallback"); Q_REG(SetProxyConfigAndRestartCallback, "SetProxyConfigAndRestartCallback"); Q_REG(GetEnabledSettingCallback, "GetEnabledSettingCallback"); Q_REG(GetMHProxyStatusCallback, "GetMHProxyStatusCallback"); moveToThread(TimerClass::getThread()); emit metagate.activeForgingreEmit(); } ProxyClient::~ProxyClient() { TimerClass::exit(); } //void ProxyClient::mvToThread(QThread *th) { // proxyClient.mvToThread(th); // this->moveToThread(th); //} void ProxyClient::startMethod() { checkServiceState(); } void ProxyClient::timerMethod() { checkServiceState(); } void ProxyClient::finishMethod() { } void ProxyClient::onGetStatus(const GetStatusCallback &callback) { BEGIN_SLOT_WRAPPER runAndEmitErrorCallback([&]{ proxyClient->sendRequest(makeGetStatusMessage(), [callback](const localconnection::LocalClient::Response &response) { BEGIN_SLOT_WRAPPER QString status; const TypedException exception = apiVrapper2([&] { CHECK_TYPED(!response.exception.isSet(), TypeErrors::PROXY_SERVER_ERROR, response.exception.toString()); const ProxyResponse result = parseProxyResponse(response.response); CHECK_TYPED(!result.error, TypeErrors::PROXY_RESTART_ERROR, result.text.toStdString()); if (!response.exception.isSet()) { QString hwid; bool active; status = parseProxyStatusResponse(response.response, hwid, active); } }); callback.emitFunc(exception, status); END_SLOT_WRAPPER }); }, callback); END_SLOT_WRAPPER } void ProxyClient::onSetProxyConfigAndRestart(bool enabled, int port, const SetProxyConfigAndRestartCallback &callback) { BEGIN_SLOT_WRAPPER runAndEmitErrorCallback([&]{ generateProxyConfig(enabled, port); proxyClient->sendRequest(makeRefreshConfigMessage(), [callback](const localconnection::LocalClient::Response &response) { const TypedException exception = apiVrapper2([&] { CHECK_TYPED(!response.exception.isSet(), TypeErrors::PROXY_SERVER_ERROR, response.exception.toString()); const ProxyResponse result = parseProxyResponse(response.response); CHECK_TYPED(!result.error, TypeErrors::PROXY_RESTART_ERROR, result.text.toStdString()); }); callback.emitFunc(exception); }); }, callback); END_SLOT_WRAPPER } void ProxyClient::onGetMHProxyStatus(const ProxyClient::GetMHProxyStatusCallback &callback) { BEGIN_SLOT_WRAPPER runAndEmitCallback([&]{ return mhProxyActive; }, callback); END_SLOT_WRAPPER } void ProxyClient::onForgingActiveChanged(bool active) { BEGIN_SLOT_WRAPPER if (active == isProxyEnabled()) return; generateProxyConfig(active, 12000); proxyClient->sendRequest(makeRefreshConfigMessage(), [](const localconnection::LocalClient::Response &response) { CHECK_TYPED(!response.exception.isSet(), TypeErrors::PROXY_SERVER_ERROR, response.exception.toString()); const ProxyResponse result = parseProxyResponse(response.response); CHECK_TYPED(!result.error, TypeErrors::PROXY_RESTART_ERROR, result.text.toStdString()); }); END_SLOT_WRAPPER } void ProxyClient::generateProxyConfig(bool enabled, int port) { QSettings settings(getProxyConfigPath(), QSettings::IniFormat); settings.setValue("proxy/enabled", enabled); settings.setValue("proxy/port", port); settings.sync(); } bool ProxyClient::isProxyEnabled() const { QSettings settings(getProxyConfigPath(), QSettings::IniFormat); return settings.value("proxy/enabled", false).toBool(); } void ProxyClient::checkServiceState() { BEGIN_SLOT_WRAPPER proxyClient->sendRequest(makeGetStatusMessage(), [this](const localconnection::LocalClient::Response &response) { if (response.exception.isSet()) { mhProxyActive = false; } else { QString status; QString hwid; bool active = mhProxyActive; status = parseProxyStatusResponse(response.response, hwid, mhProxyActive); if (hwid != hardwareId) { LOG << "HW ids are not same: " << hardwareId << " - " << hwid; } if (active != mhProxyActive) { LOG << "Proxy status changed: " << mhProxyActive; } } }); END_SLOT_WRAPPER } void ProxyClient::onGetEnabledSetting(const GetEnabledSettingCallback &callback) { BEGIN_SLOT_WRAPPER runAndEmitCallback([&]{ QSettings settings(getProxyConfigPath(), QSettings::IniFormat); return settings.value("proxy/enabled", false).toBool(); }, callback); END_SLOT_WRAPPER } } // namespace proxy_client
172e237686a9e1c8a30567f4d3e67c96bd553a48
f4c7f7a66e5506e0622101a34624aec434d2bc31
/data_server/src/server_conf.pb.cc
49a7bf5c37739101473a5ced55318c6b6db199bb
[]
no_license
machaelliu/modbus_dev
02a56bbfa7723536afa81aa88bb10e7330fe1a69
2dd415b2ecddd06aa6b913978d5b26780bcab4da
refs/heads/master
2020-03-19T04:19:50.090247
2018-06-24T08:09:59
2018-06-24T08:09:59
135,816,806
0
0
null
null
null
null
UTF-8
C++
false
true
44,890
cc
server_conf.pb.cc
// Generated by the protocol buffer compiler. DO NOT EDIT! #define INTERNAL_SUPPRESS_PROTOBUF_FIELD_DEPRECATION #include "server_conf.pb.h" #include <algorithm> #include <google/protobuf/stubs/once.h> #include <google/protobuf/io/coded_stream.h> #include <google/protobuf/wire_format_lite_inl.h> #include <google/protobuf/descriptor.h> #include <google/protobuf/reflection_ops.h> #include <google/protobuf/wire_format.h> // @@protoc_insertion_point(includes) namespace data_server { namespace { const ::google::protobuf::Descriptor* MysqlConf_descriptor_ = NULL; const ::google::protobuf::internal::GeneratedMessageReflection* MysqlConf_reflection_ = NULL; const ::google::protobuf::Descriptor* RedisConf_descriptor_ = NULL; const ::google::protobuf::internal::GeneratedMessageReflection* RedisConf_reflection_ = NULL; const ::google::protobuf::Descriptor* ServerConfig_descriptor_ = NULL; const ::google::protobuf::internal::GeneratedMessageReflection* ServerConfig_reflection_ = NULL; } // namespace void protobuf_AssignDesc_server_5fconf_2eproto() { protobuf_AddDesc_server_5fconf_2eproto(); const ::google::protobuf::FileDescriptor* file = ::google::protobuf::DescriptorPool::generated_pool()->FindFileByName( "server_conf.proto"); GOOGLE_CHECK(file != NULL); MysqlConf_descriptor_ = file->message_type(0); static const int MysqlConf_offsets_[5] = { GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(MysqlConf, host_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(MysqlConf, port_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(MysqlConf, passwd_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(MysqlConf, user_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(MysqlConf, db_name_), }; MysqlConf_reflection_ = new ::google::protobuf::internal::GeneratedMessageReflection( MysqlConf_descriptor_, MysqlConf::default_instance_, MysqlConf_offsets_, GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(MysqlConf, _has_bits_[0]), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(MysqlConf, _unknown_fields_), -1, ::google::protobuf::DescriptorPool::generated_pool(), ::google::protobuf::MessageFactory::generated_factory(), sizeof(MysqlConf)); RedisConf_descriptor_ = file->message_type(1); static const int RedisConf_offsets_[2] = { GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(RedisConf, host_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(RedisConf, port_), }; RedisConf_reflection_ = new ::google::protobuf::internal::GeneratedMessageReflection( RedisConf_descriptor_, RedisConf::default_instance_, RedisConf_offsets_, GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(RedisConf, _has_bits_[0]), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(RedisConf, _unknown_fields_), -1, ::google::protobuf::DescriptorPool::generated_pool(), ::google::protobuf::MessageFactory::generated_factory(), sizeof(RedisConf)); ServerConfig_descriptor_ = file->message_type(2); static const int ServerConfig_offsets_[6] = { GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(ServerConfig, svr_port_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(ServerConfig, log4cpp_conf_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(ServerConfig, brpc_log_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(ServerConfig, data_db_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(ServerConfig, data_point_table_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(ServerConfig, mod_data_table_), }; ServerConfig_reflection_ = new ::google::protobuf::internal::GeneratedMessageReflection( ServerConfig_descriptor_, ServerConfig::default_instance_, ServerConfig_offsets_, GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(ServerConfig, _has_bits_[0]), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(ServerConfig, _unknown_fields_), -1, ::google::protobuf::DescriptorPool::generated_pool(), ::google::protobuf::MessageFactory::generated_factory(), sizeof(ServerConfig)); } namespace { GOOGLE_PROTOBUF_DECLARE_ONCE(protobuf_AssignDescriptors_once_); inline void protobuf_AssignDescriptorsOnce() { ::google::protobuf::GoogleOnceInit(&protobuf_AssignDescriptors_once_, &protobuf_AssignDesc_server_5fconf_2eproto); } void protobuf_RegisterTypes(const ::std::string&) { protobuf_AssignDescriptorsOnce(); ::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage( MysqlConf_descriptor_, &MysqlConf::default_instance()); ::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage( RedisConf_descriptor_, &RedisConf::default_instance()); ::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage( ServerConfig_descriptor_, &ServerConfig::default_instance()); } } // namespace void protobuf_ShutdownFile_server_5fconf_2eproto() { delete MysqlConf::default_instance_; delete MysqlConf_reflection_; delete RedisConf::default_instance_; delete RedisConf_reflection_; delete ServerConfig::default_instance_; delete ServerConfig_reflection_; } void protobuf_AddDesc_server_5fconf_2eproto() { static bool already_here = false; if (already_here) return; already_here = true; GOOGLE_PROTOBUF_VERIFY_VERSION; ::google::protobuf::DescriptorPool::InternalAddGeneratedFile( "\n\021server_conf.proto\022\013data_server\"V\n\tMysq" "lConf\022\014\n\004host\030\001 \002(\t\022\014\n\004port\030\002 \002(\005\022\016\n\006pas" "swd\030\003 \002(\t\022\014\n\004user\030\004 \002(\t\022\017\n\007db_name\030\005 \002(\t" "\"\'\n\tRedisConf\022\014\n\004host\030\001 \002(\t\022\014\n\004port\030\002 \002(" "\005\"\243\001\n\014ServerConfig\022\020\n\010svr_port\030\001 \002(\005\022\024\n\014" "log4cpp_conf\030\002 \002(\t\022\020\n\010brpc_log\030\003 \002(\t\022\'\n\007" "data_db\030\004 \002(\0132\026.data_server.MysqlConf\022\030\n" "\020data_point_table\030\005 \002(\t\022\026\n\016mod_data_tabl" "e\030\006 \002(\t", 327); ::google::protobuf::MessageFactory::InternalRegisterGeneratedFile( "server_conf.proto", &protobuf_RegisterTypes); MysqlConf::default_instance_ = new MysqlConf(); RedisConf::default_instance_ = new RedisConf(); ServerConfig::default_instance_ = new ServerConfig(); MysqlConf::default_instance_->InitAsDefaultInstance(); RedisConf::default_instance_->InitAsDefaultInstance(); ServerConfig::default_instance_->InitAsDefaultInstance(); ::google::protobuf::internal::OnShutdown(&protobuf_ShutdownFile_server_5fconf_2eproto); } // Force AddDescriptors() to be called at static initialization time. struct StaticDescriptorInitializer_server_5fconf_2eproto { StaticDescriptorInitializer_server_5fconf_2eproto() { protobuf_AddDesc_server_5fconf_2eproto(); } } static_descriptor_initializer_server_5fconf_2eproto_; // =================================================================== #ifndef _MSC_VER const int MysqlConf::kHostFieldNumber; const int MysqlConf::kPortFieldNumber; const int MysqlConf::kPasswdFieldNumber; const int MysqlConf::kUserFieldNumber; const int MysqlConf::kDbNameFieldNumber; #endif // !_MSC_VER MysqlConf::MysqlConf() : ::google::protobuf::Message() { SharedCtor(); } void MysqlConf::InitAsDefaultInstance() { } MysqlConf::MysqlConf(const MysqlConf& from) : ::google::protobuf::Message() { SharedCtor(); MergeFrom(from); } void MysqlConf::SharedCtor() { _cached_size_ = 0; host_ = const_cast< ::std::string*>(&::google::protobuf::internal::kEmptyString); port_ = 0; passwd_ = const_cast< ::std::string*>(&::google::protobuf::internal::kEmptyString); user_ = const_cast< ::std::string*>(&::google::protobuf::internal::kEmptyString); db_name_ = const_cast< ::std::string*>(&::google::protobuf::internal::kEmptyString); ::memset(_has_bits_, 0, sizeof(_has_bits_)); } MysqlConf::~MysqlConf() { SharedDtor(); } void MysqlConf::SharedDtor() { if (host_ != &::google::protobuf::internal::kEmptyString) { delete host_; } if (passwd_ != &::google::protobuf::internal::kEmptyString) { delete passwd_; } if (user_ != &::google::protobuf::internal::kEmptyString) { delete user_; } if (db_name_ != &::google::protobuf::internal::kEmptyString) { delete db_name_; } if (this != default_instance_) { } } void MysqlConf::SetCachedSize(int size) const { GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); _cached_size_ = size; GOOGLE_SAFE_CONCURRENT_WRITES_END(); } const ::google::protobuf::Descriptor* MysqlConf::descriptor() { protobuf_AssignDescriptorsOnce(); return MysqlConf_descriptor_; } const MysqlConf& MysqlConf::default_instance() { if (default_instance_ == NULL) protobuf_AddDesc_server_5fconf_2eproto(); return *default_instance_; } MysqlConf* MysqlConf::default_instance_ = NULL; MysqlConf* MysqlConf::New() const { return new MysqlConf; } void MysqlConf::Clear() { if (_has_bits_[0 / 32] & (0xffu << (0 % 32))) { if (has_host()) { if (host_ != &::google::protobuf::internal::kEmptyString) { host_->clear(); } } port_ = 0; if (has_passwd()) { if (passwd_ != &::google::protobuf::internal::kEmptyString) { passwd_->clear(); } } if (has_user()) { if (user_ != &::google::protobuf::internal::kEmptyString) { user_->clear(); } } if (has_db_name()) { if (db_name_ != &::google::protobuf::internal::kEmptyString) { db_name_->clear(); } } } ::memset(_has_bits_, 0, sizeof(_has_bits_)); mutable_unknown_fields()->Clear(); } bool MysqlConf::MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input) { #define DO_(EXPRESSION) if (!(EXPRESSION)) return false ::google::protobuf::uint32 tag; while ((tag = input->ReadTag()) != 0) { switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { // required string host = 1; case 1: { if (::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == ::google::protobuf::internal::WireFormatLite::WIRETYPE_LENGTH_DELIMITED) { DO_(::google::protobuf::internal::WireFormatLite::ReadString( input, this->mutable_host())); ::google::protobuf::internal::WireFormat::VerifyUTF8String( this->host().data(), this->host().length(), ::google::protobuf::internal::WireFormat::PARSE); } else { goto handle_uninterpreted; } if (input->ExpectTag(16)) goto parse_port; break; } // required int32 port = 2; case 2: { if (::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == ::google::protobuf::internal::WireFormatLite::WIRETYPE_VARINT) { parse_port: DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< ::google::protobuf::int32, ::google::protobuf::internal::WireFormatLite::TYPE_INT32>( input, &port_))); set_has_port(); } else { goto handle_uninterpreted; } if (input->ExpectTag(26)) goto parse_passwd; break; } // required string passwd = 3; case 3: { if (::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == ::google::protobuf::internal::WireFormatLite::WIRETYPE_LENGTH_DELIMITED) { parse_passwd: DO_(::google::protobuf::internal::WireFormatLite::ReadString( input, this->mutable_passwd())); ::google::protobuf::internal::WireFormat::VerifyUTF8String( this->passwd().data(), this->passwd().length(), ::google::protobuf::internal::WireFormat::PARSE); } else { goto handle_uninterpreted; } if (input->ExpectTag(34)) goto parse_user; break; } // required string user = 4; case 4: { if (::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == ::google::protobuf::internal::WireFormatLite::WIRETYPE_LENGTH_DELIMITED) { parse_user: DO_(::google::protobuf::internal::WireFormatLite::ReadString( input, this->mutable_user())); ::google::protobuf::internal::WireFormat::VerifyUTF8String( this->user().data(), this->user().length(), ::google::protobuf::internal::WireFormat::PARSE); } else { goto handle_uninterpreted; } if (input->ExpectTag(42)) goto parse_db_name; break; } // required string db_name = 5; case 5: { if (::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == ::google::protobuf::internal::WireFormatLite::WIRETYPE_LENGTH_DELIMITED) { parse_db_name: DO_(::google::protobuf::internal::WireFormatLite::ReadString( input, this->mutable_db_name())); ::google::protobuf::internal::WireFormat::VerifyUTF8String( this->db_name().data(), this->db_name().length(), ::google::protobuf::internal::WireFormat::PARSE); } else { goto handle_uninterpreted; } if (input->ExpectAtEnd()) return true; break; } default: { handle_uninterpreted: if (::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == ::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) { return true; } DO_(::google::protobuf::internal::WireFormat::SkipField( input, tag, mutable_unknown_fields())); break; } } } return true; #undef DO_ } void MysqlConf::SerializeWithCachedSizes( ::google::protobuf::io::CodedOutputStream* output) const { // required string host = 1; if (has_host()) { ::google::protobuf::internal::WireFormat::VerifyUTF8String( this->host().data(), this->host().length(), ::google::protobuf::internal::WireFormat::SERIALIZE); ::google::protobuf::internal::WireFormatLite::WriteString( 1, this->host(), output); } // required int32 port = 2; if (has_port()) { ::google::protobuf::internal::WireFormatLite::WriteInt32(2, this->port(), output); } // required string passwd = 3; if (has_passwd()) { ::google::protobuf::internal::WireFormat::VerifyUTF8String( this->passwd().data(), this->passwd().length(), ::google::protobuf::internal::WireFormat::SERIALIZE); ::google::protobuf::internal::WireFormatLite::WriteString( 3, this->passwd(), output); } // required string user = 4; if (has_user()) { ::google::protobuf::internal::WireFormat::VerifyUTF8String( this->user().data(), this->user().length(), ::google::protobuf::internal::WireFormat::SERIALIZE); ::google::protobuf::internal::WireFormatLite::WriteString( 4, this->user(), output); } // required string db_name = 5; if (has_db_name()) { ::google::protobuf::internal::WireFormat::VerifyUTF8String( this->db_name().data(), this->db_name().length(), ::google::protobuf::internal::WireFormat::SERIALIZE); ::google::protobuf::internal::WireFormatLite::WriteString( 5, this->db_name(), output); } if (!unknown_fields().empty()) { ::google::protobuf::internal::WireFormat::SerializeUnknownFields( unknown_fields(), output); } } ::google::protobuf::uint8* MysqlConf::SerializeWithCachedSizesToArray( ::google::protobuf::uint8* target) const { // required string host = 1; if (has_host()) { ::google::protobuf::internal::WireFormat::VerifyUTF8String( this->host().data(), this->host().length(), ::google::protobuf::internal::WireFormat::SERIALIZE); target = ::google::protobuf::internal::WireFormatLite::WriteStringToArray( 1, this->host(), target); } // required int32 port = 2; if (has_port()) { target = ::google::protobuf::internal::WireFormatLite::WriteInt32ToArray(2, this->port(), target); } // required string passwd = 3; if (has_passwd()) { ::google::protobuf::internal::WireFormat::VerifyUTF8String( this->passwd().data(), this->passwd().length(), ::google::protobuf::internal::WireFormat::SERIALIZE); target = ::google::protobuf::internal::WireFormatLite::WriteStringToArray( 3, this->passwd(), target); } // required string user = 4; if (has_user()) { ::google::protobuf::internal::WireFormat::VerifyUTF8String( this->user().data(), this->user().length(), ::google::protobuf::internal::WireFormat::SERIALIZE); target = ::google::protobuf::internal::WireFormatLite::WriteStringToArray( 4, this->user(), target); } // required string db_name = 5; if (has_db_name()) { ::google::protobuf::internal::WireFormat::VerifyUTF8String( this->db_name().data(), this->db_name().length(), ::google::protobuf::internal::WireFormat::SERIALIZE); target = ::google::protobuf::internal::WireFormatLite::WriteStringToArray( 5, this->db_name(), target); } if (!unknown_fields().empty()) { target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray( unknown_fields(), target); } return target; } int MysqlConf::ByteSize() const { int total_size = 0; if (_has_bits_[0 / 32] & (0xffu << (0 % 32))) { // required string host = 1; if (has_host()) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::StringSize( this->host()); } // required int32 port = 2; if (has_port()) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::Int32Size( this->port()); } // required string passwd = 3; if (has_passwd()) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::StringSize( this->passwd()); } // required string user = 4; if (has_user()) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::StringSize( this->user()); } // required string db_name = 5; if (has_db_name()) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::StringSize( this->db_name()); } } if (!unknown_fields().empty()) { total_size += ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize( unknown_fields()); } GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); _cached_size_ = total_size; GOOGLE_SAFE_CONCURRENT_WRITES_END(); return total_size; } void MysqlConf::MergeFrom(const ::google::protobuf::Message& from) { GOOGLE_CHECK_NE(&from, this); const MysqlConf* source = ::google::protobuf::internal::dynamic_cast_if_available<const MysqlConf*>( &from); if (source == NULL) { ::google::protobuf::internal::ReflectionOps::Merge(from, this); } else { MergeFrom(*source); } } void MysqlConf::MergeFrom(const MysqlConf& from) { GOOGLE_CHECK_NE(&from, this); if (from._has_bits_[0 / 32] & (0xffu << (0 % 32))) { if (from.has_host()) { set_host(from.host()); } if (from.has_port()) { set_port(from.port()); } if (from.has_passwd()) { set_passwd(from.passwd()); } if (from.has_user()) { set_user(from.user()); } if (from.has_db_name()) { set_db_name(from.db_name()); } } mutable_unknown_fields()->MergeFrom(from.unknown_fields()); } void MysqlConf::CopyFrom(const ::google::protobuf::Message& from) { if (&from == this) return; Clear(); MergeFrom(from); } void MysqlConf::CopyFrom(const MysqlConf& from) { if (&from == this) return; Clear(); MergeFrom(from); } bool MysqlConf::IsInitialized() const { if ((_has_bits_[0] & 0x0000001f) != 0x0000001f) return false; return true; } void MysqlConf::Swap(MysqlConf* other) { if (other != this) { std::swap(host_, other->host_); std::swap(port_, other->port_); std::swap(passwd_, other->passwd_); std::swap(user_, other->user_); std::swap(db_name_, other->db_name_); std::swap(_has_bits_[0], other->_has_bits_[0]); _unknown_fields_.Swap(&other->_unknown_fields_); std::swap(_cached_size_, other->_cached_size_); } } ::google::protobuf::Metadata MysqlConf::GetMetadata() const { protobuf_AssignDescriptorsOnce(); ::google::protobuf::Metadata metadata; metadata.descriptor = MysqlConf_descriptor_; metadata.reflection = MysqlConf_reflection_; return metadata; } // =================================================================== #ifndef _MSC_VER const int RedisConf::kHostFieldNumber; const int RedisConf::kPortFieldNumber; #endif // !_MSC_VER RedisConf::RedisConf() : ::google::protobuf::Message() { SharedCtor(); } void RedisConf::InitAsDefaultInstance() { } RedisConf::RedisConf(const RedisConf& from) : ::google::protobuf::Message() { SharedCtor(); MergeFrom(from); } void RedisConf::SharedCtor() { _cached_size_ = 0; host_ = const_cast< ::std::string*>(&::google::protobuf::internal::kEmptyString); port_ = 0; ::memset(_has_bits_, 0, sizeof(_has_bits_)); } RedisConf::~RedisConf() { SharedDtor(); } void RedisConf::SharedDtor() { if (host_ != &::google::protobuf::internal::kEmptyString) { delete host_; } if (this != default_instance_) { } } void RedisConf::SetCachedSize(int size) const { GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); _cached_size_ = size; GOOGLE_SAFE_CONCURRENT_WRITES_END(); } const ::google::protobuf::Descriptor* RedisConf::descriptor() { protobuf_AssignDescriptorsOnce(); return RedisConf_descriptor_; } const RedisConf& RedisConf::default_instance() { if (default_instance_ == NULL) protobuf_AddDesc_server_5fconf_2eproto(); return *default_instance_; } RedisConf* RedisConf::default_instance_ = NULL; RedisConf* RedisConf::New() const { return new RedisConf; } void RedisConf::Clear() { if (_has_bits_[0 / 32] & (0xffu << (0 % 32))) { if (has_host()) { if (host_ != &::google::protobuf::internal::kEmptyString) { host_->clear(); } } port_ = 0; } ::memset(_has_bits_, 0, sizeof(_has_bits_)); mutable_unknown_fields()->Clear(); } bool RedisConf::MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input) { #define DO_(EXPRESSION) if (!(EXPRESSION)) return false ::google::protobuf::uint32 tag; while ((tag = input->ReadTag()) != 0) { switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { // required string host = 1; case 1: { if (::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == ::google::protobuf::internal::WireFormatLite::WIRETYPE_LENGTH_DELIMITED) { DO_(::google::protobuf::internal::WireFormatLite::ReadString( input, this->mutable_host())); ::google::protobuf::internal::WireFormat::VerifyUTF8String( this->host().data(), this->host().length(), ::google::protobuf::internal::WireFormat::PARSE); } else { goto handle_uninterpreted; } if (input->ExpectTag(16)) goto parse_port; break; } // required int32 port = 2; case 2: { if (::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == ::google::protobuf::internal::WireFormatLite::WIRETYPE_VARINT) { parse_port: DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< ::google::protobuf::int32, ::google::protobuf::internal::WireFormatLite::TYPE_INT32>( input, &port_))); set_has_port(); } else { goto handle_uninterpreted; } if (input->ExpectAtEnd()) return true; break; } default: { handle_uninterpreted: if (::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == ::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) { return true; } DO_(::google::protobuf::internal::WireFormat::SkipField( input, tag, mutable_unknown_fields())); break; } } } return true; #undef DO_ } void RedisConf::SerializeWithCachedSizes( ::google::protobuf::io::CodedOutputStream* output) const { // required string host = 1; if (has_host()) { ::google::protobuf::internal::WireFormat::VerifyUTF8String( this->host().data(), this->host().length(), ::google::protobuf::internal::WireFormat::SERIALIZE); ::google::protobuf::internal::WireFormatLite::WriteString( 1, this->host(), output); } // required int32 port = 2; if (has_port()) { ::google::protobuf::internal::WireFormatLite::WriteInt32(2, this->port(), output); } if (!unknown_fields().empty()) { ::google::protobuf::internal::WireFormat::SerializeUnknownFields( unknown_fields(), output); } } ::google::protobuf::uint8* RedisConf::SerializeWithCachedSizesToArray( ::google::protobuf::uint8* target) const { // required string host = 1; if (has_host()) { ::google::protobuf::internal::WireFormat::VerifyUTF8String( this->host().data(), this->host().length(), ::google::protobuf::internal::WireFormat::SERIALIZE); target = ::google::protobuf::internal::WireFormatLite::WriteStringToArray( 1, this->host(), target); } // required int32 port = 2; if (has_port()) { target = ::google::protobuf::internal::WireFormatLite::WriteInt32ToArray(2, this->port(), target); } if (!unknown_fields().empty()) { target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray( unknown_fields(), target); } return target; } int RedisConf::ByteSize() const { int total_size = 0; if (_has_bits_[0 / 32] & (0xffu << (0 % 32))) { // required string host = 1; if (has_host()) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::StringSize( this->host()); } // required int32 port = 2; if (has_port()) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::Int32Size( this->port()); } } if (!unknown_fields().empty()) { total_size += ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize( unknown_fields()); } GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); _cached_size_ = total_size; GOOGLE_SAFE_CONCURRENT_WRITES_END(); return total_size; } void RedisConf::MergeFrom(const ::google::protobuf::Message& from) { GOOGLE_CHECK_NE(&from, this); const RedisConf* source = ::google::protobuf::internal::dynamic_cast_if_available<const RedisConf*>( &from); if (source == NULL) { ::google::protobuf::internal::ReflectionOps::Merge(from, this); } else { MergeFrom(*source); } } void RedisConf::MergeFrom(const RedisConf& from) { GOOGLE_CHECK_NE(&from, this); if (from._has_bits_[0 / 32] & (0xffu << (0 % 32))) { if (from.has_host()) { set_host(from.host()); } if (from.has_port()) { set_port(from.port()); } } mutable_unknown_fields()->MergeFrom(from.unknown_fields()); } void RedisConf::CopyFrom(const ::google::protobuf::Message& from) { if (&from == this) return; Clear(); MergeFrom(from); } void RedisConf::CopyFrom(const RedisConf& from) { if (&from == this) return; Clear(); MergeFrom(from); } bool RedisConf::IsInitialized() const { if ((_has_bits_[0] & 0x00000003) != 0x00000003) return false; return true; } void RedisConf::Swap(RedisConf* other) { if (other != this) { std::swap(host_, other->host_); std::swap(port_, other->port_); std::swap(_has_bits_[0], other->_has_bits_[0]); _unknown_fields_.Swap(&other->_unknown_fields_); std::swap(_cached_size_, other->_cached_size_); } } ::google::protobuf::Metadata RedisConf::GetMetadata() const { protobuf_AssignDescriptorsOnce(); ::google::protobuf::Metadata metadata; metadata.descriptor = RedisConf_descriptor_; metadata.reflection = RedisConf_reflection_; return metadata; } // =================================================================== #ifndef _MSC_VER const int ServerConfig::kSvrPortFieldNumber; const int ServerConfig::kLog4CppConfFieldNumber; const int ServerConfig::kBrpcLogFieldNumber; const int ServerConfig::kDataDbFieldNumber; const int ServerConfig::kDataPointTableFieldNumber; const int ServerConfig::kModDataTableFieldNumber; #endif // !_MSC_VER ServerConfig::ServerConfig() : ::google::protobuf::Message() { SharedCtor(); } void ServerConfig::InitAsDefaultInstance() { data_db_ = const_cast< ::data_server::MysqlConf*>(&::data_server::MysqlConf::default_instance()); } ServerConfig::ServerConfig(const ServerConfig& from) : ::google::protobuf::Message() { SharedCtor(); MergeFrom(from); } void ServerConfig::SharedCtor() { _cached_size_ = 0; svr_port_ = 0; log4cpp_conf_ = const_cast< ::std::string*>(&::google::protobuf::internal::kEmptyString); brpc_log_ = const_cast< ::std::string*>(&::google::protobuf::internal::kEmptyString); data_db_ = NULL; data_point_table_ = const_cast< ::std::string*>(&::google::protobuf::internal::kEmptyString); mod_data_table_ = const_cast< ::std::string*>(&::google::protobuf::internal::kEmptyString); ::memset(_has_bits_, 0, sizeof(_has_bits_)); } ServerConfig::~ServerConfig() { SharedDtor(); } void ServerConfig::SharedDtor() { if (log4cpp_conf_ != &::google::protobuf::internal::kEmptyString) { delete log4cpp_conf_; } if (brpc_log_ != &::google::protobuf::internal::kEmptyString) { delete brpc_log_; } if (data_point_table_ != &::google::protobuf::internal::kEmptyString) { delete data_point_table_; } if (mod_data_table_ != &::google::protobuf::internal::kEmptyString) { delete mod_data_table_; } if (this != default_instance_) { delete data_db_; } } void ServerConfig::SetCachedSize(int size) const { GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); _cached_size_ = size; GOOGLE_SAFE_CONCURRENT_WRITES_END(); } const ::google::protobuf::Descriptor* ServerConfig::descriptor() { protobuf_AssignDescriptorsOnce(); return ServerConfig_descriptor_; } const ServerConfig& ServerConfig::default_instance() { if (default_instance_ == NULL) protobuf_AddDesc_server_5fconf_2eproto(); return *default_instance_; } ServerConfig* ServerConfig::default_instance_ = NULL; ServerConfig* ServerConfig::New() const { return new ServerConfig; } void ServerConfig::Clear() { if (_has_bits_[0 / 32] & (0xffu << (0 % 32))) { svr_port_ = 0; if (has_log4cpp_conf()) { if (log4cpp_conf_ != &::google::protobuf::internal::kEmptyString) { log4cpp_conf_->clear(); } } if (has_brpc_log()) { if (brpc_log_ != &::google::protobuf::internal::kEmptyString) { brpc_log_->clear(); } } if (has_data_db()) { if (data_db_ != NULL) data_db_->::data_server::MysqlConf::Clear(); } if (has_data_point_table()) { if (data_point_table_ != &::google::protobuf::internal::kEmptyString) { data_point_table_->clear(); } } if (has_mod_data_table()) { if (mod_data_table_ != &::google::protobuf::internal::kEmptyString) { mod_data_table_->clear(); } } } ::memset(_has_bits_, 0, sizeof(_has_bits_)); mutable_unknown_fields()->Clear(); } bool ServerConfig::MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input) { #define DO_(EXPRESSION) if (!(EXPRESSION)) return false ::google::protobuf::uint32 tag; while ((tag = input->ReadTag()) != 0) { switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { // required int32 svr_port = 1; case 1: { if (::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == ::google::protobuf::internal::WireFormatLite::WIRETYPE_VARINT) { DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< ::google::protobuf::int32, ::google::protobuf::internal::WireFormatLite::TYPE_INT32>( input, &svr_port_))); set_has_svr_port(); } else { goto handle_uninterpreted; } if (input->ExpectTag(18)) goto parse_log4cpp_conf; break; } // required string log4cpp_conf = 2; case 2: { if (::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == ::google::protobuf::internal::WireFormatLite::WIRETYPE_LENGTH_DELIMITED) { parse_log4cpp_conf: DO_(::google::protobuf::internal::WireFormatLite::ReadString( input, this->mutable_log4cpp_conf())); ::google::protobuf::internal::WireFormat::VerifyUTF8String( this->log4cpp_conf().data(), this->log4cpp_conf().length(), ::google::protobuf::internal::WireFormat::PARSE); } else { goto handle_uninterpreted; } if (input->ExpectTag(26)) goto parse_brpc_log; break; } // required string brpc_log = 3; case 3: { if (::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == ::google::protobuf::internal::WireFormatLite::WIRETYPE_LENGTH_DELIMITED) { parse_brpc_log: DO_(::google::protobuf::internal::WireFormatLite::ReadString( input, this->mutable_brpc_log())); ::google::protobuf::internal::WireFormat::VerifyUTF8String( this->brpc_log().data(), this->brpc_log().length(), ::google::protobuf::internal::WireFormat::PARSE); } else { goto handle_uninterpreted; } if (input->ExpectTag(34)) goto parse_data_db; break; } // required .data_server.MysqlConf data_db = 4; case 4: { if (::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == ::google::protobuf::internal::WireFormatLite::WIRETYPE_LENGTH_DELIMITED) { parse_data_db: DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual( input, mutable_data_db())); } else { goto handle_uninterpreted; } if (input->ExpectTag(42)) goto parse_data_point_table; break; } // required string data_point_table = 5; case 5: { if (::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == ::google::protobuf::internal::WireFormatLite::WIRETYPE_LENGTH_DELIMITED) { parse_data_point_table: DO_(::google::protobuf::internal::WireFormatLite::ReadString( input, this->mutable_data_point_table())); ::google::protobuf::internal::WireFormat::VerifyUTF8String( this->data_point_table().data(), this->data_point_table().length(), ::google::protobuf::internal::WireFormat::PARSE); } else { goto handle_uninterpreted; } if (input->ExpectTag(50)) goto parse_mod_data_table; break; } // required string mod_data_table = 6; case 6: { if (::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == ::google::protobuf::internal::WireFormatLite::WIRETYPE_LENGTH_DELIMITED) { parse_mod_data_table: DO_(::google::protobuf::internal::WireFormatLite::ReadString( input, this->mutable_mod_data_table())); ::google::protobuf::internal::WireFormat::VerifyUTF8String( this->mod_data_table().data(), this->mod_data_table().length(), ::google::protobuf::internal::WireFormat::PARSE); } else { goto handle_uninterpreted; } if (input->ExpectAtEnd()) return true; break; } default: { handle_uninterpreted: if (::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == ::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) { return true; } DO_(::google::protobuf::internal::WireFormat::SkipField( input, tag, mutable_unknown_fields())); break; } } } return true; #undef DO_ } void ServerConfig::SerializeWithCachedSizes( ::google::protobuf::io::CodedOutputStream* output) const { // required int32 svr_port = 1; if (has_svr_port()) { ::google::protobuf::internal::WireFormatLite::WriteInt32(1, this->svr_port(), output); } // required string log4cpp_conf = 2; if (has_log4cpp_conf()) { ::google::protobuf::internal::WireFormat::VerifyUTF8String( this->log4cpp_conf().data(), this->log4cpp_conf().length(), ::google::protobuf::internal::WireFormat::SERIALIZE); ::google::protobuf::internal::WireFormatLite::WriteString( 2, this->log4cpp_conf(), output); } // required string brpc_log = 3; if (has_brpc_log()) { ::google::protobuf::internal::WireFormat::VerifyUTF8String( this->brpc_log().data(), this->brpc_log().length(), ::google::protobuf::internal::WireFormat::SERIALIZE); ::google::protobuf::internal::WireFormatLite::WriteString( 3, this->brpc_log(), output); } // required .data_server.MysqlConf data_db = 4; if (has_data_db()) { ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( 4, this->data_db(), output); } // required string data_point_table = 5; if (has_data_point_table()) { ::google::protobuf::internal::WireFormat::VerifyUTF8String( this->data_point_table().data(), this->data_point_table().length(), ::google::protobuf::internal::WireFormat::SERIALIZE); ::google::protobuf::internal::WireFormatLite::WriteString( 5, this->data_point_table(), output); } // required string mod_data_table = 6; if (has_mod_data_table()) { ::google::protobuf::internal::WireFormat::VerifyUTF8String( this->mod_data_table().data(), this->mod_data_table().length(), ::google::protobuf::internal::WireFormat::SERIALIZE); ::google::protobuf::internal::WireFormatLite::WriteString( 6, this->mod_data_table(), output); } if (!unknown_fields().empty()) { ::google::protobuf::internal::WireFormat::SerializeUnknownFields( unknown_fields(), output); } } ::google::protobuf::uint8* ServerConfig::SerializeWithCachedSizesToArray( ::google::protobuf::uint8* target) const { // required int32 svr_port = 1; if (has_svr_port()) { target = ::google::protobuf::internal::WireFormatLite::WriteInt32ToArray(1, this->svr_port(), target); } // required string log4cpp_conf = 2; if (has_log4cpp_conf()) { ::google::protobuf::internal::WireFormat::VerifyUTF8String( this->log4cpp_conf().data(), this->log4cpp_conf().length(), ::google::protobuf::internal::WireFormat::SERIALIZE); target = ::google::protobuf::internal::WireFormatLite::WriteStringToArray( 2, this->log4cpp_conf(), target); } // required string brpc_log = 3; if (has_brpc_log()) { ::google::protobuf::internal::WireFormat::VerifyUTF8String( this->brpc_log().data(), this->brpc_log().length(), ::google::protobuf::internal::WireFormat::SERIALIZE); target = ::google::protobuf::internal::WireFormatLite::WriteStringToArray( 3, this->brpc_log(), target); } // required .data_server.MysqlConf data_db = 4; if (has_data_db()) { target = ::google::protobuf::internal::WireFormatLite:: WriteMessageNoVirtualToArray( 4, this->data_db(), target); } // required string data_point_table = 5; if (has_data_point_table()) { ::google::protobuf::internal::WireFormat::VerifyUTF8String( this->data_point_table().data(), this->data_point_table().length(), ::google::protobuf::internal::WireFormat::SERIALIZE); target = ::google::protobuf::internal::WireFormatLite::WriteStringToArray( 5, this->data_point_table(), target); } // required string mod_data_table = 6; if (has_mod_data_table()) { ::google::protobuf::internal::WireFormat::VerifyUTF8String( this->mod_data_table().data(), this->mod_data_table().length(), ::google::protobuf::internal::WireFormat::SERIALIZE); target = ::google::protobuf::internal::WireFormatLite::WriteStringToArray( 6, this->mod_data_table(), target); } if (!unknown_fields().empty()) { target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray( unknown_fields(), target); } return target; } int ServerConfig::ByteSize() const { int total_size = 0; if (_has_bits_[0 / 32] & (0xffu << (0 % 32))) { // required int32 svr_port = 1; if (has_svr_port()) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::Int32Size( this->svr_port()); } // required string log4cpp_conf = 2; if (has_log4cpp_conf()) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::StringSize( this->log4cpp_conf()); } // required string brpc_log = 3; if (has_brpc_log()) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::StringSize( this->brpc_log()); } // required .data_server.MysqlConf data_db = 4; if (has_data_db()) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual( this->data_db()); } // required string data_point_table = 5; if (has_data_point_table()) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::StringSize( this->data_point_table()); } // required string mod_data_table = 6; if (has_mod_data_table()) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::StringSize( this->mod_data_table()); } } if (!unknown_fields().empty()) { total_size += ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize( unknown_fields()); } GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); _cached_size_ = total_size; GOOGLE_SAFE_CONCURRENT_WRITES_END(); return total_size; } void ServerConfig::MergeFrom(const ::google::protobuf::Message& from) { GOOGLE_CHECK_NE(&from, this); const ServerConfig* source = ::google::protobuf::internal::dynamic_cast_if_available<const ServerConfig*>( &from); if (source == NULL) { ::google::protobuf::internal::ReflectionOps::Merge(from, this); } else { MergeFrom(*source); } } void ServerConfig::MergeFrom(const ServerConfig& from) { GOOGLE_CHECK_NE(&from, this); if (from._has_bits_[0 / 32] & (0xffu << (0 % 32))) { if (from.has_svr_port()) { set_svr_port(from.svr_port()); } if (from.has_log4cpp_conf()) { set_log4cpp_conf(from.log4cpp_conf()); } if (from.has_brpc_log()) { set_brpc_log(from.brpc_log()); } if (from.has_data_db()) { mutable_data_db()->::data_server::MysqlConf::MergeFrom(from.data_db()); } if (from.has_data_point_table()) { set_data_point_table(from.data_point_table()); } if (from.has_mod_data_table()) { set_mod_data_table(from.mod_data_table()); } } mutable_unknown_fields()->MergeFrom(from.unknown_fields()); } void ServerConfig::CopyFrom(const ::google::protobuf::Message& from) { if (&from == this) return; Clear(); MergeFrom(from); } void ServerConfig::CopyFrom(const ServerConfig& from) { if (&from == this) return; Clear(); MergeFrom(from); } bool ServerConfig::IsInitialized() const { if ((_has_bits_[0] & 0x0000003f) != 0x0000003f) return false; if (has_data_db()) { if (!this->data_db().IsInitialized()) return false; } return true; } void ServerConfig::Swap(ServerConfig* other) { if (other != this) { std::swap(svr_port_, other->svr_port_); std::swap(log4cpp_conf_, other->log4cpp_conf_); std::swap(brpc_log_, other->brpc_log_); std::swap(data_db_, other->data_db_); std::swap(data_point_table_, other->data_point_table_); std::swap(mod_data_table_, other->mod_data_table_); std::swap(_has_bits_[0], other->_has_bits_[0]); _unknown_fields_.Swap(&other->_unknown_fields_); std::swap(_cached_size_, other->_cached_size_); } } ::google::protobuf::Metadata ServerConfig::GetMetadata() const { protobuf_AssignDescriptorsOnce(); ::google::protobuf::Metadata metadata; metadata.descriptor = ServerConfig_descriptor_; metadata.reflection = ServerConfig_reflection_; return metadata; } // @@protoc_insertion_point(namespace_scope) } // namespace data_server // @@protoc_insertion_point(global_scope)
983d7e066fec6843c49da62090a0bde563b26b58
610ec95887f70da95e1ab5eb9475f0977d3c4a8a
/SuperMarioBros/src/Level/Tiles/BigBushT.h
93f66396a3a2c9b123edba3b84df079be21690eb
[]
no_license
Hypooxanthine/SuperMarioBros
0632f912ee7338d4ec685a01c3571df4e68bb69c
60d560ae0b57f86acd866300940f8a0de86975c2
refs/heads/main
2023-07-23T14:02:24.194266
2021-08-30T19:56:49
2021-08-30T19:56:49
395,396,712
0
0
null
null
null
null
UTF-8
C++
false
false
93
h
BigBushT.h
#pragma once #include "Tile.h" class BigBushT : public Tile { TILE_INIT_DEF(BigBushT) };
7c80df0fc3b970d24462ff339921aaf2a07bedeb
44ab57520bb1a9b48045cb1ee9baee8816b44a5b
/EngineTesting/Code/CoreTools/CoreToolsTesting/DataTypesSuite/MinHeapRecordTesting.cpp
dc8e9b88bec879f7e2b61076698cbe9336bb2ac5
[ "BSD-3-Clause" ]
permissive
WuyangPeng/Engine
d5d81fd4ec18795679ce99552ab9809f3b205409
738fde5660449e87ccd4f4878f7bf2a443ae9f1f
refs/heads/master
2023-08-17T17:01:41.765963
2023-08-16T07:27:05
2023-08-16T07:27:05
246,266,843
10
0
null
null
null
null
GB18030
C++
false
false
1,928
cpp
MinHeapRecordTesting.cpp
/// Copyright (c) 2010-2023 /// Threading Core Render Engine /// /// 作者:彭武阳,彭晔恩,彭晔泽 /// 联系作者:94458936@qq.com /// /// 标准:std:c++20 /// 引擎测试版本:0.9.0.6 (2023/04/11 18:05) #include "MinHeapRecordTesting.h" #include "CoreTools/DataTypes/MinHeapRecordDetail.h" #include "CoreTools/Helper/AssertMacro.h" #include "CoreTools/Helper/ClassInvariant/CoreToolsClassInvariantMacro.h" #include "CoreTools/UnitTestSuite/UnitTestDetail.h" CoreTools::MinHeapRecordTesting::MinHeapRecordTesting(const OStreamShared& stream) : ParentType{ stream } { CORE_TOOLS_SELF_CLASS_IS_VALID_1; } CLASS_INVARIANT_PARENT_IS_VALID_DEFINE(CoreTools, MinHeapRecordTesting) void CoreTools::MinHeapRecordTesting::DoRunUnitTest() { ASSERT_NOT_THROW_EXCEPTION_0(MainTest); } void CoreTools::MinHeapRecordTesting::MainTest() { ASSERT_NOT_THROW_EXCEPTION_0(FloatTest); ASSERT_NOT_THROW_EXCEPTION_0(IntegerTest); ASSERT_NOT_THROW_EXCEPTION_0(DoubleTest); } void CoreTools::MinHeapRecordTesting::FloatTest() { MinHeapRecord<int, float> minHeapRecord{}; minHeapRecord.SetGenerator(5); minHeapRecord.SetValue(1.0f); minHeapRecord.SetUniqueIndex(0); ASSERT_EQUAL(minHeapRecord.GetGenerator(), 5); ASSERT_APPROXIMATE(minHeapRecord.GetValue(), 1.0f, 1.0e-8f); ASSERT_EQUAL(minHeapRecord.GetUniqueIndex(), 0); } void CoreTools::MinHeapRecordTesting::IntegerTest() { const MinHeapRecord<double, int> minHeapRecord{ 1, 5 }; ASSERT_EQUAL(minHeapRecord.GetValue(), 5); ASSERT_EQUAL(minHeapRecord.GetUniqueIndex(), 1); ASSERT_EQUAL(minHeapRecord.GetGenerator(), 0); } void CoreTools::MinHeapRecordTesting::DoubleTest() { const MinHeapRecord minHeapRecord{ 1, 2, 5.0 }; ASSERT_APPROXIMATE(minHeapRecord.GetValue(), 5.0, 1.0e-10); ASSERT_EQUAL(minHeapRecord.GetUniqueIndex(), 1); ASSERT_EQUAL(minHeapRecord.GetGenerator(), 2); }
7e8fb5e08f37656ef0585af3776ac525f4a48a2a
8547aaa8ce45122e12ecf8862e52b331f6d54dcd
/cpp_programming/exam_question/parkinglot.h
cd9d3cd0cf50b5622ee4e03c7256a25a7a7b8d65
[]
no_license
sjyn/LahTech
fad9f3356afa18678900a742c749a829a21dac9f
adb5130e210c76e9371d34c2a4cb2a255b429d39
refs/heads/master
2021-01-15T15:43:50.843145
2016-12-07T14:55:09
2016-12-07T14:55:09
43,650,418
0
0
null
null
null
null
UTF-8
C++
false
false
359
h
parkinglot.h
#ifndef PL_H #define PL_H #include <vector> #include <mutex> #include "car.h" #include "truck.h" #include "vehicle.h" class ParkingLot { private: std::vector<Vehicle*> autos; std::vector<Vehicle*>::iterator it; std::mutex myTex; public: ParkingLot(); ~ParkingLot(); void addVehicle(Vehicle* a); void listVehicles(); }; #endif
df061f55efb22360a4fc098778f84017533608d3
cb0af0a65ae5ddc300d1b49e7dc6287faad02315
/*101**.cpp
e88ad9067a6394b77505cdd62ebecbe9c7e2a943
[]
no_license
Cloverii/LeetCode
04d45a395727f51f986d14deac9dde26675fc606
78230b56bbe60cdcce6ff483b87ad3e1f962d64e
refs/heads/master
2021-01-18T15:22:46.775775
2017-06-21T13:59:52
2017-06-21T13:59:52
84,344,778
1
0
null
null
null
null
UTF-8
C++
false
false
1,132
cpp
*101**.cpp
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { private: bool cmp(TreeNode *lft, TreeNode *rht) { if(lft && rht) { if(lft->val != rht->val) return false; return cmp(lft->left, rht->right) && cmp(lft->right, rht->left); } return !(lft || rht); } public: bool isSymmetric(TreeNode* root) { if(root == NULL) return true; /* return cmp(root->left, root->right); */ queue<TreeNode *> q; q.push(root->left); q.push(root->right); while(q.size()) { TreeNode *lft = q.front(); q.pop(); TreeNode *rht = q.front(); q.pop(); if(lft && rht) { if(lft->val != rht->val) return false; q.push(lft->left); q.push(rht->right); q.push(lft->right); q.push(rht->left); } else if(lft || rht) return false; } return true; } };
699200bdf8e5fb4cf8e880a7d39c126fbfd1833a
c28b306dbb5a0a08e6341c709c56b50006cc144c
/Evento.cpp
ee6092c412024ee9c51acdde42ea6fd7c1963365
[]
no_license
faidertms/Ridin
5421d6200fedfd9a63d6a0a97127ed1399aa09a9
0ddd6325b273a0e1679c4a2bb4407328ef022eab
refs/heads/master
2020-06-13T06:09:56.061911
2019-06-30T22:20:53
2019-06-30T22:20:53
194,565,982
0
0
null
null
null
null
ISO-8859-1
C++
false
false
1,536
cpp
Evento.cpp
//Detecção de Evento #include "estados.h" void estados::OnEvent(){ while (SDL_PollEvent(&event)) { if (tempoclass.calculartempo() >= 0){ // Verifica se o tempo de largada é maior ou igual a 0 para que possa movimentar o carro, por padrão começa como -3 o tempo switch (event.type) { case SDL_QUIT: //Caso o usuário peça para fechar o jogo running = false; break; case SDL_KEYUP: // tecla está solta; switch (event.key.keysym.sym) { case SDLK_w:MoveUp = false; aceleracao = 1; break; // caso ocorra, as variaveis booleanas vao para false, onde não ocorre nenhuma reação case SDLK_s: MoveDown = false; break; case SDLK_a: MoveLeft = false; break; case SDLK_d: MoveRight = false; break; case SDLK_UP:MoveUp2 = false; acel = 1; break; case SDLK_DOWN: MoveDown2 = false; break; case SDLK_LEFT: MoveLeft2 = false; break; case SDLK_RIGHT: MoveRight2 = false; break; } break; case SDL_KEYDOWN: // tecla está sendo pressionada switch (event.key.keysym.sym) { case SDLK_w: MoveUp = true; break; // caso ocorra, as variaveis vai assumir o valor true e consequentemente ativar os metodos movimento no loop.cpp case SDLK_s: MoveDown = true; break; case SDLK_a: MoveLeft = true; break; case SDLK_d: MoveRight = true; break; case SDLK_UP: MoveUp2 = true; break; case SDLK_DOWN: MoveDown2 = true; break; case SDLK_LEFT: MoveLeft2 = true; break; case SDLK_RIGHT: MoveRight2 = true; break; } break; } } } }
7096e65e35a31cdd00a480aa4dfd3f0369e6b4f0
3962899b0350c4ccdec015a555603f5a705bc698
/include/amino/ebstack.h
e9c1b560435ff11744a53ee10765fcecc2237740
[ "Apache-2.0" ]
permissive
bapi/amino
8fc7c82d68e5b3a960e84301d238cf7507e33adc
fb3453097793fdbf0b5b5f7c272b4c3625968d7e
refs/heads/master
2020-12-30T17:44:39.548491
2010-04-15T22:00:11
2010-04-15T22:00:11
11,505,149
1
0
null
null
null
null
UTF-8
C++
false
false
16,143
h
ebstack.h
/* * (c) Copyright 2008, IBM Corporation. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef EBSTACK_H_ #define EBSTACK_H_ #include "smr.h" #include "debug.h" namespace amino { /** * @brief The node type, which stores the data and a next pointer in it. * * @tparam T * Type of element stored in it */ template<typename T> class StackNode { public: T data; StackNode* next; StackNode() : next(NULL) { } StackNode(const T& val) : data(val), next(NULL) { } }; /** * <pre> * A Scalable Lock-free Stack Algorithm * Danny Hendler Nir Shavit Lena Yerushalmi * School of Computer Science Tel-Aviv University & School of Computer Science * Tel-Aviv University Sun Microsystems Tel-Aviv University * Tel Aviv, Israel 69978 Laboratories Tel Aviv, Israel 69978 * hendlerd@post.tau.ac.il shanir@sun.com lenay@post.tau.ac.il * </pre> * @brief This a implementation of ebstack... * @tparam T * Type of element stored in it */ template<typename T> class EBStack { private: atomic<StackNode<T>*> top; /*top pointer of stack*/ SMR<StackNode<T> , 1>* mm; /*SMR for memory management*/ /*collision array*/ static const int TRY_TIMES = 4; /*times of try on collision array*/ static StackNode<T> TOMB_STONE; static StackNode<T> REMOVED; const int coll_size; /*size of collision array*/ atomic<StackNode<T>*>* coll_pop; /*collision array for pop*/ atomic<StackNode<T>*>* coll_push; /*collision array for push*/ atomic<int> position; /*position for try on collision array*/ /*try to add element on collision array for pop*/ bool try_add(StackNode<T>*); /*try to remove element on collision array for push*/ StackNode<T>* try_remove(); int get_rand_position(); void initCollisionArray(int); void destoryCollisionArray(); const int stime; #ifdef DEBUG_STACK //record collision times.. yuezbj typedef struct _collTimes { _collTimes():pushCNum(0), pushCFNum(0),pushDNum(0), popCNum(0), popCFNum(0),popDNum(0) { } volatile int pushCNum ; volatile int pushCFNum; volatile int pushDNum ; volatile int popCNum ; volatile int popCFNum ; volatile int popDNum ; }CollTimes; /**This atomic CollTimes will record the collision times for all threads in one test case. */ atomic<CollTimes*> pAllThreadCT; ThreadLocal<CollTimes*> *pLocalCTimes; FILE* fpushLog, *fpopLog; #endif #ifdef DEBUG_CYCLE typedef struct _opCycles { _opCycles():pushC(0),popC(0),peekTopC(0) { } volatile unsigned long pushC; volatile unsigned long popC; volatile unsigned long peekTopC ; }OpCycles; atomic<OpCycles*> pAllThreadCycles; ThreadLocal<OpCycles*> *pLocalCycles; #endif public: #ifdef DEBUG_STACK /**This function will be called in the test case before the thread exit. * So the test case only suitable for EBStack. */ void freeCT() { CollTimes* ct = pLocalCTimes->get(); if (NULL != ct) { CollTimes* ptmp; CollTimes* pnew = new CollTimes(); while (!pAllThreadCT.compare_swap(ptmp, pnew)) { ptmp = pAllThreadCT.load(memory_order_relaxed); pnew->pushCNum = (ct->pushCNum + ptmp->pushCNum); pnew->pushCFNum = (ct->pushCFNum + ptmp->pushCFNum); pnew->pushDNum = (ct->pushDNum + ptmp->pushDNum); pnew->popCNum = (ct->popCNum + ptmp->popCNum); pnew->popCFNum = (ct->popCFNum + ptmp->popCFNum); pnew->popDNum = (ct->popDNum + ptmp->popDNum); } //delete ptmp; delete ct; } } void logPush(char* log) { fwrite(log, sizeof(char), strlen(log), fpushLog); } void logPop(char* log) { fwrite(log, sizeof(char), strlen(log), fpopLog); } #endif #ifdef DEBUG_CYCLE void freeOC() { OpCycles* oc = pLocalCycles->get(); if (NULL != oc) { OpCycles* ptmp; OpCycles* pnew = new OpCycles(); while (!pAllThreadCycles.compare_swap(ptmp, pnew)) { ptmp = pAllThreadCycles.load(memory_order_relaxed); pnew->pushC = (oc->pushC + ptmp->pushC); pnew->popC = (oc->popC + ptmp->popC); pnew->peekTopC = (oc->peekTopC + ptmp->peekTopC); } //delete ptmp; delete oc; } } #endif /** * @brief Constructor with size of collision array. * * @param num size of collision array */ EBStack(int num = 8) : coll_size(num), position(), stime(300) { top.store(NULL, memory_order_relaxed); mm = getSMR<StackNode<T> , 1> (); #ifdef DEBUG_STACK fpushLog = fopen("ebstack_push.log", "a+"); fpopLog = fopen("ebstack_pop.log", "a+"); CollTimes* ptmp = new CollTimes(); pAllThreadCT.store(ptmp, memory_order_relaxed); pLocalCTimes = new ThreadLocal<CollTimes*>(NULL); #endif #ifdef DEBUG_CYCLE OpCycles* ptmp = new OpCycles(); pAllThreadCycles.store(ptmp, memory_order_relaxed); pLocalCycles = new ThreadLocal<OpCycles*>(NULL); #endif initCollisionArray(num); } /** * @brief Destructor. */ ~EBStack() { #ifdef DEBUG_STACK fclose(fpushLog); fclose(fpopLog); CollTimes* ptmp = pAllThreadCT.load(memory_order_relaxed); cout<<"pushC:"<<ptmp->pushCNum<<" pushCF:"<<ptmp->pushCFNum<<" pushD:"<<ptmp->pushDNum<<endl; cout<<"popC:"<<ptmp->popCNum<<" popCF:"<<ptmp->popCFNum<<" popD:"<<ptmp->popDNum<<endl; delete ptmp; delete pLocalCTimes; #endif #ifdef DEBUG_CYCLE OpCycles* ptmp = pAllThreadCycles.load(memory_order_relaxed); cout<<"pushCycles:"<<ptmp->pushC<<" popCycles:"<<ptmp->popC<<" peekTopCycles:"<<ptmp->peekTopC<<endl; delete ptmp; delete pLocalCycles; #endif StackNode<T> *first = top.load(memory_order_relaxed); while (first != NULL) { StackNode<T> *next = first->next; delete first; first = next; } destoryCollisionArray(); } void push(const T& d); bool pop(T& ret); bool empty(); int size(); bool peekTop(T& ret); }; template<typename T> StackNode<T> EBStack<T>::TOMB_STONE; template<typename T> StackNode<T> EBStack<T>::REMOVED; /** * @brief Initialize the push and pop's collision array * * @param num * The size of the array */ template<typename T> void EBStack<T>::initCollisionArray(int num) { coll_push = new atomic<StackNode<T>*> [num]; assert(NULL != coll_push); coll_pop = new atomic<StackNode<T>*> [num]; assert(NULL != coll_pop); for (int i = 0; i < num; ++i) { coll_push[i].store(NULL); coll_pop[i].store(NULL); } } /** * @brief Delete the push and pop's collision array */ template<typename T> void EBStack<T>::destoryCollisionArray() { /*all elements in coll_push and coll_pop is unavailable now. * no need to delete node put into coll_push and coll_pop first. */ delete[] coll_push; delete[] coll_pop; } /** * @brief Get a random position * @return A random position */ template<typename T> int EBStack<T>::get_rand_position() { return position++ % coll_size; } /** * @brief Push data onto Stack. * * @param d * data to be pushed into the stack. */ template<typename T> void EBStack<T>::push(const T& d) { #ifdef DEBUG_CYCLE OpCycles* oc = pLocalCycles->get(); if ( NULL == oc) { oc = new OpCycles(); pLocalCycles->set(oc); } unsigned long begin = cycleStamp(); #endif StackNode<T>* newTop, *oldTop; #ifdef FREELIST newTop = mm->newNode(); newTop->data = d; #else newTop = new StackNode<T> (d); #endif #ifdef DEBUG_STACK CollTimes* ct = pLocalCTimes->get(); if ( NULL == ct) { ct = new CollTimes(); pLocalCTimes->set(ct); } #endif while (true) { /*no need to use a barrier*/ oldTop = top.load(memory_order_relaxed); newTop->next = oldTop; if (top.compare_swap(oldTop, newTop)) { #ifdef DEBUG_STACK ct->pushDNum++; #endif break; } /*collision*/ if (try_add(newTop)) { #ifdef DEBUG_STACK ct->pushCNum++; #endif break; } #ifdef DEBUG_STACK else { ct->pushCFNum++; } #endif } #ifdef DEBUG_CYCLE unsigned long end = cycleStamp(); oc->pushC += (end-begin); #endif } /** * @brief try_add... */ template<typename T> bool EBStack<T>::try_add(StackNode<T>* node) { int pos = get_rand_position(); for (int i = 0; i < TRY_TIMES; ++i) { int index = (pos + i) % coll_size; StackNode<T>* pop_op = coll_pop[index].load(memory_order_relaxed); /*if some thread is waiting for removal, let's feed it with * added object and return success. */ if (pop_op == &TOMB_STONE) { if (coll_pop[index].compare_swap(pop_op, node)) { #ifdef DEBUG_STACK //char log[50]; //sprintf(log, "%d:pushCNode_tomb: %x\n", (int)pthread_self(), node); //logPush(log); #endif return true; } } } /* * let's try to put adding objects to the buffer and * waiting for removal threads. */ for (int i = 0; i < TRY_TIMES; ++i) { int index = (pos + i) % coll_size; StackNode<T>* push_op = coll_push[index].load(memory_order_relaxed); if (push_op == NULL) { /*this posiotion is empty*/ if (coll_push[index].compare_swap(push_op, node)) { /* Now we check to see if added object is touched by removing threads.*/ usleep(stime); while (true) { push_op = coll_push[index].load(memory_order_relaxed); if (push_op == node) { if (coll_push[index].compare_swap(node, NULL)) { /*no removing thread touched us, return false*/ return false; } else { coll_push[index] = NULL; #ifdef DEBUG_STACK //char log[50]; //sprintf(log, "%d:pushCNode_node1: %x\n",(int)pthread_self(),node); //logPush(log); #endif return true; } } else { /*current value should be REMOVED. change REMOVED to be * null means this position is available again. */ coll_push[index] = NULL; #ifdef DEBUG_STACK //char log[50]; //sprintf(log, "%d:pushCNode_node2: %x\n",(int)pthread_self(),node); //logPush(log); #endif return true; } } } } } usleep(stime); return false; } /** * @brief Pop data from the Stack. * @param ret * topmost element of the stack. It is valid if the return value is true. * * @return If the value exists in the list, remove it and return true. else return false. */ template<typename T> bool EBStack<T>::pop(T& ret) { #ifdef DEBUG_CYCLE OpCycles* oc = pLocalCycles->get(); if ( NULL == oc) { oc = new OpCycles(); pLocalCycles->set(oc); } unsigned long begin = cycleStamp(); #endif StackNode<T> *oldTop, *newTop = NULL; typename SMR<StackNode<T>, 1>::HP_Rec * hp = mm->getHPRec(); #ifdef DEBUG_STACK CollTimes* ct = pLocalCTimes->get(); if ( NULL == ct) { ct = new CollTimes(); pLocalCTimes->set(ct); } #endif while (true) { oldTop = top.load(memory_order_relaxed); if (oldTop == NULL) { return false; } mm->employ(hp, 0, oldTop); //for memory management, hp0 = oldTop //memory barrier necessary here if (top.load(memory_order_relaxed) != oldTop) { continue; } newTop = oldTop->next; if (top.compare_swap(oldTop, newTop)) { #ifdef DEBUG_STACK ct->popDNum++; #endif break; //successful } // elimination backoff StackNode<T>* col_ele = try_remove(); if (NULL != col_ele) { ret = col_ele->data; #ifdef DEBUG_STACK ct->popCNum++; #endif return true; } #ifdef DEBUG_STACK else { ct->popCFNum++; } #endif } mm->retire(hp,0);//hp0 = NULL. optional. for memory management ret = oldTop->data; mm->delNode(oldTop); //for memory management #ifdef DEBUG_CYCLE unsigned long end = cycleStamp(); oc->popC += (end-begin); #endif return true; } /** * @brief try_remove... */ template<typename T> StackNode<T>* EBStack<T>::try_remove() { int pos = get_rand_position(); for (int i = 0; i < TRY_TIMES; ++i) { int index = (pos + i) % coll_size; StackNode<T>* push_op = coll_push[index].load(memory_order_relaxed); // collide with pop if ((push_op != NULL) && (push_op != &REMOVED)) { if (coll_push[index].compare_swap(push_op, &REMOVED)) { #ifdef DEBUG_STACK //char log[50]; //sprintf(log, "%d:popCNode_node: %x\n", (int)pthread_self(),push_op); //logPop(log); #endif return push_op; } } } for (int i = 0; i < TRY_TIMES; ++i) { int index = (pos + i) % coll_size; StackNode<T>* pop_op = coll_pop[index].load(memory_order_relaxed); if (pop_op == NULL) { if (coll_pop[index].compare_swap(pop_op, &TOMB_STONE)) { usleep(stime); while (true) { pop_op = coll_pop[index].load(memory_order_relaxed); if (pop_op != &TOMB_STONE) { coll_pop[index].store(NULL, memory_order_relaxed); #ifdef DEBUG_STACK //char log[50]; //sprintf(log, "%d:popCNode_tomb: %x\n", (int)pthread_self(),pop_op); //logPop(log); #endif return pop_op; } else { if (coll_pop[index].compare_swap(pop_op, NULL)) { return NULL; } } } } } } usleep(stime); return NULL; } /** * @brief Check to see if Stack is empty. * * @return true if stack is empty. */ template<typename T> bool EBStack<T>::empty() /*const*/{ return top.load(memory_order_relaxed) == NULL; } /** * @brief Get the size of stack * * @return * The size of stack */ template<typename T> int EBStack<T>::size() { int ret = 0; StackNode<T> *node = top.load(memory_order_relaxed); while (node != NULL) { ++ret; node = node->next; } return ret; } /** * @brief Get the topmost element in the stack. If the stack is empty, it will return false. * else return true and assign the topmost element to the parameter. * * @param ret * The topmost element in the stack. It is valid if the return value is true. * @return * If the stack is empty return false, else return true. */ template<typename T> bool EBStack<T>::peekTop(T& ret) { #ifdef DEBUG_CYCLE OpCycles* oc = pLocalCycles->get(); if ( NULL == oc) { oc = new OpCycles(); pLocalCycles->set(oc); } unsigned long begin = cycleStamp(); #endif StackNode<T>* oldtop; typename SMR<StackNode<T>, 1>::HP_Rec * hp = mm->getHPRec(); while (true) { oldtop = top.load(memory_order_relaxed); if (oldtop == NULL) return false; mm->employ(hp, 0, oldtop); if (top.load(memory_order_relaxed) != oldtop) continue; ret = oldtop->data; mm->retire(hp, 0); #ifdef DEBUG_CYCLE unsigned long end = cycleStamp(); oc->peekTopC += (end-begin); #endif return true; } } } #endif /*EBSTACK_H_*/
16ab6faf56d40f8b56ebd75089b560c4f3537270
e0bfa24bacce73eeb68673f26bd152b7963ef855
/workspace1/ABC198/C.cpp
0108053749f7bff2854d3f567e77056aa6a127e3
[]
no_license
kenji132/Competitive-Programming
52b1147d5e846000355cd7ee4805fad639e186d5
89c0336139dae002a3187fa372fda7652fd466cb
refs/heads/master
2023-04-25T08:29:04.657607
2021-05-12T09:35:20
2021-05-12T09:35:20
314,996,525
0
0
null
null
null
null
UTF-8
C++
false
false
323
cpp
C.cpp
#include <bits/stdc++.h> using namespace std; using ll = long long; int main(){ ll r,x,y; cin >> r >> x >> y; ll d2 = x*x+y*y; bool ok = true; ll ans = 1; while(ok){ if(r*r*ans*ans >= d2) break; ans++; } if(ans == 1){ if(r*r != d2){ ans = 2; } } cout << ans << endl; return 0; }
8670a321745ee2cd4202e423c6b118434c6a2c74
0ca40d4428b218d4fe74c0e9cb23aba9d2d0e278
/426.convert-binary-search-tree-to-sorted-doubly-linked-list.249629289.ac.cpp
0f6c092f5d9b5b615a402cfbcd52490e0ac5a253
[]
no_license
rjoudrey/leetcode-solutions
4c4b84cc331816c9d438e4b8e6fc9a85ab15b3eb
368e20e194383187d3786f827cfcb066329dddc3
refs/heads/master
2020-09-11T19:41:13.355768
2019-11-17T03:28:47
2019-11-17T03:28:47
222,170,630
1
0
null
null
null
null
UTF-8
C++
false
false
1,328
cpp
426.convert-binary-search-tree-to-sorted-doubly-linked-list.249629289.ac.cpp
/* // Definition for a Node. class Node { public: int val; Node* left; Node* right; Node() {} Node(int _val, Node* _left, Node* _right) { val = _val; left = _left; right = _right; } }; */ struct ProcessState { Node *first; Node *last; }; class Solution { public: void process(Node *node, ProcessState &state) { // prev <-> node // Careful: Don't modify the right subtree since we are doing inorder. node->left = nullptr; Node *prev = state.last; if (prev != nullptr) { prev->right = node; node->left = prev; } else { state.first = node; } state.last = node; } void inorder(Node *node, ProcessState &state) { if (node == nullptr) { return; } // L N R inorder(node->left, state); process(node, state); inorder(node->right, state); } Node* treeToDoublyList(Node* root) { ProcessState state; state.last = nullptr; state.first = nullptr; inorder(root, state); if (state.first != nullptr) { state.first->left = state.last; state.last->right = state.first; } return state.first; } };
3395cd344866c9e97ca43154beb973d72dea1032
56f58ef41d9c245da5fe871d8bc23d74b0a42290
/leetcode/algorithms/474 - Ones and Zeroes.cpp
2d2578a6a7bcc344d815a9606cb852c9df0850c0
[]
no_license
zotvent/competitive-programming
353dd906e87bc20090c6cbb75b1f68f8653ca489
32e9efc6b45e28b5c8d47d875de58305087ae5f1
refs/heads/master
2023-05-26T05:36:14.802939
2023-05-25T22:21:33
2023-05-25T22:21:33
93,071,555
29
2
null
null
null
null
UTF-8
C++
false
false
828
cpp
474 - Ones and Zeroes.cpp
class Solution { vector<int> countZerosOnes(string& s) { vector<int> res(2, 0); for (int i = 0; i < s.size(); i++) { res[s[i] - '0']++; } return res; } public: int findMaxForm(vector<string>& strs, int m, int n) { int res = 0; vector<vector<int>> dp(m + 1, vector<int>(n + 1, 0)); vector<int> count; for (auto& s: strs) { count = countZerosOnes(s); for (int zeros = m; zeros >= count[0]; zeros--) { for (int ones = n; ones >= count[1]; ones--) { dp[zeros][ones] = max(dp[zeros][ones], dp[zeros - count[0]][ones - count[1]] + 1); res = max(res, dp[zeros][ones]); } } } return res; } };
f5d0eb8a25df63d57fad832a8bc643105e21d79b
4235ada3707f5ef565eee5518a4a562bba67094f
/src/tadiga_IGES_geometry.cc
4f1cbf0688217ceba2daf8479b0c833fff7e29b6
[ "Apache-2.0" ]
permissive
johntfoster/TaDIgA
9d8fcc4c78d366d52909143d17ca9b03e4326c41
38b97b9e5018cd8d44624cf6b01d06b54fed488e
refs/heads/master
2020-06-12T20:46:08.455776
2017-06-01T15:49:37
2017-06-01T15:49:37
75,751,963
0
2
null
2017-05-26T02:29:44
2016-12-06T16:52:36
C++
UTF-8
C++
false
false
2,086
cc
tadiga_IGES_geometry.cc
// Copyright 2016-2017 John T. Foster, Katy L. Hanson // 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 "BRepAdaptor_Curve.hxx" #include "BRepAdaptor_Surface.hxx" #include "BRepBuilderAPI_NurbsConvert.hxx" #include "BRep_Tool.hxx" #include "BSplCLib.hxx" #include "Geom_BSplineCurve.hxx" #include "Geom_BSplineSurface.hxx" #include "IGESControl_Reader.hxx" #include "ShapeAnalysis_Edge.hxx" #include "TColStd_Array1OfReal.hxx" #include "TColStd_HSequenceOfTransient.hxx" #include "Teuchos_RCP.hpp" #include "TopExp_Explorer.hxx" #include "TopoDS.hxx" #include "tadiga_IGES_geometry.h" #include "tadiga_geometry.h" tadiga::IgesGeometry::IgesGeometry( const Teuchos::RCP<const Teuchos::Comm<int> >& kComm, const Teuchos::RCP<Teuchos::ParameterList>& kGeometryParameters) : Geometry(kComm, kGeometryParameters), kComm_(kComm) { const auto kFileName = kGeometryParameters->get<std::string>("File Name"); const auto kIgesReader = Teuchos::rcp(new IGESControl_Reader); const auto status = kIgesReader->ReadFile(kFileName.c_str()); // TODO(johntfoster@gmail.com): Check the status of the file // Returns list of all entities from IGES file auto iges_entity_list = kIgesReader->GiveList(); // Transfer all entities at once number_of_iges_entities_ = iges_entity_list->Length(); number_of_transferred_entities_ = kIgesReader->TransferList(iges_entity_list); // Obtain result in a single OCCT shape transferred_occt_shape_ = kIgesReader->OneShape(); // Print output to check status this->initialize(); }
c98f9cca2602b218911154decff55504d72f7e74
6131fc9dc8dbbb6a5c6d40a6c947e678eebfdf2d
/project_template/Windows/NYUCodebase/HW5/Game.h
1ec5c1a9b0f0db299c91da07b4299e9ef9b812a0
[]
no_license
at2336/Trapped
476e0aa03d9dae4182d761d8b660aea92b9a91fe
d00880b98fad3463ea742ca71dbaabedf8fa0eea
refs/heads/master
2021-05-31T14:22:27.157742
2016-05-15T01:40:02
2016-05-15T01:40:02
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,138
h
Game.h
#ifdef _WINDOWS #include <GL/glew.h> #endif #include <SDL.h> #include <SDL_opengl.h> #include <SDL_image.h> #include <string> #include <vector> #include "Entity.h" #include <SDL_mixer.h> using namespace std; #ifdef _WINDOWS #define RESOURCE_FOLDER "" #else #define RESOURCE_FOLDER "NYUCodebase.app/Contents/Resources/" #endif class Game { public: Game(); GLuint LoadTexture(const char *image); void DrawMap(ShaderProgram *program); bool readEntityData(std::ifstream &stream); bool readLayerData(std::ifstream &stream); bool readHeader(std::ifstream &stream); void placeEntity(string type, float placeX, float placeY); void drawEntities(ShaderProgram program); void DrawText(ShaderProgram *program, const char *image_path, string text, float size, float spacing, float x, float y); float returnX(); float returnY(); void hitLimit(); void renderAndUpdate(); private: bool win; unsigned mapHeight; unsigned mapWidth; int** levelData; int spriteCountX = 30; int spriteCountY = 30; float elapsed; float cast; float TILE_SIZE = 0.1f; float lastFrameTicks = 0.0f; vector<Entity*> entities; Mix_Chunk *someSound; };
cd77019d09f77401717aa093e0503bc2c6b269c8
6c651658d1c61b75b84a11fc0653bcf5756e84a1
/vehicle.cpp
7988083fbd54b8d8f301375080c8a889812746f8
[]
no_license
morganwallin/TrainSimulation
20b05725079bc8b90783dd9360a44267258857dc
a0a74324a40c363bf07f6aa2cf7eba104024eaf5
refs/heads/main
2022-12-24T22:48:10.300485
2020-10-08T13:45:16
2020-10-08T13:45:16
302,354,804
0
0
null
null
null
null
UTF-8
C++
false
false
3,398
cpp
vehicle.cpp
/* Morgan Vallin, mova1701, mova1701@student.miun.se 2018-06-11, Projektarbete, Objektorienterad programmering i C++ vehicle.cpp Definitions for the Vehicle Class. Manipulates vehicles. "Vehicle" is a base class for 4 other "vehicles" and 2 "locomotives". */ #include "vehicle.h" //Constructor Vehicle::Vehicle() { idNumber=-1; } //Constructor with initializing Vehicle::Vehicle(int pmIdNumber) { idNumber=pmIdNumber; } //Prints a vehicle, how much to print depends on the user Log Level void Vehicle::printVehicle(std::string pmLogLevel) const { //Lowest LogLevel std::cout << "ID-Number: " << idNumber << "\t Type of Vehicle: "; switch(typeOfVehicle) { case 0: std::cout << "Sitting Car\t\t"; break; case 1: std::cout << "Sleeping Car\t\t"; break; case 2: std::cout << "Open Cargo\t\t"; break; case 3: std::cout << "Closed Cargo\t\t"; break; case 4: std::cout << "Electric Locomotive\t"; break; case 5: std::cout << "Diesel Locomotive\t"; break; default:break; } //For normal LogLevel if(pmLogLevel == "Normal" || pmLogLevel == "High") { switch(typeOfVehicle) { case 0: std::cout << " Number of Seats: " << getParam0(); break; case 1: std::cout << " Number of Beds: " << getParam0(); break; case 2: std::cout << " Capacity (tonne): " << getParam0() << "t"; break; case 3: std::cout << " Capacity (m^3): " << getParam0() << "m^3"; break; case 4: std::cout << " Max km/h: " << getParam0() << "km/h"; break; case 5: std::cout << " Max km/h: " << getParam0() << "km/h"; break; default:break; } } //For High LogLevel if(pmLogLevel == "High") { switch(typeOfVehicle) { case 0: std::cout << "\t Internet: "; if(getParam1() == 1) { std::cout << "Yes"; } else { std::cout << "No"; } break; case 2: std::cout << "\t Load area(m^2): " << getParam1() << "m^2"; break; case 4: std::cout << "\t Max kW: " << getParam1() << "kW"; break; case 5: std::cout << "\t Litre/h: " << getParam1() << " l/h"; break; default:break; } } std::cout << std::endl; } //Constructor SittingCar::SittingCar(int pmIdNumber, int pmNrOfSeats, int pmInternet) : Vehicle(pmIdNumber) { nrOfSeats=pmNrOfSeats; internet=pmInternet; } //Constructor SleepingCar::SleepingCar(int pmIdNumber, int pmNrOfBeds) : Vehicle(pmIdNumber) { nrOfBeds=pmNrOfBeds; } //Constructor OpenCargoCar::OpenCargoCar(int pmIdNumber, int pmCapacity, int pmSquareMeter) : Vehicle(pmIdNumber) { capacity=pmCapacity; squareMeter=pmSquareMeter; } //Constructor ClosedCargoCar::ClosedCargoCar(int pmIdNumber, int pmCubicMeter) : Vehicle(pmIdNumber) { cubicMeter=pmCubicMeter; }
863aa7914141daf0d6443951baf94c7e1436d033
1735261e845e96ec83e438999bb80d914444a666
/practica_01/practica_01.ino
c6998e94d59b156559cdc53a6f88f67977371c73
[ "MIT" ]
permissive
funcionlab/automatizacion-de-huertos
fdb283c350e4c2db3b6bfe69dd45ab5b2e28ca1b
2d4647b1aaf959dbb3e52480d3ff2a40889c6ada
refs/heads/master
2020-04-15T23:16:22.810488
2019-01-12T17:25:08
2019-01-12T17:25:08
165,100,558
0
0
null
null
null
null
UTF-8
C++
false
false
299
ino
practica_01.ino
void setup() { pinMode( 9 , OUTPUT); } void loop() { analogWrite(9, 10); delay(1000); analogWrite(9, 50); delay(1000); analogWrite(9, 100); delay(1000); analogWrite(9, 150); delay(1000); analogWrite(9, 200); delay(1000); analogWrite(9, 255); delay(1000); }
3d068c2b1304fb1ce3b52c8853471244f96053be
4f1f1c8b906bebe10810525e58f9c1688eebc63b
/CodeForces/ECR1/B.cpp
7e778bd5a22386670477db7d72459e886e7131c1
[]
no_license
stone725/CompetitiveProgramming
40ef3c6c9f9c8952366b1449805d21dc0c44d6dd
d6558c718e1dce384ca5accaf7253412849d590f
refs/heads/master
2023-01-07T11:11:19.128446
2023-01-01T01:39:39
2023-01-01T01:39:39
194,200,546
0
0
null
null
null
null
UTF-8
C++
false
false
511
cpp
B.cpp
#include <iostream> #include <string> using namespace std; int main() { string str; cin >> str; int t; cin >> t; while (t--) { cerr << str << "\n"; int l, r, k; cin >> l >> r >> k; if (l == r) continue; l--; if (k > r - l) { k %= (r - l); } str = str.substr(0, l) + str.substr(r - k, k) + str.substr(l, r - l - k) + str.substr(r); } cout << str << "\n"; }
951bc86f5757797b0b39d4ac1195a34b79e3fdae
f98c9dea0e212be5c7bc3161499e5633383bd4d7
/cpp/gugudan_test.cpp
4f9a2e27f84234b784fd0db6f49f2f73b2ed7d7c
[ "MIT" ]
permissive
ysoftman/test_code
dddb5bee3420977bfa335320a09d66e5984403f5
0bf6307073081eeb1d654a1eb5efde44a0bdfe1e
refs/heads/master
2023-08-17T05:45:49.716829
2023-08-16T05:00:09
2023-08-16T05:00:09
108,200,568
4
0
MIT
2023-03-15T04:23:10
2017-10-25T00:49:26
C++
UTF-8
C++
false
false
560
cpp
gugudan_test.cpp
// ysoftman // 구구단 입력 받아 출력(1 ~ 9 숫자만) #include <stdio.h> #include <stdlib.h> #include <string.h> int main() { int num1, num2; char ch; // 출력할 단 입력 받기 while (1) { printf("Input Number: "); if ((ch = getchar()) != 0) { if (ch >= 49 && ch <= 57) { printf("Input number is %d\n", ch - 48); num1 = ch - 48; break; } else { printf("Input number1 Again\n"); } } } for (num2 = 1; num2 <= 10; num2++) { printf("%2d * %2d = %2d\n", num1, num2, num1 * num2); } return 0; }
5ff2261652ebcf063969a2d8c05114c3d538dfe4
fa2250779a2eb0b3155f8a9912b9b08caeba0cbe
/sample.Makefile/include/fn.hpp
f53e5bce4c14cd8a5c882727045d8e9c5d37e170
[ "MIT" ]
permissive
on62/daft-lib
33b3d00fe3520b9ce78ddcbd7a814ed78c1bf254
7890fdba0aab800022ab9afb958946bd06779f33
refs/heads/master
2022-11-14T23:08:13.978445
2020-07-08T13:33:09
2020-07-08T13:33:09
null
0
0
null
null
null
null
UTF-8
C++
false
false
65
hpp
fn.hpp
#ifndef _FN_HPP_ #define _FN_HPP_ extern void fn(void); #endif