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
e0a2beb866525c8933bfacc8c5bfc3fd3f8b169b
7fa689caaeea36783b31bc0ca6da36ea5adaf262
/cxx/tests/test_hirm_animals.cc
05407e3c6e756a3be666c08e36224cf424fb4520
[ "Apache-2.0" ]
permissive
probsys/hierarchical-irm
28aaa44d38d7d61a538c637f6e45fb70ef39b96c
042aaea56d66d05c4c54848353696ca60c692581
refs/heads/master
2023-07-11T02:55:35.492135
2021-06-18T21:32:14
2021-06-18T21:32:14
null
0
0
null
null
null
null
UTF-8
C++
false
false
5,751
cc
test_hirm_animals.cc
// Copyright 2021 MIT Probabilistic Computing Project // Apache License, Version 2.0, refer to LICENSE.txt #include <cassert> #include <random> #include "hirm.hh" #include "util_hash.hh" #include "util_io.hh" #include "util_math.hh" int main(int argc, char **argv) { srand(1); PRNG prng (1); string path_base = "assets/animals.unary"; auto path_schema = path_base + ".schema"; auto path_obs = path_base + ".obs"; printf("== HIRM == \n"); auto schema_unary = load_schema(path_schema); auto observations_unary = load_observations(path_obs); auto encoding_unary = encode_observations(schema_unary, observations_unary); HIRM hirm (schema_unary, &prng); incorporate_observations(hirm, encoding_unary, observations_unary); int n_obs_unary = 0; for (const auto &[z, irm] : hirm.irms) { for (const auto &[r, relation] : irm->relations) { n_obs_unary += relation->data.size(); } } assert(n_obs_unary == observations_unary.size()); hirm.transition_cluster_assignments_all(); hirm.transition_cluster_assignments_all(); hirm.set_cluster_assignment_gibbs("solitary", 120); hirm.set_cluster_assignment_gibbs("water", 741); for (int i = 0; i < 20; i++) { hirm.transition_cluster_assignments_all(); for (const auto &[t, irm] : hirm.irms) { irm->transition_cluster_assignments_all(); for (const auto &[d, domain] : irm->domains) { domain->crp.transition_alpha(); } } hirm.crp.transition_alpha(); printf("%d %f [", i, hirm.logp_score()); for (const auto &[t, customers] : hirm.crp.tables) { printf("%ld ", customers.size()); } printf("]\n"); } // TODO: Removing the relation causes solitary to have no observations, // which causes the serialization test. Instead, we need a // to_txt_dataset([relation | irm | hirm]) which writes the latest // dataset to disk and is used upon reloading the data. // hirm.remove_relation("solitary"); // hirm.transition_cluster_assignments_all(); // hirm.add_relation("solitary", {"animal"}); // hirm.transition_cluster_assignments_all(); string path_clusters = path_base + ".hirm"; to_txt(path_clusters, hirm, encoding_unary); auto &enc = std::get<0>(encoding_unary); // Marginally normalized. int persiancat = enc["animal"]["persiancat"]; auto p0_black_persiancat = hirm.logp({{"black", {persiancat}, 0.}}); auto p1_black_persiancat = hirm.logp({{"black", {persiancat}, 1.}}); assert(abs(logsumexp({p0_black_persiancat, p1_black_persiancat})) < 1e-10); // Marginally normalized. int sheep = enc["animal"]["sheep"]; auto p0_solitary_sheep = hirm.logp({{"solitary", {sheep}, 0.}}); auto p1_solitary_sheep = hirm.logp({{"solitary", {sheep}, 1.}}); assert(abs(logsumexp({p0_solitary_sheep, p1_solitary_sheep})) < 1e-10); // Jointly normalized. auto p00_black_persiancat_solitary_sheep = hirm.logp( {{"black", {persiancat}, 0.}, {"solitary", {sheep}, 0.}}); auto p01_black_persiancat_solitary_sheep = hirm.logp( {{"black", {persiancat}, 0.}, {"solitary", {sheep}, 1.}}); auto p10_black_persiancat_solitary_sheep = hirm.logp( {{"black", {persiancat}, 1.}, {"solitary", {sheep}, 0.}}); auto p11_black_persiancat_solitary_sheep = hirm.logp( {{"black", {persiancat}, 1.}, {"solitary", {sheep}, 1.}}); auto Z = logsumexp({ p00_black_persiancat_solitary_sheep, p01_black_persiancat_solitary_sheep, p10_black_persiancat_solitary_sheep, p11_black_persiancat_solitary_sheep, }); assert(abs(Z) < 1e-10); // Independence assert(abs(p00_black_persiancat_solitary_sheep - (p0_black_persiancat + p0_solitary_sheep)) < 1e-8); assert(abs(p01_black_persiancat_solitary_sheep - (p0_black_persiancat + p1_solitary_sheep)) < 1e-8); assert(abs(p10_black_persiancat_solitary_sheep - (p1_black_persiancat + p0_solitary_sheep)) < 1e-8); assert(abs(p11_black_persiancat_solitary_sheep - (p1_black_persiancat + p1_solitary_sheep)) < 1e-8); // Load the clusters. HIRM hirx ({}, &prng); from_txt(&hirx, path_schema, path_obs, path_clusters); assert(hirm.irms.size() == hirx.irms.size()); // Check IRMs agree. for (const auto &[table, irm] : hirm.irms) { auto irx = hirx.irms.at(table); // Check log scores agree. for (const auto &[d, dm] : irm->domains) { auto dx = irx->domains.at(d); dx->crp.alpha = dm->crp.alpha; } assert(abs(irx->logp_score() - irm->logp_score()) < 1e-8); // Check domains agree. for (const auto &[d, dm] : irm->domains) { auto dx = irx->domains.at(d); assert(dm->items == dx->items); assert(dm->crp.assignments == dx->crp.assignments); assert(dm->crp.tables == dx->crp.tables); assert(dm->crp.N == dx->crp.N); assert(dm->crp.alpha == dx->crp.alpha); } // Check relations agree. for (const auto &[r, rm] : irm->relations) { auto rx = irx->relations.at(r); assert(rm->data == rx->data); assert(rm->data_r == rx->data_r); assert(rm->clusters.size() == rx->clusters.size()); for (const auto &[z, clusterm] : rm->clusters) { auto clusterx = rx->clusters.at(z); assert(clusterm->N == clusterx->N); } } } hirx.crp.alpha = hirm.crp.alpha; assert(abs(hirx.logp_score() - hirm.logp_score()) < 1e-8); }
c8232abe7b5e684b32c34173c541020553334eb0
02a0312af0a33329bf8d54560bfb4f81d2ce9255
/P6/SDLProject/SDLProject/Scenes/Dungeon.cpp
5e5757537004d1a7155af0580e6297b95b6ba8b8
[]
no_license
fk798/CS-UY-3113
d663c258f5ac1b5b8a64ff26b2acdb6fdce93a6a
cb8ecbb2fb0ea9e1c71c47fb64bdad3d78ec003f
refs/heads/main
2023-04-21T03:29:43.440485
2021-05-13T02:46:30
2021-05-13T02:46:30
330,031,193
0
0
null
null
null
null
UTF-8
C++
false
false
3,431
cpp
Dungeon.cpp
#include "Dungeon.h" #define DUNGEON_WIDTH 10 #define DUNGEON_HEIGHT 10 #define DUNGEON_ENEMY_COUNT 1 using namespace std; void Dungeon::Initialize(Entity *player) { state.nextScene = -1; GLuint mapTextureID = Util::LoadTexture("medieval_tilesheet_2X.png"); state.map = new Map(DUNGEON_WIDTH, DUNGEON_HEIGHT, dungeon_data, mapTextureID, 1.0f, 24, 14); // Initialize Player state.player = player; state.enemies = new Entity[DUNGEON_ENEMY_COUNT]; GLuint enemyTextureID = Util::LoadTexture("knight.png"); state.enemies[0].entityType = ENEMY; state.enemies[0].textureID = enemyTextureID; state.enemies[0].position = glm::vec3(5, -3.0f, 0); state.enemies[0].speed = 1; state.enemies[0].aiType = WAITANDGO; state.enemies[0].aiState = IDLE; //state.enemies[0].jumpPower = 5.0f; //state.enemies[0].acceleration = glm::vec3(0, 0, 0); /* state.enemies[1].entityType = ENEMY; state.enemies[1].textureID = enemyTextureID; state.enemies[1].position = glm::vec3(11, 0.0f, 0); state.enemies[1].speed = 1; state.enemies[1].aiType = WAITANDGO; state.enemies[1].aiState = IDLE; //state.enemies[1].jumpPower = 5.0f; state.enemies[1].acceleration = glm::vec3(0, 0, 0);*/ for (int i = 0; i < DUNGEON_ENEMY_COUNT; ++i) { state.enemies[i].isActive = true; } } void Dungeon::Update(float deltaTime) { state.player->Update(deltaTime, state.player, state.enemies, DUNGEON_ENEMY_COUNT, state.map); for (int i = 0; i < DUNGEON_ENEMY_COUNT; ++i) { state.enemies[i].Update(deltaTime, state.player, state.enemies, DUNGEON_ENEMY_COUNT, state.map); } if (state.player->resetLocation == true) { state.player->resetLocation = false; state.player->numLives -= 1; state.nextScene = 2; state.player->position = glm::vec3(7, -10, 0); } if (state.player->numLives == 0) { state.nextScene = 0; } bool anyAlive = false; for (int i = 0; i < DUNGEON_ENEMY_COUNT; ++i) { if (state.enemies[i].isActive == true) { anyAlive = true; break; } } //cout << "X: " << state.player->position.x << endl; //cout << "Y: " << state.player->position.y << endl; // touches key part if (dungeon_data[25] != 208 && (state.player->position.x >= 4 && state.player->position.x < 6) && (state.player->position.y <= -1 && state.player->position.y >= -3)) { state.player->numDungeonsCleared += 1; //cout << "Number of Key Parts = " << state.player->numDungeonsCleared << endl; dungeon_data[24] = 208; dungeon_data[25] = 208; state.enemies[0].newPosition = state.enemies[0].position; state.nextScene = state.player->currentSceneNum; state.enemies[0].position = state.enemies[0].newPosition; } // exiting dungeon if ((state.player->position.x >= 4 && state.player->position.x <= 7) && (state.player->position.y <= -8 && state.player->position.y >= -10)) { state.nextScene = 2; state.player->position.x = state.player->newPosition.x; state.player->position.y = state.player->newPosition.y; } } void Dungeon::Render(ShaderProgram *program) { state.map->Render(program); state.player->Render(program); for (int i = 0; i < DUNGEON_ENEMY_COUNT; ++i) { state.enemies[i].Render(program); } }
6d3223f20d934841479c75bc1a02d65b2cd5657c
08cf73a95743dc3036af0f31a00c7786a030d7c0
/Editor source/OtE/menus/SinglePlayerMenu.h
1e0f81106d08ef08006bc967c99f33e4bf1958d5
[ "MIT" ]
permissive
errantti/ontheedge-editor
a0779777492b47f4425d6155e831df549f83d4c9
678d2886d068351d7fdd68927b272e75da687484
refs/heads/main
2023-03-04T02:52:36.538407
2021-01-23T19:42:22
2021-01-23T19:42:22
332,293,357
0
0
null
null
null
null
ISO-8859-1
C++
false
false
1,256
h
SinglePlayerMenu.h
/********************************* * * On the Edge * Copyright (2005) Azuris Productions * Jukka Tykkyläinen & Ismo Huhtiniemi * http://koti.mbnet.fi/jtykky * * SinglePlayerMenu - handles single player (ship selection) * menu functionalities and inizialiting * *********************************/ #ifndef __CSINGLEPLAYERMENU_H__ #define __CSINGLEPLAYERMENU_H__ #include "IMenu.h" enum SINGLEPLAYER_MENU_ELEMENTS { SING_BG = 500, SING_CLOSE, SING_PLAY, SING_SHIP, SING_LEFT, SING_RIGHT, SING_DETAILS, SING_COUNT }; class CSinglePlayerMenu : public IMenu { public: CSinglePlayerMenu(IMenuManager *mgr); ~CSinglePlayerMenu(); bool RemoveMenuElements(); bool InitializeMenu(CGUIEnvironment *env); bool OnEvent(SEvent event); inline void SetShipDetails(int shipIndex, string details) {m_shipDetails[shipIndex] = details;} inline void SetShipIcon(int shipIndex, string filename) {m_shipIcon[shipIndex] = filename;} inline void SetShipID(int shipIndex, long ID) {m_shipIDs[shipIndex] = ID;} virtual void Update(); private: void UpdateShipIcon(); int m_selectedShip; string m_shipIcon[4]; string m_shipDetails[4]; long m_shipIDs[4]; CTexture *m_ships[4]; bool m_bEscDown; }; #endif // #ifndef __CSINGLEPLAYERMENU_H__
ea32369499cdcf6632c1580d97c39292e9031c92
87bd32c1dcfc98c09491e8c720d7d1ba70016a37
/Classes/Pocket.cpp
cf78ad4a7c1e3e4b1f39d0f2f4be719723fde831
[ "MIT" ]
permissive
sue602/skynet_cocos2d-x_network
78a469d5de701958e675e06bad02586de2cbd6fb
0ff00d7843fb70e1187065632697761018502f74
refs/heads/master
2021-01-18T08:38:57.627955
2016-01-15T11:15:47
2016-01-15T11:15:47
50,024,840
0
1
null
2016-01-20T11:09:18
2016-01-20T11:09:18
null
UTF-8
C++
false
false
162
cpp
Pocket.cpp
#include "Pocket.h" //#include "Util.h" Pocket::Pocket():length(0),version(0),id(0),msg(NULL){ } Pocket::~Pocket() { if (msg != NULL) { delete[] msg; } }
9b15bca11f7a3bc348bfc60466ed1b870e6305b2
98f9f977a39843e5f7719062f43011ebfd169e42
/Libs/Widgets/ctkPushButton.h
9e091ae0fd64ded31d10825b1dba46729c1f3192
[ "LicenseRef-scancode-unknown-license-reference", "Apache-2.0", "LicenseRef-scancode-warranty-disclaimer" ]
permissive
txdy077345/CTK
71cab2d77193d09340afe7a50e5dddc3ea66a06d
7cd253376139ea73f0450e1bad75bab41aa1b507
refs/heads/master
2023-05-27T19:20:21.825916
2023-04-29T16:35:03
2023-04-29T16:35:03
276,658,777
1
0
Apache-2.0
2020-07-02T13:50:30
2020-07-02T13:50:29
null
UTF-8
C++
false
false
3,245
h
ctkPushButton.h
/*========================================================================= Library: CTK Copyright (c) Kitware Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.txt Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. =========================================================================*/ #ifndef __ctkPushButton_h #define __ctkPushButton_h // Qt includes #include <QPushButton> // CTK includes #include <ctkPimpl.h> #include "ctkWidgetsExport.h" class ctkPushButtonPrivate; /// \ingroup Widgets /// Description /// ctkPushButton is for displaying a QPushButton with an icon and optionally elided text. /// Alignment of the text and the icon is highly customizable. class CTK_WIDGETS_EXPORT ctkPushButton : public QPushButton { Q_OBJECT /// Set the alignment of the text on the button, /// Qt::AlignHCenter|Qt::AlignVCenter by default. /// \sa textAlignment(), setTextAlignment(), iconAlignment Q_PROPERTY(Qt::Alignment buttonTextAlignment READ buttonTextAlignment WRITE setButtonTextAlignment) /// Set the alignment of the icon with regard to the text. /// Qt::AlignLeft|Qt::AlignVCenter by default. /// \sa iconAlignment(), setIconAlignment(), textAlignment Q_PROPERTY(Qt::Alignment iconAlignment READ iconAlignment WRITE setIconAlignment) /// Set the shortening of the button text by eliding. /// Qt::ElideNone by default. /// \sa elideMode(), setElideMode() Q_PROPERTY(Qt::TextElideMode elideMode READ elideMode WRITE setElideMode) public: ctkPushButton(QWidget *parent = 0); ctkPushButton(const QString& text, QWidget *parent = 0); ctkPushButton(const QIcon& icon, const QString& text, QWidget *parent = 0); virtual ~ctkPushButton(); /// Set the buttonTextAlignment property value. /// \sa buttonTextAlignment void setButtonTextAlignment(Qt::Alignment buttonTextAlignment); /// Return the buttonTextAlignment property value. /// \sa buttonTextAlignment Qt::Alignment buttonTextAlignment()const; /// Set the iconAlignment property value. /// \sa iconAlignment void setIconAlignment(Qt::Alignment iconAlignment); /// Return the iconAlignment property value. /// \sa iconAlignment Qt::Alignment iconAlignment()const; virtual QSize minimumSizeHint()const; virtual QSize sizeHint()const; /// setElideMode can shorten the text displayed on the button. /// Qt::ElideNone by default (same as for a regular push button). void setElideMode(Qt::TextElideMode newMode); Qt::TextElideMode elideMode()const; protected: /// Reimplemented for internal reasons virtual void paintEvent(QPaintEvent*); protected: QScopedPointer<ctkPushButtonPrivate> d_ptr; ctkPushButton(ctkPushButtonPrivate*, QWidget* parent = 0); private: Q_DECLARE_PRIVATE(ctkPushButton); Q_DISABLE_COPY(ctkPushButton); }; #endif
998b778a6d117b9023972039d861e1008b11df05
a253ccb9df6064847e0ca092144684bbecbc8af4
/Rectangle.h
4b178585c2f2281cfd40e9b112dea825c1cc675d
[]
no_license
Oberon222/Polimorphism-Shape
3c84f3dc3dca321f2bc48408dd114cb9a12c4d49
8632aebb45b95dd0427891c566a9d4fa2e66274d
refs/heads/master
2022-11-11T13:58:20.774305
2020-06-28T13:25:48
2020-06-28T13:25:48
275,589,952
0
0
null
null
null
null
UTF-8
C++
false
false
1,772
h
Rectangle.h
#pragma once #include<iostream> #include <fstream> #include"Shape.h" using namespace std; class Rectangle : public Shape { int rectangleLeftCornerX; int rectangleLeftCornerY; int rectangleLength; int rectangleHeight; public: Rectangle() : rectangleLeftCornerX(0), rectangleLeftCornerY(0), rectangleLength(0), rectangleHeight(0) { } Rectangle(int rectangleLeftCornerX, int rectangleLeftCornerY, int rectangleLength, int rectangleHeight) : rectangleLeftCornerX(rectangleLeftCornerX), rectangleLeftCornerY(rectangleLeftCornerY), rectangleLength(rectangleLength), rectangleHeight(rectangleHeight) { } virtual void Show()const { cout << "The X coordinate of the left corner of the rectangle: " << rectangleLeftCornerX << endl; cout << "The Y coordinate of the left corner of the rectangle: " << rectangleLeftCornerY << endl; cout << "The length of the rectangle: " << rectangleLength << endl; cout << "The height of the rectangle: " << rectangleHeight << endl; } virtual void Save()const { ofstream fout; fout.open("Rectangle.txt"); bool isOpen = fout.is_open(); if (!isOpen) cout << "Error!" << endl; fout<< "The X coordinate of the left corner of the rectangle: " << rectangleLeftCornerX << endl; fout<< "The Y coordinate of the left corner of the rectangle: " << rectangleLeftCornerY << endl; fout<< "The length of the rectangle: " << rectangleLength << endl; fout<< "The height of the rectangle: " << rectangleHeight << endl; fout.close(); } virtual void Load() { ifstream fin; fin.open("Rectangle.txt"); if (!fin.is_open()) cout << "Error!" << endl; Rectangle tmp; fin >> tmp.rectangleLeftCornerX; fin >> tmp.rectangleLeftCornerY; fin >> tmp.rectangleLength; fin >> tmp.rectangleHeight; fin.close(); } };
a613d53f67bb4378d14beca35c3ef853bbf327e0
ae5e633003f23b107350e640d8e21e6e61f6b097
/unit_tests/gtest_string_iterator.cpp
6d16660bdd0ea6cf0c80507d037238481c58300b
[ "MIT" ]
permissive
nCine/nCine
6a723f0a26d53fd5d1f6694ad244122cbcdbe4e0
d80f0e651be8981fde21ddccbc8a695b7a738727
refs/heads/master
2023-07-20T02:43:48.931548
2023-07-10T20:59:49
2023-07-10T20:59:49
189,073,851
954
70
MIT
2021-06-30T16:55:45
2019-05-28T17:31:43
C++
UTF-8
C++
false
false
3,843
cpp
gtest_string_iterator.cpp
#include "gtest_string.h" namespace { class StringIteratorTest : public ::testing::Test { public: StringIteratorTest() : string_(Capacity) {} protected: void SetUp() override { string_ = "String1String2"; } nctl::String string_; }; TEST_F(StringIteratorTest, ForLoopIteration) { unsigned int n = 0; printf("Iterating through string characters with for loop:"); for (nctl::String::ConstIterator i = string_.begin(); i != string_.end(); ++i) { printf(" %c", *i); ASSERT_EQ(*i, string_[n++]); } printf("\n"); } TEST_F(StringIteratorTest, ForRangeIteration) { unsigned int n = 0; printf("Iterating through string characters with range-based for:"); for (char i : string_) { printf(" %c", i); ASSERT_EQ(i, string_[n++]); } printf("\n"); } TEST_F(StringIteratorTest, ForLoopEmptyIteration) { nctl::String newString(Capacity); printf("Iterating over an empty string with for loop:\n"); for (nctl::String::ConstIterator i = newString.begin(); i != newString.end(); ++i) ASSERT_TRUE(false); // should never reach this point printf("\n"); } TEST_F(StringIteratorTest, ForRangeEmptyIteration) { nctl::String newString(Capacity); printf("Iterating over an empty string with range-based for:\n"); for (char i : newString) ASSERT_TRUE(false); // should never reach this point printf("\n"); } TEST_F(StringIteratorTest, WhileLoopIteration) { unsigned int n = 0; printf("Iterating through string characters with while loop:"); nctl::String::ConstIterator i = string_.begin(); while (i != string_.end()) { printf(" %c", *i); ASSERT_EQ(*i, string_[n]); ++i; ++n; } printf("\n"); } TEST_F(StringIteratorTest, WhileLoopEmptyIteration) { nctl::String newString(Capacity); printf("Iterating over an empty string with while loop:\n"); nctl::String::ConstIterator i = newString.begin(); while (i != newString.end()) { ASSERT_TRUE(false); // should never reach this point ++i; } printf("\n"); } TEST_F(StringIteratorTest, AddIndexToIterator) { nctl::String::ConstIterator it = string_.begin(); printf("Accessing characters with an iterator and a positive index\n"); for (int i = 0; i < static_cast<int>(string_.length()); i++) { printf(" %c", *(it + i)); ASSERT_EQ(*(it + i), string_[i]); } printf("\n"); } TEST_F(StringIteratorTest, AddIndexToIteratorInPlace) { printf("Accessing characters with an iterator and a positive index\n"); for (int i = 0; i < static_cast<int>(string_.length()); i++) { nctl::String::ConstIterator it = string_.begin(); it += i; printf(" %c", *it); ASSERT_EQ(*it, string_[i]); } printf("\n"); } TEST_F(StringIteratorTest, SubtractIndexToIterator) { nctl::String::ConstIterator it = string_.end(); printf("Accessing characters with an iterator and a negative index\n"); for (int i = 1; i <= static_cast<int>(string_.length()); i++) { printf(" %c", *(it - i)); ASSERT_EQ(*(it - i), string_[string_.length() - i]); } printf("\n"); } TEST_F(StringIteratorTest, SubtractIndexToIteratorInPlace) { printf("Accessing characters with an iterator and a negative index\n"); for (unsigned int i = 1; i <= static_cast<int>(string_.length()); i++) { nctl::String::ConstIterator it = string_.end(); it -= i; printf(" %c", *it); ASSERT_EQ(*it, string_[string_.length() - i]); } printf("\n"); } TEST_F(StringIteratorTest, SubtractIterators) { const int diff = string_.end() - string_.begin(); printf("Difference between end and begin iterators: %d\n", diff); ASSERT_EQ(diff, string_.length()); } TEST_F(StringIteratorTest, SubscriptOperator) { nctl::String::ConstIterator it = string_.begin(); printf("Accessing characters with the iterator subscript operator\n"); for (int i = 0; i < static_cast<int>(string_.length()); i++) { printf(" %c", it[i]); ASSERT_EQ(it[i], string_[i]); } printf("\n"); } }
3350226fad4df364db92261f74347c3c350d3513
0b7d78e82c7fa2d9ccbd375e5f5c20121e2d6792
/codeforces/wrong_subtraction.cpp
4b4886f45673deb37a038f88633fe708f1375070
[]
no_license
bdugersuren/exercises
6c5f16f38731c06b6e46dc80bab844f0ba749161
43bd1c1399921c5b0b314f7f7159f3339b9d2605
refs/heads/master
2023-04-25T13:41:31.786355
2021-05-13T05:22:32
2021-05-13T05:22:32
null
0
0
null
null
null
null
UTF-8
C++
false
false
160
cpp
wrong_subtraction.cpp
#include <iostream> using namespace std; int main() { int n,k,i; cin >> n >> k; for (i=0;i<k;i++) (n/10*10==n ? n/=10:n--); cout << n << endl; }
139d7367d47b4e64a5df2c9fad24d58ff1000026
996dbc3c2656fa3a4b362d58f582322ada857bb6
/Board.h
086095a00b14f86bb8d63496aac75c49ecce2063
[]
no_license
jacob-anabi/cpsc350-assignment2
c249bde462c75124be9c14cf6c12bbaa1d9e825f
57ccd1f0fe871555bb5b32399ffd0e631e26934b
refs/heads/master
2020-03-29T11:02:17.003636
2018-09-30T06:53:02
2018-09-30T06:53:02
149,833,284
0
0
null
null
null
null
UTF-8
C++
false
false
3,138
h
Board.h
/** * @author Jacob Anabi * @date 2018-09-29 * @version 1.0 * 2294644 * CPSC 350 * Assignment 2 */ #ifndef BOARD_H #define BOARD_H #include <string> #include <fstream> class Board { public: /** * default constructor */ Board(); /** * variable constructor * @param row - number of rows in the board * @param column - number of columns in the board * @param populationDensity - the population density for the Game of Life */ Board(unsigned int rows, unsigned int columns, double populationDensity); /** * copy constructor * @param board - the board to copy over */ Board(const Board& board); /** * destructor */ virtual ~Board(); /** * prints the board */ void printBoard(); /** * outputs the board to a file * @param outputFile - the file to output the board to */ void outputBoard(std::ofstream& outputFile); /** * checks if a next generation is possible * @return a boolean value that returns true if a next generation is possible, false otherwise */ bool nextGenerationPossible(); /** * construct a board with a provided map file * @param mapFile - the provided map file to look over */ void fileConstruct(std::ifstream& mapFile); /** * calculates the next generation of the board * @return boolean value representing if the next generation is possible * NOTE: pure virtual function */ void nextGeneration(); /** * getter for the generation number * @return the generation number */ int getGenerationNumber(); protected: char** board; // the board to be displayed to the user char** previousBoard; // the previous board that will be used to check for stabilization char** referenceBoard; // the board to reference when calculating the next generation double populationDensity; // the initial population density on the board unsigned int rows; // number of rows in the board unsigned int columns; // number of columns in the board unsigned int generationNumber; // the generation that the board is on const char ALIVE = 'X'; // variable to represent an ALIVE cell const char DEAD = '-'; // variable to represent a DEAD cell /** * copies the original board's elements to the previous one */ void copyBoardToPrev(); /** * updates the reference board based on the regular board */ virtual void updateRefBoard() = 0; private: /** * checks if a string is numeric * @param message - the message to check * @return - boolean value that represents if the message is numeric (true for yes, false otherwise) */ bool isNumeric(std::string& message); /** * initializes the board with the appropriate information * @param rows - number of rows of the board * @param columns - number of columns of the board * @param populationDensity - the population density of the board */ void initBoard(int rows, int columns, double populationDensity); }; #endif // BOARD_H
069b3199ebaa8b4f2511027e06d7653080ecde4c
d543bd6e66eebbef9f9f8df69f5eb1143b1b280c
/VHMScript/VHMScriptInterpreter.h
d29be2587addf007c61baf9b49cdf553f5fa44fc
[]
no_license
byeongkeunahn/VirtualHDDManager
de9218558abcf1fc46eabc762cdf5b23790d849c
4ad4188dfc7f907930b536ac1b3781ef9ab549d5
refs/heads/master
2021-01-22T22:57:23.530769
2017-03-20T15:19:00
2017-03-20T15:19:00
85,592,679
0
0
null
null
null
null
UTF-8
C++
false
false
117
h
VHMScriptInterpreter.h
#pragma once class CVHMScriptInterpreter { public: CVHMScriptInterpreter(); virtual ~CVHMScriptInterpreter(); };
fc24a3e94d91daf02e022e13ea674d79d1f69f68
8e12a396645f46c0b14dfc69b84ea1f7ad3e2314
/Sniffer/Src/qsn/FrameListener.h
ac088b003f3d86eb7914ba6fa208e9e3e4258742
[]
no_license
SKNmain/Sniffer
20ba4443128ffff0449ff9903df6bb0a4eb9ac31
abadff2a9e3ff9384b8001465d0c877efafd7d2e
refs/heads/master
2021-03-07T21:05:54.539086
2020-02-20T18:47:36
2020-02-20T18:47:36
246,297,227
0
0
null
2020-03-10T12:38:56
2020-03-10T12:38:55
null
UTF-8
C++
false
false
1,371
h
FrameListener.h
#pragma once #include "stdafx.h" #include "Adapter.h" #include "Utils/Stoppable.h" #include "FramesStash.h" namespace qsn { class FrameListener { public: FrameListener(FramesStash* packetsStash); ~FrameListener(); bool isListening() const; bool loadDumpFile(const std::string& dumpFileName); void startListening(Adapter* openedAdapter, const std::string& dumpFileName); void stopListening(); private: class ListeningTask : public Stoppable { public: ListeningTask(pcap_t* deviceToListening, FramesStash* packetsStash) : device(deviceToListening), stash(packetsStash) {} virtual void run() override; protected: pcap_t* device; FramesStash* stash; }; class ListeningWithDumpTask : public ListeningTask { public: ListeningWithDumpTask(pcap_t* deviceToListening, FramesStash* packetsStash, pcap_dumper_t* dumpFile) : ListeningTask(deviceToListening, packetsStash), dump(dumpFile) {} void run() override; private: pcap_dumper_t* dump; }; bool listening = false; Adapter* adapterToListening = nullptr; FramesStash* packetsStash = nullptr; std::thread* listeningThread = nullptr; ListeningTask* listeningTask = nullptr; }; }
1a5897e316ecf4a79ad1c5c9a78e7733fe7bec55
ec36a2c8720897ea188fa2af666223329ba9b444
/Source/AssignmentGame/Single/ManagerClass/ManagerClass.h
50e8934ab927123d131dc5575ebd0a81640fa53a
[]
no_license
HongRin/AssignmentGame
8a27fb395b884aa15a7c1f9bf35f048ac548828b
82732570636362f852a8d821053805502cbb0d0a
refs/heads/main
2023-05-14T14:09:42.729812
2021-06-12T04:58:29
2021-06-12T04:58:29
374,904,443
0
0
null
null
null
null
UHC
C++
false
false
588
h
ManagerClass.h
#pragma once #include "CoreMinimal.h" #include "UObject/NoExportTypes.h" #include "ManagerClass.generated.h" // ManagerClass Type 의 객체를 간편하게 불러올 수 있는 매크로 #ifndef MANAGER_INSTANCE #define MANAGER_INSTANCE #define GetManager(ManagerClassType) (GetGameInst(GetWorld())->GetManagerClass<ManagerClassType>()) #endif UCLASS(Abstract) class ASSIGNMENTGAME_API UManagerClass : public UObject { GENERATED_BODY() public: // 매니저 클래스 등록 FORCEINLINE virtual void InitManagerClass() {}; FORCEINLINE virtual void ShutdownManagerClass() {}; };
1ca975836ee3473d2e9d205c364563d6be68b46e
1adb9272ee30261882d56e6f955ad482f80b9584
/comp15/labs/lab6/StringSet.cpp
ecfb32ff12a20ab9665d6e8279446aba77dce225
[]
no_license
tomma367/Tufts-Stuffs
45d7b2881e3bfa698c9c5029c08dbf8750ac5872
723bc0902bb246d8650a5d6651bcbf5a453d3ace
refs/heads/master
2020-09-02T10:37:08.816715
2014-08-07T13:22:23
2014-08-07T13:22:23
null
0
0
null
null
null
null
UTF-8
C++
false
false
766
cpp
StringSet.cpp
#include "StringSet.h" StringSet::StringSet() { company=""; numFlavors=0; } StringSet StringSet::produceIntersection(StringSet* other) { StringSet inter; for(int i=0; i<numFlavors; i++) { for(int j=0; j<other->numFlavors; j++) { if(flavors[i]==other->flavors[j]) { inter.add(flavors[i]); inter.numFlavors++; } } } cout << "returning" << endl; return inter; } StringSet StringSet::produceUnion(StringSet* other) { } void StringSet::setName(string a) { company=a; } string StringSet::getName() { return company; } bool StringSet::add(string a) { for(int i=0; i<flavors.size(); i++) { if(a==flavors[i]) return false; } flavors.push_back(a); return true; }
bb2e5895ef50bc2e72fbbdde6ef123e88a9990c8
ab1dedf215dc0d34cdc9aafb9613ceac549821b1
/Linear3DInterpolator.h
642e4116f526f2e69bde8772597abe72c744b447
[]
no_license
zyzdiana/MotionCorrection
8cdb5cfd84ff420bcfd2168808821fb90c13212e
930cda92c56c9de598dd554176e95dd6e6d4e07f
refs/heads/master
2020-12-20T09:46:02.144459
2017-11-20T23:03:33
2017-11-20T23:03:33
49,975,702
0
1
null
2016-03-14T16:56:48
2016-01-19T19:01:38
C++
UTF-8
C++
false
false
2,214
h
Linear3DInterpolator.h
#ifndef Linear3DInterpolator_h #define Linear3DInterpolator_h #include "Interpolator3D.h" #include <Eigen/Dense> #include <cmath> #include <vector> template <typename VolumeT, typename CoordT> class Linear3DInterpolator : public Interpolator3D<VolumeT, CoordT> { public: typedef typename VolumeT::value_type T; typedef Eigen::Matrix< T, 8, 8 > Matrix_8_8_T; typedef Eigen::Matrix< T, 8, Eigen::Dynamic > Matrix_8_X_T; T interp( const CoordT z, const CoordT y, const CoordT x) const { CoordT xInt, yInt, zInt; CoordT xFrac, yFrac, zFrac; xFrac = std::modf(x, &xInt); yFrac = std::modf(y, &yInt); zFrac = std::modf(z, &zInt); // ideally we don't want to allocate these on every call to interp // but for right now this ensures the method is thread-safe CoordT target_YArr[8]; const Eigen::Map< Eigen::Matrix<T, 8, 1> > target_YVec(target_YArr); fill_target_Y(target_YArr, zFrac, yFrac, xFrac); return target_YVec.dot( coefficients.col( ( zInt * cubeSizeCoordT + yInt) * cubeSizeCoordT + xInt ) // coefficients.col( // (((size_t) zInt) * cubeSize + ((size_t) yInt)) * // cubeSize + ((size_t) xInt) // ) ); } protected: Linear3DInterpolator(const VolumeT *volume) : Interpolator3D<VolumeT, CoordT>(volume), coefficientsInner(volume->totalPoints * 8), coefficients(&(coefficientsInner[0]), 8, volume->totalPoints), cubeSize(volume->cubeSize), cubeSizeCoordT(volume->cubeSize) {} void fill_target_Y(T* target_YArr, const T z, const T y, const T x) const { target_YArr[0] = (T) 1.0; target_YArr[1] = x; //x target_YArr[2] = y; //y target_YArr[3] = z; //z target_YArr[4] = target_YArr[1] * y; // x*y target_YArr[5] = target_YArr[2] * z; // y*z target_YArr[6] = target_YArr[3] * x; // x*z target_YArr[7] = target_YArr[4] * z; // xyz } protected: std::vector<T> coefficientsInner; Eigen::Map< Matrix_8_X_T > coefficients; const size_t cubeSize; const CoordT cubeSizeCoordT; }; #endif
d3d7b673f19fd185b99f9fe85796e5eb74fe5985
0a754910d2dce595afbb69984c786165825aa37c
/GameC1/Scene.h
9418455e218b2e13e92e96c65665eccc6dde0f71
[]
no_license
Danerwilling/learnc
58b167228bbc770a6a7046d7137920007b01cc07
ea5980f148b76a7a767a4dc34477c631e410f00f
refs/heads/master
2020-05-04T21:36:52.362242
2015-04-24T21:51:05
2015-04-24T21:51:05
34,463,577
0
0
null
null
null
null
UTF-8
C++
false
false
149
h
Scene.h
#pragma once #include <iostream> #include "Sound.h" using namespace std; class Scene:Sound { public: Scene(); ~Scene(); virtual void play(); };
a2710bab2f35a72c40b5bf0809ffdc1f4dd63f28
1b49fac0f0ea40589ecd29d04a6f1ca4d6c3a7eb
/lib/update/molecdyn/monomial/two_flavor_monomial_params_w.cc
b9a75787d99c1930dd922420ec4860419cd23a88
[ "LicenseRef-scancode-warranty-disclaimer" ]
no_license
orginos/chroma
cc22c9854e2a0db2d4f17488904671015196c36f
57ba8783393dd7668c6a45e7f4c9919280c29cd3
refs/heads/master
2021-01-16T21:38:32.182916
2015-10-18T16:03:54
2015-10-18T16:03:54
24,952,861
0
2
null
null
null
null
UTF-8
C++
false
false
1,513
cc
two_flavor_monomial_params_w.cc
// $Id: two_flavor_monomial_params_w.cc,v 3.2 2006-07-04 02:55:52 edwards Exp $ /*! @file * @brief Two-flavor monomial params */ #include "update/molecdyn/monomial/two_flavor_monomial_params_w.h" #include "io/param_io.h" namespace Chroma { // Read the parameters TwoFlavorWilsonTypeFermMonomialParams::TwoFlavorWilsonTypeFermMonomialParams(XMLReader& xml_in, const string& path) { // Get the top of the parameter XML tree XMLReader paramtop(xml_in, path); try { // Read the inverter Parameters inv_param = readXMLGroup(paramtop, "InvertParam", "invType"); fermact = readXMLGroup(paramtop, "FermionAction", "FermAct"); if( paramtop.count("./ChronologicalPredictor") == 0 ) { predictor.xml=""; } else { predictor = readXMLGroup(paramtop, "ChronologicalPredictor", "Name"); } } catch(const string& s) { QDPIO::cerr << "Caught Exception while reading parameters: " << s <<endl; QDP_abort(1); } QDPIO::cout << "TwoFlavorWilsonTypeFermMonomialParams: read \n" << fermact.id << endl; } //! Read Parameters void read(XMLReader& xml, const std::string& path, TwoFlavorWilsonTypeFermMonomialParams& params) { TwoFlavorWilsonTypeFermMonomialParams tmp(xml, path); params = tmp; } //! Write Parameters void write(XMLWriter& xml, const std::string& path, const TwoFlavorWilsonTypeFermMonomialParams& params) { // Not implemented } } //end namespace Chroma
fe33461a3557abdb9851920d0d9f5ce7d80af4f5
11e11384d50043341b021bff5eaebbe48c032254
/Main/Core/engine.cpp
b5bfd88f92f12427e3ee48a913db062d84b18c67
[]
no_license
rghvdberg/Anthem
748e7b594834a03e716df7cbec60ef6fe9018120
8f12385265d1d390c60c56ce6d951cb1305cfa8a
refs/heads/master
2020-09-07T06:54:18.082966
2019-11-11T14:52:37
2019-11-11T14:52:37
220,693,374
0
0
null
2019-11-09T19:32:54
2019-11-09T19:32:53
null
UTF-8
C++
false
false
4,792
cpp
engine.cpp
#include "engine.h" #include <QDebug> using namespace rapidjson; Engine::Engine(QObject* parent) : QObject(parent) { engine = new QProcess(this); QObject::connect(engine, &QProcess::started, this, &Engine::onEngineStart); QObject::connect(engine, &QProcess::readyRead, this, &Engine::onEngineMessageChunk); engine->setReadChannel(QProcess::ProcessChannel::StandardOutput); engine->setProcessChannelMode(QProcess::ProcessChannelMode::MergedChannels); } Engine::~Engine() { stop(); } // TODO: propagate errors to user void Engine::start() { engine->start("mock-engine"); } // TODO: propagate errors to user // TODO: don't just kill; tell the engine process to stop, and let it stop itself void Engine::stop() { engine->kill(); } void Engine::onEngineStart() { emit engineStarted(); } void Engine::onEngineMessageChunk() { qDebug() << engine->readAllStandardOutput(); } void Engine::write(Document &json) { StringBuffer buffer; Writer<StringBuffer> writer(buffer); json.Accept(writer); const char* output = buffer.GetString(); engine->write(output); engine->write("\n"); } void Engine::addRPCHeaders(Document &json, std::string method) { Value jsonrpcVal(Type::kStringType); jsonrpcVal.SetString("2.0"); json.AddMember("jsonrpc", jsonrpcVal, json.GetAllocator()); Value methodVal(Type::kStringType); methodVal.SetString(method, json.GetAllocator()); json.AddMember("method", methodVal, json.GetAllocator()); } /* * { * "jsonrpc": "2.0", * "method": "ControlUpdate", * "params": { * "control_id": (uint64) * "value": (float) * } * } */ void Engine::sendLiveControlUpdate(uint64_t controlId, float value) { Document json; json.SetObject(); Document::AllocatorType& allocator = json.GetAllocator(); addRPCHeaders(json, "ControlUpdate"); Value params(Type::kObjectType); Value controlIdVal(Type::kNumberType); controlIdVal.SetUint64(controlId); Value valueVal(Type::kNumberType); valueVal.SetFloat(value); params.AddMember("control_id", controlIdVal, allocator); params.AddMember("value", valueVal, allocator); json.AddMember("params", params, allocator); write(json); } /* * { * "jsonrpc": "2.0", * "method": "MidiNoteEvent", * "params": { * "generator_id": (uint64) * "message": [(uint8), (uint8), (uint8)] * } * } */ void Engine::sendMidiNoteEvent(uint64_t generatorId, uint8_t status, uint8_t data1, uint8_t data2) { Document json; json.SetObject(); Document::AllocatorType& allocator = json.GetAllocator(); addRPCHeaders(json, "MidiNoteEvent"); Value params(Type::kObjectType); Value generatorIdVal(Type::kNumberType); generatorIdVal.SetUint64(generatorId); Value statusVal(Type::kNumberType); statusVal.SetUint(status); Value data1Val(Type::kNumberType); data1Val.SetUint(data1); Value data2Val(Type::kNumberType); data2Val.SetUint(data2); params.AddMember("generator", generatorIdVal, allocator); Value message(Type::kArrayType); message.PushBack(statusVal, allocator); message.PushBack(data1Val, allocator); message.PushBack(data2Val, allocator); params.AddMember("message", message, allocator); json.AddMember("params", params, allocator); write(json); } void Engine::sendPatch(QString operation, QString from, QString path, Value& value) { Document json; json.SetObject(); Document::AllocatorType& allocator = json.GetAllocator(); addRPCHeaders(json, "Patch"); Value params(Type::kObjectType); Value payload(Type::kObjectType); Value operationVal(Type::kStringType); operationVal.SetString(operation.toStdString(), allocator); payload.AddMember("op", operationVal, allocator); if (!from.isNull() && !from.isEmpty()) { Value fromVal(Type::kStringType); fromVal.SetString(from.toStdString(), allocator); payload.AddMember("from", fromVal, allocator); } Value pathVal(Type::kStringType); pathVal.SetString(path.toStdString(), allocator); payload.AddMember("path", pathVal, allocator); if (!value.IsNull()) { payload.AddMember("value", value, allocator); } params.AddMember("payload", payload, allocator); json.AddMember("params", params, allocator); write(json); } void Engine::sendPatchList(rapidjson::Value& patchList) { Document json; json.SetObject(); Document::AllocatorType& allocator = json.GetAllocator(); addRPCHeaders(json, "Patch"); Value params(Type::kObjectType); params.AddMember("payload", patchList, allocator); json.AddMember("params", params, allocator); write(json); }
03592f6f2dec6521e67195457d5333aecd1a7e5a
8bf4d4002f44976131171395329e1dbe0b5d8410
/src/ASTType.h
17f38230385f2e678331856071002206d840fb55
[]
no_license
fg123/sea
7cae6e0d86d16bf72e986734974bd6faa1013dd4
1b9de0f3df9aeb82191e8b911cb7d1537e08e222
refs/heads/master
2021-06-05T15:09:24.523086
2021-04-14T02:29:25
2021-04-14T02:29:25
135,646,917
0
0
null
null
null
null
UTF-8
C++
false
false
899
h
ASTType.h
#pragma once #include "Util.h" class TypeDeclaration; struct Name { std::vector<std::string> path; Name() {} Name(std::string str) { path.push_back(str); } std::string ToString() { return ListToString(path, "."); } }; struct SeaType { Name name; TypeDeclaration* type = nullptr; bool isPrimitive = false; bool nullable = false; SeaType() {} explicit SeaType(TypeDeclaration* type) : SeaType(type, false) {} SeaType(TypeDeclaration* type, bool isPrimitive) : type(type), isPrimitive(isPrimitive) {} SeaType(Name name, bool nullable) : name(name), nullable(nullable) {} std::string ToString() { return name.ToString() + (nullable ? "?" : ""); } bool IsNothing() { return type == nullptr; } void SetNothing() { type = nullptr; } };
dc8a0d76dbdfcffb9a56d28eed314234d9c7b008
1ffe4a35cf8244cb94e2b8e50ffd026f2e9ecef4
/Tools/ResourceEditor/Classes/Commands/LandscapeOptionsCommands.cpp
385af7d2d1a9d6d89dfa36ed3e33b9899247e9ab
[]
no_license
jjiezheng/dava.framework
481ff2cff24495feaf0bf24454eedf2c3e7ad4bc
6e961010c23918bb6ae83c0c3bee5e672d18537b
refs/heads/master
2020-12-25T08:42:01.782045
2013-06-12T11:13:05
2013-06-12T11:13:05
null
0
0
null
null
null
null
UTF-8
C++
false
false
472
cpp
LandscapeOptionsCommands.cpp
#include "LandscapeOptionsCommands.h" #include "DAVAEngine.h" #include "../Qt/Scene/SceneDataManager.h" #include "../Qt/Scene/SceneData.h" using namespace DAVA; CommandNotPassableTerrain::CommandNotPassableTerrain() : Command(Command::COMMAND_WITHOUT_UNDO_EFFECT) { } void CommandNotPassableTerrain::Execute() { SceneData *activeScene = SceneDataManager::Instance()->SceneGetActive(); activeScene->ToggleNotPassableLandscape(); }
3bccd1e540256c7e98ac6421303cebf9177b38d4
bbf8f711cbaaa78af6f354aadeb8ab9e7143b255
/CaseStudy/HomeExercises/QML-C++/23102017/Team2/MessageBoard/message.cpp
bad3850cf61a06fc6ef635f908f07dd06fde31d7
[]
no_license
ngocthanhpham/TrainingQML
8381331180378adc11aa3603cc974a59d1f4440e
32419cf3064a36e05c517c2c6be77dfef230d706
refs/heads/master
2021-09-06T10:09:19.266526
2018-02-05T10:36:21
2018-02-05T10:36:21
108,637,284
0
0
null
null
null
null
UTF-8
C++
false
false
622
cpp
message.cpp
#include "message.h" CMessage::CMessage(QObject *parent) : QObject(parent) { p_author_ = new CMessageAuthor(); p_body_ = new CMessageBody(); } CMessage::~CMessage() { delete p_author_; p_author_ = NULL; delete p_body_; p_body_ = NULL; } CMessageAuthor *CMessage::author() const { return this->p_author_; } CMessageBody *CMessage::body() const { return this->p_body_; } void CMessage::setAuthor(CMessageAuthor *p_value) { this->p_author_ = p_value; emit authorChanged(); } void CMessage::setBody(CMessageBody *p_value) { this->p_body_ = p_value; emit bodyChanged(); }
112dcffc5e67e60843519ddf87f54b56a1037893
764ce8838747251ec0728d03f5d1543c9de0ace4
/Himinn_Engine/Minigin/Scene.cpp
039d8588c693f24c74cf8077343b961faf85f619
[]
no_license
Himistyr/Himinn_Engine
f2d2986e7a34e1bf8f6f78ead45461efb3c385cf
bd4a399e9ff9140bfb60cd05d2e3074b57ad2e06
refs/heads/master
2023-05-16T23:01:02.499207
2021-06-07T03:57:38
2021-06-07T03:57:38
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,193
cpp
Scene.cpp
#include "MiniginPCH.h" #include "Scene.h" #include "GameObject.h" using namespace Himinn; unsigned int Scene::m_IdCounter = 0; Scene::Scene(const std::string& name) : m_Name(name) {} Scene::~Scene() = default; void Scene::Add(const std::shared_ptr<GameObject>& object) { m_Objects.push_back(object); } void Scene::Remove(const std::shared_ptr<GameObject>& object) { m_Objects.erase(std::remove_if(m_Objects.begin(), m_Objects.end(), [object](const std::shared_ptr<GameObject>& rhs) { return object == rhs; }), m_Objects.end()); } void Himinn::Scene::FixedUpdate() { for (auto& object : m_Objects) { object->FixedUpdate(); } } void Scene::Update() { for(auto& object : m_Objects) { object->Update(); } } void Himinn::Scene::LateUpdate() { for (auto& object : m_Objects) { object->LateUpdate(); } // Clean-Up for (auto& object : m_Objects) { if (object && object->ShouldBeDestroyed()) m_Objects.erase(std::remove(m_Objects.begin(), m_Objects.end(), object), m_Objects.end()); } } void Scene::Render() const { for (const auto& object : m_Objects) { object->Render(); } } const std::string& Himinn::Scene::GetName() const { return m_Name; }
5e3aeacb81013e6eb7ca986293184e9bd52252cd
dd9b591cc6ffb832a67f2d4dfb772f12b47cddcc
/对象储存器/list/10.list_splice.cpp
8d334d0d7c316c8aee571146787ecf5b84574f2e
[]
no_license
qiqzhang/CPP-Extends
5ad308893c3f154584cb39eb368b1370d35ed5eb
290ac86bf15982f31174415d3efe0a651ec3e679
refs/heads/master
2020-04-06T09:11:21.293050
2018-07-02T12:12:36
2018-07-02T12:12:36
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,325
cpp
10.list_splice.cpp
#include <iostream> #include <list> #include <string> #include <algorithm> using namespace std; void print(int &ele) { cout << ele << ", "; } int main(void) { list<int> l0, l1, l2, l3; list<int>::iterator it1, it2, it3; l0.push_back(9); l0.push_back(-1); l1.push_back(1); l1.push_back(5); l2.push_back(2); l2.push_back(3); l3.push_back(7); l3.push_back(8); for_each(l0.begin(), l0.end(), print); cout << endl; for_each(l1.begin(), l1.end(), print); cout << endl; for_each(l2.begin(), l2.end(), print); cout << endl; for_each(l3.begin(), l3.end(), print); cout << endl; l1.splice(l1.end(), l2); for_each(l1.begin(), l1.end(), print); cout << endl; for_each(l2.begin(), l2.end(), print); cout << endl; l1.splice(l1.end(), l0, (++l0.begin())); for_each(l1.begin(), l1.end(), print); cout << endl; for_each(l0.begin(), l0.end(), print); cout << endl; l1.splice(l1.end(), l3, l3.begin(), l3.end()); for_each(l1.begin(), l1.end(), print); cout << endl; for_each(l3.begin(), l3.end(), print); cout << endl; l1.sort(greater<int>()); for_each(l1.begin(), l1.end(), print); cout << endl; l1.sort(); for_each(l1.begin(), l1.end(), print); cout << endl; return 0; }
908886a7624ccc7c4f82b990bb85bdfa84f18d8b
6fe2d3c27c4cb498b7ad6d9411cc8fa69f4a38f8
/algorithms/algorithms-cplusplus/leetcode/Question_0423_Reconstruct_Original_Digits_from_English.cc
590afcecd9ffb4e54e634b997a76709af9b66057
[]
no_license
Lanceolata/code
aae54af632a212c878ce45b11dab919bba55bcb3
f7d5a7de27c3cc8a7a4abf63eab9ff9b21d512fb
refs/heads/master
2022-09-01T04:26:56.190829
2021-07-29T05:14:40
2021-07-29T05:14:40
87,202,214
0
0
null
null
null
null
UTF-8
C++
false
false
1,383
cc
Question_0423_Reconstruct_Original_Digits_from_English.cc
#include <string> #include <vector> using namespace std; class Solution { public: string originalDigits(string s) { string res = ""; vector<int> counts(128, 0), nums(10, 0); for (char c : s) { ++counts[c]; } nums[0] = counts['z']; nums[2] = counts['w']; nums[4] = counts['u']; nums[6] = counts['x']; nums[8] = counts['g']; nums[1] = counts['o'] - nums[0] - nums[2] - nums[4]; nums[3] = counts['h'] - nums[8]; nums[5] = counts['f'] - nums[4]; nums[7] = counts['s'] - nums[6]; nums[9] = counts['i'] - nums[6] - nums[8] - nums[5]; for (int i = 0; i < nums.size(); ++i) { for (int j = 0; j < nums[i]; ++j) { res += (i + '0'); } } return res; } string originalDigits2(string s) { string res = ""; vector<string> words{"zero", "two", "four", "six", "eight", "one", "three", "five", "seven", "nine"}; vector<int> nums{0, 2, 4, 6, 8, 1, 3, 5, 7, 9}, counts(26, 0); vector<char> chars{'z', 'w', 'u', 'x', 'g', 'o', 'h', 'f', 's', 'i'}; for (char c : s) { ++counts[c - 'a']; } for (int i = 0; i < 10; ++i) { int cnt = counts[chars[i] - 'a']; for (int j = 0; j < words[i].size(); ++j) { counts[words[i][j] - 'a'] -= cnt; } while (cnt--) res += (nums[i] + '0'); } sort(res.begin(), res.end()); return res; } };
ca79e3d43438aed63c43681b3635895b012db7c2
f0cb80bcba4fcdff0969ffe6d4b343ff61655965
/MemoForm/SaveMenu.h
99ae08351c568d163017d258b28d54a089c4085c
[]
no_license
rlagudtn/Memo
4975c5cede72542ef1dbcf965989ca0403deff99
ff15a9780b84d10a93cf66e9bf8771268fbe112d
refs/heads/master
2023-06-06T07:59:18.326987
2021-06-24T05:50:32
2021-06-24T05:50:32
113,292,651
0
0
null
null
null
null
UTF-8
C++
false
false
236
h
SaveMenu.h
//SaveMenu.h #ifndef _SAVEMENU_H #define _SAVEMENU_H #include "MenuAction.h" class MemoForm; class SaveMenu :public MenuAction { public: SaveMenu(); virtual ~SaveMenu(); void Implement(MemoForm *memoForm); }; #endif // _SAVEMENU_H
b4fdf9e45f3a319571badb07bfc720a01439761e
bed3ac926beac0f4e0293303d7b2a6031ee476c9
/Modules/Core/Mesh/include/itkSimplexMeshVolumeCalculator.h
c7437c158cba3b36d778b51120ceea3ab29dc693
[ "IJG", "Zlib", "LicenseRef-scancode-proprietary-license", "SMLNJ", "BSD-3-Clause", "BSD-4.3TAHOE", "LicenseRef-scancode-free-unknown", "Spencer-86", "LicenseRef-scancode-llnl", "FSFUL", "Libpng", "libtiff", "LicenseRef-scancode-warranty-disclaimer", "LicenseRef-scancode-other-permissive", "LicenseRef-scancode-hdf5", "MIT", "NTP", "LicenseRef-scancode-mit-old-style", "GPL-1.0-or-later", "LicenseRef-scancode-unknown-license-reference", "MPL-2.0", "Apache-2.0", "LicenseRef-scancode-public-domain", "BSD-2-Clause" ]
permissive
InsightSoftwareConsortium/ITK
ed9dbbc5b8b3f7511f007c0fc0eebb3ad37b88eb
3eb8fd7cdfbc5ac2d0c2e5e776848a4cbab3d7e1
refs/heads/master
2023-08-31T17:21:47.754304
2023-08-31T00:58:51
2023-08-31T14:12:21
800,928
1,229
656
Apache-2.0
2023-09-14T17:54:00
2010-07-27T15:48:04
C++
UTF-8
C++
false
false
7,246
h
itkSimplexMeshVolumeCalculator.h
/*========================================================================= * * Copyright NumFOCUS * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0.txt * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * *=========================================================================*/ #ifndef itkSimplexMeshVolumeCalculator_h #define itkSimplexMeshVolumeCalculator_h #include "itkIntTypes.h" #include "itkPolygonCell.h" #include "itkVector.h" #include "itkSimplexMesh.h" #include "itkVectorContainer.h" namespace itk { /** \class SimplexMeshVolumeCalculator * \brief * * Adapted from itkSimplexMeshToTriangleFilter to calculate the volume of * a simplex mesh using the barycenters and normals. * call Compute() to calculate the volume and GetVolume() to get the * value. For an example see itkDeformableSimplexMesh3DFilter.cxx * (Thomas Boettger. Division Medical and Biological Informatics, * German Cancer Research Center, Heidelberg.) * \author Leila Baghdadi MICe, Hospital for Sick Children, Toronto, Canada. * * The original implementation has been replaced with an algorithm * based on the discrete form of the divergence theorem. The general * assumption here is that the model is of closed surface. For more * details see the following reference (Alyassin A.M. et al, * "Evaluation of new algorithms for the interactive measurement of * surface area and volume", Med Phys 21(6) 1994.). * \ingroup ITKMesh * * \sphinx * \sphinxexample{Core/Mesh/CalculateAreaAndVolumeOfSimplexMesh,Calculate Area And Volume Of Simplex Mesh} * \endsphinx */ template <typename TInputMesh> class ITK_TEMPLATE_EXPORT SimplexMeshVolumeCalculator : public Object { public: ITK_DISALLOW_COPY_AND_MOVE(SimplexMeshVolumeCalculator); /** Standard "Self" type alias. */ using Self = SimplexMeshVolumeCalculator; /** Standard "Superclass" type alias. */ using Superclass = Object; /** Smart pointer type alias support */ using Pointer = SmartPointer<Self>; using ConstPointer = SmartPointer<const Self>; /** Method of creation through the object factory. */ itkNewMacro(Self); /** Run-time type information (and related methods). */ itkTypeMacro(SimplexMeshVolumeCalculator, Object); using InputMeshType = TInputMesh; using InputMeshPointer = typename InputMeshType::Pointer; using InputMeshConstPointer = typename InputMeshType::ConstPointer; using InputPointType = typename InputMeshType::PointType; using InputPixelType = typename InputMeshType::PixelType; using InputCellTraitsType = typename InputMeshType::MeshTraits::CellTraits; using InputPointsContainer = typename InputMeshType::PointsContainer; using InputPointsContainerPointer = typename InputPointsContainer::ConstPointer; using InputPointsContainerIterator = typename InputPointsContainer::ConstIterator; using InputNeighbors = typename InputMeshType::NeighborListType; using InputNeighborsIterator = typename InputMeshType::NeighborListType::iterator; using SimplexCellType = typename InputMeshType::CellType; using SimplexPolygonType = itk::PolygonCell<SimplexCellType>; // stores the center for each simplex mesh cell, key is the point id using PointMapType = itk::MapContainer<IdentifierType, InputPointType>; using PointMapPointer = typename PointMapType::Pointer; using VectorType = typename InputPointType::VectorType; using CovariantVectorType = CovariantVector<typename VectorType::ValueType, 3>; /** * \class SimplexCellVisitor * This class provides methods for visiting * each simplex cell of a simplex mesh * It computes the center of each visited cell. * \ingroup ITKMesh */ class SimplexCellVisitor { public: /** * default constructor */ SimplexCellVisitor() { m_CenterMap = PointMapType::New(); } virtual ~SimplexCellVisitor() = default; /** * \brief visits all polygon cells and compute the cell centers */ void Visit(IdentifierType cellId, SimplexPolygonType * poly) { using PointIdIterator = typename SimplexPolygonType::PointIdIterator; PointIdIterator it = poly->PointIdsBegin(); InputPointType center, p; center.Fill(0); p.Fill(0.0); while (it != poly->PointIdsEnd()) { m_Mesh->GetPoint(*it, &p); center += p.GetVectorFromOrigin(); ++it; } center[0] /= poly->GetNumberOfPoints(); center[1] /= poly->GetNumberOfPoints(); center[2] /= poly->GetNumberOfPoints(); m_CenterMap->InsertElement(cellId, center); } PointMapPointer GetCenterMap() { return m_CenterMap; } void SetMesh(InputMeshPointer mesh) { m_Mesh = mesh; } protected: InputMeshPointer m_Mesh; PointMapPointer m_CenterMap; }; using SimplexVisitorInterfaceType = itk:: CellInterfaceVisitorImplementation<InputPixelType, InputCellTraitsType, SimplexPolygonType, SimplexCellVisitor>; using SimplexVisitorInterfacePointer = typename SimplexVisitorInterfaceType::Pointer; using CellMultiVisitorType = typename SimplexCellType::MultiVisitor; using CellMultiVisitorPointer = typename CellMultiVisitorType::Pointer; /** Set the input mesh. */ itkSetObjectMacro(SimplexMesh, InputMeshType); /** Compute the volume of the entire simplex mesh. */ void Compute(); /** Return the computed volume. */ itkGetConstMacro(Volume, double); /** Return the computed area. */ itkGetConstMacro(Area, double); protected: SimplexMeshVolumeCalculator() = default; ~SimplexMeshVolumeCalculator() override = default; void PrintSelf(std::ostream & os, Indent indent) const override; private: void Initialize(); void Finalize(); /** creates dual triangles for all simplex cells */ void CreateTriangles(); /** Calculate volume of triangle. */ void CalculateTriangleVolume(InputPointType p1, InputPointType p2, InputPointType p3); /** part of algorithm */ IdentifierType FindCellId(IdentifierType id1, IdentifierType id2, IdentifierType id3); /** attribute stores the result of the simplex cell visitor */ PointMapPointer m_Centers{}; InputMeshPointer m_SimplexMesh{}; double m_Volume{ 0.0 }; double m_VolumeX{ 0.0 }; double m_VolumeY{ 0.0 }; double m_VolumeZ{ 0.0 }; double m_Area{ 0.0 }; double m_Kx{ 0.0 }; double m_Ky{ 0.0 }; double m_Kz{ 0.0 }; double m_Wxyz{ 0.0 }; double m_Wxy{ 0.0 }; double m_Wxz{ 0.0 }; double m_Wyz{ 0.0 }; IndexValueType m_Muncx{ 0 }; IndexValueType m_Muncy{ 0 }; IndexValueType m_Muncz{ 0 }; SizeValueType m_NumberOfTriangles{ 0 }; }; } // namespace itk #ifndef ITK_MANUAL_INSTANTIATION # include "itkSimplexMeshVolumeCalculator.hxx" #endif #endif /* __SimplexMeshVolumeCalculator_h */
91313483437fc4c81c32f53e8c1b4e53b12e3b39
777a75e6ed0934c193aece9de4421f8d8db01aac
/src/Providers/UNIXProviders/PSExtentBasedOnPExtent/UNIX_PSExtentBasedOnPExtent_LINUX.hxx
826022450cde1c8f91b257e0dafa442f809aa00d
[ "MIT" ]
permissive
brunolauze/openpegasus-providers-old
20fc13958016e35dc4d87f93d1999db0eae9010a
b00f1aad575bae144b8538bf57ba5fd5582a4ec7
refs/heads/master
2021-01-01T20:05:44.559362
2014-04-30T17:50:06
2014-04-30T17:50:06
19,132,738
1
0
null
null
null
null
UTF-8
C++
false
false
140
hxx
UNIX_PSExtentBasedOnPExtent_LINUX.hxx
#ifdef PEGASUS_OS_LINUX #ifndef __UNIX_PSEXTENTBASEDONPEXTENT_PRIVATE_H #define __UNIX_PSEXTENTBASEDONPEXTENT_PRIVATE_H #endif #endif
4607b314cb74be72132c4df8806bcacc6de93bcb
f5c0ee1a4b274966733f0358ae8c8031f09a3c98
/MapReduceFramework.cpp
e236b68d341b005403d3b8f3868e7123501d647f
[]
no_license
nivdror1/os_ex3
b15b42bc38f15d64a013df6c7cee3da0f83dfd89
65a5070ee90e94d61a7dc657bf5d41320493a8ce
refs/heads/master
2021-01-20T09:32:14.534755
2017-05-21T15:35:17
2017-05-21T15:35:17
90,262,936
0
0
null
null
null
null
UTF-8
C++
false
false
24,916
cpp
MapReduceFramework.cpp
#include "Comparators.h" #include <pthread.h> #include <map> #include <iostream> #include <stdlib.h> #include <fstream> #include "semaphore.h" #include <time.h> #include <sys/time.h> #include <algorithm> #define CHUNK_SIZE 10 #define SECONDS_TO_NANO_SECONDS 1000000000 #define MICRO_SECONDS_TO_NANO_SECONDS 1000 typedef std::vector<std::pair<k2Base*, v2Base*>> MAP_VEC; typedef std::vector<std::pair<pthread_t,MAP_VEC>> PTC; typedef std::vector<std::pair<k3Base*, v3Base*>> REDUCE_VEC; typedef std::vector<std::pair<pthread_t,REDUCE_VEC>> REDUCED_CONTAINERS; typedef std::pair<k3Base*, v3Base*> OUT_ITEM; typedef std::vector<OUT_ITEM> OUT_ITEMS_VEC; typedef std::vector<v2Base *> V2_VEC; /** vector of pairs of thread and his matching after-mapping vector*/ PTC execMapVector; /** the shuffle thread*/ pthread_t shuffleThread; /** vector of pairs of thread and his matching after-reducing vector*/ REDUCED_CONTAINERS execReduceVector; /** the input vector that was given in the runMapReduceFramework*/ MapReduceBase* mapReduce; /** * a semaphore which control the shuffle progressing by up/down the semaphore * any time a pair is been added/deleted form the ExecMap containers */ sem_t shuffleSemaphore; /** a vector which contain mutexes of execMap containers*/ std::vector<pthread_mutex_t> mutexVector; /** the output map of the shuffle process*/ std::map<k2Base*,std::vector<v2Base*>,K2Comp> shuffledMap; /** final output vector*/ OUT_ITEMS_VEC outputVector; /** mutex for the initiation of the reduce containers */ pthread_mutex_t reduceVectorMutex; /** the log file */ std::ofstream myLogFile; /** a mutex for the log file */ pthread_mutex_t logMutex; /** a counter of the currently running ExecMap threads*/ int numberOfMappingThreads; /** a mutex for the counter of the ExecMap currently running*/ pthread_mutex_t numberOfMappingThreadsMutex; /** * a struct of resources for the ExecMap objects */ struct MapResources{ /** a mutex on the pthreadToContainer*/ pthread_mutex_t pthreadToContainerMutex; // todo maybe change the name /** a mutex on the inputVectorIndex*/ pthread_mutex_t inputVectorIndexMutex; /** the input vector that was given in the runMapReduceFramework*/ IN_ITEMS_VEC inputVector; /** the index of current location in the input vector*/ unsigned int inputVectorIndex; }MapResources; struct ShuffleResources{ /** a vector of indexes that specify where the shuffle is in the passing through the container*/ std::vector<unsigned int> mapContainerIndex; }ShuffleResources; /** * a struct of resources for the ExecReduce objects */ struct ReduceResources{ /** a mutex on the shuffledVectorIndex*/ pthread_mutex_t shuffledVectorIndexMutex; /** the index of current location in the shuffled map*/ unsigned int shuffledMapIndex; }ReduceResources; void* mapAll(void*); void* shuffleAll(void*); void* reduceAll(void*); /** * convert to nano second * @param before the time before the operation * @param after the time after the operation * @return return the converted time */ inline double conversionToNanoSecond(timeval &before, timeval &after){ return ((after.tv_sec-before.tv_sec)*SECONDS_TO_NANO_SECONDS) +((after.tv_usec- before.tv_usec)*MICRO_SECONDS_TO_NANO_SECONDS); } /** * get the date and time * @return a string representation of the date and time */ std::string getDateAndTime(){ time_t now= time(0); struct tm tstruct; char buf[80]; tstruct = *localtime(&now); strftime(buf, sizeof(buf), "%Y:%m:%d:%X", &tstruct); std::string s=buf; return s; } /** * create a non specific thread * @param thread a reference to a thread to be created * @param function the function the thread is supposed to execute */ void createThread(pthread_t &thread, void * function(void*)){ if(pthread_create(&thread, NULL, function, NULL)!=0){ std::cerr<<"mapReduceFramework failure: pthread_create failed"<<std::endl; exit(1); } } /** * join a non specific thread * @param thread a thread */ void joinThread(pthread_t &thread){ if (pthread_join(thread, NULL) != 0){ std::cerr << "MapReduceFramework Failure: pthread_join failed." << std::endl; exit(1); } } /** * create a non specific thread * @param thread a reference to a thread to be created */ void detachThread(pthread_t &thread){ if(pthread_detach(thread)!=0){ std::cerr<<"mapReduceFramework failure: pthread_detach failed"<<std::endl; exit(1); } } /** * create a non specific mutex * @param mutex a mutex */ void createMutex(pthread_mutex_t &mutex){ if(pthread_mutex_init(&mutex,NULL)!=0){ std::cerr<<"mapReduceFramework failure: pthread_mutex_init failed"<<std::endl; exit(1); } } /** * lock the mutex * @param mutex a mutex */ void lockMutex(pthread_mutex_t &mutex){ if(pthread_mutex_lock(&mutex)!=0){ std::cerr<<"mapReduceFramework failure: pthread_mutex_lock failed"<<std::endl; exit(1); } } /** * unlock the mutex * @param mutex a mutex */ void unlockMutex(pthread_mutex_t &mutex){ if(pthread_mutex_unlock(&mutex)!=0){ std::cerr<<"mapReduceFramework failure: pthread_mutex_unlock failed"<<std::endl; exit(1); } } /** * destroy a mutex * @param mutex a mutex */ void destroyMutex(pthread_mutex_t &mutex){ if(pthread_mutex_destroy(&mutex)!=0){ std::cerr<<"mapReduceFramework failure: pthread_mutex_destroy failed"<<std::endl; exit(1); } } /** * operate sem_wait */ void wait(){ if(sem_wait(&shuffleSemaphore)!=0){ std::cerr<<"mapReduceFramework failure: sem_wait failed"<<std::endl; exit(1); } } /** * operate sem_post */ void post(){ if(sem_post(&shuffleSemaphore)!=0){ std::cerr<<"mapReduceFramework failure: sem_post failed"<<std::endl; exit(1); } } /** * check if getTimeOfDay has failed is so exit * @param beforeStatus a return from getTimeOfDay function * @param afterStatus a return from getTimeOfDay function */ void checkGetTimeOfDayFailure(int &beforeStatus,int &afterStatus){ if ((beforeStatus | afterStatus) == -1) { //check for a failure in accessing the time std::cerr << "MapReduceFramework Failure: getTimeOfDay failed." << std::endl; exit(1); } } /** * initiating the map threads * In addition initiate the vector which contains the * map container and the mutex for each map thread * @param numThread number of thread to create * */ void mappingThreadsInit(int numThread){ //spawn the new threads and initiate the vector execMapVector for(int i=0;i<numThread;i++){ // create vector of mapping threads MAP_VEC newMappingVector; //spawn a new execMap thread pthread_t newExecMapThread; createThread(newExecMapThread,mapAll); execMapVector.push_back(std::make_pair(newExecMapThread, newMappingVector)); } } /** * creating the mutexes for the ExecMapThreads * @param numThread the number of threads */ void creatingExecMapMutexes(int numThread){ //create the mutex for the inputVectorIndex,ExecMapVector and // for the counter of running execMap threads createMutex(MapResources.inputVectorIndexMutex); createMutex(MapResources.pthreadToContainerMutex); createMutex(numberOfMappingThreadsMutex); for(int i=0;i<numThread;i++){ // create the mutex for the this ExecMap container and append it to the mutexVector pthread_mutex_t mapContainerMutex; createMutex(mapContainerMutex); mutexVector.push_back(mapContainerMutex); } } /** * initiating the shuffle thread and the vector that contains the indexes * that point where the shuffle at the passage of the map conainter * @param numOfThreads the number of threads * @param numOfPairs the nufm of pairs to be shuffled */ void shuffleThreadInit(int numOfThreads) { // initiating a vector of indexes for every ExecMap container for (int i = 0; i < numOfThreads; i++) { ShuffleResources.mapContainerIndex.push_back(0); } //create the shuffle thread createThread(shuffleThread, shuffleAll); } /** * initiating the reduce threads and the vector that contains the thread and * his contained * @param numThread the number of reduce threads to be created */ void reducingThreadsInit(int numThread){ //creating and locking the mutex so the execReduce threads cannot use Emit3 // until this thread finish initiating all of the ExecReduce threads and their containers createMutex(reduceVectorMutex); lockMutex(reduceVectorMutex); createMutex(ReduceResources.shuffledVectorIndexMutex); //spawn the new threads and initiate the vector execReduceVector for(int i=0;i<numThread;i++){ // create vector of mapping threads REDUCE_VEC newReducingVector; //spawn a new execReduce thread pthread_t newExecReduceThread; createThread(newExecReduceThread,reduceAll); execReduceVector.push_back(std::make_pair(newExecReduceThread, newReducingVector)); } unlockMutex(reduceVectorMutex); } /** * write a message to the log file * @param message the text to be written */ void writingToTheLogFile(std:: string message){ lockMutex(logMutex); try{ myLogFile<<message; }catch (std::ofstream::failure e){ std::cerr<<"mapReduceFramework failure: write failed"<<std::endl; exit(1); } unlockMutex(logMutex); } /** * creating the log fle * @param numThread the number of threads */ void createLogFile(int numThread){ myLogFile.exceptions(std::ofstream::failbit|std::ofstream::badbit); try{ myLogFile.open(".test"); // todo change the name of the file at the end std::string message= "RunMapReduceFramework started with "+std::to_string(numThread)+" threads\n"; writingToTheLogFile(message); } catch(std::ofstream::failure e){ std::cerr<<"mapReduceFramework failure: open|write failed"<<std::endl; exit(1); } } /** * close the log file */ void closeTheLogFile(){ try{ myLogFile.close(); }catch(std::ofstream::failure e) { std::cerr << "MapReduceFramework Failure: close failed." << std::endl; exit(1); } } /** * creating the semaphore */ void createSemaphore(){ //initiate the semaphore if(sem_init(&shuffleSemaphore,0,0)==-1){ std::cerr<<"mapReduceFramework failure: sem_init failed"<<std::endl; exit(1); } } /** * clear map and reduce vectors and clear shuffledMap * and restart the indexes to zero */ void restartingResources(){ MapResources.inputVectorIndex=0; ReduceResources.shuffledMapIndex=0; ShuffleResources.mapContainerIndex.clear(); mutexVector.clear(); execMapVector.clear(); execReduceVector.clear(); shuffledMap.clear(); } /** * initiate the threads of the mapping and shuffling, and also initiate the * pthreadToContainer. * in addition initiating inputVector, numberOfMappingThreads and the mapReduceBase object * @param numThread the number of threads to be create while mapping * @param mapReduce an object that contain the map function */ void init(int numThread,MapReduceBase& mapReduceBase,IN_ITEMS_VEC& itemsVec){ //creating the log file createMutex(logMutex); createLogFile(numThread); // creating the semaphore createSemaphore(); //initiating resources MapResources.inputVector = itemsVec; mapReduce = &mapReduceBase; numberOfMappingThreads = numThread; outputVector.clear(); // creating the mutexes for the ExecMapThreads creatingExecMapMutexes(numThread); //lock the pthreadToContainer lockMutex(MapResources.pthreadToContainerMutex); mappingThreadsInit(numThread); // shuffleThreadInit(numThread); //unlock the pthreadToContainer unlockMutex(MapResources.pthreadToContainerMutex); } /** * pass on the execMapVector and then for each thread index * pass on the container and delete every k2 and v2 objects */ void clearK2V2Vector(){ //pass on execMapVector for (unsigned int threadIndex = 0; threadIndex < execMapVector.size(); ++threadIndex){ //get the current container of the execMapThread MAP_VEC currentVector = execMapVector.at(threadIndex).second; //Pass on the container and delete k2 and v2 objects for (auto itemsIter = currentVector.begin(); itemsIter != currentVector.end() ; ++itemsIter) { delete (*itemsIter).first; delete (*itemsIter).second; } } } /** * detach execMapThreads * @param numThreads number of threads to detach */ void detachExecMapThreads(int numThreads){ for(int i=0;i < numThreads;i++){ detachThread(execMapVector.at(i).first); writingToTheLogFile("Thread ExecMap terminated "+ getDateAndTime() +"\n"); } } /** * destroy mutexes at the finalizer after the framework has finished working */ void terminateMutexesAtTheFinalizer(int numMutexes){ destroyMutex(reduceVectorMutex); destroyMutex(numberOfMappingThreadsMutex); destroyMutex(MapResources.pthreadToContainerMutex); destroyMutex(ReduceResources.shuffledVectorIndexMutex); //destroy for each execMap container it's mutex for(int i=0;i<numMutexes;i++){ destroyMutex(mutexVector[i]); } } /** * release all the resources that allocated during the running of RunMapReduceFramework. * @param autoDeleteV2K2 if true, release also V2K2 pairs */ void finalizer(bool autoDeleteV2K2, int numThreads){ //check if there need to delete k2 and v2 objects is so delete them if (autoDeleteV2K2){ clearK2V2Vector(); } //detach the execMapThreads detachExecMapThreads(numThreads); //destroy the semaphore sem_destroy(&shuffleSemaphore); //destroy the mutexes terminateMutexesAtTheFinalizer(numThreads); //clear vectors and zero the index restartingResources(); writingToTheLogFile("RunMapReduceFramework finished\n"); } /** * initialize the RunMapReduceFramework * In addition run the ExecMapThreads and the shuffle thread * and measure the time that this run takes * @param mapReduce a mapReduceBase object that encapsulates the map and reduce functions * @param itemsVec the input vector * @param multiThreadLevel the number of execMap and ExecReduce threads to create * @return the time it took to operate the map and shuffle processes */ double runMapAndShuffleThreads(int multiThreadLevel,MapReduceBase& mapReduce, IN_ITEMS_VEC& itemsVec ){ struct timeval before, after; int beforeStatus, afterStatus; //get the starting time beforeStatus = gettimeofday(&before, NULL); //init the framework init(multiThreadLevel,mapReduce,itemsVec); //join the shuffle thread joinThread(shuffleThread); //get the time at the end of the run of map and shuffle afterStatus = gettimeofday(&after, NULL); //write the time to the log checkGetTimeOfDayFailure(beforeStatus,afterStatus); return conversionToNanoSecond(before,after); } /** * join each execReduce thread and merge his container with the outputVector */ void joinExecReduceThreadsAndMergeContainers(){ //join the reduce pthreads for(unsigned int i=0;i<execReduceVector.size(); i++){ pthread_join(execReduceVector.at(i).first,NULL); //merge the reduce vector and the output vector auto curReduceVector=execReduceVector.at(i).second; outputVector.reserve( outputVector.size() + curReduceVector.size()); outputVector.insert( outputVector.end(), curReduceVector.begin(), curReduceVector.end() ); writingToTheLogFile("Thread ExecReduce terminated "+ getDateAndTime() +"\n"); } } /** * run the ExecReduceThreads and produce the final output * in addition measure the time that this run takes * @param multiThreadLevel the number of execMap and ExecReduce threads to create * @param autoDeleteV2K2 a boolean variable that specify if the framework need to delete the k2 and v2 objects * @return the time it took to operate the reduce and final output processes */ double runReduceThreads(int multiThreadLevel,bool autoDeleteV2K2){ //todo maybe change the name struct timeval before, after; int beforeStatus, afterStatus; beforeStatus = gettimeofday(&before, NULL); //initialize the execReduce threads reducingThreadsInit(multiThreadLevel); //join the threads and merge their containers joinExecReduceThreadsAndMergeContainers(); //release resources and restart them finalizer(autoDeleteV2K2, multiThreadLevel); //sort the output std::sort(outputVector.begin(),outputVector.end(),K3Comp()); destroyMutex(logMutex); afterStatus = gettimeofday(&after, NULL); checkGetTimeOfDayFailure(beforeStatus, afterStatus); return conversionToNanoSecond(before,after); } /** * run the framework i.e run the execMapThreads and the shuffle thread * and after they have finished run the execReduceThreads * at the end merge the reduce containers and sort the output vector * @param mapReduce a mapReduceBase object that encapsulates the map and reduce functions * @param itemsVec the input vector * @param multiThreadLevel the number of execMap and ExecReduce threads to create * @param autoDeleteV2K2 a boolean variable that specify if the framework need to delete the k2 and v2 objects * @return the output vector */ OUT_ITEMS_VEC RunMapReduceFramework(MapReduceBase& mapReduce, IN_ITEMS_VEC& itemsVec, int multiThreadLevel, bool autoDeleteV2K2){ //run the execMap and shuffle threads double timeMapShuffle = runMapAndShuffleThreads(multiThreadLevel, mapReduce,itemsVec); writingToTheLogFile("Map and Shuffle took " + std::to_string(timeMapShuffle)+ "ns\n"); double timeReduce = runReduceThreads(multiThreadLevel,autoDeleteV2K2); writingToTheLogFile("Reduce took " + std::to_string(timeReduce)+ "ns\n"); closeTheLogFile(); return outputVector; } /** * search for the current thread and then add the pair to it container * @param key a k2 instance * @param value a v2 instance */ void Emit2 (k2Base* key, v2Base* value) { //get the thread id pthread_t currentThreadId = pthread_self(); //search for the same thread id for (unsigned int i = 0; i < execMapVector.size(); ++i) { if (pthread_equal(execMapVector.at(i).first,currentThreadId)) { //add the pair to the execMap container lockMutex(mutexVector.at(i)); execMapVector.at(i).second.push_back(std::make_pair(key, value)); unlockMutex(mutexVector.at(i)); break; } } //after each addition to the container we raise the semaphore value by 1 post(); } /** * search for the current thread and then add the pair to it container * @param key a k3 instance * @param value a v3 instance */ void Emit3 (k3Base* key, v3Base* value){ //get the thread id pthread_t currentThreadId = pthread_self(); //search for the same thread id for (unsigned int i = 0; i < execReduceVector.size(); ++i) { if (pthread_equal(execReduceVector.at(i).first,currentThreadId)) { //add the pair to the execReduce container auto pair = std::make_pair(key,value); execReduceVector.at(i).second.push_back(pair); break; } } } /** * map a chuck of pair from the inputVector by using the function map * @param chunkStartingIndex the index to start iterating over the inputVector */ void mapCurrentChunk(unsigned int chunkStartingIndex) { IN_ITEM currentItem; // take the minimum so we don't get out of bounds from input vector unsigned int numberOfIterations = std::min(chunkStartingIndex + CHUNK_SIZE, (unsigned int)MapResources.inputVector.size()); for (unsigned int i = chunkStartingIndex; i < numberOfIterations; ++i) { // map the current item from input vector currentItem = MapResources.inputVector.at(i); mapReduce->Map(currentItem.first, currentItem.second); } } /** * mapping function that the thread actually runs, gets chunks of pairs from input vector and * mapping them according to the given map function */ void* mapAll(void*) { writingToTheLogFile("Thread ExecMap created "+ getDateAndTime() +"\n"); // lock and unlock the pthreadToContainer mutex lockMutex(MapResources.pthreadToContainerMutex); unlockMutex(MapResources.pthreadToContainerMutex); unsigned int currentIndex = 0; int currentNumberOfMappingThreads = 0; // loop until there are no more pairs to take from input vector while (currentIndex < MapResources.inputVector.size()){ // lock inputVectorIndex to get the starting index for next chunk to map lockMutex(MapResources.inputVectorIndexMutex); currentIndex = MapResources.inputVectorIndex; MapResources.inputVectorIndex += CHUNK_SIZE; unlockMutex(MapResources.inputVectorIndexMutex); mapCurrentChunk(currentIndex); currentIndex += CHUNK_SIZE; } lockMutex(numberOfMappingThreadsMutex); currentNumberOfMappingThreads = --numberOfMappingThreads; unlockMutex(numberOfMappingThreadsMutex); if (currentNumberOfMappingThreads == 0){ //post the shuffle semaphore so it will run one last iteration post(); } return 0; } /** * search the key, if it is in the map append the value to the vector, * else add a new pair to the map (key,value) * @param key the key on which to search * @param value the data that need to append */ void searchingAndInsertingData(k2Base* key, v2Base* value){ //search the key auto search = shuffledMap.find(key); //if the key has been found ,append only the value if(search != shuffledMap.end()) { search->second.push_back(value); } else{ // add a new pair auto valueVector= std::vector<v2Base*>{value} ; shuffledMap.insert(std::make_pair(key, valueVector)); } //after each addition to the shuffled map we decrease the semaphore value by 1 wait(); } /** * shuffle data from a container * @param i the index of the execMap containers * @param pairsShuffled the number of the pairs that had been shuffled */ void shufflingDataFromAContainer(unsigned int i){ //going through the execMapVector while(ShuffleResources.mapContainerIndex.at(i) < execMapVector.at(i).second.size()) { unsigned int index= ShuffleResources.mapContainerIndex.at(i); //lock the mutex of the container lockMutex(mutexVector.at(i)); //get the value from the container k2Base *key = execMapVector.at(i).second.at(index).first; v2Base *value = execMapVector.at(i).second.at(index).second; //unlock the mutex of the container unlockMutex(mutexVector.at(i)); //increase the index value of the specific map container ShuffleResources.mapContainerIndex.at(i)+=1; // insert the pair into the shuffle container searchingAndInsertingData(key,value); } } /** * the function performs the shuffle process * this process take every pair from the map containers and insert to * the shuffled container which each cell in it contain a key * and vector of value that correspond * @return do not return anything */ void* shuffleAll(void*){ bool mapStillRunning=true; writingToTheLogFile("Thread shuffle created "+ getDateAndTime() +"\n"); //wait until one of the containers is not empty wait(); while (mapStillRunning) { // if there no more execMap threads running if(numberOfMappingThreads==0){ mapStillRunning = false; } for (unsigned int i = 0; i < execMapVector.size(); i++) { // shuffling Data From A specific Container shufflingDataFromAContainer(i); } } return 0; } /** * reduce a chuck of pair from the shuffled map by using the function reduce * @param chunkStartingIndex the index to start iterating over the shuffledMap */ void reduceCurrentChunk(unsigned int chunkStartingIndex){ //advance the iterator so it point the chunkStartingIndex in the map auto iteratingIndex = shuffledMap.begin(); std::advance(iteratingIndex, chunkStartingIndex); // take the minimum so we don't get out of bounds from shuffled vector unsigned int numberOfIterations = std::min(chunkStartingIndex + CHUNK_SIZE, (unsigned int)shuffledMap.size()); for (unsigned int i = chunkStartingIndex; i < numberOfIterations; ++i) { mapReduce->Reduce(iteratingIndex->first, iteratingIndex->second); ++iteratingIndex; } } /** * reducing function that the thread actually runs, gets chunks of pairs from shuffledMap and * reducing them according to the given reduce function */ void* reduceAll(void *) { writingToTheLogFile("Thread ExecReduce created"+ getDateAndTime() +"\n"); lockMutex(reduceVectorMutex); unlockMutex(reduceVectorMutex); unsigned int currentIndex = 0; // loop until there are no more pairs to take from input vector while (currentIndex < shuffledMap.size()){ // lock shuffledVectorIndex to get the starting index for next chunk to map lockMutex(ReduceResources.shuffledVectorIndexMutex); currentIndex = ReduceResources.shuffledMapIndex; ReduceResources.shuffledMapIndex += CHUNK_SIZE; unlockMutex(ReduceResources.shuffledVectorIndexMutex); //reduce the current chunk reduceCurrentChunk(currentIndex); currentIndex += CHUNK_SIZE; } return 0; }
f72a86198f55baab296b0ca81dbc5b3314422b5a
cca8fe05f041c7a66701368f3d5d04a060feae94
/PO/Matrix/main.cpp
46caff4f0a78837f7b5197b72eb815d596ebf6c4
[]
no_license
dominik3131/PO
c4c243ca52b0a51b658f21f8554763fab0be02c0
0df8975ab7bfdaad9349cfeb9654736133b118b5
refs/heads/master
2020-05-22T19:34:16.945799
2019-05-13T20:53:59
2019-05-13T20:53:59
186,493,546
0
0
null
null
null
null
UTF-8
C++
false
false
381
cpp
main.cpp
#include <iostream> #include "matrix.h" /* run this program using the console pauser or add your own getch, system("pause") or input loop */ int main(int argc, char** argv) { rcMatrix m1(2,4,0.0); cout<<m1; try{ m1.loadFile("m1.txt"); } catch(rcMatrix::errorOpeningFile){ cout<<"das"; } catch(std::bad_alloc){ cout<<"daass"; } cout<<m1; return 0; }
0aa7fc6d56540ba4c356e04ea35d2a8b0ff4251a
957080e4caf76aebaa47e24bb47f3571f8bbe0ec
/Excercise3/Excercise3/StaticObject.cpp
0c3ec7eb90c82fce0545bb57fbd1a79ab1209424
[]
no_license
lev-michael/ICPP1_2020
53a53550a08bfe4baba04e0fb3dcfcac4a83778a
ab85e8a517c00ca58e41bb542aeaca0fac488dc4
refs/heads/master
2023-02-03T22:16:36.102491
2020-12-28T19:32:16
2020-12-28T19:32:16
299,699,599
0
0
null
null
null
null
UTF-8
C++
false
false
234
cpp
StaticObject.cpp
#include "StaticObject.h" StaticObject::StaticObject(int id, BarrierType type) :Object(id) { this->barrierType = type; } StaticObject::~StaticObject() { } BarrierType StaticObject::GetBarrierType() { return this->barrierType; }
0e426d2f62963aaf7ed330d7fbca2027d5d71a46
a4fdbe22a71ae9dfa37150dac60569e4e1277826
/Data-Structures-and-Algorithms/2-Sorting-Advance/z-Compared/compare.cpp
f91ddaf0475858b6184e4f9e38ebf5da8bb17629
[]
no_license
ideask/Rookie-training-program
c046659d5d3edbf38a1e3dd835f9abf00d11564a
5f130fa0a6857df1d9aff99b5f82bc09189a0258
refs/heads/master
2020-11-25T10:13:39.329476
2020-01-11T10:11:38
2020-01-11T10:11:38
228,613,973
0
0
null
null
null
null
UTF-8
C++
false
false
5,795
cpp
compare.cpp
#include "compare.h" template <typename T> void __merge(T *arr, int l, int mid, int r) { T aux[r-l+1]; for(int i = l; i <= r; i++) { aux[i - l] = arr[i]; } int i=l; int j=mid+1; for(int k = l; k <= r; k++) { if(i > mid){arr[k] = aux[j-l]; j++;} else if(j > r){arr[k] = aux[i-l]; i++;} else if(aux[i-l] > aux[j-l]){arr[k] = aux[j-l]; j++;} else{arr[k] = aux[i-l]; i++;} } } template <typename T> void __mergeSort(T *arr, int l, int r) { if(l>=r) return; int mid = l + (r-l)/2; __mergeSort(arr, l, mid); __mergeSort(arr, mid+1, r); __merge(arr, l, mid, r); } template <typename T> void mergeSort(T *arr, int amount) { __mergeSort(arr, 0, amount-1); } template <typename T> void insertionSort(T *arr, int l, int r) { for(int i = l; i<=r; i++) { T v = arr[i]; int j; for(j=i; arr[j-1] > v && j > 0; j--) { arr[j] = arr[j-1]; } arr[j] = v; } } template <typename T> void __mergeSortAdvance(T *arr, int l, int r) { if(r-l < 15) { insertionSort(arr, l, r); return; } int mid = l + (r-l)/2; __mergeSortAdvance(arr, l, mid); __mergeSortAdvance(arr, mid+1, r); if(arr[mid+1] > arr[mid]) return; __merge(arr, l, mid, r); } template <typename T> void mergeSortAdvance(T *arr, int amount) { __mergeSortAdvance(arr, 0, amount-1); } template <typename T> void __mergeSortBU(T *arr, int amount) { for(int sz=1; sz <= amount; sz+=sz) { /* arr[i,i+sz-1] arr[i+sz, i+sz+sz-1]*/ for(int i=0; i+sz-1 < amount-1; i+=sz+sz) { __merge(arr,i, i+sz-1, min(i+sz+sz-1, amount-1)); } } } template <typename T> void mergeSortBU(T *arr, int amount) { __mergeSortBU(arr, amount); } template <typename T> int partition(T *arr, int l, int r) { T v = arr[l]; /*arr[l+1, j] arr[j+1,r]*/ int j = l; int i = l+1; while(i<=r) { if(arr[i] >= v){i++;} else if(arr[i] < v){swap(arr[i], arr[j+1]);j++;i++;} } /*arr[l, j-1] j arr[j+1,r]*/ swap(arr[l], arr[j]); return j; } template <typename T> void __quickSort(T *arr, int l, int r) { if(l>=r) return; int p = partition(arr, l, r); __quickSort(arr, l, p-1); __quickSort(arr, p+1, r); } template <typename T> void quickSort(T *arr, int amount) { __quickSort(arr, 0, amount-1); } template <typename T> int partitionRP(T *arr, int l, int r) { srand(time(NULL)); swap(arr[l], arr[rand() % (r-l+1) + l]); T v = arr[l]; /*v=arr[l] arr[l+1, j] arr[j+1, r]*/ /*arr[l, j-1] arr[j+1, r]*/ int j = l; for(int i=l+1; i <= r; i++) { if(arr[i] < v) { swap(arr[i], arr[j+1]); j++; } } swap(arr[l], arr[j]); return j; } template <typename T> void __quickSortRandomPick(T *arr, int l, int r) { if(l >= r) return; int p = partitionRP(arr, l, r); __quickSortRandomPick(arr, l, p-1); __quickSortRandomPick(arr, p+1, r); } template <typename T> void quickSortRP(T *arr, int amount) { __quickSortRandomPick(arr, 0, amount-1); } template <typename T> int partitionTW(T *arr, int l, int r) { srand(time(NULL)); swap(arr[l], arr[rand() % (r-l+1) + l]); T v = arr[l]; /* arr[l+1, j) arr(k, r]*/ int j=l+1; int k=r; while(true) { while(arr[j] < v){j++;} while(arr[k] > v){k--;} if(j > k) break; swap(arr[j], arr[k]); j++; k++; } swap(arr[l], arr[k]); return k; } template <typename T> void __quickSortTW(T *arr, int l, int r) { if(l >= r) return; int p = partitionTW(arr, l, r); __quickSortTW(arr, l, p-1); __quickSortTW(arr, p+1, r); } template <typename T> void quickSortTwoWays(T *arr, int amount) { __quickSortTW(arr, 0, amount-1); } template <typename T> void __quickSortThreeWays(T *arr, int l, int r) { if(l >= r) return; srand(time(NULL)); swap(arr[l], arr[rand() % (r-l+1)+l]); T v = arr[l]; /*arr[l+1,lt] arr[lt+1, gt-1] arr[gt,r]*/ int i = l+1; int lt = l; int gt = r+1; while(i < gt) { if(arr[i] > v){swap(arr[i], arr[gt-1]); gt--;} else if(arr[i] < v){lt++; i++;} else{i++;} } swap(arr[l], arr[lt]); __quickSortThreeWays(arr, l, lt-1); __quickSortThreeWays(arr, gt, r); } template <typename T> void quickSortThreeWays(T *arr, int amount) { __quickSortThreeWays(arr, 0, amount-1); } int main() { #define FROM 1 #define TO 100 #define AMOUNT 100 int *arr = sortTestHelper::genRandomArr(FROM,TO,AMOUNT); int *arr11 = sortTestHelper::cpyArr(arr, AMOUNT); int *arr21 = sortTestHelper::cpyArr(arr, AMOUNT); int *arr31 = sortTestHelper::cpyArr(arr, AMOUNT); int *arr41 = sortTestHelper::cpyArr(arr, AMOUNT); int *arr51 = sortTestHelper::cpyArr(arr, AMOUNT); int *arr61 = sortTestHelper::cpyArr(arr, AMOUNT); int *arr71 = sortTestHelper::cpyArr(arr, AMOUNT); // sortTestHelper::sortBenchMark("Merge Sort base", mergeSort, arr11, AMOUNT); // sortTestHelper::sortBenchMark("Merge Sort Advance", mergeSortAdvance, arr21, AMOUNT); // sortTestHelper::sortBenchMark("Merge Sort Bottom up", mergeSortBU,arr31,AMOUNT); // sortTestHelper::sortBenchMark("Quick Sort base", quickSort,arr41,AMOUNT); // sortTestHelper::sortBenchMark("Quick Sort base Random pick", quickSortRP,arr51,AMOUNT); sortTestHelper::sortBenchMark("Quick Sort base Two ways", quickSortTwoWays,arr61,AMOUNT); sortTestHelper::sortBenchMark("Quick Sort base Three ways", quickSortThreeWays,arr71,AMOUNT); return 0; }
e67675b52a7a4e5503b73b9dcdcaaed10cfa7144
548140c7051bd42f12b56e8bb826074609c8b72e
/Jams/GameOfLife/Code/Game/GameState_Playing.cpp
cba60582d8a53ad65dab9c4fb69104d319338045
[]
no_license
etrizzo/PersonalEngineGames
3c55323ae730b6499a2d287c535c8830e945b917
6ef9db0fd4fd34c9e4e2f24a8b58540c075af280
refs/heads/master
2021-06-16T22:01:57.973833
2021-01-26T03:54:58
2021-01-26T03:54:58
135,343,718
0
0
null
null
null
null
UTF-8
C++
false
false
2,516
cpp
GameState_Playing.cpp
#include "Game/GameState_Playing.hpp" #include "Game/Game.hpp" #include "Game/Map.hpp" #include "Game/Entity.hpp" #include "Game/Player.hpp" #include "Game/DebugRenderSystem.hpp" #include "Engine/Renderer/SpriteRenderPath.hpp" #include "Engine/Renderer/Camera.hpp" #include "Game/GameOfLife.hpp" GameState_Playing::GameState_Playing() { m_renderScene = new RenderScene2D(); //straight line m_currentMap = new Map(std::vector<IntVector2>{ IntVector2(0, 0), IntVector2(0, 1), IntVector2(0, 2) }); //glider //m_currentMap = new Map(std::vector<IntVector2>{ // IntVector2(3, 6), // IntVector2(4, 5), // IntVector2(5, 5), // IntVector2(5, 6), // IntVector2(5, 7) //}); //r-pentomino //m_currentMap = new Map(std::vector<IntVector2>{ // IntVector2(3, 6), // IntVector2(3, 7), // IntVector2(2, 7), // IntVector2(3, 8), // IntVector2(4, 8) //}); } void GameState_Playing::Update(float ds) { m_timeInState+=ds; float deltaSeconds = ds; m_currentMap->Update(ds); } void GameState_Playing::RenderGame() { float width = (float)m_currentMap->GetWidth(); g_theGame->m_mainCamera->SetProjectionOrtho(width, g_gameConfigBlackboard.GetValue("windowAspect", 1.f), 0.f, 100.f); g_theGame->m_mainCamera->SetPosition(Vector3(width * -.5f, 0.f, -1.f)); g_theGame->SetMainCamera(); m_currentMap->Render(); //g_theGame->m_debugRenderSystem->UpdateAndRender(); //g_theRenderer->EnableDepth( COMPARE_LESS, true ); } void GameState_Playing::RenderUI() { //AABB2 bounds = g_theGame->SetUICamera(); } void GameState_Playing::HandleInput() { g_theGame->m_debugRenderSystem->HandleInput(); if (g_theInput->WasKeyJustPressed(VK_F1)){ g_theGame->ToggleDevMode(); } if (g_theInput->WasKeyJustPressed('P') || g_theInput->GetController(0)->WasButtonJustPressed(XBOX_START) ){ g_theGame->TransitionToState(new GameState_Paused(this)); } if (g_theInput->WasKeyJustPressed('T')){ g_theGame->m_gameClock->SetScale(.1f); } if (g_theInput->WasKeyJustReleased('T')){ g_theGame->m_gameClock->SetScale(1.f); } if (g_theInput->WasKeyJustPressed('O')) { if (m_currentMap->IsAutoTick()) { m_currentMap->SetAutoTick(false); } else { m_currentMap->m_gameOfLife->Tick(); } } if (g_theInput->WasKeyJustPressed('S')) { m_currentMap->SetAutoTick(!m_currentMap->IsAutoTick()); } if (g_theInput->WasKeyJustPressed('X')) { m_currentMap->IncreaseAutoTickRate(0.05f); } if (g_theInput->WasKeyJustPressed('Z')) { m_currentMap->IncreaseAutoTickRate(-0.05f); } }
978bdf36e5d7196b132a32bfabcc4f7a03de3b9f
67819cc35086b4a52dc1d633d97bb6b5579faede
/2021_08/week_2/NGP_2193.cpp
3e068d9c47f843a91519211bab0aa780fa481b2c
[]
no_license
HwangInHo1217/FourBeginners_AlgorithmStudy
662c81cf8b1c4d467d650d2ee3f3f4cd54f8aa8c
3ecbdf5c1066f069cb97d2b3888f02ae7e36a0c9
refs/heads/main
2023-07-02T22:24:43.082242
2021-08-12T08:54:26
2021-08-12T08:54:26
389,518,424
0
0
null
2021-07-26T05:31:25
2021-07-26T05:31:24
null
UTF-8
C++
false
false
305
cpp
NGP_2193.cpp
#include<iostream> using namespace std; long long dp[91]; int main() { ios_base::sync_with_stdio(0), cin.tie(NULL), cout.tie(NULL); int cnt; cin >> cnt; dp[1] = 1, dp[2] = 1, dp[3] = 2; for (int i = 4; i <= cnt; i++) { dp[i] = dp[i - 1] + dp[i - 2]; } cout << dp[cnt] << "\n"; }
a97e50608cb14c36b4bd4c3c2b9b05196b3492bd
4ba5e21f4ab41f83e5abd221074d24a3fb28159c
/src/particles/particle_system.cpp
66f5c933b483136e6011e513ce7607a77e83e176
[]
no_license
songmin0/ambrosia
89116552890862a5fe28df42f07a61bf6f762ecd
f717a4da885f01fe14e8866cbc56489b793eeeed
refs/heads/master
2023-08-27T17:12:05.194506
2021-04-20T01:02:47
2021-04-20T01:02:47
428,529,968
0
0
null
null
null
null
UTF-8
C++
false
false
16,298
cpp
particle_system.cpp
#include "particle_system.hpp" // stlib #include <string.h> #include <cassert> #include <sstream> #include <iostream> #include <fstream> const GLfloat ParticleSystem::particleVertexBufferData[] = { -0.5f, -0.5f, 0.0f, 0.5f, -0.5f, 0.0f, -0.5f, 0.5f, 0.0f, 0.5f, 0.5f, 0.0f, }; //TODO delete the emitter logic from the particle system so that the only way to have particles is through an emitter. ParticleSystem::ParticleSystem() { //Initialize all the member variables to stop the compiler from being upset. They are all properly initalized in the initParticles function which is called after all the GL dependencies are done being called. particleVertexBuffer = 0; particlesCenterPositionAndSizeBuffer = 0; particlesColorBuffer = 0; cameraRightWorldspaceID = 0; cameraUpWorldspaceID = 0; projectionMatrixID = 0; VertexArrayID = 0; //Initialize the arrays to 0 to stop the compiler from being upset. memset(particleCenterPositionAndSizeData, 0, sizeof(GLfloat) * MaxParticles * 4); memset(particleColorData, 0, sizeof(GLfloat) * MaxParticles * 4); secSinceLastParticleSpawn = 0.0f; for (int i = 0; i < MaxParticles; i++) { ParticlesContainer[i].life = -1.0f; } //TODO make particleContainer a heap variable so that we aren't limited to stack size (use a shared or unique pointer for this) addEmitterListener = EventSystem<AddEmitterEvent>::instance().registerListener( std::bind(&ParticleSystem::onAddedEmitterEvent, this, std::placeholders::_1)); deleteEmitterListener = EventSystem<DeleteEmitterEvent>::instance().registerListener( std::bind(&ParticleSystem::onDeleteEmitterEvent, this, std::placeholders::_1)); deleteAllEmittersListener = EventSystem<DeleteAllEmittersEvent>::instance().registerListener( std::bind(&ParticleSystem::onDeleteAllEmitterEvent, this, std::placeholders::_1)); } //http://www.opengl-tutorial.org/intermediate-tutorials/billboards-particles/particles-instancing/ void ParticleSystem::drawParticles(const mat3& projection, const vec2& cameraPos) { for (std::map<std::string, std::shared_ptr<ParticleEmitter>>::iterator it = newEmitters.begin(); it != newEmitters.end(); ++it){ it->second->drawParticles(particleVertexBuffer, cameraRightWorldspaceID, cameraUpWorldspaceID, projectionMatrixID, projection, cameraPos); } } void ParticleSystem::onAddedEmitterEvent(const AddEmitterEvent& event) { newEmitters.emplace(event.label, event.emitter); event.emitter->initEmitter(); } void ParticleSystem::onDeleteEmitterEvent(const DeleteEmitterEvent& event) { newEmitters.erase(event.label); } void ParticleSystem::onDeleteAllEmitterEvent(const DeleteAllEmittersEvent& event) { newEmitters.erase(newEmitters.begin(), newEmitters.end()); } void ParticleSystem::step(float elapsed_ms) { //Call the step function for each emitter in the world NOTE this does nothing right now because emitters haven't been fully built for (std::map<std::string, std::shared_ptr<ParticleEmitter>>::iterator it = newEmitters.begin(); it != newEmitters.end(); ++it) { it->second->step(elapsed_ms); } } void ParticleSystem::initParticles() { GLenum error = glGetError(); //generate the vertex buffer for the particles. This should be used for all particle emitters glGenBuffers(1, &particleVertexBuffer); glBindBuffer(GL_ARRAY_BUFFER, particleVertexBuffer); glBufferData(GL_ARRAY_BUFFER, sizeof(particleVertexBufferData), particleVertexBufferData, GL_STATIC_DRAW); } // ---------- ParticleEmitter base class ----------- ParticleEmitter::ParticleEmitter() { for (int i = 0; i < ParticleSystem::MaxParticles; i++) { ParticlesContainer[i].life = -1.0f; } } void ParticleEmitter::step(float elapsedMs) { int newParticles; if (burst) { newParticles = ParticleSystem::MaxParticles; burst = false; } else { float elapsed_time_sec = elapsedMs / 1000.0f; secSinceLastParticleSpawn += elapsed_time_sec; newParticles = (int)(secSinceLastParticleSpawn * particlesPerSecond); if (newParticles != 0) { secSinceLastParticleSpawn = 0.0f; } } this->simulateParticles(elapsedMs, newParticles); } void ParticleEmitter::drawParticles(GLuint vertexBuffer, GLuint cameraRightWorldspaceID, GLuint cameraUpWorldspaceID, GLuint projectionMatrixID, const mat3& projection, const vec2& cameraPos) { // Use the particle shader glUseProgram(shaderProgram.program); // Get the uniform ID's cameraRightWorldspaceID = glGetUniformLocation(shaderProgram.program, "cameraRightWorldspace"); cameraUpWorldspaceID = glGetUniformLocation(shaderProgram.program, "cameraUpWorldspace"); projectionMatrixID = glGetUniformLocation(shaderProgram.program, "projection"); cameraPosID = glGetUniformLocation(shaderProgram.program, "cameraPos"); // Hardcoded the cameraRight and up direction because we are a 2D game and don't allow camera rotation glUniform3f(cameraRightWorldspaceID, 1.0f, 0.0f, 0.0f); glUniform3f(cameraUpWorldspaceID, 0.0f, 1.0f, 0.0f); glUniformMatrix3fv(projectionMatrixID, 1, GL_FALSE, (float*)&projection); glUniform2f(cameraPosID, cameraPos.x, cameraPos.y); prepRender(vertexBuffer); //This line make sure that every instance of a particle uses the same 4 verticies glVertexAttribDivisor(0, 0); // particles vertices : All particles use the same 4 verticies. The first digit must match the vertex index in the prepRender function //This make sure that every instance of a particle uses a new center position glVertexAttribDivisor(1, 1); // positions : one per particle. The first digit must match the position index in the prepRender function //This make sure that every instance of a particle uses a new colour glVertexAttribDivisor(2, 1); // color : one per particle. The first digit must match the color index in the prepRender function // Enabling and binding texture to slot 0 glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, particleTexture.texture_id); // Draw the particules glDrawArraysInstanced(GL_TRIANGLE_STRIP, 0, 4, particlesCount); //Disable the vertex attribute arrays used for the particle instances glDisableVertexAttribArray(0); glDisableVertexAttribArray(1); glDisableVertexAttribArray(2); glBindVertexArray(0); } void ParticleEmitter::updateGPU() { auto error = glGetError(); //These two blocks of code reallocate the buffers to stop the program from having to stop and wait for the previous draw calls to be done with the previous data in the buffer. This allows us to now add our new data to the buffers without waiting. glBindBuffer(GL_ARRAY_BUFFER, particlesCenterPositionAndSizeBuffer); glBufferData(GL_ARRAY_BUFFER, ParticleSystem::MaxParticles * 4 * sizeof(GLfloat), NULL, GL_STREAM_DRAW); // Buffer orphaning //This allows us to use the already allocated buffer from the previous line rather than reallocating a new buffer glBufferSubData(GL_ARRAY_BUFFER, 0, particlesCount * sizeof(GLfloat) * 4, particleCenterPositionAndSizeData); error = glGetError(); glBindBuffer(GL_ARRAY_BUFFER, particlesColorBuffer); glBufferData(GL_ARRAY_BUFFER, ParticleSystem::MaxParticles * 4 * sizeof(GLfloat), NULL, GL_STREAM_DRAW); // Buffer orphaning //This allows us to use the already allocated buffer from the previous line rather than reallocating a new buffer glBufferSubData(GL_ARRAY_BUFFER, 0, particlesCount * sizeof(GLfloat) * 4, particleColorData); error = glGetError(); assert(error == 0); } void ParticleEmitter::prepRender(GLuint vertexBuffer) { glBindVertexArray(VertexArrayID); updateGPU(); //If we don't explicitly declare these here we already have them from the animated meshes that are rendered before particle in the render function right now but explicitly declaring here as well so it isn't enabled by "accident" glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); GLenum error = glGetError(); //particle verticies glEnableVertexAttribArray(0); glBindBuffer(GL_ARRAY_BUFFER, vertexBuffer); glVertexAttribPointer( 0, // index. Must match the shader in variable number, also must match the value used in glVertexAttribDivisor 3, // size because each triangle has 3 vertices GL_FLOAT, // type GL_FALSE, // normalized 0, // stride. this is default value for this function 0 // array buffer offset. this is default value for this function ); error = glGetError(); assert(error == 0); // particles centers glEnableVertexAttribArray(1); glBindBuffer(GL_ARRAY_BUFFER, particlesCenterPositionAndSizeBuffer); glVertexAttribPointer( 1, // index. Must match the shader in variable number, also must match the value used in glVertexAttribDivisor 4, // size: each triangle has an x,y,z location and a size which is a size of 4 GL_FLOAT, // type GL_FALSE, // normalized 0, // stride. this is default value for this function 0 // array buffer offset. this is default value for this function ); error = glGetError(); assert(error == 0); // particle colours glEnableVertexAttribArray(2); glBindBuffer(GL_ARRAY_BUFFER, particlesColorBuffer); glVertexAttribPointer( 2, // index. Must match the shader in variable number, also must match the value used in glVertexAttribDivisor 4, // size: Each triangle has a colour which has values for each rgba which is 4 values. GL_FLOAT, // type GL_FALSE, // normalized 0, // stride. this is default value for this function 0 // array buffer offset. this is default value for this function ); error = glGetError(); assert(error == 0); } //Everything below here is for emitters BasicEmitter::BasicEmitter(int particlesPerSecond){ this->particlesPerSecond = particlesPerSecond; secSinceLastParticleSpawn = 0; } void BasicEmitter::simulateParticles(float elapsedMs, int numNewParticles) { float elapsedTimeSec = elapsedMs / 1000.0f; particlesCount = 0; for (int i = 0; i < ParticleSystem::MaxParticles; i++) { //Get a reference to the current particle to work with Particle& p = ParticlesContainer[i]; if (p.life > 0.0f) { // Decrease life p.life -= elapsedMs; if (p.life > 0.0f) { p.pos += p.speed * ((float)elapsedTimeSec); // Fill the GPU buffer particleCenterPositionAndSizeData[4 * particlesCount + 0] = p.pos.x; particleCenterPositionAndSizeData[4 * particlesCount + 1] = p.pos.y; particleCenterPositionAndSizeData[4 * particlesCount + 2] = p.pos.z; particleCenterPositionAndSizeData[4 * particlesCount + 3] = p.size; particleColorData[4 * particlesCount + 0] = p.r; particleColorData[4 * particlesCount + 1] = p.g; particleColorData[4 * particlesCount + 2] = p.b; particleColorData[4 * particlesCount + 3] = p.a; } particlesCount++; } //Spawn new particles if there is an empty index and we need to spawn a new particle else if (numNewParticles > 0) { createParticle(i); numNewParticles--; } } } void BasicEmitter::createParticle(int index) { ParticlesContainer[index].life = rand() % 10 * 1000 + 1200000; // This particle will live at least 120 seconds. ParticlesContainer[index].pos = glm::vec3(rand() % 3840, -512.0f, 0.0f); glm::vec3 mainVelocity = glm::vec3(0.5f, 10.0f, 0.0f); //Genertate a random velocity so not all particles follow the same direction glm::vec3 randomVelocity = glm::vec3( rand() % 25, rand() % 5, 0.0f ); ParticlesContainer[index].speed = mainVelocity + randomVelocity; ParticlesContainer[index].r = 1.0; ParticlesContainer[index].g = 1.0; ParticlesContainer[index].b = 1.0; ParticlesContainer[index].a = 1.0; //Generate a random size for each particle ParticlesContainer[index].size = (rand() % 20) + 20.0f; } void BasicEmitter::initEmitter() { // Create and compile our GLSL program from the shaders shaderProgram.loadFromFile("data/shaders/Particle.vs.glsl", "data/shaders/Particle.fs.glsl"); particleTexture.loadFromFile(objectsPath("candy-fluff-pink.png")); //Generate the VAO for this particle system glGenVertexArrays(1, &VertexArrayID); glBindVertexArray(VertexArrayID); GLenum error = glGetError(); error = glGetError(); // The VBO containing the positions and sizes of the particles glGenBuffers(1, &particlesCenterPositionAndSizeBuffer); glBindBuffer(GL_ARRAY_BUFFER, particlesCenterPositionAndSizeBuffer); // Initialize with empty (NULL) buffer : it will be updated later, each frame. glBufferData(GL_ARRAY_BUFFER, ParticleSystem::MaxParticles * 4 * sizeof(GLfloat), NULL, GL_STREAM_DRAW); // The VBO containing the colors of the particles //particles_color_buffer; glGenBuffers(1, &particlesColorBuffer); glBindBuffer(GL_ARRAY_BUFFER, particlesColorBuffer); // Initialize with empty (NULL) buffer : it will be updated later, each frame. glBufferData(GL_ARRAY_BUFFER, ParticleSystem::MaxParticles * 4 * sizeof(GLfloat), NULL, GL_STREAM_DRAW); } BlueCottonCandyEmitter::BlueCottonCandyEmitter(int particlesPerSecond) { this->particlesPerSecond = particlesPerSecond; secSinceLastParticleSpawn = 0; } void BlueCottonCandyEmitter::simulateParticles(float elapsedMs, int numNewParticles) { float elapsedTimeSec = elapsedMs / 1000.0f; particlesCount = 0; for (int i = 0; i < ParticleSystem::MaxParticles; i++) { //Get a reference to the current particle to work with Particle& p = ParticlesContainer[i]; if (p.life > 0.0f) { // Decrease life p.life -= elapsedMs; if (p.life > 0.0f) { p.pos += p.speed * ((float)elapsedTimeSec); // Fill the GPU buffer particleCenterPositionAndSizeData[4 * particlesCount + 0] = p.pos.x; particleCenterPositionAndSizeData[4 * particlesCount + 1] = p.pos.y; particleCenterPositionAndSizeData[4 * particlesCount + 2] = p.pos.z; particleCenterPositionAndSizeData[4 * particlesCount + 3] = p.size; particleColorData[4 * particlesCount + 0] = p.r; particleColorData[4 * particlesCount + 1] = p.g; particleColorData[4 * particlesCount + 2] = p.b; particleColorData[4 * particlesCount + 3] = p.a; } particlesCount++; } //Spawn new particles if there is an empty index and we need to spawn a new particle else if (numNewParticles > 0) { createParticle(i); numNewParticles--; } } } void BlueCottonCandyEmitter::createParticle(int index) { ParticlesContainer[index].life = rand() % 10 * 1000 + 1200000; // This particle will live at least 120 seconds. ParticlesContainer[index].pos = glm::vec3(rand() % 3840 , -512.0f, 0.0f); glm::vec3 mainVelocity = glm::vec3(0.5f, 10.0f, 0.0f); //Genertate a random velocity so not all particles follow the same direction glm::vec3 randomVelocity = glm::vec3( rand() % 25, rand() % 5, 0.0f ); ParticlesContainer[index].speed = mainVelocity + randomVelocity; ParticlesContainer[index].r = 1.0; ParticlesContainer[index].g = 1.0; ParticlesContainer[index].b = 1.0; ParticlesContainer[index].a = 1.0; //Generate a random size for each particle ParticlesContainer[index].size = (rand() % 20) + 20.0f; } void BlueCottonCandyEmitter::initEmitter() { // Create and compile our GLSL program from the shaders shaderProgram.loadFromFile("data/shaders/Particle.vs.glsl", "data/shaders/Particle.fs.glsl"); particleTexture.loadFromFile(objectsPath("candy-fluff-blue.png")); //Generate the VAO for this particle system glGenVertexArrays(1, &VertexArrayID); glBindVertexArray(VertexArrayID); GLenum error = glGetError(); error = glGetError(); // The VBO containing the positions and sizes of the particles glGenBuffers(1, &particlesCenterPositionAndSizeBuffer); glBindBuffer(GL_ARRAY_BUFFER, particlesCenterPositionAndSizeBuffer); // Initialize with empty (NULL) buffer : it will be updated later, each frame. glBufferData(GL_ARRAY_BUFFER, ParticleSystem::MaxParticles * 4 * sizeof(GLfloat), NULL, GL_STREAM_DRAW); // The VBO containing the colors of the particles //particles_color_buffer; glGenBuffers(1, &particlesColorBuffer); glBindBuffer(GL_ARRAY_BUFFER, particlesColorBuffer); // Initialize with empty (NULL) buffer : it will be updated later, each frame. glBufferData(GL_ARRAY_BUFFER, ParticleSystem::MaxParticles * 4 * sizeof(GLfloat), NULL, GL_STREAM_DRAW); }
8f1c3a4570d86881c053a8bef4bbaf9e28e62502
e85141e23eb38db4d4ad9a810e6817b73f0ad96f
/tagGame/Action.h
5147d5b066256821502a2a41b5a14af137357fd9
[ "AFL-2.1", "AFL-3.0", "LicenseRef-scancode-unknown-license-reference", "MIT" ]
permissive
lluisgomez/ai4games
7aeed3c038299b6a4321a7787c9f046d9d2f5ebf
b72be3648fa0da611b999aa01aec8560728bcdd7
refs/heads/master
2020-07-12T05:37:30.658627
2017-03-12T22:40:26
2017-03-12T22:40:26
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,140
h
Action.h
// ---------------------------------------------------------------------------- // // tagGame - Example code from the book: // // Artficial Intelligence for Computer Games: An Introduction // by John David Funge // // www.ai4games.org // // Source code distributed under the Copyright (c) 2003-2007, John David Funge // Original author: John David Funge (www.jfunge.com) // // Licensed under the Academic Free License version 3.0 // (for details see LICENSE.txt in this directory). // // ---------------------------------------------------------------------------- #ifndef TG_ACTION_H #define TG_ACTION_H #include "Vec.h" namespace tagGame { /// This class is for representing actions in the tag game. /// Currently, the only action is to select a speed and direction. class Action { public: Action(); Action(Action const& a); Action& operator=(Action const& a); inline void setDesiredDirection(RealVec const& direction); inline RealVec const& getDesiredDirection() const; inline void setDesiredSpeed(Real const speed); inline Real getDesiredSpeed() const; // TODO: give all objects output methds // TODO: put most of these TODOs into a bugzilla std::ostream& output(std::ostream& out) const; protected: private: // Direction and speed are separate so that a character can stop and still // remember which direction it was heading. Also avoids potential rounding // problems with vectors whose length might otherwise get close to 0. // direction is a unit vector RealVec direction; // speed is in the range [0, 1] Real speed; }; std::ostream& operator<<(std::ostream& out, Action const& a); void Action::setDesiredDirection(RealVec const& direction) { this->direction = direction; } RealVec const& Action::getDesiredDirection() const { return direction; } void Action::setDesiredSpeed(Real const speed) { this->speed = speed; } Real Action::getDesiredSpeed() const { return speed; } } #endif
25449d54782a0fec27771fd1d1ec84e26c8b45b1
0e71161baa94c48cda9cc42f3039d5a1aaf0cb28
/tree/binary_search_tree.cc
f19e0e224a7c7c7666889bf77628ae73682451d2
[]
no_license
stevealbertwong/code_interview
8be5bd86c44b1e61d26e6cbb6974749ff62b3c08
67e6462d3ffd8d01407ec46cd997fa9e383a327a
refs/heads/main
2023-08-27T16:43:53.400849
2021-11-06T09:16:55
2021-11-06T09:16:55
425,117,081
0
0
null
null
null
null
UTF-8
C++
false
false
3,902
cc
binary_search_tree.cc
/* Author: steven wong BST == BT with slightly complex add n very complex delete BST used to implement set and map pass pointer by reference since need to swap node g++ -std=c++11 binary_search_tree.cc -o binary_search_tree */ #include <iostream> #include <math.h> using namespace std; template <class T> struct TreeNode { // TreeNode<T> <- namespace TreeNode(T val, TreeNode<T> *left = NULL, TreeNode<T> *right = NULL) { this->value = val; this->left = left; this->right = right; } T value; TreeNode<T> *left; TreeNode<T> *right; }; template <class T> class BST{ // BST<T> <- namespace private: TreeNode<T> *root; void add_node_helper(TreeNode<T>*& node, T val); void delete_all_nodes(TreeNode<T>*& node); void delete_node_helper(TreeNode<T>*& node, T val); void print_helper(TreeNode<T>* node); public: BST(){}; ~BST(); void add_node(T val); void print(); void node_count(); void delete_node(T val); TreeNode<T>* getMin(TreeNode<T>* node); }; template <class T> BST<T>::~BST(){ delete_all_nodes(root); }; template <class T> void BST<T>::delete_all_nodes(TreeNode<T>*& node){ if(node!=NULL){ delete_all_nodes(node->left); delete_all_nodes(node->right); delete node; } } template <class T> void BST<T>::add_node_helper(TreeNode<T>*& node, T val){ // pointer by reference // does nothing if val == node->val if(node == NULL){ // base case: found empty spot node = new TreeNode<T>(val); // pointer by reference, else just local var } else if(val < node->value) { // goes left add_node_helper(node->left, val); } else if(val > node->value) { // goes right add_node_helper(node->right, val); } } template <class T> void BST<T>::add_node(T val){ add_node_helper(root, val); } template <class T> TreeNode<T>* BST<T>::getMin(TreeNode<T>* node){ if (node->left == NULL){ return node; } else { getMin(node->left); } } template <class T> void BST<T>::delete_node_helper(TreeNode<T>*& node, T val){ // pointer by reference // 1st: traverse to node if(node == NULL){ // base case: failed to find such node return; } else if(val < node->value) { // recurse left delete_node_helper(node->left, val); } else if(val > node->value) { // recurse right delete_node_helper(node->right, val); // 2nd: swap() to replace if no/single child // swap() w center(min right/max left) if both child } else if(val == node->value){ // found that node ! if(node->left && node->right == NULL){ // no child delete node; } else if (node->left == NULL){ // only right child TreeNode<T>* trash = node; node = node->right; // parent->left = parent->left->right delete trash; } else if (node->right == NULL){ // only left child TreeNode<T>* trash = node; node = node->left; // update parent's child addr -> SWAP ADDR delete trash; } else { // both children exist TreeNode<T>* mr_node = getMin(node->right); // max left or min right -> 1 right all left node->value = mr_node->value; // SWAP DATA // delete mr_node; // CANNOT -> since min node might have right child !!!!!!! delete_node_helper(node->right, mr_node->value); // delete min node } } } template <class T> void BST<T>::delete_node(T val){ delete_node_helper(root, val); } template <class T> void BST<T>::print_helper(TreeNode<T>* node){ if(node != NULL){ print_helper(node->left); cout << node->value << endl; print_helper(node->right); } } template <class T> void BST<T>::print(){ print_helper(root); } int main(int argc, char const *argv[]){ // TreeNode<int> n = TreeNode<int>(10); TreeNode<int> *n = new TreeNode<int>(10); BST<int> bst = BST<int>(); bst.add_node(10); bst.add_node(5); bst.add_node(1); bst.add_node(99); bst.add_node(16); bst.print(); bst.delete_node(16); bst.delete_node(1); bst.add_node(2); bst.print(); return 0; }
577f4a1d97bbf85201a5e4926fb6dbe6f419880f
8e5fe2174bc693409d14278374bddf42356103b7
/IContainers/IZdcSmdList.hh
42094d17a73422eef25eaf3332dd8171b996e9db
[]
no_license
iyounus/PHENIX_data_analysis_framework
882b6689bb048f82145bccb6068ca76774dd568b
0947c02ac09eb5be593c77a9baa73bd12ebffe64
refs/heads/master
2021-01-19T10:29:49.499214
2015-09-18T17:52:51
2015-09-18T17:52:51
42,703,530
1
0
null
null
null
null
UTF-8
C++
false
false
655
hh
IZdcSmdList.hh
//----------------------------------------------------------- // IZdcSmdList.hh // Created April 11 2009 // Imran Younus //----------------------------------------------------------- #ifndef IZDCSMDLIST_HH #define IZDCSMDLIST_HH #ifndef ROOT_TObject #include <TObject.h> #endif class TClonesArray; class IZdcSmd; class IZdcSmdList : public TObject { public: IZdcSmdList(); virtual ~IZdcSmdList(); void Reset(); unsigned short GetNZdcSmd() const { return nZdcSmds; } IZdcSmd* AddZdcSmd(); IZdcSmd* GetZdcSmd(); protected: unsigned short nZdcSmds; TClonesArray *zdcsmdList; private: ClassDef(IZdcSmdList,1); }; #endif
0cf2c29259fba12a4078a312c0b84da5d85107ff
9b26f8f0f77dcfa51397d257849e438f42511d78
/src/Jump.hpp
80d64d04543a4f5558d468d9ed50567dcb642573
[]
no_license
darwikey/ProjetCompilation
92ed965d326b2a28a0d5308679d0d5c7ce333612
3a426a85156861ed5c854c1e9896f6947c9cc424
refs/heads/master
2020-04-15T02:06:49.996059
2015-01-12T22:38:32
2015-01-12T22:38:32
27,715,489
0
1
null
2015-01-04T20:49:23
2014-12-08T13:13:58
C++
UTF-8
C++
false
false
2,007
hpp
Jump.hpp
#ifndef JUMP_HPP #define JUMP_HPP #include <string> #include <ostream> #include <vector> #include <stdexcept> #include "Statement.hpp" #include "Expression.hpp" class Jump : public Statement{ public: Jump(Expression* fExpression = nullptr) : expression(fExpression){ } virtual std::string get_code(std::vector<Block*> fParent_blocks, Function* fFunction, bool fVectorize = false) override { std::string code; if (expression != nullptr){ code += expression->get_code(fParent_blocks, fFunction); //Verif type Type expr_type = expression->get_expression_type(fParent_blocks); if (fFunction->declarator->structure == Declarator_structure::VARIABLE){ if (fFunction->declarator->type == Declarator_type::INT && expr_type != Type::INT) throw std::logic_error("function must return a int"); else if (fFunction->declarator->type == Declarator_type::FLOAT && expr_type != Type::FLOAT) throw std::logic_error("function must return a float"); else if (fFunction->declarator->type == Declarator_type::VOID) throw std::logic_error("void function can't return a value"); } else if (fFunction->declarator->structure == Declarator_structure::POINTER && !(expr_type == Type::POINTER || expr_type == Type::FLOAT_POINTER)){ throw std::logic_error("function must return a pointer"); } // Si on retourne un float on l'empile sur la pile des floats if (expr_type == Type::FLOAT){ code += "subl $4, %esp\n"; code += "movss %xmm0, (%esp)\n"; code += "flds (%esp)\n"; code += "add $4, %esp\n"; } } else{ // return; // Verif type if (!(fFunction->declarator->type == Declarator_type::VOID && fFunction->declarator->structure != Declarator_structure::VARIABLE)){ throw std::logic_error("non void function have to return a value"); } } // fin de la fonction code += "leave\n"; code += "ret\n\n"; return code; } private: Expression* expression; }; #endif
96f56b851c6202248b031e530a27da44861a0fc9
8c4db67435f57cbd4b712ec0c2baaf445e3cf827
/RushOrder.h
a65c0f2fa786f9e331bce14a179722877426a454
[]
no_license
Dmitriy1984-tech/Exam_Order
880963518a0e78bc7ec5a463165ada967aeae26f
f6c063f57d3ee8348f23e61385220bb3aecbe8a2
refs/heads/main
2023-05-01T14:45:20.915105
2021-05-15T10:14:16
2021-05-15T10:14:16
367,598,864
0
0
null
null
null
null
UTF-8
C++
false
false
583
h
RushOrder.h
#pragma once #include "Order.h" class RushOrder : public Order { protected: string courier; Date deliveryDate; public: RushOrder(); RushOrder(Date date, Time_ time, string id, string courier, Date deliveryDate); ~RushOrder(); void setCourier(string courier); string getCourier(); void setDeliveryDate(Date deliveryDate); Date getDeliveryDate(); virtual string type() override; virtual string toString() override; virtual void save(ofstream& file) override; virtual void load(ifstream& file) override; };
490159825f372e4e6a6d942da4a2424aba23a817
ea449cfc2fd81888a4a3641d7038643d5292dc9b
/week-10/170103/server.cpp
0e959dbbe14dbbbfac6a8a21d1bad7d60249f26a
[]
no_license
greenfox-zerda-sparta/medeaeva
4cfddb2e47d35e11d73030e64dc484682bb8a8be
af505e518607243e7bceee246072942ded1fef8e
refs/heads/master
2021-01-12T17:18:14.778707
2017-01-05T14:22:31
2017-01-05T14:22:31
71,544,467
0
0
null
null
null
null
UTF-8
C++
false
false
1,135
cpp
server.cpp
#include <iostream> #include <SDL2/SDL.h> #include <SDL2/SDL_net.h> #include <string> using namespace std; int main(int argc,char** argv) { SDL_Init(SDL_INIT_EVERYTHING); SDLNet_Init(); IPaddress ip; SDLNet_ResolveHost(&ip, NULL, 1234); TCPsocket server = SDLNet_TCP_Open(&ip); TCPsocket client; std::string input; std::cout << "Type message plz" << endl; getline(std::cin, input); unsigned int input_lenght = input.length(); /*const char* text = new char[input.length() + 1]; strcopy_s(text, input_lenght, input); int message_lenght = sizeof(text)/sizeof(char) + 1; */ char text[input_lenght + 1]; for (unsigned int i = 0; i < input.length(); ++i) { text[i] = input[i]; } text[input_lenght] = '\0'; int message_lenght = sizeof(text)/sizeof(char) + 1; cout << "this is the char array: " << text << endl; while (1) { client = SDLNet_TCP_Accept(server); if (client) { SDLNet_TCP_Send(client, text, message_lenght); SDLNet_TCP_Close(client); break; } } return 0; }
60d4c23336c23887314fa1296b3744ec839020e1
0e0a39875ad5089ca1d49d1e1c68d6ef337941ff
/src/Resources/ResourceIndexer.cpp
01fe8a7d16b9256deb635b086d5e33c5a84286dd
[ "BSD-3-Clause", "BSD-2-Clause" ]
permissive
FloodProject/flood
aeb30ba9eb969ec2470bd34be8260423cd83ab9f
466ad3f4d8758989b883f089f67fbc24dcb29abd
refs/heads/master
2020-05-18T01:56:45.619407
2016-02-14T17:00:53
2016-02-14T17:18:40
4,555,061
6
2
null
2014-06-21T18:08:53
2012-06-05T02:49:39
C#
WINDOWS-1252
C++
false
false
3,467
cpp
ResourceIndexer.cpp
/************************************************************************ * * Flood Project © (2008-201x) * Licensed under the simplified BSD license. All rights reserved. * ************************************************************************/ #include "Resources/API.h" #ifdef ENABLE_RESOURCE_INDEXER #include "Resources/ResourceIndexer.h" #include "Resources/ResourceManager.h" #include "Resources/ResourceLoader.h" #include "Core/Archive.h" #include "Core/Utilities.h" #include "Core/Concurrency.h" #include "Core/Stream.h" #include "Core/Log.h" #include "Core/Math/Hash.h" NAMESPACE_RESOURCES_BEGIN //-----------------------------------// ResourceIndexer::ResourceIndexer() { } //-----------------------------------// ResourceIndexer::~ResourceIndexer() { } //-----------------------------------// void ResourceIndexer::update() { // Send pending events. ResourceMetadata metadata; while( resourcesIndexed.try_pop_front(metadata) ) { onResourceIndexed(metadata); } } //-----------------------------------// static Task* CreateIndexTask(ResourceIndexer* index, const Path& resPath) { Path* path = Allocate(AllocatorGetObject(index), Path); *path = resPath; Task* task = Allocate(AllocatorGetObject(index), Task); task->callback.Bind(index, &ResourceIndexer::indexResources); task->userdata = path; TaskPool* taskPool = GetResourceManager()->getTaskPool(); taskPool->add(task, 0); return task; } //-----------------------------------// void ResourceIndexer::addArchive(Archive* archive) { Vector<Path> res; archive->enumerateFiles(res); for(auto& i : res) { Path fullPath = archive->combinePath(i); CreateIndexTask(this, fullPath); } } //-----------------------------------// static bool GetResourceGroupFromPath(const Path& path, ResourceGroup& group) { String ext = PathGetFileExtension(path); ResourceManager* res = GetResourceManager(); ResourceLoader* loader = res->findLoader(ext); if( !loader ) return false; group = loader->getResourceGroup(); return true; } //-----------------------------------// void ResourceIndexer::indexResources(Task* task) { Path& tempPath = *((Path*) task->userdata); Path path = tempPath; DeallocateObject(&tempPath); Path basePath = PathGetFile(path); ResourceGroup group; if( !GetResourceGroupFromPath(path, group) ) { //LogDebug("Error indexing resource '%s': no loader was found", basePath.CString()); return; } //LogDebug("Indexing file '%s'", basePath.CString()); FileStream stream(path, StreamOpenMode::Read); if( !stream.isValid ) { LogWarn("Error indexing resource '%s': cannot open stream", basePath.CString()); return; } Vector<byte> data; stream.read(data); stream.close(); if( data.Empty() ) { LogWarn("Resource '%s' is empty", basePath.CString()); return; } uint32 hash = HashMurmur2(0xBEEF, &data[0], data.Size()); ResourceMetadata metadata; metadata.hash = hash; metadata.path = path; metadata.group = group; resourcesIndexed.push_back(metadata); } //-----------------------------------// NAMESPACE_RESOURCES_END #endif
b737c9f68025dfdaad2c1264d404fd264c20a70f
25ea5cd0b59f92951efce8e899b595b01b371fa8
/include/character/character.h
1c6d24ae9b7829e0544058e70155996cb1cbd54f
[ "BSL-1.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
incomingstick/OpenRPG
c0fc18c450e597f2a9c2e45161c868e47f579633
24856345cf85a4e47da6e446640e60d36b078794
refs/heads/master
2022-11-23T19:21:30.804224
2022-08-13T18:57:30
2022-08-13T18:57:30
71,913,026
139
41
NOASSERTION
2022-11-14T19:50:01
2016-10-25T15:46:54
C++
UTF-8
C++
false
false
14,913
h
character.h
/* characters - character.h Created on: Jan 30, 2017 OpenRPG Software License - Version 1.0 - February 10th, 2017 <https://openrpg.io/about/license/> This is free software: you are free to change and redistribute it. There is NO WARRANTY, to the extent permitted by law. */ #ifndef SRC_CHARACTER_H_ #define SRC_CHARACTER_H_ #ifdef _WIN32 # include "exports/character_exports.h" #else # define CHARACTER_EXPORT #endif #include "ability-scores.h" #include "skills.h" #include "races.h" #include "backgrounds.h" #include "classes.h" namespace ORPG { /* predefinition of Character class incase functions in the Characters namespace need it */ class Character; namespace Characters { /** * @desc prints the version info when -V or --version is an argument to the command. * This adhears to the GNU standard for version printing, and immediately terminates * the program with exit code EXIT_SUCCESS **/ void CHARACTER_EXPORT print_version_flag(); /** * @desc prints the help info when -h or --help is an argument to the command. * This adhears to the GNU standard for help printing, and immediately terminates * the program with exit code EXIT_SUCCESS **/ void CHARACTER_EXPORT print_help_flag(); /** * @desc prints the version info when version, ver, v, or V are called in the ORPG shell. * Because this is called from within our ORPG shell, the program will continue running. **/ void CHARACTER_EXPORT print_basic_version(); /** * @desc prints the help info when help, h, or H are called in the ORPG shell. * Because this is called from within our ORPG shell, the program will continue running. **/ void CHARACTER_EXPORT print_basic_help(); /** * TODO comments * NOTE(incomingstick): This function is not exported because it does not yet need to be **/ class RaceSelector { private: struct race_node { uint raceID; bool required; race_node* parent; std::vector<race_node* > children; }; race_node* head; race_node* current; race_node* allocate_node(uint raceID, bool required, race_node* parent); public: RaceSelector(); ~RaceSelector(); void reset() { current = head; }; std::vector<std::string> current_options(); bool has_options(); void select_option(int8 index); uint current_id(); }; /** * @desc Currently this function just checks to ensure the string contains * only digits, and returns true. It will return false otherwise. * If the provided string is empty, this function returns false. * * TODO(incomingstick): ensure we are at least coming in as an int32. * * NOTE(incomingsting): This could, and probably should, be improved * to also ensure we are within the bounds on the "question" being asked. * * NOTE(incomingstick): This function is not exported because it does not yet need to be * * @param: string check - this string to be checked * @return bool - returns true if check contains only numbers **/ bool safety_check_stoi(std::string check); /** * @desc This function is built to work in tandem specifically with the Character * module. It takes in a CharacterFactory and checks what stage it is * currently in, prompting the user for any required input from cin. * * NOTE(incomingsting): currently, we are only using numbered input * (i.e '1') so the above purity check function strictly ensures the input * will only contain digits. If it does not, it will continue to prompt the * user. * * @param: CharacterFactory factory - the factory to check and prompt from * @return auto - the selected input **/ int request_selection(RaceSelector factory); /** * @desc This function is build to work specifically in tandem with the Character * module. It prompts to stdout a request for user input, from stdin, to help determine * whether or not we should just randomly create the character * * TODO character creator switch ('-r' argv should ALSO handle this) * * @return bool - true if user wants to be random, false otherwise **/ bool CHARACTER_EXPORT request_is_random(); /** * @desc This function prompts the user for their race by using the RaceSelector * to first prompt to stdout the base race, requesting a corresponding number * via stdin. It repeats this process for the subrace, and will continue prompting * until no other race types could possibly be chosen. * * @return auto - the current race ID from the RaceSelector **/ CHARACTER_EXPORT Race* request_race(); /** * @desc This function prompts the user, via stdout, for 6 numbers to * use as their characters abilities. It specifically request their * ability scores in the following order: Strength, Dexterity, * Constitution, Intelligence, Wisdom, Charisma. * * NOTE(incomingsting): currently, we are only using numbered input * (i.e '12') so the above purity check function strictly ensures the input * will only contain digits. If it does not, it will continue to prompt the * user. * * This function could likely also be cleaner. Its just a giant switch * currently, which looks kinda ungly, and takes up space. Like this comment. * * @return AbilityScores - an AbilityScores object containing the users input * scores **/ CHARACTER_EXPORT AbilityScores* request_scores(); /** * @desc This function prompts the user via stdout for a name, and reading * from stdin the input. We use the safeGetline function via the ORPG::Utils * namespace to ensure integrity across platforms. * * @return string - the user input string to be used as a name **/ std::string CHARACTER_EXPORT request_name(); /** * @desc prints "Background\n" to stdout * * TODO(incomingstick): Add backgrounds * * @return bool - always will return true **/ uint CHARACTER_EXPORT request_background(); /** * @desc prints "Wizard Class Automatically Chosen\n" to stdout * and returns a pointer to a new Wizard. * * TODO(incomingstick): Add more character classes * * @return CharacterClass* - always will return a pointer to a Wizard **/ CHARACTER_EXPORT CharacterClass* request_class(); /** * @desc prints "Skill select based on class\n" to stdout * * TODO(incomingstick): Improve skills once classes are added * * @return bool - always will return true **/ CHARACTER_EXPORT Skills* request_skills(); /** * @desc prints "Hit points\n" to stdout * * TODO(incomingstick): Set hitpoints based on classes hit die * * @return bool - always will return true **/ bool CHARACTER_EXPORT request_hitpoints(CharacterClass* classPtr); /** * @desc prints "Equipment\n" to stdout * * TODO(incomingstick): Choose equipment based on class * and background * * @return bool - always will return true **/ bool CHARACTER_EXPORT request_equipment(); /** * @desc import_character takes in the location of a file as a string * and attempts to load it as a character class. If a new Character is * able to be created from the file, it will return a pointer to that * character. * * @return Character* - a pointer to a character created via the file **/ CHARACTER_EXPORT Character* import_character(std::string file); } /* NOTE: These are just the 5E character requirements */ /* an arrray that holds the EXP needed for each level */ extern const int CHARACTER_EXPORT EXP[]; enum CHARACTER_EXPORT Alignment { LawfulGood, NeutralGood, ChaoticGood, LawfulNeutral, TrueNeutral, ChaoticNeutral, LawfulEvil, NeutralEvil, ChaoticEvil }; /** * An enum containing genders * * NOTE(incomingstick): How far do we want to take this? We could * put ourselves in a tricky place if this is done wrong. **/ enum CHARACTER_EXPORT Gender { Male, Female, Agender }; enum CHARACTER_EXPORT Size { Tiny, // 2½ by 2½ ft. [under 2 feet tall] Small, // 5 by 5 ft. [2 to 4 feet tall] Medium, // 5 by 5 ft. [4 to 8 feet tall] Large, // 10 by 10 ft. [8 to 12 feet tall] Huge, // 15 by 15 ft. [12 to 16 feet tall] Gatgantuan // 20 by 20 ft or larger [taller than 16 feet] }; enum CHARACTER_EXPORT VisionType { Normal, Blindsight, DarkVision, TrueSight }; struct CHARACTER_EXPORT Vision { VisionType type; // type of sight int radius; // radius of vision in feet (-1 == infinite IF unobstructed) }; /* Generates a stat > 1 && < 20 */ uint8 CHARACTER_EXPORT gen_stat(); /* Generates an array of stats > 1 && < 20 */ std::vector<uint8> CHARACTER_EXPORT ability_score_vector(); /** * returns an integer representation of the passed abilities modifier * * NOTE(incomingstick): This is intended to always round down. Data loss is acceptable. **/ inline int8 CHARACTER_EXPORT modifier(int abil) { return abil / 2 - 5; }; // TODO take an in depth look at what should and should not be public here class CHARACTER_EXPORT Character { private: Race* race; // The race of our character AbilityScores* abils; // struct of ability scores CharacterClass* cClass; // the characters class Background* bg; // the characters background Skills* skills; // struct of skill checks Alignment alignment; // the character alignment Gender gender; // the characters gender Size size; // the size type struct Vision vision; // information about the characters vision std::string firstName; // the characters first name std::string lastName; // the characters first name int curr_hp; // current hit points int temp_hp; // temporary hit points int max_hp; // maximum hit points int prof; // proficiency bonus int level; // character level total int curr_exp; // current experience int max_exp; // experience needed for next level std::vector<Language> langs; // the array of known languages uint8 age; // the age of the character void Initialize(); std::string format_mod(int mod, int spaces); public: Character(Race* racePtr = Characters::new_random_race(), AbilityScores* ab = new AbilityScores, CharacterClass* classPtr = Characters::new_random_character_class(), const int bgID = -1, Skills* sk = new Skills, std::string name = ""); ~Character(); void update_skills(); // Returns a copy of our Ability abils struct AbilityScores get_ability_copy() { return *abils; }; // Returns a copy of our Skills skills struct // NOTE(var_username): Commented out because I broke it // Skills get_skills_copy() { return skills; }; /* TODO(incomingstick): We don't need all of these functions, however they could still be useful. Pros and Cons? */ /* accessor functions for ability scores */ uint8 ABILITY_SCORE(EnumAbilityScore score) { return abils->get_score(score); } uint8 STR() { return abils->get_score(EnumAbilityScore::STR); }; uint8 DEX() { return abils->get_score(EnumAbilityScore::DEX); }; uint8 CON() { return abils->get_score(EnumAbilityScore::CON); }; uint8 INT() { return abils->get_score(EnumAbilityScore::INT); }; uint8 WIS() { return abils->get_score(EnumAbilityScore::WIS); }; uint8 CHA() { return abils->get_score(EnumAbilityScore::CHA); }; /* accessor functions for ability score modifiers */ int8 SCORE_MOD(EnumAbilityScore score) { return abils->get_mod(score); } int8 STR_MOD() { return abils->get_mod(EnumAbilityScore::STR); }; int8 DEX_MOD() { return abils->get_mod(EnumAbilityScore::DEX); }; int8 CON_MOD() { return abils->get_mod(EnumAbilityScore::CON); }; int8 INT_MOD() { return abils->get_mod(EnumAbilityScore::INT); }; int8 WIS_MOD() { return abils->get_mod(EnumAbilityScore::WIS); }; int8 CHA_MOD() { return abils->get_mod(EnumAbilityScore::CHA); }; /* accessor functions for ability score saves */ int8 SCORE_SAVE(EnumAbilityScore score) { return abils->get_save(score); } int8 STR_SAVE() { return abils->get_save(EnumAbilityScore::STR); }; int8 DEX_SAVE() { return abils->get_save(EnumAbilityScore::DEX); }; int8 CON_SAVE() { return abils->get_save(EnumAbilityScore::CON); }; int8 INT_SAVE() { return abils->get_save(EnumAbilityScore::INT); }; int8 WIS_SAVE() { return abils->get_save(EnumAbilityScore::WIS); }; int8 CHA_SAVE() { return abils->get_save(EnumAbilityScore::CHA); }; int get_proficiency_bonus() { return prof; }; // allows quick conversion of a skill for its passive check int8 passive_stat(int mod) { return 8 + prof + mod; }; std::string to_string(); std::string to_ascii_sheet(); }; } #endif /* SRC_CHARACTER_H_ */
82a9e15b35767d7631a95b7fa778800ed5b15902
16a81b983122e70bdc3407aebaf6080e405151c9
/osquery_profiles.cpp
8f43165432dcaa3dd0cf4a0482c1482e424fc54f
[]
no_license
headmin/osquery-profiles
1bb4f71c6a14d6a0db20fa4a11782a27720eb3b3
d8864129b69959ed9cee1ac8f294c9cf69f25990
refs/heads/master
2021-01-12T12:11:11.286703
2016-07-22T19:22:07
2016-07-22T19:22:07
null
0
0
null
null
null
null
UTF-8
C++
false
false
9,623
cpp
osquery_profiles.cpp
#include <osquery/sdk.h> #include <osquery/system.h> #include <iomanip> #include <sstream> #include <boost/algorithm/string.hpp> #include <boost/algorithm/string/predicate.hpp> #include <boost/property_tree/json_parser.hpp> using namespace osquery; namespace pt = boost::property_tree; /* * This is a helper function to run a subprocess and capture the output. */ Status runCommand(const std::string& command, std::string& output) { char buffer[1024] = {0}; FILE* stream = popen(command.c_str(), "r"); if (stream == nullptr) { return Status(1); } output.clear(); while (fgets(buffer, sizeof(buffer), stream) != nullptr) { output.append(buffer); } pclose(stream); return Status(0, "OK"); } /* * Helper function, mostly copied from osquery's source code. * * This function extracts a list of usernames given in the input query. */ QueryData usersFromContext(const QueryContext& context, bool all = false) { QueryData users; // If the user gave a 'username' constraint, get the user with that username // (this will helpfully also not do anything if the user does not exist). if (context.hasConstraint("username", EQUALS)) { context.forEachConstraint( "username", EQUALS, ([&users](const std::string& expr) { auto user = SQL::selectAllFrom("users", "username", EQUALS, expr); users.insert(users.end(), user.begin(), user.end()); })); } else if (!all) { // The user did not give a username, and did not want everything - return // ourselves. users = SQL::selectAllFrom("users", "uid", EQUALS, std::to_string(getuid())); } else { // Return all users. users = SQL::selectAllFrom("users"); } return users; } /* * This helper function will parse the output of the `profiles` command and * call the given callback with each parsed result. */ template<typename Fn> Status parseProfile(const std::string& commandOutput, const std::string& username, Fn callback) { // Handle the case where the user does not exist. if (boost::starts_with(commandOutput, "profiles: the user could not be found")) { return Status(1, "User not found"); } // The root key of the plist is either the username, or the literal string // "_computerlevel" for system-wide profiles. std::string rootKey; if (username.length() > 0) { rootKey = username; } else { rootKey = "_computerlevel"; } pt::ptree tree; if (parsePlistContent(commandOutput, tree).ok()) { pt::ptree root; try { root = tree.get_child(rootKey); } catch (const pt::ptree_bad_path&) { return Status(1, "No profiles"); } for (const auto& it : root) { auto profile = it.second; callback(username, profile); } } return Status(0, "OK"); } /* * This helper function will extract all usernames from the given context (if * any), run the `profiles` tool to retrieve all profiles for those users, and * then call the given callback with the resulting parsed profile data. */ template<typename Fn> Status iterateProfiles(QueryContext& request, Fn callback) { std::string commandOutput; // If the caller is requesting a join against the user, then we generate // information from that user - otherwise, we grab the system-wide // profiles. if (request.constraints["username"].notExistsOrMatches("")) { // Get system profiles if (runCommand("/usr/bin/profiles -C -o stdout-xml", commandOutput).ok()) { // TODO: error handling auto result = parseProfile(commandOutput, "", callback); if (!result.ok()) { return result; } } } else { auto users = usersFromContext(request); for (const auto& row : users) { if (row.count("username") > 0) { auto username = row.at("username"); // NOTE: This is somewhat vulnerable to shell injection. Currently, // we're "safe" because the `usersFromContext` function only returns // rows where the user actually exists - take care. auto command = "/usr/bin/profiles -L -o stdout-xml -U " + username; if (runCommand(command, commandOutput).ok()) { auto result = parseProfile(commandOutput, username, callback); if (!result.ok()) { return result; } } } } } return Status(0, "OK"); } /* * This table plugin creates the `profiles` table, which returns all * configuration profiles that are currently installed on the system. */ class ProfilesTablePlugin : public TablePlugin { private: TableColumns columns() const { return { std::make_tuple("username", TEXT_TYPE, DEFAULT), std::make_tuple("type", TEXT_TYPE, DEFAULT), std::make_tuple("identifier", TEXT_TYPE, DEFAULT), std::make_tuple("display_name", TEXT_TYPE, DEFAULT), std::make_tuple("description", TEXT_TYPE, DEFAULT), std::make_tuple("organization", TEXT_TYPE, DEFAULT), std::make_tuple("verified", INTEGER_TYPE, DEFAULT), std::make_tuple("removal_allowed", INTEGER_TYPE, DEFAULT), // TODO: add a 'version' column with the 'ProfileVersion' key? //std::make_tuple("version", INTEGER_TYPE, DEFAULT), }; } QueryData generate(QueryContext& request) { QueryData results; // TODO: do we want to handle error returns here? iterateProfiles(request, [&](const std::string& username, pt::ptree& profile) { Row r; r["username"] = username; r["identifier"] = profile.get<std::string>("ProfileIdentifier", ""); r["display_name"] = profile.get<std::string>("ProfileDisplayName", ""); r["description"] = profile.get<std::string>("ProfileDescription", ""); r["organization"] = profile.get<std::string>("ProfileOrganization", ""); r["type"] = profile.get<std::string>("ProfileType", ""); if (profile.get<std::string>("ProfileVerificationState", "") == "verified") { r["verified"] = INTEGER(1); } else { r["verified"] = INTEGER(0); } // The flag is actually 'ProfileRemovalDisallowed', which is set to 'true' when the // profile cannot be removed. if (profile.get<std::string>("ProfileRemovalDisallowed", "") == "true") { r["removal_allowed"] = INTEGER(0); } else { r["removal_allowed"] = INTEGER(1); } results.push_back(r); }); return results; } }; /* * This table plugin creates the `profile_items` table, which returns all * items in the given configuration profile. */ class ProfileItemsTablePlugin : public TablePlugin { private: TableColumns columns() const { return { std::make_tuple("username", TEXT_TYPE, DEFAULT), std::make_tuple("profile_identifier", TEXT_TYPE, DEFAULT), std::make_tuple("type", TEXT_TYPE, DEFAULT), std::make_tuple("identifier", TEXT_TYPE, DEFAULT), std::make_tuple("display_name", TEXT_TYPE, DEFAULT), std::make_tuple("description", TEXT_TYPE, DEFAULT), std::make_tuple("organization", TEXT_TYPE, DEFAULT), std::make_tuple("content", TEXT_TYPE, DEFAULT), // TODO: add a 'version' column with the 'PayloadVersion' key? //std::make_tuple("version", INTEGER_TYPE, DEFAULT), }; } QueryData generate(QueryContext& request) { QueryData results; // All profiles we want to read. auto wantedProfiles = request.constraints["profile_identifier"].getAll(EQUALS); // For all profiles that match our constraints... // TODO: do we want to handle error returns here? iterateProfiles(request, [&](const std::string& username, pt::ptree& profile) { // Get this profile's identifier. auto identifier = profile.get<std::string>("ProfileIdentifier", ""); // If we don't care about this profile, we just continue. if (wantedProfiles.find(identifier) == wantedProfiles.end()) { return; } // Find all payloads in this profile, continuing if there are none. pt::ptree payloads; try { payloads = profile.get_child("ProfileItems"); } catch (const pt::ptree_bad_path&) { return; } for (const auto& it : payloads) { auto payload = it.second; Row r; r["profile_identifier"] = identifier; r["type"] = payload.get<std::string>("PayloadType", ""); r["identifier"] = payload.get<std::string>("PayloadIdentifier", ""); r["display_name"] = payload.get<std::string>("PayloadDisplayName", ""); r["description"] = payload.get<std::string>("PayloadDescription", ""); r["organization"] = payload.get<std::string>("PayloadOrganization", ""); std::string content; try { std::ostringstream buf; pt::write_json(buf, payload.get_child("PayloadContent"), false); buf.flush(); content = buf.str(); } catch (const pt::ptree_bad_path&) { // Do nothing. } boost::algorithm::trim_right(content); r["content"] = content; results.push_back(r); } }); return results; } }; REGISTER_EXTERNAL(ProfilesTablePlugin, "table", "profiles"); REGISTER_EXTERNAL(ProfileItemsTablePlugin, "table", "profile_items"); int main(int argc, char* argv[]) { osquery::Initializer runner(argc, argv, OSQUERY_EXTENSION); // Connect to osqueryi or osqueryd. auto status = startExtension("profiles", "0.0.1"); if (!status.ok()) { LOG(ERROR) << status.getMessage(); runner.requestShutdown(status.getCode()); } // Finally wait for a signal / interrupt to shutdown. runner.waitForShutdown(); return 0; }
13e5ad5643b9e766bba5b0a457e5f9fabad22f0a
38490a06760127b9f284d8a0d40c47642eebe38a
/190516/190516/NewMemory02.cpp
b0e0fdfcf97b01084b7776b7eedbf81cc26c57b5
[]
no_license
SSSOy/2019_CPP
bb7e6a8373f43978b6ab1c03c71f7028428e39e2
aea2ba91737f897c4cee2390176ddcee4d07a9f3
refs/heads/master
2020-09-28T23:11:32.236445
2019-12-09T14:07:10
2019-12-09T14:07:10
226,880,907
0
0
null
null
null
null
UTF-8
C++
false
false
176
cpp
NewMemory02.cpp
#include <iostream> using namespace std; void main() { int *ptr = new int[4]; for (int i = 0; i < 4; i++) { ptr[i] = 10 + i; cout << ptr[i] << endl; } delete[] ptr; }
1152e783081cb0422b04c2d389b2ae3fae18a28f
2d0ecc01a2876c52daad91f50c51cb5f052daf44
/offer/二进制中1的个数.cpp
79df509781296a318e6ff8013e45e38404f65954
[]
no_license
shimaomao/language
353cafdc9758142bbc2421b443070ec2942e62b2
4f1244c7222b07b03d13e534b0ee9340c3b43c07
refs/heads/master
2020-06-18T00:01:36.040333
2018-09-04T01:58:40
2018-09-04T01:58:40
null
0
0
null
null
null
null
UTF-8
C++
false
false
492
cpp
二进制中1的个数.cpp
#include <iostream> #include <cstring> #include <cstdio> #include <cmath> #include <string> #include <list> #include <queue> #include <deque> #include <vector> #include <map> #include <set> using namespace std; // int count(int num) { int cnt = 0; while(num) { cnt++; num = num & (num-1); } return cnt; } int main() { int T, num; cin >> T; while(T--) { scanf("%d", &num); cout << count(num) << "\n"; } return 0; }
a79744a5a477b901117d454ce24531fabb9c2dd9
9d51ac726e7328365605966a19c20b0d4aa45628
/source/Actors.cpp
050ce461ed87142f734271f088ff4ca80b78e966
[ "MIT" ]
permissive
TrueFinch/Roguelike_game
d139a98c52d74b30d6d1162c71fb70ccab89ea80
332b5209948e9c323b3976a8521485dbf4fc366a
refs/heads/master
2021-07-16T08:19:14.199483
2018-07-14T04:30:06
2018-07-14T04:30:06
133,841,224
0
0
null
null
null
null
UTF-8
C++
false
false
4,257
cpp
Actors.cpp
// // Created by truefinch on 20.05.18. // #include <Actors.h> #include <cmath> #include <cassert> #include <utility> #include <ncurses.h> void actor::Actor::setPosition(Point position) { this->pos_ = position; } Point actor::Actor::getPosition() const { return this->pos_; } void actor::Actor::setLiveSymbol(char symbol) { live_symbol_ = symbol; } char actor::Actor::getLiveSymbol() const { return live_symbol_; } void actor::Actor::setDeadSymbol(char symbol) { dead_symbol_ = symbol; } char actor::Actor::getDeadSymbol() const { return dead_symbol_; } std::string actor::Actor::getName() const { return name_; } enums::ActorID actor::Actor::getID() const { return id_; } void actor::Actor::isDead(bool is_dead) { is_dead_ = is_dead; } bool actor::Actor::isDead() const { return is_dead_; } void actor::Actor::isImmortal(bool is_immortal) { is_immortal_ = is_immortal; } bool actor::Actor::isImmortal() const { return is_immortal_; } void actor::ActiveActor::setMaxHealthPoints(int hp) { max_health_points_ = hp; } int actor::ActiveActor::getMaxHealthPoints() const { return max_health_points_; } void actor::ActiveActor::setCurHealthPoints(int hp) { if (!this->is_dead_) { cur_health_points_ = (hp > max_health_points_) ? (max_health_points_) : (hp); } if ((cur_health_points_ <= 0) and (!this->is_immortal_)) { this->is_dead_ = true; } } int actor::ActiveActor::getCurHealthPoints() const { return cur_health_points_; } void actor::ActiveActor::setMaxManaPoints(int mp) { max_mana_points_ = mp; } int actor::ActiveActor::getMaxManaPoints() const { return max_mana_points_; } void actor::ActiveActor::setCurManaPoints(int mp) { if (mp > max_mana_points_) { cur_mana_points_ = max_mana_points_; } else { cur_mana_points_ = mp; } } int actor::ActiveActor::getCurManaPoints() const { return cur_mana_points_; } void actor::ActiveActor::setDamagePoints(int dp) { damage_points_ = dp; } int actor::ActiveActor::getDamagePoints() const { return damage_points_; } void actor::ActiveActor::setVisibilityPoints(int vp) { visibility_points_ = vp; } int actor::ActiveActor::getVisibilityPoints() const { return visibility_points_; } void actor::ActiveActor::upLevelPoints() { ++level_points_; this->setMaxHealthPoints(max_health_points_ + max_health_points_ * level_points_ / 10); this->setCurHealthPoints(max_health_points_); this->setMaxManaPoints(max_mana_points_ + max_mana_points_ * level_points_ / 10); this->setCurManaPoints(max_mana_points_); this->setMaxScorePoints(max_score_points_ + max_score_points_ * level_points_ / 10); } void actor::ActiveActor::downLevelPoints() { if (level_points_ > 0) { (--level_points_); } else { level_points_ = 1; } } int actor::ActiveActor::getLevelPoints() const { return level_points_; } void actor::ActiveActor::setLevelPoints(int lp) { for(int i = level_points_; i < lp; ++i) { this->upLevelPoints(); } } void actor::ActiveActor::setCurScorePoints(int sp) { cur_score_points_ = sp; while (cur_score_points_ > max_score_points_) { cur_score_points_ -= max_score_points_; this->upLevelPoints(); } } int actor::ActiveActor::getCurScorePoints() const { return cur_score_points_; } void actor::ActiveActor::setMaxScorePoints(int sp) { max_score_points_ = sp; } int actor::ActiveActor::getMaxScorePoints() const { return max_score_points_; } void actor::ActiveActor::setScorePointsMultiplier(int sp_multiplier) { score_points_multiplier = sp_multiplier; } int actor::ActiveActor::getScorePointsMultiplier() const { return score_points_multiplier; } void actor::SpellActor::setDirection(Point dir) { direction_ = dir; } Point actor::SpellActor::getDirection() const { return direction_; } Point actor::SpellActor::findTarget(const std::vector<std::vector<std::shared_ptr<actor::Actor>>>& area) { return this->getDirection(); } void actor::CollectableActor::setHealthPoints(int hp) { health_points_ = hp; } int actor::CollectableActor::getHealthPoints() const { return health_points_; } void actor::CollectableActor::setManaPoints(int mp) { mana_points_ = mp; } int actor::CollectableActor::getManaPoints() const { return mana_points_; }
72fd2b4ed57db100d112623a2ff1c5e56336577e
419133d0e7ead00544caf1486f0616262d9f16fe
/src/dd1rs.cpp
62cef05f26697d544010ac21ab60ac1d9df86d32
[]
no_license
siddta/scrack
4effc3ff2b77410ed6d9c8b0f24f9fd4e146b4bb
6522dfc37068c3a4180a7a26e1af48aeba703ae3
refs/heads/master
2022-01-27T04:30:41.368436
2019-07-21T02:24:44
2019-07-21T02:24:44
null
0
0
null
null
null
null
UTF-8
C++
false
false
821
cpp
dd1rs.cpp
#include "crack.h" int ddr_find(value_type v){ int L,R; find_piece(ci, N, v, L,R); n_touched += R - L; return targeted_random_crack3(ci,v,arr,N,L,R,CRACK_AT); } int view_query(int a, int b){ merge_ripple(ci, arr, N, pins, pdel, a, b); // merge qualified updates int i1 = ddr_find(a); // unlimited cracks allowed plus one crack on v1 int i2 = ddr_find(b); // unlimited cracks allowed plus one crack on v2 return i2 - i1; // return number of qualified tuples } int count_query(int a, int b){ merge_ripple(ci, arr, N, pins, pdel, a, b); // merge qualified updates int i1 = ddr_find(a); // unlimited cracks allowed plus one crack on v1 int i2 = ddr_find(b); // unlimited cracks allowed plus one crack on v2 int cnt = 0; for (int i=i1; i<i2; i++) if (arr[i]>=0) cnt++; return cnt; }
16809523cd6fb7d763fc6ddf64ea1e5aafb1f82a
63b3efd58d5a3b292f7cdb4940826c4942b8e45f
/apcpp_assignment4/ipc_file.h
b5f018360aac4c6bb23261cbe1aace3ee711c66f
[]
no_license
flxw/apcpp16
37048696037e6e01893c8e079adab24ffc497484
f866449e6de6e8c74e2b054259b3c52fc8a6315f
refs/heads/master
2021-01-18T22:30:42.229085
2017-02-19T18:46:13
2017-02-19T18:46:13
72,547,637
0
0
null
null
null
null
UTF-8
C++
false
false
1,201
h
ipc_file.h
#include <stdlib.h> #include <string.h> #include <boost/interprocess/file_mapping.hpp> #include <boost/interprocess/managed_mapped_file.hpp> #include <map> #include <iostream> #include <iterator> //boost::interprocess::file_mapping m_file("/tmp/scorefile.txt", boost::interprocess::read_write); //boost::interprocess::mapped_region m_region(m_file, read_write); static boost::interprocess::managed_mapped_file m_file(boost::interprocess::open_or_create, "scorefile", 65536); std::uint32_t ipc_readScore(std::uint32_t playerID) { std::string playerIdString = std::to_string(playerID); return *(m_file.find<std::uint32_t>(playerIdString.c_str()).first); } void ipc_updateScore(std::uint32_t playerID, std::uint32_t newScore) { std::string playerIdString = std::to_string(playerID); m_file.destroy<int>(playerIdString.c_str()); m_file.construct<std::uint32_t>(playerIdString.c_str())(newScore); m_file.flush(); } std::map<std::uint32_t, std::uint32_t> ipc_readHighScore(bool block) { std::map<std::uint32_t, std::uint32_t> ret; for (auto it = m_file.named_begin(); it != m_file.named_end(); ++it) { ret[atoi((const char*)it->name())] = *(int*) it->value(); } return ret; }
f4780c70426d6823ece552c16840db168805becd
f8b6ea89909ac12f309a5e8fa8a33bff6e75e557
/algorithms/guards.cpp
43cef9e04d380572643fbdaace623d0e1b6b70d0
[]
no_license
mvgmb/Marathon
eaebc778a6da6699b0c87d62f0f8d0fabfe0b410
0dcc428a5e6858e2427fb40cefbd7453d1abcdb5
refs/heads/master
2020-03-27T02:10:12.225813
2018-10-22T17:51:49
2018-10-22T17:51:49
145,771,171
0
0
null
null
null
null
UTF-8
C++
false
false
818
cpp
guards.cpp
#include <iostream> #include <vector> using namespace std; #define vi vector< int > #define fr(i, n) for (int i = 0; i < n; i++) #define all(v) v.begin(),v.end() #define pb push_back #define tr(c, it) for (auto it = (c).begin(); it != (c).end(); it++) #define rtr(c, it) for (auto it = (c).rbegin(); it != (c).rend(); it++) #define present(c, x) ((c).find(x) != (c).end()) #define cpresent(c, x) ((c).find(all(c),x) != (c).end()) void dfs(){ } int main() { int loop; cin >> loop; int color[200]; vi con[10000]; fr(_, loop) { int v, e; cin >> v >> e; fr(i, v) { color[i] = -1; } fr(i, e){ con[i].clear(); } fr(i,e){ int a,b; cin >> a >> b; con[a].pb(b); } } }
d8a223a84247e3c513708d39706fc3f1fc877a60
4ee8b74813bbc9a803e4b8a02eac196b0b373231
/include/apriltag_detector.h
9d81b78a796c309b55cc42126b7e1822a0872de5
[]
no_license
apl-ocean-engineering/calibration
c63a20236b6db96e7cd3ce2891d1de84158ef603
fb0102fd2e3df197adc981bc5865bf0b8a0e8bee
refs/heads/master
2020-04-05T15:01:13.578958
2018-12-10T23:28:23
2018-12-10T23:28:23
156,948,619
1
0
null
null
null
null
UTF-8
C++
false
false
2,164
h
apriltag_detector.h
#ifndef __APRILTAG_DETECTOR_H__ #define __APRILTAG_DETECTOR_H__ #include <opencv2/core/core.hpp> #ifdef USE_TBB #include "tbb/tbb.h" #endif #include "AplCam/board.h" #include "AplCam/detection/detection.h" #include "AplCam/detection_db.h" #include "detector.h" namespace camera_calibration { using cv::Mat; using cv::Point2f; using AplCam::DetectionDb; struct AprilTagDetectorFunctor { public: AprilTagDetectorFunctor( FrameVec_t &frames, DetectionDb &db, Board *board ) : _frames( frames ), _db(db), _board( *board), timingData() {;} FrameVec_t &_frames; DetectionDb &_db; Board &_board; TimingDataVec_t timingData; #ifdef USE_TBB // Splitting constructor for TBB AprilTagDetectorFunctor( AprilTagDetectorFunctor &other, tbb::split ) : _frames( other._frames ), _db( other._db ), _board( other._board ), timingData() {;} // Interestingly, this function isn't really const, as it // modifies class members... void operator()( const tbb::blocked_range<size_t> &r ) const { size_t end = r.end(); for( size_t i = r.begin(); i != end; ++i ) { #else void operator()( ) const { size_t end = _frames.size(); for( size_t i = 0; i < end; ++i ) { #endif Detection *detection = NULL; Frame &p( _frames[i]); //cout << "Extracting from " << p.frame << ". "; // Mat grey; // cvtColor( p.img, grey, CV_BGR2GRAY ); int64 before = cv::getTickCount(); detection = _board.detectPattern( p.img ); int64 elapsed = cv::getTickCount() - before; //cout << p.frame << ": " << detection->size() << " features" << endl; // Trust the thread-safety of kyotocabinet _db.save( p.frame, *detection); int sz = detection->size(); delete detection; //timingData.push_back( make_pair( sz, elapsed ) ); } } #ifdef USE_TBB void join( const AprilTagDetectorFunctor &other ) { std::copy( other.timingData.begin(), other.timingData.end(), back_inserter( timingData ) ); } #endif }; } #endif
5ae8a53cbce6013c9cbe10b800104cf882b38afc
4cb7cee433de36370fb6eb185a27c9d1735535c4
/Source/Main.cpp
e9a3756cf877be09c5ad99e118d41c26902c7724
[ "LicenseRef-scancode-unknown-license-reference", "MIT" ]
permissive
Dani-24/Minigame
11d3e4b974a8dc730265f9a4652265e8ae738d3c
9c8b675b64c0d26c32fe9bef053edd8f969e6912
refs/heads/main
2023-03-15T02:34:59.341449
2021-03-16T17:52:38
2021-03-16T17:52:38
346,101,527
0
0
null
null
null
null
UTF-8
C++
false
false
17,240
cpp
Main.cpp
// ------------------------------------------------------------------------- // Awesome simple game with SDL // Lesson 2 - Input Events // // SDL API: http://wiki.libsdl.org/APIByCategory // ------------------------------------------------------------------------- #include <stdio.h> // Required for: printf() #include <stdlib.h> // Required for: EXIT_SUCCESS #include <math.h> // Required for: sinf(), cosf() // Include SDL libraries #include "SDL/include/SDL.h" // Required for SDL base systems functionality #include "SDL_image/include/SDL_image.h" // Required for image loading functionality #include "SDL_mixer/include/SDL_mixer.h" // Required for audio loading and playing functionality // Define libraries required by linker // WARNING: Not all compilers support this option and it couples // source code with build system, it's recommended to keep both // separated, in case of multiple build configurations //#pragma comment(lib, "SDL/lib/x86/SDL2.lib") //#pragma comment(lib, "SDL/lib/x86/SDL2main.lib") //#pragma comment(lib, "SDL_image/lib/x86/SDL2_image.lib") //#pragma comment( lib, "SDL_mixer/libx86/SDL2_mixer.lib" ) // ------------------------------------------------------------------------- // Defines, Types and Globals // ------------------------------------------------------------------------- #define SCREEN_WIDTH 1280 #define SCREEN_HEIGHT 720 #define MAX_KEYBOARD_KEYS 256 #define MAX_MOUSE_BUTTONS 5 #define JOYSTICK_DEAD_ZONE 8000 #define SHIP_SPEED 8 #define MAX_SHIP_SHOTS 32 #define SHOT_SPEED 12 #define SCROLL_SPEED 5 #define NB 3 enum WindowEvent { WE_QUIT = 0, WE_HIDE, WE_SHOW, WE_COUNT }; enum KeyState { KEY_IDLE = 0, // DEFAULT KEY_DOWN, // PRESSED (DEFAULT->DOWN) KEY_REPEAT, // KEEP DOWN (sustained) KEY_UP // RELEASED (DOWN->DEFAULT) }; enum GameScreen { LOGO = 0, TITLE, GAMEPLAY, ENDING }; struct Projectile { int x, y; bool alive; }; // Global context to store our game state data struct GlobalState { // Window and renderer SDL_Window* window; SDL_Surface* surface; SDL_Renderer* renderer; // Input events KeyState* keyboard; KeyState mouse_buttons[MAX_MOUSE_BUTTONS]; int mouse_x; int mouse_y; SDL_Joystick* gamepad; int gamepad_axis_x_dir; int gamepad_axis_y_dir; bool window_events[WE_COUNT]; // Texture variables SDL_Texture* background[NB]; SDL_Texture* ship; SDL_Texture* shot; int background_width; SDL_Texture* enemyship1; SDL_Texture* enemyshot1; // Audio variables Mix_Music* music[2]; Mix_Chunk* fx_shoot; // Game elements int ship_x; int ship_y; Projectile shots[MAX_SHIP_SHOTS]; int last_shot; int scroll; //enemy int enemyship1_x; int enemyship1_y; Projectile enemyshots1[MAX_SHIP_SHOTS]; int enemylast1_shot; GameScreen currentScreen; // 0-LOGO, 1-TITLE, 2-GAMEPLAY, 3-ENDING }; // Global game state variable GlobalState state; // Functions Declarations // Some helpful functions to draw basic shapes // ------------------------------------------------------------------------- static void DrawRectangle(int x, int y, int width, int height, SDL_Color color); static void DrawLine(int x1, int y1, int x2, int y2, SDL_Color color); static void DrawCircle(int x, int y, int radius, SDL_Color color); // Functions Declarations and Definition // ------------------------------------------------------------------------- void Start() { // Initialize SDL internal global state SDL_Init(SDL_INIT_EVERYTHING); // Init input events system //if (SDL_InitSubSystem(SDL_INIT_EVENTS) < 0) printf("SDL_EVENTS could not be initialized! SDL_Error: %s\n", SDL_GetError()); // Init window state.window = SDL_CreateWindow("Super Ludificated Game", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_SHOWN); state.surface = SDL_GetWindowSurface(state.window); // Init renderer state.renderer = SDL_CreateRenderer(state.window, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC); SDL_SetRenderDrawColor(state.renderer, 100, 149, 237, 255); // Default clear color: Cornflower blue // L2: DONE 1: Init input variables (keyboard, mouse_buttons) state.keyboard = (KeyState*)calloc(sizeof(KeyState) * MAX_KEYBOARD_KEYS, 1); for (int i = 0; i < MAX_MOUSE_BUTTONS; i++) state.mouse_buttons[i] = KEY_IDLE; // L2: DONE 2: Init input gamepad // Check SDL_NumJoysticks() and SDL_JoystickOpen() if (SDL_NumJoysticks() < 1) printf("WARNING: No joysticks connected!\n"); else { state.gamepad = SDL_JoystickOpen(0); if (state.gamepad == NULL) printf("WARNING: Unable to open game controller! SDL Error: %s\n", SDL_GetError()); } // Init image system and load textures IMG_Init(IMG_INIT_PNG); state.background[0] = SDL_CreateTextureFromSurface(state.renderer, IMG_Load("Assets/fondo.png")); state.background[1] = SDL_CreateTextureFromSurface(state.renderer, IMG_Load("Assets/minijoc.png")); state.background[2] = SDL_CreateTextureFromSurface(state.renderer, IMG_Load("Assets/menu.png")); state.ship = SDL_CreateTextureFromSurface(state.renderer, IMG_Load("Assets/turtle1.png")); state.shot = SDL_CreateTextureFromSurface(state.renderer, IMG_Load("Assets/bomb1.png")); SDL_QueryTexture(state.background[0], NULL, NULL, &state.background_width, NULL); //enemy state.enemyship1 = SDL_CreateTextureFromSurface(state.renderer, IMG_Load("Assets/medusa1.png")); // L4: TODO 1: Init audio system and load music/fx // EXTRA: Handle the case the sound can not be loaded! Mix_Init(MIX_INIT_OGG); Mix_OpenAudio(44100, MIX_DEFAULT_FORMAT, 2, 1024); state.music[0] = Mix_LoadMUS("Assets/juego.ogg"); state.music[1] = Mix_LoadMUS("Assets/menu.ogg"); state.fx_shoot = Mix_LoadWAV("Assets/ehe.ogg"); // L4: TODO 2: Start playing loaded music //Mix_PlayMusic(state.music[1], -1); Mix_PlayMusic(state.music[0], -1); // Init game variables state.ship_x = 100; state.ship_y = SCREEN_HEIGHT / 2; state.last_shot = 0; state.scroll = 0; //enemy state.enemyship1_x = 1200; state.enemyship1_y = SCREEN_HEIGHT / 2; // Pantalla: X: 0-1200 Y: 0-650 state.enemylast1_shot = 0; state.currentScreen = LOGO; } // ---------------------------------------------------------------- void Finish() { // L4: TODO 3: Unload music/fx and deinitialize audio system Mix_FreeMusic(state.music[0]); Mix_FreeMusic(state.music[1]); Mix_FreeChunk(state.fx_shoot); Mix_CloseAudio(); Mix_Quit(); // Unload textures and deinitialize image system for (int i = 0; i < NB; i++) { SDL_DestroyTexture(state.background[i]); } SDL_DestroyTexture(state.ship); SDL_DestroyTexture(state.shot); //enemy SDL_DestroyTexture(state.enemyship1); SDL_DestroyTexture(state.enemyshot1); IMG_Quit(); // L2: DONE 3: Close game controller SDL_JoystickClose(state.gamepad); state.gamepad = NULL; // Deinitialize input events system //SDL_QuitSubSystem(SDL_INIT_EVENTS); // Deinitialize renderer and window // WARNING: Renderer should be deinitialized before window SDL_DestroyRenderer(state.renderer); SDL_DestroyWindow(state.window); // Deinitialize SDL internal global state SDL_Quit(); // Free any game allocated memory free(state.keyboard); } // ---------------------------------------------------------------- bool CheckInput() { // Update current mouse buttons state // considering previous mouse buttons state for (int i = 0; i < MAX_MOUSE_BUTTONS; ++i) { if (state.mouse_buttons[i] == KEY_DOWN) state.mouse_buttons[i] = KEY_REPEAT; if (state.mouse_buttons[i] == KEY_UP) state.mouse_buttons[i] = KEY_IDLE; } // Gather the state of all input devices // WARNING: It modifies global keyboard and mouse state but // its precision may be not enough //SDL_PumpEvents(); // Poll any currently pending events on the queue, // including 'special' events like window events, joysticks and // even hotplug events for audio devices and joysticks, // you can't get those without inspecting event queue // SDL_PollEvent() is the favored way of receiving system events SDL_Event event; while (SDL_PollEvent(&event) != 0) { switch (event.type) { case SDL_QUIT: state.window_events[WE_QUIT] = true; break; case SDL_WINDOWEVENT: { switch (event.window.event) { //case SDL_WINDOWEVENT_LEAVE: case SDL_WINDOWEVENT_HIDDEN: case SDL_WINDOWEVENT_MINIMIZED: case SDL_WINDOWEVENT_FOCUS_LOST: state.window_events[WE_HIDE] = true; break; //case SDL_WINDOWEVENT_ENTER: case SDL_WINDOWEVENT_SHOWN: case SDL_WINDOWEVENT_FOCUS_GAINED: case SDL_WINDOWEVENT_MAXIMIZED: case SDL_WINDOWEVENT_RESTORED: state.window_events[WE_SHOW] = true; break; case SDL_WINDOWEVENT_CLOSE: state.window_events[WE_QUIT] = true; break; default: break; } } break; // L2: DONE 4: Check mouse events for button state case SDL_MOUSEBUTTONDOWN: state.mouse_buttons[event.button.button - 1] = KEY_DOWN; break; case SDL_MOUSEBUTTONUP: state.mouse_buttons[event.button.button - 1] = KEY_UP; break; case SDL_MOUSEMOTION: { state.mouse_x = event.motion.x; state.mouse_y = event.motion.y; } break; case SDL_JOYAXISMOTION: { // Motion on controller 0 if (event.jaxis.which == 0) { // X axis motion if (event.jaxis.axis == 0) { if (event.jaxis.value < -JOYSTICK_DEAD_ZONE) state.gamepad_axis_x_dir = -1; else if (event.jaxis.value > JOYSTICK_DEAD_ZONE) state.gamepad_axis_x_dir = 1; else state.gamepad_axis_x_dir = 0; } // Y axis motion else if (event.jaxis.axis == 1) { if (event.jaxis.value < -JOYSTICK_DEAD_ZONE) state.gamepad_axis_y_dir = -1; else if (event.jaxis.value > JOYSTICK_DEAD_ZONE) state.gamepad_axis_y_dir = 1; else state.gamepad_axis_y_dir = 0; } } } break; default: break; } } const Uint8* keys = SDL_GetKeyboardState(NULL); // L2: DONE 5: Update keyboard keys state // Consider previous keys states for KEY_DOWN and KEY_UP for (int i = 0; i < MAX_KEYBOARD_KEYS; ++i) { // A value of 1 means that the key is pressed and a value of 0 means that it is not if (keys[i] == 1) { if (state.keyboard[i] == KEY_IDLE) state.keyboard[i] = KEY_DOWN; else state.keyboard[i] = KEY_REPEAT; } else { if (state.keyboard[i] == KEY_REPEAT || state.keyboard[i] == KEY_DOWN) state.keyboard[i] = KEY_UP; else state.keyboard[i] = KEY_IDLE; } } // L2: DONE 6: Check ESCAPE key pressed to finish the game if (state.keyboard[SDL_SCANCODE_ESCAPE] == KEY_DOWN) return false; if (state.keyboard[SDL_SCANCODE_2] == KEY_DOWN) return false; // Check QUIT window event to finish the game if (state.window_events[WE_QUIT] == true) return false; return true; } // ---------------------------------------------------------------- void MoveStuff() { Mix_PauseMusic(); switch (state.currentScreen) { case LOGO: { //Mix_ResumeMusic(); //Mix_PlayMusic(state.music[0], -1) ; if (state.keyboard[SDL_SCANCODE_RETURN] == KEY_DOWN) state.currentScreen = TITLE; state.enemyship1_y = rand() % 650; // coloca la nave en un sitio distinto //state.enemyship1_x = 0; } break; case TITLE: { //Mix_ResumeMusic(); // Mix_PlayMusic(state.music[0], -1) == 1; if (state.keyboard[SDL_SCANCODE_RETURN] == KEY_DOWN) state.currentScreen = GAMEPLAY; else if (state.keyboard[SDL_SCANCODE_1] == KEY_DOWN) state.currentScreen = GAMEPLAY; } break; case GAMEPLAY: { Mix_ResumeMusic(); //Mix_PlayMusic(state.music[1], -1) == 1; //enemy if (state.ship_y != state.enemyship1_y) { if (state.ship_y - 10 > state.enemyship1_y) { state.enemyship1_y += SHIP_SPEED / 3; } else if (state.ship_y + 10 < state.enemyship1_y) { state.enemyship1_y -= SHIP_SPEED / 3; } else { } } // L2: DONE 7: Move the ship with arrow keys if (state.keyboard[SDL_SCANCODE_UP] == KEY_REPEAT) state.ship_y -= SHIP_SPEED; else if (state.keyboard[SDL_SCANCODE_DOWN] == KEY_REPEAT) state.ship_y += SHIP_SPEED; if (state.keyboard[SDL_SCANCODE_LEFT] == KEY_REPEAT) state.ship_x -= SHIP_SPEED; else if (state.keyboard[SDL_SCANCODE_RIGHT] == KEY_REPEAT) state.ship_x += SHIP_SPEED; // L2: DONE 8: Initialize a new shot when SPACE key is pressed if (state.keyboard[SDL_SCANCODE_SPACE] == KEY_DOWN) { if (state.last_shot == MAX_SHIP_SHOTS) state.last_shot = 0; state.shots[state.last_shot].alive = true; state.shots[state.last_shot].x = state.ship_x + 35; state.shots[state.last_shot].y = state.ship_y - 3; state.last_shot++; // L4: TODO 4: Play sound fx_shoot Mix_PlayChannel(-1, state.fx_shoot, 0); } // Update active shots for (int i = 0; i < MAX_SHIP_SHOTS; ++i) { if (state.shots[i].alive) { if (state.shots[i].x < SCREEN_WIDTH) state.shots[i].x += SHOT_SPEED; else state.shots[i].alive = false; } } } break; case ENDING: { } break; default: break; } } // ---------------------------------------------------------------- void Draw() { // Clear screen to Cornflower blue SDL_SetRenderDrawColor(state.renderer, 100, 149, 237, 255); SDL_RenderClear(state.renderer); switch (state.currentScreen) { case LOGO: { SDL_Rect rec = { -state.scroll, 0, state.background_width, SCREEN_HEIGHT }; SDL_RenderCopy(state.renderer, state.background[1], NULL, &rec); } break; case TITLE: { SDL_Rect rec = { -state.scroll, 0, state.background_width, SCREEN_HEIGHT }; SDL_RenderCopy(state.renderer, state.background[2], NULL, &rec); } break; case GAMEPLAY: { // Draw background and scroll state.scroll += 10;//SCROLL_SPEED; if (state.scroll >= state.background_width) state.scroll = 0; // Draw background texture (two times for scrolling effect) // NOTE: rec rectangle is being reused for next draws SDL_Rect rec = { -state.scroll, 0, state.background_width, SCREEN_HEIGHT }; SDL_RenderCopy(state.renderer, state.background[0], NULL, &rec); rec.x += state.background_width; SDL_RenderCopy(state.renderer, state.background[0], NULL, &rec); // Draw ship rectangle //DrawRectangle(state.ship_x, state.ship_y, 65, 65, { 255, 0, 0, 255 }); // Draw ship texture rec.x = state.ship_x; rec.y = state.ship_y; rec.w = 64; rec.h = 64; SDL_RenderCopy(state.renderer, state.ship, NULL, &rec); //ENEMY rec.x = state.enemyship1_x; rec.y = state.enemyship1_y; rec.w = 64; rec.h = 64; SDL_RenderCopy(state.renderer, state.enemyship1, NULL, &rec); // L2: DONE 9: Draw active shots rec.w = 64; rec.h = 64; for (int i = 0; i < MAX_SHIP_SHOTS; ++i) { if (state.shots[i].alive) { //DrawRectangle(state.shots[i].x, state.shots[i].y, 50, 20, { 0, 250, 0, 255 }); rec.x = state.shots[i].x; rec.y = state.shots[i].y; SDL_RenderCopy(state.renderer, state.shot, NULL, &rec); } } } break; case ENDING: { } break; default: break; } // Finally present framebuffer SDL_RenderPresent(state.renderer); } // Main Entry point // ------------------------------------------------------------------------- int main(int argc, char* argv[]) { Start(); while (CheckInput()) { MoveStuff(); Draw(); } Finish(); return(EXIT_SUCCESS); } // Functions Definition // ------------------------------------------------------------------------- void DrawRectangle(int x, int y, int width, int height, SDL_Color color) { SDL_SetRenderDrawBlendMode(state.renderer, SDL_BLENDMODE_BLEND); SDL_SetRenderDrawColor(state.renderer, color.r, color.g, color.b, color.a); SDL_Rect rec = { x, y, width, height }; int result = SDL_RenderFillRect(state.renderer, &rec); if (result != 0) printf("Cannot draw quad to screen. SDL_RenderFillRect error: %s", SDL_GetError()); } // ---------------------------------------------------------------- void DrawLine(int x1, int y1, int x2, int y2, SDL_Color color) { SDL_SetRenderDrawBlendMode(state.renderer, SDL_BLENDMODE_BLEND); SDL_SetRenderDrawColor(state.renderer, color.r, color.g, color.b, color.a); int result = SDL_RenderDrawLine(state.renderer, x1, y1, x2, y2); if (result != 0) printf("Cannot draw quad to screen. SDL_RenderFillRect error: %s", SDL_GetError()); } // ---------------------------------------------------------------- void DrawCircle(int x, int y, int radius, SDL_Color color) { SDL_SetRenderDrawBlendMode(state.renderer, SDL_BLENDMODE_BLEND); SDL_SetRenderDrawColor(state.renderer, color.r, color.g, color.b, color.a); SDL_Point points[360]; float factor = (float)M_PI / 180.0f; for (int i = 0; i < 360; ++i) { points[i].x = (int)(x + radius * cosf(factor * i)); points[i].y = (int)(y + radius * sinf(factor * i)); } int result = SDL_RenderDrawPoints(state.renderer, points, 360); if (result != 0) printf("Cannot draw quad to screen. SDL_RenderFillRect error: %s", SDL_GetError()); }
1d0aa6b6d70f16ee601307dc5357e1e55e6d1cc0
30f530277d108cb1901b54a633acf9bdac8eaef3
/src/render/GLFWWindow.cpp
ab8b69d388574fbeba4b1618c69a507036e7dc18
[]
no_license
davtwal/gproj
26781ff8fb5a09250bdd52d5a04efd6d6dc73ab8
389fda53d5994776540aee210cda3e2fe5fd13d5
refs/heads/master
2020-06-25T19:07:47.298231
2020-02-27T04:13:32
2020-02-27T04:13:32
199,397,402
0
0
null
null
null
null
UTF-8
C++
false
false
1,898
cpp
GLFWWindow.cpp
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // * gproj2 : GLFWWindow.cpp // * Copyright (C) DigiPen Institute of Technology 2019 // * // Created : 2019y 09m 15d // * Last Altered: 2019y 09m 15d // * // * Author : David Walker // * E-mail : d.walker\@digipen.edu // * // * Description : // * // * // * // * // * // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * #include "render/GLFWWindow.h" #include <stdexcept> namespace dw { GLFWWindow::GLFWWindow(int w, int h, std::string const& name) : m_width(w), m_height(h), m_name(name) { glfwWindowHint(GLFW_CLIENT_API, GLFW_NO_API); m_window = glfwCreateWindow(w, h, name.c_str(), nullptr, nullptr); if (!m_window) throw std::bad_alloc(); glfwSetKeyCallback(m_window, GLFWControl::KeyCB); glfwSetMouseButtonCallback(m_window, GLFWControl::MouseButtonCB); glfwSetCursorPosCallback(m_window, GLFWControl::MousePosCB); glfwSetFramebufferSizeCallback(m_window, GLFWControl::FramebufferCB); glfwSetWindowSizeCallback(m_window, GLFWControl::WindowSizeCB); glfwSetWindowUserPointer(m_window, this); } bool GLFWWindow::shouldClose() const { return m_window ? glfwWindowShouldClose(m_window) : true; } GLFWwindow* GLFWWindow::getHandle() const { return m_window; } unsigned GLFWWindow::getWidth() const { return m_width; } unsigned GLFWWindow::getHeight() const { return m_height; } void GLFWWindow::setInputHandler(InputHandler* handler) { m_inputHandler = handler; } void GLFWWindow::setOnResizeCB(OnResizeCB newCB) { m_resizeCB = newCB; } void GLFWWindow::setShouldClose(bool close) { if (m_window) glfwSetWindowShouldClose(m_window, close); } GLFWWindow::~GLFWWindow() { if (m_window) glfwDestroyWindow(m_window); } }
3bbbf56cd35f169d3d6049c3dd0ccb354d696001
8e3dd82044333bf6e04cb3cc23646f2396b1183a
/openFrameworks/apps/devApps/EGLWindowRaspberryPi/src/ofTrueTypeFontExt.h
b247cd32ee117e516a0c259af2d5b550693a93c3
[]
no_license
andreasmuller/openframeWorks-Raspberry-PI
e7f8f51d66d829c55e97a7ebe4bcd8255747fd2c
395bbe1778c5381cd32ced4b92a141a14e964faa
refs/heads/master
2016-09-06T10:46:41.498470
2012-07-22T16:58:53
2012-07-22T16:58:53
4,923,328
5
5
null
null
null
null
UTF-8
C++
false
false
331
h
ofTrueTypeFontExt.h
#pragma once #include "ofMain.h" class ofTrueTypeFontExt : public ofTrueTypeFont { public: void drawTextureAtlas( float _x, float _y, float _w, float _h ) { if( _w == 0.0f || _h == 0.0f ) { _w = texAtlas.getWidth(); _h = texAtlas.getHeight(); } texAtlas.draw( _x, _y, _w, _h ); } };
ccdd886150984a70796889d3c44675ba5cdf7ed3
25175c43fbf6c9794b01f2919aa422daac21fe3b
/Source/FruitSalad/AI/FruitAIController.cpp
797e50c536836991d581cfbb2121648c1a344884
[]
no_license
ajetty/FruitSalad
e9fff6a754dd1fb2226e58943a278840d52f61d0
52a0696f001893fbd2da7841b9480a2081e8b6a6
refs/heads/main
2023-05-30T07:35:30.456938
2021-06-04T17:35:29
2021-06-04T17:35:29
352,740,632
0
0
null
null
null
null
UTF-8
C++
false
false
3,329
cpp
FruitAIController.cpp
// Fill out your copyright notice in the Description page of Project Settings. #include "FruitAIController.h" #include "NavigationSystem.h" #include "BehaviorTree/BlackboardComponent.h" #include "FruitSalad/Building/BuildingBase.h" #include "FruitSalad/Bulldozer/PawnBulldozer.h" #include "Kismet/GameplayStatics.h" #include "Perception/AIPerceptionComponent.h" #include "Perception/AISenseConfig_Sight.h" AFruitAIController::AFruitAIController() { PrimaryActorTick.bCanEverTick = true; SightConfig = CreateDefaultSubobject<UAISenseConfig_Sight>(TEXT("Sight Config")); SetPerceptionComponent(*CreateDefaultSubobject<UAIPerceptionComponent>(TEXT("Perception Component"))); SightConfig->SightRadius = AISightRange; SightConfig->LoseSightRadius = AISightRange; SightConfig->SetMaxAge(AISightMaxAge); SightConfig->DetectionByAffiliation.bDetectEnemies = true; SightConfig->DetectionByAffiliation.bDetectFriendlies = true; SightConfig->DetectionByAffiliation.bDetectNeutrals = true; GetPerceptionComponent()->SetDominantSense(*SightConfig->GetSenseImplementation()); GetPerceptionComponent()->ConfigureSense(*SightConfig); } void AFruitAIController::Tick(float DeltaSeconds) { Super::Tick(DeltaSeconds); } void AFruitAIController::BeginPlay() { Super::BeginPlay(); if(AIBehavior != nullptr) { RunBehaviorTree(AIBehavior); //APawn* PlayerPawn = UGameplayStatics::GetPlayerPawn(GetWorld(), 0); //GetBlackboardComponent()->SetValueAsVector(TEXT("PlayerLocation"),PlayerPawn->GetActorLocation()); //GetBlackboardComponent()->SetValueAsVector(TEXT("StartLocation"),GetPawn()->GetActorLocation()); // AIPerception = FindComponentByClass<UFruitAIPerception>(); // // if(ensureMsgf(AIPerception, TEXT("AIPerception in FruitAIController is nullptr."))) // { // AIPerception->OnTargetPerceptionUpdated.AddDynamic(this, &AFruitAIController::SenseActors); // TArray<AActor*> ActorsSensed; // AIPerception->GetCurrentlyPerceivedActors(SightSense, ActorsSensed); // } // // //UNavigationSystemV1::K2_GetRandomReachablePointInRadius(); } GetPerceptionComponent()->OnPerceptionUpdated.AddDynamic(this, &AFruitAIController::OnPawnDetected); } void AFruitAIController::OnPawnDetected(const TArray<AActor*>& DetectedPawns) { for(AActor* DetectedPawn : DetectedPawns) { if(Cast<APawnBulldozer>(DetectedPawn)) { //GEngine->AddOnScreenDebugMessage(-1, 10.0f, FColor::Blue, "Perceived " + DetectedPawn->GetName()); GetBlackboardComponent()->SetValueAsBool(TEXT("HasLineOfSight"), true); } else if(Cast<ABuildingBase>(DetectedPawn)) { GEngine->AddOnScreenDebugMessage(-1, 10.0f, FColor::Blue, "Perceived " + DetectedPawn->GetName()); GetBlackboardComponent()->SetValueAsBool(TEXT("HasLineOfSight"), true); } else { //GEngine->AddOnScreenDebugMessage(-1, 10.0f, FColor::Red, "Perceived " + DetectedPawn->GetName()); GetBlackboardComponent()->SetValueAsBool(TEXT("HasLineOfSight"), false); } } } // void AFruitAIController::SenseActors(AActor* UpdatedActor, FAIStimulus Stimulus) // { // GEngine->AddOnScreenDebugMessage(-1, 10.0f, FColor::Red, "Perceived " + UpdatedActor->GetName()); // if(Stimulus.WasSuccessfullySensed()) // { // GEngine->AddOnScreenDebugMessage(-1, 10.0f, FColor::Blue, "Perceived " + UpdatedActor->GetName()); // } // }
c986c87f397d40635f634fa35705488b854bf327
0686c6c1c831f37cfbd2f08eb33d8f0581de7446
/c++/grafo_dfs.cpp
e9823abad0e2499b3d5a9249febb81a43520356e
[]
no_license
JonatanColussi/sistemas-inteligentes
78ef8d6ef7ddc7b46f0222e41dec240c9072e998
d487d01c69ad4d8d6baf8627fd3e488fb6820f50
refs/heads/master
2020-12-03T02:19:42.647232
2017-06-30T22:21:30
2017-06-30T22:21:30
95,927,771
0
0
null
null
null
null
ISO-8859-1
C++
false
false
2,156
cpp
grafo_dfs.cpp
// Grafos - DFS (busca em profundidade) #include <fstream> #include <iostream> #include <list> #include <string> #include <cstdlib> #include <algorithm> // função find #include <stack> // pilha para usar na DFS using namespace std; class Grafo{ int V; // número de vértices list<int> *adj; // ponteiro para um array contendo as listas de adjacências public: Grafo(int V); // construtor void adicionarAresta(int v1, int v2); // adiciona uma aresta no grafo // faz uma DFS a partir de um vértice void dfs(int v); }; Grafo::Grafo(int V){ this->V = V; // atribui o número de vértices adj = new list<int>[V]; // cria as listas } void Grafo::adicionarAresta(int v1, int v2){ // adiciona vértice v2 à  lista de vértices adjacentes de v1 adj[v1].push_back(v2); } void Grafo::dfs(int v){ stack<int> pilha; bool visitados[V]; // vetor de visitados // marca todos como não visitados for(int i = 0; i < V; i++) visitados[i] = false; while(true){ if(!visitados[v]){ cout << "Visitando vertice " << v << " ...\n"; visitados[v] = true; // marca como visitado pilha.push(v); // insere "v" na pilha } bool achou = false; list<int>::iterator it; // busca por um vizinho não visitado for(it = adj[v].begin(); it != adj[v].end(); it++){ if(!visitados[*it]){ achou = true; break; } } if(achou) v = *it; // atualiza o "v" else{ // se todos os vizinhos estão visitados ou não existem vizinhos // remove da pilha pilha.pop(); // se a pilha ficar vazia, então terminou a busca if(pilha.empty()) break; // se chegou aqui, é porque pode pegar elemento do topo v = pilha.top(); } } } int main(){ std::ifstream file("matriz.txt"); cout << "Informe o numero de arestas: "; int V; scanf("%i", &V); Grafo grafo(V); while (true) { std::string value; int pai; int filho; int v1, v2; if (!(file >> value)) break; pai = atoi(value.substr(0, value.find("#")).c_str()); filho = atoi(value.substr(2, value.find("#")).c_str()); grafo.adicionarAresta(pai, filho); } grafo.dfs(0); }
eb37a930643621973278caae7b9bc8eb384c6756
eb2f8b3271e8ef9c9b092fcaeff3ff8307f7af86
/Grade 10-12/2018 autumn/NOIP/NOIP2018提高组Day1程序包/GD-Senior/answers/GD-0394/road/road.cpp
907b9a5fa1f4a9429061fd9494549890dcd5caef
[]
no_license
Orion545/OI-Record
0071ecde8f766c6db1f67b9c2adf07d98fd4634f
fa7d3a36c4a184fde889123d0a66d896232ef14c
refs/heads/master
2022-01-13T19:39:22.590840
2019-05-26T07:50:17
2019-05-26T07:50:17
188,645,194
4
2
null
null
null
null
UTF-8
C++
false
false
936
cpp
road.cpp
#include<iostream> #include<cstdio> #define INF 2147483647 #define maxn 100005 using namespace std; int n,d[maxn],k; long long ans; inline int read() { char ch=getchar(); while (ch>'9'||ch<'0') ch=getchar(); int res=ch-48; ch=getchar(); while (ch<='9'&&ch>='0') { res=res*10+ch-48; ch=getchar(); } return res; } int main() { freopen("road.in","r",stdin); freopen("road.out","w",stdout); n=read(); int Min=INF,wz=0; ans=0; for (int i=1; i<=n; i++) { d[i]=read(); if (Min>d[i]&&d[i]!=0) { Min=d[i]; wz=i; } } k=0; while (k!=n) { d[wz]-=Min; int l=wz-1; int r=wz+1; while (l>=1&&d[l]!=0) { d[l]-=Min; l--; } while (r<=n&&d[r]!=0) { d[r]-=Min; r++; } ans+=Min; k=0; Min=INF; for (int i=1; i<=n; i++) { if (d[i]==0) k++; else if (d[i]<Min&&d[i]!=0) { Min=d[i]; wz=i; } } } printf("%lld",ans); fclose(stdin);fclose(stdout); return 0; }
f455487d2326b38ac37028f88999eaa780e710ee
0baa4ef2d2f65acae29f49219c36fc6c13aff547
/01_NARESH C&C++/Kiran sir/Student Data/CPP/inheritence/INHERIT1.CPP
cb66af568d2966f3bb6b6d7d456a38e2e44032d1
[]
no_license
ankitwasankar/study-material-3
874c354dc7380a8751e6efc5d8751ee7acbd1ce7
0179d762c381214336f4c64b2881affa0bf35a6c
refs/heads/master
2022-10-01T13:36:41.013854
2020-06-05T13:47:04
2020-06-05T13:47:04
269,634,446
0
0
null
null
null
null
UTF-8
C++
false
false
688
cpp
INHERIT1.CPP
//EXAMPLE PROGRAM ON SINGLE INHERITANCE # include <iostream.h> # include <conio.h> class A { int x,y; public: void input(int p,int r) { x=p; y=r; } void print() { cout<<"X VALUE IS "<<x<<endl; cout<<"Y VALUE IS "<<y<<endl; } }; class B : public A { int m,n; public: void accept() { cout<<"ENTER TWO INTEGERS "; cin>>m>>n; } void display() { cout<<"M VALUE IS "<<m<<endl; cout<<"N VALUE IS "<<n<<endl; } }; void main() { B t; clrscr(); t.input(253,445); //MEMBER FUNCTION OF BASE CLASS t.accept(); //MEMBER FUNCTION OF THE DERIVED CLASS clrscr(); t.print(); //FUNCTION OF BASE CLASS t.display(); //FUNCTION OF THE DERIVED CLASS getch(); }
a1c05e5b507d75de94c7be74303a6ffc2b5dd5d5
2475b9c1a0e3fd49432f4998d3b1b8306bb87fbf
/AniClip/tablineedit.cpp
e7e27c943adaab1b96a45210ff5f027e084ac1f2
[]
no_license
MercifulZebra/Animegraphy
b47b665004f4952325a7e12ab08f5547b52ba097
f78e2cb2070ef18f11105ec8a18333bdc37edd49
refs/heads/master
2021-05-30T09:21:37.027789
2016-01-15T19:09:31
2016-01-15T19:09:31
null
0
0
null
null
null
null
UTF-8
C++
false
false
829
cpp
tablineedit.cpp
#include "tablineedit.h" #include <QKeyEvent> #include <QCompleter> #include <QAbstractItemView> #include <QDebug> TabLineEdit::TabLineEdit(QWidget *parent) : QLineEdit(parent) { } void TabLineEdit::keyPressEvent(QKeyEvent *event){ bool shift_key = false; int mod = 0; if (event->modifiers() == Qt::ShiftModifier){ shift_key = true; mod = -1; } if ((event->key() + mod) == Qt::Key_Tab){ if ( completer() != NULL) { if ( completer()->popup()->isVisible()){ setText(completer()->currentCompletion()); } else { emit switchFocus(!shift_key); return; } } else { emit switchFocus(!shift_key); } } QLineEdit::keyPressEvent(event); }
5c56c74c9f9a61e7350d84ef905d158443eaf7a6
a5a7c59b04a1a64fe34653c7970c3cf173f9c1df
/externals/numeric_bindings/boost/numeric/bindings/ublas/matrix.hpp
bcf71aa150d7162a3c322caa2d045f1c8f14396a
[ "BSL-1.0", "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
siconos/siconos
a7afdba41a2bc1192ad8dcd93ac7266fa281f4cf
82a8d1338bfc1be0d36b5e8a9f40c1ad5384a641
refs/heads/master
2023-08-21T22:22:55.625941
2023-07-17T13:07:32
2023-07-17T13:07:32
37,709,357
166
33
Apache-2.0
2023-07-17T12:31:16
2015-06-19T07:55:53
C
UTF-8
C++
false
false
4,888
hpp
matrix.hpp
// // Copyright (c) 2009 Rutger ter Borg // // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // #ifndef BOOST_NUMERIC_BINDINGS_UBLAS_MATRIX_HPP #define BOOST_NUMERIC_BINDINGS_UBLAS_MATRIX_HPP #include <boost/numeric/bindings/begin.hpp> #include <boost/numeric/bindings/end.hpp> #include <boost/numeric/bindings/detail/adaptor.hpp> #include <boost/numeric/bindings/detail/if_row_major.hpp> #include <boost/numeric/bindings/detail/offset.hpp> #include <boost/numeric/bindings/ublas/detail/convert_to.hpp> #include <boost/numeric/bindings/ublas/storage.hpp> #include <boost/numeric/bindings/ublas/matrix_expression.hpp> #include <boost/numeric/ublas/matrix.hpp> namespace boost { namespace numeric { namespace bindings { namespace detail { template< typename T, typename F, typename A, typename Id, typename Enable > struct adaptor< ::boost::numeric::ublas::matrix< T, F, A >, Id, Enable > { typedef typename copy_const< Id, T >::type value_type; typedef typename convert_to< tag::data_order, F >::type data_order; typedef mpl::map< mpl::pair< tag::value_type, value_type >, mpl::pair< tag::entity, tag::matrix >, mpl::pair< tag::size_type<1>, std::ptrdiff_t >, mpl::pair< tag::size_type<2>, std::ptrdiff_t >, mpl::pair< tag::matrix_type, tag::general >, mpl::pair< tag::data_structure, tag::linear_array >, mpl::pair< tag::data_order, data_order >, mpl::pair< tag::stride_type<1>, typename if_row_major< data_order, std::ptrdiff_t, tag::contiguous >::type >, mpl::pair< tag::stride_type<2>, typename if_row_major< data_order, tag::contiguous, std::ptrdiff_t >::type > > property_map; static std::ptrdiff_t size1( const Id& id ) { return id.size1(); } static std::ptrdiff_t size2( const Id& id ) { return id.size2(); } static value_type* begin_value( Id& id ) { return bindings::begin_value( id.data() ); } static value_type* end_value( Id& id ) { return bindings::end_value( id.data() ); } static std::ptrdiff_t stride1( const Id& id ) { return id.size2(); } static std::ptrdiff_t stride2( const Id& id ) { return id.size1(); } }; template< typename T, std::size_t M, std::size_t N, typename F, typename Id, typename Enable > struct adaptor< ::boost::numeric::ublas::bounded_matrix< T, M, N, F >, Id, Enable > { typedef typename copy_const< Id, T >::type value_type; typedef typename convert_to< tag::data_order, F >::type data_order; typedef mpl::map< mpl::pair< tag::value_type, value_type >, mpl::pair< tag::entity, tag::matrix >, mpl::pair< tag::size_type<1>, std::ptrdiff_t >, mpl::pair< tag::size_type<2>, std::ptrdiff_t >, mpl::pair< tag::data_structure, tag::linear_array >, mpl::pair< tag::data_order, data_order >, mpl::pair< tag::stride_type<1>, typename if_row_major< data_order, mpl::int_<N>, tag::contiguous >::type >, mpl::pair< tag::stride_type<2>, typename if_row_major< data_order, tag::contiguous, mpl::int_<M> >::type > > property_map; static std::ptrdiff_t size1( const Id& id ) { return id.size1(); } static std::ptrdiff_t size2( const Id& id ) { return id.size2(); } static value_type* begin_value( Id& id ) { return bindings::begin_value( id.data() ); } static value_type* end_value( Id& id ) { return bindings::end_value( id.data() ); } }; template< typename T, std::size_t M, std::size_t N, typename Id, typename Enable > struct adaptor< ::boost::numeric::ublas::c_matrix< T, M, N >, Id, Enable > { typedef typename copy_const< Id, T >::type value_type; typedef mpl::map< mpl::pair< tag::value_type, value_type >, mpl::pair< tag::entity, tag::matrix >, mpl::pair< tag::size_type<1>, std::ptrdiff_t >, mpl::pair< tag::size_type<2>, std::ptrdiff_t >, mpl::pair< tag::matrix_type, tag::general >, mpl::pair< tag::data_structure, tag::linear_array >, mpl::pair< tag::data_order, tag::row_major >, mpl::pair< tag::stride_type<1>, mpl::int_<N> >, mpl::pair< tag::stride_type<2>, tag::contiguous > > property_map; static std::ptrdiff_t size1( const Id& id ) { return id.size1(); } static std::ptrdiff_t size2( const Id& id ) { return id.size2(); } static value_type* begin_value( Id& id ) { return id.data(); } static value_type* end_value( Id& id ) { return id.data() + offset( id, id.size1(), id.size2() ); } }; } // namespace detail } // namespace bindings } // namespace numeric } // namespace boost #endif
e970dc7604df27e634ea9436e528d49dcd08ed32
ab60cf7ed7c5b7c5808624eebffd773dc2a678a6
/module/extension/Director/tests/entire_task.cpp
dd7f16f5b4a24742d83494ac4160d7f5b50835e9
[]
no_license
NUbots/NUbots
a5faa92669e866abed7b075359faa05e6dc61911
e42a510a67684027fbd581ff696cc31af5047455
refs/heads/main
2023-09-02T19:32:50.457094
2023-09-01T19:54:01
2023-09-01T19:54:01
23,809,180
34
20
null
2023-09-12T12:55:08
2014-09-08T21:30:48
C++
UTF-8
C++
false
false
4,566
cpp
entire_task.cpp
/* * This file is part of the NUbots Codebase. * * The NUbots Codebase is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The NUbots Codebase 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 the NUbots Codebase. If not, see <http://www.gnu.org/licenses/>. * * Copyright 2022 NUbots <nubots@nubots.net> */ #include <catch2/catch_test_macros.hpp> #include <nuclear> #include "Director.hpp" #include "TestBase.hpp" #include "util/diff_string.hpp" // Anonymous namespace to avoid name collisions namespace { template <int i> struct SimpleTask { SimpleTask(const std::string& msg_) : msg(msg_) {} std::string msg; }; struct ComplexTask { ComplexTask(const std::string& msg_) : msg(msg_) {} std::string msg; }; struct BlockerTask {}; std::vector<std::string> events; class TestReactor : public TestBase<TestReactor> { public: explicit TestReactor(std::unique_ptr<NUClear::Environment> environment) : TestBase<TestReactor>(std::move(environment)) { on<Provide<SimpleTask<0>>>().then([this](const SimpleTask<0>& t) { events.push_back(t.msg); }); on<Provide<SimpleTask<1>>>().then([this](const SimpleTask<1>& t) { events.push_back(t.msg); }); on<Provide<ComplexTask>>().then([this](const ComplexTask& t) { events.push_back("emitting tasks from complex " + t.msg); emit<Task>(std::make_unique<SimpleTask<0>>("from complex " + t.msg)); emit<Task>(std::make_unique<SimpleTask<1>>("from complex " + t.msg)); }); on<Provide<BlockerTask>>().then([this] { events.push_back("emitting blocker simple task"); emit<Task>(std::make_unique<SimpleTask<0>>("from blocker")); }); /************** * TEST STEPS * **************/ on<Trigger<Step<1>>, Priority::LOW>().then([this] { // Emit a blocker task that will use SimpleTask<0> to block the complex task events.push_back("emitting blocker task"); emit<Task>(std::make_unique<BlockerTask>(), 50); }); on<Trigger<Step<2>>, Priority::LOW>().then([this] { // Emit the complex task that should be blocked by the blocker task events.push_back("emitting low priority complex task"); emit<Task>(std::make_unique<ComplexTask>("low priority"), 10); }); on<Trigger<Step<3>>, Priority::LOW>().then([this] { // Emit another complex task that should have high enough priority to execute over the blocker events.push_back("emitting high priority complex task"); emit<Task>(std::make_unique<ComplexTask>("high priority"), 100); }); on<Startup>().then([this] { emit(std::make_unique<Step<1>>()); emit(std::make_unique<Step<2>>()); emit(std::make_unique<Step<3>>()); }); } }; } // namespace TEST_CASE("Test that if all the non optional tasks can't be executed none of them will be", "[director][priority][entire]") { NUClear::PowerPlant::Configuration config; config.thread_count = 1; NUClear::PowerPlant powerplant(config); powerplant.install<module::extension::Director>(); powerplant.install<TestReactor>(); powerplant.start(); std::vector<std::string> expected = { "emitting blocker task", "emitting blocker simple task", "from blocker", "emitting low priority complex task", "emitting tasks from complex low priority", "emitting high priority complex task", "emitting tasks from complex high priority", "from complex high priority", "from complex high priority", }; // Make an info print the diff in an easy to read way if we fail INFO(util::diff_string(expected, events)); // Check the events fired in order and only those events REQUIRE(events == expected); }
47b9e40e83a4747fade3f5e74d927e82ccdb7fae
d2ba0389accde0370662b9df282ef1f8df8d69c7
/frameworks/cocos2d-x/cocos/editor-support/spine/SkeletonBounds.cpp
b801fa3fd0fcadfa4f1070012104f33d1b54669c
[]
no_license
Kuovane/LearnOpenGLES
6a42438db05eecf5c877504013e9ac7682bc291c
8458b9c87d1bf333b8679e90a8a47bc27ebe9ccd
refs/heads/master
2022-07-27T00:28:02.066179
2020-05-14T10:34:46
2020-05-14T10:34:46
262,535,484
0
0
null
null
null
null
UTF-8
C++
false
false
7,718
cpp
SkeletonBounds.cpp
/****************************************************************************** * Spine Runtimes Software License v2.5 * * Copyright (c) 2013-2016, Esoteric Software * All rights reserved. * * You are granted a perpetual, non-exclusive, non-sublicensable, and * non-transferable license to use, install, execute, and perform the Spine * Runtimes software and derivative works solely for personal or internal * use. Without the written permission of Esoteric Software (see Section 2 of * the Spine Software License Agreement), you may not (a) modify, translate, * adapt, or develop new applications using the Spine Runtimes or otherwise * create derivative works or improvements of the Spine Runtimes or (b) remove, * delete, alter, or obscure any trademarks or any copyright, trademark, patent, * or other intellectual property or proprietary rights notices on or in the * Software, including any copy thereof. Redistributions in binary or source * form must include this license and terms. * * THIS SOFTWARE IS PROVIDED BY ESOTERIC SOFTWARE "AS IS" AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO * EVENT SHALL ESOTERIC SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, BUSINESS INTERRUPTION, OR LOSS OF * USE, DATA, OR PROFITS) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. *****************************************************************************/ #ifdef SPINE_UE4 #include "SpinePluginPrivatePCH.h" #endif #include <spine/SkeletonBounds.h> #include <spine/Skeleton.h> #include <spine/BoundingBoxAttachment.h> #include <spine/Slot.h> using namespace spine; SkeletonBounds::SkeletonBounds() : _minX(0), _minY(0), _maxX(0), _maxY(0) { } void SkeletonBounds::update(Skeleton &skeleton, bool updateAabb) { Vector<Slot *> &slots = skeleton._slots; size_t slotCount = slots.size(); _boundingBoxes.clear(); for (size_t i = 0, n = _polygons.size(); i < n; ++i) { _polygonPool.add(_polygons[i]); } _polygons.clear(); for (size_t i = 0; i < slotCount; i++) { Slot *slot = slots[i]; Attachment *attachment = slot->getAttachment(); if (attachment == NULL || !attachment->getRTTI().instanceOf(BoundingBoxAttachment::rtti)) { continue; } BoundingBoxAttachment *boundingBox = static_cast<BoundingBoxAttachment *>(attachment); _boundingBoxes.add(boundingBox); Polygon *polygonP = NULL; size_t poolCount = _polygonPool.size(); if (poolCount > 0) { polygonP = _polygonPool[poolCount - 1]; _polygonPool.removeAt(poolCount - 1); } else { polygonP = new(__FILE__, __LINE__) Polygon(); } _polygons.add(polygonP); Polygon &polygon = *polygonP; size_t count = boundingBox->getWorldVerticesLength(); polygon._count = count; if (polygon._vertices.size() < count) { polygon._vertices.setSize(count, 0); } boundingBox->computeWorldVertices(*slot, polygon._vertices); } if (updateAabb) { aabbCompute(); } else { _minX = std::numeric_limits<float>::min(); _minY = std::numeric_limits<float>::min(); _maxX = std::numeric_limits<float>::max(); _maxY = std::numeric_limits<float>::max(); } } bool SkeletonBounds::aabbcontainsPoint(float x, float y) { return x >= _minX && x <= _maxX && y >= _minY && y <= _maxY; } bool SkeletonBounds::aabbintersectsSegment(float x1, float y1, float x2, float y2) { float minX = _minX; float minY = _minY; float maxX = _maxX; float maxY = _maxY; if ((x1 <= minX && x2 <= minX) || (y1 <= minY && y2 <= minY) || (x1 >= maxX && x2 >= maxX) || (y1 >= maxY && y2 >= maxY)) { return false; } float m = (y2 - y1) / (x2 - x1); float y = m * (minX - x1) + y1; if (y > minY && y < maxY) { return true; } y = m * (maxX - x1) + y1; if (y > minY && y < maxY) { return true; } float x = (minY - y1) / m + x1; if (x > minX && x < maxX) { return true; } x = (maxY - y1) / m + x1; if (x > minX && x < maxX) { return true; } return false; } bool SkeletonBounds::aabbIntersectsSkeleton(SkeletonBounds bounds) { return _minX < bounds._maxX && _maxX > bounds._minX && _minY < bounds._maxY && _maxY > bounds._minY; } bool SkeletonBounds::containsPoint(Polygon *polygon, float x, float y) { Vector<float> &vertices = polygon->_vertices; int nn = polygon->_count; int prevIndex = nn - 2; bool inside = false; for (int ii = 0; ii < nn; ii += 2) { float vertexY = vertices[ii + 1]; float prevY = vertices[prevIndex + 1]; if ((vertexY < y && prevY >= y) || (prevY < y && vertexY >= y)) { float vertexX = vertices[ii]; if (vertexX + (y - vertexY) / (prevY - vertexY) * (vertices[prevIndex] - vertexX) < x) { inside = !inside; } } prevIndex = ii; } return inside; } BoundingBoxAttachment *SkeletonBounds::containsPoint(float x, float y) { for (size_t i = 0, n = _polygons.size(); i < n; ++i) { if (containsPoint(_polygons[i], x, y)) { return _boundingBoxes[i]; } } return NULL; } BoundingBoxAttachment *SkeletonBounds::intersectsSegment(float x1, float y1, float x2, float y2) { for (size_t i = 0, n = _polygons.size(); i < n; ++i) { if (intersectsSegment(_polygons[i], x1, y1, x2, y2)) { return _boundingBoxes[i]; } } return NULL; } bool SkeletonBounds::intersectsSegment(Polygon *polygon, float x1, float y1, float x2, float y2) { Vector<float> &vertices = polygon->_vertices; size_t nn = polygon->_count; float width12 = x1 - x2, height12 = y1 - y2; float det1 = x1 * y2 - y1 * x2; float x3 = vertices[nn - 2], y3 = vertices[nn - 1]; for (size_t ii = 0; ii < nn; ii += 2) { float x4 = vertices[ii], y4 = vertices[ii + 1]; float det2 = x3 * y4 - y3 * x4; float width34 = x3 - x4, height34 = y3 - y4; float det3 = width12 * height34 - height12 * width34; float x = (det1 * width34 - width12 * det2) / det3; if (((x >= x3 && x <= x4) || (x >= x4 && x <= x3)) && ((x >= x1 && x <= x2) || (x >= x2 && x <= x1))) { float y = (det1 * height34 - height12 * det2) / det3; if (((y >= y3 && y <= y4) || (y >= y4 && y <= y3)) && ((y >= y1 && y <= y2) || (y >= y2 && y <= y1))) { return true; } } x3 = x4; y3 = y4; } return false; } spine::Polygon *SkeletonBounds::getPolygon(BoundingBoxAttachment *attachment) { int index = _boundingBoxes.indexOf(attachment); return index == -1 ? NULL : _polygons[index]; } float SkeletonBounds::getWidth() { return _maxX - _minX; } float SkeletonBounds::getHeight() { return _maxY - _minY; } void SkeletonBounds::aabbCompute() { float minX = std::numeric_limits<float>::min(); float minY = std::numeric_limits<float>::min(); float maxX = std::numeric_limits<float>::max(); float maxY = std::numeric_limits<float>::max(); for (size_t i = 0, n = _polygons.size(); i < n; ++i) { Polygon *polygon = _polygons[i]; Vector<float> &vertices = polygon->_vertices; for (int ii = 0, nn = polygon->_count; ii < nn; ii += 2) { float x = vertices[ii]; float y = vertices[ii + 1]; minX = MathUtil::min(minX, x); minY = MathUtil::min(minY, y); maxX = MathUtil::max(maxX, x); maxY = MathUtil::max(maxY, y); } } _minX = minX; _minY = minY; _maxX = maxX; _maxY = maxY; }
665e5216970f4c46990740a4a92815e0185bc02c
653523b8be62f070a532932074f5fcfec514f9f4
/leetcode/JuneLeetcoding/16 - validateIPAddress.cpp
a743ef6c52c41e84178320fe8031a673b7301013
[]
no_license
nitya2602/competitive-coding
4b02c84f09c8a0bc48ff02ac7dac1a227e613cd2
c161da52ab2791add235836d6661edb1dbf37d6b
refs/heads/master
2023-07-01T03:39:54.968205
2021-08-07T07:34:59
2021-08-07T07:34:59
284,318,327
0
0
null
null
null
null
UTF-8
C++
false
false
2,270
cpp
16 - validateIPAddress.cpp
# too many conditions class Solution { public: string validIPAddress(string IP) { if(IP.size()==0 || IP.size()>40) return "Neither"; if(IP[IP.size()-1]=='.' || IP[IP.size()-1]==':') return "Neither"; if(IP.find('.') != -1) { vector<string> words; string s1 = ""; IP = IP + "."; for(int i=0; i<IP.size(); i++) { if(IP[i]!='.') s1 += IP[i]; else { words.push_back(s1); s1 = ""; } } if(words.size()!=4) return "Neither"; for(int i=0; i<words.size(); i++) { if(words[i].size()==0) return "Neither"; if(words[i][0]=='0' && words[i].size()!=1) return "Neither"; for(int j=0; j<words[i].size(); j++) { if(!(words[i][j]>='0' && words[i][j]<='9')) return "Neither"; } if(stoi(words[i])>255) return "Neither"; } return "IPv4"; } if(IP.find(':') != -1) { vector<string> words; string s1 = ""; IP = IP + ":"; for(int i=0; i<IP.size(); i++) { if(IP[i]!=':') s1 += IP[i]; else { words.push_back(s1); s1 = ""; } } if(words.size()!=8) return "Neither"; for(int i=0; i<words.size(); i++) { if(words[i].size()>4 || words[i].size()==0) return "Neither"; for(int j=0; j<words[i].size(); j++) { if((words[i][j]>='a' && words[i][j]<='f') || (words[i][j]>='A' && words[i][j]<='F') || (words[i][j]>='0' && words[i][j]<='9')) continue; return "Neither"; } } return "IPv6"; } return "Neither"; } };
6a17a053b0b3a5f628d848786fe3936fc30b8e81
8824d24b73a355e41e9914280ee1e46f3163f457
/tmp/04/annex/test/tests.cpp
9ad3c50df2f91030b08d2b9306dc2f0016c34b90
[ "Zlib", "LicenseRef-scancode-unknown-license-reference", "BSL-1.0" ]
permissive
pombredanne/EDGE-2
fe621cbab7c189cd91e2514a946e0f355a82c010
b09f82a65a7ee594f1a544141814647e087b250a
refs/heads/master
2020-12-28T06:57:04.628369
2015-12-29T13:49:37
2015-12-29T20:57:20
48,853,467
1
0
null
2015-12-31T15:20:00
2015-12-31T15:20:00
null
UTF-8
C++
false
false
1,156
cpp
tests.cpp
/////////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2009 Benaka Moorthi // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // /////////////////////////////////////////////////////////////////////////////// #include "plugin.hpp" #include <assert.h> void plugin_load_unload() { annex::plugin<my_plugin_interface> p1("plugin1.dll"); } void multiple_plugin_load_unload() { annex::plugin<my_plugin_interface> p1("plugin1.dll"); annex::plugin<my_plugin_interface> p2("plugin2.dll"); } void multiple_plugin_calls() { annex::plugin<my_plugin_interface> p1("plugin1.dll"); annex::plugin<my_plugin_interface> p2("plugin2.dll"); assert( p1->function_1() == plugin1::function_1_result ); assert( p1->function_2() == plugin1::function_2_result ); assert( p2->function_1() == plugin2::function_1_result ); assert( p2->function_2() == plugin2::function_2_result ); } int main() { plugin_load_unload(); multiple_plugin_load_unload(); multiple_plugin_calls(); }
e6d91e28d3f973a61a7bf275a33c6974569b6856
8ff563bc33437028806847e952da7681a01dbdf6
/oslib.cpp
207651787e7aebd575d8edede098277db7e87701
[]
no_license
adjustive/QFileMan
83a3b126faaf4738d63a335379f17d639bcd4d61
83bcb6708c014038b52cab8adae75434162a4868
refs/heads/master
2021-01-22T09:17:22.339139
2013-05-10T18:01:26
2013-05-10T18:01:26
null
0
0
null
null
null
null
UTF-8
C++
false
false
824
cpp
oslib.cpp
#include <oslib.h> #if defined(Q_OS_WIN32) #include <windows.h> #include <tchar.h> #include <wchar.h>> #elif defined(Q_OS_LINUX) #include <stdlib.h> #include <unistd.h> #endif void osExecute(QString path) { #if defined(Q_OS_WIN32) { QString str = fi.canonicalFilePath(); wchar_t *wc = new wchar_t[str.length()+1]; str.toWCharArray(wc); for(int i = 0;i<str.length()+1;i++) { wc[i] = ((wc[i] != '/') ? wc[i] : '\\'); } ShellExecute(NULL,L"open",wc,NULL,NULL,SW_SHOWNORMAL); } #elif defined(Q_OS_LINUX) system((QString("xdg-open \"") + path + QString("\"")).toStdString().c_str()); #endif } QString pathConv_o2a(QString rootdir,QString str) { return ("/" + str.remove(0,rootdir.length())); } QString pathConv_a2o(QString rootdir,QString str) { return (rootdir + str); }
86673aaa994482eb6285b4268faa45b3f531be02
cae6b918421f0fa67ede241577507a61315233fc
/data-manager/src/server/dataManagerServer/session/frameElaboration/SelectDecoder.hpp
806406f0ada25c9ad5704cc556424c641866c200
[ "MIT" ]
permissive
Saafke/4dm
57e323b65fe7d876d01e59401f2acd60a4c24fb5
68e235164afb1f127def35e9c15ca883ec1426d4
refs/heads/main
2023-06-13T06:56:14.136075
2021-07-07T09:29:29
2021-07-07T09:29:29
383,741,513
0
0
MIT
2021-07-07T09:19:48
2021-07-07T09:19:47
null
UTF-8
C++
false
false
730
hpp
SelectDecoder.hpp
/* * AbstractDecoder.hpp * * Created on: Apr 23, 2019 * Author: mbortolon */ #ifndef SRC_DATAMANAGERSERVER_SESSION_FRAMEELABORATION_SELECTDECODER_HPP_ #define SRC_DATAMANAGERSERVER_SESSION_FRAMEELABORATION_SELECTDECODER_HPP_ #include "AbstractDecoder.hpp" #include "src/common/dataManager/protocol/InitMessage.pb.h" namespace dataManagerServer { namespace session { namespace frameElaboration { dataManagerServer::session::frameElaboration::AbstractDecoder* SelectCorrectDecoder(dataManager::protocol::InitMessage_ContentCodec codec); } /* namespace frameElaboration */ } /* namespace session */ } /* namespace dataManagerServer */ #endif /* SRC_DATAMANAGERSERVER_SESSION_FRAMEELABORATION_SELECT_DECODER_HPP_ */
6e193f7009c00c84d03c9eb15fb26ff0e36a15a0
5b9783418e5c743293edb8cc3ccac04103e69067
/Assignment#3/CashPayment.cpp
d1967eae75e68c6596397e66979af285c87e65ba
[]
no_license
cocotran/COEN244
ebf77c692d22fdb5818bc25481e0199f4abaa4fe
510edd1360f5a357884cd68dd66de7a07fe8a829
refs/heads/master
2023-01-08T13:43:18.089731
2020-10-24T16:54:30
2020-10-24T16:54:30
239,398,914
0
0
null
null
null
null
UTF-8
C++
false
false
321
cpp
CashPayment.cpp
// // CashPayment.cpp // Coen244-Ass3 // // Created by Tawfiq Jawhar on 2019-08-05. // Copyright © 2019 Tawfiq Jawhar. All rights reserved. // #include "CashPayment.h" double CashPayment::calculateAmountToBePaid() const { if(amount > 200) return amount - amount*0.05; else return amount; }
f6b5a8d25ea1a56569dbf0f144732b1d91415497
1f07dec5d6358d2d62b71bcd5dc51eb115cd7316
/rainbow-renderer/importers/obj_importer.hpp
58757fd9859203fe6c8998f2057b1606a50ef488
[ "LicenseRef-scancode-public-domain" ]
permissive
Mason117/rainbow-renderer
f0f00ec05cc21937507d5bdae3352eb6b1aa2fe2
f46a3b536a96eb3a2d18024987ba8e17ef1e173f
refs/heads/master
2023-01-23T19:30:28.107719
2020-12-03T08:05:35
2020-12-03T08:05:35
null
0
0
null
null
null
null
UTF-8
C++
false
false
331
hpp
obj_importer.hpp
#pragma once #include "rainbow-cpu/shapes/mesh.hpp" #include <string> #include <memory> #include <vector> #define __OBJ_IMPORTER__ using namespace rainbow::cpus::shapes; namespace rainbow::renderer::importers { #ifdef __OBJ_IMPORTER__ std::vector<std::shared_ptr<mesh>> load_obj_mesh(const std::string& file_name); #endif }
eb4871fb6651c4051aa885f86002649fbdbda1e1
48a73a0ba850ac2925118dd304baa8f7b2874582
/C++/source/Modeling/YANG/ObjectModel/YangModuleCollection.cpp
6b9cff37affe44687a697fbc92be0eb91b450305
[ "Apache-2.0" ]
permissive
cxvisa/Wave
5e66dfbe32c85405bc2761c509ba8507ff66f8fe
1aca714933ff1df53d660f038c76ca3f2202bf4a
refs/heads/master
2021-05-03T15:00:49.991391
2018-03-31T23:06:40
2018-03-31T23:06:40
56,774,204
2
1
null
null
null
null
UTF-8
C++
false
false
29,618
cpp
YangModuleCollection.cpp
/*************************************************************************** * Copyright (C) 2005-2012 Vidyasagara Guntaka * * All rights reserved. * * Author : Vidyasagara Reddy Guntaka * ***************************************************************************/ #include "Modeling/YANG/ObjectModel/YangModuleCollection.h" #include "Framework/Utils/AssertUtils.h" #include "Framework/Utils/TraceUtils.h" #include "Framework/Utils/StringUtils.h" #include "Modeling/YANG/Parser/YinParser.h" #include "Modeling/YANG/ObjectModel/YangUserInterface.h" #include "SystemManagement/WaveConfigurationSegmentMap.h" #include <fstream> #include <string> using namespace std; namespace WaveNs { YangModuleCollection::YangModuleCollection () { } YangModuleCollection::~YangModuleCollection () { removeAllModules (); } bool YangModuleCollection::isAKnownYangModuleByName (YangModule *pYangModule) const { waveAssert (NULL != pYangModule, __FILE__, __LINE__); const string yangModuleName = pYangModule->getName (); return (isAKnownYangModuleByName (yangModuleName)); } bool YangModuleCollection::isAKnownYangModuleByName (const string &yangModuleName) const { map<string, YangModule *>::const_iterator element = m_yangModulesMap.find (yangModuleName); map<string, YangModule *>::const_iterator endElement = m_yangModulesMap.end (); if (element == endElement) { return (false); } else { return (true); } } bool YangModuleCollection::isAKnownYangModuleByPrefix (YangModule *pYangModule) const { waveAssert (NULL != pYangModule, __FILE__, __LINE__); const string yangModulePrefix = pYangModule->getPrefix (); return (isAKnownYangModuleByPrefix (yangModulePrefix)); } bool YangModuleCollection::isAKnownYangModuleByPrefix (const string &yangModulePrefix) const { map<string, YangModule *>::const_iterator element = m_yangModulesMapByPrefix.find (yangModulePrefix); map<string, YangModule *>::const_iterator endElement = m_yangModulesMapByPrefix.end (); if (element == endElement) { return (false); } else { return (true); } } void YangModuleCollection::addYangModule (YangModule *pYangModule) { waveAssert (NULL != pYangModule, __FILE__, __LINE__); bool isKnown = isAKnownYangModuleByName (pYangModule); bool isKnownByPrefix = isAKnownYangModuleByPrefix (pYangModule); if ((true == isKnown) || (true == isKnownByPrefix)) { waveAssert (false, __FILE__, __LINE__); } else { const string moduleName = pYangModule->getName (); const string modulePrefix = pYangModule->getPrefix (); m_yangModules.push_back (pYangModule); m_yangModulesMap[moduleName] = pYangModule; m_yangModulesMapByPrefix[modulePrefix] = pYangModule; } } void YangModuleCollection::addYangModules (vector<YangModule *> yangModules) { UI32 numberOfYangModules = yangModules.size (); UI32 i = 0; for (i = 0; i < numberOfYangModules; i++) { addYangModule (yangModules[i]); } } void YangModuleCollection::loadModulesFromDirectory (const string &directoryPath) { vector<string> yinFileNames; vector<YangElement *> yangElements; vector<YangModule *> yangModules; UI32 numberOfYangElements = 0; UI32 i = 0; yangElements = YinParser::parseDiretory (directoryPath, yinFileNames); numberOfYangElements = yangElements.size (); for (i = 0; i < numberOfYangElements; i++) { YangElement *pYangElement = yangElements[i]; if (NULL != pYangElement) { YangModule *pYangModule = dynamic_cast<YangModule *> (pYangElement); if (NULL != pYangModule) { yangModules.push_back (pYangModule); } } } addYangModules (yangModules); } void YangModuleCollection::loadModuleFromFile (const string &filePath) { YangElement *pYangElement = NULL; YangModule *pYangModule = NULL; pYangElement = YinParser::parseFile (filePath); if (NULL != pYangElement) { pYangModule = dynamic_cast<YangModule *> (pYangElement); if (NULL != pYangModule) { addYangModule (pYangModule); } } } void YangModuleCollection::loadModulesFromDirectoriesAndFiles (const vector<string> &directoryPaths, const vector<string> &yinFileNames) { vector<string> outputYinFileNames; vector<YangElement *> yangElements; vector<YangModule *> yangModules; UI32 numberOfYangElements = 0; UI32 i = 0; yangElements = YinParser::parseDirectoriesAndFiles (directoryPaths, yinFileNames, outputYinFileNames); numberOfYangElements = yangElements.size (); for (i = 0; i < numberOfYangElements; i++) { YangElement *pYangElement = yangElements[i]; if (NULL != pYangElement) { YangModule *pYangModule = dynamic_cast<YangModule *> (pYangElement); if (NULL != pYangModule) { yangModules.push_back (pYangModule); } } } addYangModules (yangModules); } void YangModuleCollection::removeAllModules () { UI32 numberOfYangModules = m_yangModules.size (); UI32 i = 0; for (i = 0; i < numberOfYangModules; i++) { delete m_yangModules[i]; } clearAllModules (); } void YangModuleCollection::clearAllModules () { m_yangModules.clear (); m_yangModulesMap.clear (); m_yangModulesMapByPrefix.clear (); } void YangModuleCollection::getAllKnownModules (vector<string> &allKnownYangModules) { UI32 numberOfYangModules = m_yangModules.size (); UI32 i = 0; allKnownYangModules.clear (); for (i = 0; i < numberOfYangModules; i++) { const string yangModuleName = (m_yangModules[i])->getName (); allKnownYangModules.push_back (yangModuleName); } } YangModule *YangModuleCollection::getYangModuleByName (const string &yangModuleName) const { YangModule *pYangModule = NULL; if (true == (isAKnownYangModuleByName (yangModuleName))) { map<string, YangModule *>::const_iterator element = m_yangModulesMap.find (yangModuleName); pYangModule = element->second; waveAssert (NULL != pYangModule, __FILE__, __LINE__); } return (pYangModule); } YangModule *YangModuleCollection::getYangModuleByPrefix (const string &yangModulePrefix) const { YangModule *pYangModule = NULL; if (true == (isAKnownYangModuleByPrefix (yangModulePrefix))) { map<string, YangModule *>::const_iterator element = m_yangModulesMapByPrefix.find (yangModulePrefix); pYangModule = element->second; waveAssert (NULL != pYangModule, __FILE__, __LINE__); } return (pYangModule); } YangModuleCollection *YangModuleCollection::clone () const { UI32 numberOfYangModules = m_yangModules.size (); UI32 i = 0; YangModuleCollection *pClonedYangModuleCollection = new YangModuleCollection (); waveAssert (NULL != pClonedYangModuleCollection, __FILE__, __LINE__); for (i = 0; i < numberOfYangModules; i++) { YangModule *pYangModule = m_yangModules[i]; waveAssert (NULL != pYangModule, __FILE__, __LINE__); YangModule *pClonedYangModule = dynamic_cast<YangModule *> (pYangModule->clone ()); waveAssert (NULL != pClonedYangModule, __FILE__, __LINE__); pClonedYangModuleCollection->addYangModule (pClonedYangModule); } return (pClonedYangModuleCollection); } void YangModuleCollection::transferAllModulesToUserInterface (YangUserInterface *pYangUSerInterface) { map<string, YangModule *>::const_iterator element = m_yangModulesMap.begin (); map<string, YangModule *>::const_iterator endElement = m_yangModulesMap.end (); while (endElement != element) { YangModule *pYangModule = element->second; waveAssert (NULL != pYangModule, __FILE__, __LINE__); pYangUSerInterface->addChildElement (pYangModule); element++; } clearAllModules (); } void YangModuleCollection::computeUsageCountForGroupings () { UI32 numberOfYangModules = m_yangModules.size (); UI32 i = 0; for (i = 0; i < numberOfYangModules; i++) { YangModule *pYangModule = m_yangModules[i]; waveAssert (NULL != pYangModule, __FILE__, __LINE__); pYangModule->computeUsageCountForGroupings (this); } } void YangModuleCollection::computeUsageCountForGroupingsForProgrammingLanguages () { UI32 numberOfYangModules = m_yangModules.size (); UI32 i = 0; for (i = 0; i < numberOfYangModules; i++) { YangModule *pYangModule = m_yangModules[i]; waveAssert (NULL != pYangModule, __FILE__, __LINE__); pYangModule->computeUsageCountForGroupingsForProgrammingLanguages (this); } } void YangModuleCollection::inlineGroupingUsage () { UI32 numberOfYangModules = m_yangModules.size (); UI32 i = 0; for (i = 0; i < numberOfYangModules; i++) { YangModule *pYangModule = m_yangModules[i]; waveAssert (NULL != pYangModule, __FILE__, __LINE__); pYangModule->inlineGroupingUsage (this); } } void YangModuleCollection::inlineGroupingUsageForRpcs () { UI32 numberOfYangModules = m_yangModules.size (); UI32 i = 0; for (i = 0; i < numberOfYangModules; i++) { YangModule *pYangModule = m_yangModules[i]; waveAssert (NULL != pYangModule, __FILE__, __LINE__); pYangModule->inlineGroupingUsageForRpcs (this); } } void YangModuleCollection::inlineAugmentUsage () { UI32 numberOfYangModules = m_yangModules.size (); UI32 i = 0; UI32 numberOfAugmentsResolved = 1; UI32 numberOfAugmentsNotResolved = 1; UI32 numberOfAugmentsResolvedPerModule = 1; UI32 numberOfAugmentsNotResolvedPerModule = 1; UI32 passNumber = 0; while (0 != numberOfAugmentsNotResolved && passNumber < 100) { passNumber++; cout << "PASS : " << passNumber << endl; numberOfAugmentsResolved = 0; numberOfAugmentsNotResolved = 0; for (i = 0; i < numberOfYangModules; i++) { YangModule *pYangModule = m_yangModules[i]; waveAssert (NULL != pYangModule, __FILE__, __LINE__); numberOfAugmentsResolvedPerModule = 0; numberOfAugmentsNotResolvedPerModule = 0; pYangModule->inlineAugmentUsage (this, numberOfAugmentsResolvedPerModule, numberOfAugmentsNotResolvedPerModule); numberOfAugmentsResolved += numberOfAugmentsResolvedPerModule; numberOfAugmentsNotResolved += numberOfAugmentsNotResolvedPerModule; } } for (i = 0; i < numberOfYangModules; i++) { YangModule *pYangModule = m_yangModules[i]; waveAssert (NULL != pYangModule, __FILE__, __LINE__); pYangModule->rearrangeAugmenterChildElements (); } } void YangModuleCollection::checkIntegrity () const { UI32 numberOfYangModules = m_yangModules.size (); UI32 i = 0; for (i = 0; i < numberOfYangModules; i++) { YangModule *pYangModule = m_yangModules[i]; waveAssert (NULL != pYangModule, __FILE__, __LINE__); pYangModule->checkIntegrity (); } } void YangModuleCollection::removeAllUnusedGroupings () { UI32 numberOfYangModules = m_yangModules.size (); UI32 i = 0; for (i = 0; i < numberOfYangModules; i++) { YangModule *pYangModule = m_yangModules[i]; waveAssert (NULL != pYangModule, __FILE__, __LINE__); pYangModule->removeAllUnusedGroupings (); } } void YangModuleCollection::removeAllGroupings () { UI32 numberOfYangModules = m_yangModules.size (); UI32 i = 0; for (i = 0; i < numberOfYangModules; i++) { YangModule *pYangModule = m_yangModules[i]; waveAssert (NULL != pYangModule, __FILE__, __LINE__); pYangModule->removeAllGroupings (); } } void YangModuleCollection::printYinForQualifiedYangPath (const string &qualifiedYangPath, FILE *pFile) const { if (NULL == pFile) { pFile = stdout; } string moduleName; string targetNodePath; getTargetNodeDetails (qualifiedYangPath, moduleName, targetNodePath); cout << "Printing YIN for " << moduleName << ":" << targetNodePath << endl; YangModule *pYangModule = getYangModuleByName (moduleName); if (NULL != pYangModule) { pYangModule->printYinForTargetNode (targetNodePath, pFile); } } void YangModuleCollection::printYinForQualifiedYangPathToFile (const string &qualifiedYangPath, const string &filePath) const { FILE *pFile = NULL; if ("" != filePath) { pFile = fopen (filePath.c_str (), "w"); if (NULL != pFile) { printYinForQualifiedYangPath (qualifiedYangPath, pFile); fclose (pFile); } } else { pFile = stdout; printYinForQualifiedYangPath (qualifiedYangPath, pFile); } } void YangModuleCollection::printYinForPrefixQualifiedYangPath (const string &prefixQualifiedYangPath, FILE *pFile) const { if (NULL == pFile) { pFile = stdout; } string modulePrefix; string targetNodePath; getTargetNodeDetails (prefixQualifiedYangPath, modulePrefix, targetNodePath); cout << "Printing YIN for " << modulePrefix << ":" << targetNodePath << endl; YangModule *pYangModule = getYangModuleByPrefix (modulePrefix); if (NULL != pYangModule) { pYangModule->printYinForTargetNode (targetNodePath, pFile); } } void YangModuleCollection::printYinForPrefixQualifiedYangPathToFile (const string &prefixQualifiedYangPath, const string &filePath) const { FILE *pFile = NULL; if ("" != filePath) { pFile = fopen (filePath.c_str (), "w"); if (NULL != pFile) { printYinForPrefixQualifiedYangPath (prefixQualifiedYangPath, pFile); fclose (pFile); } } else { pFile = stdout; printYinForPrefixQualifiedYangPath (prefixQualifiedYangPath, pFile); } } void YangModuleCollection::printYinForAllModules (FILE *pFile) const { if (NULL == pFile) { pFile = stdout; } UI32 numberOfYangModules = m_yangModules.size (); UI32 i = 0; cout << "Printing YIN for all modules ..." << endl; for (i = 0; i < numberOfYangModules; i++) { YangModule *pYangModule = m_yangModules[i]; waveAssert (NULL != pYangModule, __FILE__, __LINE__); string moduleName = pYangModule->getName (); cout << " Processing " << moduleName << " ... "; pYangModule->printYin (0, true, pFile); cout << "Done." << endl; } } void YangModuleCollection::printYinForAllModulesToFile (const string &filePath) const { FILE *pFile = NULL; if ("" != filePath) { pFile = fopen (filePath.c_str (), "w"); if (NULL != pFile) { printYinForAllModules (pFile); fclose (pFile); } } else { pFile = stdout; printYinForAllModules (pFile); } } void YangModuleCollection::printYinForModule (const string &moduleName, FILE *pFile) const { if (NULL == pFile) { pFile = stdout; } YangModule *pYangModule = getYangModuleByName (moduleName); if (NULL != pYangModule) { cout << "Printing YIN for module " << moduleName << " ... "; pYangModule->printYin (0, true, pFile); cout << "Done." << endl; } } void YangModuleCollection::printYinForModuleToFile (const string &moduleName, const string &filePath) const { FILE *pFile = NULL; if ("" != filePath) { pFile = fopen (filePath.c_str (), "w"); if (NULL != pFile) { printYinForModule (moduleName, pFile); fclose (pFile); } } else { pFile = stdout; printYinForModule (moduleName, pFile); } } void YangModuleCollection::getTargetNodeDetails (const string &qualifiedYangPath, string &moduleName, string &targetNodePath) const { vector<string> qualifiedYangPathLevel1Tokens; UI32 numberOfLevel1TokensInQualifiedYangPath = 0; UI32 i = 0; moduleName = ""; targetNodePath = ""; StringUtils::tokenize (qualifiedYangPath, qualifiedYangPathLevel1Tokens, '/'); numberOfLevel1TokensInQualifiedYangPath = qualifiedYangPathLevel1Tokens.size (); for (i = 0; i < numberOfLevel1TokensInQualifiedYangPath; i++) { vector<string> qualifiedYangPathLevel2Tokens; UI32 numberOfLevel2TokensInQualifiedYangPath = 0; StringUtils::tokenize (qualifiedYangPathLevel1Tokens[i], qualifiedYangPathLevel2Tokens, ':'); numberOfLevel2TokensInQualifiedYangPath = qualifiedYangPathLevel2Tokens.size (); waveAssert (1 <= numberOfLevel2TokensInQualifiedYangPath, __FILE__, __LINE__); waveAssert (2 >= numberOfLevel2TokensInQualifiedYangPath, __FILE__, __LINE__); if (2 == numberOfLevel2TokensInQualifiedYangPath) { targetNodePath += "/" + qualifiedYangPathLevel2Tokens[1]; if (0 == i) { moduleName = qualifiedYangPathLevel2Tokens[0]; } } else { targetNodePath += "/" + qualifiedYangPathLevel2Tokens[0]; } } } void YangModuleCollection::getAllNames (set<string> &allNames) const { UI32 numberOfYangModules = m_yangModules.size (); UI32 i = 0; for (i = 0; i < numberOfYangModules; i++) { YangModule *pYangModule = m_yangModules[i]; waveAssert (NULL != pYangModule, __FILE__, __LINE__); pYangModule->getAllNames (allNames); } } void YangModuleCollection::printAllNames (FILE *pFile) const { if (NULL == pFile) { pFile = stdout; } set<string> allNames; getAllNames (allNames); set<string>::const_iterator element = allNames.begin (); set<string>::const_iterator endElement = allNames.end (); while (endElement != element) { fprintf (pFile, "%s\n", (*element).c_str ()); element++; } } void YangModuleCollection::printAllNamesToFile (const string &filePath) const { FILE *pFile = NULL; if ("" != filePath) { pFile = fopen (filePath.c_str (), "w"); if (NULL != pFile) { printAllNames (pFile); fclose (pFile); } } else { pFile = stdout; printAllNames (pFile); } } void YangModuleCollection::getAllCliTargetNodeNamesForData (vector<string> &allCliTargetNodeNamesForData) const { UI32 numberOfYangModules = m_yangModules.size (); UI32 i = 0; for (i = 0; i < numberOfYangModules; i++) { YangModule *pYangModule = m_yangModules[i]; waveAssert (NULL != pYangModule, __FILE__, __LINE__); pYangModule->getAllCliTargetNodeNamesForData (allCliTargetNodeNamesForData); } } void YangModuleCollection::printAllCliTargetNodeNamesForData (FILE *pFile) const { if (NULL == pFile) { pFile = stdout; } vector<string> allCliTargetNodeNamesForData; getAllCliTargetNodeNamesForData (allCliTargetNodeNamesForData); vector<string>::const_iterator element = allCliTargetNodeNamesForData.begin (); vector<string>::const_iterator endElement = allCliTargetNodeNamesForData.end (); while (endElement != element) { fprintf (pFile, "%s\n", (*element).c_str ()); element++; } } void YangModuleCollection::printAllCliTargetNodeNamesForDataToFile (const string &filePath) const { FILE *pFile = NULL; if ("" != filePath) { pFile = fopen (filePath.c_str (), "w"); if (NULL != pFile) { printAllCliTargetNodeNamesForData (pFile); fclose (pFile); } } else { pFile = stdout; printAllCliTargetNodeNamesForData (pFile); } } void YangModuleCollection::loadUserTagsFromFile (const string &userTagsFilePath) { ifstream userTagsFileStream (userTagsFilePath.c_str ()); char *pLine = NULL; string line; vector<string> tokens; UI32 numberOfTokens = 0; pLine = (char *) malloc (sizeof (char) * 1024); waveAssert (NULL != pLine, __FILE__, __LINE__); if (false == (userTagsFileStream.is_open ())) { trace (TRACE_LEVEL_ERROR, "YangModuleCollection::loadUserTagsFromFile : " + userTagsFilePath + " could not be opened."); free (pLine); return; } while (false == (userTagsFileStream.eof ())) { getline (userTagsFileStream, line); tokens.clear (); StringUtils::tokenize (line, tokens, ' '); numberOfTokens = tokens.size (); if (2 == numberOfTokens) { string userTagName = tokens[0]; UI32 userTagValue = strtoul (tokens[1].c_str (), NULL, 10); addUserTag (userTagName, userTagValue); } } free (pLine); userTagsFileStream.close (); trace (TRACE_LEVEL_INFO, string ("YangModuleCollection::loadUserTagsFromFile : Number Of loaded User Tags : ") + m_userTagsMap.size ()); } void YangModuleCollection::addUserTag (const string &userTagName, const UI32 &userTagValue) { m_userTagsMap[userTagName] = userTagValue; } UI32 YangModuleCollection::getUserTagValueByName (const string &userTagName) const { map<string, UI32>::const_iterator element = m_userTagsMap.find (userTagName); map<string, UI32>::const_iterator endElement = m_userTagsMap.end (); UI32 userTagValue = 0; if (endElement != element) { userTagValue = element->second; } return (userTagValue); } void YangModuleCollection::updateModulesWithUserTags () { UI32 numberOfYangModules = m_yangModules.size (); UI32 i = 0; for (i = 0; i < numberOfYangModules; i++) { YangModule *pYangModule = m_yangModules[i]; waveAssert (NULL != pYangModule, __FILE__, __LINE__); pYangModule->updateUserTags (this); } } void YangModuleCollection::computeConfigurationSegmentNames () { UI32 numberOfYangModules = m_yangModules.size (); UI32 i = 0; for (i = 0; i < numberOfYangModules; i++) { YangModule *pYangModule = m_yangModules[i]; waveAssert (NULL != pYangModule, __FILE__, __LINE__); pYangModule->computeConfigurationSegmentNames (); } } YangElement *YangModuleCollection::getYangElementByQualifiedYangPath (const string &qualifiedYangPath) const { string moduleName; string targetNodePath; getTargetNodeDetails (qualifiedYangPath, moduleName, targetNodePath); YangModule *pYangModule = getYangModuleByName (moduleName); YangElement *pYangElement = NULL; if (NULL != pYangModule) { pYangElement = pYangModule->getYangElementByTargetNodePath (targetNodePath); } return (pYangElement); } YangElement *YangModuleCollection::getYangElementByPrefixQualifiedYangPath (const string &prefixQualifiedYangPath) const { string modulePrefix; string targetNodePath; getTargetNodeDetails (prefixQualifiedYangPath, modulePrefix, targetNodePath); YangModule *pYangModule = getYangModuleByPrefix (modulePrefix); YangElement *pYangElement = NULL; if (NULL != pYangModule) { pYangElement = pYangModule->getYangElementByTargetNodePath (targetNodePath); } return (pYangElement); } void YangModuleCollection::computeCliTargetNodeNames () { UI32 numberOfYangModules = m_yangModules.size (); UI32 i = 0; for (i = 0; i < numberOfYangModules; i++) { YangModule *pYangModule = m_yangModules[i]; waveAssert (NULL != pYangModule, __FILE__, __LINE__); pYangModule->computeCliTargetNodeNames (); } } // TODO Get this information registered from libDcm. void YangModuleCollection::markNodeSpecificAndPartitionBaseYangElements () { do { YangElement *pYangModuleForNodeSpecific = getYangModuleByName ("brocade-rbridge"); if (NULL == pYangModuleForNodeSpecific) { break; } // waveAssert (NULL != pYangModuleForNodeSpecific, __FILE__, __LINE__); // rolling reboot. YangElement *pYangElementForNodeSpecificList = pYangModuleForNodeSpecific->getYangElementForTargetNode ("/rbridge-id"); if (NULL == pYangElementForNodeSpecificList) { break; } // waveAssert (NULL != pYangElementForNodeSpecificList, __FILE__, __LINE__); YangDataElement *pYangDataElementForNodeSpecificList = dynamic_cast<YangDataElement *> (pYangElementForNodeSpecificList); if (NULL == pYangDataElementForNodeSpecificList) { break; } // waveAssert (NULL != pYangDataElementForNodeSpecificList, __FILE__, __LINE__); pYangDataElementForNodeSpecificList->setIsNodeSpecificBaseList (); WaveConfigurationSegmentMap::setConfigurationSegmentNameForNodeSpecificList (pYangDataElementForNodeSpecificList->getConfigurationSegmentName ()); YangElement *pYangElementForMultiPartitionList = pYangModuleForNodeSpecific->getYangElementForTargetNode ("/rbridge-id/vrf"); if (NULL == pYangElementForMultiPartitionList) { break; } // waveAssert (NULL != pYangElementForMultiPartitionList, __FILE__, __LINE__); YangDataElement *pYangDataElementForMultiPartitionList = dynamic_cast<YangDataElement *> (pYangElementForMultiPartitionList); if (NULL == pYangDataElementForMultiPartitionList) { break; } // waveAssert (NULL != pYangDataElementForMultiPartitionList, __FILE__, __LINE__); pYangDataElementForMultiPartitionList->setIsMultiPartitionBaseList (); WaveConfigurationSegmentMap::setConfigurationSegmentNameForMultiPartitionList (pYangDataElementForMultiPartitionList->getConfigurationSegmentName ()); } while (0); } void YangModuleCollection::processTypeInformations () { UI32 numberOfYangModules = m_yangModules.size (); for (UI32 i = 0; i < numberOfYangModules; i++) { YangModule *pYangModule = m_yangModules[i]; waveAssert (NULL != pYangModule, __FILE__, __LINE__); pYangModule->processTypeInformations (); } } void YangModuleCollection::inlineTypedef () { UI32 numberOfYangModules = m_yangModules.size (); UI32 i = 0; for (i = 0; i < numberOfYangModules; i++) { YangModule *pYangModule = m_yangModules[i]; waveAssert (NULL != pYangModule, __FILE__, __LINE__); pYangModule->inlineTypedefInsideModule (); } for (i = 0; i < numberOfYangModules; i++) { YangModule *pYangModule = m_yangModules[i]; waveAssert (NULL != pYangModule, __FILE__, __LINE__); pYangModule->inlineTypedefFromImportedModule (this); } } UI32 YangModuleCollection::getNumberOfAllChildYangElementsInAllModules () const { UI32 numberOfAllChildElementsInTree = 0; UI32 numberOfYangModules = m_yangModules.size (); for (UI32 i = 0; i < numberOfYangModules; i++) { YangModule *pYangModule = m_yangModules[i]; waveAssert (NULL != pYangModule, __FILE__, __LINE__); numberOfAllChildElementsInTree += pYangModule->getNumberOfAllChildYangElementsInTree (); } return numberOfAllChildElementsInTree + numberOfYangModules; } void YangModuleCollection::setOriginalModuleNameSpaceUriInAllModules () { UI32 numberOfYangModules = m_yangModules.size (); for (UI32 i = 0; i < numberOfYangModules; i++) { YangModule *pYangModule = m_yangModules[i]; waveAssert (NULL != pYangModule, __FILE__, __LINE__); pYangModule->setOriginalModuleNameSpaceUriForTree (); } // std::stable_sort (m_yangModules.begin (), m_yangModules.end (), YangModule::compareYangModulesByNamespaceUri); } void YangModuleCollection::generateHFilesForCLanguageForAllModules () const { UI32 numberOfYangModules = m_yangModules.size (); UI32 i = 0; cout << "Generating H (C) for all modules ..." << endl; for (i = 0; i < numberOfYangModules; i++) { YangModule *pYangModule = m_yangModules[i]; waveAssert (NULL != pYangModule, __FILE__, __LINE__); string moduleName = pYangModule->getName (); cout << " Generating H (C) file for " << moduleName << " ... "; pYangModule->generateHFileForCLanguage (*this); cout << "Done." << endl; } } }
0eb710f142d9ddfed53a8c921c2d183a77396d62
e6f237e5f76d66795a4c5a342ccef357e4a76d09
/LinkedListDemo/LinkedList.h
e4f94df7bca967409cff41603676dde80ce3220b
[]
no_license
Masi-B/LinkedListDemo
b29a0cb948b0d9ad2b47d3a186a4b262abce59cc
bc6bda8ba9ce82e2cc3360cbca0c8e8252acf7d5
refs/heads/main
2023-01-23T15:59:25.953268
2020-12-06T02:12:06
2020-12-06T02:12:06
318,925,969
0
0
null
null
null
null
UTF-8
C++
false
false
1,446
h
LinkedList.h
#pragma once #ifndef LinkedL_H #define LinkedL_H #include <cstdlib> #include <string> #include "Node.h" #include "Node.h" #include <string> #include <cstdlib> template <typename T> class LinkedList { public: //default constructor creates empty list LinkedList<T>(); //copy constructor to copy a linked list onto another LinkedList<T>(const LinkedList<T>& list1); //destructor ~LinkedList<T>(); //adds data to linked list void add(T& data); //length of linked list std::size_t length() const; //accessors for last node data Node<T>* getTailPointer() const; Node<T>* getTailPointer(); //accessors for the first node data Node<T>* getHeadPointer() const; Node<T>* getHeadPointer(); //count number of words in linked list void size(T& data); //delete node void remove(); LinkedList<T>& operator+(const LinkedList<T>& l); //Overloaded assignment operator to copy one linked list onto another LinkedList<T>& operator=(const LinkedList<T>& list1); //private variables, headpointer points to the first node on the list //tailpointer points to the last node on the list //listlength is the length of the linked list private: Node<T>* headpointer; Node<T>* tailpointer; std::size_t listLength; }; template <typename T> std::istream& operator >> (std::istream& input, LinkedList<T>& list1); template <typename T> std::ostream& operator << (std::ostream& output, LinkedList<T>& list1); #include "LinkedList.hpp" #endif //
600c52ce3a77f8f486d1dd8618267fe98778b036
cf58b5586206b2f05e5c172d85d7533e1840a11e
/cpp/range_query/bit.cpp
f35849072ea01df2d46c248ce80357daaf5250f7
[]
no_license
tjkendev/procon-library
c467862fa995b74f3ad33028b1836bd2456d24ae
1e766cdfd65238933a1b6a13bf022a1a8c643532
refs/heads/master
2023-04-27T15:21:07.229430
2023-04-14T16:34:33
2023-04-14T16:34:33
23,149,541
15
0
null
2023-01-01T12:54:03
2014-08-20T13:27:13
Python
UTF-8
C++
false
false
366
cpp
bit.cpp
using ll = long long; #define N 100008 class BIT { int n; ll data[N]; public: BIT(int n) : n(n) { for(int i = 0; i < n+2; ++i) data[i] = 0; } void add(int k, ll x) { while(k <= n) { data[k] += x; k += k & -k; } } ll get(int k) { ll s = 0; while(k) { s += data[k]; k -= k & -k; } return s; } };
16b23912f7e9632e069461b1a0b0b192ccf7af78
d582c8d3708b01d8662942242cd2fb66b948d350
/arch/arm/pagingarm.cpp
0cc64402ec8fee36098151b16525a0613361fde4
[ "MIT" ]
permissive
jroivas/cxx-kernel
8b35ccbf4936599d5e66fc8e7f035813856ddb43
e252e89fe843f9b7cb23a19cb9d1121b9d235670
refs/heads/master
2021-11-08T02:21:44.383505
2021-08-23T18:27:04
2021-09-08T17:17:33
29,395,784
1
0
null
null
null
null
UTF-8
C++
false
false
22,150
cpp
pagingarm.cpp
#include "pagingarm.h" #include "types.h" //#include "x86.h" #include "bits.h" #define PDIR(x) ((PageDir*)x) #define BITS(x) ((Bits*)x) //#define KERNEL_PRE_POS 0x20000000 #define KERNEL_PRE_POS 0x200000 //FIXME #define KERNEL_INIT_SIZE 0x000FFFFF #define HEAP_START 0x30000000 #define HEAP_END 0x3FFFFFFF #define USER_HEAP_START 0x40000000 #define USER_HEAP_END 0x4FFFFFFF static ptr8_t __free_page_address = (ptr8_t)KERNEL_PRE_POS; //static ptr8_t __heap_address = (ptr8_t)HEAP_START; //static ptr8_t __user_heap_address = (ptr8_t)USER_HEAP_START; static ptr32_val_t __mem_size = 0; /* Memory mapping structure */ struct MemoryMap { unsigned long size; unsigned long base_addr_low; unsigned long base_addr_high; unsigned long length_low; unsigned long length_high; unsigned long type; }; #if 0 extern "C" void pagingEnable(); extern "C" void pagingDisable(); extern "C" void pagingDirectoryChange(ptr_t a); extern "C" void copyPhysicalPage(ptr_val_t a, ptr_val_t b); #endif extern unsigned int kernel_end; extern "C" void pagingEnable() { asm("mrc p15, 0, r0, c1, c0, 0"); asm("orr r0, r0, #0x1"); asm("mrc p15, 0, r0, c1, c0, 0"); } extern "C" void pagingDisable() { // Do we really want to do this? asm("mrc p15, 0, r0, c1, c0, 0"); //asm("and r0, r0, #0xfffffffe"); asm("bic r0, r0, #0x1"); asm("mrc p15, 0, r0, c1, c0, 0"); } extern "C" void setPagingDirectory(unsigned int table) { asm("ldr r0, %[table]" : : [table] "imm" (table) ); asm("mcr p15, 0, r0, c2, c0, 0"); } //Mutex for locking mapping and prevent theading/SMP problems ptr32_val_t __page_mapping_mutex = 0; ptr32_val_t __page_mapping_static_mutex = 0; void Page::copyPhys(Page p) { (void)p; //copyPhysicalPage(getAddress(), p.getAddress()); } void Page::alloc(PageType type) { if (!isAvail()) return; Paging p; void *page = p.getPage(); if (page==nullptr) return; setAddress((ptr_val_t)page); setPresent(true); setRw(true); if (type==KernelPage) { setUserspace(false); } else { setUserspace(true); } } PageTable::PageTable() { #if 0 for (unsigned int i=0; i<PAGES_PER_TABLE; i++) { pages[i] = Page(); } #endif } Page *PageTable::get(uint32_t i) { if (i<PAGES_PER_TABLE) return &pages[i]; return nullptr; } bool PageTable::copyTo(PageTable *table) { if (table==nullptr) return false; //Paging p; for (int i=0; i<PAGES_PER_TABLE; i++) { if (pages[i].isAvail()) { table->pages[i].alloc(); pages[i].copyTo(&table->pages[i]); pages[i].copyPhys(table->pages[i]); } } return true; } ptr32_val_t roundTo4k(ptr32_val_t s) { while (s%4096!=0) s++; return s; } ptr32_val_t roundTo1k(ptr32_val_t s) { while (s%1024!=0) s++; return s; } #if 0 ptr32_val_t firstLevelTableSection(ptr32_val_t section, ptr32_val_t domain, PageDir::MMUPermissions permissions) { //0x000-0xFFF ptr32_val_t val = 0; val |= (section & 0xFFF) << 20; val |= 2; //Section desc switch(permissions) { case MMU_NO_NO: // Should set System=0 and Rom=0 in CP15 break; case MMU_RO_NO: // Should set System=1 and Rom=0 in CP15 break; case MMU_RO_RO: // Should set System=0 and Rom=1 in CP15 break; case MMU_RW_NO: //01 val |= (1<<10); break; case MMU_RW_RO: //10 val |= (2<<10); break; case MMU_RW_RW: //11 val |= (3<<10); break; }; val |= (domain & 0x1f) << 5; return val; } ptr32_val_t firstLevelTableCoarse(ptr32_val_t addr, ptr32_val_t domain) { ptr32_val_t val = 0; val |= (addr & 0xFFFFF800); val |= 1; //Coarse page desc val |= (domain & 0x1f) << 5; return val; } ptr32_val_t secondLevelTable(ptr32_val_t addr, ptr32_val_t level, MMUPermissions permissions) { ptr32_val_t val = 0; if (level==0x1) { val |= (addr & 0xFFFF0000); } else if (level==0x2) { val |= (addr & 0xFFFFF000); } else if (level==0x3) { val |= (addr & 0xFFFFFC00); } else { //ERROR!!! Handle? return 0; } val |= level; ptr32_val_t per = 0; switch(permissions) { case MMU_NO_NO: // Should set System=0 and Rom=0 in CP15 break; case MMU_RO_NO: // Should set System=1 and Rom=0 in CP15 break; case MMU_RO_RO: // Should set System=0 and Rom=1 in CP15 break; case MMU_RW_NO: //01 per = 1; break; case MMU_RW_RO: //10 per = 2; break; case MMU_RW_RW: //11 per = 3; break; }; val |= (per<<4); if (level!=0x3) { val |= (per<<6); val |= (per<<8); val |= (per<<10); } return val; } #endif PageDir::PageDir(uint32_t physLoc) { phys = (ptr_t)physLoc; uint32_t tmp = physLoc; for (uint32_t i = 0; i<0x1000; i++) { *((uint32_t*)tmp) = 0; tmp += 4; } free_pos = 0; free_page_section = 1; free_page_pos = 0; } uint32_t PageDir::getPage() { if (free_page_pos<1024) { uint32_t p = free_page_pos; free_page_pos += 16; uint32_t table = getCoarseTable(free_pos); (void)p; (void)table; } return 0; } uint32_t PageDir::permissions(PageDir::MMUPermissions permissions) { uint32_t tmp = 0; switch(permissions) { case MMU_NO_NO: // Should set System=0 and Rom=0 in CP15 break; case MMU_RO_NO: // Should set System=1 and Rom=0 in CP15 break; case MMU_RO_RO: // Should set System=0 and Rom=1 in CP15 break; case MMU_RW_NO: //01 tmp = 1; break; case MMU_RW_RO: //10 tmp = 2; break; case MMU_RW_RW: //11 tmp = 3; break; }; return tmp; } ptr32_val_t PageDir::createSection(ptr32_val_t section, ptr32_val_t addr, ptr32_val_t domain, PageDir::MMUPermissions section_permissions) { ptr32_val_t val = 0; //uint32_t section = (addr >> 20) & 0xFFF; section &= 0xFFF; val |= (addr & 0xFFF00000); val |= 2; //Section desc val |= (permissions(section_permissions)<<10); val |= (domain & 0x1f) << 5; ptr_t pos = phys; pos[section] = val; return val; } ptr32_val_t PageDir::setCoarseTable(ptr32_val_t section, ptr32_val_t val) { section &= 0xFFF; ptr_t pos = phys; pos[section] = val; return val; } ptr32_val_t PageDir::getCoarseTable(ptr32_val_t section) { ptr_t pos = phys; ptr32_val_t val = pos[section]; return (val & 0xFFF00000); } //Just returns te value, need to set in table ptr32_val_t PageDir::createCoarseTable(ptr32_val_t addr, ptr32_val_t domain, PageDir::MMUPermissions section_permissions) { ptr32_val_t val = 0; val |= (addr & 0xFFFFF800); val |= 1; //Coarse page desc val |= (domain & 0x1f) << 5; ptr32_val_t per = permissions(section_permissions); val |= (per<<4); val |= (per<<6); val |= (per<<8); val |= (per<<10); return val; } //B3-13 /* extern uint32_t kernel_end; extern uint32_t my_kernel_end; */ PagingPrivate::PagingPrivate() { m.assign(&__page_mapping_mutex); m_static.assign(&__page_mapping_static_mutex); data = nullptr; pageCnt = 0; __mem_size = 0; is_ok = false; // Map free space after kernel //__free_page_address = (ptr8_t)my_kernel_end; // Create the table, we're spending some memory here... if (kernel_end>(ptr_val_t)__free_page_address) __free_page_address = (ptr8_t)kernel_end; __free_page_address = (ptr8_t)roundTo4k((ptr32_val_t)__free_page_address); ptr32_t pagingDir = (ptr32_t)__free_page_address; PageDir *pdir = new PageDir((ptr32_val_t)pagingDir); pdir->incFreePos(); // Get the free addr // Ok, setting the first level paging dir //FIXME: setPagingDirectory((ptr32_val_t)pagingDir); ptr32_t pd = pagingDir; ptr32_val_t tmp = pdir->createSection(0, 0, 0, PageDir::MMU_RW_RW); *pd++ = tmp; #if 1 tmp = pdir->createSection(1, 0, 0, PageDir::MMU_RW_RW); *pd++ = tmp; tmp = pdir->createSection(2, 0, 0, PageDir::MMU_RW_RW); *pd++ = tmp; #endif //Reserve it __free_page_address += 4096*4; // Round it __free_page_address = (ptr8_t)roundTo1k((ptr32_val_t)__free_page_address); ptr_val_t first_coarse = (ptr_val_t)__free_page_address; __free_page_address += 1024; ptr_val_t cc = pdir->createCoarseTable(first_coarse, 0, PageDir::MMU_RW_RW); pdir->incFreePos(); pdir->setCoarseTable(pdir->getFreePos(), cc); directory = (void*)pdir; } PagingPrivate::~PagingPrivate() { } bool PagingPrivate::init(void *platformData) { (void)platformData; if (data!=nullptr) return false; is_ok = false; #if 0 pagingDisable(); //Safety #endif #if 0 if (platformData!=nullptr) { MultibootInfo *info = (MultibootInfo*)platformData; MemoryMap *mmap = (MemoryMap*)(info->mmap_addr); ptr32_val_t info_end = info->mmap_addr + info->mmap_length; while ((ptr32_val_t )(mmap) + mmap->size < info_end) { if ((mmap->base_addr_low + mmap->length_low) > __mem_size) { __mem_size = mmap->base_addr_low + mmap->length_low; } unsigned long addr = mmap->base_addr_low / 0x1000; unsigned long limit = mmap->length_low / 0x1000; while (addr<0x120 && limit>0) { addr++; limit--; } if (mmap->type == 1) { //Skip } else if (mmap->type == 2 || mmap->type == 3) { //Skip } else { break; } mmap = (MemoryMap *)(((ptr32_val_t)mmap) + mmap->size + sizeof(ptr32_val_t)); } } ptr_val_t mem_end_page = (ptr_val_t)__mem_size; pageCnt = mem_end_page/PAGE_SIZE; data = (void*)new Bits(pageCnt); directory = (void*)new PageDir(); while (directory==nullptr) ; #endif #if 0 //for (uint32_t i=HEAP_START; i<HEAP_END; i+=PAGE_SIZE) { for (uint32_t i=HEAP_START; i<HEAP_START+KERNEL_INIT_SIZE; i+=PAGE_SIZE) { PDIR(directory)->getPage(i, PageDir::PageDoReserve); } //for (uint32_t i=USER_HEAP_START; i<USER_HEAP_END; i+=PAGE_SIZE) { for (uint32_t i=USER_HEAP_START; i<USER_HEAP_START+KERNEL_INIT_SIZE; i+=PAGE_SIZE) { PDIR(directory)->getPage(i, PageDir::PageDoReserve); } #endif #if 0 // Identify mapping uint32_t i = 0; while (i<(ptr_val_t)0x10000) { identityMapFrame(PDIR(directory)->getPage(i, PageDir::PageDoReserve), i, MapPageKernel, MapPageRW); i += PAGE_SIZE; } i = 0xA0000; while (i<(ptr_val_t)0xBFFFF) { //VGA display memory identityMapFrame(PDIR(directory)->getPage(i, PageDir::PageDoReserve), i, MapPageKernel, MapPageRW); i += PAGE_SIZE; } i = 0xC0000; while (i<(ptr_val_t)0xC7FFF) { //Video BIOS identityMapFrame(PDIR(directory)->getPage(i, PageDir::PageDoReserve), i, MapPageKernel, MapPageRW); i += PAGE_SIZE; } i = 0xC8000; while (i<(ptr_val_t)0xEFFFF) { //Mapped HW identityMapFrame(PDIR(directory)->getPage(i, PageDir::PageDoReserve), i, MapPageKernel, MapPageRW); i += PAGE_SIZE; } i = 0xF0000; while (i<(ptr_val_t)0xFFFFF) { //BIOS identityMapFrame(PDIR(directory)->getPage(i, PageDir::PageDoReserve), i, MapPageKernel, MapPageRW); i += PAGE_SIZE; } i = 0x100000; while (i<(ptr_val_t)__free_page_address) { identityMapFrame(PDIR(directory)->getPage(i, PageDir::PageDoReserve), i, MapPageKernel, MapPageRW); i += PAGE_SIZE; } #endif #if 0 i = (ptr_val_t)__free_page_address; ptr_val_t start = i; while (i<(ptr_val_t)start+KERNEL_INIT_SIZE) { identityMapFrame(PDIR(directory)->getPage(i, PageDir::PageDoReserve), i, MapPageKernel, MapPageRW); i += PAGE_SIZE; } #endif #if 0 for (uint32_t i=HEAP_START; i<HEAP_START+KERNEL_INIT_SIZE; i+=PAGE_SIZE) { //mapFrame(PDIR(directory)->getPage(i, PageDir::PageDoReserve), MapPageUser, MapPageReadOnly); mapFrame(PDIR(directory)->getPage(i, PageDir::PageDoReserve), MapPageKernel, MapPageRW); } for (uint32_t i=USER_HEAP_START; i<USER_HEAP_START+KERNEL_INIT_SIZE; i+=PAGE_SIZE) { mapFrame(PDIR(directory)->getPage(i, PageDir::PageDoReserve), MapPageUser, MapPageRW); } pagingDirectoryChange(PDIR(directory)->getPhys()); #endif #if 0 pagingEnable(); is_ok = true; #endif return true; } void PagingPrivate::lock() { // Doing it hard way... //cli(); m.lock(); } void PagingPrivate::unlock() { m.unlock(); //sti(); } void PagingPrivate::lockStatic() { m_static.lock(); } void PagingPrivate::unlockStatic() { m_static.unlock(); } bool PagingPrivate::identityMapFrame(Page *p, ptr_val_t addr, MapType type, MapPermissions perms) { if (p==nullptr) return false; bool res = true; uint32_t i = addr/PAGE_SIZE; //if (BITS(data)->isSet(i)) return false; if (BITS(data)->isSet(i)) res = false; BITS(data)->set(i); p->setPresent(true); if (perms==MapPageRW) p->setRw(true); else p->setRw(false); if (type==MapPageKernel) p->setUserspace(false); else p->setUserspace(true); p->setAddress(addr); return res; } bool PagingPrivate::mapFrame(Page *p, MapType type, MapPermissions perms) { if (p==nullptr) return false; //Already mapped if (!p->isAvail()) { return true; } else { bool ok = false; uint32_t i = BITS(data)->findUnset(&ok); if (!ok) { //TODO handle out of pages/memory #if 0 unsigned short *tmp = (unsigned short *)(0xB8200); static int n = 0; *tmp = 0x1741+(n++%20); tmp =(unsigned short *)(0xB8300); if (i==0) { *tmp = 0x1730; } while (i>0) { *tmp++ = 0x1730+(i%10); i/=10; } #endif while(1) ; return false; } BITS(data)->set(i); p->setPresent(true); if (perms==MapPageRW) p->setRw(true); else p->setRw(false); if (type==MapPageKernel) p->setUserspace(false); else p->setUserspace(true); p->setAddress(i*PAGE_SIZE); return true; } return false; } /* Get a free physical page */ void *PagingPrivate::getPage() { //mapFrame(PDIR(directory)->getPage(i, PageDir::PageDoReserve), MapPageUser, MapPageRW); bool ok = false; uint32_t i = BITS(data)->findUnset(&ok); if (!ok) { //TODO handle out of pages/memory return nullptr; } BITS(data)->set(i); return (void*)(i*PAGE_SIZE); } /* Free physical page corresponding to given virtuall address */ void PagingPrivate::freePage(void *ptr) { #if 1 ptr_val_t i = (ptr_val_t)ptr; i/=PAGE_SIZE; BITS(data)->clear(i); #endif } bool PagingPrivate::mapPhys(void *phys, ptr_t virt, unsigned int flags) { (void)phys; (void)virt; (void)flags; #if 0 #if 1 ptr_val_t i = 0; #if 1 if (flags&PAGING_MAP_USER) { while ((ptr_val_t)__user_heap_address%PAGE_SIZE!=0) __user_heap_address++; i = (ptr_val_t)__user_heap_address; __user_heap_address+=PAGE_SIZE; } else { while ((ptr_val_t)__heap_address%PAGE_SIZE!=0) __heap_address++; i = (ptr_val_t)__heap_address; __heap_address+=PAGE_SIZE; } #else i = (ptr_val_t)phys; #endif Page *p = PDIR(directory)->getPage(i, PageDir::PageDoReserve); if (p==nullptr) { //while(1); return false; } if (!p->isAvail()) { return false; } bool res = true; if (flags&PAGING_MAP_USER) { res = identityMapFrame(p, (ptr_val_t)phys, MapPageUser, MapPageRW); } else { res = identityMapFrame(p, (ptr_val_t)phys, MapPageKernel, MapPageRW); } if (virt!=nullptr) { *virt = i; } return res; #endif #endif return false; } /* Map physical page to virtual */ bool PagingPrivate::map(ptr_t virt, unsigned int flags, unsigned int cnt) { (void)flags; #if 0 ptr_val_t i = 0; ptr_val_t vptr = 0; unsigned int left = cnt; if (flags&PAGING_MAP_USER) { while (((ptr_val_t)__user_heap_address%PAGE_SIZE)!=0) __user_heap_address++; i = (ptr_val_t)__user_heap_address; while (left-->0) __user_heap_address+=PAGE_SIZE; } else { while (((ptr_val_t)__heap_address%PAGE_SIZE)!=0) __heap_address++; i = (ptr_val_t)__heap_address; while (left-->0) __heap_address+=PAGE_SIZE; } vptr = i; while (cnt>0) { Page *p = PDIR(directory)->getPage(i, PageDir::PageDoReserve); if (p==nullptr) { return false; } if (!p->isAvail()) { return false; } if (flags&PAGING_MAP_USER) { if (!mapFrame(p, MapPageUser, MapPageRW)) return false; } else { if (!mapFrame(p, MapPageKernel, MapPageRW)) return false; } cnt--; i+=PAGE_SIZE; } if (virt!=nullptr) { *virt = vptr; } #endif ptr_val_t vptr = (ptr_val_t)roundTo1k((ptr32_val_t)__free_page_address); while (cnt>0) { __free_page_address += PAGE_SIZE; cnt--; } if (virt!=nullptr) { *virt = vptr; } return true; } /* Unmap memory at ptr */ void *PagingPrivate::unmap(void *ptr) { (void)ptr; #if 0 ptr_val_t i = (ptr_val_t)ptr; i/=PAGE_SIZE; Page *p = PDIR(directory)->getPage(i, PageDir::PageDontReserve); if (p==nullptr) return nullptr; if (p->isAvail()) { p->setPresent(false); p->setRw(false); p->setUserspace(false); p->setAddress(0); BITS(data)->clear(i); } #endif return nullptr; } ptr8_t PagingPrivate::freePageAddress() { #if 0 ptr_val_t i = (ptr_val_t)__free_page_address/PAGE_SIZE; if (!BITS(data)->isSet(i)) { #if 0 identityMapFrame(PDIR(directory)->getPage(i, PageDir::PageDoReserve), i, MapPageKernel, MapPageRW); #else BITS(data)->set(i); #endif } #endif return __free_page_address; } void PagingPrivate::incFreePageAddress(ptr_val_t size) { #if 0 ptr_val_t i = (ptr_val_t)__free_page_address/PAGE_SIZE; if (!BITS(data)->isSet(i)) { #if 0 identityMapFrame(PDIR(directory)->getPage(i, PageDir::PageDoReserve), i, MapPageKernel, MapPageRW); #else BITS(data)->set(i); #endif } #endif __free_page_address += size; } void PagingPrivate::pageAlign(ptr_val_t align) { /* Align to proper boundaries */ #if 1 #if 0 while (((ptr32_val_t)__free_page_address & (align-1))!=0) { BITS(data)->set((ptr_val_t)__free_page_address/PAGE_SIZE); __free_page_address++; } #else ptr8_t tmp = freePageAddress(); while (((ptr32_val_t)tmp & (align-1))!=0) { tmp++; incFreePageAddress(1); } #endif #endif } ptr_val_t PagingPrivate::memSize() { return __mem_size; } #if 0 PageDir::PageDir() { for (int i=0; i<TABLES_PER_DIRECTORY; i++) { tables[i] = nullptr; tablesPhys[i] = 0; } phys = (ptr_t)tablesPhys; } PageTable *PageDir::getTable(uint32_t i) { if (i<TABLES_PER_DIRECTORY) { return tables[i]; } return nullptr; } Page *PageDir::getPage(ptr_val_t addr, PageReserve reserve) { addr/=PAGE_SIZE; uint32_t index = addr / PAGES_PER_TABLE; //We already have the table if (tables[index]!=nullptr) { return tables[index]->get(addr%PAGES_PER_TABLE); } else if (reserve==PageDoReserve) { ptr_val_t physPtr = 0; tables[index] = new ((ptr_t)&physPtr) PageTable(); if (physPtr==0) { /* unsigned short *vid = (unsigned short *)(0xB8000); *vid = 0x1745; //E while (1); */ return nullptr; } tablesPhys[index] = physPtr | PAGING_MAP_R2; return tables[index]->get(addr%PAGES_PER_TABLE); } return nullptr; } void PageDir::copyTo(PageDir *dir) { ptr_t offs = (ptr_t)((ptr_val_t)dir->tablesPhys - (ptr_val_t)dir); dir->phys = (ptr_val_t)phys + offs; for (int i=0; i<TABLES_PER_DIRECTORY; i++) { if (tables[i]!=nullptr) { if (1) { dir->tables[i] = tables[i]; dir->tablesPhys[i] = tablesPhys[i]; } else { ptr_val_t tmp; dir->tables[i] = new (&tmp) PageTable(); dir->tablesPhys[i] = tmp | PAGING_MAP_R2; tables[i]->copyTo(dir->tables[i]); } } } } #endif static Paging p; void paging_mmap_init(MultibootInfo *info) { /* Initialize paging */ p.init((void*)info); }
b320d7ae020a3643a7e0ed65b88ae65ba3839eca
9a5bf542c7ae2268a44350d8ef7f046cbec5fee1
/Brick Breaker/Brick Breaker/BrickBreaker.h
7100d12553414a44ef8e5be0663a0fcd26bb9d87
[]
no_license
Phuc-T-Tran/Brick-Breaker
5a8f61a4aaf427732458a4f9f1b3624ef9c55ce0
1eb6cc54fa9a0073487fa1118520e0a977eb056a
refs/heads/master
2021-01-10T16:01:43.889699
2015-12-29T16:19:09
2015-12-29T16:19:09
48,660,546
2
0
null
null
null
null
UTF-8
C++
false
false
165
h
BrickBreaker.h
#ifndef BRICKBREAKER_H #define BRICKBREAKER_H #include "core\Game.h" class BrickBreaker : public Game { public: BrickBreaker(); ~BrickBreaker(); }; #endif
842ec73ab0a2c14dde82648199cf2ff2c1ba8b9d
a39c1c747c20f12e85be39216a456100a4f10b76
/solver/cost_functors/person_3d_errors.cc
51e6dd49f52ffe5eb174a268b74e0ae274ab5e5a
[]
no_license
tmjeong1103/Estimating-3D-Motion-Forces
547348307def936b6b3c00b742ef6d3363f09f73
de5bd8436076d0be9b281a7b23fd8a4ad6e8d29e
refs/heads/master
2023-07-23T14:02:39.898384
2021-08-24T11:59:41
2021-08-24T11:59:41
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,879
cc
person_3d_errors.cc
#include "person_3d_errors.h" CostFunctorPerson3dErrors::CostFunctorPerson3dErrors( int i, DataloaderPerson *person_loader) { i_ = i; // num of time step person_loader_ = person_loader; nq_ = person_loader_->get_nq(); // 75d vector nq_pino_ = person_loader_->get_nq_pino(); // 99d vector // Measure the 12 limb joints only int joints_interest[] = {1, 2, 3, 5, 6, 7, 15, 16, 17, 20, 21, 22}; for (int k = 0; k < 12; k++) { joint_ids_.push_back(joints_interest[k]); } njoints_ = (int)joint_ids_.size(); // Save the 3D locations of the 18 joints (relative to the base joint) Eigen::VectorXd joint_3d_positions = person_loader_->get_joint_3d_positions_column(i_); joint_3d_positions_rel_ = joint_3d_positions - (joint_3d_positions.head<3>()).replicate(person_loader_->get_njoints(),1); } bool CostFunctorPerson3dErrors::Evaluate( double const *const * parameters, double * residual, double ** jacobians) const { const double *const q = parameters[0]; VectorXd q_mat = Eigen::Map<const VectorXd>(q,nq_,1); // convert 3D axis-angles to a 4D quaternions person_loader_->UpdateConfigPino(i_, q_mat); VectorXd q_pino = Eigen::Map<VectorXd>( person_loader_->mutable_config_pino(i_), nq_pino_, 1); assert(q_pino.size() == nq_pino_ && "q_pino of wrong dimension"); // forwardKinematics pinocchio::forwardKinematics(person_loader_->model_, person_loader_->data_, q_pino); // Get the base joint position const Vector3d & base_position = person_loader_->data_.oMi[1].translation(); for (int i = 0; i < njoints_; i++) { int joint_id = joint_ids_[(size_t)i]; // the id number of an openpose joint // Compute the joint position relative to the base joint const Vector3d & joint_position_rel = person_loader_->data_.oMi[(size_t)joint_id + 1].translation() - base_position; for (int k = 0; k < 3; k++) { residual[3 * i + k] = (joint_position_rel(k) - joint_3d_positions_rel_(3 * joint_id + k)); } } if(jacobians) { // do nothing } return true; } ceres::CostFunction * CostFunctorPerson3dErrors::Create( int i, DataloaderPerson *person_loader) { CostFunctorPerson3dErrors *cost_functor = new CostFunctorPerson3dErrors(i, person_loader); CostFunctionPerson3dErrors *cost_function = new CostFunctionPerson3dErrors(cost_functor); // person config parameters int nq = cost_functor->get_nq(); cost_function->AddParameterBlock(nq); // number of residuals int njoints = cost_functor->get_njoints(); cost_function->SetNumResiduals(3 * njoints); return cost_function; } int CostFunctorPerson3dErrors::get_njoints() const { return njoints_; } int CostFunctorPerson3dErrors::get_nq() const { return nq_; }
2ca8cfb28fe10becace17497db1621c8ccb5128b
e9cb1818bde5c0c544df0366d51420863b0a5c54
/day03/ex04/NinjaTrap.cpp
ad50a9434ce84a8453b495e61f75a41fdca5a492
[]
no_license
vdoroshyn/42-cpp-piscine
2ba1ac72a74a2b8e1980b041d4411bd95139f160
3f795bd2bf6666007606aff14a8b5d0925168f11
refs/heads/master
2021-05-16T15:58:57.590386
2018-01-30T12:58:12
2018-01-30T12:58:12
119,534,885
0
0
null
null
null
null
UTF-8
C++
false
false
2,528
cpp
NinjaTrap.cpp
#include "NinjaTrap.hpp" NinjaTrap::NinjaTrap() : ClapTrap() { this->_name = "Marian"; this->_hitPoints = 60; this->_maxHitPoints = 60; this->_energyPoints = 120; this->_maxEnergyPoints = 120; this->_level = 1; this->_meleeAttackDamage = 60; this->_rangedAttackDamage = 5; this->_armorDamageReduction = 0; std::cout << this->getName() << ": Now I will dominate!" << std::endl; } NinjaTrap::NinjaTrap(std::string name) : ClapTrap(name) { this->_name = name; this->_hitPoints = 60; this->_maxHitPoints = 60; this->_energyPoints = 120; this->_maxEnergyPoints = 120; this->_level = 1; this->_meleeAttackDamage = 60; this->_rangedAttackDamage = 5; this->_armorDamageReduction = 0; std::cout << this->getName() << ": Heyyah!" << std::endl; } NinjaTrap::NinjaTrap(NinjaTrap const& src) { *this = src; std::cout << this->getName() << ": I'm flying! I'm really flying!" << std::endl; } NinjaTrap::~NinjaTrap() { std::cout << this->getName() << ": No fair! I wasn't ready." << std::endl; } //methods void NinjaTrap::rangedAttack(std::string const& target) { std::cout << "N1NJ4-TP <" << this->getName() << "> attacks <" << target << "> at range, causing <" << this->getRangedAttackDamage() << "> points of damage !" << std::endl; } void NinjaTrap::meleeAttack(std::string const& target) { std::cout << "N1NJ4-TP <" << this->getName() << "> attacks <" << target << "> at range, causing <" << this->getMeleeAttackDamage() << "> points of damage !" << std::endl; } void NinjaTrap::ninjaShoebox(NinjaTrap const& rhs) { std::cout << this->getName() << " farts loudly in " << rhs.getName() << "'s face" << std::endl; } void NinjaTrap::ninjaShoebox(FragTrap const& rhs) { std::cout << this->getName() << " spits right between " << rhs.getName() << "'s eyes" << std::endl; } void NinjaTrap::ninjaShoebox(ScavTrap const& rhs) { std::cout << this->getName() << " shows his dirty, smelly crotch to " << rhs.getName() << std::endl; } //operator overloads NinjaTrap& NinjaTrap::operator=(NinjaTrap const& rhs) { std::cout << "Recompiling my combat code!" << std::endl; if (this != &rhs) { this->_name = rhs.getName(); this->_hitPoints = getHitPoints(); this->_maxHitPoints = getMaxHitPoints(); this->_energyPoints = getEnergyPoints(); this->_maxEnergyPoints = getMaxEnergyPoints(); this->_level = getLevel(); this->_meleeAttackDamage = getMeleeAttackDamage(); this->_rangedAttackDamage = getRangedAttackDamage(); this->_armorDamageReduction = getArmorDamageReduction(); } return *this; }
de069dc1f4b3dfb96526dc4007e4a4e8619ce8d9
14ba43c20af3e13901e6517cb890d600ede4c808
/sysapps/device_capabilities/storage_info_provider.h
a2ea45a401fb32475d085914b9dafe22fcb3a49a
[ "BSD-3-Clause" ]
permissive
sillsdev/crosswalk
da0f73a8934ddb3bafcfe493373b75772b715b99
5b045977a1ff60fb93609cbd3bb10351f25bb699
refs/heads/master
2021-07-14T02:17:21.104996
2020-08-10T21:23:46
2020-08-11T01:37:57
54,854,425
2
1
null
2016-03-28T00:25:16
2016-03-28T00:25:16
null
UTF-8
C++
false
false
1,919
h
storage_info_provider.h
// Copyright (c) 2013 Intel Corporation. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef XWALK_SYSAPPS_DEVICE_CAPABILITIES_STORAGE_INFO_PROVIDER_H_ #define XWALK_SYSAPPS_DEVICE_CAPABILITIES_STORAGE_INFO_PROVIDER_H_ #include <vector> #include "base/callback_forward.h" #include "base/memory/scoped_ptr.h" #include "base/observer_list.h" #include "xwalk/sysapps/device_capabilities/device_capabilities.h" namespace xwalk { namespace sysapps { using jsapi::device_capabilities::StorageUnit; using jsapi::device_capabilities::SystemStorage; class StorageInfoProvider { public: virtual ~StorageInfoProvider(); // The storage backend might not be ready yet when the instance is created. In // this case, we can use this method to queue tasks. void AddOnInitCallback(base::Closure callback); bool IsInitialized() const { return is_initialized_; } void MarkInitialized(); virtual scoped_ptr<SystemStorage> storage_info() const = 0; class Observer { public: Observer() {} virtual ~Observer() {} virtual void OnStorageAttached(const StorageUnit& storage) = 0; virtual void OnStorageDetached(const StorageUnit& storage) = 0; }; void AddObserver(Observer* observer); void RemoveObserver(Observer* observer); bool HasObserver(Observer* observer) const; protected: StorageInfoProvider(); virtual void StartStorageMonitoring() = 0; virtual void StopStorageMonitoring() = 0; void NotifyStorageAttached(const StorageUnit& storage); void NotifyStorageDetached(const StorageUnit& storage); private: bool is_initialized_; std::vector<base::Closure> callbacks_; base::ObserverList<Observer> observer_list_; DISALLOW_COPY_AND_ASSIGN(StorageInfoProvider); }; } // namespace sysapps } // namespace xwalk #endif // XWALK_SYSAPPS_DEVICE_CAPABILITIES_STORAGE_INFO_PROVIDER_H_
819fd5fb79c4bf5f6c9e5a61f5f7dbddb00c2693
cf47614d4c08f3e6e5abe82d041d53b50167cac8
/CS101_Autumn2020-21/Fibonacci/280_fibonacci.cpp
ca7f3ef77c1a54a04b283c645be22fe8dbce3836
[]
no_license
krishna-raj007/BodhiTree-Annotation
492d782dffe3744740f48c4c7e6bbf2ee2c0febd
28a6467038bac7710c4b3e3860a369ca0a6e31bf
refs/heads/master
2023-02-28T18:23:05.880438
2021-02-07T17:55:33
2021-02-07T17:55:33
299,254,966
0
0
null
null
null
null
UTF-8
C++
false
false
289
cpp
280_fibonacci.cpp
#include<simplecpp> #include<iostream> using namespace std; main_program{ int n; int f=0,s=1,t=0,k=0; cin>>n>>k; cout<<0%k<<endl; cout<<1%k<<endl; for(int i=0;i<n-2;i++){ t=f+s; f=s; s=t; cout<<abs(t%k)<<endl; } }
053c8e84a9a47f815e3ab85131dda1e34eeeda8b
f791e02dba63257700b05877a41ae9036d1113fd
/OurLogicSimulator/OurLogicSimulatorView.h
e4354d552cb2221c59a0ac469af00c9add38f7cc
[]
no_license
RyuJaeChan/MFCLogicSimulator
56758c472447a70f1a5fc5fae853ddaaebbe4600
75f414719d466b054f1f65b23f6c5caf86a647c3
refs/heads/master
2021-01-01T05:11:24.938128
2016-05-20T03:55:55
2016-05-20T03:55:55
58,743,507
0
0
null
null
null
null
UHC
C++
false
false
1,346
h
OurLogicSimulatorView.h
// OurLogicSimulatorView.h : COurLogicSimulatorView 클래스의 인터페이스 // #pragma once class COurLogicSimulatorView : public CView { protected: // serialization에서만 만들어집니다. COurLogicSimulatorView(); DECLARE_DYNCREATE(COurLogicSimulatorView) // 특성입니다. public: COurLogicSimulatorDoc* GetDocument() const; // 작업입니다. public: bool isCreate; int gateNum; // 재정의입니다. public: virtual void OnDraw(CDC* pDC); // 이 뷰를 그리기 위해 재정의되었습니다. virtual BOOL PreCreateWindow(CREATESTRUCT& cs); protected: // 구현입니다. public: virtual ~COurLogicSimulatorView(); #ifdef _DEBUG virtual void AssertValid() const; virtual void Dump(CDumpContext& dc) const; #endif protected: // 생성된 메시지 맵 함수 protected: DECLARE_MESSAGE_MAP() public: afx_msg void OnLButtonDown(UINT nFlags, CPoint point); // afx_msg void OnMouseMove(UINT nFlags, CPoint point); afx_msg void OnLButtonUp(UINT nFlags, CPoint point); afx_msg void OnKeyDown(UINT nChar, UINT nRepCnt, UINT nFlags); afx_msg void OnMouseMove(UINT nFlags, CPoint point); }; #ifndef _DEBUG // OurLogicSimulatorView.cpp의 디버그 버전 inline COurLogicSimulatorDoc* COurLogicSimulatorView::GetDocument() const { return reinterpret_cast<COurLogicSimulatorDoc*>(m_pDocument); } #endif
43acab1113a7e3104749c1eef26868f6edac1d1f
2ab387702039bb8e39eb04e27612e4bc5ebae6f3
/exception.hpp
0be64d0f30c040bfa7e3a3536509dab310979b8f
[]
no_license
gordonzu/cpp_util
fc392fedd52138bf9391f48bf35545cbd966c5e3
1752d4003f14f6fa906325e81021b8029ad9d415
refs/heads/master
2021-01-20T03:59:27.171186
2017-04-27T17:00:58
2017-04-27T17:00:58
89,616,952
0
0
null
null
null
null
UTF-8
C++
false
false
1,702
hpp
exception.hpp
// exception.hpp #include <exception> #include <system_error> #include <future> #include <iostream> #include <utility> namespace util { template <typename T> void processCodeException(const T& e) { auto c = e.code(); std::cerr << "- category: " << c.category().name() << std::endl; std::cerr << "- value: " << c.value() << std::endl; std::cerr << "- msg: " << c.message() << std::endl; std::cerr << "- def category: " << c.default_error_condition().category().name() << std::endl; std::cerr << "- def value: " << c.default_error_condition().value() << std::endl; std::cerr << "- def msg: " << c.default_error_condition().message() << std::endl; } void processException() { try { throw; // rethrow exception to deal with it here } catch (const ios_base::failure& e) { cerr << "I/O EXCEPTION: " << e.what() << endl; processCodeException(e); } catch (const system_error& e) { cerr << "SYSTEM EXCEPTION: " << e.what() << endl; processCodeException(e); } catch (const future_error& e) { cerr << "FUTURE EXCEPTION: " << e.what() << endl; processCodeException(e); } catch (const bad_alloc& e) { cerr << "BAD ALLOC EXCEPTION: " << e.what() << endl; } catch (const exception& e) { cerr << "EXCEPTION: " << e.what() << endl; } catch (...) { cerr << "EXCEPTION (unknown)" << endl; } } template <typename T1, typename T2> std::ostream& operator << (std::ostream& strm, const std::pair<T1,T2>& p) { return strm << "[" << p.first << "," << p.second << "]"; } }
35b39f992284f43512e3bb317a8af1acd3216834
8c00f20b072b0ea9e6452531b8439c239394e672
/HeapSort.cpp
1e01c7a9500e80228fe85e0d58f25fe71ec51107
[]
no_license
salonigit/Sorting
3b7d09d9f86ae580852d53d3e7d2979fd9be4991
dd1aefbb6fc545e8f20de10846d983c15b8a4289
refs/heads/master
2023-04-28T10:35:51.232601
2021-05-20T04:54:45
2021-05-20T04:54:45
369,083,426
0
0
null
null
null
null
UTF-8
C++
false
false
1,018
cpp
HeapSort.cpp
#include<bits/stdc++.h> using namespace std; void Heapsortcreate(int A[], int n){ int i=n,temp=A[i]; while(i>1 && temp>A[i/2]){ A[i]=A[i/2]; i=i/2; } A[i]=temp; } int Heapsortdelete(int A[],int n){ int i,j,x,temp,val; val=A[1]; x=A[n]; A[1]=A[n]; A[n]=val; i=1;j=i*2; while(j<n-1){ if(A[j+1]>A[j]){ j=j+1; } if(A[i]<A[j]){ temp=A[i]; A[i]=A[j]; A[j]=temp; i=j; j=2*j; } else{ break; } } return val; } int main(){ int A[]={0,10,20,30,25,5,40,35}; // int n=sizeof(A)/sizeof(A[0]); // Heapsortcreate(A,2); // Heapsortcreate(A,5); // Heapsortcreate(A,9); // Heapsortdelete(A,n); for(int i=2;i<=7;i++){ Heapsortcreate(A,i); } for(int i=7;i>1;i--){ Heapsortdelete(A,i); } for(int i=1;i<7;i++){ cout<<A[i]<<" "; } cout<<endl; return 0; }
092b2c5e63ad889abdcbd565eed88573f0ae51dd
ae14d60e1649546ad51ce461289554a212b0edfa
/keylogger/build-event_logger-Desktop_Qt_5_15_2_clang_64bit-Debug/moc_usagedata6model.cpp
aea7b0fb9b61a4395927759f49656a918c4627b0
[]
no_license
svadoe/upwork
43f1f37f3c1ac096ac3cac55096445ee84a104aa
274b6b45f6cc8c323d698716fca66b05af55776e
refs/heads/main
2023-02-07T08:29:08.177410
2020-12-20T16:29:50
2020-12-20T16:29:50
323,115,242
0
0
null
null
null
null
UTF-8
C++
false
false
4,584
cpp
moc_usagedata6model.cpp
/**************************************************************************** ** Meta object code from reading C++ file 'usagedata6model.h' ** ** Created by: The Qt Meta Object Compiler version 67 (Qt 5.15.2) ** ** WARNING! All changes made in this file will be lost! *****************************************************************************/ #include <memory> #include "../logger/usagedata6model.h" #include <QtCore/qbytearray.h> #include <QtCore/qmetatype.h> #if !defined(Q_MOC_OUTPUT_REVISION) #error "The header file 'usagedata6model.h' doesn't include <QObject>." #elif Q_MOC_OUTPUT_REVISION != 67 #error "This file was generated using the moc from 5.15.2. It" #error "cannot be used with the include files from this version of Qt." #error "(The moc has changed too much.)" #endif QT_BEGIN_MOC_NAMESPACE QT_WARNING_PUSH QT_WARNING_DISABLE_DEPRECATED struct qt_meta_stringdata_UsageData6Model_t { QByteArrayData data[10]; char stringdata0[96]; }; #define QT_MOC_LITERAL(idx, ofs, len) \ Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \ qptrdiff(offsetof(qt_meta_stringdata_UsageData6Model_t, stringdata0) + ofs \ - idx * sizeof(QByteArrayData)) \ ) static const qt_meta_stringdata_UsageData6Model_t qt_meta_stringdata_UsageData6Model = { { QT_MOC_LITERAL(0, 0, 15), // "UsageData6Model" QT_MOC_LITERAL(1, 16, 27), // "RegisterEnumClassesUnscoped" QT_MOC_LITERAL(2, 44, 5), // "false" QT_MOC_LITERAL(3, 50, 11), // "insert_data" QT_MOC_LITERAL(4, 62, 0), // "" QT_MOC_LITERAL(5, 63, 10), // "QDateTime&" QT_MOC_LITERAL(6, 74, 9), // "timestamp" QT_MOC_LITERAL(7, 84, 4), // "data" QT_MOC_LITERAL(8, 89, 2), // "at" QT_MOC_LITERAL(9, 92, 3) // "row" }, "UsageData6Model\0RegisterEnumClassesUnscoped\0" "false\0insert_data\0\0QDateTime&\0timestamp\0" "data\0at\0row" }; #undef QT_MOC_LITERAL static const uint qt_meta_data_UsageData6Model[] = { // content: 8, // revision 0, // classname 1, 14, // classinfo 3, 16, // methods 0, 0, // properties 0, 0, // enums/sets 0, 0, // constructors 0, // flags 0, // signalCount // classinfo: key, value 1, 2, // methods: name, argc, parameters, tag, flags 3, 2, 31, 4, 0x02 /* Public */, 8, 1, 36, 4, 0x02 /* Public */, 8, 0, 39, 4, 0x22 /* Public | MethodCloned */, // methods: parameters QMetaType::Void, 0x80000000 | 5, QMetaType::QString, 6, 7, QMetaType::QVariantMap, QMetaType::Int, 9, QMetaType::QVariantMap, 0 // eod }; void UsageData6Model::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a) { if (_c == QMetaObject::InvokeMetaMethod) { auto *_t = static_cast<UsageData6Model *>(_o); Q_UNUSED(_t) switch (_id) { case 0: _t->insert_data((*reinterpret_cast< QDateTime(*)>(_a[1])),(*reinterpret_cast< const QString(*)>(_a[2]))); break; case 1: { QVariantMap _r = _t->at((*reinterpret_cast< int(*)>(_a[1]))); if (_a[0]) *reinterpret_cast< QVariantMap*>(_a[0]) = std::move(_r); } break; case 2: { QVariantMap _r = _t->at(); if (_a[0]) *reinterpret_cast< QVariantMap*>(_a[0]) = std::move(_r); } break; default: ; } } } QT_INIT_METAOBJECT const QMetaObject UsageData6Model::staticMetaObject = { { QMetaObject::SuperData::link<QAbstractListModel::staticMetaObject>(), qt_meta_stringdata_UsageData6Model.data, qt_meta_data_UsageData6Model, qt_static_metacall, nullptr, nullptr } }; const QMetaObject *UsageData6Model::metaObject() const { return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject; } void *UsageData6Model::qt_metacast(const char *_clname) { if (!_clname) return nullptr; if (!strcmp(_clname, qt_meta_stringdata_UsageData6Model.stringdata0)) return static_cast<void*>(this); return QAbstractListModel::qt_metacast(_clname); } int UsageData6Model::qt_metacall(QMetaObject::Call _c, int _id, void **_a) { _id = QAbstractListModel::qt_metacall(_c, _id, _a); if (_id < 0) return _id; if (_c == QMetaObject::InvokeMetaMethod) { if (_id < 3) qt_static_metacall(this, _c, _id, _a); _id -= 3; } else if (_c == QMetaObject::RegisterMethodArgumentMetaType) { if (_id < 3) *reinterpret_cast<int*>(_a[0]) = -1; _id -= 3; } return _id; } QT_WARNING_POP QT_END_MOC_NAMESPACE
1db20b2d6c83080007bcc4f6c841a59908ef04d9
902e56e5eb4dcf96da2b8c926c63e9a0cc30bf96
/Sources/HOO/HOOAdminProtocol/AdminLogin.h
01744a724341557077232fc46baab5b862ded125
[ "BSD-3-Clause" ]
permissive
benkaraban/anima-games-engine
d4e26c80f1025dcef05418a071c0c9cbd18a5670
8aa7a5368933f1b82c90f24814f1447119346c3b
refs/heads/master
2016-08-04T18:31:46.790039
2015-03-22T08:13:55
2015-03-22T08:13:55
32,633,432
2
0
null
null
null
null
UTF-8
C++
false
false
3,365
h
AdminLogin.h
/* * Copyright (c) 2010, Anima Games, Benjamin Karaban, Laurent Schneider, * Jérémie Comarmond, Didier Colin. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * - Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef HOOADMINPROTOCOL_ADMINLOGIN_H_ #define HOOADMINPROTOCOL_ADMINLOGIN_H_ #include <HOOAdminProtocol/IAdminMessage.h> namespace HOOAdminProtocol { class LM_API_HAP AdminLogin : public Core::Object, public IAdminRequest { public: AdminLogin() {} AdminLogin(const Core::String & login, const Core::String & password); virtual ~AdminLogin(){} virtual EAdminRequestType getType() const { return ADMIN_LOGIN; } const Core::String & getLogin() const {return _login;} const Core::String & getPassword() const {return _password;} virtual void read(Core::InputStream & inputStream); virtual void write(Core::OutputStream & outputStream) const; protected: Core::String _login; Core::String _password; }; LM_ENUM_4(EAdminLoginAnswerType, ADMIN_LOGIN_OK, ADMIN_LOGIN_FAILED, ADMIN_PASSWD_FAILED, NOT_AN_ADMIN_ACCOUNT) class LM_API_HAP AdminLoginAnswer : public Core::Object, public IAdminAnswer { public: AdminLoginAnswer() {} AdminLoginAnswer(EAdminLoginAnswerType type) : _loginAnswerType(type) {} virtual ~AdminLoginAnswer(){} virtual EAdminAnswerType getType() const { return ADMIN_LOGIN_ANSWER; } EAdminLoginAnswerType getLoginAnswerType() const { return _loginAnswerType; } virtual void read(Core::InputStream & inputStream); virtual void write(Core::OutputStream & outputStream) const; protected: EAdminLoginAnswerType _loginAnswerType; }; }//namespace HOOAdminProtocol #endif/*HOOADMINPROTOCOL_ADMINLOGIN_H_*/
f48bc3ee8b25c5baf153adba08377bdc3050c775
29609b94d70ca16b173ebbe4d86d7795786a1bff
/HW 2 - regular/2/ElectionResultsDatabase.hpp
6a6a4a7be1fa69fc664b39cfbd539d2eb52437f2
[]
no_license
RadoslavSV/Object-Oriented_Programming
84af4d65d9ab857312efc5bc7d55872ff2edb493
e781422ec7243f38ca2f87c848c885c74bb6acba
refs/heads/main
2023-06-07T06:35:04.059771
2021-07-01T07:49:09
2021-07-01T07:49:09
381,949,621
0
0
null
null
null
null
UTF-8
C++
false
false
1,252
hpp
ElectionResultsDatabase.hpp
/// Radoslav Velkov, fn 62528, group 1 #pragma once #include <iostream> #include <fstream> #include <ostream> #include "SectionVotes.cpp" using namespace std; class ElectionResultsDatabase{ int party1TotalVotes=0, party2TotalVotes=0, party3TotalVotes=0; int sectionsNumber=0; public: ElectionResultsDatabase(): party1TotalVotes(0), party2TotalVotes(0), party3TotalVotes(0) {}; void addResultsFromFile(const char* filename); int numberOfSections() const; int votesForParty(Party) const; Party winningParty() const; int getParty1TotalVotes() const; int getParty2TotalVotes() const; int getParty3TotalVotes() const; friend std::istream& operator>>(std::istream& in, ElectionResultsDatabase& s); friend std::ostream& operator<<(std::ostream& out, const ElectionResultsDatabase& s); }; inline std::istream& operator>>(std::istream& in, ElectionResultsDatabase& s) { char discard; in>>s.party1TotalVotes>>discard>>s.party2TotalVotes>>discard>>s.party3TotalVotes; return in; } inline std::ostream& operator<<(std::ostream& out, const ElectionResultsDatabase& s) { out<<s.getParty1TotalVotes()<<" "<<s.getParty2TotalVotes()<<" "<<s.getParty3TotalVotes()<<std::endl; return out; }
332a3724145acdc16ca0305e5b76aa829d34b3dc
fbd408a9ff965cbbfa5ddcba87908f2fbdfb7cff
/Cliente.cpp
a7968b1163fcbd982720a09afe6dd624bda86ec9
[]
no_license
matisyo/TP2-Concu
897b22faec2d4d47f6509582de766888b27169cf
3bb02cef38dd0b9362acbb6b0440c634258882c5
refs/heads/master
2021-08-14T06:35:10.768243
2017-11-14T21:43:29
2017-11-14T21:43:29
110,712,320
0
0
null
null
null
null
UTF-8
C++
false
false
893
cpp
Cliente.cpp
#include <iostream> using namespace std; #include "Queue.h" #include <string.h> #include <unistd.h> #include "Identificadores.h" #include "Cliente.h" int Cliente::run() { Queue server(Identificadores::ID_SERVIDOR); Queue client(Identificadores::ID_CLIENTES); msj aux; aux.mtype = Identificadores::MSJ_CLIENTE_CLIMA; aux.from = getpid(); strcpy(aux.mensaje, "Buenos Aires"); std::cout << "Client sending" << std::endl; server.send(&aux); msj resp; client.recive(&resp,getpid()); std::cout << "CLIENT GETS " << resp.mensaje << std::endl; // aux.mtype = Identificadores::MSJ_CERRAR; // aux.from = getpid(); // strcpy(aux.mensaje, "Cerrate"); // // std::cout << "Client sending" << std::endl; // // c.send(&aux); // // msj aux2; // c.recive(&aux2,aux.from); // std::cout << aux2.mensaje << std::endl; return 0; }
64bdd30e08b5ea34ea46fd80f9ad5a58ab036a96
5defd28536a93b1d61d651a5679a0c85006028f4
/_7SegmentDisplay_74HC595.ino
c4727eff36d01ef45eb0c36ce0c2030c0c949220
[]
no_license
nxxcxx/AR-7SegmentDisplay-74HC595
3da43d809dded06425202fa44eaab77350189bc8
b8c43a537688c0225e374a2692f8d523d3df10dc
refs/heads/master
2016-09-06T04:47:56.832402
2014-08-28T12:52:13
2014-08-28T12:52:13
null
0
0
null
null
null
null
UTF-8
C++
false
false
820
ino
_7SegmentDisplay_74HC595.ino
/* 74HC595 SHIFT REGISTER PIN CONFIG Q0-Q7 = A-G Q9-Q12 = common anode Q8, Q13-Q16 = BLANK */ const int dataPin = 3; const int clockPin = 4; const int latchPin = 5; const byte disp[4] = { B00000001, B00000010, B00000100, B00001000 }; const byte digits[10] = { B11000000, B11111001, B10100100, B10110000, B10011001, B10010010, B10000010, B11111000, B10000000, B10010000 }; void setup() { pinMode(dataPin, OUTPUT); pinMode(clockPin, OUTPUT); pinMode(latchPin, OUTPUT); } void loop() { showDigit(3, 8); showDigit(2, 7); showDigit(1, 6); showDigit(0, 5); } void showDigit(int dsp, int dgt) { digitalWrite(latchPin, LOW); shiftOut(dataPin, clockPin, MSBFIRST, disp[dsp]); shiftOut(dataPin, clockPin, MSBFIRST, digits[dgt]); digitalWrite(latchPin, HIGH); }
10cbc79ab6561b8ed81f73aa02039b797c600516
a62342d6359a88b0aee911e549a4973fa38de9ea
/0.6.0.3/Internal/SDK/BP_MasterTrap_StaticMesh_Net_classes.h
fbe3d86f89c335cc624a12af0c855a86eab214cc
[]
no_license
zanzo420/Medieval-Dynasty-SDK
d020ad634328ee8ee612ba4bd7e36b36dab740ce
d720e49ae1505e087790b2743506921afb28fc18
refs/heads/main
2023-06-20T03:00:17.986041
2021-07-15T04:51:34
2021-07-15T04:51:34
386,165,085
0
0
null
null
null
null
UTF-8
C++
false
false
1,879
h
BP_MasterTrap_StaticMesh_Net_classes.h
#pragma once // Name: Medieval Dynasty, Version: 0.6.0.3 /*!!DEFINE!!*/ /*!!HELPER_DEF!!*/ /*!!HELPER_INC!!*/ #ifdef _MSC_VER #pragma pack(push, 0x01) #endif namespace CG { //--------------------------------------------------------------------------- // Classes //--------------------------------------------------------------------------- // BlueprintGeneratedClass BP_MasterTrap_StaticMesh_Net.BP_MasterTrap_StaticMesh_Net_C // 0x0010 (FullSize[0x0530] - InheritedSize[0x0520]) class ABP_MasterTrap_StaticMesh_Net_C : public ABP_MasterTrap_StaticMesh_C { public: struct FPointerToUberGraphFrame UberGraphFrame; // 0x0520(0x0008) (ZeroConstructor, Transient, DuplicateTransient, UObjectWrapper) class UBoxComponent* Box; // 0x0528(0x0008) (BlueprintVisible, ZeroConstructor, InstancedReference, IsPlainOldData, NonTransactional, NoDestructor, UObjectWrapper, HasGetValueTypeHash) static UClass* StaticClass() { static auto ptr = UObject::FindClass("BlueprintGeneratedClass BP_MasterTrap_StaticMesh_Net.BP_MasterTrap_StaticMesh_Net_C"); return ptr; } void IsInteractable(class ABP_BaseCharacter_C* BaseCharacter, bool* Interactable, bool* Possibility, bool* ShowPressUI, bool* ShowTimerUI, bool* ShowOnlyName, float* Time, float* Distance); void GetInteractAction(struct FText* InteractActionText, struct FText* InteractSecondActionText); void GetWaterDirection(TEnumAsByte<E_WaterDirection_E_WaterDirection>* Forward); void CheckObstruction(bool* CanBePlaced_); void DisableGhost(); void Interact(class ABP_BaseCharacter_C* BaseCharacter, const struct FHitResult& Hit, bool Timer); void ExecuteUbergraph_BP_MasterTrap_StaticMesh_Net(int EntryPoint); }; } #ifdef _MSC_VER #pragma pack(pop) #endif
db4e80cafe116eedf0825234299e99c931d82c49
a9a368a41ac02c6bf41d6e7ed15df7243de36700
/002.DAY_QUANG_US/015.AVLtree/studentln.h
f58de16cdc70057e9690d08c0a7df519aaaff2e9
[]
no_license
phong2018/Cplusplus
e4aa4bac8da08d26285ecf07f6384a0127287750
9ef9c62207a498ac92c26d06b0fd68b4280be584
refs/heads/master
2023-04-02T16:55:37.725510
2021-04-10T23:20:52
2021-04-10T23:20:52
331,883,467
0
0
null
null
null
null
UTF-8
C++
false
false
1,998
h
studentln.h
#include <iostream> using namespace std; //--------- class Student{ public: string id; string first_name; string last_name; string email; Student(); Student(string,string,string,string); void set(string,string,string,string); void get(); void print(); bool operator >(const Student& k); bool operator ==(const Student& k); bool operator <(const Student& k); friend ostream &operator<<( ostream &output, const Student &k ){ output<<k.id<<" " <<k.first_name<<" " << k.last_name<<" " <<k.email <<endl; // Nhập tốc độ return output; } }; //-------- Student::Student(){ id=""; first_name=""; last_name=""; email=""; } Student::Student(string sid,string sfn,string sln,string sm){ cout<<"co so"<<endl; id=sid; first_name=sfn; last_name=sln; email=sm; } void Student::set(string sid,string sfn,string sln,string sm){ id=sid; first_name=sfn; last_name=sln; email=sm; } void Student::get(){ } void Student::print(){ cout<<id<<"__"<<first_name<<"__"<<last_name<<"__"<<email<<endl; } bool Student::operator >(const Student& k){ char su[100],sv[100]; string si=id; string sj=k.id; for(int e=0;e<si.length();e++) su[e]=si[e]; for(int e=0;e<sj.length();e++) sv[e]=sj[e]; //----- if(strcmp(su, sv)>0) return true; else return false; } bool Student::operator ==(const Student& k){ char su[100],sv[100]; string si=id; string sj=k.id; for(int e=0;e<si.length();e++) su[e]=si[e]; for(int e=0;e<sj.length();e++) sv[e]=sj[e]; //----- if(strcmp(su, sv)==0) return true; else return false; } bool Student::operator <(const Student& k){ char su[100],sv[100]; string si=id; string sj=k.id; for(int e=0;e<si.length();e++) su[e]=si[e]; for(int e=0;e<sj.length();e++) sv[e]=sj[e]; //----- if(strcmp(su, sv)<0) return true; else return false; }
34c8141062135bc58ce7907e002eda2ef74bae26
8e06d83c86f08422d5fe968b95fce5335557c799
/src/main/native/new/probe/ViewProbe.cpp
6ffd977d306db52001318edf89f9cc5ac765df38
[]
no_license
bellmit/emp_355
4413b09a7b4d15343bc8d3f6035fb44456e2c996
657d41e2928d8490e3656cf11d169b019e7f4345
refs/heads/master
2022-04-09T00:00:47.384123
2017-06-25T00:26:34
2017-06-25T00:26:34
null
0
0
null
null
null
null
UTF-8
C++
false
false
19,687
cpp
ViewProbe.cpp
#include "probe/ViewProbe.h" #include "utils/Const.h" #include "utils/FakeXUtils.h" #include "utils/MainWindowConfig.h" #include "display/TopArea.h" #include "display/HintArea.h" #include "imageProc/ImgProcPw.h" #include "imageProc/MenuPW.h" #include "imageProc/ModeStatus.h" #include "imageProc/ScanMode.h" #include "keyboard/KeyDef.h" #include "keyboard/KeyValueOpr.h" #include "keyboard/LightDef.h" #include "probe/BiopsyMan.h" #include "sysMan/UserSelect.h" #include "ViewMain.h" #include "sysMan/ViewSystem.h" enum { PROBE_INDEX, EXAM_COLUMN, N_COLUMNS }; ViewProbe* ViewProbe::m_instance = NULL; // --------------------------------------------------------- ViewProbe* ViewProbe::GetInstance() { if (m_instance == NULL) { m_instance = new ViewProbe(); } return m_instance; } ViewProbe::ViewProbe() { m_dialog = NULL; m_comboboxtext_user = NULL; m_treeview0 = NULL; m_treeview1 = NULL; m_treeview2 = NULL; m_treeview3 = NULL; int m_preSocketIndex = -1; int m_examItemIndex = -1; int m_treeViewIndex = -1; int m_probeIndex = -1; int m_itemIndex = -1; int m_probe_index = -1; m_itemList = NULL; } ViewProbe::~ViewProbe() { if (m_instance != NULL) { delete m_instance; } m_instance = NULL; } bool ViewProbe::Create() { HintArea::GetInstance()->UpdateHint(_("[Probe Select]: Reading Probe Para...")); if (ImgProcPw::GetInstance()->GetTraceStatus() && ModeStatus::IsFreezeMode()) { if (g_menuPW.GetAutoTraceStatus()) { ImgProcPw::GetInstance()->SetAutoCalc(false); } } gdk_threads_enter(); while (gtk_events_pending()) { gtk_main_iteration(); // 解决pw冻结,屏幕上有pw trace计算时,不能读探头 } gdk_threads_leave(); ReadProbe(); return true; } bool ViewProbe::Create(int socket) { HintArea::GetInstance()->UpdateHint(_("[Probe Select]: Reading Probe Para...")); gdk_threads_enter(); while (gtk_events_pending()) { gtk_main_iteration(); } gdk_threads_leave(); ReadOneProbe(socket); return true; } void ViewProbe::Destroy() { gtk_combo_box_popdown(GTK_COMBO_BOX(m_comboboxtext_user)); m_pKps.ActiveHV(true); if (GTK_IS_WIDGET(m_dialog)) { g_keyInterface.Pop(); gtk_widget_destroy(GTK_WIDGET(m_dialog)); if (g_keyInterface.Size() == 1) { SetSystemCursor(SYSCURSOR_X, SYSCUROSR_Y); } } ScanMode::GetInstance()->DarkAllModeLight(); g_keyInterface.CtrlLight(TRUE, LIGHT_D2); if (ImgProcPw::GetInstance()->GetTraceStatus() && ModeStatus::IsFreezeMode()) { if (g_menuPW.GetAutoTraceStatus()) { ImgProcPw::GetInstance()->SetAutoCalc(true); } } m_dialog = NULL; m_comboboxtext_user = NULL; m_treeview0 = NULL; m_treeview1 = NULL; m_treeview2 = NULL; m_treeview3 = NULL; m_itemList = NULL; } void ViewProbe::ReadProbe() { cout << "ViewProbe::ReadProbe() 0" << endl; if (!m_pKps.ProbeRead()) { // no probe is found HintArea::GetInstance()->UpdateHint(_("[Probe Select]: No Probe was found."), 2); return ; } cout << "ViewProbe::ReadProbe() 1" << endl; HintArea::GetInstance()->ClearHint(); // display probe dialog and wait user's operation ProbeSocket::ProbePara* para = NULL; int maxSocket = 0; cout << "ViewProbe::ReadProbe() 2" << endl; m_pKps.GetPara(para, m_itemList, maxSocket); cout << "ViewProbe::ReadProbe() 3" << endl; //if (para == NULL) { cout << "ViewProbe::ReadProbe NULL" << endl; // return; //} cout << "ViewProbe::ReadProbe CreateWindow" << endl; //CreateWindow(para, m_itemList, maxSocket); } void ViewProbe::ReadOneProbe(int socket) { if (!m_pKps.OneProbeRead(socket)) { // no probe is found HintArea::GetInstance()->UpdateHint(_("[Probe Select]: No Probe was found."), 2); return ; } HintArea::GetInstance()->ClearHint(); // display probe dialog and wait user's operation ProbeSocket::ProbePara* para = NULL; int maxSocket = 0; m_pKps.GetPara(para, m_itemList, maxSocket); if (para == NULL) { return; } CreateWindow(para, m_itemList, maxSocket); } string ViewProbe::GetUserName() { return ""; //Utils::combobox_active_text(m_combobox_user_select); } string ViewProbe::GetItemNameUserDef() { return m_itemNameUserDef; } int ViewProbe::GetProbeIndex() { return m_probeIndex; } int ViewProbe::GetCurExamItemIndex() { return m_examItemIndex; } // --------------------------------------------------------- void ViewProbe::BtnClickedExit(GtkButton* button) { m_probe_index = ProbeMan::GetInstance()->GetCurProbeSocket(); ProbeMan::GetInstance()->SetProbeSocket(m_probe_index); Destroy(); } void ViewProbe::ComboboxChangedProbeUser(GtkComboBox* combobox) { string name; int select = gtk_combo_box_get_active(combobox); if (select >= 0) { name = gtk_combo_box_get_active_text (combobox); } UserSelect::GetInstance()->save_cur_username(name); IniFile ini(string(CFG_RES_PATH) + string(STORE_DEFAULT_ITEM_PATH)); ExamItem exam; string username = exam.TransUserSelectForEng(name); exam.WriteDefaultUserSelect(&ini, username); ProbeSocket::ProbePara* para = NULL; int maxSocket = 0; m_pKps.GetPara(para, m_itemList, maxSocket); if (para == NULL) { return; } else { for (int i = 0; i < maxSocket; i++) { if (para[i].exist) { vector<string> exam_type = CreateAllExamType(para[i].model, m_itemList[i]); GetCurExamItemIndex(exam_type, i); GtkTreeModel* model = CreateModel(exam_type, i); if (i==0) { gtk_tree_view_set_model(m_treeview0, model); gtk_tree_view_expand_all(m_treeview0); } if (i==1) { gtk_tree_view_set_model(m_treeview1, model); gtk_tree_view_expand_all(m_treeview1); } if (i==2) { gtk_tree_view_set_model(m_treeview2, model); gtk_tree_view_expand_all(m_treeview2); } if (i==3) { gtk_tree_view_set_model(m_treeview3, model); gtk_tree_view_expand_all(m_treeview3); } } } } } void ViewProbe::TreeViewFocusOut(GtkTreeView* treeview, GdkEventFocus* event) { GtkTreeSelection* select = gtk_tree_view_get_selection(treeview); gtk_tree_selection_unselect_all(select); } void ViewProbe::TreeViewButtonClicked(GtkTreeView* treeview, GdkEventButton* event) { if (event->window == gtk_tree_view_get_bin_window(treeview) && event->type == GDK_BUTTON_PRESS && event->button == 1) { string name = Utils::combobox_active_text(m_comboboxtext_user); if (!name.empty()) { int num = gtk_combo_box_get_active(GTK_COMBO_BOX(m_comboboxtext_user)); UserSelect::GetInstance()->save_cur_username(name); ExamItem exam; string username = exam.TransUserSelectForEng(name); IniFile ini(string(CFG_RES_PATH) + string(STORE_DEFAULT_ITEM_PATH)); exam.WriteDefaultUserSelect(&ini, username); exam.WriteDefaultUserIndex(&ini, num); stringstream ss; if (num > 0) { ss << "userconfig/" << name << ".ini"; } else { ss << "ItemPara.ini"; } g_user_configure = ss.str(); } int x = 0; int y = 0; gtk_tree_view_convert_widget_to_bin_window_coords(treeview, event->x, event->y, &x, &y); GtkTreeModel* model = gtk_tree_view_get_model(treeview); GtkTreePath* path = NULL; if (gtk_tree_view_get_path_at_pos(treeview, x, y, &path, NULL, NULL, NULL)) { GtkTreeIter iter; if (gtk_tree_model_get_iter(model, &iter, path)) { gtk_tree_model_get(model, &iter, PROBE_INDEX, &m_probe_index, -1); m_probeIndex = m_probe_index; string path_string = gtk_tree_path_to_string(path); int i = atoi(path_string.c_str()); int itemNumOfProbe = m_itemList[m_probeIndex].size(); ExamItem exam; IniFile ini(string(CFG_RES_PATH) + string(STORE_DEFAULT_ITEM_PATH)); if (i >= itemNumOfProbe) { gtk_tree_model_get(model, &iter, EXAM_COLUMN, &m_userItemName, -1); m_itemNameUserDef = m_userItemName; m_itemIndex = 0; m_pKps.UserItemOfProbeInit(m_probeIndex, (ExamItem::EItem)m_itemIndex, m_userItemName); exam.WriteUserItemFlag(&ini, true); exam.WriteDefaultProbeItemName(&ini, m_userItemName); } else { m_itemIndex = m_itemList[m_probeIndex][i]; m_pKps.ProbeInit(m_probeIndex, (ExamItem::EItem)m_itemIndex); exam.WriteUserItemFlag(&ini, false); exam.WriteDefaultProbeItemName(&ini, EXAM_TYPES[m_itemIndex]); } gtk_tree_path_free(path); int counts = 0; while (gtk_events_pending()) { gtk_main_iteration(); counts++; if(counts > 15) { break; } } g_timeout_add(500, signal_callback_destroy_window, this); ProbeSocket::ProbePara para; ProbeMan::GetInstance()->GetCurProbe(para); ProbeMan::GetInstance()->WriteDefaultProbe((char*)para.model, &ini); exam.WriteDefaultProbeItem(&ini, m_itemIndex); BiopsyMan::GetInstance()->SetCurBioBracketAndAngleTypeOfProbeChanged(); } } } } void ViewProbe::KeyEvent(unsigned char keyValue) { FakeXEvent::KeyEvent(keyValue); if (keyValue == KEY_ESC) { BtnClickedExit(NULL); } } void ViewProbe::CreateWindow(ProbeSocket::ProbePara* para, vector<ExamItem::EItem>* itemList, int maxSocket) { cout << "ViewProbe::CreateWindow 0" << endl; MultiFuncFactory::GetInstance()->Create(MultiFuncFactory::NONE); cout << "ViewProbe::CreateWindow 1" << endl; m_dialog = Utils::create_dialog(NULL, _("Probe Select"), 550, 600); GtkButton* button_exit = Utils::add_dialog_button(m_dialog, _("Exit"), GTK_RESPONSE_CLOSE, GTK_STOCK_QUIT); g_signal_connect(button_exit, "clicked", G_CALLBACK(signal_button_clicked_exit), this); GtkTable* table = Utils::create_table(8, 1); gtk_container_set_border_width(GTK_CONTAINER(table), 0); gtk_container_add(GTK_CONTAINER(gtk_dialog_get_content_area(m_dialog)), GTK_WIDGET(table)); if (maxSocket > 0) { GtkTable* table_probe = Utils::create_table(1, maxSocket); gtk_container_set_border_width(GTK_CONTAINER(table_probe), 10); gtk_table_set_row_spacings(table_probe, 0); cout << "ViewProbe::CreateWindow 10" << endl; for (int i = 0; i < maxSocket; i++) { GtkWidget* probe = NULL; cout << "ViewProbe::CreateWindow 11" << endl; if (para != NULL && para[i].exist) { cout << "ViewProbe::CreateWindow 12" << endl; ProbeSocket::ProbePara probe_para; ProbeMan::GetInstance()->GetCurProbe(probe_para); cout << "ViewProbe::CreateWindow 13" << endl; if (probe_para.model == para[i].model) { m_preSocketIndex = i; } else { m_preSocketIndex = -1; } cout << "ViewProbe::CreateWindow 000 1 " << i << endl; vector<string> exam_type = CreateAllExamType(para[i].model, itemList[i]); cout << "ViewProbe::CreateWindow 000 2 " << endl; probe = CreateProbe(para[i].model, para[i].type, exam_type, i); cout << "ViewProbe::CreateWindow 000 3 " << endl; } else { cout << "ViewProbe::CreateWindow 16" << endl; m_examItemIndex = -1; vector<string> exam_type; probe = CreateProbe("", 0, exam_type, i); cout << "ViewProbe::CreateWindow 17" << endl; } cout << "ViewProbe::CreateWindow 18" << endl; gtk_table_attach_defaults(table_probe, probe, i, i + 1, 0, 1); } cout << "ViewProbe::CreateWindow 19" << endl; gtk_table_attach_defaults(table, GTK_WIDGET(table_probe), 0, 1, 0, 7); } cout << "ViewProbe::CreateWindow 2" << endl; GtkTable* table_user = Utils::create_table(1, 9); gtk_container_set_border_width(GTK_CONTAINER(table_user), 10); gtk_table_attach_defaults(table, GTK_WIDGET(table_user), 0, 1, 7, 8); GtkLabel* label = Utils::create_label(_("Current User:")); m_comboboxtext_user = Utils::create_combobox_text(); gtk_table_attach_defaults(table_user, GTK_WIDGET(label), 0, 2, 0, 1); gtk_table_attach(table_user, GTK_WIDGET(m_comboboxtext_user), 2, 6, 0, 1, (GtkAttachOptions)(GTK_FILL | GTK_EXPAND), GTK_SHRINK, 0, 0); UserSelect::GetInstance()->read_default_username(GTK_COMBO_BOX(m_comboboxtext_user)); UserSelect::GetInstance()->read_username_db(USERNAME_DB, GTK_COMBO_BOX(m_comboboxtext_user)); UserSelect::GetInstance()->set_active_user(GTK_COMBO_BOX(m_comboboxtext_user), UserSelect::GetInstance()->get_active_user()); IniFile ini(string(CFG_RES_PATH) + string(STORE_DEFAULT_ITEM_PATH)); cout << "ViewProbe::CreateWindow 3" << endl; ExamItem exam; int index_username = exam.ReadDefaultUserIndex(&ini); gtk_combo_box_set_active(GTK_COMBO_BOX(m_comboboxtext_user), index_username); g_signal_connect(GTK_COMBO_BOX(m_comboboxtext_user), "changed", G_CALLBACK(signal_combobox_changed_probe_user), this); gtk_widget_show_all(GTK_WIDGET(m_dialog)); g_signal_connect(G_OBJECT(m_dialog), "delete-event", G_CALLBACK(signal_window_delete_event), this); cout << "ViewProbe::CreateWindow 4" << endl; g_keyInterface.Push(this); SetSystemCursorToCenter(); } GtkWidget* ViewProbe::CreateProbe(const string probe_name, const char probeType, const vector<string> exam_type, int probe_index) { GtkBox* vbox = Utils::create_vbox(); GtkLabel* label_name = NULL; if (!probe_name.empty()) { label_name = Utils::create_label(ProbeMan::GetInstance()->VerifyProbeName(probe_name)); } else { label_name = Utils::create_label(_("No Probe")); } GtkFrame* frame_image = Utils::create_frame(); GtkFrame* frame_exam = Utils::create_frame(); gtk_box_pack_start(vbox, GTK_WIDGET(label_name), FALSE, FALSE, 10); gtk_box_pack_start(vbox, GTK_WIDGET(frame_image), FALSE, FALSE, 0); gtk_box_pack_start(vbox, GTK_WIDGET(frame_exam), TRUE, TRUE, 0); gtk_misc_set_alignment(GTK_MISC(label_name), 0.5, 0); string probe_path; switch ((int)probeType) { case 'C': case 'c': { probe_path = "res/probe/35C50K.png"; break; } case 'L': case 'l': { if (probe_name == "55L60H") { probe_path = "res/probe/55L60H.png"; } else { probe_path = "res/probe/75L40K.png"; } break; } case 'T': case 't': { if (probe_name == "65C10H" || probe_name == "65C10E") { probe_path = "res/probe/65C10H.png"; } else { probe_path = "res/probe/65C10K.png"; } break; } case 'N': case 'n': probe_path = "res/probe/35C20H.png"; break; case 'P': case 'p': probe_path = "res/probe/30P16A.png"; break; case 'V': case 'v': probe_path = "res/probe/35D40J.png"; break; case 0: probe_path = "res/probe/NoProbe.png"; break; default: probe_path = "res/probe/35C50K.png"; break; } GtkImage* image_probe = Utils::create_image(string(CFG_RES_PATH) + probe_path); gtk_container_add(GTK_CONTAINER(frame_image), GTK_WIDGET(image_probe)); GtkScrolledWindow* scrolled_window = Utils::create_scrolled_window(); gtk_container_add(GTK_CONTAINER(frame_exam), GTK_WIDGET(scrolled_window)); if (probe_index >= 0 && probe_index <= 3) { GtkTreeView* treeview = CreateTreeView(exam_type, probe_index); gtk_container_add(GTK_CONTAINER(scrolled_window), GTK_WIDGET(treeview)); if (probe_index == 0) { m_treeview0 = treeview; } if (probe_index == 1) { m_treeview1 = treeview; } if (probe_index == 2) { m_treeview2 = treeview; } if (probe_index == 3) { m_treeview3 = treeview; } } return GTK_WIDGET(vbox); } vector<string> ViewProbe::CreateAllExamType(const string model, vector<ExamItem::EItem> item) { vector<string> vec; for (int i = 0; i < item.size(); i++) { vec.push_back(EXAM_TYPES[item[i]]); } GetUserItemNameOfProbe(model); for (int i = 0; i < m_vecUserItemName.size(); i++) { vec.push_back(m_vecUserItemName[i]); } } void ViewProbe::GetUserItemNameOfProbe(const string model) { m_vecUserItemName.clear(); IniFile ini(string(CFG_RES_PATH) + string(STORE_DEFAULT_ITEM_PATH)); ExamItem exam; string username = exam.ReadDefaultUserSelect(&ini); ExamItem examitem; vector<string> useritemgroup = examitem.GetDefaultUserGroup(); for (int i= 0 ; i < useritemgroup.size(); i++) { string userselect; string probelist; string useritem; string department; string firstGenItem; examitem.GetDefaultUserItem(useritemgroup[i], userselect, probelist, useritem, department, firstGenItem); ExamPara exampara; exampara.name = useritem; exampara.index = ExamItem::USERNAME; if(username == userselect) { if (probelist == model) { m_vecUserItemName.push_back(exampara.name); } } } } GtkTreeView* ViewProbe::CreateTreeView(const vector<string> exam_type, int probe_index) { GtkTreeModel* model = CreateModel(exam_type, probe_index); GetCurExamItemIndex(exam_type, probe_index); if (probe_index >= 0 && probe_index <= 3) { GtkTreeView* treeview = Utils::create_tree_view(model); AddColumn(treeview); gtk_tree_view_set_enable_search(treeview, FALSE); gtk_tree_view_set_headers_visible(treeview, FALSE); GtkTreeSelection* select = gtk_tree_view_get_selection(treeview); gtk_tree_selection_set_mode(select, GTK_SELECTION_SINGLE); GTK_WIDGET_UNSET_FLAGS (treeview, GTK_CAN_FOCUS); if (m_preSocketIndex == probe_index && m_examItemIndex >= 0) { stringstream ss; ss << m_examItemIndex; m_treeViewPath = ss.str(); GtkTreePath* path = gtk_tree_path_new_from_string(m_treeViewPath.c_str()); if (path != NULL) { gtk_tree_view_set_cursor(treeview, path, NULL, TRUE); gtk_tree_path_free(path); m_treeViewIndex = m_preSocketIndex; } } g_signal_connect(treeview, "focus-out-event", G_CALLBACK(signal_treeview_focusout), this); g_signal_connect(treeview, "button-press-event", G_CALLBACK(signal_treeview_button_clicked), this); g_object_unref(model); if (probe_index == 0) { m_treeview0 = treeview; } if (probe_index == 1) { m_treeview1 = treeview; } if (probe_index == 2) { m_treeview2 = treeview; } if (probe_index == 3) { m_treeview3 = treeview; } return treeview; } return NULL; } GtkTreeModel* ViewProbe::CreateModel(const vector<string> exam_type, int probe_index) { GtkTreeIter iter; GtkListStore* store = gtk_list_store_new(N_COLUMNS, G_TYPE_INT, G_TYPE_STRING); for (int i = 0; i < exam_type.size(); i++) { if (!exam_type[i].empty()) { gtk_list_store_append(store, &iter); gtk_list_store_set(store, &iter, PROBE_INDEX, probe_index, EXAM_COLUMN, exam_type[i].c_str(), -1); } } return GTK_TREE_MODEL(store); } void ViewProbe::AddColumn(GtkTreeView* treeview) { GtkCellRenderer* renderer_text = gtk_cell_renderer_text_new(); GtkTreeViewColumn* column_text = gtk_tree_view_column_new_with_attributes("EXAM_NAME", renderer_text, "text", EXAM_COLUMN, NULL); gtk_tree_view_append_column(treeview, column_text); } void ViewProbe::GetCurExamItemIndex(const vector<string> exam_type, int probe_index) { string str_check_park = TopArea::GetInstance()->GetCheckPart(); m_examItemIndex = 0; for (int i = 0; i < exam_type.size(); i++) { if (!exam_type[i].empty()) { if (m_preSocketIndex == probe_index) { if (str_check_park == exam_type[i]) { m_examItemIndex++; } else { break; } } } } }
cd00d50a6bde829e1bee2c03a440ca811c6c2085
a9aa074f0d0bbbd75bc5ea72c4a60c3985407762
/attitude/tasks/newmakefilter/BooleanData.cc
030304bee9e60c857021bbac6b55fa14df0b0a0a
[]
no_license
Areustle/heasoft-6.20
d54e5d5b8769a2544472d98b1ac738a1280da6c1
1162716527d9d275cdca064a82bf4d678fbafa15
refs/heads/master
2021-01-21T10:29:55.195578
2017-02-28T14:26:43
2017-02-28T14:26:43
83,440,883
0
1
null
null
null
null
UTF-8
C++
false
false
1,340
cc
BooleanData.cc
#include "BooleanData.hh" /******************************************************************************** * check thast all bits are equal. Note that we assume that the padding bits * are always properly set to zero. ********************************************************************************/ BooleanData::BooleanData(int dimen) : Data(dimen, TLOGICAL) { value = new char[dimen]; } // end of constructor /******************************************************************************** * ********************************************************************************/ bool BooleanData::equals(const Data* data) const { const BooleanData* cast = dynamic_cast<const BooleanData*>(data); if(cast == NULL) return false; for(long i=0; i< dimen; ++i) { if(value[i] != cast->value[i]) return false; } return true; } // end of equals method /******************************************************************************** * write out the bits. There's probably a more efficient way to do this, * but who cares? ********************************************************************************/ void BooleanData::print(ostream& out) const { for(long i=0; i< dimen; ++i) { if(value[i] == 0) out << '0'; else out << value[i]; } } // end of print method
0a5bc2081ae37284261b8ea4c0c7f77d6c1bda3a
3c37f543bf4995e6029b716be42ad9ca3fb717b9
/Implement strStr().cpp
6afd0f9af101ab4b8a81730939a3ee3ce3f61fed
[]
no_license
awplxz/LeetCode
4838261a11eec041c00981e810e72bdffe4078f6
673c4687d9588ebc3b9ee9ee9330be2fb18c8aa1
refs/heads/master
2021-01-20T20:08:59.072018
2016-07-21T01:43:42
2016-07-21T01:43:42
61,102,987
0
0
null
null
null
null
UTF-8
C++
false
false
410
cpp
Implement strStr().cpp
class Solution { public: int strStr(string haystack, string needle) { int n = haystack.length(); int m = needle.length(); int i ,j; if(m == 0) return 0; for(i = 0;i<=n-m;i++){ for(j = 0;j<m;j++){ if(haystack[i+j] != needle[j]) break; } if(j == m) return i; } return -1; } };
2d3bb2916c3fa93482fa341a1b6614bdcd60afa7
2a35885833380c51048e54fbdc7d120fd6034f39
/Competitions/ICPC/2020/Sub-Regionals/N/N.cpp
03fd490780aea91113d7912d2200bb0acf13fcbf
[]
no_license
NelsonGomesNeto/Competitive-Programming
8152ab8aa6a40b311e0704b932fe37a8f770148b
4d427ae6a06453d36cbf370a7ec3d33e68fdeb1d
refs/heads/master
2022-05-24T07:06:25.540182
2022-04-07T01:35:08
2022-04-07T01:35:08
201,100,734
8
7
null
null
null
null
UTF-8
C++
false
false
1,753
cpp
N.cpp
#include <bits/stdc++.h> #define DEBUG if(0) #define lli long long int #define ldouble long double using namespace std; const int maxX = 31622777; // sqrt(10^15) bool notPrime[maxX + 1]; vector<int> primes; const int maxN = 1e3; int m, n, k; lli ns[maxN], ms[maxN]; vector<pair<lli, int>> nToM[maxN], mToN[maxN]; void propagate(int i) { for (auto &e: mToN[i]) ns[e.first] /= ms[i]; } int main() { notPrime[0] = notPrime[1] = true; for (int i = 2; i <= maxX; i ++) { if (!notPrime[i]) primes.push_back(i); //primeFactors[i].push_back({i, 1}); for (int j = 0; i*primes[j] <= maxX; j ++) { notPrime[i*primes[j]] = true; int p = 0, num = i * primes[j]; while (num % primes[j] == 0) num /= primes[j], p ++; // primeFactors[i * primes[j]].push_back({primes[j], p}); // primeFactors[i * primes[j]].insert(primeFactors[i * primes[j]].end(), primeFactors[num].begin(), primeFactors[num].end()); if (i % primes[j] == 0) break; } } while (scanf("%d %d %d", &m, &n, &k) != EOF) { for (int i = 0; i < n; i++) scanf("%lld", &ns[i]); for (int i = 0; i < k; i++) { int mi, ni, d; scanf("%d %d %d", &mi, &ni, &d); mi--, ni--; nToM[ni].push_back({mi, d}); mToN[mi].push_back({ni, d}); } int sp = 0; for (int i = 0; i < m; i++) { ms[i] = -1; for (; sp < primes.size(); sp++) if (ns[mToN[i][0].first] % primes[sp] == 0) { ms[i] = primes[sp++]; propagate(i); break; } if (ms[i] == -1) { ms[i] = ns[mToN[i][0].first]; propagate(i); } } for (int i = 0; i < m; i++) printf("%lld%c", ms[i], i < m - 1 ? ' ' : '\n'); } return 0; }
0ccf374168ff942fca286462c915b229b2899761
5e135c34baf51eb8c17db4b7fa71fb4f21ab8b8c
/external/aloha_cm/FFS1_3_1.h
c73e57e1c8646396274949665d96bec787701c29
[]
no_license
lmcoy/mypowheg
cd77ae40471272282e28da4a3b21ea12c2d9794c
f9f57e50ebed0d1756b1472e1ef29f4e5bf5dfb9
refs/heads/master
2021-01-12T08:07:54.918090
2018-09-30T16:53:51
2018-09-30T16:53:51
76,482,229
2
0
null
2017-04-27T09:28:32
2016-12-14T17:34:54
Fortran
UTF-8
C++
false
false
330
h
FFS1_3_1.h
// This File is Automatically generated by ALOHA // #ifndef FFS1_3_1_guard #define FFS1_3_1_guard #include <complex> void FFS1_3_1(std::complex<double> F2[], std::complex<double> S3[], std::complex<double> COUP1, std::complex<double> COUP2, std::complex<double> M1, std::complex<double> F1[]); #endif
2d7b8933f053131668838f91ed4000b999059498
3599675c04ebe39d269c37495c2f5a55d2b8bde1
/boj_sources/11931.cpp
66e30b1b236872a9d9e81ec2fd32ffef2af92e78
[]
no_license
JOOHOJANG/Problem_Solving
56b7c88938e482904e468e32950a68cfa4a6aa65
a20946e882e83843c5933b1792b25c6625042dee
refs/heads/master
2022-08-14T05:18:47.122762
2020-05-18T06:38:38
2020-05-18T06:38:38
264,841,077
0
0
null
null
null
null
UTF-8
C++
false
false
468
cpp
11931.cpp
#include <cstdio> #include <algorithm> #include <stdlib.h> using namespace std; int arr[1000000]; int compare(const void *a, const void *b) { int num1 = *(int*)a; int num2 = *(int*)b; ​ if (num1 > num2) return -1; if (num1 < num2) return 1; return 0; } int main() { int n, i; scanf("%d", &n); for (i = 0; i < n; i++) scanf("%d", &arr[i]); qsort(arr, n, sizeof(int), compare); for (i = 0; i < n; i++) printf("%d\n", arr[i]); }
4e98627968da7df2a0f4daa06910da1fa2784d2c
d28a1ce087a84a4be8eac81c20b507d84d026425
/Homework 2/hw02.cpp
3f4dc85e52dc1fd9cc5addb1f4efc9092e9a512e
[]
no_license
jackyteoh/CS1124
04fcb90c4c2abadceae72a8eb5e4e97d472425e0
5ab98775db6d1bcd15504e6d00c71d0c7f5c7ea4
refs/heads/master
2021-01-17T23:19:16.648343
2018-05-22T03:42:49
2018-05-22T03:42:49
68,481,898
0
1
null
null
null
null
UTF-8
C++
false
false
6,695
cpp
hw02.cpp
/* Jacky Teoh - jt2908 CS1124 - Homework 2 - Warriors hw02.cpp */ #include <iostream> #include <string> #include <fstream> #include <vector> using namespace std; // Creating Weapon class class Weapon { public: // Weapon constructor, taking in the name of the weapon and the weapon strength as parameters, initialized Weapon(string inputWeapon, int inputStrength) : weaponName(inputWeapon), weaponStrength(inputStrength) {} // Weapon name getter string getWeapon() const { return weaponName; } // Weapon strength getter int getWeaponStrength() const { return weaponStrength; } // Weapon strength setter, used for after battles. void setWeaponStrength(int newStrength) { weaponStrength = newStrength; } private: string weaponName; int weaponStrength; }; // Creating Warrior class class Warrior { public: // Warrior constructor, taking in warrior name, weapon name, weapon strength, // Initializing to warrior, creating a weapon for the warrior using the parameters. Warrior(string inputWarrior, string inputWeapon, int inputStrength) : warriorName(inputWarrior), warriorsWeapon(inputWeapon, inputStrength) {} // Warrior name getter string getName() const{ return warriorName; } // Getting the name of the weapon FROM the weapon class THROUGH the warrior. string getWeaponName() const { return warriorsWeapon.getWeapon(); } // Getting the strength of the weapon FROM the weapon class THROUGH the warrior int getWeaponStrengthWarrior() const { return warriorsWeapon.getWeaponStrength(); } // Setting the strength of the weapon THROUGH the warrior void setWeaponStrengthWarrior(int newStrength) { warriorsWeapon.setWeaponStrength(newStrength); } private: string warriorName; Weapon warriorsWeapon; }; // Displaying the status of every warrior, taking in a vector of Warriors as a parameter. void displayStatus(vector<Warrior>& x) { // Iterates over the vector, for every warrior found, prints out the name, weapon name, and weapon strength of the warrior. for (Warrior& w : x) { cout << "Warrior: " << w.getName() << ", Weapon: " << w.getWeaponName() << ", " << w.getWeaponStrengthWarrior() << endl; } } // Battle function, taking in two warriors as parameters. void battle(Warrior& x, Warrior& y) { // Printing out who battles who cout << x.getName() << " battles " << y.getName() << endl; // Testing if the strength of the first warrior passed is greater than the strength of the second warrior passed. // If it's greater, sets the strength of the first warrior to the value of first warrior's strength minus the second warrior's strength // Then sets the value of the weaker warrior's strength to 0 because he lost. // Then prints out the victor of the battle. if (x.getWeaponStrengthWarrior() > y.getWeaponStrengthWarrior()) { x.setWeaponStrengthWarrior(x.getWeaponStrengthWarrior() - y.getWeaponStrengthWarrior()); y.setWeaponStrengthWarrior(0); cout << x.getName() << " wins! " << endl; } // Testing if the strength of the second warrior passed is greater than the strength of the first warrior passed. // Does the same as above, stronger - weaker. // Sets the strength of the weaker to 0. // Then prints out the victor of the battle. if (y.getWeaponStrengthWarrior() > x.getWeaponStrengthWarrior()) { y.setWeaponStrengthWarrior(y.getWeaponStrengthWarrior() - x.getWeaponStrengthWarrior()); x.setWeaponStrengthWarrior(0); cout << y.getName() << " wins! " << endl; } // Testing if the strengths of the two warriors passed are equal. // Then both their strengths both get reduced to 0 // Then prints out that they both lose. if (x.getWeaponStrengthWarrior() == y.getWeaponStrengthWarrior()) { x.setWeaponStrengthWarrior(0); y.setWeaponStrengthWarrior(0); cout << x.getName() << " and " << y.getName() << " both lose." << endl; } } int main() { // Checking to see if the file successfully opens or not. ifstream ifs("warriors.txt"); if (ifs.is_open()) { cout << "Your file has successfully opened!" << endl << endl; } else { cout << "Error in opening file." << endl << endl; } // Creating a vector of Warriors called vectorOfWarriors vector<Warrior> vectorOfWarriors; // Checking the first word in the file to see what we have to do (Create a warrior, Check the status, or battle) string task; while (ifs >> task) { // If "Warrior" is the first word, that means we have to create a warrior. // Then sets the following values, which are the name of the warrior, name of the warrior's weapon, and the weapon strength, // To variables created, warriorName, warriorWeapon, and weaponPower // Then gets passed into the warrior constructor, and pushes back that warrior object into the vector of Warriors. if (task == "Warrior") { string warriorName; string warriorWeapon; int weaponPower; ifs >> warriorName >> warriorWeapon >> weaponPower; Warrior nextWarrior(warriorName, warriorWeapon, weaponPower); vectorOfWarriors.push_back(nextWarrior); } // If "Status" is the first word, it will call the displayStatus function and pass in the vector of Warriors. else if (task == "Status") { displayStatus(vectorOfWarriors); } // If "Battle" is the first word, means we have to call the battle function // "Battle" is followed by two warrior's names who are designated to battle. // Creating variables for warrior1 and warrior2 to store those names. // Then variables for the positions of those warriors in the vector are created. // Checks the line, inputs the string name of the warriors from the file into the warrior1 and warrior2 variables. // Then iterates over the vector of Warriors, if the name matches with the name from the vector, // Stores the position of that warrior in positionOfWarrior. This helps us call it later in the battle function because the an index of a vector of warriors is a warrior: vectorOfWarriors[i] is a warrior. // Iterates again to check and store the second warrior's name and position. // Then calls the battle function, passing in the warriors (The position of the warriors in the vector) else if (task == "Battle") { string warrior1; string warrior2; int positionOfWarrior1; int positionOfWarrior2; ifs >> warrior1 >> warrior2; for (int i = 0; i < vectorOfWarriors.size(); i++) { if (warrior1 == vectorOfWarriors[i].getName()) { positionOfWarrior1 = i; } } for (int j = 0; j < vectorOfWarriors.size(); j++){ if (warrior2 == vectorOfWarriors[j].getName()) { positionOfWarrior2 = j; } } battle(vectorOfWarriors[positionOfWarrior1], vectorOfWarriors[positionOfWarrior2]); } } // Closing the opened file. ifs.close(); system("pause"); }
a73c74a9f526c0378ad220b4a2697562fe67b9d0
c0d8930b9cfecf8790937a67c32d14e35b716b8e
/charInputTest/main.cpp
160b154eaf1c69d7b92c249e50669e2931a0fe2f
[]
no_license
imWhS/ProblemSolving
4309af97b3760f7a0fbc01a73551f0bd778ebc30
1ca342d6d244c2ff3c6b571f028e0a7d1f8f6b98
refs/heads/master
2021-08-20T04:53:16.972633
2021-06-29T14:26:36
2021-06-29T14:26:36
231,716,104
0
0
null
null
null
null
UTF-8
C++
false
false
676
cpp
main.cpp
#include <iostream> #define endl "\n" using namespace std; int N; char map[51][51]; int main() { ios::sync_with_stdio(false); cin >> N; for(int i = 1; i <= N; i++) for(int j = 1; j<= N; j++) cin >> map[i][j]; for(int i = 1; i <= N; i++) { for(int j = 1; j <= N; j++) cout << map[i][j] << " "; cout << endl; } map[1][1]++; map[2][2]++; for(int i = 1; i <= N; i++) { for(int j = 1; j <= N; j++) cout << map[i][j] << " "; cout << endl; } if(map[1][2] == 'b') cout << "b hello!" << endl; if(map[2][2] == '3') cout << "3 hello!" << endl; return 0; }
80a433073d78a4ff87a70f1cf960b07804225b00
787bb89817b3e0730b9d532fabb1c5fd97cbcebe
/server/main.cpp
60bdfd78f1b55627d693a19af774398f43b9d07e
[]
no_license
ankhmesut/clientserver
9ca9604377be785cda9adc93eadfbd5ed60777fc
a0d2f9f538210ba36d14b836b0771c26f2597047
refs/heads/master
2022-10-22T10:48:25.656766
2020-06-08T10:07:16
2020-06-08T10:07:16
270,614,516
0
0
null
null
null
null
UTF-8
C++
false
false
3,449
cpp
main.cpp
#include <iostream> #include <chrono> #include <thread> #include <limits> #include <cstdlib> #include <iterator> #include "ber.h" #include "tcpserver.h" #include "gmpxx.h" static constexpr const char * DATA_LENGTH = "67108864"; std::string getHostStr(const Connection& client) { uint32_t ip = client.getHost (); return std::string() + std::to_string(int(reinterpret_cast<char*>(&ip)[0])) + '.' + std::to_string(int(reinterpret_cast<char*>(&ip)[1])) + '.' + std::to_string(int(reinterpret_cast<char*>(&ip)[2])) + '.' + std::to_string(int(reinterpret_cast<char*>(&ip)[3])) + ':' + std::to_string( client.getPort ()); } // // For demo purposes returns random char :) // May read from file or smth. // char getNextByte() noexcept { return 'A' + rand() % 26; } std::string sendLargeData(const Connection &client, const mpz_class &length, std::function<char(void)> nextByte) { int chunkSize = 1024; mpz_class sent = 0; int ret = 0; if (length <= chunkSize) { std::unique_ptr<char[]> data(new char[length.get_ui()]); for (size_t i = 0; i < length.get_ui(); ++i) data[i] = nextByte(); return std::to_string(client.sendData(data.get(), length.get_ui())); } while (sent < length) { std::unique_ptr<char[]> data(new char[chunkSize]); if (sent + chunkSize <= length) { for (size_t i = 0; i < chunkSize; ++i) data[i] = nextByte(); ret = client.sendData(data.get(), chunkSize, false); } else if (sent != length) { for (size_t i = 0; i < length - sent; ++i) data[i] = nextByte(); mpz_class l = length - sent; ret = client.sendData(data.get(), l.get_ui(), false); } if (ret < 0) return "0"; else if (ret == 0) return "-1"; else sent += ret; } return sent.get_str(); } int main(int argc, char *argv[]) { ::srand(::time(NULL)); TcpServer server( 8080, [](Connection client) { std::cout << "Thread: " << std::this_thread::get_id() << std::endl; // Print client address std::cout << "Connected host: " << getHostStr(client) << std::endl; std::vector<uint8_t> len_ber; convert_len_to_ber(DATA_LENGTH, len_ber); // Send BER encoded length octets std::cout << "Sent BER length bytes: " << client.sendData((char *)len_ber.data(), len_ber.size(), false) << ": "; std::copy(len_ber.cbegin(), len_ber.cend(), std::ostream_iterator<int>(std::cout, " ")); std::cout << std::endl; // Send data part mpz_class len; len = DATA_LENGTH; std::cout << "Sent data bytes: " << sendLargeData(client, len, getNextByte) << std::endl; client.close(); } ); if(server.start() == Status::Up) { std::cout << "Server is up!" << std::endl; server.joinLoop(); } else { std::cout << "Server start error! Error code:" << int(server.getStatus()) << std::endl; return -1; } return 0; }
8046988fe64e03fdc95d8c6cb5bf7ac872892270
9421b150bac45eeec08ef6c69694e789a1694773
/ITP1/ITP1_4_C/main.cpp
721cc507a8c8f6b805a0550547958c5c310eeb19
[]
no_license
izumisan/AOJ
3e36a2bb987852acfa1afe6ffabfc7279244fcda
596470bba3c5a3ee3ecff666e4b96a67f1bd9f4c
refs/heads/master
2020-07-10T20:01:18.697945
2019-09-05T15:02:55
2019-09-05T15:02:55
204,356,784
0
0
null
null
null
null
UTF-8
C++
false
false
736
cpp
main.cpp
// AOJ: ITP1_4_C // http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=ITP1_4_C&lang=jp #include <iostream> #include <string> #include <map> #include <functional> static const std::map<std::string, std::function<int(int, int)>> calculator_ = { { "+", [](int x, int y){ return x + y; } }, { "-", [](int x, int y){ return x - y; } }, { "*", [](int x, int y){ return x * y; } }, { "/", [](int x, int y){ return x / y; } } }; int main() { std::string buff {}; int a, b = 0; std::string op {}; while ( true ) { std::cin >> a >> op >> b; if ( op == "?" ) { break; } std::cout << calculator_.at( op )( a, b ) << std::endl; } return 0; }
9098acbdaf52df8067eb2188a6423ffe3419a436
0bbfc371e210ef951cef31622aeaba722c388180
/src/pcb.cpp
1cd546a19ab1d49d1ac78df163dbbe2c5a8939d5
[ "CC0-1.0" ]
permissive
valzgit/OS-Kernel
45d52e48d95de42d75fa0b988d28251fa0463852
189ec26c8df7ab3e98bbe5fa119fd4a8acfd0849
refs/heads/main
2023-04-28T22:17:13.619631
2021-05-16T21:04:00
2021-05-16T21:04:00
367,984,612
1
0
null
null
null
null
UTF-8
C++
false
false
3,876
cpp
pcb.cpp
#include "pcb.h" #include "schedule.h" #include <iostream.h> #include "pcbqueue.h" #include "sleeplst.h" #include "idlethr.h" #include <stdlib.h> #ifndef BCC_BLOCK_IGNORE void _FAR * _FARFUNC operator new(unsigned size) { asm { pushf; cli; } void _FAR * membuf = malloc(size); asm { popf; } return membuf; } void _FARFUNC operator delete(void _FAR * p) { asm { pushf; cli; } free(p); asm { popf; } } #endif int lockFlag=0; int dispIgnored=0; void lockF(){lockFlag=1;} void unlockF(){lockFlag=0;if(dispIgnored==1){dispIgnored=0;dispatch();}} PCB* PCB::running = 0; Time PCB::runCounter = 0; pInterrupt PCB::prevTimer = 0; SleepList* PCB::sleepingThreads = 0; IdleThread* PCB::idleThread = 0; PCB* PCB::idlePCB = 0; int PCB::creatingIdleThread = 0; int PCB::Blocked = 1; int PCB::Ready = 2; int PCB::Finished = 3; int PCB::New = 4; ID PCB::nextId = 0; PCBQueue* PCB::allThreads = 0; void setVect(IVTNo ivtNo, pInterrupt newIntr) { LOCK #ifndef BCC_BLOCK_IGNORE setvect(ivtNo, newIntr); #endif UNLOCK } pInterrupt getVect(IVTNo ivtNo) { LOCK pInterrupt retVal = 0; #ifndef BCC_BLOCK_IGNORE retVal = getvect(ivtNo); #endif UNLOCK return retVal; } PCB::PCB(StackSize stackSize, Time timeSlice, Thread* thread) { this->stackSize = stackSize; this->timeSlice = timeSlice; myThread = thread; ss = sp = bp = 0; stack = 0; state = PCB::New; blockedThreads = new PCBQueue(); if (creatingIdleThread != 0) idlePCB = this; id = ++nextId; allThreads->add(this); ksem = 0;ret=0; } PCB::~PCB() { allThreads->remove(this); delete blockedThreads; delete[] stack; } void PCB::setupStack() { StackSize size = stackSize / sizeof(unsigned int); stack = new unsigned int[size]; stack[size - 1] = SEGM(myThread); stack[size - 2] = OFFS(myThread); stack[size - 3] = 0; // ret_wrapper CS stack[size - 4] = 0; // ret_wrapper IP stack[size - 5] = 0x200; stack[size - 6] = SEGM(&wrapper); stack[size - 7] = OFFS(&wrapper); ss = SEGM(stack + size - 16); sp = OFFS(stack + size - 16); //sizeof(tip) bp = OFFS(stack + size - 16); } void PCB::start() { if (state == PCB::New) { setupStack(); if (this != PCB::idlePCB) Scheduler::put(this); state = PCB::Ready; } } ID PCB::getId() { return id; } Thread* PCB::getThreadById(ID id) { PCB* pcb=0; pcb = allThreads->findPCB(id); if (pcb!=0) { return pcb->myThread; } else { return 0; } } void interrupt PCB::dispatchIntr() { static unsigned int tss, tsp, tbp; #ifndef BCC_BLOCK_IGNORE asm { mov tss, ss; mov tsp, sp; mov tbp, bp; } #endif running->ss = tss; running->sp = tsp; running->bp = tbp; if (running != PCB::idlePCB && running->state == PCB::Ready){ Scheduler::put(running);} running = Scheduler::get(); if (running == 0) { running = PCB::idlePCB; } ASSERT(running != 0); tss = running->ss; tsp = running->sp; tbp = running->bp; #ifndef BCC_BLOCK_IGNORE asm { mov ss, tss; mov sp, tsp; mov bp, tbp; } #endif runCounter = 0; } void PCB::wrapper(Thread* thread) { thread->run(); LOCK PCB* pcb=0; while ((pcb=running->blockedThreads->takeFirst())!=0) { pcb->state = PCB::Ready; Scheduler::put(pcb); } running->state = PCB::Finished; UNLOCK dispatch(); } void PCB::waitToComplete() { if ((running != this) && (this->state == PCB::Ready || this->state == PCB::Blocked)) { running->state = PCB::Blocked; this->blockedThreads->add(running); dispatch(); } } void tick(); void interrupt PCB::timerIntr(...) { (*prevTimer)(); runCounter++; tick(); sleepingThreads->updateSleepingThreads(); if(lockFlag==1){dispIgnored=1;return;} if (runCounter >= running->timeSlice && running->timeSlice > 0) { dispatch(); } }
41b9af4d8639e5f8a5bee90f2e258a3053df7857
d0507d52048fb2417c129942dd37ec21de7024e4
/B2nkbz/B2nkbz/B2nkbz_custom_main.cxx
20ac976e20696b75e2b8ec244a7ea65ddf870684
[]
no_license
isliulin/B2nkbz
8b176848a7d12cda0e99129ac70f4b301c9721a8
4636a2fc1737ef3534cfaf56fe448d376fc8d86b
refs/heads/master
2021-09-27T10:37:36.759927
2018-11-08T01:27:32
2018-11-08T01:27:32
null
0
0
null
null
null
null
GB18030
C++
false
false
745
cxx
B2nkbz_custom_main.cxx
#include "init.h" #include "Debug.h" #include "DBHandler.h" #ifdef __cplusplus extern "C" { #endif /****************************************************************** 程序主函数 *******************************************************************/ DLLAPI int B2nkbz_register_callbacks() { int ifail = ITK_ok; //注册函数,并非是注册user service函数,其需要另外定义 ifail = CUSTOM_register_exit( "B2nkbz", "USER_gs_shell_init_module", (CUSTOM_EXIT_ftn_t)CUST_init_module); if (ifail == 0) { Debug("初始化CUST_init_module成功"); } else { Debug("初始化CUST_init_module失败"); } //B2nkbz_save(USERNAME, PASSWORD, DBNAME,NULL); return ifail; } #ifdef __cplusplus } #endif
7012fb3dab100a003f49a39b6d362867af01003c
60569746dc5203f1a74afc3b589b3307b7428cfd
/tests/cmdline_tester.cpp
e8c9906de79ec417a3c5236594e62acb6e6d75bb
[]
no_license
voytech/DesktopCouchResource
ab272aab1df38159cfbecab8009b53456763683a
925b3b94080100106717204e36ba12d649329860
refs/heads/master
2021-01-01T05:36:13.129050
2010-09-11T08:35:20
2010-09-11T08:35:20
null
0
0
null
null
null
null
UTF-8
C++
false
false
951
cpp
cmdline_tester.cpp
#include <QtCore/QCoreApplication> #include <iostream> #include <qdebug.h> #include <qtimer.h> #include <qmetatype.h> //include <Qt/QtDBus> //#include "desktop_couch.h" #include <desktop_couch.h> //#include <couchdb-qt.h> //class Test; int main( int argc, char** argv ) { QCoreApplication app( argc, argv ); /*QMap<QString,QVariant> smap; smap.insert("Name",QVariant(QString("Dorota"))); smap.insert("LastName",QVariant(QString("Loran"))); smap.insert("BirthDate",QVariant(QString("19-09-1985"))); QVariant sample(smap); CouchDBDocumentInfo info; info.setId("doc4"); info.setDatabase("contacts");*/ //DesktopCouchProvider provider; //CouchDBQt* db = provider.getWrappedCouchDB(); //provider.authenticate(); CouchDBQt* db = new CouchDBQt(5964); //db->listDocuments("contacts2"); db->createDatabase("contacts"); // qDebug("removing "); //db->deleteDocument(info);*/ //delete db; return app.exec(); }
026bd115b8b0275daa7f2bdc157f59c1e943da95
e1fbd1fd1d7fe04926d76e3513bcbd155b522342
/RShell/CDCommand.h
396b985262fca3c58ae7ad9245862310e3b3fd5a
[]
no_license
RdlP/RShell
fc55c512f21c9fc1f1b5ae19c9623db5909a1b74
cd0f4a426f17481ec6dd190b1189248489c4ac5a
refs/heads/master
2021-01-19T00:50:25.271911
2017-04-04T16:25:46
2017-04-04T16:25:46
87,210,149
0
0
null
null
null
null
UTF-8
C++
false
false
157
h
CDCommand.h
#pragma once #include "Command.h" class CDCommand : public Command { public: CDCommand(wstring line, Shell*); virtual ~CDCommand(); int execute(); };
558a5248ba709b8689f6f3fd99cd2411e065dbac
93088fe67401f51470ea3f9d55d12e0b40f04450
/jni/include/CraneTrigger.h
cffb9f6ab3bcf8ff4be7d0d36248d649ff4abf95
[ "LicenseRef-scancode-warranty-disclaimer", "MIT" ]
permissive
4nakin/canabalt-bluegin
f9967891418e07690c270075a1de0386b1d9a456
c68dc378d420e271dd7faa49b89e30c7c87c7233
refs/heads/master
2021-01-24T03:08:39.081279
2011-04-17T06:05:57
2011-04-17T06:05:57
null
0
0
null
null
null
null
UTF-8
C++
false
false
422
h
CraneTrigger.h
#pragma once #include "flx/object.h" #include "flx/data/rect.h" class Player; class CraneTrigger; typedef shared_ptr<CraneTrigger> CraneTriggerPtr; class CraneTrigger : public flx::Object { public: Player* player; static CraneTriggerPtr create(flx::Rect frame, Player* player); CraneTrigger(flx::Rect frame, Player* player); virtual void update(); virtual void render() { } };