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
4bee468971216ea197989f56c8aac1cef9cdc0dd
d229621f907e1bbe255ac32d42eeeabfef70801f
/Codeforces/Soldier and bananas/main.cpp
1341cf6b7411a8cfcb4c47243ecd5508219c1c69
[]
no_license
geekswaroop/Competitive-Coding-Solutions
df8f8dafedab0aac1d081a6fcb6c099395b47765
25124a3ce58b081c6f54c1442855489038315e78
refs/heads/master
2020-05-14T15:08:29.659499
2019-11-04T11:55:49
2019-11-04T11:55:49
181,846,111
0
0
null
null
null
null
UTF-8
C++
false
false
215
cpp
main.cpp
#include <iostream> using namespace std; int main() { long long k,n,w,ans; cin>>k>>n>>w; ans=(((k*w*(w+1))/2)-n); if(ans>0) cout<<((k*w*(w+1))/2)-n; else cout<<"0"; return 0; }
1194517e536c3f8fcf067ae84c573fa2241eb628
be04d41cc516caec667467787a238e1463b815eb
/src/py/wrapper_90fba55bcadf52088b0326eb2a205040.cpp
66d9c5507e8a72ab56137991289271b3857ba113
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
nikhilkalige/ClangLite
9f0db6088dee83f89996d4c01da9979c39b3862c
dcb6d7385cca25c0a888bb56ae3ec1eb951cd752
refs/heads/master
2020-04-21T23:48:28.409657
2019-02-20T08:14:21
2019-02-20T08:14:21
169,958,200
0
0
Apache-2.0
2019-02-10T08:37:14
2019-02-10T08:37:14
null
UTF-8
C++
false
false
1,272
cpp
wrapper_90fba55bcadf52088b0326eb2a205040.cpp
#include "_clanglite.h" class ::clang::ObjCAtDefsFieldDecl * (*method_pointer_83c5fa6f39485e8f901598dba33095be)(class ::clang::ASTContext &, unsigned int )= ::clang::ObjCAtDefsFieldDecl::CreateDeserialized; bool (*method_pointer_d221044262765a60acaf9e3b81cca3c6)(class ::clang::Decl const *)= ::clang::ObjCAtDefsFieldDecl::classof; bool (*method_pointer_149b9040920c5fffbdec7c6fceea3d15)(enum ::clang::Decl::Kind )= ::clang::ObjCAtDefsFieldDecl::classofKind; namespace autowig { } void wrapper_90fba55bcadf52088b0326eb2a205040(pybind11::module& module) { pybind11::class_<class ::clang::ObjCAtDefsFieldDecl, autowig::HolderType< class ::clang::ObjCAtDefsFieldDecl >::Type, class ::clang::FieldDecl > class_90fba55bcadf52088b0326eb2a205040(module, "ObjCAtDefsFieldDecl", "Represents a field declaration created by an @defs(…).\n\n"); class_90fba55bcadf52088b0326eb2a205040.def_static("create_deserialized", method_pointer_83c5fa6f39485e8f901598dba33095be, pybind11::return_value_policy::reference_internal, ""); class_90fba55bcadf52088b0326eb2a205040.def_static("classof", method_pointer_d221044262765a60acaf9e3b81cca3c6, ""); class_90fba55bcadf52088b0326eb2a205040.def_static("classof_kind", method_pointer_149b9040920c5fffbdec7c6fceea3d15, ""); }
6594de125e5bfb0c15cf8281b3cf18858cbf98cb
4b48afdb133aead2777a24ead2955dca920436a1
/src/requestMapping/RequestMapping.hpp
2026c2a1111e9026b1e1d497e646e81fd3f65126
[]
no_license
xiyuan-fengyu/RequestMapping
9e309964b86ec34750441b692d75f2eb141849b6
597a21ceb861630abdf538343c1ba8f5cddba57a
refs/heads/master
2021-09-05T22:25:44.503695
2018-01-31T10:43:27
2018-01-31T10:43:27
119,371,648
1
0
null
null
null
null
UTF-8
C++
false
false
762
hpp
RequestMapping.hpp
// // Created by xiyuan_fengyu on 2018/1/29. // #ifndef REQUESTMAPPING_REQUESTMAPPING_HPP #define REQUESTMAPPING_REQUESTMAPPING_HPP #include "RequestDispatcher.hpp" namespace xiyuan { // 全局函数版本 #ifndef RequestMapping #define RequestMapping(pathMatch, httpMethod, methodName) \ void handler_##methodName##_callback(const std::shared_ptr<HttpServer::Response> &response, const std::shared_ptr<HttpServer::Request> &request);\ auto handler_##methodName##_index = xiyuan::add(pathMatch, #httpMethod, &(handler_##methodName##_callback)); /* NOLINT */\ void handler_##methodName##_callback(const std::shared_ptr<HttpServer::Response> &response, const std::shared_ptr<HttpServer::Request> &request) #endif } #endif //REQUESTMAPPING_REQUESTMAPPING_HPP
c99adb66f022d47b1a46266a10a9900cb06a56b9
21a9be8ad0b098bed68175a9b3f4ce7be6920296
/6_12.cpp
52d41b3bcc4916ba844fa5ff0588734b05d3bcc7
[]
no_license
201711010346/oop_6
08f8df367f59b3e56a110ac50ae63651cf4a84a2
4a16bb98cfceb98928d921e5d8251f18e31f5aac
refs/heads/master
2020-04-13T08:46:57.981512
2018-12-25T15:07:47
2018-12-25T15:07:47
163,091,874
0
0
null
null
null
null
UTF-8
C++
false
false
147
cpp
6_12.cpp
#include"6_12.h" void Line::Draw() { cout << "Line::Draw is called.\n"; } void Circle::Draw() { cout << "Circle::Draw is called.\n"; }
43284730483c02af0d803fc633bf1864f07df946
40c8decd720fd821620383ca40350b64543cce79
/Win32.0/IControl.cpp
b0ada3d67ebe6d08db028dc0221e68ae1e615115
[]
no_license
shimachao/Win32.0
a94f465afecc7bc533641d43e671534d4c0c3815
f0767b81e66c37e438cbe0b14c7f5692a53a3be1
refs/heads/master
2021-01-10T03:47:47.863610
2017-03-06T14:53:15
2017-03-06T14:53:15
53,912,561
2
0
null
null
null
null
GB18030
C++
false
false
796
cpp
IControl.cpp
#include "IControl.h" IControl::IControl(int width, int height) :IElement(width, height) { } IControl::~IControl() { } bool IControl::ifMouseIn(int x, int y) { if (x >= 0 && x <= m_width && y >=0 && y << m_height) { return true; } else { return false; } } // 鼠标移到控件上 void IControl::mouseMoveIn() { // do nothing } // 鼠标移到控件外 void IControl::mouseMoveOut() { // do nothing } // 鼠标左键按下(在控件捕获范围内) void IControl::LMBDown() { // do nothing } // 鼠标左键弹起(在控件捕获范围内) void IControl::LMBUp() { // do nothing } // 获得焦点 void IControl::getFocus() { // do nothing } // 失去焦点 void IControl::loseFocus() { // do nothing }
cf23b54250b8bf27b64f18cfca764d33886243f2
02b87cef237d92926cffdfb17fd071810ad47308
/src/hed/shc/arcpdp/ArcPolicy.cpp
877162f51cfce94200f81d7ec6de1aa1fa753868
[ "MIT", "LicenseRef-scancode-warranty-disclaimer", "Apache-2.0" ]
permissive
nordugrid/arc
1a7bf10f00a5d62c30aece7ae14a34c3073d420a
170dc8e8a2a2eb0d4734a475c9ca16843483e7cb
refs/heads/master
2023-08-31T05:11:54.609507
2023-08-17T10:40:48
2023-08-17T10:40:48
176,701,676
9
11
Apache-2.0
2022-06-03T12:54:51
2019-03-20T09:42:06
C++
UTF-8
C++
false
false
5,028
cpp
ArcPolicy.cpp
#ifdef HAVE_CONFIG_H #include <config.h> #endif #include <list> #include <arc/security/ClassLoader.h> #include "ArcPolicy.h" #include "ArcRule.h" Arc::Logger ArcSec::ArcPolicy::logger(Arc::Logger::rootLogger, "ArcPolicy"); static Arc::NS policyns("policy", "http://www.nordugrid.org/schemas/policy-arc"); /** get_policy (in charge of class-loading of ArcPolicy) can only accept one type of argument--XMLNode */ Arc::Plugin* ArcSec::ArcPolicy::get_policy(Arc::PluginArgument* arg) { //std::cout<<"Argument type of ArcPolicy:"<<typeid(arg).name()<<std::endl; if(arg==NULL) return NULL; Arc::ClassLoaderPluginArgument* clarg = arg?dynamic_cast<Arc::ClassLoaderPluginArgument*>(arg):NULL; if(!clarg) return NULL; // Check if empty or valid policy is supplied Arc::XMLNode* doc = (Arc::XMLNode*)(*clarg); if(doc==NULL) { std::cerr<<"ArcPolicy creation requires XMLNode as argument"<<std::endl; return NULL; } // NOTE: Following line is not good for autodetection. Should it be removed? //if(!(*doc)) return new ArcSec::ArcPolicy; ArcSec::ArcPolicy* policy = new ArcSec::ArcPolicy(*doc,arg); if((!policy) || (!(*policy))) { delete policy; return NULL; }; return policy; } //loader_descriptors __arc_policy_modules__ = { // { "arc.policy", 0, &ArcSec::ArcPolicy::get_policy }, // { NULL, 0, NULL } //}; using namespace Arc; using namespace ArcSec; ArcPolicy::ArcPolicy(Arc::PluginArgument* parg) : Policy(parg), comalg(NULL), evaluatorctx(NULL), algfactory(NULL) { Arc::XMLNode newpolicy(policyns,"policy:Policy"); newpolicy.New(policynode); policytop=policynode; } ArcPolicy::ArcPolicy(const XMLNode node,Arc::PluginArgument* parg) : Policy(node,parg), comalg(NULL), evaluatorctx(NULL), algfactory(NULL) { if((!node) || (node.Size() == 0)) { logger.msg(ERROR,"Policy is empty"); return; } node.New(policynode); std::list<XMLNode> res = policynode.XPathLookup("//policy:Policy",policyns); if(res.empty()) { policynode.Destroy(); return; } policytop = *(res.begin()); } ArcPolicy::ArcPolicy(const XMLNode node, EvaluatorContext* ctx, Arc::PluginArgument* parg) : Policy(node,parg), comalg(NULL) { if((!node) || (node.Size() == 0)) { logger.msg(WARNING,"Policy is empty"); return; } node.New(policynode); std::list<XMLNode> res = policynode.XPathLookup("//policy:Policy",policyns); if(res.empty()) { policynode.Destroy(); return; } policytop = *(res.begin()); setEvaluatorContext(ctx); make_policy(); } void ArcPolicy::make_policy() { //EvalResult.node record the policy(in XMLNode) information about evaluation result. //According to the developer's requirement, EvalResult.node can include rules(in XMLNode) //that "Permit" or "Deny" the request tuple. In the existing code, it include all //the original rules. if(!policynode) return; if(!policytop) return; evalres.node = policynode; evalres.effect = "Not_applicable"; ArcRule *rule; //Get AlgFactory from EvaluatorContext algfactory = (AlgFactory*)(*evaluatorctx); XMLNode nd = policytop; XMLNode rnd; if((bool)nd){ nd = policytop; id = (std::string)(nd.Attribute("PolicyId")); //Setup the rules' combining algorithm inside one policy, according to the "CombiningAlg" name if(nd.Attribute("CombiningAlg")) comalg = algfactory->createAlg((std::string)(nd.Attribute("CombiningAlg"))); else comalg = algfactory->createAlg("Deny-Overrides"); description = (std::string)(nd["Description"]); } logger.msg(VERBOSE, "PolicyId: %s Alg inside this policy is:-- %s", id, comalg?(comalg->getalgId()):""); for ( int i=0;; i++ ){ rnd = nd["Rule"][i]; if(!rnd) break; rule = new ArcRule(rnd, evaluatorctx); subelements.push_back(rule); } } MatchResult ArcPolicy::match(EvaluationCtx*){// ctx){ //RequestTuple* evaltuple = ctx->getEvalTuple(); //Because ArcPolicy definition has no any <Subject, Resource, Action, Condition> directly; //All the <Subject, Resource, Action, Condition>s are only in ArcRule. //So the function always return "Match" return MATCH; } Result ArcPolicy::eval(EvaluationCtx* ctx){ Result result = comalg?comalg->combine(ctx, subelements):DECISION_INDETERMINATE; if(result == DECISION_PERMIT) evalres.effect = "Permit"; else if(result == DECISION_DENY) evalres.effect = "Deny"; else if(result == DECISION_INDETERMINATE) evalres.effect = "Indeterminate"; else if(result == DECISION_NOT_APPLICABLE) evalres.effect = "Not_Applicable"; return result; } EvalResult& ArcPolicy::getEvalResult() { return evalres; } void ArcPolicy::setEvalResult(EvalResult& res){ evalres = res; } const char* ArcPolicy::getEvalName() const{ return "arc.evaluator"; } const char* ArcPolicy::getName() const{ return "arc.policy"; } ArcPolicy::~ArcPolicy(){ while(!(subelements.empty())){ delete subelements.back(); subelements.pop_back(); } }
5480f2349534de983d161753941d94880491713c
efb1e3bd4f1bf79f5c2bc90a34bb33bf171f5f43
/drake/examples/QPInverseDynamicsForHumanoids/system/humanoid_status_translator_system.h
c35b4920438acd195322cbb57258e422a3ace609
[ "BSD-3-Clause" ]
permissive
martiwer/drake
dab2278d41fc4197ccc13a518c4327caa57040b1
709171b00b92e79557920329346f5500718a2caf
refs/heads/master
2021-05-16T09:44:48.965884
2017-09-22T01:25:43
2017-09-22T01:25:43
104,477,877
6
1
null
null
null
null
UTF-8
C++
false
false
4,329
h
humanoid_status_translator_system.h
#pragma once #include <memory> #include <string> #include <utility> #include "drake/common/drake_copyable.h" #include "drake/examples/QPInverseDynamicsForHumanoids/humanoid_status.h" #include "drake/manipulation/util/robot_state_msg_translator.h" #include "drake/multibody/rigid_body_tree.h" #include "drake/systems/controllers/qp_inverse_dynamics/robot_kinematic_state.h" #include "drake/systems/framework/leaf_system.h" namespace drake { namespace examples { namespace qp_inverse_dynamics { /** * An abstract base class for systems that translate various types of state * into HumanoidStatus. */ class HumanoidStatusTranslatorSystem : public systems::LeafSystem<double> { public: DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(HumanoidStatusTranslatorSystem) /** * Constructor. * @param robot Pointer to a RigidBodyTree. The lifespan of @p robot must * be longer than this object. * @param alias_group_path Path to the alias groups file. Used to construct * HumanoidStatus. */ HumanoidStatusTranslatorSystem(const RigidBodyTree<double>* robot, const std::string& alias_group_path); /** * Returns the output port for HumanoidStatus. */ const systems::OutputPort<double>& get_output_port_humanoid_status() const { return get_output_port(output_port_index_humanoid_status_); } protected: const systems::controllers::qp_inverse_dynamics::RobotKinematicState<double>& get_default_output() const { return *default_output_; } /** * Derived classes should use this to record the output port index. */ void set_output_port_index_humanoid_status(systems::OutputPortIndex index) { output_port_index_humanoid_status_ = index; } const RigidBodyTree<double>& get_robot() const { return robot_; } private: const RigidBodyTree<double>& robot_; std::unique_ptr< systems::controllers::qp_inverse_dynamics::RobotKinematicState<double>> default_output_; int output_port_index_humanoid_status_{0}; }; /** * Translates a state vector to HumanoidStatus. */ class StateToHumanoidStatusSystem : public HumanoidStatusTranslatorSystem { public: DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(StateToHumanoidStatusSystem) /** * Constructor. * @param robot Pointer to a RigidBodyTree. The lifespan of @p robot must * be longer than this object. * @param alias_group_path Path to the alias groups file. Used to construct * HumanoidStatus. */ StateToHumanoidStatusSystem(const RigidBodyTree<double>* robot, const std::string& alias_group_path); /** * Returns the input port for a state vector. */ const systems::InputPortDescriptor<double>& get_input_port_state() const { return get_input_port(input_port_index_state_); } private: // This is the calculator for the output port. void CalcHumanoidStatus( const systems::Context<double>& context, systems::controllers::qp_inverse_dynamics::RobotKinematicState<double>* output) const; int input_port_index_state_{0}; }; /** * Translates a bot_core::robot_state_t message to HumanoidStatus. */ class RobotStateMsgToHumanoidStatusSystem : public HumanoidStatusTranslatorSystem { public: DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(RobotStateMsgToHumanoidStatusSystem) /** * Constructor. * @param robot Pointer to a RigidBodyTree. The lifespan of @p robot * must be longer than this object. * @param alias_group_path Path to the alias groups file. Used to construct * HumanoidStatus. */ RobotStateMsgToHumanoidStatusSystem(const RigidBodyTree<double>* robot, const std::string& alias_group_path); /** * Returns input port for bot_core::robot_state_t. */ inline const systems::InputPortDescriptor<double>& get_input_port_robot_state_msg() const { return get_input_port(input_port_index_lcm_msg_); } private: // This is the calculator for the output port. void CalcHumanoidStatus( const systems::Context<double>& context, systems::controllers::qp_inverse_dynamics::RobotKinematicState<double>* output) const; const manipulation::RobotStateLcmMessageTranslator translator_; int input_port_index_lcm_msg_{0}; }; } // namespace qp_inverse_dynamics } // namespace examples } // namespace drake
e7115adf7be643cf533a24f2f68e54a2aa1c5487
d340d503e132508de61f8b7379ea6f0100ff0297
/duet_exploration/include/duet_exploration/costmap_tools.h
43fbc043fef6be49a2b867719be2f78c6cb16a05
[]
no_license
wang81522472/uav_nuc
ff171f063d846a4dea7523c47ec149d8d7815c5f
b60a39a1cc318485e701fd9924a94bf5671bc15f
refs/heads/master
2021-04-03T04:10:26.366328
2018-04-27T11:48:44
2018-04-27T11:48:44
124,403,871
7
2
null
null
null
null
UTF-8
C++
false
false
2,173
h
costmap_tools.h
#ifndef COSTMAP_TOOLS_H_ #define COSTMAP_TOOLS_H_ #include <geometry_msgs/PolygonStamped.h> #include <geometry_msgs/PointStamped.h> #include <costmap_2d/costmap_2d.h> #include <boost/foreach.hpp> #include <ros/ros.h> namespace duet_exploration{ /** * @brief Determine 4-connected neighbourhood of an input cell, checking for map edges * @param idx input cell index * @param costmap Reference to map data * @return neighbour cell indexes */ std::vector<unsigned int> nhood4(unsigned int idx, unsigned int size_x_, unsigned int size_y_){ std::vector<unsigned int> out; if (idx > size_x_ * size_y_ -1){ ROS_WARN("Evaluating nhood for offmap point"); return out; } if(idx % size_x_ > 0){ out.push_back(idx - 1); } if(idx % size_x_ < size_x_ - 1){ out.push_back(idx + 1); } if(idx >= size_x_){ out.push_back(idx - size_x_); } if(idx < size_x_*(size_y_-1)){ out.push_back(idx + size_x_); } return out; } /** * @brief Determine 8-connected neighbourhood of an input cell, checking for map edges * @param idx input cell index * @param costmap Reference to map data * @return neighbour cell indexes */ std::vector<unsigned int> nhood8(unsigned int idx, unsigned int size_x_, unsigned int size_y_){ //get 8-connected neighbourhood indexes, check for edge of map std::vector<unsigned int> out = nhood4(idx, size_x_, size_y_); if (idx > size_x_ * size_y_ -1){ return out; } if(idx % size_x_ > 0 && idx >= size_x_){ out.push_back(idx - 1 - size_x_); } if(idx % size_x_ > 0 && idx < size_x_*(size_y_-1)){ out.push_back(idx - 1 + size_x_); } if(idx % size_x_ < size_x_ - 1 && idx >= size_x_){ out.push_back(idx + 1 - size_x_); } if(idx % size_x_ < size_x_ - 1 && idx < size_x_*(size_y_-1)){ out.push_back(idx + 1 + size_x_); } return out; } int sign(int x) { return x > 0 ? 1.0 : -1.0; } } #endif
40cb4e5f2702371938478fb56f79283d1359b4ad
a8f712b403e92b2f217ef2a6d68460280752c4ea
/puzzleBobble/2DGame/puzzleBobble/02-Bubble/Player.cpp
18365ac0270b6f54e809e91a6dd4fed0115c9afd
[]
no_license
xictrov/puzzleBobble
60761e718fe79d35d1100c11b20b259214fa07fd
6fd9de98c73145378e36bec4fab60653fd5d83ba
refs/heads/master
2021-08-19T16:11:13.769086
2017-11-26T20:23:45
2017-11-26T20:23:45
105,983,949
1
1
null
null
null
null
UTF-8
C++
false
false
2,371
cpp
Player.cpp
#define _USE_MATH_DEFINES #include <cmath> #include <iostream> #include <GL/glew.h> #include <GL/glut.h> #include "Player.h" #include "Game.h" #define JUMP_ANGLE_STEP 4 #define JUMP_HEIGHT 96 #define FALL_STEP 4 bool izq = true; enum PlayerAnims { COLOR }; enum explosionAnims { ONE, TWO, THREE, FOUR, FIVE }; void Player::init(const glm::ivec2 &tileMapPos, ShaderProgram &shaderProgram, int colorbola, bool &gameover) { color=colorbola; bJumping = false; if (color == 20) { spritesheet.loadFromFile("images/bomb.png", TEXTURE_PIXEL_FORMAT_RGBA); sprite = Sprite::createSprite(glm::ivec2(32, 32), glm::vec2(1,1), &spritesheet, &shaderProgram); sprite->setNumberAnimations(1); sprite->setAnimationSpeed(COLOR, 0); sprite->addKeyframe(COLOR, glm::vec2(0.f, color)); } else { if (!gameover) { spritesheet.loadFromFile("images/sprites.png", TEXTURE_PIXEL_FORMAT_RGBA); } else { spritesheet.loadFromFile("images/escalagrises.png", TEXTURE_PIXEL_FORMAT_RGBA); } sprite = Sprite::createSprite(glm::ivec2(32, 32), glm::vec2(0.16666, 0.125f), &spritesheet, &shaderProgram); sprite->setNumberAnimations(1); sprite->setAnimationSpeed(COLOR, 0); sprite->addKeyframe(COLOR, glm::vec2(0.f, color / 8.f)); } sprite->changeAnimation(0); tileMapDispl = tileMapPos; posPlayer = glm::vec2(0.0f); posPlayerF = glm::vec2(0.0f); sprite->setPosition(glm::vec2(float(tileMapDispl.x), float(tileMapDispl.y))); } void Player::update(int deltaTime, float angle, bool &cambio, bool &acaba, bool &gameover) { sprite->update(deltaTime, 0.0f, false, true); if (posPlayer.x < -112.5f || posPlayer.x>112.5f ) { angle = (float) M_PI - angle; cambio = true; } posPlayerF.x -= cos(angle) * 15; posPlayerF.y -= sin(angle) * 15; posPlayer.x=int(roundf(posPlayerF.x)); posPlayer.y=int(roundf(posPlayerF.y)); acaba = map->collision(posPlayer+tileMapDispl, color, gameover, deltaTime); sprite->setPosition(glm::vec2(float(tileMapDispl.x + posPlayer.x), float(tileMapDispl.y + posPlayer.y))); } void Player::render() { sprite->render(); } void Player::setTileMap(TileMap *tileMap) { map = tileMap; } void Player::setPosition(const glm::vec2 &pos) { posPlayer = pos; sprite->setPosition(glm::vec2(float(tileMapDispl.x + posPlayer.x), float(tileMapDispl.y + posPlayer.y))); } void Player::setColor(int col) { color=col; }
2cda12e08de325dd8675fd9879b6538d02082430
287b14395f1509784f5c76ca898c0319447be111
/branchingLogic/IF/4.3.IGRA-1_v3-funcExample.cpp
8ec91ba790ec09929f5693dedba65806b23649b8
[ "MIT" ]
permissive
dovanduy/cppTopics
48045085e7afff79e22373aa04dc688056cda118
94461d25832b53e6c40c374fb2ff1695b3dfe3c7
refs/heads/master
2020-05-26T19:22:24.706301
2017-06-28T19:38:57
2017-06-28T19:38:57
null
0
0
null
null
null
null
UTF-8
C++
false
false
480
cpp
4.3.IGRA-1_v3-funcExample.cpp
// IGRA_v3.cpp #include <iostream> using namespace std; int moveMe (int movingPos1, int oldPos2, int zarValue, int mapSize) { int newPos ; newPos = ((movingPos1 + zarValue > mapSize ) ? movingPos1 : movingPos1 + zarValue ) ; newPos += (oldPos2 == newPos) ? -1 : 0 ; return newPos ; } main() { int m, p1, p2, k, p ; char const DELIMITER = ' ' ; cin >>m >>p1 >>p2 >>k >>p ; p1 = moveMe (p1, p2, k, m) ; p2 = moveMe (p2, p1, p, m) ; cout <<p1 <<DELIMITER <<p2 ; }
fe2e0e956e85ab9e62769f860d99a143244db97d
6c2b9ff417b98e54f39fdc533d59a18e1108094f
/main.cpp
19e2a39309e3b762d9c6ec4d608ac6dcfaeaedc7
[]
no_license
rostek93/English_teacher
d4703b94ea035f63733c008bdc445719ed0c695c
99470df845793716e0f58d199af7313103a7c61a
refs/heads/master
2021-01-10T04:26:35.752510
2016-03-27T17:40:20
2016-03-27T17:40:20
54,840,510
0
0
null
null
null
null
UTF-8
C++
false
false
338
cpp
main.cpp
/** * @file main.cpp * @author Damian Pobrotyn , Kamil Rostecki * @brief Function main. */ #include "MainWindow.h" #include "DatabaseFile.h" #include <QApplication> int main(int argc, char *argv[]) { QApplication a(argc, argv); MainWindow w; w.show(); DatabaseFile df; df.registerFun(); return a.exec(); }
29bf87735fa189e87a10a342011e6f90a08252a5
fa4017a751d52b30dae39964832bcffd9ed62944
/吉田学園情報ビジネス専門学校_髙岩一稀/Square/開発環境/life_ui.h
b2676de1cb8d5ad4a3d96d70f5098262d53184ed
[]
no_license
takaki2018/Takaiwa_Game
a02bd15a1887526d707276c6a5100e7615cb029b
eee9356e755839e1163b488bf23da3b8c3ab1470
refs/heads/master
2023-09-01T20:29:11.756042
2021-10-28T06:41:38
2021-10-28T06:41:38
305,336,787
0
1
null
2020-10-22T01:08:21
2020-10-19T09:49:55
C++
SHIFT_JIS
C++
false
false
1,564
h
life_ui.h
//============================================================================= // // ライフUI処理 [life_ui.h] // Author : itsuki takaiwa // //============================================================================= #ifndef _LIFEUI_H_ #define _LIFEUI_H_ #include "scene.h" //***************************************************************************** // マクロ定義 //***************************************************************************** #define MAX_LIFE (3) // 最大ライフ数 #define LIFE_SIZE (30.0f) // ライフのサイズ //***************************************************************************** // 前方宣言 //***************************************************************************** class CScene2D; //***************************************************************************** // ライフクラス(派生クラス) //***************************************************************************** class CLifeUI : public CScene { public: CLifeUI(int nPriority); ~CLifeUI(); static HRESULT Load(void); static void Unload(void); static CLifeUI *Create(D3DXVECTOR3 pos, D3DXVECTOR2 size); HRESULT Init(D3DXVECTOR3 pos, D3DXVECTOR2 size); void Uninit(void); void Update(void); void Draw(void); int GetLife(void) { return m_nLife; } void SetLife(int nLife); private: static LPDIRECT3DTEXTURE9 m_pTexture; // テクスチャ情報のポインタ CScene2D *m_apScene2D[MAX_LIFE]; // 2Dポリゴン情報 int m_nLife; // ライフ数 }; #endif
ac4e1f77f322badc12b615d45b596b4b8cf785b9
8d79a78930d457a62f009ef4e3b085afcc7dacfc
/LeetCodeProblems/src/Challenges/2020/May/week3/FindAllAnagramsInString.cpp
296b832c5b40d614bd9aef882cb55d9e8c418999
[]
no_license
usseif97/Problem-Solving
cf877dfdce7cb96d6ef8423b93aebf69d36f1734
a0bf8ab46f419a7b9fcdb4413e494f2aa9e5c7d9
refs/heads/master
2022-12-18T18:05:55.197905
2020-10-02T12:53:46
2020-10-02T12:53:46
269,500,931
0
0
null
null
null
null
UTF-8
C++
false
false
1,398
cpp
FindAllAnagramsInString.cpp
#include "FindAllAnagramsInString.h" #include <bits/stdc++.h> #include <stdio.h> #include <stdlib.h> #include <string.h> using namespace std; FindAllAnagramsInString::FindAllAnagramsInString() { // TODO Auto-generated constructor stub } FindAllAnagramsInString::~FindAllAnagramsInString() { // TODO Auto-generated destructor stub } vector<int> FindAllAnagramsInString::findAnagrams(string s, string p) {// need to be ReVisited // if(letters[s.at(i) - 'a']++ >= 0) // means check letters[s.at(i) - 'a'] >= 0 then increase it int letters[26] = {0}; for(char c : p) { letters[c - 'a']++; } vector<int> result; int remaining = p.size(), j = 0; //sliding window technique. () for(int i = 0; i < s.size(); i++){ while(j < s.size() && j - i < p.size()){ if(letters[s.at(j) - 'a'] > 0){ remaining--; } letters[s.at(j) - 'a']--; j++; } if(remaining == 0){ result.push_back(i); } // Since letters[s.at(i) - 'a'] >= 0 then it's character from Anagrams and definitely // j pass through it before and remaining decrease by 1 So when i pass through it // must increase by 1 again if(letters[s.at(i) - 'a'] >= 0){ remaining++; } letters[s.at(i) - 'a']++; } return result; } // if(letters[s.at(j) - 'a']-- > 0) // First checks if letters[s.at(j) - 'a'] > 0, then decrements letters[s.at(j) - 'a']--
3e88e0562fa5cb4aa42e2232a8912c8914b6c151
bfb0c727497c12cd5fe18ae97857da9a218ab464
/Components/Tocs/Ui/ContainerBase.cpp
6f0c2d1dfe9ff89885fc8a87d049184ed72e1be8
[]
no_license
LordTocs/TocsEngine
67e8784f865ed2b41f45e28d482e0c0196f62252
218e731b53d436f9770457ddc2ea89e52f90658f
refs/heads/master
2021-05-28T06:13:03.337976
2014-04-14T02:04:08
2014-04-14T02:04:08
7,833,667
0
0
null
null
null
null
UTF-8
C++
false
false
1,194
cpp
ContainerBase.cpp
#include "ContainerBase.h" #include "LayoutAble.h" #include <algorithm> namespace Tocs { namespace Ui { void ContainerBase::Add(LayoutAble &thing) { if (thing.Parent_ != nullptr) thing.UnParent(); thing.Parent(*this); } void ContainerBase::InternalAdd(LayoutAble &thing) { OSAttach(thing); Items.push_back(&thing); LayoutContents(Position, RegionSize); } void ContainerBase::Remove(LayoutAble &thing) { if (thing.Parent_ != this) return; thing.UnParent(); } void ContainerBase::InternalRemove(LayoutAble &thing) { auto i = std::find(Items.begin(), Items.end(), &thing); if (i == Items.end()) return; OSDetach(thing); Items.erase(i); } void ContainerBase::LayoutContents(Point p, Size s) { if (p.X == Position.X && p.Y == Position.Y && s.X == RegionSize.X && s.Y == RegionSize.Y && LastCount == Items.size()) return; //No change Position = p; RegionSize = s; LastCount = Items.size(); DoLayout(p, s); EnforceMinimumSize(GetMinimumSize()); } class LayoutHolder { public: int Pos; unsigned int Width; DimensionType Type; bool Maxed; int Index; LayoutHolder(int index) : Index(index), Pos(0), Width(0), Type(DimensionType::Strength), Maxed(false) {} }; }}
25bed0c85d6d7cd749201e4b06e4f0e5a3615970
4749b64b52965942f785b4e592392d3ab4fa3cda
/chrome/browser/signin/easy_unlock_screenlock_state_handler.cc
f2eb9ee0f914108946c4365121831e723379abac
[ "BSD-3-Clause" ]
permissive
crosswalk-project/chromium-crosswalk-efl
763f6062679727802adeef009f2fe72905ad5622
ff1451d8c66df23cdce579e4c6f0065c6cae2729
refs/heads/efl/crosswalk-10/39.0.2171.19
2023-03-23T12:34:43.905665
2014-12-23T13:44:34
2014-12-23T13:44:34
27,142,234
2
8
null
2014-12-23T06:02:24
2014-11-25T19:27:37
C++
UTF-8
C++
false
false
8,001
cc
easy_unlock_screenlock_state_handler.cc
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/signin/easy_unlock_screenlock_state_handler.h" #include "base/bind.h" #include "base/prefs/pref_service.h" #include "base/strings/string16.h" #include "base/strings/utf_string_conversions.h" #include "chrome/browser/chromeos/chromeos_utils.h" #include "chrome/common/pref_names.h" #include "chrome/grit/generated_resources.h" #include "ui/base/l10n/l10n_util.h" namespace { size_t kIconSize = 27u; size_t kSpinnerResourceWidth = 1215u; size_t kSpinnerIntervalMs = 50u; std::string GetIconURLForState(EasyUnlockScreenlockStateHandler::State state) { switch (state) { case EasyUnlockScreenlockStateHandler::STATE_NO_BLUETOOTH: case EasyUnlockScreenlockStateHandler::STATE_NO_PHONE: case EasyUnlockScreenlockStateHandler::STATE_PHONE_NOT_AUTHENTICATED: case EasyUnlockScreenlockStateHandler::STATE_PHONE_LOCKED: case EasyUnlockScreenlockStateHandler::STATE_PHONE_NOT_NEARBY: case EasyUnlockScreenlockStateHandler::STATE_PHONE_UNLOCKABLE: case EasyUnlockScreenlockStateHandler::STATE_PHONE_UNSUPPORTED: return "chrome://theme/IDR_EASY_UNLOCK_LOCKED"; case EasyUnlockScreenlockStateHandler::STATE_BLUETOOTH_CONNECTING: return "chrome://theme/IDR_EASY_UNLOCK_SPINNER"; case EasyUnlockScreenlockStateHandler::STATE_AUTHENTICATED: return "chrome://theme/IDR_EASY_UNLOCK_UNLOCKED"; default: return ""; } } bool HasAnimation(EasyUnlockScreenlockStateHandler::State state) { return state == EasyUnlockScreenlockStateHandler::STATE_BLUETOOTH_CONNECTING; } bool HardlockOnClick(EasyUnlockScreenlockStateHandler::State state) { return state != EasyUnlockScreenlockStateHandler::STATE_INACTIVE; } size_t GetTooltipResourceId(EasyUnlockScreenlockStateHandler::State state) { switch (state) { case EasyUnlockScreenlockStateHandler::STATE_NO_BLUETOOTH: return IDS_EASY_UNLOCK_SCREENLOCK_TOOLTIP_NO_BLUETOOTH; case EasyUnlockScreenlockStateHandler::STATE_NO_PHONE: return IDS_EASY_UNLOCK_SCREENLOCK_TOOLTIP_NO_PHONE; case EasyUnlockScreenlockStateHandler::STATE_PHONE_NOT_AUTHENTICATED: return IDS_EASY_UNLOCK_SCREENLOCK_TOOLTIP_PHONE_NOT_AUTHENTICATED; case EasyUnlockScreenlockStateHandler::STATE_PHONE_LOCKED: return IDS_EASY_UNLOCK_SCREENLOCK_TOOLTIP_PHONE_LOCKED; case EasyUnlockScreenlockStateHandler::STATE_PHONE_UNLOCKABLE: return IDS_EASY_UNLOCK_SCREENLOCK_TOOLTIP_PHONE_UNLOCKABLE; case EasyUnlockScreenlockStateHandler::STATE_PHONE_NOT_NEARBY: return IDS_EASY_UNLOCK_SCREENLOCK_TOOLTIP_PHONE_NOT_NEARBY; case EasyUnlockScreenlockStateHandler::STATE_AUTHENTICATED: return IDS_EASY_UNLOCK_SCREENLOCK_TOOLTIP_HARDLOCK_INSTRUCTIONS; case EasyUnlockScreenlockStateHandler::STATE_PHONE_UNSUPPORTED: return IDS_EASY_UNLOCK_SCREENLOCK_TOOLTIP_UNSUPPORTED_ANDROID_VERSION; default: return 0; } } bool TooltipContainsDeviceType(EasyUnlockScreenlockStateHandler::State state) { return state == EasyUnlockScreenlockStateHandler::STATE_AUTHENTICATED || state == EasyUnlockScreenlockStateHandler::STATE_PHONE_UNLOCKABLE || state == EasyUnlockScreenlockStateHandler::STATE_NO_BLUETOOTH || state == EasyUnlockScreenlockStateHandler::STATE_PHONE_UNSUPPORTED; } } // namespace EasyUnlockScreenlockStateHandler::EasyUnlockScreenlockStateHandler( const std::string& user_email, PrefService* pref_service, ScreenlockBridge* screenlock_bridge) : state_(STATE_INACTIVE), user_email_(user_email), pref_service_(pref_service), screenlock_bridge_(screenlock_bridge) { DCHECK(screenlock_bridge_); screenlock_bridge_->AddObserver(this); } EasyUnlockScreenlockStateHandler::~EasyUnlockScreenlockStateHandler() { screenlock_bridge_->RemoveObserver(this); // Make sure the screenlock state set by this gets cleared. ChangeState(STATE_INACTIVE); } void EasyUnlockScreenlockStateHandler::ChangeState(State new_state) { if (state_ == new_state) return; state_ = new_state; // If lock screen is not active or it forces offline password, just cache the // current state. The screenlock state will get refreshed in |ScreenDidLock|. if (!screenlock_bridge_->IsLocked() || screenlock_bridge_->lock_handler()->GetAuthType(user_email_) == ScreenlockBridge::LockHandler::FORCE_OFFLINE_PASSWORD) { return; } UpdateScreenlockAuthType(); ScreenlockBridge::UserPodCustomIconOptions icon_options; std::string icon_url = GetIconURLForState(state_); if (icon_url.empty()) { screenlock_bridge_->lock_handler()->HideUserPodCustomIcon(user_email_); return; } icon_options.SetIconAsResourceURL(icon_url); bool trial_run = IsTrialRun(); UpdateTooltipOptions(trial_run, &icon_options); icon_options.SetSize(kIconSize, kIconSize); if (HasAnimation(state_)) icon_options.SetAnimation(kSpinnerResourceWidth, kSpinnerIntervalMs); // Hardlocking is disabled in trial run. if (!trial_run && HardlockOnClick(state_)) icon_options.SetHardlockOnClick(); if (trial_run && state_ == STATE_AUTHENTICATED) MarkTrialRunComplete(); screenlock_bridge_->lock_handler()->ShowUserPodCustomIcon(user_email_, icon_options); } void EasyUnlockScreenlockStateHandler::OnScreenDidLock() { State last_state = state_; // This should force updating screenlock state. state_ = STATE_INACTIVE; ChangeState(last_state); } void EasyUnlockScreenlockStateHandler::OnScreenDidUnlock() { } void EasyUnlockScreenlockStateHandler::OnFocusedUserChanged( const std::string& user_id) { } void EasyUnlockScreenlockStateHandler::UpdateTooltipOptions( bool trial_run, ScreenlockBridge::UserPodCustomIconOptions* icon_options) { size_t resource_id = 0; base::string16 device_name; if (trial_run && state_ == STATE_AUTHENTICATED) { resource_id = IDS_EASY_UNLOCK_SCREENLOCK_TOOLTIP_TUTORIAL; } else { resource_id = GetTooltipResourceId(state_); if (TooltipContainsDeviceType(state_)) device_name = GetDeviceName(); } if (!resource_id) return; base::string16 tooltip; if (device_name.empty()) { tooltip = l10n_util::GetStringUTF16(resource_id); } else { tooltip = l10n_util::GetStringFUTF16(resource_id, device_name); } if (tooltip.empty()) return; icon_options->SetTooltip( tooltip, state_ == STATE_AUTHENTICATED && trial_run /* autoshow tooltip */); } bool EasyUnlockScreenlockStateHandler::IsTrialRun() { return pref_service_ && pref_service_->GetBoolean(prefs::kEasyUnlockShowTutorial); } void EasyUnlockScreenlockStateHandler::MarkTrialRunComplete() { if (!pref_service_) return; pref_service_->SetBoolean(prefs::kEasyUnlockShowTutorial, false); } base::string16 EasyUnlockScreenlockStateHandler::GetDeviceName() { #if defined(OS_CHROMEOS) return chromeos::GetChromeDeviceType(); #else // TODO(tbarzic): Figure out the name for non Chrome OS case. return base::ASCIIToUTF16("Chrome"); #endif } void EasyUnlockScreenlockStateHandler::UpdateScreenlockAuthType() { if (screenlock_bridge_->lock_handler()->GetAuthType(user_email_) == ScreenlockBridge::LockHandler::FORCE_OFFLINE_PASSWORD) return; if (state_ == STATE_AUTHENTICATED) { screenlock_bridge_->lock_handler()->SetAuthType( user_email_, ScreenlockBridge::LockHandler::USER_CLICK, l10n_util::GetStringUTF16( IDS_EASY_UNLOCK_SCREENLOCK_USER_POD_AUTH_VALUE)); } else if (screenlock_bridge_->lock_handler()->GetAuthType(user_email_) != ScreenlockBridge::LockHandler::OFFLINE_PASSWORD) { screenlock_bridge_->lock_handler()->SetAuthType( user_email_, ScreenlockBridge::LockHandler::OFFLINE_PASSWORD, base::string16()); } }
428295d769b594c8f3b1923e831a3daeb655bcae
6b1a0116b6df527de47f113c31650b7c370efc7c
/main.cpp
36454d78bc938a3712580462f4bed706a237b862
[]
no_license
fannygt95/Multiprocessor-Programming
738c960cd5ac736b375dc55843bbcfbe779999d2
37f41c2444af14da036c22e3dd5716a430192f04
refs/heads/master
2020-04-18T03:53:30.187478
2019-05-03T17:14:50
2019-05-03T17:14:50
167,217,630
2
1
null
null
null
null
UTF-8
C++
false
false
13,027
cpp
main.cpp
#include "lodepng.h" #include <limits.h> #include <stdio.h> #include <stdlib.h> #include <iostream> #include <sstream> #include <vector> #include <chrono> #include <cmath> #include <fstream> #include <string> using namespace std; unsigned width, height; unsigned average = 0; int const disparity = 65; const int windowSize = 9; double correlation = 0; unsigned char biggestCorrelation; vector<vector<unsigned char>> reduceim0; vector<vector<unsigned char>> reduceim1; // MAPAS DE DISPARIDAD // vector<vector<unsigned char>> IzqDer; vector<vector<unsigned char>> DerIzq; // MAPA FINAL// vector<vector<unsigned char>> FinalMap; // MAPA FINAL EN UN VECTOR vector<unsigned char>FinalVector; void getTheImagenInAVector(const char* filename, vector<unsigned char> &image); void ReduceGrayMatrix(vector<unsigned char> imagen, vector<vector<unsigned char>>&reducematrix); void ZNCC(vector<vector<unsigned char>> im0, vector<vector<unsigned char>>im1, vector<vector<unsigned char>>&DisMap, bool time); unsigned char operations(int j, int i, double vector0[windowSize*windowSize], vector<vector<unsigned char>> im1, int average0, double desTipica0, bool time); void CalculateLastMap(vector<vector<unsigned char>>firstMap, vector<vector<unsigned char>>secondMap, vector<vector<unsigned char>>&lastMap); void SustituirCeros(vector<vector<unsigned char>>&lastMap); void MapToVector(vector<vector<unsigned char>>Map, vector<unsigned char>&vector); void crearImagen(vector<vector<unsigned char>> imagen, vector<vector<unsigned char>>&imagennueva); int main(int argc, char *argv[]) { vector<unsigned char> image0; vector<unsigned char> image1; vector<unsigned char> aux; const char* filename0 = argc > 1 ? argv[1] : "im0.png"; const char* filename1 = argc > 1 ? argv[1] : "im1.png"; getTheImagenInAVector(filename0, image0); getTheImagenInAVector(filename1, image1); ReduceGrayMatrix(image0, reduceim0); ReduceGrayMatrix(image1, reduceim1); width = width / 4; height = height / 4; image0.clear(); image0.shrink_to_fit(); image1.clear(); image1.shrink_to_fit(); vector<vector<unsigned char>> ZNCCIzqDer; vector<vector<unsigned char>> ZNCCDerIzq; vector<unsigned char> VectorZNCCDerIzq; vector<unsigned char> VectorZNCCIzqDer; bool FirstZncc = true; /* ZNCC(reduceim0, reduceim1, IzqDer, FirstZncc); crearImagen(IzqDer, ZNCCIzqDer); MapToVector(ZNCCIzqDer, VectorZNCCIzqDer); lodepng::encode("ZNCCIzqDer.png", VectorZNCCIzqDer, width, height, LCT_GREY, 8); */ FirstZncc = false; ZNCC(reduceim1, reduceim0, DerIzq, FirstZncc); crearImagen(DerIzq, ZNCCDerIzq); MapToVector(ZNCCDerIzq, VectorZNCCDerIzq); lodepng::encode("ZNCCFalseim1ima0.png", VectorZNCCDerIzq, width, height, LCT_GREY, 8); reduceim0.clear(); reduceim0.shrink_to_fit(); reduceim1.clear(); reduceim1.shrink_to_fit(); CalculateLastMap(DerIzq, IzqDer, FinalMap); SustituirCeros(FinalMap); MapToVector(FinalMap, FinalVector); //IMPRIMIR FOTOGRAFIA lodepng::encode("DisparityMap.png", FinalVector, width, height, LCT_GREY, 8); } void getTheImagenInAVector(const char* filename, vector<unsigned char> &image) { unsigned error0 = lodepng::decode(image, width, height, filename); //if there's an error, display it if (error0) std::cout << "decoder error " << error0 << ": " << lodepng_error_text(error0) << std::endl; //the pixels are now in the vector "image", 4 bytes per pixel, ordered RGBARGBA..., use it as texture, draw it, ... } void ReduceGrayMatrix(vector<unsigned char> imagen, vector<vector<unsigned char>>&reduceimagen) { vector <unsigned char> auxvector; unsigned char aux; vector<vector<unsigned char>> auxImagen; int R = 0, G = 1, B = 2; for (int i = 0; i < height; i++) { for (int x = 0; x < width; x++) { aux = imagen[R] * 0.2126 + imagen[G] * 0.7152 + imagen[B] * 0.0722; if (x + i * width < imagen.size()) { auxvector.push_back(aux); } R = R + 4; G = G + 4; B = B + 4; } auxImagen.push_back(auxvector); auxvector.erase(auxvector.begin(), auxvector.end()); } for (int i = 0; i < height; i += 4) { for (int x = 0; x < width; x += 4) { auxvector.push_back(auxImagen[i][x]); } reduceimagen.push_back(auxvector); auxvector.erase(auxvector.begin(), auxvector.end()); } } void ZNCC(vector<vector<unsigned char>> im0, vector<vector<unsigned char>> im1, vector<vector<unsigned char>>&DisMap, bool time) { int count0 = 0; //Contador para la suma de los datos de las ventanas double vector0[windowSize * windowSize]; //Guarda los datos de la ventana de la primera imagen double vector1[windowSize * windowSize]; //Guarda los datos de la ventana de la segunda imagen double average0; //Calcular medias double desTipica0 = 0, desTipica1 = 0; //Calcular desviaciones típicas double covarianza = 0; // Calcular covarianza unsigned char aux; vector<unsigned char> vectorAux; if (time == true) { for (int i = windowSize / 2; i < height - windowSize / 2; i++) { //RECORRER IMAGEN for (int j = windowSize / 2; j < width - windowSize / 2; j++) { int m = 0; count0 = 0; average0 = 0; for (int y = i - windowSize / 2; y < i + 1 + windowSize / 2; y++) {// RECORRER VENTANA IMAGEN 0 for (int x = j - windowSize / 2; x < j + 1 + windowSize / 2; x++) { count0 = count0 + im0[y][x]; //Sumatorio datos ventana imagen 0 vector0[m] = im0[y][x]; //Guardar datos m++; } } average0 = count0 / (pow(windowSize, 2)); //Media ventana imagen0 int aux0 = 0; desTipica0 = 0; for (m = 0; m < sizeof(vector0) / sizeof(*vector0); m++) {//RECORRER OTRA VEZ VENTANA IMAGEN 0, esta vez usamos el vector aux0 = vector0[m] - average0; desTipica0 = desTipica0 + (pow(aux0, 2)); } desTipica0 = sqrt(desTipica0 / (pow(windowSize, 2))); aux = operations(i, j, vector0, im1, average0, desTipica0, time); vectorAux.push_back(aux); } DisMap.push_back(vectorAux); vectorAux.erase(vectorAux.begin(), vectorAux.end()); } } else { for (int i = windowSize / 2; i < height - windowSize / 2; i++) { //RECORRER IMAGEN for (int j = windowSize / 2; j < width - windowSize / 2; j++) { int m = 0; count0 = 0; average0 = 0; for (int y = i - windowSize / 2; y < i + 1 + windowSize / 2; y++) {// RECORRER VENTANA IMAGEN 0 for (int x = j - windowSize / 2; x < j + 1 + windowSize / 2; x++) { count0 = count0 + im0[y][x]; //Sumatorio datos ventana imagen 0 vector0[m] = im0[y][x]; //Guardar datos m++; } } average0 = count0 / (pow(windowSize, 2)); //Media ventana imagen0 int aux0 = 0; desTipica0 = 0; for (m = 0; m < sizeof(vector0) / sizeof(*vector0); m++) {//RECORRER OTRA VEZ VENTANA IMAGEN 0, esta vez usamos el vector aux0 = vector0[m] - average0; desTipica0 = desTipica0 + (pow(aux0, 2)); } desTipica0 = sqrt(desTipica0 / (pow(windowSize, 2))); aux = operations(i, j, vector0, im1, average0, desTipica0, time); vectorAux.push_back(aux); } DisMap.push_back(vectorAux); vectorAux.erase(vectorAux.begin(), vectorAux.end()); } } } unsigned char operations(int hei, int wid, double vector0[windowSize*windowSize], vector<vector<unsigned char>> im1, int average0, double desTipica0, bool time) { int vector1[windowSize * windowSize]; int h = wid; int g = hei; int countDisparity = 0; unsigned char ValorMatriz = 0; double biggestCorrelation = -1000; if (time == true) { while (h < width - windowSize / 2 && countDisparity < disparity) { int count1 = 0; int n = 0; for (int win_y = g - (windowSize / 2); win_y < g + 1 + (windowSize / 2); win_y++) { //CONTADOR DE LOS DATOS VENTANA IMAGEN 1 for (int win_x = h - (windowSize / 2); win_x < h + 1 + (windowSize / 2); win_x++) { count1 = count1 + im1[win_y][win_x]; vector1[n] = im1[win_y][win_x]; //CREAR VECTOR DE DATOS VENTANA IMAGEN 1 n++; } } double average1 = 0; average1 = count1 / (pow(windowSize, 2)); int aux1 = 0; double desTipica1 = 0; for (int n = 0; n < sizeof(vector1) / sizeof(*vector1); n++) {//RECORRER OTRA VEZ VENTANA IMAGEN 1, esta vez usamos el vector aux1 = vector1[n] - average1; desTipica1 = desTipica1 + (pow(aux1, 2)); } desTipica1 = sqrt(desTipica1 / (pow(windowSize, 2))); double auxcovarianza = 0; double covarianza = 0; for (int n = 0; n < sizeof(vector1) / sizeof(*vector1); n++) { //CALCULAR COVARIANZA CON LOS DATOS GUARDADOS EN LOS VECTORES auxcovarianza = (vector0[n] - average0) * (vector1[n] - average1); covarianza = covarianza + auxcovarianza; } covarianza = covarianza / (pow(windowSize, 2)); double correlation = covarianza / (desTipica0 * desTipica1); // CORRELACIÓN // WE ARE GOING TO COMPARING ONE WINDOW IN THE IMG0 WITH 65 WINDOWS IN THE IMG1 AND WE TAKE THE BIGGEST ONE // WHICH IT IS THE BIGGEST DISPARITY if (correlation > biggestCorrelation) { biggestCorrelation = correlation; ValorMatriz = countDisparity; } countDisparity++; h++; } } else { countDisparity = 65; while (h > (windowSize / 2) - 1 && 0 < countDisparity) { int count1 = 0; int n = 0; for (int win_y = g - (windowSize / 2); win_y < g + 1 + (windowSize / 2); win_y++) { //CONTADOR DE LOS DATOS VENTANA IMAGEN 1 for (int win_x = h - (windowSize / 2); win_x < h + 1 + (windowSize / 2); win_x++) { count1 = count1 + im1[win_y][win_x]; vector1[n] = im1[win_y][win_x]; //CREAR VECTOR DE DATOS VENTANA IMAGEN 1 n++; } } double average1 = 0; average1 = count1 / (pow(windowSize, 2)); int aux1 = 0; double desTipica1 = 0; for (int n = 0; n < sizeof(vector1) / sizeof(*vector1); n++) {//RECORRER OTRA VEZ VENTANA IMAGEN 1, esta vez usamos el vector aux1 = vector1[n] - average1; desTipica1 = desTipica1 + (pow(aux1, 2)); } desTipica1 = sqrt(desTipica1 / (pow(windowSize, 2))); double auxcovarianza = 0; double covarianza = 0; for (int n = 0; n < sizeof(vector1) / sizeof(*vector1); n++) { //CALCULAR COVARIANZA CON LOS DATOS GUARDADOS EN LOS VECTORES auxcovarianza = (vector0[n] - average0) * (vector1[n] - average1); covarianza = covarianza + auxcovarianza; } covarianza = covarianza / (pow(windowSize, 2)); double correlation = covarianza / (desTipica0 * desTipica1); // CORRELACIÓN // WE ARE GOING TO COMPARING ONE WINDOW IN THE IMG0 WITH 65 WINDOWS IN THE IMG1 AND WE TAKE THE BIGGEST ONE // WHICH IT IS THE BIGGEST DISPARITY if (correlation > biggestCorrelation){ biggestCorrelation = correlation; ValorMatriz = disparity - countDisparity; } countDisparity--; h--; } } return ValorMatriz; } void CalculateLastMap(vector<vector<unsigned char>> firstMap, vector<vector<unsigned char>> secondMap, vector<vector<unsigned char>>&lastMap) { vector <unsigned char> aux; int resta = 0; int h = 0; for (int i = 0; i < height ; i++) { int p = 0; for (int j = 0; j < width; j++) { if (i > 3 && i < 500 && 3 < j && j < 731) { resta = firstMap[h][p] - secondMap[h][p]; resta = abs(resta); if (resta > 8) { aux.push_back(0); } else { aux.push_back(resta); } p++; } else { aux.push_back(0); } } if(i > 3){ h++; } lastMap.push_back(aux); aux.erase(aux.begin(), aux.end()); } } void SustituirCeros(vector<vector<unsigned char>>&lastMap) { int aux = 0; for (int i = windowSize / 2; i < height + 1 - windowSize / 2; i++) { for (int j = windowSize / 2; j < width + 1 - windowSize / 2; j++) { if (lastMap[i][j] == 0) { aux = lastMap[i][j + 1] + lastMap[i][j - 1] + lastMap[i + 1][j] + lastMap[i - 1][j] + lastMap[i - 1][j - 1] + lastMap[i - 1][j + 1] + lastMap[i + 1][j - 1] + lastMap[i + 1][j + 1]; aux = aux / 8; lastMap[i][j] = aux; //cout << lastMap[j][i] << " "; } } } } void MapToVector(vector<vector<unsigned char>> Map, vector<unsigned char> &vector) { //int n = 0; //char *vector = (char*)malloc(sizeof (char)); for (int i = 0; i < height; i++) { for (int j = 0; j < width; j++) { vector.push_back(Map[i][j]); //cout << vector[n] << " "; //n++; } } } void crearImagen(vector<vector<unsigned char>> imagen, vector<vector<unsigned char>>&imagennueva) { vector <unsigned char> aux; int h = 0; for (int i = 0; i < height; i++){ int p = 0; for (int x = 0; x < width; x++) { if (i > 3 && i < 500 && 3 < x && x < 731) { aux.push_back(imagen[h][p]); p++; } else { aux.push_back(0); } } if (i > 3) { h++; } imagennueva.push_back(aux); aux.erase(aux.begin(), aux.end()); } }
09a0dfb66fd0d447f1ad53388786ca8211b83e5b
e6ae6070d3053ca1e4ff958c719a8cf5dfcd6b9b
/treap_spoj.cpp
6b8e7efd6108d2331f081d7ee5d742092fa718c8
[]
no_license
Arti14/Competitive-Programming
31d246d34581599219ffb7e23a3372f02fc6dfa6
de42977b6cce39bb480d3cf90c1781d806be3b56
refs/heads/master
2021-01-25T07:34:29.240567
2015-05-08T07:07:10
2015-05-08T07:07:10
35,263,950
0
0
null
null
null
null
UTF-8
C++
false
false
2,186
cpp
treap_spoj.cpp
#include <iostream> #include <string> #include <cstdio> #include <cstdlib> using namespace std; struct treap{ string key ; int weight; treap *L ; treap *R; }; void rotate_C( treap **node) { treap *tmp = (*node)->L; (*node)->L=tmp->R; tmp->R=*node; *node = tmp; } void rotate_A( treap **node) { treap *tmp = (*node)->R; (*node)->R=tmp->L; tmp->L=*node; *node = tmp; } void balance(treap **node ) { if( (*node)->L != NULL && (*node)->L->weight > (*node)->weight ) { rotate_C( node ); } else if ( (*node)->R != NULL && (*node)->R->weight > (*node)->weight) { rotate_A( node ); } } void insert( struct treap **node, string k, int w) { if(*node == NULL) { *node = new treap; (*node)->key=k; (*node)->weight=w; (*node)->L=(*node)->R= NULL; return; } else if (k <= (*node)->key) { insert( &( (*node)->L ),k,w); } else { insert( &( (*node)->R ), k , w); } balance(node); } void print_treap( treap *node) { if(node == NULL ) return; cout<<"("; print_treap(node->L); cout<<node->key<<"/"<< node->weight; print_treap(node->R); cout<<")"; } int main() { char str[50]; int T; scanf("%d",&T); while(T>0) { treap *root =NULL; for(int i=0;i<T;i++) { string k; char tmp[50]; int w; scanf("%s",str); int j=0; while(str[j]!='/') { k=k+str[j++]; } j++; int l=0; while(str[j]!='\0') { tmp[l++]=str[j++]; } tmp[l]='\0'; w=atoi(tmp); insert(&root,k,w); } print_treap(root); cout<<endl; scanf("%d",&T); } }
c432d579c47abbcf78763d561a663119d32325c0
aed2ad37d2896a0a8cbc008fc225d23b2383d481
/ModelFitting/EnergyFunctions.cpp
5e940751f1e5832d8ab608a611ed9b4939854ff6
[]
no_license
qchen2017/Thin_Vessel_Segmentation
67b8b67f13010f8b2b3a10b4eee4e8e69b1d7fb7
e1e4c1d20acd6fddf2b5ef55abdc6c4a8d5ea71d
refs/heads/master
2021-08-19T09:31:35.847731
2017-11-25T15:52:19
2017-11-25T15:52:19
null
0
0
null
null
null
null
UTF-8
C++
false
false
5,185
cpp
EnergyFunctions.cpp
#include <opencv2/core/core.hpp> #include "EnergyFunctions.h" #include "Line3D.h" #include "Neighbour26.h" #include "Data3D.h" #include "Timer.h" #include "../SparseMatrixCV/SparseMatrixCV.h" #include <vector> #include <omp.h> #if _MSC_VER && !__INTEL_COMPILER #ifdef _DEBUG #pragma comment(lib,"../x64/Debug/SparseMatrixCV.lib") #pragma comment(lib,"../x64/Debug/SparseMatrix.lib") #else #pragma comment(lib,"../x64/Release/SparseMatrixCV.lib") #pragma comment(lib,"../x64/Release/SparseMatrix.lib") #endif #endif using namespace std; using namespace cv; static const double epsilon_double = 1e-50; double compute_datacost_for_one( const Line3D* line_i, const Vec3d& pi ) { const Vec3d proj_point = line_i->projection( pi ); const Vec3d dir = proj_point - pi; const double dist2 = dir.dot(dir); const double sigma2 = line_i->getSigma() * line_i->getSigma(); return DATA_COST2 * dist2 / sigma2; } void smoothcost_func_quadratic( const Line3D* line_i, const Line3D* line_j, const Vec3d& pi_tilde, const Vec3d& pj_tilde, double& smooth_cost_i, double& smooth_cost_j, void* func_data ) { // single projection const Vec3d pi = line_i->projection( pi_tilde ); const Vec3d pj = line_j->projection( pj_tilde ); // double projection const Vec3d pi_prime = line_j->projection( pi ); const Vec3d pj_prime = line_i->projection( pj ); // distance vector const Vec3d pi_pj = pi - pj; const Vec3d pi_pi_prime = pi - pi_prime; const Vec3d pj_pj_prime = pj - pj_prime; // distances const double dist_pi_pi_prime2 = pi_pi_prime.dot(pi_pi_prime); const double dist_pj_pj_prime2 = pj_pj_prime.dot(pj_pj_prime); const double dist_pi_pj2 = max( pi_pj.dot(pi_pj), epsilon_double ); smooth_cost_i = PAIRWISE_SMOOTH2 * dist_pi_pi_prime2 / dist_pi_pj2; smooth_cost_j = PAIRWISE_SMOOTH2 * dist_pj_pj_prime2 / dist_pi_pj2; } void smoothcost_func_linear( const Line3D* line_i, const Line3D* line_j, const cv::Vec3d& pi_tilde, const cv::Vec3d& pj_tilde, double& smooth_cost_i, double& smooth_cost_j, void* func_data ) { // single projection const Vec3d pi = line_i->projection( pi_tilde ); const Vec3d pj = line_j->projection( pj_tilde ); // double projection const Vec3d pi_prime = line_j->projection( pi ); const Vec3d pj_prime = line_i->projection( pj ); // distance vector const Vec3d pi_pj = pi - pj; const Vec3d pi_pi_prime = pi - pi_prime; const Vec3d pj_pj_prime = pj - pj_prime; // distances const double dist_pi_pi_prime2 = max( pi_pi_prime.dot(pi_pi_prime), epsilon_double ); const double dist_pj_pj_prime2 = max( pj_pj_prime.dot(pj_pj_prime), epsilon_double ); const double dist_pi_pj2 = max( pi_pj.dot(pi_pj), epsilon_double ); const double dist_pi_pi_prime = sqrt( dist_pi_pi_prime2 ); const double dist_pj_pj_prime = sqrt( dist_pj_pj_prime2 ); const double dist_pi_pj = sqrt( dist_pi_pj2 ); smooth_cost_i = PAIRWISE_SMOOTH2 * dist_pi_pi_prime / dist_pi_pj; smooth_cost_j = PAIRWISE_SMOOTH2 * dist_pj_pj_prime / dist_pi_pj; if( func_data ) { static const double eps = 0.5e-2; std::pair<double,double>& coefficiency = *((std::pair<double,double>*)func_data); coefficiency.first = ( dist_pi_pj + eps) / ( dist_pi_pi_prime + eps); coefficiency.second = ( dist_pi_pj + eps) / ( dist_pj_pj_prime + eps); } } // compute total energy: smoothcost + datacost double compute_energy( const std::vector<cv::Vec3i>& dataPoints, const std::vector<int>& labelings, const std::vector<Line3D*>& lines, const Data3D<int>& indeces, SmoothCostFunc using_smoothcost_func ) { smart_assert( using_smoothcost_func, "Please define what smooth cost energy function you want to use. " ); double energy = 0.0; // computer data cost for( int site = 0; site < (int) dataPoints.size(); site++ ) { const int& label = labelings[site]; energy += compute_datacost_for_one( lines[label], dataPoints[site] ); } // compute smooth cost for( unsigned site = 0; site < dataPoints.size(); site++ ) // For each data point { for( int neibourIndex=0; neibourIndex<13; neibourIndex++ ) { // neighbour position Vec3i neig; Neighbour26::getNeigbour( neibourIndex, dataPoints[site], neig ); if( !indeces.isValid(neig) ) continue; // not a valid position, otherwise const int site2 = indeces.at(neig); if( site2==-1 ) continue ; // not a neighbour, other wise, found a neighbour const int l1 = labelings[site]; const int l2 = labelings[site2]; if( l1==l2 ) continue; double energy_smoothness_i = 0, energy_smoothness_j = 0; using_smoothcost_func( lines[l1], lines[l2], dataPoints[site], dataPoints[site2], energy_smoothness_i, energy_smoothness_j, NULL ); energy += energy_smoothness_i + energy_smoothness_j; } } return energy; }
04d42c8607160ed0a6032f62d8d5d85028fbd2f9
a92b18defb50c5d1118a11bc364f17b148312028
/src/prod/src/api/wrappers/ComInfrastructureServiceAgent.cpp
c3873745f375a97f91a40492a9dc52e2d8715e90
[ "MIT" ]
permissive
KDSBest/service-fabric
34694e150fde662286e25f048fb763c97606382e
fe61c45b15a30fb089ad891c68c893b3a976e404
refs/heads/master
2023-01-28T23:19:25.040275
2020-11-30T11:11:58
2020-11-30T11:11:58
301,365,601
1
0
MIT
2020-11-30T11:11:59
2020-10-05T10:05:53
null
UTF-8
C++
false
false
14,632
cpp
ComInfrastructureServiceAgent.cpp
// ------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License (MIT). See License.txt in the repo root for license information. // ------------------------------------------------------------ #include "stdafx.h" using namespace std; using namespace Common; using namespace Api; using namespace ServiceModel; // ******************************************************************************************************************** // ComAsyncOperationContext Classes // class ComInfrastructureServiceAgent::ComStartInfrastructureTaskAsyncOperation : public ComAsyncOperationContext { DENY_COPY(ComStartInfrastructureTaskAsyncOperation); public: ComStartInfrastructureTaskAsyncOperation( __in IInfrastructureServiceAgent & impl, FABRIC_INFRASTRUCTURE_TASK_DESCRIPTION * taskDescription) : ComAsyncOperationContext() , impl_(impl) , taskDescription_(taskDescription) , timeout_(TimeSpan::Zero) { } virtual ~ComStartInfrastructureTaskAsyncOperation() { } HRESULT Initialize( __in ComponentRootSPtr const & rootSPtr, __in DWORD timeoutMilliseconds, __in IFabricAsyncOperationCallback * callback) { HRESULT hr = this->ComAsyncOperationContext::Initialize(rootSPtr, callback); if (SUCCEEDED(hr)) { timeout_ = TimeSpan::FromMilliseconds(timeoutMilliseconds); } return hr; } static HRESULT End(__in IFabricAsyncOperationContext * context) { if (context == NULL) { return E_POINTER; } ComPointer<ComAsyncOperationContext> thisCPtr(context, IID_IFabricAsyncOperationContext); return thisCPtr->End(); } protected: virtual void OnStart(AsyncOperationSPtr const & proxySPtr) { auto operation = impl_.BeginStartInfrastructureTask( taskDescription_, timeout_, [this](AsyncOperationSPtr const & operation) { this->OnStartInfrastructureTaskComplete(operation, false); }, proxySPtr); this->OnStartInfrastructureTaskComplete(operation, true); } private: void OnStartInfrastructureTaskComplete(AsyncOperationSPtr const & operation, bool expectedCompletedSynchronously) { if (operation->CompletedSynchronously != expectedCompletedSynchronously) { return; } ErrorCode error = impl_.EndStartInfrastructureTask(operation); this->TryComplete(operation->Parent, error.ToHResult()); } IInfrastructureServiceAgent & impl_; FABRIC_INFRASTRUCTURE_TASK_DESCRIPTION * taskDescription_; TimeSpan timeout_; }; class ComInfrastructureServiceAgent::ComFinishInfrastructureTaskAsyncOperation : public ComAsyncOperationContext { DENY_COPY(ComFinishInfrastructureTaskAsyncOperation); public: ComFinishInfrastructureTaskAsyncOperation( __in IInfrastructureServiceAgent & impl, wstring const & taskId, uint64 instanceId) : ComAsyncOperationContext() , impl_(impl) , taskId_(taskId) , instanceId_(instanceId) , timeout_(TimeSpan::Zero) { } virtual ~ComFinishInfrastructureTaskAsyncOperation() { } HRESULT Initialize( __in ComponentRootSPtr const & rootSPtr, __in DWORD timeoutMilliseconds, __in IFabricAsyncOperationCallback * callback) { HRESULT hr = this->ComAsyncOperationContext::Initialize(rootSPtr, callback); if (SUCCEEDED(hr)) { timeout_ = TimeSpan::FromMilliseconds(timeoutMilliseconds); } return hr; } static HRESULT End(__in IFabricAsyncOperationContext * context) { if (context == NULL) { return E_POINTER; } ComPointer<ComAsyncOperationContext> thisCPtr(context, IID_IFabricAsyncOperationContext); return thisCPtr->End(); } protected: virtual void OnStart(AsyncOperationSPtr const & proxySPtr) { auto operation = impl_.BeginFinishInfrastructureTask( taskId_, instanceId_, timeout_, [this](AsyncOperationSPtr const & operation) { this->OnFinishInfrastructureTaskComplete(operation, false); }, proxySPtr); this->OnFinishInfrastructureTaskComplete(operation, true); } private: void OnFinishInfrastructureTaskComplete(AsyncOperationSPtr const & operation, bool expectedCompletedSynchronously) { if (operation->CompletedSynchronously != expectedCompletedSynchronously) { return; } ErrorCode error = impl_.EndFinishInfrastructureTask(operation); this->TryComplete(operation->Parent, error.ToHResult()); } IInfrastructureServiceAgent & impl_; wstring taskId_; uint64 instanceId_; TimeSpan timeout_; }; // {34a16309-07f5-49c6-bac9-626d181a2e52} static const GUID CLSID_ComQueryInfrastructureTaskAsyncOperation = { 0x34a16309, 0x07f5, 0x49c6, { 0xba, 0xc9, 0x62, 0x6d, 0x18, 0x1a, 0x2e, 0x52 } }; class ComInfrastructureServiceAgent::ComQueryInfrastructureTaskAsyncOperation : public ComAsyncOperationContext { DENY_COPY(ComQueryInfrastructureTaskAsyncOperation); COM_INTERFACE_AND_DELEGATE_LIST( ComQueryInfrastructureTaskAsyncOperation, CLSID_ComQueryInfrastructureTaskAsyncOperation, ComQueryInfrastructureTaskAsyncOperation, ComAsyncOperationContext) public: ComQueryInfrastructureTaskAsyncOperation( __in IInfrastructureServiceAgent & impl) : ComAsyncOperationContext() , impl_(impl) , timeout_(TimeSpan::Zero) { } virtual ~ComQueryInfrastructureTaskAsyncOperation() { } HRESULT Initialize( __in ComponentRootSPtr const & rootSPtr, __in DWORD timeoutMilliseconds, __in IFabricAsyncOperationCallback * callback) { HRESULT hr = this->ComAsyncOperationContext::Initialize(rootSPtr, callback); if (SUCCEEDED(hr)) { timeout_ = TimeSpan::FromMilliseconds(timeoutMilliseconds); } return hr; } static HRESULT End(__in IFabricAsyncOperationContext * context, __out IFabricInfrastructureTaskQueryResult ** result) { if ((context == NULL) || (result == NULL)) { return E_POINTER; } ComPointer<ComQueryInfrastructureTaskAsyncOperation> thisCPtr(context, CLSID_ComQueryInfrastructureTaskAsyncOperation); auto hr = thisCPtr->Result; if (SUCCEEDED(hr)) { vector<InfrastructureTaskQueryResult> resultList; auto error = thisCPtr->nativeResult_.MoveList(resultList); if (error.IsSuccess()) { ComPointer<IFabricInfrastructureTaskQueryResult> cPtr = make_com<ComQueryResult, IFabricInfrastructureTaskQueryResult>(move(resultList)); hr = cPtr->QueryInterface(IID_IFabricInfrastructureTaskQueryResult, reinterpret_cast<void**>(result)); } else { hr = error.ToHResult(); } } return hr; } protected: virtual void OnStart(AsyncOperationSPtr const & proxySPtr) { auto operation = impl_.BeginQueryInfrastructureTask( timeout_, [this](AsyncOperationSPtr const & operation) { this->OnQueryInfrastructureTaskComplete(operation, false); }, proxySPtr); this->OnQueryInfrastructureTaskComplete(operation, true); } private: void OnQueryInfrastructureTaskComplete(AsyncOperationSPtr const & operation, bool expectedCompletedSynchronously) { if (operation->CompletedSynchronously != expectedCompletedSynchronously) { return; } auto error = impl_.EndQueryInfrastructureTask(operation, nativeResult_); this->TryComplete(operation->Parent, error.ToHResult()); } IInfrastructureServiceAgent & impl_; QueryResult nativeResult_; TimeSpan timeout_; }; class ComInfrastructureServiceAgent::ComQueryResult : public IFabricInfrastructureTaskQueryResult , private Common::ComUnknownBase { DENY_COPY_ASSIGNMENT(ComQueryResult) BEGIN_COM_INTERFACE_LIST(ComQueryResult) COM_INTERFACE_ITEM(IID_IUnknown,IFabricInfrastructureTaskQueryResult) COM_INTERFACE_ITEM(IID_IFabricInfrastructureTaskQueryResult,IFabricInfrastructureTaskQueryResult) END_COM_INTERFACE_LIST() public: explicit ComQueryResult(vector<InfrastructureTaskQueryResult> && resultList) { queryResult_ = heap_.AddItem<FABRIC_INFRASTRUCTURE_TASK_QUERY_RESULT_LIST>(); auto array = heap_.AddArray<FABRIC_INFRASTRUCTURE_TASK_QUERY_RESULT_ITEM>(resultList.size()); queryResult_->Count = static_cast<ULONG>(resultList.size()); queryResult_->Items = array.GetRawArray(); for (size_t ix = 0; ix < resultList.size(); ++ix) { FABRIC_INFRASTRUCTURE_TASK_QUERY_RESULT_ITEM * arrayItem = &array[ix]; InfrastructureTaskQueryResult const & listItem = resultList[ix]; arrayItem->Description = heap_.AddItem<FABRIC_INFRASTRUCTURE_TASK_DESCRIPTION>().GetRawPointer(); listItem.Description.ToPublicApi(heap_, *arrayItem->Description); arrayItem->State = Management::ClusterManager::InfrastructureTaskState::ToPublicApi(listItem.State); } } const FABRIC_INFRASTRUCTURE_TASK_QUERY_RESULT_LIST * STDMETHODCALLTYPE get_Result(void) { return queryResult_.GetRawPointer(); } private: Common::ScopedHeap heap_; Common::ReferencePointer<FABRIC_INFRASTRUCTURE_TASK_QUERY_RESULT_LIST> queryResult_; }; // ******************************************************************************************************************** // ComInfrastructureServiceAgent::ComInfrastructureServiceAgent Implementation // ComInfrastructureServiceAgent::ComInfrastructureServiceAgent(IInfrastructureServiceAgentPtr const & impl) : IFabricInfrastructureServiceAgent() , ComUnknownBase() , impl_(impl) { } ComInfrastructureServiceAgent::~ComInfrastructureServiceAgent() { // Break lifetime cycle between ISAgent and ServiceRoutingAgentProxy impl_->Release(); } HRESULT STDMETHODCALLTYPE ComInfrastructureServiceAgent::RegisterInfrastructureServiceFactory( IFabricStatefulServiceFactory * factory) { return ComUtility::OnPublicApiReturn(impl_->RegisterInfrastructureServiceFactory(factory).ToHResult()); } HRESULT STDMETHODCALLTYPE ComInfrastructureServiceAgent::RegisterInfrastructureService( FABRIC_PARTITION_ID partitionId, FABRIC_REPLICA_ID replicaId, IFabricInfrastructureService * comInterface, IFabricStringResult ** serviceAddress) { if (serviceAddress == NULL) { return ComUtility::OnPublicApiReturn(E_POINTER); } wstring serviceAddressResult; impl_->RegisterInfrastructureService( partitionId, replicaId, WrapperFactory::create_rooted_com_proxy(comInterface), serviceAddressResult); auto result = make_com<ComStringResult, IFabricStringResult>(serviceAddressResult); *serviceAddress = result.DetachNoRelease(); return ComUtility::OnPublicApiReturn(S_OK); } HRESULT STDMETHODCALLTYPE ComInfrastructureServiceAgent::UnregisterInfrastructureService( FABRIC_PARTITION_ID partitionId, FABRIC_REPLICA_ID replicaId) { impl_->UnregisterInfrastructureService(partitionId, replicaId); return ComUtility::OnPublicApiReturn(S_OK); } HRESULT STDMETHODCALLTYPE ComInfrastructureServiceAgent::BeginStartInfrastructureTask( /* [in] */ FABRIC_INFRASTRUCTURE_TASK_DESCRIPTION * taskDescription, /* [in] */ DWORD timeoutMilliseconds, /* [in] */ IFabricAsyncOperationCallback * callback, /* [out, retval] */ IFabricAsyncOperationContext ** context) { auto operation = make_com<ComStartInfrastructureTaskAsyncOperation>(*impl_.get(), taskDescription); HRESULT hr = operation->Initialize( impl_.get_Root(), timeoutMilliseconds, callback); if (FAILED(hr)) { return ComUtility::OnPublicApiReturn(hr); } return ComUtility::OnPublicApiReturn(ComAsyncOperationContext::StartAndDetach(move(operation), context)); } HRESULT STDMETHODCALLTYPE ComInfrastructureServiceAgent::EndStartInfrastructureTask( /* [in] */ IFabricAsyncOperationContext * context) { return ComUtility::OnPublicApiReturn(ComStartInfrastructureTaskAsyncOperation::End(context)); } HRESULT STDMETHODCALLTYPE ComInfrastructureServiceAgent::BeginFinishInfrastructureTask( /* [in] */ LPCWSTR taskId, /* [in] */ ULONGLONG instanceId, /* [in] */ DWORD timeoutMilliseconds, /* [in] */ IFabricAsyncOperationCallback * callback, /* [out, retval] */ IFabricAsyncOperationContext ** context) { wstring parsedTaskId; HRESULT hr = StringUtility::LpcwstrToWstring(taskId, false, parsedTaskId); if (FAILED(hr)) { return ComUtility::OnPublicApiReturn(hr); } auto operation = make_com<ComFinishInfrastructureTaskAsyncOperation>(*impl_.get(), parsedTaskId, instanceId); hr = operation->Initialize( impl_.get_Root(), timeoutMilliseconds, callback); if (FAILED(hr)) { return ComUtility::OnPublicApiReturn(hr); } return ComUtility::OnPublicApiReturn(ComAsyncOperationContext::StartAndDetach(move(operation), context)); } HRESULT STDMETHODCALLTYPE ComInfrastructureServiceAgent::EndFinishInfrastructureTask( /* [in] */ IFabricAsyncOperationContext * context) { return ComUtility::OnPublicApiReturn(ComFinishInfrastructureTaskAsyncOperation::End(context)); } HRESULT STDMETHODCALLTYPE ComInfrastructureServiceAgent::BeginQueryInfrastructureTask( /* [in] */ DWORD timeoutMilliseconds, /* [in] */ IFabricAsyncOperationCallback * callback, /* [out, retval] */ IFabricAsyncOperationContext ** context) { auto operation = make_com<ComQueryInfrastructureTaskAsyncOperation>(*impl_.get()); auto hr = operation->Initialize( impl_.get_Root(), timeoutMilliseconds, callback); if (FAILED(hr)) { return ComUtility::OnPublicApiReturn(hr); } return ComUtility::OnPublicApiReturn(ComAsyncOperationContext::StartAndDetach(move(operation), context)); } HRESULT STDMETHODCALLTYPE ComInfrastructureServiceAgent::EndQueryInfrastructureTask( /* [in] */ IFabricAsyncOperationContext * context, /* [out, retval] */ IFabricInfrastructureTaskQueryResult ** result) { return ComUtility::OnPublicApiReturn(ComQueryInfrastructureTaskAsyncOperation::End(context, result)); }
be2d9bcb62aa4ac5a7283c08c2818019fe9e8697
31ac07ecd9225639bee0d08d00f037bd511e9552
/externals/OCCTLib/inc/Draw_Drawable2D.hxx
4bd6b3f9cd0b1d0f75224d9424530cfd90a80dcb
[]
no_license
litao1009/SimpleRoom
4520e0034e4f90b81b922657b27f201842e68e8e
287de738c10b86ff8f61b15e3b8afdfedbcb2211
refs/heads/master
2021-01-20T19:56:39.507899
2016-07-29T08:01:57
2016-07-29T08:01:57
64,462,604
1
0
null
null
null
null
UTF-8
C++
false
false
1,040
hxx
Draw_Drawable2D.hxx
// This file is generated by WOK (CPPExt). // Please do not edit this file; modify original file instead. // The copyright and license terms as defined for the original file apply to // this header file considered to be the "object code" form of the original source. #ifndef _Draw_Drawable2D_HeaderFile #define _Draw_Drawable2D_HeaderFile #ifndef _Standard_HeaderFile #include <Standard.hxx> #endif #ifndef _Standard_DefineHandle_HeaderFile #include <Standard_DefineHandle.hxx> #endif #ifndef _Handle_Draw_Drawable2D_HeaderFile #include <Handle_Draw_Drawable2D.hxx> #endif #ifndef _Draw_Drawable3D_HeaderFile #include <Draw_Drawable3D.hxx> #endif #ifndef _Standard_Boolean_HeaderFile #include <Standard_Boolean.hxx> #endif class Draw_Drawable2D : public Draw_Drawable3D { public: //! Returns False. <br> Standard_EXPORT virtual Standard_Boolean Is3D() const; DEFINE_STANDARD_RTTI(Draw_Drawable2D) protected: private: }; // other Inline functions and methods (like "C++: function call" methods) #endif
129af98693bf11e93a82dd4fe4a9c2d0943fd7a3
04bc05d1140cfcdb2c42c371c61e3f70ec524d77
/c++/C++编程实例100篇/实例18/COUNT.CPP
e510aa050eebac08b542124f8b1f913ceb628f7d
[]
no_license
lcong/vsSource
52ad6fdffd5a0ad841215c0bd5ee6db1ea2d59ef
7ec52c5cd63215e7dbd1c89a3421309aa695bc5b
refs/heads/master
2021-06-23T05:12:17.588868
2017-08-11T05:57:40
2017-08-11T05:57:40
null
0
0
null
null
null
null
UTF-8
C++
false
false
285
cpp
COUNT.CPP
//IMPLEMENTATION OF COUNTER CLASS //FILE COUNT.CPP #define MAX 65535 #include "Count.h" void COUNTER::operator++() { if (NUMBER<MAX) NUMBER+=10; } void COUNTER::operator--() { if (NUMBER>0) NUMBER-=10; } void COUNTER::DISPLAY() { printf("\n THE TEST COUNTER = %d",NUMBER); }
1e3e87354023fcf708e91d6d4f7077c38cc1f1c4
735449faa3ff13e4e9239bb6b7d9f896190f743c
/functionFindMatIntersection.h
75990afbd3bd1b324896a150f84fea6d3093c079
[]
no_license
jollytrees/popupImage
a552c8644cfbc00dc5649e68bde62844e1ffac98
7f0e36f14b1b8518d2d76bd10d304bc0b50e2ebb
refs/heads/master
2021-01-16T23:34:13.905386
2017-01-08T21:19:36
2017-01-08T21:19:36
48,270,729
0
2
null
null
null
null
UTF-8
C++
false
false
3,170
h
functionFindMatIntersection.h
#ifndef fuctionFindMatIntersection_h #define fuctionFindMatIntersection_h #include <opencv2/imgproc/imgproc.hpp> #include <opencv/cv.h> static void checkType(cv::Mat &input){ if(input.type() == CV_8UC3) input.convertTo(input, CV_8UC1); } static int findMatIntersectionRInt( cv::Mat input1, cv::Mat input2, cv::Mat &output){ cv::Mat addImg(input1.size(), CV_8UC1); checkType(input1); checkType(input2); addImg = input1 & input2; int count = cv::countNonZero(addImg); //std::cout << count << std::endl; if(count>0){ output = addImg.clone(); return count; } return 0; } static int findMatIntersectionInt( cv::Mat input1, cv::Mat input2, cv::Mat &output){ cv::Mat addImg(input1.size(), CV_8UC1); checkType(input1); checkType(input2); addImg = input1 & input2; int count = cv::countNonZero(addImg); if(count>3){ output = addImg.clone(); return count; } return count; } static bool findMatIntersection( cv::Mat input1, cv::Mat input2, cv::Mat &output){ cv::Mat addImg(input1.size(), CV_8UC1); checkType(input1); checkType(input2); addImg = input1 & input2; int count = cv::countNonZero(addImg); if(count>3){ output = addImg.clone(); return true; } return false; } static bool isLineAndMatConn(foldLineType &line, cv::Mat &inputMat, std::vector<cv::Vec4i> &lineVec){ cv::Mat lineImg(inputMat.size(), CV_8UC1); cv::Mat addImg(inputMat.size(), CV_8UC1); lineImg.setTo(0); addImg.setTo(0); //line cv::line(lineImg, line.line.first, line.line.second, 255, 3); if(findMatIntersection(lineImg, inputMat, addImg)){ lineVec.clear(); HoughLinesP( addImg, lineVec, 1, CV_PI/180, 3 ); if(lineVec.size()>0) return true; } return false; } static int isLineAndPatchConnInt(struct patches &pch, foldLineType &line, cv::Size &matSize){ cv::Mat lineImg(matSize, CV_8UC1); cv::Mat patchImg(matSize, CV_8UC1); cv::Mat addImg(matSize, CV_8UC1); lineImg.setTo(0); patchImg.setTo(0); addImg.setTo(0); //line cv::line(lineImg, line.line.first, line.line.second, 255, 8); //patch cv::drawContours(patchImg, pch.paths, 0, 255, CV_FILLED); int isConn = findMatIntersectionInt(lineImg, patchImg, addImg); //if(isConn) imshow("aa", addImg); return isConn; } static bool isLineAndPatchConn(struct patches &pch, foldLineType &line, cv::Size &matSize){ cv::Mat lineImg(matSize, CV_8UC1); cv::Mat patchImg(matSize, CV_8UC1); cv::Mat addImg(matSize, CV_8UC1); lineImg.setTo(0); patchImg.setTo(0); addImg.setTo(0); //line cv::line(lineImg, line.line.first, line.line.second, 255, 8); //patch cv::drawContours(patchImg, pch.paths, 0, 255, CV_FILLED); bool isConn = findMatIntersection(lineImg, patchImg, addImg); //if(isConn) imshow("aa", addImg); return isConn; } #endif /* fuctionFindMatIntersection_h */
30b25988ab993801a9b6f329b5e305cc99b6e7e7
426ca7875bf182fbe7b2be195743ba37e9a67637
/src/RenderState.hpp
9c44dd61aaa3d977578e8dc1e5adf5ec5892ab10
[]
no_license
JoshRWinter/darktimes
9f6137e98d25c41cc150537d7666b817eae7f0dc
fa96d10d23c9ba9feef272414efa984db29a70cb
refs/heads/master
2023-08-31T20:35:05.145016
2023-07-13T00:21:19
2023-07-13T00:21:19
169,932,205
0
0
null
null
null
null
UTF-8
C++
false
false
257
hpp
RenderState.hpp
#pragma once #include <vector> #include "Darktimes.hpp" #include "Renderable.hpp" struct RenderState { NO_COPY_MOVE(RenderState); RenderState() : centerx(0.0f) , centery(0.0f) {} float centerx, centery; std::vector<Renderable> renderables; };
9dd722ebd3b844b6e071a75a9bca92ddcb3381d8
a997694a9bad0eefed928962abb5b1fcdfa7ebe7
/leetcode/leetcode_319/leetcode_319/leetcode_319.cpp
3f6cb05327e980b2b5640053d11d43e5757b1fd2
[ "MIT" ]
permissive
gingkg/happyleetcodeeveryday
55f447ccca11760573a5ab2f0dfd88ea13827828
7101e0404afca10ec3b18caafe4c5ef67eec38b6
refs/heads/main
2023-07-07T09:14:27.991977
2021-08-15T08:49:59
2021-08-15T08:49:59
382,788,210
0
0
null
null
null
null
UTF-8
C++
false
false
1,770
cpp
leetcode_319.cpp
/* 319. 灯泡开关 初始时有 n 个灯泡处于关闭状态。 对某个灯泡切换开关意味着:如果灯泡状态为关闭,那该灯泡就会被开启;而灯泡状态为开启,那该灯泡就会被关闭。 第 1 轮,每个灯泡切换一次开关。即,打开所有的灯泡。 第 2 轮,每两个灯泡切换一次开关。 即,每两个灯泡关闭一个。 第 3 轮,每三个灯泡切换一次开关。 第 i 轮,每 i 个灯泡切换一次开关。 而第 n 轮,你只切换最后一个灯泡的开关。 找出 n 轮后有多少个亮着的灯泡。 示例 1: 输入:n = 3 输出:1 解释: 初始时, 灯泡状态 [关闭, 关闭, 关闭]. 第一轮后, 灯泡状态 [开启, 开启, 开启]. 第二轮后, 灯泡状态 [开启, 关闭, 开启]. 第三轮后, 灯泡状态 [开启, 关闭, 关闭]. 你应该返回 1,因为只有一个灯泡还亮着。 示例 2: 输入:n = 0 输出:0 示例 3: 输入:n = 1 输出:1   提示: 0 <= n <= 10^9 什么数的因数的个数是奇数个? 答案是完全平方数. 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/bulb-switcher 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 */ #include <iostream> #include <cmath> #include <vector> using namespace std; class Solution { public: int bulbSwitch(int n) { if (n == 0) return 0; int res = 1; while (true) { if (res * res < n) { res++; } else { break; } } return res-1; } }; int main() { cout << "Hello World!\n"; Solution S; int n = 9999999; cout << S.bulbSwitch(n) << endl; }
ee2f3265a6b1758f95d45199a9358318cd784dbd
c84fd723c6e30f883123945e263e9a7c3a0c496b
/backup/201510B/tang/82-1.cpp
a6b590f005c97361710283d1bdc6095ebbb5cf8b
[]
no_license
LabsCluster/DLC-QD1
26521e0f4f55073462fb64882a084b264ba8a3e4
bf6369e293e95470cc0792f8d17f1affa4dedc86
refs/heads/master
2021-01-01T06:38:31.573709
2016-02-20T04:52:51
2016-02-20T04:52:51
41,633,411
1
0
null
null
null
null
UTF-8
C++
false
false
128
cpp
82-1.cpp
#include<stdio.h> #include<math.h> int main() { double p,n; scanf("%lf",&n); p=pow(1+0.09,n); printf("%f",p); return 0; }
e2ed42d4ed9eb984eab6f971e332b9df791700e3
e01fc0982465c01a8beea8263648d56169d6ad4a
/src/HBDemo/CSModule/CSTools/CSAudio/AudioDecoder/CSAudioDecoder.h
e991f7238ff2e5bc785f79f0ffe8ed340eb9e72e
[]
no_license
heibaihei/HbFFmpegMedia
8d4a0082193020d877329eb585e2a71b5317a939
c7ae30634cc53571b31017e4a91264832d507417
refs/heads/master
2021-03-24T12:41:19.488446
2017-12-14T12:10:45
2017-12-14T12:10:45
98,384,354
1
0
null
null
null
null
UTF-8
C++
false
false
2,073
h
CSAudioDecoder.h
// // CSAudioDecoder.h // FFmpeg // // Created by zj-db0519 on 2017/8/15. // Copyright © 2017年 meitu. All rights reserved. // #ifndef CSAudioDecoder_h #define CSAudioDecoder_h #include <stdio.h> #include <stdint.h> #include <iostream> #include "HBAudio.h" namespace HBMedia { /** * 1、解码包含有音视频流的媒体文件 * 2、对接编码器 */ typedef class CSAudioDecoder { public: CSAudioDecoder(AudioParams* targetAudioParam); ~CSAudioDecoder(); /** * 配置输入的音频文件 */ void setInputAudioMediaFile(char *file); char *getInputAudioMediaFile(); /** * 配置输出的音频文件 */ void setOutputAudioMediaFile(char *file); char *getOutputAudioMediaFile(); /** * 解码器初始化、启动、关闭、释放 */ int audioDecoderInitial(); int audioDecoderOpen(); int audioDecoderClose(); int audioDecoderRelease(); /** * 音频读包 * @return HB_OK 执行正常 * HB_ERROR 执行发生异常 */ int readAudioPacket(); /** * 音频解帧 */ int selectAudieoFrame(); /** * 将音频数据写入音频缓冲区 */ int CSIOPushDataBuffer(uint8_t* data, int samples); private: /** * 检验音频参数的有效性 */ int _checkAudioParamValid(); protected: int mPKTSerial; char *mInputAudioMediaFile; int mAudioStreamIndex; AVAudioFifo *mAudioFifo; AudioParams mTargetAudioParams; AVFormatContext* mPInputAudioFormatCtx; AVCodecContext* mPInputAudioCodecCtx; AVCodec* mPInputAudioCodec; CSAudioResample *mAudioResample; PacketQueue mPacketCacheList; /** 输出文件,只是针对不做编码的情况下,将音频数据以裸流PCM格数的方式输出 */ char *mOutputAudioMediaFile; FILE *mAudioOutputFileHandle; int64_t mDecodeStateFlag; private: } CSAudioDecoder; } #endif /* CSAudioDecoder_h */
500ef5fdb62dd93360caff19747b773908fdfd1f
105c5cfbea2469542253f9917d28671b7a01abc4
/src/Fitness/MO/TrapInverseTrap.hpp
301c68a971aaa6155d9d105e0ffec61e68e78b20
[]
no_license
tdenottelander/GA
1fd11c60ac7f68a9faf41ea2300a3aebe24dc925
26adc7558a6169939e5f119b2a7cb116c177f659
refs/heads/master
2023-02-02T15:21:48.555329
2020-12-11T16:39:53
2020-12-11T16:39:53
221,727,778
0
0
null
null
null
null
UTF-8
C++
false
false
715
hpp
TrapInverseTrap.hpp
// // TrapInverseTrap.hpp // GA // // Created by Tom den Ottelander on 06/02/2020. // Copyright © 2020 Tom den Ottelander. All rights reserved. // #ifndef TrapInverseTrap_hpp #define TrapInverseTrap_hpp #include <stdio.h> #include "FitnessFunction.hpp" class TrapInverseTrap : public FitnessFunction { public: int blocks; int blocksize = 5; TrapInverseTrap (int length); std::vector<float> evaluate(Individual &ind) override; float subfunc (Individual &ind, int startIdx, int endIdx, int objective); void display() override; std::string id() override; FitnessFunction* clone() const override; bool entireParetoFrontFound() override; }; #endif /* TrapInverseTrap_hpp */
7e3d7e00c69e21ffd572735a333a011a32b1e71c
5aa80aab7a75d76b0aa838bf8f74a276a12c876e
/src/vnsw/agent/oper/vm.h
9507c2cf731847a539ddca91ae084a29403556b9
[ "Apache-2.0", "LicenseRef-scancode-warranty-disclaimer" ]
permissive
tungstenfabric/tf-controller
83b6d58afadb5697b540b5345711a5b2af90d201
f825fde287f4eb2089aba2225ca73eeab3888040
refs/heads/master
2023-08-28T02:56:27.329584
2023-08-20T12:15:38
2023-08-20T12:31:34
231,070,970
55
29
Apache-2.0
2023-07-23T01:38:17
2019-12-31T10:24:38
C++
UTF-8
C++
false
false
3,612
h
vm.h
/* * Copyright (c) 2013 Juniper Networks, Inc. All rights reserved. */ #ifndef vnsw_agent_vm_hpp #define vnsw_agent_vm_hpp #include <cmn/agent_cmn.h> #include <oper/oper_db.h> #include <agent_types.h> typedef std::map<std::string, boost::uuids::uuid> VmNameUuidTree; struct VmKey : public AgentOperDBKey { VmKey(boost::uuids::uuid id) : AgentOperDBKey(), uuid_(id) {} ; virtual ~VmKey() { } boost::uuids::uuid uuid_; }; struct VmData : public AgentOperDBData { typedef vector<boost::uuids::uuid> SGUuidList; VmData(Agent *agent, IFMapNode *node, const std::string &name, const SGUuidList &sg_list) : AgentOperDBData(agent, node), name_(name), sg_list_(sg_list) { } virtual ~VmData() { } std::string name_; SGUuidList sg_list_; }; class VmEntry : AgentRefCount<VmEntry>, public AgentOperDBEntry { public: static const int kVectorIncreaseSize = 16; VmEntry(const boost::uuids::uuid &id); virtual ~VmEntry(); virtual bool IsLess(const DBEntry &rhs) const; virtual KeyPtr GetDBRequestKey() const; virtual void SetKey(const DBRequestKey *key); virtual string ToString() const; const string &GetCfgName() const { return name_; } void SetCfgName(std::string name) { name_ = name; } const boost::uuids::uuid &GetUuid() const { return uuid_; } uint32_t GetRefCount() const { return AgentRefCount<VmEntry>::GetRefCount(); } void SendObjectLog(AgentLogEvent::type event) const; bool DBEntrySandesh(Sandesh *sresp, std::string &name) const; uint32_t flow_count() const { return flow_count_; } void update_flow_count(int val) const; uint32_t linklocal_flow_count() const { return linklocal_flow_count_; } void update_linklocal_flow_count(int val) const { int tmp = linklocal_flow_count_.fetch_and_add(val); if (val < 0) assert(tmp >= val); } bool drop_new_flows() const { return drop_new_flows_; } private: void SetInterfacesDropNewFlows(bool drop_new_flows) const; friend class VmTable; boost::uuids::uuid uuid_; std::string name_; mutable tbb::atomic<int> flow_count_; mutable tbb::atomic<int> linklocal_flow_count_; mutable bool drop_new_flows_; DISALLOW_COPY_AND_ASSIGN(VmEntry); }; class VmTable : public AgentOperDBTable { public: VmTable(DB *db, const std::string &name) : AgentOperDBTable(db, name) { } virtual ~VmTable() { } virtual std::auto_ptr<DBEntry> AllocEntry(const DBRequestKey *k) const; virtual size_t Hash(const DBEntry *entry) const {return 0;} virtual size_t Hash(const DBRequestKey *key) const {return 0;} virtual DBEntry *OperDBAdd(const DBRequest *req); virtual bool OperDBOnChange(DBEntry *entry, const DBRequest *req); virtual bool OperDBDelete(DBEntry *entry, const DBRequest *req); virtual bool IFNodeToReq(IFMapNode *node, DBRequest &req, const boost::uuids::uuid &u); virtual bool IFNodeToUuid(IFMapNode *node, boost::uuids::uuid &u); bool ProcessConfig(IFMapNode *node, DBRequest &req, const boost::uuids::uuid &u); virtual AgentSandeshPtr GetAgentSandesh(const AgentSandeshArguments *args, const std::string &context); static DBTableBase *CreateTable(DB *db, const std::string &name); static VmTable *GetInstance() {return vm_table_;} boost::uuids::uuid GetVmUuid(const std::string &name); private: static VmTable *vm_table_; VmNameUuidTree vm_name_uuid_tree_; DISALLOW_COPY_AND_ASSIGN(VmTable); }; #endif // vnsw_agent_vm_hpp
7406b2a77df6a09833ab4885d1a9b2ae5a8ccb03
0310ed95e8f9062f4b1f6100d7c105b23fbfd50a
/Parser/includes/Nodes/NodeExp2Bracket.h
ed2da654ff9fd87f885063974bd4dea7d5a37348
[]
no_license
markusheupel/Compiler
acd7200b2272a346d7a71ca865050a3f4a2939c4
4aef81755cf7081705e478d1e4705f3bee73ae04
refs/heads/master
2020-04-12T20:24:49.852450
2019-01-02T19:57:10
2019-01-02T19:57:10
162,735,311
0
0
null
null
null
null
UTF-8
C++
false
false
531
h
NodeExp2Bracket.h
/* * NodeExp2Bracket.h * * Created on: 08.01.2017 * Author: yannick */ #ifndef PARSER_INCLUDES_NODES_NODEEXP2BRACKET_H_ #define PARSER_INCLUDES_NODES_NODEEXP2BRACKET_H_ class NodeExp2Bracket: public NodeExp2 { private: NodeExp* exp; public: ~NodeExp2Bracket() { delete this->exp; } void addNode(NodeExp* exp) { this->exp = exp; } void accept(ParseTreeVisitor* visitor) { visitor->visitNode(this); } NodeExp* getExp() { return this->exp; } }; #endif /* PARSER_INCLUDES_NODES_NODEEXP2BRACKET_H_ */
28243c1f17a0fb66017a76247ad11f691963a22a
fc38cecf0d0b928aae1ba84ba9412be685e2b3fb
/PCLApp/Segmentation.cpp
d4110941a338b3d743e5f0d2a42b8cda9c5c161e
[]
no_license
otradovec/PCL_osX
eafa1163904c9bd5dc4acca8d39e6c2d3e9cdc10
87597482d1c4b63dafbba0f2f02c14f0accc410b
refs/heads/master
2023-02-25T09:00:41.979223
2021-01-29T09:33:39
2021-01-29T09:33:39
315,912,680
0
0
null
null
null
null
UTF-8
C++
false
false
1,571
cpp
Segmentation.cpp
#include "Segmentation.hpp" Segmentation::Segmentation(){ } std::vector<pcl::PointCloud<pcl::PointXYZ>::Ptr> Segmentation::euclidianClusterSegmentation(pcl::PointCloud<pcl::PointXYZ>::Ptr cloudToSegment){ std::vector<pcl::PointCloud<pcl::PointXYZ>::Ptr> segmentedClouds; pcl::search::KdTree<pcl::PointXYZ>::Ptr kdTree (new pcl::search::KdTree<pcl::PointXYZ>); kdTree->setInputCloud (cloudToSegment); std::vector<pcl::PointIndices> clusterIndices; pcl::EuclideanClusterExtraction<pcl::PointXYZ> euclideanClusterExtraction; euclideanClusterExtraction.setClusterTolerance (1.15); // 2cm euclideanClusterExtraction.setMinClusterSize (100); euclideanClusterExtraction.setMaxClusterSize (1000); euclideanClusterExtraction.setSearchMethod (kdTree); euclideanClusterExtraction.setInputCloud (cloudToSegment); euclideanClusterExtraction.extract (clusterIndices); for (std::vector<pcl::PointIndices>::const_iterator it = clusterIndices.begin (); it != clusterIndices.end (); ++it) { pcl::PointCloud<pcl::PointXYZ>::Ptr cloudCluster (new pcl::PointCloud<pcl::PointXYZ>); for (std::vector<int>::const_iterator pit = it->indices.begin (); pit != it->indices.end (); ++pit) cloudCluster->points.push_back (cloudToSegment->points[*pit]); //* cloudCluster->width = cloudCluster->points.size (); cloudCluster->height = 1; cloudCluster->is_dense = true; segmentedClouds.push_back(cloudCluster); } return segmentedClouds; }
7c340f9df9abff33f1a9ad2bf90e960435a5cbbe
7e285313f203b0000e6ae7d63828f0e22571a35b
/code/lib/lichtkrant/lichtkrant.cpp
731d2b3c8c9de6700bb5d8176c7b199f339a2ffb
[]
no_license
buzztiaan/arduino-lichtkrant
6c9b439f9312b33f589804c4ec7d7727e5bc85b5
46f0a5f465239c0840b5e2fec224f98971adf3b5
refs/heads/master
2020-01-21T03:41:03.424308
2012-11-25T19:08:37
2012-11-25T19:08:37
6,854,490
2
0
null
null
null
null
UTF-8
C++
false
false
2,351
cpp
lichtkrant.cpp
#include "Arduino.h" #include "lichtkrant.h" byte frameBuffer[ROWS][SHREGISTERS]; byte readPixel(byte whichBuffer[][SHREGISTERS], byte x, byte y) // left upper pixel is x0, y0. it does account for the not connected pins on the sh-registers. { return bitRead(whichBuffer[y][(x+NONVISABLES)/(SHREGISTERS+1)], 7-((x+NONVISABLES)%8)); } void setPixel(byte whichBuffer[][SHREGISTERS], byte value, byte x, byte y) // left upper pixel is x0, y0. it does account for the not connected pins on the sh-registers. { bitWrite(whichBuffer[y][(x+NONVISABLES)/(SHREGISTERS+1)], 7-((x+NONVISABLES)%8) , value); } void bufferCopy(byte from[][SHREGISTERS], byte to[][SHREGISTERS]) { for(byte row = 0; row < ROWS; row++) { for(byte sr = 0; sr < SHREGISTERS; sr++) { to[row][sr] = from[row][sr]; } } } void setBuffer(byte whichBuffer[][SHREGISTERS], byte data) { for(byte row = 0; row < ROWS; row++) { for(byte sr = 0; sr < SHREGISTERS; sr++) { whichBuffer[row][sr] = data; } } } void serviceFramebuffer(void) { unsigned long currentMicros = micros(); static long prevRowMicros = 0L; if(currentMicros - prevRowMicros > MICROSPERROW) { static int rowInUse = 0; prevRowMicros = currentMicros; digitalWrite(rowToPin[rowInUse], HIGH); // switch row /off/ rowInUse++; if (rowInUse == ROWS) { rowInUse = 0; } digitalWrite(LATCHPIN, LOW); for(byte sr = 0; sr < SHREGISTERS; sr++) { shiftOut(DATAPIN, CLOCKPIN, MSBFIRST, ~frameBuffer[rowInUse][sr]); // 0 is /on/, 1 is /off/ } digitalWrite(LATCHPIN, HIGH); digitalWrite(rowToPin[rowInUse], LOW); // switch row /on/ } } void initHardware(void) { for(byte row = 0; row < 7; row++) // row mosfets { pinMode(rowToPin[row], OUTPUT); digitalWrite(rowToPin[row], HIGH); // turn all /off/. These pins are also pulled up externally. } pinMode(DATAPIN, OUTPUT); // shiftregister digitalWrite(DATAPIN, HIGH); pinMode(LATCHPIN, OUTPUT); digitalWrite(LATCHPIN, HIGH); pinMode(CLOCKPIN, OUTPUT); digitalWrite(CLOCKPIN, LOW); digitalWrite(LATCHPIN, LOW); for(byte sr = 0; sr < SHREGISTERS; sr++) { shiftOut(DATAPIN, CLOCKPIN, MSBFIRST, byte(B11111111)); // all /off/ } digitalWrite(LATCHPIN, HIGH); }
e9e5a482340ad557c8faeb439e296fe298f18e15
795000f575aebcc0f1993194ce4e54c9d0096248
/C++ STL/Queue/IPL_2021_MatchDay2.cpp
e828fa87c3f6913247e73e772f6ebc414db7aaaf
[]
no_license
nayalchitra/P3_Program
fb94329bf658cecda487249dc8cb96a1bd1b80af
06f3436f863e87a7b77f3bf74ca556bc1afac7a1
refs/heads/master
2023-03-09T09:24:45.189517
2023-02-21T16:45:45
2023-02-21T16:45:45
191,009,535
0
0
null
null
null
null
UTF-8
C++
false
false
2,414
cpp
IPL_2021_MatchDay2.cpp
/* Due to the rise of covid-19 cases in India, this year BCCI decided to organize knock-out matches in IPL rather than a league. Today is matchday 2 and it is between the most loved team Chennai Super Kings and the most underrated team - Punjab Kings. Stephen Fleming, the head coach of CSK, analyzing the batting stats of Punjab. He has stats of runs scored by all N players in the previous season and he wants to find the maximum score for each and every contiguous sub-list of size K to strategize for the game. N = 9, K = 3 arr[] = 1 2 3 1 4 5 2 3 6 Output: 3 3 4 5 5 5 6 Explanation: 1st contiguous subarray = {1 2 3} Max = 3 2nd contiguous subarray = {2 3 1} Max = 3 3rd contiguous subarray = {3 1 4} Max = 4 4th contiguous subarray = {1 4 5} Max = 5 5th contiguous subarray = {4 5 2} Max = 5 6th contiguous subarray = {5 2 3} Max = 5 7th contiguous subarray = {2 3 6} Max = 6 Input: N = 10, K = 4 arr[] = 8 5 10 7 9 4 15 12 90 13 Output: 10 10 10 15 15 90 90 Explanation: 1st contiguous subarray = {8 5 10 7}, Max = 10 2nd contiguous subarray = {5 10 7 9}, Max = 10 3rd contiguous subarray = {10 7 9 4}, Max = 10 4th contiguous subarray = {7 9 4 15}, Max = 15 5th contiguous subarray = {9 4 15 12}, Max = 15 6th contiguous subarray = {4 15 12 90}, Max = 90 7th contiguous subarray = {15 12 90 13}, Max = 90 Your Task: You don't need to read input or print anything. Complete the function max_of_subarrays() which takes the array, N, and K as input parameters and returns a list of integers denoting the maximum of every contiguous subarray of size K. */ #include<bits/stdc++.h> using namespace std; vector<int> max_of_subarrays(vector<int> arr, int n, int k) { vector<int> res; deque<int>dq; for( int i =0 ; i < n; i++) { if(!dq.empty() and dq.front() == i - k) dq.pop_front(); while(!dq.empty() and arr[dq.front()] < arr[i]) dq.pop_back(); dq.push_back(i); if( i >= k-1) res.push_back(arr[dq.front()]); } return res; } int main() { int t; cin >> t; while( t--) { int n, k; cin >> n >> k; vector<int>arr(n); for(int i = 0; i < n; i++) cin >> arr[i]; vector<int>res = max_of_subarrays(arr, n, k); for(int i = 0 ;i < res.size() ; i ++) cout << res[i]<< " "; cout<<endl; } }
bf16371d37846a2e21ecfa48a919287865040947
69c3a9292a8b76696695712329cd68b56a5ba2c8
/Volume 0/0040.cpp
4b1dde2c44438f819c60f8bcbabeb64d664aa0c5
[]
no_license
yuta1024/aoj
ebbf7ccc03d1adf00c2301559a8d835fba5e4003
da24890eaf199f7eb2cb98bfed1bf7e1c533b586
refs/heads/master
2021-01-02T22:37:55.372004
2012-09-18T11:36:43
2012-09-18T11:36:43
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,022
cpp
0040.cpp
#include <iostream> #include <string> #include <ctype.h> using namespace std; int gcd(int a, int b) { if (b == 0) return a; return gcd(b, a%b); } string solve(string cipher) { for ( ; ; ) { for (int a = 1; ; ++a) { if (gcd(a, 26) != 1) continue; bool decrypt = false; for (int b = 0; b < 26; ++b) { string plain = cipher; for (unsigned int i = 0; i < plain.size(); ++i) { if (isalpha(plain[i])) plain[i] = ('a' + ((a * (plain[i]-'a') + b) % 26)); } if (plain.find("that") != string::npos || plain.find("this") != string::npos) return plain; } } } } int main() { int n; cin >> n; string cipher; getline(cin, cipher); for (int i = 0; i < n; ++i) { getline(cin, cipher); if (cipher.find_first_of("\n") != string::npos) cipher.erase(cipher.end()-1); if (cipher.find_first_of("\r") != string::npos) cipher.erase(cipher.end()-1); cout << solve(cipher) << endl; } return 0; }
9eb4109f50df79741fe9db5f56aeb6ef6f321bec
c35c231a05f24f22c5aae7ef94e1ded6dcfd848c
/codeforces/A. About Grisha N. - ACM ICPC 2014-2015. NEERC. Eastern Subregional Contest.cpp
23073b37d9c9e3063d0b522b25c865661d9bb8da
[]
no_license
irvifa/online-judges
081bed8db248c4c0d5a096fb2a196a119778788c
c128a03b711f256f8888ed3d2e526889dce90ca2
refs/heads/master
2021-03-12T02:39:44.868187
2020-03-11T13:46:07
2020-03-11T13:46:07
246,582,524
0
0
null
null
null
null
UTF-8
C++
false
false
120
cpp
A. About Grisha N. - ACM ICPC 2014-2015. NEERC. Eastern Subregional Contest.cpp
#include <iostream> using namespace std; int main(){ int f; cin >> f; cout<<(12-f > 5 ? "NO\n":"YES\n"); return 0; }
8079ea8c74c617a804f6729b5fdcdd13045962bb
82f76b60e80df85f3f05d01f02162195a52d6e5b
/ch4/4.5.cpp
315b194788c6c7a52d89666b9c1a86ee6c06c30c
[]
no_license
yckuo/cracking
23938d47854fe3c48b6a1ddbd4dc6f030173ad74
84f7f5f7837d9a4977f2003f972a2574979a5308
refs/heads/master
2021-01-13T15:12:17.733142
2017-01-14T23:07:03
2017-01-14T23:07:03
76,221,105
0
0
null
null
null
null
UTF-8
C++
false
false
816
cpp
4.5.cpp
/* Copyright (C) yckuo - All Rights Reserved */ #include <iostream> #include <fstream> #include <sstream> #include <climits> #include "TreeNode.h" using namespace std; class Solution { public: bool IsBST(TreeNode* root) { return IsBST(root, INT_MIN, INT_MAX); } private: bool IsBST(TreeNode* root, int minval, int maxval) { if (!root) return true; return root->val <= maxval && root->val >= minval && IsBST(root->left, minval, root->val - 1) && IsBST(root->right, root->val + 1, maxval); } }; int main(int argc, char** argv) { freopen(argv[1], "r", stdin); Solution sol; string line; while (getline(cin, line)) { istringstream iss(line); TreeNode* root = TreeNode::Read(iss); cout << sol.IsBST(root) << endl; } return 0; }
aa713b260b2ced1ef96edfeee17b8a0278b15845
525705ba39c566ad1acd684f4753efdeb0d389ae
/src/universe.h
6495968852dc9f6b5a920dd3f0b951a9b55ec585
[]
no_license
tbake0155/mites_and_stars
3d22ffc3f37efcd741891b2449787aa22387c822
16844d3b3789a8a0f3956c59095bb66e9056d13a
refs/heads/master
2021-05-11T20:45:24.015166
2018-01-15T14:49:11
2018-01-15T14:49:11
117,448,240
0
0
null
null
null
null
UTF-8
C++
false
false
2,463
h
universe.h
// // Author: Timothy Baker // cs361: Assignment 2 //"A story of Mites and Stars" // //universe.h //////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////// #include <random> #include <list> #include <thread> #include "cthulu.h" #include "node.h" #include "mite.h" #include "star.h" using namespace std; #ifndef UNIVERSE_H_INCLUDED #define UNIVERSE_H_INCLUDED ///////////////////////////////////////////////////////////////////// // universe class for time and universe size ///////////////////////////////////////////////////////////////////// class universe { private: int clock; int size; int units; int rare_links; double longest_possible; public: //constructors and destructor universe(){clock=size=0;longest_possible=0.0;rare_links=4;} ~universe(){} //setters and getters int get_rare_link(){return rare_links;} void increment_rare_link(){rare_links--;} void set_clock(int c){clock=c;} int get_clock(){return clock;} void set_size(int s); int get_size(){return size;} void set_units(int u){units=u;} int get_units(){return units;} double range_finder_double(node * planet, node * link); void max_range(int size); }; ///////////////////////////////////////////////////////////////////// // universal function defintions ///////////////////////////////////////////////////////////////////// void find_xyz(int seeding_size, default_random_engine * random_engine, int &x, int &y, int &z); int find_planets_size(default_random_engine * random_engine, int seeding_size); int find_mites_size(int seeding_size, default_random_engine * random_engine); int find_stars_size(int seeding_size, default_random_engine * random_engine); int find_units(int seeding_size); void * stars_tick_tock(list<star>* stars, list<node>* planets, default_random_engine* random_engine); void * mites_tick_tock(list<mite>* mites, list<node>* planets, default_random_engine* random_engine, universe * universal); void * planets_tick_tock(list<node>* planets); bool update_user(int clock, int i); void * gif_maker(); void * patients(thread * thread); bool range_finder(node * planets, node * links); #endif//UNIVERSE_H_INCLUDED
373418a614e740f17093aea2aa7458d957602f46
2effc621ca20726d0546b55fd1f1b1c5a6874cd5
/UVA11369/UVA11369.cpp
46b836ce664c125a7219692c184aece6c10027ff
[]
no_license
lpc0503/UVA
c0c6e7e8c2a88d0c0558a2ec2bff7982a508ca91
12affc8685fcc1a2e644ce924e3e5308e7ec7145
refs/heads/master
2021-06-04T11:03:40.624832
2020-06-24T12:18:58
2020-06-24T12:18:58
139,245,261
3
0
null
null
null
null
UTF-8
C++
false
false
536
cpp
UVA11369.cpp
#include<bits/stdc++.h> using namespace std; #define PROBLEM "11369" int a[100010]; int main(void){ #ifdef DBG freopen(PROBLEM ".in", "r", stdin); freopen(PROBLEM ".out", "w", stdout); #endif int cases; int n; scanf("%d", &cases); while(cases--){ memset(a, 0, sizeof(a)); scanf("%d", &n); for(int i = 1 ; i <= n ; i++) scanf("%d", &a[i]); sort(a+1, a+n+1); long long ans = 0; for(int i = n ; i > 0 ;){ if(i-2 <= 0) break; ans += a[i-2]; i-=3; } printf("%lld\n", ans); } return 0; }
df2345d12485fdcdba5927a0f80dddbd082c5040
9c9003f4912e2065c3901f1f51ef5b398f999a10
/projectb/client/game_xxx/newProtocol/game_qznn_def.pb.cc
0fd98b04e824d2fa48f60335ea16eab384f6559b
[]
no_license
PHDaozhang/recharge_h5
41424d5725eae69cc6a921cd1ef954b255a0ca65
7d5e63d97e731ea860d927c37612fe35f7d3bd61
refs/heads/master
2020-08-11T21:57:49.842525
2019-10-15T07:32:40
2019-10-15T07:32:40
214,632,134
0
3
null
null
null
null
UTF-8
C++
false
true
6,453
cc
game_qznn_def.pb.cc
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: game_qznn_def.proto #define INTERNAL_SUPPRESS_PROTOBUF_FIELD_DEPRECATION #include "game_qznn_def.pb.h" #include <algorithm> #include <google/protobuf/stubs/common.h> #include <google/protobuf/stubs/once.h> #include <google/protobuf/io/coded_stream.h> #include <google/protobuf/wire_format_lite_inl.h> #include <google/protobuf/descriptor.h> #include <google/protobuf/generated_message_reflection.h> #include <google/protobuf/reflection_ops.h> #include <google/protobuf/wire_format.h> // @@protoc_insertion_point(includes) namespace game_qznn_protocols { namespace { const ::google::protobuf::EnumDescriptor* e_server_msg_type_descriptor_ = NULL; const ::google::protobuf::EnumDescriptor* e_notify_type_descriptor_ = NULL; const ::google::protobuf::EnumDescriptor* e_table_status_descriptor_ = NULL; } // namespace void protobuf_AssignDesc_game_5fqznn_5fdef_2eproto() { protobuf_AddDesc_game_5fqznn_5fdef_2eproto(); const ::google::protobuf::FileDescriptor* file = ::google::protobuf::DescriptorPool::generated_pool()->FindFileByName( "game_qznn_def.proto"); GOOGLE_CHECK(file != NULL); e_server_msg_type_descriptor_ = file->enum_type(0); e_notify_type_descriptor_ = file->enum_type(1); e_table_status_descriptor_ = file->enum_type(2); } namespace { GOOGLE_PROTOBUF_DECLARE_ONCE(protobuf_AssignDescriptors_once_); inline void protobuf_AssignDescriptorsOnce() { ::google::protobuf::GoogleOnceInit(&protobuf_AssignDescriptors_once_, &protobuf_AssignDesc_game_5fqznn_5fdef_2eproto); } void protobuf_RegisterTypes(const ::std::string&) { protobuf_AssignDescriptorsOnce(); } } // namespace void protobuf_ShutdownFile_game_5fqznn_5fdef_2eproto() { } void protobuf_AddDesc_game_5fqznn_5fdef_2eproto() { static bool already_here = false; if (already_here) return; already_here = true; GOOGLE_PROTOBUF_VERIFY_VERSION; ::google::protobuf::DescriptorPool::InternalAddGeneratedFile( "\n\023game_qznn_def.proto\022\023game_qznn_protoco" "ls*\256\010\n\021e_server_msg_type\022\024\n\017e_mst_start_" "c2l\020\220N\022\032\n\025e_mst_c2l_check_state\020\221N\022\035\n\030e_" "mst_c2l_get_scene_info\020\222N\022\034\n\027e_mst_c2l_g" "et_room_info\020\232N\022\032\n\025e_mst_c2l_enter_table" "\020\235N\022\032\n\025e_mst_c2l_leave_table\020\236N\022\033\n\026e_mst" "_c2l_user_trustee\020\237N\022\024\n\017e_mst_c2l_ready\020" "\240N\022\033\n\026e_mst_c2l_change_table\020\242N\022\036\n\031e_mst" "_c2l_change_card_req\020\243N\022\031\n\024e_mst_c2l_ban" "ker_req\020\244N\022\030\n\023e_mst_c2l_times_req\020\245N\022\024\n\017" "e_mst_start_l2c\020\230u\022!\n\034e_mst_l2c_check_st" "ate_result\020\231u\022 \n\033e_mst_l2c_scene_info_re" "sult\020\232u\022\037\n\032e_mst_l2c_room_info_result\020\242u" "\022!\n\034e_mst_l2c_enter_table_result\020\254u\022!\n\034e" "_mst_l2c_leave_table_result\020\255u\022&\n!e_mst_" "l2c_table_enter_player_info\020\256u\022&\n!e_mst_" "l2c_table_leave_player_info\020\257u\022\033\n\026e_mst_" "l2c_user_trustee\020\260u\022\031\n\024e_mst_l2c_game_st" "art\020\262u\022\027\n\022e_mst_l2c_game_end\020\264u\022\"\n\035e_mst" "_l2c_table_status_notify\020\265u\022\036\n\031e_mst_l2c" "_room_award_list\020\266u\022\037\n\032e_mst_l2c_room_to" "tal_award\020\267u\022\036\n\031e_mst_l2c_room_award_ite" "m\020\270u\022\032\n\025e_mst_l2c_game_notify\020\271u\022\036\n\031e_ms" "t_l2c_change_card_res\020\272u\022!\n\034e_mst_l2c_ch" "ange_card_notify\020\273u\022\032\n\025e_mst_l2c_banker_" "info\020\274u\022\034\n\027e_mst_l2c_banker_notify\020\275u\022\031\n" "\024e_mst_l2c_times_info\020\276u\022\030\n\023e_mst_l2c_fi" "ve_card\020\277u\022\027\n\021e_mst_clend_index\020\240\234\001*T\n\re" "_notify_type\022\026\n\022e_nt_table_dismiss\020\001\022\030\n\024" "e_nt_gold_not_enough\020\002\022\021\n\re_nt_shutdown\020" "\003*\213\001\n\016e_table_status\022\r\n\te_ts_free\020\000\022\016\n\ne" "_ts_reset\020\001\022\024\n\020e_ts_change_card\020\003\022\017\n\013e_t" "s_banker\020\004\022\016\n\ne_ts_times\020\005\022\022\n\016e_ts_five_" "card\020\006\022\017\n\013e_ts_result\020\007", 1343); ::google::protobuf::MessageFactory::InternalRegisterGeneratedFile( "game_qznn_def.proto", &protobuf_RegisterTypes); ::google::protobuf::internal::OnShutdown(&protobuf_ShutdownFile_game_5fqznn_5fdef_2eproto); } // Force AddDescriptors() to be called at static initialization time. struct StaticDescriptorInitializer_game_5fqznn_5fdef_2eproto { StaticDescriptorInitializer_game_5fqznn_5fdef_2eproto() { protobuf_AddDesc_game_5fqznn_5fdef_2eproto(); } } static_descriptor_initializer_game_5fqznn_5fdef_2eproto_; const ::google::protobuf::EnumDescriptor* e_server_msg_type_descriptor() { protobuf_AssignDescriptorsOnce(); return e_server_msg_type_descriptor_; } bool e_server_msg_type_IsValid(int value) { switch(value) { case 10000: case 10001: case 10002: case 10010: case 10013: case 10014: case 10015: case 10016: case 10018: case 10019: case 10020: case 10021: case 15000: case 15001: case 15002: case 15010: case 15020: case 15021: case 15022: case 15023: case 15024: case 15026: case 15028: case 15029: case 15030: case 15031: case 15032: case 15033: case 15034: case 15035: case 15036: case 15037: case 15038: case 15039: case 20000: return true; default: return false; } } const ::google::protobuf::EnumDescriptor* e_notify_type_descriptor() { protobuf_AssignDescriptorsOnce(); return e_notify_type_descriptor_; } bool e_notify_type_IsValid(int value) { switch(value) { case 1: case 2: case 3: return true; default: return false; } } const ::google::protobuf::EnumDescriptor* e_table_status_descriptor() { protobuf_AssignDescriptorsOnce(); return e_table_status_descriptor_; } bool e_table_status_IsValid(int value) { switch(value) { case 0: case 1: case 3: case 4: case 5: case 6: case 7: return true; default: return false; } } // @@protoc_insertion_point(namespace_scope) } // namespace game_qznn_protocols // @@protoc_insertion_point(global_scope)
076387d54c0f8bb7c4e853ffe96c79545ad54ee1
caf55812511d43016cfe908a279ef60915f3428a
/Source/McRave/ResourceInfo.h
6f52ab36c4de629cd2ec2744552add64116f25c5
[ "MIT" ]
permissive
impie66/McRave
8572655d65b1bbf1bceba79431b222e724c431cb
51ff5a0768dc553f4adea109784035b5d6020fd1
refs/heads/master
2022-12-08T23:04:16.276859
2020-08-31T12:48:34
2020-08-31T12:48:34
291,378,719
2
0
null
2020-08-30T01:36:49
2020-08-30T01:36:48
null
UTF-8
C++
false
false
2,943
h
ResourceInfo.h
#pragma once #include <BWAPI.h> #include "BWEB.h" namespace McRave { class UnitInfo; class ResourceInfo : public std::enable_shared_from_this<ResourceInfo> { private: int remainingResources; BWAPI::Unit thisUnit; BWAPI::UnitType type; BWAPI::Position position; BWAPI::TilePosition tilePosition; BWEB::Station * station; ResourceState rState; std::vector<std::weak_ptr<UnitInfo>> targetedBy; public: ResourceInfo(BWAPI::Unit newResource) { thisUnit = newResource; station = nullptr; remainingResources = 0; rState = ResourceState::None; type = BWAPI::UnitTypes::None; position = BWAPI::Positions::None; tilePosition = BWAPI::TilePositions::None; } void updateResource() { type = thisUnit->getType(); remainingResources = thisUnit->getResources(); position = thisUnit->getPosition(); tilePosition = thisUnit->getTilePosition(); } void addTargetedBy(std::weak_ptr<UnitInfo> unit) { targetedBy.push_back(unit); } void removeTargetedBy(std::weak_ptr<UnitInfo> unit) { for (auto itr = targetedBy.begin(); itr != targetedBy.end(); itr++) { if ((itr)->lock() == unit.lock()) { targetedBy.erase(itr); break; } } } // bool hasStation() { return station != nullptr; } BWEB::Station * getStation() { return station; } void setStation(BWEB::Station* newStation) { station = newStation; } int getGathererCount() { return int(targetedBy.size()); } int getRemainingResources() { return remainingResources; } ResourceState getResourceState() { return rState; } BWAPI::Unit unit() { return thisUnit; } BWAPI::UnitType getType() { return type; } BWAPI::Position getPosition() { return position; } BWAPI::TilePosition getTilePosition() { return tilePosition; } std::vector<std::weak_ptr<UnitInfo>>& targetedByWhat() { return targetedBy; } // void setRemainingResources(int newInt) { remainingResources = newInt; } void setResourceState(ResourceState newState) { rState = newState; } void setUnit(BWAPI::Unit newUnit) { thisUnit = newUnit; } void setType(BWAPI::UnitType newType) { type = newType; } void setPosition(BWAPI::Position newPosition) { position = newPosition; } void setTilePosition(BWAPI::TilePosition newTilePosition) { tilePosition = newTilePosition; } // bool operator== (ResourceInfo& p) { return thisUnit == p.unit(); } bool operator< (ResourceInfo& p) { return thisUnit < p.unit(); } }; }
88914571322ba110f60881ff807a6651093698f7
ce8fce7859f49cd07252356f15f76d010614c5c4
/Graphical/includes/Resource.hpp
7b4eb8f1ee6074b837a1e927aba95432b1622dfa
[]
no_license
NightPlow/Zappy
8cd9934002b38dfeeb627bb869862ffb9da2cf41
e27d96df29e36db28b56e666e139e0b1f80fdb07
refs/heads/master
2021-01-03T08:34:54.788183
2019-06-23T20:37:10
2019-06-23T20:37:10
null
0
0
null
null
null
null
UTF-8
C++
false
false
37
hpp
Resource.hpp
../GraphicalAPI/includes/Resource.hpp
b024f8ab0e8f87ea03f0af4708c571408fae0642
0538ae5aa55f0203b76314c8a656d9b76e43391f
/src/vm-memory-segment.cc
ea522bc0b2270081fb1cf338863561b23066779a
[ "BSD-3-Clause", "BSD-2-Clause" ]
permissive
emptyland/mio
db78ad87a5d971f822113159ac1a636da19241b2
77ec9737b4002820c31fca241aaa6711a7391285
refs/heads/master
2021-05-04T11:50:00.383421
2017-08-13T04:59:23
2017-08-13T04:59:23
49,038,378
0
0
null
null
null
null
UTF-8
C++
false
false
458
cc
vm-memory-segment.cc
#include "vm-memory-segment.h" namespace mio { MemorySegment::MemorySegment() : size_(0) , capacity_(kPageSize) , chunk_(malloc(kPageSize)) { } MemorySegment::~MemorySegment() { free(chunk_); } void *MemorySegment::Advance(int add) { if (size_ + add > capacity_) { capacity_ += kPageSize; chunk_ = realloc(chunk_, capacity_); } auto old = size_; size_ += add; return offset(old); } } // namespace mio
b4bd7a6b0cb0745e5d288ed1894cb5c61775c3c1
2ae0b8d95d439ccfd55ea7933ad4a2994ad0f6c5
/src/core/src/file_util.cpp
1809311c49b38d3dbd040a1143545b0d6933e0b3
[ "Apache-2.0" ]
permissive
openvinotoolkit/openvino
38ea745a247887a4e14580dbc9fc68005e2149f9
e4bed7a31c9f00d8afbfcabee3f64f55496ae56a
refs/heads/master
2023-08-18T03:47:44.572979
2023-08-17T21:24:59
2023-08-17T21:24:59
153,097,643
3,953
1,492
Apache-2.0
2023-09-14T21:42:24
2018-10-15T10:54:40
C++
UTF-8
C++
false
false
1,759
cpp
file_util.cpp
// Copyright (C) 2018-2023 Intel Corporation // SPDX-License-Identifier: Apache-2.0 // #include "ngraph/file_util.hpp" #include "openvino/util/file_util.hpp" NGRAPH_SUPPRESS_DEPRECATED_START using namespace std; using namespace ngraph; string file_util::get_file_name(const string& s) { return ov::util::get_file_name(s); } string file_util::get_file_ext(const string& s) { return ov::util::get_file_ext(s); } string file_util::get_directory(const string& s) { return ov::util::get_directory(s); } string file_util::path_join(const string& s1, const string& s2, const string& s3) { return ov::util::path_join({s1, s2, s3}); } string file_util::path_join(const string& s1, const string& s2, const string& s3, const string& s4) { return ov::util::path_join({s1, s2, s3, s4}); } string file_util::path_join(const string& s1, const string& s2) { return ov::util::path_join({s1, s2}); } void file_util::iterate_files(const string& path, function<void(const string& file, bool is_dir)> func, bool recurse, bool include_links) { ov::util::iterate_files(path, func, recurse, include_links); } std::string file_util::sanitize_path(const std::string& path) { return ov::util::sanitize_path(path); } void file_util::convert_path_win_style(std::string& path) { ov::util::convert_path_win_style(path); } #ifdef OPENVINO_ENABLE_UNICODE_PATH_SUPPORT std::string file_util::wstring_to_string(const std::wstring& wstr) { return ov::util::wstring_to_string(wstr); } std::wstring file_util::multi_byte_char_to_wstring(const char* str) { return ov::util::string_to_wstring(str); } #endif // OPENVINO_ENABLE_UNICODE_PATH_SUPPORT
0f82607f03ef59a54a5a44cc123baa2c7952abc3
d443ca6a0f68ebc845dc652e221d02844b9889aa
/train_exceptions/calculatrice.cpp
7ff9bc693b8faa8fc2f8fd512e1a36d022636749
[]
no_license
JulietteNdn/CPlusPlus_TP
66ec1332cad3690dafa881084f724cd17588733b
fa3aeecb9db3da79680929593452fffc9e88b5a5
refs/heads/master
2020-04-05T00:53:11.950831
2018-12-01T16:02:48
2018-12-01T16:02:48
156,414,365
0
0
null
null
null
null
UTF-8
C++
false
false
810
cpp
calculatrice.cpp
#include "mon_exception.hpp" #include <stdexcept> #include <vector> using namespace std; int division(int a, int b){ if(b == 0) throw MonException(1,"Division par zéro!!",2); // s'arrête si l'exception est levée car le reste du code jusqu'au catch n'est pas exécuté. return a/b; } int main (int, char**){ try{ division(5,0); }catch(MonException const& E){ cerr << "ERREUR : " << E.what() << endl; } int indice = -1; int tab_[5]; try { vector<int> a(1000000000,1); //Un tableau bien trop grand } catch(exception const& e) //On rattrape les exceptions standard de tous types { cerr << "ERREUR : " << e.what() << endl; //On affiche la description de l'erreur throw; } catch(e){ cout << "coucou" << endl; } return 0; }
14500e3ff3175ecc3959050a5199be27873e635b
ad273708d98b1f73b3855cc4317bca2e56456d15
/aws-cpp-sdk-connect/source/model/UserPhoneConfig.cpp
9a249abf79c819aef93fb3c1cd2fe2a2741c9163
[ "MIT", "Apache-2.0", "JSON" ]
permissive
novaquark/aws-sdk-cpp
b390f2e29f86f629f9efcf41c4990169b91f4f47
a0969508545bec9ae2864c9e1e2bb9aff109f90c
refs/heads/master
2022-08-28T18:28:12.742810
2020-05-27T15:46:18
2020-05-27T15:46:18
267,351,721
1
0
Apache-2.0
2020-05-27T15:08:16
2020-05-27T15:08:15
null
UTF-8
C++
false
false
2,814
cpp
UserPhoneConfig.cpp
/* * Copyright 2010-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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 <aws/connect/model/UserPhoneConfig.h> #include <aws/core/utils/json/JsonSerializer.h> #include <utility> using namespace Aws::Utils::Json; using namespace Aws::Utils; namespace Aws { namespace Connect { namespace Model { UserPhoneConfig::UserPhoneConfig() : m_phoneType(PhoneType::NOT_SET), m_phoneTypeHasBeenSet(false), m_autoAccept(false), m_autoAcceptHasBeenSet(false), m_afterContactWorkTimeLimit(0), m_afterContactWorkTimeLimitHasBeenSet(false), m_deskPhoneNumberHasBeenSet(false) { } UserPhoneConfig::UserPhoneConfig(JsonView jsonValue) : m_phoneType(PhoneType::NOT_SET), m_phoneTypeHasBeenSet(false), m_autoAccept(false), m_autoAcceptHasBeenSet(false), m_afterContactWorkTimeLimit(0), m_afterContactWorkTimeLimitHasBeenSet(false), m_deskPhoneNumberHasBeenSet(false) { *this = jsonValue; } UserPhoneConfig& UserPhoneConfig::operator =(JsonView jsonValue) { if(jsonValue.ValueExists("PhoneType")) { m_phoneType = PhoneTypeMapper::GetPhoneTypeForName(jsonValue.GetString("PhoneType")); m_phoneTypeHasBeenSet = true; } if(jsonValue.ValueExists("AutoAccept")) { m_autoAccept = jsonValue.GetBool("AutoAccept"); m_autoAcceptHasBeenSet = true; } if(jsonValue.ValueExists("AfterContactWorkTimeLimit")) { m_afterContactWorkTimeLimit = jsonValue.GetInteger("AfterContactWorkTimeLimit"); m_afterContactWorkTimeLimitHasBeenSet = true; } if(jsonValue.ValueExists("DeskPhoneNumber")) { m_deskPhoneNumber = jsonValue.GetString("DeskPhoneNumber"); m_deskPhoneNumberHasBeenSet = true; } return *this; } JsonValue UserPhoneConfig::Jsonize() const { JsonValue payload; if(m_phoneTypeHasBeenSet) { payload.WithString("PhoneType", PhoneTypeMapper::GetNameForPhoneType(m_phoneType)); } if(m_autoAcceptHasBeenSet) { payload.WithBool("AutoAccept", m_autoAccept); } if(m_afterContactWorkTimeLimitHasBeenSet) { payload.WithInteger("AfterContactWorkTimeLimit", m_afterContactWorkTimeLimit); } if(m_deskPhoneNumberHasBeenSet) { payload.WithString("DeskPhoneNumber", m_deskPhoneNumber); } return payload; } } // namespace Model } // namespace Connect } // namespace Aws
232bc233ec1ca40a55f9348578cd49c8a84e1f54
4e580b69a16f94aab7aa4c8a9fc8c353883bbc41
/wxx_hxx_final/src/ofApp.h
cb0c2a075e1b553549db8906a80461b11dcf1934
[]
no_license
zhouy546/YunqiZhou2_OFanimation2015
770e26a2355cf4bc6393d3a4faea3239d2a54804
870c5d56c6cc8fb6cbb02bf6634aeb735d6f9ebd
refs/heads/master
2021-01-01T16:05:48.632856
2015-05-14T00:47:23
2015-05-14T00:47:23
31,288,975
0
0
null
null
null
null
UTF-8
C++
false
false
2,383
h
ofApp.h
/******************************************************************/ /** * @file ofApp.h * @brief Example for ofxKinectNui addon * @note * @todo * @bug * * @author sadmb * @date Oct. 28, 2011 */ /******************************************************************/ #pragma once #include "ofMain.h" #include "ofxKinectNui.h" #include "ofxKinectNuiDraw.h" #include "particle.h" enum PlayState {STATE_BLANK, STATE_NEW_MESSAGE,STATE_WAIT,STATE_REMOVE_ALL}; class ofxKinectNuiDrawTexture; class ofxKinectNuiDrawSkeleton; // uncomment this to read from two kinects simultaneously //#define USE_TWO_KINECTS class ofApp : public ofBaseApp { public: //particle std::vector<Particle*> particles; ofImage txtData; void removeAll(); void audioIn(float * input, int bufferSize, int nChannels); PlayState currentState; void startParticles(); std::vector<ofVec2f> vboPoints; std::vector<ofFloatColor> vboColors; ofVec2f getField(ofVec2f* position); float fallOffTriger; float newMessage; float removeAllTriger; ofVbo vbo; //``````````````````````````````````` //sound ofSoundStream soundStream; vector <float> left; vector <float> right; vector <float> volHistory; int bufferCounter; int drawCounter; float smoothedVol; float scaledVol; float speed; float g; //------------------------------------------------------------ void setup(); void update(); void draw(); /** * @brief example for adjusting video images to depth images * @note inspired by akira's video http://vimeo.com/17146552 */ void drawCalibratedTexture(); void exit(); void drawCircle3f(int n, int radius, ofVec3f cur); void keyPressed (int key); void mouseMoved(int x, int y ); void mouseDragged(int x, int y, int button); void mousePressed(int x, int y, int button); void mouseReleased(int x, int y, int button); void windowResized(int w, int h); void kinectPlugged(); void kinectUnplugged(); ofxKinectNui kinect; ofxBase3DVideo* kinectSource; bool bPlugged; bool bUnplugged; //unsigned short nearClipping; //unsigned short farClipping; int angle; int mRotationX, mRotationY; // Please declare these texture pointer and initialize when you want to draw them ofxKinectNuiDrawSkeleton* skeletonDraw_; float x,y; };
e2dd4773d16399a8a1cf4d4f35041b6f9130c739
50edda2bfaf6d47bd7b5d7ec155e0cc5bf1be7c1
/GameTemplate/game/ParticleEmitter.h
95f5d92ae34bef8c83437a9b6e3df078f18ee858
[]
no_license
TakumiArita/CarGame7
dbefb5df3ec8bde097d4ff84c07f8243158c1ee5
4c157b47fc358851bbba93e0c4824bbd661a57f4
refs/heads/master
2021-05-11T12:15:31.288561
2018-05-10T11:29:31
2018-05-10T11:29:31
117,651,635
0
0
null
null
null
null
SHIFT_JIS
C++
false
false
1,311
h
ParticleEmitter.h
#pragma once #include <list> #include <d3d9.h> #include <d3dx9effect.h> class Particle; /* * @brief パーティクル生成パラメータ。 */ struct SParticleEmitParameter { //初期化。 void Init() { memset(this, 0, sizeof(SParticleEmitParameter)); } const char* texturePath; //テクスチャのファイルパス。 float w; //パーティクルの幅。 float h; //パーティクルの高さ。 float intervalTime; //パーティクルの発生間隔。 D3DXVECTOR3 initSpeed; //初速度。 D3DXVECTOR3 position; //座標 }; /* * @brief パーティクルの発生機 */ class ParticleEmitter { public: ParticleEmitter(); ~ParticleEmitter(); /* * @brief 初期化。 *@param[in] camera パーティクルの描画で使用するカメラ。 *@param[in] param パーティクル生成用のパラメータ */ void Init(const SParticleEmitParameter& param); void Update(); void Render(const D3DXMATRIX& viewMatrix, const D3DXMATRIX& projMatrix); private: SParticleEmitParameter param; //パラメータ。 std::list<Particle*> particleList; //パーティクルのリスト。 float timer; //タイマー。 };
106ddad7bf0d927c52126d924b5d668c9492739e
63c71060f36866bca4ac27304cef6d5755fdc35c
/src/TaskMgr/TaskScheduler.cpp
003569205d11ce9777d0cd3762f03126228b0233
[]
no_license
15831944/barry_dev
bc8441cbfbd4b62fbb42bee3dcb79ff7f5fcaf8a
d4a83421458aa28ca293caa7a5567433e9358596
refs/heads/master
2022-03-24T07:00:26.810732
2015-12-22T07:19:58
2015-12-22T07:19:58
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,123
cpp
TaskScheduler.cpp
//////////////////////////////////////////////////////////////////////////// // // Copyright (C) 2005 // Packet Engineering, Inc. All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification is not permitted unless authorized in writing by a duly // appointed officer of Packet Engineering, Inc. or its derivatives // // Description: // // // Modification History: // 08/13/2011 Created by Chen Ding //////////////////////////////////////////////////////////////////////////// #if 0 #include "TaskMgr/TaskScheduler.h" #include "alarm_c/alarm.h" #include "Alarm/Alarm.h" #include "API/AosApi.h" #include "Debug/Debug.h" #include "Porting/Sleep.h" #include "Rundata/Rundata.h" #include "SmartDoc/SmartDoc.h" #include "SEInterfaces/SmartDocObj.h" #include "TaskMgr/MapTask.h" #include "TaskMgr/TaskThrd.h" #include "Thread/Mutex.h" #include "Thread/CondVar.h" #include "Thread/Thread.h" #include "Util/OmnNew.h" #include "Util1/Ptrs.h" #include "Util1/Timer.h" AosTaskScheduler::AosTaskScheduler() : mLock(OmnNew OmnMutex()), mCondVar(OmnNew OmnCondVar()) { } AosTaskScheduler::~AosTaskScheduler() { } bool AosTaskScheduler::start() { OmnThreadedObjPtr thisPtr(this, false); mThread = OmnNew OmnThread(thisPtr, "task_scheduler", 0, true, true, __FILE__, __LINE__); mThread->start(); return true; } bool AosTaskScheduler::stop() { return true; } bool AosTaskScheduler::config(const AosXmlTagPtr &config) { return true; } bool AosTaskScheduler::threadFunc( OmnThrdStatus::E &state, const OmnThreadPtr &thread) { while (state == OmnThrdStatus::eActive) { mLock->lock(); if (mPendingTasks.size() <= 0) { // queryDb(); if (mPendingTasks.size() <= 0) { mCondVar->wait(mLock); mLock->unlock(); continue; } } scheduleTasks(); mLock->unlock(); } return true; } bool AosTaskScheduler::addRequest( const AosXmlTagPtr &request, const AosRundataPtr &rdata) { OmnNotImplementedYet; return false; } bool AosTaskScheduler::scheduleTasks() { OmnNotImplementedYet; return false; } #endif
71578fd251d03eaa5197b0d0a7dae6ecb94a2b2f
1193b8d2ab6bb40ce2adbf9ada5b3d1124f1abb3
/branches/mapmodule/modules/genericmapmodule/include/GenericMapWalkmeshSubManager.h
19ce784f0cf11a462547d24b7cfed9a8dda5f13d
[]
no_license
sonetto/legacy
46bb60ef8641af618d22c08ea198195fd597240b
e94a91950c309fc03f9f52e6bc3293007c3a0bd1
refs/heads/master
2021-01-01T16:45:02.531831
2009-09-10T21:50:42
2009-09-10T21:50:42
32,183,635
0
2
null
null
null
null
UTF-8
C++
false
false
2,787
h
GenericMapWalkmeshSubManager.h
/*----------------------------------------------------------------------------- This source file is part of Sonetto RPG Engine. Copyright (C) 2007,2008 Arthur Carvalho de Souza Lima, Guilherme Prá Vieira Sonetto RPG Engine is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Sonetto RPG Engine 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA or go to http://www.gnu.org/copyleft/lesser.txt -----------------------------------------------------------------------------*/ #ifndef GENERICMAP_WALKMESHSUBMANAGER_H #define GENERICMAP_WALKMESHSUBMANAGER_H #include <OgreVector3.h> #include "GenericMapEvent.h" namespace GenericMapModule { class WalkmeshSubManager { public: WalkmeshSubManager() : mWalkmesh(NULL) {} virtual ~WalkmeshSubManager() {} virtual void setWalkmesh(const Walkmesh *walkmesh); virtual inline const Walkmesh *getWalkmesh() const { return mWalkmesh; } virtual void registerEvent(Event *evt); virtual void unregisterEvent(Event *evt); virtual inline void clearRegisteredEvents() { mEvents.clear(); } /** Moves a registered event This method moves the object, translating it from it's current location. Note that the final position may not be the same as inputed in this function, as it will first pass through a collision test against the walkmesh and other registered events if the EventObject::mIgnoreCollisions flag is not set. @param moveVector This it the desired movement vector the character will move if it doesn't find any obstacle on its path. */ virtual void moveEvent(Event *evt,const Ogre::Vector3 &moveVector); virtual bool setEventPosition(Event *evt,const Ogre::Vector3 &pos); virtual bool isEventOverTriangle(Event *evt,uint32 triangleID); protected: virtual bool walkmeshBorderCross(Event *evt,Ogre::Vector3 &position, float *slideFactor = NULL); virtual bool checkCollisions(Event *evt,Ogre::Vector3 &position); const Walkmesh *mWalkmesh; EventVector mEvents; }; } // namespace #endif
859d5b3ea8cb3ff2b96c0e11c416702858133e40
e97277433a8170de159b7fc20a611be2373720bb
/enml2html.cpp
b1b7b48b0414d08bf2a12ed1f1b96de0b0cd5200
[ "Apache-2.0" ]
permissive
zhongluqiang/evernote-sdk-cpp-quickstart
a4b25a217343818657730462b4f95c1cf9084957
63bb6008306a0ee4db2a3823436b8ffbd3542569
refs/heads/master
2020-05-02T21:23:30.874418
2019-05-02T16:36:38
2019-05-02T16:36:38
178,218,785
0
0
null
null
null
null
UTF-8
C++
false
false
9,518
cpp
enml2html.cpp
#include "enml2html.h" static const string HEADER_TO_TITLE = "<!DOCTYPE html> \n" "<html>\n" "<head>\n" "<meta charset=\"utf-8\">\n" "<title>"; static const string TITLE_TO_BODY = "</title>\n" "</head>\n" "<body style=\"width:1000px; margin-left:auto; margin-right:auto;\">\n"; static const string TAIL = "\n</body>\n</html>"; // trim from start (in place) static inline void ltrim(std::string &s) { s.erase(s.begin(), std::find_if(s.begin(), s.end(), std::not1(std::ptr_fun<int, int>(std::isspace)))); } // trim from end (in place) static inline void rtrim(std::string &s) { s.erase(std::find_if(s.rbegin(), s.rend(), std::not1(std::ptr_fun<int, int>(std::isspace))) .base(), s.end()); } // trim from both ends (in place) static inline void trim(std::string &s) { ltrim(s); rtrim(s); } void replaceMediaTags(string &enml) { regex pattern("(<en-media[^>]*?>)"); vector<string> enmdia_array; /* 找到所有的en-media标签 */ for (sregex_iterator it(enml.begin(), enml.end(), pattern), end_it; it != end_it; ++it) { // cout << it->str() << endl; enmdia_array.push_back(it->str()); } /* 正则表达式对象的赋值非常消耗时间,不应放在循环体内部(by C++ Primier 5th) */ regex hash_pattern("hash=\"([^\"]*)\""); regex type_pattern("type=\"([^\"]*)\""); /* 解析所有的en-media标签,如果是image类型,则转换成<img>标签,否则转换成<a>标签 */ for (auto i = enmdia_array.begin(); i != enmdia_array.end(); ++i) { /* 获取hash值,暂时使用hash值作为img的url地址 */ smatch hash_matches; smatch type_matches; string url; if (regex_search(*i, hash_matches, hash_pattern) && regex_search(*i, type_matches, type_pattern)) { string hash = hash_matches.str(1); string type = type_matches.str(1); /* 构造en-media标签的替代标签 */ if (type.find("image") != string::npos) { url = "<img src=\""; } else { url = "<a href=\""; } url += hash; url += "."; url += type.substr(type.find("/") + 1); url += "\"/>"; size_t start_pos = enml.find(*i); if (start_pos != std::string::npos) { enml.replace(start_pos, i->length(), url); } } } } void replaceCheckboxes(string &enml) { regex pattern("<en-todo[^>]*?>"); vector<string> entodo_array; /* 找到所有的en-todo标签 */ for (sregex_iterator it(enml.begin(), enml.end(), pattern), end_it; it != end_it; ++it) { // cout << it->str() << endl; entodo_array.push_back(it->str()); } pattern = "true"; /* 将en-todo标签转化成input标签 */ for (auto i = entodo_array.begin(); i != entodo_array.end(); ++i) { string input_tag = "<input type=\"checkbox\" name=\"unused\" " "value=\"unused\" disabled "; /* 获取entodo的checked属性是否为true */ smatch checked_maches; if (regex_search(*i, checked_maches, pattern)) { // cout << checked_maches.str() << endl; if (string("true") == checked_maches.str()) { input_tag += "checked>"; } } else { input_tag += ">"; } // cout << input_tag << endl; /* 将en-todo标签整体替换成input标签 */ size_t start_pos = enml.find(*i); if (start_pos != std::string::npos) { enml.replace(start_pos, i->length(), input_tag); } } } int enml2html(string &title, string &enml, string &html) { /* 删除xml版本声明 */ regex reg("(<\\?xml[^>]*?>)"); enml = regex_replace(enml, reg, ""); /* 删除DOCTYPE声明 */ reg = "(<!DOCTYPE[^>]*?>)"; enml = regex_replace(enml, reg, ""); /* 删除<en-note>标签对 */ reg = "(<en-note[^>]*?>)"; enml = regex_replace(enml, reg, ""); reg = "(</en-note>)"; enml = regex_replace(enml, reg, ""); /* 删除<en-crypt>标签对及其内容 */ reg = "<en-crypt[^>]*?>[\\s\\S]*?<\\/en-crypt>"; enml = regex_replace(enml, reg, ""); /* 删除印象笔记的<del>标签 */ reg = "(<del[^>]*?>[\\s\\S]*?<\\/del>)"; enml = regex_replace(enml, reg, ""); /* 删除第1个div标签的属性,这项主要是针对马克飞象编辑的笔记。印象笔记全部的 * 笔记内容都处在第一个div内,这个div的属性会影响整篇内容。如果是用印象笔记 * 客户端编辑的笔记,那这个div的内容一般为空,而用马克飞象编辑的笔记,这个 * div的属性会不为空。将其属性删除之后,马克飞象编辑过的文本字会更清晰一些, * 因为马克飞象默认的属性会对字体进行一度的模糊处理 */ reg = "(<div)(\\s*[^>]*?)(>)"; /* 使用format_first_only指定只替换子表达式的第1次出现 */ enml = regex_replace(enml, reg, "$1$3", regex_constants::format_first_only); /* 删除印象笔记的隐藏标签<center> */ reg = "(<center[^>]*?display[^>]*?>[\\s\\S]*?<\\/center>)"; enml = regex_replace(enml, reg, ""); /* 转换<en-media>中的图片标签,非图片标签转换成下载链接 */ replaceMediaTags(enml); /* 清除空的<div>标签 */ reg = "<div[^>]*?><\\/div>"; enml = regex_replace(enml, reg, ""); /* 清除前后空格 */ trim(enml); /* 清除不需要的标签,ENML基于XHTML,增加的元素有些不被HTML支持,需要删除 */ // todo... /* 删除印象笔记自带的高亮style属性的-evernote-highlight:true字段 * <xxx style="...;-evernote-highlight:true;"> */ reg = "(<\\w+\\s+style=\"[^>]*?;)(-evernote-highlight:true;)(\">)"; enml = regex_replace(enml, reg, "$1$3"); /* 删除印象笔记自带的代码格式中的sytle属性的-en-codeblock:true字段 * <div style="...;-en-codeblock:true;"> */ reg = "(<div\\s+style=\"[^>]*?;)(-en-codeblock:true;)(\">)"; enml = regex_replace(enml, reg, "$1$3"); /* 将印象笔记自带的en-todo复选框转换成HTML的input标签,使用type="checkbox" * 属性使其转变成复选框形式,使用checked属性选中复选框,使用disabled使复选框 * 不可编辑 */ replaceCheckboxes(enml); /* 备注:evernote-sync插件中对印象笔记自带的代码格式进行了转换,将div标签 * 转换成br标签,实际测试发现不需要转换就可以正常显示;同样,pre标签下的马克 * 飞象笔记代码也不需要转换,否则由于pre的预格式定义功能,代码格式会出现错乱 */ /* 备注:evernote-sync插件会对印象笔记中单独的行进行字体大小判断,根据字体 * 大小将其重新格式化成HTML的h1~h6标题,这一部并不是必须的,可跳过 */ /* 清除标签属性,实际测试发现,删除div p pre的属性对马克飞象的笔记显示效果有 * 一点点提升,主要是字体辨识度提高了一些,所以这三个标签的属性可以删除,但大 * 部分标签的属性是不可以删除的,例如h1~h6, code, span等,这些标签的属性一旦 * 删除会影响显著影响原有的格式,所以不宜删除 */ // reg = "(<div|p|pre)(\\s+[^>]*?)(>)"; // enml = regex_replace(enml, reg, "$1$3"); /* 剩下的是一些收尾工作,目的是使html文档的格式更整洁一些 */ /* 格式化br标签,删除属性,全部变成<br/> */ reg = "<br[^>]*?>"; enml = regex_replace(enml, reg, "<br/>"); /* 清除重复的<br/>标签 */ reg = "(<br\\/>){2,10}"; enml = regex_replace(enml, reg, "$1"); /* 清除<div.../>、<p.../>、<span.../>,这些标签是只有标签但没有内容的 */ reg = "<(div|p|span)((\\s[^>]*)?)\\/>"; enml = regex_replace(enml, reg, ""); /* 清除空标签 <xxx> </xxx>*/ /* 这串表达式的原始内容是:<([0-9a-zA-Z]+)[^>\/]*?>[\s]*?<\/\1> 最后一个 \1表示的是第一个表达式子串所匹配到的值 */ reg = "<([0-9a-zA-Z]+)[^>\\/]*?>[\\s]*?<\\/\\1>"; enml = regex_replace(enml, reg, ""); /* 清除空标签 <xxx> <br/> </xxx> */ /* 印象笔记原生笔记使用<div><br/></div>来表示空白行,所这条不能删除 */ // reg = "<([0-9a-zA-Z]+)[^>\\/]*?>[\\s]*?<br/>[\\s]*?<\\/\\1>"; // enml = regex_replace(enml, reg, ""); /* 清理无用的<br/> */ /* 使用马克飞象编辑的笔记中的有序列表使用<br/>来进行换行,这一条不可以删除 */ // reg = "<br\\/>"; // enml = regex_replace(enml, reg, ""); /* 压缩空白行,暂时还没想到行好的办法,todo...*/ /* 下面的压缩语句有bug,处理pre标签时如果将内部的span标签之间的空格删除掉的话 * 会导致马克飞象代码块中的空格全部消失 */ // reg = ">(\\s+?)<"; // enml = regex_replace(enml, reg, "><"); html = HEADER_TO_TITLE; html += title; html += TITLE_TO_BODY; html += enml; html += TAIL; return 0; }
d09b27bc3554dcc69fce5af1d662b022ac2c66c3
3bf24078b5b1a0558dbc497d4cce9f2dfd74e9be
/login.h
4ac0e6f0630764cb8106216e8e5bfa0fd0c9d905
[]
no_license
caowenbo2000/CwbChat
1fd1d7eb2f3dbcc9f4f7299cde93c239c48ca0e0
9969143d14ab6f1b4c5462ee213674292a6f5851
refs/heads/master
2021-01-16T01:45:57.927880
2020-03-13T14:56:53
2020-03-13T14:56:53
242,931,622
0
0
null
null
null
null
UTF-8
C++
false
false
513
h
login.h
#ifndef LOGIN_H #define LOGIN_H #include <QWidget> #include <QSqlDatabase> #include <QString> #include <string> #include <QSqlQuery> #include <QMessageBox> #include "sqlconnect.h" #include "sqliteconnect.h" namespace Ui { class Login; } class Login : public QWidget { Q_OBJECT public: explicit Login(QWidget *parent = nullptr); ~Login(); private slots: void on_button_log_released(); private: Ui::Login *ui; Sqlconnect yourdb; SqliteConnect ConversationDB ; }; #endif // LOGIN_H
651f3e3c6538b0eb9b9cc2f1efc48a0b744be8ce
855c09841525fa657d7ca3901a2cd587c69b7caa
/MAIL/SMTPClient.cpp
98c1683afd7a7facdf0d58011b6ce91585fb0256
[ "MIT" ]
permissive
embeddedmz/mailclient-cpp
eca2fc30d6b4ba027bdaeb12aca0208f199a8871
5b4a323cffdc37a4cfb8421868d1fdb30788304e
refs/heads/master
2022-06-21T18:21:01.216631
2022-06-07T10:23:14
2022-06-07T10:23:14
77,830,667
54
25
MIT
2023-08-19T11:25:34
2017-01-02T12:03:27
C++
UTF-8
C++
false
false
8,393
cpp
SMTPClient.cpp
/** * @file SMTPClient.cpp * @brief implementation of the SMTP client class * @author Mohamed Amine Mzoughi <mohamed-amine.mzoughi@laposte.net> */ #include "SMTPClient.h" CSMTPClient::CSMTPClient(LogFnCallback oLogger) : CMailClient(oLogger), m_eOperationType(SMTP_SEND_STRING) { } const bool CSMTPClient::SendString(const std::string& strFrom, const std::string& strTo, const std::string& strCc, const std::string& strMail) { m_strFrom = strFrom; m_strTo = strTo; m_strCc = strCc; m_strMail = strMail; m_eOperationType = SMTP_SEND_STRING; return Perform(); } const bool CSMTPClient::SendFile(const std::string& strFrom, const std::string& strTo, const std::string& strCc, const std::string& strPath) { m_strFrom = strFrom; m_strTo = strTo; m_strCc = strCc; m_strLocalFile = strPath; m_eOperationType = SMTP_SEND_FILE; return Perform(); } const bool CSMTPClient::VerifyAddress(const std::string& strAddress) { m_strTo = strAddress; m_eOperationType = SMTP_VRFY; return Perform(); } const bool CSMTPClient::ExpandMailList(const std::string& strListName) { m_strMail = strListName; m_eOperationType = SMTP_EXPN; return Perform(); } void CSMTPClient::ParseURL(std::string& strURL) { /* Note the use of smtps:// rather than smtp:// to request a SSL based connection. * for TLS you don't need to change the scheme to smtps. */ std::string strTmp = strURL; std::transform(strTmp.begin(), strTmp.end(), strTmp.begin(), ::toupper); if (strTmp.compare(0, 8, "SMTPS://") == 0 || strTmp.compare(0, 7, "SMTP://") == 0) { if (m_eSslTlsFlags != SslTlsFlag::ENABLE_SSL) m_eSslTlsFlags = SslTlsFlag::ENABLE_SSL; } else if (m_eSslTlsFlags == SslTlsFlag::ENABLE_SSL) { strURL.insert(0, "smtps://"); } else strURL.insert(0, "smtp://"); } /** * @brief configures the curl session according to requested * SMTP operation. * * * @retval true Successfully configured the curl session. * @retval false The configuration couldn't be performed. * */ const bool CSMTPClient::PrePerform() { //size_t uFileSize = 0; //size_t uCountLF = 0; m_ssString.clear(); switch (m_eOperationType) { case SMTP_SEND_STRING: if (!m_strFrom.empty() && !m_strTo.empty()) { m_ssString.str(m_strMail); /* Note that this option isn't strictly required, omitting it will result * in libcurl sending the MAIL FROM command with empty sender data. All * autoresponses should have an empty reverse-path, and should be directed * to the address in the reverse-path which triggered them. Otherwise, * they could cause an endless loop. See RFC 5321 Section 4.5.5 for more * details. */ curl_easy_setopt(m_pCurlSession, CURLOPT_MAIL_FROM, m_strFrom.c_str()); /* Add two recipients, in this particular case they correspond to the * To: and Cc: addressees in the header, but they could be any kind of * recipient. */ m_pRecipientslist = curl_slist_append(m_pRecipientslist, m_strTo.c_str()); if (!m_strCc.empty()) m_pRecipientslist = curl_slist_append(m_pRecipientslist, m_strCc.c_str()); curl_easy_setopt(m_pCurlSession, CURLOPT_MAIL_RCPT, m_pRecipientslist); /* We're using a callback function to specify the payload (the headers and * body of the message). You could just use the CURLOPT_READDATA option to * specify a FILE pointer to read from. */ // LF will be replaced by CRLF when sending the mail /*uCountLF = std::count_if(m_strMail.cbegin(), m_strMail.cend(), [](const char c) { return c == '\n'; });*/ //curl_easy_setopt(m_pCurlSession, CURLOPT_INFILESIZE, uCountLF + m_strMail.length()); curl_easy_setopt(m_pCurlSession, CURLOPT_READFUNCTION, ReadLineFromStringStreamCallback); curl_easy_setopt(m_pCurlSession, CURLOPT_READDATA, &m_ssString); curl_easy_setopt(m_pCurlSession, CURLOPT_UPLOAD, 1L); } else return false; break; case SMTP_SEND_FILE: if (!m_strLocalFile.empty() && !m_strFrom.empty() && !m_strTo.empty()) { // Request file size /*struct stat file_info; if (stat(m_strLocalFile.c_str(), &file_info)) { if (m_eSettingsFlags & ENABLE_LOG) m_oLog(StringFormat("[SMTPClient][Error] Unable to request local file size %s : %s" "- in MAILClient::Perform() in case SMTP_SEND.", m_strLocalFile.c_str(), strerror(errno))); return false; } curl_off_t fsize = (curl_off_t)file_info.st_size;*/ // I want to compute the size of the file without CR bytes // does this work properly ? m_fLocalFile.open(m_strLocalFile, std::fstream::in); // LF will be replaced by CRLF when sending the mail /*uCountLF = std::count_if((std::istreambuf_iterator<char>(m_fLocalFile)), std::istreambuf_iterator<char>(), [&uFileSize](const char c) -> bool { ++uFileSize; return c == '\n'; });*/ if (m_fLocalFile) { m_fLocalFile.seekg(0); curl_easy_setopt(m_pCurlSession, CURLOPT_READFUNCTION, CMailClient::ReadLineFromFileStreamCallback); curl_easy_setopt(m_pCurlSession, CURLOPT_READDATA, &m_fLocalFile); curl_easy_setopt(m_pCurlSession, CURLOPT_UPLOAD, 1L); //curl_easy_setopt(m_pCurlSession, CURLOPT_INFILESIZE_LARGE, uFileSize + uCountLF); } else { if (m_eSettingsFlags & ENABLE_LOG) m_oLog(StringFormat("[SMTPClient][Error] Unable to open local file %s in CSMTPClient::PrePerform()" "in case SMTP_SEND_FILE.", m_strLocalFile.c_str())); return false; } curl_easy_setopt(m_pCurlSession, CURLOPT_MAIL_FROM, m_strFrom.c_str()); m_pRecipientslist = curl_slist_append(m_pRecipientslist, m_strTo.c_str()); if (!m_strCc.empty()) m_pRecipientslist = curl_slist_append(m_pRecipientslist, m_strCc.c_str()); curl_easy_setopt(m_pCurlSession, CURLOPT_MAIL_RCPT, m_pRecipientslist); } else return false; break; case SMTP_VRFY: /* Note that the CURLOPT_MAIL_RCPT takes a list, not a char array */ if (!m_strTo.empty()) { if (m_strTo.at(0) != '<') m_strTo.insert(0, "<"); if (m_strTo.at(m_strTo.length() - 1) != '>') m_strTo += '>'; m_pRecipientslist = curl_slist_append(m_pRecipientslist, m_strTo.c_str()); curl_easy_setopt(m_pCurlSession, CURLOPT_MAIL_RCPT, m_pRecipientslist); } else return false; break; case SMTP_EXPN: /* Note that the CURLOPT_MAIL_RCPT takes a list, not a char array. e.g. "Friends" */ m_pRecipientslist = curl_slist_append(m_pRecipientslist, m_strMail.c_str()); curl_easy_setopt(m_pCurlSession, CURLOPT_MAIL_RCPT, m_pRecipientslist); /* Set the EXPN command */ curl_easy_setopt(m_pCurlSession, CURLOPT_CUSTOMREQUEST, "EXPN"); break; default: if (m_eSettingsFlags & ENABLE_LOG) m_oLog("[SMTPClient][Error] Unknown operation."); break; } curl_easy_setopt(m_pCurlSession, CURLOPT_URL, m_strURL.c_str()); return true; } /** * @brief performs operations that need to be done after performing * an SMTP request. * * * @retval true Successfully performed post request operations. * @retval false The post request operations couldn't be performed. * */ const bool CSMTPClient::PostPerform(CURLcode ePerformCode) { ePerformCode; if (m_eOperationType == SMTP_SEND_FILE) if (m_fLocalFile.is_open()) m_fLocalFile.close(); return true; }
765801f058272f1fec76d90c7cec8b0ea831ca29
94d18506c43b5b495d9e2a7a98b888abebc5e29f
/H2_SD_logger/H2_SD_logger.ino
99d0ff10f6da4f71485ceabcc1156a593f181224
[]
no_license
ghiraldini/Arduino
850145cf726a6764b3c9893b8a1c9d12fb43ec80
68c2f3d6fb5a37c4ad77a53a9281d11f71869459
refs/heads/master
2020-07-03T12:02:01.191029
2019-10-04T04:21:43
2019-10-04T04:21:43
74,171,865
0
0
null
null
null
null
UTF-8
C++
false
false
2,415
ino
H2_SD_logger.ino
/* SD card datalogger Modified from SD - dataLogger Example This code read the AIN0 of a thermistor and converts to a temperature This temperature is written to an SD card. The circuit: analog sensors on analog ins 0 SD card attached to SPI bus as follows: ** MOSI - pin 11 ** MISO - pin 12 ** CLK - pin 13 ** CS - pin 4 */ #include <SPI.h> #include <SD.h> const int chipSelect = 4; const int dioPin = 0; const int DAY = 86400; void setup() { // pinMode(chipSelect, OUTPUT); // digitalWrite(chipSelect, HIGH); // Open serial communications and wait for port to open: Serial.begin(9600); while (!Serial) { ; // wait for serial port to connect. Needed for native USB port only } Serial.print("Initializing SD card..."); // see if the card is present and can be initialized: if (!SD.begin(chipSelect)) { Serial.println("Card failed, or not present"); // don't do anything more: return; } Serial.println("card initialized."); pinMode(dioPin, INPUT); } void loop() { int count = 0; int i = 0; // int dioState = digitalRead(dioPin); // Serial.print("Digital Read: "); // Serial.println(dioState); delay(1000); while (/*dioState == HIGH*/ 1) { logH2(count); delay(1000); i++; if (i >= DAY) { count++; i = 0; } // dioState = digitalRead(dioPin); // if(dioState == LOW){ // break; // } } } void logH2(int count) { // make a string for assembling the data to log: String dataString = ""; // Data File Name Increment char dataFileName[] = "Fart_"; char myFile[32]; int analogPin = 0; sprintf(myFile, "%s%i.txt", dataFileName, count); Serial.print("Writing to data file: "); Serial.println(myFile); int sensor = analogRead(analogPin); dataString = String(getH2(sensor)); // open the file. note that only one file can be open at a time, // so you have to close this one before opening another. File dataFile = SD.open(myFile, FILE_WRITE); // if the file is available, write to it: if (dataFile) { dataFile.println(dataString); dataFile.close(); // print to the serial port too: Serial.println(dataString); } // if the file isn't open, pop up an error: else { Serial.print("error opening: "); Serial.println(dataFileName); } return; } float getH2(int rawADC){ float h2_val = rawADC * 5.0 / 1024.0; return h2_val; }
0ce6614793aaad66a27184b57cdb2aabfc38685a
8f160542786dd2e7bb093ffd76fe2e7b991a0ec3
/eventbuilders/EventBuilder_SMWZ.cxx
7ac3fe75c7ec5f2b5811b2d0d5b6b992bb96f9b0
[]
no_license
mileswu/proofana-chicago
fd909c65e22bf292c0756bdc2458e8a53a0419d4
a0c0b872583627e01f129f8143641b780dceae96
refs/heads/master
2021-01-20T04:02:32.673436
2013-07-12T16:11:50
2013-07-12T16:20:12
null
0
0
null
null
null
null
UTF-8
C++
false
false
29,678
cxx
EventBuilder_SMWZ.cxx
/************************************************************************** ** ** File: EventBuilder_SMWZ.cxx ** ** Description: EventBuilder class for analyzing the v7 GRJETS D3PDs. Use ** cases include but are not limited to the following: ** ** Authors: D. W. Miller and M. Swiatlowski ** ** Created: 2012-02-22 ** Modified: 2012-03-01 - DWM ** **************************************************************************/ #define EventBuilder_SMWZ_cxx #include "EventBuilder_SMWZ.h" #include "AnaConfig.h" #include "AnalysisBase.h" #include "TMath.h" #include "TVector3.h" #include "TKey.h" #include <iostream> #include "TPRegexp.h" #include <vector> #ifdef __MAKECINT__ #pragma link C++ class vector<vector<double> >+; #pragma link C++ class vector<vector<float> >+; #pragma link C++ class vector<vector<int> >+; #endif #ifdef GOODRUNLIST #include "GoodRunsLists/TGoodRunsList.h" #endif #ifdef APPLYJETCALIBRATION #include "ApplyJetCalibration/ApplyJetCalibration.h" #endif #ifdef MUONSMEARING #include "MuonMomentumCorrections/SmearingClass.h" #endif #ifdef ELECTRONSMEARING #include "egammaAnalysisUtils/EnergyRescalerUpgrade.h" #endif #ifdef PILEUPREWEIGHTING #include "PileupReweighting/TPileupReweighting.h" #endif #define UNITCONVERSION 0.001 ///========================================= /// Constructor ///========================================= EventBuilder_SMWZ::EventBuilder_SMWZ(TTree * /*tree*/) { } ///========================================= /// Destructor ///========================================= EventBuilder_SMWZ::~EventBuilder_SMWZ(){ } ///========================================= /// Initialize ///========================================= void EventBuilder_SMWZ::Initialize() { #ifdef PILEUPREWEIGHTING myPRW = (Root::TPileupReweighting*)fInput->FindObject("myPRW"); #endif #ifdef GOODRUNLIST myGRL = (Root::TGoodRunsList*)fInput->FindObject("myGRL"); #endif #ifdef APPLYJETCALIBRATION myJetCalibrationTool = (JetCalibrationTool*)fInput->FindObject("myJetCalibrationTool"); myJetCalibrationTool->UseGeV(true); #endif #ifdef MUONSMEARING myMuonSmear = (MuonSmear::SmearingClass*)fInput->FindObject("myMuonSmear"); #endif #ifdef ELECTRONSMEARING myErs = (egRescaler::EnergyRescalerUpgrade*)fInput->FindObject("myErs"); #endif } ///========================================= /// CopyEvent ///========================================= Bool_t EventBuilder_SMWZ::CopyEvent(AnalysisBase* evt) { // Copy the event from the TTree to the event class. Return false if you want to reject // event at the EventBuilder level using D3PD snippets, etc. static const MomKey mChannelNumber("ChannelNumber"); static const MomKey misMC("isMC"); fEvt = evt; ///=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= /// Get the overall configuration ///=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= if (fEvt->Debug()) cout << "EventBuilder_SMWZ: DEBUG CopyEvent() " << endl; /// Setup default options doBasic = true; doTruthLinks = false; doTruthJetLinks=false; doTrackJetLinks= false; doJetStructure = false; doConstituents = false; doTruthConstituents = false; doParentChild = false; doTrack = false; doLCCluster = false; doEMCluster = false; doTruth = false; doVertex = false; doPhotons = false; doSubjets = false; doElectrons = false; doMuons = false; doJets = false; doMET = false; doMiniIsolation = false; // Load option overides fEvt->Cfg()->Get("DOBASIC" , doBasic ); fEvt->Cfg()->Get("DOTRUTHLINKS" , doTruthLinks ); fEvt->Cfg()->Get("DOTRUTH" , doTruth ); fEvt->Cfg()->Get("DOTRACKJETLINKS" , doTrackJetLinks); fEvt->Cfg()->Get("DOJETSTRUCT" , doJetStructure ); fEvt->Cfg()->Get("DOCONSTIT" , doConstituents ); fEvt->Cfg()->Get("DOTRUTHCONSTIT" , doTruthConstituents ); fEvt->Cfg()->Get("DOPARENTCHILD" , doParentChild ); fEvt->Cfg()->Get("DOTRACK" , doTrack ); fEvt->Cfg()->Get("DOLCCLUSTER" , doLCCluster ); fEvt->Cfg()->Get("DOEMCLUSTER" , doEMCluster ); fEvt->Cfg()->Get("DOTRUTH" , doTruth ); fEvt->Cfg()->Get("DOVTX" , doVertex ); fEvt->Cfg()->Get("DOPHOTON" , doPhotons ); fEvt->Cfg()->Get("DOSUBJETS" , doSubjets ); fEvt->Cfg()->Get("DOELECTRONS" , doElectrons ); fEvt->Cfg()->Get("DOMUONS" , doMuons ); fEvt->Cfg()->Get("DOMINIISOLATION" , doMiniIsolation ); fEvt->Cfg()->Get("DOMET" , doMET ); fEvt->Cfg()->Get("DOJETS" , doJets ); fEvt->Cfg()->Get("GRL" , isGRL); if (fEvt->Debug()) cout << "EventBuilder_SMWZ::CopyEvent(): DEBUG Setting up configs" << endl; ///=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= /// BASIC OPTIONS: Run, Event, etc ///=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= if (doBasic) { if (fEvt->Debug()) cout << "EventBuilder_SMWZ::CopyEvent(): DEBUG Setting basic event level quantities" << endl; fEvt->Set("PassedGRL", true); #ifdef GOODRUNLIST if(myGRL) { if(!myGRL) Abort("GRL not loaded"); if(!myGRL->HasRunLumiBlock(Get<UInt_t>("RunNumber"), Get<UInt_t>("lbn"))) { cout << "did not pass" << endl; fEvt->Set("PassedGRL", false); } else { fEvt->Set("PassedGRL", true); } } #endif /// Overall event info fEvt->Set("RunNumber" , (int) Get<UInt_t>("RunNumber")); fEvt->Set("EventNumber" , (int) Get<UInt_t>("EventNumber")); fEvt->Set("EventWeight" , 1.0) ; // default value fEvt->Set("grl" , true); // default value fEvt->Set("larerror" , Get<int>("larError")); fEvt->Set("averageIntPerXing" , Get<Float_t>("averageIntPerXing")); fEvt->Set("LBN" , (int) Get<UInt_t>("lbn")); //fEvt->Set("BunchCrossingID" , (int) Get<UInt_t>("bcid")); int npv=0; for(int i=0; i < Get<Int_t>("vxp_n"); i++) { if(Get<vector<int> >("vxp_nTracks")[i] >= 2) npv++; } fEvt->Set("npv", npv); fEvt->Set("EF_mu18_tight_mu8_EFFS", Get<Bool_t>("EF_mu18_tight_mu8_EFFS")); fEvt->Set("EF_mu24i_tight", Get<Bool_t>("EF_mu24i_tight")); fEvt->Set("EF_mu36_tight", Get<Bool_t>("EF_mu36_tight")); fEvt->Set("EF_e24vhi_medium1", Get<Bool_t>("EF_e24vhi_medium1")); fEvt->Set("EF_e60_medium1", Get<Bool_t>("EF_e60_medium1")); fEvt->Set("EF_2e12Tvh_loose1", Get<Bool_t>("EF_2e12Tvh_loose1")); ///=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= /// Event level options ///=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= /// Determine if this is Monte Carlo or not /// by looking for the process ID = mc_channel_number if(BranchNames().find("mc_channel_number")!=BranchNames().end()) { //if(true) { //cout << (float) Get<Float_t>("mc_event_weight") << " or " << Get<vector<vector<double> > >("mcevt_weight")[0][0] << endl; fEvt->Set(mChannelNumber,(int)Get<UInt_t>("mc_channel_number")); fEvt->Set(misMC,true); float averageIntPerXing = Get<Float_t>("averageIntPerXing"); averageIntPerXing = (Get<UInt_t>("lbn")==1 && int(averageIntPerXing+0.5)==1) ? 0. : averageIntPerXing; #ifdef PILEUPREWEIGHTING float weight = myPRW->GetCombinedWeight(Get<UInt_t>("RunNumber"), Get<UInt_t>("mc_channel_number"), averageIntPerXing); fEvt->Set("PRWweight", weight); #endif fEvt->Set("MCweight", Get<Float_t>("mc_event_weight")); } else { fEvt->Set(misMC, false); fEvt->Set(mChannelNumber, 0); } if (fEvt->Debug()) cout << "EventBuilder_SMWZ::CopyEvent(): DEBUG Set event level quantities" << endl; } ///=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= /// BASIC OPTIONS: DEFAULT ///=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= else { if (fEvt->Debug()) cout << "EventBuilder_SMWZ::CopyEvent(): DEBUG doBasic = false. Setting event level quantities to 1" << endl; fEvt->Set(misMC , true); //if basic is off, we're almost certainly in MC only mode fEvt->Set("RunNumber" , 1); fEvt->Set("EventNumber" , 1); fEvt->Set("ChannelNumber" , (int) fEvt->Cfg()->Int("CHANNEL")); fEvt->Set("grl" , true); fEvt->Set("mcweight" , Get<Float_t>("mc_event_weight")); if(fEvt->Debug()) cout << "EventBuilder_SMWZ::CopyEvent(): DEBUG doBasic = false. Parameters set" << endl; } ///=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= /// BUILD EVENT ///=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= bool success = true; if(fEvt->Debug()) cout << "EventBuilder_SMWZ::CopyEvent(): About to build the full event" << endl; if(doMuons) success = success && CopyMuons(); if(doElectrons) success = success && CopyElectrons(); if(doJets) success = success && CopyJets(); if(doTrack) success = success && CopyTracks(); if(doTrack && doMuons && doMiniIsolation) success = success && AddMuonMiniIsolation(); if(fEvt->isMC() && doTruth) success = success && CopyTruth(); if(fEvt->isMC() && doTruth && doMuons) success = success && CopyMuonsTruth(); if(doMET) success = success & CopyMET(); if(fEvt->isMC() && doTruth && doMET) success = success & CopyTruthMET(); if(doLCCluster) success = success && CopyClusters(); /* success = success && CopyVertices(); success = success && AddTruthLinks(); success = success && CopyPhotons(); success = success && CopyJets(); success = success && AddTrackingInfo(); success = success && AddTruthJetLinks(); success = success && AddParentLinks(); success = success && AddConstituents(); success = success && AddBadJetType(); success = success && AddTriggers(); success = success && CopySubjets(); success = success && AddBtags();*/ /// The above need to be sorted by pt, Truth done by E fEvt->SortPtAll(); if (fEvt->Debug()) cout << "EventBuilder_SMWZ::CopyEvent(): DEBUG Done! Status = " << success << endl; return success; } Bool_t EventBuilder_SMWZ::CopyJets() { if (fEvt->Debug()) cout << "EventBuilder_SMWZ::CopyJets() Begin" << endl; TString prefix("jet_AntiKt4LCTopo_"); //TString prefix("jet_AntiKt4TopoEM_"); fEvt->AddVec("jets"); unsigned int nJets = Get<Int_t>(prefix + "n"); for(unsigned int iJ = 0; iJ < nJets; iJ++) { Particle *jet = new Particle(); jet->p.SetPtEtaPhiM( Get<vector<float> >(prefix + "pt")[iJ]*UNITCONVERSION, Get<vector<float> >(prefix + "eta")[iJ], Get<vector<float> >(prefix + "phi")[iJ], Get<vector<float> >(prefix + "m")[iJ]*UNITCONVERSION); int npv = fEvt->Int("npv"); #ifdef APPLYJETCALIBRATION jet->p = myJetCalibrationTool->ApplyJetAreaOffsetEtaJES( Get<vector<float> >(prefix + "constscale_E")[iJ]*UNITCONVERSION, Get<vector<float> >(prefix + "constscale_eta")[iJ], Get<vector<float> >(prefix + "constscale_phi")[iJ], Get<vector<float> >(prefix + "m")[iJ]*UNITCONVERSION, Get<vector<float> >(prefix + "ActiveAreaPx")[iJ]*UNITCONVERSION, Get<vector<float> >(prefix + "ActiveAreaPy")[iJ]*UNITCONVERSION, Get<vector<float> >(prefix + "ActiveAreaPz")[iJ]*UNITCONVERSION, Get<vector<float> >(prefix + "ActiveAreaE")[iJ]*UNITCONVERSION, Get<Float_t>("Eventshape_rhoKt4LC"), Get<Float_t>("averageIntPerXing"), npv ); #endif jet->Set("isBadLooseMinus", Get<vector<int> >(prefix + "isBadLooseMinus")[iJ]); jet->Set("jvtxf", Get<vector<float> >(prefix + "jvtxf")[iJ]); jet->Set("MV1", Get<vector<float> >(prefix + "flavor_weight_MV1")[iJ]); fEvt->Add("jets", jet); } if (fEvt->Debug()) cout << "EventBuilder_SMWZ::CopyJets() Done" << endl; return true; } Bool_t EventBuilder_SMWZ::CopyMET() { if (fEvt->Debug()) cout << "EventBuilder_SMWZ::CopyMET() Begin" << endl; fEvt->Set("MET_Et", Get<Float_t>("MET_RefFinal_et") * UNITCONVERSION); fEvt->Set("MET_Phi", Get<Float_t>("MET_RefFinal_phi")); if (fEvt->Debug()) cout << "EventBuilder_SMWZ::CopyMET() Done" << endl; return true; } Bool_t EventBuilder_SMWZ::CopyTruthMET() { if (fEvt->Debug()) cout << "EventBuilder_SMWZ::CopyTruthMET() Begin" << endl; fEvt->Set("TruthMET_Et", Get<Float_t>("MET_Truth_NonInt_et") * UNITCONVERSION); fEvt->Set("TruthMET_Phi", Get<Float_t>("MET_Truth_NonInt_phi")); if (fEvt->Debug()) cout << "EventBuilder_SMWZ::CopyTruthMET() Done" << endl; return true; } Bool_t EventBuilder_SMWZ::CopyMuons() { if (fEvt->Debug()) cout << "EventBuilder_SMWZ::CopyMuons() Begin" << endl; TString prefix("mu_staco_"); fEvt->AddVec("muons"); unsigned int nMuons = Get<Int_t>("mu_staco_n"); for(unsigned int iMu = 0; iMu < nMuons; iMu++) { Particle *muon = new Particle(); muon->Set("charge", Get<vector<int> >(prefix + "charge")[iMu]); muon->p.SetPtEtaPhiM( Get<vector<float> >(prefix + "pt")[iMu]*UNITCONVERSION, Get<vector<float> >(prefix + "eta")[iMu], Get<vector<float> >(prefix + "phi")[iMu], Get<vector<float> >(prefix + "m")[iMu]*UNITCONVERSION); muon->Set("id_qoverp", Get<vector<float> >(prefix + "id_qoverp")[iMu]/UNITCONVERSION); muon->Set("me_qoverp", Get<vector<float> >(prefix + "me_qoverp")[iMu]/UNITCONVERSION); muon->Set("id_qoverp_err", sqrt(Get<vector<float> >(prefix + "id_cov_qoverp_exPV")[iMu])/UNITCONVERSION); muon->Set("me_qoverp_err", sqrt(Get<vector<float> >(prefix + "me_cov_qoverp_exPV")[iMu])/UNITCONVERSION); muon->Set("id_pt", fabs(1.0/Get<vector<float> >(prefix + "id_qoverp")[iMu]) * sin(Get<vector<float> >(prefix + "id_theta")[iMu])*UNITCONVERSION); muon->Set("me_pt", fabs(1.0/Get<vector<float> >(prefix + "me_qoverp")[iMu]) * sin(Get<vector<float> >(prefix + "me_theta")[iMu])*UNITCONVERSION); #ifdef MUONSMEARING if(fEvt->Bool("isMC") && Get<vector<int> >(prefix + "isCombinedMuon")[iMu]) { myMuonSmear->SetSeed(fEvt->Int("EventNumber"), iMu); myMuonSmear->Event( muon->Float("id_pt"), muon->Float("me_pt"), Get<vector<float> >(prefix + "pt")[iMu]*UNITCONVERSION, Get<vector<float> >(prefix + "eta")[iMu], Get<vector<int> >(prefix + "charge")[iMu]); muon->p.SetPtEtaPhiM( myMuonSmear->pTCB(), Get<vector<float> >(prefix + "eta")[iMu], Get<vector<float> >(prefix + "phi")[iMu], Get<vector<float> >(prefix + "m")[iMu]*UNITCONVERSION); if(myMuonSmear->ChargeFlipCB() == -1) muon->Set("charge", -Get<vector<int> >(prefix + "charge")[iMu]); } #endif // Impact parameters muon->Set("d0", Get<vector<float> >(prefix + "trackd0pvunbiased")[iMu]); muon->Set("d0_err", Get<vector<float> >(prefix + "tracksigd0pvunbiased")[iMu]); muon->Set("z0", Get<vector<float> >(prefix + "trackz0pvunbiased")[iMu]); muon->Set("tracktheta", Get<vector<float> >(prefix + "tracktheta")[iMu]); muon->Set("isCombined", Get<vector<int> >(prefix + "isCombinedMuon")[iMu]); muon->Set("author", Get<vector<int> >(prefix + "author")[iMu]); // Quality muon->Set("nPixHits", Get<vector<int> >(prefix + "nPixHits")[iMu]); muon->Set("nPixDead", Get<vector<int> >(prefix + "nPixelDeadSensors")[iMu]); muon->Set("nPixHoles", Get<vector<int> >(prefix + "nPixHoles")[iMu]); muon->Set("nSCTHits", Get<vector<int> >(prefix + "nSCTHits")[iMu]); muon->Set("nSCTDead", Get<vector<int> >(prefix + "nSCTDeadSensors")[iMu]); muon->Set("nSCTHoles", Get<vector<int> >(prefix + "nSCTHoles")[iMu]); muon->Set("expectBLayerHit", Get<vector<int> >(prefix + "expectBLayerHit")[iMu]); muon->Set("nBLayerHits", Get<vector<int> >(prefix + "nBLHits")[iMu]); muon->Set("nTRTHits", Get<vector<int> >(prefix + "nTRTHits")[iMu]); muon->Set("nTRTOutliers", Get<vector<int> >(prefix + "nTRTOutliers")[iMu]); // Isolation cones muon->Set("Ptcone20", Get<vector<float> >(prefix + "ptcone20")[iMu]*UNITCONVERSION); muon->Set("Ptcone30", Get<vector<float> >(prefix + "ptcone30")[iMu]*UNITCONVERSION); muon->Set("Ptcone40", Get<vector<float> >(prefix + "ptcone40")[iMu]*UNITCONVERSION); muon->Set("Etcone20", Get<vector<float> >(prefix + "etcone20")[iMu]*UNITCONVERSION); muon->Set("Etcone30", Get<vector<float> >(prefix + "etcone30")[iMu]*UNITCONVERSION); muon->Set("Etcone40", Get<vector<float> >(prefix + "etcone40")[iMu]*UNITCONVERSION); muon->Set("Nucone20", Get<vector<float> >(prefix + "nucone20")[iMu]); muon->Set("Nucone30", Get<vector<float> >(prefix + "nucone30")[iMu]); muon->Set("Nucone40", Get<vector<float> >(prefix + "nucone40")[iMu]); fEvt->Add("muons", muon); } if (fEvt->Debug()) cout << "EventBuilder_SMWZ::CopyMuons() Done" << endl; return true; } Bool_t EventBuilder_SMWZ::CopyElectrons() { if (fEvt->Debug()) cout << "EventBuilder_SMWZ::CopyElectrons() Begin" << endl; //Constant for mass double electron_mass = 0.510998/1000.0; TString prefix("el_"); fEvt->AddVec("electrons"); unsigned int nElectrons = Get<Int_t>(prefix + "n"); for(unsigned int iE = 0; iE < nElectrons; iE++) { Particle *electron = new Particle(); electron->Set("charge", Get<vector<int> >(prefix + "charge")[iE]); electron->Set("d0_err", Get<vector<float> >(prefix + "tracksigd0pvunbiased")[iE]); electron->Set("z0", Get<vector<float> >(prefix + "trackz0pvunbiased")[iE]); electron->Set("d0", Get<vector<float> >(prefix + "trackd0pvunbiased")[iE]); // Quality electron->Set("nPixHits", Get<vector<int> >(prefix + "nPixHits")[iE]); electron->Set("nSCTHits", Get<vector<int> >(prefix + "nSCTHits")[iE]); electron->Set("mediumPP", (bool)Get<vector<int> >(prefix + "mediumPP")[iE]); electron->Set("tightPP", (bool)Get<vector<int> >(prefix + "tightPP")[iE]); electron->Set("loosePP", (bool)Get<vector<int> >(prefix + "loosePP")[iE]);/* electron->Set("tight", (bool)((quality_bitmask & (1 << 2)) >> 2)); electron->Set("medium", (bool)((quality_bitmask & (1 << 2)) >> 1)); electron->Set("loose", (bool)(quality_bitmask & 1)); */ electron->Set("author", Get<vector<int> >(prefix + "author")[iE]); electron->Set("OQ", Get<vector<unsigned int> >(prefix + "OQ")[iE]); // Pt/Eta/Phi electron->Set("tracktheta", Get<vector<float> >(prefix + "tracktheta")[iE]); electron->Set("trackEta", Get<vector<float> >(prefix + "tracketa")[iE]); electron->Set("trackPhi", Get<vector<float> >(prefix + "trackphi")[iE]); electron->Set("trackPt", Get<vector<float> >(prefix + "trackpt")[iE]*UNITCONVERSION); electron->Set("clusterEta", Get<vector<float> >(prefix + "cl_eta")[iE]); electron->Set("clusterPhi", Get<vector<float> >(prefix + "cl_phi")[iE]); electron->Set("clusterE", Get<vector<float> >(prefix + "cl_E")[iE]*UNITCONVERSION); /*if(electron->Int("nPixHits") + electron->Int("nSCTHits") >= 4) { electron->p.SetPtEtaPhiM( electron->Float("clusterE") / cosh(electron->Float("trackEta")), electron->Float("trackEta"), electron->Float("trackPhi"), electron_mass); cout << electron->p.Pt() << "," << Get<vector<float> >(prefix+ "pt")[iE]*UNITCONVERSION << endl; } else { electron->p.SetPtEtaPhiM( electron->Float("clusterE") / cosh(electron->Float("clusterEta")), electron->Float("clusterEta"), electron->Float("clusterPhi"), electron_mass); }*/ electron->p.SetPtEtaPhiM( Get<vector<float> >(prefix + "pt")[iE]*UNITCONVERSION, Get<vector<float> >(prefix + "eta")[iE], Get<vector<float> >(prefix + "phi")[iE], Get<vector<float> >(prefix + "m")[iE]*UNITCONVERSION); #ifdef ELECTRONSMEARING if(fEvt->Bool("isMC")) { myErs->SetRandomSeed(fEvt->Int("EventNumber") + 100*iE); electron->p *= myErs->getSmearingCorrection(electron->p.Eta(), electron->p.E()/UNITCONVERSION, egRescaler::EnergyRescalerUpgrade::NOMINAL); } #endif // Isolation cones electron->Set("Ptcone20", Get<vector<float> >(prefix + "ptcone20")[iE]*UNITCONVERSION); electron->Set("Ptcone30", Get<vector<float> >(prefix + "ptcone30")[iE]*UNITCONVERSION); electron->Set("Ptcone40", Get<vector<float> >(prefix + "ptcone40")[iE]*UNITCONVERSION); electron->Set("Etcone20", Get<vector<float> >(prefix + "Etcone20")[iE]*UNITCONVERSION); electron->Set("Etcone20_corrected", Get<vector<float> >(prefix + "Etcone20_pt_corrected")[iE]*UNITCONVERSION); electron->Set("Etcone30", Get<vector<float> >(prefix + "Etcone30")[iE]*UNITCONVERSION); electron->Set("Etcone40", Get<vector<float> >(prefix + "Etcone40")[iE]*UNITCONVERSION); fEvt->Add("electrons", electron); } if (fEvt->Debug()) cout << "EventBuilder_SMWZ::CopyElectrons() Done" << endl; return true; } Bool_t EventBuilder_SMWZ::CopyTracks() { if (fEvt->Debug()) cout << "EventBuilder_SMWZ::CopyTracks() Begin" << endl; fEvt->AddVec("tracks"); unsigned int nTracks = Get<Int_t>("trk_n"); for(int iT=0; iT < nTracks; iT++) { Particle *track = new Particle(); track->p.SetPtEtaPhiM( Get<vector<float> >("trk_pt")[iT] * UNITCONVERSION, Get<vector<float> >("trk_eta")[iT], Get<vector<float> >("trk_phi_wrtPV")[iT], 0); int charge = round(Get<vector<float> >("trk_qoverp_wrtPV")[iT]/UNITCONVERSION * track->p.P()); track->Set("charge", charge); track->Set("d0", Get<vector<float> >("trk_d0_wrtPV")[iT]); track->Set("z0", Get<vector<float> >("trk_z0_wrtPV")[iT]); TString prefix("trk_"); track->Set("nPixHits", Get<vector<int> >(prefix + "nPixHits")[iT]); track->Set("nPixDead", Get<vector<int> >(prefix + "nPixelDeadSensors")[iT]); track->Set("nPixHoles", Get<vector<int> >(prefix + "nPixHoles")[iT]); track->Set("nSCTHits", Get<vector<int> >(prefix + "nSCTHits")[iT]); track->Set("nSCTDead", Get<vector<int> >(prefix + "nSCTDeadSensors")[iT]); track->Set("nSCTHoles", Get<vector<int> >(prefix + "nSCTHoles")[iT]); track->Set("expectBLayerHit", Get<vector<int> >(prefix + "expectBLayerHit")[iT]); track->Set("nBLayerHits", Get<vector<int> >(prefix + "nBLHits")[iT]); fEvt->Add("tracks", track); } if (fEvt->Debug()) cout << "EventBuilder_SMWZ::CopyTracks() Done" << endl; return true; } Bool_t EventBuilder_SMWZ::CopyClusters() { if (fEvt->Debug()) cout << "EventBuilder_SMWZ: DEBUG CopyClusters() " << endl; fEvt->AddVec("clustersLCTopo"); for(unsigned int iCl = 0; iCl < Get<UInt_t>("cl_n"); iCl++) { Particle* cl = new Particle(); float pt = Get<vector<float> >("cl_pt") .at(iCl); float eta = Get<vector<float> >("cl_eta").at(iCl); float phi = Get<vector<float> >("cl_phi").at(iCl); cl->p.SetPtEtaPhiM(pt*UNITCONVERSION,eta,phi,0); fEvt->Add("clustersLCTopo",cl); } if (fEvt->Debug()) cout << "EventBuilder_SMWZ::CopyClusters(): scheduled clusters" << endl; return kTRUE; } Bool_t EventBuilder_SMWZ::AddMuonMiniIsolation() { if (fEvt->Debug()) cout << "EventBuilder_SMWZ::AddMuonMiniIsolation() Begin" << endl; for(int iMu=0; iMu < fEvt->muons(); iMu++) { Particle &mu = fEvt->muon(iMu); double miniiso5 = 0; double miniiso10 = 0; double miniiso15 = 0; double miniiso20 = 0; double miniiso25 = 0; double miniiso30 = 0; double miniiso35 = 0; double miniiso40 = 0; double miniiso45 = 0; double miniiso60 = 0; double miniiso80 = 0; double miniiso100 = 0; double miniiso45max30 = 0; double iso40 = 0; double iso30 = 0; double iso20 = 0; for(int iT=0; iT < fEvt->tracks(); iT++) { if(fEvt->track(iT).p.Pt() < 1.0) continue; if(fabs(fEvt->track(iT).Float("d0")) > 1.5) continue; if(fabs(fEvt->track(iT).Float("z0")) > 1.0) continue; if(fEvt->track(iT).Int("expectBLayerHit") == 1 && fEvt->track(iT).Int("nBLayerHits") == 0) continue; if(fEvt->track(iT).Int("nPixHits") + fEvt->track(iT).Int("nPixDead") < 2) continue; if(fEvt->track(iT).Int("nPixHits") + fEvt->track(iT).Int("nPixDead") + fEvt->track(iT).Int("nSCTDead") + fEvt->track(iT).Int("nSCTHits") < 7) continue; if(fEvt->track(iT).Int("nPixHits") + fEvt->track(iT).Int("nSCTHits") < 3) continue; //if(fEvt->track(iT).Int("nPixHoles") > 0) continue; double deltar = fEvt->track(iT).p.DeltaR(mu.p); if(deltar < 0.004) continue; if(deltar < 5.0 / mu.p.Pt()) miniiso5 += fEvt->track(iT).p.Pt(); if(deltar < 10.0 / mu.p.Pt()) miniiso10 += fEvt->track(iT).p.Pt(); if(deltar < 15.0 / mu.p.Pt()) miniiso15 += fEvt->track(iT).p.Pt(); if(deltar < 20.0 / mu.p.Pt()) miniiso20 += fEvt->track(iT).p.Pt(); if(deltar < 25.0 / mu.p.Pt()) miniiso25 += fEvt->track(iT).p.Pt(); if(deltar < 30.0 / mu.p.Pt()) miniiso30 += fEvt->track(iT).p.Pt(); if(deltar < 35.0 / mu.p.Pt()) miniiso35 += fEvt->track(iT).p.Pt(); if(deltar < 40.0 / mu.p.Pt()) miniiso40 += fEvt->track(iT).p.Pt(); if(deltar < 45.0 / mu.p.Pt()) miniiso45 += fEvt->track(iT).p.Pt(); if(deltar < 60.0 / mu.p.Pt()) miniiso60 += fEvt->track(iT).p.Pt(); if(deltar < 80.0 / mu.p.Pt()) miniiso80 += fEvt->track(iT).p.Pt(); if(deltar < 100.0 / mu.p.Pt()) miniiso100 += fEvt->track(iT).p.Pt(); if(deltar < (45.0 / mu.p.Pt() > 0.3 ? 0.3 : 45.0 / mu.p.Pt())) miniiso45max30 += fEvt->track(iT).p.Pt(); if(deltar < 0.4) iso40 += fEvt->track(iT).p.Pt(); if(deltar < 0.3) iso30 += fEvt->track(iT).p.Pt(); if(deltar < 0.2) iso20 += fEvt->track(iT).p.Pt(); } mu.Set("PtconeMini5", miniiso5); mu.Set("PtconeMini10", miniiso10); mu.Set("PtconeMini15", miniiso15); mu.Set("PtconeMini20", miniiso20); mu.Set("PtconeMini25", miniiso25); mu.Set("PtconeMini30", miniiso30); mu.Set("PtconeMini35", miniiso35); mu.Set("PtconeMini40", miniiso40); mu.Set("PtconeMini45", miniiso45); mu.Set("PtconeMini60", miniiso60); mu.Set("PtconeMini80", miniiso80); mu.Set("PtconeMini100", miniiso100); mu.Set("PtconeMini45Max30", miniiso45max30); mu.Set("Ptcone40my", iso40); mu.Set("Ptcone30my", iso30); mu.Set("Ptcone20my", iso20); } if (fEvt->Debug()) cout << "EventBuilder_SMWZ::AddMuonMiniIsolation() Done" << endl; return true; } Bool_t EventBuilder_SMWZ::CopyMuonsTruth() { if (fEvt->Debug()) cout << "EventBuilder_SMWZ::CopyMuonsTruth() Begin" << endl; fEvt->AddVec("truthsmuons"); unsigned int nTruth = Get<Int_t>("muonTruth_n"); for(unsigned int iT = 0; iT < nTruth; iT++) { Particle *truth = new Particle(); truth->p.SetPtEtaPhiM( Get<vector<float> >("muonTruth_pt")[iT]*UNITCONVERSION, Get<vector<float> >("muonTruth_eta")[iT], Get<vector<float> >("muonTruth_phi")[iT], Get<vector<float> >("muonTruth_m")[iT]*UNITCONVERSION); // Deduplicator /* int add=1; for(unsigned int iT2 = 0; iT2 < fEvt->Objs("truthsmuons"); iT2++) { if(fEvt->truth(iT2, "muons").p.DeltaR(truth->p) < 0.01) { add = 0; break; } } if(add == 0) { delete truth; break; }*/ truth->Set("charge", Get<vector<float> >("muonTruth_charge")[iT]); truth->Set("origin", Get<vector<int> >("muonTruth_origin")[iT]); fEvt->Add("truthsmuons", truth); } if (fEvt->Debug()) cout << "EventBuilder_SMWZ::CopyMuonsTruth() Done" << endl; return true; } Bool_t EventBuilder_SMWZ::CopyTruth() { if (fEvt->Debug()) cout << "EventBuilder_SMWZ::CopyTruth() Begin" << endl; fEvt->AddVec("truths"); map<int, Particle *> truths_by_ntuple_index; unsigned int nTruth = Get<Int_t>("mc_n"); for(unsigned int iT = 0; iT < nTruth; iT++) { int status = Get<vector<int> >("mc_status")[iT]; //if(status != 1 && status != 2 && status != 4) continue; //Recommendation from https://twiki.cern.ch/twiki/bin/viewauth/AtlasProtected/PhysicsAnalysisWorkBookExMCRel15 Particle *truth = new Particle(); truth->p.SetPtEtaPhiM( Get<vector<float> >("mc_pt")[iT]*UNITCONVERSION, Get<vector<float> >("mc_eta")[iT], Get<vector<float> >("mc_phi")[iT], Get<vector<float> >("mc_m")[iT]*UNITCONVERSION); truth->Set("pdgId", Get<vector<int> >("mc_pdgId")[iT]); truth->Set("barcode", Get<vector<int> >("mc_barcode")[iT]); truth->Set("status", status); truth->Set("_indexinntup", iT); truth->AddVec("children", true); // weak reference truth->AddVec("parents"); // weak reference fEvt->Add("truths", truth); truths_by_ntuple_index.insert( pair<int, Particle *>(iT, truth) ); } // Build parent/children arrays for(int iT = 0; iT < fEvt->truths(); iT++) { Particle *truth = &fEvt->truth(iT); int index = truth->Int("_indexinntup"); vector<int> index_parents = Get<vector<vector<int> > >("mc_parent_index")[index]; for(int iT2=0; iT2 < index_parents.size(); iT2++) { int index_parent = index_parents[iT2]; // Go look for the parent using the ntup map map<int, Particle *>::iterator it = truths_by_ntuple_index.find(index_parent); // Did we find a parent: if so do something if(it != truths_by_ntuple_index.end()) { Particle *truth_parent = (*it).second; truth_parent->Add("children", truth); truth->Add("parents", truth_parent); } } } if (fEvt->Debug()) cout << "EventBuilder_SMWZ::CopyTruth() Done" << endl; return true; } ///========================================= /// WriteAuxTrees ///========================================= void EventBuilder_SMWZ::WriteAuxTrees(TDirectory* outfile) { if (fEvt->Debug()) cout << "EventBuilder_SMWZ: DEBUG WriteAuxTrees() " << endl; }
c76e4bbca7ad1796c0fa16c53fd17dbcff2291b0
ee99c05afa22e204812e1e19dff0b1ff36bec739
/include/ast/EvalInputNode.h
a3ad8a0d9bf4bcbbe84fa24093559a5facb7b28a
[ "BSL-1.0" ]
permissive
stenbror/PythonCoreNative
ab4c3c18f9ed73ee7e9588c349191bb8bd0bfed1
9b5b1e55acf7d6adc7d8202e951872b2b9f71167
refs/heads/master
2023-05-30T04:07:48.480731
2021-06-20T16:37:23
2021-06-20T16:37:23
361,491,052
0
1
BSL-1.0
2021-05-24T11:23:55
2021-04-25T17:16:41
C++
UTF-8
C++
false
false
969
h
EvalInputNode.h
#pragma once #include <ast/StatementNode.h> #include <ast/ExpressionNode.h> #include <Token.h> #include <memory> #include <vector> namespace PythonCoreNative::RunTime::Parser::AST { class EvalInputNode : public StatementNode { public: EvalInputNode( unsigned int start, unsigned int end, std::shared_ptr<std::vector<std::shared_ptr<Token>>> newlines, std::shared_ptr<ExpressionNode> right, std::shared_ptr<Token> eof ); std::shared_ptr<std::vector<std::shared_ptr<Token>>> GetNewlines(); std::shared_ptr<ExpressionNode> GetRight(); std::shared_ptr<Token> GetEof(); protected: std::shared_ptr<std::vector<std::shared_ptr<Token>>> mNewlines; std::shared_ptr<ExpressionNode> mRight; std::shared_ptr<Token> mEof; }; }
d8d07634d803f9646035f8e50baed030f5195b46
a2cef9db3c6e7d6a5f34ad4c6c313c2c2575e8a1
/Ifrad/menu_customer.h
34f996d7d251fa5366e3de75675e2d7720cadc03
[]
no_license
Ridwan230/Restaurant-Management-System
69c6650e9cdaeade86a37b6d7144e4f6139d3b85
de8e942ff4c5b152de703359268260917092284b
refs/heads/master
2022-12-12T18:17:15.155048
2020-09-14T09:10:57
2020-09-14T09:10:57
250,228,245
0
2
null
null
null
null
UTF-8
C++
false
false
973
h
menu_customer.h
#ifndef MENU_CUSTOMER_H #define MENU_CUSTOMER_H #include <QDialog> #include "menu_last.h" namespace Ui { class menu_customer; } class menu_customer : public QDialog { Q_OBJECT public: explicit menu_customer(QWidget *parent = nullptr); ~menu_customer(); private slots: void on_Burger_quantity_pos_pushButton_clicked(); void on_Burger_quantity_neg_pushButton_clicked(); void on_Fries_quantity_pos_pushButton_clicked(); void on_Fries_quantity_neg_pushButton_clicked(); void on_Drinks_quantity_pos_pushButton_clicked(); void on_Drinks_quantity_neg_pushButton_clicked(); void on_Back_pushButton_clicked(); void on_Burger_img_pushButton_clicked(); void on_Fries_img_pushButton_clicked(); void on_Drinks_img_pushButton_clicked(); void on_Confirm_pushButton_clicked(); private: Ui::menu_customer *ui; menu_last *menu_lst; }; #endif // MENU_CUSTOMER_H
713c744b8b8834d6feccfa93e4d0048f51e8fa25
df23fd83cfd786980ae55a9541d9c1d701b2bf19
/code/realtime/animatedcharacterbuffers.hpp
3068ae873438487e27f3f6c4cf2cbcda8b4dfb08
[ "MIT" ]
permissive
sidsahay/nidra
0f5202e01b9a33c2d2373888817f716c897da02f
c99702ac144c925daa1e9e3f7bac94cdc1f3ef5e
refs/heads/master
2020-04-01T00:53:25.456654
2018-10-12T11:17:24
2018-10-12T11:17:24
152,717,503
0
0
null
null
null
null
UTF-8
C++
false
false
958
hpp
animatedcharacterbuffers.hpp
#ifndef NIDRA_CODE_ANIMATEDCHARACTERBUFFERS_HPP #define NIDRA_CODE_ANIMATEDCHARACTERBUFFERS_HPP #include "../scene/animatedcharacterdata.hpp" #include "../utilities/shader.hpp" #include "../utilities/texture.hpp" struct AnimatedCharacterBuffers { explicit AnimatedCharacterBuffers(const AnimatedCharacterData &character); ~AnimatedCharacterBuffers(); const AnimatedCharacterData &character; std::vector<GLuint> vertexBuffers; std::vector<GLuint> uvBuffers; std::vector<GLuint> normalBuffers; std::vector<GLuint> elementBuffers; std::vector<GLuint> vboneBuffers; GLint matrixID; GLint viewMatrixID; GLint modelMatrixID; GLint lightID; GLint boneXformArrayID; GLuint shaderProgramID; GLuint textureID; GLint textureSamplerID; bool isBuilt = false; void Build(); void Render(); void UpdateLight(const vec3 &light); }; #endif //NIDRA_CODE_ANIMATEDCHARACTERBUFFERS_HPP
b08d82687207740444a8da5d5709fff3a94e172c
642a5d419fa4464e1c9ab88ec109a29ee7f180b1
/FanxyStudio/finddialog.h
0b6f434a6b722142a829ebc22c853cb16c5ad88e
[]
no_license
Hedgefog/fanxy-studio
35b734b86262b0a2cc1def5a9e12571b82db3138
d09fa53d39a6556b2cfa12da7f71d2216c7b3497
refs/heads/master
2021-01-11T20:45:39.288485
2017-01-18T22:34:15
2017-01-18T22:34:15
79,178,971
2
0
null
null
null
null
UTF-8
C++
false
false
668
h
finddialog.h
#ifndef FINDDIALOG_H #define FINDDIALOG_H #include <QDialog> #include <QPlainTextEdit> #include <QPlainTextEdit> namespace Ui { class FindDialog; } class FindDialog : public QDialog { Q_OBJECT public: explicit FindDialog(QPlainTextEdit *target); ~FindDialog(); protected: QPlainTextEdit *m_target; public slots: void show(); void find(); protected slots: void on_findButton_clicked(); void on_replaceButton_clicked(); void on_replaceAllButton_clicked(); void on_cancelButton_clicked(); private: Ui::FindDialog *ui; }; #endif // FINDDIALOG_H
21ace004489d326004afba633b8702192940fb70
c08f8bd82cb6c50a888e4fa403b183662395874a
/multsetPq/ANUMLA.cpp
7b2f33f8ca52bb476d08a47995079a2081ea6d01
[]
no_license
vaibhavgeek/tompetitive
253a744771b558e8e727a2ad57bc4f2ceebc6c4a
8d887d10936f22286f48aa1cf328a7d46e28aa0c
refs/heads/master
2021-06-12T10:12:39.941473
2021-05-29T14:11:40
2021-05-29T14:11:40
202,127,253
0
0
null
null
null
null
UTF-8
C++
false
false
1,138
cpp
ANUMLA.cpp
#include <bits/stdc++.h> using namespace std; #define ll long long int main() { ll t; cin>>t; while(t--){ int n; cin>>n; int subsno = pow(2,n); multiset <int> sum_set; for(int i = 1; i <= subsno; i++) { int sum; cin>>sum; sum_set.insert(sum); } vector <long long> subset_sums; vector <int> original_array; sum_set.erase(0); subset_sums.push_back(0); while(original_array.size() < n) { multiset <int> :: iterator it = sum_set.begin(); int current_element = *it; int current_subset_sum_stored = subset_sums.size(); for(int i = 0; i < current_subset_sum_stored; i++) { multiset <int> :: iterator it2 = sum_set.find(current_element + subset_sums[i]); int current_sum = *it2; sum_set.erase(it2); subset_sums.push_back(current_sum); } original_array.push_back(current_element); } for(int i = 0; i < n; i++) cout<<original_array[i]<<" "; cout<<endl; } // your code goes here return 0; }
153e0c660db1c5c0945133ebb07e8066e5059932
74a31a9666df200ab18c44566f2227d031823b23
/alabs0002/Classes/depends/scribble/ScribbleSpineNode.h
260d4e3366083dcd3b04052d7b12f3d5cc5ff9ad
[]
no_license
Crasader/Demo_Earlier_CC
448f3447fc3fb237c2346069bf2344f44bd552db
320c57f91b7d6603a6293b65a6702f76b1e035ba
refs/heads/master
2020-12-04T12:24:47.254647
2018-05-31T02:51:24
2018-05-31T02:51:24
null
0
0
null
null
null
null
UTF-8
C++
false
false
997
h
ScribbleSpineNode.h
// // ScribbleSpineNode.h // // // Created by renhong on 16/1/8. // // #ifndef ScribbleSpineNode_h #define ScribbleSpineNode_h #ifdef SCRIBBLE_USE_SPINE #include <stdio.h> #include "spine/spine-cocos2dx.h" #include "spine/extension.h" #include "ScribbleNode.h" #include "cocos2d.h" using namespace cocos2d; using namespace spine; #define ScribbleSpineAtlasPage "ScribbleSpineAtlasPage" class ScribbleSpineNode : public ScribbleTouchNode{ public: static ScribbleSpineNode *create(Size pCanvasSize); ScribbleSpineNode(); ~ScribbleSpineNode(); bool init(Size pCanvasSize); void displaySkin(); protected: void update(float dt); spAtlasPage* createScribbleAtlasPage(); void displayScribbleAtlasPage(spAtlasPage* atlasPage, spAtlasRegion* region); private: float* _worldVertices; CC_SYNTHESIZE(SkeletonAnimation *, _skeletonAnimation, SkeletonAnimation); CC_SYNTHESIZE(spSlot *, _slot, Slot); }; #endif #endif /* ScribbleSpineNode_hpp */
84ccc23416514b57451dd338fa8107c76db15c1a
68263901ba61a333c9ae6558396187e9fe54f6bd
/ce_dd_bootsectors/convertor.cpp
5a5efd78983520359babaede9794f3555479abc1
[]
no_license
miniupnp/ce-atari
b906fc2fbb2d51b46b97f076ab085465ccac0913
78a3d85de852ec20776061b130058f67f5749ca8
refs/heads/master
2023-08-22T18:54:13.641510
2019-08-15T18:16:46
2019-08-15T18:16:46
56,238,691
0
0
null
2016-04-14T13:15:25
2016-04-14T13:15:24
null
UTF-8
C++
false
false
5,871
cpp
convertor.cpp
#include <stdio.h> #include <stdlib.h> #include <string.h> #define CE_DD_PRG_PATH "../ce_dd_prg/" #define BYTE unsigned char #define WORD unsigned short #define DWORD unsigned int WORD swapNibbles(WORD val); bool createBootsectorFromPrg(const char *path, const char *inFile, const char *outFile, bool bootsectorNotRaw); void checkCeddSize(void); DWORD getValue(BYTE *p); void createImage(void); int main(int argc, char *argv[]) { const char * path = "./"; /*const char *path = "c:\\!nohaj\\tmp\\assembla_atarijookie\\trunk\\ce_dd_bootsectors";*/ if(argc > 1) path = argv[1]; createBootsectorFromPrg(path, "bs.prg", "ce_dd.bs", true); createBootsectorFromPrg(path, "bs_l2.prg", "ce_dd_l2.bs", false); #if 0 checkCeddSize(); createImage(); #endif /*getchar();*/ return 0; } bool createBootsectorFromPrg(const char *path, const char *inFile, const char *outFile, bool bootsectorNotRaw) { printf("\nConvert: %s -> %s\n", inFile, outFile); char bfr[512]; memset(bfr, 0, 512); bfr[0] = 0x60; // store magic word bfr[1] = 0x1c; char fullInFile [256]; char fullOutFile[256]; snprintf(fullInFile, sizeof(fullInFile), "%s%s", path, inFile); snprintf(fullOutFile, sizeof(fullOutFile), "%s%s", path, outFile); //--------------------------------------- // read the boot code to buffer FILE *bc = fopen(fullInFile, "rb"); if(!bc) { printf("\nCould not open INPUT file: %s\n", fullInFile); return false; } fseek (bc, 0, SEEK_END); // move to end int fsize = ftell(bc) - 256; // get file size fseek(bc, 256, SEEK_SET); // skip TOS prog header int offset = 0x1e; int len = 512 - 32; if(!bootsectorNotRaw) { // if it's raw sector, the offset and length are different offset = 0; len = 512; } int cnt = fread(&bfr[offset], 1, len, bc); if(fsize > len) { printf("\nFile is bigger than what we can use! Is the bootcode too long? (usable space: %d, this file size: %d)\n", len, fsize); } fclose(bc); //--------------------------------------- // create the check sum WORD sum = 0, val; WORD *p = (WORD *) bfr; for(int i=0; i<255; i++) { val = *p; val = swapNibbles(val); sum += val; p++; } if(bootsectorNotRaw) { // do checksum only if not raw WORD cs = 0x1234 - sum; sum = sum & 0xffff; printf("sum %04x, check-sum is %04x, check is %04x, free space: %d bytes\n", sum, cs, (cs + sum) & 0xffff, len - cnt); bfr[510] = cs >> 8; // store the check sum bfr[511] = cs; } //--------------------------------------- // now write it to file FILE *bs = fopen(fullOutFile, "wb"); if(!bs) { printf("\nCould not open OUTPUT file: %s\n", fullOutFile); return false; } fwrite(bfr, 1, 512, bs); fclose(bs); printf("Done : %s -> %s\n", inFile, outFile); return true; } void createImage(void) { BYTE bfr[1024*1024]; // open output file FILE *out = fopen("ceddboot.img", "wb"); if(!out) { printf("\ncreateImage - could not open OUTPUT file!\n"); getchar(); return; } DWORD cnt = 0; //-------------------------- // read and write bootsector FILE *in = fopen("bootsect.bin", "rb"); if(!in) { fclose(out); printf("\ncreateImage - could not open bootsector file (001)!\n"); getchar(); return; } int res = fread(bfr, 1, 512, in); // read and write bootsector if(res >= 0) { cnt += res; } fclose(in); fwrite(bfr, 1, 512, out); //-------------------------- // read and write the driver in = fopen(CE_DD_PRG_PATH "ce_dd.prg", "rb"); if(!in) { fclose(out); printf("\ncreateImage - could not open driver file (002)!\n"); getchar(); return; } res = fread(bfr, 1, 1024*1024, in); // read and write driver if(res >= 0) { cnt += res; } fclose(in); fwrite(bfr, 1, res, out); //-------------------------- // pad with zeros to make full sectors int mod = cnt % 512; int add = 1024 - mod; memset(bfr, 0, add); fwrite(bfr, 1, add, out); //-------------------------- // pad to 5MB for STEEM Pasti memset(bfr, 0, 1024*1024); for(int i=0; i<5; i++) { fwrite(bfr, 1, 1024*1024, out); } fclose(out); printf("\nCEDDBOOT.IMG created.\n"); } void checkCeddSize(void) { FILE *f = fopen(CE_DD_PRG_PATH "ce_dd.prg", "rb"); if(!f) { printf("\nCould not open ce_dd.prg file!\n"); getchar(); return; } char bfr[20]; fread(bfr, 1, 20, f); fclose(f); DWORD tsize, dsize, bsize; tsize = getValue((BYTE *)(bfr + 2)); dsize = getValue((BYTE *)(bfr + 6)); bsize = getValue((BYTE *)(bfr + 10)); printf("\n\nCEDD driver \n"); printf("text size: %d\n", tsize); printf("data size: %d\n", dsize); printf("bss size: %d\n", bsize); printf("TOTAL size: %d\n", tsize + dsize + bsize); } DWORD getValue(BYTE *p) { DWORD val = 0; val = ((DWORD) p[0]); val = val << 8; val = val | ((DWORD) p[1]); val = val << 8; val = val | ((DWORD) p[2]); val = val << 8; val = val | ((DWORD) p[3]); return val; } WORD swapNibbles(WORD val) { WORD a,b; a = val >> 8; // get upper b = val & 0xff; // get lower return ((b << 8) | a); }
b987b3367c1ff8b204c23e691f35b286290234f9
4347d54df89b71ed4171afdf0105ca7f13941122
/leetcode9.cpp
beae4da3f25881d9718d7ae908800abf982df8c9
[]
no_license
369713387/Leetcode-Note
547c993ea5adef1f4e6c0ffc3d862aca13acf81a
03e1a155f7a5105a04a8545b837c26e31a80f51f
refs/heads/master
2020-03-31T11:57:15.791163
2018-12-20T03:36:01
2018-12-20T03:36:01
152,197,406
0
0
null
null
null
null
UTF-8
C++
false
false
356
cpp
leetcode9.cpp
#include<iostream> using namespace std; bool isPalindrome(int x) { if (x < 0) { return false; } if (x >= 0 && x <= 9) { return true; } long long res = 0; long long val = x; while (x) { res = res * 10 + x % 10; x /= 10; } if (res == val) { return true; } return false; } void main() { bool flag = isPalindrome(2147483647); return; }
77a453a0fe6e1cfd96072dc9490abc6356563f48
2c3d58b7dcdf38c7d04bdc2b3fd269f713abce26
/27oct/Is your horseshoe on the other hoof.cpp
dd65d30636b4b1e99a486a58416f573c47c4d111
[]
no_license
deepralhan26/Dailycodeforces
1d5dd7f63bcb7d146b0925fdc1094d3045fff419
18a41e7d60f7c475d151123c10c5874e06a1cc7a
refs/heads/main
2023-01-03T21:38:01.548115
2020-10-31T21:34:55
2020-10-31T21:34:55
307,508,509
0
0
null
null
null
null
UTF-8
C++
false
false
346
cpp
Is your horseshoe on the other hoof.cpp
#include <bits/stdc++.h> using namespace std; #define IOS ios::sync_with_stdio(0); cin.tie(0); cout.tie(0); #define int long long int32_t main() { IOS; int s1,s2,s3,s4; cin>>s1>>s2>>s3>>s4; set<int>a; a.insert(s1); a.insert(s2); a.insert(s3); a.insert(s4); cout<<4 - a.size(); return 0; }
67316220a4f4c65050337cf0d52a509b51db0295
54c67306d63bb69a5cf381d12108d3dc98ae0f5d
/goalc/simple_main.cpp
fe14bbb1deed6ee13a477ebaf094b1a150c29e01
[ "ISC" ]
permissive
open-goal/jak-project
adf30a3459c24afda5b180e3abe1583c93458a37
d96dce27149fbf58586160cfecb634614f055943
refs/heads/master
2023-09-01T21:51:16.736237
2023-09-01T16:10:59
2023-09-01T16:10:59
289,585,720
1,826
131
ISC
2023-09-14T13:27:47
2020-08-22T23:55:21
Common Lisp
UTF-8
C++
false
false
1,577
cpp
simple_main.cpp
#include "common/log/log.h" #include "common/util/FileUtil.h" #include "common/versions/versions.h" #include "goalc/compiler/Compiler.h" int main(int argc, char** argv) { // logging lg::set_stdout_level(lg::level::info); lg::set_flush_level(lg::level::info); lg::initialize(); // game version std::string game = "jak1"; if (argc > 1) { game = argv[1]; } GameVersion game_version = game_name_to_version(game); // path if (!file_util::setup_project_path(std::nullopt)) { return 1; } lg::info("OpenGOAL Compiler {}.{}", versions::GOAL_VERSION_MAJOR, versions::GOAL_VERSION_MINOR); std::unique_ptr<Compiler> compiler; ReplStatus status = ReplStatus::OK; try { compiler = std::make_unique<Compiler>(game_version, std::nullopt, "", std::make_unique<REPL::Wrapper>(game_version)); while (status != ReplStatus::WANT_EXIT) { if (status == ReplStatus::WANT_RELOAD) { lg::info("Reloading compiler..."); if (compiler) { compiler->save_repl_history(); } compiler = std::make_unique<Compiler>(game_version, std::nullopt, "", std::make_unique<REPL::Wrapper>(game_version)); status = ReplStatus::OK; } std::string input_from_stdin = compiler->get_repl_input(); if (!input_from_stdin.empty()) { status = compiler->handle_repl_string(input_from_stdin); } } } catch (std::exception& e) { lg::error("Compiler Fatal Error: {}", e.what()); } return 0; }
3b75b02cd2db9461d70b6ae64f6bef56d6d57d8b
a18168091fd6a5ea575c7bc5906cefada0b7c3f0
/arduino/fetchable-client/fetchable-client.ino
8fc0404619501913847dcfcd380eec5db67980ef
[]
no_license
Skandalik/imperius-arduino
7860df2dbeeec616c41721c9fd5e9f6848b8ced8
d59ece20da1b57d2531676b1f59375e4bfaaad74
refs/heads/master
2021-04-27T10:37:22.427991
2018-02-22T22:09:03
2018-02-22T22:09:03
122,541,149
0
0
null
null
null
null
UTF-8
C++
false
false
7,194
ino
fetchable-client.ino
#include <DHT.h> #include <ArduinoJson.h> #include <EEPROM.h> #include <ESP8266WiFi.h> #include <PubSubClient.h> #include <ESP8266TrueRandom.h> // CONSTANTS #define UUID_SIZE 16 #define SENSOR_ID_SIZE 70 #define SENSOR_ID_INIT_FLAG 1 #define DHT_PIN 2 #define DHT_TYPE DHT11 // GLOBAL VARIABLES // Address pointer and sensor ID variables int addressPointer = 0; String sensorId; char sensorIdToEeprom[SENSOR_ID_SIZE]; // Flag variables boolean registeredFlag = false; boolean switchable = false; boolean adjustable = false; boolean fetchable = true; // WiFi credentials const char *ssid = "HomeWifi"; const char *password = "B0Wkup%3$il4*"; // MQTT Server address const char *mqtt_server = "192.168.1.102"; // OBJECTS DECLARATION WiFiClient wifiClient; PubSubClient client(wifiClient); StaticJsonBuffer<200> jsonBuffer; DHT dht(DHT_PIN, DHT_TYPE); // ADDITIONAL VARIABLES unsigned long tempTime = 0; const long interval = 10000; float sensorStatus; String statusString; // TOPICS String TOPIC_PREFIX = "sensor/"; String responseTopic = TOPIC_PREFIX + "response"; String registeredTopic; String checkStatusTopic; String allCheckStatusTopic; String checkStatusResponseTopic; void setup() { Serial.begin(115200); Serial.println(); delay(1000); dht.begin(); sensorStatus = dht.readHumidity(); fetchSensorStatus(); createSensorId(); // handleSensorId(); setupWifi(); setupMqtt(); } void loop() { unsigned long timeDelay = millis(); if (!client.connected()) { reconnect(); } if (!client.loop()) client.connect(sensorIdToEeprom); if ((timeDelay - tempTime >= interval) && !registeredFlag) { tempTime = timeDelay; sendRegisterBroadcastMessage(client); } } void fetchSensorStatus() { statusString = ""; do { sensorStatus = dht.readHumidity(); } while (isnan(sensorStatus)); Serial.print("Humidity: "); Serial.print(sensorStatus); Serial.print(". String: "); statusString = sensorStatus; Serial.println(statusString); } // Sending register message every 10 seconds (can be changed) void sendRegisterBroadcastMessage(PubSubClient client) { JsonObject &sensorInit = jsonBuffer.createObject(); char jsonCharInit[200] = ""; String ip = WiFi.localIP().toString(); fetchSensorStatus(); sensorInit["uuid"] = sensorId.c_str(); sensorInit["switchable"] = switchable; sensorInit["adjustable"] = adjustable; sensorInit["status"] = statusString.c_str(); sensorInit["ip"] = ip.c_str(); sensorInit["action"] = "register"; sensorInit.printTo((char *)jsonCharInit, sensorInit.measureLength() + 1); client.publish("sensor/register", jsonCharInit); jsonBuffer.clear(); } // SENSOR ID HANDLER void handleSensorId() { byte sensorIdFlag = SENSOR_ID_INIT_FLAG; EEPROM.begin(1024); sensorIdFlag = EEPROM.read(addressPointer); if (sensorIdFlag == 0) { clearSensorEEPROM(); saveFlagOnEeprom(sensorIdFlag); createSensorId(); EEPROM.put(addressPointer, sensorIdToEeprom); EEPROM.commit(); } else { addressPointer++; EEPROM.get(addressPointer, sensorIdToEeprom); addressPointer += sizeof(sensorIdToEeprom); } EEPROM.end(); } void saveFlagOnEeprom(byte flag) { flag = SENSOR_ID_INIT_FLAG; EEPROM.write(addressPointer, flag); addressPointer++; } /* * END SENSOR ID HANDLER */ /** * Clears EEPROM memory. * Must be used after EEPROM.begin() and must use EEPROM.end() */ void clearSensorEEPROM() { Serial.println("Clearing EEPROM memory."); for (int i = 0; i < 1024; i++) { EEPROM.write(i, 0); } EEPROM.commit(); Serial.println("Cleared"); } // SENSOR ID GENERATOR /** * Creates unique UUID for sensor. * It's made of generated UUID and added ESP8266 chip ID to it in byte form. */ void createSensorId() { byte uuidNumber[UUID_SIZE]; String chipId = String(ESP.getChipId(), HEX); ESP8266TrueRandom.uuid(uuidNumber); appendToString(uuidNumber, UUID_SIZE); sensorId += chipId; sensorId.toUpperCase(); sensorId.toCharArray(sensorIdToEeprom, SENSOR_ID_SIZE); } /** * Appends to String */ void appendToString(byte *byteArray, int arraySize) { for (int i = 0; i < arraySize; i++) { addHexToString(byteArray[i]); } } /** * Gets first and second part of byte as integers, * then passes to String constructor with HEX parameter which * converts input variable to HEX value and then it's appended * to global String variable. */ void addHexToString(byte number) { sensorId += String(getFirstHexDigit(number), HEX); sensorId += String(getSecondHexDigit(number), HEX); } /** * Gets first 4 bits of byte which are first hex digit * and returns an integer */ int getFirstHexDigit(byte number) { return number >> 4; } /** * Gets second 4 bits of byte which are second hex digit * and returns an integer */ int getSecondHexDigit(byte number) { return number & 0x0F; } // END SENSOR ID GENERATOR // WIFI HANDLER void setupWifi() { delay(10); WiFi.begin(ssid, password); while (WiFi.status() != WL_CONNECTED) { delay(500); } Serial.println(WiFi.localIP()); } // MQTT HANDLER void setupMqtt() { client.setServer(mqtt_server, 1883); client.setCallback(callback); registeredTopic = TOPIC_PREFIX + sensorIdToEeprom + "/registered"; checkStatusResponseTopic = TOPIC_PREFIX + sensorIdToEeprom + "/status/response"; checkStatusTopic = TOPIC_PREFIX + sensorIdToEeprom + "/status/check"; allCheckStatusTopic = TOPIC_PREFIX + "all/status/check"; } // CALLBACK FOR MESSAGE void callback(String topic, byte *message, unsigned int length) { String messageTemp; JsonObject &sensor = jsonBuffer.createObject(); char jsonChar[200] = ""; // Decodes message from bytes to String for (int i = 0; i < length; i++) { messageTemp += (char)message[i]; } if (topic.equals(registeredTopic)) { registeredFlag = true; client.unsubscribe(registeredTopic.c_str()); } if (topic.equals(allCheckStatusTopic) || topic.equals(checkStatusTopic)) { fetchSensorStatus(); sensor["uuid"] = sensorId.c_str(); sensor["status"] = statusString.c_str(); sensor["action"] = "update"; sensor.printTo((char *)jsonChar, sensor.measureLength() + 1); client.publish(responseTopic.c_str(), jsonChar); jsonBuffer.clear(); } } // This functions reconnects your ESP8266 to your MQTT broker // Change the function below if you want to subscribe to more topics with your ESP8266 void reconnect() { // Loop until we're reconnected while (!client.connected()) { Serial.print("Attempting MQTT connection..."); if (client.connect(sensorIdToEeprom)) { Serial.println("connected"); // Subscribe or resubscribe to a topic // You can subscribe to more topics (to control more LEDs in this example) client.subscribe(registeredTopic.c_str()); client.subscribe(checkStatusTopic.c_str()); client.subscribe(allCheckStatusTopic.c_str()); } else { Serial.print("failed, rc="); Serial.print(client.state()); Serial.println(" try again in 5 seconds"); // Wait 5 seconds before retrying delay(5000); } } }
b9a22fdc1425e712b4a88c0621e97d8c6a853e43
08bfc8a1f8e44adc624d1f1c6250a3d9635f99de
/SDKs/squish-ccr/extra/squishgen.cpp
bf1dcbb9dae511bd5837079935047f1f46b8fc30
[]
no_license
Personwithhat/CE_SDKs
cd998a2181fcbc9e3de8c58c7cc7b2156ca21d02
7afbd2f7767c9c5e95912a1af42b37c24d57f0d4
refs/heads/master
2020-04-09T22:14:56.917176
2019-07-04T00:19:11
2019-07-04T00:19:11
160,623,495
0
0
null
null
null
null
UTF-8
C++
false
false
130
cpp
squishgen.cpp
version https://git-lfs.github.com/spec/v1 oid sha256:8d7d200cdb49e8d55e7c5552694a6dd20b88c2f21fe1b6421217a2f492c8cdad size 25964
a39ac017d9ff836bb73d6adbc32f9d80416ec5b3
2981ad592d9195113b617ec1aa5c031c033b117e
/Asg2/Asg2/submit.cpp
60a02eda822d5c8b6d8bd857c2ffcf2dcc8f8a34
[]
no_license
tingyn012/CSCI3260
bb688cc3fbe75813763a35547fd7617449798d14
89968c1a64e8e50c9158d8e00de87731c0a71fdd
refs/heads/master
2021-01-18T20:38:30.027647
2017-04-02T10:45:41
2017-04-02T10:45:41
86,979,909
1
0
null
null
null
null
WINDOWS-1252
C++
false
false
20,936
cpp
submit.cpp
/********************************************************* FILE : submit.cpp (csci3260 2016-2017 Assignment 2) *********************************************************/ /********************************************************* Student Information Student ID: 1155032539 Student Name: NG, Ting Yuk *********************************************************/ #include "Dependencies\glew\glew.h" #include "Dependencies\freeglut\freeglut.h" #include "Dependencies\glm\glm.hpp" #include "Dependencies\glm\gtc\matrix_transform.hpp" #include <iostream> #include <fstream> #include <vector> using namespace std; using glm::vec3; using glm::mat4; GLint programID; // Could define the Vao&Vbo and interaction parameter here GLuint vao[3]; GLuint vertexbuffer[3]; GLuint uvbuffer[3]; GLuint normalbuffer[3]; size_t vertices_size[3]; std::vector<glm::vec3> vertices; std::vector<glm::vec2> uvs; std::vector<glm::vec3> normals; // Won't be used at the moment. GLuint Texture[6]; GLuint TextureID[6]; float xpos; float ypos; float diff_brightness = 2.0f; GLint spec_brightness = 10; GLfloat rotate_x; bool pause = false; GLfloat x_tran = 0.0f; GLfloat y_tran = 0.0f; bool checkStatus( GLuint objectID, PFNGLGETSHADERIVPROC objectPropertyGetterFunc, PFNGLGETSHADERINFOLOGPROC getInfoLogFunc, GLenum statusType) { GLint status; objectPropertyGetterFunc(objectID, statusType, &status); if (status != GL_TRUE) { GLint infoLogLength; objectPropertyGetterFunc(objectID, GL_INFO_LOG_LENGTH, &infoLogLength); GLchar* buffer = new GLchar[infoLogLength]; GLsizei bufferSize; getInfoLogFunc(objectID, infoLogLength, &bufferSize, buffer); cout << buffer << endl; delete[] buffer; return false; } return true; } bool checkShaderStatus(GLuint shaderID) { return checkStatus(shaderID, glGetShaderiv, glGetShaderInfoLog, GL_COMPILE_STATUS); } bool checkProgramStatus(GLuint programID) { return checkStatus(programID, glGetProgramiv, glGetProgramInfoLog, GL_LINK_STATUS); } string readShaderCode(const char* fileName) { ifstream meInput(fileName); if (!meInput.good()) { cout << "File failed to load..." << fileName; exit(1); } return std::string( std::istreambuf_iterator<char>(meInput), std::istreambuf_iterator<char>() ); } void installShaders() { GLuint vertexShaderID = glCreateShader(GL_VERTEX_SHADER); GLuint fragmentShaderID = glCreateShader(GL_FRAGMENT_SHADER); const GLchar* adapter[1]; string temp = readShaderCode("VertexShader.glsl"); adapter[0] = temp.c_str(); glShaderSource(vertexShaderID, 1, adapter, 0); temp = readShaderCode("FragmentShader.glsl"); adapter[0] = temp.c_str(); glShaderSource(fragmentShaderID, 1, adapter, 0); glCompileShader(vertexShaderID); glCompileShader(fragmentShaderID); if (!checkShaderStatus(vertexShaderID) || !checkShaderStatus(fragmentShaderID)) return; programID = glCreateProgram(); glAttachShader(programID, vertexShaderID); glAttachShader(programID, fragmentShaderID); glLinkProgram(programID); if (!checkProgramStatus(programID)) return; glDeleteShader(vertexShaderID); glDeleteShader(fragmentShaderID); glUseProgram(programID); } void keyboard(unsigned char key, int x, int y) { //TODO: Use keyboard to do interactive events and animation if (key == 'q') { diff_brightness += 1.0f; } if (key == 'w') { diff_brightness -= 1.0f; } if (key == 'z') { if (spec_brightness < 105) spec_brightness += 5; } if (key == 'x') { if(spec_brightness > 5) spec_brightness -= 5; } if (key == 's') { if (pause == false) { pause = true; return; } if (pause == true) { pause = false; return; } } } void SpecialInput(int key, int x, int y) { if (key == GLUT_KEY_UP) { x_tran += 0.2f; //printf("x_tran: %f \n", x_tran); } if (key == GLUT_KEY_DOWN) { x_tran -= 0.2f; //printf("x_tran: %f \n", x_tran); } if (key == GLUT_KEY_LEFT) { y_tran -= 0.2f; //printf("y_tran: %f \n", y_tran); } if (key == GLUT_KEY_RIGHT) { y_tran += 0.2f; //printf("y_tran: %f \n", y_tran); } } void PassiveMouse(int x, int y) { //TODO: Use Mouse to do interactive events and animation xpos = (float) (640 - x) / 640 * 18; ypos = (float) (480 - y) / 480 * 18; //printf("xpos:%f ", xpos); //printf("ypos:%f \n", ypos); } bool loadOBJ( const char * path, std::vector<glm::vec3> & out_vertices, std::vector<glm::vec2> & out_uvs, std::vector<glm::vec3> & out_normals ) { printf("Loading OBJ file %s...\n", path); std::vector<unsigned int> vertexIndices, uvIndices, normalIndices; std::vector<glm::vec3> temp_vertices; std::vector<glm::vec2> temp_uvs; std::vector<glm::vec3> temp_normals; FILE * file = fopen(path, "r"); if (file == NULL) { printf("Impossible to open the file ! Are you in the right path ? See Tutorial 1 for details\n"); getchar(); return false; } while (1) { char lineHeader[128]; // read the first word of the line int res = fscanf(file, "%s", lineHeader); if (res == EOF) break; // EOF = End Of File. Quit the loop. // else : parse lineHeader if (strcmp(lineHeader, "v") == 0) { glm::vec3 vertex; fscanf(file, "%f %f %f\n", &vertex.x, &vertex.y, &vertex.z); temp_vertices.push_back(vertex); } else if (strcmp(lineHeader, "vt") == 0) { glm::vec2 uv; fscanf(file, "%f %f\n", &uv.x, &uv.y); uv.y = -uv.y; // Invert V coordinate since we will only use DDS texture, which are inverted. Remove if you want to use TGA or BMP loaders. temp_uvs.push_back(uv); } else if (strcmp(lineHeader, "vn") == 0) { glm::vec3 normal; fscanf(file, "%f %f %f\n", &normal.x, &normal.y, &normal.z); temp_normals.push_back(normal); } else if (strcmp(lineHeader, "f") == 0) { std::string vertex1, vertex2, vertex3; unsigned int vertexIndex[3], uvIndex[3], normalIndex[3]; int matches = fscanf(file, "%d/%d/%d %d/%d/%d %d/%d/%d\n", &vertexIndex[0], &uvIndex[0], &normalIndex[0], &vertexIndex[1], &uvIndex[1], &normalIndex[1], &vertexIndex[2], &uvIndex[2], &normalIndex[2]); if (matches != 9) { printf("File can't be read by our simple parser :-( Try exporting with other options\n"); return false; } vertexIndices.push_back(vertexIndex[0]); vertexIndices.push_back(vertexIndex[1]); vertexIndices.push_back(vertexIndex[2]); uvIndices.push_back(uvIndex[0]); uvIndices.push_back(uvIndex[1]); uvIndices.push_back(uvIndex[2]); normalIndices.push_back(normalIndex[0]); normalIndices.push_back(normalIndex[1]); normalIndices.push_back(normalIndex[2]); } else { // Probably a comment, eat up the rest of the line char stupidBuffer[1000]; fgets(stupidBuffer, 1000, file); } } // For each vertex of each triangle for (unsigned int i = 0; i<vertexIndices.size(); i++) { // Get the indices of its attributes unsigned int vertexIndex = vertexIndices[i]; unsigned int uvIndex = uvIndices[i]; unsigned int normalIndex = normalIndices[i]; // Get the attributes thanks to the index glm::vec3 vertex = temp_vertices[vertexIndex - 1]; glm::vec2 uv = temp_uvs[uvIndex - 1]; glm::vec3 normal = temp_normals[normalIndex - 1]; // Put the attributes in buffers out_vertices.push_back(vertex); out_uvs.push_back(uv); out_normals.push_back(normal); } printf("Success!\n"); return true; } GLuint loadBMP_custom(const char * imagepath) { printf("Reading image %s\n", imagepath); unsigned char header[54]; unsigned int dataPos; unsigned int imageSize; unsigned int width, height; unsigned char * data; FILE * file = fopen(imagepath, "rb"); if (!file) { printf("%s could not be opened. Are you in the right directory ? Don't forget to read the FAQ !\n", imagepath); getchar(); return 0; } if (fread(header, 1, 54, file) != 54) { printf("Not a correct BMP file\n"); return 0; } if (header[0] != 'B' || header[1] != 'M') { printf("Not a correct BMP file\n"); return 0; } if (*(int*)&(header[0x1E]) != 0) { printf("Not a correct BMP file\n"); return 0; } if (*(int*)&(header[0x1C]) != 24) { printf("Not a correct BMP file\n"); return 0; } dataPos = *(int*)&(header[0x0A]); imageSize = *(int*)&(header[0x22]); width = *(int*)&(header[0x12]); height = *(int*)&(header[0x16]); if (imageSize == 0) imageSize = width*height * 3; if (dataPos == 0) dataPos = 54; data = new unsigned char[imageSize]; fread(data, 1, imageSize, file); fclose(file); GLuint textureID; //TODO: Create one OpenGL texture and set the texture parameter glGenTextures(1, &textureID); // "Bind" the newly created texture : all future texture functions will modify this texture glBindTexture(GL_TEXTURE_2D, textureID); // Give the image to OpenGL glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_BGR, GL_UNSIGNED_BYTE, data); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); printf("Success!\n"); return textureID; } void sendDataToOpenGL() { //TODO: //Load objects and bind to VAO & VBO //Load texture // Read our .obj file bool res[3]; res[0] = loadOBJ("jeep.obj", vertices, uvs, normals); Texture[0] = loadBMP_custom("jeep_texture.bmp"); TextureID[0] = glGetUniformLocation(programID, "myTextureSampler"); Texture[3] = loadBMP_custom("jeep_texture.bmp"); TextureID[3] = glGetUniformLocation(programID, "myTextureSampler_2"); // Load it into a VBO glGenVertexArrays(1, &vao[0]); glBindVertexArray(vao[0]); glGenBuffers(1, &vertexbuffer[0]); glBindBuffer(GL_ARRAY_BUFFER, vertexbuffer[0]); glBufferData(GL_ARRAY_BUFFER, vertices.size() * sizeof(glm::vec3), &vertices[0], GL_STATIC_DRAW); // 1rst attribute buffer : vertices glEnableVertexAttribArray(0); glBindBuffer(GL_ARRAY_BUFFER, vertexbuffer[0]); glVertexAttribPointer( 0, // attribute 3, // size GL_FLOAT, // type GL_FALSE, // normalized? 0, // stride (void*)0 // array buffer offset ); vertices_size[0] = vertices.size(); // printf("%d \n", vertices_size[0]); glGenBuffers(1, &uvbuffer[0]); glBindBuffer(GL_ARRAY_BUFFER, uvbuffer[0]); glBufferData(GL_ARRAY_BUFFER, uvs.size() * sizeof(glm::vec2), &uvs[0], GL_STATIC_DRAW); // 2nd attribute buffer : UVs glEnableVertexAttribArray(1); glBindBuffer(GL_ARRAY_BUFFER, uvbuffer[0]); glVertexAttribPointer( 1, // attribute 2, // size GL_FLOAT, // type GL_FALSE, // normalized? 0, // stride (void*)0 // array buffer offset ); glGenBuffers(1, &normalbuffer[0]); glBindBuffer(GL_ARRAY_BUFFER, normalbuffer[0]); glBufferData(GL_ARRAY_BUFFER, normals.size() * sizeof(glm::vec3), &normals[0], GL_STATIC_DRAW); // 1rst attribute buffer : vertices glEnableVertexAttribArray(2); glBindBuffer(GL_ARRAY_BUFFER, normalbuffer[0]); glVertexAttribPointer( 2, // attribute 3, // size GL_FLOAT, // type GL_FALSE, // normalized? 0, // stride (void*)0 // array buffer offset ); res[1] = loadOBJ("plane.obj", vertices, uvs, normals); Texture[1] = loadBMP_custom("plane_texture.bmp"); TextureID[1] = glGetUniformLocation(programID, "myTextureSampler"); Texture[4] = loadBMP_custom("grass_texture.bmp"); TextureID[4] = glGetUniformLocation(programID, "myTextureSampler_2"); glGenVertexArrays(1, &vao[1]); glBindVertexArray(vao[1]); glGenBuffers(1, &vertexbuffer[1]); glBindBuffer(GL_ARRAY_BUFFER, vertexbuffer[1]); glBufferData(GL_ARRAY_BUFFER, vertices.size() * sizeof(glm::vec3), &vertices[0], GL_STATIC_DRAW); // 1rst attribute buffer : vertices glEnableVertexAttribArray(0); glBindBuffer(GL_ARRAY_BUFFER, vertexbuffer[1]); glVertexAttribPointer( 0, // attribute 3, // size GL_FLOAT, // type GL_FALSE, // normalized? 0, // stride (void*)0 // array buffer offset ); vertices_size[1] = vertices.size(); // printf("%d \n", vertices_size[1]); glGenBuffers(1, &uvbuffer[1]); glBindBuffer(GL_ARRAY_BUFFER, uvbuffer[1]); glBufferData(GL_ARRAY_BUFFER, uvs.size() * sizeof(glm::vec2), &uvs[0], GL_STATIC_DRAW); // 2nd attribute buffer : UVs glEnableVertexAttribArray(1); glBindBuffer(GL_ARRAY_BUFFER, uvbuffer[1]); glVertexAttribPointer( 1, // attribute 2, // size GL_FLOAT, // type GL_FALSE, // normalized? 0, // stride (void*)0 // array buffer offset ); glGenBuffers(1, &normalbuffer[1]); glBindBuffer(GL_ARRAY_BUFFER, normalbuffer[1]); glBufferData(GL_ARRAY_BUFFER, normals.size() * sizeof(glm::vec3), &normals[0], GL_STATIC_DRAW); // 1rst attribute buffer : vertices glEnableVertexAttribArray(2); glBindBuffer(GL_ARRAY_BUFFER, normalbuffer[1]); glVertexAttribPointer( 2, // attribute 3, // size GL_FLOAT, // type GL_FALSE, // normalized? 0, // stride (void*)0 // array buffer offset ); res[2] = loadOBJ("tank.obj", vertices, uvs, normals); Texture[2] = loadBMP_custom("tank_texture.bmp"); TextureID[2] = glGetUniformLocation(programID, "myTextureSampler"); Texture[5] = loadBMP_custom("tank_texture.bmp"); TextureID[5] = glGetUniformLocation(programID, "myTextureSampler_2"); glGenVertexArrays(1, &vao[2]); glBindVertexArray(vao[2]); glGenBuffers(1, &vertexbuffer[2]); glBindBuffer(GL_ARRAY_BUFFER, vertexbuffer[2]); glBufferData(GL_ARRAY_BUFFER, vertices.size() * sizeof(glm::vec3), &vertices[0], GL_STATIC_DRAW); // 1rst attribute buffer : vertices glEnableVertexAttribArray(0); glBindBuffer(GL_ARRAY_BUFFER, vertexbuffer[2]); glVertexAttribPointer( 0, // attribute 3, // size GL_FLOAT, // type GL_FALSE, // normalized? 0, // stride (void*)0 // array buffer offset ); vertices_size[2] = vertices.size(); // printf("%d \n", vertices_size[2]); glGenBuffers(1, &uvbuffer[2]); glBindBuffer(GL_ARRAY_BUFFER, uvbuffer[2]); glBufferData(GL_ARRAY_BUFFER, uvs.size() * sizeof(glm::vec2), &uvs[0], GL_STATIC_DRAW); // 2nd attribute buffer : UVs glEnableVertexAttribArray(1); glBindBuffer(GL_ARRAY_BUFFER, uvbuffer[2]); glVertexAttribPointer( 1, // attribute 2, // size GL_FLOAT, // type GL_FALSE, // normalized? 0, // stride (void*)0 // array buffer offset ); glGenBuffers(1, &normalbuffer[2]); glBindBuffer(GL_ARRAY_BUFFER, normalbuffer[2]); glBufferData(GL_ARRAY_BUFFER, normals.size() * sizeof(glm::vec3), &normals[0], GL_STATIC_DRAW); // 1rst attribute buffer : vertices glEnableVertexAttribArray(2); glBindBuffer(GL_ARRAY_BUFFER, normalbuffer[2]); glVertexAttribPointer( 2, // attribute 3, // size GL_FLOAT, // type GL_FALSE, // normalized? 0, // stride (void*)0 // array buffer offset ); } void setupMVPmatrix(void) { /* First step : generating our MVP matrix. This must be done for each model you render. */ // Projection matrix : 45¢X Field of View, 4:3 ratio, display range : 0.1 unit <-> 100 units glm::mat4 Projection = glm::perspective(glm::radians(45.0f), 4.0f / 3.0f, 0.1f, 100.0f); // Or, for an ortho camera : // glm::mat4 Projection = glm::ortho(-10.0f,10.0f,-10.0f,10.0f,0.0f,100.0f); // In world coordinates //x += 0.001; //printf("%f\n", x); // Camera matrix glm::mat4 View = glm::lookAt( glm::vec3(xpos, ypos, 18), // Camera is at (4,3,3), in World Space glm::vec3(0, 0, 0), // and looks at the origin glm::vec3(0, 1, 0) // Head is up (set to 0,-1,0 to look upside-down) ); // Model matrix : an identity matrix (model will be at the origin) glm::mat4 Model = glm::mat4(1.0f); // Our ModelViewProjection : multiplication of our 3 matrices glm::mat4 MVP = Projection * View * Model; // Remember, matrix multiplication is the other way around /* Second step : give it to GLSL */ // Get a handle for our "MVP" uniform // Only during the initialisation GLuint MatrixID = glGetUniformLocation(programID, "MVP"); // Send our transformation to the currently bound shader, in the "MVP" uniform // This is done in the main loop since each model will have a different MVP matrix (At least for the M part) glUniformMatrix4fv(MatrixID, 1, GL_FALSE, &MVP[0][0]); } void paintGL(void) { // Enable depth test glEnable(GL_DEPTH_TEST); // Accept fragment if it closer to the camera than the former one glDepthFunc(GL_LESS); glClearColor(0.0f, 0.0f, 0.2f, 0.0f); // navy blue background glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT); //TODO: //Set lighting information, such as position and color of lighting source //Set transformation matrix //Bind different texture setupMVPmatrix(); GLint ambientLightUniformLocation = glGetUniformLocation(programID, "ambientLight"); vec3 ambientLight(0.2f, 0.2f, 0.2f); glUniform3fv(ambientLightUniformLocation, 1, &ambientLight[0]); GLint lightPositionUniformLocation = glGetUniformLocation(programID, "lightPositionWorld"); vec3 lightPosition(2.0f, 2.0f, 2.0f); glUniform3fv(lightPositionUniformLocation, 1, &lightPosition[0]); GLint diff_brightnessUniformLocation = glGetUniformLocation(programID, "Diff_brightness"); vec3 diff_brightnessPosition(diff_brightness, diff_brightness, diff_brightness); glUniform3fv(diff_brightnessUniformLocation, 1, &diff_brightnessPosition[0]); GLint eyePositionUniformLocation = glGetUniformLocation(programID, "eyePositionWorld"); vec3 eyePosition(0.0f, 0.0f, 0.0f); glUniform3fv(eyePositionUniformLocation, 1, &eyePosition[0]); int spec_brightnessLocation = glGetUniformLocation(programID, "spec_brightness"); glUniform1i(spec_brightnessLocation, spec_brightness); glm::mat4 modelTransformMatrix; GLint modelTransformMatrixUniformLocation = glGetUniformLocation(programID, "modelTransformMatrix");; // Bind our texture in Texture Unit 0 glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, Texture[0]); glUniform1i(TextureID[0], 0); glActiveTexture(GL_TEXTURE1); glBindTexture(GL_TEXTURE_2D, Texture[3]); glUniform1i(TextureID[3], 1); glBindVertexArray(vao[0]); //glm::mat4 modelTransformMatrix_temp = glm::translate(glm::mat4(), glm::vec3(-x_tran, 0.0f, -y_tran)); //glm::mat4 modelTransformMatrix_temp2 = glm::rotate(glm::mat4(), rotate_x, glm::vec3(0, 1, 0)); //modelTransformMatrix = glm::translate(glm::mat4(), glm::vec3(x_tran, 0.0f, y_tran)) * modelTransformMatrix_temp2 * modelTransformMatrix_temp; modelTransformMatrix = glm::rotate(glm::mat4(), rotate_x, glm::vec3(0, 1, 0)); glUniformMatrix4fv(modelTransformMatrixUniformLocation, 1, GL_FALSE, &modelTransformMatrix[0][0]); if (pause == false) rotate_x += 0.0002f; glDrawArrays(GL_TRIANGLES, 0, vertices_size[0]); glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, Texture[1]); glUniform1i(TextureID[1], 0); glActiveTexture(GL_TEXTURE1); glBindTexture(GL_TEXTURE_2D, Texture[4]); glUniform1i(TextureID[4], 1); glBindVertexArray(vao[1]); modelTransformMatrix = glm::mat4(1.0); glUniformMatrix4fv(modelTransformMatrixUniformLocation, 1, GL_FALSE, &modelTransformMatrix[0][0]); glDrawArrays(GL_TRIANGLES, vertices_size[0], vertices_size[1] - vertices_size[0]); glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, Texture[2]); glUniform1i(TextureID[2], 0); glActiveTexture(GL_TEXTURE1); glBindTexture(GL_TEXTURE_2D, Texture[5]); glUniform1i(TextureID[5], 1); glBindVertexArray(vao[2]); modelTransformMatrix = glm::translate(glm::mat4(), glm::vec3(y_tran + 7.0f, 2.0f, x_tran + 5.0f)); glUniformMatrix4fv(modelTransformMatrixUniformLocation, 1, GL_FALSE, &modelTransformMatrix[0][0]); glDrawArrays(GL_TRIANGLES, vertices_size[1] , vertices_size[2] - vertices_size[1]); glFlush(); glutPostRedisplay(); } void initializedGL(void) { glewInit(); glEnable(GL_DEPTH_TEST); glDepthFunc(GL_LESS); glEnable(GL_CULL_FACE); installShaders(); sendDataToOpenGL(); } int main(int argc, char *argv[]) { glutInit(&argc, argv); glutInitDisplayMode(GLUT_RGB | GLUT_SINGLE); //TODO: //Create a window with title specified glutInitWindowPosition(100, 100); glutInitWindowSize(640, 480); glutCreateWindow("Assignment 2"); initializedGL(); glutDisplayFunc(paintGL); glutPassiveMotionFunc(PassiveMouse); glutKeyboardFunc(keyboard); glutSpecialFunc(SpecialInput); glutMainLoop(); return 0; }
0be53848f9ee84c5681a9ce4e31724ebe746fc4c
6aba3d9e4a5401b5387548475d0ca74794e73c69
/GROMACS/nonbonded_benchmark/gromacs_source_code/src/gromacs/utility/tests/arrayref.cpp
e8a8388f862b8897813af1a72ac54743aab8b4c2
[ "LGPL-2.1-only", "LGPL-2.0-or-later", "LicenseRef-scancode-sun-rpc", "LGPL-2.1-or-later", "SunPro", "GPL-1.0-or-later", "BSD-2-Clause-Views", "GPL-2.0-only", "BSL-1.0", "Apache-2.0", "BSD-3-Clause", "Zlib", "BSD-2-Clause", "MIT", "LicenseRef-scancode-free-unknown" ]
permissive
rvhonorato/bioexcel-exascale-co-design-benchmarks
a47b2608ad796329247a671ca95c7b487be213ca
41bfd28e64a65f7d08a4195bdfd0024646664351
refs/heads/master
2020-06-18T05:56:43.151669
2019-07-10T15:17:45
2019-07-10T15:17:45
196,187,655
0
0
MIT
2019-07-10T10:50:25
2019-07-10T10:50:24
null
UTF-8
C++
false
false
7,586
cpp
arrayref.cpp
/* * This file is part of the GROMACS molecular simulation package. * * Copyright (c) 2015,2016,2017,2018,2019, by the GROMACS development team, led by * Mark Abraham, David van der Spoel, Berk Hess, and Erik Lindahl, * and including many others, as listed in the AUTHORS file in the * top-level source directory and at http://www.gromacs.org. * * GROMACS is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * as published by the Free Software Foundation; either version 2.1 * of the License, or (at your option) any later version. * * GROMACS 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with GROMACS; if not, see * http://www.gnu.org/licenses, or write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * * If you want to redistribute modifications to GROMACS, please * consider that scientific software is very special. Version * control is crucial - bugs must be traceable. We will be happy to * consider code for inclusion in the official distribution, but * derived work must not be called official GROMACS. Details are found * in the README & COPYING files - if they are missing, get the * official version at http://www.gromacs.org. * * To help us fund GROMACS development, we humbly ask that you cite * the research papers on the package. Check out http://www.gromacs.org. */ /*! \internal \file * \brief Tests for gmx::ArrayRef. * * \author Mark Abraham <mark.j.abraham@gmail.com> * \ingroup module_utility */ #include "gmxpre.h" #include "gromacs/utility/arrayref.h" #include <vector> #include <gtest/gtest.h> #include "gromacs/utility/basedefinitions.h" #include "gromacs/utility/real.h" namespace gmx { namespace { TEST(EmptyArrayRefTest, IsEmpty) { ArrayRef<real> empty; EXPECT_EQ(0U, empty.size()); EXPECT_TRUE(empty.empty()); } TEST(EmptyConstArrayRefTest, IsEmpty) { ArrayRef<const real> empty; EXPECT_EQ(0U, empty.size()); EXPECT_TRUE(empty.empty()); } #ifdef GTEST_HAS_TYPED_TEST //! Define the types that end up being available as TypeParam in the test cases for both kinds of ArrayRef typedef ::testing::Types< ArrayRef<char>, ArrayRef<unsigned char>, ArrayRef<int>, ArrayRef<unsigned int>, ArrayRef<long>, ArrayRef<unsigned long>, ArrayRef<int64_t>, ArrayRef<uint64_t>, ArrayRef<float>, ArrayRef<double>, ArrayRef<const char>, ArrayRef<const unsigned char>, ArrayRef<const int>, ArrayRef<const unsigned int>, ArrayRef<const long>, ArrayRef<const unsigned long>, ArrayRef<const int64_t>, ArrayRef<const uint64_t>, ArrayRef<const float>, ArrayRef<const double> > ArrayRefTypes; constexpr index aSize = 3; /*! \brief Permit all the tests to run on all kinds of ArrayRefs * * The main objective is to verify that all the different kinds of * construction lead to the expected result. */ template <typename TypeParam> class ArrayRefTest : public ::testing::Test { public: typedef TypeParam ArrayRefType; typedef typename ArrayRefType::value_type ValueType; typedef typename std::remove_const<ValueType>::type NonConstValueType; /*! \brief Run the same tests all the time * * Note that test cases must call this->runTests(), because * that's how the derived-class templates that implement * type-parameterized tests actually work. */ void runTests(ValueType *aData, ArrayRefType &arrayRef) { ASSERT_EQ(aSize, arrayRef.size()); ASSERT_FALSE(arrayRef.empty()); EXPECT_EQ(aData, arrayRef.data()); EXPECT_EQ(a[0], arrayRef.front()); EXPECT_EQ(a[aSize-1], arrayRef.back()); for (index i = 0; i != aSize; ++i) { EXPECT_EQ(a[i], arrayRef[i]); } } ValueType a[aSize] = { ValueType(1.2), ValueType(2.4), ValueType(3.1) }; NonConstValueType ma[aSize] = { ValueType(1.2), ValueType(2.4), ValueType(3.1) }; }; TYPED_TEST_CASE(ArrayRefTest, ArrayRefTypes); TYPED_TEST(ArrayRefTest, MakeWithAssignmentWorks) { typename TestFixture::ArrayRefType arrayRef = this->a; this->runTests(this->a, arrayRef); } TYPED_TEST(ArrayRefTest, MakeWithNonConstAssignmentWorks) { typename TestFixture::ArrayRefType arrayRef = this->ma; this->runTests(this->ma, arrayRef); } TYPED_TEST(ArrayRefTest, ConstructWithTemplateConstructorWorks) { typename TestFixture::ArrayRefType arrayRef(this->a); this->runTests(this->a, arrayRef); } TYPED_TEST(ArrayRefTest, ConstructWithNonConstTemplateConstructorWorks) { typename TestFixture::ArrayRefType arrayRef(this->ma); this->runTests(this->ma, arrayRef); } TYPED_TEST(ArrayRefTest, ConstructFromPointersWorks) { typename TestFixture::ArrayRefType arrayRef(this->a, this->a + aSize); this->runTests(this->a, arrayRef); } TYPED_TEST(ArrayRefTest, ConstructFromNonConstPointersWorks) { typename TestFixture::ArrayRefType arrayRef(this->ma, this->ma + aSize); this->runTests(this->ma, arrayRef); } template<bool c, typename T> using makeConstIf_t = typename std::conditional<c, const T, T>::type; TYPED_TEST(ArrayRefTest, ConstructFromVectorWorks) { makeConstIf_t<std::is_const<typename TestFixture::ValueType>::value, std::vector<typename TestFixture::NonConstValueType> > v(this->a, this->a + aSize); typename TestFixture::ArrayRefType arrayRef(v); this->runTests(v.data(), arrayRef); } TYPED_TEST(ArrayRefTest, ConstructFromNonConstVectorWorks) { std::vector<typename TestFixture::NonConstValueType> v(this->a, this->a + aSize); typename TestFixture::ArrayRefType arrayRef(v); this->runTests(v.data(), arrayRef); } //! Helper struct for the case actually used in mdrun signalling template <typename T> struct Helper { public: T a[3]; int size; }; /*! \brief Test of the case actually used in mdrun signalling * * There, we take a non-const struct-field array of static length and * make an ArrayRef to it using the template constructor that is * supposed to infer the length from the static size. This has * been a problem (for a compiler that we no longer support), * so we test it. */ TYPED_TEST(ArrayRefTest, ConstructFromStructFieldWithTemplateConstructorWorks) { Helper<typename TestFixture::NonConstValueType> h; h.size = aSize; for (int i = 0; i != h.size; ++i) { h.a[i] = this->a[i]; } typename TestFixture::ArrayRefType arrayRef(h.a); this->runTests(h.a, arrayRef); } #else // GTEST_HAS_TYPED_TEST /* A dummy test that at least signals that something is missing if one runs the * unit test executable itself. */ TEST(DISABLED_ArrayRefTest, GenericTests) { ADD_FAILURE() << "Tests for generic ArrayRef functionality require support for " << "Google Test typed tests, which was not available when the tests " << "were compiled."; } #endif // GTEST_HAS_TYPED_TEST } // namespace } // namespace gmx
13c260bb23265448b11e1e78f47471788b2ae7fa
d138bdec3f86f0d1469ed8b225ee6411380954bb
/graph_chess.h
af595fa96976fb8cf49f289c1aa2314a09fb77ac
[]
no_license
XxprogrammatorxX/chess
437391ef1d8a7430712379bf9a41f50efda36d5d
74a313d45f10466cb4abf6eff32cf3adf134c9ff
refs/heads/main
2023-02-13T03:53:10.766822
2021-01-12T13:18:04
2021-01-12T13:18:04
328,991,678
0
0
null
null
null
null
UTF-8
C++
false
false
4,852
h
graph_chess.h
#ifndef GRAPH_CHESS_H #define GRAPH_CHESS_H #include "../Graph_lib/Window.h" #include "../Graph_lib/Graph.h" #include "../Graph_lib/GUI.h" #include <iostream> #include <vector> #include <map> #include "yadro.h" #include "bot_chess.h" using namespace Graph_lib; const Point win_p {500,20}; constexpr int win_max_x = 1000; constexpr int win_max_y = 700; constexpr int indent_x = 100; constexpr int indent_y = 20; constexpr int weight_cell = 80; const int col_cell1 = 175; const int col_cell2 = 65; const Color select_col1 = Color::blue; const Color select_col2 = Color::green; const Color select_col3 = Color::red; const string path_image = "D:\\inf\\c++\\projects\\chess\\"; std::string letters (); std::string digits1 (); std::string digits2 (); const map <Figures, string> fig_type { {Figures::king, "K.png"}, {Figures::queen, "Q.png"}, {Figures::elephant, "B.png"}, {Figures::horse, "N.png"}, {Figures::tower, "R.png"}, {Figures::pawn, "P.png"}, }; const map <FigColor, string> fig_col { {FigColor::black, "figures/b"}, {FigColor::white, "figures/w"} }; struct Print_motion { vector<Out_box*> out; vector<string> str; Print_motion(); }; struct End_Return { Situation sit; FigColor win_color; }; class My_Window : public Graph_lib::Window { public: My_Window(); //Переопределение Fl_Window::hide void hide() override { quit(); } bool quit_is = false; protected: //Реализованный выход Button quit_button; static void cb_quit (Address, Address addr) { Graph_lib::reference_to<My_Window>(addr).quit(); } void quit () { quit_is = true; Fl_Window::hide(); } //Сброс игры Button reset_button; static void cb_reset (Address, Address addr) { Graph_lib::reference_to<My_Window>(addr).reset_play(); } virtual void reset_play () = 0; bool reset = false; //Отмена хода Button reverse_motion_button; static void cb_reverse_motion (Address, Address addr) { Graph_lib::reference_to<My_Window>(addr).reverse_motion(); } virtual void reverse_motion () = 0; bool reverse = false; //Ничья Button draw_button; static void cb_draw (Address, Address addr) { Graph_lib::reference_to<My_Window>(addr).go_draw(); } void go_draw () {draw_is = true;} bool draw_is = false; }; class Chessboard : public My_Window { public: Chessboard(); void click(Address); protected: //Объекты на доске Table desk; std::vector <Image*> figures; Vector_ref <Button> b_cells; Vector_ref <Shape> cells; //Нажатие кнопок bool recovery_button(); bool is_click() const { return clicked;} Point cell_click(); bool clicked = false; int click_x = -1; int click_y = -1; //Буковки и циферки Graph_lib::Marks x_labels_w; Graph_lib::Marks x_labels_b; Graph_lib::Marks y_labels_w; Graph_lib::Marks y_labels_b; //Превращение пешки static void cb_trans(Address addr1, Address addr2) { Graph_lib::reference_to<Chessboard>(addr2).trans(addr1); } void trans(Address addr1) { x_trans = Graph_lib::reference_to<Fl_Widget>(addr1).x(); y_trans = Graph_lib::reference_to<Fl_Widget>(addr1).y(); is_cl_trans = true; } bool is_cl_trans = false; int x_trans = -1; int y_trans = -1; //Вывод прошлых ходов Print_motion moves; void print_moves(); Out_box* out; }; class My_Chessboard : public Chessboard { public: My_Chessboard(); End_Return play(); End_Return play_bot(FigColor bot_col); private: //Вывод на экран void attach_all(); void attach_start(); void position(); void detach_posit(); //Выделение и его сброс void selection(int x, int y); void unselection(); std::vector <Shape*> select; void reset_play () override; void reverse_motion () override; Figures transformation(FigColor col); End_Return check_sit(Situation sit = Situation::none); }; struct Cell : Button { Cell(Point p) :Button{ p, weight_cell, weight_cell, "", cb_click} {} static void cb_click(Address button, Address win) { Graph_lib::reference_to<Chessboard>(win).click(button); } }; const map <int, string> str_leters { {0, "a"}, {1, "b"}, {2, "c"}, {3, "d"}, {4, "e"}, {5, "f"}, {6, "g"}, {7, "h"} }; #endif // GRAPH_CHESS_H
58451f87d8c8037b11c7dd2bd51e9bbb974e9db5
6f874ccb136d411c8ec7f4faf806a108ffc76837
/code/Windows-classic-samples/Samples/Win7Samples/multimedia/WMP/cpp/WMPHost/CWMPHost.cpp
f31ad3f1094df9a310e2479e09d69a7084019791
[ "MIT" ]
permissive
JetAr/ZDoc
c0f97a8ad8fd1f6a40e687b886f6c25bb89b6435
e81a3adc354ec33345e9a3303f381dcb1b02c19d
refs/heads/master
2022-07-26T23:06:12.021611
2021-07-11T13:45:57
2021-07-11T13:45:57
33,112,803
8
8
null
null
null
null
UTF-8
C++
false
false
14,802
cpp
CWMPHost.cpp
// CWMPHost.cpp : Implementation of the CWMPHost // // Copyright (c) Microsoft Corporation. All rights reserved. // #include "stdafx.h" #include "CWMPHost.h" #include "dialogs.h" ///////////////////////////////////////////////////////////////////////////// // CWMPHost void CWMPHost::OnFinalMessage(HWND /*hWnd*/) { ::PostQuitMessage(0); } LRESULT CWMPHost::OnCreate(UINT /* uMsg */, WPARAM /* wParam */, LPARAM /* lParam */, BOOL& /* bHandled */) { AtlAxWinInit(); CComPtr<IAxWinHostWindow> spHost; CComPtr<IConnectionPointContainer> spConnectionContainer; CComWMPEventDispatch *pEventListener = NULL; CComPtr<IWMPEvents> spEventListener; HRESULT hr; RECT rcClient; m_dwAdviseCookie = 0; // create window GetClientRect(&rcClient); m_wndView.Create(m_hWnd, rcClient, NULL, WS_CHILD | WS_VISIBLE | WS_CLIPCHILDREN, WS_EX_CLIENTEDGE); if (NULL == m_wndView.m_hWnd) goto FAILURE; // load OCX in window hr = m_wndView.QueryHost(&spHost); if (FAILMSG(hr)) goto FAILURE; hr = spHost->CreateControl(CComBSTR(L"{6BF52A52-394A-11d3-B153-00C04F79FAA6}"), m_wndView, 0); if (FAILMSG(hr)) goto FAILURE; hr = m_wndView.QueryControl(&m_spWMPPlayer); if (FAILMSG(hr)) goto FAILURE; // start listening to events hr = CComWMPEventDispatch::CreateInstance(&pEventListener); spEventListener = pEventListener; if (FAILMSG(hr)) goto FAILURE; hr = m_spWMPPlayer->QueryInterface(&spConnectionContainer); if (FAILMSG(hr)) goto FAILURE; // See if OCX supports the IWMPEvents interface hr = spConnectionContainer->FindConnectionPoint(__uuidof(IWMPEvents), &m_spConnectionPoint); if (FAILED(hr)) { // If not, try the _WMPOCXEvents interface, which will use IDispatch hr = spConnectionContainer->FindConnectionPoint(__uuidof(_WMPOCXEvents), &m_spConnectionPoint); if (FAILMSG(hr)) goto FAILURE; } hr = m_spConnectionPoint->Advise(spEventListener, &m_dwAdviseCookie); if (FAILMSG(hr)) goto FAILURE; return 0; FAILURE: ::PostQuitMessage(0); return 0; } LRESULT CWMPHost::OnDestroy(UINT /* uMsg */, WPARAM /* wParam */, LPARAM /* lParam */, BOOL& bHandled ) { // stop listening to events if (m_spConnectionPoint) { if (0 != m_dwAdviseCookie) m_spConnectionPoint->Unadvise(m_dwAdviseCookie); m_spConnectionPoint.Release(); } // close the OCX if (m_spWMPPlayer) { m_spWMPPlayer->close(); m_spWMPPlayer.Release(); } bHandled = FALSE; return 0; } LRESULT CWMPHost::OnErase(UINT /* uMsg */, WPARAM /* wParam */, LPARAM /* lParam */, BOOL& /* bHandled */) { return 1; } LRESULT CWMPHost::OnSize(UINT /* uMsg */, WPARAM /* wParam */, LPARAM /* lParam */, BOOL& /* bHandled */) { RECT rcClient; GetClientRect(&rcClient); m_wndView.MoveWindow(rcClient.left, rcClient.top, rcClient.right, rcClient.bottom); return 0; } LRESULT CWMPHost::OnFileOpen(WORD /* wNotifyCode */, WORD /* wID */, HWND /* hWndCtl */, BOOL& /* bHandled */) { CFileOpenDlg dlgOpen; HRESULT hr; if (dlgOpen.DoModal(m_hWnd) == IDOK) { hr = m_spWMPPlayer->put_URL(dlgOpen.m_bstrName); if (FAILMSG(hr)) return 0; } return 0; } LRESULT CWMPHost::OnFileExit(WORD /* wNotifyCode */, WORD /* wID */, HWND /* hWndCtl */, BOOL& /* bHandled */) { DestroyWindow(); return 0; } LRESULT CWMPHost::OnWMPCoreClose(WORD /* wNotifyCode */, WORD /* wID */, HWND /* hWndCtl */, BOOL& /* bHandled */) { HRESULT hr; hr = m_spWMPPlayer->close(); if (FAILMSG(hr)) return 0; return 0; } LRESULT CWMPHost::OnWMPCoreURL(WORD /* wNotifyCode */, WORD /* wID */, HWND /* hWndCtl */, BOOL& /* bHandled */) { CComBSTR m_bstrValue; HRESULT hr; hr = m_spWMPPlayer->get_URL(&m_bstrValue); if (FAILMSG(hr)) return 0; CStringDlg dlgString(L"IWMPCore->URL", m_bstrValue); if (dlgString.DoModal(m_hWnd) == IDOK) { hr = m_spWMPPlayer->put_URL(dlgString.m_bstrValue); if (FAILMSG(hr)) return 0; } return 0; } LRESULT CWMPHost::OnWMPCoreOpenState(WORD /* wNotifyCode */, WORD /* wID */, HWND /* hWndCtl */, BOOL& /* bHandled */) { HRESULT hr; WMPOpenState osValue; hr = m_spWMPPlayer->get_openState(&osValue); if (FAILMSG(hr)) return 0; WCHAR wszValue[MAX_STRING]; ::swprintf_s(wszValue, MAX_STRING, L"Value = %d", osValue); ::MessageBox(NULL, wszValue, L"IWMPCore->openState", MB_OK); return 0; } LRESULT CWMPHost::OnWMPCorePlayState(WORD /* wNotifyCode */, WORD /* wID */, HWND /* hWndCtl */, BOOL& /* bHandled */) { HRESULT hr; WMPPlayState psValue; hr = m_spWMPPlayer->get_playState(&psValue); if (FAILMSG(hr)) return 0; WCHAR wszValue[MAX_STRING]; ::swprintf_s(wszValue, MAX_STRING, L"Value = %d", psValue); ::MessageBox(NULL, wszValue, L"IWMPCore->playState", MB_OK); return 0; } LRESULT CWMPHost::OnWMPCoreVersionInfo(WORD /* wNotifyCode */, WORD /* wID */, HWND /* hWndCtl */, BOOL& /* bHandled */) { CComBSTR m_bstrValue; HRESULT hr; hr = m_spWMPPlayer->get_versionInfo(&m_bstrValue); if (FAILMSG(hr)) return 0; WCHAR wszValue[MAX_STRING]; ::swprintf_s(wszValue, MAX_STRING, L"Version = %s", m_bstrValue); ::MessageBox(NULL, wszValue, L"IWMPCore->versionInfo", MB_OK); return 0; } LRESULT CWMPHost::OnWMPCoreLaunchURL(WORD /* wNotifyCode */, WORD /* wID */, HWND /* hWndCtl */, BOOL& /* bHandled */) { CComBSTR m_bstrValue; HRESULT hr; CStringDlg dlgString(L"IWMPCore->LaunchURL"); if (dlgString.DoModal(m_hWnd) == IDOK) { hr = m_spWMPPlayer->launchURL(dlgString.m_bstrValue); if (FAILMSG(hr)) return 0; } return 0; } LRESULT CWMPHost::OnWMPCoreIsOnline(WORD /* wNotifyCode */, WORD /* wID */, HWND /* hWndCtl */, BOOL& /* bHandled */) { HRESULT hr; VARIANT_BOOL fValue; hr = m_spWMPPlayer->get_isOnline(&fValue); if (FAILMSG(hr)) return 0; WCHAR wszValue[MAX_STRING]; ::swprintf_s(wszValue, MAX_STRING, L"Value = %s", fValue ? L"TRUE" : L"FALSE"); ::MessageBox(NULL, wszValue, L"IWMPCore->isOnline", MB_OK); return 0; } LRESULT CWMPHost::OnWMPCoreStatus(WORD /* wNotifyCode */, WORD /* wID */, HWND /* hWndCtl */, BOOL& /* bHandled */) { CComBSTR m_bstrValue; HRESULT hr; hr = m_spWMPPlayer->get_status(&m_bstrValue); if (FAILMSG(hr)) return 0; WCHAR wszValue[MAX_STRING]; ::swprintf_s(wszValue, MAX_STRING, L"Status = %s", m_bstrValue); ::MessageBox(NULL, wszValue, L"IWMPCore->status", MB_OK); return 0; } LRESULT CWMPHost::OnWMPCoreInterface(WORD /* wNotifyCode */, WORD wID, HWND /* hWndCtl */, BOOL& /* bHandled */) { HRESULT hr; WCHAR wszName[MAX_STRING]; void *pUnknown; hr = E_FAIL; wszName[0] = L'\0'; pUnknown = NULL; switch (wID) { case ID_WMPCORE_CONTROLS: { CComPtr<IWMPControls> spWMPControls; hr = m_spWMPPlayer->get_controls(&spWMPControls); if (spWMPControls) { spWMPControls->QueryInterface(__uuidof(IWMPControls), &pUnknown); wcscpy_s(wszName, MAX_STRING, L"IWMPCore->controls"); } } break; case ID_WMPCORE_SETTINGS: { CComPtr<IWMPSettings> spWMPSettings; hr = m_spWMPPlayer->get_settings(&spWMPSettings); if (spWMPSettings) { spWMPSettings->QueryInterface(__uuidof(IWMPSettings), &pUnknown); wcscpy_s(wszName, MAX_STRING, L"IWMPCore->settings"); } } break; case ID_WMPCORE_CURRENTMEDIA: { CComPtr<IWMPMedia> spWMPMedia; hr = m_spWMPPlayer->get_currentMedia(&spWMPMedia); if (spWMPMedia) { spWMPMedia->QueryInterface(__uuidof(IWMPMedia), &pUnknown); wcscpy_s(wszName, MAX_STRING, L"IWMPCore->currentMedia"); } } break; case ID_WMPCORE_MEDIACOLLECTION: { CComPtr<IWMPMediaCollection> spWMPMediaCollection; hr = m_spWMPPlayer->get_mediaCollection(&spWMPMediaCollection); if (spWMPMediaCollection) { spWMPMediaCollection->QueryInterface(__uuidof(IWMPMediaCollection), &pUnknown); wcscpy_s(wszName, MAX_STRING, L"IWMPCore->currentMediaCollection"); } } break; case ID_WMPCORE_PLAYLISTCOLLECTION: { CComPtr<IWMPPlaylistCollection> spWMPPlaylistCollection; hr = m_spWMPPlayer->get_playlistCollection(&spWMPPlaylistCollection); if (spWMPPlaylistCollection) { spWMPPlaylistCollection->QueryInterface(__uuidof(IWMPPlaylistCollection), &pUnknown); wcscpy_s(wszName, MAX_STRING, L"IWMPCore->playlistCollection"); } } break; case ID_WMPCORE_NETWORK: { CComPtr<IWMPNetwork> spWMPNetwork; hr = m_spWMPPlayer->get_network(&spWMPNetwork); if (spWMPNetwork) { spWMPNetwork->QueryInterface(__uuidof(IWMPNetwork), &pUnknown); wcscpy_s(wszName, MAX_STRING, L"IWMPCore->network"); } } break; case ID_WMPCORE_CURRENTPLAYLIST: { CComPtr<IWMPPlaylist> spWMPPlaylist; hr = m_spWMPPlayer->get_currentPlaylist(&spWMPPlaylist); if (spWMPPlaylist) { spWMPPlaylist->QueryInterface(__uuidof(IWMPPlaylist), &pUnknown); wcscpy_s(wszName, MAX_STRING, L"IWMPCore->currentPlaylist"); } } break; case ID_WMPCORE_CDROMCOLLECTION: { CComPtr<IWMPCdromCollection> spWMPCDRomCollection; hr = m_spWMPPlayer->get_cdromCollection(&spWMPCDRomCollection); if (spWMPCDRomCollection) { spWMPCDRomCollection->QueryInterface(__uuidof(IWMPCdromCollection), &pUnknown); wcscpy_s(wszName, MAX_STRING, L"IWMPCore->cdromCollection"); } } break; case ID_WMPCORE_CLOSEDCAPTION: { CComPtr<IWMPClosedCaption> spWMPClosedCaption; hr = m_spWMPPlayer->get_closedCaption(&spWMPClosedCaption); if (spWMPClosedCaption) { spWMPClosedCaption->QueryInterface(__uuidof(IWMPClosedCaption), &pUnknown); wcscpy_s(wszName, MAX_STRING, L"IWMPCore->closedCaption"); } } break; case ID_WMPCORE_ERROR: { CComPtr<IWMPError> spWMPError; hr = m_spWMPPlayer->get_error(&spWMPError); if (spWMPError) { spWMPError->QueryInterface(__uuidof(IWMPError), &pUnknown); wcscpy_s(wszName, MAX_STRING, L"IWMPCore->error"); } } break; case ID_WMPCORE2_DVD: { CComPtr<IWMPPlayer3> spWMPPlayer3; hr = m_spWMPPlayer.QueryInterface(&spWMPPlayer3); if (FAILMSG(hr)) return 0; CComPtr<IWMPDVD> spWMPDVD; hr = spWMPPlayer3->get_dvd(&spWMPDVD); if (spWMPDVD) { spWMPDVD->QueryInterface(__uuidof(IWMPDVD), &pUnknown); wcscpy_s(wszName, MAX_STRING, L"IWMPCore2->dvd"); } } break; } if (FAILMSG(hr)) return 0; if (!pUnknown) { FAILMSG(E_NOINTERFACE); return 0; } ((IUnknown *)pUnknown)->Release(); ::MessageBox(NULL, L"Got the expected interface", wszName, MB_OK); return 0; } LRESULT CWMPHost::OnWMPPlayerEnabled(WORD /* wNotifyCode */, WORD /* wID */, HWND /* hWndCtl */, BOOL& /* bHandled */) { HRESULT hr; VARIANT_BOOL fValue; hr = m_spWMPPlayer->get_enabled(&fValue); if (FAILMSG(hr)) return 0; CBooleanDlg dlgBoolean(L"IWMPPlayer->enabled", fValue); if (dlgBoolean.DoModal(m_hWnd) == IDOK) { hr = m_spWMPPlayer->put_enabled(dlgBoolean.m_fValue); if (FAILMSG(hr)) return 0; } return 0; } LRESULT CWMPHost::OnWMPPlayerFullScreen(WORD /* wNotifyCode */, WORD /* wID */, HWND /* hWndCtl */, BOOL& /* bHandled */) { HRESULT hr; VARIANT_BOOL fValue; hr = m_spWMPPlayer->get_fullScreen(&fValue); if (FAILMSG(hr)) return 0; CBooleanDlg dlgBoolean(L"IWMPPlayer->fullScreen", fValue); if (dlgBoolean.DoModal(m_hWnd) == IDOK) { hr = m_spWMPPlayer->put_fullScreen(dlgBoolean.m_fValue); if (FAILMSG(hr)) return 0; } return 0; } LRESULT CWMPHost::OnWMPPlayerEnableContextMenu(WORD /* wNotifyCode */, WORD /* wID */, HWND /* hWndCtl */, BOOL& /* bHandled */) { HRESULT hr; VARIANT_BOOL fValue; hr = m_spWMPPlayer->get_enableContextMenu(&fValue); if (FAILMSG(hr)) return 0; CBooleanDlg dlgBoolean(L"IWMPPlayer->enableContextMenu", fValue); if (dlgBoolean.DoModal(m_hWnd) == IDOK) { hr = m_spWMPPlayer->put_enableContextMenu(dlgBoolean.m_fValue); if (FAILMSG(hr)) return 0; } return 0; } LRESULT CWMPHost::OnWMPPlayerUIMode(WORD /* wNotifyCode */, WORD /* wID */, HWND /* hWndCtl */, BOOL& /* bHandled */) { CComBSTR m_bstrValue; HRESULT hr; hr = m_spWMPPlayer->get_uiMode(&m_bstrValue); if (FAILMSG(hr)) return 0; CStringDlg dlgString(L"IWMPCore->uiMode", m_bstrValue); if (dlgString.DoModal(m_hWnd) == IDOK) { hr = m_spWMPPlayer->put_uiMode(dlgString.m_bstrValue); if (FAILMSG(hr)) return 0; } return 0; } LRESULT CWMPHost::OnWMPPlayer2StretchToFit(WORD /* wNotifyCode */, WORD /* wID */, HWND /* hWndCtl */, BOOL& /* bHandled */) { HRESULT hr; VARIANT_BOOL fValue; CComPtr<IWMPPlayer2> spWMPPlayer2; hr = m_spWMPPlayer.QueryInterface(&spWMPPlayer2); if (FAILMSG(hr)) return 0; hr = spWMPPlayer2->get_stretchToFit(&fValue); if (FAILMSG(hr)) return 0; CBooleanDlg dlgBoolean(L"IWMPPlayer2->stretchToFit", fValue); if (dlgBoolean.DoModal(m_hWnd) == IDOK) { hr = spWMPPlayer2->put_stretchToFit(dlgBoolean.m_fValue); if (FAILMSG(hr)) return 0; } return 0; } LRESULT CWMPHost::FowardMsgToWMP(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled) { HRESULT hr; LRESULT llResult = 0; CComPtr<IOleInPlaceObjectWindowless> spSite = NULL; hr = m_spWMPPlayer->QueryInterface(&spSite); if( SUCCEEDED(hr) ) { spSite->OnWindowMessage(uMsg, wParam, lParam, &llResult); } bHandled = TRUE; return llResult; }
5c56c284e0d6052b4449ebc2d7ebead94d94b02e
5a92f6db6e8b7698aef17179b3c6864e06968294
/include/ffw/graphics/glrenderwindow.h
409c2f0aa4a439700908a7ac20567c9585c014d1
[ "MIT" ]
permissive
AlbertoGP/finegraphics
51de742339d298f43f211121f159fcaabf75e0dd
815eb9bc30ac27e8032785ed8963978c2aca758b
refs/heads/master
2022-01-18T23:10:31.185935
2019-01-20T11:14:44
2019-01-20T11:14:44
null
0
0
null
null
null
null
UTF-8
C++
false
false
13,309
h
glrenderwindow.h
/* This file is part of FineFramework project */ #ifndef FFW_GRAPHICS_GL_RENDER_WINDOW #define FFW_GRAPHICS_GL_RENDER_WINDOW #include <vector> #include <memory> #include "renderwindow.h" #include "monitors.h" #include "vec2.h" #include "config.h" #include "constants.h" namespace ffw { /** * @ingroup graphics * @brief An OpenGL render window using GLFW library */ class FFW_API GLRenderWindow: public RenderWindow { public: /** * @brief Returns a vector of all physical monitors available */ static std::vector<Monitor> getMonitors(); /** * @brief Returns the primary monitor defined by the OS */ static Monitor getPrimaryMonitor(); /** * @brief Returns all possible modes for the given monitor */ static std::vector<Monitor::Mode> getMonitorModes(const Monitor& monitor); /** * @brief Creates the window * @param args Arguments and hints for the window * @param other If another window is provided, their OpenGL context will be shared, * otherwise NULL * @param monitor If a monitor is provided, the window will be fullscreen */ GLRenderWindow(const RenderWindowArgs& args, GLRenderWindow* other, Monitor* monitor = nullptr); virtual ~GLRenderWindow(); /** * @brief Sets the position of the window relative to the framebuffer * @note This function must only be called from the main thread. */ void setPos(int posx, int posy) override; /** * @brief Sets the size of the window's framebuffer * @note This function must only be called from the main thread. */ void setSize(int width, int height) override; /** * @brief Returns the position of the window relative to the framebuffer (not relative to * the OS specific border around the window) */ Vec2<int> getPos() const override; /** * @brief Returns the size of the window's framebuffer (does not include the OS specific * border) */ Vec2<int> getSize() const override; /** * @brief Sets the window into windowed mode, if the window was in maximized mode * @note This function must only be called from the main thread. * @details This function sets the window in windowed mode. This function does not update * the height, width, or position. Instead, it uses the last size and position before * entering fullscreen mode. */ void setWindowedMode() const; /** * @brief Sets the window into windowed mode with specific size and position * @note This function must only be called from the main thread. * @details This function sets the window in windowed mode. This function also updates * the widh, height, and position. */ void setWindowedMode(int posx, int posy, int width, int height) const; /** * @brief Sets the window into fullscreen mode * @note This function must only be called from the main thread. * @details This function sets the monitor that the window uses for full screen mode. * When setting a monitor, this function updates the width, height and refresh rate of * the desired video mode and switches to the video mode closest to it. * The window position is ignored when setting a monitor. */ void setFullscreen(const Monitor* monitor) const; /** * @brief Returns true if shouldClose() has been set to true */ bool shouldRender() const override; /** * @brief Renders the frame by setting up the context and calling protected method render() * @details This function makes the OpenGL or OpenGL ES context of the specified window * current on the calling thread. A context can only be made current on a single thread * at a time and each thread can have only a single current context at a time. * This function also calls glViewport with the current window's framebuffer size. */ void renderFrame() override; /** * @brief Processes all user events * @details This function processes only those events that are already in the event queue * and then returns immediately. Processing events will cause the window and input callbacks * associated with those events to be called. On some platforms, a window move, resize will * cause event processing to block. This is due to how event processing is designed on those * platforms. You can use the window refresh callback to redraw the contents of your window * when necessary during such operations. */ void poolEvents() override; /** * @brief Waits for user events and processes them all * @note This function must only be called from the main thread. * @details This function puts the calling thread to sleep until at least one event is * available in the event queue. Once one or more events are available, it behaves exactly * like poolEvents, i.e. the events in the queue are processed and the function then returns * immediately. Processing events will cause the window and input callbacks associated with * those events to be called. Since not all events are associated with callbacks, * this function may return without a callback having been called even if you are monitoring * all callbacks. On some platforms, a window move, resize or menu operation will cause * event processing to block. This is due to how event processing is designed on those * platforms. You can use the window refresh callback to redraw the contents * of your window when necessary during such operations. */ void waitForEvents() override; /** * @brief Returns true if the window has been initialized * @note This function must only be called from the main thread. */ bool isInitialized() const override; /** * @brief Returns the address of the specified function for the current context. * @details This function returns the address of the specified OpenGL or OpenGL ES * core or extension function, if it is supported by the current context. * A context must be current on the calling thread. Calling this function without * a current context will cause a GLFW_NO_CURRENT_CONTEXT error. * @code * PFNGLACTIVETEXTUREPROC myGlActiveTexture = getGlextFunc("glActiveTexture"); * if (myGlActiveTexture != nullptr) { * std::cout << "myGlActiveTexture is loaded" << std::endl; * } * @endcode */ void* getGlextFunc(const std::string& name) const override; /** * @brief Returns wheter given GL extension is supported. */ bool isGlextExtSupported(const std::string& name) const override; /** * @brief Sets swap interval (enables or disables V-sync) * @note This function must only be called from the main thread. */ void setSwapInterval(int interval) const; /** * @brief Sets the internal should close flag * @details This function sets the swap interval for the current OpenGL or * OpenGL ES context, i.e. the number of screen updates to wait from the time * glfwSwapBuffers was called before swapping the buffers and returning. This is * sometimes called vertical synchronization, vertical retrace synchronization or * just vsync. */ void shouldClose(bool close) override; /** * @brief Makes the window visible * @details This function makes the specified window visible if it was previously hidden. * If the window is already visible or is in full screen mode, this function * does nothing. * @note This function must only be called from the main thread. */ void show() override; /** * @brief Makes the window hidden * @details This function hides the specified window if it was previously visible. * If the window is already hidden or is in full screen mode, this function * does nothing. * @note This function must only be called from the main thread. */ void hide() override; /** * @brief Iconifies the specified window * @details This function iconifies (minimizes) the specified window if it was previously * restored. If the window is already iconified, this function does nothing.If the * specified window is a full screen window, the original monitor resolution is restored * until the window is restored. * @note This function must only be called from the main thread. */ void iconify() override; /** * @brief Restores the specified window * @details This function restores the specified window if it was previously iconified * (minimized) or maximized. If the window is already restored, this function does nothing. * If the specified window is a full screen window, the resolution chosen for the window * is restored on the selected monitor. * @note This function must only be called from the main thread. */ void restore() override; /** * @brief Maximizes the specified window * @details This function maximizes the specified window if it was previously not * maximized. If the window is already maximized, this function does nothing. * If the specified window is a full screen window, this function does nothing. * @note This function must only be called from the main thread. */ void maximize() override; /** * @brief Sets single buffer mode * @details In single buffer mode, no back and front buffer swapping is done. Instead, * glFlush and glFinish is used. * @note This function must only be called from the main thread. */ void setSingleBufferMode(bool enabled) override; #if defined(FFW_WINDOWS) /** * @code * reinterpret_cast<HWND>(window->getCocoaWindow()); * @endcode */ void* getWin32Window(); /** * @code * reinterpret_cast<HGLRC>(window->getCocoaWindow()); * @endcode */ void* getWGLContext(); #elif defined(FFW_LINUX) /** * @code * reinterpret_cast<Window>(window->getCocoaWindow()); * @endcode */ void* getX11Window(); /** * @code * reinterpret_cast<Display*>(window->getCocoaWindow()); * @endcode */ void* getX11Display(); #elif defined(FFW_OSX) /** * @code * reinterpret_cast<NSWindow>(window->getCocoaWindow()); * @endcode */ void* getCocoaWindow(); /** * @code * reinterpret_cast<NSOpenGLContext>(window->getCocoaWindow()); * @endcode */ void* getNSGLContext(); #endif struct WindowCallback; friend struct WindowCallback; protected: /** * @brief Called every time the frame is being rendered */ virtual void render() = 0; /** * @brief Called when the user presses a key to type text (unicode only) */ virtual void textInputEvent(unsigned int c); /** * @brief Called when the user presses a physical key */ virtual void keyPressedEvent(ffw::Key key, ffw::KeyMode mode); /** * @brief Called when the user moves a mouse */ virtual void mouseMovedEvent(int mousex, int mousey); /** * @brief Called when the user scrolls down or up */ virtual void mouseScrollEvent(int scroll); /** * @brief Called when the user presses a mouse button */ virtual void mouseButtonEvent(ffw::MouseButton button, ffw::MouseMode mode); /** * @brief Called when the window is resized to a new size */ virtual void windowResizedEvent(int width, int height); /** * @brief Called when the window is moved to a new position */ virtual void windowMovedEvent(int posx, int posy); /** * @brief Called when the user presses the [X] button on the window */ virtual void windowCloseEvent(); /** * @brief Called when the window will gain or looses focus */ virtual void windowFocusEvent(bool focus); /** * @brief Called when the user drags and drops one or multiple files * @note UTF-8 enabled */ virtual void filesDroppedEvent(std::vector<std::string> filelist); private: class Impl; std::unique_ptr<Impl> pimpl; }; }; #endif
e559eb19dfcd3ca605f8f2a87c55aef3cc593dee
06ba4269a1bd6ceb5dfff799f33f808fb3ab1eff
/src/Surface.h
b68a844356e5a25f26e32f6e05f20b5472cc1611
[]
no_license
micahdlamb/Collision
bca7efc206ec57dc7812ce6f3ecfef159e49f2a9
dac5dfe3c414b432613d349e3102ed6f61756bab
refs/heads/master
2020-05-31T16:05:44.464911
2013-11-21T00:48:44
2013-11-21T00:48:44
null
0
0
null
null
null
null
UTF-8
C++
false
false
17,596
h
Surface.h
#pragma once //I, the index type must be defined struct Surface : public Viewport, public Scene, public FPInput { //typedef GLushort I; typedef glm::detail::tvec3<I> I3; Shader shader; UniformMat4 worldTransform; UniformMat3 normalTransform; Uniform1i pattern; Uniform1i reflectionsOn; Uniform1i blur; UniformSampler reflections; CubeBackground background; CubeMap* backgrounds[4]; bool wireframe; int terrainFile; float nearPlane, farPlane, fovY; const static int MAXVERTICES = 1000000;//1 million dollars ControlCurve* cc1, *cc2; Smoother<I> smoother; enum Mode {NOTHING,TRIANGLES,QUADS,CURVE,CUBE,PYRAMID,SPRING,TERRAIN,CATMULL,DOO_SABIN,LOOP}; Mode mode; vector<vec3> vertices, normals; vector<I> indices; VAO geom; Surface(float x, float y, float w, float h, ControlCurve* cc1, ControlCurve* cc2): Viewport(x,y,w,h) ,nearPlane(.01f), farPlane(1001.f), fovY(60.f) ,cc1(cc1), cc2(cc2) ,wireframe(false) ,terrainFile(-1) ,mode(NOTHING) { Scene::operator()(this); shader("surface.vert", "surface.frag"); shader.enable(); worldTransform("worldTransform",&shader); normalTransform("normalTransform",&shader); pattern("pattern",&shader, 1); Scene::globals.lights[0].color = vec3(0,1,0); Scene::globals.lights[0].pos = vec3(0,0,25); reflectionsOn("reflectionsOn",&shader,1); blur("blur",&shader,0); Viewer::pos = vec3(0,0,1.5f); #define STR(x) #x #define CM(file) STR(cubemaps/clouds/##file) char* clouds[] = {CM(px.png),CM(nx.png),CM(py.png),CM(ny.png),CM(pz.png),CM(nz.png)}; backgrounds[0] = new CubeMap(clouds, IL_ORIGIN_UPPER_LEFT); #undef CM #define CM(file) STR(cubemaps/deadmeat/##file) char* deadmeat[] = {CM(px.jpg),CM(nx.jpg),CM(py.jpg),CM(ny.jpg),CM(pz.jpg),CM(nz.jpg)}; backgrounds[1] = new CubeMap(deadmeat, IL_ORIGIN_UPPER_LEFT); #undef CM #define CM(file) STR(cubemaps/hills/##file) char* hills[] = {CM(px.png),CM(nx.png),CM(py.png),CM(ny.png),CM(pz.png),CM(nz.png)}; backgrounds[2] = new CubeMap(hills, IL_ORIGIN_UPPER_LEFT); #undef CM #define CM(file) STR(cubemaps/brightday/##file) char* brightday[] = {CM(px.png),CM(nx.png),CM(py.png),CM(ny.png),CM(pz.png),CM(nz.png)}; backgrounds[3] = new CubeMap(brightday, IL_ORIGIN_UPPER_LEFT); reflections("reflections",&shader,backgrounds[0]); background(backgrounds[0]); geom(mode, GL_DYNAMIC_DRAW); geom.bind(); geom.buffer(NULL, MAXVERTICES * sizeof(vec3));//vertices geom.in(3,GL_FLOAT); geom.buffer(NULL, MAXVERTICES * sizeof(vec3));//normals geom.in(3,GL_FLOAT); geom.buffer(NULL, MAXVERTICES * sizeof(GL_I) * 4);//*4 is guess, think about it later geom.indices(GL_I); geom.unbind(); } void setGeometry(vector<vec3>& vertices, vector<I>& indices, Mode mode){ this->vertices = vertices; this->indices = indices; setGeometry(mode); } //for some funcs its easier to copy verts and indices in directly void setGeometry(Mode mode){ setMode(mode); normals = computeNormals<I>(vertices, indices, faceSize()); push(); } void setMode(Mode mode){ if (this->mode != mode) onModeChange(this->mode, mode); this->mode = mode; } void onModeChange(Mode from, Mode to){ if (from == DOO_SABIN)//accomodate hack for doo_sabin smoother.feedbackAvailable = false; } void push(){ if (!indices.size()) return; geom.update(&vertices[0], vertices.size()*sizeof(vec3), 0); geom.update(&normals[0], normals.size() * sizeof(vec3), 1); geom.update(&indices[0], indices.size() * sizeof(I), 2); } GLenum glMode(){ switch(mode){ case DOO_SABIN: case LOOP: case PYRAMID: case TRIANGLES: return GL_TRIANGLES; default: return GL_QUADS; } } int faceSize(){ return glMode()==GL_QUADS?4:3; } void clear(){ setMode(NOTHING); indices.clear(); vertices.clear(); } void setPattern(int pattern){ shader.enable(); switch(pattern){ case 0: Scene::globals.lights[0].color = vec3(0,1,0); break; case 1: Scene::globals.lights[0].color = vec3(1,1,0); break; case 2: Scene::globals.lights[0].color = vec3(0,0,1); break; case 3: Scene::globals.lights[0].color = vec3(1,1,0); break; } this->pattern = pattern; } void toggleReflections(){ shader.enable(); reflectionsOn = *reflectionsOn ? 0 : 1; } void setBlur(int i){ shader.enable(); blur = clamp(i,0,8); } void setBackground(int i){ shader.enable(); //reflections = backgrounds[i]; background.set(backgrounds[i]); } void setWorldTransform(mat4& m){ shader.enable(); worldTransform = m; normalTransform = mat3(transpose(inverse(m))); } virtual void draw(){ //glEnable(GL_CULL_FACE); frame(); glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); background.draw(); shader.enable(); glPushAttrib(GL_POLYGON_BIT); if (wireframe) glPolygonMode( GL_FRONT_AND_BACK, GL_LINE ); geom.draw(indices.size(),0,glMode()); glPopAttrib(); } /////////////////////// //CURVE & SURFACE STUFF /////////////////////// I strideX; bool wrapX(){ return surfaceType == REVOLUTION || (curveClosed() && surfaceType == SWEEP); } bool wrapY(){ return curveClosed(); } void buildFromCurves(){ clear(); if (!((surfaceType == REVOLUTION || surfaceType == EXTRUSION) && cc1->curvePts.size() > 2 || cc1->curvePts.size() > 2 && cc2->curvePts.size() > 1)) return; vector<vec2> curve1 = cc1->getCurvePtPositions(), curve2 = cc2->getCurvePtPositions(); //remove duplicate point on closed curves if (curveClosed()){ curve1.pop_back(); if (curve2.size()) curve2.pop_back(); } //compute vertices switch (surfaceType){ case REVOLUTION: vertices = Surfaces::revolution(curve1); break; case EXTRUSION: vertices = Surfaces::extrusion(curve1); break; case SWEEP: vertices = Surfaces::sweep(curve1, curve2, extrude); break; } strideX = (I)curve1.size();//store strideX for use in other surface funcs indices = gridIndices((I)vertices.size(), strideX, wrapX(), wrapY()); setGeometry(CURVE); } //convert vertices to grid (2d array vector) vector<vector<vec3 >> unflatten(){ vector<vector<vec3 >> grid(vertices.size() / strideX); for (U i=0,x=0; i < vertices.size(); i+=strideX,x++){ grid[x].resize(strideX); for (U y=0; y < strideX; y++) grid[x][y] = vertices[i+y]; } return grid; } //convert grid to void flatten(vector<vector<vec3 >> grid, bool wrapX, bool wrapY){ vertices.clear(); strideX = grid[0].size(); for (U x=0; x < grid.size(); x++){ //if (wrapX && x == grid.size()-1) //continue; for (U y=0; y < strideX; y++) vertices.push_back(grid[x][y]); } indices = gridIndices((I)vertices.size(), strideX, wrapX, wrapY); } void surface(int type){ if (mode != CURVE) return; //construct grid auto grid = unflatten(); switch (type){ case 0: if (strideX > 25 || (surfaceType == REVOLUTION && slices > 25)){ cout << "too many curve points or slices.... will take too long" << endl; return; } grid = Bezier::casteljauSurf(grid, 100, wrapX(), wrapY()); flatten(grid, wrapX(), wrapY()); break; case 1: grid = BSpline::cubic_surface(grid, 3, wrapX(), wrapY()); flatten(grid, wrapX(), wrapY()); break; } setGeometry(CURVE); } void smooth(int type=0){ if (!indices.size()) return; Mode mode; switch (type){ case 0: mode = CATMULL; smoother.catmull_clark(vertices, indices, faceSize()); break; case 1: mode = DOO_SABIN; smoother.doo_sabin(vertices, indices, faceSize()); break; case 2: mode = LOOP; smoother.loop(vertices, indices, faceSize()); } smoother.printErrors(); setGeometry(smoother.newVertices, smoother.newIndices, mode); cout << "smooth complete" << endl; } void cube(){ GLfloat v[] = { -.5, .5, .5, -.5, -.5, .5, .5, -.5, .5, .5, .5, .5, -.5, .5, -.5, -.5, -.5, -.5, .5, -.5, -.5, .5, .5, -.5, }; I i[] = { 0, 1, 2, 3, 3, 2, 6, 7, 7, 6, 5, 4, 4, 5, 1, 0, 0, 3, 7, 4, 1, 5, 6, 2 }; vertices.assign((vec3*)v, (vec3*)(v + 24));//strange that casts required indices.assign(i, i + 24); setGeometry(CUBE); } void pyramid(){ GLfloat v[] = { -.5,-.5,.5, .5,-.5,.5, .5,-.5,-.5, -.5,-.5,-.5, 0, .5, 0 }; I i[] = { 0,3,1, 1,3,2, 0,1,4, 1,2,4, 2,3,4, 3,0,4, }; vertices.assign((vec3*)v, (vec3*)(v + 15));//strange that casts required indices.assign(i, i + 18); setGeometry(PYRAMID); } vector<vec2> circlePts(float radius, int numPts){ vector<vec2> pts; float dtheta = 2*PI / numPts; float EPS = dtheta / 2; for (float theta=0; theta < 2*PI - EPS; theta+=dtheta) pts.push_back(vec2(cos(theta), sin(theta)) * radius); return pts; } vector<vec3> helixPts(float loops, float radius, float height, int numPts){ vector<vec3> pts; numPts--;//since loop adds extra point float rads = 2*PI * loops; float dtheta = rads / numPts; float dy = height / numPts; float EPS = dtheta / 2; for (float theta=0, y=-height/2; abs(theta) < abs(rads)+EPS; theta+=dtheta, y+=dy) pts.push_back(vec3(cos(theta) * radius, y, -sin(theta) * radius)); return pts; } void triangulateQuads(vector<I>& indices){ vector<I> triIndices; for (size_t i=0; i < indices.size(); i+=4){ triIndices.push_back(indices[i]); triIndices.push_back(indices[i+1]); triIndices.push_back(indices[i+3]); triIndices.push_back(indices[i+1]); triIndices.push_back(indices[i+2]); triIndices.push_back(indices[i+3]); } indices = triIndices; } //fill in a shape with triangles template <class I> vector<I> triangulate(I begin, I end, I pt, bool reverse=false){ vector<I> indices; for (auto i=begin; i < end; i++){ indices.push_back(i); indices.push_back((i == end-1) ? begin : i+1); indices.push_back(pt); } if (reverse) std::reverse(indices.begin(), indices.end()); return indices; } //must have even number of points >= 6 template <class I> vector<I> quadFan(I begin, I end, I center, bool reverse=false){ vector<I> indices; for (I i = begin; i < end; i += 2){ indices.push_back(i); indices.push_back(i+1); indices.push_back((i+2 == end) ? begin : i+2); indices.push_back(center); } if (reverse) for (size_t i=0; i < indices.size(); i+=4) swap(indices[i], indices[i+2]); return indices; } void spring(float loops=5, float radius=.1, float thickness=.05, float height=1, int verts=2000, bool smoothCaps=false){ float helixLen = sqrt(pow(loops * PI * radius * 2, 2) + pow(height, 2)); float circleLen = PI * thickness * 2; float ratio = circleLen / helixLen; int helixVerts = sqrt(verts / ratio); int circleVerts = verts / helixVerts; //make sure circleVerts >= 6 and even so the quadFan func will work if (circleVerts < 6) circleVerts = 6; if (circleVerts % 2) circleVerts++; //generate helix quads auto circle = circlePts(thickness, circleVerts); auto helix = helixPts(loops, radius, height, helixVerts); vertices = Surfaces::sweep(circle, helix); strideX = (I)circle.size();//store strideX for use in other smoothing funcs indices = gridIndices((I)vertices.size(), strideX, false, true); //generate caps quads if (smoothCaps){ auto cap1 = quadFan<I>(vertices.size()-circle.size(), vertices.size(), vertices.size(), true); vertices.push_back(helix.back()); auto cap2 = quadFan<I>(0, circle.size(), vertices.size()); vertices.push_back(helix[0]); indices.insert(indices.end(), cap1.begin(), cap1.end()); indices.insert(indices.end(), cap2.begin(), cap2.end()); } else { auto helixEnd = vertices.size(); vertices.insert(vertices.end(), vertices.begin(), vertices.begin() + circle.size()); auto cap1 = quadFan<I>(vertices.size()-circle.size(), vertices.size(), vertices.size()); vertices.push_back(helix[0]); vertices.insert(vertices.end(), &vertices[helixEnd - circle.size()], &vertices[helixEnd]); auto cap2 = quadFan<I>(vertices.size()-circle.size(), vertices.size(), vertices.size(), true); vertices.push_back(helix.back()); indices.insert(indices.end(), cap1.begin(), cap1.end()); indices.insert(indices.end(), cap2.begin(), cap2.end()); } setGeometry(QUADS); } void terrain(){ terrainFile = ++terrainFile % 5; string file = string("terrain")+itos(terrainFile) + ".hm"; Array2d<float> heights; msg("loading terrain map",file); heights.load(file.c_str()); clear(); Array2d<vec3> vertices(heights.cols,heights.rows);; for (U x=0; x < heights.cols; x++) for (U z=0; z < heights.rows; z++) vertices[x][z] = vec3((x/(float)heights.cols)-.5,heights[x][z]/5.f,-(z/(float)heights.rows)+.5); //quads #define v(x,y) vertices.index(x,y) for (U y=0; y < vertices.rows-1; y++){ for (U x=0; x < vertices.cols-1; x++){ indices.push_back(v(x,y)); indices.push_back(v(x+1,y)); indices.push_back(v(x+1,y+1)); indices.push_back(v(x,y+1)); } } //trick vector into copying an Array2d this->vertices.assign(vertices.value_ptr(), vertices.value_ptr() + vertices.size()); setGeometry(TERRAIN); } void frame(){ FPInput::frame(); Scene::frame(); if (keys['>']) setWorldTransform(scale(mat4(1),vec3(1) + vec3(Clock::delta)) * *worldTransform); if (keys['<']) setWorldTransform(scale(mat4(1),vec3(1) - vec3(Clock::delta)) * *worldTransform); if (keys['c']) Scene::globals.lights[0].color = rainbowColors(.01); if (keys['X']) setWorldTransform(*worldTransform * scale(mat4(1),vec3(1+Clock::delta,1,1))); if (keys['x']) setWorldTransform(*worldTransform * scale(mat4(1),vec3(1-Clock::delta,1,1))); if (keys['Y']) setWorldTransform(*worldTransform * scale(mat4(1),vec3(1,1+Clock::delta,1))); if (keys['y']) setWorldTransform(*worldTransform * scale(mat4(1),vec3(1,1-Clock::delta,1))); if (keys['Z']) setWorldTransform(*worldTransform * scale(mat4(1),vec3(1,1,1+Clock::delta))); if (keys['z']) setWorldTransform(*worldTransform * scale(mat4(1),vec3(1,1,1-Clock::delta))); } //called by the ViewportManager virtual void resize(){ Scene::resize(perspective(fovY, (GLfloat)w/h, nearPlane, farPlane), w, h); } virtual void mouseButton(int button, int state, int x, int y){ FPInput::mouseButton(button, state, x, y); } virtual void mouseMove(int x, int y) { FPInput::mouseMove(x, y); //rotate worldTransform with right mouse if (mouseDown[1]){ mat4 m = rotate(mat4(1), mouseDelta.x*25.f*Clock::delta, vec3(0,1,0)) * rotate(mat4(1), -mouseDelta.y*25.f*Clock::delta, right()); setWorldTransform(m * *worldTransform); } } virtual void passiveMouseMove(int x, int y){ //inputHandler.passive } virtual void keyDown (unsigned char key, int x, int y) { FPInput::keyDown(key, x, y); switch (key){ case 'p': setWorldTransform(mat4(1)); break; case 'r': toggleReflections(); break; case ',': setBlur(*blur-1); break; case '.': setBlur(*blur+1); break; case '/': cout << "vertices / indices: " << vertices.size() << " / " << indices.size() << endl; break; //experiment with custom shading in surface.frag case '1': case '2': case '3': /* case '4': case '5': case '6': case '7': case '8': case '9': */ pattern = key-'1'; break; case ' ': wireframe = !wireframe; break; } } virtual void keyUp(unsigned char key, int x, int y){ FPInput::keyUp(key, x, y); } void load(const char* file){ cout << "loading: " << file << endl; ifstream fin(file); if (fin.fail()){ cout << "file couldn't be opened" << endl; return; } clear(); stringstream ss; string line; int numVertices, numFaces; getline(fin, line); //cout << line << endl; getline(fin, line); //cout << line << endl; ss << line; ss >> numVertices; ss >> numFaces; cout << "vertices="<<numVertices << " faces="<< numFaces << endl; for (int i=0; i < numVertices; i++){ ss.str(""); ss.clear(); getline(fin, line); ss << line; vec3 v; ss >> v.x; ss >> v.y; ss >> v.z; vertices.push_back(v); } int faceSize=-1; for (int i=0; i < numFaces; i++){ ss.str(""); ss.clear(); getline(fin, line); ss << line; /*use this to allow faces other than triangle, will fail for files with multiple face sizes int tmp; ss >> tmp; assert(faceSize == -1 || faceSize == tmp); faceSize = tmp; for (int j=0; j < faceSize; j++){ I index; ss >> index; indices.push_back(index); } */ ss >> faceSize; vector<I> face; for (int j=0; j < faceSize; j++){ I index; ss >> index; face.push_back(index); } //convert face into triangles for (U j=1; j < face.size()-1; ++j){ indices.push_back(face[0]); indices.push_back(face[j]); indices.push_back(face[j+1]); } } setGeometry(TRIANGLES);//getMode(faceSize) } void print(const char* file){ cout << "saving geometry to: " << file << endl; ofstream out(file); out << vertices.size() << " " << indices.size() / 4 << endl; for (U i=0; i < vertices.size(); i++) out << vertices[i].x << " " << vertices[i].y << " " << vertices[i].z << endl; for (U i=0; i < indices.size(); i+=4){ for (int j=0; j < 4; j++) out << indices[i+j] << " "; out << endl; } } };
a294aab1016715f2c478f6b98f4018031d9a387b
6122703152701f6ae24865f3d94fe95ae8b83c86
/Projekt-Zaliczeniowy.cpp
22c77d80ada318c643e242844ca6a147f9c34f7a
[]
no_license
DawidDabkowski/Programowanie-Obiektowe
a8e37a770fd55f3245f6b31cfe2a1563046b74e7
2db85591fab2e5ad15440cf59b26d2fd3ef45f12
refs/heads/master
2021-01-23T13:16:23.292208
2017-06-03T09:02:27
2017-06-03T09:02:27
93,236,611
0
0
null
null
null
null
UTF-8
C++
false
false
72,013
cpp
Projekt-Zaliczeniowy.cpp
#include <iostream> #include <queue> // priority_queue #include <cassert> // Dodatkowe sprawdzania (assert) #include <cstdlib> // Generacja liczb losowych (srand, rand) #include <ctime> // time, użyty tylko w srand #include <cmath> // floor #include <vector> // vector #include <fstream> // Zaślepka #include <sstream> // ostringstream - zaślepka dla to_string #include <cstring> using namespace std; // deklaracje klas i struktur wystepujacych w programie struct ElementBiletu; struct ElementLinii; class Czas; class Zdarzenie; class Compare; class KolejkaZdarzen; class Bilet; class BiletTeatr; class Statystyki; class Obiekt; class Przystanek; class Linia; class LiniaTramwajowa; class Pojazd; class Tramwaj; class Miejsce; class Uniwersytet; class Teatr; class CentrumHandlowe; class Osoba; class Pracujacy; class Artysta; class Student; class Uczen; //--- Zaślepka: potrzebna tylko dla MinGW pod Windows zwn na błąd w tamtej implementacji ------------------ template <typename T> string to_string(const T& n) { ostringstream stm; stm << n; return stm.str(); }; //--- Koniec zaślepki ---------------------------------- class Czas { private: int miesiac, dzien, godzina, minuta, dzienTygodnia; public: // API int DajMiesiac() const {return miesiac;}; int DajDzien() const {return dzien;}; int DajGodzina() const {return godzina;}; int DajMinuta() const {return minuta;}; int DajDzienTygodnia() const {return dzienTygodnia;}; Czas Dzisiaj(); Czas Srodek(); Czas Jutro(); void operator+=(const Czas&); Czas operator+(const Czas&); void operator+=(const int&); Czas operator+(const int&); void operator-=(const Czas&); Czas operator-(const Czas&); void operator-=(const int&); Czas operator-(const int&); Czas& operator=(const Czas&); bool operator>(Czas); bool operator<(Czas); bool operator==(Czas); bool operator!=(Czas); bool operator>=(Czas); bool operator<=(Czas); Czas& operator++(); Czas operator++(int); Czas& operator--(); Czas operator--(int); // operator << zdefiniowany jako funkcja // Techniczna string ToString() const; void Skroc(); Czas(int mies, int dz, int godz, int min); Czas(const Czas&) = default; ~Czas() = default; }; class Zdarzenie { private: static int idNo; // Zmienna klasowa, numer kolejnego zdarzenia Czas czas; // Kiedy ma nastąpić zdarzenie? Obiekt& kto; // Kto zgłosił to zdarzenie? string czynnosc; // Jaka czynnosc zainicjalizowala zdarzenie? int id; // Identyfikator zdarzenia public: // API virtual void Zajdz() const; // Niech to zdarzenie zajdzie virtual Czas DajCzas() const {return czas;}; // Daje czas zdarzenia virtual int DajId() const {return id;}; // Daje identyfikator zdarzenia virtual Obiekt& DajKto() const {return kto;}; // Daje ref do osoby, ktora wywolala zdarzenie virtual string DajCzynnosc() const {return czynnosc;}; // Daje nazwe czynnosci, ktora osoba ma wykonac virtual string to_stringImpl() const; // Postać tekstowa obiektu, przydatna szczególnie przy debugowaniu. Zwykle używa się nazwy to_string(). //techniczne Zdarzenie(Czas, Obiekt&, string); // Konstruktor główny Zdarzenie() = delete; // Zdarzenia wymagają danych, konstr. bezarg. to nie dla nich! Zdarzenie(const Zdarzenie&) = delete; // Nie chcemy kopiować zdarzeń Zdarzenie& operator=(const Zdarzenie&) = delete; // P. wyżej/ virtual ~Zdarzenie() = default; // Ta deklaracja jest konieczna zwn virtual! }; int Zdarzenie::idNo = 0; // Zmienna klasowa z Zdarzenie class Compare { // Klasa obiektów porównujących zdarzenia, potrzebna zwn priority_queue public: bool operator()(const Zdarzenie* z1, const Zdarzenie* z2) { return ((z1->DajCzas() > z2->DajCzas()) || ((z1->DajCzas() == z2->DajCzas()) && (z1->DajId() > z2->DajId())) ); } }; class KolejkaZdarzen { priority_queue<const Zdarzenie*, std::vector<const Zdarzenie*>, Compare> zdarzenia; // Mam kolejkę zdarzeń i nie zawaham się jej użyć Czas czas; // Aktualny czas symulacji public: // API virtual void Wstaw(const Zdarzenie*); // Wstawia zdarzenie do wykonania w przyszłości virtual Czas& KtoraGodzina() {return czas;}; // Która jest właściwie teraz godzina? virtual int DzienTygodnia() {return czas.DajDzienTygodnia();}; virtual void NiechSieDzieje(Czas koniecSwiata); // Wykonuj zdarzenia do wskazanego czasu // techniczne KolejkaZdarzen(); // Zaczynamy o godzinie 0 z pustą kolejką zdarzeń KolejkaZdarzen(const KolejkaZdarzen&) = delete; // Nie kopiuj mnie, proszę. A nawet nalegam. KolejkaZdarzen& operator=(const KolejkaZdarzen&) = delete; // Patrz konstr. kop. virtual ~KolejkaZdarzen() = default; // Nie mam wskaźników, więc default mi pasuje! }; // --- Definicja globalnej kolejki --- KolejkaZdarzen kol; // --- Koniec definicji --- struct ElementBiletu { int liniaId; int przystanekId; bool czyNaprzod; ElementBiletu* nast; ElementBiletu(int linId, int przystId, bool czyNap, ElementBiletu* nas) : liniaId(linId), przystanekId(przystId), czyNaprzod(czyNap), nast(nas) {}; }; class Bilet { protected: ElementBiletu* trasa; ElementBiletu* aktualny; public: // API void DodajPrzesiadke(int, int, bool); // void DodajOdwrotny(); ElementBiletu* DajKoniec(); ElementBiletu* DajAktualny() {return aktualny;}; void Przesun() {aktualny = aktualny->nast;}; void Uprosc(); // techniczne void Wypisz(); Bilet(); Bilet(int, int, bool); //Bilet(int, int, bool, int, int, bool); Bilet(const Bilet&) = default; ~Bilet(); }; class BiletTeatr { protected: int teatrId; Czas czasSpektaklu; public: // API int DajTeatrId() {return teatrId;}; Czas DajCzasSpektaklu() {return czasSpektaklu;}; // techniczne BiletTeatr() = delete; BiletTeatr(int tId, Czas czasSpek) : teatrId(tId), czasSpektaklu(czasSpek) {}; BiletTeatr(const BiletTeatr&) = delete; ~BiletTeatr() = default; }; class Statystyki { private: int liczbaPrzejazdow[7]; // +1 gdy osoba wchodzi do tramwaju int czasCzekania[7]; // +X gdy os. wchodzi; -Y gdy schodzi/taxi int liczbaCzekania[7]; // +1 gdy osoba wchodzi na przystanek int osoboSpektakle[7]; // +1 gdy osoba wychodzi do teatru int miejscoSpektakle[7]; // +X gdy teatr odgrywa spektakl int liczbaZakupow[7]; // +1 gdy osoba wychodzi na zakupy public: // API void zmienLiczbaPrzejazdow(int l) {liczbaPrzejazdow[kol.KtoraGodzina().DajDzienTygodnia()] += l;}; void zmienCzasCzekania(int l) {czasCzekania[kol.KtoraGodzina().DajDzienTygodnia()] += l;}; void zmienLiczbaCzekania(int l) {liczbaCzekania[kol.KtoraGodzina().DajDzienTygodnia()] += l;}; void zmienOsoboSpektakle (int l) {osoboSpektakle[kol.KtoraGodzina().DajDzienTygodnia()] += l;}; void zmienMiejscoSpektakle(int l) {miejscoSpektakle[kol.KtoraGodzina().DajDzienTygodnia()] += l;}; void zmienLiczbaZakupow(int l) {liczbaZakupow[kol.KtoraGodzina().DajDzienTygodnia()] += l;}; string ToString() const; // techniczne Statystyki(); Statystyki(const Statystyki&) = delete; ~Statystyki() = default; }; class Obiekt { protected: string typ; // typ odroznia obiekty roznych podklas int id; // identyfikator odroznia obiekty w obrebie podklasy int przystanekId; // id aktualnego polozenia obiektu; -1 oznacza obiekt niematerialny lub "poza" miastem Czas zajetyDo; // w niektorych przypadkach obiekt jest zajety i nie powinien reagowac na zdarzenia do jakiejs godziny Bilet* bilet; // obiekt bedacy w podrozy rowniez nie powinien reagowac stad potrzeba rozrozniana czy obiekt ma bilet // zmienne stat. daja obiektom dostep do glob. inform. uzywanych w metodach static int liczbaPrzystankow; static int liczbaLiniiTramwajowych; static int liczbaUniwersytetow; static int liczbaTeatrow; static int liczbaCentrowHandlowych; static Przystanek* przystanki; static LiniaTramwajowa* linieTramwajowe; static Uniwersytet* uniwersytety; static Teatr* teatry; static CentrumHandlowe* centraHandlowe; static Statystyki* statystyki; public: // API virtual bool Reaguj(string) = 0; virtual string DajTyp() const {return typ;}; virtual int DajId() const {return id;}; virtual int DajPrzystanekId() const {return przystanekId;}; virtual Czas DajZajetyDo() const {return zajetyDo;}; virtual Bilet* DajBilet() {return bilet;}; virtual void PrzesunBilet() {bilet->Przesun();}; virtual void KasujBilet(); // operator << zdefiniowany jako funkcja // techniczne virtual string ToString() const; virtual string ToStringSimple() const; static void UstawLiczbaPrzystankow(int l) {liczbaPrzystankow = l;}; static void UstawLiczbaLiniiTramwajowych(int l) {liczbaLiniiTramwajowych = l;}; static void UstawLiczbaUniwersytetow(int l) {liczbaUniwersytetow = l;}; static void UstawLiczbaTeatrow(int l) {liczbaTeatrow = l;}; static void UstawLiczbaCentrowHandlowych(int l) {liczbaCentrowHandlowych = l;}; static void UstawPrzystanki(Przystanek* przyst) {przystanki = przyst;}; static void UstawLinieTramwajowe(LiniaTramwajowa* lin) {linieTramwajowe = lin;}; static void UstawUniwersytety(Uniwersytet* uniw) {uniwersytety = uniw;}; static void UstawTeatry(Teatr* te) {teatry = te;}; static void UstawCentraHandlowe(CentrumHandlowe* centra) {centraHandlowe = centra;}; static void UstawStatystyki(Statystyki* stat) {statystyki = stat;}; explicit Obiekt(string, int, int); // explicit, bo chcę konstruktora, ale nie konwersję Obiekt(); Obiekt(const Obiekt&) = default; Obiekt& operator=(const Obiekt&) = default; virtual ~Obiekt() = default; // To jest bardzo ważne zw. virtual }; class Przystanek : public Obiekt { protected: string polozenie; deque<Osoba*> kolejka; // nowe osoby wchodza na poczatek public: // API bool Reaguj(string) override; void PlanujDzien(); void KonczDzialanie(); void Ustaw(Osoba* o) {kolejka.push_front(o);}; void Oddal(int i) {kolejka.erase(kolejka.begin()+i);}; string DajPolozenie() const {return polozenie;}; Osoba* DajOsoba(int i) {return kolejka[i];}; int DajDlugosc() {return kolejka.size();}; // techniczne string ToString() const; Przystanek(); Przystanek(int, string); Przystanek(const Przystanek&) = delete; ~Przystanek() = default; }; struct ElementLinii { int przystanekId; int czas; ElementLinii* poprz; ElementLinii* nast; ElementLinii(int przystId, int cz, ElementLinii* pop, ElementLinii* nas) : przystanekId(przystId), czas(cz), poprz(pop), nast(nas){}; }; class Linia : public Obiekt { // Linia impl. jako lista dwukierunkowa protected: int liczbaPojazdow; ElementLinii* trasa; public: // API virtual void DodajPrzystanek(int, int); ElementLinii* DajPoczatekTrasy(); ElementLinii* DajKoniecTrasy(); int CzasPostoju() {return DajKoniecTrasy()->czas;}; // techniczne virtual string ToString() const; Linia(); Linia(int, int); Linia(const Linia&) = delete; virtual ~Linia(); }; class LiniaTramwajowa : public Linia { protected: static double procentZmniejszenia; double odstep; Tramwaj* tramwaje; int wypuszczone; public: // API bool Reaguj(string); void PlanujDzien(); void WyslijTramwaj(bool); // techniczne double LiczOdstep(); static void UstawProcentZmniejszenia(double p) {procentZmniejszenia = p;}; string ToString() const; LiniaTramwajowa(); LiniaTramwajowa(int, int); LiniaTramwajowa(const Linia&) = delete; // ~LiniaTramwajowa(); }; class Pojazd : public Obiekt { protected: int liniaId; ElementLinii* polozenieTrasa; public: // API // techniczne string ToString() const; Pojazd(); Pojazd(string, int, int); Pojazd(const Pojazd&) = delete; ~Pojazd() = default; }; class Tramwaj : public Pojazd { protected: static int pojemnosc; vector<Osoba*> pasazerowie; bool czyNaprzod; public: // API bool Reaguj(string); void RuszajNaprzod(); void RuszajWstecz(); void AktualizujPasazerow(); void Wysiadac(); void Wsiadac(); void KonczKursowanie(); void UstawPrzystanekId(int przystId) {przystanekId = przystId;}; void UstawPolozenieTrasa(ElementLinii* polTrasa) {polozenieTrasa = polTrasa;}; // techniczne string ToString() const; static void UstawPojemnosc(int poj) {pojemnosc = poj;}; Tramwaj(); Tramwaj(int, int); Tramwaj(const Tramwaj&) = delete; ~Tramwaj() = default; }; class Miejsce : public Obiekt { protected: string nazwa; public: // API virtual string DajNazwa() const {return nazwa;}; // techniczne virtual string ToString() const; Miejsce(); Miejsce(string, int, string, int); Miejsce(const Miejsce&) = delete; ~Miejsce() = default; }; class Uniwersytet : public Miejsce { protected: // ... public: // API bool Reaguj(string) {return true;}; // techniczne string ToString() const; Uniwersytet(); Uniwersytet(int, string, int); Uniwersytet(const Uniwersytet&) = default; ~Uniwersytet() = default; }; class Teatr : public Miejsce { protected: int pojemnosc; bool czyOtwarty[5]; Czas pierwszyWolny; Czas czasSpektaklu; int zapelnieniePierwszyWolny; public: // API Czas DajPierwszyWolny() {return pierwszyWolny;}; Czas DajCzasSpektaklu() {return czasSpektaklu;}; bool Reaguj(string); void SprzedajBilet(); void OdgrywajSpektakl(); void KonczSpektakl(); // techniczne void AktualizujPierwszyWolny(); string ToString() const; Teatr(); Teatr(int, string, int, int); Teatr(const Teatr&) = delete; ~Teatr() = default; }; class CentrumHandlowe : public Miejsce { protected: // ... public: // API bool Reaguj(string) {return true;}; // techniczne string ToString() const; CentrumHandlowe(); CentrumHandlowe(int, string, int); CentrumHandlowe(const CentrumHandlowe&) = delete; ~CentrumHandlowe() = default; }; class Osoba : public Obiekt { protected: int mieszkanieId; static double pZakupy; double pTeatr; BiletTeatr* biletTeatr; public: // API virtual bool Reaguj(string); virtual void PlanujDzien() = 0; virtual void Podroz(int); //virtual void Podroz2(int); //virtual Bilet SzukajBiletu(Bilet, bool*, int); virtual void UstawNaPrzystanku(); virtual void ZejdzZPrzystanku(); virtual void WsiadzDoTramwaju(); virtual void WysiadzZTramwaju(); virtual int DajMieszkanieId() {return mieszkanieId;}; virtual void NaZakupy(); virtual void ZZakupow(); virtual Czas LosujCzasNaZakupy(); virtual void RezerwujTeatr(); virtual void DoTeatru(); virtual void ZTeatru(); virtual void KasujBiletTeatr(); virtual void ZamowTaxi(); virtual void UstawPrzystanekId(int przystId) {przystanekId = przystId;}; // techniczne virtual string ToString() const; static void UstawPZakupy(double p) {pZakupy = p;}; Osoba(); Osoba(string, int, double); Osoba(const Osoba&) = delete; ~Osoba() = default; }; class Pracujacy : public Osoba { protected: int pracaId; Czas czasDoPracy; static double pWyjazd; static double pTeatr; public: // API bool Reaguj(string); void PlanujDzien(); void DoPracy(); void WyjazdSluzbowy(); void ZPracy(); // techniczne string ToString() const; static void UstawPWyjazd(double p) {pWyjazd = p;}; static void UstawPTeatr(double p) {pTeatr = p;}; Pracujacy(); Pracujacy(int); Pracujacy(const Pracujacy&) = delete; ~Pracujacy() = default; }; class Artysta : public Osoba { protected: int pracaId[7]; static double pTeatr; public: // API bool Reaguj(string); Czas LosujCzasDoPracy(); void PlanujDzien(); void DoPracy(); void ZPracy(); // techniczne string ToString() const; static void UstawPTeatr(double p) {pTeatr = p;}; Artysta(); Artysta(int); Artysta(const Artysta&) = delete; ~Artysta() = default; }; class Student : public Osoba { protected: int uniwersytet1Id; int uniwersytet2Id; Czas czasNaUniwersytet[5]; Czas czasZajec[5]; static double pTeatr; public: // API bool Reaguj(string); void PlanujDzien(); void NaUniwersytet(); void ZUniwersytetu(); // techniczne string ToString() const; static void UstawPTeatr(double p) {pTeatr = p;}; Student(); Student(int, bool); Student(const Student&) = delete; ~Student() = default; }; class Uczen : public Osoba { protected: int szkolaId; Czas czasLekcji[5]; static double pTeatr; public: // API bool Reaguj(string); void PlanujDzien(); void DoSzkoly(); void ZeSzkoly(); // techniczne string ToString() const; static void UstawPTeatr(double); Uczen(); Uczen(int); Uczen(const Uczen&) = delete; ~Uczen() = default; }; // --- Implementacja Czas --- Czas Czas::Dzisiaj() { Czas a(miesiac, dzien, 0, 0); return a; }; Czas Czas::Srodek() { Czas a(0, 0, 0, 0); a.minuta = (((miesiac * 30 + dzien)*24 + godzina)*60 + minuta) / 2; a.Skroc(); return a; }; Czas Czas::Jutro() { Czas a(miesiac, dzien + 1, 0, 0); return a; }; // W moim programie wszystkie skladowe czasu licze od 0, dla prostoty i // spojnosci zapisu czasu jako daty i jako odstepu czasu. void Czas::operator+=(const Czas& a) { miesiac += a.miesiac; dzien += a.dzien; godzina += a.godzina; minuta += a.minuta; dzienTygodnia = (dzienTygodnia + a.dzienTygodnia) % 7; Skroc(); }; Czas Czas::operator+(const Czas& a) { Czas wyn(*this); wyn += a; return wyn; }; void Czas::operator+=(const int& a) { Czas b(0, 0, 0, a); (*this) += b; }; Czas Czas::operator+(const int& a) { Czas wyn(*this); wyn += a; return wyn; }; void Czas::operator-=(const Czas& a) { assert(*this>a); minuta = ((miesiac * 30 + dzien)*24 + godzina)*60 + minuta; godzina = 0; dzien = 0; miesiac = 0; dzienTygodnia = 0; minuta -= ((a.miesiac * 30 + a.dzien)*24 + a.godzina)*60 + a.minuta; Skroc(); }; Czas Czas::operator-(const Czas& a) { Czas wyn(*this); wyn -= a; return wyn; }; void Czas::operator-=(const int& a) { Czas b(0, 0, 0, a); assert(*this>b); (*this) -= b; }; Czas Czas::operator-(const int& a) { Czas wyn(*this); wyn -= a; return wyn; }; Czas& Czas::operator=(const Czas& a) { if(&a != this) { miesiac = a.miesiac; dzien = a.dzien; godzina = a.godzina; minuta = a.minuta; dzienTygodnia = a.dzienTygodnia; } return *this; }; bool Czas::operator>(Czas a) { if (miesiac > a.miesiac) return true; else if (miesiac < a.miesiac) return false; else if (dzien > a.dzien) return true; else if (dzien < a.dzien) return false; else if (godzina > a.godzina) return true; else if (godzina < a.godzina) return false; else if (minuta > a.minuta) return true; else return false; }; bool Czas::operator<(Czas a) { if (a> *this) return true; else return false; }; bool Czas::operator==(Czas a) { if (*this>a || *this<a) return false; else return true; }; bool Czas::operator!=(Czas a) { if (*this == a) return false; else return true; }; bool Czas::operator>=(Czas a) { if (*this<a) return false; else return true; }; bool Czas::operator<=(Czas a) { if (*this>a) return false; else return true; }; Czas& Czas::operator++(){ (*this) += 1; return *this; }; Czas Czas::operator++(int){ Czas wyn(*this); ++(*this); return wyn; }; Czas& Czas::operator--(){ (*this) -= 1; return *this; }; Czas Czas::operator--(int){ Czas wyn(*this); --(*this); return wyn; }; ostream& operator<< (ostream &wyjscie, const Czas& c) { wyjscie << c.ToString(); return wyjscie; }; string Czas::ToString() const { string a = "Czas["; a += (miesiac < 10 ? "0" : "") + to_string(miesiac) + "." + (dzien < 10 ? "0" : "") + to_string(dzien); switch (dzienTygodnia) { case 0: a += "-pn-"; break; case 1: a += "-wt-"; break; case 2: a += "-sr-"; break; case 3: a += "-cw-"; break; case 4: a += "-pt-"; break; case 5: a += "-sb-"; break; case 6: a += "-nd-"; break; default: a += "-BLAD-"; break; }; a += (godzina < 10 ? "0" : "") + to_string(godzina) + ":" + (minuta < 10 ? "0" : "") + to_string(minuta) + "]; "; return a; }; void Czas::Skroc() { int pom; if (minuta > 59) { pom = minuta; minuta %= 60; pom = (pom - minuta) / 60; godzina += pom; } if (godzina > 23) { pom = godzina; godzina %= 24; pom = (pom - godzina) / 24; dzien += pom; dzienTygodnia = (dzienTygodnia + pom) % 7; } if (dzien > 29) { pom = dzien; dzien %= 30; pom = (pom - dzien) / 30; miesiac += pom; } }; Czas::Czas(int mies = 0, int dz = 0, int godz = 0, int min = 0) { if (mies < 0 || dz < 0 || godz < 0 || min < 0) { cout << "BLAD: Czas::Zly parametr konstruktora!"; exit(13); } miesiac = mies; dzien = dz; godzina = godz; minuta = min; dzienTygodnia = ((miesiac * 30) + dzien) % 7; Skroc(); }; // --- Implementacja Bilet --- void Bilet::DodajPrzesiadke(int linId, int przystId, bool czyNap) { if (trasa == nullptr) trasa = new ElementBiletu(linId, przystId, czyNap, nullptr); else { ElementBiletu* p = trasa; while (p->nast != nullptr) p = p->nast; // ok jestesmy w ostatnim elemencie p->nast = new ElementBiletu(linId, przystId, czyNap, nullptr); } aktualny = trasa; }; ElementBiletu* Bilet::DajKoniec() { if (trasa == nullptr) return nullptr; else { ElementBiletu* p = trasa; while (p->nast != nullptr) p = p->nast; // ok jestesmy w ostatnim elemencie return p; } }; void Bilet::Uprosc() { if (trasa != nullptr) { ElementBiletu* p = trasa; while (p->nast != nullptr) { if (p->liniaId == p->nast->liniaId && p->czyNaprzod == p->nast->czyNaprzod) { ElementBiletu* temp = p->nast; p->nast = p->nast->nast; delete temp; } else p = p->nast; } } }; void Bilet::Wypisz() { cout << "Bilet("; if (trasa == nullptr) cout << "pusty) "; else { ElementBiletu* p = trasa; while (p->nast != nullptr) { cout << "linId" << to_string(p->liniaId) << ", "; cout << "przystId" << to_string(p->przystanekId); p = p->nast; } // ok jestesmy w ostatnim elemencie cout << "linId" << to_string(p->liniaId) << ", "; cout << "przystId" << to_string(p->przystanekId) << ") "; } }; Bilet::Bilet() { aktualny = trasa = nullptr; } Bilet::Bilet(int lin, int cId, bool czyNap) { aktualny = trasa = nullptr; DodajPrzesiadke(lin, cId, czyNap); }; Bilet::~Bilet() { ElementBiletu* p = trasa; if (p != nullptr) { while (p->nast != nullptr){ ElementBiletu* temp = p->nast; delete p; p = temp; } delete p; } }; // --- Implementacja Statystyki --- Statystyki::Statystyki() { for (int i=0; i<7; i++) { liczbaPrzejazdow[i] = 0; czasCzekania[i] = 0; liczbaCzekania[i] = 0; osoboSpektakle[i] = 0; miejscoSpektakle[i] = 0; liczbaZakupow[i] = 0; } } string Statystyki::ToString() const { string stat = "LACZNE:\n"; int a = 0; for (int i=0; i<7; i++) a += liczbaPrzejazdow[i]; stat += "Laczna liczba przejazdow = " + to_string(a) + "\n"; double b = 0; double c = 0; for (int i=0; i<7; i++) { b += czasCzekania[i]; c += liczbaCzekania[i]; } stat += "Sredni czas czekania na przystanku = " + (c != 0? to_string(b/c) : "?") + "min\n"; double d = 0; double e = 0; for (int i=0; i<7; i++) { d += osoboSpektakle[i]; e += miejscoSpektakle[i]; } stat += "Sredni procent wypelnienia teatru = " + (e != 0? to_string(d/e * 100) : "?") + "%\n"; double f = 0; for (int i=0; i<5; i++) f += liczbaZakupow[i]; stat += "Srednia liczba zakupow w tygodniu roboczym = " + to_string(f/5) + "\n"; for (int i=0; i<7; i++) { stat += "DZIEN TYGODNIA " + to_string(i+1) + "\n"; stat += "Laczna liczba przejazdow = " + to_string(liczbaPrzejazdow[i]) + "\n"; stat += "Laczny czas czekania na przystankach = " + to_string(czasCzekania[i]) + "min\n"; stat += "Liczba osobo-spektakli = " + to_string(osoboSpektakle[i]) + "\n"; stat += "Liczba zakupow = " + to_string(liczbaZakupow[i]) + "\n"; } return stat; } // --- Implementacja Obiekt --- void Obiekt::KasujBilet() { delete bilet; bilet = nullptr; } string Obiekt::ToString() const { string a = "Obiekt[typ=" + to_string(typ) + ", id=" + to_string(id); if (przystanekId != -1) a += ", polozenie=" + przystanki[przystanekId].DajPolozenie(); return a += "]; "; }; string Obiekt::ToStringSimple() const { string a = "Obiekt[typ=" + to_string(typ) + ", id=" + to_string(id); if (przystanekId != -1) a += ", polozenie=" + przystanki[przystanekId].DajPolozenie(); return a += "]; "; }; Obiekt::Obiekt() : typ("niezdefiniowano"), id(-1), przystanekId(-1), bilet(nullptr) { Czas a; zajetyDo = a; }; Obiekt::Obiekt(string t, int d, int przystId) : typ(t), id(d), bilet(nullptr), przystanekId(przystId) { Czas a; zajetyDo = a; }; ostream& operator<< (ostream &wyjscie, const Obiekt& o) { wyjscie << o.ToString(); return wyjscie; }; // --- Implementacja Przystanek --- bool Przystanek::Reaguj(string czynnosc) { if (czynnosc == "planuje dzien") PlanujDzien(); else if (czynnosc == "konczy dzialanie") KonczDzialanie(); else cout << "BLAD: Przystanek.Reaguj::Podano zla nazwe czynnosci! " << czynnosc << endl; }; void Przystanek::PlanujDzien() { Czas b(0, 0, 23, 0); kol.Wstaw(new Zdarzenie(kol.KtoraGodzina()+b, *this, "konczy dzialanie")); kol.Wstaw(new Zdarzenie(kol.KtoraGodzina().Jutro(), *this, "planuje dzien")); }; void Przystanek::KonczDzialanie() { for (int i=0; i<kolejka.size(); i++) { kol.Wstaw(new Zdarzenie(kol.KtoraGodzina(), *kolejka[i], "zamawia taxi")); Czas a = kol.KtoraGodzina(); statystyki->zmienCzasCzekania(60*a.DajGodzina()+a.DajMinuta()); kolejka[i]->KasujBilet(); } kolejka.clear(); }; string Przystanek::ToString() const { string a = Obiekt::ToString() + "Przystanek[oczekujacy=("; for (int i=0; i<kolejka.size(); i++) a += kolejka[i]->DajTyp() + " " + to_string(kolejka[i]->DajId()) + ", "; return a += ")]; "; }; Przystanek::Przystanek() : Obiekt(), polozenie("niezdefiniowano") {}; Przystanek::Przystanek(int d, string pol) : Obiekt("przystanek", d, d), polozenie(pol) {}; // --- Implementacja Linia --- string Linia::ToString() const { string a = Obiekt::ToString() + "Linia[ilosc pojazdow=" + to_string(liczbaPojazdow) + ", trasa=("; ElementLinii* p = trasa; if (p == nullptr) a += ")]; "; else { while (p->nast != nullptr){ a += przystanki[p->przystanekId].DajPolozenie() + ", " + to_string(p->czas) + ", "; p = p->nast; } a += przystanki[p->przystanekId].DajPolozenie() + ", " + to_string(p->czas) + ")]; "; } return a; }; void Linia::DodajPrzystanek(int przystID, int czas) { if (trasa == nullptr) trasa = new ElementLinii(przystID, czas, nullptr, nullptr); else { ElementLinii* p = trasa; while (p->nast != nullptr) p = p->nast; // dobra jestesmy w ostatnim elemencie p->nast = new ElementLinii(przystID, czas, p, nullptr); } }; ElementLinii* Linia::DajPoczatekTrasy() { return trasa; }; ElementLinii* Linia::DajKoniecTrasy() { if (trasa == nullptr) return trasa; else{ ElementLinii* p = trasa; while (p->nast != nullptr) p = p->nast; return p; } }; Linia::Linia() : Obiekt(), liczbaPojazdow(-1), trasa(nullptr) {}; Linia::Linia(int d, int liczbaPoj) : Obiekt("linia", d, -1), liczbaPojazdow(liczbaPoj), trasa(nullptr) {}; Linia::~Linia(){ ElementLinii* p = trasa; if (p != nullptr) { while (p->nast != nullptr){ ElementLinii* temp = p->nast; delete p; p = temp; } delete p; } }; // --- Implementacja LiniaTramwajowa --- bool LiniaTramwajowa::Reaguj(string czynnosc) { if (czynnosc == "planuje dzien") PlanujDzien(); else if (czynnosc == "wysyla tramwaj z poczatku") WyslijTramwaj(false); else if (czynnosc == "wysyla tramwaj z konca") WyslijTramwaj(true); else cout << "BLAD:LiniaTramwajowa.Reaguj::Podano zla nazwe czynnosci!" << czynnosc << endl; }; void LiniaTramwajowa::PlanujDzien() { odstep = LiczOdstep(); wypuszczone = 0; int i = 0; Czas a(0, 0, 6, 0); a += kol.KtoraGodzina(); Czas b(0, 0, 23, 0); b += kol.KtoraGodzina(); if (kol.DzienTygodnia()<5){ while (i < liczbaPojazdow && a <= b) { kol.Wstaw(new Zdarzenie(a, *this, "wysyla tramwaj z poczatku")); i++; if (i < liczbaPojazdow){ kol.Wstaw(new Zdarzenie(a, *this, "wysyla tramwaj z konca")); i++; a += floor(odstep); } } } else { int ilosc = floor(liczbaPojazdow*(100-procentZmniejszenia)/100); int ods = floor(odstep*100/(100-procentZmniejszenia)); while (i < ilosc && a <= b) { kol.Wstaw(new Zdarzenie(a, *this, "wysyla tramwaj z poczatku")); i++; if (i < ilosc) { kol.Wstaw(new Zdarzenie(a, *this, "wysyla tramwaj z konca")); i++; a += ods; } } } kol.Wstaw(new Zdarzenie(kol.KtoraGodzina().Jutro(), *this, "planuje dzien")); }; void LiniaTramwajowa::WyslijTramwaj(bool odwrotnie) { ElementLinii* start = (odwrotnie == true? DajKoniecTrasy() : DajPoczatekTrasy()); tramwaje[wypuszczone].UstawPrzystanekId(start->przystanekId); tramwaje[wypuszczone].UstawPolozenieTrasa(start); if (odwrotnie == false) kol.Wstaw(new Zdarzenie(kol.KtoraGodzina(), tramwaje[wypuszczone], "zatrzymuje sie (kierunek naprzod)")); else kol.Wstaw(new Zdarzenie(kol.KtoraGodzina(), tramwaje[wypuszczone], "zatrzymuje sie (kierunek wstecz)")); wypuszczone++; }; double LiniaTramwajowa::LiczOdstep(){ ElementLinii* p = trasa; double o = 0; if (p != nullptr) { while (p->nast != nullptr){ o += p->czas; p = p->nast; } o += p->czas; } o *= 2; o /= liczbaPojazdow; o = floor(o); return o; }; string LiniaTramwajowa::ToString() const { return Linia::ToString() + "LiniaTramwajowa[...]; "; }; LiniaTramwajowa::LiniaTramwajowa() : Linia(), odstep(-1), wypuszczone(0), tramwaje(nullptr) {}; LiniaTramwajowa::LiniaTramwajowa(int d, int liczbaPoj) : Linia(d, liczbaPoj), odstep(-1), wypuszczone(0) { tramwaje = new Tramwaj[liczbaPoj]; for (int i=0; i<liczbaPoj; i++) { // Tramwaj* p = new Tramwaj(i, id); // tramwaje[i] = *p; tramwaje[i] = Tramwaj(i, id); cout << tramwaje[i] << endl; } }; // LiniaTramwajowa::~LiniaTramwajowa() { // delete[] tramwaje; // } // --- Impl. Pojazd --- string Pojazd::ToString() const { return Obiekt::ToString() + "Pojazd[liniaId=" + to_string(liniaId) + "]; "; }; Pojazd::Pojazd() : Obiekt(), liniaId(-1), polozenieTrasa(nullptr) {}; Pojazd::Pojazd(string t, int d, int lin) : Obiekt(t, d, -1), liniaId(lin), polozenieTrasa(nullptr) {}; // --- Implementacja Tramwaj --- bool Tramwaj::Reaguj(string czynnosc) { if (czynnosc == "zatrzymuje sie (kierunek naprzod)") RuszajNaprzod(); else if (czynnosc == "zatrzymuje sie (kierunek wstecz)") RuszajWstecz(); else if (czynnosc == "konczy kursowanie") KonczKursowanie(); else cout << "BLAD: Tramwaj.Reaguj::Podano zla nazwe czynnosci!" << czynnosc << endl; }; void Tramwaj::RuszajNaprzod() { czyNaprzod = true; AktualizujPasazerow(); Wysiadac(); Wsiadac(); Czas b(0, 0, 23, 0); b += kol.KtoraGodzina().Dzisiaj(); int c = polozenieTrasa->czas; if (kol.KtoraGodzina()+c >= b) kol.Wstaw(new Zdarzenie(b, *this, "konczy kursowanie")); else if (polozenieTrasa->nast == nullptr) kol.Wstaw(new Zdarzenie(kol.KtoraGodzina()+c, *this, "zatrzymuje sie (kierunek wstecz)")); else { kol.Wstaw(new Zdarzenie(kol.KtoraGodzina()+c, *this, "zatrzymuje sie (kierunek naprzod)")); polozenieTrasa = polozenieTrasa->nast; przystanekId = polozenieTrasa->przystanekId; } }; void Tramwaj::RuszajWstecz() { czyNaprzod = false; AktualizujPasazerow(); Wysiadac(); Wsiadac(); Czas b(0, 0, 23, 0); b += kol.KtoraGodzina().Dzisiaj(); if (polozenieTrasa->poprz == nullptr){ int c = linieTramwajowe[liniaId].CzasPostoju(); if (kol.KtoraGodzina()+c >= b) kol.Wstaw(new Zdarzenie(b, *this, "konczy kursowanie")); else kol.Wstaw(new Zdarzenie(kol.KtoraGodzina()+c, *this, "zatrzymuje sie (kierunek naprzod)")); } else { int c = polozenieTrasa->poprz->czas; if (kol.KtoraGodzina()+c >= b) kol.Wstaw(new Zdarzenie(b, *this, "konczy kursowanie")); else { kol.Wstaw(new Zdarzenie(kol.KtoraGodzina()+c, *this, "zatrzymuje sie (kierunek wstecz)")); polozenieTrasa = polozenieTrasa->poprz; przystanekId = polozenieTrasa->przystanekId; } } }; void Tramwaj::AktualizujPasazerow() { for (int i=0; i<pasazerowie.size(); i++) pasazerowie[i]->UstawPrzystanekId(przystanekId); }; void Tramwaj::Wysiadac() { int a = pasazerowie.size(); for (int i=a-1; i>=0; i--){ if (pasazerowie[i]->DajBilet()->DajAktualny()->przystanekId == przystanekId) { kol.Wstaw(new Zdarzenie(kol.KtoraGodzina(), *pasazerowie[i], "wysiada z tramwaju")); pasazerowie[i]->PrzesunBilet(); przystanki[przystanekId].Ustaw(pasazerowie[i]); if (pasazerowie[i]->DajBilet()->DajAktualny() == nullptr) kol.Wstaw(new Zdarzenie(kol.KtoraGodzina(), *pasazerowie[i], "schodzi z przystanku")); pasazerowie.erase(pasazerowie.begin()+i); } } }; void Tramwaj::Wsiadac() { int a = przystanki[przystanekId].DajDlugosc(); for (int i=a-1; i>=0; i--) { if (przystanki[przystanekId].DajOsoba(i)->DajBilet() != nullptr && przystanki[przystanekId].DajOsoba(i)->DajBilet()->DajAktualny() != nullptr && przystanki[przystanekId].DajOsoba(i)->DajBilet()->DajAktualny()->liniaId == liniaId && przystanki[przystanekId].DajOsoba(i)->DajBilet()->DajAktualny()->czyNaprzod == czyNaprzod && pasazerowie.size()<pojemnosc) { kol.Wstaw(new Zdarzenie(kol.KtoraGodzina(), *przystanki[przystanekId].DajOsoba(i), "wsiada do tramwaju")); pasazerowie.push_back(przystanki[przystanekId].DajOsoba(i)); przystanki[przystanekId].Oddal(i); } } }; void Tramwaj::KonczKursowanie() { for (int i=0; i<pasazerowie.size(); i++) { pasazerowie[i]->KasujBilet(); kol.Wstaw(new Zdarzenie(kol.KtoraGodzina(), *pasazerowie[i], "zamawia taxi")); } pasazerowie.clear(); przystanekId = -1; }; string Tramwaj::ToString() const { string a = Pojazd::ToString() + "Tramwaj[zapelnienie=" + to_string(pasazerowie.size()) + ", pasazerowie=("; for (int i=0; i<pasazerowie.size(); i++) a += to_string(pasazerowie[i]->DajTyp()) + " " + to_string(pasazerowie[i]->DajId()) + ", "; return a+= ")]; "; }; Tramwaj::Tramwaj() : Pojazd(), czyNaprzod(true) {}; Tramwaj::Tramwaj(int i, int lin) : Pojazd("tramwaj", i, lin), czyNaprzod(true) {}; // --- Implementacja Miejsce --- string Miejsce::ToString() const { return Obiekt::ToString() + "Miejsce[nazwa=" + nazwa + "]; "; }; Miejsce::Miejsce() : Obiekt() {}; Miejsce::Miejsce(string t, int i, string naz, int przyst) : Obiekt(t, i, przyst), nazwa(naz){}; // ----------------- Impl. Uniwersytet -------------------- string Uniwersytet::ToString() const { return Miejsce::ToString() + "Uniwersytet[...]; "; } Uniwersytet::Uniwersytet() : Miejsce() {}; Uniwersytet::Uniwersytet(int i, string naz, int przyst) : Miejsce("uniwersytet", i, naz, przyst) {}; // ---------------- Impl. Teatr --------------------------- bool Teatr::Reaguj(string czynnosc){ if (czynnosc == "sprzedaje bilet") SprzedajBilet(); else if (czynnosc == "odgrywa spektakl") OdgrywajSpektakl(); else if (czynnosc == "konczy spektakl") KonczSpektakl(); else cout << "BLAD: Teatr.Reaguj::Podano zla nazwe czynnosci!" << czynnosc << endl; return true; }; void Teatr::SprzedajBilet(){ // bilety na seans wyprzedane lub seans juz sie skonczyl if (zapelnieniePierwszyWolny == pojemnosc || kol.KtoraGodzina() >= pierwszyWolny){ zapelnieniePierwszyWolny = 0; AktualizujPierwszyWolny(); } zapelnieniePierwszyWolny++; if (zapelnieniePierwszyWolny == 1){ // mamy widza, ruszamy z organizacja spektaklu! Czas a(0, 0, 1, rand() % 121); czasSpektaklu = a; kol.Wstaw(new Zdarzenie(pierwszyWolny, *this, "odgrywa spektakl")); kol.Wstaw(new Zdarzenie(pierwszyWolny + czasSpektaklu, *this, "konczy spektakl")); } }; void Teatr::OdgrywajSpektakl() { statystyki->zmienMiejscoSpektakle(pojemnosc); }; void Teatr::KonczSpektakl() {}; void Teatr::AktualizujPierwszyWolny(){ // termin jest niedobry wiec szukamy nastepnego bool dobry = false; Czas a(0, 0, 17, 0); Czas b(0, 0, 19, 0); while (dobry == false || kol.KtoraGodzina() >= pierwszyWolny) { switch (pierwszyWolny.DajDzienTygodnia()){ case 0: pierwszyWolny = pierwszyWolny.Jutro() + b; dobry = czyOtwarty[1]; break; case 1: pierwszyWolny = pierwszyWolny.Jutro() + b; dobry = czyOtwarty[2]; break; case 2: pierwszyWolny = pierwszyWolny.Jutro() + b; dobry = czyOtwarty[3]; break; case 3: pierwszyWolny = pierwszyWolny.Jutro() + b; dobry = czyOtwarty[4]; break; case 4: pierwszyWolny = pierwszyWolny.Jutro() + a; dobry = true; break; case 5: if (pierwszyWolny.DajGodzina() == 17){ pierwszyWolny = pierwszyWolny.Dzisiaj() + b; dobry = true; } else { pierwszyWolny = pierwszyWolny.Jutro() + a; dobry = true; } break; case 6: if (pierwszyWolny.DajGodzina() == 17){ pierwszyWolny = pierwszyWolny.Dzisiaj() + b; dobry = true; } else { pierwszyWolny = pierwszyWolny.Jutro() + b; dobry = czyOtwarty[0]; } break; default: cout << "BLAD: Teatr.AktualizujPierwszyWolny::Zly dzien tygodnia!" << endl; break; } } }; string Teatr::ToString() const { return Miejsce::ToString() + "Teatr[pojemnosc=" + to_string(pojemnosc) + ", pierwszyWolny=" + pierwszyWolny.ToString() + "zapelnieniePierwszyWolny=" + to_string(zapelnieniePierwszyWolny) + "]; "; }; Teatr::Teatr() : Miejsce(), pojemnosc(-1), zapelnieniePierwszyWolny(-1) { for (int i=0; i<5; i++) czyOtwarty[i] = false; Czas a; pierwszyWolny = a; czasSpektaklu = a; }; Teatr::Teatr(int d, string naz, int przyst, int poj) : Miejsce("teatr", d, naz, przyst), pojemnosc(poj), zapelnieniePierwszyWolny(0) { for (int i=0; i<5; i++) czyOtwarty[i] = rand() % 2; Czas a(0, 0, 19, 0); pierwszyWolny = a; if (czyOtwarty[0] == false) AktualizujPierwszyWolny(); Czas b; czasSpektaklu = b; }; // --- Implementacja CentrumHandlowe --- string CentrumHandlowe::ToString() const { return Miejsce::ToString() + "CentrumHandlowe[...]; "; }; CentrumHandlowe::CentrumHandlowe() : Miejsce() {}; CentrumHandlowe::CentrumHandlowe(int d, string naz, int przyst) : Miejsce("centrum handlowe", d, naz, przyst) {}; // --- Implementacja Osoba --- bool Osoba::Reaguj(string czynnosc) { if (czynnosc == "planuje dzien") PlanujDzien(); else if (czynnosc == "ustawia sie na przystanku") UstawNaPrzystanku(); else if (czynnosc == "schodzi z przystanku") ZejdzZPrzystanku(); else if (czynnosc == "wsiada do tramwaju") WsiadzDoTramwaju(); else if (czynnosc == "wysiada z tramwaju") WysiadzZTramwaju(); else if (czynnosc == "wychodzi na zakupy") NaZakupy(); else if (czynnosc == "wychodzi z zakupow") ZZakupow(); else if (czynnosc == "rezerwuje teatr") RezerwujTeatr(); else if (czynnosc == "wychodzi do teatru") DoTeatru(); else if (czynnosc == "wychodzi z teatru") ZTeatru(); else if (czynnosc == "zamawia taxi") ZamowTaxi(); else return false; return true; }; void Osoba::Podroz(int cId) { // szuka biletu pod warunkiem ze da sie dojechac bezposrednio if (cId != przystanekId) { kol.Wstaw(new Zdarzenie(kol.KtoraGodzina(), *this, "ustawia sie na przystanku")); for (int i=0; i < liczbaLiniiTramwajowych; i++) { ElementLinii* p = linieTramwajowe[i].DajPoczatekTrasy(); if (p != nullptr) { while (p != nullptr) { // linie jednoprzystankowe i tak nas nie interesuja if (p->przystanekId == przystanekId) { // dobra, linia przebiega przez nasz przystanek! teraz szukamy celu ElementLinii* nasz = p; while (p != nullptr) { if (p->przystanekId == cId) { bilet = new Bilet(i, cId, true); cout << "A\n"; return; } p = p->nast; } p = nasz; while (p != nullptr) { if (p->przystanekId == cId) { bilet = new Bilet(i, cId, false); cout << "B\n"; return; } p = p->poprz; } p = nasz; } p = p->nast; } } } } }; //void Osoba::Podroz2(int cId) { // nieukonczona wersja szukania trasy do dowolnego punktu // if (cId != przystanekId) { // Bilet bil(); // bool odwiedzony[liczbaPrzystankow]; // for (int i=0; i<liczbaPrzystankow; i++) // odwiedzony[i] = false; // odwiedzony[przystanekId] = true; // *bilet = SzukajBiletu(bil, odwiedzony, cId); // //bilet.Uprosc(); // kol.Wstaw(new Zdarzenie(kol.KtoraGodzina(), *this, "ustawia sie na przystanku")); // } //; //Bilet Osoba::SzukajBiletu(Bilet bil, bool odwiedzony[], int cId) { // if (bil.DajKoniec()->przystanekId == cId) // return bil; // if (cId != przystanekId) { // Bilet bil1 = bil; // Bilet bil2 = bil; // for (int i=0; i<liczbaLiniiTramwajowych; i++) { // ElementLinii* p = linieTramwajowe[i].DajPoczatekTrasy(); // if (p != nullptr) { // while (p->nast != nullptr) { // linie jednoprzystankowe i tak nas nie interesuja // if (p->przystanekId == przystanekId) { // // dobra znalezlismy nasz przystanek na linii! jedziemy dalej // if (p->nast != nullptr && odwiedzony[p->nast->przystanekId] == false) { // int nastepny = p->nast->przystanekId; // bil1.DodajPrzesiadke(i, nastepny, true); // odwiedzony[p->nast->przystanekId] = true; // return SzukajBiletu(bil1, odwiedzony[], cId); // } // if (p->poprz != nullptr && odwiedzony[p->poprz->przystanekId] == false) { // int poprzedni = p->poprz->przystanekId; // bil2.DodajPrzesiadke(i, poprzedni, false); // odwiedzony[poprzedni] = true; // return SzukajBiletu(bil2, odwiedzony[], cId); // } // } // p = p->nast; // } // } // } // } // return Bilet(); //}; void Osoba::UstawNaPrzystanku() { przystanki[przystanekId].Ustaw(this); statystyki->zmienLiczbaCzekania(1); Czas a = kol.KtoraGodzina(); statystyki->zmienCzasCzekania(-60*a.DajGodzina()-a.DajMinuta()); if (bilet == nullptr) cout << "JEST NUL\n\n"; }; void Osoba::ZejdzZPrzystanku() { for (int i=0; i<przystanki[przystanekId].DajDlugosc(); i++) { if (przystanki[przystanekId].DajOsoba(i) == this) przystanki[przystanekId].Oddal(i); } Czas a = kol.KtoraGodzina(); statystyki->zmienCzasCzekania(60*a.DajGodzina()+a.DajMinuta()); KasujBilet(); }; void Osoba::WsiadzDoTramwaju() { statystyki->zmienLiczbaPrzejazdow(1); Czas a = kol.KtoraGodzina(); statystyki->zmienCzasCzekania(60*a.DajGodzina()+a.DajMinuta()); } void Osoba::WysiadzZTramwaju() { Czas a = kol.KtoraGodzina(); statystyki->zmienCzasCzekania(-60*a.DajGodzina()-a.DajMinuta()); } void Osoba::NaZakupy() { // osoba idzie na zakupy Podroz(centraHandlowe[rand() % liczbaCentrowHandlowych].DajPrzystanekId()); statystyki->zmienLiczbaZakupow(1); // oraz planuje co dalej Czas a(0, 0, 1, rand() % 121); a += kol.KtoraGodzina(); kol.Wstaw(new Zdarzenie(a, *this, "wychodzi z zakupow")); zajetyDo = a; }; void Osoba::ZZakupow() { // osoba wraca z zakupow Podroz(mieszkanieId); }; Czas Osoba::LosujCzasNaZakupy() { Czas a(0, 0, 10, rand() % 481); return a; }; void Osoba::RezerwujTeatr(){ int tId = rand() % liczbaTeatrow; teatry[tId].Reaguj("sprzedaje bilet"); Czas a = teatry[tId].DajPierwszyWolny(); kol.Wstaw(new Zdarzenie((a-60 < kol.KtoraGodzina() ? kol.KtoraGodzina() : a-60), *this, "wychodzi do teatru")); biletTeatr = new BiletTeatr(tId, teatry[tId].DajCzasSpektaklu()); }; void Osoba::DoTeatru(){ // osoba idzie do teatru Podroz(teatry[biletTeatr->DajTeatrId()].DajPrzystanekId()); statystyki->zmienOsoboSpektakle(1); Czas a = kol.KtoraGodzina() + 60 + biletTeatr->DajCzasSpektaklu(); kol.Wstaw(new Zdarzenie(a, *this, "wychodzi z teatru")); zajetyDo = a; }; void Osoba::ZTeatru(){ KasujBiletTeatr(); double p = rand() % 100; p /= 100; if (pTeatr > p) kol.Wstaw(new Zdarzenie(kol.KtoraGodzina(), *this, "rezerwuje teatr")); // osoba wraca z teatru Podroz(mieszkanieId); }; void Osoba::KasujBiletTeatr() { delete biletTeatr; biletTeatr = nullptr; } void Osoba::ZamowTaxi() { Czas a = kol.KtoraGodzina(); statystyki->zmienCzasCzekania(60*a.DajGodzina()+a.DajMinuta()); przystanekId = mieszkanieId; }; string Osoba::ToString() const { return Obiekt::ToString() + "Osoba[mieszkanie=" + przystanki[mieszkanieId].DajPolozenie() + "]; "; }; Osoba::Osoba() : Obiekt(), mieszkanieId(-1), pTeatr(-1), biletTeatr(nullptr) {}; Osoba::Osoba(string t, int i, double praw) : Obiekt(t, i, rand() % 3), mieszkanieId(przystanekId), pTeatr(praw), biletTeatr(nullptr) {}; // --- Implementacja Pracujacy --- bool Pracujacy::Reaguj(string czynnosc) { bool a = Osoba::Reaguj(czynnosc); if (a == false){ if (czynnosc == "wychodzi do pracy") DoPracy(); else if (czynnosc == "wyjezdza sluzbowo") WyjazdSluzbowy(); else if (czynnosc == "wychodzi z pracy") ZPracy(); else cout << "BLAD: Pracujacy.Reaguj::Podano zla nazwe czynnosci!" << czynnosc << endl; } return true; }; void Pracujacy::PlanujDzien() { if (kol.DzienTygodnia() < 5) kol.Wstaw(new Zdarzenie(kol.KtoraGodzina() + czasDoPracy, *this, "wychodzi do pracy")); else kol.Wstaw(new Zdarzenie(kol.KtoraGodzina() + LosujCzasNaZakupy(), *this, "wychodzi na zakupy")); kol.Wstaw(new Zdarzenie(kol.KtoraGodzina().Jutro(), *this, "planuje dzien")); if (kol.KtoraGodzina().DajDzien() == 0) kol.Wstaw(new Zdarzenie(kol.KtoraGodzina(), *this, "rezerwuje teatr")); }; void Pracujacy::DoPracy() { // Osoba idzie do pracy: Podroz(pracaId); // Nastepnie planuje: double p = rand() % 100; p /= 100; Czas b(0, 0, 9, 0); b += kol.KtoraGodzina(); if (pWyjazd > p) { Czas a(0, 0, 0, rand() % 541); a += kol.KtoraGodzina(); kol.Wstaw(new Zdarzenie(a, *this, "wyjezdza sluzbowo")); zajetyDo = a; } else zajetyDo = b; kol.Wstaw(new Zdarzenie(b, *this, "wychodzi z pracy")); }; void Pracujacy::WyjazdSluzbowy() { // Osoba jedzie w losowe miejsce i wraca: int celId = rand() % liczbaPrzystankow; Podroz(celId); if (bilet != nullptr) bilet->DodajPrzesiadke(bilet->DajAktualny()->liniaId, pracaId, !(bilet->DajAktualny()->czyNaprzod)); //bilet.DodajOdwrotny(); Czas b(0, 0, 9, 0); zajetyDo = kol.KtoraGodzina().Dzisiaj() + czasDoPracy + b; }; void Pracujacy::ZPracy() { double p = rand() % 100; p /= 100; if (pZakupy > p) { kol.Wstaw(new Zdarzenie(kol.KtoraGodzina(), *this, "wychodzi na zakupy")); } else Podroz(mieszkanieId); }; string Pracujacy::ToString() const { return Osoba::ToString() + "Pracujacy[praca=" + przystanki[pracaId].DajPolozenie() + "]; "; }; Pracujacy::Pracujacy() : Osoba(), pracaId(-1) { Czas a; czasDoPracy = a; }; Pracujacy::Pracujacy(int d) : Osoba("pracujacy", d, pTeatr), pracaId(rand() % liczbaPrzystankow) { Czas a(0, 0, 6, rand() % 241); czasDoPracy = a; }; // --- Implementacja Artysta --- bool Artysta::Reaguj(string czynnosc){ bool a = Osoba::Reaguj(czynnosc); if (a == false){ if (czynnosc == "wychodzi do pracy") DoPracy(); else if (czynnosc == "wychodzi z pracy") ZPracy(); else cout << "BLAD: Artysta.Reaguj::Podano zla nazwe czynnosci!" << czynnosc << endl; } return true; }; Czas Artysta::LosujCzasDoPracy() { Czas b(0, 0, 8, rand() % 241); return b; }; void Artysta::PlanujDzien() { kol.Wstaw(new Zdarzenie(kol.KtoraGodzina() + LosujCzasDoPracy(), *this, "wychodzi do pracy")); kol.Wstaw(new Zdarzenie(kol.KtoraGodzina().Jutro(), *this, "planuje dzien")); if (kol.KtoraGodzina().DajDzien() == 0) kol.Wstaw(new Zdarzenie(kol.KtoraGodzina(), *this, "rezerwuje teatr")); }; void Artysta::DoPracy() { // Osoba idzie do pracy: Podroz(pracaId[kol.DzienTygodnia()]); // Nastepnie planuje: Czas a(0, 0, 5, rand() % 121); a += kol.KtoraGodzina(); kol.Wstaw(new Zdarzenie(a, *this, "wychodzi z pracy")); zajetyDo = a; }; void Artysta::ZPracy() { // Osoba wraca z pracy: double p = rand() % 100; p /= 100; if (kol.KtoraGodzina().DajDzienTygodnia() >= 5 || pZakupy > p) kol.Wstaw(new Zdarzenie(kol.KtoraGodzina(), *this, "wychodzi na zakupy")); else Podroz(mieszkanieId); }; string Artysta::ToString() const { return Osoba::ToString() + "Artysta[praca=(...)]; "; }; Artysta::Artysta() : Osoba() { for (int i = 0; i < 7; i++) pracaId[i] = -1; }; Artysta::Artysta(int d) : Osoba("artysta", d, pTeatr) { int miejscaPracy[] ={rand() % liczbaPrzystankow, rand() % liczbaPrzystankow, rand() % liczbaPrzystankow}; for (int i = 0; i < 7; i++) pracaId[i] = miejscaPracy[rand() % 3]; }; // --- Implementacja Student --- bool Student::Reaguj(string czynnosc) { bool a = Osoba::Reaguj(czynnosc); if (a == false){ if (czynnosc == "wychodzi na uniwersytet") NaUniwersytet(); else if (czynnosc == "wychodzi z uniwersytetu") ZUniwersytetu(); else cout << "BLAD: Student.Reaguj::Podano zla nazwe czynnosci!" << czynnosc << endl; return true; } }; void Student::PlanujDzien() { if (kol.DzienTygodnia() < 5) { if (uniwersytet2Id != -1) { Czas a(0, 0, 0, 1); kol.Wstaw(new Zdarzenie(kol.KtoraGodzina() + czasNaUniwersytet[kol.DzienTygodnia()] + czasZajec[kol.DzienTygodnia()].Srodek() + a, *this, "wychodzi na uniwersytet")); } kol.Wstaw(new Zdarzenie(kol.KtoraGodzina() + czasNaUniwersytet[kol.DzienTygodnia()], *this, "wychodzi na uniwersytet")); } else kol.Wstaw(new Zdarzenie(kol.KtoraGodzina() + LosujCzasNaZakupy(), *this, "wychodzi na zakupy")); kol.Wstaw(new Zdarzenie(kol.KtoraGodzina().Jutro(), *this, "planuje dzien")); if (kol.KtoraGodzina().DajDzien() == 0) kol.Wstaw(new Zdarzenie(kol.KtoraGodzina(), *this, "rezerwuje teatr")); }; void Student::NaUniwersytet() { if (uniwersytet2Id == -1) { // student jedzie na uniwersytet1 Podroz(uniwersytety[uniwersytet1Id].DajPrzystanekId()); // i planuje co dalej Czas a = kol.KtoraGodzina() + czasZajec[kol.DzienTygodnia()]; kol.Wstaw(new Zdarzenie(a, *this, "wychodzi z uniwersytetu")); zajetyDo = a; } else { // student jedzie na uniwersytet2 Podroz(uniwersytety[uniwersytet2Id].DajPrzystanekId()); // i planuje co dalej Czas a = kol.KtoraGodzina() + czasZajec[kol.DzienTygodnia()].Srodek(); kol.Wstaw(new Zdarzenie(a, *this, "wychodzi z uniwersytetu")); zajetyDo = a; } }; void Student::ZUniwersytetu() { double p = rand() % 100; p /= 100; if (pZakupy > p && kol.KtoraGodzina() == kol.KtoraGodzina().Dzisiaj() + czasNaUniwersytet[kol.DzienTygodnia()] + czasZajec[kol.DzienTygodnia()]) { // student jedzie na zakupy kol.Wstaw(new Zdarzenie(kol.KtoraGodzina(), *this, "wychodzi na zakupy")); } else // student wraca do domu Podroz(mieszkanieId); }; string Student::ToString() const { return Osoba::ToString() + "Student[uniwersytet1=" + uniwersytety[uniwersytet1Id].DajNazwa() + ", uniwersytet2=" + (uniwersytet2Id == -1? "brak" : uniwersytety[uniwersytet2Id].DajNazwa()) + "]; "; }; Student::Student() : Osoba(), uniwersytet1Id(-1), uniwersytet2Id(-1) { Czas a; for (int i = 0; i < 5; i++) { czasNaUniwersytet[i] = a; czasZajec[i] = a; } }; Student::Student(int d, bool drugi) : Osoba("student", d, pTeatr) { uniwersytet1Id = rand() % liczbaUniwersytetow; uniwersytet2Id = -1; if (drugi == true && liczbaUniwersytetow > 1) { do // napisac lepsze losowanie? uniwersytet2Id = rand() % liczbaUniwersytetow; while (uniwersytet2Id == uniwersytet1Id); } for (int i = 0; i < 5; i++) { Czas a(0, 0, 8, rand() % 241); Czas b(0, 0, 2, rand() % 481); Czas c(0, 0, 20, 0); Czas e; e = (a + b >= c ? c - a : b); czasNaUniwersytet[i] = a; czasZajec[i] = e; } }; // --- Implementacja Uczen --- bool Uczen::Reaguj(string czynnosc) { bool a = Osoba::Reaguj(czynnosc); if (a == false){ if (czynnosc == "wychodzi do szkoly") DoSzkoly(); else if (czynnosc == "wychodzi ze szkoly") ZeSzkoly(); else cout << "BLAD: Uczen.Reaguj::Podano zla nazwe czynnosci!" << czynnosc << endl; return true; } }; void Uczen::PlanujDzien() { if (kol.DzienTygodnia() < 5) { Czas a(0, 0, 8, 0); kol.Wstaw(new Zdarzenie(kol.KtoraGodzina() + a, *this, "wychodzi do szkoly")); } kol.Wstaw(new Zdarzenie(kol.KtoraGodzina().Jutro(), *this, "planuje dzien")); if (kol.KtoraGodzina().DajDzien() == 0) kol.Wstaw(new Zdarzenie(kol.KtoraGodzina(), *this, "rezerwuje teatr")); }; void Uczen::DoSzkoly() { // uczen jedzie na uniwersytet1 Podroz(szkolaId); // i planuje co dalej Czas a = kol.KtoraGodzina() + czasLekcji[kol.DzienTygodnia()]; kol.Wstaw(new Zdarzenie(a, *this, "wychodzi ze szkoly")); zajetyDo = a; }; void Uczen::ZeSzkoly() { // uczen wraca do domu Podroz(mieszkanieId); }; string Uczen::ToString() const { return Osoba::ToString() + "Uczen[szkola=" + przystanki[szkolaId].DajPolozenie() + "]; "; }; void Uczen::UstawPTeatr(double p) { pTeatr = p; }; Uczen::Uczen() : Osoba() { Czas a; for (int i = 0; i < 5; i++) czasLekcji[i] = a; }; Uczen::Uczen(int d) : Osoba("uczen", d, pTeatr) { szkolaId = rand() % liczbaPrzystankow; for (int j = 0; j < 5; j++) { Czas a(0, 0, 4, rand() % 301); czasLekcji[j] = a; } }; // --- Implementacja Zdarzenie --- Zdarzenie::Zdarzenie(Czas cz, Obiekt& kt, string czyn) : czas(cz), kto(kt), czynnosc(czyn), id(idNo) { idNo++; }; void Zdarzenie::Zajdz() const { kto.Reaguj(czynnosc); }; string Zdarzenie::to_stringImpl() const { return "Zdarzenie[this=" + ::to_string(this) + ": id=" + ::to_string(id) + ", czas=" + ::to_string(&czas) + ", kto=" + ::to_string(&kto) + ", kol=" + ::to_string(&kol) + "]"; }; ostream& operator<< (ostream& wyjscie, const Zdarzenie& zdarz) { wyjscie << "Zdarzenie[id=" << zdarz.DajId() << "]; "; return wyjscie; }; //ostream& operator<<(ostream& o, const Zdarzenie& z) { // o << z.to_stringImpl(); // return o; //} // --- Implementacja KolejkaZdarzen --- KolejkaZdarzen::KolejkaZdarzen() : zdarzenia() { Czas a; czas = a; }; void KolejkaZdarzen::Wstaw(const Zdarzenie* z) { assert(czas <= z->DajCzas()); zdarzenia.push(z); }; void KolejkaZdarzen::NiechSieDzieje(Czas koniecSwiata) { while (!zdarzenia.empty() and czas <= koniecSwiata) { const Zdarzenie* z = zdarzenia.top(); czas = z->DajCzas(); if (((czas >= z->DajKto().DajZajetyDo()) && (z->DajKto().DajBilet() == nullptr)) || z->DajCzynnosc() == "ustawia sie na przystanku" || z->DajCzynnosc() == "wsiada do tramwaju" || z->DajCzynnosc() == "wysiada z tramwaju" || z->DajCzynnosc() == "schodzi z przystanku") { cout << czas << *z << z->DajKto().ToStringSimple() << z->DajCzynnosc() << endl; z->Zajdz(); } // cout << *z << endl; // Ta linijka może się przydać przy debugowaniu zdarzenia.pop(); // Dla obiektów (tu są wskaźniki, więc ich to nie dotyczy) woła destruktor elementu usuwanego z kolejki delete z; } // czyszczenie kolejki - żeby nie zostawiać w kolejce śmieci while (!zdarzenia.empty()) { const Zdarzenie* z = zdarzenia.top(); zdarzenia.pop(); delete z; } }; // --- Funkcje pomocnicze --- int SzukajPrzystanku(string naz, Przystanek przyst[], int liczbaPrzyst) { // wyszukuje Id przystanku o podanej nazwie for (int i = 0; i < liczbaPrzyst; i++) { if (przyst[i].DajPolozenie() == naz) return i; }; cout << "BLAD: Funkcja SzukajPrzystanku nie znalazla przystanku o nazwie " << naz << "!"; return -1; }; // ---------------- Program główny ----------------------- int Obiekt::liczbaPrzystankow; int Obiekt::liczbaLiniiTramwajowych; int Obiekt::liczbaUniwersytetow; int Obiekt::liczbaTeatrow; int Obiekt::liczbaCentrowHandlowych; Przystanek* Obiekt::przystanki; LiniaTramwajowa* Obiekt::linieTramwajowe; Uniwersytet* Obiekt::uniwersytety; Teatr* Obiekt::teatry; CentrumHandlowe* Obiekt::centraHandlowe; double LiniaTramwajowa::procentZmniejszenia; double Pracujacy::pWyjazd; double Osoba::pZakupy; double Pracujacy::pTeatr; double Artysta::pTeatr; double Student::pTeatr; double Uczen::pTeatr; int Tramwaj::pojemnosc; Statystyki* Obiekt::statystyki; int main(int, char**) { srand(time(nullptr)); // Inicjuje gen. liczb losowych - przy szukaniu błędów lepiej tę instrukcję wykomentować (za każdym razem będzie wtedy ten sam ciąg liczb losowych) cout << "--- START PROGRAMU ---" << endl; // --- Wczytanie danych --- cout << "--- DANE SYMULACJI ---" << endl; fstream plik; plik.open ("in.txt", ios::in); if (plik.good() == false) { cout << "BLAD: Nie udalo sie otworzyc pliku 'in.txt'!"; } else { int dniSymulacji; plik >> dniSymulacji; cout << "dni symulacji = " << dniSymulacji << endl; Czas koniecSymulacji(0, dniSymulacji, 0, 0); int liczbaPracujacych; plik >> liczbaPracujacych; Pracujacy pracujacy[liczbaPracujacych]; int liczbaStudentow; plik >> liczbaStudentow; Student student[liczbaStudentow]; int liczbaArtystow; plik >> liczbaArtystow; Artysta artysta[liczbaArtystow]; int liczbaUczniow; plik >> liczbaUczniow; Uczen uczen[liczbaUczniow]; double pracPWyjazd; plik >> pracPWyjazd; cout << "prawdop. wyjazdu sluzbowego dla pracujacych = " << pracPWyjazd << endl; Pracujacy::UstawPWyjazd(pracPWyjazd); double osobaPZakupy; plik >> osobaPZakupy; cout << "prawdop. zakupow po pracy/uczelni dla osoby = " << osobaPZakupy << endl; Osoba::UstawPZakupy(osobaPZakupy); int procentDwukierunkowych; plik >> procentDwukierunkowych; cout << "procent studentow z dwoma miejscami studiow = " << procentDwukierunkowych << endl; int liczbaDwukierunkowych = floor(procentDwukierunkowych/100*liczbaStudentow); int procentZmniejszenia; plik >> procentZmniejszenia; cout << "procent zmniejszenia liczby tramwajow w weekendy = " << procentZmniejszenia << endl; LiniaTramwajowa::UstawProcentZmniejszenia(procentZmniejszenia); double pracPTeatr; plik >> pracPTeatr; cout << "prawdop. pojscia do teatru dla pracujacych = " << pracPTeatr << endl; Pracujacy::UstawPTeatr(pracPTeatr); double studPTeatr; plik >> studPTeatr; cout << "prawdop. pojscia do teatru dla studentow = " << studPTeatr << endl; Student::UstawPTeatr(studPTeatr); double artPTeatr; plik >> artPTeatr; cout << "prawdop. pojscia do teatru dla artystow = " << artPTeatr << endl; Artysta::UstawPTeatr(artPTeatr); double uczPTeatr; plik >> uczPTeatr; cout << "prawdop. pojscia do teatru dla uczniow = " << uczPTeatr << endl; Uczen::UstawPTeatr(uczPTeatr); int pojemnosc; plik >> pojemnosc; cout << "pojemnosc tramwajow = " << pojemnosc << endl; Tramwaj::UstawPojemnosc(45); // --- Stworzenie miejsc --- int liczbaPrzystankow; plik >> liczbaPrzystankow; cout << "liczba przystankow = " << liczbaPrzystankow << endl; Obiekt::UstawLiczbaPrzystankow(liczbaPrzystankow); //Przystanek* przystanki = new Przystanek[liczbaPrzystankow]; Przystanek przystanki[liczbaPrzystankow]; Obiekt::UstawPrzystanki(przystanki); for (int i=0; i<liczbaPrzystankow; i++) { string naz; plik >> naz; przystanki[i] = Przystanek(i, naz); cout << przystanki[i] << endl; } int liczbaLiniiTramwajowych; plik >> liczbaLiniiTramwajowych; cout << "liczba linii tramwajowych = " << liczbaLiniiTramwajowych << endl; Obiekt::UstawLiczbaLiniiTramwajowych(liczbaLiniiTramwajowych); string wiersz; getline(plik, wiersz); // przejscie do nastepnego wiersza //LiniaTramwajowa* linieTramwajowe = new LiniaTramwajowa[liczbaLiniiTramwajowych]; LiniaTramwajowa linieTramwajowe[liczbaLiniiTramwajowych]; Obiekt::UstawLinieTramwajowe(linieTramwajowe); for (int i=0; i<liczbaLiniiTramwajowych; i++) { getline(plik, wiersz); stringstream lineStream(wiersz); int liczbaTramwajow; lineStream >> liczbaTramwajow; linieTramwajowe[i] = LiniaTramwajowa(i, liczbaTramwajow); string naz; int czas; while (lineStream >> naz >> czas) linieTramwajowe[i].DodajPrzystanek(SzukajPrzystanku(naz, przystanki, liczbaPrzystankow), czas); cout << linieTramwajowe[i] << endl; } int liczbaUniwersytetow; plik >> liczbaUniwersytetow; cout << "liczba uniwersytetow = " << liczbaUniwersytetow << endl; Obiekt::UstawLiczbaUniwersytetow(liczbaUniwersytetow); Uniwersytet uniwersytety[liczbaUniwersytetow]; Obiekt::UstawUniwersytety(uniwersytety); for (int i=0; i<liczbaUniwersytetow; i++) { string naz, przyst; plik >> naz >> przyst; uniwersytety[i] = Uniwersytet(i, naz, SzukajPrzystanku(przyst, przystanki, liczbaPrzystankow)); cout << uniwersytety[i] << endl; } int liczbaTeatrow; plik >> liczbaTeatrow; cout << "liczba teatrow = " << liczbaTeatrow << endl; Obiekt::UstawLiczbaTeatrow(liczbaTeatrow); Teatr teatry[liczbaTeatrow]; Obiekt::UstawTeatry(teatry); for (int i=0; i<liczbaTeatrow; i++) { string naz, przyst; int poj; plik >> naz >> przyst >> poj; teatry[i] = Teatr(i, naz, SzukajPrzystanku(przyst, przystanki, liczbaPrzystankow), poj); cout << teatry[i] << endl; } int liczbaCentrowHandlowych; plik >> liczbaCentrowHandlowych; cout << "liczba centrow handlowych = " << liczbaCentrowHandlowych << endl; Obiekt::UstawLiczbaCentrowHandlowych(liczbaCentrowHandlowych); CentrumHandlowe centraHandlowe[liczbaCentrowHandlowych]; Obiekt::UstawCentraHandlowe(centraHandlowe); for (int i=0; i<liczbaCentrowHandlowych; i++) { string naz, przyst; plik >> naz >> przyst; centraHandlowe[i] = CentrumHandlowe(i, naz, SzukajPrzystanku(przyst, przystanki, liczbaPrzystankow)); cout << centraHandlowe[i] << endl; } // ----------------- Stworzenie osob --------------- cout << "liczba pracujacych = " << liczbaPracujacych << endl; for (int i = 0; i < liczbaPracujacych; i++){ pracujacy[i] = Pracujacy(i); cout << pracujacy[i] << endl; } cout << "liczba artystow = " << liczbaArtystow << endl; for (int i = 0; i < liczbaArtystow; i++){ artysta[i] = Artysta(i); cout << artysta[i] << endl; } cout << "liczba studentow = " << liczbaStudentow << endl; for(int i = 0; i < liczbaDwukierunkowych; i++){ student[i] = Student(i, true); cout << student[i] << endl; } for(int i = liczbaDwukierunkowych; i < liczbaStudentow; i++){ student[i] = Student(i, false); cout << student[i] << endl; } cout << "liczba uczniow = " << liczbaUczniow << endl; for (int i = 0; i < liczbaUczniow; i++){ uczen[i] = Uczen(i); cout << uczen[i] << endl; } Statystyki stat; Obiekt::UstawStatystyki(&stat); plik.close(); // ---------- Inicjalizacja zdarzen ------------ for (int i = 0; i < liczbaPrzystankow; i++) kol.Wstaw(new Zdarzenie(kol.KtoraGodzina(), przystanki[i], "planuje dzien")); for (int i = 0; i < liczbaLiniiTramwajowych; i++) kol.Wstaw(new Zdarzenie(kol.KtoraGodzina(), linieTramwajowe[i], "planuje dzien")); for (int i = 0; i < liczbaPracujacych; i++) kol.Wstaw(new Zdarzenie(kol.KtoraGodzina(), pracujacy[i], "planuje dzien")); for (int i = 0; i < liczbaArtystow; i++) kol.Wstaw(new Zdarzenie(kol.KtoraGodzina(), artysta[i], "planuje dzien")); for (int i = 0; i < liczbaStudentow; i++) kol.Wstaw(new Zdarzenie(kol.KtoraGodzina(), student[i], "planuje dzien")); for (int i = 0; i < liczbaUczniow; i++) kol.Wstaw(new Zdarzenie(kol.KtoraGodzina(), uczen[i], "planuje dzien")); // ---------------- Symulacja ------------------ cout << "--- POCZATEK SYMULACJI ---" << endl; kol.NiechSieDzieje(koniecSymulacji); cout << "--- STATYSTYKI ---" << endl; cout << stat.ToString(); cout << "--- KONIEC PROGRAMU ---" << endl; } } // Dodatkowe zalozenia: // - zawsze istnieje linia tramwajowa, ktora osoba dotrze bezposrednio do celu // (niestety, nie udalo mi sie wprowadzic ogolnej funkcji szukajacej trasy) // - artysci zaczynaja prace o 8-12 i koncza po 5-7 h // - zakupy "wracajac z pracy" tycza sie pracujacych, artystow i studentow // - artysci robia zawsze weekendowe zakupy tuż po pracy // - jesli jest tylko jedna uczelnia, to wszyscy studenci maja jeden uniwersytet // - tramwaje o 23 koncza prace i juz sie nie zatrzymuja // - funkcja szukajaca trasy zwraca nry linii, przystanki wejscia i kier jazdy // - pracujacy nie wyjezdzaja o losowej porze lecz zaczynaja prace o losowej // - osoba wybierajac sie do teatru wychodzi godzine wczesniej // - jesli osoba nie wyjedzie do teatru to nie jest liczona jako osobospektakl
3ecea2e435a2928b651edb174e85ac6c72444cc0
dac5254630fefae851da7c843dcab7f6a6af9703
/Linux/Sources/Application/Status/CVisualProgress.h
846c82f8b6fd25bc73449012d38ff50e8199fca2
[ "Apache-2.0" ]
permissive
gpreviato/Mulberry-Mail
dd4e3618468fff36361bd2aeb0a725593faa0f8d
ce5c56ca7044e5ea290af8d3d2124c1d06f36f3a
refs/heads/master
2021-01-20T03:31:39.515653
2017-09-21T13:09:55
2017-09-21T13:09:55
18,178,314
5
2
null
null
null
null
UTF-8
C++
false
false
1,488
h
CVisualProgress.h
/* Copyright (c) 2007 Cyrus Daboo. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ // Header for CProgressDialog class #ifndef __CProgressDialog__MULBERRY__ #define __CProgressDialog__MULBERRY__ #include "CDialogDirector.h" #include "CProgress.h" #include "cdstring.h" // Classes class CStaticText; class JXTextButton; class CProgressDialog : public CDialogDirector, public CProgress { public: CProgressDialog(JXDirector* supervisor); virtual ~CProgressDialog(); static CProgressDialog* StartDialog(const cdstring& rsrc); static void StopDialog(CProgressDialog* dlog); virtual void SetDescriptor(const cdstring& title); virtual void SetCount(unsigned long count); virtual void SetTotal(unsigned long total); virtual void SetIndeterminate(); protected: // begin JXLayout JXTextButton* mCancelBtn; CStaticText* mTitle; CBarPane* mBarPane; // end JXLayout virtual void OnCreate(); }; #endif
92ac949c4f36114beb5f3e6aba3a35c55728554d
857178cde25020429e3f6d672e5b3d2bd04c6973
/Interest.cpp
47f330c687b0ff87e04058a97984da2d56d0136c
[]
no_license
intelij/bank_oop_cpp
9c6cd226a7ed73a016bf16d37c5a7053a580156c
ec518b2382fc8122b4bc18b007996f6a9052463f
refs/heads/master
2023-06-14T17:40:28.831815
2021-07-10T19:26:13
2021-07-10T19:26:13
384,774,260
0
0
null
null
null
null
UTF-8
C++
false
false
924
cpp
Interest.cpp
#include"Interest.h" Interest::Interest() { } Interest::Interest(string type, float m, date d, time t) { typeOfInterest = type; amount = m; Date = d; Time = t; } void Interest::input() { Date.setDate(); Time.setTime(); cout << "Enter transection amount: "; cin >> amount; do { cout << "Enter type of interest (daily/monthly/annualy): "; cin >> typeOfInterest; } while (typeOfInterest != "daily" && typeOfInterest != "monthly" && typeOfInterest != "annually"); } void Interest::display() { cout << "INT " << Date.getDate() << " " << Time.getTime() << " " << amount << " " << typeOfInterest << endl; } string Interest::checkDate() { return Date.getDate(); } void Interest::saveFile(string filename) { ofstream out(filename.c_str(), ios::app); out << "INT " << Date.getDate() << " " << Time.getTime() << " " << amount << " " << typeOfInterest << endl; } void Interest::loadFile(string filename) { }
a5ec329f2856ad13ea5399d74ab45b44041c4bd5
fdfeb3da025ece547aed387ad9c83b34a28b4662
/Simple/CCore/inc/gadget/PtrLen.h
076e6a059a0a77b38dacf696aed5b4f3ede81920
[ "FTL", "BSL-1.0" ]
permissive
SergeyStrukov/CCore-3-xx
815213a9536e9c0094548ad6db469e62ab2ad3f7
820507e78f8aa35ca05761e00e060c8f64c59af5
refs/heads/master
2021-06-04T05:29:50.384520
2020-07-04T20:20:29
2020-07-04T20:20:29
93,891,835
8
1
null
null
null
null
UTF-8
C++
false
false
7,438
h
PtrLen.h
/* PtrLen.h */ //---------------------------------------------------------------------------------------- // // Project: CCore 3.00 // // Tag: Simple Mini // // License: Boost Software License - Version 1.0 - August 17th, 2003 // // see http://www.boost.org/LICENSE_1_0.txt or the local copy // // Copyright (c) 2015 Sergey Strukov. All rights reserved. // //---------------------------------------------------------------------------------------- #ifndef CCore_inc_gadget_PtrLen_h #define CCore_inc_gadget_PtrLen_h #include <CCore/inc/gadget/Len.h> #include <CCore/inc/gadget/Nothing.h> #include <CCore/inc/gadget/UtilFunc.h> #include <CCore/inc/gadget/Classification.h> namespace CCore { /* functions */ template <class T,class S> void RangeCopy(T *restrict dst,const S *restrict src,ulen count) { for(; count ;count--) *(dst++)=*(src++); } template <class T> void RangeSet(T *restrict dst,T src,ulen count) { for(; count ;count--) *(dst++)=src; } template <class T> void RangeSet_null(T *restrict dst,ulen count) { for(; count ;count--) *(dst++)=T(); } template <class T,class S> ulen RangeMatch(const T *dst,const S *src,ulen count) { for(ulen cnt=count; cnt ;cnt--) if( *(dst++)!=*(src++) ) return count-cnt; return count; } /* classes */ template <class T> struct PtrLen; struct StrLen; /* struct PtrLen<T> */ template <class T> struct PtrLen { T *ptr; ulen len; // constructors PtrLen() noexcept : ptr(0),len(0) {} PtrLen(NothingType) : PtrLen() {} PtrLen(T *ptr_,ulen len_) : ptr(ptr_),len(len_) {} operator PtrLen<const T>() const { return {ptr,len}; } // cursor ulen operator + () const { return len; } bool operator ! () const { return !len; } T & operator * () const { return *ptr; } T * operator -> () const { return ptr; } void operator ++ () { ptr++; len--; } void operator -- () { ptr--; len++; } PtrLen<T> operator += (ulen delta) // assume fit(delta) { PtrLen<T> ret(ptr,delta); ptr+=delta; len-=delta; return ret; } PtrLen<T> takeup(ulen delta) { return (*this)+=Min(delta,len); } T & take() { T &ret=*ptr; ptr++; len--; return ret; } PtrLen<T> getFinal() const { return {ptr+len,0}; } // fit bool fit(ulen length) const { return length<=len; } bool fit(ulen off,ulen length) const { return off<=len && length<=(len-off) ; } // parts PtrLen<T> prefix(ulen length) const { return {ptr,length}; } // assume fit(length) PtrLen<T> prefix(PtrLen<T> suffix) const { return {ptr,len-suffix.len}; } PtrLen<T> suffix(ulen length) const { return {ptr+(len-length),length}; } // assume fit(length) PtrLen<T> part(ulen off,ulen length) const { return {ptr+off,length}; } // assume fit(off,length) PtrLen<T> part(ulen off) const { return {ptr+off,len-off}; } // assume fit(off) PtrLen<T> inner(ulen off,ulen endoff) const { return {ptr+off,len-off-endoff}; } // assume fit(off,endoff) PtrLen<T> safe_part(ulen off,ulen length) const { if( off>len ) return Null; return part(off,Min_cast(length,len-off)); } PtrLen<T> safe_part(ulen off) const { if( off>len ) return Null; return part(off); } // index access T & operator [] (ulen index) const { return ptr[index]; } T & at(ulen index) const { GuardIndex(index,len); return ptr[index]; } T & back(ulen index) const // 1 is the last { return ptr[len-index]; } // methods template <class S> void copyTo(S dst[/* len */]) const { RangeCopy<S,T>(dst,ptr,len); } template <class S> void copyFrom(const S src[/* len */]) const { RangeCopy<T,S>(ptr,src,len); } void copy(const T src[/* len */]) const { RangeCopy<T,T>(ptr,src,len); } void set(T src) const { RangeSet<T>(ptr,src,len); } void set_null() const { RangeSet_null<T>(ptr,len); } template <class S> ulen match(const S src[/* len */]) const { return RangeMatch<T,S>(ptr,src,len); } template <class S> bool equal(const S src[/* len */]) const { return match(src)==len; } template <class S> bool equal(PtrLen<S> src) const { return len==src.len && equal(src.ptr) ; } template <class S> bool hasPrefix(PtrLen<S> src) const { return len>=src.len && src.equal(ptr) ; } template <class S> bool hasSuffix(PtrLen<S> src) const { return len>=src.len && src.equal(ptr+(len-src.len)) ; } // begin()/end() support bool operator != (ulen end_len) const { return len!=end_len; } }; /* struct StrLen */ struct StrLen : PtrLen<const char> { // constructors StrLen() noexcept {} StrLen(NothingType) {} StrLen(const char *zstr); StrLen(PtrLen<const char> str) : PtrLen<const char>(str) {} StrLen(PtrLen<char> str) : PtrLen<const char>(str.ptr,str.len) {} StrLen(const char *str,ulen len) : PtrLen<const char>(str,len) {} }; /* StrLen literal */ inline StrLen operator "" _c (const char *str,ulen len) { return StrLen(str,len); } /* Range...() */ template <class T> PtrLen<T> Range(PtrLen<T> a) { return a; } template <class T,ulen Len> PtrLen<T> Range(T (&buf)[Len]) { return {buf,Len}; } template <class T> PtrLen<T> Range(T *ptr,ulen len) { return {ptr,len}; } template <class T> PtrLen<T> Range(T *ptr,T *lim) { return {ptr,Dist(ptr,lim)}; } template <class T> PtrLen<const T> Range_const(PtrLen<T> a) { return a; } template <class T,ulen Len> PtrLen<const T> Range_const(T (&buf)[Len]) { return {buf,Len}; } template <class T> PtrLen<const T> Range_const(T *ptr,ulen len) { return {ptr,len}; } template <class T> PtrLen<const T> Range_const(T *ptr,T *lim) { return {ptr,Dist(ptr,lim)}; } /* Single() */ template <class T> PtrLen<T> Single(T &obj) { return {&obj,1}; } /* container Range...() */ auto Range(RangeAccessType &&obj) { return Range(obj.getPtr(),obj.getLen()); } auto Range_const(const RangeAccessType &obj) { return Range_const(obj.getPtr_const(),obj.getLen()); } /* const IsPtrLen<R> */ template <class R> const bool IsPtrLen = false ; template <class T> const bool IsPtrLen<PtrLen<T> > = true ; /* concept RangeableType<T> */ template <class T> // ref extended concept bool RangeableType = requires(T &obj) { Range(obj); } ; /* concept TypeRangeableType<T,S> */ template <class T,class S> // T ref extended concept bool TypeRangeableType = RangeableType<T> && requires(T &obj) { { Range(obj) } -> PtrLen<S> ; } ; /* concept ConstRangeableType<T> */ template <class T> // ref extended concept bool ConstRangeableType = requires(Meta::ToConst<T> &cobj) { Range_const(cobj); } ; /* concept TypeRangeableType<T,S> */ template <class T,class S> // T ref extended concept bool ConstTypeRangeableType = ConstRangeableType<T> && requires(Meta::ToConst<T> &cobj) { { Range_const(cobj) } -> PtrLen<const S> ; } ; /* begin()/end() */ auto begin(RangeAccessType &&obj) { return Range(obj.getPtr(),obj.getLen()); } ulen end(RangeAccessType &&) { return 0; } template <class T> PtrLen<T> begin(PtrLen<T> a) { return a; } template <class T> ulen end(PtrLen<T>) { return 0; } /* Mutate...() */ template <CharType T> T * MutatePtr(void *ptr) { return static_cast<T *>(ptr); } template <ConstCharType T> T * MutatePtr(const void *ptr) { return static_cast<T *>(ptr); } template <class T,class S> PtrLen<T> Mutate(PtrLen<S> a) { return {MutatePtr<T>(a.ptr),a.len*sizeof (S)}; } } // namespace CCore #endif
aafa6d512db81abede78d6aa912e4dd0a0120c2e
1dda1083e4d03ab4f1e339c515fba5adb38268dd
/cube.cpp
f98e6bd609d24e3b7ed8dea22a92201e04d189a3
[]
no_license
imclab/3D-Tic-Tac-Toe
cef3fab803547a075c7dad8d331bb97943321f9e
90934c32d24cc4ab7fb55e55b3f0babf264c2432
refs/heads/master
2021-01-21T00:17:15.502197
2014-05-17T13:32:53
2014-05-17T13:32:53
null
0
0
null
null
null
null
UTF-8
C++
false
false
9,106
cpp
cube.cpp
/* Copyright (C) 2008 by Wai Khoo AUTHOR: Wai Khoo FILE: cube.cpp CLASS: Cube DETAILS: Visualize the 3D Tic Tac Toe cube. Inherits from QGLWidget, which is OpenGL */ #include "cube.h" /* Constructor Setting up the cube, default rotation angle, and default cube selected. Assigning color: 1st player is green; 2nd player is blue; white for blank. */ Cube::Cube(QWidget *p, QGLWidget *shareWidget) : QGLWidget(p, shareWidget) { xRot = 300; yRot = 360; zRot = 0; currX = 0; currY = 2; currZ = 0; m_maxCube = QColor(Qt::green); m_minCube = QColor(Qt::blue); m_blankCube = QColor(Qt::white); for (int x = 0; x < 3; x++) for (int y = 0; y < 3; y++) for (int z = 0; z < 3; z++) { cubeObj[x][y][z] = 0; markedField[x][y][z] = Blank; } } /* Destructor delete opengl list which contains cube specifications. */ Cube::~Cube() { makeCurrent(); for (int x = 0; x < 3; x++) for (int y = 0; y < 3; y++) for (int z = 0; z < 3; z++) glDeleteLists(cubeObj[x][y][z], 1); } /* Set/selection function; called within this class. set the x axis to dx and upate the cube. */ void Cube::changeXAxis(int dx) { currX += dx; currX = currX > 2 ? 2 : currX; currX = currX < 0 ? 0 : currX; updateCube(); } /* Set/selection function; called within this class. set the y axis to dy and update the cube. */ void Cube::changeYAxis(int dy) { currY += dy; currY = currY > 2 ? 2 : currY; currY = currY < 0 ? 0 : currY; updateCube(); } /* Set/selection function; called within this class. set the z axis to dz and update the cube */ void Cube::changeZAxis(int dz) { currZ += dz; currZ = currZ > 2 ? 2 : currZ; currZ = currZ < 0 ? 0 : currZ; updateCube(); } /* Set/selection function; allow other class to modify the cube selection set the axis to x, y, z and update the cube. */ void Cube::setAxis(int x, int y, int z) { currX = x; currY = y; currZ = z; updateCube(); } /* Only allow to mark blank square. */ bool Cube::markCube(PlayerCube p) { if (markedField[currX][currY][currZ] != Blank) return false; markedField[currX][currY][currZ] = p; updateCube(); return true; } /* reset the cube to default configurations/values. */ void Cube::reset() { xRot = 300; yRot = 360; zRot = 0; currX = 0; currY = 2; currZ = 0; for (int x = 0; x < 3; x++) for (int y = 0; y < 3; y++) for (int z = 0; z < 3; z++) { cubeObj[x][y][z] = 0; markedField[x][y][z] = Blank; } updateCube(); } /* Protected function. initialize opengl. */ void Cube::initializeGL() { glEnable(GL_DEPTH_TEST); glEnable(GL_CULL_FACE); glEnable(GL_TEXTURE_2D); glEnable(GL_LINE_SMOOTH); glEnable(GL_BLEND); updateCube(); } /* Protected function this function is called every times a cube is updated. */ void Cube::paintGL() { QColor m_color(Qt::lightGray); qglClearColor(m_color.lighter(105)); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glLoadIdentity(); glTranslated(0.0, 0.0, -12.0); glRotated(xRot / 16.0, 1.0, 0.0, 0.0); glRotated(yRot / 16.0, 0.0, 1.0, 0.0); glRotated(zRot / 16.0, 0.0, 0.0, 1.0); int indX, indY, indZ; double x, y, z; for (indX = 0, x = -1.0; x <= 1.0; x++, indX++) for (indY = 0, y = -1.0; y <= 1.0; y++, indY++) for (indZ = 0, z = -1.0; z <= 1.0; z++, indZ++) drawCube(cubeObj[indX][indY][indZ], x, y, z); } /* Protected function this function is called whenever the window is resize. */ void Cube::resizeGL(int w, int h) { int side = qMin(w, h); glViewport((w - side)/2, (h - side)/2, side, side); glMatrixMode(GL_PROJECTION); glLoadIdentity(); glFrustum(-1.0, +1.0, -1.0, 1.0, 5.0, 60.0); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); glTranslated(0.0, 0.0, -40.0); } /* A cube is made based on 3 parameters (selected, active, who owns it) If a cube is selected, it will paint a red border. If a cube is active, it will paint white with no transparency. If a cube is owned, it will paint the appropriate color. This function return a "specification" for the cube, which is stored in a 3D array. */ GLuint Cube::makeCube(bool selectCube, bool transparent, PlayerCube p) { QColor m_lineColor, m_cubeColor; static const int coords[6][4][3] = { { { +1, -1, -1 }, { -1, -1, -1 }, { -1, +1, -1 }, { +1, +1, -1 } }, { { +1, +1, -1 }, { -1, +1, -1 }, { -1, +1, +1 }, { +1, +1, +1 } }, { { +1, -1, +1 }, { +1, -1, -1 }, { +1, +1, -1 }, { +1, +1, +1 } }, { { -1, -1, -1 }, { -1, -1, +1 }, { -1, +1, +1 }, { -1, +1, -1 } }, { { +1, -1, +1 }, { -1, -1, +1 }, { -1, -1, -1 }, { +1, -1, -1 } }, { { -1, -1, +1 }, { +1, -1, +1 }, { +1, +1, +1 }, { -1, +1, +1 } } }; int alpha = transparent? 100 : 255; m_maxCube.setAlpha(alpha); m_minCube.setAlpha(alpha); m_blankCube.setAlpha(alpha); switch (p) { case Blank: m_cubeColor = m_blankCube; break; case MaxCube: m_cubeColor = m_maxCube; break; case MinCube: m_cubeColor = m_minCube; break; } GLuint list = glGenLists(1); glNewList(list, GL_COMPILE); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); if (selectCube) { glLineWidth(2.0); m_lineColor = Qt::red; } else { glLineWidth(1.0); m_lineColor = Qt::black; } for (int i = 0; i < 6; i++) { qglColor(m_lineColor); glBegin(GL_LINE_STRIP); for (int j = 0; j < 4; j++) { glTexCoord2d(j == 0 || j == 3, j == 0 || j == 1); glVertex3d(0.2 * coords[i][j][0], 0.2 * coords[i][j][1], 0.2 * coords[i][j][2]); } glEnd(); qglColor(m_cubeColor); glBegin(GL_QUADS); glEdgeFlag(false); for (int j = 0; j < 4; j++) { glTexCoord2d(j == 0 || j == 3, j == 0 || j == 1); glVertex3d(0.195 * coords[i][j][0], 0.195 * coords[i][j][1], 0.195 * coords[i][j][2]); } glEnd(); } glEndList(); return list; } /* Draw all the cubes based on the "specification" list. */ void Cube::drawCube(GLuint cube, GLdouble dx, GLdouble dy, GLdouble dz) { glPushMatrix(); glTranslated(dx, dy, dz); glScaled(1.4, 1.4, 1.4); glCallList(cube); glPopMatrix(); } /* Every times a cube has changed, it will generate a new cube with new parameter to reflect the current state of the game. */ void Cube::updateCube() { for (int x = 0; x < 3; x++) for (int y = 0; y < 3; y++) for (int z = 0; z < 3; z++) { if(z == currZ) { if (x == currX && y == currY) cubeObj[x][y][z] = makeCube(true, false, markedField[x][y][z]); else cubeObj[x][y][z] = makeCube(false, false, markedField[x][y][z]); } else cubeObj[x][y][z] = makeCube(false, true, markedField[x][y][z]); } updateGL(); } /* Set function; called within this class. set the x angle of the cube. */ void Cube::setXRotation(int angle) { normalizeAngle(&angle); if (angle != xRot) { xRot = angle; updateGL(); } } /* Set function; called within this class. set the y angle of the cube. */ void Cube::setYRotation(int angle) { normalizeAngle(&angle); if (angle != yRot) { yRot = angle; updateGL(); } } /* Set function; called within this class. set the z angle of the cube. */ void Cube::setZRotation(int angle) { normalizeAngle(&angle); if (angle != zRot) { zRot = angle; updateGL(); } } /* normalize the angle. setting the rotation speed to 1/16 turn per pixel */ void Cube::normalizeAngle(int *angle) { while (*angle < 0) *angle += 360 * 16; while (*angle > 360 * 16) *angle -= 360 * 16; } /* Protected function record mouse clicked position; needed for rotation. */ void Cube::mousePressEvent(QMouseEvent *e) { lastPos = e->pos(); } /* Protected function calculate the mouse displacement and rotate the cube accordingly. 8 degree/pixel. */ void Cube::mouseMoveEvent(QMouseEvent *e) { int dx = e->x() - lastPos.x(); int dy = e->y() - lastPos.y(); if (e->buttons() & Qt::LeftButton) { setXRotation(xRot + 8 * dy); setYRotation(yRot + 8 * dx); } else if (e->buttons() & Qt::RightButton) { setXRotation(xRot + 8 * dy); setZRotation(zRot - 8 * dx); } lastPos = e->pos(); } /* Protected function using keyboard arrow keys and Pg Up/Pg Dn to select cube. spacebar is to mark the cube with your color. */ void Cube::keyPressEvent(QKeyEvent *e) { // X axis if (e->key() == Qt::Key_Left) changeXAxis(-1); if (e->key() == Qt::Key_Right) changeXAxis(1); // Y axis if (e->key() == Qt::Key_Up) changeYAxis(1); if (e->key() == Qt::Key_Down) changeYAxis(-1); // Z axis if (e->key() == Qt::Key_PageUp) changeZAxis(-1); if (e->key() == Qt::Key_PageDown) changeZAxis(1); // Marking a field if (e->key() == Qt::Key_Space) emit marked(currX*9 + currY*3 + currZ); }
94c03b5b004d80a4b8491722f82306e7e1520beb
36ce92927aad48af03f2d2d38c3979261f47697e
/doc/MSc/msc_students/former/simen_reine/HovedOppgaven/VMC/SolidHarmonics/SolidHarmonics.h
7b605722df432c367b128edbebfda240ace1a90d
[ "CC0-1.0" ]
permissive
CompPhysics/ThesisProjects
47fe8f0215525bca42cc76485c75101c9ab10a36
8267e3c9b48ee6f46de391e0ec1cb250ae6476e2
refs/heads/master
2023-08-16T15:14:40.203860
2023-08-09T14:53:48
2023-08-09T14:53:48
42,999,924
9
4
null
null
null
null
UTF-8
C++
false
false
1,566
h
SolidHarmonics.h
#ifndef SolidHarmonics_IS_INCLUDED #define SolidHarmonics_IS_INCLUDED #include "../Domain/Domain.h" #include <iostream> #include <iomanip> #include "../SolidHarmonicsFuncs/SolidHarmonicsFuncs.h" #ifndef sqr_IS_INCLUDED #define sqr_IS_INCLUDED inline double sqr(double x) {return x*x;}; #endif // **************************************************************** // * SOLIDHARMONICS * // **************************************************************** template <class Param> class SolidHarmonics { protected: SolidHarmonicsFuncs<Param>** SHfuncs; public: SolidHarmonics() {} void init(int num, int orbL, int orbM) { SHfuncs = new SolidHarmonicsFuncs<Param>*[num]; for (int i=0; i<num; i++) { if ( (orbL == 0)&(orbM == 0) ) SHfuncs[i] = new SH00<Param>; else if ( (orbL == 1)&(orbM == -1) ) SHfuncs[i] = new SH1m1<Param>; else if ( (orbL == 1)&(orbM == 0) ) SHfuncs[i] = new SH10<Param>; else if ( (orbL == 1)&(orbM == 1) ) SHfuncs[i] = new SH1p1<Param>; else if ( (orbL == 2)&(orbM == -2) ) SHfuncs[i] = new SH2m2<Param>; else if ( (orbL == 2)&(orbM == -1) ) SHfuncs[i] = new SH2m1<Param>; else if ( (orbL == 2)&(orbM == 0) ) SHfuncs[i] = new SH20<Param>; else if ( (orbL == 2)&(orbM == 1) ) SHfuncs[i] = new SH2p1<Param>; else if ( (orbL == 2)&(orbM == 2) ) SHfuncs[i] = new SH2p2<Param>; } } virtual double operator ()(Param& coordinate, int num, int currentNumber) { return SHfuncs[num]->SH(coordinate, currentNumber); } }; #endif
d919459f7ea7026efcd65e165e4b96d0f7e9ae4c
f2631000e14e9f049cf8168baf955438a146d105
/lab9_3.cpp
f98eb2c692252d5625d5c41b220633435c931763
[]
no_license
cpe102/lab9-2562-2-protonnote
79656c695736dd53362b2f1e588f596a63714f5f
55bf473ded590a19dde271fc50af2437af49b260
refs/heads/master
2022-04-01T08:58:37.613008
2020-01-28T09:35:03
2020-01-28T09:35:03
236,682,547
0
0
null
null
null
null
UTF-8
C++
false
false
704
cpp
lab9_3.cpp
#include <iostream> //cout << "Number of data = "; #include <fstream> //cout << "Number of data = "; #include <string> //cout << "Mean = "; #include <cmath> //<< "Standard deviation = "; using namespace std; int main(){ ifstream score; score.open("score.txt"); string textline; double sum = 0, mean,sd,num=0; while(getline(score,textline)){ sum += atof(textline.c_str()); num++; } cout << "Number of data = " << num << endl; mean = 1/num*sum; cout << "Mean = " << mean << endl; sd = pow((pow(sum,2)/num)-pow(mean,2),0.5); cout << "Standard deviation = " << sd << endl; return 0; }
839e8d37a860360224b5cb5f20a1f95d775e636e
965a026fd62a9c6d76e4d0dd683fd04d31bb2f65
/Code_Implementation/src/ToastGame/Timer/Timer.h
482373c90c50c9cec1b47bdea8dbc427f7982cef
[]
no_license
cr1tterp0wer/csc300-microwave
d2db6d69adaa139c407f07eed96c1ab5737bbe05
85d5aff424db37e871325994e787797a037b2830
refs/heads/master
2020-06-19T22:51:02.739568
2019-08-06T02:11:57
2019-08-06T02:11:57
196,903,873
1
0
null
null
null
null
UTF-8
C++
false
false
374
h
Timer.h
#pragma once #include <ctime> using std::time_t; class Timer{ //one hour static const int MAX_TIME = 3600; private: time_t currentTime; time_t prevTime; time_t secs; public: Timer(); Timer( int s ); virtual ~Timer(); void clearSeconds(); int getSeconds(); void setSeconds( int s ); bool decrementSeconds(); };
68ca566ed64b5b089ed88354ad9be3ef3be27247
b754091e462cc03c4d4dceada61be905dd8a456e
/cpu/q1.cpp
bdfd3721f7a15953a32e97a869345cdb24bc3e9d
[ "BSD-3-Clause" ]
permissive
eyalroz/tpch_q1_on_gpu
ae1a266efbb0dd4d8eb4116427739cde368eb564
5a1a0ca79a2a0ac8e4c48cb02e096e23cf6867cb
refs/heads/master
2020-03-24T09:22:20.618594
2018-08-17T16:07:02
2018-08-17T16:07:02
142,627,326
0
0
null
null
null
null
UTF-8
C++
false
false
7,991
cpp
q1.cpp
#include <sstream> #include <vector> #include <time.h> #include "common.hpp" #include "vectorized.hpp" #include "kernels/naive.hpp" #include "kernels/naive_compact.hpp" #include "kernels/hyper.hpp" #include "kernels/hyper_compact.hpp" #include "kernels/x100.hpp" #include "kernels/x100_old.hpp" // Commented-out per Tim's suggests 2018-07-18 // #include "kernels/avx512.hpp" #include <tuple> size_t morsel_size = 10*1024; #define PRINT_RESULTS uint32_t* precomp_filter = nullptr; uint16_t* compr_shipdate = nullptr; moodycamel::BlockingConcurrentQueue<FilterChunk> precomp_filter_queue; void precompute_filter_for_table_chunk( const uint16_t* __restrict__ compressed_ship_date, uint32_t* __restrict__ precomputed_filter, uint32_t num_tuples) { throw std::bad_alloc(); } static const size_t REP_COUNT = 25; static int runIdCounter = 0; template<typename F, typename... Args> void run(const lineitem& li, const std::string& name, Args&&... args) { F fun(li, args...); size_t total_time = 0; double total_millis = 0.0; const size_t n = li.l_extendedprice.cardinality; for (size_t rep=0; rep<REP_COUNT; rep++) { fun.Clear(); timespec ts_start, ts_end; clock_gettime(CLOCK_MONOTONIC, &ts_start); const auto start = get_cycles(); fun(); const auto time = get_cycles() - start; clock_gettime(CLOCK_MONOTONIC, &ts_end); double million = 1000000.0; int64_t millisec = (ts_end.tv_sec - ts_start.tv_sec) * 1000.0 + ((ts_end.tv_nsec - ts_start.tv_nsec) / million); if (rep != 0) { /* Throw cold run away */ total_time += time; total_millis += millisec; } } const double hot_reps = REP_COUNT-1; const double total_tuples = hot_reps * n; printf("%d \t %-40s \t %.1f \t %.1f \t %.1f \t %.1f \t %.1f\n", runIdCounter, name.c_str(), (double)total_time / total_tuples, (double)total_millis / hot_reps, (double)fun.sum_aggr_time / total_tuples, (double)fun.sum_magic_time / total_tuples, (double)(total_time - 0 - fun.sum_aggr_time - fun.sum_magic_time) / total_tuples); runIdCounter++; // fun.Profile(total_tuples); #ifdef PRINT_RESULTS auto print_dec = [] (auto s, auto x) { printf("%s%ld.%ld", s, Decimal64::GetInt(x), Decimal64::GetFrac(x)); }; // printf("# returnflag|linestatus|sum_qty|sum_base_price|sum_disc_price|sum_charge|count_order\n"); auto sum_64 = [] (auto& arr, size_t i, size_t n) { int64_t start = 0; for (size_t k=i; k<i+n; k++) { start += arr[k]; } return start; }; auto sum_128 = [] (auto& hi, auto& lo, size_t i, size_t n) { __int128 start = 0; for (size_t k=i; k<i+n; k++) { auto h = (__int128)hi[k] << 64; auto l = (__int128)lo[k]; start += h | l; } return start; }; for (size_t group=0; group<MAX_GROUPS; group++) { if (fun.aggrs0[group].count > 0) { char rf = group >> 8; char ls = group & std::numeric_limits<unsigned char>::max(); size_t i = group; printf("# %c|%c", rf, ls); print_dec("|", fun.aggrs0[i].sum_quantity); print_dec("|", fun.aggrs0[i].sum_base_price); print_dec("|", fun.aggrs0[i].sum_disc_price); print_dec("|", fun.aggrs0[i].sum_charge); printf("|%ld\n", fun.aggrs0[i].count); } } size_t i=0; for (size_t group=0; group<MAX_GROUPS; group++) { char rf = group >> 8; char ls = group & std::numeric_limits<unsigned char>::max(); int64_t count = sum_64(fun.aggr_avx0_count, i, 8); if (count > 0) { char rf = group >> 8; char ls = group & std::numeric_limits<unsigned char>::max(); printf("# %c|%c", rf, ls); print_dec("|", sum_64(fun.aggr_avx0_sum_quantity, i, 8)); print_dec("|", sum_64(fun.aggr_avx0_sum_base_price, i, 8)); print_dec("|", sum_128(fun.aggr_avx0_sum_disc_price_hi, fun.aggr_avx0_sum_disc_price_lo, i, 8)); print_dec("|", sum_128(fun.aggr_avx0_sum_charge_hi, fun.aggr_avx0_sum_charge_lo, i, 8)); printf("|%ld\n", count); } i+=8; } #endif } using namespace std; inline bool file_exists(const string& name) { struct stat buffer; return (stat (name.c_str(), &buffer) == 0); } inline std::string join_path(std::string a, std::string b) { return a + "/" + b; } std::pair<string,string> split_once(string delimited, char delimiter) { auto pos = delimited.find_first_of(delimiter); return { delimited.substr(0, pos), delimited.substr(pos+1) }; } int main(int argc, const char** argv) { double scale_factor = 1; for(int i = 1; i < argc; i++) { auto arg = string(argv[i]); if (arg.substr(0,2) != "--") { exit(1); } arg = arg.substr(2); // A name=value argument auto p = split_once(arg, '='); auto& arg_name = p.first; auto& arg_value = p.second; if (arg_name == "scale-factor") { scale_factor = std::stod(arg_value); if (scale_factor - 0 < 0.001) { std::invalid_argument("Invalid scale factor"); } } else { exit(1); } } std::string tpch_directory = join_path(EXPAND_THEN_QUOTE(DATA_FILES_DIR) , std::to_string(scale_factor)); std::string input_file = join_path(tpch_directory, "lineitem.tbl"); if (not file_exists(input_file.c_str())) { throw std::runtime_error("Cannot locate table text file " + input_file); // Not generating it ourselves - that's: 1. Not healthy and 2. Not portable; // setup scripts are intended to do that } /* load data */ lineitem li((size_t)(7000000 * std::max(scale_factor, 1.0))); li.FromFile(input_file.c_str()); /* start processing */ printf("ID \t %-40s \t timetuple \t millisec \t aggrtuple \t pshuffletuple \t remainingtuple\n", "Configuration"); // run<KernelWeld>(li, "$\\text{Weld}$"); #if 0 run<KernelOldX100<kMultiplePrims, true, kSinglePrims, false>>(li, "$\\text{X100 Full NSM Standard}$"); run<KernelOldX100<kMultiplePrims, false, kSinglePrims, false>>(li, "$\\text{X100 Full DSM Standard}$"); run<KernelOldX100<k1Step, true, kSinglePrims, false>>(li, "$\\text{X100 Full NSM Standard Fused}$"); run<KernelOldX100<kMagic, true, kSinglePrims, true>>(li, "$\\text{X100 Full NSM In-Reg}$"); run<KernelX100<kMultiplePrims, true>>(li, "$\\text{X100 Compact NSM Standard}$"); run<KernelX100<kMultiplePrims, false>>(li, "$\\text{X100 Compact DSM Standard}$"); run<KernelX100<k1Step, true>>(li, "$\\text{X100 Compact NSM Standard Fused}$"); #endif run<KernelX100<kMagic, true>>(li, "$\\text{X100 Compact NSM In-Reg}$", 0); run<Morsel<KernelX100<kMagic, true>, true>>(li, "$\\text{Full system Morsel X100 Compact NSM In-Reg}$"); run<Morsel<KernelX100<kMagic, true>, false>>(li, "$\\text{One socket Morsel X100 Compact NSM In-Reg}$"); run<Morsel<KernelX100<kMagic, true, kPopulationCount>, true>>(li, "$\\text{AVX512 opt, Full system Morsel X100 Compact NSM In-Reg}$"); run<Morsel<KernelX100<kMagic, true, kPopulationCount>, false>>(li, "$\\text{AVX512 opt, One socket Morsel X100 Compact NSM In-Reg}$"); //run<Morsel<KernelNaiveCompact>>(li, "$\\text{HyPer Compact NoOverflow}$"); //run<KernelNaiveCompact>(li, "$\\text{HyPer Compact NoOverflow}$", 0); #if 0 #ifdef __AVX512F__ run<KernelX100<kMagic, true, kPopulationCount>>(li, "$\\text{X100 Compact NSM In-Reg AVX-512}$"); run<KernelX100<kMagic, true, kCompare>>(li, "$\\text{X100 Compact NSM In-Reg AVX-512 Cmp}$"); #endif run<KernelHyPer<true>>(li, "$\\text{HyPer Full}$"); run<KernelHyPer<false>>(li, "$\\text{HyPer Full OverflowBranch}$"); run<KernelNaive>(li, "$\\text{HyPer Full NoOverflow}$"); run<KernelHyPerCompact<true>>(li, "$\\text{HyPer Compact}$"); run<KernelHyPerCompact<false>>(li, "$\\text{HyPer Compact OverflowBranch}$"); run<KernelNaiveCompact>(li, "$\\text{HyPer Compact NoOverflow}$"); #ifdef __AVX512F__ run<AVX512<false, false, true>>(li, "$\\text{Handwritten AVX-512}$"); run<AVX512<false, false, false>>(li, "$\\text{Handwritten AVX-512 Only64BitAggr}$"); #endif #endif return 0; }
71107863d54ea7d6f1431717cf862046a2816659
b7d57e803e9990d3a782c730d3d3bdfa6f0c83c2
/src/Backend/Window/GLFW/BackendGLFW.cpp
34ed1921ca68b1f42d0a11b8bf50e94288c79787
[ "Zlib" ]
permissive
texus/TGUI
f114ae502418599ddc8f26cd6ef0b29e12a314d3
3103f6e1279ae40b5a2fac2ef9125d56a97b41bd
refs/heads/1.x
2023-09-05T21:26:16.767847
2023-09-03T18:10:03
2023-09-03T18:11:01
4,234,723
739
140
Zlib
2023-09-03T16:40:26
2012-05-05T15:38:22
C++
UTF-8
C++
false
false
11,937
cpp
BackendGLFW.cpp
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // TGUI - Texus' Graphical User Interface // Copyright (C) 2012-2023 Bruno Van de Velde (vdv_b@tgui.eu) // // This software is provided 'as-is', without any express or implied warranty. // In no event will the authors be held liable for any damages arising from the use of this software. // // Permission is granted to anyone to use this software for any purpose, // including commercial applications, and to alter it and redistribute it freely, // subject to the following restrictions: // // 1. The origin of this software must not be misrepresented; // you must not claim that you wrote the original software. // If you use this software in a product, an acknowledgment // in the product documentation would be appreciated but is not required. // // 2. Altered source versions must be plainly marked as such, // and must not be misrepresented as being the original software. // // 3. This notice may not be removed or altered from any source distribution. // ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #include <TGUI/Backend/Window/GLFW/BackendGLFW.hpp> #define GLFW_INCLUDE_NONE // Don't let GLFW include an OpenGL extention loader #include <GLFW/glfw3.h> ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// namespace tgui { ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// BackendGLFW::~BackendGLFW() { for (auto& cursor : m_mouseCursors) { if (cursor.second) glfwDestroyCursor(cursor.second); } } ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// void BackendGLFW::setGuiWindow(BackendGui* gui, GLFWwindow* window) { TGUI_ASSERT(m_guis.find(gui) != m_guis.end(), "BackendGLFW::setGuiWindow called with a gui that wasn't attached"); m_guiResources[gui].window = window; } ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// void BackendGLFW::detatchGui(BackendGui* gui) { // Don't check if it existed, detach is called for every gui while attached is only called for properly initialized guis m_guiResources.erase(gui); Backend::detatchGui(gui); } ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// void BackendGLFW::setMouseCursorStyle(Cursor::Type type, const std::uint8_t* pixels, Vector2u size, Vector2u hotspot) { GLFWimage image; image.width = static_cast<int>(size.x); image.height = static_cast<int>(size.y); image.pixels = static_cast<unsigned char*>(const_cast<std::uint8_t*>(pixels)); // NOLINT(cppcoreguidelines-pro-type-const-cast) GLFWcursor* cursor = glfwCreateCursor(&image, static_cast<int>(hotspot.x), static_cast<int>(hotspot.y)); if (!cursor) return; updateMouseCursorStyle(type, cursor); } ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// void BackendGLFW::resetMouseCursorStyle(Cursor::Type type) { updateMouseCursorStyle(type, createSystemCursor(type)); } ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// void BackendGLFW::setMouseCursor(BackendGui* gui, Cursor::Type type) { TGUI_ASSERT(m_guis.find(gui) != m_guis.end(), "BackendGLFW::setMouseCursor called with a gui that wasn't attached"); if (type == m_guiResources[gui].mouseCursor) return; m_guiResources[gui].mouseCursor = type; // If the gui has no access to the window then we can't change the mouse cursor if (!m_guiResources[gui].window) return; updateShownMouseCursor(m_guiResources[gui].window, type); } ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// bool BackendGLFW::isKeyboardModifierPressed(Event::KeyModifier modifierKey) { /// TODO: If there are multiple windows then we need to do this on the focused window GLFWwindow* window = getAnyWindow(); if (!window) return false; switch (modifierKey) { case Event::KeyModifier::System: return (glfwGetKey(window, GLFW_KEY_LEFT_SUPER) == GLFW_PRESS) || (glfwGetKey(window, GLFW_KEY_RIGHT_SUPER) == GLFW_PRESS); case Event::KeyModifier::Control: return (glfwGetKey(window, GLFW_KEY_LEFT_CONTROL) == GLFW_PRESS) || (glfwGetKey(window, GLFW_KEY_RIGHT_CONTROL) == GLFW_PRESS); case Event::KeyModifier::Shift: return (glfwGetKey(window, GLFW_KEY_LEFT_SHIFT) == GLFW_PRESS) || (glfwGetKey(window, GLFW_KEY_RIGHT_SHIFT) == GLFW_PRESS); case Event::KeyModifier::Alt: return (glfwGetKey(window, GLFW_KEY_LEFT_ALT) == GLFW_PRESS) || (glfwGetKey(window, GLFW_KEY_RIGHT_ALT) == GLFW_PRESS); } TGUI_ASSERT(false, "BackendGLFW::isKeyboardModifierPressed called with an invalid value"); return false; } ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// void BackendGLFW::setClipboard(const String& contents) { #if GLFW_VERSION_MAJOR > 3 || (GLFW_VERSION_MAJOR == 3 && GLFW_VERSION_MINOR >= 3) glfwSetClipboardString(nullptr, std::string(contents).c_str()); #else GLFWwindow* window = getAnyWindow(); if (!window) return; glfwSetClipboardString(window, std::string(contents).c_str()); #endif } ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// String BackendGLFW::getClipboard() const { #if GLFW_VERSION_MAJOR > 3 || (GLFW_VERSION_MAJOR == 3 && GLFW_VERSION_MINOR >= 3) const char* contents = glfwGetClipboardString(nullptr); #else GLFWwindow* window = getAnyWindow(); if (!window) return ""; const char* contents = glfwGetClipboardString(window); #endif if (!contents) return ""; return contents; } ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// GLFWcursor* BackendGLFW::createSystemCursor(Cursor::Type type) { int typeGLFW = GLFW_ARROW_CURSOR; #if GLFW_VERSION_MAJOR > 3 || (GLFW_VERSION_MAJOR == 3 && GLFW_VERSION_MINOR >= 4) switch (type) { case Cursor::Type::Arrow: typeGLFW = GLFW_ARROW_CURSOR; break; case Cursor::Type::Text: typeGLFW = GLFW_IBEAM_CURSOR; break; case Cursor::Type::Hand: typeGLFW = GLFW_POINTING_HAND_CURSOR; break; case Cursor::Type::SizeLeft: case Cursor::Type::SizeRight: case Cursor::Type::SizeHorizontal: typeGLFW = GLFW_RESIZE_EW_CURSOR; break; case Cursor::Type::SizeTop: case Cursor::Type::SizeBottom: case Cursor::Type::SizeVertical: typeGLFW = GLFW_RESIZE_NS_CURSOR; break; case Cursor::Type::SizeBottomRight: case Cursor::Type::SizeTopLeft: typeGLFW = GLFW_RESIZE_NWSE_CURSOR; break; case Cursor::Type::SizeBottomLeft: case Cursor::Type::SizeTopRight: typeGLFW = GLFW_RESIZE_NESW_CURSOR; break; case Cursor::Type::Crosshair: typeGLFW = GLFW_CROSSHAIR_CURSOR; break; case Cursor::Type::Help: TGUI_PRINT_WARNING("BackendGLFW doesn't support Cursor::Type::Help"); break; case Cursor::Type::NotAllowed: typeGLFW = GLFW_NOT_ALLOWED_CURSOR; break; } #else switch (type) { case Cursor::Type::SizeBottomRight: case Cursor::Type::SizeTopLeft: case Cursor::Type::SizeBottomLeft: case Cursor::Type::SizeTopRight: case Cursor::Type::Arrow: typeGLFW = GLFW_ARROW_CURSOR; break; case Cursor::Type::Text: typeGLFW = GLFW_IBEAM_CURSOR; break; case Cursor::Type::Hand: typeGLFW = GLFW_HAND_CURSOR; break; case Cursor::Type::SizeLeft: case Cursor::Type::SizeRight: case Cursor::Type::SizeHorizontal: typeGLFW = GLFW_HRESIZE_CURSOR; break; case Cursor::Type::SizeTop: case Cursor::Type::SizeBottom: case Cursor::Type::SizeVertical: typeGLFW = GLFW_VRESIZE_CURSOR; break; case Cursor::Type::Crosshair: typeGLFW = GLFW_CROSSHAIR_CURSOR; break; case Cursor::Type::Help: // In release mode, Help and NotAllowed branches are identical. NOLINT(bugprone-branch-clone) TGUI_PRINT_WARNING("BackendGLFW doesn't support Cursor::Type::Help"); break; case Cursor::Type::NotAllowed: TGUI_PRINT_WARNING("BackendGLFW doesn't support Cursor::Type::NotAllowed with GLFW < 3.4"); break; } #endif return glfwCreateStandardCursor(typeGLFW); } ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// void BackendGLFW::updateMouseCursorStyle(Cursor::Type type, GLFWcursor* cursor) { if (m_mouseCursors[type]) glfwDestroyCursor(m_mouseCursors[type]); m_mouseCursors[type] = cursor; // Update the cursor on the screen if the cursor was in use for (const auto& pair : m_guiResources) { if (pair.second.mouseCursor == type) { if (pair.second.window) updateShownMouseCursor(pair.second.window, type); } } } ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// void BackendGLFW::updateShownMouseCursor(GLFWwindow* window, Cursor::Type type) { TGUI_ASSERT(window != nullptr, "BackendGLFW::updateShownMouseCursor requires a valid window"); // If the cursor doesn't exist yet then create it now if (!m_mouseCursors[type]) { GLFWcursor* cursor = createSystemCursor(type); if (!cursor) return; m_mouseCursors[type] = cursor; } // Pass the cursor to GLFW to set it while the mouse is on top of the window glfwSetCursor(window, m_mouseCursors[type]); } ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// GLFWwindow* BackendGLFW::getAnyWindow() const { GLFWwindow* window = nullptr; for (const auto& pair : m_guiResources) { if (pair.second.window) { window = pair.second.window; break; } } return window; } ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
305f1156637af1292e3d80c68b4e8979d5a84e1d
8daf7c920144001fdbe1ca37eacd9237a2fc75b7
/TableToUser/TableToUser/TableToUser.cpp
604f37b37776f0321d3d6b8a89f01b3b90b9b8cd
[]
no_license
MuggleBee/VR-CAD
5d3061981b849a740f2675cfea5c01d525c8e87f
09aec6411805f5dbc33193e5e9bd4e3dedbdca3b
refs/heads/master
2020-05-27T22:27:46.298495
2019-04-11T16:47:48
2019-04-11T16:47:48
null
0
0
null
null
null
null
UTF-8
C++
false
false
10,697
cpp
TableToUser.cpp
#include "pch.h" #include <iostream> #include <stdio.h> #include <stdlib.h> #include <vector> #include <thread> #include <winsock2.h> #include <Windows.h> #include <WS2tcpip.h> #include <math.h> #include <tuple> #include <time.h> #include <strstream> #include <Windows.h> #include<tchar.h> #pragma comment(lib,"Ws2_32.lib") //disable POSIX Errors in MSVC++ #ifdef _MSC_VER #pragma warning(disable : 4996) #define _CRT_SECURE_NO_WARNINGS #endif //Allow compilation even if OpenCV is not installed for testing purposes #if __has_include(<opencv2/opencv.hpp>) #include <opencv2/objdetect.hpp> #include <opencv2/highgui.hpp> #include <opencv2/imgproc.hpp> #include <opencv2/opencv.hpp> #else #define NO_CV //#warning "OpenCV Headers not found, please check your VisualStudio Configuration" #endif #define BUFFER_LENGTH 2048 #define DEFAULT_PORT "25565" #define HOST_NAME "127.0.0.1" void serveFunction(); void processing(); volatile bool serveStop = false; volatile unsigned short numClients = 0; volatile bool serveFail = false; #ifdef NO_CV //double[] lookAt = {0.0, 0.0, 0.0}; //double[] eye = {0.0, 0.0, 0.0}; #else cv::Vec3d lookAt(0.0, 0.0, 0.0); cv::Vec3d eye(0.0, 0.0, 0.0); typedef struct Eye { cv::Point center; double radius; } Eye; typedef struct Face { cv::Point center; double radius; cv::Scalar color; std::vector<Eye> eyes; } Face; #endif int main(){ std::thread* serveThread; serveThread = new std::thread(&serveFunction); srand(time(nullptr)); processing(); serveThread->join(); } void processing() { #ifndef NO_CV //TODO: Enable Kinect kia Windows SDK / Kinect.h cv::setUseOptimized(true); std::vector < Face > faceList; //Create the image capture variables cv::VideoCapture capture; cv::Mat frame, image; cv::CascadeClassifier cascade, nestedCascade; double scale = 1.0; //Use OpenCV facial classifiers //TODO: train new classifiers to work better with glasses nestedCascade.load("./resources/haarcascade_eye_tree_eyeglasses.xml"); cascade.load("./resources/haarcascade_frontalface_default.xml"); cv::namedWindow("Configurations"); int bright_slider = 100; int contrast_slider = 10; int denoise_slider = 3; cv::createTrackbar("Brightness", "Configurations", &bright_slider, 200); cv::createTrackbar("Contrast", "Configurations", &contrast_slider, 20); cv::createTrackbar("Denoising", "Configurations", &denoise_slider, 10); capture.open(0); if (capture.isOpened()) { std::cout << "Processing loop starting" << std::endl; for (;;) { //Extract the next frame capture >> frame; if (frame.empty()) { std::cout << "Empty frame; video disconnected" << std::endl; break; } cv::Mat frame1 = frame.clone(); std::vector<cv::Rect> faces, faces2; cv::Mat grey, processFrame, vizFrame; cv::cvtColor(frame1, grey, cv::COLOR_BGR2GRAY); double fx = 1.0 / scale; cv::resize(grey, processFrame, cv::Size(), fx, fx, cv::INTER_LINEAR); for (int y = 0; y < processFrame.rows; y++) { for (int x = 0; x < processFrame.cols; x++) { double alpha = ((contrast_slider - 10) >= 0) ? double(contrast_slider - 9) / 2 : 1.0 / double(cv::abs(11 - contrast_slider)); double beta = bright_slider - 100; uchar newVal = cv::saturate_cast<uchar>(alpha*(processFrame.at<uchar>(y, x)) + beta); processFrame.at<uchar>(y, x) = newVal; } } cv::equalizeHist(processFrame, processFrame); if (denoise_slider != 0) { cv::fastNlMeansDenoising(processFrame, processFrame, denoise_slider); } //Detect the faces cascade.detectMultiScale(processFrame, faces, 1.1, 2, cv::CASCADE_SCALE_IMAGE, cv::Size(30, 30)); //Save old frame if necessary //For face in faces std::vector<Face> newFaces; for (std::size_t i = 0; i < faces.size(); i++) { cv::Rect r = faces[i]; cv::Mat smallImgROI; std::vector<cv::Rect> nestedObjects; cv::Point center; cv::Scalar color(rand() % 255, rand() % 255, rand() % 255); int radius; //Mark faces double aspectRatio = double(r.width) / double(r.height); if (0.75 < aspectRatio && aspectRatio < 1.3) { center.x = cvRound((r.x + r.width*0.5)*scale); center.y = cvRound((r.y + r.height*0.5)*scale); radius = cvRound((r.width + r.height)*0.25*scale); } Face face = { center, radius, color, std::vector<Eye>() }; if (nestedCascade.empty()) continue; smallImgROI = processFrame(r); // Detection of eyes in the input image nestedCascade.detectMultiScale(smallImgROI, nestedObjects, 1.1, 2, cv::CASCADE_SCALE_IMAGE, cv::Size(30, 30)); // Identify Eyes for (size_t j = 0; j < nestedObjects.size(); j++) { cv::Rect nr = nestedObjects[j]; center.x = cvRound((r.x + nr.x + nr.width*0.5)*scale); center.y = cvRound((r.y + nr.y + nr.height*0.5)*scale); radius = cvRound((nr.width + nr.height)*0.25*scale); Eye eye = { center, radius }; face.eyes.push_back(eye); } newFaces.push_back(face); } //Interframe facial tracking - bipartite lists for (std::vector<Face>::iterator iter = faceList.begin(); iter != faceList.end(); iter++) { Face face = *iter; Face nearest; double distance = std::numeric_limits<double>::infinity(); //Remove missing faces if (newFaces.size() < 1) { do { faceList.erase(iter); } while (iter != faceList.end()); break; } //Find match for face for (std::vector<Face>::iterator iter2 = newFaces.begin(); iter2 != newFaces.end(); iter2++) { Face face2 = *iter2; double dist = cv::abs(face2.center.dot(face.center)); if (dist < distance) { distance = dist; nearest = face2; } } nearest.color = face.color; *iter = nearest; //Remove found face for (std::vector<Face>::iterator iter2 = newFaces.begin(); iter2 != newFaces.end(); iter2++) { Face face2 = *iter2; if (face2.center == nearest.center) { newFaces.erase(iter2); break; } } } //Add new faces in for (std::vector<Face>::iterator iter = newFaces.begin(); iter != newFaces.end(); iter++) { faceList.push_back(*iter); } cv::cvtColor(processFrame, vizFrame, cv::COLOR_GRAY2BGR); //Draw circles around faces and eyes for (std::vector<Face>::iterator iter = faceList.begin(); iter != faceList.end(); iter++) { Face face = *iter; cv::circle(vizFrame, face.center, face.radius, face.color, 5); for (std::vector<Eye>::iterator iter2 = face.eyes.begin(); iter2 != face.eyes.end(); iter2++) { Eye eye = *iter2; cv::circle(vizFrame, eye.center, eye.radius, face.color, 3); } } //Set variables for other thread if (faceList.size() > 0) { eye[0] = faceList[0].center.x; eye[1] = faceList[0].center.y; lookAt[0] = eye[0]; lookAt[1] = eye[1]; } imshow("Face Detection", vizFrame); char c = (char)cv::waitKey(1); if (c == VK_ESCAPE) { std::cout << "Escape pressed, exiting" << std::endl; break; } } } serveStop = true; #else std::cout << "No Vision Capability, halting thread. Server still will function\n" << std::endl; #endif } int sendData(int sckt, void *data, int dataLength) { char *msgData = (char *)data; int bytesSent; //call send in a loop until proper bytes of data have been sent to client while (dataLength > 0) { bytesSent = send(sckt, msgData, dataLength, 0); if (bytesSent == -1) { return -1; } msgData += bytesSent; dataLength -= bytesSent; } return 0; } void serveFunction() { //Create server socket WSADATA wsaData; int iResult; SOCKET listener = INVALID_SOCKET; SOCKET client = INVALID_SOCKET; struct addrinfo *result = NULL; struct addrinfo hints; char recvBuffer[BUFFER_LENGTH]; size_t recvbuflen = BUFFER_LENGTH; iResult = WSAStartup(MAKEWORD(2, 2), &wsaData); if (iResult) { serveFail = true; std::cerr << "WSA Startup Failure!" << std::endl; return; } ZeroMemory(&hints, sizeof(hints)); hints.ai_family = AF_INET; hints.ai_socktype = SOCK_STREAM; hints.ai_protocol = IPPROTO_TCP; hints.ai_flags = AI_PASSIVE; iResult = getaddrinfo(HOST_NAME, DEFAULT_PORT, &hints, &result); if (iResult) { serveFail = true; std::cerr << "Addressing failure" << std::endl; WSACleanup(); return; } // Create a SOCKET for connecting to server listener = socket(result->ai_family, result->ai_socktype, result->ai_protocol); if (listener == INVALID_SOCKET) { printf("socket failed with error: %ld\n", WSAGetLastError()); freeaddrinfo(result); WSACleanup(); return; } // Setup the TCP listening socket iResult = bind(listener, result->ai_addr, (int)result->ai_addrlen); if (iResult == SOCKET_ERROR) { printf("bind failed with error: %d\n", WSAGetLastError()); freeaddrinfo(result); closesocket(listener); WSACleanup(); return; } freeaddrinfo(result); iResult = listen(listener, SOMAXCONN); if (iResult == SOCKET_ERROR) { printf("listen failed with error: %d\n", WSAGetLastError()); closesocket(listener); WSACleanup(); return; } client = accept(listener, NULL, NULL); if (client == INVALID_SOCKET) { std::cout << WSAGetLastError() << std::endl; serveFail = true; std::cerr << "Failure to bind to requisite socket" << std::endl; closesocket(listener); WSACleanup(); return; } do { iResult = recv(client, recvBuffer, recvbuflen, 0); std::cout << recvBuffer << std::endl; if (iResult < 0) { serveFail = true; std::cerr << "Failure to recv from socket" << std::endl; closesocket(client); WSACleanup(); return; } //TODO: parse bytes (should indicate request type and are stored in recvBuffer) //if a well formatted API request is recv'd, then send well formatted API response back //if malformed request, respond with the correct HTTP code std::strstream wsss; wsss << "HTTP/1.1 200 OK\r\n" << "Content-Type: text/html; charset=utf-8 \r\n" << "Content-Length: " << sizeof(L"this shit working") << "\r\n" << L"this shit working" << "\r\n\r\n"; //send headers std::string headers = wsss.str(); int res = sendData(client, (void *)headers.c_str(), headers.size()); if (res == -1) { //Error with sending the header } res = sendData(client, recvBuffer, recvbuflen); if (res == -1) { //error sending response data } if (iResult == 0) { //client disconnected } //TODO: send response } while (iResult && !serveStop); //Clean up the socket when done iResult = shutdown(client, SD_SEND); if (iResult == SOCKET_ERROR) { closesocket(client); WSACleanup(); std::cerr << "Ffailure to shutdown socket" << std::endl; serveFail = true; } closesocket(client); WSACleanup(); }
d7072ffbce02da3637e29b38ea176233198e963c
04a1b008ab612f9002db51404f7d48113ddb8624
/src/Data.h
62ac3ff65e230f8621e08e4904d1e7492e2db746
[]
no_license
liadc9/Taxi
66007930a6a35228fead9c831f147aef3817f0c2
39ef70fd47d097a3fbf5271284e8377043dacba9
refs/heads/master
2021-01-11T20:09:31.859312
2017-01-24T15:29:58
2017-01-24T15:29:58
77,460,754
0
0
null
null
null
null
UTF-8
C++
false
false
822
h
Data.h
// // Created by gal on 16/01/17. // #ifndef TAXI_DATA_H #define TAXI_DATA_H #include "TaxiCenter.h" #include "sockets/Socket.h" class Data { private: int numOfDrivers; TaxiCenter* taxiCenter; int port; Socket* socket; int accept; Driver* driver; public: Data(int numOfDrivers,TaxiCenter* taxiCenter,int port, Socket* socket,int accept,Driver* driver); Driver *getDriver(); void setDriver(Driver *driver); ~Data(); int getNumOfDrivers(); void setNumOfDrivers(int numOfDrivers); TaxiCenter *getTaxiCenter(); void setTaxiCenter(TaxiCenter *taxiCenter); int getPort(); void setPort(int port); Socket *getSocket(); void setSocket(Socket *socket); int getAccept(); void setAccept(int accept); }; #endif //TAXI_DATA_H
e1ac1641763d42cc64d13c0b9e0018231817331a
a1df43787df7c31f63e6052f67b4ec41c201e48a
/SRM146_Div2/p1000.cpp
6e407bf7eed54a16507efe83e2faac3028e31726
[]
no_license
BenjaminHolden/TopCoder
c071f03d5da1ba761030d31f71f73130884d9563
f22528acab792a994e9579dc730eeea41ab1045d
refs/heads/master
2021-01-20T03:31:39.277131
2014-09-17T06:49:46
2014-09-17T06:49:46
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,438
cpp
p1000.cpp
#include <vector> #include <iostream> #include <string> #include <climits> using namespace std; class BridgeCrossing{ public: vector<int> myTimes; enum Side{ START, END }; struct State{ vector<int> start_side; //holds indices of people on start side vector<int> end_side; Side mySide = START; int time =0; }; int minTime(vector<int> times){ int N = times.size(); if(N == 0){ return 0; } myTimes = times; State myState; for(int i=0;i<N;i++){ myState.start_side.push_back(i); } return helper(myState); } private: int helper(State s){ if(s.start_side.size() == 0){ return s.time; } int min_time = INT_MAX; if(s.mySide == START){ if(s.start_side.size() == 1){ return s.time + myTimes[s.start_side[0]]; } for(int i=0;i<s.start_side.size();i++){ for(int j=0;j<s.start_side.size();j++){ if(i == j){ continue; //can't move the same person twice at the same time } if(j>i){ continue; //i j, is the same as j i --> so don't do both } int person_i = s.start_side[i]; int person_j = s.start_side[j]; State s_new = s; myRemove(&s_new.start_side, person_i); myRemove(&s_new.start_side, person_j); s_new.end_side.push_back(person_i); s_new.end_side.push_back(person_j); s_new.time += max(myTimes[person_i],myTimes[person_j]); s_new.mySide = END; int time = helper(s_new); if(time<min_time){ min_time = time; } } } }else{ //mySide == END for(int i=0;i<s.end_side.size();i++){ int person_i = s.end_side[i]; State s_new = s; myRemove(&s_new.end_side, person_i); //remove person from end side s_new.start_side.push_back(person_i); //add person to start side s_new.time += myTimes[person_i]; //increase time s_new.mySide = START; //change mySide to START //cout<<"Person: "<<person_i<<", moved from end side --> start side, in t: "<<myTimes[person_i]<<", for a current total time of: "<<s_new.time<<endl; int time = helper(s_new); if(time<min_time){ min_time = time; } } } return min_time; } void myRemove(vector<int>* v, int val){ for(int i=0;i<v->size();i++){ if(val == v->at(i)){ v->erase(v->begin() + i); return; } } cerr << "Failed to find element with value: "<<val<<endl; for(auto v_e : *v){ cerr<<v_e<<", "; } cerr<<endl; exit(-1); } };
1256369f83cf34ae34102a6ad3fc83b6f31ee2dd
f6f0fd9eb64c403a8dad02682a3650ecc7e3f71d
/LAB9.cpp
43586e336245c2a8b75651f84df3952b01bae36d
[]
no_license
MysticJ/LAB9
21b2391ecfd160ea9bfbbc8dc67bca9598d886c6
88a913b50811cdbaf4bc6c090fa4fd0b0b675842
refs/heads/master
2020-03-11T17:47:37.165813
2018-04-22T16:02:31
2018-04-22T16:02:31
130,157,362
0
0
null
null
null
null
UTF-8
C++
false
false
9,674
cpp
LAB9.cpp
//============================================================================ // Name : LAB9.cpp // Author : QIAN Shiyi & JIN Menghe // Version : // Copyright : Your copyright notice // Description : LAB9 //============================================================================ /* Graba-Graba! You are Minion Jerry! You and your Weapons Team buddies Kevin & Carl are playing a game of Graba-Graba. On a 15 x 15 factory floor, Dr. Nefario��s wacky weapons machine spits out weapons on the floor at random! The firepower and weapons it spits out are: 10 FartGun, 9 ShrinkRay, 8, FreezeRay, 7 RocketLauncher, 6 Dynamite, 5 FireExtinguisher, 4 Axe, 3 Scythe, 2 Cleaver, and 1 EggBeater. For each move you make, the probability each weapon will be spit out is inversely proportional to the firepower, meaning an EggBeater will appear every move, but a FartGun only every 10 moves! Also, for each move you make, Kevin & Carl also move. Kevin moves toward the strongest weapon nearby. Carl is not very smart, and simply moves at random. When you move into a square with a weapon, it is added to your collection. Each round lasts 10-20 seconds. Go for the gusto! Grab like an octopus! Make it simple & fun. Use structs Minion and Weapon. Minion contains the name and a Weapon pointer. The struct Weapon contains the weapon name, firepower, and another Weapon pointer. Link weapons from one to another in a chain (Optionally: from highest-tolowest). When the game is over, list the weapons and their total firepower. */ #include <iostream> #include <ctime> #include <cstdlib> #include <stdio.h> #include <cstring> using namespace std; struct Weapon{ char WeaponName[20]; int Power; Weapon* next; }; struct Minion{ char Name[10]; int row; int col; int TotalPower; Weapon* first; }; void InitMap(int map[][15]); void InitWeapons(char weapons[][20]); void Display(int map[][15], const Minion x, const Minion y, const Minion z); bool CheckEmpty(int row, int col, int map[][15], const Minion x, const Minion y, const Minion z); void SpitWeapon(int map[][15], const Minion x, const Minion y, const Minion z); void GetWeapon(char weapons[][20], int map[][15], Minion& x); void OneRound(int map[][15], char weapons[][20], Minion& Kevin, Minion& Carl, Minion& Jerry); void ShowResult(const Minion x, const Minion y, const Minion z); int main() { // Initialize Minion Minion Kevin = {"Kevin", 7, 7, 0, nullptr}, Carl = {"Carl", 7, 7, 0, nullptr}, Jerry = {"Jerry", 7, 7, 0, nullptr}; // Struct an 15x15 int array and initialize it int map[15][15]; InitMap(map); // Struct an array for weapon names char weapons[10][20]; InitWeapons(weapons); srand(time(NULL)); time_t start=time(nullptr); while (time(nullptr)-start<90){ // total play time time_t RoundStart = time(nullptr); OneRound(map, weapons, Kevin, Carl, Jerry); while (time(nullptr)-RoundStart<10){}; // pause if above actions take less than 10 seconds } ShowResult(Kevin, Carl, Jerry); return 0; } void InitMap(int map[][15]){ for (int i=0; i<15; i++){ for (int j=0; j<15; j++){ map[i][j]=0; } } } void InitWeapons(char weapons[][20]){ // 10 FartGun, 9 ShrinkRay, 8, FreezeRay, 7 RocketLauncher, 6 Dynamite, 5 FireExtinguisher, 4 Axe, // 3 Scythe, 2 Cleaver, and 1 EggBeater strcpy(weapons[0], "EggBeater"); strcpy(weapons[1], "Cleaver"); strcpy(weapons[2], "Scythe"); strcpy(weapons[3], "Axe"); strcpy(weapons[4], "FireExtinguisher"); strcpy(weapons[5], "Dynamite"); strcpy(weapons[6], "RocketLauncher"); strcpy(weapons[7], "FreezeRay"); strcpy(weapons[8], "ShrinkRay"); strcpy(weapons[9], "FartGun"); } void Display(int map[][15], const Minion x, const Minion y, const Minion z){ cout<<"Total Power \t"<<x.Name<<": "<<x.TotalPower<<"\t"<<y.Name<<": "<<y.TotalPower<<"\t"<<z.Name<<": "<<z.TotalPower<<endl; for (int i=0; i<15; i++){ for (int j=0; j<15; j++){ if ((i==x.row)&&(j==x.col)&&(i==y.row)&&(j==y.col)&&(i==z.row)&&(j==z.row)){ cout<<"KCJ"; } else if ((i==x.row)&&(j==x.col)&&(i==y.row)&&(j==y.col)&&((i!=z.row)||(j!=z.row))){ cout<<"KC "; } else if ((i==x.row)&&(j==x.col)&&(i==z.row)&&(j==z.col)&&((i!=y.row)||(j!=y.row))){ cout<<"KJ "; } else if ((i==y.row)&&(j==y.col)&&(i==z.row)&&(j==z.col)&&((i!=x.row)||(j!=x.row))){ cout<<"CJ "; } else if ((i==x.row)&&(j==x.col)&&((i!=y.row)||(j!=y.col))&&((i!=z.row)||(j!=z.row))){ cout<<" K "; } else if ((i==y.row)&&(j==y.col)&&((i!=x.row)||(j!=x.col))&&((i!=z.row)||(j!=z.row))){ cout<<" C "; } else if ((i==z.row)&&(j==z.col)&&((i!=y.row)||(j!=y.col))&&((i!=x.row)||(j!=x.row))){ cout<<" J "; } else if (map[i][j]==0){ cout<<" "; } else if (map[i][j]==10){ cout<<"10 "; } else { cout<<" "<<map[i][j]<<" "; } cout<<"|"; } cout<<endl; } } bool CheckEmpty(int row, int col, int map[][15], const Minion x, const Minion y, const Minion z){ if ((map[row][col]==0)&&((row!=x.row)||(col!=x.col))&&((row!=y.row)||(col!=y.col))&&((row!=y.row)||(col!=y.col))){ return true; } else { return false; } } void SpitWeapon(int map[][15], const Minion x, const Minion y, const Minion z){ for (int i=1; i<=10; i++){ int set = rand()%i, row, col; if (set==0){ do { row=rand()%15; col=rand()%15; } while (!CheckEmpty(row, col, map, x, y, z)); map[row][col]=i; } } } void GetWeapon(char weapons[][20], int map[][15], Minion& x){ for (int i=1; i<=10; i++){ if (map[x.row][x.col]==i){ // when Jerry runs into a weapon x.TotalPower +=i; // add to total power of collection Weapon* p = new Weapon; // create a new weapon struct, p is the address of this struct strcpy(p->WeaponName, weapons[i-1]); // fill the struct information p->Power = i; p->next = nullptr; // it is the last object of the linked list // NOTE: at this time, the newly created object is not yet part of the list // if (x.first==nullptr){ // x.first=p; // cout<<"Weapon name is"<<p->WeaponName<<endl; // } // else{ // for (Weapon* pp = x.first; pp; pp=pp->next){ // trace to the last object of the list created // if (pp==nullptr){ // pp = p; // add the new struct to the end of the list // break; // that is, to make the "Weapon* next" to be the address of the new object // } // } // } Weapon* pp=x.first; while(pp != nullptr){ pp=pp->next; } pp=p; // delete p; map[x.row][x.col]=0; break; } } } void MoveCarl(int map[][15], char weapons[][20], Minion& x){ int direction = rand()%4; if (direction==0){ x.col=(x.col-1<0)?0:x.col-1; } else if (direction==1){ x.row=(x.row+1>14)?14:x.row+1; } else if (direction==2){ x.col=(x.col+1>14)?14:x.col+1; } else { x.row=(x.row-1<0)?0:x.row-1; } // get weapon GetWeapon(weapons, map, x); } int Max(int x, int y){ if(x>y) return x; else return y; } void MoveKevin(int map[][15], char weapons[][20], Minion& x){ // ??? int value=Max(15-x.col,15-x.row)-1; // cout<<"value: "<<value<<endl; // cout<<"Kevin position: "<<x.row<<"\t"<<x.col<<endl; int max_bomb=0; int row_p=0,col_p=0; int pos_x,pos_y; for (int i=1;i<=value;i++){ for (col_p=x.col-i;col_p<=x.col+i;col_p++){ for(row_p=x.row-i;row_p<=x.row+i;row_p++){ if(map[row_p][col_p]>max_bomb){ max_bomb=map[row_p][col_p]; pos_x=row_p; pos_y=col_p; //cout<<"max_bomb: "<<max_bomb<<endl; } } } if(max_bomb!=0){ //cout<<"max_bomb: "<<max_bomb<<"\tpos_x: "<<pos_x<<"\tpos_y: "<<pos_y<<endl; break; } } // cout<<"max_bomb: "<<max_bomb<<"\trow_p: "<<row_p<<"\tcol_p: "<<col_p<<endl; if(pos_x>x.row){ x.row=(x.row+1>14)?14:x.row+1; if(pos_y>x.row) x.col=(x.col+1>14)?14:x.col+1; else if(pos_y<x.row) x.col=(x.col-1>14)?14:x.col-1; else x.col=(x.col>14)?14:x.col; } else if(pos_x<x.row){ x.row=(x.row-1>14)?14:x.row-1; if(pos_y>x.col) x.col=(x.col+1>14)?14:x.col+1; else if(pos_y<x.col) x.col=(x.col-1>14)?14:x.col-1; else x.col=(x.col>14)?14:x.col; } else if(pos_x==x.row){ x.row=(x.row>14)?14:x.row; if(pos_y>x.col) x.col=(x.col+1>14)?14:x.col+1; else if(pos_y<x.col) x.col=(x.col-1>14)?14:x.col-1; else x.col=(x.col>14)?14:x.col; } cout<<"Kevin next position: "<<x.row<<"\t"<<x.col<<endl; GetWeapon(weapons, map, x); } void MoveJerry(int map[][15], char weapons[][20], Minion& x){ // move char direction; cout<<x.Name<<", it is your turn to move!"<<endl; do { cout<<"Enter \'a\' to move left, enter \'s\' to move downward, enter \'d\' to move right, enter \'w\' to move upward:"; cin>>direction; } while ((direction!='a')&&(direction!='s')&&(direction!='d')&&(direction!='w')); if (direction=='a'){ x.col=(x.col-1<0)?0:x.col-1; } else if (direction=='s'){ x.row=(x.row+1>14)?14:x.row+1; } else if (direction=='d'){ x.col=(x.col+1>14)?14:x.col+1; } else { x.row=(x.row-1<0)?0:x.row-1; } // get weapon GetWeapon(weapons, map, x); } void OneRound(int map[][15], char weapons[][20], Minion& Kevin, Minion& Carl, Minion& Jerry){ SpitWeapon(map, Kevin, Carl, Jerry); Display(map, Kevin, Carl, Jerry); MoveJerry(map, weapons, Jerry); MoveKevin(map, weapons, Kevin); MoveCarl(map, weapons, Carl); Display(map, Kevin, Carl, Jerry); } void ShowResult(const Minion x, const Minion y, const Minion z){ cout<<"Kevin's Weapon: "; Weapon* px=x.first; while(px->next!=nullptr){ cout<<px->WeaponName<<"\t"; } cout<<endl; cout<<"Carl's Weapon: "; Weapon* py=y.first; while(py->next!=nullptr){ cout<<py->WeaponName<<"\t"; } cout<<endl; cout<<"Jerry's Weapon: "; Weapon* pz=z.first; while(pz->next!=nullptr){ cout<<pz->WeaponName<<"\t"; } cout<<endl; }
64e0bac14cdf15134fe772711b793439e22aa32a
57abfa3c84b001ec0af8688723d47f5846c37b3c
/week08/8.2/Shape.cpp
82e8f7b0b374bd994b498a91683625a004301a3e
[]
no_license
mdnam2410/hcmus-oop
808e3d7ffd750c259b360c2a5170018d3fbd4f00
da3f70f0b090e984c1c4eb1b6638059dfc894806
refs/heads/master
2023-07-03T13:51:12.026369
2021-08-01T10:14:21
2021-08-01T10:14:21
316,934,644
0
0
null
null
null
null
UTF-8
C++
false
false
139
cpp
Shape.cpp
#include "Shape.h" #include <iostream> Shape::~Shape() { } void Shape::info() const { std::cout << "This is class Shape." << '\n'; }
08aabeeea3890cdb49b7cac55821ac5dcf35f6db
7e5ab2551f381d178e306884a24d99abffb3d089
/src/header.h
b8a4fcdd686b9a4015d8f873520641bf39d08ac8
[]
no_license
sworsman31415926/the_http_client
13beab48f50827044740c93ac45d2bfeaf7f5ced
6db8bb1dd2515d7aca40e95a95d29447f3e35647
refs/heads/master
2023-01-31T07:44:09.801141
2020-12-15T10:23:32
2020-12-15T10:23:32
321,630,644
0
0
null
null
null
null
UTF-8
C++
false
false
2,455
h
header.h
#ifndef HEADER_H #define HEADER_H #include <iostream> class Header { public: Header(); void setHost(std::string host); void setPath(std::string path); void addVariable(std::string variable,std::string value); void addCookie(std::string variable,std::string value); void setCookie(std::string cookie) {this->cookie = cookie;} void setReferer(std::string past) {this->referer = past;} void setUserAgent(std::string past) {this->userAgent = past;} void setAccept(std::string accepted) {this->accept = accepted;} void setMethod(std::string method) {this->method = method;} void setAccept_language(std::string lg) {this->accept_language = lg;} void setAccept_encoding(std::string encoding) {this->accept_encoding = encoding;} void setConnexion(std::string past) {this->connexion = host;} void setIfNotMatch(std::string iNm) {this->if_None_Match = iNm;} void removeVariable(){ variable=""; } void removeCookie(){ cookie = ""; } const char* getHostChar(bool removeHttp=true); std::string getHostString(bool removeHttp=true); std::string getPathString() {return path;} std::string getRefererString() {return referer;} std::string getUserAgent() {return userAgent;} std::string getAccept() {return accept;} std::string getCookie() {return cookie;} std::string getMethod() {return method;} std::string getAccept_language() {return accept_language;} std::string getAccept_encoding() {return accept_encoding;} std::string getVariable() {return variable;} std::string getConnexion() {return connexion;} std::string getIfnotMatch() {return if_None_Match;} private: bool cookieExist(std::string variable); std::string connexion; std::string variable; std::string method; std::string cookie; std::string accept_encoding; std::string accept_language; std::string accept; std::string referer; std::string host; std::string userAgent; std::string path; std::string if_None_Match; void removeHttp(std::string* s); void removeHttp(char s[]); }; #endif // HEADER_H
ce2c2c7ccec4f4ffb3607fb411289a20d6ddb4bf
47da6d55a98505d8e880611bdbeb6aee2be95921
/ASC7/F_fei.cpp
1a0f098de618ac28f38e1aaaa313630121a77b71
[]
no_license
Totoro97/Andrew
a0c8c90fc7e6f72ec45f89b175299df9017062b1
0b0ed207dac6437a93eceabb919e49594403aa7f
refs/heads/master
2021-01-10T15:16:30.933521
2016-09-06T00:38:01
2016-09-06T00:38:01
52,795,203
0
0
null
null
null
null
UTF-8
C++
false
false
2,876
cpp
F_fei.cpp
#include <cstdio> #include <cstring> #include <cmath> #include <algorithm> #define S(a) ((a) * (a)) #define eps (1e-10) using namespace std; const double pi = acos(-1); struct point { double x,y; point (double x = 0,double y = 0) : x(x) , y(y) {} void read() { scanf("%lf %lf",&x,&y); } }; point operator + (point a,point b) { return point(a.x + b.x, a.y + b.y); } point operator - (point a,point b) { return point(a.x - b.x, a.y - b.y); } double operator * (point a,point b) { return (a.x * b.x + a.y * b.y); } double operator / (point a,point b) { return (a.x * b.y - a.y * b.x); } point operator * (point a,double b) { return point(a.x * b,a.y * b); } point operator / (point a,double b) { return point(a.x / b,a.y / b); } double length(point a) { return sqrt(a * a); } double cut(point o,double r,point A,point B,point C) { point v = A - B; double dis = fabs(v / (o - B) / length(A - B)); double ans = 0; if (dis > r + eps) return 0; double ang = acos(dis / r); double x = sqrt(S(r) - S(dis)); ans = ang * r * r - dis * x; if (((o - B) / (A - B)) * ((A - B) / (C - B)) > 0) ans = r * r * pi - ans; return ans; } point get_point(double r,point A,point B) { point v = A - B; double sh = -(B * v / length(v)); point M = B + v / length(v) * sh; if (length(M) > r + eps) return point(-100000000,-100000000); double x = sqrt(S(r) - M * M); M = M + v / length(v) * x; return M; } double rec(point o,double r,point A,point B,point C) { double ans = 0; A = A - o; B = B - o; C = C - o; if (length(A) > r + eps) return 0; point p1 = get_point(r,A,C); point p2 = get_point(r,A,B); double ang = acos(p1 * p2 / length(p1) / length(p2)); if (p1 / p2 < 0) ang = -ang; ans += ang * r * r; ans += p2 / A + A / p1; return fabs(ans) / 2.0; } bool judge(point o,double r,point A,point B,point C) { A = A - o; B = B - o; C = C - o; if (length(A) < r - eps) return false; if (length(B) < r - eps) return false; if (length(C) < r - eps) return false; point p; p = get_point(r,A,B); if ((A - p) * (B - p) < eps) return false; p = get_point(r,A,C); if ((A - p) * (C - p) < eps) return false; p = get_point(r,B,C); if ((B - p) * (C - p) < eps) return false; if ((((B - A) / A) * ((C - B) / B) > eps) && (((B - A) / A) * ((A - C) / C) > eps)) return false; return true; } double solve(point o,double r,point A,point B,point C) { if (judge(o,r,A,B,C)) return 0; // return 0; double ans = r * r * pi; ans -= cut(o,r,A,B,C); ans -= cut(o,r,A,C,B); ans -= cut(o,r,B,C,A); ans += rec(o,r,A,B,C); ans += rec(o,r,B,A,C); ans += rec(o,r,C,A,B); return ans; } point o,A,B; double r,ans; int main() { freopen("mammoth.in","r",stdin); freopen("mammoth.out","w",stdout); o.read(); scanf("%lf",&r); A.read(); B.read(); ans += solve(o,r,A,B,point(A.x,B.y)); ans += solve(o,r,A,B,point(B.x,A.y)); printf("%.6lf\n",ans); return 0; }
74bdf312e2663db6ec9a99f06987195a81dcc903
b8af6e912a5809bb426f3efe835955f8cd2c98b5
/StudentManager/shipai.h
338def378e61daeab73ab4e49f21f10c8ca0bbd5
[]
no_license
DICTATOR666/Basic-Student-Manager
801725642a648434dd217b10ce4818fe0df2dea3
221da44a27467cb4c2610985a4f303238bbfe08d
refs/heads/main
2023-05-04T01:31:39.807874
2021-05-24T10:57:13
2021-05-24T10:57:13
370,315,326
0
0
null
null
null
null
UTF-8
C++
false
false
295
h
shipai.h
//石牌校区学生 #pragma once #include<iostream> using namespace std; #include"student.h" class Shipai :public Student { public: Shipai(int id, string name, string major, int cId); //构造函数 void ShowInfo(); //显示个人信息 string GetCampusName(); //获取专业名称 };
16622d77560144e068a595942e87ba6be45d0db2
371d965e314f385c0f1fa99c0a0f45d0f5c74c73
/utils/unit_tests/main.cpp
db45a3dc5c9161fa33d52a67ef56e6ac163b9f56
[ "MIT" ]
permissive
orion-project/orion-qt
d9a833911efa7392d9ac3e3df313bd3f2e458d51
85388975fc7da430c6cb16f5f5ab47ca45321e32
refs/heads/master
2023-08-22T22:28:07.056983
2023-08-09T14:59:24
2023-08-09T14:59:24
69,646,682
8
6
null
null
null
null
UTF-8
C++
false
false
338
cpp
main.cpp
#include "testing/OriTestManager.h" #include "tests/orion_tests.h" #include <QApplication> int main(int argc, char* argv[]) { QApplication app(argc, argv); // It is used as settings storage location. app.setOrganizationName("orion_examples"); return Ori::Testing::run(app, { ADD_SUITE(Ori::Tests), }); }
b9a238fd8786e51099e66fc9ecfbbf85a3151dfd
8aad400620b0a65d0c37e467b94c398e20ff5ce0
/gui.cpp
ebb751ae7ed5c7b1cdf4ba109b6fdac4d499b3a9
[]
no_license
WWU-cptr143-sprouts/sprouts
48e5b6f527618d50ee8cad8bc72c540b7ac92594
eba879ec5ba45bba2996c95e97040b8954adf9fc
refs/heads/master
2020-04-05T18:59:11.333492
2014-06-11T16:21:58
2014-06-11T16:21:58
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,966
cpp
gui.cpp
#include "gui.h" /************** *Description: *Input: *Output: **************/ unordered_map<shared_ptr<GUIContainer>, weak_ptr<GUIRunner>> * GUIRunner::runners = nullptr; void GUIRunner::makeRunners() { if(runners == nullptr) runners = new unordered_map<shared_ptr<GUIContainer>, weak_ptr<GUIRunner>>; } namespace { Image getBackground() { static Image * pbackground = nullptr; if(pbackground == nullptr) pbackground = new Image(); Image & background = *pbackground; if(!background) background = Image(L"background.png"); return background; } } bool GUIRunner::run() { Renderer renderer; Image background = getBackground(); needQuit = false; runRetval = false; bool first = true; while(!needQuit) { Display::initFrame(); if(first) { first = false; gui->reset(); } Display::handleEvents(gui); glClearColor(0, 0, 0, 0); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); TextureDescriptor td = TextureDescriptor(background, 0, (float)Display::width() / background.width(), 0, (float)Display::height() / background.height()); Mesh backgroundmesh = Generate::quadrilateral(td, VectorF(-Display::scaleX(), -Display::scaleY(), -1), Color(1), VectorF(Display::scaleX(), -Display::scaleY(), -1), Color(1), VectorF(Display::scaleX(), Display::scaleY(), -1), Color(1), VectorF(-Display::scaleX(), Display::scaleY(), -1), Color(1)); renderer << backgroundmesh; Display::initOverlay(); renderer << gui->render(); Display::flip(60); vector<function<void()>> fns = std::move(functionList); functionList.clear(); for(function<void()> fn : fns) { fn(); } } return runRetval; }
855e050ffd4ec1bb6cd661d047c10e2ccd9e60f2
dc8e0ffa5a0da3059849440a2cff05a7a9428ad3
/PixelTrigonometry/src/testApp.cpp
772ca8177eefa998274d6dc45fbb0ba91290ff1a
[]
no_license
martoo6/ofStuff
a4922b709f9e8bfdf5fa91e653b2902c84383105
976da1a1a27ae9a022d8cb00356d6b3a37a82da2
refs/heads/master
2020-04-01T23:12:06.297904
2013-09-12T22:19:36
2013-09-12T22:19:36
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,730
cpp
testApp.cpp
#include "testApp.h" //-------------------------------------------------------------- void testApp::setup(){ img.allocate(ofGetWidth(),ofGetHeight(), OF_IMAGE_COLOR); } //-------------------------------------------------------------- void testApp::update(){ } //-------------------------------------------------------------- void testApp::draw(){ for(int i=0;i<ofGetWidth();i++){ a = FMath::cosine(i*0.2)*50; b =FMath::tang(i*0.02); for(int e=0;e<ofGetHeight();e++){ img.setColor(i,e,ofColor::fromHsb(100+(FMath::tang(e*0.02)*a+b*FMath::cosine(e*0.2)*50)*FMath::cosine(ofGetFrameNum()*0.1),255,255)); } } img.update(); img.draw(0,0); } //-------------------------------------------------------------- void testApp::keyPressed(int key){ } //-------------------------------------------------------------- void testApp::keyReleased(int key){ } //-------------------------------------------------------------- void testApp::mouseMoved(int x, int y ){ } //-------------------------------------------------------------- void testApp::mouseDragged(int x, int y, int button){ } //-------------------------------------------------------------- void testApp::mousePressed(int x, int y, int button){ } //-------------------------------------------------------------- void testApp::mouseReleased(int x, int y, int button){ } //-------------------------------------------------------------- void testApp::windowResized(int w, int h){ } //-------------------------------------------------------------- void testApp::gotMessage(ofMessage msg){ } //-------------------------------------------------------------- void testApp::dragEvent(ofDragInfo dragInfo){ }
67348bb18ea31acc7dfc69720591625446d3a92c
7aacdd31e65c81293b156d3b4beed28289152e13
/bluetooth_and_ultrasonic_hc_with_6_motors1.ino
4a60df395b5289e14f78429ceddc137774ee9c6d
[]
no_license
odaifarhat/Project_Electronics_Bluetooth-and-Ultrasonic-HC-with-6-Motors
b66e6fac02906ef850c77dfb906125b90c328901
fad265f2b9400c7507405a3fa706355ad39cb4d1
refs/heads/main
2023-05-31T18:40:10.722151
2021-07-07T18:23:54
2021-07-07T18:23:54
383,873,848
0
0
null
null
null
null
UTF-8
C++
false
false
2,093
ino
bluetooth_and_ultrasonic_hc_with_6_motors1.ino
/* July 7/7/2021 By Eng.Odai Farhat. Project_Electronics_Bluetooth-and-Ultrasonic-HC-with-6-Motors. Define a start for each engine. Programming three coordinated arm movements robot arms. */ #include <Servo.h> // char inputByte; //Bluetooth Servo servo1,servo2,servo3,servo4,servo5,servo6; int trigPin = 9; int echoPin = 8; long distance; long duration; void setup() { /* Serial.begin(9600);//Bluetooth pinMode(13,OUTPUT); */ servo1.attach(7); servo2.attach(6); servo3.attach(5); servo4.attach(4); servo5.attach(3); servo6.attach(2); pinMode(trigPin, OUTPUT); pinMode(echoPin, INPUT);// put your setup code here, to run once: } void loop() { /* while(Serial.available()>0){ //Bluetooth inputByte= Serial.read(); Serial.println(inputByte); if (inputByte=='Z'){ digitalWrite(13,HIGH); } else if (inputByte=='z'){ digitalWrite(13,LOW); } } */ ultra(); servo1.write(0); servo2.write(0); servo3.write(0); servo4.write(0); servo5.write(0); servo6.write(0); if(distance <= 10){ servo1.write(60); servo2.write(60); servo3.write(60); servo4.write(60); servo5.write(60); servo6.write(60); delay(3000); } if(distance <= 9){ servo1.write(90); servo2.write(90); servo3.write(90); servo4.write(90); servo5.write(90); servo6.write(90); delay(2000); } if(distance <= 8){ servo1.write(120); servo2.write(120); servo3.write(120); servo4.write(120); servo5.write(120); servo6.write(120); delay(1000); } if(distance <= 5){ servo1.write(0); servo2.write(0); servo3.write(0); servo4.write(0); servo5.write(0); servo6.write(0); delay(2000); } } void ultra(){ digitalWrite(trigPin, LOW); delayMicroseconds(2); digitalWrite(trigPin, HIGH); delayMicroseconds(10); digitalWrite(trigPin, LOW); duration = pulseIn(echoPin, HIGH); distance = duration*0.034/2; }
54aa7a273d4da3554752797fb393f76ed03dfb22
f072254ddbcf9d7d5b8c91f31019bcd47e3db1ad
/codechef/c++/exit.cpp
d070f5af760913486f30da4586df25891726ef30
[]
no_license
nitishkumar07/Competitive-Programming
87389fac93a525a84dcca882a982ff573599f222
020c70b6e4e6a747524eefd841968cda2c9a7af8
refs/heads/master
2023-01-23T06:03:00.480202
2020-12-02T10:39:32
2020-12-02T10:39:32
292,838,022
0
0
null
null
null
null
UTF-8
C++
false
false
203
cpp
exit.cpp
#include<bits/stdc++.h> using namespace std; int main() { int t=1,n; while(t>0) { cin>>n; if(n==42) exit(0); else cout<<n<<"\n"; } return 0; }
2880a0ef813e3a25069f3ade3adf8ece05f4d9e4
4ab081170168cf8fa9af875842c2f62a4ec08abb
/graph/Stoer_Wagner.cpp
684586dd298fb02c94223076854b7643d3e0820f
[ "MIT" ]
permissive
wangchaohui/lib
be32e1ab6bd3468af62d4c27024fccbf521cddf8
762e7bedad895b3a271c9d52aa9367a83e2ddd35
refs/heads/master
2021-01-21T12:39:34.857850
2014-12-25T07:47:48
2014-12-25T07:47:48
null
0
0
null
null
null
null
UTF-8
C++
false
false
928
cpp
Stoer_Wagner.cpp
#include <stdio.h> #include <string.h> #define maxn 400 #define maxw 2000000000 int g[maxn+1][maxn+1]; int cost[maxn+1]; int n; int Stoer_Wagner() { int ans=maxw,i,j,m,mn,pre,t; while(n>1) { for(i=1;i<=n;i++)cost[i]=0; mn=-1; for(i=1;i<=n;i++) { pre=mn;m=-maxw; for(j=1;j<=n;j++)if(cost[j]>m){m=cost[j];mn=j;} cost[mn]=-maxw; for(j=1;j<=n;j++)if(cost[mn]!=-maxw)cost[j]+=g[mn][j]; } t=0; for(i=1;i<=n;i++)t+=g[mn][i]; if(ans>t)ans=t; for(i=1;i<=n;i++) { g[pre][i]+=g[mn][i]; g[i][pre]+=g[mn][i]; } g[pre][pre]=0; for(i=1;i<=n-1;i++)g[mn][i]=g[i][mn]=g[n][i]; g[mn][mn]=0; n--; } return ans; } int main() { int m,a,b,c,i,vs,ans; while(scanf("%d %d %d",&n,&m,&vs)==3 && n) { memset(g,0,sizeof(g)); for(i=1;i<=m;i++) { scanf("%d %d %d",&a,&b,&c); if(a==b)continue; g[a][b]+=c; g[b][a]+=c; } ans=Stoer_Wagner(); printf("%d\n",ans); } return 0; }
84b2178be34b42324611adf237c19feaa5a82a77
b46470f4a770f582d12146e1dd0f8d8935826f55
/lib/mac_layer/pdu/mpdu.cpp
3923ee82824e6d87930127071d62945306fb6541
[]
no_license
AlbertaSat/ex2_sdr
29b91d6793a75bd2b1b5a79f12a21c7b894b6e28
aa9fff79dc2fcb615a9035d3ddd16ea802174acc
refs/heads/master
2023-08-16T13:48:39.590266
2023-04-26T19:27:55
2023-04-26T19:27:55
373,630,507
3
3
null
2023-04-26T19:27:57
2021-06-03T20:17:45
C++
UTF-8
C++
false
false
4,933
cpp
mpdu.cpp
/*! * @file mpdu.cpp * @author Steven Knudsen * @date May 25, 2021 * * @details The MPDU class. * * @copyright University of Alberta, 2021 * * @license * This software may not be modified or distributed in any form, except as described in the LICENSE file. */ #include "mpdu.hpp" #define MPDU_DEBUG 0 // set to 1 for debug output namespace ex2 { namespace sdr { MPDUException::MPDUException(const std::string& message) : runtime_error(message) { } MPDU::MPDU ( MPDUHeader& header, std::vector<uint8_t>& codeword) { try { // Make a copy m_mpduHeader = new MPDUHeader(header); // TODO Not sure we need to keep the codeword for this constructor since // the MPDU object will be used to define a transparent mode payload // comprising Data Field 1 and 2, that is, the header and the codeword // together. m_payload = std::vector<uint8_t>(codeword); m_rawMPDU.resize(0); std::vector<uint8_t> temp = header.getHeaderPayload(); m_rawMPDU.insert(m_rawMPDU.end(), temp.begin(), temp.end()); m_rawMPDU.insert(m_rawMPDU.end(), codeword.begin(), codeword.end()); } catch (MPDUHeaderException& e) { // @todo should log this #if MPDU_DEBUG printf("MPDUHeader exception : %s\n", e.what()); #endif throw MPDUException("MPDU: Bad MPDUHeader."); } } MPDU::MPDU (std::vector<uint8_t>& rawMPDU) { // There are several possibilities for received @p rawMPDU: // 1. Shorter than expected // 2. As long as expected // 3. Longer than expected // // For 1., as long as there are enough bytes to make an MPDUHeader, it's // worth processing because it might be the first packet fragment. The // MPDUHeader may decode alright and then if it's the first packet // fragment, we can choose to substitute dummy data for the missing, // but expected message. Maybe subsequent payload will be okay... // // For 2., just process to make the MPDU // // For 3., process only the expected number of bytes to make the MPDU // the @p rawPayload is assumed to contain Data Field 1, the raw header, // and the codeword. Data Field 1 is not encoded, so we take our chances; // assume that the radio receives only as many Data Field 2 bytes as // indicated by Data Field 1 regardless of how much was actually transmitted // by the other end. Unless Data Field 1 is 129, the raw MPDU is no good // @todo Maybe we should allow for Data Field 1 to be bad? For example, as // long as we get enough bytes for the MPDU header and can check it, we // can still have a partial packet. In that case, we check for rawMPDU.size() // > try { m_mpduHeader = new MPDUHeader(rawMPDU); // Header seems okay, so make codeword based on how many remaining bytes // in rawMPDU uint32_t minMPDULength = MPDUHeader::MACHeaderLength() + MPDU::maxMTU(); if (rawMPDU.size() >= (minMPDULength)) { m_payload.assign(rawMPDU.begin()+MPDUHeader::MACHeaderLength(), rawMPDU.begin()+minMPDULength); } else { // insert what we have and then pad to correct length m_payload.assign(rawMPDU.begin()+MPDUHeader::MACHeaderLength(), rawMPDU.end()); m_payload.resize(minMPDULength); } } catch (MPDUHeaderException& e) { // @todo should log this #if MPDU_DEBUG printf("MPDUHeader exception : %s\n", e.what()); #endif throw MPDUException("MPDU: Bad raw MPDUHeader."); } // Might as well copy the input as the member raw MPDU m_rawMPDU = std::vector<uint8_t>(rawMPDU); } MPDU::~MPDU () { if (m_mpduHeader != NULL) { delete m_mpduHeader; } } const std::vector<uint8_t>& MPDU::getRawMPDU() const { return m_rawMPDU; } uint16_t MPDU::mpdusInNBytes(uint32_t byteCount, ErrorCorrection &errorCorrection) { // First find how many messages are needed for @p byteCount bytes uint32_t msgLen = errorCorrection.getMessageLen() / 8; uint32_t numMsgsPerPacket; if (byteCount > 0) { numMsgsPerPacket = byteCount / msgLen; if (byteCount % msgLen != 0) { numMsgsPerPacket++; } } else { numMsgsPerPacket = 1; } // Codewords are packed into consecutive MPDUs, so find out how many // are needed, being sure to round up. uint32_t numCodewordBytesPerPacket = numMsgsPerPacket * errorCorrection.getCodewordLen() / 8; uint32_t numMPDUsPerPacket = numCodewordBytesPerPacket / maxMTU(); if (numCodewordBytesPerPacket % maxMTU() != 0) { numMPDUsPerPacket++; } return numMPDUsPerPacket; } } /* namespace sdr */ } /* namespace ex2 */
bd8f0e5ac568e91a06653d3b10eb24655a3c1342
da9c4798a6e30152382eb1ba876718b51b9bd4f2
/leetcode-cn-cpp/leetcode-cn-120/main.cpp
928fc9b6782c686ff5858f7f77cd111b8616f2d8
[]
no_license
zivyou/labofziv
cb2b51f48b3315a8f408eafa940fdc04e1797bfa
e0319d6bc1bbb417f49275bdd07c28019e4b4089
refs/heads/master
2023-08-17T03:10:05.615780
2023-08-07T06:42:05
2023-08-07T06:42:05
6,417,825
0
0
null
null
null
null
UTF-8
C++
false
false
1,195
cpp
main.cpp
#include <iostream> #include <vector> using namespace std; class Solution { public: int minimumTotal(vector<vector<int>>& triangle) { if (triangle.size() <= 0) return 0; int **dp = new int*[triangle.size()+1]; cout<<"OK"<<endl; for (int i=0; i<triangle.size(); i++){ dp[i] = new int[triangle[i].size()]; } dp[triangle.size()] = new int[triangle[triangle.size()-1].size()+1]; for (int i=0; i<=triangle[triangle.size()-1].size(); i++) dp[triangle.size()][i] = 0; for (int i=triangle.size()-1; i>=0; i--) for (int j=triangle[i].size()-1; j>=0; j--) if (dp[i+1][j] > dp[i+1][j+1]) dp[i][j] = dp[i+1][j+1] + triangle[i][j]; else dp[i][j] = dp[i+1][j] + triangle[i][j]; return dp[0][0]; } }; int main() { vector<vector<int>> triangle; triangle.push_back(vector<int>({2})); triangle.push_back(vector<int>({3,4})); triangle.push_back(vector<int>({6,5,7})); triangle.push_back(vector<int>({4,1,8,3})); Solution s; cout<<s.minimumTotal(triangle)<<endl; return 0; }
6f89e96218ca8b3641207796cb91325d2245a6ba
890cae9ca70d12d34924f399ed34f1dee9357f82
/96A_Football.cpp
44aea8f2e7069318a5392d82e4ffa4fdbb3d607b
[]
no_license
UrvashiKishnani/codeforces
0a7a8a41987d629b090fdf8bc09d5fed274cab26
97aeb7138e35be8f4d2d2f65e974bb634be0b92f
refs/heads/master
2020-04-04T01:09:02.572089
2019-06-14T19:39:07
2019-06-14T19:39:07
155,669,751
3
1
null
null
null
null
UTF-8
C++
false
false
505
cpp
96A_Football.cpp
#include <iostream> using namespace std; int main() { string a; int i,m=0,ct=1,b; cin>>a; b=a[0]; for(i=1;a[i]!='\0';i++) { if(a[i]==b) ct++; else { if(ct>m) m=ct; ct=1; b=a[i]; } } if(ct>m) m=ct; if(m>=7) cout<<"YES"; else cout<<"NO"; return 0; }
e1e4ae7a1a2dcdc934bc693fca1116ac3ed53f9d
39fe085377f3c7327e82d92dcb38083d039d8447
/core/sql/optimizer/MvRefreshBuilder.h
dea5fdc07a99df836df15520df4c529a528381f6
[ "Apache-2.0" ]
permissive
naveenmahadevuni/incubator-trafodion
0da8d4c7d13a47d3247f260b4e67618c0fae1539
ed24b19436530b2c214e4bf73280bc8e3f419669
refs/heads/master
2021-01-22T04:40:52.402291
2015-07-16T00:02:50
2015-07-16T00:02:50
null
0
0
null
null
null
null
UTF-8
C++
false
false
31,563
h
MvRefreshBuilder.h
/********************************************************************** // @@@ START COPYRIGHT @@@ // // (C) Copyright 2003-2014 Hewlett-Packard Development Company, L.P. // // 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. // // @@@ END COPYRIGHT @@@ **********************************************************************/ #ifndef REFRESHBUILDER_H #define REFRESHBUILDER_H /* -*-C++-*- ****************************************************************************** * * File: MvRefreshBuilder.h * Description: Definition of class Refresh for MV INTERNAL REFRESH command. * * Created: 12/27/2000 * Language: C++ * Status: $State: Exp $ * * ****************************************************************************** */ #include "ComMvDefs.h" #include "RelMisc.h" #include "Refresh.h" #include "ChangesTable.h" // classes defined in this file class MvRefreshBuilder; class MvRecomputeBuilder; class MavBuilder; class MinMaxMavBuilder; class MultiDeltaMavBuilder; class MvMultiTxnMavBuilder; class PipelinedMavBuilder; class MultiDeltaRefreshMatrix; class MultiDeltaRefreshMatrixRow; class MavRelRootBuilder; struct MinMaxColExtraInfo; // Forward references class LogsInfo; class DeltaDefinitionPtrList; class IntegerList; class CorrName; class QualifiedName; class Refresh; class MVColumnInfo; class MvIudLog; class MVJoinGraph; class Union; class RelSequence; //---------------------------------------------------------------------------- // The MvRefreshBuilder class hierarchy is responsible for the actual // inlining work of building the refresh RelExpr trees. // For ON REQUEST MVs, if the refresh is not pipelined, only one object is // built and used. In case of pipelined refresh, several objects are built, // each for a single level of MV refresh. // The MvRefreshBuilder class itself is abstract. // Here is the class hierarchy: // MvRefreshBuilder : // MvRecomputeBuilder // MjvBuilder (defined in MjvBuilder.h/cpp) // MjvImmInsertBuilder // MjvImmDeleteBuilder // MjvImmDirectUpdateBuilder // MavBuilder // MultiDeltaMavBuilder // MvMultiTxnMavBuilder // MinMaxMavBuilder // PipelinedMavBuilder //---------------------------------------------------------------------------- class MvRefreshBuilder : public NABasicObject { public: MvRefreshBuilder(const CorrName& mvName, MVInfoForDML *mvInfo, Refresh *refreshNode, BindWA *bindWA); private: // Copy Ctor and = operator are not implemented. MvRefreshBuilder(const MvRefreshBuilder& other); #pragma nowarn(1026) // warning elimination MvRefreshBuilder& operator=(const MvRefreshBuilder& other); #pragma warn(1026) // warning elimination public: enum { MAX_EPOCH_FOR_UNION_BACKBONE = 50 }; public: virtual ~MvRefreshBuilder(); // Accessors to private data members const CorrName& getMvCorrName() const { return mvCorrName_; } Refresh *getRefreshNode() const { return refreshNode_; } MVInfoForDML *getMvInfo() const { return mvInfo_; } Lng32 getPhase() const { return phase_; } const DeltaDefinitionPtrList *getDeltaDefList() const { return deltaDefList_;} void setDeltaDefList(const DeltaDefinitionPtrList *deltaDef) { deltaDefList_ = deltaDef;} // Build the refresh RelExpr tree. This pure virtual method is respossible // for building the main refresh tree. This is done differently for every // refresh type. virtual RelExpr *buildRefreshTree() = 0; // Transform the Scan on the base table from the MV SELECT tree, to scan // the logs instead. This is the basic implementation that handles the IUD // log and the range log. It is overridden by MvMultiTxnMavBuilder for // that special case. virtual RelExpr *buildLogsScanningBlock(const QualifiedName& baseTable); virtual NABoolean needAlternateCIorder() const; virtual Union *buildUnionBetweenRangeAndIudBlocks(RelExpr *scanIUDLogBlock, RelExpr *scanRangeLogBlock) const; protected: virtual RelRoot *buildRootWithUniformSelectList(RelExpr *topNode, ItemExpr *opExpr, const CorrName *nameOverride, NABoolean forRange) const; LogsInfo &getLogsInfo() const { CMPASSERT(logsInfo_); return *logsInfo_; } // Prepare for Multi-Delta refresh (both MAV and MJV) MultiDeltaRefreshMatrix *prepareProductMatrix(NABoolean supportPhases, NABoolean checkOnlyInserts); // Prepare a single join product according to the product matrix row. RelRoot *prepareProductFromMatrix( const MultiDeltaRefreshMatrix& productMatrix, RelRoot *rawJoinProduct, Int32 rowNumber, NABoolean isLast); // Any reason not to implement multi-delta optimization? // (implemented differently by MAV and MJV) virtual NABoolean avoidMultiDeltaOptimization() { return FALSE; }; // Methods called internally for reading the IUD log // ---------------------------------------------------- virtual RelExpr *buildReadIudLogBlock(); virtual Int32 getNumOfScansInUnionBackbone() const; void fixScanCardinality(RelExpr *node, double cardinalityFactor, Cardinality cardinality) const; // Construct the appropriate expression for the Op@ virtual column. // The value of this column is 1 for inserted rows, and -1 for deleted rows. ItemExpr *constructOpExpression() const; // buildReadIudLogBlock callee virtual ItemExpr *buildSelectionPredicateForScanOnIudLog() const; virtual ItemExpr *buildSelectionListForScanOnIudLog() const; virtual ItemExpr *buildBaseTableColumnList(Lng32 specialFlags=0) const; // Have a uniform select list over the IUD log virtual RelRoot *buildRootOverIUDLog(RelExpr *topNode) const; // Methods called internally for reading the range log // ---------------------------------------------------- virtual RelExpr *buildReadBaseTable() const; // Construct a join between the base table and the range log virtual RelExpr *buildReadRangesBlock() const; virtual ItemExpr *buildEndRangeVector() const; virtual ItemExpr *buildBeginRangeVector() const; // Construct a join between the base table and the range log virtual RelExpr *buildReadRangeLogBlock() const; // buildReadRangeLogBlock() callee virtual RelRoot *buildRootOverRangeBlock(RelExpr *topNode) const; // buildReadRangeLogBlock() callee virtual RelExpr *buildJoinBaseTableWithRangeLog(RelExpr *scanRangeLog, RelExpr *scanBaseTable) const; // Used by buildUnionWithRangeLog(), Overridden by MvMultiTxnMavBuilder virtual ItemExpr *buildSelectionPredicateForScanOnRangeLog() const; // Construct the join predicate between the base table and the range log. // Overridden by MvMultiTxnMavBuilder for additional predicates. virtual ItemExpr *buildRangeLogJoinPredicate() const; virtual ItemExpr *buildRangeLogJoinPredicateWithCols( ItemExpr *rangeType, ItemExpr *baseCI, ItemExpr *beginRangeCI, ItemExpr *endRangeCI) const; virtual NABoolean useUnionBakeboneToMergeEpochs() const; virtual RelExpr *buildUnionBakeboneToMergeEpochs(RelExpr *topNode) const; virtual Int32 isGroupByAprefixOfTableCKeyColumns() const { return FALSE; } virtual ItemExpr *buildAlternateCIorder(ItemExpr *ciColumns, const CorrName &tableNameCorr) const; // Was INTERNAL REFRESH invoked with DE LEVEL 3? NABoolean wasFullDE() const; // The statement heap (taken from bindWA). CollHeap *heap_; BindWA *bindWA_; private: // Data members. // ---------------------------------------------------- // The name of the MV being refreshed. CorrName mvCorrName_; // The Delta Definitions of the logs used. const DeltaDefinitionPtrList *deltaDefList_; // Which phase of multi-delta refresh is this invocation? Lng32 phase_; MVInfoForDML *mvInfo_; Refresh *refreshNode_; LogsInfo *logsInfo_; }; // class MvRefreshBuilder //---------------------------------------------------------------------------- // The simplest Refresh tree: RECOMPUTE. //---------------------------------------------------------------------------- class MvRecomputeBuilder : public MvRefreshBuilder { public: MvRecomputeBuilder(const CorrName& mvName, MVInfoForDML *mvInfo, NABoolean noDeleteOnRecompute, BindWA *bindWA) : MvRefreshBuilder(mvName, mvInfo, NULL, bindWA), noDeleteOnRecompute_(noDeleteOnRecompute) {} virtual ~MvRecomputeBuilder() {} private: // Copy Ctor and = operator are not implemented. MvRecomputeBuilder(const MvRecomputeBuilder& other); #pragma nowarn(1026) // warning elimination MvRecomputeBuilder& operator=(const MvRecomputeBuilder& other); #pragma warn(1026) // warning elimination public: virtual RelExpr *buildRefreshTree(); private: RelExpr *buildInsertToMvSubTree() const; RelExpr *buildDeleteFromMvSubTree() const; private: NABoolean noDeleteOnRecompute_; }; // class MvRecomputeBuilder //---------------------------------------------------------------------------- // Builds the refresh tree of a single-delta MAV. // This MAV reads the logs of its base tables for the refresh operation. //---------------------------------------------------------------------------- class MavBuilder : public MvRefreshBuilder { public: MavBuilder(const CorrName& mvName, MVInfoForDML *mvInfo, Refresh *refreshNode, NABoolean isProjectingMvDelta, BindWA *bindWA); private: // Copy Ctor and = operator are not implemented. MavBuilder(const MavBuilder& other); #pragma nowarn(1026) // warning elimination MavBuilder& operator=(const MavBuilder& other); #pragma warn(1026) // warning elimination public: enum GroupOpNumbers { GOP_INSERT = 1, GOP_DELETE, GOP_UPDATE, GOP_MINMAX_RECOMPUTE_FROM_UPDATE, GOP_MINMAX_RECOMPUTE_FROM_INSERT }; virtual ~MavBuilder() {} // The implementation-specific part of building the MAV refresh tree. // This method is overridden by every sub-class. virtual RelExpr *buildRefreshTree(); static const char *getVirtualOpColumnName() { return virtualOpColumnName_; } static const char *getVirtualGopColumnName() { return virtualGopColumnName_; } static const char *getVirtualIsLastColName() { return virtualIsLastColumnName_; } // These are correlation names to "tables". static const char *getSysDeltaName() { return sysDeltaName_; } static const char *getSysCalcName() { return sysCalcName_; } static const char *getSysMavName() { return sysMavName_; } static const char *getStartCtxName() { return startCtxName_; } static const char *getEndCtxName() { return endCtxName_; } static const char *getMinMaxMavName() { return minMaxMavName_; } // These are name suffixes of extra aggregate columns added for each // Min/Max column. static const char *getExtraColSuffixForIns() { return extraColSuffixForIns_; } static const char *getExtraColSuffixForDel() { return extraColSuffixForDel_; } protected: // Internal methods used by buildRefreshTree(). // The actual building of the refresh tree, that is the same for all // MAV sub-classes. RelExpr *buildTheMavRefreshTree(RelExpr *mvSelectTree, DeltaDefinition *deltaDef); // build the left side of the refresh tree - the DCB. RelExpr *buildDeltaCalculationBlock(RelExpr *mvSelectTree); // Construct a selection predicate on the MAV group by columns. ItemExpr *buildGroupByColumnsPredicate(const NAString& table1Name, const NAString& table2Name = "", const NABoolean ignoreAlias = FALSE) const; // build the right side of the refresh tree - the DPB. RelExpr *buildDeltaProcessingBlock(DeltaDefinition *deltaDef); // Build the Delta Processing Block Insert sub-tree. RelExpr *buildDPBInsert(DeltaDefinition *deltaDef, RelExpr *topNode) const; RelExpr *buildDPBInsertNodes(const NAString& sourceTable) const; // Build the Delta Processing Block Delete sub-tree. RelExpr *buildDPBDelete(RelExpr *topNode); // Build the Delta Processing Block Update sub-tree. // The Update expressions are of the form: // (a is a MAV aggregate column, b is a MAV groupby column) // SET expressions: a = tableForSet.a // WHERE expressions: b = tableForWhere.b RelExpr *buildDPBUpdate(const NAString& tableForSet, const NAString& tableForWhere) const; // Build a stack of 5 RelRoot nodes to calculate the SYS_CALC columns. RelExpr *buildLotsOfRootsForCalcCalculation(RelExpr *topNode, RelExpr *mvSelectTree); NABoolean isProjectingMvDelta() const { return isProjectingMvDelta_; } virtual NABoolean useUnionBakeboneToMergeEpochs() const; virtual Int32 isGroupByAprefixOfTableCKeyColumns() const; // Accessors for static data members const char *getGopTableName() const { return gopTableName_; } const char *getGopCol1Name() const { return gopCol1Name_; } const char *getGopCol2Name() const { return gopCol2Name_; } private: // All the methods below are used for the generic support of MIN/MAX. // Delta Processing Block RelExpr *buildDPBMinMaxIfCondition(const RelExpr *updateNode) const; RelExpr *createSignal() const; // Builds a Signal for this class. // Overridden by MinMaxOptimizedMavBuilder. virtual RelExpr *buildMinMaxRecomputationBlock() const; private: // TRUE if this is not the top most refresh builder. NABoolean isProjectingMvDelta_; // TRUE when there is no need to check if the Min/Max value was deleted. NABoolean canSkipMinMax_; // This attribute has lazy evaluation, thus we use int instead of boolean. // -1 is unintialized, 0 is false,1 is true Int32 isGroupByAprefixOfTableCKeyColumns_; // This is needed for accessing the NATable of the base tables for // MIN/MAX optimizations. BindWA *pBindWA; // "Virtual" columns are columns that are manualy added to the RETDesc. static const char virtualOpColumnName_[]; static const char virtualGopColumnName_[]; static const char virtualIsLastColumnName_[]; // These are correlation names to "tables". static const char sysDeltaName_[]; static const char sysCalcName_[]; static const char sysMavName_[]; static const char startCtxName_[]; static const char endCtxName_[]; static const char minMaxMavName_[]; // These names are used in pipelined refresh, for the TupleList join. static const char gopTableName_[]; static const char gopCol1Name_[]; static const char gopCol2Name_[]; // These are name suffixes of extra aggregate columns added for each // Min/Max column. static const char extraColSuffixForIns_[]; static const char extraColSuffixForDel_[]; }; // class MavBuilder //---------------------------------------------------------------------------- class MinMaxOptimizedMavBuilder : public MavBuilder { public: MinMaxOptimizedMavBuilder(const CorrName& mvName, MVInfoForDML *mvInfo, Refresh *refreshNode, NABoolean isProjectingMvDelta, BindWA *bindWA) : MavBuilder(mvName, mvInfo, refreshNode, isProjectingMvDelta, bindWA) {} virtual ~MinMaxOptimizedMavBuilder() {} private: // Copy Ctor and = operator are not implemented. MinMaxOptimizedMavBuilder(const MinMaxOptimizedMavBuilder& other); #pragma nowarn(1026) // warning elimination MinMaxOptimizedMavBuilder& operator=(const MinMaxOptimizedMavBuilder& other); #pragma warn(1026) // warning elimination protected: virtual RelExpr *buildMinMaxRecomputationBlock() const; void fixGroupingColumns(RelRoot* pRoot) const; void removeGroupingColsFromSelectList(RelRoot* pRoot) const; }; // MinMaxOptimizedMavBuilder //---------------------------------------------------------------------------- class MultiDeltaMavBuilder : public MavBuilder { public: MultiDeltaMavBuilder(const CorrName& mvName, MVInfoForDML *mvInfo, Refresh *refreshNode, NABoolean isProjectingMvDelta, BindWA *bindWA) : MavBuilder(mvName, mvInfo, refreshNode, isProjectingMvDelta, bindWA), isDuplicatesOptimized_(FALSE) {} private: // Copy Ctor and = operator are not implemented. MultiDeltaMavBuilder(const MultiDeltaMavBuilder& other); #pragma nowarn(1026) // warning elimination MultiDeltaMavBuilder& operator=(const MultiDeltaMavBuilder& other); #pragma warn(1026) // warning elimination public: virtual ~MultiDeltaMavBuilder() {} virtual RelExpr *buildRefreshTree(); protected: // Any reason not to implement multi-delta optimization? // (implemented differently by MAV and MJV) virtual NABoolean avoidMultiDeltaOptimization(); virtual NABoolean isTableExpressionPresent(RelExpr *currentNode); private: void bindJoinProduct(RelRoot *product, NABoolean isSignPlus); RelExpr *buildRawDeltaCalculationTree( const MultiDeltaRefreshMatrix& productMatrix); void prepareRetdescForUnion(RETDesc *retDesc, NABoolean isSignPlus); NABoolean collectOpExpressions(RETDesc *retDesc, const ColumnDesc *columnDesc, ItemExpr *&newOpExpr); RelExpr *getMvSelectTree() { return mvSelectTree_; } private: NABoolean isDuplicatesOptimized_; RelExpr *mvSelectTree_; }; // class MultiDeltaMavBuilder //---------------------------------------------------------------------------- class MvMultiTxnMavBuilder : public MavBuilder { public: MvMultiTxnMavBuilder(const CorrName& mvName, MVInfoForDML *mvInfo, Refresh *refreshNode, NABoolean isProjectingMvDelta, BindWA *bindWA) : MavBuilder(mvName, mvInfo, refreshNode, isProjectingMvDelta, bindWA), pMultiTxnClause_(refreshNode->getNRowsClause()) {} private: // Copy Ctor and = operator are not implemented. MvMultiTxnMavBuilder(const MvMultiTxnMavBuilder& other); #pragma nowarn(1026) // warning elimination MvMultiTxnMavBuilder& operator=(const MvMultiTxnMavBuilder& other); #pragma warn(1026) // warning elimination public: virtual ~MvMultiTxnMavBuilder() {} virtual RelExpr *buildRefreshTree(); RelExpr *buildLogsScanningBlock(const QualifiedName& baseTable); protected: virtual RelExpr *buildReadPreviousContext(); RelExpr *buildErrorOnNoContext(RelExpr *topNode); RelExpr *buildPhase1SelectList(RelExpr *topNode, const NATable *baseNaTable); virtual RelExpr *buildReadIudLogBlock() ; // buildReadIudLogBlock callee virtual ItemExpr *buildSelectionPredicateForScanOnIudLog() const; virtual NABoolean needAlternateCIorder() const; virtual Union *buildUnionBetweenRangeAndIudBlocks(RelExpr *scanIUDLogBlock, RelExpr *scanRangeLogBlock) const; virtual ItemExpr *buildSelectionPredicateForScanOnRangeLog() const; virtual ItemExpr *buildCatchupSelectionPredicateForScanOnRangeLog() const; virtual ItemExpr *buildPhase1SelectionPredicateForScanOnRangeLog() const; virtual ItemExpr *buildSelectionListForScanOnIudLog() const; virtual ItemExpr *buildRangeLogJoinPredicate() const; virtual ItemExpr *addContextPredicatesOnIUDLog() const; virtual NAString *getSequenceByPrefixColName() const { return NULL; } virtual NABoolean useUnionBakeboneToMergeEpochs() const; virtual RelSequence *buildSequenceOnScan(RelExpr *topNode, ItemExpr *isLastExpr) const; virtual RelRoot *buildRootOverSequence(RelExpr *topNode, ItemExpr *isLastExpr) const; virtual ItemExpr *buildSequenceIsLastExpr() const; virtual RelExpr *buildInsertContextNode(); virtual RelExpr *buildInsertContextTree(RelExpr *leftTopNode); const NRowsClause *pMultiTxnClause_; }; // class MvMultiTxnMavBuilder //---------------------------------------------------------------------------- //---------------------------------------------------------------------------- //---------------------------------------------------------------------------- //---------------------------------------------------------------------------- // Exclude from coverage testing - used only with range loggiing // LCOV_EXCL_START class MultiTxnDEMavBuilder : public MvMultiTxnMavBuilder { public: MultiTxnDEMavBuilder(const CorrName& mvName, MVInfoForDML *mvInfo, Refresh *refreshNode, NABoolean isProjectingMvDelta, BindWA *bindWA) : MvMultiTxnMavBuilder(mvName, mvInfo, refreshNode, isProjectingMvDelta, bindWA) {} private: // Copy Ctor and = operator are not implemented. MultiTxnDEMavBuilder(const MultiTxnDEMavBuilder& other); #pragma nowarn(1026) // warning elimination MultiTxnDEMavBuilder& operator=(const MultiTxnDEMavBuilder& other); #pragma warn(1026) // warning elimination public: virtual ~MultiTxnDEMavBuilder() {} protected: virtual const char *getVirtualRangeSpecialCol() const { return virtualRangeSpecialCol_; } virtual NAString *getSequenceByPrefixColName() const { return new(heap_) NAString(sequenceByPrefixColName_); } virtual NAString *getLastNotNullPrefixColName() const { return new(heap_) NAString(lastNotNullPrefixColName_); } // The Range of values that @SPECIAL can recieve enum { VIRTUAL_BEGIN_RANGE, TABLE_ROWS, IUD_LOG_ROWS }; // Have a uniform select list over the IUD log virtual RelRoot *buildRootOverIUDLog(RelExpr *topNode) const; // Have a uniform select list over the Range log virtual RelRoot *buildRootOverRangeBlock(RelExpr *topNode) const; ItemExpr *buildComputedTableSyskey(ItemExpr *colExpr) const; void buildSortKeyColumnsForRangeBlock(ItemExprList &sortKeyCols) const; void addSyskeyToSortKeyColumnsForRangeBlock(ItemExprList &sortKeyCols) const; RelRoot *buildRootWithFilterForEmptyRanges(RelExpr *topNode) const; virtual RelSequence *buildSequenceOnScan(RelExpr *topNode, ItemExpr *isLastExpr) const; virtual RelRoot *buildRootOverSequence(RelExpr *topNode, ItemExpr *isLastExpr) const; RelRoot *buildFinalRootOverSequence(RelExpr *topNode) const; ItemExpr *buildSelectionOverSequence() const; ItemExpr *buildIsCoveredByRange() const; ItemExpr *buildIsPhysicallyCoveredByRangeBoundries() const; // buildReadRangeLogBlock() callee virtual RelExpr *buildJoinBaseTableWithRangeLog(RelExpr *scanRangeLog, RelExpr *scanBaseTable) const; virtual RelExpr *buildReadRangeLogBlock() const; private: static const char virtualRangeSpecialCol_[]; static const char sequenceByPrefixColName_[]; static const char lastNotNullPrefixColName_[]; }; // MultiTxnDEMavBuilder // LCOV_EXCL_STOP //---------------------------------------------------------------------------- // Builds the refresh tree of a single-delta pipelined MAV. // This MAV gets its input pipelined by the refresh tree of the used MV. class PipelinedMavBuilder : public MavBuilder { public: PipelinedMavBuilder(const CorrName& mvName, MVInfoForDML *mvInfo, Refresh *refreshNode, NABoolean isProjectingMvDelta, const QualifiedName *pipeliningSource, BindWA *bindWA); private: // Copy Ctor and = operator are not implemented. PipelinedMavBuilder(const PipelinedMavBuilder& other); #pragma nowarn(1026) // warning elimination PipelinedMavBuilder& operator=(const PipelinedMavBuilder& other); #pragma warn(1026) // warning elimination public: virtual ~PipelinedMavBuilder() {} // called by Refresh::bindnode() for building the next level refresh tree // and connecting it as a "view" that is projecting the data. RelExpr *buildAndConnectPipeliningRefresh(RelExpr *pipeliningTree); protected: QualifiedName *getPipeliningSource() { return getDeltaDefList()->at(0)->getTableName(); } // Methods called by buildAndConnectPipeliningRefresh(). // ---------------------------------------------------- RelExpr *buildJoinWithTupleList(RelExpr *topNode); RelRoot *buildRenameToLog(RelExpr *topNode); }; // class PipelinedMavBuilder //---------------------------------------------------------------------------- //---------------------------------------------------------------------------- //---------------------------------------------------------------------------- class LogsInfo : public NABasicObject { public: LogsInfo(DeltaDefinition &deltaDef, MVInfoForDML *mvInfo, BindWA *bindWA); virtual ~LogsInfo(); private: // Copy Ctor and = operator are not implemented. LogsInfo(const LogsInfo& other); #pragma nowarn(1026) // warning elimination LogsInfo& operator=(const LogsInfo& other); #pragma warn(1026) // warning elimination public: DeltaDefinition &getDeltaDefinition() { return deltaDef_; } MvIudLog &getMvIudlog() { return *currentMvIudlog_; } IntegerList *getBaseTableDirectionVector() { return baseTableDirectionVector_; } BindWA *getBindWA() { return bindWA_; } const NATable *getBaseNaTable() { return currentMvIudlog_->getSubjectNaTable(); } const NATable *getIudLogNaTable() { return currentMvIudlog_->getNaTable(); } const NATable *getRangeNaLogTable() { CMPASSERT(rangeNaTable_); return rangeNaTable_; } const CorrName &getBaseTableName() { return currentMvIudlog_->getSubjectTableName(); } const CorrName &getIudLogTableName() { return *currentMvIudlog_->getTableName(); } const CorrName &getRangeLogTableName() { CMPASSERT(rangeTableName_); return *rangeTableName_; } private: // Given the base table name, construct the range log name from it. CorrName *calcRangeLogName(const CorrName &theTable, CollHeap *heap) const; DeltaDefinition &deltaDef_; MvIudLog *currentMvIudlog_; IntegerList *baseTableDirectionVector_; MVInfoForDML *mvInfo_; BindWA *bindWA_; NATable *rangeNaTable_; CorrName *rangeTableName_; }; //---------------------------------------------------------------------------- //---------------------------------------------------------------------------- //---------------------------------------------------------------------------- class MultiDeltaRefreshMatrixRow : public NABasicObject { private: enum rowSign { SIGN_MINUS = 0, SIGN_PLUS=1 }; enum scanType { SCAN_TABLE = 0, SCAN_DELTA=1 }; public: // Ctor for creating an all-but-last SCAN_TABLE row. MultiDeltaRefreshMatrixRow(Int32 length, Int32 maxLength, CollHeap *heap); // Copy Ctor. MultiDeltaRefreshMatrixRow(const MultiDeltaRefreshMatrixRow& other); // Dtor virtual ~MultiDeltaRefreshMatrixRow() {} // Mutators void initArray(); void flipSignAndLastTable(); void addColumn(scanType type = SCAN_TABLE); // Accessors NABoolean isSignPlus() const { return sign_==SIGN_PLUS; } NABoolean isScanOnDelta(CollIndex i) const { return tableScanTypes_[i]==SCAN_DELTA; } #ifndef NDEBUG void display() const; void print(FILE* ofd = stdout, const char* indent = DEFAULT_INDENT, const char* title = "MultiDeltaRefreshMatrixRow") const; #endif private: rowSign sign_; // The sign of this matrix row. Int32 currentLength_; // How many tables so far. Int32 maxLength_; // The array size. ARRAY(scanType) tableScanTypes_; // The matrix row itself. CollHeap *heap_; // Used by the copy Ctor. }; // class MultiDeltaRefreshMatrixRow //---------------------------------------------------------------------------- class MultiDeltaRefreshMatrix : public NABasicObject { public: MultiDeltaRefreshMatrix(Int32 maxNumOfRows, MVJoinGraph *joinGraph, CollHeap *heap); virtual ~MultiDeltaRefreshMatrix(); // Mutators void addTable(NABoolean readDelta); void setThisPhase(Int32 phase); void calculatePhases(); // Accessors const MultiDeltaRefreshMatrixRow *getRow(Int32 i) const; Int32 getNumOfRows() const { return numOfRows_; } Int32 getRowLength() const { return currentRowLength_; } NABoolean isLastPhase() const { return isLastPhase_; } Lng32 getTableIndexFor(Int32 index) const { return tableIndexMapping_[index];} Int32 getFirstRowForThisPhase() const { return firstRowForThisPhase_; } Int32 getNumOfRowsForThisPhase() const { return numOfRowsForThisPhase_; } void setPhasesSupported(NABoolean supported) { isPhasesSupported_ = supported; } NABoolean isPhasesSupported() const { return isPhasesSupported_; } NABoolean isTooManyDeltasError() const { return TooManyDeltasError_; } NABoolean isDuplicatesOptimized() const { return isDuplicatesOptimized_; } void disableDuplicateOptimization() { isDuplicatesOptimized_ = FALSE; } #ifndef NDEBUG void display() const; void print(FILE* ofd = stdout, const char* indent = DEFAULT_INDENT, const char* title = "MultiDeltaRefreshMatrix") const; #endif private: Int32 numOfRows_; // How many rows so far. Int32 currentRowLength_; // How many tables so far. Int32 maxRowLength_; // No. of tables in join product CollHeap *heap_; // The binder (statement) heap. // The actual matrix is an array of matrix rows. ARRAY(MultiDeltaRefreshMatrixRow *) theMatrix_; // The mapping from the tableIndex to the array of used objects in MVInfo. // This mapping is created by the join graph algorithm. ARRAY(Lng32) tableIndexMapping_; // data members for division to phases. NABoolean isPhasesSupported_; // Do we need to support divition to phases? Int32 thisPhase_; // PHASE parameter to refresh. NABoolean isLastPhase_; // Are more phases needed? Int32 firstRowForThisPhase_; // Where does this phase start? Int32 numOfRowsForThisPhase_; // Ho many rows in this phase? NABoolean TooManyDeltasError_; // Abort rather than risk an optimizer crash. NABoolean isDuplicatesOptimized_; // Do not build full matrix, since duplicates // are eliminated elsewhere. // Heuristic parameters taken from the Defaults table: // Maximum number of tables in a join for doing everything in one phase. Int32 maxJoinSizeForSinglePhase_; // Default is 3 // Minimum join size for doing a single matrix row per phase. Int32 minJoinSizeForSingleProductPerPhase_; // Default is 8 // When the join size is between the two parameters above - how many // matrix rows to do per phase. Int32 phaseSizeForMidRange_; // Default is 6 // If there are too many deltas, the optimizer may explode. Int32 maxDeltasThreshold_; // Default is 31 rows (Six deltas) }; // class MultiDeltaRefreshMatrix #endif
7935d5fb37e35e2db4d7e8786d6610f9de4f7dc3
41c02ba28693bc255df72861145e8edd8dfcb3d8
/c++ DroneSim/droneex.cpp
45b482202b80e8fd2c62eca53fbf1113264dd7e2
[]
no_license
nevepura/drone-simulator
828a85f9d83a049b9b614d8ac7ca400c5c7d8d2a
45bab51a05ccf5daec2323663706ecf5ff4773f0
refs/heads/master
2020-08-30T23:09:44.832189
2019-10-30T12:41:40
2019-10-30T12:41:40
218,516,657
0
0
null
null
null
null
UTF-8
C++
false
false
386
cpp
droneex.cpp
#include "droneex.h" #include "eccezione.h" #include <cmath> using std::abs; droneEx::droneEx(bool o, int b, int x, int y):drone(o,b,x,y){} string droneEx::getName()const{ return "Drone Ex"; } coord droneEx::move(int x, int y){ if(abs(x)==1 && abs(y)==1 ){ return drone::move(x,y); } else{ throw eccezione('m'); } } int droneEx::batteryUsage= 5;