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
575efc939dd8f5b3aa21adac215640365f817daa
3816aabf6ac456679546a64187589ea41a7edcdf
/src/BoundingBox.cpp
430bf28fba90587732b8899dbc49b90f92309fe1
[ "MIT" ]
permissive
AirChen/AlgorithmCpp
e0f9c156d66802c39be8b8d31b6af0e792545a81
cbb47f0add5cae2c1b2b7fad90c3ee65e17b0e1f
refs/heads/main
2023-06-08T10:43:21.514209
2023-05-24T07:22:49
2023-05-24T07:22:49
367,346,804
0
0
null
null
null
null
UTF-8
C++
false
false
106
cpp
BoundingBox.cpp
// // BoundingBox.cpp // algorithm // // Created by tuRen on 2021/5/14. // #include "BoundingBox.hpp"
96162af169c70404fc2126da313112ef42d3fd0e
6b67ec0f8633e4dfb19d5771fa051b4f6a398993
/usdsCPP/BasicParser/Source/Converters/usdsBinaryParser.cpp
55f3ff24c1895201a2a3908802b0d3c7da895ff6
[]
no_license
rolandocampo/USDS
6c825c1f388312ea662c8866e410a5be487421d8
11a612ccd7e558a7b82853602335a7a3b17776c7
refs/heads/USDS-1.0
2021-01-15T19:35:23.569617
2016-06-09T14:46:56
2016-06-09T14:46:56
64,934,724
0
0
null
2016-08-04T12:57:02
2016-08-04T12:57:02
null
UTF-8
C++
false
false
3,243
cpp
usdsBinaryParser.cpp
#include "converters\usdsBinaryParser.h" #include "dictionary\usdsDictionary.h" #include "base\usdsErrors.h" using namespace usds; BinaryParser::BinaryParser() { }; BinaryParser::~BinaryParser() { }; void BinaryParser::setBinary(const uint8_t* data, size_t data_size) throw(...) try { headExists = false; dictionaryExists = false; bodyExists = false; binary.setBinary(data, data_size); uint8_t signature = binary.readUByte(); // analize binary // try to read Head if (signature == USDS_MAJOR_SIGNATURE) { // read all head uint8_t head[3]; binary.readByteArray(head, 3); if (head[0] != USDS_MINOR_SIGNATURE || head[1] != USDS_MAJOR_VERSION || head[2] != USDS_MINOR_VERSION) throw ErrorMessage(BINARY_PARSER__UNKNOWN_FORMAT, "Unknown format of the binary, head must be '$S10'"); // read dictionary version dictionaryID = binary.readInt(); dictionaryMajor = binary.readUByte(); dictionaryMinor = binary.readUByte(); binary.readUVarint(&documentSize); headExists = true; if (binary.isEnd()) return; // no dictionary and body in binary //read next signature signature = binary.readUByte(); } // try to read Dictionary if (signature == USDS_DICTIONARY_SIGNATURE_WITH_SIZE) { if (!headExists) throw ErrorMessage(BINARY_PARSER__UNKNOWN_FORMAT, "Unknown format of the binary: dictionary without head"); // read dictionary size size_t dict_size; binary.readUVarint(&dict_size); const uint8_t* dict_data = binary.getCurrentPosition(); // try to move to the end of the dictionary binary.stepForward(dict_size); dictionaryBinary.setBinary(dict_data, dict_size); dictionaryExists = true; if (binary.isEnd()) return; // no body in binary //read next signature signature = binary.readUByte(); } // try to read Body if (signature == USDS_BODY_SIGNATURE) { const uint8_t* body_data = binary.getCurrentPosition(); size_t body_size = data_size - (body_data - data); bodyBinary.setBinary(body_data, body_size); bodyExists = true; return; } else throw ErrorMessage(BINARY_PARSER__UNKNOWN_FORMAT) << "Unexpected signature '" << signature << "' at the binary";; } catch (ErrorMessage& msg) { throw ErrorStack("BinaryParser::setBinary") << data << data_size << msg; } catch (ErrorStack& err) { err.addLevel("BinaryParser::setBinary") << data << data_size; throw; } bool BinaryParser::isHeadIncluded() { return headExists; }; bool BinaryParser::isDictionaryIncluded() { return dictionaryExists; }; int32_t BinaryParser::getDictionaryID() { return dictionaryID; }; uint8_t BinaryParser::getDictionaryMajor() { return dictionaryMajor; }; uint8_t BinaryParser::getDictionaryMinor() { return dictionaryMinor; }; bool BinaryParser::isBodyIncluded() { return bodyExists; }; void BinaryParser::initDictionaryFromBinary(Dictionary* dict) throw(...) try { dictionaryParser.parse(&dictionaryBinary, dict); } catch (ErrorStack& err) { err.addLevel("BinaryParser::initDictionaryFromBinary") << (void*)dict; throw; }; void BinaryParser::initBodyFromBinary(Dictionary* dict, Body* body) throw(...) try { bodyParser.parse(&bodyBinary, dict, body); } catch (ErrorStack& err) { err.addLevel("BinaryParser::initBodyFromBinary") << (void*)body; throw; };
87c401b2aba37d2b1422c09da4d2891c738841c1
a271b2edab3c760ba22d9b1009749b8a85f877ab
/tracklet.hpp
166cbd73373ae203d5e92f603218ca01f9ff1f44
[]
no_license
knigawkl/tracker
04836c5e3b553cce605055891e08b9f4bad7135f
99724d88ba8373e1d9c14f732ce957f7b1a6fd61
refs/heads/master
2023-03-02T23:21:45.246756
2021-02-03T19:06:27
2021-02-03T19:06:27
297,281,463
1
1
null
null
null
null
UTF-8
C++
false
false
1,202
hpp
tracklet.hpp
#pragma once #include <vector> #include <iostream> #include "templates.hpp" #include "node.hpp" #include "utils.hpp" #include "video.hpp" #include <opencv2/opencv.hpp> class Tracklet { public: vector<Node> detection_track; Node centroid; video::vidinfo video_info; bool is_end_of_traj; bool is_start_of_traj; bool is_hypothetical = false; cv::Scalar color; Tracklet(const vector<Node> &path, const video::vidinfo &video_info) : video_info(video_info), detection_track(path) { init_color(); set_centroid(); eliminate_outliers(); is_end_of_traj = is_end_of_trajectory(); is_start_of_traj = is_start_of_trajectory(); print(); } void print() const; void draw() const; static void print_tracklets(const vector2d<Tracklet> &tracklets); static void draw_tracklets(const vector2d<Tracklet> &tracklets); private: static constexpr std::size_t const OUTLIER_COEFF = 3; void set_middle_point(); void set_histogram(); void set_centroid(); void eliminate_outliers(); void init_color(); bool is_end_of_trajectory() const; bool is_start_of_trajectory() const; };
bf1af53ca716f1501487910274245d9b2585c736
6eb408c0c8fd99fb3cdd74fd08bb2f7b978a0d3a
/Game engine/beziercurve.cpp
2e907dacb486cf34c0733be3d54c30504c20158c
[]
no_license
BredeJoh/highlights
c1fc99d4c9573df2f8d6df5a817917beb9a24de6
2b398a36f327c10f0e497e75bb7f7251fb8b2991
refs/heads/master
2023-01-08T06:21:35.771669
2019-12-16T14:04:47
2019-12-16T14:04:47
228,050,036
0
0
null
2023-01-04T14:54:07
2019-12-14T16:03:10
C++
UTF-8
C++
false
false
4,561
cpp
beziercurve.cpp
#include "beziercurve.h" #include <cmath> #include "vertex.h" #include "vec3.h" #include "vec2.h" BezierCurve::BezierCurve() { type = Orf::BEZIER; initGeometry(); } void BezierCurve::drawGeometry(GLint positionattribute, GLint normalAttribute, GLint textureAttribute, int renderMode) { glBindBuffer(GL_ARRAY_BUFFER, mVertexBuffer); //glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, mIndexBuffer); SetAttributePointers(positionattribute, normalAttribute, textureAttribute, renderMode); //glPointSize((GLfloat)10.0f); glDrawArrays(GL_LINE_STRIP, 0, mVertices.size()); //GL_POINT_SIZE //Unbind buffers: glBindBuffer(GL_ARRAY_BUFFER, 0); //glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); //Unbind shader glUseProgram(0); } #include <cstdlib> #include <ctime> void BezierCurve::initGeometry() { int curveCount = 1000; // amount of connected beziercurves std::srand((int)std::time(0)); for(int m = 0; m < 4 * curveCount; m++){ controlPoints.push_back(Vec3((std::rand() % 11) -5, (std::rand() % 11) -5, (std::rand() % 11) -5)); } int lineSteps = 100; // amount of lines Vec3 nextPointsOffset; for(int x = 0; x < curveCount; x++) { for(int i = 0; i < lineSteps; i++){ float t = 1.0f/(float)lineSteps * i; Vec3 b = EvaluateBezier(3, t, x); mVertices.push_back(Vertex(Vec3(b.x, b.y, b.z), Vec3(0, 1, 1), Vec2(0, 0))); } // preping points on next curve int nextCurveIndex = (x+1) * 4; // offset from first point in curve to last point nextPointsOffset = nextPointsOffset + (controlPoints[nextCurveIndex-1] - controlPoints[nextCurveIndex-4]); // controlpoint 3 to 4 vector for alligning second point of curve for continous curve Vec3 P2_P3 = controlPoints[nextCurveIndex-1] - controlPoints[nextCurveIndex-2]; //P2_P3 = P2_P3.normalized() * (controlPoints[point-1] - controlPoints[point]); if(x != curveCount-1){ // not done on the last curve controlPoints[nextCurveIndex] = (controlPoints[nextCurveIndex-1]); // set first point in curve to the last of previus curve controlPoints[nextCurveIndex+1] = (controlPoints[nextCurveIndex] + P2_P3); //force allignement controlPoints[nextCurveIndex+2] = (controlPoints[nextCurveIndex+2] + nextPointsOffset); // add offset controlPoints[nextCurveIndex+3] = (controlPoints[nextCurveIndex+3] + nextPointsOffset); } } // we must add the last point mVertices.push_back(Vertex(controlPoints[controlPoints.size()-1], Vec3(0, 1, 1), Vec2(0, 0))); mBoundingBoxmesh = new BoundingBoxMesh(); mBoundingBoxmesh->getBoundingBox()->calulateBoundingBox(mVertices); initializeOpenGLFunctions(); // Transfer vertex data to VBO 0 glGenBuffers(1, &mVertexBuffer); glBindBuffer(GL_ARRAY_BUFFER, mVertexBuffer); glBufferData(GL_ARRAY_BUFFER, mVertices.size()*sizeof(Vertex), mVertices.data(), GL_STATIC_DRAW); } Vec3 BezierCurve::EvaluateBezier(int degree, float t, int curveNum) { Vec3 c[4]; for (unsigned int i = 0; i < 4; i++){ c[i] = controlPoints[i + (curveNum*4)]; } for(int k = 1; k <= degree; k++){ for(int i = 0; i < degree - k + 1; i++){ c[i] = c[i] * (1-t) + c[i+1] * t; } } return c[0]; } //for(int x = 0; x < curveCount; x++) //{ // for (float i = 0; i <= 1.0f; i += 1.0f/(float)lineSteps) // { // Vec3 temp = (controlPoints[0] * ((float)pow(1 - i, 3))) + // (controlPoints[1] * (3 * (float)pow(1 - i, 2) * i)) + // (controlPoints[2] * (3 * (1 - i) * (float)pow(i, 2))) + // (controlPoints[3] * (float)pow(i, 3)); // // //qDebug() << "x: " << temp.x << " y: " << temp.y << " z: " << temp.z << " " << i; // mVertices.push_back(Vertex(temp, Vec3(1.0f, 0.0f + i, 1.0f - i), Vec2(0, 0))); // } // // because of inaccuracies (rounding error) in float, we have to add the last point manually // mVertices.push_back(Vertex(controlPoints[3], Vec3(1, 0, 1), Vec2(0, 0))); // // // vector from startPoint to endPoint in curve // Vec3 nextPointsOffset = (controlPoints[3] - controlPoints[0]); // // // points are offset to be repeated // controlPoints[0] = (controlPoints[3]); // controlPoints[1] = (controlPoints[1] + nextPointsOffset); // controlPoints[2] = (controlPoints[2] + nextPointsOffset); // controlPoints[3] = (controlPoints[3] + nextPointsOffset); //}
d66f66f92f6738395a32f79c399d16b6f6583f27
fa74435c33c7c2387b82b214d1bc7a9308557dca
/BeagleCode/SailbotBrain/include/filterAlphaBeta.h
904c93ae5e41876a44e3e0ca826dc074f0c30136
[]
no_license
munsailbot/munsailbot
34f232f3e63ecc1f3edc8833b890a7f4c6ecaaee
5caad0fb46ef380cb0f4a84fbd71540a29374f20
refs/heads/master
2020-05-21T04:45:01.561250
2018-06-16T21:13:36
2018-06-16T21:13:36
43,016,839
2
2
null
2017-10-20T17:12:13
2015-09-23T17:42:07
C
UTF-8
C++
false
false
586
h
filterAlphaBeta.h
/* * filterAlphaBeta.h * * Created on: 2011-06-08 * Author: Brian */ #ifndef FILTERALPHABETA_H_ #define FILTERALPHABETA_H_ class filterAlphaBeta { long predictedValue; long lastPredictedValue; long lastPredictedRate; long predictedRate; long estimationError; long measuredValue; long upperLimit; long offset; int alpha; int beta; public: filterAlphaBeta(int,int); void init(); void init(long); void filterValue(long, long); void setUpperLimit(long); long getFilteredValue(); long getFilteredRate(); ~filterAlphaBeta(); }; #endif /* FILTERALPHABETA_H_ */
ddaeab9bcf42ac826af06fd54e9a77c53187fb21
e7823aee06fed311ced4be2e16ff619f7bb34521
/Week6/CMP105App/Mushroom.cpp
be68f6bc871995f3d073b137c2b50230e649adb3
[]
no_license
Frazzle17/CMP105_W6
ec4eab54ef123dd791c4e44591b2be2c24e32ac4
05b16686fcef76e5686494cd5194c9f90abdcc2b
refs/heads/master
2021-01-14T19:55:57.515538
2020-02-24T16:35:09
2020-02-24T16:35:09
242,738,749
0
0
null
2020-02-24T13:07:22
2020-02-24T13:07:21
null
UTF-8
C++
false
false
1,108
cpp
Mushroom.cpp
#include "Mushroom.h" #include <iostream> Mushroom::Mushroom() { window = nullptr; float scale = 200; gravity = sf::Vector2f(0, 9.8) * scale; jumping = false; doublejump = false; } Mushroom::~Mushroom() { } void Mushroom::handleInput(float dt) { //jump/double jump if (input->isKeyDown(sf::Keyboard::Up) && jumping == false) { stepVelocity = sf::Vector2f(0, -1000); jumping = true; } if (!input->isKeyDown(sf::Keyboard::Up) && jumping == true && doublejump == false) { jumping = false; doublejump = true; } if (input->isMouseLDown()) { setPosition(sf::Vector2f(input->getMouseX() - (getSize().x / 2), input->getMouseY() - (getSize().y / 2))); stepVelocity = sf::Vector2f(0, 0); } } void Mushroom::update(float dt) { sf::Vector2f pos = stepVelocity * dt + 0.5f * gravity * dt * dt; stepVelocity += gravity * dt; setPosition(getPosition() + pos); sf::Vector2u windowSize = window->getSize(); if (getPosition().y >= (windowSize.y-getSize().y)) { doublejump = false; setPosition(getPosition().x, (windowSize.y - getSize().y)); stepVelocity = sf::Vector2f(0, 0); } }
8222640fd3e4aade073a41dfa06db0a78cbedbc5
64b43c3f095f39684883eeea706e8c3cf5b2aed7
/TATPhysics/TATCommon/TATObjectPool.h
59b6491a0da7479188559a8a7d1478a878ca5477
[]
no_license
thealmightyzhou/TATPhysics
bd426977b12fa387d271f84c1e59a36adeb1a71a
9888f6bcc818ed1dc2ca84a2730ce4f33d8e58c9
refs/heads/master
2023-01-22T07:51:25.249586
2020-12-03T03:41:54
2020-12-03T03:41:54
259,520,730
0
0
null
null
null
null
UTF-8
C++
false
false
2,544
h
TATObjectPool.h
#pragma once #include <iostream> #include <vector> #include <assert.h> template<class T> //object in pool mush have a Clear() function class TATObjectPool { public: TATObjectPool(int maxSize):m_MaxSize(maxSize) { assert(maxSize > 0); m_Objects = new T[maxSize]; m_UsedMap = new bool[maxSize]; TAT_MEMSET_NEW(m_UsedMap, maxSize, false); m_NextUnused = 0; m_UsedCount = 0; } TATObjectPool() {} void Initialize(int max_sz) { assert(max_sz > 0); m_Objects = new T[max_sz]; m_UsedMap = new bool[max_sz]; TAT_MEMSET_NEW(m_UsedMap, max_sz, false); m_NextUnused = 0; m_UsedCount = 0; } ~TATObjectPool() { delete m_Objects; delete m_UsedMap; m_UsedObjects.clear(); } T* FetchUnused() { int index = -1; if (m_UsedCount >= m_MaxSize) return 0; if (!m_UsedMap[m_NextUnused]) { index = m_NextUnused; } else { for (int i = 0; i < m_MaxSize; i++) { if (!m_UsedMap[i]) { index = i; } } } if (index < m_MaxSize && 0 <= index) { m_UsedMap[index] = true; m_NextUnused++; _Clamp(m_NextUnused, 0, m_MaxSize - 1); m_Objects[index].Clear(); m_UsedCount++; m_Objects[index].m_IndexInPool = index; m_UsedObjects.push_back(&m_Objects[index]); return &m_Objects[index]; } return 0; } void ReturnUsed(T*& obj) { typename std::vector<T*>::iterator it = m_UsedObjects.begin(); while (it != m_UsedObjects.end()) { if((*it) == obj) it = m_UsedObjects.erase(it); else it++; } int index = obj->m_IndexInPool; if (&m_Objects[index] == obj) { m_NextUnused = index; m_UsedMap[index] = false; m_UsedCount--; obj = 0; return; } delete obj; obj = 0; } void ReturnUsed(int index) { typename std::vector<T*>::iterator it = m_UsedObjects.begin(); for (it; it != m_UsedObjects.end(); it++) { if (*it == &m_Objects[index]) m_UsedObjects.erase(it); } m_NextUnused = index; m_UsedMap[index] = false; m_UsedCount--; m_Objects[index].Clear(); return; } void Clear() { for (int i = 0; i < m_UsedObjects.size(); ++i) { m_UsedObjects[i]->Clear(); } m_UsedObjects.clear(); m_UsedCount = 0; TAT_MEMSET_NEW(m_UsedMap, m_MaxSize, false); m_NextUnused = 0; } const std::vector<T*>& FetchAllUsed() { return m_UsedObjects; } T* GetPool() { return m_Objects; } T& operator[](int index) { return m_Objects[index]; } protected: T* m_Objects; int m_NextUnused; bool* m_UsedMap; int m_MaxSize; int m_UsedCount; std::vector<T*> m_UsedObjects; };
bf542f6efd4e277406cd1a26947369dccf876226
c252f753c1090c247ff118213a6d7d1aaf6396ca
/Boss.h
8723c7cb3457ed08cd0bed2d282727675e0c5f6d
[]
no_license
CoopperGuy/1945
d7f44788ecb6071f5ed3661e9afa9c349064e672
6c848efd3f5b3b54bcb685bdbb8b22c42dffeff2
refs/heads/main
2023-06-23T05:24:55.646442
2021-07-13T11:34:31
2021-07-13T11:34:31
383,678,340
0
0
null
null
null
null
UTF-8
C++
false
false
711
h
Boss.h
#pragma once #ifndef __CBOSS_H__ #define __CBOSS_H__ #include "Monster.h" class CBoss : public CMonster { enum PATTERN {P_ATTACK,P_ATTACK2_,P_MOVE,P_MOVEATK,P_END}; public: CBoss(); virtual ~CBoss(); public: virtual HRESULT Initialize() override; virtual void Ready() override; virtual int Update() override; virtual void Late_Update() override; virtual void Render(HDC _DC) override; virtual void Release() override; public: void Attack_First(); void Attack_Second(); void BossMove(); void BossMoveAttack(); private: DWORD m_PatternTime; DWORD m_PateernDelay; float m_fAngle = 0.f; float m_MoveAngle = 0.f; bool m_bPatternEnd = false; PATTERN m_ePattern = P_END; }; #endif //__CBOSS_H__
31f8986ef1f719ef38e306da405af106922012f8
2c5d8839db951f78c33a5c152cec17bfc865f413
/Source.cpp
f6912a0b628fc53cbd0acf3b85c20a3582b499ca
[]
no_license
Aleks1y/ooop_lab3
77104cc503dbeeb53f0ac408989289d41f990d18
aee6cd69e22675a4e010144d7b06f77dd9a29506
refs/heads/main
2023-02-12T00:44:32.552264
2021-01-10T10:03:29
2021-01-10T10:03:29
324,604,973
0
0
null
null
null
null
UTF-8
C++
false
false
13,763
cpp
Source.cpp
#include "Header.h" void Player::SetShip(int x, int y, bool horizontal, ShipType type) { int length = (int)type; if (horizontal) for (int i = 0; i < length; ++i) field[y][x + i] = PLAYER_SHIP; else for (int i = 0; i < length; ++i) field[y + i][x] = PLAYER_SHIP; } bool Player::isGoodShip(int x, int y, bool horizontal, ShipType type) { int length = (int)type; for (size_t k = 0; k < length; k++) { for (int i = -1; i < 2; i++) { if (y + i < 10 && y + i >= 0) { for (int j = -1; j < 2; j++) { if (x + j < 10 && x + j >= 0 && field[y + i][x + j] != EMPTY_FIELD) { return false; } } } } x += (int)horizontal; y += (int)(!horizontal); if (x > 9 || y > 9) return false; } return true; } void Player::SetSuccessOnLastStep(bool val) { successOnLastStep = val; } void Player::SetDestroyShipOnLast(bool val) { destroyShipOnLast = val; } shared_ptr<Player> Player::createPlayer(PlayerType type) { switch (type) { case Random: return make_shared<RandomPlayer>(); case Optimal: return make_shared<OptimalPlayer>(); case Interactive: return make_shared<ConsolePlayer>(); } } void Player::FillFieldRandom() { bool ishorizontal; int x, y; do { ishorizontal = (rand() % 2); x = rand() % 10; y = rand() % 10; }while (!isGoodShip(x, y, ishorizontal, ShipType::four)); SetShip(x, y, ishorizontal, ShipType::four); for (int i = 0; i < 2; ++i) { do { ishorizontal = (rand() % 2); x = rand() % 10; y = rand() % 10; } while (!isGoodShip(x, y, ishorizontal, ShipType::three)); SetShip(x, y, ishorizontal, ShipType::three); } for (int i = 0; i < 3; ++i) { do { ishorizontal = (rand() % 2); x = rand() % 10; y = rand() % 10; } while (!isGoodShip(x, y, ishorizontal, ShipType::two)); SetShip(x, y, ishorizontal, ShipType::two); } for (int i = 0; i < 4; ++i) { do { ishorizontal = (rand() % 2); x = rand() % 10; y = rand() % 10; } while (!isGoodShip(x, y, ishorizontal, ShipType::one)); SetShip(x, y, ishorizontal, ShipType::one); } } void Player::FillField() { bool ishorizontal; int x, y; do { cout << "Enter information about four decked ship (int x, int y, bool ishorizontal)"; cin >> x >> y >> ishorizontal; } while (!isGoodShip(x, y, ishorizontal, ShipType::four)); SetShip(x - 1, y - 1, ishorizontal, ShipType::four); for (int i = 0; i < 2; ++i) { do { cout << "Enter information about #" << i + 1 << " three decked ship (int x, int y, bool ishorizontal)"; cin >> x >> y >> ishorizontal; } while (!isGoodShip(x - 1, y - 1, ishorizontal, ShipType::three)); SetShip(x - 1, y - 1, ishorizontal, ShipType::three); } for (int i = 0; i < 3; ++i) { do { cout << "Enter information about #" << i + 1 << " two decked ship (int x, int y, bool ishorizontal)"; cin >> x >> y >> ishorizontal; } while (!isGoodShip(x - 1, y - 1, ishorizontal, ShipType::two)); SetShip(x - 1, y - 1, ishorizontal, ShipType::two); } for (int i = 0; i < 4; ++i) { do { cout << "Enter information about #" << i + 1 << " one decked ship (int x, int y, bool ishorizontal)"; cin >> x >> y >> ishorizontal; } while (!isGoodShip(x - 1, y - 1, ishorizontal, ShipType::one)); SetShip(x - 1, y - 1, ishorizontal, ShipType::one); } } Coord ConsolePlayer::nextStep() { cout << "Enter int x int y" << endl; int x, y; cin >> x >> y; return { x - 1, y - 1 }; } ConsolePlayer::ConsolePlayer() { string str; do { cout << "Do you want to set the ships random? yes/no \n"; cin >> str; } while (str != "yes" && str != "no"); if (str == "yes") FillFieldRandom(); else FillField(); } Coord RandomPlayer::nextStep() { int x = rand() % 10; int y = rand() % 10; return { x, y }; } RandomPlayer::RandomPlayer() { FillFieldRandom(); } Coord OptimalPlayer::strategyFire() { if (diag0 < 10) { lastPoint = { diag0, diag0 }; diag0++; return lastPoint; } else if (diag1 < 10) { lastPoint = { 9 - diag1, diag1 }; diag1++; return lastPoint; } else if (diag2 < 10) { lastPoint = { 4, diag2 }; diag2++; return lastPoint; } else if (diag3 < 10) { lastPoint = { diag3, 5 }; diag3++; return lastPoint; } else { lastPoint = { rand() % 10, rand() % 10 }; return lastPoint; } } Coord OptimalPlayer::nextStep() { if (!successOnLastStep && lastSuccessPoints.empty()) return strategyFire(); else if (!successOnLastStep && !lastSuccessPoints.empty()) { while (lastSuccessPoints.size() > 1) { lastSuccessPoints.pop_back(); } vectorFire = (vectorFire + 1) % 4; } else if (destroyShipOnLast) { lastSuccessPoints.clear(); vectorFire = 0; return strategyFire(); } else if (successOnLastStep) lastSuccessPoints.push_back(lastPoint); switch (vectorFire) { case 0: lastPoint = { lastSuccessPoints[lastSuccessPoints.size() - 1].first + 1, lastSuccessPoints[lastSuccessPoints.size() - 1].second }; break; case 1: lastPoint = {lastSuccessPoints[lastSuccessPoints.size() - 1].first - 1, lastSuccessPoints[lastSuccessPoints.size() - 1].second}; break; case 2: lastPoint = { lastSuccessPoints[lastSuccessPoints.size() - 1].first, lastSuccessPoints[lastSuccessPoints.size() - 1].second + 1 }; break; case 3: lastPoint = { lastSuccessPoints[lastSuccessPoints.size() - 1].first, lastSuccessPoints[lastSuccessPoints.size() - 1].second - 1 }; break; } return lastPoint; } OptimalPlayer::OptimalPlayer() { FillFieldRandom(); } size_t Judge::GetPlayerDestroyed(bool isFirst) { return isFirst ? player1destroyed : player2destroyed; } void Judge::IncPlayerDestroyed(bool isFirst) { isFirst ? player1destroyed++ : player2destroyed++; } bool Judge::isGoodField(const int (&field)[10][10]) { size_t emptySquares = 0, countOne = 0, countTwo = 0, countThree = 0, countFour = 0; for (int i = 0; i < 10; i++) { for (int j = 0; j < 10; j++) { if (field[i][j] == PLAYER_SHIP) { if (!(i - 1 >= 0 && field[i - 1][j] == PLAYER_SHIP) && !(j - 1 >= 0 && field[i][j - 1] == PLAYER_SHIP)) { size_t length = 1, vectorY = 0, vectorX = 0; if (i + 1 < 10 && field[i + 1][j] == PLAYER_SHIP) vectorY = 1; else vectorX = 1; while (i + vectorY < 10 && j + vectorX < 10 && field[i + vectorY][j + vectorX] == PLAYER_SHIP) { length++; vectorY ? vectorY++ : vectorX++; } if (length == 1) countOne++; else if (length == 2) countTwo++; else if (length == 3) countThree++; else if (length == 4) countFour++; else return false; } } else { emptySquares++; } } } if (countOne == 4 && countTwo == 3 && countThree == 2 && countFour == 1 && emptySquares == (100 - 4 - 3 * 2 - 2 * 3 - 4)) return true; return false; } bool Judge::isGoodStep(int x, int y, bool isFirst) { if (x < 0 || y < 0 || x > 9 || y > 9) return false; if(FIELD[y][x] < 0 || FIELD[y][x] > 1) return false; return true; } int Judge::step(int x, int y, bool isFirst) { if (FIELD[y][x] == EMPTY_FIELD) { FIELD[y][x] = MISSED; return MISSED; } if (FIELD[y][x] == PLAYER_SHIP) { FIELD[y][x] = DAMAGED; for (int i = 1; y - i > -1 && (isFirst ? field2 : field1)[y - i][x] > 0; i++) { if (FIELD[y - i][x] == PLAYER_SHIP) return DAMAGED; } for (int i = 1; y + i < 10 && FIELD[y + i][x] > 0; i++) { if (FIELD[y + i][x] == PLAYER_SHIP) return DAMAGED; } for (int i = 1; x - i > -1 && FIELD[y][x - i] > 0; i++) { if (FIELD[y][x - i] == PLAYER_SHIP) return DAMAGED; } for (int i = 1; x + i < 10 && FIELD[y][x + i] > 0; i++) { if (FIELD[y][x + i] == PLAYER_SHIP) return DAMAGED; } int vectorY = 0, vectorX = 0; if (y - 1 >= 0 && FIELD[y - 1][x] == DAMAGED) vectorY = -1; else if (y + 1 < 10 && FIELD[y + 1][x] == DAMAGED) vectorY = 1; else if (x - 1 >= 0 && FIELD[y][x - 1] == DAMAGED) vectorX = -1; else if (x + 1 < 10 && FIELD[y][x + 1] == DAMAGED) vectorX = 1; do { for (int i = -1; i < 2; i++) { if (y + i < 10 && y + i >= 0) { for (int j = -1; j < 2; j++) { if (x + j < 10 && x + j >= 0 && FIELD[y + i][x + j] == EMPTY_FIELD) { FIELD[y + i][x + j] = MISSED; } } } } y += vectorY; x += vectorX; } while ((vectorY != 0 || vectorX != 0) && y < 10 && x < 10 && y >= 0 && x >= 0 && FIELD[y][x] == DAMAGED); return DESTROYED; } } Judge::Judge(shared_ptr<Player> player1, shared_ptr<Player> player2) { for (size_t i = 0; i < 10; i++) { for (size_t j = 0; j < 10; j++) { field1[i][j] = player1->field[i][j]; field2[i][j] = player2->field[i][j]; } } if (!isGoodField(field1) || !isGoodField(field2)) throw("Bad field"); } void execute(int rounds, PlayerType firstType, PlayerType secondType) { srand(time(NULL)); int scoreFirst = 0; int scoreSecond = 0; for (size_t i = 0; i < rounds; i++) { shared_ptr<Player> first = Player::createPlayer(firstType); shared_ptr<Player> second = Player::createPlayer(secondType); Judge judge(first, second); bool motion = 1; while (judge.GetPlayerDestroyed(1) != 10 && judge.GetPlayerDestroyed(0) != 10) { Coord step; do { step = (motion ? first : second)->nextStep(); if (!judge.isGoodStep(step.first, step.second, motion)) { (motion ? first : second)->SetSuccessOnLastStep(0); continue; } break; } while (true); switch (judge.step(step.first, step.second, motion)) { case MISSED: (motion ? first : second)->SetSuccessOnLastStep(0); (motion ? first : second)->SetDestroyShipOnLast(0); cout << (motion ? "First player missed" : "Second player missed") << endl; motion ? motion = false : motion = true; break; case DAMAGED: (motion ? first : second)->SetSuccessOnLastStep(1); (motion ? first : second)->SetDestroyShipOnLast(0); cout << (motion ? "First player damaged" : "Second player damaged") << endl; break; case DESTROYED: (motion ? first : second)->SetSuccessOnLastStep(1); (motion ? first : second)->SetDestroyShipOnLast(1); judge.IncPlayerDestroyed(motion); cout << (motion ? "First player destroyed" : "Second player destroyed") << endl; break; } } if (judge.GetPlayerDestroyed(1) == 10) scoreFirst++; else scoreSecond++; cout << "First player score: " << scoreFirst << endl; cout << "Second player score: " << scoreSecond << endl; } if (scoreFirst > scoreSecond) cout << "The First player wins"; else if (scoreFirst < scoreSecond) cout << "The Second player wins"; else cout << "Equal points"; }
0c88e255dad47fc5a35df10c90035b460b4d7a4e
3530f022141b88e1c5b979dddd86a8cbadc37846
/Array/US/268.missing-number.cpp
f9f8ff49d63370970e4bc92b6fad05ac748f0802
[]
no_license
stinkycats/LeetcodeSolution
3a60a1634441a09255bc72495492ee8c12b5ffe0
2a5656498307e4ee0a25cbaccbc122ba987d3990
refs/heads/master
2023-01-23T08:47:23.952581
2020-11-15T13:10:47
2020-11-15T13:10:47
302,892,396
0
0
null
null
null
null
UTF-8
C++
false
false
619
cpp
268.missing-number.cpp
/* * @lc app=leetcode id=268 lang=cpp * * [268] Missing Number */ // @lc code=start class Solution { public: int missingNumber(vector<int>& nums) { unordered_map<int,int> imap; //initalize first map for(int i=0;i<nums.size()+1;i++) imap[i]=0; //make the exist number location to one for(int i=0;i<nums.size();i++) imap[nums[i]]++; //get result int result; for(int i=0;i<imap.size();i++) if(imap[i]==0) result=i; return result; } }; // @lc code=end
28c97183edcb41f9f17fb48e220c47923c6e78bb
6f49cc2d5112a6b97f82e7828f59b201ea7ec7b9
/apiwdbe/WdbeQPplPpl1NSegment.h
c5be6fdcfc2aee130a78f05970cbe43818616488
[ "MIT" ]
permissive
mpsitech/wdbe-WhizniumDBE
d3702800d6e5510e41805d105228d8dd8b251d7a
89ef36b4c86384429f1e707e5fa635f643e81240
refs/heads/master
2022-09-28T10:27:03.683192
2022-09-18T22:04:37
2022-09-18T22:04:37
282,705,449
5
0
null
null
null
null
UTF-8
C++
false
false
1,120
h
WdbeQPplPpl1NSegment.h
/** * \file WdbeQPplPpl1NSegment.h * API code for table TblWdbeQPplPpl1NSegment (declarations) * \copyright (C) 2016-2020 MPSI Technologies GmbH * \author Alexander Wirthmueller (auto-generation) * \date created: 26 Aug 2021 */ // IP header --- ABOVE #ifndef WDBEQPPLPPL1NSEGMENT_H #define WDBEQPPLPPL1NSEGMENT_H #include <sbecore/Xmlio.h> /** * WdbeQPplPpl1NSegment */ class WdbeQPplPpl1NSegment { public: WdbeQPplPpl1NSegment(const Sbecore::uint jnum = 0, const std::string stubRef = ""); public: Sbecore::uint jnum; std::string stubRef; public: bool readXML(xmlXPathContext* docctx, std::string basexpath = "", bool addbasetag = false); }; /** * ListWdbeQPplPpl1NSegment */ class ListWdbeQPplPpl1NSegment { public: ListWdbeQPplPpl1NSegment(); ListWdbeQPplPpl1NSegment(const ListWdbeQPplPpl1NSegment& src); ListWdbeQPplPpl1NSegment& operator=(const ListWdbeQPplPpl1NSegment& src); ~ListWdbeQPplPpl1NSegment(); void clear(); public: std::vector<WdbeQPplPpl1NSegment*> nodes; public: bool readXML(xmlXPathContext* docctx, std::string basexpath = "", bool addbasetag = false); }; #endif
79e3ed64aca82add61a65edcf6ad81ac0a883487
c3c848ae6c90313fed11be129187234e487c5f96
/VC6PLATSDK/samples/Com/Fundamentals/TutSamp/AptServe/Factory.Cpp
56f8211bb94f0deb0a1e084943040904b9ccc24e
[ "LicenseRef-scancode-warranty-disclaimer" ]
no_license
timxx/VC6-Platform-SDK
247e117cfe77109cd1b1effcd68e8a428ebe40f0
9fd59ed5e8e25a1a72652b44cbefb433c62b1c0f
refs/heads/master
2023-07-04T06:48:32.683084
2021-08-10T12:52:47
2021-08-10T12:52:47
null
0
0
null
null
null
null
UTF-8
C++
false
false
46,182
cpp
Factory.Cpp
/*+========================================================================== File: FACTORY.CPP Summary: Implementation file for the ClassFactories of the APTSERVE server. This server provides several Car-related COM Components: Car, UtilityCar, and CruiseCar. For each of these components, IClassFactory is implemented in appropriate ClassFactory COM objects: CFCar, CFUtilityCar, and CFCruiseCar. The COM Components that can be manufactured by this server are known outside the server by their respective CLSIDs: CLSID_AptCar, CLSID_AptUtilityCar, and CLSID_AptCruiseCar. For a comprehensive tutorial code tour of this module's contents and offerings see the tutorial APTSERVE.HTM file. For more specific technical details on the internal workings see the comments dispersed throughout the module's source code. Classes: CFCar, CFUtilityCar, CFCruiseCar Functions: . Origin: 3-20-96: atrent - Editor-inheritance from CAR.CPP in the LOCSERVE Tutorial Code Sample. ---------------------------------------------------------------------------- This file is part of the Microsoft COM Tutorial Code Samples. Copyright (C) 1995 - 2000 Microsoft Corporation. All rights reserved. This source code is intended only as a supplement to Microsoft Development Tools and/or on-line documentation. See these other materials for detailed information regarding Microsoft code samples. THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE. ==========================================================================+*/ /*--------------------------------------------------------------------------- We include WINDOWS.H for all Win32 applications. We include OLE2.H because we will be calling the COM/OLE Libraries. We include APPUTIL.H because we will be building this DLL using the convenient Virtual Window and Dialog classes and other utility functions in the APPUTIL Library (ie, APPUTIL.LIB). We include MICARS.H and CARGUIDS.H for the common car-related Interface class, GUID, and CLSID specifications. We include SERVER.H because it has the necessary internal class and resource definitions for this DLL. We include FACTORY.H because it has the necessary internal class factory declarations for this DLL component server. Those factories we will be implementing in this module. We include CAR.H, UTILCAR,H, and, CRUCAR.H for the object class declarations for the COCar, COUtilityCar, and COCruiseCar COM objects. ---------------------------------------------------------------------------*/ #include <windows.h> #include <ole2.h> #include <apputil.h> #include <micars.h> #include <carguids.h> #include "server.h" #include "factory.h" #include "car.h" #include "utilcar.h" #include "crucar.h" /*--------------------------------------------------------------------------- Implementation the CFCar Class Factory. CFCar is the COM object class for the Class Factory that can manufacture COCar COM Components. ---------------------------------------------------------------------------*/ /*M+M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M Method: CFCar::CFCar Summary: CFCar Constructor. Note the member initializer: "m_ImpIClassFactory(this, pUnkOuter, pServer)" which is used to pass the 'this', pUnkOuter, and pServer pointers of this constructor function to the constructor executed in the instantiation of the CImpIClassFactory interface whose implementation is nested inside this present object class. Args: IUnknown* pUnkOuter, Pointer to the the outer Unknown. NULL means this COM Object is not being Aggregated. Non NULL means it is being created on behalf of an outside COM object that is reusing it via aggregation. CServer* pServer) Pointer to the server's control object. Modifies: m_cRefs, m_pUnkOuter. Returns: void M---M---M---M---M---M---M---M---M---M---M---M---M---M---M---M---M---M---M-M*/ CFCar::CFCar( IUnknown* pUnkOuter, CServer* pServer) : m_ImpIClassFactory(this, pUnkOuter, pServer) { // Zero the COM object's reference count. m_cRefs = 0; // No AddRef necessary if non-NULL, as we're nested. m_pUnkOuter = pUnkOuter; // Init the pointer to the server control object. m_pServer = pServer; LOGF2("L<%X>: CFCar Constructor. m_pUnkOuter=0x%X.",TID,m_pUnkOuter); return; } /*M+M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M Method: CFCar::~CFCar Summary: CFCar Destructor. Args: void Returns: void M---M---M---M---M---M---M---M---M---M---M---M---M---M---M---M---M---M---M-M*/ CFCar::~CFCar(void) { LOGF1("L<%X>: CFCar::Destructor.",TID); return; } /*M+M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M Method: CFCar::QueryInterface Summary: QueryInterface of the CFCar non-delegating IUnknown implementation. Args: REFIID riid, [in] GUID of the Interface being requested. PPVOID ppv) [out] Address of the caller's pointer variable that will receive the requested interface pointer. Returns: HRESULT Standard result code. NOERROR for success. M---M---M---M---M---M---M---M---M---M---M---M---M---M---M---M---M---M---M-M*/ STDMETHODIMP CFCar::QueryInterface( REFIID riid, PPVOID ppv) { HRESULT hr = E_NOINTERFACE; *ppv = NULL; if (IID_IUnknown == riid) { *ppv = this; LOGF1("L<%X>: CFCar::QueryInterface. 'this' pIUnknown returned.",TID); } else if (IID_IClassFactory == riid) { *ppv = &m_ImpIClassFactory; LOGF1("L<%X>: CFCar::QueryInterface. pIClassFactory returned.",TID); } if (NULL != *ppv) { // We've handed out a pointer to the interface so obey the COM rules // and AddRef the reference count. ((LPUNKNOWN)*ppv)->AddRef(); hr = NOERROR; } return (hr); } /*M+M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M Method: CFCar::AddRef Summary: AddRef of the CFCar non-delegating IUnknown implementation. Args: void Modifies: m_cRefs. Returns: ULONG New value of m_cRefs (COM object's reference count). M---M---M---M---M---M---M---M---M---M---M---M---M---M---M---M---M---M---M-M*/ STDMETHODIMP_(ULONG) CFCar::AddRef(void) { InterlockedIncrement((PLONG) &m_cRefs); LOGF2("L<%X>: CFCar::AddRef. New cRefs=%i.",TID,m_cRefs); return m_cRefs; } /*M+M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M Method: CFCar::Release Summary: Release of the CFCar non-delegating IUnknown implementation. Args: void Modifies: m_cRefs. Returns: ULONG New value of m_cRefs (COM object's reference count). M---M---M---M---M---M---M---M---M---M---M---M---M---M---M---M---M---M---M-M*/ STDMETHODIMP_(ULONG) CFCar::Release(void) { ULONG cRefs; InterlockedDecrement((PLONG) &m_cRefs); cRefs = m_cRefs; LOGF2("L<%X>: CFCar::Release. New cRefs=%i.",TID,m_cRefs); if (0 == m_cRefs) { // We artificially bump the main ref count to prevent reentrancy // via the main object destructor. Not really needed in this // CFCar but a good practice because we are aggregatable and // may at some point in the future add something entertaining like // some Releases to the CFCar destructor. InterlockedIncrement((PLONG) &m_cRefs); delete this; } return cRefs; } /*--------------------------------------------------------------------------- CFCar's nested implementation of the IClassFactory interface including Constructor, Destructor, QueryInterface, AddRef, Release, CreateInstance, and LockServer methods. ---------------------------------------------------------------------------*/ /*M+M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M Method: CFCar::CImpIClassFactory::CImpIClassFactory Summary: Constructor for the CImpIClassFactory interface instantiation. Args: CFCar* pBackObj, Back pointer to the parent outer object. IUnknown* pUnkOuter, Pointer to the outer Unknown. For delegation. CServer* pServer) Pointer to the server's control object. Modifies: m_cRefI, m_pBackObj, m_pUnkOuter, m_pServer. Returns: void M---M---M---M---M---M---M---M---M---M---M---M---M---M---M---M---M---M---M-M*/ CFCar::CImpIClassFactory::CImpIClassFactory( CFCar* pBackObj, IUnknown* pUnkOuter, CServer* pServer) { // Init the Interface Ref Count (used for debugging only). m_cRefI = 0; // Init the Back Object Pointer to point to the parent object. m_pBackObj = pBackObj; // Init the pointer to the server control object. m_pServer = pServer; // Init the CImpIClassFactory interface's delegating Unknown pointer. // We use the Back Object pointer for IUnknown delegation here if we are // not being aggregated. If we are being aggregated we use the supplied // pUnkOuter for IUnknown delegation. In either case the pointer // assignment requires no AddRef because the CImpIClassFactory lifetime is // quaranteed by the lifetime of the parent object in which // CImpIClassFactory is nested. if (NULL == pUnkOuter) { m_pUnkOuter = pBackObj; LOGF1("L<%X>: CFCar::CImpIClassFactory Constructor. Non-Aggregating.",TID); } else { m_pUnkOuter = pUnkOuter; LOGF1("L<%X>: CFCar::CImpIClassFactory Constructor. Aggregating.",TID); } return; } /*M+M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M Method: CFCar::CImpIClassFactory::~CImpIClassFactory Summary: Destructor for the CImpIClassFactory interface instantiation. Args: void Returns: void M---M---M---M---M---M---M---M---M---M---M---M---M---M---M---M---M---M---M-M*/ CFCar::CImpIClassFactory::~CImpIClassFactory(void) { LOGF1("L<%X>: CFCar::CImpIClassFactory Destructor.",TID); return; } /*M+M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M Method: CFCar::CImpIClassFactory::QueryInterface Summary: The QueryInterface IUnknown member of this IClassFactory interface implementation that delegates to m_pUnkOuter, whatever it is. Args: REFIID riid, [in] GUID of the Interface being requested. PPVOID ppv) [out] Address of the caller's pointer variable that will receive the requested interface pointer. Returns: HRESULT Standard result code. NOERROR for success. Returned by the delegated outer QueryInterface call. M---M---M---M---M---M---M---M---M---M---M---M---M---M---M---M---M---M---M-M*/ STDMETHODIMP CFCar::CImpIClassFactory::QueryInterface( REFIID riid, PPVOID ppv) { LOGF1("L<%X>: CFCar::CImpIClassFactory::QueryInterface. Delegating.",TID); // Delegate this call to the outer object's QueryInterface. return m_pUnkOuter->QueryInterface(riid, ppv); } /*M+M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M Method: CFCar::CImpIClassFactory::AddRef Summary: The AddRef IUnknown member of this IClassFactory interface implementation that delegates to m_pUnkOuter, whatever it is. Args: void Modifies: m_cRefI. Returns: ULONG Returned by the delegated outer AddRef call. M---M---M---M---M---M---M---M---M---M---M---M---M---M---M---M---M---M---M-M*/ STDMETHODIMP_(ULONG) CFCar::CImpIClassFactory::AddRef(void) { // Increment the Interface Reference Count. InterlockedIncrement((PLONG) &m_cRefI); LOGF2("L<%X>: CFCar::CImpIClassFactory::Addref. Delegating. New cI=%i.",TID,m_cRefI); // Delegate this call to the outer object's AddRef. return m_pUnkOuter->AddRef(); } /*M+M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M Method: CFCar::CImpIClassFactory::Release Summary: The Release IUnknown member of this IClassFactory interface implementation that delegates to m_pUnkOuter, whatever it is. Args: void Returns: ULONG Returned by the delegated outer Release call. M---M---M---M---M---M---M---M---M---M---M---M---M---M---M---M---M---M---M-M*/ STDMETHODIMP_(ULONG) CFCar::CImpIClassFactory::Release(void) { // Decrement the Interface Reference Count. InterlockedDecrement((PLONG) &m_cRefI); LOGF2("L<%X>: CFCar::CImpIClassFactory::Release. Delegating. New cI=%i.",TID,m_cRefI); // Delegate this call to the outer object's Release. return m_pUnkOuter->Release(); } /*M+M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M Method: CFCar::CImpIClassFactory::CreateInstance Summary: The CreateInstance member method of this IClassFactory interface implementation. Creates an instance of the COCar COM component. Args: IUnknown* pUnkOuter, [in] Pointer to the controlling IUnknown. REFIID riid, [in] GUID of the Interface being requested. PPVOID ppvCob) [out] Address of the caller's pointer variable that will receive the requested interface pointer. Returns: HRESULT Standard result code. NOERROR for success. M---M---M---M---M---M---M---M---M---M---M---M---M---M---M---M---M---M---M-M*/ STDMETHODIMP CFCar::CImpIClassFactory::CreateInstance( IUnknown* pUnkOuter, REFIID riid, PPVOID ppv) { HRESULT hr = E_FAIL; COCar* pCob = NULL; LOGF2("L<%X>: CFCar::CImpIClassFactory::CreateInstance. pUnkOuter=0x%X.",TID,pUnkOuter); // NULL the output pointer. *ppv = NULL; // If the creation call is requesting aggregation (pUnkOuter != NULL), // the COM rules state the IUnknown interface MUST also be concomitantly // requested. If it is not so requested (riid != IID_IUnknown) then // an error must be returned indicating that no aggregate creation of // the CFCar COM Object can be performed. if (NULL != pUnkOuter && riid != IID_IUnknown) hr = CLASS_E_NOAGGREGATION; else { // Instantiate a COCar COM Object. pCob = new COCar(pUnkOuter, m_pServer); if (NULL != pCob) { // We initially created the new COM object so tell the server // to increment its global server object count to help ensure // that the server remains loaded until this partial creation // of a COM component is completed. m_pServer->ObjectsUp(); // We QueryInterface this new COM Object not only to deposit the // main interface pointer to the caller's pointer variable, but to // also automatically bump the Reference Count on the new COM // Object after handing out this reference to it. hr = pCob->QueryInterface(riid, (PPVOID)ppv); if (FAILED(hr)) { delete pCob; m_pServer->ObjectsDown(); } } else { // If we were launched to create this object and could not then // we should force a shutdown of this server. m_pServer->ObjectsUp(); m_pServer->ObjectsDown(); hr = E_OUTOFMEMORY; } } if (SUCCEEDED(hr)) { LOGF2("L<%X>: CFCar::CImpIClassFactory::CreateInstance Succeeded. *ppv=0x%X.",TID,*ppv); } else { LOGF1("L<%X>: CFCar::CImpIClassFactory::CreateInstance Failed.",TID); } return hr; } /*M+M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M Method: CFCar::CImpIClassFactory::LockServer Summary: The LockServer member method of this IClassFactory interface implementation. Args: BOOL fLock) [in] Flag determining whether to Lock or Unlock the server. Returns: HRESULT Standard result code. NOERROR for success. M---M---M---M---M---M---M---M---M---M---M---M---M---M---M---M---M---M---M-M*/ STDMETHODIMP CFCar::CImpIClassFactory::LockServer( BOOL fLock) { HRESULT hr = NOERROR; LOGF1("L<%X>: CFCar::CImpIClassFactory::LockServer.",TID); if (fLock) m_pServer->Lock(); else m_pServer->Unlock(); return hr; } /*--------------------------------------------------------------------------- Implementation the CFUtilityCar Class Factory. CFUtilityCar is the COM object class for the Class Factory that can manufacture COUtilityCar COM Components. ---------------------------------------------------------------------------*/ /*M+M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M Method: CFUtilityCar::CFUtilityCar Summary: CFUtilityCar Constructor. Note the member initializer: "m_ImpIClassFactory(this, pUnkOuter, pServer)" which is used to pass the 'this', pUnkOuter, and pServer pointers of this constructor function to the constructor executed in the instantiation of the CImpIClassFactory interface whose implementation is nested inside this present object class. Args: IUnknown* pUnkOuter, Pointer to the the outer Unknown. NULL means this COM Object is not being Aggregated. Non NULL means it is being created on behalf of an outside COM object that is reusing it via aggregation. CServer* pServer) Pointer to the server's control object. Modifies: m_cRefs, m_pUnkOuter. Returns: void M---M---M---M---M---M---M---M---M---M---M---M---M---M---M---M---M---M---M-M*/ CFUtilityCar::CFUtilityCar( IUnknown* pUnkOuter, CServer* pServer) : m_ImpIClassFactory(this, pUnkOuter, pServer) { // Zero the COM object's reference count. m_cRefs = 0; // No AddRef necessary if non-NULL, as we're nested. m_pUnkOuter = pUnkOuter; // Init the pointer to the server control object. m_pServer = pServer; LOGF2("L<%X>: CFUtilityCar Constructor. m_pUnkOuter=0x%X.",TID,m_pUnkOuter); return; } /*M+M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M Method: CFUtilityCar::~CFUtilityCar Summary: CFUtilityCar Destructor. Args: void Returns: void M---M---M---M---M---M---M---M---M---M---M---M---M---M---M---M---M---M---M-M*/ CFUtilityCar::~CFUtilityCar(void) { LOGF1("L<%X>: CFUtilityCar::Destructor.",TID); return; } /*M+M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M Method: CFUtilityCar::QueryInterface Summary: QueryInterface of the CFUtilityCar non-delegating IUnknown implementation. Args: REFIID riid, [in] GUID of the Interface being requested. PPVOID ppv) [out] Address of the caller's pointer variable that will receive the requested interface pointer. Returns: HRESULT Standard result code. NOERROR for success. M---M---M---M---M---M---M---M---M---M---M---M---M---M---M---M---M---M---M-M*/ STDMETHODIMP CFUtilityCar::QueryInterface( REFIID riid, PPVOID ppv) { HRESULT hr = E_NOINTERFACE; *ppv = NULL; if (IID_IUnknown == riid) { *ppv = this; LOGF1("L<%X>: CFUtilityCar::QueryInterface. 'this' pIUnknown returned.",TID); } else if (IID_IClassFactory == riid) { *ppv = &m_ImpIClassFactory; LOGF1("L<%X>: CFUtilityCar::QueryInterface. pIClassFactory returned.",TID); } if (NULL != *ppv) { // We've handed out a pointer to the interface so obey the COM rules // and AddRef the reference count. ((LPUNKNOWN)*ppv)->AddRef(); hr = NOERROR; } return (hr); } /*M+M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M Method: CFUtilityCar::AddRef Summary: AddRef of the CFUtilityCar non-delegating IUnknown implementation. Args: void Modifies: m_cRefs. Returns: ULONG New value of m_cRefs (COM object's reference count). M---M---M---M---M---M---M---M---M---M---M---M---M---M---M---M---M---M---M-M*/ STDMETHODIMP_(ULONG) CFUtilityCar::AddRef(void) { InterlockedIncrement((PLONG) &m_cRefs); LOGF2("L<%X>: CFUtilityCar::AddRef. New cRefs=%i.",TID,m_cRefs); return m_cRefs; } /*M+M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M Method: CFUtilityCar::Release Summary: Release of the CFUtilityCar non-delegating IUnknown implementation. Args: void Modifies: m_cRefs. Returns: ULONG New value of m_cRefs (COM object's reference count). M---M---M---M---M---M---M---M---M---M---M---M---M---M---M---M---M---M---M-M*/ STDMETHODIMP_(ULONG) CFUtilityCar::Release(void) { ULONG cRefs; InterlockedDecrement((PLONG) &m_cRefs); cRefs = m_cRefs; LOGF2("L<%X>: CFUtilityCar::Release. New cRefs=%i.",TID,m_cRefs); if (0 == m_cRefs) { // We artificially bump the main ref count to prevent reentrancy // via the main object destructor. Not really needed in this // CFUtilityCar but a good practice because we are aggregatable and // may at some point in the future add something entertaining like // some Releases to the CFUtilityCar destructor. InterlockedIncrement((PLONG) &m_cRefs); delete this; } return cRefs; } /*--------------------------------------------------------------------------- CFUtilityCar's nested implementation of the IClassFactory interface including Constructor, Destructor, QueryInterface, AddRef, Release, CreateInstance, and LockServer methods. ---------------------------------------------------------------------------*/ /*M+M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M Method: CFUtilityCar::CImpIClassFactory::CImpIClassFactory Summary: Constructor for the CImpIClassFactory interface instantiation. Args: CFUtilityCar* pBackObj, Back pointer to the parent outer object. IUnknown* pUnkOuter, Pointer to the outer Unknown. For delegation. CServer* pServer) Pointer to the server's control object. Modifies: m_cRefI, m_pBackObj, m_pUnkOuter, m_pServer. Returns: void M---M---M---M---M---M---M---M---M---M---M---M---M---M---M---M---M---M---M-M*/ CFUtilityCar::CImpIClassFactory::CImpIClassFactory( CFUtilityCar* pBackObj, IUnknown* pUnkOuter, CServer* pServer) { // Init the Interface Ref Count (used for debugging only). m_cRefI = 0; // Init the Back Object Pointer to point to the parent object. m_pBackObj = pBackObj; // Init the pointer to the server control object. m_pServer = pServer; // Init the CImpIClassFactory interface's delegating Unknown pointer. // We use the Back Object pointer for IUnknown delegation here if we are // not being aggregated. If we are being aggregated we use the supplied // pUnkOuter for IUnknown delegation. In either case the pointer // assignment requires no AddRef because the CImpIClassFactory lifetime is // quaranteed by the lifetime of the parent object in which // CImpIClassFactory is nested. if (NULL == pUnkOuter) { m_pUnkOuter = pBackObj; LOGF1("L<%X>: CFUtilityCar::CImpIClassFactory Constructor. Non-Aggregating.",TID); } else { m_pUnkOuter = pUnkOuter; LOGF1("L<%X>: CFUtilityCar::CImpIClassFactory Constructor. Aggregating.",TID); } return; } /*M+M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M Method: CFUtilityCar::CImpIClassFactory::~CImpIClassFactory Summary: Destructor for the CImpIClassFactory interface instantiation. Args: void Returns: void M---M---M---M---M---M---M---M---M---M---M---M---M---M---M---M---M---M---M-M*/ CFUtilityCar::CImpIClassFactory::~CImpIClassFactory(void) { LOGF1("L<%X>: CFUtilityCar::CImpIClassFactory Destructor.",TID); return; } /*M+M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M Method: CFUtilityCar::CImpIClassFactory::QueryInterface Summary: The QueryInterface IUnknown member of this IClassFactory interface implementation that delegates to m_pUnkOuter, whatever it is. Args: REFIID riid, [in] GUID of the Interface being requested. PPVOID ppv) [out] Address of the caller's pointer variable that will receive the requested interface pointer. Returns: HRESULT Standard result code. NOERROR for success. Returned by the delegated outer QueryInterface call. M---M---M---M---M---M---M---M---M---M---M---M---M---M---M---M---M---M---M-M*/ STDMETHODIMP CFUtilityCar::CImpIClassFactory::QueryInterface( REFIID riid, PPVOID ppv) { LOGF1("L<%X>: CFUtilityCar::CImpIClassFactory::QueryInterface. Delegating.",TID); // Delegate this call to the outer object's QueryInterface. return m_pUnkOuter->QueryInterface(riid, ppv); } /*M+M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M Method: CFUtilityCar::CImpIClassFactory::AddRef Summary: The AddRef IUnknown member of this IClassFactory interface implementation that delegates to m_pUnkOuter, whatever it is. Args: void Modifies: m_cRefI. Returns: ULONG Returned by the delegated outer AddRef call. M---M---M---M---M---M---M---M---M---M---M---M---M---M---M---M---M---M---M-M*/ STDMETHODIMP_(ULONG) CFUtilityCar::CImpIClassFactory::AddRef(void) { // Increment the Interface Reference Count. InterlockedIncrement((PLONG) &m_cRefI); LOGF2("L<%X>: CFUtilityCar::CImpIClassFactory::Addref. Delegating. New cI=%i.",TID,m_cRefI); // Delegate this call to the outer object's AddRef. return m_pUnkOuter->AddRef(); } /*M+M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M Method: CFUtilityCar::CImpIClassFactory::Release Summary: The Release IUnknown member of this IClassFactory interface implementation that delegates to m_pUnkOuter, whatever it is. Args: void Modifies: m_cRefI. Returns: ULONG Returned by the delegated outer Release call. M---M---M---M---M---M---M---M---M---M---M---M---M---M---M---M---M---M---M-M*/ STDMETHODIMP_(ULONG) CFUtilityCar::CImpIClassFactory::Release(void) { // Decrement the Interface Reference Count. InterlockedDecrement((PLONG) &m_cRefI); LOGF2("L<%X>: CFUtilityCar::CImpIClassFactory::Release. Delegating. New cI=%i.",TID,m_cRefI); // Delegate this call to the outer object's Release. return m_pUnkOuter->Release(); } /*M+M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M Method: CFUtilityCar::CImpIClassFactory::CreateInstance Summary: The CreateInstance member method of this IClassFactory interface implementation. Creates an instance of the COUtilityCar COM component. Args: IUnknown* pUnkOuter, [in] Pointer to the controlling IUnknown. REFIID riid, [in] GUID of the Interface being requested. PPVOID ppvCob) [out] Address of the caller's pointer variable that will receive the requested interface pointer. Returns: HRESULT Standard result code. NOERROR for success. M---M---M---M---M---M---M---M---M---M---M---M---M---M---M---M---M---M---M-M*/ STDMETHODIMP CFUtilityCar::CImpIClassFactory::CreateInstance( IUnknown* pUnkOuter, REFIID riid, PPVOID ppv) { HRESULT hr = E_FAIL; COUtilityCar* pCob = NULL; LOGF2("L<%X>: CFUtilityCar::CImpIClassFactory::CreateInstance. pUnkOuter=0x%X.",TID,pUnkOuter); // If the creation call is requesting aggregation (pUnkOuter != NULL), // the COM rules state the IUnknown interface MUST also be concomitantly // requested. If it is not so requested ( riid != IID_IUnknown) then // an error must be returned indicating that no aggregate creation of // the COUtilityCar COM Object can be performed. if (NULL != pUnkOuter && riid != IID_IUnknown) hr = CLASS_E_NOAGGREGATION; else { // Instantiate a COUtilityCar COM Object. pCob = new COUtilityCar(pUnkOuter, m_pServer); if (NULL != pCob) { // We initially created the new COM object so tell the server // to increment its global server object count to help ensure // that the server remains loaded until this partial creation // of a COM component is completed. m_pServer->ObjectsUp(); // If we have succeeded in instantiating the COM object we // initialize it to set up any subordinate objects. hr = pCob->Init(); if (SUCCEEDED(hr)) { // We QueryInterface this new COM Object not only to deposit the // main interface pointer to the caller's pointer variable, but to // also automatically bump the Reference Count on the new COM // Object after handing out this reference to it. hr = pCob->QueryInterface(riid, (PPVOID)ppv); } if (FAILED(hr)) { delete pCob; m_pServer->ObjectsDown(); } } else { // If we were launched to create this object and could not then // we should force a shutdown of this server. m_pServer->ObjectsUp(); m_pServer->ObjectsDown(); hr = E_OUTOFMEMORY; } } if (SUCCEEDED(hr)) { LOGF2("L<%X>: CFUtilityCar::CImpIClassFactory::CreateInstance Succeeded. *ppv=0x%X.",TID,*ppv); } else { LOGF1("L<%X>: CFUtilityCar::CImpIClassFactory::CreateInstance Failed.",TID); } return hr; } /*M+M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M Method: CFUtilityCar::CImpIClassFactory::LockServer Summary: The LockServer member method of this IClassFactory interface implementation. Args: BOOL fLock) [in] Flag determining whether to Lock or Unlock the server. Returns: HRESULT Standard result code. NOERROR for success. M---M---M---M---M---M---M---M---M---M---M---M---M---M---M---M---M---M---M-M*/ STDMETHODIMP CFUtilityCar::CImpIClassFactory::LockServer( BOOL fLock) { HRESULT hr = NOERROR; LOGF1("L<%X>: CFUtilityCar::CImpIClassFactory::LockServer.",TID); if (fLock) m_pServer->Lock(); else m_pServer->Unlock(); return hr; } /*--------------------------------------------------------------------------- Implementation the CFCruiseCar Class Factory. CFCruiseCar is the COM object class for the Class Factory that can manufacture COCruiseCar COM Components. ---------------------------------------------------------------------------*/ /*M+M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M Method: CFCruiseCar::CFCruiseCar Summary: CFCruiseCar Constructor. Note the member initializer: "m_ImpIClassFactory(this, pUnkOuter, pServer)" which is used to pass the 'this', pUnkOuter, and pServer pointers of this constructor function to the constructor executed in the instantiation of the CImpIClassFactory interface whose implementation is nested inside this present object class. Args: IUnknown* pUnkOuter, Pointer to the the outer Unknown. NULL means this COM Object is not being Aggregated. Non NULL means it is being created on behalf of an outside COM object that is reusing it via aggregation. CServer* pServer) Pointer to the server's control object. Modifies: m_cRefs, m_pUnkOuter, m_pServer. Returns: void M---M---M---M---M---M---M---M---M---M---M---M---M---M---M---M---M---M---M-M*/ CFCruiseCar::CFCruiseCar( IUnknown* pUnkOuter, CServer* pServer) : m_ImpIClassFactory(this, pUnkOuter, pServer) { // Zero the COM object's reference count. m_cRefs = 0; // No AddRef necessary if non-NULL, as we're nested. m_pUnkOuter = pUnkOuter; // Init the pointer to the server control object. m_pServer = pServer; LOGF2("L<%X>: CFCruiseCar Constructor. m_pUnkOuter=0x%X.",TID,m_pUnkOuter); return; } /*M+M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M Method: CFCruiseCar::~CFCruiseCar Summary: CFCruiseCar Destructor. Args: void Returns: void M---M---M---M---M---M---M---M---M---M---M---M---M---M---M---M---M---M---M-M*/ CFCruiseCar::~CFCruiseCar(void) { LOGF1("L<%X>: CFCruiseCar::Destructor.",TID); return; } /*M+M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M Method: CFCruiseCar::QueryInterface Summary: QueryInterface of the CFCruiseCar non-delegating IUnknown implementation. Args: REFIID riid, [in] GUID of the Interface being requested. PPVOID ppv) [out] Address of the caller's pointer variable that will receive the requested interface pointer. Returns: HRESULT Standard result code. NOERROR for success. M---M---M---M---M---M---M---M---M---M---M---M---M---M---M---M---M---M---M-M*/ STDMETHODIMP CFCruiseCar::QueryInterface( REFIID riid, PPVOID ppv) { HRESULT hr = E_NOINTERFACE; *ppv = NULL; if (IID_IUnknown == riid) { *ppv = this; LOGF1("L<%X>: CFCruiseCar::QueryInterface. 'this' pIUnknown returned.",TID); } else if (IID_IClassFactory == riid) { *ppv = &m_ImpIClassFactory; LOGF1("L<%X>: CFCruiseCar::QueryInterface. pIClassFactory returned.",TID); } if (NULL != *ppv) { // We've handed out a pointer to the interface so obey the COM rules // and AddRef the reference count. ((LPUNKNOWN)*ppv)->AddRef(); hr = NOERROR; } return (hr); } /*M+M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M Method: CFCruiseCar::AddRef Summary: AddRef of the CFCruiseCar non-delegating IUnknown implementation. Args: void Modifies: m_cRefs. Returns: ULONG New value of m_cRefs (COM object's reference count). M---M---M---M---M---M---M---M---M---M---M---M---M---M---M---M---M---M---M-M*/ STDMETHODIMP_(ULONG) CFCruiseCar::AddRef(void) { InterlockedIncrement((PLONG) &m_cRefs); LOGF2("L<%X>: CFCruiseCar::AddRef. New cRefs=%i.",TID,m_cRefs); return m_cRefs; } /*M+M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M Method: CFCruiseCar::Release Summary: Release of the CFCruiseCar non-delegating IUnknown implementation. Args: void Modifies: m_cRefs. Returns: ULONG New value of m_cRefs (COM object's reference count). M---M---M---M---M---M---M---M---M---M---M---M---M---M---M---M---M---M---M-M*/ STDMETHODIMP_(ULONG) CFCruiseCar::Release(void) { ULONG cRefs; InterlockedDecrement((PLONG) &m_cRefs); cRefs = m_cRefs; LOGF2("L<%X>: CFCruiseCar::Release. New cRefs=%i.",TID,m_cRefs); if (0 == m_cRefs) { // We artificially bump the main ref count to prevent reentrancy // via the main object destructor. Not really needed in this // CFCruiseCar but a good practice because we are aggregatable and // may at some point in the future add something entertaining like // some Releases to the CFCruiseCar destructor. InterlockedIncrement((PLONG) &m_cRefs); delete this; } return cRefs; } /*--------------------------------------------------------------------------- CFCruiseCar's nested implementation of the IClassFactory interface including Constructor, Destructor, QueryInterface, AddRef, Release, CreateInstance, and LockServer methods. ---------------------------------------------------------------------------*/ /*M+M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M Method: CFCruiseCar::CImpIClassFactory::CImpIClassFactory Summary: Constructor for the CImpIClassFactory interface instantiation. Args: CFCruiseCar* pBackObj, Back pointer to the parent outer object. IUnknown* pUnkOuter, Pointer to the outer Unknown. For delegation. CServer* pServer) Pointer to the server's control object. Modifies: m_cRefI, m_pBackObj, m_pUnkOuter, m_pServer. Returns: void M---M---M---M---M---M---M---M---M---M---M---M---M---M---M---M---M---M---M-M*/ CFCruiseCar::CImpIClassFactory::CImpIClassFactory( CFCruiseCar* pBackObj, IUnknown* pUnkOuter, CServer* pServer) { // Init the Interface Ref Count (used for debugging only). m_cRefI = 0; // Init the Back Object Pointer to point to the parent object. m_pBackObj = pBackObj; // Init the pointer to the server control object. m_pServer = pServer; // Init the CImpIClassFactory interface's delegating Unknown pointer. // We use the Back Object pointer for IUnknown delegation here if we are // not being aggregated. If we are being aggregated we use the supplied // pUnkOuter for IUnknown delegation. In either case the pointer // assignment requires no AddRef because the CImpIClassFactory lifetime is // quaranteed by the lifetime of the parent object in which // CImpIClassFactory is nested. if (NULL == pUnkOuter) { m_pUnkOuter = pBackObj; LOGF1("L<%X>: CFCruiseCar::CImpIClassFactory Constructor. Non-Aggregating.",TID); } else { m_pUnkOuter = pUnkOuter; LOGF1("L<%X>: CFCruiseCar::CImpIClassFactory Constructor. Aggregating.",TID); } return; } /*M+M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M Method: CFCruiseCar::CImpIClassFactory::~CImpIClassFactory Summary: Destructor for the CImpIClassFactory interface instantiation. Args: void Returns: void M---M---M---M---M---M---M---M---M---M---M---M---M---M---M---M---M---M---M-M*/ CFCruiseCar::CImpIClassFactory::~CImpIClassFactory(void) { LOGF1("L<%X>: CFCruiseCar::CImpIClassFactory Destructor.",TID); return; } /*M+M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M Method: CFCruiseCar::CImpIClassFactory::QueryInterface Summary: The QueryInterface IUnknown member of this IClassFactory interface implementation that delegates to m_pUnkOuter, whatever it is. Args: REFIID riid, [in] GUID of the Interface being requested. PPVOID ppv) [out] Address of the caller's pointer variable that will receive the requested interface pointer. Returns: HRESULT Standard result code. NOERROR for success. Returned by the delegated outer QueryInterface call. M---M---M---M---M---M---M---M---M---M---M---M---M---M---M---M---M---M---M-M*/ STDMETHODIMP CFCruiseCar::CImpIClassFactory::QueryInterface( REFIID riid, PPVOID ppv) { LOGF1("L<%X>: CFCruiseCar::CImpIClassFactory::QueryInterface. Delegating.",TID); // Delegate this call to the outer object's QueryInterface. return m_pUnkOuter->QueryInterface(riid, ppv); } /*M+M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M Method: CFCruiseCar::CImpIClassFactory::AddRef Summary: The AddRef IUnknown member of this IClassFactory interface implementation that delegates to m_pUnkOuter, whatever it is. Args: void Modifies: m_cRefI. Returns: ULONG Returned by the delegated outer AddRef call. M---M---M---M---M---M---M---M---M---M---M---M---M---M---M---M---M---M---M-M*/ STDMETHODIMP_(ULONG) CFCruiseCar::CImpIClassFactory::AddRef(void) { // Increment the Interface Reference Count. InterlockedIncrement((PLONG) &m_cRefI); LOGF2("L<%X>: CFCruiseCar::CImpIClassFactory::Addref. Delegating. New cI=%i.",TID,m_cRefI); // Delegate this call to the outer object's AddRef. return m_pUnkOuter->AddRef(); } /*M+M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M Method: CFCruiseCar::CImpIClassFactory::Release Summary: The Release IUnknown member of this IClassFactory interface implementation that delegates to m_pUnkOuter, whatever it is. Args: void Modifies: m_cRefI. Returns: ULONG Returned by the delegated outer Release call. M---M---M---M---M---M---M---M---M---M---M---M---M---M---M---M---M---M---M-M*/ STDMETHODIMP_(ULONG) CFCruiseCar::CImpIClassFactory::Release(void) { // Decrement the Interface Reference Count. InterlockedDecrement((PLONG) &m_cRefI); LOGF2("L<%X>: CFCruiseCar::CImpIClassFactory::Release. Delegating. New cI=%i.",TID,m_cRefI); // Delegate this call to the outer object's Release. return m_pUnkOuter->Release(); } /*M+M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M Method: CFCruiseCar::CImpIClassFactory::CreateInstance Summary: The CreateInstance member method of this IClassFactory interface implementation. Creates an instance of the COCruiseCar COM component. Args: IUnknown* pUnkOuter, [in] Pointer to the controlling IUnknown. REFIID riid, [in] GUID of the Interface being requested. PPVOID ppvCob) [out] Address of the caller's pointer variable that will receive the requested interface pointer. Returns: HRESULT Standard result code. NOERROR for success. M---M---M---M---M---M---M---M---M---M---M---M---M---M---M---M---M---M---M-M*/ STDMETHODIMP CFCruiseCar::CImpIClassFactory::CreateInstance( IUnknown* pUnkOuter, REFIID riid, PPVOID ppv) { HRESULT hr = E_FAIL; COCruiseCar* pCob = NULL; LOGF2("L<%X>: CFCruiseCar::CImpIClassFactory::CreateInstance. pUnkOuter=0x%X.",TID,pUnkOuter); // If the creation call is requesting aggregation (pUnkOuter != NULL), // the COM rules state the IUnknown interface MUST also be concomitantly // requested. If it is not so requested ( riid != IID_IUnknown) then // an error must be returned indicating that no aggregate creation of // the COCruiseCarFactory COM Object can be performed. if (NULL != pUnkOuter && riid != IID_IUnknown) hr = CLASS_E_NOAGGREGATION; else { // Instantiate a COCruiseCar COM Object. pCob = new COCruiseCar(pUnkOuter, m_pServer); if (NULL != pCob) { // We initially created the new COM object so tell the server // to increment its global server object count to help ensure // that the server remains loaded until this partial creation // of a COM component is completed. m_pServer->ObjectsUp(); // If we have succeeded in instantiating the COM object we // initialize it to set up any subordinate objects. hr = pCob->Init(); if (SUCCEEDED(hr)) { // We QueryInterface this new COM Object not only to deposit the // main interface pointer to the caller's pointer variable, but to // also automatically bump the Reference Count on the new COM // Object after handing out this reference to it. hr = pCob->QueryInterface(riid, (PPVOID)ppv); } if (FAILED(hr)) { delete pCob; m_pServer->ObjectsDown(); } } else { // If we were launched to create this object and could not then // we should force a shutdown of this server. m_pServer->ObjectsUp(); m_pServer->ObjectsDown(); hr = E_OUTOFMEMORY; } } if (SUCCEEDED(hr)) { LOGF2("L<%X>: CFCruiseCar::CImpIClassFactory::CreateInstance Succeeded. *ppv=0x%X.",TID,*ppv); } else { LOGF1("L<%X>: CFCruiseCar::CImpIClassFactory::CreateInstance Failed.",TID); } return hr; } /*M+M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M+++M Method: CFCruiseCar::CImpIClassFactory::LockServer Summary: The LockServer member method of this IClassFactory interface implementation. Args: BOOL fLock) [in] Flag determining whether to Lock or Unlock the server. Returns: HRESULT Standard result code. NOERROR for success. M---M---M---M---M---M---M---M---M---M---M---M---M---M---M---M---M---M---M-M*/ STDMETHODIMP CFCruiseCar::CImpIClassFactory::LockServer( BOOL fLock) { HRESULT hr = NOERROR; LOGF1("L<%X>: CFCruiseCar::CImpIClassFactory::LockServer.",TID); if (fLock) m_pServer->Lock(); else m_pServer->Unlock(); return hr; }
9eee6b3fe9abc8ff95adac75b6a2bc5ba37c853f
82b081493f7f2401ce0a309c22962444744170ed
/codeforces/750A.cpp
127c3dbffc737f08d5ccba673668f6c64ea4d144
[]
no_license
HeNeos/CompetitiveProgramming
c69eaf91e597f7b66d5ad325daa8862ae813d7c1
56de3e5e403f9f6f7801f56683f5245c93f56a87
refs/heads/master
2023-06-23T06:14:15.373718
2023-06-18T21:42:35
2023-06-18T21:42:35
164,735,512
3
0
null
null
null
null
UTF-8
C++
false
false
282
cpp
750A.cpp
#include<bits/stdc++.h> using namespace std; int main(){ int n; int k; cin >> n >> k; for(int i=1; i<=n; i++){ if(5*i*(i + 1) <= 2*(240 - k)) continue; else{ cout<<i - 1; return 0; } } cout<<n; return 0; }
2cc791e6caf6b4bc176dde829b03754a1aded12d
04fee3ff94cde55400ee67352d16234bb5e62712
/10.24contest/source/Stu-16-³ÌÔóÑô/climb/climb.cpp
3a5c22852bc7439c4d18c45ebef4b64bcfc3b2ab
[]
no_license
zsq001/oi-code
0bc09c839c9a27c7329c38e490c14bff0177b96e
56f4bfed78fb96ac5d4da50ccc2775489166e47a
refs/heads/master
2023-08-31T06:14:49.709105
2021-09-14T02:28:28
2021-09-14T02:28:28
218,049,685
1
0
null
null
null
null
UTF-8
C++
false
false
286
cpp
climb.cpp
#include<cstdio> int main() { int n; freopen("climb.in","r",stdin); freopen("climb.out","w",stdout); scanf("%d",&n); if(n==4){ printf("5"); return 0; } if(n==7){ printf("6"); return 0; } printf("%d",n); fclose(stdin); fclose(stdout); return 0; }
096217595f33bf1250251467fc9ecb92c031dfa3
74b352eb46c3bbc886f8d6cfd64a90b3ebb8aed2
/不寻常的DP-方格取数.cpp
8848fe1ca4703e192abcd3f1ab75f12cdce0faf2
[]
no_license
Jeblqr/Model
d9c95f90147ec755f7968d1ac90609838385ef83
0d92b695fc7fea0bad916fcfcf5ddde68440eeea
refs/heads/master
2021-05-10T12:46:56.474823
2019-11-12T09:35:07
2019-11-12T09:35:07
118,451,544
8
3
null
null
null
null
UTF-8
C++
false
false
520
cpp
不寻常的DP-方格取数.cpp
#include<bits/stdc++.h> #define max(a,b,c,d) max(max(a,b),max(c,d)) using namespace std; int n,f[100][100][100][100],a[1000][1000],x,y,z; int main() { cin>>n>>x>>y>>z; while (x&&y&&z) { a[x][y]=z; cin>>x>>y>>z; } for (int i=1;i<=n;i++) for (int j=1;j<=n;j++) for (int h=1;h<=n;h++) for (int k=1;k<=n;k++) { f[i][j][h][k]=max(f[i-1][j][h-1][k],f[i][j-1][h][k-1],f[i][j-1][h-1][k],f[i-1][j][h][k-1])+a[i][j]; if (i!=h&&j!=k) f[i][j][h][k]+=a[h][k]; } cout<<f[n][n][n][n]; return 0; }
76b74f31fd4edd4c10d6dcf4f9bfec136d68b165
700f8cc1bf6dd4b4a1e019a615d3d86f8adaece9
/Vehicle/Car.h
817408c07c0bffce20609e4de63b6d4a568c2475
[]
no_license
Ddoty42/Vehicle
58ba86da26ae0eb4bc974e9eaec7fe7067a7892c
ff7b5bc8ae477df7ccaf494fa07a5279e664baaf
refs/heads/master
2023-01-18T19:09:10.967583
2020-11-29T16:03:41
2020-11-29T16:03:41
316,988,856
0
0
null
null
null
null
UTF-8
C++
false
false
321
h
Car.h
#ifndef CAR_H #define CAR_H #include "Vehicle.h" class Car : public Vehicle { private: int numDoors; public: Car() : Vehicle() { numDoors = 0; } void setDoors(int door) { numDoors = door; } int getDoors() { return numDoors; } void displayInfo() { cout << "Doors: " << getDoors() << endl; } }; #endif
fa17137f44061168836b54887b79fba0cb505490
3f3095dbf94522e37fe897381d9c76ceb67c8e4f
/Current/BP_GuntowerWeakpoint.hpp
d9881c34431f20bedb756eb6a501eb0fa06ab37c
[]
no_license
DRG-Modding/Header-Dumps
763c7195b9fb24a108d7d933193838d736f9f494
84932dc1491811e9872b1de4f92759616f9fa565
refs/heads/main
2023-06-25T11:11:10.298500
2023-06-20T13:52:18
2023-06-20T13:52:18
399,652,576
8
7
null
null
null
null
UTF-8
C++
false
false
765
hpp
BP_GuntowerWeakpoint.hpp
#ifndef UE4SS_SDK_BP_GuntowerWeakpoint_HPP #define UE4SS_SDK_BP_GuntowerWeakpoint_HPP class ABP_GuntowerWeakpoint_C : public AGuntowerWeakPoint { FPointerToUberGraphFrame UberGraphFrame; class UPawnAfflictionComponent* PawnAffliction; class UPointLightComponent* PointLight; class UCapsuleComponent* ProjectileCollision'; class UOutlineComponent* outline; class UEnemyComponent* enemy; class UPawnStatsComponent* PawnStats; FVector GetTargetCenterMass(); void ReceiveBeginPlay(); void BndEvt__Health_K2Node_ComponentBoundEvent_0_DeathSig__DelegateSignature(class UHealthComponentBase* HealthComponent); void OnExposedChanged(bool isExposed); void ExecuteUbergraph_BP_GuntowerWeakpoint(int32 EntryPoint); }; #endif
0dcf7f6377a3208cb26eb200a151f1ce192f066e
97aa1181a8305fab0cfc635954c92880460ba189
/torch/csrc/jit/passes/xnnpack_rewrite.h
178307dce769bc7e2eaa402d5f8c04ffe44444d2
[ "BSD-2-Clause" ]
permissive
zhujiang73/pytorch_mingw
64973a4ef29cc10b96e5d3f8d294ad2a721ccacb
b0134a0acc937f875b7c4b5f3cef6529711ad336
refs/heads/master
2022-11-05T12:10:59.045925
2020-08-22T12:10:32
2020-08-22T12:10:32
123,688,924
8
4
NOASSERTION
2022-10-17T12:30:52
2018-03-03T12:15:16
C++
UTF-8
C++
false
false
676
h
xnnpack_rewrite.h
#pragma once #include <torch/csrc/jit/api/module.h> #include <torch/csrc/jit/ir/ir.h> namespace torch { namespace jit { enum class MobileOptimizerType : int8_t { CONV_BN_FUSION, INSERT_FOLD_PREPACK_OPS, REMOVE_DROPOUT }; TORCH_API void insertPrePackedOps(std::shared_ptr<Graph>& graph); TORCH_API void insertPrePackedOps(script::Module& module); TORCH_API void fusePrePackedLinearConvWithClamp(script::Module& module); TORCH_API void FoldPrePackingOps(script::Module& module); TORCH_API script::Module optimizeForMobile( const script::Module& module, const std::set<MobileOptimizerType>& optimization_blacklist = {}); } // namespace jit } // namespace torch
f3830de981228c612a7c234b6bd19c69d75c88c9
eda7f1e5c79682bf55cfa09582a82ce071ee6cee
/aspects/fluid/potential/GunnsFluidPressureHead.hh
af6aded6e4cc9a3d2e259307955d091c81a0eb10
[ "LicenseRef-scancode-us-govt-public-domain", "LicenseRef-scancode-warranty-disclaimer", "LicenseRef-scancode-unknown-license-reference" ]
permissive
nasa/gunns
923f4f7218e2ecd0a18213fe5494c2d79a566bb3
d5455e3eaa8b50599bdb16e4867a880705298f62
refs/heads/master
2023-08-30T06:39:08.984844
2023-07-27T12:18:42
2023-07-27T12:18:42
235,422,976
34
11
NOASSERTION
2023-08-30T15:11:41
2020-01-21T19:21:16
C++
UTF-8
C++
false
false
9,838
hh
GunnsFluidPressureHead.hh
#ifndef GunnsFluidPressureHead_EXISTS #define GunnsFluidPressureHead_EXISTS /** @file GunnsFluidPressureHead.hh @brief GUNNS Fluid Pressure Head Spotter declarations @defgroup TSM_GUNNS_FLUID_POTENTIAL_PRESSURE_HEAD_SPOTTER GUNNS Fluid Pressure Head Spotter @ingroup TSM_GUNNS_FLUID_POTENTIAL @copyright Copyright 2021 United States Government as represented by the Administrator of the National Aeronautics and Space Administration. All Rights Reserved. PURPOSE: (Provides the classes for the GUNNS Fluid Pressure Head Spotter. This spotter is used to calculate the pressure head of a column of fluid in an acceleration field, and provide it to a connected GunnsFluidPotential or GunnsFluidAccum link.) @details REFERENCE: - (TBD) ASSUMPTIONS AND LIMITATIONS: - ((Assume fluid is incompressible.) (For accumulator links we assume column height is linear with bellows position.)) LIBRARY DEPENDENCY: - ((GunnsFluidPressureHead.o)) PROGRAMMERS: - ((Jason Harvey) (CACI) (April 2021) (Initial)) @{ */ #include "software/SimCompatibility/TsSimCompatibility.hh" #include "core/GunnsNetworkSpotter.hh" #include "math/MsMath.hh" //////////////////////////////////////////////////////////////////////////////////////////////////// /// @brief GUNNS Fluid Pressure Head Spotter Configuration Data /// /// @details The sole purpose of this class is to provide a data structure for the GUNNS Fluid /// Pressure Head Spotter configuration data. //////////////////////////////////////////////////////////////////////////////////////////////////// class GunnsFluidPressureHeadConfigData : public GunnsNetworkSpotterConfigData { public: double mFluidColumn[3]; /**< (m) trick_chkpnt_io(**) Height and orientation vector of the fluid column in the structure reference frame. */ const double* mAcceleration; /**< (m/s2) trick_chkpnt_io(**) Pointer to the acceleration vector. */ bool mReverseAcceleration; /**< (1) trick_chkpnt_io(**) Reverse the acceleration vector direction. */ const double* mRotationDcm; /**< (1) trick_chkpnt_io(**) Pointer to the rotation direction cosine matrix. */ bool mTransposeRotation; /**< (1) trick_chkpnt_io(**) Reverse the frame transformation direction. */ /// @brief Default constructs this GUNNS Fluid Pressure Head Spotter configuration data. GunnsFluidPressureHeadConfigData(const std::string& name, const double fluidColumnX = 0.0, const double fluidColumnY = 0.0, const double fluidColumnZ = 0.0, const double* acceleration = 0, const bool reverseAcceleration = false, const double* rotationDcm = 0, const bool transposeRotation = false); /// @brief Default destructs this GUNNS Fluid Pressure Head Spotter configuration data. virtual ~GunnsFluidPressureHeadConfigData(); private: /// @brief Copy constructor unavailable since declared private and not implemented. GunnsFluidPressureHeadConfigData(const GunnsFluidPressureHeadConfigData& that); /// @brief Assignment operator unavailable since declared private and not implemented. GunnsFluidPressureHeadConfigData& operator =(const GunnsFluidPressureHeadConfigData& that); }; //////////////////////////////////////////////////////////////////////////////////////////////////// /// @brief GUNNS Fluid Pressure Head Spotter Input Data /// /// @details The sole purpose of this class is to provide a data structure for the GUNNS Fluid /// Pressure Head Spotter input data. //////////////////////////////////////////////////////////////////////////////////////////////////// class GunnsFluidPressureHeadInputData : public GunnsNetworkSpotterInputData { public: /// @brief Default constructs this GUNNS Fluid Pressure Head Spotter input data. GunnsFluidPressureHeadInputData(); /// @brief Default destructs this GUNNS Fluid Pressure Head Spotter input data. virtual ~GunnsFluidPressureHeadInputData(); private: /// @brief Copy constructor unavailable since declared private and not implemented. GunnsFluidPressureHeadInputData(const GunnsFluidPressureHeadInputData& that); /// @brief Assignment operator unavailable since declared private and not implemented. GunnsFluidPressureHeadInputData& operator =(const GunnsFluidPressureHeadInputData& that); }; // Forward-declare referenced types. class GunnsFluidLink; class GunnsFluidPotential; class GunnsFluidAccum; //////////////////////////////////////////////////////////////////////////////////////////////////// /// @brief GUNNS Fluid Pressure Head Spotter Class. /// /// @details This spotter automates the calculation of the pressure created by a column of fluid /// under acceleration. This receives an acceleration vector and optional frame rotation, /// and outputs the resulting pressure head (delta-pressure) to an attached /// GunnsFluidPotential or GunnsFluidAccum link. This spotter is configured with the /// direction vector of the fluid column in its structural reference frame. /// /// Both link types define the 'bottom' of their column vector at port 1, and port 0 is /// towards the 'top'. By default, the acceleration is defined such that if the vehicle /// is accelerating towards the direction of the 'top' end of the column, the acceleration /// vector points in that direction, and this creates a pressure increase at the bottom of /// the fluid column. /// /// If the user is stuck with an acceleration vector that is defined opposite of the above /// they can set the mReverseAcceleration flag to cause us to flip their direction to our /// convention. Likewise, the rotation direction cosine matrix (DCM), which normally /// rotates an acceleration reference frame vector into the structural reference frame, /// can be made to do the reverse rotation instead. //////////////////////////////////////////////////////////////////////////////////////////////////// class GunnsFluidPressureHead : public GunnsNetworkSpotter { TS_MAKE_SIM_COMPATIBLE(GunnsFluidPressureHead); public: /// @brief Default Constructor GunnsFluidPressureHead(GunnsFluidLink& link); /// @brief Default destructor. virtual ~GunnsFluidPressureHead(); /// @brief Initializes the GUNNS Fluid Pressure Head Spotter with configuration and /// input data. virtual void initialize(const GunnsNetworkSpotterConfigData* configData, const GunnsNetworkSpotterInputData* inputData); /// @brief Steps the GUNNS Fluid Pressure Head Spotter prior to the GUNNS solver step. virtual void stepPreSolver(const double dt); /// @brief Steps the GUNNS Fluid Pressure Head Spotter after the GUNNS solver step. virtual void stepPostSolver(const double dt); /// @brief Returns the pressure head value. double getPressureHead() const; protected: GunnsFluidLink* mLink; /**< ** (1) trick_chkpnt_io(**) Pointer to the link. */ GunnsFluidPotential* mPotentialLink; /**< ** (1) trick_chkpnt_io(**) Pointer to the fluid potential link. */ GunnsFluidAccum* mAccumLink; /**< ** (1) trick_chkpnt_io(**) Pointer to the fluid accumulator link. */ double mFluidColumn[3]; /**< (m) trick_chkpnt_io(**) Height and orientation of the fluid column in the structure reference frame. */ const double* mAcceleration; /**< (m/s2) trick_chkpnt_io(**) Pointer to the acceleration vector. */ bool mReverseAcceleration; /**< (1) trick_chkpnt_io(**) Reverse the acceleration vector direction. */ const double* mRotationDcm; /**< (1) trick_chkpnt_io(**) Pointer to the rotation direction cosine matrix. */ bool mTransposeRotation; /**< (1) trick_chkpnt_io(**) Reverse the frame transformation direction. */ double mPressureHead; /**< (kPa) trick_chkpnt_io(**) Output pressure head. */ /// @brief Validates the supplied configuration data. const GunnsFluidPressureHeadConfigData* validateConfig(const GunnsNetworkSpotterConfigData* config); /// @brief Validates the supplied input data. const GunnsFluidPressureHeadInputData* validateInput (const GunnsNetworkSpotterInputData* input); private: /// @brief Copy constructor unavailable since declared private and not implemented. GunnsFluidPressureHead(const GunnsFluidPressureHead& that); /// @brief Assignment operator unavailable since declared private and not implemented. GunnsFluidPressureHead& operator =(const GunnsFluidPressureHead& that); }; /// @} //////////////////////////////////////////////////////////////////////////////////////////////////// /// @returns double (kPa) Pressure head. /// /// @details Returns the value of the mPressureHead attribute. //////////////////////////////////////////////////////////////////////////////////////////////////// inline double GunnsFluidPressureHead::getPressureHead() const { return mPressureHead; } #endif
4e5c8b23e81e0b475c937f832f4e12431b193aef
999db95b111103f10862980c88d7df2322ccfd4c
/polygonpointsmodel.cpp
c31128c33b7389d503a4a7b4847f329b0ce69aa6
[]
no_license
google-code/alegria-editor
a0da6cb4afcb3509b2919a11f8d456aefd0fdc60
557a70abe4ae2819e4f71adaea29452a384e2ead
refs/heads/master
2016-09-02T03:41:44.557478
2015-03-14T13:12:06
2015-03-14T13:12:06
32,212,512
0
0
null
null
null
null
UTF-8
C++
false
false
2,505
cpp
polygonpointsmodel.cpp
#include "polygonpointsmodel.h" PolygonPointsModel::PolygonPointsModel(AED_PhysicsComp *comp, QObject *parent) : QAbstractTableModel(parent),m_comp(comp) { m_list = comp->GetPoints(); } int PolygonPointsModel::rowCount(const QModelIndex & parent) const{ return m_list->size(); } int PolygonPointsModel::columnCount(const QModelIndex & parent) const{ return 2; } QVariant PolygonPointsModel::data ( const QModelIndex & index, int role) const{ if(role==Qt::DisplayRole||role==Qt::EditRole){ int row = index.row(); AED_PhysicsComp::Point point = (*m_list)[row]; QVariant var; if(index.column()==0) var = point.x; else if(index.column()==1) var = point.y; else return QVariant(QVariant::Invalid); return var; } return QVariant(QVariant::Invalid); } QVariant PolygonPointsModel::headerData ( int section, Qt::Orientation orientation, int role) const{ if(orientation==Qt::Horizontal){ if (role==Qt::DisplayRole||role==Qt::EditRole){ if(section==0) return tr("X"); else if(section==1) return tr("Y"); }else{ return QVariant(QVariant::Invalid); } }else{ if (role==Qt::DisplayRole||role==Qt::EditRole){ QVariant h(QVariant::Int); h=section+1; return h; }else{ return QVariant(QVariant::Invalid); } } return QVariant(QVariant::Invalid); } void PolygonPointsModel::AddPoint(){ m_comp->AddPoint(0,0); emit layoutChanged(); } void PolygonPointsModel::RemovePoint(int index){ m_comp->RemovePoint(index); emit layoutChanged(); } bool PolygonPointsModel::setData(const QModelIndex &index, const QVariant &value, int role){ int row = index.row(); int column = index.column(); if(index.isValid() && role==Qt::EditRole){ if(column==0){ (*m_list)[row].x = value.toFloat(); }else if(column==1){ (*m_list)[row].y = value.toFloat(); }else{ return false; } emit dataChanged(index,index); return true; } return false; } Qt::ItemFlags PolygonPointsModel::flags(const QModelIndex &index) const{ Qt::ItemFlags flags = Qt::ItemIsEnabled|Qt::ItemIsEditable|Qt::ItemIsSelectable; return flags; }
c8b382f826fe62fc1eea9f2d1e73460d6b0a2447
0cf4d867ca87f205d5e65e37966e48a30bd6098f
/Fractal/Fractal/GravityIterator.cpp
ced3dfc8884c287965e6ca24632fa886cefa34f3
[ "ISC" ]
permissive
pauldoo/scratch
344fd0c2a081caca7c75be93279b9b531ed53ee7
400e2647e1026402c8b72828f694db3cda682d0d
refs/heads/master
2023-03-08T19:27:29.911309
2022-05-10T18:40:30
2022-05-10T18:40:30
393,548
2
1
ISC
2023-03-02T22:56:23
2009-12-03T00:37:13
C++
UTF-8
C++
false
false
2,589
cpp
GravityIterator.cpp
#include "External.h" #include "GravityIterator.h" #include "Accumulator.h" #include "Geometry.h" namespace Fractal { template<typename T> GravityIterator<T>::GravityIterator( Accumulator* accumulator00, const std::vector<Vector>& masses, const double acc_step, const double damping, const double distance_cutoff ) : m_accumulator00(accumulator00), m_masses(masses), m_acc_step(acc_step), m_damping(damping), m_distance_cutoff(distance_cutoff) { } template<typename T> GravityIterator<T>::~GravityIterator() { } template<typename T> void GravityIterator<T>::Seed(const T& seed) { m_position = seed; m_velocity.clear(); } template<typename T> const T& GravityIterator<T>::Value(void) const { return m_position; } template<typename T> const T& GravityIterator<T>::Iterate(void) { Vector acceleration; acceleration.clear(); for (typename VectorList::const_iterator i = m_masses.begin(); i != m_masses.end(); ++i) { const Vector displacement = (*i) - m_position; const double distance = norm_2(displacement); const Vector displacement_unit_vec = displacement / distance; const Vector force = displacement_unit_vec / (distance * distance); acceleration += force; } const double time_step = m_acc_step / norm_2(acceleration); m_velocity *= pow(1.0 - m_damping, time_step); m_velocity += acceleration * time_step; m_position += m_velocity * time_step; if (m_accumulator00) { m_accumulator00->Accumulate( Fractal::Geometry::Vector2ToVector4(Value()), time_step ); } return Value(); } template<typename T> const int GravityIterator<T>::IterateUntilTrapped() { while (true) { const int result = Trapped(); if (result != -1) { return result; } Iterate(); } } template<typename T> const int GravityIterator<T>::Trapped(void) const { for (typename VectorList::const_iterator i = m_masses.begin(); i != m_masses.end(); ++i) { const Vector displacement = (*i) - m_position; const double distance = norm_2(displacement); if (distance <= m_distance_cutoff) { return i - m_masses.begin(); } } return -1; } template class GravityIterator< Fractal::Vector2 >; }
7de4307dbfe674e8a3ab9e4e8591eaa9999483fb
246f356e638f66a3b2adfd9fc70b059170f25994
/1-beginners/12-while.cpp
5eb3ec7246ffe29252b0fa8e8880cfff567eae04
[]
no_license
romanprograms/codebeauty-channel
f29535e79ccfd527aa7e28021389717e9151c7f0
b3a9f357ec2d1c45ec1a2329845728680ec49964
refs/heads/master
2023-02-14T22:38:27.007628
2021-01-02T14:58:07
2021-01-02T14:58:07
null
0
0
null
null
null
null
UTF-8
C++
false
false
551
cpp
12-while.cpp
#include <iostream> int main() { std::cout << std::endl << std::endl << std::endl << std::endl; // Count digits of a number int number, count = 0; std::cout << "Number: ", std::cin >> number; if (number == 0) std::cout << "You have entered 0. \n"; else { if (number < 0) number *= -1; while (number >= 1) { number /= 10; count++; } } std::cout << "There are " << count << " Digits\n"; std::cout << std::endl << std::endl << std::endl << std::endl; }
c1a680e0ba86b2459898af0971245b070a3adea1
d3d28452cfc4b79b1cf0f5578a4eb3be1fe75fb7
/libpjsip/src/main/cpp/SipManager.cpp
48624bcbfaecce9234ee0b6ed3564aab62295afc
[]
no_license
m15115021148/AndroidLibPJSip-master
7cb351f6dda3a96666bacc2ef8b03a9e0892159e
62b6147246e40735a46c46708131e7bbf06a2774
refs/heads/master
2021-05-12T06:01:11.010781
2018-01-12T07:28:44
2018-01-12T07:28:44
117,208,041
2
0
null
null
null
null
UTF-8
C++
false
false
708
cpp
SipManager.cpp
// // Created by weiminji on 11/5/17. // #include <pjsua2/include/pjsip/sip_types.h> #include "SipManager.h" SipManager::SipManager() { } SipManager::~SipManager() { } bool SipManager::init(unsigned port) { mSipEndpoint.libCreate(); // Initialize endpoint EpConfig ep_cfg; mSipEndpoint.libInit( ep_cfg ); // Create SIP transport. Error handling sample is shown TransportConfig tcfg; tcfg.port = port; try { mSipEndpoint.transportCreate(PJSIP_TRANSPORT_UDP, tcfg); } catch (Error &err) { std::cout << err.info() << std::endl; return false; } // Start the library (worker threads etc) mSipEndpoint.libStart(); return true; }
99d32ca7b452724ec59f4271f4d9096e98d556fd
1035fe3cd67abf519b8c1e28dfd647e9b7c96e58
/Orbit/Dependencies/Camera/Camera.cpp
5e215e50e9a55f549f78317357b306d37fdd0733
[]
no_license
talhacali/Orbit
059e0dbec5ba1587ca2658ef60c3a72653407af7
8cd0aea74b28d613bc8dde47482e983eb87f30da
refs/heads/master
2022-12-07T21:27:44.472233
2020-09-03T12:05:50
2020-09-03T12:05:50
284,675,944
0
0
null
null
null
null
UTF-8
C++
false
false
42
cpp
Camera.cpp
#include "Camera.h" namespace Orbit { }
3d1b17fb279733b4c7ec8f750885d6a3ad8e9fc5
7f1822a1a2afa0a90a5840ec8dff2252b44206f1
/AllGL/OpenGL_9_16/Vector3.cpp
50a42890b6ffeea177dbb608a8929ef6aa739612
[]
no_license
shujianhework/NULL
4938d265f57868da52fcb183959e8243a1faee2c
198d6bc77d5d02236a935eaade91b2b90d565c91
refs/heads/master
2020-03-27T08:37:56.787734
2019-01-15T12:45:37
2019-01-15T12:45:37
146,271,737
0
0
null
null
null
null
UTF-8
C++
false
false
230
cpp
Vector3.cpp
#include "stdafx.h" #include "Vector3.h" Vector3::Vector3(double x, double y, double z) :x(x), y(y), z(z) { } Vector3::~Vector3() { } void Vector3::set(double x, double y, double z){ this->x = x; this->y = y; this->z = z; }
e7b593d5a9d88542ef60b1e776bbbfd1192126c8
2e1817c8e72d85cb305f7bff995dbc3e46dcbe18
/Src/EtriPPSP/EtriPPSP/PP/Cancel.cpp
af2b6f0fed5b75c1e95d3911b31d0eac6713149c
[]
no_license
ETRI-PEC/PPSP
3cb9c593f38761fc26be73945c362125396ef1a4
16366672341c8c33cb2f622956c926777805dc44
refs/heads/master
2021-01-13T01:36:12.437384
2016-09-09T10:59:54
2016-09-09T10:59:54
42,294,963
0
0
null
null
null
null
UTF-8
C++
false
false
1,264
cpp
Cancel.cpp
#include "Cancel.h" #include <string.h> #include "../Common/Util.h" Cancel::Cancel() { MessageType = PP_MESSAGETYPE_CANCEL; } Cancel::~Cancel() { } int Cancel::Create(char* data) { int idx = 0; memcpy(&DestinationChannelID, data, 4); DestinationChannelID = CalcEndianN2H(DestinationChannelID); idx += 4; LogPrint(LOG_LEVEL_DEBUG, "DestinationChannelID : %d\n", DestinationChannelID); idx++; // message type; memcpy(&StartChunk, data + idx, 4); StartChunk = CalcEndianN2H(StartChunk); idx += 4; LogPrint(LOG_LEVEL_DEBUG, "StartChunk : %d\n", StartChunk); memcpy(&EndChunk, data + idx, 4); EndChunk = CalcEndianN2H(EndChunk); idx += 4; LogPrint(LOG_LEVEL_DEBUG, "EndChunk : %d\n", EndChunk); return idx; } char* Cancel::GetBuffer(int* len) { char buf[1024]; memset(buf, 0, 1024); int idx = 0, tmpl = 0; tmpl = CalcEndianH2N(DestinationChannelID); memcpy(buf, &tmpl, 4); idx += 4; memcpy(buf + idx, &MessageType, 1); idx += 1; tmpl = CalcEndianH2N(StartChunk); memcpy(buf + idx, &tmpl, 4); idx += 4; tmpl = CalcEndianH2N(EndChunk); memcpy(buf + idx, &tmpl, 4); idx += 4; if (Buffer != 0) delete[] Buffer; Buffer = new char[idx]; memset(Buffer, 0, idx); memcpy(Buffer, buf, idx); *len = idx; return Buffer; }
0d5659b3645288d3620fdcf45acb895ac7c482ea
23f35b2d300ce3698dc3a0ef19ac9ac76ff360da
/64FrameWork/Tool/Code/MyForm.cpp
691ca21fff68e8f20dd7a20baeff30a8f3445337
[]
no_license
cat5778/CodeVein7.0
ea22d99e71aa9ce0e0988fa0b3dac541c9a4260e
9060290d96dc3d4ebb6418938b6a7377594dc11b
refs/heads/master
2022-12-01T06:34:38.464392
2020-08-16T04:00:34
2020-08-16T04:00:34
278,945,120
0
0
null
null
null
null
UHC
C++
false
false
3,638
cpp
MyForm.cpp
// ../Code/MyForm.cpp : 구현 파일입니다. // #include "stdafx.h" #include "Tool.h" #include "MyForm.h" #include "ObjectTool.h" #include "CameraTool.h" #include "NavMeshTool.h" #include "MainFrm.h" #include "ToolView.h" #include "ColliderTool.h" // CMyForm IMPLEMENT_DYNCREATE(CMyForm, CFormView) CMyForm::CMyForm() : CFormView(IDD_MYFORM) { } CMyForm::~CMyForm() { //Engine::Safe_Release(m_pDevice); //Engine::Safe_Release(m_pDeviceClass); Safe_Delete(m_pObjectTool); Safe_Delete(m_pCameraTool); Safe_Delete(m_pNavMeshTool); } void CMyForm::DoDataExchange(CDataExchange* pDX) { CFormView::DoDataExchange(pDX); DDX_Control(pDX, IDC_TAB2, m_TabCtrl); } BEGIN_MESSAGE_MAP(CMyForm, CFormView) ON_NOTIFY(TCN_SELCHANGE, IDC_TAB2, &CMyForm::OnTcnSelchangeTab2) END_MESSAGE_MAP() // CMyForm 진단입니다. #ifdef _DEBUG void CMyForm::AssertValid() const { CFormView::AssertValid(); } #ifndef _WIN32_WCE void CMyForm::Dump(CDumpContext& dc) const { CFormView::Dump(dc); } #endif #endif //_DEBUG // CMyForm 메시지 처리기입니다. void CMyForm::OnInitialUpdate() { CFormView::OnInitialUpdate(); // TODO: 여기에 특수화된 코드를 추가 및/또는 기본 클래스를 호출합니다. m_TabCtrl.InsertItem(0, _T("Object")); m_TabCtrl.InsertItem(1, _T("Camera")); m_TabCtrl.InsertItem(2, _T("NavMesh")); m_TabCtrl.InsertItem(3, _T("Collider")); m_TabCtrl.GetCurSel(); CRect rect; m_TabCtrl.GetWindowRect(&rect); //m_pCameraTab = new CCameraTab; if (m_pDeviceClass == nullptr) { CMainFrame* pFrameWnd = dynamic_cast<CMainFrame*>(::AfxGetApp()->GetMainWnd()); NULL_CHECK(pFrameWnd); m_pToolView = dynamic_cast<CToolView*>(pFrameWnd->m_MainSplitter.GetPane(0, 1)); NULL_CHECK(m_pToolView); m_pDeviceClass = m_pToolView->GetDeviceClass(); m_pDevice = m_pToolView->GetDevice(); m_pScene = m_pToolView->GetScene(); } m_pObjectTool = new CObjectTool; m_pObjectTool->Create(IDD_DIALOG1, &m_TabCtrl); m_pObjectTool->MoveWindow(0, 21, rect.Width(), rect.Height()); m_pObjectTool->ShowWindow(SW_HIDE); m_pCameraTool = new CCameraTool; m_pCameraTool->Create(IDD_DIALOG2, &m_TabCtrl); m_pCameraTool->MoveWindow(0, 21, rect.Width(), rect.Height()); m_pCameraTool->ShowWindow(SW_HIDE); m_pNavMeshTool = new CNavMeshTool; m_pNavMeshTool->Create(IDD_DIALOG3, &m_TabCtrl); m_pNavMeshTool->MoveWindow(0, 21, rect.Width(), rect.Height()); m_pNavMeshTool->ShowWindow(SW_HIDE); m_pColliderTool = new CColliderTool; m_pColliderTool->Create(IDD_DIALOG4, &m_TabCtrl); m_pColliderTool->MoveWindow(0, 21, rect.Width(), rect.Height()); m_pColliderTool->ShowWindow(SW_HIDE); m_TabCtrl.SetCurSel(0); m_pObjectTool->ShowWindow(SW_SHOW); } void CMyForm::OnTcnSelchangeTab2(NMHDR *pNMHDR, LRESULT *pResult) { //// TODO: 여기에 컨트롤 알림 처리기 코드를 추가합니다. int iSel = m_TabCtrl.GetCurSel(); switch (iSel) { case 0: m_pObjectTool->ShowWindow(SW_SHOW); m_pCameraTool->ShowWindow(SW_HIDE); m_pNavMeshTool->ShowWindow(SW_HIDE); m_pColliderTool->ShowWindow(SW_HIDE); break; case 1: m_pObjectTool->ShowWindow(SW_HIDE); m_pCameraTool->ShowWindow(SW_SHOW); m_pNavMeshTool->ShowWindow(SW_HIDE); m_pColliderTool->ShowWindow(SW_HIDE); break; case 2: m_pObjectTool->ShowWindow(SW_HIDE); m_pCameraTool->ShowWindow(SW_HIDE); m_pNavMeshTool->ShowWindow(SW_SHOW); m_pColliderTool->ShowWindow(SW_HIDE); break; case 3: m_pObjectTool->ShowWindow(SW_HIDE); m_pCameraTool->ShowWindow(SW_HIDE); m_pNavMeshTool->ShowWindow(SW_HIDE); m_pColliderTool->ShowWindow(SW_SHOW); break; //default: // break; } *pResult = 0; }
53f8d52eaea6c0d5a65eb79351c8fccd4b7cb387
2bf510c216511f4ac6e559b8d7ceaf5ab1ff5bd6
/twodlearn/core/cuda/tests/matmul_pattern/matmul_pattern.cu.cc
b3958433971fb13bfce2973d1fa824432fa912c4
[ "Apache-2.0" ]
permissive
danmar3/twodlearn
6495a04f5ed8fb7202fb16cd54a4c1d1b01dbd31
02b23bf07618d5288e338bd8f312cc38aa58c195
refs/heads/master
2022-11-16T03:37:21.968697
2019-08-23T02:22:40
2019-08-23T02:22:40
186,306,667
0
1
Apache-2.0
2022-11-04T05:16:12
2019-05-12T21:36:56
Jupyter Notebook
UTF-8
C++
false
false
2,771
cc
matmul_pattern.cu.cc
// *********************************************************************** // Test of matmul pattern implementation // Wrote by: Daniel L. Marino (marinodl@vcu.edu) (2016) // *********************************************************************** /* Includes, system */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <iostream> #include <functional> /* Includes, cuda */ #include "twodlearn/core/cuda/eigen_cuda.cu.h" #include "twodlearn/core/cuda/matmul_pattern.cu.h" #define BLOCK_SIZE 32 /* Includes, eigen */ #include "Eigen/Dense" using namespace Eigen; using namespace std; /* Main */ int main(int argc, char **argv){ unsigned m= 1000; unsigned k= 800; unsigned n= 1101; struct timespec start_cpu, end_cpu; // Allocate and fill h_A and h_B with data: TwinMat<double, RowMajor> a(m, k); a.transfer_h2d(); TwinMat<double, RowMajor> b(k, n); b.transfer_h2d(); TwinMat<double, RowMajor> c(m, n); //c.transfer_h2d(); // For performance measure cudaEvent_t start, stop; cudaEventCreate(&start); cudaEventCreate(&stop); // 1. --------------------------- matmul test --------------------------- // 1.1. matmul on cpu cout << "Running matmul on cpu" << endl; clock_gettime(CLOCK_MONOTONIC_RAW, &start_cpu); MatrixXd c_eigen = a.mat * b.mat; clock_gettime(CLOCK_MONOTONIC_RAW, &end_cpu); uint64_t cpu_time_ms = (1000000000L * (end_cpu.tv_sec - start_cpu.tv_sec) + end_cpu.tv_nsec - start_cpu.tv_nsec) / 1e6; // 1.2. matmul on gpu cout << "Running matmul on GPU" << endl; MulFunc<double> mul_cu; SumFunc<double> sum_cu; dim3 dim_grid( 1 + ((c.mat.cols() -1)/BLOCK_SIZE), 1 + ((c.mat.rows() -1)/BLOCK_SIZE), 1); dim3 dim_block(BLOCK_SIZE, BLOCK_SIZE, 1); cout << dim_grid.x << " " << dim_grid.y << " " << BLOCK_SIZE << endl; cudaEventRecord(start); matmul_pattern_cuda<MulFunc<double>, SumFunc<double>, double, BLOCK_SIZE> <<<dim_grid, dim_block>>> (c.device, a.device, b.device, a.mat.rows(), a.mat.cols(), b.mat.cols(), mul_cu, sum_cu); cudaDeviceSynchronize(); c.transfer_d2h(); cudaEventRecord(stop); // 1.3. print performance // error MatrixXd diff= c_eigen - c.mat; diff = diff.array().pow(2); cout << "difference: " << diff.sum() << "\n"; // time cudaEventSynchronize(stop); float gpu_time_ms; cudaEventElapsedTime(&gpu_time_ms, start, stop); cout << "time on cpu: " << cpu_time_ms << "[ms] \n"; cout << "time on gpu: " << gpu_time_ms << "[ms] \n"; if ((a.mat.rows()) < 5 && (a.mat.cols()) < 5 && (b.mat.cols()) < 5){ cout << "A:" << endl<< a.mat << endl; cout << "B:" << endl<< b.mat << endl; cout << "C(CPU):" << endl<< c_eigen << endl; cout << "C(GPU):" << endl<< c.mat << endl; } }
5b76b308fe63db22f07f4f52f3954b3e1137b633
8c7b97a5e2ab7f64ce5bcff81e421c62214c5ed4
/DoubleEndedQueue_CircleArray.cpp
7ea1e7a813f055ace13550fbd7ff38b52d0d05b9
[]
no_license
Anniebhalla10/Data-Structures
b22d6a6ea0ee2780d1751fea27222475a5c26f3c
0287a5d02f9717201918fc9c36d63cd32a5c457a
refs/heads/master
2023-04-05T15:42:04.494799
2021-04-03T16:15:08
2021-04-03T16:15:08
293,104,385
0
0
null
null
null
null
UTF-8
C++
false
false
2,664
cpp
DoubleEndedQueue_CircleArray.cpp
/* Name : Annie Bhalla Roll No. : 19HCS4009 Course : BSC (H) Computer Science Semester : 3 Subject : Data Structures Title : Implementation of Double Ended Queues ( Circular Array ) */ #include<iostream> using namespace std; typedef int Elem; class DQueue { Elem *arr; int actual_len; int front; int rear; int ctr; public: DQueue(int ); // 1 bool empty()const; // 2 int size()const; // 3 void addFront(const Elem& e); // 4 void addBack(const Elem& e); // 5 void eraseFront(); // 6 void eraseBack(); // 7 void display(); }; // (1) Constructor DQueue::DQueue(int n=0) { actual_len=n; arr= new Elem[n]; front=-1; rear=-1; ctr=0; } // (2) to check whether the DQ is empty bool DQueue::empty()const { return (ctr==0); } // (3) to return the size of the queue int DQueue::size()const { return ctr; } // (4) to add an element in the front void DQueue::addFront(const Elem& e) { if(size()==actual_len) throw " Function enqueue() : Queue Full "; if(rear==-1) rear= actual_len-1; if(front==-1 || front==0) front = actual_len-1; else front= front-1; arr[front] = e; ctr++; } // (5) to add element at the back void DQueue::addBack(const Elem& e) { if(size()==actual_len) throw " Function enqueue() : Queue Full "; if(front==-1) front=0; rear= (rear+1)%actual_len; arr[rear] = e; ctr++; } // (6) to remove element from front void DQueue::eraseFront() { if(empty()) { front=-1; rear=-1; throw " Function dequeue() : Empty List , Cannot delete more elements"; } front = (front+1)%actual_len; ctr= ctr-1; } // (7) to remove element from back void DQueue::eraseBack() { if(empty()) { front=-1; rear=-1; throw " Function dequeue() : Empty List , Cannot delete more elements"; } if(rear==0) rear = actual_len-1; rear--; ctr=ctr-1; } // (8) display queue void DQueue::display() { if(empty()) throw " Function Display() : Empty List "; int i=front; while( i!= rear) { cout<<arr[i]<<" -> "; i = (i+1)% actual_len; } cout<<arr[rear]; cout<<endl; } // driver code int main() { int N; cout<<"\n Enter the size of the queue :"; cin>>N; try { DQueue D(N); D.addFront(5); D.addBack(10); D.addBack(15); D.addBack(20); D.display(); D.eraseFront(); D.display(); D.eraseBack(); D.display(); cout<<"\n Number of elements : "<<D.size(); } catch(const char* str) { cout<<"\n Exception Found at : "<<str; } return 0; }
1806681d78ff6ff0e24c21da97861172568fb131
549d781df9365fdda48f34b392d55645d324b34d
/graph/libgraphalgo/bron2.cc
217f02a5b9d0b12827fa50011ebf7461760701a1
[]
no_license
jeffery-cavallaro-cavcom/cavcom
ec61cfa1f2d6d0e46c6ebe96a80dcbb13a8ad9b3
53a41a7f9e48102488bc0d244e6e0218837bce37
refs/heads/master
2020-06-28T16:45:07.716506
2020-01-10T22:10:59
2020-01-10T22:10:59
200,286,479
0
0
null
null
null
null
UTF-8
C++
false
false
5,872
cc
bron2.cc
#include "bron2.h" namespace cavcom { namespace graph { Bron2::Bron2(const SimpleGraph &graph, int mode, bool save) : Bron(graph, mode, save) {} bool Bron2::extend(VertexNumberList *pcandidates, VertexNumberList *pused) { add_call(); const SimpleGraph &g = graph(); VertexNumberList &candidates = *pcandidates; VertexNumberList &used = *pused; // If only trying to determine the clique number then abandon branches that don't have enough candidates to // make a clique that exceeds the current maximum. if (mode() < 0) { if (current_.size() + candidates.size() <= number()) { done_call(); return true; } } // The vertex with the least amount of adjacencies to the candidate vertices. VertexNumber target = 0; // The position in the used or candidate list of the target vertex. VertexNumberList::size_type target_pos = 0; // The number of candidates that are not adjacent to the target vertex. VertexNumberList::size_type count = 0; // False: the target is in the used list; True: the target is in the candidate list. bool is_a_candidate = false; // Look for a used vertex that has the least number of adjacencies with the candidate vertices. VertexNumberList::size_type nc = candidates.size(); VertexNumberList::size_type nu = used.size(); for (VertexNumberList::size_type iu = 0; iu < nu; ++iu) { VertexNumber next_used = used[iu]; VertexNumberList::size_type next_count = 0; for (VertexNumberList::size_type ic = 0; ic < nc; ++ic) { if (!g.adjacent(next_used, candidates[ic])) { ++next_count; } } if ((iu == 0) || (next_count < count)) { target = next_used; target_pos = iu; count = next_count; } } // If there exists a used vertex that is adjacent to every candidate vertex then the remaining candidates will // never be able to construct a maximal clique. if ((nu > 0) && (count == 0)) { done_call(); return true; } // See if there are any candidates with even less adjacencies. Be sure to count the fact that a vertex is not // adjacent to iteself. for (VertexNumberList::size_type ic = 0; ic < nc; ++ic) { VertexNumber next_candidate = candidates[ic]; VertexNumberList::size_type next_count = 0; for (VertexNumberList::size_type jc = 0; jc < nc; ++jc) { if (!g.adjacent(next_candidate, candidates[jc])) { ++next_count; } } if (((nu == 0) && (ic == 0)) || (next_count < count)) { target = next_candidate; target_pos = ic; count = next_count; is_a_candidate = true; } } // Keep going as long as the target used vertex is not adjacent to at least one candidate. while (count > 0) { // Select the next candidate and swap it into the next select position at the end of the candidate list. VertexNumber &last = candidates.back(); VertexNumberList::size_type last_pos = candidates.size() - 1; if (is_a_candidate) { // The target vertex is still in the candidate list. Make sure that it is the next one selected. if (target_pos != last_pos) { candidates[target_pos] = last; last = target; target_pos = last_pos; } } else { // Find a candidate vertex that is not adjacent to the used target. There should be at least one. This // will decrease the target count when the selected vertex gets moved to the used list. for (VertexNumberList::size_type ic = 0; ic < nc; ++ic) { VertexNumber next = candidates[ic]; if (!g.adjacent(target, next)) { if (ic != last_pos) { candidates[ic] = last; last = next; } break; } } } // Add the next candidate to the current clique. VertexNumber selected = candidates.back(); current_.push_back(selected); // Only keep additional candidates that are adjacent to the current selected candidate. VertexNumberList next_candidates; for (VertexNumberList::size_type ic = 0; ic < nc; ++ic) { VertexNumber c = candidates[ic]; if (g.adjacent(selected, c)) next_candidates.push_back(c); } // Only keep used vertices that are still adjacent to the current clique. VertexNumberList next_used; for (VertexNumberList::size_type iu = 0; iu < nu; ++iu) { VertexNumber u = used[iu]; if (g.adjacent(selected, u)) next_used.push_back(u); } // Find all maximal cliques that extend the current clique. if (!extend(&next_candidates, &next_used)) return false; // All done with the current selected vertex. Move it to the used list. current_.pop_back(); candidates.pop_back(); --nc; used.push_back(selected); ++nu; // If the target was previously a candidate then mark it as the current target in the used list. if (is_a_candidate) { target = used.back(); target_pos = used.size() - 1; is_a_candidate = false; } // The target now has one less nonadjacency. --count; } // All the candidates for this level have been tried. Accept the current clique if it is maximal. bool status = true; if (used.empty()) { VertexNumbers clique(current_.cbegin(), current_.cend()); status = add_clique(clique); } done_call(); return status; } } // namespace graph } // namespace cavcom
9c432ffce228c8cdc1f034bd5c30a233fc441ff8
447b91b0fa781e6deaa12348ef8346eafa452ee1
/wtplayer/src/WTKeyboardPollInfo.hpp
70b899885401d19cf039c0cba8221701d69b7a7e
[]
no_license
Alstruit/WTExtractor
ae3798ee00c23a84cf86ccda9a69bdb88bff417a
a1812e75184330ace0fea9c7ff6197e7b19fa65f
refs/heads/master
2023-08-14T05:52:32.468283
2021-04-10T22:34:36
2021-04-10T22:34:36
null
0
0
null
null
null
null
UTF-8
C++
false
false
104
hpp
WTKeyboardPollInfo.hpp
#pragma once class WTKeyboardPollInfo { public: int getNextKeyDown(); int isKeyDown(int key); };
cf326aa2b2e4a81efe0c61894bc618eccd3a806c
9388178a14bd88d5a4a5545e2d2cc0246801f7b1
/src/Instruction/GGraphicsInstructionItem.h
8584fef81a8851d3922cc8322827d4a5519b6653
[ "LicenseRef-scancode-warranty-disclaimer" ]
no_license
GaelReinaudi/LabExe
40644a53dc7aa365ed556b70f4f945f40c6f322d
85257d5bd3e4fa5f71a9a2f328d99ca3a89bbd97
refs/heads/master
2020-04-13T23:34:15.876457
2019-08-01T08:28:13
2019-08-01T08:28:13
10,020,827
0
1
null
null
null
null
UTF-8
C++
false
false
316
h
GGraphicsInstructionItem.h
#ifndef GGRAPHICSINSTRUCTIONITEM_H #define GGRAPHICSINSTRUCTIONITEM_H #include <QGraphicsRectItem> class GGraphicsInstructionItem : public QGraphicsRectItem { public: GGraphicsInstructionItem(/*QObject *parent*/); ~GGraphicsInstructionItem(); private: }; #endif // GGRAPHICSINSTRUCTIONITEM_H
a7732f55854fc1881187fb2eda0abcfbf466483f
ca53741ceb8a36a5dad40abdd56fab25435f3562
/Encryption/main.cpp
cafa8984df649b38343ec61a3b844d163895c8fb
[]
no_license
RefugioCornejo/Encriptador
4bc5775831322ca69ef28e460a2d002cae979497
bf2c578cff08187e90a06114c4f83f327cd1d6a9
refs/heads/master
2021-01-01T05:06:43.309141
2016-05-23T22:52:56
2016-05-23T22:52:56
59,523,693
0
1
null
null
null
null
UTF-8
C++
false
false
3,402
cpp
main.cpp
// // main.cpp // Encryption // // Created by Refugio Cornejo on 3/29/16. // Copyright © 2016 Refugio Cornejo. All rights reserved. // #include <iostream> #include <math.h> #include "FileManager.h" #include "Conversor.h" #include "KeyGen.h" #include "Encryption.h" #include <tbb/tbb.h> #include <time.h> int **matrix; int**key; int ** encryptar(int **matrix,int n,int ** key); int main(int argc, const char * argv[]) { FileManager filemanager; Conversor convert; KeyGen keyGen; //***********************GET FILE TO ENCRYPT AND EXPORT TO MEMORY************************************************** filemanager.loadInput("/Users/RCO/Google\ Drive/8vo/Programación\ Concurrente\ y\ Distribuida/Encryption/Encryption/MyFile.txt"); string input= filemanager.getInput(); //cout<<input<<endl; size_t length = input.size(); cout<<length<<" Caracteres "<<endl; double n = sqrt(length); int N = ceil(n); cout<<"Matrix de "<<N<<"x"<<N<<endl; clock_t begin, end; double time_spent; begin = clock(); time_spent = (double)(end - begin) / CLOCKS_PER_SEC; cout<<"Generating matrixes for encryption.."<<endl; matrix=convert.toMatrix(input, N, N); //***********************GENERATE ENCRYPTION KEY & ENCRYPT*********************************************************** key=keyGen.GenerateKey(N); end = clock(); time_spent = (double)(end - begin) / CLOCKS_PER_SEC; cout<<"Execution time : "<<time_spent<<" seconds"<<endl; cout<<"Encrypting....."<<endl; cout<<"Sequential"<<endl; begin = clock(); int **encrypted,**encrypted2; EncryptionManager encrypt(matrix,N,key); encrypted=encrypt.encrypt(matrix, N, N, key); end = clock(); time_spent = (double)(end - begin) / CLOCKS_PER_SEC; cout<<"Execution time : "<<time_spent<<" seconds"<<endl; begin = clock(); encrypted2=encryptar(matrix,N,key); end = clock(); time_spent = (double)(end - begin) / CLOCKS_PER_SEC; cout<<"Execution time : "<<time_spent<<" seconds"<<endl; filemanager.saveFile("/Users/RCO/Google\ Drive/8vo/Programación\ Concurrente\ y\ Distribuida/Encryption/Encryption/Encrypted.txt", encrypted, N, N); filemanager.saveFile("/Users/RCO/Google\ Drive/8vo/Programación\ Concurrente\ y\ Distribuida/Encryption/Encryption/Encrypted2.txt", encrypted2, N, N); // ****************************DECRYPTION**************************************************************************** filemanager.readEncryptedFile("/Users/RCO/Google\ Drive/8vo/Programación\ Concurrente\ y\ Distribuida/Encryption/Encryption/Encrypted2.txt",N); cout<<endl<<endl; int ** crypto = filemanager.getCryptograph(); double**newKey =convert.toDouble(key, N); cout<<encrypt.decrypt(newKey, crypto,N)<<endl; //*****************************Clean up memory....*******************************************************************! convert.destoyMatrix(matrix, N, N); convert.destoyMatrix(key, N, N); convert.destoyMatrix(encrypted, N, N); return 0; } int ** encryptar(int **matrix,int n,int ** key) { tbb::task_scheduler_init init(tbb::task_scheduler_init); //Conversor convert; EncryptionManager encrypt(matrix,n,key); tbb::parallel_for ( tbb::blocked_range2d<size_t>(0, n, n, 0, n, n),encrypt); return encrypt.encryptedMessage; }
af265739c00f6ba526f11d2b1c6d4c3fcae2b5a1
3453dd0498feb4b61f2e48f9277a4184ef2417cc
/src/dynd/compound_div.cpp
6cae32b02ea457beed5672d8c14fb5d1c13b5695
[ "BSL-1.0", "BSD-2-Clause" ]
permissive
insertinterestingnamehere/libdynd
d2290b289bcce4f6ef412f7b31df74ce6b9cbdf4
a0c4fe18cd0772ec52bb090024aadbf6dd7e0ef7
refs/heads/master
2021-05-24T00:08:37.320818
2020-09-11T00:25:53
2020-09-11T00:25:53
22,548,868
0
0
NOASSERTION
2018-12-13T21:13:39
2014-08-02T15:34:03
C++
UTF-8
C++
false
false
291
cpp
compound_div.cpp
// // Copyright (C) 2011-16 DyND Developers // BSD 2-Clause License, see LICENSE.txt // #include <dynd/callables/compound_div_callable.hpp> #include <dynd/compound_arithmetic.hpp> DYND_API nd::callable nd::compound_div = make_compound_arithmetic<nd::compound_div_callable, binop_types>();
09043a8d39243bd84dadaef7d42ab3890b4bcaa1
5a8a21f1b241d13c8294312700728a913e4e9900
/C++/300_LongestIncreasingSubsequence.cpp
dc84a79144fac2f1a2177e2ea1681b11086878f6
[]
no_license
iamzay/leetcode
251d2b4fd5a9be1d3dbb34a0807b23f73938e2df
c1e72b6a78949f01822feeac6db24e793d5530d6
refs/heads/master
2020-12-30T13:29:14.063837
2018-10-15T03:10:56
2018-10-15T03:10:56
91,225,387
1
0
null
null
null
null
UTF-8
C++
false
false
407
cpp
300_LongestIncreasingSubsequence.cpp
class Solution { public: int lengthOfLIS(vector<int>& nums) { int n=nums.size(); if(!n) return 0; // d[n]表示以nums[n]为结尾的最长子串的长度 vector<int> d(n,1); d[0]=1; int _max=1; for(int i=1;i<n;++i){ for(int j=0;j<i;++j){ if(nums[j]<nums[i]) d[i]=max(d[i],1+d[j]); } _max=max(_max,d[i]); } return _max; } };
7f5efcf5c0344c73c43c379b72bd099e4b6b84d9
8bd80baf1e6faab75f258992f08e0c75b328f3d4
/GameEngine/old/resources.h
92b84e85dd3109a4529a304d2a6e8631d6fd4512
[]
no_license
danjr26/game-engine
20fa362bcdfdc84c3da1a1ad12cca3ef53166676
f884a88ce7238b3713e9336ab7c325f53e22fe64
refs/heads/master
2021-04-30T04:53:55.646691
2020-02-02T20:26:13
2020-02-02T20:26:13
121,543,636
0
0
null
null
null
null
UTF-8
C++
false
false
433
h
resources.h
#ifndef RESOURCES_H #define RESOURCES_H #include <string> #include "component.h" class Resource { public: string name; Resource (string in_name); virtual ~Resource (); }; class ResourceManager { private: std::map<string, void*> resources; public: ResourceManager (); ~ResourceManager(); void Add (Resource* in_resource); void Remove (Resource* in_resource); Resource* Get (string in_name); }; #endif
e167b4b9dec0206d9bec2325ae0240e845951f6f
6854bf6cf47c68de574f855af19981a74087da7d
/0257 - Binary Tree Paths/cpp/main.cpp
a9aea7e32972ed2d14723bd044a8f52dd130642b
[ "MIT" ]
permissive
xiaoswu/Leetcode
5a2a864afa3b204badf5034d2124b104edfbbe8e
e4ae8b2f72a312ee247084457cf4e6dbcfd20e18
refs/heads/master
2021-08-14T23:21:04.461658
2021-08-10T06:15:01
2021-08-10T06:15:01
152,703,066
5
0
null
null
null
null
UTF-8
C++
false
false
1,275
cpp
main.cpp
// // main.cpp // 257 - Binary Tree Paths // // Created by ynfMac on 2019/11/25. // Copyright © 2019 ynfMac. All rights reserved. // #include <iostream> #include <vector> using namespace std; struct TreeNode { int val; TreeNode *left; TreeNode *right; TreeNode(int x) : val(x), left(NULL), right(NULL) {} }; class Solution { public: vector<string> binaryTreePaths(TreeNode* root) { vector<string> res; allPaths(root, res, ""); return res; } private: void allPaths(TreeNode *node,vector<string>&res, string s){ if (node == nullptr) { return; } s.append(to_string(node->val)); if (node->left == nullptr && node->right == nullptr) { res.push_back(s); return; } else { s.append("->"); } if (node->left) { allPaths(node->left, res, s); } if (node->right) { allPaths(node->right, res, s); } } }; int main(int argc, const char * argv[]) { TreeNode *node = new TreeNode(3); node->left = new TreeNode(5); node->right = new TreeNode(6); Solution().binaryTreePaths(node); std::cout << "Hello, World!\n"; return 0; }
81001b9b718a9c1f8e84cc1c02d4d97108e235db
f3b46ac9ea25cd3a362fcff4ec95a785482dcc42
/lesson01/src/some_math.h
ae4b68adc5cbce070d3700b3b80dc442bb193549
[ "MIT" ]
permissive
PolarNick239/CPPExercises2021
1d616abc39e7ec8b201d5739d8739762c516b5e4
a9768507e6c5d87792d8c09b9ae951dac7e041ec
refs/heads/main
2023-08-04T09:37:00.686848
2021-09-21T21:16:51
2021-09-21T21:16:51
404,235,872
0
1
MIT
2021-09-14T19:35:38
2021-09-08T06:27:56
null
UTF-8
C++
false
false
201
h
some_math.h
#pragma once #include <vector> int fibbonachiRecursive(int n); int fibbonachiFast(int n); double solveLinearAXB(double a, double b); std::vector<double> solveSquare(double a, double b, double c);
d7b96dd42a124185d3f50d3b8b9f30445d44792c
0981b963c63f4aa673e99c668f5c8c8d51de89c4
/11631.cpp
08bd8b55ab9e273ed7124b2e233cfdc6874dba7f
[ "MIT" ]
permissive
felikjunvianto/kfile-uvaoj-submissions
f21fa85463d6f1bde317c513d670139cfddb9483
5bd8b3b413ca8523abe412b0a0545f766f70ce63
refs/heads/master
2021-01-12T15:57:58.583203
2016-10-06T18:12:35
2016-10-06T18:12:35
70,179,293
0
0
null
null
null
null
UTF-8
C++
false
false
1,282
cpp
11631.cpp
#include <cstdio> #include <cmath> #include <iostream> #include <string> #include <cstring> #include <algorithm> #include <vector> #include <utility> #include <stack> #include <queue> #define fi first #define se second #define pb push_back #define mp make_pair #define pi 2*acos(0.0) #define eps 1e-9 #define PII pair<int,int> #define PDD pair<double,double> using namespace std; int node,edge,x,total; int par[200100]; pair<int,PII> edgelist[200100]; int find(int i) { if(par[i]==-1) par[i]=i; else { int ti=i; while(par[ti]!=ti) ti=par[ti]; par[i]=ti; } return(par[i]); } bool is_union(int a,int b) { if(find(a)!=find(b)) { par[par[a]]=par[b]; return false; } return true; } int kruskal() { memset(par,-1,sizeof(par)); sort(edgelist,edgelist+edge); int cost=0; for(int x=0;x<edge;x++) if(!is_union(edgelist[x].se.fi,edgelist[x].se.se)) cost+=edgelist[x].fi; return(cost); } int main() { do { scanf("%d %d",&node,&edge); if(node+edge==0) break; total=0; for(x=0;x<edge;x++) { scanf("%d %d %d",&edgelist[x].se.fi,&edgelist[x].se.se,&edgelist[x].fi); total+=edgelist[x].fi; } printf("%d\n",total-kruskal()); }while(node+edge!=0); return 0; }
fa34e61bd324e679531f2a1a6bb7af92a821799e
7937dad06fa38714f49bbf33a12cb9153fb4d5cb
/z/compiler/lang.ZScript/lang.syntax/program.h
d1f6d818fccbcf703b60489196fc2ec17cac42e0
[ "MIT" ]
permissive
ZacharyWesterman/zing
ddd1bc8da15a9c3f1b6b8e4ab58bb2e9c7d03d2e
735cf9a69913949f4088750332d1626310bb8d32
refs/heads/master
2021-06-02T02:23:00.222533
2019-12-23T04:56:38
2019-12-23T04:56:38
77,483,315
0
0
MIT
2019-12-23T04:56:40
2016-12-27T21:20:49
C++
UTF-8
C++
false
false
3,393
h
program.h
/** * File: program.h * Namespace: z::script * Description: Implementation of the lexer's * syntax generating member functions. * This file should NOT be included * in a project. Include "lexer.h" * instead,and put this file in the * "syntaxRules" folder. * * * Author: Zachary Westerman * Email: zacharywesterman@yahoo.com * Last modified: 21 Aug. 2017 **/ #pragma once #ifndef PROGRAM_H_INCLUDED #define PROGRAM_H_INCLUDED #include <z/script/compiler/syntaxRule.h> namespace z { namespace script { namespace compiler { class program : public syntaxRule { public: ~program() {} bool apply(core::array< phrase_t* >*, int, core::array<error>*); }; bool program::apply(core::array< phrase_t* >* phrase_nodes, int index, core::array<error>* error_buffer) { if (phrase_nodes->is_valid(index+1) && (phrase_nodes->at(index)->type == PROGRAM) && ((phrase_nodes->at(index+1)->type == VARIABLE_DECL) || (phrase_nodes->at(index+1)->type == TYPEVAR_DECL) || (phrase_nodes->at(index+1)->type == FUNC_PROTOTYPE) || (phrase_nodes->at(index+1)->type == FUNCTION_DECL) || (phrase_nodes->at(index+1)->type == TYPEDECL) || (phrase_nodes->at(index+1)->type == EXTERNALDECL) || (phrase_nodes->at(index+1)->type == SHAREDDECL) || (phrase_nodes->at(index+1)->type == SUBROUTINE_DECL) ) ) { phrase_nodes->at(index+1)->parent = phrase_nodes->at(index); phrase_nodes->at(index)->children.add(phrase_nodes->at(index+1)); phrase_nodes->remove(index+1); return true; } else if ((phrase_nodes->at(index)->type == VARIABLE_DECL) || (phrase_nodes->at(index)->type == TYPEVAR_DECL) || (phrase_nodes->at(index)->type == FUNC_PROTOTYPE) || (phrase_nodes->at(index)->type == FUNCTION_DECL) || (phrase_nodes->at(index)->type == TYPEDECL) || (phrase_nodes->at(index)->type == EXTERNALDECL) || (phrase_nodes->at(index)->type == SHAREDDECL) || (phrase_nodes->at(index)->type == SUBROUTINE_DECL) ) { phrase_t* pIndex = phrase_nodes->at(index); phrase_t* node = new phrase_t(*pIndex, PROGRAM); node->type = PROGRAM; pIndex->parent = node; node->children.add(pIndex); phrase_nodes->at(index) = node; return true; } else if (phrase_nodes->at(index)->type != PROGRAM) { if (error_buffer->size() == 0) error_buffer->add(newError(phrase_nodes->at(index), "Syntax error")); } return false; } } } } #endif // PROGRAM_H_INCLUDED
02a40c3f9855d891c50ae7d3e110a1b16e9362de
288840a48549582b64d2eb312c2e348d588b278b
/src/pktk/MString.h
aebfb954ef81e88ae909b0a07581d7ad3c9ed0e3
[]
no_license
mikegogulski/Mephbot
590672d2cf859b2b125514d4f581b9543894ff46
efa1e17a447300b763111f0993a6bc91b6a7b0d4
refs/heads/master
2016-09-06T02:05:43.197714
2011-12-10T20:07:46
2011-12-10T20:07:46
1,107,469
9
5
null
null
null
null
UTF-8
C++
false
false
13,045
h
MString.h
/* MString - Dynamic string data type library Copyright (C) 2000 Jesse L. Lovelace This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ // Section added by Mike Gogulski <mike@gogulski.com> 4 Aug 2002 #pragma once #include <windows.h> #include <stdio.h> #include <stdlib.h> #include <fstream.h> #include <iostream.h> #define CString MString // End Mike Gogulski additions #ifndef MSTRING_H #define MSTRING_H #ifdef __cplusplus // we only want this for C++ code /* MString by Jesse Lovelace (mentat) jllovela@eos.ncsu.edu (MString began as GString but was changed to remain compatible with gtk+'s GString data type.) http://www4.ncsu.edu/~jllovela/MString/ MString is a string library that uses dynamically sizable character strings. To do this I used linked lists instead of dynamic arrays for various reasons (one being the problems that arrays of dynamic arrays cause). MString is designed to maintain compatibility with the MFC CString library. MString should be 99% compatible if you exclude the windoze specific operations (including buffer access) and the .Format commands. For the full documentation see functions.txt MString also includes the MStringArray class. MStringArray follows the same scheme as CStringArray from MFC. CStringArrays are also linked lists for now (I may change them to dynamically allocated arrays in the future). Please submit any suggestions/bugs/comments to jllovela@eos.ncsu.edu Enjoy. Thanks to: Dingo - pointer debugging, Rask - math and Trim(char ch), Botch - debugging and advice, Antiloop - for phat grooves. (Last modified September 4, 2000) */ const int MAX_PRECISION = 9; //due to bad double to string code. const char MString_VERSION[8] = "0.61"; //typedef const char * LPCSTR; #include <fstream.h> class MNode; struct MStringData { char * pcStr; int precision; int iBufLen; // length of buffer minus 1 for null terminator int iBufferInUse; }; class MString { //Begin overloaded stream functions ----------------------- friend ostream& operator<< (ostream& out, const MString& string); // PRE: out is a valid output stream, string is a valid MString // POST: contents of string are sent to stream out. friend istream& operator>> (istream& in, MString& string); // PRE: in is a valid input stream, string is a valid MString // POST: characters in input stream are stored in string. friend istream& getline(istream& in, MString& string); // PRE: in is valid input stream, sting is a valid MString // POST: characters up to (and including) the newline are stored // in string. // EX: getline(in, string); //End overloaded stream functions ------------------------- public: //Begin Constructors -------------------------------------- MString(); // Info: construct empty MString MString(const MString& stringSrc); // Info: copy constructor // PRE: stringSrc is a valid MString object. // POST: new object is a deep copy of stringSrc. MString(const char ch, int nRepeat = 1); // Info: construct with single character repeated nRepeat times // PRE: ch is a valid ascii character and non null. // POST: new object contains ch repeated nRepeat times. MString(const char* string); // PRE: string is a valid null-terminated string. // POST: new object contains the data from string minues null. // Added by Bruce Riggins MString(const char * string, int nLength); // Info: copy with maximum length // PRE: string is a valid null-terminated string, nLength>0 // POST: new object contains the data from string minues null // End addition MString(const int num); // NEW CODE, PLEASE HELP DEBUG (v. 60) MString(double num); ~MString(); // Info: destructor //End Constructors ---------------------------------------- //Begin Test Functions ------------------------------------ void testG(); // Info: uses cout to display the data and pointer of each // Node. MString GetGVersion(); // Info: returns the current version of MString. // POST: returns an object of type MString containing version info MString ReturnLicense(); // Info: returns license info // POST: returns an object of type MString containing license info //End Test Functions -------------------------------------- //Begin Precision Functions ------------------------------- void SetPrecision(int num); // PRE: num <= MAX_PRECISION // POST: double conversion precision changed to num. int GetPrecision() const; // POST: returns an int type equal to the current double precision. //End Precision Functions --------------------------------- //Begin String as Array Functions ------------------------- int GetLength() const; // Info: returns the length of the string excluding null bool IsEmpty() const; // Info: nonzero if string has 0 length void Empty(); // Info: empty's the string and free's memory char GetAt(int nIndex) const; // Info: returns char at index char operator [](int nIndex) const; // Info: operator overload of GetAt(int nIndex) char& operator [](int nIndex); // Info: use like SetAt, myString[0] = 'M'; void SetAt(int nIndex, char ch); // Info: sets the character at nIndex //End String as Array Functions --------------------------- //Begin added operators by Bruce Riggins --------------- operator const char * () const; //End added operators by Bruce Riggins ----------------- //Begin Assignment/Concatination operators ---------------- const MString& operator =(const MString& stringSrc); //Idea from CString const MString& operator =(char ch); const MString& operator =(const char* string); const MString& operator =(int num); //Original MString const MString& operator =(double num); //Original MString const MString& operator =(float num); //Original MString const MString& operator +=(const MString& string); //Idea from CString const MString& operator +=(char ch); const MString& operator +=(char* string); const MString& operator +=(int num); //Original MString const MString& operator +=(double num); //Original MString const MString& operator +=(float num); //Original MString void Cat(char ch); //Not implimented yet. void Cat(char* string); void Cat(MString& string); friend MString operator +(const MString& string1, const MString& string2); friend MString operator +(const MString& string, char ch); friend MString operator +(char ch, const MString& string); friend MString operator +(const MString& string1, char* string2); friend MString operator +(char* string1, const MString& string2); friend MString operator +(int num, const MString& string); friend MString operator +(const MString& string, int num); //End Assignment/Concatination operators ------------------ //Begin Comparison operators ------------------------------ friend bool operator==(const MString& s1, const MString& s2); //Idea from CString friend bool operator==(const MString& s1, const char* s2); friend bool operator==(const char* s1, const MString& s2); friend bool operator!=(const MString& s1, const MString& s2); //Idea from CString friend bool operator!=(const MString& s1, char* s2); friend bool operator!=(char* s1, const MString& s2); friend bool operator <(const MString& s1, const MString& s2); //Idea from CString friend bool operator <(const MString& s1, char* s2); friend bool operator <(char* s1, const MString& s2); friend bool operator >(const MString& s1, const MString& s2); //Idea from CString friend bool operator >(const MString& s1, char* s2); friend bool operator >(char* s1, const MString& s2); friend bool operator <=(const MString& s1, const MString& s2); //Idea from CString friend bool operator <=(const MString& s1, char* s2); friend bool operator <=(char* s1, const MString& s2); friend bool operator >=(const MString& s1, const MString& s2); //Idea from CString friend bool operator >=(const MString& s1, char* s2); friend bool operator >=(char* s1, const MString& s2); int Compare(const char* string) const; //Idea from CString int Compare(const MString& string) const; //MString original int CompareNoCase(const char* string) const; //Idea from CString int Collate(char* string) const; //Idea from CString int CollateNoCase(char* string) const; //Idea from CString //End Comparison operators -------------------------------- //Begin Extraction operators ------------------------------ MString Mid(int nFirst) const; //Idea from CString MString Mid(int nFirst, int nCount) const; //Idea from CString MString Left(int nCount) const; //Idea from CString MString Right(int nCount) const; //Idea from CString MString SpanIncluding(char* string) const; //Idea from CString MString SpanExcluding(char* string) const; //Idea from CString char* ToChar(int nStart = 0); // PRE: nStart is >0 and < GetLength(). // POST: returns a pointer to a new null-terminated character array // that is a copy of the infomation in the MString. int ToInt(int nStart = 0); // PRE: nStart is > 0 and < GetLength(). // POST: returns an integer created from the numbers starting at nStart // Other: ToInt does not check to see if the string of numbers contained // in the MString object is to long for type int. ToInt converts // a sequence of ASCII values 48 thru 57 ('0' to '9') non-number // values result in a return from the function. // EX: if myString is of type MString containing "12345C1232" // myString.ToInt(0) returns 12345 // myString.ToInt(1) returns 2345 //End Extraction operators -------------------------------- //Begin Other Conversions --------------------------------- void MakeUpper(); //Idea from CString void MakeLower(); //Idea from CString void MakeReverse(); //Idea from CString int Replace(char chOld, char chNew); //Idea from CString int Replace(char* stringOld, char* stringNew); //Idea from CString int Remove(char ch); //Idea from CString int Insert(int nIndex, char ch); //Idea from CString int Insert(int nIndex, char* string); //Idea from CString int Delete(int nIndex, int nCount = 1); //Idea from CString //Research Format // Additions by Bruce Riggins 11/14/00 void Format(char * sFormat, ...); // End additions by Bruce Riggins 11/14/00 void Trim(); //Original MString void Trim(char ch); //Original MString void Trim(char* string); void TrimLeft(); //Idea from CString void TrimLeft(char ch); void TrimLeft(char* string); void TrimRight(); //Idea from CString void TrimRight(char ch); void TrimRight(char* string); //End Other Conversions ----------------------------------- //Research FormatMessage //Begin Searching ----------------------------------------- int Find(char ch, int nStart = 0) const; //Idea from CString int Find(char* string, int nStart = 0) const; //Idea from CString int ReverseFind(char ch) const; //Idea from CString int ReverseFind(char* string) const; //MString original int FindOneOf(char* string) const; //Idea from CString //End Searching ------------------------------------------- //Buffer Access and Windows-Specific items not included. //Begin Buffer Access ------------------------------------- // Additions by Bruce Riggins 11/7/00 // Access to string implementation buffer as "C" character array char * GetBuffer(int nMinBufLength); //Idea from CString void ReleaseBuffer(int nNewLength = -1); //Idea from CString // char * GetBufferSetLength(int nNewLength); //Idea from CString // void FreeExtra(); //Idea from CString // Use LockBuffer/UnlockBuffer to turn refcounting off char * LockBuffer(); //Idea from CString void UnlockBuffer(); //Idea from CString // End of BR additions //End Buffer Access --------------------------------------- private: MNode* GetPointerAt(int nIndex); void deallocate(MNode *p); // added by Bruce Riggins char * pcStr; MNode *headMNode; MNode *tailMNode; //New for .3b int precision; int iBufLen; // length of buffer minus 1 for null terminator int iBufferInUse; }; #endif // __cplusplus #endif
c5f1c5785e7b14fd4d32e1069f9a849904852bbc
f061007f1bd90578ec2aac3b18f262b13b67f8a5
/AVL_tree/Node.h
a4e96516e8da5fe2f779436972264b4fc30d1898
[]
no_license
nevaeh511/DataStructures
779927b657a99e0262149d4fa384887a54b2e5d3
481a6c7a3cf161fd6ba05d41f9e83c3ad2e80e8e
refs/heads/master
2020-12-24T13:44:13.441326
2016-04-05T19:40:27
2016-04-05T19:40:27
32,424,843
0
0
null
null
null
null
UTF-8
C++
false
false
360
h
Node.h
// Aaron Merrill // Course: CS 2420 section: 001 #include<cstdlib> #include<algorithm> using namespace std; struct node { //nodes data value int data; //pointer to the left child node node* left; //pointer to the right child node node* right; int height; node::node(int val) { data = val; left = nullptr; right = nullptr; height = 1; } };
91905095e8195dc9b09c34c90fac931d525dfa2d
fb7efe44f4d9f30d623f880d0eb620f3a81f0fbd
/components/multidevice/service/multidevice_service_unittest.cc
489ae4ca651383b8e16aa57fe905de4e358415db
[ "BSD-3-Clause" ]
permissive
wzyy2/chromium-browser
2644b0daf58f8b3caee8a6c09a2b448b2dfe059c
eb905f00a0f7e141e8d6c89be8fb26192a88c4b7
refs/heads/master
2022-11-23T20:25:08.120045
2018-01-16T06:41:26
2018-01-16T06:41:26
117,618,467
3
2
BSD-3-Clause
2022-11-20T22:03:57
2018-01-16T02:09:10
null
UTF-8
C++
false
false
7,282
cc
multidevice_service_unittest.cc
// Copyright 2017 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // #include "multidevice_service.h" #include <memory> #include "base/barrier_closure.h" #include "base/run_loop.h" #include "components/multidevice/service/public/interfaces/constants.mojom.h" #include "components/multidevice/service/public/interfaces/device_sync.mojom.h" #include "mojo/public/cpp/bindings/binding.h" #include "services/service_manager/public/cpp/service_test.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" namespace { const char kServiceTestName[] = "multidevice_service_unittest"; enum class MultiDeviceServiceActionType { FORCE_ENROLLMENT_NOW, FORCE_SYNC_NOW }; } // namespace namespace multidevice { class MultiDeviceServiceTest : public service_manager::test::ServiceTest { public: class DeviceSyncObserverImpl : public device_sync::mojom::DeviceSyncObserver { public: DeviceSyncObserverImpl( device_sync::mojom::DeviceSyncObserverRequest request) : binding_(this, std::move(request)) {} void OnEnrollmentFinished(bool success) override { if (success) { num_times_enrollment_finished_called_.success_count++; } else { num_times_enrollment_finished_called_.failure_count++; } on_callback_invoked_->Run(); } void OnDevicesSynced(bool success) override { if (success) { num_times_device_synced_.success_count++; } else { num_times_device_synced_.failure_count++; } on_callback_invoked_->Run(); } // Sets the necessary callback that will be invoked upon each interface // method call in order to return control to the test. void SetOnCallbackInvokedClosure(base::Closure* on_callback_invoked) { on_callback_invoked_ = on_callback_invoked; } int GetNumCalls(MultiDeviceServiceActionType type, bool success_count) { switch (type) { case MultiDeviceServiceActionType::FORCE_ENROLLMENT_NOW: return num_times_enrollment_finished_called_.CountType(success_count); case MultiDeviceServiceActionType::FORCE_SYNC_NOW: return num_times_device_synced_.CountType(success_count); default: NOTREACHED(); } return 0; } private: struct ObserverCallbackCount { int success_count = 0; int failure_count = 0; int CountType(bool success) { return success ? success_count : failure_count; } }; mojo::Binding<device_sync::mojom::DeviceSyncObserver> binding_; base::Closure* on_callback_invoked_ = nullptr; ObserverCallbackCount num_times_enrollment_finished_called_; ObserverCallbackCount num_times_device_synced_; }; MultiDeviceServiceTest() : ServiceTest(kServiceTestName){}; ~MultiDeviceServiceTest() override{}; void SetUp() override { ServiceTest::SetUp(); connector()->BindInterface(multidevice::mojom::kServiceName, &device_sync_ptr_); } void AddDeviceSyncObservers(int num) { device_sync::mojom::DeviceSyncObserverPtr device_sync_observer_ptr; for (int i = 0; i < num; i++) { device_sync_observer_ptr = device_sync::mojom::DeviceSyncObserverPtr(); observers_.emplace_back(base::MakeUnique<DeviceSyncObserverImpl>( mojo::MakeRequest(&device_sync_observer_ptr))); device_sync_ptr_->AddObserver(std::move(device_sync_observer_ptr)); } } void MultDeviceServiceAction(MultiDeviceServiceActionType type) { base::RunLoop run_loop; base::Closure closure = base::BarrierClosure( static_cast<int>(observers_.size()), run_loop.QuitClosure()); for (auto& observer : observers_) { observer->SetOnCallbackInvokedClosure(&closure); } switch (type) { case MultiDeviceServiceActionType::FORCE_ENROLLMENT_NOW: device_sync_ptr_->ForceEnrollmentNow(); break; case MultiDeviceServiceActionType::FORCE_SYNC_NOW: device_sync_ptr_->ForceSyncNow(); break; default: NOTREACHED(); } run_loop.Run(); } device_sync::mojom::DeviceSyncPtr device_sync_ptr_; std::vector<std::unique_ptr<DeviceSyncObserverImpl>> observers_; }; TEST_F(MultiDeviceServiceTest, MultipleCallTest) { AddDeviceSyncObservers(2); MultDeviceServiceAction(MultiDeviceServiceActionType::FORCE_ENROLLMENT_NOW); EXPECT_EQ(1, observers_[0]->GetNumCalls( MultiDeviceServiceActionType::FORCE_ENROLLMENT_NOW, true /* success_count */)); EXPECT_EQ(1, observers_[1]->GetNumCalls( MultiDeviceServiceActionType::FORCE_ENROLLMENT_NOW, true /* success_count */)); EXPECT_EQ(0, observers_[0]->GetNumCalls( MultiDeviceServiceActionType::FORCE_ENROLLMENT_NOW, false /* success_count */)); EXPECT_EQ(0, observers_[1]->GetNumCalls( MultiDeviceServiceActionType::FORCE_ENROLLMENT_NOW, false /* success_count */)); MultDeviceServiceAction(MultiDeviceServiceActionType::FORCE_SYNC_NOW); EXPECT_EQ(1, observers_[0]->GetNumCalls( MultiDeviceServiceActionType::FORCE_SYNC_NOW, true /* success_count */)); EXPECT_EQ(1, observers_[1]->GetNumCalls( MultiDeviceServiceActionType::FORCE_SYNC_NOW, true /* success_count */)); EXPECT_EQ(0, observers_[0]->GetNumCalls( MultiDeviceServiceActionType::FORCE_SYNC_NOW, false /* success_count */)); EXPECT_EQ(0, observers_[1]->GetNumCalls( MultiDeviceServiceActionType::FORCE_SYNC_NOW, false /* success_count */)); MultDeviceServiceAction(MultiDeviceServiceActionType::FORCE_ENROLLMENT_NOW); EXPECT_EQ(2, observers_[0]->GetNumCalls( MultiDeviceServiceActionType::FORCE_ENROLLMENT_NOW, true /* success_count */)); EXPECT_EQ(2, observers_[1]->GetNumCalls( MultiDeviceServiceActionType::FORCE_ENROLLMENT_NOW, true /* success_count */)); EXPECT_EQ(0, observers_[0]->GetNumCalls( MultiDeviceServiceActionType::FORCE_ENROLLMENT_NOW, false /* success_count */)); EXPECT_EQ(0, observers_[1]->GetNumCalls( MultiDeviceServiceActionType::FORCE_ENROLLMENT_NOW, false /* success_count */)); MultDeviceServiceAction(MultiDeviceServiceActionType::FORCE_SYNC_NOW); EXPECT_EQ(2, observers_[0]->GetNumCalls( MultiDeviceServiceActionType::FORCE_SYNC_NOW, true /* success_count */)); EXPECT_EQ(2, observers_[1]->GetNumCalls( MultiDeviceServiceActionType::FORCE_SYNC_NOW, true /* success_count */)); EXPECT_EQ(0, observers_[0]->GetNumCalls( MultiDeviceServiceActionType::FORCE_SYNC_NOW, false /* success_count */)); EXPECT_EQ(0, observers_[1]->GetNumCalls( MultiDeviceServiceActionType::FORCE_SYNC_NOW, false /* success_count */)); } } // namespace multidevice
bd0a5dbb8d6be5249eb003b89fcde1fa8966ddd1
a3d6556180e74af7b555f8d47d3fea55b94bcbda
/third_party/blink/renderer/modules/webgl/webgl_shared_platform_3d_object.cc
32bc3f908399d2c01589df8a6975225c32e8e579
[ "LGPL-2.0-or-later", "LicenseRef-scancode-warranty-disclaimer", "LGPL-2.1-only", "GPL-1.0-or-later", "GPL-2.0-only", "LGPL-2.0-only", "BSD-2-Clause", "LicenseRef-scancode-other-copyleft", "BSD-3-Clause", "MIT", "Apache-2.0" ]
permissive
chromium/chromium
aaa9eda10115b50b0616d2f1aed5ef35d1d779d6
a401d6cf4f7bf0e2d2e964c512ebb923c3d8832c
refs/heads/main
2023-08-24T00:35:12.585945
2023-08-23T22:01:11
2023-08-23T22:01:11
120,360,765
17,408
7,102
BSD-3-Clause
2023-09-10T23:44:27
2018-02-05T20:55:32
null
UTF-8
C++
false
false
842
cc
webgl_shared_platform_3d_object.cc
// Copyright 2015 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "third_party/blink/renderer/modules/webgl/webgl_shared_platform_3d_object.h" #include "third_party/blink/renderer/modules/webgl/webgl_rendering_context_base.h" namespace blink { WebGLSharedPlatform3DObject::WebGLSharedPlatform3DObject( WebGLRenderingContextBase* ctx) : WebGLSharedObject(ctx), object_(0) {} void WebGLSharedPlatform3DObject::SetObject(GLuint object) { // SetObject may only be called when this container is in the // uninitialized state: object==0 && marked_for_deletion==false. DCHECK(!object_); DCHECK(!MarkedForDeletion()); object_ = object; } bool WebGLSharedPlatform3DObject::HasObject() const { return object_ != 0; } } // namespace blink
117e914679bcfdbfb496717aa898a1c91ccdb0a0
56d9d4ecaa194e33f69cc77eaf1f3f767367b486
/7_longestNoReapeatingLength.cpp
6f7820088d6d40038f5d124ae0b14c283d52bc6c
[ "MIT" ]
permissive
Cheemion/Leetcode
cbd6b70219cc1c9bf50e7ae10726d2a0b495fd4b
e0fee06896b13b1efb11338c383dafd5d0dfed19
refs/heads/main
2023-03-28T02:43:24.035758
2021-03-23T08:39:09
2021-03-23T08:39:09
350,611,550
0
0
null
null
null
null
UTF-8
C++
false
false
864
cpp
7_longestNoReapeatingLength.cpp
#include<iostream> #include<vector> #include<unordered_set> using std::vector; using std::unordered_set; class Solution { public: /** * @param arr int整型vector the array * @return int整型 */ int maxLength(vector<int>& arr) { if(arr.size() < 2) return arr.size(); int i = 0; int j = 0; int res = 0; std::unordered_set<int> set; while(j < arr.size()) { if(set.find(arr[j]) != set.end()) { // include set.erase(arr[i]); i++; } else { set.insert(arr[j]); j++; } res = std::max(res, j - i); } return res; } }; int main(){ Solution s; vector<int> ints = {1, 2, 3, 4, 1, 2, 2}; std::cout << s.maxLength(ints) << std::endl; return 0; }
9dc97df2580ac2acd468d1cd2e0d5be39793579e
e02e993083e57b8f7c5e657d354ab6a1f6b98db4
/Translator/socket.hpp
fc8a1b5e07d3c8c3f337f3439086c46775d953bc
[]
no_license
NintyS/NetworkInQt
16d5513c04214a82b8fae3c75b4f8c38d8e32b2b
149d551a3e91399f0960b0c37866745f213566e9
refs/heads/main
2023-03-04T08:17:10.863754
2021-02-12T10:42:12
2021-02-12T10:42:12
336,815,352
0
0
null
null
null
null
UTF-8
C++
false
false
273
hpp
socket.hpp
#ifndef SOCKET_HPP #define SOCKET_HPP #include <QTcpSocket> #include <QObject> class Socket : public QObject { Q_OBJECT public: explicit Socket(QObject *parent = nullptr); void Connect(); signals: private: QTcpSocket *socket; }; #endif // SOCKET_HPP
7f9650691bdc6f34c49b8783642c9acc105f7634
cd96666e1b57299f8544afaa294b7143ef25ad60
/Brick.h
1565751121cccff019299367a5580d1cef8bc998
[]
no_license
KolololoPL/Arkanoid
d30ae82c3f9a3634f7453130f70077b3df7f1df6
421230e7620006e2bc6bdca2fa1c3d592e0d4719
refs/heads/master
2021-01-22T14:39:07.791470
2015-09-11T06:21:10
2015-09-11T06:21:10
42,291,392
0
0
null
null
null
null
UTF-8
C++
false
false
421
h
Brick.h
#ifndef BRICK_H #define BRICK_H #include "Collider.h" #include "Vector2d.h" #include "Config.h" #include "MySDL.h" class Brick : public Collider { private: SDL_Surface* sprite; Vector2d position; SDL_Rect rect; short lives, id; public: Brick(SDL_Surface*, Vector2d, short, short); ~Brick(); void Draw(); void SetSpriteRect(); short GetId(); short GetLives(); void OnCollision(Collider* const); }; #endif
4712b0cd730c32c6d106aeb95e0c9acfe4a77cdf
cd0725fbb3fb21e0cea76d8c63f365ee05b50b7c
/TEvent.cpp
2a8702eb95f527dab79df5bfd2950970b4c8222f
[]
no_license
nastja123456789/pro3
7bc2c050da212c77cba6189a81211027ddeb9b87
d6e7589bce94f6e409df78cbb0a807ab2e7df11f
refs/heads/main
2023-02-09T21:14:45.961293
2020-12-22T05:14:41
2020-12-22T05:14:41
323,527,283
0
0
null
null
null
null
UTF-8
C++
false
false
550
cpp
TEvent.cpp
#include "TEvent.h" TEvent::TEvent( char *s) { name = s; } bool TEvent::inDate( const QDate &st, const QDate &en ) { return true; } void TEvent::getDescr( char *s ) { strcpy( s, "Всегда выполняется" ); } void TEvent::getStringTime( char *s ) { sprintf( s,"Каждый час"); } void TEvent::setName(QString name) { this->name = name; } QString TEvent::getName() { return name; } bool TEvent::compare(TEvent *&ev) { return this->getName() < ev->getName(); }
54f7b179e1265a5365210d5f7e520d749a22f341
d0d27c784e09efca99e370c8c42b15d2f0ab0b8a
/02_Class/02_Class/Source.cpp
474b4aa77c0bd619f936d69a51c1627725c95773
[]
no_license
mhmmdd/Cpp-Training-Example
9b20784ec003579a409ee42d29892cf2acc6673b
0f926c29744c234caacd3076bd6dba71680a4e1e
refs/heads/master
2021-04-27T20:54:45.633774
2018-03-04T16:25:04
2018-03-04T16:25:04
122,387,876
0
0
null
null
null
null
ISO-8859-9
C++
false
false
955
cpp
Source.cpp
#include <iostream> class Log { public: const int logLevelError = 0; const int logLevelWarning = 1; const int logLevelInfo = 2; private: int logLevel = logLevelError; public: void setLogLevel(int level) { this->logLevel = level; } void error(const char* message) { if(logLevel >= logLevelError) { std::cout << "[ERROR]: " << message << std::endl; } } void info(const char* message) { if (logLevel >= logLevelInfo) { std::cout << "[INFO]: " << message << std::endl; } } void warn(const char* message) { if (logLevel >= logLevelWarning) { std::cout << "[WARNING]: " << message << std::endl; } } }; int main() { Log log; log.setLogLevel(log.logLevelWarning); log.warn("Hello!"); int max = 90; // İçerik değiştirilemez //const int* a = new int; //*a = 2; // Adres değiştirilemez int *const a = new int; *a = 2; //a = (int*) &max; *a = 4; std::cout << *a << std::endl; std::cin.get(); }
9d7fe06697c9342d8308ac6a948f1781d83138c2
e019c932d38c6da8cd8f427f3752d167a67a1038
/scientistrepository.cpp
2a7a9fe3a5e49a21c2807b9cb231a0eb7b618131
[]
no_license
AndriM/Vika2
f81f7490fa75a430297ff25887ac0a54f5bc262e
93eadf5c7b0d59f291ce95e71f40a735e227cc6a
refs/heads/master
2021-01-23T14:05:10.013249
2014-12-09T23:19:02
2014-12-09T23:19:02
null
0
0
null
null
null
null
UTF-8
C++
false
false
7,942
cpp
scientistrepository.cpp
#include "scientistrepository.h" ScientistRepository::ScientistRepository(std::string fname) { filename = fname; delimiter = '\t'; std::ifstream scientistFile; try { scientistFile.open(filename.c_str(),std::ios::in); } catch(...) { // Ignore the error, the file is non existent and will be created next time we save. } scientistList = std::list<Scientist>(); if(scientistFile.is_open()) { std::string lineToRead = ""; // Load all records into memory while(std::getline(scientistFile,lineToRead)) { Scientist scientist = Scientist(); std::vector<std::string> fields = util::split(lineToRead,delimiter); scientist.name = fields.at(0); scientist.dateOfBirth = fields.at(1); scientist.dateOfDeath = fields.at(2); scientist.gender = fields.at(3); scientistList.push_back(scientist); } scientistFile.close(); } } ScientistRepository::~ScientistRepository() { } QSqlDatabase ScientistRepository::openDatabase() { QString connectionName = "DatabaseConnection"; QSqlDatabase db; if(QSqlDatabase::contains("DatabaseConnection")) { db = QSqlDatabase::database("DatabaseConnection"); } else { db = QSqlDatabase::addDatabase("QSQLITE", "DatabaseConnection"); QString dbName = "science_db.sqlite"; db.setDatabaseName(dbName); db.open(); } return db; } void ScientistRepository::connect(int sID, int cID) { scientistDB = openDatabase(); scientistDB.open(); QSqlQuery query(scientistDB); query.exec(QString("INSERT INTO Joined (s_ID, c_ID) VALUES (%1,%2);") .arg(sID) .arg(cID)); scientistDB.close(); } std::list<Scientist> ScientistRepository::connectedScientists(int sID) { std::list<Scientist> scientist = std::list<Scientist>(); Scientist s = Scientist(); scientistDB = openDatabase(); scientistDB.open(); QSqlQuery query(scientistDB); QString s_ID = QString::number(sID); query.exec(QString("SELECT ID, Name FROM scientists JOIN Joined ON Joined.s_ID = scientists.ID WHERE Joined.c_ID = %1") .arg(sID)); while(query.next()){ s.name = query.value("Name").toString().toStdString(); scientist.push_back(s); } scientistDB.close(); return scientist; } void ScientistRepository::add(Scientist scientist) { scientistDB = openDatabase(); scientistDB.open(); QSqlQuery query(scientistDB); query.prepare("INSERT INTO scientists (Name, BirthYear, DeathYear, Gender)" "VALUES(:name, :dateOfBirth, :dateOfDeath, :gender)"); query.bindValue(":name", QString::fromStdString(scientist.name)); query.bindValue(":dateOfBirth", QString::fromStdString(scientist.dateOfBirth)); query.bindValue(":dateOfDeath", QString::fromStdString(scientist.dateOfDeath)); query.bindValue(":gender", QString::fromStdString(scientist.gender)); query.exec(); scientistDB.close(); } std::list<Scientist> ScientistRepository::list() { //tetta fall saekir gogn ur toflunni fyrir visindamenn ur gagnagrunninum og setur thau i lista std::list<Scientist> scientist = std::list<Scientist>(); scientistDB = openDatabase(); scientistDB.open(); QSqlQuery query(scientistDB); Scientist s = Scientist(); query.exec("SELECT * FROM scientists"); while(query.next()){ s.name = query.value("Name").toString().toStdString(); s.gender = query.value("Gender").toString().toStdString(); s.dateOfBirth = query.value("BirthYear").toString().toStdString(); s.dateOfDeath = query.value("DeathYear").toString().toStdString(); scientist.push_back(s); } scientistDB.close(); return scientist; } std::list<Scientist> ScientistRepository::orderBy(std::string order) { std::list<Scientist> scientist = std::list<Scientist>(); scientistDB = openDatabase(); scientistDB.open(); QSqlQuery query(scientistDB); Scientist s = Scientist(); if(order == "name") { query.exec("SELECT * FROM scientists ORDER BY Name"); while(query.next()){ s.name = query.value("Name").toString().toStdString(); s.gender = query.value("Gender").toString().toStdString(); s.dateOfBirth = query.value("BirthYear").toString().toStdString(); s.dateOfDeath = query.value("DeathYear").toString().toStdString(); scientist.push_back(s); } scientistDB.close(); return scientist; } else if(order == "dob") { query.exec("SELECT * FROM scientists ORDER BY BirthYear"); while(query.next()){ s.name = query.value("Name").toString().toStdString(); s.gender = query.value("Gender").toString().toStdString(); s.dateOfBirth = query.value("BirthYear").toString().toStdString(); s.dateOfDeath = query.value("DeathYear").toString().toStdString(); scientist.push_back(s); } scientistDB.close(); return scientist; } else if(order == "dod") { query.exec("SELECT * FROM scientists ORDER BY DeathYear"); while(query.next()){ s.name = query.value("Name").toString().toStdString(); s.gender = query.value("Gender").toString().toStdString(); s.dateOfBirth = query.value("BirthYear").toString().toStdString(); s.dateOfDeath = query.value("DeathYear").toString().toStdString(); scientist.push_back(s); } scientistDB.close(); return scientist; } else if(order == "gender") { query.exec("SELECT * FROM scientists ORDER BY Gender"); while(query.next()){ s.name = query.value("Name").toString().toStdString(); s.gender = query.value("Gender").toString().toStdString(); s.dateOfBirth = query.value("BirthYear").toString().toStdString(); s.dateOfDeath = query.value("DeathYear").toString().toStdString(); scientist.push_back(s); } scientistDB.close(); return scientist; } else { scientistDB.close(); exit(0); } } std::list<Scientist> ScientistRepository::search(std::string searchField, std::string searchTerm) { std::list<Scientist> scientist = std::list<Scientist>(); scientistDB = openDatabase(); scientistDB.open(); QSqlQuery query(scientistDB); Scientist s = Scientist(); QString field = QString::fromStdString(searchField); QString term = QString::fromStdString(searchTerm); query.exec("SELECT * FROM scientists s WHERE s.\'" + field + "\' = \'" + term + "\'"); while(query.next()){ s.name = query.value("Name").toString().toStdString(); s.gender = query.value("Gender").toString().toStdString(); s.dateOfBirth = query.value("BirthYear").toString().toStdString(); s.dateOfDeath = query.value("DeathYear").toString().toStdString(); scientist.push_back(s); } scientistDB.close(); return scientist; } std::list<Scientist> ScientistRepository::listID() { std::list<Scientist> scientist = std::list<Scientist>(); scientistDB = openDatabase(); scientistDB.open(); QSqlQuery query(scientistDB); Scientist s = Scientist(); query.exec("SELECT * FROM scientists"); while(query.next()){ s.name = query.value("Name").toString().toStdString(); s.ID = query.value("ID").toString().toStdString(); scientist.push_back(s); } scientistDB.close(); return scientist; }
cbf8097742ef8de8000e9361fc6638b7f48d3c2f
da8ee835b202a5ec76ee0ec021db6518069bef6a
/Random Codes/8_queen_problem.cpp
f7aff49c1cca09a4965c2d2610a4787cd8357620
[]
no_license
TarekHasan011/Artificial-Intelligence
6710b28bef2ad446581bf8633943a93e75a62b9f
955afe59e67e2aecd4624339611732cbd4ce1be3
refs/heads/main
2023-07-18T17:24:00.621686
2021-08-20T17:17:01
2021-08-20T17:17:01
307,750,517
0
0
null
null
null
null
UTF-8
C++
false
false
1,349
cpp
8_queen_problem.cpp
#include<bits/stdc++.h> #define SIZE 8 using namespace std; char board[SIZE][SIZE]; bool isSafe(int r, int c) { for(int i=0;i<SIZE;i++) { if(board[r][i]=='Q') return false; } for(int i=0;i<SIZE;i++) { if(board[i][c]=='Q') return false; } for(int i=r,j=c;i<SIZE && j<SIZE;i++,j++) { if(board[i][j]=='Q') return false; } for(int i=r,j=c;i>=0 && j>=0;i--,j--) { if(board[i][j]=='Q') return false; } for(int i=r,j=c;i<SIZE && j>=0;i++,j--) { if(board[i][j]=='Q') return false; } for(int i=r,j=c;i>=0 && j<SIZE;i--,j++) { if(board[i][j]=='Q') return false; } return true; } bool solve(int row) { if(row==SIZE) return true; for(int i=0;i<SIZE;i++) { if(isSafe(row,i)) { board[row][i]='Q'; if(solve(row+1)) return true; else board[row][i]='.'; } } return false; } int main() { memset(board,'.',sizeof(board)); solve(0); for(int i=0;i<SIZE;i++) { for(int j=0;j<SIZE;j++) cout << board[i][j] << " "; cout << endl; } return 0; }
2ddb68ce9846dc10cb96c7cf22524418ef64020b
06dcff60c265be3685bf718fdacf0ae79f1d772f
/src/AudioOutput.cpp
3095d08a03aeefbedeacee4f5a30219c395aa6f9
[]
no_license
Shadkirill/libmediafy
e2ed36f9249a573d259b93528336730b77a565ad
02070b1220a8fdebc162ee99165b49f5fa24d99d
refs/heads/main
2023-04-22T10:46:24.129523
2021-05-21T01:13:41
2021-05-21T01:13:41
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,614
cpp
AudioOutput.cpp
// // Created by adebayo on 5/7/21. // #include "AudioOutput.h" #include <atomic> extern "C" { #include <libavutil/time.h> }; #define MINIAUDIO_IMPLEMENTATION #include "miniaudio.h" #ifndef MA_SUCCESS #define MA_SUCCESS 0 #endif void data_callback(ma_device* device, void* output, const void* input, ma_uint32 frames); class LibmediafyAudioOutput : public libmediafy::AudioOutput { public: LibmediafyAudioOutput(int sampleRate, AVSampleFormat sampleFormat, int channels, libmediafy::AudioCallbackHandler* handler) : AudioOutput(sampleRate, sampleFormat, channels, handler) { ma_format fmt = ma_format_f32; if (sampleFormat == AV_SAMPLE_FMT_S16) fmt = ma_format_s16; ma_device_config config = ma_device_config_init(ma_device_type_playback); config.playback.format = fmt; config.playback.channels = channels; config.sampleRate = sampleRate; config.dataCallback = data_callback; config.pUserData = this; initialized = ma_device_init(nullptr, &config, &device) == MA_SUCCESS; } void start() override { if (!initialized) return; started = true; ma_device_start(&device); } void stop() override { if (!initialized) return; started = false; ma_device_stop(&device); } void close() override { if (!initialized) return; started = false; ma_device_stop(&device); } void flush() override { if (!initialized) return; // Nothing TODO } bool is_started() override { return started; } virtual ~LibmediafyAudioOutput() { ma_device_uninit(&device); } private: ma_device device; std::atomic_bool started{false}; }; libmediafy::AudioOutputBuilder& libmediafy::AudioOutputBuilder::set_sample_format(AVSampleFormat format) { sample_format = format; return *this; } libmediafy::AudioOutputBuilder &libmediafy::AudioOutputBuilder::set_sample_rate(int rate) { sample_rate = rate; return *this; } libmediafy::AudioOutputBuilder &libmediafy::AudioOutputBuilder::set_channels(int count) { channels = count; return *this; } libmediafy::AudioOutputBuilder& libmediafy::AudioOutputBuilder::set_audio_callback_handler(libmediafy::AudioCallbackHandler* handler) { callback_handler = handler; return *this; } std::unique_ptr<libmediafy::AudioOutput> libmediafy::AudioOutputBuilder::create() { if (channels < 0 || sample_rate < 0 || sample_format == AV_SAMPLE_FMT_NONE) return nullptr; if (!callback_handler) return nullptr; AudioOutput* aout{nullptr}; aout = new LibmediafyAudioOutput(sample_rate, sample_format, channels, callback_handler); if (!aout) return nullptr; if (!aout->initialized) { delete aout; aout = nullptr; } return std::unique_ptr<libmediafy::AudioOutput>(aout); } libmediafy::AudioOutput::AudioOutput(int sampleRate, AVSampleFormat sampleFormat, int channels, libmediafy::AudioCallbackHandler* handler) : sample_rate(sampleRate), sample_format(sampleFormat), channels(channels), callback_handler(handler) {} void data_callback(ma_device* device, void* output, const void* input, ma_uint32 frames) { libmediafy::AudioOutput* aout = reinterpret_cast<libmediafy::AudioOutput*>(device->pUserData); unsigned int bytes_per_frame = device->playback.format == ma_format_f32 ? sizeof(float) * device->playback.channels : sizeof(int16_t) * device->playback.channels; aout->callback_handler->get_buffer(frames, bytes_per_frame, output); }
d85383d6f970f25de92b7d1e315147511c626e10
f3bb2403ab48b5964e398bbf5082b66ec17bfdef
/SQLConnectionGUIVS/InsertData.h
8e913f73f630a5ce06bdd466a1c777cc2adb4c27
[]
no_license
JosipDraguljic/CPP_GUIVSSQLConnection
074293984059b2571264bc6340b8472d9a437e2a
28609bb8503ec3d6f3ef55b18516d92b20a1b272
refs/heads/main
2023-04-06T12:05:13.441718
2021-04-13T11:10:47
2021-04-13T11:10:47
null
0
0
null
null
null
null
ISO-8859-1
C++
false
false
2,627
h
InsertData.h
#pragma once #include "Functions.h" namespace SQLConnectionGUIVS { using namespace System; using namespace System::ComponentModel; using namespace System::Collections; using namespace System::Windows::Forms; using namespace System::Data; using namespace System::Drawing; /// <summary> /// Zusammenfassung für InsertData /// </summary> public ref class InsertData : public System::Windows::Forms::Form { public: InsertData(void) { InitializeComponent(); // //TODO: Konstruktorcode hier hinzufügen. // } protected: /// <summary> /// Verwendete Ressourcen bereinigen. /// </summary> ~InsertData() { if (components) { delete components; } } private: System::Windows::Forms::TextBox^ txtName; protected: private: System::Windows::Forms::Button^ btnInsertName; private: /// <summary> /// Erforderliche Designervariable. /// </summary> System::ComponentModel::Container ^components; #pragma region Windows Form Designer generated code /// <summary> /// Erforderliche Methode für die Designerunterstützung. /// Der Inhalt der Methode darf nicht mit dem Code-Editor geändert werden. /// </summary> void InitializeComponent(void) { this->txtName = (gcnew System::Windows::Forms::TextBox()); this->btnInsertName = (gcnew System::Windows::Forms::Button()); this->SuspendLayout(); // // txtName // this->txtName->Location = System::Drawing::Point(185, 106); this->txtName->Name = L"txtName"; this->txtName->Size = System::Drawing::Size(163, 20); this->txtName->TabIndex = 0; // // btnInsertName // this->btnInsertName->Location = System::Drawing::Point(185, 141); this->btnInsertName->Name = L"btnInsertName"; this->btnInsertName->Size = System::Drawing::Size(163, 23); this->btnInsertName->TabIndex = 1; this->btnInsertName->Text = L"Insert Name"; this->btnInsertName->UseVisualStyleBackColor = true; this->btnInsertName->Click += gcnew System::EventHandler(this, &InsertData::btnInsertName_Click); // // InsertData // this->AutoScaleDimensions = System::Drawing::SizeF(6, 13); this->AutoScaleMode = System::Windows::Forms::AutoScaleMode::Font; this->ClientSize = System::Drawing::Size(524, 310); this->Controls->Add(this->btnInsertName); this->Controls->Add(this->txtName); this->Name = L"InsertData"; this->Text = L"InsertData"; this->ResumeLayout(false); this->PerformLayout(); } #pragma endregion private: System::Void btnInsertName_Click(System::Object^ sender, System::EventArgs^ e) { Functions f; f.Insert(txtName->Text); } }; }
3a6d747602007800b5bf0c8b517a88ff66e12e72
4d66f0bd23b55646b78a4ab75f38435914351211
/src/capi_function.cpp
0af4422e0f714398ec3e9999ce1a8fcde49a8570
[]
no_license
mkoval/boost_python_examples
682786dcfdb1f96bbf317f1120809814af96123d
5bb93be595a12c611dc99d255c9bebbe975819f0
refs/heads/master
2020-04-14T14:49:49.897891
2014-04-18T06:11:24
2014-04-18T06:11:24
null
0
0
null
null
null
null
UTF-8
C++
false
false
635
cpp
capi_function.cpp
#include <Python.h> static PyObject *py_hello_world(PyObject *self, PyObject *args) { char const *const message = "Hello World"; // Helper function for creating Python objects. The first argument is // similar to a format string, where "s" is a Python string. return Py_BuildValue("s", message); } // The module initialization function must be a C function. extern "C" { // This must be called "my<module_name>". void initcapi_function() { static PyMethodDef methods[] = { { "hello_world", py_hello_world, METH_VARARGS }, { NULL, NULL }, }; Py_InitModule("capi_function", methods); } }
8f1279a8589b360faac546ddeb05b95c5906c262
09dc57d26326f2190d7aee1c5562793aed986ba5
/Inc/Socket.h
b5d17fccfca35c8c76aff9f1bb806bd28cd7b69f
[]
no_license
colinhp/SpellCorrection-System
8a295e4c6c7a7fce6fabbbfdd1e1df7ac4e7d297
251fbac8c72c87d04d82f0222c9e94b85e1918fc
refs/heads/master
2021-05-20T23:31:31.968607
2015-12-27T05:07:56
2015-12-27T05:07:56
null
0
0
null
null
null
null
UTF-8
C++
false
false
622
h
Socket.h
#ifndef __SOCKET_H__ #define __SOCKET_H__ #include "Noncopyable.h" namespace tanfy { class InetAddress; class Socket:Noncopyable { public: Socket(); Socket(int sockfd); ~Socket(); int getfd() { return sockfd_; } void ready(InetAddress &addr, int clinum); int accept(); static InetAddress getLocalAddr(int acceptfd); static InetAddress getPeerAddr(int acceptfd); void shutdownWrite(); private: void bindAddress(InetAddress &addr); void listen(int clinum); void setReuseAddr(bool flag); void setReusePort(bool flag); private: int sockfd_; bool isRunning_; }; }//end of namespace #endif
46efb9732116cb54aa5900513e96c3d5e175cc11
7311bdc40745b1ad207cd551567c6b835f8c56d7
/Round 1B/cards.cc
311435ecc2756785b494496d9799f6912ccd37fb
[]
no_license
PereCP/CodeJam-2020
ce29f0b266a0438437f9ea94bfdcfa5de5e562dc
f99b3adde5c9ea86bb0e87499d209b9ee9139caa
refs/heads/master
2022-07-22T02:16:04.746642
2020-05-09T13:47:45
2020-05-09T13:47:45
262,580,610
0
0
null
null
null
null
UTF-8
C++
false
false
2,379
cc
cards.cc
#include <iostream> #include <list> using namespace std; typedef pair<int, int> card; void print_list(const list<card>& l) { for (list<card>::const_iterator it = l.begin(); it != l.end(); ++it) { cout << (*it).first << ' ' << (*it).second << endl; } } void genlist(list<card>& l, int r, int s) { for (int i = 1; i <= s; ++i) { for (int j = 1; j <= r; ++j) { l.push_front(pair<int, int>(j, i)); } } } int main() { int cases; cin >> cases; for (int x = 1; x <= cases; ++x) { cout << "Case #" << x << ": "; int r, s; cin >> r >> s; int total = r * s; list<card> l; genlist(l, r, s); int k = 1; bool finish = false; list<card>::reverse_iterator pos = l.rbegin(); int moves = 0; if (r == 0 or s == 0) cout << 0 << endl; else { string out; while (not finish) { int i = 1; list<card>::iterator it = l.begin(); while ((*it).first != k) { ++i; ++it; } ++it; list<card> a; a.splice(a.begin(), l, l.begin(), it); int j = 0; list<card>::reverse_iterator rit = pos; while ((*rit).first == k) { ++j; ++rit; } j = l.size() - j - (k-1)*s; it = l.begin(); advance(it, j); list<card> b; b.splice(b.begin(), l, l.begin(), it); l.splice(l.begin(), a, a.begin(), a.end()); l.splice(l.begin(), b, b.begin(), b.end()); int num = 0; rit = pos; while ((*rit).first == k) { ++num; ++rit; } if (num == s) { ++k; pos = rit; } finish = k == r; ++moves; out.push_back(char(i + int('0'))); out.push_back(char(j + int('0'))); } cout << moves << endl; int n = out.length(); for (int i = 0; i < n; i += 2) cout << out[i] << ' ' << out[i + 1] << endl; } } }
6f28e89d2d6a2eb771d20c1b026315201120cca3
049ec768ecf957f1337f957a16db05416ef92e78
/inc/osapp/osmain.hxx
a66424d6a075fa32a85224c3482611b5a3291ae2
[ "MIT" ]
permissive
frang75/nappgui
59f48e01b5f8efdccd6d02c6487cdd39f11456e0
319d6c3a2a3eadd5d6375186b3aa31bf17e27b6f
refs/heads/master
2023-01-12T06:36:39.430488
2022-12-26T14:05:12
2022-12-26T14:05:12
194,401,589
73
7
null
2021-01-26T21:07:05
2019-06-29T12:10:08
C
UTF-8
C++
false
false
596
hxx
osmain.hxx
/* * NAppGUI Cross-platform C SDK * 2015-2022 Francisco Garcia Collado * MIT Licence * https://nappgui.com/en/legal/license.html * * File: osmain.hxx * */ /* Cross-platform main */ #ifndef __OSMAIN_HXX__ #define __OSMAIN_HXX__ #include "osapp.hxx" typedef void*(*FPtr_app_create)(void); #define FUNC_CHECK_APP_CREATE(func, type)\ (void)((type*(*)(void))func == func) typedef void(*FPtr_app_update)(void *app, const real64_t prtime, const real64_t ctime); #define FUNC_CHECK_APP_UPDATE(func, type)\ (void)((void(*)(type*, const real64_t, const real64_t))func == func) #endif
384a8b8280f62d98e023960194019775423efd6b
031cd28ddd4a326b0829f196ceaa06020c4ae235
/src/gui/GLSLHighlighter.h
e547d276c63d349663dfe6c758721e90de518297
[ "BSD-3-Clause" ]
permissive
c42f/displaz
364e6d3a3b14131b629fd806ef4a354fefc678cc
ae998f37688a4eeffacfbae8583c2e982997d155
refs/heads/master
2023-08-31T10:46:12.698720
2023-08-19T01:07:23
2023-08-19T01:07:23
6,596,947
207
91
NOASSERTION
2023-09-10T07:43:55
2012-11-08T13:48:08
C++
UTF-8
C++
false
false
1,373
h
GLSLHighlighter.h
// Copyright 2015, Christopher J. Foster and the other displaz contributors. // Use of this code is governed by the BSD-style license found in LICENSE.txt #ifndef DISPLAZ_GLSL_HIGHLIGHTER_H_INCLUDED #define DISPLAZ_GLSL_HIGHLIGHTER_H_INCLUDED #include <QSyntaxHighlighter> #include <QTextCharFormat> #include <QString> /// Highlights GLSL code class GLSLHighlighter : public QSyntaxHighlighter { Q_OBJECT public: GLSLHighlighter(QTextDocument* parent = 0); protected: void highlightBlock(const QString& text) Q_DECL_OVERRIDE; private: enum class TextStyle { Plain, Italic, }; /// States a section of text can have enum BlockState { // QSyntaxHighlighter defaults all text to -1 Default = -1, MultilineComment, }; /// Describes how text matching regexp should be formatted struct Rule { QRegExp regexp; QTextCharFormat format; }; /// Adds a rule to m_rules void addRule(const QString& color, TextStyle style, const QString& pattern); QVector<Rule> m_rules; QTextCharFormat m_comment; QRegExp m_commentBegin; // Matches a /* QRegExp m_commentEnd; // Matches a */ }; #endif // DISPLAZ_GLSL_HIGHLIGHTER_H_INCLUDED
e9d45b97d4afd4aee93d38802a1279776740425e
44341e2500d1aafe1615b0f79ce0f52c19a4d044
/RenderEngine2/Model.h
836154ebcc88f0ed42daab6935e16a1fab24b64c
[]
no_license
daniel-zhang/render_demos
9a420306bdf00761e2ffac4f919fbdd6777e2f8c
73aa0958b97c9354147404d4f0c5a7754d80bf38
refs/heads/master
2020-12-24T16:06:39.923784
2016-04-02T00:17:25
2016-04-02T00:17:25
19,178,207
0
0
null
null
null
null
UTF-8
C++
false
false
1,474
h
Model.h
#ifndef MODEL_H #define MODEL_H #include "Util.h" #include "GeometryGenerator.h" #include "InputLayoutMgr.h" #include "LightHelper.h" class Model { public: Model(ID3D11Device* dv, ID3D11DeviceContext* ctx); virtual ~Model(); // // Supports loading from .obj, GeometryGenerator, and the simple meshes // void loadObj(std::wstring filename, bool coordConvert = true); void loadPrimitive(GeometryGenerator::MeshData& mesh); void loadSimpleMesh(std::wstring filename); void update(XMFLOAT4X4 world, XMFLOAT4X4 texTransform); // TODO: RenderState management void draw(ID3DX11EffectTechnique* pTech, XMFLOAT4X4 viewProj); // TODO: Binary save/load virtual void save(){} virtual void load(){} private: // Vertex structure is defined in InputLayoutManager struct ModelSubset { ModelSubset(): matId(-1), indexOffset(0), indexCount(0) {} int matId; UINT indexOffset; UINT indexCount; }; private: // Pipeline ID3D11Device* mDevice; ID3D11DeviceContext* mCtx; // Mesh ID3D11Buffer* mVB; ID3D11Buffer* mIB; std::vector<ModelSubset> mSubsets; std::vector<Material> mMaterials; std::vector<ID3D11ShaderResourceView*> mDiffuseMaps; // System memory copy of mesh std::vector<Vertex::PosNormalTex> mVertices; std::vector<UINT> mIndices; // Matrices XMFLOAT4X4 mWorld; XMFLOAT4X4 mTexTransform; }; #endif
34ced44eec549b5f8d853fc1f033e0154e0de869
b0883836413b336033ebdaad4f40bf921201b5c5
/person.cpp
7a9350346934fdf89c4f03e48bb9b2b7a4989d3e
[]
no_license
tuananh0209/OOP_HK2020
152eaafac937d263f3b33d0657c00f65cbb79658
d1803e6eee0fe341a5aa95a5f31e6fc60caa4d09
refs/heads/master
2023-08-25T15:26:00.899889
2021-10-18T04:08:54
2021-10-18T04:08:54
null
0
0
null
null
null
null
UTF-8
C++
false
false
276
cpp
person.cpp
#include "person.h" Person::Person(){}; Person::Person(string username, string name, string phone, string address, string birthday){ this->name = name; this->username = username; this->address = address; this->phone = phone; this->birthday = birthday; }
2734f3ae2d2b46c1be618778f493ce613e7d058f
23012559f8099fbb6a4c86d3d86ab5c5212de48e
/libs/kasten/gui/shell/shellwindow.cpp
cbe0437feb57bb87ed30a3d9ed288daca410f834
[]
no_license
KDE/okteta
a916cdb9e16cdc6c48a756205604df600a3b271c
cb7d9884a52d0c08c1496d4a3578f5dfe0c2a404
refs/heads/master
2023-09-01T09:33:47.395026
2023-08-29T04:33:32
2023-08-29T04:33:32
42,718,476
92
9
null
2020-12-29T18:58:56
2015-09-18T11:44:12
C++
UTF-8
C++
false
false
1,355
cpp
shellwindow.cpp
/* This file is part of the Kasten Framework, made within the KDE community. SPDX-FileCopyrightText: 2007-2009, 2011 Friedrich W. H. Kossebau <kossebau@kde.org> SPDX-License-Identifier: LGPL-2.1-only OR LGPL-3.0-only OR LicenseRef-KDE-Accepted-LGPL */ #include "shellwindow.hpp" #include "shellwindow_p.hpp" namespace Kasten { ShellWindow::ShellWindow(ViewManager* viewManager) : d_ptr(new ShellWindowPrivate(this, viewManager)) { } ShellWindow::~ShellWindow() = default; ViewManager* ShellWindow::viewManager() const { Q_D(const ShellWindow); return d->viewManager(); } MultiViewAreas* ShellWindow::viewArea() const { Q_D(const ShellWindow); return d->viewArea(); } QVector<ToolViewDockWidget*> ShellWindow::dockWidgets() const { Q_D(const ShellWindow); return d->dockWidgets(); } void ShellWindow::addXmlGuiController(AbstractXmlGuiController* controller) { Q_D(ShellWindow); d->addXmlGuiController(controller); } void ShellWindow::addTool(AbstractToolView* toolView) { Q_D(ShellWindow); d->addTool(toolView); } void ShellWindow::showDocument(AbstractDocument* document) { Q_D(ShellWindow); d->showDocument(document); } void ShellWindow::updateControllers(AbstractView* view) { Q_D(ShellWindow); d->updateControllers(view); } } #include "moc_shellwindow.cpp"
22f5edbccf95fc6eb87cec679056317e6a81e230
9a017c44f25e3757b14b5ad4f06b660d8249c0fd
/parsch_labs/lab_6/src/main.cpp
a84ba8380be3ae00524d86f000c01dcabb5634bb
[]
no_license
unseenshadow2/Data_Structures_and_Algorithms
61fba670dc9d99e5b81265e37a77a545dd7fb122
b9fdcc9635a870efc785482631dc3ba95712aa1d
refs/heads/master
2020-12-21T06:14:22.062972
2016-08-14T05:52:07
2016-08-14T05:52:07
59,049,891
0
0
null
null
null
null
UTF-8
C++
false
false
1,039
cpp
main.cpp
// Lab 6 Assignemnt // Data Structures and Algorithms // Written by Anthony Parsch // Compiled and tested on Ubuntu Linux #include <iostream> #include "Queue.hpp" using namespace std; int main () { Queue<int> toTest (10); // Enqueue test cout << "Testing insert:" << endl; for (int i = 0; i < 10; i++) { toTest.enqueue(i*2+1); } toTest.showStructure(); // Enqueue error test cout << "\nTesting insert error catching:" << endl; try { toTest.enqueue(3900); // OOPS } catch (logic_error le) { cout << "The error happened properly..." << endl; } // Dequeue test cout << "\nTesting dequeue (should be 1): " << toTest.dequeue() << endl; toTest.showStructure(); // Clear test cout << "\nTesting clear:" << endl; toTest.clear(); toTest.showStructure(); // Dequeue error test cout << "\nTesting dequeue error catching:" << endl; try { toTest.dequeue(); } catch (logic_error le) { cout << "The error happend properly..." << endl; } return 0; }
c8c43dd5f9fc928463aa0fe7da8b94177f66272c
1c5754e7f43ff4ddf3977e0f146513ce0636aeaa
/CodeJam/2014/ChargingChaos/main.cpp
e98dfc4c94127aaf7ab6d399cfda5ea0fb6cbd3f
[]
no_license
weirdNox/Competitive
5fa7ac0e43699ecdb2eed6a550052ef95ecd2238
3d1d856a94896fd87c982441256a1faa60e27684
refs/heads/master
2021-10-20T19:18:13.686715
2019-03-01T10:20:20
2019-03-01T10:20:20
83,240,799
0
0
null
null
null
null
UTF-8
C++
false
false
2,486
cpp
main.cpp
#include <algorithm> #include <array> #include <chrono> #include <cmath> #include <cstdlib> #include <fstream> #include <iomanip> #include <iostream> #include <limits> #include <map> #include <string> #include <unordered_map> #include <vector> std::vector<std::string> getFlips(const std::string &device, const std::vector<std::string> &outlets) { std::vector<std::string> ret; for(auto &outlet : outlets) { std::string flips; for(int i = 0; i < device.length(); ++i) { if(device[i] == outlet[i]) flips += '0'; else flips += '1'; } ret.push_back(flips); } return ret; } int main() { // auto time = std::chrono::steady_clock::now(); std::ifstream in("in"); std::ofstream out("out"); int T; in >> T; int n, l; for(int caseNum = 1; caseNum <= T; ++caseNum) { std::cout << "Case #" << caseNum << std::endl; out << "Case #" << caseNum << ": "; in >> n >> l; std::vector<std::string> outlets(n); std::vector<std::string> devices(n); for(short i = 0; i < n; ++i) { in >> outlets[i]; } for(short i = 0; i < n; ++i) { in >> devices[i]; } std::vector<std::vector<std::string>> allFlips; for(auto &device : devices) { auto flips = getFlips(device, outlets); std::sort(flips.begin(), flips.end()); allFlips.push_back(flips); } std::vector<std::string> intersect = allFlips[0]; for(size_t i = 1; i < allFlips.size(); ++i) { std::vector<std::string> temp; std::set_intersection(intersect.begin(), intersect.end(), allFlips[i].begin(), allFlips[i].end(), std::back_inserter(temp)); intersect = temp; } int answer = std::numeric_limits<int>::max(); for(auto &flip : intersect) { answer = std::min(answer, std::count(flip.begin(), flip.end(), '1')); } if(intersect.size()) out << answer << '\n'; else out << "NOT POSSIBLE" << '\n'; } // std::cout << "Execution time: " << std::chrono::duration_cast<std::chrono::milliseconds> // (std::chrono::steady_clock::now() - time).count() / 1000.f << " seconds" << std::endl; return 0; }
9a566e669499f46df24fb33b9695101ffbb83a76
b53f1953f5520e5208f34bb87d42d86ead33dba6
/src/Platform/Code/Diag_Export/ODM.h
d0ee897384566b7167d8197630dff6f070a82c0a
[]
no_license
Jonkoping/data
e01b2ded3335742165ea3feb9c06e0d111ab5fb7
03de309b5f7998f394b2ed1d8b0bc0114ca686f3
refs/heads/master
2020-06-30T18:24:29.032625
2018-01-04T09:18:55
2018-01-04T09:18:55
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,884
h
ODM.h
#pragma once #include "interfacebase.h" #include "NVItem.h" #include <string> #include <vector> #include "..\CommonUtil\XMLManager.h" #include "Header_MotoXPRS.h" #ifdef DIAG_EXPORT_EXPORTS #define DIAG_API extern "C" __declspec(dllexport) #define DIAG_CLASS_API __declspec(dllexport) #else #define DIAG_API extern "C" __declspec(dllimport) #define DIAG_CLASS_API __declspec(dllimport) #endif #ifndef TSTRING #ifdef _UNICODE #define TSTRING std::wstring #define _TC(x) L ## x #else #define TSTRING std::string #define _TC(x) "x" #endif #endif class DIAG_CLASS_API CODM :public CInterfaceBase { class NameValue { friend class CODM; public: NameValue(const TSTRING& strName,const TSTRING& strValue):m_strName(strName),m_strValue(strValue){} protected: TSTRING m_strName; TSTRING m_strValue; }; public: CODM(int nCOMPort); virtual ~CODM(); virtual bool EnableDiagEvent(bool bEnable); /* bool GetOPProfLogger();// Get Operation Profile Logger */ bool GetMotoXprsLogger(TCHAR* szPATH,int nLen);// Get MotoXprs Logger /* bool GetCallDropLogger();// Get Call Drop logger bool ReadTrackID();// Read TrackID bool ReadPicasoNumber();// Read PicasoNumber bool WriteTrackID Write();// TackID bool WritePicasoNumber Wrtie();// PicasoNumber */ TSTRING GetIMEI(); private: void UpdateElement(XMLMANAGER::XMLElement& Element,const TSTRING& strName,const TSTRING& strValue); void AddProfile(XMLMANAGER::XMLElement& Element,const TSTRING& strProfileName,std::vector<NameValue>& ProfileValues); TSTRING GetCharger(int nIndex,opxprofile_data& MotoXprsData); TSTRING GetPower(int nIndex,opxprofile_data& MotoXprsData); TSTRING ToString(unsigned short usValue); TSTRING ToString(unsigned char* szValue); TSTRING INTToString(unsigned int usValue); void QLIB_Reset(); private: CNVItem m_NVItem; };
d819923b03af4532e9ee9eb51f3a7bef0f6ae07d
f7a53f0690572751ee54b9acc94019d318902f6d
/LightOj1433.cpp
6fc74862a7a041062c0c7f18e3a0dd7e357f97a8
[]
no_license
shamim7999/LightOjProblems
237248f26bc5ee48391ac518fb15767d12a43e6e
107959eee9ea6fedb8209db655b342766e77c0bc
refs/heads/master
2022-01-21T16:45:43.715820
2022-01-10T06:47:36
2022-01-10T06:47:36
231,510,067
0
1
null
null
null
null
UTF-8
C++
false
false
1,265
cpp
LightOj1433.cpp
#include<bits/stdc++.h> using namespace std; #define dd double #define pb push_back #define pf push_front #define popb pop_back #define popf pop_front #define ll long long #define ull unsigned long long #define ld long double #define mx 100005 #define mod 1000000007 #define fr first #define cti(a) (a-48) #define itc(a) char(a+48) #define se second #define End cout<<"\n" #define fast ios_base::sync_with_stdio(false);cin.tie(0);cout.tie(0) #define memo(Array,val) memset(Array, val, sizeof Array) #define PI acos(-1) bool check(ll n, ll pos){ return (n&(1<<pos)); } bool Set(ll n, ll pos) { return (n | (1<<pos)); } ld LOG(ld b, ld e){ return log(b)/log(e); } int tc; ld dist(ld x1, ld y1, ld x2, ld y2) { ld cc = sqrt(((x1-x2)*(x1-x2))+((y1-y2)*(y1-y2))); return cc; } void solve(int kk) { ld oa,ob,ab; ld ox,oy,ax,ay,bx,by; ld theta; cin >> ox >> oy >> ax >> ay >> bx >> by; oa = dist(ox,oy,ax,ay); ob = dist(ox,oy,bx,by); ab = dist(ax,ay,bx,by); ld hold = ((oa*oa)+(ob*ob)-(ab*ab))/(2*oa*ob); theta = (acos(hold)); cout << "Case " << kk << ": "; cout << setprecision(12) << theta*oa << "\n"; } int main() { //fast; int kk=0; scanf("%d", &tc); while(++kk<=tc) solve(kk); return 0; }
542bc6ffab444d9ad46b5d310248e20215c461d1
e226c1d58ba1f6b74784fa485f95cc381e27a8fc
/source/reverse.cpp
8aeb604daafd597bb191e54e0c47569d5515a31d
[]
no_license
hazelnusse/ctci
08768d31a230a117650d69645db521927bde2c26
f0cb6d30b1b6cebb2c8aba8425c82e4ea6c09ac3
refs/heads/main
2023-04-21T14:12:37.999600
2021-04-16T23:09:20
2021-04-16T23:40:16
337,652,770
0
1
null
2021-04-23T03:56:12
2021-02-10T07:49:38
C++
UTF-8
C++
false
false
364
cpp
reverse.cpp
#include <cstring> #include <ctci/reverse.hpp> namespace ctci { void reverse(std::string &s) { if (s.empty()) { return; } auto last_char = s.end() - 1; for (auto first_char = s.begin(); first_char < last_char;) { std::string::value_type const tmp = *first_char; *first_char++ = *last_char; *last_char-- = tmp; } } } // namespace ctci
6f97798c809aa6470c29f19e1c2f9e511906cea6
5407058fb4871915f3225ba0551b8c41dd72fe6e
/Source/Brendenmoor/GlobalEventHandler.cpp
4fad470237bcb4167973ccbbb9a109f9d15495c4
[]
no_license
andrewclear/Brendenmoor-Unreal
0ebc72d5301553ec5e988f6d6a71610f87b5e0e0
40e71b1f239e7be3f67534153b148aa851bfe8fd
refs/heads/master
2023-05-04T19:13:17.450997
2020-03-30T19:34:07
2020-03-30T19:34:07
76,518,179
0
0
null
null
null
null
UTF-8
C++
false
false
160
cpp
GlobalEventHandler.cpp
// Fill out your copyright notice in the Description page of Project Settings. #include "Brendenmoor.h" #include "Engine.h" #include "GlobalEventHandler.h"
bbfdc0ee4644d73b09ab3e3cd2b8cb7f131219f6
50256e647b57a2bd3068f2eb351f619c29a30c86
/src/SiemensS7TcpDriver.cpp
129f06fcb3785056200ed1d285f64be9c3d0b2d2
[]
no_license
bisegni/chaos-driver-siemens-s7
30bc7f488bd734e82d01f7d8b919b77114337e36
a1bbe17d849a183ee4df4230ce3cc5859f1549de
refs/heads/master
2020-06-04T00:57:53.165601
2013-08-28T14:22:41
2013-08-28T14:22:41
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,659
cpp
SiemensS7TcpDriver.cpp
/* * SiemensS7TcpDriver.h * !CHOAS * Created by Bisegni Claudio. * * Copyright 2013 INFN, National Institute of Nuclear Physics * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "SiemensS7TcpDriver.h" #include <string> #include <chaos/cu_toolkit/driver_manager/driver/AbstractDriverPlugin.h> #include <boost/regex.hpp> namespace cu_driver = chaos::cu::driver_manager::driver; #define SL7DRVLAPP_ LAPP_ << "[SiemensS7TcpDriver] " #define SL7DRVLDBG_ LDBG_ << "[SiemensS7TcpDriver] " #define SL7DRVLERR_ LERR_ << "[SiemensS7TcpDriver] " //! Regular expression for check server hostname and port static const boost::regex PlcHostNameAndPort("([a-zA-Z0-9]+(.[a-zA-Z0-9]+)+):([0-9]{3,5})"); //! Regular expression for check server ip and port static const boost::regex PlcIpAnPort("(\\b(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\b):([0-9]{4,5})"); //GET_PLUGIN_CLASS_DEFINITION //we need only to define the driver because we don't are makeing a plugin OPEN_CU_DRIVER_PLUGIN_CLASS_DEFINITION(SiemensS7TcpDriver, 1.0.0, chaos::cu::driver_manager::driver::siemens_s7::SiemensS7TcpDriver) REGISTER_CU_DRIVER_PLUGIN_CLASS_INIT_ATTRIBUTE(SiemensS7TcpDriver,http_address/dnsname:port) CLOSE_CU_DRIVER_PLUGIN_CLASS_DEFINITION //register the two plugin OPEN_REGISTER_PLUGIN REGISTER_PLUGIN(chaos::cu::driver_manager::driver::siemens_s7::SiemensS7TcpDriver) CLOSE_REGISTER_PLUGIN //default constructor definition DEFAULT_CU_DRIVER_PLUGIN_CONSTRUCTOR_WITH_NS(chaos::cu::driver_manager::driver::siemens_s7, SiemensS7TcpDriver) { } //default descrutcor cu_driver::siemens_s7::SiemensS7TcpDriver::~SiemensS7TcpDriver() { } void cu_driver::siemens_s7::SiemensS7TcpDriver::driverInit(const char *initParameter) throw(chaos::CException) { SL7DRVLAPP_ << "Init siemens s7 plc driver"; //check the input parameter boost::smatch match; std::string inputStr = initParameter; bool isIpAndPort = regex_match(inputStr, match, PlcIpAnPort, boost::match_extra); bool isHostnameAndPort = isIpAndPort ? false:regex_match(inputStr, match, PlcHostNameAndPort, boost::match_extra); if(!isIpAndPort && !isHostnameAndPort) { SL7DRVLERR_ << "The address " << inputStr << " is not well formed"; throw new chaos::CException(1, "the initialization paramter for the siemens sl7 is not well formed", "SiemensS7TcpDriver::driverInit"); } std::string address = match[1]; std::string port = match[(int)(match.size()-1)]; SL7DRVLAPP_ << "using address " << address << " and port " << port; fds.rfd=openSocket(std::atoi(port.c_str()), address.c_str()); fds.wfd=fds.rfd; if (fds.rfd>0) { di = daveNewInterface(fds,"IF1",0, daveProtoISOTCP, daveSpeed187k); if(di) daveSetTimeout(di,10000000); dc = di ? daveNewConnection(di,2,0,0):NULL; // insert your rack and slot here if(di && dc && (daveInitAdapter(di) == 0) && (daveConnectPLC(dc) == 0)) { } else { if(dc) daveDisconnectPLC(dc); if(fds.rfd)closeSocket(fds.rfd); SL7DRVLERR_ << "Error opening address"; throw new chaos::CException(2, "Error opening address", "SiemensS7TcpDriver::driverInit"); } } else { SL7DRVLERR_ << "Error opening address"; throw new chaos::CException(3, "Error opening address", "SiemensS7TcpDriver::driverInit"); } } void cu_driver::siemens_s7::SiemensS7TcpDriver::driverDeinit() throw(chaos::CException) { SL7DRVLAPP_ << "Deinit siemens s7 plc driver"; if(dc) { daveDisconnectPLC(dc); dc = NULL; } if(fds.rfd) { closeSocket(fds.rfd); fds.rfd = fds.wfd = 0; } } cu_driver::MsgManagmentResultType::MsgManagmentResult cu_driver::siemens_s7::SiemensS7TcpDriver::getDouble(PlcVariable& variable_info, void *mem_for_result) { int res = 0; double *usr_doub_ptr = static_cast<double*>(mem_for_result); res=daveReadBytes(dc, daveDB, variable_info.db_num, variable_info.start, variable_info.byte_count, NULL); if(0==res) { *usr_doub_ptr = static_cast<double>(daveGetFloat(dc)); return cu_driver::MsgManagmentResultType::MMR_EXECUTED; } else { return cu_driver::MsgManagmentResultType::MMR_ERROR; } }
9315f1f12a335a5fcf36456588b872bf2e99c11a
82b915115c7a72b1f97278ffc3f56116f73493f7
/bitwise sieve.cpp
9f100b35daf47e7cc697391728a43c0e6da3775f
[]
no_license
dv66/programming_problems_cpp
284ca62f08ca9e572ed30af13edd2a793f3aebdc
40e2b038aa1811ebc8a89d5617c81b7cebd38d37
refs/heads/master
2021-06-19T18:19:44.361483
2017-06-05T15:05:43
2017-06-05T15:05:43
null
0
0
null
null
null
null
UTF-8
C++
false
false
440
cpp
bitwise sieve.cpp
#include<bits/stdc++.h> using namespace std; int setbit(int n, int i){ return ((1<<(i-1)) | n);} void printbits(int n){ int m = 1 << 31; for(int i =0; i<32; i++){ if((m&n) == 0) putchar('0'); else putchar('1'); n = n<<1; if((i + 1)%4 == 0) putchar(' '); } cout<<endl; } int main(){ int n ; cin>>n; //cout<<n<<endl; printbits(n); printbits(setbit(n, 10)); return 0; }
0a735480b77637595f7278421e3b03886b9f8c9f
36d20a2c232b39b08a64262f5d99ffa331aabe01
/Userland/Libraries/LibTLS/CipherSuite.h
590e46ef9faa90fa2b91fff4d062f5e1191263a2
[ "BSD-2-Clause" ]
permissive
ReasonablePanic/serenity
c7e8c9f6a3020392fe46c192b3a36ed13388b41a
6048e245ee807f5520685d0e4751059676e24ed1
refs/heads/master
2023-05-01T09:34:42.605849
2021-05-21T14:14:40
2021-05-21T14:14:40
358,444,795
0
0
BSD-2-Clause
2021-04-27T19:15:46
2021-04-16T01:51:03
null
UTF-8
C++
false
false
1,527
h
CipherSuite.h
/* * Copyright (c) 2020, Ali Mohammad Pur <mpfard@serenityos.org> * * SPDX-License-Identifier: BSD-2-Clause */ #pragma once namespace TLS { enum class CipherSuite { Invalid = 0, AES_128_GCM_SHA256 = 0x1301, AES_256_GCM_SHA384 = 0x1302, AES_128_CCM_SHA256 = 0x1304, AES_128_CCM_8_SHA256 = 0x1305, // We support these RSA_WITH_AES_128_CBC_SHA = 0x002F, RSA_WITH_AES_256_CBC_SHA = 0x0035, RSA_WITH_AES_128_CBC_SHA256 = 0x003C, RSA_WITH_AES_256_CBC_SHA256 = 0x003D, RSA_WITH_AES_128_GCM_SHA256 = 0x009C, RSA_WITH_AES_256_GCM_SHA384 = 0x009D, }; enum class HashAlgorithm : u8 { None = 0, MD5 = 1, SHA1 = 2, SHA224 = 3, SHA256 = 4, SHA384 = 5, SHA512 = 6, }; enum class SignatureAlgorithm : u8 { Anonymous = 0, RSA = 1, DSA = 2, ECDSA = 3, }; enum class CipherAlgorithm { Invalid, AES_128_CBC, AES_128_GCM, AES_128_CCM, AES_128_CCM_8, AES_256_CBC, AES_256_GCM, }; constexpr size_t cipher_key_size(CipherAlgorithm algorithm) { switch (algorithm) { case CipherAlgorithm::AES_128_CBC: case CipherAlgorithm::AES_128_GCM: case CipherAlgorithm::AES_128_CCM: case CipherAlgorithm::AES_128_CCM_8: return 128; case CipherAlgorithm::AES_256_CBC: case CipherAlgorithm::AES_256_GCM: return 256; case CipherAlgorithm::Invalid: default: return 0; } } struct SignatureAndHashAlgorithm { HashAlgorithm hash; SignatureAlgorithm signature; }; }
a99c24f30b560d92102540186cb8a4aee61b2745
e532259516df1bf99475ebe3e00923c4ed0f66d2
/PWFA/Lu_bubble_profile/bubble_regime_Lu.cpp
bb3e828a6975c78adeb22a9b56f3255317db3e14
[]
no_license
albz/Plasma_PyCalculator
c090e4ae66d7321fbecce04492391fc5778b21d3
59bd188ef22cd05ca1e99c5a58d17bdbab504580
refs/heads/master
2021-09-08T22:38:28.726579
2018-03-12T14:59:33
2018-03-12T14:59:33
46,377,025
0
1
null
null
null
null
UTF-8
C++
false
false
7,473
cpp
bubble_regime_Lu.cpp
/* * Created by F. Mira A. Marocchino C. Gatti */ #include "parameters.h" #include <math.h> #include <stdio.h> #include <iostream> #include <sstream> #include <iomanip> #include <fstream> #include <stdlib.h> typedef double (*func)(double,double,double); double density(double); double density_driver(double); double density_witness(double); void compute_beta(double&, double); void compute_Dbeta(double&,double&, double); void compute_DDbeta(double&, double&,double&, double); void compute_coefficients(double&,double&,double&,double,double); double compute_Ez( double, double, double); double g(double,double,double); double f(double,double,double); void RK4traj(func,func,double&,double&,double&,double); const double Ebeam=100;//MeV const double Lchannel=0.03; const double mu=5;//driver position double alpha; double ComputeAlpha(double,double); int main(int argc, char **argv) { if (argc<8){ std::cout<<"Usage: ./bubble.exe n0(10^16 cm-3) Q(driver pC) sigma_z(driver mum) sigma_r(driver mum) Q(witness pC) sigma_z(witness mum) twd(distance witness from driver mum) ScanFlag(yes/no)"<<std::endl; return 0; } for (int i=0;i<argc;i++){ std::cout<<"ARG["<<i<<"]="<<argv[i]<<std::endl; } /** perform parameter scan **/ std::string ScanFlag; if (argc==9) { ScanFlag=argv[8]; } else { ScanFlag="no"; } /** Units n --> n/n0 L --> kp L E --> eE/(kp me c^2) Q -> Qkp^3/n0e **/ n0 = atof(argv[1])*1e16; //background density input in cm^-3 wp=pow(4.*pi*re*clight*clight*n0*1.e6,0.5); //plasma frequency in rad/s kp=wp/clight; //kp in m^-1 lp=2.*pi*clight/wp; // plasma wavelength in m std::cout<<"lambda_p(mum) "<<lp/l0<<std::endl; std::cout<<"kp(mum^-1) "<<kp*l0<<std::endl; /** conversione factors**/ double Qnorm=(qe*n0*1e6)/pow(kp,3); //charge in a skin depth volume in C double Efield=me*kp; //MV/m Qd = atof(argv[2])*pC/Qnorm; //input in pC, Qnorm in C Sz_d = kp*atof(argv[3])*l0; //input in mum, kp in m^-1 Sr_d = kp*atof(argv[4])*l0; //input in mum, kp in m^-1 double Qw0 = atof(argv[5])*pC/Qnorm; //input in pC, Qnorm in C double Sz_w0 = kp*atof(argv[6])*l0; //input in mum, kp in m^-1 double tm_w0 = kp*atof(argv[7])*l0; //input in mum, kp in m^-1 /** initial values for scan parameters **/ Qw=Qw0; Sz_w=Sz_w0; tm_w=tm_w0; // double ndriver=Qd/pow(2*pi,1.5)/Sz_d/Sr_d/Sr_d; //maximum value of the density of the driver double rmax=2.*Sr_d*pow(ndriver,0.5); //bubble dimension std::cout<<"Rmax= "<<rmax<<std::endl; std::cout<<"ndriver(adimensional)= "<<ndriver<<std::endl; std::cout<<"ndriver(10^16 cm^-3)= "<<ndriver*n0*1.e-16<<std::endl; std::cout<<"ndriver (radially integrated)= "<<ndriver*2*pi*Sr_d*Sr_d<<std::endl; std::cout<<"Q0(pC)= "<<(qe*n0*1e6)/pow(kp,3)/pC<<std::endl; //-apri file di output-// char fname[1024]; sprintf(fname,"bubble_RK4.dat"); std::ofstream outfile(fname); /** corrispondenza nomi vecchie variabili f=function_r g=function_u y=ub h=Dxi t=xi x=rb **/ double t,x,y,h; int NScan=20;//point scan if (ScanFlag=="no") NScan=1; double DeltaQw=3./2.*Qw/double(NScan); double DeltaXi=1./10.*tm_w/double(NScan); for(int ixi=0;ixi<NScan;ixi++) { tm_w=tm_w0-(ixi-NScan/2)*DeltaXi; for (int iq=0;iq<NScan;iq++) { Qw=Qw0-(iq-NScan/2)*DeltaQw; int nmax=1e9; int it=0; t = 0.; x = Sr_d*1e-1; y = 0; h =1e-5; double Eav=0,SigmaE=0,Qtot=0,Eznow=0,den=0,tm_wnow=0; while (it<nmax&&x>0) { RK4traj(f,g,t,x,y,h); it++; Eznow=compute_Ez(x,t,y); den=density_witness(t); if (int(it)%100==0&&ScanFlag=="no") outfile<<t<<"\t"<<x<<"\t"<<density(t)*2*pi<<"\t"<<Eznow<<"\n"; if (Eznow!=Eznow) { // for f NAN: f!=f is true std::cout<<"in t="<<t<<" Eznow is "<<Eznow<<std::endl; } else { Eav+=Eznow*den*h; SigmaE+=Eznow*Eznow*den*h; Qtot+=den*h; } } Eav=-Eav/Qtot; SigmaE=pow(SigmaE/Qtot-Eav*Eav,0.5)*Efield*Lchannel; Eav=Eav*Efield*Lchannel; double SEoverE=SigmaE/(Ebeam+Eav); Qtot=Qw*Qnorm/pC; tm_wnow=tm_w/kp/l0; std::cout<<"Witness position (mum)= "<<tm_wnow<<" Qwitness(pC)= "<<Qtot<<" Ebeam(MeV)="<<Ebeam<<" <DEnergy>(MeV)="<<Eav <<" SigmaEnergy(MeV)="<<SigmaE <<" SigmaE/E="<<SEoverE <<std::endl; if (ScanFlag=="yes") outfile<<tm_wnow<<"\t"<<"\t"<<Qtot<<"\t"<<"\t"<<Eav<<"\t"<<"\t"<<SEoverE<<std::endl; std::cout<<"crossing point reached at iteration n "<<it<<std::endl; } }//Scan outfile.close(); return 0; } void RK4traj(func f,func g,double& t,double &x,double& y,double h) { double s=x,r=y,q=t; double K1 = f(q,s,r),L1=g(q,s,r); s= x+(h/2)*K1; r=y+(h/2)*L1; q=t+h/2; double K2 = f(q,s,r),L2=g(q,s,r); s= x+(h/2)*K2; r=y+(h/2)*L2; q=t+h/2; double K3 = f(q,s,r),L3=g(q,s,r); s= x+h*K3; r=y+h*L3; q=t+h; double K4 = f(q,s,r),L4=g(q,s,r); x += h*(K1+2*(K2+K3)+K4)/6; y += h*(L1+2*(L2+L3)+L4)/6; t += h; } double f(double t,double x,double y) { return y; } double g(double t,double x,double y) { double fu,A,B,C; double L = density(t); compute_coefficients(A,B,C,x,t); return (L/x - C*x -B*x*y*y)/A; } double density( double t ){ /** extra 1/(2*pig) since Q= 2 pig \int lambda dxi **/ return (density_driver(t)+density_witness(t))/(2*pi); } double density_driver( double t ){ double sigma, rho; sigma = Sz_d; rho = exp(-(t-mu)*(t-mu)/2./sigma/sigma); rho = Qd*rho/pow(2.*pi,0.5)/sigma; return rho; } double density_witness( double t ){ double sigma, rho; sigma = Sz_w; rho = exp(-(t-mu-tm_w)*(t-mu-tm_w)/2./sigma/sigma); rho = Qw*rho/pow(2.*pi,0.5)/sigma; return rho; } double ComputeAlpha(double r,double t) { double DS=0.1; double DL=1; /** if (t>mu+3){ DL=1-(t-mu-3)*0.8/4.; } **/ alpha=DL/r+DS; return alpha; } void compute_beta(double &beta, double r){ //alpha=1./r+0.1; beta = (1.+alpha)*(1.+alpha) * 2.*log(1.+alpha) / (alpha*(2.+alpha)) - 1.; } void compute_Dbeta(double &Dbeta,double& beta, double r){ compute_beta(beta, r); Dbeta = 2.*(1.+alpha)/(r*r*alpha*(2.+alpha))*(beta-log(pow(alpha+1.,2))); } void compute_DDbeta(double &DDbeta, double &Dbeta, double &beta, double r){ compute_Dbeta(Dbeta,beta,r); DDbeta = (1+alpha)*(r*r*Dbeta+beta*(1+alpha)/alpha/(2+alpha))/alpha/(2+alpha); DDbeta = DDbeta - (r*r*Dbeta+(beta+1)/(1+alpha))/(1+alpha); DDbeta = DDbeta + beta/pow(alpha*(2+alpha),2); DDbeta = 2*(DDbeta/r/r-Dbeta)/r; } void compute_coefficients(double &A,double &B,double &C,double r,double t) { double beta,Dbeta,DDbeta; //compute_beta(beta, r); //compute_Dbeta(Dbeta,beta, r); //first derivative ComputeAlpha(r,t); compute_DDbeta(DDbeta, Dbeta, beta, r); //second derivative A = 1+(0.25+beta/2.+r*Dbeta/8.) *r*r; B = .5 + 0.75*beta+3./4.*r*Dbeta+0.125*r*r*DDbeta; C = .25 + 0.25/pow(1.+beta/4.*r*r,2); /** A = r*r*0.25; B=0.5; C=0.25; **/ } double compute_Ez( double r, double t, double u){ double Ez,beta,Dbeta; double Du=g(r,t,u); ComputeAlpha(r,t); compute_beta(beta, r); compute_Dbeta(Dbeta,beta, r); //first derivative Ez = 0.5*u*r * (1.+beta+0.5*r*Dbeta); // Ez = 0.5*r*u; return Ez; }
4b3c36b82c9f143384f2e61837190f38f7c76717
402b890909f0bea35c52bf5c67cf47c49ec7b93b
/09 - Szarmaztatas/fajlrendszer/fileSystem.cpp
344d378a028bcbf4621d15b82088a3cb917c8d72
[]
no_license
kovacs-levent/ELTEProg
528baee1bb8bd57b17087eee1e095997a29586f2
2f8c0ee953628381709ba0876943568b038156f6
refs/heads/master
2020-07-27T14:54:52.652474
2019-05-15T16:56:19
2019-05-15T16:56:19
145,883,210
3
2
null
null
null
null
UTF-8
C++
false
false
507
cpp
fileSystem.cpp
#include "fileSystem.h" bool FileSystem::removeEntry(Entry* p) { bool l = false; int i = 0, ind; while(!l && i < content.size()) { l = (content[i] == p); ind = i; ++i; } if(l) { content[ind] = content[content.size()-1]; content.pop_back(); } return l; } unsigned int FileSystem::getSize() { unsigned int sum = 0; for(int i = 0; i < content.size(); i++) { sum += content[i]->getSize(); } return sum; }
546994c9c225a9d9a422fdfdb0ddb0501c4a572e
4aba7432993fd407f8a6999e6fe3d809d9f38c13
/include/Obbligato/Platform_Win32.hpp
3a59e53d8130c304b990b5ed3c678b842d539396
[]
no_license
jdkoftinoff/Obbligato
cc6243e4195127365a95f64dd7e467a345761d4d
f4dc5b3ef7f107b23f664a9bd7e157bf6c6f190b
refs/heads/master
2020-05-17T03:23:04.141450
2015-08-30T04:11:24
2015-08-30T04:11:24
7,463,372
1
1
null
null
null
null
UTF-8
C++
false
false
2,246
hpp
Platform_Win32.hpp
#pragma once /* Copyright (c) 2013, J.D. Koftinoff Software, Ltd. <jeffk@jdkoftinoff.com> http://www.jdkoftinoff.com/ All rights reserved. Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #ifdef _WIN32 #undef NTDDI_VERSION #define NTDDI_VERSION 0x06010000 #undef WINVER #define WINVER 0x601 #undef _WIN32_WINNT #define _WIN32_WINNT 0x601 #ifndef BYTE_ORDER #define BYTE_ORDER 1234 #endif #ifndef LITTLE_ENDIAN #define LITTLE_ENDIAN 1234 #endif #ifndef BIG_ENDIAN #define BIG_ENDIAN 4321 #endif #ifdef _MSC_VER #include <WinSDKVer.h> #include <SDKDDKVer.h> #include <WinSock2.h> #include <windows.h> #include <WS2ipdef.h> #include <WS2tcpip.h> #include <Iphlpapi.h> #if _MSC_VER < 1800 #ifndef ssize_t #define ssize_t SSIZE_T #endif #else # ifdef _WIN64 typedef __int64 ssize_t; # else typedef __int32 ssize_t; # endif #include <stdint.h> #include <inttypes.h> #include <stdbool.h> #endif #else #include <WinSock2.h> #include <windows.h> #include <WS2ipdef.h> #include <WS2tcpip.h> #include <Iphlpapi.h> #ifndef AF_LINK /// MINGW for WIN32 is missing AF_LINK and sockaddr_dl for WINVER >= /// 0x601 #undef AF_MAX #define AF_LINK 33 #define AF_MAX 34 typedef struct sockaddr_dl { ADDRESS_FAMILY sdl_family; UCHAR sdl_data[8]; UCHAR sdl_zero[4]; } SOCKADDR_DL, *PSOCKADDR_DL; #endif #ifndef AI_NUMERICSERV #define AI_NUMERICSERV 0x00000008 #endif #endif typedef SOCKET socket_fd_t; inline void sleep( int sec ) { Sleep( sec * 1000 ); } inline void usleep( int usec ) { Sleep( usec / 1000 ); } namespace Obbligato { namespace Platform { } } #endif
70cb6f908884e42bdda32950325302ec48d9266a
f0a26ec6b779e86a62deaf3f405b7a83868bc743
/Engine/Source/Editor/UnrealEd/Private/LinkedObjEditor.cpp
b7613d717dba3a3e7f9d1b7d1e579ba748ff9e90
[]
no_license
Tigrouzen/UnrealEngine-4
0f15a56176439aef787b29d7c80e13bfe5c89237
f81fe535e53ac69602bb62c5857bcdd6e9a245ed
refs/heads/master
2021-01-15T13:29:57.883294
2014-03-20T15:12:46
2014-03-20T15:12:46
18,375,899
1
0
null
null
null
null
UTF-8
C++
false
false
39,356
cpp
LinkedObjEditor.cpp
// Copyright 1998-2014 Epic Games, Inc. All Rights Reserved. /*============================================================================= UnLinkedEdInterface.cpp: Base class for boxes-and-lines editing =============================================================================*/ #include "UnrealEd.h" #include "LinkedObjEditor.h" #include "LinkedObjDrawUtils.h" const static float LinkedObjectEditor_ZoomIncrement = 0.1f; const static float LinkedObjectEditor_ZoomSpeed = 0.005f; const static float LinkedObjectEditor_ZoomNotchThresh = 0.007f; const static int32 LinkedObjectEditor_ScrollBorderSize = 20; const static float LinkedObjectEditor_ScrollBorderSpeed = 400.f; /*----------------------------------------------------------------------------- FLinkedObjViewportClient -----------------------------------------------------------------------------*/ FLinkedObjViewportClient::FLinkedObjViewportClient( FLinkedObjEdNotifyInterface* InEdInterface ) : bAlwaysDrawInTick( false ) { // No funky rendering features EngineShowFlags.PostProcessing = 0; EngineShowFlags.HMDDistortion = 0; EngineShowFlags.DisableAdvancedFeatures(); // This window will be 2D/canvas only, so set the viewport type to None ViewportType = LVT_None; EdInterface = InEdInterface; Origin2D = FIntPoint(0, 0); Zoom2D = 1.0f; MinZoom2D = 0.1f; MaxZoom2D = 1.f; bMouseDown = false; OldMouseX = 0; OldMouseY = 0; BoxStartX = 0; BoxStartY = 0; BoxEndX = 0; BoxEndY = 0; DeltaXFraction = 0.0f; DeltaYFraction = 0.0f; ScrollAccum = FVector2D::ZeroVector; DistanceDragged = 0; bTransactionBegun = false; bMakingLine = false; bMovingConnector = false; bSpecialDrag = false; bBoxSelecting = false; bAllowScroll = true; bHasMouseCapture = false; bShowCursorOverride = true; bIsScrolling = false; MouseOverObject = NULL; MouseOverTime = 0.f; ToolTipDelayMS = -1; GConfig->GetInt( TEXT( "ToolTips" ), TEXT( "DelayInMS" ), ToolTipDelayMS, GEditorUserSettingsIni ); SpecialIndex = 0; DesiredPanTime = 0.f; NewX = NewY = 0; SetRealtime( false ); } void FLinkedObjViewportClient::Draw(FViewport* Viewport, FCanvas* Canvas) { Canvas->PushAbsoluteTransform(FScaleMatrix(Zoom2D) * FTranslationMatrix(FVector(Origin2D.X,Origin2D.Y,0))); { // Erase background Canvas->Clear( FColor(197,197,197) ); EdInterface->DrawObjects( Viewport, Canvas ); // Draw new line if(bMakingLine && !Canvas->IsHitTesting()) { FIntPoint StartPoint = EdInterface->GetSelectedConnLocation(Canvas); FIntPoint EndPoint( (NewX - Origin2D.X)/Zoom2D, (NewY - Origin2D.Y)/Zoom2D ); int32 ConnType = EdInterface->GetSelectedConnectorType(); FColor LinkColor = EdInterface->GetMakingLinkColor(); // Curves { float Tension; if(ConnType == LOC_INPUT || ConnType == LOC_OUTPUT) { Tension = FMath::Abs<int32>(StartPoint.X - EndPoint.X); } else { Tension = FMath::Abs<int32>(StartPoint.Y - EndPoint.Y); } if(ConnType == LOC_INPUT) { FLinkedObjDrawUtils::DrawSpline(Canvas, StartPoint, Tension*FVector2D(-1,0), EndPoint, Tension*FVector2D(-1,0), LinkColor, false); } else if(ConnType == LOC_OUTPUT) { FLinkedObjDrawUtils::DrawSpline(Canvas, StartPoint, Tension*FVector2D(1,0), EndPoint, Tension*FVector2D(1,0), LinkColor, false); } else if(ConnType == LOC_VARIABLE) { FLinkedObjDrawUtils::DrawSpline(Canvas, StartPoint, Tension*FVector2D(0,1), EndPoint, FVector2D::ZeroVector, LinkColor, false); } else { FLinkedObjDrawUtils::DrawSpline(Canvas, StartPoint, Tension*FVector2D(0,1), EndPoint, Tension*FVector2D(0,1), LinkColor, false); } } } } Canvas->PopTransform(); Canvas->PushAbsoluteTransform(FTranslationMatrix(FVector(Origin2D.X,Origin2D.Y,0))); { // Draw the box select box if(bBoxSelecting) { int32 MinX = (FMath::Min(BoxStartX, BoxEndX) - BoxOrigin2D.X); int32 MinY = (FMath::Min(BoxStartY, BoxEndY) - BoxOrigin2D.Y); int32 MaxX = (FMath::Max(BoxStartX, BoxEndX) - BoxOrigin2D.X); int32 MaxY = (FMath::Max(BoxStartY, BoxEndY) - BoxOrigin2D.Y); FCanvasBoxItem BoxItem( FVector2D(MinX, MinY), FVector2D(BoxEndX-BoxStartX, BoxEndY-BoxStartY) ); BoxItem.SetColor( FLinearColor::Red ); Canvas->DrawItem( BoxItem ); } } Canvas->PopTransform(); } bool FLinkedObjViewportClient::InputKey(FViewport* Viewport, int32 ControllerId, FKey Key, EInputEvent Event, float /*AmountDepressed*/,bool /*Gamepad*/) { bool bHandled = false; const bool bCtrlDown = Viewport->KeyState(EKeys::LeftControl) || Viewport->KeyState(EKeys::RightControl); const bool bShiftDown = Viewport->KeyState(EKeys::LeftShift) || Viewport->KeyState(EKeys::RightShift); const bool bAltDown = Viewport->KeyState(EKeys::LeftAlt) || Viewport->KeyState(EKeys::RightAlt); const int32 HitX = Viewport->GetMouseX(); const int32 HitY = Viewport->GetMouseY(); const bool LeftMouseButtonDown = Viewport->KeyState(EKeys::LeftMouseButton) ? true : false; const bool MiddleMouseButtonDown = Viewport->KeyState(EKeys::MiddleMouseButton) ? true : false; const bool RightMouseButtonDown = Viewport->KeyState(EKeys::RightMouseButton) ? true : false; const bool bAnyMouseButtonsDown = (LeftMouseButtonDown || MiddleMouseButtonDown || RightMouseButtonDown ); const bool bAllMouseButtonsUp = !bAnyMouseButtonsDown; if (bAnyMouseButtonsDown && Event == IE_Pressed) {bHasMouseCapture = true;} else if (bAllMouseButtonsUp && Event == IE_Released) {bHasMouseCapture = false;} if ( !bHasMouseCapture ) { Viewport->ShowCursor( true ); Viewport->LockMouseToViewport( false ); } static bool bDoubleClicking = false; static EInputEvent LastEvent = IE_Pressed; if( Key == EKeys::LeftMouseButton ) { switch( Event ) { case IE_Pressed: case IE_DoubleClick: { if (Event == IE_DoubleClick) { bDoubleClicking = true; } DeltaXFraction = 0.0f; DeltaYFraction = 0.0f; HHitProxy* HitResult = Viewport->GetHitProxy(HitX,HitY); if( HitResult ) { // Handle click/double-click on line proxy if ( HitResult->IsA( HLinkedObjLineProxy::StaticGetType() ) ) { // clicked on a line HLinkedObjLineProxy *LineProxy = (HLinkedObjLineProxy*)HitResult; if ( Event == IE_Pressed ) { if( !EdInterface->HaveObjectsSelected() ) { EdInterface->ClickedLine(LineProxy->Src,LineProxy->Dest); } } else if ( Event == IE_DoubleClick ) { EdInterface->DoubleClickedLine( LineProxy->Src,LineProxy->Dest ); } } // Handle click/double-click on object proxy else if( HitResult->IsA( HLinkedObjProxy::StaticGetType() ) ) { UObject* Obj = ( (HLinkedObjProxy*)HitResult )->Obj; if( !bCtrlDown ) { if( Event == IE_DoubleClick ) { EdInterface->EmptySelection(); EdInterface->AddToSelection( Obj ); EdInterface->UpdatePropertyWindow(); EdInterface->DoubleClickedObject( Obj ); bMouseDown = false; return true; } else if( !EdInterface->HaveObjectsSelected() ) { // if there are no objects selected add this object. // if objects are selected, we should not clear the selection until a mouse up occurs // since the user might be trying to pan. Panning should not break selection. EdInterface->AddToSelection( Obj ); EdInterface->UpdatePropertyWindow(); } } } // Handle click/double-click on connector proxy else if( HitResult->IsA(HLinkedObjConnectorProxy::StaticGetType()) ) { HLinkedObjConnectorProxy* ConnProxy = (HLinkedObjConnectorProxy*)HitResult; EdInterface->SetSelectedConnector( ConnProxy->Connector ); EdInterface->EmptySelection(); EdInterface->UpdatePropertyWindow(); if ( bAltDown ) { // break the connectors EdInterface->AltClickConnector( ConnProxy->Connector ); } else if( bCtrlDown ) { // Begin moving a connector if ctrl+mouse click over a connector was done bMovingConnector = true; EdInterface->SetSelectedConnectorMoving( bMovingConnector ); } else { if ( Event == IE_DoubleClick ) { EdInterface->DoubleClickedConnector( ConnProxy->Connector ); } else { bMakingLine = true; NewX = HitX; NewY = HitY; } } } // Handle click/double-click on special proxy else if( HitResult->IsA(HLinkedObjProxySpecial::StaticGetType()) ) { HLinkedObjProxySpecial* SpecialProxy = (HLinkedObjProxySpecial*)HitResult; // Copy properties out of SpecialProxy first, in case it gets invalidated! int32 ProxyIndex = SpecialProxy->SpecialIndex; UObject* ProxyObj = SpecialProxy->Obj; FIntPoint MousePos( (HitX - Origin2D.X)/Zoom2D, (HitY - Origin2D.Y)/Zoom2D ); // If object wasn't selected already OR // we didn't handle it all in special click - change selection if( !EdInterface->IsInSelection( ProxyObj ) || !EdInterface->SpecialClick( MousePos.X, MousePos.Y, ProxyIndex, Viewport, ProxyObj ) ) { bSpecialDrag = true; SpecialIndex = ProxyIndex; // Slightly quirky way of avoiding selecting the same thing again. if( !( EdInterface->GetNumSelected() == 1 && EdInterface->IsInSelection( ProxyObj ) ) ) { EdInterface->EmptySelection(); EdInterface->AddToSelection( ProxyObj ); EdInterface->UpdatePropertyWindow(); } // For supporting undo EdInterface->BeginTransactionOnSelected(); bTransactionBegun = true; } } } else { if( bCtrlDown && bAltDown ) { BoxOrigin2D = Origin2D; BoxStartX = BoxEndX = HitX; BoxStartY = BoxEndY = HitY; bBoxSelecting = true; } } OldMouseX = HitX; OldMouseY = HitY; //default to not having moved yet bHasMouseMovedSinceClick = false; DistanceDragged = 0; bMouseDown = true; if( !bMakingLine && !bBoxSelecting && !bSpecialDrag && !(bCtrlDown && EdInterface->HaveObjectsSelected()) && bAllowScroll ) { } else { Viewport->LockMouseToViewport(true); } Viewport->Invalidate(); } break; case IE_Released: { if( bMakingLine ) { Viewport->Invalidate(); HHitProxy* HitResult = Viewport->GetHitProxy( HitX,HitY ); if( HitResult ) { if( HitResult->IsA(HLinkedObjConnectorProxy::StaticGetType()) ) { HLinkedObjConnectorProxy* EndConnProxy = (HLinkedObjConnectorProxy*)HitResult; if( DistanceDragged < 4 ) { HLinkedObjConnectorProxy* ConnProxy = (HLinkedObjConnectorProxy*)HitResult; bool bDoDeselect = EdInterface->ClickOnConnector( EndConnProxy->Connector.ConnObj, EndConnProxy->Connector.ConnType, EndConnProxy->Connector.ConnIndex ); if( bDoDeselect && LastEvent != IE_DoubleClick ) { EdInterface->EmptySelection(); EdInterface->UpdatePropertyWindow(); } } else if ( bAltDown ) { EdInterface->AltClickConnector( EndConnProxy->Connector ); } else { EdInterface->MakeConnectionToConnector( EndConnProxy->Connector ); } } else if( HitResult->IsA(HLinkedObjProxy::StaticGetType()) ) { UObject* Obj = ( (HLinkedObjProxy*)HitResult )->Obj; EdInterface->MakeConnectionToObject( Obj ); } } } else if( bBoxSelecting ) { // When box selecting, the region that user boxed can be larger than the size of the viewport // so we use the viewport as a max region and loop through the box, rendering different chunks of it // and reading back its hit proxy map to check for objects. TArray<UObject*> NewSelection; // Save the current origin since we will be modifying it. FVector2D SavedOrigin2D; SavedOrigin2D.X = Origin2D.X; SavedOrigin2D.Y = Origin2D.Y; // Calculate the size of the box and its extents. const int32 MinX = FMath::Min(BoxStartX, BoxEndX); const int32 MinY = FMath::Min(BoxStartY, BoxEndY); const int32 MaxX = FMath::Max(BoxStartX, BoxEndX) + 1; const int32 MaxY = FMath::Max(BoxStartY, BoxEndY) + 1; const int32 ViewX = Viewport->GetSizeXY().X-1; const int32 ViewY = Viewport->GetSizeXY().Y-1; const int32 BoxSizeX = MaxX - MinX; const int32 BoxSizeY = MaxY - MinY; const float BoxMinX = MinX-BoxOrigin2D.X; const float BoxMinY = MinY-BoxOrigin2D.Y; const float BoxMaxX = BoxMinX + BoxSizeX; const float BoxMaxY = BoxMinY + BoxSizeY; // Loop through 'tiles' of the box using the viewport size as our maximum tile size. int32 TestSizeX = FMath::Min(ViewX, BoxSizeX); int32 TestSizeY = FMath::Min(ViewY, BoxSizeY); float TestStartX = BoxMinX; float TestStartY = BoxMinY; while(TestStartX < BoxMaxX) { TestStartY = BoxMinY; TestSizeY = FMath::Min(ViewY, BoxSizeY); while(TestStartY < BoxMaxY) { // We read back the hit proxy map for the required region. Origin2D.X = -TestStartX; Origin2D.Y = -TestStartY; TArray<HHitProxy*> ProxyMap; Viewport->Invalidate(); Viewport->InvalidateHitProxy(); Viewport->GetHitProxyMap( FIntRect(0, 0, TestSizeX + 1, TestSizeY + 1), ProxyMap ); // Todo: something is wrong here, we request the rectable bigger than we now process it. // This code will go away at some point so we don't change it for now // Find any keypoint hit proxies in the region - add the keypoint to selection. for( int32 Y=0; Y < TestSizeY; Y++ ) { for( int32 X=0; X < TestSizeX; X++ ) { HHitProxy* HitProxy = NULL; int32 ProxyMapIndex = Y * TestSizeX + X; // calculate location in proxy map if( ProxyMapIndex < ProxyMap.Num() ) // If within range, grab the hit proxy from there { HitProxy = ProxyMap[ProxyMapIndex]; } UObject* SelObject = NULL; // If we got one, add it to the NewSelection list. if( HitProxy ) { if(HitProxy->IsA(HLinkedObjProxy::StaticGetType())) { SelObject = ((HLinkedObjProxy*)HitProxy)->Obj; } // Special case for the little resizer triangles in the bottom right corner of comment frames else if( HitProxy->IsA(HLinkedObjProxySpecial::StaticGetType()) ) { SelObject = NULL; } if( SelObject ) { // Don't want to call AddToSelection here because that might invalidate the display and we'll crash. NewSelection.AddUnique( SelObject ); } } } } TestStartY += ViewY; TestSizeY = FMath::Min(ViewY, FMath::Trunc(BoxMaxY - TestStartY)); } TestStartX += ViewX; TestSizeX = FMath::Min(ViewX, FMath::Trunc(BoxMaxX - TestStartX)); } // restore the original viewport settings Origin2D.X = SavedOrigin2D.X; Origin2D.Y = SavedOrigin2D.Y; // If shift is down, don't empty, just add to selection. if( !bShiftDown ) { EdInterface->EmptySelection(); } // Iterate over array adding each to selection. for( int32 i=0; i<NewSelection.Num(); i++ ) { EdInterface->AddToSelection( NewSelection[i] ); } EdInterface->UpdatePropertyWindow(); } else { HHitProxy* HitResult = Viewport->GetHitProxy(HitX,HitY); // If mouse didn't really move since last time, and we released over empty space, deselect everything. if( !HitResult && DistanceDragged < 4 ) { NewX = HitX; NewY = HitY; const bool bDoDeselect = EdInterface->ClickOnBackground() && !bCtrlDown; if( bDoDeselect && LastEvent != IE_DoubleClick ) { EdInterface->EmptySelection(); EdInterface->UpdatePropertyWindow(); } } // If we've hit something and not really dragged anywhere, attempt to select // whatever has been hit else if ( HitResult && DistanceDragged < 4 ) { // Released on a line if ( HitResult->IsA(HLinkedObjLineProxy::StaticGetType()) ) { HLinkedObjLineProxy *LineProxy = (HLinkedObjLineProxy*)HitResult; EdInterface->ClickedLine( LineProxy->Src,LineProxy->Dest ); } // Released on an object else if( HitResult->IsA(HLinkedObjProxy::StaticGetType()) ) { UObject* Obj = (( HLinkedObjProxy*)HitResult )->Obj; if( !bCtrlDown ) { EdInterface->EmptySelection(); EdInterface->AddToSelection(Obj); } else if( EdInterface->IsInSelection( Obj ) ) { // Remove the object from selection its in the selection and this isn't the initial click where the object was added EdInterface->RemoveFromSelection( Obj ); } // At this point, the user CTRL-clicked on an unselected kismet object. // Since the the user isn't dragging, add the object the selection. else { // The user is trying to select multiple objects at once EdInterface->AddToSelection( Obj ); } if (!bDoubleClicking) { EdInterface->UpdatePropertyWindow(); } } } else if( bCtrlDown && DistanceDragged >= 4 ) { EdInterface->PositionSelectedObjects(); } } if( bTransactionBegun ) { EdInterface->EndTransactionOnSelected(); bTransactionBegun = false; } bMouseDown = false; bMakingLine = false; // Mouse was released, stop moving the connector bMovingConnector = false; EdInterface->SetSelectedConnectorMoving( bMovingConnector ); bSpecialDrag = false; bBoxSelecting = false; Viewport->LockMouseToViewport( false ); Viewport->Invalidate(); bDoubleClicking = false; } break; } bHandled = true; } else if( Key == EKeys::RightMouseButton ) { switch( Event ) { case IE_Pressed: { NewX = Viewport->GetMouseX(); NewY = Viewport->GetMouseY(); DeltaXFraction = 0.0f; DeltaYFraction = 0.0f; DistanceDragged = 0; } break; case IE_Released: { Viewport->Invalidate(); if( bTransactionBegun ) { EdInterface->EndTransactionOnSelected(); bTransactionBegun = false; } if(bMakingLine || Viewport->KeyState(EKeys::LeftMouseButton)) break; // If right clicked and dragged - don't pop up menu. Have to click and release in roughly the same spot. if( FMath::Abs(HitX - NewX) + FMath::Abs(HitY - NewY) > 4 || DistanceDragged > 4) break; HHitProxy* HitResult = Viewport->GetHitProxy(HitX,HitY); if(!HitResult) { EdInterface->OpenNewObjectMenu(); } else { if( HitResult->IsA(HLinkedObjConnectorProxy::StaticGetType()) ) { HLinkedObjConnectorProxy* ConnProxy = (HLinkedObjConnectorProxy*)HitResult; // First select the connector and deselect any objects. EdInterface->SetSelectedConnector( ConnProxy->Connector ); EdInterface->EmptySelection(); EdInterface->UpdatePropertyWindow(); Viewport->Invalidate(); // Then open connector options menu. EdInterface->OpenConnectorOptionsMenu(); } else if( HitResult->IsA(HLinkedObjProxy::StaticGetType()) ) { // When right clicking on an unselected object, select it only before opening menu. UObject* Obj = ((HLinkedObjProxy*)HitResult)->Obj; if( !EdInterface->IsInSelection(Obj) ) { EdInterface->EmptySelection(); EdInterface->AddToSelection(Obj); EdInterface->UpdatePropertyWindow(); Viewport->Invalidate(); } EdInterface->OpenObjectOptionsMenu(); } } } break; } bHandled = true; } else if ( (Key == EKeys::MouseScrollDown || Key == EKeys::MouseScrollUp) && Event == IE_Pressed ) { // Mousewheel up/down zooms in/out. const float DeltaZoom = (Key == EKeys::MouseScrollDown ? -LinkedObjectEditor_ZoomIncrement : LinkedObjectEditor_ZoomIncrement ); if( (DeltaZoom < 0.f && Zoom2D > MinZoom2D) || (DeltaZoom > 0.f && Zoom2D < MaxZoom2D) ) { //Default zooming to center of the viewport float CenterOfZoomX = Viewport->GetSizeXY().X*0.5f; float CenterOfZoomY= Viewport->GetSizeXY().Y*0.5f; if (GetDefault<ULevelEditorViewportSettings>()->bCenterZoomAroundCursor) { //center of zoom is now around the mouse CenterOfZoomX = OldMouseX; CenterOfZoomY = OldMouseY; } //Old offset const float ViewCenterX = (CenterOfZoomX - Origin2D.X)/Zoom2D; const float ViewCenterY = (CenterOfZoomY - Origin2D.Y)/Zoom2D; //change zoom ratio Zoom2D = FMath::Clamp<float>(Zoom2D+DeltaZoom,MinZoom2D,MaxZoom2D); //account for new offset float DrawOriginX = ViewCenterX - (CenterOfZoomX/Zoom2D); float DrawOriginY = ViewCenterY - (CenterOfZoomY/Zoom2D); //move origin by delta we've calculated Origin2D.X = -(DrawOriginX * Zoom2D); Origin2D.Y = -(DrawOriginY * Zoom2D); EdInterface->ViewPosChanged(); Viewport->Invalidate(); } bHandled = true; } // Handle the user pressing the first thumb mouse button else if ( Key == EKeys::ThumbMouseButton && Event == IE_Pressed && !bMouseDown ) { // Attempt to set the navigation history for the ed interface back an entry EdInterface->NavigationHistoryBack(); bHandled = true; } // Handle the user pressing the second thumb mouse button else if ( Key == EKeys::ThumbMouseButton2 && Event == IE_Pressed && !bMouseDown ) { // Attempt to set the navigation history for the ed interface forward an entry EdInterface->NavigationHistoryForward(); bHandled = true; } else if ( Event == IE_Pressed ) { // Bookmark support TCHAR CurChar = 0; if( Key == EKeys::Zero ) CurChar = '0'; else if( Key == EKeys::One ) CurChar = '1'; else if( Key == EKeys::Two ) CurChar = '2'; else if( Key == EKeys::Three ) CurChar = '3'; else if( Key == EKeys::Four ) CurChar = '4'; else if( Key == EKeys::Five ) CurChar = '5'; else if( Key == EKeys::Six ) CurChar = '6'; else if( Key == EKeys::Seven ) CurChar = '7'; else if( Key == EKeys::Eight ) CurChar = '8'; else if( Key == EKeys::Nine ) CurChar = '9'; if( ( CurChar >= '0' && CurChar <= '9' ) && !bAltDown && !bShiftDown && !bMouseDown) { // Determine the bookmark index based on the input key const int32 BookmarkIndex = CurChar - '0'; // CTRL+# will set a bookmark, # will jump to it. if( bCtrlDown ) { EdInterface->SetBookmark( BookmarkIndex ); } else { EdInterface->JumpToBookmark( BookmarkIndex ); } bHandled = true; } } if(EdInterface->EdHandleKeyInput(Viewport, Key, Event)) { bHandled = true; } LastEvent = Event; // Hide and lock mouse cursor if we're capturing mouse input. // But don't hide mouse cursor if drawing lines and other special cases. bool bCanLockMouse = (Key == EKeys::LeftMouseButton) || (Key == EKeys::RightMouseButton); if ( bHasMouseCapture && bCanLockMouse ) { //Update cursor and lock to window if invisible bool bShowCursor = UpdateCursorVisibility (); bool bDraggingObject = (bCtrlDown && EdInterface->HaveObjectsSelected()); Viewport->LockMouseToViewport( !bShowCursor || bDraggingObject || bMakingLine || bBoxSelecting || bSpecialDrag); } // Handle viewport screenshot. InputTakeScreenshot( Viewport, Key, Event ); return bHandled; } void FLinkedObjViewportClient::MouseMove(FViewport* Viewport, int32 X, int32 Y) { int32 DeltaX = X - OldMouseX; int32 DeltaY = Y - OldMouseY; OldMouseX = X; OldMouseY = Y; // Do mouse-over stuff (if mouse button is not held). OnMouseOver( X, Y ); } void FLinkedObjViewportClient::CapturedMouseMove( FViewport* InViewport, int32 InMouseX, int32 InMouseY ) { FEditorViewportClient::CapturedMouseMove(InViewport, InMouseX, InMouseY); // This is a hack put in place to make the slate material editor work ok // Because this runs InputAxis through Tick, any ShowCursor handling is overwritten during OnMouseMove. // As a result, this hack redoes the ShowCursor part during OnMouseMove as well. // It should be removed when either we use the SGraphPanel or when reworking the input scheme if (bIsScrolling) { Viewport->ShowCursor(bShowCursorOverride); } } /** Handle mouse over events */ void FLinkedObjViewportClient::OnMouseOver( int32 X, int32 Y ) { // Do mouse-over stuff (if mouse button is not held). UObject *NewMouseOverObject = NULL; int32 NewMouseOverConnType = -1; int32 NewMouseOverConnIndex = INDEX_NONE; HHitProxy* HitResult = NULL; if(!bMouseDown || bMakingLine) { HitResult = Viewport->GetHitProxy(X,Y); } if( HitResult ) { if( HitResult->IsA(HLinkedObjProxy::StaticGetType()) ) { NewMouseOverObject = ((HLinkedObjProxy*)HitResult)->Obj; } else if( HitResult->IsA(HLinkedObjConnectorProxy::StaticGetType()) ) { NewMouseOverObject = ((HLinkedObjConnectorProxy*)HitResult)->Connector.ConnObj; NewMouseOverConnType = ((HLinkedObjConnectorProxy*)HitResult)->Connector.ConnType; NewMouseOverConnIndex = ((HLinkedObjConnectorProxy*)HitResult)->Connector.ConnIndex; if( !EdInterface->ShouldHighlightConnector(((HLinkedObjConnectorProxy*)HitResult)->Connector) ) { NewMouseOverConnType = -1; NewMouseOverConnIndex = INDEX_NONE; } } else if (HitResult->IsA(HLinkedObjLineProxy::StaticGetType()) && !bMakingLine) // don't mouse-over lines when already creating a line { HLinkedObjLineProxy *LineProxy = (HLinkedObjLineProxy*)HitResult; NewMouseOverObject = LineProxy->Src.ConnObj; NewMouseOverConnType = LineProxy->Src.ConnType; NewMouseOverConnIndex = LineProxy->Src.ConnIndex; } } if( NewMouseOverObject != MouseOverObject || NewMouseOverConnType != MouseOverConnType || NewMouseOverConnIndex != MouseOverConnIndex ) { MouseOverObject = NewMouseOverObject; MouseOverConnType = NewMouseOverConnType; MouseOverConnIndex = NewMouseOverConnIndex; MouseOverTime = FPlatformTime::Seconds(); Viewport->InvalidateDisplay(); EdInterface->OnMouseOver(MouseOverObject); } } bool FLinkedObjViewportClient::InputAxis(FViewport* Viewport, int32 ControllerId, FKey Key, float Delta, float DeltaTime, int32 NumSamples, bool bGamepad) { bShowCursorOverride = true; bIsScrolling = false; const bool LeftMouseButtonDown = Viewport->KeyState(EKeys::LeftMouseButton) ? true : false; const bool MiddleMouseButtonDown = Viewport->KeyState(EKeys::MiddleMouseButton) ? true : false; const bool RightMouseButtonDown = Viewport->KeyState(EKeys::RightMouseButton) ? true : false; const bool bMouseButtonDown = (LeftMouseButtonDown || MiddleMouseButtonDown || RightMouseButtonDown ); bool bCtrlDown = Viewport->KeyState(EKeys::LeftControl) || Viewport->KeyState(EKeys::RightControl); bool bShiftDown = Viewport->KeyState(EKeys::LeftShift) || Viewport->KeyState(EKeys::RightShift); // DeviceDelta is not constricted to mouse locks float DeviceDeltaX = (Key == EKeys::MouseX) ? Delta : 0; float DeviceDeltaY = (Key == EKeys::MouseY) ? -Delta : 0; // Mouse variables represent the actual (potentially constrained) location of the mouse int32 MouseX = Viewport->GetMouseX(); int32 MouseY = Viewport->GetMouseY(); int32 MouseDeltaX = MouseX - OldMouseX; int32 MouseDeltaY = MouseY - OldMouseY; // Accumulate delta fractions, since these will get dropped when truncated to int32. DeltaXFraction += MouseDeltaX * (1.f/Zoom2D) - int32(MouseDeltaX * (1.f/Zoom2D)); DeltaYFraction += MouseDeltaY * (1.f/Zoom2D) - int32(MouseDeltaY * (1.f/Zoom2D)); int32 DeltaXAdd = int32(DeltaXFraction); int32 DeltaYAdd = int32(DeltaYFraction); DeltaXFraction -= DeltaXAdd; DeltaYFraction -= DeltaYAdd; bool bLeftMouseButtonDown = Viewport->KeyState(EKeys::LeftMouseButton); bool bRightMouseButtonDown = Viewport->KeyState(EKeys::RightMouseButton); if( Key == EKeys::MouseX || Key == EKeys::MouseY ) { DistanceDragged += FMath::Abs(MouseDeltaX) + FMath::Abs(MouseDeltaY); } // If holding both buttons, we are zooming. if(bLeftMouseButtonDown && bRightMouseButtonDown) { if(Key == EKeys::MouseY) { //Always zoom around center for two button zoom float CenterOfZoomX = Viewport->GetSizeXY().X*0.5f; float CenterOfZoomY= Viewport->GetSizeXY().Y*0.5f; const float ZoomDelta = -Zoom2D * Delta * LinkedObjectEditor_ZoomSpeed; const float ViewCenterX = (CenterOfZoomX - (float)Origin2D.X)/Zoom2D; const float ViewCenterY = (CenterOfZoomY - (float)Origin2D.Y)/Zoom2D; Zoom2D = FMath::Clamp<float>(Zoom2D+ZoomDelta,MinZoom2D,MaxZoom2D); // We have a 'notch' around 1.f to make it easy to get back to normal zoom factor. if( FMath::Abs(Zoom2D - 1.f) < LinkedObjectEditor_ZoomNotchThresh ) { Zoom2D = 1.f; } const float DrawOriginX = ViewCenterX - (CenterOfZoomX/Zoom2D); const float DrawOriginY = ViewCenterY - (CenterOfZoomY/Zoom2D); Origin2D.X = -FMath::Round(DrawOriginX * Zoom2D); Origin2D.Y = -FMath::Round(DrawOriginY * Zoom2D); EdInterface->ViewPosChanged(); Viewport->Invalidate(); } } else if(bLeftMouseButtonDown || bRightMouseButtonDown) { bool bInvalidate = false; if(bMakingLine) { NewX = MouseX; NewY = MouseY; bInvalidate = true; } else if(bBoxSelecting) { BoxEndX = MouseX + (BoxOrigin2D.X - Origin2D.X); BoxEndY = MouseY + (BoxOrigin2D.Y - Origin2D.Y); bInvalidate = true; } else if(bSpecialDrag) { FIntPoint MousePos( (MouseX - Origin2D.X)/Zoom2D, (MouseY - Origin2D.Y)/Zoom2D ); EdInterface->SpecialDrag( MouseDeltaX * (1.f/Zoom2D) + DeltaXAdd, MouseDeltaY * (1.f/Zoom2D) + DeltaYAdd, MousePos.X, MousePos.Y, SpecialIndex ); bInvalidate = true; } else if( bCtrlDown && EdInterface->HaveObjectsSelected() ) { EdInterface->MoveSelectedObjects( MouseDeltaX * (1.f/Zoom2D) + DeltaXAdd, MouseDeltaY * (1.f/Zoom2D) + DeltaYAdd ); // If haven't started a transaction, and moving some stuff, and have moved mouse far enough, start transaction now. if(!bTransactionBegun && DistanceDragged > 4) { EdInterface->BeginTransactionOnSelected(); bTransactionBegun = true; } bInvalidate = true; } else if( bCtrlDown && bMovingConnector ) { // A connector is being moved. Calculate the delta it should move const float InvZoom2D = 1.f/Zoom2D; int32 DX = MouseDeltaX * InvZoom2D + DeltaXAdd; int32 DY = MouseDeltaY * InvZoom2D + DeltaYAdd; EdInterface->MoveSelectedConnLocation(DX,DY); bInvalidate = true; } else if(bAllowScroll && bHasMouseCapture) { //Default to using device delta int32 DeltaXForScroll; int32 DeltaYForScroll; if (GetDefault<ULevelEditorViewportSettings>()->bPanMovesCanvas) { //override to stay with the mouse. it's pixel accurate. DeltaXForScroll = DeviceDeltaX; DeltaYForScroll = DeviceDeltaY; if (DeltaXForScroll || DeltaYForScroll) { MarkMouseMovedSinceClick(); } //assign both so the updates work right (now) AND the assignment at the bottom works (after). OldMouseX = MouseX = OldMouseX + DeviceDeltaX; OldMouseY = MouseY = OldMouseY + DeviceDeltaY; bShowCursorOverride = UpdateCursorVisibility(); bIsScrolling = true; UpdateMousePosition(); } else { DeltaXForScroll = -DeviceDeltaX; DeltaYForScroll = -DeviceDeltaY; } Origin2D.X += DeltaXForScroll; Origin2D.Y += DeltaYForScroll; EdInterface->ViewPosChanged(); bInvalidate = true; } OnMouseOver( MouseX, MouseY ); if ( bInvalidate ) { Viewport->InvalidateDisplay(); } } //save the latest mouse position OldMouseX = MouseX; OldMouseY = MouseY; return true; } EMouseCursor::Type FLinkedObjViewportClient::GetCursor(FViewport* Viewport, int32 X, int32 Y) { bool bLeftDown = Viewport->KeyState(EKeys::LeftMouseButton) ? true : false; bool bRightDown = Viewport->KeyState(EKeys::RightMouseButton) ? true : false; //if we're allowed to scroll, we are in "canvas move mode" and ONLY one mouse button is down if ((bAllowScroll) && GetDefault<ULevelEditorViewportSettings>()->bPanMovesCanvas && (bLeftDown ^ bRightDown)) { const bool bCtrlDown = Viewport->KeyState(EKeys::LeftControl) || Viewport->KeyState(EKeys::RightControl); //double check there is no other overriding operation (other than panning) if (!bMakingLine && !bBoxSelecting && !bSpecialDrag) { if ((bCtrlDown && EdInterface->HaveObjectsSelected())) { return EMouseCursor::CardinalCross; } else if (bHasMouseMovedSinceClick) { return EMouseCursor::Hand; } } } return EMouseCursor::Default; } /** * Sets the cursor to be visible or not. Meant to be called as the mouse moves around in "move canvas" mode (not just on button clicks) */ bool FLinkedObjViewportClient::UpdateCursorVisibility (void) { bool bShowCursor = ShouldCursorBeVisible(); bool bCursorWasVisible = Viewport->IsCursorVisible() ; Viewport->ShowCursor( bShowCursor); //first time showing the cursor again. Update old mouse position so there isn't a jump as well. if (!bCursorWasVisible && bShowCursor) { OldMouseX = Viewport->GetMouseX(); OldMouseY = Viewport->GetMouseY(); } return bShowCursor; } /** * Given that we're in "move canvas" mode, set the snap back visible mouse position to clamp to the viewport */ void FLinkedObjViewportClient::UpdateMousePosition(void) { const int32 SizeX = Viewport->GetSizeXY().X; const int32 SizeY = Viewport->GetSizeXY().Y; int32 ClampedMouseX = FMath::Clamp<int32>(OldMouseX, 0, SizeX); int32 ClampedMouseY = FMath::Clamp<int32>(OldMouseY, 0, SizeY); Viewport->SetMouse(ClampedMouseX, ClampedMouseY); } /** Determines if the cursor should presently be visible * @return - true if the cursor should remain visible */ bool FLinkedObjViewportClient::ShouldCursorBeVisible(void) { bool bLeftDown = Viewport->KeyState(EKeys::LeftMouseButton) ? true : false; bool bRightDown = Viewport->KeyState(EKeys::RightMouseButton) ? true : false; bool bCtrlDown = Viewport->KeyState(EKeys::LeftControl) || Viewport->KeyState(EKeys::RightControl); const int32 SizeX = Viewport->GetSizeXY().X; const int32 SizeY = Viewport->GetSizeXY().Y; bool bInViewport = FMath::IsWithin<int32>(OldMouseX, 1, SizeX-1) && FMath::IsWithin<int32>(OldMouseY, 1, SizeY-1); //both mouse button zoom hides mouse as well bool bShowMouseOnScroll = (!bAllowScroll) || GetDefault<ULevelEditorViewportSettings>()->bPanMovesCanvas && (bLeftDown ^ bRightDown) && bInViewport; //if scrolling isn't allowed, or we're in "inverted" pan mode, lave the mouse visible bool bHideCursor = !bMakingLine && !bBoxSelecting && !bSpecialDrag && !(bCtrlDown && EdInterface->HaveObjectsSelected()) && !bShowMouseOnScroll; return !bHideCursor; } /** * See if cursor is in 'scroll' region around the edge, and if so, scroll the view automatically. * Returns the distance that the view was moved. */ FIntPoint FLinkedObjViewportClient::DoScrollBorder(float DeltaTime) { FIntPoint Result( 0, 0 ); if (bAllowScroll) { const int32 PosX = Viewport->GetMouseX(); const int32 PosY = Viewport->GetMouseY(); const int32 SizeX = Viewport->GetSizeXY().X; const int32 SizeY = Viewport->GetSizeXY().Y; DeltaTime = FMath::Clamp(DeltaTime, 0.01f, 1.0f); if(PosX < LinkedObjectEditor_ScrollBorderSize) { ScrollAccum.X += (1.f - ((float)PosX/(float)LinkedObjectEditor_ScrollBorderSize)) * LinkedObjectEditor_ScrollBorderSpeed * DeltaTime; } else if(PosX > SizeX - LinkedObjectEditor_ScrollBorderSize) { ScrollAccum.X -= ((float)(PosX - (SizeX - LinkedObjectEditor_ScrollBorderSize))/(float)LinkedObjectEditor_ScrollBorderSize) * LinkedObjectEditor_ScrollBorderSpeed * DeltaTime; } else { ScrollAccum.X = 0.f; } float ScrollY = 0.f; if(PosY < LinkedObjectEditor_ScrollBorderSize) { ScrollAccum.Y += (1.f - ((float)PosY/(float)LinkedObjectEditor_ScrollBorderSize)) * LinkedObjectEditor_ScrollBorderSpeed * DeltaTime; } else if(PosY > SizeY - LinkedObjectEditor_ScrollBorderSize) { ScrollAccum.Y -= ((float)(PosY - (SizeY - LinkedObjectEditor_ScrollBorderSize))/(float)LinkedObjectEditor_ScrollBorderSize) * LinkedObjectEditor_ScrollBorderSpeed * DeltaTime; } else { ScrollAccum.Y = 0.f; } // Apply integer part of ScrollAccum to origin, and save the rest. const int32 MoveX = FMath::Floor(ScrollAccum.X); Origin2D.X += MoveX; ScrollAccum.X -= MoveX; const int32 MoveY = FMath::Floor(ScrollAccum.Y); Origin2D.Y += MoveY; ScrollAccum.Y -= MoveY; // Update the box selection if necessary if (bBoxSelecting) { BoxEndX += MoveX; BoxEndY += MoveY; } // If view has changed, notify the app and redraw the viewport. if( FMath::Abs<int32>(MoveX) > 0 || FMath::Abs<int32>(MoveY) > 0 ) { EdInterface->ViewPosChanged(); Viewport->Invalidate(); } Result = FIntPoint(MoveX, MoveY); } return Result; } /** * Sets whether or not the viewport should be invalidated in Tick(). */ void FLinkedObjViewportClient::SetRedrawInTick(bool bInAlwaysDrawInTick) { bAlwaysDrawInTick = bInAlwaysDrawInTick; } void FLinkedObjViewportClient::Tick(float DeltaSeconds) { FEditorViewportClient::Tick(DeltaSeconds); // Auto-scroll display if moving/drawing etc. and near edge. bool bCtrlDown = Viewport->KeyState(EKeys::LeftControl) || Viewport->KeyState(EKeys::RightControl); if( bMouseDown ) { // If holding both buttons, we are zooming. if(Viewport->KeyState(EKeys::RightMouseButton) && Viewport->KeyState(EKeys::LeftMouseButton)) { } else if(bMakingLine || bBoxSelecting) { DoScrollBorder(DeltaSeconds); } else if(bSpecialDrag) { FIntPoint Delta = DoScrollBorder(DeltaSeconds); if(Delta.Size() > 0) { EdInterface->SpecialDrag( -Delta.X * (1.f/Zoom2D), -Delta.Y * (1.f/Zoom2D), 0, 0, SpecialIndex ); // TODO fix mouse position in this case. } } else if(bCtrlDown && EdInterface->HaveObjectsSelected()) { FIntPoint Delta = DoScrollBorder(DeltaSeconds); // In the case of dragging boxes around, we move them as well when dragging at the edge of the screen. EdInterface->MoveSelectedObjects( -Delta.X * (1.f/Zoom2D), -Delta.Y * (1.f/Zoom2D) ); DistanceDragged += ( FMath::Abs<int32>(Delta.X) + FMath::Abs<int32>(Delta.Y) ); if(!bTransactionBegun && DistanceDragged > 4) { EdInterface->BeginTransactionOnSelected(); bTransactionBegun = true; } } } // Pan to DesiredOrigin2D within DesiredPanTime seconds. if( DesiredPanTime > 0.f ) { Origin2D.X = FMath::Lerp( Origin2D.X, DesiredOrigin2D.X, FMath::Min(DeltaSeconds/DesiredPanTime,1.f) ); Origin2D.Y = FMath::Lerp( Origin2D.Y, DesiredOrigin2D.Y, FMath::Min(DeltaSeconds/DesiredPanTime,1.f) ); DesiredPanTime -= DeltaSeconds; Viewport->InvalidateDisplay(); } else if ( bAlwaysDrawInTick ) { Viewport->InvalidateDisplay(); } if (MouseOverObject && ToolTipDelayMS > 0 && (FPlatformTime::Seconds() - MouseOverTime) > ToolTipDelayMS * .001f) { // Redraw so that tooltips can be displayed Viewport->InvalidateDisplay(); } }
b031092d0c123551158f2d1b75f0cc48662d9294
9baddaf0c91617af0554ea80780dff4d8e126cdb
/CodeVein_0.1/Engine/Headers/Light_Manager.h
4bb0b8b11da59258258abb2f93461dae66b32bf4
[]
no_license
plmnb14/TeamProject_3D_CodeVein
d0742b799f639f7d78db51aaba198195f4cc5c76
15317dac5d8a75d76abf267d31d7c3930505684a
refs/heads/master
2023-05-07T08:21:02.579479
2020-04-02T06:57:57
2020-04-02T06:57:57
null
0
0
null
null
null
null
UTF-8
C++
false
false
492
h
Light_Manager.h
#pragma once #include "Light.h" BEGIN(Engine) class CLight_Manager final : public CBase { DECLARE_SINGLETON(CLight_Manager) private: explicit CLight_Manager(); virtual ~CLight_Manager() = default; public: const D3DLIGHT9* Get_LightDesc(_uint iIndex); public: HRESULT Add_Light(LPDIRECT3DDEVICE9 pGraphic_Device, D3DLIGHT9 LightDesc); HRESULT Render_Light(CShader* pShader); public: list<CLight*> m_LightList; typedef list<CLight*> LIGHTLIST; public: virtual void Free(); }; END
896291afd0f769814431089d627a8614419d02fa
f494463d726437f946887b41bdc61209a1115646
/logindialogue.h
503aa100689720da5c0407ae3d060a5ea40adde5
[]
no_license
joe564338/ChatSec
a17eed92c40de881479dae4f2e7c154e11de1e92
611415c4230173d963c331daf8871e822a21c372
refs/heads/master
2021-01-02T09:14:09.734548
2015-12-11T19:00:19
2015-12-11T19:00:19
42,022,226
0
0
null
null
null
null
UTF-8
C++
false
false
614
h
logindialogue.h
#ifndef LOGINDIALOGUE_H #define LOGINDIALOGUE_H #include <QDialog> //class to verify the user does want to relogin namespace Ui { /** Window for confirming decision to re-login if the user is already connected*/ class loginDialogue; } class loginDialogue : public QDialog { Q_OBJECT public: explicit loginDialogue(QWidget *parent = 0);//constructor ~loginDialogue();//destructor private slots: void on_mYesButton_clicked();//yes button listener void on_mNoButton_clicked();//no button listener private: Ui::loginDialogue *ui;//ui for the dialogue window }; #endif // LOGINDIALOGUE_H
085a809b4dac572e51623ee01ccb64751f91d111
96087808a05a1a6beba14207b813ac7a152ef28a
/AlgorithmQuestions/AtCoder/abc178/d.cpp
0aaa99063fad7ffc2cf8b0bcd005aa044af86112
[]
no_license
phonism/notes
d76dd50d1e5b9463c2b65eafca7a596bd97e523b
97e72472657dfbabdf858fe812308790c0214a0b
refs/heads/master
2022-09-10T04:23:39.394736
2022-08-17T12:28:30
2022-08-17T12:28:30
24,148,792
12
1
null
null
null
null
UTF-8
C++
false
false
392
cpp
d.cpp
#include <bits/stdc++.h> using namespace std; const int N = 2222; const int MOD = 1e9 + 7; long long dp[N]; int main() { int s; cin >> s; for (int i = 3; i < N; ++i) { dp[i] = 1; } for (int i = 6; i <= s; ++i) { for (int j = 3; j <= i - 3; ++j) { dp[i] += dp[i - j]; dp[i] %= MOD; } } cout << dp[s] << endl; }
a828099d87a95138cb3b28773afd5b00bcd2753a
a52f02e202261afdaa53f266f1dfddb0d160be66
/2011.cpp
561a61ddc06b2a570ec6e66fd1e35f6f3f9e5aec
[]
no_license
tamtam484/procon_submissions
4e9d2b135a24e42d8ed4cbf349efae6ff7a075ee
28d91d2cdf1cce9c4276f199e2549d9574409a04
refs/heads/master
2021-01-20T14:09:03.208662
2017-08-12T16:43:23
2017-08-12T16:43:23
90,567,310
0
0
null
null
null
null
UTF-8
C++
false
false
2,705
cpp
2011.cpp
//http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=2011 #define _USE_MATH_DEFINES #include <sstream> //string stream its useful! #include<string> #include<iostream> #include<utility> //pair #include <vector> // vector #include <algorithm> // swap,sort,binary_search #include <functional> // std::greater #include <map> //map #include<set> //set #include<queue> //queue #include<list> //list #include<cmath> #include<numeric> #include<cassert> #include <iomanip> //cout<<setprecision #include <regex> typedef long long ll; #define FOR(i,a,b) for (int i=(a);i<(b);i++) #define REP(i,n) for (int i=0;i<(n);i++) #define RREP(i,n) for (int i=(n)-1;i>=0;i--) ll W = 1000000007; using namespace std; void omajinai() { cin.tie(0); ios::sync_with_stdio(false); cout<<setprecision(15); //freopen("txt.csv","r",stdin); } class Main{ public: int n; vector<int> uf; vector<int> sum; vector<ll> schedule; Main(){ cin>>n; if(n == 0) exit(0); schedule = vector<ll>(n,0); for(int i = 0; i<n; i++){ int fi; cin>>fi; for(int j = 0 ; j<fi ; j++){ int x; cin>>x; //????????????????????±?????\?????? schedule[i] += 1<<x; } } uf = vector<int>(n); sum = vector<int>(n); } void uf_init(){ for(int i = 0; i<n;i++) uf[i] = i; for(int i = 0;i<n;i++) sum[i] = 1; } int find(int i){ if(uf[i]!=i) uf[i] = find(uf[i]); return uf[i]; } void unite(int i , int j){ int s = find(i), t = find(j); if (s == t) return; uf[max(s,t)] = min(s,t); sum[min(s,t)] += sum[max(s,t)]; } void run(){ vector<int> ans(n); for(int center = 0;center<n;center++){ ans[center] = 31; for(int i = 30; i>0;i--){ uf_init(); for(int j = i;j>0;j--){ bool canunite = false; for(int k = 0; k<n;k++){ canunite |= schedule[k] & 1<<j && find(k) == find(center); } if(canunite){ for(int k = 0; k<n;k++){ if(schedule[k] & 1<<j) unite(center,k); } } } if(sum[find(center)]== n) ans[center] = i; else break; } } int answer = *min_element(ans.begin(),ans.end()); if(answer == 31) answer = -1; cout<<answer<<endl; } }; int main(){ omajinai(); while(true) Main().run(); }
49fe253edb57a047b69347d06c4e4394eb05f0c3
09eaf2b22ad39d284eea42bad4756a39b34da8a2
/ojs/icpc/4794/4794.cpp
8f2da56f75889deb9f033fbd3b2c07df62368368
[]
no_license
victorsenam/treinos
186b70c44b7e06c7c07a86cb6849636210c9fc61
72a920ce803a738e25b6fc87efa32b20415de5f5
refs/heads/master
2021-01-24T05:58:48.713217
2018-10-14T13:51:29
2018-10-14T13:51:29
41,270,007
2
0
null
null
null
null
UTF-8
C++
false
false
2,158
cpp
4794.cpp
#include <bits/stdc++.h> using namespace std; typedef unsigned long long int ull; typedef long long int ll; typedef unsigned int ui; #ifndef ONLINE_JUDGE #define DEBUG(...) {fprintf(stderr, __VA_ARGS__);} #else #define DEBUG(...) {} #endif const int K = 15; const int N = (1<<K); const int M = 107; bool memo[N][M]; int visi[N][M], turn; int n, x, y; int v[K]; int arr[N]; vector<ui> siz[K]; bool dp (ui mask, int w); bool dp (ui mask, int w) { if (__builtin_popcount(mask) == 1) return 1; if (w <= 0) return 0; //printf("%s\n", (bitset<15>(mask).to_string().c_str())); bool & me = memo[mask][w]; if (visi[mask][w] == turn) return me; visi[mask][w] = turn; me = 0; int sz = 0; int a = 0; for (int i = 0; i < n; i++) { if ((1<<i)&mask) { a += v[i]; sz++; } } if (a%w) return me; int h = a/w; for (int k = 1; k <= (sz/2); k++) { for (int kk = 0; kk < siz[k].size(); kk++) { ui tm = siz[k][kk]; if ((tm|mask) != mask) continue; int ar = arr[tm]; if (ar%w == 0 && (a-ar)%w == 0) { me = ((dp(tm, w) || dp(tm, ar/w)) && (dp(mask^tm, w) || dp(mask^tm, (a-ar)/w))); if (me) return me; } } } return me; } int main () { int x, y, a; for (ui i = 1; i < N; i++) siz[__builtin_popcount(i)].push_back(i); while (scanf("%d", &n) != EOF && n) { ++turn; a = 0; scanf("%d %d", &x, &y); for (int i = 0; i < n; i++) { scanf("%d ", v+i); a += v[i]; } sort(v, v+n); printf("Case %d: ", turn); if (a != x*y) printf("No\n"); else { for (ui i = 1; i < (1u<<n); i++) { arr[i] = 0; for (int j = 0; j < n; j++) if ((1u<<j)&i) arr[i] += v[j]; } if (!dp((1u<<n) - 1, x) && !dp((1u<<n) - 1, y)) printf("No\n"); else printf("Yes\n"); } } }
934bfdc16d2a069cfd878317375c9c9690f9e69e
88b299df27d2644c07546a63ed93803a76f677af
/main.cxx
af65e25ec283e393b0a5ff403c40ae39c7b2ea4b
[]
no_license
aymanrs/pascal-trianle
3a19f69d1a56cd6d60ddc38c9903a67c546fb561
e0214b2eeb2ca9b77167a22f686eb3c433671985
refs/heads/master
2022-04-11T03:43:11.702481
2020-03-26T12:47:50
2020-03-26T12:47:50
250,254,340
1
0
null
null
null
null
UTF-8
C++
false
false
472
cxx
main.cxx
#include <iostream> #include <vector> int main(){ const int seed = 1; std::vector<std::vector<unsigned long long>> triangle = {{0, 0, seed, 0, 0}}; std::cout << seed << '\n'; for(int n = 1;n < 11;n++){ triangle.push_back(std::vector<unsigned long long>(n * 2 + 5, 0)); for(int k = 0;k < n*2+1;k++){ triangle[n][k+2] = triangle[n-1][k] + triangle[n-1][k+1] + triangle[n-1][k+2]; std::cout << triangle[n][k+2] << ' '; } std::cout << '\n'; } return 0; }
be68794d4f14d91a9fc42ab6b988c0c90b672058
59f69f50fdcc7ce50650394643ea4fa408e63a14
/proj/a2_particle_physics/ParticleFluid.h
ecef33787105dc7a1cd874d4a6819bad5837bab7
[]
no_license
yanghaoxiang7/Yang-Haoxiang-Third-Research-Turn
b318ef0d394e99520e5017ddc1ba9ff73d4f283c
dbf6a964560738be0ba1198789e76b1eeb58e2e9
refs/heads/master
2022-12-27T05:36:25.829332
2020-10-17T01:01:51
2020-10-17T01:01:51
269,100,528
2
1
null
null
null
null
UTF-8
C++
false
false
8,384
h
ParticleFluid.h
//##################################################################### // Particle Fluid (SPH) // Dartmouth COSC 89.18/189.02: Computational Methods for Physical Systems, Assignment starter code // Contact: Bo Zhu (bo.zhu@dartmouth.edu) //##################################################################### #ifndef __ParticleFluid_h__ #define __ParticleFluid_h__ #include "Common.h" #include "Particles.h" #include "ImplicitGeometry.h" ////////////////////////////////////////////////////////////////////////// ////Kernel function template<int d> class Kernel {using VectorD=Vector<real,d>; public: ////precomputed coefs; real h; real coef_Wspiky; real coef_dWspiky; real coef_Wvis; real coef_d2Wvis; real pi=3.1415927; void Precompute_Coefs(real _h) { h=_h; coef_Wspiky=15.0/(pi*pow(h,6)); coef_dWspiky=-45.0/(pi*pow(h,6)); coef_Wvis=2*pi*pow(h,3); coef_d2Wvis=45.0/(pi*pow(h,6)); } ////Kernel Spiky real Wspiky(const VectorD& xji) { real r=xji.norm(); if(r>=0&&r<=h){return 15.0/(pi*pow(h,6))*pow(h-r,3);} else{return 0;} } VectorD gradientWspiky(const VectorD& v){ real r=v.norm(); if(r<= h&&r>0){return -45.0/(pi*pow(h,6))*pow(h-r,2)*v/r;} else{return VectorD::Zero();} } ////Kernel viscosity real Wvis(const VectorD& xji){ real r=xji.norm(); if(r>=0&&r<=h){return 15.0/(2*pi*pow(h,3))*((-pow(r,3)/(2*pow(h,3))+r*r/(h*h)+h/(2*r)-1));} else{return 0;} } real laplacianWvis(const VectorD& v){ real r=v.norm(); if(r<=h&&r>0){return 45.0/(pi*pow(h,6))*(h-r);} else{return 0;} } }; ////////////////////////////////////////////////////////////////////////// ////Spatial hashing template<int d> class SpatialHashing {using VectorD=Vector<real,d>;using VectorDi=Vector<int,d>; public: real dx=1.; ////grid cell size Hashtable<VectorDi,Array<int> > voxels; void Update_Voxels(const Array<VectorD>& points) {Clear_Voxels();for(int i=0;i<(int)points.size();i++)Add_Point(i,points[i]);} void Clear_Voxels(){voxels.clear();} bool Add_Point(const int point_idx,const VectorD& point_pos) { VectorDi cell=Cell_Coord(point_pos); auto iter=voxels.find(cell); if(iter==voxels.end())iter=voxels.insert(std::make_pair(cell,Array<int>())).first; Array<int>& bucket=iter->second; bucket.push_back(point_idx); return true; } ////////////////////////////////////////////////////////////////////////// ////YOUR IMPLEMENTATION (P2 TASK): find all the neighboring particles within the "kernel_radius" around "pos" and record their indices in "nbs", the position of the particles are given in "points" ////You need to traverse all the 3^d neighboring cells in the background grid around the cell occupied by "pos", and then check the distance between each particle in each neighboring cell and the given "pos" ////Use the helper function Cell_Coord to get the cell coordinates for a given "pos" ////Use the helper function Nb_R to get the cell coordinates of the ith neighboring cell around the cell "coord" bool Find_Nbs(const VectorD& pos,const Array<VectorD>& points,const real kernel_radius,/*returned result*/Array<int>& nbs) const { VectorDi cell = Cell_Coord(pos); for (int index = 0; index < 9; index++) { VectorDi nb = Nb_R( (Vector2i)cell, index); // 2d auto iter = voxels.find(nb); if (iter == voxels.end()) continue; Array<int> bucket = iter->second; for (int i = 0; i < bucket.size(); i++) { int id = bucket[i]; if ((pos - points[id]).norm() < kernel_radius) nbs.push_back(id); } } return nbs.size()>0; } protected: ////Helper functions VectorDi Cell_Coord(const VectorD& pos) const {VectorD coord_with_frac=(pos)/dx;return coord_with_frac.template cast<int>();} Vector2i Nb_R(const Vector2i& coord,const int index) const {assert(index>=0&&index<9);int i=index/3;int j=index%3;return coord+Vector2i(-1+i,-1+j);} Vector3i Nb_R(const Vector3i& coord,const int index) const {assert(index>=0&&index<27);int i=index/9;int m=index%9;int j=m/3;int k=m%3;return coord+Vector3i(-1+i,-1+j,-1+k);} }; ////////////////////////////////////////////////////////////////////////// ////Particle fluid simulator template<int d> class ParticleFluid {using VectorD=Vector<real,d>; public: Particles<d> particles; Array<Array<int> > neighbors; SpatialHashing<d> spatial_hashing; Kernel<d> kernel; real kernel_radius=(real).8; ////kernel radius real pressure_density_coef=(real)1e1; ////pressure-density-relation coefficient, used in Update_Pressure() real density_0=(real)10.; ////rest density, used in Update_Pressure() real viscosity_coef=(real)1e1; ////viscosity coefficient, used in Update_Viscosity_Force() real kd=(real)1e2; ////stiffness for environmental collision response VectorD g=VectorD::Unit(1)*(real)-1.; ////gravity ////Environment objects Array<ImplicitGeometry<d>* > env_objects; virtual void Initialize() { kernel.Precompute_Coefs(kernel_radius); } virtual void Update_Neighbors() { spatial_hashing.Clear_Voxels(); spatial_hashing.Update_Voxels(particles.XRef()); neighbors.resize(particles.Size()); for(int i=0;i<particles.Size();i++){ Array<int> nbs; spatial_hashing.Find_Nbs(particles.X(i),particles.XRef(),kernel_radius,nbs); neighbors[i]=nbs;} } virtual void Advance(const real dt) { for(int i=0;i<particles.Size();i++){ particles.F(i)=VectorD::Zero();} Update_Neighbors(); Update_Density(); Update_Pressure(); Update_Pressure_Force(); Update_Viscosity_Force(); Update_Body_Force(); Update_Boundary_Collision_Force(); for(int i=0;i<particles.Size();i++){ particles.V(i)+=particles.F(i)/particles.D(i)*dt; particles.X(i)+=particles.V(i)*dt;} } ////////////////////////////////////////////////////////////////////////// ////YOUR IMPLEMENTATION (P2 TASK): update the density (particles.D(i)) of each particle based on the kernel function (Wspiky) void Update_Density() { for (int i = 0; i < particles.Size(); i++) { particles.D(i) = 0; for (int j2 = 0; j2 < neighbors[i].size(); j2++) { int j = neighbors[i][j2]; real wij = kernel.Wspiky(particles.X(i) - particles.X(j)); particles.D(i) += particles.M(j) * wij; } } } ////////////////////////////////////////////////////////////////////////// ////YOUR IMPLEMENTATION (P2 TASK): update the pressure (particles.P(i)) of each particle based on its current density (particles.D(i)) and the rest density (density_0) void Update_Pressure() { for (int i = 0; i < particles.Size(); i++) particles.P(i) = pressure_density_coef * (particles.D(i) - density_0); } ////////////////////////////////////////////////////////////////////////// ////YOUR IMPLEMENTATION (P2 TASK): compute the pressure force for each particle based on its current pressure (particles.P(i)) and the kernel function gradient (gradientWspiky), and then add the force to particles.F(i) void Update_Pressure_Force() { for (int i = 0; i < particles.Size(); i++) for (int j2 = 0; j2 < neighbors[i].size(); j2++) { int j = neighbors[i][j2]; VectorD dwij = kernel.gradientWspiky(particles.X(i) - particles.X(j)); particles.F(i) -= 0.5 * (particles.P(i) + particles.P(j)) * particles.M(i) / particles.D(i) * dwij; } } ////////////////////////////////////////////////////////////////////////// ////YOUR IMPLEMENTATION (P2 TASK): compute the viscosity force for each particle based on its current velocity difference (particles.V(j)-particles.V(i)) and the kernel function Laplacian (laplacianWvis), and then add the force to particles.F(i) void Update_Viscosity_Force() { for (int i = 0; i < particles.Size(); i++) for (int j2 = 0; j2 < neighbors[i].size(); j2++) { int j = neighbors[i][j2]; real d2wij = kernel.laplacianWvis(particles.X(i) - particles.X(j)); particles.F(i) += viscosity_coef * (particles.V(j) - particles.V(i)) * particles.M(i) / particles.D(i) * d2wij; } } void Update_Body_Force() { for(int i=0;i<particles.Size();i++){ particles.F(i)+=particles.D(i)*g;} } void Update_Boundary_Collision_Force() { for(int i=0;i<particles.Size();i++){ for(int j=0;j<env_objects.size();j++){ real phi=env_objects[j]->Phi(particles.X(i)); if(phi<particles.R(i)){ VectorD normal=env_objects[j]->Normal(particles.X(i)); particles.F(i)+=normal*kd*(particles.R(i)-phi)*particles.D(i);}}} // ?? } }; #endif
19f73cc7504b11ea51fc5d968b06b989857ed2c1
7bc74c12d85d5298f437d043fdc48943ccfdeda7
/001_Project/102_interfaceTMP/adas/src-gen/provides/v0/com/harman/adas/PASService.hpp
58c4943a21c33afea43ebcc201b98bf20ee0006f
[]
no_license
BobDeng1974/cameraframework-github
364dd6e9c3d09a06384bb4772a24ed38b49cbc30
86efc7356d94f4957998e6e0ae718bd9ed4a4ba0
refs/heads/master
2020-08-29T16:14:02.898866
2017-12-15T14:55:25
2017-12-15T14:55:37
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,117
hpp
PASService.hpp
/* * This file was generated by the CommonAPI Generators. * Used org.genivi.commonapi.core 3.1.5.201702211714. * Used org.franca.core 0.9.1.201412191134. * * generated by DCIF CodeGen Version: R2_v2.3.0 * generated on: Tue Aug 01 13:37:50 CST 2017 */ #ifndef V0_COM_HARMAN_ADAS_PAS_SERVICE_HPP_ #define V0_COM_HARMAN_ADAS_PAS_SERVICE_HPP_ #if !defined (COMMONAPI_INTERNAL_COMPILATION) #define COMMONAPI_INTERNAL_COMPILATION #endif #include <CommonAPI/Types.hpp> #undef COMMONAPI_INTERNAL_COMPILATION namespace v0 { namespace com { namespace harman { namespace adas { class PASService { public: virtual ~PASService() { } static inline const char* getInterface(); static inline CommonAPI::Version getInterfaceVersion(); }; const char* PASService::getInterface() { return ("com.harman.adas.PASService"); } CommonAPI::Version PASService::getInterfaceVersion() { return CommonAPI::Version(0, 1); } } // namespace adas } // namespace harman } // namespace com } // namespace v0 namespace CommonAPI { } // Compatibility namespace v0_1 = v0; #endif // V0_COM_HARMAN_ADAS_PAS_SERVICE_HPP_
690320b81e5311362732bd43862cad3f5f31a5c2
396fb5e5e39e4490347cfa6927e60c601d86b735
/src/smooth.cpp
6d5fa8fc41132656149a737910154a654345fe67
[]
no_license
Xiuying/ggstat
1d58cb6ed8019abbf78df395d1ef2e6dbad8abc9
662b5d14a9e7ec2772d0759073d4f5477f2ff781
refs/heads/master
2021-05-31T06:46:08.859611
2016-05-09T22:29:17
2016-05-09T22:29:17
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,492
cpp
smooth.cpp
#include <Rcpp.h> #include "smoothers.h" using namespace Rcpp; inline double tricube(double x) { if (NumericVector::is_na(x)) return 0; x = fabs(x); if (x > 1) return 0; double y = 1 - x * x * x; return y * y * y; } bool both_na(double x, double y) { return NumericVector::is_na(x) && NumericVector::is_na(y); } template <class Smoother> NumericVector smooth(const NumericVector& x_in, const NumericVector& z_in, const NumericVector& w_in, const NumericVector& x_out, const Smoother& smoother, const double h) { if (h <= 0) stop("h <= 0"); if (x_in.size() != z_in.size()) stop("x and z must be same length"); if (x_in.size() != w_in.size()) stop("x and w must be same length"); int n_in = x_in.size(), n_out = x_out.size(); NumericVector z_out(n_out); for(int j = 0; j < n_out; ++j) { std::vector<double> x1, z1, w1; // Could make this fast if we assume x_out is ordered: use binary // search to find first and last locations for (int i = 0; i < n_in; ++i) { double in = x_in[i], out = x_out[j]; double dist = both_na(in, out) ? 0 : in - out; double w = tricube(dist / h) * w_in[i]; if (w == 0) continue; x1.push_back(dist); z1.push_back(z_in[i]); w1.push_back(w); } z_out[j] = smoother.compute(x1, z1, w1); } return z_out; } // [[Rcpp::export]] NumericVector smooth_linear(const NumericVector& x_in, const NumericVector& z_in, const NumericVector& w_in, const NumericVector& x_out, const double h) { return smooth(x_in, z_in, w_in, x_out, LinearSmoother(), h); } // [[Rcpp::export]] NumericVector smooth_robust(const NumericVector& x_in, const NumericVector& z_in, const NumericVector& w_in, const NumericVector& x_out, const double h, int iterations = 3) { return smooth(x_in, z_in, w_in, x_out, RobustSmoother(iterations), h); } // [[Rcpp::export]] NumericVector smooth_mean(const NumericVector& x_in, const NumericVector& z_in, const NumericVector& w_in, const NumericVector& x_out, const double h) { return smooth(x_in, z_in, w_in, x_out, MeanSmoother(), h); }
5e006a5cd25d08320a6a7e15444420ae1f689b24
a8477806ec9796279f7092b78e9da2bf8e0c087f
/versions/PlayDoorbell__6_neopixels/PlayDoorbell__6_neopixels.ino
74d7d154693b722a8c1823e5e3de12cdc9117c55
[ "MIT" ]
permissive
jkeefe/play-doorbell
a2c96fd27c595953bd5523d3c9d3fcec2d325f58
f3e2e43cc6a2ec27515490ed53b969203e8f48c5
refs/heads/master
2020-04-05T18:21:36.402836
2019-01-07T03:14:59
2019-01-07T03:14:59
157,098,552
1
1
null
null
null
null
UTF-8
C++
false
false
12,078
ino
PlayDoorbell__6_neopixels.ino
// v5 add button logic #define THIS_NODE 1 // <<<< change this for each node #define N_NODES 3 // total nodes // #include <EEPROM.h> // not available on the Feather M0 #include <RHRouter.h> #include <RHMesh.h> #include <RH_RF95.h> #include <ArduinoJson.h> // from https://arduinojson.org/v5/example/parser/ #include <Adafruit_NeoPixel_ZeroDMA.h> // ^^^ 2 other libs also needed. See: https://learn.adafruit.com/dma-driven-neopixels/overview // set up neopixels for M0 #define STRIP_PIN 5 #define TOTAL_PIXELS 16 Adafruit_NeoPixel_ZeroDMA strip(TOTAL_PIXELS, STRIP_PIN, NEO_GRB); // pushbutton details #define BUTTON 18 // aka A4 ... Seems most/all MO pins can be used as external interrupts // tho some are shared. see pinout .https://learn.adafruit.com/assets/46254 #define BUTTON_LIGHT 17 // aka A3 #define DEBUG_MODE 1 // 1 true, 0 false #define RH_HAVE_SERIAL #define LED 9 /* for feather32u4 #define RFM95_CS 8 #define RFM95_RST 4 #define RFM95_INT 7 */ // for feather m0 #define RFM95_CS 8 #define RFM95_RST 4 #define RFM95_INT 3 /* for shield #define RFM95_CS 10 #define RFM95_RST 9 #define RFM95_INT 7 */ /* Feather 32u4 w/wing #define RFM95_RST 11 // "A" #define RFM95_CS 10 // "B" #define RFM95_INT 2 // "SDA" (only SDA/SCL/RX/TX have IRQ!) */ /* Feather m0 w/wing #define RFM95_RST 11 // "A" #define RFM95_CS 10 // "B" #define RFM95_INT 6 // "D" */ #if defined(ESP8266) /* for ESP w/featherwing */ #define RFM95_CS 2 // "E" #define RFM95_RST 16 // "D" #define RFM95_INT 15 // "B" #elif defined(ESP32) /* ESP32 feather w/wing */ #define RFM95_RST 27 // "A" #define RFM95_CS 33 // "B" #define RFM95_INT 12 // next to A #elif defined(NRF52) /* nRF52832 feather w/wing */ #define RFM95_RST 7 // "A" #define RFM95_CS 11 // "B" #define RFM95_INT 31 // "C" #elif defined(TEENSYDUINO) /* Teensy 3.x w/wing */ #define RFM95_RST 9 // "A" #define RFM95_CS 10 // "B" #define RFM95_INT 4 // "C" #endif // Change to 434.0 or other frequency, must match RX's freq! #define RF95_FREQ 907.2 // Singleton instance of the radio driver RH_RF95 rf95(RFM95_CS, RFM95_INT); // Class to manage message delivery and receipt, using the driver declared above RHMesh *manager; // ArduinoJson Settings: // see https://arduinojson.org/v5/assistant/ for settings here, esp constant at the end // currently assuming transmission content to look like this: // {"b":0,"t":[{"n":255,"r":0},{"n":2,"r":-27},{"n":127,"r":0}] } const size_t bufferSize = JSON_ARRAY_SIZE(N_NODES) + (N_NODES+1)*JSON_OBJECT_SIZE(2) + 40; DynamicJsonBuffer jsonBuffer(bufferSize); uint8_t nodeId; uint8_t routes[N_NODES]; // full routing table for mesh int16_t rssi[N_NODES]; // signal strength info // message buffer char buf[RH_MESH_MAX_MESSAGE_LEN]; boolean my_button_active = false; unsigned long my_button_millis = 0; unsigned long my_button_debounce = 50; // millis for debounce detection //// This doesn't seem to compile on the Feather M0: //int freeMem() { // extern int __heap_start, *__brkval; // int v; // return (int) &v - (__brkval == 0 ? (int) &__heap_start : (int) __brkval); //} /// THIS RUNS ONCE AT POWER-UP void setup() { pinMode(RFM95_RST, OUTPUT); digitalWrite(RFM95_RST, HIGH); // for the button detection / interrupt pinMode(BUTTON, INPUT_PULLUP); // douse the button light pinMode(BUTTON_LIGHT, OUTPUT); digitalWrite(BUTTON_LIGHT, LOW); randomSeed(analogRead(0)); pinMode(LED, OUTPUT); Serial.begin(115200); // this while statment stops the program until a serial monitor window is open // currently engaged only for node 1, which is my main node if (THIS_NODE == 1) { while (!Serial) { delay(1); } }; delay(100); // manual reset digitalWrite(RFM95_RST, LOW); delay(10); digitalWrite(RFM95_RST, HIGH); delay(10); while (!rf95.init()) { Serial.println("LoRa radio init failed"); while (1); } Serial.println("LoRa radio init OK!"); nodeId = THIS_NODE; /* // EEPROM not available on the Feather M0 // so for now I'm hard-coding THIS_NODE before each upload nodeId = EEPROM.read(0); if (nodeId > 10) { Serial.print(F("EEPROM nodeId invalid: ")); Serial.println(nodeId); nodeId = 1; } Serial.print(F("initializing node ")); */ manager = new RHMesh(rf95, nodeId); if (!manager->init()) { Serial.println(F("mesh init failed")); } else { Serial.println("done"); } // set the transmit power rf95.setTxPower(23, false); // set the frequency if (!rf95.setFrequency(RF95_FREQ)) { Serial.println("setFrequency failed"); while (1); } Serial.print("Set Freq to: "); Serial.println(RF95_FREQ); rf95.setCADTimeout(500); // Possible configurations: // Bw125Cr45Sf128 (the chip default) // Bw500Cr45Sf128 // Bw31_25Cr48Sf512 // Bw125Cr48Sf4096 // long range configuration requires for on-air time <-- will explore this later boolean longRange = false; if (longRange) { RH_RF95::ModemConfig modem_config = { 0x78, // Reg 0x1D: BW=125kHz, Coding=4/8, Header=explicit 0xC4, // Reg 0x1E: Spread=4096chips/symbol, CRC=enable 0x08 // Reg 0x26: LowDataRate=On, Agc=Off. 0x0C is LowDataRate=ON, ACG=ON }; rf95.setModemRegisters(&modem_config); if (!rf95.setModemConfig(RH_RF95::Bw125Cr48Sf4096)) { Serial.println(F("set config failed")); } } Serial.println("RF95 ready"); /// clear all the variables we're tracking for all nodes for(uint8_t n=1;n<=N_NODES;n++) { routes[n-1] = 0; rssi[n-1] = 0; } // Serial.print(F("mem = ")); // Serial.println(freeMem()); } const __FlashStringHelper* getErrorString(uint8_t error) { switch(error) { case 1: return F("invalid length"); break; case 2: return F("no route"); break; case 3: return F("timeout"); break; case 4: return F("no reply"); break; case 5: return F("unable to deliver"); break; } return F("unknown"); } void updateRoutingTable() { // update every node in the table for(uint8_t n=1;n<=N_NODES;n++) { RHRouter::RoutingTableEntry *route = manager->getRouteTo(n); if (n == nodeId) { routes[n-1] = 255; // self } else { routes[n-1] = route->next_hop; if (routes[n-1] == 0) { // if we have no route to the node, reset the received signal strength rssi[n-1] = 0; } } } } // Create a JSON string with the routing info to each node // note sprintf puts the string into a buffer // ... the one we passed to it // ... which is how we get it back out later. // see https://liudr.wordpress.com/2012/01/16/sprintf/ void getRouteInfoString(char *p, size_t len) { p[0] = '\0'; // clear buffer first // building json like this if DEBUG_MODE is 1: // {"b":0,"t":[{"n":255,"r":0},{"n":2,"r":-27},{"n":127,"r":0}] } // otherwise it's just // {"b":0} strcat(p, "{\"b\":"); // b: button state sprintf(p+strlen(p), "%d", my_button_active); if (DEBUG_MODE) { // add routing table data to json strcat(p, ",\"t\":["); // t: table for(uint8_t n=1;n<=N_NODES;n++) { strcat(p, "{\"n\":"); // n: node sprintf(p+strlen(p), "%d", routes[n-1]); strcat(p, ","); strcat(p, "\"r\":"); // r: signal strength sprintf(p+strlen(p), "%d", rssi[n-1]); strcat(p, "}"); if (n<N_NODES) { strcat(p, ","); } } strcat(p, "]"); } strcat(p, "}"); } void printNodeInfo(uint8_t node, char *s) { Serial.print(F("node: ")); Serial.print(F("{")); Serial.print(F("\"")); Serial.print(node); Serial.print(F("\"")); Serial.print(F(": ")); Serial.print(s); Serial.println(F("}")); } void parsePlayArray(uint8_t node, char *s) { // all code usage here pulled from https://arduinojson.org/v5/assistant/ // after I put in my sample json array JsonArray& nodearray = jsonBuffer.parseArray(s); for(uint8_t n=1;n<=N_NODES;n++) { // this parses the array JsonObject& item = nodearray[n-1]; int playval = item["p"]; Serial.print("Node "); Serial.print(node); Serial.print(" reports that play status of node "); Serial.print(n); Serial.print(" is: "); Serial.println(playval); } } void buttonPushed() { // this function activated by the interrupt // immediately detatch the interrupt until we're done here detachInterrupt(digitalPinToInterrupt(BUTTON)); // check if button has just been pushed (or got noise) if ( (millis() - my_button_millis) > my_button_debounce) { // toggle button state my_button_active = !my_button_active; // reset millis my_button_millis = millis(); // turn button LED on or off, depending on state if (my_button_active) { digitalWrite(BUTTON_LIGHT, HIGH); } else { digitalWrite(BUTTON_LIGHT, LOW); } } // reestablish interrupt attachInterrupt(digitalPinToInterrupt(BUTTON), buttonPushed, LOW); } // makes one row of a rainbow, start to finish on the strip length void rainbowRow(uint8_t wait) { uint16_t pixel, gap, i; // cycle three times for (i=0; i < 3; i++) { gap = 256 / TOTAL_PIXELS; for (pixel = 0; pixel < TOTAL_PIXELS; pixel++) { strip.setPixelColor(pixel, Wheel(pixel * gap)); strip.show(); delay(wait); } // turn them off for (pixel = 0; pixel < TOTAL_PIXELS; pixel++) { strip.setPixelColor(pixel, strip.Color(0, 0, 0)); strip.show(); delay(wait); } } } // Input a value 0 to 255 to get a color value. // The colours are a transition r - g - b - back to r. uint32_t Wheel(byte WheelPos) { if(WheelPos < 85) { return strip.Color(WheelPos * 3, 255 - WheelPos * 3, 0); } else if(WheelPos < 170) { WheelPos -= 85; return strip.Color(255 - WheelPos * 3, 0, WheelPos * 3); } else { WheelPos -= 170; return strip.Color(0, WheelPos * 3, 255 - WheelPos * 3); } } void loop() { // establish interrupt attachInterrupt(digitalPinToInterrupt(BUTTON), buttonPushed, LOW); for(uint8_t n=1;n<=N_NODES;n++) { // SEND to all of the notes (tho not ourself) if (n == nodeId) continue; // self updateRoutingTable(); getRouteInfoString(buf, RH_MESH_MAX_MESSAGE_LEN); Serial.print(F("->")); Serial.print(n); Serial.print(F(" :")); Serial.print(buf); // send an acknowledged message to the target node uint8_t error = manager->sendtoWait((uint8_t *)buf, strlen(buf), n); if (error != RH_ROUTER_ERROR_NONE) { Serial.println(); Serial.print(F(" ! ")); Serial.println(getErrorString(error)); } else { Serial.println(F(" OK")); // we received an acknowledgement from the next hop for the node we tried to send to. RHRouter::RoutingTableEntry *route = manager->getRouteTo(n); if (route->next_hop != 0) { rssi[route->next_hop-1] = rf95.lastRssi(); } } // listen for incoming messages. Wait a random amount of time before we transmit // again to the next node unsigned long nextTransmit = millis() + random(3000, 5000); while (nextTransmit > millis()) { int waitTime = nextTransmit - millis(); uint8_t len = sizeof(buf); uint8_t from; if (manager->recvfromAckTimeout((uint8_t *)buf, &len, waitTime, &from)) { buf[len] = '\0'; // null terminate string Serial.print(from); Serial.print(F("->")); Serial.print(F(" :")); Serial.println(buf); // parsePlayArray(from, buf); if (nodeId == 1) { printNodeInfo(from, buf); // debugging } // we received data from node 'from', but it may have actually come from an intermediate node RHRouter::RoutingTableEntry *route = manager->getRouteTo(from); if (route->next_hop != 0) { rssi[route->next_hop-1] = rf95.lastRssi(); } } } } }
ec6ea04f1551e90e1476cc4b074cd3fa1a35c929
4d52c3db6e28506370d66fc42580292f31cc713b
/Problem - 051 to 100/Problem - 093.cpp
985ed32a36808d465610c0d50c0455a1b649ef52
[]
no_license
Futsy/Euler
165b1a4bf18fae559aeb4e42986939a56b31ab2f
592635d0f2a0429e41af9b1675f5942249c490f8
refs/heads/master
2020-12-24T15:05:26.751714
2018-10-31T14:27:22
2018-10-31T14:27:22
15,485,029
0
0
null
null
null
null
UTF-8
C++
false
false
2,282
cpp
Problem - 093.cpp
/** * Run time solution * 0.0382165 seconds */ #include <algorithm> #include <cmath> #include <iterator> #include <iostream> #include <set> double op(double number1, double number2, int operation) { if (operation == 0) { return number1 + number2; } else if (operation == 1) { return number1 - number2; } else if (operation == 2) { return number1 * number2; } return number1 / number2; } int getDigits(const int digit1, const int digit2, const int digit3, const int digit4) { std::set<int> numbers; double result[4]; int digits[] = {digit1,digit2,digit3,digit4}; do { for (int op1 = 0; op1 < 4; op1++){ for (int op2 = 0; op2 < 4; op2++){ for (int op3 = 0; op3 < 4; op3++){ result[0] = op(op(op(digits[0], digits[1], op1), digits[2], op2), digits[3], op3); result[1] = op(op(digits[0], digits[1], op1), op(digits[2], digits[3], op2), op3); result[2] = op(op(digits[0], op(digits[1], digits[2], op1), op2), digits[3], op3); result[3] = op(digits[3], op(digits[0], op(digits[1], digits[2], op1), op2), op3); for (const auto& e : result) { if (e > 0 && fabs(floor(e) - e) < 0.0001) { numbers.insert(e); } } } } } } while (std::next_permutation(digits, digits + 4)); int i = 1; auto it = numbers.begin(); for (; it != numbers.end() && *it == i; ++it, i++); return i - 1; } int main() { int solution = 0; int currentMax = 0; for (int i = 1; i < 10; i++){ for (int j = i + 1; j < 10; j++){ for (int k = j + 1; k < 10; k++){ for (int l = k + 1; l < 10; l++){ const int current = getDigits(i, j, k, l); if (current > currentMax){ currentMax = current; solution = 1000 * i + 100 * j + 10 * k + l; } } } } } std::cout << "Solution: " << solution << std::endl; }
1b4b4b5c52f7d5b115d71716980d5f015c3c95e7
bc0e6b77ee649ef611ade21bc1b24fc321653e4d
/PFCalEE/include/SamplingSection.hh
935c1a8f39411daf42c17e1149b962d5c5ec3234
[]
no_license
pfs/PFCal
08dcfb7db908a688c1a0f390965752537022df5f
2922434ce888d40acdc832d13313c1e6a8835278
refs/heads/master
2023-03-13T17:39:57.706091
2023-03-01T12:47:14
2023-03-01T12:47:14
11,907,151
0
17
null
2021-03-15T16:42:25
2013-08-05T19:44:57
C++
UTF-8
C++
false
false
6,738
hh
SamplingSection.hh
#ifndef _samplingsection_hh_ #define _samplingsection_hh_ #include "G4VUserDetectorConstruction.hh" #include "globals.hh" #include "G4ThreeVector.hh" #include "G4Colour.hh" #include <iomanip> #include <vector> #include "G4SiHit.hh" class SamplingSection { public: //CTOR SamplingSection(const std::vector<G4double> & aThicknessVec, const std::vector<std::string> & aMaterialVec) { if (aMaterialVec.size() != aThicknessVec.size()) { G4cout << " -- ERROR in sampling section definition. Expect input vectors with same size containing thicknesses (size=" << aThicknessVec.size() << ") and material names (size=" << aMaterialVec.size() << "). Exiting..." << G4endl; exit(1); } Total_thick = 0; n_sens_elements=0; n_elements=0; n_sectors=0; ele_thick.clear(); ele_name.clear(); ele_X0.clear(); ele_L0.clear(); ele_vol.clear(); hasScintillator = false; for (unsigned ie(0); ie<aThicknessVec.size(); ++ie){ //consider only material with some non-0 width... if (aThicknessVec[ie]>0){ ele_thick.push_back(aThicknessVec[ie]); ele_name.push_back(aMaterialVec[ie]); if (aMaterialVec[ie]== "Scintillator") hasScintillator = true; ele_X0.push_back(0); ele_dEdx.push_back(0); ele_L0.push_back(0); ele_vol.push_back(0); Total_thick+=aThicknessVec[ie]; ++n_elements; //the following method check the total size... //so incrementing first. if (isSensitiveElement(n_elements-1)) { G4SiHitVec lVec; sens_HitVec.push_back(lVec); ++n_sens_elements; } } } sens_HitVec_size_max = 0; sc_HitVec_size_max = 0; resetCounters(); std::cout << " -- End of sampling section initialisation. Input " << aThicknessVec.size() << " elements, constructing " << n_elements << " elements with " << n_sens_elements << " sensitive elements." << std::endl; }; //DTOR ~SamplingSection() { }; inline void setNumberOfSectors(const unsigned nSec){ n_sectors = nSec; ele_vol.clear(); for (unsigned ie(0); ie<n_elements*n_sectors; ++ie){ ele_vol.push_back(0); } }; // void add(G4double den, G4double dl, G4double globalTime,G4int pdgId, G4VPhysicalVolume* vol, const G4ThreeVector & position, G4int trackID, G4int parentID, G4int layerId); inline bool isSensitiveElement(const unsigned & aEle){ if (aEle < n_elements && (ele_name[aEle] == "Si" || ele_name[aEle] == "Scintillator") ) return true; return false; }; inline unsigned getSensitiveLayerIndex(std::string astr){ if (astr.find("_")== astr.npos) return 0; size_t pos = astr.find("phys"); //std::cout << astr << " " << pos << std::endl; if (pos != astr.npos && pos>1) { unsigned idx = 0;//atoi(astr[pos-1]); std::istringstream(astr.substr(pos-1,1))>>idx; return idx; } return 0; }; inline G4Colour g4Colour(const unsigned & aEle){ if (isSensitiveElement(aEle)) return G4Colour::Red(); else if (ele_name[aEle] == "Cu") return G4Colour::Black(); else if (ele_name[aEle] == "CuExtra") return G4Colour::Magenta(); else if (isAbsorberElement(aEle)) return G4Colour::Gray(); else if (ele_name[aEle] == "PCB") return G4Colour::Blue(); else if (ele_name[aEle] == "Air") return G4Colour::Cyan(); return G4Colour::Yellow(); }; inline bool isAbsorberElement(const unsigned & aEle){ if (aEle < n_elements && ( ele_name[aEle] == "Pb" || ele_name[aEle] == "Cu" || ele_name[aEle] == "CuExtra" || ele_name[aEle] == "W" || ele_name[aEle] == "Brass" || ele_name[aEle] == "Fe" || ele_name[aEle] == "Steel" || ele_name[aEle] == "SSteel" || ele_name[aEle] == "Al" || ele_name[aEle] == "WCu" || ele_name[aEle] == "NeutMod" ) ) return true; return false; }; //reset inline void resetCounters() { ele_den.resize(n_elements,0); ele_dl.resize(n_elements,0); for (unsigned idx(0); idx<n_elements; ++idx){ ele_den[idx] = 0; ele_dl[idx] = 0; } sens_time.resize(n_sens_elements,0); sens_gFlux.resize(n_sens_elements,0); sens_eFlux.resize(n_sens_elements,0); sens_muFlux.resize(n_sens_elements,0); sens_neutronFlux.resize(n_sens_elements,0); sens_hadFlux.resize(n_sens_elements,0); //reserve some space based on first event.... for (unsigned idx(0); idx<n_sens_elements; ++idx){ sens_time[idx]=0; sens_gFlux[idx]=0; sens_eFlux[idx]=0; sens_muFlux[idx]=0; sens_neutronFlux[idx]=0; sens_hadFlux[idx]=0; if (sens_HitVec[idx].size() > sens_HitVec_size_max) { sens_HitVec_size_max = 2*sens_HitVec[idx].size(); G4cout << "-- SamplingSection::resetCounters(), space reserved for HitVec vector increased to " << sens_HitVec_size_max << G4endl; } sens_HitVec[idx].clear(); sens_HitVec[idx].reserve(sens_HitVec_size_max); } if (supportcone_HitVec.size() > sc_HitVec_size_max) { sc_HitVec_size_max = 2*supportcone_HitVec.size(); G4cout << "-- SamplingSection::resetCounters(), space reserved for AluHitVec vector increased to " << sc_HitVec_size_max << G4endl; } supportcone_HitVec.clear(); supportcone_HitVec.reserve(sc_HitVec_size_max); }; // G4double getMeasuredEnergy(bool weighted=true); G4double getAbsorbedEnergy(); G4double getTotalEnergy(); G4double getAbsorberX0(); G4double getAbsorberdEdx(); G4double getAbsorberLambda(); G4double getHadronicFraction(); G4double getNeutronFraction(); G4double getMuonFraction(); G4double getPhotonFraction(); G4double getElectronFraction(); G4double getAverageTime(); G4int getTotalSensHits(); G4double getTotalSensE(); const G4SiHitVec & getSiHitVec(const unsigned & idx) const; const G4SiHitVec & getAlHitVec() const; void trackParticleHistory(const unsigned & idx,const G4SiHitVec & incoming); // void report(bool header=false); //members, all public unsigned n_elements; unsigned n_sectors; unsigned n_sens_elements; std::vector<G4double> ele_thick; std::vector<std::string> ele_name; std::vector<G4double> ele_X0; std::vector<G4double> ele_dEdx; std::vector<G4double> ele_L0; std::vector<G4double> ele_den; std::vector<G4double> ele_dl; std::vector<G4VPhysicalVolume*> ele_vol; G4VPhysicalVolume* supportcone_vol; G4VPhysicalVolume* dummylayer_vol; std::vector<G4double> sens_gFlux, sens_eFlux, sens_muFlux, sens_neutronFlux, sens_hadFlux, sens_time; G4double Total_thick; std::vector<G4SiHitVec> sens_HitVec; G4SiHitVec supportcone_HitVec; unsigned sens_HitVec_size_max; unsigned sc_HitVec_size_max; bool hasScintillator; double sensitiveZ; }; #endif
92b4399603423ae4651c56cec4e079033e53dc10
38620afd3304cdfe479832499a591690edd57cb1
/Data Structure and Algorithms Implementations/Data Structures/inorder.cpp
c931183f95e5149866021af54f7eed742d7e9eae
[]
no_license
ankan-ekansh/Competitive-Programming
6ca0e83af3507a7fa6fc2fc674d634750e73c1e0
b2a74f435acacd3b90d5271497bbe6392aa2689d
refs/heads/master
2021-06-12T18:44:30.295323
2021-05-14T16:43:24
2021-05-14T16:43:24
195,109,964
1
0
null
null
null
null
UTF-8
C++
false
false
1,115
cpp
inorder.cpp
#include<iostream> #include<stack> using namespace std; struct Node{ int data; Node *left, *right; Node(int data){ this->data = data; this->left = this->right = NULL; } }; void inorder(Node *node){ if(!node){ return; } inorder(node->left); cout << node->data << " "; inorder(node->right); } void inorderiter(Node *node){ if(!node){ return; } stack<Node*> s; // s.push(node); Node *cur = node; while(1){ while(cur){ s.push(cur); cur = cur->left; } if(s.empty()){ break; } cur = s.top(); s.pop(); cout << cur->data << " "; cur = cur->right; } } int main(){ Node* root = new Node(10); root->left = new Node(20); root->right = new Node(30); root->left->left = new Node(40); root->left->left->left = new Node(70); root->left->right = new Node(50); root->right->left = new Node(60); root->left->left->right = new Node(80); inorder(root); cout << '\n'; inorderiter(root); }
36275d4e5d48dbc6d5859b82c41029f2ec88eca3
3eeb870066b97115852a36d8eb1a65944b03c415
/src/main.cpp
1bf7f9ca5a4dbd453fc08700f9e967c9a162163a
[]
no_license
xVKSx/otus_008_print_ip
d3fb29647c51da02a1ce629f36693b13dcd907e2
c4533be7c9a223a63cfaa63b4db687928b4b2f50
refs/heads/master
2020-05-24T05:19:45.605358
2019-05-17T08:25:04
2019-05-17T08:25:04
187,112,759
0
0
null
null
null
null
UTF-8
C++
false
false
828
cpp
main.cpp
#include <iostream> #include <string> #include <vector> #include <list> #include <tuple> #include "ip/print.h" int main() { std::cout << Ip_NS::print_ip(char(-1)) << std::endl; std::cout << Ip_NS::print_ip(short(0)) << std::endl; std::cout << Ip_NS::print_ip(int(2130706433)) << std::endl; std::cout << Ip_NS::print_ip(long(8875824491850138409)) << std::endl; std::cout << Ip_NS::print_ip(std::string("127.0.0.1")) << std::endl; std::cout << Ip_NS::print_ip(std::vector<std::string>{"192", "168", "0", "100"}) << std::endl; std::cout << Ip_NS::print_ip(std::list<int>{192, 168, 0, 200}) << std::endl; std::cout << Ip_NS::print_ip(std::make_tuple("192", "168", "0", "255")) << std::endl; std::cout << Ip_NS::print_ip(std::make_tuple(192, 168, 0, 254)) << std::endl; return 0; }
538d8ff5ee26c9d714c82618755bf2f23ddeb60e
d448f745fc00af7fc980bfdfd5ffd0d6f87c2dfe
/Q1_Assignment_02(modified).cpp
5d689abd4e795068334cb805ea587f40b7221603
[]
no_license
muhammadzunique09/muhammadzunique09
af1d9356dba3492379ec70964675326a6903e7e6
fa81175d600cf12ab655a07f4b425a5b9827563b
refs/heads/main
2023-06-18T18:00:06.322405
2021-07-12T20:26:42
2021-07-12T20:26:42
374,230,337
0
0
null
null
null
null
WINDOWS-1252
C++
false
false
11,246
cpp
Q1_Assignment_02(modified).cpp
/* PROBLEM QUESTION: Package-delivery services, such as FedEx®, DHL® and UPS®, offer a number of different shipping options, each with specific costs associated. Create an inheritance hierarchy to represent various types of packages. Use Package as the base class of the hierarchy, then include classes TwoDayPackage and OvernightPackage that derive from Package. Base class Package should include data members representing the name, address, city, state and ZIP code for both the sender and the recipient of the package, in addition to data members that store the weight (in ounces) and cost per ounce to ship the package. Package’s constructor should initialize these data members. Ensure that the weight and cost per ounce contain positive values. Package should provide a public member function calculateCost that returns a double indicating the cost associated with shipping the package. Package’s calculateCost function should determine the cost by multiplying the weight by the cost per ounce. Derived class TwoDayPackage should inherit the functionality of base class Package, but also include a data member that represents a flat fee that the shipping company charges for two-day-delivery service. TwoDayPackage’s constructor should receive a value to initialize this data member. TwoDayPackage should redefine member function calculateCost so that it computes the shipping cost by adding the flat fee to the weight-based cost calculated by base class Package’s calculateCost function. Class OvernightPackage should inherit directly from class Package and contain an additional data member representing an additional fee per ounce charged for overnight-delivery service. OvernightPackage should redefine member function calculateCost so that it adds the additional fee per ounce to the standard cost per ounce before calculating the shipping cost. Write a test program that creates objects of each type of Package and tests member function calculateCost. */ #include<iostream> #include<iomanip> #include<string.h> #include<stdlib.h> #include<conio.h> using namespace std ; //BASE CLASS 1// class Person{ private: string name; string city; string state; string address; public: Person() { } //*****setters*****// void set_address(string address) { this->address = address; } void set_name(string name) { this->name = name; } void set_city(string city) { this->city = city; } void set_state(string state) { this->state = state; } //******getters********// string get_address() { return address; } string get_name() { return name; } string get_city() { return city; } string get_state() { return state; } //input// void input() { fflush(stdin); cout<<"Enter the Name : " ; getline(cin,name); fflush(stdin); cout<<"Enter Address : "; getline(cin,address); fflush(stdin); cout<<"Enter State : " ; getline(cin,state); fflush(stdin); cout<<"Enter City : "; getline(cin,city); fflush(stdin); } //display// void display() { cout<<"NAME : " <<name<<endl ; cout<<"STATE : " <<state<<endl ; cout<<"CITY : " <<city<<endl ; cout<<"ADDRESS : "<<address<<endl; } }; //sender's class class Sender:public Person{ private: string sender_zip_code; public: Sender() { } //setter// void set_s_zip(string sender_zip_code) { this->sender_zip_code = sender_zip_code; } //getter// string get_s_zip() { return sender_zip_code ; } //input// void input() { cout<<"SENDER'S DETAILS : \n------------------\n\n"; Person::input(); fflush(stdin); cout<<"Enter Zip code : " ; cin>>sender_zip_code; fflush(stdin); } //display// void display() { cout<<"SENDER'S DETAILS : \n---------------\n\n"; Person::display(); cout<<"ZIP CODE : "<<sender_zip_code; } }; //receiver's class class Receiver:public Person{ private: string receiver_zip_code; public: Receiver() { } //setter// void set_r_zip(string receiver_zip_code) { this->receiver_zip_code = receiver_zip_code; } //getter// string get_r_zip() { return receiver_zip_code ; } //input// void input() { cout<<"RECERIVER'S DETAILS : \n--------------------\n\n"; Person::input(); fflush(stdin); cout<<"Enter Zip code : " ; cin>>receiver_zip_code; fflush(stdin); } //display// void display() { cout<<"RECERIVER'S DETAILS : \n--------------------\n\n"; Person::display(); cout<<"ZIP CODE : "<<receiver_zip_code; } }; //BASE CLASS 2// class Package{ private: //private data member float weight_ounce; float cost_per_ounce; string obj_name; public: //public data membes and functions float total_cost ; //*****setters*****// void set_obj_name(string obj_name) { this->obj_name = obj_name; } void set_weight(float weight_ounce) { this->weight_ounce = weight_ounce; } void set_cost_per_ounce(float cost_per_ounce) { this->cost_per_ounce = cost_per_ounce; } //******getters********// string get_ob_name() { return obj_name; } float get_weight() { return weight_ounce; } float get_cost_per_ounce() { return cost_per_ounce; } double get_total_cost() { return total_cost ; } //***** default Constructor*********// Package() { total_cost = 0.0 ; } //***INPUT FUNCTION****// void input() { cout<<"Enter Name of Object you Want to send : "; getline(cin,obj_name); fflush(stdin); cout<<"Enter Weight of Package (ounces) : " ; cin>>weight_ounce; while(weight_ounce < 0.0) { cout<<endl <<"Re-enter weight as it was enterted negative : " ; cin>>weight_ounce; } fflush(stdin); cout<<"Enter Cost per Ounce : $ " ; cin>>cost_per_ounce; while(cost_per_ounce < 0.0) { cout<<endl <<"Re-enter Cost as it was enterted negative : $ " ; cin>>cost_per_ounce; } } //***display******// void display() { cout<<"PRODUCT'S DETAILS "<<endl<<"--------------------"<<endl<<endl; cout<<"ITEM NAME : "<<obj_name<<endl; cout<<"WEIGHT : " <<weight_ounce <<" ounce " <<endl ; cout<<"COST PER OUNCE : $ " <<cost_per_ounce <<endl ; } //calcu total cost **// void cal_total_cost() { total_cost = (cost_per_ounce)*(weight_ounce); } }; //****DERIVED CLASS*******// class TwoDayPackage:public Package,public Sender,public Receiver{ private : //private data members float flat_fee ; public : //public data members //setter// void set_flat_fee() { cout<<"Enter Flat Fee you want to Add : $ " ; cin>>flat_fee ; } //getter// float get_flat_fee() { return flat_fee ; } //default constructor// TwoDayPackage() { flat_fee = 0.0 ; } //parametrized constructor// TwoDaypackage(float fee) { this->flat_fee = fee ; } //***INPUT FUNCTION****// void input() { cout<<endl<<"Enter Details of Product : "<<endl<<"-------------"<<endl<<endl; Package::input(); cout<<"Enter Flat fee you want to add :$"; cin>>flat_fee ; fflush(stdin); } //calc total cost// void cal_total_cost() { total_cost = (get_cost_per_ounce())*(get_weight()) + flat_fee ; } void display() { cout<<"TWO DAY DELIVERY SERVICE " <<endl<<"======================="<<endl<<endl; Package::display(); cout<<"FLAT FEE : $ " <<flat_fee<<endl; cout<<"TOTAL AMOUNT : $ " <<total_cost <<endl<<endl<<endl<<endl ; } }; //Derivred Class// class OverNightPackage:public Package,public Sender,public Receiver{ private : //private data members float add_fee_per_ounce; public : //public data members //setter// void set_add_fee() { cout<<"Enter Additional Fee per Ounce for this service : $ "; cin>>add_fee_per_ounce; } float get_add_fee() { return add_fee_per_ounce; } //input function// void input() { cout<<endl<<"Enter Details of Product : "<<endl<<"------------------------"<<endl<<endl; Package::input(); cout<<"Enter additional fee per ounce for this service : $ "; cin>>add_fee_per_ounce; fflush(stdin); } //calc total cost// void cal_total_cost() { total_cost = (get_cost_per_ounce()+ (add_fee_per_ounce))*(get_weight()); } //display// void display() { cout<<"OVER NIGHT DELIVERY SERVICE " <<endl<<"==========================="<<endl<<endl; Package::display(); cout<<"Additional Fee charged : $ "<<add_fee_per_ounce<<endl; cout<<"TOTAL AMOUNT : $ "<<total_cost<<endl<<endl<<endl<<endl; } }; //***************main driver code******************// int main() { TwoDayPackage pack1; //creaing object of class_Two day Package OverNightPackage pack2; //creaing object of class_over night package Sender sen; //sender object Receiver rec; //receiver object string x ; //local varaible //Creating menu Bar // menu: system("CLS"); cout<<endl; cout<<"WELCOME TO OUR DELIVERY SERVICE "<<endl<<"==============================="<<endl<<endl ; cout<<"-> Two Day Delivery Service"<<endl<<"-> Over-Night Delivery Service "<<endl<<"-> EXIT CASE (Press 0)"<<endl; int choice; cout<<endl<<"Press 1 For Two Day and 2 For Over-Night"<<endl ; cout<<"Select the type of delivery You want : "; cin>>choice; //case-1 // if (choice == 1 ) { system("CLS"); cout<<"TWO DAY DELIVERY SERVICE " <<endl<<"======================="<<endl<<endl; fflush(stdin); sen.input(); cout<<endl; rec.input(); pack1.input(); pack1.cal_total_cost(); system("CLS"); pack1.display(); sen.display(); cout<<endl<<endl<<endl; rec.display(); cout<<endl<<endl; cout<<"Press Y to Continue .... "; cin>>x; if(x == "y"||"Y") { goto menu; } } //case-2// if(choice == 2) { system("CLS"); cout<<"OVER NIGHT DELIVERY SERVICE " <<endl<<"==========================="<<endl<<endl; fflush(stdin); sen.input(); cout<<endl; rec.input(); pack2.input(); pack2.cal_total_cost(); system("CLS"); pack2.display(); sen.display(); cout<<endl<<endl<<endl; rec.display(); cout<<endl<<endl; cout<<"Press Y to Continue .... "; cin>>x; if(x == "y"||"Y") { goto menu; } } //exiting case// if(choice == 0 ) { cout<<endl<<"EXITING PROGRAM ....!"<<endl; cout<<"THANK YOU ...!"<<endl; exit(0); } return 0 ; } //**********END OF MAIN************//
3db262ce30e9bf7c11ac9fe209d3ade5cb265b08
ba528bbca9dbfb68308cfea17f174a826e39aaa6
/SDCND-Project6-Extended-Kalman-Filter/src/tools.h
49d3197965e21a0ed38c7cc9180a98886a1d066f
[]
no_license
blester125/SDCND-Projects
dacd1fd1624cb8015c8c244a421796d0eb53672a
87890efaed34de4ec353574d2e3ed0a463d29ede
refs/heads/master
2020-03-07T16:12:52.577252
2018-03-31T22:25:49
2018-03-31T22:25:49
127,576,115
0
0
null
null
null
null
UTF-8
C++
false
false
854
h
tools.h
#ifndef TOOLS_H_ #define TOOLS_H_ #include <vector> #include "Eigen/Dense" #include "measurement_package.h" using Eigen::MatrixXd; using Eigen::VectorXd; using namespace std; /** * A helper method to calculate RMSE. */ VectorXd CalculateRMSE(const vector<VectorXd> &estimations, const vector<VectorXd> &ground_truth); /** * A helper method to calculate Jacobians. */ MatrixXd CalculateJacobian(const VectorXd& x_state); /** * A Helper method that converts Polar to Cartesian coordinates */ void PolarToCartesian(const MeasurementPackage &measurement_pack, double &px, double &py); /** * A Helper method to convert Cartesian To Polar coordinates */ Eigen::VectorXd CartesianToPolar(const Eigen::VectorXd x); /** * A Helper method to normalize an angle to be between -pi and pi */ void NormalizeAngle(double &angle); #endif /* TOOLS_H_ */
1c043a8e20bca724fdb342e2af7e9bca0dc8a823
e6e6c81568e0f41831a85490895a7cf5c929d50e
/yukicoder/1/1.cpp
7ba9d626f94c3842eaad0959f495da239d6f6275
[]
no_license
mint6421/kyopro
69295cd06ff907cd6cc43887ce964809aa2534d9
f4ef43669352d84bd32e605a40f75faee5358f96
refs/heads/master
2021-07-02T04:57:13.566704
2020-10-23T06:51:20
2020-10-23T06:51:20
182,088,856
0
0
null
null
null
null
UTF-8
C++
false
false
2,278
cpp
1.cpp
#include<bits/stdc++.h> using namespace std; #define inf 1000000000 #define INF 1000000000000000 #define ll long long #define ull unsigned long long #define M (int)(1e9+7) #define P pair<int,int> #define PLL pair<ll,ll> #define FOR(i,m,n) for(int i=(int)m;i<(int)n;i++) #define RFOR(i,m,n) for(int i=(int)m;i>=(int)n;i--) #define rep(i,n) FOR(i,0,n) #define rrep(i,n) RFOR(i,n,0) #define all(a) a.begin(),a.end() #define IN(a,n) rep(i,n){ cin>>a[i]; } const int vx[4] = {0,1,0,-1}; const int vy[4] = {1,0,-1,0}; #define PI 3.14159265 #define F first #define S second #define PB push_back #define EB emplace_back #define int ll void init(){ cin.tie(0); ios::sync_with_stdio(false); } template< typename T > struct edge { int src, to; T cost; edge(int to, T cost) : src(-1), to(to), cost(cost) {} edge(int src, int to, T cost) : src(src), to(to), cost(cost) {} edge &operator=(const int &x) { to = x; return *this; } operator int() const { return to; } }; template< typename T > using Edges = vector< edge< T > >; template< typename T > using WG = vector< Edges< T > >; using UG = vector< vector< int > >; template< typename T > using Matrix = vector< vector< T > >; template< typename T > vector<T> dijkstra(WG<T> &g,int s){ const auto lim = numeric_limits<T>::max(); vector<T> dist(g.size(),lim); using Pi = pair<T,int>; priority_queue<Pi,vector<Pi>,greater<Pi>> q; dist[s] = 0; q.emplace(dist[s],s); while(!q.empty()){ T cost; int idx; tie(cost,idx) = q.top(); q.pop(); if(dist[idx] < cost) continue; for( auto &e : g[idx]){ auto next_cost = cost + e.cost; if(dist[e.to] <= next_cost) continue; dist[e.to] = next_cost; q.emplace(dist[e.to],e.to); } } return dist; } main(){ int n,c,v; cin>>n>>c>>v; WG<int> es(n*(c+1)); vector<int> s(v),t(v),y(v),m(v); rep(i,v){ cin>>s[i]; s[i]--; } rep(i,v){ cin>>t[i]; t[i]--; } rep(i,v){ cin>>y[i]; } rep(i,v){ cin>>m[i]; } rep(i,v){ FOR(j,0,c-y[i]+1){ es[s[i]*(c+1)+j+y[i]].PB(edge<int>(t[i]*(c+1)+j,m[i])); } } vector<int> res=dijkstra(es,c); int ans=INF; rep(i,c+1){ ans=min(ans,res[(n-1)*(c+1)+i]); } cout<<(ans==INF?-1:ans)<<endl; }
762b73e2b6bb47274e6eb3373fec4622d54979b7
a677872af2c7257439587f620c0082c136350114
/include/Arbol.h
97bc6855f8857d7d8057b818a5a5f23b846d5dcd
[]
no_license
hr9457/-EDD-Tarea3_201314296
5ac3d13bdfb3bc6c3a88dbbfdfb8e5a629eb6571
d5ec4c56ffcfa2e614c275fc539d170af1723b79
refs/heads/master
2020-07-11T17:05:27.462406
2019-08-30T04:09:02
2019-08-30T04:09:02
204,600,386
0
0
null
null
null
null
UTF-8
C++
false
false
561
h
Arbol.h
#ifndef ARBOL_H #define ARBOL_H #include "NodoArbol.h" #include <iostream> #include <stdlib.h> #include <fstream> using namespace std; class Arbol { private: public: NodoArbol *raiz; ofstream archivo; int contadorNodos=0; Arbol();//constructor void insertar(string); void impresion(NodoArbol*); void generarDot(); void eliminarNodo(string); void buscarNodo(NodoArbol*,string); void borrarNodo(NodoArbol*,string); void generarImagenDot(); }; #endif // ARBOL_H
d38dc473573694138b4b061c3680055fc658bcaf
a147d891b2eb10380122b47faa0b11411c3125f6
/Socket-Programming/server.cpp
ac10dac1c8267441ff36fdc4034c5e23da689329
[]
no_license
aribalam/Object-Oriented-System-Design-Assignments
bf0c37314d4f05dd2216462abee897a56cf0a338
f2f3e0a0c7b6082ebcf6ea13baced966963449e6
refs/heads/master
2020-06-27T06:28:21.031572
2019-08-25T14:23:40
2019-08-25T14:23:40
199,869,630
0
0
null
null
null
null
UTF-8
C++
false
false
1,453
cpp
server.cpp
#include<iostream> #include <string.h> #include <unistd.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> using namespace std; #define PORT 8080 #define MAX_QUEUE 5 void sort(int num[], int n) { int t; for (int i = 0; i < n; i++) { for (int j = 0; j < n-1-i; j++) { if (num[j] > num[j+1]) { t = num[j]; num[j] = num[j+1]; num[j+1] = t; } } } } int main() { struct sockaddr_in serv_address, client_address; socklen_t client_len; int socketfd = socket(AF_INET, SOCK_STREAM, 0); if (socketfd < 0) { cout << "Error creating socket" << endl; return 0; } cout << "Socket created" << endl; bzero((char *) &serv_address, sizeof(serv_address)); serv_address.sin_family = AF_INET; serv_address.sin_addr.s_addr = INADDR_ANY; serv_address.sin_port = htons(PORT); int code = bind(socketfd, (struct sockaddr* ) &serv_address, sizeof(serv_address)); if (code < 0) { cout << "Error binding the socket" << endl; } cout << "Socket binded" << endl; listen(socketfd, MAX_QUEUE); client_len = sizeof(client_address); int new_socket_fd = accept(socketfd, (struct sockaddr*) &client_address, &client_len); if (new_socket_fd < 0) { cout << "Error accepting a socket" << endl; } cout << "Socket accepted" << endl; int numbers[10]; while (recv(new_socket_fd, &numbers, 10 * sizeof(int), 0) > 0) { sort(numbers, 10); write(new_socket_fd, &numbers, 10 * sizeof(int)); } }
4d61b4786c474615ca47d2c9370909e79ef25ebe
35376451f198aeaae05bc4b49aaa8535271487cf
/Minemonics/src/controller/universe/environments/Plane.cpp
ad42732260e9746ebec6f8706294b1b4443b95e4
[]
no_license
benelot/minemonics
11d267619dc2a325841b6bec37a0cd4820ed8ed4
e6e306dc704772a495afa3824f5f391703251e8c
refs/heads/master
2022-06-21T15:31:06.041996
2022-06-10T21:39:09
2022-06-10T21:39:09
26,160,744
32
4
null
null
null
null
UTF-8
C++
false
false
993
cpp
Plane.cpp
//# corresponding headers #include <controller/universe/environments/Plane.hpp> //# forward declarations //# system headers //## controller headers //## model headers //## view headers //# custom headers //## base headers //## configuration headers //## controller headers //## model headers //## view headers //## utils headers BoostLogger Plane::mBoostLogger; /*<! initialize the boost logger*/ Plane::_Init Plane::_initializer; Plane::Plane() : Environment() { } Plane::~Plane() { // They are all deleted in environment } void Plane::initialize( EnvironmentModel* const environmentModel, const Ogre::Light* const l) { Environment::initialize(); // setup the planet model mEnvironmentModel = environmentModel; // setup the plane view mEnvironmentGraphics = new PlaneO3D((PlaneModel*) mEnvironmentModel); getPlaneView()->initialize(l); } void Plane::update(double timeSinceLastTick) { getPlaneModel()->update(timeSinceLastTick); getPlaneView()->update(timeSinceLastTick); }
839a02e8c182f37b71ce456fc076e3221c39b3b1
a186bf948ac29f3696238e3677f0cf0138fb6860
/Atividades/Jader_Oliveira/Lista2/EX9_Jader_Oliveira.cpp
fc0cf05b2c9691594b673ad94a47810e3a4934f6
[]
no_license
professorlineu/PROA3-2019-2
b8c3c944884e847370940a9a48fe580bfea9a4d3
84f1cf48598cc925d56e2ed0164c561ae7f5249e
refs/heads/master
2020-06-25T16:38:52.992529
2019-11-25T22:33:16
2019-11-25T22:33:16
199,367,654
0
0
null
null
null
null
ISO-8859-1
C++
false
false
810
cpp
EX9_Jader_Oliveira.cpp
/********************************************************** - Autor: Jader Oliveira - Descrição: Lista 2 EX9 **********************************************************/ #include <iostream> #include <locale.h> #include <cstdlib> using namespace std; int main() { float fBaseMa = 0; float fBaseMe = 0; float fAltura = 0; float fArea = 0; setlocale(LC_ALL,""); system("color F1"); cout << "veja só, calcule a área de um trapézio!!" << endl; cout << "digite o valor da base maior: "; cin >> fBaseMa; cout << "digite o valor da base menor: "; cin >> fBaseMe; cout << "digite o valor da altura: "; cin >> fAltura; fArea = ((fBaseMa-fBaseMe)*fAltura)/2; cout << "a área do trapézio é: " << fArea; }
5ac5ccaea64064be2ef2b122f5e4377f7e9aa2c2
5062a66be5eb35e7346e5ad58c5a6730a5fb6619
/Source/UI/EffectConnectable.h
8b1693b025a5ee4be0e8750f5adc0a60717c5f83
[]
no_license
Franchovy/QDIO
2d0733563cc669a56cb920fe1f18503d4dbc54c9
bef0fe4ae7244619c999baa918310ca5d35bcb5c
refs/heads/master
2023-05-31T10:11:56.848370
2020-10-20T11:54:12
2020-10-20T11:54:12
244,294,600
14
1
null
null
null
null
UTF-8
C++
false
false
943
h
EffectConnectable.h
/* ============================================================================== EffectConnectable.h Created: 15 Oct 2020 11:17:47am Author: maxime ============================================================================== */ #pragma once #include <JuceHeader.h> #include "ConnectionPort.h" #include "ConnectionContainer.h" struct EffectPorts { OwnedArray<ConnectionPort> inPorts; OwnedArray<ConnectionPort> outPorts; }; class EffectConnectable { public: EffectConnectable(); virtual void setNumPorts(int numIn, int numOut); void addConnectionToThis(Connection* newConnection); void moveConnectedComponent(SceneComponent* component, Point<int> delta); Array<ConnectionPort*> getPorts(); protected: EffectPorts ports; private: std::unique_ptr<ConnectionPort> createPort(bool isInput); ReferenceCountedArray<Connection> connections; };
35ce2972686a2454643cd8668456cf13da76ded4
d51838e7568a7ed1d134ec361d1cd942dd03ab96
/Calculations/Task_1/Project2/Main.cpp
879dc45d61f58131c0fe74eff48d5ef3706ae7dd
[]
no_license
Serbernari/study_projects
9173a093ac7f05151a3cecd570187e614472f1f3
6b901d125db37e3a7ee34bfcd90ebb842a43cb55
refs/heads/master
2021-12-14T04:26:59.464547
2021-11-25T22:34:07
2021-11-25T22:34:07
150,863,061
0
0
null
null
null
null
UTF-8
C++
false
false
643
cpp
Main.cpp
#include <iostream> #include <fstream> #include <vector> #include "MyMatrix.h" #include "MatrixMath.h" #include <string> using namespace std; int main() { std::string *f_diag = new string, *f_lower = new string, *f_upper = new string; *f_diag = "D:/GitHub/study_projects/Calculations/Task1_files/f_diag.txt"; *f_lower = "D:/GitHub/study_projects/Calculations/Task1_files/f_lower.txt"; *f_upper = "D:/GitHub/study_projects/Calculations/Task1_files/f_upper.txt"; MyMatrix testMatrix(f_diag,f_lower,f_upper); vector<double> testVec = {1,1,1,1,1,1,1,1,1 }; mult_MatOnVect(&testMatrix, &testVec); LU_expansion(&testMatrix); return 0; }
bb1d2ed4e42f477f0f49f87f293b626ebc3bec5f
8abb30b3946f44a0fa5e548da30bb7d53eeeeffb
/Source/VMKFingersSolverEditor/Private/VMKFingersSolverEditor.cpp
1050c363c7590a2abb471997a9d75b3e191b9cef
[]
no_license
maddigit/ViveMocapKit
8589373df2b1671b5f68797dbf2d019ed95473fd
965a3af13d6d585d87fdd6d5d22bb63dda2afbf5
refs/heads/main
2023-03-18T11:10:38.618471
2020-10-12T07:48:28
2020-10-12T07:48:28
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,587
cpp
VMKFingersSolverEditor.cpp
// VR IK Body Component // (c) Yuri N Kalinin, 2017, ykasczc@gmail.com. All right reserved. #include "VMKFingersSolverEditor.h" #include "Framework/Application/SlateApplication.h" #include "Modules/ModuleManager.h" #include "ContentBrowserModule.h" #include "Animation/AnimSequence.h" #include "Framework/Commands/UICommandInfo.h" #include "Framework/Commands/UICommandList.h" #include "Framework/MultiBox/MultiBoxBuilder.h" #include "AssetData.h" #include "Textures/SlateIcon.h" #include "EditorDirectories.h" #include "DesktopPlatformModule.h" #include "IDesktopPlatform.h" #include "AnimationExportFunctionLibrary.h" #define LOCTEXT_NAMESPACE "FVMKFingersSolverEditor" void FVMKFingersSolverEditor::StartupModule() { CommandList = MakeShareable(new FUICommandList); FContentBrowserModule& ContentBrowserModule = FModuleManager::LoadModuleChecked<FContentBrowserModule>(TEXT("ContentBrowser")); ContentBrowserModule.GetAllAssetViewContextMenuExtenders().Add(FContentBrowserMenuExtender_SelectedAssets::CreateLambda([this](const TArray<FAssetData>& SelectedAssets) { TSharedRef<FExtender> Extender = MakeShared<FExtender>(); if (SelectedAssets.ContainsByPredicate([](const FAssetData& AssetData) { return AssetData.GetClass() == UAnimSequence::StaticClass(); })) { Extender->AddMenuExtension( "AssetContextMoveActions", EExtensionHook::After, CommandList, FMenuExtensionDelegate::CreateLambda([this, SelectedAssets](FMenuBuilder& MenuBuilder) { MenuBuilder.AddMenuEntry( LOCTEXT("VMK_ExportAnimationBVH", "Export Animation (BVH)..."), LOCTEXT("VMK_ExportAnimationBVHToolTip", "Export animation sequence to BVH file"), FSlateIcon(), FUIAction(FExecuteAction::CreateRaw(this, &FVMKFingersSolverEditor::ExportAnimSequenceToBVH, SelectedAssets))); })); } return Extender; })); ContentBrowserMenuExtenderHandle = ContentBrowserModule.GetAllAssetViewContextMenuExtenders().Last().GetHandle(); } void FVMKFingersSolverEditor::ExportAnimSequenceToBVH(TArray<FAssetData> SelectedAssets) { IDesktopPlatform* const DesktopPlatform = FDesktopPlatformModule::Get(); const void* ParentWindowWindowHandle = FSlateApplication::Get().FindBestParentWindowHandleForDialogs(nullptr); for (const auto& Asset : SelectedAssets) { if (Asset.GetClass() == UAnimSequence::StaticClass()) { const FString DefaultPath = FEditorDirectories::Get().GetLastDirectory(ELastDirectory::GENERIC_EXPORT); TArray<FString> OutFiles; if (DesktopPlatform->SaveFileDialog( ParentWindowWindowHandle, LOCTEXT("ExportAnimationBVHTitle", "Choose file name to save...").ToString(), DefaultPath, TEXT(""),//TEXT("Curve Table JSON (*.json)|*.json"); TEXT("Biovision Hierarchical Data (*.bvh)|*.bvh"), EFileDialogFlags::None, OutFiles )) { const UAnimSequence* AnimSequence = Cast<UAnimSequence>(Asset.GetAsset()); if (AnimSequence && OutFiles.Num() > 0) { UAnimationExportFunctionLibrary::ExportAnimSequenceToBVH(AnimSequence, OutFiles[0], true, true, false); } } } } } void FVMKFingersSolverEditor::ShutdownModule() { FContentBrowserModule* ContentBrowserModule = FModuleManager::GetModulePtr<FContentBrowserModule>(TEXT("ContentBrowser")); if (ContentBrowserModule) { ContentBrowserModule->GetAllAssetViewContextMenuExtenders().RemoveAll([=](const FContentBrowserMenuExtender_SelectedAssets& InDelegate) { return ContentBrowserMenuExtenderHandle == InDelegate.GetHandle(); }); } } #undef LOCTEXT_NAMESPACE IMPLEMENT_MODULE(FVMKFingersSolverEditor, VMKFingersSolverEditor)
e1c58584f8c920aaf47879d87ca535ce28ca8f27
af920815edbcc7bb4dbd347e714cd703980437ec
/main/device/drv_fusb302.cpp
1078dc251203cebb80157b102ad26f0f6c93321a
[ "MIT" ]
permissive
huming2207/fusb302-esp
0105c7272f0bb5070c7ef2254a718871f7086c18
34a7753b1b4f5b71e97d2b2111a3b707a1a22656
refs/heads/master
2020-12-12T22:13:42.765121
2020-04-07T01:23:57
2020-04-07T01:23:57
234,243,428
4
1
null
null
null
null
UTF-8
C++
false
false
18,917
cpp
drv_fusb302.cpp
#include <hal/i2c_types.h> #include <hal/gpio_types.h> #include <driver/i2c.h> #include <esp_log.h> #include "drv_fusb302.hpp" #include "tcpc_drv.hpp" #define I2C_WRITE_BIT 0U #define I2C_READ_BIT 1U #define FUSB302_ADDR 0x22U #define FUSB302_INTR_GENERAL_BIT (1U << 0U) #define FUSB302_INTR_TX_DONE_BIT (1U << 1U) #define FUSB302_INTR_TX_FAIL_BIT (1U << 2U) #define TAG "fusb302_drv" using namespace device; EventGroupHandle_t fusb302::intr_evt_group = nullptr; void IRAM_ATTR fusb302::gpio_isr_handler(void* arg) { static BaseType_t taskStatus = pdFALSE; xEventGroupSetBitsFromISR(intr_evt_group, FUSB302_INTR_GENERAL_BIT, &taskStatus); } void fusb302::write_reg(uint8_t reg, uint8_t param) { i2c_cmd_handle_t cmd = i2c_cmd_link_create(); ESP_ERROR_CHECK(i2c_master_start(cmd)); ESP_ERROR_CHECK(i2c_master_write_byte(cmd, (uint8_t)(FUSB302_ADDR << 1U) | I2C_WRITE_BIT, true)); ESP_ERROR_CHECK(i2c_master_write_byte(cmd, reg, true)); ESP_ERROR_CHECK(i2c_master_write_byte(cmd, param, true)); ESP_ERROR_CHECK(i2c_master_stop(cmd)); ESP_ERROR_CHECK(i2c_master_cmd_begin(i2c_port, cmd, pdMS_TO_TICKS(1000))); i2c_cmd_link_delete(cmd); } uint8_t fusb302::read_reg(uint8_t reg) { uint8_t result = 0; i2c_cmd_handle_t cmd = i2c_cmd_link_create(); ESP_ERROR_CHECK(i2c_master_start(cmd)); ESP_ERROR_CHECK(i2c_master_write_byte(cmd, (uint8_t)(FUSB302_ADDR << 1U) | I2C_WRITE_BIT, true)); ESP_ERROR_CHECK(i2c_master_write_byte(cmd, reg, true)); ESP_ERROR_CHECK(i2c_master_start(cmd)); ESP_ERROR_CHECK(i2c_master_write_byte(cmd, (uint8_t)(FUSB302_ADDR << 1U) | I2C_READ_BIT, true)); ESP_ERROR_CHECK(i2c_master_read_byte(cmd, &result, I2C_MASTER_LAST_NACK)); ESP_ERROR_CHECK(i2c_master_stop(cmd)); ESP_ERROR_CHECK(i2c_master_cmd_begin(i2c_port, cmd, pdMS_TO_TICKS(1000))); i2c_cmd_link_delete(cmd); return result; } esp_err_t fusb302::transmit_pkt(uint16_t header, const uint32_t *data_objs, size_t obj_cnt) { if (data_objs == nullptr && obj_cnt > 0) return ESP_ERR_INVALID_ARG; // Step 1. Flush Tx FIFO set_ctrl_0(FUSB302_REG_CONTROL0_TX_FLUSH); i2c_cmd_handle_t cmd = i2c_cmd_link_create(); ESP_ERROR_CHECK(i2c_master_start(cmd)); ESP_ERROR_CHECK(i2c_master_write_byte(cmd, (uint8_t)(FUSB302_ADDR << 1U) | I2C_WRITE_BIT, true)); ESP_ERROR_CHECK(i2c_master_write_byte(cmd, FUSB302_REG_FIFOS, true)); // Step 2. Send SOP tokens uint8_t sop_token[4] = {fusb302_token::SYNC1, fusb302_token::SYNC1, fusb302_token::SYNC1, fusb302_token::SYNC2 }; ESP_ERROR_CHECK(i2c_master_write(cmd, sop_token, sizeof(sop_token), true)); // Step 3. Send packet header ESP_ERROR_CHECK(i2c_master_write_byte(cmd, (uint8_t)(header & 0xffU), true)); ESP_ERROR_CHECK(i2c_master_write_byte(cmd, (uint8_t)(header >> 8U), true)); // Step 4. Send data objects (if there is any) if (data_objs != nullptr && obj_cnt > 0) { for (size_t idx = 0; idx < obj_cnt; idx ++) { ESP_ERROR_CHECK(i2c_master_write_byte(cmd, (uint8_t)(data_objs[idx] & 0xffU), true)); ESP_ERROR_CHECK(i2c_master_write_byte(cmd, (uint8_t)(data_objs[idx] >> 8U), true)); ESP_ERROR_CHECK(i2c_master_write_byte(cmd, (uint8_t)(data_objs[idx] >> 16U), true)); ESP_ERROR_CHECK(i2c_master_write_byte(cmd, (uint8_t)(data_objs[idx] >> 24U), true)); } } // Step 5. Send CRC, End of Packet and TX_OFF tokens, with TX_ON token appended uint8_t post_token[4] = {fusb302_token::JAMCRC, fusb302_token::EOP, fusb302_token::TXOFF, fusb302_token::TXON }; ESP_ERROR_CHECK(i2c_master_write(cmd, post_token, sizeof(post_token), true)); ESP_ERROR_CHECK(i2c_master_stop(cmd)); ESP_ERROR_CHECK(i2c_master_cmd_begin(i2c_port, cmd, pdMS_TO_TICKS(1000))); i2c_cmd_link_delete(cmd); return ESP_OK; } /** * Read FIFO * @param drv_handle[in] * @param header[out] PD Header (2 bytes, 16 bits) * @param data_objs[out] Data objects (4 bytes, 32 bits for each) * @param max_cnt Maxmium data objects can be received * @param actual_cnt Actual received data objects * @return * */ esp_err_t fusb302::receive_pkt(uint16_t *header, uint32_t *data_objs, size_t max_cnt) { if (header == nullptr || (data_objs == nullptr && max_cnt > 0 )) return ESP_ERR_INVALID_ARG; i2c_cmd_handle_t cmd = i2c_cmd_link_create(); ESP_ERROR_CHECK(i2c_master_start(cmd)); ESP_ERROR_CHECK(i2c_master_write_byte(cmd, (FUSB302_ADDR << 1U) | I2C_WRITE_BIT, true)); ESP_ERROR_CHECK(i2c_master_write_byte(cmd, FUSB302_REG_FIFOS, true)); ESP_ERROR_CHECK(i2c_master_start(cmd)); ESP_ERROR_CHECK(i2c_master_write_byte(cmd, (FUSB302_ADDR << 1U) | I2C_READ_BIT, true)); // Step 1. Read first token byte uint8_t token_byte = 0; ESP_ERROR_CHECK(i2c_master_read_byte(cmd, &token_byte, I2C_MASTER_ACK)); ESP_ERROR_CHECK(i2c_master_cmd_begin(i2c_port, cmd, pdMS_TO_TICKS(1000))); i2c_cmd_link_delete(cmd); // Step 2. Read header, 2 bytes cmd = i2c_cmd_link_create(); uint8_t header_bytes[2] = { 0 }; ESP_ERROR_CHECK(i2c_master_read(cmd, header_bytes, 2, I2C_MASTER_ACK)); ESP_ERROR_CHECK(i2c_master_cmd_begin(i2c_port, cmd, pdMS_TO_TICKS(1000))); *header = (uint16_t)(header_bytes[1] << 8U) | header_bytes[0]; i2c_cmd_link_delete(cmd); // Step 3. Calculate packet length uint8_t data_obj_cnt = TCPC_PD_HEADER_DATA_OBJ_CNT(*header); // Step 4. Read data object (if it is not a control message) if (data_obj_cnt > 0) { if (data_obj_cnt > max_cnt) { ESP_LOGE(TAG, "Buffer is too small: got %u DO's, but max space is %u", data_obj_cnt, max_cnt); return ESP_ERR_NO_MEM; } uint8_t data_obj_bytes[28] = { 0 }; // Maximum data objects is 7, so 7 * 4 = 28 bytes cmd = i2c_cmd_link_create(); ESP_ERROR_CHECK(i2c_master_read(cmd, data_obj_bytes, sizeof(data_obj_bytes), I2C_MASTER_ACK)); ESP_ERROR_CHECK(i2c_master_cmd_begin(i2c_port, cmd, pdMS_TO_TICKS(1000))); i2c_cmd_link_delete(cmd); // Copy to output buffer for (size_t idx = 0; idx < data_obj_cnt * 4; idx += 4) { data_objs[idx] = (uint32_t)(data_obj_bytes[idx + 3] << 24U) | (uint32_t)(data_obj_bytes[idx + 2] << 16U) | (uint32_t)(data_obj_bytes[idx + 1] << 8U) | data_obj_bytes[idx]; } } // Step 5. Read CRC-32 uint8_t checksum_bytes[4] = { 0 }; cmd = i2c_cmd_link_create(); ESP_ERROR_CHECK(i2c_master_read(cmd, checksum_bytes, sizeof(checksum_bytes), I2C_MASTER_LAST_NACK)); ESP_ERROR_CHECK(i2c_master_stop(cmd)); ESP_ERROR_CHECK(i2c_master_cmd_begin(i2c_port, cmd, pdMS_TO_TICKS(1000))); i2c_cmd_link_delete(cmd); // Step 6: Flush FIFO set_ctrl_1(FUSB302_REG_CONTROL1_RX_FLUSH); return ESP_OK; } void fusb302::intr_task(void* arg) { ESP_LOGD(TAG, "Interrupt task started"); auto *ctx = static_cast<fusb302 *>(arg); while(true) { // Clear on exit, wait only one bit xEventGroupWaitBits(intr_evt_group, FUSB302_INTR_GENERAL_BIT, pdTRUE, pdFALSE, portMAX_DELAY); if (ctx == nullptr) { ESP_LOGE(TAG, "Interrupt triggered but ctx is invalid"); return; } ESP_LOGD(TAG, "Interrupt triggered, talking on I2C num: "); ctx->clear_irq(); if ((ctx->interrupt_reg & FUSB302_REG_INTERRUPT_VBUSOK) > 0) { ESP_LOGI(TAG, "Cable connected!"); ctx->auto_config_polarity(); } else if ((ctx->interrupt_reg & FUSB302_REG_INTERRUPT_CRC_CHK) > 0) { ESP_LOGI(TAG, "Packet received!"); if (ctx->rx_cb) ctx->rx_cb(); } } } fusb302::fusb302(int sda, int scl, int intr, i2c_port_t port) { // Setup I2C i2c_port = port; i2c_config_t fusb_i2c_config = {}; fusb_i2c_config.mode = I2C_MODE_MASTER; fusb_i2c_config.sda_io_num = (gpio_num_t)sda; fusb_i2c_config.sda_pullup_en = GPIO_PULLUP_ENABLE; fusb_i2c_config.scl_io_num = (gpio_num_t)scl; fusb_i2c_config.scl_pullup_en = GPIO_PULLUP_ENABLE; fusb_i2c_config.master.clk_speed = 100000; esp_err_t err = i2c_param_config(i2c_port, &fusb_i2c_config); err = err ?: i2c_driver_install(i2c_port, fusb_i2c_config.mode, 0, 0, 0); if (err != ESP_OK) { ESP_LOGE(TAG, "Failed to set I2C"); } // Setup INTR pin gpio_config_t intr_gpio_conf = {}; intr_gpio_conf.mode = GPIO_MODE_INPUT; intr_gpio_conf.intr_type = GPIO_INTR_NEGEDGE; intr_gpio_conf.pull_down_en = GPIO_PULLDOWN_ENABLE; intr_gpio_conf.pull_up_en = GPIO_PULLUP_DISABLE; intr_gpio_conf.pin_bit_mask = (1U << (uint32_t)intr); gpio_config(&intr_gpio_conf); // Reset FUSB302 and PD reset(true, true); // Create GPIO Interrupt event group intr_evt_group = xEventGroupCreate(); if (intr_evt_group == nullptr) { ESP_LOGE(TAG, "Cannot create interrupt event group"); } // Setup interrupt service err = gpio_install_isr_service(0); err = err ?: gpio_isr_handler_add((gpio_num_t)intr, gpio_isr_handler, nullptr); if (err != ESP_OK) { ESP_LOGE(TAG, "Cannot setup GPIO interrupt services"); } // Start GPIO Interrupt task xTaskCreate(fusb302::intr_task, "fusb_intr", 4096, this, 3, nullptr); // Read Device ID uint8_t dev_id = get_dev_id(); ESP_LOGI(TAG, "Init sequence started, DevID: 0x%02x", dev_id); // Retry 3 times, auto retry enable uint8_t reg_ctrl_3 = get_ctrl_3(); reg_ctrl_3 |= FUSB302_REG_CONTROL3_AUTO_RETRY; reg_ctrl_3 |= PD_RETRY_COUNT << FUSB302_REG_CONTROL3_N_RETRIES_POS; set_ctrl_3(reg_ctrl_3); // Mask interrupts // Enable CRC_CHK and VBUSOK (set to 0), disable others uint8_t mask_bits = 0xff; mask_bits &= ~FUSB302_REG_MASK_CRC_CHK; // CRC_CHK interrupt for packet receive callback mask_bits &= ~FUSB302_REG_MASK_VBUSOK; // VBUSOK interrupt for charger connection detection set_mask(mask_bits); set_mask_a(0xff); set_mask_b(FUSB302_REG_MASK_B_GCRCSENT); // Enable global interrupt uint8_t ctrl0_reg = get_ctrl_0(); ctrl0_reg &= ~FUSB302_REG_CONTROL0_INT_MASK; set_ctrl_0(ctrl0_reg); // Clear IRQ clear_irq(); // Switches1: CC1 Tx Enable, PD 2.0, Auto GoodCRC Enable set_switch_1(FUSB302_REG_SWITCHES1_TXCC1_EN | FUSB302_REG_SWITCHES1_AUTO_GCRC | FUSB302_REG_SWITCHES1_SPECREV0); // Enable all power set_power(FUSB302_REG_POWER_PWR_ALL); // Clear IRQ clear_irq(); } void fusb302::on_pkt_received(const tcpc_def::rx_ready_cb &func) { rx_cb = func; } bool fusb302::detect_vbus() { return false; } esp_err_t fusb302::set_rp(tcpc_def::rp_mode rp) { return 0; } esp_err_t fusb302::set_cc(tcpc_def::cc_pull pull) { return 0; } esp_err_t fusb302::get_cc(tcpc_def::cc_status *status_cc1, tcpc_def::cc_status *status_cc2) { ESP_LOGD(TAG, "Getting CC status"); if(status_cc1 == nullptr || status_cc2 == nullptr) return ESP_ERR_INVALID_ARG; // TODO: implement source mode if (is_pull_up) return ESP_ERR_NOT_SUPPORTED; detect_cc_pin_sink(status_cc1, status_cc2); return ESP_OK; } esp_err_t fusb302::set_polarity(bool is_flipped) { // Step 1: Configure Switch0 uint8_t sw0_reg = get_switch_0(); // Step 1.1: Re-configure VCONN sw0_reg &= ~FUSB302_REG_SWITCHES0_VCONN_CC1; sw0_reg &= ~FUSB302_REG_SWITCHES0_VCONN_CC2; if (vconn_enabled) { sw0_reg |= is_flipped ? FUSB302_REG_SWITCHES0_VCONN_CC2 : FUSB302_REG_SWITCHES0_VCONN_CC1; } // Step 1.2: Re-configure MEAS sw0_reg &= ~FUSB302_REG_SWITCHES0_MEAS_CC1; sw0_reg &= ~FUSB302_REG_SWITCHES0_MEAS_CC2; sw0_reg |= is_flipped ? FUSB302_REG_SWITCHES0_MEAS_CC2 : FUSB302_REG_SWITCHES0_MEAS_CC1; // Step 1.3: Write back to Switch0 set_switch_0(sw0_reg); // Step 2: Configure Switch1 uint8_t sw1_reg = get_switch_1(); sw1_reg &= ~FUSB302_REG_SWITCHES1_TXCC1_EN; sw1_reg &= ~FUSB302_REG_SWITCHES1_TXCC2_EN; sw1_reg |= is_flipped ? FUSB302_REG_SWITCHES1_TXCC2_EN : FUSB302_REG_SWITCHES1_TXCC1_EN; sw1_reg |= FUSB302_REG_SWITCHES1_AUTO_GCRC; // Enable Auto GoodCRC again? // Step 2.1: Write back to Switch1 set_switch_1(sw1_reg); return ESP_OK; } esp_err_t fusb302::auto_config_polarity() { ESP_LOGD(TAG, "Polarity auto config started"); tcpc_def::cc_status status_cc1, status_cc2; auto ret = get_cc(&status_cc1, &status_cc2); if (ret != ESP_OK) { ESP_LOGE(TAG, "Failed to get CC status"); return ESP_FAIL; } if (status_cc1 == status_cc2) { ESP_LOGE(TAG, "Both CC lines are active or disconnected!"); return ESP_ERR_INVALID_STATE; } bool is_flipped = status_cc1 < status_cc2; ESP_LOGI(TAG, "Cable flipped: %s", is_flipped ? "Yes" : "No"); return set_polarity(is_flipped); } esp_err_t fusb302::set_vconn(bool enable) { return 0; } uint8_t fusb302::get_dev_id() { return read_reg(FUSB302_REG_DEVICE_ID); } void fusb302::set_switch_0(uint8_t val) { write_reg(FUSB302_REG_SWITCHES0, val); } uint8_t fusb302::get_switch_0() { return read_reg(FUSB302_REG_SWITCHES0); } void fusb302::set_switch_1(uint8_t val) { write_reg(FUSB302_REG_SWITCHES1, val); } uint8_t fusb302::get_switch_1() { return read_reg(FUSB302_REG_SWITCHES1); } void fusb302::set_measure(uint8_t val) { write_reg(FUSB302_REG_MEASURE, val); } uint8_t fusb302::get_measure() { return read_reg(FUSB302_REG_MEASURE); } void fusb302::set_slice(uint8_t val) { write_reg(FUSB302_REG_SLICE, val); } uint8_t fusb302::get_slice() { return read_reg(FUSB302_REG_SLICE); } void fusb302::set_ctrl_0(uint8_t val) { write_reg(FUSB302_REG_CONTROL0, val); } uint8_t fusb302::get_ctrl_0() { return read_reg(FUSB302_REG_CONTROL0); } void fusb302::set_ctrl_1(uint8_t val) { write_reg(FUSB302_REG_CONTROL1, val); } uint8_t fusb302::get_ctrl_1() { return read_reg(FUSB302_REG_CONTROL1); } void fusb302::set_ctrl_2(uint8_t val) { write_reg(FUSB302_REG_CONTROL2, val); } uint8_t fusb302::get_ctrl_2() { return read_reg(FUSB302_REG_CONTROL2); } void fusb302::set_ctrl_3(uint8_t val) { write_reg(FUSB302_REG_CONTROL3, val); } uint8_t fusb302::get_ctrl_3() { return read_reg(FUSB302_REG_CONTROL3); } void fusb302::set_ctrl_4(uint8_t val) { write_reg(FUSB302_REG_CONTROL4, val); } uint8_t fusb302::get_ctrl_4() { return read_reg(FUSB302_REG_CONTROL4); } void fusb302::set_mask(uint8_t val) { write_reg(FUSB302_REG_MASK, val); } uint8_t fusb302::get_mask() { return read_reg(FUSB302_REG_MASK); } void fusb302::set_power(uint8_t val) { write_reg(FUSB302_REG_POWER, val); } uint8_t fusb302::get_power() { return read_reg(FUSB302_REG_POWER); } void fusb302::reset(bool pd_rst, bool sw_rst) { write_reg(FUSB302_REG_RESET, (pd_rst ? FUSB302_REG_RESET_PD_RESET : 0U) | (sw_rst ? FUSB302_REG_RESET_SW_RESET : 0U)); } uint8_t fusb302::get_ocp() { return read_reg(FUSB302_REG_OCP); } void fusb302::set_ocp(uint8_t val) { write_reg(FUSB302_REG_OCP, val); } void fusb302::set_mask_a(uint8_t val) { write_reg(FUSB302_REG_MASK_A, val); } uint8_t fusb302::get_mask_a() { return read_reg(FUSB302_REG_MASK_A); } void fusb302::set_mask_b(uint8_t val) { write_reg(FUSB302_REG_MASK_B, val); } uint8_t fusb302::get_mask_b() { return read_reg(FUSB302_REG_MASK_B); } uint8_t fusb302::get_status_0a() { return read_reg(FUSB302_REG_STATUS0A); } uint8_t fusb302::get_status_1a() { return read_reg(FUSB302_REG_STATUS1A); } uint8_t fusb302::get_status_0() { return read_reg(FUSB302_REG_STATUS0); } uint8_t fusb302::get_status_1() { return read_reg(FUSB302_REG_STATUS1); } void fusb302::clear_interrupt_a(uint8_t val) { write_reg(FUSB302_REG_INTERRUPT_A, val); } uint8_t fusb302::get_interrupt_a() { return read_reg(FUSB302_REG_INTERRUPT_A); } void fusb302::clear_interrupt_b(uint8_t val) { write_reg(FUSB302_REG_INTERRUPT_B, val); } uint8_t fusb302::get_interrupt_b() { return read_reg(FUSB302_REG_INTERRUPT_B); } void fusb302::clear_interrupt(uint8_t val) { write_reg(FUSB302_REG_INTERRUPT, val); } uint8_t fusb302::get_interrupt() { return read_reg(FUSB302_REG_INTERRUPT); } void fusb302::detect_cc_pin_sink(tcpc_def::cc_status *cc1, tcpc_def::cc_status *cc2) { // Step 1. Read Switch0 register uint8_t sw0_reg = get_switch_0(); // Step 2. Backup original state uint8_t meas_cc1_orig = ((sw0_reg & FUSB302_REG_SWITCHES0_MEAS_CC1) == 0) ? 0 : 1; uint8_t meas_cc2_orig = ((sw0_reg & FUSB302_REG_SWITCHES0_MEAS_CC2) == 0) ? 0 : 1; // Step 3. Disable CC2 and enable CC1 measurement sw0_reg &= ~FUSB302_REG_SWITCHES0_MEAS_CC2; sw0_reg |= FUSB302_REG_SWITCHES0_MEAS_CC1; set_switch_0(sw0_reg); vTaskDelay(pdMS_TO_TICKS(1)); // Step 4. Get CC1 measurement result uint8_t bc_lvl_cc1 = get_status_0(); bc_lvl_cc1 &= (FUSB302_REG_STATUS0_BC_LVL0 | FUSB302_REG_STATUS0_BC_LVL1); // Step 5. Disable CC1 and enable CC2 measurement sw0_reg &= ~FUSB302_REG_SWITCHES0_MEAS_CC1; sw0_reg |= FUSB302_REG_SWITCHES0_MEAS_CC2; set_switch_0(sw0_reg); vTaskDelay(pdMS_TO_TICKS(1)); // Step 6. Get CC1 measurement result uint8_t bc_lvl_cc2 = get_status_0(); bc_lvl_cc2 &= (FUSB302_REG_STATUS0_BC_LVL0 | FUSB302_REG_STATUS0_BC_LVL1); // Step 7. Convert detection output *cc1 = convert_bc_lvl(bc_lvl_cc1); *cc2 = convert_bc_lvl(bc_lvl_cc2); // Step 8. Restore Switch0 register sw0_reg = get_switch_0(); if (meas_cc1_orig > 0) { sw0_reg |= FUSB302_REG_SWITCHES0_MEAS_CC1; } else { sw0_reg &= ~FUSB302_REG_SWITCHES0_MEAS_CC1; } if (meas_cc2_orig > 0) { sw0_reg |= FUSB302_REG_SWITCHES0_MEAS_CC2; } else { sw0_reg &= ~FUSB302_REG_SWITCHES0_MEAS_CC2; } set_switch_0(sw0_reg); } tcpc_def::cc_status fusb302::convert_bc_lvl(uint8_t bc_lvl) { auto ret = tcpc_def::TCPC_VOLT_OPEN; if (is_pull_up) { if (bc_lvl == 0x00) ret = tcpc_def::TCPC_VOLT_RA; else if (bc_lvl < 0x3) ret = tcpc_def::TCPC_VOLT_RD; } else { if (bc_lvl == 0x1) ret = tcpc_def::TCPC_VOLT_SNK_DEF; else if (bc_lvl == 0x2) ret = tcpc_def::TCPC_VOLT_SNK_1_5; else if (bc_lvl == 0x3) ret = tcpc_def::TCPC_VOLT_SNK_3_0; } return ret; } void fusb302::clear_irq() { interrupt_reg = get_interrupt(); interrupt_a_reg = get_interrupt_a(); interrupt_b_reg = get_interrupt_b(); ESP_LOGD(TAG, "IRQ: 0x%02x, a: 0x%02x, b: 0x%02x", interrupt_reg, interrupt_a_reg, interrupt_b_reg); }
5ebc952e15fc788e96e90aacc5c9d81a398650a0
6b2c8d135641dd4bddca24badcbbd1aa53f45f46
/owe.h
b91f677ba81801a08ed04a8dca0bd076a7c87880
[]
no_license
hojei1452/Opportunistic-Wireless-Encryption-OWE-
2eee696385fa9ea568fd88e0a0ac16200c7608fb
9b28164ca78cccf58cbe15d7cd8375bc72b330ac
refs/heads/main
2023-08-24T23:07:02.170550
2021-10-09T12:30:41
2021-10-09T12:30:41
415,302,107
0
0
null
null
null
null
UTF-8
C++
false
false
2,192
h
owe.h
#ifndef _OWE_H_ #define _OWE_H_ #include "debug_owe.h" #include "key_owe.h" #include "utils.h" #include "packet.h" #include <unistd.h> #include <thread> #include <ctime> #include <map> #include <utility> #define IS_TEST class OWE { private: #define MAX_INTERVAL_COUNT 3 typedef struct PACKED _ADDR { u8 ap[IEEE80211_ADDR_LEN]; u8 bssid[IEEE80211_ADDR_LEN]; u8 sta[IEEE80211_ADDR_LEN]; u8 br[IEEE80211_ADDR_LEN]; } ADDR; typedef enum _STATUS_CODE { NONE_AP, AP_ADDR_CAPTURE, SEND_PROBE_REQ, RECV_PROBE_RES, SEND_AUTH_REQ, RECV_AUTH_RES, SEND_ASSOC_REQ, RECV_ASSOC_RES, EAPOL, DONE } STATUS_CODE; typedef struct _KEY { pcap_t *handle; ADDR addr; KEY_OWE ap; KEY_OWE sta; STATUS_CODE status; } KEY; PACKET packet; string dev; string adapter; pcap_t *handle; pcap_t *beaconHandle; pcap_t *probeHandle; void init(string _dev); void init(KEY *_key, u8 *_sta); bool start_ap(KEY *_key); void sendp(pcap_t *_handle, const int _interval, u8 *_packet, int _len); bool recvp(pcap_t *_handle, u16 _fc, u8 *_src, u8 *_dst); bool send_recv(pcap_t *_handle, u16 _fc, const int _interval, u8 *_send_packet, int _send_len, u8 *_src, u8 *_dst); bool send_recv(KEY *_key, u16 _fc, const int _interval, u8 *_send_packet, int _send_len, u8 *_src, u8 *_dst); bool send_recv(pcap_t *_handle, u16 _fc, const int _interval, u8 *_send_packet1, int _send_len1, u8 *_send_packet2, int _send_len2, u8 *_src, u8 *_dst); bool send_recv(KEY *_key, u16 _fc, const int _interval, u8 *_send_packet1, int _send_len1, u8 *_send_packet2, int _send_len2, u8 *_src, u8 *_dst); bool send_recv_key(KEY *_key); void recv_send(pcap_t *_handle, u16 _recv_fc, u16 _send_fc); bool recv_send_key(pcap_t *_handle); public: map<string, KEY> info; KEY key; ADDR addr; void start(); OWE(string _dev); ~OWE(); }; OWE::OWE(string _dev) { this->init(_dev); this->key.status = NONE_AP; } OWE::~OWE() { this->handle = NULL; } #endif