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
7e6a1f64659287bbe1f6016145fc366d12f85685
223dd6cdf14a826fead3aba84fbb310e2757c448
/Volume 10000/Volume 109/10922 - 2 the 9s.cpp
5a624e8c2fe10124e3d7fb5bebfdff57b219e9e4
[]
no_license
badstyle319/UVA
dad2972fcdd0dc219e90328607547a3524b8b047
28c27e8dfe766d7d83969a0f5b7dbc9a6b9282c6
refs/heads/master
2022-11-29T07:07:35.957202
2020-08-03T06:46:40
2020-08-03T06:46:40
284,227,832
0
0
null
null
null
null
UTF-8
C++
false
false
1,097
cpp
10922 - 2 the 9s.cpp
#include <cstdio> #include <cstdlib> #include <cstring> #include <string> #include <vector> #include <map> #include <algorithm> #include <cmath> #include <iostream> #include <iomanip> #include <sstream> #include <bitset> #define LL long long #define ULL unsigned long long #define PI 3.14159265 using namespace std; static int dx[] = {-1,-1,-1,0,0,1,1,1}; static int dy[] = {-1,0,1,-1,1,-1,0,1}; void ans(string str, int &deg){ int sum=0; for(int i=0;i<str.size();i++) sum+=str[i]-'0'; if(sum%9==0){ deg++; stringstream ss; ss<<sum; if(sum!=9) ans(ss.str(), deg); } } int main() { #ifndef ONLINE_JUDGE freopen("in.txt", "r", stdin); freopen("out.txt", "w", stdout); #endif while(1){ string str; int degree=0; cin>>str; if(str=="0") break; ans(str, degree); if(degree>0) cout<<str<<" is a multiple of 9 and has 9-degree "<<degree<<"."<<endl; else cout<<str<<" is not a multiple of 9."<<endl; } #ifndef ONLINE_JUDGE fclose(stdin); fclose(stdout); #endif return 0; }
c200dbf5f30a34cdbb50c4cde37fc0306ea7784d
93ddbfb911f129b20aa0c211437b3c94a92b83e6
/src/client/Client.h
f0c6d8c0f6a2eb975b39279c774fb114bef57aa6
[ "MIT" ]
permissive
pedro-esteves-pinto/mcbridge
38c8581033f3796eaf08a72b734b472362d5e390
7302e8161015d76e81b355821496dae655b1dd00
refs/heads/master
2022-11-13T23:11:21.686598
2020-07-03T21:30:59
2020-07-03T21:30:59
268,184,386
5
1
null
null
null
null
UTF-8
C++
false
false
694
h
Client.h
#pragma once #include "ClientConfig.h" #include <memory> namespace mcbridge { struct Message; // Orchestrates the connection to a mcbridge server, the creation of // new multicast senders and possibly the discovery of new joined // groups. class Client { public: explicit Client(ClientConfig const &); ~Client(); int run(); private: enum class State; struct ConnectionRec; void schedule_timer(); void pause(); void connect(); void on_timer(); void on_msg(Message const &); void on_disconnect(); void scan_for_new_joined_groups(); std::set<EndPoint> get_current_groups(); struct PImpl; std::unique_ptr<PImpl> me; }; } // namespace mcbridge
abbbc7947836dee1624b872a8efcb5999a48e192
ee08b92160608af6fe2925c64aa2df143efa775c
/sudoku_solver/game_screen.h
79488fb1e0ff397aa5100111e1cecc30889530b5
[]
no_license
DennisSHCheung/sudoku_solver
1f507a33506e1ff6352ee46cdca21bbd5d1db1e2
22c464c4902177479d59e0f930725682c93e25f5
refs/heads/master
2020-09-03T02:26:47.016380
2020-06-19T12:05:16
2020-06-19T12:05:16
219,361,778
1
0
null
null
null
null
UTF-8
C++
false
false
1,411
h
game_screen.h
#pragma once #include "screen.h" #include <fstream> #include "sudoku_logic.h" #include "ascii_character.h" #include <random> class game_screen : public screen { private: enum button_name { SOLVE, RETURN, NEW }; protected: sf::RectangleShape grid; std::vector<sf::RectangleShape> box; std::vector<sf::Sprite> number_sprite; sf::RectangleShape indicator; std::vector<sf::Sprite> text; // grid indicator bool is_indicator_on; bool is_changed; int indicator_position; // 9x9 grid int game_puzzle[9][9]; bool is_init_exist[9][9]; int puzzles_count; int current_puzzle; std::vector<std::vector<std::vector<int>>> all_puzzles; public: game_screen(); virtual screen_name run(sf::RenderWindow& app); void display(sf::RenderWindow& app); // Initialize game void init(bool is_custom); void init_indicator(); void load_puzzle(); void select_puzzle(); void set_grid_origin(int index, float& position); void draw_grid(); void draw_inner_grid(sf::Vector2f origin); void draw_numbers(); virtual void draw_UI(); bool key_code_handler(sf::Event& event, int i); screen_name event_handler(sf::Event&event, sf::RenderWindow& app); virtual void insert_number(sf::Event& event); void check_indicator(sf::RenderWindow& app); void solve_sudoku(); virtual void init_buttons(); screen_name button_handler(sf::RenderWindow& app); int find_button(sf::RenderWindow& app); ~game_screen(); };
1573cbf15a8b2438a827b7d871b6497c7f0dfc3b
f1b37e672c9ecdca1c91d8fe1ace9de9eca253a0
/tests/unittest.cc
4a03b1bdd3b866b31211241eab3c6eaafab79ad3
[ "MIT" ]
permissive
SuperDan1/DataStructure
80322faa334f8ab20e391a37787b305e3f050922
5e2eb2a2cee612591934ebc81b7c9eee44133e00
refs/heads/main
2023-04-12T00:45:22.050575
2021-05-15T12:13:01
2021-05-15T12:13:01
347,659,388
1
0
MIT
2021-05-15T12:13:02
2021-03-14T14:28:26
C++
UTF-8
C++
false
false
335
cc
unittest.cc
#include "gtest/gtest.h" double add_numbers(const double f1, const double f2) { return f1 + f2; } TEST(example, add) { double res; res = add_numbers(1.0, 2.0); ASSERT_NEAR(res, 3.0, 1.0e-11); } int main(int argc, char **argv) { ::testing::InitGoogleTest(&argc, argv); int ret = RUN_ALL_TESTS(); return ret; }
a591446cb4347010e65e9ee17de63db8d88cde4b
f8e8700964d4f9159a043f18ade9ceff5eb7594c
/c++/other/Count of positives sum of negatives.cpp
7a9c3098cb76c0815187370ace3ce2b851440cba
[]
no_license
xlfsummer/codewar-solutions
bf6dd0a4282c2af387bdf535da2476fed4f0e7a1
7107e660422043b782bdda97e8cac36b201fffb0
refs/heads/master
2020-06-29T00:49:56.417427
2019-08-22T18:01:57
2019-08-22T18:01:57
200,390,216
0
0
null
null
null
null
UTF-8
C++
false
false
244
cpp
Count of positives sum of negatives.cpp
#include <vector> std::vector<int> countPositivesSumNegatives(std::vector<int> input) { if(input.empty()) return {}; int countP = 0; int sumN = 0; for(int i: input) i > 0 ? countP++ : (sumN += i); return {countP , sumN}; }
aba387914f4d29153fd5af50345985838f22063a
76faf7e71ff6d645a3feb89d13248badb55c5035
/liberParVisu/liberParVisuVTK.cpp
daa233816d89c8b8a953f49c7783bdd60ed34dcc
[]
no_license
liberlocus/LLParVisu
a2b08a26ec06131db70b863ead9d66e168d9282a
06c02a19754cd002b737dbae965ee3625d4e16bb
refs/heads/master
2016-09-06T18:25:38.506913
2013-05-01T04:41:13
2013-05-01T04:41:13
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,389
cpp
liberParVisuVTK.cpp
#include "liberParVisuVTK.h" #include <string> c_ParVTK::c_ParVTK(string fileName, int nodeNum, float *x, float *y, float *z, int cellNum, int nodePerCell, int **cellConnectivity, char ** varName, int varSize, float **varMatrix, int mpi_rank, int mpi_size) : c_VTK(fileName, nodeNum, x, y, z, cellNum, nodePerCell, cellConnectivity, varName, varSize, varMatrix){ // Related to MPI _mpi_rank = mpi_rank; _mpi_size = mpi_size; } // c_ParVTK::~c_ParVTK(){ // delete [] _x; // _x = NULL; // // delete [] _y; // _y = NULL; // // delete [] _z; // _z = NULL; for(int i=0; i<_cellNum; i++){ delete [] _cellConnectivity[i]; _cellConnectivity[i] = NULL; } delete [] _cellConnectivity; _cellConnectivity = NULL; delete [] _varName; _varName = NULL; for(int i=0; i<_varSize; i++){ delete [] _varMatrix[i]; _varMatrix[i] = NULL; } delete [] _varMatrix; _varMatrix = NULL; } void c_ParVTK::doAll(){ fileCreation(); } string c_ParVTK::getIndividualFileName(){ string f1, f2, f3, f4, ff; f1 = _fileName; f2 = "_"; stringstream ss; ss << _mpi_rank; f3 = ss.str(); // f3 = to_string(_mpi_rank); // Cmake doesnt work with -std=c++11 f4 = ".vtu"; ff = f1 + f2 + f3 + f4; return ff; } void c_ParVTK::writeIndividualFile(){ _writer = vtkSmartPointer<vtkXMLUnstructuredGridWriter>::New(); string fileName = getIndividualFileName(); _writer->SetFileName(fileName.c_str()); #if VTK_MAJOR_VERSION <= 5 _writer->SetInput(_unstructuredGrid); #else _writer->SetInputData(_unstructuredGrid); #endif _writer->Write(); } string c_ParVTK::getParallelFileName(){ string f1, f2, ff; f1 = _fileName; f2 = ".pvtu"; ff = f1 +f2; return ff; } void c_ParVTK::parallelWriteFile(){ if(_mpi_rank==0){ _pwriter = vtkSmartPointer<vtkXMLPUnstructuredGridWriter>::New(); string fileName = getParallelFileName(); _pwriter->SetFileName(fileName.c_str()); _pwriter->SetNumberOfPieces(_mpi_size); #if VTK_MAJOR_VERSION <= 5 _pwriter->SetInput(_unstructuredGrid); #else _pwriter->SetInputData(_unstructuredGrid); #endif _pwriter->Write(); } } void c_ParVTK::fileCreation(){ createPoints(); createCells(); createCellCenterData(); createGrid(); writeIndividualFile(); parallelWriteFile(); }
3deeb76b3a04f574fffa7e49b059a2ac2bdf4a9b
8ca4009e33c2a3b72e5666b58ed2d8568a297f92
/test/UnitTest/Tests/Services/EventHandlers/TestStepStartEventHandlerTest.cpp
ae227bd0d84733985b105b7c553112548613ec17
[ "MIT" ]
permissive
systelab/cpp-gtest-allure-utilities
6a391f76795eb0be4a3b7602176b126d1c967d69
9f1f776c3cd47ad29b1e681cc6e62fbe555db08a
refs/heads/master
2021-12-24T04:40:38.801271
2021-10-27T13:07:21
2021-10-27T13:07:21
160,388,133
11
6
MIT
2021-05-31T08:41:08
2018-12-04T16:37:13
C++
UTF-8
C++
false
false
4,213
cpp
TestStepStartEventHandlerTest.cpp
#include "stdafx.h" #include "GTestAllureUtilities/Services/EventHandlers/TestStepStartEventHandler.h" #include "GTestAllureUtilities/Model/StepType.h" #include "GTestAllureUtilities/Model/TestProgram.h" #include "TestUtilities/Mocks/Services/System/MockTimeService.h" using namespace testing; using namespace systelab::gtest_allure; using namespace systelab::gtest_allure::test_utility; namespace systelab { namespace gtest_allure { namespace unit_test { class TestStepStartEventHandlerTest : public testing::Test { void SetUp() { setUpTestProgram(); auto timeService = buildTimeService(); m_service = std::make_unique<service::TestStepStartEventHandler>(m_testProgram, std::move(timeService)); } void setUpTestProgram() { model::TestSuite finishedTestSuite; finishedTestSuite.setStage(model::Stage::FINISHED); finishedTestSuite.addTestCase(buildTestCase("TC-1.1", model::Stage::FINISHED)); finishedTestSuite.addTestCase(buildTestCase("TC-1.2", model::Stage::FINISHED)); m_testProgram.addTestSuite(finishedTestSuite); model::TestSuite runningTestSuite; runningTestSuite.setStage(model::Stage::RUNNING); runningTestSuite.addTestCase(buildTestCase("TC-2.1", model::Stage::FINISHED)); runningTestSuite.addTestCase(buildTestCase("TC-2.2", model::Stage::RUNNING)); m_testProgram.addTestSuite(runningTestSuite); m_runningTestCase = &(m_testProgram.getTestSuite(1).getTestCases()[1]); } model::TestCase buildTestCase(const std::string& name, model::Stage stage) { model::TestCase testCase; testCase.setName(name); testCase.setStage(stage); testCase.setStatus(model::Status::UNKNOWN); return testCase; } std::unique_ptr<service::ITimeService> buildTimeService() { auto timeService = std::make_unique<MockTimeService>(); m_timeService = timeService.get(); m_currentTime = 987654321; ON_CALL(*m_timeService, getCurrentTime()).WillByDefault(Return(m_currentTime)); return timeService; } protected: std::unique_ptr<service::TestStepStartEventHandler> m_service; model::TestProgram m_testProgram; MockTimeService* m_timeService; model::TestCase* m_runningTestCase; time_t m_currentTime; }; TEST_F(TestStepStartEventHandlerTest, testHandleTestStepStartAddsStartedActionStepIntoRunningTestCase) { std::string startedActionName = "StartedAction"; bool isActionStep = true; m_service->handleTestStepStart(startedActionName, isActionStep); ASSERT_EQ(1, m_runningTestCase->getStepCount()); const model::Step& addedTestStep = *m_runningTestCase->getStep(0); EXPECT_EQ(startedActionName, addedTestStep.getName()); EXPECT_EQ(model::StepType::ACTION_STEP, addedTestStep.getStepType()); EXPECT_EQ(m_currentTime, addedTestStep.getStart()); EXPECT_EQ(model::Stage::RUNNING, addedTestStep.getStage()); EXPECT_EQ(model::Status::UNKNOWN, addedTestStep.getStatus()); } TEST_F(TestStepStartEventHandlerTest, testHandleTestStepStartAddsStartedExpectedResultStepIntoRunningTestCase) { std::string startedExpectedResultName = "StartedExpectedResult"; bool isActionStep = false; m_service->handleTestStepStart(startedExpectedResultName, isActionStep); ASSERT_EQ(1, m_runningTestCase->getStepCount()); const model::Step& addedTestStep = *m_runningTestCase->getStep(0); EXPECT_EQ(startedExpectedResultName, addedTestStep.getName()); EXPECT_EQ(model::StepType::EXPECTED_RESULT_STEP, addedTestStep.getStepType()); EXPECT_EQ(m_currentTime, addedTestStep.getStart()); EXPECT_EQ(model::Stage::RUNNING, addedTestStep.getStage()); EXPECT_EQ(model::Status::UNKNOWN, addedTestStep.getStatus()); } TEST_F(TestStepStartEventHandlerTest, testHandleTestStepStartThrowsExceptionWhenNoRunningTestSuite) { m_testProgram.clearTestSuites(); ASSERT_THROW(m_service->handleTestStepStart("StartedStep", true), service::TestStepStartEventHandler::NoRunningTestSuiteException); } TEST_F(TestStepStartEventHandlerTest, testHandleTestStepStartThrowsExceptionWhenNoRunningTestCase) { m_testProgram.getTestSuite(1).clearTestCases(); ASSERT_THROW(m_service->handleTestStepStart("StartedStep", true), service::TestStepStartEventHandler::NoRunningTestCaseException); } }}}
5aa72085246d13e29362f5cd1bd9e721b7a7fb84
5dc4ea36514927efd678638e2095a4e8e32c0386
/NPSVisor/tools/svMaker/source/pAlarm/alarmEditorDlg.h
3604e2f2d03f711c4638e932ced845bb195a7727
[ "Unlicense" ]
permissive
NPaolini/NPS_OpenSource
732173afe958f9549af13bc39b15de79e5d6470c
0c7da066b02b57ce282a1903a3901a563d04a28f
refs/heads/main
2023-03-15T09:34:19.674662
2021-03-13T13:22:00
2021-03-13T13:22:00
342,852,203
0
0
null
null
null
null
UTF-8
C++
false
false
1,858
h
alarmEditorDlg.h
//----------- alarmEditorDlg.h ------------------------------------------------------ //---------------------------------------------------------------------------- #ifndef alarmEditorDlg_H_ #define alarmEditorDlg_H_ //---------------------------------------------------------------------------- #include "precHeader.h" //---------------------------------------------------------------------------- #include <commctrl.h> #include <stdlib.h> #include "resource.h" #include "pModDialog.h" #include "p_Vect.h" #include "alarmDlg.h" #include "assocDlg.h" //---------------------------------------------------------------------------- class PD_alarmEditorDlg : public PModDialog { private: typedef PModDialog baseClass; public: PD_alarmEditorDlg(PWin* parent, uint resId = IDD_ALARM_EDITOR, HINSTANCE hinstance = 0); virtual ~PD_alarmEditorDlg(); virtual bool create(); PD_Alarm* getAlarm(PD_Assoc* client); PD_Assoc* getAssoc(PD_Alarm* client); // verifica non l'oggetto passato, ma quello collegato bool isDirty(PD_Alarm* client); bool isDirty(PD_Assoc* client); bool isDirty(PD_Base* client); bool isDirty(); protected: virtual LRESULT windowProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam); private: PVect<PD_Alarm*> clientAlarm; PVect<PD_Assoc*> clientAssoc; int currPage; HIMAGELIST ImageList; void chgPage(int page); void chgAssocPage(int page); void chgAlarmPage(int page); enum which { jobbingAlarm, jobbingAssoc }; which onJob; void toggleVis(); bool saveOnExit(); void remTab(); void addTab(); void moveChild(PWin* child); void makeClient(); void performAddTab(uint cid, uint pos); bool saveDirtyPage(bool req); }; //---------------------------------------------------------------------------- #endif
d0cbfda3b1a79a9b33a16f28562627ca8712d1bf
1222b97d66c89d16d09ccf84cbe44fce27df00d5
/이진탐색트리(포인터).cpp
148f755943e712ef082b043a4e5d343962a46b2b
[]
no_license
Hyonony/tree_project
6fa9ba2145116fee29471a6d7fb6f98ce94b2f93
94bf590fbdd51e9512b92bf192acabfdec60ef2f
refs/heads/master
2023-05-10T19:50:14.081989
2021-05-26T02:49:22
2021-05-26T02:49:22
370,885,501
0
0
null
2021-05-26T02:38:45
2021-05-26T02:38:45
null
WINDOWS-1252
C++
false
false
2,951
cpp
이진탐색트리(포인터).cpp
#include <stdio.h> #include <stdlib.h> #include <iostream> using namespace std; typedef struct node { int data; struct node* rightChild; struct node* leftChild; }Node; typedef Node* treePointer; treePointer Search(treePointer T, int Key); treePointer Insert(treePointer T, int Key); treePointer Create(int S[]); void print(treePointer T); void PreOrder(treePointer T); void InOrder(treePointer T); void PostOrder(treePointer T); void SuccessorCopy(treePointer& T, int& Key); void Delete(treePointer& T, int Key); treePointer Search(treePointer T, int Key) { if (T == NULL) printf("¿À·ù"); else if (T->data == Key) return T; else if (T->data > Key) return Search(T->leftChild, Key); else return Search(T->rightChild, Key); } treePointer Insert(treePointer T, int Key) { if (T == NULL) { T = new node; T->data = Key; T->leftChild = NULL; T->rightChild = NULL; } else if (T->data > Key) { T->leftChild = Insert(T->leftChild, Key); } else { T->rightChild = Insert(T->rightChild, Key); } return T; } treePointer Create(int S[]) { treePointer root = NULL; root = Insert(root, S[0]); for (int i = 0; i < 10; i++) { Insert(root, S[i]); } return root; } void print(treePointer T) { if (T == NULL) return; printf("%d ", T->data); print(T->leftChild); print(T->rightChild); } void PreOrder(treePointer T) { if (T != NULL) { return; } printf("%d ", T->data); print(T->leftChild); print(T->rightChild); } void InOrder(treePointer T) { if (T != NULL) { return; } print(T->leftChild); printf("%d ", T->data); print(T->rightChild); } void PostOrder(treePointer T) { if (T != NULL) { return; } print(T->leftChild); print(T->rightChild); printf("%d ", T->data); } void SuccessorCopy(treePointer& T, int& Key) { if (T->leftChild == NULL) { Key = T->data; treePointer Temp = T; T = T->rightChild; delete Temp; } else SuccessorCopy(T->leftChild, Key); } void Delete(treePointer& T, int Key) { if (T == NULL) printf("¿À·ù"); else if (T->data > Key) Delete(T->leftChild, Key); else if (T->data < Key) Delete(T->rightChild, Key); else if (T->data == Key) { if ((T->leftChild == NULL) && (T->rightChild == NULL)) { treePointer Temp = T; T = NULL; delete Temp; } else if (T->leftChild == NULL) { treePointer Temp = T; T = T->rightChild; delete Temp; } else if (T->rightChild == NULL) { treePointer Temp = T; T = T->leftChild; delete Temp; } else SuccessorCopy(T->rightChild, T->data); } } int main() { treePointer BT = NULL; int S[10] = { 6,4,8,3,5,7,9,1,2,10 }; BT = Create(S); PreOrder(BT); cout << endl; InOrder(BT); cout << endl; PostOrder(BT); cout << endl; Delete(BT, 10); PreOrder(BT); cout << endl; Delete(BT, 9); PreOrder(BT); cout << endl; Delete(BT, 1); PreOrder(BT); cout << endl; Delete(BT, 5); PreOrder(BT); cout << endl; InOrder(BT); cout << endl; return 0; }
77d38a47557340874d116d6e7e218ae2085da293
3af68b32aaa9b7522a1718b0fc50ef0cf4a704a9
/cpp/D/A/D/A/ADADA.cpp
bbb9b381454832c0ee0b69bb62184be950ae236b
[]
no_license
devsisters/2021-NDC-ICECREAM
7cd09fa2794cbab1ab4702362a37f6ab62638d9b
ac6548f443a75b86d9e9151ff9c1b17c792b2afd
refs/heads/master
2023-03-19T06:29:03.216461
2021-03-10T02:53:14
2021-03-10T02:53:14
341,872,233
0
0
null
null
null
null
UTF-8
C++
false
false
500
cpp
ADADA.cpp
#include "ADADA.h" #include "A/ADADAA.h" #include "B/ADADAB.h" #include "C/ADADAC.h" #include "D/ADADAD.h" #include "E/ADADAE.h" namespace ADADA { std::string run() { std::string out("ADADA"); out += std::string(SEPARATOR); out += ADADAA::run(); out += std::string(SEPARATOR); out += ADADAB::run(); out += std::string(SEPARATOR); out += ADADAC::run(); out += std::string(SEPARATOR); out += ADADAD::run(); out += std::string(SEPARATOR); out += ADADAE::run(); return out; } }
a0cbd3dfc2794265c7bd273d151648c6a2dbf711
250101ffb5bd6c4bcfe328854284338772e9aab5
/map_server/logic_moudle/task_moudle/MapLogicTasker.cpp
80f2c7571f42cf185c71fcf7827642f0b8427fe0
[]
no_license
MENGJIANGTAO/GameServer-2
aa1299e9442e221a1a2d26457c18396d5e4c54bd
be261b565a1f823d8d17235a21dd1f2431c0a30d
refs/heads/master
2021-09-17T22:45:10.621608
2018-07-06T05:15:47
2018-07-06T05:15:47
null
0
0
null
null
null
null
UTF-8
C++
false
false
97,307
cpp
MapLogicTasker.cpp
/* * MapLogicTasker.cpp * * Created on: 2013-11-07 10:42 * Author: lyz */ #include "MapLogicTasker.h" #include "MapLogicPlayer.h" #include "MapMonitor.h" #include "TaskImplement.h" #include "TaskRoutineImp.h" #include "TaskTrialImp.h" #include "SerialRecord.h" #include "ProtoDefine.h" #include "GameFont.h" #include "MLMounter.h" MapLogicTasker::MapLogicTasker(void) : novice_step_(0), lastest_main_task_id_(0),lcontri_day_(0) { ::memset(this->uiopen_step_, 0, sizeof(this->uiopen_step_)); } MapLogicTasker::~MapLogicTasker(void) { /*NULL*/ } MapLogicPlayer *MapLogicTasker::task_player(void) { return dynamic_cast<MapLogicPlayer *>(this); } int MapLogicTasker::task_sign_in(const int type) { this->task_construct_main(); this->task_construct_branch(false); this->task_listen_enter_special_scene(this->task_player()->scene_id()); this->correct_main_task(); this->refresh_routine_task(Time_Value::gettimeofday(), false); // this->refresh_trial_task(false); // this->check_and_update_open_ui_by_sign(); this->new_task_construct_routine(true); this->offer_task_construct_routine(true); this->league_task_construct_routine(true); return 0; } int MapLogicTasker::task_sign_out(void) { return 0; } bool MapLogicTasker::is_finish_guide_task() { static int task_id = CONFIG_INSTANCE->const_set("new_main_task_id"); JUDGE_RETURN(task_id != 0, true); return this->task_submited_once_.count(task_id) > 0; } void MapLogicTasker::task_reset() { TaskInfo *task_info = 0; for (TaskMap::iterator iter = this->task_map_.begin(); iter != this->task_map_.end(); ++iter) { task_info = iter->second; MAP_MONITOR->task_info_pool()->push(task_info); } this->task_map_.clear(); this->task_accepted_lvl_.clear(); this->task_accepted_monster_.clear(); this->task_accepted_collect_.clear(); this->task_accepted_attend_.clear(); this->task_accepted_package_.clear(); this->task_accepted_scene_.clear(); this->task_submited_once_.clear(); this->task_listen_item_.unbind_all(); this->finish_task_.clear(); this->task_accepted_branch_.clear(); this->novice_step_ = 0; this->lastest_main_task_id_ = 0; ::memset(this->uiopen_step_, 0, sizeof(this->uiopen_step_)); this->routine_refresh_tick_ = Time_Value::zero; this->clear_routine_task(false); this->routine_consume_history_.clear(); this->is_second_routine_.clear(); this->is_finish_all_routine_.clear(); this->is_routine_task_.clear(); this->routine_task_index_.clear(); this->routine_total_num_.clear(); this->lcontri_day_tick_ = Time_Value::zero; this->lcontri_day_ = 0; this->open_ui_set_.clear(); this->ui_version_ = 0; } void MapLogicTasker::adjust_level_by_task(int task_id) { if (task_id == 0) { task_id = this->latest_main_task(); } TaskInfo* task_info = this->find_task(task_id); JUDGE_RETURN(task_info != NULL, ;); JUDGE_RETURN(task_info->is_visible() == true, ;); JUDGE_RETURN(task_info->is_main_task() == true, ;); const Json::Value& conf = task_info->conf(); JUDGE_RETURN(conf["lvl_compensate"].asInt() == 1, ;); MapLogicPlayer* player = this->task_player(); int need_level = conf["before_accept"]["level"][1u].asInt(); JUDGE_RETURN(player->role_level() < need_level, ;); JUDGE_RETURN(player->add_validate_operate_tick(3, GameEnum::TASK_LEVLE_OPERATE) == true, ;); player->send_to_map_thread(INNER_MAP_PROP_LEVELUP); } int MapLogicTasker::task_time_up(const Time_Value &nowtime) { // 检查日常环式任务是否到刷新时间 this->refresh_routine_task(nowtime, true); return 0; } int MapLogicTasker::task_construct_main(bool notify_add) { const GameConfig::ConfigMap &task_map = CONFIG_INSTANCE->main_task_map(); for (GameConfig::ConfigMap::const_iterator iter = task_map.begin(); iter != task_map.end(); ++iter) { const Json::Value &task_json = *(iter->second); TaskInfo *task_info = this->find_task(iter->first); if (task_info != 0) { // 处理任务可见到可接的状态变化 if (task_info->is_acceptable() == false && task_info->is_accepted() == false && task_info->is_finish() == false && task_info->is_submit() == false) { const Json::Value &task_prev_level_json = task_json["before_accept"]["level"]; if (task_prev_level_json.size() >= 3) { if (task_prev_level_json[1u].asInt() <= this->task_player()->role_level() && this->task_player()->role_level() <= task_prev_level_json[2u].asInt()) { task_info->set_task_status(TaskInfo::TASK_STATUS_ACCEPTABLE); if (notify_add == true) { this->notify_task_update(task_info); } } } } continue; } if (this->task_submited_once_.find(iter->first) != this->task_submited_once_.end()) { continue; } int prev_task = task_json["precondition"].asInt(); if (prev_task > 0 && this->task_submited_once_.find(prev_task) == this->task_submited_once_.end()) { continue; } if (task_json["before_accept"]["level"].isArray() && task_json["before_accept"]["level"].size() > 0) { if (this->task_player()->role_detail().__level < task_json["before_accept"]["level"][0u].asInt()) { continue; } } if (notify_add == true) { this->insert_task(iter->first, task_json); this->adjust_level_by_task(iter->first); } else { this->init_task(iter->first, task_json); } if (this->task_map_.find(iter->first) != this->task_map_.end()) { break; } } return 0; } int MapLogicTasker::task_construct_branch(bool notify_add) { JUDGE_RETURN(this->is_finish_guide_task() == true, 0); const GameConfig::ConfigMap &task_map = CONFIG_INSTANCE->branch_task_map(); for (GameConfig::ConfigMap::const_iterator iter = task_map.begin(); iter != task_map.end(); ++iter) { const Json::Value &task_json = *(iter->second); TaskInfo *task_info = this->find_task(iter->first); if (task_info != 0) { // 处理任务可见到可接的状态变化 if (task_info->is_accepted() == false && task_info->is_finish() == false && task_info->is_submit() == false) { const Json::Value &task_prev_level_json = task_json["before_accept"]["level"]; if (task_prev_level_json[1u].asInt() <= this->task_player()->role_level() && this->task_player()->role_level() <= task_prev_level_json[2u].asInt()) { task_info->set_task_status(TaskInfo::TASK_STATUS_ACCEPTABLE); this->task_accept(iter->first); } } int branch_type = task_json["exec"]["condition"][0u]["id"][0u].asInt(); //更新最新数据 this->accept_branch_request_info(branch_type); continue; } if (this->task_submited_once_.find(iter->first) != this->task_submited_once_.end()) continue; int prev_task = task_json["precondition"].asInt(); if (prev_task > 0 && this->task_submited_once_.find(prev_task) == this->task_submited_once_.end()) continue; if (task_json["before_accept"]["level"].isArray() && task_json["before_accept"]["level"].size() > 0) { if (this->task_player()->role_detail().__level < task_json["before_accept"]["level"][0u].asInt()) continue; } if (notify_add == true) { this->insert_task(iter->first, task_json); } else { this->init_task(iter->first, task_json); task_info = this->find_task(iter->first); if (task_info != NULL && task_info->is_acceptable() == true) { task_info->set_task_status(TaskInfo::TASK_STATUS_ACCEPTABLE); this->task_accept(iter->first); } } int branch_type = task_json["exec"]["condition"][0u]["id"][0u].asInt(); //更新最新数据 this->accept_branch_request_info(branch_type); } return 0; } int MapLogicTasker::correct_main_task(void) { // 用于登录修正一些错误 return 0; } TaskInfo *MapLogicTasker::init_task(const int task_id, const Json::Value &task_json) { int task_type = task_json["task_type"].asInt(); switch (task_type) { case TaskInfo::TASK_GTYPE_MAINLINE: { return this->init_main_task(task_id, task_json); } case TaskInfo::TASK_GTYPE_ROUTINE: case TaskInfo::TASK_GTYPE_OFFER_ROUTINE: case TaskInfo::TASK_GTYPE_LEAGUE_ROUTINE: { return this->init_routine_task(task_id, task_json); } case TaskInfo::TASK_GTYPE_BRANCH: { return this->init_branch_task(task_id, task_json); } } return 0; } int MapLogicTasker::insert_task(const int task_id, const Json::Value &json) { JUDGE_RETURN(this->task_submited_once_.count(task_id) == 0, -1); TaskInfo *task_info = this->init_task(task_id, json); JUDGE_RETURN(task_info != NULL, -1); if (task_info->is_acceptable() == true) { return this->task_accept(task_id); } else { return this->notify_task_add(task_info); } } TaskInfo *MapLogicTasker::init_branch_task(const int task_id, const Json::Value &task_json) { int level = this->task_player()->role_level(); int status = TaskInfo::TASK_STATUS_NONE; const Json::Value &before_level_json = task_json["before_accept"]["level"]; if (before_level_json.size() < 3 || (before_level_json[1u].asInt() <= level && level <= before_level_json[2u].asInt())) { status = TaskInfo::TASK_STATUS_ACCEPTABLE; } TaskInfo *task_info = MAP_MONITOR->task_info_pool()->pop(); task_info->__task_id = task_id; task_info->__game_type = task_json["task_type"].asInt(); task_info->set_task_status(status); if (this->init_task_object(task_info, task_json) != 0) { MAP_MONITOR->task_info_pool()->push(task_info); return 0; } return task_info; } TaskInfo *MapLogicTasker::init_main_task(const int task_id, const Json::Value &task_json) { int level = this->task_player()->role_level(); int status = TaskInfo::TASK_STATUS_VISIBLE; const Json::Value &before_level_json = task_json["before_accept"]["level"]; if (before_level_json.size() < 3 || (before_level_json[1u].asInt() <= level && level <= before_level_json[2u].asInt())) { status = TaskInfo::TASK_STATUS_ACCEPTABLE; } TaskInfo *task_info = MAP_MONITOR->task_info_pool()->pop(); task_info->__task_id = task_id; task_info->__game_type = task_json["task_type"].asInt(); task_info->set_task_status(status); if (this->init_task_object(task_info, task_json) != 0) { MAP_MONITOR->task_info_pool()->push(task_info); return 0; } this->set_latest_main_task(task_id); return task_info; } int MapLogicTasker::init_task_condition(TaskInfo *task_info, const Json::Value &task_json) { const Json::Value &cond_json = task_json["exec"]["condition"]; for (uint i = 0; i < cond_json.size(); ++i) { TaskConditon* task_cond = MAP_MONITOR->task_condition_pool()->pop(); const std::string &type_str = cond_json[i]["type"].asString(); task_cond->__type = TaskConditon::fetch_type(type_str); task_info->set_logic_type(task_cond->__type); task_cond->__cond_index = i; if (cond_json[i].isMember("id")) { task_cond->__id_list_index = 0; task_cond->__cond_id = TaskConditon::fetch_id(task_cond->__type, cond_json[i]); task_cond->__final_value = cond_json[i]["value"].asInt(); } else if (cond_json[i].isMember("id_list")) { task_cond->__id_list_index = rand() % int(cond_json[i]["id_list"].size()); task_cond->__cond_id = cond_json[i]["id_list"][task_cond->__id_list_index].asInt(); if (cond_json[i].isMember("value_list")) { if (task_cond->is_kill_monster()) { int index = rand() % cond_json[i]["value_list"].size(); task_cond->__final_value = cond_json[i]["value_list"][index].asInt(); } else { int index = (task_cond->__id_list_index >= int(cond_json[i]["value_list"].size()) ? (int(cond_json[i]["value_list"].size()) - 1) : task_cond->__id_list_index); task_cond->__final_value = cond_json[i]["value_list"][index].asInt(); } } else if (cond_json[i].isMember("value_range_list")) { int index = (task_cond->__id_list_index >= int(cond_json[i]["value_range_list"].size()) ? (int(cond_json[i]["value_range_list"].size()) - 1) : task_cond->__id_list_index); const Json::Value &value_range_json = cond_json[i]["value_range_list"][index]; int range = value_range_json[1u].asInt() - value_range_json[0u].asInt() + 1; task_cond->__final_value = value_range_json[0u].asInt() + rand() % range; } MSG_USER("task condition %s %ld %d %d %d %d", this->task_player()->name(), this->task_player()->role_id(), task_info->__task_id, task_cond->__cond_id, task_cond->__final_value, task_cond->__current_value); } else { // trial condition task_cond->__id_list_index = 0; task_cond->__final_value = cond_json[i]["value"].asInt(); } //环式任务优化 if (cond_json[i].isMember("kill_type")) { int kill_type = cond_json[i]["kill_type"].asInt(); int task_type = task_json["task_type"].asInt(); // int range_level = cond_json["range_level"].asInt(); int range_level = this->task_player()->role_level(); if (kill_type == 1) { task_cond->__cond_id = this->fetch_routine_monster_id(task_type, range_level); } task_cond->__kill_type = kill_type; task_cond->__range_level = range_level; } task_info->__condition_list.push_back(task_cond); } return 0; } int MapLogicTasker::init_task_star(TaskInfo *task_info, const Json::Value &task_json) { JUDGE_RETURN(task_json.isMember("task_star"), 0); int rand_value = rand() % 10000; int rand_base = 0; for (uint i = 0; i < task_json["task_star"].size(); ++i) { rand_base += int(task_json["task_star"][i][0u].asDouble() * 100); if (rand_value < rand_base) { task_info->__task_star = i + 1; break; } } return 0; } int MapLogicTasker::init_task_object(TaskInfo *task_info, const Json::Value &task_json) { int serial_type = TASK_SERIAL_VISIBLE; if (task_info->is_acceptable()) { serial_type = TASK_SERIAL_ACCEPTABLE; } this->init_task_condition(task_info, task_json); this->init_task_star(task_info, task_json); task_info->__task_imp = this->pop_task_imp(task_info->__game_type); if (task_info->__task_imp == 0) return -1; if (this->task_map_.insert(TaskMap::value_type(task_info->__task_id, task_info)).second == false) return -1; this->record_serial(task_info->__task_id, serial_type); if (task_json["before_accept"]["auto_accept"].asInt() == 1 && this->process_accept(task_info->__task_id, true) == 0) { this->record_serial(task_info->__task_id, TASK_SERIAL_ACCEPTED); } return 0; } TaskImplement *MapLogicTasker::pop_task_imp(const int game_type) { TaskImplement *task_imp = 0; if (game_type == TaskInfo::TASK_GTYPE_MAINLINE || game_type == TaskInfo::TASK_GTYPE_BRANCH) { task_imp = MAP_MONITOR->task_imp_pool()->pop(); if (task_imp != 0) task_imp->set_tasker(this); } if (game_type == TaskInfo::TASK_GTYPE_ROUTINE || game_type == TaskInfo::TASK_GTYPE_OFFER_ROUTINE || game_type == TaskInfo::TASK_GTYPE_LEAGUE_ROUTINE) { TaskRoutineImp *routine_imp = MAP_MONITOR->task_routine_imp_pool()->pop(); task_imp = routine_imp; if (task_imp != 0) task_imp->set_tasker(this); } // if (game_type == TaskInfo::TASK_GTYPE_TRIAL) // { // TaskTrialImp *trial_imp = MAP_MONITOR->task_trial_imp_pool()->pop(); // task_imp = trial_imp; // if (task_imp != 0) // task_imp->set_tasker(this); // } return task_imp; } int MapLogicTasker::task_branch_update(Message *msg) { MSG_DYNAMIC_CAST_RETURN(Proto31400023 *, request, -1); return this->task_listen_branch(request->id(), request->num()); } int MapLogicTasker::accept_branch_request_info(int type) { MapLogicPlayer* player = this->task_player(); if ((type >= GameEnum::BRANCH_FB_BEGIN && type <= GameEnum::BRANCH_FB_END) || type == GameEnum::BRANCH_EXP_FB || type == GameEnum::BRANCH_LEGEND_TOP) { Proto30400026 info; info.set_id(type); info.set_num(0); player->send_to_map_thread(info); } else if (type == GameEnum::BRANCH_EQUIP) { GamePackage* package = player->find_package(GameEnum::INDEX_EQUIP); PackageItem* item = package->find_by_index(0); JUDGE_RETURN(item != NULL, -1); this->task_listen_branch(type, item->__equipment.strengthen_level_); } else if (type == GameEnum::BRANCH_FIRST_RECHARGE) { JUDGE_RETURN(player->recharge_detail().__recharge_money > 0, -1); this->task_listen_branch(type, 1); } else if (type == GameEnum::BRANCH_LEAGUE) { JUDGE_RETURN(player->role_detail().__league_id != 0, -1); this->task_listen_branch(type, 1); } else if (type == GameEnum::BRANCH_LEVEL) { this->task_listen_branch(type, player->role_level()); } else if (type == GameEnum::BRANCH_WEDDING) { JUDGE_RETURN(player->role_detail().__partner_id > 0, -1); this->task_listen_branch(type, 1); } return 0; } int MapLogicTasker::task_accept(Message *msg) { MSG_DYNAMIC_CAST_RETURN(Proto11400326 *, request, -1); return this->task_accept(request->task_id()); } int MapLogicTasker::task_accept(int task_id) { MapLogicPlayer *player = this->task_player(); const Json::Value &task_json = CONFIG_INSTANCE->find_task(task_id); CONDITION_PLAYER_NOTIFY_RETURN(task_json.empty() == false, RETURN_TASK_ACCEPT, ERROR_CONFIG_NOT_EXIST); int npc_id = task_json["before_accept"]["npc"].asInt(); if (npc_id > 0 && npc_id != 1) { Proto11400326 request; request.set_task_id(task_id); return this->is_nearby_npc(CLIENT_TASK_ACCEPT, &request, npc_id); } else { int ret = this->process_accept(task_id); CONDITION_PLAYER_NOTIFY_RETURN(ret == 0, RETURN_TASK_ACCEPT, ret); this->record_serial(task_id, TASK_SERIAL_ACCEPTED); FINER_PLAYER_PROCESS_NOTIFY(RETURN_TASK_ACCEPT); } } int MapLogicTasker::task_abandon(Message *msg) { DYNAMIC_CAST_RETURN(Proto11400327 *, request, msg, -1); MapLogicPlayer *player = this->task_player(); MSG_DEBUG("abandon task %s %d %d", player->name(), player->role_id(), request->task_id()); int ret = this->process_abandon(request->task_id()); CONDITION_PLAYER_NOTIFY_RETURN(ret == 0, RETURN_TASK_ABANDON, ret); this->record_serial(request->task_id(), TASK_SERIAL_ABANDON); return player->respond_to_client(RETURN_TASK_ABANDON); } int MapLogicTasker::task_submit(Message *msg, bool test) { MapLogicPlayer *player = this->task_player(); MSG_DYNAMIC_CAST_RETURN(Proto11400328 *, request, -1); int task_id = request->task_id(); int is_double = request->is_double(); MSG_DEBUG("submit task %s %d %d %d", player->name(), player->role_id(), task_id, is_double); CONDITION_PLAYER_NOTIFY_RETURN(request->task_id() > 0, RETURN_TASK_SUBMIT, ERROR_CLIENT_OPERATE); const Json::Value &task_json = CONFIG_INSTANCE->find_task(request->task_id()); CONDITION_PLAYER_NOTIFY_RETURN(task_json.empty() == false, RETURN_TASK_SUBMIT, ERROR_CONFIG_NOT_EXIST); int npc_id = task_json["finish"]["npc"].asInt(); if (test == false && npc_id > 0 && npc_id != 1) { return this->is_nearby_npc(CLIENT_TASK_SUBMIT, msg, npc_id); } int ret = this->process_submit(task_id, is_double, test); CONDITION_PLAYER_NOTIFY_RETURN_B(ret == 0, RETURN_TASK_SUBMIT, ret, ERROR_TASK_ID); this->record_serial(request->task_id(), TASK_SERIAL_SUBMIT); player->cache_tick().update_cache(MapLogicPlayer::CACHE_TASK, true); FINER_PLAYER_PROCESS_NOTIFY(RETURN_TASK_SUBMIT); } int MapLogicTasker::task_talk(Message *msg) { MSG_DYNAMIC_CAST_RETURN(Proto11400331 *, request, -1); MapLogicPlayer *player = this->task_player(); MSG_DEBUG("talk task %s %d %d", player->name(), player->role_id(), request->task_id()); int ret = this->process_talk(request->task_id()); CONDITION_PLAYER_NOTIFY_RETURN(ret == 0, RETURN_TASK_TALK, ret); return player->respond_to_client(RETURN_TASK_TALK); } int MapLogicTasker::task_get_list(Message *msg) // 获取任务列表 { if (this->task_map_.size() <= 0 && this->lastest_main_task_id_ > 0) { // 没有主线任务时显示最后一次任务后的相关提示 Proto81400107 respond; respond.set_lastest_task_id(this->lastest_main_task_id_); this->task_player()->respond_to_client(ACTIVE_LASTEST_MAIN_TASK, &respond); } Proto51400325 respond; respond.set_is_finish_guide(this->is_finish_guide_task()); for (TaskMap::iterator iter = this->task_map_.begin(); iter != this->task_map_.end(); ++iter) { TaskInfo* task_info = iter->second; if (task_info->is_finish() == false && task_info->is_accepted() == false && task_info->is_acceptable() == false && task_info->is_visible() == false) continue; ProtoTaskInfo *proto_task_info = respond.add_task_list(); this->serail_task_info(task_info, proto_task_info); } for (IntSet::iterator iter = this->finish_task_.begin(); iter != this->finish_task_.end(); ++iter) { respond.add_task_finish(*iter); } return this->task_player()->respond_to_client(RETURN_TASK_TRACK_LIST, &respond); } int MapLogicTasker::task_npc_list(Message *msg) // 获取npc列表 { DYNAMIC_CAST_RETURN(Proto11400329 *, request, msg, -1); MapLogicPlayer *player = this->task_player(); const BIntSet &task_set = CONFIG_INSTANCE->npc_task_list(request->npc_id()); Proto51400329 respond; TaskInfo *task_info = 0; for (BIntSet::iterator iter = task_set.begin(); iter != task_set.end(); ++iter) { if ((task_info = this->find_task(*iter)) == 0) continue; if (task_info->is_finish() == false && task_info->is_accepted() == false && task_info->is_acceptable() == false && task_info->is_visible() == false) continue; const Json::Value &task_json = CONFIG_INSTANCE->find_task(*iter); int before_npc = task_json["before_accept"]["npc"].asInt(), accepted_npc = task_json["after_accept"]["npc"].asInt(), finish_npc = task_json["finish"]["npc"].asInt(); bool is_check_true = false; if (is_check_true == false && before_npc == request->npc_id() && before_npc > 0) { if (task_info->is_acceptable() == true) is_check_true = true; } if (is_check_true == false && accepted_npc == request->npc_id() && accepted_npc > 0) { if (task_info->is_accepted() == true) is_check_true = true; } if (is_check_true == false && finish_npc == request->npc_id() && finish_npc > 0) { if (task_info->is_finish() == true) is_check_true = true; } if (is_check_true == false) continue; ProtoTaskInfo *proto_task_info = respond.add_task_list(); this->serail_task_info(task_info, proto_task_info); } return player->respond_to_client(RETURN_TASK_NPC_LIST, &respond); } int MapLogicTasker::task_fast_finish(Message *msg) // 快速完成任务 { MSG_DYNAMIC_CAST_RETURN(Proto11400330 *, request, -1); MapLogicPlayer *player = this->task_player(); int ret = this->process_fast_finish(request->task_id()); CONDITION_PLAYER_NOTIFY_RETURN(ret == 0, RETURN_TASK_FAST_FINISH, ret); return player->respond_to_client(RETURN_TASK_FAST_FINISH); } int MapLogicTasker::task_after_check_npc(Message *msg) { MSG_DYNAMIC_CAST_RETURN(Proto31400231 *, request, -1); int serial_type = 0, task_id = 0; MapLogicPlayer *player = this->task_player(); int recogn = request->recogn(); switch (recogn) { case CLIENT_TASK_ACCEPT: { Proto11400326 sub_request; sub_request.ParsePartialFromString(request->msg_body()); int ret = this->process_accept(sub_request.task_id()); JUDGE_RETURN(ret == 0, -1); serial_type = TASK_SERIAL_ACCEPTED; task_id = sub_request.task_id(); player->respond_to_client(RETURN_TASK_ACCEPT); break; } case CLIENT_TASK_ABANDON: { Proto11400327 sub_request; sub_request.ParsePartialFromString(request->msg_body()); int ret = this->process_abandon(sub_request.task_id()); CONDITION_PLAYER_NOTIFY_RETURN(ret == 0, RETURN_TASK_ABANDON, ret); serial_type = TASK_SERIAL_ABANDON; task_id = sub_request.task_id(); player->respond_to_client(RETURN_TASK_ABANDON); break; } case CLIENT_TASK_SUBMIT: { Proto11400328 sub_request; sub_request.ParsePartialFromString(request->msg_body()); int ret = this->process_submit(sub_request.task_id(), sub_request.is_double()); CONDITION_PLAYER_NOTIFY_RETURN_B(ret == 0, RETURN_TASK_SUBMIT, ret, ERROR_TASK_ID); serial_type = TASK_SERIAL_SUBMIT; task_id = sub_request.task_id(); player->respond_to_client(RETURN_TASK_SUBMIT); break; } default: { MSG_USER("after check npc %d", recogn); return -1; } } this->record_serial(task_id, serial_type); player->cache_tick().update_cache(MapLogicPlayer::CACHE_TASK, true); return 0; } bool MapLogicTasker::is_task_submited(const int task_id) { if (this->task_submited_once_.find(task_id) != this->task_submited_once_.end()) return true; return false; } bool MapLogicTasker::is_nearby_npc(const int recogn, Message *msg, const int npc_id) { Proto31400231 request; request.set_npc_id(npc_id); request.set_recogn(recogn); if (msg != 0) msg->SerializePartialToString(request.mutable_msg_body()); return MAP_MONITOR->process_inner_map_request(this->task_player()->role_id(), request); } int MapLogicTasker::bind_task(const int task_id, TaskInfo *info) { TaskMap::iterator iter = this->task_map_.find(task_id); if (iter != this->task_map_.end()) return -1; if (this->task_map_.insert(TaskMap::value_type(task_id, info)).second == true) return 0; return -1; } int MapLogicTasker::unbind_task(const int task_id) { return this->task_map_.erase(task_id); } TaskInfo *MapLogicTasker::find_task(const int task_id) { JUDGE_RETURN(this->task_map_.count(task_id) > 0, NULL); return this->task_map_[task_id]; } MapLogicTasker::TaskMap &MapLogicTasker::task_map(void) { return this->task_map_; } MapLogicTasker::TaskSet &MapLogicTasker::task_accepted_lvl_set(void) { return this->task_accepted_lvl_; } MapLogicTasker::TaskSet &MapLogicTasker::task_accepted_monster_set(void) { return this->task_accepted_monster_; } MapLogicTasker::TaskSet &MapLogicTasker::task_accepted_collect_set(void) { return this->task_accepted_collect_; } MapLogicTasker::TaskSet &MapLogicTasker::task_accepted_attend_set(void) { return this->task_accepted_attend_; } MapLogicTasker::TaskSet &MapLogicTasker::task_accepted_scene_set(void) { return this->task_accepted_scene_; } MapLogicTasker::TaskSet &MapLogicTasker::task_accepted_package_set(void) { return this->task_accepted_package_; } MapLogicTasker::TaskSet &MapLogicTasker::task_accepted_branch_set(void) { return this->task_accepted_branch_; } MapLogicTasker::TaskIdSet &MapLogicTasker::task_submited_once_set(void) { return this->task_submited_once_; } MapLogicTasker::ItemTaskMap &MapLogicTasker::task_listen_item_map(void) { return this->task_listen_item_; } int MapLogicTasker::init_task_listen_item(TaskInfo *task_info) { const Json::Value &task_json = CONFIG_INSTANCE->find_task(task_info->__task_id); const Json::Value &cond_json = task_json["exec"]["condition"]; for (uint i = 0; i < cond_json.size(); ++i) { if (cond_json[i]["type"].asString() != "package") continue; int item_id = cond_json[i]["id"][0u].asInt(); this->task_listen_item_[item_id].insert(task_info->__task_id); } return 0; } int MapLogicTasker::erase_task_listen_item(TaskInfo *task_info, const bool is_finish) { const Json::Value &task_json = CONFIG_INSTANCE->find_task(task_info->__task_id); const Json::Value &cond_json = task_json["exec"]["condition"]; for (uint i = 0; i < cond_json.size(); ++i) { if (cond_json[i]["type"].asString() != "package") continue; int item_id = cond_json[i]["id"][0u].asInt(); if (is_finish == true && cond_json[i]["is_remove"].asInt() == 1) { if (cond_json[i].isMember("bind") == false || cond_json[i]["bind"].asInt() == -1) { this->task_player()->pack_remove(SerialObj(ITEM_TASK_REMOVE, task_info->__task_id), item_id, cond_json[i]["value"].asInt()); } else if (cond_json[i]["bind"].asInt() == 0) { int item_num = cond_json[i]["value"].asInt(); while (item_num > 0) { PackageItem *item = this->task_player()->pack_find_by_unbind_id(item_id); if (item == 0) break; if (item->__amount > item_num) { this->task_player()->pack_remove(SerialObj(ITEM_TASK_REMOVE, task_info->__task_id), item, item_num); item_num = 0; } else { item_num -= item->__amount; this->task_player()->pack_remove(SerialObj(ITEM_TASK_REMOVE, task_info->__task_id), item, item->__amount); } } } else { int item_num = cond_json[i]["value"].asInt(); while (item_num > 0) { PackageItem *item = this->task_player()->pack_find_by_bind_id(item_id); if (item == 0) { item = this->task_player()->pack_find_by_unbind_id(item_id); if (item == 0) break; } if (item->__amount > item_num) { this->task_player()->pack_remove(SerialObj(ITEM_TASK_REMOVE, task_info->__task_id), item, item_num); item_num = 0; } else { item_num -= item->__amount; this->task_player()->pack_remove(SerialObj(ITEM_TASK_REMOVE, task_info->__task_id), item, item->__amount); } } } } if (this->task_listen_item_.find(item_id) == false) continue; TaskIdSet &id_set = this->task_listen_item_[item_id]; id_set.erase(task_info->__task_id); if (id_set.size() <= 0) this->task_listen_item_.unbind(item_id); } return 0; } bool MapLogicTasker::is_task_listen_item(const int item_id) { return this->task_listen_item_.find(item_id); } int MapLogicTasker::task_listen_lvl_up(int target_level) { TaskInfo *task_info = 0; std::vector<TaskInfo *> task_vc; for (TaskSet::iterator iter = this->task_accepted_lvl_.begin(); iter != this->task_accepted_lvl_.end(); ++iter) { task_info = *iter; if (task_info->is_accepted() == false) continue; if (task_info->is_logic_level_up() == false) continue; task_vc.push_back(task_info); } for (std::vector<TaskInfo *>::iterator iter = task_vc.begin(); iter != task_vc.end(); ++iter) { task_info = *iter; task_info->task_imp()->process_listen_lvl_up(task_info, target_level); } MapLogicPlayer* player = this->task_player(); if (GameCommon::is_normal_scene(player->scene_id())) { this->check_current_version_open_ui(target_level, GameEnum::CHECK_UIT_LEVELUP); } this->task_construct_main(true); this->task_construct_branch(true); // this->task_listen_branch(GameEnum::BRANCH_LEVEL, player->role_level()); /* if (this->task_player()->role_level() >= CONFIG_INSTANCE->task_setting()["trial_level"].asInt()) this->notify_virtual_trial_task_for_novice(); */ if (this->task_player()->role_level() >= CONFIG_INSTANCE->task_setting()["daliy_routine_start_level"].asInt()) this->new_task_construct_routine(true); if (this->task_player()->role_level() >= CONFIG_INSTANCE->task_setting()["offer_routine_start_level"].asInt()) this->offer_task_construct_routine(true); if (this->task_player()->role_level() >= CONFIG_INSTANCE->task_setting()["league_routine_start_level"].asInt() && this->task_player()->role_detail().__league_id != 0) this->league_task_construct_routine(true); return 0; } int MapLogicTasker::task_listen_branch(const int id, const int num) { TaskInfo *task_info = 0; std::vector<TaskInfo *> task_vc; for (TaskSet::iterator iter = this->task_accepted_branch_.begin(); iter != this->task_accepted_branch_.end(); ++iter) { task_info = *iter; if (task_info->is_accepted() == false || task_info->is_logic_branch() == false) continue; task_vc.push_back(task_info); } for (std::vector<TaskInfo *>::iterator iter = task_vc.begin(); iter != task_vc.end(); ++iter) { task_info = *iter; task_info->task_imp()->process_listen_branch(task_info, id, num); } return 0; } int MapLogicTasker::task_listen_kill_monster(const int sort, const int num) { TaskInfo *task_info = 0; std::vector<TaskInfo *> task_vc; for (TaskSet::iterator iter = this->task_accepted_monster_.begin(); iter != this->task_accepted_monster_.end(); ++iter) { task_info = *iter; if (task_info->is_accepted() == false) continue; if (task_info->is_logic_kill_monster() == false && task_info->is_logic_lvl_monster() == false && task_info->is_logic_kill_boss() == false) continue; task_vc.push_back(task_info); } for (std::vector<TaskInfo *>::iterator iter = task_vc.begin(); iter != task_vc.end(); ++iter) { task_info = *iter; task_info->task_imp()->process_listen_kill_monster(task_info, sort, num); } return 0; } int MapLogicTasker::task_listen_collect_item(const int id, const int num, const int bind) { TaskInfo *task_info = 0; std::vector<TaskInfo *> task_vc; for (TaskSet::iterator iter = this->task_accepted_collect_.begin(); iter != this->task_accepted_collect_.end(); ++iter) { task_info = *iter; if (task_info->is_accepted() == false) continue; if (task_info->is_logic_collect_item() == false && task_info->is_logic_collect_any() == false) continue; task_vc.push_back(task_info); } for (std::vector<TaskInfo *>::iterator iter = task_vc.begin(); iter != task_vc.end(); ++iter) { task_info = *iter; task_info->task_imp()->process_listen_collect_item(task_info, id, num, bind); } return 0; } int MapLogicTasker::task_listen_attend(const int type, const int sub_type, const int inc_value) { int value = inc_value; // if (type == GameEnum::ACTIVITY_LEAGUE_DONATE) // { // this->refresh_daily_league_contri(); // if (inc_value > 0) // this->lcontri_day_ += inc_value; // value = this->lcontri_day_; // } TaskInfoVec task_vc; for (TaskSet::iterator iter = this->task_accepted_attend_.begin(); iter != this->task_accepted_attend_.end(); ++iter) { TaskInfo *task_info = *iter; if (task_info->is_accepted() == false) continue; if (task_info->is_logic_attend() == false) continue; task_vc.push_back(task_info); } for (TaskInfoVec::iterator iter = task_vc.begin(); iter != task_vc.end(); ++iter) { TaskInfo *task_info = *iter; task_info->task_imp()->process_listen_attend(task_info, type, sub_type, value); } return 0; } int MapLogicTasker::task_listen_package_item(const int id, const int num, const int bind) { TaskInfoVec task_vc; for (TaskSet::iterator iter = this->task_accepted_package_.begin(); iter != this->task_accepted_package_.end(); ++iter) { TaskInfo *task_info = *iter; if (task_info->is_accepted() == false) continue; if (task_info->is_logic_package() == false) continue; task_vc.push_back(task_info); } for (TaskInfoVec::iterator iter = task_vc.begin(); iter != task_vc.end(); ++iter) { TaskInfo *task_info = *iter; task_info->task_imp()->process_listen_package_item(task_info, id, num, bind); } return 0; } int MapLogicTasker::task_listen_enter_special_scene(int scene_id) { TaskInfoVec task_vc; for (TaskSet::iterator iter = this->task_accepted_scene_.begin(); iter != this->task_accepted_scene_.end(); ++iter) { TaskInfo* task_info = *iter; JUDGE_CONTINUE(task_info->is_accepted() == true); JUDGE_CONTINUE(task_info->is_logic_scene() == true); task_vc.push_back(task_info); } for (TaskInfoVec::iterator iter = task_vc.begin(); iter != task_vc.end(); ++iter) { TaskInfo* task_info = *iter; task_info->task_imp()->process_listen_enter_special_scene(task_info,scene_id); } return 0; } int MapLogicTasker::process_accept(int task_id, bool is_init) { // if (this->task_type(task_id) == TaskInfo::TASK_GTYPE_TRIAL) // { // return this->process_accept_trial(task_id, is_init); // } TaskInfo *task_info = this->find_task(task_id); JUDGE_RETURN(task_info != 0, ERROR_TASK_ID); JUDGE_RETURN(task_info->is_acceptable() == true, ERROR_TASK_STATUS); if (task_info->is_routine_task()) { this->is_second_routine_[task_info->__game_type] = 1; } int ret = task_info->task_imp()->process_accept(task_info, is_init); JUDGE_RETURN(ret == 0, ret); return 0; } int MapLogicTasker::process_abandon(const int task_id) { TaskInfo *task_info = this->find_task(task_id); JUDGE_RETURN(task_info != 0, ERROR_TASK_ID); JUDGE_RETURN(task_info->is_accepted() == true, ERROR_TASK_STATUS); JUDGE_RETURN(task_info->is_main_task() == false, ERROR_TASK_ABANDON); const Json::Value &task_json = CONFIG_INSTANCE->find_task(task_id); JUDGE_RETURN(task_json != Json::Value::null, ERROR_CONFIG_NOT_EXIST); JUDGE_RETURN(task_json["exec"]["abandon"].asInt() == 1, ERROR_TASK_ABANDON); return task_info->task_imp()->process_abandon(task_info); } int MapLogicTasker::process_submit(const int task_id, const int is_double, bool test) { TaskInfo *task_info = this->find_task(task_id); JUDGE_RETURN(task_info != 0, ERROR_TASK_ID); if (test == false) { JUDGE_RETURN(task_info->is_finish() == true, ERROR_TASK_STATUS); } int ret = task_info->task_imp()->process_submit(task_info, is_double); JUDGE_RETURN(ret == 0, ret); return 0; } int MapLogicTasker::process_fast_finish(const int task_id) { TaskInfo *task_info = this->find_task(task_id); JUDGE_RETURN(task_info != 0, ERROR_TASK_ID); JUDGE_RETURN(task_info->is_finish() == false, ERROR_TASK_STATUS); if (task_info->is_routine_task()) { this->is_second_routine_[task_info->__game_type] = 1; } return task_info->task_imp()->process_fast_finish(task_info); } int MapLogicTasker::process_talk(const int task_id) { TaskInfo *task_info = this->find_task(task_id); JUDGE_RETURN(task_info != 0, ERROR_TASK_ID); JUDGE_RETURN(task_info->is_logic_patrol() == true && task_info->is_accepted() == true, ERROR_TASK_STATUS); task_info->set_task_status(TaskInfo::TASK_STATUS_FINISH); this->notify_task_update(task_info); return 0; } int MapLogicTasker::serail_task_info(TaskInfo *task_info, ProtoTaskInfo *proto_task_info) { task_info->serialize(proto_task_info); if (task_info->is_routine_task()) { proto_task_info->set_is_first_routine((this->is_second_routine_[task_info->__game_type] == 0)); proto_task_info->set_is_routine(this->is_routine_task_[task_info->__game_type]); proto_task_info->set_routine_index(this->routine_task_index_[task_info->__game_type]); proto_task_info->set_routine_total(this->routine_total_num_[task_info->__game_type]); } return 0; } int MapLogicTasker::notify_task_add(TaskInfo *task_info) { int task_status = task_info->task_status(); JUDGE_RETURN(task_status > 0, -1); const int TASK_ADD_CMD = 1/*, TASK_DEL_CMD = 2, TASK_UPDATE_CMD = 3*/; if (task_info->is_routine_task()) { return this->notify_routine_task_status(TASK_ADD_CMD, task_info); } Proto81400104 respond; respond.set_cmd(TASK_ADD_CMD); respond.set_is_finish_guide(this->is_finish_guide_task()); ProtoTaskInfo *ptask_info = respond.mutable_task_info(); this->serail_task_info(task_info, ptask_info); return this->task_player()->respond_to_client(ACTIVE_TASK_UPDATE, &respond); } int MapLogicTasker::notify_task_del(TaskInfo *task_info) { const int /*TASK_ADD_CMD = 1, */TASK_DEL_CMD = 2/*, TASK_UPDATE_CMD = 3*/; if (task_info->is_routine_task()) { return this->notify_routine_task_status(TASK_DEL_CMD, task_info); } Proto81400104 respond; respond.set_cmd(TASK_DEL_CMD); respond.set_is_finish_guide(this->is_finish_guide_task()); ProtoTaskInfo *ptask_info = respond.mutable_task_info(); ptask_info->set_task_id(task_info->__task_id); ptask_info->set_type(task_info->__game_type); ptask_info->set_status(task_info->task_status()); return this->task_player()->respond_to_client(ACTIVE_TASK_UPDATE, &respond); } int MapLogicTasker::notify_task_update(TaskInfo *task_info) { const int /*TASK_ADD_CMD = 1, TASK_DEL_CMD = 2, */TASK_UPDATE_CMD = 3; if (task_info->is_routine_task()) { return this->notify_routine_task_status(TASK_UPDATE_CMD, task_info); } Proto81400104 respond; respond.set_cmd(TASK_UPDATE_CMD); respond.set_is_finish_guide(this->is_finish_guide_task()); ProtoTaskInfo *ptask_info = respond.mutable_task_info(); this->serail_task_info(task_info, ptask_info); return this->task_player()->respond_to_client(ACTIVE_TASK_UPDATE, &respond); } int MapLogicTasker::notify_routine_task_status(const int cmd, TaskInfo *task_info) { int status = task_info->task_status(); TaskConditon *task_cond_obj = task_info->task_condition(0); int total_size = this->routine_total_num_[task_info->__game_type], cur_index = this->routine_task_index_[task_info->__game_type]; Proto81400203 respond; respond.set_cmd(cmd); respond.set_task_id(task_info->__task_id); respond.set_type(task_info->__game_type); respond.set_status(status); respond.set_is_first_routine((this->is_second_routine_[task_info->__game_type] == 0)); respond.set_total_routine_size(total_size); respond.set_routine_task_index(cur_index); if (task_cond_obj != 0) { respond.set_cond_type(task_cond_obj->__type); respond.set_cond_index(0); respond.set_cond_id(task_cond_obj->__cond_id); respond.set_cur_value(task_cond_obj->__current_value); respond.set_final_value(task_cond_obj->__final_value); respond.set_kill_type(task_cond_obj->__kill_type); respond.set_range_level(task_cond_obj->__range_level); } return this->task_player()->respond_to_client(ACTIVE_TASK_ROUTINE_UPDATE, &respond); } int MapLogicTasker::serialize_task(Message *msg) { MSG_DYNAMIC_CAST_RETURN(Proto31400108 *, request, -1); for (TaskMap::iterator iter = this->task_map_.begin(); iter != this->task_map_.end(); ++iter) { TaskInfo *task_info = iter->second; task_info->serialize(request->add_task_list()); } for (TaskIdSet::iterator iter = this->task_submited_once_.begin(); iter != this->task_submited_once_.end(); ++iter) { request->add_submited_task(*iter); } for (IntSet::iterator iter = this->finish_task_.begin(); iter != this->finish_task_.end(); ++iter) { request->add_finish_task(*iter); } // request->set_is_first_rename(this->task_player()->role_detail().__is_first_rename); request->set_novice_step(this->novice_step()); request->set_latest_main_task(this->lastest_main_task_id_); for (int i = 0; i <= GameEnum::UIOPEN_STEP_SIZE; ++i) { request->add_uiopen_step(this->uiopen_step_[i]); } for (int i = TaskInfo::TASK_GTYPE_ROUTINE; i < TaskInfo::TASK_GTYPE_END; ++i) { if (i == TaskInfo::TASK_GTYPE_ROUTINE || i == TaskInfo::TASK_GTYPE_OFFER_ROUTINE || i == TaskInfo::TASK_GTYPE_LEAGUE_ROUTINE) { request->add_is_finish_all_routine(this->is_finish_all_routine_[i]); request->add_is_second_routine(this->is_second_routine_[i]); request->add_routine_index(this->routine_task_index_[i]); request->add_is_routine_task(this->is_routine_task_[i]); request->add_total_num(this->routine_total_num_[i]); } } request->set_routine_refresh_tick(this->routine_refresh_tick_.sec()); request->set_lcontri_tick(this->lcontri_day_tick_.sec()); request->set_lcontri_day(this->lcontri_day_); request->set_ui_version(this->ui_version_); for (TaskIdSet::iterator iter = this->routine_consume_history_.begin(); iter != this->routine_consume_history_.end(); ++iter) { request->add_routine_consume_history(*iter); } // for (OpenUiSet::iterator iter = this->open_ui_set().begin(); // iter != this->open_ui_set().end(); ++iter) // { // request->add_open_ui_list(*iter); // } return 0; } int MapLogicTasker::unserialize_task(Message *proto) { DYNAMIC_CAST_RETURN(Proto31400108 *, request, proto, -1); int task_info_size = request->task_list_size(); for (int i = 0; i < task_info_size; ++i) { const ProtoInnerTaskInfo &inner_task_info = request->task_list(i); TaskInfo *task_info = this->task_player()->monitor()->task_info_pool()->pop(); task_info->__task_id = inner_task_info.task_id(); if (this->task_map_.insert(TaskMap::value_type(task_info->__task_id, task_info)).second == false) { this->task_player()->monitor()->task_info_pool()->push(task_info); continue; } task_info->unserialize(inner_task_info); task_info->__task_imp = this->pop_task_imp(task_info->__game_type); if (task_info->is_logic_level_up()) this->task_accepted_lvl_set().insert(task_info); if (task_info->is_logic_kill_monster() || task_info->is_logic_lvl_monster() || task_info->is_logic_kill_boss()) this->task_accepted_monster_set().insert(task_info); if (task_info->is_logic_collect_item() || task_info->is_logic_collect_any()) this->task_accepted_collect_set().insert(task_info); if (task_info->is_logic_attend()) this->task_accepted_attend_set().insert(task_info); if (task_info->is_logic_scene()) this->task_accepted_scene_set().insert(task_info); if (task_info->is_logic_package()) { this->init_task_listen_item(task_info); this->task_accepted_package_set().insert(task_info); } if (task_info->is_branch_task()) { this->task_accepted_branch_set().insert(task_info); } } for (int i = 0; i < request->submited_task_size(); ++i) { this->task_submited_once_.insert(request->submited_task(i)); } for (int i = 0; i < request->finish_task_size(); ++i) { this->insert_finish_task(request->finish_task(i)); } // this->task_player()->role_detail().__is_first_rename = request->is_first_rename(); this->novice_step_ = request->novice_step(); this->lastest_main_task_id_ = request->latest_main_task(); for (int i = 0; i < request->uiopen_step_size(); ++i) { this->uiopen_step_[i] = request->uiopen_step(i); } for (int i = 0; i < request->routine_index_size(); ++i) { int type = 3; switch (i) { case 0 : type = TaskInfo::TASK_GTYPE_ROUTINE; break; case 1 : type = TaskInfo::TASK_GTYPE_OFFER_ROUTINE; break; case 2 : type = TaskInfo::TASK_GTYPE_LEAGUE_ROUTINE; break; default : type = TaskInfo::TASK_GTYPE_ROUTINE; } this->routine_task_index_[type] = request->routine_index(i); this->is_finish_all_routine_[type] = request->is_finish_all_routine(i); this->is_second_routine_[type] = request->is_second_routine(i); this->routine_total_num_[type] = request->total_num(i); this->is_routine_task_[type] = request->is_routine_task(i); } this->routine_refresh_tick_.sec(request->routine_refresh_tick()); this->lcontri_day_tick_.sec(request->lcontri_tick()); this->lcontri_day_ = request->lcontri_day(); this->ui_version_ = request->ui_version(); for (int i = 0; i < request->routine_consume_history_size(); ++i) this->routine_consume_history_.insert(request->routine_consume_history(i)); // for (int i = 0; i < request->open_ui_list_size(); ++i) // this->open_ui_set().insert(request->open_ui_list(i)); return 0; } int MapLogicTasker::notify_finished_task_set(void) { // MapLogicPlayer* player = this->task_player(); // if (GameCommon::is_normal_scene(player->scene_id())) // { // this->check_current_version_open_ui(player->role_level(), // GameEnum::CHECK_UIT_LEVELUP); // } // // Proto81400106 respond; // for (OpenUiSet::iterator iter = this->open_ui_set().begin(); // iter != this->open_ui_set().end(); ++iter) // { // respond.add_pass_ui(*iter); // } // // Proto31400602 inner_req; // inner_req.set_msg_body(respond.SerializeAsString()); // return player->send_to_map_thread(inner_req); return 0; } int MapLogicTasker::request_fetch_novice_step(void) { Proto51400333 respond; respond.set_step(this->novice_step_); return this->task_player()->respond_to_client(RETURN_FETCH_NOVICE_STEP, &respond); } int MapLogicTasker::request_set_novice_step(Message *msg) { DYNAMIC_CAST_RETURN(Proto11400334 *, request, msg, -1); this->novice_step_ = request->step(); return this->task_player()->respond_to_client(RETURN_SET_NOVICE_STEP); } int MapLogicTasker::novice_step(void) { return this->novice_step_; } void MapLogicTasker::set_novice_step(const int step) { this->novice_step_ = step; } int MapLogicTasker::latest_main_task(void) { return this->lastest_main_task_id_; } void MapLogicTasker::set_latest_main_task(const int id) { this->lastest_main_task_id_ = id; } int MapLogicTasker::lcontri_day_value(void) { return this->lcontri_day_; } MapLogicTasker::OpenUiSet &MapLogicTasker::open_ui_set(void) { return this->open_ui_set_; } int MapLogicTasker::ui_version(void) { return this->ui_version_; } int MapLogicTasker::request_fetch_uiopen_step(void) { Proto51400336 respond; for (int i = 0; i <= GameEnum::UIOPEN_STEP_SIZE; ++i) { respond.add_step(this->uiopen_step_[i]); } return this->task_player()->respond_to_client(RETURN_FETCH_UIOPEN_STEP, &respond); } int MapLogicTasker::request_set_uiopen_step(Message *msg) { MapLogicPlayer *player = this->task_player(); DYNAMIC_CAST_RETURN(Proto11400337 *, request, msg, -1); this->set_uiopen_step(request->step()); return player->respond_to_client(RETURN_SET_UIOPEN_STEP); } void MapLogicTasker::set_uiopen_step(const int step) { if (step < 0 || step > GameEnum::UIOPEN_STEP_SIZE) return; this->uiopen_step_[step] = 1; } int MapLogicTasker::start_script_wave_task_listen(int scene_id) { for (TaskMap::iterator iter = this->task_map_.begin(); iter != this->task_map_.end(); ++iter) { TaskInfo *task_info = iter->second; JUDGE_CONTINUE(task_info->is_accepted() == true); JUDGE_CONTINUE(task_info->is_logic_script_wave() == true); JUDGE_CONTINUE(task_info->__condition_list.empty() == false); TaskConditon* cond = task_info->__condition_list[0]; JUDGE_CONTINUE(cond->__cond_id == scene_id) Proto31400601 req; req.set_script_sort(scene_id); this->task_player()->send_to_map_thread(req); } return 0; } int MapLogicTasker::check_script_wave_task_finish(Message *msg) { MSG_DYNAMIC_CAST_RETURN(Proto31400601*, request, -1); int scene_id = request->script_sort(); int passed = request->pass_chapter(); for (TaskMap::iterator iter = this->task_map_.begin(); iter != this->task_map_.end(); ++iter) { TaskInfo *task_info = iter->second; JUDGE_CONTINUE(task_info->is_accepted() == true); JUDGE_CONTINUE(task_info->is_logic_script_wave() == true); JUDGE_CONTINUE(task_info->__condition_list.empty() == false); TaskConditon* cond = task_info->__condition_list[0]; JUDGE_CONTINUE(cond->__cond_id == scene_id); JUDGE_CONTINUE(passed >= cond->__final_value); task_info->task_imp()->process_finish(task_info); this->task_player()->request_force_exit_system(scene_id); } return 0; } int MapLogicTasker::test_special_task(int task_id) { const Json::Value &task_json = CONFIG_INSTANCE->find_task(task_id); JUDGE_RETURN(task_json != Json::Value::null, -1); this->task_submited_once_.clear(); this->task_accepted_lvl_.clear(); this->task_accepted_monster_.clear(); this->task_accepted_collect_.clear(); this->task_accepted_attend_.clear(); this->task_accepted_package_.clear(); this->task_accepted_scene_.clear(); this->task_listen_item_.clear(); this->task_accepted_branch_.clear(); int prev_task_id = task_json["precondition"].asInt(); this->lastest_main_task_id_ = prev_task_id; for (TaskMap::iterator iter = this->task_map_.begin(); iter != this->task_map_.end(); ++iter) { this->notify_task_del(iter->second); MAP_MONITOR->task_info_pool()->push(iter->second); } this->task_map_.clear(); while (prev_task_id > 0) { this->task_submited_once_.insert(prev_task_id); const Json::Value &prev_task_json = CONFIG_INSTANCE->find_task(prev_task_id); prev_task_id = prev_task_json["precondition"].asInt(); } this->insert_task(task_id, task_json); return 0; } int MapLogicTasker::test_task_open_ui(int task_id) { if (task_id != 0) { this->check_current_version_open_ui(task_id, GameEnum::CHECK_UIT_SUBMIT_TASK); return 0; } for (BStrIntMap::iterator iter = CONFIG_INSTANCE->task_fun_open_map().begin(); iter != CONFIG_INSTANCE->task_fun_open_map().end(); ++iter) { this->check_current_version_open_ui(iter->second, GameEnum::CHECK_UIT_SUBMIT_TASK); } return 0; } int MapLogicTasker::fetch_routine_monster_id(int type, int range_level, int monster_id) { // range_level = this->task_player()->role_level(); const Json::Value& lvl_json = CONFIG_INSTANCE->role_level(0, range_level); JUDGE_RETURN(lvl_json != Json::Value::null, -1); switch(type) { case TaskInfo::TASK_GTYPE_ROUTINE: { string c_str = "daily_monster_list"; int size = (int)lvl_json[c_str].size(); JUDGE_RETURN(size > 0, 0); int rand_index = ::std::rand() % size; return lvl_json[c_str][rand_index].asInt(); } case TaskInfo::TASK_GTYPE_LEAGUE_ROUTINE: { string c_str = "league_monster_list"; int size = (int)lvl_json[c_str].size(); JUDGE_RETURN(size > 0, 0); int rand_index = ::std::rand() % size; return lvl_json[c_str][rand_index].asInt(); } case TaskInfo::TASK_GTYPE_OFFER_ROUTINE: { string c_str = "offer_monster_list"; int size = (int)lvl_json[c_str].size(); for (int i = 0; i < size; ++i) if (lvl_json[c_str][i].asInt() == monster_id) return 1; return 0; } } return 0; } void MapLogicTasker::refresh_routine_task(const Time_Value &nowtime, const bool notify/*= true*/) { JUDGE_RETURN(this->routine_refresh_tick_ <= nowtime, ;); this->routine_refresh_tick_ = next_day(0, 0, nowtime); this->clear_routine_task(notify, TaskInfo::TASK_GTYPE_LEAGUE_ROUTINE); this->clear_routine_task(notify, TaskInfo::TASK_GTYPE_OFFER_ROUTINE); this->clear_routine_task(notify); } int MapLogicTasker::open_league_task(Message* msg) { MSG_DYNAMIC_CAST_RETURN(Proto31400324 *, request, -1); this->task_player()->role_detail().__league_id = request->league_id(); this->league_task_construct_routine(true); this->task_listen_branch(GameEnum::BRANCH_LEAGUE, 1); return 0; } int MapLogicTasker::league_task_construct_routine(const bool notify_add) { JUDGE_RETURN(this->is_routine_task_[TaskInfo::TASK_GTYPE_LEAGUE_ROUTINE] == 0, 0); JUDGE_RETURN(this->is_finish_all_routine_[TaskInfo::TASK_GTYPE_LEAGUE_ROUTINE] == 0, 0); JUDGE_RETURN(this->is_finish_guide_task(), 0); //开放等级 int start_level = CONFIG_INSTANCE->task_setting()["league_routine_start_level"].asInt(); JUDGE_RETURN(this->task_player()->role_level() >= start_level, 0); JUDGE_RETURN(this->task_player()->role_detail().__league_id != 0, 0); this->clear_routine_task(true, TaskInfo::TASK_GTYPE_LEAGUE_ROUTINE); TaskIdSet t_consume_set; this->routine_task_index_[TaskInfo::TASK_GTYPE_LEAGUE_ROUTINE] = 0; int size = (int)this->task_list_json()["league_routine_list"].size(); this->routine_total_num_[TaskInfo::TASK_GTYPE_LEAGUE_ROUTINE] = size; int task_id = this->task_list_json()["league_routine_list"] [this->routine_task_index_[TaskInfo::TASK_GTYPE_LEAGUE_ROUTINE]].asInt(); // 插入第一个帮派日常任务 const Json::Value &task_json = CONFIG_INSTANCE->find_task(task_id); if (notify_add == true) this->insert_task(task_id, task_json); else this->init_task(task_id, task_json); this->is_routine_task_[TaskInfo::TASK_GTYPE_LEAGUE_ROUTINE] = 1; return 0; } int MapLogicTasker::offer_task_construct_routine(const bool notify_add) { JUDGE_RETURN(this->is_routine_task_ [TaskInfo::TASK_GTYPE_OFFER_ROUTINE]== 0, 0); JUDGE_RETURN(this->is_finish_all_routine_[TaskInfo::TASK_GTYPE_OFFER_ROUTINE] == 0, 0); JUDGE_RETURN(this->is_finish_guide_task(), 0); //开放等级 int start_level = CONFIG_INSTANCE->task_setting()["offer_routine_start_level"].asInt(); JUDGE_RETURN(this->task_player()->role_level() >= start_level, 0); JUDGE_RETURN(this->is_finish_all_routine_[TaskInfo::TASK_GTYPE_ROUTINE] == 1, 0); this->clear_routine_task(true, TaskInfo::TASK_GTYPE_OFFER_ROUTINE); TaskIdSet t_consume_set; this->routine_task_index_[TaskInfo::TASK_GTYPE_OFFER_ROUTINE] = 0; int size = (int)this->task_list_json()["offer_routine_list"].size(); if (size <= 0) return -1; this->routine_total_num_[TaskInfo::TASK_GTYPE_OFFER_ROUTINE] = size; int task_id = this->task_list_json()["offer_routine_list"] [this->routine_task_index_[TaskInfo::TASK_GTYPE_OFFER_ROUTINE]].asInt(); // 插入第一个悬赏日常任务 const Json::Value &task_json = CONFIG_INSTANCE->find_task(task_id); if (notify_add == true) this->insert_task(task_id, task_json); else this->init_task(task_id, task_json); this->is_routine_task_[TaskInfo::TASK_GTYPE_OFFER_ROUTINE] = 1; return 0; } int MapLogicTasker::new_task_construct_routine(const bool notify_add) { JUDGE_RETURN(this->is_routine_task_[TaskInfo::TASK_GTYPE_ROUTINE] == 0, 0); JUDGE_RETURN(this->is_finish_all_routine_[TaskInfo::TASK_GTYPE_ROUTINE] == 0, 0); JUDGE_RETURN(this->is_finish_guide_task(), 0); //开放等级 int start_level = CONFIG_INSTANCE->task_setting()["daliy_routine_start_level"].asInt(); JUDGE_RETURN(this->task_player()->role_level() >= start_level, 0); this->clear_routine_task(true); TaskIdSet t_consume_set; this->routine_task_index_[TaskInfo::TASK_GTYPE_ROUTINE] = 0; int size = (int)this->task_list_json()["daliy_routine_list"].size(); this->routine_total_num_[TaskInfo::TASK_GTYPE_ROUTINE] = size; int task_id = this->task_list_json()["daliy_routine_list"] [this->routine_task_index_[TaskInfo::TASK_GTYPE_ROUTINE]].asInt(); // 插入第一个日常任务 const Json::Value &task_json = CONFIG_INSTANCE->find_task(task_id); if (notify_add == true) this->insert_task(task_id, task_json); else this->init_task(task_id, task_json); this->is_routine_task_[TaskInfo::TASK_GTYPE_ROUTINE] = 1; return 0; } /* int MapLogicTasker::task_construct_routine(const bool notify_add) { JUDGE_RETURN(this->is_routine_task_ == 0, 0); //开放等级 int start_level = CONFIG_INSTANCE->task_setting()["daliy_routine_start_level"].asInt(); JUDGE_RETURN(this->task_player()->role_level() >= start_level, 0); this->clear_routine_task(true); this->notify_delete_virtual_routine_task(); MapLogicPlayer *player = this->task_player(); RoutineTaskVec t_liveness_vc, t_script_vc, t_arena_vc, t_consume_vc, t_other_vc, t_rand_vc, t_other_scene_vc; TaskIdSet t_consume_set; int level = this->task_player()->role_level(); const GameConfig::ConfigMap &routine_task_map = CONFIG_INSTANCE->routine_task_map(); for (GameConfig::ConfigMap::const_iterator iter = routine_task_map.begin(); iter != routine_task_map.end(); ++iter) { const Json::Value &task_json = *(iter->second); { const Json::Value &before_level_json = task_json["before_accept"]["level"]; if (level < before_level_json[0u].asInt()) continue; if (level < before_level_json[1u].asInt() || before_level_json[2u].asInt() < level) continue; } int task_sub_type = task_json["sub_type"].asInt(), task_belong_scene = task_json["exec"]["belong_scene"].asInt(); if (task_belong_scene > 0) { int jump_step = CONFIG_INSTANCE->scene_jump(player->scene_id(), task_belong_scene); if ((jump_step < 0 || jump_step > 3) && task_sub_type == TaskInfo::TASK_ST_ROUTINE_OTHER) { t_other_scene_vc.push_back(iter->first); continue; } } switch (task_sub_type) { case TaskInfo::TASK_ST_ROUTINE_LIVENESS: t_liveness_vc.push_back(iter->first); break; case TaskInfo::TASK_ST_ROUTINE_SCRIPT: t_script_vc.push_back(iter->first); break; case TaskInfo::TASK_ST_ROUTINE_ARENA: t_arena_vc.push_back(iter->first); break; case TaskInfo::TASK_ST_ROUTINE_CONSUME: t_consume_vc.push_back(iter->first); t_consume_set.insert(iter->first); break; case TaskInfo::TASK_ST_ROUTINE_OTHER: t_other_vc.push_back(iter->first); break; } } // 每种子类型任务至少取一个, 同一个任务当天不出现两次 IntSet selected_task_set; if (t_script_vc.size() > 0) { int index = rand() % t_script_vc.size(); this->routine_task_vc_.push_back(t_script_vc[index]); selected_task_set.insert(t_script_vc[index]); for (int i = 0; i < int(t_script_vc.size()); ++i) { if (i == index) continue; t_rand_vc.push_back(t_script_vc[i]); } } if (t_arena_vc.size() > 0) { int index = rand() % t_arena_vc.size(); this->routine_task_vc_.push_back(t_arena_vc[index]); selected_task_set.insert(t_arena_vc[index]); for (int i = 0; i < int(t_arena_vc.size()); ++i) { if (i == index) continue; t_rand_vc.push_back(t_arena_vc[i]); } } // 消费任务不重复前几天的任务 if (t_consume_vc.size() > 0) { if (t_consume_vc.size() <= this->routine_consume_history_.size()) this->routine_consume_history_.clear(); int index = rand() % t_consume_vc.size(), i = index; do { int consume_task = t_consume_vc[i]; if (this->routine_consume_history_.find(consume_task) == this->routine_consume_history_.end()) { this->routine_consume_history_.insert(consume_task); this->routine_task_vc_.push_back(consume_task); selected_task_set.insert(consume_task); break; } i = (i + 1) % t_consume_vc.size(); } while(i != index); for (int j = 0; j < int(t_consume_vc.size()); ++j) { int consume_task = t_consume_vc[j]; if (this->routine_consume_history_.find(consume_task) != this->routine_consume_history_.end()) continue; t_rand_vc.push_back(consume_task); } } // 日常任务数量控制 int routine_max_size = CONFIG_INSTANCE->task_setting()["daliy_routine_number"].asInt(); if (routine_max_size <= 0) routine_max_size = 7; if (t_liveness_vc.size() > 0) --routine_max_size; int left_size = routine_max_size - this->routine_task_vc_.size(); if (t_other_vc.size() > 0) { for (RoutineTaskVec::iterator iter = t_other_vc.begin(); iter != t_other_vc.end(); ++iter) { t_rand_vc.push_back(*iter); } } if (left_size > int(t_rand_vc.size())) { std::random_shuffle(t_other_scene_vc.begin(), t_other_scene_vc.end()); int need_size = left_size - t_rand_vc.size(); for (int i = 0; i < int(t_other_scene_vc.size()) && i < need_size; ++i) t_rand_vc.push_back(t_other_scene_vc[i]); } std::random_shuffle(t_rand_vc.begin(), t_rand_vc.end()); for (int i = 0; i < left_size && i < int(t_rand_vc.size()); ++i) { this->routine_task_vc_.push_back(t_rand_vc[i]); } std::random_shuffle(this->routine_task_vc_.begin(), this->routine_task_vc_.end()); if (t_liveness_vc.size() > 0) { int index = rand() % t_liveness_vc.size(); this->routine_task_vc_.push_back(t_liveness_vc[index]); } // 插入第一个日常任务 if (this->routine_task_vc_.size() > 0) { for (RoutineTaskVec::iterator iter = this->routine_task_vc_.begin(); iter != this->routine_task_vc_.end(); ++iter) { MSG_USER("routine task %s %ld %d", this->task_player()->role_name().c_str(), this->task_player()->role_id(), *iter); } this->routine_task_index_ = 0; int first_task = this->routine_task_vc_[this->routine_task_index_]; const Json::Value &task_json = CONFIG_INSTANCE->find_task(first_task); if (notify_add == true) this->insert_task(first_task, task_json); else this->init_task(first_task, task_json); this->is_routine_task_ = 1; } return 0; } */ void MapLogicTasker::clear_routine_task(const bool notify/* = true*/, const int type) { std::vector<TaskInfo *> remove_task_vc; for (TaskMap::iterator iter = this->task_map_.begin(); iter != this->task_map_.end(); ++iter) { TaskInfo *task_info = iter->second; if (task_info->__game_type != type) continue; remove_task_vc.push_back(task_info); } for (std::vector<TaskInfo *>::iterator iter = remove_task_vc.begin(); iter != remove_task_vc.end(); ++iter) { TaskInfo *task_info = *iter; if (task_info->task_imp() != 0) { TaskImplement *task_imp = task_info->task_imp(); task_imp->remove_task_listen(task_info); task_imp->remove_task_info(task_info, notify); } } // if (notify == false) return ; this->routine_task_index_[type] = -1; this->is_finish_all_routine_[type] = 0; this->is_routine_task_[type] = 0; } TaskInfo *MapLogicTasker::init_routine_task(const int task_id, const Json::Value &task_json) { TaskInfo *task_info = MAP_MONITOR->task_info_pool()->pop(); task_info->__task_id = task_id; task_info->__game_type = task_json["task_type"].asInt(); task_info->set_task_status(TaskInfo::TASK_STATUS_ACCEPTABLE); if (this->init_task_object(task_info, task_json) != 0) { MAP_MONITOR->task_info_pool()->push(task_info); return 0; } return task_info; } TaskInfo *MapLogicTasker::init_trial_task(const int task_id, const Json::Value &task_json) { // TaskInfo *task_info = MAP_MONITOR->task_info_pool()->pop(); // task_info->__task_id = task_id; // task_info->__game_type = task_json["task_type"].asInt(); // task_info->set_task_status(TaskInfo::TASK_STATUS_ACCEPTABLE); // // if (this->init_task_object(task_info, task_json) != 0) // { // MAP_MONITOR->task_info_pool()->push(task_info); // return 0; // } // // this->trial_task_set().insert(task_id); // // return task_info; return 0; } int MapLogicTasker::generate_next_routine_task(int type) { switch (type) { case TaskInfo::TASK_GTYPE_ROUTINE : { ++this->routine_task_index_[type]; //资源找回 this->task_player()->refresh_restore_info(GameEnum::ES_ACT_DAILY_ROUTINE, this->task_player()->role_level(), 1); //成就 this->task_player()->update_achieve_info(GameEnum::DAILY_TASK, 1); if (this->routine_task_index_[type] >= this->routine_total_num_[type]) { this->is_finish_all_routine_[type] = 1; this->routine_task_index_[type] = -1; if (this->is_finish_all_routine_[TaskInfo::TASK_GTYPE_OFFER_ROUTINE] == 0 && this->is_routine_task_[TaskInfo::TASK_GTYPE_OFFER_ROUTINE] == 0) this->offer_task_construct_routine(true); //接悬赏任务 return ERROR_ROUTINE_FINISH_ALL; } int next_routine_task = this->task_list_json()["daliy_routine_list"][this->routine_task_index_[type]].asInt(); const Json::Value &task_json = CONFIG_INSTANCE->find_task(next_routine_task); return this->insert_task(next_routine_task, task_json); } case TaskInfo::TASK_GTYPE_OFFER_ROUTINE : { ++this->routine_task_index_[type]; //资源找回 this->task_player()->refresh_restore_info(GameEnum::ES_ACT_OFFER_ROUTINE, this->task_player()->role_level(), 1); //成就 this->task_player()->update_achieve_info(GameEnum::REWARD_TASK, 1); if (this->routine_task_index_[type] >= this->routine_total_num_[type]) { this->is_finish_all_routine_[type] = 1; this->routine_task_index_[type] = -1; return ERROR_ROUTINE_FINISH_ALL; } int next_routine_task = this->task_list_json()["offer_routine_list"][this->routine_task_index_[type]].asInt(); const Json::Value &task_json = CONFIG_INSTANCE->find_task(next_routine_task); return this->insert_task(next_routine_task, task_json); } case TaskInfo::TASK_GTYPE_LEAGUE_ROUTINE : { ++this->routine_task_index_[type]; //资源找回 this->task_player()->refresh_restore_info(GameEnum::ES_ACT_LEAGUE_ROUTINE, this->task_player()->role_level(), 1); //成就 this->task_player()->update_achieve_info(GameEnum::LEAGUE_TASK, 1); if (this->routine_task_index_[type] >= this->routine_total_num_[type]) { this->is_finish_all_routine_[type] = 1; this->routine_task_index_[type] = -1; return ERROR_ROUTINE_FINISH_ALL; } int next_routine_task = this->task_list_json()["league_routine_list"][this->routine_task_index_[type]].asInt(); const Json::Value &task_json = CONFIG_INSTANCE->find_task(next_routine_task); return this->insert_task(next_routine_task, task_json); } } return 0; } /* int MapLogicTasker::request_routine_ui_status(void) { MapLogicPlayer *player = this->task_player(); const int ROUTINE_STATUS_NO_START = 0, ROUTINE_STATUS_DOING = 1, ROUTINE_STATUS_FINISH_ALL = 2; Proto51400343 respond; if (this->is_routine_task_ == 0) { if (this->is_finish_all_routine_ == 1) respond.set_status(ROUTINE_STATUS_FINISH_ALL); else respond.set_status(ROUTINE_STATUS_NO_START); } else { if (this->is_finish_all_routine_ == 1) respond.set_status(ROUTINE_STATUS_FINISH_ALL); else respond.set_status(ROUTINE_STATUS_DOING); } return player->respond_to_client(RETURN_ROUTINE_UI_STATUS, &respond); } */ /* int MapLogicTasker::request_routine_ui_detail(void) { MapLogicPlayer *player = this->task_player(); // 修正主线没有提交就获取日常的数据 const Json::Value &task_setting_json = CONFIG_INSTANCE->task_setting(); int prev_main_task_id = task_setting_json["virtual_routine_appear"].asInt(); if (this->task_submited_once_.find(prev_main_task_id) == this->task_submited_once_.end()) { TaskInfo *task_info = this->find_task(prev_main_task_id); if (task_info != NULL) { if (task_info->is_finish() == true || task_info->is_accepted() == true) this->process_submit(prev_main_task_id, 0); else this->process_accept(prev_main_task_id); } } this->refresh_routine_task(Time_Value::gettimeofday(), true); if (this->is_routine_task_ == 0 && this->is_finish_all_routine_ == 0) { //this->task_construct_routine(true); this->new_task_construct_routine(); } const Json::Value &finish_extra_json = CONFIG_INSTANCE->routine_wish(); Proto51400344 respond; { // 完成时额外奖励经验 const Json::Value &exp_json = finish_extra_json["exp"]; int first_level = exp_json["first_level"].asInt(); if (player->role_level() >= first_level) respond.set_extra_exp(GameCommon::json_by_index(exp_json["award"], player->role_level() - first_level).asInt()); } { // 完成时额外奖励的道具 const Json::Value &item_json = finish_extra_json["item"]; int first_level = item_json["first_level"].asInt(); if (player->role_level() >= first_level) { const Json::Value &level_item_json = GameCommon::json_by_index(item_json["award"], player->role_level() - first_level); for (uint i = 0; i < level_item_json.size(); ++i) { ProtoItem *proto_item = respond.add_extra_item(); proto_item->set_id(level_item_json[i][0u].asInt()); proto_item->set_amount(level_item_json[i][1u].asInt()); proto_item->set_bind(level_item_json[i][2u].asInt()); } } } { // 一键完成环式任务需要的元宝 int per_task_gold = task_setting_json["daliy_routine_fast_money"].asInt(); int left_routine_task_amount = this->left_routine_task_amount(); ProtoMoney *proto_money = respond.mutable_fast_gold(); proto_money->set_gold(left_routine_task_amount * per_task_gold); } { // 当前环信息 int task_index = this->routine_task_index_ + 1; if (task_index >= int(this->routine_task_vc_.size())) task_index = int(this->routine_task_vc_.size()); respond.set_routine_task_index(task_index); respond.set_total_routine_size(task_setting_json["daliy_routine_number"].asInt()); } { // 当前环式任务信息 TaskInfo *task_info = this->current_routine_task(); if (task_info != NULL && task_info->is_routine_task()) { this->serail_task_info(task_info, respond.mutable_routine_task()); const Json::Value &task_json = CONFIG_INSTANCE->find_task(task_info->__task_id); // 当前任务奖励信息 int award_exp = 0; Money award_money; std::map<int, ItemObj> item_map; double star_rate = this->calc_star_to_rate(task_info->__task_star, task_json); this->calc_routine_task_award(&award_exp, award_money, item_map, task_json, star_rate); award_money.serialize(respond.mutable_task_award_money()); respond.set_task_award_exp(award_exp); for (std::map<int, ItemObj>::iterator iter = item_map.begin(); iter != item_map.end(); ++iter) { ItemObj &item_obj = iter->second; item_obj.serialize(respond.add_task_award_item()); } #ifdef TEST_COMMAND char msg[514] = {0,}; ::sprintf(msg, "当前日常ID: %d", task_info->__task_id); this->task_player()->test_msg_in_chat(msg); #endif } } // 双倍奖励花费 { int double_award_need_money = task_setting_json["routine_double_award_money"].asInt(); ProtoMoney *proto_money = respond.mutable_double_award_money(); proto_money->set_gold(double_award_need_money); } //奖励礼包 { TaskInfo *task_info = this->current_routine_task(); const Json::Value &task_json = CONFIG_INSTANCE->find_task(task_info->__task_id); int award_id = task_json["award"]["award_id"].asInt(); respond.set_extra_award_id(GameEnum::ROUTINE_TASK_EXTRA_AWARD_NUM); respond.set_award_id(award_id); } return player->respond_to_client(RETURN_ROUTINE_UI_DETAIL, &respond); } */ int MapLogicTasker::routine_task_index(int type) { return this->routine_task_index_[type]; } int MapLogicTasker::routine_total_num(int type) { return this->routine_total_num_[type]; } int MapLogicTasker::left_routine_task_amount(int type) { int routine_amount = this->routine_total_num_[type]; if (this->is_routine_task_[type] == 0) { if (this->is_finish_all_routine_[type] == 0) return routine_amount; else return 0; } else { if (this->is_finish_all_routine_[type] == 1) return 0; int left_size = routine_amount - this->routine_task_index_[type]; // TaskInfo *current_routine = this->current_routine_task(type); // if (current_routine != NULL && (current_routine->is_finish() == true || current_routine->is_submit() == true)) // --left_size; // if (left_size < 0) left_size = 0; return left_size; } return 0; } const Json::Value &MapLogicTasker::task_list_json() { int level = this->task_player()->role_level(); return CONFIG_INSTANCE->role_level(0,level); } int MapLogicTasker::current_routine_task_id(int type) { switch(type) { case TaskInfo::TASK_GTYPE_ROUTINE: return this->task_list_json()["daliy_routine_list"][this->routine_task_index_[type]].asInt(); case TaskInfo::TASK_GTYPE_OFFER_ROUTINE: return this->task_list_json()["offer_routine_list"][this->routine_task_index_[type]].asInt(); case TaskInfo::TASK_GTYPE_LEAGUE_ROUTINE: return this->task_list_json()["league_routine_list"][this->routine_task_index_[type]].asInt(); } return 0; } TaskInfo *MapLogicTasker::current_routine_task(int type) { int task_id = this->current_routine_task_id(type); if (task_id <= 0) return NULL; return this->find_task(task_id); } bool MapLogicTasker::is_last_routine_task(int type) { if (this->routine_task_index_[type] == this->routine_total_num_[type]) return true; return false; } int MapLogicTasker::request_routine_world_chat(void) { return 0; } int MapLogicTasker::request_routine_open_market(void) { return 0; } int MapLogicTasker::refresh_daily_league_contri(void) { Time_Value nowtime = Time_Value::gettimeofday(); JUDGE_RETURN(this->lcontri_day_tick_ < nowtime, 0); this->lcontri_day_tick_ = next_day(0, 0, nowtime); this->lcontri_day_ = 0; return 0; } int MapLogicTasker::routine_fast_finish(const Json::Value &effect, PackageItem *pack_item) { bool routine_accepted = true; TaskInfo *task_info = 0; for (TaskMap::iterator iter = this->task_map_.begin(); iter != this->task_map_.end(); ++iter) { TaskInfo *info = iter->second; if (info->is_routine_task() == false) continue; if (info->is_accepted() == false) { routine_accepted = false; continue; } task_info = info; break; } if (task_info == 0) { if (routine_accepted == false) return ERROR_TASK_NO_ACCEPT; return ERROR_NO_TASK_CAN_FINISH; } int ret = task_info->__task_imp->process_finish(task_info); JUDGE_RETURN(ret == 0, ret); return 0; } int MapLogicTasker::update_open_ui_set(const Json::Value &json) { // const Json::Value &accept_json = json["accept"]; // for (uint i = 0; i < accept_json.size(); ++i) // { // int task_id = accept_json[i][0u].asInt(); // if (this->is_task_submited(task_id) == true) // { // this->open_ui_set().insert(accept_json[i][1u].asString()); // continue; // } // TaskInfo *task_info = this->find_task(task_id); // if (task_info != NULL && task_info->is_accepted() == true) // this->open_ui_set().insert(accept_json[i][1u].asString()); // } // const Json::Value &finish_json = json["finish"]; // for (uint i = 0; i < finish_json.size(); ++i) // { // int task_id = finish_json[i][0u].asInt(); // if (this->is_task_submited(task_id) == true) // { // this->open_ui_set().insert(finish_json[i][1u].asString()); // continue; // } // TaskInfo *task_info = this->find_task(task_id); // if (task_info != NULL && task_info->is_finish() == true) // this->open_ui_set().insert(finish_json[i][1u].asString()); // } // const Json::Value &submit_json = json["submit"]; // for (uint i = 0; i < submit_json.size(); ++i) // { // int task_id = submit_json[i][0u].asInt(); // if (this->is_task_submited(task_id)) // this->open_ui_set().insert(submit_json[i][1u].asString()); // } // const Json::Value &level_json = json["levelUP"]; // for (uint i = 0; i < level_json.size(); ++i) // { // int level = level_json[i][0u].asInt(); // if (this->task_player()->role_level() >= level) // this->open_ui_set().insert(level_json[i][1u].asString()); // } // const Json::Value &otherUI_json = json["otherUI"]; // { // if(otherUI_json.isMember("mount_grade")) // { // MountDetail& mount = this->task_player()->mount_detail(); // int condition = otherUI_json["mount_grade"][0u].asInt(); // if(mount.mount_grade_ >= condition) // this->open_ui_set().insert(otherUI_json["mount_grade"][1u].asString()); // // } // } return 0; } int MapLogicTasker::check_and_update_open_ui_by_sign(void) { // const Json::Value &prev_version_json = CONFIG_INSTANCE->task_setting()["novice_open_ui"]["prev_version"]; // const Json::Value &cur_version_json = CONFIG_INSTANCE->task_setting()["novice_open_ui"]["current_version"]; // if (this->ui_version_ != cur_version_json["version"].asInt()) // { // this->update_open_ui_set(prev_version_json); // this->ui_version_ = cur_version_json["version"].asInt(); // } // // this->update_open_ui_set(cur_version_json); return 0; } int MapLogicTasker::check_finish_task(int id) { JUDGE_RETURN(id > 0, true); return this->finish_task_.count(id) > 0; } int MapLogicTasker::check_current_version_open_ui(const int id, const int type,const char* key) { MapLogicPlayer *player = this->task_player(); if (type == GameEnum::CHECK_UIT_FINISH_TASK) { } else if (type == GameEnum::CHECK_UIT_SUBMIT_TASK) { const Json::Value& task_json = CONFIG_INSTANCE->find_task(id); if (task_json.isMember("skill") == true) { int sex = player->role_detail().__sex; player->request_sync_map_skill(task_json["skill"][sex - 1].asInt()); } if (task_json.isMember("save") == true) { player->insert_finish_task(id); } //通过完成任务开启功能 player->open_smelt(id); player->mount_try_task(id); player->spool_handle_player_task(id); player->fashion_handle_player_task(id); player->transfer_handle_player_task(id); player->check_league_open_task(id); player->change_magic_weapon_status(GameEnum::RAMA_GET_FROM_TASK, id); player->check_open_rama(id); player->check_open_illustration(id); } return 0; } int MapLogicTasker::request_refresh_task_star(Message *msg) { // DYNAMIC_CAST_RETURN(Proto11400345 *, request, msg, -1); // // MapLogicPlayer *player = this->task_player(); // // int task_id = request->task_id(); // TaskInfo *task_info = this->find_task(task_id); // CONDITION_PLAYER_NOTIFY_RETURN(task_info != NULL && task_info->is_routine_task(), // RETURN_ROUTINE_FRESH_STAR, ERROR_CLIENT_OPERATE); // // const Json::Value &task_json = CONFIG_INSTANCE->find_task(task_id); // CONDITION_PLAYER_NOTIFY_RETURN(task_json.isMember("task_star"), // RETURN_ROUTINE_FRESH_STAR, ERROR_CONFIG_NOT_EXIST); // CONDITION_PLAYER_NOTIFY_RETURN(task_info->__task_star < int(task_json["task_star"].size()), // RETURN_ROUTINE_FRESH_STAR, ERROR_TASK_TOP_STAR); // // const Json::Value &task_setting_json = CONFIG_INSTANCE->task_setting(); // Money cost; // cost.__bind_copper = task_setting_json["routine_star_fresh_copper"].asInt(); // GameCommon::adjust_money(cost, player->own_money()); // CONDITION_PLAYER_NOTIFY_RETURN(player->validate_money(cost) == true, // RETURN_ROUTINE_FRESH_STAR, ERROR_PACK_BIND_COPPER_AMOUNT); // // player->pack_money_sub(cost, SerialObj(SUB_MONEY_TASK_STAR, task_id)); // // this->init_task_star(task_info, task_json); // // ++task_info->__fresh_star_times; // if (task_info->__fresh_star_times >= task_setting_json["routine_protect_star_full"][0u].asInt()) // { // task_info->__task_star = int(task_json["task_star"].size()); // } // // Proto51400345 respond; // respond.set_task_id(task_id); // respond.set_star_level(task_info->__task_star); // return player->respond_to_client(RETURN_ROUTINE_FRESH_STAR, &respond); return 0; } int MapLogicTasker::request_routine_finish_all(Message *msg) { MSG_DYNAMIC_CAST_RETURN(Proto11400346 *, request, -1); int type = request->type(); MapLogicPlayer *player = this->task_player(); int left_routine_task_amount = this->left_routine_task_amount(type); CONDITION_PLAYER_NOTIFY_RETURN(left_routine_task_amount > 0, RETURN_ROUTINE_FINISH_ALL, ERROR_NO_TASK_CAN_FINISH); CONDITION_PLAYER_NOTIFY_RETURN(player->vip_type() > 0, RETURN_ROUTINE_FINISH_ALL, ERROR_VIP_LEVEL); const Json::Value &vip_json = CONFIG_INSTANCE->vip(player->vip_type()); CONDITION_PLAYER_NOTIFY_RETURN(vip_json["routine_fast"].asInt() == 1, RETURN_ROUTINE_FINISH_ALL, ERROR_VIP_LEVEL); const Json::Value &task_setting_json = CONFIG_INSTANCE->task_setting(); int per_task_gold = task_setting_json["routine_fast_money"].asInt(); Money cost; cost.__gold = left_routine_task_amount * per_task_gold; CONDITION_PLAYER_NOTIFY_RETURN(player->validate_money(cost), RETURN_ROUTINE_FINISH_ALL, ERROR_PACKAGE_GOLD_AMOUNT); Money ret; int scale = CONFIG_INSTANCE->vip(player->vip_type())["fast_return"].asInt(); ret.__bind_gold = cost.__gold * scale / BASE_SCALE_NUM; Proto51400346 respond; respond.set_type(type); ProtoMoney* money = respond.mutable_money(); ProtoMoney* return_money = respond.mutable_return_money(); cost.serialize(money); ret.serialize(return_money); respond.set_scale(scale / 100); string type_name; int type_index = this->routine_task_index_[type], type_num = this->routine_total_num_[type]; switch (type) { case TaskInfo::TASK_GTYPE_ROUTINE: { type_name = "daliy_routine_list"; break; } case TaskInfo::TASK_GTYPE_OFFER_ROUTINE: { type_name = "offer_routine_list"; break; } case TaskInfo::TASK_GTYPE_LEAGUE_ROUTINE: { type_name = "league_routine_list"; break; } default: type_name = "daliy_routine_list"; type_index = this->routine_task_index_[TaskInfo::TASK_GTYPE_ROUTINE]; type_num = this->routine_total_num_[TaskInfo::TASK_GTYPE_ROUTINE]; break; } for (int index = type_index; index < type_num; ++index) { int task_id = this->task_list_json()[type_name][index].asInt(); TaskInfo *task = NULL; if (this->find_task(task_id) != 0) { task = this->find_task(task_id); } else { const Json::Value &task_json = CONFIG_INSTANCE->find_task(task_id); task = this->init_task(task_id, task_json); } if (task == NULL) continue; TaskRoutineImp *routine_imp = dynamic_cast<TaskRoutineImp *>(task->task_imp()); routine_imp->new_process_task_reward(task); this->routine_task_index_[type]++; JUDGE_CONTINUE(task->task_imp() != NULL); routine_imp->remove_task_listen(task); routine_imp->remove_task_info(task, true); } this->clear_routine_task(true,type); this->routine_task_index_[type] = this->routine_total_num_[type]; this->is_finish_all_routine_[type] = 1; if (type == TaskInfo::TASK_GTYPE_ROUTINE && this->is_finish_all_routine_[TaskInfo::TASK_GTYPE_OFFER_ROUTINE] == 0 && this->is_routine_task_[TaskInfo::TASK_GTYPE_OFFER_ROUTINE] == 0) { this->offer_task_construct_routine(true); //接悬赏任务 } GameCommon::adjust_money(cost, player->own_money()); player->pack_money_sub(cost, SerialObj(SUB_MONEY_FAST_FINISH_ROUTINE)); player->pack_money_add(ret,SerialObj(ADD_FROM_VIP_RETURN)); for (int index = 0; index < type_num; ++index) { int task_id = this->task_list_json()[type_name][index].asInt(); const Json::Value &task_json = CONFIG_INSTANCE->find_task(task_id); TaskInfo *task_info = this->init_task(task_id, task_json); TaskRoutineImp *routine_imp = dynamic_cast<TaskRoutineImp *>(task_info->task_imp()); JUDGE_CONTINUE(task_info != NULL); JUDGE_CONTINUE(task_info->task_imp() != NULL); routine_imp->remove_task_listen(task_info); routine_imp->remove_task_info(task_info, true); } //更新剑池任务 this->update_sword_pool_info(left_routine_task_amount, type); this->update_cornucopia_task_info(left_routine_task_amount, type); int es_type = -1, achieve_type = -1; switch (type) { case TaskInfo::TASK_GTYPE_ROUTINE: { es_type = GameEnum::ES_ACT_DAILY_ROUTINE; achieve_type = GameEnum::DAILY_TASK; break; } case TaskInfo::TASK_GTYPE_OFFER_ROUTINE: { es_type = GameEnum::ES_ACT_OFFER_ROUTINE; achieve_type = GameEnum::REWARD_TASK; break; } case TaskInfo::TASK_GTYPE_LEAGUE_ROUTINE: { es_type = GameEnum::ES_ACT_LEAGUE_ROUTINE; achieve_type = GameEnum::LEAGUE_TASK; break; } default: break; } //资源找回 this->task_player()->refresh_restore_info(es_type, this->task_player()->role_level(), left_routine_task_amount); //成就 this->task_player()->update_achieve_info(achieve_type, left_routine_task_amount); return player->respond_to_client(RETURN_ROUTINE_FINISH_ALL, &respond); } int MapLogicTasker::calc_routine_task_award(int *award_exp, Money &award_money, std::map<int, ItemObj> &item_map, const Json::Value &task_json, const double real_rate) { MapLogicPlayer *player = this->task_player(); const Json::Value &level_award_json = task_json["level_award"]; const Json::Value &level_json = level_award_json["level"]; int level = player->role_level(), level_index = 0; for (uint i = 0; i < level_json.size(); ++i) { if (level_json[i].asInt() == level) { level_index = i; break; } } if (level_index >= int(level_json.size())) level_index = int(level_json.size()) - 1; JUDGE_RETURN(level_index >= 0, ERROR_CONFIG_ERROR); // 计算任务的等级奖励 { // normal const Json::Value &normal_json = level_award_json["normal"]; if (normal_json.isMember("goods")) { const Json::Value &goods_json = GameCommon::json_by_index(normal_json["goods"], level_index); for (uint i = 0; i < goods_json.size(); ++i) { int item_id = goods_json[i][0u].asInt(); ItemObj &item_obj = item_map[item_id]; item_obj.id_ = item_id; int item_amount = goods_json[i][1u].asInt(); if (real_rate > 0.0000001) item_amount = int(item_amount * real_rate); item_obj.amount_ += item_amount; item_obj.bind_ = 2; if (goods_json[i].size() >= 3) item_obj.bind_ = goods_json[i][2u].asInt(); } } if (normal_json.isMember("money")) { const Json::Value &money_json = GameCommon::json_by_index(normal_json["money"], level_index); int gold = money_json[0u].asInt(), bind_gold = money_json[1u].asInt(), copper = money_json[2u].asInt(), bind_copper = money_json[3u].asInt(); if (real_rate > 0.000001) { bind_copper = int(bind_copper * real_rate); copper = int(copper * real_rate); bind_gold = int(bind_gold * real_rate); gold = int(gold * real_rate); } award_money.__bind_copper += bind_copper; award_money.__copper += copper; award_money.__bind_gold += bind_gold; award_money.__gold += gold; } // add exp if (normal_json.isMember("exp")) { const Json::Value &exp_json = GameCommon::json_by_index(normal_json["exp"], level_index); int inc_exp = exp_json.asInt(); if (real_rate > 0.000001) inc_exp = int(inc_exp * real_rate); *award_exp += inc_exp; } } return 0; } int MapLogicTasker::calc_routine_extra_award(int *award_exp, Money &award_money, std::map<int, ItemObj> &item_map) { return 0; } double MapLogicTasker::calc_star_to_rate(const int star, const Json::Value &task_json) { int star_rate = 0; if (star > 0) { star_rate = GameCommon::json_by_index(task_json["task_star"], star - 1)[1u].asInt(); } if (star_rate > 0) return star_rate / 100.0; return 0.0; } void MapLogicTasker::insert_finish_task(int task_id) { JUDGE_RETURN(task_id > 0, ;); this->finish_task_.insert(task_id); } int MapLogicTasker::update_sword_pool_info(int num, int type) { Proto31402901 inner_res; inner_res.set_left_add_flag(1); inner_res.set_left_add_num(num); int task_id = 0; switch(type) { case TaskInfo::TASK_GTYPE_ROUTINE: { task_id = GameEnum::SPOOL_TASK_DAILY; break; } case TaskInfo::TASK_GTYPE_OFFER_ROUTINE: { task_id = GameEnum::SPOOL_TASK_REWARD; break; } case TaskInfo::TASK_GTYPE_LEAGUE_ROUTINE: { task_id = GameEnum::SPOOL_TASK_LEAGUE; break; } default: break; } inner_res.set_task_id(task_id); MSG_USER("MapLogicTasker, update_sword_pool_info, Proto31402901: %s", inner_res.Utf8DebugString().c_str()); MapLogicPlayer *player = this->task_player(); JUDGE_RETURN(player != NULL, 0); player->update_task_info(&inner_res); return 0; } int MapLogicTasker::record_serial(int task_id, int serial_type) { MapLogicPlayer *player = this->task_player(); return SERIAL_RECORD->record_task(player, player->agent_code(), player->market_code(), serial_type, task_id, player->role_level()); } int MapLogicTasker::update_cornucopia_task_info(int num, int type) { MSG_USER("MapLogicTasker::update_cornucopia_task_info start type:%d", type); Proto31403200 task_info; int task_id = 0; switch(type) { case TaskInfo::TASK_GTYPE_ROUTINE: { task_id = GameEnum::CORNUCOPIA_TASK_DAILY; break; } case TaskInfo::TASK_GTYPE_LEAGUE_ROUTINE: { task_id = GameEnum::CORNUCOPIA_TASK_LEAGUE; break; } default: return -1; } if(task_id == 0) return -1; task_info.set_task_id(task_id); task_info.set_task_finish_count(num); MSG_USER("MapLogicTasker, update_cornucopia_task_info, Proto31403200: %s", task_info.Utf8DebugString().c_str()); MapLogicPlayer *player = this->task_player(); return MAP_MONITOR->dispatch_to_logic(player, &task_info); }
6a53f7dd8d1f75e0f849c8fbda23d006d2a0bb17
4284deaf82e244ccf43015fab80a9b45acf65d6d
/test.cpp
b9c4e415e040405c7a03b718ff866c89a43c0f46
[]
no_license
soramimi/jstream
086d26dbd41c7877f2e8c9c6c1000680086db4f3
f6572b1194a0bebd38c9799f27ab2e54223dc6d6
refs/heads/master
2021-07-06T16:40:31.985000
2021-04-14T10:29:59
2021-04-14T10:29:59
234,760,713
0
0
null
null
null
null
UTF-8
C++
false
false
5,272
cpp
test.cpp
#include "test.h" #include "jstream.h" #include <fcntl.h> #include <sys/stat.h> #include <algorithm> #ifdef _WIN32 #include <io.h> #include <windows.h> #else #include <dirent.h> #include <unistd.h> #define O_BINARY 0 #endif std::string trim(std::string const &s) { char const *begin = s.c_str(); char const *end = begin + s.size(); while (begin < end && isspace((unsigned char)*begin)) begin++; while (begin < end && isspace((unsigned char)end[-1])) end--; std::vector<char> vec; vec.reserve(end - begin); char const *src = begin; while (src < end) { if (*src == '\r') { src++; } else { vec.push_back(*src); src++; } } if (vec.empty()) return {}; begin = vec.data(); end = begin + vec.size(); return std::string(begin, end); } bool read_file(char const *path, std::vector<char> *out) { bool ok = false; out->clear(); int fd = open(path, O_RDONLY | O_BINARY); if (fd != -1) { struct stat st; if (fstat(fd, &st) == 0) { ok = true; if (st.st_size > 0) { out->resize(st.st_size); if (read(fd, out->data(), out->size()) != st.st_size) { ok = false; } } } close(fd); } return ok; } void parse_test_case(char const *begin, char const *end, std::vector<std::string> *strings) { strings->clear(); char const *head = begin; char const *ptr = begin; bool newline = true; while (1) { int c = 0; if (ptr < end) { c = (unsigned char)*ptr; } if (c == 0) { strings->push_back(std::string(head, ptr)); break; } if (c == '\r' || c == '\n') { newline = true; ptr++; } else { if (c == '-' && newline) { if (ptr + 3 < end && ptr[1] == '-' && ptr[2] == '-') { c = ptr[3]; if (c == '\r' || c == '\n') { strings->push_back(std::string(head, ptr)); ptr += 4; head = ptr; } } } newline = false; ptr++; } } } void parse(char const *source, std::string *result1) { jstream::Reader json(source, source + strlen(source)); while (json.next()) { char tmp[1000]; tmp[0] = 0; switch (json.state()) { case jstream::StartObject: sprintf(tmp, "StartObject: \"%s\"\n", json.key().c_str()); break; case jstream::EndObject: sprintf(tmp, "EndObject: \"%s\"\n", json.key().c_str()); break; case jstream::StartArray: sprintf(tmp, "StartArray: \"%s\"\n", json.key().c_str()); break; case jstream::EndArray: sprintf(tmp, "EndArray: \"%s\"\n", json.key().c_str()); break; case jstream::String: sprintf(tmp, "StringValue: \"%s\" = \"%s\"\n", json.key().c_str(), json.string().c_str()); break; case jstream::Number: sprintf(tmp, "NumberValue: \"%s\" = %f\n", json.key().c_str(), json.number()); break; case jstream::Null: case jstream::False: case jstream::True: sprintf(tmp, "SymbolValue: \"%s\" = %s\n", json.key().c_str(), json.string().c_str()); break; } *result1 += tmp; if (json.isvalue()) { std::string s = json.path() + '='; if (json.state() == jstream::String) { s = s + '\"' + json.string() + '\"'; } else { s = s + json.string(); } s += '\n'; *result1 += s; } } if (json.state() == jstream::Error) { *result1 += "Error: " + json.string(); } } #ifdef _WIN32 void get_tests(const std::string &loc, std::vector<std::string> *out) { out->clear(); std::string filter = loc + "*.*"; WIN32_FIND_DATAA fd; HANDLE h = FindFirstFileA(filter.c_str(), &fd); if (h != INVALID_HANDLE_VALUE) { do { std::string name; name = fd.cFileName; if (fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) { continue; } out->push_back(name); } while (FindNextFileA(h, &fd)); FindClose(h); } } #else void get_tests(std::string const &loc, std::vector<std::string> *out) { out->clear(); DIR *dir = opendir(loc.c_str()); if (dir) { while (dirent *d = readdir(dir)) { std::string name; name = d->d_name; if (d->d_type & DT_DIR) { continue; } out->push_back(name); } closedir(dir); } } #endif void test_all() { int pass = 0; int fail = 0; int total = 0; std::string dir = "test/"; std::vector<std::string> tests; get_tests(dir.c_str(), &tests); std::sort(tests.begin(), tests.end()); for (std::string const &name : tests) { std::string path = dir + name; std::vector<char> vec; if (read_file(path.c_str(), &vec) && !vec.empty()) { total++; std::vector<std::string> strings; char const *begin = vec.data(); char const *end = begin + vec.size(); parse_test_case(begin, end, &strings); std::string input; std::string result; if (strings.size() == 2) { input = strings[0]; result = strings[1]; } else { fail++; printf("#%d TEST CASE SYNTAX ERROR %s\n", total, name.c_str()); continue; } std::string result1; parse(input.c_str(), &result1); if (trim(result1) == trim(result)) { pass++; printf("#%d PASS %s\n", total, name.c_str()); } else { fail++; printf("#%d FAIL %s\n", total, name.c_str()); puts("--- INPUT ---------"); puts(trim(input).c_str()); puts("--- EXPECTED EVENTS ----------"); puts(trim(result).c_str()); puts("--- ACTUAL RESULT ----------"); puts(trim(result1).c_str()); puts("---"); } } } printf("---\n" "TOTAL: %d\n" " PASS: %d\n" " FAIL: %d\n", total, pass, fail); }
aa16f9831ca2b38ff0acbf3ad696c0d5b56f3835
4e932dd028c6660b822936dc49a53759ffb748d7
/rush01/Module.hpp
70f0b52f1063c848a1d024d830b800cc999051b7
[]
no_license
YoungTran/cpp-crash-course
134075759e2e673e5f822f605a10d388b0ccd4bc
cfe52bc6161c911ed1b0fba49c916f4d0878a2af
refs/heads/master
2023-06-17T16:31:26.772811
2021-07-22T05:59:51
2021-07-22T05:59:51
168,427,962
0
0
null
null
null
null
UTF-8
C++
false
false
1,729
hpp
Module.hpp
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* Module.hpp :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: ytran <marvin@42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2018/10/13 20:55:25 by ytran #+# #+# */ /* Updated: 2018/10/13 20:55:26 by ytran ### ########.fr */ /* */ /* ************************************************************************** */ #ifndef MODULE_HPP #define MODULE_HPP #include "IMonitorModule.hpp" #include <string> #include <iostream> class Module : public IMonitorModule { protected: std::string const _name; int _sx; int _sy; int _x; int _y; public: Module(std::string const &name); Module(Module const &src, std::string const &name); Module & operator=(Module const & rhs); virtual ~Module(); std::string getName() const; int getSizeX(); int getSizeY(); int getX(); int getY(); void setSizeX(int); void setSizeY(int); void setX(int); void setY(int); virtual std::string getData(void); }; #endif
73091581ca260dbcccfa99dc6dab3fad9c455e29
67f5e017387096337e2bf4a43cc87d849a553d97
/Sources/Shared/Responses/Response.cpp
f4f692f214a390cbeee8575621c1174f347358b4
[]
no_license
Kacper20/TIN
64953fe058a67c97e5b79ac34354e6b219352843
3f54e7f0ed4394c350771f42b2b402704c4aacab
refs/heads/master
2021-01-18T11:14:54.256191
2016-06-07T14:46:53
2016-06-07T14:46:53
56,088,590
0
0
null
2016-06-07T11:34:57
2016-04-12T18:39:40
C++
UTF-8
C++
false
false
315
cpp
Response.cpp
// // Created by Kacper Harasim on 21.05.2016. // #include "Response.h" Json::Value Response::generateJSON() { Json::Value root; root[JSONConstants::ResponseType] = descriptionForResponseType(responseType); root[JSONConstants::ResponseStatus] = descriptionForResponseStatus(responseStatus); return root; }
832b61f54f3e0d73c41146e2796c2e25eef25b19
883887c3c84bd3ac4a11ac76414129137a1b643b
/nengine/navatar/LoadingCal3DObjectsTask.h
5471c2adc410394bd320cb17c0e3f12d25277f15
[]
no_license
15831944/vAcademia
4dbb36d9d772041e2716506602a602d516e77c1f
447f9a93defb493ab3b6f6c83cbceb623a770c5c
refs/heads/master
2022-03-01T05:28:24.639195
2016-08-18T12:32:22
2016-08-18T12:32:22
null
0
0
null
null
null
null
UTF-8
C++
false
false
794
h
LoadingCal3DObjectsTask.h
#pragma once #include "CommonAvatarHeader.h" #include <vector> #include "ITask.h" #include "FakeObject.h" class CLoadingCal3DObjectsTask : public ITask { public: CLoadingCal3DObjectsTask(); ~CLoadingCal3DObjectsTask(); void SetParams(CAvatarObject* avatarObject, C3DObject* obj3d, const std::string& path, const std::string& name, void* data, unsigned int size); STransitionalInfo* GetTransitionalInfo(); std::string GetPath(); std::string GetName(); bool IsLoaded()const; void Start(); void PrintInfo(); void Destroy(); void SelfDestroy(); bool IsOptionalTask() { return false; } private: void FreeData(); CAvatarObject* m_avatarObject; MP_STRING m_path; MP_STRING m_name; STransitionalInfo* m_info; bool m_isLoaded; unsigned int m_size; void* m_data; };
d5d9be23b588a8aa88486b93d4c4b8ba83ecb1c8
c30529671974f8d36576bcde7c611634e993c0c1
/Lab2/SecurityCam2/SCCameraCommand.cpp
1a4b31bda11b20c12372e1b981d451a9772d00ec
[]
no_license
ccceeefff/18646-lpsoc-labs
51ac2737300713dea42e46ad1366f76025138de6
70e60df0252b18c13666241eb179f0998bae3189
refs/heads/master
2021-01-10T13:34:03.299999
2016-03-04T11:12:40
2016-03-04T11:12:40
50,469,930
0
0
null
null
null
null
UTF-8
C++
false
false
4,959
cpp
SCCameraCommand.cpp
#include "SCCameraCommand.h" #include "Arduino_Due_SD_HSCMI.h" SCCameraCommand::SCCameraCommand(uint8_t command){ _command = command; } SCCameraCommand::SCCameraCommand(uint8_t command, String parameter){ _command = command; _parameter = parameter.substring(0); //copy } uint8_t SCCameraCommand::getCommand(){ return _command; } String SCCameraCommand::getParameter(){ return _parameter; } /* * Camera Log */ SCCamera_log::SCCamera_log(QueueHandle_t commandQueue){ _commandQueue = commandQueue; } int SCCamera_log::execute(SCCommand *command, SCStream *in, SCStream *out){ if(command->getArgCount() == 0){ out->println("Must specify enable or disable"); return -1; } String arg = command->getArg(0); if(arg == "enable" || arg == "disable"){ SCCameraCommand *cmd = new SCCameraCommand(CAMERA_SET_LOGGING, arg); xQueueSendToBack(_commandQueue, &cmd, portMAX_DELAY); } else { out->println("Must specify enable or disable"); return -2; } return 0; } String SCCamera_log::getCommand(){ return "log"; } String SCCamera_log::getDescription(){ return "use to enable logging (camera log enable)"; } /* * Camera Snapshot */ SCCamera_snapshot::SCCamera_snapshot(QueueHandle_t commandQueue){ _commandQueue = commandQueue; } int SCCamera_snapshot::execute(SCCommand *command, SCStream *in, SCStream *out){ out->println("Taking snapshot now!"); SCCameraCommand *cmd = new SCCameraCommand(CAMERA_TAKE_PICTURE); xQueueSendToBack(_commandQueue, &cmd, portMAX_DELAY); return 0; } String SCCamera_snapshot::getCommand(){ return "snapshot"; } String SCCamera_snapshot::getDescription(){ return "take a snapshot using the camera"; } /* * Camera Image Size */ SCCamera_imageSize::SCCamera_imageSize(QueueHandle_t commandQueue){ _commandQueue = commandQueue; } int SCCamera_imageSize::execute(SCCommand *command, SCStream *in, SCStream *out){ if(command->getArgCount() == 0){ out->println("Must specify size!"); return -1; } String arg = command->getArg(0); if(arg == "640x480" || arg == "320x240" || arg == "160x120"){ SCCameraCommand *cmd = new SCCameraCommand(CAMERA_SET_IMAGE_SIZE, arg); xQueueSendToBack(_commandQueue, &cmd, portMAX_DELAY); } else { out->println("Invalid image size specified."); return -2; } return 0; } String SCCamera_imageSize::getCommand(){ return "imagesize"; } String SCCamera_imageSize::getDescription(){ return "set the size of the image to capture. use preset sizes e.g. 640x480, 320x240, etc"; } /* * Camera Motion Detect */ SCCamera_motionDetect::SCCamera_motionDetect(QueueHandle_t commandQueue){ _commandQueue = commandQueue; } int SCCamera_motionDetect::execute(SCCommand *command, SCStream *in, SCStream *out){ if(command->getArgCount() == 0){ out->println("Must specify enable or disable"); return -1; } String arg = command->getArg(0); if(arg == "enable" || arg == "disable"){ SCCameraCommand *cmd = new SCCameraCommand(CAMERA_SET_MOTION_DETECT, arg); xQueueSendToBack(_commandQueue, &cmd, portMAX_DELAY); } else { out->println("Must specify enable or disable"); return -2; } return 0; } String SCCamera_motionDetect::getCommand(){ return "motiondetect"; } String SCCamera_motionDetect::getDescription(){ return "enable or disable motion detection. use with 'enable' to turn on motion detection"; } /* * Camera Change Directory */ SCCamera_cd::SCCamera_cd(QueueHandle_t commandQueue){ _commandQueue = commandQueue; } int SCCamera_cd::execute(SCCommand *command, SCStream *in, SCStream *out){ // must have one string paramter if(command->getArgCount() == 0){ out->println("Must specify target directory!"); return -1; } String dir = command->getArg(0); if(SD.PathExists(dir.c_str())){ SCCameraCommand *cmd = new SCCameraCommand(CAMERA_SET_IMAGE_DIRECTORY, dir); xQueueSendToBack(_commandQueue, &cmd, portMAX_DELAY); } else { out->println(dir + " does not exists."); return -1; } return 0; } String SCCamera_cd::getCommand(){ return "cd"; } String SCCamera_cd::getDescription(){ return "change where the camera should store images"; } /* * Camera TV */ SCCamera_tv::SCCamera_tv(QueueHandle_t commandQueue){ _commandQueue = commandQueue; } int SCCamera_tv::execute(SCCommand *command, SCStream *in, SCStream *out){ if(command->getArgCount() == 0){ out->println("Must specify enable or disable"); return -1; } String arg = command->getArg(0); if(arg == "enable" || arg == "disable"){ SCCameraCommand *cmd = new SCCameraCommand(CAMERA_SET_TV_ENABLED, arg); xQueueSendToBack(_commandQueue, &cmd, portMAX_DELAY); } else { out->println("Must specify enable or disable"); return -2; } return 0; } String SCCamera_tv::getCommand(){ return "tv"; } String SCCamera_tv::getDescription(){ return "enable or disable the camera tv output"; }
01550eff4602a399b93dcb79e736cb4f1f86076b
575d2081b3bb1f72a73ee7a6d446ab3352747728
/sensor/arduino_sensor.ino
5254f3f0b51960223f977b722b340dc0fa267729
[]
no_license
St-Edwards-6th-Form-Cheltenham/FootballSpeedAnalysis
917245cc3d815da09e615d4bd84656084ba123c6
34b5ee9373df849c2fe20b6988df760ae1cf5389
refs/heads/master
2020-12-15T15:50:55.155108
2020-02-18T12:44:54
2020-02-18T12:44:54
235,163,851
0
2
null
null
null
null
UTF-8
C++
false
false
1,424
ino
arduino_sensor.ino
// Below: pin number for FOUT #define PIN_NUMBER 4 // Below: number of samples for averaging #define AVERAGE 4 // Below: define to use serial output with python script //#define PYTHON_OUTPUT unsigned int doppler_div = 190; unsigned int samples[AVERAGE]; unsigned int x; void setup() { Serial.begin(9600); pinMode(PIN_NUMBER, INPUT); } void loop() { noInterrupts(); pulseIn(PIN_NUMBER, HIGH); unsigned int pulse_length = 0; for (x = 0; x < AVERAGE; x++) { pulse_length = pulseIn(PIN_NUMBER, HIGH); pulse_length += pulseIn(PIN_NUMBER, LOW); samples[x] = pulse_length; } interrupts(); // Check for consistency bool samples_ok = true; unsigned int nbPulsesTime = samples[0]; for (x = 1; x < AVERAGE; x++) { nbPulsesTime += samples[x]; if ((samples[x] > samples[0] * 2) || (samples[x] < samples[0] / 2)) { samples_ok = false; } } if (samples_ok) { unsigned int Ttime = nbPulsesTime / AVERAGE; unsigned int Freq = 1000000 / Ttime; #ifdef PYTHON_OUTPUT Serial.write(Freq/doppler_div); #else //Serial.print(Ttime); Serial.print("\r\n"); Serial.print(Freq); Serial.print("Hz : "); Serial.print(Freq/doppler_div); Serial.print("km/h\r\n"); #endif } else { #ifndef PYTHON_OUTPUT Serial.print("."); #endif } }
96b5eae93df481c5d88b0840fc257967e9ecd5d8
337c461e7e6fe51fd2a0d60b3cec73f9d05c2018
/USB2Mat_i.h
43dea77f1f7ffa349483f0d48f69dedda679c398
[]
no_license
huangjielg/USB2Mat
7d28add066e0cfaacb8b92ad86854e58c1d485d5
aad41ef27720fd798626ad1159e0381a06a413cf
refs/heads/master
2023-02-24T02:24:35.971956
2020-09-11T06:30:56
2020-09-11T06:30:56
334,005,115
0
0
null
null
null
null
UTF-8
C++
false
false
17,824
h
USB2Mat_i.h
/* this ALWAYS GENERATED file contains the definitions for the interfaces */ /* File created by MIDL compiler version 8.01.0622 */ /* at Tue Jan 19 11:14:07 2038 */ /* Compiler settings for USB2Mat.idl: Oicf, W1, Zp8, env=Win32 (32b run), target_arch=X86 8.01.0622 protocol : dce , ms_ext, c_ext, robust error checks: allocation ref bounds_check enum stub_data VC __declspec() decoration level: __declspec(uuid()), __declspec(selectany), __declspec(novtable) DECLSPEC_UUID(), MIDL_INTERFACE() */ /* @@MIDL_FILE_HEADING( ) */ /* verify that the <rpcndr.h> version is high enough to compile this file*/ #ifndef __REQUIRED_RPCNDR_H_VERSION__ #define __REQUIRED_RPCNDR_H_VERSION__ 500 #endif #include "rpc.h" #include "rpcndr.h" #ifndef __RPCNDR_H_VERSION__ #error this stub requires an updated version of <rpcndr.h> #endif /* __RPCNDR_H_VERSION__ */ #ifndef COM_NO_WINDOWS_H #include "windows.h" #include "ole2.h" #endif /*COM_NO_WINDOWS_H*/ #ifndef __USB2Mat_i_h__ #define __USB2Mat_i_h__ #if defined(_MSC_VER) && (_MSC_VER >= 1020) #pragma once #endif /* Forward Declarations */ #ifndef __IUSB_FWD_DEFINED__ #define __IUSB_FWD_DEFINED__ typedef interface IUSB IUSB; #endif /* __IUSB_FWD_DEFINED__ */ #ifndef ___IUSBEvents_FWD_DEFINED__ #define ___IUSBEvents_FWD_DEFINED__ typedef interface _IUSBEvents _IUSBEvents; #endif /* ___IUSBEvents_FWD_DEFINED__ */ #ifndef __USB_FWD_DEFINED__ #define __USB_FWD_DEFINED__ #ifdef __cplusplus typedef class USB USB; #else typedef struct USB USB; #endif /* __cplusplus */ #endif /* __USB_FWD_DEFINED__ */ /* header files for imported files */ #include "oaidl.h" #include "ocidl.h" #include "shobjidl.h" #ifdef __cplusplus extern "C"{ #endif #ifndef __IUSB_INTERFACE_DEFINED__ #define __IUSB_INTERFACE_DEFINED__ /* interface IUSB */ /* [unique][nonextensible][dual][uuid][object] */ EXTERN_C const IID IID_IUSB; #if defined(__cplusplus) && !defined(CINTERFACE) MIDL_INTERFACE("0e75bdde-9867-48aa-915a-c57277a22e42") IUSB : public IDispatch { public: virtual /* [id] */ HRESULT STDMETHODCALLTYPE Start( void) = 0; virtual /* [id] */ HRESULT STDMETHODCALLTYPE Stop( void) = 0; virtual /* [id] */ HRESULT STDMETHODCALLTYPE Read( /* [in] */ LONG len, /* [retval][out] */ SAFEARRAY * *pRetVal) = 0; virtual /* [id] */ HRESULT STDMETHODCALLTYPE ReadSync( /* [in] */ LONG len, /* [retval][out] */ SAFEARRAY * *pRetVal) = 0; virtual /* [id][propget] */ HRESULT STDMETHODCALLTYPE get_saveFileName( /* [retval][out] */ BSTR *pVal) = 0; virtual /* [id][propput] */ HRESULT STDMETHODCALLTYPE put_saveFileName( /* [in] */ BSTR newVal) = 0; virtual /* [id][propget] */ HRESULT STDMETHODCALLTYPE get_Avial( /* [retval][out] */ LONG *pVal) = 0; virtual /* [id][propget] */ HRESULT STDMETHODCALLTYPE get_readyThreshold( /* [retval][out] */ LONG *pVal) = 0; virtual /* [id][propput] */ HRESULT STDMETHODCALLTYPE put_readyThreshold( /* [in] */ LONG newVal) = 0; virtual /* [id] */ HRESULT STDMETHODCALLTYPE ReadDirect( /* [in] */ LONG len, /* [retval][out] */ SAFEARRAY * *pRetVal) = 0; virtual /* [id] */ HRESULT STDMETHODCALLTYPE WriteDirect( SAFEARRAY * Val) = 0; virtual /* [id] */ HRESULT STDMETHODCALLTYPE WriteReg( /* [in] */ USHORT addr, /* [in] */ USHORT Val) = 0; virtual /* [id] */ HRESULT STDMETHODCALLTYPE ReadReg( /* [in] */ USHORT addr, /* [retval][out] */ USHORT *pVal) = 0; virtual /* [id][propget] */ HRESULT STDMETHODCALLTYPE get_doInit( /* [retval][out] */ LONG *pVal) = 0; virtual /* [id][propput] */ HRESULT STDMETHODCALLTYPE put_doInit( /* [in] */ LONG newVal) = 0; virtual /* [id][propget] */ HRESULT STDMETHODCALLTYPE get_outFormat( /* [retval][out] */ BSTR *pVal) = 0; virtual /* [id][propput] */ HRESULT STDMETHODCALLTYPE put_outFormat( /* [in] */ BSTR newVal) = 0; virtual /* [id] */ HRESULT STDMETHODCALLTYPE ReadDouble( /* [in] */ LONG len, /* [retval][out] */ SAFEARRAY * *pRetVal) = 0; virtual /* [id] */ HRESULT STDMETHODCALLTYPE ReadDoubleSync( /* [in] */ LONG len, /* [retval][out] */ SAFEARRAY * *pRetVal) = 0; }; #else /* C style interface */ typedef struct IUSBVtbl { BEGIN_INTERFACE HRESULT ( STDMETHODCALLTYPE *QueryInterface )( IUSB * This, /* [in] */ REFIID riid, /* [annotation][iid_is][out] */ _COM_Outptr_ void **ppvObject); ULONG ( STDMETHODCALLTYPE *AddRef )( IUSB * This); ULONG ( STDMETHODCALLTYPE *Release )( IUSB * This); HRESULT ( STDMETHODCALLTYPE *GetTypeInfoCount )( IUSB * This, /* [out] */ UINT *pctinfo); HRESULT ( STDMETHODCALLTYPE *GetTypeInfo )( IUSB * This, /* [in] */ UINT iTInfo, /* [in] */ LCID lcid, /* [out] */ ITypeInfo **ppTInfo); HRESULT ( STDMETHODCALLTYPE *GetIDsOfNames )( IUSB * This, /* [in] */ REFIID riid, /* [size_is][in] */ LPOLESTR *rgszNames, /* [range][in] */ UINT cNames, /* [in] */ LCID lcid, /* [size_is][out] */ DISPID *rgDispId); /* [local] */ HRESULT ( STDMETHODCALLTYPE *Invoke )( IUSB * This, /* [annotation][in] */ _In_ DISPID dispIdMember, /* [annotation][in] */ _In_ REFIID riid, /* [annotation][in] */ _In_ LCID lcid, /* [annotation][in] */ _In_ WORD wFlags, /* [annotation][out][in] */ _In_ DISPPARAMS *pDispParams, /* [annotation][out] */ _Out_opt_ VARIANT *pVarResult, /* [annotation][out] */ _Out_opt_ EXCEPINFO *pExcepInfo, /* [annotation][out] */ _Out_opt_ UINT *puArgErr); /* [id] */ HRESULT ( STDMETHODCALLTYPE *Start )( IUSB * This); /* [id] */ HRESULT ( STDMETHODCALLTYPE *Stop )( IUSB * This); /* [id] */ HRESULT ( STDMETHODCALLTYPE *Read )( IUSB * This, /* [in] */ LONG len, /* [retval][out] */ SAFEARRAY * *pRetVal); /* [id] */ HRESULT ( STDMETHODCALLTYPE *ReadSync )( IUSB * This, /* [in] */ LONG len, /* [retval][out] */ SAFEARRAY * *pRetVal); /* [id][propget] */ HRESULT ( STDMETHODCALLTYPE *get_saveFileName )( IUSB * This, /* [retval][out] */ BSTR *pVal); /* [id][propput] */ HRESULT ( STDMETHODCALLTYPE *put_saveFileName )( IUSB * This, /* [in] */ BSTR newVal); /* [id][propget] */ HRESULT ( STDMETHODCALLTYPE *get_Avial )( IUSB * This, /* [retval][out] */ LONG *pVal); /* [id][propget] */ HRESULT ( STDMETHODCALLTYPE *get_readyThreshold )( IUSB * This, /* [retval][out] */ LONG *pVal); /* [id][propput] */ HRESULT ( STDMETHODCALLTYPE *put_readyThreshold )( IUSB * This, /* [in] */ LONG newVal); /* [id] */ HRESULT ( STDMETHODCALLTYPE *ReadDirect )( IUSB * This, /* [in] */ LONG len, /* [retval][out] */ SAFEARRAY * *pRetVal); /* [id] */ HRESULT ( STDMETHODCALLTYPE *WriteDirect )( IUSB * This, SAFEARRAY * Val); /* [id] */ HRESULT ( STDMETHODCALLTYPE *WriteReg )( IUSB * This, /* [in] */ USHORT addr, /* [in] */ USHORT Val); /* [id] */ HRESULT ( STDMETHODCALLTYPE *ReadReg )( IUSB * This, /* [in] */ USHORT addr, /* [retval][out] */ USHORT *pVal); /* [id][propget] */ HRESULT ( STDMETHODCALLTYPE *get_doInit )( IUSB * This, /* [retval][out] */ LONG *pVal); /* [id][propput] */ HRESULT ( STDMETHODCALLTYPE *put_doInit )( IUSB * This, /* [in] */ LONG newVal); /* [id][propget] */ HRESULT ( STDMETHODCALLTYPE *get_outFormat )( IUSB * This, /* [retval][out] */ BSTR *pVal); /* [id][propput] */ HRESULT ( STDMETHODCALLTYPE *put_outFormat )( IUSB * This, /* [in] */ BSTR newVal); /* [id] */ HRESULT ( STDMETHODCALLTYPE *ReadDouble )( IUSB * This, /* [in] */ LONG len, /* [retval][out] */ SAFEARRAY * *pRetVal); /* [id] */ HRESULT ( STDMETHODCALLTYPE *ReadDoubleSync )( IUSB * This, /* [in] */ LONG len, /* [retval][out] */ SAFEARRAY * *pRetVal); END_INTERFACE } IUSBVtbl; interface IUSB { CONST_VTBL struct IUSBVtbl *lpVtbl; }; #ifdef COBJMACROS #define IUSB_QueryInterface(This,riid,ppvObject) \ ( (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) ) #define IUSB_AddRef(This) \ ( (This)->lpVtbl -> AddRef(This) ) #define IUSB_Release(This) \ ( (This)->lpVtbl -> Release(This) ) #define IUSB_GetTypeInfoCount(This,pctinfo) \ ( (This)->lpVtbl -> GetTypeInfoCount(This,pctinfo) ) #define IUSB_GetTypeInfo(This,iTInfo,lcid,ppTInfo) \ ( (This)->lpVtbl -> GetTypeInfo(This,iTInfo,lcid,ppTInfo) ) #define IUSB_GetIDsOfNames(This,riid,rgszNames,cNames,lcid,rgDispId) \ ( (This)->lpVtbl -> GetIDsOfNames(This,riid,rgszNames,cNames,lcid,rgDispId) ) #define IUSB_Invoke(This,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr) \ ( (This)->lpVtbl -> Invoke(This,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr) ) #define IUSB_Start(This) \ ( (This)->lpVtbl -> Start(This) ) #define IUSB_Stop(This) \ ( (This)->lpVtbl -> Stop(This) ) #define IUSB_Read(This,len,pRetVal) \ ( (This)->lpVtbl -> Read(This,len,pRetVal) ) #define IUSB_ReadSync(This,len,pRetVal) \ ( (This)->lpVtbl -> ReadSync(This,len,pRetVal) ) #define IUSB_get_saveFileName(This,pVal) \ ( (This)->lpVtbl -> get_saveFileName(This,pVal) ) #define IUSB_put_saveFileName(This,newVal) \ ( (This)->lpVtbl -> put_saveFileName(This,newVal) ) #define IUSB_get_Avial(This,pVal) \ ( (This)->lpVtbl -> get_Avial(This,pVal) ) #define IUSB_get_readyThreshold(This,pVal) \ ( (This)->lpVtbl -> get_readyThreshold(This,pVal) ) #define IUSB_put_readyThreshold(This,newVal) \ ( (This)->lpVtbl -> put_readyThreshold(This,newVal) ) #define IUSB_ReadDirect(This,len,pRetVal) \ ( (This)->lpVtbl -> ReadDirect(This,len,pRetVal) ) #define IUSB_WriteDirect(This,Val) \ ( (This)->lpVtbl -> WriteDirect(This,Val) ) #define IUSB_WriteReg(This,addr,Val) \ ( (This)->lpVtbl -> WriteReg(This,addr,Val) ) #define IUSB_ReadReg(This,addr,pVal) \ ( (This)->lpVtbl -> ReadReg(This,addr,pVal) ) #define IUSB_get_doInit(This,pVal) \ ( (This)->lpVtbl -> get_doInit(This,pVal) ) #define IUSB_put_doInit(This,newVal) \ ( (This)->lpVtbl -> put_doInit(This,newVal) ) #define IUSB_get_outFormat(This,pVal) \ ( (This)->lpVtbl -> get_outFormat(This,pVal) ) #define IUSB_put_outFormat(This,newVal) \ ( (This)->lpVtbl -> put_outFormat(This,newVal) ) #define IUSB_ReadDouble(This,len,pRetVal) \ ( (This)->lpVtbl -> ReadDouble(This,len,pRetVal) ) #define IUSB_ReadDoubleSync(This,len,pRetVal) \ ( (This)->lpVtbl -> ReadDoubleSync(This,len,pRetVal) ) #endif /* COBJMACROS */ #endif /* C style interface */ #endif /* __IUSB_INTERFACE_DEFINED__ */ #ifndef __USB2MatLib_LIBRARY_DEFINED__ #define __USB2MatLib_LIBRARY_DEFINED__ /* library USB2MatLib */ /* [version][uuid] */ EXTERN_C const IID LIBID_USB2MatLib; #ifndef ___IUSBEvents_DISPINTERFACE_DEFINED__ #define ___IUSBEvents_DISPINTERFACE_DEFINED__ /* dispinterface _IUSBEvents */ /* [uuid] */ EXTERN_C const IID DIID__IUSBEvents; #if defined(__cplusplus) && !defined(CINTERFACE) MIDL_INTERFACE("0e75bdde-9867-48aa-915a-c57277a22e43") _IUSBEvents : public IDispatch { }; #else /* C style interface */ typedef struct _IUSBEventsVtbl { BEGIN_INTERFACE HRESULT ( STDMETHODCALLTYPE *QueryInterface )( _IUSBEvents * This, /* [in] */ REFIID riid, /* [annotation][iid_is][out] */ _COM_Outptr_ void **ppvObject); ULONG ( STDMETHODCALLTYPE *AddRef )( _IUSBEvents * This); ULONG ( STDMETHODCALLTYPE *Release )( _IUSBEvents * This); HRESULT ( STDMETHODCALLTYPE *GetTypeInfoCount )( _IUSBEvents * This, /* [out] */ UINT *pctinfo); HRESULT ( STDMETHODCALLTYPE *GetTypeInfo )( _IUSBEvents * This, /* [in] */ UINT iTInfo, /* [in] */ LCID lcid, /* [out] */ ITypeInfo **ppTInfo); HRESULT ( STDMETHODCALLTYPE *GetIDsOfNames )( _IUSBEvents * This, /* [in] */ REFIID riid, /* [size_is][in] */ LPOLESTR *rgszNames, /* [range][in] */ UINT cNames, /* [in] */ LCID lcid, /* [size_is][out] */ DISPID *rgDispId); /* [local] */ HRESULT ( STDMETHODCALLTYPE *Invoke )( _IUSBEvents * This, /* [annotation][in] */ _In_ DISPID dispIdMember, /* [annotation][in] */ _In_ REFIID riid, /* [annotation][in] */ _In_ LCID lcid, /* [annotation][in] */ _In_ WORD wFlags, /* [annotation][out][in] */ _In_ DISPPARAMS *pDispParams, /* [annotation][out] */ _Out_opt_ VARIANT *pVarResult, /* [annotation][out] */ _Out_opt_ EXCEPINFO *pExcepInfo, /* [annotation][out] */ _Out_opt_ UINT *puArgErr); END_INTERFACE } _IUSBEventsVtbl; interface _IUSBEvents { CONST_VTBL struct _IUSBEventsVtbl *lpVtbl; }; #ifdef COBJMACROS #define _IUSBEvents_QueryInterface(This,riid,ppvObject) \ ( (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) ) #define _IUSBEvents_AddRef(This) \ ( (This)->lpVtbl -> AddRef(This) ) #define _IUSBEvents_Release(This) \ ( (This)->lpVtbl -> Release(This) ) #define _IUSBEvents_GetTypeInfoCount(This,pctinfo) \ ( (This)->lpVtbl -> GetTypeInfoCount(This,pctinfo) ) #define _IUSBEvents_GetTypeInfo(This,iTInfo,lcid,ppTInfo) \ ( (This)->lpVtbl -> GetTypeInfo(This,iTInfo,lcid,ppTInfo) ) #define _IUSBEvents_GetIDsOfNames(This,riid,rgszNames,cNames,lcid,rgDispId) \ ( (This)->lpVtbl -> GetIDsOfNames(This,riid,rgszNames,cNames,lcid,rgDispId) ) #define _IUSBEvents_Invoke(This,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr) \ ( (This)->lpVtbl -> Invoke(This,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr) ) #endif /* COBJMACROS */ #endif /* C style interface */ #endif /* ___IUSBEvents_DISPINTERFACE_DEFINED__ */ EXTERN_C const CLSID CLSID_USB; #ifdef __cplusplus class DECLSPEC_UUID("b0a07713-3940-4dee-940a-d8d2ac284272") USB; #endif #endif /* __USB2MatLib_LIBRARY_DEFINED__ */ /* Additional Prototypes for ALL interfaces */ unsigned long __RPC_USER BSTR_UserSize( unsigned long *, unsigned long , BSTR * ); unsigned char * __RPC_USER BSTR_UserMarshal( unsigned long *, unsigned char *, BSTR * ); unsigned char * __RPC_USER BSTR_UserUnmarshal(unsigned long *, unsigned char *, BSTR * ); void __RPC_USER BSTR_UserFree( unsigned long *, BSTR * ); unsigned long __RPC_USER LPSAFEARRAY_UserSize( unsigned long *, unsigned long , LPSAFEARRAY * ); unsigned char * __RPC_USER LPSAFEARRAY_UserMarshal( unsigned long *, unsigned char *, LPSAFEARRAY * ); unsigned char * __RPC_USER LPSAFEARRAY_UserUnmarshal(unsigned long *, unsigned char *, LPSAFEARRAY * ); void __RPC_USER LPSAFEARRAY_UserFree( unsigned long *, LPSAFEARRAY * ); unsigned long __RPC_USER BSTR_UserSize64( unsigned long *, unsigned long , BSTR * ); unsigned char * __RPC_USER BSTR_UserMarshal64( unsigned long *, unsigned char *, BSTR * ); unsigned char * __RPC_USER BSTR_UserUnmarshal64(unsigned long *, unsigned char *, BSTR * ); void __RPC_USER BSTR_UserFree64( unsigned long *, BSTR * ); unsigned long __RPC_USER LPSAFEARRAY_UserSize64( unsigned long *, unsigned long , LPSAFEARRAY * ); unsigned char * __RPC_USER LPSAFEARRAY_UserMarshal64( unsigned long *, unsigned char *, LPSAFEARRAY * ); unsigned char * __RPC_USER LPSAFEARRAY_UserUnmarshal64(unsigned long *, unsigned char *, LPSAFEARRAY * ); void __RPC_USER LPSAFEARRAY_UserFree64( unsigned long *, LPSAFEARRAY * ); /* end of Additional Prototypes */ #ifdef __cplusplus } #endif #endif
831129e882e9fefc18fb08471cd23b030693caf2
320bef0f77b0c24b189be687824c6d6a5a7f029e
/Jogador.cpp
ed56c94ae70abb2ec6e643fdfb718e30e0727666
[]
no_license
leovolpatto/bisca-test
35e144be49dbaba709bb4706a2bdaffba803a68a
bd284875feee9b907d69a703ef4a9394047b5595
refs/heads/master
2020-06-18T13:13:10.892541
2016-11-30T00:35:51
2016-11-30T00:35:51
75,135,296
0
0
null
null
null
null
UTF-8
C++
false
false
942
cpp
Jogador.cpp
#include "Jogador.h" Jogador::Jogador(std::string nome) { this->nome = nome; //this->cartas = std::list<Carta*>(); } Jogador::~Jogador() { } std::string Jogador::getNome() const { return this->nome; } Carta Jogador::jogar(Jogada& jogada) { } void Jogador::pescar(Baralho& baralho) { Carta* c = baralho.pescar(); this->receberCarta(c); } void Jogador::receberCarta(Carta* carta) { this->cartas.push_back(carta); std::cout << "recebeu " << std::addressof(carta) << " - " << carta->getNaipe() << " - " << carta->getNumero() << std::endl; } void Jogador::testar() { std::cout << this->nome << "-------------" << std::endl; std::list<Carta*> cartas = this->cartas; for (std::list<Carta*>::iterator it = cartas.begin(); it != cartas.end(); it++) { Carta* a = *it; std::cout << std::addressof(a) << " - " << a->getNaipe() << " - " << a->getNumero() << std::endl; } }
cd9b46571ab166a83e74cb5fa549769fffeb20e9
50d403d6e8e2fe0026e18edc812a8086acbd4a8e
/Assignment 3/stairclimber.cpp
e17e16cd5c059a5c55ad249bcd90dace14465d07
[]
no_license
NicholasColonna6/CS-385
d6713dbe8a4a50fd830ded8f95ee110910df9e36
2c4878d97007b77e68f2d8de786f89531bc351ff
refs/heads/master
2023-02-11T20:29:21.579653
2021-01-05T02:00:19
2021-01-05T02:00:19
326,843,458
0
0
null
null
null
null
UTF-8
C++
false
false
3,588
cpp
stairclimber.cpp
/******************************************************************************* * Name : stairclimber.cpp * Author : Nicholas Colonna * Date : 9/26/2018 * Description : Lists the number of ways to climb n stairs. * Pledge : "I pledge my honor that I have abided by the Stevens Honor System." -Nicholas Colonna ******************************************************************************/ #include <iostream> #include <vector> #include <algorithm> #include <sstream> #include <iomanip> using namespace std; vector<vector<int>> get_ways(int num_stairs) { //Return a vector of vectors of ints representing the different combinations of //ways to climb num_stairs stairs, moving up either 1, 2, or 3 stairs at a time. vector<vector<int>> ways; vector<vector<int>> result; if(num_stairs <= 0){ ways.push_back(vector<int>()); //add empty vector if can't add anymore stairs }else{ for(int i = 1; i<=3; i++){ //loop for each move type -- 1, 2, or 3 stairs if(num_stairs >= i){ //if its possible to move i stairs, do it result = get_ways(num_stairs - i); //recurse after making the move for(auto it = result.begin(); it != result.end(); ++it){ it->insert(it->begin(), i); //i to the solutions found } ways.reserve(ways.size() + result.size()); //reserve & insert found on stackoverflow ways.insert(ways.end(), result.begin(), result.end()); } } } return ways; } int num_digits(int num) { // Helper Function: Determines how many digits are in an integer // Divides num by 10 every time it loops and increments count to keep track of total digits int digits = 0; while(num >= 1){ num = num / 10; digits++; } return digits; } void display_ways(const vector<vector<int>> &ways) { // Display the ways to climb stairs by iterating over the vector of vectors and printing each combination. if((int)ways.size() < 10){ //if less than 10 ways, we want to left align for(int i=1; i<=(int)ways.size(); i++){ //loops through ways array cout << i << ". ["; for(int j=1; j<=(int)ways[i-1].size(); j++){ //loops through individual ways cout << ways[i-1][j-1]; if(j != (int)ways[i-1].size()){ cout << ", "; }else{ cout << "]" << endl; } } } }else{ //if 10 or greater ways, align right to widest number int max_width = num_digits((int)ways.size()); for(int i=1; i<=(int)ways.size(); i++){ //loops through ways array cout << setw(max_width) << i << ". ["; for(int j=1; j<=(int)ways[i-1].size(); j++){ //loops through individual ways cout << ways[i-1][j-1]; if(j != (int)ways[i-1].size()){ cout << ", "; }else{ cout << "]" << endl; } } } } } int main(int argc, char * const argv[]) { if(argc != 2){ //error if no input or too many input arguments are given cerr << "Usage: ./stairclimber <number of stairs>" << endl; return 1; } if(atoi(argv[1]) != (int)atoi(argv[1]) || atoi(argv[1]) <= 0){ //error if non-integer, zero or negative integer is given cerr << "Error: Number of stairs must be a positive integer." << endl; return 1; } int num_stairs = atoi(argv[1]); //atoi() conversion of character to int found on stackoverflow vector<vector<int>> ways = get_ways(num_stairs); if(num_stairs == 1){ //appropriate grammar if only 1 stair cout << ways.size() <<" way to climb " << num_stairs << " stair." << endl; display_ways(ways); }else{ //all other stair numbers cout << ways.size() << " ways to climb " << num_stairs << " stairs." << endl; display_ways(ways); } return 0; }
37bd11d7256e811bc683e06c5c984909fb95439b
1e9063402c285564b24d2abce4fcee01b16c4059
/Sorting and Searching/insertionSort.cpp
ddfa419d577faedd2174b94b53f7f02eb10e3eed
[]
no_license
LoggIT2001/Data_Structure_And_Algorithms_PTIT_2021
0628d0262486aee08e7ec3d58e986c026b48b3f0
da282f12db54d13e5e6642d91c11c3a503bcfa2f
refs/heads/master
2023-05-31T13:51:53.859740
2021-07-12T15:42:37
2021-07-12T15:42:37
385,298,353
1
0
null
null
null
null
UTF-8
C++
false
false
414
cpp
insertionSort.cpp
#include<iostream> #include<vector> #include<algorithm> using namespace std; int main(){ int n; cin >> n; int a[n+5]; for(int i=0;i<n;i++) cin >> a[i]; vector <int> b; for(int i=0;i<n;i++){ b.push_back(a[i]); sort(b.begin(),b.end()); cout << "Buoc " << i+1 << ": "; for(int j=0;j<b.size();j++) cout << b[j] <<" "; cout << endl; } return 0; }
80e01ab742c661fba7f03e9911f40a4151964a1a
9520f3776b9c4c5b8e2a45d626b6da461c3654ad
/src/snvcounts.cpp
c30b59c24847d926927440be71d94c91b813fabb
[]
no_license
putnamdk/VCF2CNA-Beta
a093fb57aba7c4482549351abdffe75ee1f3db4b
52a4082ad8b0ee84bbf76c0463f0d61c08a59a0e
refs/heads/main
2023-06-19T14:56:10.689495
2021-07-07T14:42:09
2021-07-07T14:42:09
320,370,016
0
0
null
null
null
null
UTF-8
C++
false
false
10,056
cpp
snvcounts.cpp
//------------------------------------------------------------------------------------ // // snvcounts.cpp - program that extracts mutant and total counts for SNVs in tumor and // normal samples from a Bambino output file ("high_20") or a file in // the Mutation Annotation Format (MAF); the output files written by // this program are inputs to the consprep program // // Author: Stephen V. Rice, Ph.D. // // Copyright 2016 St. Jude Children's Research Hospital // //------------------------------------------------------------------------------------ #include "genutil.h" const uint16_t MAX_COUNT = 65535; uint64_t occurrences; // number of normal coverage values uint64_t normalTotalCount[MAX_COUNT + 1]; // histogram of normal coverage values void compressCounts(int inMutant, int inTotal, uint16_t& outMutant, uint16_t& outTotal); // forward declaration //------------------------------------------------------------------------------------ class PosCounts // concisely stores the counts for one sample { public: PosCounts(int inTumorMutant, int inTumorTotal, int inNormalMutant, int inNormalTotal) { compressCounts(inTumorMutant, inTumorTotal, tumorMutant, tumorTotal); compressCounts(inNormalMutant, inNormalTotal, normalMutant, normalTotal); } uint16_t tumorMutant, tumorTotal, normalMutant, normalTotal; }; typedef std::map<int, PosCounts> PosMap; // key is position PosMap posmap[NUM_CHROMOSOMES + 1]; // one map for each chromosome //------------------------------------------------------------------------------------ class MAF_Parser // for parsing lines in Mutation Annotation Format (MAF) { public: MAF_Parser(const std::string& headingLine); virtual ~MAF_Parser() { } virtual bool parseLine(const std::string& line, std::string& chrName, int& position, std::string& variantType, int& tumorMutant, int& tumorTotal, int& normalMutant, int& normalTotal) const; //column numbers of columns of interest int chrCol, posCol, typeCol, tumorMutantCol, tumorTotalCol, normalMutantCol, normalTotalCol; int numColumns; }; //------------------------------------------------------------------------------------ // MAF_Parser::MAF_Parser() determines the column number of columns of interest by // parsing a heading line read from a MAF file MAF_Parser::MAF_Parser(const std::string& headingLine) : chrCol(-1), posCol(-1), typeCol(-1), tumorMutantCol(-1), tumorTotalCol(-1), normalMutantCol(-1), normalTotalCol(-1) { StringVector heading; getDelimitedStrings(headingLine, '\t', heading); numColumns = heading.size(); for (int i = 0; i < numColumns; i++) { std::string h = heading[i]; if (h == "Chromosome") chrCol = i; else if (h == "Start_Position" || h == "Start_position") posCol = i; else if (h == "Variant_Type" || h == "VariantType") typeCol = i; else if (h == "Tumor_ReadCount_Alt") tumorMutantCol = i; else if (h == "Tumor_ReadCount_Total") tumorTotalCol = i; else if (h == "Normal_ReadCount_Alt") normalMutantCol = i; else if (h == "Normal_ReadCount_Total") normalTotalCol = i; } if (chrCol < 0 || posCol < 0 || typeCol < 0 || tumorMutantCol < 0 || tumorTotalCol < 0 || normalMutantCol < 0 || normalTotalCol < 0) throw std::runtime_error("missing column(s) in MAF file"); } //------------------------------------------------------------------------------------ // MAF_Parser::parseLine() parses a non-heading line read from a MAF file bool MAF_Parser::parseLine(const std::string& line, std::string& chrName, int& position, std::string& variantType, int& tumorMutant, int& tumorTotal, int& normalMutant, int& normalTotal) const { StringVector value; getDelimitedStrings(line, '\t', value); if (value.size() != numColumns) return false; position = stringToInt(value[posCol]); tumorMutant = stringToInt(value[tumorMutantCol]); tumorTotal = stringToInt(value[tumorTotalCol]); normalMutant = stringToInt(value[normalMutantCol]); normalTotal = stringToInt(value[normalTotalCol]); if (position < 0 || tumorMutant < 0 || tumorTotal < 0 || normalMutant < 0 || normalTotal < 0) return false; // unable to convert strings to integers chrName = value[chrCol]; variantType = value[typeCol]; return true; } //------------------------------------------------------------------------------------ // compressCounts() converts counts from four-byte signed integers to two-byte // unsigned integers void compressCounts(int inMutant, int inTotal, uint16_t& outMutant, uint16_t& outTotal) { if (inMutant > inTotal) inMutant = inTotal; if (inTotal > MAX_COUNT) // count is too large to fit in two bytes { // proportionally reduce the mutant count so that the ratio of mutant/total // is preserved inMutant = roundit(MAX_COUNT * static_cast<double>(inMutant) / inTotal); inTotal = MAX_COUNT; } outMutant = static_cast<uint16_t>(inMutant); outTotal = static_cast<uint16_t>(inTotal); } //------------------------------------------------------------------------------------ // readFile() reads a Bambino output file or MAF file and stores the position data // in an array of maps void readFile(const std::string& filename) { BambinoParserTumor *bp = NULL; MAF_Parser *mp = NULL; std::ifstream infile(filename.c_str()); if (!infile.is_open()) throw std::runtime_error("unable to open " + filename); std::string line; if (!std::getline(infile, line)) throw std::runtime_error("empty file " + filename); // examine the heading line to see what kind of file it is try { bp = new BambinoParserTumor(line); } catch (const std::runtime_error&) { } if (!bp) // it is not a Bambino output file { try { mp = new MAF_Parser(line); } catch (const std::runtime_error&) { } } if (!bp && !mp) throw std::runtime_error("unrecognized file format in " + filename); // now read the file while (std::getline(infile, line)) { std::string chrName, type, ref, alt, tumorSample; int position, tumorRef, tumorMutant, tumorTotal, normalRef, normalMutant, normalTotal; if (bp && bp->parseLine(line, chrName, position, type, ref, alt, normalRef, normalMutant, tumorRef, tumorMutant, tumorSample)) { tumorTotal = tumorRef + tumorMutant; normalTotal = normalRef + normalMutant; } else if (mp && mp->parseLine(line, chrName, position, type, tumorMutant, tumorTotal, normalMutant, normalTotal)) { } else throw std::runtime_error("unable to parse line in " + filename + " \"" + line + "\""); int chrnum; if (type != "SNP" || (chrnum = getChrNumber(chrName)) == 0) continue; // this is not an SNV or this is an unrecognized chromosome PosMap& pmap = posmap[chrnum]; // get the map for this chromosome if (pmap.find(position) == pmap.end()) // this position is not already in map { pmap.insert(std::make_pair(position, PosCounts(tumorMutant, tumorTotal, normalMutant, normalTotal))); occurrences++; if (normalTotal > MAX_COUNT) normalTotalCount[MAX_COUNT]++; else normalTotalCount[normalTotal]++; } } if (infile.bad()) throw std::runtime_error("read error in " + filename); infile.close(); delete bp; delete mp; } //------------------------------------------------------------------------------------ // writeCounts() writes the counts in order by chromosome and position void writeCounts(const std::string& filename) { std::ofstream outfile(filename.c_str()); if (!outfile.is_open()) throw std::runtime_error("unable to open " + filename); outfile << "Chr" << "\t" << "Pos" << "\t" << "TumorMutant" << "\t" << "TumorTotal" << "\t" << "NormalMutant" << "\t" << "NormalTotal" << std::endl; for (int chrnum = 1; chrnum <= NUM_CHROMOSOMES; chrnum++) { PosMap& pmap = posmap[chrnum]; for (PosMap::iterator ppos = pmap.begin(); ppos != pmap.end(); ++ppos) outfile << chrLongName[chrnum] << "\t" << ppos->first << "\t" << ppos->second.tumorMutant << "\t" << ppos->second.tumorTotal << "\t" << ppos->second.normalMutant << "\t" << ppos->second.normalTotal << "\n"; } outfile.close(); } //------------------------------------------------------------------------------------ // writeMedian() computes and writes the median normal coverage void writeMedian(const std::string& filename) { uint64_t half = (occurrences + 1) / 2; uint64_t count = normalTotalCount[0]; int i = 0; while (count < half) count += normalTotalCount[++i]; std::ofstream outfile(filename.c_str()); if (!outfile.is_open()) throw std::runtime_error("unable to open " + filename); outfile << i << std::endl; // write the median normal coverage outfile.close(); } //------------------------------------------------------------------------------------ int main(int argc, char *argv[]) { if (argc != 4) { std::cout << "Usage: " << argv[0] << " inputfile" << " snvcounts_outputfile" << " median_outputfile" << std::endl; return 1; } try { std::string infilename = argv[1]; std::string cntfilename = argv[2]; std::string medfilename = argv[3]; readFile(infilename); writeCounts(cntfilename); writeMedian(medfilename); } catch (const std::runtime_error& error) { std::cerr << argv[0] << ": " << error.what() << std::endl; return 1; } return 0; }
7b9eecdb7d8bebaedb1438f5507195557e6fec18
b756f49e50c5e833435b0fddd98cb4d3bbf896c3
/XCard/MainTest/ServerCommonPart.cpp
29914b6615cdfd58175b143e879489c277bd1474
[]
no_license
sword2ya/XCard
26bd6c2700c308d53baa79d06f26ebf947834c53
70f9536aab36bfc9fd7823419e7db5900c89a8d0
refs/heads/master
2021-01-01T16:09:45.452788
2017-08-03T03:27:25
2017-08-03T03:27:25
97,782,717
1
0
null
null
null
null
GB18030
C++
false
false
1,638
cpp
ServerCommonPart.cpp
#include "StdAfx.h" #include "ServerCommonPart.h" #include "ServerSession.h" using namespace csmsg; CServerCommonPart::CServerCommonPart(void) { m_pServerSession = NULL; } CServerCommonPart::~CServerCommonPart(void) { } void CServerCommonPart::HandlerMsg(const csmsg::TCSMessage* pMsg ) { csmsg::ECSMessageID eMsgID = pMsg->emsgid(); switch (eMsgID) { case eMsgID_LoginReq: __HandlerLoginReq(pMsg); } } bool CServerCommonPart::Create( CServerSession* pServerSession ) { if (NULL == pServerSession) { return false; } m_pServerSession = pServerSession; return true; } size_t CServerCommonPart::GetLoginReqCount() { return m_vtLoginReq.size(); } bool CServerCommonPart::GetLoginReqByIndex( size_t nIdx, string& strUserName, string& strPsw, DWORD& dwUserData ) { if (nIdx >= m_vtLoginReq.size()) { return false; } TLoginReq &stLoginReq = m_vtLoginReq[nIdx]; strUserName = stLoginReq.strUserName; strPsw = stLoginReq.strPsw; dwUserData = stLoginReq.dwUserData; return true; } void CServerCommonPart::ClearLoginReq() { m_vtLoginReq.clear(); } void CServerCommonPart::__HandlerLoginReq( const csmsg::TCSMessage* pMsg ) { if (!pMsg->has_stloginreq()) { Error(__FUNCTION__<<" 登录请求结构未定义"); return; } const csmsg::TMSG_LOGIN_REQ& stLoginReq = pMsg->stloginreq(); const string& strUserName = stLoginReq.strusername(); const string& strPsw = stLoginReq.strpassword(); int nUserData = stLoginReq.nuserdata(); TLoginReq stLoginData; stLoginData.strUserName = strUserName; stLoginData.strPsw = strPsw; stLoginData.dwUserData = nUserData; m_vtLoginReq.push_back(stLoginData); }
39b2f3aec45a4101252d60350f648007e914f28e
28fcb6ba57895c593b031224a5b2d3e2d68456c3
/pe/analyzers/vb_analyzer.h
2eb75674d3cd3482e173d2f22e2a78a5fe544866
[ "MIT" ]
permissive
REDasmOrg/REDasm-Loaders
48751074becba3deeee9473f7d9211aea22f2f1c
b401849f9aa54dfd9562aed1a6d2e03f75ac455f
refs/heads/master
2022-05-20T11:32:15.533134
2022-04-13T19:54:47
2022-04-13T19:54:47
190,985,757
4
4
null
null
null
null
UTF-8
C++
false
false
709
h
vb_analyzer.h
#pragma once #include "../vb/vb_header.h" class PELoader; class VBAnalyzer { public: VBAnalyzer(RDContext* ctx, PELoader* peloader); void analyze(); private: void disassembleTrampoline(rd_address eventva, const std::string &name); void decompileObject(const VBPublicObjectDescriptor& pubobjdescr); bool decompile(rd_address thunrtdata); private: PELoader* m_peloader; RDContext* m_context; VBHeader* m_vbheader{nullptr}; VBProjectInfo* m_vbprojinfo{nullptr}; VBObjectTable* m_vbobjtable{nullptr}; VBObjectTreeInfo* m_vbobjtreeinfo{nullptr}; VBPublicObjectDescriptor* m_vbpubobjdescr{nullptr}; };
87d00c91cda61ff72c9e0bcfb415b753a86f1e72
364f7d17c4f024c39c47c99bda284bacb913d470
/sci_gateway/cpp/opencv_convolver.cpp
8a5d289098dbebf7507058379851ab5b2d17b61a
[]
no_license
msharsha/FOSSEE-Image-Processing-Toolbox
6ce7bafc187b99b9e01d1eedcc09a11c3a80370d
f8b16bc3329f9186a3b362f29d9a40d20b48cfd4
refs/heads/master
2020-12-02T07:55:57.553927
2017-07-10T07:41:21
2017-07-10T07:41:21
96,747,260
0
0
null
2017-07-10T07:14:37
2017-07-10T07:14:37
null
UTF-8
C++
false
false
4,872
cpp
opencv_convolver.cpp
/****************************************************************************************** *Author : Kevin George , Manoj Sree Harsha * *-> To execute, Image = convolver(I1, size, values,scalar) * where 'I1' is image to be convoluted, * where 'size' is size of kernel i.e size x size gives total no. of values in kernel, * where 'values' contains the values of the kernel * where 'scalar' is a float value * *******************************************************************************************/ #include <numeric> #include <string.h> #include "opencv2/core/core.hpp" #include "opencv2/highgui/highgui.hpp" #include "opencv2/opencv.hpp" #include "opencv2/imgproc/imgproc.hpp" #include "opencv2/features2d/features2d.hpp" #include <iostream> #include <math.h> #include <vector> using namespace cv; using namespace std; extern "C" { #include "api_scilab.h" #include "Scierror.h" #include "BOOL.h" #include <localization.h> #include "sciprint.h" #include "../common.h" int opencv_convolver(char *fname, unsigned long fname_len) { //-> Error Management variables SciErr sciErr; int intErr=0; //-> Mat containers for images Mat image_1; Mat image_2; //-> Address of Various Arguments int *piAddr = NULL; //-> Local Variables double *values1 = NULL; float *values2 =NULL; double size; double scalar; int iRows = 0; int iCols = 0; int *outList = NULL; unsigned char *red = NULL; unsigned char *green = NULL; unsigned char *blue = NULL; //-> Checks the number of arguments //-> pvApiCtx is a Scilab environment pointer CheckInputArgument(pvApiCtx, 4, 4); //Check on Number of Input Arguments CheckOutputArgument(pvApiCtx, 1, 1); //Check on Number of Output Arguments //-> Read Image retrieveImage( image_1, 1); //-> Taking in size of kernel sciErr = getVarAddressFromPosition(pvApiCtx, 2, &piAddr); if (sciErr.iErr) { printError(&sciErr, 0); return 0; } intErr = getScalarDouble(pvApiCtx, piAddr, &size); if(intErr) { return intErr; } if(size!=3 && size != 4 && size !=5) { Scierror(999," Invalid Value size. Please enter a non negative Double value\\n"); return 0; } //-> Taking the kernel values sciErr = getVarAddressFromPosition(pvApiCtx, 3, &piAddr); if (sciErr.iErr) { printError(&sciErr, 0); return 0; } sciErr = getMatrixOfDouble(pvApiCtx, piAddr, &iRows, &iCols, &values1); if(sciErr.iErr) { printError(&sciErr, 0); return 0; } if(iRows*iCols!=9 && iRows*iCols!=16 && iRows*iCols!=25 ) { Scierror(999,"Invalid Argument\n"); return 0; } values2 = (float*)malloc(sizeof(float)*size*size); for(int i=0; i<size*size; i++) { values2[i] = (float)values1[i]; } //-> Taking scalar values sciErr = getVarAddressFromPosition(pvApiCtx, 4, &piAddr); if (sciErr.iErr) { printError(&sciErr, 0); return 0; } intErr = getScalarDouble(pvApiCtx, piAddr, &scalar); if(intErr) { return intErr; } if( scalar == 0) { Scierror(999," Invalid scalar value. Please enter a non negative Double value\\n"); return 0; } //Application Code try { Mat kernel(size,size,CV_32F, values2); Mat kernel2 = kernel/ (float)(scalar); Point anchor; double delta; int ddepth; anchor = Point( -1, -1 ); delta = 0; ddepth = -1; filter2D(image_1, image_2, ddepth,kernel2,anchor,delta, BORDER_DEFAULT); //returning final image string tempstring = type2str(image_2.type()); char *checker; checker = (char *)malloc(tempstring.size() + 1); memcpy(checker, tempstring.c_str(), tempstring.size() + 1); returnImage(checker,image_2,1); free(checker); } catch(cv::Exception& e) { const char* err=e.what(); Scierror(999,("%s"),err); } //Assigning output variables AssignOutputVariable(pvApiCtx, 1) = nbInputArgument(pvApiCtx) + 1; //Returning the Output Variables as arguments to the Scilab environment ReturnArguments(pvApiCtx); return 0; } }
3a9290eacc0fdc216f50b11b9a2d760dc1eea224
f2bb0f4f51f8b08dde295436f850f2284e49ac5e
/chatserver.cpp
fb2ffb82e4c7eefb9cabdcdb4f3916accbc1e555
[]
no_license
luayalshawi/qml-chat-demo
5c3027df089f9d9734b2985b8d98e1a7da2831c2
290f3cabb8610f0a215960b8e24c07ecf576cfa3
refs/heads/master
2021-05-09T23:42:36.857904
2018-01-24T19:39:06
2018-01-24T19:39:06
118,805,675
0
0
null
null
null
null
UTF-8
C++
false
false
707
cpp
chatserver.cpp
#include <QtDebug> #include "chatserver.h" ChatServer::ChatServer(QObject *parent) : QObject(parent) { } void ChatServer::registerUser(QString user){ qInfo() <<"C++ Backend: "<< user << "I am in registerUser\n" ; // map can be better used on a real chat application // since it's useful to keep track of logged in users // if this approach is fully used then there should be // another emitter to remove the user from the map // this->clients.insert(user,user); } void ChatServer::sendMessage(QString sender,QString receiver, QString msg){ qInfo() << "C++ Backend: sendMessage\n" ; if( !(msg.isNull() || msg.isEmpty()) ){ emit update(sender,receiver,msg); } }
9cca1ccc296604ccdfd1430a9ee1f1b6e8519c4b
3b5dcd8c97cf0b128ff4571f616e6f93cde4d14f
/src-qt3/FE/DialogManager/AutoDialog/Dialogs/memberWidget.cpp
5b925ce187c7d1d5b79ebeea5ac393a4e38fea40
[]
no_license
jeez/iqr
d096820360516cda49f33a96cfe34ded36300c4c
c6e066cc5d4ce235d4399ca34e0b238d7784a7af
refs/heads/master
2021-01-01T16:55:55.516919
2011-02-10T12:00:01
2011-02-10T12:00:01
1,109,194
1
0
null
null
null
null
UTF-8
C++
false
false
3,721
cpp
memberWidget.cpp
#include "memberWidget.h" #include <iostream> iqrfe::ClsMemberWidget::ClsMemberWidget(QWidget *parent, string _strName, bool _bModal, string _strValue, list<string> lstValues) : QGroupBox(parent, _strName.c_str()), strName(_strName), bModal(_bModal), strValue(_strValue) { bValueChanged = false; QGridLayout *pqlayLayout = new QGridLayout(this, 3, 3, 5, 0, strName.c_str()); setTitle(strName.c_str()); QLabel *qlblText0 = new QLabel(this, "current_type"); qlblText0->setText("current type:"); qlblValue = new QLabel(this, strName.c_str()); qlblValue->setText(strValue.c_str()); qpb = new QPushButton("edit", this, "edit"); qpb->setToggleButton(true); connect(qpb, SIGNAL(clicked()), this, SLOT(buttonClick())); QLabel *qlblText1 = new QLabel(this, "set_type"); qlblText1->setText("set type:"); qcombo = new QComboBox(false, this, "combo box"); if(strValue.size()<=0){ qcombo->insertItem(QString("")); qpb->setEnabled(false); } list<string>::iterator it; for (it = lstValues.begin(); it != lstValues.end(); ++it) { qcombo->insertItem((*it).c_str()); } qcombo->setCurrentText(strValue.c_str()); connect(qcombo, SIGNAL(activated(const QString &)), this, SLOT(setValueChanged(const QString &))); // pqlayLayout->addMultiCellWidget(qlblText0, 0, 0, 0, 2); pqlayLayout->addWidget(qlblText0, 1, 0); pqlayLayout->addWidget(qlblValue, 1, 1); pqlayLayout->addWidget(qpb, 1, 2); pqlayLayout->addWidget(qlblText1, 2, 0); pqlayLayout->addMultiCellWidget(qcombo, 2, 2, 1, 2); }; void iqrfe::ClsMemberWidget::buttonClick() { // cout << "ClsMemberWidget::buttonClick()" << endl; if(qlblValue->text().length()>0){ if(qpb->state()==QButton::On){ // cout << "show Member" << endl; toggleEdit(false); emit toggleMemberEdit(strName, qlblValue->text().latin1(), ClsMemberWidget::SHOW); } else { // cout << "hide Member" << endl; toggleEdit(true); emit toggleMemberEdit(strName, qlblValue->text().latin1(), ClsMemberWidget::HIDE); } } else { qpb->setOn(false); } } void iqrfe::ClsMemberWidget::toggleEdit(bool b) { qcombo->setEnabled(b); if(b){ qpb->setText("edit"); qpb->setOn(false); } else { qpb->setText("hide"); qpb->setOn(true); } } void iqrfe::ClsMemberWidget::slotSelectorEnabled(bool b) { // cout << "iqrfe::ClsMemberWidget::slotSelectorEnabled(bool b)" << endl; qcombo->setEnabled(b); } void iqrfe::ClsMemberWidget::slotEditEnabled(bool b) { /* this is a bit obscure, but we have to make sure, we don not enable the button if the label is empty */ if(b && qlblValue->text().length()>0){ qpb->setEnabled(true); } else { qpb->setEnabled(false); } } void iqrfe::ClsMemberWidget::setValueChanged(const QString & qstrValue) { // cout << "ClsMemberWidget::setValueChanged(QString)" << qstrValue.latin1() << endl; strValue = qstrValue.latin1(); bValueChanged = true; /* cout << "strValue.size(): " << strValue.size() << endl; cout << "qlblValue->text().length(): " << qlblValue->text().length() << endl; */ if(qlblValue->text().length()>0){ qpb->setEnabled(true); } else { qpb->setEnabled(false); } emit sigChanged(); } void iqrfe::ClsMemberWidget::setValue(string _strValue) { // cout << "ClsMemberWidget::setValue(string _strValue)" << endl; strValue = _strValue; qlblValue->setText(strValue.c_str()); if(strValue.size()>0){ qpb->setEnabled(true); } else { qpb->setEnabled(false); } } //// Local Variables: //// mode: c++ //// compile-command: "cd ../ && make -k -j8" //// End:
18bee65cb54992ec90b6105669cc96f88edfca04
4a6e83f655843c8057e063d9edfbc4321bafa3d3
/DP/maxMoneyLooted.cpp
a4c530a475ec3c12854f27bd1a4778bb5252af91
[]
no_license
capchitts/Coding
5c5edcdbee5af4e863ed00f0ef0c873a72c1ff6c
a38e05e10965695fd26b4dbed8ddaf2840302d44
refs/heads/master
2023-05-04T21:01:20.925665
2021-06-01T06:12:57
2021-06-01T06:12:57
355,104,113
0
0
null
null
null
null
UTF-8
C++
false
false
1,073
cpp
maxMoneyLooted.cpp
/* *TC --> O(2^n) *SC --> O(1) */ int maxMoneyLooted_BF(int *arr, int n) { //Write your code here if(n <=0) return 0; //Decision return max(arr[n-1]+maxMoneyLooted_BF(arr,n-2),maxMoneyLooted_BF(arr,n-1)); } /* *TC --> O(n) *SC --> O(n) */ int maxMoneyLooted_Mem(int *arr, int n, int *dp) { if(n<=0) return 0; if(dp[n]!=-1) return dp[n]; dp[n] = max(arr[n-1]+maxMoneyLooted_Mem(arr,n-2,dp),maxMoneyLooted_Mem(arr,n-1,dp)); return dp[n]; } int maxMoneyLooted(int *arr, int n) { //Write your code here //Initialization int *dp = new int[n+1]; for(int i = 0;i<=n;i++) { dp[i] = -1; } return maxMoneyLooted_Mem(arr,n,dp); } /* *TC --> O(n) *SC --> O(n) */ int maxMoneyLooted_DP(int *arr, int n) { //Write your code here //Initialization int *dp = new int[n]; dp[0] = arr[0]; dp[1] = arr[1]; for(int i = 2;i<n;i++) { dp[i] = max(arr[i]+dp[i-2], dp[i-1]); } return dp[n-1]; }
63ea7ea845151a96de47844eae702ec93ebe287a
72e95df33ab3fb6bba03a81867b77b755f46bb66
/irohad/ametsuchi/impl/postgres_options.hpp
35ee7dc3a458a2d947fe7ed7f8afdd6d986577cb
[ "Apache-2.0", "CC-BY-4.0" ]
permissive
hyperledger/iroha
f07a81389fe1d3c488968919ab9196c548048f3a
f2d96e3050a504a982b983d8061588d8c650c5ad
refs/heads/main
2023-09-06T00:40:53.092106
2023-09-01T17:37:08
2023-09-01T17:37:08
67,340,575
1,125
419
Apache-2.0
2019-04-16T17:26:30
2016-09-04T11:17:53
C++
UTF-8
C++
false
false
2,770
hpp
postgres_options.hpp
/** * Copyright Soramitsu Co., Ltd. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0 */ #ifndef IROHA_POSTGRES_OPTIONS_HPP #define IROHA_POSTGRES_OPTIONS_HPP #include <unordered_map> #include "common/result.hpp" #include "logger/logger_fwd.hpp" namespace iroha { namespace ametsuchi { /** * Type for convenient formatting of PostgreSQL connection strings. */ class PostgresOptions { public: /** * @param pg_opt The connection options string. * @param default_dbname The default name of database to use when one is * not provided in pg_opt. * @param log Logger for internal messages. * * TODO 2019.06.07 mboldyrev IR-556 remove this constructor */ PostgresOptions(const std::string &pg_opt, std::string default_dbname, logger::LoggerPtr log); /** * @param host PostgreSQL host. * @param port PostgreSQL port. * @param user PostgreSQL username. * @param password PostgreSQL password. * @param working_dbname The name of working database. * @param maintenance_dbname The name of database for maintenance * purposes. It will not be altered in any way and is used to manage * working database. * @param log Logger for internal messages. */ PostgresOptions(const std::string &host, uint16_t port, const std::string &user, const std::string &password, const std::string &working_dbname, const std::string &maintenance_dbname, logger::LoggerPtr log); /// @return connection string without dbname param std::string connectionStringWithoutDbName() const; /// @return connection string to working database std::string workingConnectionString() const; /// @return connection string to maintenance database std::string maintenanceConnectionString() const; /// @return working database name std::string workingDbName() const; /// @return maintenance database name std::string maintenanceDbName() const; /// @return prepared block name const std::string &preparedBlockName() const; private: std::string getConnectionStringWithDbName( const std::string &dbname) const; const std::string host_; const uint16_t port_; const std::string user_; const std::string password_; const std::string working_dbname_; const std::string maintenance_dbname_; const std::string prepared_block_name_; }; } // namespace ametsuchi } // namespace iroha #endif // IROHA_POSTGRES_OPTIONS_HPP
4a75c490e3871a24568dbc0393d944580877afc2
f713bb3150fe164dbac3e94e2278d0ff2e7c2f24
/ESP32/RidesTracker/components/ble/bluetooth.cpp
8b048390bd670f8f7ccc9026f1688969600bc34e
[]
no_license
lkubecka/IoT
3fcb37bcb511614ac75af9b597dd8c493ef8a584
3fc66258bf19ac60a77626a104c4c94ab59f7c3f
refs/heads/master
2020-12-24T12:01:35.084240
2018-06-22T20:11:43
2018-06-22T20:11:43
73,098,586
0
0
null
null
null
null
UTF-8
C++
false
false
4,358
cpp
bluetooth.cpp
#define __USE_BLUETOOTH_ #ifdef __USE_BLUETOOTH_ #include <BLEDevice.h> #include <BLEUtils.h> #include <BLEServer.h> #include <BLE2902.h> #include <Arduino.h> #include "record.hpp" #include "time.hpp" #include <sstream> #include "esp_log.h" #include "bluetooth.hpp" using namespace kalfy; constexpr char BLE::SERVICE_UUID[]; constexpr char BLE::CHARACTERISTIC_HAS_DATA_UUID[]; constexpr char BLE::CHARACTERISTIC_SEND_DATA_UUID[]; constexpr char BLE::CHARACTERISTIC_TIME_UUID[]; constexpr int BLE::MAX_BLE_PACKET_SIZE; constexpr char BLE::DESCRIPTOR_HAS_DATA[]; constexpr char BLE::DESCRIPTOR_SEND_DATA[]; constexpr char BLE::DESCRIPTOR_TIME[]; bool BLE::_BLEClientConnected = false; bool BLE::_transferRequested = false; BLE::BLE(const char* filename) : _filename(filename), _secondsPassed(0), _hasDataCharacteristic(CHARACTERISTIC_HAS_DATA_UUID, BLECharacteristic::PROPERTY_READ), _hasDataDescriptor(DESCRIPTOR_HAS_DATA), _sendDataCharacteristic(CHARACTERISTIC_SEND_DATA_UUID, BLECharacteristic::PROPERTY_WRITE | BLECharacteristic::PROPERTY_INDICATE), _sendDataDescriptor(DESCRIPTOR_SEND_DATA), _timeCharacteristic(CHARACTERISTIC_TIME_UUID, BLECharacteristic::PROPERTY_WRITE | BLECharacteristic::PROPERTY_READ), _timeDescriptor(DESCRIPTOR_TIME) { } void BLE::_init(void) { ESP_LOGI(TAG, "BLE Starting"); BLEDevice::init("RidesTrack device"); BLEDevice::setMTU(MAX_BLE_PACKET_SIZE + 3); // 517 maximum allowed by BLE spec, but ESP32 allows only 514 (3 bytes seem to be reserved): https://github.com/espressif/esp-idf/blob/a4fe12cb6d195a580a57690ceed45e1e06dc58e0/components/bt/bluedroid/stack/gatt/att_protocol.c#L324 // Create the BLE Server BLEServer *pServer = BLEDevice::createServer(); pServer->setCallbacks(new MyServerCallbacks()); // Create the BLE Service BLEService *service = pServer->createService(SERVICE_UUID); // Add hasData Characteristic service->addCharacteristic(&_hasDataCharacteristic); _hasDataDescriptor.setValue(std::string("Has data (true/false)?")); _hasDataCharacteristic.addDescriptor(&_hasDataDescriptor); _hasDataCharacteristic.setValue(std::string("false")); // Add sendData Characteristic service->addCharacteristic(&_sendDataCharacteristic); _sendDataDescriptor.setValue(std::string("Send data")); _sendDataCharacteristic.addDescriptor(&_sendDataDescriptor); _sendDataCharacteristic.addDescriptor(new BLE2902()); _sendDataCharacteristic.setValue(std::string("false")); _sendDataCharacteristic.setCallbacks(new SendDataCharacteristicCallbacks()); // Add time Characteristic service->addCharacteristic(&_timeCharacteristic); _timeDescriptor.setValue(std::string("Set time")); std::string time; std::stringstream strstream; strstream << kalfy::time::getCurrentTime().tv_sec; strstream >> time; _timeCharacteristic.setValue(time); _timeCharacteristic.addDescriptor(&_timeDescriptor); _timeCharacteristic.setCallbacks(new TimeCharacteristicCallbacks()); pServer->getAdvertising()->addServiceUUID(SERVICE_UUID); service->start(); // Start advertising pServer->getAdvertising()->start(); ESP_LOGI(TAG, "BLE Started"); } void BLE::_transferFile() { ESP_LOGI(TAG, "starting file transfer"); File record = kalfy::record::openRecordForUpload(_filename.c_str()); char sizeBuffer[MAX_BLE_PACKET_SIZE]; snprintf(sizeBuffer, MAX_BLE_PACKET_SIZE, "%u", record.size()); _sendDataCharacteristic.setValue(std::string(sizeBuffer)); _sendDataCharacteristic.indicate(); uint8_t buffer[20]; size_t bytesRead = 1; while ((bytesRead = record.read(buffer, MAX_BLE_PACKET_SIZE)) > 0) { ESP_LOGI(TAG, "transferring %u bytes\n", bytesRead); _sendDataCharacteristic.setValue(buffer, bytesRead); _sendDataCharacteristic.indicate(); } ESP_LOGI(TAG, "file transfer complete"); kalfy::record::uploadSucceeded(record, _filename.c_str()); // deletes the underlying file } void BLE::run() { _init(); _hasDataCharacteristic.setValue(kalfy::record::hasData(_filename.c_str()) ? std::string("true") : std::string("false")); while (_secondsPassed < 60 || _transferRequested) { ESP_LOGI(TAG, "_secondsPassed: %d, _transferring: %d, _BLEClientConnected: %d\n", _secondsPassed, _transferRequested, _BLEClientConnected); if (_transferRequested) { _transferFile(); return; } delay(1000); _secondsPassed++; } ESP_LOGI(TAG, "BLE koncim"); } #endif
f78bfa5da6c6fb1c430ed4f14c7110cc4c386fe1
65ed7427063f2ccb82a1b519e1f2929eb01ebd8e
/08_receptor_rtp/h264rtpdepacketizer.cc
3d324ab4d7ffb6eb94e09c29c842f6972d46e250
[]
no_license
EdiiDD/Comul
cfa751e80485ca4d984aa6b2d7987076e1c6a369
d0cec41c8fe99f30fd0780c3a9d4d906371b6d24
refs/heads/master
2021-11-04T01:52:12.496850
2019-04-27T12:04:06
2019-04-27T12:04:06
183,765,180
0
0
null
null
null
null
UTF-8
C++
false
false
2,624
cc
h264rtpdepacketizer.cc
#include "h264rtpdepacketizer.h" #include <unistd.h> bool H264RTPDepacketizer::init(uint16_t fps, RTPReceiver *receiver) { #ifdef GEN_FILE fout = fopen("recv.264","wb"); #endif period = 90000/fps; this->receiver = receiver; firstTS = 0; seqNum = 0; parar = false; frame = NULL; frame_size = 0; first_packet = true; return true; } bool H264RTPDepacketizer::receive(uint8_t **buffer, uint32_t *size, int64_t *pts) { const uint8_t *payload; uint32_t payload_size; while(!parar) { if (!receiver->getPayloadData()) { // No hay paquete RTP disponible. // Compruebo si el otro extremo sigue emitiendo... if (receiver->isClosed()) // Ha cerrado el otro extremo. return false; // No se tiene constancia de que el otro extremo haya cerrado. // Intento obtener un paquete RTP nuevo... if (!receiver->receive()) { // No lo he conseguido. Espero el minimo posible antes de reintentar usleep(1); } else { // Recibido un paquete. Imprimo su TS printf("TS: %u SN: %u Size: %u\n",receiver->getTimestamp(),receiver->getSeqNum(), receiver->getPayloadSize()); } } else { // Hay un paquete RTP disponible if (first_packet) { // Primer paquete firstTS = timestamp = receiver->getTimestamp(); first_packet = false; } payload = receiver->getPayloadData(); payload_size = receiver->getPayloadSize(); // Compruebo si es del mismo frame if (timestamp == receiver->getTimestamp()) { // Mismo frame frame = (uint8_t *)realloc(frame,frame_size+1+payload_size); frame[frame_size++] = 0x00; frame[frame_size++] = 0x00; frame[frame_size++] = 0x00; frame[frame_size++] = 0x01; memcpy(frame + frame_size, payload + 3,payload_size - 3); frame_size += payload_size - 3; // Sólo liberar porque es el mismo frame receiver->freePacket(); } else { // Distinto frame: devolver *buffer = frame; *size = frame_size; *pts = (timestamp-firstTS)/period; #ifdef GEN_FILE fwrite(frame,frame_size,1,fout); fflush(fout); #endif // Actualizo datos para siguiente frame timestamp = receiver->getTimestamp(); frame_size = 0; frame = NULL; return true; } } } return false; } void H264RTPDepacketizer::close() { // Do nothing #ifdef GEN_FILE fclose(fout); #endif } void H264RTPDepacketizer::stop() { parar = true; } uint32_t H264RTPDepacketizer::getClock() { return RTPCLOCK; }
217a51d82606c6309c60815ab7f9cefcd8702c45
faa7283bb1832070b5a31344e91f01933b35d53f
/src/DbFilter.h
0e3387bab2cd86c737a824c3aaf68c3cffbc61fb
[]
no_license
qqiezhian/litedb
5d3b50478d7c1e270e40ab72b280d042cba31ad6
ef808d040c695c0c0b4262ecab1ae25c0f5ca161
refs/heads/master
2021-04-03T10:28:54.135437
2018-03-25T13:34:25
2018-03-25T13:34:25
124,757,258
1
0
null
null
null
null
UTF-8
C++
false
false
760
h
DbFilter.h
#ifndef LITEDB_DBFILTER_H #define LITEDB_DBFILTER_H #endif #include "dbtype.h" #include "Slice.h" #include <iostream> using namespace std; namespace litedb { class DbFilter { public: DbFilter():m_(0), k_(0), bits_(NULL), seeds_(0) {} DbFilter(uint m, uint k); void insertEle(Key& key); bool checkEle(Key& key); private: uint m_; uint k_; uchar* bits_; uint* seeds_; void init_seeds(); void setBit(uint i); bool getBit(uint i); uint BKDR_Hash(uint hashIdx, Key& key); }; inline void DbFilter::setBit(uint i) { //uint byteSeq = i / 8; //uint bitSeq = i % 8; bits_[i / 8] |= 0x1 << (i % 8); } inline bool DbFilter::getBit(uint i) { //uint byteSeq = i / 8; //uint bitSeq = i % 8; return (0 != (bits_[i / 8] & (0x1 << (i % 8)))); } }
bb25e05a298d38123cf861ef9dc61851eec30152
e967d490962965e7f84028f500018b3687c57065
/facedetector.cpp
005b6b08be8568529a1fe3dcc35766bc2e2b76cf
[]
no_license
Sergimech/RoboticaUVic-FaceDetect
da011223e444225fc50569a7e7f660566e06aff9
c45b30bf7a6ebb23640643dc291e160e970448a8
refs/heads/master
2020-06-12T21:33:21.629871
2016-12-29T14:54:36
2016-12-29T14:54:36
75,505,739
0
0
null
2016-12-03T23:12:03
2016-12-03T23:12:03
null
UTF-8
C++
false
false
3,268
cpp
facedetector.cpp
//Face Detector C++ code // ********** Impl. by Sergi Baiges ********** - MASTER on ROBOTICS (Eurecat-UVic) //Execute cmake CMakeLists in file directory after make files, and then execute ./(example) //Libraries // #include "opencv2/objdetect.hpp" #include "opencv2/videoio.hpp" #include "opencv2/highgui.hpp" #include "opencv2/imgproc.hpp" #include <opencv2/core/core.hpp> #include <iostream> #include <stdio.h> //Variables // using namespace std; using namespace cv; // Function Headers // void detectAndDisplay( Mat screenFrame ); // Global variables - Load XML classifier // String face_cascade_name = "haarcascade_frontalface_alt.xml"; String eyes_cascade_name = "haarcascade_eye_tree_eyeglasses.xml"; CascadeClassifier face_cascade; CascadeClassifier eyes_cascade; String window_name = "### Face detector ### - Press -C- to quit"; // Main function // int main(int argc, char *argv[] ) { VideoCapture capture; Mat screenFrame; //-- 1. Load the cascades filters if( !face_cascade.load( face_cascade_name ) ){ printf("--(!)Error loading face cascade\n"); return -1; }; if( !eyes_cascade.load( eyes_cascade_name ) ){ printf("--(!)Error loading eyes cascade\n"); return -1; }; //-- 2. Read the video stream capture.open( -1 ); if ( ! capture.isOpened() ) { printf("--(!)Error opening video capture\n"); return -1; } while ( capture.read(screenFrame) ) { if( screenFrame.empty() ) { printf(" --(!) No captured screenFrame -- Break!"); break; } detectAndDisplay( screenFrame ); int c = waitKey(10); if( (char)c == 'c' ) break; } return 0; } //-- 3. Apply the classifier to the screenFrame. //We create a Mat to save the image in gray and //a vector called faces that stores all the pixels void detectAndDisplay( Mat screenFrame ) { std::vector<Rect> faces; Mat screenFrame_gray; cvtColor( screenFrame, screenFrame_gray, COLOR_BGR2GRAY ); equalizeHist( screenFrame_gray, screenFrame_gray ); //We improved the image //-- Detect faces face_cascade.detectMultiScale( screenFrame_gray, faces, 1.1, 2, 0|CASCADE_SCALE_IMAGE, Size(30, 30) ); // We create a loop that allows us to draw an ellipse around a point for ( size_t i = 0; i < faces.size(); i++ ) { Point center( faces[i].x + faces[i].width/2, faces[i].y + faces[i].height/2 ); ellipse( screenFrame, center, Size( faces[i].width/2, faces[i].height/2 ), 0, 0, 360, Scalar( 0, 0, 255 ), 4, 8, 0 ); Mat faceROI = screenFrame_gray( faces[i] ); std::vector<Rect> eyes; //-- In each face, detect eyes (perform detection) and draw a circles around eyes eyes_cascade.detectMultiScale( faceROI, eyes, 1.1, 2, 0 |CASCADE_SCALE_IMAGE, Size(30, 30) ); for ( size_t j = 0; j < eyes.size(); j++ ) { Point eye_center( faces[i].x + eyes[j].x + eyes[j].width/2, faces[i].y + eyes[j].y + eyes[j].height/2 ); int radius = cvRound( (eyes[j].width + eyes[j].height)*0.25 ); circle( screenFrame, eye_center, radius, Scalar( 0, 255, 0 ), 4, 8, 0 ); } } //-- Show what you got imshow( window_name, screenFrame ); }
a49102784cc737f1dbc731e40e48804c7760e0a6
f419446fe13d0fe020a3615910879e2087f76b70
/Sim900.cpp
3610e994c0e1d14d508ded9b16fc9f1a9ca98f94
[]
no_license
pietrodizinno/Sim900NetLib
dcbff3cf9819cd8b0dce15b58a3cda24b0b2931e
6066fcca75e5aa197f758f19a496be8560b0f698
refs/heads/master
2021-01-20T14:05:02.076410
2014-11-27T20:14:17
2014-11-27T20:14:17
null
0
0
null
null
null
null
UTF-8
C++
false
false
11,887
cpp
Sim900.cpp
#include "Sim900.h" static int put_data(char c, FILE *f) { Sim900::ser->write(c); return 0; } Sim900::Sim900(Stream* serial, int powerPin, Stream &debugStream) : ds(debugStream) //, parser(debugStream) { _powerPin = powerPin; Sim900::ser = serial; lastDataWrite = 0; dataBufferTail = 0; dataBufferHead = 0; pinMode(powerPin, OUTPUT); parser.gsm = this; parser.ctx = this; memset(_dataBuffer,0, DATA_BUFFER_SIZE); #ifdef fdev_setup_stream fdev_setup_stream(&dataStream,put_data, NULL, _FDEV_SETUP_WRITE); #endif } Stream* Sim900::ser = {0}; /* Get gsm network registration status Return values S900_ERROR, S900_TIMEOUT, SEARCHING_FOR_NETWORK0, HOME_NETWORK, SEARCHING_FOR_NETWORK, REGISTRATION_DENIED, REGISTRATION_UNKNOWN, ROAMING */ int Sim900::GetRegistrationStatus() { parser.SetCommandType(AT_CREG); ser->println(F("AT+CREG?")); registrationStatus = PopCommandResult(AT_DEFAULT_TIMEOUT); return registrationStatus; } /* Get operator name Return values S900_OK, S900_ERROR, S900_TIMEOUT */ int Sim900::GetOperatorName() { operatorName[0] = 0; parser.SetCommandType(AT_COPS); ser->println(F("AT+COPS?")); int result = PopCommandResult(AT_DEFAULT_TIMEOUT); return result; } /* Get signal quality returned by AT+CSQ Return values S900_OK, S900_ERROR, S900_TIMEOUT */ int Sim900::getSignalQuality() { parser.SetCommandType(AT_CSQ); ser->println(F("AT+CSQ")); int result = PopCommandResult(AT_DEFAULT_TIMEOUT); return result; } void Sim900::PrintEscapedChar( char c ) { if(c=='\r') ds.print("\\r"); else if(c=='\n') ds.print("\\n"); else ds.print(c); } /* Get pdp context status using AT+CIPSTATUS Return values S900_ERR, S900_TIMEOUT IP_INITIAL, IP_START, IP_CONFIG, IP_GPRSACT, IP_STATUS, TCP_CONNECTING, TCP_CLOSED, PDP_DEACT, CONNECT_OK */ int Sim900::GetIpStatus() { parser.SetCommandType(AT_CIPSTATUS); ser->println(F("AT+CIPSTATUS")); return PopCommandResult(AT_DEFAULT_TIMEOUT); } /* Get ip address using AT+CIFSR Return values S900_OK, S900_TIMEOUT */ int Sim900::GetIpAddress( ) { parser.SetCommandType(AT_CIFSR); ser->println(F("AT+CIFSR")); int result = PopCommandResult(AT_DEFAULT_TIMEOUT); return result; } /* Bring up GRPS connection Return values S900_OK, S900_ERROR, S900_TIMEOUT */ int Sim900::AttachGprs() { parser.SetCommandType(AT_DEFAULT); ser->println(F("AT+CIICR")); return PopCommandResult(60000); } /* Start tcp connection to address:port Return values S900_OK, S900_ERROR, S900_TIMEOUT */ int Sim900::StartTransparentIpConnection(const char *address, int port, S900Socket *socket = 0 ) { dataBufferHead = dataBufferTail = 0; parser.SetCommandType(AT_CIPSTART); // Execute command like AT+CIPSTART="TCP","ag.kt29.net","80" ser->print(F("AT+CIPSTART=\"TCP\",\"")); ser->print(address); ser->print(F("\",\"")); ser->print(port); ser->println('"'); if(socket != 0) socket->s900 = this; return PopCommandResult(60000); } /* close active connection */ int Sim900::CloseConnection() { parser.SetCommandType(AT_CIPCLOSE); ser->println(F("AT+CIPCLOSE=1")); return PopCommandResult(AT_DEFAULT_TIMEOUT); } /* returns true if any data is available to read from transparent connection */ bool Sim900::DataAvailable() { if(dataBufferHead != dataBufferTail) return true; if(ser->available()) return true; return false; } void Sim900::PrintDataByte(uint8_t data) // prints 8-bit data in hex { char tmp[3]; byte first; byte second; first = (data >> 4) & 0x0f; second = data & 0x0f; tmp[0] = first+48; tmp[1] = second+48; if (first > 9) tmp[0] += 39; if (second > 9) tmp[1] += 39; tmp[2] = 0; ds.write(' '); ds.print(tmp); ds.write(' '); } int Sim900::DataRead() { int ret = ReadDataBuffer(); if(ret != -1) { //PrintDataByte(ret); return ret; } ret = ser->read(); if(ret != -1) { // PrintDataByte(ret); } return ret; } /* Switches to command mode ATO Return values S900_OK, S900_ERROR, S900_TIMEOUT */ int Sim900::SwitchToCommandMode() { parser.SetCommandType(AT_SWITH_TO_COMMAND); commandBeforeRN = true; // +++ escape sequence needs to wait 1000ms after last data was sent via transparent connection // in the meantime data from tcp connection may arrive so we read it here to dataBuffer // ex: lastDataWrite = 1500 // loop will exit when millis()-1500<1000 so when millis is 2500 delay(1000); /* while(ser->available() || (millis()-lastDataWrite) < 1000) { while(ser->available()) { int c = ser->read(); pr("\nsc_data: %c\n", (char)c); WriteDataBuffer(c); } }*/ ser->print(F("+++")); lastDataWrite = millis(); return PopCommandResult(500); } int Sim900::SwitchToCommandModeDropData() { parser.SetCommandType(AT_SWITH_TO_COMMAND); ser->flush(); while(ser->available()) ser->read(); delay(1500); while(ser->available()) ser->read(); ser->print(F("+++")); return PopCommandResult(500); } /* Switches to data mode ATO Return values S900_OK, S900_ERROR, S900_TIMEOUT */ int Sim900::SwitchToDataMode() { parser.SetCommandType(AT_SWITCH_TO_DATA); ser->println(F("ATO")); int result = PopCommandResult(AT_DEFAULT_TIMEOUT); if(result == S900_OK) { delay(100); while(ser->available()) { int c = ser->read(); //pr("\nsd_data: %c\n", (char)c); //ds.print("s_data: "); ds.println((int)c); WriteDataBuffer(c); } } lastDataWrite = millis(); return result; } /* Interets incoming data from serial port as results Return values S900_OK, S900_ERROR, S900_TIMEOUT, specific function return values, specific errors */ int Sim900::PopCommandResult( int timeout ) { unsigned long start = millis(); while(parser.commandReady == false && (millis()-start) < (unsigned long)timeout) { if(ser->available()) { char c = ser->read(); parser.FeedChar(c); } } int commandResult = parser.lastResult; if (commandResult == S900_NONE) commandResult = S900_TIMEOUT; parser.SetCommandType(0); return commandResult; } /* Disables/enables echo on serial port Return values S900_OK, S900_ERROR, S900_TIMEOUT */ int Sim900::SetEcho( bool echoEnabled ) { parser.SetCommandType(AT_DEFAULT); if(echoEnabled) ser->println(F("ATE1")); else ser->println(F("ATE0")); int r = PopCommandResult(AT_DEFAULT_TIMEOUT); delay(100); // without 100ms wait, next command failed, idk wky return r; } /* Set sim900 to use transparent mode Return values S900_OK, S900_ERROR, S900_TIMEOUT */ int Sim900::SetTransparentMode( bool transparentMode ) { parser.SetCommandType(AT_DEFAULT); if(transparentMode) ser->println(F("AT+CIPMODE=1")); else ser->println(F("AT+CIPMODE=0")); return PopCommandResult(AT_DEFAULT_TIMEOUT); } /* Set apn details Return values S900_OK, S900_ERROR, S900_TIMEOUT */ int Sim900::SetApn(const char *apnName, const char *username,const char *password ) { parser.SetCommandType(AT_DEFAULT); ser->print(F("AT+CSTT=\"")); ser->print(apnName); ser->print(F("\",\"")); ser->print(username); ser->print(F("\",\"")); ser->print(password); ser->print(F("\"\r\n")); return PopCommandResult(AT_DEFAULT_TIMEOUT); } /* Execute At command Return values S900_OK, S900_ERROR, S900_TIMEOUT */ int Sim900::ExecuteCommand_P( const __FlashStringHelper* command ) { parser.SetCommandType(AT_DEFAULT); ser->println(command); return PopCommandResult(AT_DEFAULT_TIMEOUT); } void Sim900::DataWrite( const __FlashStringHelper* data ) { ser->print(data); lastDataWrite = millis(); } void Sim900::DataWrite( char* data ) { ser->print(data); lastDataWrite = millis(); } void Sim900::DataWrite( char *data, int length ) { ser->write((unsigned char*)data, length); lastDataWrite = millis(); } void Sim900::DataWrite( char c ) { ser->write(c); lastDataWrite = millis(); } void Sim900::DataEndl() { ser->print(F("\r\n")); ser->flush(); lastDataWrite = millis(); } /* makes sure modem is enabled */ /* well this function may take forever */ int Sim900::TurnOn() { // while(!IsPoweredUp()) // { ds.println(F("Timeout, trying to turn on")); pinMode(9, OUTPUT); digitalWrite(9,LOW); delay(1000); digitalWrite(9,HIGH); delay(2000); digitalWrite(9,LOW); delay(3000); // } return S900_OK; } int Sim900::SetBaudRate(uint32_t baud) { parser.SetCommandType(AT_DEFAULT); ser->print(F("AT+IPR=")); ser->println(baud); return PopCommandResult(AT_DEFAULT_TIMEOUT); } int Sim900::GetIMEI() { parser.SetCommandType(AT_GSN); ser->println(F("AT+GSN")); return PopCommandResult(AT_DEFAULT_TIMEOUT); } bool Sim900::IsPoweredUp() { return GetIMEI() == S900_OK; //int result = S900_TIMEOUT; // //parser.SetCommandType(AT_DEFAULT); //ser->println(F("AT+GSN")); //result = PopCommandResult(400); // // //if(result == S900_TIMEOUT) //return false; //return true; } void Sim900::wait(int ms) { unsigned long start = millis(); while((millis()-start) <= (unsigned long)ms) if(ser->available()) parser.FeedChar(ser->read()); } int Sim900::ExecuteFunction(FunctionBase &function) { parser.SetCommandType(&function); ser->println(function.getCommand()); int initialResult = PopCommandResult(function.functionTimeout); if(initialResult == S900_OK) return initialResult; if(function.GetInitSequence() == NULL) return initialResult; char *p= (char*)function.GetInitSequence(); while(pgm_read_byte(p) != 0) { // ds.print(F("Exec: ")); //printf("Exec: %s\n", p); ds.println((__FlashStringHelper*)p); delay(100); int r = ExecuteCommand_P((__FlashStringHelper*)p); if(r < 0) { ds.println(F("Fail")); return r; } ds.println(" __Fin"); while(pgm_read_byte(p) != 0) p++; p++; } delay(500); parser.SetCommandType(&function); ser->println(function.getCommand()); return PopCommandResult(function.functionTimeout); } int Sim900::SendSms(char *number, char *message) { parser.SetCommandType(AT_DEFAULT); ser->print(F("AT+CMGS=\"")); ser->print(number); ser->println(F("\"")); uint64_t start = millis(); // wait for > while (ser->read() != '>') if (millis() - start > 200) return S900_ERR; ser->print(message); ser->print('\x1a'); return PopCommandResult(AT_DEFAULT_TIMEOUT); } int Sim900::SendUssdWaitResponse(char *ussd, char*response, int responseBufferLength) { parser.SetCommandType(AT_CUSD); buffer_ptr = response; buffer_size = responseBufferLength; ser->print(F("AT+CUSD=1,\"")); ser->print(ussd); ser->println(F("\"")); return PopCommandResult(10000); } int Sim900::UnwriteDataBuffer() { if (dataBufferTail == 0) dataBufferTail = DATA_BUFFER_SIZE - 1; else dataBufferTail--; return _dataBuffer[dataBufferTail]; } void Sim900::WriteDataBuffer(char c) { int tmp = dataBufferTail+1; if(tmp == DATA_BUFFER_SIZE) tmp = 0; if(tmp == dataBufferHead) { ds.println(F("Buffer overflow")); return; } //ds.print(F("Written ")); this->PrintDataByte(c); _dataBuffer[dataBufferTail] = c; dataBufferTail = tmp; } int Sim900::ReadDataBuffer() { if(dataBufferHead != dataBufferTail) { int ret= _dataBuffer[dataBufferHead]; dataBufferHead++; if(dataBufferHead==DATA_BUFFER_SIZE) dataBufferHead = 0; return ret; } return -1; } int Sim900::Cipshut() { parser.SetCommandType(AT_CIPSHUT); ser->println(F("AT+CIPSHUT")); return PopCommandResult(AT_DEFAULT_TIMEOUT); } void Sim900::DataWriteNumber(int c) { ser->print(c); lastDataWrite = millis(); } void Sim900::DataWriteNumber(uint16_t c) { ser->print(c); lastDataWrite = millis(); } void Sim900::data_printf(const __FlashStringHelper *fmt, ...) { va_list args; va_start(args, fmt); vfprintf_P(&dataStream, (const char*)fmt, args); va_end(args); lastDataWrite = millis(); } int Sim900::Call(char *number) { parser.SetCommandType(AT_DEFAULT); ser->print(F("ATD")); ser->print(number); ser->println(F(";")); return PopCommandResult(AT_DEFAULT_TIMEOUT); } void Sim900::Shutdown() { ser->println(F("AT+CPOWD=0")); }
73a710b698ddf453908904f153513d203f622fdb
2f14367ec3260046f65bc8c345cc08afc5c307a6
/Classes/HelloWorldScene.cpp
28e9125ed03234801eadb6a7a06936b1aafb8bc6
[]
no_license
fordream/Line
369ef8437eee0abce628be4b792358958f0931c4
a1efeaf9357d1cdeb67d209a8381f4c21270f4ca
refs/heads/master
2021-01-21T07:20:32.763508
2014-04-01T13:16:19
2014-04-01T13:16:19
null
0
0
null
null
null
null
UTF-8
C++
false
false
6,612
cpp
HelloWorldScene.cpp
#include "HelloWorldScene.h" USING_NS_CC; #define DOT_SEGMENT 20.0f #define DOT_LENGTH 100 #define Pi 3.1415926f #define PiAngle 180.0f #define AREA_LIMIT 20.0f #define BALL_LENGTH 5 #define BALL_SCALE 0.1f const char* ball[] = {"Blue-Candy.png","Green-Candy.png","Pink-Candy.png","Red-Candy.png","Yellow-Candy.png"}; #define MONSTER_LENGTH 5 const char* monster[] = {"BigFootcube.png","Frankencube.png","Mummycube.png","Ogrecube.png","Vampcube.png"}; CCScene* HelloWorld::scene() { // 'scene' is an autorelease object CCScene *scene = CCScene::create(); // 'layer' is an autorelease object HelloWorld *layer = HelloWorld::create(); // add layer as a child to scene scene->addChild(layer); // return the scene return scene; } // on "init" you need to initialize your instance bool HelloWorld::init() { ////////////////////////////// // 1. super init first if ( !CCLayer::init() ) { return false; } CCSize visibleSize = CCDirector::sharedDirector()->getVisibleSize(); CCPoint origin = CCDirector::sharedDirector()->getVisibleOrigin(); ///////////////////////////// // 2. add a menu item with "X" image, which is clicked to quit the program // you may modify it. // add a "close" icon to exit the progress. it's an autorelease object CCMenuItemImage *pCloseItem = CCMenuItemImage::create( "CloseNormal.png", "CloseSelected.png", this, menu_selector(HelloWorld::menuCloseCallback)); pCloseItem->setPosition(ccp(origin.x + visibleSize.width - pCloseItem->getContentSize().width/2 , origin.y + pCloseItem->getContentSize().height/2)); // create menu, it's an autorelease object CCMenu* pMenu = CCMenu::create(pCloseItem, NULL); pMenu->setPosition(CCPointZero); this->addChild(pMenu, 1); ///////////////////////////// // 3. add your codes below... // add a label shows "Hello World" // create and initialize a label CCLabelTTF* pLabel = CCLabelTTF::create("Hello World", "Arial", 24); // position the label on the center of the screen pLabel->setPosition(ccp(origin.x + visibleSize.width/2, origin.y + visibleSize.height - pLabel->getContentSize().height)); // add the label as a child to this layer this->addChild(pLabel, 1); // add "HelloWorld" splash screen" CCSprite* pSprite = CCSprite::create("HelloWorld.png"); // position the sprite on the center of the screen pSprite->setPosition(ccp(visibleSize.width/2 + origin.x, visibleSize.height/2 + origin.y)); // add the sprite as a child to this layer this->addChild(pSprite, 0); CCDirector::sharedDirector()->getTouchDispatcher()->addTargetedDelegate(this, 1, true); m_BeginPoint = ccp(visibleSize.width/2, AREA_LIMIT); m_Rect.setRect(-(m_BeginPoint.x - AREA_LIMIT), -(m_BeginPoint.y - AREA_LIMIT), visibleSize.width - 2*AREA_LIMIT, visibleSize.height - 2*AREA_LIMIT); m_pBatchNode = CCSpriteBatchNode::create("test.png"); this->addChild(m_pBatchNode); m_pBatchNode->setPosition(m_BeginPoint); m_pBatchNode->setVisible(false); for (int i = 0; i < DOT_LENGTH; i++) { CCSprite* sprite = CCSprite::create("test.png"); m_pBatchNode->addChild(sprite); sprite->setPosition(ccp(0,i*DOT_SEGMENT)); m_vDot.push_back(sprite); } m_pBall = CCSprite::create(ball[0]); this->addChild(m_pBall); m_pBall->setPosition(m_BeginPoint); for (int i = 0; i < MONSTER_LENGTH; i++) { CCSprite* monsterSp = CCSprite::create(monster[i]); this->addChild(monsterSp); monsterSp->setPosition(ccp(200*i+200, 300)); CCLog("%f==%f",monsterSp->getContentSize().width,monsterSp->getContentSize().height); m_vMonster.push_back(monsterSp); } return true; } void HelloWorld::menuCloseCallback(CCObject* pSender) { CCDirector::sharedDirector()->end(); #if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS) exit(0); #endif } float HelloWorld::getAngle(CCPoint* des, CCPoint* tar) { float angle; float _x = tar->x - des->x; float _y = tar->y - des->y; angle = atan2f(_y, _x); for (int i = 0; i < m_vDot.size(); i++) { float height = i*DOT_SEGMENT; float y = sinf(angle)*height; float x = cosf(angle)*height; CCPoint pt = ccp(x,y); checkRect(&pt); m_vDot[i]->setPosition(pt); } return angle; } BORDER4 HelloWorld::checkRect(cocos2d::CCPoint* pt) { //Top float top = m_Rect.origin.y + m_Rect.size.height; if (pt->y > top) { pt->y = 2*top - pt->y; } //Left float left = m_Rect.origin.x; if (pt->x < left) { pt->x = 2*left - pt->x; } //Buttom float buttom = m_Rect.origin.y; if (pt->y < buttom) { pt->y = 2*buttom - pt->y; } //Right float right = m_Rect.origin.x + m_Rect.size.width; if (pt->x > right) { pt->x = 2*right - pt->x; } if (!m_Rect.containsPoint(*pt)) { checkRect(pt); } return BORDER_BOTTOM; } bool HelloWorld::ccTouchBegan(cocos2d::CCTouch *pTouch, cocos2d::CCEvent *pEvent) { m_pBatchNode->setVisible(true); CCPoint tar = pTouch->getLocation(); CCPoint new_tar = tar;//ccpSub(tar, m_BeginPoint); float angle = getAngle(&m_BeginPoint, &new_tar); CCLOG("ccTouchBegan :%f %f == %f %f %f",tar.x,tar.y,angle/Pi*PiAngle,atan2f(1,1)/Pi*PiAngle,tan(45.0f/PiAngle*Pi)); return true; } void HelloWorld::ccTouchMoved(cocos2d::CCTouch *pTouch, cocos2d::CCEvent *pEvent) { CCPoint tar = pTouch->getLocation(); CCPoint new_tar = tar;//ccpSub(tar, m_BeginPoint); float angle = getAngle(&m_BeginPoint, &new_tar); CCLOG("ccTouchMoved :%f %f",tar.x,tar.y); } void HelloWorld::ccTouchEnded(cocos2d::CCTouch *pTouch, cocos2d::CCEvent *pEvent) { m_pBatchNode->setVisible(false); CCPoint tar = pTouch->getLocation(); CCLOG("ccTouchEnded :%f %f",tar.x,tar.y); } void HelloWorld::ccTouchCancelled(cocos2d::CCTouch *pTouch, cocos2d::CCEvent *pEvent) { m_pBatchNode->setVisible(false); CCPoint tar = pTouch->getLocation(); CCLOG("ccTouchCancelled :%f %f",tar.x,tar.y); }
1ddab02837931cb1fb54691342ff7f9a32bc1092
b20353e26e471ed53a391ee02ea616305a63bbb0
/trunk/engine/tools/MakePatch/IDiff.h
2dd634f1910a2ccd361585ce04515ce2bd179a03
[]
no_license
trancx/ybtx
61de88ef4b2f577e486aba09c9b5b014a8399732
608db61c1b5e110785639d560351269c1444e4c4
refs/heads/master
2022-12-17T05:53:50.650153
2020-09-19T12:10:09
2020-09-19T12:10:09
291,492,104
0
0
null
2020-08-30T15:00:16
2020-08-30T15:00:15
null
UTF-8
C++
false
false
291
h
IDiff.h
#pragma once #include "BaseTypes.h" using namespace sqr; class IDiff { public: virtual bool MakeDiff(const char* szNewFile, const char* szOldFile)=0; virtual uint32 GetDiffType() const=0; virtual uint32 GetAllSize() const=0; virtual void WriteDiffData(void* fp)=0; };
55eda93df04188e5a41e174bf8acddb38fc48945
f22fca98c1e2f9ff2d950c5e9a9e66c55c40f8b2
/mycp/utils.h
8a4afb5a97c3af704f57b5f945141fde0b569711
[]
no_license
popenyuk/AdvancedMyShell
b071486b42f3fa38ff7a0e9b500b437496a25a6c
5406fc6f7c98e22e7995fdb035b438373cf1504b
refs/heads/master
2020-09-12T02:16:21.667290
2020-01-26T14:14:56
2020-01-26T14:14:56
222,266,926
0
0
null
null
null
null
UTF-8
C++
false
false
1,159
h
utils.h
// // Created by markiian on 08.01.20. // #ifndef MYFUNCPACK_UTILS_H #define MYFUNCPACK_UTILS_H #include <cstring> #include <fcntl.h> #include <sys/stat.h> #include <sys/sendfile.h> #include <cerrno> #include <sys/types.h> #include <sstream> #include <vector> #include <iostream> #include <dirent.h> #include <unistd.h> #define DIR_TYPE 1 #define FILE_TYPE 2 typedef std::pair<int, int> File; #define ERR_File File{-1, -1} #define SKIP_File File{-2, -2} #define ABORT_File File{-3, -3} int copy_raw(int fd_from, int fd_to); File try_to_get_source(const char *filename); std::string getPathWOFileName(const std::string &s); File try_to_get_dest(const char *filename, bool &force_flag); int is_directory(const char *path); std::string getFileName(const std::string &s); void listdir(char *path, size_t size, std::vector<char *> &path_list, std::vector<char *> &simplified_path_list, size_t prefix_length, const std::string &dir_to); void recursiveDirTraversal(char *path, std::vector<char *> &from, std::vector<char *> &to, const std::string &dir_to); void free_vector_of_char_p(std::vector<char *> &vec); #endif //MYFUNCPACK_UTILS_H
ac6076e092c110d0dee4925d3862cfb0f535ba9c
7cd7df07fdada6a71372fbab8b61166511917895
/codeninja/arrays_strings/test.cpp
fa156c727bdb43525d95893c63996ea455aa7bb8
[]
no_license
Divya063/programming
dd85e5f7bca989b60a63b6a85b5c568e2bc2dd61
b4fcc68b6c3a874f739e34a32f0531a8b6e97e68
refs/heads/master
2022-02-17T16:45:06.451071
2019-10-01T06:30:41
2019-10-01T06:30:41
212,022,118
0
0
null
null
null
null
UTF-8
C++
false
false
930
cpp
test.cpp
#include <iostream> using namespace std; struct Node{ int data; Node* left; Node* right; }; Node* insert(int data){ Node* node = new Node(); node->data = data; node->left = NULL; node->right = NULL; return node; } Node* insert1(int arr[], int i, Node* root, int n){ if(i<n){ Node* temp = insert(arr[i]); root = temp; root->left = insert1(arr, 2*i+1, root->left, n); root->right = insert1(arr, 2*i+2, root->right, n); } return root; } void inOrder(Node* root) { if (root != NULL) { inOrder(root->left); cout << root->data <<" "; inOrder(root->right); } } int main() { //code int n; cin >> n; while(n--){ int size; cin >> size; int arr[size]; for(int i =0; i<size; i++){ cin >> arr[i]; } Node* root = insert1(arr, 0, root, n); inOrder(root); } }
fd332b1e8185fcb67d79c80506186b29a6f1bab2
9c6b59f7bf7b33688de5fe65235c1fd55a53d25b
/QuickTest/QuickTest.cpp
aa754c653dea1ce16563d175431905769236f1e7
[]
no_license
Xiaoy312/Erebus2Helper
9fab7c5e685d4ca5d0ab265ee9993ae98aee919c
f9e757a28ceaae37a53da4104dae88e192089a3a
refs/heads/master
2016-09-16T01:26:58.208422
2015-04-12T21:13:51
2015-04-12T21:13:51
37,831,805
0
0
null
null
null
null
UTF-8
C++
false
false
2,245
cpp
QuickTest.cpp
#define WIN32_LEAN_AND_MEAN // Exclude rarely-used stuff from Windows headers #include <Windows.h> #include <stdio.h> #include <fstream> #include <tlhelp32.h> #define MODULE_NAME "XyErebus2.dll" bool FileExists(const char *path) { std::ifstream ifile(path); return ifile; } void Inject(HANDLE process, LPCSTR modulePath) { if(!FileExists(modulePath)) { MessageBox(0, modulePath, "File Not Found", 0); return; } LPVOID address = nullptr; BOOL success = FALSE; HMODULE kernel32 = nullptr; HANDLE thread = nullptr; __try { // Inject the dll path into the target process address = VirtualAllocEx(process, NULL, strlen(modulePath), MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE); printf("Address allocated : %X\n", address); success = WriteProcessMemory(process, (LPVOID)address, modulePath, strlen(modulePath), NULL); printf("WriteProcessMemory : %s\n", success? "successed":"failed"); // Invoke LoadLibrary via CreateRemoteThread kernel32 = GetModuleHandle("kernel32.dll"); printf("Kernel32 : %X\n", kernel32); thread = CreateRemoteThread(process, NULL, 0, (LPTHREAD_START_ROUTINE)GetProcAddress(kernel32, "LoadLibraryA"), (LPVOID)address, 0, NULL); printf("Remote thread handle : %X\n", thread); } __finally { if(thread) CloseHandle(thread); if(kernel32) FreeLibrary(kernel32); if(address) VirtualFreeEx(process, NULL, (size_t)strlen(modulePath), MEM_RESERVE|MEM_COMMIT); } } HANDLE FindHostProcess(const char * name) { PROCESSENTRY32 entry; entry.dwSize = sizeof(PROCESSENTRY32); HANDLE snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, NULL); if (Process32First(snapshot, &entry) == TRUE) { while (Process32Next(snapshot, &entry) == TRUE) { if (_stricmp(entry.szExeFile, name) == 0) { return OpenProcess(PROCESS_ALL_ACCESS, FALSE, entry.th32ProcessID); } } } CloseHandle(snapshot); } int main(int argc, char* argv[]) { char path[255]; GetFullPathName(MODULE_NAME, 255, path, 0); HANDLE process = FindHostProcess("Erebus2.exe"); Inject(process, path); CloseHandle(process); return 0; }
840eff18a86f1011d5a810811f09c4dc652349af
f36878942654f1b6afa6c6c39fbfbea2efc10a3f
/Yankin_Exam/Yankin_Exam/TrapeziumBase.h
131de7ae8820f810780cbdf96514f1959307f988
[]
no_license
darkllen/OOP_Exam
22bf8ed70f4ac8b53eaa82e26935511041866757
b2c6c60ffcd9b6ba0cac75a1ce7959d9d84d9bdc
refs/heads/master
2022-04-17T21:27:44.551300
2020-04-14T14:48:19
2020-04-14T14:48:19
254,915,860
0
0
null
null
null
null
UTF-8
C++
false
false
818
h
TrapeziumBase.h
#pragma once #include "Trapezium.h" class TrapeziumAxes; class TrapeziumBase : public Trapezium { public: //constructor TrapeziumBase(const Segment& ab, const Segment& cd); ~TrapeziumBase(); //cast to TrapeziumAxes operator TrapeziumAxes() const; //trapezium square double area(); //trapezium perimeter double perimeter(); //return tops and sides const Point pointA(); const Point pointB(); const Point pointC(); const Point pointD(); const Segment sideAB(); const Segment sideBC(); const Segment sideCD(); const Segment sideAD(); //get middle line of trapezium const Segment& getMidLine(); //arbitrary axis mirroring void flip(const Axis); //trapezium rotation void rotate(const double); //output method ostream& show(ostream&); private: Segment _ab, _cd; Segment* _midLine; };
9df7d261e0dcabfd77f0513cd7d590ea86024498
84ee543935b36942a839480ba2e297424ee03dee
/C++/303_Range_Sum_Query_Immutable.cpp
acfa5b4e4fccd75e70f6b7b277a43ef92a0540f7
[]
no_license
yuyilei/LeetCode
ddd008bbfa7f5be02f9391a808e49da746634e5c
dfeac0af40fb4a6b9263b1c101eb6906e2f881f4
refs/heads/master
2021-12-21T12:54:59.666693
2021-12-02T13:37:49
2021-12-02T13:37:49
101,265,411
9
0
null
null
null
null
UTF-8
C++
false
false
539
cpp
303_Range_Sum_Query_Immutable.cpp
/* */ class NumArray { private: vector<int> sums; public: NumArray(vector<int> nums) { if ( nums.size() == 0 ) return; sums.push_back(nums[0]); for ( int i = 1 ; i < nums.size() ; i++) sums.push_back(sums[i-1]+nums[i]); } int sumRange(int i, int j) { return ( i == 0 ) ? sums[j] : sums[j] - sums[i-1]; } }; /** * Your NumArray object will be instantiated and called as such: * NumArray obj = new NumArray(nums); * int param_1 = obj.sumRange(i,j); */
18f30d061ecd6b1134a6ff6c33334490aeee2b14
9672f8f18d46f21fe53013202ba17aad96ecf211
/Project3/Medusa.cpp
e073107be815eeb099f8d4fdc59976269e113605
[]
no_license
cdavis4/CS_162
99793d4f6186c621ccf95a3e2cb52d8722819919
fa74f43af55b890cde8f7deaf632cf5d8f21728c
refs/heads/master
2020-05-23T18:01:47.750458
2019-05-15T18:08:46
2019-05-15T18:08:46
186,878,985
0
0
null
null
null
null
UTF-8
C++
false
false
2,130
cpp
Medusa.cpp
/******************************************************* ** Author: carrie davis ** Date:August 2, 2018 ** Description: Project 3 Medusa ******************************************************/ #include <iostream> #include <random> #include <string> using namespace std; #include "Medusa.hpp" /******************************************************** * Medusa::Medusa * Override data members ********************************************************/ //Default Constructor Medusa::Medusa() { } /******************************************************* * Medusa::attack method * attacks other player and inflicts damage *********************************************************/ int Medusa::combatAttack() { random_device rd; //seed mt19937 gen(rd()); uniform_int_distribution<int> dist(2,attack); int damageRoll = dist(gen); if(damageRoll == 12) //GLARE of Medusa { cout << "Attacker rolled " << damageRoll << "." <<endl; cout << "Medusa GLARE activated!" <<endl; damageRoll = 50; } cout << "Medusa rolled " << damageRoll << " out of " << attack << " possible hit points." <<endl; return damageRoll; // subtract defenders roll and defenders armor } /******************************************************* * Medusa::defense method * defense takes damage when attacked * calculates inflicted damage on strength *********************************************************/ void Medusa::combatDefense(int inDamage) { //roll defense random_device rd; //seed mt19937 gen(rd()); uniform_int_distribution<int> dist(1,defense); int defenseRoll = dist(gen); int damageCalculated = inDamage - defenseRoll - armor; if(damageCalculated < 0) {damageCalculated =0;} //depends on roll then armor cout << "Medusa rolled " << defenseRoll << " out of " << defense << " possible defense points." <<endl; cout << "Armor deflects " << armor << " hit points." <<endl; cout << "Total damage inflicted: " <<damageCalculated <<endl; strength -=damageCalculated; cout << "Strength: " << strength <<endl; }
f9ff326a70af771b3b943f137693889dd941a122
5e7b5330f395d408b667ee0d290ef8f0081829cd
/Code/tp6/pb2/probleme2_TP6.cpp
1f3fbe78ece1b3501da180bc7a89fa424754ecbf
[ "MIT" ]
permissive
joabda/Robot
1266d598de77150df4a3e91d5adc34cf8ec8d2df
ce27e2e615cb87480c05f9e0ce32124648f9baff
refs/heads/master
2021-07-19T18:17:54.072988
2020-05-24T22:14:04
2020-05-24T22:14:04
171,281,897
1
0
null
null
null
null
UTF-8
C++
false
false
2,246
cpp
probleme2_TP6.cpp
/* Ce programme a pour but de programmer la DEL du robot en fonction de la luminosité ambiante : * - Verte lorsque la diode est cachée, * - Ambrée à luminosité ambiante * - Rouge sous une lampe torche * Date: 2019-02-16 * Auteurs: ABDO Joe 1939689 CHRITIN Mathurin 1883619 * probleme2_1939689_1883619.cpp * */ #define F_CPU 8000000//UL // 8 MHz -- Define toujours au debut #include <avr/io.h> #include <util/delay.h> #include "can.h" // On branche notre photorésistance sur la PINA0 // On branche la LED sur PINB0-1 void initialisation() // Fonction d'initialisation pour les ports et les interruptions { DDRB = 0xff; // PORT B est en mode sortie pour envoyer les couleurs a la DEL DDRA = 0x00; // PORT D est en mode lecture pour lire le boutton pressoire } void ambree(const uint8_t& rougeLED, const uint8_t& vertLED) /* * Fonction qui envoie les valeurs nécessaires de rouge et de vert (passés en paramètre) pour que la LED prenne une couleur ambrée. */ { PORTB = rougeLED; _delay_ms(1); PORTB = vertLED; _delay_ms(7); } int main() { initialisation(); const uint8_t eteinteLED = 0x0; const uint8_t rougeLED = 0x1; const uint8_t vertLED = 0x2; PORTB = eteinteLED; //Initialisation de la DEl à éteinte //La photorésistance renvoie une valeur entre 160 et 260 à luminosité du laboratoire (220 environ) const uint8_t luminositeForte = 240; const uint8_t luminositeFaible = 180; can photoresistance; //Creation d'un objet photoresistance (voir can.h can.cpp) while(true) { uint16_t lecture = (photoresistance.lecture(0) >> 2); // on décale de 2 comme mentiionné dans l'énoncé : les deux derniers bits ne sont pas significatifs // luminosité forte (lampe torche) if (lecture > luminositeForte) PORTB = rougeLED; // luminosité ambiante (lampes du labo) if (lecture <= luminositeForte && lecture >= luminositeFaible) ambree(rougeLED, vertLED); // luminosité faible (photoresistance cachée) if (lecture < luminositeFaible) PORTB = vertLED; _delay_ms(10); //delay parce qu'on n'a pas besoin d'autre chose pendant ce temps, et pas besoin de lire la valeur de la photoresistance à chaque tick d'horloge } }
1b37ebf438d1fa9c869cb7d4fade7e1eb77bc418
6213740f4b6798ace434fa5717bb6c24b1e8fdb7
/Bootstrap-ShooterGame-master/ShooterGame/include/StateMachine/Game/MainMenuState.h
de358dac489f3ee06f8d648d81e87fb073dda772
[ "MIT" ]
permissive
zackslay3r/C---Projects
4fb40ae3bc3e2bb38e1238822c0aed5585f10943
5e1bf2014dbfa4f74715f544f19a5886e679ea8e
refs/heads/master
2021-01-21T15:53:27.311648
2017-08-13T11:54:17
2017-08-13T11:54:17
91,862,799
0
0
null
null
null
null
UTF-8
C++
false
false
566
h
MainMenuState.h
#pragma once #include "IGameState.h" #include <memory> #include <iostream> class Menu; class MenuBtn; class ShooterGameApp; namespace aie { class Font; class Renderer2D; } class MainMenuState : public IGameState { public: MainMenuState(ShooterGameApp *app); ~MainMenuState(); virtual void update(float dt); virtual void render(aie::Renderer2D *renderer); private: std::unique_ptr<aie::Font> m_statusFont; std::unique_ptr<Menu> m_menu; #pragma region ButtonFunctions void newGameFunc(); void loadGameFunc(); void quitFunc(); #pragma endregion };
5015fee876f69917c7613f6fb9a62efe77ab9e80
cabdefdd535422fea3de20ec740533dba90af825
/MISSION_ARCHIVE2016/insect_repelllent_Test.Stratis/sounds/config.cpp
1de0e2368c94f275c71900a2d3ad01e4f081b005
[]
no_license
TForren/ARMA_Mission_Archive
33be0d8e305349eabadeadb485a49b191575f277
8b8db53beec8297c550f25b3107dc260dedf4e9b
refs/heads/master
2021-07-26T00:39:30.949043
2017-11-05T20:36:16
2017-11-05T20:36:16
109,613,817
1
1
null
null
null
null
UTF-8
C++
false
false
391
cpp
config.cpp
class CfgSounds { sounds[] = { }; class flies1 { name="flies1"; sound[]={"sounds\flies1.ogg",db+15,1.0,0.5}; titles[]={}; }; class flies2 { name="flies2"; sound[]={"sounds\flies2.ogg",db+15,1.0,0.5}; titles[]={}; }; class flies3 { name="flies3"; sound[]={"sounds\flies3.ogg",db+15,1.0,0.5}; titles[]={}; }; };
be4f03a3ef86eb79658653165f1ddaa7c34aa645
418951d67fe92f26eaa9ce768059e8047c947eaf
/punteros.cpp
56a5786822e310178d08bdb664ae46682abb8d44
[]
no_license
Danielafe7GitHub/EDA
f80477bbecbe48dcb40d5655abcb035214eb705a
df48fa090b9a244688dba01ca6253483ebb9c483
refs/heads/master
2020-11-30T15:23:05.483694
2016-09-16T14:56:04
2016-09-16T14:56:04
67,265,808
0
0
null
null
null
null
UTF-8
C++
false
false
1,248
cpp
punteros.cpp
<<<<<<< HEAD #include <iostream> using namespace std; int main() { int array[7] = {1, 5, 3, 4, 5, 6, 7}; int *ptr = array; /*Apunta al primer elemento del array*/ for (int i = 0; i < 7; i++) { cout << array[i]; } cout << endl; cout << "Contenido del Puntero " << *ptr << endl; cout << *ptr++ << endl;/*Lo deja apuntando en 7*/ cout << *ptr << endl; cout<<"Actualizando Valores"<<endl; ptr = array; cout << "Contenido del Puntero " << *ptr << endl; cout << *++ptr << endl; cout<<"Actualizando Valores"<<endl; ptr = array; cout << "Contenido del Puntero " << *ptr << endl; cout << ++*ptr << endl; cout<<"Actualizando Valores"<<endl; cout << "Contenido del Puntero " << *ptr << endl; ptr = array; cout << (*ptr)++ << endl; return 0; } ======= void Resta(int X,int Y) { int result; result= X-Y; cout<<result<<endl; } void imprimir() { cout<<"Bienvenido "<<endl; } void Suma(int X, int Y) { imprimir(); int result; result=X+Y; cout<<result<<endl; } int main() { cout<<"Ramitas"<<endl; Suma(8,7) ; cout<<"Se ha finalizado la OPeracion" <<endl; } >>>>>>> 38c6cfe3983618fbe20d6cd3ab514348fb56b21b
5de804c51c46e32bcaedba61093bb1c333d098ea
cc37b234e06b9b51ea44e1d84c1e673db8b66857
/domain-server/src/DomainServerSettingsManager.cpp
9c741b2a3b3bac35af47e548df2b458e9fe200cf
[ "Apache-2.0" ]
permissive
Adrianl3d/hifi
b557a7af3236de539150118ef46e4feafe443de9
7bd01f606b768f6aa3e21d48959718ad249a3551
refs/heads/master
2021-01-17T09:04:27.782837
2014-12-14T00:58:24
2014-12-14T00:58:24
22,494,482
0
0
null
2014-09-30T08:20:14
2014-08-01T03:48:17
null
UTF-8
C++
false
false
9,305
cpp
DomainServerSettingsManager.cpp
// // DomainServerSettingsManager.cpp // domain-server/src // // Created by Stephen Birarda on 2014-06-24. // Copyright 2014 High Fidelity, Inc. // // Distributed under the Apache License, Version 2.0. // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #include <QtCore/QCoreApplication> #include <QtCore/QFile> #include <QtCore/QJsonArray> #include <QtCore/QJsonObject> #include <QtCore/QUrl> #include <QtCore/QUrlQuery> #include <Assignment.h> #include <HTTPConnection.h> #include "DomainServerSettingsManager.h" const QString SETTINGS_DESCRIPTION_RELATIVE_PATH = "/resources/web/settings/describe.json"; const QString SETTINGS_CONFIG_FILE_RELATIVE_PATH = "/resources/config.json"; DomainServerSettingsManager::DomainServerSettingsManager() : _descriptionObject(), _settingsMap() { // load the description object from the settings description QFile descriptionFile(QCoreApplication::applicationDirPath() + SETTINGS_DESCRIPTION_RELATIVE_PATH); descriptionFile.open(QIODevice::ReadOnly); _descriptionObject = QJsonDocument::fromJson(descriptionFile.readAll()).object(); // load the existing config file to get the current values QFile configFile(QCoreApplication::applicationDirPath() + SETTINGS_CONFIG_FILE_RELATIVE_PATH); if (configFile.exists()) { configFile.open(QIODevice::ReadOnly); _settingsMap = QJsonDocument::fromJson(configFile.readAll()).toVariant().toMap(); } } const QString DESCRIPTION_SETTINGS_KEY = "settings"; const QString SETTING_DEFAULT_KEY = "default"; bool DomainServerSettingsManager::handlePublicHTTPRequest(HTTPConnection* connection, const QUrl &url) { if (connection->requestOperation() == QNetworkAccessManager::GetOperation && url.path() == "/settings.json") { // this is a GET operation for our settings // check if there is a query parameter for settings affecting a particular type of assignment const QString SETTINGS_TYPE_QUERY_KEY = "type"; QUrlQuery settingsQuery(url); QString typeValue = settingsQuery.queryItemValue(SETTINGS_TYPE_QUERY_KEY); QJsonObject responseObject; if (typeValue.isEmpty()) { // combine the description object and our current settings map responseObject["descriptions"] = _descriptionObject; responseObject["values"] = QJsonDocument::fromVariant(_settingsMap).object(); } else { // convert the string type value to a QJsonValue QJsonValue queryType = QJsonValue(typeValue.toInt()); const QString AFFECTED_TYPES_JSON_KEY = "assignment-types"; // enumerate the groups in the description object to find which settings to pass foreach(const QString& group, _descriptionObject.keys()) { QJsonObject groupObject = _descriptionObject[group].toObject(); QJsonObject groupSettingsObject = groupObject[DESCRIPTION_SETTINGS_KEY].toObject(); QJsonObject groupResponseObject; foreach(const QString& settingKey, groupSettingsObject.keys()) { QJsonObject settingObject = groupSettingsObject[settingKey].toObject(); QJsonArray affectedTypesArray = settingObject[AFFECTED_TYPES_JSON_KEY].toArray(); if (affectedTypesArray.isEmpty()) { affectedTypesArray = groupObject[AFFECTED_TYPES_JSON_KEY].toArray(); } if (affectedTypesArray.contains(queryType)) { // this is a setting we should include in the responseObject // we need to check if the settings map has a value for this setting QVariant variantValue; QVariant settingsMapGroupValue = _settingsMap.value(group); if (!settingsMapGroupValue.isNull()) { variantValue = settingsMapGroupValue.toMap().value(settingKey); } if (variantValue.isNull()) { // no value for this setting, pass the default groupResponseObject[settingKey] = settingObject[SETTING_DEFAULT_KEY]; } else { groupResponseObject[settingKey] = QJsonValue::fromVariant(variantValue); } } } if (!groupResponseObject.isEmpty()) { // set this group's object to the constructed object responseObject[group] = groupResponseObject; } } } connection->respond(HTTPConnection::StatusCode200, QJsonDocument(responseObject).toJson(), "application/json"); return true; } return false; } bool DomainServerSettingsManager::handleAuthenticatedHTTPRequest(HTTPConnection *connection, const QUrl &url) { if (connection->requestOperation() == QNetworkAccessManager::PostOperation && url.path() == "/settings.json") { // this is a POST operation to change one or more settings QJsonDocument postedDocument = QJsonDocument::fromJson(connection->requestContent()); QJsonObject postedObject = postedDocument.object(); // we recurse one level deep below each group for the appropriate setting recurseJSONObjectAndOverwriteSettings(postedObject, _settingsMap, _descriptionObject); // store whatever the current _settingsMap is to file persistToFile(); // return success to the caller QString jsonSuccess = "{\"status\": \"success\"}"; connection->respond(HTTPConnection::StatusCode200, jsonSuccess.toUtf8(), "application/json"); return true; } return false; } const QString SETTING_DESCRIPTION_TYPE_KEY = "type"; void DomainServerSettingsManager::recurseJSONObjectAndOverwriteSettings(const QJsonObject& postedObject, QVariantMap& settingsVariant, QJsonObject descriptionObject) { foreach(const QString& key, postedObject.keys()) { QJsonValue rootValue = postedObject[key]; // we don't continue if this key is not present in our descriptionObject if (descriptionObject.contains(key)) { if (rootValue.isString()) { if (rootValue.toString().isEmpty()) { // this is an empty value, clear it in settings variant so the default is sent settingsVariant.remove(key); } else { if (descriptionObject[key].toObject().contains(SETTING_DESCRIPTION_TYPE_KEY)) { // for now this means that this is a double, so set it as a double settingsVariant[key] = rootValue.toString().toDouble(); } else { settingsVariant[key] = rootValue.toString(); } } } else if (rootValue.isBool()) { settingsVariant[key] = rootValue.toBool(); } else if (rootValue.isObject()) { // there's a JSON Object to explore, so attempt to recurse into it QJsonObject nextDescriptionObject = descriptionObject[key].toObject(); if (nextDescriptionObject.contains(DESCRIPTION_SETTINGS_KEY)) { if (!settingsVariant.contains(key)) { // we don't have a map below this key yet, so set it up now settingsVariant[key] = QVariantMap(); } QVariantMap& thisMap = *reinterpret_cast<QVariantMap*>(settingsVariant[key].data()); recurseJSONObjectAndOverwriteSettings(rootValue.toObject(), thisMap, nextDescriptionObject[DESCRIPTION_SETTINGS_KEY].toObject()); if (thisMap.isEmpty()) { // we've cleared all of the settings below this value, so remove this one too settingsVariant.remove(key); } } } } } } QByteArray DomainServerSettingsManager::getJSONSettingsMap() const { return QJsonDocument::fromVariant(_settingsMap).toJson(); } void DomainServerSettingsManager::persistToFile() { QFile settingsFile(QCoreApplication::applicationDirPath() + SETTINGS_CONFIG_FILE_RELATIVE_PATH); if (settingsFile.open(QIODevice::WriteOnly)) { settingsFile.write(getJSONSettingsMap()); } else { qCritical("Could not write to JSON settings file. Unable to persist settings."); } }
ec722eaf4b071e31f503b37a9168c723da9ae962
f0130a980e74692a311aee2db9573456e737d31f
/41.first_missing_positive.cpp
44e3d07397fa5bb3ea408849039a98af32adedfc
[]
no_license
rahulinsane11/leetcode
e31ed9e2ae76572263cd0cf4900bb1e629ce9510
6207df6c0249a108a3e38786dc022cdcf85e09fd
refs/heads/main
2023-07-15T19:51:09.546239
2021-08-17T07:47:38
2021-08-17T07:47:38
382,948,860
0
0
null
null
null
null
UTF-8
C++
false
false
456
cpp
41.first_missing_positive.cpp
class Solution { public: int firstMissingPositive(vector<int>& nums) { // T.C.=O(nlogn) ; S.C.=O(1) int n=nums.size(), min=1; sort(nums.begin(),nums.end()); for(int i=0; i<n; i++) { if(nums[i]>0) { if(nums[i]==min) min++; else if(nums[i]>min) return min; } } return min; } };
5443f04067c91505c11157c8ce1466e9f40eb7eb
4da66fb8568f88e8ad777ca29732166e5fe0704a
/tests/cpp/rpytest/ft/include/lifetime.h
eb04dde9f9a9af306e81cce50671633d28fba5d2
[ "BSD-3-Clause" ]
permissive
robotpy/robotpy-build
b5b091b9a1ccdd995da492f50b515f67fbfdd8d1
8274a674f6177906fe38309ae008b783a0c9b159
refs/heads/main
2023-07-12T03:33:17.326548
2023-07-07T14:37:40
2023-07-07T14:37:40
214,119,803
32
19
BSD-3-Clause
2023-09-10T23:58:02
2019-10-10T07:47:40
Python
UTF-8
C++
false
false
344
h
lifetime.h
#pragma once #include <memory> struct LTWithVirtual { virtual bool get_bool() { return false; } }; class LTTester { public: void set_val(std::shared_ptr<LTWithVirtual> val) { m_val = val; } bool get_bool() { return m_val->get_bool(); } private: std::shared_ptr<LTWithVirtual> m_val; };
c13e6136afad894cda6c51ff45fcf85af1cdf669
b77349e25b6154dae08820d92ac01601d4e761ee
/Bar/Scrollbar/Scrollbar ActiveX/XPBtn_Scroll/_vscroll.cpp
51ca8764019ab03ee8b327d9a8f240536e77bd4d
[]
no_license
ShiverZm/MFC
e084c3460fe78f820ff1fec46fe1fc575c3e3538
3d05380d2e02b67269d2f0eb136a3ac3de0dbbab
refs/heads/master
2023-02-21T08:57:39.316634
2021-01-26T10:18:38
2021-01-26T10:18:38
332,725,087
0
0
null
2021-01-25T11:35:20
2021-01-25T11:29:59
null
UTF-8
C++
false
false
1,255
cpp
_vscroll.cpp
// Machine generated IDispatch wrapper class(es) created by Microsoft Visual C++ // NOTE: Do not modify the contents of this file. If this class is regenerated by // Microsoft Visual C++, your modifications will be overwritten. #include "stdafx.h" #include "_vscroll.h" ///////////////////////////////////////////////////////////////////////////// // C_VScroll IMPLEMENT_DYNCREATE(C_VScroll, CWnd) ///////////////////////////////////////////////////////////////////////////// // C_VScroll properties ///////////////////////////////////////////////////////////////////////////// // C_VScroll operations CString C_VScroll::GetLargeChange() { CString result; InvokeHelper(0x68030001, DISPATCH_PROPERTYGET, VT_BSTR, (void*)&result, NULL); return result; } void C_VScroll::SetLargeChange(LPCTSTR lpszNewValue) { static BYTE parms[] = VTS_BSTR; InvokeHelper(0x68030001, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, lpszNewValue); } short C_VScroll::GetValue() { short result; InvokeHelper(0x68030000, DISPATCH_PROPERTYGET, VT_I2, (void*)&result, NULL); return result; } void C_VScroll::SetValue(short nNewValue) { static BYTE parms[] = VTS_I2; InvokeHelper(0x68030000, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms, nNewValue); }
ef38d1859d5ceb98e3fbdc2e1980a6785daf59ea
e69c6452c8ce23d552ef39da4752f8c620b939b9
/Code/CPP/PCSX2/pcsx2/gui/Resources/EmbeddedImage.h
1e5eaad9c7ad72f987f81db8d23c75331f2fe35d
[]
no_license
madnessw/thesnow
31a155e428bb6f79d2003c229cf2e570ca620c0f
0f1aeb7903397dda06e0044aa6e35cc2705ed71c
refs/heads/master
2021-01-23T12:00:27.906724
2014-01-09T05:42:41
2014-01-09T05:42:41
37,446,411
1
1
null
null
null
null
UTF-8
C++
false
false
5,114
h
EmbeddedImage.h
/* PCSX2 - PS2 Emulator for PCs * Copyright (C) 2002-2010 PCSX2 Dev Team * * PCSX2 is free software: you can redistribute it and/or modify it under the terms * of the GNU Lesser General Public License as published by the Free Software Found- * ation, either version 3 of the License, or (at your option) any later version. * * PCSX2 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 PCSX2. * If not, see <http://www.gnu.org/licenses/>. */ #pragma once #include <wx/image.h> #include <wx/mstream.h> #include <wx/gdicmn.h> ////////////////////////////////////////////////////////////////////////////////////////// // Interface for loadable embedded images. See EmbeddedImage description for details. // class IEmbeddedImage { public: virtual const wxImage& Get()=0; virtual wxImage Rescale( int width, int height )=0; virtual wxImage Resample( int width, int height )=0; }; ////////////////////////////////////////////////////////////////////////////////////////// // EmbeddedImage - Helper class for loading images which have been embedded into the binary // manifest of the executable file. Images are only loaded when Get() is called, // which allows this type to be passed to functions as a fallback or default action without // incurring an unnecessary memory footprint. // // Note: Get() only loads the image once. All subsequent calls to Get will use the // previously loaded image data. // template< typename ImageType > class EmbeddedImage : public IEmbeddedImage { protected: wxImage m_Image; const wxSize m_ResampleTo; protected: // ------------------------------------------------------------------------ // Internal function used to ensure the image is loaded before returning the image // handle (called from all methods that return an image handle). // void _loadImage() { if( !m_Image.Ok() ) { wxMemoryInputStream joe( ImageType::Data, ImageType::Length ); m_Image.LoadFile( joe, ImageType::GetFormat() ); if( m_ResampleTo.IsFullySpecified() && ( m_ResampleTo.GetWidth() != m_Image.GetWidth() || m_ResampleTo.GetHeight() != m_Image.GetHeight() ) ) m_Image = m_Image.ResampleBox( m_ResampleTo.GetWidth(), m_ResampleTo.GetHeight() ); } } public: EmbeddedImage() : m_Image() , m_ResampleTo( wxDefaultSize ) { } // ------------------------------------------------------------------------ // Constructor for creating an embedded image that gets resampled to the specified size when // loaded. // // Implementation Note: This function uses wxWidgets ResamplBox method to resize the image. // wxWidgets ResampleBicubic appears to be buggy and produces fairly poor results when down- // sampling images (basically resembles a pixel resize). ResampleBox produces much cleaner // results. // EmbeddedImage( int newWidth, int newHeight ) : m_Image() , m_ResampleTo( newWidth, newHeight ) { } // ------------------------------------------------------------------------ // Loads and retrieves the embedded image. The embedded image is only loaded from its em- // bedded format once. Any subsequent calls to Get(), Rescale(), or Resample() will use // the pre-loaded copy. Translation: the png/jpeg decoding overhead happens only once, // and only happens when the image is actually fetched. Simply creating an instance // of an EmbeddedImage object uses no excess memory nor cpu overhead. :) // const wxImage& Get() { _loadImage(); return m_Image; } wxIcon GetIcon() { wxIcon retval; retval.CopyFromBitmap( Get() ); return retval; } // ------------------------------------------------------------------------ // Performs a pixel resize of the loaded image and returns a new image handle (EmbeddedImage // is left unmodified). Useful for creating ugly versions of otherwise nice graphics. Do // us all a favor and use Resample() instead. // // (this method included for sake of completeness only). // wxImage Rescale( int width, int height ) { _loadImage(); if( width != m_Image.GetWidth() || height != m_Image.GetHeight() ) return m_Image.Rescale( width, height ); else return m_Image; } // ------------------------------------------------------------------------ // Implementation Note: This function uses wxWidgets ResampleBox method to resize the image. // wxWidgets ResampleBicubic appears to be buggy and produces fairly poor results when down- // sampling images (basically resembles a pixel resize). ResampleBox produces much cleaner // results. // wxImage Resample( int width, int height ) { _loadImage(); if( width != m_Image.GetWidth() || height != m_Image.GetHeight() ) return m_Image.ResampleBox( width, height ); else return m_Image; } };
be8bf77663bc0748b60ab443d40ad9cc0b1b3a38
5cc7297c191e27fbfbc1a940830e2bbe7d2c5fb3
/AST.h
c4b9a59d96fe56b2d9246416de96754a6be6f249
[]
no_license
bsblcc/Compiler
dc7dd630d1d66366a708ff039906bfd5f1522695
d6c4159854cab57111204dbbb7b445c8cf3c7003
refs/heads/master
2021-01-16T05:40:57.583465
2020-02-25T13:12:49
2020-02-25T13:12:49
242,995,579
0
0
null
null
null
null
UTF-8
C++
false
false
7,990
h
AST.h
#include <vector> #include <list> #include <iostream> #include "type.h" #include <fstream> #ifndef AST_H #define AST_H using namespace std; const string ASTNode_dic[] = { "root", "translation unit", "external declaration", "function definition", "function declaration", "variable declaration", "type specifier", "variable declarator list", "initial variable declarator", "variable declarator", "function definition declarator", "parameter declaration list", "parameter declaration", "show symbol table", "statement", "compound statement", "expression statement", "selection statement", "iteration statement", "expression", "assignment expression", "unary expression", "postfix expression", "argument expression list", "logical-or expression", "logical-and expression", "inclusive-or expression", "exclusive-or expression", "and expression", "equality expression", "relational expression", "shift expression", "additive expression", "multiplicative expression", "primary expression", "jump statement", "struct declaration", "left bracet", "right bracet", "struct variable declaration list", }; enum ASTNode_type { ROOT, TRANS_UNIT, EXTERN_DECL, FUNC_DEF, FUNC_DECL, VAR_DECL, TYPE_SPEC, VAR_DECLARATOR_LIST, INIT_VAR_DECLARATOR, VAR_DECLARATOR, FUNC_DEF_DECLARATOR, PARAM_DECL_LIST, PARAM_DECL, SHOW_STAB, STATEMENT, COMPOUND_STMT, EXPRESSION_STMT, SELECTION_STMT, ITERATION_STMT, EXPRESSION, ASSIGN_EXPR, UNARY_EXPR, POSTFIX_EXPR, ARGUMENT_EXPR_LIST, LOGICALOR_EXPR, LOGICALAND_EXPR, INCLUSIVEOR_EXPR, EXCLUSIVEOR_EXPR, AND_EXPR, EQUALITY_EXPR, RELATIONAL_EXPR, SHIFT_EXPR, ADDITIVE_EXPR, MULTIPLICATIVE_EXPR, PRIMARY_EXPR, JUMP_STMT, STRUCT_DECL, LEFT_BRACET, RIGHT_BRACET, STRUCT_VAR_DECL_LIST, }; class AST_node { public: std::vector<AST_node*> child; int height; string blank_buffer; virtual int get_nodeType(); void print_nodeName(); virtual void print_info(); void print(); void bracet_begin(); void bracet_end(); void insertChild(AST_node* t) { child.push_back(t); } template <typename T, typename... Args> void insertChild(T t, Args... args) { //std::cout << t <<std::endl ; child.push_back(t); insertChild(args...) ; } }; class transUnit_node : public AST_node { public: virtual int get_nodeType(); }; class externDecl_node : public transUnit_node { public: virtual int get_nodeType(); }; class funcDef_node : public externDecl_node { public: virtual int get_nodeType(); }; class funcDecl_node : public externDecl_node { public: virtual int get_nodeType(); }; class varDecl_node : public externDecl_node { public: virtual int get_nodeType(); }; class typeSpec_node : public AST_node { public: virtual int get_nodeType(); enum { STRUCT, BUILTIN, } type; enum builtInType_type { INT_TYPE, VOID_TYPE, CHAR_TYPE, FLOAT_TYPE, }; union { string* name; builtInType_type builtInType; }; virtual void print_info(); }; class varDeclaratorList_node : public AST_node { public: virtual int get_nodeType(); }; class initVarDeclarator_node : public AST_node { public: virtual int get_nodeType(); }; class varDeclarator_node : public AST_node { public: virtual int get_nodeType(); string varName; list<typeSpecifier_type> typeSpecifierList; virtual void print_info(); }; class funcDefDeclarator_node : public AST_node { public: virtual int get_nodeType(); string funcName; list<typeSpecifier_type> typeSpecifierList; virtual void print_info(); }; class paramDeclList_node : public AST_node { public: virtual int get_nodeType(); }; class paramDecl_node : public AST_node { public: virtual int get_nodeType(); }; class showStab_node : public AST_node { public: virtual int get_nodeType(); }; class Statement_node : public AST_node { public: virtual int get_nodeType(); }; class compoundStmt_node : public Statement_node { public: virtual int get_nodeType(); }; class expressionStmt_node : public Statement_node { public: virtual int get_nodeType(); }; class selectionStmt_node : public Statement_node { public: virtual int get_nodeType(); }; class iterationStmt_node : public Statement_node { public: virtual int get_nodeType(); }; class Expression_node : public AST_node { public: virtual int get_nodeType(); Type_type *type_p; bool lValue; int id; static int count; int usage; Expression_node(); virtual string getOpStr(); void printQuad(); }; class assignExpr_node : public Expression_node { public: virtual int get_nodeType(); virtual string getOpStr(); }; class unaryExpr_node : public Expression_node { public: virtual int get_nodeType(); enum { INC_OP, DEC_OP, REF_OP, IDR_OP, PLUS_OP, MINUS_OP, NEG_OP, CMPL_OP, PRINT_OP } expr_operator; virtual void print_info(); static const string unary_op_dic[]; virtual string getOpStr(); }; class postfixExpr_node : public Expression_node { public: virtual int get_nodeType(); enum { SUBSCRIPT_OP, FUNC_CALL_OP, DOT_OP, AR_OP, INC_OP, DEC_OP, } expr_operator; string memberName; virtual void print_info(); static const string postfix_op_dic[]; virtual string getOpStr(); }; class argumentExprList_node : public Expression_node { public: virtual int get_nodeType(); //virtual string getOpStr(); }; class logicalOrExpr_node : public Expression_node { public: virtual int get_nodeType(); virtual string getOpStr(); }; class logicalAndExpr_node : public Expression_node { public: virtual int get_nodeType(); virtual string getOpStr(); }; class inclusiveOrExpr_node : public Expression_node { public: virtual int get_nodeType(); virtual string getOpStr(); }; class exclusiveOrExpr_node : public Expression_node { public: virtual int get_nodeType(); virtual string getOpStr(); }; class andExpr_node : public Expression_node { public: virtual int get_nodeType(); virtual string getOpStr(); }; class equalityExpr_node : public Expression_node { public: virtual int get_nodeType(); enum { EQ_OP, NE_OP, } expr_operator; virtual void print_info(); static const string equality_op_dic[]; virtual string getOpStr(); }; class relationalExpr_node : public Expression_node { public: virtual int get_nodeType(); enum { L_OP, G_OP, LE_OP, GE_OP, } expr_operator; virtual void print_info(); static const string relational_op_dic[]; virtual string getOpStr(); }; class shiftExpr_node : public Expression_node { public: virtual int get_nodeType(); enum { LSHIFT_OP, RSHIFT_OP, } expr_operator; virtual void print_info(); static const string shift_op_dic[]; virtual string getOpStr(); }; class additiveExpr_node : public Expression_node { public: virtual int get_nodeType(); enum { ADD_OP, SUB_OP, } expr_operator; virtual void print_info(); static const string additive_op_dic[]; virtual string getOpStr(); }; class multiplicativeExpr_node : public Expression_node { public: virtual int get_nodeType(); virtual void print_info(); enum { MUL_OP, DIV_OP, } expr_operator; static const string multiplicative_op_dic[]; virtual string getOpStr(); }; class primaryExpr_node : public Expression_node { public: virtual int get_nodeType(); enum { ID, INT, FLOAT, STRING, CHAR } valueType; string primaryValue; const static string valueType_dic[]; virtual void print_info(); virtual string getOpStr(); }; class jumpStmt_node : public AST_node { public: virtual int get_nodeType(); virtual void print_info(); enum { BREAK, RETURN, CONTINUE, } jump_type; static const string jump_type_dic[]; }; class leftBracet_node: public AST_node { public: virtual int get_nodeType(); virtual void print_info(); }; class rightBracet_node: public AST_node { public: virtual int get_nodeType(); virtual void print_info(); }; class structDecl_node : public externDecl_node { public: virtual int get_nodeType(); string name; }; class structVarDeclList_node: public AST_node { public: virtual int get_nodeType(); }; void print(AST_node* t); #endif
d57763971386770f0442ff26c0cac5c37498db2a
c3dd5418d36b83e2e8f1784093a2ed677ee57846
/Model/modellist.cpp
3fa0d6878aae90dcf7d7e64fe8c21e63a5d403c4
[]
no_license
yuanyuanc03/Game-Mario
c42d7713f66aa2473ae190fccf4a6ab9b52217b2
8f8231a385d574ed15b4338cf1cbb42d1f10f6a6
refs/heads/master
2022-10-02T04:34:34.473224
2020-05-25T22:10:23
2020-05-25T22:11:59
263,081,638
0
0
null
2020-05-25T21:25:16
2020-05-11T15:25:56
C++
UTF-8
C++
false
false
9,749
cpp
modellist.cpp
#include "modellist.h" #include <QFile> ModelList::ModelList() { this->background = new QList<Background *>; this->floors = new QList<Floor *>; this->bricks = new QList<Brick*>; this->mushrooms = new QList<Mushroom *>; this->golds = new QList<Gold *>; this->flames = new QList<Flame *>; this->splashscreen = new SplashScreen(330, 170, ":/files/images/go2.png"); this->darkeaters = new QList<DarkEater *>; this->background = new QList<Background *>; this->score = new Score(); this->models = new QList<Model*> ; this->trees = new QList<Tree *>; this->mario = new Mario(200, 340); this->blood = new Blood(0, 0); this->shock = new Shock(0, 0); this->label = new Label(0, 0, ""); this->getLabel()->setType(LabelType::NONE); this->time = new Time(0, 0); QFile fichier(":/files/ModelMap.txt"); if(fichier.open(QIODevice::ReadOnly)) { QTextStream in (&fichier); while(!in.atEnd()) { QString stock = in.readLine(); if (stock.left(6)=="LIGNEa") { for(int i = 0; i < stock.size(); ++i) { if(stock.at(i).isDigit() || stock.at(i).isLetter()) { this->list1.append(stock.at(i)); } } } else if (stock.left(6)=="LIGNEb") { for(int i=0;i<stock.size();++i) { if(stock.at(i).isDigit() || stock.at(i).isLetter()) { this->list2.append(stock.at(i)); } } } else if (stock.left(6)=="LIGNEc") { for(int i=0;i<stock.size();++i) { if(stock.at(i).isDigit() || stock.at(i).isLetter()) { this->list3.append(stock.at(i)); } } } else if (stock.left(6)=="LIGNEd") { for(int i=0;i<stock.size();++i) { if(stock.at(i).isDigit() || stock.at(i).isLetter()) { this->list4.append(stock.at(i)); } } } else if (stock.left(6)=="LIGNEe") { for(int i=0;i<stock.size();++i) { if(stock.at(i).isDigit() || stock.at(i).isLetter()) { this->list5.append(stock.at(i)); } } } else if (stock.left(6)=="LIGNEf") { for(int i=0;i<stock.size();++i) { if(stock.at(i).isDigit() || stock.at(i).isLetter()) { this->list6.append(stock.at(i)); } } } } fichier.close(); } for (int i = 0; i < this->NbModelVisible; i++) { Floor *k = new Floor(i*this->modelSize, this->Height - this->modelSize, QString(":/files/images/floor_bottom.jpg")); this->floors->append(k); Floor *k2 = new Floor(i*this->modelSize, this->Height - 2*this->modelSize, QString(":/files/images/floor_grass.png")); this->floors->append(k2); } for (int i = 0; i < this->NbModelVisible; i++) { Model *model = new Model(i*this->modelSize, this->Height + this->modelSize); this->models->append(model); } for (int i = 0; i < 2; i++) { Background* bg = new Background(i*ModelList::Width, 0); this->background->append(bg); } } ModelList::~ModelList() { this->floors->clear(); delete this->floors; this->golds->clear(); delete this->golds; this->models->clear(); delete this->models; this->background->clear(); delete this->background; this->mushrooms->clear(); delete this->mushrooms; this->darkeaters->clear(); delete this->darkeaters; this->flames->clear(); delete this->flames; this->trees->clear(); delete this->trees; delete this->mario; delete this->splashscreen; } void ModelList::createModel(QList<QChar> c, int num, int x) { QChar myChar = c.at(this->mapPosition); if(myChar == '0') return; else if(myChar == '1') { Floor *k= new Floor(x + this->modelSize, this->Height - num*this->modelSize, QString(":/files/images/floor_bottom.jpg")); this->floors->append(k); return; } else if(myChar == '2') { Brick* t= new Brick(x + this->modelSize, this->Height - num*this->modelSize); this->bricks->append(t); return; } else if(myChar == '3') { Gold* g= new Gold(x + this->modelSize, this->Height - num*this->modelSize); this->golds->append(g); return; } else if(myChar == '4') { DarkEater* d = new DarkEater(x + this->modelSize, this->Height - num*this->modelSize); d->setMoveX(false); this->darkeaters->append(d); return; } else if(myChar == '5') { Flame* f = new Flame(x + this->modelSize, this->Height - num*this->modelSize); f->setMoveX(false); this->flames->append(f); return; } else if(myChar == '6') { Brick* t= new Brick(x + this->modelSize, this->Height - num*this->modelSize); t->setCapacity(2); this->bricks->append(t); return; } else if(myChar == '7') { Floor *k= new Floor(x + this->modelSize, this->Height - num*this->modelSize, QString(":/files/images/floor_grass.png")); floors->append(k); return; } else if(myChar == '8') { Floor *k= new Floor(x + this->modelSize, this->Height - num*this->modelSize, QString(":/files/images/floor_right.png")); floors->append(k); return; } else if(myChar == '9') { Floor *k= new Floor(x + this->modelSize, this->Height - num*this->modelSize, QString(":/files/images/floor_left.png")); floors->append(k); return; } else if(myChar == 'a'){ Tree *k= new Tree(x + this->modelSize, this->Height - num*this->modelSize); this->trees->append(k); return; } } void ModelList::modelOrganisation() { for(int i = 0; i < this->background->size(); i++) { if(this->background->at(i)->getRect().x() < -this->background->at(i)->getRect().width() + 2) { this->background->removeAt(i); Background* b = new Background(1000,0); this->background->append(b); } } if(this->models->last()->getRect().x() < ((this->NbModelVisible)*this->modelSize)) { Model *m = new Model(this->models->last()->getRect().x() + this->modelSize, this->Height + this->modelSize); this->createModel(this->list1, 1, this->models->last()->getRect().x()); this->createModel(this->list2, 2, this->models->last()->getRect().x()); this->createModel(this->list3, 3, this->models->last()->getRect().x()); this->createModel(this->list4, 4, this->models->last()->getRect().x()); this->createModel(this->list5, 5, this->models->last()->getRect().x()); this->createModel(this->list6, 6, this->models->last()->getRect().x()); this->models->append(m); this->mapPosition++; } if (this->models->first()->getRect().x() <= -this->modelSize) { this->models->removeAt(this->models->indexOf(this->models->first())); } for(int i = 0; i < this->floors->size(); i++) { if (this->floors->at(i)->getRect().x() <= -this->modelSize || this->floors->at(i)->isDestroyed()) this->floors->removeAt(i); } for(int i = 0; i < this->bricks->size(); i++) { if (this->bricks->at(i)->getRect().x() <= -this->modelSize || this->bricks->at(i)->isDestroyed()) { this->bricks->removeAt(i); } } for(int i = 0; i < this->golds->size(); i++) { if (this->golds->at(i)->getRect().x() <= -this->modelSize || golds->at(i)->isDestroyed()) { golds->removeAt(i); } } for(int i = 0; i < this->mushrooms->size(); i++){ if (this->mushrooms->at(i)->getRect().x() <= -this->modelSize || this->mushrooms->at(i)->isDestroyed()) { this->mushrooms->removeAt(i); } } for(int i = 0; i < this->flames->size(); i++) { if (this->flames->at(i)->getRect().x() <= -this->modelSize || this->flames->at(i)->isDestroyed()) { this->flames->removeAt(i); } } for(int i = 0; i < this->darkeaters->size(); i++) { if (this->darkeaters->at(i)->getRect().x() <= -this->modelSize ) { this->darkeaters->removeAt(i); } } } void ModelList::createMushroom(int x, int y, bool up) { Mushroom *m = new Mushroom(x + 9, y + 10, up); m->setYR(0); m->setXR(0); m->setStartY(m->getRect().y() + 50); this->mushrooms->append(m); } void ModelList::createGameOver(int x, int y) { this->splashscreen = new SplashScreen(x, y, ":/files/images/gameover.png"); } void ModelList::createCompleted(int x, int y) { this->splashscreen = new SplashScreen(x, y, ":/files/images/level_complete.png"); } void ModelList::createPrincess(int x, int y) { this->princess = new Princess(x, y); this->princess->setIsMovingL(true); } void ModelList::createLabel(int x, int y, QString path) { this->label = new Label(x, y, path); }
f7f82c2adf291526b3fc1899b49845e2558f5520
da210c63cddec28ea4aeb0d06ec8f6ca1139aba7
/src/Analysis.cc
eaf7edbe06cced78c89947333e41e91356828483
[]
no_license
denschwarz/PPT-Analysis
3ae022f6786db7168becd864308f37e65b489e0e
7fe8b05704ecac3dcb4c73a5e8093b81b8dd1d64
refs/heads/master
2021-07-08T02:43:44.066249
2019-08-06T19:45:41
2019-08-06T19:45:41
141,400,198
0
0
null
2019-02-06T16:04:47
2018-07-18T07:48:30
C++
UTF-8
C++
false
false
12,263
cc
Analysis.cc
#include "../include/Analysis.h" /* Dies ist der eigentliche Analyse-Code. Hier werden die rohen Root Dateien jedes Prozesses eingelesen und verarbeitet. Ihr koennt hier Variablen zusammensetzen und Histogramme fuellen. Der Output wird gesammelt in einer weiteren Root Datei abgespeichert. */ int main(int argc, char* argv[]){ // --------------------------------------------------------------------------- // Hier wird der Name der Output Datei vergeben TString outputName = "Histograms.root"; TFile* outputFile=new TFile(outputName,"recreate"); // --------------------------------------------------------------------------- // Hier werden Histogramme definiert. // Dabei ist für jede Größe ein Vektor definiert. // Dieser Vektor enthält je ein Histogramm für jeden Prozess (Daten, Higgs, ZZ, DY) vector<TH1F*> hist_EventCount = CreateHistograms("EventCount",1, 0, 2); vector<TH1F*> hist_muonNUMBER = CreateHistograms("muonNUMBER", 6, -0.5, 5.5); vector<TH1F*> hist_muonPT = CreateHistograms("muonPT", 20, 0, 300); vector<TH1F*> hist_muonPHI = CreateHistograms("muonPHI", 20, -4, 4); vector<TH1F*> hist_muonETA = CreateHistograms("muonETA", 20, -3, 3); vector<TH1F*> hist_muonCHARGE = CreateHistograms("muonCHARGE", 5, -2.5, 2.5); vector<TH1F*> hist_elecNUMBER = CreateHistograms("elecNUMBER", 6, -0.5, 5.5); vector<TH1F*> hist_elecPT = CreateHistograms("elecPT", 20, 0, 300); vector<TH1F*> hist_elecPHI = CreateHistograms("elecPHI", 20, -4, 4); vector<TH1F*> hist_elecETA = CreateHistograms("elecETA", 20, -3, 3); vector<TH1F*> hist_elecCHARGE = CreateHistograms("elecCHARGE", 5, -2.5, 2.5); vector<TH1F*> hist_Zmass = CreateHistograms("Zmass", 20, 0, 150); vector<TH1F*> hist_HIGGSmass = CreateHistograms("HIGGSmass", 30, 0, 220); // --------------------------------------------------------------------------- // Hier findet die eigentliche Analyse statt. // Dabei wird jede Root-Datei geöffnet und ausgelesen. // Daraus erhält man je eine Liste an Elektronen und Myonen. // Diese werden dann für die Analyse ausgewertet int events_tot = 0; int events_2mu2el = 0; int events_4mu = 0; int events_4el = 0; double ptmax = 0; bool iselec = false; int Nsamples = sample_names.size(); // Anzahl an Root-Dateien for(int isample=0; isample<Nsamples; isample++){ // Schleife über alle Root-Dateien for(auto channel: sample_channels[isample]){ // Schleife über alle möglichen Kanäle einer Datei // mögliche Kanäle: "4el", "4mu", "2mu2el" cout << "Analising " << sample_names[isample] << "..." << endl; // Hier werden die Dateien ausgelesen und Vektoren von Myonen und Elektronen erstellt ReadLeptons reader(sample_names[isample], channel); int Nevents = reader.GetEventCount(); vector< vector<Particle> > allMuons = reader.GetMuons(); vector< vector<Particle> > allElecs = reader.GetElectrons(); //// // Gewicht, Histindex auslesen TString process = sample_process[isample]; double weight = sample_weights[isample]; //// // events in data zählen if(process == "data"){ events_tot += Nevents; if(channel == "2mu2el") events_2mu2el += Nevents; else if(channel == "4mu") events_4mu += Nevents; else if(channel == "4el") events_4el += Nevents; } //// /* In der eigentlichen Analyse führen wir für jedes Ereignis aus. Da wir immer das gleiche für jedes Ereignis tun, benutzen wir hier eine Schleife. */ for(int ievent=0; ievent<Nevents; ievent++){ /* Für jedes Ereignis wird zunächst eine Liste Myonen und eine Liste Elektronen angelegt. Diese können im weiteren Verlauf analysiert werden. */ vector<Particle> Muons = allMuons[ievent]; vector<Particle> Elecs = allElecs[ievent]; /* In dieses Histogramm wird für ein Ereignis immer für der selber Wert (1) eingetragen. Damit enthält es am Ende exakt die Anzahl an Ereignissen. */ FillHistogram(hist_EventCount, 1, weight, process); if(channel == "2mu2el"){ /* Hier wird ein Z aus Myonen und ein Z aus Elektronen rekonstruiert In dem 2mu2el Kanal ist hier die Zuordnung eindeutig, weil ein Z immer in 2 Myonen oder 2 Elektronen zerfällt. */ Particle Z1 = Combine(Muons[0], Muons[1]); Particle Z2 = Combine(Elecs[0], Elecs[1]); FillHistogram(hist_Zmass, Z1.Mass(), weight, process); FillHistogram(hist_Zmass, Z2.Mass(), weight, process); // Hier ist das Higgs Particle H = Combine(Z1, Z2); FillHistogram(hist_HIGGSmass, H.Mass(), weight, process); } else if(channel == "4mu"){ // Finde mögliche Kombinationen für Muon[0] mit Hilfe der Ladung // Das zweite Z sind dann die verbleibenden 2 Myonen Particle ZA1, ZA2, ZB1, ZB2; int charge0 = Muons[0].Charge(); int charge1 = Muons[1].Charge(); int charge2 = Muons[2].Charge(); int charge3 = Muons[3].Charge(); if(charge0 != charge1 && charge0 != charge2){ ZA1 = Combine(Muons[0], Muons[1]); ZA2 = Combine(Muons[2], Muons[3]); ZB1 = Combine(Muons[0], Muons[2]); ZB2 = Combine(Muons[1], Muons[3]); } if(charge0 != charge1 && charge0 != charge3){ ZA1 = Combine(Muons[0], Muons[1]); ZA2 = Combine(Muons[2], Muons[3]); ZB1 = Combine(Muons[0], Muons[3]); ZB2 = Combine(Muons[1], Muons[2]); } if(charge0 != charge2 && charge0 != charge3){ ZA1 = Combine(Muons[0], Muons[2]); ZA2 = Combine(Muons[1], Muons[3]); ZB1 = Combine(Muons[0], Muons[3]); ZB2 = Combine(Muons[1], Muons[2]); } // Jetzt muss noch Kombination A oder B ausgewählt werden. // Prüfe dafür welches der 4 Z dichter an der Z-Masse von 91 GeV liegt Particle Z1, Z2; double deltaZA1 = fabs(ZA1.Mass() - 91); double deltaZA2 = fabs(ZA2.Mass() - 91); double deltaZB1 = fabs(ZB1.Mass() - 91); double deltaZB2 = fabs(ZB2.Mass() - 91); if(deltaZA1 < deltaZB1 && deltaZA1 < deltaZB2){ Z1 = ZA1; Z2 = ZA2; } else if(deltaZA2 < deltaZB1 && deltaZA2 < deltaZB2){ Z1 = ZA1; Z2 = ZA2; } else{ Z1 = ZB1; Z2 = ZB2; } FillHistogram(hist_Zmass, Z1.Mass(), weight, process); FillHistogram(hist_Zmass, Z2.Mass(), weight, process); Particle H = Combine(Z1, Z2); FillHistogram(hist_HIGGSmass, H.Mass(), weight, process); } else if(channel == "4el"){ // Finde mögliche Kombinationen für Muon[0] mit Hilfe der Ladung // Das zweite Z sind dann die verbleibenden 2 Myonen Particle ZA1, ZA2, ZB1, ZB2; int charge0 = Elecs[0].Charge(); int charge1 = Elecs[1].Charge(); int charge2 = Elecs[2].Charge(); int charge3 = Elecs[3].Charge(); if(charge0 != charge1 && charge0 != charge2){ ZA1 = Combine(Elecs[0], Elecs[1]); ZA2 = Combine(Elecs[2], Elecs[3]); ZB1 = Combine(Elecs[0], Elecs[2]); ZB2 = Combine(Elecs[1], Elecs[3]); } if(charge0 != charge1 && charge0 != charge3){ ZA1 = Combine(Elecs[0], Elecs[1]); ZA2 = Combine(Elecs[2], Elecs[3]); ZB1 = Combine(Elecs[0], Elecs[3]); ZB2 = Combine(Elecs[1], Elecs[2]); } if(charge0 != charge2 && charge0 != charge3){ ZA1 = Combine(Elecs[0], Elecs[2]); ZA2 = Combine(Elecs[1], Elecs[3]); ZB1 = Combine(Elecs[0], Elecs[3]); ZB2 = Combine(Elecs[1], Elecs[2]); } // Jetzt muss noch Kombination A oder B ausgewählt werden. // Prüfe dafür welches der 4 Z dichter an der Z-Masse von 91 GeV liegt Particle Z1, Z2; double deltaZA1 = fabs(ZA1.Mass() - 91); double deltaZA2 = fabs(ZA2.Mass() - 91); double deltaZB1 = fabs(ZB1.Mass() - 91); double deltaZB2 = fabs(ZB2.Mass() - 91); if(deltaZA1 < deltaZB1 && deltaZA1 < deltaZB2){ Z1 = ZA1; Z2 = ZA2; } else if(deltaZA2 < deltaZB1 && deltaZA2 < deltaZB2){ Z1 = ZA1; Z2 = ZA2; } else{ Z1 = ZB1; Z2 = ZB2; } FillHistogram(hist_Zmass, Z1.Mass(), weight, process); FillHistogram(hist_Zmass, Z2.Mass(), weight, process); Particle H = Combine(Z1, Z2); FillHistogram(hist_HIGGSmass, H.Mass(), weight, process); } // Anzahl an Elektronen bzw. Myonen int numberMUONS = Muons.size(); FillHistogram(hist_muonNUMBER, numberMUONS, weight, process); int numberELECS = Elecs.size(); FillHistogram(hist_elecNUMBER, numberELECS, weight, process); // Schleife über alle Myonen in einem Ereignis ------------------------- for(int i=0; i<Muons.size(); i++){ // Variablen von Myon auslesen double pt = Muons[i].Pt(); double eta = Muons[i].Eta(); double phi = Muons[i].Phi(); int charge = Muons[i].Charge(); // in Histogramme füllen FillHistogram(hist_muonPT, pt, weight, process); FillHistogram(hist_muonETA, eta, weight, process); FillHistogram(hist_muonPHI, phi, weight, process); FillHistogram(hist_muonCHARGE, charge, weight, process); // ptmax finden if(process == "data"){ if(pt > ptmax) ptmax = pt; } } // --------------------------------------------------------------------- // Schleife über alle Elektronen in einem Ereignis --------------------- for(int i=0; i<Elecs.size(); i++){ // Variablen von Myon auslesen double pt = Elecs[i].Pt(); double eta = Elecs[i].Eta(); double phi = Elecs[i].Phi(); int charge = Elecs[i].Charge(); // in Histogramme füllen FillHistogram(hist_elecPT, pt, weight, process); FillHistogram(hist_elecETA, eta, weight, process); FillHistogram(hist_elecPHI, phi, weight, process); FillHistogram(hist_elecCHARGE, charge, weight, process); // ptmax finden if(process == "data"){ if(pt > ptmax) ptmax = pt; } } // --------------------------------------------------------------------- } } } cout << "Events in total: " << events_tot << endl; cout << "Events in 2mu2el: " << events_2mu2el << endl; cout << "Events in 4mu: " << events_4mu << endl; cout << "Events in 4el: " << events_4el << endl; cout << "max pT in data: " << ptmax << endl; // Am Ende: Abspeichern der Histogramme in der Output Datei outputFile->Write(); return 0; } // ----------------------------------------------------------------------------- // Diese Funktion wird aufgerufen um Histogramme zu erstellen ------------------ vector<TH1F*> CreateHistograms(TString histname, int nbins, double min, double max){ vector<TH1F*> hists; vector<TString> processes = {"data", "higgs", "ZZ", "DY"}; for(auto process: processes){ hists.push_back(new TH1F("hist_"+histname+"_"+process, " ", nbins, min, max)); } return hists; } // ----------------------------------------------------------------------------- // Diese Funktion wird aufgerufen um Histogramme zu füllen --------------------- void FillHistogram(vector<TH1F*> hists, double value, double weight, TString process){ int index; if(process == "data") index = 0; else if (process == "higgs") index = 1; else if (process == "ZZ") index = 2; else if (process == "DY") index = 3; else cout << "[ERROR] the process name '" << process << "' does not exist!" << endl; hists[index]->Fill(value, weight); return; }
d4c3f03f3c2eaea865a200211e8a5d71717127e6
b2092d2a4a65cf82cab916c416114f2d9c1e928e
/Engine/include/Engine/Gui/Widget.h
d764684c60f5d64b8e9ec6b2f0a4ca3f3cc9cba3
[]
no_license
von6yka/Arcanoid-3D
6664a4df6375b71a36a8254cc3382fc26cea400a
591ed9320573848c38e3257dad9c300bbe926fcb
refs/heads/master
2016-09-06T18:58:58.493016
2015-04-11T06:02:38
2015-04-11T06:02:38
33,681,011
0
0
null
null
null
null
UTF-8
C++
false
false
1,463
h
Widget.h
#pragma once #include <string> #include "Engine/Forwards.h" #include "Engine/Object.h" #include "Engine/Math/Size.h" #include "Engine/Math/Vec2i.h" #include "Engine/Gui/GuiRenderable.h" namespace engine { class Widget : public Object { public: enum Anchor { ANCHOR_UNDEFINED, ANCHOR_BOTTOM_LEFT, ANCHOR_BOTTOM_RIGHT, ANCHOR_TOP_LEFT, ANCHOR_TOP_RIGHT, ANCHOR_CENTER }; Widget(Widget* parent, const std::wstring& name); ~Widget(); public: virtual void render(GuiRenderable& guiRenderable) = 0; virtual void update(Window& window, InputSystem& inputSystem, AudioSystem& audioSystem); virtual Size size() const; virtual void setSize(const Size& size); public: bool isVisible() const { return _isVisible; } void setVisible(bool isVisible) { _isVisible = isVisible; } Vec2i position() const { return _position; } void setPosition(const Vec2i& position) { _position = position; } Anchor anchor() const { return _anchor; } void setAnchor(Anchor anchor) { _anchor = anchor; } WidgetLayer* widgetLayer() const { return _widgetLayer; } void setWidgetLayer(WidgetLayer* widgetLayer); private: WidgetLayer* _widgetLayer; bool _isVisible; Size _size; Vec2i _position; Anchor _anchor; }; }//namespace engine
9eff6fd83e0c40c3dc78681efb184a6eb1b6b13f
942f6adbadf324458cf17059c70b3cc55a26c7ad
/1.select/tcp_server.cpp
70ba49c2f9335b70ca54141b4843ac4f95eebb7a
[]
no_license
fwjieok/ipr
2b501798cdaa047533f7e47cb78ecd1feb1a19f0
23e5dfe4f3404b8fba38a713b876da9be9c7be26
refs/heads/master
2021-01-01T20:14:29.747733
2017-09-17T08:58:57
2017-09-17T08:58:57
98,797,529
0
0
null
null
null
null
UTF-8
C++
false
false
2,603
cpp
tcp_server.cpp
#include "tcp_server.h" TCP_Server::TCP_Server() { } TCP_Server::~TCP_Server() { shutdown(server_sockfd, SHUT_RDWR); close(server_sockfd); server_sockfd = -1; } int TCP_Server::begin(char *ip, int port) { if (port <= 0) { printf("listen error, the parameter port is not equals 0\n"); return -1; } server_sockfd = -1; listen_port = port; bzero(&server_addr, sizeof(server_addr)); server_addr.sin_family = PF_INET; server_addr.sin_port = htons(listen_port); if (ip) { if (INADDR_NONE == inet_addr(ip)) { printf("the parameter ip %s is not legal\n", ip); return -1; } server_addr.sin_addr.s_addr = inet_addr(ip); } else { server_addr.sin_addr.s_addr = INADDR_ANY; } timeout_val.tv_sec = 0; timeout_val.tv_usec = 0; if ((server_sockfd = socket(PF_INET, SOCK_STREAM, 0)) == -1) { perror("socket"); fflush(stdout); return -1; } // 设置套接字选项避免地址使用错误 int opt = 1; if(setsockopt(server_sockfd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt)) < 0) { perror("setsockopt"); fflush(stdout); return -1; } if (bind(server_sockfd, (struct sockaddr *)&server_addr, sizeof(struct sockaddr)) == -1) { perror("bind"); fflush(stdout); exit(-1); } if (listen(server_sockfd, 65535) == -1) { perror("listen"); fflush(stdout); return -1; } printf("tcp listening on %s:%d, server_sockfd: %d\n", ip, port, server_sockfd); return 0; } void TCP_Server::on_accept_process() { int client_fd = -1; struct sockaddr_in client_addr; socklen_t len = sizeof(client_addr); bzero(&client_addr, sizeof(client_addr)); if ((client_fd = accept(server_sockfd, (struct sockaddr *)&client_addr, &len)) == -1) { perror("ERROR: accept"); fflush(stdout); exit(-1); } else { /* Socket_Helper *socket_helper = new Socket_Helper(); strcpy(socket_helper->remote_addr, inet_ntoa(client_addr.sin_addr)); socket_helper->remote_port = ntohs(client_addr.sin_port); socket_helper->socket_fd = client_fd; */ on_new_connection(client_fd); } } void TCP_Server::loop() { if (server_sockfd <= 0) { return; } FD_ZERO(&readfds); FD_SET(server_sockfd, &readfds); int max_fd = server_sockfd + 1; int ret = select(max_fd, &readfds, NULL, NULL, &timeout_val); if (ret < 0) { perror("TCP Server select"); } else if (ret == 0) { //select timeout } else { if (FD_ISSET(server_sockfd, &readfds)) { on_accept_process(); } } } void TCP_Server::tick_1s() { }
1476bb031a1583d81bd61921efec3638c1efd72e
4cc5643008bee761a29e8fd2c26bf7acf3cbb596
/Code/SingleFitting/C++/irsir.cpp
b25f441ab705ca6255f2d8a9a8627070ff5ea9ff
[]
no_license
jameshay218/epidemics
59c89f4d5fc9cdab859189ec00759fa2b5576e1a
485c40e712875b11db337ebf5fd643e032a066b9
refs/heads/master
2021-01-15T14:36:36.444672
2014-09-05T18:34:11
2014-09-05T18:34:11
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,056
cpp
irsir.cpp
using namespace std; #include "irsir.hpp" IRSIR::~IRSIR(){ } /* ============================== MODEL EQUATIONS ============================== */ void IRSIR::Diff(vector<double> Pop) { // The differential equations dPop[0] = - beta*Pop[0]*Pop[1]; // dS/dt dPop[1] = beta*Pop[0]*Pop[1] - gamma*Pop[1]*Pop[2]; // dI/dt dPop[2] = gamma*Pop[1]*Pop[2]; // dR/dt } /* ================================== SSE FITTING PROCEDURE ================================= */ vector<vector<double> > IRSIR::ode_solve(vector<double> parameters){ pars = parameters; reset_models((current_data.size()/step)); beta = exp(parameters[0]); gamma = exp(parameters[1]); populations[0] = exp(parameters[2]); if(optimT0 && parameters.size() > 2) if(optimI0) t0 = exp(parameters[4]); else t0 = exp(parameters[3]); else t0 = 0; if(optimI0 && parameters.size() > 2) populations[1] = exp(parameters[3]); else populations[1] = 1.0; populations[2] = 1.0; Solve_Eq_t0(temp_model, 1); return(temp_model); }
4b6e5524ecbd0ce92426fa7e09504a748a609e5c
d85978556a8e57fe33fedfc9b2c7ff38d0cb6e8b
/Twins/Twins.cpp
5f520c4742d9adf0672a44815c19423790eb42e9
[]
no_license
Lianghe-Chen/hackerrank-2
c9ee73df5b6f13e92f057281c12789a61bec8554
1d7aa60f9c02e2130da1ac7482bd3c9ae1de8a83
refs/heads/master
2022-03-27T03:10:02.998643
2019-12-12T01:00:29
2019-12-12T01:00:29
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,116
cpp
Twins.cpp
#include <vector> #include <iostream> using namespace std; long long isqrt(long long n) { auto begin = 1ll, end = n / 2 + 1; while(begin < end) { auto mid = (begin + end + 1) / 2; if(mid <= n / mid) { begin = mid; } else { end = mid - 1; } } return begin; } int main() { int n, m, result = 0; cin >> n >> m; vector<bool> front(isqrt(m) + 1, 1), back(m - n + 1, 1); if(n == 1) { back[0] = 0; } for(auto i = 2; i * i < front.size(); i++) { if(front[i]) { for(auto j = i + i; j < front.size(); j += i) { front[j] = 0; } } } for(auto i = 2; i < front.size(); i++) { if(front[i]) { auto j = ((n - 1) / i + 1) * i; if(j == i) { j += i; } for(; j <= m; j += i) { back[j - n] = 0; } } } for(auto i = 2; i < back.size(); i++) { if(back[i] && back[i - 2]) { result++; } } cout << result; return 0; }
b9d74df62e7c11de0a9f4c5a9ecdf3433f1ae1b8
1170d3e8fad1122c7a6889eb33aafa1d12ebeced
/week1/string/01_reverse-string.cpp
c9984ca00a75eab390919a354159d271240bb173
[]
no_license
muhammedyusuf-sermet/wallbreakers
433394ecf6bd84e4adcb19f989a9209241226872
62c4b1f4a82bc6c5124a7675ea79fe5737565730
refs/heads/master
2020-06-09T11:13:07.895446
2019-08-01T19:42:48
2019-08-01T19:42:48
193,428,235
0
0
null
null
null
null
UTF-8
C++
false
false
274
cpp
01_reverse-string.cpp
class Solution { public: void reverseString(vector<char>& s) { int length = s.size(); char swap; for(int i=0; i<floor(length/2); i++){ swap = s[i]; s[i] = s[length-1-i]; s[length-1-i] = swap; } } };
0990ec293b249e9ccc0ae40ed5abbd483a405ddb
8ec160f284390ff416f162eb4dda093218e005aa
/Encoder/helper.cpp
0cd7089339c772e995e83ef4669d966f748a39b9
[]
no_license
demidov91/AK_curs_3.2_encoder
3657dea4c2a229c2f1d16ed81342af420f9027d4
af64e25c5000612e644b2587cc0bb847e6b117bb
refs/heads/master
2016-09-06T11:19:21.820927
2012-06-06T09:33:22
2012-06-06T09:33:22
null
0
0
null
null
null
null
UTF-8
C++
false
false
283
cpp
helper.cpp
#include "helper.h" #include <string> using namespace std; bool vector_contains_string(vector<const string> *v, const string* s) { for(vector<const string> ::iterator it = v ->begin(); it < v ->end(); it++) { if (!s ->compare(*it)) { return true; } } return false; };
b36d938500f9385ba3839c3100b1b1e2b0c427f2
ceb020fee45a01645f0b2adc118483c6cf296226
/RectangleOverlap.cpp
0b18dc064b47566d607fbb816aa04b87d496590d
[]
no_license
anaypaul/LeetCode
6423c4ca1b0d147206c06ebb86c9e558a85077f2
667825d32df2499301184d486e3a674291c0ca0b
refs/heads/master
2021-09-28T06:05:21.256702
2020-10-12T04:01:46
2020-10-12T04:01:46
153,226,092
0
0
null
null
null
null
UTF-8
C++
false
false
1,904
cpp
RectangleOverlap.cpp
class Solution { public: bool isRectangleOverlap(vector<int>& rec1, vector<int>& rec2) { int ax0 = rec1[0]; int ay0 = rec1[1]; int ax2 = rec1[2]; int ay2 = rec1[3]; int bx0 = rec2[0]; int by0 = rec2[1]; int bx2 = rec2[2]; int by2 = rec2[3]; return !( ay2 <= by0 || ay0 >= by2 || bx2 <= ax0 || ax2 <= bx0); } }; //Implementation 2 class Solution { public: bool isRectangleOverlap(vector<int>& rec1, vector<int>& rec2) { //check vertically int x1_1 = rec1[0]; int y1_1 = rec1[1]; int x2_1 = rec1[2]; int y2_1 = rec1[3]; int x1_2 = rec2[0]; int y1_2 = rec2[1]; int x2_2 = rec2[2]; int y2_2 = rec2[3]; bool check1 = false; cout<<min(y1_2, y2_2)<<" "<<max(y1_2, y2_2)<<endl; if((min(y1_2, y2_2)< min(y1_1, y2_1) && min(y1_1, y2_1) < max(y1_2, y2_2)) || (min(y1_2, y2_2)< max(y1_1, y2_1) && max(y1_1, y2_1) < max(y1_2, y2_2)) || (min(y1_1, y2_1)< min(y1_2, y2_2) && min(y1_2, y2_2) < max(y1_1, y2_1)) || (min(y1_1, y2_1)< max(y1_2, y2_2) && max(y1_2, y2_2) < max(y1_1, y2_1)) ){ cout<<"overlapps vertically"<<endl; check1 = true; } bool check2 = false; if((min(x1_2, x2_2) < max(x1_1, x2_1) && max(x1_1, x2_1) < max(x1_2, x2_2)) || (min(x1_2, x2_2) < min(x1_1, x2_1) && min(x1_1, x2_1) < max(x1_2, x2_2)) || (min(x1_1, x2_1) < max(x1_2, x2_2) && max(x1_2, x2_2) < max(x1_1, x2_1)) || (min(x1_1, x2_1) < min(x1_2, x2_2) && min(x1_2, x2_2) < max(x1_1, x2_1)) ){ cout<<"overlaps horizontally"<<endl; check2 = true; } if(check1 && check2){ return true; } return false; } };
df1cf5821b67d3cdca9bf0b8c885339ecdec5b24
3696156349f138b4ae6e7122977aee605082e766
/atcoder.jp/abc163/abc163_c/Main.cpp
b00673d113c667ad23ae4546d0ef3e42cf0763c4
[]
no_license
ryu-dev/Atcoder_archive
a69fd6ebb7de3f66db2661c38de39cd9a28f01a5
85a8712c884287c66633c13bd3d98df88d7999da
refs/heads/main
2023-07-22T11:50:51.261534
2021-08-29T12:43:46
2021-08-29T12:43:46
306,061,429
0
0
null
null
null
null
UTF-8
C++
false
false
200
cpp
Main.cpp
#include<bits/stdc++.h> using namespace std; int main(){ int n,a;cin>>n; map<int, int>mp; for(int i=1;i<n;++i){ cin>>a; ++mp[a]; } for(int i=1;i<=n;++i){ cout<<mp[i]<<endl; } }
9648c7acfbb3ea8908cc5bf41def49e1a0d0c668
9fca8099b867a4f15f2696a108b6e58a4f3238e3
/src/world.hpp
d7c4743ef9c71da9380de1a26ccaac64225f17a0
[]
no_license
iskinmike/wolf
89dd8aa34b523a59ee5768e3c27bd852e29e6af3
b5fe1641c175edf51d8e6548d9b805a1177b3639
refs/heads/master
2020-04-25T23:12:34.797061
2019-02-28T15:29:14
2019-02-28T15:29:14
173,137,269
0
0
null
null
null
null
UTF-8
C++
false
false
1,590
hpp
world.hpp
#ifndef WORLD_HPP #define WORLD_HPP #include <iostream> #include <SDL2/SDL.h> #include <thread> #include <atomic> #include <map> #include "stb/stb.h" #include "stb/stb_image.h" #include "preconstruction_class.hpp" #include "color.hpp" #include "game_field.hpp" #include "player.hpp" #include "view_screen.hpp" struct window_settings{ std::string title; int screen_pos_x; int screen_pos_y; int width; int height; }; struct world_construction_token{ window_settings win_set; SDL_Renderer* renderer; SDL_Window* screen; SDL_Texture* texture; std::string error; std::atomic_bool loop_stop_flag; world_construction_token& operator=(world_construction_token&& token); world_construction_token(const world_construction_token& token); world_construction_token(); }; class world : public preconstruction_class<world_construction_token> { std::thread loop_thread; world(); std::map<std::string, sdl_image> textures; game_field field; view_screen view; player player_1; public: static world_construction_token construct_token(const std::string& title, int screen_pos_x, int screen_pos_y, int width, int height); world(world_construction_token&& inpt_token); ~world(); void run_loop(); void start_loop(); void load_game_field(); void load_texture(const std::string& texture_path, int width, int height); void update_player(); void update_texture(sdl_image& texture); void draw_sigh_angle(); pixel_info draw_line_of_sight(double angle); }; #endif /* WORLD_HPP */
adea6d37f5b800cd868f42bbcac6f0535804484b
354a2bcf2d5e5d4e4052ca1b199bfb44fd2bc462
/vtkm/filter/flow/internal/Messenger.cxx
52c582f2017a458b881e2a376a51e3f6b4acb364
[ "BSD-3-Clause", "LicenseRef-scancode-unknown-license-reference" ]
permissive
Kitware/VTK-m
108f96185fc3c3914498873c58a94ca75f2f2219
0c86e3277b6f19c91e5db240da00ff33028b9a2e
refs/heads/master
2023-08-30T13:05:05.132168
2023-08-29T20:36:57
2023-08-29T20:37:14
190,059,477
22
7
null
null
null
null
UTF-8
C++
false
false
13,495
cxx
Messenger.cxx
//============================================================================ // Copyright (c) Kitware, Inc. // All rights reserved. // See LICENSE.txt for details. // // This software is distributed WITHOUT ANY WARRANTY; without even // the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR // PURPOSE. See the above copyright notice for more information. //============================================================================ int R = 1; #include <vtkm/Math.h> #include <vtkm/cont/ErrorFilterExecution.h> #include <vtkm/filter/flow/internal/Messenger.h> #include <iostream> #include <sstream> #include <string.h> #ifdef VTKM_ENABLE_MPI #include <vtkm/thirdparty/diy/mpi-cast.h> #endif namespace vtkm { namespace filter { namespace flow { namespace internal { VTKM_CONT #ifdef VTKM_ENABLE_MPI Messenger::Messenger(vtkmdiy::mpi::communicator& comm, bool useAsyncComm) : MPIComm(vtkmdiy::mpi::mpi_cast(comm.handle())) , MsgID(0) , NumRanks(comm.size()) , Rank(comm.rank()) , UseAsynchronousCommunication(useAsyncComm) #else Messenger::Messenger(vtkmdiy::mpi::communicator& vtkmNotUsed(comm), bool vtkmNotUsed(useAsyncComm)) #endif { } #ifdef VTKM_ENABLE_MPI VTKM_CONT void Messenger::RegisterTag(int tag, std::size_t num_recvs, std::size_t size) { if (this->MessageTagInfo.find(tag) != this->MessageTagInfo.end() || tag == TAG_ANY) { std::stringstream msg; msg << "Invalid message tag: " << tag << std::endl; throw vtkm::cont::ErrorFilterExecution(msg.str()); } this->MessageTagInfo[tag] = std::pair<std::size_t, std::size_t>(num_recvs, size); } std::size_t Messenger::CalcMessageBufferSize(std::size_t msgSz) { return sizeof(int) // rank // std::vector<int> msg; // msg.size() + sizeof(std::size_t) // msgSz ints. + msgSz * sizeof(int); } void Messenger::InitializeBuffers() { //Setup receive buffers. for (const auto& it : this->MessageTagInfo) { int tag = it.first; std::size_t num = it.second.first; std::size_t sz = it.second.second; for (std::size_t i = 0; i < num; i++) this->PostRecv(tag, sz); } } void Messenger::CleanupRequests(int tag) { std::vector<RequestTagPair> delKeys; for (const auto& i : this->RecvBuffers) { if (tag == TAG_ANY || tag == i.first.second) delKeys.emplace_back(i.first); } if (!delKeys.empty()) { for (auto& v : delKeys) { char* buff = this->RecvBuffers[v]; MPI_Cancel(&(v.first)); delete[] buff; this->RecvBuffers.erase(v); } } } void Messenger::PostRecv(int tag) { auto it = this->MessageTagInfo.find(tag); if (it != this->MessageTagInfo.end()) this->PostRecv(tag, it->second.second); } void Messenger::PostRecv(int tag, std::size_t sz, int src) { sz += sizeof(Messenger::Header); char* buff = new char[sz]; memset(buff, 0, sz); MPI_Request req; if (src == -1) MPI_Irecv(buff, sz, MPI_BYTE, MPI_ANY_SOURCE, tag, this->MPIComm, &req); else MPI_Irecv(buff, sz, MPI_BYTE, src, tag, this->MPIComm, &req); RequestTagPair entry(req, tag); this->RecvBuffers[entry] = buff; } void Messenger::CheckPendingSendRequests() { std::vector<RequestTagPair> reqTags; this->CheckRequests(this->SendBuffers, {}, false, reqTags); //Cleanup any send buffers that have completed. for (const auto& rt : reqTags) { auto entry = this->SendBuffers.find(rt); if (entry != this->SendBuffers.end()) { delete[] entry->second; this->SendBuffers.erase(entry); } } } void Messenger::CheckRequests(const std::map<RequestTagPair, char*>& buffers, const std::set<int>& tagsToCheck, bool BlockAndWait, std::vector<RequestTagPair>& reqTags) { std::vector<MPI_Request> req, copy; std::vector<int> tags; reqTags.resize(0); //Check the buffers for the specified tags. for (const auto& it : buffers) { if (tagsToCheck.empty() || tagsToCheck.find(it.first.second) != tagsToCheck.end()) { req.emplace_back(it.first.first); copy.emplace_back(it.first.first); tags.emplace_back(it.first.second); } } //Nothing.. if (req.empty()) return; //Check the outstanding requests. std::vector<MPI_Status> status(req.size()); std::vector<int> indices(req.size()); int num = 0; int err; if (BlockAndWait) err = MPI_Waitsome(req.size(), req.data(), &num, indices.data(), status.data()); else err = MPI_Testsome(req.size(), req.data(), &num, indices.data(), status.data()); if (err != MPI_SUCCESS) throw vtkm::cont::ErrorFilterExecution("Error with MPI_Testsome in Messenger::RecvData"); //Add the req/tag to the return vector. reqTags.reserve(static_cast<std::size_t>(num)); for (int i = 0; i < num; i++) reqTags.emplace_back(RequestTagPair(copy[indices[i]], tags[indices[i]])); } bool Messenger::PacketCompare(const char* a, const char* b) { Messenger::Header ha, hb; memcpy(&ha, a, sizeof(ha)); memcpy(&hb, b, sizeof(hb)); return ha.packet < hb.packet; } void Messenger::PrepareForSend(int tag, const vtkmdiy::MemoryBuffer& buff, std::vector<char*>& buffList) { auto it = this->MessageTagInfo.find(tag); if (it == this->MessageTagInfo.end()) { std::stringstream msg; msg << "Message tag not found: " << tag << std::endl; throw vtkm::cont::ErrorFilterExecution(msg.str()); } std::size_t bytesLeft = buff.size(); std::size_t maxDataLen = it->second.second; Messenger::Header header; header.tag = tag; header.rank = this->Rank; header.id = this->GetMsgID(); header.numPackets = 1; if (buff.size() > maxDataLen) header.numPackets += buff.size() / maxDataLen; header.packet = 0; header.packetSz = 0; header.dataSz = 0; buffList.resize(header.numPackets); std::size_t pos = 0; for (std::size_t i = 0; i < header.numPackets; i++) { header.packet = i; if (i == (header.numPackets - 1)) header.dataSz = bytesLeft; else header.dataSz = maxDataLen; header.packetSz = header.dataSz + sizeof(header); char* b = new char[header.packetSz]; //Write the header. char* bPtr = b; memcpy(bPtr, &header, sizeof(header)); bPtr += sizeof(header); //Write the data. memcpy(bPtr, &buff.buffer[pos], header.dataSz); pos += header.dataSz; buffList[i] = b; bytesLeft -= maxDataLen; } } void Messenger::SendDataAsync(int dst, int tag, const vtkmdiy::MemoryBuffer& buff) { std::vector<char*> bufferList; //Add headers, break into multiple buffers if needed. this->PrepareForSend(tag, buff, bufferList); Messenger::Header header; for (const auto& b : bufferList) { memcpy(&header, b, sizeof(header)); MPI_Request req; int err = MPI_Isend(b, header.packetSz, MPI_BYTE, dst, tag, this->MPIComm, &req); if (err != MPI_SUCCESS) throw vtkm::cont::ErrorFilterExecution("Error in MPI_Isend inside Messenger::SendData"); //Add it to sendBuffers RequestTagPair entry(req, tag); this->SendBuffers[entry] = b; } } void Messenger::SendDataSync(int dst, int tag, vtkmdiy::MemoryBuffer& buff) { auto entry = std::make_pair(dst, std::move(buff)); auto it = this->SyncSendBuffers.find(tag); if (it == this->SyncSendBuffers.end()) { std::vector<std::pair<int, vtkmdiy::MemoryBuffer>> vec; vec.push_back(std::move(entry)); this->SyncSendBuffers.insert(std::make_pair(tag, std::move(vec))); } else it->second.emplace_back(std::move(entry)); it = this->SyncSendBuffers.find(tag); } bool Messenger::RecvDataAsync(const std::set<int>& tags, std::vector<std::pair<int, vtkmdiy::MemoryBuffer>>& buffers, bool blockAndWait) { buffers.resize(0); std::vector<RequestTagPair> reqTags; this->CheckRequests(this->RecvBuffers, tags, blockAndWait, reqTags); //Nothing came in. if (reqTags.empty()) return false; std::vector<char*> incomingBuffers; incomingBuffers.reserve(reqTags.size()); for (const auto& rt : reqTags) { auto it = this->RecvBuffers.find(rt); if (it == this->RecvBuffers.end()) throw vtkm::cont::ErrorFilterExecution("receive buffer not found"); incomingBuffers.emplace_back(it->second); this->RecvBuffers.erase(it); } this->ProcessReceivedBuffers(incomingBuffers, buffers); //Re-post receives for (const auto& rt : reqTags) this->PostRecv(rt.second); return !buffers.empty(); } bool Messenger::RecvDataSync(const std::set<int>& tags, std::vector<std::pair<int, vtkmdiy::MemoryBuffer>>& buffers, bool blockAndWait) { buffers.resize(0); if (!blockAndWait) return false; //Exchange data for (auto tag : tags) { //Determine the number of messages being sent to each rank and the maximum size. std::vector<int> maxBuffSize(this->NumRanks, 0), numMessages(this->NumRanks, 0); const auto& it = this->SyncSendBuffers.find(tag); if (it != this->SyncSendBuffers.end()) { for (const auto& i : it->second) { int buffSz = i.second.size(); maxBuffSize[i.first] = vtkm::Max(maxBuffSize[i.first], buffSz); //static_cast<int>(i.second.size())); numMessages[i.first]++; } } int err = MPI_Allreduce( MPI_IN_PLACE, maxBuffSize.data(), this->NumRanks, MPI_INT, MPI_MAX, this->MPIComm); if (err != MPI_SUCCESS) throw vtkm::cont::ErrorFilterExecution("Error in MPI_Isend inside Messenger::RecvDataSync"); err = MPI_Allreduce( MPI_IN_PLACE, numMessages.data(), this->NumRanks, MPI_INT, MPI_SUM, this->MPIComm); if (err != MPI_SUCCESS) throw vtkm::cont::ErrorFilterExecution("Error in MPI_Isend inside Messenger::RecvDataSync"); MPI_Status status; std::vector<char> recvBuff; for (int r = 0; r < this->NumRanks; r++) { int numMsgs = numMessages[r]; if (numMsgs == 0) continue; //Rank r needs some stuff.. if (this->Rank == r) { int maxSz = maxBuffSize[r]; recvBuff.resize(maxSz); for (int n = 0; n < numMsgs; n++) { err = MPI_Recv(recvBuff.data(), maxSz, MPI_BYTE, MPI_ANY_SOURCE, 0, this->MPIComm, &status); if (err != MPI_SUCCESS) throw vtkm::cont::ErrorFilterExecution( "Error in MPI_Recv inside Messenger::RecvDataSync"); std::pair<int, vtkmdiy::MemoryBuffer> entry; entry.first = tag; entry.second.buffer = recvBuff; buffers.emplace_back(std::move(entry)); } } else { if (it != this->SyncSendBuffers.end()) { //it = <tag, <dst,buffer>> for (const auto& dst_buff : it->second) { if (dst_buff.first == r) { err = MPI_Send(dst_buff.second.buffer.data(), dst_buff.second.size(), MPI_BYTE, r, 0, this->MPIComm); if (err != MPI_SUCCESS) throw vtkm::cont::ErrorFilterExecution( "Error in MPI_Send inside Messenger::RecvDataSync"); } } } } } //Clean up the send buffers. if (it != this->SyncSendBuffers.end()) this->SyncSendBuffers.erase(it); } MPI_Barrier(this->MPIComm); return !buffers.empty(); } void Messenger::ProcessReceivedBuffers(std::vector<char*>& incomingBuffers, std::vector<std::pair<int, vtkmdiy::MemoryBuffer>>& buffers) { for (auto& buff : incomingBuffers) { //Grab the header. Messenger::Header header; memcpy(&header, buff, sizeof(header)); //Only 1 packet, strip off header and add to list. if (header.numPackets == 1) { std::pair<int, vtkmdiy::MemoryBuffer> entry; entry.first = header.tag; entry.second.save_binary((char*)(buff + sizeof(header)), header.dataSz); entry.second.reset(); buffers.emplace_back(std::move(entry)); delete[] buff; } //Multi packet.... else { RankIdPair k(header.rank, header.id); auto i2 = this->RecvPackets.find(k); //First packet. Create a new list and add it. if (i2 == this->RecvPackets.end()) { std::list<char*> l; l.emplace_back(buff); this->RecvPackets[k] = l; } else { i2->second.emplace_back(buff); // The last packet came in, merge into one MemStream. if (i2->second.size() == header.numPackets) { //Sort the packets into proper order. i2->second.sort(Messenger::PacketCompare); std::pair<int, vtkmdiy::MemoryBuffer> entry; entry.first = header.tag; for (const auto& listIt : i2->second) { char* bi = listIt; Messenger::Header header2; memcpy(&header2, bi, sizeof(header2)); entry.second.save_binary((char*)(bi + sizeof(header2)), header2.dataSz); delete[] bi; } entry.second.reset(); buffers.emplace_back(std::move(entry)); this->RecvPackets.erase(i2); } } } } } #endif } } } } // vtkm::filter::flow::internal
4c34a1d53bcb308a2ac7a84312b24e11edae7616
c24829931dfb7bd8afa48ba08598e5c542310e6b
/Dijkstra/Dijkstra.cpp
ecacad9dd7cf5c34d5069f845f5a929de6c7ff3d
[]
no_license
IsabellaGarcia/HK-Eco-Path-Calculation
4a5d7fae22ef4fb71c17ff198de667b71c632aa7
9884d53ba3b68dd28adda129c70340d45fda3288
refs/heads/master
2020-05-16T21:12:23.291293
2014-12-05T07:32:57
2014-12-05T07:32:57
null
0
0
null
null
null
null
GB18030
C++
false
false
4,055
cpp
Dijkstra.cpp
#include"Dijkstra.h" #include <tuple> #include<vector> //Initialize adjacency list structure vexNode adjlist[POINTS_NUM]; void Dijkstra::createGraph(const int n,const int e) { ifstream infile; //string line; infile.open("current_weight.txt"); //getline(infile, line); database db; int i; for(i=1;i<=n;i++) { //cout <<db.search_index_name(i) << endl; adjlist[i].info = db.search_index_name(i); adjlist[i].link = NULL; lowcost[i] = Infinity; parent[i] = i; } //while(1); edgeNode *p1; int v1,v2; //cout << e << endl; for(i=1;i<=e+1;i++) { if(i<=e){ string line; getline(infile, line); istringstream iss; iss.str(line); iss>> v1 >> v2; //cout << v1 << " " << v2 << endl; int v1_r = db.search_name_index(v1); int v2_r = db.search_name_index(v2); p1 = (edgeNode*)malloc(sizeof(edgeNode)); p1->no = v2_r; //weight iss >> p1->cost; //insert near the edge node p1->next = adjlist[v1_r].link; adjlist[v1_r].link = p1; } if(i==e+1){ getline(infile,capture_time); } } } //当插入节点到优先队列时,保持队列优先性 void Dijkstra::keep_min_heap(Queue *priQue,int &num,const int k) { int l = 2*k; int r = 2*k + 1; int smallest = k; if(l<=num&&priQue[l].cost<priQue[k].cost) smallest = l; if(r<=num&&priQue[r].cost<priQue[smallest].cost) smallest = r; if(smallest != k) { Queue temp = priQue[smallest]; priQue[smallest] = priQue[k]; priQue[k] = temp; keep_min_heap(priQue,num,smallest); } } //插入节点到优先队列时并且保持队列优先性 void Dijkstra::heap_insert(Queue *priQue,int &num,int no,int cost) { //members in the Queue num +=1; priQue[num].no = no; priQue[num].cost = cost; int i = num; while(i>1&&priQue[i/2].cost>priQue[i].cost) { Queue temp = priQue[i]; priQue[i] = priQue[i/2]; priQue[i/2] = temp; i = i/2; } } //取出优先队列的队头元素 Queue Dijkstra::heap_extract_min(Queue *priQue,int &num) { if(num<1) return priQue[0]; Queue min = priQue[1]; priQue[1] = priQue[num]; num -=1; keep_min_heap(priQue,num,1); return min; } //打印指定源点带序号为i的点的最短路径 void Dijkstra::print_it(int *parent,vexNode *adjlist,int v) { if(parent[v] == v){ //cout<<"("<<v<<":"<<adjlist[v].info<<") "; database db; tuple<double, double> temp = make_tuple(db.search_north_index(v), db.search_east_index(v)); route.push_back(temp); } else { print_it(parent,adjlist,parent[v]); //cout<<"("<<v<<":"<<adjlist[v].info<<") "; database db; tuple<double, double> temp = make_tuple(db.search_north_index(v), db.search_east_index(v)); route.push_back(temp); } } int Dijkstra::dijkstra(int start_index, int end_index) { for(int i = 0; i< MAX ;i++){ priQue[i].no = 0; priQue[i].cost = 0; lowcost[i] = 0; parent[i] = 0; } int n,e; // cout<<"请输入节点数:"; n = POINTS_NUM; // cout<<"请输入边数:"; e = EDGE_NUM; //队列中的元素,初始为0 int num = 0; int i; //创建邻接表 createGraph(n,e); //cout << "Begin index of point:"; int v0; v0 = start_index; int v = v0; //cout << "End index of point:"; int v_end; v_end = end_index; lowcost[v0] = 0; //cout << endl; Queue queue; for(i=1;i<n;i++) { //cout << "V0 = " << v0 << endl; edgeNode *p = adjlist[v0].link; //cout << p->no << endl; while(p != NULL) { if(lowcost[v0] + p->cost<lowcost[p->no]) { lowcost[p->no] = lowcost[v0] + p->cost; parent[p->no] = v0; heap_insert(priQue,num,p->no,lowcost[p->no]); } p = p->next; } //cout << endl; queue = heap_extract_min(priQue,num); v0 = queue.no; } //cout<<"From point "<<adjlist[v].info<<" to "<<adjlist[v_end].info<<", the shortest path is:"<<endl; print_it(parent,adjlist,v_end); // cout<<"The distance is :"<<lowcost[v_end]<<endl; //system("pause"); return 0; } vector<tuple<double, double>> Dijkstra::get_waypts(){ return route; } string Dijkstra::get_capturetime(){ return capture_time; }
944515ca1171213271cc2a490beb9c6833a3217a
f33886602458e5198df3084ec783d4ac2d01c923
/1085.cpp
97ed1f04b4ae18fc4025cf590ccf74bf840a2ff5
[]
no_license
andongjoo/algorithm
4effa845698060dc6079638cff4c73752f3fc792
22622d1fc5cef10beabbf0b1c5ac3f2136664cfa
refs/heads/master
2021-06-18T12:31:47.259169
2021-02-15T11:54:18
2021-02-15T11:54:18
176,703,891
0
0
null
null
null
null
UTF-8
C++
false
false
982
cpp
1085.cpp
#include <iostream> #include <algorithm> #include <queue> using namespace std; const int MAX=1001; int dy[]={1,-1,0,0}; int dx[]={0,0,1,-1}; int cnt[MAX][MAX]={0}; int visit[MAX][MAX]={0}; int map[MAX][MAX]={0}; int x,y,w,h; queue<int> q; int main(int argc, char** argv) { cin>>x>>y>>w>>h; q.push(x); q.push(y); while(!q.empty()) { visit[x][y]=1; int front_x=q.front(); q.pop(); int front_y=q.front(); q.pop(); for(int i=0;i<4;i++) { int nx=dx[i]+front_x; int ny=dy[i]+front_y; if(0<=nx && nx<=w && 0<=ny && ny<=h && !visit[nx][ny] ) { q.push(nx); q.push(ny); visit[nx][ny]=1; cnt[nx][ny]=cnt[front_x][front_y]+1; } } } int ans=999999999; for(int i=0;i<=w;i++) { for(int j=0;j<=h;j++) { if( i==0 || j==0 || i==w || j==h) { ans=min(ans,cnt[i][j]); } } } printf("%d\n",ans); return 0; }
976ec1b0864f5bb68790edb8d68c6f76b4426353
a8be210046488b8e8723475839c3975280dade3e
/Game/Game/ENTITY.h
71d32460e490e968538186b1a9921368361f0a29
[]
no_license
romashka99/game_mario
ecd96bd2e86ac0f9f95aa3792326738843983aab
6412e92f38fc048f4cf66ebb651a25c521446e6a
refs/heads/master
2023-03-08T11:49:54.637446
2021-02-12T11:24:22
2021-02-12T11:24:22
338,296,715
0
0
null
null
null
null
WINDOWS-1251
C++
false
false
9,012
h
ENTITY.h
#include <SFML/Graphics.hpp> #include "level.h" using namespace sf; using namespace std; class ENTITY { public: float dx, dy, speed; int health; bool life, onGround; vector<Object> obj;//вектор объектов карты FloatRect rect; Sprite sprite; Texture texture; String name; ENTITY(Texture &texture, String Name, float X, float Y, int W, int H) { this->texture = texture; rect = FloatRect(X, Y, W, H); name = Name; speed = 0; health = 100; dx = 0; dy = 0; life = true; onGround = false; sprite.setTexture(texture); } FloatRect getRect() { //ф-ция получения прямоугольника. его коорд,размеры (шир,высот). return rect; //эта ф-ция нужна для проверки столкновений } virtual void update(float time) = 0; virtual void Collision(float Dx, float Dy) = 0; }; class PLAYER : public ENTITY { private: enum statusPlayer { motion, jump, stay }; public: bool key; statusPlayer state; float currentFrame; int playerScore; PLAYER(Texture &texture, Level &lev, String Name, float X, float Y, int W, int H) : ENTITY(texture, Name, X, Y, W, H) { playerScore = 0; state = stay; obj = lev.GetAllObjects();//инициализируем.получаем все объекты для взаимодействия персонажа с картой currentFrame = 0; if (name == "Player1") { sprite.setTextureRect(IntRect(0, 0, rect.width, rect.height)); health = 210; speed = dx = 0; key = false; } } void update(float time) { control(); rect.left += speed * time; Collision(speed, 0); if (!onGround) dy = dy + 0.004*time; rect.top += dy * time; onGround = false; Collision(0, dy); currentFrame += time * 0.015;; sprite.setPosition(rect.left, rect.top); speed = 0; switch (state) { case stay: { if (dx > 0) { sprite.setTextureRect(IntRect(0, 0, rect.width, rect.height)); } if (dx < 0) { sprite.setTextureRect(IntRect(0 + rect.width, 0, -rect.width, rect.height)); } } break; case motion: { if (currentFrame > 3) currentFrame = 1; if (dx > 0) { sprite.setTextureRect(IntRect(rect.width * int(currentFrame), 0, rect.width, rect.height)); } if (dx < 0) { sprite.setTextureRect(IntRect(rect.width * int(currentFrame) + rect.width, 0, -rect.width, rect.height)); } } break; case jump: { if (dx > 0) { sprite.setTextureRect(IntRect(rect.width * 4, 0, rect.width, rect.height)); } if (dx < 0) { sprite.setTextureRect(IntRect(rect.width * 5, 0, -rect.width, rect.height)); } } break; default: break; } sprite.setPosition(rect.left, rect.top); if (health <= 0) { life = false; } } void control() { if (Keyboard::isKeyPressed(Keyboard::A) || Keyboard::isKeyPressed(Keyboard::Left)) { speed = dx = -0.9; if (state == stay) state = motion; } if (Keyboard::isKeyPressed(Keyboard::D) || Keyboard::isKeyPressed(Keyboard::Right)) { speed = dx = 0.9; if (state == stay) state = motion; } if ((Keyboard::isKeyPressed(Keyboard::Space)|| Keyboard::isKeyPressed(Keyboard::Up)) && onGround ) { dy = -1.9; state = jump; onGround = false; } } void Collision(float Dx, float Dy) { for (int i = 0; i < obj.size(); i++)//проходимся по объектам { if (getRect().intersects(obj[i].rect)) { if (obj[i].name == "Solid")//если встретили препятствие { if (Dy < 0) { rect.top = obj[i].rect.top + obj[i].rect.height; dy = 0; } if (Dy > 0) { rect.top = obj[i].rect.top - rect.height; dy = 0; onGround = true; state = stay;} if (Dx > 0) { rect.left = obj[i].rect.left - rect.width; } if (Dx < 0) { rect.left = obj[i].rect.left + obj[i].rect.width; } } if (obj[i].name == "End") { if (!key) { if (Dy < 0) { rect.top = obj[i].rect.top + obj[i].rect.height; dy = 0; } if (Dy > 0) { rect.top = obj[i].rect.top - rect.height; dy = 0; onGround = true; state = stay; } if (Dx > 0) { rect.left = obj[i].rect.left - rect.width; } if (Dx < 0) { rect.left = obj[i].rect.left + obj[i].rect.width; } } } if (FloatRect(rect.left, rect.top + rect.height, rect.width, 2).intersects(obj[i].rect) && obj[i].name == "SolidPlat") { if (dy > 0) { rect.top = obj[i].rect.top - rect.height; dy = 0; onGround = true; state = stay; } } } } } }; class ENEMY : public ENTITY { public: float currentFrame; float moveTimer; ENEMY(Texture &texture, Level &lvl, String Name, float X, float Y, int W, int H) : ENTITY(texture, Name, X, Y, W, H) { obj = lvl.GetAllObjects();//инициализируем.получаем объекты для взаимодействия врага с картой if (name == "easyEnemy1") { sprite.setTextureRect(IntRect(0, 0, rect.width, rect.height)); dx = 0.4; currentFrame = 0; } if (name == "easyEnemy2") { sprite.setTextureRect(IntRect(0, 0, rect.width, rect.height)); dy = 0.4; currentFrame = 0; moveTimer = 0; } } void update(float time) { if (name == "easyEnemy1") { rect.left += dx * time; Collision(dx, 0); currentFrame += time * 0.015; sprite.setPosition(rect.left, rect.top); if (currentFrame > 3) currentFrame -= 3; if (dx < 0) sprite.setTextureRect(IntRect(rect.width * int(currentFrame) + rect.width, 0, -rect.width, rect.height)); if (dx > 0) sprite.setTextureRect(IntRect(rect.width * int(currentFrame), 0, rect.width, rect.height)); if (health <= 0) { life = false; } } if (name == "easyEnemy2") { moveTimer += time;//наращиваем таймер if (moveTimer > 200) { dy *= -1; moveTimer = 0; } rect.top += dy * time; Collision(0, dy); currentFrame += time * 0.015; sprite.setPosition(rect.left, rect.top); if (currentFrame > 14) currentFrame -= 14; sprite.setTextureRect(IntRect(rect.width * int(currentFrame), 0, rect.width, rect.height)); if (health <= 0) { life = false; } } } void Collision(float Dx, float Dy) { for (int i = 0; i < obj.size(); i++)//проходимся по объектам if (getRect().intersects(obj[i].rect))//проверяем пересечение игрока с объектом { if (obj[i].name == "Solid" || obj[i].name == "Limit" || obj[i].name == "SolidPlat") { if (Dy > 0) { rect.top = obj[i].rect.top - rect.height; dy *= -1; moveTimer = 0; } if (Dy < 0) { rect.top = obj[i].rect.top + obj[i].rect.height; dy *= -1; moveTimer = 0; } if (Dx > 0) { rect.left = obj[i].rect.left - rect.width; dx *= -1; } if (Dx < 0) { rect.left = obj[i].rect.left + obj[i].rect.width; dx *= -1; } } } } }; class MOVINFPLATFORM : public ENTITY {//класс движущейся платформы private: float moveTimer; public: MOVINFPLATFORM(Texture &texture, Level &lvl, String Name, float X, float Y, int W, int H) :ENTITY(texture, Name, X, Y, W, H) { obj = lvl.GetAllObjects();//инициализируем.получаем объекты для взаимодействия врага с картой sprite.setColor(Color::Black); sprite.setTextureRect(IntRect(0, 0, W, H));//прямоугольник dx = 0.2;//изначальное ускорение по Х } void update(float time)//функция обновления платформы. { rect.left += dx * time;//реализация движения по горизонтали moveTimer += time;//наращиваем таймер Collision(dx, 0); if (moveTimer > 20000) { dx *= -1; moveTimer = 0; }//если прошло примерно 2 сек, то меняется направление движения платформы,а таймер обнуляется sprite.setPosition(rect.left, rect.top);//задаем позицию спрайту } void Collision(float Dx, float Dy) { for (int i = 0; i < obj.size(); i++)//проходимся по объектам if (getRect().intersects(obj[i].rect)) { if (obj[i].name == "Solid" || obj[i].name == "SolidPlat") { if (Dx > 0) { rect.left = obj[i].rect.left - rect.width; dx *= -1; moveTimer = 0; } if (Dx < 0) { rect.left = obj[i].rect.left + obj[i].rect.width; dx *= -1; moveTimer = 0; } } } } }; class ITEM : public ENTITY { public: ITEM(Texture &texture, Level &lvl, String Name, float X, float Y, int W, int H) : ENTITY(texture, Name, X, Y, W, H) { if (name == "Coin") { sprite.setTextureRect(IntRect(21, 472, rect.width, rect.height)); } if (name == "Kristall") { sprite.setTextureRect(IntRect(300, 381, rect.width, rect.height)); } if (name == "Key") { sprite.setTextureRect(IntRect(209, 373, rect.width, rect.height)); } dx = 0; } void update(float time) { sprite.setPosition(rect.left, rect.top); if (health <= 0) { life = false; } } void Collision(float Dx, float Dy) { } };
6d29b6f402acfae7eba4e7fef03585ffc8ae6703
8f50c262f89d3dc4f15f2f67eb76e686b8f808f5
/Event/xAOD/xAODMuonAthenaPool/src/xAODMuonAuxContainerCnv.cxx
36f9fd14f54c7ed6018165dd1d2b56a28db951d9
[ "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
169
cxx
xAODMuonAuxContainerCnv.cxx
/* Copyright (C) 2002-2019 CERN for the benefit of the ATLAS collaboration */ // Dummy source file so that the build system knows that this // is a custom converter.
95e0f9a3d8638dc00bd575075dd497eef563cf16
54fbab5a0ec14e4e634ef205b38787f8c4bf18e6
/nsl/rts/incl/nsl_dout_num_1.h
52b847ed7a0b4954e9f9d5773efc4b850490e856
[]
no_license
biorobaw/QTNSLSpring2018
dcc5b954e0560740657256ce953b595c828fcfad
4d8afa6314ac6f15f09ef989e991d39b6980d712
refs/heads/master
2021-07-20T15:29:42.724283
2020-05-14T21:46:46
2020-05-14T21:46:46
162,358,177
0
0
null
null
null
null
UTF-8
C++
false
false
7,325
h
nsl_dout_num_1.h
/* SCCS %W%---%E%--%U% */ // // nsl_dout_num_1.h // #ifndef _NSL_DOUT_NUM_1_H #define _NSL_DOUT_NUM_1_H #include "nsl_public.h" #include "nsl_num_1.h" class nsl_num_0; extern fstream* NSL_FILE; extern int TRACE_FG; template<class NslNumType, int NslTypeId> class nsl_dout_num_1 : public nsl_num_1 { public: nsl_dout_num_1(const int = 0,int = 0,int=0,int=1); nsl_dout_num_1(const char*,nsl_model* = 0,const int = 0, row_col_enum = NSL_ROW,int=0,int=1,int=1); nsl_dout_num_1(const nsl_dout_num_1<NslNumType,NslTypeId>&,int=0,int=0,int=1); ~nsl_dout_num_1(); void initialize(const char*,nsl_public* = 0,const int = 0, row_col_enum = NSL_ROW,int=0,int=1,int=1); // assignment is not inherited in C++ nsl_num_1& operator=(const NslFloat1&); // nsl_num_1& operator=(const nsl_din_num_1<NslNumType,NslTypeId>&); // nsl_num_1& operator=(const nsl_dout_num_1<NslNumType,NslTypeId>&); nsl_num_1& operator=(const nsl_num_0&); // nsl_num_1& operator=(const nsl_din_num_0<NslNumType,NslTypeId>&); // nsl_num_1& operator=(const nsl_dout_num_0<NslNumType,NslTypeId>&); nsl_num_1& operator=(const float); nsl_num_1& operator=(const double); nsl_num_1& operator=(const int); void send(); void receive(); void copy(nsl_layer*); }; template<class NslNumType, int NslTypeId> nsl_dout_num_1<NslNumType,NslTypeId>::nsl_dout_num_1(const int s,int sfg,int fg,int rfg) : nsl_num_1(s,sfg,fg,rfg) { // _port = new AslInOutPort<NslNumType>(str,m,this,ASL_DATA_OUTPUT); } template<class NslNumType, int NslTypeId> nsl_dout_num_1<NslNumType,NslTypeId>::nsl_dout_num_1(const char* str,nsl_model* m, const int s,row_col_enum vtype,int sfg,int fg,int rfg) : nsl_num_1(str,m,s,vtype,sfg,fg,rfg) { _port = new AslInOutPort<NslNumType>(str,m,this,ASL_DATA_OUTPUT); } template<class NslNumType, int NslTypeId> nsl_dout_num_1<NslNumType,NslTypeId>::nsl_dout_num_1(const nsl_dout_num_1<NslNumType,NslTypeId>& a, int sfg,int fg,int rfg) : nsl_num_1(a,sfg,fg,rfg) { // _port = new AslInOutPort<NslNumType>(str,m,this,ASL_DATA_OUTPUT); } template<class NslNumType, int NslTypeId> nsl_dout_num_1<NslNumType,NslTypeId>::~nsl_dout_num_1() { } // initialize template<class NslNumType, int NslTypeId> void nsl_dout_num_1<NslNumType,NslTypeId>::initialize(const char* str,nsl_public* m, const int s,row_col_enum vtype,int sfg,int fg,int rfg) { nsl_num_1::initialize(str,m,s,vtype,sfg,fg,rfg); _port = new AslInOutPort<NslNumType>(str,m,this,ASL_DATA_OUTPUT); } // vector assignment template<class NslNumType, int NslTypeId> nsl_num_1& nsl_dout_num_1<NslNumType,NslTypeId>::operator=(const NslFloat1& a) { if (a.get_imax() != imax) { cmd_error("ERROR: nsl_num_1<int>::operator="); a.print_status(cerr); this->print_status(cerr); cmd_error("Inconsistent vector sizes"); return *this; } for (int i = 0; i < imax; i++) v[i] = a[i]; if (TRACE_FG == 1 && NSL_FILE != NULL && m_parent != NULL && m_parent != (nsl_base*)SYSTEM) { m_parent->print(*NSL_FILE); nsl_base::print(*NSL_FILE); } // send(); // send out implicitely when modified return *this; } /* template<class NslNumType, int NslTypeId> nsl_num_1& nsl_dout_num_1<NslNumType,NslTypeId>::operator=(const nsl_din_num_1<NslNumType,NslTypeId>& a) { if (a.get_imax() != imax) { cmd_error("ERROR: nsl_num_1<int>::operator="); a.print_status(cerr); this->print_status(cerr); cmd_error("Inconsistent vector sizes"); return *this; } for (int i = 0; i < imax; i++) v[i] = a[i]; if (TRACE_FG == 1 && NSL_FILE != NULL && m_parent != NULL && m_parent != SYSTEM) { m_parent->print(*NSL_FILE); print(*NSL_FILE); } // send(); // send out implicitely when modified return *this; } template<class NslNumType, int NslTypeId> nsl_num_1& nsl_dout_num_1<NslNumType,NslTypeId>::operator=(const nsl_dout_num_1<NslNumType,NslTypeId>& a) { if (a.get_imax() != imax) { cmd_error("ERROR: nsl_num_1<int>::operator="); a.print_status(cerr); this->print_status(cerr); cmd_error("Inconsistent vector sizes"); return *this; } for (int i = 0; i < imax; i++) v[i] = a[i]; if (TRACE_FG == 1 && NSL_FILE != NULL && m_parent != NULL && m_parent != SYSTEM) { m_parent->print(*NSL_FILE); print(*NSL_FILE); } // send(); // send out implicitely when modified return *this; } */ template<class NslNumType, int NslTypeId> nsl_num_1& nsl_dout_num_1<NslNumType,NslTypeId>::operator=(const NslFloat0& a) { NslNumType val = a.get_value(); for (int i = 0; i < imax; i++) v[i] = (NslNumType) val; if (TRACE_FG == 1 && NSL_FILE != NULL && m_parent != NULL && m_parent != (nsl_base*)SYSTEM) { m_parent->print(*NSL_FILE); nsl_base::print(*NSL_FILE); } // send(); // send out implicitely when modified return *this; } /* template<class NslNumType, int NslTypeId> nsl_num_1& nsl_dout_num_1<NslNumType,NslTypeId>::operator=(const nsl_din_num_0<NslNumType,NslTypeId>& a) { NslNumType val = a.get_value(); for (int i = 0; i < imax; i++) v[i] = (NslNumType) val; if (TRACE_FG == 1 && NSL_FILE != NULL && m_parent != NULL && m_parent != SYSTEM) { m_parent->print(*NSL_FILE); print(*NSL_FILE); } // send(); // send out implicitely when modified return *this; } template<class NslNumType, int NslTypeId> nsl_num_1& nsl_dout_num_1<NslNumType,NslTypeId>::operator=(const nsl_dout_num_0<NslNumType,NslTypeId>& a) { NslNumType val = a.get_value(); for (int i = 0; i < imax; i++) v[i] = (NslNumType) val; if (TRACE_FG == 1 && NSL_FILE != NULL && m_parent != NULL && m_parent != SYSTEM) { m_parent->print(*NSL_FILE); print(*NSL_FILE); } // send(); // send out implicitely when modified return *this; } */ template<class NslNumType, int NslTypeId> nsl_num_1& nsl_dout_num_1<NslNumType,NslTypeId>::operator=(const float a) { for (int i = 0; i < imax; i++) v[i] = (NslNumType) a; if (TRACE_FG == 1 && NSL_FILE != NULL && m_parent != NULL && m_parent != (nsl_base*)SYSTEM) { m_parent->print(*NSL_FILE); nsl_base::print(*NSL_FILE); } // send(); // send out implicitely when modified return *this; } template<class NslNumType, int NslTypeId> nsl_num_1& nsl_dout_num_1<NslNumType,NslTypeId>::operator=(const double a) { for (int i = 0; i < imax; i++) v[i] = (NslNumType) a; if (TRACE_FG == 1 && NSL_FILE != NULL && m_parent != NULL && m_parent != (nsl_base*)SYSTEM) { m_parent->print(*NSL_FILE); nsl_base::print(*NSL_FILE); } // send(); // send out implicitely when modified return *this; } template<class NslNumType, int NslTypeId> nsl_num_1& nsl_dout_num_1<NslNumType,NslTypeId>::operator=(const int a) { for (int i = 0; i < imax; i++) v[i] = (NslNumType) a; if (TRACE_FG == 1 && NSL_FILE != NULL && m_parent != NULL && m_parent != (nsl_base*)SYSTEM) { m_parent->print(*NSL_FILE); nsl_base::print(*NSL_FILE); } // send(); // send out implicitely when modified return *this; } template<class NslNumType, int NslTypeId> void nsl_dout_num_1<NslNumType,NslTypeId>::send() { *((AslInOutPort<NslNumType>*) _port) << *this; } template<class NslNumType, int NslTypeId> void nsl_dout_num_1<NslNumType,NslTypeId>::receive() { *((AslInOutPort<NslNumType>*) _port) >> *this; } template<class NslNumType, int NslTypeId> void nsl_dout_num_1<NslNumType,NslTypeId>::copy(nsl_layer* var) { *this = *((nsl_num_1*) var); } #endif
dadf35f6a4b1ff1c291a97c13ec70203974be9ad
cd327aee5966e332c384b1a59eeab0e20c45c6bd
/Source/Sks/Src/Accelero/IntelliSS7/common/test/SampleApp/WorkerPool/src/App1Main.cpp
26fd0ca9441bcf52c4d88cb868ec5b91cce9c338
[]
no_license
komi-jangra/A_TEST
4ae3b7c31f0db75e210f0b7e514c14cee5b24443
117f4d702d241de6074903be0e5a579f450fff91
refs/heads/master
2021-01-22T23:48:28.202567
2017-03-21T07:15:15
2017-03-21T07:15:15
85,664,924
0
0
null
null
null
null
UTF-8
C++
false
false
2,521
cpp
App1Main.cpp
/*************************************************************************** * * * Copyright 1997 IntelliNet Technologies, Inc. All Rights Reserved. * * Manufactured in the United States of America. * * 1990 W. New Haven Ste. 312, Melbourne, Florida, 32904 U.S.A. * * * * This product and related documentation is protected by copyright and * * distributed under licenses restricting its use, copying, distribution * * and decompilation. No part of this product or related documentation * * may be reproduced in any form by any means without prior written * * authorization of IntelliNet Technologies and its licensors, if any. * * * * RESTRICTED RIGHTS LEGEND: Use, duplication, or disclosure by the * * government is subject to restrictions as set forth in subparagraph * * (c)(1)(ii) of the Rights in Technical Data and Computer Software * * clause at DFARS 252.227-7013 and FAR 52.227-19. * * * ***************************************************************************** * * ID: $Id: App1Main.cpp,v 1.1.1.1 2007-10-08 11:12:01 bsccs2 Exp $ * * LOG: $Log: not supported by cvs2svn $ * LOG: Revision 1.1.1.1 2007/10/04 13:24:34 bsccs2 * LOG: init tree * LOG: * LOG: Revision 1.1.1.1 2007/08/03 06:49:15 cvsadmin * LOG: BscCs2 * LOG: * LOG: Revision 1.1.1.1 2007/03/08 15:14:27 cvsadmin * LOG: BSC project * LOG: * LOG: Revision 9.1 2005/03/23 12:53:53 cvsadmin * LOG: Begin PR6.5 * LOG: * LOG: Revision 1.2 2005/03/23 07:26:10 cvsadmin * LOG: PR6.4.2 Source Propagated to Current * LOG: * LOG: Revision 1.1.2.1 2005/01/31 11:15:28 kannanp * LOG: Sample App - Initial. * LOG: ****************************************************************************/ #ident "$Id: App1Main.cpp,v 1.1.1.1 2007-10-08 11:12:01 bsccs2 Exp $" #include <engine.h> int main(int argc, const char **argv) { /* Set the application name */ APPL_SetName("App1"); /* Set the application extension */ APPL_SetConfigFileExtension("xml"); //DBC_SetDoCommand(ExecuteCommand); ENGINE_Initialize(argc, argv, NULL, 0); return(ENGINE_Run(argc, argv)); }
4c39be5d94f03939f1a62382264a1f82d0390476
576a2a4b2d576c9ef263a7d2858665bff4f19bfa
/src/bsdf/fresnelblend.cpp
89647d0c7dd83dd453a478fa86195b3696d11a3a
[]
no_license
brickray/pol
827799236d3058d11724bfd7789883cf5ca5da34
c2303bae0d35b86797a1f60c554ea3f55864afc2
refs/heads/master
2020-08-24T14:28:53.434452
2020-03-25T13:25:59
2020-03-25T13:25:59
216,844,737
0
0
null
null
null
null
UTF-8
C++
false
false
3,715
cpp
fresnelblend.cpp
#include "fresnelblend.h" #include "../core/scene.h" namespace pol { POL_REGISTER_CLASS(FresnelBlend, "fresnelblend"); FresnelBlend::FresnelBlend(const PropSets& props, Scene& scene) :Bsdf(props, scene) { string diffName = props.GetString("diffuse"); string specName = props.GetString("specular"); diffuse = scene.GetTexture(diffName); specular = scene.GetTexture(specName); bool isotropic = props.HasValue("alpha"); if (isotropic) { string alphaName = props.GetString("alpha"); alphaX = scene.GetTexture(alphaName); alphaY = alphaX; } else { string axName = props.GetString("alphaX"); string ayName = props.GetString("alphaY"); alphaX = scene.GetTexture(axName); alphaY = scene.GetTexture(ayName); } diffuseWeight = props.GetFloat("diffuseWeight", 0.5); } bool FresnelBlend::IsDelta() const { return false; } void FresnelBlend::SampleBsdf(const Intersection& isect, const Vector3f& in, const Vector2f& u, Vector3f& out, Vector3f& fr, Float& pdf) const { bool sameSide = Frame::CosTheta(in) > 0; Float ax = alphaX->Evaluate(isect).X(); Float ay = alphaY->Evaluate(isect).X(); if (u.x < diffuseWeight) { //diffuse part Float ux = u.x / diffuseWeight; out = Warp::CosineHemiSphere(Vector2f(ux, u.y)); if (!sameSide) out = -out; } else { //specular part Float ux = (u.x - diffuseWeight) / (1 - diffuseWeight); Vector3f wh = SampleWh(Vector2f(ux, u.y), ax, ay); out = Reflect(in, wh); if (Frame::CosTheta(in) * Frame::CosTheta(out) < 0) { //to prevent light leak //it may occur at grazing angle pdf = 0; return; } } Float c0 = Frame::AbsCosTheta(in); Float c1 = Frame::AbsCosTheta(out); Vector3f rd = diffuse->Evaluate(isect); Vector3f rs = specular->Evaluate(isect); Float cons0 = 1 - 0.5 * c0; Float cons1 = 1 - 0.5 * c1; Vector3f wh = Normalize(in + out); Vector3f diff = Float(28 / (23 * PI)) * rd * (Vector3f::One() - rs) * (1 - Pow5(cons0)) * (1 - Pow5(cons1)); Float D = GGXD(wh, ax, ay); Vector3f spec = D * SchlickFresnel(rs, fabs(Dot(out, wh))) / (4 * fabs(Dot(out, wh)) * Max(c0, c1)); fr = (diff + spec) * c1; Float diffPdf = c1 * INVPI; Float specPdf = D * Frame::AbsCosTheta(wh) / (4 * fabs(Dot(in, wh))); pdf = Lerp(diffPdf, specPdf, diffuseWeight); return; } void FresnelBlend::Fr(const Intersection& isect, const Vector3f& in, const Vector3f& out, Vector3f& fr, Float& pdf) const { if (Frame::CosTheta(in) * Frame::AbsCosTheta(out) < 0) { //to prevent light leak pdf = 0; return; } Float ax = alphaX->Evaluate(isect).X(); Float ay = alphaY->Evaluate(isect).X(); Float c0 = Frame::AbsCosTheta(in); Float c1 = Frame::AbsCosTheta(out); Vector3f rd = diffuse->Evaluate(isect); Vector3f rs = specular->Evaluate(isect); Float cons0 = 1 - 0.5 * c0; Float cons1 = 1 - 0.5 * c1; Vector3f wh = Normalize(in + out); Vector3f diff = Float(28 / (23 * PI)) * rd * (Vector3f::One() - rs) * (1 - Pow5(cons0)) * (1 - Pow5(cons1)); Float D = GGXD(wh, ax, ay); Vector3f spec = D * SchlickFresnel(rs, fabs(Dot(out, wh))) / (4 * fabs(Dot(out, wh)) * Max(c0, c1)); fr = (diff + spec) * c1; Float diffPdf = c1 * INVPI; Float specPdf = D * Frame::AbsCosTheta(wh) / (4 * fabs(Dot(in, wh))); pdf = Lerp(diffPdf, specPdf, diffuseWeight); return; } string FresnelBlend::ToString() const { string ret; ret += "FresnelBlend[\n diffuse = " + indent(diffuse->ToString()) + ",\n specular = " + indent(specular->ToString()) + ",\n alphaX = " + indent(alphaX->ToString()) + ",\n alphaY = " + indent(alphaY->ToString()) + ",\n diffuse weight = " + to_string(diffuseWeight) + "\n]"; return ret; } }
04d37180243614c6700263826ed9c72f258057b2
b778e917abddb88107d669d731cdbcf10baef0ee
/vision/CameraParameters.h
8a7397030c61e8cfad1fa72508b33c1d33541220
[]
no_license
PamirGhimire/cvPlay
2e22585186577763e127b925429676f50c3062a5
c80760356a445cdafb56a3992b0d41c1a4e6294b
refs/heads/master
2020-09-16T08:17:08.184440
2019-12-23T19:34:50
2019-12-23T19:34:50
223,709,470
0
0
null
2019-12-23T19:34:52
2019-11-24T07:43:25
C++
UTF-8
C++
false
false
300
h
CameraParameters.h
#pragma once namespace cvp { namespace vision { constexpr float kFocalLength = 1000; struct CameraIntrinsics { float focal_x_{kFocalLength}; float focal_y_{kFocalLength}; float skew_{0}; float optical_center_x_{0}; float optical_center_y_{0}; }; } // namespace vision } // namespace cvp
3bb54866ffbd2c0ae48bd3840d1f5cb69192827d
e81f4aaae967e99f060364990000701f3c383bb3
/labs/lab8/code/code/AvlTree.h
e097e119886360821c23877c2760abdc3a95c1cd
[ "Apache-2.0" ]
permissive
acarteas/Teaching-DataStructures
262c5a27bdef4c5c85674968fc6b248e3e9d1c6f
4b90ab02e8251315f6d455a95e35d7f032bee76f
refs/heads/master
2021-06-05T14:53:38.580314
2019-11-07T18:22:03
2019-11-07T18:22:03
115,886,774
12
20
Apache-2.0
2018-05-10T18:10:56
2017-12-31T21:45:15
null
UTF-8
C++
false
false
2,951
h
AvlTree.h
#pragma once #ifndef AVL_TREE_H #define AVL_TREE_H #include "BinarySearchTree.h" template <typename T> class AvlTree : public BinarySearchTree<T> { private: AvlNode<T>* rotateRight(AvlNode<T>* node) { //Let new_root = node's left child AvlNode<T>* new_root = node->getLeft(); //Set node's LC equal to new_root's RC node->setLeft(new_root->getRight()); node = setHeight(node); //set new_root's right to node new_root->setRight(node); return setHeight(new_root); } AvlNode<T>* rotateLeft(AvlNode<T>* node) { AvlNode<T>* new_root = node->getRight(); node->setRight(new_root->getLeft()); node = setHeight(node); new_root->setLeft(node); return setHeight(new_root); } //balances out a given node AvlNode<T>* balance(AvlNode<T>* node) { if (node == nullptr) { return node; } int balance_factor = node->getBalanceFactor(); if (balance_factor > 1) { //When the balance factor of the node is positive //and the balance factor of the node's right child is //negative: //rotate right at node's right child //rotate left at node if (node->getRight()->getBalanceFactor() < 0) { //TODO: rotate right child right node->setRight(rotateRight(node->getRight())); } //TODO: rotate left at node return rotateLeft(node); } else if (balance_factor < -1) { //When the balance factor of the node is negative //and the balance factor of the node's left child is //positive: //rotate left at node's left child //rotate right at node if (node->getLeft()->getBalanceFactor() > 0) { //TODO: rotate left child left node->setLeft(rotateLeft(node->getLeft())); } //TODO: rotate right at node return rotateRight(node); } return node; } //sets the height of the supplied node AvlNode<T>* setHeight(AvlNode<T>* node) { //ALWAYS check for nullness if (node == nullptr) { return node; } AvlNode<T>* left = node->getLeft(); AvlNode<T>* right = node->getRight(); int left_height = (left == nullptr) ? -1 : left->getHeight(); int right_height = (right == nullptr) ? -1 : right->getHeight(); int height = left_height; if (left_height < right_height) { height = right_height; } //add 1 to account for us height++; node->setHeight(height); //check for AVL compliance int balance_factor = node->getBalanceFactor(); if (balance_factor > 1 || balance_factor < -1) { //NOT AVL compliant return balance(node); } return node; } protected: //this will override default BST add behavior virtual BinaryNode<T>* bstAdd(BinaryNode<T>* node, int value) { //be sure to create AVL nodes, NOT BST nodes if (node == nullptr) { node = new AvlNode<T>{ value }; return node; } //reuse previous code AvlNode<T>* result = dynamic_cast<AvlNode<T>*>( BinarySearchTree<T>::bstAdd(node, value) ); //set node's height return setHeight(result); } }; #endif
95049f5eec31dffa9ee5f47b7a3664634bc033ba
6eab1018af8cf91c7cfb120631edd4c68b57d666
/applications/system-service/apibase.h
5ffdd356a9c1db3aad8ed7cf96e419002cbe8792
[ "MIT", "Apache-2.0" ]
permissive
Utopiah/oxide
09011db34d5b205cbf707c0b5cbd9d06b07f5e41
ba28d16aad5cbd036de98d036f89377993e991a3
refs/heads/master
2022-12-27T13:59:04.514420
2020-09-28T14:30:57
2020-09-28T14:30:57
null
0
0
null
null
null
null
UTF-8
C++
false
false
310
h
apibase.h
#ifndef APIBASE_H #define APIBASE_H #include <QObject> #include "dbussettings.h" class APIBase : public QObject{ Q_OBJECT Q_CLASSINFO("Version", OXIDE_INTERFACE_VERSION) public: APIBase(QObject* parent) : QObject(parent) {} virtual void setEnabled(bool enabled) = 0; }; #endif // APIBASE_H
1ee5f4c98955bd8931832fa599af6c83fa625f4b
d8bca84c6440baeb1184bf593f47723c3e44483d
/src/gil.h
8db9ade8a16c6e96a22cbe4bb1af7d464b7ea821
[ "BSD-3-Clause" ]
permissive
wyli/cpp-py-example
40fca8d35d91a344725bf73e414cc1bd0bea10ba
8ad6fd8f0b4a4f4ddcde2f21099fc9d914cc0f36
refs/heads/master
2020-03-20T06:06:25.773113
2018-06-13T16:04:35
2018-06-13T16:04:35
137,238,726
0
1
null
2018-06-13T16:00:34
2018-06-13T16:00:33
null
UTF-8
C++
false
false
749
h
gil.h
#pragma once #include <boost/python.hpp> class ScopedGilRelease { protected: PyThreadState * _thread_state; public: inline ScopedGilRelease() : _thread_state(nullptr) { if (PyEval_ThreadsInitialized() != 0) _thread_state = PyEval_SaveThread(); } inline ~ScopedGilRelease() { if (_thread_state != nullptr) { PyEval_RestoreThread(_thread_state); _thread_state = nullptr; } } }; class ScopedGilAcquisition { protected: PyGILState_STATE _gil_state; public: inline ScopedGilAcquisition() { _gil_state = PyGILState_Ensure(); } inline ~ScopedGilAcquisition() { PyGILState_Release(_gil_state); } };
fe911269374a2d1c8b3f448fb3648c3fa894a0f6
aeabee0b5ba8cb0b190fb88fce144b8021a6f6e0
/libraries/newTOclass/newTOclass.h
ae82573431a580877744adc7453d4abcf1d5259e
[]
no_license
guydvir2/Arduino
7313d590af23c95f7af59e7b1d07e19ed438f344
a33077d21ebe2b07d838794e0548d6bcaa311bbe
refs/heads/master
2023-05-26T11:27:59.517191
2023-04-21T13:17:06
2023-04-21T13:17:06
144,481,047
3
0
null
2018-11-25T20:34:29
2018-08-12T16:05:45
C++
UTF-8
C++
false
false
83
h
newTOclass.h
#ifndef newTO_h #define newTO_h #include "Arduino.h" class CronJobs { }; #endif
3474a76d075a92db7dd569ee795fd2d739408dee
8ab3e882303250ef5b279418d7916c7036b0a1d9
/workspace/w05_04_DoSomethingByFwdRef/DoSomethingByFwdRef.cpp
92357cb60e3f7eaabbe56376585bf840ee22b2c5
[]
no_license
PeterSommerlad/CPPCourseExpert
eaac3a0562ef390b259031629d943f82e384b8cd
84b365c4508c7906f638199115fc2f9597319b4d
refs/heads/main
2023-06-12T00:31:38.864261
2023-05-26T15:51:29
2023-05-26T15:51:45
470,980,622
2
2
null
null
null
null
UTF-8
C++
false
false
850
cpp
DoSomethingByFwdRef.cpp
#include <iostream> #include <boost/type_index.hpp> struct S { S() = default; S(S const &) { std::cout << "S(S const &) -> copy\n"; } S(S&&) { std::cout << "S(S &&) -> move\n"; } }; void do_something(S const &) { std::cout << "do_something(S const &)\n"; } void do_something(S&&) { std::cout << "do_something(S &&)\n"; } template<typename T> void log_and_do(T const & t) { std::cout << "logging!\n"; do_something(t); } template<typename T> void log_and_do(T && t) { std::cout << "logging!\n"; do_something(std::move(t)); } int main(int argc, char **argv) { S s{}; std::cout << "--- calling log_and_do(s)\n"; log_and_do(s); //lvalue S const sc{}; std::cout << "--- calling log_and_do(sc)\n"; log_and_do(sc); //lvalue std::cout << "--- calling log_and_do(S{})\n"; log_and_do(S{}); //rvalue std::cout << "--- end\n"; }
bffc2b9ed6fcf67ad63f50b0d4b7d370ed02274b
20ad3fe7c319e8574cefdc7fda0fb1316789d50b
/[Cpp]Week3/[Cpp]Week3/Stack.h
49982419702a029c1b65e68ec62635f0a9db3b6e
[]
no_license
Jsfumato/Cpp_NEXT
b8e107414b7bd6634965ac809913130c9b968ecb
ceaf23a78632d371a6cca3e1f655066e4bda0c07
refs/heads/master
2020-05-26T07:21:45.155332
2015-10-14T15:26:15
2015-10-14T15:26:15
42,442,965
0
0
null
null
null
null
UTF-8
C++
false
false
618
h
Stack.h
// // Stack.h // [Cpp]Week3 // // Created by Jsfumato on 2015. 10. 1.. // Copyright © 2015년 Jsfumato. All rights reserved. // #ifndef Stack_h #define Stack_h #include <iostream> using namespace std; template <class T> class Stack { private: T* list; int size; int top; public: Stack(int num = 10):size(num),top(-1),list(new T[num]) { for(int i=0; i<size; i++) { list[i] = NULL; } }; ~Stack() { delete[] list; }; void Push(const T &item); T Pop(); bool IsFull(); bool IsEmpty(); }; #endif /* Stack_h */
a10f3cf038dfe6124118dd762750eaca9a51a81a
12909a45a5c0c0731c93a07ea2f55946818417e3
/DxFontFallback/DxFontFallback.cpp
3b63bfb2ed4af9b674f4fff529ac4e7cca5338f4
[]
no_license
gillesgg/DxFontFallback
4f4a576a902a822804d2699fa7374835805780cb
c89157c5e6d471b963931718131b572343c5fc8f
refs/heads/master
2020-08-27T23:42:52.882500
2019-10-25T12:32:43
2019-10-25T12:32:43
217,523,374
1
0
null
null
null
null
UTF-8
C++
false
false
524
cpp
DxFontFallback.cpp
// DxFontFallback.cpp : This file contains the 'main' function. Program execution begins and ends there. // #include "pch.h" #include "FontFallbackConst.h" #include "MapCharacters.h" #include <iostream> int main() { MapCharacters map; map.init(); map.CreateFontFallBack(); for (auto i = 0; i < DWriteFontFallback::SampleConstants::MaxTextBlocks1; i++) { std::wstring str_text = DWriteFontFallback::SampleConstants::TextStrings1[i].TextString; if (!str_text.empty()) map.MapChar(str_text); } return S_OK; }
2d538d67e17a1bf6ae76e37847d5b89d9d847071
fa476614d54468bcdd9204c646bb832b4e64df93
/otherRepos/luis/CDC/SNACKDOWN2016/QR/B.cpp
4d36ffe208e40975aecd88b433d45c328afece45
[]
no_license
LuisAlbertoVasquezVargas/CP
300b0ed91425cd7fea54237a61a4008c5f1ed2b7
2901a603a00822b008fae3ac65b7020dcddcb491
refs/heads/master
2021-01-22T06:23:14.143646
2017-02-16T17:52:59
2017-02-16T17:52:59
81,754,145
0
0
null
null
null
null
UTF-8
C++
false
false
847
cpp
B.cpp
#include<bits/stdc++.h> using namespace std; #define REP(i,n) for(int i=0;i<n;++i) #define all(v) v.begin(),v.end() typedef long long LL; typedef vector< LL > VLL; typedef vector< int > VI; VLL get( VI &A ){ int n = A.size(); VLL DP( n ); DP[ 0 ] = A[ 0 ]; for( int i = 1 ; i < n ; ++i ) DP[ i ] = max( (LL)A[ i ] , A[ i ] + DP[ i - 1 ] ); return DP; } int main(){ int cases; scanf( "%d" , &cases ); REP( tc , cases ){ int n; scanf( "%d" , &n ); VI A( n ); REP( i , n ) scanf( "%d" , &A[ i ] ); VLL dp = get( A ); reverse( all( A ) ); VLL dpRev = get( A ); reverse( all( dpRev ) ); LL ans = LLONG_MIN; REP( i , n ) ans = max( ans , dp[ i ] ); for( int i = 1 ; i + 1 < n ; ++i ){ ans = max( ans , dp[ i - 1 ] + dpRev[ i + 1 ] ); } printf( "%lld\n" , ans ); } }
50bc767b3599f5b29eeb951f375cba4c9338b774
32c980889389b022b8d1e5645d272775d11b51b2
/pb_message_package/http_json_package.hpp
0cc0657287de5181a53b9bc78eacf386ec4489ec
[]
no_license
xyconly/btool
063836f671480ea8b6b60d361bbd7ce105408ee3
60d67d81dc32ef67c85c5c9a06014b037755e3f4
refs/heads/master
2023-07-11T03:02:18.282931
2023-07-07T02:13:51
2023-07-07T02:13:51
173,895,319
16
0
null
null
null
null
GB18030
C++
false
false
11,637
hpp
http_json_package.hpp
/************************************************************************ * Purpose: 用于http通讯的json字符串消息封包解包 Json格式: { "Code": 200, #"Msg": "",# // 无错误时为空 "ServerTime": 2256612312, "Data": {} } /************************************************************************/ #pragma once #include <memory> #include <algorithm> #include <string> #include <sstream> #include <openssl/sha.h> #include <boost/beast/http.hpp> #include <boost/beast/version.hpp> #include <json/writer.h> #include <json/reader.h> #include <json/json.h> #include "../comm_str_os.hpp" #include "../datetime_convert.hpp" #ifdef _MSC_VER # ifndef WIN32_LEAN_AND_MEAN # define WIN32_LEAN_AND_MEAN # endif // !WIN32_LEAN_AND_MEAN # include <winsock2.h> #elif defined(__GNUC__) # include <arpa/inet.h> #endif namespace NPHttpJsonPackage { #define HEAD_MSG_ContentType "Content-Type" // 内容类型,一般为application/json,get请求时无需该参数 #define HEAD_MSG_Nonce "Nonce" // 唯一码,公钥 #define HEAD_MSG_CurTime "CurTime" // 当前时间(unix时间戳),秒 #define HEAD_MSG_CheckSum "CheckSum" // 校验码(Secret(私钥)+Nonce+CurTime(字符串),SHA1 ,然后全小写) #define SHA_DIGEST_LENGTH 20 // SHA散列值长度 #define RSP_Code "code" // 返回码,int,200:成功; 500:失败 #define RSP_Msg "msg" // Error Message,无错误时为空 #define RSP_ServerTime "serverTime" // 服务器时间 #define RSP_Data "data" // 数据 // 包头 struct PackHeader { std::string content_type_; // 内容类型 std::string nonce_; // 唯一码 std::string cur_time_; // 当前时间 std::string check_sum_; // 校验码 }; class Package { public: typedef boost::beast::http::request<boost::beast::http::string_body> request_type; typedef boost::beast::http::response<boost::beast::http::string_body> response_type; protected: static std::string generate_checksum(const char* const secret, const std::string& nonce, const std::string& cur_time) { std::string src = secret + nonce + cur_time; unsigned char digest[SHA_DIGEST_LENGTH] = { 0 }; SHA1((const unsigned char*)src.c_str(), src.length(), (unsigned char*)&digest); char mdString[SHA_DIGEST_LENGTH * 2 + 1] = { 0 }; for (int i = 0; i < SHA_DIGEST_LENGTH; i++) sprintf_s(&mdString[i * 2], 3, "%02x", (unsigned int)digest[i]); return mdString; } }; // 解包 class DecodePackage : public Package { public: DecodePackage(const request_type& request, const char* const secret) : m_method(request.method()) { if(m_method != boost::beast::http::verb::get && m_method != boost::beast::http::verb::post /*&& m_method != boost::beast::http::verb::head*/) { m_cur_isvaild = false; return; } if (request.target().empty() || request.target()[0] != '/' || request.target().find("..") != boost::beast::string_view::npos) { m_cur_isvaild = false; return; } auto split_pos = request.target().find_first_of('?'); if(split_pos != boost::beast::string_view::npos) { m_path = request.target().substr(0, split_pos).to_string(); std::transform(m_path.begin(), m_path.end(), m_path.begin(), ::tolower); m_params = request.target().substr(split_pos + 1).to_string(); //std::transform(m_params.begin(), m_params.end(), m_params.begin(), ::tolower); } else { m_path = request.target().to_string(); std::transform(m_path.begin(), m_path.end(), m_path.begin(), ::tolower); } //auto content_type_iter = request.find(HEAD_MSG_ContentType); //m_cur_isvaild = content_type_iter != request.end(); //if (m_cur_isvaild) m_head.content_type_ = /*content_type_iter->value().to_string()*/"application/json"; //else if(m_method != boost::beast::http::verb::get) // return; //auto nonce_iter = request.find(HEAD_MSG_Nonce); //m_cur_isvaild = nonce_iter != request.end(); //if (!m_cur_isvaild) // return; //m_head.nonce_ = nonce_iter->value().to_string(); /*auto cur_time_iter = request.find(HEAD_MSG_CurTime); m_cur_isvaild = cur_time_iter != request.end(); if (!m_cur_isvaild) return; m_head.cur_time_ = cur_time_iter->value().to_string(); auto check_sum_iter = request.find(HEAD_MSG_CheckSum); m_cur_isvaild = check_sum_iter != request.end(); if (!m_cur_isvaild) return;*/ //m_head.check_sum_ = check_sum_iter->value().to_string(); /* std::transform(m_head.check_sum_.begin(), m_head.check_sum_.end(), m_head.check_sum_.begin(), ::tolower); m_cur_isvaild = generate_checksum(secret, m_head.nonce_, m_head.cur_time_) == m_head.check_sum_; if (!m_cur_isvaild) return;*/ m_cur_isvaild = true; m_body = request.body(); } public: // 当前包是否是完整包 bool is_entire() const { return m_cur_isvaild; } // 获取path路径,均为小写 const std::string& get_path() const { return m_path; } // 获取params参数,均为小写 const std::string& get_params() const { return m_params; } // 获取http请求方法 const boost::beast::http::verb& get_method() const { return m_method; } // 获取内容类型,一般为application/json const std::string& get_content_type() const { return m_head.content_type_; } // 获取唯一码 const std::string& get_nonce() const { return m_head.nonce_; } // 获取当前时间 const std::string& get_cur_time() const { return m_head.cur_time_; } // 获取校验码 const std::string& get_check_sum() const { return m_head.check_sum_; } // 获取包头 const PackHeader& get_head() const { return m_head; } // 获取包体 const std::string& get_body() const { return m_body; } private: PackHeader m_head; // 当前包头 std::string m_body; // 包体内容 std::string m_path; // path路径(http://127.0.0.1:22/path/) std::string m_params; // params参数(?之后的参数) boost::beast::http::verb m_method; // http请求方法 bool m_cur_isvaild; // 当前解的包是否有效 }; // 打包 class EncodePackage : public Package { public: EncodePackage(const request_type& request, const char* const secret) : m_request(request) , m_secret(secret) { } ~EncodePackage() { } response_type bad_request(const std::string& why) { response_type res{ boost::beast::http::status::bad_request, m_request.version() }; rsp_set(res, false, why); return std::move(res); } response_type not_found(const std::string& path) { response_type res{ boost::beast::http::status::not_found, m_request.version() }; rsp_set(res, false, "The target '" + path + "' was not support!"); return std::move(res); } response_type server_error(const std::string& why) { response_type res{ boost::beast::http::status::internal_server_error, m_request.version() }; rsp_set(res, false, why); return std::move(res); } // boost::beast::http::response<boost::beast::http::empty_body> request_head(size_t size) { // boost::beast::http::response<boost::beast::http::empty_body> res{ boost::beast::http::status::ok, m_request.version() }; // res.set(boost::beast::http::field::server, BOOST_BEAST_VERSION_STRING); // res.set(boost::beast::http::field::content_type, "application/json"); // res.content_length(size); // res.keep_alive(m_request.keep_alive()); // return std::move(res); // } template<typename BodyType> response_type response(bool is_true, const BodyType& body) { response_type res{ boost::beast::http::status::ok, m_request.version() }; rsp_set(res, is_true, body); return std::move(res); } private: // is_true:为true时body表示发送数据; 为false时表示错误内容 template<typename BodyType> std::string rsp_body(bool is_true, const BodyType& body) { Json::Value body_json; if(is_true) { body_json[RSP_Code] = 200; body_json[RSP_Data] = body; } else { body_json[RSP_Code] = 400; body_json[RSP_Msg] = body; } body_json[RSP_ServerTime] = BTool::DateTimeConvert::GetCurrentSystemTime(BTool::DateTimeConvert::DTS_YMDHMS).to_time_t(); Json::StreamWriterBuilder builder; builder["commentStyle"] = "None"; builder["indentation"] = ""; std::unique_ptr<Json::StreamWriter> writer(builder.newStreamWriter()); std::stringstream os; writer->write(body_json, &os); return os.str(); } template<typename BodyType> void rsp_set(response_type& res, bool is_true, const BodyType& body) { res.set(boost::beast::http::field::server, BOOST_BEAST_VERSION_STRING); res.set(boost::beast::http::field::content_type, "application/json"); res.keep_alive(m_request.keep_alive()); // res.set(HEAD_MSG_ContentType, "application/json"); res.set(HEAD_MSG_Nonce, m_request[HEAD_MSG_Nonce]); std::string cur_time = std::to_string(BTool::DateTimeConvert::GetCurrentSystemTime(BTool::DateTimeConvert::DTS_YMDHMS).to_time_t()); res.set(HEAD_MSG_CurTime, cur_time); std::string send_body = rsp_body(is_true, body); res.set(HEAD_MSG_CheckSum, generate_checksum(m_secret, m_request[HEAD_MSG_Nonce].to_string(), cur_time)); res.content_length(send_body.length()); res.body() = send_body; res.prepare_payload(); } private: const request_type& m_request; const char* const m_secret; }; }
4254dfdefe83c6ac0b4c86cd0ca75f44f72c9fc0
f2c14b21568a9c827b4b2b32651be645003f1838
/colors/docker/GradientEditor.cpp
a989c5bedac5967d2baff60631fdf8a804a5209c
[]
no_license
KDE/koffice-plugins
c300d852a6dfe1dddbe86316e28c03ee49de854d
ba6e431a676058970fa8f8223d4ca40d34159adf
refs/heads/master
2016-09-09T21:05:08.672197
2013-10-13T04:25:03
2013-10-13T04:25:03
42,722,310
2
1
null
2015-10-10T10:29:14
2015-09-18T12:58:18
C++
UTF-8
C++
false
false
5,580
cpp
GradientEditor.cpp
/* This file is part of the KDE project * Copyright (C) 2011 Thomas Zander <zander@kde.org> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public License * along with this library; see the file COPYING.LIB. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. */ #include "GradientEditor.h" #include <KoResourceServerAdapter.h> #include <KoAbstractGradient.h> #include <KoResourceServerProvider.h> #include <KoResourceItemChooser.h> #include <QGridLayout> GradientEditor::GradientEditor(QWidget* parent) : QWidget(parent), m_type(QGradient::LinearGradient), m_spread(QGradient::PadSpread), m_gradientEdit(0) { setObjectName("GradientEditor"); widget.setupUi(this); KoAbstractResourceServerAdapter *adapter = new KoResourceServerAdapter<KoAbstractGradient> (KoResourceServerProvider::instance()->gradientServer()); KoResourceItemChooser *chooser = new KoResourceItemChooser(adapter, widget.selectionPage); chooser->showButtons(false); widget.selectionPageLayout->addWidget(chooser, 0, 0); //chooser->setObjectName("GradientChooser"); //chooser->setColumnCount(1); connect (widget.editCheckbox, SIGNAL(clicked(bool)), this, SLOT(setEditMode(bool))); connect (widget.gradientEditor, SIGNAL(changed(const QGradientStops&)), this, SLOT(updateStops(const QGradientStops&))); connect (widget.gradientType, SIGNAL(currentIndexChanged(int)), this, SLOT(setGradientType(int))); connect (widget.gradientRepeat, SIGNAL(currentIndexChanged(int)), this, SLOT(setGradientRepeat(int))); connect(chooser, SIGNAL(resourceSelected(KoResource *)), this, SLOT(setGradient(KoResource *))); // TODO store editCheckbox state persistently setEditMode(false); } GradientEditor::~GradientEditor() { } void GradientEditor::setGradientEdit(QGradient *gradient) { m_gradientEdit = 0; if (gradient) { setGradientRepeat((int) (gradient->spread())); widget.gradientEditor->setStops(gradient->stops()); setGradientType((int) (gradient->type())); } m_gradientEdit = gradient; } void GradientEditor::setEditMode(bool on) { widget.editCheckbox->setChecked(on); widget.stackedWidget->setCurrentIndex(on ? 0 : 1); } void GradientEditor::setGradientType(int type) { QGradient::Type t = static_cast<QGradient::Type>(type); if (m_type == t) return; QPointF oldStart(0.3, 0.5); if (m_gradientEdit) { switch (m_gradientEdit->type()) { case QGradient::LinearGradient: oldStart = static_cast<QLinearGradient*>(m_gradientEdit)->start(); break; case QGradient::RadialGradient: oldStart = static_cast<QRadialGradient*>(m_gradientEdit)->center(); break; case QGradient::ConicalGradient: oldStart = static_cast<QConicalGradient*>(m_gradientEdit)->center(); break; default: break; } } m_type = t; widget.gradientType->setCurrentIndex(type); // since this is a differnt type; I have to delete the m_gradientEdit if (m_gradientEdit) { m_gradientEdit = 0; // we don't own it. Don't delete it! QGradient *gradient = 0; switch (m_type) { case QGradient::LinearGradient: gradient = new QLinearGradient(oldStart.x(), oldStart.y(), 1., 0.5); break; case QGradient::RadialGradient: gradient = new QRadialGradient(oldStart.x(), oldStart.y(), 0.5); break; case QGradient::ConicalGradient: gradient = new QConicalGradient(oldStart.x(), oldStart.y(), 45.); break; case QGradient::NoGradient: Q_ASSERT(0); return; } gradient->setSpread(m_spread); gradient->setCoordinateMode(QGradient::ObjectBoundingMode); gradient->setStops(widget.gradientEditor->stops()); emit changedGradientType(*gradient); delete gradient; emit changed(); } } void GradientEditor::setGradientRepeat(int repeat) { QGradient::Spread s = static_cast<QGradient::Spread>(repeat); if (m_spread == s) return; m_spread = s; widget.gradientRepeat->setCurrentIndex(repeat); if (m_gradientEdit) { m_gradientEdit->setSpread(m_spread); emit changed(); } } void GradientEditor::updateStops(const QGradientStops &stops) { if (m_gradientEdit) { m_gradientEdit->setStops(stops); emit changed(); } } void GradientEditor::setGradient(KoResource *resource) { Q_ASSERT(resource); KoAbstractGradient *gradientResource = dynamic_cast<KoAbstractGradient*>(resource); Q_ASSERT(gradientResource); if (!gradientResource) return; QGradient *gradient = gradientResource->toQGradient(); updateStops(gradient->stops()); widget.gradientEditor->setStops(gradient->stops()); delete gradient; } #include "GradientEditor.moc"
22810c56508d6f21fac4ddd5344edc80bbe7a254
475850f09ea39d11814f3c9f6e301df2fd62c76e
/leetcode/389_Find the Difference.cpp
a3a8227071ff45522d5e6d4d99ba88d231504305
[]
no_license
njuHan/OJcodes
fed59759b4b954a123cdc423d8c36addd7252d41
1adc57f0850f3f0031ba8d62e974ab3842da5c2d
refs/heads/master
2021-01-25T14:22:21.728203
2019-06-16T05:11:55
2019-06-16T05:11:55
123,686,571
16
1
null
null
null
null
UTF-8
C++
false
false
271
cpp
389_Find the Difference.cpp
int a[26] = {0}; class Solution { public: char findTheDifference(string s, string t) { memset(a, 0, sizeof(a)); for (char& ch : t) a[ch-'a']++; for (char& ch : s) a[ch-'a']--; for (int i=0; i<26; i++) if (a[i]) return i + 'a'; } };
87dece1eddb434a22af317b3188f79671962edc6
0f6e9c1c3e44b48fac41dc36d6f114e280617ef6
/chap07/7-3.cpp
dd62ad3ecd75b1bb0d97e71e63e11c5182a9fdbc
[]
no_license
lilixuelian/mingjie-book
78af575dc391897114428d4da539f33cad426d1c
a0dcfcec5b84ada9503bc396ebe81e1a4267266b
refs/heads/master
2020-04-10T13:06:45.567820
2019-08-21T08:01:05
2019-08-21T08:01:05
161,040,911
0
0
null
null
null
null
GB18030
C++
false
false
427
cpp
7-3.cpp
#include <stdio.h> unsigned rrotate(unsigned x,int n){ return x >> n; } unsigned lrotate(unsigned x,int n){ return x << n; } int main (void) { int i, j; printf("请输入整数:%d", i); scanf("%d", &i); printf("请输入移动位数:%d", j); scanf("%d", &j); printf("%u向右移动%d次后的值:%u\n", i, j, rrotate(i, j)); printf("%u向左移动%d次后的值:%u\n", i, j, lrotate(i, j)); }
5ae3ec51f6271811522b8b85f71d67370566d8c8
5d3b17e59b458815d15c7072368d5ca014bffe82
/qtworkplace/zhizuoruanjian/widget.cpp
55a3b3bb1135cc2f4521695e0432500291e1c196
[]
no_license
wushengjun85/QtcreatorWorkplace
274d75331bbdeec57f11f9bb1b59c35c551b3ae4
2366644909f2dce2e5640d7cd67fbee447740bea
refs/heads/master
2021-01-19T23:50:12.348968
2017-12-25T08:40:55
2017-12-25T08:40:55
89,039,956
0
0
null
null
null
null
UTF-8
C++
false
false
1,243
cpp
widget.cpp
#include "widget.h" #include "ui_widget.h" #include<QString> #include<QDebug> #include<QByteArray> Widget::Widget(QWidget *parent) : QWidget(parent), ui(new Ui::Widget) { ui->setupUi(this); // QString str="FF"; // bool ok= true; // int decotc=str.toInt(&ok,10); //dec=255 ; ok=rue // qDebug()<<"decotc == "<<decotc<<endl; QString str3 = "123"; QByteArray ba; qDebug()<<ba.append(str3).toHex()<<endl; } Widget::~Widget() { delete ui; } void Widget::on_pushButton_clicked() { QString temp; temp = ui->lineEdit_3->text(); qDebug()<<temp<<endl; bool ok = true; int testNumber = temp.toInt(&ok,16); // int dec = temp.toInt(&ok,10); // int hex = temp.toInt(&ok,16); // qDebug()<<"dec == "<<dec<<endl; // qDebug()<<"hex NUmber == "<<hex<<endl; //FMI int Fmi = testNumber; Fmi >>= 16; Fmi &= 0x1f; ui->lineEdit->setText(QString::number(Fmi)); int SpnGaowei = testNumber; SpnGaowei = SpnGaowei>>16; SpnGaowei = SpnGaowei&0xe0; SpnGaowei = SpnGaowei>>5; int SpnDiWeiTwo = testNumber; SpnDiWeiTwo &= 0xFFFF; int Spn = SpnGaowei; Spn <<= 16; Spn |= SpnDiWeiTwo; ui->lineEdit_2->setText(QString::number(Spn)); }
ee60a386036641473db3291651558d1d4ce01c59
9bd6b19ab87747123fe1de195c42cdcf27e855a1
/AdeeptLesson/Lesson12/_12_PIRSensorModule/_12_PIRSensorModule.ino
178fa5dccd2f6a0bb0dbd0a1e530993d1b49892c
[]
no_license
adeept/Adeept_Ultimate_Sensor_Kit_for_UNO_R3
bd1aba0fa547fde388407ffcea18f456cf355a4c
2a7bdc05a4426529c66ef616f52395a5661b0000
refs/heads/master
2022-06-23T09:01:38.936541
2020-05-12T02:18:58
2020-05-12T02:18:58
261,412,600
1
0
null
null
null
null
UTF-8
C++
false
false
808
ino
_12_PIRSensorModule.ino
/*********************************************************** File name: _12_PIRSensorModule.ino Description: The motion has been detected by PIR sensor module, and displayed in the serial monitor Website: www.adeept.com E-mail: support@adeept.com Author: Tom Date: 2017/03/14 ***********************************************************/ int PIRPin=8; //Set the digital 8 to PIR void setup() { pinMode( PIRPin,INPUT);//initialize the PIR pin as input Serial.begin(9600); //opens serial port, sets data rate to 9600 bps } void loop() { if(digitalRead(PIRPin)==LOW) { Serial.println("No invasion"); //send data to the serial monitor }else { Serial.println("Invasion"); //send data to the serial monitor } delay(1000); //delay 1s }
291bc99a155500abedab0648b99edb4c8ec1df41
d96ebf4dac46404a46253afba5ba5fc985d5f6fc
/security/sandbox/chromium/sandbox/linux/bpf_dsl/bpf_dsl.h
c56cdefb7781e341945536fced26a26eee1dd399
[ "BSD-3-Clause", "LicenseRef-scancode-unknown-license-reference" ]
permissive
marco-c/gecko-dev-wordified-and-comments-removed
f9de100d716661bd67a3e7e3d4578df48c87733d
74cb3d31740be3ea5aba5cb7b3f91244977ea350
refs/heads/master
2023-08-04T23:19:13.836981
2023-08-01T00:33:54
2023-08-01T00:33:54
211,297,165
1
0
null
null
null
null
UTF-8
C++
false
false
5,333
h
bpf_dsl.h
# ifndef SANDBOX_LINUX_BPF_DSL_BPF_DSL_H_ # define SANDBOX_LINUX_BPF_DSL_BPF_DSL_H_ # include < stddef . h > # include < stdint . h > # include < memory > # include < utility > # include < vector > # include " base / macros . h " # include " sandbox / linux / bpf_dsl / bpf_dsl_forward . h " # include " sandbox / linux / bpf_dsl / cons . h " # include " sandbox / linux / bpf_dsl / trap_registry . h " # include " sandbox / sandbox_export . h " namespace sandbox { namespace bpf_dsl { template < typename T > class Caser ; class Elser ; using ResultExpr = std : : shared_ptr < const internal : : ResultExprImpl > ; using BoolExpr = std : : shared_ptr < const internal : : BoolExprImpl > ; SANDBOX_EXPORT ResultExpr Allow ( ) ; SANDBOX_EXPORT ResultExpr Error ( int err ) ; SANDBOX_EXPORT ResultExpr Kill ( ) ; SANDBOX_EXPORT ResultExpr Trace ( uint16_t aux ) ; SANDBOX_EXPORT ResultExpr Trap ( TrapRegistry : : TrapFnc trap_func const void * aux ) ; SANDBOX_EXPORT ResultExpr UnsafeTrap ( TrapRegistry : : TrapFnc trap_func const void * aux ) ; SANDBOX_EXPORT BoolExpr BoolConst ( bool value ) ; SANDBOX_EXPORT BoolExpr Not ( BoolExpr cond ) ; SANDBOX_EXPORT BoolExpr AllOf ( ) ; SANDBOX_EXPORT BoolExpr AllOf ( BoolExpr lhs BoolExpr rhs ) ; template < typename . . . Rest > SANDBOX_EXPORT BoolExpr AllOf ( BoolExpr first Rest & & . . . rest ) ; SANDBOX_EXPORT BoolExpr AnyOf ( ) ; SANDBOX_EXPORT BoolExpr AnyOf ( BoolExpr lhs BoolExpr rhs ) ; template < typename . . . Rest > SANDBOX_EXPORT BoolExpr AnyOf ( BoolExpr first Rest & & . . . rest ) ; template < typename T > class SANDBOX_EXPORT Arg { public : explicit Arg ( int num ) ; Arg ( const Arg & arg ) : num_ ( arg . num_ ) mask_ ( arg . mask_ ) { } friend Arg operator & ( const Arg & lhs uint64_t rhs ) { return Arg ( lhs . num_ lhs . mask_ & rhs ) ; } friend BoolExpr operator = = ( const Arg & lhs T rhs ) { return lhs . EqualTo ( rhs ) ; } friend BoolExpr operator ! = ( const Arg & lhs T rhs ) { return Not ( lhs = = rhs ) ; } private : Arg ( int num uint64_t mask ) : num_ ( num ) mask_ ( mask ) { } BoolExpr EqualTo ( T val ) const ; int num_ ; uint64_t mask_ ; DISALLOW_ASSIGN ( Arg ) ; } ; SANDBOX_EXPORT Elser If ( BoolExpr cond ResultExpr then_result ) ; class SANDBOX_EXPORT Elser { public : Elser ( const Elser & elser ) ; ~ Elser ( ) ; Elser ElseIf ( BoolExpr cond ResultExpr then_result ) const ; ResultExpr Else ( ResultExpr else_result ) const ; private : using Clause = std : : pair < BoolExpr ResultExpr > ; explicit Elser ( cons : : List < Clause > clause_list ) ; cons : : List < Clause > clause_list_ ; friend Elser If ( BoolExpr ResultExpr ) ; template < typename T > friend Caser < T > Switch ( const Arg < T > & ) ; DISALLOW_ASSIGN ( Elser ) ; } ; template < typename T > SANDBOX_EXPORT Caser < T > Switch ( const Arg < T > & arg ) ; template < typename T > class SANDBOX_EXPORT Caser { public : Caser ( const Caser < T > & caser ) : arg_ ( caser . arg_ ) elser_ ( caser . elser_ ) { } ~ Caser ( ) { } Caser < T > Case ( T value ResultExpr result ) const ; template < typename . . . Values > Caser < T > CasesImpl ( ResultExpr result const Values & . . . values ) const ; ResultExpr Default ( ResultExpr result ) const ; private : Caser ( const Arg < T > & arg Elser elser ) : arg_ ( arg ) elser_ ( elser ) { } Arg < T > arg_ ; Elser elser_ ; template < typename U > friend Caser < U > Switch ( const Arg < U > & ) ; DISALLOW_ASSIGN ( Caser ) ; } ; # define SANDBOX_BPF_DSL_CASES ( values result ) \ CasesImpl ( result SANDBOX_BPF_DSL_CASES_HELPER values ) # define SANDBOX_BPF_DSL_CASES_HELPER ( . . . ) __VA_ARGS__ namespace internal { using bpf_dsl : : Not ; using bpf_dsl : : AllOf ; using bpf_dsl : : AnyOf ; SANDBOX_EXPORT BoolExpr ArgEq ( int num size_t size uint64_t mask uint64_t val ) ; SANDBOX_EXPORT uint64_t DefaultMask ( size_t size ) ; } template < typename T > Arg < T > : : Arg ( int num ) : num_ ( num ) mask_ ( internal : : DefaultMask ( sizeof ( T ) ) ) { } template < typename T > BoolExpr Arg < T > : : EqualTo ( T val ) const { if ( sizeof ( T ) = = 4 ) { return internal : : ArgEq ( num_ sizeof ( T ) mask_ static_cast < uint32_t > ( val ) ) ; } return internal : : ArgEq ( num_ sizeof ( T ) mask_ static_cast < uint64_t > ( val ) ) ; } template < typename T > SANDBOX_EXPORT Caser < T > Switch ( const Arg < T > & arg ) { return Caser < T > ( arg Elser ( nullptr ) ) ; } template < typename T > Caser < T > Caser < T > : : Case ( T value ResultExpr result ) const { return SANDBOX_BPF_DSL_CASES ( ( value ) std : : move ( result ) ) ; } template < typename T > template < typename . . . Values > Caser < T > Caser < T > : : CasesImpl ( ResultExpr result const Values & . . . values ) const { return Caser < T > ( arg_ elser_ . ElseIf ( AnyOf ( ( arg_ = = values ) . . . ) std : : move ( result ) ) ) ; } template < typename T > ResultExpr Caser < T > : : Default ( ResultExpr result ) const { return elser_ . Else ( std : : move ( result ) ) ; } template < typename . . . Rest > BoolExpr AllOf ( BoolExpr first Rest & & . . . rest ) { return AllOf ( std : : move ( first ) AllOf ( std : : forward < Rest > ( rest ) . . . ) ) ; } template < typename . . . Rest > BoolExpr AnyOf ( BoolExpr first Rest & & . . . rest ) { return AnyOf ( std : : move ( first ) AnyOf ( std : : forward < Rest > ( rest ) . . . ) ) ; } } } # endif
63f3663e2c3b07114cb162e985ef395f67f8e0b0
8f9964d7cf0df36b2bd073ae94533f304e93fc63
/services_2.0/password_manager/PasswordManager.pb.cc
cdd8020415718261c86716d11421c07330b70c2a
[]
no_license
yangsongx/cdbackend
5aee1999a38a6864948f2f3a8b40c25bf7d0176b
4bd9505cc9d2c31910257a07dd9d5708cb1cef9c
refs/heads/master
2020-07-14T00:47:45.607616
2016-03-17T07:58:11
2016-03-17T09:13:27
67,760,275
0
0
null
null
null
null
UTF-8
C++
false
true
30,998
cc
PasswordManager.pb.cc
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: PasswordManager.proto #define INTERNAL_SUPPRESS_PROTOBUF_FIELD_DEPRECATION #include "PasswordManager.pb.h" #include <algorithm> #include <google/protobuf/stubs/common.h> #include <google/protobuf/stubs/once.h> #include <google/protobuf/io/coded_stream.h> #include <google/protobuf/wire_format_lite_inl.h> #include <google/protobuf/descriptor.h> #include <google/protobuf/generated_message_reflection.h> #include <google/protobuf/reflection_ops.h> #include <google/protobuf/wire_format.h> // @@protoc_insertion_point(includes) namespace com { namespace caredear { namespace { const ::google::protobuf::Descriptor* PasswordManagerRequest_descriptor_ = NULL; const ::google::protobuf::internal::GeneratedMessageReflection* PasswordManagerRequest_reflection_ = NULL; const ::google::protobuf::Descriptor* PasswordManagerResponse_descriptor_ = NULL; const ::google::protobuf::internal::GeneratedMessageReflection* PasswordManagerResponse_reflection_ = NULL; const ::google::protobuf::EnumDescriptor* PasswordType_descriptor_ = NULL; } // namespace void protobuf_AssignDesc_PasswordManager_2eproto() { protobuf_AddDesc_PasswordManager_2eproto(); const ::google::protobuf::FileDescriptor* file = ::google::protobuf::DescriptorPool::generated_pool()->FindFileByName( "PasswordManager.proto"); GOOGLE_CHECK(file != NULL); PasswordManagerRequest_descriptor_ = file->message_type(0); static const int PasswordManagerRequest_offsets_[5] = { GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(PasswordManagerRequest, type_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(PasswordManagerRequest, caredear_id_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(PasswordManagerRequest, new_passwd_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(PasswordManagerRequest, old_passwd_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(PasswordManagerRequest, cur_token_), }; PasswordManagerRequest_reflection_ = new ::google::protobuf::internal::GeneratedMessageReflection( PasswordManagerRequest_descriptor_, PasswordManagerRequest::default_instance_, PasswordManagerRequest_offsets_, GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(PasswordManagerRequest, _has_bits_[0]), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(PasswordManagerRequest, _unknown_fields_), -1, ::google::protobuf::DescriptorPool::generated_pool(), ::google::protobuf::MessageFactory::generated_factory(), sizeof(PasswordManagerRequest)); PasswordManagerResponse_descriptor_ = file->message_type(1); static const int PasswordManagerResponse_offsets_[2] = { GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(PasswordManagerResponse, result_code_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(PasswordManagerResponse, extra_msg_), }; PasswordManagerResponse_reflection_ = new ::google::protobuf::internal::GeneratedMessageReflection( PasswordManagerResponse_descriptor_, PasswordManagerResponse::default_instance_, PasswordManagerResponse_offsets_, GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(PasswordManagerResponse, _has_bits_[0]), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(PasswordManagerResponse, _unknown_fields_), -1, ::google::protobuf::DescriptorPool::generated_pool(), ::google::protobuf::MessageFactory::generated_factory(), sizeof(PasswordManagerResponse)); PasswordType_descriptor_ = file->enum_type(0); } namespace { GOOGLE_PROTOBUF_DECLARE_ONCE(protobuf_AssignDescriptors_once_); inline void protobuf_AssignDescriptorsOnce() { ::google::protobuf::GoogleOnceInit(&protobuf_AssignDescriptors_once_, &protobuf_AssignDesc_PasswordManager_2eproto); } void protobuf_RegisterTypes(const ::std::string&) { protobuf_AssignDescriptorsOnce(); ::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage( PasswordManagerRequest_descriptor_, &PasswordManagerRequest::default_instance()); ::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage( PasswordManagerResponse_descriptor_, &PasswordManagerResponse::default_instance()); } } // namespace void protobuf_ShutdownFile_PasswordManager_2eproto() { delete PasswordManagerRequest::default_instance_; delete PasswordManagerRequest_reflection_; delete PasswordManagerResponse::default_instance_; delete PasswordManagerResponse_reflection_; } void protobuf_AddDesc_PasswordManager_2eproto() { static bool already_here = false; if (already_here) return; already_here = true; GOOGLE_PROTOBUF_VERIFY_VERSION; ::google::protobuf::DescriptorPool::InternalAddGeneratedFile( "\n\025PasswordManager.proto\022\014com.caredear\"\222\001" "\n\026PasswordManagerRequest\022(\n\004type\030\001 \002(\0162\032" ".com.caredear.PasswordType\022\023\n\013caredear_i" "d\030\002 \002(\004\022\022\n\nnew_passwd\030\003 \002(\t\022\022\n\nold_passw" "d\030\004 \001(\t\022\021\n\tcur_token\030\005 \001(\t\"A\n\027PasswordMa" "nagerResponse\022\023\n\013result_code\030\001 \002(\005\022\021\n\tex" "tra_msg\030\002 \001(\t*&\n\014PasswordType\022\n\n\006MODIFY\020" "\000\022\n\n\006FORGET\020\001", 293); ::google::protobuf::MessageFactory::InternalRegisterGeneratedFile( "PasswordManager.proto", &protobuf_RegisterTypes); PasswordManagerRequest::default_instance_ = new PasswordManagerRequest(); PasswordManagerResponse::default_instance_ = new PasswordManagerResponse(); PasswordManagerRequest::default_instance_->InitAsDefaultInstance(); PasswordManagerResponse::default_instance_->InitAsDefaultInstance(); ::google::protobuf::internal::OnShutdown(&protobuf_ShutdownFile_PasswordManager_2eproto); } // Force AddDescriptors() to be called at static initialization time. struct StaticDescriptorInitializer_PasswordManager_2eproto { StaticDescriptorInitializer_PasswordManager_2eproto() { protobuf_AddDesc_PasswordManager_2eproto(); } } static_descriptor_initializer_PasswordManager_2eproto_; const ::google::protobuf::EnumDescriptor* PasswordType_descriptor() { protobuf_AssignDescriptorsOnce(); return PasswordType_descriptor_; } bool PasswordType_IsValid(int value) { switch(value) { case 0: case 1: return true; default: return false; } } // =================================================================== #ifndef _MSC_VER const int PasswordManagerRequest::kTypeFieldNumber; const int PasswordManagerRequest::kCaredearIdFieldNumber; const int PasswordManagerRequest::kNewPasswdFieldNumber; const int PasswordManagerRequest::kOldPasswdFieldNumber; const int PasswordManagerRequest::kCurTokenFieldNumber; #endif // !_MSC_VER PasswordManagerRequest::PasswordManagerRequest() : ::google::protobuf::Message() { SharedCtor(); // @@protoc_insertion_point(constructor:com.caredear.PasswordManagerRequest) } void PasswordManagerRequest::InitAsDefaultInstance() { } PasswordManagerRequest::PasswordManagerRequest(const PasswordManagerRequest& from) : ::google::protobuf::Message() { SharedCtor(); MergeFrom(from); // @@protoc_insertion_point(copy_constructor:com.caredear.PasswordManagerRequest) } void PasswordManagerRequest::SharedCtor() { ::google::protobuf::internal::GetEmptyString(); _cached_size_ = 0; type_ = 0; caredear_id_ = GOOGLE_ULONGLONG(0); new_passwd_ = const_cast< ::std::string*>(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); old_passwd_ = const_cast< ::std::string*>(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); cur_token_ = const_cast< ::std::string*>(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); ::memset(_has_bits_, 0, sizeof(_has_bits_)); } PasswordManagerRequest::~PasswordManagerRequest() { // @@protoc_insertion_point(destructor:com.caredear.PasswordManagerRequest) SharedDtor(); } void PasswordManagerRequest::SharedDtor() { if (new_passwd_ != &::google::protobuf::internal::GetEmptyStringAlreadyInited()) { delete new_passwd_; } if (old_passwd_ != &::google::protobuf::internal::GetEmptyStringAlreadyInited()) { delete old_passwd_; } if (cur_token_ != &::google::protobuf::internal::GetEmptyStringAlreadyInited()) { delete cur_token_; } if (this != default_instance_) { } } void PasswordManagerRequest::SetCachedSize(int size) const { GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); _cached_size_ = size; GOOGLE_SAFE_CONCURRENT_WRITES_END(); } const ::google::protobuf::Descriptor* PasswordManagerRequest::descriptor() { protobuf_AssignDescriptorsOnce(); return PasswordManagerRequest_descriptor_; } const PasswordManagerRequest& PasswordManagerRequest::default_instance() { if (default_instance_ == NULL) protobuf_AddDesc_PasswordManager_2eproto(); return *default_instance_; } PasswordManagerRequest* PasswordManagerRequest::default_instance_ = NULL; PasswordManagerRequest* PasswordManagerRequest::New() const { return new PasswordManagerRequest; } void PasswordManagerRequest::Clear() { if (_has_bits_[0 / 32] & 31) { type_ = 0; caredear_id_ = GOOGLE_ULONGLONG(0); if (has_new_passwd()) { if (new_passwd_ != &::google::protobuf::internal::GetEmptyStringAlreadyInited()) { new_passwd_->clear(); } } if (has_old_passwd()) { if (old_passwd_ != &::google::protobuf::internal::GetEmptyStringAlreadyInited()) { old_passwd_->clear(); } } if (has_cur_token()) { if (cur_token_ != &::google::protobuf::internal::GetEmptyStringAlreadyInited()) { cur_token_->clear(); } } } ::memset(_has_bits_, 0, sizeof(_has_bits_)); mutable_unknown_fields()->Clear(); } bool PasswordManagerRequest::MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input) { #define DO_(EXPRESSION) if (!(EXPRESSION)) goto failure ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:com.caredear.PasswordManagerRequest) for (;;) { ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoff(127); tag = p.first; if (!p.second) goto handle_unusual; switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { // required .com.caredear.PasswordType type = 1; case 1: { if (tag == 8) { int value; DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< int, ::google::protobuf::internal::WireFormatLite::TYPE_ENUM>( input, &value))); if (::com::caredear::PasswordType_IsValid(value)) { set_type(static_cast< ::com::caredear::PasswordType >(value)); } else { mutable_unknown_fields()->AddVarint(1, value); } } else { goto handle_unusual; } if (input->ExpectTag(16)) goto parse_caredear_id; break; } // required uint64 caredear_id = 2; case 2: { if (tag == 16) { parse_caredear_id: DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< ::google::protobuf::uint64, ::google::protobuf::internal::WireFormatLite::TYPE_UINT64>( input, &caredear_id_))); set_has_caredear_id(); } else { goto handle_unusual; } if (input->ExpectTag(26)) goto parse_new_passwd; break; } // required string new_passwd = 3; case 3: { if (tag == 26) { parse_new_passwd: DO_(::google::protobuf::internal::WireFormatLite::ReadString( input, this->mutable_new_passwd())); ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField( this->new_passwd().data(), this->new_passwd().length(), ::google::protobuf::internal::WireFormat::PARSE, "new_passwd"); } else { goto handle_unusual; } if (input->ExpectTag(34)) goto parse_old_passwd; break; } // optional string old_passwd = 4; case 4: { if (tag == 34) { parse_old_passwd: DO_(::google::protobuf::internal::WireFormatLite::ReadString( input, this->mutable_old_passwd())); ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField( this->old_passwd().data(), this->old_passwd().length(), ::google::protobuf::internal::WireFormat::PARSE, "old_passwd"); } else { goto handle_unusual; } if (input->ExpectTag(42)) goto parse_cur_token; break; } // optional string cur_token = 5; case 5: { if (tag == 42) { parse_cur_token: DO_(::google::protobuf::internal::WireFormatLite::ReadString( input, this->mutable_cur_token())); ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField( this->cur_token().data(), this->cur_token().length(), ::google::protobuf::internal::WireFormat::PARSE, "cur_token"); } else { goto handle_unusual; } if (input->ExpectAtEnd()) goto success; break; } default: { handle_unusual: if (tag == 0 || ::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == ::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) { goto success; } DO_(::google::protobuf::internal::WireFormat::SkipField( input, tag, mutable_unknown_fields())); break; } } } success: // @@protoc_insertion_point(parse_success:com.caredear.PasswordManagerRequest) return true; failure: // @@protoc_insertion_point(parse_failure:com.caredear.PasswordManagerRequest) return false; #undef DO_ } void PasswordManagerRequest::SerializeWithCachedSizes( ::google::protobuf::io::CodedOutputStream* output) const { // @@protoc_insertion_point(serialize_start:com.caredear.PasswordManagerRequest) // required .com.caredear.PasswordType type = 1; if (has_type()) { ::google::protobuf::internal::WireFormatLite::WriteEnum( 1, this->type(), output); } // required uint64 caredear_id = 2; if (has_caredear_id()) { ::google::protobuf::internal::WireFormatLite::WriteUInt64(2, this->caredear_id(), output); } // required string new_passwd = 3; if (has_new_passwd()) { ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField( this->new_passwd().data(), this->new_passwd().length(), ::google::protobuf::internal::WireFormat::SERIALIZE, "new_passwd"); ::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased( 3, this->new_passwd(), output); } // optional string old_passwd = 4; if (has_old_passwd()) { ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField( this->old_passwd().data(), this->old_passwd().length(), ::google::protobuf::internal::WireFormat::SERIALIZE, "old_passwd"); ::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased( 4, this->old_passwd(), output); } // optional string cur_token = 5; if (has_cur_token()) { ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField( this->cur_token().data(), this->cur_token().length(), ::google::protobuf::internal::WireFormat::SERIALIZE, "cur_token"); ::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased( 5, this->cur_token(), output); } if (!unknown_fields().empty()) { ::google::protobuf::internal::WireFormat::SerializeUnknownFields( unknown_fields(), output); } // @@protoc_insertion_point(serialize_end:com.caredear.PasswordManagerRequest) } ::google::protobuf::uint8* PasswordManagerRequest::SerializeWithCachedSizesToArray( ::google::protobuf::uint8* target) const { // @@protoc_insertion_point(serialize_to_array_start:com.caredear.PasswordManagerRequest) // required .com.caredear.PasswordType type = 1; if (has_type()) { target = ::google::protobuf::internal::WireFormatLite::WriteEnumToArray( 1, this->type(), target); } // required uint64 caredear_id = 2; if (has_caredear_id()) { target = ::google::protobuf::internal::WireFormatLite::WriteUInt64ToArray(2, this->caredear_id(), target); } // required string new_passwd = 3; if (has_new_passwd()) { ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField( this->new_passwd().data(), this->new_passwd().length(), ::google::protobuf::internal::WireFormat::SERIALIZE, "new_passwd"); target = ::google::protobuf::internal::WireFormatLite::WriteStringToArray( 3, this->new_passwd(), target); } // optional string old_passwd = 4; if (has_old_passwd()) { ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField( this->old_passwd().data(), this->old_passwd().length(), ::google::protobuf::internal::WireFormat::SERIALIZE, "old_passwd"); target = ::google::protobuf::internal::WireFormatLite::WriteStringToArray( 4, this->old_passwd(), target); } // optional string cur_token = 5; if (has_cur_token()) { ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField( this->cur_token().data(), this->cur_token().length(), ::google::protobuf::internal::WireFormat::SERIALIZE, "cur_token"); target = ::google::protobuf::internal::WireFormatLite::WriteStringToArray( 5, this->cur_token(), target); } if (!unknown_fields().empty()) { target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray( unknown_fields(), target); } // @@protoc_insertion_point(serialize_to_array_end:com.caredear.PasswordManagerRequest) return target; } int PasswordManagerRequest::ByteSize() const { int total_size = 0; if (_has_bits_[0 / 32] & (0xffu << (0 % 32))) { // required .com.caredear.PasswordType type = 1; if (has_type()) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::EnumSize(this->type()); } // required uint64 caredear_id = 2; if (has_caredear_id()) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::UInt64Size( this->caredear_id()); } // required string new_passwd = 3; if (has_new_passwd()) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::StringSize( this->new_passwd()); } // optional string old_passwd = 4; if (has_old_passwd()) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::StringSize( this->old_passwd()); } // optional string cur_token = 5; if (has_cur_token()) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::StringSize( this->cur_token()); } } 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 PasswordManagerRequest::MergeFrom(const ::google::protobuf::Message& from) { GOOGLE_CHECK_NE(&from, this); const PasswordManagerRequest* source = ::google::protobuf::internal::dynamic_cast_if_available<const PasswordManagerRequest*>( &from); if (source == NULL) { ::google::protobuf::internal::ReflectionOps::Merge(from, this); } else { MergeFrom(*source); } } void PasswordManagerRequest::MergeFrom(const PasswordManagerRequest& from) { GOOGLE_CHECK_NE(&from, this); if (from._has_bits_[0 / 32] & (0xffu << (0 % 32))) { if (from.has_type()) { set_type(from.type()); } if (from.has_caredear_id()) { set_caredear_id(from.caredear_id()); } if (from.has_new_passwd()) { set_new_passwd(from.new_passwd()); } if (from.has_old_passwd()) { set_old_passwd(from.old_passwd()); } if (from.has_cur_token()) { set_cur_token(from.cur_token()); } } mutable_unknown_fields()->MergeFrom(from.unknown_fields()); } void PasswordManagerRequest::CopyFrom(const ::google::protobuf::Message& from) { if (&from == this) return; Clear(); MergeFrom(from); } void PasswordManagerRequest::CopyFrom(const PasswordManagerRequest& from) { if (&from == this) return; Clear(); MergeFrom(from); } bool PasswordManagerRequest::IsInitialized() const { if ((_has_bits_[0] & 0x00000007) != 0x00000007) return false; return true; } void PasswordManagerRequest::Swap(PasswordManagerRequest* other) { if (other != this) { std::swap(type_, other->type_); std::swap(caredear_id_, other->caredear_id_); std::swap(new_passwd_, other->new_passwd_); std::swap(old_passwd_, other->old_passwd_); std::swap(cur_token_, other->cur_token_); 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 PasswordManagerRequest::GetMetadata() const { protobuf_AssignDescriptorsOnce(); ::google::protobuf::Metadata metadata; metadata.descriptor = PasswordManagerRequest_descriptor_; metadata.reflection = PasswordManagerRequest_reflection_; return metadata; } // =================================================================== #ifndef _MSC_VER const int PasswordManagerResponse::kResultCodeFieldNumber; const int PasswordManagerResponse::kExtraMsgFieldNumber; #endif // !_MSC_VER PasswordManagerResponse::PasswordManagerResponse() : ::google::protobuf::Message() { SharedCtor(); // @@protoc_insertion_point(constructor:com.caredear.PasswordManagerResponse) } void PasswordManagerResponse::InitAsDefaultInstance() { } PasswordManagerResponse::PasswordManagerResponse(const PasswordManagerResponse& from) : ::google::protobuf::Message() { SharedCtor(); MergeFrom(from); // @@protoc_insertion_point(copy_constructor:com.caredear.PasswordManagerResponse) } void PasswordManagerResponse::SharedCtor() { ::google::protobuf::internal::GetEmptyString(); _cached_size_ = 0; result_code_ = 0; extra_msg_ = const_cast< ::std::string*>(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); ::memset(_has_bits_, 0, sizeof(_has_bits_)); } PasswordManagerResponse::~PasswordManagerResponse() { // @@protoc_insertion_point(destructor:com.caredear.PasswordManagerResponse) SharedDtor(); } void PasswordManagerResponse::SharedDtor() { if (extra_msg_ != &::google::protobuf::internal::GetEmptyStringAlreadyInited()) { delete extra_msg_; } if (this != default_instance_) { } } void PasswordManagerResponse::SetCachedSize(int size) const { GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); _cached_size_ = size; GOOGLE_SAFE_CONCURRENT_WRITES_END(); } const ::google::protobuf::Descriptor* PasswordManagerResponse::descriptor() { protobuf_AssignDescriptorsOnce(); return PasswordManagerResponse_descriptor_; } const PasswordManagerResponse& PasswordManagerResponse::default_instance() { if (default_instance_ == NULL) protobuf_AddDesc_PasswordManager_2eproto(); return *default_instance_; } PasswordManagerResponse* PasswordManagerResponse::default_instance_ = NULL; PasswordManagerResponse* PasswordManagerResponse::New() const { return new PasswordManagerResponse; } void PasswordManagerResponse::Clear() { if (_has_bits_[0 / 32] & 3) { result_code_ = 0; if (has_extra_msg()) { if (extra_msg_ != &::google::protobuf::internal::GetEmptyStringAlreadyInited()) { extra_msg_->clear(); } } } ::memset(_has_bits_, 0, sizeof(_has_bits_)); mutable_unknown_fields()->Clear(); } bool PasswordManagerResponse::MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input) { #define DO_(EXPRESSION) if (!(EXPRESSION)) goto failure ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:com.caredear.PasswordManagerResponse) for (;;) { ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoff(127); tag = p.first; if (!p.second) goto handle_unusual; switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { // required int32 result_code = 1; case 1: { if (tag == 8) { DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< ::google::protobuf::int32, ::google::protobuf::internal::WireFormatLite::TYPE_INT32>( input, &result_code_))); set_has_result_code(); } else { goto handle_unusual; } if (input->ExpectTag(18)) goto parse_extra_msg; break; } // optional string extra_msg = 2; case 2: { if (tag == 18) { parse_extra_msg: DO_(::google::protobuf::internal::WireFormatLite::ReadString( input, this->mutable_extra_msg())); ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField( this->extra_msg().data(), this->extra_msg().length(), ::google::protobuf::internal::WireFormat::PARSE, "extra_msg"); } else { goto handle_unusual; } if (input->ExpectAtEnd()) goto success; break; } default: { handle_unusual: if (tag == 0 || ::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == ::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) { goto success; } DO_(::google::protobuf::internal::WireFormat::SkipField( input, tag, mutable_unknown_fields())); break; } } } success: // @@protoc_insertion_point(parse_success:com.caredear.PasswordManagerResponse) return true; failure: // @@protoc_insertion_point(parse_failure:com.caredear.PasswordManagerResponse) return false; #undef DO_ } void PasswordManagerResponse::SerializeWithCachedSizes( ::google::protobuf::io::CodedOutputStream* output) const { // @@protoc_insertion_point(serialize_start:com.caredear.PasswordManagerResponse) // required int32 result_code = 1; if (has_result_code()) { ::google::protobuf::internal::WireFormatLite::WriteInt32(1, this->result_code(), output); } // optional string extra_msg = 2; if (has_extra_msg()) { ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField( this->extra_msg().data(), this->extra_msg().length(), ::google::protobuf::internal::WireFormat::SERIALIZE, "extra_msg"); ::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased( 2, this->extra_msg(), output); } if (!unknown_fields().empty()) { ::google::protobuf::internal::WireFormat::SerializeUnknownFields( unknown_fields(), output); } // @@protoc_insertion_point(serialize_end:com.caredear.PasswordManagerResponse) } ::google::protobuf::uint8* PasswordManagerResponse::SerializeWithCachedSizesToArray( ::google::protobuf::uint8* target) const { // @@protoc_insertion_point(serialize_to_array_start:com.caredear.PasswordManagerResponse) // required int32 result_code = 1; if (has_result_code()) { target = ::google::protobuf::internal::WireFormatLite::WriteInt32ToArray(1, this->result_code(), target); } // optional string extra_msg = 2; if (has_extra_msg()) { ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField( this->extra_msg().data(), this->extra_msg().length(), ::google::protobuf::internal::WireFormat::SERIALIZE, "extra_msg"); target = ::google::protobuf::internal::WireFormatLite::WriteStringToArray( 2, this->extra_msg(), target); } if (!unknown_fields().empty()) { target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray( unknown_fields(), target); } // @@protoc_insertion_point(serialize_to_array_end:com.caredear.PasswordManagerResponse) return target; } int PasswordManagerResponse::ByteSize() const { int total_size = 0; if (_has_bits_[0 / 32] & (0xffu << (0 % 32))) { // required int32 result_code = 1; if (has_result_code()) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::Int32Size( this->result_code()); } // optional string extra_msg = 2; if (has_extra_msg()) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::StringSize( this->extra_msg()); } } 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 PasswordManagerResponse::MergeFrom(const ::google::protobuf::Message& from) { GOOGLE_CHECK_NE(&from, this); const PasswordManagerResponse* source = ::google::protobuf::internal::dynamic_cast_if_available<const PasswordManagerResponse*>( &from); if (source == NULL) { ::google::protobuf::internal::ReflectionOps::Merge(from, this); } else { MergeFrom(*source); } } void PasswordManagerResponse::MergeFrom(const PasswordManagerResponse& from) { GOOGLE_CHECK_NE(&from, this); if (from._has_bits_[0 / 32] & (0xffu << (0 % 32))) { if (from.has_result_code()) { set_result_code(from.result_code()); } if (from.has_extra_msg()) { set_extra_msg(from.extra_msg()); } } mutable_unknown_fields()->MergeFrom(from.unknown_fields()); } void PasswordManagerResponse::CopyFrom(const ::google::protobuf::Message& from) { if (&from == this) return; Clear(); MergeFrom(from); } void PasswordManagerResponse::CopyFrom(const PasswordManagerResponse& from) { if (&from == this) return; Clear(); MergeFrom(from); } bool PasswordManagerResponse::IsInitialized() const { if ((_has_bits_[0] & 0x00000001) != 0x00000001) return false; return true; } void PasswordManagerResponse::Swap(PasswordManagerResponse* other) { if (other != this) { std::swap(result_code_, other->result_code_); std::swap(extra_msg_, other->extra_msg_); 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 PasswordManagerResponse::GetMetadata() const { protobuf_AssignDescriptorsOnce(); ::google::protobuf::Metadata metadata; metadata.descriptor = PasswordManagerResponse_descriptor_; metadata.reflection = PasswordManagerResponse_reflection_; return metadata; } // @@protoc_insertion_point(namespace_scope) } // namespace caredear } // namespace com // @@protoc_insertion_point(global_scope)
a34672d7f82768eb7576007c4982e416dcfe63c4
55c1b823a32cfb5df84c3c3e1e0e72d1c5d80069
/include/selectionsort.h
5c559d4f4cbad31fb9220c9c557f2b6b1c81cde7
[]
no_license
carlcherry/coding_practice
13b824680743c21807e4e5b5eb0f8b272d4fcf83
c15e94f52fea0bd61de2073c3d8508aefa042513
refs/heads/master
2020-05-30T15:11:52.973387
2019-04-22T17:33:44
2019-04-22T17:33:44
4,406,846
1
1
null
null
null
null
UTF-8
C++
false
false
389
h
selectionsort.h
/* * insertionsort.h * * Created on: 2013-01-22 * Author: carl */ #ifndef __CC_SELECTION_SORT__ #define __CC_SELECTION_SORT__ namespace cc { void testSelectionSort(); void selectionsort(int *arrayToSort, int length); void selectionsort2(int *input, int length); int findsecondlargestelement(int *arrayToSort, int length); } #endif /* __CC_SELECTION_SORT__ */
090c494232290aa7c1a859ddc207e3e4d56d2814
1993b222111223c8a9976a9b6552d68bf626d7e0
/20200514-1074.cpp
0cabbb416ec44e7a9f02d78ab9c7cc5ce962ff72
[]
no_license
mango0713/C
6ea40f6bf76a0e33ce8a331bf596aab1b33773a4
60afccd972b21f6871628fd84baeaf6a021e65ac
refs/heads/main
2022-12-29T18:46:57.047727
2020-10-13T08:22:37
2020-10-13T08:22:37
301,655,162
0
0
null
null
null
null
UTF-8
C++
false
false
160
cpp
20200514-1074.cpp
#include <stdio.h> int main (void) { char x, t='a'; scanf("%c", &x); do { printf("%c ", t); t+=1; }while(t<x +1); }
00017c8fe56bbb3179f513fe6ba6cc21e85404a0
ded789c4a7a443bf1bc0b7ccb6a34947dcf71fa2
/test/stm.cpp
59869bf27895cef643d75e9e954739d1312adfd7
[ "LicenseRef-scancode-proprietary-license", "BSL-1.0" ]
permissive
roland-wolf/HsmBase
cb2bed5f73ff8116d439ccf7ef8c021644480e93
a09b86c5e6d0fd701c1e671f35625a257a4d4b4b
refs/heads/master
2023-04-09T11:19:02.178556
2023-03-30T07:48:37
2023-03-30T07:48:37
33,789,737
2
2
BSL-1.0
2021-05-14T19:46:33
2015-04-11T19:44:20
C++
UTF-8
C++
false
false
5,404
cpp
stm.cpp
#include <iostream> #include "stm.h" //Implementation of the state machine published in //Practical UML Statecharts in C++ //Miro Samek //2nd Edition //page 88 Stm::Stm() { setRoot(&Stm::s); //define the hierarchy of states addChildState(&Stm::s, &Stm::s1); addChildState(&Stm::s, &Stm::s2); addChildState(&Stm::s1, &Stm::s11); addChildState(&Stm::s2, &Stm::s21); addChildState(&Stm::s21, &Stm::s211); //register initial transitions addInit(&Stm::s, &Stm::s11); addInit(&Stm::s1, &Stm::s11); addInit(&Stm::s2, &Stm::s211); addInit(&Stm::s21, &Stm::s211); initStatemachine(&Stm::s2, &Stm::firstInitialTransition); } //TODO: init function void Stm::firstInitialTransition(const Event *ev) { writeMessage("top-INIT"); m_foo = 0; transition(&Stm::s2); } void Stm::s(const Event *ev) { if(reason() == ROUTE){ switch(*ev){ case E: writeMessage("s-E"); transition(&Stm::s11); break; case I: if (m_foo) { writeMessage("s-I"); m_foo = 0; handled(); } break; default: break; } }else if(reason() == ENTRY){ writeMessage("s-ENTRY"); }else if(reason() == EXIT){ writeMessage("s-EXIT"); }else if(reason() == INIT) { writeMessage("s-INIT"); } } void Stm::s1(const Event *ev) { if(reason() == ROUTE){ switch(*ev){ case A: { writeMessage("s1-A"); transition(&Stm::s1); } break; case B: { writeMessage("s1-B"); transition(&Stm::s11); } break; case C: { writeMessage("s1-C"); transition(&Stm::s2); } break; case D: { if (!m_foo) { writeMessage("s1-D"); m_foo = 1; transition(&Stm::s); } break; } case F: { writeMessage("s1-F"); transition(&Stm::s211); } break; case I: { writeMessage("s1-I"); handled(); } break; default: break; } }else if(reason() == ENTRY){ writeMessage("s1-ENTRY"); }else if(reason() == EXIT){ writeMessage("s1-EXIT"); }else if(reason() == INIT){ writeMessage("s1-INIT"); } } void Stm::s11(const Event *ev) { if(reason() == ROUTE){ switch(*ev){ case D: { if (m_foo) { writeMessage("s11-D"); m_foo = 0; transition(&Stm::s1); } break; } case G: { writeMessage("s11-G"); return transition(&Stm::s211); } break; case H: { writeMessage("s11-H"); transition(&Stm::s); } break; default: break; } }else if(reason() == ENTRY){ writeMessage("s11-ENTRY"); }else if(reason() == EXIT){ writeMessage("s11-EXIT"); } } void Stm::s2(const Event *ev) { Reason theReason = reason(); if(reason() == ROUTE){ switch(*ev){ case C: { writeMessage("s2-C"); transition(&Stm::s1); } break; case F: { writeMessage("s2-F"); transition(&Stm::s11); } break; case I: { if (!m_foo) { writeMessage("s2-I"); m_foo = 1; handled(); } break; } default: break; } }else if(reason() == ENTRY){ writeMessage("s2-ENTRY"); }else if(reason() == EXIT){ writeMessage("s2-EXIT"); }else if(reason() == INIT){ writeMessage("s2-INIT"); } } void Stm::s21(const Event *ev) { if(reason() == ROUTE){ switch(*ev){ case A: { writeMessage("s21-A"); transition(&Stm::s21); break; } case B: { writeMessage("s21-B"); transition(&Stm::s211); break; } case G: { writeMessage("s21-G"); transition(&Stm::s1); break; } default: break; } }else if(reason() == ENTRY){ writeMessage("s21-ENTRY"); }else if(reason() == EXIT){ writeMessage("s21-EXIT"); }else if(reason() == INIT){ writeMessage("s21-INIT"); } } void Stm::s211(const Event *ev) { if(reason() == ROUTE){ switch(*ev){ case D: { writeMessage("s211-D"); transition(&Stm::s21); break; } case H: { writeMessage("s211-H"); transition(&Stm::s); } break; default: break; } }else if(reason() == ENTRY){ writeMessage("s211-ENTRY"); }else if(reason() == EXIT){ writeMessage("s211-EXIT"); }else if(reason() == INIT){ } } void Stm::clearAndDispatch(const Event *ev) { messages.clear(); processEvent(ev); } void Stm::writeMessage(const char *msg) { messages.add(msg); //std::cout << msg; }
e648752140a7a92617d1f7c144d8e1322150337d
c3b90a52a52d9325176fcf1d108369a0bf35578e
/training/cpp/accelerated_cpp/5/5-1/permuted_rotation.h
8f2c4143a53201fbc2cfa7f5a72b97e1e4654536
[]
no_license
all-in-one-of/studies
1b8d778f48de0f1c9b0808bd665b64fb40851a81
17cbec59098f99164f97650ae9cb7afe27e18f80
refs/heads/master
2020-06-13T15:48:55.416807
2019-08-24T08:02:58
2019-08-24T08:02:58
194,699,836
0
0
null
2019-07-01T15:33:54
2019-07-01T15:33:54
null
UTF-8
C++
false
false
295
h
permuted_rotation.h
#ifndef __Permuted_Rotations__ #define __Permuted_Rotations__ #include <vector> #include <string> struct permuted_rotation { std::vector<std::string> rotated; double f_index; }; std::vector<permuted_rotation> rotations(const std::string& s); void rotate(const std::string& s); #endif
1f1118f48d418d27db52e82698ca902345f1e1de
3f7028cc89a79582266a19acbde0d6b066a568de
/test/extensions/config_subscription/grpc/pausable_ack_queue_test.cc
e52e3a32b414f8d7fae8345888e66f25fd0340d0
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
envoyproxy/envoy
882d3c7f316bf755889fb628bee514bb2f6f66f0
72f129d273fa32f49581db3abbaf4b62e3e3703c
refs/heads/main
2023-08-31T09:20:01.278000
2023-08-31T08:58:36
2023-08-31T08:58:36
65,214,191
21,404
4,756
Apache-2.0
2023-09-14T21:56:37
2016-08-08T15:07:24
C++
UTF-8
C++
false
false
2,652
cc
pausable_ack_queue_test.cc
#include "source/extensions/config_subscription/grpc/pausable_ack_queue.h" #include "gtest/gtest.h" namespace Envoy { namespace Config { namespace { TEST(PausableAckQueueTest, TestEmpty) { PausableAckQueue p; EXPECT_EQ(0, p.size()); EXPECT_TRUE(p.empty()); } TEST(PausableAckQueueTest, TestPush) { PausableAckQueue p; p.push(UpdateAck{"bogusnonce", "bogustypeurl"}); EXPECT_EQ(1, p.size()); EXPECT_FALSE(p.empty()); EXPECT_EQ("bogusnonce", p.front().nonce_); EXPECT_EQ("bogustypeurl", p.front().type_url_); } TEST(PausableAckQueueTest, TestPop) { PausableAckQueue p; p.push(UpdateAck{"bogusnonce", "bogustypeurl"}); UpdateAck ack = p.popFront(); EXPECT_EQ(0, p.size()); EXPECT_TRUE(p.empty()); EXPECT_EQ("bogusnonce", ack.nonce_); EXPECT_EQ("bogustypeurl", ack.type_url_); } TEST(PausableAckQueueTest, TestPauseResume) { PausableAckQueue p; p.push(UpdateAck{"nonce1", "type1"}); p.push(UpdateAck{"nonce2", "type2"}); p.push(UpdateAck{"nonce3", "type1"}); p.push(UpdateAck{"nonce4", "type2"}); EXPECT_EQ(4, p.size()); EXPECT_FALSE(p.empty()); // pausing 'type1' should make it invisible to the queue p.pause("type1"); // size() doesn't honor pause state, a bit strange but this is by design EXPECT_EQ(4, p.size()); // validate that both front() and popFront() honor pause state EXPECT_EQ("nonce2", p.front().nonce_); EXPECT_EQ("type2", p.front().type_url_); // validate the above result is invariant even if we nest pauses. p.pause("type1"); EXPECT_EQ(4, p.size()); EXPECT_EQ("nonce2", p.front().nonce_); EXPECT_EQ("type2", p.front().type_url_); p.resume("type1"); EXPECT_EQ("nonce2", p.front().nonce_); EXPECT_EQ("type2", p.front().type_url_); UpdateAck ack = p.popFront(); EXPECT_EQ("nonce2", ack.nonce_); EXPECT_EQ("type2", ack.type_url_); EXPECT_EQ(3, p.size()); // validate that types come back when they're resumed p.resume("type1"); EXPECT_EQ("nonce1", p.front().nonce_); EXPECT_EQ("type1", p.front().type_url_); p.pause("type1"); EXPECT_EQ("nonce4", p.front().nonce_); EXPECT_EQ("type2", p.front().type_url_); p.popFront(); EXPECT_EQ(2, p.size()); p.pause("type2"); EXPECT_TRUE(p.empty()); // A bit strange but this is by design EXPECT_EQ(2, p.size()); p.resume("type1"); EXPECT_FALSE(p.empty()); EXPECT_EQ("nonce1", p.front().nonce_); EXPECT_EQ("type1", p.front().type_url_); p.popFront(); EXPECT_EQ("nonce3", p.front().nonce_); EXPECT_EQ("type1", p.front().type_url_); p.popFront(); EXPECT_TRUE(p.empty()); EXPECT_EQ(0, p.size()); } } // namespace } // namespace Config } // namespace Envoy
b8d5ddbf582ccb403a3c3a3b17402c44a6a7e9cd
6f1daf0280352575f21f93e85ea3dc96c44af156
/returnwindow.cpp
830bac81cb6c27ee2fd6c12e868069976067109f
[]
no_license
ZzzAmy/bookstore
09fa9698fbd17ac73734ecd347aa0bf59fad27f8
fe1c4349976889778a251ec027a44c1b9b1d5e29
refs/heads/master
2021-01-20T17:57:39.799395
2016-07-14T09:18:33
2016-07-14T09:18:33
63,223,098
0
2
null
null
null
null
UTF-8
C++
false
false
370
cpp
returnwindow.cpp
#include "returnwindow.h" #include "ui_returnwindow.h" #include "isreturn.h" returnWindow::returnWindow(QWidget *parent) : QDialog(parent), ui(new Ui::returnWindow) { ui->setupUi(this); } returnWindow::~returnWindow() { delete ui; } void returnWindow::on_pushButton_clicked() { Isreturn a; if(a.exec() == QDialog::Accepted) { } }
a668a4d8fb63984a998fa87651d1b7d1e4201862
97943eb0c1dc4d20f47b0b90a09887a5bd14e75b
/game/obstacle.cpp
40d396a59716937c6c6763f0afeface2ae2716b3
[]
no_license
Biohazard90/Project-Neo-Gemini
c304846d8ed6b0aa2edc4bde314170dff7fe083d
9d84c4023b42be5730151894b951a6ea0591686f
refs/heads/master
2021-01-21T12:06:45.832651
2013-12-11T22:37:28
2013-12-11T22:37:28
14,528,789
0
2
null
null
null
null
UTF-8
C++
false
false
1,866
cpp
obstacle.cpp
#include "obstacle.h" #include "gamebase.h" REGISTER_ENTITY_CLASS(Obstacle, obstacle); Obstacle::Obstacle() { } void Obstacle::OnSimulate(float frametime) { BaseClass::OnSimulate(frametime); if ((GetOrigin().x + GetSize().x) < Camera::GetInstance()->GetWorldMins().x) { Remove(); } } bool Obstacle::ShouldCollide(ICollidable *other) const { Entity *e = (Entity*)other; return e->IsEnemy() || e->IsPlayer() || e->IsProjectile(); } void Obstacle::OnCollision(ICollidable *other) { Entity *entity = (Entity*)other; if (entity->IsPlayer()) { Damage_t damage; damage.damage = 1; damage.inflictor = this; damage.statsInflictorName = GetEntityClassName(); damage.statsInflictorClass = GetEntityResourceClass(); entity->TakeDamage(damage); Vector2D delta = GetCollisionOrigin() - entity->GetCollisionOrigin(); TakeDamage(GetHealth(), nullptr, delta); } } void Obstacle::Init(const Resource_Obstacle_t &data) { BaseClass::Init(data); Q_ASSERT(data.materialCount > 0); this->data = data; if (data.materialCount > 0) { int index = qrand(data.materialCount - 1); Q_ASSERT(index >= 0 && index < data.materialCount); SetMaterial(data.materials[index]); } Vector2D origin = GetOrigin(); origin.x = Camera::GetInstance()->GetWorldMaxs().x + data.origin_x_offset; Teleport(origin); SetAngle(qfrand() * 360.0f); SetAngularVelocity(qlerp(qfrand(), data.angularvelocity_min, data.angularvelocity_max)); SetVelocity(Vector2D(qlerp(qfrand(), data.velocity_x_min, data.velocity_x_max), 0)); float size = qlerp(qfrand(), data.size_min, data.size_max); SetSize(Vector2D(size, size)); SetMaxHealth(qlerp(qfrand(), data.health_min, data.health_max)); }
e99c8616954eb4c8f26214c429f6dd09b3fdd56a
806735c91d9fac50ac6a0e0b44c68ac438b9ecb6
/iitk interview/night-fury/Q.cpp
5c159014449d257c940070f8cdd0f4f4ce20d154
[]
no_license
v-pratap/cp
a04119a5c42853b5ae5bb3535deaa726a23b113d
28ba7e27cd7b065800954445497642b852e20160
refs/heads/main
2023-06-05T03:46:55.685212
2021-06-28T05:56:06
2021-06-28T05:56:06
null
0
0
null
null
null
null
UTF-8
C++
false
false
947
cpp
Q.cpp
#include <bits/stdc++.h> using namespace std; // Complete the encryption function below. string encryption(string s) { string S = ""; for(auto &x:s){ if(x!=' ') S+=x; } int n = S.size(); int r,c; int root = sqrt(n); if(root*root==n) r = c = root; else{ r = root; c = root+1; } char grid[r][c]; int idx = 0; int maxr = 0,maxc = 0; for(int i = 0;i<r && idx<n;i++){ for(int j = 0;j<c && idx<n;j++){ grid[i][j] = S[idx++]; maxc = j; maxr = max(maxr,i); } } string ans = ""; for(int i = 0;i<c;i++){ for(int j = 0;j<=maxr;j++){ if(i>maxc && j==maxr) continue; ans+=grid[j][i]; } ans+=' '; } return ans; } int main() { string s; getline(cin, s); string result = encryption(s); cout << result << "\n"; return 0; }
8f936091328396e54953a445e05f48eb583d25a6
d35d86a90eb171ccd4ae8a3c9b0ffdeadb0165ed
/src/LineSegment.h
90ae48d3d9293f5d1b30c7aad22e6393989c8cf9
[]
no_license
fosterkong/terrainExploration
f7aa033cd79b5e10f17534899b81b0534d65b9ef
a2d4fa9392acc43355218b0af5add0d229150c9a
refs/heads/master
2021-12-05T20:44:15.433154
2015-08-24T14:40:18
2015-08-24T14:40:18
null
0
0
null
null
null
null
UTF-8
C++
false
false
545
h
LineSegment.h
#ifndef LINE_SEGMENT_H #define LINE_SEGMENT_H #include "Vector.h" #include "NodeLineSegment.h" class CLineSegment { public: CVector a,b; CLineSegment(){} CLineSegment(CVector _a, CVector _b) : a(_a), b(_b) {} CLineSegment(const CNodeLineSegment &_nls) : a(_nls.up->position), b(_nls.down->position) {} CVector MiddlePoint() const; double Lenght() const; void Set(const CNodeLineSegment &_nls) { a=_nls.up->position; b=_nls.down->position; } void Set(CVector _a, CVector _b){ a=_a; b=_b; } void Draw(); }; #endif
4857e66e19ebc0372acb323bdc373844730f449a
cb7ac15343e3b38303334f060cf658e87946c951
/source/runtime/RenderCore/ShaderCache.h
ec0eb4a41c871ad268be4827fab312a7a30de242
[]
no_license
523793658/Air2.0
ac07e33273454442936ce2174010ecd287888757
9e04d3729a9ce1ee214b58c2296188ec8bf69057
refs/heads/master
2021-11-10T16:08:51.077092
2021-11-04T13:11:59
2021-11-04T13:11:59
178,317,006
1
0
null
null
null
null
UTF-8
C++
false
false
108
h
ShaderCache.h
#pragma once #include "ShaderCoreConfig.h" namespace Air { ///class SHADER_CORE_API ShaderCache : public }
dd574d733bc3c497593ce64399f2dcae63feb7d9
9540b4cbac0ef7ac7b33260e7d2289afab93bbad
/agent-server/task/agentQueryTask.h
459dbc550fd22d7b76d52f6f83a896ba6889062f
[]
no_license
xuchuG/agent
b658469d4c7077c86d46116ff5c868e3cd3905be
708efacce66cd6464948f5011cdddc314de1e693
refs/heads/master
2021-09-05T21:09:16.922318
2018-01-31T02:22:04
2018-01-31T02:22:04
117,307,135
1
0
null
null
null
null
UTF-8
C++
false
false
414
h
agentQueryTask.h
#ifndef AGENTQUERYTASK_H_ #define AGENTQUERYTASK_H_ #include "agentBehaviorTask.h" #include "../communicationModule/epoll/tcpEpoller.h" #include "../tableManage/agentState.h" class AgentQueryTask : public AgentBehaviorTask { private: TcpEpoller * tcp_epoller; public: AgentQueryTask(TcpEpoller * ptr) { tcp_epoller = ptr; } ~AgentQueryTask(){} virtual void run(); }; #endif
c30fc02208200b4a97811cb9de22f55bf8a45a55
e8b3391e925cf5c5e4b434c01eb5b2e2c20298f1
/stack.hh
2a879555f0eb856f7c25115ce28e619170533495
[]
no_license
farnir/syntax
14aaf43a01b208e489e0e42d91bfedf5eb2ea2e2
d2fc0e291b3cecaba541862dbb661edd7c493c2e
refs/heads/master
2020-06-01T17:08:33.555033
2019-06-09T16:00:08
2019-06-09T16:00:08
190,860,334
0
0
null
null
null
null
UTF-8
C++
false
false
561
hh
stack.hh
// // Created by daze on 08/06/19. // #ifndef SYNTAX_STACK_HH #define SYNTAX_STACK_HH #include <iostream> #include <queue> #include "symbol.hh" class Stack { private: std::string _str; // String corresponding to the input file std::deque<std::string> _queue; // Queue representing the stack acting as a LiFo TableSymbol _table; // Object containing all the symbols void split(std::string str); // Function used to split and push into the stack public: Stack(std::string str); bool loop(); // Main loop }; #endif //SYNTAX_STACK_HH